@chrischall/warapp-mcp 0.0.0 → 0.1.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.
Files changed (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,348 @@
1
+ #!/usr/bin/env node
2
+ // scout.mjs — war.app Profile / CommonGames HTML on stdin → allowlisted JSON on stdout.
3
+ //
4
+ // fpx get "https://war.app/Profile?p=$PLAYER" -p warapp | node scout.mjs profile
5
+ // fpx get "https://war.app/CommonGames?p=$PLAYER" -p warapp | node scout.mjs common
6
+ //
7
+ // Dependency-free twin of warapp-mcp's src/scout.ts (its tests pin parity).
8
+ // Both pages also carry personal details (e.g. a self-reported location): this
9
+ // script projects an ALLOWLIST and never prints anything else. Missing blocks
10
+ // (a new player has no ranked games) are null, never an error.
11
+ // A page over MAX_PAGE_CHARS is not parsed, every pattern runs on a bounded
12
+ // window, and each stat is read only from its own block (never from the name,
13
+ // tagline or location the player writes); a value of the wrong shape is null.
14
+ // The anchor is war.app's label markup, which a player cannot write: Played is
15
+ // the one whole block (div, p, li or td) "Played in …" straight after a run of label rows, Level the
16
+ // block straight before them, Last seen and Booted the blocks straight after
17
+ // Played (src/scout.ts's header says what that relies on).
18
+ //
19
+ // Exit codes: 0 ok · 1 usage · 2 no HTML on stdin (the fetch before it failed).
20
+
21
+ /**
22
+ * Larger than any real Profile or CommonGames page (tens of kilobytes). A bigger
23
+ * page is not parsed: every block reads as missing.
24
+ */
25
+ const MAX_PAGE_CHARS = 1 << 20;
26
+ /** Text longer than this is never a stat block, a label or a title. */
27
+ const MAX_NODE_CHARS = 1024;
28
+ /** A tag is classified from at most this many characters. */
29
+ const MAX_TAG_CHARS = 512;
30
+ /** How far a common-games row's next cell may be from the last. */
31
+ const CELL_WINDOW = 2048;
32
+ /** Label rows (Location, Joined, …) that may sit between the Level and Played blocks. */
33
+ const MAX_LABEL_ROWS = 16;
34
+ const MAX_FORMATS = 64;
35
+ /** More common games than anyone plays against one player; the rest of a bigger page is dropped. */
36
+ const MAX_GAMES = 1000;
37
+
38
+ const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
39
+
40
+ function decodeEntities(s) {
41
+ return s.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{1,8});/gi, (m, e) => {
42
+ if (e[0] === '#') {
43
+ const code = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
44
+ return Number.isInteger(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m;
45
+ }
46
+ return ENTITIES[e.toLowerCase()] ?? m;
47
+ });
48
+ }
49
+
50
+ const clean = (s) => decodeEntities(s).replace(/\s+/g, ' ').trim();
51
+
52
+ /** Text of a (bounded) HTML fragment: tags dropped, entities decoded, whitespace collapsed. */
53
+ const textOf = (html) => clean(html.replace(/<[^<>]*>/g, ' '));
54
+
55
+ // Values are validated by shape: an integer (thousands separators allowed), a percentage.
56
+ const INT = '(\\d{1,3}(?:,\\d{3})+|\\d{1,12})';
57
+ const PCT = '(\\d{1,3}(?:\\.\\d{1,2})?)';
58
+ const int = (s) => {
59
+ const n = Number(s.replace(/,/g, ''));
60
+ return Number.isSafeInteger(n) ? n : null;
61
+ };
62
+ const pct = (s) => {
63
+ const n = Number(s);
64
+ return Number.isFinite(n) && n >= 0 && n <= 100 ? n : null;
65
+ };
66
+ /** Every value of a block, or null when any of them has the wrong shape. */
67
+ const values = (v) => (v.every((x) => x !== null) ? v : null);
68
+
69
+ const LEVEL = new RegExp(`^Level ${INT}$`);
70
+ const PLAYED = new RegExp(`^Played in ${INT} multi-player games \\(${PCT}% real-time\\)$`);
71
+ // war.app's own phrasing only, e.g. "less than 15 minutes ago", "3 days ago".
72
+ const SEEN = /^Last seen ((?:less than )?\d{1,4} (?:second|minute|hour|day|week|month|year)s? ago)$/i;
73
+ const SEEN_BLOCK = /^Last seen\b/i;
74
+ const PLAYED_BLOCK = /^Played in\b/i;
75
+ const BOOTED = new RegExp(`^Booted ${INT} times? \\(${PCT}% of their last 100\\)$`);
76
+ const RANKED = new RegExp(`^${INT} ranked games \\(${INT} / ${INT}\\)$`);
77
+ const FORMAT_LABEL = /^([^:]{1,60}):$/;
78
+ const FORMAT_ROW = new RegExp(`^${INT} ?/ ?${INT} ?\\( ?${PCT} ?% ?\\)$`);
79
+ const MUTED = /^<font\b[^>]*\bclass\s*=\s*["']?text-muted\b/i;
80
+ const BLOCK_OPEN = /^<(div|p|li|td)\b/i;
81
+ const BLOCK_CLOSE = /^<\/(div|p|li|td)\s*>/i;
82
+
83
+ /**
84
+ * The non-empty text nodes of `html` from `from` on, in one linear pass. Script and
85
+ * style bodies are skipped; an over-long node keeps its place but matches nothing.
86
+ */
87
+ function textNodes(html, from) {
88
+ const nodes = [];
89
+ let open = '';
90
+ let pos = from;
91
+ while (pos < html.length) {
92
+ const lt = html.indexOf('<', pos);
93
+ const end = lt < 0 ? html.length : lt;
94
+ const raw = html.slice(pos, end);
95
+ const text = raw.length > MAX_NODE_CHARS ? '\u0000' : clean(raw);
96
+ const gt = lt < 0 ? -1 : html.indexOf('>', lt + 1);
97
+ const close = gt < 0 ? '' : html.slice(lt, Math.min(gt + 1, lt + MAX_TAG_CHARS));
98
+ if (text) nodes.push({ text, open, close });
99
+ if (gt < 0) break;
100
+ open = close;
101
+ pos = gt + 1;
102
+ const body = /^<(script|style)\b/i.exec(close);
103
+ if (body && !close.endsWith('/>')) {
104
+ const shut = new RegExp(`</${body[1]}\\s*>`, 'gi');
105
+ shut.lastIndex = pos;
106
+ const m = shut.exec(html);
107
+ if (!m) break;
108
+ pos = m.index;
109
+ }
110
+ }
111
+ return nodes;
112
+ }
113
+
114
+ /** A label in war.app's own markup, `<font class="text-muted">LABEL</font>`. */
115
+ const isMuted = (n) =>
116
+ !!n && MUTED.test(n.open) && /^<\/font\s*>/i.test(n.close);
117
+ const isLabel = (n) => isMuted(n) && n.text.endsWith(':');
118
+ /** A label's value: the text straight after the label's `</font>`, never a block of its own. */
119
+ const isLabelValue = (label, n) =>
120
+ isLabel(label) && !!n && /^<\/font\s*>/i.test(n.open);
121
+ /** A whole block: all the text of a `<div>` (or p, li, td) with no tag inside it. */
122
+ const isBlock = (n) => {
123
+ const o = n ? BLOCK_OPEN.exec(n.open) : null;
124
+ const c = o ? BLOCK_CLOSE.exec(n.close) : null;
125
+ return !!c && c[1].toLowerCase() === o[1].toLowerCase();
126
+ };
127
+
128
+ /** The first match of `re` (anchored, not global) in the `window` characters from `from`, as offsets. */
129
+ function near(html, from, re, window = CELL_WINDOW) {
130
+ const m = re.exec(html.slice(from, from + window));
131
+ return m ? { start: from + m.index, end: from + m.index + m[0].length } : null;
132
+ }
133
+
134
+ const EMPTY_PROFILE = {
135
+ name: null,
136
+ level: null,
137
+ multiplayerGames: null,
138
+ realTimePct: null,
139
+ lastSeen: null,
140
+ boots: null,
141
+ bootRatePct: null,
142
+ ranked: null,
143
+ formats: [],
144
+ };
145
+
146
+ function parseProfile(html) {
147
+ if (html.length > MAX_PAGE_CHARS) return { ...EMPTY_PROFILE, formats: [] };
148
+
149
+ // The name comes from the title only; the stats are read after it and after the
150
+ // name heading, both of which the player writes.
151
+ let name = null;
152
+ let start = 0;
153
+ const title = /<title\b[^<>]{0,200}>/i.exec(html);
154
+ if (title) {
155
+ const from = title.index + title[0].length;
156
+ const shut = near(html, from, /<\/title\s*>/i, MAX_NODE_CHARS);
157
+ if (shut) {
158
+ const titleText = textOf(html.slice(from, shut.start));
159
+ const nameMatch = / - War\.app\b/i.exec(titleText);
160
+ name = nameMatch && nameMatch.index > 0 ? titleText.slice(0, nameMatch.index).trim() : null;
161
+ start = shut.end;
162
+ }
163
+ }
164
+ const heading = /<\/h1\s*>/i.exec(html.slice(start));
165
+ if (heading) start += heading.index + heading[0].length;
166
+
167
+ const nodes = textNodes(html, start);
168
+ const at = (i) => nodes[i]?.text ?? '';
169
+ const isValue = (i) => isLabelValue(nodes[i - 1], nodes[i]);
170
+ /** The node just before the run of label rows that ends right before node `i`; null when no label row is there. */
171
+ const beforeLabels = (i) => {
172
+ let j = i - 1;
173
+ for (let rows = 0; j >= 0 && rows < MAX_LABEL_ROWS; rows++) {
174
+ if (isLabel(nodes[j])) j -= 1;
175
+ else if (isValue(j)) j -= 2;
176
+ else break;
177
+ }
178
+ return j < i - 1 ? j : null;
179
+ };
180
+
181
+ // Played: the one whole block worded "Played in …" that follows war.app's label rows
182
+ // (Location, Joined, …) — the player cannot write that markup, only the text in it.
183
+ // Two such blocks, or one of the wrong shape, read as null, and so does everything
184
+ // anchored to it: never an imitation from elsewhere on the page.
185
+ const candidates = [];
186
+ for (let i = 0; i < nodes.length && candidates.length < 2; i++) {
187
+ if (PLAYED_BLOCK.test(at(i)) && isBlock(nodes[i]) && beforeLabels(i) !== null) candidates.push(i);
188
+ }
189
+ let p = -1;
190
+ let played = null;
191
+ if (candidates.length === 1) {
192
+ const m = PLAYED.exec(at(candidates[0]));
193
+ played = m ? values([int(m[1]), pct(m[2])]) : null;
194
+ if (played) p = candidates[0];
195
+ }
196
+
197
+ // Level: the whole block just before those label rows.
198
+ let level = null;
199
+ if (p >= 0) {
200
+ const j = beforeLabels(p);
201
+ const m = j >= 0 && isBlock(nodes[j]) ? LEVEL.exec(at(j)) : null;
202
+ level = m ? int(m[1]) : null;
203
+ }
204
+
205
+ // Last seen, then Booted: the whole blocks right after Played.
206
+ let lastSeen = null;
207
+ let booted = null;
208
+ if (p >= 0) {
209
+ let k = p + 1;
210
+ if (SEEN_BLOCK.test(at(k)) && isBlock(nodes[k])) {
211
+ lastSeen = SEEN.exec(at(k))?.[1] ?? null;
212
+ k++;
213
+ }
214
+ const m = isBlock(nodes[k]) ? BOOTED.exec(at(k)) : null;
215
+ booted = m ? values([int(m[1]), pct(m[2])]) : null;
216
+ }
217
+
218
+ // Ranked: war.app's `Completed` label and its value, then the per-format label rows.
219
+ let ranked = null;
220
+ const formats = [];
221
+ for (let i = 0; i < nodes.length - 1 && !ranked; i++) {
222
+ if (!isMuted(nodes[i]) || at(i) !== 'Completed') continue;
223
+ const m = RANKED.exec(at(i + 1));
224
+ const v = m ? values([int(m[1]), int(m[2]), int(m[3])]) : null;
225
+ if (!v) continue;
226
+ ranked = { completed: v[0], wins: v[1], games: v[2] };
227
+ for (let r = i + 2; r + 1 < nodes.length && formats.length < MAX_FORMATS; r += 2) {
228
+ const label = isLabel(nodes[r]) ? FORMAT_LABEL.exec(at(r)) : null;
229
+ const row = label ? FORMAT_ROW.exec(at(r + 1)) : null;
230
+ const rv = row ? values([int(row[1]), int(row[2]), pct(row[3])]) : null;
231
+ if (!rv) break;
232
+ formats.push({ format: label[1].trim(), wins: rv[0], games: rv[1], pct: rv[2] });
233
+ }
234
+ }
235
+
236
+ return {
237
+ // A page with neither a level nor games played is not a profile (signed out, no such player).
238
+ name: level !== null || played ? name : null,
239
+ level,
240
+ multiplayerGames: played ? played[0] : null,
241
+ realTimePct: played ? played[1] : null,
242
+ lastSeen,
243
+ boots: booted ? booted[0] : null,
244
+ bootRatePct: booted ? booted[1] : null,
245
+ ranked,
246
+ formats,
247
+ };
248
+ }
249
+
250
+ /** A side of more than one player ("2v2", "3v3v3", "Teams"): they may have been my teammate. */
251
+ function isTeamGame(teams) {
252
+ if (/\bteams?\b/i.test(teams)) return true;
253
+ const sides = /^\s*\d+(?:\s*v\s*\d+)+\s*$/i.test(teams) ? teams.split(/v/i).map((x) => Number(x.trim())) : [];
254
+ return sides.some((n) => n > 1);
255
+ }
256
+
257
+ /** My state in a common game, as a win, a loss, still going, or none of those (declined, …). */
258
+ function outcomeOf(state) {
259
+ if (/^won\b/i.test(state)) return 'win';
260
+ if (/eliminated|booted|surrender|lost/i.test(state)) return 'loss';
261
+ if (/playing|invited|waiting/i.test(state)) return 'inProgress';
262
+ return undefined;
263
+ }
264
+
265
+ const HEADER = new RegExp(`^\\s*${INT}\\s+Common Games?\\b`, 'i');
266
+ const GAME_LINK = /(?:^|\/)MultiPlayer\?GameID=(\d{1,12})(?!\d)/i;
267
+
268
+ /** One table row from the game link's tag end at `from`: its four cells and where it ends. */
269
+ function rowAt(html, from) {
270
+ const a = near(html, from, /<\/a\s*>/i);
271
+ if (!a) return null;
272
+ const cells = [html.slice(from, a.start)];
273
+ const first = near(html, a.end, /^\s*<\/td\s*>/i, MAX_TAG_CHARS);
274
+ if (!first) return null;
275
+ let pos = first.end;
276
+ for (let c = 0; c < 3; c++) {
277
+ const td = near(html, pos, /^\s*<td\b[^<>]{0,200}>/i, MAX_TAG_CHARS);
278
+ if (!td) return null;
279
+ const shut = near(html, td.end, /<\/td\s*>/i);
280
+ if (!shut) return null;
281
+ cells.push(html.slice(td.end, shut.start));
282
+ pos = shut.end;
283
+ }
284
+ return { cells, end: pos };
285
+ }
286
+
287
+ function parseCommonGames(html) {
288
+ const games = [];
289
+ let count = null;
290
+ if (html.length <= MAX_PAGE_CHARS) {
291
+ const h1 = /<h1\b[^<>]{0,200}>/gi;
292
+ for (let m = h1.exec(html); m && count === null; m = h1.exec(html)) {
293
+ const head = HEADER.exec(html.slice(h1.lastIndex, h1.lastIndex + 256));
294
+ if (head) count = int(head[1]);
295
+ }
296
+ const link = /<a\b[^<>]{0,500}>/gi;
297
+ for (let m = link.exec(html); m && games.length < MAX_GAMES; m = link.exec(html)) {
298
+ const href = /\bhref\s*=\s*(?:"([^"]{0,300})"|'([^']{0,300})'|([^\s"'>]{1,300}))/i.exec(m[0]);
299
+ const id = href ? GAME_LINK.exec(href[1] ?? href[2] ?? href[3]) : null;
300
+ const row = id ? rowAt(html, link.lastIndex) : null;
301
+ if (!id || !row) continue;
302
+ const [name, started, teams, state] = row.cells.map(textOf);
303
+ games.push({ id: Number(id[1]), name, started, teams, myState: state });
304
+ link.lastIndex = row.end;
305
+ }
306
+ }
307
+ // Wins and losses count games without teams only; team games are `teamGames`.
308
+ const tally = { win: 0, loss: 0, inProgress: 0 };
309
+ let teamGames = 0;
310
+ for (const g of games) {
311
+ const o = outcomeOf(g.myState);
312
+ const team = isTeamGame(g.teams);
313
+ if (team) teamGames++;
314
+ if (o === 'inProgress' || (o && !team)) tally[o]++;
315
+ }
316
+ return {
317
+ count: count ?? (games.length ? games.length : null),
318
+ wins: tally.win,
319
+ losses: tally.loss,
320
+ inProgress: tally.inProgress,
321
+ teamGames,
322
+ games,
323
+ };
324
+ }
325
+
326
+ const PARSERS = { profile: parseProfile, common: parseCommonGames };
327
+
328
+ // A reader that stops early (`| head`) closes the pipe: that is not an error.
329
+ process.stdout.on('error', (e) => {
330
+ if (e && e.code === 'EPIPE') process.exit(0);
331
+ throw e;
332
+ });
333
+
334
+ const args = process.argv.slice(2);
335
+ const parse = args.length === 1 && Object.hasOwn(PARSERS, args[0]) ? PARSERS[args[0]] : undefined;
336
+ if (!parse) {
337
+ process.stderr.write('usage: node scout.mjs profile|common < page.html\n');
338
+ process.exit(1);
339
+ }
340
+
341
+ let html = '';
342
+ process.stdin.setEncoding('utf8');
343
+ for await (const chunk of process.stdin) html += chunk;
344
+ if (!html.trim()) {
345
+ process.stderr.write('scout: no HTML on stdin (did the fpx call before it fail?)\n');
346
+ process.exit(2);
347
+ }
348
+ process.stdout.write(`${JSON.stringify(parse(html), null, 2)}\n`);
@@ -13,7 +13,15 @@
13
13
  # on curl's command line (the body goes in on stdin) and never printed — an
