@craft_eco/craft-mcp 0.1.31 → 0.1.32

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 (96) hide show
  1. package/README.md +4 -4
  2. package/dist-server/game-workflow/check.mjs +35 -13
  3. package/dist-server/game-workflow/draft-archive.mjs +14 -5
  4. package/dist-server/game-workflow/draft-uploads.mjs +22 -9
  5. package/dist-server/game-workflow/upload-security-policy.mjs +241 -0
  6. package/dist-server/game-workflow/upload-security.mjs +41 -0
  7. package/dist-server/integrations/runtime-gc.mjs +131 -35
  8. package/dist-server/mcp/server.mjs +31 -19
  9. package/package.json +3 -1
  10. package/resources/craft-create/SKILL.md +2 -0
  11. package/resources/craft-update/SKILL.md +2 -0
  12. package/resources/targets/claude/js/craft-game-maker/SKILL.md +3 -3
  13. package/resources/targets/claude/js/js/bundle.json +5 -5
  14. package/resources/targets/claude/js/target.json +1 -1
  15. package/resources/targets/claude/js3d/craft-game-maker/SKILL.md +3 -3
  16. package/resources/targets/claude/js3d/js3d/bundle.json +5 -5
  17. package/resources/targets/claude/js3d/target.json +1 -1
  18. package/resources/targets/codebuddy/js/craft-game-maker/SKILL.md +3 -3
  19. package/resources/targets/codebuddy/js/js/bundle.json +5 -5
  20. package/resources/targets/codebuddy/js/target.json +1 -1
  21. package/resources/targets/codebuddy/js3d/craft-game-maker/SKILL.md +3 -3
  22. package/resources/targets/codebuddy/js3d/js3d/bundle.json +5 -5
  23. package/resources/targets/codebuddy/js3d/target.json +1 -1
  24. package/resources/targets/codex/js/craft-game-maker/SKILL.md +3 -3
  25. package/resources/targets/codex/js/js/bundle.json +5 -5
  26. package/resources/targets/codex/js/target.json +1 -1
  27. package/resources/targets/codex/js3d/craft-game-maker/SKILL.md +3 -3
  28. package/resources/targets/codex/js3d/js3d/bundle.json +5 -5
  29. package/resources/targets/codex/js3d/target.json +1 -1
  30. package/resources/targets/comate/js/craft-game-maker/SKILL.md +3 -3
  31. package/resources/targets/comate/js/js/bundle.json +5 -5
  32. package/resources/targets/comate/js/target.json +1 -1
  33. package/resources/targets/comate/js3d/craft-game-maker/SKILL.md +3 -3
  34. package/resources/targets/comate/js3d/js3d/bundle.json +5 -5
  35. package/resources/targets/comate/js3d/target.json +1 -1
  36. package/resources/targets/cursor/js/craft-game-maker/SKILL.md +3 -3
  37. package/resources/targets/cursor/js/js/bundle.json +5 -5
  38. package/resources/targets/cursor/js/target.json +1 -1
  39. package/resources/targets/cursor/js3d/craft-game-maker/SKILL.md +3 -3
  40. package/resources/targets/cursor/js3d/js3d/bundle.json +5 -5
  41. package/resources/targets/cursor/js3d/target.json +1 -1
  42. package/resources/targets/dsh/js/craft-game-maker/SKILL.md +3 -3
  43. package/resources/targets/dsh/js/js/bundle.json +5 -5
  44. package/resources/targets/dsh/js/target.json +1 -1
  45. package/resources/targets/dsh/js3d/craft-game-maker/SKILL.md +3 -3
  46. package/resources/targets/dsh/js3d/js3d/bundle.json +5 -5
  47. package/resources/targets/dsh/js3d/target.json +1 -1
  48. package/resources/targets/index.json +56 -56
  49. package/resources/targets/kimi/js/craft-game-maker/SKILL.md +3 -3
  50. package/resources/targets/kimi/js/js/bundle.json +5 -5
  51. package/resources/targets/kimi/js/target.json +1 -1
  52. package/resources/targets/kimi/js3d/craft-game-maker/SKILL.md +3 -3
  53. package/resources/targets/kimi/js3d/js3d/bundle.json +5 -5
  54. package/resources/targets/kimi/js3d/target.json +1 -1
  55. package/resources/targets/opencode/js/craft-game-maker/SKILL.md +3 -3
  56. package/resources/targets/opencode/js/js/bundle.json +5 -5
  57. package/resources/targets/opencode/js/target.json +1 -1
  58. package/resources/targets/opencode/js3d/craft-game-maker/SKILL.md +3 -3
  59. package/resources/targets/opencode/js3d/js3d/bundle.json +5 -5
  60. package/resources/targets/opencode/js3d/target.json +1 -1
  61. package/resources/targets/qoder/js/craft-game-maker/SKILL.md +3 -3
  62. package/resources/targets/qoder/js/js/bundle.json +5 -5
  63. package/resources/targets/qoder/js/target.json +1 -1
  64. package/resources/targets/qoder/js3d/craft-game-maker/SKILL.md +3 -3
  65. package/resources/targets/qoder/js3d/js3d/bundle.json +5 -5
  66. package/resources/targets/qoder/js3d/target.json +1 -1
  67. package/resources/targets/qoder-cn/js/craft-game-maker/SKILL.md +3 -3
  68. package/resources/targets/qoder-cn/js/js/bundle.json +5 -5
  69. package/resources/targets/qoder-cn/js/target.json +1 -1
  70. package/resources/targets/qoder-cn/js3d/craft-game-maker/SKILL.md +3 -3
  71. package/resources/targets/qoder-cn/js3d/js3d/bundle.json +5 -5
  72. package/resources/targets/qoder-cn/js3d/target.json +1 -1
  73. package/resources/targets/qwen/js/craft-game-maker/SKILL.md +3 -3
  74. package/resources/targets/qwen/js/js/bundle.json +5 -5
  75. package/resources/targets/qwen/js/target.json +1 -1
  76. package/resources/targets/qwen/js3d/craft-game-maker/SKILL.md +3 -3
  77. package/resources/targets/qwen/js3d/js3d/bundle.json +5 -5
  78. package/resources/targets/qwen/js3d/target.json +1 -1
  79. package/resources/targets/trae/js/craft-game-maker/SKILL.md +3 -3
  80. package/resources/targets/trae/js/js/bundle.json +5 -5
  81. package/resources/targets/trae/js/target.json +1 -1
  82. package/resources/targets/trae/js3d/craft-game-maker/SKILL.md +3 -3
  83. package/resources/targets/trae/js3d/js3d/bundle.json +5 -5
  84. package/resources/targets/trae/js3d/target.json +1 -1
  85. package/resources/targets/workbuddy/js/craft-game-maker/SKILL.md +3 -3
  86. package/resources/targets/workbuddy/js/js/bundle.json +5 -5
  87. package/resources/targets/workbuddy/js/target.json +1 -1
  88. package/resources/targets/workbuddy/js3d/craft-game-maker/SKILL.md +3 -3
  89. package/resources/targets/workbuddy/js3d/js3d/bundle.json +5 -5
  90. package/resources/targets/workbuddy/js3d/target.json +1 -1
  91. package/resources/targets/zcode/js/craft-game-maker/SKILL.md +3 -3
  92. package/resources/targets/zcode/js/js/bundle.json +5 -5
  93. package/resources/targets/zcode/js/target.json +1 -1
  94. package/resources/targets/zcode/js3d/craft-game-maker/SKILL.md +3 -3
  95. package/resources/targets/zcode/js3d/js3d/bundle.json +5 -5
  96. package/resources/targets/zcode/js3d/target.json +1 -1
