@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.
Files changed (194) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +211 -9
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/award.js +159 -0
  6. package/dist/analysis/bonuses.js +98 -0
  7. package/dist/analysis/breach.js +62 -0
  8. package/dist/analysis/calibrate.js +239 -0
  9. package/dist/analysis/card-support.js +329 -0
  10. package/dist/analysis/card-threats.js +234 -0
  11. package/dist/analysis/cards-in-effect.js +130 -0
  12. package/dist/analysis/chains.js +59 -0
  13. package/dist/analysis/chokepoints.js +140 -0
  14. package/dist/analysis/combat.js +231 -0
  15. package/dist/analysis/commander-safety.js +149 -0
  16. package/dist/analysis/commitments.js +338 -0
  17. package/dist/analysis/exchange.js +155 -0
  18. package/dist/analysis/finished-game.js +136 -0
  19. package/dist/analysis/game-lessons.js +217 -0
  20. package/dist/analysis/graph.js +82 -0
  21. package/dist/analysis/guard-off.js +54 -0
  22. package/dist/analysis/guess.js +351 -0
  23. package/dist/analysis/headroom.js +241 -0
  24. package/dist/analysis/hold-diff.js +64 -0
  25. package/dist/analysis/how-lost.js +130 -0
  26. package/dist/analysis/index.js +14 -0
  27. package/dist/analysis/local-deploy.js +179 -0
  28. package/dist/analysis/lookahead.js +108 -0
  29. package/dist/analysis/opponent-profile.js +552 -0
  30. package/dist/analysis/opponents.js +1253 -0
  31. package/dist/analysis/outlook.js +695 -0
  32. package/dist/analysis/overrides.js +60 -0
  33. package/dist/analysis/picks.js +1879 -0
  34. package/dist/analysis/plan/after-leftover.js +140 -0
  35. package/dist/analysis/plan/cap-spend.js +242 -0
  36. package/dist/analysis/plan/captures.js +1195 -0
  37. package/dist/analysis/plan/commander.js +236 -0
  38. package/dist/analysis/plan/completed.js +29 -0
  39. package/dist/analysis/plan/conceded-out.js +131 -0
  40. package/dist/analysis/plan/estimates.js +715 -0
  41. package/dist/analysis/plan/guard-off.js +232 -0
  42. package/dist/analysis/plan/holds.js +1631 -0
  43. package/dist/analysis/plan/leftover.js +760 -0
  44. package/dist/analysis/plan/move-order.js +319 -0
  45. package/dist/analysis/plan/orders.js +317 -0
  46. package/dist/analysis/plan/relations.js +702 -0
  47. package/dist/analysis/plan/report.js +672 -0
  48. package/dist/analysis/plan/shared.js +1405 -0
  49. package/dist/analysis/plan/stand-still.js +823 -0
  50. package/dist/analysis/plan/state.js +44 -0
  51. package/dist/analysis/plan/strike.js +1416 -0
  52. package/dist/analysis/plan/targets.js +651 -0
  53. package/dist/analysis/plan/team.js +299 -0
  54. package/dist/analysis/plan/threats.js +1001 -0
  55. package/dist/analysis/plan/transfers.js +328 -0
  56. package/dist/analysis/plan/util.js +5 -0
  57. package/dist/analysis/plan/vacated.js +285 -0
  58. package/dist/analysis/planner.js +2927 -0
  59. package/dist/analysis/player-record.js +144 -0
  60. package/dist/analysis/player.js +268 -0
  61. package/dist/analysis/profile.js +347 -0
  62. package/dist/analysis/relations.js +1030 -0
  63. package/dist/analysis/schedule.js +88 -0
  64. package/dist/analysis/since-last.js +50 -0
  65. package/dist/analysis/static-seats.js +71 -0
  66. package/dist/analysis/stress.js +584 -0
  67. package/dist/analysis/team-brief.js +151 -0
  68. package/dist/analysis/tripwire.js +644 -0
  69. package/dist/analysis/turn-sim.js +259 -0
  70. package/dist/analysis/whereabouts.js +1112 -0
  71. package/dist/board.js +105 -0
  72. package/dist/bundle.js +121082 -36148
  73. package/dist/calibration-source.js +75 -0
  74. package/dist/cards.js +435 -0
  75. package/dist/chat-cursor.js +135 -0
  76. package/dist/chat.js +265 -0
  77. package/dist/client.js +439 -0
  78. package/dist/config.js +62 -0
  79. package/dist/direct/link.js +102 -0
  80. package/dist/direct/session.js +267 -0
  81. package/dist/direct/transport.js +424 -0
  82. package/dist/finished-store.js +357 -0
  83. package/dist/guess-salt.js +65 -0
  84. package/dist/hosted.js +24 -0
  85. package/dist/index.js +33 -0
  86. package/dist/join-color.js +140 -0
  87. package/dist/lessons-store.js +356 -0
  88. package/dist/live.js +287 -0
  89. package/dist/map-details.js +127 -0
  90. package/dist/map-stats.js +160 -0
  91. package/dist/map-store.js +242 -0
  92. package/dist/move-order.js +141 -0
  93. package/dist/my-games.js +218 -0
  94. package/dist/normalize.js +443 -0
  95. package/dist/notifications.js +143 -0
  96. package/dist/open-games.js +537 -0
  97. package/dist/outlook-log.js +165 -0
  98. package/dist/path-lock.js +22 -0
  99. package/dist/pick-list.js +193 -0
  100. package/dist/player-record-store.js +231 -0
  101. package/dist/player-states.js +31 -0
  102. package/dist/profile-store.js +727 -0
  103. package/dist/protocol/bundle.js +375 -0
  104. package/dist/protocol/codec.js +556 -0
  105. package/dist/protocol/decoded.js +12 -0
  106. package/dist/protocol/interp.js +1904 -0
  107. package/dist/protocol/methods.js +615 -0
  108. package/dist/protocol/rpc.js +202 -0
  109. package/dist/push/listener.js +393 -0
  110. package/dist/push/packets.js +66 -0
  111. package/dist/push/socketio.js +333 -0
  112. package/dist/push/websocket.js +179 -0
  113. package/dist/redact.js +62 -0
  114. package/dist/relations-store.js +242 -0
  115. package/dist/replay.js +227 -0
  116. package/dist/scalars.js +28 -0
  117. package/dist/scout.js +346 -0
  118. package/dist/stats.js +291 -0
  119. package/dist/strategy/card-clock.js +185 -0
  120. package/dist/strategy/map-notes.js +128 -0
  121. package/dist/strategy/notes.js +2223 -0
  122. package/dist/surrender-pending.js +126 -0
  123. package/dist/team-cards.js +84 -0
  124. package/dist/team-orders.js +150 -0
  125. package/dist/teams.js +19 -0
  126. package/dist/tools/accept-surrender.js +311 -0
  127. package/dist/tools/award.js +206 -0
  128. package/dist/tools/begin-turn.js +162 -0
  129. package/dist/tools/board.js +77 -0
  130. package/dist/tools/card-advice.js +256 -0
  131. package/dist/tools/card-effects.js +49 -0
  132. package/dist/tools/card-plays.js +434 -0
  133. package/dist/tools/card-support-advice.js +140 -0
  134. package/dist/tools/chat-inbox.js +158 -0
  135. package/dist/tools/chat-read-mark.js +179 -0
  136. package/dist/tools/chat.js +525 -0
  137. package/dist/tools/check-plan.js +689 -0
  138. package/dist/tools/commander-check.js +103 -0
  139. package/dist/tools/commitments.js +216 -0
  140. package/dist/tools/common.js +143 -0
  141. package/dist/tools/diplomacy.js +342 -0
  142. package/dist/tools/end-of-game.js +384 -0
  143. package/dist/tools/game.js +151 -0
  144. package/dist/tools/guess-view.js +56 -0
  145. package/dist/tools/healthcheck.js +90 -0
  146. package/dist/tools/hints.js +34 -0
  147. package/dist/tools/how-lost.js +154 -0
  148. package/dist/tools/index.js +152 -0
  149. package/dist/tools/join-game.js +327 -0
  150. package/dist/tools/leave-game.js +181 -0
  151. package/dist/tools/live-context.js +339 -0
  152. package/dist/tools/live.js +404 -0
  153. package/dist/tools/map-details.js +88 -0
  154. package/dist/tools/map-stats.js +130 -0
  155. package/dist/tools/map.js +141 -0
  156. package/dist/tools/my-games.js +193 -0
  157. package/dist/tools/notifications.js +484 -0
  158. package/dist/tools/open-games.js +104 -0
  159. package/dist/tools/opponents.js +163 -0
  160. package/dist/tools/order-options.js +135 -0
  161. package/dist/tools/past-games.js +94 -0
  162. package/dist/tools/picks.js +305 -0
  163. package/dist/tools/profile-hook.js +156 -0
  164. package/dist/tools/profile-opponents.js +121 -0
  165. package/dist/tools/profile-reads.js +99 -0
  166. package/dist/tools/push.js +445 -0
  167. package/dist/tools/relations.js +611 -0
  168. package/dist/tools/resolve.js +45 -0
  169. package/dist/tools/route.js +36 -0
  170. package/dist/tools/scout.js +87 -0
  171. package/dist/tools/session.js +163 -0
  172. package/dist/tools/strategy.js +257 -0
  173. package/dist/tools/stress-opponents.js +83 -0
  174. package/dist/tools/surrender-pending.js +74 -0
  175. package/dist/tools/surrender.js +247 -0
  176. package/dist/tools/survival.js +189 -0
  177. package/dist/tools/team-brief.js +266 -0
  178. package/dist/tools/team-source.js +222 -0
  179. package/dist/tools/team.js +178 -0
  180. package/dist/tools/turn.js +2825 -0
  181. package/dist/tools/uncommit.js +160 -0
  182. package/dist/tools/where.js +300 -0
  183. package/dist/tools/write-kit.js +164 -0
  184. package/dist/transport-bridge.js +33 -0
  185. package/dist/trend.js +577 -0
  186. package/dist/version.js +4 -0
  187. package/manifest.json +194 -4
  188. package/mint.yaml +106 -14
  189. package/package.json +11 -6
  190. package/server.json +40 -3
  191. package/skills/warapp-api/SKILL.md +95 -4
  192. package/skills/warapp-api/references/scout.mjs +348 -0
  193. package/skills/warapp-api/scripts/warapp.sh +69 -8
  194. package/skills/warapp-mcp/SKILL.md +1096 -21