14
14
  # upstream error has both scrubbed before it reaches stderr.
15
15
  #
16
- # Return codes: 0 ok · 1 usage (bad game id) · 2 no credentials ·
16
+ # Extra Param=value arguments are checked against a conservative character set, and
17
+ # curl runs with URL globbing off, reads no config file (-q, which must come first),
18
+ # speaks only the checked origin's protocol and follows no redirect, so every request
19
+ # of a call (one, or two when curl's single retry answers a transient error) goes to
20
+ # the checked origin and nowhere else. A loopback test origin bypasses every proxy;
21
+ # war.app keeps the environment's proxy settings.
22
+ #
23
+ # Return codes: 0 ok · 1 usage (bad game id, bad extra argument, refused
24
+ # WARAPP_BASE_URL) · 2 no credentials ·
17
25
  # 3 Auth failed (wrong email/token) · 4 no such game · 5 anything else
18
26
  # (network, HTTP error, non-JSON answer, other GameFeed error).
19
27
  #
@@ -22,10 +30,14 @@
22
30
  #
23
31
  # Variable names avoid `path` and `status` (special in zsh).
24
32
 
33
+ # Character classes are spelled out, never ranges: under a UTF-8 locale some shells
34
+ # (macOS /bin/bash 3.2) match [A-Za-z0-9] by collation order, letting accented and
35
+ # fullwidth letters through. Spelled out, the sets hold ASCII only in every shell and locale.
36
+
25
37
  # _warapp_gameid <id>: a positive whole number below 2^31.
