@chrischall/warapp-mcp 0.3.1 → 0.5.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/dist/chat.js CHANGED
@@ -16,9 +16,12 @@ import { parseFeedTime } from './normalize.js';
16
16
  import { asInt } from './scalars.js';
17
17
  export const GAME_DETAILS_AND_CHAT = 'warlight.shared.GameDetailsAndChat';
18
18
  export const GAME_MESSAGE = 'warlight.shared.GameMessage';
19
- /** GameMessage field positions in read order, and its whole field count. */
20
- const GM = { date: 0, sender: 1, group: 2, id: 4, text: 5, channel: 6, to: 7, turn: 9 };
21
- export const GAME_MESSAGE_FIELDS = 10;
19
+ /**
20
+ * GameMessage field positions in read order, and its whole field count (protocol 243: the shared images,
21
+ * an optional list of strings, at 5, and the reactions, an optional list of records, at 7).
22
+ */
23
+ const GM = { date: 0, sender: 1, group: 2, id: 4, images: 5, text: 6, reactions: 7, channel: 8, to: 9, turn: 11 };
24
+ export const GAME_MESSAGE_FIELDS = 12;
22
25
  /** The public channel's value (any other is a team). */
23
26
  export const PUBLIC_CHANNEL = -1;
24
27
  export const CHAT_CHANNELS = ['public', 'team', 'private', 'unknown'];
@@ -39,8 +42,13 @@ function webLine(m) {
39
42
  const channel = f[GM.channel];
40
43
  const to = f[GM.to];
41
44
  const turn = f[GM.turn];
45
+ const images = f[GM.images];
46
+ const reactions = f[GM.reactions];
42
47
  if (!(date === null || date instanceof Date) || !optInt(sender) || !optInt(group) || !optInt(to) || !optInt(turn))
43
48
  return undefined;
49
+ // Not reported, but checked: a field of another type here means the layout is not 243's.
50
+ if (!(images === null || Array.isArray(images)) || !(reactions === null || Array.isArray(reactions)))
51
+ return undefined;
44
52
  if (!(id === null || typeof id === 'string' || isInt(id)) || typeof text !== 'string' || !isInt(channel))
45
53
  return undefined;
46
54
  const line = { sender, text, turn, channel: 'unknown' };
@@ -43,6 +43,7 @@ import { detectEdgeBlock, EdgeBlockedError, McpToolError } from '@chrischall/mcp
43
43
  import { createDirectFirstTransport, readTransportMode, } from '@chrischall/mcp-utils/fetchproxy';
44
44
  import { fetchPublic } from '@chrischall/mcp-utils/netguard';
45
45
  import { egressDispatcher } from './egress.js';
46
+ import { decodeReplyEnvelope, fromHex } from '../protocol/codec.js';
46
47
  import { isHosted } from '../hosted.js';
47
48
  import { hostedSession, SESSION_HOST, scrubError } from './session.js';
48
49
  /** The env var pinning the transport: `direct` | `fetchproxy` | `auto` (default). */
@@ -287,9 +288,75 @@ export function looksSignedOut(requestedUrl, res) {
287
288
  return true;
288
289
  return false;
289
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
+ };
290
350
  /**
291
351
  * The direct leg: a plain HTTPS request to war.app carrying the linked
292
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.
293
360
  */
294
361
  export class DirectBridge {
295
362
  store;
@@ -302,6 +369,27 @@ export class DirectBridge {
302
369
  this.fetchImpl = fetchImpl;
303
370
  this.hostSignIn = hostSignIn;
304
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
+ }
305
393
  async fetch(init, signal) {
306
394
  const sess = await this.store.read();
307
395
  if (!sess)
@@ -337,8 +425,13 @@ export class DirectBridge {
337
425
  });
338
426
  }
339
427
  }
340
- if (looksSignedOut(url, res)) {
341
- 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
+ }
342
435
  }
