@chrischall/warapp-mcp 0.2.0 → 0.3.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.
@@ -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,296 @@
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.
33
+ import { detectEdgeBlock, McpToolError } from '@chrischall/mcp-utils';
34
+ import { createPublicOnlyDispatcher } from '@chrischall/mcp-utils/netguard';
35
+ import { fetch as undiciFetch } from 'undici';
36
+ import { scrubSecrets } from '../redact.js';
37
+ import { isPlausibleAuthToken, SESSION_HOST } from './session.js';
38
+ import { hasPasswordInput } from './transport.js';
39
+ /** The one origin the sign-in talks to. */
40
+ const ORIGIN = `https://${SESSION_HOST}`;
41
+ /** war.app's sign-in page; its form posts to the page's own URL (#333 trace). */
42
+ export const SIGN_IN_URL = `${ORIGIN}/LogIn`;
43
+ /** The cookie that carries the signed-in session. */
44
+ const AUTH_COOKIE = 'AuthToken';
45
+ /** Redirects followed after the GET, and after the POST (each as a GET). */
46
+ const MAX_REDIRECTS = 3;
47
+ /** A cookie value this long or longer is scrubbed from refusal text. */
48
+ const MIN_SCRUBBED_COOKIE = 6;
49
+ /** One deadline (ms) over the whole exchange: every hop and every body read. */
50
+ export const SIGN_IN_TIMEOUT_MS = 30_000;
51
+ /** Byte cap on each response body (the sign-in page is a few tens of KB). */
52
+ export const SIGN_IN_MAX_BODY_BYTES = 2 * 1024 * 1024;
53
+ /** The default single-hop fetch: undici through a public-only dispatcher, redirects never followed. */
54
+ export function createSignInFetch(opts = {}) {
55
+ const maxBytes = opts.maxBytes ?? SIGN_IN_MAX_BODY_BYTES;
56
+ return async (url, init) => {
57
+ const owned = opts.dispatcher ? undefined : createPublicOnlyDispatcher();
58
+ try {
59
+ const res = await undiciFetch(url, {
60
+ method: init.method,
61
+ headers: init.headers,
62
+ ...(init.body !== undefined ? { body: init.body } : {}),
63
+ redirect: 'manual',
64
+ dispatcher: opts.dispatcher ?? owned,
65
+ signal: init.signal,
66
+ });
67
+ const headers = {};
68
+ res.headers.forEach((v, k) => {
69
+ if (k.toLowerCase() !== 'set-cookie')
70
+ headers[k.toLowerCase()] = v;
71
+ });
72
+ const setCookies = res.headers.getSetCookie();
73
+ const body = await readCapped(res.body, maxBytes);
74
+ return { status: res.status, headers, setCookies, body };
75
+ }
76
+ finally {
77
+ await owned?.close().catch(() => { });
78
+ }
79
+ };
80
+ }
81
+ /** A response body as text, refusing past `maxBytes`. */
82
+ async function readCapped(body, maxBytes) {
83
+ if (!body)
84
+ return '';
85
+ const chunks = [];
86
+ let total = 0;
87
+ for await (const chunk of body) {
88
+ total += chunk.byteLength;
89
+ if (total > maxBytes) {
90
+ throw new McpToolError(`war.app's sign-in answered with more than ${maxBytes} bytes.`, { kind: 'too_large' });
91
+ }
92
+ chunks.push(chunk);
93
+ }
94
+ return Buffer.concat(chunks).toString('utf8');
95
+ }
96
+ /**
97
+ * The cookie a `Set-Cookie` header sets, or `null` for a deletion (an empty
98
+ * value, `Max-Age` of zero or less, or an `Expires` in the past) — the value is
99
+ * then `null` so the jar drops it.
100
+ */
101
+ export function parseSetCookie(header, now = Date.now()) {
102
+ const [pair = '', ...attrs] = header.split(';');
103
+ const eq = pair.indexOf('=');
104
+ if (eq <= 0)
105
+ return null;
106
+ const name = pair.slice(0, eq).trim();
107
+ if (!name)
108
+ return null;
109
+ let value = pair.slice(eq + 1).trim();
110
+ if (value.startsWith('"') && value.endsWith('"') && value.length >= 2)
111
+ value = value.slice(1, -1);
112
+ for (const attr of attrs) {
113
+ const i = attr.indexOf('=');
114
+ const key = (i < 0 ? attr : attr.slice(0, i)).trim().toLowerCase();
115
+ const v = i < 0 ? '' : attr.slice(i + 1).trim();
116
+ if (key === 'max-age' && /^-?\d+$/.test(v) && Number(v) <= 0)
117
+ value = null;
118
+ if (key === 'expires') {
119
+ const t = Date.parse(v);
120
+ if (!Number.isNaN(t) && t <= now)
121
+ value = null;
122
+ }
123
+ }
124
+ if (value === '')
125
+ value = null;
126
+ return { name, value };
127
+ }
128
+ /** Whether `url` is exactly on https://war.app (no other port, no userinfo). */
129
+ function onWarapp(url) {
130
+ return url.origin === ORIGIN && url.username === '' && url.password === '';
131
+ }
132
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
133
+ /** Bot-check markup: a captcha widget or a hosted challenge script. */
134
+ const CHALLENGE_MARKUP = /g-recaptcha|grecaptcha|recaptcha\/api|h-captcha|hcaptcha\.com|cf-turnstile|challenges\.cloudflare\.com/i;
135
+ /** Why the sign-in was refused, as the error's kind and message. */
136
+ const NOT_RETRIED = 'It was not retried, because war.app may count failed sign-ins.';
137
+ function refusal(kind, message, hint) {
138
+ return new McpToolError(message, { kind, ...(hint ? { hint } : {}) });
139
+ }
140
+ /** A bot check answered instead of war.app's page: the credential was never judged. */
141
+ function challenge(what) {
142
+ 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.');
143
+ }
144
+ /** A bot check on a response, or `null`: an edge block, a 429, a 403 or captcha markup. */
145
+ function challengeIn(res) {
146
+ const edge = detectEdgeBlock({ body: res.body, headers: res.headers, status: res.status });
147
+ if (edge)
148
+ return challenge(`a ${edge.vendor} bot check`);
149
+ if (res.status === 429)
150
+ return challenge('"too many requests" (HTTP 429)');
151
+ if (CHALLENGE_MARKUP.test(res.body))
152
+ return challenge('a captcha');
153
+ if (res.status === 403)
154
+ return challenge('a refusal (HTTP 403)');
155
+ return null;
156
+ }
157
+ /**
158
+ * Sign in to war.app once with `email` and `password` and return the
159
+ * `AuthToken` cookie it sets. Throws an {@link McpToolError} on any refusal —
160
+ * `credential_rejected` (the form came back), `edge_blocked` (a captcha, a CDN
161
+ * challenge, 403 or 429), `transport` / `timeout` (network), `http` / `unknown`
162
+ * otherwise — whose text never holds the email, the password or a cookie value.
163
+ */
164
+ export async function signIn(creds, opts = {}) {
165
+ const jar = new Map();
166
+ // Cookie values shorter than MIN_SCRUBBED_COOKIE are not secrets (`FirstReferrer=x`) and would
167
+ // shred every word holding that letter; the email and the password are scrubbed whatever their length.
168
+ const secrets = () => [
169
+ { value: creds.email, anyCase: true },
170
+ creds.password,
171
+ ...[...jar.values()].filter((v) => v.length >= MIN_SCRUBBED_COOKIE),
172
+ ];
173
+ try {
174
+ return await exchange(creds, jar, opts);
175
+ }
176
+ catch (err) {
177
+ throw scrubbed(err, secrets());
178
+ }
179
+ }
180
+ async function exchange(creds, jar, opts) {
181
+ if (!creds.email.trim() || !creds.password) {
182
+ throw refusal('no_credential', 'Signing in to war.app needs both the email and the password; nothing was sent.');
183
+ }
184
+ const fetchHop = opts.fetch ?? createSignInFetch();
185
+ const timeoutMs = opts.timeoutMs ?? SIGN_IN_TIMEOUT_MS;
186
+ const timeout = AbortSignal.timeout(timeoutMs);
187
+ const signal = opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout;
188
+ let posted = false;
189
+ const hop = async (url, method, body) => {
190
+ const headers = { accept: 'text/html,application/xhtml+xml' };
191
+ if (jar.size > 0)
192
+ headers.cookie = [...jar].map(([k, v]) => `${k}=${v}`).join('; ');
193
+ if (method === 'POST') {
194
+ headers['content-type'] = 'application/x-www-form-urlencoded';
195
+ headers.origin = ORIGIN;
196
+ headers.referer = SIGN_IN_URL;
197
+ }
198
+ let res;
199
+ try {
200
+ res = await fetchHop(url.href, { method, headers, ...(body !== undefined ? { body } : {}), signal });
201
+ }
202
+ catch (err) {
203
+ if (opts.signal?.aborted)
204
+ throw opts.signal.reason;
205
+ const after = posted
206
+ ? ' The sign-in may or may not have reached war.app; it was not retried.'
207
+ : ' Nothing was sent to war.app.';
208
+ if (timeout.aborted) {
209
+ throw refusal('timeout', `war.app did not answer the sign-in within ${Math.round(timeoutMs / 1000)} s.${after}`);
210
+ }
211
+ if (err instanceof McpToolError && err.kind === 'too_large')
212
+ throw err;
213
+ throw refusal('transport', `Could not reach war.app to sign in.${after}`);
214
+ }
215
+ for (const header of res.setCookies) {
216
+ const c = parseSetCookie(header);
217
+ if (!c)
218
+ continue;
219
+ if (c.value === null)
220
+ jar.delete(c.name);
221
+ else
222
+ jar.set(c.name, c.value);
223
+ }
224
+ return res;
225
+ };
226
+ /**
227
+ * Follow `res`'s redirects (as GETs, within war.app) until a final answer or, once the POST
228
+ * has gone, the AuthToken. Before the POST an AuthToken ends nothing: it is not this
229
+ * account's (the page phase drops it), and stopping on a redirect would read as no form.
230
+ */
231
+ const follow = async (from, first) => {
232
+ let url = from;
233
+ let res = first;
234
+ for (let n = 0;; n++) {
235
+ if (posted && jar.has(AUTH_COOKIE))
236
+ return { url, res };
237
+ const location = REDIRECTS.has(res.status) ? res.headers.location : undefined;
238
+ if (!location)
239
+ return { url, res };
240
+ let next;
241
+ try {
242
+ next = new URL(location, url);
243
+ }
244
+ catch {
245
+ throw refusal('unknown', `war.app redirected the sign-in to an address that does not parse. ${NOT_RETRIED}`);
246
+ }
247
+ if (!onWarapp(next)) {
248
+ throw refusal('unknown', `war.app redirected the sign-in away from ${ORIGIN}; it was not followed. ${NOT_RETRIED}`);
249
+ }
250
+ if (n >= MAX_REDIRECTS) {
251
+ throw refusal('unknown', `war.app redirected the sign-in more than ${MAX_REDIRECTS} times. ${NOT_RETRIED}`);
252
+ }
253
+ url = next;
254
+ res = await hop(url, 'GET');
255
+ }
256
+ };
257
+ // 1. The sign-in page, for its cookies (and to see its form before any attempt).
258
+ const page = await follow(new URL(SIGN_IN_URL), await hop(new URL(SIGN_IN_URL), 'GET'));
259
+ const pageCheck = challengeIn(page.res);
260
+ if (pageCheck)
261
+ throw pageCheck;
262
+ if (page.res.status !== 200 || !hasPasswordInput(page.res.body)) {
263
+ 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.');
264
+ }
265
+ // A session from the page alone is not this account's: only one the POST earns counts.
266
+ jar.delete(AUTH_COOKIE);
267
+ // 2. The one attempt.
268
+ const form = new URLSearchParams({ Email: creds.email.trim(), Password: creds.password, KeepSignedIn: 'on' });
269
+ posted = true;
270
+ const postUrl = new URL(SIGN_IN_URL);
271
+ const done = await follow(postUrl, await hop(postUrl, 'POST', form.toString()));
272
+ // 3. Success is the AuthToken, set on any hop.
273
+ const token = jar.get(AUTH_COOKIE);
274
+ if (token) {
275
+ if (isPlausibleAuthToken(token))
276
+ return { authToken: token };
277
+ // Kept, it would be a secret the hosted child ignores (src/direct/session.ts `hostedSession`).
278
+ 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.');
279
+ }
280
+ const check = challengeIn(done.res);
281
+ if (check)
282
+ throw check;
283
+ // The form came back (on the POST's answer, or after a redirect to the sign-in page).
284
+ if (hasPasswordInput(done.res.body)) {
285
+ 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.');
286
+ }
287
+ 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.');
288
+ }
289
+ /** `err` rebuilt with every secret scrubbed out of its message and hint, and no cause. */
290
+ function scrubbed(err, secrets) {
291
+ const e = err;
292
+ const scrub = (s) => scrubSecrets(s, secrets);
293
+ const message = scrub(typeof e?.message === 'string' ? e.message : String(err));
294
+ const kind = err instanceof McpToolError && err.kind ? err.kind : 'unknown';
295
+ return new McpToolError(message, { kind, ...(typeof e?.hint === 'string' ? { hint: scrub(e.hint) } : {}) });
296
+ }
@@ -31,27 +31,37 @@
31
31
  // errors are scrubbed BY VALUE ({@link scrubError}: message, hint, stack and
