@chrischall/warapp-mcp 0.3.0 → 0.4.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,75 @@
1
+ // mcp-host's egress proxy, for the requests that bring their own dispatcher.
2
+ //
3
+ // On mcp-host a child reaches the internet ONLY through the egress proxy that
4
+ // `HTTPS_PROXY` + `NODE_USE_ENV_PROXY=1` point Node's built-in fetch at: a
5
+ // direct socket is silently dropped and reads as a timeout. Global fetch
6
+ // honours the variable; a custom undici dispatcher does not. The war.app
7
+ // sign-in (src/direct/sign-in.ts) and the direct leg (src/direct/transport.ts)
8
+ // each send through their own dispatcher — mcp-utils netguard's public-only
9
+ // one — so hosted, neither could reach war.app at all ("Could not reach
10
+ // war.app to sign in"). GameFeed (`createApiClient`) and the bundle download
11
+ // use global fetch and need nothing here.
12
+ //
13
+ // With a proxy configured, those two send through an undici `ProxyAgent` for
14
+ // it instead (a CONNECT tunnel; TLS to war.app still checks war.app's
15
+ // certificate). The host check stays in our code — the exact origin
16
+ // https://war.app — and the proxy enforces the child's allowlist and its own
17
+ // address table, so netguard's public-only pin is not needed there. Without a
18
+ // proxy (local) nothing changes: the public-only dispatcher, as before.
19
+ //
20
+ // A proxy that is set but unusable is a configuration error, refused clearly:
21
+ // never a fallback to a direct connection. NO_PROXY is not read: war.app is
22
+ // never meant to bypass the proxy. The proxy URL is never echoed (it may carry
23
+ // a password).
24
+ import { McpToolError, readEnvVar } from '@chrischall/mcp-utils';
25
+ import { ProxyAgent } from 'undici';
26
+ /** The variables naming the proxy, in the order read (curl's and undici's spellings). */
27
+ export const EGRESS_PROXY_ENV = ['HTTPS_PROXY', 'https_proxy'];
28
+ /** The start of the refusal for a proxy that is set but unusable. */
29
+ export const EGRESS_PROXY_INVALID = 'HTTPS_PROXY is set but is not a usable http(s) proxy URL';
30
+ export const defaultProxyAgent = (url) => new ProxyAgent(url.href);
31
+ const rawProxy = (env) => {
32
+ for (const key of EGRESS_PROXY_ENV) {
33
+ const v = readEnvVar(key, { env });
34
+ if (v !== undefined)
35
+ return v;
36
+ }
37
+ return undefined;
38
+ };
39
+ /** Whether a proxy is configured at all (usable or not): then nothing may connect directly. */
40
+ export function egressProxyConfigured(env = process.env) {
41
+ return rawProxy(env) !== undefined;
42
+ }
43
+ /**
44
+ * The egress proxy's URL when `HTTPS_PROXY` (or `https_proxy`) is set, else
45
+ * `undefined`. Throws a clear error, before anything is sent, when the variable
46
+ * is set but not an http(s) URL with a host (never echoing it).
47
+ */
48
+ export function egressProxyUrl(env = process.env) {
49
+ const raw = rawProxy(env);
50
+ if (raw === undefined)
51
+ return undefined;
52
+ let url;
53
+ try {
54
+ url = new URL(raw);
55
+ }
56
+ catch {
57
+ url = undefined;
58
+ }
59
+ if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:') || !url.hostname) {
60
+ throw new McpToolError(`${EGRESS_PROXY_INVALID}, so nothing was sent to war.app.`, {
61
+ kind: 'unknown',
62
+ hint: 'Set HTTPS_PROXY to a proxy URL such as http://127.0.0.1:8080, or unset it to connect directly.',
63
+ });
64
+ }
65
+ return url;
66
+ }
67
+ /**
68
+ * The dispatcher to send war.app traffic through: a proxy agent for
69
+ * {@link egressProxyUrl}, else `undefined` (the caller keeps its public-only
70
+ * dispatcher). Throws as {@link egressProxyUrl} does. The caller closes the agent.
71
+ */
72
+ export function egressDispatcher(env = process.env, make = defaultProxyAgent) {
73
+ const url = egressProxyUrl(env);
74
+ return url ? make(url) : undefined;
75
+ }
@@ -29,10 +29,14 @@
29
29
  // value: each is scrubbed BY VALUE, and the cause chain is dropped.