26
38
  _warapp_gameid() {
27
39
  case "${1:-}" in
28
- '' | *[!0-9]* | 0*)
40
+ '' | *[!0123456789]* | 0*)
29
41
  echo "warapp: game id must be a positive whole number, got '${1:-}'" >&2
30
42
  return 1
31
43
  ;;
@@ -36,6 +48,48 @@ _warapp_gameid() {
36
48
  fi
37
49
  }
38
50
 
51
+ # _warapp_base: print the GameFeed origin. WARAPP_BASE_URL is a test seam only: the
52
+ # credentials go in every request, so it is honoured only when it is exactly
53
+ # https://war.app or a loopback stand-in (http://127.0.0.1:<port> or
54
+ # http://localhost:<port>). Anything else is refused before a request is made.
55
+ _warapp_base() {
56
+ local url="${WARAPP_BASE_URL:-https://war.app}" port=''
57
+ case "$url" in
58
+ https://war.app) printf '%s' "$url"; return 0 ;;
59
+ http://127.0.0.1:*) port="${url#http://127.0.0.1:}" ;;
60
+ http://localhost:*) port="${url#http://localhost:}" ;;
61
+ esac
62
+ case "$port" in
63
+ '' | *[!0123456789]*) ;;
64
+ *)
65
+ if [ "${#port}" -le 5 ] && [ "$port" -ge 1 ] && [ "$port" -le 65535 ]; then
66
+ printf '%s' "$url"
67
+ return 0
68
+ fi
69
+ ;;
70
+ esac
71
+ echo "warapp: refusing WARAPP_BASE_URL: it must be https://war.app or http://127.0.0.1:<port> / http://localhost:<port>" >&2
72
+ return 1
73
+ }
74
+
75
+ # _warapp_arg <Name=value>: an extra query parameter. Name is a letter then letters or
76
+ # digits; value is letters, digits, '.', '_' or '-' (possibly empty). Nothing that could
77
+ # change the query, the URL or the shell's reading of it gets through.
78
+ _warapp_arg() {
79
+ local name="${1%%=*}" val="${1#*=}" ok=1
80
+ case "$1" in *=*) ;; *) ok=0 ;; esac
81
+ case "$name" in
82
+ '' | [!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]* | *[!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789]*) ok=0 ;;
83
+ esac
84
+ case "$val" in
85
+ *[!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-]*) ok=0 ;;
86
+ esac
87
+ if [ "$ok" -ne 1 ]; then
88
+ echo "warapp: refusing extra argument: expected Name=value (letters/digits, value also . _ -)" >&2
89
+ return 1
90
+ fi
91
+ }
92
+
39
93
  # _warapp_load: fill the CALLER's local _warapp_email/_warapp_token.