32
32
  // cause chain). The direct leg refuses to attach the cookie to any host but
33
33
  // war.app itself (no subdomain), so the token can never be sent elsewhere.
34
- // Direct mode is LOCAL-ONLY, enforced here: on a hosted child (src/hosted.ts)
35
- // {@link createDirectFirstBridge} pins the router to the browser bridge
36
- // whatever WARAPP_TRANSPORT says, and its session store reads as empty.
34
+ // Hosted (src/hosted.ts), the direct leg serves only from the AuthToken
35
+ // mcp-host captured at sign-in (WARAPP_AUTH_TOKEN, src/direct/session.ts
36
+ // `hostedSession`, in memory, never stored), with the bridge as its fallback
37
+ // exactly as locally; without that token {@link createDirectFirstBridge} pins
38
+ // the router to the browser bridge whatever WARAPP_TRANSPORT says and its
39
+ // session store reads as empty, as before (#333).
37
40
  import { detectEdgeBlock, EdgeBlockedError, McpToolError } from '@chrischall/mcp-utils';
38
41
  import { createDirectFirstTransport, readTransportMode, } from '@chrischall/mcp-utils/fetchproxy';
39
42
  import { fetchPublic } from '@chrischall/mcp-utils/netguard';
40
43
  import { isHosted } from '../hosted.js';