package/README.md CHANGED
@@ -12,9 +12,9 @@ Craft MCP 是面向支持本地 stdio MCP 的 AI IDE 的游戏制作服务,例
12
12
 
13
13
  ```sh
14
14
  # 在 Codex 中安装
15
- npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.31 install --ide codex
15
+ npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.32 install --ide codex
16
16
  # 在 WorkBuddy 中安装
17
- npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.31 install --ide workbuddy
17
+ npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.32 install --ide workbuddy
18
18
  ```
19
19
 
20
20
  其他宿主将 --ide 改为 cursor、codebuddy、claude、dsh、zcode、kimi、trae、qoder-cn、qoder、comate、opencode 或 qwen。TRAE 与国际版 Qoder IDE 还须 --host-config <宿主设置中打开的 MCP 配置绝对路径>;TRAE CN 加 --trae-region cn,国际版默认 global。这两个选项也适用于 doctor/check/update/connect/project-setup,可由 CRAFT_HOST_CONFIG、CRAFT_TRAE_REGION 环境变量提供。kimi 指当前 Kimi Code CLI,不写旧 Python Kimi CLI 的 ~/.kimi。可用 --workspace <绝对游戏父目录> 和 --platform <HTTPS origin> 指定目录与平台;未提供时保留现有配置,新安装默认 ~/CraftGames 和本包平台。安装不创建游戏、不修改信任权限;低版本或同版不同构建不会覆盖现有新版。
@@ -32,7 +32,7 @@ Claude Code 使用 ~/.claude.json 与 ~/.claude/skills;DSH 使用 ~/.dsh/cordi
32
32
  执行本包 guide,根据当前宿主调用上面的标准 install。十四种宿主使用同一安装流程,无需选择连接模式。当前进程不会因安装新版而切换版本;固定入口在下次启动时读取已安装目标。
33
33
 
34
34
  ```sh
35
- npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.31 guide
35
+ npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.32 guide
36
36
  ```
37
37
 
38
38
  专家和连接器只通过 connect --ide workbuddy 解析标准安装并启动同一受管入口,首次使用也须先执行标准 install。connect 不安装程序、不改宿主配置、不创建游戏;安装缺失、禁用或平台/工作区不一致时明确失败。不要用无参数 npx 直接启动业务包来替代标准安装。未适配宿主的原始 stdio 调试不包含自动更新和 Skill 安装。
@@ -47,7 +47,7 @@ npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.31 gui
47
47
 
48
48
  先读取 craft_game_info 的通用流程及所选 js / js3d 引擎 AGENTS.md。使用 craft_game_check 和 craft_game_review 验收真实玩法及画面,再由宿主终端按 craft_game_deliver 返回的命令启动本地预览。
49
49
 
50
- 使用 craft_game_upload 上传同次验收的源码与 dist。draft_ready 后把 project_url 交给用户,在 Craft 网页完成发布。
50
+ 使用 craft_game_upload 上传同次检查冻结的源码与 dist。安全检查失败时告知用户原因并停止上传。安全检查通过后,玩法和画面问题作为报告反馈。draft_ready 后把 project_url 交给用户,在 Craft 网页完成发布。
51
51
 
