@g33ks/foundryvtt-mcp 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +468 -2
- package/dist/character/manager.js +208 -0
- package/dist/cli/checks.js +307 -0
- package/dist/cli/config-file.js +120 -0
- package/dist/cli/init.js +410 -0
- package/dist/cli/prompt.js +117 -0
- package/dist/cli/snippets.js +49 -0
- package/dist/combat/manager.js +371 -0
- package/dist/config/env-layers.js +49 -0
- package/dist/config/index.js +298 -0
- package/dist/config/sources.js +201 -0
- package/dist/core.js +415 -0
- package/dist/diagnostics/client.js +353 -0
- package/dist/diagnostics/types.js +94 -0
- package/dist/foundry/auth.js +220 -0
- package/dist/foundry/browser-detect.js +170 -0
- package/dist/foundry/client.js +5555 -0
- package/dist/foundry/dice-formula.js +154 -0
- package/dist/foundry/event-log.js +299 -0
- package/dist/foundry/headless-gm-session.js +740 -0
- package/dist/foundry/journal-history.js +90 -0
- package/dist/foundry/journal-integrity.js +306 -0
- package/dist/foundry/module-bridge.js +413 -0
- package/dist/foundry/types.js +52 -0
- package/dist/foundry/world-cache.js +386 -0
- package/dist/index.js +107 -0
- package/dist/mcp-server.js +63 -0
- package/dist/server.js +159 -0
- package/dist/shared/build-order.js +134 -0
- package/dist/shared/config-hash.js +62 -0
- package/dist/shared/config-notice.js +55 -0
- package/dist/shared/control.js +255 -0
- package/dist/shared/daemon-link.js +135 -0
- package/dist/shared/daemon.js +313 -0
- package/dist/shared/ipc-client.js +200 -0
- package/dist/shared/ipc-server.js +316 -0
- package/dist/shared/paths.js +79 -0
- package/dist/shared/protocol.js +230 -0
- package/dist/shared/relay-config.js +65 -0
- package/dist/shared/relay.js +120 -0
- package/dist/shared/rotating-log.js +57 -0
- package/dist/shared/spawn.js +39 -0
- package/dist/shared/state-file.js +33 -0
- package/dist/shared/token.js +62 -0
- package/dist/shared/version.js +57 -0
- package/dist/tools/base.js +74 -0
- package/dist/tools/definitions.js +3109 -0
- package/dist/tools/handlers/actor-mutations.js +128 -0
- package/dist/tools/handlers/actors.js +114 -0
- package/dist/tools/handlers/chat-mutations.js +49 -0
- package/dist/tools/handlers/chat.js +36 -0
- package/dist/tools/handlers/combat-mutations.js +215 -0
- package/dist/tools/handlers/combat-order.js +94 -0
- package/dist/tools/handlers/combat.js +51 -0
- package/dist/tools/handlers/compendium.js +83 -0
- package/dist/tools/handlers/diagnostics.js +438 -0
- package/dist/tools/handlers/dice.js +54 -0
- package/dist/tools/handlers/effects.js +103 -0
- package/dist/tools/handlers/events.js +50 -0
- package/dist/tools/handlers/generation.js +258 -0
- package/dist/tools/handlers/item-mutations.js +132 -0
- package/dist/tools/handlers/items.js +53 -0
- package/dist/tools/handlers/journal-mutations.js +230 -0
- package/dist/tools/handlers/journals.js +80 -0
- package/dist/tools/handlers/module-bridge.js +421 -0
- package/dist/tools/handlers/placeable-mutations.js +272 -0
- package/dist/tools/handlers/resources.js +203 -0
- package/dist/tools/handlers/roll-tables.js +97 -0
- package/dist/tools/handlers/scene-mutations.js +159 -0
- package/dist/tools/handlers/scenes.js +355 -0
- package/dist/tools/handlers/settings.js +53 -0
- package/dist/tools/handlers/tile-mutations.js +56 -0
- package/dist/tools/handlers/token-mutations.js +356 -0
- package/dist/tools/handlers/users.js +59 -0
- package/dist/tools/handlers/utils.js +47 -0
- package/dist/tools/handlers/wall-mutations.js +98 -0
- package/dist/tools/handlers/world-documents.js +222 -0
- package/dist/tools/handlers/world.js +92 -0
- package/dist/tools/index.js +25 -0
- package/dist/tools/new-router.js +97 -0
- package/dist/tools/registry.js +79 -0
- package/dist/tools/resources.js +63 -0
- package/dist/tools/router.js +688 -0
- package/dist/tools/write-tools.js +97 -0
- package/dist/utils/cache-instance.js +30 -0
- package/dist/utils/cache.js +205 -0
- package/dist/utils/diagnostics.js +332 -0
- package/dist/utils/guards.js +17 -0
- package/dist/utils/image-size.js +160 -0
- package/dist/utils/log-args.js +47 -0
- package/dist/utils/logger.js +203 -0
- package/dist/utils/refusal.js +30 -0
- package/dist/utils/sanitize.js +22 -0
- package/dist/utils/serial-queue.js +22 -0
- package/package.json +124 -4
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview WebSocket relay to the companion Foundry module.
|
|
3
|
+
*
|
|
4
|
+
* FoundryVTT's own Socket.IO API (used by {@link FoundryClient}) only reaches
|
|
5
|
+
* the document/database layer — it has no route to the browser's canvas,
|
|
6
|
+
* PIXI, or `game.packs`. A handful of capabilities (scene screenshots, fog
|
|
7
|
+
* reveal, compendium import) only exist inside a real, rendered browser tab.
|
|
8
|
+
*
|
|
9
|
+
* This class is the server side of that bridge: it hosts a plain WebSocket
|
|
10
|
+
* server that the companion `foundry-module/` package (loaded into Foundry as
|
|
11
|
+
* a module, running in the GM's browser) dials into as a client. Commands are
|
|
12
|
+
* `{ id, type, params }`; responses are `{ id, result }` or `{ id, error }` —
|
|
13
|
+
* the same shape used by alexivenkov/foundry-api-bridge-module's
|
|
14
|
+
* `WebSocketClient.ts` (MIT), which this mirrors from the server side.
|
|
15
|
+
*
|
|
16
|
+
* Exactly one module connection is supported at a time (the GM's client); a
|
|
17
|
+
* new *authenticated* connection replaces the previous one.
|
|
18
|
+
*
|
|
19
|
+
* Authentication (protocol v1). The loopback listener is reachable by every
|
|
20
|
+
* local process and every page open in a local browser, so a connection is
|
|
21
|
+
* only trusted once it has proven it is the module running in the headless
|
|
22
|
+
* GM session ({@link HeadlessGmSession}), and the module only obeys once the
|
|
23
|
+
* server has proven it is this process:
|
|
24
|
+
*
|
|
25
|
+
* 1. Upgrade: the `Origin` header must be `FOUNDRY_URL`'s origin (HTTP 403
|
|
26
|
+
* otherwise), so a page from any other site cannot even open the socket.
|
|
27
|
+
* 2. Server → module `{type: "auth_challenge", protocol: 1, nonce: Ns}`.
|
|
28
|
+
* 3. Module → server `{type: "auth_response", protocol: 1, nonce: Nc, proof: Pc}`.
|
|
29
|
+
* 4. Server → module `{type: "auth_ok", proof: Ps}`.
|
|
30
|
+
*
|
|
31
|
+
* Both proofs are HMAC-SHA256 over the two nonces, keyed by a random secret
|
|
32
|
+
* generated per instance that never leaves this class: the module obtains
|
|
33
|
+
* `Nc`, `Pc` and the expected `Ps` from {@link ModuleBridge.prove}, which the
|
|
34
|
+
* headless session exposes to its page through a Playwright binding. Until
|
|
35
|
+
* step 3 checks out, a connection cannot replace the current module, receives
|
|
36
|
+
* no command, and nothing it sends is processed.
|
|
37
|
+
*/
|
|
38
|
+
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
39
|
+
import { WebSocket, WebSocketServer } from 'ws';
|
|
40
|
+
import { isRecord } from '../utils/guards.js';
|
|
41
|
+
import { logger } from '../utils/logger.js';
|
|
42
|
+
/** Version of the authentication handshake spoken by this server. */
|
|
43
|
+
export const BRIDGE_PROTOCOL_VERSION = 1;
|
|
44
|
+
/** Close codes sent to a connection that fails authentication. */
|
|
45
|
+
export const BRIDGE_CLOSE_CODES = {
|
|
46
|
+
/** Wrong proof, unknown protocol version, or any other message before authenticating. */
|
|
47
|
+
unauthorized: 4401,
|
|
48
|
+
/** No `auth_response` within the authentication window. */
|
|
49
|
+
authTimeout: 4408,
|
|
50
|
+
/** A message larger than {@link MAX_PREAUTH_MESSAGE_BYTES} before authenticating. */
|
|
51
|
+
messageTooBig: 1009,
|
|
52
|
+
};
|
|
53
|
+
const NONCE_BYTES = 32;
|
|
54
|
+
/** Length of the base64 encoding of {@link NONCE_BYTES} bytes. */
|
|
55
|
+
const NONCE_BASE64_LENGTH = 44;
|
|
56
|
+
const AUTH_TIMEOUT_MS = 5000;
|
|
57
|
+
const MAX_PREAUTH_MESSAGE_BYTES = 4096;
|
|
58
|
+
const PROOF_LABEL = 'foundryvtt-mcp-bridge/v1';
|
|
59
|
+
/** Refusal warnings logged per window; the rest are counted and summarised. */
|
|
60
|
+
const REFUSAL_LOG_LIMIT = 10;
|
|
61
|
+
const REFUSAL_LOG_WINDOW_MS = 60_000;
|
|
62
|
+
function isBridgeMessage(value) {
|
|
63
|
+
return typeof value === 'object' && value !== null;
|
|
64
|
+
}
|
|
65
|
+
/** A canonical base64 encoding of exactly {@link NONCE_BYTES} bytes. */
|
|
66
|
+
function isNonce(value) {
|
|
67
|
+
if (typeof value !== 'string' || value.length !== NONCE_BASE64_LENGTH) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
const bytes = Buffer.from(value, 'base64');
|
|
71
|
+
return bytes.length === NONCE_BYTES && bytes.toString('base64') === value;
|
|
72
|
+
}
|
|
73
|
+
function rawDataBytes(data) {
|
|
74
|
+
if (Array.isArray(data)) {
|
|
75
|
+
return data.reduce((total, chunk) => total + chunk.length, 0);
|
|
76
|
+
}
|
|
77
|
+
return data instanceof ArrayBuffer ? data.byteLength : data.length;
|
|
78
|
+
}
|
|
79
|
+
function rawDataText(data) {
|
|
80
|
+
if (Array.isArray(data)) {
|
|
81
|
+
return Buffer.concat(data).toString();
|
|
82
|
+
}
|
|
83
|
+
return data instanceof ArrayBuffer ? Buffer.from(data).toString() : data.toString();
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Logs connection refusals without letting a local process flood the log by
|
|
87
|
+
* reconnecting in a loop: at most {@link REFUSAL_LOG_LIMIT} per window, then
|
|
88
|
+
* one line with the count of the ones left out.
|
|
89
|
+
*/
|
|
90
|
+
class RefusalLog {
|
|
91
|
+
windowStart = 0;
|
|
92
|
+
logged = 0;
|
|
93
|
+
suppressed = 0;
|
|
94
|
+
warn(message, meta) {
|
|
95
|
+
const now = Date.now();
|
|
96
|
+
if (now - this.windowStart >= REFUSAL_LOG_WINDOW_MS) {
|
|
97
|
+
if (this.suppressed > 0) {
|
|
98
|
+
logger.warn(`Module bridge: ${this.suppressed} more refused connection(s) not logged in the last minute`);
|
|
99
|
+
}
|
|
100
|
+
this.windowStart = now;
|
|
101
|
+
this.logged = 0;
|
|
102
|
+
this.suppressed = 0;
|
|
103
|
+
}
|
|
104
|
+
if (this.logged < REFUSAL_LOG_LIMIT) {
|
|
105
|
+
this.logged++;
|
|
106
|
+
logger.warn(message, meta);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
this.suppressed++;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
export class ModuleBridge {
|
|
114
|
+
/** One listener per loopback address. */
|
|
115
|
+
servers = [];
|
|
116
|
+
/** The authenticated module connection; unauthenticated ones are never stored here. */
|
|
117
|
+
socket = null;
|
|
118
|
+
connectedSince = null;
|
|
119
|
+
pending = new Map();
|
|
120
|
+
nextId = 1;
|
|
121
|
+
port;
|
|
122
|
+
expectedOrigin;
|
|
123
|
+
requestTimeoutMs;
|
|
124
|
+
authTimeoutMs;
|
|
125
|
+
/** HMAC key of the handshake. In memory only: never logged, persisted or returned. */
|
|
126
|
+
secret = randomBytes(32);
|
|
127
|
+
refusals = new RefusalLog();
|
|
128
|
+
/**
|
|
129
|
+
* Invoked for every unsolicited `{event, payload}` push from the module —
|
|
130
|
+
* canvas activity (targeting, pings) that never crosses FoundryVTT's own
|
|
131
|
+
* `modifyDocument` Socket.IO channel. `null` when nobody is listening.
|
|
132
|
+
*/
|
|
133
|
+
onEvent = null;
|
|
134
|
+
constructor(port, options) {
|
|
135
|
+
this.port = port;
|
|
136
|
+
this.expectedOrigin = options.expectedOrigin;
|
|
137
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? 15000;
|
|
138
|
+
this.authTimeoutMs = options.authTimeoutMs ?? AUTH_TIMEOUT_MS;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Starts the relay server and waits for it to be listening.
|
|
142
|
+
*
|
|
143
|
+
* Loopback only: the module dials `ws://localhost:<port>` from a browser
|
|
144
|
+
* on this machine, and the bridge drives a GM session, so it must not be
|
|
145
|
+
* reachable from the network. `localhost` may resolve to either family,
|
|
146
|
+
* hence one listener on 127.0.0.1 and one on ::1 (skipped when IPv6 is
|
|
147
|
+
* unavailable).
|
|
148
|
+
*/
|
|
149
|
+
async start() {
|
|
150
|
+
await this.listenOn('127.0.0.1');
|
|
151
|
+
try {
|
|
152
|
+
await this.listenOn('::1');
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
const code = error.code;
|
|
156
|
+
if (code !== 'EADDRNOTAVAIL' && code !== 'EAFNOSUPPORT') {
|
|
157
|
+
await this.stop();
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
logger.debug(`Module bridge: IPv6 loopback unavailable (${code}); IPv4 only`);
|
|
161
|
+
}
|
|
162
|
+
logger.info(`Module bridge listening on ws://localhost:${this.port} (loopback only)`);
|
|
163
|
+
}
|
|
164
|
+
listenOn(host) {
|
|
165
|
+
return new Promise((resolve, reject) => {
|
|
166
|
+
const wss = new WebSocketServer({
|
|
167
|
+
host,
|
|
168
|
+
port: this.port,
|
|
169
|
+
verifyClient: (info, done) => {
|
|
170
|
+
if (info.origin === this.expectedOrigin) {
|
|
171
|
+
done(true);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
this.refusals.warn('Module bridge refused a connection: unexpected Origin', {
|
|
175
|
+
origin: info.origin ?? '(none)',
|
|
176
|
+
remoteAddress: info.req.socket.remoteAddress,
|
|
177
|
+
});
|
|
178
|
+
done(false, 403, 'Forbidden');
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
wss.once('listening', () => {
|
|
182
|
+
this.servers.push(wss);
|
|
183
|
+
resolve();
|
|
184
|
+
});
|
|
185
|
+
wss.once('error', (err) => {
|
|
186
|
+
wss.close();
|
|
187
|
+
reject(err);
|
|
188
|
+
});
|
|
189
|
+
wss.on('connection', (ws, req) => this.handleConnection(ws, req));
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Challenges a fresh connection. It only becomes the module connection —
|
|
194
|
+
* replacing the previous one — once its `auth_response` checks out.
|
|
195
|
+
*/
|
|
196
|
+
handleConnection(ws, req) {
|
|
197
|
+
const remoteAddress = req.socket.remoteAddress;
|
|
198
|
+
const serverNonce = randomBytes(NONCE_BYTES).toString('base64');
|
|
199
|
+
let authenticated = false;
|
|
200
|
+
let refused = false;
|
|
201
|
+
const refuse = (code, reason, detail) => {
|
|
202
|
+
refused = true;
|
|
203
|
+
clearTimeout(authTimer);
|
|
204
|
+
this.refusals.warn(`Module bridge refused a connection: ${detail}`, { remoteAddress });
|
|
205
|
+
ws.close(code, reason);
|
|
206
|
+
};
|
|
207
|
+
const authTimer = setTimeout(() => refuse(BRIDGE_CLOSE_CODES.authTimeout, 'authentication timeout', `client did not authenticate within ${this.authTimeoutMs} ms; likely an outdated ` +
|
|
208
|
+
'foundryvtt-mcp-bridge module (< 0.5.0), redeploy it'), this.authTimeoutMs);
|
|
209
|
+
ws.on('message', (data) => {
|
|
210
|
+
if (authenticated) {
|
|
211
|
+
// A replaced module may still be sending until its socket closes.
|
|
212
|
+
if (this.socket === ws) {
|
|
213
|
+
this.handleMessage(rawDataText(data));
|
|
214
|
+
}
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (refused) {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (rawDataBytes(data) > MAX_PREAUTH_MESSAGE_BYTES) {
|
|
221
|
+
refuse(BRIDGE_CLOSE_CODES.messageTooBig, 'message too big', `message over ${MAX_PREAUTH_MESSAGE_BYTES} bytes before authentication`);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const verdict = this.checkAuthResponse(rawDataText(data), serverNonce);
|
|
225
|
+
if (!verdict.ok) {
|
|
226
|
+
refuse(BRIDGE_CLOSE_CODES.unauthorized, 'unauthorized', verdict.reason);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
authenticated = true;
|
|
230
|
+
clearTimeout(authTimer);
|
|
231
|
+
ws.send(JSON.stringify({ type: 'auth_ok', proof: verdict.serverProof }));
|
|
232
|
+
this.adopt(ws, remoteAddress);
|
|
233
|
+
});
|
|
234
|
+
ws.on('close', () => {
|
|
235
|
+
clearTimeout(authTimer);
|
|
236
|
+
if (this.socket === ws) {
|
|
237
|
+
logger.warn('Foundry module disconnected from bridge');
|
|
238
|
+
this.socket = null;
|
|
239
|
+
this.connectedSince = null;
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
ws.on('error', (err) => {
|
|
243
|
+
logger.error('Module bridge socket error', { error: err.message });
|
|
244
|
+
});
|
|
245
|
+
ws.send(JSON.stringify({
|
|
246
|
+
type: 'auth_challenge',
|
|
247
|
+
protocol: BRIDGE_PROTOCOL_VERSION,
|
|
248
|
+
nonce: serverNonce,
|
|
249
|
+
}));
|
|
250
|
+
}
|
|
251
|
+
/** Makes an authenticated connection the module connection. */
|
|
252
|
+
adopt(ws, remoteAddress) {
|
|
253
|
+
const previous = this.socket;
|
|
254
|
+
this.socket = ws;
|
|
255
|
+
this.connectedSince = new Date();
|
|
256
|
+
if (previous) {
|
|
257
|
+
// e.g. the headless page reloaded before its old socket closed.
|
|
258
|
+
previous.terminate();
|
|
259
|
+
logger.info('Foundry module re-authenticated; previous module connection replaced', {
|
|
260
|
+
remoteAddress,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
logger.info(`Foundry module connected and authenticated (protocol v${BRIDGE_PROTOCOL_VERSION})`, { remoteAddress });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
checkAuthResponse(raw, serverNonce) {
|
|
268
|
+
let parsed;
|
|
269
|
+
try {
|
|
270
|
+
parsed = JSON.parse(raw);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return { ok: false, reason: 'non-JSON message before authentication' };
|
|
274
|
+
}
|
|
275
|
+
if (!isRecord(parsed) || parsed.type !== 'auth_response') {
|
|
276
|
+
return { ok: false, reason: 'message other than auth_response before authentication' };
|
|
277
|
+
}
|
|
278
|
+
if (parsed.protocol !== BRIDGE_PROTOCOL_VERSION) {
|
|
279
|
+
return {
|
|
280
|
+
ok: false,
|
|
281
|
+
reason: `unsupported bridge protocol ${JSON.stringify(parsed.protocol)} (expected ${BRIDGE_PROTOCOL_VERSION})`,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
if (!isNonce(parsed.nonce) || typeof parsed.proof !== 'string') {
|
|
285
|
+
return { ok: false, reason: 'malformed auth_response' };
|
|
286
|
+
}
|
|
287
|
+
const expected = this.hmac('client', serverNonce, parsed.nonce);
|
|
288
|
+
const received = Buffer.from(parsed.proof, 'base64');
|
|
289
|
+
if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
|
|
290
|
+
return { ok: false, reason: 'wrong authentication proof' };
|
|
291
|
+
}
|
|
292
|
+
return {
|
|
293
|
+
ok: true,
|
|
294
|
+
serverProof: this.hmac('server', serverNonce, parsed.nonce).toString('base64'),
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
hmac(role, serverNonce, clientNonce) {
|
|
298
|
+
return createHmac('sha256', this.secret)
|
|
299
|
+
.update(`${PROOF_LABEL}|${role}|${serverNonce}|${clientNonce}`)
|
|
300
|
+
.digest();
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Answers a server challenge on the module's behalf: picks the client
|
|
304
|
+
* nonce and computes both proofs. Called from the headless session's page
|
|
305
|
+
* binding, so `serverNonce` is untrusted input.
|
|
306
|
+
*
|
|
307
|
+
* @throws if `serverNonce` is not the base64 of {@link NONCE_BYTES} bytes
|
|
308
|
+
*/
|
|
309
|
+
prove(serverNonce) {
|
|
310
|
+
if (!isNonce(serverNonce)) {
|
|
311
|
+
throw new Error('Invalid server nonce');
|
|
312
|
+
}
|
|
313
|
+
const nonce = randomBytes(NONCE_BYTES).toString('base64');
|
|
314
|
+
return {
|
|
315
|
+
nonce,
|
|
316
|
+
clientProof: this.hmac('client', serverNonce, nonce).toString('base64'),
|
|
317
|
+
serverProof: this.hmac('server', serverNonce, nonce).toString('base64'),
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
/** What the module needs to dial in: the protocol and this bridge's port. */
|
|
321
|
+
info() {
|
|
322
|
+
return { protocol: BRIDGE_PROTOCOL_VERSION, port: this.port };
|
|
323
|
+
}
|
|
324
|
+
async stop() {
|
|
325
|
+
for (const [, pending] of this.pending) {
|
|
326
|
+
clearTimeout(pending.timeout);
|
|
327
|
+
pending.reject(new Error('Module bridge shutting down'));
|
|
328
|
+
}
|
|
329
|
+
this.pending.clear();
|
|
330
|
+
this.socket?.close();
|
|
331
|
+
this.socket = null;
|
|
332
|
+
this.connectedSince = null;
|
|
333
|
+
const servers = this.servers;
|
|
334
|
+
this.servers = [];
|
|
335
|
+
await Promise.all(servers.map((wss) => new Promise((resolve, reject) => {
|
|
336
|
+
// Unauthenticated connections are not tracked here; close them too.
|
|
337
|
+
for (const client of wss.clients) {
|
|
338
|
+
client.terminate();
|
|
339
|
+
}
|
|
340
|
+
wss.close((err) => (err ? reject(err) : resolve()));
|
|
341
|
+
})));
|
|
342
|
+
}
|
|
343
|
+
/** True once {@link start} has bound the port, until {@link stop}. */
|
|
344
|
+
isListening() {
|
|
345
|
+
return this.servers.length > 0;
|
|
346
|
+
}
|
|
347
|
+
/** True while an authenticated module is connected. */
|
|
348
|
+
isConnected() {
|
|
349
|
+
return this.socket?.readyState === WebSocket.OPEN;
|
|
350
|
+
}
|
|
351
|
+
/** When the current authenticated module connection was established, or `null`. */
|
|
352
|
+
moduleConnectedSince() {
|
|
353
|
+
return this.isConnected() ? this.connectedSince : null;
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Sends a command to the connected module and awaits its response.
|
|
357
|
+
*
|
|
358
|
+
* @throws if no module is connected, or the module reports an error, or
|
|
359
|
+
* the request times out (the module hung, or the command type is unknown
|
|
360
|
+
* to it).
|
|
361
|
+
*/
|
|
362
|
+
send(type, params = {}) {
|
|
363
|
+
if (!this.isConnected() || !this.socket) {
|
|
364
|
+
throw new Error('No authenticated Foundry module connected to the bridge. Install and enable the companion module (0.5.0 or later), confirm FOUNDRY_MODULE_BRIDGE_ENABLED=true, and check that the headless GM session is logged in.');
|
|
365
|
+
}
|
|
366
|
+
const id = String(this.nextId++);
|
|
367
|
+
const socket = this.socket;
|
|
368
|
+
return new Promise((resolve, reject) => {
|
|
369
|
+
const timeout = setTimeout(() => {
|
|
370
|
+
this.pending.delete(id);
|
|
371
|
+
reject(new Error(`Module command '${type}' timed out after ${this.requestTimeoutMs}ms`));
|
|
372
|
+
}, this.requestTimeoutMs);
|
|
373
|
+
this.pending.set(id, { resolve, reject, timeout });
|
|
374
|
+
socket.send(JSON.stringify({ id, type, params }));
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
handleMessage(raw) {
|
|
378
|
+
let parsed;
|
|
379
|
+
try {
|
|
380
|
+
parsed = JSON.parse(raw);
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
logger.warn('Module bridge received non-JSON message');
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (!isBridgeMessage(parsed)) {
|
|
387
|
+
logger.warn('Module bridge received a message with no request id');
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
if (typeof parsed.id !== 'string') {
|
|
391
|
+
if (typeof parsed.event === 'string') {
|
|
392
|
+
this.onEvent?.(parsed.event, isRecord(parsed.payload) ? parsed.payload : {});
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
logger.warn('Module bridge received a message with no request id');
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const pending = this.pending.get(parsed.id);
|
|
399
|
+
if (!pending) {
|
|
400
|
+
// Late response to a request that already timed out, or an unsolicited message.
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
this.pending.delete(parsed.id);
|
|
404
|
+
clearTimeout(pending.timeout);
|
|
405
|
+
if (parsed.error !== undefined) {
|
|
406
|
+
pending.reject(new Error(typeof parsed.error === 'string' ? parsed.error : 'Module error'));
|
|
407
|
+
}
|
|
408
|
+
else {
|
|
409
|
+
pending.resolve(parsed.result);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
//# sourceMappingURL=module-bridge.js.map
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview TypeScript type definitions for FoundryVTT data structures
|
|
3
|
+
*
|
|
4
|
+
* This module contains comprehensive type definitions for all FoundryVTT entities
|
|
5
|
+
* including actors, items, scenes, tokens, and other game objects. These types
|
|
6
|
+
* provide type safety and intellisense when working with FoundryVTT data.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @author FoundryVTT MCP Team
|
|
10
|
+
* @see {@link https://foundryvtt.com/api/} FoundryVTT API Documentation
|
|
11
|
+
*/
|
|
12
|
+
/** {@link DocumentVisibility} → the `ownership.default` level it maps to. */
|
|
13
|
+
export const VISIBILITY_LEVELS = {
|
|
14
|
+
'gm-only': 0,
|
|
15
|
+
observer: 2,
|
|
16
|
+
owner: 3,
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* FoundryVTT's `CONST.DOCUMENT_OWNERSHIP_LEVELS` — who can read, observe, or
|
|
20
|
+
* edit a document.
|
|
21
|
+
*/
|
|
22
|
+
export const OWNERSHIP_LEVELS = {
|
|
23
|
+
none: 0,
|
|
24
|
+
limited: 1,
|
|
25
|
+
observer: 2,
|
|
26
|
+
owner: 3,
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* FoundryVTT's `CONST.USER_ROLES` — user permission tiers.
|
|
30
|
+
*/
|
|
31
|
+
export const USER_ROLES = {
|
|
32
|
+
none: 0,
|
|
33
|
+
player: 1,
|
|
34
|
+
trusted: 2,
|
|
35
|
+
assistant: 3,
|
|
36
|
+
gamemaster: 4,
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* FoundryVTT's `CONST.ACTIVE_EFFECT_MODES` — how an `ActiveEffect` change
|
|
40
|
+
* combines with the base value. Tools accept the string name, never the raw
|
|
41
|
+
* number: an LLM misremembering whether `override` is `2` or `5` would
|
|
42
|
+
* silently apply the wrong mechanic rather than fail loudly.
|
|
43
|
+
*/
|
|
44
|
+
export const ACTIVE_EFFECT_MODES = {
|
|
45
|
+
custom: 0,
|
|
46
|
+
multiply: 1,
|
|
47
|
+
add: 2,
|
|
48
|
+
downgrade: 3,
|
|
49
|
+
upgrade: 4,
|
|
50
|
+
override: 5,
|
|
51
|
+
};
|
|
52
|
+
//# sourceMappingURL=types.js.map
|