40
94
  _warapp_load() {
41
95
  local file line key val
@@ -73,12 +127,18 @@ _warapp_uri() {
73
127
 
74
128
  # warapp_feed <game-id> [Param=value …]: the raw GameFeed body for one game.
75
129
  # Extra arguments are appended to the query, e.g. GetSettings=true GetMap=false
76
- # GetHistory=true GetChat=true.
130
+ # GetHistory=true GetChat=true (each checked by _warapp_arg; anything else exits 1).
77
131
  warapp_feed() {
78
- local game="${1:-}" query='' arg body rc err _warapp_email _warapp_token
132
+ local game="${1:-}" query='' arg body rc err origin proto noproxy _warapp_email _warapp_token
79
133
  _warapp_gameid "$game" || return 1
80
134
  shift
135
+ origin="$(_warapp_base)" || return 1
136
+ case "$origin" in
137
+ https://*) proto='=https' noproxy="${no_proxy-${NO_PROXY-}}" ;;
138
+ *) proto='=http' noproxy='*' ;;
139
+ esac
81
140
  for arg in "$@"; do
141
+ _warapp_arg "$arg" || return 1
82
142
  query="$query&$arg"
83
143
  done
84
144
  _warapp_load || return 2
@@ -86,10 +146,11 @@ warapp_feed() {
86
146
  printf 'Email=%s&APIToken=%s' \
87
147
  "$(printf '%s' "$_warapp_email" | _warapp_uri)" \
88
148
  "$(printf '%s' "$_warapp_token" | _warapp_uri)" |
89
- curl -sS --fail-with-body --max-time 30 --retry 1 \
149
+ curl -q --globoff --proto "$proto" --max-redirs 0 --noproxy "$noproxy" \
150
+ -sS --fail-with-body --max-time 30 --retry 1 \
90
151
  -H 'Content-Type: application/x-www-form-urlencoded' \
91
152
  --data-binary @- \
92
- "${WARAPP_BASE_URL:-https://war.app}/API/GameFeed?GameID=$game$query"
153
+ "$origin/API/GameFeed?GameID=$game$query"
93
154
  )"
94
155
  rc=$?
95
156
  if [ "$rc" -ne 0 ]; then
@@ -140,7 +201,7 @@ warapp_map() {
140
201
  if [ -r "$dir/game-$game.map" ]; then
141
202
  mapid="$(cat "$dir/game-$game.map")"
142
203
  case "$mapid" in
143
- '' | *[!0-9]*) ;;
204
+ '' | *[!0123456789]*) ;;
144
205
  *)
145
206
  if [ -r "$dir/map-$mapid.json" ]; then
146
207
  cat "$dir/map-$mapid.json"
@@ -154,7 +215,7 @@ warapp_map() {
154
215
  [ "$rc" -eq 0 ] || return "$rc"
155
216
  mapid="$(printf '%s' "$out" | jq -r '.map.id // empty | tostring')"
156
217
  case "$mapid" in
157
- '' | *[!0-9]*)
218
+ '' | *[!0123456789]*)
158
219
  echo "warapp: the response for game $game carries no usable map id" >&2
159
220
  return 5
160
221
  ;;