@chrischall/warapp-mcp 0.2.0 → 0.3.1

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.
@@ -0,0 +1,75 @@
1
+ // mcp-host's egress proxy, for the requests that bring their own dispatcher.
2
+ //
3
+ // On mcp-host a child reaches the internet ONLY through the egress proxy that
4
+ // `HTTPS_PROXY` + `NODE_USE_ENV_PROXY=1` point Node's built-in fetch at: a
5
+ // direct socket is silently dropped and reads as a timeout. Global fetch
6
+ // honours the variable; a custom undici dispatcher does not. The war.app
7
+ // sign-in (src/direct/sign-in.ts) and the direct leg (src/direct/transport.ts)
8
+ // each send through their own dispatcher — mcp-utils netguard's public-only
9
+ // one — so hosted, neither could reach war.app at all ("Could not reach
10
+ // war.app to sign in"). GameFeed (`createApiClient`) and the bundle download
11
+ // use global fetch and need nothing here.
12
+ //
13
+ // With a proxy configured, those two send through an undici `ProxyAgent` for
14
+ // it instead (a CONNECT tunnel; TLS to war.app still checks war.app's
15
+ // certificate). The host check stays in our code — the exact origin
16
+ // https://war.app — and the proxy enforces the child's allowlist and its own
17
+ // address table, so netguard's public-only pin is not needed there. Without a
18
+ // proxy (local) nothing changes: the public-only dispatcher, as before.
19
+ //
20
+ // A proxy that is set but unusable is a configuration error, refused clearly:
21
+ // never a fallback to a direct connection. NO_PROXY is not read: war.app is
22
+ // never meant to bypass the proxy. The proxy URL is never echoed (it may carry
23
+ // a password).
24
+ import { McpToolError, readEnvVar } from '@chrischall/mcp-utils';
25
+ import { ProxyAgent } from 'undici';
26
+ /** The variables naming the proxy, in the order read (curl's and undici's spellings). */
27
+ export const EGRESS_PROXY_ENV = ['HTTPS_PROXY', 'https_proxy'];
28
+ /** The start of the refusal for a proxy that is set but unusable. */
29
+ export const EGRESS_PROXY_INVALID = 'HTTPS_PROXY is set but is not a usable http(s) proxy URL';
30
+ export const defaultProxyAgent = (url) => new ProxyAgent(url.href);
31
+ const rawProxy = (env) => {
32
+ for (const key of EGRESS_PROXY_ENV) {
33
+ const v = readEnvVar(key, { env });
34
+ if (v !== undefined)
35
+ return v;
36
+ }
37
+ return undefined;
38
+ };
39
+ /** Whether a proxy is configured at all (usable or not): then nothing may connect directly. */
40
+ export function egressProxyConfigured(env = process.env) {
41
+ return rawProxy(env) !== undefined;
42
+ }
43
+ /**
44
+ * The egress proxy's URL when `HTTPS_PROXY` (or `https_proxy`) is set, else
45
+ * `undefined`. Throws a clear error, before anything is sent, when the variable
46
+ * is set but not an http(s) URL with a host (never echoing it).
47
+ */
48
+ export function egressProxyUrl(env = process.env) {
49
+ const raw = rawProxy(env);
50
+ if (raw === undefined)
51
+ return undefined;
52
+ let url;
53
+ try {
54
+ url = new URL(raw);
55
+ }
56
+ catch {
57
+ url = undefined;
58
+ }
59
+ if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:') || !url.hostname) {
60
+ throw new McpToolError(`${EGRESS_PROXY_INVALID}, so nothing was sent to war.app.`, {
61
+ kind: 'unknown',
62
+ hint: 'Set HTTPS_PROXY to a proxy URL such as http://127.0.0.1:8080, or unset it to connect directly.',
63
+ });
64
+ }
65
+ return url;
66
+ }
67
+ /**
68
+ * The dispatcher to send war.app traffic through: a proxy agent for
69
+ * {@link egressProxyUrl}, else `undefined` (the caller keeps its public-only
70
+ * dispatcher). Throws as {@link egressProxyUrl} does. The caller closes the agent.
71
+ */
72
+ export function egressDispatcher(env = process.env, make = defaultProxyAgent) {
73
+ const url = egressProxyUrl(env);
74
+ return url ? make(url) : undefined;
75
+ }
@@ -13,8 +13,10 @@
13
13
  // returns it, never logs it, never puts it in an error: it returns only when
