@lousy-agents/lint 5.14.1 → 5.14.3
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/index.js +3797 -126
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -566,7 +566,7 @@ module.exports = webpackEmptyAsyncContext;
|
|
|
566
566
|
|
|
567
567
|
|
|
568
568
|
},
|
|
569
|
-
|
|
569
|
+
2202(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
|
|
570
570
|
|
|
571
571
|
// EXPORTS
|
|
572
572
|
__webpack_require__.d(__webpack_exports__, {
|
|
@@ -753,8 +753,6 @@ __webpack_require__.d(constructs_namespaceObject, {
|
|
|
753
753
|
}
|
|
754
754
|
}
|
|
755
755
|
|
|
756
|
-
// EXTERNAL MODULE: external "node:fs/promises"
|
|
757
|
-
var promises_ = __webpack_require__(1455);
|
|
758
756
|
// EXTERNAL MODULE: external "node:path"
|
|
759
757
|
var external_node_path_ = __webpack_require__(6760);
|
|
760
758
|
// EXTERNAL MODULE: ../../node_modules/yaml/dist/index.js
|
|
@@ -777,73 +775,3689 @@ var dist = __webpack_require__(3519);
|
|
|
777
775
|
reason: "missing"
|
|
778
776
|
};
|
|
779
777
|
}
|
|
780
|
-
let endIndex = -1;
|
|
781
|
-
for(let i = 1; i < lines.length; i++){
|
|
782
|
-
if (lines[i]?.trim() === "---") {
|
|
783
|
-
endIndex = i;
|
|
784
|
-
break;
|
|
778
|
+
let endIndex = -1;
|
|
779
|
+
for(let i = 1; i < lines.length; i++){
|
|
780
|
+
if (lines[i]?.trim() === "---") {
|
|
781
|
+
endIndex = i;
|
|
782
|
+
break;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
if (endIndex === -1) {
|
|
786
|
+
return {
|
|
787
|
+
ok: false,
|
|
788
|
+
reason: "missing"
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
const yamlContent = lines.slice(1, endIndex).join("\n");
|
|
792
|
+
let data;
|
|
793
|
+
try {
|
|
794
|
+
const parsed = (0,dist/* .parse */.qg)(yamlContent, {
|
|
795
|
+
maxAliasCount: 0
|
|
796
|
+
});
|
|
797
|
+
data = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
798
|
+
} catch (error) {
|
|
799
|
+
const detail = error instanceof Error ? error.message : "Unknown YAML parse error";
|
|
800
|
+
return {
|
|
801
|
+
ok: false,
|
|
802
|
+
reason: "invalid",
|
|
803
|
+
detail
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
const fieldLines = new Map();
|
|
807
|
+
for(let i = 1; i < endIndex; i++){
|
|
808
|
+
const match = lines[i]?.match(/^([^\s:][^:]*?):(?:\s|$)/);
|
|
809
|
+
if (match?.[1]) {
|
|
810
|
+
fieldLines.set(match[1], i + 1);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
return {
|
|
814
|
+
ok: true,
|
|
815
|
+
data: {
|
|
816
|
+
data: data ?? {},
|
|
817
|
+
fieldLines,
|
|
818
|
+
frontmatterStartLine: 1
|
|
819
|
+
}
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Parses YAML frontmatter from markdown content.
|
|
824
|
+
*
|
|
825
|
+
* Returns `null` when the content has no opening `---`, no closing `---`,
|
|
826
|
+
* or contains invalid YAML.
|
|
827
|
+
*/ function parseFrontmatter(content) {
|
|
828
|
+
const result = parseFrontmatterWithError(content);
|
|
829
|
+
return result.ok ? result.data : null;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// EXTERNAL MODULE: external "node:fs"
|
|
833
|
+
var external_node_fs_ = __webpack_require__(3024);
|
|
834
|
+
// EXTERNAL MODULE: external "node:fs/promises"
|
|
835
|
+
var promises_ = __webpack_require__(1455);
|
|
836
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/errors.js
|
|
837
|
+
const OPERATIONAL_CODES = new Set([
|
|
838
|
+
"helper-failed",
|
|
839
|
+
"helper-unavailable",
|
|
840
|
+
"permission-unverified",
|
|
841
|
+
"timeout",
|
|
842
|
+
"unsupported-platform",
|
|
843
|
+
]);
|
|
844
|
+
function categorizeFsSafeError(code) {
|
|
845
|
+
return OPERATIONAL_CODES.has(code) ? "operational" : "policy";
|
|
846
|
+
}
|
|
847
|
+
class errors_FsSafeError extends Error {
|
|
848
|
+
code;
|
|
849
|
+
category;
|
|
850
|
+
constructor(code, message, options = {}) {
|
|
851
|
+
super(message, options);
|
|
852
|
+
this.name = "FsSafeError";
|
|
853
|
+
this.code = code;
|
|
854
|
+
this.category = categorizeFsSafeError(code);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// EXTERNAL MODULE: external "node:crypto"
|
|
859
|
+
var external_node_crypto_ = __webpack_require__(7598);
|
|
860
|
+
// EXTERNAL MODULE: external "node:stream/promises"
|
|
861
|
+
var external_node_stream_promises_ = __webpack_require__(6466);
|
|
862
|
+
// EXTERNAL MODULE: external "node:stream"
|
|
863
|
+
var external_node_stream_ = __webpack_require__(7075);
|
|
864
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/bounded-read-stream.js
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
function createMaxBytesTransform(maxBytes) {
|
|
868
|
+
let bytes = 0;
|
|
869
|
+
return new external_node_stream_.Transform({
|
|
870
|
+
transform(chunk, _encoding, callback) {
|
|
871
|
+
const buffer = chunk instanceof Buffer ? chunk : Buffer.from(chunk);
|
|
872
|
+
bytes += buffer.byteLength;
|
|
873
|
+
if (bytes > maxBytes) {
|
|
874
|
+
callback(new errors_FsSafeError("too-large", `file exceeds limit of ${maxBytes} bytes (got at least ${bytes})`));
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
callback(null, buffer);
|
|
878
|
+
},
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
function createBoundedReadStream(opened, maxBytes) {
|
|
882
|
+
const stream = opened.handle.createReadStream();
|
|
883
|
+
return maxBytes === undefined ? stream : stream.pipe(createMaxBytesTransform(maxBytes));
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/file-identity.js
|
|
887
|
+
function isZero(value) {
|
|
888
|
+
return value === 0 || value === 0n;
|
|
889
|
+
}
|
|
890
|
+
function file_identity_sameFileIdentity(left, right, platform = process.platform) {
|
|
891
|
+
if (left.ino !== right.ino) {
|
|
892
|
+
return false;
|
|
893
|
+
}
|
|
894
|
+
// On Windows, path-based stat calls can report dev=0 while fd-based stat
|
|
895
|
+
// reports a real volume serial; treat either-side dev=0 as "unknown device".
|
|
896
|
+
if (left.dev === right.dev) {
|
|
897
|
+
return true;
|
|
898
|
+
}
|
|
899
|
+
return platform === "win32" && (isZero(left.dev) || isZero(right.dev));
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/string-coerce.js
|
|
903
|
+
function readStringValue(value) {
|
|
904
|
+
return typeof value === "string" ? value : undefined;
|
|
905
|
+
}
|
|
906
|
+
function normalizeNullableString(value) {
|
|
907
|
+
if (typeof value !== "string") {
|
|
908
|
+
return null;
|
|
909
|
+
}
|
|
910
|
+
const trimmed = value.trim();
|
|
911
|
+
return trimmed ? trimmed : null;
|
|
912
|
+
}
|
|
913
|
+
function normalizeOptionalString(value) {
|
|
914
|
+
return normalizeNullableString(value) ?? undefined;
|
|
915
|
+
}
|
|
916
|
+
function normalizeStringifiedOptionalString(value) {
|
|
917
|
+
if (typeof value === "string") {
|
|
918
|
+
return normalizeOptionalString(value);
|
|
919
|
+
}
|
|
920
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
921
|
+
return normalizeOptionalString(String(value));
|
|
922
|
+
}
|
|
923
|
+
return undefined;
|
|
924
|
+
}
|
|
925
|
+
function normalizeOptionalLowercaseString(value) {
|
|
926
|
+
return normalizeOptionalString(value)?.toLowerCase();
|
|
927
|
+
}
|
|
928
|
+
function normalizeLowercaseStringOrEmpty(value) {
|
|
929
|
+
return normalizeOptionalLowercaseString(value) ?? "";
|
|
930
|
+
}
|
|
931
|
+
function normalizeFastMode(raw) {
|
|
932
|
+
if (typeof raw === "boolean") {
|
|
933
|
+
return raw;
|
|
934
|
+
}
|
|
935
|
+
if (!raw) {
|
|
936
|
+
return undefined;
|
|
937
|
+
}
|
|
938
|
+
const key = normalizeLowercaseStringOrEmpty(raw);
|
|
939
|
+
if (["off", "false", "no", "0", "disable", "disabled", "normal"].includes(key)) {
|
|
940
|
+
return false;
|
|
941
|
+
}
|
|
942
|
+
if (["on", "true", "yes", "1", "enable", "enabled", "fast"].includes(key)) {
|
|
943
|
+
return true;
|
|
944
|
+
}
|
|
945
|
+
return undefined;
|
|
946
|
+
}
|
|
947
|
+
function lowercasePreservingWhitespace(value) {
|
|
948
|
+
return value.toLowerCase();
|
|
949
|
+
}
|
|
950
|
+
function localeLowercasePreservingWhitespace(value) {
|
|
951
|
+
return value.toLocaleLowerCase();
|
|
952
|
+
}
|
|
953
|
+
function resolvePrimaryStringValue(value) {
|
|
954
|
+
if (typeof value === "string") {
|
|
955
|
+
return normalizeOptionalString(value);
|
|
956
|
+
}
|
|
957
|
+
if (!value || typeof value !== "object") {
|
|
958
|
+
return undefined;
|
|
959
|
+
}
|
|
960
|
+
return normalizeOptionalString(value.primary);
|
|
961
|
+
}
|
|
962
|
+
function normalizeOptionalThreadValue(value) {
|
|
963
|
+
if (typeof value === "number") {
|
|
964
|
+
return Number.isFinite(value) ? Math.trunc(value) : undefined;
|
|
965
|
+
}
|
|
966
|
+
return normalizeOptionalString(value);
|
|
967
|
+
}
|
|
968
|
+
function normalizeOptionalStringifiedId(value) {
|
|
969
|
+
const normalized = normalizeOptionalThreadValue(value);
|
|
970
|
+
return normalized == null ? undefined : String(normalized);
|
|
971
|
+
}
|
|
972
|
+
function hasNonEmptyString(value) {
|
|
973
|
+
return normalizeOptionalString(value) !== undefined;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/path.js
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
const NOT_FOUND_CODES = new Set(["ENOENT", "ENOTDIR"]);
|
|
982
|
+
const SYMLINK_OPEN_CODES = new Set(["ELOOP", "EINVAL", "ENOTSUP"]);
|
|
983
|
+
const POSIX_SEPARATOR_CHAR_CODE = 0x2f;
|
|
984
|
+
function normalizeWindowsPathForComparison(input) {
|
|
985
|
+
let normalized = external_node_path_.win32.normalize(input);
|
|
986
|
+
if (normalized.startsWith("\\\\?\\")) {
|
|
987
|
+
normalized = normalized.slice(4);
|
|
988
|
+
if (normalized.toUpperCase().startsWith("UNC\\")) {
|
|
989
|
+
normalized = `\\\\${normalized.slice(4)}`;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
return normalizeLowercaseStringOrEmpty(normalized.replaceAll("/", "\\"));
|
|
993
|
+
}
|
|
994
|
+
function isNodeError(value) {
|
|
995
|
+
return Boolean(value && typeof value === "object" && "code" in value);
|
|
996
|
+
}
|
|
997
|
+
function hasNodeErrorCode(value, code) {
|
|
998
|
+
return isNodeError(value) && value.code === code;
|
|
999
|
+
}
|
|
1000
|
+
function path_assertNoNulPathInput(filePath, message = "path contains a NUL byte") {
|
|
1001
|
+
if (filePath.includes("\0")) {
|
|
1002
|
+
throw new errors_FsSafeError("invalid-path", message);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
function path_isNotFoundPathError(value) {
|
|
1006
|
+
return isNodeError(value) && typeof value.code === "string" && NOT_FOUND_CODES.has(value.code);
|
|
1007
|
+
}
|
|
1008
|
+
function isSymlinkOpenError(value) {
|
|
1009
|
+
return isNodeError(value) && typeof value.code === "string" && SYMLINK_OPEN_CODES.has(value.code);
|
|
1010
|
+
}
|
|
1011
|
+
function path_isPathInside(root, target) {
|
|
1012
|
+
if (process.platform === "win32") {
|
|
1013
|
+
const rootForCompare = normalizeWindowsPathForComparison(external_node_path_.win32.resolve(root));
|
|
1014
|
+
const targetForCompare = normalizeWindowsPathForComparison(external_node_path_.win32.resolve(target));
|
|
1015
|
+
const relative = external_node_path_.win32.relative(rootForCompare, targetForCompare);
|
|
1016
|
+
const firstSegment = relative.split(external_node_path_.win32.sep)[0];
|
|
1017
|
+
return (relative === "" || (firstSegment !== ".." && !external_node_path_.win32.isAbsolute(relative)));
|
|
1018
|
+
}
|
|
1019
|
+
if (root.length > 0 &&
|
|
1020
|
+
root.charCodeAt(0) === POSIX_SEPARATOR_CHAR_CODE &&
|
|
1021
|
+
target.length >= root.length &&
|
|
1022
|
+
target.charCodeAt(0) === POSIX_SEPARATOR_CHAR_CODE &&
|
|
1023
|
+
!target.includes("/..") &&
|
|
1024
|
+
(target === root ||
|
|
1025
|
+
(target.startsWith(root) && target.charCodeAt(root.length) === POSIX_SEPARATOR_CHAR_CODE))) {
|
|
1026
|
+
return true;
|
|
1027
|
+
}
|
|
1028
|
+
const resolvedRoot = external_node_path_.resolve(root);
|
|
1029
|
+
const resolvedTarget = external_node_path_.resolve(target);
|
|
1030
|
+
const relative = external_node_path_.relative(resolvedRoot, resolvedTarget);
|
|
1031
|
+
const firstSegment = relative.split(external_node_path_.posix.sep)[0];
|
|
1032
|
+
return relative === "" || (firstSegment !== ".." && !external_node_path_.isAbsolute(relative));
|
|
1033
|
+
}
|
|
1034
|
+
function resolveSafeBaseDir(rootDir) {
|
|
1035
|
+
const resolved = path.resolve(rootDir);
|
|
1036
|
+
return resolved.endsWith(path.sep) ? resolved : `${resolved}${path.sep}`;
|
|
1037
|
+
}
|
|
1038
|
+
function isWithinDir(rootDir, targetPath) {
|
|
1039
|
+
return path_isPathInside(rootDir, targetPath);
|
|
1040
|
+
}
|
|
1041
|
+
function safeRealpathSync(targetPath, cache) {
|
|
1042
|
+
const cached = cache?.get(targetPath);
|
|
1043
|
+
if (cached) {
|
|
1044
|
+
return cached;
|
|
1045
|
+
}
|
|
1046
|
+
try {
|
|
1047
|
+
const resolved = fs.realpathSync(targetPath);
|
|
1048
|
+
cache?.set(targetPath, resolved);
|
|
1049
|
+
cache?.set(resolved, resolved);
|
|
1050
|
+
return resolved;
|
|
1051
|
+
}
|
|
1052
|
+
catch {
|
|
1053
|
+
return null;
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
function isPathInsideWithRealpath(basePath, candidatePath, opts) {
|
|
1057
|
+
if (!path_isPathInside(basePath, candidatePath)) {
|
|
1058
|
+
return false;
|
|
1059
|
+
}
|
|
1060
|
+
const baseReal = safeRealpathSync(basePath, opts?.cache);
|
|
1061
|
+
const candidateReal = safeRealpathSync(candidatePath, opts?.cache);
|
|
1062
|
+
if (!baseReal || !candidateReal) {
|
|
1063
|
+
return opts?.requireRealpath === false;
|
|
1064
|
+
}
|
|
1065
|
+
return path_isPathInside(baseReal, candidateReal);
|
|
1066
|
+
}
|
|
1067
|
+
function safeStatSync(targetPath) {
|
|
1068
|
+
try {
|
|
1069
|
+
return fs.statSync(targetPath);
|
|
1070
|
+
}
|
|
1071
|
+
catch {
|
|
1072
|
+
return null;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
function splitSafeRelativePath(relativePath) {
|
|
1076
|
+
if (relativePath.length === 0 || relativePath === ".") {
|
|
1077
|
+
return [];
|
|
1078
|
+
}
|
|
1079
|
+
path_assertNoNulPathInput(relativePath, "relative path contains a NUL byte");
|
|
1080
|
+
if (relativePath.includes("\\")) {
|
|
1081
|
+
throw new FsSafeError("invalid-path", "relative path must use forward slashes");
|
|
1082
|
+
}
|
|
1083
|
+
if (path.posix.isAbsolute(relativePath) ||
|
|
1084
|
+
path.win32.isAbsolute(relativePath) ||
|
|
1085
|
+
relativePath.startsWith("//")) {
|
|
1086
|
+
throw new FsSafeError("invalid-path", "relative path must not be absolute");
|
|
1087
|
+
}
|
|
1088
|
+
const segments = relativePath.split("/").filter((segment) => segment.length > 0 && segment !== ".");
|
|
1089
|
+
for (const segment of segments) {
|
|
1090
|
+
if (segment === "..") {
|
|
1091
|
+
throw new FsSafeError("invalid-path", "relative path must not contain '..'");
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return segments;
|
|
1095
|
+
}
|
|
1096
|
+
function resolveSafeRelativePath(rootDir, relativePath) {
|
|
1097
|
+
const root = path.resolve(rootDir);
|
|
1098
|
+
const target = path.resolve(root, ...splitSafeRelativePath(relativePath));
|
|
1099
|
+
if (target !== root && !target.startsWith(root + path.sep)) {
|
|
1100
|
+
throw new FsSafeError("outside-workspace", "relative path escapes root");
|
|
1101
|
+
}
|
|
1102
|
+
return target;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/directory-guard.js
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
|
|
1110
|
+
|
|
1111
|
+
|
|
1112
|
+
async function directory_guard_createAsyncDirectoryGuard(dir) {
|
|
1113
|
+
const stat = await promises_.lstat(dir);
|
|
1114
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
1115
|
+
throw new errors_FsSafeError("not-file", "directory component must be a directory");
|
|
1116
|
+
}
|
|
1117
|
+
return { dir, realPath: await promises_.realpath(dir), stat };
|
|
1118
|
+
}
|
|
1119
|
+
async function assertAsyncDirectoryGuard(guard) {
|
|
1120
|
+
const stat = await promises_.lstat(guard.dir);
|
|
1121
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
1122
|
+
throw new errors_FsSafeError("not-file", "directory component must be a directory");
|
|
1123
|
+
}
|
|
1124
|
+
if (!file_identity_sameFileIdentity(stat, guard.stat) || (await promises_.realpath(guard.dir)) !== guard.realPath) {
|
|
1125
|
+
throw new errors_FsSafeError("path-mismatch", "directory changed during operation");
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
function directory_guard_createSyncDirectoryGuard(dir) {
|
|
1129
|
+
const stat = fsSync.lstatSync(dir);
|
|
1130
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
1131
|
+
throw new FsSafeError("not-file", "directory component must be a directory");
|
|
1132
|
+
}
|
|
1133
|
+
return { dir, realPath: fsSync.realpathSync(dir), stat };
|
|
1134
|
+
}
|
|
1135
|
+
function directory_guard_assertSyncDirectoryGuard(guard) {
|
|
1136
|
+
const stat = fsSync.lstatSync(guard.dir);
|
|
1137
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
1138
|
+
throw new FsSafeError("not-file", "directory component must be a directory");
|
|
1139
|
+
}
|
|
1140
|
+
if (!sameFileIdentity(stat, guard.stat) || fsSync.realpathSync(guard.dir) !== guard.realPath) {
|
|
1141
|
+
throw new FsSafeError("path-mismatch", "directory changed during operation");
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
async function directory_guard_createNearestExistingDirectoryGuard(rootReal, targetPath) {
|
|
1145
|
+
let current = external_node_path_.resolve(targetPath);
|
|
1146
|
+
const root = external_node_path_.resolve(rootReal);
|
|
1147
|
+
while (current !== root) {
|
|
1148
|
+
try {
|
|
1149
|
+
return await directory_guard_createAsyncDirectoryGuard(current);
|
|
1150
|
+
}
|
|
1151
|
+
catch (error) {
|
|
1152
|
+
if (!path_isNotFoundPathError(error)) {
|
|
1153
|
+
throw error;
|
|
1154
|
+
}
|
|
1155
|
+
current = external_node_path_.dirname(current);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
return await directory_guard_createAsyncDirectoryGuard(root);
|
|
1159
|
+
}
|
|
1160
|
+
function directory_guard_createNearestExistingSyncDirectoryGuard(rootReal, targetPath) {
|
|
1161
|
+
let current = path.resolve(targetPath);
|
|
1162
|
+
const root = path.resolve(rootReal);
|
|
1163
|
+
while (current !== root) {
|
|
1164
|
+
try {
|
|
1165
|
+
return directory_guard_createSyncDirectoryGuard(current);
|
|
1166
|
+
}
|
|
1167
|
+
catch (error) {
|
|
1168
|
+
if (!isNotFoundPathError(error)) {
|
|
1169
|
+
throw error;
|
|
1170
|
+
}
|
|
1171
|
+
current = path.dirname(current);
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
return directory_guard_createSyncDirectoryGuard(root);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/guarded-mkdir.js
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
|
|
1181
|
+
|
|
1182
|
+
function isSameOrChildPath(candidate, parent) {
|
|
1183
|
+
return candidate === parent || candidate.startsWith(`${parent}${external_node_path_.sep}`);
|
|
1184
|
+
}
|
|
1185
|
+
function isPathEscape(relativePath) {
|
|
1186
|
+
return relativePath === ".." || relativePath.startsWith(`..${external_node_path_.sep}`) || external_node_path_.isAbsolute(relativePath);
|
|
1187
|
+
}
|
|
1188
|
+
async function mkdirPathComponentsWithGuards(params) {
|
|
1189
|
+
const root = external_node_path_.resolve(params.rootReal);
|
|
1190
|
+
const target = external_node_path_.resolve(params.targetPath);
|
|
1191
|
+
const relative = external_node_path_.relative(root, target);
|
|
1192
|
+
if (isPathEscape(relative)) {
|
|
1193
|
+
throw new errors_FsSafeError("outside-workspace", "directory is outside workspace root");
|
|
1194
|
+
}
|
|
1195
|
+
let current = root;
|
|
1196
|
+
for (const part of relative.split(external_node_path_.sep).filter(Boolean)) {
|
|
1197
|
+
const next = external_node_path_.join(current, part);
|
|
1198
|
+
const parentGuard = await directory_guard_createAsyncDirectoryGuard(current);
|
|
1199
|
+
await params.beforeComponent?.(next);
|
|
1200
|
+
await assertAsyncDirectoryGuard(parentGuard);
|
|
1201
|
+
try {
|
|
1202
|
+
await promises_.mkdir(next);
|
|
1203
|
+
}
|
|
1204
|
+
catch (error) {
|
|
1205
|
+
if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") {
|
|
1206
|
+
throw error;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
const stat = await promises_.lstat(next);
|
|
1210
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
1211
|
+
throw new errors_FsSafeError("not-file", "directory component must be a directory");
|
|
1212
|
+
}
|
|
1213
|
+
// Node's recursive mkdir follows symlinks in missing components. Build one
|
|
1214
|
+
// segment at a time and realpath-check each segment before descending.
|
|
1215
|
+
if (!isSameOrChildPath(external_node_path_.resolve(await promises_.realpath(next)), root)) {
|
|
1216
|
+
throw new errors_FsSafeError("outside-workspace", "directory escaped workspace root");
|
|
1217
|
+
}
|
|
1218
|
+
await directory_guard_createAsyncDirectoryGuard(next);
|
|
1219
|
+
await assertAsyncDirectoryGuard(parentGuard);
|
|
1220
|
+
current = next;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/guarded-mutation.js
|
|
1225
|
+
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
|
|
1229
|
+
async function withAsyncDirectoryGuards(guards, mutate, options = {}) {
|
|
1230
|
+
for (const guard of guards) {
|
|
1231
|
+
await assertAsyncDirectoryGuard(guard);
|
|
1232
|
+
}
|
|
1233
|
+
const result = await mutate();
|
|
1234
|
+
if (options.verifyAfter !== false) {
|
|
1235
|
+
try {
|
|
1236
|
+
for (const guard of guards) {
|
|
1237
|
+
await assertAsyncDirectoryGuard(guard);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
catch (error) {
|
|
1241
|
+
if (options.onPostGuardFailure) {
|
|
1242
|
+
try {
|
|
1243
|
+
// The mutation may have returned an owned resource before the post-guard
|
|
1244
|
+
// check detected a swapped directory. Give callers one chance to close
|
|
1245
|
+
// handles without letting cleanup hide the boundary failure.
|
|
1246
|
+
await options.onPostGuardFailure(result, error);
|
|
1247
|
+
}
|
|
1248
|
+
catch {
|
|
1249
|
+
// Preserve the boundary failure. Cleanup is best-effort.
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
throw error;
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
return result;
|
|
1256
|
+
}
|
|
1257
|
+
function withSyncDirectoryGuards(guards, mutate, options = {}) {
|
|
1258
|
+
for (const guard of guards) {
|
|
1259
|
+
assertSyncDirectoryGuard(guard);
|
|
1260
|
+
}
|
|
1261
|
+
const result = mutate();
|
|
1262
|
+
if (options.verifyAfter !== false) {
|
|
1263
|
+
for (const guard of guards) {
|
|
1264
|
+
assertSyncDirectoryGuard(guard);
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
return result;
|
|
1268
|
+
}
|
|
1269
|
+
async function guardedRename(params) {
|
|
1270
|
+
const sourceGuard = await createAsyncDirectoryGuard(path.dirname(params.from));
|
|
1271
|
+
const targetGuard = params.targetRoot
|
|
1272
|
+
? await createNearestExistingDirectoryGuard(params.targetRoot, path.dirname(params.to))
|
|
1273
|
+
: await createAsyncDirectoryGuard(path.dirname(params.to));
|
|
1274
|
+
await withAsyncDirectoryGuards([sourceGuard, targetGuard], async () => {
|
|
1275
|
+
await fs.rename(params.from, params.to);
|
|
1276
|
+
}, { verifyAfter: params.verifyAfter });
|
|
1277
|
+
}
|
|
1278
|
+
function guardedRenameSync(params) {
|
|
1279
|
+
const sourceGuard = createSyncDirectoryGuard(path.dirname(params.from));
|
|
1280
|
+
const targetGuard = params.targetRoot
|
|
1281
|
+
? createNearestExistingSyncDirectoryGuard(params.targetRoot, path.dirname(params.to))
|
|
1282
|
+
: createSyncDirectoryGuard(path.dirname(params.to));
|
|
1283
|
+
withSyncDirectoryGuards([sourceGuard, targetGuard], () => fsSync.renameSync(params.from, params.to), { verifyAfter: params.verifyAfter });
|
|
1284
|
+
}
|
|
1285
|
+
async function guardedRm(params) {
|
|
1286
|
+
const guard = await createAsyncDirectoryGuard(path.dirname(params.target));
|
|
1287
|
+
await withAsyncDirectoryGuards([guard], async () => {
|
|
1288
|
+
await fs.rm(params.target, {
|
|
1289
|
+
...(params.recursive !== undefined ? { recursive: params.recursive } : {}),
|
|
1290
|
+
...(params.force !== undefined ? { force: params.force } : {}),
|
|
1291
|
+
});
|
|
1292
|
+
}, { verifyAfter: params.verifyAfter });
|
|
1293
|
+
}
|
|
1294
|
+
function guardedRmSync(params) {
|
|
1295
|
+
const guard = createSyncDirectoryGuard(path.dirname(params.target));
|
|
1296
|
+
withSyncDirectoryGuards([guard], () => fsSync.rmSync(params.target, {
|
|
1297
|
+
...(params.recursive !== undefined ? { recursive: params.recursive } : {}),
|
|
1298
|
+
...(params.force !== undefined ? { force: params.force } : {}),
|
|
1299
|
+
}), { verifyAfter: params.verifyAfter });
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-python-config.js
|
|
1303
|
+
let overrideConfig = {};
|
|
1304
|
+
function parseMode(value) {
|
|
1305
|
+
if (!value) {
|
|
1306
|
+
return undefined;
|
|
1307
|
+
}
|
|
1308
|
+
const normalized = value.trim().toLowerCase();
|
|
1309
|
+
if (normalized === "0" || normalized === "false" || normalized === "off" || normalized === "never") {
|
|
1310
|
+
return "off";
|
|
1311
|
+
}
|
|
1312
|
+
if (normalized === "1" || normalized === "true" || normalized === "on" || normalized === "auto") {
|
|
1313
|
+
return "auto";
|
|
1314
|
+
}
|
|
1315
|
+
if (normalized === "required" || normalized === "require") {
|
|
1316
|
+
return "require";
|
|
1317
|
+
}
|
|
1318
|
+
return undefined;
|
|
1319
|
+
}
|
|
1320
|
+
function configureFsSafePython(config) {
|
|
1321
|
+
overrideConfig = { ...overrideConfig, ...config };
|
|
1322
|
+
}
|
|
1323
|
+
function getFsSafePythonConfig() {
|
|
1324
|
+
return {
|
|
1325
|
+
mode: overrideConfig.mode ??
|
|
1326
|
+
parseMode(process.env.FS_SAFE_PYTHON_MODE) ??
|
|
1327
|
+
parseMode(process.env.OPENCLAW_FS_SAFE_PYTHON_MODE) ??
|
|
1328
|
+
"auto",
|
|
1329
|
+
pythonPath: overrideConfig.pythonPath ??
|
|
1330
|
+
process.env.FS_SAFE_PYTHON ??
|
|
1331
|
+
process.env.OPENCLAW_FS_SAFE_PYTHON ??
|
|
1332
|
+
process.env.OPENCLAW_PINNED_PYTHON ??
|
|
1333
|
+
process.env.OPENCLAW_PINNED_WRITE_PYTHON,
|
|
1334
|
+
};
|
|
1335
|
+
}
|
|
1336
|
+
function canFallbackFromPythonError(error) {
|
|
1337
|
+
const code = error instanceof Error && "code" in error ? error.code : undefined;
|
|
1338
|
+
return (getFsSafePythonConfig().mode !== "require" &&
|
|
1339
|
+
(code === "helper-unavailable" || code === "unsupported-platform"));
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// EXTERNAL MODULE: external "node:child_process"
|
|
1343
|
+
var external_node_child_process_ = __webpack_require__(1421);
|
|
1344
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-python.js
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
const PINNED_PYTHON_WORKER_SOURCE = String.raw `
|
|
1350
|
+
import base64
|
|
1351
|
+
import errno
|
|
1352
|
+
import json
|
|
1353
|
+
import os
|
|
1354
|
+
import secrets
|
|
1355
|
+
import stat
|
|
1356
|
+
import sys
|
|
1357
|
+
|
|
1358
|
+
DIR_FLAGS = os.O_RDONLY
|
|
1359
|
+
if hasattr(os, "O_DIRECTORY"):
|
|
1360
|
+
DIR_FLAGS |= os.O_DIRECTORY
|
|
1361
|
+
if hasattr(os, "O_NOFOLLOW"):
|
|
1362
|
+
DIR_FLAGS |= os.O_NOFOLLOW
|
|
1363
|
+
READ_FLAGS = os.O_RDONLY
|
|
1364
|
+
if hasattr(os, "O_NOFOLLOW"):
|
|
1365
|
+
READ_FLAGS |= os.O_NOFOLLOW
|
|
1366
|
+
WRITE_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
1367
|
+
if hasattr(os, "O_NOFOLLOW"):
|
|
1368
|
+
WRITE_FLAGS |= os.O_NOFOLLOW
|
|
1369
|
+
|
|
1370
|
+
def split_relative(value):
|
|
1371
|
+
if value in ("", "."):
|
|
1372
|
+
return []
|
|
1373
|
+
if "\x00" in value or value.startswith("/") or value.startswith("//"):
|
|
1374
|
+
raise OSError(errno.EPERM, "invalid relative path")
|
|
1375
|
+
if value.startswith("..\\"):
|
|
1376
|
+
raise OSError(errno.EPERM, "path traversal is not allowed")
|
|
1377
|
+
parts = [part for part in value.split("/") if part and part != "."]
|
|
1378
|
+
for part in parts:
|
|
1379
|
+
if part == "..":
|
|
1380
|
+
raise OSError(errno.EPERM, "path traversal is not allowed")
|
|
1381
|
+
return parts
|
|
1382
|
+
|
|
1383
|
+
def open_dir(path_value, dir_fd=None):
|
|
1384
|
+
return os.open(path_value, DIR_FLAGS, dir_fd=dir_fd)
|
|
1385
|
+
|
|
1386
|
+
def walk_dir(root_fd, segments, mkdir_enabled=False):
|
|
1387
|
+
current_fd = os.dup(root_fd)
|
|
1388
|
+
try:
|
|
1389
|
+
for segment in segments:
|
|
1390
|
+
try:
|
|
1391
|
+
next_fd = open_dir(segment, dir_fd=current_fd)
|
|
1392
|
+
except FileNotFoundError:
|
|
1393
|
+
if not mkdir_enabled:
|
|
1394
|
+
raise
|
|
1395
|
+
os.mkdir(segment, 0o777, dir_fd=current_fd)
|
|
1396
|
+
next_fd = open_dir(segment, dir_fd=current_fd)
|
|
1397
|
+
os.close(current_fd)
|
|
1398
|
+
current_fd = next_fd
|
|
1399
|
+
return current_fd
|
|
1400
|
+
except Exception:
|
|
1401
|
+
os.close(current_fd)
|
|
1402
|
+
raise
|
|
1403
|
+
|
|
1404
|
+
def parent_and_basename(root_fd, relative):
|
|
1405
|
+
segments = split_relative(relative)
|
|
1406
|
+
if not segments:
|
|
1407
|
+
raise OSError(errno.EPERM, "operation requires a non-root path")
|
|
1408
|
+
parent_fd = walk_dir(root_fd, segments[:-1])
|
|
1409
|
+
return parent_fd, segments[-1]
|
|
1410
|
+
|
|
1411
|
+
def encode_stat(st):
|
|
1412
|
+
mode = st.st_mode
|
|
1413
|
+
return {
|
|
1414
|
+
"dev": st.st_dev,
|
|
1415
|
+
"gid": st.st_gid,
|
|
1416
|
+
"ino": st.st_ino,
|
|
1417
|
+
"isDirectory": stat.S_ISDIR(mode),
|
|
1418
|
+
"isFile": stat.S_ISREG(mode),
|
|
1419
|
+
"isSymbolicLink": stat.S_ISLNK(mode),
|
|
1420
|
+
"mode": mode,
|
|
1421
|
+
"mtimeMs": st.st_mtime * 1000,
|
|
1422
|
+
"nlink": st.st_nlink,
|
|
1423
|
+
"size": st.st_size,
|
|
1424
|
+
"uid": st.st_uid,
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
def reject_unsafe_endpoint(st):
|
|
1428
|
+
mode = st.st_mode
|
|
1429
|
+
if stat.S_ISLNK(mode):
|
|
1430
|
+
raise OSError(errno.ELOOP, "symlink endpoint is not allowed")
|
|
1431
|
+
if stat.S_ISREG(mode) and st.st_nlink > 1:
|
|
1432
|
+
raise OSError(errno.EPERM, "hardlinked file endpoint is not allowed")
|
|
1433
|
+
|
|
1434
|
+
def stat_path(root_fd, payload):
|
|
1435
|
+
relative = payload.get("relativePath", "")
|
|
1436
|
+
segments = split_relative(relative)
|
|
1437
|
+
if not segments:
|
|
1438
|
+
return encode_stat(os.fstat(root_fd))
|
|
1439
|
+
parent_fd, basename = parent_and_basename(root_fd, relative)
|
|
1440
|
+
try:
|
|
1441
|
+
st = os.lstat(basename, dir_fd=parent_fd)
|
|
1442
|
+
if payload.get("rejectSymlink", True) and stat.S_ISLNK(st.st_mode):
|
|
1443
|
+
raise OSError(errno.ELOOP, "symlink endpoint is not allowed")
|
|
1444
|
+
return encode_stat(st)
|
|
1445
|
+
finally:
|
|
1446
|
+
os.close(parent_fd)
|
|
1447
|
+
|
|
1448
|
+
def readdir_path(root_fd, payload):
|
|
1449
|
+
dir_fd = walk_dir(root_fd, split_relative(payload.get("relativePath", "")))
|
|
1450
|
+
try:
|
|
1451
|
+
names = sorted(os.listdir(dir_fd))
|
|
1452
|
+
if not payload.get("withFileTypes", False):
|
|
1453
|
+
return names
|
|
1454
|
+
entries = []
|
|
1455
|
+
for name in names:
|
|
1456
|
+
st = os.lstat(name, dir_fd=dir_fd)
|
|
1457
|
+
entry = encode_stat(st)
|
|
1458
|
+
entry["name"] = name
|
|
1459
|
+
entries.append(entry)
|
|
1460
|
+
return entries
|
|
1461
|
+
finally:
|
|
1462
|
+
os.close(dir_fd)
|
|
1463
|
+
|
|
1464
|
+
def mkdirp_path(root_fd, payload):
|
|
1465
|
+
dir_fd = walk_dir(root_fd, split_relative(payload.get("relativePath", "")), mkdir_enabled=True)
|
|
1466
|
+
os.close(dir_fd)
|
|
1467
|
+
return None
|
|
1468
|
+
|
|
1469
|
+
def remove_tree(parent_fd, basename):
|
|
1470
|
+
st = os.lstat(basename, dir_fd=parent_fd)
|
|
1471
|
+
if stat.S_ISDIR(st.st_mode) and not stat.S_ISLNK(st.st_mode):
|
|
1472
|
+
dir_fd = open_dir(basename, dir_fd=parent_fd)
|
|
1473
|
+
try:
|
|
1474
|
+
for child in os.listdir(dir_fd):
|
|
1475
|
+
remove_tree(dir_fd, child)
|
|
1476
|
+
finally:
|
|
1477
|
+
os.close(dir_fd)
|
|
1478
|
+
os.rmdir(basename, dir_fd=parent_fd)
|
|
1479
|
+
else:
|
|
1480
|
+
os.unlink(basename, dir_fd=parent_fd)
|
|
1481
|
+
|
|
1482
|
+
def remove_path(root_fd, payload):
|
|
1483
|
+
parent_fd, basename = parent_and_basename(root_fd, payload.get("relativePath", ""))
|
|
1484
|
+
try:
|
|
1485
|
+
try:
|
|
1486
|
+
st = os.lstat(basename, dir_fd=parent_fd)
|
|
1487
|
+
except FileNotFoundError:
|
|
1488
|
+
if payload.get("force", True):
|
|
1489
|
+
return None
|
|
1490
|
+
raise
|
|
1491
|
+
if stat.S_ISDIR(st.st_mode) and not stat.S_ISLNK(st.st_mode):
|
|
1492
|
+
if payload.get("recursive", False):
|
|
1493
|
+
remove_tree(parent_fd, basename)
|
|
1494
|
+
else:
|
|
1495
|
+
os.rmdir(basename, dir_fd=parent_fd)
|
|
1496
|
+
else:
|
|
1497
|
+
os.unlink(basename, dir_fd=parent_fd)
|
|
1498
|
+
return None
|
|
1499
|
+
finally:
|
|
1500
|
+
os.close(parent_fd)
|
|
1501
|
+
|
|
1502
|
+
def rename_path(root_fd, payload):
|
|
1503
|
+
from_parent_fd, from_base = parent_and_basename(root_fd, payload["from"])
|
|
1504
|
+
to_parent_fd, to_base = parent_and_basename(root_fd, payload["to"])
|
|
1505
|
+
try:
|
|
1506
|
+
from_stat = os.lstat(from_base, dir_fd=from_parent_fd)
|
|
1507
|
+
reject_unsafe_endpoint(from_stat)
|
|
1508
|
+
if not payload.get("overwrite", True):
|
|
1509
|
+
try:
|
|
1510
|
+
os.lstat(to_base, dir_fd=to_parent_fd)
|
|
1511
|
+
raise FileExistsError(errno.EEXIST, "destination exists", to_base)
|
|
1512
|
+
except FileNotFoundError:
|
|
1513
|
+
pass
|
|
1514
|
+
os.rename(from_base, to_base, src_dir_fd=from_parent_fd, dst_dir_fd=to_parent_fd)
|
|
1515
|
+
os.fsync(from_parent_fd)
|
|
1516
|
+
if from_parent_fd != to_parent_fd:
|
|
1517
|
+
os.fsync(to_parent_fd)
|
|
1518
|
+
return None
|
|
1519
|
+
finally:
|
|
1520
|
+
os.close(from_parent_fd)
|
|
1521
|
+
os.close(to_parent_fd)
|
|
1522
|
+
|
|
1523
|
+
def create_temp_file(parent_fd, basename, mode):
|
|
1524
|
+
prefix = "." + basename + "."
|
|
1525
|
+
for _ in range(128):
|
|
1526
|
+
candidate = prefix + secrets.token_hex(6) + ".tmp"
|
|
1527
|
+
try:
|
|
1528
|
+
fd = os.open(candidate, WRITE_FLAGS, mode, dir_fd=parent_fd)
|
|
1529
|
+
return candidate, fd
|
|
1530
|
+
except FileExistsError:
|
|
1531
|
+
continue
|
|
1532
|
+
raise RuntimeError("failed to allocate pinned temp file")
|
|
1533
|
+
|
|
1534
|
+
def write_path(root_fd, payload):
|
|
1535
|
+
parent_fd = walk_dir(root_fd, split_relative(payload.get("relativeParentPath", "")), bool(payload.get("mkdir", True)))
|
|
1536
|
+
temp_fd = None
|
|
1537
|
+
temp_name = None
|
|
1538
|
+
basename = payload["basename"]
|
|
1539
|
+
mode = int(payload.get("mode", 0o600))
|
|
1540
|
+
overwrite = bool(payload.get("overwrite", True))
|
|
1541
|
+
max_bytes = int(payload.get("maxBytes", -1))
|
|
1542
|
+
data = base64.b64decode(payload.get("base64", ""))
|
|
1543
|
+
try:
|
|
1544
|
+
if max_bytes >= 0 and len(data) > max_bytes:
|
|
1545
|
+
raise RuntimeError("fs-safe-too-large:%d:%d" % (max_bytes, len(data)))
|
|
1546
|
+
if not overwrite:
|
|
1547
|
+
try:
|
|
1548
|
+
os.lstat(basename, dir_fd=parent_fd)
|
|
1549
|
+
raise FileExistsError(errno.EEXIST, "destination exists", basename)
|
|
1550
|
+
except FileNotFoundError:
|
|
1551
|
+
pass
|
|
1552
|
+
temp_name, temp_fd = create_temp_file(parent_fd, basename, mode)
|
|
1553
|
+
view = memoryview(data)
|
|
1554
|
+
while view:
|
|
1555
|
+
written = os.write(temp_fd, view)
|
|
1556
|
+
if written <= 0:
|
|
1557
|
+
raise OSError(errno.EIO, "short write")
|
|
1558
|
+
view = view[written:]
|
|
1559
|
+
os.fsync(temp_fd)
|
|
1560
|
+
os.close(temp_fd)
|
|
1561
|
+
temp_fd = None
|
|
1562
|
+
os.replace(temp_name, basename, src_dir_fd=parent_fd, dst_dir_fd=parent_fd)
|
|
1563
|
+
temp_name = None
|
|
1564
|
+
os.fsync(parent_fd)
|
|
1565
|
+
result_stat = os.stat(basename, dir_fd=parent_fd, follow_symlinks=False)
|
|
1566
|
+
return {"dev": result_stat.st_dev, "ino": result_stat.st_ino}
|
|
1567
|
+
finally:
|
|
1568
|
+
if temp_fd is not None:
|
|
1569
|
+
os.close(temp_fd)
|
|
1570
|
+
if temp_name is not None:
|
|
1571
|
+
try:
|
|
1572
|
+
os.unlink(temp_name, dir_fd=parent_fd)
|
|
1573
|
+
except FileNotFoundError:
|
|
1574
|
+
pass
|
|
1575
|
+
os.close(parent_fd)
|
|
1576
|
+
|
|
1577
|
+
def copy_path(root_fd, payload):
|
|
1578
|
+
source_fd = os.open(payload["sourcePath"], READ_FLAGS)
|
|
1579
|
+
parent_fd = None
|
|
1580
|
+
temp_fd = None
|
|
1581
|
+
temp_name = None
|
|
1582
|
+
try:
|
|
1583
|
+
source_stat = os.fstat(source_fd)
|
|
1584
|
+
if not stat.S_ISREG(source_stat.st_mode):
|
|
1585
|
+
raise RuntimeError("fs-safe-not-file")
|
|
1586
|
+
if source_stat.st_dev != int(payload["sourceDev"]) or source_stat.st_ino != int(payload["sourceIno"]):
|
|
1587
|
+
raise RuntimeError("fs-safe-source-mismatch")
|
|
1588
|
+
basename = payload["basename"]
|
|
1589
|
+
mode = int(payload.get("mode", 0o600))
|
|
1590
|
+
overwrite = bool(payload.get("overwrite", True))
|
|
1591
|
+
max_bytes = int(payload.get("maxBytes", -1))
|
|
1592
|
+
if max_bytes >= 0 and source_stat.st_size > max_bytes:
|
|
1593
|
+
raise RuntimeError("fs-safe-too-large:%d:%d" % (max_bytes, source_stat.st_size))
|
|
1594
|
+
parent_fd = walk_dir(root_fd, split_relative(payload.get("relativeParentPath", "")), bool(payload.get("mkdir", True)))
|
|
1595
|
+
if not overwrite:
|
|
1596
|
+
try:
|
|
1597
|
+
os.lstat(basename, dir_fd=parent_fd)
|
|
1598
|
+
raise FileExistsError(errno.EEXIST, "destination exists", basename)
|
|
1599
|
+
except FileNotFoundError:
|
|
1600
|
+
pass
|
|
1601
|
+
temp_name, temp_fd = create_temp_file(parent_fd, basename, mode)
|
|
1602
|
+
written_bytes = 0
|
|
1603
|
+
while True:
|
|
1604
|
+
chunk = os.read(source_fd, 65536)
|
|
1605
|
+
if not chunk:
|
|
1606
|
+
break
|
|
1607
|
+
written_bytes += len(chunk)
|
|
1608
|
+
if max_bytes >= 0 and written_bytes > max_bytes:
|
|
1609
|
+
raise RuntimeError("fs-safe-too-large:%d:%d" % (max_bytes, written_bytes))
|
|
1610
|
+
view = memoryview(chunk)
|
|
1611
|
+
while view:
|
|
1612
|
+
written = os.write(temp_fd, view)
|
|
1613
|
+
if written <= 0:
|
|
1614
|
+
raise OSError(errno.EIO, "short write")
|
|
1615
|
+
view = view[written:]
|
|
1616
|
+
os.fsync(temp_fd)
|
|
1617
|
+
os.close(temp_fd)
|
|
1618
|
+
temp_fd = None
|
|
1619
|
+
os.replace(temp_name, basename, src_dir_fd=parent_fd, dst_dir_fd=parent_fd)
|
|
1620
|
+
temp_name = None
|
|
1621
|
+
os.fsync(parent_fd)
|
|
1622
|
+
result_stat = os.stat(basename, dir_fd=parent_fd, follow_symlinks=False)
|
|
1623
|
+
return {"dev": result_stat.st_dev, "ino": result_stat.st_ino}
|
|
1624
|
+
finally:
|
|
1625
|
+
os.close(source_fd)
|
|
1626
|
+
if temp_fd is not None:
|
|
1627
|
+
os.close(temp_fd)
|
|
1628
|
+
if temp_name is not None and parent_fd is not None:
|
|
1629
|
+
try:
|
|
1630
|
+
os.unlink(temp_name, dir_fd=parent_fd)
|
|
1631
|
+
except FileNotFoundError:
|
|
1632
|
+
pass
|
|
1633
|
+
if parent_fd is not None:
|
|
1634
|
+
os.close(parent_fd)
|
|
1635
|
+
|
|
1636
|
+
def run_operation(operation, root_path, payload):
|
|
1637
|
+
root_fd = open_dir(root_path)
|
|
1638
|
+
try:
|
|
1639
|
+
if operation == "stat":
|
|
1640
|
+
return stat_path(root_fd, payload)
|
|
1641
|
+
if operation == "readdir":
|
|
1642
|
+
return readdir_path(root_fd, payload)
|
|
1643
|
+
if operation == "mkdirp":
|
|
1644
|
+
return mkdirp_path(root_fd, payload)
|
|
1645
|
+
if operation == "remove":
|
|
1646
|
+
return remove_path(root_fd, payload)
|
|
1647
|
+
if operation == "rename":
|
|
1648
|
+
return rename_path(root_fd, payload)
|
|
1649
|
+
if operation == "write":
|
|
1650
|
+
return write_path(root_fd, payload)
|
|
1651
|
+
if operation == "copy":
|
|
1652
|
+
return copy_path(root_fd, payload)
|
|
1653
|
+
raise RuntimeError("unknown operation: " + operation)
|
|
1654
|
+
finally:
|
|
1655
|
+
os.close(root_fd)
|
|
1656
|
+
|
|
1657
|
+
for line in sys.stdin:
|
|
1658
|
+
try:
|
|
1659
|
+
request = json.loads(line)
|
|
1660
|
+
result = run_operation(request["operation"], request["rootPath"], request.get("payload") or {})
|
|
1661
|
+
response = {"id": request["id"], "ok": True, "result": result}
|
|
1662
|
+
except Exception as exc:
|
|
1663
|
+
response = {
|
|
1664
|
+
"id": request.get("id") if isinstance(locals().get("request"), dict) else None,
|
|
1665
|
+
"ok": False,
|
|
1666
|
+
"code": exc.__class__.__name__,
|
|
1667
|
+
"errno": getattr(exc, "errno", None),
|
|
1668
|
+
"message": str(exc),
|
|
1669
|
+
}
|
|
1670
|
+
print(json.dumps(response, separators=(",", ":")), flush=True)
|
|
1671
|
+
`;
|
|
1672
|
+
let nextRequestId = 1;
|
|
1673
|
+
let worker = null;
|
|
1674
|
+
function __resetPinnedPythonWorkerForTest() {
|
|
1675
|
+
const currentWorker = worker;
|
|
1676
|
+
worker = null;
|
|
1677
|
+
if (!currentWorker) {
|
|
1678
|
+
return;
|
|
1679
|
+
}
|
|
1680
|
+
currentWorker.pending.clear();
|
|
1681
|
+
currentWorker.child.kill("SIGTERM");
|
|
1682
|
+
}
|
|
1683
|
+
const PYTHON_CANDIDATE_DEFAULTS = [
|
|
1684
|
+
"/usr/bin/python3",
|
|
1685
|
+
"/opt/homebrew/bin/python3",
|
|
1686
|
+
"/usr/local/bin/python3",
|
|
1687
|
+
];
|
|
1688
|
+
function canExecute(binPath) {
|
|
1689
|
+
try {
|
|
1690
|
+
external_node_fs_.accessSync(binPath, external_node_fs_.constants.X_OK);
|
|
1691
|
+
return true;
|
|
1692
|
+
}
|
|
1693
|
+
catch {
|
|
1694
|
+
return false;
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
function resolvePython() {
|
|
1698
|
+
const configured = getFsSafePythonConfig().pythonPath;
|
|
1699
|
+
if (configured) {
|
|
1700
|
+
return configured;
|
|
1701
|
+
}
|
|
1702
|
+
for (const candidate of PYTHON_CANDIDATE_DEFAULTS) {
|
|
1703
|
+
if (canExecute(candidate)) {
|
|
1704
|
+
return candidate;
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
return "python3";
|
|
1708
|
+
}
|
|
1709
|
+
function assertPinnedHelperSupported() {
|
|
1710
|
+
if (process.platform === "win32") {
|
|
1711
|
+
throw new errors_FsSafeError("unsupported-platform", "fd-relative pinned filesystem operations are not available on Windows");
|
|
1712
|
+
}
|
|
1713
|
+
if (getFsSafePythonConfig().mode === "off") {
|
|
1714
|
+
throw new errors_FsSafeError("helper-unavailable", "Python helper is disabled");
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
function isSpawnUnavailable(error) {
|
|
1718
|
+
if (!(error instanceof Error)) {
|
|
1719
|
+
return false;
|
|
1720
|
+
}
|
|
1721
|
+
const maybeErrno = error;
|
|
1722
|
+
return (typeof maybeErrno.syscall === "string" &&
|
|
1723
|
+
maybeErrno.syscall.startsWith("spawn") &&
|
|
1724
|
+
["EACCES", "ENOENT", "ENOEXEC"].includes(maybeErrno.code ?? ""));
|
|
1725
|
+
}
|
|
1726
|
+
function mapWorkerError(response) {
|
|
1727
|
+
const code = typeof response.code === "string" ? response.code : "";
|
|
1728
|
+
const errno = typeof response.errno === "number" ? response.errno : undefined;
|
|
1729
|
+
const message = typeof response.message === "string" && response.message
|
|
1730
|
+
? response.message
|
|
1731
|
+
: "pinned helper failed";
|
|
1732
|
+
const tooLarge = message.match(/fs-safe-too-large:(\d+):(\d+)/);
|
|
1733
|
+
if (tooLarge) {
|
|
1734
|
+
const [, limit, got] = tooLarge;
|
|
1735
|
+
return new errors_FsSafeError("too-large", `file exceeds limit of ${limit} bytes (got at least ${got})`);
|
|
1736
|
+
}
|
|
1737
|
+
if (message.includes("fs-safe-not-file")) {
|
|
1738
|
+
return new errors_FsSafeError("not-file", "not a file");
|
|
1739
|
+
}
|
|
1740
|
+
if (message.includes("fs-safe-source-mismatch")) {
|
|
1741
|
+
return new errors_FsSafeError("path-mismatch", "source path changed during copy");
|
|
1742
|
+
}
|
|
1743
|
+
if (code === "FileNotFoundError" || errno === 2) {
|
|
1744
|
+
return new errors_FsSafeError("not-found", "file not found");
|
|
1745
|
+
}
|
|
1746
|
+
if (code === "FileExistsError" || errno === 17) {
|
|
1747
|
+
return new errors_FsSafeError("already-exists", message);
|
|
1748
|
+
}
|
|
1749
|
+
if (errno === 39) {
|
|
1750
|
+
return new errors_FsSafeError("not-empty", "directory is not empty");
|
|
1751
|
+
}
|
|
1752
|
+
if (errno === 1 || errno === 13 || errno === 21) {
|
|
1753
|
+
return new errors_FsSafeError("not-removable", "path is not removable under root");
|
|
1754
|
+
}
|
|
1755
|
+
if (code === "NotADirectoryError" || code === "OSError" || errno === 20 || errno === 40) {
|
|
1756
|
+
return new errors_FsSafeError("path-alias", message);
|
|
1757
|
+
}
|
|
1758
|
+
return new errors_FsSafeError("helper-failed", message);
|
|
1759
|
+
}
|
|
1760
|
+
function rejectPending(error) {
|
|
1761
|
+
if (!worker) {
|
|
1762
|
+
return;
|
|
1763
|
+
}
|
|
1764
|
+
setWorkerRef(worker, false);
|
|
1765
|
+
for (const pending of worker.pending.values()) {
|
|
1766
|
+
pending.reject(error);
|
|
1767
|
+
}
|
|
1768
|
+
worker.pending.clear();
|
|
1769
|
+
worker = null;
|
|
1770
|
+
}
|
|
1771
|
+
function handleWorkerLine(line) {
|
|
1772
|
+
if (!worker || !line.trim()) {
|
|
1773
|
+
return;
|
|
1774
|
+
}
|
|
1775
|
+
let decoded;
|
|
1776
|
+
try {
|
|
1777
|
+
decoded = JSON.parse(line);
|
|
1778
|
+
}
|
|
1779
|
+
catch {
|
|
1780
|
+
rejectPending(new errors_FsSafeError("helper-failed", `pinned helper returned invalid JSON: ${line}`));
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
if (typeof decoded !== "object" || decoded === null || !("id" in decoded)) {
|
|
1784
|
+
rejectPending(new errors_FsSafeError("helper-failed", "pinned helper returned invalid response"));
|
|
1785
|
+
return;
|
|
1786
|
+
}
|
|
1787
|
+
const response = decoded;
|
|
1788
|
+
const id = typeof response.id === "number" ? response.id : undefined;
|
|
1789
|
+
if (id === undefined) {
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
const pending = worker.pending.get(id);
|
|
1793
|
+
if (!pending) {
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
worker.pending.delete(id);
|
|
1797
|
+
if (worker.pending.size === 0) {
|
|
1798
|
+
setWorkerRef(worker, false);
|
|
1799
|
+
}
|
|
1800
|
+
if (response.ok === true) {
|
|
1801
|
+
pending.resolve(response.result);
|
|
1802
|
+
return;
|
|
1803
|
+
}
|
|
1804
|
+
pending.reject(mapWorkerError(decoded));
|
|
1805
|
+
}
|
|
1806
|
+
function getWorker() {
|
|
1807
|
+
assertPinnedHelperSupported();
|
|
1808
|
+
if (worker) {
|
|
1809
|
+
return worker;
|
|
1810
|
+
}
|
|
1811
|
+
const child = (0,external_node_child_process_.spawn)(resolvePython(), ["-u", "-c", PINNED_PYTHON_WORKER_SOURCE], {
|
|
1812
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1813
|
+
});
|
|
1814
|
+
worker = { child, pending: new Map(), stderr: "", stdoutBuffer: "" };
|
|
1815
|
+
child.stdout.setEncoding("utf8");
|
|
1816
|
+
child.stderr.setEncoding("utf8");
|
|
1817
|
+
child.stdout.on("data", (chunk) => {
|
|
1818
|
+
const current = worker;
|
|
1819
|
+
if (!current) {
|
|
1820
|
+
return;
|
|
1821
|
+
}
|
|
1822
|
+
current.stdoutBuffer += chunk;
|
|
1823
|
+
for (;;) {
|
|
1824
|
+
const newline = current.stdoutBuffer.indexOf("\n");
|
|
1825
|
+
if (newline < 0) {
|
|
1826
|
+
break;
|
|
1827
|
+
}
|
|
1828
|
+
const line = current.stdoutBuffer.slice(0, newline);
|
|
1829
|
+
current.stdoutBuffer = current.stdoutBuffer.slice(newline + 1);
|
|
1830
|
+
handleWorkerLine(line);
|
|
1831
|
+
}
|
|
1832
|
+
});
|
|
1833
|
+
child.stderr.on("data", (chunk) => {
|
|
1834
|
+
if (worker) {
|
|
1835
|
+
worker.stderr = `${worker.stderr}${chunk}`.slice(-4096);
|
|
1836
|
+
}
|
|
1837
|
+
});
|
|
1838
|
+
child.once("error", (error) => {
|
|
1839
|
+
const mapped = isSpawnUnavailable(error)
|
|
1840
|
+
? new errors_FsSafeError("helper-unavailable", "Python helper is unavailable", { cause: error })
|
|
1841
|
+
: error instanceof Error
|
|
1842
|
+
? error
|
|
1843
|
+
: new Error(String(error));
|
|
1844
|
+
rejectPending(mapped);
|
|
1845
|
+
});
|
|
1846
|
+
child.once("close", (code, signal) => {
|
|
1847
|
+
const stderr = worker?.stderr.trim();
|
|
1848
|
+
rejectPending(new errors_FsSafeError("helper-failed", stderr || `pinned helper exited with code ${code ?? "null"} (${signal ?? "?"})`));
|
|
1849
|
+
});
|
|
1850
|
+
process.once("exit", () => {
|
|
1851
|
+
child.kill("SIGTERM");
|
|
1852
|
+
});
|
|
1853
|
+
setWorkerRef(worker, false);
|
|
1854
|
+
return worker;
|
|
1855
|
+
}
|
|
1856
|
+
function setRefable(value, ref) {
|
|
1857
|
+
if (!value) {
|
|
1858
|
+
return;
|
|
1859
|
+
}
|
|
1860
|
+
const method = ref ? "ref" : "unref";
|
|
1861
|
+
const refable = value;
|
|
1862
|
+
refable[method]?.();
|
|
1863
|
+
}
|
|
1864
|
+
function setWorkerRef(currentWorker, ref) {
|
|
1865
|
+
setRefable(currentWorker.child, ref);
|
|
1866
|
+
setRefable(currentWorker.child.stdin, ref);
|
|
1867
|
+
setRefable(currentWorker.child.stdout, ref);
|
|
1868
|
+
setRefable(currentWorker.child.stderr, ref);
|
|
1869
|
+
}
|
|
1870
|
+
async function runPinnedPythonOperation(params) {
|
|
1871
|
+
const requestId = nextRequestId++;
|
|
1872
|
+
const currentWorker = getWorker();
|
|
1873
|
+
if (typeof currentWorker.child.stdin?.write !== "function") {
|
|
1874
|
+
throw new errors_FsSafeError("helper-unavailable", "Python helper stdin is unavailable");
|
|
1875
|
+
}
|
|
1876
|
+
setWorkerRef(currentWorker, true);
|
|
1877
|
+
return await new Promise((resolve, reject) => {
|
|
1878
|
+
currentWorker.pending.set(requestId, {
|
|
1879
|
+
reject,
|
|
1880
|
+
resolve: (value) => resolve(value),
|
|
1881
|
+
});
|
|
1882
|
+
const request = JSON.stringify({
|
|
1883
|
+
id: requestId,
|
|
1884
|
+
operation: params.operation,
|
|
1885
|
+
rootPath: params.rootPath,
|
|
1886
|
+
payload: params.payload,
|
|
1887
|
+
});
|
|
1888
|
+
currentWorker.child.stdin.write(`${request}\n`, (error) => {
|
|
1889
|
+
if (error) {
|
|
1890
|
+
currentWorker.pending.delete(requestId);
|
|
1891
|
+
if (currentWorker.pending.size === 0) {
|
|
1892
|
+
setWorkerRef(currentWorker, false);
|
|
1893
|
+
}
|
|
1894
|
+
reject(error);
|
|
1895
|
+
}
|
|
1896
|
+
});
|
|
1897
|
+
});
|
|
1898
|
+
}
|
|
1899
|
+
function assertPinnedPythonOperationAvailable() {
|
|
1900
|
+
const currentWorker = getWorker();
|
|
1901
|
+
if (typeof currentWorker.child.stdin?.write !== "function") {
|
|
1902
|
+
throw new errors_FsSafeError("helper-unavailable", "Python helper stdin is unavailable");
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
function validatePinnedOperationPayload(payload) {
|
|
1906
|
+
if (typeof payload.relativePath === "string") {
|
|
1907
|
+
validatePinnedRelativePath(payload.relativePath);
|
|
1908
|
+
}
|
|
1909
|
+
if (typeof payload.relativeParentPath === "string") {
|
|
1910
|
+
validatePinnedRelativePath(payload.relativeParentPath);
|
|
1911
|
+
}
|
|
1912
|
+
if (typeof payload.from === "string") {
|
|
1913
|
+
validatePinnedRelativePath(payload.from);
|
|
1914
|
+
}
|
|
1915
|
+
if (typeof payload.to === "string") {
|
|
1916
|
+
validatePinnedRelativePath(payload.to);
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
function isPinnedHelperUnavailable(error) {
|
|
1920
|
+
return error instanceof Error &&
|
|
1921
|
+
"code" in error &&
|
|
1922
|
+
error.code === "helper-unavailable";
|
|
1923
|
+
}
|
|
1924
|
+
function validatePinnedRelativePath(relativePath) {
|
|
1925
|
+
if (relativePath.length === 0 || relativePath === ".") {
|
|
1926
|
+
return;
|
|
1927
|
+
}
|
|
1928
|
+
if (relativePath.includes("\0")) {
|
|
1929
|
+
throw new errors_FsSafeError("invalid-path", "relative path contains a NUL byte");
|
|
1930
|
+
}
|
|
1931
|
+
if (relativePath.startsWith("/") ||
|
|
1932
|
+
relativePath.startsWith("//") ||
|
|
1933
|
+
relativePath === ".." ||
|
|
1934
|
+
relativePath.startsWith("../") ||
|
|
1935
|
+
relativePath.startsWith("..\\")) {
|
|
1936
|
+
throw new errors_FsSafeError("invalid-path", "relative path must not escape root");
|
|
1937
|
+
}
|
|
1938
|
+
for (const segment of relativePath.split("/")) {
|
|
1939
|
+
if (segment === "..") {
|
|
1940
|
+
throw new errors_FsSafeError("invalid-path", "relative path must not contain '..'");
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-helper.js
|
|
1946
|
+
|
|
1947
|
+
|
|
1948
|
+
async function runPinnedHelper(operation, rootDir, payload) {
|
|
1949
|
+
validatePinnedOperationPayload(payload);
|
|
1950
|
+
return await runPinnedPythonOperation({
|
|
1951
|
+
operation,
|
|
1952
|
+
rootPath: rootDir,
|
|
1953
|
+
payload,
|
|
1954
|
+
});
|
|
1955
|
+
}
|
|
1956
|
+
async function helperStat(rootDir, relativePath) {
|
|
1957
|
+
return await runPinnedHelper("stat", rootDir, { relativePath });
|
|
1958
|
+
}
|
|
1959
|
+
async function helperReaddir(rootDir, relativePath, withFileTypes) {
|
|
1960
|
+
return await runPinnedHelper("readdir", rootDir, {
|
|
1961
|
+
relativePath,
|
|
1962
|
+
withFileTypes,
|
|
1963
|
+
});
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-path.js
|
|
1967
|
+
|
|
1968
|
+
|
|
1969
|
+
|
|
1970
|
+
function isPinnedPathHelperSpawnError(error) {
|
|
1971
|
+
return canFallbackFromPythonError(error);
|
|
1972
|
+
}
|
|
1973
|
+
async function runPinnedPathHelper(params) {
|
|
1974
|
+
try {
|
|
1975
|
+
await runPinnedHelper(params.operation, params.rootPath, {
|
|
1976
|
+
relativePath: params.relativePath,
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
1979
|
+
catch (error) {
|
|
1980
|
+
if (error instanceof errors_FsSafeError) {
|
|
1981
|
+
throw error;
|
|
1982
|
+
}
|
|
1983
|
+
throw new errors_FsSafeError("helper-failed", "pinned path helper failed", {
|
|
1984
|
+
cause: error instanceof Error ? error : undefined,
|
|
1985
|
+
});
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-write.js
|
|
1990
|
+
|
|
1991
|
+
|
|
1992
|
+
|
|
1993
|
+
|
|
1994
|
+
|
|
1995
|
+
|
|
1996
|
+
|
|
1997
|
+
|
|
1998
|
+
|
|
1999
|
+
|
|
2000
|
+
|
|
2001
|
+
function byteLength(input, encoding) {
|
|
2002
|
+
return typeof input === "string"
|
|
2003
|
+
? Buffer.byteLength(input, encoding ?? "utf8")
|
|
2004
|
+
: input.byteLength;
|
|
2005
|
+
}
|
|
2006
|
+
function assertSafeBasename(basename) {
|
|
2007
|
+
if (!basename ||
|
|
2008
|
+
basename === "." ||
|
|
2009
|
+
basename === ".." ||
|
|
2010
|
+
basename.includes("/") ||
|
|
2011
|
+
basename.includes("\0")) {
|
|
2012
|
+
throw new errors_FsSafeError("invalid-path", "invalid target path");
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
function assertWithinMaxBytes(bytes, maxBytes) {
|
|
2016
|
+
if (maxBytes !== undefined && bytes > maxBytes) {
|
|
2017
|
+
throw new errors_FsSafeError("too-large", `file exceeds limit of ${maxBytes} bytes (got at least ${bytes})`);
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
function pinned_write_createMaxBytesTransform(maxBytes) {
|
|
2021
|
+
if (maxBytes === undefined) {
|
|
2022
|
+
return undefined;
|
|
2023
|
+
}
|
|
2024
|
+
let bytes = 0;
|
|
2025
|
+
return new external_node_stream_.Transform({
|
|
2026
|
+
transform(chunk, _encoding, callback) {
|
|
2027
|
+
bytes += chunk.byteLength;
|
|
2028
|
+
if (bytes > maxBytes) {
|
|
2029
|
+
callback(new errors_FsSafeError("too-large", `file exceeds limit of ${maxBytes} bytes (got at least ${bytes})`));
|
|
2030
|
+
return;
|
|
2031
|
+
}
|
|
2032
|
+
callback(null, chunk);
|
|
2033
|
+
},
|
|
2034
|
+
});
|
|
2035
|
+
}
|
|
2036
|
+
async function pipelineWithMaxBytes(stream, destination, maxBytes) {
|
|
2037
|
+
const limiter = pinned_write_createMaxBytesTransform(maxBytes);
|
|
2038
|
+
if (limiter) {
|
|
2039
|
+
await (0,external_node_stream_promises_.pipeline)(stream, limiter, destination);
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
2042
|
+
await (0,external_node_stream_promises_.pipeline)(stream, destination);
|
|
2043
|
+
}
|
|
2044
|
+
async function inputToBase64(input, maxBytes) {
|
|
2045
|
+
if (input.kind === "buffer") {
|
|
2046
|
+
assertWithinMaxBytes(byteLength(input.data, input.encoding), maxBytes);
|
|
2047
|
+
return (typeof input.data === "string"
|
|
2048
|
+
? Buffer.from(input.data, input.encoding ?? "utf8")
|
|
2049
|
+
: input.data).toString("base64");
|
|
2050
|
+
}
|
|
2051
|
+
const chunks = [];
|
|
2052
|
+
let bytes = 0;
|
|
2053
|
+
for await (const chunk of input.stream) {
|
|
2054
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
2055
|
+
bytes += buffer.byteLength;
|
|
2056
|
+
assertWithinMaxBytes(bytes, maxBytes);
|
|
2057
|
+
chunks.push(buffer);
|
|
2058
|
+
}
|
|
2059
|
+
return Buffer.concat(chunks, bytes).toString("base64");
|
|
2060
|
+
}
|
|
2061
|
+
async function runPinnedWriteHelper(params) {
|
|
2062
|
+
assertSafeBasename(params.basename);
|
|
2063
|
+
validatePinnedOperationPayload({
|
|
2064
|
+
relativeParentPath: params.relativeParentPath,
|
|
2065
|
+
});
|
|
2066
|
+
if (getFsSafePythonConfig().mode === "off") {
|
|
2067
|
+
return await runPinnedWriteFallback(params);
|
|
2068
|
+
}
|
|
2069
|
+
if (params.input.kind === "stream") {
|
|
2070
|
+
try {
|
|
2071
|
+
assertPinnedPythonOperationAvailable();
|
|
2072
|
+
}
|
|
2073
|
+
catch (error) {
|
|
2074
|
+
if (canFallbackFromPythonError(error)) {
|
|
2075
|
+
return await runPinnedWriteFallback(params);
|
|
2076
|
+
}
|
|
2077
|
+
throw error;
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
const payload = {
|
|
2081
|
+
base64: await inputToBase64(params.input, params.maxBytes),
|
|
2082
|
+
basename: params.basename,
|
|
2083
|
+
maxBytes: params.maxBytes ?? -1,
|
|
2084
|
+
mkdir: params.mkdir,
|
|
2085
|
+
mode: params.mode || 0o600,
|
|
2086
|
+
overwrite: params.overwrite !== false,
|
|
2087
|
+
relativeParentPath: params.relativeParentPath,
|
|
2088
|
+
};
|
|
2089
|
+
try {
|
|
2090
|
+
return await runPinnedPythonOperation({
|
|
2091
|
+
operation: "write",
|
|
2092
|
+
rootPath: params.rootPath,
|
|
2093
|
+
payload,
|
|
2094
|
+
});
|
|
2095
|
+
}
|
|
2096
|
+
catch (error) {
|
|
2097
|
+
if (canFallbackFromPythonError(error)) {
|
|
2098
|
+
return await runPinnedWriteFallback(params);
|
|
2099
|
+
}
|
|
2100
|
+
throw error;
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
async function runPinnedCopyHelper(params) {
|
|
2104
|
+
assertSafeBasename(params.basename);
|
|
2105
|
+
validatePinnedOperationPayload({
|
|
2106
|
+
relativeParentPath: params.relativeParentPath,
|
|
2107
|
+
});
|
|
2108
|
+
return await runPinnedPythonOperation({
|
|
2109
|
+
operation: "copy",
|
|
2110
|
+
rootPath: params.rootPath,
|
|
2111
|
+
payload: {
|
|
2112
|
+
basename: params.basename,
|
|
2113
|
+
maxBytes: params.maxBytes ?? -1,
|
|
2114
|
+
mkdir: params.mkdir,
|
|
2115
|
+
mode: params.mode || 0o600,
|
|
2116
|
+
overwrite: params.overwrite !== false,
|
|
2117
|
+
relativeParentPath: params.relativeParentPath,
|
|
2118
|
+
sourceDev: params.sourceIdentity.dev,
|
|
2119
|
+
sourceIno: params.sourceIdentity.ino,
|
|
2120
|
+
sourcePath: params.sourcePath,
|
|
2121
|
+
},
|
|
2122
|
+
});
|
|
2123
|
+
}
|
|
2124
|
+
async function runPinnedWriteFallback(params) {
|
|
2125
|
+
const parentPath = params.relativeParentPath
|
|
2126
|
+
? external_node_path_.join(params.rootPath, ...params.relativeParentPath.split("/"))
|
|
2127
|
+
: params.rootPath;
|
|
2128
|
+
const parentGuard = await directory_guard_createNearestExistingDirectoryGuard(params.rootPath, parentPath);
|
|
2129
|
+
if (params.mkdir) {
|
|
2130
|
+
await withAsyncDirectoryGuards([parentGuard], async () => {
|
|
2131
|
+
await promises_.mkdir(parentPath, { recursive: true });
|
|
2132
|
+
});
|
|
2133
|
+
}
|
|
2134
|
+
const targetPath = external_node_path_.join(parentPath, params.basename);
|
|
2135
|
+
if (params.overwrite === false) {
|
|
2136
|
+
let handle = await withAsyncDirectoryGuards([parentGuard], async () => await promises_.open(targetPath, external_node_fs_.constants.O_WRONLY | external_node_fs_.constants.O_CREAT | external_node_fs_.constants.O_EXCL, params.mode), {
|
|
2137
|
+
onPostGuardFailure: async (openedHandle) => {
|
|
2138
|
+
// The parent failed verification, so targetPath may now resolve
|
|
2139
|
+
// somewhere else. Close the fd, but do not clean up by path.
|
|
2140
|
+
await openedHandle.close().catch(() => undefined);
|
|
2141
|
+
},
|
|
2142
|
+
});
|
|
2143
|
+
let created = true;
|
|
2144
|
+
try {
|
|
2145
|
+
if (params.input.kind === "buffer") {
|
|
2146
|
+
assertWithinMaxBytes(byteLength(params.input.data, params.input.encoding), params.maxBytes);
|
|
2147
|
+
if (typeof params.input.data === "string") {
|
|
2148
|
+
await handle.writeFile(params.input.data, params.input.encoding ?? "utf8");
|
|
2149
|
+
}
|
|
2150
|
+
else {
|
|
2151
|
+
await handle.writeFile(params.input.data);
|
|
2152
|
+
}
|
|
2153
|
+
}
|
|
2154
|
+
else {
|
|
2155
|
+
await pipelineWithMaxBytes(params.input.stream, handle.createWriteStream(), params.maxBytes);
|
|
2156
|
+
}
|
|
2157
|
+
const stat = await handle.stat();
|
|
2158
|
+
created = false;
|
|
2159
|
+
return { dev: stat.dev, ino: stat.ino };
|
|
2160
|
+
}
|
|
2161
|
+
finally {
|
|
2162
|
+
await handle.close().catch(() => undefined);
|
|
2163
|
+
if (created) {
|
|
2164
|
+
await promises_.rm(targetPath, { force: true }).catch(() => undefined);
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
const tempPath = external_node_path_.join(parentPath, `.${params.basename}.${(0,external_node_crypto_.randomUUID)()}.fallback.tmp`);
|
|
2169
|
+
const tempFlags = external_node_fs_.constants.O_WRONLY |
|
|
2170
|
+
external_node_fs_.constants.O_CREAT |
|
|
2171
|
+
external_node_fs_.constants.O_EXCL |
|
|
2172
|
+
(process.platform !== "win32" && "O_NOFOLLOW" in external_node_fs_.constants
|
|
2173
|
+
? external_node_fs_.constants.O_NOFOLLOW
|
|
2174
|
+
: 0);
|
|
2175
|
+
let handle;
|
|
2176
|
+
let handleClosedByStream = false;
|
|
2177
|
+
try {
|
|
2178
|
+
handle = await promises_.open(tempPath, tempFlags, params.mode);
|
|
2179
|
+
if (params.input.kind === "buffer") {
|
|
2180
|
+
assertWithinMaxBytes(byteLength(params.input.data, params.input.encoding), params.maxBytes);
|
|
2181
|
+
if (typeof params.input.data === "string") {
|
|
2182
|
+
await handle.writeFile(params.input.data, params.input.encoding ?? "utf8");
|
|
2183
|
+
}
|
|
2184
|
+
else {
|
|
2185
|
+
await handle.writeFile(params.input.data);
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
else {
|
|
2189
|
+
const writable = handle.createWriteStream();
|
|
2190
|
+
writable.once("close", () => {
|
|
2191
|
+
handleClosedByStream = true;
|
|
2192
|
+
});
|
|
2193
|
+
await pipelineWithMaxBytes(params.input.stream, writable, params.maxBytes);
|
|
2194
|
+
}
|
|
2195
|
+
if (!handleClosedByStream) {
|
|
2196
|
+
await handle.close().catch(() => undefined);
|
|
2197
|
+
handle = undefined;
|
|
2198
|
+
}
|
|
2199
|
+
await withAsyncDirectoryGuards([parentGuard], async () => {
|
|
2200
|
+
await promises_.rename(tempPath, targetPath);
|
|
2201
|
+
});
|
|
2202
|
+
}
|
|
2203
|
+
catch (error) {
|
|
2204
|
+
if (handle && !handleClosedByStream) {
|
|
2205
|
+
await handle.close().catch(() => undefined);
|
|
2206
|
+
}
|
|
2207
|
+
await promises_.rm(tempPath, { force: true }).catch(() => undefined);
|
|
2208
|
+
throw error;
|
|
2209
|
+
}
|
|
2210
|
+
const stat = await promises_.stat(targetPath);
|
|
2211
|
+
return { dev: stat.dev, ino: stat.ino };
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
// EXTERNAL MODULE: external "node:os"
|
|
2215
|
+
var external_node_os_ = __webpack_require__(8161);
|
|
2216
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-path.js
|
|
2217
|
+
|
|
2218
|
+
|
|
2219
|
+
|
|
2220
|
+
|
|
2221
|
+
|
|
2222
|
+
const ROOT_PATH_ALIAS_POLICIES = {
|
|
2223
|
+
strict: Object.freeze({
|
|
2224
|
+
allowFinalSymlinkForUnlink: false,
|
|
2225
|
+
allowFinalHardlinkForUnlink: false,
|
|
2226
|
+
}),
|
|
2227
|
+
unlinkTarget: Object.freeze({
|
|
2228
|
+
allowFinalSymlinkForUnlink: true,
|
|
2229
|
+
allowFinalHardlinkForUnlink: true,
|
|
2230
|
+
}),
|
|
2231
|
+
};
|
|
2232
|
+
async function resolveRootPath(params) {
|
|
2233
|
+
const rootPath = external_node_path_.resolve(params.rootPath);
|
|
2234
|
+
const absolutePath = external_node_path_.resolve(params.absolutePath);
|
|
2235
|
+
const rootCanonicalPath = params.rootCanonicalPath
|
|
2236
|
+
? external_node_path_.resolve(params.rootCanonicalPath)
|
|
2237
|
+
: await resolvePathViaExistingAncestor(rootPath);
|
|
2238
|
+
const context = createBoundaryResolutionContext({
|
|
2239
|
+
resolveParams: params,
|
|
2240
|
+
rootPath,
|
|
2241
|
+
absolutePath,
|
|
2242
|
+
rootCanonicalPath,
|
|
2243
|
+
outsideLexicalCanonicalPath: await resolveOutsideLexicalCanonicalPathAsync({
|
|
2244
|
+
rootPath,
|
|
2245
|
+
absolutePath,
|
|
2246
|
+
}),
|
|
2247
|
+
});
|
|
2248
|
+
const outsideResult = await resolveOutsideRootPathAsync({
|
|
2249
|
+
boundaryLabel: params.boundaryLabel,
|
|
2250
|
+
context,
|
|
2251
|
+
});
|
|
2252
|
+
if (outsideResult) {
|
|
2253
|
+
return outsideResult;
|
|
2254
|
+
}
|
|
2255
|
+
return resolveRootPathLexicalAsync({
|
|
2256
|
+
params,
|
|
2257
|
+
absolutePath: context.absolutePath,
|
|
2258
|
+
rootPath: context.rootPath,
|
|
2259
|
+
rootCanonicalPath: context.rootCanonicalPath,
|
|
2260
|
+
});
|
|
2261
|
+
}
|
|
2262
|
+
function resolveRootPathSync(params) {
|
|
2263
|
+
const rootPath = path.resolve(params.rootPath);
|
|
2264
|
+
const absolutePath = path.resolve(params.absolutePath);
|
|
2265
|
+
const rootCanonicalPath = params.rootCanonicalPath
|
|
2266
|
+
? path.resolve(params.rootCanonicalPath)
|
|
2267
|
+
: resolvePathViaExistingAncestorSync(rootPath);
|
|
2268
|
+
const context = createBoundaryResolutionContext({
|
|
2269
|
+
resolveParams: params,
|
|
2270
|
+
rootPath,
|
|
2271
|
+
absolutePath,
|
|
2272
|
+
rootCanonicalPath,
|
|
2273
|
+
outsideLexicalCanonicalPath: resolveOutsideLexicalCanonicalPathSync({
|
|
2274
|
+
rootPath,
|
|
2275
|
+
absolutePath,
|
|
2276
|
+
}),
|
|
2277
|
+
});
|
|
2278
|
+
const outsideResult = resolveOutsideRootPathSync({
|
|
2279
|
+
boundaryLabel: params.boundaryLabel,
|
|
2280
|
+
context,
|
|
2281
|
+
});
|
|
2282
|
+
if (outsideResult) {
|
|
2283
|
+
return outsideResult;
|
|
2284
|
+
}
|
|
2285
|
+
return resolveRootPathLexicalSync({
|
|
2286
|
+
params,
|
|
2287
|
+
absolutePath: context.absolutePath,
|
|
2288
|
+
rootPath: context.rootPath,
|
|
2289
|
+
rootCanonicalPath: context.rootCanonicalPath,
|
|
2290
|
+
});
|
|
2291
|
+
}
|
|
2292
|
+
function isPromiseLike(value) {
|
|
2293
|
+
return Boolean(value &&
|
|
2294
|
+
(typeof value === "object" || typeof value === "function") &&
|
|
2295
|
+
"then" in value &&
|
|
2296
|
+
typeof value.then === "function");
|
|
2297
|
+
}
|
|
2298
|
+
function createLexicalTraversalState(params) {
|
|
2299
|
+
const relative = external_node_path_.relative(params.rootPath, params.absolutePath);
|
|
2300
|
+
return {
|
|
2301
|
+
segments: relative.split(external_node_path_.sep).filter(Boolean),
|
|
2302
|
+
allowFinalSymlink: params.params.policy?.allowFinalSymlinkForUnlink === true,
|
|
2303
|
+
canonicalCursor: params.rootCanonicalPath,
|
|
2304
|
+
lexicalCursor: params.rootPath,
|
|
2305
|
+
preserveFinalSymlink: false,
|
|
2306
|
+
};
|
|
2307
|
+
}
|
|
2308
|
+
function assertLexicalCursorInsideBoundary(params) {
|
|
2309
|
+
assertInsideBoundary({
|
|
2310
|
+
boundaryLabel: params.params.boundaryLabel,
|
|
2311
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2312
|
+
candidatePath: params.candidatePath,
|
|
2313
|
+
absolutePath: params.absolutePath,
|
|
2314
|
+
});
|
|
2315
|
+
}
|
|
2316
|
+
function applyMissingSuffixToCanonicalCursor(params) {
|
|
2317
|
+
const missingSuffix = params.state.segments.slice(params.missingFromIndex);
|
|
2318
|
+
params.state.canonicalCursor = external_node_path_.resolve(params.state.canonicalCursor, ...missingSuffix);
|
|
2319
|
+
assertLexicalCursorInsideBoundary({
|
|
2320
|
+
params: params.params,
|
|
2321
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2322
|
+
candidatePath: params.state.canonicalCursor,
|
|
2323
|
+
absolutePath: params.absolutePath,
|
|
2324
|
+
});
|
|
2325
|
+
}
|
|
2326
|
+
function advanceCanonicalCursorForSegment(params) {
|
|
2327
|
+
params.state.canonicalCursor = external_node_path_.resolve(params.state.canonicalCursor, params.segment);
|
|
2328
|
+
assertLexicalCursorInsideBoundary({
|
|
2329
|
+
params: params.params,
|
|
2330
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2331
|
+
candidatePath: params.state.canonicalCursor,
|
|
2332
|
+
absolutePath: params.absolutePath,
|
|
2333
|
+
});
|
|
2334
|
+
}
|
|
2335
|
+
function finalizeLexicalResolution(params) {
|
|
2336
|
+
assertLexicalCursorInsideBoundary({
|
|
2337
|
+
params: params.params,
|
|
2338
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2339
|
+
candidatePath: params.state.canonicalCursor,
|
|
2340
|
+
absolutePath: params.absolutePath,
|
|
2341
|
+
});
|
|
2342
|
+
return buildResolvedRootPath({
|
|
2343
|
+
absolutePath: params.absolutePath,
|
|
2344
|
+
canonicalPath: params.state.canonicalCursor,
|
|
2345
|
+
rootPath: params.rootPath,
|
|
2346
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2347
|
+
kind: params.kind,
|
|
2348
|
+
});
|
|
2349
|
+
}
|
|
2350
|
+
function handleLexicalLstatFailure(params) {
|
|
2351
|
+
if (!path_isNotFoundPathError(params.error)) {
|
|
2352
|
+
return false;
|
|
2353
|
+
}
|
|
2354
|
+
applyMissingSuffixToCanonicalCursor({
|
|
2355
|
+
state: params.state,
|
|
2356
|
+
missingFromIndex: params.missingFromIndex,
|
|
2357
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2358
|
+
params: params.resolveParams,
|
|
2359
|
+
absolutePath: params.absolutePath,
|
|
2360
|
+
});
|
|
2361
|
+
return true;
|
|
2362
|
+
}
|
|
2363
|
+
function handleLexicalStatReadFailure(params) {
|
|
2364
|
+
if (handleLexicalLstatFailure({
|
|
2365
|
+
error: params.error,
|
|
2366
|
+
state: params.state,
|
|
2367
|
+
missingFromIndex: params.missingFromIndex,
|
|
2368
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2369
|
+
resolveParams: params.resolveParams,
|
|
2370
|
+
absolutePath: params.absolutePath,
|
|
2371
|
+
})) {
|
|
2372
|
+
return null;
|
|
2373
|
+
}
|
|
2374
|
+
throw params.error;
|
|
2375
|
+
}
|
|
2376
|
+
function handleLexicalStatDisposition(params) {
|
|
2377
|
+
if (!params.isSymbolicLink) {
|
|
2378
|
+
advanceCanonicalCursorForSegment({
|
|
2379
|
+
state: params.state,
|
|
2380
|
+
segment: params.segment,
|
|
2381
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2382
|
+
params: params.resolveParams,
|
|
2383
|
+
absolutePath: params.absolutePath,
|
|
2384
|
+
});
|
|
2385
|
+
return "continue";
|
|
2386
|
+
}
|
|
2387
|
+
if (params.state.allowFinalSymlink && params.isLast) {
|
|
2388
|
+
params.state.preserveFinalSymlink = true;
|
|
2389
|
+
advanceCanonicalCursorForSegment({
|
|
2390
|
+
state: params.state,
|
|
2391
|
+
segment: params.segment,
|
|
2392
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2393
|
+
params: params.resolveParams,
|
|
2394
|
+
absolutePath: params.absolutePath,
|
|
2395
|
+
});
|
|
2396
|
+
return "break";
|
|
2397
|
+
}
|
|
2398
|
+
return "resolve-link";
|
|
2399
|
+
}
|
|
2400
|
+
function applyResolvedSymlinkHop(params) {
|
|
2401
|
+
if (!path_isPathInside(params.rootCanonicalPath, params.linkCanonical)) {
|
|
2402
|
+
throw symlinkEscapeError({
|
|
2403
|
+
boundaryLabel: params.boundaryLabel,
|
|
2404
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2405
|
+
symlinkPath: params.state.lexicalCursor,
|
|
2406
|
+
});
|
|
2407
|
+
}
|
|
2408
|
+
params.state.canonicalCursor = params.linkCanonical;
|
|
2409
|
+
params.state.lexicalCursor = params.linkCanonical;
|
|
2410
|
+
}
|
|
2411
|
+
function readLexicalStat(params) {
|
|
2412
|
+
try {
|
|
2413
|
+
const stat = params.read(params.state.lexicalCursor);
|
|
2414
|
+
if (isPromiseLike(stat)) {
|
|
2415
|
+
return Promise.resolve(stat).catch((error) => handleLexicalStatReadFailure({ ...params, error }));
|
|
2416
|
+
}
|
|
2417
|
+
return stat;
|
|
2418
|
+
}
|
|
2419
|
+
catch (error) {
|
|
2420
|
+
return handleLexicalStatReadFailure({ ...params, error });
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
function resolveAndApplySymlinkHop(params) {
|
|
2424
|
+
const linkCanonical = params.resolveLinkCanonical(params.state.lexicalCursor);
|
|
2425
|
+
if (isPromiseLike(linkCanonical)) {
|
|
2426
|
+
return Promise.resolve(linkCanonical).then((value) => applyResolvedSymlinkHop({
|
|
2427
|
+
state: params.state,
|
|
2428
|
+
linkCanonical: value,
|
|
2429
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2430
|
+
boundaryLabel: params.boundaryLabel,
|
|
2431
|
+
}));
|
|
2432
|
+
}
|
|
2433
|
+
applyResolvedSymlinkHop({
|
|
2434
|
+
state: params.state,
|
|
2435
|
+
linkCanonical,
|
|
2436
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2437
|
+
boundaryLabel: params.boundaryLabel,
|
|
2438
|
+
});
|
|
2439
|
+
}
|
|
2440
|
+
function* iterateLexicalTraversal(state) {
|
|
2441
|
+
for (let idx = 0; idx < state.segments.length; idx += 1) {
|
|
2442
|
+
const segment = state.segments[idx] ?? "";
|
|
2443
|
+
const isLast = idx === state.segments.length - 1;
|
|
2444
|
+
state.lexicalCursor = external_node_path_.join(state.lexicalCursor, segment);
|
|
2445
|
+
yield { idx, segment, isLast };
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
async function resolveRootPathLexicalAsync(params) {
|
|
2449
|
+
const state = createLexicalTraversalState(params);
|
|
2450
|
+
const sharedStepParams = {
|
|
2451
|
+
state,
|
|
2452
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2453
|
+
resolveParams: params.params,
|
|
2454
|
+
absolutePath: params.absolutePath,
|
|
2455
|
+
};
|
|
2456
|
+
for (const { idx, segment, isLast } of iterateLexicalTraversal(state)) {
|
|
2457
|
+
const stat = await readLexicalStat({
|
|
2458
|
+
...sharedStepParams,
|
|
2459
|
+
missingFromIndex: idx,
|
|
2460
|
+
read: (cursor) => promises_.lstat(cursor),
|
|
2461
|
+
});
|
|
2462
|
+
if (!stat) {
|
|
2463
|
+
break;
|
|
2464
|
+
}
|
|
2465
|
+
const disposition = handleLexicalStatDisposition({
|
|
2466
|
+
...sharedStepParams,
|
|
2467
|
+
isSymbolicLink: stat.isSymbolicLink(),
|
|
2468
|
+
segment,
|
|
2469
|
+
isLast,
|
|
2470
|
+
});
|
|
2471
|
+
if (disposition === "continue") {
|
|
2472
|
+
continue;
|
|
2473
|
+
}
|
|
2474
|
+
if (disposition === "break") {
|
|
2475
|
+
break;
|
|
2476
|
+
}
|
|
2477
|
+
await resolveAndApplySymlinkHop({
|
|
2478
|
+
state,
|
|
2479
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2480
|
+
boundaryLabel: params.params.boundaryLabel,
|
|
2481
|
+
resolveLinkCanonical: (cursor) => resolveSymlinkHopPath(cursor),
|
|
2482
|
+
});
|
|
2483
|
+
}
|
|
2484
|
+
const kind = await getPathKind(params.absolutePath, state.preserveFinalSymlink);
|
|
2485
|
+
return finalizeLexicalResolution({
|
|
2486
|
+
...params,
|
|
2487
|
+
state,
|
|
2488
|
+
kind,
|
|
2489
|
+
});
|
|
2490
|
+
}
|
|
2491
|
+
function resolveRootPathLexicalSync(params) {
|
|
2492
|
+
const state = createLexicalTraversalState(params);
|
|
2493
|
+
for (let idx = 0; idx < state.segments.length; idx += 1) {
|
|
2494
|
+
const segment = state.segments[idx] ?? "";
|
|
2495
|
+
const isLast = idx === state.segments.length - 1;
|
|
2496
|
+
state.lexicalCursor = path.join(state.lexicalCursor, segment);
|
|
2497
|
+
const maybeStat = readLexicalStat({
|
|
2498
|
+
state,
|
|
2499
|
+
missingFromIndex: idx,
|
|
2500
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2501
|
+
resolveParams: params.params,
|
|
2502
|
+
absolutePath: params.absolutePath,
|
|
2503
|
+
read: (cursor) => fs.lstatSync(cursor),
|
|
2504
|
+
});
|
|
2505
|
+
if (isPromiseLike(maybeStat)) {
|
|
2506
|
+
throw new Error("Unexpected async lexical stat");
|
|
2507
|
+
}
|
|
2508
|
+
const stat = maybeStat;
|
|
2509
|
+
if (!stat) {
|
|
2510
|
+
break;
|
|
2511
|
+
}
|
|
2512
|
+
const disposition = handleLexicalStatDisposition({
|
|
2513
|
+
state,
|
|
2514
|
+
isSymbolicLink: stat.isSymbolicLink(),
|
|
2515
|
+
segment,
|
|
2516
|
+
isLast,
|
|
2517
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2518
|
+
resolveParams: params.params,
|
|
2519
|
+
absolutePath: params.absolutePath,
|
|
2520
|
+
});
|
|
2521
|
+
if (disposition === "continue") {
|
|
2522
|
+
continue;
|
|
2523
|
+
}
|
|
2524
|
+
if (disposition === "break") {
|
|
2525
|
+
break;
|
|
2526
|
+
}
|
|
2527
|
+
const maybeApplied = resolveAndApplySymlinkHop({
|
|
2528
|
+
state,
|
|
2529
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2530
|
+
boundaryLabel: params.params.boundaryLabel,
|
|
2531
|
+
resolveLinkCanonical: (cursor) => resolveSymlinkHopPathSync(cursor),
|
|
2532
|
+
});
|
|
2533
|
+
if (isPromiseLike(maybeApplied)) {
|
|
2534
|
+
throw new Error("Unexpected async symlink resolution");
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
const kind = getPathKindSync(params.absolutePath, state.preserveFinalSymlink);
|
|
2538
|
+
return finalizeLexicalResolution({
|
|
2539
|
+
...params,
|
|
2540
|
+
state,
|
|
2541
|
+
kind,
|
|
2542
|
+
});
|
|
2543
|
+
}
|
|
2544
|
+
function resolveCanonicalOutsideLexicalPath(params) {
|
|
2545
|
+
return params.outsideLexicalCanonicalPath ?? params.absolutePath;
|
|
2546
|
+
}
|
|
2547
|
+
function createBoundaryResolutionContext(params) {
|
|
2548
|
+
const lexicalInside = path_isPathInside(params.rootPath, params.absolutePath);
|
|
2549
|
+
const canonicalOutsideLexicalPath = resolveCanonicalOutsideLexicalPath({
|
|
2550
|
+
absolutePath: params.absolutePath,
|
|
2551
|
+
outsideLexicalCanonicalPath: params.outsideLexicalCanonicalPath,
|
|
2552
|
+
});
|
|
2553
|
+
assertLexicalBoundaryOrCanonicalAlias({
|
|
2554
|
+
skipLexicalRootCheck: params.resolveParams.skipLexicalRootCheck,
|
|
2555
|
+
lexicalInside,
|
|
2556
|
+
canonicalOutsideLexicalPath,
|
|
2557
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2558
|
+
boundaryLabel: params.resolveParams.boundaryLabel,
|
|
2559
|
+
rootPath: params.rootPath,
|
|
2560
|
+
absolutePath: params.absolutePath,
|
|
2561
|
+
});
|
|
2562
|
+
return {
|
|
2563
|
+
rootPath: params.rootPath,
|
|
2564
|
+
absolutePath: params.absolutePath,
|
|
2565
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2566
|
+
lexicalInside,
|
|
2567
|
+
canonicalOutsideLexicalPath,
|
|
2568
|
+
};
|
|
2569
|
+
}
|
|
2570
|
+
async function resolveOutsideRootPathAsync(params) {
|
|
2571
|
+
if (params.context.lexicalInside) {
|
|
2572
|
+
return null;
|
|
2573
|
+
}
|
|
2574
|
+
const kind = await getPathKind(params.context.absolutePath, false);
|
|
2575
|
+
return buildOutsideRootPathFromContext({
|
|
2576
|
+
boundaryLabel: params.boundaryLabel,
|
|
2577
|
+
context: params.context,
|
|
2578
|
+
kind,
|
|
2579
|
+
});
|
|
2580
|
+
}
|
|
2581
|
+
function resolveOutsideRootPathSync(params) {
|
|
2582
|
+
if (params.context.lexicalInside) {
|
|
2583
|
+
return null;
|
|
2584
|
+
}
|
|
2585
|
+
const kind = getPathKindSync(params.context.absolutePath, false);
|
|
2586
|
+
return buildOutsideRootPathFromContext({
|
|
2587
|
+
boundaryLabel: params.boundaryLabel,
|
|
2588
|
+
context: params.context,
|
|
2589
|
+
kind,
|
|
2590
|
+
});
|
|
2591
|
+
}
|
|
2592
|
+
function buildOutsideRootPathFromContext(params) {
|
|
2593
|
+
return buildOutsideLexicalRootPath({
|
|
2594
|
+
boundaryLabel: params.boundaryLabel,
|
|
2595
|
+
rootCanonicalPath: params.context.rootCanonicalPath,
|
|
2596
|
+
absolutePath: params.context.absolutePath,
|
|
2597
|
+
canonicalOutsideLexicalPath: params.context.canonicalOutsideLexicalPath,
|
|
2598
|
+
rootPath: params.context.rootPath,
|
|
2599
|
+
kind: params.kind,
|
|
2600
|
+
});
|
|
2601
|
+
}
|
|
2602
|
+
async function resolveOutsideLexicalCanonicalPathAsync(params) {
|
|
2603
|
+
if (path_isPathInside(params.rootPath, params.absolutePath)) {
|
|
2604
|
+
return undefined;
|
|
2605
|
+
}
|
|
2606
|
+
return await resolvePathViaExistingAncestor(params.absolutePath);
|
|
2607
|
+
}
|
|
2608
|
+
function resolveOutsideLexicalCanonicalPathSync(params) {
|
|
2609
|
+
if (isPathInside(params.rootPath, params.absolutePath)) {
|
|
2610
|
+
return undefined;
|
|
2611
|
+
}
|
|
2612
|
+
return resolvePathViaExistingAncestorSync(params.absolutePath);
|
|
2613
|
+
}
|
|
2614
|
+
function buildOutsideLexicalRootPath(params) {
|
|
2615
|
+
assertInsideBoundary({
|
|
2616
|
+
boundaryLabel: params.boundaryLabel,
|
|
2617
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2618
|
+
candidatePath: params.canonicalOutsideLexicalPath,
|
|
2619
|
+
absolutePath: params.absolutePath,
|
|
2620
|
+
});
|
|
2621
|
+
return buildResolvedRootPath({
|
|
2622
|
+
absolutePath: params.absolutePath,
|
|
2623
|
+
canonicalPath: params.canonicalOutsideLexicalPath,
|
|
2624
|
+
rootPath: params.rootPath,
|
|
2625
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2626
|
+
kind: params.kind,
|
|
2627
|
+
});
|
|
2628
|
+
}
|
|
2629
|
+
function assertLexicalBoundaryOrCanonicalAlias(params) {
|
|
2630
|
+
if (params.skipLexicalRootCheck || params.lexicalInside) {
|
|
2631
|
+
return;
|
|
2632
|
+
}
|
|
2633
|
+
if (path_isPathInside(params.rootCanonicalPath, params.canonicalOutsideLexicalPath)) {
|
|
2634
|
+
return;
|
|
2635
|
+
}
|
|
2636
|
+
throw pathEscapeError({
|
|
2637
|
+
boundaryLabel: params.boundaryLabel,
|
|
2638
|
+
rootPath: params.rootPath,
|
|
2639
|
+
absolutePath: params.absolutePath,
|
|
2640
|
+
});
|
|
2641
|
+
}
|
|
2642
|
+
function buildResolvedRootPath(params) {
|
|
2643
|
+
return {
|
|
2644
|
+
absolutePath: params.absolutePath,
|
|
2645
|
+
canonicalPath: params.canonicalPath,
|
|
2646
|
+
rootPath: params.rootPath,
|
|
2647
|
+
rootCanonicalPath: params.rootCanonicalPath,
|
|
2648
|
+
relativePath: relativeInsideRoot(params.rootCanonicalPath, params.canonicalPath),
|
|
2649
|
+
exists: params.kind.exists,
|
|
2650
|
+
kind: params.kind.kind,
|
|
2651
|
+
};
|
|
2652
|
+
}
|
|
2653
|
+
async function resolvePathViaExistingAncestor(targetPath) {
|
|
2654
|
+
const normalized = external_node_path_.resolve(targetPath);
|
|
2655
|
+
let cursor = normalized;
|
|
2656
|
+
const missingSuffix = [];
|
|
2657
|
+
while (!isFilesystemRoot(cursor) && !(await pathExists(cursor))) {
|
|
2658
|
+
missingSuffix.unshift(external_node_path_.basename(cursor));
|
|
2659
|
+
const parent = external_node_path_.dirname(cursor);
|
|
2660
|
+
if (parent === cursor) {
|
|
2661
|
+
break;
|
|
2662
|
+
}
|
|
2663
|
+
cursor = parent;
|
|
2664
|
+
}
|
|
2665
|
+
if (!(await pathExists(cursor))) {
|
|
2666
|
+
return normalized;
|
|
2667
|
+
}
|
|
2668
|
+
try {
|
|
2669
|
+
const resolvedAncestor = external_node_path_.resolve(await promises_.realpath(cursor));
|
|
2670
|
+
if (missingSuffix.length === 0) {
|
|
2671
|
+
return resolvedAncestor;
|
|
2672
|
+
}
|
|
2673
|
+
return external_node_path_.resolve(resolvedAncestor, ...missingSuffix);
|
|
2674
|
+
}
|
|
2675
|
+
catch {
|
|
2676
|
+
return normalized;
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
function resolvePathViaExistingAncestorSync(targetPath) {
|
|
2680
|
+
const normalized = path.resolve(targetPath);
|
|
2681
|
+
let cursor = normalized;
|
|
2682
|
+
const missingSuffix = [];
|
|
2683
|
+
while (!isFilesystemRoot(cursor) && !fs.existsSync(cursor)) {
|
|
2684
|
+
missingSuffix.unshift(path.basename(cursor));
|
|
2685
|
+
const parent = path.dirname(cursor);
|
|
2686
|
+
if (parent === cursor) {
|
|
2687
|
+
break;
|
|
2688
|
+
}
|
|
2689
|
+
cursor = parent;
|
|
2690
|
+
}
|
|
2691
|
+
if (!fs.existsSync(cursor)) {
|
|
2692
|
+
return normalized;
|
|
2693
|
+
}
|
|
2694
|
+
try {
|
|
2695
|
+
// Keep sync behavior aligned with async (`fsp.realpath`) to avoid
|
|
2696
|
+
// platform-specific canonical alias drift (notably on Windows).
|
|
2697
|
+
const resolvedAncestor = path.resolve(fs.realpathSync(cursor));
|
|
2698
|
+
if (missingSuffix.length === 0) {
|
|
2699
|
+
return resolvedAncestor;
|
|
2700
|
+
}
|
|
2701
|
+
return path.resolve(resolvedAncestor, ...missingSuffix);
|
|
2702
|
+
}
|
|
2703
|
+
catch {
|
|
2704
|
+
return normalized;
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
async function getPathKind(absolutePath, preserveFinalSymlink) {
|
|
2708
|
+
try {
|
|
2709
|
+
const stat = preserveFinalSymlink
|
|
2710
|
+
? await promises_.lstat(absolutePath)
|
|
2711
|
+
: await promises_.stat(absolutePath);
|
|
2712
|
+
return { exists: true, kind: toResolvedKind(stat) };
|
|
2713
|
+
}
|
|
2714
|
+
catch (error) {
|
|
2715
|
+
if (path_isNotFoundPathError(error)) {
|
|
2716
|
+
return { exists: false, kind: "missing" };
|
|
2717
|
+
}
|
|
2718
|
+
throw error;
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
function getPathKindSync(absolutePath, preserveFinalSymlink) {
|
|
2722
|
+
try {
|
|
2723
|
+
const stat = preserveFinalSymlink ? fs.lstatSync(absolutePath) : fs.statSync(absolutePath);
|
|
2724
|
+
return { exists: true, kind: toResolvedKind(stat) };
|
|
2725
|
+
}
|
|
2726
|
+
catch (error) {
|
|
2727
|
+
if (isNotFoundPathError(error)) {
|
|
2728
|
+
return { exists: false, kind: "missing" };
|
|
2729
|
+
}
|
|
2730
|
+
throw error;
|
|
2731
|
+
}
|
|
2732
|
+
}
|
|
2733
|
+
function toResolvedKind(stat) {
|
|
2734
|
+
if (stat.isFile()) {
|
|
2735
|
+
return "file";
|
|
2736
|
+
}
|
|
2737
|
+
if (stat.isDirectory()) {
|
|
2738
|
+
return "directory";
|
|
2739
|
+
}
|
|
2740
|
+
if (stat.isSymbolicLink()) {
|
|
2741
|
+
return "symlink";
|
|
2742
|
+
}
|
|
2743
|
+
return "other";
|
|
2744
|
+
}
|
|
2745
|
+
function relativeInsideRoot(rootPath, targetPath) {
|
|
2746
|
+
const relative = external_node_path_.relative(external_node_path_.resolve(rootPath), external_node_path_.resolve(targetPath));
|
|
2747
|
+
if (!relative || relative === ".") {
|
|
2748
|
+
return "";
|
|
2749
|
+
}
|
|
2750
|
+
if (relative.startsWith("..") || external_node_path_.isAbsolute(relative)) {
|
|
2751
|
+
return "";
|
|
2752
|
+
}
|
|
2753
|
+
return relative;
|
|
2754
|
+
}
|
|
2755
|
+
function assertInsideBoundary(params) {
|
|
2756
|
+
if (path_isPathInside(params.rootCanonicalPath, params.candidatePath)) {
|
|
2757
|
+
return;
|
|
2758
|
+
}
|
|
2759
|
+
throw new Error(`Path resolves outside ${params.boundaryLabel} (${shortPath(params.rootCanonicalPath)}): ${shortPath(params.absolutePath)}`);
|
|
2760
|
+
}
|
|
2761
|
+
function pathEscapeError(params) {
|
|
2762
|
+
return new Error(`Path escapes ${params.boundaryLabel} (${shortPath(params.rootPath)}): ${shortPath(params.absolutePath)}`);
|
|
2763
|
+
}
|
|
2764
|
+
function symlinkEscapeError(params) {
|
|
2765
|
+
return new Error(`Symlink escapes ${params.boundaryLabel} (${shortPath(params.rootCanonicalPath)}): ${shortPath(params.symlinkPath)}`);
|
|
2766
|
+
}
|
|
2767
|
+
function shortPath(value) {
|
|
2768
|
+
const home = external_node_os_.homedir();
|
|
2769
|
+
if (value.startsWith(home)) {
|
|
2770
|
+
return `~${value.slice(home.length)}`;
|
|
2771
|
+
}
|
|
2772
|
+
return value;
|
|
2773
|
+
}
|
|
2774
|
+
function isFilesystemRoot(candidate) {
|
|
2775
|
+
return external_node_path_.parse(candidate).root === candidate;
|
|
2776
|
+
}
|
|
2777
|
+
async function pathExists(targetPath) {
|
|
2778
|
+
try {
|
|
2779
|
+
await promises_.lstat(targetPath);
|
|
2780
|
+
return true;
|
|
2781
|
+
}
|
|
2782
|
+
catch (error) {
|
|
2783
|
+
if (path_isNotFoundPathError(error)) {
|
|
2784
|
+
return false;
|
|
2785
|
+
}
|
|
2786
|
+
throw error;
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
async function resolveSymlinkHopPath(symlinkPath) {
|
|
2790
|
+
try {
|
|
2791
|
+
return external_node_path_.resolve(await promises_.realpath(symlinkPath));
|
|
2792
|
+
}
|
|
2793
|
+
catch (error) {
|
|
2794
|
+
if (!path_isNotFoundPathError(error)) {
|
|
2795
|
+
throw error;
|
|
2796
|
+
}
|
|
2797
|
+
const linkTarget = await promises_.readlink(symlinkPath);
|
|
2798
|
+
const linkAbsolute = external_node_path_.resolve(external_node_path_.dirname(symlinkPath), linkTarget);
|
|
2799
|
+
return resolvePathViaExistingAncestor(linkAbsolute);
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
function resolveSymlinkHopPathSync(symlinkPath) {
|
|
2803
|
+
try {
|
|
2804
|
+
return path.resolve(fs.realpathSync(symlinkPath));
|
|
2805
|
+
}
|
|
2806
|
+
catch (error) {
|
|
2807
|
+
if (!isNotFoundPathError(error)) {
|
|
2808
|
+
throw error;
|
|
2809
|
+
}
|
|
2810
|
+
const linkTarget = fs.readlinkSync(symlinkPath);
|
|
2811
|
+
const linkAbsolute = path.resolve(path.dirname(symlinkPath), linkTarget);
|
|
2812
|
+
return resolvePathViaExistingAncestorSync(linkAbsolute);
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/path-policy.js
|
|
2817
|
+
|
|
2818
|
+
|
|
2819
|
+
|
|
2820
|
+
|
|
2821
|
+
const PATH_ALIAS_POLICIES = ROOT_PATH_ALIAS_POLICIES;
|
|
2822
|
+
async function assertNoPathAliasEscape(params) {
|
|
2823
|
+
const resolved = await resolveRootPath({
|
|
2824
|
+
absolutePath: params.absolutePath,
|
|
2825
|
+
rootPath: params.rootPath,
|
|
2826
|
+
boundaryLabel: params.boundaryLabel,
|
|
2827
|
+
policy: params.policy,
|
|
2828
|
+
});
|
|
2829
|
+
const allowFinalSymlink = params.policy?.allowFinalSymlinkForUnlink === true;
|
|
2830
|
+
if (allowFinalSymlink && resolved.kind === "symlink") {
|
|
2831
|
+
return;
|
|
2832
|
+
}
|
|
2833
|
+
await assertNoHardlinkedFinalPath({
|
|
2834
|
+
filePath: resolved.absolutePath,
|
|
2835
|
+
root: resolved.rootPath,
|
|
2836
|
+
boundaryLabel: params.boundaryLabel,
|
|
2837
|
+
allowFinalHardlinkForUnlink: params.policy?.allowFinalHardlinkForUnlink,
|
|
2838
|
+
});
|
|
2839
|
+
}
|
|
2840
|
+
async function assertNoHardlinkedFinalPath(params) {
|
|
2841
|
+
if (params.allowFinalHardlinkForUnlink) {
|
|
2842
|
+
return;
|
|
2843
|
+
}
|
|
2844
|
+
let stat;
|
|
2845
|
+
try {
|
|
2846
|
+
stat = await promises_.stat(params.filePath);
|
|
2847
|
+
}
|
|
2848
|
+
catch (err) {
|
|
2849
|
+
if (path_isNotFoundPathError(err)) {
|
|
2850
|
+
return;
|
|
2851
|
+
}
|
|
2852
|
+
throw err;
|
|
2853
|
+
}
|
|
2854
|
+
if (!stat.isFile()) {
|
|
2855
|
+
return;
|
|
2856
|
+
}
|
|
2857
|
+
if (stat.nlink > 1) {
|
|
2858
|
+
throw new Error(`Hardlinked path is not allowed under ${params.boundaryLabel} (${path_policy_shortPath(params.root)}): ${path_policy_shortPath(params.filePath)}`);
|
|
2859
|
+
}
|
|
2860
|
+
}
|
|
2861
|
+
function path_policy_shortPath(value) {
|
|
2862
|
+
if (value.startsWith(external_node_os_.homedir())) {
|
|
2863
|
+
return `~${value.slice(external_node_os_.homedir().length)}`;
|
|
2864
|
+
}
|
|
2865
|
+
return value;
|
|
2866
|
+
}
|
|
2867
|
+
|
|
2868
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/path-stat.js
|
|
2869
|
+
function pathStatFromStats(stat) {
|
|
2870
|
+
return {
|
|
2871
|
+
dev: Number(stat.dev),
|
|
2872
|
+
gid: Number(stat.gid),
|
|
2873
|
+
ino: Number(stat.ino),
|
|
2874
|
+
isDirectory: stat.isDirectory(),
|
|
2875
|
+
isFile: stat.isFile(),
|
|
2876
|
+
isSymbolicLink: stat.isSymbolicLink(),
|
|
2877
|
+
mode: stat.mode,
|
|
2878
|
+
mtimeMs: stat.mtimeMs,
|
|
2879
|
+
nlink: stat.nlink,
|
|
2880
|
+
size: stat.size,
|
|
2881
|
+
uid: stat.uid,
|
|
2882
|
+
};
|
|
2883
|
+
}
|
|
2884
|
+
|
|
2885
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/home-dir.js
|
|
2886
|
+
|
|
2887
|
+
|
|
2888
|
+
|
|
2889
|
+
function normalize(value) {
|
|
2890
|
+
const trimmed = normalizeOptionalString(value);
|
|
2891
|
+
if (!trimmed) {
|
|
2892
|
+
return undefined;
|
|
2893
|
+
}
|
|
2894
|
+
if (trimmed === "undefined" || trimmed === "null") {
|
|
2895
|
+
return undefined;
|
|
2896
|
+
}
|
|
2897
|
+
return trimmed;
|
|
2898
|
+
}
|
|
2899
|
+
function resolveEffectiveHomeDir(env = process.env, homedir = external_node_os_.homedir) {
|
|
2900
|
+
const raw = resolveRawHomeDir(env, homedir);
|
|
2901
|
+
return raw ? external_node_path_.resolve(raw) : undefined;
|
|
2902
|
+
}
|
|
2903
|
+
function resolveOsHomeDir(env = process.env, homedir = os.homedir) {
|
|
2904
|
+
const raw = resolveRawOsHomeDir(env, homedir);
|
|
2905
|
+
return raw ? path.resolve(raw) : undefined;
|
|
2906
|
+
}
|
|
2907
|
+
function resolveRawHomeDir(env, homedir) {
|
|
2908
|
+
const explicitHome = normalize(env.OPENCLAW_HOME);
|
|
2909
|
+
if (!explicitHome) {
|
|
2910
|
+
return resolveRawOsHomeDir(env, homedir);
|
|
2911
|
+
}
|
|
2912
|
+
const segments = external_node_path_.normalize(explicitHome).split(external_node_path_.sep);
|
|
2913
|
+
if (segments[0] !== "~") {
|
|
2914
|
+
return explicitHome;
|
|
2915
|
+
}
|
|
2916
|
+
// OPENCLAW_HOME starts with "~"; expand against the os home dir. Fall
|
|
2917
|
+
// back to undefined when there is no os home to expand against rather
|
|
2918
|
+
// than returning a raw "~"-prefixed path the caller cannot use.
|
|
2919
|
+
const fallbackHome = resolveRawOsHomeDir(env, homedir);
|
|
2920
|
+
if (!fallbackHome) {
|
|
2921
|
+
return undefined;
|
|
2922
|
+
}
|
|
2923
|
+
return expandHomePrefix(explicitHome, { home: fallbackHome });
|
|
2924
|
+
}
|
|
2925
|
+
function resolveRawOsHomeDir(env, homedir) {
|
|
2926
|
+
const envHome = normalize(env.HOME);
|
|
2927
|
+
if (envHome) {
|
|
2928
|
+
return envHome;
|
|
2929
|
+
}
|
|
2930
|
+
const userProfile = normalize(env.USERPROFILE);
|
|
2931
|
+
if (userProfile) {
|
|
2932
|
+
return userProfile;
|
|
2933
|
+
}
|
|
2934
|
+
return normalizeSafe(homedir);
|
|
2935
|
+
}
|
|
2936
|
+
function normalizeSafe(homedir) {
|
|
2937
|
+
try {
|
|
2938
|
+
return normalize(homedir());
|
|
2939
|
+
}
|
|
2940
|
+
catch {
|
|
2941
|
+
return undefined;
|
|
2942
|
+
}
|
|
2943
|
+
}
|
|
2944
|
+
function resolveRequiredHomeDir(env = process.env, homedir = os.homedir) {
|
|
2945
|
+
return resolveEffectiveHomeDir(env, homedir) ?? path.resolve(process.cwd());
|
|
2946
|
+
}
|
|
2947
|
+
function resolveRequiredOsHomeDir(env = process.env, homedir = os.homedir) {
|
|
2948
|
+
return resolveOsHomeDir(env, homedir) ?? path.resolve(process.cwd());
|
|
2949
|
+
}
|
|
2950
|
+
function expandHomePrefix(input, opts) {
|
|
2951
|
+
const segments = external_node_path_.normalize(input).split(external_node_path_.sep);
|
|
2952
|
+
if (segments[0] !== "~") {
|
|
2953
|
+
return input;
|
|
2954
|
+
}
|
|
2955
|
+
const home = normalize(opts?.home) ??
|
|
2956
|
+
resolveEffectiveHomeDir(opts?.env ?? process.env, opts?.homedir ?? external_node_os_.homedir);
|
|
2957
|
+
if (!home) {
|
|
2958
|
+
return input;
|
|
2959
|
+
}
|
|
2960
|
+
return external_node_path_.join(home, ...segments.slice(1));
|
|
2961
|
+
}
|
|
2962
|
+
function resolveHomeRelativePath(input, opts) {
|
|
2963
|
+
if (!input) {
|
|
2964
|
+
return input;
|
|
2965
|
+
}
|
|
2966
|
+
const segments = path.normalize(input).split(path.sep);
|
|
2967
|
+
if (segments[0] !== "~") {
|
|
2968
|
+
return path.resolve(input);
|
|
2969
|
+
}
|
|
2970
|
+
const expanded = expandHomePrefix(input, {
|
|
2971
|
+
home: resolveRequiredHomeDir(opts?.env ?? process.env, opts?.homedir ?? os.homedir),
|
|
2972
|
+
env: opts?.env,
|
|
2973
|
+
homedir: opts?.homedir,
|
|
2974
|
+
});
|
|
2975
|
+
return path.resolve(expanded);
|
|
2976
|
+
}
|
|
2977
|
+
function resolveUserPath(input, optsOrEnv, homedir) {
|
|
2978
|
+
const opts = optsOrEnv && ("env" in optsOrEnv || "homedir" in optsOrEnv)
|
|
2979
|
+
? optsOrEnv
|
|
2980
|
+
: { env: optsOrEnv, homedir };
|
|
2981
|
+
return resolveHomeRelativePath(input, opts);
|
|
2982
|
+
}
|
|
2983
|
+
function resolveOsHomeRelativePath(input, opts) {
|
|
2984
|
+
if (!input) {
|
|
2985
|
+
return input;
|
|
2986
|
+
}
|
|
2987
|
+
const segments = path.normalize(input).split(path.sep);
|
|
2988
|
+
if (segments[0] !== "~") {
|
|
2989
|
+
return path.resolve(input);
|
|
2990
|
+
}
|
|
2991
|
+
const expanded = expandHomePrefix(input, {
|
|
2992
|
+
home: resolveRequiredOsHomeDir(opts?.env ?? process.env, opts?.homedir ?? os.homedir),
|
|
2993
|
+
env: opts?.env,
|
|
2994
|
+
homedir: opts?.homedir,
|
|
2995
|
+
});
|
|
2996
|
+
return path.resolve(expanded);
|
|
2997
|
+
}
|
|
2998
|
+
|
|
2999
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-context.js
|
|
3000
|
+
|
|
3001
|
+
|
|
3002
|
+
|
|
3003
|
+
|
|
3004
|
+
|
|
3005
|
+
|
|
3006
|
+
const ensureTrailingSep = (value) => value.endsWith(external_node_path_.sep) ? value : value + external_node_path_.sep;
|
|
3007
|
+
function assertValidRootRelativePath(relativePath) {
|
|
3008
|
+
path_assertNoNulPathInput(relativePath, "relative path contains a NUL byte");
|
|
3009
|
+
}
|
|
3010
|
+
let cachedHomePath;
|
|
3011
|
+
async function expandRelativePathWithHome(relativePath) {
|
|
3012
|
+
const rawHome = process.env.HOME || process.env.USERPROFILE || external_node_os_.homedir();
|
|
3013
|
+
if (cachedHomePath?.raw !== rawHome) {
|
|
3014
|
+
let realHome = rawHome;
|
|
3015
|
+
try {
|
|
3016
|
+
realHome = await promises_.realpath(rawHome);
|
|
3017
|
+
}
|
|
3018
|
+
catch {
|
|
3019
|
+
// If the home dir cannot be canonicalized, keep lexical expansion behavior.
|
|
3020
|
+
}
|
|
3021
|
+
cachedHomePath = { raw: rawHome, real: realHome };
|
|
3022
|
+
}
|
|
3023
|
+
return expandHomePrefix(relativePath, { home: cachedHomePath.real });
|
|
3024
|
+
}
|
|
3025
|
+
async function resolveRootContext(rootDir) {
|
|
3026
|
+
path_assertNoNulPathInput(rootDir, "root dir contains a NUL byte");
|
|
3027
|
+
let rootReal;
|
|
3028
|
+
try {
|
|
3029
|
+
rootReal = await promises_.realpath(rootDir);
|
|
3030
|
+
const rootStat = await promises_.stat(rootReal);
|
|
3031
|
+
if (!rootStat.isDirectory()) {
|
|
3032
|
+
throw new errors_FsSafeError("invalid-path", "root dir is not a directory");
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
catch (err) {
|
|
3036
|
+
if (err instanceof errors_FsSafeError) {
|
|
3037
|
+
throw err;
|
|
3038
|
+
}
|
|
3039
|
+
if (path_isNotFoundPathError(err)) {
|
|
3040
|
+
throw new errors_FsSafeError("not-found", "root dir not found");
|
|
3041
|
+
}
|
|
3042
|
+
throw err;
|
|
3043
|
+
}
|
|
3044
|
+
return {
|
|
3045
|
+
rootDir: external_node_path_.resolve(rootDir),
|
|
3046
|
+
rootReal,
|
|
3047
|
+
rootWithSep: ensureTrailingSep(rootReal),
|
|
3048
|
+
};
|
|
3049
|
+
}
|
|
3050
|
+
async function resolvePathInRoot(root, relativePath) {
|
|
3051
|
+
assertValidRootRelativePath(relativePath);
|
|
3052
|
+
const expanded = await expandRelativePathWithHome(relativePath);
|
|
3053
|
+
const resolved = external_node_path_.resolve(root.rootWithSep, expanded);
|
|
3054
|
+
if (!path_isPathInside(root.rootWithSep, resolved)) {
|
|
3055
|
+
throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
|
|
3056
|
+
}
|
|
3057
|
+
return { rootReal: root.rootReal, rootWithSep: root.rootWithSep, resolved };
|
|
3058
|
+
}
|
|
3059
|
+
async function resolvePathWithinRoot(params) {
|
|
3060
|
+
return await resolvePathInRoot(await resolveRootContext(params.rootDir), params.relativePath);
|
|
3061
|
+
}
|
|
3062
|
+
|
|
3063
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-errors.js
|
|
3064
|
+
|
|
3065
|
+
|
|
3066
|
+
function isAlreadyExistsError(error) {
|
|
3067
|
+
return hasNodeErrorCode(error, "EEXIST") || /File exists|EEXIST/i.test(String(error));
|
|
3068
|
+
}
|
|
3069
|
+
function normalizePinnedWriteError(error) {
|
|
3070
|
+
if (error instanceof errors_FsSafeError) {
|
|
3071
|
+
return error;
|
|
3072
|
+
}
|
|
3073
|
+
return new errors_FsSafeError("invalid-path", "path is not a regular file under root", {
|
|
3074
|
+
cause: error instanceof Error ? error : undefined,
|
|
3075
|
+
});
|
|
3076
|
+
}
|
|
3077
|
+
function normalizePinnedPathError(error) {
|
|
3078
|
+
if (error instanceof errors_FsSafeError) {
|
|
3079
|
+
return error;
|
|
3080
|
+
}
|
|
3081
|
+
return new errors_FsSafeError("path-alias", "path is not under root", {
|
|
3082
|
+
cause: error instanceof Error ? error : undefined,
|
|
3083
|
+
});
|
|
3084
|
+
}
|
|
3085
|
+
|
|
3086
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/test-hooks.js
|
|
3087
|
+
let test_hooks_fsSafeTestHooks;
|
|
3088
|
+
function allowFsSafeTestHooks() {
|
|
3089
|
+
return false || process.env.VITEST === "true";
|
|
3090
|
+
}
|
|
3091
|
+
function getFsSafeTestHooks() {
|
|
3092
|
+
return test_hooks_fsSafeTestHooks;
|
|
3093
|
+
}
|
|
3094
|
+
function __setFsSafeTestHooksForTest(hooks) {
|
|
3095
|
+
if (hooks && !allowFsSafeTestHooks()) {
|
|
3096
|
+
throw new Error("__setFsSafeTestHooksForTest is only available in tests");
|
|
3097
|
+
}
|
|
3098
|
+
test_hooks_fsSafeTestHooks = hooks;
|
|
3099
|
+
}
|
|
3100
|
+
|
|
3101
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/temp-cleanup.js
|
|
3102
|
+
|
|
3103
|
+
const tempCleanupEntries = new Map();
|
|
3104
|
+
let cleanupRegistered = false;
|
|
3105
|
+
function cleanupRegisteredTempPathsSync() {
|
|
3106
|
+
for (const entry of tempCleanupEntries.values()) {
|
|
3107
|
+
try {
|
|
3108
|
+
external_node_fs_.rmSync(entry.path, { force: true, recursive: entry.recursive });
|
|
3109
|
+
}
|
|
3110
|
+
catch {
|
|
3111
|
+
// Process-exit cleanup is best-effort.
|
|
3112
|
+
}
|
|
3113
|
+
}
|
|
3114
|
+
tempCleanupEntries.clear();
|
|
3115
|
+
}
|
|
3116
|
+
function registerTempPathForExit(tempPath, options) {
|
|
3117
|
+
if (!cleanupRegistered) {
|
|
3118
|
+
cleanupRegistered = true;
|
|
3119
|
+
process.once("exit", cleanupRegisteredTempPathsSync);
|
|
3120
|
+
}
|
|
3121
|
+
tempCleanupEntries.set(tempPath, {
|
|
3122
|
+
path: tempPath,
|
|
3123
|
+
recursive: options?.recursive === true,
|
|
3124
|
+
});
|
|
3125
|
+
return () => {
|
|
3126
|
+
tempCleanupEntries.delete(tempPath);
|
|
3127
|
+
};
|
|
3128
|
+
}
|
|
3129
|
+
function __cleanupRegisteredTempPathsForTest() {
|
|
3130
|
+
cleanupRegisteredTempPathsSync();
|
|
3131
|
+
}
|
|
3132
|
+
function __cleanupRegisteredTempPathForTest(tempPath) {
|
|
3133
|
+
const entry = tempCleanupEntries.get(tempPath);
|
|
3134
|
+
if (!entry) {
|
|
3135
|
+
return;
|
|
3136
|
+
}
|
|
3137
|
+
try {
|
|
3138
|
+
fsSync.rmSync(entry.path, { force: true, recursive: entry.recursive });
|
|
3139
|
+
}
|
|
3140
|
+
finally {
|
|
3141
|
+
tempCleanupEntries.delete(tempPath);
|
|
3142
|
+
}
|
|
3143
|
+
}
|
|
3144
|
+
|
|
3145
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/write-queue.js
|
|
3146
|
+
const writeQueues = new Map();
|
|
3147
|
+
async function serializePathWrite(key, run) {
|
|
3148
|
+
const previous = writeQueues.get(key) ?? Promise.resolve();
|
|
3149
|
+
const task = (async () => {
|
|
3150
|
+
await previous.catch(() => undefined);
|
|
3151
|
+
return await run();
|
|
3152
|
+
})();
|
|
3153
|
+
const done = task.then(() => undefined, () => undefined);
|
|
3154
|
+
writeQueues.set(key, done);
|
|
3155
|
+
try {
|
|
3156
|
+
return await task;
|
|
3157
|
+
}
|
|
3158
|
+
finally {
|
|
3159
|
+
if (writeQueues.get(key) === done) {
|
|
3160
|
+
writeQueues.delete(key);
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
}
|
|
3164
|
+
|
|
3165
|
+
;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-impl.js
|
|
3166
|
+
|
|
3167
|
+
|
|
3168
|
+
|
|
3169
|
+
|
|
3170
|
+
|
|
3171
|
+
|
|
3172
|
+
|
|
3173
|
+
|
|
3174
|
+
|
|
3175
|
+
|
|
3176
|
+
|
|
3177
|
+
|
|
3178
|
+
|
|
3179
|
+
|
|
3180
|
+
|
|
3181
|
+
|
|
3182
|
+
|
|
3183
|
+
|
|
3184
|
+
|
|
3185
|
+
|
|
3186
|
+
|
|
3187
|
+
|
|
3188
|
+
|
|
3189
|
+
|
|
3190
|
+
function logWarn(message) {
|
|
3191
|
+
if (process.env.FS_SAFE_DEBUG_WARNINGS === "1") {
|
|
3192
|
+
console.warn(message);
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
const SUPPORTS_NOFOLLOW = process.platform !== "win32" && "O_NOFOLLOW" in external_node_fs_.constants;
|
|
3196
|
+
const NONBLOCK_OPEN_FLAG = "O_NONBLOCK" in external_node_fs_.constants ? external_node_fs_.constants.O_NONBLOCK : 0;
|
|
3197
|
+
const OPEN_READ_FLAGS = external_node_fs_.constants.O_RDONLY | (SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0);
|
|
3198
|
+
const OPEN_READ_NONBLOCK_FLAGS = OPEN_READ_FLAGS | NONBLOCK_OPEN_FLAG;
|
|
3199
|
+
const OPEN_READ_FOLLOW_FLAGS = external_node_fs_.constants.O_RDONLY;
|
|
3200
|
+
const OPEN_READ_FOLLOW_NONBLOCK_FLAGS = OPEN_READ_FOLLOW_FLAGS | NONBLOCK_OPEN_FLAG;
|
|
3201
|
+
const OPEN_WRITE_EXISTING_FLAGS = external_node_fs_.constants.O_WRONLY | (SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0);
|
|
3202
|
+
const OPEN_WRITE_CREATE_FLAGS = external_node_fs_.constants.O_WRONLY |
|
|
3203
|
+
external_node_fs_.constants.O_CREAT |
|
|
3204
|
+
external_node_fs_.constants.O_EXCL |
|
|
3205
|
+
(SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0);
|
|
3206
|
+
const OPEN_APPEND_EXISTING_FLAGS = external_node_fs_.constants.O_RDWR | external_node_fs_.constants.O_APPEND | (SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0);
|
|
3207
|
+
const OPEN_APPEND_CREATE_FLAGS = external_node_fs_.constants.O_RDWR |
|
|
3208
|
+
external_node_fs_.constants.O_APPEND |
|
|
3209
|
+
external_node_fs_.constants.O_CREAT |
|
|
3210
|
+
external_node_fs_.constants.O_EXCL |
|
|
3211
|
+
(SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0);
|
|
3212
|
+
const DEFAULT_ROOT_MAX_BYTES = 16 * 1024 * 1024;
|
|
3213
|
+
function closeHandleForDispose(handle) {
|
|
3214
|
+
return handle.close().catch(() => undefined);
|
|
3215
|
+
}
|
|
3216
|
+
function openResult(params) {
|
|
3217
|
+
return {
|
|
3218
|
+
handle: params.handle,
|
|
3219
|
+
realPath: params.realPath,
|
|
3220
|
+
stat: params.stat,
|
|
3221
|
+
[Symbol.asyncDispose]: async () => {
|
|
3222
|
+
await closeHandleForDispose(params.handle);
|
|
3223
|
+
},
|
|
3224
|
+
};
|
|
3225
|
+
}
|
|
3226
|
+
async function openVerifiedLocalFile(filePath, options) {
|
|
3227
|
+
const fsSafeTestHooks = getFsSafeTestHooks();
|
|
3228
|
+
// Reject directories before opening so we never surface EISDIR to callers (e.g. tool
|
|
3229
|
+
// results that get sent to messaging channels). See openclaw/openclaw#31186.
|
|
3230
|
+
try {
|
|
3231
|
+
const preStat = await promises_.lstat(filePath);
|
|
3232
|
+
if (preStat.isDirectory()) {
|
|
3233
|
+
throw new errors_FsSafeError("not-file", "not a file");
|
|
785
3234
|
}
|
|
3235
|
+
await fsSafeTestHooks?.afterPreOpenLstat?.(filePath);
|
|
786
3236
|
}
|
|
787
|
-
|
|
3237
|
+
catch (err) {
|
|
3238
|
+
if (err instanceof errors_FsSafeError) {
|
|
3239
|
+
throw err;
|
|
3240
|
+
}
|
|
3241
|
+
// ENOENT and other lstat errors: fall through and let fs.open handle.
|
|
3242
|
+
}
|
|
3243
|
+
let handle;
|
|
3244
|
+
try {
|
|
3245
|
+
const openFlags = options?.symlinks === "follow-within-root"
|
|
3246
|
+
? options?.nonBlockingRead
|
|
3247
|
+
? OPEN_READ_FOLLOW_NONBLOCK_FLAGS
|
|
3248
|
+
: OPEN_READ_FOLLOW_FLAGS
|
|
3249
|
+
: options?.nonBlockingRead
|
|
3250
|
+
? OPEN_READ_NONBLOCK_FLAGS
|
|
3251
|
+
: OPEN_READ_FLAGS;
|
|
3252
|
+
await fsSafeTestHooks?.beforeOpen?.(filePath, openFlags);
|
|
3253
|
+
handle = await promises_.open(filePath, openFlags);
|
|
3254
|
+
try {
|
|
3255
|
+
await fsSafeTestHooks?.afterOpen?.(filePath, handle);
|
|
3256
|
+
}
|
|
3257
|
+
catch (err) {
|
|
3258
|
+
await handle.close().catch(() => { });
|
|
3259
|
+
throw err;
|
|
3260
|
+
}
|
|
3261
|
+
}
|
|
3262
|
+
catch (err) {
|
|
3263
|
+
if (path_isNotFoundPathError(err)) {
|
|
3264
|
+
throw new errors_FsSafeError("not-found", "file not found");
|
|
3265
|
+
}
|
|
3266
|
+
if (isSymlinkOpenError(err)) {
|
|
3267
|
+
throw new errors_FsSafeError("symlink", "symlink open blocked", { cause: err });
|
|
3268
|
+
}
|
|
3269
|
+
// Defensive: if open still throws EISDIR (e.g. race), sanitize so it never leaks.
|
|
3270
|
+
if (hasNodeErrorCode(err, "EISDIR")) {
|
|
3271
|
+
throw new errors_FsSafeError("not-file", "not a file");
|
|
3272
|
+
}
|
|
3273
|
+
throw err;
|
|
3274
|
+
}
|
|
3275
|
+
try {
|
|
3276
|
+
const stat = await handle.stat();
|
|
3277
|
+
if (!stat.isFile()) {
|
|
3278
|
+
throw new errors_FsSafeError("not-file", "not a file");
|
|
3279
|
+
}
|
|
3280
|
+
if (options?.hardlinks === "reject" && stat.nlink > 1) {
|
|
3281
|
+
throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
|
|
3282
|
+
}
|
|
3283
|
+
if (options?.symlinks === "follow-within-root") {
|
|
3284
|
+
const pathStat = await promises_.stat(filePath);
|
|
3285
|
+
if (!file_identity_sameFileIdentity(stat, pathStat)) {
|
|
3286
|
+
throw new errors_FsSafeError("path-mismatch", "path changed during read");
|
|
3287
|
+
}
|
|
3288
|
+
}
|
|
3289
|
+
else {
|
|
3290
|
+
const pathStat = await promises_.lstat(filePath);
|
|
3291
|
+
if (pathStat.isSymbolicLink()) {
|
|
3292
|
+
throw new errors_FsSafeError("symlink", "symlink not allowed");
|
|
3293
|
+
}
|
|
3294
|
+
if (!file_identity_sameFileIdentity(stat, pathStat)) {
|
|
3295
|
+
throw new errors_FsSafeError("path-mismatch", "path changed during read");
|
|
3296
|
+
}
|
|
3297
|
+
}
|
|
3298
|
+
const realPath = await resolveOpenedFileRealPathForHandle(handle, filePath);
|
|
3299
|
+
const realStat = await promises_.stat(realPath);
|
|
3300
|
+
if (options?.hardlinks === "reject" && realStat.nlink > 1) {
|
|
3301
|
+
throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
|
|
3302
|
+
}
|
|
3303
|
+
if (!file_identity_sameFileIdentity(stat, realStat)) {
|
|
3304
|
+
throw new errors_FsSafeError("path-mismatch", "path mismatch");
|
|
3305
|
+
}
|
|
3306
|
+
return openResult({ handle, realPath, stat });
|
|
3307
|
+
}
|
|
3308
|
+
catch (err) {
|
|
3309
|
+
await handle.close().catch(() => { });
|
|
3310
|
+
if (err instanceof errors_FsSafeError) {
|
|
3311
|
+
throw err;
|
|
3312
|
+
}
|
|
3313
|
+
if (path_isNotFoundPathError(err)) {
|
|
3314
|
+
throw new errors_FsSafeError("not-found", "file not found");
|
|
3315
|
+
}
|
|
3316
|
+
throw err;
|
|
3317
|
+
}
|
|
3318
|
+
}
|
|
3319
|
+
class RootHandle {
|
|
3320
|
+
rootDir;
|
|
3321
|
+
rootReal;
|
|
3322
|
+
rootWithSep;
|
|
3323
|
+
defaults;
|
|
3324
|
+
constructor(context, defaults = {}) {
|
|
3325
|
+
this.rootDir = context.rootDir;
|
|
3326
|
+
this.rootReal = context.rootReal;
|
|
3327
|
+
this.rootWithSep = context.rootWithSep;
|
|
3328
|
+
this.defaults = defaults;
|
|
3329
|
+
}
|
|
3330
|
+
get context() {
|
|
788
3331
|
return {
|
|
789
|
-
|
|
790
|
-
|
|
3332
|
+
rootDir: this.rootDir,
|
|
3333
|
+
rootReal: this.rootReal,
|
|
3334
|
+
rootWithSep: this.rootWithSep,
|
|
791
3335
|
};
|
|
792
3336
|
}
|
|
793
|
-
|
|
794
|
-
|
|
3337
|
+
async resolve(relativePath) {
|
|
3338
|
+
return (await resolvePathInRoot(this.context, relativePath)).resolved;
|
|
3339
|
+
}
|
|
3340
|
+
async open(relativePath, options = {}) {
|
|
3341
|
+
return await openFileInRoot(this.context, {
|
|
3342
|
+
relativePath,
|
|
3343
|
+
...readDefaults(this.defaults),
|
|
3344
|
+
...options,
|
|
3345
|
+
});
|
|
3346
|
+
}
|
|
3347
|
+
async read(relativePath, options = {}) {
|
|
3348
|
+
return await readFileInRoot(this.context, {
|
|
3349
|
+
relativePath,
|
|
3350
|
+
...readDefaults(this.defaults),
|
|
3351
|
+
...options,
|
|
3352
|
+
});
|
|
3353
|
+
}
|
|
3354
|
+
async readBytes(relativePath, options = {}) {
|
|
3355
|
+
return (await this.read(relativePath, options)).buffer;
|
|
3356
|
+
}
|
|
3357
|
+
async readText(relativePath, options = {}) {
|
|
3358
|
+
const { encoding = "utf8", ...readOptions } = options;
|
|
3359
|
+
return (await this.read(relativePath, readOptions)).buffer.toString(encoding);
|
|
3360
|
+
}
|
|
3361
|
+
async readJson(relativePath, options = {}) {
|
|
3362
|
+
return JSON.parse(await this.readText(relativePath, options));
|
|
3363
|
+
}
|
|
3364
|
+
async readAbsolute(filePath, options = {}) {
|
|
3365
|
+
return await readPathInRoot(this.context, {
|
|
3366
|
+
filePath,
|
|
3367
|
+
...readDefaults(this.defaults),
|
|
3368
|
+
...options,
|
|
3369
|
+
});
|
|
3370
|
+
}
|
|
3371
|
+
reader(options = {}) {
|
|
3372
|
+
return async (filePath) => {
|
|
3373
|
+
return (await this.readAbsolute(filePath, options)).buffer;
|
|
3374
|
+
};
|
|
3375
|
+
}
|
|
3376
|
+
async openWritable(relativePath, options = {}) {
|
|
3377
|
+
const writeMode = options.writeMode ?? "replace";
|
|
3378
|
+
return await openWritableFileInRoot(this.context, {
|
|
3379
|
+
relativePath,
|
|
3380
|
+
mkdir: this.defaults.mkdir,
|
|
3381
|
+
mode: this.defaults.mode,
|
|
3382
|
+
...options,
|
|
3383
|
+
append: writeMode === "append",
|
|
3384
|
+
truncateExisting: writeMode === "replace",
|
|
3385
|
+
});
|
|
3386
|
+
}
|
|
3387
|
+
async append(relativePath, data, options = {}) {
|
|
3388
|
+
await appendFileInRoot(this.context, {
|
|
3389
|
+
relativePath,
|
|
3390
|
+
data,
|
|
3391
|
+
mkdir: this.defaults.mkdir,
|
|
3392
|
+
mode: this.defaults.mode,
|
|
3393
|
+
...options,
|
|
3394
|
+
});
|
|
3395
|
+
}
|
|
3396
|
+
async remove(relativePath) {
|
|
3397
|
+
assertValidRootRelativePath(relativePath);
|
|
3398
|
+
await removePathInRoot(this.context, relativePath);
|
|
3399
|
+
}
|
|
3400
|
+
async mkdir(relativePath) {
|
|
3401
|
+
assertValidRootRelativePath(relativePath);
|
|
3402
|
+
await mkdirPathInRoot(this.context, { relativePath });
|
|
3403
|
+
}
|
|
3404
|
+
async ensureRoot() {
|
|
3405
|
+
await mkdirPathInRoot(this.context, { relativePath: "", allowRoot: true });
|
|
3406
|
+
}
|
|
3407
|
+
async write(relativePath, data, options = {}) {
|
|
3408
|
+
await writeFileInRoot(this.context, {
|
|
3409
|
+
relativePath,
|
|
3410
|
+
data,
|
|
3411
|
+
mkdir: this.defaults.mkdir,
|
|
3412
|
+
mode: this.defaults.mode,
|
|
3413
|
+
...options,
|
|
3414
|
+
});
|
|
3415
|
+
}
|
|
3416
|
+
async create(relativePath, data, options = {}) {
|
|
3417
|
+
await writeFileInRoot(this.context, {
|
|
3418
|
+
relativePath,
|
|
3419
|
+
data,
|
|
3420
|
+
mkdir: this.defaults.mkdir,
|
|
3421
|
+
mode: this.defaults.mode,
|
|
3422
|
+
...options,
|
|
3423
|
+
overwrite: false,
|
|
3424
|
+
});
|
|
3425
|
+
}
|
|
3426
|
+
async writeJson(relativePath, data, options = {}) {
|
|
3427
|
+
const { replacer, space, trailingNewline = true, ...writeOptions } = options;
|
|
3428
|
+
const json = JSON.stringify(data, replacer, space);
|
|
3429
|
+
await this.write(relativePath, trailingNewline ? `${json}\n` : json, writeOptions);
|
|
3430
|
+
}
|
|
3431
|
+
async createJson(relativePath, data, options = {}) {
|
|
3432
|
+
const { replacer, space, trailingNewline = true, ...writeOptions } = options;
|
|
3433
|
+
const json = JSON.stringify(data, replacer, space);
|
|
3434
|
+
await this.create(relativePath, trailingNewline ? `${json}\n` : json, writeOptions);
|
|
3435
|
+
}
|
|
3436
|
+
async copyIn(relativePath, sourcePath, options = {}) {
|
|
3437
|
+
assertValidRootRelativePath(relativePath);
|
|
3438
|
+
await copyFileInRoot(this.context, {
|
|
3439
|
+
sourcePath,
|
|
3440
|
+
relativePath,
|
|
3441
|
+
maxBytes: this.defaults.maxBytes,
|
|
3442
|
+
mkdir: this.defaults.mkdir,
|
|
3443
|
+
mode: this.defaults.mode,
|
|
3444
|
+
...options,
|
|
3445
|
+
});
|
|
3446
|
+
}
|
|
3447
|
+
async exists(relativePath) {
|
|
3448
|
+
try {
|
|
3449
|
+
await this.stat(relativePath);
|
|
3450
|
+
return true;
|
|
3451
|
+
}
|
|
3452
|
+
catch (err) {
|
|
3453
|
+
if (err instanceof errors_FsSafeError && err.code === "not-found") {
|
|
3454
|
+
return false;
|
|
3455
|
+
}
|
|
3456
|
+
throw err;
|
|
3457
|
+
}
|
|
3458
|
+
}
|
|
3459
|
+
async stat(relativePath) {
|
|
3460
|
+
assertValidRootRelativePath(relativePath);
|
|
3461
|
+
try {
|
|
3462
|
+
return await helperStat(this.rootReal, relativePath);
|
|
3463
|
+
}
|
|
3464
|
+
catch (error) {
|
|
3465
|
+
if (canFallbackFromPythonError(error)) {
|
|
3466
|
+
return await statPathFallback(this.context, relativePath);
|
|
3467
|
+
}
|
|
3468
|
+
throw error;
|
|
3469
|
+
}
|
|
3470
|
+
}
|
|
3471
|
+
async list(relativePath, options = {}) {
|
|
3472
|
+
assertValidRootRelativePath(relativePath);
|
|
3473
|
+
try {
|
|
3474
|
+
return options.withFileTypes === true
|
|
3475
|
+
? await helperReaddir(this.rootReal, relativePath, true)
|
|
3476
|
+
: await helperReaddir(this.rootReal, relativePath, false);
|
|
3477
|
+
}
|
|
3478
|
+
catch (error) {
|
|
3479
|
+
if (canFallbackFromPythonError(error)) {
|
|
3480
|
+
return await listPathFallback(this.context, relativePath, options.withFileTypes === true);
|
|
3481
|
+
}
|
|
3482
|
+
throw error;
|
|
3483
|
+
}
|
|
3484
|
+
}
|
|
3485
|
+
async move(fromRelative, toRelative, options = {}) {
|
|
3486
|
+
assertValidRootRelativePath(fromRelative);
|
|
3487
|
+
assertValidRootRelativePath(toRelative);
|
|
3488
|
+
try {
|
|
3489
|
+
await runPinnedHelper("rename", this.rootReal, {
|
|
3490
|
+
from: fromRelative,
|
|
3491
|
+
overwrite: options.overwrite ?? false,
|
|
3492
|
+
to: toRelative,
|
|
3493
|
+
});
|
|
3494
|
+
}
|
|
3495
|
+
catch (error) {
|
|
3496
|
+
if (canFallbackFromPythonError(error)) {
|
|
3497
|
+
await movePathFallback(this.context, {
|
|
3498
|
+
fromRelative,
|
|
3499
|
+
overwrite: options.overwrite ?? false,
|
|
3500
|
+
toRelative,
|
|
3501
|
+
});
|
|
3502
|
+
return;
|
|
3503
|
+
}
|
|
3504
|
+
throw error;
|
|
3505
|
+
}
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
function readDefaults(defaults) {
|
|
3509
|
+
return {
|
|
3510
|
+
hardlinks: defaults.hardlinks,
|
|
3511
|
+
maxBytes: defaults.maxBytes ?? DEFAULT_ROOT_MAX_BYTES,
|
|
3512
|
+
nonBlockingRead: defaults.nonBlockingRead,
|
|
3513
|
+
symlinks: defaults.symlinks,
|
|
3514
|
+
};
|
|
3515
|
+
}
|
|
3516
|
+
async function root_impl_root(rootDir, defaults = {}) {
|
|
3517
|
+
return new RootHandle(await resolveRootContext(rootDir), defaults);
|
|
3518
|
+
}
|
|
3519
|
+
async function openFileInRoot(root, params) {
|
|
3520
|
+
const { rootWithSep, resolved } = await resolvePathInRoot(root, params.relativePath);
|
|
3521
|
+
let opened;
|
|
795
3522
|
try {
|
|
796
|
-
|
|
797
|
-
|
|
3523
|
+
opened = await openVerifiedLocalFile(resolved, {
|
|
3524
|
+
nonBlockingRead: params.nonBlockingRead,
|
|
3525
|
+
symlinks: params.symlinks,
|
|
798
3526
|
});
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
3527
|
+
}
|
|
3528
|
+
catch (err) {
|
|
3529
|
+
if (err instanceof errors_FsSafeError) {
|
|
3530
|
+
throw err;
|
|
3531
|
+
}
|
|
3532
|
+
throw err;
|
|
3533
|
+
}
|
|
3534
|
+
if (params.hardlinks !== "allow" && opened.stat.nlink > 1) {
|
|
3535
|
+
await opened.handle.close().catch(() => { });
|
|
3536
|
+
throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
|
|
3537
|
+
}
|
|
3538
|
+
if (!path_isPathInside(rootWithSep, opened.realPath)) {
|
|
3539
|
+
await opened.handle.close().catch(() => { });
|
|
3540
|
+
throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
|
|
3541
|
+
}
|
|
3542
|
+
return opened;
|
|
3543
|
+
}
|
|
3544
|
+
async function readFileInRoot(root, params) {
|
|
3545
|
+
const opened = await openFileInRoot(root, params);
|
|
3546
|
+
try {
|
|
3547
|
+
return await readOpenedFileSafely({ opened, maxBytes: params.maxBytes });
|
|
3548
|
+
}
|
|
3549
|
+
finally {
|
|
3550
|
+
await opened.handle.close().catch(() => { });
|
|
3551
|
+
}
|
|
3552
|
+
}
|
|
3553
|
+
async function readPathInRoot(root, params) {
|
|
3554
|
+
const rootDir = root.rootDir;
|
|
3555
|
+
const candidatePath = external_node_path_.isAbsolute(params.filePath)
|
|
3556
|
+
? external_node_path_.resolve(params.filePath)
|
|
3557
|
+
: external_node_path_.resolve(rootDir, params.filePath);
|
|
3558
|
+
const relativePath = external_node_path_.relative(rootDir, candidatePath);
|
|
3559
|
+
return await readFileInRoot(root, {
|
|
3560
|
+
relativePath,
|
|
3561
|
+
hardlinks: params.hardlinks,
|
|
3562
|
+
maxBytes: params.maxBytes,
|
|
3563
|
+
nonBlockingRead: params.nonBlockingRead,
|
|
3564
|
+
symlinks: params.symlinks,
|
|
3565
|
+
});
|
|
3566
|
+
}
|
|
3567
|
+
async function readLocalFileSafely(params) {
|
|
3568
|
+
const opened = await openLocalFileSafely({ filePath: params.filePath });
|
|
3569
|
+
try {
|
|
3570
|
+
return await readOpenedFileSafely({ opened, maxBytes: params.maxBytes });
|
|
3571
|
+
}
|
|
3572
|
+
finally {
|
|
3573
|
+
await opened.handle.close().catch(() => { });
|
|
3574
|
+
}
|
|
3575
|
+
}
|
|
3576
|
+
async function openLocalFileSafely(params) {
|
|
3577
|
+
assertNoNulPathInput(params.filePath, "file path contains a NUL byte");
|
|
3578
|
+
return await openVerifiedLocalFile(params.filePath);
|
|
3579
|
+
}
|
|
3580
|
+
async function readOpenedFileSafely(params) {
|
|
3581
|
+
if (params.maxBytes !== undefined && params.opened.stat.size > params.maxBytes) {
|
|
3582
|
+
throw new errors_FsSafeError("too-large", `file exceeds limit of ${params.maxBytes} bytes (got ${params.opened.stat.size})`);
|
|
3583
|
+
}
|
|
3584
|
+
const buffer = await params.opened.handle.readFile();
|
|
3585
|
+
if (params.maxBytes !== undefined && buffer.byteLength > params.maxBytes) {
|
|
3586
|
+
throw new errors_FsSafeError("too-large", `file exceeds limit of ${params.maxBytes} bytes (got ${buffer.byteLength})`);
|
|
3587
|
+
}
|
|
3588
|
+
return {
|
|
3589
|
+
buffer,
|
|
3590
|
+
realPath: params.opened.realPath,
|
|
3591
|
+
stat: params.opened.stat,
|
|
3592
|
+
};
|
|
3593
|
+
}
|
|
3594
|
+
function emitWriteBoundaryWarning(reason) {
|
|
3595
|
+
logWarn(`security: fs-safe write boundary warning (${reason})`);
|
|
3596
|
+
}
|
|
3597
|
+
function buildAtomicWriteTempPath(targetPath) {
|
|
3598
|
+
const dir = external_node_path_.dirname(targetPath);
|
|
3599
|
+
const base = external_node_path_.basename(targetPath);
|
|
3600
|
+
return external_node_path_.join(dir, `.${base}.${process.pid}.${(0,external_node_crypto_.randomUUID)()}.tmp`);
|
|
3601
|
+
}
|
|
3602
|
+
function rootWriteQueueKey(root, relativePath) {
|
|
3603
|
+
return `${root.rootReal}\0${relativePath}`;
|
|
3604
|
+
}
|
|
3605
|
+
async function writeTempFileForAtomicReplace(params) {
|
|
3606
|
+
const tempHandle = await promises_.open(params.tempPath, OPEN_WRITE_CREATE_FLAGS, params.mode);
|
|
3607
|
+
try {
|
|
3608
|
+
if (typeof params.data === "string") {
|
|
3609
|
+
await tempHandle.writeFile(params.data, params.encoding ?? "utf8");
|
|
3610
|
+
}
|
|
3611
|
+
else {
|
|
3612
|
+
await tempHandle.writeFile(params.data);
|
|
3613
|
+
}
|
|
3614
|
+
return await tempHandle.stat();
|
|
3615
|
+
}
|
|
3616
|
+
finally {
|
|
3617
|
+
await tempHandle.close().catch(() => { });
|
|
3618
|
+
}
|
|
3619
|
+
}
|
|
3620
|
+
async function verifyAtomicWriteResult(params) {
|
|
3621
|
+
const opened = await openVerifiedLocalFile(params.targetPath, { hardlinks: "reject" });
|
|
3622
|
+
try {
|
|
3623
|
+
if (!file_identity_sameFileIdentity(opened.stat, params.expectedIdentity)) {
|
|
3624
|
+
throw new errors_FsSafeError("path-mismatch", "path changed during write");
|
|
3625
|
+
}
|
|
3626
|
+
if (!path_isPathInside(params.root.rootWithSep, opened.realPath)) {
|
|
3627
|
+
throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
3630
|
+
finally {
|
|
3631
|
+
await opened.handle.close().catch(() => { });
|
|
3632
|
+
}
|
|
3633
|
+
}
|
|
3634
|
+
async function resolveOpenedFileRealPathForHandle(handle, ioPath) {
|
|
3635
|
+
const handleStat = await handle.stat();
|
|
3636
|
+
const fdCandidates = process.platform === "linux"
|
|
3637
|
+
? [`/proc/self/fd/${handle.fd}`, `/dev/fd/${handle.fd}`]
|
|
3638
|
+
: process.platform === "win32"
|
|
3639
|
+
? []
|
|
3640
|
+
: [`/dev/fd/${handle.fd}`];
|
|
3641
|
+
for (const fdPath of fdCandidates) {
|
|
3642
|
+
try {
|
|
3643
|
+
const fdRealPath = await promises_.realpath(fdPath);
|
|
3644
|
+
const fdRealStat = await promises_.stat(fdRealPath);
|
|
3645
|
+
if (file_identity_sameFileIdentity(handleStat, fdRealStat)) {
|
|
3646
|
+
return fdRealPath;
|
|
3647
|
+
}
|
|
3648
|
+
}
|
|
3649
|
+
catch {
|
|
3650
|
+
// try next fd path
|
|
3651
|
+
}
|
|
3652
|
+
}
|
|
3653
|
+
try {
|
|
3654
|
+
const ioRealPath = await promises_.realpath(ioPath);
|
|
3655
|
+
const ioRealStat = await promises_.stat(ioRealPath);
|
|
3656
|
+
if (file_identity_sameFileIdentity(handleStat, ioRealStat)) {
|
|
3657
|
+
return ioRealPath;
|
|
3658
|
+
}
|
|
3659
|
+
}
|
|
3660
|
+
catch (err) {
|
|
3661
|
+
if (!path_isNotFoundPathError(err)) {
|
|
3662
|
+
throw err;
|
|
3663
|
+
}
|
|
3664
|
+
}
|
|
3665
|
+
const parentResolved = await resolveOpenedFileRealPathFromParent(handleStat, ioPath);
|
|
3666
|
+
if (parentResolved) {
|
|
3667
|
+
return parentResolved;
|
|
3668
|
+
}
|
|
3669
|
+
throw new errors_FsSafeError("path-mismatch", "unable to resolve opened file path");
|
|
3670
|
+
}
|
|
3671
|
+
async function resolveOpenedFileRealPathFromParent(handleStat, ioPath) {
|
|
3672
|
+
let parentReal;
|
|
3673
|
+
try {
|
|
3674
|
+
parentReal = await promises_.realpath(external_node_path_.dirname(ioPath));
|
|
3675
|
+
}
|
|
3676
|
+
catch (err) {
|
|
3677
|
+
if (path_isNotFoundPathError(err)) {
|
|
3678
|
+
return null;
|
|
3679
|
+
}
|
|
3680
|
+
throw err;
|
|
3681
|
+
}
|
|
3682
|
+
let entries;
|
|
3683
|
+
try {
|
|
3684
|
+
entries = await promises_.readdir(parentReal);
|
|
3685
|
+
}
|
|
3686
|
+
catch (err) {
|
|
3687
|
+
if (path_isNotFoundPathError(err)) {
|
|
3688
|
+
return null;
|
|
3689
|
+
}
|
|
3690
|
+
throw err;
|
|
3691
|
+
}
|
|
3692
|
+
for (const entry of entries.toSorted()) {
|
|
3693
|
+
const candidatePath = external_node_path_.join(parentReal, entry);
|
|
3694
|
+
try {
|
|
3695
|
+
const candidateStat = await promises_.lstat(candidatePath);
|
|
3696
|
+
if (candidateStat.isFile() && file_identity_sameFileIdentity(handleStat, candidateStat)) {
|
|
3697
|
+
return await promises_.realpath(candidatePath);
|
|
3698
|
+
}
|
|
3699
|
+
}
|
|
3700
|
+
catch (err) {
|
|
3701
|
+
if (!path_isNotFoundPathError(err)) {
|
|
3702
|
+
throw err;
|
|
3703
|
+
}
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
return null;
|
|
3707
|
+
}
|
|
3708
|
+
async function openWritableFileInRoot(root, params) {
|
|
3709
|
+
const { rootReal, rootWithSep, resolved } = await resolvePathInRoot(root, params.relativePath);
|
|
3710
|
+
try {
|
|
3711
|
+
await assertNoPathAliasEscape({
|
|
3712
|
+
absolutePath: resolved,
|
|
3713
|
+
rootPath: rootReal,
|
|
3714
|
+
boundaryLabel: "root",
|
|
3715
|
+
});
|
|
3716
|
+
}
|
|
3717
|
+
catch (err) {
|
|
3718
|
+
throw new errors_FsSafeError("path-alias", "path alias escape blocked", { cause: err });
|
|
3719
|
+
}
|
|
3720
|
+
if (params.mkdir !== false) {
|
|
3721
|
+
const parentGuard = await directory_guard_createNearestExistingDirectoryGuard(rootReal, external_node_path_.dirname(resolved));
|
|
3722
|
+
await withAsyncDirectoryGuards([parentGuard], async () => {
|
|
3723
|
+
await promises_.mkdir(external_node_path_.dirname(resolved), { recursive: true });
|
|
3724
|
+
});
|
|
3725
|
+
}
|
|
3726
|
+
let ioPath = resolved;
|
|
3727
|
+
try {
|
|
3728
|
+
const resolvedRealPath = await promises_.realpath(resolved);
|
|
3729
|
+
if (!path_isPathInside(rootWithSep, resolvedRealPath)) {
|
|
3730
|
+
throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
|
|
3731
|
+
}
|
|
3732
|
+
ioPath = resolvedRealPath;
|
|
3733
|
+
}
|
|
3734
|
+
catch (err) {
|
|
3735
|
+
if (err instanceof errors_FsSafeError) {
|
|
3736
|
+
throw err;
|
|
3737
|
+
}
|
|
3738
|
+
if (!path_isNotFoundPathError(err)) {
|
|
3739
|
+
throw err;
|
|
3740
|
+
}
|
|
3741
|
+
}
|
|
3742
|
+
const mode = params.mode ?? 0o600;
|
|
3743
|
+
let handle;
|
|
3744
|
+
let createdForWrite = false;
|
|
3745
|
+
const existingFlags = params.append ? OPEN_APPEND_EXISTING_FLAGS : OPEN_WRITE_EXISTING_FLAGS;
|
|
3746
|
+
const createFlags = params.append ? OPEN_APPEND_CREATE_FLAGS : OPEN_WRITE_CREATE_FLAGS;
|
|
3747
|
+
try {
|
|
3748
|
+
try {
|
|
3749
|
+
handle = await promises_.open(ioPath, existingFlags, mode);
|
|
3750
|
+
}
|
|
3751
|
+
catch (err) {
|
|
3752
|
+
if (!path_isNotFoundPathError(err)) {
|
|
3753
|
+
throw err;
|
|
3754
|
+
}
|
|
3755
|
+
handle = await promises_.open(ioPath, createFlags, mode);
|
|
3756
|
+
createdForWrite = true;
|
|
3757
|
+
}
|
|
3758
|
+
}
|
|
3759
|
+
catch (err) {
|
|
3760
|
+
if (path_isNotFoundPathError(err)) {
|
|
3761
|
+
throw new errors_FsSafeError("not-found", "file not found");
|
|
3762
|
+
}
|
|
3763
|
+
if (isSymlinkOpenError(err)) {
|
|
3764
|
+
throw new errors_FsSafeError("symlink", "symlink open blocked", { cause: err });
|
|
3765
|
+
}
|
|
3766
|
+
if (hasNodeErrorCode(err, "EISDIR")) {
|
|
3767
|
+
throw new errors_FsSafeError("not-file", "not a file", { cause: err });
|
|
3768
|
+
}
|
|
3769
|
+
throw err;
|
|
3770
|
+
}
|
|
3771
|
+
let realPathForCleanup = null;
|
|
3772
|
+
try {
|
|
3773
|
+
const stat = await handle.stat();
|
|
3774
|
+
if (!stat.isFile()) {
|
|
3775
|
+
throw new errors_FsSafeError("invalid-path", "path is not a regular file under root");
|
|
3776
|
+
}
|
|
3777
|
+
if (stat.nlink > 1) {
|
|
3778
|
+
throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
|
|
3779
|
+
}
|
|
3780
|
+
try {
|
|
3781
|
+
const lstat = await promises_.lstat(ioPath);
|
|
3782
|
+
if (lstat.isSymbolicLink() || !lstat.isFile()) {
|
|
3783
|
+
throw new errors_FsSafeError(lstat.isSymbolicLink() ? "symlink" : "not-file", "path is not a regular file under root");
|
|
3784
|
+
}
|
|
3785
|
+
if (!file_identity_sameFileIdentity(stat, lstat)) {
|
|
3786
|
+
throw new errors_FsSafeError("path-mismatch", "path changed during write");
|
|
3787
|
+
}
|
|
3788
|
+
}
|
|
3789
|
+
catch (err) {
|
|
3790
|
+
if (!path_isNotFoundPathError(err)) {
|
|
3791
|
+
throw err;
|
|
3792
|
+
}
|
|
3793
|
+
}
|
|
3794
|
+
const realPath = await resolveOpenedFileRealPathForHandle(handle, ioPath);
|
|
3795
|
+
realPathForCleanup = realPath;
|
|
3796
|
+
const realStat = await promises_.stat(realPath);
|
|
3797
|
+
if (!file_identity_sameFileIdentity(stat, realStat)) {
|
|
3798
|
+
throw new errors_FsSafeError("path-mismatch", "path mismatch");
|
|
3799
|
+
}
|
|
3800
|
+
if (realStat.nlink > 1) {
|
|
3801
|
+
throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
|
|
3802
|
+
}
|
|
3803
|
+
if (!path_isPathInside(rootWithSep, realPath)) {
|
|
3804
|
+
throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
|
|
3805
|
+
}
|
|
3806
|
+
// Truncate only after boundary and identity checks complete. This avoids
|
|
3807
|
+
// irreversible side effects if a symlink target changes before validation.
|
|
3808
|
+
if (params.append !== true && params.truncateExisting !== false && !createdForWrite) {
|
|
3809
|
+
await handle.truncate(0);
|
|
3810
|
+
}
|
|
802
3811
|
return {
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
3812
|
+
handle,
|
|
3813
|
+
createdForWrite,
|
|
3814
|
+
realPath,
|
|
3815
|
+
stat,
|
|
3816
|
+
[Symbol.asyncDispose]: async () => {
|
|
3817
|
+
await closeHandleForDispose(handle);
|
|
3818
|
+
},
|
|
806
3819
|
};
|
|
807
3820
|
}
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
const
|
|
811
|
-
|
|
812
|
-
|
|
3821
|
+
catch (err) {
|
|
3822
|
+
const cleanupCreatedPath = createdForWrite && err instanceof errors_FsSafeError;
|
|
3823
|
+
const cleanupPath = realPathForCleanup ?? ioPath;
|
|
3824
|
+
await handle.close().catch(() => { });
|
|
3825
|
+
if (cleanupCreatedPath) {
|
|
3826
|
+
await promises_.rm(cleanupPath, { force: true }).catch(() => { });
|
|
813
3827
|
}
|
|
3828
|
+
throw err;
|
|
814
3829
|
}
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
3830
|
+
}
|
|
3831
|
+
async function appendFileInRoot(root, params) {
|
|
3832
|
+
const target = await openWritableFileInRoot(root, {
|
|
3833
|
+
relativePath: params.relativePath,
|
|
3834
|
+
mkdir: params.mkdir,
|
|
3835
|
+
mode: params.mode,
|
|
3836
|
+
truncateExisting: false,
|
|
3837
|
+
append: true,
|
|
3838
|
+
});
|
|
3839
|
+
try {
|
|
3840
|
+
let prefix = "";
|
|
3841
|
+
if (params.prependNewlineIfNeeded === true &&
|
|
3842
|
+
!target.createdForWrite &&
|
|
3843
|
+
target.stat.size > 0 &&
|
|
3844
|
+
((typeof params.data === "string" && !params.data.startsWith("\n")) ||
|
|
3845
|
+
(Buffer.isBuffer(params.data) && params.data.length > 0 && params.data[0] !== 0x0a))) {
|
|
3846
|
+
const lastByte = Buffer.alloc(1);
|
|
3847
|
+
const { bytesRead } = await target.handle.read(lastByte, 0, 1, target.stat.size - 1);
|
|
3848
|
+
if (bytesRead === 1 && lastByte[0] !== 0x0a) {
|
|
3849
|
+
prefix = "\n";
|
|
3850
|
+
}
|
|
3851
|
+
}
|
|
3852
|
+
if (typeof params.data === "string") {
|
|
3853
|
+
await target.handle.appendFile(`${prefix}${params.data}`, params.encoding ?? "utf8");
|
|
3854
|
+
return;
|
|
3855
|
+
}
|
|
3856
|
+
const payload = prefix.length > 0 ? Buffer.concat([Buffer.from(prefix, "utf8"), params.data]) : params.data;
|
|
3857
|
+
await target.handle.appendFile(payload);
|
|
3858
|
+
}
|
|
3859
|
+
finally {
|
|
3860
|
+
await target.handle.close().catch(() => { });
|
|
3861
|
+
}
|
|
3862
|
+
}
|
|
3863
|
+
async function removePathInRoot(root, relativePath) {
|
|
3864
|
+
const resolved = await resolvePinnedRemovePathInRoot(root, relativePath);
|
|
3865
|
+
if (process.platform === "win32") {
|
|
3866
|
+
await removePathFallback(resolved);
|
|
3867
|
+
return;
|
|
3868
|
+
}
|
|
3869
|
+
try {
|
|
3870
|
+
await runPinnedPathHelper({
|
|
3871
|
+
operation: "remove",
|
|
3872
|
+
rootPath: resolved.rootReal,
|
|
3873
|
+
relativePath: resolved.relativePosix,
|
|
3874
|
+
});
|
|
3875
|
+
}
|
|
3876
|
+
catch (error) {
|
|
3877
|
+
if (isPinnedPathHelperSpawnError(error)) {
|
|
3878
|
+
await removePathFallback(resolved);
|
|
3879
|
+
return;
|
|
3880
|
+
}
|
|
3881
|
+
throw normalizePinnedPathError(error);
|
|
3882
|
+
}
|
|
3883
|
+
}
|
|
3884
|
+
async function mkdirPathInRoot(root, params) {
|
|
3885
|
+
const resolved = await resolvePinnedPathInRoot(root, params);
|
|
3886
|
+
if (process.platform === "win32") {
|
|
3887
|
+
await mkdirPathFallback(resolved);
|
|
3888
|
+
return;
|
|
3889
|
+
}
|
|
3890
|
+
try {
|
|
3891
|
+
await runPinnedPathHelper({
|
|
3892
|
+
operation: "mkdirp",
|
|
3893
|
+
rootPath: resolved.rootReal,
|
|
3894
|
+
relativePath: resolved.relativePosix,
|
|
3895
|
+
});
|
|
3896
|
+
}
|
|
3897
|
+
catch (error) {
|
|
3898
|
+
if (isPinnedPathHelperSpawnError(error)) {
|
|
3899
|
+
await mkdirPathFallback(resolved);
|
|
3900
|
+
return;
|
|
3901
|
+
}
|
|
3902
|
+
throw normalizePinnedPathError(error);
|
|
3903
|
+
}
|
|
3904
|
+
}
|
|
3905
|
+
async function writeFileInRoot(root, params) {
|
|
3906
|
+
if (process.platform === "win32") {
|
|
3907
|
+
await serializePathWrite(rootWriteQueueKey(root, params.relativePath), async () => {
|
|
3908
|
+
await writeFileFallback(root, params);
|
|
3909
|
+
});
|
|
3910
|
+
return;
|
|
3911
|
+
}
|
|
3912
|
+
const pinned = await resolvePinnedWriteTargetInRoot(root, params.relativePath, params.mode);
|
|
3913
|
+
await serializePathWrite(pinned.targetPath, async () => {
|
|
3914
|
+
let identity;
|
|
3915
|
+
try {
|
|
3916
|
+
identity = await runPinnedWriteHelper({
|
|
3917
|
+
rootPath: pinned.rootReal,
|
|
3918
|
+
relativeParentPath: pinned.relativeParentPath,
|
|
3919
|
+
basename: pinned.basename,
|
|
3920
|
+
mkdir: params.mkdir !== false,
|
|
3921
|
+
mode: params.mode ?? pinned.mode,
|
|
3922
|
+
overwrite: params.overwrite,
|
|
3923
|
+
input: {
|
|
3924
|
+
kind: "buffer",
|
|
3925
|
+
data: params.data,
|
|
3926
|
+
encoding: params.encoding,
|
|
3927
|
+
},
|
|
3928
|
+
});
|
|
3929
|
+
}
|
|
3930
|
+
catch (error) {
|
|
3931
|
+
if (params.overwrite === false && isAlreadyExistsError(error)) {
|
|
3932
|
+
throw new errors_FsSafeError("already-exists", "file already exists", {
|
|
3933
|
+
cause: error instanceof Error ? error : undefined,
|
|
3934
|
+
});
|
|
3935
|
+
}
|
|
3936
|
+
throw normalizePinnedWriteError(error);
|
|
3937
|
+
}
|
|
3938
|
+
try {
|
|
3939
|
+
await verifyAtomicWriteResult({
|
|
3940
|
+
root,
|
|
3941
|
+
targetPath: pinned.targetPath,
|
|
3942
|
+
expectedIdentity: identity,
|
|
3943
|
+
});
|
|
3944
|
+
}
|
|
3945
|
+
catch (err) {
|
|
3946
|
+
emitWriteBoundaryWarning(`post-write verification failed: ${String(err)}`);
|
|
3947
|
+
throw err;
|
|
3948
|
+
}
|
|
3949
|
+
});
|
|
3950
|
+
}
|
|
3951
|
+
async function copyFileInRoot(root, params) {
|
|
3952
|
+
assertValidRootRelativePath(params.relativePath);
|
|
3953
|
+
path_assertNoNulPathInput(params.sourcePath, "source path contains a NUL byte");
|
|
3954
|
+
const source = await openVerifiedLocalFile(params.sourcePath, {
|
|
3955
|
+
hardlinks: params.sourceHardlinks,
|
|
3956
|
+
});
|
|
3957
|
+
if (params.maxBytes !== undefined && source.stat.size > params.maxBytes) {
|
|
3958
|
+
await source.handle.close().catch(() => { });
|
|
3959
|
+
throw new errors_FsSafeError("too-large", `file exceeds limit of ${params.maxBytes} bytes (got ${source.stat.size})`);
|
|
3960
|
+
}
|
|
3961
|
+
try {
|
|
3962
|
+
if (process.platform === "win32") {
|
|
3963
|
+
await serializePathWrite(rootWriteQueueKey(root, params.relativePath), async () => {
|
|
3964
|
+
await copyFileFallback(root, params, source);
|
|
3965
|
+
});
|
|
3966
|
+
return;
|
|
3967
|
+
}
|
|
3968
|
+
const pinned = await resolvePinnedWriteTargetInRoot(root, params.relativePath, params.mode);
|
|
3969
|
+
await serializePathWrite(pinned.targetPath, async () => {
|
|
3970
|
+
let identity;
|
|
3971
|
+
try {
|
|
3972
|
+
if (getFsSafePythonConfig().mode === "off") {
|
|
3973
|
+
await copyFileFallback(root, params, source);
|
|
3974
|
+
return;
|
|
3975
|
+
}
|
|
3976
|
+
identity = await runPinnedCopyHelper({
|
|
3977
|
+
rootPath: pinned.rootReal,
|
|
3978
|
+
relativeParentPath: pinned.relativeParentPath,
|
|
3979
|
+
basename: pinned.basename,
|
|
3980
|
+
mkdir: params.mkdir !== false,
|
|
3981
|
+
mode: pinned.mode,
|
|
3982
|
+
overwrite: true,
|
|
3983
|
+
maxBytes: params.maxBytes,
|
|
3984
|
+
sourcePath: source.realPath,
|
|
3985
|
+
sourceIdentity: { dev: source.stat.dev, ino: source.stat.ino },
|
|
3986
|
+
});
|
|
3987
|
+
}
|
|
3988
|
+
catch (error) {
|
|
3989
|
+
if (canFallbackFromPythonError(error)) {
|
|
3990
|
+
await copyFileFallback(root, params, source);
|
|
3991
|
+
return;
|
|
3992
|
+
}
|
|
3993
|
+
throw normalizePinnedWriteError(error);
|
|
3994
|
+
}
|
|
3995
|
+
try {
|
|
3996
|
+
await verifyAtomicWriteResult({
|
|
3997
|
+
root,
|
|
3998
|
+
targetPath: pinned.targetPath,
|
|
3999
|
+
expectedIdentity: identity,
|
|
4000
|
+
});
|
|
4001
|
+
}
|
|
4002
|
+
catch (err) {
|
|
4003
|
+
emitWriteBoundaryWarning(`post-copy verification failed: ${String(err)}`);
|
|
4004
|
+
throw err;
|
|
4005
|
+
}
|
|
4006
|
+
});
|
|
4007
|
+
}
|
|
4008
|
+
finally {
|
|
4009
|
+
await source.handle.close().catch(() => { });
|
|
4010
|
+
}
|
|
4011
|
+
}
|
|
4012
|
+
async function resolvePinnedWriteTargetInRoot(root, relativePath, requestedMode) {
|
|
4013
|
+
const { rootReal, rootWithSep, resolved } = await resolvePathInRoot(root, relativePath);
|
|
4014
|
+
try {
|
|
4015
|
+
await assertNoPathAliasEscape({
|
|
4016
|
+
absolutePath: resolved,
|
|
4017
|
+
rootPath: rootReal,
|
|
4018
|
+
boundaryLabel: "root",
|
|
4019
|
+
});
|
|
4020
|
+
}
|
|
4021
|
+
catch (err) {
|
|
4022
|
+
throw new errors_FsSafeError("path-alias", "path alias escape blocked", { cause: err });
|
|
4023
|
+
}
|
|
4024
|
+
// resolvePathInRoot already enforces isPathInside, so any actual escape
|
|
4025
|
+
// is rejected upstream.
|
|
4026
|
+
const relativeResolved = external_node_path_.relative(rootReal, resolved);
|
|
4027
|
+
if (external_node_path_.isAbsolute(relativeResolved)) {
|
|
4028
|
+
throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
|
|
4029
|
+
}
|
|
4030
|
+
const relativePosix = relativeResolved
|
|
4031
|
+
? relativeResolved.split(external_node_path_.sep).join(external_node_path_.posix.sep)
|
|
4032
|
+
: "";
|
|
4033
|
+
const basename = external_node_path_.posix.basename(relativePosix);
|
|
4034
|
+
if (!basename || basename === "." || basename === "/") {
|
|
4035
|
+
throw new errors_FsSafeError("invalid-path", "invalid target path");
|
|
4036
|
+
}
|
|
4037
|
+
let mode = requestedMode ?? 0o600;
|
|
4038
|
+
try {
|
|
4039
|
+
const opened = await openFileInRoot(root, {
|
|
4040
|
+
relativePath,
|
|
4041
|
+
hardlinks: "reject",
|
|
4042
|
+
nonBlockingRead: true,
|
|
4043
|
+
});
|
|
4044
|
+
try {
|
|
4045
|
+
mode = requestedMode ?? (opened.stat.mode & 0o777);
|
|
4046
|
+
if (!path_isPathInside(rootWithSep, opened.realPath)) {
|
|
4047
|
+
throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
|
|
4048
|
+
}
|
|
4049
|
+
}
|
|
4050
|
+
finally {
|
|
4051
|
+
await opened.handle.close().catch(() => { });
|
|
821
4052
|
}
|
|
4053
|
+
}
|
|
4054
|
+
catch (err) {
|
|
4055
|
+
if (!(err instanceof errors_FsSafeError) || err.code !== "not-found") {
|
|
4056
|
+
throw err;
|
|
4057
|
+
}
|
|
4058
|
+
}
|
|
4059
|
+
return {
|
|
4060
|
+
rootReal,
|
|
4061
|
+
targetPath: resolved,
|
|
4062
|
+
relativeParentPath: external_node_path_.posix.dirname(relativePosix) === "." ? "" : external_node_path_.posix.dirname(relativePosix),
|
|
4063
|
+
basename,
|
|
4064
|
+
mode: mode || 0o600,
|
|
822
4065
|
};
|
|
823
4066
|
}
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
4067
|
+
async function resolvePinnedPathInRoot(root, params) {
|
|
4068
|
+
return await resolvePinnedOperationPathInRoot(root, {
|
|
4069
|
+
allowRoot: params.allowRoot,
|
|
4070
|
+
relativePath: params.relativePath,
|
|
4071
|
+
policy: PATH_ALIAS_POLICIES.strict,
|
|
4072
|
+
});
|
|
4073
|
+
}
|
|
4074
|
+
async function resolvePinnedRemovePathInRoot(root, relativePath) {
|
|
4075
|
+
return await resolvePinnedOperationPathInRoot(root, {
|
|
4076
|
+
relativePath,
|
|
4077
|
+
policy: PATH_ALIAS_POLICIES.unlinkTarget,
|
|
4078
|
+
});
|
|
4079
|
+
}
|
|
4080
|
+
async function resolvePinnedOperationPathInRoot(root, params) {
|
|
4081
|
+
const resolved = await resolvePinnedRootPathInRoot(root, {
|
|
4082
|
+
relativePath: params.relativePath,
|
|
4083
|
+
policy: params.policy,
|
|
4084
|
+
});
|
|
4085
|
+
const relativeResolved = external_node_path_.relative(resolved.rootReal, resolved.canonicalPath);
|
|
4086
|
+
if ((relativeResolved === "" || relativeResolved === ".") && params.allowRoot === true) {
|
|
4087
|
+
return { rootReal: resolved.rootReal, resolved: resolved.canonicalPath, relativePosix: "" };
|
|
4088
|
+
}
|
|
4089
|
+
const firstSegment = relativeResolved.split(external_node_path_.sep)[0];
|
|
4090
|
+
if (relativeResolved === "" ||
|
|
4091
|
+
relativeResolved === "." ||
|
|
4092
|
+
firstSegment === ".." ||
|
|
4093
|
+
external_node_path_.isAbsolute(relativeResolved)) {
|
|
4094
|
+
throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
|
|
4095
|
+
}
|
|
4096
|
+
const relativePosix = relativeResolved.split(external_node_path_.sep).join(external_node_path_.posix.sep);
|
|
4097
|
+
if (!path_isPathInside(resolved.rootWithSep, resolved.canonicalPath)) {
|
|
4098
|
+
throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
|
|
4099
|
+
}
|
|
4100
|
+
return { rootReal: resolved.rootReal, resolved: resolved.canonicalPath, relativePosix };
|
|
4101
|
+
}
|
|
4102
|
+
async function resolvePinnedRootPathInRoot(root, params) {
|
|
4103
|
+
const rootReal = root.rootReal;
|
|
4104
|
+
let resolved;
|
|
4105
|
+
try {
|
|
4106
|
+
resolved = await resolveRootPath({
|
|
4107
|
+
absolutePath: external_node_path_.resolve(rootReal, await expandRelativePathWithHome(params.relativePath)),
|
|
4108
|
+
rootPath: rootReal,
|
|
4109
|
+
rootCanonicalPath: rootReal,
|
|
4110
|
+
boundaryLabel: "root",
|
|
4111
|
+
policy: params.policy,
|
|
4112
|
+
});
|
|
4113
|
+
}
|
|
4114
|
+
catch (err) {
|
|
4115
|
+
throw new errors_FsSafeError("path-alias", "path alias escape blocked", { cause: err });
|
|
4116
|
+
}
|
|
4117
|
+
const rootWithSep = ensureTrailingSep(resolved.rootCanonicalPath);
|
|
4118
|
+
return {
|
|
4119
|
+
rootReal: resolved.rootCanonicalPath,
|
|
4120
|
+
rootWithSep,
|
|
4121
|
+
canonicalPath: resolved.canonicalPath,
|
|
4122
|
+
};
|
|
4123
|
+
}
|
|
4124
|
+
async function removePathFallback(resolved) {
|
|
4125
|
+
const guard = await directory_guard_createAsyncDirectoryGuard(external_node_path_.dirname(resolved.resolved));
|
|
4126
|
+
await getFsSafeTestHooks()?.beforeRootFallbackMutation?.("remove", resolved.resolved);
|
|
4127
|
+
await assertAsyncDirectoryGuard(guard);
|
|
4128
|
+
await ((await promises_.lstat(resolved.resolved)).isDirectory() ? promises_.rmdir(resolved.resolved) : promises_.rm(resolved.resolved));
|
|
4129
|
+
await assertAsyncDirectoryGuard(guard).catch(() => undefined);
|
|
4130
|
+
}
|
|
4131
|
+
async function mkdirPathFallback(resolved) {
|
|
4132
|
+
await mkdirPathComponentsWithGuards({
|
|
4133
|
+
rootReal: resolved.rootReal, targetPath: resolved.resolved,
|
|
4134
|
+
beforeComponent: async (componentPath) => await getFsSafeTestHooks()?.beforeRootFallbackMutation?.("mkdir", componentPath),
|
|
4135
|
+
});
|
|
4136
|
+
}
|
|
4137
|
+
async function statPathFallback(root, relativePath) {
|
|
4138
|
+
const resolved = await resolvePinnedPathInRoot(root, { relativePath, allowRoot: true });
|
|
4139
|
+
try {
|
|
4140
|
+
return pathStatFromStats(await promises_.lstat(resolved.resolved));
|
|
4141
|
+
}
|
|
4142
|
+
catch (error) {
|
|
4143
|
+
if (path_isNotFoundPathError(error)) {
|
|
4144
|
+
throw new errors_FsSafeError("not-found", "file not found", {
|
|
4145
|
+
cause: error instanceof Error ? error : undefined,
|
|
4146
|
+
});
|
|
4147
|
+
}
|
|
4148
|
+
throw error;
|
|
4149
|
+
}
|
|
4150
|
+
}
|
|
4151
|
+
async function listPathFallback(root, relativePath, withFileTypes) {
|
|
4152
|
+
const resolved = await resolvePinnedPathInRoot(root, { relativePath, allowRoot: true });
|
|
4153
|
+
try {
|
|
4154
|
+
const names = await promises_.readdir(resolved.resolved);
|
|
4155
|
+
const sortedNames = names.toSorted();
|
|
4156
|
+
if (!withFileTypes) {
|
|
4157
|
+
return sortedNames;
|
|
4158
|
+
}
|
|
4159
|
+
const entries = [];
|
|
4160
|
+
for (const name of sortedNames) {
|
|
4161
|
+
entries.push({
|
|
4162
|
+
name,
|
|
4163
|
+
...pathStatFromStats(await promises_.lstat(external_node_path_.join(resolved.resolved, name))),
|
|
4164
|
+
});
|
|
4165
|
+
}
|
|
4166
|
+
return entries;
|
|
4167
|
+
}
|
|
4168
|
+
catch (error) {
|
|
4169
|
+
if (path_isNotFoundPathError(error)) {
|
|
4170
|
+
throw new errors_FsSafeError("not-found", "directory not found", {
|
|
4171
|
+
cause: error instanceof Error ? error : undefined,
|
|
4172
|
+
});
|
|
4173
|
+
}
|
|
4174
|
+
throw error;
|
|
4175
|
+
}
|
|
4176
|
+
}
|
|
4177
|
+
async function movePathFallback(root, params) {
|
|
4178
|
+
const source = await resolvePathInRoot(root, params.fromRelative);
|
|
4179
|
+
await resolvePinnedRootPathInRoot(root, {
|
|
4180
|
+
relativePath: params.fromRelative,
|
|
4181
|
+
policy: PATH_ALIAS_POLICIES.strict,
|
|
4182
|
+
});
|
|
4183
|
+
const target = await resolvePathInRoot(root, params.toRelative);
|
|
4184
|
+
await resolvePinnedRootPathInRoot(root, {
|
|
4185
|
+
relativePath: params.toRelative,
|
|
4186
|
+
policy: PATH_ALIAS_POLICIES.unlinkTarget,
|
|
4187
|
+
});
|
|
4188
|
+
try {
|
|
4189
|
+
await assertNoPathAliasEscape({
|
|
4190
|
+
absolutePath: target.resolved,
|
|
4191
|
+
rootPath: target.rootReal,
|
|
4192
|
+
boundaryLabel: "root",
|
|
4193
|
+
});
|
|
4194
|
+
}
|
|
4195
|
+
catch (error) {
|
|
4196
|
+
throw new errors_FsSafeError("path-alias", "path alias escape blocked", {
|
|
4197
|
+
cause: error instanceof Error ? error : undefined,
|
|
4198
|
+
});
|
|
4199
|
+
}
|
|
4200
|
+
let sourceStat;
|
|
4201
|
+
try {
|
|
4202
|
+
sourceStat = await promises_.lstat(source.resolved);
|
|
4203
|
+
}
|
|
4204
|
+
catch (error) {
|
|
4205
|
+
if (path_isNotFoundPathError(error)) {
|
|
4206
|
+
throw new errors_FsSafeError("not-found", "file not found", {
|
|
4207
|
+
cause: error instanceof Error ? error : undefined,
|
|
4208
|
+
});
|
|
4209
|
+
}
|
|
4210
|
+
throw error;
|
|
4211
|
+
}
|
|
4212
|
+
if (sourceStat.isSymbolicLink()) {
|
|
4213
|
+
throw new errors_FsSafeError("symlink", "symlink not allowed");
|
|
4214
|
+
}
|
|
4215
|
+
if (sourceStat.isFile() && sourceStat.nlink > 1) {
|
|
4216
|
+
throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
|
|
4217
|
+
}
|
|
4218
|
+
if (!params.overwrite) {
|
|
4219
|
+
try {
|
|
4220
|
+
await promises_.lstat(target.resolved);
|
|
4221
|
+
throw new errors_FsSafeError("already-exists", "destination exists");
|
|
4222
|
+
}
|
|
4223
|
+
catch (error) {
|
|
4224
|
+
if (error instanceof errors_FsSafeError) {
|
|
4225
|
+
throw error;
|
|
4226
|
+
}
|
|
4227
|
+
if (!path_isNotFoundPathError(error)) {
|
|
4228
|
+
throw error;
|
|
4229
|
+
}
|
|
4230
|
+
}
|
|
4231
|
+
}
|
|
4232
|
+
const sourceParentGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_.dirname(source.resolved));
|
|
4233
|
+
const targetParentGuard = await directory_guard_createNearestExistingDirectoryGuard(target.rootReal, external_node_path_.dirname(target.resolved));
|
|
4234
|
+
await getFsSafeTestHooks()?.beforeRootFallbackMutation?.("move", target.resolved);
|
|
4235
|
+
await assertAsyncDirectoryGuard(sourceParentGuard);
|
|
4236
|
+
await assertAsyncDirectoryGuard(targetParentGuard);
|
|
4237
|
+
try {
|
|
4238
|
+
await promises_.rename(source.resolved, target.resolved);
|
|
4239
|
+
}
|
|
4240
|
+
catch (error) {
|
|
4241
|
+
if (path_isNotFoundPathError(error)) {
|
|
4242
|
+
throw new errors_FsSafeError("not-found", "file not found", {
|
|
4243
|
+
cause: error instanceof Error ? error : undefined,
|
|
4244
|
+
});
|
|
4245
|
+
}
|
|
4246
|
+
if (hasNodeErrorCode(error, "EEXIST")) {
|
|
4247
|
+
throw new errors_FsSafeError("already-exists", "destination exists", {
|
|
4248
|
+
cause: error instanceof Error ? error : undefined,
|
|
4249
|
+
});
|
|
4250
|
+
}
|
|
4251
|
+
throw error;
|
|
4252
|
+
}
|
|
4253
|
+
await assertAsyncDirectoryGuard(targetParentGuard).catch(() => undefined);
|
|
4254
|
+
}
|
|
4255
|
+
async function writeFileFallback(root, params) {
|
|
4256
|
+
if (params.overwrite === false) {
|
|
4257
|
+
await writeMissingFileFallback(root, params);
|
|
4258
|
+
return;
|
|
4259
|
+
}
|
|
4260
|
+
const target = await openWritableFileInRoot(root, {
|
|
4261
|
+
relativePath: params.relativePath,
|
|
4262
|
+
mkdir: params.mkdir,
|
|
4263
|
+
mode: params.mode,
|
|
4264
|
+
truncateExisting: false,
|
|
4265
|
+
});
|
|
4266
|
+
const destinationPath = target.realPath;
|
|
4267
|
+
const mode = params.mode ?? (target.stat.mode & 0o777);
|
|
4268
|
+
await target.handle.close().catch(() => { });
|
|
4269
|
+
const destinationGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_.dirname(destinationPath));
|
|
4270
|
+
let tempPath = null;
|
|
4271
|
+
let unregisterTempPath = null;
|
|
4272
|
+
try {
|
|
4273
|
+
tempPath = buildAtomicWriteTempPath(destinationPath);
|
|
4274
|
+
unregisterTempPath = registerTempPathForExit(tempPath);
|
|
4275
|
+
const writtenStat = await writeTempFileForAtomicReplace({
|
|
4276
|
+
tempPath,
|
|
4277
|
+
data: params.data,
|
|
4278
|
+
encoding: params.encoding,
|
|
4279
|
+
mode: mode || 0o600,
|
|
4280
|
+
});
|
|
4281
|
+
const commitTempPath = tempPath;
|
|
4282
|
+
await withAsyncDirectoryGuards([destinationGuard], async () => {
|
|
4283
|
+
await promises_.rename(commitTempPath, destinationPath);
|
|
4284
|
+
});
|
|
4285
|
+
tempPath = null;
|
|
4286
|
+
unregisterTempPath();
|
|
4287
|
+
unregisterTempPath = null;
|
|
4288
|
+
try {
|
|
4289
|
+
await verifyAtomicWriteResult({
|
|
4290
|
+
root,
|
|
4291
|
+
targetPath: destinationPath,
|
|
4292
|
+
expectedIdentity: writtenStat,
|
|
4293
|
+
});
|
|
4294
|
+
}
|
|
4295
|
+
catch (err) {
|
|
4296
|
+
emitWriteBoundaryWarning(`post-write verification failed: ${String(err)}`);
|
|
4297
|
+
throw err;
|
|
4298
|
+
}
|
|
4299
|
+
}
|
|
4300
|
+
finally {
|
|
4301
|
+
if (tempPath) {
|
|
4302
|
+
await promises_.rm(tempPath, { force: true }).catch(() => { });
|
|
4303
|
+
}
|
|
4304
|
+
unregisterTempPath?.();
|
|
4305
|
+
}
|
|
4306
|
+
}
|
|
4307
|
+
async function writeMissingFileFallback(root, params) {
|
|
4308
|
+
const { rootReal, resolved } = await resolvePathInRoot(root, params.relativePath);
|
|
4309
|
+
try {
|
|
4310
|
+
await assertNoPathAliasEscape({
|
|
4311
|
+
absolutePath: resolved,
|
|
4312
|
+
rootPath: rootReal,
|
|
4313
|
+
boundaryLabel: "root",
|
|
4314
|
+
});
|
|
4315
|
+
}
|
|
4316
|
+
catch (err) {
|
|
4317
|
+
throw new errors_FsSafeError("path-alias", "path alias escape blocked", { cause: err });
|
|
4318
|
+
}
|
|
4319
|
+
if (params.mkdir !== false) {
|
|
4320
|
+
await promises_.mkdir(external_node_path_.dirname(resolved), { recursive: true });
|
|
4321
|
+
}
|
|
4322
|
+
const parentGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_.dirname(resolved));
|
|
4323
|
+
let created = false;
|
|
4324
|
+
try {
|
|
4325
|
+
const { handle, writtenStat } = await withAsyncDirectoryGuards([parentGuard], async () => {
|
|
4326
|
+
const handle = await promises_.open(resolved, OPEN_WRITE_CREATE_FLAGS, params.mode ?? 0o600);
|
|
4327
|
+
created = true;
|
|
4328
|
+
try {
|
|
4329
|
+
if (typeof params.data === "string") {
|
|
4330
|
+
await handle.writeFile(params.data, params.encoding ?? "utf8");
|
|
4331
|
+
}
|
|
4332
|
+
else {
|
|
4333
|
+
await handle.writeFile(params.data);
|
|
4334
|
+
}
|
|
4335
|
+
return { handle, writtenStat: await handle.stat() };
|
|
4336
|
+
}
|
|
4337
|
+
catch (error) {
|
|
4338
|
+
await handle.close().catch(() => undefined);
|
|
4339
|
+
throw error;
|
|
4340
|
+
}
|
|
4341
|
+
}, {
|
|
4342
|
+
onPostGuardFailure: async ({ handle }) => {
|
|
4343
|
+
created = false; // Parent is untrusted now; skip outer path cleanup by name.
|
|
4344
|
+
await handle.close().catch(() => undefined);
|
|
4345
|
+
},
|
|
4346
|
+
});
|
|
4347
|
+
await handle.close();
|
|
4348
|
+
await verifyAtomicWriteResult({
|
|
4349
|
+
root,
|
|
4350
|
+
targetPath: resolved,
|
|
4351
|
+
expectedIdentity: writtenStat,
|
|
4352
|
+
});
|
|
4353
|
+
created = false;
|
|
4354
|
+
}
|
|
4355
|
+
catch (err) {
|
|
4356
|
+
if (hasNodeErrorCode(err, "EEXIST")) {
|
|
4357
|
+
throw new errors_FsSafeError("already-exists", "file already exists", {
|
|
4358
|
+
cause: err instanceof Error ? err : undefined,
|
|
4359
|
+
});
|
|
4360
|
+
}
|
|
4361
|
+
throw err;
|
|
4362
|
+
}
|
|
4363
|
+
finally {
|
|
4364
|
+
if (created) {
|
|
4365
|
+
await promises_.rm(resolved, { force: true }).catch(() => undefined);
|
|
4366
|
+
}
|
|
4367
|
+
}
|
|
4368
|
+
}
|
|
4369
|
+
async function copyFileFallback(root, params, source) {
|
|
4370
|
+
let target = null;
|
|
4371
|
+
let sourceClosedByStream = false;
|
|
4372
|
+
let targetClosedByUs = false;
|
|
4373
|
+
let tempHandle = null;
|
|
4374
|
+
let tempPath = null;
|
|
4375
|
+
let unregisterTempPath = null;
|
|
4376
|
+
let tempClosedByStream = false;
|
|
4377
|
+
try {
|
|
4378
|
+
target = await openWritableFileInRoot(root, {
|
|
4379
|
+
relativePath: params.relativePath,
|
|
4380
|
+
mkdir: params.mkdir,
|
|
4381
|
+
mode: params.mode,
|
|
4382
|
+
truncateExisting: false,
|
|
4383
|
+
});
|
|
4384
|
+
const destinationPath = target.realPath;
|
|
4385
|
+
const mode = params.mode ?? (target.stat.mode & 0o777);
|
|
4386
|
+
await target.handle.close().catch(() => { });
|
|
4387
|
+
targetClosedByUs = true;
|
|
4388
|
+
const destinationGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_.dirname(destinationPath));
|
|
4389
|
+
tempPath = buildAtomicWriteTempPath(destinationPath);
|
|
4390
|
+
unregisterTempPath = registerTempPathForExit(tempPath);
|
|
4391
|
+
tempHandle = await promises_.open(tempPath, OPEN_WRITE_CREATE_FLAGS, mode || 0o600);
|
|
4392
|
+
const sourceStream = createBoundedReadStream(source, params.maxBytes);
|
|
4393
|
+
const targetStream = tempHandle.createWriteStream();
|
|
4394
|
+
sourceStream.once("close", () => {
|
|
4395
|
+
sourceClosedByStream = true;
|
|
4396
|
+
});
|
|
4397
|
+
targetStream.once("close", () => {
|
|
4398
|
+
tempClosedByStream = true;
|
|
4399
|
+
});
|
|
4400
|
+
await (0,external_node_stream_promises_.pipeline)(sourceStream, targetStream);
|
|
4401
|
+
const writtenStat = await promises_.stat(tempPath);
|
|
4402
|
+
if (!tempClosedByStream) {
|
|
4403
|
+
await tempHandle.close().catch(() => { });
|
|
4404
|
+
tempClosedByStream = true;
|
|
4405
|
+
}
|
|
4406
|
+
tempHandle = null;
|
|
4407
|
+
const commitTempPath = tempPath;
|
|
4408
|
+
await withAsyncDirectoryGuards([destinationGuard], async () => {
|
|
4409
|
+
await promises_.rename(commitTempPath, destinationPath);
|
|
4410
|
+
});
|
|
4411
|
+
tempPath = null;
|
|
4412
|
+
unregisterTempPath();
|
|
4413
|
+
unregisterTempPath = null;
|
|
4414
|
+
try {
|
|
4415
|
+
await verifyAtomicWriteResult({
|
|
4416
|
+
root,
|
|
4417
|
+
targetPath: destinationPath,
|
|
4418
|
+
expectedIdentity: writtenStat,
|
|
4419
|
+
});
|
|
4420
|
+
}
|
|
4421
|
+
catch (err) {
|
|
4422
|
+
emitWriteBoundaryWarning(`post-copy verification failed: ${String(err)}`);
|
|
4423
|
+
throw err;
|
|
4424
|
+
}
|
|
4425
|
+
}
|
|
4426
|
+
catch (err) {
|
|
4427
|
+
if (target?.createdForWrite) {
|
|
4428
|
+
await promises_.rm(target.realPath, { force: true }).catch(() => { });
|
|
4429
|
+
}
|
|
4430
|
+
throw err;
|
|
4431
|
+
}
|
|
4432
|
+
finally {
|
|
4433
|
+
if (!sourceClosedByStream) {
|
|
4434
|
+
await source.handle.close().catch(() => { });
|
|
4435
|
+
}
|
|
4436
|
+
if (tempHandle && !tempClosedByStream) {
|
|
4437
|
+
await tempHandle.close().catch(() => { });
|
|
4438
|
+
}
|
|
4439
|
+
if (tempPath) {
|
|
4440
|
+
await promises_.rm(tempPath, { force: true }).catch(() => { });
|
|
4441
|
+
}
|
|
4442
|
+
unregisterTempPath?.();
|
|
4443
|
+
if (target && !targetClosedByUs) {
|
|
4444
|
+
await target.handle.close().catch(() => { });
|
|
4445
|
+
}
|
|
4446
|
+
}
|
|
832
4447
|
}
|
|
833
4448
|
|
|
834
|
-
// EXTERNAL MODULE: external "node:fs"
|
|
835
|
-
var external_node_fs_ = __webpack_require__(3024);
|
|
836
4449
|
;// CONCATENATED MODULE: ../core/src/gateways/file-system-utils.ts
|
|
837
4450
|
/**
|
|
838
4451
|
* Shared file system utilities for gateways.
|
|
839
4452
|
*/
|
|
840
4453
|
|
|
841
4454
|
|
|
4455
|
+
|
|
842
4456
|
/**
|
|
843
4457
|
* Checks if a file or directory exists.
|
|
844
4458
|
*/ async function fileExists(path) {
|
|
845
4459
|
try {
|
|
846
|
-
await
|
|
4460
|
+
await access(path);
|
|
847
4461
|
return true;
|
|
848
4462
|
} catch {
|
|
849
4463
|
return false;
|
|
@@ -852,9 +4466,92 @@ var external_node_fs_ = __webpack_require__(3024);
|
|
|
852
4466
|
function isPathWithinRoot(rootPath, candidatePath) {
|
|
853
4467
|
return candidatePath === rootPath || candidatePath.startsWith(`${rootPath}${external_node_path_.sep}`);
|
|
854
4468
|
}
|
|
4469
|
+
function mapFsSafeError(error, relativePath) {
|
|
4470
|
+
if (error instanceof errors_FsSafeError) {
|
|
4471
|
+
switch(error.code){
|
|
4472
|
+
case "outside-workspace":
|
|
4473
|
+
case "invalid-path":
|
|
4474
|
+
throw new Error(`Resolved path is outside target directory: ${relativePath}`, {
|
|
4475
|
+
cause: error
|
|
4476
|
+
});
|
|
4477
|
+
case "path-alias":
|
|
4478
|
+
case "symlink":
|
|
4479
|
+
throw new Error(`Symlinks are not allowed: path contains symbolic link: ${relativePath}`, {
|
|
4480
|
+
cause: error
|
|
4481
|
+
});
|
|
4482
|
+
case "too-large":
|
|
4483
|
+
throw new Error(`File ${relativePath} exceeds size limit: ${error.message}`, {
|
|
4484
|
+
cause: error
|
|
4485
|
+
});
|
|
4486
|
+
default:
|
|
4487
|
+
throw error;
|
|
4488
|
+
}
|
|
4489
|
+
}
|
|
4490
|
+
throw error;
|
|
4491
|
+
}
|
|
4492
|
+
async function createSafeRoot(targetDir, maxBytes) {
|
|
4493
|
+
return root_impl_root(targetDir, {
|
|
4494
|
+
hardlinks: "reject",
|
|
4495
|
+
maxBytes,
|
|
4496
|
+
symlinks: "reject"
|
|
4497
|
+
});
|
|
4498
|
+
}
|
|
4499
|
+
async function readTextWithinRoot(targetDir, relativePath, maxBytes) {
|
|
4500
|
+
try {
|
|
4501
|
+
const safeRoot = await createSafeRoot(targetDir, maxBytes);
|
|
4502
|
+
return await safeRoot.readText(relativePath, {
|
|
4503
|
+
maxBytes
|
|
4504
|
+
});
|
|
4505
|
+
} catch (error) {
|
|
4506
|
+
mapFsSafeError(error, relativePath);
|
|
4507
|
+
}
|
|
4508
|
+
}
|
|
4509
|
+
async function listDirectoryWithinRoot(targetDir, relativePath) {
|
|
4510
|
+
try {
|
|
4511
|
+
const safeRoot = await createSafeRoot(targetDir);
|
|
4512
|
+
const entries = await safeRoot.list(relativePath, {
|
|
4513
|
+
withFileTypes: true
|
|
4514
|
+
});
|
|
4515
|
+
return entries.map(toSafeDirEntry);
|
|
4516
|
+
} catch (error) {
|
|
4517
|
+
mapFsSafeError(error, relativePath);
|
|
4518
|
+
}
|
|
4519
|
+
}
|
|
4520
|
+
function toSafeDirEntry(entry) {
|
|
4521
|
+
return {
|
|
4522
|
+
name: entry.name,
|
|
4523
|
+
isDirectory: ()=>entry.isDirectory,
|
|
4524
|
+
isFile: ()=>entry.isFile,
|
|
4525
|
+
isSymbolicLink: ()=>entry.isSymbolicLink
|
|
4526
|
+
};
|
|
4527
|
+
}
|
|
4528
|
+
async function pathExistsWithinRoot(targetDir, relativePath) {
|
|
4529
|
+
try {
|
|
4530
|
+
const safeRoot = await createSafeRoot(targetDir);
|
|
4531
|
+
return await safeRoot.exists(relativePath);
|
|
4532
|
+
} catch (error) {
|
|
4533
|
+
mapFsSafeError(error, relativePath);
|
|
4534
|
+
}
|
|
4535
|
+
}
|
|
4536
|
+
/**
|
|
4537
|
+
* Returns true if the error originated from an fs-safe security check
|
|
4538
|
+
* (symlink, traversal, or size-limit violation). These errors carry a
|
|
4539
|
+
* FsSafeError as their `cause` and should be re-thrown rather than
|
|
4540
|
+
* silently swallowed by per-file error handlers.
|
|
4541
|
+
*/ function isFsSafeViolation(error) {
|
|
4542
|
+
return error instanceof Error && error.cause instanceof FsSafeError;
|
|
4543
|
+
}
|
|
4544
|
+
async function statWithinRoot(targetDir, relativePath) {
|
|
4545
|
+
try {
|
|
4546
|
+
const safeRoot = await createSafeRoot(targetDir);
|
|
4547
|
+
return await safeRoot.stat(relativePath);
|
|
4548
|
+
} catch (error) {
|
|
4549
|
+
mapFsSafeError(error, relativePath);
|
|
4550
|
+
}
|
|
4551
|
+
}
|
|
855
4552
|
/**
|
|
856
4553
|
* Resolves a relative path under targetDir and rejects traversal outside the root.
|
|
857
|
-
*/ async function
|
|
4554
|
+
*/ async function file_system_utils_resolvePathWithinRoot(targetDir, relativePath) {
|
|
858
4555
|
if (!relativePath) {
|
|
859
4556
|
throw new Error("Path must not be empty");
|
|
860
4557
|
}
|
|
@@ -896,7 +4593,7 @@ function isPathWithinRoot(rootPath, candidatePath) {
|
|
|
896
4593
|
/**
|
|
897
4594
|
* Resolves a relative path under targetDir and validates it does not pass through symlinks.
|
|
898
4595
|
*/ async function resolveSafePath(targetDir, relativePath) {
|
|
899
|
-
const resolvedPath = await
|
|
4596
|
+
const resolvedPath = await file_system_utils_resolvePathWithinRoot(targetDir, relativePath);
|
|
900
4597
|
await assertPathHasNoSymbolicLinks(targetDir, resolvedPath);
|
|
901
4598
|
return resolvedPath;
|
|
902
4599
|
}
|
|
@@ -954,38 +4651,31 @@ function isPathWithinRoot(rootPath, candidatePath) {
|
|
|
954
4651
|
*/
|
|
955
4652
|
|
|
956
4653
|
|
|
957
|
-
|
|
958
4654
|
/** Maximum agent file size: 1 MB */ const MAX_AGENT_FILE_BYTES = 1_048_576;
|
|
959
4655
|
/**
|
|
960
4656
|
* File system implementation of the agent lint gateway.
|
|
961
4657
|
*/ class FileSystemAgentLintGateway {
|
|
962
4658
|
async discoverAgents(targetDir) {
|
|
963
|
-
const agentsDir = (0,external_node_path_.join)(
|
|
964
|
-
let agentsDirStats;
|
|
4659
|
+
const agentsDir = (0,external_node_path_.join)(".github", "agents");
|
|
965
4660
|
try {
|
|
966
|
-
|
|
967
|
-
} catch (error) {
|
|
968
|
-
if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
|
|
4661
|
+
if (!await pathExistsWithinRoot(targetDir, agentsDir)) {
|
|
969
4662
|
return [];
|
|
970
4663
|
}
|
|
971
|
-
|
|
972
|
-
}
|
|
973
|
-
if (agentsDirStats.isSymbolicLink() || !agentsDirStats.isDirectory()) {
|
|
4664
|
+
} catch {
|
|
974
4665
|
return [];
|
|
975
4666
|
}
|
|
976
|
-
const resolvedAgentsDir = (0,external_node_path_.resolve)(agentsDir);
|
|
4667
|
+
const resolvedAgentsDir = (0,external_node_path_.resolve)(targetDir, agentsDir);
|
|
977
4668
|
const agents = [];
|
|
978
4669
|
const walk = async (dir)=>{
|
|
979
|
-
const entries = await (
|
|
980
|
-
withFileTypes: true
|
|
981
|
-
});
|
|
4670
|
+
const entries = await listDirectoryWithinRoot(targetDir, dir);
|
|
982
4671
|
for (const entry of entries){
|
|
983
4672
|
const name = entry.name;
|
|
984
4673
|
if (name.includes("..") || name.includes("/") || name.includes("\\")) {
|
|
985
4674
|
continue;
|
|
986
4675
|
}
|
|
987
4676
|
const entryPath = (0,external_node_path_.join)(dir, name);
|
|
988
|
-
const
|
|
4677
|
+
const absoluteEntryPath = (0,external_node_path_.join)(targetDir, entryPath);
|
|
4678
|
+
const resolvedPath = (0,external_node_path_.resolve)(absoluteEntryPath);
|
|
989
4679
|
const rel = (0,external_node_path_.relative)(resolvedAgentsDir, resolvedPath);
|
|
990
4680
|
if (rel.startsWith("..") || rel.startsWith(external_node_path_.sep)) {
|
|
991
4681
|
continue;
|
|
@@ -1005,7 +4695,7 @@ function isPathWithinRoot(rootPath, candidatePath) {
|
|
|
1005
4695
|
}
|
|
1006
4696
|
const agentName = name.endsWith(".agent.md") ? (0,external_node_path_.basename)(name, ".agent.md") : (0,external_node_path_.basename)(name, ".md");
|
|
1007
4697
|
agents.push({
|
|
1008
|
-
filePath:
|
|
4698
|
+
filePath: absoluteEntryPath,
|
|
1009
4699
|
agentName
|
|
1010
4700
|
});
|
|
1011
4701
|
}
|
|
@@ -1119,53 +4809,57 @@ function isPathWithinRoot(rootPath, candidatePath) {
|
|
|
1119
4809
|
* Supports GitHub Copilot, Claude Code, and community agent instruction formats.
|
|
1120
4810
|
*/
|
|
1121
4811
|
|
|
1122
|
-
|
|
1123
4812
|
/**
|
|
1124
4813
|
* File system implementation of the instruction file discovery gateway.
|
|
1125
4814
|
*/ class FileSystemInstructionFileDiscoveryGateway {
|
|
1126
4815
|
async discoverInstructionFiles(targetDir) {
|
|
1127
4816
|
const files = [];
|
|
1128
4817
|
// .github/copilot-instructions.md
|
|
1129
|
-
const copilotInstructions = (0,external_node_path_.join)(
|
|
1130
|
-
if (await
|
|
4818
|
+
const copilotInstructions = (0,external_node_path_.join)(".github", "copilot-instructions.md");
|
|
4819
|
+
if (await this.safePathExists(targetDir, copilotInstructions)) {
|
|
1131
4820
|
files.push({
|
|
1132
|
-
filePath: copilotInstructions,
|
|
4821
|
+
filePath: (0,external_node_path_.join)(targetDir, copilotInstructions),
|
|
1133
4822
|
format: "copilot-instructions"
|
|
1134
4823
|
});
|
|
1135
4824
|
}
|
|
1136
4825
|
// .github/instructions/*.md
|
|
1137
|
-
const instructionsDir = (0,external_node_path_.join)(
|
|
1138
|
-
await this.discoverMdFilesInDir(instructionsDir, "copilot-scoped", files);
|
|
4826
|
+
const instructionsDir = (0,external_node_path_.join)(".github", "instructions");
|
|
4827
|
+
await this.discoverMdFilesInDir(targetDir, instructionsDir, "copilot-scoped", files);
|
|
1139
4828
|
// .github/agents/*.md
|
|
1140
|
-
const agentsDir = (0,external_node_path_.join)(
|
|
1141
|
-
await this.discoverMdFilesInDir(agentsDir, "copilot-agent", files);
|
|
4829
|
+
const agentsDir = (0,external_node_path_.join)(".github", "agents");
|
|
4830
|
+
await this.discoverMdFilesInDir(targetDir, agentsDir, "copilot-agent", files);
|
|
1142
4831
|
// AGENTS.md at repo root
|
|
1143
|
-
const agentsMd =
|
|
1144
|
-
if (await
|
|
4832
|
+
const agentsMd = "AGENTS.md";
|
|
4833
|
+
if (await this.safePathExists(targetDir, agentsMd)) {
|
|
1145
4834
|
files.push({
|
|
1146
|
-
filePath: agentsMd,
|
|
4835
|
+
filePath: (0,external_node_path_.join)(targetDir, agentsMd),
|
|
1147
4836
|
format: "agents-md"
|
|
1148
4837
|
});
|
|
1149
4838
|
}
|
|
1150
4839
|
// CLAUDE.md at repo root
|
|
1151
|
-
const claudeMd =
|
|
1152
|
-
if (await
|
|
4840
|
+
const claudeMd = "CLAUDE.md";
|
|
4841
|
+
if (await this.safePathExists(targetDir, claudeMd)) {
|
|
1153
4842
|
files.push({
|
|
1154
|
-
filePath: claudeMd,
|
|
4843
|
+
filePath: (0,external_node_path_.join)(targetDir, claudeMd),
|
|
1155
4844
|
format: "claude-md"
|
|
1156
4845
|
});
|
|
1157
4846
|
}
|
|
1158
4847
|
return files;
|
|
1159
4848
|
}
|
|
1160
|
-
async
|
|
1161
|
-
|
|
4849
|
+
async safePathExists(targetDir, relativePath) {
|
|
4850
|
+
try {
|
|
4851
|
+
return await pathExistsWithinRoot(targetDir, relativePath);
|
|
4852
|
+
} catch {
|
|
4853
|
+
return false;
|
|
4854
|
+
}
|
|
4855
|
+
}
|
|
4856
|
+
async discoverMdFilesInDir(targetDir, dirPath, format, files) {
|
|
4857
|
+
if (!await this.safePathExists(targetDir, dirPath)) {
|
|
1162
4858
|
return;
|
|
1163
4859
|
}
|
|
1164
4860
|
try {
|
|
1165
|
-
const entries = await (
|
|
1166
|
-
|
|
1167
|
-
});
|
|
1168
|
-
const resolvedDirPath = (0,external_node_path_.resolve)(dirPath);
|
|
4861
|
+
const entries = await listDirectoryWithinRoot(targetDir, dirPath);
|
|
4862
|
+
const resolvedDirPath = (0,external_node_path_.resolve)(targetDir, dirPath);
|
|
1169
4863
|
for (const entry of entries){
|
|
1170
4864
|
if (entry.isSymbolicLink()) {
|
|
1171
4865
|
continue;
|
|
@@ -1178,7 +4872,7 @@ function isPathWithinRoot(rootPath, candidatePath) {
|
|
|
1178
4872
|
continue;
|
|
1179
4873
|
}
|
|
1180
4874
|
if (name.endsWith(".md")) {
|
|
1181
|
-
const filePath = (0,external_node_path_.join)(dirPath, name);
|
|
4875
|
+
const filePath = (0,external_node_path_.join)(targetDir, dirPath, name);
|
|
1182
4876
|
const resolvedFilePath = (0,external_node_path_.resolve)(filePath);
|
|
1183
4877
|
const rel = (0,external_node_path_.relative)(resolvedDirPath, resolvedFilePath);
|
|
1184
4878
|
if (rel.startsWith("..") || rel.startsWith(external_node_path_.sep)) {
|
|
@@ -1194,14 +4888,6 @@ function isPathWithinRoot(rootPath, candidatePath) {
|
|
|
1194
4888
|
// Skip directory if we can't read it
|
|
1195
4889
|
}
|
|
1196
4890
|
}
|
|
1197
|
-
async isSymlink(filePath) {
|
|
1198
|
-
try {
|
|
1199
|
-
const stats = await (0,promises_.lstat)(filePath);
|
|
1200
|
-
return stats.isSymbolicLink();
|
|
1201
|
-
} catch {
|
|
1202
|
-
return false;
|
|
1203
|
-
}
|
|
1204
|
-
}
|
|
1205
4891
|
}
|
|
1206
4892
|
/**
|
|
1207
4893
|
* Creates and returns the default instruction file discovery gateway.
|
|
@@ -29620,7 +33306,6 @@ const PackageJsonSchema = schemas_object({
|
|
|
29620
33306
|
*/
|
|
29621
33307
|
|
|
29622
33308
|
|
|
29623
|
-
|
|
29624
33309
|
/** Maximum skill file size: 1 MB */ const MAX_SKILL_FILE_BYTES = 1_048_576;
|
|
29625
33310
|
/**
|
|
29626
33311
|
* Skill directory locations to search for SKILL.md files.
|
|
@@ -29635,30 +33320,22 @@ const PackageJsonSchema = schemas_object({
|
|
|
29635
33320
|
async discoverSkills(targetDir) {
|
|
29636
33321
|
const skills = [];
|
|
29637
33322
|
for (const relativeDir of SKILL_DIRECTORIES){
|
|
29638
|
-
const
|
|
29639
|
-
const discovered = await this.discoverSkillsInDir(skillsDir);
|
|
33323
|
+
const discovered = await this.discoverSkillsInDir(targetDir, relativeDir);
|
|
29640
33324
|
skills.push(...discovered);
|
|
29641
33325
|
}
|
|
29642
33326
|
return skills;
|
|
29643
33327
|
}
|
|
29644
|
-
async discoverSkillsInDir(skillsDir) {
|
|
29645
|
-
let dirStats;
|
|
33328
|
+
async discoverSkillsInDir(targetDir, skillsDir) {
|
|
29646
33329
|
try {
|
|
29647
|
-
|
|
29648
|
-
} catch (error) {
|
|
29649
|
-
if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
|
|
33330
|
+
if (!await pathExistsWithinRoot(targetDir, skillsDir)) {
|
|
29650
33331
|
return [];
|
|
29651
33332
|
}
|
|
29652
|
-
|
|
29653
|
-
}
|
|
29654
|
-
if (dirStats.isSymbolicLink() || !dirStats.isDirectory()) {
|
|
33333
|
+
} catch {
|
|
29655
33334
|
return [];
|
|
29656
33335
|
}
|
|
29657
33336
|
let entries;
|
|
29658
33337
|
try {
|
|
29659
|
-
entries = await (
|
|
29660
|
-
withFileTypes: true
|
|
29661
|
-
});
|
|
33338
|
+
entries = await listDirectoryWithinRoot(targetDir, skillsDir);
|
|
29662
33339
|
} catch (error) {
|
|
29663
33340
|
if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
|
|
29664
33341
|
return [];
|
|
@@ -29673,20 +33350,16 @@ const PackageJsonSchema = schemas_object({
|
|
|
29673
33350
|
if (entry.name.includes("..") || entry.name.includes("/") || entry.name.includes("\\")) {
|
|
29674
33351
|
continue;
|
|
29675
33352
|
}
|
|
29676
|
-
const
|
|
29677
|
-
let
|
|
33353
|
+
const skillRelativePath = (0,external_node_path_.join)(skillsDir, entry.name, "SKILL.md");
|
|
33354
|
+
let hasSkillFile = false;
|
|
29678
33355
|
try {
|
|
29679
|
-
|
|
29680
|
-
} catch
|
|
29681
|
-
|
|
29682
|
-
skillStat = null;
|
|
29683
|
-
} else {
|
|
29684
|
-
throw error;
|
|
29685
|
-
}
|
|
33356
|
+
hasSkillFile = await pathExistsWithinRoot(targetDir, skillRelativePath);
|
|
33357
|
+
} catch {
|
|
33358
|
+
hasSkillFile = false;
|
|
29686
33359
|
}
|
|
29687
|
-
if (
|
|
33360
|
+
if (hasSkillFile) {
|
|
29688
33361
|
skills.push({
|
|
29689
|
-
filePath:
|
|
33362
|
+
filePath: (0,external_node_path_.join)(targetDir, skillRelativePath),
|
|
29690
33363
|
skillName: entry.name
|
|
29691
33364
|
});
|
|
29692
33365
|
}
|
|
@@ -29733,7 +33406,7 @@ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
|
|
|
29733
33406
|
const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
|
|
29734
33407
|
const _PATH_ROOT_RE = /^[/\\]|^[a-zA-Z]:[/\\]/;
|
|
29735
33408
|
const sep = "/";
|
|
29736
|
-
const
|
|
33409
|
+
const pathe_M_eThtNZ_normalize = function(path) {
|
|
29737
33410
|
if (path.length === 0) {
|
|
29738
33411
|
return ".";
|
|
29739
33412
|
}
|
|
@@ -29781,7 +33454,7 @@ const pathe_M_eThtNZ_join = function(...segments) {
|
|
|
29781
33454
|
path += seg;
|
|
29782
33455
|
}
|
|
29783
33456
|
}
|
|
29784
|
-
return
|
|
33457
|
+
return pathe_M_eThtNZ_normalize(path);
|
|
29785
33458
|
};
|
|
29786
33459
|
function pathe_M_eThtNZ_cwd() {
|
|
29787
33460
|
if (typeof process !== "undefined" && typeof process.cwd === "function") {
|
|
@@ -29877,7 +33550,7 @@ const pathe_M_eThtNZ_extname = function(p) {
|
|
|
29877
33550
|
const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
|
|
29878
33551
|
return match && match[1] || "";
|
|
29879
33552
|
};
|
|
29880
|
-
const
|
|
33553
|
+
const pathe_M_eThtNZ_relative = function(from, to) {
|
|
29881
33554
|
const _from = pathe_M_eThtNZ_resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
29882
33555
|
const _to = pathe_M_eThtNZ_resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
29883
33556
|
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) {
|
|
@@ -29934,7 +33607,7 @@ const pathe_M_eThtNZ_parse = function(p) {
|
|
|
29934
33607
|
};
|
|
29935
33608
|
};
|
|
29936
33609
|
const matchesGlob = (path, pattern) => {
|
|
29937
|
-
return zeptomatch(pattern,
|
|
33610
|
+
return zeptomatch(pattern, pathe_M_eThtNZ_normalize(path));
|
|
29938
33611
|
};
|
|
29939
33612
|
|
|
29940
33613
|
const pathe_M_eThtNZ_path = (/* unused pure expression or super */ null && ({
|
|
@@ -29946,10 +33619,10 @@ const pathe_M_eThtNZ_path = (/* unused pure expression or super */ null && ({
|
|
|
29946
33619
|
isAbsolute: isAbsolute,
|
|
29947
33620
|
join: pathe_M_eThtNZ_join,
|
|
29948
33621
|
matchesGlob: matchesGlob,
|
|
29949
|
-
normalize:
|
|
33622
|
+
normalize: pathe_M_eThtNZ_normalize,
|
|
29950
33623
|
normalizeString: normalizeString,
|
|
29951
33624
|
parse: pathe_M_eThtNZ_parse,
|
|
29952
|
-
relative:
|
|
33625
|
+
relative: pathe_M_eThtNZ_relative,
|
|
29953
33626
|
resolve: pathe_M_eThtNZ_resolve,
|
|
29954
33627
|
sep: sep,
|
|
29955
33628
|
toNamespacedPath: toNamespacedPath
|
|
@@ -29959,8 +33632,6 @@ const pathe_M_eThtNZ_path = (/* unused pure expression or super */ null && ({
|
|
|
29959
33632
|
|
|
29960
33633
|
// EXTERNAL MODULE: ../../node_modules/dotenv/lib/main.js
|
|
29961
33634
|
var lib_main = __webpack_require__(5599);
|
|
29962
|
-
// EXTERNAL MODULE: external "node:os"
|
|
29963
|
-
var external_node_os_ = __webpack_require__(8161);
|
|
29964
33635
|
// EXTERNAL MODULE: external "node:assert"
|
|
29965
33636
|
var external_node_assert_ = __webpack_require__(4589);
|
|
29966
33637
|
// EXTERNAL MODULE: external "node:v8"
|
|
@@ -31495,8 +35166,8 @@ function findFarthestFile(filename, options = {}) {
|
|
|
31495
35166
|
});
|
|
31496
35167
|
}
|
|
31497
35168
|
function _resolvePath(id, opts = {}) {
|
|
31498
|
-
if (id instanceof URL || id.startsWith("file://")) return
|
|
31499
|
-
if (isAbsolute(id)) return
|
|
35169
|
+
if (id instanceof URL || id.startsWith("file://")) return pathe_M_eThtNZ_normalize((0,external_node_url_.fileURLToPath)(id));
|
|
35170
|
+
if (isAbsolute(id)) return pathe_M_eThtNZ_normalize(id);
|
|
31500
35171
|
return resolveModulePath(id, {
|
|
31501
35172
|
...opts,
|
|
31502
35173
|
from: opts.from || opts.parent || opts.url
|
|
@@ -32105,7 +35776,7 @@ function tryResolve(id, options) {
|
|
|
32105
35776
|
extensions: SUPPORTED_EXTENSIONS,
|
|
32106
35777
|
cache: false
|
|
32107
35778
|
});
|
|
32108
|
-
return res ?
|
|
35779
|
+
return res ? pathe_M_eThtNZ_normalize(res) : void 0;
|
|
32109
35780
|
}
|
|
32110
35781
|
//#endregion
|
|
32111
35782
|
//#region src/types.ts
|
|
@@ -42338,7 +46009,7 @@ if (installedChunkData !== 0) { // 0 means "already installed".'
|
|
|
42338
46009
|
// module factories are used so entry inlining is disabled
|
|
42339
46010
|
// startup
|
|
42340
46011
|
// Load entry module and return exports
|
|
42341
|
-
var __webpack_exports__ = __webpack_require__(
|
|
46012
|
+
var __webpack_exports__ = __webpack_require__(2202);
|
|
42342
46013
|
var __webpack_exports__DEFAULT_LINT_RULES = __webpack_exports__.Kd;
|
|
42343
46014
|
var __webpack_exports__LintValidationError = __webpack_exports__.F5;
|
|
42344
46015
|
var __webpack_exports__createFormatter = __webpack_exports__.xi;
|