@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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +22 -4
- package/dist/bundle.js +1111 -754
- package/dist/direct/egress.js +75 -0
- package/dist/direct/link.js +9 -5
- package/dist/direct/session.js +60 -6
- package/dist/direct/sign-in.js +308 -0
- package/dist/direct/transport.js +93 -38
- package/dist/hosted.js +6 -4
- package/dist/push/websocket.js +9 -2
- package/dist/tools/chat-read-mark.js +1 -1
- package/dist/tools/healthcheck.js +7 -1
- package/dist/tools/index.js +10 -4
- package/dist/tools/join-game.js +1 -1
- package/dist/tools/live-context.js +2 -0
- package/dist/tools/my-games.js +1 -1
- package/dist/tools/open-games.js +5 -2
- package/dist/tools/session.js +50 -18
- package/dist/tools/sign-in.js +56 -0
- package/dist/tools/team-brief.js +1 -1
- package/dist/tools/team.js +1 -1
- package/dist/tools/write-kit.js +10 -3
- package/dist/version.js +1 -1
- package/docs/examples/warapp-auth-flow.json +31 -0
- package/manifest.json +1 -1
- package/mint.yaml +30 -13
- package/package.json +3 -2
- package/server.json +2 -2
package/dist/bundle.js
CHANGED
|
@@ -37974,7 +37974,7 @@ var require_proxy_agent = __commonJS({
|
|
|
37974
37974
|
return this.#client.destroy(err);
|
|
37975
37975
|
}
|
|
37976
37976
|
};
|
|
37977
|
-
var
|
|
37977
|
+
var ProxyAgent2 = class extends DispatcherBase {
|
|
37978
37978
|
constructor(opts) {
|
|
37979
37979
|
if (!opts || typeof opts === "object" && !(opts instanceof URL) && !opts.uri) {
|
|
37980
37980
|
throw new InvalidArgumentError("Proxy uri is mandatory");
|
|
@@ -38148,7 +38148,7 @@ var require_proxy_agent = __commonJS({
|
|
|
38148
38148
|
throw new InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
|
|
38149
38149
|
}
|
|
38150
38150
|
}
|
|
38151
|
-
module.exports =
|
|
38151
|
+
module.exports = ProxyAgent2;
|
|
38152
38152
|
}
|
|
38153
38153
|
});
|
|
38154
38154
|
|
|
@@ -38158,7 +38158,7 @@ var require_env_http_proxy_agent = __commonJS({
|
|
|
38158
38158
|
"use strict";
|
|
38159
38159
|
var DispatcherBase = require_dispatcher_base();
|
|
38160
38160
|
var { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require_symbols();
|
|
38161
|
-
var
|
|
38161
|
+
var ProxyAgent2 = require_proxy_agent();
|
|
38162
38162
|
var Agent2 = require_agent();
|
|
38163
38163
|
var DEFAULT_PORTS = {
|
|
38164
38164
|
"http:": 80,
|
|
@@ -38175,13 +38175,13 @@ var require_env_http_proxy_agent = __commonJS({
|
|
|
38175
38175
|
this[kNoProxyAgent] = new Agent2(agentOpts);
|
|
38176
38176
|
const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
|
|
38177
38177
|
if (HTTP_PROXY) {
|
|
38178
|
-
this[kHttpProxyAgent] = new
|
|
38178
|
+
this[kHttpProxyAgent] = new ProxyAgent2({ ...agentOpts, uri: HTTP_PROXY });
|
|
38179
38179
|
} else {
|
|
38180
38180
|
this[kHttpProxyAgent] = this[kNoProxyAgent];
|
|
38181
38181
|
}
|
|
38182
38182
|
const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY;
|
|
38183
38183
|
if (HTTPS_PROXY) {
|
|
38184
|
-
this[kHttpsProxyAgent] = new
|
|
38184
|
+
this[kHttpsProxyAgent] = new ProxyAgent2({ ...agentOpts, uri: HTTPS_PROXY });
|
|
38185
38185
|
} else {
|
|
38186
38186
|
this[kHttpsProxyAgent] = this[kHttpProxyAgent];
|
|
38187
38187
|
}
|
|
@@ -50509,7 +50509,7 @@ var require_parse3 = __commonJS({
|
|
|
50509
50509
|
var { maxNameValuePairSize, maxAttributeValueSize } = require_constants5();
|
|
50510
50510
|
var { isCTLExcludingHtab } = require_util6();
|
|
50511
50511
|
var assert2 = __require("node:assert");
|
|
50512
|
-
function
|
|
50512
|
+
function parseSetCookie2(header) {
|
|
50513
50513
|
if (isCTLExcludingHtab(header)) {
|
|
50514
50514
|
return null;
|
|
50515
50515
|
}
|
|
@@ -50632,7 +50632,7 @@ var require_parse3 = __commonJS({
|
|
|
50632
50632
|
}
|
|
50633
50633
|
}
|
|
50634
50634
|
module.exports = {
|
|
50635
|
-
parseSetCookie,
|
|
50635
|
+
parseSetCookie: parseSetCookie2,
|
|
50636
50636
|
parseUnparsedAttributes
|
|
50637
50637
|
};
|
|
50638
50638
|
}
|
|
@@ -50642,7 +50642,7 @@ var require_parse3 = __commonJS({
|
|
|
50642
50642
|
var require_cookies = __commonJS({
|
|
50643
50643
|
"node_modules/undici/lib/web/cookies/index.js"(exports, module) {
|
|
50644
50644
|
"use strict";
|
|
50645
|
-
var { parseSetCookie } = require_parse3();
|
|
50645
|
+
var { parseSetCookie: parseSetCookie2 } = require_parse3();
|
|
50646
50646
|
var { stringify } = require_util6();
|
|
50647
50647
|
var { webidl } = require_webidl();
|
|
50648
50648
|
var { Headers: Headers3 } = require_headers();
|
|
@@ -50681,11 +50681,11 @@ var require_cookies = __commonJS({
|
|
|
50681
50681
|
if (!cookies) {
|
|
50682
50682
|
return [];
|
|
50683
50683
|
}
|
|
50684
|
-
return cookies.map((pair2) =>
|
|
50684
|
+
return cookies.map((pair2) => parseSetCookie2(pair2));
|
|
50685
50685
|
}
|
|
50686
50686
|
function parseCookie(cookie) {
|
|
50687
50687
|
cookie = webidl.converters.DOMString(cookie);
|
|
50688
|
-
return
|
|
50688
|
+
return parseSetCookie2(cookie);
|
|
50689
50689
|
}
|
|
50690
50690
|
function setCookie(headers, cookie) {
|
|
50691
50691
|
webidl.argumentLengthCheck(arguments, 2, "setCookie");
|
|
@@ -53716,7 +53716,7 @@ var require_undici = __commonJS({
|
|
|
53716
53716
|
var BalancedPool = require_balanced_pool();
|
|
53717
53717
|
var RoundRobinPool = require_round_robin_pool();
|
|
53718
53718
|
var Agent2 = require_agent();
|
|
53719
|
-
var
|
|
53719
|
+
var ProxyAgent2 = require_proxy_agent();
|
|
53720
53720
|
var Socks5ProxyAgent = require_socks5_proxy_agent();
|
|
53721
53721
|
var EnvHttpProxyAgent = require_env_http_proxy_agent();
|
|
53722
53722
|
var RetryAgent = require_retry_agent();
|
|
@@ -53743,7 +53743,7 @@ var require_undici = __commonJS({
|
|
|
53743
53743
|
module.exports.BalancedPool = BalancedPool;
|
|
53744
53744
|
module.exports.RoundRobinPool = RoundRobinPool;
|
|
53745
53745
|
module.exports.Agent = Agent2;
|
|
53746
|
-
module.exports.ProxyAgent =
|
|
53746
|
+
module.exports.ProxyAgent = ProxyAgent2;
|
|
53747
53747
|
module.exports.Socks5ProxyAgent = Socks5ProxyAgent;
|
|
53748
53748
|
module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent;
|
|
53749
53749
|
module.exports.RetryAgent = RetryAgent;
|
|
@@ -69811,8 +69811,8 @@ function truncateErrorMessage(text, max = DEFAULT_ERROR_MESSAGE_MAX, opts = {})
|
|
|
69811
69811
|
const str = text === null || text === void 0 ? "" : String(text);
|
|
69812
69812
|
const cap = Math.max(ERROR_REDACTION_INPUT_MAX, max);
|
|
69813
69813
|
const capped = str.length > cap ? str.slice(0, cap) : str;
|
|
69814
|
-
const
|
|
69815
|
-
const redacted = redactSecrets(
|
|
69814
|
+
const scrubbed2 = opts.values !== void 0 ? redactValues(capped, opts.values, opts.placeholder !== void 0 ? { placeholder: opts.placeholder } : {}) : capped;
|
|
69815
|
+
const redacted = redactSecrets(scrubbed2);
|
|
69816
69816
|
if (redacted.length <= max)
|
|
69817
69817
|
return redacted;
|
|
69818
69818
|
return `${redacted.slice(0, max)}\u2026 [truncated]`;
|
|
@@ -91148,9 +91148,9 @@ function detectEdgeBlock(input2) {
|
|
|
91148
91148
|
const body = input2.body?.slice(0, EDGE_BLOCK_SCAN_MAX);
|
|
91149
91149
|
if (!body)
|
|
91150
91150
|
return null;
|
|
91151
|
-
const
|
|
91151
|
+
const refusal3 = input2.status === void 0 || input2.status >= 400 && input2.status < 500;
|
|
91152
91152
|
for (const marker of EDGE_BLOCK_MARKERS) {
|
|
91153
|
-
if ((marker.anyStatus ||
|
|
91153
|
+
if ((marker.anyStatus || refusal3) && marker.test(body))
|
|
91154
91154
|
return { vendor: marker.vendor };
|
|
91155
91155
|
}
|
|
91156
91156
|
return null;
|
|
@@ -120915,7 +120915,7 @@ async function startHost(opts) {
|
|
|
120915
120915
|
}
|
|
120916
120916
|
if (frame.type === "hello-rejected" && identified === "extension") {
|
|
120917
120917
|
if (frame.mcpId === opts.ownMcpId) {
|
|
120918
|
-
const
|
|
120918
|
+
const refusal3 = new FetchproxyHelloRejectedError({
|
|
120919
120919
|
mcpId: frame.mcpId,
|
|
120920
120920
|
reason: frame.reason,
|
|
120921
120921
|
platform: extensionHello?.platform ?? null
|
|
@@ -120923,8 +120923,8 @@ async function startHost(opts) {
|
|
|
120923
120923
|
if (ownRetryableRefusal)
|
|
120924
120924
|
resetSessionPromise();
|
|
120925
120925
|
const settlesPending = !ownSessionSettled;
|
|
120926
|
-
rejectOwnSession(
|
|
120927
|
-
if (
|
|
120926
|
+
rejectOwnSession(refusal3);
|
|
120927
|
+
if (refusal3.retryable && settlesPending)
|
|
120928
120928
|
ownRetryableRefusal = true;
|
|
120929
120929
|
} else {
|
|
120930
120930
|
const slot = peers.get(frame.mcpId);
|
|
@@ -121315,7 +121315,7 @@ async function startPeer(opts) {
|
|
|
121315
121315
|
return;
|
|
121316
121316
|
}
|
|
121317
121317
|
if (frame.type === "hello-rejected" && frame.mcpId === opts.mcpId) {
|
|
121318
|
-
const
|
|
121318
|
+
const refusal3 = new FetchproxyHelloRejectedError({
|
|
121319
121319
|
mcpId: frame.mcpId,
|
|
121320
121320
|
reason: frame.reason,
|
|
121321
121321
|
platform: extensionHello?.platform ?? null
|
|
@@ -121323,8 +121323,8 @@ async function startPeer(opts) {
|
|
|
121323
121323
|
if (retryableRefusal)
|
|
121324
121324
|
resetSessionPromise();
|
|
121325
121325
|
const settlesPending = !sessionPromiseSettled;
|
|
121326
|
-
rejectFirstReady(
|
|
121327
|
-
if (
|
|
121326
|
+
rejectFirstReady(refusal3);
|
|
121327
|
+
if (refusal3.retryable && settlesPending)
|
|
121328
121328
|
retryableRefusal = true;
|
|
121329
121329
|
}
|
|
121330
121330
|
if (frame.type === "pair-pending" && frame.mcpId === opts.mcpId) {
|
|
@@ -124776,7 +124776,7 @@ async function captureBearerHeader(opts) {
|
|
|
124776
124776
|
}
|
|
124777
124777
|
|
|
124778
124778
|
// src/version.ts
|
|
124779
|
-
var VERSION2 = "0.
|
|
124779
|
+
var VERSION2 = "0.3.1";
|
|
124780
124780
|
|
|
124781
124781
|
// src/transport-bridge.ts
|
|
124782
124782
|
var SERVER_NAME = "warapp-mcp";
|
|
@@ -124799,6 +124799,165 @@ function createWarappBridge(opts = {}) {
|
|
|
124799
124799
|
return createLazyTransport(() => createBridgeTransport(opts));
|
|
124800
124800
|
}
|
|
124801
124801
|
|
|
124802
|
+
// src/direct/session.ts
|
|
124803
|
+
import { execFile } from "node:child_process";
|
|
124804
|
+
import { randomBytes as randomBytes7 } from "node:crypto";
|
|
124805
|
+
import { readFileSync as readFileSync2 } from "node:fs";
|
|
124806
|
+
import { chmod as chmod4, mkdir as mkdir7, open as open2, readFile as readFile8, rename as rename7, rm as rm4, stat as stat4 } from "node:fs/promises";
|
|
124807
|
+
import { dirname, join as join11, resolve } from "node:path";
|
|
124808
|
+
import { promisify } from "node:util";
|
|
124809
|
+
var SESSION_HOST = "war.app";
|
|
124810
|
+
var HOST_TOKEN_ENV = "WARAPP_AUTH_TOKEN";
|
|
124811
|
+
var HOST_CAPTURED_AT = "captured by the host";
|
|
124812
|
+
var HOST_TOKEN_SHAPE = /^[\x21-\x7e]{16,4096}$/;
|
|
124813
|
+
var HOST_TOKEN_FORBIDDEN = /[;,"\\]/;
|
|
124814
|
+
function hostTokenValue(env) {
|
|
124815
|
+
const raw = readEnvVar(HOST_TOKEN_ENV, { env });
|
|
124816
|
+
if (raw === void 0) return void 0;
|
|
124817
|
+
return raw.trim().replace(/^AuthToken=/, "");
|
|
124818
|
+
}
|
|
124819
|
+
function hostedTokenState(env = process.env) {
|
|
124820
|
+
if (!isHosted(env)) return "none";
|
|
124821
|
+
const v = hostTokenValue(env);
|
|
124822
|
+
if (v === void 0) return "none";
|
|
124823
|
+
return isPlausibleAuthToken(v) ? "ok" : "malformed";
|
|
124824
|
+
}
|
|
124825
|
+
function isPlausibleAuthToken(v) {
|
|
124826
|
+
return HOST_TOKEN_SHAPE.test(v) && !HOST_TOKEN_FORBIDDEN.test(v);
|
|
124827
|
+
}
|
|
124828
|
+
function hostedSession(env = process.env) {
|
|
124829
|
+
if (hostedTokenState(env) !== "ok") return null;
|
|
124830
|
+
return { authToken: hostTokenValue(env), capturedAt: HOST_CAPTURED_AT, host: SESSION_HOST, origin: "host" };
|
|
124831
|
+
}
|
|
124832
|
+
var isRec6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
124833
|
+
function sessionFilePath(env = process.env) {
|
|
124834
|
+
return readEnvVar("WARAPP_SESSION_FILE", { env }) ?? join11(dataDir(env), "session.json");
|
|
124835
|
+
}
|
|
124836
|
+
function parseSession(raw) {
|
|
124837
|
+
if (!isRec6(raw)) return null;
|
|
124838
|
+
const { authToken, capturedAt, host } = raw;
|
|
124839
|
+
if (typeof authToken !== "string" || authToken.length === 0) return null;
|
|
124840
|
+
if (typeof capturedAt !== "string" || capturedAt.length === 0) return null;
|
|
124841
|
+
if (host !== SESSION_HOST) return null;
|
|
124842
|
+
return { authToken, capturedAt, host };
|
|
124843
|
+
}
|
|
124844
|
+
async function readSession(env = process.env) {
|
|
124845
|
+
if (isHosted(env)) return hostedSession(env);
|
|
124846
|
+
try {
|
|
124847
|
+
return parseSession(JSON.parse(await readFile8(sessionFilePath(env), "utf8")));
|
|
124848
|
+
} catch {
|
|
124849
|
+
return null;
|
|
124850
|
+
}
|
|
124851
|
+
}
|
|
124852
|
+
function readSessionSync(env = process.env) {
|
|
124853
|
+
if (isHosted(env)) return hostedSession(env);
|
|
124854
|
+
try {
|
|
124855
|
+
return parseSession(JSON.parse(readFileSync2(sessionFilePath(env), "utf8")));
|
|
124856
|
+
} catch {
|
|
124857
|
+
return null;
|
|
124858
|
+
}
|
|
124859
|
+
}
|
|
124860
|
+
function sessionDirVerdict(st, myUid) {
|
|
124861
|
+
if (myUid === void 0) return "ok";
|
|
124862
|
+
if (st.uid === myUid) return (st.mode & 63) !== 0 ? "tighten" : "ok";
|
|
124863
|
+
if (st.uid !== 0) return "refuse";
|
|
124864
|
+
return (st.mode & 18) !== 0 ? "refuse" : "ok";
|
|
124865
|
+
}
|
|
124866
|
+
var run = promisify(execFile);
|
|
124867
|
+
var MACOS_ACLS = process.platform === "darwin";
|
|
124868
|
+
function lsShowsAcl(stdout) {
|
|
124869
|
+
return stdout.split("\n").slice(1).some((line) => /^\s*\d+: /.test(line));
|
|
124870
|
+
}
|
|
124871
|
+
async function hasAcl(path) {
|
|
124872
|
+
const { stdout } = await run("/bin/ls", ["-led", path]);
|
|
124873
|
+
return lsShowsAcl(stdout);
|
|
124874
|
+
}
|
|
124875
|
+
async function stripAcl(path, what) {
|
|
124876
|
+
await run("/bin/chmod", ["-N", path]);
|
|
124877
|
+
if (await hasAcl(path)) {
|
|
124878
|
+
throw new McpToolError(`Refusing to store the war.app session: could not remove the access control list on ${what}.`, {
|
|
124879
|
+
hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory only you can read, with no ACL (`ls -le`)."
|
|
124880
|
+
});
|
|
124881
|
+
}
|
|
124882
|
+
}
|
|
124883
|
+
function sessionTmpPath(path) {
|
|
124884
|
+
return `${path}.${randomBytes7(16).toString("hex")}.tmp`;
|
|
124885
|
+
}
|
|
124886
|
+
async function writeSession(session, env = process.env) {
|
|
124887
|
+
if (isHosted(env)) {
|
|
124888
|
+
throw new McpToolError(
|
|
124889
|
+
"A hosted server never stores a war.app session: its session is the one mcp-host captured at sign-in.",
|
|
124890
|
+
{
|
|
124891
|
+
kind: "unknown"
|
|
124892
|
+
}
|
|
124893
|
+
);
|
|
124894
|
+
}
|
|
124895
|
+
const path = resolve(sessionFilePath(env));
|
|
124896
|
+
const dir = dirname(path);
|
|
124897
|
+
await mkdir7(dir, { recursive: true, mode: 448 });
|
|
124898
|
+
const st = await stat4(dir);
|
|
124899
|
+
const myUid = process.getuid?.();
|
|
124900
|
+
const verdict = sessionDirVerdict(st, myUid);
|
|
124901
|
+
if (verdict === "refuse") {
|
|
124902
|
+
throw new McpToolError(`Refusing to store the war.app session in ${dir}: it is not yours, and others could reach files in it.`, {
|
|
124903
|
+
hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory of your own that only you can write to."
|
|
124904
|
+
});
|
|
124905
|
+
}
|
|
124906
|
+
if (verdict === "tighten") await chmod4(dir, 448);
|
|
124907
|
+
if (MACOS_ACLS) {
|
|
124908
|
+
if (st.uid === myUid) await stripAcl(dir, dir);
|
|
124909
|
+
else if (await hasAcl(dir)) {
|
|
124910
|
+
throw new McpToolError(`Refusing to store the war.app session in ${dir}: it carries an access control list and is not yours.`, {
|
|
124911
|
+
hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory of your own that only you can read."
|
|
124912
|
+
});
|
|
124913
|
+
}
|
|
124914
|
+
}
|
|
124915
|
+
const tmp = sessionTmpPath(path);
|
|
124916
|
+
const file2 = await open2(tmp, "wx", 384);
|
|
124917
|
+
try {
|
|
124918
|
+
try {
|
|
124919
|
+
await file2.chmod(384);
|
|
124920
|
+
if (MACOS_ACLS) await stripAcl(tmp, "the session file");
|
|
124921
|
+
await file2.writeFile(JSON.stringify(session));
|
|
124922
|
+
} finally {
|
|
124923
|
+
await file2.close();
|
|
124924
|
+
}
|
|
124925
|
+
await rename7(tmp, path);
|
|
124926
|
+
} catch (e) {
|
|
124927
|
+
await rm4(tmp, { force: true }).catch(() => {
|
|
124928
|
+
});
|
|
124929
|
+
throw e;
|
|
124930
|
+
}
|
|
124931
|
+
}
|
|
124932
|
+
var SCRUBBED = "[warapp-session]";
|
|
124933
|
+
function scrubToken(s, token) {
|
|
124934
|
+
if (!token) return s;
|
|
124935
|
+
return scrubSecrets(s, [token, stripBearer(token)], SCRUBBED);
|
|
124936
|
+
}
|
|
124937
|
+
function errorStrings(err, depth = 0) {
|
|
124938
|
+
if (depth > 4 || typeof err !== "object" || err === null) return typeof err === "string" ? [err] : [];
|
|
124939
|
+
const e = err;
|
|
124940
|
+
const own2 = [e.message, e.hint, e.stack].filter((v) => typeof v === "string");
|
|
124941
|
+
return [...own2, ...errorStrings(e.cause, depth + 1)];
|
|
124942
|
+
}
|
|
124943
|
+
function errorCarriesToken(err, tokens) {
|
|
124944
|
+
const strings = errorStrings(err);
|
|
124945
|
+
return tokens.some((t) => !!t && strings.some((s) => scrubToken(s, t) !== s));
|
|
124946
|
+
}
|
|
124947
|
+
function scrubError(err, tokens) {
|
|
124948
|
+
if (!errorCarriesToken(err, tokens)) return err;
|
|
124949
|
+
const ordered = tokens.filter((t) => !!t).sort((a, b) => b.length - a.length);
|
|
124950
|
+
const scrub = (s) => ordered.reduce((acc, t) => scrubToken(acc, t), s);
|
|
124951
|
+
const e = typeof err === "object" && err !== null ? err : {};
|
|
124952
|
+
const message = scrub(typeof e.message === "string" ? e.message : String(err));
|
|
124953
|
+
const kind = err instanceof McpToolError && err.kind ? err.kind : "transport";
|
|
124954
|
+
return new McpToolError(message, {
|
|
124955
|
+
kind,
|
|
124956
|
+
...typeof e.status === "number" ? { status: e.status } : {},
|
|
124957
|
+
...typeof e.hint === "string" ? { hint: scrub(e.hint) } : {}
|
|
124958
|
+
});
|
|
124959
|
+
}
|
|
124960
|
+
|
|
124802
124961
|
// src/tools/live-context.ts
|
|
124803
124962
|
function parseInviteTokenText(html) {
|
|
124804
124963
|
const m = /Your invite token is\s*(\d{5,20})/.exec(html);
|
|
@@ -124952,6 +125111,7 @@ function createLiveContext(opts) {
|
|
|
124952
125111
|
fetchPage: fetchText,
|
|
124953
125112
|
dataDir: dir,
|
|
124954
125113
|
hosted: isHosted(opts.env ?? process.env),
|
|
125114
|
+
hostSignIn: hostedSession(opts.env ?? process.env) !== null,
|
|
124955
125115
|
client: opts.client,
|
|
124956
125116
|
rpc,
|
|
124957
125117
|
decoderReport: () => lastBundle?.report?.(),
|
|
@@ -125034,6 +125194,471 @@ async function loadPicks(ctx, gameId, inGamePlayerId) {
|
|
|
125034
125194
|
return readTerritoryPicks(env.body);
|
|
125035
125195
|
}
|
|
125036
125196
|
|
|
125197
|
+
// node_modules/@chrischall/mcp-utils/dist/netguard/index.js
|
|
125198
|
+
var import_undici = __toESM(require_undici(), 1);
|
|
125199
|
+
import { lookup as dnsLookup } from "node:dns/promises";
|
|
125200
|
+
import { isIP as isIP2 } from "node:net";
|
|
125201
|
+
var systemResolver = async (hostname3) => (await dnsLookup(hostname3, { all: true, verbatim: true })).map((a) => a.address);
|
|
125202
|
+
function refuseHost(hostname3) {
|
|
125203
|
+
return new UrlNotAllowedError(`Refusing to connect to ${hostname3}: it is, or resolves to, a private, loopback, link-local or reserved address.`, "host");
|
|
125204
|
+
}
|
|
125205
|
+
function createPublicOnlyDispatcher(opts = {}) {
|
|
125206
|
+
const resolve2 = opts.resolve ?? systemResolver;
|
|
125207
|
+
const allowed = opts.isAllowedAddress ?? isPublicAddress;
|
|
125208
|
+
const lookup = (hostname3, options, callback2) => {
|
|
125209
|
+
resolve2(hostname3).then((addresses) => {
|
|
125210
|
+
if (addresses.length === 0 || !addresses.every(allowed)) {
|
|
125211
|
+
callback2(refuseHost(hostname3), "", 0);
|
|
125212
|
+
return;
|
|
125213
|
+
}
|
|
125214
|
+
const entries2 = addresses.map((address) => ({ address, family: isIP2(address) }));
|
|
125215
|
+
if (options.all) {
|
|
125216
|
+
callback2(null, entries2);
|
|
125217
|
+
return;
|
|
125218
|
+
}
|
|
125219
|
+
const wanted = options.family === 4 || options.family === 6 ? options.family : 0;
|
|
125220
|
+
const pick5 = entries2.find((e) => wanted === 0 || e.family === wanted) ?? entries2[0];
|
|
125221
|
+
callback2(null, pick5.address, pick5.family);
|
|
125222
|
+
}, (err) => callback2(err, "", 0));
|
|
125223
|
+
};
|
|
125224
|
+
const inner = (0, import_undici.buildConnector)({ ...opts.connect, lookup });
|
|
125225
|
+
const connect = (options, callback2) => {
|
|
125226
|
+
const host = options.hostname.replace(/^\[|\]$/g, "");
|
|
125227
|
+
if (isIP2(host) !== 0 && !allowed(host)) {
|
|
125228
|
+
callback2(refuseHost(options.hostname), null);
|
|
125229
|
+
return;
|
|
125230
|
+
}
|
|
125231
|
+
inner(options, callback2);
|
|
125232
|
+
};
|
|
125233
|
+
return new import_undici.Agent({ ...opts.agent, connect });
|
|
125234
|
+
}
|
|
125235
|
+
var REDIRECT_STATUSES2 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
125236
|
+
var CROSS_ORIGIN_DROPPED = ["authorization", "cookie", "proxy-authorization"];
|
|
125237
|
+
function findUrlRefusal(err) {
|
|
125238
|
+
let e = err;
|
|
125239
|
+
for (let i2 = 0; i2 < 8 && e; i2 += 1) {
|
|
125240
|
+
if (e instanceof UrlNotAllowedError)
|
|
125241
|
+
return e;
|
|
125242
|
+
e = e.cause;
|
|
125243
|
+
}
|
|
125244
|
+
return void 0;
|
|
125245
|
+
}
|
|
125246
|
+
async function fetchPublic(url4, opts = {}) {
|
|
125247
|
+
const { maxRedirects = 10, timeoutMs, maxBytes, signal: callerSignal, dispatcher: given2, requireHttps, allowHosts, stopBefore, resolve: resolve2, isAllowedAddress, headers: initHeaders, method: initMethod, body: initBody, ...init } = opts;
|
|
125248
|
+
if (!Number.isInteger(maxRedirects) || maxRedirects < 0) {
|
|
125249
|
+
throw new TypeError("fetchPublic: maxRedirects must be a non-negative integer.");
|
|
125250
|
+
}
|
|
125251
|
+
const check2 = (target) => assertAllowedUrl(target, {
|
|
125252
|
+
allowHosts: allowHosts ?? [/(?:)/],
|
|
125253
|
+
...requireHttps !== void 0 ? { requireHttps } : {}
|
|
125254
|
+
});
|
|
125255
|
+
let current2 = check2(url4);
|
|
125256
|
+
const origin = current2.origin;
|
|
125257
|
+
if (stopBefore?.(current2))
|
|
125258
|
+
return { stopped: true, url: current2.href, hops: 0 };
|
|
125259
|
+
const timeout = timeoutMs !== void 0 ? AbortSignal.timeout(timeoutMs) : void 0;
|
|
125260
|
+
const signals = [callerSignal, timeout].filter((s) => s !== void 0);
|
|
125261
|
+
const signal = signals.length > 0 ? AbortSignal.any(signals) : void 0;
|
|
125262
|
+
const owned = given2 === void 0 ? createPublicOnlyDispatcher({
|
|
125263
|
+
...resolve2 ? { resolve: resolve2 } : {},
|
|
125264
|
+
...isAllowedAddress ? { isAllowedAddress } : {}
|
|
125265
|
+
}) : void 0;
|
|
125266
|
+
const dispatcher = given2 ?? owned;
|
|
125267
|
+
let method = (initMethod ?? "GET").toUpperCase();
|
|
125268
|
+
let body = initBody;
|
|
125269
|
+
const headers = new import_undici.Headers(initHeaders);
|
|
125270
|
+
const fail = (err) => {
|
|
125271
|
+
if (callerSignal?.aborted)
|
|
125272
|
+
throw callerSignal.reason;
|
|
125273
|
+
if (timeout?.aborted)
|
|
125274
|
+
throw new RequestTimeoutError(current2.host, timeoutMs);
|
|
125275
|
+
const refused = findUrlRefusal(err);
|
|
125276
|
+
if (refused)
|
|
125277
|
+
throw refused;
|
|
125278
|
+
if (err instanceof McpToolError)
|
|
125279
|
+
throw err;
|
|
125280
|
+
throw new McpToolError(`Could not reach ${current2.host}.`, {
|
|
125281
|
+
kind: "transport",
|
|
125282
|
+
hint: "Check the link is reachable from the server.",
|
|
125283
|
+
cause: err
|
|
125284
|
+
});
|
|
125285
|
+
};
|
|
125286
|
+
try {
|
|
125287
|
+
for (let hops = 0; ; ) {
|
|
125288
|
+
let res;
|
|
125289
|
+
try {
|
|
125290
|
+
res = await (0, import_undici.fetch)(current2, {
|
|
125291
|
+
...init,
|
|
125292
|
+
method,
|
|
125293
|
+
headers,
|
|
125294
|
+
...body !== void 0 && body !== null ? { body } : {},
|
|
125295
|
+
redirect: "manual",
|
|
125296
|
+
dispatcher,
|
|
125297
|
+
...signal ? { signal } : {}
|
|
125298
|
+
});
|
|
125299
|
+
} catch (err) {
|
|
125300
|
+
return fail(err);
|
|
125301
|
+
}
|
|
125302
|
+
const location = REDIRECT_STATUSES2.has(res.status) ? res.headers.get("location") : null;
|
|
125303
|
+
if (location === null) {
|
|
125304
|
+
let bytes;
|
|
125305
|
+
try {
|
|
125306
|
+
bytes = await readBytesCapped(res, maxBytes, current2.host, (p) => p);
|
|
125307
|
+
} catch (err) {
|
|
125308
|
+
return fail(err);
|
|
125309
|
+
}
|
|
125310
|
+
return { stopped: false, url: current2.href, hops, status: res.status, headers: res.headers, body: bytes };
|
|
125311
|
+
}
|
|
125312
|
+
await res.body?.cancel().catch(() => {
|
|
125313
|
+
});
|
|
125314
|
+
if (hops >= maxRedirects) {
|
|
125315
|
+
throw new RedirectRefusedError(`Refusing to follow more than ${maxRedirects} redirects (last from ${current2.host}).`);
|
|
125316
|
+
}
|
|
125317
|
+
let next;
|
|
125318
|
+
try {
|
|
125319
|
+
next = new URL(location, current2);
|
|
125320
|
+
} catch {
|
|
125321
|
+
throw new UrlNotAllowedError("The redirect target is not a valid URL.", "invalid");
|
|
125322
|
+
}
|
|
125323
|
+
next = check2(next);
|
|
125324
|
+
hops += 1;
|
|
125325
|
+
if (res.status === 303 || (res.status === 301 || res.status === 302) && method === "POST") {
|
|
125326
|
+
if (method !== "HEAD")
|
|
125327
|
+
method = "GET";
|
|
125328
|
+
body = void 0;
|
|
125329
|
+
for (const h of ["content-type", "content-length", "content-encoding", "content-language", "content-location"]) {
|
|
125330
|
+
headers.delete(h);
|
|
125331
|
+
}
|
|
125332
|
+
}
|
|
125333
|
+
if (next.origin !== origin)
|
|
125334
|
+
for (const h of CROSS_ORIGIN_DROPPED)
|
|
125335
|
+
headers.delete(h);
|
|
125336
|
+
current2 = next;
|
|
125337
|
+
if (stopBefore?.(current2))
|
|
125338
|
+
return { stopped: true, url: current2.href, hops };
|
|
125339
|
+
}
|
|
125340
|
+
} finally {
|
|
125341
|
+
if (owned)
|
|
125342
|
+
await owned.destroy().catch(() => {
|
|
125343
|
+
});
|
|
125344
|
+
}
|
|
125345
|
+
}
|
|
125346
|
+
|
|
125347
|
+
// src/direct/egress.ts
|
|
125348
|
+
var import_undici2 = __toESM(require_undici(), 1);
|
|
125349
|
+
var EGRESS_PROXY_ENV = ["HTTPS_PROXY", "https_proxy"];
|
|
125350
|
+
var EGRESS_PROXY_INVALID = "HTTPS_PROXY is set but is not a usable http(s) proxy URL";
|
|
125351
|
+
var defaultProxyAgent = (url4) => new import_undici2.ProxyAgent(url4.href);
|
|
125352
|
+
var rawProxy = (env) => {
|
|
125353
|
+
for (const key of EGRESS_PROXY_ENV) {
|
|
125354
|
+
const v = readEnvVar(key, { env });
|
|
125355
|
+
if (v !== void 0) return v;
|
|
125356
|
+
}
|
|
125357
|
+
return void 0;
|
|
125358
|
+
};
|
|
125359
|
+
function egressProxyConfigured(env = process.env) {
|
|
125360
|
+
return rawProxy(env) !== void 0;
|
|
125361
|
+
}
|
|
125362
|
+
function egressProxyUrl(env = process.env) {
|
|
125363
|
+
const raw = rawProxy(env);
|
|
125364
|
+
if (raw === void 0) return void 0;
|
|
125365
|
+
let url4;
|
|
125366
|
+
try {
|
|
125367
|
+
url4 = new URL(raw);
|
|
125368
|
+
} catch {
|
|
125369
|
+
url4 = void 0;
|
|
125370
|
+
}
|
|
125371
|
+
if (!url4 || url4.protocol !== "http:" && url4.protocol !== "https:" || !url4.hostname) {
|
|
125372
|
+
throw new McpToolError(`${EGRESS_PROXY_INVALID}, so nothing was sent to war.app.`, {
|
|
125373
|
+
kind: "unknown",
|
|
125374
|
+
hint: "Set HTTPS_PROXY to a proxy URL such as http://127.0.0.1:8080, or unset it to connect directly."
|
|
125375
|
+
});
|
|
125376
|
+
}
|
|
125377
|
+
return url4;
|
|
125378
|
+
}
|
|
125379
|
+
function egressDispatcher(env = process.env, make = defaultProxyAgent) {
|
|
125380
|
+
const url4 = egressProxyUrl(env);
|
|
125381
|
+
return url4 ? make(url4) : void 0;
|
|
125382
|
+
}
|
|
125383
|
+
|
|
125384
|
+
// src/direct/transport.ts
|
|
125385
|
+
var TRANSPORT_ENV = "WARAPP_TRANSPORT";
|
|
125386
|
+
var MAX_DIRECT_BODY_BYTES = 16 * 1024 * 1024;
|
|
125387
|
+
var DIRECT_TIMEOUT_MS = 3e4;
|
|
125388
|
+
var 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 new session). Meanwhile, a war.app tab signed in and paired with the browser bridge works, since calls fall back to it.';
|
|
125389
|
+
var SessionNotLinkedError = class extends McpToolError {
|
|
125390
|
+
name = "SessionNotLinkedError";
|
|
125391
|
+
constructor(opts = {}) {
|
|
125392
|
+
super(
|
|
125393
|
+
opts.hostSignIn ? `This connection has no war.app session. ${HOST_SIGN_IN_ADVICE}` : "No war.app session is linked for the direct transport. Run warapp_link_session to capture one.",
|
|
125394
|
+
{ kind: "no_credential" }
|
|
125395
|
+
);
|
|
125396
|
+
}
|
|
125397
|
+
};
|
|
125398
|
+
var SessionExpiredError = class extends McpToolError {
|
|
125399
|
+
name = "SessionExpiredError";
|
|
125400
|
+
/** When the expired session was captured (non-secret), so a relink can be told apart. */
|
|
125401
|
+
capturedAt;
|
|
125402
|
+
/** The session was the one mcp-host captured: the remedy is its Sign in, not warapp_link_session. */
|
|
125403
|
+
hostSignIn;
|
|
125404
|
+
constructor(opts = {}) {
|
|
125405
|
+
const remedy = opts.hostSignIn ? HOST_SIGN_IN_ADVICE : "Run warapp_link_session to relink.";
|
|
125406
|
+
super(
|
|
125407
|
+
(opts.hostSignIn ? "The war.app session this connection signed in with is no longer signed in. " : "The linked war.app session is no longer signed in. ") + (opts.notResent ? `The request had already reached war.app, so it was not re-sent over the browser bridge (a write must never be sent twice); later calls use the bridge. Retry, or: ${remedy}` : remedy),
|
|
125408
|
+
{ kind: "session_expired" }
|
|
125409
|
+
);
|
|
125410
|
+
this.capturedAt = opts.capturedAt;
|
|
125411
|
+
this.hostSignIn = opts.hostSignIn ?? false;
|
|
125412
|
+
}
|
|
125413
|
+
};
|
|
125414
|
+
var decoder = new TextDecoder();
|
|
125415
|
+
var isSafeToReplay = (method) => /^(?:GET|HEAD)$/i.test(method);
|
|
125416
|
+
var SESSION_ORIGIN = `https://${SESSION_HOST}`;
|
|
125417
|
+
var MAX_DIRECT_GET_REDIRECTS = 5;
|
|
125418
|
+
var UNFOLLOWED_REDIRECT_STATUS = 302;
|
|
125419
|
+
function directFetchOptions(method) {
|
|
125420
|
+
const base = { requireHttps: true, allowHosts: [SESSION_HOST] };
|
|
125421
|
+
if (isSafeToReplay(method)) {
|
|
125422
|
+
return { ...base, maxRedirects: MAX_DIRECT_GET_REDIRECTS, stopBefore: (url4) => url4.origin !== SESSION_ORIGIN };
|
|
125423
|
+
}
|
|
125424
|
+
let first = true;
|
|
125425
|
+
return {
|
|
125426
|
+
...base,
|
|
125427
|
+
maxRedirects: 1,
|
|
125428
|
+
stopBefore: () => {
|
|
125429
|
+
if (first) {
|
|
125430
|
+
first = false;
|
|
125431
|
+
return false;
|
|
125432
|
+
}
|
|
125433
|
+
return true;
|
|
125434
|
+
}
|
|
125435
|
+
};
|
|
125436
|
+
}
|
|
125437
|
+
function toDirectResult(res) {
|
|
125438
|
+
if ("stopped" in res && res.stopped) return { status: UNFOLLOWED_REDIRECT_STATUS, body: "", url: res.url };
|
|
125439
|
+
const done = res;
|
|
125440
|
+
const out = { status: done.status, body: decoder.decode(done.body), url: done.url };
|
|
125441
|
+
if (done.headers) {
|
|
125442
|
+
const headers = {};
|
|
125443
|
+
done.headers.forEach((v, k) => {
|
|
125444
|
+
headers[k.toLowerCase()] = v;
|
|
125445
|
+
});
|
|
125446
|
+
out.headers = headers;
|
|
125447
|
+
}
|
|
125448
|
+
return out;
|
|
125449
|
+
}
|
|
125450
|
+
function createDirectFetch(opts = {}) {
|
|
125451
|
+
return async (url4, init) => {
|
|
125452
|
+
const proxy = egressDispatcher(opts.env ?? process.env, opts.proxyAgent);
|
|
125453
|
+
try {
|
|
125454
|
+
const res = await fetchPublic(url4, {
|
|
125455
|
+
...directFetchOptions(init.method),
|
|
125456
|
+
method: init.method,
|
|
125457
|
+
headers: init.headers,
|
|
125458
|
+
maxBytes: MAX_DIRECT_BODY_BYTES,
|
|
125459
|
+
timeoutMs: DIRECT_TIMEOUT_MS,
|
|
125460
|
+
...init.body !== void 0 ? { body: init.body } : {},
|
|
125461
|
+
...init.signal ? { signal: init.signal } : {},
|
|
125462
|
+
...proxy ? { dispatcher: proxy } : {}
|
|
125463
|
+
});
|
|
125464
|
+
return toDirectResult(res);
|
|
125465
|
+
} finally {
|
|
125466
|
+
await proxy?.close().catch(() => {
|
|
125467
|
+
});
|
|
125468
|
+
}
|
|
125469
|
+
};
|
|
125470
|
+
}
|
|
125471
|
+
var fetchViaPublic = createDirectFetch();
|
|
125472
|
+
function warappUrl(path) {
|
|
125473
|
+
const raw = /^https?:\/\//i.test(path) ? path : `https://${SESSION_HOST}${path.startsWith("/") ? "" : "/"}${path}`;
|
|
125474
|
+
let u;
|
|
125475
|
+
try {
|
|
125476
|
+
u = new URL(raw);
|
|
125477
|
+
} catch {
|
|
125478
|
+
throw new McpToolError(`The direct transport could not parse the request path.`, { kind: "unknown" });
|
|
125479
|
+
}
|
|
125480
|
+
if (u.hostname !== SESSION_HOST || u.port !== "" || u.username !== "" || u.password !== "") {
|
|
125481
|
+
throw new McpToolError(`The direct transport only talks to ${SESSION_HOST}.`, { kind: "unknown" });
|
|
125482
|
+
}
|
|
125483
|
+
if (u.protocol !== "https:") {
|
|
125484
|
+
throw new McpToolError("The direct transport requires https.", { kind: "unknown" });
|
|
125485
|
+
}
|
|
125486
|
+
return u.href;
|
|
125487
|
+
}
|
|
125488
|
+
var SIGNIN_PATH = /\/(?:sign-?in|log-?in)\b/i;
|
|
125489
|
+
var INPUT_TAG = /<input(?=[\s/>])/gi;
|
|
125490
|
+
var TAG_ATTR = /\s*(?:(>)|([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>`=]+)))?|\/)/y;
|
|
125491
|
+
var NOT_MARKUP = /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title)\b[^>]*(?:>|$)[\s\S]*?(?:<\/\1\s*>|$)/gi;
|
|
125492
|
+
function hasPasswordInput(raw) {
|
|
125493
|
+
const body = raw.replace(NOT_MARKUP, " ");
|
|
125494
|
+
INPUT_TAG.lastIndex = 0;
|
|
125495
|
+
for (let m = INPUT_TAG.exec(body); m; m = INPUT_TAG.exec(body)) {
|
|
125496
|
+
TAG_ATTR.lastIndex = INPUT_TAG.lastIndex;
|
|
125497
|
+
for (let a = TAG_ATTR.exec(body); a && !a[1]; a = TAG_ATTR.exec(body)) {
|
|
125498
|
+
const name = a[2]?.toLowerCase();
|
|
125499
|
+
const value = (a[3] ?? a[4] ?? a[5] ?? "").trim().toLowerCase();
|
|
125500
|
+
if ((name === "type" || name === "name") && value === "password") return true;
|
|
125501
|
+
}
|
|
125502
|
+
}
|
|
125503
|
+
return false;
|
|
125504
|
+
}
|
|
125505
|
+
function looksLikeHexFrame(body) {
|
|
125506
|
+
const t = body.trim();
|
|
125507
|
+
return t.length > 0 && t.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(t);
|
|
125508
|
+
}
|
|
125509
|
+
function looksSignedOut(requestedUrl, res) {
|
|
125510
|
+
let finalPath = "";
|
|
125511
|
+
try {
|
|
125512
|
+
finalPath = new URL(res.url).pathname;
|
|
125513
|
+
} catch {
|
|
125514
|
+
finalPath = "";
|
|
125515
|
+
}
|
|
125516
|
+
if (SIGNIN_PATH.test(finalPath)) return true;
|
|
125517
|
+
if (res.status === 401 || res.status === 403) return true;
|
|
125518
|
+
if (res.status !== 200) return false;
|
|
125519
|
+
if (hasPasswordInput(res.body)) return true;
|
|
125520
|
+
let reqPath = "";
|
|
125521
|
+
try {
|
|
125522
|
+
reqPath = new URL(requestedUrl).pathname;
|
|
125523
|
+
} catch {
|
|
125524
|
+
reqPath = "";
|
|
125525
|
+
}
|
|
125526
|
+
if (/\/services\b/i.test(reqPath) && !looksLikeHexFrame(res.body)) return true;
|
|
125527
|
+
return false;
|
|
125528
|
+
}
|
|
125529
|
+
var DirectBridge = class {
|
|
125530
|
+
constructor(store, fetchImpl = fetchViaPublic, hostSignIn = false) {
|
|
125531
|
+
this.store = store;
|
|
125532
|
+
this.fetchImpl = fetchImpl;
|
|
125533
|
+
this.hostSignIn = hostSignIn;
|
|
125534
|
+
}
|
|
125535
|
+
store;
|
|
125536
|
+
fetchImpl;
|
|
125537
|
+
hostSignIn;
|
|
125538
|
+
async fetch(init, signal) {
|
|
125539
|
+
const sess = await this.store.read();
|
|
125540
|
+
if (!sess) throw new SessionNotLinkedError(this.hostSignIn ? { hostSignIn: true } : {});
|
|
125541
|
+
const token = sess.authToken;
|
|
125542
|
+
const url4 = warappUrl(init.path);
|
|
125543
|
+
const headers = { ...init.headers ?? {}, cookie: `AuthToken=${token}` };
|
|
125544
|
+
let res;
|
|
125545
|
+
try {
|
|
125546
|
+
res = await this.fetchImpl(url4, {
|
|
125547
|
+
method: init.method,
|
|
125548
|
+
headers,
|
|
125549
|
+
...init.body !== void 0 ? { body: init.body } : {},
|
|
125550
|
+
...signal ? { signal } : {}
|
|
125551
|
+
});
|
|
125552
|
+
} catch (err) {
|
|
125553
|
+
throw scrubError(err, [token]);
|
|
125554
|
+
}
|
|
125555
|
+
const answered = res.status === 200 && looksLikeHexFrame(res.body);
|
|
125556
|
+
if (!answered && (res.status !== 200 || res.headers?.["cf-mitigated"])) {
|
|
125557
|
+
const edge = detectEdgeBlock({ body: res.body, ...res.headers ? { headers: res.headers } : {}, status: res.status });
|
|
125558
|
+
if (edge) {
|
|
125559
|
+
throw new EdgeBlockedError(res.status, edge.vendor, {
|
|
125560
|
+
service: SESSION_HOST,
|
|
125561
|
+
method: init.method,
|
|
125562
|
+
path: new URL(url4).pathname
|
|
125563
|
+
});
|
|
125564
|
+
}
|
|
125565
|
+
}
|
|
125566
|
+
if (looksSignedOut(url4, res)) {
|
|
125567
|
+
throw new SessionExpiredError({ capturedAt: sess.capturedAt, hostSignIn: this.hostSignIn || sess.origin === "host" });
|
|
125568
|
+
}
|
|
125569
|
+
return { status: res.status, body: res.body, url: res.url };
|
|
125570
|
+
}
|
|
125571
|
+
};
|
|
125572
|
+
var RELINK_CHECK_MS = 5e3;
|
|
125573
|
+
function createDirectFirstBridge(opts) {
|
|
125574
|
+
const env = opts.env ?? process.env;
|
|
125575
|
+
const hosted = isHosted(env);
|
|
125576
|
+
const hostSession = hosted ? hostedSession(env) : null;
|
|
125577
|
+
const pinned = hosted && !hostSession;
|
|
125578
|
+
const mode = pinned ? "fetchproxy" : opts.mode ?? readTransportMode(TRANSPORT_ENV, opts.env ? { env: opts.env } : {});
|
|
125579
|
+
const store = hosted ? { read: async () => hostSession } : opts.store;
|
|
125580
|
+
const hostSignIn = hostSession !== null;
|
|
125581
|
+
const direct = new DirectBridge(store, opts.directFetch ?? createDirectFetch({ env }), hostSignIn);
|
|
125582
|
+
const log = opts.log ?? ((m) => console.error(m));
|
|
125583
|
+
const now = opts.now ?? Date.now;
|
|
125584
|
+
let wall = null;
|
|
125585
|
+
let stale = false;
|
|
125586
|
+
let lastRelinkCheck = Number.NEGATIVE_INFINITY;
|
|
125587
|
+
const onFallback = ({ error: error62 }) => {
|
|
125588
|
+
const next = error62 instanceof SessionExpiredError ? { kind: "session", capturedAt: error62.capturedAt ?? null } : error62 instanceof SessionNotLinkedError ? { kind: "session", capturedAt: null } : { kind: "edge" };
|
|
125589
|
+
wall = next;
|
|
125590
|
+
const why = error62 instanceof SessionExpiredError ? "the linked war.app session is signed out" : error62 instanceof SessionNotLinkedError ? "no war.app session is linked" : "the site edge refused the direct request";
|
|
125591
|
+
log(
|
|
125592
|
+
`[warapp-mcp] Direct transport unavailable (${why}) \u2014 switching to the ContextMint Bridge browser bridge. Keep a ${SESSION_HOST} tab open and approve the pairing prompt in the extension if one appears` + (next.kind !== "session" ? "." : hostSignIn ? `. ${HOST_SIGN_IN_ADVICE}` : hosted ? "." : "; run warapp_link_session to return to the direct transport.")
|
|
125593
|
+
);
|
|
125594
|
+
};
|
|
125595
|
+
const build2 = () => createDirectFirstTransport({
|
|
125596
|
+
direct,
|
|
125597
|
+
bridge: opts.makeBridge,
|
|
125598
|
+
mode,
|
|
125599
|
+
serverName: "warapp-mcp",
|
|
125600
|
+
hostLabel: SESSION_HOST,
|
|
125601
|
+
shouldFallBack: (err) => err instanceof SessionExpiredError || err instanceof SessionNotLinkedError || err instanceof EdgeBlockedError,
|
|
125602
|
+
bridgeHealth: (b) => b.transport(),
|
|
125603
|
+
onFallback
|
|
125604
|
+
});
|
|
125605
|
+
let legs = build2();
|
|
125606
|
+
const liftSessionWall = () => {
|
|
125607
|
+
if (wall?.kind !== "session") return;
|
|
125608
|
+
wall = null;
|
|
125609
|
+
legs = build2();
|
|
125610
|
+
};
|
|
125611
|
+
const relinkedSinceWall = async () => {
|
|
125612
|
+
if (wall?.kind !== "session") return false;
|
|
125613
|
+
const t = now();
|
|
125614
|
+
if (t - lastRelinkCheck < RELINK_CHECK_MS) return false;
|
|
125615
|
+
lastRelinkCheck = t;
|
|
125616
|
+
const sess = await store.read();
|
|
125617
|
+
return sess !== null && sess.capturedAt !== wall.capturedAt;
|
|
125618
|
+
};
|
|
125619
|
+
const runOne = async (init) => {
|
|
125620
|
+
if (mode === "auto" && await relinkedSinceWall()) {
|
|
125621
|
+
liftSessionWall();
|
|
125622
|
+
stale = false;
|
|
125623
|
+
}
|
|
125624
|
+
let reached;
|
|
125625
|
+
return legs.run(async (leg, ctx) => {
|
|
125626
|
+
if (leg === direct) {
|
|
125627
|
+
try {
|
|
125628
|
+
const res = await direct.fetch(init, ctx.signal);
|
|
125629
|
+
if (res.status === 200) stale = false;
|
|
125630
|
+
return res;
|
|
125631
|
+
} catch (err) {
|
|
125632
|
+
if (err instanceof SessionExpiredError) {
|
|
125633
|
+
stale = true;
|
|
125634
|
+
if (!isSafeToReplay(init.method)) reached = err;
|
|
125635
|
+
}
|
|
125636
|
+
throw err;
|
|
125637
|
+
}
|
|
125638
|
+
}
|
|
125639
|
+
if (reached) {
|
|
125640
|
+
throw new SessionExpiredError({ capturedAt: reached.capturedAt, notResent: true, hostSignIn: reached.hostSignIn });
|
|
125641
|
+
}
|
|
125642
|
+
return leg.ready().then((t) => t.fetch(init));
|
|
125643
|
+
});
|
|
125644
|
+
};
|
|
125645
|
+
return {
|
|
125646
|
+
ready: async () => ({ fetch: (init) => runOne(init) }),
|
|
125647
|
+
status: () => legs.status(),
|
|
125648
|
+
bridgeTransport: () => legs.bridgeTransport(),
|
|
125649
|
+
stats: () => legs.stats(),
|
|
125650
|
+
sessionStale: () => stale,
|
|
125651
|
+
sessionLinked: () => {
|
|
125652
|
+
stale = false;
|
|
125653
|
+
if (mode === "auto") liftSessionWall();
|
|
125654
|
+
},
|
|
125655
|
+
identityState: async () => {
|
|
125656
|
+
const sess = await store.read();
|
|
125657
|
+
return JSON.stringify([legs.status().transport, stale, sess?.capturedAt ?? null]);
|
|
125658
|
+
}
|
|
125659
|
+
};
|
|
125660
|
+
}
|
|
125661
|
+
|
|
125037
125662
|
// src/tools/resolve.ts
|
|
125038
125663
|
function pick3(items, input2, what) {
|
|
125039
125664
|
const raw = String(input2).trim();
|
|
@@ -125077,7 +125702,9 @@ function resolvePlayer(players, input2) {
|
|
|
125077
125702
|
function refuse(message, hint) {
|
|
125078
125703
|
throw new McpToolError(message, { kind: "unknown", hint });
|
|
125079
125704
|
}
|
|
125080
|
-
function signedInHint(
|
|
125705
|
+
function signedInHint(view) {
|
|
125706
|
+
const { hosted, hostSignIn } = typeof view === "object" ? view : { hosted: view, hostSignIn: false };
|
|
125707
|
+
if (hosted && hostSignIn) return `${HOST_SIGN_IN_ADVICE} Then retry.`;
|
|
125081
125708
|
return hosted ? "Make sure a war.app tab signed in to your account is open and paired (reload or focus it if it is frozen), then retry." : "Make sure a war.app tab signed in to your account is open and paired (reload or focus it if it is frozen), or link a session with warapp_link_session, then retry.";
|
|
125082
125709
|
}
|
|
125083
125710
|
function accountUnknown(hosted, consequence = "nothing was sent") {
|
|
@@ -125088,7 +125715,7 @@ function accountUnknown(hosted, consequence = "nothing was sent") {
|
|
|
125088
125715
|
}
|
|
125089
125716
|
async function requireMe(ctx, opts = {}) {
|
|
125090
125717
|
const token = await ctx.myInviteToken({ fresh: opts.fresh ?? true });
|
|
125091
|
-
if (token === void 0) throw accountUnknown(ctx
|
|
125718
|
+
if (token === void 0) throw accountUnknown(ctx, opts.consequence);
|
|
125092
125719
|
return token;
|
|
125093
125720
|
}
|
|
125094
125721
|
function mySeat(game, token) {
|
|
@@ -125747,7 +126374,7 @@ function chatViewMarks(lines, meInGame, channels) {
|
|
|
125747
126374
|
out.channels = CHAT_CHANNELS.filter((c) => has[c]);
|
|
125748
126375
|
return out.channels.length ? out : void 0;
|
|
125749
126376
|
}
|
|
125750
|
-
var
|
|
126377
|
+
var isRec7 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
125751
126378
|
var pick4 = (r, keys) => {
|
|
125752
126379
|
for (const k of keys) if (r[k] !== void 0 && r[k] !== null) return r[k];
|
|
125753
126380
|
return void 0;
|
|
@@ -125761,11 +126388,11 @@ var CHANNEL_KEYS = ["channel", "Channel", "teamID", "teamId", "team", "Team"];
|
|
|
125761
126388
|
var RECIPIENT_KEYS = ["recipientID", "recipientId", "recipient", "toPlayerID", "toPlayerId", "privateTo", "to"];
|
|
125762
126389
|
function feedChatLines(raw) {
|
|
125763
126390
|
let list3 = raw;
|
|
125764
|
-
if (
|
|
126391
|
+
if (isRec7(list3)) list3 = pick4(list3, LIST_KEYS);
|
|
125765
126392
|
if (!Array.isArray(list3)) return void 0;
|
|
125766
126393
|
const out = [];
|
|
125767
126394
|
for (const item of list3) {
|
|
125768
|
-
if (!
|
|
126395
|
+
if (!isRec7(item)) return void 0;
|
|
125769
126396
|
const text = pick4(item, TEXT_KEYS);
|
|
125770
126397
|
if (typeof text !== "string") return void 0;
|
|
125771
126398
|
const from = pick4(item, SENDER_KEYS);
|
|
@@ -125819,9 +126446,9 @@ function fillFromFeed(web, feed) {
|
|
|
125819
126446
|
|
|
125820
126447
|
// src/chat-cursor.ts
|
|
125821
126448
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
125822
|
-
import { mkdir as
|
|
125823
|
-
import { join as
|
|
125824
|
-
var chatCursorPath = (dir, gameId) =>
|
|
126449
|
+
import { mkdir as mkdir8, readFile as readFile9, rename as rename8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
|
|
126450
|
+
import { join as join12 } from "node:path";
|
|
126451
|
+
var chatCursorPath = (dir, gameId) => join12(dir, "chat", `${gameId}.json`);
|
|
125825
126452
|
var byChannel = (lines, channel) => lines.map((l, i2) => [l, i2]).filter(([l]) => l.channel === channel);
|
|
125826
126453
|
function markNew(lines, cursor) {
|
|
125827
126454
|
const out = lines.map((l) => !l.mine);
|
|
@@ -125870,10 +126497,10 @@ function unreadCounts(lines, fresh) {
|
|
|
125870
126497
|
const unknown4 = n("unknown");
|
|
125871
126498
|
return { public: n("public"), team: n("team"), private: n("private"), ...unknown4 ? { unknown: unknown4 } : {} };
|
|
125872
126499
|
}
|
|
125873
|
-
var
|
|
126500
|
+
var isRec8 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
125874
126501
|
var count = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
|
|
125875
126502
|
function channelOf(v) {
|
|
125876
|
-
if (!
|
|
126503
|
+
if (!isRec8(v) || !count(v.seen)) return void 0;
|
|
125877
126504
|
const c = { seen: v.seen };
|
|
125878
126505
|
if (typeof v.lastTimeMs === "number" && Number.isFinite(v.lastTimeMs)) {
|
|
125879
126506
|
c.lastTimeMs = v.lastTimeMs;
|
|
@@ -125883,8 +126510,8 @@ function channelOf(v) {
|
|
|
125883
126510
|
}
|
|
125884
126511
|
async function readChatCursor(dir, gameId, playerId) {
|
|
125885
126512
|
try {
|
|
125886
|
-
const c = JSON.parse(await
|
|
125887
|
-
if (!
|
|
126513
|
+
const c = JSON.parse(await readFile9(chatCursorPath(dir, gameId), "utf8"));
|
|
126514
|
+
if (!isRec8(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec8(c.channels)) return void 0;
|
|
125888
126515
|
const channels = {};
|
|
125889
126516
|
for (const ch of CHAT_CHANNELS) {
|
|
125890
126517
|
const v = channelOf(c.channels[ch]);
|
|
@@ -125899,13 +126526,13 @@ async function readChatCursor(dir, gameId, playerId) {
|
|
|
125899
126526
|
async function writeChatCursor(dir, cursor) {
|
|
125900
126527
|
try {
|
|
125901
126528
|
const path = chatCursorPath(dir, cursor.gameId);
|
|
125902
|
-
await
|
|
126529
|
+
await mkdir8(join12(dir, "chat"), { recursive: true, mode: 448 });
|
|
125903
126530
|
const tmp = `${path}.${process.pid}.${randomUUID2()}.tmp`;
|
|
125904
126531
|
try {
|
|
125905
126532
|
await writeFile7(tmp, JSON.stringify(cursor), { mode: 384 });
|
|
125906
|
-
await
|
|
126533
|
+
await rename8(tmp, path);
|
|
125907
126534
|
} catch (e) {
|
|
125908
|
-
await
|
|
126535
|
+
await rm5(tmp, { force: true }).catch(() => void 0);
|
|
125909
126536
|
throw e;
|
|
125910
126537
|
}
|
|
125911
126538
|
return true;
|
|
@@ -126918,21 +127545,21 @@ function commitmentWarnings(input2) {
|
|
|
126918
127545
|
|
|
126919
127546
|
// src/relations-store.ts
|
|
126920
127547
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
126921
|
-
import { mkdir as
|
|
126922
|
-
import { join as
|
|
126923
|
-
var
|
|
127548
|
+
import { mkdir as mkdir9, readFile as readFile10, rename as rename9, writeFile as writeFile8 } from "node:fs/promises";
|
|
127549
|
+
import { join as join13 } from "node:path";
|
|
127550
|
+
var isRec9 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
126924
127551
|
var isInt4 = (v) => typeof v === "number" && Number.isInteger(v);
|
|
126925
127552
|
var ints = (v) => Array.isArray(v) && v.every(isInt4) ? [...v] : void 0;
|
|
126926
127553
|
var MAX_AGREEMENTS = 50;
|
|
126927
127554
|
var MAX_USAGE_TURNS = 200;
|
|
126928
127555
|
var MAX_COMMITMENTS = 200;
|
|
126929
|
-
var relationsDir = (dir) =>
|
|
126930
|
-
var relationsPath = (dir, gameId, playerId) =>
|
|
127556
|
+
var relationsDir = (dir) => join13(dir, "relations");
|
|
127557
|
+
var relationsPath = (dir, gameId, playerId) => join13(relationsDir(dir), `${gameId}-${playerId}.json`);
|
|
126931
127558
|
var AGREEMENT_ID = /^a(\d{1,9})$/;
|
|
126932
127559
|
var idNumber = (id) => Number(AGREEMENT_ID.exec(id)?.[1] ?? 0);
|
|
126933
127560
|
function scopeOf(v) {
|
|
126934
127561
|
if (v === "all") return "all";
|
|
126935
|
-
if (!
|
|
127562
|
+
if (!isRec9(v)) return void 0;
|
|
126936
127563
|
const t = ints(v.territories);
|
|
126937
127564
|
if (t) return { territories: t };
|
|
126938
127565
|
const b = ints(v.bonuses);
|
|
@@ -126940,7 +127567,7 @@ function scopeOf(v) {
|
|
|
126940
127567
|
}
|
|
126941
127568
|
var isStatus = (v) => typeof v === "string" && AGREEMENT_STATUSES.includes(v);
|
|
126942
127569
|
function termsOf(v) {
|
|
126943
|
-
if (!
|
|
127570
|
+
if (!isRec9(v)) return void 0;
|
|
126944
127571
|
const scope = scopeOf(v.scope);
|
|
126945
127572
|
if (!scope || !isInt4(v.noticeTurns) || v.noticeTurns < 0 || v.noticeTurns > MAX_NOTICE_TURNS) return void 0;
|
|
126946
127573
|
const t = { scope, noticeTurns: v.noticeTurns };
|
|
@@ -126951,11 +127578,11 @@ function termsOf(v) {
|
|
|
126951
127578
|
return t;
|
|
126952
127579
|
}
|
|
126953
127580
|
function agreementOf(v) {
|
|
126954
|
-
if (!
|
|
127581
|
+
if (!isRec9(v) || typeof v.id !== "string" || !AGREEMENT_ID.test(v.id) || !isInt4(v.with) || v.kind !== "truce" || !isStatus(v.status) || !isInt4(v.createdTurn))
|
|
126955
127582
|
return void 0;
|
|
126956
127583
|
const terms = termsOf(v.terms);
|
|
126957
127584
|
if (!terms || !Array.isArray(v.history)) return void 0;
|
|
126958
|
-
const history = v.history.filter((h) =>
|
|
127585
|
+
const history = v.history.filter((h) => isRec9(h) && isInt4(h.turn) && isStatus(h.status));
|
|
126959
127586
|
const a = { id: v.id, with: v.with, kind: "truce", status: v.status, createdTurn: v.createdTurn, terms, history };
|
|
126960
127587
|
if (isInt4(v.agreedTurn)) a.agreedTurn = v.agreedTurn;
|
|
126961
127588
|
if (isInt4(v.noticeTurn)) a.noticeTurn = v.noticeTurn;
|
|
@@ -126966,7 +127593,7 @@ function agreementOf(v) {
|
|
|
126966
127593
|
}
|
|
126967
127594
|
var COMMITMENT_ID = /^c(\d{1,9})$/;
|
|
126968
127595
|
function commitmentOf(v) {
|
|
126969
|
-
if (!
|
|
127596
|
+
if (!isRec9(v) || typeof v.id !== "string" || !COMMITMENT_ID.test(v.id) || !isInt4(v.sentTurn)) return void 0;
|
|
126970
127597
|
if (typeof v.kind !== "string" || !COMMITMENT_KINDS.includes(v.kind)) return void 0;
|
|
126971
127598
|
const base = { id: v.id, sentTurn: v.sentTurn };
|
|
126972
127599
|
switch (v.kind) {
|
|
@@ -126996,12 +127623,12 @@ function nextCommitmentId(ledger) {
|
|
|
126996
127623
|
return `c${n + 1}`;
|
|
126997
127624
|
}
|
|
126998
127625
|
function usageOf(v) {
|
|
126999
|
-
if (!
|
|
127626
|
+
if (!isRec9(v)) return {};
|
|
127000
127627
|
const out = {};
|
|
127001
127628
|
for (const [k, list3] of Object.entries(v)) {
|
|
127002
127629
|
if (!/^\d+$/.test(k) || !Array.isArray(list3)) continue;
|
|
127003
127630
|
const num3 = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
|
|
127004
|
-
out[k] = list3.filter((u) =>
|
|
127631
|
+
out[k] = list3.filter((u) => isRec9(u) && typeof u.agreementId === "string").map((u) => ({
|
|
127005
127632
|
agreementId: u.agreementId,
|
|
127006
127633
|
armiesFreed: num3(u.armiesFreed),
|
|
127007
127634
|
lossIfBroken: num3(u.lossIfBroken),
|
|
@@ -127013,8 +127640,8 @@ function usageOf(v) {
|
|
|
127013
127640
|
var emptyLedger = (gameId, playerId) => ({ gameId, playerId, agreements: [], usage: {} });
|
|
127014
127641
|
async function readLedger(dir, gameId, playerId) {
|
|
127015
127642
|
try {
|
|
127016
|
-
const c = JSON.parse(await
|
|
127017
|
-
if (!
|
|
127643
|
+
const c = JSON.parse(await readFile10(relationsPath(dir, gameId, playerId), "utf8"));
|
|
127644
|
+
if (!isRec9(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements)) return void 0;
|
|
127018
127645
|
const agreements = c.agreements.map(agreementOf).filter((a) => a !== void 0);
|
|
127019
127646
|
return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
|
|
127020
127647
|
} catch {
|
|
@@ -127024,13 +127651,13 @@ async function readLedger(dir, gameId, playerId) {
|
|
|
127024
127651
|
async function readLedgerForWrite(dir, gameId, playerId) {
|
|
127025
127652
|
let text;
|
|
127026
127653
|
try {
|
|
127027
|
-
text = await
|
|
127654
|
+
text = await readFile10(relationsPath(dir, gameId, playerId), "utf8");
|
|
127028
127655
|
} catch (e) {
|
|
127029
127656
|
return e.code === "ENOENT" ? null : "unreadable";
|
|
127030
127657
|
}
|
|
127031
127658
|
try {
|
|
127032
127659
|
const c = JSON.parse(text);
|
|
127033
|
-
if (!
|
|
127660
|
+
if (!isRec9(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements)) return "unreadable";
|
|
127034
127661
|
const agreements = c.agreements.map(agreementOf).filter((a) => a !== void 0);
|
|
127035
127662
|
return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
|
|
127036
127663
|
} catch {
|
|
@@ -127052,10 +127679,10 @@ function boundLedger(ledger) {
|
|
|
127052
127679
|
async function writeLedger(dir, ledger) {
|
|
127053
127680
|
try {
|
|
127054
127681
|
const path = relationsPath(dir, ledger.gameId, ledger.playerId);
|
|
127055
|
-
await
|
|
127682
|
+
await mkdir9(relationsDir(dir), { recursive: true, mode: 448 });
|
|
127056
127683
|
const tmp = `${path}.${process.pid}.${randomUUID3()}.tmp`;
|
|
127057
127684
|
await writeFile8(tmp, JSON.stringify(boundLedger(ledger)), { mode: 384 });
|
|
127058
|
-
await
|
|
127685
|
+
await rename9(tmp, path);
|
|
127059
127686
|
return true;
|
|
127060
127687
|
} catch {
|
|
127061
127688
|
return false;
|
|
@@ -127183,15 +127810,15 @@ function playerRecord(tallies, entries2 = []) {
|
|
|
127183
127810
|
}
|
|
127184
127811
|
|
|
127185
127812
|
// src/player-record-store.ts
|
|
127186
|
-
import { createHmac as createHmac3, randomBytes as
|
|
127187
|
-
import { link as link2, mkdir as
|
|
127188
|
-
import { join as
|
|
127189
|
-
var
|
|
127813
|
+
import { createHmac as createHmac3, randomBytes as randomBytes8, randomUUID as randomUUID4 } from "node:crypto";
|
|
127814
|
+
import { link as link2, mkdir as mkdir10, readFile as readFile11, rename as rename10, unlink as unlink7, writeFile as writeFile9 } from "node:fs/promises";
|
|
127815
|
+
import { join as join14 } from "node:path";
|
|
127816
|
+
var isRec10 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
127190
127817
|
var SALT = /^[0-9a-f]{32}$/;
|
|
127191
127818
|
var HASH = /^[0-9a-f]{32}$/;
|
|
127192
127819
|
var OUTCOMES = /* @__PURE__ */ new Set(["open", "not-agreed", "kept", "ended-with-notice", "broken-by-them", "broken-by-me"]);
|
|
127193
|
-
var playerRecordPath = (dir) =>
|
|
127194
|
-
var playerRecordSaltPath = (dir) =>
|
|
127820
|
+
var playerRecordPath = (dir) => join14(relationsDir(dir), "players.json");
|
|
127821
|
+
var playerRecordSaltPath = (dir) => join14(relationsDir(dir), "players.salt");
|
|
127195
127822
|
function playerRecordEnabled(env = process.env) {
|
|
127196
127823
|
const v = readEnvVar("WARAPP_PLAYER_RECORD", { env });
|
|
127197
127824
|
return v === void 0 || !/^(off|0|false|no)$/i.test(v.trim());
|
|
@@ -127199,7 +127826,7 @@ function playerRecordEnabled(env = process.env) {
|
|
|
127199
127826
|
async function readSalt(dir) {
|
|
127200
127827
|
let text;
|
|
127201
127828
|
try {
|
|
127202
|
-
text = await
|
|
127829
|
+
text = await readFile11(playerRecordSaltPath(dir), "utf8");
|
|
127203
127830
|
} catch (e) {
|
|
127204
127831
|
return e.code === "ENOENT" ? "missing" : "malformed";
|
|
127205
127832
|
}
|
|
@@ -127215,9 +127842,9 @@ async function playerSaltForWrite(dir) {
|
|
|
127215
127842
|
if (typeof s === "object") return s.salt;
|
|
127216
127843
|
if (s === "malformed") return void 0;
|
|
127217
127844
|
const path = playerRecordSaltPath(dir);
|
|
127218
|
-
await
|
|
127845
|
+
await mkdir10(relationsDir(dir), { recursive: true, mode: 448 });
|
|
127219
127846
|
const tmp = `${path}.${process.pid}.${randomUUID4()}.tmp`;
|
|
127220
|
-
await writeFile9(tmp,
|
|
127847
|
+
await writeFile9(tmp, randomBytes8(16).toString("hex"), { mode: 384 });
|
|
127221
127848
|
try {
|
|
127222
127849
|
await link2(tmp, path);
|
|
127223
127850
|
} catch (e) {
|
|
@@ -127237,19 +127864,19 @@ var legacyEntryKey = (salt, gameId, agreementId) => hmac(salt, `agreement:${game
|
|
|
127237
127864
|
var count2 = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
|
|
127238
127865
|
var intOrNull = (v) => v === null || typeof v === "number" && Number.isInteger(v);
|
|
127239
127866
|
function talliesFrom(v) {
|
|
127240
|
-
if (!
|
|
127867
|
+
if (!isRec10(v) || !COUNT_KEYS.every((k) => count2(v[k]))) return void 0;
|
|
127241
127868
|
const out = { ...ZERO_COUNTS };
|
|
127242
127869
|
for (const k of COUNT_KEYS) out[k] = v[k];
|
|
127243
127870
|
return out;
|
|
127244
127871
|
}
|
|
127245
127872
|
function entryOf2(v) {
|
|
127246
|
-
if (!
|
|
127873
|
+
if (!isRec10(v) || typeof v.key !== "string" || !HASH.test(v.key) || !OUTCOMES.has(v.outcome) || typeof v.updated !== "number")
|
|
127247
127874
|
return void 0;
|
|
127248
|
-
if (!
|
|
127875
|
+
if (!isRec10(v.format) || !isRec10(v.terms) || !intOrNull(v.agreedTurn) || !intOrNull(v.endedTurn)) return void 0;
|
|
127249
127876
|
return v;
|
|
127250
127877
|
}
|
|
127251
127878
|
function playerOf(v) {
|
|
127252
|
-
if (!
|
|
127879
|
+
if (!isRec10(v)) return void 0;
|
|
127253
127880
|
const entries2 = Array.isArray(v.entries) ? v.entries.map(entryOf2).filter((e) => e !== void 0) : [];
|
|
127254
127881
|
const tallies = talliesFrom(v.tallies) ?? talliesFrom(v.counts) ?? (entries2.length ? talliesOf(entries2) : void 0);
|
|
127255
127882
|
if (!tallies) return void 0;
|
|
@@ -127259,7 +127886,7 @@ function playerOf(v) {
|
|
|
127259
127886
|
async function readFileRecord(dir) {
|
|
127260
127887
|
let text;
|
|
127261
127888
|
try {
|
|
127262
|
-
text = await
|
|
127889
|
+
text = await readFile11(playerRecordPath(dir), "utf8");
|
|
127263
127890
|
} catch (e) {
|
|
127264
127891
|
return e.code === "ENOENT" ? { version: 3, players: {} } : "unreadable";
|
|
127265
127892
|
}
|
|
@@ -127269,7 +127896,7 @@ async function readFileRecord(dir) {
|
|
|
127269
127896
|
} catch {
|
|
127270
127897
|
return "unreadable";
|
|
127271
127898
|
}
|
|
127272
|
-
if (!
|
|
127899
|
+
if (!isRec10(c) || !isRec10(c.players)) return "unreadable";
|
|
127273
127900
|
const players = {};
|
|
127274
127901
|
for (const [k, v] of Object.entries(c.players)) {
|
|
127275
127902
|
const p = HASH.test(k) ? playerOf(v) : void 0;
|
|
@@ -127281,10 +127908,10 @@ async function writeFileRecord(dir, file2) {
|
|
|
127281
127908
|
const keys = Object.keys(file2.players).sort((a, b) => file2.players[b].updated - file2.players[a].updated || (a < b ? -1 : 1)).slice(0, MAX_RECORD_PLAYERS).sort();
|
|
127282
127909
|
const bounded = { version: 3, players: Object.fromEntries(keys.map((k) => [k, file2.players[k]])) };
|
|
127283
127910
|
const path = playerRecordPath(dir);
|
|
127284
|
-
await
|
|
127911
|
+
await mkdir10(relationsDir(dir), { recursive: true, mode: 448 });
|
|
127285
127912
|
const tmp = `${path}.${process.pid}.${randomUUID4()}.tmp`;
|
|
127286
127913
|
await writeFile9(tmp, JSON.stringify(bounded), { mode: 384 });
|
|
127287
|
-
await
|
|
127914
|
+
await rename10(tmp, path);
|
|
127288
127915
|
}
|
|
127289
127916
|
async function readPlayerRecord(dir, playerId, env) {
|
|
127290
127917
|
if (!playerRecordEnabled(env)) return "off";
|
|
@@ -127329,14 +127956,14 @@ async function updatePlayerRecord(dir, playerId, update, env, now = Date.now())
|
|
|
127329
127956
|
}
|
|
127330
127957
|
|
|
127331
127958
|
// src/replay.ts
|
|
127332
|
-
import { readdir as readdir6, readFile as
|
|
127333
|
-
import { join as
|
|
127959
|
+
import { readdir as readdir6, readFile as readFile12, stat as stat5, unlink as unlink8 } from "node:fs/promises";
|
|
127960
|
+
import { join as join15 } from "node:path";
|
|
127334
127961
|
var MAX_GAME_RECORDS = 200;
|
|
127335
127962
|
var VERSION3 = 1;
|
|
127336
127963
|
var GAME_FILE = /^\d+\.json$/;
|
|
127337
|
-
var
|
|
127338
|
-
var gamesDir = (dir) =>
|
|
127339
|
-
var gameRecordPath = (dir, gameId) =>
|
|
127964
|
+
var isRec11 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
127965
|
+
var gamesDir = (dir) => join15(dir, "games");
|
|
127966
|
+
var gameRecordPath = (dir, gameId) => join15(gamesDir(dir), `${gameId}.json`);
|
|
127340
127967
|
var ENUM_SETTINGS = /* @__PURE__ */ new Set(["Pace", "Fog", "MoveOrder", "RoundingMode", "InstantSurrender", "AutomaticTerritoryDistribution"]);
|
|
127341
127968
|
var DROPPED_SETTINGS = /* @__PURE__ */ new Set(["PersonalMessage", "Mods", "OverriddenBonuses"]);
|
|
127342
127969
|
var CARD_ENUM_KEYS = /* @__PURE__ */ new Set(["Mode"]);
|
|
@@ -127354,7 +127981,7 @@ function cleanValue(v, depth, enumOk, names2, enumKeys = NO_KEYS) {
|
|
|
127354
127981
|
}
|
|
127355
127982
|
if (depth > MAX_DEPTH2) return void 0;
|
|
127356
127983
|
if (Array.isArray(v)) return v.map((x) => cleanValue(x, depth + 1, false, names2)).filter((x) => x !== void 0);
|
|
127357
|
-
if (
|
|
127984
|
+
if (isRec11(v)) {
|
|
127358
127985
|
const out = {};
|
|
127359
127986
|
for (const [k, x] of Object.entries(v)) {
|
|
127360
127987
|
if (!ENUM.test(k) && !NUMERIC.test(k)) continue;
|
|
@@ -127392,8 +128019,8 @@ async function pruneGames(dir, keep) {
|
|
|
127392
128019
|
for (const name of await readdir6(folder)) {
|
|
127393
128020
|
if (!GAME_FILE.test(name) || name === `${keep}.json`) continue;
|
|
127394
128021
|
try {
|
|
127395
|
-
const at2 = (await
|
|
127396
|
-
if (at2 < cutoff) await unlink8(
|
|
128022
|
+
const at2 = (await stat5(join15(folder, name))).mtimeMs;
|
|
128023
|
+
if (at2 < cutoff) await unlink8(join15(folder, name));
|
|
127397
128024
|
else files.push({ name, at: at2 });
|
|
127398
128025
|
} catch {
|
|
127399
128026
|
}
|
|
@@ -127401,7 +128028,7 @@ async function pruneGames(dir, keep) {
|
|
|
127401
128028
|
const excess = files.length + 1 - MAX_GAME_RECORDS;
|
|
127402
128029
|
if (excess <= 0) return;
|
|
127403
128030
|
files.sort((a, b) => a.at - b.at || a.name.localeCompare(b.name));
|
|
127404
|
-
for (const f of files.slice(0, excess)) await unlink8(
|
|
128031
|
+
for (const f of files.slice(0, excess)) await unlink8(join15(folder, f.name)).catch(() => {
|
|
127405
128032
|
});
|
|
127406
128033
|
}
|
|
127407
128034
|
function nameFreeSettings(game) {
|
|
@@ -127441,13 +128068,13 @@ async function writeGameRecord(dir, game) {
|
|
|
127441
128068
|
}
|
|
127442
128069
|
|
|
127443
128070
|
// src/pick-list.ts
|
|
127444
|
-
import { mkdir as
|
|
127445
|
-
import { join as
|
|
127446
|
-
var pickListPath = (dir, gameId) =>
|
|
128071
|
+
import { mkdir as mkdir11, readdir as readdir7, readFile as readFile13, rename as rename11, stat as stat6, unlink as unlink9, writeFile as writeFile10 } from "node:fs/promises";
|
|
128072
|
+
import { join as join16 } from "node:path";
|
|
128073
|
+
var pickListPath = (dir, gameId) => join16(dir, "picks", `${gameId}.json`);
|
|
127447
128074
|
var PICK_LIST_MAX_AGE_MS = 60 * 864e5;
|
|
127448
128075
|
var PICK_FILE = /^\d+\.json$/;
|
|
127449
128076
|
var pruned2 = /* @__PURE__ */ new Set();
|
|
127450
|
-
var
|
|
128077
|
+
var isRec12 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
127451
128078
|
var isId = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0;
|
|
127452
128079
|
var isIds = (v) => Array.isArray(v) && v.every(isId);
|
|
127453
128080
|
var isArmies = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
|
|
@@ -127459,7 +128086,7 @@ function neutralsOf(v) {
|
|
|
127459
128086
|
}
|
|
127460
128087
|
function awardOf(v) {
|
|
127461
128088
|
if (v === null) return null;
|
|
127462
|
-
if (!
|
|
128089
|
+
if (!isRec12(v) || !isIds(v.granted) || !isIds(v.unlisted) || !isIds(v.opponentStarts)) return void 0;
|
|
127463
128090
|
if (typeof v.allStartsKnown !== "boolean") return void 0;
|
|
127464
128091
|
if (v.role !== null && v.role !== "first" && v.role !== "second") return void 0;
|
|
127465
128092
|
if (v.opponentFirstAward !== null && !isId(v.opponentFirstAward)) return void 0;
|
|
@@ -127476,8 +128103,8 @@ function awardOf(v) {
|
|
|
127476
128103
|
}
|
|
127477
128104
|
async function readPickRecord(dir, gameId, playerId) {
|
|
127478
128105
|
try {
|
|
127479
|
-
const c = JSON.parse(await
|
|
127480
|
-
if (!
|
|
128106
|
+
const c = JSON.parse(await readFile13(pickListPath(dir, gameId), "utf8"));
|
|
128107
|
+
if (!isRec12(c) || c.gameId !== gameId || c.playerId !== playerId) return void 0;
|
|
127481
128108
|
const list3 = isIds(c.list) && c.list.length ? c.list : void 0;
|
|
127482
128109
|
const pickable = isIds(c.pickable) && c.pickable.length ? c.pickable : void 0;
|
|
127483
128110
|
const neutrals = neutralsOf(c.neutrals);
|
|
@@ -127496,16 +128123,16 @@ async function readPickRecord(dir, gameId, playerId) {
|
|
|
127496
128123
|
}
|
|
127497
128124
|
}
|
|
127498
128125
|
async function prunePickLists(dir) {
|
|
127499
|
-
const picks =
|
|
128126
|
+
const picks = join16(dir, "picks");
|
|
127500
128127
|
if (pruned2.has(picks)) return;
|
|
127501
128128
|
pruned2.add(picks);
|
|
127502
128129
|
const cutoff = Date.now() - PICK_LIST_MAX_AGE_MS;
|
|
127503
128130
|
try {
|
|
127504
128131
|
for (const name of await readdir7(picks)) {
|
|
127505
128132
|
if (!PICK_FILE.test(name)) continue;
|
|
127506
|
-
const file2 =
|
|
128133
|
+
const file2 = join16(picks, name);
|
|
127507
128134
|
try {
|
|
127508
|
-
if ((await
|
|
128135
|
+
if ((await stat6(file2)).mtimeMs < cutoff) await unlink9(file2);
|
|
127509
128136
|
} catch {
|
|
127510
128137
|
}
|
|
127511
128138
|
}
|
|
@@ -127515,10 +128142,10 @@ async function prunePickLists(dir) {
|
|
|
127515
128142
|
async function writeRecord2(dir, record4) {
|
|
127516
128143
|
try {
|
|
127517
128144
|
const path = pickListPath(dir, record4.gameId);
|
|
127518
|
-
await
|
|
128145
|
+
await mkdir11(join16(dir, "picks"), { recursive: true, mode: 448 });
|
|
127519
128146
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
127520
128147
|
await writeFile10(tmp, JSON.stringify(record4), { mode: 384 });
|
|
127521
|
-
await
|
|
128148
|
+
await rename11(tmp, path);
|
|
127522
128149
|
await prunePickLists(dir);
|
|
127523
128150
|
return true;
|
|
127524
128151
|
} catch {
|
|
@@ -127570,8 +128197,8 @@ function pickingNeutrals(board) {
|
|
|
127570
128197
|
}
|
|
127571
128198
|
|
|
127572
128199
|
// src/tools/team-source.ts
|
|
127573
|
-
import { readdir as readdir12, readFile as
|
|
127574
|
-
import { join as
|
|
128200
|
+
import { readdir as readdir12, readFile as readFile20, stat as stat12, unlink as unlink14 } from "node:fs/promises";
|
|
128201
|
+
import { join as join23 } from "node:path";
|
|
127575
128202
|
|
|
127576
128203
|
// src/my-games.ts
|
|
127577
128204
|
var MY_GAMES_RETURN = "warlight.shared.MyGamesReturn";
|
|
@@ -128407,15 +129034,15 @@ function addCalibration(a, b, scale = 1) {
|
|
|
128407
129034
|
}
|
|
128408
129035
|
|
|
128409
129036
|
// src/lessons-store.ts
|
|
128410
|
-
import { readdir as readdir8, readFile as
|
|
128411
|
-
import { join as
|
|
129037
|
+
import { readdir as readdir8, readFile as readFile14, stat as stat7, unlink as unlink10 } from "node:fs/promises";
|
|
129038
|
+
import { join as join17 } from "node:path";
|
|
128412
129039
|
var MAX_MAP_ENTRIES = 50;
|
|
128413
129040
|
var MAX_MAP_RECORDS = 200;
|
|
128414
129041
|
var MAX_LESSON_ENTRIES = 500;
|
|
128415
|
-
var mapRecordDir = (dir) =>
|
|
128416
|
-
var mapRecordPath = (dir, mapId) =>
|
|
128417
|
-
var lessonsPath = (dir) =>
|
|
128418
|
-
var
|
|
129042
|
+
var mapRecordDir = (dir) => join17(dir, "maps-record");
|
|
129043
|
+
var mapRecordPath = (dir, mapId) => join17(mapRecordDir(dir), `${mapId}.json`);
|
|
129044
|
+
var lessonsPath = (dir) => join17(dir, "lessons.json");
|
|
129045
|
+
var isRec13 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
128419
129046
|
var isInt6 = (v) => typeof v === "number" && Number.isInteger(v);
|
|
128420
129047
|
var num = (v) => typeof v === "number" && Number.isFinite(v);
|
|
128421
129048
|
var ints2 = (v) => Array.isArray(v) && v.every(isInt6);
|
|
@@ -128428,34 +129055,34 @@ var CAUSES = ["commander", "last-territories", "unknown", "surrendered", "booted
|
|
|
128428
129055
|
async function readStore(path) {
|
|
128429
129056
|
let text;
|
|
128430
129057
|
try {
|
|
128431
|
-
text = await
|
|
129058
|
+
text = await readFile14(path, "utf8");
|
|
128432
129059
|
} catch (e) {
|
|
128433
129060
|
return e.code === "ENOENT" ? "missing" : "unreadable";
|
|
128434
129061
|
}
|
|
128435
129062
|
try {
|
|
128436
129063
|
const v = JSON.parse(text);
|
|
128437
|
-
return
|
|
129064
|
+
return isRec13(v) ? v : "unreadable";
|
|
128438
129065
|
} catch {
|
|
128439
129066
|
return "unreadable";
|
|
128440
129067
|
}
|
|
128441
129068
|
}
|
|
128442
|
-
var countsOf = (v) =>
|
|
129069
|
+
var countsOf = (v) => isRec13(v) && Object.values(v).every(isInt6) ? Object.fromEntries(Object.entries(v)) : void 0;
|
|
128443
129070
|
var bumpCount = (c, k, by) => {
|
|
128444
129071
|
const n = (c[k] ?? 0) + by;
|
|
128445
129072
|
if (n) c[k] = n;
|
|
128446
129073
|
else delete c[k];
|
|
128447
129074
|
};
|
|
128448
|
-
var regionOf = (v) =>
|
|
129075
|
+
var regionOf = (v) => isRec13(v) && ints2(v.territories) && ints2(v.bonuses) ? { territories: v.territories, bonuses: v.bonuses } : void 0;
|
|
128449
129076
|
function mapEntryOf(v) {
|
|
128450
|
-
if (!
|
|
129077
|
+
if (!isRec13(v) || typeof v.key !== "string" || !HASH2.test(v.key) || !isFormat(v.format) || !isInt6(v.seats) || !isResult(v.result) || !intOrNull2(v.turns)) return void 0;
|
|
128451
129078
|
const m = v.me;
|
|
128452
129079
|
const mine2 = regionOf(m);
|
|
128453
|
-
if (!mine2 || !
|
|
129080
|
+
if (!mine2 || !isRec13(m) || !Array.isArray(m.income) || !m.income.every(intOrNull2) || !intOrNull2(m.income4) || !intOrNull2(m.income8)) return void 0;
|
|
128454
129081
|
if (!Array.isArray(v.winners)) return void 0;
|
|
128455
129082
|
const winners = [];
|
|
128456
129083
|
for (const w of v.winners) {
|
|
128457
129084
|
const r = regionOf(w);
|
|
128458
|
-
if (!r || !
|
|
129085
|
+
if (!r || !isRec13(w) || !intOrNull2(w.income4) || !intOrNull2(w.income8)) return void 0;
|
|
128459
129086
|
winners.push({ ...r, income4: w.income4, income8: w.income8 });
|
|
128460
129087
|
}
|
|
128461
129088
|
return {
|
|
@@ -128506,9 +129133,9 @@ async function pruneMapRecords(dir, keep, protect) {
|
|
|
128506
129133
|
const files = [];
|
|
128507
129134
|
for (const name of await readdir8(folder)) {
|
|
128508
129135
|
if (!/^\d+\.json$/.test(name)) continue;
|
|
128509
|
-
const path =
|
|
129136
|
+
const path = join17(folder, name);
|
|
128510
129137
|
try {
|
|
128511
|
-
files.push({ path, at: (await
|
|
129138
|
+
files.push({ path, at: (await stat7(path)).mtimeMs });
|
|
128512
129139
|
} catch {
|
|
128513
129140
|
}
|
|
128514
129141
|
}
|
|
@@ -128559,11 +129186,11 @@ function mapRecordStarts(rec) {
|
|
|
128559
129186
|
};
|
|
128560
129187
|
}
|
|
128561
129188
|
function statsOf(v) {
|
|
128562
|
-
if (!
|
|
129189
|
+
if (!isRec13(v) || !isInt6(v.n) || !num(v.sum) || !num(v.sq) || !num(v.logSum) || !isInt6(v.under) || !isInt6(v.over)) return void 0;
|
|
128563
129190
|
return { n: v.n, sum: v.sum, sq: v.sq, logSum: v.logSum, under: v.under, over: v.over };
|
|
128564
129191
|
}
|
|
128565
129192
|
function calibrationOf(v) {
|
|
128566
|
-
if (!
|
|
129193
|
+
if (!isRec13(v)) return void 0;
|
|
128567
129194
|
const out = {};
|
|
128568
129195
|
for (const [k, s] of Object.entries(v)) {
|
|
128569
129196
|
if (!COVERAGE_BUCKETS.includes(k)) return void 0;
|
|
@@ -128575,23 +129202,23 @@ function calibrationOf(v) {
|
|
|
128575
129202
|
}
|
|
128576
129203
|
function lossOf(v) {
|
|
128577
129204
|
if (v === null) return null;
|
|
128578
|
-
if (!
|
|
129205
|
+
if (!isRec13(v) || !CAUSES.includes(v.cause) || !intOrNull2(v.turn)) return void 0;
|
|
128579
129206
|
return { cause: v.cause, turn: v.turn };
|
|
128580
129207
|
}
|
|
128581
129208
|
function lessonEntryOf(v) {
|
|
128582
|
-
if (!
|
|
129209
|
+
if (!isRec13(v) || typeof v.key !== "string" || !HASH2.test(v.key) || !isFormat(v.format) || !isInt6(v.seats) || !isResult(v.result) || !intOrNull2(v.flatAfterTurn)) return void 0;
|
|
128583
129210
|
const loss = lossOf(v.howLost);
|
|
128584
129211
|
const calibration = calibrationOf(v.calibration);
|
|
128585
129212
|
if (loss === void 0 || !calibration) return void 0;
|
|
128586
129213
|
return { key: v.key, format: v.format, seats: v.seats, result: v.result, flatAfterTurn: v.flatAfterTurn, howLost: loss, calibration };
|
|
128587
129214
|
}
|
|
128588
129215
|
function totalsOf(v) {
|
|
128589
|
-
if (!
|
|
129216
|
+
if (!isRec13(v) || !isInt6(v.games)) return void 0;
|
|
128590
129217
|
const outcomes = countsOf(v.outcomes);
|
|
128591
129218
|
const lost = countsOf(v.howLost);
|
|
128592
129219
|
const calibration = calibrationOf(v.calibration);
|
|
128593
129220
|
const f = v.flat;
|
|
128594
|
-
if (!outcomes || !lost || !calibration || !
|
|
129221
|
+
if (!outcomes || !lost || !calibration || !isRec13(f) || !isInt6(f.n) || !num(f.sum)) return void 0;
|
|
128595
129222
|
return { games: v.games, outcomes, howLost: lost, flat: { n: f.n, sum: f.sum }, calibration };
|
|
128596
129223
|
}
|
|
128597
129224
|
async function readLessons(dir) {
|
|
@@ -128599,7 +129226,7 @@ async function readLessons(dir) {
|
|
|
128599
129226
|
const v = await readStore(lessonsPath(dir));
|
|
128600
129227
|
if (v === "unreadable") return v;
|
|
128601
129228
|
if (v === "missing") return { version: 1, byFormat: {}, entries: [] };
|
|
128602
|
-
if (v.version !== 1 || !
|
|
129229
|
+
if (v.version !== 1 || !isRec13(v.byFormat)) return "unreadable";
|
|
128603
129230
|
const byFormat = {};
|
|
128604
129231
|
for (const [k, t] of Object.entries(v.byFormat)) {
|
|
128605
129232
|
const totals = totalsOf(t);
|
|
@@ -128676,8 +129303,8 @@ function lessonsSummary(file2) {
|
|
|
128676
129303
|
}
|
|
128677
129304
|
|
|
128678
129305
|
// src/profile-store.ts
|
|
128679
|
-
import { mkdir as
|
|
128680
|
-
import { join as
|
|
129306
|
+
import { mkdir as mkdir12, readdir as readdir9, readFile as readFile15, rename as rename12, stat as stat8, unlink as unlink11, writeFile as writeFile11 } from "node:fs/promises";
|
|
129307
|
+
import { join as join18 } from "node:path";
|
|
128681
129308
|
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
128682
129309
|
var PROFILE_ENV = "WARAPP_PLAYER_PROFILE";
|
|
128683
129310
|
var MAX_PROFILE_GAME_FILES = 200;
|
|
@@ -128689,18 +129316,18 @@ function profileState(env, dataDir2) {
|
|
|
128689
129316
|
if (!profileEnabled(env)) return "off";
|
|
128690
129317
|
return dataDir2 ? "kept" : "not-kept";
|
|
128691
129318
|
}
|
|
128692
|
-
var profileGamesDir = (dir) =>
|
|
128693
|
-
var profileGamePath = (dir, gameId, playerId) =>
|
|
128694
|
-
var
|
|
129319
|
+
var profileGamesDir = (dir) => join18(dir, "profiles", "games");
|
|
129320
|
+
var profileGamePath = (dir, gameId, playerId) => join18(profileGamesDir(dir), `${gameId}-${playerId}.json`);
|
|
129321
|
+
var isRec14 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
128695
129322
|
var isInt7 = (v) => typeof v === "number" && Number.isInteger(v);
|
|
128696
129323
|
var ids = (v) => Array.isArray(v) && v.every(isInt7) ? [...v] : void 0;
|
|
128697
129324
|
function primitivesOf(v) {
|
|
128698
|
-
if (!
|
|
129325
|
+
if (!isRec14(v) || typeof v.contact !== "boolean" || typeof v.iAttacked !== "boolean") return void 0;
|
|
128699
129326
|
if (v.attackedMe !== null && typeof v.attackedMe !== "boolean") return void 0;
|
|
128700
129327
|
const r = v.reinforce;
|
|
128701
|
-
if (!
|
|
129328
|
+
if (!isRec14(r) || !isInt7(r.n) || !isInt7(r.e) || !isInt7(r.extra)) return void 0;
|
|
128702
129329
|
const s = v.stack;
|
|
128703
|
-
if (s !== null && !(
|
|
129330
|
+
if (s !== null && !(isRec14(s) && isInt7(s.top) && isInt7(s.total))) return void 0;
|
|
128704
129331
|
const took = v.tookFromMe === null ? null : ids(v.tookFromMe);
|
|
128705
129332
|
const lost = ids(v.lostToMe);
|
|
128706
129333
|
if (took === void 0 || !lost) return void 0;
|
|
@@ -128714,14 +129341,14 @@ function primitivesOf(v) {
|
|
|
128714
129341
|
lostToMe: lost
|
|
128715
129342
|
};
|
|
128716
129343
|
}
|
|
128717
|
-
var seatsOf = (v) =>
|
|
129344
|
+
var seatsOf = (v) => isRec14(v) && PROFILE_FORMATS.includes(v.format) && isInt7(v.players) && ids(v.ai) && ids(v.turnedAI) ? { format: v.format, players: v.players, ai: ids(v.ai), turnedAI: ids(v.turnedAI) } : void 0;
|
|
128718
129345
|
async function readGameFile(dir, gameId, playerId) {
|
|
128719
129346
|
try {
|
|
128720
|
-
const f = JSON.parse(await
|
|
128721
|
-
if (!
|
|
129347
|
+
const f = JSON.parse(await readFile15(profileGamePath(dir, gameId, playerId), "utf8"));
|
|
129348
|
+
if (!isRec14(f) || f.version !== 1 || f.gameId !== gameId || f.playerId !== playerId || !isRec14(f.turns)) return { turns: {} };
|
|
128722
129349
|
const out = {};
|
|
128723
129350
|
for (const [t, byOpponent] of Object.entries(f.turns)) {
|
|
128724
|
-
if (!/^\d+$/.test(t) || !
|
|
129351
|
+
if (!/^\d+$/.test(t) || !isRec14(byOpponent)) continue;
|
|
128725
129352
|
const kept = {};
|
|
128726
129353
|
for (const [o, p] of Object.entries(byOpponent)) {
|
|
128727
129354
|
const v = /^\d+$/.test(o) ? primitivesOf(p) : void 0;
|
|
@@ -128785,9 +129412,9 @@ async function prune(dir, env) {
|
|
|
128785
129412
|
for (const name of await readdir9(folder)) {
|
|
128786
129413
|
const m = /^(\d+)-(\d+)\.json$/.exec(name);
|
|
128787
129414
|
if (!m) continue;
|
|
128788
|
-
const path =
|
|
129415
|
+
const path = join18(folder, name);
|
|
128789
129416
|
try {
|
|
128790
|
-
files.push({ path, mtime: (await
|
|
129417
|
+
files.push({ path, mtime: (await stat8(path)).mtimeMs, gameId: Number(m[1]), playerId: Number(m[2]) });
|
|
128791
129418
|
} catch {
|
|
128792
129419
|
}
|
|
128793
129420
|
}
|
|
@@ -128847,26 +129474,26 @@ async function recordBehaviour(dir, input2, env = process.env) {
|
|
|
128847
129474
|
}
|
|
128848
129475
|
}
|
|
128849
129476
|
async function writeGameFile(path, body) {
|
|
128850
|
-
await
|
|
129477
|
+
await mkdir12(join18(path, ".."), { recursive: true, mode: 448 });
|
|
128851
129478
|
const tmp = `${path}.${process.pid}.${randomUUID5()}.tmp`;
|
|
128852
129479
|
await writeFile11(tmp, JSON.stringify(body), { mode: 384 });
|
|
128853
|
-
await
|
|
129480
|
+
await rename12(tmp, path);
|
|
128854
129481
|
}
|
|
128855
129482
|
var MAX_PROFILE_ENTRIES = 30;
|
|
128856
129483
|
var MAX_PROFILE_PLAYERS = 1e3;
|
|
128857
129484
|
var MAX_POPULATION_ENTRIES = 500;
|
|
128858
|
-
var profilePlayersPath = (dir) =>
|
|
128859
|
-
var profilePopulationPath = (dir) =>
|
|
128860
|
-
var storeLock = (dir) =>
|
|
129485
|
+
var profilePlayersPath = (dir) => join18(dir, "profiles", "players.json");
|
|
129486
|
+
var profilePopulationPath = (dir) => join18(dir, "profiles", "population.json");
|
|
129487
|
+
var storeLock = (dir) => join18(dir, "profiles", ".store");
|
|
128861
129488
|
var ENDINGS = ["Won", "SurrenderAccepted", "Booted", "Eliminated", "EndedByVote"];
|
|
128862
129489
|
function endingOf(state) {
|
|
128863
129490
|
return ENDINGS.includes(state ?? "") ? state : "unknown";
|
|
128864
129491
|
}
|
|
128865
129492
|
var HASH3 = /^[0-9a-f]{32}$/;
|
|
128866
129493
|
var num2 = (v) => typeof v === "number" && Number.isFinite(v);
|
|
128867
|
-
var rateOf = (v) =>
|
|
129494
|
+
var rateOf = (v) => isRec14(v) && num2(v.e) && num2(v.n) ? { e: v.e, n: v.n } : void 0;
|
|
128868
129495
|
function habitsFrom(v) {
|
|
128869
|
-
if (!
|
|
129496
|
+
if (!isRec14(v)) return void 0;
|
|
128870
129497
|
const r = rateOf(v.reinforce);
|
|
128871
129498
|
const a = rateOf(v.attack);
|
|
128872
129499
|
const f = rateOf(v.firstStrike);
|
|
@@ -128875,12 +129502,12 @@ function habitsFrom(v) {
|
|
|
128875
129502
|
const x = v.reinforceExtra;
|
|
128876
129503
|
const s = v.stacking;
|
|
128877
129504
|
if (!r || !a || !f || !rt || !rk || !num2(v.turns)) return void 0;
|
|
128878
|
-
if (!
|
|
129505
|
+
if (!isRec14(x) || !num2(x.n) || !num2(x.sum) || !isRec14(s) || !num2(s.n) || !num2(s.sum) || !num2(s.sq)) return void 0;
|
|
128879
129506
|
return { reinforce: r, reinforceExtra: { n: x.n, sum: x.sum }, attack: a, firstStrike: f, stacking: { n: s.n, sum: s.sum, sq: s.sq }, retaliate: rt, retake: rk, turns: v.turns };
|
|
128880
129507
|
}
|
|
128881
129508
|
function totalsFrom(v) {
|
|
128882
129509
|
const out = {};
|
|
128883
|
-
if (!
|
|
129510
|
+
if (!isRec14(v)) return out;
|
|
128884
129511
|
for (const f of PROFILE_FORMATS) {
|
|
128885
129512
|
const h = habitsFrom(v[f]);
|
|
128886
129513
|
if (h) out[f] = h;
|
|
@@ -128889,7 +129516,7 @@ function totalsFrom(v) {
|
|
|
128889
129516
|
}
|
|
128890
129517
|
var isFormat2 = (v) => PROFILE_FORMATS.includes(v);
|
|
128891
129518
|
function entryFrom(v) {
|
|
128892
|
-
if (!
|
|
129519
|
+
if (!isRec14(v) || typeof v.key !== "string" || !HASH3.test(v.key) || !isFormat2(v.format) || !isInt7(v.players) || !isInt7(v.turnsSeen)) return void 0;
|
|
128893
129520
|
if (v.source !== "live" && v.source !== "history" || !num2(v.weight)) return void 0;
|
|
128894
129521
|
const habits = habitsFrom(v.habits);
|
|
128895
129522
|
if (!habits) return void 0;
|
|
@@ -128899,13 +129526,13 @@ function entryFrom(v) {
|
|
|
128899
129526
|
async function readStore2(path) {
|
|
128900
129527
|
let text;
|
|
128901
129528
|
try {
|
|
128902
|
-
text = await
|
|
129529
|
+
text = await readFile15(path, "utf8");
|
|
128903
129530
|
} catch (e) {
|
|
128904
129531
|
return e.code === "ENOENT" ? "missing" : "unreadable";
|
|
128905
129532
|
}
|
|
128906
129533
|
try {
|
|
128907
129534
|
const v = JSON.parse(text);
|
|
128908
|
-
return
|
|
129535
|
+
return isRec14(v) ? v : "unreadable";
|
|
128909
129536
|
} catch {
|
|
128910
129537
|
return "unreadable";
|
|
128911
129538
|
}
|
|
@@ -128914,10 +129541,10 @@ async function readPlayers(dir) {
|
|
|
128914
129541
|
const v = await readStore2(profilePlayersPath(dir));
|
|
128915
129542
|
if (v === "unreadable") return v;
|
|
128916
129543
|
if (v === "missing") return { version: 1, seq: 0, players: {} };
|
|
128917
|
-
if (v.version !== 1 || !
|
|
129544
|
+
if (v.version !== 1 || !isRec14(v.players)) return "unreadable";
|
|
128918
129545
|
const players = {};
|
|
128919
129546
|
for (const [k, p] of Object.entries(v.players)) {
|
|
128920
|
-
if (!HASH3.test(k) || !
|
|
129547
|
+
if (!HASH3.test(k) || !isRec14(p) || !isInt7(p.seq) || !isInt7(p.games) || !Array.isArray(p.entries)) continue;
|
|
128921
129548
|
players[k] = { seq: p.seq, games: p.games, totals: totalsFrom(p.totals), entries: p.entries.map(entryFrom).filter((e) => e !== void 0) };
|
|
128922
129549
|
}
|
|
128923
129550
|
return { version: 1, seq: isInt7(v.seq) ? v.seq : 0, players };
|
|
@@ -128929,7 +129556,7 @@ async function readPopulation(dir) {
|
|
|
128929
129556
|
if (v.version !== 1) return "unreadable";
|
|
128930
129557
|
const entries2 = [];
|
|
128931
129558
|
for (const e of Array.isArray(v.entries) ? v.entries : []) {
|
|
128932
|
-
if (!
|
|
129559
|
+
if (!isRec14(e) || typeof e.key !== "string" || !HASH3.test(e.key) || !isFormat2(e.format)) continue;
|
|
128933
129560
|
if (e.source !== "live" && e.source !== "history") continue;
|
|
128934
129561
|
const humans = habitsFrom(e.humans);
|
|
128935
129562
|
const ai = habitsFrom(e.ai);
|
|
@@ -128938,10 +129565,10 @@ async function readPopulation(dir) {
|
|
|
128938
129565
|
return { version: 1, games: isInt7(v.games) ? v.games : 0, totals: totalsFrom(v.totals), ai: habitsFrom(v.ai) ?? emptyHabits(), entries: entries2 };
|
|
128939
129566
|
}
|
|
128940
129567
|
async function writeStore(path, body) {
|
|
128941
|
-
await
|
|
129568
|
+
await mkdir12(join18(path, ".."), { recursive: true, mode: 448 });
|
|
128942
129569
|
const tmp = `${path}.${process.pid}.${randomUUID5()}.tmp`;
|
|
128943
129570
|
await writeFile11(tmp, JSON.stringify(body), { mode: 384 });
|
|
128944
|
-
await
|
|
129571
|
+
await rename12(tmp, path);
|
|
128945
129572
|
}
|
|
128946
129573
|
var sumOf = (list3) => list3.reduce((a, h) => addHabits(a, h), emptyHabits());
|
|
128947
129574
|
var sumTotals = (t) => sumOf(PROFILE_FORMATS.flatMap((f) => t[f] ? [t[f]] : []));
|
|
@@ -129022,7 +129649,7 @@ async function readProfileHistory(dir, ids2, game, env = process.env) {
|
|
|
129022
129649
|
if (players === "unreadable" || population === "unreadable") return "unreadable";
|
|
129023
129650
|
const pools = { byFormat: population.totals, all: sumTotals(population.totals), ai: population.ai, games: population.games };
|
|
129024
129651
|
const out = { players: /* @__PURE__ */ new Map(), pools };
|
|
129025
|
-
const saltText = await
|
|
129652
|
+
const saltText = await readFile15(playerRecordSaltPath(dir), "utf8").catch((e) => e.code === "ENOENT" ? null : "");
|
|
129026
129653
|
if (saltText === null) return out;
|
|
129027
129654
|
const salt = await playerRecordSalt(dir);
|
|
129028
129655
|
if (!salt) return "unreadable";
|
|
@@ -129108,7 +129735,7 @@ async function foldFinishedGame(dir, game, env = process.env) {
|
|
|
129108
129735
|
async function markHistoryFolded(dir, gameId, playerId) {
|
|
129109
129736
|
const path = profileGamePath(dir, gameId, playerId);
|
|
129110
129737
|
try {
|
|
129111
|
-
await
|
|
129738
|
+
await stat8(path);
|
|
129112
129739
|
} catch {
|
|
129113
129740
|
return;
|
|
129114
129741
|
}
|
|
@@ -129120,7 +129747,7 @@ async function markHistoryFolded(dir, gameId, playerId) {
|
|
|
129120
129747
|
}
|
|
129121
129748
|
async function profileFileState(dir, gameId, playerId) {
|
|
129122
129749
|
try {
|
|
129123
|
-
await
|
|
129750
|
+
await stat8(profileGamePath(dir, gameId, playerId));
|
|
129124
129751
|
} catch (e) {
|
|
129125
129752
|
return e.code === "ENOENT" ? "none" : "kept";
|
|
129126
129753
|
}
|
|
@@ -129139,7 +129766,7 @@ async function profileGameFolded(dir, me, gameId) {
|
|
|
129139
129766
|
try {
|
|
129140
129767
|
const population = await readPopulation(dir);
|
|
129141
129768
|
if (population === "unreadable") return true;
|
|
129142
|
-
const saltText = await
|
|
129769
|
+
const saltText = await readFile15(playerRecordSaltPath(dir), "utf8").catch((e) => e.code === "ENOENT" ? null : "");
|
|
129143
129770
|
if (saltText === null) return false;
|
|
129144
129771
|
const salt = await playerRecordSalt(dir);
|
|
129145
129772
|
if (!salt) return true;
|
|
@@ -129151,34 +129778,34 @@ async function profileGameFolded(dir, me, gameId) {
|
|
|
129151
129778
|
}
|
|
129152
129779
|
|
|
129153
129780
|
// src/finished-store.ts
|
|
129154
|
-
import { readdir as readdir10, readFile as
|
|
129155
|
-
import { join as
|
|
129781
|
+
import { readdir as readdir10, readFile as readFile16, stat as stat9, unlink as unlink12, utimes as utimes2 } from "node:fs/promises";
|
|
129782
|
+
import { join as join19 } from "node:path";
|
|
129156
129783
|
var MAX_FINISHED_RECORDS = 500;
|
|
129157
129784
|
var MAX_PROCESSED_KEYS = 5e3;
|
|
129158
129785
|
var MAX_RECORD_BOARDS_HEAD = 30;
|
|
129159
129786
|
var MAX_RECORD_BOARDS_TAIL = 30;
|
|
129160
129787
|
var VERSION4 = 1;
|
|
129161
129788
|
var FILE = /^[0-9a-f]{32}\.json$/;
|
|
129162
|
-
var finishedDir = (dir) =>
|
|
129163
|
-
var finishedPath = (dir, salt, me, gameId) =>
|
|
129164
|
-
var processedPath = (dir) =>
|
|
129789
|
+
var finishedDir = (dir) => join19(dir, "finished");
|
|
129790
|
+
var finishedPath = (dir, salt, me, gameId) => join19(finishedDir(dir), `${finishedGameKey(salt, me, gameId)}.json`);
|
|
129791
|
+
var processedPath = (dir) => join19(finishedDir(dir), "processed.json");
|
|
129165
129792
|
var KEY = /^[0-9a-f]{32}$/;
|
|
129166
129793
|
var OWNER_NEUTRAL2 = -1;
|
|
129167
129794
|
var OWNER_AVAILABLE = -2;
|
|
129168
129795
|
var OWNER_UNKNOWN = -3;
|
|
129169
129796
|
var FOG_WORD = /^[A-Za-z0-9]{1,20}$/;
|
|
129170
|
-
var
|
|
129797
|
+
var isRec15 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
129171
129798
|
var STATUSES = /* @__PURE__ */ new Set(["captured", "history-unreadable", "read-failed"]);
|
|
129172
129799
|
async function readFinishedState(path) {
|
|
129173
129800
|
let text;
|
|
129174
129801
|
try {
|
|
129175
|
-
text = await
|
|
129802
|
+
text = await readFile16(path, "utf8");
|
|
129176
129803
|
} catch (e) {
|
|
129177
129804
|
return e.code === "ENOENT" ? "missing" : "unreadable";
|
|
129178
129805
|
}
|
|
129179
129806
|
try {
|
|
129180
129807
|
const v = JSON.parse(text);
|
|
129181
|
-
if (!
|
|
129808
|
+
if (!isRec15(v) || v.version !== VERSION4 || typeof v.status !== "string" || !STATUSES.has(v.status)) return "unreadable";
|
|
129182
129809
|
return { status: v.status };
|
|
129183
129810
|
} catch {
|
|
129184
129811
|
return "unreadable";
|
|
@@ -129199,13 +129826,13 @@ async function readProcessed(dir) {
|
|
|
129199
129826
|
async function readProcessedKeys(dir) {
|
|
129200
129827
|
let text;
|
|
129201
129828
|
try {
|
|
129202
|
-
text = await
|
|
129829
|
+
text = await readFile16(processedPath(dir), "utf8");
|
|
129203
129830
|
} catch (e) {
|
|
129204
129831
|
return e.code === "ENOENT" ? [] : "unreadable";
|
|
129205
129832
|
}
|
|
129206
129833
|
try {
|
|
129207
129834
|
const v = JSON.parse(text);
|
|
129208
|
-
if (!
|
|
129835
|
+
if (!isRec15(v) || v.version !== VERSION4 || !Array.isArray(v.keys) || !v.keys.every((k) => typeof k === "string" && KEY.test(k))) return "unreadable";
|
|
129209
129836
|
return v.keys;
|
|
129210
129837
|
} catch {
|
|
129211
129838
|
return "unreadable";
|
|
@@ -129231,9 +129858,9 @@ async function pruneFinished(dir, keep, protect) {
|
|
|
129231
129858
|
const files = [];
|
|
129232
129859
|
for (const name of await readdir10(folder)) {
|
|
129233
129860
|
if (!FILE.test(name)) continue;
|
|
129234
|
-
const path =
|
|
129861
|
+
const path = join19(folder, name);
|
|
129235
129862
|
try {
|
|
129236
|
-
files.push({ path, at: (await
|
|
129863
|
+
files.push({ path, at: (await stat9(path)).mtimeMs });
|
|
129237
129864
|
} catch {
|
|
129238
129865
|
}
|
|
129239
129866
|
}
|
|
@@ -129328,12 +129955,12 @@ function storeBoards(boards, ids2, key) {
|
|
|
129328
129955
|
}
|
|
129329
129956
|
|
|
129330
129957
|
// src/outlook-log.ts
|
|
129331
|
-
import { mkdir as
|
|
129958
|
+
import { mkdir as mkdir13, readFile as readFile17, rename as rename13, writeFile as writeFile12 } from "node:fs/promises";
|
|
129332
129959
|
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
129333
|
-
import { join as
|
|
129334
|
-
var
|
|
129960
|
+
import { join as join20 } from "node:path";
|
|
129961
|
+
var isRec16 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
129335
129962
|
var OUTLOOK_LOG_TURNS = 500;
|
|
129336
|
-
var outlookLogPath = (dir, gameId) =>
|
|
129963
|
+
var outlookLogPath = (dir, gameId) => join20(dir, "outlook", `${gameId}.json`);
|
|
129337
129964
|
var logged = (e) => ({
|
|
129338
129965
|
incomes: e.incomes ? { ...e.incomes, ...e.incomes.players ? { players: [...e.incomes.players] } : {} } : null,
|
|
129339
129966
|
opponents: e.opponents.map(({ playerId, income, source, coverage, thin }) => ({ playerId, income, source, coverage, thin })),
|
|
@@ -129341,8 +129968,8 @@ var logged = (e) => ({
|
|
|
129341
129968
|
});
|
|
129342
129969
|
async function readOutlookLog(dir, gameId, playerId) {
|
|
129343
129970
|
try {
|
|
129344
|
-
const c = JSON.parse(await
|
|
129345
|
-
if (!
|
|
129971
|
+
const c = JSON.parse(await readFile17(outlookLogPath(dir, gameId), "utf8"));
|
|
129972
|
+
if (!isRec16(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec16(c.turns)) return void 0;
|
|
129346
129973
|
return c;
|
|
129347
129974
|
} catch {
|
|
129348
129975
|
return void 0;
|
|
@@ -129350,10 +129977,10 @@ async function readOutlookLog(dir, gameId, playerId) {
|
|
|
129350
129977
|
}
|
|
129351
129978
|
async function write(dir, log) {
|
|
129352
129979
|
const path = outlookLogPath(dir, log.gameId);
|
|
129353
|
-
await
|
|
129980
|
+
await mkdir13(join20(dir, "outlook"), { recursive: true, mode: 448 });
|
|
129354
129981
|
const tmp = `${path}.${process.pid}.${randomUUID6()}.tmp`;
|
|
129355
129982
|
await writeFile12(tmp, JSON.stringify(log), { mode: 384 });
|
|
129356
|
-
await
|
|
129983
|
+
await rename13(tmp, path);
|
|
129357
129984
|
}
|
|
129358
129985
|
async function recordOutlook(dir, gameId, playerId, outlook) {
|
|
129359
129986
|
try {
|
|
@@ -129419,8 +130046,8 @@ async function recordResult(dir, gameId, playerId, result) {
|
|
|
129419
130046
|
}
|
|
129420
130047
|
async function readOutlookPlayer(dir, gameId) {
|
|
129421
130048
|
try {
|
|
129422
|
-
const c = JSON.parse(await
|
|
129423
|
-
return
|
|
130049
|
+
const c = JSON.parse(await readFile17(outlookLogPath(dir, gameId), "utf8"));
|
|
130050
|
+
return isRec16(c) && c.gameId === gameId && typeof c.playerId === "number" ? c.playerId : void 0;
|
|
129424
130051
|
} catch {
|
|
129425
130052
|
return void 0;
|
|
129426
130053
|
}
|
|
@@ -129440,8 +130067,8 @@ async function recordLoss(dir, gameId, playerId, loss) {
|
|
|
129440
130067
|
async function recordFinalResult(dir, game) {
|
|
129441
130068
|
if (game.state !== "Finished") return false;
|
|
129442
130069
|
try {
|
|
129443
|
-
const c = JSON.parse(await
|
|
129444
|
-
if (!
|
|
130070
|
+
const c = JSON.parse(await readFile17(outlookLogPath(dir, game.id), "utf8"));
|
|
130071
|
+
if (!isRec16(c) || typeof c.playerId !== "number") return false;
|
|
129445
130072
|
const playerId = c.playerId;
|
|
129446
130073
|
const state = game.players.find((p) => p.id === playerId)?.state;
|
|
129447
130074
|
return state === void 0 ? false : await recordResult(dir, game.id, playerId, state);
|
|
@@ -129451,7 +130078,7 @@ async function recordFinalResult(dir, game) {
|
|
|
129451
130078
|
}
|
|
129452
130079
|
|
|
129453
130080
|
// src/tools/profile-hook.ts
|
|
129454
|
-
import { stat as
|
|
130081
|
+
import { stat as stat10, utimes as utimes3 } from "node:fs/promises";
|
|
129455
130082
|
function observeSettings(game) {
|
|
129456
130083
|
const s = game.settings;
|
|
129457
130084
|
return {
|
|
@@ -129545,7 +130172,7 @@ async function foldFinished(dataDir2, env, game) {
|
|
|
129545
130172
|
);
|
|
129546
130173
|
if (!kept) return nothing("no-turns");
|
|
129547
130174
|
const path = profileGamePath(dataDir2, game.id, me);
|
|
129548
|
-
const boardTime = await
|
|
130175
|
+
const boardTime = await stat10(boardCachePath(dataDir2, game.id)).then((s) => s.mtime).catch(() => void 0);
|
|
129549
130176
|
if (!await foldFinishedGame(dataDir2, resolved, env)) return nothing("failed");
|
|
129550
130177
|
if (boardTime) await utimes3(path, boardTime, boardTime).catch(() => void 0);
|
|
129551
130178
|
return { status: "folded", source: "backfill", opponents: await foldedOpponents(dataDir2, env, resolved, me) };
|
|
@@ -129802,9 +130429,9 @@ function firstMoverOnTurn(input2) {
|
|
|
129802
130429
|
}
|
|
129803
130430
|
|
|
129804
130431
|
// src/move-order.ts
|
|
129805
|
-
import { mkdir as
|
|
129806
|
-
import { join as
|
|
129807
|
-
var firstMoverPath = (dir, gameId) =>
|
|
130432
|
+
import { mkdir as mkdir14, readdir as readdir11, readFile as readFile18, rename as rename14, stat as stat11, unlink as unlink13, writeFile as writeFile13 } from "node:fs/promises";
|
|
130433
|
+
import { join as join21 } from "node:path";
|
|
130434
|
+
var firstMoverPath = (dir, gameId) => join21(dir, "move-order", `${gameId}.json`);
|
|
129808
130435
|
var FIRST_MOVER_MAX_AGE_MS = 60 * 864e5;
|
|
129809
130436
|
var FILE2 = /^\d+\.json$/;
|
|
129810
130437
|
var pruned3 = /* @__PURE__ */ new Set();
|
|
@@ -129850,7 +130477,7 @@ function verifiedFirstMover(resolved) {
|
|
|
129850
130477
|
var same = (a, b) => b !== void 0 && a.turn === b.turn && a.firstMover === b.firstMover && a.source === b.source;
|
|
129851
130478
|
async function readFirstMover(dir, gameId, playerId) {
|
|
129852
130479
|
try {
|
|
129853
|
-
const c = JSON.parse(await
|
|
130480
|
+
const c = JSON.parse(await readFile18(firstMoverPath(dir, gameId), "utf8"));
|
|
129854
130481
|
if (typeof c !== "object" || c === null || Array.isArray(c)) return void 0;
|
|
129855
130482
|
const r = c;
|
|
129856
130483
|
if (r.gameId !== gameId || r.playerId !== playerId) return void 0;
|
|
@@ -129861,16 +130488,16 @@ async function readFirstMover(dir, gameId, playerId) {
|
|
|
129861
130488
|
}
|
|
129862
130489
|
}
|
|
129863
130490
|
async function prune2(dir) {
|
|
129864
|
-
const base =
|
|
130491
|
+
const base = join21(dir, "move-order");
|
|
129865
130492
|
if (pruned3.has(base)) return;
|
|
129866
130493
|
pruned3.add(base);
|
|
129867
130494
|
const cutoff = Date.now() - FIRST_MOVER_MAX_AGE_MS;
|
|
129868
130495
|
try {
|
|
129869
130496
|
for (const name of await readdir11(base)) {
|
|
129870
130497
|
if (!FILE2.test(name)) continue;
|
|
129871
|
-
const file2 =
|
|
130498
|
+
const file2 = join21(base, name);
|
|
129872
130499
|
try {
|
|
129873
|
-
if ((await
|
|
130500
|
+
if ((await stat11(file2)).mtimeMs < cutoff) await unlink13(file2);
|
|
129874
130501
|
} catch {
|
|
129875
130502
|
}
|
|
129876
130503
|
}
|
|
@@ -129881,10 +130508,10 @@ async function writeFirstMover(dir, gameId, playerId, seen2) {
|
|
|
129881
130508
|
if (!isTurn(seen2.turn) || !isMover(seen2.firstMover) || !isSource(seen2.source)) return false;
|
|
129882
130509
|
try {
|
|
129883
130510
|
const path = firstMoverPath(dir, gameId);
|
|
129884
|
-
await
|
|
130511
|
+
await mkdir14(join21(dir, "move-order"), { recursive: true, mode: 448 });
|
|
129885
130512
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
129886
130513
|
await writeFile13(tmp, JSON.stringify({ gameId, playerId, turn: seen2.turn, firstMover: seen2.firstMover, source: seen2.source }), { mode: 384 });
|
|
129887
|
-
await
|
|
130514
|
+
await rename14(tmp, path);
|
|
129888
130515
|
await prune2(dir);
|
|
129889
130516
|
return true;
|
|
129890
130517
|
} catch {
|
|
@@ -130723,7 +131350,7 @@ function registerTeamTool(server, ctx) {
|
|
|
130723
131350
|
async ({ game_id }) => {
|
|
130724
131351
|
const gameId = parseGameId(game_id);
|
|
130725
131352
|
const identity = await ctx.myIdentity().catch(() => void 0);
|
|
130726
|
-
if (!identity) throw accountUnknown(ctx
|
|
131353
|
+
if (!identity) throw accountUnknown(ctx, "your team cannot be read");
|
|
130727
131354
|
const read = await ctx.client.getGame(gameId, { settings: true, chat: true });
|
|
130728
131355
|
const { game, source } = await resolveTeams(ctx, read);
|
|
130729
131356
|
const me = game.players.find((p) => p.id === identity.token);
|
|
@@ -132494,44 +133121,44 @@ function guessOrdersOf(orders, guess) {
|
|
|
132494
133121
|
}
|
|
132495
133122
|
|
|
132496
133123
|
// src/guess-salt.ts
|
|
132497
|
-
import { randomBytes as
|
|
132498
|
-
import { mkdir as
|
|
132499
|
-
import { join as
|
|
133124
|
+
import { randomBytes as randomBytes9 } from "node:crypto";
|
|
133125
|
+
import { mkdir as mkdir15, readFile as readFile19, rename as rename15, writeFile as writeFile14 } from "node:fs/promises";
|
|
133126
|
+
import { join as join22 } from "node:path";
|
|
132500
133127
|
var SALT2 = /^[0-9a-f]{32}$/;
|
|
132501
133128
|
var processSalt;
|
|
132502
133129
|
var cached2 = /* @__PURE__ */ new Map();
|
|
132503
|
-
var guessSaltPath = (dir) =>
|
|
133130
|
+
var guessSaltPath = (dir) => join22(dir, "guess-salt");
|
|
132504
133131
|
async function peekGuessSalt(dir) {
|
|
132505
133132
|
if (!dir) return processSalt;
|
|
132506
133133
|
const hit = cached2.get(dir);
|
|
132507
133134
|
if (hit) return hit;
|
|
132508
133135
|
try {
|
|
132509
|
-
const text = (await
|
|
133136
|
+
const text = (await readFile19(guessSaltPath(dir), "utf8")).trim();
|
|
132510
133137
|
if (SALT2.test(text)) return text;
|
|
132511
133138
|
} catch {
|
|
132512
133139
|
}
|
|
132513
133140
|
return processSalt;
|
|
132514
133141
|
}
|
|
132515
133142
|
async function guessSalt(dir) {
|
|
132516
|
-
const fallback = () => processSalt ??=
|
|
133143
|
+
const fallback = () => processSalt ??= randomBytes9(16).toString("hex");
|
|
132517
133144
|
if (!dir) return fallback();
|
|
132518
133145
|
const hit = cached2.get(dir);
|
|
132519
133146
|
if (hit) return hit;
|
|
132520
133147
|
const path = guessSaltPath(dir);
|
|
132521
133148
|
try {
|
|
132522
|
-
const text = (await
|
|
133149
|
+
const text = (await readFile19(path, "utf8")).trim();
|
|
132523
133150
|
if (SALT2.test(text)) {
|
|
132524
133151
|
cached2.set(dir, text);
|
|
132525
133152
|
return text;
|
|
132526
133153
|
}
|
|
132527
133154
|
} catch {
|
|
132528
133155
|
}
|
|
132529
|
-
const salt =
|
|
133156
|
+
const salt = randomBytes9(16).toString("hex");
|
|
132530
133157
|
try {
|
|
132531
|
-
await
|
|
133158
|
+
await mkdir15(dir, { recursive: true, mode: 448 });
|
|
132532
133159
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
132533
133160
|
await writeFile14(tmp, salt, { mode: 384 });
|
|
132534
|
-
await
|
|
133161
|
+
await rename15(tmp, path);
|
|
132535
133162
|
cached2.set(dir, salt);
|
|
132536
133163
|
return salt;
|
|
132537
133164
|
} catch {
|
|
@@ -138464,7 +139091,7 @@ async function listMyGames(read, windows = MY_GAMES_WINDOWS) {
|
|
|
138464
139091
|
async function myInGameId(ctx) {
|
|
138465
139092
|
const me = await ctx.myInGameId();
|
|
138466
139093
|
if (me === void 0) {
|
|
138467
|
-
throw accountUnknown(ctx
|
|
139094
|
+
throw accountUnknown(ctx, "its games cannot be listed");
|
|
138468
139095
|
}
|
|
138469
139096
|
return me;
|
|
138470
139097
|
}
|
|
@@ -138556,14 +139183,14 @@ function registerMyGamesTool(server, ctx, deps = {}) {
|
|
|
138556
139183
|
var MAX_TEAM_RECORDS = 200;
|
|
138557
139184
|
var TEAM_RECORD_VERSION = 2;
|
|
138558
139185
|
var TEAM_FILE = /^\d+\.json$/;
|
|
138559
|
-
var teamsDir = (dir) =>
|
|
138560
|
-
var teamRecordPath = (dir, gameId) =>
|
|
138561
|
-
var
|
|
139186
|
+
var teamsDir = (dir) => join23(dir, "teams");
|
|
139187
|
+
var teamRecordPath = (dir, gameId) => join23(teamsDir(dir), `${gameId}.json`);
|
|
139188
|
+
var isRec17 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
138562
139189
|
var isInt10 = (v) => typeof v === "number" && Number.isInteger(v);
|
|
138563
139190
|
async function readTeamFile(dir, gameId) {
|
|
138564
139191
|
try {
|
|
138565
|
-
const r = JSON.parse(await
|
|
138566
|
-
if (!
|
|
139192
|
+
const r = JSON.parse(await readFile20(teamRecordPath(dir, gameId), "utf8"));
|
|
139193
|
+
if (!isRec17(r) || r.version !== TEAM_RECORD_VERSION || r.gameId !== gameId) return void 0;
|
|
138567
139194
|
if (!("teams" in r)) return isInt10(r.incompleteTurn) ? { incompleteTurn: r.incompleteTurn } : void 0;
|
|
138568
139195
|
if (!Array.isArray(r.teams)) return void 0;
|
|
138569
139196
|
const out = /* @__PURE__ */ new Map();
|
|
@@ -138586,14 +139213,14 @@ async function pruneTeams(dir, keep) {
|
|
|
138586
139213
|
for (const name of await readdir12(folder)) {
|
|
138587
139214
|
if (!TEAM_FILE.test(name) || name === `${keep}.json`) continue;
|
|
138588
139215
|
try {
|
|
138589
|
-
files.push({ name, at: (await
|
|
139216
|
+
files.push({ name, at: (await stat12(join23(folder, name))).mtimeMs });
|
|
138590
139217
|
} catch {
|
|
138591
139218
|
}
|
|
138592
139219
|
}
|
|
138593
139220
|
const excess = files.length + 1 - MAX_TEAM_RECORDS;
|
|
138594
139221
|
if (excess <= 0) return;
|
|
138595
139222
|
files.sort((a, b) => a.at - b.at || a.name.localeCompare(b.name));
|
|
138596
|
-
for (const f of files.slice(0, excess)) await unlink14(
|
|
139223
|
+
for (const f of files.slice(0, excess)) await unlink14(join23(folder, f.name)).catch(() => {
|
|
138597
139224
|
});
|
|
138598
139225
|
}
|
|
138599
139226
|
async function writeRecord3(dir, gameId, body) {
|
|
@@ -140185,7 +140812,7 @@ function registerMarkChatReadTool(server, ctx) {
|
|
|
140185
140812
|
async plan({ game_id, channel }) {
|
|
140186
140813
|
const game = await ctx.client.getGame(game_id, { chat: true, map: false });
|
|
140187
140814
|
const me = await ctx.myIdentity({ fresh: true }).catch(() => void 0);
|
|
140188
|
-
if (!me) throw accountUnknown(ctx
|
|
140815
|
+
if (!me) throw accountUnknown(ctx);
|
|
140189
140816
|
const read = await readChat(ctx, game, me);
|
|
140190
140817
|
if (!read || read.source === "gamefeed") {
|
|
140191
140818
|
refuse(
|
|
@@ -140999,146 +141626,13 @@ function registerGameTool(server, client, dir, env, identity) {
|
|
|
140999
141626
|
);
|
|
141000
141627
|
}
|
|
141001
141628
|
|
|
141002
|
-
// src/direct/session.ts
|
|
141003
|
-
import { execFile } from "node:child_process";
|
|
141004
|
-
import { randomBytes as randomBytes9 } from "node:crypto";
|
|
141005
|
-
import { readFileSync as readFileSync2 } from "node:fs";
|
|
141006
|
-
import { chmod as chmod4, mkdir as mkdir15, open as open2, readFile as readFile20, rename as rename15, rm as rm5, stat as stat12 } from "node:fs/promises";
|
|
141007
|
-
import { dirname, join as join23, resolve } from "node:path";
|
|
141008
|
-
import { promisify } from "node:util";
|
|
141009
|
-
var SESSION_HOST = "war.app";
|
|
141010
|
-
var isRec17 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
141011
|
-
function sessionFilePath(env = process.env) {
|
|
141012
|
-
return readEnvVar("WARAPP_SESSION_FILE", { env }) ?? join23(dataDir(env), "session.json");
|
|
141013
|
-
}
|
|
141014
|
-
function parseSession(raw) {
|
|
141015
|
-
if (!isRec17(raw)) return null;
|
|
141016
|
-
const { authToken, capturedAt, host } = raw;
|
|
141017
|
-
if (typeof authToken !== "string" || authToken.length === 0) return null;
|
|
141018
|
-
if (typeof capturedAt !== "string" || capturedAt.length === 0) return null;
|
|
141019
|
-
if (host !== SESSION_HOST) return null;
|
|
141020
|
-
return { authToken, capturedAt, host };
|
|
141021
|
-
}
|
|
141022
|
-
async function readSession(env = process.env) {
|
|
141023
|
-
if (isHosted(env)) return null;
|
|
141024
|
-
try {
|
|
141025
|
-
return parseSession(JSON.parse(await readFile20(sessionFilePath(env), "utf8")));
|
|
141026
|
-
} catch {
|
|
141027
|
-
return null;
|
|
141028
|
-
}
|
|
141029
|
-
}
|
|
141030
|
-
function readSessionSync(env = process.env) {
|
|
141031
|
-
if (isHosted(env)) return null;
|
|
141032
|
-
try {
|
|
141033
|
-
return parseSession(JSON.parse(readFileSync2(sessionFilePath(env), "utf8")));
|
|
141034
|
-
} catch {
|
|
141035
|
-
return null;
|
|
141036
|
-
}
|
|
141037
|
-
}
|
|
141038
|
-
function sessionDirVerdict(st, myUid) {
|
|
141039
|
-
if (myUid === void 0) return "ok";
|
|
141040
|
-
if (st.uid === myUid) return (st.mode & 63) !== 0 ? "tighten" : "ok";
|
|
141041
|
-
if (st.uid !== 0) return "refuse";
|
|
141042
|
-
return (st.mode & 18) !== 0 ? "refuse" : "ok";
|
|
141043
|
-
}
|
|
141044
|
-
var run = promisify(execFile);
|
|
141045
|
-
var MACOS_ACLS = process.platform === "darwin";
|
|
141046
|
-
function lsShowsAcl(stdout) {
|
|
141047
|
-
return stdout.split("\n").slice(1).some((line) => /^\s*\d+: /.test(line));
|
|
141048
|
-
}
|
|
141049
|
-
async function hasAcl(path) {
|
|
141050
|
-
const { stdout } = await run("/bin/ls", ["-led", path]);
|
|
141051
|
-
return lsShowsAcl(stdout);
|
|
141052
|
-
}
|
|
141053
|
-
async function stripAcl(path, what) {
|
|
141054
|
-
await run("/bin/chmod", ["-N", path]);
|
|
141055
|
-
if (await hasAcl(path)) {
|
|
141056
|
-
throw new McpToolError(`Refusing to store the war.app session: could not remove the access control list on ${what}.`, {
|
|
141057
|
-
hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory only you can read, with no ACL (`ls -le`)."
|
|
141058
|
-
});
|
|
141059
|
-
}
|
|
141060
|
-
}
|
|
141061
|
-
function sessionTmpPath(path) {
|
|
141062
|
-
return `${path}.${randomBytes9(16).toString("hex")}.tmp`;
|
|
141063
|
-
}
|
|
141064
|
-
async function writeSession(session, env = process.env) {
|
|
141065
|
-
if (isHosted(env)) {
|
|
141066
|
-
throw new McpToolError("The direct transport is local-only: a hosted server never stores a war.app session.", {
|
|
141067
|
-
kind: "unknown"
|
|
141068
|
-
});
|
|
141069
|
-
}
|
|
141070
|
-
const path = resolve(sessionFilePath(env));
|
|
141071
|
-
const dir = dirname(path);
|
|
141072
|
-
await mkdir15(dir, { recursive: true, mode: 448 });
|
|
141073
|
-
const st = await stat12(dir);
|
|
141074
|
-
const myUid = process.getuid?.();
|
|
141075
|
-
const verdict = sessionDirVerdict(st, myUid);
|
|
141076
|
-
if (verdict === "refuse") {
|
|
141077
|
-
throw new McpToolError(`Refusing to store the war.app session in ${dir}: it is not yours, and others could reach files in it.`, {
|
|
141078
|
-
hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory of your own that only you can write to."
|
|
141079
|
-
});
|
|
141080
|
-
}
|
|
141081
|
-
if (verdict === "tighten") await chmod4(dir, 448);
|
|
141082
|
-
if (MACOS_ACLS) {
|
|
141083
|
-
if (st.uid === myUid) await stripAcl(dir, dir);
|
|
141084
|
-
else if (await hasAcl(dir)) {
|
|
141085
|
-
throw new McpToolError(`Refusing to store the war.app session in ${dir}: it carries an access control list and is not yours.`, {
|
|
141086
|
-
hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory of your own that only you can read."
|
|
141087
|
-
});
|
|
141088
|
-
}
|
|
141089
|
-
}
|
|
141090
|
-
const tmp = sessionTmpPath(path);
|
|
141091
|
-
const file2 = await open2(tmp, "wx", 384);
|
|
141092
|
-
try {
|
|
141093
|
-
try {
|
|
141094
|
-
await file2.chmod(384);
|
|
141095
|
-
if (MACOS_ACLS) await stripAcl(tmp, "the session file");
|
|
141096
|
-
await file2.writeFile(JSON.stringify(session));
|
|
141097
|
-
} finally {
|
|
141098
|
-
await file2.close();
|
|
141099
|
-
}
|
|
141100
|
-
await rename15(tmp, path);
|
|
141101
|
-
} catch (e) {
|
|
141102
|
-
await rm5(tmp, { force: true }).catch(() => {
|
|
141103
|
-
});
|
|
141104
|
-
throw e;
|
|
141105
|
-
}
|
|
141106
|
-
}
|
|
141107
|
-
var SCRUBBED = "[warapp-session]";
|
|
141108
|
-
function scrubToken(s, token) {
|
|
141109
|
-
if (!token) return s;
|
|
141110
|
-
return scrubSecrets(s, [token, stripBearer(token)], SCRUBBED);
|
|
141111
|
-
}
|
|
141112
|
-
function errorStrings(err, depth = 0) {
|
|
141113
|
-
if (depth > 4 || typeof err !== "object" || err === null) return typeof err === "string" ? [err] : [];
|
|
141114
|
-
const e = err;
|
|
141115
|
-
const own2 = [e.message, e.hint, e.stack].filter((v) => typeof v === "string");
|
|
141116
|
-
return [...own2, ...errorStrings(e.cause, depth + 1)];
|
|
141117
|
-
}
|
|
141118
|
-
function errorCarriesToken(err, tokens) {
|
|
141119
|
-
const strings = errorStrings(err);
|
|
141120
|
-
return tokens.some((t) => !!t && strings.some((s) => scrubToken(s, t) !== s));
|
|
141121
|
-
}
|
|
141122
|
-
function scrubError(err, tokens) {
|
|
141123
|
-
if (!errorCarriesToken(err, tokens)) return err;
|
|
141124
|
-
const ordered = tokens.filter((t) => !!t).sort((a, b) => b.length - a.length);
|
|
141125
|
-
const scrub = (s) => ordered.reduce((acc, t) => scrubToken(acc, t), s);
|
|
141126
|
-
const e = typeof err === "object" && err !== null ? err : {};
|
|
141127
|
-
const message = scrub(typeof e.message === "string" ? e.message : String(err));
|
|
141128
|
-
const kind = err instanceof McpToolError && err.kind ? err.kind : "transport";
|
|
141129
|
-
return new McpToolError(message, {
|
|
141130
|
-
kind,
|
|
141131
|
-
...typeof e.status === "number" ? { status: e.status } : {},
|
|
141132
|
-
...typeof e.hint === "string" ? { hint: scrub(e.hint) } : {}
|
|
141133
|
-
});
|
|
141134
|
-
}
|
|
141135
|
-
|
|
141136
141629
|
// src/tools/healthcheck.ts
|
|
141137
141630
|
var PROBE_PATH = `/API/GameFeed?GameID=${PROBE_GAME_ID}&GetMap=false`;
|
|
141138
141631
|
var BRIDGE_PROBE_PATH = "/";
|
|
141139
141632
|
function sessionSummary(env, now) {
|
|
141140
141633
|
const s = readSessionSync(env);
|
|
141141
141634
|
if (!s) return { linked: false };
|
|
141635
|
+
if (s.origin === "host") return { linked: true, linkedBy: "host" };
|
|
141142
141636
|
const ageSeconds = Math.max(0, Math.round((now() - Date.parse(s.capturedAt)) / 1e3));
|
|
141143
141637
|
return { linked: true, capturedAt: s.capturedAt, ageSeconds };
|
|
141144
141638
|
}
|
|
@@ -141713,7 +142207,7 @@ function captureWarappCookie(opts) {
|
|
|
141713
142207
|
}
|
|
141714
142208
|
async function linkSession(opts = {}) {
|
|
141715
142209
|
if (isHosted(opts.env ?? process.env)) {
|
|
141716
|
-
throw new McpToolError("
|
|
142210
|
+
throw new McpToolError("Linking a war.app session is local-only: a hosted server reaches war.app directly only from the session captured at sign-in, and never links one.", {
|
|
141717
142211
|
kind: "unknown"
|
|
141718
142212
|
});
|
|
141719
142213
|
}
|
|
@@ -141732,7 +142226,10 @@ async function linkSession(opts = {}) {
|
|
|
141732
142226
|
|
|
141733
142227
|
// src/tools/session.ts
|
|
141734
142228
|
var HINT_NOT_LINKED = "No war.app session is linked. Run warapp_link_session to use the direct (no-browser) transport; the browser bridge is used until then.";
|
|
141735
|
-
var NOTE_HOSTED = "This server is hosted: the
|
|
142229
|
+
var NOTE_HOSTED = "This server is hosted: it reaches war.app directly only from the session captured at sign-in, and this connection has none, so war.app calls go through the browser bridge and your signed-in war.app tab. " + HOST_SIGN_IN_ADVICE;
|
|
142230
|
+
var NOTE_HOSTED_DIRECT = "This server is hosted and signed in to war.app by mcp-host: war.app calls go directly to war.app with the session captured at sign-in, and fall back to the browser bridge only when that session stops working.";
|
|
142231
|
+
var NOTE_HOSTED_MALFORMED = `This server is hosted, and the war.app session mcp-host passed it is not usable, so war.app calls go through the browser bridge and your signed-in war.app tab. ${HOST_SIGN_IN_ADVICE}`;
|
|
142232
|
+
var HINT_HOST_EXPIRED = `The war.app session this connection signed in with is signed out. ${HOST_SIGN_IN_ADVICE}`;
|
|
141736
142233
|
var HINT_EXPIRED = "The linked war.app session is signed out (war.app answered a direct call signed-out this run). Run warapp_link_session to relink.";
|
|
141737
142234
|
function noBrowserNote(hosted) {
|
|
141738
142235
|
return hosted ? "" : " Works without a browser once a session is linked (warapp_link_session).";
|
|
@@ -141742,6 +142239,7 @@ function registerSessionTools(server, deps) {
|
|
|
141742
142239
|
const link3 = deps.link ?? ((opts) => linkSession({ ...deps.env ? { env: deps.env } : {}, ...opts }));
|
|
141743
142240
|
const now = deps.now ?? Date.now;
|
|
141744
142241
|
const hosted = deps.hosted ?? isHosted(deps.env ?? process.env);
|
|
142242
|
+
const hostToken = hosted ? deps.hostToken ?? hostedTokenState(deps.env ?? process.env) : "none";
|
|
141745
142243
|
const decoderView = () => {
|
|
141746
142244
|
if (!deps.decoder) return {};
|
|
141747
142245
|
const d = deps.decoder();
|
|
@@ -141764,13 +142262,30 @@ function registerSessionTools(server, deps) {
|
|
|
141764
142262
|
{
|
|
141765
142263
|
title: "war.app direct-transport session status",
|
|
141766
142264
|
description: untrustedDescription(
|
|
141767
|
-
hosted ? "Report which transport serves war.app calls on this hosted server (
|
|
142265
|
+
hosted && hostToken === "ok" ? "Report which transport serves war.app calls on this hosted server (direct to war.app with the session mcp-host captured at sign-in, or the browser bridge after that session stops working) and which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Never shows the session cookie. Read-only." : hosted ? "Report which transport serves war.app calls on this hosted server (the browser bridge: hosted, the direct, no-browser transport runs only from the session captured at sign-in, and this connection has none) and which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Read-only." : "Report whether a signed-in war.app session is linked for the direct (no-browser) transport, when it was captured and how old it is, which transport is currently active (direct, or the browser bridge), and which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Never shows the session cookie. Read-only; use warapp_link_session to link or relink."
|
|
141768
142266
|
),
|
|
141769
142267
|
_meta: lookupMeta(["war.app session", "is war.app linked", "direct transport status"]),
|
|
141770
142268
|
annotations: readAnnotations("war.app session status"),
|
|
141771
142269
|
inputSchema: external_exports.object({})
|
|
141772
142270
|
},
|
|
141773
142271
|
async () => {
|
|
142272
|
+
if (hosted && hostToken === "ok") {
|
|
142273
|
+
const pt2 = deps.pushTransport?.();
|
|
142274
|
+
const base = {
|
|
142275
|
+
hosted: true,
|
|
142276
|
+
linked: true,
|
|
142277
|
+
linkedBy: "host",
|
|
142278
|
+
activeTransport: deps.transport.activeLeg(),
|
|
142279
|
+
...pt2 ? { pushTransport: pt2 } : {},
|
|
142280
|
+
...decoderView(),
|
|
142281
|
+
hostedNote: NOTE_HOSTED_DIRECT
|
|
142282
|
+
};
|
|
142283
|
+
return respond(
|
|
142284
|
+
void 0,
|
|
142285
|
+
["compact"],
|
|
142286
|
+
() => deps.transport.sessionStale() ? { ...base, sessionExpired: true, hint: HINT_HOST_EXPIRED } : base
|
|
142287
|
+
);
|
|
142288
|
+
}
|
|
141774
142289
|
if (hosted) {
|
|
141775
142290
|
const pt2 = deps.pushTransport?.();
|
|
141776
142291
|
return respond(void 0, ["compact"], () => ({
|
|
@@ -141779,7 +142294,7 @@ function registerSessionTools(server, deps) {
|
|
|
141779
142294
|
activeTransport: "fetchproxy",
|
|
141780
142295
|
...pt2 ? { pushTransport: pt2 } : {},
|
|
141781
142296
|
...decoderView(),
|
|
141782
|
-
hostedNote: NOTE_HOSTED
|
|
142297
|
+
hostedNote: hostToken === "malformed" ? NOTE_HOSTED_MALFORMED : NOTE_HOSTED
|
|
141783
142298
|
}));
|
|
141784
142299
|
}
|
|
141785
142300
|
const session = await read();
|
|
@@ -141853,7 +142368,7 @@ async function openGamesPage(ctx) {
|
|
|
141853
142368
|
} catch (e) {
|
|
141854
142369
|
throw new McpToolError(`Could not read war.app's open games page: ${e instanceof Error ? e.message : String(e)}`, {
|
|
141855
142370
|
kind: "unknown",
|
|
141856
|
-
hint: (ctx.hosted ? "Make sure" : "Link a session with warapp_link_session to read it without a browser, or make sure") + " a signed-in war.app tab is open and paired (reload or focus it if it is frozen), then retry.",
|
|
142371
|
+
hint: ctx.hosted && ctx.hostSignIn ? `${HOST_SIGN_IN_ADVICE} Then retry.` : (ctx.hosted ? "Make sure" : "Link a session with warapp_link_session to read it without a browser, or make sure") + " a signed-in war.app tab is open and paired (reload or focus it if it is frozen), then retry.",
|
|
141857
142372
|
cause: e
|
|
141858
142373
|
});
|
|
141859
142374
|
}
|
|
@@ -142090,7 +142605,7 @@ function registerJoinGameTool(server, ctx) {
|
|
|
142090
142605
|
async plan({ game_id, allow_team, team: askedTeam, accept_entry_fee, color: requested }) {
|
|
142091
142606
|
const gameId = parseGameId(game_id);
|
|
142092
142607
|
const [html, me] = await Promise.all([openGamesPage(ctx), ctx.myIdentity({ fresh: true })]);
|
|
142093
|
-
if (me === void 0) throw accountUnknown(ctx
|
|
142608
|
+
if (me === void 0) throw accountUnknown(ctx);
|
|
142094
142609
|
const { token, inGameId: myId } = me;
|
|
142095
142610
|
const bundle = await ctx.bundle();
|
|
142096
142611
|
const parsed = parseOpenGamesPage(html, bundle);
|
|
@@ -144779,7 +145294,7 @@ function registerTeamBriefTool(server, ctx) {
|
|
|
144779
145294
|
async ({ game_id }) => {
|
|
144780
145295
|
const gameId = parseGameId(game_id);
|
|
144781
145296
|
const identity = await ctx.myIdentity().catch(() => void 0);
|
|
144782
|
-
if (!identity) throw accountUnknown(ctx
|
|
145297
|
+
if (!identity) throw accountUnknown(ctx, "your team brief cannot be read");
|
|
144783
145298
|
const feed = await ctx.client.getGame(gameId, { settings: true });
|
|
144784
145299
|
if (feed.state !== PLAYING4 && feed.state !== DISTRIBUTING5) {
|
|
144785
145300
|
throw new McpToolError(`Game ${feed.id} is not being picked or played (game state: ${feed.state}), so there is nothing to brief.`, {
|
|
@@ -145367,408 +145882,6 @@ function parsePacket(raw) {
|
|
|
145367
145882
|
}
|
|
145368
145883
|
}
|
|
145369
145884
|
|
|
145370
|
-
// node_modules/@chrischall/mcp-utils/dist/netguard/index.js
|
|
145371
|
-
var import_undici = __toESM(require_undici(), 1);
|
|
145372
|
-
import { lookup as dnsLookup } from "node:dns/promises";
|
|
145373
|
-
import { isIP as isIP2 } from "node:net";
|
|
145374
|
-
var systemResolver = async (hostname3) => (await dnsLookup(hostname3, { all: true, verbatim: true })).map((a) => a.address);
|
|
145375
|
-
function refuseHost(hostname3) {
|
|
145376
|
-
return new UrlNotAllowedError(`Refusing to connect to ${hostname3}: it is, or resolves to, a private, loopback, link-local or reserved address.`, "host");
|
|
145377
|
-
}
|
|
145378
|
-
function createPublicOnlyDispatcher(opts = {}) {
|
|
145379
|
-
const resolve2 = opts.resolve ?? systemResolver;
|
|
145380
|
-
const allowed = opts.isAllowedAddress ?? isPublicAddress;
|
|
145381
|
-
const lookup = (hostname3, options, callback2) => {
|
|
145382
|
-
resolve2(hostname3).then((addresses) => {
|
|
145383
|
-
if (addresses.length === 0 || !addresses.every(allowed)) {
|
|
145384
|
-
callback2(refuseHost(hostname3), "", 0);
|
|
145385
|
-
return;
|
|
145386
|
-
}
|
|
145387
|
-
const entries2 = addresses.map((address) => ({ address, family: isIP2(address) }));
|
|
145388
|
-
if (options.all) {
|
|
145389
|
-
callback2(null, entries2);
|
|
145390
|
-
return;
|
|
145391
|
-
}
|
|
145392
|
-
const wanted = options.family === 4 || options.family === 6 ? options.family : 0;
|
|
145393
|
-
const pick5 = entries2.find((e) => wanted === 0 || e.family === wanted) ?? entries2[0];
|
|
145394
|
-
callback2(null, pick5.address, pick5.family);
|
|
145395
|
-
}, (err) => callback2(err, "", 0));
|
|
145396
|
-
};
|
|
145397
|
-
const inner = (0, import_undici.buildConnector)({ ...opts.connect, lookup });
|
|
145398
|
-
const connect = (options, callback2) => {
|
|
145399
|
-
const host = options.hostname.replace(/^\[|\]$/g, "");
|
|
145400
|
-
if (isIP2(host) !== 0 && !allowed(host)) {
|
|
145401
|
-
callback2(refuseHost(options.hostname), null);
|
|
145402
|
-
return;
|
|
145403
|
-
}
|
|
145404
|
-
inner(options, callback2);
|
|
145405
|
-
};
|
|
145406
|
-
return new import_undici.Agent({ ...opts.agent, connect });
|
|
145407
|
-
}
|
|
145408
|
-
var REDIRECT_STATUSES2 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
145409
|
-
var CROSS_ORIGIN_DROPPED = ["authorization", "cookie", "proxy-authorization"];
|
|
145410
|
-
function findUrlRefusal(err) {
|
|
145411
|
-
let e = err;
|
|
145412
|
-
for (let i2 = 0; i2 < 8 && e; i2 += 1) {
|
|
145413
|
-
if (e instanceof UrlNotAllowedError)
|
|
145414
|
-
return e;
|
|
145415
|
-
e = e.cause;
|
|
145416
|
-
}
|
|
145417
|
-
return void 0;
|
|
145418
|
-
}
|
|
145419
|
-
async function fetchPublic(url4, opts = {}) {
|
|
145420
|
-
const { maxRedirects = 10, timeoutMs, maxBytes, signal: callerSignal, dispatcher: given2, requireHttps, allowHosts, stopBefore, resolve: resolve2, isAllowedAddress, headers: initHeaders, method: initMethod, body: initBody, ...init } = opts;
|
|
145421
|
-
if (!Number.isInteger(maxRedirects) || maxRedirects < 0) {
|
|
145422
|
-
throw new TypeError("fetchPublic: maxRedirects must be a non-negative integer.");
|
|
145423
|
-
}
|
|
145424
|
-
const check2 = (target) => assertAllowedUrl(target, {
|
|
145425
|
-
allowHosts: allowHosts ?? [/(?:)/],
|
|
145426
|
-
...requireHttps !== void 0 ? { requireHttps } : {}
|
|
145427
|
-
});
|
|
145428
|
-
let current2 = check2(url4);
|
|
145429
|
-
const origin = current2.origin;
|
|
145430
|
-
if (stopBefore?.(current2))
|
|
145431
|
-
return { stopped: true, url: current2.href, hops: 0 };
|
|
145432
|
-
const timeout = timeoutMs !== void 0 ? AbortSignal.timeout(timeoutMs) : void 0;
|
|
145433
|
-
const signals = [callerSignal, timeout].filter((s) => s !== void 0);
|
|
145434
|
-
const signal = signals.length > 0 ? AbortSignal.any(signals) : void 0;
|
|
145435
|
-
const owned = given2 === void 0 ? createPublicOnlyDispatcher({
|
|
145436
|
-
...resolve2 ? { resolve: resolve2 } : {},
|
|
145437
|
-
...isAllowedAddress ? { isAllowedAddress } : {}
|
|
145438
|
-
}) : void 0;
|
|
145439
|
-
const dispatcher = given2 ?? owned;
|
|
145440
|
-
let method = (initMethod ?? "GET").toUpperCase();
|
|
145441
|
-
let body = initBody;
|
|
145442
|
-
const headers = new import_undici.Headers(initHeaders);
|
|
145443
|
-
const fail = (err) => {
|
|
145444
|
-
if (callerSignal?.aborted)
|
|
145445
|
-
throw callerSignal.reason;
|
|
145446
|
-
if (timeout?.aborted)
|
|
145447
|
-
throw new RequestTimeoutError(current2.host, timeoutMs);
|
|
145448
|
-
const refused = findUrlRefusal(err);
|
|
145449
|
-
if (refused)
|
|
145450
|
-
throw refused;
|
|
145451
|
-
if (err instanceof McpToolError)
|
|
145452
|
-
throw err;
|
|
145453
|
-
throw new McpToolError(`Could not reach ${current2.host}.`, {
|
|
145454
|
-
kind: "transport",
|
|
145455
|
-
hint: "Check the link is reachable from the server.",
|
|
145456
|
-
cause: err
|
|
145457
|
-
});
|
|
145458
|
-
};
|
|
145459
|
-
try {
|
|
145460
|
-
for (let hops = 0; ; ) {
|
|
145461
|
-
let res;
|
|
145462
|
-
try {
|
|
145463
|
-
res = await (0, import_undici.fetch)(current2, {
|
|
145464
|
-
...init,
|
|
145465
|
-
method,
|
|
145466
|
-
headers,
|
|
145467
|
-
...body !== void 0 && body !== null ? { body } : {},
|
|
145468
|
-
redirect: "manual",
|
|
145469
|
-
dispatcher,
|
|
145470
|
-
...signal ? { signal } : {}
|
|
145471
|
-
});
|
|
145472
|
-
} catch (err) {
|
|
145473
|
-
return fail(err);
|
|
145474
|
-
}
|
|
145475
|
-
const location = REDIRECT_STATUSES2.has(res.status) ? res.headers.get("location") : null;
|
|
145476
|
-
if (location === null) {
|
|
145477
|
-
let bytes;
|
|
145478
|
-
try {
|
|
145479
|
-
bytes = await readBytesCapped(res, maxBytes, current2.host, (p) => p);
|
|
145480
|
-
} catch (err) {
|
|
145481
|
-
return fail(err);
|
|
145482
|
-
}
|
|
145483
|
-
return { stopped: false, url: current2.href, hops, status: res.status, headers: res.headers, body: bytes };
|
|
145484
|
-
}
|
|
145485
|
-
await res.body?.cancel().catch(() => {
|
|
145486
|
-
});
|
|
145487
|
-
if (hops >= maxRedirects) {
|
|
145488
|
-
throw new RedirectRefusedError(`Refusing to follow more than ${maxRedirects} redirects (last from ${current2.host}).`);
|
|
145489
|
-
}
|
|
145490
|
-
let next;
|
|
145491
|
-
try {
|
|
145492
|
-
next = new URL(location, current2);
|
|
145493
|
-
} catch {
|
|
145494
|
-
throw new UrlNotAllowedError("The redirect target is not a valid URL.", "invalid");
|
|
145495
|
-
}
|
|
145496
|
-
next = check2(next);
|
|
145497
|
-
hops += 1;
|
|
145498
|
-
if (res.status === 303 || (res.status === 301 || res.status === 302) && method === "POST") {
|
|
145499
|
-
if (method !== "HEAD")
|
|
145500
|
-
method = "GET";
|
|
145501
|
-
body = void 0;
|
|
145502
|
-
for (const h of ["content-type", "content-length", "content-encoding", "content-language", "content-location"]) {
|
|
145503
|
-
headers.delete(h);
|
|
145504
|
-
}
|
|
145505
|
-
}
|
|
145506
|
-
if (next.origin !== origin)
|
|
145507
|
-
for (const h of CROSS_ORIGIN_DROPPED)
|
|
145508
|
-
headers.delete(h);
|
|
145509
|
-
current2 = next;
|
|
145510
|
-
if (stopBefore?.(current2))
|
|
145511
|
-
return { stopped: true, url: current2.href, hops };
|
|
145512
|
-
}
|
|
145513
|
-
} finally {
|
|
145514
|
-
if (owned)
|
|
145515
|
-
await owned.destroy().catch(() => {
|
|
145516
|
-
});
|
|
145517
|
-
}
|
|
145518
|
-
}
|
|
145519
|
-
|
|
145520
|
-
// src/direct/transport.ts
|
|
145521
|
-
var TRANSPORT_ENV = "WARAPP_TRANSPORT";
|
|
145522
|
-
var MAX_DIRECT_BODY_BYTES = 16 * 1024 * 1024;
|
|
145523
|
-
var DIRECT_TIMEOUT_MS = 3e4;
|
|
145524
|
-
var SessionNotLinkedError = class extends McpToolError {
|
|
145525
|
-
name = "SessionNotLinkedError";
|
|
145526
|
-
constructor() {
|
|
145527
|
-
super("No war.app session is linked for the direct transport. Run warapp_link_session to capture one.", {
|
|
145528
|
-
kind: "no_credential"
|
|
145529
|
-
});
|
|
145530
|
-
}
|
|
145531
|
-
};
|
|
145532
|
-
var SessionExpiredError = class extends McpToolError {
|
|
145533
|
-
name = "SessionExpiredError";
|
|
145534
|
-
/** When the expired session was captured (non-secret), so a relink can be told apart. */
|
|
145535
|
-
capturedAt;
|
|
145536
|
-
constructor(opts = {}) {
|
|
145537
|
-
super(
|
|
145538
|
-
"The linked war.app session is no longer signed in. " + (opts.notResent ? "The request had already reached war.app, so it was not re-sent over the browser bridge (a write must never be sent twice); later calls use the bridge. Retry, or run warapp_link_session to relink." : "Run warapp_link_session to relink."),
|
|
145539
|
-
{ kind: "session_expired" }
|
|
145540
|
-
);
|
|
145541
|
-
this.capturedAt = opts.capturedAt;
|
|
145542
|
-
}
|
|
145543
|
-
};
|
|
145544
|
-
var decoder = new TextDecoder();
|
|
145545
|
-
var isSafeToReplay = (method) => /^(?:GET|HEAD)$/i.test(method);
|
|
145546
|
-
var SESSION_ORIGIN = `https://${SESSION_HOST}`;
|
|
145547
|
-
var MAX_DIRECT_GET_REDIRECTS = 5;
|
|
145548
|
-
var UNFOLLOWED_REDIRECT_STATUS = 302;
|
|
145549
|
-
function directFetchOptions(method) {
|
|
145550
|
-
const base = { requireHttps: true, allowHosts: [SESSION_HOST] };
|
|
145551
|
-
if (isSafeToReplay(method)) {
|
|
145552
|
-
return { ...base, maxRedirects: MAX_DIRECT_GET_REDIRECTS, stopBefore: (url4) => url4.origin !== SESSION_ORIGIN };
|
|
145553
|
-
}
|
|
145554
|
-
let first = true;
|
|
145555
|
-
return {
|
|
145556
|
-
...base,
|
|
145557
|
-
maxRedirects: 1,
|
|
145558
|
-
stopBefore: () => {
|
|
145559
|
-
if (first) {
|
|
145560
|
-
first = false;
|
|
145561
|
-
return false;
|
|
145562
|
-
}
|
|
145563
|
-
return true;
|
|
145564
|
-
}
|
|
145565
|
-
};
|
|
145566
|
-
}
|
|
145567
|
-
function toDirectResult(res) {
|
|
145568
|
-
if ("stopped" in res && res.stopped) return { status: UNFOLLOWED_REDIRECT_STATUS, body: "", url: res.url };
|
|
145569
|
-
const done = res;
|
|
145570
|
-
const out = { status: done.status, body: decoder.decode(done.body), url: done.url };
|
|
145571
|
-
if (done.headers) {
|
|
145572
|
-
const headers = {};
|
|
145573
|
-
done.headers.forEach((v, k) => {
|
|
145574
|
-
headers[k.toLowerCase()] = v;
|
|
145575
|
-
});
|
|
145576
|
-
out.headers = headers;
|
|
145577
|
-
}
|
|
145578
|
-
return out;
|
|
145579
|
-
}
|
|
145580
|
-
var fetchViaPublic = async (url4, init) => {
|
|
145581
|
-
const res = await fetchPublic(url4, {
|
|
145582
|
-
...directFetchOptions(init.method),
|
|
145583
|
-
method: init.method,
|
|
145584
|
-
headers: init.headers,
|
|
145585
|
-
maxBytes: MAX_DIRECT_BODY_BYTES,
|
|
145586
|
-
timeoutMs: DIRECT_TIMEOUT_MS,
|
|
145587
|
-
...init.body !== void 0 ? { body: init.body } : {},
|
|
145588
|
-
...init.signal ? { signal: init.signal } : {}
|
|
145589
|
-
});
|
|
145590
|
-
return toDirectResult(res);
|
|
145591
|
-
};
|
|
145592
|
-
function warappUrl(path) {
|
|
145593
|
-
const raw = /^https?:\/\//i.test(path) ? path : `https://${SESSION_HOST}${path.startsWith("/") ? "" : "/"}${path}`;
|
|
145594
|
-
let u;
|
|
145595
|
-
try {
|
|
145596
|
-
u = new URL(raw);
|
|
145597
|
-
} catch {
|
|
145598
|
-
throw new McpToolError(`The direct transport could not parse the request path.`, { kind: "unknown" });
|
|
145599
|
-
}
|
|
145600
|
-
if (u.hostname !== SESSION_HOST || u.port !== "" || u.username !== "" || u.password !== "") {
|
|
145601
|
-
throw new McpToolError(`The direct transport only talks to ${SESSION_HOST}.`, { kind: "unknown" });
|
|
145602
|
-
}
|
|
145603
|
-
if (u.protocol !== "https:") {
|
|
145604
|
-
throw new McpToolError("The direct transport requires https.", { kind: "unknown" });
|
|
145605
|
-
}
|
|
145606
|
-
return u.href;
|
|
145607
|
-
}
|
|
145608
|
-
var SIGNIN_PATH = /\/(?:sign-?in|log-?in)\b/i;
|
|
145609
|
-
var INPUT_TAG = /<input(?=[\s/>])/gi;
|
|
145610
|
-
var TAG_ATTR = /\s*(?:(>)|([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>`=]+)))?|\/)/y;
|
|
145611
|
-
var NOT_MARKUP = /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title)\b[^>]*(?:>|$)[\s\S]*?(?:<\/\1\s*>|$)/gi;
|
|
145612
|
-
function hasPasswordInput(raw) {
|
|
145613
|
-
const body = raw.replace(NOT_MARKUP, " ");
|
|
145614
|
-
INPUT_TAG.lastIndex = 0;
|
|
145615
|
-
for (let m = INPUT_TAG.exec(body); m; m = INPUT_TAG.exec(body)) {
|
|
145616
|
-
TAG_ATTR.lastIndex = INPUT_TAG.lastIndex;
|
|
145617
|
-
for (let a = TAG_ATTR.exec(body); a && !a[1]; a = TAG_ATTR.exec(body)) {
|
|
145618
|
-
const name = a[2]?.toLowerCase();
|
|
145619
|
-
const value = (a[3] ?? a[4] ?? a[5] ?? "").trim().toLowerCase();
|
|
145620
|
-
if ((name === "type" || name === "name") && value === "password") return true;
|
|
145621
|
-
}
|
|
145622
|
-
}
|
|
145623
|
-
return false;
|
|
145624
|
-
}
|
|
145625
|
-
function looksLikeHexFrame(body) {
|
|
145626
|
-
const t = body.trim();
|
|
145627
|
-
return t.length > 0 && t.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(t);
|
|
145628
|
-
}
|
|
145629
|
-
function looksSignedOut(requestedUrl, res) {
|
|
145630
|
-
let finalPath = "";
|
|
145631
|
-
try {
|
|
145632
|
-
finalPath = new URL(res.url).pathname;
|
|
145633
|
-
} catch {
|
|
145634
|
-
finalPath = "";
|
|
145635
|
-
}
|
|
145636
|
-
if (SIGNIN_PATH.test(finalPath)) return true;
|
|
145637
|
-
if (res.status === 401 || res.status === 403) return true;
|
|
145638
|
-
if (res.status !== 200) return false;
|
|
145639
|
-
if (hasPasswordInput(res.body)) return true;
|
|
145640
|
-
let reqPath = "";
|
|
145641
|
-
try {
|
|
145642
|
-
reqPath = new URL(requestedUrl).pathname;
|
|
145643
|
-
} catch {
|
|
145644
|
-
reqPath = "";
|
|
145645
|
-
}
|
|
145646
|
-
if (/\/services\b/i.test(reqPath) && !looksLikeHexFrame(res.body)) return true;
|
|
145647
|
-
return false;
|
|
145648
|
-
}
|
|
145649
|
-
var DirectBridge = class {
|
|
145650
|
-
constructor(store, fetchImpl = fetchViaPublic) {
|
|
145651
|
-
this.store = store;
|
|
145652
|
-
this.fetchImpl = fetchImpl;
|
|
145653
|
-
}
|
|
145654
|
-
store;
|
|
145655
|
-
fetchImpl;
|
|
145656
|
-
async fetch(init, signal) {
|
|
145657
|
-
const sess = await this.store.read();
|
|
145658
|
-
if (!sess) throw new SessionNotLinkedError();
|
|
145659
|
-
const token = sess.authToken;
|
|
145660
|
-
const url4 = warappUrl(init.path);
|
|
145661
|
-
const headers = { ...init.headers ?? {}, cookie: `AuthToken=${token}` };
|
|
145662
|
-
let res;
|
|
145663
|
-
try {
|
|
145664
|
-
res = await this.fetchImpl(url4, {
|
|
145665
|
-
method: init.method,
|
|
145666
|
-
headers,
|
|
145667
|
-
...init.body !== void 0 ? { body: init.body } : {},
|
|
145668
|
-
...signal ? { signal } : {}
|
|
145669
|
-
});
|
|
145670
|
-
} catch (err) {
|
|
145671
|
-
throw scrubError(err, [token]);
|
|
145672
|
-
}
|
|
145673
|
-
const answered = res.status === 200 && looksLikeHexFrame(res.body);
|
|
145674
|
-
if (!answered && (res.status !== 200 || res.headers?.["cf-mitigated"])) {
|
|
145675
|
-
const edge = detectEdgeBlock({ body: res.body, ...res.headers ? { headers: res.headers } : {}, status: res.status });
|
|
145676
|
-
if (edge) {
|
|
145677
|
-
throw new EdgeBlockedError(res.status, edge.vendor, {
|
|
145678
|
-
service: SESSION_HOST,
|
|
145679
|
-
method: init.method,
|
|
145680
|
-
path: new URL(url4).pathname
|
|
145681
|
-
});
|
|
145682
|
-
}
|
|
145683
|
-
}
|
|
145684
|
-
if (looksSignedOut(url4, res)) throw new SessionExpiredError({ capturedAt: sess.capturedAt });
|
|
145685
|
-
return { status: res.status, body: res.body, url: res.url };
|
|
145686
|
-
}
|
|
145687
|
-
};
|
|
145688
|
-
var RELINK_CHECK_MS = 5e3;
|
|
145689
|
-
function createDirectFirstBridge(opts) {
|
|
145690
|
-
const hosted = isHosted(opts.env ?? process.env);
|
|
145691
|
-
const mode = hosted ? "fetchproxy" : opts.mode ?? readTransportMode(TRANSPORT_ENV, opts.env ? { env: opts.env } : {});
|
|
145692
|
-
const store = hosted ? { read: async () => null } : opts.store;
|
|
145693
|
-
const direct = new DirectBridge(store, opts.directFetch);
|
|
145694
|
-
const log = opts.log ?? ((m) => console.error(m));
|
|
145695
|
-
const now = opts.now ?? Date.now;
|
|
145696
|
-
let wall = null;
|
|
145697
|
-
let stale = false;
|
|
145698
|
-
let lastRelinkCheck = Number.NEGATIVE_INFINITY;
|
|
145699
|
-
const onFallback = ({ error: error62 }) => {
|
|
145700
|
-
const next = error62 instanceof SessionExpiredError ? { kind: "session", capturedAt: error62.capturedAt ?? null } : error62 instanceof SessionNotLinkedError ? { kind: "session", capturedAt: null } : { kind: "edge" };
|
|
145701
|
-
wall = next;
|
|
145702
|
-
const why = error62 instanceof SessionExpiredError ? "the linked war.app session is signed out" : error62 instanceof SessionNotLinkedError ? "no war.app session is linked" : "the site edge refused the direct request";
|
|
145703
|
-
log(
|
|
145704
|
-
`[warapp-mcp] Direct transport unavailable (${why}) \u2014 switching to the ContextMint Bridge browser bridge. Keep a ${SESSION_HOST} tab open and approve the pairing prompt in the extension if one appears` + (next.kind === "session" && !hosted ? "; run warapp_link_session to return to the direct transport." : ".")
|
|
145705
|
-
);
|
|
145706
|
-
};
|
|
145707
|
-
const build2 = () => createDirectFirstTransport({
|
|
145708
|
-
direct,
|
|
145709
|
-
bridge: opts.makeBridge,
|
|
145710
|
-
mode,
|
|
145711
|
-
serverName: "warapp-mcp",
|
|
145712
|
-
hostLabel: SESSION_HOST,
|
|
145713
|
-
shouldFallBack: (err) => err instanceof SessionExpiredError || err instanceof SessionNotLinkedError || err instanceof EdgeBlockedError,
|
|
145714
|
-
bridgeHealth: (b) => b.transport(),
|
|
145715
|
-
onFallback
|
|
145716
|
-
});
|
|
145717
|
-
let legs = build2();
|
|
145718
|
-
const liftSessionWall = () => {
|
|
145719
|
-
if (wall?.kind !== "session") return;
|
|
145720
|
-
wall = null;
|
|
145721
|
-
legs = build2();
|
|
145722
|
-
};
|
|
145723
|
-
const relinkedSinceWall = async () => {
|
|
145724
|
-
if (wall?.kind !== "session") return false;
|
|
145725
|
-
const t = now();
|
|
145726
|
-
if (t - lastRelinkCheck < RELINK_CHECK_MS) return false;
|
|
145727
|
-
lastRelinkCheck = t;
|
|
145728
|
-
const sess = await store.read();
|
|
145729
|
-
return sess !== null && sess.capturedAt !== wall.capturedAt;
|
|
145730
|
-
};
|
|
145731
|
-
const runOne = async (init) => {
|
|
145732
|
-
if (mode === "auto" && await relinkedSinceWall()) {
|
|
145733
|
-
liftSessionWall();
|
|
145734
|
-
stale = false;
|
|
145735
|
-
}
|
|
145736
|
-
let reached;
|
|
145737
|
-
return legs.run(async (leg, ctx) => {
|
|
145738
|
-
if (leg === direct) {
|
|
145739
|
-
try {
|
|
145740
|
-
const res = await direct.fetch(init, ctx.signal);
|
|
145741
|
-
if (res.status === 200) stale = false;
|
|
145742
|
-
return res;
|
|
145743
|
-
} catch (err) {
|
|
145744
|
-
if (err instanceof SessionExpiredError) {
|
|
145745
|
-
stale = true;
|
|
145746
|
-
if (!isSafeToReplay(init.method)) reached = err;
|
|
145747
|
-
}
|
|
145748
|
-
throw err;
|
|
145749
|
-
}
|
|
145750
|
-
}
|
|
145751
|
-
if (reached) throw new SessionExpiredError({ capturedAt: reached.capturedAt, notResent: true });
|
|
145752
|
-
return leg.ready().then((t) => t.fetch(init));
|
|
145753
|
-
});
|
|
145754
|
-
};
|
|
145755
|
-
return {
|
|
145756
|
-
ready: async () => ({ fetch: (init) => runOne(init) }),
|
|
145757
|
-
status: () => legs.status(),
|
|
145758
|
-
bridgeTransport: () => legs.bridgeTransport(),
|
|
145759
|
-
stats: () => legs.stats(),
|
|
145760
|
-
sessionStale: () => stale,
|
|
145761
|
-
sessionLinked: () => {
|
|
145762
|
-
stale = false;
|
|
145763
|
-
if (mode === "auto") liftSessionWall();
|
|
145764
|
-
},
|
|
145765
|
-
identityState: async () => {
|
|
145766
|
-
const sess = await store.read();
|
|
145767
|
-
return JSON.stringify([legs.status().transport, stale, sess?.capturedAt ?? null]);
|
|
145768
|
-
}
|
|
145769
|
-
};
|
|
145770
|
-
}
|
|
145771
|
-
|
|
145772
145885
|
// src/push/websocket.ts
|
|
145773
145886
|
var defaultWebSocketFactory = (url4, init) => {
|
|
145774
145887
|
const Ctor = globalThis.WebSocket;
|
|
@@ -145790,9 +145903,9 @@ function websocketUrl(sid) {
|
|
|
145790
145903
|
if (!/^[A-Za-z0-9_-]+$/.test(sid)) throw new Error("war.app returned an unusable push-socket session id.");
|
|
145791
145904
|
return `wss://${WS_HOST}/socket.io/1/websocket/${sid}`;
|
|
145792
145905
|
}
|
|
145793
|
-
function pushWebSocketLeg(bridge2, readSession2, seams = {}) {
|
|
145906
|
+
function pushWebSocketLeg(bridge2, readSession2, seams = {}, env = process.env) {
|
|
145794
145907
|
return {
|
|
145795
|
-
select: () => bridge2.status().transport === "direct",
|
|
145908
|
+
select: () => bridge2.status().transport === "direct" && !egressProxyConfigured(env),
|
|
145796
145909
|
session: readSession2,
|
|
145797
145910
|
...seams
|
|
145798
145911
|
};
|
|
@@ -146517,6 +146630,249 @@ function pushListenerFor(key, opts) {
|
|
|
146517
146630
|
return l;
|
|
146518
146631
|
}
|
|
146519
146632
|
|
|
146633
|
+
// src/direct/sign-in.ts
|
|
146634
|
+
var import_undici3 = __toESM(require_undici(), 1);
|
|
146635
|
+
var ORIGIN = `https://${SESSION_HOST}`;
|
|
146636
|
+
var SIGN_IN_URL = `${ORIGIN}/LogIn`;
|
|
146637
|
+
var AUTH_COOKIE2 = "AuthToken";
|
|
146638
|
+
var MAX_REDIRECTS = 3;
|
|
146639
|
+
var MIN_SCRUBBED_COOKIE = 6;
|
|
146640
|
+
var SIGN_IN_TIMEOUT_MS = 3e4;
|
|
146641
|
+
var SIGN_IN_MAX_BODY_BYTES = 2 * 1024 * 1024;
|
|
146642
|
+
function createSignInFetch(opts = {}) {
|
|
146643
|
+
const maxBytes = opts.maxBytes ?? SIGN_IN_MAX_BODY_BYTES;
|
|
146644
|
+
const proxy = opts.dispatcher ? void 0 : egressProxyUrl(opts.env ?? process.env);
|
|
146645
|
+
const makeProxy = opts.proxyAgent ?? defaultProxyAgent;
|
|
146646
|
+
return async (url4, init) => {
|
|
146647
|
+
const owned = opts.dispatcher ? void 0 : proxy ? makeProxy(proxy) : createPublicOnlyDispatcher();
|
|
146648
|
+
try {
|
|
146649
|
+
const res = await (0, import_undici3.fetch)(url4, {
|
|
146650
|
+
method: init.method,
|
|
146651
|
+
headers: init.headers,
|
|
146652
|
+
...init.body !== void 0 ? { body: init.body } : {},
|
|
146653
|
+
redirect: "manual",
|
|
146654
|
+
dispatcher: opts.dispatcher ?? owned,
|
|
146655
|
+
signal: init.signal
|
|
146656
|
+
});
|
|
146657
|
+
const headers = {};
|
|
146658
|
+
res.headers.forEach((v, k) => {
|
|
146659
|
+
if (k.toLowerCase() !== "set-cookie") headers[k.toLowerCase()] = v;
|
|
146660
|
+
});
|
|
146661
|
+
const setCookies = res.headers.getSetCookie();
|
|
146662
|
+
const body = await readCapped2(res.body, maxBytes);
|
|
146663
|
+
return { status: res.status, headers, setCookies, body };
|
|
146664
|
+
} finally {
|
|
146665
|
+
await owned?.close().catch(() => {
|
|
146666
|
+
});
|
|
146667
|
+
}
|
|
146668
|
+
};
|
|
146669
|
+
}
|
|
146670
|
+
async function readCapped2(body, maxBytes) {
|
|
146671
|
+
if (!body) return "";
|
|
146672
|
+
const chunks = [];
|
|
146673
|
+
let total = 0;
|
|
146674
|
+
for await (const chunk2 of body) {
|
|
146675
|
+
total += chunk2.byteLength;
|
|
146676
|
+
if (total > maxBytes) {
|
|
146677
|
+
throw new McpToolError(`war.app's sign-in answered with more than ${maxBytes} bytes.`, { kind: "too_large" });
|
|
146678
|
+
}
|
|
146679
|
+
chunks.push(chunk2);
|
|
146680
|
+
}
|
|
146681
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
146682
|
+
}
|
|
146683
|
+
function parseSetCookie(header, now = Date.now()) {
|
|
146684
|
+
const [pair2 = "", ...attrs] = header.split(";");
|
|
146685
|
+
const eq = pair2.indexOf("=");
|
|
146686
|
+
if (eq <= 0) return null;
|
|
146687
|
+
const name = pair2.slice(0, eq).trim();
|
|
146688
|
+
if (!name) return null;
|
|
146689
|
+
let value = pair2.slice(eq + 1).trim();
|
|
146690
|
+
if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) value = value.slice(1, -1);
|
|
146691
|
+
for (const attr of attrs) {
|
|
146692
|
+
const i2 = attr.indexOf("=");
|
|
146693
|
+
const key = (i2 < 0 ? attr : attr.slice(0, i2)).trim().toLowerCase();
|
|
146694
|
+
const v = i2 < 0 ? "" : attr.slice(i2 + 1).trim();
|
|
146695
|
+
if (key === "max-age" && /^-?\d+$/.test(v) && Number(v) <= 0) value = null;
|
|
146696
|
+
if (key === "expires") {
|
|
146697
|
+
const t = Date.parse(v);
|
|
146698
|
+
if (!Number.isNaN(t) && t <= now) value = null;
|
|
146699
|
+
}
|
|
146700
|
+
}
|
|
146701
|
+
if (value === "") value = null;
|
|
146702
|
+
return { name, value };
|
|
146703
|
+
}
|
|
146704
|
+
function onWarapp(url4) {
|
|
146705
|
+
return url4.origin === ORIGIN && url4.username === "" && url4.password === "";
|
|
146706
|
+
}
|
|
146707
|
+
var REDIRECTS = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
146708
|
+
var CHALLENGE_MARKUP = /g-recaptcha|grecaptcha|recaptcha\/api|h-captcha|hcaptcha\.com|cf-turnstile|challenges\.cloudflare\.com/i;
|
|
146709
|
+
var NOT_RETRIED = "It was not retried, because war.app may count failed sign-ins.";
|
|
146710
|
+
function refusal2(kind, message, hint) {
|
|
146711
|
+
return new McpToolError(message, { kind, ...hint ? { hint } : {} });
|
|
146712
|
+
}
|
|
146713
|
+
function challenge(what) {
|
|
146714
|
+
return refusal2(
|
|
146715
|
+
"edge_blocked",
|
|
146716
|
+
`war.app answered the sign-in with ${what}, which this connector cannot answer. ${NOT_RETRIED}`,
|
|
146717
|
+
"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."
|
|
146718
|
+
);
|
|
146719
|
+
}
|
|
146720
|
+
function challengeIn(res) {
|
|
146721
|
+
const edge = detectEdgeBlock({ body: res.body, headers: res.headers, status: res.status });
|
|
146722
|
+
if (edge) return challenge(`a ${edge.vendor} bot check`);
|
|
146723
|
+
if (res.status === 429) return challenge('"too many requests" (HTTP 429)');
|
|
146724
|
+
if (CHALLENGE_MARKUP.test(res.body)) return challenge("a captcha");
|
|
146725
|
+
if (res.status === 403) return challenge("a refusal (HTTP 403)");
|
|
146726
|
+
return null;
|
|
146727
|
+
}
|
|
146728
|
+
async function signIn(creds, opts = {}) {
|
|
146729
|
+
const jar = /* @__PURE__ */ new Map();
|
|
146730
|
+
const secrets = () => [
|
|
146731
|
+
{ value: creds.email, anyCase: true },
|
|
146732
|
+
creds.password,
|
|
146733
|
+
...[...jar.values()].filter((v) => v.length >= MIN_SCRUBBED_COOKIE)
|
|
146734
|
+
];
|
|
146735
|
+
try {
|
|
146736
|
+
return await exchange(creds, jar, opts);
|
|
146737
|
+
} catch (err) {
|
|
146738
|
+
throw scrubbed(err, secrets());
|
|
146739
|
+
}
|
|
146740
|
+
}
|
|
146741
|
+
async function exchange(creds, jar, opts) {
|
|
146742
|
+
if (!creds.email.trim() || !creds.password) {
|
|
146743
|
+
throw refusal2("no_credential", "Signing in to war.app needs both the email and the password; nothing was sent.");
|
|
146744
|
+
}
|
|
146745
|
+
const fetchHop = opts.fetch ?? createSignInFetch(opts.env ? { env: opts.env } : {});
|
|
146746
|
+
const timeoutMs = opts.timeoutMs ?? SIGN_IN_TIMEOUT_MS;
|
|
146747
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
146748
|
+
const signal = opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout;
|
|
146749
|
+
let posted = false;
|
|
146750
|
+
const hop = async (url4, method, body) => {
|
|
146751
|
+
const headers = { accept: "text/html,application/xhtml+xml" };
|
|
146752
|
+
if (jar.size > 0) headers.cookie = [...jar].map(([k, v]) => `${k}=${v}`).join("; ");
|
|
146753
|
+
if (method === "POST") {
|
|
146754
|
+
headers["content-type"] = "application/x-www-form-urlencoded";
|
|
146755
|
+
headers.origin = ORIGIN;
|
|
146756
|
+
headers.referer = SIGN_IN_URL;
|
|
146757
|
+
}
|
|
146758
|
+
let res;
|
|
146759
|
+
try {
|
|
146760
|
+
res = await fetchHop(url4.href, { method, headers, ...body !== void 0 ? { body } : {}, signal });
|
|
146761
|
+
} catch (err) {
|
|
146762
|
+
if (opts.signal?.aborted) throw opts.signal.reason;
|
|
146763
|
+
const after = posted ? " The sign-in may or may not have reached war.app; it was not retried." : " Nothing was sent to war.app.";
|
|
146764
|
+
if (timeout.aborted) {
|
|
146765
|
+
throw refusal2("timeout", `war.app did not answer the sign-in within ${Math.round(timeoutMs / 1e3)} s.${after}`);
|
|
146766
|
+
}
|
|
146767
|
+
if (err instanceof McpToolError && err.kind === "too_large") throw err;
|
|
146768
|
+
throw refusal2("transport", `Could not reach war.app to sign in.${after}`);
|
|
146769
|
+
}
|
|
146770
|
+
for (const header of res.setCookies) {
|
|
146771
|
+
const c = parseSetCookie(header);
|
|
146772
|
+
if (!c) continue;
|
|
146773
|
+
if (c.value === null) jar.delete(c.name);
|
|
146774
|
+
else jar.set(c.name, c.value);
|
|
146775
|
+
}
|
|
146776
|
+
return res;
|
|
146777
|
+
};
|
|
146778
|
+
const follow = async (from, first) => {
|
|
146779
|
+
let url4 = from;
|
|
146780
|
+
let res = first;
|
|
146781
|
+
for (let n = 0; ; n++) {
|
|
146782
|
+
if (posted && jar.has(AUTH_COOKIE2)) return { url: url4, res };
|
|
146783
|
+
const location = REDIRECTS.has(res.status) ? res.headers.location : void 0;
|
|
146784
|
+
if (!location) return { url: url4, res };
|
|
146785
|
+
let next;
|
|
146786
|
+
try {
|
|
146787
|
+
next = new URL(location, url4);
|
|
146788
|
+
} catch {
|
|
146789
|
+
throw refusal2("unknown", `war.app redirected the sign-in to an address that does not parse. ${NOT_RETRIED}`);
|
|
146790
|
+
}
|
|
146791
|
+
if (!onWarapp(next)) {
|
|
146792
|
+
throw refusal2("unknown", `war.app redirected the sign-in away from ${ORIGIN}; it was not followed. ${NOT_RETRIED}`);
|
|
146793
|
+
}
|
|
146794
|
+
if (n >= MAX_REDIRECTS) {
|
|
146795
|
+
throw refusal2("unknown", `war.app redirected the sign-in more than ${MAX_REDIRECTS} times. ${NOT_RETRIED}`);
|
|
146796
|
+
}
|
|
146797
|
+
url4 = next;
|
|
146798
|
+
res = await hop(url4, "GET");
|
|
146799
|
+
}
|
|
146800
|
+
};
|
|
146801
|
+
const page2 = await follow(new URL(SIGN_IN_URL), await hop(new URL(SIGN_IN_URL), "GET"));
|
|
146802
|
+
const pageCheck = challengeIn(page2.res);
|
|
146803
|
+
if (pageCheck) throw pageCheck;
|
|
146804
|
+
if (page2.res.status !== 200 || !hasPasswordInput(page2.res.body)) {
|
|
146805
|
+
throw refusal2(
|
|
146806
|
+
"http",
|
|
146807
|
+
`war.app's sign-in page did not show its form (HTTP ${page2.res.status}); no password was sent.`,
|
|
146808
|
+
"war.app may be down or have changed its sign-in page. Try Sign in again later."
|
|
146809
|
+
);
|
|
146810
|
+
}
|
|
146811
|
+
jar.delete(AUTH_COOKIE2);
|
|
146812
|
+
const form = new URLSearchParams({ Email: creds.email.trim(), Password: creds.password, KeepSignedIn: "on" });
|
|
146813
|
+
posted = true;
|
|
146814
|
+
const postUrl = new URL(SIGN_IN_URL);
|
|
146815
|
+
const done = await follow(postUrl, await hop(postUrl, "POST", form.toString()));
|
|
146816
|
+
const token = jar.get(AUTH_COOKIE2);
|
|
146817
|
+
if (token) {
|
|
146818
|
+
if (isPlausibleAuthToken(token)) return { authToken: token };
|
|
146819
|
+
throw refusal2(
|
|
146820
|
+
"unknown",
|
|
146821
|
+
"war.app signed in, but its session cookie is not in a shape this connector can use; it was not kept.",
|
|
146822
|
+
"war.app may have changed its session cookie. Report this; nothing was retried."
|
|
146823
|
+
);
|
|
146824
|
+
}
|
|
146825
|
+
const check2 = challengeIn(done.res);
|
|
146826
|
+
if (check2) throw check2;
|
|
146827
|
+
if (hasPasswordInput(done.res.body)) {
|
|
146828
|
+
throw refusal2(
|
|
146829
|
+
"credential_rejected",
|
|
146830
|
+
`war.app refused the sign-in: the email or password is not right (its sign-in form came back). ${NOT_RETRIED}`,
|
|
146831
|
+
"Check the war.app password (and the email on this connection), then use Sign in on the connection again."
|
|
146832
|
+
);
|
|
146833
|
+
}
|
|
146834
|
+
throw refusal2(
|
|
146835
|
+
done.res.status >= 400 ? "http" : "unknown",
|
|
146836
|
+
`war.app answered the sign-in (HTTP ${done.res.status}) without setting a session. ${NOT_RETRIED}`,
|
|
146837
|
+
"war.app may have changed how it signs in. Try Sign in again later."
|
|
146838
|
+
);
|
|
146839
|
+
}
|
|
146840
|
+
function scrubbed(err, secrets) {
|
|
146841
|
+
const e = err;
|
|
146842
|
+
const scrub = (s) => scrubSecrets(s, secrets);
|
|
146843
|
+
const message = scrub(typeof e?.message === "string" ? e.message : String(err));
|
|
146844
|
+
const kind = err instanceof McpToolError && err.kind ? err.kind : "unknown";
|
|
146845
|
+
return new McpToolError(message, { kind, ...typeof e?.hint === "string" ? { hint: scrub(e.hint) } : {} });
|
|
146846
|
+
}
|
|
146847
|
+
|
|
146848
|
+
// src/tools/sign-in.ts
|
|
146849
|
+
function registerSignInTool(server, deps = {}) {
|
|
146850
|
+
const run2 = deps.signIn ?? signIn;
|
|
146851
|
+
server.registerTool(
|
|
146852
|
+
"warapp_sign_in",
|
|
146853
|
+
{
|
|
146854
|
+
title: "Sign in to war.app (host sign-in flow)",
|
|
146855
|
+
description: "For the host's sign-in flow only, not for chat use: signs in to war.app once with the account's email and password and returns the session cookie war.app sets, as `authToken`, which the host keeps as this connection's own secret so later calls reach war.app without a browser. The password is used for this one sign-in and never stored. A refusal (wrong email or password, a captcha or bot check, a network failure) is an error that says which, and is never retried, because war.app may count failed sign-ins.",
|
|
146856
|
+
_meta: mintMeta("other", ["sign in to war.app"]),
|
|
146857
|
+
annotations: toolAnnotations({
|
|
146858
|
+
title: "Sign in to war.app",
|
|
146859
|
+
readOnly: false,
|
|
146860
|
+
destructive: false,
|
|
146861
|
+
idempotent: false,
|
|
146862
|
+
openWorld: true
|
|
146863
|
+
}),
|
|
146864
|
+
inputSchema: external_exports.object({
|
|
146865
|
+
email: external_exports.string().min(1).max(320).describe("The war.app account's email."),
|
|
146866
|
+
password: external_exports.string().min(1).max(1024).describe("The war.app account's password, used once and never stored.")
|
|
146867
|
+
})
|
|
146868
|
+
},
|
|
146869
|
+
async ({ email: email4, password }, ctx) => {
|
|
146870
|
+
const { authToken } = await run2({ email: email4, password }, { signal: ctx.mcpReq.signal });
|
|
146871
|
+
return { content: [{ type: "text", text: JSON.stringify({ authToken }) }] };
|
|
146872
|
+
}
|
|
146873
|
+
);
|
|
146874
|
+
}
|
|
146875
|
+
|
|
146520
146876
|
// src/tools/index.ts
|
|
146521
146877
|
function registerAllTools(server, deps = {}) {
|
|
146522
146878
|
const client = new WarappClient({ ...deps, dataDir: () => dataDir(deps.env) });
|
|
@@ -146580,7 +146936,7 @@ function registerAllTools(server, deps = {}) {
|
|
|
146580
146936
|
registerDiplomacyTool(server, live, deps.env ? { env: deps.env } : {});
|
|
146581
146937
|
const push = deps.push ?? pushListenerFor(fetchproxy, {
|
|
146582
146938
|
transport: () => bridge2.ready(),
|
|
146583
|
-
webSocket: pushWebSocketLeg(bridge2, () => readSession(deps.env)),
|
|
146939
|
+
webSocket: pushWebSocketLeg(bridge2, () => readSession(deps.env), {}, deps.env ?? process.env),
|
|
146584
146940
|
extras: () => live.rpc.extras
|
|
146585
146941
|
});
|
|
146586
146942
|
registerSessionTools(server, {
|
|
@@ -146596,6 +146952,7 @@ function registerAllTools(server, deps = {}) {
|
|
|
146596
146952
|
...env ? { env } : {}
|
|
146597
146953
|
});
|
|
146598
146954
|
registerPushTools(server, live, push, deps.env ? { env: deps.env } : {});
|
|
146955
|
+
if (hosted) registerSignInTool(server, deps.signIn ? { signIn: deps.signIn } : {});
|
|
146599
146956
|
}
|
|
146600
146957
|
|
|
146601
146958
|
// src/index.ts
|