30
30
  // - The single-hop fetch goes through mcp-utils netguard's public-only
31
31
  // dispatcher (a name that resolves or rebinds inward is refused), with one
32
- // deadline over the whole exchange and a byte cap on each body.
32
+ // deadline over the whole exchange and a byte cap on each body. With an
33
+ // egress proxy configured (HTTPS_PROXY: mcp-host's only way out) it goes
34
+ // through a proxy agent instead (src/direct/egress.ts); a proxy that is set
35
+ // but unusable is refused before anything is sent.
33
36
  import { detectEdgeBlock, McpToolError } from '@chrischall/mcp-utils';
34
37
  import { createPublicOnlyDispatcher } from '@chrischall/mcp-utils/netguard';
35
38
  import { fetch as undiciFetch } from 'undici';
39
+ import { defaultProxyAgent, egressProxyUrl } from './egress.js';
36
40
  import { scrubSecrets } from '../redact.js';
37
41
  import { isPlausibleAuthToken, SESSION_HOST } from './session.js';
38
42
  import { hasPasswordInput } from './transport.js';
@@ -50,11 +54,19 @@ const MIN_SCRUBBED_COOKIE = 6;
50
54
  export const SIGN_IN_TIMEOUT_MS = 30_000;
51
55
  /** Byte cap on each response body (the sign-in page is a few tens of KB). */
52
56
  export const SIGN_IN_MAX_BODY_BYTES = 2 * 1024 * 1024;