41
- import { SESSION_HOST, scrubError } from './session.js';
44
+ import { hostedSession, SESSION_HOST, scrubError } from './session.js';
42
45
  /** The env var pinning the transport: `direct` | `fetchproxy` | `auto` (default). */
43
46
  export const TRANSPORT_ENV = 'WARAPP_TRANSPORT';
44
47
  /** The byte cap on a direct reply (a board/standing reply is a few KB; pages tens of KB). */
45
48
  const MAX_DIRECT_BODY_BYTES = 16 * 1024 * 1024;
46
49
  /** The deadline over a direct request and its body read. */
47
50
  const DIRECT_TIMEOUT_MS = 30_000;
51
+ /**
52
+ * What to do about a signed-out host-captured session: mcp-host runs the sign-in again. Until then the
53
+ * router falls back to the browser bridge, so a paired war.app tab still serves the connection.
54
+ */
55
+ export const HOST_SIGN_IN_ADVICE = 'Use "Sign in" on this war.app connection, or reconnect it (mcp-host signs in to war.app again and captures a ' +
56
+ 'new session). Meanwhile, a war.app tab signed in and paired with the browser bridge works, since calls fall ' +
57
+ 'back to it.';
48
58
  /** No war.app session is linked — the router (in `auto`) falls back to the bridge. */
