@trama-dev/runtime 0.1.0 → 0.1.1

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/tools.js CHANGED
@@ -1,12 +1,88 @@
1
- import { spawn } from "child_process";
2
- import { readFileSync, writeFileSync, mkdirSync } from "fs";
1
+ import { spawn, spawnSync } from "child_process";
2
+ import { readFileSync, writeFileSync, mkdirSync, realpathSync, readlinkSync, lstatSync, existsSync } from "fs";
3
3
  import { resolve, dirname, sep } from "path";
4
- export function createTools(projectDir) {
4
+ const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
5
+ export function cappedBuffer() {
6
+ let buf = "";
7
+ let capped = false;
8
+ return {
9
+ append(text) {
10
+ if (capped)
11
+ return;
12
+ buf += text;
13
+ if (buf.length > MAX_OUTPUT) {
14
+ buf = buf.slice(0, MAX_OUTPUT) + "\n[trama] output truncated at 10MB";
15
+ capped = true;
16
+ }
17
+ },
18
+ get value() { return buf; },
19
+ };
20
+ }
21
+ export function createTools(projectDir, signal) {
5
22
  const normalizedProjectDir = resolve(projectDir);
23
+ let realProjectDir;
24
+ try {
25
+ realProjectDir = realpathSync(normalizedProjectDir);
26
+ }
27
+ catch {
28
+ realProjectDir = normalizedProjectDir;
29
+ }
6
30
  const activeShells = new Set();
31
+ const activeSessions = new Set();
32
+ const sessionReapers = new Map();
33
+ const stopReapingSession = (sessionId) => {
34
+ const timer = sessionReapers.get(sessionId);
35
+ if (timer) {
36
+ clearTimeout(timer);
37
+ sessionReapers.delete(sessionId);
38
+ }
39
+ };
40
+ const listSessionPids = (sessionId) => {
41
+ const result = spawnSync("ps", ["-o", "pid=", "-s", String(sessionId)], {
42
+ encoding: "utf-8",
43
+ });
44
+ if (result.error)
45
+ return [];
46
+ return result.stdout
47
+ .split("\n")
48
+ .map(line => parseInt(line.trim(), 10))
49
+ .filter(pid => Number.isInteger(pid) && pid > 0);
50
+ };
51
+ const killSession = (sessionId, signal) => {
52
+ const pids = listSessionPids(sessionId);
53
+ if (pids.length > 0) {
54
+ for (const pid of pids) {
55
+ try {
56
+ process.kill(pid, signal);
57
+ }
58
+ catch { /* already exited */ }
59
+ }
60
+ return;
61
+ }
62
+ try {
63
+ process.kill(-sessionId, signal);
64
+ }
65
+ catch { /* already exited */ }
66
+ };
67
+ const reapSessionWhenGone = (sessionId) => {
68
+ stopReapingSession(sessionId);
69
+ const timer = setTimeout(() => {
70
+ if (!activeSessions.has(sessionId))
71
+ return;
72
+ if (listSessionPids(sessionId).length === 0) {
73
+ activeSessions.delete(sessionId);
74
+ sessionReapers.delete(sessionId);
75
+ return;
76
+ }
77
+ reapSessionWhenGone(sessionId);
78
+ }, 250);
79
+ timer.unref?.();
80
+ sessionReapers.set(sessionId, timer);
81
+ };
7
82
  /**
8
- * Path traversal guard. Not a security sandbox — just a footgun guard.
9
- * Uses normalizedProjectDir + sep to prevent /tmp/foo-bar matching /tmp/foo.
83
+ * Path traversal guard. Checks both logical path (.. segments) and
84
+ * real path (symlinks) to prevent escaping the project directory.
85
+ * Not a security sandbox — just a footgun guard.
10
86
  */
11
87
  const resolvePath = (p) => {
12
88
  const resolved = resolve(normalizedProjectDir, p);
@@ -15,56 +91,135 @@ export function createTools(projectDir) {
15
91
  }
16
92
  return resolved;
17
93
  };
94
+ /** Verify that an existing path's real location is inside the project dir. */
95
+ const verifyRealPath = (real, original) => {
96
+ if (real !== realProjectDir && !real.startsWith(realProjectDir + sep)) {
97
+ throw new Error(`Path escapes project directory via symlink: ${original}`);
98
+ }
99
+ };
100
+ /**
101
+ * Walk up from `resolved` to find the deepest existing ancestor,
102
+ * then verify its real path is inside the project dir.
103
+ * This catches symlink escapes BEFORE any mkdir side effects.
104
+ */
105
+ const verifyNearestAncestor = (resolved, original) => {
106
+ let cur = resolved;
107
+ while (!existsSync(cur)) {
108
+ const parent = dirname(cur);
109
+ if (parent === cur)
110
+ return; // reached filesystem root — nothing to verify
111
+ cur = parent;
112
+ }
113
+ verifyRealPath(realpathSync(cur), original);
114
+ };
18
115
  return {
19
116
  killActiveShells() {
20
117
  for (const proc of activeShells) {
21
- proc.kill("SIGKILL");
118
+ if (proc.pid) {
119
+ try {
120
+ process.kill(-proc.pid, "SIGKILL");
121
+ }
122
+ catch { /* already exited */ }
123
+ }
124
+ }
125
+ for (const sessionId of activeSessions) {
126
+ killSession(sessionId, "SIGKILL");
127
+ stopReapingSession(sessionId);
22
128
  }
23
129
  activeShells.clear();
130
+ activeSessions.clear();
24
131
  },
25
132
  async read(path) {
26
- return readFileSync(resolvePath(path), "utf-8");
133
+ const target = resolvePath(path);
134
+ verifyRealPath(realpathSync(target), path);
135
+ return readFileSync(target, "utf-8");
27
136
  },
28
137
  async write(path, content) {
29
138
  const target = resolvePath(path);
139
+ verifyNearestAncestor(target, path); // before mkdir — prevents side effects outside project
30
140
  mkdirSync(dirname(target), { recursive: true });
141
+ try {
142
+ if (lstatSync(target).isSymbolicLink()) {
143
+ try {
144
+ verifyRealPath(realpathSync(target), path);
145
+ }
146
+ catch (e) {
147
+ if (e.code !== "ENOENT")
148
+ throw e;
149
+ // Dangling symlink — resolve what we can via nearest existing ancestor
150
+ verifyNearestAncestor(resolve(dirname(target), readlinkSync(target)), path);
151
+ }
152
+ }
153
+ }
154
+ catch (e) {
155
+ if (e.code !== "ENOENT")
156
+ throw e;
157
+ }
31
158
  writeFileSync(target, content);
32
159
  },
33
160
  async shell(command, options = {}) {
34
161
  const timeout = options.timeout ?? 30_000;
35
162
  const cwd = options.cwd ? resolvePath(options.cwd) : normalizedProjectDir;
163
+ try {
164
+ if (options.cwd)
165
+ verifyRealPath(realpathSync(cwd), options.cwd);
166
+ }
167
+ catch (err) {
168
+ if (err.code !== "ENOENT")
169
+ throw err;
170
+ // cwd doesn't exist — spawn will fail with ENOENT on its own
171
+ }
36
172
  return new Promise((resolve) => {
37
173
  const child = spawn("sh", ["-c", command], {
38
174
  cwd,
39
175
  stdio: ["pipe", "pipe", "pipe"],
176
+ detached: true,
40
177
  });
41
178
  activeShells.add(child);
42
- let stdout = "";
43
- let stderr = "";
179
+ if (child.pid)
180
+ activeSessions.add(child.pid);
181
+ const out = cappedBuffer();
182
+ const err = cappedBuffer();
44
183
  let timedOut = false;
45
184
  let exited = false;
46
- child.stdout.on("data", (chunk) => { stdout += chunk; });
47
- child.stderr.on("data", (chunk) => { stderr += chunk; });
48
- child.on("error", (err) => {
49
- activeShells.delete(child);
50
- resolve({ exitCode: 1, stdout, stderr: err.message });
51
- });
185
+ let killFallbackTimer = null;
186
+ child.stdout.on("data", (chunk) => { out.append(String(chunk)); });
187
+ child.stderr.on("data", (chunk) => { err.append(String(chunk)); });
52
188
  const timer = setTimeout(() => {
53
189
  timedOut = true;
54
- child.kill("SIGTERM");
55
- setTimeout(() => {
56
- if (!exited)
57
- child.kill("SIGKILL");
190
+ if (child.pid) {
191
+ killSession(child.pid, "SIGTERM");
192
+ }
193
+ killFallbackTimer = setTimeout(() => {
194
+ if (!exited && child.pid) {
195
+ killSession(child.pid, "SIGKILL");
196
+ }
58
197
  }, 5000);
198
+ killFallbackTimer.unref?.();
59
199
  }, timeout);
200
+ child.on("error", (err) => {
201
+ clearTimeout(timer);
202
+ if (killFallbackTimer)
203
+ clearTimeout(killFallbackTimer);
204
+ activeShells.delete(child);
205
+ if (child.pid) {
206
+ activeSessions.delete(child.pid);
207
+ stopReapingSession(child.pid);
208
+ }
209
+ resolve({ exitCode: 1, stdout: out.value, stderr: err.message });
210
+ });
60
211
  child.on("close", (code) => {
61
212
  exited = true;
62
213
  activeShells.delete(child);
63
214
  clearTimeout(timer);
215
+ if (killFallbackTimer)
216
+ clearTimeout(killFallbackTimer);
217
+ if (child.pid)
218
+ reapSessionWhenGone(child.pid);
64
219
  resolve({
65
220
  exitCode: timedOut ? 1 : (code ?? 1),
66
- stdout,
67
- stderr: timedOut ? stderr + "\ntimeout" : stderr,
221
+ stdout: out.value,
222
+ stderr: timedOut ? err.value + "\ntimeout" : err.value,
68
223
  });
69
224
  });
70
225
  });
@@ -74,6 +229,7 @@ export function createTools(projectDir) {
74
229
  method: options.method ?? "GET",
75
230
  headers: options.headers,
76
231
  body: options.body,
232
+ signal,
77
233
  });
78
234
  const body = await response.text();
79
235
  const headers = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {