@stmcw1/dacw 1.0.1 → 1.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.
package/dist/runner.js CHANGED
@@ -1,25 +1,19 @@
1
1
  import { spawn, ChildProcess } from 'child_process';
2
2
  import * as path from 'path';
3
3
  import * as fsSync from 'fs';
4
+ import * as fs from 'fs/promises';
5
+ import * as os from 'os';
6
+ import * as crypto from 'crypto';
4
7
  import { StringDecoder } from 'string_decoder';
8
+ import { TEST_TOOL_WHITELIST, buildDockerRunArgv, defaultImageForCommand, newContainerName, resolveDockerExecutable } from './sandbox.js';
9
+ import { redactSecretsInText } from './secrets.js';
5
10
  export class Runner {
6
11
  workspaceDir;
12
+ policy;
7
13
  MAX_OUTPUT_CHARS = 50_000;
8
14
  HARD_LIMIT_CHARS = 100_000;
9
15
  KILL_GRACE_MS = 2_000;
10
16
  EXIT_GRACE_MS = 1_500;
11
- ALLOWED_CMDS = [
12
- 'npm',
13
- 'pnpm',
14
- 'yarn',
15
- 'npx',
16
- 'node',
17
- 'python',
18
- 'python3',
19
- 'pytest',
20
- 'cargo',
21
- 'go'
22
- ];
23
17
  static CMD_META = /[&|<>^%!"\r\n]/;
24
18
  static SHIM_CLI = {
25
19
  npm: [
@@ -47,8 +41,11 @@ export class Runner {
47
41
  'yarn.js'
48
42
  ]
49
43
  };
50
- constructor(workspaceDir){
44
+ constructor(workspaceDir, policy = {
45
+ kind: 'host'
46
+ }){
51
47
  this.workspaceDir = path.resolve(workspaceDir);
48
+ this.policy = policy;
52
49
  }
53
50
  resolveCommandPath(bareName) {
54
51
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(bareName)) {
@@ -96,42 +93,8 @@ export class Runner {
96
93
  if (c >= 0xDC00 && c <= 0xDFFF) cut = cut.slice(1);
97
94
  return cut;
98
95
  }
99
- run(command, args, timeoutMs = 60000) {
100
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
101
- timeoutMs = 60000;
102
- }
103
- const cmdBase = command.replace(/\.(cmd|exe|bat)$/i, '').toLowerCase();
104
- if (!this.ALLOWED_CMDS.includes(cmdBase)) {
105
- return Promise.resolve({
106
- success: false,
107
- exitCode: null,
108
- output: `[安全拦截] 运行机拒绝执行未授权命令:${command}`,
109
- timedOut: false,
110
- truncated: false
111
- });
112
- }
113
- const resolution = this.resolveCommandPath(cmdBase);
114
- if (!resolution.ok) {
115
- return Promise.resolve({
116
- success: false,
117
- exitCode: null,
118
- output: `[安全拦截] ${resolution.reason}`,
119
- timedOut: false,
120
- truncated: false
121
- });
122
- }
123
- const isWin = process.platform === 'win32';
124
- const useCmdShim = isWin && resolution.absPath.toLowerCase().endsWith('.cmd');
125
- if (useCmdShim && args.some((a)=>Runner.CMD_META.test(a))) {
126
- return Promise.resolve({
127
- success: false,
128
- exitCode: null,
129
- output: `[安全拦截] 参数包含 cmd 元字符,拒绝执行:${args.join(' ')}`,
130
- timedOut: false,
131
- truncated: false
132
- });
133
- }
134
- const childEnv = {
96
+ buildChildEnv() {
97
+ return {
135
98
  PATH: process.env.PATH || '',
136
99
  SYSTEMROOT: process.env.SYSTEMROOT || '',
137
100
  SYSTEMDRIVE: process.env.SYSTEMDRIVE || '',
@@ -146,51 +109,146 @@ export class Runner {
146
109
  LC_ALL: 'en_US.UTF-8',
147
110
  PYTHONIOENCODING: 'utf-8'
148
111
  };
149
- return new Promise((resolve)=>{
150
- let child;
151
- try {
152
- if (useCmdShim) {
153
- const cliParts = Runner.SHIM_CLI[cmdBase];
154
- const cliJs = cliParts ? path.join(path.dirname(resolution.absPath), ...cliParts) : null;
155
- const nodeRes = cliJs && fsSync.existsSync(cliJs) ? this.resolveCommandPath('node') : null;
156
- if (cliJs && nodeRes && nodeRes.ok) {
157
- child = spawn(nodeRes.absPath, [
158
- cliJs,
159
- ...args
112
+ }
113
+ rejected(output) {
114
+ return Promise.resolve({
115
+ success: false,
116
+ exitCode: null,
117
+ output,
118
+ timedOut: false,
119
+ truncated: false
120
+ });
121
+ }
122
+ run(command, args, timeoutMs = 60000) {
123
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
124
+ timeoutMs = 60000;
125
+ }
126
+ const cmdBase = command.replace(/\.(cmd|exe|bat)$/i, '').toLowerCase();
127
+ if (!TEST_TOOL_WHITELIST.includes(cmdBase)) {
128
+ return this.rejected(`[安全拦截] 运行机拒绝执行未授权命令:${command}`);
129
+ }
130
+ if (this.policy.kind === 'blocked') {
131
+ return this.rejected(`[安全拦截] 测试未执行(沙箱不可用,fail-closed):${this.policy.reason}\n` + '你选择了容器模式(sandbox.mode="auto"/"docker"),当前环境无法提供容器,运行机拒绝执行测试。\n' + '处理方式:安装/启动 Docker;或改用 sandbox.mode: "host"(宿主直执,无隔离)接受宿主执行。');
132
+ }
133
+ if (this.policy.kind === 'docker') {
134
+ return this.runDocker(cmdBase, args, timeoutMs);
135
+ }
136
+ return this.runHost(cmdBase, args, timeoutMs);
137
+ }
138
+ async runHost(cmdBase, args, timeoutMs) {
139
+ const resolution = this.resolveCommandPath(cmdBase);
140
+ if (!resolution.ok) {
141
+ return this.rejected(`[安全拦截] ${resolution.reason}`);
142
+ }
143
+ const isWin = process.platform === 'win32';
144
+ const useCmdShim = isWin && resolution.absPath.toLowerCase().endsWith('.cmd');
145
+ if (useCmdShim && args.some((a)=>Runner.CMD_META.test(a))) {
146
+ return this.rejected(`[安全拦截] 参数包含 cmd 元字符,拒绝执行:${args.join(' ')}`);
147
+ }
148
+ let file;
149
+ let argv;
150
+ if (useCmdShim) {
151
+ const cliParts = Runner.SHIM_CLI[cmdBase];
152
+ const cliJs = cliParts ? path.join(path.dirname(resolution.absPath), ...cliParts) : null;
153
+ const nodeRes = cliJs && fsSync.existsSync(cliJs) ? this.resolveCommandPath('node') : null;
154
+ if (cliJs && nodeRes && nodeRes.ok) {
155
+ file = nodeRes.absPath;
156
+ argv = [
157
+ cliJs,
158
+ ...args
159
+ ];
160
+ } else {
161
+ return this.rejected(`[安全拦截] 无法安全执行 ${cmdBase}:找不到底层的 JS 入口或 node 命令。为防工作区注入,已拒绝 cmd.exe 回退。`);
162
+ }
163
+ } else {
164
+ file = resolution.absPath;
165
+ argv = args;
166
+ }
167
+ return this.spawnAndCollect({
168
+ file,
169
+ args: argv,
170
+ cwd: this.workspaceDir,
171
+ env: this.buildChildEnv(),
172
+ timeoutMs,
173
+ detachGroup: process.platform !== 'win32'
174
+ });
175
+ }
176
+ async runDocker(cmdBase, args, timeoutMs) {
177
+ if (this.policy.kind !== 'docker') return this.rejected('[运行机错误] runDocker 在非 docker 策略下被调用');
178
+ const image = this.policy.image.trim() || defaultImageForCommand(cmdBase);
179
+ const dockerRes = resolveDockerExecutable(this.workspaceDir);
180
+ if (!dockerRes.ok) {
181
+ return this.rejected(`[安全拦截] Docker 不可用,测试未执行:${dockerRes.reason}`);
182
+ }
183
+ const staging = path.join(os.tmpdir(), `dacw-sandbox-${crypto.randomBytes(8).toString('hex')}`);
184
+ try {
185
+ await fs.cp(this.workspaceDir, staging, {
186
+ recursive: true,
187
+ filter: (src)=>{
188
+ const base = path.basename(src);
189
+ return base !== '.git' && base !== '.dacw-workspace';
190
+ }
191
+ });
192
+ } catch (e) {
193
+ await fs.rm(staging, {
194
+ recursive: true,
195
+ force: true
196
+ }).catch(()=>{});
197
+ return this.rejected(`[安全拦截] 复制工作区到一次性暂存目录失败,测试未执行:${e?.message ?? String(e)}`);
198
+ }
199
+ const containerName = newContainerName();
200
+ const argv = buildDockerRunArgv({
201
+ image,
202
+ memoryMb: this.policy.memoryMb,
203
+ cpus: this.policy.cpus,
204
+ pidsLimit: this.policy.pidsLimit,
205
+ tmpfsMb: this.policy.tmpfsMb
206
+ }, staging, containerName, cmdBase, args);
207
+ try {
208
+ return await this.spawnAndCollect({
209
+ file: dockerRes.absPath,
210
+ args: argv,
211
+ cwd: this.workspaceDir,
212
+ env: this.buildChildEnv(),
213
+ timeoutMs,
214
+ detachGroup: false,
215
+ extraKill: ()=>{
216
+ try {
217
+ spawn(dockerRes.absPath, [
218
+ 'rm',
219
+ '-f',
220
+ containerName
160
221
  ], {
161
- cwd: this.workspaceDir,
162
- env: childEnv,
163
- shell: false,
222
+ stdio: 'ignore',
164
223
  windowsHide: true,
165
- stdio: [
166
- 'ignore',
167
- 'pipe',
168
- 'pipe'
169
- ]
170
- });
171
- } else {
172
- return resolve({
173
- success: false,
174
- exitCode: null,
175
- output: `[安全拦截] 无法安全执行 ${cmdBase}:找不到底层的 JS 入口或 node 命令。为防工作区注入,已拒绝 cmd.exe 回退。`,
176
- timedOut: false,
177
- truncated: false
178
- });
179
- }
180
- } else {
181
- child = spawn(resolution.absPath, args, {
182
- cwd: this.workspaceDir,
183
- env: childEnv,
184
- shell: false,
185
- detached: process.platform !== 'win32',
186
- windowsHide: true,
187
- stdio: [
188
- 'ignore',
189
- 'pipe',
190
- 'pipe'
191
- ]
192
- });
224
+ shell: false
225
+ }).unref?.();
226
+ } catch {}
193
227
  }
228
+ });
229
+ } finally{
230
+ await fs.rm(staging, {
231
+ recursive: true,
232
+ force: true
233
+ }).catch(()=>{});
234
+ }
235
+ }
236
+ spawnAndCollect(opts) {
237
+ return new Promise((resolve)=>{
238
+ let child;
239
+ try {
240
+ child = spawn(opts.file, opts.args, {
241
+ cwd: opts.cwd,
242
+ env: opts.env,
243
+ shell: false,
244
+ detached: opts.detachGroup,
245
+ windowsHide: true,
246
+ stdio: [
247
+ 'ignore',
248
+ 'pipe',
249
+ 'pipe'
250
+ ]
251
+ });
194
252
  } catch (syncErr) {
195
253
  return resolve({
196
254
  success: false,
@@ -200,6 +258,7 @@ export class Runner {
200
258
  truncated: false
201
259
  });
202
260
  }
261
+ const timeoutMs = opts.timeoutMs;
203
262
  let output = '';
204
263
  let truncated = false;
205
264
  let timedOut = false;
@@ -257,7 +316,7 @@ export class Runner {
257
316
  child.kill('SIGKILL');
258
317
  } catch {}
259
318
  });
260
- } else {
319
+ } else if (opts.detachGroup) {
261
320
  try {
262
321
  process.kill(-child.pid, 'SIGKILL');
263
322
  } catch {
@@ -265,7 +324,14 @@ export class Runner {
265
324
  child.kill('SIGKILL');
266
325
  } catch {}
267
326
  }
327
+ } else {
328
+ try {
329
+ child.kill('SIGKILL');
330
+ } catch {}
268
331
  }
332
+ try {
333
+ opts.extraKill?.();
334
+ } catch {}
269
335
  };
270
336
  const finalize = ()=>{
271
337
  if (settled) return;
@@ -291,6 +357,7 @@ export class Runner {
291
357
  if (timedOut) {
292
358
  finalOutput += `\n[执行超时 ${timeoutMs}ms,运行机已强杀进程树;exitCode=${exitCode ?? 'null'}, signal=${exitSignal ?? 'none'}]`;
293
359
  }
360
+ finalOutput = redactSecretsInText(finalOutput);
294
361
  resolve({
295
362
  success: !timedOut && exitCode === 0,
296
363
  exitCode,
@@ -0,0 +1,297 @@
1
+ import { spawn } from 'child_process';
2
+ import * as path from 'path';
3
+ import * as fsSync from 'fs';
4
+ import * as crypto from 'crypto';
5
+ export const TEST_TOOL_WHITELIST = [
6
+ 'npm',
7
+ 'pnpm',
8
+ 'yarn',
9
+ 'npx',
10
+ 'node',
11
+ 'python',
12
+ 'python3',
13
+ 'pytest',
14
+ 'cargo',
15
+ 'go'
16
+ ];
17
+ export const SANDBOX_MODES = [
18
+ 'auto',
19
+ 'docker',
20
+ 'host'
21
+ ];
22
+ export const DEFAULT_SANDBOX_CONFIG = {
23
+ mode: 'host',
24
+ image: '',
25
+ memoryMb: 1024,
26
+ cpus: 1,
27
+ pidsLimit: 256,
28
+ tmpfsMb: 128
29
+ };
30
+ export function buildSandboxConsentRequest(plan) {
31
+ return {
32
+ title: '沙盒不可用',
33
+ message: '未检测到可用的沙盒隔离环境(如 Docker 未安装或未启动)。是否关闭沙盒模式并继续?',
34
+ detail: `检测结果(sandbox.mode="${plan.mode}"):${plan.reason}`,
35
+ options: [
36
+ {
37
+ id: 'keep_sandbox',
38
+ label: '保持沙盒(取消本次运行)',
39
+ description: '不会在宿主上执行任何测试代码;安装/启动 Docker 后可重试。'
40
+ },
41
+ {
42
+ id: 'disable_sandbox',
43
+ label: '关闭沙盒并继续',
44
+ description: '本次运行的测试将以宿主用户全权限执行,AI 生成的代码会直接接触宿主系统(安全降级,结果会标注)。'
45
+ }
46
+ ]
47
+ };
48
+ }
49
+ export function parseSandboxConsentAnswer(answer, request, questionId = 'dacw-sandbox-consent') {
50
+ if (!answer || typeof answer !== 'object') return {
51
+ decision: 'keep_sandbox'
52
+ };
53
+ const answers = answer.answers;
54
+ if (!Array.isArray(answers)) return {
55
+ decision: 'keep_sandbox'
56
+ };
57
+ const hit = answers.find((item)=>item && item.id === questionId);
58
+ if (!hit || !Array.isArray(hit.selected)) return {
59
+ decision: 'keep_sandbox'
60
+ };
61
+ const selectedLabels = hit.selected.filter((label)=>typeof label === 'string');
62
+ const disableOption = request.options.find((option)=>option.id === 'disable_sandbox');
63
+ const keepOption = request.options.find((option)=>option.id === 'keep_sandbox');
64
+ if (disableOption && selectedLabels.includes(disableOption.label)) return {
65
+ decision: 'disable_sandbox'
66
+ };
67
+ if (keepOption && selectedLabels.includes(keepOption.label)) return {
68
+ decision: 'keep_sandbox'
69
+ };
70
+ return {
71
+ decision: 'keep_sandbox'
72
+ };
73
+ }
74
+ function pushWarning(warnings, prefix, message) {
75
+ warnings.push(prefix ? `${prefix}.${message}` : message);
76
+ }
77
+ function positiveIntOr(value, fallback, warnings, prefix, field) {
78
+ if (value === undefined || value === null) return fallback;
79
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) return Math.floor(value);
80
+ pushWarning(warnings, prefix, `${field} 非法(需要正数),已回退默认值 ${fallback}`);
81
+ return fallback;
82
+ }
83
+ function positiveNumberOr(value, fallback, warnings, prefix, field) {
84
+ if (value === undefined || value === null) return fallback;
85
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;
86
+ pushWarning(warnings, prefix, `${field} 非法(需要正数),已回退默认值 ${fallback}`);
87
+ return fallback;
88
+ }
89
+ export function normalizeSandboxConfig(raw, warnings, prefix) {
90
+ const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
91
+ let mode = input.mode;
92
+ if (mode === undefined || mode === null) mode = DEFAULT_SANDBOX_CONFIG.mode;
93
+ if (typeof mode !== 'string' || !SANDBOX_MODES.includes(mode)) {
94
+ pushWarning(warnings, prefix, `mode 非法(只接受 ${SANDBOX_MODES.join(' / ')}),已回退 "${DEFAULT_SANDBOX_CONFIG.mode}"`);
95
+ mode = DEFAULT_SANDBOX_CONFIG.mode;
96
+ }
97
+ let image = input.image;
98
+ if (image === undefined || image === null) image = DEFAULT_SANDBOX_CONFIG.image;
99
+ if (typeof image !== 'string') {
100
+ pushWarning(warnings, prefix, 'image 非法(需要字符串),已回退默认值(按测试命令自动选择镜像)');
101
+ image = DEFAULT_SANDBOX_CONFIG.image;
102
+ }
103
+ return {
104
+ mode: mode,
105
+ image: image.trim(),
106
+ memoryMb: positiveIntOr(input.memoryMb, DEFAULT_SANDBOX_CONFIG.memoryMb, warnings, prefix, 'memoryMb'),
107
+ cpus: positiveNumberOr(input.cpus, DEFAULT_SANDBOX_CONFIG.cpus, warnings, prefix, 'cpus'),
108
+ pidsLimit: positiveIntOr(input.pidsLimit, DEFAULT_SANDBOX_CONFIG.pidsLimit, warnings, prefix, 'pidsLimit'),
109
+ tmpfsMb: positiveIntOr(input.tmpfsMb, DEFAULT_SANDBOX_CONFIG.tmpfsMb, warnings, prefix, 'tmpfsMb')
110
+ };
111
+ }
112
+ export function defaultImageForCommand(command) {
113
+ switch(command){
114
+ case 'python':
115
+ case 'python3':
116
+ case 'pytest':
117
+ return 'python:3.12-slim';
118
+ case 'cargo':
119
+ return 'rust:1-slim';
120
+ case 'go':
121
+ return 'golang:1.23-bookworm';
122
+ default:
123
+ return 'node:22-bookworm-slim';
124
+ }
125
+ }
126
+ export function buildDockerRunArgv(policy, stagingDir, containerName, command, args) {
127
+ return [
128
+ 'run',
129
+ '--rm',
130
+ '--pull=missing',
131
+ '--name',
132
+ containerName,
133
+ '--network',
134
+ 'none',
135
+ '--memory',
136
+ `${policy.memoryMb}m`,
137
+ '--memory-swap',
138
+ `${policy.memoryMb}m`,
139
+ '--cpus',
140
+ String(policy.cpus),
141
+ '--pids-limit',
142
+ String(policy.pidsLimit),
143
+ '--read-only',
144
+ '--tmpfs',
145
+ `/tmp:rw,nosuid,size=${policy.tmpfsMb}m`,
146
+ '--cap-drop',
147
+ 'ALL',
148
+ '--security-opt',
149
+ 'no-new-privileges',
150
+ '--user',
151
+ '1000:1000',
152
+ '-e',
153
+ 'HOME=/tmp',
154
+ '-e',
155
+ 'CI=1',
156
+ '-e',
157
+ 'npm_config_update_notifier=false',
158
+ '--volume',
159
+ `${stagingDir}:/dacw`,
160
+ '--workdir',
161
+ '/dacw',
162
+ '--init',
163
+ policy.image,
164
+ command,
165
+ ...args
166
+ ];
167
+ }
168
+ export function describePolicy(policy) {
169
+ if (policy.kind === 'docker') {
170
+ return `一次性 Docker 容器(image=${policy.image || '按测试命令自动选择'};无网络、只读根文件系统、非 root、` + `cap-drop ALL、内存 ${policy.memoryMb}MB、CPU ${policy.cpus}、进程数上限 ${policy.pidsLimit})`;
171
+ }
172
+ if (policy.kind === 'host') {
173
+ return '宿主直接执行(无隔离):写手产出的代码将以宿主用户全权限运行';
174
+ }
175
+ return `已拒绝执行测试(fail-closed):${policy.reason}`;
176
+ }
177
+ export function resolveDockerExecutable(excludeDir) {
178
+ const isWin = process.platform === 'win32';
179
+ const candidates = isWin ? [
180
+ 'docker.exe'
181
+ ] : [
182
+ 'docker'
183
+ ];
184
+ const pathDirs = (process.env.PATH || '').split(isWin ? ';' : ':').map((d)=>d.trim().replace(/^"|"$/g, '')).filter((d)=>d.length > 0);
185
+ const excluded = path.resolve(excludeDir && excludeDir.trim() ? excludeDir : process.cwd());
186
+ const excludedLower = isWin ? excluded.toLowerCase() : excluded;
187
+ for (const dir of pathDirs){
188
+ const resolved = path.resolve(dir);
189
+ const resolvedLower = isWin ? resolved.toLowerCase() : resolved;
190
+ if (resolvedLower === excludedLower || resolvedLower.startsWith(excludedLower + path.sep)) continue;
191
+ for (const cand of candidates){
192
+ const full = path.join(resolved, cand);
193
+ try {
194
+ fsSync.accessSync(full, fsSync.constants.X_OK);
195
+ return {
196
+ ok: true,
197
+ absPath: path.resolve(full)
198
+ };
199
+ } catch {}
200
+ }
201
+ }
202
+ return {
203
+ ok: false,
204
+ reason: 'PATH 上未找到 docker 可执行文件(工作区目录已从搜索范围排除)'
205
+ };
206
+ }
207
+ export function detectDocker(timeoutMs = 4000) {
208
+ const resolution = resolveDockerExecutable();
209
+ if (!resolution.ok) return Promise.resolve({
210
+ ok: false,
211
+ reason: resolution.reason
212
+ });
213
+ return new Promise((resolve)=>{
214
+ let child;
215
+ try {
216
+ child = spawn(resolution.absPath, [
217
+ 'version',
218
+ '--format',
219
+ '{{.Server.Version}}'
220
+ ], {
221
+ stdio: [
222
+ 'ignore',
223
+ 'pipe',
224
+ 'pipe'
225
+ ],
226
+ windowsHide: true,
227
+ shell: false
228
+ });
229
+ } catch (e) {
230
+ resolve({
231
+ ok: false,
232
+ reason: `docker 探测进程启动失败:${e?.message ?? String(e)}`
233
+ });
234
+ return;
235
+ }
236
+ let output = '';
237
+ let settled = false;
238
+ const done = (result)=>{
239
+ if (settled) return;
240
+ settled = true;
241
+ clearTimeout(timer);
242
+ try {
243
+ child.kill();
244
+ } catch {}
245
+ resolve(result);
246
+ };
247
+ const timer = setTimeout(()=>{
248
+ done({
249
+ ok: false,
250
+ reason: 'docker version 探测超时(守护进程无响应?)'
251
+ });
252
+ }, timeoutMs);
253
+ child.stdout?.on('data', (d)=>{
254
+ output += d.toString('utf8');
255
+ });
256
+ child.stderr?.on('data', ()=>{});
257
+ child.on('error', (err)=>done({
258
+ ok: false,
259
+ reason: `docker 探测失败:${err.message}`
260
+ }));
261
+ child.on('close', (code)=>{
262
+ const version = output.trim();
263
+ if (code === 0 && version) done({
264
+ ok: true,
265
+ version
266
+ });
267
+ else done({
268
+ ok: false,
269
+ reason: `docker version 退出码 ${code ?? 'null'}(Docker 未安装或守护进程未启动)`
270
+ });
271
+ });
272
+ });
273
+ }
274
+ export async function resolveExecutionPolicy(config, detect = detectDocker) {
275
+ if (config.mode === 'host') return {
276
+ kind: 'host'
277
+ };
278
+ const detection = await detect();
279
+ if (detection.ok) {
280
+ return {
281
+ kind: 'docker',
282
+ image: config.image,
283
+ memoryMb: config.memoryMb,
284
+ cpus: config.cpus,
285
+ pidsLimit: config.pidsLimit,
286
+ tmpfsMb: config.tmpfsMb
287
+ };
288
+ }
289
+ return {
290
+ kind: 'blocked',
291
+ reason: detection.reason,
292
+ mode: config.mode
293
+ };
294
+ }
295
+ export function newContainerName() {
296
+ return `dacw-${crypto.randomBytes(6).toString('hex')}`;
297
+ }
@@ -0,0 +1,42 @@
1
+ export const SECRET_PATTERNS = [
2
+ {
3
+ category: 'PEM 私钥',
4
+ re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/
5
+ },
6
+ {
7
+ category: 'AWS Access Key',
8
+ re: /AKIA[0-9A-Z]{16}/
9
+ },
10
+ {
11
+ category: 'GitHub Token',
12
+ re: /ghp_[A-Za-z0-9]{36}/
13
+ },
14
+ {
15
+ category: 'Slack Token',
16
+ re: /xox[baprs]-[A-Za-z0-9-]{10,}/
17
+ },
18
+ {
19
+ category: 'OpenAI Key',
20
+ re: /sk-[A-Za-z0-9]{32,}/
21
+ }
22
+ ];
23
+ export function scanWriterOutputForSecrets(delta) {
24
+ for (const item of delta.changed){
25
+ for (const pattern of SECRET_PATTERNS){
26
+ if (pattern.re.test(item.code)) return {
27
+ file: item.file,
28
+ category: pattern.category
29
+ };
30
+ }
31
+ }
32
+ return null;
33
+ }
34
+ export function redactSecretsInText(text) {
35
+ if (!text) return text;
36
+ let redacted = text;
37
+ for (const { category, re } of SECRET_PATTERNS){
38
+ const flags = re.flags.includes('g') ? re.flags : `${re.flags}g`;
39
+ redacted = redacted.replace(new RegExp(re.source, flags), `[REDACTED:${category}]`);
40
+ }
41
+ return redacted;
42
+ }