@mwillbanks/ast-mcp 0.6.3 → 0.6.4
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/ast-mcp.js +292 -292
- package/dist/ast-mcp.js.map +14 -13
- package/dist/workers/code-intelligence-worker.js +2 -2
- package/dist/workers/code-intelligence-worker.js.map +4 -4
- package/package.json +1 -1
- package/src/helpers/mcp-schema.ts +91 -8
- package/src/intelligence/mutation/journal.ts +101 -20
- package/src/intelligence/mutation/locks.ts +92 -28
- package/src/patch/engine.ts +166 -87
- package/src/runtime/attributes.ts +158 -1
- package/src/runtime/file-delete.ts +111 -65
- package/src/runtime/file-rename.ts +126 -20
- package/src/runtime/parent-directories.ts +114 -0
- package/src/tools/code-intelligence-compute.ts +14 -6
- package/src/tools/code-intelligence-worker.ts +11 -2
- package/src/tools/code-intelligence.ts +126 -40
- package/src/tools/files.ts +2 -2
- package/src/tools/lifecycle.ts +30 -29
- package/templates/AGENTS.md +1 -0
- package/templates/skills/ast-mcp/SKILL.md +2 -0
- package/templates/skills/ast-mcp/references/agents-guidance.md +1 -0
- package/templates/skills/ast-mcp/references/patch-state-machine.md +8 -2
- package/templates/skills/ast-mcp/references/tool-catalog.md +4 -1
package/src/patch/engine.ts
CHANGED
|
@@ -1,15 +1,6 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import {
|
|
4
|
-
chmod,
|
|
5
|
-
lstat,
|
|
6
|
-
mkdir,
|
|
7
|
-
realpath,
|
|
8
|
-
rename,
|
|
9
|
-
rmdir,
|
|
10
|
-
unlink,
|
|
11
|
-
writeFile,
|
|
12
|
-
} from "node:fs/promises";
|
|
3
|
+
import { chmod, lstat, rename, unlink, writeFile } from "node:fs/promises";
|
|
13
4
|
import path from "node:path";
|
|
14
5
|
|
|
15
6
|
import { currentConfig } from "../config";
|
|
@@ -44,6 +35,11 @@ import {
|
|
|
44
35
|
withFencedFileLock,
|
|
45
36
|
withFencedFileLocks,
|
|
46
37
|
} from "../runtime/locks";
|
|
38
|
+
import {
|
|
39
|
+
ensureParentDirectories,
|
|
40
|
+
removeCreatedDirectories,
|
|
41
|
+
revalidateWritePath,
|
|
42
|
+
} from "../runtime/parent-directories";
|
|
47
43
|
import { resolveWritablePath } from "../runtime/paths";
|
|
48
44
|
import { requireExpectedHash, verifyExpectedHash } from "../runtime/policy";
|
|
49
45
|
import {
|
|
@@ -113,48 +109,12 @@ async function removeTemporary(filePath: string) {
|
|
|
113
109
|
} catch {}
|
|
114
110
|
}
|
|
115
111
|
|
|
116
|
-
async function ensureParent(filePath: string): Promise<string[]> {
|
|
117
|
-
const parent = path.dirname(filePath);
|
|
118
|
-
const first = await mkdir(parent, { recursive: true });
|
|
119
|
-
const revalidated = await resolveWritablePath(filePath);
|
|
120
|
-
if (revalidated !== filePath)
|
|
121
|
-
throw new Error("Parent creation changed the resolved write path");
|
|
122
|
-
if (!first) return [];
|
|
123
|
-
// Recursive mkdir can return a different physical alias on Windows.
|
|
124
|
-
const [canonicalFirst, canonicalParent] = await Promise.all([
|
|
125
|
-
realpath(first),
|
|
126
|
-
realpath(parent),
|
|
127
|
-
]);
|
|
128
|
-
const relative = path.relative(canonicalFirst, canonicalParent);
|
|
129
|
-
if (
|
|
130
|
-
relative === ".." ||
|
|
131
|
-
relative.startsWith(`..${path.sep}`) ||
|
|
132
|
-
path.isAbsolute(relative)
|
|
133
|
-
)
|
|
134
|
-
throw new Error(
|
|
135
|
-
"Created parent directory escaped its first created ancestor",
|
|
136
|
-
);
|
|
137
|
-
const created = [canonicalFirst];
|
|
138
|
-
let current = canonicalFirst;
|
|
139
|
-
for (const segment of relative.split(path.sep)) {
|
|
140
|
-
if (!segment) continue;
|
|
141
|
-
current = path.join(current, segment);
|
|
142
|
-
created.push(current);
|
|
143
|
-
}
|
|
144
|
-
return created;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
112
|
async function ignoreFailure(operation: Promise<unknown>): Promise<void> {
|
|
148
113
|
try {
|
|
149
114
|
await operation;
|
|
150
115
|
} catch {}
|
|
151
116
|
}
|
|
152
117
|
|
|
153
|
-
async function removeCreatedDirectories(directories: string[]): Promise<void> {
|
|
154
|
-
for (const directory of [...directories].reverse())
|
|
155
|
-
await ignoreFailure(rmdir(directory));
|
|
156
|
-
}
|
|
157
|
-
|
|
158
118
|
async function commit(
|
|
159
119
|
filePath: string,
|
|
160
120
|
content: string,
|
|
@@ -169,18 +129,16 @@ async function commit(
|
|
|
169
129
|
sha256: string;
|
|
170
130
|
}> {
|
|
171
131
|
const next = temporary(filePath);
|
|
172
|
-
|
|
132
|
+
const createdDirectories: string[] = [];
|
|
173
133
|
let committed = false;
|
|
134
|
+
let primaryFailure: unknown;
|
|
174
135
|
try {
|
|
175
|
-
|
|
176
|
-
() => true,
|
|
177
|
-
() => false,
|
|
178
|
-
);
|
|
179
|
-
createdDirectories = parentExists ? [] : await ensureParent(filePath);
|
|
136
|
+
await ensureParentDirectories(filePath, createdDirectories, beforeReplace);
|
|
180
137
|
const formatted = alreadyFormatted
|
|
181
138
|
? content
|
|
182
139
|
: await formatContent(filePath, content);
|
|
183
140
|
await beforeReplace?.();
|
|
141
|
+
await revalidateWritePath(filePath);
|
|
184
142
|
await writeFile(next, formatted, { encoding: "utf8", flag: "wx", mode });
|
|
185
143
|
if (mode !== undefined) {
|
|
186
144
|
await beforeReplace?.();
|
|
@@ -195,6 +153,7 @@ async function commit(
|
|
|
195
153
|
verifyExpectedHash(expectedSha256, actual);
|
|
196
154
|
}
|
|
197
155
|
await beforeReplace?.();
|
|
156
|
+
await revalidateWritePath(filePath);
|
|
198
157
|
await rename(next, filePath);
|
|
199
158
|
committed = true;
|
|
200
159
|
return {
|
|
@@ -202,9 +161,26 @@ async function commit(
|
|
|
202
161
|
createdDirectories,
|
|
203
162
|
sha256: committedSha256,
|
|
204
163
|
};
|
|
164
|
+
} catch (error) {
|
|
165
|
+
primaryFailure = error;
|
|
166
|
+
throw error;
|
|
205
167
|
} finally {
|
|
206
168
|
await removeTemporary(next);
|
|
207
|
-
if (!committed)
|
|
169
|
+
if (!committed) {
|
|
170
|
+
try {
|
|
171
|
+
await removeCreatedDirectories(createdDirectories);
|
|
172
|
+
} catch (cleanupError) {
|
|
173
|
+
throw Object.assign(
|
|
174
|
+
new AggregateError(
|
|
175
|
+
[primaryFailure, cleanupError],
|
|
176
|
+
"File write failed and parent cleanup was incomplete",
|
|
177
|
+
),
|
|
178
|
+
{
|
|
179
|
+
details: { affectedPaths: createdDirectories },
|
|
180
|
+
},
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
208
184
|
}
|
|
209
185
|
}
|
|
210
186
|
function previewDiff(filePath: string, before: string, after: string): string {
|
|
@@ -295,6 +271,60 @@ const MAX_PREVIEW_SESSION_BYTES = 16 * 1024 * 1024;
|
|
|
295
271
|
const MAX_PREVIEW_SESSION_RECEIPTS = 32;
|
|
296
272
|
const previewReceipts = new Map<string, PreviewReceipt>();
|
|
297
273
|
const expiredPreviewReceipts = new Set<string>();
|
|
274
|
+
const reservedPreviewReceipts = new Map<string, symbol>();
|
|
275
|
+
const previewReservation = new AsyncLocalStorage<symbol>();
|
|
276
|
+
|
|
277
|
+
interface ReceiptBatchState {
|
|
278
|
+
completed: boolean;
|
|
279
|
+
safeToRelease: boolean;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function withReservedPreviewReceipts<T>(
|
|
283
|
+
requests: unknown[],
|
|
284
|
+
state: ReceiptBatchState,
|
|
285
|
+
operation: () => Promise<T>,
|
|
286
|
+
): Promise<T> {
|
|
287
|
+
const owner = Symbol("patch receipt batch");
|
|
288
|
+
const tokens = requests.flatMap((request) => {
|
|
289
|
+
const token = (request as PatchBatchRequest).previewReceipt;
|
|
290
|
+
return typeof token === "string" ? [token] : [];
|
|
291
|
+
});
|
|
292
|
+
if (
|
|
293
|
+
new Set(tokens).size !== tokens.length ||
|
|
294
|
+
tokens.some((token) => reservedPreviewReceipts.has(token))
|
|
295
|
+
)
|
|
296
|
+
throw receiptError(
|
|
297
|
+
"preview_receipt_reserved",
|
|
298
|
+
"Preview receipt is already reserved by an active batch",
|
|
299
|
+
);
|
|
300
|
+
const receipts = tokens.map(
|
|
301
|
+
(token) => [token, previewReceipts.get(token)] as const,
|
|
302
|
+
);
|
|
303
|
+
for (const token of tokens) reservedPreviewReceipts.set(token, owner);
|
|
304
|
+
try {
|
|
305
|
+
return await previewReservation.run(owner, operation);
|
|
306
|
+
} finally {
|
|
307
|
+
for (const [token, receipt] of receipts) {
|
|
308
|
+
let reusable = state.safeToRelease && !state.completed;
|
|
309
|
+
if (receipt && reusable) {
|
|
310
|
+
try {
|
|
311
|
+
reusable = await patchSignals.run(
|
|
312
|
+
undefined,
|
|
313
|
+
async () =>
|
|
314
|
+
sha256(await readText(receipt.filePath)) === receipt.sourceSha256,
|
|
315
|
+
);
|
|
316
|
+
} catch {
|
|
317
|
+
reusable = false;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (!reusable && receipt) {
|
|
321
|
+
clearTimeout(receipt.expiryTimer);
|
|
322
|
+
previewReceipts.delete(token);
|
|
323
|
+
}
|
|
324
|
+
reservedPreviewReceipts.delete(token);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
298
328
|
|
|
299
329
|
function expirePreviewReceipt(token: string): void {
|
|
300
330
|
previewReceipts.delete(token);
|
|
@@ -343,6 +373,14 @@ function previewPayloadBytes(
|
|
|
343
373
|
}
|
|
344
374
|
|
|
345
375
|
async function validatePreviewReceipt(filePath: string, token: string) {
|
|
376
|
+
if (
|
|
377
|
+
reservedPreviewReceipts.has(token) &&
|
|
378
|
+
reservedPreviewReceipts.get(token) !== previewReservation.getStore()
|
|
379
|
+
)
|
|
380
|
+
throw receiptError(
|
|
381
|
+
"preview_receipt_reserved",
|
|
382
|
+
"Preview receipt is already reserved by an active batch",
|
|
383
|
+
);
|
|
346
384
|
const receipt = previewReceipts.get(token);
|
|
347
385
|
if (!receipt)
|
|
348
386
|
throw receiptError(
|
|
@@ -649,11 +687,8 @@ async function applyPreparedPatch(
|
|
|
649
687
|
prepared.candidate,
|
|
650
688
|
await inspectFileCapabilities(filePath),
|
|
651
689
|
);
|
|
652
|
-
if (prepared.receiptToken)
|
|
653
|
-
|
|
654
|
-
if (receipt) clearTimeout(receipt.expiryTimer);
|
|
655
|
-
previewReceipts.delete(prepared.receiptToken);
|
|
656
|
-
}
|
|
690
|
+
if (prepared.receiptToken)
|
|
691
|
+
await validatePreviewReceipt(filePath, prepared.receiptToken);
|
|
657
692
|
await commit(
|
|
658
693
|
filePath,
|
|
659
694
|
candidate,
|
|
@@ -699,20 +734,35 @@ async function preflightFileWrite(
|
|
|
699
734
|
);
|
|
700
735
|
mode = (await lstat(filePath)).mode;
|
|
701
736
|
}
|
|
702
|
-
const
|
|
703
|
-
|
|
704
|
-
() => false,
|
|
705
|
-
);
|
|
706
|
-
const createdDirectories = parentExists ? [] : await ensureParent(filePath);
|
|
737
|
+
const createdDirectories: string[] = [];
|
|
738
|
+
let primaryFailure: unknown;
|
|
707
739
|
try {
|
|
740
|
+
await ensureParentDirectories(filePath, createdDirectories, async () =>
|
|
741
|
+
patchSignals.getStore()?.throwIfAborted(),
|
|
742
|
+
);
|
|
708
743
|
return {
|
|
709
744
|
actual,
|
|
710
745
|
content: await formatContent(filePath, request.content),
|
|
711
746
|
existing: existing !== undefined,
|
|
712
747
|
mode,
|
|
713
748
|
};
|
|
749
|
+
} catch (error) {
|
|
750
|
+
primaryFailure = error;
|
|
751
|
+
throw error;
|
|
714
752
|
} finally {
|
|
715
|
-
|
|
753
|
+
try {
|
|
754
|
+
await removeCreatedDirectories(createdDirectories);
|
|
755
|
+
} catch (cleanupError) {
|
|
756
|
+
throw Object.assign(
|
|
757
|
+
new AggregateError(
|
|
758
|
+
[primaryFailure, cleanupError],
|
|
759
|
+
"File write preflight failed and parent cleanup was incomplete",
|
|
760
|
+
),
|
|
761
|
+
{
|
|
762
|
+
details: { affectedPaths: createdDirectories },
|
|
763
|
+
},
|
|
764
|
+
);
|
|
765
|
+
}
|
|
716
766
|
}
|
|
717
767
|
}
|
|
718
768
|
|
|
@@ -795,6 +845,7 @@ async function rollbackFileBatch(
|
|
|
795
845
|
fence: () => Promise<void>,
|
|
796
846
|
): Promise<void> {
|
|
797
847
|
const failures: unknown[] = [];
|
|
848
|
+
const affectedPaths: string[] = [];
|
|
798
849
|
for (const { resolvedPath, result } of committed.reverse()) {
|
|
799
850
|
const snapshot = snapshots.get(resolvedPath);
|
|
800
851
|
try {
|
|
@@ -821,20 +872,26 @@ async function rollbackFileBatch(
|
|
|
821
872
|
await unlink(resolvedPath);
|
|
822
873
|
const createdDirectories = result.createdDirectories;
|
|
823
874
|
if (Array.isArray(createdDirectories))
|
|
824
|
-
await removeCreatedDirectories(
|
|
825
|
-
createdDirectories.filter(
|
|
826
|
-
(value): value is string => typeof value === "string",
|
|
827
|
-
),
|
|
828
|
-
);
|
|
875
|
+
await removeCreatedDirectories(createdDirectories);
|
|
829
876
|
} catch (error) {
|
|
830
|
-
|
|
877
|
+
affectedPaths.push(resolvedPath);
|
|
878
|
+
failures.push(
|
|
879
|
+
Object.assign(new Error("File rollback failed", { cause: error }), {
|
|
880
|
+
details: { affectedPaths: [resolvedPath] },
|
|
881
|
+
}),
|
|
882
|
+
);
|
|
831
883
|
}
|
|
832
884
|
}
|
|
833
885
|
if (failures.length > 0)
|
|
834
|
-
throw
|
|
886
|
+
throw Object.assign(
|
|
887
|
+
new AggregateError(failures, "Mutation rollback requires recovery"),
|
|
888
|
+
{
|
|
889
|
+
details: { affectedPaths },
|
|
890
|
+
},
|
|
891
|
+
);
|
|
835
892
|
}
|
|
836
893
|
|
|
837
|
-
async function
|
|
894
|
+
async function executeReservedFileBatch<T, Prepared>(
|
|
838
895
|
tool: "file_patch" | "file_write",
|
|
839
896
|
entries: ResolvedBatchEntry<T>[],
|
|
840
897
|
handler: (
|
|
@@ -846,7 +903,8 @@ async function executePreparedFileBatch<T, Prepared>(
|
|
|
846
903
|
preflight: (filePath: string, request: T) => Promise<Prepared>,
|
|
847
904
|
mutates: (request: T) => boolean,
|
|
848
905
|
fence: () => Promise<void>,
|
|
849
|
-
signal
|
|
906
|
+
signal: AbortSignal | undefined,
|
|
907
|
+
receiptState: ReceiptBatchState,
|
|
850
908
|
): Promise<Record<string, unknown>> {
|
|
851
909
|
signal?.throwIfAborted();
|
|
852
910
|
const snapshots = await captureBatchSnapshots(entries);
|
|
@@ -888,6 +946,7 @@ async function executePreparedFileBatch<T, Prepared>(
|
|
|
888
946
|
try {
|
|
889
947
|
signal?.throwIfAborted();
|
|
890
948
|
if (plannedEntries.length > 0) {
|
|
949
|
+
receiptState.safeToRelease = false;
|
|
891
950
|
await beginMutation({
|
|
892
951
|
files: sourcePlan,
|
|
893
952
|
operationId,
|
|
@@ -931,6 +990,7 @@ async function executePreparedFileBatch<T, Prepared>(
|
|
|
931
990
|
began && commits.length > 0
|
|
932
991
|
? await completeMutation(operationId, commits)
|
|
933
992
|
: null;
|
|
993
|
+
receiptState.completed = true;
|
|
934
994
|
return intelligenceRefresh ? { files, intelligenceRefresh } : { files };
|
|
935
995
|
} catch (error) {
|
|
936
996
|
discardPreparedPreviews(prepared);
|
|
@@ -939,11 +999,20 @@ async function executePreparedFileBatch<T, Prepared>(
|
|
|
939
999
|
await patchSignals.run(undefined, () =>
|
|
940
1000
|
rollbackFileBatch(committed, snapshots, fence),
|
|
941
1001
|
);
|
|
942
|
-
if (began) await
|
|
1002
|
+
if (began) await recordMutationRollback(operationId);
|
|
1003
|
+
// A failed begin can leave an uncertain journal even without file commits.
|
|
1004
|
+
receiptState.safeToRelease = began || receiptState.safeToRelease;
|
|
943
1005
|
} catch (rollbackError) {
|
|
944
|
-
throw
|
|
945
|
-
|
|
946
|
-
|
|
1006
|
+
throw Object.assign(
|
|
1007
|
+
new AggregateError(
|
|
1008
|
+
[error, rollbackError],
|
|
1009
|
+
"Mutation failed and rollback requires recovery",
|
|
1010
|
+
),
|
|
1011
|
+
{
|
|
1012
|
+
details: {
|
|
1013
|
+
affectedPaths: committed.map(({ resolvedPath }) => resolvedPath),
|
|
1014
|
+
},
|
|
1015
|
+
},
|
|
947
1016
|
);
|
|
948
1017
|
}
|
|
949
1018
|
throw error;
|
|
@@ -976,19 +1045,29 @@ async function processFileBatch<T, Prepared>(
|
|
|
976
1045
|
resolvedPath: await resolveWritablePath(inputPath),
|
|
977
1046
|
})),
|
|
978
1047
|
);
|
|
1048
|
+
const receiptState: ReceiptBatchState = {
|
|
1049
|
+
completed: false,
|
|
1050
|
+
safeToRelease: true,
|
|
1051
|
+
};
|
|
979
1052
|
return withFencedFileLocks(
|
|
980
1053
|
resolvedEntries.map(({ resolvedPath }) => resolvedPath),
|
|
981
1054
|
(leases: readonly FileLockLease[]) =>
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
1055
|
+
withReservedPreviewReceipts(
|
|
1056
|
+
resolvedEntries.map(({ request }) => request),
|
|
1057
|
+
receiptState,
|
|
1058
|
+
() =>
|
|
1059
|
+
executeReservedFileBatch(
|
|
1060
|
+
tool,
|
|
1061
|
+
resolvedEntries,
|
|
1062
|
+
handler,
|
|
1063
|
+
preflight,
|
|
1064
|
+
mutates,
|
|
1065
|
+
async () => {
|
|
1066
|
+
for (const lease of leases) await lease.fence();
|
|
1067
|
+
},
|
|
1068
|
+
options.signal,
|
|
1069
|
+
receiptState,
|
|
1070
|
+
),
|
|
992
1071
|
),
|
|
993
1072
|
{ ...options, deadline: options.deadline ?? Date.now() + 10_000 },
|
|
994
1073
|
);
|
|
@@ -1,4 +1,159 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { chmod, chown, lstat, open, type FileHandle } from "node:fs/promises";
|
|
4
|
+
|
|
5
|
+
import { sha256 } from "./hash";
|
|
6
|
+
|
|
7
|
+
export interface FileChattrGuard {
|
|
8
|
+
dev: number;
|
|
9
|
+
ino: number;
|
|
10
|
+
sha256: string;
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
beforeMutation?: () => void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function changedFile(filePath: string) {
|
|
16
|
+
return Object.assign(new Error("File changed before attribute mutation"), {
|
|
17
|
+
code: "stale_or_missing_hash",
|
|
18
|
+
details: { affectedPaths: [filePath] },
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function readFileChattrSnapshot(
|
|
23
|
+
filePath: string,
|
|
24
|
+
signal?: AbortSignal,
|
|
25
|
+
) {
|
|
26
|
+
signal?.throwIfAborted();
|
|
27
|
+
const handle = await open(
|
|
28
|
+
filePath,
|
|
29
|
+
constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW,
|
|
30
|
+
);
|
|
31
|
+
try {
|
|
32
|
+
const metadata = await handle.stat();
|
|
33
|
+
if (!metadata.isFile()) throw changedFile(filePath);
|
|
34
|
+
const content = await handle.readFile({ signal });
|
|
35
|
+
signal?.throwIfAborted();
|
|
36
|
+
return {
|
|
37
|
+
attributes: {
|
|
38
|
+
chmod: metadata.mode & 0o777,
|
|
39
|
+
chown: { gid: metadata.gid, uid: metadata.uid },
|
|
40
|
+
},
|
|
41
|
+
content,
|
|
42
|
+
dev: metadata.dev,
|
|
43
|
+
ino: metadata.ino,
|
|
44
|
+
sha256: sha256(content),
|
|
45
|
+
};
|
|
46
|
+
} finally {
|
|
47
|
+
await handle.close();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function verifyChattrHandle(
|
|
52
|
+
handle: FileHandle,
|
|
53
|
+
filePath: string,
|
|
54
|
+
guard: FileChattrGuard,
|
|
55
|
+
) {
|
|
56
|
+
guard.signal?.throwIfAborted();
|
|
57
|
+
const metadata = await handle.stat();
|
|
58
|
+
const current = await lstat(filePath);
|
|
59
|
+
if (
|
|
60
|
+
!metadata.isFile() ||
|
|
61
|
+
current.isSymbolicLink() ||
|
|
62
|
+
metadata.dev !== guard.dev ||
|
|
63
|
+
metadata.ino !== guard.ino ||
|
|
64
|
+
current.dev !== guard.dev ||
|
|
65
|
+
current.ino !== guard.ino
|
|
66
|
+
)
|
|
67
|
+
throw changedFile(filePath);
|
|
68
|
+
const hash = createHash("sha256");
|
|
69
|
+
const buffer = Buffer.alloc(64 * 1024);
|
|
70
|
+
let position = 0;
|
|
71
|
+
for (;;) {
|
|
72
|
+
guard.signal?.throwIfAborted();
|
|
73
|
+
const { bytesRead } = await handle.read(
|
|
74
|
+
buffer,
|
|
75
|
+
0,
|
|
76
|
+
Math.min(buffer.length, metadata.size - position + 1),
|
|
77
|
+
position,
|
|
78
|
+
);
|
|
79
|
+
if (position + bytesRead > metadata.size) throw changedFile(filePath);
|
|
80
|
+
if (!bytesRead) break;
|
|
81
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
82
|
+
position += bytesRead;
|
|
83
|
+
}
|
|
84
|
+
if (hash.digest("hex") !== guard.sha256) throw changedFile(filePath);
|
|
85
|
+
const after = await lstat(filePath);
|
|
86
|
+
if (after.dev !== guard.dev || after.ino !== guard.ino)
|
|
87
|
+
throw changedFile(filePath);
|
|
88
|
+
guard.signal?.throwIfAborted();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function applyGuardedChattr(
|
|
92
|
+
filePath: string,
|
|
93
|
+
chattr: FileChattr | undefined,
|
|
94
|
+
beforeChange: (() => Promise<void>) | undefined,
|
|
95
|
+
guard: FileChattrGuard,
|
|
96
|
+
) {
|
|
97
|
+
const validated = validateFileChattr(chattr);
|
|
98
|
+
const handle = await open(
|
|
99
|
+
filePath,
|
|
100
|
+
constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW,
|
|
101
|
+
);
|
|
102
|
+
try {
|
|
103
|
+
await verifyChattrHandle(handle, filePath, guard);
|
|
104
|
+
const before = await handle.stat();
|
|
105
|
+
let changed = false;
|
|
106
|
+
const check = async (rollback = false) => {
|
|
107
|
+
await beforeChange?.();
|
|
108
|
+
await verifyChattrHandle(
|
|
109
|
+
handle,
|
|
110
|
+
filePath,
|
|
111
|
+
rollback ? { ...guard, signal: undefined } : guard,
|
|
112
|
+
);
|
|
113
|
+
};
|
|
114
|
+
try {
|
|
115
|
+
if (validated?.chown) {
|
|
116
|
+
await check();
|
|
117
|
+
guard.beforeMutation?.();
|
|
118
|
+
await handle.chown(validated.chown.uid, validated.chown.gid);
|
|
119
|
+
changed = true;
|
|
120
|
+
}
|
|
121
|
+
if (validated?.chmod !== undefined) {
|
|
122
|
+
await check();
|
|
123
|
+
guard.beforeMutation?.();
|
|
124
|
+
await handle.chmod(validated.chmod);
|
|
125
|
+
changed = true;
|
|
126
|
+
}
|
|
127
|
+
await verifyChattrHandle(handle, filePath, guard);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
if (changed) {
|
|
130
|
+
try {
|
|
131
|
+
await check(true);
|
|
132
|
+
if (validated?.chown && process.platform !== "win32")
|
|
133
|
+
await handle.chown(before.uid, before.gid);
|
|
134
|
+
await check(true);
|
|
135
|
+
await handle.chmod(before.mode & 0o777);
|
|
136
|
+
} catch (rollbackError) {
|
|
137
|
+
throw Object.assign(
|
|
138
|
+
new AggregateError(
|
|
139
|
+
[error, rollbackError],
|
|
140
|
+
"File attribute mutation failed and rollback was incomplete",
|
|
141
|
+
),
|
|
142
|
+
{ details: { affectedPaths: [filePath] } },
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
const after = await handle.stat();
|
|
149
|
+
return {
|
|
150
|
+
chmod: after.mode & 0o777,
|
|
151
|
+
chown: { gid: after.gid, uid: after.uid },
|
|
152
|
+
};
|
|
153
|
+
} finally {
|
|
154
|
+
await handle.close();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
2
157
|
|
|
3
158
|
export interface FileChattr {
|
|
4
159
|
chmod?: number;
|
|
@@ -44,7 +199,9 @@ export async function applyFileChattr(
|
|
|
44
199
|
filePath: string,
|
|
45
200
|
chattr: FileChattr | undefined,
|
|
46
201
|
beforeChange?: () => Promise<void>,
|
|
202
|
+
guard?: FileChattrGuard,
|
|
47
203
|
) {
|
|
204
|
+
if (guard) return applyGuardedChattr(filePath, chattr, beforeChange, guard);
|
|
48
205
|
const validated = validateFileChattr(chattr);
|
|
49
206
|
const before = await resultingFileChattr(filePath);
|
|
50
207
|
if (!validated) return before;
|