@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.
@@ -23,7 +23,9 @@
23
23
  import { createHash, randomBytes } from 'node:crypto';
24
24
  import { chmod, mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
25
25
  import { join } from 'node:path';
26
- import { BundleInterpreter, parseBundle, READER_HELPERS, REQUIRED_HELPERS, } from './interp.js';
26
+ import { withPathLock } from '../path-lock.js';
27
+ import { PROTOCOL_VERSION } from './codec.js';
28
+ import { BundleInterpreter, parseBundle, } from './interp.js';
27
29
  /** A page that loads the game client (the homepage does not). */
28
30
  const DEFAULT_PAGE_URL = 'https://war.app/MultiPlayer';
29
31
  /** The only host the bundle is downloaded from (exactly this host: no subdomain, no port). */
@@ -83,9 +85,40 @@ export class WarappBundle {
83
85
  interp;
84
86
  /** Loaded from the cache because the current version could not be looked up. */
85
87
  fallback = false;
88
+ /** Set when this is the pinned known-good client standing in for a refused current one. */
89
+ standInFor;
90
+ /** Set while this build stands in for a refused current client: the window (see {@link StandInWindow}). */
91
+ standIn;
92
+ /** The SHA-256 of this build's bytes (set by {@link loadBundle}); a build without one is never recorded. */
93
+ digest;
94
+ /** Records this build as one that decoded a live board (set by {@link loadBundle}). */
95
+ recorder;
96
+ recorded;
97
+ /**
98
+ * A live board decoded with this build, every byte consumed: record it as a build that works, so a
99
+ * later client this server cannot read is stood in for by it (the owner, 2026-11-17: fall back
100
+ * gracefully). Once per loaded bundle; never throws.
101
+ */
102
+ markDecoded() {
103
+ if (this.recorded)
104
+ return this.recorded.then((r) => (r === 'recorded' ? 'unchanged' : r));
105
+ this.recorded = this.recorder ? this.recorder().catch(() => 'failed') : Promise.resolve('unchanged');
106
+ return this.recorded;
107
+ }
86
108
  constructor(src, version, opts = {}) {
87
109
  this.version = version;
88
110
  this.interp = new BundleInterpreter(parseBundle(src), opts);
111
+ // Every request is framed in this server's protocol, and war.app answers in the protocol a request
112
+ // declares, so the replies are in PROTOCOL_VERSION's layout: a client whose readers default to another
113
+ // protocol would read them in its own layout. Such a build (a newer release, or an old stand-in) is
114
+ // refused here, like a client whose helpers cannot be checked (docs/CLIENT-RELEASES.md).
115
+ const protocol = this.interp.bundleProtocol;
116
+ if (opts.version === undefined && protocol !== undefined && protocol !== PROTOCOL_VERSION) {
117
+ throw new BundleError('protocol-mismatch', `war.app's client bundle ${version} speaks protocol ${protocol}, and this server speaks ${PROTOCOL_VERSION}; ` +
118
+ 'its readers would read the replies in the wrong layout, so it is not used. ' +
119
+ (protocol > PROTOCOL_VERSION ? 'The client changed and this server needs an update.' : 'It is an older client.'));
120
+ }
121
+ this.protocol = protocol;
89
122
  // The built-in reader helpers are pinned to one client release while the bundle floats:
90
123
  // refuse a bundle whose own helpers read differently, rather than decode it wrongly (#131).
91
124
  this.dialectCheck = this.interp.verifyDialect();
@@ -95,7 +128,7 @@ export class WarappBundle {
95
128
  }
96
129
  // The count, flag and byte helpers decode every army count, fog flag and unit count: one this
97
130
  // check cannot verify could be a swapped same-width read, which no later check catches (#148).
98
- const unverifiedRequired = REQUIRED_HELPERS.map((n) => `${READER_HELPERS}.${n}`).filter((k) => this.dialectCheck.unverified.includes(k));
131
+ const unverifiedRequired = this.interp.requiredHelpers.map((n) => `${this.interp.helperClass}.${n}`).filter((k) => this.dialectCheck.unverified.includes(k));
99
132
  if (unverifiedRequired.length) {
100
133
  throw new BundleError('dialect-unverified', `war.app's client bundle ${version} defines ${unverifiedRequired.join(', ')} in a way this server cannot check ` +
101
134
  `(${unverifiedRequired.map((k) => this.dialectCheck.reasons?.[k] ?? 'unverified').join('; ')}); those read every ` +
@@ -104,6 +137,12 @@ export class WarappBundle {
104
137
  }
105
138
  /** The built-in reader helpers checked against this bundle's own definitions at load. */
106
139
  dialectCheck;
140
+ /** The protocol version the bundle's readers default to, when it can be read from the bundle. */
141
+ protocol;
142
+ /** The reader names were derived from this bundle (false: the built-in v6.07 names). */
143
+ get derivedDialect() {
144
+ return this.interp.derived;
145
+ }
107
146
  /** What this bundle's decoding rests on, for the tools to show (#148). */
108
147
  report() {
109
148
  const { verified, unverified, reasons } = this.dialectCheck;
@@ -111,6 +150,8 @@ export class WarappBundle {
111
150
  bundleVersion: this.version,
112
151
  fallback: this.fallback,
113
152
  helpers: { verified: [...verified], unverified: [...unverified], ...(reasons ? { reasons: { ...reasons } } : {}) },
153
+ ...(this.standInFor ? { standInFor: { ...this.standInFor } } : {}),
154
+ ...(this.standIn ? { standIn: { ...this.standIn } } : {}),
114
155
  };
115
156
  }
116
157
  /** Whether a type name is registered in this bundle. */
@@ -133,6 +174,19 @@ export class WarappBundle {
133
174
  return this.interp.readClass(typeNameOrVar, reader, budget);
134
175
  }
135
176
  }
177
+ /**
178
+ * The pinned known-good client: v6.08.0.2, protocol 243, the release every hand-written encoder and
179
+ * reader of this server is written for (#340). It stands in for a current client refused at load when
180
+ * no recorded build does, only with this digest. war.app's CDN ignores `?v=` and serves the current
181
+ * build, so it can be downloaded by version only while Cloudflare still caches that URL
182
+ * (docs/CLIENT-RELEASES.md): the copy kept in the data dir is what a stand-in really rests on.
183
+ */
184
+ export const KNOWN_GOOD_BUNDLE = {
185
+ version: '639304508939095333',
186
+ digest: '3c55e2d08681d05661eb350b3d72d02f25729130bb78dc9c5d3b1febd73febd1',
187
+ };
188
+ /** The CDN URL of a client release, by version (the location {@link discoverBundleUrl} pins). */
189
+ const bundleUrlOf = (version) => `https://${BUNDLE_HOST}${BUNDLE_PATH}?v=${version}`;
136
190
  /** A cached bundle: `<version>.<sha256 of its bytes>.js`. */
137
191
  const BUNDLE_FILE = /^([A-Za-z0-9._-]{1,64})\.([0-9a-f]{64})\.js$/;
138
192
  /** A cache file of the earlier layouts, never read, only pruned: `<version>.js` and `<version>.js.sha256`. */
@@ -182,7 +236,7 @@ async function abandoned(file, pid) {
182
236
  async function pruneBundles(dir, keep) {
183
237
  try {
184
238
  for (const name of await readdir(dir)) {
185
- if (name === keep)
239
+ if (keep.includes(name))
186
240
  continue;
187
241
  const partial = PARTIAL_FILE.exec(name);
188
242
  if (!partial && !BUNDLE_FILE.test(name) && !LEGACY_FILE.test(name))
@@ -288,10 +342,172 @@ async function readVerified(file, digest) {
288
342
  await rm(file, { force: true });
289
343
  return null;
290
344
  }
345
+ /** Whether `e` is the load-time refusal of a client this server cannot read (#131, #148). */
346
+ const isDialectRefusal = (e) => e instanceof BundleError && (e.kind === 'dialect-mismatch' || e.kind === 'dialect-unverified' || e.kind === 'protocol-mismatch');
347
+ /** Write `src` into the cache as `name` (`0700` directories, an atomic `0600` file). */
348
+ async function cacheBundle(dataDir, dir, name, src) {
349
+ await ensurePrivateDir(dataDir);
350
+ await ensurePrivateDir(dir);
351
+ await writePrivateAtomic(join(dir, name), Buffer.from(src, 'utf8'));
352
+ }
353
+ /** The record of client builds that decoded a live board, in `<dataDir>/bundle/`. */
354
+ export const KNOWN_GOOD_FILE = 'known-good.json';
355
+ /** The open stand-in window (the refused client and when it was first refused), in `<dataDir>/bundle/`. */
356
+ export const STAND_IN_FILE = 'stand-in.json';
357
+ /** How many recorded builds are kept, newest first (each keeps its ~16 MB copy on disk). */
358
+ export const MAX_KNOWN_GOOD = 3;
359
+ const DIGEST = /^[0-9a-f]{64}$/;
360
+ const isRecorded = (v) => {
361
+ if (typeof v !== 'object' || v === null)
362
+ return false;
363
+ const r = v;
364
+ return (typeof r.version === 'string' &&
365
+ SAFE_VERSION.test(r.version) &&
366
+ typeof r.digest === 'string' &&
367
+ DIGEST.test(r.digest) &&
368
+ typeof r.verifiedAt === 'string');
369
+ };
370
+ /**
371
+ * The recorded builds in the bundle directory `dir`, newest first: `[]` when there is no record,
372
+ * `'unreadable'` when the file exists but does not parse (never overwritten). Malformed entries are skipped.
373
+ */
374
+ export async function readKnownGood(dir) {
375
+ let text;
376
+ try {
377
+ text = await readFile(join(dir, KNOWN_GOOD_FILE), 'utf8');
378
+ }
379
+ catch (e) {
380
+ return e.code === 'ENOENT' ? [] : 'unreadable';
381
+ }
382
+ try {
383
+ const parsed = JSON.parse(text);
384
+ const builds = parsed?.builds;
385
+ if (!Array.isArray(builds))
386
+ return 'unreadable';
387
+ return builds.filter(isRecorded);
388
+ }
389
+ catch {
390
+ return 'unreadable';
391
+ }
392
+ }
393
+ /**
394
+ * Record `entry` as a build that decoded a live board: newest first, one entry per version and digest, at
395
+ * most {@link MAX_KNOWN_GOOD}; written `0600` through a temporary file and a rename, under the in-process
396
+ * path lock. A record that does not parse is never overwritten (`'unreadable'`).
397
+ */
398
+ export async function recordKnownGood(dataDir, entry) {
399
+ if (!isRecorded(entry))
400
+ return 'failed';
401
+ const dir = join(dataDir, 'bundle');
402
+ const file = join(dir, KNOWN_GOOD_FILE);
403
+ return withPathLock(file, async () => {
404
+ const builds = await readKnownGood(dir);
405
+ if (builds === 'unreadable')
406
+ return 'unreadable';
407
+ const rest = builds.filter((b) => !(b.version === entry.version && b.digest === entry.digest));
408
+ const next = [entry, ...rest].slice(0, MAX_KNOWN_GOOD);
409
+ try {
410
+ await ensurePrivateDir(dataDir);
411
+ await ensurePrivateDir(dir);
412
+ await writePrivateAtomic(file, `${JSON.stringify({ builds: next }, null, 2)}\n`);
413
+ return 'recorded';
414
+ }
415
+ catch {
416
+ return 'failed';
417
+ }
418
+ });
419
+ }
420
+ /** The open stand-in window on disk, or undefined (none, or not readable). */
421
+ async function readWindow(dir) {
422
+ try {
423
+ const w = JSON.parse(await readFile(join(dir, STAND_IN_FILE), 'utf8'));
424
+ if (typeof w.refusedVersion === 'string' && typeof w.since === 'string' && !Number.isNaN(Date.parse(w.since))) {
425
+ return { refusedVersion: w.refusedVersion, since: w.since };
426
+ }
427
+ }
428
+ catch {
429
+ // None yet.
430
+ }
431
+ return undefined;
432
+ }
433
+ /**
434
+ * When `refusedVersion` was first refused here: the time kept on disk for that version, else `now`
435
+ * (written, so the window survives a restart). Best effort: a write that fails still returns `now`.
436
+ */
437
+ async function openWindow(dataDir, dir, refusedVersion, reason, now) {
438
+ const kept = await readWindow(dir);
439
+ if (kept?.refusedVersion === refusedVersion)
440
+ return kept.since;
441
+ const since = new Date(now).toISOString();
442
+ try {
443
+ await ensurePrivateDir(dataDir);
444
+ await ensurePrivateDir(dir);
445
+ await writePrivateAtomic(join(dir, STAND_IN_FILE), `${JSON.stringify({ refusedVersion, since, reason }, null, 2)}\n`);
446
+ }
447
+ catch {
448
+ // The window is still reported for this load.
449
+ }
450
+ return since;
451
+ }
452
+ /** The current client loads: the window is closed. Best effort. */
453
+ async function closeWindow(dir) {
454
+ await rm(join(dir, STAND_IN_FILE), { force: true }).catch(() => undefined);
455
+ }
456
+ /**
457
+ * A build pinned by version and digest, from the cache or downloaded by version and kept only when its bytes
458
+ * hash to that digest, loaded; `undefined` when it cannot be had or this server refuses it too.
459
+ */
460
+ async function loadPinned(opts, dir, kg) {
461
+ const name = bundleName(kg.version, kg.digest);
462
+ let src = await readVerified(join(dir, name), kg.digest);
463
+ if (src === null) {
464
+ let fetched;
465
+ try {
466
+ fetched = await opts.fetchText(bundleUrlOf(kg.version));
467
+ }
468
+ catch {
469
+ return undefined;
470
+ }
471
+ if (sha256(Buffer.from(fetched, 'utf8')) !== kg.digest || !looksLikeBundle(fetched))
472
+ return undefined;
473
+ try {
474
+ await cacheBundle(opts.dataDir, dir, name, fetched);
475
+ }
476
+ catch {
477
+ return undefined;
478
+ }
479
+ src = fetched;
480
+ }
481
+ try {
482
+ const bundle = new WarappBundle(src, kg.version, opts.interp);
483
+ bundle.digest = kg.digest;
484
+ return { bundle, name };
485
+ }
486
+ catch {
487
+ return undefined;
488
+ }
489
+ }
490
+ /** Wire `bundle` to record itself once a live board decodes with it. */
491
+ function withRecorder(opts, bundle) {
492
+ const now = opts.now ?? Date.now;
493
+ bundle.recorder = async () => {
494
+ if (!bundle.digest)
495
+ return 'unchanged';
496
+ return recordKnownGood(opts.dataDir, { version: bundle.version, digest: bundle.digest, verifiedAt: new Date(now()).toISOString() });
497
+ };
498
+ return bundle;
499
+ }
500
+ /** The cache names of every recorded build (they stay on disk: a later refusal may need any of them). */
501
+ async function recordedNames(dir) {
502
+ const builds = await readKnownGood(dir);
503
+ return builds === 'unreadable' ? [] : builds.map((b) => bundleName(b.version, b.digest));
504
+ }
291
505
  /** Discover, fetch (or reuse the verified cached copy of) and load the current client bundle. */
292
506
  export async function loadBundle(opts) {
293
507
  const pageUrl = opts.pageUrl ?? DEFAULT_PAGE_URL;
294
508
  const dir = join(opts.dataDir, 'bundle');
509
+ const kg = opts.knownGood === undefined ? KNOWN_GOOD_BUNDLE : opts.knownGood;
510
+ const now = opts.now ?? Date.now;
295
511
  let source;
296
512
  try {
297
513
  source = discoverBundleUrl(await opts.fetchText(pageUrl), pageUrl);
@@ -299,13 +515,24 @@ export async function loadBundle(opts) {
299
515
  catch (e) {
300
516
  // The page naming the current version could not be read (a frozen tab, a signed-out page):
301
517
  // a copy already on disk still decodes, rather than failing every live read (#131).
302
- // Only a copy that still matches its recorded digest stands in.
303
- const cached = await newestVerified(dir);
304
- if (!cached)
305
- throw e;
306
- const b = new WarappBundle(cached.src, cached.version, opts.interp);
307
- b.fallback = true;
308
- return b;
518
+ // Only a copy that still matches its recorded digest stands in, newest first, skipping one
519
+ // this server refuses to read (a client it was never written for).
520
+ for (const c of await cachedNewestFirst(dir)) {
521
+ const src = await readVerified(c.file, c.digest);
522
+ if (src === null)
523
+ continue;
524
+ try {
525
+ const b = new WarappBundle(src, c.version, opts.interp);
526
+ b.fallback = true;
527
+ b.digest = c.digest;
528
+ return withRecorder(opts, b);
529
+ }
530
+ catch (err) {
531
+ if (!isDialectRefusal(err))
532
+ throw err;
533
+ }
534
+ }
535
+ throw e;
309
536
  }
310
537
  const { url, version } = source;
311
538
  const cached = await newestVerified(dir, version);
@@ -319,22 +546,54 @@ export async function loadBundle(opts) {
319
546
  if (!looksLikeBundle(src)) {
320
547
  throw new BundleError('bad-bundle', `${url} does not look like the war.app client bundle`);
321
548
  }
322
- await ensurePrivateDir(opts.dataDir);
323
- await ensurePrivateDir(dir);
324
- const bytes = Buffer.from(src, 'utf8');
325
549
  // One file, its digest in its name, made visible by one rename: never a bundle without its digest.
326
- name = bundleName(version, sha256(bytes));
327
- await writePrivateAtomic(join(dir, name), bytes);
550
+ name = bundleName(version, sha256(Buffer.from(src, 'utf8')));
551
+ await cacheBundle(opts.dataDir, dir, name, src);
328
552
  }
329
- const bundle = new WarappBundle(src, version, opts.interp);
330
- await pruneBundles(dir, name);
331
- return bundle;
553
+ const keepKnownGood = kg ? [bundleName(kg.version, kg.digest)] : [];
554
+ const keepRecorded = await recordedNames(dir);
555
+ let bundle;
556
+ try {
557
+ bundle = new WarappBundle(src, version, opts.interp);
558
+ }
559
+ catch (e) {
560
+ if (!isDialectRefusal(e))
561
+ throw e;
562
+ // Stand-ins, best first: every build that decoded a live board here (newest first), then the pin.
563
+ const recorded = await readKnownGood(dir);
564
+ const candidates = [
565
+ ...(recorded === 'unreadable' ? [] : recorded.map(({ version: v, digest }) => ({ version: v, digest }))),
566
+ ...(kg ? [kg] : []),
567
+ ].filter((c, i, all) => c.version !== version && all.findIndex((o) => o.version === c.version && o.digest === c.digest) === i);
568
+ for (const c of candidates) {
569
+ const standIn = await loadPinned(opts, dir, c);
570
+ if (!standIn)
571
+ continue;
572
+ const since = await openWindow(opts.dataDir, dir, version, e.message, now());
573
+ standIn.bundle.standInFor = { version, reason: e.message };
574
+ standIn.bundle.standIn = { version: c.version, refusedVersion: version, since, reason: e.message };
575
+ // All stay: the refused copy so the next lookup does not download it again, the stand-in in use,
576
+ // and every recorded build.
577
+ await pruneBundles(dir, [name, standIn.name, ...keepKnownGood, ...keepRecorded]);
578
+ return withRecorder(opts, standIn.bundle);
579
+ }
580
+ throw e;
581
+ }
582
+ bundle.digest = name.slice(version.length + 1, -'.js'.length);
583
+ await closeWindow(dir);
584
+ await pruneBundles(dir, [name, ...keepKnownGood, ...keepRecorded]);
585
+ return withRecorder(opts, bundle);
332
586
  }
333
587
  /**
334
588
  * How long a fallback bundle is used, or a refused (dialect-mismatch) bundle is remembered, before
335
589
  * the current version is looked up again.
336
590
  */
337
591
  const FALLBACK_RETRY_MS = 5 * 60_000;
592
+ /**
593
+ * How long the known-good stand-in is used before the current version is looked up again: re-checking
594
+ * a refused ~16 MB bundle costs seconds of parsing, and a client release changes rarely.
595
+ */
596
+ const STAND_IN_RETRY_MS = 60 * 60_000;
338
597
  /**
339
598
  * Loads the bundle once per process; a failed load is retried on the next call, except a bundle
340
599
  * refused as a dialect mismatch, which is retried after {@link FALLBACK_RETRY_MS}.
@@ -356,14 +615,18 @@ export class BundleProvider {
356
615
  this.pending = p;
357
616
  p.then((b) => {
358
617
  // A cached copy stands in only until the version can be looked up again.
359
- if (b.fallback && this.pending === p)
618
+ if (this.pending !== p)
619
+ return;
620
+ if (b.standInFor)
621
+ this.fallbackUntil = now() + STAND_IN_RETRY_MS;
622
+ else if (b.fallback)
360
623
  this.fallbackUntil = now() + FALLBACK_RETRY_MS;
361
624
  }, (e) => {
362
625
  if (this.pending !== p)
363
626
  return;
364
627
  // A bundle this server cannot read stays unreadable: remember the refusal for a while
365
628
  // instead of re-reading and re-checking ~16 MB on every live call (#131).
366
- if (e instanceof BundleError && (e.kind === 'dialect-mismatch' || e.kind === 'dialect-unverified')) {
629
+ if (isDialectRefusal(e)) {
367
630
  this.fallbackUntil = now() + FALLBACK_RETRY_MS;
368
631
  }
369
632
  else
@@ -19,7 +19,7 @@
19
19
  // parameters. Replies carry a byte (1 → MessageExtrasDown follows), a kind byte
20
20
  // (5 → a server error {code, message} follows) and the method's result.
21
21
  export const PREAMBLE = 1514664249;
22
- export const PROTOCOL_VERSION = 242;
22
+ export const PROTOCOL_VERSION = 243;
23
23
  const REPLY_FLAG = 0x8000;
24
24
  /** Milliseconds from the Unix epoch to 2000-01-01T00:00:00Z, the protocol's date epoch. */
25
25
  export const DATE_EPOCH_MS = Date.UTC(2000, 0, 1);