@saturn-universe/runtime-host 0.0.0-stage → 0.1.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.
Files changed (116) hide show
  1. package/LICENSE +661 -0
  2. package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
  3. package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
  4. package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
  5. package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
  6. package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
  7. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
  8. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
  9. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
  10. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
  11. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
  12. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
  13. package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
  14. package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
  15. package/dist/command-dispatch.d.ts +10 -0
  16. package/dist/command-dispatch.js +65 -0
  17. package/dist/completion-judge.d.ts +10 -0
  18. package/dist/completion-judge.js +156 -0
  19. package/dist/composition.d.ts +108 -0
  20. package/dist/composition.js +1180 -0
  21. package/dist/configuration.d.ts +49 -0
  22. package/dist/configuration.js +51 -0
  23. package/dist/context-extensions.d.ts +681 -0
  24. package/dist/context-extensions.js +289 -0
  25. package/dist/cordis/context-core-plugin.d.ts +35 -0
  26. package/dist/cordis/context-core-plugin.js +296 -0
  27. package/dist/cordis/env-probe-plugin.d.ts +27 -0
  28. package/dist/cordis/env-probe-plugin.js +114 -0
  29. package/dist/cordis/host-context.d.ts +65 -0
  30. package/dist/cordis/host-context.js +199 -0
  31. package/dist/cordis/model-responses-plugin.d.ts +81 -0
  32. package/dist/cordis/model-responses-plugin.js +209 -0
  33. package/dist/cordis/plugin-contributions.d.ts +47 -0
  34. package/dist/cordis/plugin-contributions.js +119 -0
  35. package/dist/cordis/plugin-lifecycle.d.ts +57 -0
  36. package/dist/cordis/plugin-lifecycle.js +222 -0
  37. package/dist/cordis/plugin-loader.d.ts +18 -0
  38. package/dist/cordis/plugin-loader.js +310 -0
  39. package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
  40. package/dist/cordis/plugin-sdk-adapter.js +283 -0
  41. package/dist/cordis/required-host-plugin.d.ts +6 -0
  42. package/dist/cordis/required-host-plugin.js +1 -0
  43. package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
  44. package/dist/cordis/runtime-hooks-plugin.js +103 -0
  45. package/dist/cordis/sandbox-plugin.d.ts +18 -0
  46. package/dist/cordis/sandbox-plugin.js +21 -0
  47. package/dist/cordis/scoped-layers.d.ts +63 -0
  48. package/dist/cordis/scoped-layers.js +170 -0
  49. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
  50. package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
  51. package/dist/cordis/tools/index.d.ts +17 -0
  52. package/dist/cordis/tools/index.js +40 -0
  53. package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
  54. package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
  55. package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
  56. package/dist/cordis/tools/process-manager-plugin.js +39 -0
  57. package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
  58. package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
  59. package/dist/cordis/tools/tool-guidance.d.ts +4 -0
  60. package/dist/cordis/tools/tool-guidance.js +30 -0
  61. package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
  62. package/dist/cordis/tools/tools-core-plugin.js +486 -0
  63. package/dist/cordis/tools/web-fetch.d.ts +17 -0
  64. package/dist/cordis/tools/web-fetch.js +529 -0
  65. package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
  66. package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
  67. package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
  68. package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
  69. package/dist/env-probe.d.ts +8 -0
  70. package/dist/env-probe.js +172 -0
  71. package/dist/host-configuration.d.ts +27 -0
  72. package/dist/host-configuration.js +185 -0
  73. package/dist/host-tools.d.ts +19 -0
  74. package/dist/host-tools.js +30 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +140 -0
  77. package/dist/ipc.d.ts +24 -0
  78. package/dist/ipc.js +162 -0
  79. package/dist/logger.d.ts +11 -0
  80. package/dist/logger.js +84 -0
  81. package/dist/mcp-configuration.d.ts +17 -0
  82. package/dist/mcp-configuration.js +50 -0
  83. package/dist/modes.d.ts +27 -0
  84. package/dist/modes.js +478 -0
  85. package/dist/ownership.d.ts +7 -0
  86. package/dist/ownership.js +100 -0
  87. package/dist/plugin-configuration.d.ts +9 -0
  88. package/dist/plugin-configuration.js +21 -0
  89. package/dist/plugin-tool-grants.d.ts +18 -0
  90. package/dist/plugin-tool-grants.js +21 -0
  91. package/dist/process-workspaces.d.ts +4 -0
  92. package/dist/process-workspaces.js +28 -0
  93. package/dist/progress.d.ts +30 -0
  94. package/dist/progress.js +699 -0
  95. package/dist/provider-catalog.d.ts +754 -0
  96. package/dist/provider-catalog.js +472 -0
  97. package/dist/run-budget.d.ts +24 -0
  98. package/dist/run-budget.js +47 -0
  99. package/dist/run-checkpoint.d.ts +2 -0
  100. package/dist/run-checkpoint.js +52 -0
  101. package/dist/sandbox-manager.d.ts +111 -0
  102. package/dist/sandbox-manager.js +1519 -0
  103. package/dist/session-paths.d.ts +15 -0
  104. package/dist/session-paths.js +40 -0
  105. package/dist/side-question.d.ts +14 -0
  106. package/dist/side-question.js +89 -0
  107. package/dist/skills-runtime.d.ts +13 -0
  108. package/dist/skills-runtime.js +243 -0
  109. package/dist/token-estimator.d.ts +3 -0
  110. package/dist/token-estimator.js +73 -0
  111. package/dist/tool-result.d.ts +2 -0
  112. package/dist/tool-result.js +91 -0
  113. package/dist/user-config.d.ts +23 -0
  114. package/dist/user-config.js +36 -0
  115. package/package.json +28 -3
  116. package/README.md +0 -3
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Process-level global lease manager for remote CTF platform instances.
3
+ * Coordinates concurrent Worker/Helper requests against platform container quotas
4
+ * and enforces post-stop cooldown windows without leaking platform credentials.
5
+ */
6
+ export function createInstanceLeaseManager({
7
+ maxRemoteInstances = 1,
8
+ instanceCooldownMs = 30_000,
9
+ now = () => Date.now(),
10
+ } = {}) {
11
+ /** @type {Map<string, { challengeId: string, ownerSessionId?: string, startedAt: string, expiresAt: string | null, connection: Record<string, unknown> }>} */
12
+ const activeLeases = new Map();
13
+ /** @type {number | undefined} */
14
+ let lastStoppedAt;
15
+
16
+ function prune(currentMs = now()) {
17
+ const expired = [];
18
+ for (const [id, lease] of activeLeases.entries()) {
19
+ if (typeof lease.expiresAt === 'string') {
20
+ const expiresAtMs = Date.parse(lease.expiresAt);
21
+ if (Number.isFinite(expiresAtMs) && expiresAtMs <= currentMs) {
22
+ activeLeases.delete(id);
23
+ expired.push(id);
24
+ }
25
+ }
26
+ }
27
+ return expired;
28
+ }
29
+
30
+ function list(currentMs = now(), ownerSessionId) {
31
+ prune(currentMs);
32
+ return [...activeLeases.values()]
33
+ .filter((lease) => ownerSessionId === undefined || lease.ownerSessionId === ownerSessionId)
34
+ .map(({ challengeId, ownerSessionId: leaseOwner, startedAt, expiresAt }) => ({
35
+ challengeId,
36
+ ...(leaseOwner !== undefined ? { ownerSessionId: leaseOwner } : {}),
37
+ startedAt,
38
+ expiresAt,
39
+ }));
40
+ }
41
+
42
+ function get(challengeId, currentMs = now(), ownerSessionId) {
43
+ prune(currentMs);
44
+ const lease = activeLeases.get(challengeId);
45
+ if (!lease) return undefined;
46
+ if (ownerSessionId !== undefined && lease.ownerSessionId !== ownerSessionId) return undefined;
47
+ return lease;
48
+ }
49
+
50
+ function has(challengeId, currentMs = now(), ownerSessionId) {
51
+ return get(challengeId, currentMs, ownerSessionId) !== undefined;
52
+ }
53
+
54
+ function checkStart(challengeId, currentMs = now(), ownerSessionId) {
55
+ prune(currentMs);
56
+ const existing = activeLeases.get(challengeId);
57
+ if (existing) {
58
+ if (ownerSessionId === undefined || existing.ownerSessionId === ownerSessionId) {
59
+ return { ok: true, reused: true, lease: existing };
60
+ }
61
+ return {
62
+ ok: false,
63
+ code: 'REMOTE_QUOTA_EXCEEDED',
64
+ maxRemoteInstances,
65
+ activeLeases: list(currentMs),
66
+ ownedByOtherSession: true,
67
+ };
68
+ }
69
+ if (activeLeases.size >= maxRemoteInstances) {
70
+ return {
71
+ ok: false,
72
+ code: 'REMOTE_QUOTA_EXCEEDED',
73
+ maxRemoteInstances,
74
+ activeLeases: list(currentMs),
75
+ };
76
+ }
77
+ if (lastStoppedAt !== undefined && instanceCooldownMs > 0) {
78
+ const elapsed = currentMs - lastStoppedAt;
79
+ if (elapsed < instanceCooldownMs) {
80
+ return {
81
+ ok: false,
82
+ code: 'INSTANCE_COOLDOWN',
83
+ retryAfterMs: instanceCooldownMs - elapsed,
84
+ instanceCooldownMs,
85
+ };
86
+ }
87
+ }
88
+ return { ok: true, reused: false };
89
+ }
90
+
91
+ function acquire(challengeId, { startedAt, expiresAt, connection, ownerSessionId } = {}) {
92
+ const currentMs = now();
93
+ prune(currentMs);
94
+ const lease = {
95
+ challengeId,
96
+ ...(ownerSessionId !== undefined ? { ownerSessionId } : {}),
97
+ startedAt: startedAt ?? new Date(currentMs).toISOString(),
98
+ expiresAt: expiresAt ?? null,
99
+ connection: connection ?? { active: true, updatedAt: new Date(currentMs).toISOString() },
100
+ };
101
+ activeLeases.set(challengeId, lease);
102
+ return lease;
103
+ }
104
+
105
+ function renew(challengeId, { expiresAt, connection, ownerSessionId } = {}) {
106
+ const currentMs = now();
107
+ prune(currentMs);
108
+ const previous = activeLeases.get(challengeId);
109
+ const resolvedOwner = ownerSessionId ?? previous?.ownerSessionId;
110
+ const lease = {
111
+ challengeId,
112
+ ...(resolvedOwner !== undefined ? { ownerSessionId: resolvedOwner } : {}),
113
+ startedAt: previous?.startedAt ?? new Date(currentMs).toISOString(),
114
+ expiresAt: expiresAt !== undefined ? (expiresAt ?? null) : (previous?.expiresAt ?? null),
115
+ connection: connection ??
116
+ previous?.connection ?? { active: true, updatedAt: new Date(currentMs).toISOString() },
117
+ };
118
+ activeLeases.set(challengeId, lease);
119
+ return lease;
120
+ }
121
+
122
+ function release(challengeId, currentMs = now(), ownerSessionId) {
123
+ const existing = activeLeases.get(challengeId);
124
+ if (!existing) return false;
125
+ if (ownerSessionId !== undefined && existing.ownerSessionId !== ownerSessionId) return false;
126
+ activeLeases.delete(challengeId);
127
+ lastStoppedAt = currentMs;
128
+ return true;
129
+ }
130
+
131
+ function reset(ownerSessionId) {
132
+ if (ownerSessionId === undefined) {
133
+ activeLeases.clear();
134
+ lastStoppedAt = undefined;
135
+ return;
136
+ }
137
+ for (const [id, lease] of activeLeases.entries()) {
138
+ if (lease.ownerSessionId === ownerSessionId) activeLeases.delete(id);
139
+ }
140
+ }
141
+
142
+ return {
143
+ prune,
144
+ list,
145
+ get,
146
+ has,
147
+ checkStart,
148
+ acquire,
149
+ renew,
150
+ release,
151
+ reset,
152
+ };
153
+ }
@@ -0,0 +1,336 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import { watch } from 'node:fs';
3
+ import { createServer } from 'node:http';
4
+ import { basename as pathBasename } from 'node:path';
5
+ import { boardHtml, clientScript, styles } from './view.mjs';
6
+
7
+ const hash = (value) => `'sha256-${createHash('sha256').update(value).digest('base64')}'`;
8
+ const csp = `default-src 'none'; script-src ${hash(clientScript)}; style-src ${hash(styles)}; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`;
9
+ // Avoid WHATWG Fetch restricted ports when binding an OS-assigned ephemeral port so browsers and fetch clients can connect.
10
+ const BROWSER_UNSAFE_PORTS = new Set([
11
+ 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669, 6697, 10080,
12
+ ]);
13
+ const BOARD_COOKIE_NAME = 'saturn_board_token';
14
+
15
+ function parseCookie(header, name) {
16
+ if (typeof header !== 'string' || !header) return undefined;
17
+ for (const part of header.split(';')) {
18
+ const eq = part.indexOf('=');
19
+ if (eq <= 0) continue;
20
+ if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
21
+ }
22
+ return undefined;
23
+ }
24
+
25
+ export function createBoardService(boardOrProvider, port, readLedgerLegacy, logger, options = {}) {
26
+ const isSingleBoard = typeof boardOrProvider?.snapshot === 'function';
27
+ const provider = isSingleBoard
28
+ ? {
29
+ getDefaultSessionId: () => 'default',
30
+ listSessions: async () => [
31
+ { id: 'default', title: (await boardOrProvider.snapshot()).metadata?.title },
32
+ ],
33
+ getBoard: async () => ({ sessionId: 'default', board: boardOrProvider }),
34
+ readLedger: async (_sessionId, challengeId) => readLedgerLegacy(challengeId),
35
+ watchRoot: () => boardOrProvider.directory(),
36
+ }
37
+ : boardOrProvider;
38
+
39
+ const clients = new Set();
40
+ const boardToken = options.boardToken;
41
+ const boardPublicHost = options.boardPublicHost?.toLowerCase();
42
+ const expectedTokenDigest = boardToken
43
+ ? createHash('sha256').update(boardToken, 'utf8').digest()
44
+ : undefined;
45
+ let server;
46
+ let watcher;
47
+ let heartbeat;
48
+ let pollTimer;
49
+ let starting;
50
+ let disposed = false;
51
+ let url;
52
+
53
+ function isAuthorizedToken(candidate) {
54
+ if (!expectedTokenDigest || typeof candidate !== 'string' || !candidate) return false;
55
+ const actual = createHash('sha256').update(candidate, 'utf8').digest();
56
+ return timingSafeEqual(actual, expectedTokenDigest);
57
+ }
58
+
59
+ function authorizeRequest(req, res, requestUrl) {
60
+ if (!expectedTokenDigest) return true;
61
+ const authHeader = typeof req.headers.authorization === 'string' ? req.headers.authorization : undefined;
62
+ const bearerMatch = authHeader?.match(/^Bearer\s+(.+)$/iu);
63
+ if (bearerMatch && isAuthorizedToken(bearerMatch[1].trim())) {
64
+ return true;
65
+ }
66
+ const queryToken = requestUrl.searchParams.get('token');
67
+ if (queryToken && isAuthorizedToken(queryToken)) {
68
+ res.setHeader('Set-Cookie', `${BOARD_COOKIE_NAME}=${boardToken}; HttpOnly; SameSite=Lax; Path=/`);
69
+ return true;
70
+ }
71
+ const cookieToken = parseCookie(req.headers.cookie, BOARD_COOKIE_NAME);
72
+ if (cookieToken && isAuthorizedToken(cookieToken)) {
73
+ return true;
74
+ }
75
+ res.setHeader('WWW-Authenticate', 'Bearer realm="saturn-board"');
76
+ json(res, 401, { error: 'UNAUTHORIZED' });
77
+ return false;
78
+ }
79
+
80
+ function isAllowedHostAndOrigin(req) {
81
+ if (!url || typeof req.headers.host !== 'string') return false;
82
+ const localHost = new URL(url).host.toLowerCase();
83
+ const requestHost = req.headers.host.toLowerCase();
84
+ if (requestHost !== localHost && (!boardPublicHost || requestHost !== boardPublicHost)) return false;
85
+ if (req.headers.origin) {
86
+ const origin = req.headers.origin.toLowerCase();
87
+ const allowedOrigins = new Set([
88
+ url.toLowerCase(),
89
+ ...(boardPublicHost ? [`http://${boardPublicHost}`, `https://${boardPublicHost}`] : []),
90
+ ]);
91
+ if (!allowedOrigins.has(origin)) return false;
92
+ }
93
+ return true;
94
+ }
95
+
96
+ function sendClient(entry, message) {
97
+ if (!entry.res.write(message)) {
98
+ clients.delete(entry);
99
+ entry.res.destroy();
100
+ }
101
+ }
102
+
103
+ const encode = (value) => `data: ${JSON.stringify(value)}\n\n`;
104
+
105
+ async function snapshotFor(requestedSessionId) {
106
+ const resolved = await provider.getBoard(requestedSessionId);
107
+ if (!resolved?.board) return undefined;
108
+ const snap = await resolved.board.snapshot();
109
+ return { sessionId: resolved.sessionId, snapshot: { ...snap, sessionId: resolved.sessionId } };
110
+ }
111
+
112
+ async function publish(targetSessionId) {
113
+ if (!clients.size) return;
114
+ try {
115
+ const cache = new Map();
116
+ for (const entry of [...clients]) {
117
+ const key = entry.requestedSessionId ?? '__default__';
118
+ if (targetSessionId && entry.resolvedSessionId && entry.resolvedSessionId !== targetSessionId) {
119
+ continue;
120
+ }
121
+ let payload = cache.get(key);
122
+ if (!payload) {
123
+ payload = await snapshotFor(entry.requestedSessionId);
124
+ if (payload) cache.set(key, payload);
125
+ }
126
+ if (!payload) continue;
127
+ const versionKey = `${payload.sessionId}:${payload.snapshot.revision}`;
128
+ if (targetSessionId === '__poll__' && entry.lastVersionKey === versionKey) continue;
129
+ entry.resolvedSessionId = payload.sessionId;
130
+ entry.lastVersionKey = versionKey;
131
+ sendClient(entry, encode(payload.snapshot));
132
+ }
133
+ } catch {
134
+ logger.error({ code: 'CTF_BOARD_READ_FAILED' }, 'Could not publish the board');
135
+ }
136
+ }
137
+
138
+ function json(response, status, value) {
139
+ response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
140
+ response.end(JSON.stringify(value));
141
+ }
142
+
143
+ function requestedSessionFrom(requestUrl) {
144
+ const raw = requestUrl.searchParams.get('sessionId') ?? requestUrl.searchParams.get('session');
145
+ return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined;
146
+ }
147
+
148
+ async function request(req, res) {
149
+ res.setHeader('Cache-Control', 'no-store');
150
+ res.setHeader('X-Content-Type-Options', 'nosniff');
151
+ res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
152
+ if (!isAllowedHostAndOrigin(req)) {
153
+ return json(res, 403, { error: 'INVALID_BOARD_ORIGIN' });
154
+ }
155
+ if (req.method !== 'GET') {
156
+ res.setHeader('Allow', 'GET');
157
+ return json(res, 405, { error: 'METHOD_NOT_ALLOWED' });
158
+ }
159
+ const requestUrl = new URL(req.url, url);
160
+ if (!authorizeRequest(req, res, requestUrl)) return;
161
+ if (requestUrl.pathname === '/') {
162
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': csp });
163
+ return res.end(boardHtml);
164
+ }
165
+ if (requestUrl.pathname === '/api/sessions') {
166
+ const sessions = await provider.listSessions();
167
+ return json(res, 200, { sessions, defaultSessionId: provider.getDefaultSessionId() });
168
+ }
169
+ if (requestUrl.pathname === '/api/board') {
170
+ const requestedSessionId = requestedSessionFrom(requestUrl);
171
+ const result = await snapshotFor(requestedSessionId);
172
+ if (!result) return json(res, 404, { error: 'SESSION_NOT_FOUND' });
173
+ const { sessionId, snapshot: value } = result;
174
+ const id = requestUrl.searchParams.get('challengeId');
175
+ if (id === null) return json(res, 200, value);
176
+ if (!value.challenges.some((item) => item.id === id))
177
+ return json(res, 404, { error: 'CHALLENGE_NOT_FOUND' });
178
+ return json(res, 200, { ...value, ledger: await provider.readLedger(sessionId, id) });
179
+ }
180
+ if (requestUrl.pathname === '/api/events') {
181
+ if (clients.size >= 32) return json(res, 503, { error: 'TOO_MANY_CLIENTS' });
182
+ const requestedSessionId = requestedSessionFrom(requestUrl);
183
+ const initialResult = await snapshotFor(requestedSessionId);
184
+ if (!initialResult) return json(res, 404, { error: 'SESSION_NOT_FOUND' });
185
+ if (disposed || res.destroyed) return res.destroy();
186
+ res.writeHead(200, {
187
+ 'Content-Type': 'text/event-stream; charset=utf-8',
188
+ 'Cache-Control': 'no-cache, no-transform',
189
+ Connection: 'keep-alive',
190
+ 'X-Accel-Buffering': 'no',
191
+ });
192
+ const entry = {
193
+ res,
194
+ requestedSessionId,
195
+ resolvedSessionId: initialResult.sessionId,
196
+ lastVersionKey: `${initialResult.sessionId}:${initialResult.snapshot.revision}`,
197
+ };
198
+ res.on('close', () => clients.delete(entry));
199
+ clients.add(entry);
200
+ sendClient(entry, encode(initialResult.snapshot));
201
+ return;
202
+ }
203
+ return json(res, 404, { error: 'NOT_FOUND' });
204
+ }
205
+
206
+ function createHttpServer() {
207
+ return createServer((req, res) => {
208
+ void request(req, res).catch(() => {
209
+ if (res.headersSent) res.destroy();
210
+ else json(res, 500, { error: 'CTF_BOARD_READ_FAILED' });
211
+ });
212
+ });
213
+ }
214
+
215
+ function listenOn(targetServer, listenPort) {
216
+ return new Promise((resolve, reject) => {
217
+ const onError = (error) => {
218
+ targetServer.removeListener('listening', onListening);
219
+ reject(error);
220
+ };
221
+ const onListening = () => {
222
+ targetServer.removeListener('error', onError);
223
+ resolve();
224
+ };
225
+ targetServer.once('error', onError);
226
+ targetServer.once('listening', onListening);
227
+ targetServer.listen(listenPort, '127.0.0.1');
228
+ });
229
+ }
230
+
231
+ async function bindEphemeralServer() {
232
+ const rejected = [];
233
+ try {
234
+ for (let attempt = 0; attempt < 16; attempt++) {
235
+ const candidate = createHttpServer();
236
+ await listenOn(candidate, 0);
237
+ const assignedPort = candidate.address()?.port;
238
+ if (!BROWSER_UNSAFE_PORTS.has(assignedPort) || attempt === 15) {
239
+ return candidate;
240
+ }
241
+ rejected.push(candidate);
242
+ }
243
+ } finally {
244
+ await Promise.all(
245
+ rejected.map((candidate) =>
246
+ candidate.listening ? new Promise((resolve) => candidate.close(resolve)) : Promise.resolve(),
247
+ ),
248
+ );
249
+ }
250
+ }
251
+
252
+ return {
253
+ getUrl: () => url,
254
+ start() {
255
+ if (disposed) throw new Error('Board service is closed.');
256
+ return (starting ??= (async () => {
257
+ const directory = await provider.watchRoot();
258
+ if (disposed) throw new Error('Board service is closed.');
259
+ if (port === 0) {
260
+ server = await bindEphemeralServer();
261
+ } else {
262
+ server = createHttpServer();
263
+ try {
264
+ await listenOn(server, port);
265
+ } catch (error) {
266
+ if (error?.code !== 'EADDRINUSE') throw error;
267
+ logger.info(
268
+ { code: 'CTF_BOARD_PORT_IN_USE', requestedPort: port },
269
+ 'Configured board port is in use; falling back to an ephemeral port',
270
+ );
271
+ if (server.listening) {
272
+ await new Promise((resolve) => server.close(resolve));
273
+ }
274
+ if (disposed) throw new Error('Board service is closed.');
275
+ server = await bindEphemeralServer();
276
+ }
277
+ }
278
+ if (disposed) {
279
+ await new Promise((resolve) => server.close(resolve));
280
+ throw new Error('Board service is closed.');
281
+ }
282
+ try {
283
+ if (directory) {
284
+ try {
285
+ watcher = watch(directory, { recursive: true }, (_event, filename) => {
286
+ if (!filename || pathBasename(filename) === 'board.json') void publish();
287
+ });
288
+ } catch {
289
+ watcher = watch(directory, (_event, filename) => {
290
+ if (!filename || filename === 'board.json') void publish();
291
+ });
292
+ }
293
+ watcher.on('error', () =>
294
+ logger.error({ code: 'CTF_BOARD_WATCH_FAILED' }, 'Board watcher failed'),
295
+ );
296
+ }
297
+ heartbeat = setInterval(() => {
298
+ for (const entry of clients) sendClient(entry, ': heartbeat\n\n');
299
+ }, 15_000);
300
+ heartbeat.unref?.();
301
+ pollTimer = setInterval(() => {
302
+ if (clients.size > 0) void publish('__poll__');
303
+ }, 3_000);
304
+ pollTimer.unref?.();
305
+ url = `http://127.0.0.1:${server.address().port}`;
306
+ logger.info({ code: 'CTF_BOARD_STARTED', url, requestedPort: port }, 'CTF board WebUI listening');
307
+ return url;
308
+ } catch (error) {
309
+ watcher?.close();
310
+ clearInterval(heartbeat);
311
+ clearInterval(pollTimer);
312
+ await new Promise((resolve) => server.close(resolve));
313
+ throw error;
314
+ }
315
+ })().catch((error) => {
316
+ starting = undefined;
317
+ throw error;
318
+ }));
319
+ },
320
+ publish,
321
+ async dispose() {
322
+ disposed = true;
323
+ await starting?.catch(() => {});
324
+ watcher?.close();
325
+ clearInterval(heartbeat);
326
+ clearInterval(pollTimer);
327
+ for (const entry of clients) entry.res.destroy();
328
+ clients.clear();
329
+ if (server?.listening) {
330
+ const closing = new Promise((resolve) => server.close(resolve));
331
+ server.closeAllConnections();
332
+ await closing;
333
+ }
334
+ },
335
+ };
336
+ }