@chrischall/warapp-mcp 0.0.0 → 0.2.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/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +211 -9
- package/dist/analysis/accept-surrender.js +56 -0
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/calibrate.js +239 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/finished-game.js +136 -0
- package/dist/analysis/game-lessons.js +217 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +179 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +552 -0
- package/dist/analysis/opponents.js +1253 -0
- package/dist/analysis/outlook.js +695 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1405 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +1001 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2927 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +584 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1112 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +121082 -36148
- package/dist/calibration-source.js +75 -0
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +265 -0
- package/dist/client.js +439 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/finished-store.js +357 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/lessons-store.js +356 -0
- package/dist/live.js +287 -0
- package/dist/map-details.js +127 -0
- package/dist/map-stats.js +160 -0
- package/dist/map-store.js +242 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +218 -0
- package/dist/normalize.js +443 -0
- package/dist/notifications.js +143 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +165 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +231 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +727 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +615 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +227 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +291 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2223 -0
- package/dist/surrender-pending.js +126 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/accept-surrender.js +311 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +158 -0
- package/dist/tools/chat-read-mark.js +179 -0
- package/dist/tools/chat.js +525 -0
- package/dist/tools/check-plan.js +689 -0
- package/dist/tools/commander-check.js +103 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/end-of-game.js +384 -0
- package/dist/tools/game.js +151 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +152 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-details.js +88 -0
- package/dist/tools/map-stats.js +130 -0
- package/dist/tools/map.js +141 -0
- package/dist/tools/my-games.js +193 -0
- package/dist/tools/notifications.js +484 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +163 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/past-games.js +94 -0
- package/dist/tools/picks.js +305 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +445 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +257 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender-pending.js +74 -0
- package/dist/tools/surrender.js +247 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +178 -0
- package/dist/tools/turn.js +2825 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +300 -0
- package/dist/tools/write-kit.js +164 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +577 -0
- package/dist/version.js +4 -0
- package/manifest.json +194 -4
- package/mint.yaml +106 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +1096 -21
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
// The war.app client bundle, fetched at runtime and cached — never vendored.
|
|
2
|
+
//
|
|
3
|
+
// A war.app page loads the client as `<script src="https://warappcdn.com/js/Release/ujs.js?v=<n>">`.
|
|
4
|
+
// The bundle's generated readers are the authority on every wire class layout, and those
|
|
5
|
+
// layouts (and the minified names) change between client releases, so this module:
|
|
6
|
+
// 1. fetches a war.app page and discovers the current bundle URL and version,
|
|
7
|
+
// 2. reuses `<dataDir>/bundle/<version>.<sha256>.js` if present and its bytes still hash to the
|
|
8
|
+
// digest in its name, else downloads and caches it,
|
|
9
|
+
// 3. exposes `readClass(typeName | var, reader)` keyed by the stable registered type
|
|
10
|
+
// name (e.g. `warlight.shared.LatestGameInfo`), evaluated by `BundleInterpreter`.
|
|
11
|
+
// Fetching is injected so the transport (and tests) decide how pages are retrieved.
|
|
12
|
+
//
|
|
13
|
+
// The cache is content-addressed, because several processes share one cache directory. A cached
|
|
14
|
+
// bundle is ONE file whose name carries the SHA-256 of its bytes, written to a private temporary
|
|
15
|
+
// file and renamed into place in one step. So there is no moment at which another process can see a
|
|
16
|
+
// bundle without its digest (and delete it as unverified), and pruning cannot remove half of a pair:
|
|
17
|
+
// there is no pair. A file whose bytes do not hash to its name (a truncated write, a disk error, a
|
|
18
|
+
// later edit) is deleted and never loaded. A cache from before this layout (`<version>.js`, with or
|
|
19
|
+
// without a `<version>.js.sha256` beside it) is never read: it is downloaded again and the old files
|
|
20
|
+
// pruned. Pruning follows #140: an unfinished download (`….tmp-<pid>[-<random>]`) is removed only when
|
|
21
|
+
// this process wrote it, its writer is gone, or it is stale — never while another live process may
|
|
22
|
+
// still rename it into place.
|
|
23
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
24
|
+
import { chmod, mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
|
|
25
|
+
import { join } from 'node:path';
|
|
26
|
+
import { BundleInterpreter, parseBundle, READER_HELPERS, REQUIRED_HELPERS, } from './interp.js';
|
|
27
|
+
/** A page that loads the game client (the homepage does not). */
|
|
28
|
+
const DEFAULT_PAGE_URL = 'https://war.app/MultiPlayer';
|
|
29
|
+
/** The only host the bundle is downloaded from (exactly this host: no subdomain, no port). */
|
|
30
|
+
const BUNDLE_HOST = 'warappcdn.com';
|
|
31
|
+
/** The only path the bundle is downloaded from; its `v` query parameter is the only variable. */
|
|
32
|
+
const BUNDLE_PATH = '/js/Release/ujs.js';
|
|
33
|
+
/** How long the bundle download may take, headers and body together. */
|
|
34
|
+
export const BUNDLE_FETCH_TIMEOUT_MS = 120_000;
|
|
35
|
+
/** The most bytes the bundle download may carry (the bundle is about 17 MB). */
|
|
36
|
+
export const BUNDLE_MAX_BYTES = 64 * 1024 * 1024;
|
|
37
|
+
export class BundleError extends Error {
|
|
38
|
+
kind;
|
|
39
|
+
constructor(kind, message) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.kind = kind;
|
|
42
|
+
this.name = 'BundleError';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const SCRIPT_RE = /<script\b[^>]*?\bsrc\s*=\s*["']([^"']*\/ujs\.js(?:\?[^"']*)?)["']/i;
|
|
46
|
+
const SAFE_VERSION = /^[A-Za-z0-9._-]{1,64}$/;
|
|
47
|
+
/**
|
|
48
|
+
* Find the client bundle's URL and version in a war.app page. The location is pinned:
|
|
49
|
+
* `https://` + exactly {@link BUNDLE_HOST} + exactly {@link BUNDLE_PATH} + `?v=<version>`,
|
|
50
|
+
* nothing else — the page only gets to choose the version.
|
|
51
|
+
*/
|
|
52
|
+
export function discoverBundleUrl(html, pageUrl) {
|
|
53
|
+
const m = SCRIPT_RE.exec(html);
|
|
54
|
+
if (!m)
|
|
55
|
+
throw new BundleError('no-script', `no ujs.js script tag on ${pageUrl}`);
|
|
56
|
+
const src = m[1].replace(/&/g, '&');
|
|
57
|
+
const url = new URL(src, pageUrl);
|
|
58
|
+
if (url.protocol !== 'https:')
|
|
59
|
+
throw new BundleError('bad-url', `bundle URL is not https: ${url.href}`);
|
|
60
|
+
if (url.host !== BUNDLE_HOST || url.username || url.password) {
|
|
61
|
+
throw new BundleError('bad-url', `bundle host not allowed: ${url.host} (only ${BUNDLE_HOST})`);
|
|
62
|
+
}
|
|
63
|
+
if (url.pathname !== BUNDLE_PATH) {
|
|
64
|
+
throw new BundleError('bad-url', `bundle path not allowed: ${url.pathname} (only ${BUNDLE_PATH})`);
|
|
65
|
+
}
|
|
66
|
+
if (url.hash)
|
|
67
|
+
throw new BundleError('bad-url', 'bundle URL must not carry a fragment');
|
|
68
|
+
const keys = [...url.searchParams.keys()];
|
|
69
|
+
if (keys.some((k) => k !== 'v') || keys.length > 1) {
|
|
70
|
+
throw new BundleError('bad-url', `bundle URL query must be only ?v=<version>: ${url.search}`);
|
|
71
|
+
}
|
|
72
|
+
const version = url.searchParams.get('v');
|
|
73
|
+
if (version === null)
|
|
74
|
+
throw new BundleError('bad-version', 'bundle URL carries no version (?v=)');
|
|
75
|
+
if (!SAFE_VERSION.test(version) || version === '.' || version === '..') {
|
|
76
|
+
throw new BundleError('bad-version', `bundle version is not a safe file name: ${JSON.stringify(version)}`);
|
|
77
|
+
}
|
|
78
|
+
return { url: `https://${BUNDLE_HOST}${BUNDLE_PATH}?v=${version}`, version };
|
|
79
|
+
}
|
|
80
|
+
/** A loaded bundle: reads wire classes by stable type name. */
|
|
81
|
+
export class WarappBundle {
|
|
82
|
+
version;
|
|
83
|
+
interp;
|
|
84
|
+
/** Loaded from the cache because the current version could not be looked up. */
|
|
85
|
+
fallback = false;
|
|
86
|
+
constructor(src, version, opts = {}) {
|
|
87
|
+
this.version = version;
|
|
88
|
+
this.interp = new BundleInterpreter(parseBundle(src), opts);
|
|
89
|
+
// The built-in reader helpers are pinned to one client release while the bundle floats:
|
|
90
|
+
// refuse a bundle whose own helpers read differently, rather than decode it wrongly (#131).
|
|
91
|
+
this.dialectCheck = this.interp.verifyDialect();
|
|
92
|
+
if (this.dialectCheck.mismatched.length) {
|
|
93
|
+
throw new BundleError('dialect-mismatch', `war.app's client bundle ${version} reads ${this.dialectCheck.mismatched.join(', ')} differently from this ` +
|
|
94
|
+
"server's built-in readers; the client changed and this server needs an update to read it.");
|
|
95
|
+
}
|
|
96
|
+
// The count, flag and byte helpers decode every army count, fog flag and unit count: one this
|
|
97
|
+
// 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));
|
|
99
|
+
if (unverifiedRequired.length) {
|
|
100
|
+
throw new BundleError('dialect-unverified', `war.app's client bundle ${version} defines ${unverifiedRequired.join(', ')} in a way this server cannot check ` +
|
|
101
|
+
`(${unverifiedRequired.map((k) => this.dialectCheck.reasons?.[k] ?? 'unverified').join('; ')}); those read every ` +
|
|
102
|
+
'army count, so the board is not decoded rather than risk a wrong one. The client changed and this server needs an update.');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** The built-in reader helpers checked against this bundle's own definitions at load. */
|
|
106
|
+
dialectCheck;
|
|
107
|
+
/** What this bundle's decoding rests on, for the tools to show (#148). */
|
|
108
|
+
report() {
|
|
109
|
+
const { verified, unverified, reasons } = this.dialectCheck;
|
|
110
|
+
return {
|
|
111
|
+
bundleVersion: this.version,
|
|
112
|
+
fallback: this.fallback,
|
|
113
|
+
helpers: { verified: [...verified], unverified: [...unverified], ...(reasons ? { reasons: { ...reasons } } : {}) },
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** Whether a type name is registered in this bundle. */
|
|
117
|
+
has(typeName) {
|
|
118
|
+
return this.interp.bundle.varOf.has(typeName);
|
|
119
|
+
}
|
|
120
|
+
fieldsCache = new Map();
|
|
121
|
+
/** The fields `ownerType`'s reader fills from `fieldType`'s reader, in read order (cached). */
|
|
122
|
+
fieldsReadAs(ownerType, fieldType) {
|
|
123
|
+
const key = `${ownerType}\u0000${fieldType}`;
|
|
124
|
+
let out = this.fieldsCache.get(key);
|
|
125
|
+
if (!out) {
|
|
126
|
+
out = this.interp.fieldsReadAs(ownerType, fieldType);
|
|
127
|
+
this.fieldsCache.set(key, out);
|
|
128
|
+
}
|
|
129
|
+
return [...out];
|
|
130
|
+
}
|
|
131
|
+
/** Read one instance of a class, by registered type name (or minified var); `budget` spans several reads. */
|
|
132
|
+
readClass(typeNameOrVar, reader, budget) {
|
|
133
|
+
return this.interp.readClass(typeNameOrVar, reader, budget);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** A cached bundle: `<version>.<sha256 of its bytes>.js`. */
|
|
137
|
+
const BUNDLE_FILE = /^([A-Za-z0-9._-]{1,64})\.([0-9a-f]{64})\.js$/;
|
|
138
|
+
/** A cache file of the earlier layouts, never read, only pruned: `<version>.js` and `<version>.js.sha256`. */
|
|
139
|
+
const LEGACY_FILE = /^[A-Za-z0-9._-]{1,64}\.js(?:\.sha256)?$/;
|
|
140
|
+
/**
|
|
141
|
+
* A write that never finished: `<version>[.<sha256>].js[.sha256].tmp-<pid>`, optionally followed by
|
|
142
|
+
* `-<random>` (what {@link writePrivateAtomic} writes; the shorter forms are the earlier layouts').
|
|
143
|
+
*/
|
|
144
|
+
const PARTIAL_FILE = /^[A-Za-z0-9._-]{1,64}(?:\.[0-9a-f]{64})?\.js(?:\.sha256)?\.tmp-(\d+)(?:-[0-9a-f]+)?$/;
|
|
145
|
+
/** The cache file name of `version` with these bytes' digest. */
|
|
146
|
+
const bundleName = (version, digest) => `${version}.${digest}.js`;
|
|
147
|
+
/** A partial download older than this is abandoned, whoever wrote it (a pid can be reused). */
|
|
148
|
+
const STALE_PARTIAL_MS = 10 * 60_000;
|
|
149
|
+
/** Whether process `pid` is running (EPERM: it exists, owned by someone else). */
|
|
150
|
+
function alive(pid) {
|
|
151
|
+
try {
|
|
152
|
+
process.kill(pid, 0);
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
catch (e) {
|
|
156
|
+
return e.code === 'EPERM';
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** This process's unfinished writes (temporary files not yet renamed into place). */
|
|
160
|
+
const writing = new Set();
|
|
161
|
+
/**
|
|
162
|
+
* A partial download may be pruned when this process wrote it and is no longer writing it, its
|
|
163
|
+
* writer is gone, or it is stale; never while a live process — another one, or a concurrent load
|
|
164
|
+
* in this one — may still rename it into place (#140).
|
|
165
|
+
*/
|
|
166
|
+
async function abandoned(file, pid) {
|
|
167
|
+
if (pid === process.pid)
|
|
168
|
+
return !writing.has(file);
|
|
169
|
+
if (!alive(pid))
|
|
170
|
+
return true;
|
|
171
|
+
try {
|
|
172
|
+
return Date.now() - (await stat(file)).mtimeMs > STALE_PARTIAL_MS;
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Delete every cached bundle but `keep` (each is ~16 MB, one per client release), every file of an
|
|
180
|
+
* earlier cache layout and any abandoned unfinished download. Best effort: never throws.
|
|
181
|
+
*/
|
|
182
|
+
async function pruneBundles(dir, keep) {
|
|
183
|
+
try {
|
|
184
|
+
for (const name of await readdir(dir)) {
|
|
185
|
+
if (name === keep)
|
|
186
|
+
continue;
|
|
187
|
+
const partial = PARTIAL_FILE.exec(name);
|
|
188
|
+
if (!partial && !BUNDLE_FILE.test(name) && !LEGACY_FILE.test(name))
|
|
189
|
+
continue;
|
|
190
|
+
if (partial && !(await abandoned(join(dir, name), Number(partial[1]))))
|
|
191
|
+
continue;
|
|
192
|
+
await unlink(join(dir, name)).catch(() => undefined);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
// Nothing to prune.
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** Cached bundles (of `version`, when given), newest (by modification time) first. */
|
|
200
|
+
async function cachedNewestFirst(dir, version) {
|
|
201
|
+
const found = [];
|
|
202
|
+
try {
|
|
203
|
+
for (const name of await readdir(dir)) {
|
|
204
|
+
const m = BUNDLE_FILE.exec(name);
|
|
205
|
+
if (!m || (version !== undefined && m[1] !== version))
|
|
206
|
+
continue;
|
|
207
|
+
const file = join(dir, name);
|
|
208
|
+
try {
|
|
209
|
+
found.push({ version: m[1], digest: m[2], name, file, mtime: (await stat(file)).mtimeMs });
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
// Gone since the listing (pruned by another process).
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return [];
|
|
218
|
+
}
|
|
219
|
+
return found.sort((a, b) => b.mtime - a.mtime).map(({ mtime: _, ...c }) => c);
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* The newest cached bundle (of `version`, when given) that passes {@link readVerified} (the digest in
|
|
223
|
+
* its name and the content check), or undefined. A copy that fails is deleted by that check, never loaded.
|
|
224
|
+
*/
|
|
225
|
+
async function newestVerified(dir, version) {
|
|
226
|
+
for (const c of await cachedNewestFirst(dir, version)) {
|
|
227
|
+
const src = await readVerified(c.file, c.digest);
|
|
228
|
+
if (src !== null)
|
|
229
|
+
return { version: c.version, name: c.name, src };
|
|
230
|
+
}
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
/** The content check: a client bundle registers its classes as `W["<type name>"]=<var>;`. */
|
|
234
|
+
const looksLikeBundle = (src) => /W\["[\w.$]+"\]=[\w$]+;/.test(src);
|
|
235
|
+
const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
236
|
+
/**
|
|
237
|
+
* Create `dir` (and missing parents) `0700`; when it already exists with group/other bits
|
|
238
|
+
* and this process owns it, tighten it to `0700` (a `mkdir` mode never changes an existing
|
|
239
|
+
* directory). No-op on Windows, which has no POSIX modes.
|
|
240
|
+
*/
|
|
241
|
+
async function ensurePrivateDir(dir) {
|
|
242
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
243
|
+
if (process.platform === 'win32' || typeof process.getuid !== 'function')
|
|
244
|
+
return;
|
|
245
|
+
const st = await stat(dir);
|
|
246
|
+
if ((st.mode & 0o077) !== 0 && st.uid === process.getuid())
|
|
247
|
+
await chmod(dir, 0o700);
|
|
248
|
+
}
|
|
249
|
+
/** Write `data` to `file` `0600` through a fresh temporary file and a rename. */
|
|
250
|
+
async function writePrivateAtomic(file, data) {
|
|
251
|
+
const tmp = `${file}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`;
|
|
252
|
+
writing.add(tmp);
|
|
253
|
+
try {
|
|
254
|
+
await writeFile(tmp, data, { mode: 0o600, flag: 'wx' });
|
|
255
|
+
await rename(tmp, file);
|
|
256
|
+
}
|
|
257
|
+
catch (e) {
|
|
258
|
+
await rm(tmp, { force: true });
|
|
259
|
+
throw e;
|
|
260
|
+
}
|
|
261
|
+
finally {
|
|
262
|
+
writing.delete(tmp);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* The cached bundle's text when its bytes still hash to `digest` (the one in its name) and it still
|
|
267
|
+
* passes the content check; `null` (gone, or the copy was rejected and deleted).
|
|
268
|
+
*
|
|
269
|
+
* This guards against later corruption of, or tampering with, the cache — a truncated write,
|
|
270
|
+
* a disk error, or anything that rewrites the file after it was downloaded — so one bad copy
|
|
271
|
+
* cannot persist across restarts. It is trust on first download: it does not protect against
|
|
272
|
+
* a malicious first download (the digest is computed from what was received), which only the
|
|
273
|
+
* pinned location and the interpreter's own hardening limit. Deleting a rejected copy can race
|
|
274
|
+
* only with another process renaming a good copy of the same bytes to the same name; the cost is
|
|
275
|
+
* one extra download, never an unverified load.
|
|
276
|
+
*/
|
|
277
|
+
async function readVerified(file, digest) {
|
|
278
|
+
let bytes;
|
|
279
|
+
try {
|
|
280
|
+
bytes = await readFile(file);
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
const src = bytes.toString('utf8');
|
|
286
|
+
if (sha256(bytes) === digest && looksLikeBundle(src))
|
|
287
|
+
return src;
|
|
288
|
+
await rm(file, { force: true });
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
/** Discover, fetch (or reuse the verified cached copy of) and load the current client bundle. */
|
|
292
|
+
export async function loadBundle(opts) {
|
|
293
|
+
const pageUrl = opts.pageUrl ?? DEFAULT_PAGE_URL;
|
|
294
|
+
const dir = join(opts.dataDir, 'bundle');
|
|
295
|
+
let source;
|
|
296
|
+
try {
|
|
297
|
+
source = discoverBundleUrl(await opts.fetchText(pageUrl), pageUrl);
|
|
298
|
+
}
|
|
299
|
+
catch (e) {
|
|
300
|
+
// The page naming the current version could not be read (a frozen tab, a signed-out page):
|
|
301
|
+
// 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;
|
|
309
|
+
}
|
|
310
|
+
const { url, version } = source;
|
|
311
|
+
const cached = await newestVerified(dir, version);
|
|
312
|
+
let src;
|
|
313
|
+
let name;
|
|
314
|
+
if (cached) {
|
|
315
|
+
({ src, name } = cached);
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
src = await opts.fetchText(url);
|
|
319
|
+
if (!looksLikeBundle(src)) {
|
|
320
|
+
throw new BundleError('bad-bundle', `${url} does not look like the war.app client bundle`);
|
|
321
|
+
}
|
|
322
|
+
await ensurePrivateDir(opts.dataDir);
|
|
323
|
+
await ensurePrivateDir(dir);
|
|
324
|
+
const bytes = Buffer.from(src, 'utf8');
|
|
325
|
+
// 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);
|
|
328
|
+
}
|
|
329
|
+
const bundle = new WarappBundle(src, version, opts.interp);
|
|
330
|
+
await pruneBundles(dir, name);
|
|
331
|
+
return bundle;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* How long a fallback bundle is used, or a refused (dialect-mismatch) bundle is remembered, before
|
|
335
|
+
* the current version is looked up again.
|
|
336
|
+
*/
|
|
337
|
+
const FALLBACK_RETRY_MS = 5 * 60_000;
|
|
338
|
+
/**
|
|
339
|
+
* Loads the bundle once per process; a failed load is retried on the next call, except a bundle
|
|
340
|
+
* refused as a dialect mismatch, which is retried after {@link FALLBACK_RETRY_MS}.
|
|
341
|
+
*/
|
|
342
|
+
export class BundleProvider {
|
|
343
|
+
opts;
|
|
344
|
+
pending = null;
|
|
345
|
+
constructor(opts) {
|
|
346
|
+
this.opts = opts;
|
|
347
|
+
}
|
|
348
|
+
fallbackUntil;
|
|
349
|
+
get() {
|
|
350
|
+
const now = this.opts.now ?? Date.now;
|
|
351
|
+
if (this.pending && this.fallbackUntil !== undefined && now() >= this.fallbackUntil)
|
|
352
|
+
this.pending = null;
|
|
353
|
+
if (!this.pending) {
|
|
354
|
+
this.fallbackUntil = undefined;
|
|
355
|
+
const p = loadBundle(this.opts);
|
|
356
|
+
this.pending = p;
|
|
357
|
+
p.then((b) => {
|
|
358
|
+
// A cached copy stands in only until the version can be looked up again.
|
|
359
|
+
if (b.fallback && this.pending === p)
|
|
360
|
+
this.fallbackUntil = now() + FALLBACK_RETRY_MS;
|
|
361
|
+
}, (e) => {
|
|
362
|
+
if (this.pending !== p)
|
|
363
|
+
return;
|
|
364
|
+
// A bundle this server cannot read stays unreadable: remember the refusal for a while
|
|
365
|
+
// 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')) {
|
|
367
|
+
this.fallbackUntil = now() + FALLBACK_RETRY_MS;
|
|
368
|
+
}
|
|
369
|
+
else
|
|
370
|
+
this.pending = null;
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
return this.pending;
|
|
374
|
+
}
|
|
375
|
+
}
|