@triflare/fx 2.3.0 → 2.3.1-alpha.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@triflare/fx",
3
- "version": "2.3.0",
3
+ "version": "2.3.1-alpha.2",
4
4
  "description": "Code PenguinMod projects with text.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/product.yml CHANGED
@@ -1,7 +1,7 @@
1
1
  # Identity
2
2
  name: "Triflare Fx"
3
3
  command: "fx"
4
- version: "2.3.0"
4
+ version: "2.3.1-alpha.2"
5
5
  tagline: "Code PenguinMod projects with text."
6
6
  author: "Triflare"
7
7
  homepage: "https://github.com/triflare/fx"
package/src/build.js CHANGED
@@ -11,6 +11,11 @@ import { loadConfigFrom, DEFAULT_PROJECT, DEFAULT_FX } from "./config.js";
11
11
  import { sourceExtension } from "./brand.js";
12
12
  import { DEFAULT_TEST_PATTERN } from "./test/discover.js";
13
13
  import { DEFAULT_RUN_PATTERN } from "./run/pattern.js";
14
+ import {
15
+ externalFileAllowed,
16
+ findProjectRoot,
17
+ resolveProjectFile,
18
+ } from "./project-path.js";
14
19
 
15
20
  /**
16
21
  * @typedef {object} BuildOptions
@@ -28,6 +33,7 @@ import { DEFAULT_RUN_PATTERN } from "./run/pattern.js";
28
33
  * @property {string|null} [testPattern] Glob for test files to exclude.
29
34
  * @property {string|null} [runPattern] Glob for run files to exclude.
30
35
  * @property {boolean} [runMode] Compile run-only blocks instead of dropping them.
36
+ * @property {boolean} [allowOutsideFiles] Allow asset paths outside the project.
31
37
  */
32
38
 
33
39
  /**
@@ -154,13 +160,22 @@ export function build(options = {}) {
154
160
 
155
161
  // Assets are resolved relative to the file that references them, falling
156
162
  // back to the config directory (or the scanned directory) for inline
157
- // sources that have no path of their own.
163
+ // sources that have no path of their own. The enclosing checkout is the
164
+ // trusted root, so shared assets next to an example project keep working.
158
165
  const baseDir = configPath ? path.dirname(configPath) : dir;
166
+ const rootDir = findProjectRoot(baseDir);
167
+ const fileOptions = {
168
+ rootDir,
169
+ allowOutside: externalFileAllowed(options),
170
+ };
159
171
  const loadAsset = (assetPath, loc) => {
160
172
  const from = loc && loc.file ? path.dirname(loc.file) : baseDir;
161
- const resolved = path.isAbsolute(assetPath)
162
- ? assetPath
163
- : path.resolve(from, assetPath);
173
+ const resolved = resolveProjectFile(
174
+ assetPath,
175
+ from,
176
+ `asset ${JSON.stringify(String(assetPath))}`,
177
+ fileOptions,
178
+ );
164
179
  return fs.readFileSync(resolved);
165
180
  };
166
181
 
@@ -210,6 +210,8 @@ extensions into the project config.`,
210
210
  if (restored.loadEntries.length > 0) {
211
211
  const loaded = await loadExtensions(restored.loadEntries, {
212
212
  baseDir: outDir || cwd,
213
+ // Entries were just written by restoreExtensions into outDir.
214
+ allowOutside: true,
213
215
  });
214
216
  catalog = loaded.catalog;
215
217
  for (const warning of loaded.warnings) reporter.warn(warning);
package/src/cli/run.js CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  errorToJson,
16
16
  formatError,
17
17
  } from "./errors.js";
18
+ import { setExternalFilesAllowed } from "../project-path.js";
18
19
  import { createReporter } from "./reporter.js";
19
20
  import { createTheme } from "./theme.js";
20
21
 
@@ -39,6 +40,7 @@ function scanGlobalFlags(argv) {
39
40
  json: false,
40
41
  quiet: false,
41
42
  verbose: false,
43
+ allowExternalFiles: false,
42
44
  color: "auto",
43
45
  };
44
46
  for (let i = 0; i < argv.length; i += 1) {
@@ -46,6 +48,8 @@ function scanGlobalFlags(argv) {
46
48
  if (token === "--json") result.json = true;
47
49
  else if (token === "-q" || token === "--quiet") result.quiet = true;
48
50
  else if (token === "-v" || token === "--verbose") result.verbose = true;
51
+ else if (token === "--allow-external-files")
52
+ result.allowExternalFiles = true;
49
53
  else if (token === "--no-color") result.color = "never";
50
54
  else if (token === "--color") result.color = argv[++i] ?? "auto";
51
55
  else if (token.startsWith("--color="))
@@ -139,6 +143,10 @@ function createProgram(product, theme, color) {
139
143
  .option("--config <file>", "Use a specific config file")
140
144
  .option("--no-config", "Ignore the project config file")
141
145
  .option("--no-input", "Never prompt for input")
146
+ .option(
147
+ "--allow-external-files",
148
+ "Allow project config to reference files outside the project (unsafe for untrusted projects)",
149
+ )
142
150
  .option("-y, --yes", "Accept defaults and confirm destructive actions")
143
151
  .option(
144
152
  "--no-upgrade-prompt",
@@ -171,6 +179,7 @@ export async function run(argv = process.argv.slice(2)) {
171
179
  const product = loadProduct();
172
180
  const raw = scanGlobalFlags(argv);
173
181
  const color = resolveColor(raw);
182
+ setExternalFilesAllowed(raw.allowExternalFiles);
174
183
  const theme = createTheme({ product, color, stream: process.stdout });
175
184
  const reporter = createReporter({
176
185
  product,
package/src/config.js CHANGED
@@ -413,11 +413,54 @@ function isPlainObject(value) {
413
413
  return value != null && typeof value === "object" && !Array.isArray(value);
414
414
  }
415
415
 
416
- function mergePlain(target, source) {
416
+ // js-yaml parses `__proto__` as an ordinary own key. Merging it into a plain
417
+ // object would otherwise write through to Object.prototype.
418
+ const UNSAFE_CONFIG_KEYS = new Set(["__proto__", "constructor", "prototype"]);
419
+
420
+ /** @param {string} key @param {string} label */
421
+ function assertSafeKey(key, label) {
422
+ if (UNSAFE_CONFIG_KEYS.has(key))
423
+ throw new Error(
424
+ `${configFilename()}: unsafe key ${JSON.stringify(key)} in ${label}`,
425
+ );
426
+ }
427
+
428
+ /**
429
+ * Reject prototype-sensitive keys anywhere in a parsed YAML value before any
430
+ * normalization or merge can touch them.
431
+ * @param {unknown} value
432
+ * @param {string} label
433
+ */
434
+ function validateConfigKeys(value, label) {
435
+ if (Array.isArray(value)) {
436
+ value.forEach((item, index) =>
437
+ validateConfigKeys(item, `${label}[${index}]`),
438
+ );
439
+ return;
440
+ }
441
+ if (!isPlainObject(value)) return;
442
+ for (const [key, child] of Object.entries(value)) {
443
+ assertSafeKey(key, label);
444
+ validateConfigKeys(child, `${label}.${key}`);
445
+ }
446
+ }
447
+
448
+ function mergePlain(target, source, label = "configuration") {
417
449
  for (const [key, value] of Object.entries(source || {})) {
418
- if (isPlainObject(value) && isPlainObject(target[key]))
419
- mergePlain(target[key], value);
420
- else target[key] = value;
450
+ assertSafeKey(key, label);
451
+ if (
452
+ isPlainObject(value) &&
453
+ Object.hasOwn(target, key) &&
454
+ isPlainObject(target[key])
455
+ )
456
+ mergePlain(target[key], value, `${label}.${key}`);
457
+ else
458
+ Object.defineProperty(target, key, {
459
+ value,
460
+ writable: true,
461
+ enumerable: true,
462
+ configurable: true,
463
+ });
421
464
  }
422
465
  return target;
423
466
  }
@@ -452,6 +495,7 @@ export function normalizePackageTarget(value) {
452
495
  export function normalizePackage(raw = {}) {
453
496
  if (!isPlainObject(raw))
454
497
  throw new Error(`${configFilename()}: "package" must be a mapping`);
498
+ validateConfigKeys(raw, "package");
455
499
 
456
500
  const unknown = Object.keys(raw).filter(
457
501
  (key) =>
@@ -720,6 +764,7 @@ export function parseConfig(text) {
720
764
  throw new Error(
721
765
  `${configFilename()} must contain a mapping at the top level`,
722
766
  );
767
+ validateConfigKeys(raw, configFilename());
723
768
  if (raw.fx != null && (typeof raw.fx !== "object" || Array.isArray(raw.fx)))
724
769
  throw new Error(`${configFilename()} must contain an "fx" mapping`);
725
770
  const fx = normalizeFx(raw.fx || {});
package/src/dev.js CHANGED
@@ -38,6 +38,65 @@ function urlHost(host) {
38
38
  return host;
39
39
  }
40
40
 
41
+ function bareHost(host) {
42
+ return String(host)
43
+ .toLowerCase()
44
+ .replace(/^\[|\]$/g, "");
45
+ }
46
+
47
+ /**
48
+ * Hosts allowed to address this dev server. A wildcard bind accepts the
49
+ * machine's own interface addresses; a concrete bind accepts only that address
50
+ * plus loopback aliases.
51
+ */
52
+ function allowedHostnames(host) {
53
+ const allowed = new Set(["localhost", "127.0.0.1", "::1"]);
54
+ if (isWildcardHost(host)) {
55
+ for (const addresses of Object.values(os.networkInterfaces()))
56
+ for (const address of addresses || [])
57
+ allowed.add(bareHost(address.address));
58
+ } else allowed.add(bareHost(host));
59
+ return allowed;
60
+ }
61
+
62
+ /** Validate `Host` so a public page cannot reach the server via DNS rebinding. */
63
+ function requestHostAllowed(request, allowed, port) {
64
+ const raw = request.headers.host;
65
+ if (typeof raw !== "string" || raw === "") return false;
66
+ let url;
67
+ try {
68
+ url = new URL(`http://${raw}`);
69
+ } catch {
70
+ return false;
71
+ }
72
+ if (url.host.toLowerCase() !== raw.toLowerCase()) return false;
73
+ if (!allowed.has(bareHost(url.hostname))) return false;
74
+ return !url.port || Number(url.port) === port;
75
+ }
76
+
77
+ /** Browser-sent `Origin` must be this same local server, never a remote page. */
78
+ function requestOriginAllowed(request, allowed, port) {
79
+ const origin = request.headers.origin;
80
+ if (origin == null) return true; // non-browser clients send no Origin
81
+ if (typeof origin !== "string" || origin === "null") return false;
82
+ try {
83
+ const url = new URL(origin);
84
+ if (url.protocol !== "http:" || url.username || url.password) return false;
85
+ if (!allowed.has(bareHost(url.hostname))) return false;
86
+ return !url.port || Number(url.port) === port;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
92
+ function refuse(response, status, message) {
93
+ response.writeHead(status, {
94
+ "Content-Type": "text/plain; charset=utf-8",
95
+ "Cache-Control": "no-store",
96
+ });
97
+ response.end(`${message}\n`);
98
+ }
99
+
41
100
  function ignoredFile(filename) {
42
101
  if (!filename) return false;
43
102
  return filename.split(/[\\/]/).some((segment) => {
@@ -494,8 +553,23 @@ export async function startDevServer(options = {}) {
494
553
  timer.unref?.();
495
554
  }
496
555
 
556
+ const allowedHosts = allowedHostnames(host);
497
557
  const server = http.createServer((request, response) => {
498
- const url = new URL(request.url || "/", "http://localhost");
558
+ let url;
559
+ try {
560
+ url = new URL(request.url || "/", "http://localhost");
561
+ } catch {
562
+ refuse(response, 400, "Bad request");
563
+ return;
564
+ }
565
+
566
+ if (
567
+ !requestHostAllowed(request, allowedHosts, port) ||
568
+ !requestOriginAllowed(request, allowedHosts, port)
569
+ ) {
570
+ refuse(response, 403, "Forbidden");
571
+ return;
572
+ }
499
573
 
500
574
  if (url.pathname === DEV_EVENTS_PATH) {
501
575
  response.writeHead(200, {
package/src/extensions.js CHANGED
@@ -22,8 +22,8 @@
22
22
  * must be allowed to run unsandboxed when the project is opened.
23
23
  */
24
24
  import fs from "node:fs";
25
- import path from "node:path";
26
25
  import { getQuickJS } from "quickjs-emscripten";
26
+ import { resolveProjectFile } from "./project-path.js";
27
27
 
28
28
  /** `Scratch.BlockType` (values used by scratch-vm / PenguinMod). */
29
29
  export const BlockType = {
@@ -788,8 +788,16 @@ export function readExtensionDataUri(uri) {
788
788
  *
789
789
  * The raw buffer is retained so vendoring can lock exactly what the server
790
790
  * returned, even when the text decoder strips a byte-order mark.
791
+ *
792
+ * Local paths are confined to `baseDir` unless `allowOutside` is set; trusted
793
+ * callers (bundled features, already-contained vendor files) opt in explicitly.
791
794
  */
792
- export async function resolveSource(entry, baseDir, fetchImpl) {
795
+ export async function resolveSource(
796
+ entry,
797
+ baseDir,
798
+ fetchImpl,
799
+ { allowOutside = false } = {},
800
+ ) {
793
801
  const value = String(entry);
794
802
  if (/^data:/i.test(value)) {
795
803
  const source = readExtensionDataUri(value);
@@ -823,9 +831,12 @@ export async function resolveSource(entry, baseDir, fetchImpl) {
823
831
  url: value,
824
832
  };
825
833
  }
826
- const resolved = path.isAbsolute(value)
827
- ? value
828
- : path.resolve(baseDir, value);
834
+ const resolved = resolveProjectFile(
835
+ value,
836
+ baseDir,
837
+ `extension source ${JSON.stringify(value)}`,
838
+ { allowOutside },
839
+ );
829
840
  const buffer = fs.readFileSync(resolved);
830
841
  return {
831
842
  source: buffer.toString("utf8"),
@@ -888,7 +899,7 @@ export async function inspectExtension(source, filename = "extension") {
888
899
  * Load a list of extension references.
889
900
  *
890
901
  * @param {Array<string>} list Paths, `http(s)://` URLs or `data:` URIs.
891
- * @param {{baseDir?: string, fetchImpl?: typeof fetch, expectUnsandboxed?: string|string[], reportUnmatchedUnsandboxed?: boolean}} [options]
902
+ * @param {{baseDir?: string, fetchImpl?: typeof fetch, expectUnsandboxed?: string|string[], reportUnmatchedUnsandboxed?: boolean, allowOutside?: boolean}} [options]
892
903
  * `expectUnsandboxed` acknowledges extensions that are known to require
893
904
  * unsandboxed mode, silencing the warning for them. Set
894
905
  * `reportUnmatchedUnsandboxed` to false when a caller combines declarations
@@ -905,6 +916,7 @@ export async function loadExtensions(
905
916
  fetchImpl,
906
917
  expectUnsandboxed = [],
907
918
  reportUnmatchedUnsandboxed = true,
919
+ allowOutside = false,
908
920
  } = {},
909
921
  ) {
910
922
  const catalog = {};
@@ -931,6 +943,7 @@ export async function loadExtensions(
931
943
  entry,
932
944
  baseDir,
933
945
  fetchImpl,
946
+ { allowOutside },
934
947
  );
935
948
  const { infos, unsandboxed: needsUnsandboxed } =
936
949
  await evaluateExtensionAny(
package/src/features.js CHANGED
@@ -468,6 +468,9 @@ export async function loadFeatureExtensions({ configDir, config } = {}) {
468
468
  const loaded = await loadExtensions([absolute], {
469
469
  baseDir: configDir,
470
470
  reportUnmatchedUnsandboxed: false,
471
+ // Feature paths were already checked with assertInside above; core
472
+ // features ship as absolute paths inside this package.
473
+ allowOutside: true,
471
474
  });
472
475
  Object.assign(catalog, loaded.catalog);
473
476
  Object.assign(extensionUrls, loaded.extensionUrls);
@@ -47,6 +47,43 @@ export function marketplaceApiBase(apiBase) {
47
47
  ).replace(/\/+$/, "");
48
48
  }
49
49
 
50
+ /** Parse a secure URL, refusing credentials and non-HTTPS schemes. */
51
+ function secureUrl(value, label) {
52
+ let url;
53
+ try {
54
+ url = new URL(value);
55
+ } catch (error) {
56
+ throw new VendorError(`Invalid ${label}: ${String(value)}`, {
57
+ cause: error,
58
+ });
59
+ }
60
+ if (url.protocol !== "https:" || url.username || url.password)
61
+ throw new VendorError(
62
+ `Invalid ${label}: ${String(value)} must be an HTTPS URL without credentials`,
63
+ );
64
+ return url;
65
+ }
66
+
67
+ /**
68
+ * Origins trusted for compiled downloads: the official marketplace, the
69
+ * configured API origin, and any self-hosted CDN named explicitly by
70
+ * `FX_MARKETPLACE_DOWNLOAD_HOSTS` (comma/space separated).
71
+ */
72
+ export function marketplaceAllowedOrigins(base) {
73
+ const origins = new Set([
74
+ secureUrl(DEFAULT_MARKETPLACE_API, "marketplace API").origin,
75
+ ]);
76
+ origins.add(secureUrl(base, "marketplace API base").origin);
77
+ const extra = process.env.FX_MARKETPLACE_DOWNLOAD_HOSTS || "";
78
+ for (const entry of extra.split(/[\s,]+/).filter(Boolean)) {
79
+ const value = /^[a-z][a-z0-9+.-]*:\/\//i.test(entry)
80
+ ? entry
81
+ : `https://${entry}`;
82
+ origins.add(secureUrl(value, "FX_MARKETPLACE_DOWNLOAD_HOSTS").origin);
83
+ }
84
+ return origins;
85
+ }
86
+
50
87
  /** Fetch and parse a JSON response, turning failures into VendorError. */
51
88
  async function fetchJson(url, fetchImpl, label) {
52
89
  const fetchFn = fetchImpl || globalThis.fetch;
@@ -97,6 +134,8 @@ export async function resolveMarketplaceExtension({
97
134
  }) {
98
135
  const parsed = parseMarketplaceSource(source);
99
136
  const base = marketplaceApiBase(apiBase);
137
+ secureUrl(base, "marketplace API base");
138
+ const allowedOrigins = marketplaceAllowedOrigins(base);
100
139
  const label =
101
140
  parsed.ref === "latest"
102
141
  ? parsed.package
@@ -137,7 +176,11 @@ export async function resolveMarketplaceExtension({
137
176
  "refusing to vendor an unverifiable download.",
138
177
  );
139
178
 
140
- const downloaded = await fetchVendorSource(downloadUrl, { fetchImpl });
179
+ secureUrl(downloadUrl, "marketplace download URL");
180
+ const downloaded = await fetchVendorSource(downloadUrl, {
181
+ fetchImpl,
182
+ allowedOrigins,
183
+ });
141
184
  const actual = sha256(downloaded.buffer);
142
185
  if (actual !== digest)
143
186
  throw new VendorError(
package/src/package.js CHANGED
@@ -9,6 +9,7 @@ import fs from "node:fs";
9
9
  import path from "node:path";
10
10
  import { outputDirectory } from "./brand.js";
11
11
  import { DEFAULT_PACKAGE, normalizePackageTarget } from "./config.js";
12
+ import { externalFileAllowed, resolveProjectFile } from "./project-path.js";
12
13
 
13
14
  /** Turn a project name into a filesystem-friendly slug. */
14
15
  export function slugify(name) {
@@ -21,12 +22,17 @@ export function slugify(name) {
21
22
  );
22
23
  }
23
24
 
24
- /** @param {unknown} value @param {string} label @param {string} baseDir */
25
- function readTextSource(value, label, baseDir) {
25
+ /**
26
+ * @param {unknown} value
27
+ * @param {string} label
28
+ * @param {string} baseDir
29
+ * @param {{allowOutside?: boolean}} [options]
30
+ */
31
+ function readTextSource(value, label, baseDir, options) {
26
32
  if (value == null) return "";
27
33
  if (typeof value === "string") return value;
28
34
  if (value && typeof value === "object" && typeof value.file === "string") {
29
- const file = path.resolve(baseDir, value.file);
35
+ const file = resolveProjectFile(value.file, baseDir, label, options);
30
36
  try {
31
37
  return fs.readFileSync(file, "utf8");
32
38
  } catch (err) {
@@ -42,7 +48,7 @@ function readTextSource(value, label, baseDir) {
42
48
  * Resolve file-backed values and paths in a normalized `package:` block.
43
49
  *
44
50
  * @param {typeof DEFAULT_PACKAGE} [pkg]
45
- * @param {{baseDir?: string, projectName?: string}} [options]
51
+ * @param {{baseDir?: string, projectName?: string, allowOutside?: boolean}} [options]
46
52
  * @returns {{
47
53
  * target: string,
48
54
  * output: string|null,
@@ -58,17 +64,35 @@ function readTextSource(value, label, baseDir) {
58
64
  export function resolvePackageConfig(pkg = DEFAULT_PACKAGE, options = {}) {
59
65
  const baseDir = path.resolve(options.baseDir || process.cwd());
60
66
  const projectName = options.projectName || null;
67
+ const fileOptions = { allowOutside: externalFileAllowed(options) };
61
68
  return {
62
69
  target: normalizePackageTarget(pkg.target),
63
70
  output: pkg.output ? path.resolve(baseDir, pkg.output) : null,
64
71
  extract: Boolean(pkg.extract),
65
72
  name: pkg.name || projectName || null,
66
73
  version: pkg.version || null,
67
- icon: pkg.icon ? path.resolve(baseDir, pkg.icon) : null,
74
+ icon: pkg.icon
75
+ ? resolveProjectFile(pkg.icon, baseDir, "package.icon", fileOptions)
76
+ : null,
68
77
  custom: {
69
- js: readTextSource(pkg.custom?.js, "package.custom.js", baseDir),
70
- css: readTextSource(pkg.custom?.css, "package.custom.css", baseDir),
71
- html: readTextSource(pkg.custom?.html, "package.custom.html", baseDir),
78
+ js: readTextSource(
79
+ pkg.custom?.js,
80
+ "package.custom.js",
81
+ baseDir,
82
+ fileOptions,
83
+ ),
84
+ css: readTextSource(
85
+ pkg.custom?.css,
86
+ "package.custom.css",
87
+ baseDir,
88
+ fileOptions,
89
+ ),
90
+ html: readTextSource(
91
+ pkg.custom?.html,
92
+ "package.custom.html",
93
+ baseDir,
94
+ fileOptions,
95
+ ),
72
96
  },
73
97
  options: pkg.options || {},
74
98
  baseDir,
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Shared filesystem boundary for paths that come from an untrusted project.
3
+ *
4
+ * `fx.yml` and project sources are data, not trusted code. A `{ file: ... }`
5
+ * reference or an asset path must therefore stay inside the project: absolute
6
+ * paths, `../` traversal and symlinks that lead outside the project are refused
7
+ * unless the caller explicitly opts in with `--allow-external-files`.
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+
12
+ let externallyAllowed = false;
13
+
14
+ /** Opt in to external file references for this process (CLI use). */
15
+ export function setExternalFilesAllowed(value) {
16
+ externallyAllowed = Boolean(value);
17
+ }
18
+
19
+ /** Whether the caller explicitly allowed files outside the project. */
20
+ export function externalFileAllowed(options = {}) {
21
+ return (
22
+ options.allowOutside === true ||
23
+ options.allowExternalFiles === true ||
24
+ externallyAllowed ||
25
+ process.env.FX_ALLOW_EXTERNAL_FILES === "1"
26
+ );
27
+ }
28
+
29
+ /** Relative path from `base` to `target`, or null when it escapes. */
30
+ function relativeInside(base, target) {
31
+ const relative = path.relative(base, target);
32
+ if (
33
+ relative === ".." ||
34
+ relative.startsWith(`..${path.sep}`) ||
35
+ path.isAbsolute(relative)
36
+ )
37
+ return null;
38
+ return relative;
39
+ }
40
+
41
+ /**
42
+ * Nearest enclosing Git repository, or `dir` itself when there is none.
43
+ *
44
+ * This lets a project keep shared assets in a directory next to its `fx.yml`
45
+ * while still refusing paths outside the checkout.
46
+ */
47
+ export function findProjectRoot(dir) {
48
+ let current = path.resolve(dir);
49
+ for (;;) {
50
+ if (fs.existsSync(path.join(current, ".git"))) return current;
51
+ const parent = path.dirname(current);
52
+ if (parent === current) return path.resolve(dir);
53
+ current = parent;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Resolve a project-controlled file reference.
59
+ *
60
+ * @param {unknown} value Path from project config or source.
61
+ * @param {string} baseDir Directory the reference is relative to.
62
+ * @param {string} label Human-readable description used in errors.
63
+ * @param {{allowOutside?: boolean, rootDir?: string}} [options]
64
+ * @returns {string} Absolute path.
65
+ */
66
+ export function resolveProjectFile(value, baseDir, label, options = {}) {
67
+ const text = String(value ?? "");
68
+ if (!text) throw new Error(`${label}: empty file path`);
69
+ const root = path.resolve(options.rootDir || baseDir);
70
+ const allowOutside = externalFileAllowed(options);
71
+ const absolute = path.isAbsolute(text)
72
+ ? path.resolve(text)
73
+ : path.resolve(path.resolve(baseDir), text);
74
+
75
+ if (path.isAbsolute(text) && !allowOutside)
76
+ throw new Error(
77
+ `${label}: absolute paths are not allowed (${text}); use a project-relative path or pass --allow-external-files`,
78
+ );
79
+ if (!allowOutside && relativeInside(root, absolute) === null)
80
+ throw new Error(
81
+ `${label}: ${JSON.stringify(text)} is outside the project directory; use --allow-external-files to allow it explicitly`,
82
+ );
83
+
84
+ // Check links too: a symlinked ancestor (or the file itself) must not lead
85
+ // back outside the project. For missing files the longest existing prefix is
86
+ // checked, so the same rule applies where the file would be created.
87
+ if (!allowOutside) {
88
+ let probe = absolute;
89
+ while (!fs.existsSync(probe)) {
90
+ const parent = path.dirname(probe);
91
+ if (parent === probe) break;
92
+ probe = parent;
93
+ }
94
+ let rootReal;
95
+ let probeReal;
96
+ try {
97
+ rootReal = fs.realpathSync(root);
98
+ probeReal = fs.realpathSync(probe);
99
+ } catch (error) {
100
+ throw new Error(`${label}: could not resolve ${text}: ${error.message}`, {
101
+ cause: error,
102
+ });
103
+ }
104
+ if (relativeInside(rootReal, probeReal) === null)
105
+ throw new Error(
106
+ `${label}: ${JSON.stringify(text)} resolves outside the project through a symbolic link`,
107
+ );
108
+ }
109
+
110
+ return absolute;
111
+ }