14
14
  // the capture happened ({@link LinkResult} is `capturedAt` + `host`). Every
15
15
  // cookie but `AuthToken` is discarded. A capture that yields no AuthToken
16
- // throws {@link NoAuthTokenError} and stores nothing. Direct mode is
17
- // LOCAL-ONLY — the hosted path keeps the browser bridge and stores no token.
16
+ // throws {@link NoAuthTokenError} and stores nothing. Linking is LOCAL-ONLY: a
17
+ // hosted child rides the direct transport only from the session captured at
18
+ // sign-in (mcp-host's authFlow, WARAPP_AUTH_TOKEN, held in memory: #333,
19
+ // src/direct/session.ts) and never links or stores one.
18
20
  import { McpToolError, readPortEnv } from '@chrischall/mcp-utils';
19
21
  import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
20
22
  import { isHosted } from '../hosted.js';
@@ -77,10 +79,12 @@ function captureWarappCookie(opts) {
77
79
  * when the captured cookie carries no `AuthToken`.
78
80
  */
79
81
  export async function linkSession(opts = {}) {
80
- // Local-only: a hosted child never pulls the full-account cookie into memory
81
- // (the tool is not registered there, and writeSession refuses too).
82
+ // Local-only: a hosted child never pulls the cookie off a tab; it reaches war.app
83
+ // directly only from the session captured at sign-in (the tool is not
84
+ // registered there, and writeSession refuses too).
82
85
  if (isHosted(opts.env ?? process.env)) {
83
- throw new McpToolError('The direct transport is local-only: a hosted server never links a war.app session.', {
86
+ throw new McpToolError('Linking a war.app session is local-only: a hosted server reaches war.app directly only from the session ' +
87
+ 'captured at sign-in, and never links one.', {
84
88
  kind: 'unknown',
85
89
  });
86
90
  }
@@ -20,8 +20,12 @@
20
20
  // import time, the server boots without a session, and a missing OR corrupt
21
21
  // file reads as `null` — never a throw.
22
22
  //
23
- // LOCAL-ONLY: on a hosted child (src/hosted.ts) the store reads as empty — a
24
- // session file already in the data dir is never read — and refuses to write.
23
+ // Hosted (src/hosted.ts) the FILE is never read or written: a session file
24
+ // already in the data dir is ignored and {@link writeSession} refuses. The one
25
+ // session a hosted child has is the AuthToken mcp-host captured at sign-in and
26
+ // injects as {@link HOST_TOKEN_ENV} (#333): {@link hostedSession} reads it into
27
+ // memory, read-only, never stored. Without it the store reads as empty, as
28
+ // before. Locally the variable is ignored: only the session file counts.
25
29
  import { execFile } from 'node:child_process';
26
30
  import { randomBytes } from 'node:crypto';
27
31
  import { readFileSync } from 'node:fs';
@@ -35,6 +39,55 @@ import { isHosted } from '../hosted.js';
35
39
  import { scrubSecrets } from '../redact.js';
36
40
  /** The only host a session is ever stored for. */
37
41
  export const SESSION_HOST = 'war.app';
42
+ /**
43
+ * The env var mcp-host's sign-in flow captures war.app's AuthToken into on a
44
+ * hosted child (an `authFlow` `capture`, stored as a per-user secret). Hosted
45
+ * only; a local process ignores it.
46
+ */
47
+ export const HOST_TOKEN_ENV = 'WARAPP_AUTH_TOKEN';
48
+ /** The `capturedAt` of the host's session: the time is not known to this process. */
49
+ export const HOST_CAPTURED_AT = 'captured by the host';
50
+ /** Loose bounds on a captured AuthToken: a cookie value, nothing a header could split on. */
51
+ const HOST_TOKEN_SHAPE = /^[\x21-\x7e]{16,4096}$/;
52
+ const HOST_TOKEN_FORBIDDEN = /[;,"\\]/;
53
+ /** The env value as a bare cookie value: trimmed, a leading `AuthToken=` dropped. */
54
+ function hostTokenValue(env) {
55
+ const raw = readEnvVar(HOST_TOKEN_ENV, { env });
56
+ if (raw === undefined)
57
+ return undefined;
58
+ return raw.trim().replace(/^AuthToken=/, '');
59
+ }
60
+ /**
61
+ * Whether a hosted child has a usable host-captured token: `none` (not hosted,
62
+ * or the variable unset), `ok`, or `malformed` (set, but not a plausible cookie
63
+ * value — treated as absent, and never echoed).
64
+ */
65
+ export function hostedTokenState(env = process.env) {
66
+ if (!isHosted(env))
67
+ return 'none';
68
+ const v = hostTokenValue(env);
69
+ if (v === undefined)
70
+ return 'none';
71
+ return isPlausibleAuthToken(v) ? 'ok' : 'malformed';
72
+ }
73
+ /**
74
+ * Whether `v` is a plausible bare AuthToken cookie value (the loose bounds the
75
+ * hosted child accepts in {@link HOST_TOKEN_ENV}). warapp_sign_in returns only a
76
+ * token that passes, so a capture never stores one the child would ignore.
77
+ */
78
+ export function isPlausibleAuthToken(v) {
79
+ return HOST_TOKEN_SHAPE.test(v) && !HOST_TOKEN_FORBIDDEN.test(v);
80
+ }
81
+ /**
82
+ * The hosted child's session: the AuthToken mcp-host captured at sign-in
83
+ * ({@link HOST_TOKEN_ENV}), in memory and read-only, or `null` when not hosted,
84
+ * unset or malformed. Never throws, never stores anything.
85
+ */
86
+ export function hostedSession(env = process.env) {
87
+ if (hostedTokenState(env) !== 'ok')
88
+ return null;
89
+ return { authToken: hostTokenValue(env), capturedAt: HOST_CAPTURED_AT, host: SESSION_HOST, origin: 'host' };
90
+ }
38
91
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
39
92
  /**
40
93
  * Where the session is stored: `WARAPP_SESSION_FILE` if set, else
@@ -60,11 +113,12 @@ function parseSession(raw) {
60
113
  }
61
114
  /**
62
115
  * The linked session, or `null` when none is linked or the file is missing or
63
- * unusable (wrong shape, wrong host, not JSON). Never throws.
116
+ * unusable (wrong shape, wrong host, not JSON). Hosted: {@link hostedSession},
117
+ * never the file. Never throws.
64
118
  */
65
119
  export async function readSession(env = process.env) {
66
120
  if (isHosted(env))
67
- return null;
121
+ return hostedSession(env);
68
122
  try {
69
123
  return parseSession(JSON.parse(await readFile(sessionFilePath(env), 'utf8')));
70
124
  }
@@ -80,7 +134,7 @@ export async function readSession(env = process.env) {
80
134
  */
81
135
  export function readSessionSync(env = process.env) {
82
136
  if (isHosted(env))
83
- return null;
137
+ return hostedSession(env);
84
138
  try {
85
139
  return parseSession(JSON.parse(readFileSync(sessionFilePath(env), 'utf8')));
86
140
  }
@@ -156,7 +210,7 @@ export function sessionTmpPath(path) {
156
210
  */
157
211
  export async function writeSession(session, env = process.env) {
158
212
  if (isHosted(env)) {
159
- throw new McpToolError('The direct transport is local-only: a hosted server never stores a war.app session.', {
213
+ throw new McpToolError('A hosted server never stores a war.app session: its session is the one mcp-host captured at sign-in.', {
160
214
  kind: 'unknown',
161
215
  });
162
216
  }
@@ -0,0 +1,308 @@
1
+ // Signing in to war.app with an email and password, for mcp-host's hosted
2
+ // sign-in flow (#333, part B; owner decision "Build it, token only").
3
+ //
4
+ // The flow (docs/examples/warapp-auth-flow.json) asks for the war.app password
5
+ // once, masked, and calls `warapp_sign_in` as its `capture`: the result's
6
+ // `authToken` becomes the per-user secret WARAPP_AUTH_TOKEN, which the hosted
7
+ // child then rides the direct leg on (src/direct/session.ts `hostedSession`).
8
+ // The password is used for this one exchange and never stored.
9
+ //
10
+ // The exchange, as traced live on #333 (one cookie-less GET, nothing submitted):
11
+ // 1. GET https://war.app/LogIn — it sets `jses_WS60`, `FirstReferrer` and
12
+ // `AWSELB` before any sign-in; they are carried to the POST.
13
+ // 2. POST the form `LoginForm` to the same URL: exactly `Email`, `Password`,
14
+ // `KeepSignedIn=on` (no hidden fields, no captcha on the page).
15
+ // 3. Success is an `AuthToken` cookie set on ANY hop: the POST's answer or a
16
+ // redirect after it (how a success answers is not verified live yet).
17
+ //
18
+ // Rules:
19
+ // - ONE attempt, never retried: war.app (like every service) may count failed
20
+ // sign-ins, and mcp-host treats a refused credential as terminal anyway.
21
+ // - The password is sent once: every redirect, after the POST too, is followed
22
+ // as a GET without a body (a 307/308 included), so it is never re-sent.
23
+ // - Every hop is the exact origin https://war.app; a redirect anywhere else is
24
+ // refused without being requested. Redirects are followed by hand, a few at
25
+ // most, so each hop's Set-Cookie is read.
26
+ // - The result is `{ authToken }` and nothing else about the account. A
27
+ // refusal (wrong credentials, a bot check, a network failure) is an error
28
+ // whose message and hint never hold the email, the password or any cookie
29
+ // value: each is scrubbed BY VALUE, and the cause chain is dropped.
30
+ // - The single-hop fetch goes through mcp-utils netguard's public-only
31
+ // dispatcher (a name that resolves or rebinds inward is refused), with one
32
+ // deadline over the whole exchange and a byte cap on each body. With an
33
+ // egress proxy configured (HTTPS_PROXY: mcp-host's only way out) it goes
34
+ // through a proxy agent instead (src/direct/egress.ts); a proxy that is set
35
+ // but unusable is refused before anything is sent.
36
+ import { detectEdgeBlock, McpToolError } from '@chrischall/mcp-utils';
37
+ import { createPublicOnlyDispatcher } from '@chrischall/mcp-utils/netguard';
38
+ import { fetch as undiciFetch } from 'undici';
39
+ import { defaultProxyAgent, egressProxyUrl } from './egress.js';
40
+ import { scrubSecrets } from '../redact.js';
41
+ import { isPlausibleAuthToken, SESSION_HOST } from './session.js';
42
+ import { hasPasswordInput } from './transport.js';
43
+ /** The one origin the sign-in talks to. */
44
+ const ORIGIN = `https://${SESSION_HOST}`;
45
+ /** war.app's sign-in page; its form posts to the page's own URL (#333 trace). */
46
+ export const SIGN_IN_URL = `${ORIGIN}/LogIn`;
47
+ /** The cookie that carries the signed-in session. */
48
+ const AUTH_COOKIE = 'AuthToken';
49
+ /** Redirects followed after the GET, and after the POST (each as a GET). */
50
+ const MAX_REDIRECTS = 3;
51
+ /** A cookie value this long or longer is scrubbed from refusal text. */
52
+ const MIN_SCRUBBED_COOKIE = 6;
53
+ /** One deadline (ms) over the whole exchange: every hop and every body read. */
54
+ export const SIGN_IN_TIMEOUT_MS = 30_000;
55
+ /** Byte cap on each response body (the sign-in page is a few tens of KB). */
56
+ export const SIGN_IN_MAX_BODY_BYTES = 2 * 1024 * 1024;
57
+ /**
58
+ * The default single-hop fetch: undici, redirects never followed, through the
59
+ * egress proxy when one is configured (src/direct/egress.ts), else through a
60
+ * public-only dispatcher. A proxy that is set but unusable throws here, before
61
+ * any request.
62
+ */
63
+ export function createSignInFetch(opts = {}) {
64
+ const maxBytes = opts.maxBytes ?? SIGN_IN_MAX_BODY_BYTES;
65
+ // Read (and a bad proxy refused) now, before any request; an agent is built per hop and closed.
66
+ const proxy = opts.dispatcher ? undefined : egressProxyUrl(opts.env ?? process.env);
67
+ const makeProxy = opts.proxyAgent ?? defaultProxyAgent;
68
+ return async (url, init) => {
69
+ const owned = opts.dispatcher ? undefined : proxy ? makeProxy(proxy) : createPublicOnlyDispatcher();
70
+ try {
71
+ const res = await undiciFetch(url, {
72
+ method: init.method,
73
+ headers: init.headers,
74
+ ...(init.body !== undefined ? { body: init.body } : {}),
75
+ redirect: 'manual',
76
+ dispatcher: opts.dispatcher ?? owned,
77
+ signal: init.signal,
78
+ });
79
+ const headers = {};
80
+ res.headers.forEach((v, k) => {
81
+ if (k.toLowerCase() !== 'set-cookie')
82
+ headers[k.toLowerCase()] = v;
83
+ });
84
+ const setCookies = res.headers.getSetCookie();
85
+ const body = await readCapped(res.body, maxBytes);
86
+ return { status: res.status, headers, setCookies, body };
87
+ }
88
+ finally {
89
+ await owned?.close().catch(() => { });
90
+ }
91
+ };
92
+ }
93
+ /** A response body as text, refusing past `maxBytes`. */
94
+ async function readCapped(body, maxBytes) {
95
+ if (!body)
96
+ return '';
97
+ const chunks = [];
98
+ let total = 0;
99
+ for await (const chunk of body) {
100
+ total += chunk.byteLength;
101
+ if (total > maxBytes) {
102
+ throw new McpToolError(`war.app's sign-in answered with more than ${maxBytes} bytes.`, { kind: 'too_large' });
103
+ }
104
+ chunks.push(chunk);
105
+ }
106
+ return Buffer.concat(chunks).toString('utf8');
107
+ }
108
+ /**
109
+ * The cookie a `Set-Cookie` header sets, or `null` for a deletion (an empty
110
+ * value, `Max-Age` of zero or less, or an `Expires` in the past) — the value is
111
+ * then `null` so the jar drops it.
112
+ */
113
+ export function parseSetCookie(header, now = Date.now()) {
114
+ const [pair = '', ...attrs] = header.split(';');
115
+ const eq = pair.indexOf('=');
116
+ if (eq <= 0)
117
+ return null;
118
+ const name = pair.slice(0, eq).trim();
119
+ if (!name)
120
+ return null;
121
+ let value = pair.slice(eq + 1).trim();
122
+ if (value.startsWith('"') && value.endsWith('"') && value.length >= 2)
123
+ value = value.slice(1, -1);
124
+ for (const attr of attrs) {
125
+ const i = attr.indexOf('=');
126
+ const key = (i < 0 ? attr : attr.slice(0, i)).trim().toLowerCase();
127
+ const v = i < 0 ? '' : attr.slice(i + 1).trim();
128
+ if (key === 'max-age' && /^-?\d+$/.test(v) && Number(v) <= 0)
129
+ value = null;
130
+ if (key === 'expires') {
131
+ const t = Date.parse(v);
132
+ if (!Number.isNaN(t) && t <= now)
133
+ value = null;
134
+ }
135
+ }
136
+ if (value === '')
137
+ value = null;
138
+ return { name, value };
139
+ }
140
+ /** Whether `url` is exactly on https://war.app (no other port, no userinfo). */
141
+ function onWarapp(url) {
142
+ return url.origin === ORIGIN && url.username === '' && url.password === '';
143
+ }
144
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
145
+ /** Bot-check markup: a captcha widget or a hosted challenge script. */
146
+ const CHALLENGE_MARKUP = /g-recaptcha|grecaptcha|recaptcha\/api|h-captcha|hcaptcha\.com|cf-turnstile|challenges\.cloudflare\.com/i;
147
+ /** Why the sign-in was refused, as the error's kind and message. */
148
+ const NOT_RETRIED = 'It was not retried, because war.app may count failed sign-ins.';
149
+ function refusal(kind, message, hint) {
150
+ return new McpToolError(message, { kind, ...(hint ? { hint } : {}) });
151
+ }
152
+ /** A bot check answered instead of war.app's page: the credential was never judged. */
153
+ function challenge(what) {
154
+ return refusal('edge_blocked', `war.app answered the sign-in with ${what}, which this connector cannot answer. ${NOT_RETRIED}`, 'Wait a while and use Sign in on the connection again. Until then the connection still works through the war.app tab (the browser bridge); if it keeps happening, report it.');
155
+ }
156
+ /** A bot check on a response, or `null`: an edge block, a 429, a 403 or captcha markup. */
157
+ function challengeIn(res) {
158
+ const edge = detectEdgeBlock({ body: res.body, headers: res.headers, status: res.status });
159
+ if (edge)
160
+ return challenge(`a ${edge.vendor} bot check`);
161
+ if (res.status === 429)
162
+ return challenge('"too many requests" (HTTP 429)');
163
+ if (CHALLENGE_MARKUP.test(res.body))
164
+ return challenge('a captcha');
165
+ if (res.status === 403)
166
+ return challenge('a refusal (HTTP 403)');
167
+ return null;
168
+ }
169
+ /**
170
+ * Sign in to war.app once with `email` and `password` and return the
171
+ * `AuthToken` cookie it sets. Throws an {@link McpToolError} on any refusal —
172
+ * `credential_rejected` (the form came back), `edge_blocked` (a captcha, a CDN
173
+ * challenge, 403 or 429), `transport` / `timeout` (network), `http` / `unknown`
174
+ * otherwise — whose text never holds the email, the password or a cookie value.
175
+ */
176
+ export async function signIn(creds, opts = {}) {
177
+ const jar = new Map();
178
+ // Cookie values shorter than MIN_SCRUBBED_COOKIE are not secrets (`FirstReferrer=x`) and would
179
+ // shred every word holding that letter; the email and the password are scrubbed whatever their length.
180
+ const secrets = () => [
181
+ { value: creds.email, anyCase: true },
182
+ creds.password,
183
+ ...[...jar.values()].filter((v) => v.length >= MIN_SCRUBBED_COOKIE),
184
+ ];
185
+ try {
186
+ return await exchange(creds, jar, opts);
187
+ }
188
+ catch (err) {
189
+ throw scrubbed(err, secrets());
190
+ }
191
+ }
192
+ async function exchange(creds, jar, opts) {
193
+ if (!creds.email.trim() || !creds.password) {
194
+ throw refusal('no_credential', 'Signing in to war.app needs both the email and the password; nothing was sent.');
195
+ }
196
+ const fetchHop = opts.fetch ?? createSignInFetch(opts.env ? { env: opts.env } : {});
197
+ const timeoutMs = opts.timeoutMs ?? SIGN_IN_TIMEOUT_MS;
198
+ const timeout = AbortSignal.timeout(timeoutMs);
199
+ const signal = opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout;
200
+ let posted = false;
201
+ const hop = async (url, method, body) => {
202
+ const headers = { accept: 'text/html,application/xhtml+xml' };
203
+ if (jar.size > 0)
204
+ headers.cookie = [...jar].map(([k, v]) => `${k}=${v}`).join('; ');
205
+ if (method === 'POST') {
206
+ headers['content-type'] = 'application/x-www-form-urlencoded';
207
+ headers.origin = ORIGIN;
208
+ headers.referer = SIGN_IN_URL;
209
+ }
210
+ let res;
211
+ try {
212
+ res = await fetchHop(url.href, { method, headers, ...(body !== undefined ? { body } : {}), signal });
213
+ }
214
+ catch (err) {
215
+ if (opts.signal?.aborted)
216
+ throw opts.signal.reason;
217
+ const after = posted
218
+ ? ' The sign-in may or may not have reached war.app; it was not retried.'
219
+ : ' Nothing was sent to war.app.';
220
+ if (timeout.aborted) {
221
+ throw refusal('timeout', `war.app did not answer the sign-in within ${Math.round(timeoutMs / 1000)} s.${after}`);
222
+ }
223
+ if (err instanceof McpToolError && err.kind === 'too_large')
224
+ throw err;
225
+ throw refusal('transport', `Could not reach war.app to sign in.${after}`);
226
+ }
227
+ for (const header of res.setCookies) {
228
+ const c = parseSetCookie(header);
229
+ if (!c)
230
+ continue;
231
+ if (c.value === null)
232
+ jar.delete(c.name);
233
+ else
234
+ jar.set(c.name, c.value);
235
+ }
236
+ return res;
237
+ };
238
+ /**
239
+ * Follow `res`'s redirects (as GETs, within war.app) until a final answer or, once the POST
240
+ * has gone, the AuthToken. Before the POST an AuthToken ends nothing: it is not this
241
+ * account's (the page phase drops it), and stopping on a redirect would read as no form.
242
+ */
243
+ const follow = async (from, first) => {
244
+ let url = from;
245
+ let res = first;
246
+ for (let n = 0;; n++) {
247
+ if (posted && jar.has(AUTH_COOKIE))
248
+ return { url, res };
249
+ const location = REDIRECTS.has(res.status) ? res.headers.location : undefined;
250
+ if (!location)
251
+ return { url, res };
252
+ let next;
253
+ try {
254
+ next = new URL(location, url);
255
+ }
256
+ catch {
257
+ throw refusal('unknown', `war.app redirected the sign-in to an address that does not parse. ${NOT_RETRIED}`);
258
+ }
259
+ if (!onWarapp(next)) {
260
+ throw refusal('unknown', `war.app redirected the sign-in away from ${ORIGIN}; it was not followed. ${NOT_RETRIED}`);
261
+ }
262
+ if (n >= MAX_REDIRECTS) {
263
+ throw refusal('unknown', `war.app redirected the sign-in more than ${MAX_REDIRECTS} times. ${NOT_RETRIED}`);
264
+ }
265
+ url = next;
266
+ res = await hop(url, 'GET');
267
+ }
268
+ };
269
+ // 1. The sign-in page, for its cookies (and to see its form before any attempt).
270
+ const page = await follow(new URL(SIGN_IN_URL), await hop(new URL(SIGN_IN_URL), 'GET'));
271
+ const pageCheck = challengeIn(page.res);
272
+ if (pageCheck)
273
+ throw pageCheck;
274
+ if (page.res.status !== 200 || !hasPasswordInput(page.res.body)) {
275
+ throw refusal('http', `war.app's sign-in page did not show its form (HTTP ${page.res.status}); no password was sent.`, 'war.app may be down or have changed its sign-in page. Try Sign in again later.');
276
+ }
277
+ // A session from the page alone is not this account's: only one the POST earns counts.
278
+ jar.delete(AUTH_COOKIE);
279
+ // 2. The one attempt.
280
+ const form = new URLSearchParams({ Email: creds.email.trim(), Password: creds.password, KeepSignedIn: 'on' });
281
+ posted = true;
282
+ const postUrl = new URL(SIGN_IN_URL);
283
+ const done = await follow(postUrl, await hop(postUrl, 'POST', form.toString()));
284
+ // 3. Success is the AuthToken, set on any hop.
285
+ const token = jar.get(AUTH_COOKIE);
286
+ if (token) {
287
+ if (isPlausibleAuthToken(token))
288
+ return { authToken: token };
289
+ // Kept, it would be a secret the hosted child ignores (src/direct/session.ts `hostedSession`).
290
+ throw refusal('unknown', 'war.app signed in, but its session cookie is not in a shape this connector can use; it was not kept.', 'war.app may have changed its session cookie. Report this; nothing was retried.');
291
+ }
292
+ const check = challengeIn(done.res);
293
+ if (check)
294
+ throw check;
295
+ // The form came back (on the POST's answer, or after a redirect to the sign-in page).
296
+ if (hasPasswordInput(done.res.body)) {
297
+ throw refusal('credential_rejected', `war.app refused the sign-in: the email or password is not right (its sign-in form came back). ${NOT_RETRIED}`, 'Check the war.app password (and the email on this connection), then use Sign in on the connection again.');
298
+ }
299
+ throw refusal(done.res.status >= 400 ? 'http' : 'unknown', `war.app answered the sign-in (HTTP ${done.res.status}) without setting a session. ${NOT_RETRIED}`, 'war.app may have changed how it signs in. Try Sign in again later.');
300
+ }
301
+ /** `err` rebuilt with every secret scrubbed out of its message and hint, and no cause. */
302
+ function scrubbed(err, secrets) {
303
+ const e = err;
304
+ const scrub = (s) => scrubSecrets(s, secrets);
305
+ const message = scrub(typeof e?.message === 'string' ? e.message : String(err));
306
+ const kind = err instanceof McpToolError && err.kind ? err.kind : 'unknown';
307
+ return new McpToolError(message, { kind, ...(typeof e?.hint === 'string' ? { hint: scrub(e.hint) } : {}) });
308
+ }