52
52
  当前业务平台是 https://craft.qq.com。npm 程序公开可下载不代表生产环境或公开发布开关已启用;上传和提审需要匹配的 Web 服务与审核配置。
53
53
 
@@ -6,7 +6,8 @@ import { finalizeGameContext, buildJsStatic, prepareStaticArtifacts, prepareBrow
6
6
  import { fingerprint } from './projects.mjs';
7
7
  import { atomicJson } from './request-store.mjs';
8
8
  import { engineDefinition } from './engines.mjs';
9
- import { freezeCheckedBuild, freezeCheckedSource } from './draft-archive.mjs';
9
+ import { checkedDraftFiles, checkedDraftSource, freezeCheckedBuild, freezeCheckedSource } from './draft-archive.mjs';
10
+ import { reviewUploadSecurity } from './upload-security.mjs';
10
11
  import { guardWork } from './work-scope.mjs';
11
12
 
12
13
  export function validateSteps(steps) {
@@ -41,6 +42,24 @@ export function evaluateCapture(capture, steps, engine = 'js') {
41
42
  return { passed:issues.length === 0, issues };
42
43
  }
43
44
 
45
+ async function captureCheckedGame(project, resources, brief, steps, runDir, signal) {
46
+ const engine = resources.engine;
47
+ const requestFile = path.join(runDir,'request.json');
48
+ try {
49
+ const browserEnv = await prepareBrowserEnvironment({ cwd:project, env:process.env, signal });
50
+ await atomicJson(requestFile,{ project, engine, brief, steps, limits:{ browser_deadline_ms:180000, screenshot_timeout_ms:15000 } });
51
+ const result = await runProcess(process.execPath,[fileURLToPath(new URL('./capture-worker.mjs',import.meta.url)), resources.capture, requestFile],{
52
+ cwd:project, signal, timeoutMs:200000,
53
+ env:{ PATH:process.env.PATH ?? '', HOME:process.env.HOME ?? '', ...browserEnv },
54
+ });
55
+ if (result.timedOut) throw new Error('Browser capture timed out');
56
+ if (result.exitCode !== 0) throw new Error((result.stderr || result.stdout).trim() || `Capture worker exited with code ${result.exitCode}`);
57
+ return JSON.parse(await readFile(path.join(runDir,'capture.json'),'utf8'));
58
+ } catch (error) {
59
+ return { build:'passed', engine, shots:[], errors:[], unverified:['Game capture failed: ' + String(error.message).slice(-1500)] };
60
+ }
61
+ }
62
+
44
63
  export async function checkGame(project, resources, brief, steps, signal) {
45
64
  if (typeof brief !== 'string' || brief.trim().length < 3 || brief.length > 8000) throw new Error('Game brief must contain 3 to 8000 characters');
46
65
  validateSteps(steps);
@@ -55,25 +74,28 @@ export async function checkGame(project, resources, brief, steps, signal) {
55
74
  await guardWork();
56
75
  if (source !== await fingerprint(project)) throw new Error('Sources changed during build; finish editing and check again');
57
76
  const artifacts = await prepareStaticArtifacts(path.join(project,'dist'));
58
- const browserEnv = await prepareBrowserEnvironment({ cwd:project, env:process.env, signal });
59
77
  await mkdir(resources.evidence,{ recursive:true,mode:0o700 });
60
78
  if ((await lstat(resources.evidence)).isSymbolicLink()) throw new Error('Game check directory must not be a symbolic link');
61
79
  const snapshotId = randomUUID(), runDir = path.join(await realpath(resources.evidence),snapshotId);
62
80
  await mkdir(runDir,{ mode:0o700 });
63
81
  await freezeCheckedBuild(project,runDir,artifacts,signal);
64
82
  const sourceSnapshot = await freezeCheckedSource(project,runDir,signal);
65
- const requestFile = path.join(runDir,'request.json');
66
- await atomicJson(requestFile,{ project, engine, brief, steps, limits:{ browser_deadline_ms:180000, screenshot_timeout_ms:15000 } });
67
- const result = await runProcess(process.execPath,[fileURLToPath(new URL('./capture-worker.mjs',import.meta.url)), resources.capture, requestFile],{
68
- cwd:project, signal, timeoutMs:200000,
69
- env:{ PATH:process.env.PATH ?? '', HOME:process.env.HOME ?? '', ...browserEnv },
70
- });
83
+ const security = reviewUploadSecurity(
84
+ await checkedDraftSource(resources.evidence,snapshotId,sourceSnapshot,signal),sourceSnapshot.format,
85
+ await checkedDraftFiles(resources.evidence,snapshotId,artifacts,signal),signal,
86
+ );
87
+
88
+ const capture = security.passed ? await captureCheckedGame(project,resources,brief,steps,runDir,signal) : {
89
+ build:'passed', engine, shots:[], errors:[], unverified:['Browser capture was skipped because the upload security check found risks.'],
90
+ };
71
91
  signal.throwIfAborted();
72
92
  await guardWork();
73
- if (result.exitCode !== 0 || result.timedOut) throw new Error('Game capture failed: ' + (result.stderr || result.stdout).slice(-1500));
74
- const capture = JSON.parse(await readFile(path.join(runDir,'capture.json'),'utf8'));
75
- if (source !== await fingerprint(project)) throw new Error('Sources changed during browser verification; check again');
93
+ if (source !== await fingerprint(project)) throw new Error('Sources changed during game verification; check again');
76
94
  const gate = evaluateCapture(capture,steps,engine);
77
- return { engine, source, artifacts, snapshot_id:snapshotId, source_snapshot:sourceSnapshot, gate, capture, screenshots:capture.shots.map(shot=>path.join(runDir,shot.file)),
78
- visual_review:'required', next:gate.passed ? 'Inspect the screenshots using the host AI IDE; then craft_game_deliver with this check task id.' : 'Fix the reported errors, then check again.' };
95
+ const screenshots = capture.shots.map(shot=>path.join(runDir,shot.file));
96
+ const next = gate.passed ? 'Inspect the screenshots using the host AI IDE, then craft_game_deliver with this check task id.' :
97
+ 'Report the check issues and inspect available screenshots. Upload when requested. Fix the issues and check again for a verified preview.';
98
+ return { engine, source, artifacts, snapshot_id:snapshotId, source_snapshot:sourceSnapshot, security, gate, capture, screenshots,
99
+ visual_review:screenshots.length ? 'required' : 'unavailable',
100
+ next:security.passed ? next : 'Report the security findings. Fix them and run a new check before uploading.' };
79
101
  }
@@ -20,6 +20,12 @@ const textExtensions = new Set([
20
20
  'sh','sql','svg','toml','tres','tscn','ts','tsx','txt','vue','xml','yaml','yml','mts',
21
21
  ]);
22
22
 
23
+ export function sourceFileEncoding(file) {
24
+ const name = path.posix.basename(file);
25
+ const dot = name.lastIndexOf('.');
26
+ return dot > 0 && !textExtensions.has(name.slice(dot + 1).toLowerCase()) ? 'base64' : 'utf8';
27
+ }
28
+
23
29
  function skipSourceEntry(name, relative) {
24
30
  const lower = name.toLowerCase(), match = relative.toLowerCase();
25
31
  return name.startsWith('.') || credentialName.test(name) || credentialExtension.test(name) ||
@@ -90,8 +96,7 @@ export async function freezeCheckedSource(project, runDirectory, signal) {
90
96
  }
91
97
  if (!entry.isFile()) throw new Error('Project source must be a regular file');
92
98
  if (++files > sourceMaxFiles) throw new Error('Project source snapshot exceeds the 2000 file limit');
93
- const dot = entry.name.lastIndexOf('.');
94
- const binary = dot > 0 && !textExtensions.has(entry.name.slice(dot + 1).toLowerCase());
99
+ const encoding = sourceFileEncoding(entry.name);
95
100
  const changed = () => new Error('Project source changed during collection');
96
101
  const before = await lstat(file,{ bigint:true });
97
102
  if (!before.isFile()) throw changed();
@@ -105,8 +110,8 @@ export async function freezeCheckedSource(project, runDirectory, signal) {
105
110
  if (!sameSourceFile(opened,await source.stat({ bigint:true })) || await realpath(file) !== file ||
106
111
  !sameSourceFile(before,await lstat(file,{ bigint:true }))) throw changed();
107
112
  } finally { await source.close(); }
108
- if (!binary && (!isUtf8(data) || data.includes(0))) throw new Error(`Project source file must contain UTF-8 text: ${relative}`);
109
- const content = data.toString(binary ? 'base64' : 'utf8');
113
+ if (encoding === 'utf8' && (!isUtf8(data) || data.includes(0))) throw new Error(`Project source file must contain UTF-8 text: ${relative}`);
114
+ const content = data.toString(encoding);
110
115
  await append((files > 1 ? ',' : '') + JSON.stringify({ path:relative,content }));
111
116
  }
112
117
  }
@@ -193,6 +198,10 @@ export async function checkedDraftFiles(evidence, snapshotId, artifacts, signal)
193
198
 
194
199
 
195
200
  export async function checkedDraftArchive(evidence,snapshotId,artifacts,signal) {
196
- const files=await checkedDraftFiles(evidence,snapshotId,artifacts,signal);
201
+ const files = await checkedDraftFiles(evidence,snapshotId,artifacts,signal);
202
+ return encodeCheckedDraftArchive(files,signal);
203
+ }
204
+
205
+ export function encodeCheckedDraftArchive(files,signal) {
197
206
  return encodeExternalGameArchive(Array.from(files,([url,{ data }])=>[url.slice(1),data]),signal);
198
207
  }
@@ -1,10 +1,11 @@
1
- import { checkedDraftArchive, checkedDraftSource } from './draft-archive.mjs';
1
+ import { checkedDraftFiles, checkedDraftSource, encodeCheckedDraftArchive } from './draft-archive.mjs';
2
2
  import { guardWork } from './work-scope.mjs';
3
3
  import path from 'node:path';
4
4
  import { DraftBindings } from './draft-bindings.mjs';
5
5
  import { draftUploadIdentity } from './draft-upload-identity.mjs';
6
6
  import { digest } from './request-store.mjs';
7
7
  import { assertSourceUploadLimit, validSourceMetadata } from '../upstream/draft-source.mjs';
8
+ import { assertUploadSecurity, uploadSecurityPolicyVersion } from './upload-security.mjs';
8
9
 
9
10
  function prepareInput(record) {
10
11
  const input = record.prepare_input ?? { client_request_id:record.request_id, engine:record.engine,
@@ -33,6 +34,12 @@ function assertFrozenInputs(record, archive, source) {
33
34
  }
34
35
  }
35
36
 
37
+ function hasCurrentSecurityReview(record) {
38
+ const input = record.prepare_input, review = record.security_review;
39
+ return Boolean(input?.source && review?.policy_version === uploadSecurityPolicyVersion &&
40
+ review.source_sha256 === input.source.sha256 && review.archive_sha256 === input.sha256);
41
+ }
42
+
36
43
  function mergeReceipt(record, result) {
37
44
  if (record.upload_id !== undefined && record.upload_id !== result.upload_id) throw new Error('Craft changed the upload ID for this request');
38
45
  if (record.prepare_input?.source && result.state !== 'expired') {
@@ -111,6 +118,7 @@ export class DraftUploads {
111
118
  if (record.engine !== scope.engine || digest(prepareInput(record)) !== digest(prepareInput(saved))) {
112
119
  throw new Error('Pending draft request changed');
113
120
  }
121
+ if (!hasCurrentSecurityReview(record) && hasCurrentSecurityReview(saved)) record.security_review = saved.security_review;
114
122
  // Keep a complete pending receipt in the shared ledger so another profile can recover it.
115
123
  await this.store.save(record);
116
124
  return record;
@@ -133,13 +141,14 @@ export class DraftUploads {
133
141
 
134
142
  async #recover(record, request, signal) {
135
143
  if (terminal(record)) return record;
136
- if (!record.prepare_input?.source && !record.upload_id) return record;
137
144
  signal?.throwIfAborted();
138
- if (!record.upload_id) await guardWork();
139
- record = await this.#accept(record,await (record.upload_id
140
- ? request('status',{ id:record.upload_id },signal)
141
- : request('prepare',{ input:prepareInput(record) },signal)));
142
- if (record.prepare_input?.source && record.state === 'uploaded') {
145
+ if (record.upload_id) record = await this.#accept(record,await request('status',{ id:record.upload_id },signal));
146
+ if (terminal(record) || !hasCurrentSecurityReview(record)) return record;
147
+ if (!record.upload_id) {
148
+ await guardWork();
149
+ record = await this.#accept(record,await request('prepare',{ input:prepareInput(record) },signal));
150
+ }
151
+ if (record.state === 'uploaded') {
143
152
  signal?.throwIfAborted();
144
153
  await guardWork();
145
154
  record = await this.#accept(record,await request('commit',{ id:record.upload_id },signal));
@@ -184,7 +193,7 @@ export class DraftUploads {
184
193
  const record = await this.#pending(scope,binding);
185
194
  if (record.request_id === id) return binding;
186
195
  let recovered = await this.#recover(record,request,signal);
187
- if (!terminal(recovered) && !recovered.prepare_input?.source) {
196
+ if (!terminal(recovered) && !hasCurrentSecurityReview(recovered)) {
188
197
  recovered = { ...recovered,state:'superseded' };
189
198
  await this.store.save(recovered);
190
199
  }
@@ -207,7 +216,9 @@ export class DraftUploads {
207
216
  }
208
217
  if (record && !record.prepare_input?.source) throw new Error('This upload predates project source uploads. Run a new craft_game_check');
209
218
  const source = await checkedDraftSource(this.evidence,result.snapshot_id,result.source_snapshot,signal);
210
- const archive = await checkedDraftArchive(this.evidence,result.snapshot_id,result.artifacts,signal);
219
+ const files = await checkedDraftFiles(this.evidence,result.snapshot_id,result.artifacts,signal);
220
+ assertUploadSecurity(source,result.source_snapshot.format,files,signal);
221
+ const archive = await encodeCheckedDraftArchive(files,signal);
211
222
  assertFrozenInputs(record,archive,result.source_snapshot);
212
223
  const limits = await this.platform.uploadLimits(owner,signal);
213
224
  assertSourceUploadLimit(result.source_snapshot.bytes,limits.source_max_bytes);
@@ -235,6 +246,8 @@ export class DraftUploads {
235
246
  previous_binding:{ conversation_id:binding.conversation_id,version_id:binding.version_id }, ...scope, bytes:input.bytes, sha256:input.sha256,
236
247
  state:'preparing',prepare_input:input });
237
248
  record.prepare_input ??= input;
249
+ record.security_review = { policy_version:uploadSecurityPolicyVersion,
250
+ source_sha256:result.source_snapshot.sha256, archive_sha256:archive.sha256 };
238
251
  // Save immutable target/base before any remote request, then make it recoverable across profiles.
239
252
  await this.store.save(record);
240
253
  binding.pending = record;
@@ -0,0 +1,241 @@
1
+ import { isUtf8 } from 'node:buffer';
2
+ import { isIP } from 'node:net';
3
+ import path from 'node:path';
4
+ import { parse } from '@babel/parser';
5
+ import { parse as parseHtml } from 'parse5';
6
+
7
+ const maxFindings = 32;
8
+ const maxCodeBytes = 8 * 1024 * 1024;
9
+ const codeExtensions = new Set(['.js','.mjs','.cjs','.jsx','.ts','.mts','.cts','.tsx']);
10
+ const markupExtensions = new Set(['.html','.htm','.svg','.xhtml']);
11
+ const executableExtensions = new Set(['.exe','.dll','.node','.msi','.com','.sys','.scr']);
12
+ const scriptTypes = new Set([
13
+ '','module','application/ecmascript','application/javascript','application/x-ecmascript','application/x-javascript',
14
+ 'text/ecmascript','text/javascript','text/javascript1.0','text/javascript1.1','text/javascript1.2','text/javascript1.3',
15
+ 'text/javascript1.4','text/javascript1.5','text/jscript','text/livescript','text/x-ecmascript','text/x-javascript',
16
+ ]);
17
+ const profileScript = 'https://file.craft.qq.com/QA/profile_toolbox.js';
18
+ const processModules = new Set(['child_process','node:child_process']);
19
+ const browserGlobals = new Set(['globalThis','self','window']);
20
+ const methods = /^(?:GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|CONNECT|TRACE)$/i;
21
+ const scriptAddress = /^(?:(?:https?|wss?|data|blob|javascript|file):|\/\/)/i;
22
+ const privateKey = /-----BEGIN (?:(?:RSA|EC|DSA|OPENSSH|ENCRYPTED) )?PRIVATE KEY-----/;
23
+
24
+ const messages = {
25
+ EMBEDDED_PRIVATE_KEY:'文件内含私钥标记。移除私钥后重新检查。',
26
+ EXECUTABLE_ATTACHMENT:'游戏附件包含本机可执行文件。移除该文件后重新检查。',
27
+ PROCESS_EXECUTION:'代码引入了可启动本机进程的模块。移除此调用后重新检查。',
28
+ REMOTE_EXECUTABLE_CODE:'代码从外部地址或动态数据地址加载可执行脚本。请使用项目内可检查的脚本。',
29
+ PRIVATE_NETWORK_REQUEST:'代码直接请求本机或私有网络地址。移除该请求后重新检查。',
30
+ UNSAFE_CODE_GENERATION:'代码将字符串作为 JavaScript 执行。请改用普通函数。',
31
+ UNBOUNDED_NETWORK_CALLS:'代码会在持续循环或极短的定时间隔内反复发起网络请求。请限制请求频率。',
32
+ UNSCANNABLE_CODE:'无法完整解析此代码文件。修复语法、编码或拆分过大的文件后重新检查。',
33
+ };
34
+
35
+ function staticString(node) {
36
+ if (node?.type === 'StringLiteral') return node.value;
37
+ if (node?.type === 'TemplateLiteral' && node.expressions.length === 0) return node.quasis[0].value.cooked;
38
+ }
39
+
40
+ function propertyName(node) {
41
+ if (!['MemberExpression','OptionalMemberExpression'].includes(node?.type)) return;
42
+ return node.computed ? staticString(node.property) : node.property.name;
43
+ }
44
+
45
+ function globalName(node) {
46
+ if (node?.type === 'Identifier') return node.name;
47
+ if (browserGlobals.has(node?.object?.name)) return propertyName(node);
48
+ }
49
+
50
+ function literalAddress(node) {
51
+ if (node?.type === 'NewExpression' && ['URL','Request'].includes(globalName(node.callee))) return staticString(node.arguments[0]);
52
+ return staticString(node);
53
+ }
54
+
55
+ function normalizeAddress(value) {
56
+ return value?.replace(/[\t\r\n]/g,'').trim() ?? '';
57
+ }
58
+
59
+ const hasExecutableAddress = value => scriptAddress.test(normalizeAddress(value));
60
+
61
+ function privateIPv4(host) {
62
+ const [first,second] = host.split('.').map(Number);
63
+ return first === 0 || first === 10 || first === 127 || (first === 169 && second === 254) ||
64
+ (first === 172 && second >= 16 && second <= 31) || (first === 192 && second === 168) ||
65
+ (first === 100 && second >= 64 && second <= 127);
66
+ }
67
+
68
+ function privateNetwork(value) {
69
+ const address = normalizeAddress(value);
70
+ if (!address || !/^(?:(?:https?|wss?):|\/\/)/i.test(address)) return false;
71
+ let host;
72
+ try { host = new URL(address.startsWith('//') ? 'http:' + address : address).hostname.replace(/^\[|\]$|\.$/g,''); }
73
+ catch { return false; }
74
+ if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local')) return true;
75
+ if (isIP(host) === 4) return privateIPv4(host);
76
+ if (isIP(host) !== 6) return false;
77
+ const mapped = host.match(/^::ffff:([0-9a-f]+):([0-9a-f]+)$/i);
78
+ if (mapped) {
79
+ const upper = Number.parseInt(mapped[1],16), lower = Number.parseInt(mapped[2],16);
80
+ return privateIPv4([upper >> 8,upper & 255,lower >> 8,lower & 255].join('.'));
81
+ }
82
+ return host === '::' || host === '::1' || /^(?:f[cd]|fe[89ab])/i.test(host);
83
+ }
84
+
85
+ function callArguments(node) {
86
+ if (['CallExpression','OptionalCallExpression','NewExpression'].includes(node?.type)) return node.arguments;
87
+ }
88
+
89
+ function networkArguments(node) {
90
+ const args = callArguments(node);
91
+ if (!args) return;
92
+ const name = globalName(node.callee);
93
+ if (['fetch','WebSocket','EventSource'].includes(name)) return args;
94
+ const property = propertyName(node.callee);
95
+ if (property === 'sendBeacon' && node.callee.object?.name === 'navigator') return args;
96
+ if (property === 'open' && methods.test(staticString(args[0]) ?? '') && args.length >= 2) return args.slice(1);
97
+ }
98
+
99
+ function* syntaxNodes(root, skipFunctions = false) {
100
+ const pending = [root];
101
+ while (pending.length) {
102
+ const node = pending.pop();
103
+ if (skipFunctions && /Function|Method/.test(node.type)) continue;
104
+ yield node;
105
+ for (const value of Object.values(node)) {
106
+ if (Array.isArray(value)) {
107
+ for (let i = value.length - 1; i >= 0; i--) if (typeof value[i]?.type === 'string') pending.push(value[i]);
108
+ } else if (typeof value?.type === 'string') pending.push(value);
109
+ }
110
+ }
111
+ }
112
+
113
+ function unboundedNetworkLoop(node) {
114
+ const forever = (node.type === 'ForStatement' && node.test === null) ||
115
+ (['ForStatement','WhileStatement','DoWhileStatement'].includes(node.type) && node.test?.type === 'BooleanLiteral' && node.test.value);
116
+ if (!forever) return false;
117
+ let network = false;
118
+ for (const child of syntaxNodes(node.body,true)) {
119
+ if (['AwaitExpression','YieldExpression','BreakStatement','ReturnStatement','ThrowStatement'].includes(child.type)) return false;
120
+ network ||= Boolean(networkArguments(child));
121
+ }
122
+ return network;
123
+ }
124
+
125
+ function unsafeCodeGeneration(name, args) {
126
+ if (name === 'eval') return true;
127
+ // Phaser uses a constant Function body to locate the global object.
128
+ if (name === 'Function') return args.length !== 1 || !/^return\s+this\s*;?$/.test(staticString(args[0])?.trim() ?? '');
129
+ return ['setTimeout','setInterval'].includes(name) && ['StringLiteral','TemplateLiteral'].includes(args[0]?.type);
130
+ }
131
+
132
+ function scanScript(text, report, signal, {extension='.js',line=1,handler=false,declaration=false} = {}) {
133
+ let tree;
134
+ try {
135
+ const plugins = [];
136
+ if (['.ts','.mts','.cts','.tsx'].includes(extension)) plugins.push(['typescript',{dts:declaration}]);
137
+ if (['.jsx','.tsx','.js','.mjs','.cjs'].includes(extension)) plugins.push('jsx');
138
+ tree = parse(text,{sourceType:'unambiguous',plugins,attachComment:false,createImportExpressions:true,allowReturnOutsideFunction:handler});
139
+ } catch {
140
+ report('UNSCANNABLE_CODE',line);
141
+ return;
142
+ }
143
+ let visited = 0;
144
+ for (const node of syntaxNodes(tree)) {
145
+ if ((visited++ & 1023) === 0) signal?.throwIfAborted();
146
+ const at = line - 1 + (node.loc?.start?.line ?? 1);
147
+ const args = callArguments(node);
148
+ const callee = globalName(node.callee);
149
+ if (['ImportDeclaration','ExportAllDeclaration','ExportNamedDeclaration','ImportExpression'].includes(node.type)) {
150
+ const source = staticString(node.source);
151
+ if (processModules.has(source)) report('PROCESS_EXECUTION',at);
152
+ if (hasExecutableAddress(source)) report('REMOTE_EXECUTABLE_CODE',at);
153
+ }
154
+ if (unboundedNetworkLoop(node)) report('UNBOUNDED_NETWORK_CALLS',at);
155
+ if (!args) continue;
156
+ if (callee === 'require' && processModules.has(staticString(args[0]))) report('PROCESS_EXECUTION',at);
157
+ if (['Worker','SharedWorker','importScripts'].includes(callee) && args.some(arg=>hasExecutableAddress(literalAddress(arg)))) {
158
+ report('REMOTE_EXECUTABLE_CODE',at);
159
+ }
160
+ if (unsafeCodeGeneration(callee,args)) report('UNSAFE_CODE_GENERATION',at);
161
+ if (privateNetwork(literalAddress(networkArguments(node)?.[0]))) report('PRIVATE_NETWORK_REQUEST',at);
162
+ if (callee === 'setInterval' && args[1]?.type === 'NumericLiteral' && args[1].value <= 5 &&
163
+ ['ArrowFunctionExpression','FunctionExpression'].includes(args[0]?.type)) {
164
+ for (const child of syntaxNodes(args[0].body,true)) {
165
+ if (!networkArguments(child)) continue;
166
+ report('UNBOUNDED_NETWORK_CALLS',at);
167
+ break;
168
+ }
169
+ }
170
+ }
171
+ }
172
+
173
+ function scanMarkup(text, report, signal, {firstLine=1,depth=0,profilePage=false} = {}) {
174
+ if (depth >= 4) {
175
+ report('UNSCANNABLE_CODE',firstLine);
176
+ return;
177
+ }
178
+ const queue = [parseHtml(text,{sourceCodeLocationInfo:true})];
179
+ while (queue.length) {
180
+ signal?.throwIfAborted();
181
+ const element = queue.pop();
182
+ for (const child of element.childNodes ?? []) queue.push(child);
183
+ if (element.content) queue.push(element.content);
184
+ if (!element.attrs) continue;
185
+ const attributes = new Map(element.attrs.map(({name,value})=>[name,value]));
186
+ for (const [name,value] of attributes) {
187
+ const location = element.sourceCodeLocation?.attrs?.[name] ?? element.sourceCodeLocation;
188
+ const line = firstLine - 1 + (location?.startLine ?? 1);
189
+ if (['src','href','action','formaction','poster','data'].includes(name) && privateNetwork(value)) {
190
+ report('PRIVATE_NETWORK_REQUEST',line);
191
+ }
192
+ if (['src','href','action','formaction'].includes(name) && /^javascript:/i.test(normalizeAddress(value))) {
193
+ report('UNSAFE_CODE_GENERATION',line);
194
+ }
195
+ if (name.startsWith('on') && name.length > 2) scanScript(value,report,signal,{line,handler:true});
196
+ if (name === 'srcdoc' && element.tagName === 'iframe') scanMarkup(value,report,signal,{firstLine:line,depth:depth + 1});
197
+ }
198
+ const type = (attributes.get('type') ?? '').toLowerCase().split(';',1)[0].trim();
199
+ if (element.tagName !== 'script' || !scriptTypes.has(type)) continue;
200
+ const source = attributes.get('src') ?? attributes.get('href');
201
+ const line = firstLine - 1 + (element.sourceCodeLocation?.startLine ?? 1);
202
+ // Vite emits a separate profiler page pointing to this first-party toolbox.
203
+ const isProfileTool = profilePage && type === '' && source === profileScript;
204
+ if (hasExecutableAddress(source) && !isProfileTool) report('REMOTE_EXECUTABLE_CODE',line);
205
+ for (const child of element.childNodes ?? []) {
206
+ if (child.nodeName === '#text') {
207
+ const scriptLine = firstLine - 1 + (child.sourceCodeLocation?.startLine ?? element.sourceCodeLocation?.startLine ?? 1);
208
+ scanScript(child.value,report,signal,{line:scriptLine});
209
+ }
210
+ }
211
+ }
212
+ }
213
+
214
+ export function scanUploadFiles(files, {signal} = {}) {
215
+ const findings = [];
216
+ for (const {path:filename,content} of files) {
217
+ signal?.throwIfAborted();
218
+ if (!Buffer.isBuffer(content) || typeof filename !== 'string') throw new TypeError('Invalid upload security scan file');
219
+ const seen = new Set();
220
+ const report = (rule,line) => {
221
+ const key = rule + ':' + line;
222
+ if (findings.length >= maxFindings || seen.has(key)) return;
223
+ seen.add(key);
224
+ findings.push({path:filename,line,rule,message:messages[rule]});
225
+ };
226
+ const extension = path.extname(filename).toLowerCase();
227
+ if (executableExtensions.has(extension)) report('EXECUTABLE_ATTACHMENT',1);
228
+ const isCode = codeExtensions.has(extension) || markupExtensions.has(extension);
229
+ const validText = isUtf8(content) && !content.includes(0);
230
+ if (isCode && (!validText || content.length > maxCodeBytes)) report('UNSCANNABLE_CODE',1);
231
+ else if (validText) {
232
+ const text = content.toString('utf8');
233
+ const key = privateKey.exec(text);
234
+ if (key) report('EMBEDDED_PRIVATE_KEY',text.slice(0,key.index).split('\n').length);
235
+ if (codeExtensions.has(extension)) scanScript(text,report,signal,{extension,declaration:/\.d\.[cm]?ts$/i.test(filename)});
236
+ if (markupExtensions.has(extension)) scanMarkup(text,report,signal,{profilePage:filename === 'dist/index_profile.html'});
237
+ }
238
+ if (findings.length >= maxFindings) break;
239
+ }
240
+ return findings;
241
+ }
@@ -0,0 +1,41 @@
1
+ import { legacySourceFormat, sourceFormat } from '../upstream/draft-source.mjs';
2
+ import { sourceFileEncoding } from './draft-archive.mjs';
3
+ import { scanUploadFiles } from './upload-security-policy.mjs';
4
+
5
+ export const uploadSecurityPolicyVersion = 1;
6
+
7
+ function* uploadedFiles(source, format, dist) {
8
+ const parsed = JSON.parse(source.toString('utf8'));
9
+ let files;
10
+ if (format === sourceFormat && Array.isArray(parsed)) files = parsed;
11
+ else if (format === legacySourceFormat && parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
12
+ files = Object.entries(parsed).map(([path,content])=>({ path,content }));
13
+ } else throw new Error('Invalid frozen project source');
14
+
15
+ for (const file of files) {
16
+ if (!file || typeof file.path !== 'string' || typeof file.content !== 'string') throw new Error('Invalid frozen project file');
17
+ const encoding = format === legacySourceFormat ? 'utf8' : sourceFileEncoding(file.path);
18
+ yield { path:'source/' + file.path,content:Buffer.from(file.content,encoding) };
19
+ }
20
+ for (const [url,{ data }] of dist) yield { path:'dist' + url,content:data };
21
+ }
22
+
23
+ export function reviewUploadSecurity(source, format, dist, signal) {
24
+ try {
25
+ const findings = scanUploadFiles(uploadedFiles(source,format,dist),{ signal });
26
+ return { passed:findings.length === 0,findings };
27
+ } catch {
28
+ signal?.throwIfAborted();
29
+ const error = new Error('上传安全检查未能完成。请重新运行游戏检查,排查源码或构建产物读取错误。');
30
+ error.detail = { code:'UPLOAD_SECURITY_CHECK_FAILED' };
31
+ throw error;
32
+ }
33
+ }
34
+
35
+ export function assertUploadSecurity(source, format, dist, signal) {
36
+ const review = reviewUploadSecurity(source,format,dist,signal);
37
+ if (review.passed) return;
38
+ const error = new Error('上传安全检查未通过。请修复 findings 列出的风险后重新检查。');
39
+ error.detail = { code:'UPLOAD_SECURITY_BLOCKED',findings:review.findings };
40
+ throw error;
41
+ }