@@ -0,0 +1,333 @@
1
+ import { decodeReplyEnvelope, encodeRequest, fromHex, Reader, readExtrasUp, readHeader, toHex } from '../protocol/codec.js';
2
+ import { Method, readSubscribeResult, writeSubscribeParams } from '../protocol/methods.js';
3
+ import { parseHandshake, parsePacket, SOCKET_URL, splitPayload } from './packets.js';
4
+ import { realSetTimer, runWebSocketSession, WebSocketUnavailableError } from './websocket.js';
5
+ export { parseHandshake, parsePacket, SOCKET_URL, splitPayload } from './packets.js';
6
+ export const POST_CONTENT_TYPE = 'text/plain;charset=UTF-8';
7
+ /** A Subscribe frame (method 238, no auth block) as the uppercase hex a message packet carries. */
8
+ export function subscribeFrameHex(topics, msgNum, extras) {
9
+ return toHex(encodeRequest({
10
+ method: Method.Subscribe,
11
+ msgNum,
12
+ extras,
13
+ email: null,
14
+ params: (w) => writeSubscribeParams(w, topics),
15
+ }));
16
+ }
17
+ /**
18
+ * Decode a frame from a message packet. A server push is a request-shaped
19
+ * frame (MessageExtrasUp, no auth): GameUpdated (241) starts with the game id,
20
+ * then two bools the client logs as `chat` and `nonChat` (read from the bundle's
21
+ * handler; UNVERIFIED live), then an optional dict this server does not read.
22
+ * The flags are read only when present: a push without them is a plain update.
23
+ * Returns undefined for anything that does not decode — never throws.
24
+ */
25
+ export function parsePushFrame(hex) {
26
+ try {
27
+ const bytes = fromHex(hex);
28
+ const r = new Reader(bytes);
29
+ const header = readHeader(r);
30
+ if (header.reply) {
31
+ if (header.method !== Method.Subscribe)
32
+ return { kind: 'other', method: header.method };
33
+ const env = decodeReplyEnvelope(bytes);
34
+ if (env.error)
35
+ return { kind: 'subscribe-reply', msgNum: env.msgNum, rejected: new Map(), error: env.error.code };
36
+ return { kind: 'subscribe-reply', msgNum: env.msgNum, rejected: readSubscribeResult(env.body) };
37
+ }
38
+ if (header.method !== Method.GameUpdated)
39
+ return { kind: 'other', method: header.method };
40
+ readExtrasUp(r);
41
+ const gameId = r.int32();
42
+ let chat = false;
43
+ try {
44
+ chat = r.bool();
45
+ }
46
+ catch {
47
+ // No flags: a plain update.
48
+ }
49
+ return chat ? { kind: 'game-updated', gameId, chat: true } : { kind: 'game-updated', gameId };
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ export const DEFAULT_INITIAL_BACKOFF_MS = 1_000;
56
+ export const DEFAULT_MAX_BACKOFF_MS = 60_000;
57
+ const DEFAULT_STABLE_MS = 30_000;
58
+ const DEFAULT_MIN_POLL_MS = 1_000;
59
+ const DEFAULT_MAX_POLL_PACE_MS = 5_000;
60
+ const realSleep = (ms) => new Promise((resolve) => {
61
+ const t = setTimeout(resolve, ms);
62
+ t.unref?.();
63
+ });
64
+ class Disconnected extends Error {
65
+ }
66
+ /**
67
+ * A long-lived socket.io client: the direct WebSocket when its leg is selected
68
+ * and comes up, otherwise xhr-polling over the bridge. `start()` runs the
69
+ * session loop in the background; failures reconnect with backoff (a new
70
+ * handshake, a new sid, `onConnect` re-subscribes) until `stop()`.
71
+ */
72
+ export class SocketIoClient {
73
+ opts;
74
+ sleep;
75
+ now;
76
+ running = false;
77
+ /**
78
+ * The run each loop belongs to, bumped by `start()` and `stop()`. A loop stopped while a poll or
79
+ * a backoff sleep was in flight wakes to a newer generation and exits, even when a later
80
+ * `start()` has set `running` again — otherwise two loops would keep replacing each other's sid
81
+ * (#131).
82
+ */
83
+ generation = 0;
84
+ sid;
85
+ isConnected = false;
86
+ waiters = [];
87
+ failures = 0;
88
+ lastErrorMessage;
89
+ connects = 0;
90
+ /** When the current session connected; undefined until it does. */
91
+ connectedAt;
92
+ sender;
93
+ closeSession;
94
+ active;
95
+ constructor(opts) {
96
+ this.opts = opts;
97
+ this.sleep = opts.sleep ?? realSleep;
98
+ this.now = opts.now ?? Date.now;
99
+ }
100
+ get connected() {
101
+ return this.isConnected;
102
+ }
103
+ get started() {
104
+ return this.running;
105
+ }
106
+ /** How many times a session has connected since the last `start()`. */
107
+ get connectCount() {
108
+ return this.connects;
109
+ }
110
+ get lastError() {
111
+ return this.lastErrorMessage;
112
+ }
113
+ /** The transport of the current (or last) session; undefined before the first. */
114
+ get transport() {
115
+ return this.active;
116
+ }
117
+ start() {
118
+ if (this.running)
119
+ return;
120
+ this.running = true;
121
+ // A restart begins afresh: its first connect is not a reconnect (no push gap on this run).
122
+ this.connects = 0;
123
+ this.failures = 0;
124
+ void this.run(++this.generation);
125
+ }
126
+ /** Stop. An in-flight poll is abandoned, not awaited; an open WebSocket is closed. */
127
+ stop() {
128
+ this.running = false;
129
+ this.generation++;
130
+ const close = this.closeSession;
131
+ this.closeSession = undefined;
132
+ close?.();
133
+ this.disconnect();
134
+ }
135
+ /**
136
+ * End the current session and start a new one at once: a new handshake, a new sid, and `onConnect`
137
+ * (then `onReconnect`) as after any reconnect. An xhr poll in flight is abandoned, as on `stop()`;
138
+ * its loop wakes to a newer generation and exits. No-op when stopped.
139
+ */
140
+ recycle() {
141
+ if (!this.running)
142
+ return;
143
+ const gen = ++this.generation;
144
+ const close = this.closeSession;
145
+ this.closeSession = undefined;
146
+ close?.();
147
+ this.disconnect();
148
+ void this.run(gen);
149
+ }
150
+ /** Resolves once connected (the connect packet seen on the current session). */
151
+ whenConnected() {
152
+ if (this.isConnected)
153
+ return Promise.resolve();
154
+ return new Promise((resolve) => this.waiters.push(resolve));
155
+ }
156
+ /** Send a message packet carrying a hex frame. Only once connected. */
157
+ async sendMessage(hex) {
158
+ if (!this.isConnected || !this.sender)
159
+ throw new Error('The war.app push socket is not connected.');
160
+ await this.sender(`3:::${hex}`);
161
+ }
162
+ url() {
163
+ return `${SOCKET_URL}xhr-polling/${this.sid}?t=${this.now()}`;
164
+ }
165
+ async post(packet) {
166
+ if (!this.isConnected || this.sid === undefined) {
167
+ throw new Error('The war.app push socket is not connected.');
168
+ }
169
+ const t = await this.opts.transport();
170
+ const res = await t.fetch({
171
+ method: 'POST',
172
+ path: this.url(),
173
+ headers: { 'content-type': POST_CONTENT_TYPE },
174
+ body: packet,
175
+ });
176
+ if (res.status !== 200)
177
+ throw new Error(`war.app answered HTTP ${res.status} to a push-socket send.`);
178
+ }
179
+ disconnect() {
180
+ this.isConnected = false;
181
+ this.sid = undefined;
182
+ this.sender = undefined;
183
+ }
184
+ /** A session saw its connect packet: record it, (re)subscribe, then signal a reconnect. */
185
+ async markConnected(gen, send) {
186
+ if (!this.live(gen))
187
+ return;
188
+ this.sender = send;
189
+ this.isConnected = true;
190
+ // The backoff is not reset here: a session that connects and fails at once would retry every
191
+ // second forever. It resets when a session that held for `stableMs` ends (#131).
192
+ this.connectedAt = this.now();
193
+ this.connects++;
194
+ const w = this.waiters;
195
+ this.waiters = [];
196
+ w.forEach((f) => f());
197
+ await this.opts.onConnect?.();
198
+ if (this.connects > 1)
199
+ this.opts.onReconnect?.();
200
+ }
201
+ backoffMs(failures = this.failures) {
202
+ const initial = this.opts.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS;
203
+ const max = this.opts.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
204
+ return Math.min(max, initial * 2 ** Math.min(failures, 30));
205
+ }
206
+ /** Whether a loop of generation `gen` should keep going. */
207
+ live(gen) {
208
+ return this.running && this.generation === gen;
209
+ }
210
+ async run(gen) {
211
+ while (this.live(gen)) {
212
+ this.connectedAt = undefined;
213
+ try {
214
+ await this.session(gen);
215
+ }
216
+ catch (e) {
217
+ // A stale loop must not touch the state of the run that replaced it.
218
+ if (!this.live(gen))
219
+ break;
220
+ this.disconnect();
221
+ const held = this.connectedAt !== undefined && this.now() - this.connectedAt >= (this.opts.stableMs ?? DEFAULT_STABLE_MS);
222
+ if (held)
223
+ this.failures = 0;
224
+ const err = e instanceof Error ? e : new Error(String(e));
225
+ this.lastErrorMessage = err.message;
226
+ this.opts.onError?.(err);
227
+ const delay = this.backoffMs();
228
+ this.failures++;
229
+ await this.sleep(delay);
230
+ }
231
+ }
232
+ }
233
+ /** One session: the WebSocket when selected and available, else xhr-polling. */
234
+ async session(gen) {
235
+ const leg = this.opts.webSocket;
236
+ if (leg && (await leg.select())) {
237
+ this.active = 'websocket';
238
+ try {
239
+ await runWebSocketSession(leg, {
240
+ running: () => this.live(gen),
241
+ now: this.now,
242
+ setTimer: this.opts.setTimer ?? realSetTimer,
243
+ onConnected: (send) => this.markConnected(gen, send),
244
+ onMessage: (data) => this.opts.onMessage(data),
245
+ setCloser: (close) => {
246
+ if (this.live(gen))
247
+ this.closeSession = close;
248
+ else
249
+ close?.();
250
+ },
251
+ });
252
+ return;
253
+ }
254
+ catch (e) {
255
+ if (!(e instanceof WebSocketUnavailableError))
256
+ throw e;
257
+ // Fall back to xhr-polling over the bridge for this session.
258
+ this.lastErrorMessage = e.message;
259
+ }
260
+ }
261
+ if (!this.live(gen))
262
+ return;
263
+ this.active = 'xhr-polling';
264
+ await this.pollSession(gen);
265
+ }
266
+ /** One xhr-polling session: handshake, then poll until it fails or the client stops. */
267
+ async pollSession(gen) {
268
+ const t = await this.opts.transport();
269
+ const hs = await t.fetch({ method: 'GET', path: `${SOCKET_URL}?t=${this.now()}`, retryOnTimeout: false });
270
+ if (!this.live(gen))
271
+ return;
272
+ if (hs.status !== 200)
273
+ throw new Error(`war.app answered HTTP ${hs.status} to the socket handshake.`);
274
+ const handshake = parseHandshake(hs.body);
275
+ if (!handshake.transports.includes('xhr-polling')) {
276
+ throw new Error('war.app did not offer the xhr-polling socket transport.');
277
+ }
278
+ const sid = handshake.sid;
279
+ this.sid = sid;
280
+ let first = true;
281
+ /** Polls in a row answered at once with nothing to say. */
282
+ let idle = 0;
283
+ while (this.live(gen) && this.sid === sid) {
284
+ const started = this.now();
285
+ const res = await t.fetch({ method: 'GET', path: this.url(), retryOnTimeout: false });
286
+ if (!this.live(gen) || this.sid !== sid)
287
+ return;
288
+ if (res.status !== 200)
289
+ throw new Error(`war.app answered HTTP ${res.status} to a push-socket poll.`);
290
+ const packets = splitPayload(res.body).map(parsePacket);
291
+ if (first && packets[0]?.type !== 'connect') {
292
+ throw new Error('war.app did not open the push socket (no connect packet).');
293
+ }
294
+ const wasFirst = first;
295
+ first = false;
296
+ let useful = wasFirst;
297
+ for (const p of packets) {
298
+ // A heartbeat is answered, but it is not news: a server answering every poll with one at
299
+ // once would otherwise spin the loop (#148). One that ends a long poll is not paced anyway.
300
+ if (p.type === 'connect' || p.type === 'message')
301
+ useful = true;
302
+ switch (p.type) {
303
+ case 'connect':
304
+ if (!this.isConnected)
305
+ await this.markConnected(gen, (packet) => this.post(packet));
306
+ break;
307
+ case 'heartbeat':
308
+ await this.post('2::');
309
+ break;
310
+ case 'message':
311
+ this.opts.onMessage(p.data);
312
+ break;
313
+ case 'disconnect':
314
+ throw new Disconnected('war.app closed the push socket.');
315
+ case 'error':
316
+ throw new Error(`war.app refused the push socket (${p.reason || 'no reason'}).`);
317
+ default:
318
+ break;
319
+ }
320
+ }
321
+ // A long poll ends with a noop after a quiet spell; one answered at once with nothing to say
322
+ // (an empty body, a noop, a heartbeat, a packet this client ignores) would otherwise re-poll in a tight
323
+ // loop. Pace those like the reconnect backoff, but capped low: a push that arrives during the
324
+ // pause waits for the next poll (#131).
325
+ if (useful || this.now() - started >= (this.opts.minPollMs ?? DEFAULT_MIN_POLL_MS)) {
326
+ idle = 0;
327
+ }
328
+ else if (this.live(gen) && this.sid === sid) {
329
+ await this.sleep(Math.min(this.opts.maxPollPaceMs ?? DEFAULT_MAX_POLL_PACE_MS, this.backoffMs(idle++)));
330
+ }
331
+ }
332
+ }
333
+ }
@@ -0,0 +1,179 @@
1
+ import { scrubToken } from '../direct/session.js';
2
+ import { DirectBridge } from '../direct/transport.js';
3
+ import { parseHandshake, parsePacket, SOCKET_URL } from './packets.js';
4
+ /** The default factory: Node's built-in WebSocket, which accepts a `headers` option. */
5
+ export const defaultWebSocketFactory = (url, init) => {
6
+ const Ctor = globalThis.WebSocket;
7
+ if (!Ctor)
8
+ throw new Error('This Node.js has no built-in WebSocket.');
9
+ // The host is the fixed literal wss://war.app (see websocketUrl), so the
10
+ // socket needs no netguard address pinning. Binary frames arrive as
11
+ // ArrayBuffer (Node defaults to Blob, which dataText cannot read).
12
+ const ws = new Ctor(url, init);
13
+ ws.binaryType = 'arraybuffer';
14
+ return ws;
15
+ };
16
+ export const realSetTimer = (ms, fn) => {
17
+ const t = setTimeout(fn, ms);
18
+ t.unref?.();
19
+ return () => clearTimeout(t);
20
+ };
21
+ /**
22
+ * The WebSocket could not be brought up (no session, signed out, the handshake
23
+ * failed or did not offer `websocket`, the upgrade failed, or no connect
24
+ * packet arrived): the caller falls back to xhr-polling over the bridge.
25
+ */
26
+ export class WebSocketUnavailableError extends Error {
27
+ name = 'WebSocketUnavailableError';
28
+ }
29
+ const WS_HOST = 'war.app';
30
+ /** The war.app socket URL for a session id; refuses any sid that could change the path. */
31
+ export function websocketUrl(sid) {
32
+ if (!/^[A-Za-z0-9_-]+$/.test(sid))
33
+ throw new Error('war.app returned an unusable push-socket session id.');
34
+ return `wss://${WS_HOST}/socket.io/1/websocket/${sid}`;
35
+ }
36
+ /**
37
+ * The leg for the process's direct-first bridge: the WebSocket is selected
38
+ * only while the active transport is `direct` (pinned `direct`, or `auto`
39
+ * still on the direct leg); otherwise the push stays on xhr-polling.
40
+ */
41
+ export function pushWebSocketLeg(bridge, readSession, seams = {}) {
42
+ return {
43
+ select: () => bridge.status().transport === 'direct',
44
+ session: readSession,
45
+ ...seams,
46
+ };
47
+ }
48
+ const errMessage = (ev) => {
49
+ const m = ev?.message ??
50
+ ev?.error?.message;
51
+ return typeof m === 'string' && m ? `: ${m}` : '';
52
+ };
53
+ const dataText = (data) => typeof data === 'string'
54
+ ? data
55
+ : data instanceof ArrayBuffer || ArrayBuffer.isView(data)
56
+ ? new TextDecoder().decode(data)
57
+ : String(data);
58
+ /**
59
+ * One WebSocket session: handshake, open, wait for `1::`, then serve packets
60
+ * until the socket closes, errors, misses its heartbeat or `stop()` ends it.
61
+ * Rejects with {@link WebSocketUnavailableError} for any failure before the
62
+ * connect packet (the caller falls back), a plain Error after it (the caller
63
+ * reconnects). Resolves only when stopped. Every message is token-scrubbed.
64
+ */
65
+ export async function runWebSocketSession(leg, hooks) {
66
+ const sess = await leg.session();
67
+ if (!sess)
68
+ throw new WebSocketUnavailableError('No war.app session is linked for the push WebSocket.');
69
+ const token = sess.authToken;
70
+ const scrub = (s) => scrubToken(s, token);
71
+ let sid;
72
+ let heartbeatMs;
73
+ try {
74
+ // DirectBridge: host-locked to war.app, cookie attached, errors scrubbed, sign-outs detected.
75
+ const direct = new DirectBridge({ read: async () => sess }, leg.fetch);
76
+ const res = await direct.fetch({ method: 'GET', path: `${SOCKET_URL}?t=${hooks.now()}` });
77
+ if (res.status !== 200)
78
+ throw new Error(`war.app answered HTTP ${res.status} to the socket handshake.`);
79
+ const hs = parseHandshake(res.body);
80
+ if (!hs.transports.includes('websocket'))
81
+ throw new Error('war.app did not offer the websocket socket transport.');
82
+ sid = hs.sid;
83
+ heartbeatMs = hs.heartbeatMs;
84
+ }
85
+ catch (e) {
86
+ throw new WebSocketUnavailableError(scrub(`Push WebSocket handshake failed: ${e instanceof Error ? e.message : String(e)}`));
87
+ }
88
+ let ws;
89
+ try {
90
+ ws = (leg.open ?? defaultWebSocketFactory)(websocketUrl(sid), { headers: { Cookie: `AuthToken=${token}` } });
91
+ }
92
+ catch (e) {
93
+ throw new WebSocketUnavailableError(scrub(`Push WebSocket upgrade failed: ${e instanceof Error ? e.message : String(e)}`));
94
+ }
95
+ await new Promise((resolve, reject) => {
96
+ let connected = false;
97
+ let done = false;
98
+ let cancelTimer = () => { };
99
+ let chain = Promise.resolve();
100
+ const finish = (why) => {
101
+ if (done)
102
+ return;
103
+ done = true;
104
+ cancelTimer();
105
+ hooks.setCloser(undefined);
106
+ ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;
107
+ try {
108
+ ws.close();
109
+ }
110
+ catch {
111
+ // Already closed.
112
+ }
113
+ if (why === undefined)
114
+ resolve();
115
+ else if (connected)
116
+ reject(new Error(scrub(why)));
117
+ else
118
+ reject(new WebSocketUnavailableError(scrub(why)));
119
+ };
120
+ const arm = () => {
121
+ cancelTimer();
122
+ if (heartbeatMs > 0) {
123
+ cancelTimer = hooks.setTimer(heartbeatMs, () => finish(connected
124
+ ? 'The war.app push WebSocket missed its heartbeat.'
125
+ : 'The war.app push WebSocket did not connect before the heartbeat timeout.'));
126
+ }
127
+ };
128
+ const send = async (packet) => {
129
+ if (done)
130
+ throw new Error('The war.app push socket is not connected.');
131
+ ws.send(packet);
132
+ };
133
+ const handle = async (raw) => {
134
+ const p = parsePacket(raw);
135
+ if (!connected && p.type !== 'connect') {
136
+ finish('war.app did not open the push WebSocket (no connect packet).');
137
+ return;
138
+ }
139
+ switch (p.type) {
140
+ case 'connect':
141
+ if (!connected) {
142
+ connected = true;
143
+ await hooks.onConnected(send);
144
+ }
145
+ break;
146
+ case 'heartbeat':
147
+ await send('2::');
148
+ break;
149
+ case 'message':
150
+ hooks.onMessage(p.data);
151
+ break;
152
+ case 'disconnect':
153
+ finish('war.app closed the push WebSocket.');
154
+ break;
155
+ case 'error':
156
+ finish(`war.app refused the push socket (${p.reason || 'no reason'}).`);
157
+ break;
158
+ default:
159
+ break;
160
+ }
161
+ };
162
+ hooks.setCloser(() => finish());
163
+ arm();
164
+ ws.onopen = () => arm();
165
+ ws.onmessage = (ev) => {
166
+ if (done)
167
+ return;
168
+ arm();
169
+ const raw = dataText(ev.data);
170
+ chain = chain
171
+ .then(() => (done ? undefined : handle(raw)))
172
+ .catch((e) => finish(`The war.app push WebSocket failed: ${e instanceof Error ? e.message : String(e)}`));
173
+ };
174
+ ws.onclose = () => finish(connected ? 'war.app closed the push WebSocket.' : 'The push WebSocket upgrade failed (closed before connecting).');
175
+ ws.onerror = (ev) => finish(`The war.app push WebSocket failed${errMessage(ev)}.`);
176
+ if (!hooks.running())
177
+ finish();
178
+ });
179
+ }
package/dist/redact.js ADDED
@@ -0,0 +1,62 @@
1
+ // By-value scrubbing of the credentials this server holds (the account email,
2
+ // the GameFeed API token, the AuthToken cookie) out of upstream text.
3
+ //
4
+ // An upstream page that echoes a request body or URL may show a value raw,
5
+ // JSON-escaped, or encoded — percent-encoded by any encoder (strict RFC 3986
6
+ // writes `*` as `%2A`, JS encoders do not), partly encoded, with hex digits in
7
+ // either case, or form-encoded (spaces as `+`). So rather than listing
8
+ // spellings, each secret becomes one pattern in which every character matches
9
+ // itself, its percent-encoded UTF-8 bytes (hex in any case), its JSON escape
10
+ // (`\"`, `\uXXXX`) or, for a space, `+` — the same as comparing after decoding.
11
+ // An `anyCase` value (the email) also matches its letters in any case.
12
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
13
+ /** One hex digit, matching either case even in a case-sensitive pattern. */
14
+ const hexDigit = (d) => (/[0-9]/.test(d) ? d : `[${d.toLowerCase()}${d.toUpperCase()}]`);
15
+ const hexPattern = (n, width) => n
16
+ .toString(16)
17
+ .padStart(width, '0')
18
+ .split('')
19
+ .map(hexDigit)
20
+ .join('');
21
+ /** Every way one character of a secret may be written in an echo, as a regex alternation. */
22
+ function charPattern(ch) {
23
+ const alts = new Set([escapeRegExp(ch)]);
24
+ // Percent-encoded UTF-8 bytes (a lone surrogate has none worth matching).
25
+ if (!/[\uD800-\uDFFF]/.test(ch) || ch.length === 2) {
26
+ alts.add([...Buffer.from(ch, 'utf8')].map((b) => `%${hexPattern(b, 2)}`).join(''));
27
+ }
28
+ if (ch === ' ')
29
+ alts.add('\\+');
30
+ const json = JSON.stringify(ch).slice(1, -1);
31
+ if (json !== ch)
32
+ alts.add(escapeRegExp(json));
33
+ // A \uXXXX escape of each UTF-16 unit (`+` for '+', `@` for '@').
34
+ alts.add(ch
35
+ .split('')
36
+ .map((u) => `\\\\u${hexPattern(u.charCodeAt(0), 4)}`)
37
+ .join(''));
38
+ return `(?:${[...alts].join('|')})`;
39
+ }
40
+ /** The pattern matching every spelling of `value` (see the file header). */
41
+ function secretPattern(value, anyCase = false) {
42
+ return new RegExp(Array.from(value, charPattern).join(''), anyCase ? 'gi' : 'g');
43
+ }
44
+ /**
45
+ * `text` with every spelling of each secret replaced by `placeholder`
46
+ * ({@link secretPattern}); the longest secrets first, so the longer of two
47
+ * overlapping secrets goes whole.
48
+ */
49
+ export function scrubSecrets(text, secrets, placeholder = '[REDACTED]') {
50
+ const values = new Map();
51
+ for (const s of secrets) {
52
+ const { value, anyCase = false } = typeof s === 'object' && s !== null ? s : { value: s };
53
+ if (!value)
54
+ continue;
55
+ values.set(value, (values.get(value) ?? false) || anyCase);
56
+ }
57
+ let out = String(text ?? '');
58
+ for (const [value, anyCase] of [...values].sort((a, b) => b[0].length - a[0].length)) {
59
+ out = out.replace(secretPattern(value, anyCase), () => placeholder);
60
+ }
61
+ return out;
62
+ }