343
436
  return { status: res.status, body: res.body, url: res.url };
344
437
  }
@@ -348,6 +441,16 @@ export class DirectBridge {
348
441
  * another process) at most once per this many ms, not on every bridged call.
349
442
  */
350
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;
351
454
  /**
352
455
  * Wire the direct leg and the fetchproxy bridge into a direct-first router,
353
456
  * returning an object shaped like today's bridge (`ready()` → `{ fetch }`) plus
@@ -377,18 +480,24 @@ export function createDirectFirstBridge(opts) {
377
480
  let wall = null;
378
481
  let stale = false;
379
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;
380
485
  const onFallback = ({ error }) => {
381
- const next = error instanceof SessionExpiredError
382
- ? { kind: 'session', capturedAt: error.capturedAt ?? null }
383
- : error instanceof SessionNotLinkedError
384
- ? { kind: 'session', capturedAt: null }
385
- : { kind: 'edge' };
386
- wall = next;
387
486
  const why = error instanceof SessionExpiredError
388
487
  ? 'the linked war.app session is signed out'
389
488
  : error instanceof SessionNotLinkedError
390
489
  ? 'no war.app session is linked'
391
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;
392
501
  log(`[warapp-mcp] Direct transport unavailable (${why}) — switching to the ContextMint Bridge browser bridge. ` +
393
502
  `Keep a ${SESSION_HOST} tab open and approve the pairing prompt in the extension if one appears` +
394
503
  (next.kind !== 'session'
@@ -410,12 +519,18 @@ export function createDirectFirstBridge(opts) {
410
519
  onFallback,
411
520
  });
412
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
+ };
413
529
  /** Lift a session-caused wall: a fresh router, back on the direct leg. An edge wall stays. */
414
530
  const liftSessionWall = () => {
415
531
  if (wall?.kind !== 'session')
416
532
  return;
417
- wall = null;
418
- legs = build();
533
+ liftWall();
419
534
  };
420
535
  /** Behind a session wall: has a DIFFERENT session been linked since (e.g. by another process)? */
421
536
  const relinkedSinceWall = async () => {
@@ -433,6 +548,10 @@ export function createDirectFirstBridge(opts) {
433
548
  liftSessionWall();
434
549
  stale = false;
435
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();
436
555
  // A non-GET whose direct attempt reached war.app (it answered signed-out)
437
556
  // is never re-sent over the bridge: a write must never be sent twice.
438
557
  let reached;
@@ -441,8 +560,10 @@ export function createDirectFirstBridge(opts) {
441
560
  try {
442
561
  const res = await direct.fetch(init, ctx.signal);
443
562
  // Only a 200 proves the session works; a 5xx says nothing about it.
444
- if (res.status === 200)
563
+ if (res.status === 200) {
445
564
  stale = false;
565
+ wallsInARow = 0;
566
+ }
446
567
  return res;
447
568
  }
448
569
  catch (err) {
@@ -466,6 +587,27 @@ export function createDirectFirstBridge(opts) {
466
587
  bridgeTransport: () => legs.bridgeTransport(),
467
588
  stats: () => legs.stats(),
468
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
+ },
469
611
  sessionLinked: () => {
470
612
  stale = false;
471
613
  if (mode === 'auto')
package/dist/my-games.js CHANGED
@@ -26,7 +26,7 @@ export const gameStateName = (code) => GAME_STATE_NAMES[code] ?? String(code);
26
26
  const GAME_WAITING = 2;
27
27
  const GAME_PLAYING = 3;
28
28
  const GAME_DISTRIBUTING = 5;
29
- const GAME_FINISHED = 4;
29
+ export const GAME_FINISHED = 4;
30
30
  const PLAYER_PLAYING = 2;
31
31
  /** GameInfo field positions in read order, and its whole field count (src/open-games.ts reads the same record). */
32
32
  const GI = { gameId: 7, name: 13, lastTurn: 14, players: 16, state: 22 };