49
59
  export class SessionNotLinkedError extends McpToolError {
50
60
  name = 'SessionNotLinkedError';
51
- constructor() {
52
- super('No war.app session is linked for the direct transport. Run warapp_link_session to capture one.', {
53
- kind: 'no_credential',
54
- });
61
+ constructor(opts = {}) {
62
+ super(opts.hostSignIn
63
+ ? `This connection has no war.app session. ${HOST_SIGN_IN_ADVICE}`
64
+ : 'No war.app session is linked for the direct transport. Run warapp_link_session to capture one.', { kind: 'no_credential' });
55
65
  }
56
66
  }
57
67
  /** The linked session is no longer signed in — the router (in `auto`) falls back to the bridge. */
@@ -59,13 +69,19 @@ export class SessionExpiredError extends McpToolError {
59
69
  name = 'SessionExpiredError';
60
70
  /** When the expired session was captured (non-secret), so a relink can be told apart. */
61
71
  capturedAt;
72
+ /** The session was the one mcp-host captured: the remedy is its Sign in, not warapp_link_session. */
73
+ hostSignIn;
62
74
  constructor(opts = {}) {
63
- super('The linked war.app session is no longer signed in. ' +
75
+ const remedy = opts.hostSignIn ? HOST_SIGN_IN_ADVICE : 'Run warapp_link_session to relink.';
76
+ super((opts.hostSignIn
77
+ ? 'The war.app session this connection signed in with is no longer signed in. '
78
+ : 'The linked war.app session is no longer signed in. ') +
64
79
  (opts.notResent
65
80
  ? 'The request had already reached war.app, so it was not re-sent over the browser bridge (a write must ' +
66
- 'never be sent twice); later calls use the bridge. Retry, or run warapp_link_session to relink.'
67
- : 'Run warapp_link_session to relink.'), { kind: 'session_expired' });
81
+ `never be sent twice); later calls use the bridge. Retry, or: ${remedy}`
82
+ : remedy), { kind: 'session_expired' });
68
83
  this.capturedAt = opts.capturedAt;
84
+ this.hostSignIn = opts.hostSignIn ?? false;
69
85
  }
70
86
  }
