@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,130 @@
1
+ import { fail } from '../board.mjs';
2
+ import {
3
+ checkCaptcha,
4
+ jsonResponse,
5
+ normalizeContainerInfo,
6
+ numericId,
7
+ optionalJsonResponse,
8
+ } from './http.mjs';
9
+
10
+ function parseSubmitStatus(payload) {
11
+ const message =
12
+ typeof payload?.message === 'string' && payload.message.trim() ? payload.message.trim() : undefined;
13
+ if (typeof payload === 'boolean') return { status: payload ? 'correct' : 'incorrect' };
14
+ if (!payload || typeof payload !== 'object') {
15
+ throw fail('PLATFORM_INVALID_RESPONSE', 'Unexpected GZCTF submission response.');
16
+ }
17
+ if (payload.alreadySolved === true) return { status: 'already_solved', ...(message ? { message } : {}) };
18
+ if (payload.correct === true || payload.accepted === true || payload.isCorrect === true) {
19
+ return { status: 'correct', ...(message ? { message } : {}) };
20
+ }
21
+ if (payload.correct === false || payload.accepted === false || payload.isCorrect === false) {
22
+ return { status: 'incorrect', ...(message ? { message } : {}) };
23
+ }
24
+ const raw = payload.status ?? payload.result ?? payload.answerResult ?? payload.type;
25
+ if (typeof raw === 'boolean') {
26
+ return { status: raw ? 'correct' : 'incorrect', ...(message ? { message } : {}) };
27
+ }
28
+ if (typeof raw === 'string') {
29
+ const normalized = raw.trim().toLowerCase().replace(/[\s_-]+/g, '');
30
+ if (['accepted', 'correct', 'solved', 'success'].includes(normalized)) {
31
+ return { status: 'correct', ...(message ? { message } : {}) };
32
+ }
33
+ if (['alreadysolved', 'already', 'duplicate'].includes(normalized)) {
34
+ return { status: 'already_solved', ...(message ? { message } : {}) };
35
+ }
36
+ if (['wronganswer', 'wrong', 'incorrect', 'failed'].includes(normalized)) {
37
+ return { status: 'incorrect', ...(message ? { message } : {}) };
38
+ }
39
+ if (['ratelimited', 'paused'].includes(normalized)) {
40
+ return { status: 'rate_limited', ...(message ? { message } : {}) };
41
+ }
42
+ }
43
+ throw fail('PLATFORM_INVALID_RESPONSE', 'Unexpected GZCTF submission response.');
44
+ }
45
+
46
+ export function gzctf(transport, auth, gameId) {
47
+ const game = numericId(gameId);
48
+ const headers = auth.token ? { Authorization: `Bearer ${auth.token}` } : {};
49
+ const gamePath = `api/game/${game}`;
50
+ const data = async (resource, signal) =>
51
+ jsonResponse(await transport.request(resource, { headers, signal }));
52
+ const details = (signal) => data(`${gamePath}/Details`, signal);
53
+ return {
54
+ async connect(signal) {
55
+ if (auth.username) {
56
+ const response = await transport.request('api/account/LogIn', {
57
+ method: 'POST',
58
+ signal,
59
+ headers: { 'Content-Type': 'application/json' },
60
+ body: JSON.stringify({ userName: auth.username, password: auth.password }),
61
+ });
62
+ checkCaptcha(await response.text(), response.status);
63
+ transport.requireSession();
64
+ }
65
+ await details(signal);
66
+ },
67
+ async list(signal) {
68
+ const result = await details(signal);
69
+ if (!result?.challenges || typeof result.challenges !== 'object' || Array.isArray(result.challenges))
70
+ throw fail('PLATFORM_INVALID_RESPONSE', 'Expected a GZCTF challenge list.');
71
+ const solved = new Set(
72
+ (result.rank?.solvedChallenges ?? []).map((challenge) => numericId(challenge.id)),
73
+ );
74
+ const items = [];
75
+ for (const [category, challenges] of Object.entries(result.challenges)) {
76
+ if (!Array.isArray(challenges))
77
+ throw fail('PLATFORM_INVALID_RESPONSE', 'Expected a GZCTF category list.');
78
+ for (const item of challenges) {
79
+ const remoteId = numericId(item.id);
80
+ const detail = await data(`${gamePath}/challenges/${remoteId}`, signal);
81
+ const solves = item.acceptedCount ?? item.solves ?? detail.acceptedCount ?? detail.solves;
82
+ items.push({
83
+ id: `gzctf-${game}-${remoteId}`,
84
+ remoteId,
85
+ title: detail.title,
86
+ description: detail.content,
87
+ category,
88
+ points: detail.score,
89
+ ...(typeof solves === 'number' && Number.isSafeInteger(solves) && solves >= 0 ? { solves } : {}),
90
+ ...(typeof item.type === 'string' && /dynamic/i.test(item.type) ? { hasContainer: true } : {}),
91
+ ...(solved.has(remoteId) ? { status: 'solved' } : {}),
92
+ resources: detail.context?.url ? [transport.attachment(detail.context.url)] : [],
93
+ });
94
+ }
95
+ }
96
+ return items;
97
+ },
98
+ async instance(remoteId, action, signal) {
99
+ const id = numericId(remoteId);
100
+ let endpoint;
101
+ let method;
102
+ if (action === 'start') {
103
+ endpoint = `${gamePath}/container/${id}`;
104
+ method = 'POST';
105
+ } else if (action === 'renew') {
106
+ endpoint = `${gamePath}/container/${id}/extend`;
107
+ method = 'POST';
108
+ } else if (action === 'stop') {
109
+ endpoint = `${gamePath}/container/${id}`;
110
+ method = 'DELETE';
111
+ } else {
112
+ throw fail('INVALID_INPUT', 'Unsupported instance action.');
113
+ }
114
+ const response = await transport.request(endpoint, { method, headers, signal });
115
+ const payload = await optionalJsonResponse(response);
116
+ return normalizeContainerInfo(payload, action);
117
+ },
118
+ async submit(remoteId, answer, signal) {
119
+ const id = numericId(remoteId);
120
+ const response = await transport.request(`${gamePath}/challenges/${id}`, {
121
+ method: 'POST',
122
+ headers: { ...headers, 'Content-Type': 'application/json' },
123
+ body: JSON.stringify({ flag: answer }),
124
+ signal,
125
+ });
126
+ return parseSubmitStatus(await jsonResponse(response));
127
+ },
128
+ download: (resource, signal) => transport.download(resource, headers, signal),
129
+ };
130
+ }
@@ -0,0 +1,336 @@
1
+ import { fail, safeSegment } from '../board.mjs';
2
+
3
+ const captcha =
4
+ /(?:g-recaptcha|h-captcha|cf-turnstile|captcha.{0,24}(?:required|failed|invalid)|token\s+validation\s+failed|verify (?:that )?you are human)/i;
5
+ const redirectStatuses = new Set([301, 302, 303, 307, 308]);
6
+ const maxAttachmentBytes = 64 * 1024 * 1024;
7
+
8
+ export function createTransport(baseUrl, auth, registerSecret, fetcher = fetch) {
9
+ for (const value of [auth.token, auth.cookie, auth.password]) {
10
+ if (typeof value === 'string' && value) registerSecret(value);
11
+ }
12
+ let base;
13
+ try {
14
+ base = new URL(baseUrl);
15
+ } catch {
16
+ throw fail('PLATFORM_INVALID_URL', 'Expected a valid HTTP(S) platform URL.');
17
+ }
18
+ if (
19
+ !['http:', 'https:'].includes(base.protocol) ||
20
+ base.username ||
21
+ base.password ||
22
+ base.search ||
23
+ base.hash
24
+ )
25
+ throw fail(
26
+ 'PLATFORM_INVALID_URL',
27
+ 'Expected an HTTP(S) platform URL without embedded credentials or query.',
28
+ );
29
+ base.pathname = base.pathname.replace(/\/*$/, '/');
30
+ const cookies = new Map();
31
+ function saveCookiePart(part, cookiePath = '/') {
32
+ const at = part.indexOf('=');
33
+ if (at <= 0) return false;
34
+ const name = part.slice(0, at).trim();
35
+ const value = part.slice(at + 1).trim();
36
+ const key = `${name}\0${cookiePath}`;
37
+ if (value) {
38
+ registerSecret(value);
39
+ cookies.set(key, { name, value, path: cookiePath });
40
+ return true;
41
+ }
42
+ cookies.delete(key);
43
+ return false;
44
+ }
45
+ function saveSetCookie(header) {
46
+ const segments = header.split(';');
47
+ const first = segments[0] ?? '';
48
+ const at = first.indexOf('=');
49
+ if (at <= 0) return;
50
+ const name = first.slice(0, at).trim();
51
+ const value = first.slice(at + 1).trim();
52
+ let cookiePath = '/';
53
+ let expired = false;
54
+ for (const rawAttr of segments.slice(1)) {
55
+ const eq = rawAttr.indexOf('=');
56
+ const attrName = (eq < 0 ? rawAttr : rawAttr.slice(0, eq)).trim().toLowerCase();
57
+ const attrValue = eq < 0 ? '' : rawAttr.slice(eq + 1).trim();
58
+ if (attrName === 'path' && attrValue.startsWith('/')) {
59
+ cookiePath = attrValue;
60
+ } else if (attrName === 'max-age' && /^-?\d+$/u.test(attrValue) && Number(attrValue) <= 0) {
61
+ expired = true;
62
+ } else if (attrName === 'expires') {
63
+ const timestamp = Date.parse(attrValue);
64
+ if (Number.isFinite(timestamp) && timestamp <= Date.now()) expired = true;
65
+ }
66
+ }
67
+ const key = `${name}\0${cookiePath}`;
68
+ if (!value || expired) {
69
+ cookies.delete(key);
70
+ return;
71
+ }
72
+ registerSecret(value);
73
+ cookies.set(key, { name, value, path: cookiePath });
74
+ }
75
+ for (const part of (auth.cookie ?? '').split(';')) saveCookiePart(part);
76
+
77
+ function cookieHeaderFor(pathname) {
78
+ const reqPath = pathname || '/';
79
+ const matched = [...cookies.values()]
80
+ .filter(
81
+ ({ path: cookiePath }) =>
82
+ cookiePath === '/' ||
83
+ reqPath === cookiePath ||
84
+ (cookiePath.endsWith('/') ? reqPath.startsWith(cookiePath) : reqPath.startsWith(`${cookiePath}/`)),
85
+ )
86
+ .sort((a, b) => b.path.length - a.path.length);
87
+ const seen = new Set();
88
+ const pairs = [];
89
+ for (const entry of matched) {
90
+ if (seen.has(entry.name)) continue;
91
+ seen.add(entry.name);
92
+ pairs.push(`${entry.name}=${entry.value}`);
93
+ }
94
+ return pairs.join('; ');
95
+ }
96
+
97
+ function requireSession() {
98
+ if (!cookies.size) throw fail('PLATFORM_AUTH_FAILED', 'The platform did not issue a session cookie.');
99
+ }
100
+
101
+ async function request(url, { method = 'GET', headers, body, signal, allowLoginRedirect = false } = {}) {
102
+ const destination = url instanceof URL ? url : new URL(url, base);
103
+ if (destination.origin !== base.origin || destination.username || destination.password)
104
+ throw fail('PLATFORM_INVALID_URL', 'The platform resource must have the configured origin.');
105
+ const requestHeaders = new Headers(headers);
106
+ const cookieHeader = cookieHeaderFor(destination.pathname);
107
+ if (cookieHeader) requestHeaders.set('cookie', cookieHeader);
108
+ let response;
109
+ try {
110
+ const timeout = AbortSignal.timeout(20_000);
111
+ response = await fetcher(destination, {
112
+ method,
113
+ headers: requestHeaders,
114
+ body,
115
+ redirect: 'manual',
116
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
117
+ });
118
+ } catch {
119
+ throw fail('PLATFORM_UNREACHABLE', 'Unable to contact the platform.');
120
+ }
121
+ for (const header of response.headers.getSetCookie()) {
122
+ registerSecret(header);
123
+ saveSetCookie(header);
124
+ }
125
+ if (response.ok) return response;
126
+ if (allowLoginRedirect && [302, 303].includes(response.status)) {
127
+ const location = response.headers.get('location');
128
+ const target = location ? new URL(location, destination) : undefined;
129
+ await response.body?.cancel();
130
+ if (target?.origin === base.origin && target.pathname !== destination.pathname) return response;
131
+ throw fail('PLATFORM_AUTH_FAILED', 'Unexpected login redirect.');
132
+ }
133
+ if (redirectStatuses.has(response.status)) {
134
+ await response.body?.cancel();
135
+ throw fail('PLATFORM_REDIRECT', 'Unexpected redirect. Check the configured URL and session cookie.');
136
+ }
137
+ const text = [400, 401, 403, 429, 451, 503].includes(response.status)
138
+ ? await response.text()
139
+ : (await response.body?.cancel(), '');
140
+ checkCaptcha(text, response.status);
141
+ const message =
142
+ response.status === 451
143
+ ? 'Platform request returned HTTP 451 (access restricted or account blocked by platform; do NOT retry—stop platform calls and report immediately).'
144
+ : response.status === 401
145
+ ? 'Platform request returned HTTP 401 (authentication rejected; do NOT retry blindly without fresh credentials).'
146
+ : response.status === 403
147
+ ? 'Platform request returned HTTP 403 (forbidden; do NOT retry blindly).'
148
+ : `Platform request returned HTTP ${response.status}.`;
149
+ throw Object.assign(
150
+ fail(response.status === 401 ? 'PLATFORM_AUTH_FAILED' : 'PLATFORM_HTTP_ERROR', message),
151
+ { status: response.status, ...(text ? { responseText: text } : {}) },
152
+ );
153
+ }
154
+
155
+ function attachment(location, preferredName) {
156
+ if (typeof location !== 'string' || !location || /[\\\u0000-\u0020]/u.test(location))
157
+ throw fail('INVALID_PATH', 'Invalid attachment URL.');
158
+ const rawPath = location.split(/[?#]/u, 1)[0].replace(/^https?:\/\/[^/]+/iu, '');
159
+ const parts = rawPath.split('/').filter(Boolean);
160
+ let name;
161
+ try {
162
+ for (const part of parts) name = safeSegment(decodeURIComponent(part));
163
+ } catch {
164
+ throw fail('INVALID_PATH', 'Invalid attachment path.');
165
+ }
166
+ if (typeof preferredName === 'string' && preferredName.trim()) {
167
+ try {
168
+ name = safeSegment(preferredName.trim());
169
+ } catch {
170
+ // Keep the validated URL segment when the display name is not a portable filename.
171
+ }
172
+ }
173
+ const url = new URL(location, base);
174
+ if (!name || url.origin !== base.origin || url.username || url.password)
175
+ throw fail('INVALID_PATH', 'Expected a named attachment on the configured platform origin.');
176
+ return { name, url };
177
+ }
178
+
179
+ async function download(resource, headers, signal, { method = 'GET', body } = {}) {
180
+ const response = await request(resource.url, { method, headers, body, signal });
181
+ const bytes = [];
182
+ let size = 0;
183
+ const reader = response.body?.getReader();
184
+ if (!reader) throw fail('PLATFORM_INVALID_RESPONSE', 'Missing attachment body.');
185
+ try {
186
+ while (true) {
187
+ const { done, value } = await reader.read();
188
+ if (done) break;
189
+ size += value.byteLength;
190
+ if (size > maxAttachmentBytes) throw fail('PLATFORM_ATTACHMENT_LIMIT', 'Attachment exceeds 64 MiB.');
191
+ bytes.push(value);
192
+ }
193
+ return Buffer.concat(bytes, size);
194
+ } finally {
195
+ await reader.cancel().catch(() => {});
196
+ }
197
+ }
198
+
199
+ return { request, requireSession, attachment, download };
200
+ }
201
+
202
+ export function checkCaptcha(text, status) {
203
+ if ([403, 429].includes(status) || captcha.test(text))
204
+ throw fail(
205
+ 'PLATFORM_CAPTCHA_REQUIRED',
206
+ 'The platform requested verification. Use a valid Cookie or Token.',
207
+ );
208
+ }
209
+
210
+ export async function jsonResponse(response) {
211
+ const text = await response.text();
212
+ try {
213
+ return JSON.parse(text);
214
+ } catch {
215
+ checkCaptcha(text, response.status);
216
+ throw fail('PLATFORM_INVALID_RESPONSE', 'The platform did not return JSON.');
217
+ }
218
+ }
219
+
220
+ export async function optionalJsonResponse(response) {
221
+ const text = await response.text();
222
+ if (!text.trim()) return undefined;
223
+ try {
224
+ return JSON.parse(text);
225
+ } catch {
226
+ checkCaptcha(text, response.status);
227
+ throw fail('PLATFORM_INVALID_RESPONSE', 'The platform did not return JSON.');
228
+ }
229
+ }
230
+
231
+ function parseEntryEndpoint(entry) {
232
+ if (typeof entry !== 'string' || !entry.trim()) return {};
233
+ const trimmed = entry.trim();
234
+ if (/^https?:\/\//iu.test(trimmed)) {
235
+ try {
236
+ const parsed = new URL(trimmed);
237
+ const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'https:' ? 443 : 80;
238
+ return {
239
+ ...(parsed.hostname ? { host: parsed.hostname } : {}),
240
+ ...(Number.isSafeInteger(port) && port >= 1 && port <= 65535 ? { port } : {}),
241
+ };
242
+ } catch {
243
+ return {};
244
+ }
245
+ }
246
+ const match = /^(?:nc\s+)?(\[[0-9a-fA-F:]+\]|[a-zA-Z0-9._-]+)(?::|\s+)(\d{1,5})\b/u.exec(trimmed);
247
+ if (!match) return {};
248
+ const port = Number(match[2]);
249
+ return {
250
+ host: match[1].replace(/^\[|\]$/g, ''),
251
+ ...(Number.isSafeInteger(port) && port >= 1 && port <= 65535 ? { port } : {}),
252
+ };
253
+ }
254
+
255
+ function normalizeExpiresAt(value) {
256
+ if (typeof value === 'number' && Number.isFinite(value)) {
257
+ const ms = value < 1e12 ? value * 1000 : value;
258
+ return new Date(ms).toISOString();
259
+ }
260
+ if (typeof value === 'string' && value.trim()) {
261
+ const trimmed = value.trim();
262
+ if (/^\d+(?:\.\d+)?$/u.test(trimmed)) {
263
+ const num = Number(trimmed);
264
+ if (Number.isFinite(num)) {
265
+ const ms = num < 1e12 ? num * 1000 : num;
266
+ return new Date(ms).toISOString();
267
+ }
268
+ }
269
+ const parsed = Date.parse(trimmed);
270
+ if (Number.isFinite(parsed)) return new Date(parsed).toISOString();
271
+ }
272
+ return undefined;
273
+ }
274
+
275
+ export function normalizeContainerInfo(payload, action) {
276
+ if (action === 'stop') {
277
+ return { supported: true, action: 'stop', active: false };
278
+ }
279
+ let raw = payload && typeof payload === 'object' ? payload : undefined;
280
+ if (raw && typeof raw.data === 'object' && raw.data !== null) raw = raw.data;
281
+ if (raw && typeof raw.container === 'object' && raw.container !== null) raw = raw.container;
282
+ if (raw && typeof raw.result === 'object' && raw.result !== null) raw = raw.result;
283
+
284
+ const entryRaw = [raw?.entry, raw?.url, raw?.address, raw?.connect].find(
285
+ (value) => typeof value === 'string' && value.trim().length > 0,
286
+ );
287
+ let entry = entryRaw?.trim();
288
+ const hostRaw = [raw?.host, raw?.ip, raw?.hostname, raw?.domain].find(
289
+ (value) => typeof value === 'string' && value.trim().length > 0,
290
+ );
291
+ let host = hostRaw?.trim();
292
+ let port;
293
+ if (typeof raw?.port === 'number' && Number.isSafeInteger(raw.port) && raw.port >= 1 && raw.port <= 65535) {
294
+ port = raw.port;
295
+ } else if (typeof raw?.port === 'string' && /^\d{1,5}$/u.test(raw.port.trim())) {
296
+ const parsedPort = Number(raw.port.trim());
297
+ if (parsedPort >= 1 && parsedPort <= 65535) port = parsedPort;
298
+ }
299
+
300
+ if (entry && (!host || port === undefined)) {
301
+ const parsed = parseEntryEndpoint(entry);
302
+ host ??= parsed.host;
303
+ port ??= parsed.port;
304
+ }
305
+ if (!entry && host && port !== undefined) {
306
+ entry = `${host}:${port}`;
307
+ }
308
+ const expiresAt = normalizeExpiresAt(
309
+ raw?.expectStopAt ?? raw?.expiresAt ?? raw?.expireTime ?? raw?.expiredAt ?? raw?.expires_at ?? raw?.exp,
310
+ );
311
+
312
+ return {
313
+ supported: true,
314
+ action,
315
+ active: true,
316
+ ...(host ? { host } : {}),
317
+ ...(port !== undefined ? { port } : {}),
318
+ ...(entry ? { entry } : {}),
319
+ ...(expiresAt ? { expiresAt } : {}),
320
+ };
321
+ }
322
+
323
+ export function isContainerAlreadyGoneError(error) {
324
+ if (!error || error.code !== 'PLATFORM_HTTP_ERROR') return false;
325
+ if (error.status === 404) return true;
326
+ const msg = String(error.apiMsg ?? error.message ?? '');
327
+ return /未找到|不存在|未启动|已关闭|已销毁|not\s*found|no\s*(?:running|active)?\s*container|not\s*running/i.test(
328
+ msg,
329
+ );
330
+ }
331
+
332
+ export function numericId(value) {
333
+ if (!/^\d+$/u.test(String(value)) || !Number.isSafeInteger(Number(value)) || Number(value) < 1)
334
+ throw fail('PLATFORM_INVALID_RESPONSE', 'Expected a positive numeric platform ID.');
335
+ return String(Number(value));
336
+ }
@@ -0,0 +1,133 @@
1
+ import path from 'node:path';
2
+ import { atomicWrite, checkedDirectory, fail, safeSegment } from '../board.mjs';
3
+ import { ctfd } from './ctfd.mjs';
4
+ import { ctfplus } from './ctfplus.mjs';
5
+ import { gzctf } from './gzctf.mjs';
6
+ import { createTransport, numericId } from './http.mjs';
7
+ export { isContainerAlreadyGoneError } from './http.mjs';
8
+ export { createInstanceLeaseManager } from './lease.mjs';
9
+
10
+ /**
11
+ * @typedef {object} PlatformAdapter
12
+ * @property {(signal: AbortSignal) => Promise<void>} connect
13
+ * @property {(signal: AbortSignal, options?: object) => Promise<object[]>} list
14
+ * @property {(signal: AbortSignal) => Promise<object | undefined>} [metadata]
15
+ * @property {(remoteId: string, action: 'start' | 'stop' | 'renew', signal: AbortSignal) => Promise<object>} instance
16
+ * @property {(remoteId: string, answer: string, signal: AbortSignal) => Promise<object>} submit
17
+ * @property {(resource: {name: string, url: URL}, signal: AbortSignal) => Promise<Buffer>} download
18
+ */
19
+
20
+ export function resolveRemoteChallengeId(challenge, connection) {
21
+ if (!challenge.platform || challenge.platform !== connection.platform) {
22
+ throw fail(
23
+ 'PLATFORM_MISMATCH',
24
+ `Challenge "${challenge.id}" is not bound to platform "${connection.platform}".`,
25
+ );
26
+ }
27
+ if (connection.platform === 'ctfd') {
28
+ const match = /^ctfd-(\d+)$/u.exec(challenge.id);
29
+ return numericId(challenge.remoteId ?? match?.[1]);
30
+ }
31
+ if (connection.platform === 'gzctf') {
32
+ const match = /^gzctf-(\d+)-(\d+)$/u.exec(challenge.id);
33
+ if (match && connection.gameId !== undefined && match[1] !== String(connection.gameId)) {
34
+ throw fail('PLATFORM_MISMATCH', `Challenge "${challenge.id}" belongs to a different GZCTF game.`);
35
+ }
36
+ return numericId(challenge.remoteId ?? match?.[2]);
37
+ }
38
+ if (connection.platform === 'ctfplus') {
39
+ const match = /^ctfplus-(\d+)$/u.exec(challenge.id);
40
+ return numericId(challenge.remoteId ?? match?.[1]);
41
+ }
42
+ throw fail('PLATFORM_INVALID_TYPE', 'Unsupported competition platform.');
43
+ }
44
+
45
+ /** @returns {PlatformAdapter} */
46
+ export function platformAdapter({ platform, baseUrl, auth, gameId, portalBaseUrl }, registerSecret, fetcher) {
47
+ const transport = createTransport(baseUrl, auth, registerSecret, fetcher);
48
+ const credentials = [auth.token, auth.cookie, auth.username && auth.password].filter(Boolean);
49
+ if (credentials.length !== 1 || Boolean(auth.username) !== Boolean(auth.password))
50
+ throw fail('PLATFORM_INVALID_AUTH', 'Supply a token, cookie, or username and password.');
51
+ if (platform === 'ctfd') return ctfd(transport, auth);
52
+ if (platform === 'gzctf') {
53
+ if (!gameId) throw fail('PLATFORM_GAME_REQUIRED', 'GZCTF requires a game ID.');
54
+ return gzctf(transport, auth, gameId);
55
+ }
56
+ if (platform === 'ctfplus') {
57
+ return ctfplus(transport, auth, { baseUrl, gameId, portalBaseUrl, registerSecret, fetcher });
58
+ }
59
+ throw fail('PLATFORM_INVALID_TYPE', 'Unsupported competition platform.');
60
+ }
61
+
62
+ const SYNC_CONCURRENCY = 4;
63
+
64
+ export async function syncPlatform(adapter, platform, board, redact, signal, options = {}) {
65
+ const meta = await adapter.metadata?.(signal).catch(() => undefined);
66
+ const listOptions = options.challengeIds ? { challengeIds: options.challengeIds } : undefined;
67
+ const allItems = await adapter.list(signal, listOptions);
68
+ const categorySet =
69
+ Array.isArray(options.categories) && options.categories.length
70
+ ? new Set(options.categories.map((cat) => String(cat).trim().toLowerCase()).filter(Boolean))
71
+ : undefined;
72
+ const items = categorySet
73
+ ? allItems.filter((item) => {
74
+ const candidates = [item.category, ...(Array.isArray(item.tags) ? item.tags : [])];
75
+ return candidates.some(
76
+ (value) => typeof value === 'string' && value.trim() && categorySet.has(value.trim().toLowerCase()),
77
+ );
78
+ })
79
+ : allItems;
80
+ const downloadAttachments = options.downloadAttachments !== false;
81
+ const merged = new Array(items.length);
82
+ let downloadedAttachments = 0;
83
+ let cursor = 0;
84
+
85
+ const targetRoot = (await board.ensureAssetsRoot?.()) ?? board.assetsRoot ?? board.root;
86
+
87
+ async function processItem() {
88
+ while (cursor < items.length) {
89
+ const index = cursor++;
90
+ signal.throwIfAborted();
91
+ const { resources, ...item } = items[index];
92
+ if (typeof item.title !== 'string' || typeof item.description !== 'string')
93
+ throw fail('PLATFORM_INVALID_RESPONSE', 'Invalid challenge title or description.');
94
+ const names = new Set();
95
+ for (const resource of resources) {
96
+ const name = safeSegment(resource.name).normalize('NFC').toLowerCase();
97
+ if (names.has(name)) throw fail('INVALID_PATH', 'Duplicate attachment names in a challenge.');
98
+ names.add(name);
99
+ }
100
+ const directory = await checkedDirectory(targetRoot, [item.id], true);
101
+ const descriptionFile = 'platform-description.md';
102
+ await atomicWrite(path.join(directory, descriptionFile), redact(item.description));
103
+ const attachments = [];
104
+ if (resources.length && downloadAttachments) {
105
+ const attachmentDirectory = await checkedDirectory(directory, ['attachments'], true);
106
+ for (const resource of resources) {
107
+ const bytes = await adapter.download(resource, signal);
108
+ await atomicWrite(path.join(attachmentDirectory, resource.name), bytes);
109
+ attachments.push('attachments/' + resource.name);
110
+ downloadedAttachments += 1;
111
+ }
112
+ }
113
+ merged[index] = { ...item, descriptionFile, attachments, platform, workSubpath: item.id };
114
+ }
115
+ }
116
+
117
+ const workerCount = Math.min(SYNC_CONCURRENCY, items.length);
118
+ if (workerCount > 0) {
119
+ await Promise.all(Array.from({ length: workerCount }, () => processItem()));
120
+ }
121
+
122
+ if (meta && Object.keys(meta).length) {
123
+ await board.change((current) => {
124
+ Object.assign(current.metadata, meta);
125
+ });
126
+ }
127
+ const snapshot = await board.merge(merged);
128
+ return {
129
+ snapshot,
130
+ syncedSubpaths: merged.map((entry) => entry.workSubpath),
131
+ downloadedAttachments,
132
+ };
133
+ }