@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/LICENSE +21 -0
- package/README.md +61 -2
- package/dist/index.d.mts +184 -0
- package/dist/index.mjs +792 -0
- package/dist/rolldown-runtime-3qf6kE1h.d.mts +1 -0
- package/package.json +36 -3
- package/src/configurable-sandbox.provide.ts +15 -0
- package/src/containment.ts +50 -0
- package/src/contract/index.ts +3 -0
- package/src/contract/sandbox-file.contract.ts +13 -0
- package/src/contract/sandbox-rules.contract.ts +30 -0
- package/src/defaults.ts +105 -0
- package/src/dialects.ts +115 -0
- package/src/events.ts +12 -0
- package/src/fs.service.ts +209 -0
- package/src/index.ts +16 -0
- package/src/policy-text.ts +46 -0
- package/src/rules.ts +228 -0
- package/src/runtime-contexts.service.ts +125 -0
- package/src/sandbox-file.service.ts +81 -0
- package/src/sandbox-rules.service.ts +187 -0
- package/src/sandbox.service.ts +114 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { __exportAll as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@morlay/configurable-sandbox",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.2.0-alpha.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "可配置沙箱:替换进程沙箱与文件围栏,在官方语义之上叠加额外可写根、只读根与拒绝项;规则来自 {AppEnv.dataDir}/sandbox.toml。",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist",
|
|
8
|
+
"src",
|
|
9
|
+
"!**/__tests__"
|
|
10
|
+
],
|
|
11
|
+
"type": "module",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.mts",
|
|
15
|
+
"default": "./dist/index.mjs"
|
|
16
|
+
},
|
|
17
|
+
"./package.json": "./package.json"
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@morlay/dsh-agent": "^0.2.0-alpha.0",
|
|
21
|
+
"@morlay/dsh-fs": "^0.2.0-alpha.0",
|
|
22
|
+
"@morlay/dsh-permission": "^0.2.0-alpha.0",
|
|
23
|
+
"@morlay/dsh-sandbox": "^0.2.0-alpha.0",
|
|
24
|
+
"@morlay/zephyr": "^0.2.0-alpha.0",
|
|
25
|
+
"@morlay/zephyr-app": "^0.2.0-alpha.0"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@morlay/dsh-session": "^0.2.0-alpha.0"
|
|
29
|
+
},
|
|
30
|
+
"engines": {
|
|
31
|
+
"dsh": ">= 0.2.3-alpha.3 < 0.2.4"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "https://github.com/morlay/zephyr.git",
|
|
36
|
+
"directory": "packages/agent-ex/configurable-sandbox"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {}
|
|
6
39
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { provide } from "@morlay/zephyr";
|
|
2
|
+
import { ConfigurableFsSandbox } from "./fs.service.ts";
|
|
3
|
+
import { SandboxRuntimeContexts } from "./runtime-contexts.service.ts";
|
|
4
|
+
import { ConfigurableSandbox } from "./sandbox.service.ts";
|
|
5
|
+
import { SandboxFileDefault } from "./sandbox-file.service.ts";
|
|
6
|
+
import { SandboxRulesDefault } from "./sandbox-rules.service.ts";
|
|
7
|
+
|
|
8
|
+
// 顺序有依赖:读配置 → 解析规则 → 两个替换实现 → 接管运行时文本(最后一步要规则与策略都就绪)。
|
|
9
|
+
export const provideConfigurableSandbox = provide([
|
|
10
|
+
SandboxFileDefault,
|
|
11
|
+
SandboxRulesDefault,
|
|
12
|
+
ConfigurableSandbox,
|
|
13
|
+
ConfigurableFsSandbox,
|
|
14
|
+
SandboxRuntimeContexts,
|
|
15
|
+
]);
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// 路径包含判定:先做字面比较,再沿祖先链比 inode(符号链接指到同一个对象时也算包含)。
|
|
2
|
+
import type { BigIntStats } from "node:fs";
|
|
3
|
+
import { stat } from "node:fs/promises";
|
|
4
|
+
import { dirname, sep } from "node:path";
|
|
5
|
+
|
|
6
|
+
const MISSING_CODES: ReadonlySet<string> = new Set(["ENOENT", "ENOTDIR"]);
|
|
7
|
+
|
|
8
|
+
async function statIfPresent(path: string): Promise<BigIntStats | undefined> {
|
|
9
|
+
try {
|
|
10
|
+
return await stat(path, { bigint: true });
|
|
11
|
+
} catch (error) {
|
|
12
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
13
|
+
if (code !== undefined && MISSING_CODES.has(code)) return undefined;
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function comparablePath(path: string, caseSensitive: boolean): string {
|
|
19
|
+
return caseSensitive ? path : path.toLowerCase();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function isLexicallyUnder(path: string, root: string, caseSensitive: boolean): boolean {
|
|
23
|
+
const comparableTarget = comparablePath(path, caseSensitive);
|
|
24
|
+
const comparableRoot = comparablePath(root, caseSensitive);
|
|
25
|
+
if (comparableTarget === comparableRoot) return true;
|
|
26
|
+
const prefix = comparableRoot.endsWith(sep) ? comparableRoot : comparableRoot + sep;
|
|
27
|
+
return comparableTarget.startsWith(prefix);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function sameIdentity(left: BigIntStats, right: BigIntStats): boolean {
|
|
31
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function isPathUnder(
|
|
35
|
+
path: string,
|
|
36
|
+
root: string,
|
|
37
|
+
caseSensitive = process.platform !== "win32",
|
|
38
|
+
): Promise<boolean> {
|
|
39
|
+
if (isLexicallyUnder(path, root, caseSensitive)) return true;
|
|
40
|
+
const rootInfo = await statIfPresent(root);
|
|
41
|
+
if (rootInfo === undefined) return false;
|
|
42
|
+
let ancestor = path;
|
|
43
|
+
for (;;) {
|
|
44
|
+
const ancestorInfo = await statIfPresent(ancestor);
|
|
45
|
+
if (ancestorInfo !== undefined && sameIdentity(ancestorInfo, rootInfo)) return true;
|
|
46
|
+
const parent = dirname(ancestor);
|
|
47
|
+
if (parent === ancestor) return false;
|
|
48
|
+
ancestor = parent;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// 配置文件的读面:把"从哪读、怎么读"变成可注入的依赖。
|
|
2
|
+
//
|
|
3
|
+
// 默认实现读 `<AppEnv.dataDir>/sandbox.toml`;测试注入假件,不碰真实数据根。
|
|
4
|
+
import { Injectable } from "@morlay/zephyr";
|
|
5
|
+
|
|
6
|
+
@Injectable()
|
|
7
|
+
export abstract class SandboxFile {
|
|
8
|
+
// 配置文件内容;文件不存在给 `undefined`(与"读到空"区分开:前者是"没写规则")。
|
|
9
|
+
abstract read(): Promise<string | undefined>;
|
|
10
|
+
|
|
11
|
+
// 配置文件路径(日志里点名用)。
|
|
12
|
+
abstract readonly path: string;
|
|
13
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// 规则面契约:`sandbox.toml` 解析后的装配事实与规则源。
|
|
2
|
+
//
|
|
3
|
+
// 两个实现(进程沙箱、文件围栏)都从这里取同一份规则——一份文件一个 owner。
|
|
4
|
+
import { Injectable } from "@morlay/zephyr";
|
|
5
|
+
import type { RuleSource } from "../rules.ts";
|
|
6
|
+
|
|
7
|
+
// `sandbox.toml` 的六个字段:启动时读一次,之后不再变(本部署没有配置页)。
|
|
8
|
+
export interface SandboxSettings {
|
|
9
|
+
// 规则条目:`rw <路径>` / `r- <路径>` / `-- <模式>`。
|
|
10
|
+
readonly access: readonly string[];
|
|
11
|
+
// runner 启动命令;空数组表示按平台自带的链去选。
|
|
12
|
+
readonly runnerCommand: readonly string[];
|
|
13
|
+
// runner 命令"用不了"的判定片段(与 `runnerCommand` 成对)。
|
|
14
|
+
readonly runnerFailureSignatures: readonly string[];
|
|
15
|
+
// 探测 runner 可用性的超时(毫秒)。
|
|
16
|
+
readonly probeTimeoutMs: number;
|
|
17
|
+
// 相对路径的解析基准(文件围栏的 `cwd`)。
|
|
18
|
+
readonly cwd: string;
|
|
19
|
+
// 覆盖写差异的单侧字节上限。
|
|
20
|
+
readonly diffBasisMaxBytes: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
@Injectable()
|
|
24
|
+
export abstract class SandboxRules {
|
|
25
|
+
// 装配事实(交给官方两个基类的配置)。
|
|
26
|
+
abstract settings(): SandboxSettings;
|
|
27
|
+
|
|
28
|
+
// 规则源(环境变量已在加载期展开)。文件缺失 / 损坏时是全空的一份。
|
|
29
|
+
abstract source(): RuleSource;
|
|
30
|
+
}
|
package/src/defaults.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// 默认的 `<AppEnv.dataDir>/sandbox.toml`:文件不存在时写这一份,用户照着改。
|
|
2
|
+
//
|
|
3
|
+
// 内容与源部署(`@morlay/sandbox-profile` 的 patch)**逐条一致**——那些条目是「本机真跑得起来」的
|
|
4
|
+
// 最小集合:临时目录可写、agent-browser 与 XDG 的缓存/状态/数据可写、XDG 配置只读、
|
|
5
|
+
// mise 配方与私钥一律拒绝。空规则(一条都不给)会让沙箱退化成「只有工作区可写」,
|
|
6
|
+
// 症状是 agent-browser 起不来、`XDG_CACHE_HOME` 写不进去。
|
|
7
|
+
//
|
|
8
|
+
// **与源部署那一份的唯一差别:写出去的是本机具体路径,不带 `{{ env.* }}` 模板。**
|
|
9
|
+
// 模板由规则层按 `process.env` 展开,而 `expandEnvTemplates` 对未设/空值是 fail-loud——整份 `access`
|
|
10
|
+
// 作废、只剩一条 warn。这份文件是**我们代用户写的**,不该依赖恰好存在的变量:普通 macOS 与
|
|
11
|
+
// `apps/dsh` 的容器都没有 `XDG_*`,那样写出去的默认配置一装就整份不生效,正好落回上面那个症状。
|
|
12
|
+
// 用户自己在文件里写模板时语义不变(那是他的选择,缺变量就整份退化 + warn)。
|
|
13
|
+
//
|
|
14
|
+
// `XDG_*` 按 XDG 惯例回退:变量有非空值就用它,否则 `~/.cache` / `~/.local/state` /
|
|
15
|
+
// `~/.local/share` / `~/.config`。`HOME` 也没有时,依赖它的那几行**写不出来**:跳过它们并让调用方 warn,
|
|
16
|
+
// 既不产出空规则,也不留依赖 `HOME` 的模板。
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
|
|
19
|
+
/** XDG 目录在变量缺失时的回退(XDG Base Directory 的惯例路径,相对用户主目录)。 */
|
|
20
|
+
const XDG_FALLBACKS = {
|
|
21
|
+
XDG_CACHE_HOME: [".cache"],
|
|
22
|
+
XDG_STATE_HOME: [".local", "state"],
|
|
23
|
+
XDG_DATA_HOME: [".local", "share"],
|
|
24
|
+
XDG_CONFIG_HOME: [".config"],
|
|
25
|
+
} as const;
|
|
26
|
+
|
|
27
|
+
/** 一条默认规则的路径来源之一。 */
|
|
28
|
+
type XdgName = keyof typeof XDG_FALLBACKS;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 环境变量的非空值(XDG 惯例:空串等于未设)。
|
|
32
|
+
* @param env - 进程环境。
|
|
33
|
+
* @param name - 变量名。
|
|
34
|
+
* @returns 非空值,或 `undefined`。
|
|
35
|
+
*/
|
|
36
|
+
function valueOf(env: NodeJS.ProcessEnv, name: string): string | undefined {
|
|
37
|
+
const value = env[name];
|
|
38
|
+
return value === undefined || value.length === 0 ? undefined : value;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 首次写盘用的默认规则。 */
|
|
42
|
+
export interface DefaultSandboxToml {
|
|
43
|
+
/** 落盘的文本(`access` 里是具体路径,没有模板)。 */
|
|
44
|
+
readonly text: string;
|
|
45
|
+
/** 因为没有对应环境变量而跳过的条目(变量名,按条目顺序):调用方据此 warn。 */
|
|
46
|
+
readonly skipped: readonly string[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 造首次写盘用的默认规则:用户目录与 XDG 目录在这里就落成本机具体路径。
|
|
51
|
+
* @param env - 进程环境(用户目录与 XDG 目录的唯一来源)。
|
|
52
|
+
* @returns 文本与跳过的条目。
|
|
53
|
+
*/
|
|
54
|
+
export function defaultSandboxToml(env: NodeJS.ProcessEnv): DefaultSandboxToml {
|
|
55
|
+
const home = valueOf(env, "HOME");
|
|
56
|
+
const skipped: string[] = [];
|
|
57
|
+
|
|
58
|
+
/** 一个 XDG 目录:显式值优先,否则按惯例回退到 `home` 下。 */
|
|
59
|
+
const userDirOf = (name: XdgName): string | undefined => {
|
|
60
|
+
const explicit = valueOf(env, name);
|
|
61
|
+
if (explicit !== undefined) return explicit;
|
|
62
|
+
if (home === undefined) {
|
|
63
|
+
skipped.push(name);
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
return join(home, ...XDG_FALLBACKS[name]);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const lines: string[] = ["rw /tmp"];
|
|
70
|
+
if (home === undefined) skipped.push("HOME");
|
|
71
|
+
else lines.push(`rw ${join(home, ".agent-browser")}`);
|
|
72
|
+
const cache = userDirOf("XDG_CACHE_HOME");
|
|
73
|
+
const state = userDirOf("XDG_STATE_HOME");
|
|
74
|
+
const data = userDirOf("XDG_DATA_HOME");
|
|
75
|
+
const config = userDirOf("XDG_CONFIG_HOME");
|
|
76
|
+
if (cache !== undefined) lines.push(`rw ${cache}`);
|
|
77
|
+
if (state !== undefined) lines.push(`rw ${state}`);
|
|
78
|
+
if (data !== undefined) lines.push(`rw ${data}`);
|
|
79
|
+
if (config !== undefined) lines.push(`r- ${config}`);
|
|
80
|
+
lines.push("-- mise.*.toml", "-- **/*.pem");
|
|
81
|
+
|
|
82
|
+
return { text: renderSandboxToml(lines), skipped };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 把条目行拼成整份 `sandbox.toml`(块标量一行一条;尾部换行固定)。
|
|
87
|
+
* @param lines - `access` 的条目行。
|
|
88
|
+
* @returns 文本。
|
|
89
|
+
*/
|
|
90
|
+
function renderSandboxToml(lines: readonly string[]): string {
|
|
91
|
+
return [
|
|
92
|
+
"",
|
|
93
|
+
"# 本机可写:临时目录(构建工具、npm、各种 tmp)",
|
|
94
|
+
'access = """',
|
|
95
|
+
...lines,
|
|
96
|
+
'"""',
|
|
97
|
+
"",
|
|
98
|
+
"# runner 探测超时(毫秒):平台自带的链选不出可用 runner 时的兜底上限。",
|
|
99
|
+
"probeTimeoutMs = 5000",
|
|
100
|
+
"",
|
|
101
|
+
"# 覆盖写差异的单侧字节上限(10 MiB)。",
|
|
102
|
+
"diffBasisMaxBytes = 10485760",
|
|
103
|
+
"",
|
|
104
|
+
].join("\n");
|
|
105
|
+
}
|
package/src/dialects.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// 平台方言:把规则追加到官方 runner 的 argv。
|
|
2
|
+
//
|
|
3
|
+
// 各平台能表达的不一样(见 `DIALECT_CAPABILITIES`),表达不了的由装配期告警说明,不在这里静默丢弃。
|
|
4
|
+
import { isEmptyRules, type CompiledRules } from "./rules.ts";
|
|
5
|
+
|
|
6
|
+
export type SandboxDialect = "seatbelt" | "bwrap" | "landlock" | "windows-acl";
|
|
7
|
+
|
|
8
|
+
const SEPARATOR = "--";
|
|
9
|
+
|
|
10
|
+
export interface DialectCapabilities {
|
|
11
|
+
readonly allowWrite: boolean;
|
|
12
|
+
|
|
13
|
+
readonly readOnly: boolean;
|
|
14
|
+
|
|
15
|
+
readonly denyReadWrite: boolean;
|
|
16
|
+
|
|
17
|
+
readonly denyWriteOnly: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const DIALECT_CAPABILITIES: Record<SandboxDialect, DialectCapabilities> = {
|
|
21
|
+
seatbelt: { allowWrite: true, readOnly: true, denyReadWrite: true, denyWriteOnly: false },
|
|
22
|
+
bwrap: { allowWrite: true, readOnly: true, denyReadWrite: false, denyWriteOnly: true },
|
|
23
|
+
landlock: { allowWrite: true, readOnly: false, denyReadWrite: false, denyWriteOnly: false },
|
|
24
|
+
"windows-acl": { allowWrite: false, readOnly: false, denyReadWrite: false, denyWriteOnly: false },
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function separatorIndex(argv: readonly string[]): number {
|
|
28
|
+
const index = argv.indexOf(SEPARATOR);
|
|
29
|
+
if (index === -1) {
|
|
30
|
+
throw new Error("sandbox rules: the confined argv carries no `--` separator to extend");
|
|
31
|
+
}
|
|
32
|
+
return index;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function dialectOf(argv: readonly string[]): SandboxDialect | undefined {
|
|
36
|
+
const separator = argv.indexOf(SEPARATOR);
|
|
37
|
+
const runner = separator === -1 ? argv : argv.slice(0, separator);
|
|
38
|
+
if (runner.includes("-p")) return "seatbelt";
|
|
39
|
+
if (runner[0] === "bwrap") return "bwrap";
|
|
40
|
+
if (runner.includes("--workspace")) return "windows-acl";
|
|
41
|
+
if (runner.includes("--ro") || runner.includes("--rw")) return "landlock";
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function sbplString(value: string): string {
|
|
46
|
+
return `"${value.replaceAll("\\", String.raw`\\`).replaceAll('"', String.raw`\"`)}"`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function sbplRegexBody(source: string): string {
|
|
50
|
+
if (source.includes('"')) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
`sandbox rules: deny pattern ${JSON.stringify(source)} cannot be expressed in a Seatbelt profile`,
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
return source;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function extendSeatbelt(argv: readonly string[], rules: CompiledRules): string[] {
|
|
59
|
+
const index = argv.indexOf("-p");
|
|
60
|
+
const profile = index === -1 ? undefined : argv[index + 1];
|
|
61
|
+
if (profile === undefined) {
|
|
62
|
+
throw new Error("sandbox rules: the Seatbelt runner argv carries no `-p` profile to extend");
|
|
63
|
+
}
|
|
64
|
+
const additions = [
|
|
65
|
+
...rules.allowRoots.map((root) => `(allow file-write* (subpath ${sbplString(root)}))`),
|
|
66
|
+
...rules.readOnlySubtrees.map((path) => `(deny file-write* (subpath ${sbplString(path)}))`),
|
|
67
|
+
...rules.readOnlyPatterns.map(
|
|
68
|
+
(pattern) => `(deny file-write* (regex #"${sbplRegexBody(pattern.source)}"))`,
|
|
69
|
+
),
|
|
70
|
+
...rules.denySubtrees.map(
|
|
71
|
+
(path) => `(deny file-read* file-write* (subpath ${sbplString(path)}))`,
|
|
72
|
+
),
|
|
73
|
+
...rules.denyPatterns.map(
|
|
74
|
+
(pattern) => `(deny file-read* file-write* (regex #"${sbplRegexBody(pattern.source)}"))`,
|
|
75
|
+
),
|
|
76
|
+
];
|
|
77
|
+
const extended = `${profile} ${additions.join(" ")}`;
|
|
78
|
+
return [...argv.slice(0, index + 1), extended, ...argv.slice(index + 2)];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function extendBwrap(argv: readonly string[], rules: CompiledRules): string[] {
|
|
82
|
+
const separator = separatorIndex(argv);
|
|
83
|
+
const additions: string[] = [];
|
|
84
|
+
for (const root of rules.allowRoots) additions.push("--bind-try", root, root);
|
|
85
|
+
for (const path of [...rules.readOnlySubtrees, ...rules.denySubtrees]) {
|
|
86
|
+
additions.push("--ro-bind-try", path, path);
|
|
87
|
+
}
|
|
88
|
+
return [...argv.slice(0, separator), ...additions, ...argv.slice(separator)];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function extendLandlock(argv: readonly string[], rules: CompiledRules): string[] {
|
|
92
|
+
const separator = separatorIndex(argv);
|
|
93
|
+
const additions = rules.allowRoots.flatMap((root) => ["--rw", root]);
|
|
94
|
+
return [...argv.slice(0, separator), ...additions, ...argv.slice(separator)];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function extendConfinedArgv(argv: readonly string[], rules: CompiledRules): string[] {
|
|
98
|
+
if (isEmptyRules(rules)) return [...argv];
|
|
99
|
+
const dialect = dialectOf(argv);
|
|
100
|
+
if (dialect === undefined) {
|
|
101
|
+
throw new Error(
|
|
102
|
+
"sandbox rules: cannot extend an unrecognized sandbox runner argv; drop allowWrite/deny or configure a bwrap-compatible runnerCommand",
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
switch (dialect) {
|
|
106
|
+
case "seatbelt":
|
|
107
|
+
return extendSeatbelt(argv, rules);
|
|
108
|
+
case "bwrap":
|
|
109
|
+
return extendBwrap(argv, rules);
|
|
110
|
+
case "landlock":
|
|
111
|
+
return extendLandlock(argv, rules);
|
|
112
|
+
case "windows-acl":
|
|
113
|
+
return [...argv];
|
|
114
|
+
}
|
|
115
|
+
}
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// 本包订阅的上游事件:名字与参数表收在类里(拼错名字或参数表在编译期就报)。
|
|
2
|
+
//
|
|
3
|
+
// 与上游同名即可互通——上游用 `ctx.emit("agent/created", …)` 派发,这里用同一套名字订阅。
|
|
4
|
+
import type { Agent } from "@morlay/dsh-agent/contract";
|
|
5
|
+
import { EventEmitter } from "@morlay/zephyr";
|
|
6
|
+
|
|
7
|
+
// 会话建好了(晚于它的 preset 行挂载,早于第一次装配)。
|
|
8
|
+
export class AgentCreated extends EventEmitter<[{ readonly agent: Agent }]> {
|
|
9
|
+
constructor() {
|
|
10
|
+
super("agent/created");
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// 文件围栏:继承官方 `LocalFileSystem`,在五个写面与 `resolve`(读入口)上叠加本包的规则。
|
|
2
|
+
//
|
|
3
|
+
// 与官方 `fs-sandbox` 同一威胁模型(受信代码 + 模型可控路径);内核级隔离仍归 `ctx.sandbox`。
|
|
4
|
+
// 规则里的相对路径相对**会话工作区**解析:读写两侧同一个基准,读被拒的文件才不会在写路径上被放行。
|
|
5
|
+
import { FsError } from "@morlay/dsh-fs/contract";
|
|
6
|
+
import type {
|
|
7
|
+
FsDeleteOutcome,
|
|
8
|
+
FsEditOutcome,
|
|
9
|
+
FsEditRequest,
|
|
10
|
+
FsMoveOutcome,
|
|
11
|
+
FsTarget,
|
|
12
|
+
FsVersion,
|
|
13
|
+
FsWriteIntent,
|
|
14
|
+
FsWriteOutcome,
|
|
15
|
+
} from "@morlay/dsh-fs/contract";
|
|
16
|
+
import type { FileSystemConfig as UpstreamFsConfig } from "@morlay/dsh-fs";
|
|
17
|
+
import { LocalFileSystem } from "@morlay/dsh-fs";
|
|
18
|
+
import type { SandboxExecutionPolicy, SandboxMode } from "@morlay/dsh-sandbox/contract";
|
|
19
|
+
import { SandboxPolicy } from "@morlay/dsh-sandbox";
|
|
20
|
+
import { FileSystem } from "@morlay/dsh-fs";
|
|
21
|
+
import { inject, Injectable, type Context } from "@morlay/zephyr";
|
|
22
|
+
import { fromCordis } from "@morlay/zephyr/compat";
|
|
23
|
+
import { SandboxRules, type SandboxSettings } from "./contract/sandbox-rules.contract.ts";
|
|
24
|
+
import { isPathUnder } from "./containment.ts";
|
|
25
|
+
import {
|
|
26
|
+
compileRules,
|
|
27
|
+
isDenied,
|
|
28
|
+
isReadOnly,
|
|
29
|
+
writableRootsWith,
|
|
30
|
+
type CompiledRules,
|
|
31
|
+
} from "./rules.ts";
|
|
32
|
+
|
|
33
|
+
// 交给官方基类的配置:它认的两个字段(其余字段是本包自己的)。
|
|
34
|
+
export function upstreamFsConfigOf(settings: SandboxSettings) {
|
|
35
|
+
return { cwd: settings.cwd, diffBasisMaxBytes: settings.diffBasisMaxBytes };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// 上游构造面的 ctx 类型:直接推导,不把 `@deepseek-ai/cordis` 引成依赖。
|
|
39
|
+
type UpstreamFsContext = ConstructorParameters<typeof LocalFileSystem>[0];
|
|
40
|
+
|
|
41
|
+
// deps 上的名字:上游实例按 `ctx.get("sandboxRules")` / `ctx.get("sandboxPolicy")` 读它们。
|
|
42
|
+
const RULES_DEP = "sandboxRules";
|
|
43
|
+
const POLICY_DEP = "sandboxPolicy";
|
|
44
|
+
|
|
45
|
+
@Injectable()
|
|
46
|
+
export class ConfigurableFileSystem extends LocalFileSystem {
|
|
47
|
+
private readonly rules: SandboxRules;
|
|
48
|
+
|
|
49
|
+
private readonly policy: SandboxPolicy;
|
|
50
|
+
|
|
51
|
+
private readonly compiled = new Map<string, CompiledRules>();
|
|
52
|
+
|
|
53
|
+
constructor(ctx: UpstreamFsContext, config: UpstreamFsConfig) {
|
|
54
|
+
super(ctx, config);
|
|
55
|
+
const read = (ctx as unknown as { get(name: string, strict?: boolean): unknown }).get.bind(ctx);
|
|
56
|
+
this.rules = read(RULES_DEP) as SandboxRules;
|
|
57
|
+
this.policy = read(POLICY_DEP) as SandboxPolicy;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
override get sandboxMode(): SandboxMode {
|
|
61
|
+
return this.policy.defaultMode;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
override async resolve(
|
|
65
|
+
path: string,
|
|
66
|
+
opts?: { cwd?: string; signal?: AbortSignal },
|
|
67
|
+
): Promise<FsTarget> {
|
|
68
|
+
const target = await super.resolve(path, opts);
|
|
69
|
+
this.assertNotDenied(
|
|
70
|
+
this.rulesFor(this.policy.resolve().workspaceRoot),
|
|
71
|
+
target.targetKey,
|
|
72
|
+
target.displayPath,
|
|
73
|
+
);
|
|
74
|
+
return target;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
override async writeText(
|
|
78
|
+
target: FsTarget,
|
|
79
|
+
content: string,
|
|
80
|
+
expected?: FsWriteIntent,
|
|
81
|
+
signal?: AbortSignal,
|
|
82
|
+
sandboxPolicy?: SandboxExecutionPolicy,
|
|
83
|
+
): Promise<FsWriteOutcome> {
|
|
84
|
+
return super.writeText(
|
|
85
|
+
await this.checkedTarget(target, sandboxPolicy),
|
|
86
|
+
content,
|
|
87
|
+
expected,
|
|
88
|
+
signal,
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
override async editText(
|
|
93
|
+
target: FsTarget,
|
|
94
|
+
edit: FsEditRequest,
|
|
95
|
+
expected?: { version: FsVersion },
|
|
96
|
+
signal?: AbortSignal,
|
|
97
|
+
sandboxPolicy?: SandboxExecutionPolicy,
|
|
98
|
+
): Promise<FsEditOutcome> {
|
|
99
|
+
return super.editText(await this.checkedTarget(target, sandboxPolicy), edit, expected, signal);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
override async patchText(
|
|
103
|
+
target: FsTarget,
|
|
104
|
+
hunks: Parameters<LocalFileSystem["patchText"]>[1],
|
|
105
|
+
expected?: { version: FsVersion },
|
|
106
|
+
signal?: AbortSignal,
|
|
107
|
+
sandboxPolicy?: SandboxExecutionPolicy,
|
|
108
|
+
): Promise<FsEditOutcome> {
|
|
109
|
+
return super.patchText(
|
|
110
|
+
await this.checkedTarget(target, sandboxPolicy),
|
|
111
|
+
hunks,
|
|
112
|
+
expected,
|
|
113
|
+
signal,
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
override async deleteFile(
|
|
118
|
+
target: FsTarget,
|
|
119
|
+
expected?: { version: FsVersion },
|
|
120
|
+
signal?: AbortSignal,
|
|
121
|
+
sandboxPolicy?: SandboxExecutionPolicy,
|
|
122
|
+
): Promise<FsDeleteOutcome> {
|
|
123
|
+
return super.deleteFile(await this.checkedTarget(target, sandboxPolicy), expected, signal);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
override async moveFile(
|
|
127
|
+
source: FsTarget,
|
|
128
|
+
destination: FsTarget,
|
|
129
|
+
options: Parameters<LocalFileSystem["moveFile"]>[2],
|
|
130
|
+
signal?: AbortSignal,
|
|
131
|
+
sandboxPolicy?: SandboxExecutionPolicy,
|
|
132
|
+
): Promise<FsMoveOutcome> {
|
|
133
|
+
const checkedSource = await this.checkedTarget(source, sandboxPolicy);
|
|
134
|
+
const checkedDestination = await this.checkedTarget(destination, sandboxPolicy);
|
|
135
|
+
return super.moveFile(checkedSource, checkedDestination, options, signal);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private assertNotDenied(
|
|
139
|
+
rules: CompiledRules,
|
|
140
|
+
canonicalTarget: string,
|
|
141
|
+
displayPath: string,
|
|
142
|
+
): void {
|
|
143
|
+
if (!isDenied(rules, canonicalTarget)) return;
|
|
144
|
+
throw new FsError(
|
|
145
|
+
`cannot access "${displayPath}": file access denied by the configured "--" rules`,
|
|
146
|
+
"FS_SANDBOX_DENIED",
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private assertWritable(rules: CompiledRules, canonicalTarget: string, displayPath: string): void {
|
|
151
|
+
this.assertNotDenied(rules, canonicalTarget, displayPath);
|
|
152
|
+
if (!isReadOnly(rules, canonicalTarget)) return;
|
|
153
|
+
throw new FsError(
|
|
154
|
+
`cannot write "${displayPath}": path is read-only by the configured "r-" rule`,
|
|
155
|
+
"FS_SANDBOX_DENIED",
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 先过本包规则,再过官方模式围栏:`r-` / `--` 优先于可写根,但不放松 `read-only`。
|
|
160
|
+
private async checkedTarget(
|
|
161
|
+
target: FsTarget,
|
|
162
|
+
sandboxPolicy?: SandboxExecutionPolicy,
|
|
163
|
+
): Promise<FsTarget> {
|
|
164
|
+
const policy = sandboxPolicy ?? this.policy.resolve();
|
|
165
|
+
const rules = this.rulesFor(policy.workspaceRoot);
|
|
166
|
+
this.assertWritable(rules, target.targetKey, target.displayPath);
|
|
167
|
+
if (policy.mode === "danger-full-access") return target;
|
|
168
|
+
if (policy.mode === "read-only") {
|
|
169
|
+
throw new FsError(
|
|
170
|
+
`cannot write "${target.displayPath}": file access denied under read-only mode`,
|
|
171
|
+
"FS_SANDBOX_DENIED",
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const fresh = await super.resolve(target.displayPath);
|
|
176
|
+
this.assertWritable(rules, fresh.targetKey, fresh.displayPath);
|
|
177
|
+
for (const root of writableRootsWith(rules, policy)) {
|
|
178
|
+
if (await isPathUnder(fresh.targetKey, root)) return fresh;
|
|
179
|
+
}
|
|
180
|
+
throw new FsError(
|
|
181
|
+
`cannot write "${target.displayPath}": file access denied under workspace-write mode`,
|
|
182
|
+
"FS_SANDBOX_DENIED",
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// 规则源是启动时读一次的那份:按工作区缓存编译结果。
|
|
187
|
+
private rulesFor(workspaceRoot: string): CompiledRules {
|
|
188
|
+
const cached = this.compiled.get(workspaceRoot);
|
|
189
|
+
if (cached !== undefined) return cached;
|
|
190
|
+
const compiled = compileRules(this.rules.source(), workspaceRoot);
|
|
191
|
+
this.compiled.set(workspaceRoot, compiled);
|
|
192
|
+
return compiled;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
@Injectable()
|
|
197
|
+
export class ConfigurableFsSandbox extends fromCordis(FileSystem, ConfigurableFileSystem) {
|
|
198
|
+
// 注入字段必须是**普通属性**:装配期回填注入走 Object.keys(instance),# 私有字段不可见。
|
|
199
|
+
private readonly rulesSource = inject(SandboxRules);
|
|
200
|
+
|
|
201
|
+
private readonly sandboxPolicyFace = inject(SandboxPolicy);
|
|
202
|
+
|
|
203
|
+
override async onInit(ctx: Context): Promise<void> {
|
|
204
|
+
await this.mount(ctx, upstreamFsConfigOf(this.rulesSource.settings()), {
|
|
205
|
+
[RULES_DEP]: this.rulesSource,
|
|
206
|
+
[POLICY_DEP]: this.sandboxPolicyFace,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// configurable-sandbox 的包根:契约 + 默认实现 + 装配模块(**不导出 default**)。
|
|
2
|
+
//
|
|
3
|
+
// 本包**只有宿主半**:没有浏览器面、不引 react / css。出口只有 `.`。
|
|
4
|
+
export * from "./contract/index.ts";
|
|
5
|
+
export * from "./rules.ts";
|
|
6
|
+
export * from "./containment.ts";
|
|
7
|
+
export * from "./dialects.ts";
|
|
8
|
+
export * from "./policy-text.ts";
|
|
9
|
+
export * from "./sandbox.service.ts";
|
|
10
|
+
export * from "./fs.service.ts";
|
|
11
|
+
export * from "./sandbox-file.service.ts";
|
|
12
|
+
export * from "./sandbox-rules.service.ts";
|
|
13
|
+
export * from "./runtime-contexts.service.ts";
|
|
14
|
+
export * from "./configurable-sandbox.provide.ts";
|
|
15
|
+
// 事件统一放在 `Events` 命名空间下:不与服务混在同一个出口里。
|
|
16
|
+
export * as Events from "./events.ts";
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// 运行时策略文本:本部署换了沙箱实现,模型看到的那两段也要跟着换、换成中文。
|
|
2
|
+
//
|
|
3
|
+
// 挂载方式在 `runtime-contexts.service.ts`:按 agent 作用域注册同名 context,遮蔽上游在全局层注册的那条。
|
|
4
|
+
import type { SandboxExecutionPolicy } from "@morlay/dsh-sandbox/contract";
|
|
5
|
+
import type { ApprovalPolicy } from "@morlay/dsh-permission/contract";
|
|
6
|
+
import type { RuleSource } from "./rules.ts";
|
|
7
|
+
|
|
8
|
+
// 上游注册的运行时上下文名:同名才叫接管。
|
|
9
|
+
export const SANDBOX_POLICY_CONTEXT = "sandbox:policy";
|
|
10
|
+
export const APPROVAL_POLICY_CONTEXT = "approval:policy";
|
|
11
|
+
|
|
12
|
+
// 官方三种 mode 的中文语义 + 本部署追加的规则;返回给模型看的一段文本。
|
|
13
|
+
export function renderPolicyContext(policy: SandboxExecutionPolicy, rules: RuleSource): string {
|
|
14
|
+
const base = ((): string => {
|
|
15
|
+
switch (policy.mode) {
|
|
16
|
+
case "read-only":
|
|
17
|
+
return "文件策略:只读——不能修改任何文件。别因此拒绝必需的修改:照常尝试工具,按它的拒绝与升级指引行动。";
|
|
18
|
+
case "workspace-write":
|
|
19
|
+
return `文件策略:workspace-write——可改会话工作区 ${JSON.stringify(policy.workspaceRoot)} 下的文件,部分平台临时目录同样可写。`;
|
|
20
|
+
case "danger-full-access":
|
|
21
|
+
return "文件策略:全权——文件改动不再受限。";
|
|
22
|
+
}
|
|
23
|
+
})();
|
|
24
|
+
|
|
25
|
+
const extras: string[] = [];
|
|
26
|
+
if (rules.allowWrite.length > 0) {
|
|
27
|
+
extras.push(`额外可写:${rules.allowWrite.join("、")}。`);
|
|
28
|
+
}
|
|
29
|
+
if (rules.readOnly.length > 0) {
|
|
30
|
+
extras.push(`只读(不可写):${rules.readOnly.join("、")}。`);
|
|
31
|
+
}
|
|
32
|
+
if (rules.deny.length > 0) {
|
|
33
|
+
extras.push(`拒绝(读写都拒):${rules.deny.join("、")}。`);
|
|
34
|
+
}
|
|
35
|
+
return extras.length === 0 ? base : `${base} ${extras.join("")}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// `approval:policy` 的两段文本。`never` 是确定性拒绝,所以顺带告诉模型别去要沙箱升级。
|
|
39
|
+
const APPROVAL_ASK_TEXT = "审批策略:ask——需要审批的操作会询问用户;没有可用的应答者时直接失败。";
|
|
40
|
+
const APPROVAL_NEVER_TEXT =
|
|
41
|
+
"审批提示已禁用:需要审批的操作一律自动拒绝——不要请求沙箱升级(不要设 sandbox_permissions)。";
|
|
42
|
+
|
|
43
|
+
// 策略文本按会话的有效策略选段。
|
|
44
|
+
export function renderApprovalContext(policy: ApprovalPolicy): string {
|
|
45
|
+
return policy === "never" ? APPROVAL_NEVER_TEXT : APPROVAL_ASK_TEXT;
|
|
46
|
+
}
|