@saturn-universe/runtime-host 0.0.0-stage → 0.1.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.
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 +472 -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 +471 -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,769 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { fail, safeSegment } from '../board.mjs';
3
+ import {
4
+ checkCaptcha,
5
+ createTransport,
6
+ isContainerAlreadyGoneError,
7
+ jsonResponse,
8
+ normalizeContainerInfo,
9
+ numericId,
10
+ } from './http.mjs';
11
+
12
+ const KNOWN_CATEGORIES = new Set([
13
+ 'web',
14
+ 'misc',
15
+ 'reverse',
16
+ 'pwn',
17
+ 'crypto',
18
+ 'ai安全',
19
+ 'ai',
20
+ 'mobile',
21
+ 'forensics',
22
+ 'iot',
23
+ 'blockchain',
24
+ 'osint',
25
+ 'hardware',
26
+ 'cloud',
27
+ 'awdp',
28
+ 'pentest',
29
+ ]);
30
+
31
+ const DETAIL_CONCURRENCY = 6;
32
+
33
+ function unwrapEnvelope(payload, fallbackMsg) {
34
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
35
+ throw fail('PLATFORM_INVALID_RESPONSE', fallbackMsg);
36
+ }
37
+ if ('code' in payload && payload.code !== 200) {
38
+ const msg =
39
+ typeof payload.msg === 'string' && payload.msg.trim()
40
+ ? payload.msg.trim()
41
+ : typeof payload.message === 'string' && payload.message.trim()
42
+ ? payload.message.trim()
43
+ : fallbackMsg;
44
+ if (payload.code === 401) throw fail('PLATFORM_AUTH_FAILED', msg);
45
+ checkCaptcha(msg, payload.code);
46
+ throw Object.assign(fail('PLATFORM_HTTP_ERROR', msg), {
47
+ status: payload.code,
48
+ apiCode: payload.code,
49
+ apiMsg: msg,
50
+ });
51
+ }
52
+ return 'data' in payload ? payload.data : payload;
53
+ }
54
+
55
+ function renderInline(nodes) {
56
+ if (!Array.isArray(nodes)) return '';
57
+ return nodes
58
+ .map((node) => {
59
+ if (!node || typeof node !== 'object') return '';
60
+ if (node.type === 'text') return String(node.text ?? '');
61
+ if (node.type === 'hardBreak') return '\n';
62
+ if (node.content) return renderInline(node.content);
63
+ return '';
64
+ })
65
+ .join('');
66
+ }
67
+
68
+ function renderRichNodes(nodes) {
69
+ if (!Array.isArray(nodes)) return [];
70
+ const blocks = [];
71
+ for (const node of nodes) {
72
+ if (!node || typeof node !== 'object') continue;
73
+ if (node.type === 'paragraph') {
74
+ const line = renderInline(node.content).trim();
75
+ if (line) blocks.push(line);
76
+ } else if (node.type === 'heading') {
77
+ const level = Math.min(6, Math.max(1, Number(node.attrs?.level ?? 2) || 2));
78
+ const line = renderInline(node.content).trim();
79
+ if (line) blocks.push(`${'#'.repeat(level)} ${line}`);
80
+ } else if (node.type === 'codeBlock') {
81
+ const lang = typeof node.attrs?.language === 'string' ? node.attrs.language : '';
82
+ const code = renderInline(node.content);
83
+ blocks.push(`\`\`\`${lang}\n${code}\n\`\`\``);
84
+ } else if (node.type === 'bulletList' || node.type === 'orderedList') {
85
+ const items = Array.isArray(node.content) ? node.content : [];
86
+ const lines = items
87
+ .map((item, idx) => {
88
+ const text = renderRichNodes(item.content).join('\n').trim();
89
+ if (!text) return '';
90
+ return node.type === 'orderedList' ? `${idx + 1}. ${text}` : `- ${text}`;
91
+ })
92
+ .filter(Boolean);
93
+ if (lines.length) blocks.push(lines.join('\n'));
94
+ } else if (node.type === 'blockquote') {
95
+ const inner = renderRichNodes(node.content)
96
+ .join('\n')
97
+ .split('\n')
98
+ .map((line) => `> ${line}`)
99
+ .join('\n');
100
+ if (inner) blocks.push(inner);
101
+ } else if (node.content) {
102
+ const nested = renderRichNodes(node.content).join('\n\n').trim();
103
+ if (nested) blocks.push(nested);
104
+ } else if (typeof node.text === 'string' && node.text.trim()) {
105
+ blocks.push(node.text.trim());
106
+ }
107
+ }
108
+ return blocks;
109
+ }
110
+
111
+ export function extractRichText(raw) {
112
+ if (typeof raw !== 'string') return '';
113
+ const trimmed = raw.trim();
114
+ if (!trimmed) return '';
115
+ if (trimmed.startsWith('{')) {
116
+ try {
117
+ const parsed = JSON.parse(trimmed);
118
+ if (parsed && typeof parsed === 'object' && parsed.type === 'doc') {
119
+ const rendered = renderRichNodes(parsed.content).join('\n\n').trim();
120
+ return rendered || trimmed;
121
+ }
122
+ } catch {
123
+ // Plain text that starts with '{'
124
+ }
125
+ }
126
+ return trimmed;
127
+ }
128
+
129
+ function pickCategory(tags) {
130
+ if (!Array.isArray(tags) || !tags.length) return 'Misc';
131
+ const visible = tags
132
+ .filter((tag) => tag && !tag.is_hidden && typeof tag.tag_name === 'string' && tag.tag_name.trim())
133
+ .map((tag) => tag.tag_name.trim());
134
+ const candidates = visible.length
135
+ ? visible
136
+ : tags
137
+ .filter((tag) => tag && typeof tag.tag_name === 'string' && tag.tag_name.trim())
138
+ .map((tag) => tag.tag_name.trim());
139
+ const known = candidates.find((name) => KNOWN_CATEGORIES.has(name.toLowerCase()));
140
+ if (known) return known;
141
+ const nonWeek = candidates.find((name) => !/^week\s*\d+$/iu.test(name));
142
+ return nonWeek ?? candidates[0] ?? 'Misc';
143
+ }
144
+
145
+ function parseNonNegativeInt(value) {
146
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value;
147
+ if (typeof value === 'string' && /^\d+$/u.test(value.trim())) {
148
+ const parsed = Number(value.trim());
149
+ if (Number.isSafeInteger(parsed) && parsed >= 0) return parsed;
150
+ }
151
+ return undefined;
152
+ }
153
+
154
+ function extractVisibleTags(tags) {
155
+ if (!Array.isArray(tags)) return [];
156
+ const seen = new Set();
157
+ const out = [];
158
+ for (const tag of tags) {
159
+ if (!tag || tag.is_hidden || typeof tag.tag_name !== 'string') continue;
160
+ const name = tag.tag_name.trim();
161
+ if (!name || seen.has(name)) continue;
162
+ seen.add(name);
163
+ out.push(name);
164
+ }
165
+ return out;
166
+ }
167
+
168
+ function normalizeDifficulty(value) {
169
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
170
+ if (typeof value === 'string' && value.trim()) return value.trim();
171
+ return undefined;
172
+ }
173
+
174
+ function normalizeAttachmentPath(rawPath) {
175
+ if (typeof rawPath !== 'string' || !rawPath.trim() || /[\\\u0000-\u0020]/u.test(rawPath)) {
176
+ throw fail('INVALID_PATH', 'Invalid CTF Plus attachment path.');
177
+ }
178
+ const clean = rawPath
179
+ .trim()
180
+ .replace(/^\/?api\/file\/?/iu, '')
181
+ .replace(/^\/?file\/?/iu, '')
182
+ .replace(/^\/+/u, '');
183
+ if (!clean || clean.split('/').some((part) => part === '..' || part === '.')) {
184
+ throw fail('INVALID_PATH', 'Invalid CTF Plus attachment path.');
185
+ }
186
+ return `api/file/${clean}`;
187
+ }
188
+
189
+ function toIsoTimestamp(value) {
190
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined;
191
+ const ms = value < 1e12 ? value * 1000 : value;
192
+ return new Date(ms).toISOString();
193
+ }
194
+
195
+ function resolvePortalBaseUrl(baseUrl, explicitPortalUrl) {
196
+ if (typeof explicitPortalUrl === 'string' && explicitPortalUrl.trim()) {
197
+ return explicitPortalUrl.trim();
198
+ }
199
+ const parsed = new URL(baseUrl);
200
+ if (parsed.hostname.endsWith('.ctfplus.cn') && parsed.hostname !== 'www.ctfplus.cn') {
201
+ return 'https://www.ctfplus.cn';
202
+ }
203
+ return baseUrl;
204
+ }
205
+
206
+ function discoverSubdomain(baseUrl) {
207
+ const host = new URL(baseUrl).hostname.toLowerCase();
208
+ const playMatch = /^([a-z0-9-]+)\.play\.ctfplus\.cn$/u.exec(host);
209
+ if (playMatch) return playMatch[1];
210
+ const nodeMatch = /^([a-z0-9-]+)\.ctfplus\.cn$/u.exec(host);
211
+ if (nodeMatch && nodeMatch[1] !== 'www') return nodeMatch[1];
212
+ return undefined;
213
+ }
214
+
215
+ async function runBounded(items, concurrency, worker) {
216
+ const results = new Array(items.length);
217
+ let cursor = 0;
218
+ async function next() {
219
+ while (cursor < items.length) {
220
+ const index = cursor++;
221
+ results[index] = await worker(items[index], index);
222
+ }
223
+ }
224
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => next());
225
+ await Promise.all(workers);
226
+ return results;
227
+ }
228
+
229
+ function parseSubmitMessage(msg, alreadySolved = false) {
230
+ const text = typeof msg === 'string' && msg.trim() ? msg.trim() : undefined;
231
+ const lower = (text ?? '').toLowerCase();
232
+ if (
233
+ alreadySolved ||
234
+ /already|已解出|重复解出|请勿重复提交|已经解决|通过该题/u.test(lower)
235
+ ) {
236
+ return { status: 'already_solved', ...(text ? { message: text } : {}) };
237
+ }
238
+ if (/rate|limit|频繁|冷却|稍后|too fast|cooldown/u.test(lower)) {
239
+ return { status: 'rate_limited', ...(text ? { message: text } : {}) };
240
+ }
241
+ return { status: 'incorrect', ...(text ? { message: text } : {}) };
242
+ }
243
+
244
+ function normalizeStartContainer(data, action) {
245
+ const endpoints =
246
+ typeof data?.address === 'string'
247
+ ? data.address
248
+ .split(',')
249
+ .map((part) => part.trim())
250
+ .filter(Boolean)
251
+ : [];
252
+ const rawAddress = endpoints[0] ?? '';
253
+ const restTime = Number(data?.rest_time ?? data?.restTime ?? 0);
254
+ const expiresAt =
255
+ Number.isFinite(restTime) && restTime > 0
256
+ ? new Date(Date.now() + restTime * 1000).toISOString()
257
+ : toIsoTimestamp(Number(data?.container_delete_time ?? data?.expiresAt ?? 0));
258
+ const normalized = normalizeContainerInfo(
259
+ {
260
+ ...(rawAddress ? { entry: rawAddress } : {}),
261
+ ...(expiresAt ? { expiresAt } : {}),
262
+ },
263
+ action,
264
+ );
265
+ return endpoints.length > 1 ? { ...normalized, endpoints } : normalized;
266
+ }
267
+
268
+ function buildSyncedChallengeMeta(detail, item, withActiveAddress = false) {
269
+ const solves = parseNonNegativeInt(detail?.sum_solves ?? detail?.solves ?? item.sum_solves ?? item.solves);
270
+ const difficulty = normalizeDifficulty(detail?.difficulty ?? item.difficulty);
271
+ const runtimeRaw = detail?.runtimeMode ?? item.runtimeMode;
272
+ const runtimeMode = typeof runtimeRaw === 'string' && runtimeRaw.trim() ? runtimeRaw.trim() : undefined;
273
+ const hasContainer = Boolean(
274
+ detail?.is_docker === true || runtimeMode === 'docker' || detail?.hasContainer === true,
275
+ );
276
+ const tags = extractVisibleTags(detail?.tags ?? item.tags);
277
+ const locked = item.stage_locked === true;
278
+ const lockedReason =
279
+ typeof item.locked_reason === 'string' && item.locked_reason.trim() ? item.locked_reason.trim() : undefined;
280
+ let connection;
281
+ if (withActiveAddress && typeof detail?.address === 'string' && detail.address.trim()) {
282
+ const info = normalizeStartContainer(detail, 'start');
283
+ connection = {
284
+ active: true,
285
+ ...(info.host ? { host: info.host } : {}),
286
+ ...(info.port !== undefined ? { port: info.port } : {}),
287
+ ...(info.entry ? { entry: info.entry } : {}),
288
+ ...(info.expiresAt ? { expiresAt: info.expiresAt } : {}),
289
+ updatedAt: new Date().toISOString(),
290
+ };
291
+ }
292
+ return {
293
+ ...(solves !== undefined ? { solves } : {}),
294
+ ...(difficulty !== undefined ? { difficulty } : {}),
295
+ ...(runtimeMode ? { runtimeMode } : {}),
296
+ hasContainer,
297
+ ...(tags.length ? { tags } : {}),
298
+ ...(locked ? { locked: true, ...(lockedReason ? { lockedReason } : {}) } : {}),
299
+ ...(connection ? { connection } : {}),
300
+ };
301
+ }
302
+
303
+ export function ctfplus(transport, auth, options = {}) {
304
+ const { baseUrl, gameId, portalBaseUrl, registerSecret = () => {}, fetcher } = options;
305
+ let mode = 'web';
306
+ const agentHeaders = auth.token ? { Authorization: `Bearer ${auth.token}` } : {};
307
+
308
+ async function apiJson(targetTransport, resource, { method = 'GET', headers = {}, body, signal } = {}) {
309
+ const response = await targetTransport.request(resource, {
310
+ method,
311
+ headers: body !== undefined ? { 'Content-Type': 'application/json', ...headers } : headers,
312
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
313
+ signal,
314
+ });
315
+ return unwrapEnvelope(await jsonResponse(response), `CTF Plus returned an invalid response for ${resource}.`);
316
+ }
317
+
318
+ async function resolveCompetitionId(portal, portalHeaders, signal) {
319
+ if (gameId !== undefined) return String(gameId);
320
+ const slug = discoverSubdomain(baseUrl);
321
+ const endpoints = [
322
+ ['api/competition/getMyJoinedCompetitionList', { page: { page: 1, size: 50 } }],
323
+ ['api/competition/getMyCreatedCompetitionList', { page: { page: 1, size: 50 } }],
324
+ ['api/competition/getMyManagedCompetitionList', { page: { page: 1, size: 50 } }],
325
+ ];
326
+ const allCompetitions = [];
327
+ for (const [endpoint, body] of endpoints) {
328
+ try {
329
+ const data = await apiJson(portal, endpoint, {
330
+ method: 'POST',
331
+ headers: portalHeaders,
332
+ body,
333
+ signal,
334
+ });
335
+ const list = Array.isArray(data?.competitions) ? data.competitions : [];
336
+ for (const comp of list) allCompetitions.push(comp);
337
+ if (slug) {
338
+ const matched = list.find(
339
+ (comp) => typeof comp?.shortName === 'string' && comp.shortName.toLowerCase() === slug,
340
+ );
341
+ if (matched?.id !== undefined) return String(matched.id);
342
+ }
343
+ } catch (error) {
344
+ if (error.code === 'PLATFORM_AUTH_FAILED' || error.code === 'PLATFORM_CAPTCHA_REQUIRED') throw error;
345
+ }
346
+ }
347
+ if (allCompetitions.length === 1 && allCompetitions[0]?.id !== undefined) {
348
+ return String(allCompetitions[0].id);
349
+ }
350
+ throw fail(
351
+ 'PLATFORM_GAME_REQUIRED',
352
+ 'Unable to resolve CTF Plus competition ID for this host; provide gameId.',
353
+ );
354
+ }
355
+
356
+ async function connectViaPortalToken(portal, mainToken, signal) {
357
+ registerSecret(mainToken);
358
+ const portalHeaders = { Authorization: mainToken };
359
+ const competitionId = await resolveCompetitionId(portal, portalHeaders, signal);
360
+ const ticketData = await apiJson(portal, 'api/user/generateTmpLoginVerifyToken', {
361
+ method: 'POST',
362
+ headers: portalHeaders,
363
+ body: { competitionId },
364
+ signal,
365
+ });
366
+ const ticket = ticketData?.token;
367
+ if (typeof ticket !== 'string' || !ticket.trim()) {
368
+ throw fail('PLATFORM_AUTH_FAILED', 'CTF Plus did not issue a competition SSO ticket.');
369
+ }
370
+ registerSecret(ticket);
371
+ const baseData = await apiJson(transport, `api/user/getBase?token=${encodeURIComponent(ticket)}`, { signal });
372
+ if (typeof baseData?.token === 'string' && baseData.token) registerSecret(baseData.token);
373
+ transport.requireSession();
374
+ mode = 'web';
375
+ }
376
+
377
+ async function inspectContainerEntry(remoteId, action, signal) {
378
+ const data = await apiJson(transport, 'api/challenge/userGetContainerList', { signal });
379
+ const list = Array.isArray(data?.containers) ? data.containers : [];
380
+ const match = list.find((item) => String(item?.challenge_id ?? '') === String(remoteId));
381
+ if (!match) {
382
+ return normalizeContainerInfo({}, action);
383
+ }
384
+ return normalizeStartContainer(match, action);
385
+ }
386
+
387
+ return {
388
+ async connect(signal) {
389
+ if (auth.username) {
390
+ const portal = createTransport(
391
+ resolvePortalBaseUrl(baseUrl, portalBaseUrl),
392
+ { username: auth.username, password: auth.password },
393
+ registerSecret,
394
+ fetcher,
395
+ );
396
+ try {
397
+ const version = await apiJson(portal, 'api/home/getPlatformVersion', { signal });
398
+ if (version?.captchaRequired) {
399
+ throw fail(
400
+ 'PLATFORM_CAPTCHA_REQUIRED',
401
+ 'CTF Plus login requires graphical CAPTCHA. Use a valid Cookie or Token.',
402
+ );
403
+ }
404
+ } catch (error) {
405
+ if (error.code === 'PLATFORM_CAPTCHA_REQUIRED') throw error;
406
+ }
407
+ let loginData;
408
+ try {
409
+ loginData = await apiJson(portal, 'api/user/userLogin', {
410
+ method: 'POST',
411
+ body: { account: auth.username, passWord: auth.password },
412
+ signal,
413
+ });
414
+ } catch (error) {
415
+ if (/图形验证码|captcha/iu.test(String(error.message ?? ''))) {
416
+ throw fail(
417
+ 'PLATFORM_CAPTCHA_REQUIRED',
418
+ 'CTF Plus login requires graphical CAPTCHA. Use a valid Cookie or Token.',
419
+ );
420
+ }
421
+ throw error;
422
+ }
423
+ if (typeof loginData?.token !== 'string' || !loginData.token.trim()) {
424
+ throw fail('PLATFORM_AUTH_FAILED', 'CTF Plus login did not return a session token.');
425
+ }
426
+ await connectViaPortalToken(portal, loginData.token, signal);
427
+ return;
428
+ }
429
+
430
+ if (auth.cookie) {
431
+ const baseData = await apiJson(transport, 'api/user/getBase', { signal });
432
+ if (typeof baseData?.token === 'string' && baseData.token) registerSecret(baseData.token);
433
+ mode = 'web';
434
+ return;
435
+ }
436
+
437
+ if (auth.token) {
438
+ try {
439
+ await apiJson(transport, 'api/agent/v1/challenges/list', {
440
+ method: 'POST',
441
+ headers: agentHeaders,
442
+ body: {},
443
+ signal,
444
+ });
445
+ mode = 'agent';
446
+ return;
447
+ } catch (error) {
448
+ if (error.code === 'PLATFORM_CAPTCHA_REQUIRED') throw error;
449
+ }
450
+
451
+ try {
452
+ const baseData = await apiJson(transport, `api/user/getBase?token=${encodeURIComponent(auth.token)}`, {
453
+ signal,
454
+ });
455
+ if (typeof baseData?.token === 'string' && baseData.token) registerSecret(baseData.token);
456
+ transport.requireSession();
457
+ mode = 'web';
458
+ return;
459
+ } catch {
460
+ // Fall back to treating auth.token as a main-portal token.
461
+ }
462
+
463
+ const portal = createTransport(
464
+ resolvePortalBaseUrl(baseUrl, portalBaseUrl),
465
+ { token: auth.token },
466
+ registerSecret,
467
+ fetcher,
468
+ );
469
+ await connectViaPortalToken(portal, auth.token, signal);
470
+ }
471
+ },
472
+
473
+ async metadata(signal) {
474
+ if (mode === 'agent') return undefined;
475
+ const settingData = await apiJson(transport, 'api/setting/getPartialMatchSetting', { signal });
476
+ const setting = settingData?.match_setting ?? settingData;
477
+ const startTime = toIsoTimestamp(Number(setting?.start_time ?? 0));
478
+ const endTime = toIsoTimestamp(Number(setting?.end_time ?? 0));
479
+ let categories = [];
480
+ try {
481
+ const tagData = await apiJson(transport, 'api/setting/getTagList', { signal });
482
+ const seen = new Set();
483
+ for (const tag of tagData?.tag_list ?? []) {
484
+ if (!tag || tag.is_hidden || typeof tag.tag_name !== 'string') continue;
485
+ const name = tag.tag_name.trim();
486
+ if (!name || /^week\s*\d+$/iu.test(name) || seen.has(name)) continue;
487
+ seen.add(name);
488
+ categories.push(name);
489
+ }
490
+ } catch {
491
+ categories = [];
492
+ }
493
+ return {
494
+ ...(typeof setting?.match_name === 'string' && setting.match_name.trim()
495
+ ? { title: setting.match_name.trim() }
496
+ : {}),
497
+ ...(typeof setting?.short_description === 'string' && setting.short_description.trim()
498
+ ? { subtitle: setting.short_description.trim() }
499
+ : {}),
500
+ ...(startTime ? { startTime } : {}),
501
+ ...(endTime ? { endTime } : {}),
502
+ ...(categories.length ? { categories } : {}),
503
+ };
504
+ },
505
+
506
+ async list(signal, listOptions = {}) {
507
+ const requested = Array.isArray(listOptions.challengeIds)
508
+ ? new Set(listOptions.challengeIds.map((id) => String(id).replace(/^ctfplus-/u, '')))
509
+ : undefined;
510
+
511
+ if (mode === 'agent') {
512
+ const listData = await apiJson(transport, 'api/agent/v1/challenges/list', {
513
+ method: 'POST',
514
+ headers: agentHeaders,
515
+ body: {},
516
+ signal,
517
+ });
518
+ const rawList = Array.isArray(listData?.challenges) ? listData.challenges : [];
519
+ const filtered = requested
520
+ ? rawList.filter((item) => requested.has(String(item.challenge_id)))
521
+ : rawList;
522
+ return runBounded(filtered, DETAIL_CONCURRENCY, async (item) => {
523
+ const remoteId = numericId(item.challenge_id);
524
+ const detailData = await apiJson(transport, 'api/agent/v1/challenges/detail', {
525
+ method: 'POST',
526
+ headers: agentHeaders,
527
+ body: { challengeId: Number(remoteId) },
528
+ signal,
529
+ });
530
+ const detail = detailData?.challenge ?? detailData;
531
+ const desc = extractRichText(detail?.short_des ?? item.short_des ?? '');
532
+ const hints = (Array.isArray(detail?.hint) ? detail.hint : [])
533
+ .map((h) => extractRichText(h?.content ?? ''))
534
+ .filter(Boolean);
535
+ const description = hints.length
536
+ ? `${desc}\n\n## Hints\n${hints.map((h) => `- ${h}`).join('\n')}`.trim()
537
+ : desc;
538
+ return {
539
+ id: `ctfplus-${remoteId}`,
540
+ remoteId,
541
+ title: String(detail?.challenge_name ?? item.challenge_name ?? `ctfplus-${remoteId}`),
542
+ description,
543
+ category: pickCategory(detail?.tags ?? item.tags),
544
+ points: Number(detail?.current_score ?? item.score ?? 0),
545
+ ...buildSyncedChallengeMeta(detail, item, false),
546
+ ...(detail?.is_solved || item.is_solved ? { status: 'solved' } : {}),
547
+ resources: (Array.isArray(detail?.attachments) ? detail.attachments : []).map((att) => ({
548
+ ...transport.attachment(normalizeAttachmentPath(att.attachment_path), att.attachment_name),
549
+ agentPayload: { challengeId: Number(remoteId), attachmentPath: String(att.attachment_path) },
550
+ })),
551
+ };
552
+ });
553
+ }
554
+
555
+ const listData = await apiJson(transport, 'api/challenge/getChallengeList', {
556
+ method: 'POST',
557
+ body: {},
558
+ signal,
559
+ });
560
+ const rawList = Array.isArray(listData?.challenges) ? listData.challenges : [];
561
+ const filtered = requested
562
+ ? rawList.filter((item) => requested.has(String(item.challenge_id)))
563
+ : rawList;
564
+
565
+ return runBounded(filtered, DETAIL_CONCURRENCY, async (item) => {
566
+ const remoteId = numericId(item.challenge_id);
567
+ const detailData = await apiJson(transport, 'api/challenge/getChallengeDetailInfo', {
568
+ method: 'POST',
569
+ body: { id: remoteId },
570
+ signal,
571
+ });
572
+ const detail = detailData?.challenge ?? detailData;
573
+ const desc = extractRichText(detail?.short_des ?? item.short_des ?? '');
574
+ const hints = (Array.isArray(detail?.hint) ? detail.hint : [])
575
+ .map((h) => extractRichText(h?.content ?? ''))
576
+ .filter(Boolean);
577
+ const description = hints.length
578
+ ? `${desc}\n\n## Hints\n${hints.map((h) => `- ${h}`).join('\n')}`.trim()
579
+ : desc;
580
+ return {
581
+ id: `ctfplus-${remoteId}`,
582
+ remoteId,
583
+ title: String(detail?.challenge_name ?? item.challenge_name ?? `ctfplus-${remoteId}`),
584
+ description,
585
+ category: pickCategory(detail?.tags ?? item.tags),
586
+ points: Number(detail?.current_score ?? item.score ?? 0),
587
+ ...buildSyncedChallengeMeta(detail, item, true),
588
+ ...(detail?.is_solved || item.is_solved ? { status: 'solved' } : {}),
589
+ resources: (Array.isArray(detail?.attachments) ? detail.attachments : []).map((att) =>
590
+ transport.attachment(normalizeAttachmentPath(att.attachment_path), att.attachment_name),
591
+ ),
592
+ };
593
+ });
594
+ },
595
+
596
+ async instance(remoteId, action, signal) {
597
+ const id = numericId(remoteId);
598
+ if (mode === 'agent') {
599
+ const endpoint =
600
+ action === 'start'
601
+ ? 'api/agent/v1/runtimes/start'
602
+ : action === 'renew'
603
+ ? 'api/agent/v1/runtimes/extend'
604
+ : action === 'stop'
605
+ ? 'api/agent/v1/runtimes/stop'
606
+ : null;
607
+ if (!endpoint) throw fail('INVALID_INPUT', 'Unsupported instance action.');
608
+ try {
609
+ await apiJson(transport, endpoint, {
610
+ method: 'POST',
611
+ headers: agentHeaders,
612
+ body: { challengeId: Number(id), requestId: randomUUID() },
613
+ signal,
614
+ });
615
+ } catch (error) {
616
+ if (action === 'stop' && isContainerAlreadyGoneError(error)) {
617
+ return { ...normalizeContainerInfo({}, 'stop'), alreadyStopped: true };
618
+ }
619
+ throw error;
620
+ }
621
+ if (action === 'stop') return normalizeContainerInfo({}, 'stop');
622
+ const inspect = await apiJson(transport, 'api/agent/v1/runtimes/inspect', {
623
+ method: 'POST',
624
+ headers: agentHeaders,
625
+ body: { challengeId: Number(id) },
626
+ signal,
627
+ });
628
+ const firstEp = Array.isArray(inspect?.endpoints) ? inspect.endpoints[0] : undefined;
629
+ return normalizeContainerInfo(
630
+ {
631
+ ...(firstEp?.address ? { entry: firstEp.address } : {}),
632
+ ...(firstEp?.host ? { host: firstEp.host } : {}),
633
+ ...(firstEp?.port !== undefined ? { port: firstEp.port } : {}),
634
+ ...(inspect?.expiresAt ? { expiresAt: inspect.expiresAt } : {}),
635
+ },
636
+ action,
637
+ );
638
+ }
639
+
640
+ if (action === 'start') {
641
+ const data = await apiJson(transport, 'api/challenge/startChallenge', {
642
+ method: 'POST',
643
+ body: { id },
644
+ signal,
645
+ });
646
+ if (typeof data?.address === 'string' && data.address.trim()) {
647
+ return normalizeStartContainer(data, 'start');
648
+ }
649
+ return inspectContainerEntry(id, 'start', signal);
650
+ }
651
+ if (action === 'renew') {
652
+ await apiJson(transport, 'api/challenge/delayChallenge', {
653
+ method: 'POST',
654
+ body: { id },
655
+ signal,
656
+ });
657
+ return inspectContainerEntry(id, 'renew', signal);
658
+ }
659
+ if (action === 'stop') {
660
+ try {
661
+ await apiJson(transport, 'api/challenge/stopChallenge', {
662
+ method: 'POST',
663
+ body: { id },
664
+ signal,
665
+ });
666
+ } catch (error) {
667
+ if (isContainerAlreadyGoneError(error)) {
668
+ return { ...normalizeContainerInfo({}, 'stop'), alreadyStopped: true };
669
+ }
670
+ throw error;
671
+ }
672
+ return normalizeContainerInfo({}, 'stop');
673
+ }
674
+ throw fail('INVALID_INPUT', 'Unsupported instance action.');
675
+ },
676
+
677
+ async submit(remoteId, answer, signal) {
678
+ const id = numericId(remoteId);
679
+ if (mode === 'agent') {
680
+ let payload;
681
+ try {
682
+ payload = await apiJson(transport, 'api/agent/v1/submissions/flag', {
683
+ method: 'POST',
684
+ headers: agentHeaders,
685
+ body: { challengeId: Number(id), flag: answer, requestId: randomUUID() },
686
+ signal,
687
+ });
688
+ } catch (error) {
689
+ if (error.code === 'PLATFORM_HTTP_ERROR' && error.apiMsg) {
690
+ return parseSubmitMessage(error.apiMsg);
691
+ }
692
+ throw error;
693
+ }
694
+ if (payload?.alreadySolved === true) {
695
+ return {
696
+ status: 'already_solved',
697
+ ...(typeof payload.message === 'string' && payload.message.trim()
698
+ ? { message: payload.message.trim() }
699
+ : {}),
700
+ };
701
+ }
702
+ if (payload?.correct === false || payload?.accepted === false || payload?.result === false) {
703
+ return parseSubmitMessage(payload.message ?? payload.msg);
704
+ }
705
+ return {
706
+ status: 'correct',
707
+ ...(typeof payload?.message === 'string' && payload.message.trim()
708
+ ? { message: payload.message.trim() }
709
+ : {}),
710
+ };
711
+ }
712
+
713
+ let raw;
714
+ try {
715
+ const response = await transport.request('api/challenge/submitFlag', {
716
+ method: 'POST',
717
+ headers: { 'Content-Type': 'application/json' },
718
+ body: JSON.stringify({ challenge_id: Number(id), flag: answer }),
719
+ signal,
720
+ });
721
+ raw = await jsonResponse(response);
722
+ } catch (error) {
723
+ if (error.code === 'PLATFORM_HTTP_ERROR' && error.responseText) {
724
+ try {
725
+ raw = JSON.parse(error.responseText);
726
+ } catch {
727
+ throw error;
728
+ }
729
+ } else {
730
+ throw error;
731
+ }
732
+ }
733
+
734
+ if (!raw || typeof raw !== 'object') {
735
+ throw fail('PLATFORM_INVALID_RESPONSE', 'CTF Plus returned an invalid submission response.');
736
+ }
737
+ const code = 'code' in raw ? raw.code : 200;
738
+ const msg =
739
+ typeof raw.msg === 'string' && raw.msg.trim()
740
+ ? raw.msg.trim()
741
+ : typeof raw.message === 'string' && raw.message.trim()
742
+ ? raw.message.trim()
743
+ : undefined;
744
+ if (code === 401) throw fail('PLATFORM_AUTH_FAILED', msg ?? 'Unauthorized');
745
+ if (code !== 200) return parseSubmitMessage(msg);
746
+ const data = 'data' in raw ? raw.data : raw;
747
+ if (data?.alreadySolved === true || data?.already_solved === true) {
748
+ return { status: 'already_solved', ...(msg ? { message: msg } : {}) };
749
+ }
750
+ if (data === false || data?.correct === false || data?.result === false || data?.is_correct === false) {
751
+ return parseSubmitMessage(msg);
752
+ }
753
+ return { status: 'correct', ...(msg ? { message: msg } : {}) };
754
+ },
755
+
756
+ async download(resource, signal) {
757
+ safeSegment(resource.name);
758
+ if (mode === 'agent' && resource.agentPayload) {
759
+ return transport.download(
760
+ { ...resource, url: 'api/agent/v1/attachments/download' },
761
+ { 'Content-Type': 'application/json', ...agentHeaders },
762
+ signal,
763
+ { method: 'POST', body: JSON.stringify(resource.agentPayload) },
764
+ );
765
+ }
766
+ return transport.download(resource, {}, signal);
767
+ },
768
+ };
769
+ }