@mailquilt/mcp 0.0.0-stage → 0.5.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,401 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { realpathSync } from "node:fs";
3
+ import {
4
+ lstat,
5
+ mkdir,
6
+ readFile,
7
+ realpath,
8
+ rename,
9
+ unlink,
10
+ writeFile,
11
+ } from "node:fs/promises";
12
+ import path from "node:path";
13
+
14
+ /** Error thrown when a path resolves outside the configured workspace root. */
15
+ export class WorkspacePathError extends Error {
16
+ readonly code: "invalid_path" | "not_a_file" | "not_found" | "outside_root";
17
+
18
+ constructor(
19
+ code: "invalid_path" | "not_a_file" | "not_found" | "outside_root",
20
+ message: string
21
+ ) {
22
+ super(message);
23
+ this.name = "WorkspacePathError";
24
+ this.code = code;
25
+ }
26
+ }
27
+
28
+ export interface ResolvedWorkspacePath {
29
+ /** Absolute, symlink-verified path on disk. */
30
+ readonly absolutePath: string;
31
+ /** Normalized POSIX-style path relative to the workspace root. */
32
+ readonly relativePath: string;
33
+ }
34
+
35
+ const isErrnoException = (error: unknown): error is NodeJS.ErrnoException =>
36
+ typeof error === "object" && error !== null && "code" in error;
37
+
38
+ /**
39
+ * Resolves the workspace root directory to a canonical realpath when it exists,
40
+ * or resolves its deepest existing ancestor when the directory is not yet created.
41
+ */
42
+ export const canonicalizeRoot = (root: string): string => {
43
+ const absolute = path.resolve(root);
44
+ try {
45
+ return realpathSync(absolute);
46
+ } catch (error) {
47
+ if (!isErrnoException(error) || error.code !== "ENOENT") {
48
+ throw error;
49
+ }
50
+ }
51
+ const missing: string[] = [];
52
+ let cursor = absolute;
53
+ while (true) {
54
+ const parent = path.dirname(cursor);
55
+ if (parent === cursor) {
56
+ return absolute;
57
+ }
58
+ missing.unshift(path.basename(cursor));
59
+ cursor = parent;
60
+ try {
61
+ return path.join(realpathSync(cursor), ...missing);
62
+ } catch (error) {
63
+ if (!isErrnoException(error) || error.code !== "ENOENT") {
64
+ throw error;
65
+ }
66
+ }
67
+ }
68
+ };
69
+
70
+ /** Returns true when `target` is strictly inside `root` (never equal to `root`). */
71
+ const isStrictlyInsideRoot = (root: string, target: string): boolean => {
72
+ const relative = path.relative(root, target);
73
+ return (
74
+ relative !== "" &&
75
+ relative !== ".." &&
76
+ !relative.startsWith(`..${path.sep}`) &&
77
+ !path.isAbsolute(relative)
78
+ );
79
+ };
80
+
81
+ /** Returns true when `target` is equal to or inside `root`. */
82
+ const isWithinRoot = (root: string, target: string): boolean => {
83
+ const relative = path.relative(root, target);
84
+ return (
85
+ relative === "" ||
86
+ (relative !== ".." &&
87
+ !relative.startsWith(`..${path.sep}`) &&
88
+ !path.isAbsolute(relative))
89
+ );
90
+ };
91
+
92
+ const toPosixRelative = (root: string, target: string): string =>
93
+ path.relative(root, target).split(path.sep).join("/");
94
+
95
+ const validateCandidate = (
96
+ canonicalRoot: string,
97
+ inputPath: string
98
+ ): { candidate: string; lexicalRelative: string } => {
99
+ if (typeof inputPath !== "string" || inputPath.trim() === "") {
100
+ throw new WorkspacePathError(
101
+ "invalid_path",
102
+ "Path must be a non-empty string."
103
+ );
104
+ }
105
+ if (inputPath.includes("\0")) {
106
+ throw new WorkspacePathError(
107
+ "invalid_path",
108
+ "Path must not contain null bytes."
109
+ );
110
+ }
111
+ const candidate = path.resolve(canonicalRoot, inputPath);
112
+ if (!isStrictlyInsideRoot(canonicalRoot, candidate)) {
113
+ throw new WorkspacePathError(
114
+ "outside_root",
115
+ `Path "${inputPath}" escapes the workspace root.`
116
+ );
117
+ }
118
+ return {
119
+ candidate,
120
+ lexicalRelative: path.relative(canonicalRoot, candidate),
121
+ };
122
+ };
123
+
124
+ /**
125
+ * Resolves an existing file inside `root`, rejecting `..` traversal, absolute
126
+ * paths outside `root`, directories, and symlinks pointing outside `root`.
127
+ */
128
+ export const resolveWorkspaceReadPath = async (
129
+ root: string,
130
+ inputPath: string
131
+ ): Promise<ResolvedWorkspacePath> => {
132
+ const canonicalRoot = canonicalizeRoot(root);
133
+ const { candidate } = validateCandidate(canonicalRoot, inputPath);
134
+
135
+ let realTarget: string;
136
+ try {
137
+ realTarget = await realpath(candidate);
138
+ } catch (error) {
139
+ if (isErrnoException(error) && error.code === "ENOENT") {
140
+ // Distinguish a broken symlink escaping root from a missing file.
141
+ try {
142
+ const linkStat = await lstat(candidate);
143
+ if (linkStat.isSymbolicLink()) {
144
+ throw new WorkspacePathError(
145
+ "outside_root",
146
+ `Symlink "${inputPath}" cannot be resolved inside the workspace root.`
147
+ );
148
+ }
149
+ } catch (lstatError) {
150
+ if (lstatError instanceof WorkspacePathError) {
151
+ throw lstatError;
152
+ }
153
+ }
154
+ throw new WorkspacePathError(
155
+ "not_found",
156
+ `File "${inputPath}" was not found.`
157
+ );
158
+ }
159
+ throw error;
160
+ }
161
+
162
+ if (!isStrictlyInsideRoot(canonicalRoot, realTarget)) {
163
+ throw new WorkspacePathError(
164
+ "outside_root",
165
+ `Path "${inputPath}" resolves outside the workspace root.`
166
+ );
167
+ }
168
+
169
+ const targetStat = await lstat(realTarget);
170
+ if (!targetStat.isFile()) {
171
+ throw new WorkspacePathError(
172
+ "not_a_file",
173
+ `Path "${inputPath}" is not a regular file.`
174
+ );
175
+ }
176
+
177
+ return {
178
+ absolutePath: realTarget,
179
+ relativePath: toPosixRelative(canonicalRoot, realTarget),
180
+ };
181
+ };
182
+
183
+ const resolveWriteSegment = async (
184
+ canonicalRoot: string,
185
+ inputPath: string,
186
+ current: string,
187
+ segments: readonly string[],
188
+ index: number
189
+ ): Promise<ResolvedWorkspacePath> => {
190
+ if (index >= segments.length) {
191
+ if (!isStrictlyInsideRoot(canonicalRoot, current)) {
192
+ throw new WorkspacePathError(
193
+ "outside_root",
194
+ `Path "${inputPath}" resolves outside the workspace root.`
195
+ );
196
+ }
197
+ return {
198
+ absolutePath: current,
199
+ relativePath: toPosixRelative(canonicalRoot, current),
200
+ };
201
+ }
202
+
203
+ const segment = segments[index];
204
+ if (!segment) {
205
+ return await resolveWriteSegment(
206
+ canonicalRoot,
207
+ inputPath,
208
+ current,
209
+ segments,
210
+ index + 1
211
+ );
212
+ }
213
+
214
+ const next = path.join(current, segment);
215
+ const isLast = index === segments.length - 1;
216
+
217
+ let entryStat: Awaited<ReturnType<typeof lstat>>;
218
+ try {
219
+ entryStat = await lstat(next);
220
+ } catch (error) {
221
+ if (isErrnoException(error) && error.code === "ENOENT") {
222
+ // From this component onward nothing exists on disk yet, so no
223
+ // symlink can redirect outside `current`.
224
+ const finalPath = path.join(current, ...segments.slice(index));
225
+ if (!isStrictlyInsideRoot(canonicalRoot, finalPath)) {
226
+ throw new WorkspacePathError(
227
+ "outside_root",
228
+ `Path "${inputPath}" escapes the workspace root.`
229
+ );
230
+ }
231
+ return {
232
+ absolutePath: finalPath,
233
+ relativePath: toPosixRelative(canonicalRoot, finalPath),
234
+ };
235
+ }
236
+ throw error;
237
+ }
238
+
239
+ if (entryStat.isSymbolicLink()) {
240
+ let realNext: string;
241
+ try {
242
+ realNext = await realpath(next);
243
+ } catch {
244
+ throw new WorkspacePathError(
245
+ "outside_root",
246
+ `Symlink "${inputPath}" cannot be resolved inside the workspace root.`
247
+ );
248
+ }
249
+ if (!isWithinRoot(canonicalRoot, realNext)) {
250
+ throw new WorkspacePathError(
251
+ "outside_root",
252
+ `Path "${inputPath}" traverses a symlink outside the workspace root.`
253
+ );
254
+ }
255
+ if (isLast && !isStrictlyInsideRoot(canonicalRoot, realNext)) {
256
+ throw new WorkspacePathError(
257
+ "outside_root",
258
+ `Path "${inputPath}" resolves outside the workspace root.`
259
+ );
260
+ }
261
+ const resolvedStat = await lstat(realNext);
262
+ if (isLast && resolvedStat.isDirectory()) {
263
+ throw new WorkspacePathError(
264
+ "not_a_file",
265
+ `Path "${inputPath}" is a directory.`
266
+ );
267
+ }
268
+ if (!isLast && !resolvedStat.isDirectory()) {
269
+ throw new WorkspacePathError(
270
+ "invalid_path",
271
+ `Parent of "${inputPath}" is not a directory.`
272
+ );
273
+ }
274
+ return await resolveWriteSegment(
275
+ canonicalRoot,
276
+ inputPath,
277
+ realNext,
278
+ segments,
279
+ index + 1
280
+ );
281
+ }
282
+
283
+ if (isLast) {
284
+ if (entryStat.isDirectory()) {
285
+ throw new WorkspacePathError(
286
+ "not_a_file",
287
+ `Path "${inputPath}" is a directory.`
288
+ );
289
+ }
290
+ return await resolveWriteSegment(
291
+ canonicalRoot,
292
+ inputPath,
293
+ next,
294
+ segments,
295
+ index + 1
296
+ );
297
+ }
298
+
299
+ if (!entryStat.isDirectory()) {
300
+ throw new WorkspacePathError(
301
+ "invalid_path",
302
+ `Parent of "${inputPath}" is not a directory.`
303
+ );
304
+ }
305
+ return await resolveWriteSegment(
306
+ canonicalRoot,
307
+ inputPath,
308
+ next,
309
+ segments,
310
+ index + 1
311
+ );
312
+ };
313
+
314
+ /**
315
+ * Resolves a target file path for writing inside `root`. Walks every existing
316
+ * path component from `root` downward to verify that neither an ancestor
317
+ * directory symlink nor the target symlink escapes `root`.
318
+ */
319
+ export const resolveWorkspaceWritePath = async (
320
+ root: string,
321
+ inputPath: string
322
+ ): Promise<ResolvedWorkspacePath> => {
323
+ const canonicalRoot = canonicalizeRoot(root);
324
+ const { lexicalRelative } = validateCandidate(canonicalRoot, inputPath);
325
+ const segments = lexicalRelative.split(path.sep);
326
+ return await resolveWriteSegment(
327
+ canonicalRoot,
328
+ inputPath,
329
+ canonicalRoot,
330
+ segments,
331
+ 0
332
+ );
333
+ };
334
+
335
+ /** Reads a UTF-8 file strictly inside `root`. */
336
+ export const readWorkspaceFile = async (
337
+ root: string,
338
+ inputPath: string
339
+ ): Promise<ResolvedWorkspacePath & { content: string }> => {
340
+ const resolved = await resolveWorkspaceReadPath(root, inputPath);
341
+ const content = await readFile(resolved.absolutePath, "utf-8");
342
+ return { ...resolved, content };
343
+ };
344
+
345
+ /**
346
+ * Atomically writes UTF-8 content to a file strictly inside `root` by writing
347
+ * to a sibling temporary file and renaming it into place.
348
+ */
349
+ export const writeWorkspaceFileAtomic = async (
350
+ root: string,
351
+ inputPath: string,
352
+ content: string,
353
+ options: { overwrite?: boolean } = {}
354
+ ): Promise<ResolvedWorkspacePath> => {
355
+ const { overwrite = true } = options;
356
+ const resolved = await resolveWorkspaceWritePath(root, inputPath);
357
+
358
+ if (!overwrite) {
359
+ try {
360
+ await lstat(resolved.absolutePath);
361
+ throw new Error(
362
+ `File "${resolved.relativePath}" already exists. Pass overwrite: true to replace it.`
363
+ );
364
+ } catch (error) {
365
+ if (!isErrnoException(error) || error.code !== "ENOENT") {
366
+ throw error;
367
+ }
368
+ }
369
+ }
370
+
371
+ const directory = path.dirname(resolved.absolutePath);
372
+ await mkdir(directory, { recursive: true });
373
+
374
+ // Re-verify parent directory realpath after creation.
375
+ const canonicalRoot = canonicalizeRoot(root);
376
+ const realDir = await realpath(directory);
377
+ if (!isWithinRoot(canonicalRoot, realDir)) {
378
+ throw new WorkspacePathError(
379
+ "outside_root",
380
+ `Parent directory for "${inputPath}" escapes the workspace root.`
381
+ );
382
+ }
383
+
384
+ const tempPath = path.join(
385
+ realDir,
386
+ `.mailquilt-tmp-${process.pid}-${randomBytes(6).toString("hex")}`
387
+ );
388
+ try {
389
+ await writeFile(tempPath, content, "utf-8");
390
+ await rename(tempPath, resolved.absolutePath);
391
+ } catch (error) {
392
+ try {
393
+ await unlink(tempPath);
394
+ } catch {
395
+ // Ignore cleanup failures if the temp file was never created.
396
+ }
397
+ throw error;
398
+ }
399
+
400
+ return resolved;
401
+ };