Open History to see the last commit
1const APPIMAGE_RUNTIME_ENV_KEYS = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"] as const;
2// ld.so also splits LD_LIBRARY_PATH on semicolons.
3const APPIMAGE_PATH_LIKE_ENV_SEPARATORS = {
4 PATH: /:/,
5 LD_LIBRARY_PATH: /[:;]/,
6 XDG_DATA_DIRS: /:/,
7 GSETTINGS_SCHEMA_DIR: /:/,
8} as const;
9
10interface NormalizedPosixPath {
11 readonly absolute: boolean;
12 readonly parts: readonly string[];
13}
14
15function normalizePosixPath(value: string): NormalizedPosixPath {
16 return {
17 absolute: value.startsWith("/"),
18 parts: value.split("/").filter((part) => part !== "" && part !== "."),
19 };
20}
21
22function isPathSegmentUnderAppDir(segment: string, appDir: NormalizedPosixPath): boolean {
23 const normalized = normalizePosixPath(segment);
24 // Where ".." lands depends on symlinks, so such an entry may point outside the mount; keep it.
25 if (
26 normalized.absolute !== appDir.absolute ||
27 normalized.parts.length < appDir.parts.length ||
28 normalized.parts.includes("..")
29 ) {
30 return false;
31 }
32 return appDir.parts.every((part, index) => normalized.parts[index] === part);
33}
34
35// AppImage mount paths would make child commands resolve against the mount instead of the user's system.
36export function stripAppImageRuntimeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
37 if (env.APPIMAGE === undefined && env.APPDIR === undefined) return env;
38
39 const scrubbed: NodeJS.ProcessEnv = { ...env };
40 for (const key of APPIMAGE_RUNTIME_ENV_KEYS) {
41 delete scrubbed[key];
42 }
43
44 const appDir = env.APPDIR ? normalizePosixPath(env.APPDIR) : undefined;
45 if (appDir && appDir.parts.length > 0) {
46 for (const [key, separator] of Object.entries(APPIMAGE_PATH_LIKE_ENV_SEPARATORS)) {
47 const value = scrubbed[key];
48 if (value === undefined) continue;
49 const segments = value.split(separator);
50 const kept = segments.filter((segment) => !isPathSegmentUnderAppDir(segment, appDir));
51 if (kept.length === segments.length) continue;
52 if (kept.length === 0) {
53 delete scrubbed[key];
54 } else {
55 // Empty entries mean the current directory; a lone one must stay ":" since "" means none.
56 scrubbed[key] = kept.length === 1 && kept[0] === "" ? ":" : kept.join(":");
57 }
58 }
59 }
60
61 return scrubbed;
62}