@morlay/configurable-sandbox 0.0.0-stage → 0.2.0-alpha.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/src/rules.ts ADDED
@@ -0,0 +1,228 @@
1
+ // 沙箱规则:`access` 条目的解析、编译与命中判定。
2
+ //
3
+ // 三类前缀:`rw <路径>` 追加可写根、`r- <路径>` 只读、`-- <路径>` 拒绝。路径支持 `{{ env.NAME }}`
4
+ // 与 glob;`rw` 必须是具体路径(可写根没有通配语义)。相对路径相对**会话工作区**解析。
5
+ import { isAbsolute, resolve, sep } from "node:path";
6
+ import { canonicalPath, writableRoots } from "@morlay/dsh-sandbox/contract";
7
+ import type { SandboxExecutionPolicy } from "@morlay/dsh-sandbox/contract";
8
+
9
+ const ENV_TEMPLATE = /\{\{\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;
10
+
11
+ const ACCESS_LINE = /^(rw|r-|--)(?:\s+(.*))?$/u;
12
+
13
+ const GLOB_META = /[*?[]/;
14
+
15
+ const REGEX_META = /[\\^$+.(){}|]/;
16
+
17
+ export function expandEnvTemplates(value: string, env: NodeJS.ProcessEnv): string {
18
+ return value.replace(ENV_TEMPLATE, (_match, name: string) => {
19
+ const resolved = env[name];
20
+ if (resolved === undefined || resolved.length === 0) {
21
+ throw new Error(
22
+ `sandbox rules: "${value}" references the unset environment variable "${name}"`,
23
+ );
24
+ }
25
+ return resolved;
26
+ });
27
+ }
28
+
29
+ export function globToRegexSource(pattern: string): string {
30
+ let source = "";
31
+ for (let index = 0; index < pattern.length; index += 1) {
32
+ const char = pattern[index] as string;
33
+ if (char === "*") {
34
+ if (pattern[index + 1] === "*") {
35
+ index += 1;
36
+ if (pattern[index + 1] === "/") {
37
+ index += 1;
38
+ source += "(.*/)?";
39
+ } else {
40
+ source += ".*";
41
+ }
42
+ } else {
43
+ source += "[^/]*";
44
+ }
45
+ continue;
46
+ }
47
+ if (char === "?") {
48
+ source += "[^/]";
49
+ continue;
50
+ }
51
+ if (char === "[") {
52
+ const close = pattern.indexOf("]", index + 1);
53
+ if (close === -1) {
54
+ source += "\\[";
55
+ continue;
56
+ }
57
+ const body = pattern.slice(index + 1, close);
58
+ if (body.length === 0) {
59
+ source += "\\[\\]";
60
+ index = close;
61
+ continue;
62
+ }
63
+ source += body.startsWith("!") ? `[^${body.slice(1)}]` : `[${body}]`;
64
+ index = close;
65
+ continue;
66
+ }
67
+ source += REGEX_META.test(char) ? `\\${char}` : char;
68
+ }
69
+ return source;
70
+ }
71
+
72
+ export interface RuleSource {
73
+ readonly allowWrite: readonly string[];
74
+
75
+ readonly readOnly: readonly string[];
76
+
77
+ readonly deny: readonly string[];
78
+ }
79
+
80
+ export interface CompiledPattern {
81
+ readonly source: string;
82
+
83
+ readonly regex: RegExp;
84
+ }
85
+
86
+ export interface CompiledRules {
87
+ readonly allowRoots: readonly string[];
88
+
89
+ readonly readOnlySubtrees: readonly string[];
90
+
91
+ readonly readOnlyPatterns: readonly CompiledPattern[];
92
+
93
+ readonly denySubtrees: readonly string[];
94
+
95
+ readonly denyPatterns: readonly CompiledPattern[];
96
+ }
97
+
98
+ export function isEmptyRules(rules: CompiledRules): boolean {
99
+ return (
100
+ rules.allowRoots.length === 0 &&
101
+ rules.readOnlySubtrees.length === 0 &&
102
+ rules.readOnlyPatterns.length === 0 &&
103
+ rules.denySubtrees.length === 0 &&
104
+ rules.denyPatterns.length === 0
105
+ );
106
+ }
107
+
108
+ export function withoutAllowRoots(rules: CompiledRules): CompiledRules {
109
+ return rules.allowRoots.length === 0 ? rules : { ...rules, allowRoots: [] };
110
+ }
111
+
112
+ export function parseAccess(input: string | readonly string[] | undefined): RuleSource {
113
+ const lines = (input === undefined ? [] : typeof input === "string" ? [input] : [...input])
114
+ .flatMap((value) => value.split(/\r?\n/u))
115
+ .map((line) => line.trim())
116
+ .filter((line) => line.length > 0);
117
+ const allowWrite: string[] = [];
118
+ const readOnly: string[] = [];
119
+ const deny: string[] = [];
120
+ for (const line of lines) {
121
+ const match = ACCESS_LINE.exec(line);
122
+ if (match === null) {
123
+ throw new Error(
124
+ `sandbox rules: access entry ${JSON.stringify(line)} must start with "rw " (write), "r- " (read-only) or "-- " (deny)`,
125
+ );
126
+ }
127
+ const rule = (match[2] ?? "").trim();
128
+ if (rule.length === 0) {
129
+ throw new Error(`sandbox rules: access entry ${JSON.stringify(line)} carries no path`);
130
+ }
131
+ if (match[1] === "rw") allowWrite.push(rule);
132
+ else if (match[1] === "r-") readOnly.push(rule);
133
+ else deny.push(rule);
134
+ }
135
+ return { allowWrite, readOnly, deny };
136
+ }
137
+
138
+ export function ruleSourceOf(
139
+ access: string | readonly string[] | undefined,
140
+ env: NodeJS.ProcessEnv,
141
+ ): RuleSource {
142
+ const parsed = parseAccess(access);
143
+ const expand = (values: readonly string[]): string[] =>
144
+ values.map((value) => expandEnvTemplates(value, env));
145
+ return {
146
+ allowWrite: expand(parsed.allowWrite),
147
+ readOnly: expand(parsed.readOnly),
148
+ deny: expand(parsed.deny),
149
+ };
150
+ }
151
+
152
+ function absolutize(value: string, workspaceRoot: string): string {
153
+ return isAbsolute(value) ? value : resolve(workspaceRoot, value);
154
+ }
155
+
156
+ function compilePaths(
157
+ values: readonly string[],
158
+ workspaceRoot: string,
159
+ ): { subtrees: string[]; patterns: CompiledPattern[] } {
160
+ const subtrees: string[] = [];
161
+ const patterns: CompiledPattern[] = [];
162
+ for (const value of values) {
163
+ const absolute = absolutize(value, workspaceRoot);
164
+ if (GLOB_META.test(value)) {
165
+ const pattern = `^${globToRegexSource(absolute)}$`;
166
+ patterns.push({ source: pattern, regex: new RegExp(pattern) });
167
+ } else {
168
+ subtrees.push(canonicalPath(absolute));
169
+ }
170
+ }
171
+ return { subtrees, patterns };
172
+ }
173
+
174
+ export function compileRules(source: RuleSource, workspaceRoot: string): CompiledRules {
175
+ const allowRoots: string[] = [];
176
+ for (const value of source.allowWrite) {
177
+ if (GLOB_META.test(value)) {
178
+ throw new Error(`sandbox rules: rw entry "${value}" must name a concrete path, not a glob`);
179
+ }
180
+ allowRoots.push(canonicalPath(absolutize(value, workspaceRoot)));
181
+ }
182
+ const readOnly = compilePaths(source.readOnly, workspaceRoot);
183
+ const deny = compilePaths(source.deny, workspaceRoot);
184
+ return {
185
+ allowRoots,
186
+ readOnlySubtrees: readOnly.subtrees,
187
+ readOnlyPatterns: readOnly.patterns,
188
+ denySubtrees: deny.subtrees,
189
+ denyPatterns: deny.patterns,
190
+ };
191
+ }
192
+
193
+ // 本包的可写根:官方那份 + `rw` 条目(只在 `workspace-write` 下追加)。
194
+ export function writableRootsWith(
195
+ rules: CompiledRules,
196
+ policy: SandboxExecutionPolicy,
197
+ ): readonly string[] {
198
+ const roots = writableRoots(policy);
199
+ return policy.mode === "workspace-write" ? [...roots, ...rules.allowRoots] : roots;
200
+ }
201
+
202
+ function isUnder(path: string, root: string): boolean {
203
+ if (path === root) return true;
204
+ return path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
205
+ }
206
+
207
+ function matches(
208
+ canonicalTarget: string,
209
+ subtrees: readonly string[],
210
+ patterns: readonly CompiledPattern[],
211
+ ): boolean {
212
+ for (const subtree of subtrees) {
213
+ if (isUnder(canonicalTarget, subtree)) return true;
214
+ }
215
+ return patterns.some((pattern) => pattern.regex.test(canonicalTarget));
216
+ }
217
+
218
+ export function isDenied(rules: CompiledRules, canonicalTarget: string): boolean {
219
+ return matches(canonicalTarget, rules.denySubtrees, rules.denyPatterns);
220
+ }
221
+
222
+ export function isReadOnly(rules: CompiledRules, canonicalTarget: string): boolean {
223
+ return matches(canonicalTarget, rules.readOnlySubtrees, rules.readOnlyPatterns);
224
+ }
225
+
226
+ export function blocksWrite(rules: CompiledRules, canonicalTarget: string): boolean {
227
+ return isDenied(rules, canonicalTarget) || isReadOnly(rules, canonicalTarget);
228
+ }
@@ -0,0 +1,125 @@
1
+ // 运行时上下文的接管:本部署换了沙箱实现,模型看到的两段策略文本也要跟着换、换成中文。
2
+ //
3
+ // 上游在**全局层**注册 `sandbox:policy`(`@deepseek-ai/dsh-sandbox-policy`)与 `approval:policy`
4
+ // (`@deepseek-ai/dsh-user-approval`)。全局层同名注册会抛错,上游给的官方路径是**按 agent 作用域覆盖**:
5
+ // 在 agent 自己的 `ctx` 上注册同名 context,装配时近的作用域遮蔽全局那条;agentless 装配保持上游那条。
6
+ //
7
+ // 注册点必须是 `agent.ctx.get("systemPrompt")` 而不是注入来的那个实例:`context()` 的 scope 取自调用的
8
+ // ctx,注入实例绑定的是**本行** ctx,在它上面注册只会落在全局层(与上游那条撞名抛错)。
9
+ //
10
+ // 时机必须是 agent 创建时:`SystemPrompt.assemble()` 先把 `contexts` merge 好、再进瀑布,
11
+ // 挂在瀑布里注册只能从第二次装配起生效(会话里表现为"先英文后中文")。
12
+ import type { Agent } from "@morlay/dsh-agent/contract";
13
+ import type { ApprovalPolicy } from "@morlay/dsh-permission/contract";
14
+ import { SandboxPolicy } from "@morlay/dsh-sandbox";
15
+ import { inject, Injectable, type Context, type OnInit } from "@morlay/zephyr";
16
+ import { SandboxRules } from "./contract/sandbox-rules.contract.ts";
17
+ import { AgentCreated } from "./events.ts";
18
+ import {
19
+ APPROVAL_POLICY_CONTEXT,
20
+ SANDBOX_POLICY_CONTEXT,
21
+ renderApprovalContext,
22
+ renderPolicyContext,
23
+ } from "./policy-text.ts";
24
+
25
+ // 提示词注册面(`ctx.get("systemPrompt")` 的读面):只声明两条注册入口与两个 order 读取。
26
+ interface PromptRegistry {
27
+ context(context: {
28
+ readonly name: string;
29
+ readonly order: number;
30
+ readonly text: (context: unknown) => string;
31
+ }): () => void;
32
+ getContextOrder(name: string): number;
33
+ }
34
+
35
+ // 一次装配的上下文入参(本包只读 agent)。
36
+ interface AssembleContextLike {
37
+ readonly agent?: { readonly session: { readonly id: string }; readonly ctx: Context };
38
+ }
39
+
40
+ // 上游 `ApprovalService` 的公开面:`overrideOf`(会话日志里最后一条 `approval/policy`)与 `config.policy`。
41
+ interface ApprovalSource {
42
+ overrideOf(session: { readonly id: string }): ApprovalPolicy | undefined;
43
+ readonly config: { readonly policy?: ApprovalPolicy };
44
+ }
45
+
46
+ // 某个会话此刻生效的审批策略:override 优先,否则部署默认,再退 `ask`。
47
+ function effectiveApprovalPolicy(
48
+ approval: ApprovalSource,
49
+ session: { readonly id: string },
50
+ ): ApprovalPolicy {
51
+ return approval.overrideOf(session) ?? approval.config.policy ?? "ask";
52
+ }
53
+
54
+ @Injectable()
55
+ export class SandboxRuntimeContexts implements OnInit {
56
+ readonly created$ = new AgentCreated();
57
+
58
+ private readonly rules = inject(SandboxRules);
59
+
60
+ private readonly policy = inject(SandboxPolicy);
61
+
62
+ private readonly installed = new WeakSet<Agent>();
63
+
64
+ onInit(ctx: Context): void {
65
+ this.created$.on(({ agent }) => {
66
+ this.install(agent);
67
+ });
68
+ // 本行晚于已有 agent 挂载时(行重挂 / HMR)也要覆盖它们:`agent/created` 不会再为它们发一次。
69
+ for (const agent of this.existingAgents(ctx)) this.install(agent);
70
+ }
71
+
72
+ private existingAgents(ctx: Context): readonly Agent[] {
73
+ const registry = (ctx as unknown as { get(name: string, strict?: boolean): unknown }).get(
74
+ "agents",
75
+ false,
76
+ ) as { list(): readonly Agent[] } | undefined;
77
+ return registry?.list() ?? [];
78
+ }
79
+
80
+ private install(agent: Agent): void {
81
+ if (this.installed.has(agent)) return;
82
+ this.installed.add(agent);
83
+ const prompt = (agent.ctx as unknown as { get(name: string, strict?: boolean): unknown }).get(
84
+ "systemPrompt",
85
+ false,
86
+ ) as PromptRegistry | undefined;
87
+ if (prompt === undefined) return;
88
+ this.registerSandboxPolicy(prompt);
89
+ this.registerApprovalPolicy(prompt);
90
+ }
91
+
92
+ // 在该 agent 的 scope 上注册同名 `sandbox:policy`:装配时遮蔽全局那条。
93
+ private registerSandboxPolicy(prompt: PromptRegistry): void {
94
+ const rules = this.rules.source();
95
+ const policy = this.policy;
96
+ prompt.context({
97
+ name: SANDBOX_POLICY_CONTEXT,
98
+ order: prompt.getContextOrder("SANDBOX_POLICY"),
99
+ text: (context) => {
100
+ const session = (context as AssembleContextLike).agent?.session;
101
+ if (session === undefined) return "";
102
+ return renderPolicyContext(policy.resolve({ session } as never), rules);
103
+ },
104
+ });
105
+ }
106
+
107
+ // 同上,接管 `approval:policy`:文本按会话有效策略选段。
108
+ private registerApprovalPolicy(prompt: PromptRegistry): void {
109
+ prompt.context({
110
+ name: APPROVAL_POLICY_CONTEXT,
111
+ order: prompt.getContextOrder("APPROVAL_POLICY"),
112
+ text: (context) => {
113
+ const current = (context as AssembleContextLike).agent;
114
+ if (current === undefined) return "";
115
+ // 审批能力是可选的(headless 部署可能没装):没装就按"没有这条"读,空串遮蔽不了任何东西。
116
+ const approval = (
117
+ current.ctx as unknown as { get(name: string, strict?: boolean): unknown }
118
+ ).get("approval", false) as ApprovalSource | undefined;
119
+ return approval === undefined
120
+ ? ""
121
+ : renderApprovalContext(effectiveApprovalPolicy(approval, current.session));
122
+ },
123
+ });
124
+ }
125
+ }
@@ -0,0 +1,81 @@
1
+ // 默认读面:`<AppEnv.dataDir>/sandbox.toml`。
2
+ //
3
+ // **文件不存在就写一份默认的**:沙箱的规则不是「空着也能用」——一条 `rw` 都没有时只有工作区可写,
4
+ // 症状是 agent-browser 起不来、`XDG_CACHE_HOME` 写不进去。第一次启动就把可用集合落到文件里,
5
+ // 用户照着改,比让他从空文件猜语法强。
6
+ //
7
+ // 写失败(只读盘、权限)**不影响启动**:内置那份规则仍然生效(读面返回它),只记一条警告——
8
+ // 规则面缺失是产品问题,文件写不进去是环境问题,不该把启动挡住。
9
+ import { readFile, writeFile } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { AppEnv } from "@morlay/zephyr-app";
12
+ import { inject, Injectable, Logger } from "@morlay/zephyr";
13
+ import { SandboxFile } from "./contract/sandbox-file.contract.ts";
14
+ import { defaultSandboxToml } from "./defaults.ts";
15
+
16
+ @Injectable()
17
+ export class SandboxFileDefault extends SandboxFile {
18
+ /**
19
+ * 数据根:`AppEnv` 是**唯一**来源(部署值由装配面给,包内不读进程环境)。
20
+ *
21
+ * 路径必须是 getter:字段初始化那一刻 `inject(AppEnv)` 还是注入占位,把路径在那里算死就永远
22
+ * 拿到占位值(同包 `SandboxRulesDefault` 的惰性状态同一条理由)。
23
+ */
24
+ private readonly appEnv = inject(AppEnv);
25
+
26
+ /** 配置文件路径:`<dataDir>/sandbox.toml`。 */
27
+ get path(): string {
28
+ return join(this.appEnv.values.dataDir, "sandbox.toml");
29
+ }
30
+
31
+ private readonly logger = inject.optional(Logger);
32
+
33
+ /**
34
+ * 诊断:`Logger` 是可选注入(纯规则装配里没有它),缺的时候拿到的是注入占位而不是实例。
35
+ * 这里判一次成员类型,缺了就当没有——诊断丢了不影响规则面正确性。
36
+ */
37
+ private log(level: "info" | "warn", message: string, ...args: unknown[]): void {
38
+ const sink = this.logger as { info?: unknown; warn?: unknown } | undefined;
39
+ const write = sink?.[level];
40
+ if (typeof write === "function") write.call(sink, message, ...args);
41
+ }
42
+
43
+ async read(): Promise<string | undefined> {
44
+ try {
45
+ return await readFile(this.path, "utf8");
46
+ } catch (error) {
47
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
48
+ // 权限、路径是目录这类是环境问题:读成「没配规则」会让沙箱静默退回官方行为,比启动失败更难查。
49
+ throw error;
50
+ }
51
+ }
52
+ return await this.createDefault();
53
+ }
54
+
55
+ /** 首次启动:把默认规则落盘;写不进去就只在内存里用它,并记一条警告。 */
56
+ private async createDefault(): Promise<string> {
57
+ // 默认文本按**本机**的用户目录现算(`{{ env.* }}` 模板会在规则层展开时整份退化,见 `defaults.ts`)。
58
+ const { text, skipped } = defaultSandboxToml(process.env);
59
+ if (skipped.length > 0) {
60
+ // 不给空规则、也不留依赖未设变量的模板:缺哪几条说清,剩下的照旧可用。
61
+ this.log(
62
+ "warn",
63
+ "默认沙箱规则有 %d 条写不出来(环境变量未设:%s),这份文件会缺那几条:%s",
64
+ skipped.length,
65
+ skipped.join(" / "),
66
+ this.path,
67
+ );
68
+ }
69
+ try {
70
+ await writeFile(this.path, text, { encoding: "utf8", flag: "wx" });
71
+ this.log("info", "已创建默认沙箱规则:%s", this.path);
72
+ } catch (error) {
73
+ // `EEXIST`:并发启动时别人先写了,读回来用他的那份。其它错误:内置那份照样生效。
74
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") {
75
+ return await readFile(this.path, "utf8").catch(() => text);
76
+ }
77
+ this.log("warn", "默认沙箱规则写不进去(%s),本次用内置那份:%s", this.path, String(error));
78
+ }
79
+ return text;
80
+ }
81
+ }
@@ -0,0 +1,187 @@
1
+ // 规则的唯一 owner:启动时读一次 `<AppEnv.dataDir>/sandbox.toml`,之后不再变(本部署没有配置页)。
2
+ //
3
+ // 坏配置不阻断启动——用户写坏一份 toml 不该让宿主起不来。四种坏法一个口径:整份配置按"没有规则"处理,
4
+ // 并 warn 一条点名(文件路径 + 坏在哪)。不认识的字段也算坏:多写一个键说明这份文件不是本版本认的形状,
5
+ // 挑一半字段生效比一条都不生效更难查。
6
+ import { inject, Injectable, Logger, type Context, type OnInit } from "@morlay/zephyr";
7
+ import { AppEnv, parseToml } from "@morlay/zephyr-app";
8
+ import { SandboxFile } from "./contract/sandbox-file.contract.ts";
9
+ import { SandboxRules, type SandboxSettings } from "./contract/sandbox-rules.contract.ts";
10
+ import { ruleSourceOf, type RuleSource } from "./rules.ts";
11
+
12
+ // 认得的顶层字段;其余一律按坏配置处理。
13
+ const KNOWN_KEYS: ReadonlySet<string> = new Set([
14
+ "access",
15
+ "runnerCommand",
16
+ "runnerFailureSignatures",
17
+ "probeTimeoutMs",
18
+ "cwd",
19
+ "diffBasisMaxBytes",
20
+ ]);
21
+
22
+ // 每次新建:模块级常量会被多个实例(多个 app)共享,前一个用例的规则会漏到后一个。
23
+ function emptySource(): RuleSource {
24
+ return { allowWrite: [], readOnly: [], deny: [] };
25
+ }
26
+
27
+ /**
28
+ * 缺省规则。
29
+ *
30
+ * `cwd`(相对路径的解析基准)由调用方给 `AppEnv` 的起始目录——环境事实只有那一个来源。
31
+ * 每次新建:模块级常量会被多个实例(多个 app)共享,前一个用例的规则会漏到后一个。
32
+ * @param cwd - 相对路径的解析基准。
33
+ * @returns 一份全新的缺省设置。
34
+ */
35
+ function defaults(cwd: string): SandboxSettings {
36
+ return {
37
+ access: [],
38
+ runnerCommand: [],
39
+ runnerFailureSignatures: [],
40
+ probeTimeoutMs: 5_000,
41
+ cwd,
42
+ diffBasisMaxBytes: 10 * 1024 * 1024,
43
+ };
44
+ }
45
+
46
+ function strings(value: unknown, field: string): readonly string[] {
47
+ if (value === undefined) return [];
48
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
49
+ throw new TypeError(`"${field}" must be an array of strings`);
50
+ }
51
+ return value as readonly string[];
52
+ }
53
+
54
+ /**
55
+ * 规则条目:**数组与多行字符串两种写法都收**。
56
+ *
57
+ * TOML 里最顺手的写法是块标量(`access = """\nrw /tmp\n"""`,一行一条),源部署的 patch 就是那个形状;
58
+ * 只认数组会让那份配置整份被当成坏文件退到空规则——症状是沙箱静默只剩工作区可写。
59
+ * 空行丢弃(块标量首尾的空行是写法带来的,不是规则)。
60
+ * @param value - 文档里的 `access` 字段。
61
+ * @returns 一条条规则文本。
62
+ */
63
+ function accessEntries(value: unknown): readonly string[] {
64
+ if (typeof value === "string") {
65
+ return value
66
+ .split("\n")
67
+ .map((line) => line.trim())
68
+ .filter((line) => line.length > 0);
69
+ }
70
+ return strings(value, "access");
71
+ }
72
+
73
+ function positiveInteger(value: unknown, field: string, fallback: number): number {
74
+ if (value === undefined) return fallback;
75
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
76
+ throw new TypeError(`"${field}" must be a positive integer`);
77
+ }
78
+ return value;
79
+ }
80
+
81
+ function text(value: unknown, field: string, fallback: string): string {
82
+ if (value === undefined) return fallback;
83
+ if (typeof value !== "string" || value.length === 0) {
84
+ throw new TypeError(`"${field}" must be a non-empty string`);
85
+ }
86
+ return value;
87
+ }
88
+
89
+ @Injectable()
90
+ export class SandboxRulesDefault extends SandboxRules implements OnInit {
91
+ private readonly file = inject(SandboxFile);
92
+
93
+ private readonly logger = inject(Logger);
94
+
95
+ /**
96
+ * `cwd` 缺省的来源:`AppEnv.defaultWorkingDirectory`。
97
+ *
98
+ * 注入而不是在缺省值里读 `process.cwd()`:环境事实只有一个来源,
99
+ * 打包形态下进程 cwd 不是用户的项目目录。
100
+ */
101
+ private readonly appEnv = inject(AppEnv);
102
+
103
+ // 惰性建:字段初始化器那一刻 `inject(AppEnv)` 还只是占位,读不到真值。
104
+ private state: SandboxSettings | undefined;
105
+
106
+ private readonly rules: RuleSource = emptySource();
107
+
108
+ async onInit(_ctx: Context): Promise<void> {
109
+ const raw = await this.file.read();
110
+ if (raw === undefined) return;
111
+ const loaded = this.load(raw);
112
+ if (loaded === undefined) return;
113
+ Object.assign(this.settings(), loaded.settings);
114
+ Object.assign(this.rules, loaded.source);
115
+ }
116
+
117
+ settings(): SandboxSettings {
118
+ this.state ??= defaults(this.appEnv.defaultWorkingDirectory);
119
+ return this.state;
120
+ }
121
+
122
+ source(): RuleSource {
123
+ return this.rules;
124
+ }
125
+
126
+ // 解析一份 toml;任何一处坏掉都给 `undefined`(= 沿用默认值与空规则),并 warn 一条点名。
127
+ private load(raw: string): { settings: SandboxSettings; source: RuleSource } | undefined {
128
+ let document: Record<string, unknown>;
129
+ try {
130
+ // 编码规则只有一份(框架层 parseToml,与 dsh-setting / session-mode 同一面):坏文本它如实抛,
131
+ // 吞不吞是本包的口径 —— 下面三条 degraded() 就是那个口径。
132
+ document = parseToml(raw);
133
+ } catch (error) {
134
+ return this.degraded(`is not valid TOML (${String(error)})`);
135
+ }
136
+
137
+ const unknown = Object.keys(document).filter((key) => !KNOWN_KEYS.has(key));
138
+ if (unknown.length > 0) {
139
+ return this.degraded(`has unknown field(s) ${unknown.join(", ")}`);
140
+ }
141
+
142
+ const base = this.settings();
143
+ let settings: SandboxSettings;
144
+ try {
145
+ settings = {
146
+ access: accessEntries(document["access"]),
147
+ runnerCommand: strings(document["runnerCommand"], "runnerCommand"),
148
+ runnerFailureSignatures: strings(
149
+ document["runnerFailureSignatures"],
150
+ "runnerFailureSignatures",
151
+ ),
152
+ probeTimeoutMs: positiveInteger(
153
+ document["probeTimeoutMs"],
154
+ "probeTimeoutMs",
155
+ base.probeTimeoutMs,
156
+ ),
157
+ cwd: text(document["cwd"], "cwd", base.cwd),
158
+ diffBasisMaxBytes: positiveInteger(
159
+ document["diffBasisMaxBytes"],
160
+ "diffBasisMaxBytes",
161
+ base.diffBasisMaxBytes,
162
+ ),
163
+ };
164
+ } catch (error) {
165
+ return this.degraded(`has a wrongly typed field (${String(error)})`);
166
+ }
167
+
168
+ try {
169
+ return { settings, source: ruleSourceOf(settings.access, process.env) };
170
+ } catch (error) {
171
+ // 条目坏掉时整份规则都不用:半套规则比没有规则更危险。
172
+ this.warn(`has an unusable access entry (${String(error)})`);
173
+ return undefined;
174
+ }
175
+ }
176
+
177
+ private degraded(reason: string): undefined {
178
+ this.warn(reason);
179
+ return undefined;
180
+ }
181
+
182
+ private warn(reason: string): void {
183
+ this.logger.warn(
184
+ `configurable-sandbox: ${this.file.path} ${reason}, so no sandbox rules are applied`,
185
+ );
186
+ }
187
+ }