53
- /** The default single-hop fetch: undici through a public-only dispatcher, redirects never followed. */
57
+ /**
58
+ * The default single-hop fetch: undici, redirects never followed, through the
59
+ * egress proxy when one is configured (src/direct/egress.ts), else through a
60
+ * public-only dispatcher. A proxy that is set but unusable throws here, before
61
+ * any request.
62
+ */
54
63
  export function createSignInFetch(opts = {}) {
55
64
  const maxBytes = opts.maxBytes ?? SIGN_IN_MAX_BODY_BYTES;
65
+ // Read (and a bad proxy refused) now, before any request; an agent is built per hop and closed.
66
+ const proxy = opts.dispatcher ? undefined : egressProxyUrl(opts.env ?? process.env);
67
+ const makeProxy = opts.proxyAgent ?? defaultProxyAgent;
56
68
  return async (url, init) => {
57
- const owned = opts.dispatcher ? undefined : createPublicOnlyDispatcher();
69
+ const owned = opts.dispatcher ? undefined : proxy ? makeProxy(proxy) : createPublicOnlyDispatcher();
58
70
  try {
59
71
  const res = await undiciFetch(url, {
60
72
  method: init.method,
@@ -181,7 +193,7 @@ async function exchange(creds, jar, opts) {
181
193
  if (!creds.email.trim() || !creds.password) {
182
194
  throw refusal('no_credential', 'Signing in to war.app needs both the email and the password; nothing was sent.');
183
195
  }
184
- const fetchHop = opts.fetch ?? createSignInFetch();
196
+ const fetchHop = opts.fetch ?? createSignInFetch(opts.env ? { env: opts.env } : {});
185
197
  const timeoutMs = opts.timeoutMs ?? SIGN_IN_TIMEOUT_MS;
186
198
  const timeout = AbortSignal.timeout(timeoutMs);
187
199
  const signal = opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout;
@@ -10,7 +10,9 @@
10
10
  // {@link DirectBridge} is that direct leg: it reads the AuthToken from the
11
11
  // session store (src/direct/session.ts) per call and issues an HTTPS request
12
12
  // through mcp-utils netguard `fetchPublic` (pinned to public addresses, so a
13
- // name that resolves or rebinds inward is refused). Every hop must be the exact
13
+ // name that resolves or rebinds inward is refused) — or, with an egress proxy
14
+ // configured (HTTPS_PROXY, mcp-host's only way out), through a proxy agent for
15
+ // it (src/direct/egress.ts), the proxy holding the address table. Every hop must be the exact
14
16
  // origin https://war.app; a non-GET follows no redirect at all, so its body (the
15
17
  // account email, the orders) is never re-sent anywhere
16
18
  // ({@link directFetchOptions}). It maps the reply into the same
@@ -40,6 +42,8 @@
40
42
  import { detectEdgeBlock, EdgeBlockedError, McpToolError } from '@chrischall/mcp-utils';
41
43
  import { createDirectFirstTransport, readTransportMode, } from '@chrischall/mcp-utils/fetchproxy';
42
44
  import { fetchPublic } from '@chrischall/mcp-utils/netguard';
45
+ import { egressDispatcher } from './egress.js';
46
+ import { decodeReplyEnvelope, fromHex } from '../protocol/codec.js';
43
47
  import { isHosted } from '../hosted.js';
44
48
  import { hostedSession, SESSION_HOST, scrubError } from './session.js';
45
49
  /** The env var pinning the transport: `direct` | `fetchproxy` | `auto` (default). */
@@ -150,19 +154,36 @@ export function toDirectResult(res) {
150
154
  }
151
155
  return out;
152
156
  }
153
- /** The default direct leg: a real HTTPS request through netguard `fetchPublic` (public-only, war.app-only). */
154
- const fetchViaPublic = async (url, init) => {
155
- const res = await fetchPublic(url, {
156
- ...directFetchOptions(init.method),
157
- method: init.method,
158
- headers: init.headers,
159
- maxBytes: MAX_DIRECT_BODY_BYTES,
160
- timeoutMs: DIRECT_TIMEOUT_MS,
161
- ...(init.body !== undefined ? { body: init.body } : {}),
162
- ...(init.signal ? { signal: init.signal } : {}),
163
- });
164
- return toDirectResult(res);
165
- };
157
+ /**
158
+ * The default direct leg: a real HTTPS request through netguard `fetchPublic`
159
+ * (war.app-only by `allowHosts` and `stopBefore`). With an egress proxy
160
+ * configured (HTTPS_PROXY: mcp-host's only way out, src/direct/egress.ts) it
161
+ * goes through a proxy agent, built per request and closed after; else netguard
162
+ * builds its public-only dispatcher, as before. A proxy that is set but unusable
163
+ * throws before anything is sent: never a direct connection instead.
164
+ */
165
+ export function createDirectFetch(opts = {}) {
166
+ return async (url, init) => {
167
+ const proxy = egressDispatcher(opts.env ?? process.env, opts.proxyAgent);
168
+ try {
169
+ const res = await fetchPublic(url, {
170
+ ...directFetchOptions(init.method),
171
+ method: init.method,
172
+ headers: init.headers,
173
+ maxBytes: MAX_DIRECT_BODY_BYTES,
174
+ timeoutMs: DIRECT_TIMEOUT_MS,
175
+ ...(init.body !== undefined ? { body: init.body } : {}),
176
+ ...(init.signal ? { signal: init.signal } : {}),
177
+ ...(proxy ? { dispatcher: proxy } : {}),
178
+ });
179
+ return toDirectResult(res);
180
+ }
181
+ finally {
182
+ await proxy?.close().catch(() => { });
183
+ }
184
+ };
185
+ }
186
+ const fetchViaPublic = createDirectFetch();
166
187
  /**
167
188
  * Resolve a bridge path to an absolute https URL on the exact host war.app,
168
189
  * refusing any other host (a subdomain or look-alike included), userinfo and a
@@ -267,9 +288,75 @@ export function looksSignedOut(requestedUrl, res) {
267
288
  return true;
268
289
  return false;
269
290
  }
291
+ /**
292
+ * The page that says whether the session is signed in (live 2026-11-17): signed in it
293
+ * answers 200 "Your invite token is N"; signed out, a 302 to `/LogIn?AuthNeeded=true`.
294
+ */
295
+ export const SIGNED_IN_PROBE_URL = `${SESSION_ORIGIN}/InviteToken`;
296
+ /** war.app's `AuthFailed` server error: its `/Services` answer to a signed-out (or unknown) AuthToken. */
297
+ export const AUTH_FAILED_CODE = 3;
298
+ const INVITE_TOKEN_TEXT = /Your invite token is\s*\d{5,20}/;
299
+ /** Read a reply to {@link SIGNED_IN_PROBE_URL} (pure). Never decides on a reply that says neither. */
300
+ export function signInVerdict(res) {
301
+ let path = '';
302
+ try {
303
+ path = new URL(res.url).pathname;
304
+ }
305
+ catch {
306
+ path = '';
307
+ }
308
+ if (SIGNIN_PATH.test(path))
309
+ return 'signed-out';
310
+ if (res.status !== 200)
311
+ return 'unknown';
312
+ if (INVITE_TOKEN_TEXT.test(res.body))
313
+ return 'signed-in';
314
+ if (hasPasswordInput(res.body))
315
+ return 'signed-out';
316
+ return 'unknown';
317
+ }
318
+ /**
319
+ * Whether a `/Services` reply is war.app's own "not signed in" answer: a valid reply frame
320
+ * carrying server error {@link AUTH_FAILED_CODE} (live 2026-11-17: with no AuthToken, or a
321
+ * bogus one, war.app answers exactly that — never a non-frame body).
322
+ */
323
+ export function isAuthFailedReply(body) {
324
+ if (!looksLikeHexFrame(body))
325
+ return false;
326
+ try {
327
+ return decodeReplyEnvelope(fromHex(body.trim())).error?.code === AUTH_FAILED_CODE;
328
+ }
329
+ catch {
330
+ return false;
331
+ }
332
+ }
333
+ const isServicesUrl = (url) => {
334
+ try {
335
+ return /\/services\b/i.test(new URL(url).pathname);
336
+ }
337
+ catch {
338
+ return false;
339
+ }
340
+ };
341
+ const isProbeUrl = (url) => {
342
+ try {
343
+ const u = new URL(url);
344
+ return u.origin === SESSION_ORIGIN && u.pathname === new URL(SIGNED_IN_PROBE_URL).pathname;
345
+ }
346
+ catch {
347
+ return false;
348
+ }
349
+ };
270
350
  /**
271
351
  * The direct leg: a plain HTTPS request to war.app carrying the linked
272
352
  * AuthToken cookie, mapped to the bridge's `.fetch(init)` surface.
353
+ *
354
+ * A reply that only SUGGESTS a sign-out (a sign-in redirect or form, a 401/403, a
355
+ * `/Services` reply that is not a frame, or war.app's AuthFailed frame) is confirmed with one
356
+ * GET of {@link SIGNED_IN_PROBE_URL} before it is called one: a probe that shows the
357
+ * session signed in passes the reply through as an ordinary failure, so one odd answer no
358
+ * longer walls a good session; a probe that shows it signed out, or cannot tell, keeps the
359
+ * old reading.
273
360
  */
274
361
  export class DirectBridge {
275
362
  store;
@@ -282,6 +369,27 @@ export class DirectBridge {
282
369
  this.fetchImpl = fetchImpl;
283
370
  this.hostSignIn = hostSignIn;
284
371
  }
372
+ /** One GET of {@link SIGNED_IN_PROBE_URL} with the session; `none` when no session is linked. Never throws. */
373
+ async checkSignedIn(signal) {
374
+ const sess = await this.store.read();
375
+ if (!sess)
376
+ return 'none';
377
+ return this.probe(sess.authToken, signal);
378
+ }
379
+ async probe(token, signal) {
380
+ try {
381
+ const res = await this.fetchImpl(SIGNED_IN_PROBE_URL, {
382
+ method: 'GET',
383
+ headers: { cookie: `AuthToken=${token}` },
384
+ ...(signal ? { signal } : {}),
385
+ });
386
+ return signInVerdict(res);
387
+ }
388
+ catch {
389
+ // Nothing from a failed probe reaches a caller: the token cannot leak through it.
390
+ return 'unknown';
391
+ }
392
+ }
285
393
  async fetch(init, signal) {
286
394
  const sess = await this.store.read();
287
395
  if (!sess)
@@ -317,8 +425,13 @@ export class DirectBridge {
317
425
  });
318
426
  }
319
427
  }
320
- if (looksSignedOut(url, res)) {
321
- throw new SessionExpiredError({ capturedAt: sess.capturedAt, hostSignIn: this.hostSignIn || sess.origin === 'host' });
428
+ const suspect = looksSignedOut(url, res) || (answered && isServicesUrl(url) && isAuthFailedReply(res.body));
429
+ if (suspect) {
430
+ // A GET of the probe page is its own probe; anything else asks once.
431
+ const verdict = isProbeUrl(url) && isSafeToReplay(init.method) ? signInVerdict(res) : await this.probe(token, signal);
432
+ if (verdict !== 'signed-in') {
433
+ throw new SessionExpiredError({ capturedAt: sess.capturedAt, hostSignIn: this.hostSignIn || sess.origin === 'host' });
434
+ }
322
435
  }
323
436
  return { status: res.status, body: res.body, url: res.url };
324
437
  }
@@ -328,6 +441,16 @@ export class DirectBridge {
328
441
  * another process) at most once per this many ms, not on every bridged call.
329
442
  */
330
443
  export const RELINK_CHECK_MS = 5_000;
444
+ /**
445
+ * Hosted, the direct leg is tried again this long after the router leaves it: a hosted
446
+ * child cannot be relinked in-process (its session is the one mcp-host injected at spawn, whose
447
+ * capture time never changes), so without a retry one odd answer — or a passing edge challenge —
448
+ * kept it off the direct leg until the process restarted. Each wall in a row doubles the wait,
449
+ * up to {@link WALL_RETRY_MAX_MS}; a direct success starts it over.
450
+ */
451
+ export const WALL_RETRY_BASE_MS = 60_000;
452
+ /** The longest wait before a hosted child tries the direct leg again. */
453
+ export const WALL_RETRY_MAX_MS = 30 * 60_000;
331
454
  /**
332
455
  * Wire the direct leg and the fetchproxy bridge into a direct-first router,
333
456
  * returning an object shaped like today's bridge (`ready()` → `{ fetch }`) plus
@@ -351,24 +474,30 @@ export function createDirectFirstBridge(opts) {
351
474
  : (opts.mode ?? readTransportMode(TRANSPORT_ENV, opts.env ? { env: opts.env } : {}));
352
475
  const store = hosted ? { read: async () => hostSession } : opts.store;
353
476
  const hostSignIn = hostSession !== null;
354
- const direct = new DirectBridge(store, opts.directFetch, hostSignIn);
477
+ const direct = new DirectBridge(store, opts.directFetch ?? createDirectFetch({ env }), hostSignIn);
355
478
  const log = opts.log ?? ((m) => console.error(m));
356
479
  const now = opts.now ?? Date.now;
357
480
  let wall = null;
358
481
  let stale = false;
359
482
  let lastRelinkCheck = Number.NEGATIVE_INFINITY;
483
+ /** Walls in a row since the direct leg last answered 200: the hosted backoff's exponent. */
484
+ let wallsInARow = 0;
360
485
  const onFallback = ({ error }) => {
361
- const next = error instanceof SessionExpiredError
362
- ? { kind: 'session', capturedAt: error.capturedAt ?? null }
363
- : error instanceof SessionNotLinkedError
364
- ? { kind: 'session', capturedAt: null }
365
- : { kind: 'edge' };
366
- wall = next;
367
486
  const why = error instanceof SessionExpiredError
368
487
  ? 'the linked war.app session is signed out'
369
488
  : error instanceof SessionNotLinkedError
370
489
  ? 'no war.app session is linked'
371
490
  : 'the site edge refused the direct request';
491
+ const since = now();
492
+ wallsInARow += 1;
493
+ const retryAt = hosted ? since + Math.min(WALL_RETRY_BASE_MS * 2 ** (wallsInARow - 1), WALL_RETRY_MAX_MS) : null;
494
+ const timing = { reason: why, since, retryAt };
495
+ const next = error instanceof SessionExpiredError
496
+ ? { kind: 'session', capturedAt: error.capturedAt ?? null, ...timing }
497
+ : error instanceof SessionNotLinkedError
498
+ ? { kind: 'session', capturedAt: null, ...timing }
499
+ : { kind: 'edge', ...timing };
500
+ wall = next;
372
501
  log(`[warapp-mcp] Direct transport unavailable (${why}) — switching to the ContextMint Bridge browser bridge. ` +
373
502
  `Keep a ${SESSION_HOST} tab open and approve the pairing prompt in the extension if one appears` +
374
503
  (next.kind !== 'session'
@@ -390,12 +519,18 @@ export function createDirectFirstBridge(opts) {
390
519
  onFallback,
391
520
  });
392
521
  let legs = build();
522
+ /** Lift any wall: a fresh router, back on the direct leg. */
523
+ const liftWall = () => {
524
+ if (!wall)
525
+ return;
526
+ wall = null;
527
+ legs = build();
528
+ };
393
529
  /** Lift a session-caused wall: a fresh router, back on the direct leg. An edge wall stays. */
394
530
  const liftSessionWall = () => {
395
531
  if (wall?.kind !== 'session')
396
532
  return;
397
- wall = null;
398
- legs = build();
533
+ liftWall();
399
534
  };
400
535
  /** Behind a session wall: has a DIFFERENT session been linked since (e.g. by another process)? */
401
536
  const relinkedSinceWall = async () => {
@@ -413,6 +548,10 @@ export function createDirectFirstBridge(opts) {
413
548
  liftSessionWall();
414
549
  stale = false;
415
550
  }
551
+ // Hosted: past the backoff, the direct leg is tried again. A write that reaches
552
+ // war.app signed out on it is still never re-sent over the bridge (below).
553
+ if (mode === 'auto' && wall?.retryAt != null && now() >= wall.retryAt)
554
+ liftWall();
416
555
  // A non-GET whose direct attempt reached war.app (it answered signed-out)
417
556
  // is never re-sent over the bridge: a write must never be sent twice.
418
557
  let reached;
@@ -421,8 +560,10 @@ export function createDirectFirstBridge(opts) {
421
560
  try {
422
561
  const res = await direct.fetch(init, ctx.signal);
423
562
  // Only a 200 proves the session works; a 5xx says nothing about it.
424
- if (res.status === 200)
563
+ if (res.status === 200) {
425
564
  stale = false;
565
+ wallsInARow = 0;
566
+ }
426
567
  return res;
427
568
  }
428
569
  catch (err) {
@@ -446,6 +587,27 @@ export function createDirectFirstBridge(opts) {
446
587
  bridgeTransport: () => legs.bridgeTransport(),
447
588
  stats: () => legs.stats(),
448
589
  sessionStale: () => stale,
590
+ wall: () => wall
591
+ ? {
592
+ kind: wall.kind,
593
+ reason: wall.reason,
594
+ since: new Date(wall.since).toISOString(),
595
+ retryAt: wall.retryAt === null ? null : new Date(wall.retryAt).toISOString(),
596
+ }
597
+ : null,
598
+ checkSession: async () => {
599
+ const verdict = await direct.checkSignedIn();
600
+ if (verdict === 'signed-in') {
601
+ stale = false;
602
+ wallsInARow = 0;
603
+ if (mode === 'auto')
604
+ liftWall();
605
+ }
606
+ else if (verdict === 'signed-out') {
607
+ stale = true;
608
+ }
609
+ return verdict;
610
+ },
449
611
  sessionLinked: () => {
450
612
  stale = false;
451
613
  if (mode === 'auto')