@exulu/backend 5.12.0 → 5.14.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.
@@ -0,0 +1,306 @@
1
+ import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
2
+ import { randomBytes } from 'node:crypto'
3
+ import { basename, dirname, join, resolve, sep } from 'node:path'
4
+ import { execFile } from 'node:child_process'
5
+ import { promisify } from 'node:util'
6
+ import { listS3ObjectsByPrefix, getS3ObjectBytes } from '@SRC/uppy/index.ts'
7
+ import { PROJECT_DIR, projectFilePrefix } from '@SRC/exulu/project-files.ts'
8
+ import { hasProjectAccess } from '@SRC/exulu/project-access.ts'
9
+ import type { ExuluConfig } from '@SRC/exulu/app/index.ts'
10
+
11
+ type Entry = { name: string; size: number }
12
+
13
+ /**
14
+ * What has to change in `<sessionDir>/project/` so it mirrors the project folder:
15
+ * new and size-changed files are downloaded, local files the project no longer
16
+ * has are removed. Same rule as the session restore (`needsDownload`): size only.
17
+ */
18
+ export function planProjectSync(remote: Entry[], local: Entry[]): { download: string[]; remove: string[] } {
19
+ const localSizes = new Map(local.map((e) => [e.name, e.size]))
20
+ const remoteNames = new Set(remote.map((e) => e.name))
21
+ return {
22
+ download: remote.filter((e) => localSizes.get(e.name) !== e.size).map((e) => e.name),
23
+ remove: local.filter((e) => !remoteNames.has(e.name)).map((e) => e.name),
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Records which project the session's `project/` folder was last synced from. It
29
+ * lives OUTSIDE the session directory (the sandbox may only write inside it), and
30
+ * it is what lets a session without a project tell "a project folder we created,
31
+ * to be removed after a detach" from "a folder the agent named project/ itself".
32
+ */
33
+ export function projectSyncMarkerPath(sessionDir: string): string {
34
+ return join(dirname(sessionDir), '.project-sync', basename(sessionDir))
35
+ }
36
+
37
+ async function readMarker(sessionDir: string): Promise<string | null> {
38
+ try {
39
+ return (await readFile(projectSyncMarkerPath(sessionDir), 'utf8')).trim() || null
40
+ } catch {
41
+ return null
42
+ }
43
+ }
44
+
45
+ /** Removes the marker; part of a sandbox's cleanup. */
46
+ export async function clearProjectSyncMarker(sessionDir: string): Promise<void> {
47
+ await rm(projectSyncMarkerPath(sessionDir), { force: true })
48
+ }
49
+
50
+ const isFlatName = (name: string) => !!name && !name.includes('/') && !name.includes('\\') && name !== '.' && name !== '..'
51
+
52
+ /**
53
+ * Backend-only helper directories, siblings of the session dirs under
54
+ * /tmp/exulu-sessions (same filesystem, so rename never crosses devices). The
55
+ * sandbox policy only allows writes inside `sessionDir`, and the leading dot
56
+ * keeps the names apart from session ids (uuids).
57
+ */
58
+ const HELPER_KINDS = ['.project-staging', '.project-trash'] as const
59
+ type HelperKind = (typeof HELPER_KINDS)[number]
60
+ const helperRoot = (sessionDir: string, kind: HelperKind) => join(dirname(sessionDir), kind)
61
+ const helperPath = (sessionDir: string, kind: HelperKind) =>
62
+ join(helperRoot(sessionDir, kind), `${basename(sessionDir)}-${randomBytes(8).toString('hex')}`)
63
+
64
+ const execFileAsync = promisify(execFile)
65
+
66
+ /**
67
+ * Recursively remove a trash or staging directory. Node's fs.rm walks by path
68
+ * (lstat, then readdir/rmdir by name), so a process the agent left running inside
69
+ * the moved-away folder could swap a subdirectory for a link mid-walk and steer it
70
+ * outside. coreutils/BSD `rm` descends by file descriptor (openat/unlinkat, links
71
+ * never followed), so it is spawned directly, without a shell. Only paths strictly
72
+ * inside one of the two helper roots are accepted, never anything under a session
73
+ * dir. Failures are logged: a leftover trash dir is harmless and swept later.
74
+ */
75
+ export async function removeTreeSafely(path: string, sessionDir: string): Promise<boolean> {
76
+ const target = resolve(path)
77
+ const inside = HELPER_KINDS.some((kind) => {
78
+ const root = resolve(helperRoot(sessionDir, kind))
79
+ return target.startsWith(root + sep) && !target.slice(root.length + 1).includes(sep)
80
+ })
81
+ if (!inside) {
82
+ console.error(`[SKILLS] Refusing to remove ${path}: not a project staging or trash directory.`)
83
+ return false
84
+ }
85
+ try {
86
+ await execFileAsync('rm', ['-rf', '--', target])
87
+ return true
88
+ } catch (err) {
89
+ console.error(`[SKILLS] Failed to remove ${target}; leaving it for a later sweep.`, err)
90
+ return false
91
+ }
92
+ }
93
+
94
+ const DAY_MS = 24 * 60 * 60 * 1000
95
+
96
+ /** Remove this session's helper dirs a crash or failed rm left behind more than a day ago. */
97
+ async function sweepStaleHelpers(sessionDir: string): Promise<void> {
98
+ const prefix = `${basename(sessionDir)}-`
99
+ for (const kind of HELPER_KINDS) {
100
+ const root = helperRoot(sessionDir, kind)
101
+ let names: string[]
102
+ try {
103
+ names = await readdir(root)
104
+ } catch {
105
+ continue
106
+ }
107
+ for (const name of names) {
108
+ if (!name.startsWith(prefix)) continue
109
+ const st = await lstat(join(root, name)).catch(() => null)
110
+ if (st && Date.now() - st.mtimeMs > DAY_MS) await removeTreeSafely(join(root, name), sessionDir)
111
+ }
112
+ }
113
+ }
114
+
115
+ const errCode = (err: unknown) => (err as NodeJS.ErrnoException | undefined)?.code
116
+
117
+ /**
118
+ * Move `<sessionDir>/project` (whatever it is: directory, file or link) out of
119
+ * the agent's reach. rename acts on the entry itself and never follows a link.
120
+ * Returns the trash path, or null when there was nothing to move.
121
+ */
122
+ async function moveAway(dir: string, sessionDir: string): Promise<string | null> {
123
+ const trash = helperPath(sessionDir, '.project-trash')
124
+ await mkdir(dirname(trash), { recursive: true })
125
+ try {
126
+ await rename(dir, trash)
127
+ return trash
128
+ } catch (err) {
129
+ if (errCode(err) === 'ENOENT') return null
130
+ throw err
131
+ }
132
+ }
133
+
134
+ async function discard(path: string | null, sessionDir: string): Promise<void> {
135
+ if (path) await removeTreeSafely(path, sessionDir)
136
+ }
137
+
138
+ /**
139
+ * Move any entry of the session directory (a directory, file or link) out of the
140
+ * agent's reach and delete it there; see moveAway and removeTreeSafely. Used for
141
+ * backend-side deletes under the session dir (e.g. a skill folder being replaced).
142
+ */
143
+ export async function discardEntry(path: string, sessionDir: string): Promise<void> {
144
+ await discard(await moveAway(path, sessionDir), sessionDir)
145
+ }
146
+
147
+ /**
148
+ * Mirror the project's shared files into `<sessionDir>/project/` (read-only by
149
+ * convention: the sandbox never writes this folder back). With `projectId: null`
150
+ * a folder that an earlier sync created is removed; a folder of that name the
151
+ * agent made in a session that never had a project is left alone. Failures while
152
+ * mirroring are logged and not thrown — one bad object must not end a turn. The
153
+ * detach branch (`projectId: null`) is the exception: a failure removing the old
154
+ * folder or its marker can propagate, so callers must catch it (create-sandbox.ts does).
155
+ *
156
+ * The agent can swap `project` (or anything in it) for a link at any moment, and
157
+ * this runs as the backend user, so it NEVER operates under the agent-writable
158
+ * path: the old folder is renamed away, the new one is built in a private staging
159
+ * directory and renamed into place. The only operations on `<sessionDir>/project`
160
+ * are those two renames.
161
+ */
162
+ export async function syncProjectDir(args: {
163
+ sessionDir: string
164
+ projectId: string | null
165
+ config: ExuluConfig
166
+ }): Promise<void> {
167
+ const { sessionDir, projectId, config } = args
168
+ const dir = join(sessionDir, PROJECT_DIR)
169
+ const previous = await readMarker(sessionDir)
170
+
171
+ if (!projectId) {
172
+ if (previous !== null) {
173
+ await discard(await moveAway(dir, sessionDir), sessionDir)
174
+ await clearProjectSyncMarker(sessionDir)
175
+ }
176
+ return
177
+ }
178
+
179
+ if (!config.fileUploads) {
180
+ console.warn(`[SKILLS] File uploads are not configured; project files are not synced into ${sessionDir}.`)
181
+ return
182
+ }
183
+
184
+ const { projectPrefix } = projectFilePrefix(projectId)
185
+ const remote = new Map<string, { size: number; key: string }>()
186
+ try {
187
+ for (const obj of await listS3ObjectsByPrefix(projectPrefix, config)) {
188
+ // listS3ObjectsByPrefix prepends the general s3prefix; recover the name
189
+ // the same way restoreArtifactsFromS3 does.
190
+ const idx = obj.key.indexOf(projectPrefix)
191
+ const name = idx >= 0 ? obj.key.slice(idx + projectPrefix.length) : ''
192
+ if (!isFlatName(name)) continue
193
+ remote.set(name, { size: obj.size, key: obj.key })
194
+ }
195
+ } catch (err) {
196
+ // Keep the local copy as it is: a transient S3 error must not empty the folder.
197
+ console.error(`[SKILLS] Failed to list project files for project ${projectId}; keeping the local copy.`, err)
198
+ return
199
+ }
200
+
201
+ await sweepStaleHelpers(sessionDir)
202
+
203
+ await mkdir(dirname(projectSyncMarkerPath(sessionDir)), { recursive: true })
204
+ // Written before anything moves, so a crash halfway still lets a later detach clean up.
205
+ await writeFile(projectSyncMarkerPath(sessionDir), projectId)
206
+
207
+ const trashes: Array<string | null> = []
208
+ const staging = helperPath(sessionDir, '.project-staging')
209
+ let installed = false
210
+ try {
211
+ const old = await moveAway(dir, sessionDir)
212
+ trashes.push(old)
213
+ await mkdir(dirname(staging), { recursive: true })
214
+ await mkdir(staging) // fresh, private: nothing else knows this path
215
+
216
+ // Reuse unchanged files of the same project. Only regular files are taken
217
+ // (lstat, no link is followed); another project's files never are.
218
+ const local: Array<{ name: string; size: number }> = []
219
+ const oldStat = old && previous === projectId ? await lstat(old).catch(() => null) : null
220
+ if (old && oldStat?.isDirectory()) {
221
+ for (const name of await readdir(old)) {
222
+ const st = await lstat(join(old, name)).catch(() => null)
223
+ if (!st?.isFile() || remote.get(name)?.size !== st.size) continue
224
+ await rename(join(old, name), join(staging, name))
225
+ // A process still inside the old folder could have swapped the entry
226
+ // between lstat and rename; anything that is not a regular file goes back.
227
+ const moved = await lstat(join(staging, name)).catch(() => null)
228
+ if (!moved?.isFile()) {
229
+ await rename(join(staging, name), join(old, `.rejected-${randomBytes(4).toString('hex')}`)).catch(() => {})
230
+ continue
231
+ }
232
+ local.push({ name, size: moved.size })
233
+ }
234
+ }
235
+
236
+ const plan = planProjectSync(
237
+ [...remote].map(([name, r]) => ({ name, size: r.size })),
238
+ local,
239
+ )
240
+ // Sequential on purpose: a project holds up to 200 files and a turn must not
241
+ // fan out that many parallel S3 reads.
242
+ for (const name of plan.download) {
243
+ try {
244
+ const bytes = await getS3ObjectBytes(remote.get(name)!.key, config)
245
+ await writeFile(join(staging, name), bytes, { flag: 'wx' })
246
+ } catch (err) {
247
+ console.error(`[SKILLS] Failed to sync project file ${name} (project ${projectId}); continuing.`, err)
248
+ }
249
+ }
250
+
251
+ // Swap in. The agent may have planted something at project/ meanwhile:
252
+ // move that away too and retry once, then give up for this turn.
253
+ for (let attempt = 0; attempt < 2 && !installed; attempt++) {
254
+ try {
255
+ await rename(staging, dir)
256
+ installed = true
257
+ } catch (err) {
258
+ const code = errCode(err)
259
+ if (attempt === 0 && (code === 'EEXIST' || code === 'ENOTEMPTY' || code === 'ENOTDIR' || code === 'EISDIR')) {
260
+ trashes.push(await moveAway(dir, sessionDir))
261
+ continue
262
+ }
263
+ console.error(`[SKILLS] Could not install the project folder for session ${sessionDir}; skipping this turn.`, err)
264
+ break
265
+ }
266
+ }
267
+ } catch (err) {
268
+ console.error(`[SKILLS] Project sync failed for project ${projectId}; continuing.`, err)
269
+ } finally {
270
+ if (!installed) await discard(staging, sessionDir)
271
+ for (const t of trashes) await discard(t, sessionDir)
272
+ }
273
+ }
274
+
275
+ type ProjectRow = { id: string; created_by?: number | string | null; rights_mode?: string | null }
276
+ type OwnerLike = Parameters<typeof hasProjectAccess>[0]['user']
277
+
278
+ /**
279
+ * The project id the session's sandbox may show: only when the session OWNER can
280
+ * read the project (one sandbox per session, so it follows the owner, not the
281
+ * speaker). A missing project, a missing owner, no access or any error → null;
282
+ * resolving must never break the chat turn.
283
+ */
284
+ export async function resolveSandboxProjectId(
285
+ args: { projectId?: string | null; ownerId?: number | string | null; owner?: OwnerLike },
286
+ deps: {
287
+ getProject: (id: string) => Promise<ProjectRow | undefined | null>
288
+ getRbac: (project: ProjectRow) => Promise<{ type: string; users?: any[]; roles?: any[]; teams?: any[] }>
289
+ getUser: (id: number | string) => Promise<OwnerLike | undefined | null>
290
+ },
291
+ ): Promise<string | null> {
292
+ const { projectId, ownerId } = args
293
+ if (!projectId || ownerId == null) return null
294
+ try {
295
+ const project = await deps.getProject(projectId)
296
+ if (!project) return null
297
+ const owner = args.owner && String(args.owner.id) === String(ownerId) ? args.owner : await deps.getUser(ownerId)
298
+ if (!owner) return null
299
+ const rbac = await deps.getRbac(project)
300
+ const allowed = hasProjectAccess({ project, rbac, user: owner, want: 'read' })
301
+ return allowed ? String(project.id) : null
302
+ } catch (err) {
303
+ console.error(`[SKILLS] Failed to resolve project ${projectId} for the session sandbox; continuing without project files.`, err)
304
+ return null
305
+ }
306
+ }
@@ -0,0 +1,69 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { closeSync, constants, openSync } from "node:fs";
3
+ import { mkdtemp, rm, truncate, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { MAX_ADOPT_UPLOAD_BYTES } from "@SRC/exulu/session-file-adopt";
7
+ import { readRegularFileInside } from "./safe-fs";
8
+
9
+ let dir: string;
10
+ beforeEach(async () => {
11
+ dir = await mkdtemp(join(tmpdir(), "exulu-safefs-"));
12
+ jest.spyOn(console, "warn").mockImplementation(() => {});
13
+ });
14
+ afterEach(async () => {
15
+ jest.restoreAllMocks();
16
+ await rm(dir, { recursive: true, force: true });
17
+ });
18
+
19
+ const canMkfifo = (() => {
20
+ try {
21
+ execFileSync("mkfifo", [join(tmpdir(), `exulu-fifo-probe-${process.pid}`)]);
22
+ execFileSync("rm", ["-f", join(tmpdir(), `exulu-fifo-probe-${process.pid}`)]);
23
+ return true;
24
+ } catch {
25
+ return false;
26
+ }
27
+ })();
28
+
29
+ describe("readRegularFileInside: special files and size", () => {
30
+ (canMkfifo ? it : it.skip)(
31
+ "a FIFO at the path returns null at once instead of blocking a threadpool thread",
32
+ async () => {
33
+ const fifo = join(dir, "f");
34
+ execFileSync("mkfifo", [fifo]);
35
+ const result = await Promise.race([
36
+ readRegularFileInside(dir, fifo),
37
+ new Promise((r) => setTimeout(() => r("still blocked"), 1500)),
38
+ ]);
39
+ // Release a reader that a regression left blocked, so the suite can still exit.
40
+ try {
41
+ closeSync(openSync(fifo, constants.O_WRONLY | constants.O_NONBLOCK));
42
+ } catch {
43
+ // no reader waiting: nothing to release
44
+ }
45
+ expect(result).toBeNull();
46
+ },
47
+ 5000,
48
+ );
49
+
50
+ it("skips a (sparse) file just over the upload cap and reads one just under it", async () => {
51
+ const over = join(dir, "over.bin");
52
+ const under = join(dir, "under.bin");
53
+ await writeFile(over, "");
54
+ await writeFile(under, "");
55
+ await truncate(over, MAX_ADOPT_UPLOAD_BYTES + 1);
56
+ await truncate(under, MAX_ADOPT_UPLOAD_BYTES - 1);
57
+ expect(await readRegularFileInside(dir, over)).toBeNull();
58
+ expect((await readRegularFileInside(dir, under))?.length).toBe(MAX_ADOPT_UPLOAD_BYTES - 1);
59
+ }, 20000);
60
+ });
61
+
62
+ describe("readRegularFileInside: small and empty files", () => {
63
+ it("reads a small file exactly and an empty file as an empty buffer", async () => {
64
+ await writeFile(join(dir, "small.txt"), "hello");
65
+ await writeFile(join(dir, "empty.txt"), "");
66
+ expect(String(await readRegularFileInside(dir, join(dir, "small.txt")))).toBe("hello");
67
+ expect((await readRegularFileInside(dir, join(dir, "empty.txt")))?.length).toBe(0);
68
+ });
69
+ });
@@ -0,0 +1,216 @@
1
+ import { constants } from 'node:fs'
2
+ import { lstat, mkdir, open, readlink, realpath, rename, unlink, writeFile } from 'node:fs/promises'
3
+ import { randomBytes } from 'node:crypto'
4
+ import { discardEntry } from './project-sync'
5
+ import { dirname, isAbsolute, join, sep } from 'node:path'
6
+ import { MAX_ADOPT_UPLOAD_BYTES } from '@SRC/exulu/session-file-adopt'
7
+
8
+ /**
9
+ * Filesystem access by the BACKEND (not the sandboxed agent) inside a session
10
+ * directory. The agent can write anything under `sessionDir` — symlinks included,
11
+ * possibly from a process that outlives its command — while the backend runs with
12
+ * more rights than the sandbox. Every backend read or write there must therefore
13
+ * refuse to follow a link out of the session directory: a followed link would let
14
+ * the agent read files the sandbox denies (uploaded as "artifacts") or make the
15
+ * backend overwrite files outside the session.
16
+ *
17
+ * Node has no openat/renameat, so a link swapped in between a check and the
18
+ * operation remains a (narrow) race; on Linux the read path closes it by checking
19
+ * the opened descriptor's real location via /proc.
20
+ */
21
+
22
+ export class UnsafeSessionPathError extends Error {
23
+ constructor(message: string) {
24
+ super(message)
25
+ this.name = 'UnsafeSessionPathError'
26
+ }
27
+ }
28
+
29
+ const errCode = (err: unknown) => (err as NodeJS.ErrnoException | undefined)?.code
30
+
31
+ const isInside = (root: string, path: string) => path === root || path.startsWith(root + sep)
32
+
33
+ /**
34
+ * Read `path` (absolute, under `sessionDir`) only when it is a regular file whose
35
+ * directory really lies inside the session directory. Returns null — and logs —
36
+ * for a symlink, anything that is not a regular file, or a path that resolves
37
+ * outside; never throws for those, so one planted link cannot fail a whole tool call.
38
+ */
39
+ export async function readRegularFileInside(sessionDir: string, path: string): Promise<Buffer | null> {
40
+ const skip = (why: string) => {
41
+ console.warn(`[SKILLS] Not reading ${path} back from the sandbox: ${why}.`)
42
+ return null
43
+ }
44
+ let root: string
45
+ let parent: string
46
+ try {
47
+ root = await realpath(sessionDir)
48
+ parent = await realpath(dirname(path))
49
+ } catch {
50
+ return skip('path does not resolve')
51
+ }
52
+ if (!isInside(root, parent)) return skip('it resolves outside the session directory')
53
+
54
+ let handle
55
+ try {
56
+ // O_NOFOLLOW: a final component that is a link fails with ELOOP instead of being followed.
57
+ // O_NONBLOCK: a FIFO the agent planted would otherwise block this open (and a
58
+ // libuv threadpool thread with it) until a writer appears; with it the open
59
+ // returns at once and the isFile() check below skips the entry.
60
+ // O_NOCTTY: opening a terminal device must never make it our controlling tty.
61
+ handle = await open(
62
+ path,
63
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK | constants.O_NOCTTY,
64
+ )
65
+ } catch (err) {
66
+ return skip(errCode(err) === 'ELOOP' ? 'it is a symbolic link' : `open failed (${errCode(err) ?? 'unknown'})`)
67
+ }
68
+ try {
69
+ const st = await handle.stat()
70
+ if (!st.isFile()) return skip('it is not a regular file')
71
+ // Same ceiling as an upload: a sparse `truncate -s 2G` costs the agent no
72
+ // disk but would make the backend read and upload gigabytes.
73
+ if (st.size > MAX_ADOPT_UPLOAD_BYTES) {
74
+ return skip(`it is larger than the ${MAX_ADOPT_UPLOAD_BYTES / (1024 * 1024)}MB upload limit (${st.size} bytes)`)
75
+ }
76
+ // A parent directory swapped for a link after the realpath check above would
77
+ // have steered the open elsewhere. Where the descriptor's real path is
78
+ // available (Linux), check that instead of trusting the earlier check.
79
+ const fdPath = await readlink(`/proc/self/fd/${handle.fd}`).catch(() => null)
80
+ if (fdPath !== null) {
81
+ if (!isInside(root, fdPath)) return skip('it resolves outside the session directory')
82
+ } else {
83
+ const again = await realpath(dirname(path)).catch(() => null)
84
+ if (again === null || !isInside(root, again)) return skip('it resolves outside the session directory')
85
+ }
86
+ // Bounded read: the file may still grow after the fstat above.
87
+ const chunks: Buffer[] = []
88
+ let total = 0
89
+ // Sized from fstat (+1 to see EOF in one read), at least 64 KiB in case the
90
+ // file grows, at most 1 MiB per read.
91
+ const chunkSize = Math.min(Math.max(st.size + 1, 64 * 1024), 1024 * 1024)
92
+ for (;;) {
93
+ const chunk = Buffer.allocUnsafe(chunkSize)
94
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null)
95
+ if (bytesRead === 0) break
96
+ total += bytesRead
97
+ if (total > MAX_ADOPT_UPLOAD_BYTES) return skip('it grew past the upload limit while being read')
98
+ chunks.push(chunk.subarray(0, bytesRead))
99
+ }
100
+ return Buffer.concat(chunks, total)
101
+ } finally {
102
+ await handle.close().catch(() => {})
103
+ }
104
+ }
105
+
106
+ /** Splits a session-relative path, refusing absolute paths, `..` and empty input. */
107
+ function safeSegments(relativePath: string): string[] {
108
+ if (!relativePath || isAbsolute(relativePath) || relativePath.includes('\\')) {
109
+ throw new UnsafeSessionPathError(`Refusing path "${relativePath}": not a plain relative path.`)
110
+ }
111
+ const segments = relativePath.split('/').filter((s) => s !== '' && s !== '.')
112
+ if (segments.length === 0 || segments.includes('..')) {
113
+ throw new UnsafeSessionPathError(`Refusing path "${relativePath}": it contains a ".." segment or no file name.`)
114
+ }
115
+ return segments
116
+ }
117
+
118
+ /**
119
+ * Create `<sessionDir>/<segments...>` one component at a time. Any existing
120
+ * component that is not a real directory (a link, a file) is refused; the final
121
+ * parent's real path must still lie inside the session directory afterwards.
122
+ */
123
+ async function ensureDirInside(sessionDir: string, segments: string[]): Promise<string> {
124
+ const root = await realpath(sessionDir)
125
+ let current = sessionDir
126
+ for (const segment of segments) {
127
+ current = join(current, segment)
128
+ let st = await lstat(current).catch((err) => (errCode(err) === 'ENOENT' ? null : Promise.reject(err)))
129
+ if (!st) {
130
+ try {
131
+ await mkdir(current)
132
+ } catch (err) {
133
+ if (errCode(err) !== 'EEXIST') throw err
134
+ }
135
+ st = await lstat(current)
136
+ }
137
+ if (!st.isDirectory()) {
138
+ throw new UnsafeSessionPathError(`Refusing to write under ${current}: it is not a real directory.`)
139
+ }
140
+ }
141
+ const real = await realpath(current)
142
+ if (!isInside(root, real)) {
143
+ throw new UnsafeSessionPathError(`Refusing to write under ${current}: it resolves outside the session directory.`)
144
+ }
145
+ return current
146
+ }
147
+
148
+ /**
149
+ * Write `bytes` to `<sessionDir>/<relativePath>` without following links. Parents
150
+ * are created component by component (see ensureDirInside). The bytes go to an
151
+ * exclusive temp file in the same directory which is then renamed over the
152
+ * destination: rename replaces a link planted at the destination instead of
153
+ * writing through it. Returns the absolute destination path.
154
+ */
155
+ export async function writeFileInside(sessionDir: string, relativePath: string, bytes: Buffer | string): Promise<string> {
156
+ const segments = safeSegments(relativePath)
157
+ const name = segments[segments.length - 1]!
158
+ const parent = await ensureDirInside(sessionDir, segments.slice(0, -1))
159
+ const destination = join(parent, name)
160
+ const temp = join(parent, `.exulu-write-${randomBytes(8).toString('hex')}`)
161
+ // 'wx' = O_CREAT | O_EXCL: never opens an existing entry (link or not).
162
+ await writeFile(temp, bytes, { flag: 'wx' })
163
+ try {
164
+ await rename(temp, destination)
165
+ } catch (err) {
166
+ await unlink(temp).catch(() => {})
167
+ throw err
168
+ }
169
+ return destination
170
+ }
171
+
172
+ /**
173
+ * Make `<sessionDir>/<relativeDir>` (one level, e.g. "skills") a real directory:
174
+ * an existing link or file there is unlinked itself (never followed) and a real
175
+ * directory created in its place.
176
+ */
177
+ export async function ensureRealDirectory(sessionDir: string, relativeDir: string): Promise<string> {
178
+ const segments = safeSegments(relativeDir)
179
+ let current = sessionDir
180
+ for (const segment of segments) {
181
+ current = join(current, segment)
182
+ const st = await lstat(current).catch(() => null)
183
+ if (st && !st.isDirectory()) {
184
+ console.warn(`[SKILLS] ${current} is not a real directory; replacing it.`)
185
+ await unlink(current)
186
+ }
187
+ }
188
+ return ensureDirInside(sessionDir, segments)
189
+ }
190
+
191
+ /**
192
+ * Remove `<sessionDir>/<relativePath>` when it is a real directory inside the
193
+ * session directory; a link or file there is unlinked itself. The recursive
194
+ * removal only runs after the parent's real path was checked, so it never walks
195
+ * through a symlinked parent.
196
+ */
197
+ export async function removeEntryInside(sessionDir: string, relativePath: string): Promise<void> {
198
+ const segments = safeSegments(relativePath)
199
+ const target = join(sessionDir, ...segments)
200
+ const root = await realpath(sessionDir)
201
+ const parentReal = await realpath(dirname(target)).catch(() => null)
202
+ if (parentReal === null) return // parent missing: nothing to remove
203
+ if (!isInside(root, parentReal)) {
204
+ throw new UnsafeSessionPathError(`Refusing to remove ${target}: its parent resolves outside the session directory.`)
205
+ }
206
+ const st = await lstat(target).catch(() => null)
207
+ if (!st) return
208
+ if (!st.isDirectory()) {
209
+ await unlink(target)
210
+ return
211
+ }
212
+ // Same as the project folder (project-sync.ts): rename the directory out of
213
+ // the session (rename acts on the entry, never through it), then delete the
214
+ // moved copy with an fd-based rm that a process still inside cannot steer.
215
+ await discardEntry(target, sessionDir)
216
+ }