71
87
  const decoder = new TextDecoder();
@@ -258,14 +274,18 @@ export function looksSignedOut(requestedUrl, res) {
258
274
  export class DirectBridge {
259
275
  store;
260
276
  fetchImpl;
261
- constructor(store, fetchImpl = fetchViaPublic) {
277
+ hostSignIn;
278
+ constructor(store, fetchImpl = fetchViaPublic,
279
+ /** A hosted child signed in by mcp-host: its signed-out errors point at Sign in. */
280
+ hostSignIn = false) {
262
281
  this.store = store;
263
282
  this.fetchImpl = fetchImpl;
283
+ this.hostSignIn = hostSignIn;
264
284
  }
265
285
  async fetch(init, signal) {
266
286
  const sess = await this.store.read();
267
287
  if (!sess)
268
- throw new SessionNotLinkedError();
288
+ throw new SessionNotLinkedError(this.hostSignIn ? { hostSignIn: true } : {});
269
289
  const token = sess.authToken;
270
290
  // warappUrl refuses a non-war.app host BEFORE the cookie is built.
271
291
  const url = warappUrl(init.path);
@@ -297,8 +317,9 @@ export class DirectBridge {
297
317
  });
298
318
  }
299
319
  }
300
- if (looksSignedOut(url, res))
301
- throw new SessionExpiredError({ capturedAt: sess.capturedAt });
320
+ if (looksSignedOut(url, res)) {
321
+ throw new SessionExpiredError({ capturedAt: sess.capturedAt, hostSignIn: this.hostSignIn || sess.origin === 'host' });
322
+ }
302
323
  return { status: res.status, body: res.body, url: res.url };
303
324
  }
304
325
  }
@@ -316,14 +337,21 @@ export const RELINK_CHECK_MS = 5_000;
316
337
  * is lifted when a NEW session is linked, so the direct leg is retried.
317
338
  */
318
339
  export function createDirectFirstBridge(opts) {
319
- // LOCAL-ONLY: a hosted child never rides the direct leg nor reads a stored
320
- // session, whatever WARAPP_TRANSPORT (or `mode`) says.
321
- const hosted = isHosted(opts.env ?? process.env);
322
- const mode = hosted
340
+ // A hosted child never reads a stored session. With the token mcp-host
341
+ // captured at sign-in it rides the direct leg from that token alone (the
342
+ // given store is not consulted) and resolves its mode as a local process
343
+ // does; without one it is pinned to the browser bridge whatever
344
+ // WARAPP_TRANSPORT (or `mode`) says.
345
+ const env = opts.env ?? process.env;
346
+ const hosted = isHosted(env);
347
+ const hostSession = hosted ? hostedSession(env) : null;
348
+ const pinned = hosted && !hostSession;
349
+ const mode = pinned
323
350
  ? 'fetchproxy'
324
351
  : (opts.mode ?? readTransportMode(TRANSPORT_ENV, opts.env ? { env: opts.env } : {}));
325
- const store = hosted ? { read: async () => null } : opts.store;
326
- const direct = new DirectBridge(store, opts.directFetch);
352
+ const store = hosted ? { read: async () => hostSession } : opts.store;
353
+ const hostSignIn = hostSession !== null;
354
+ const direct = new DirectBridge(store, opts.directFetch, hostSignIn);
327
355
  const log = opts.log ?? ((m) => console.error(m));
328
356
  const now = opts.now ?? Date.now;
329
357
  let wall = null;
@@ -343,7 +371,13 @@ export function createDirectFirstBridge(opts) {
343
371
  : 'the site edge refused the direct request';
344
372
  log(`[warapp-mcp] Direct transport unavailable (${why}) — switching to the ContextMint Bridge browser bridge. ` +
345
373
  `Keep a ${SESSION_HOST} tab open and approve the pairing prompt in the extension if one appears` +
346
- (next.kind === 'session' && !hosted ? '; run warapp_link_session to return to the direct transport.' : '.'));
374
+ (next.kind !== 'session'
375
+ ? '.'
376
+ : hostSignIn
377
+ ? `. ${HOST_SIGN_IN_ADVICE}`
378
+ : hosted
379
+ ? '.'
380
+ : '; run warapp_link_session to return to the direct transport.'));
347
381
  };
348
382
  const build = () => createDirectFirstTransport({
349
383
  direct,
@@ -400,8 +434,9 @@ export function createDirectFirstBridge(opts) {
400
434
  throw err;
401
435
  }
402
436
  }
403
- if (reached)
404
- throw new SessionExpiredError({ capturedAt: reached.capturedAt, notResent: true });
437
+ if (reached) {
438
+ throw new SessionExpiredError({ capturedAt: reached.capturedAt, notResent: true, hostSignIn: reached.hostSignIn });
439
+ }
405
440
  return leg.ready().then((t) => t.fetch(init));
406
441
  });
407
442
  };
package/dist/hosted.js CHANGED
@@ -3,10 +3,12 @@
3
3
  // mcp-host gives this server no explicit "hosted" flag, so a hosted child is
4
4
  // recognised by the variables only the host sets ({@link HOSTED_MARKERS}).
5
5
  // Consulted by the map statistics (always off when hosted, src/stats.ts) and by
6
- // the direct transport, which is LOCAL-ONLY: when hosted the session store
7
- // reads as empty and refuses writes (src/direct/session.ts), the router is
8
- // pinned to the browser bridge (src/direct/transport.ts), and
9
- // warapp_link_session is not registered (src/tools/session.ts).
6
+ // the direct transport: when hosted no session file is ever read or written
7
+ // (src/direct/session.ts) and warapp_link_session is not registered
8
+ // (src/tools/session.ts). The direct leg then serves only from the AuthToken
9
+ // mcp-host captured at sign-in (WARAPP_AUTH_TOKEN, in memory, #333), the
10
+ // bridge its fallback; without one the router is pinned to the browser bridge
11
+ // (src/direct/transport.ts).
10
12
  import { readEnvVar } from '@chrischall/mcp-utils';
11
13
  /**
12
14
  * Variables only a hosted child sees: mcp-host's own (its child-env contract —
@@ -75,7 +75,7 @@ export function registerMarkChatReadTool(server, ctx) {
75
75
  // The gate binds the account read fresh (the write rules); its in-game id keys the private marks.
76
76
  const me = await ctx.myIdentity({ fresh: true }).catch(() => undefined);
77
77
  if (!me)
78
- throw accountUnknown(ctx.hosted);
78
+ throw accountUnknown(ctx);
79
79
  const read = await readChat(ctx, game, me);
80
80
  // A filled web read (#313) still carries the web messages' ids; GameFeed's added lines carry none and mark nothing.
81
81
  if (!read || read.source === 'gamefeed') {
@@ -26,11 +26,17 @@ export { PROBE_GAME_ID };
26
26
  const PROBE_PATH = `/API/GameFeed?GameID=${PROBE_GAME_ID}&GetMap=false`;
27
27
  /** The page the bridge arm round-trips through the user's war.app tab. */
28
28
  export const BRIDGE_PROBE_PATH = '/';
29
- /** The non-secret facts about the linked direct session — never the token. */
29
+ /**
30
+ * The non-secret facts about the linked direct session — never the token. The
31
+ * session mcp-host captured at sign-in (hosted, #333) is `linked: true` with `linkedBy: 'host'` (`linked` stays a boolean), with
32
+ * no capture time or age: this process does not know them.
33
+ */
30
34
  function sessionSummary(env, now) {
31
35
  const s = readSessionSync(env);
32
36
  if (!s)
33
37
  return { linked: false };
38
+ if (s.origin === 'host')
39
+ return { linked: true, linkedBy: 'host' };
34
40
  const ageSeconds = Math.max(0, Math.round((now() - Date.parse(s.capturedAt)) / 1000));
35
41
  return { linked: true, capturedAt: s.capturedAt, ageSeconds };
36
42
  }