All files / shared-utils/src path.ts

93.02% Statements 40/43
85.71% Branches 24/28
100% Functions 6/6
92.1% Lines 35/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98                        1535x 376x                                               376x 376x     376x 376x 376x   376x 376x 376x 1540x 1540x 3x   1535x       1535x     1535x 372x 113x   1163x 1163x 214x 214x 208x       109x             1163x 317x 317x       1535x 1535x 1535x 1535x 268x 268x   1267x     1267x      
import { isAbortError, throwIfAborted } from './abort.ts';
import { isMaliciousAssetPath } from './core.ts';
 
// `node:fs/promises` and `node:path` are loaded lazily inside `resolveFirstExistingPath` / `pathExists` so this
// module can be re-exported from `@be-music/shared-utils` (the package root) without dragging the Node built-ins into a
// browser bundle. Vite externalises `node:`-prefixed imports for browser targets, but only emits a runtime error
// if the externalised symbol is actually accessed; keeping these lazy confines that to the Node-specific call
// paths the browser never exercises.
type NodeFSPromises = typeof import('node:fs/promises');
type NodePath = typeof import('node:path');
let nodeFSPromisesPromise: Promise<NodeFSPromises> | undefined;
let nodePathPromise: Promise<NodePath> | undefined;
const loadNodeFSPromises = (): Promise<NodeFSPromises> => (nodeFSPromisesPromise ??= import('node:fs/promises'));
const loadNodePath = (): Promise<NodePath> => (nodePathPromise ??= import('node:path'));
 
/**
 * Resolves the first existing path among `candidates`, interpreted relative to `baseDir`. Each candidate is vetted
 * against the bmson 1.0.0 spec's malicious-path constraints before any filesystem access:
 *
 * - Absolute paths (`/etc/passwd`, `C:\\passwords.txt`), parent-directory traversals (`../../config.php`), and null
 *   bytes are rejected by `isMaliciousAssetPath` and never touch \`fs.access\`.
 * - The resolved absolute path is additionally pinned to `baseDir` — even if a candidate slipped through the per-string
 *   check, the post-resolve containment guard refuses to return paths outside the chart bundle.
 *
 * Set `fallbackConcurrency` to check that many fallback candidates at once after the first lookup misses. The
 * earliest existing candidate still wins.
 *
 * Both layers are defense-in-depth — the per-string predicate catches the obvious shapes before we even spawn a
 * syscall; the containment check catches anything subtle (symlinks, platform-specific path quirks, future additions to
 * the candidate generator).
 */
export async function resolveFirstExistingPath(
  baseDir: string,
  candidates: Iterable<string>,
  signal?: AbortSignal,
  options?: { fallbackConcurrency?: number },
): Promise<string | undefined> {
  const { resolve, sep } = await loadNodePath();
  const baseAbsolute = resolve(baseDir);
  // Trailing-separator normalized form lets the containment check work regardless of whether `baseDir` was passed with
  // or without a slash — `/foo` vs `/foo/` both produce `/foo/` for the prefix comparison.
  const baseAbsoluteWithSep = baseAbsolute.endsWith(sep) ? baseAbsolute : baseAbsolute + sep;
  const concurrency = options?.fallbackConcurrency ?? 1;
  Iif (!Number.isSafeInteger(concurrency) || concurrency < 1)
    throw new RangeError('Path fallback concurrency must be a positive integer.');
  const batch: string[] = [];
  let checkedFirst = false;
  for (const candidate of candidates) {
    throwIfAborted(signal);
    if (isMaliciousAssetPath(candidate)) {
      continue;
    }
    const absolute = resolve(baseDir, candidate);
    // Containment guard — the resolved path must either be `baseDir` itself or sit underneath it. Anything outside
    // (e.g. via symlinks the caller already followed, or via exotic candidate shapes that escaped the string check) is
    // treated as not-found.
    Iif (absolute !== baseAbsolute && !absolute.startsWith(baseAbsoluteWithSep)) {
      continue;
    }
    if (!checkedFirst || concurrency === 1) {
      if (await pathExists(absolute, signal)) return absolute;
      checkedFirst = true;
    } else {
      batch.push(absolute);
      if (batch.length === concurrency) {
        const match = await firstAccessiblePath(batch, signal);
        if (match !== undefined) return match;
        batch.length = 0;
      }
    }
  }
  return batch.length > 0 ? firstAccessiblePath(batch, signal) : undefined;
}
 
async function firstAccessiblePath(
  paths: readonly string[],
  signal: AbortSignal | undefined,
): Promise<string | undefined> {
  const exists = await Promise.all(paths.map((path) => pathExists(path, signal)));
  throwIfAborted(signal);
  return paths[exists.indexOf(true)];
}
 
async function pathExists(path: string, signal?: AbortSignal): Promise<boolean> {
  try {
    throwIfAborted(signal);
    const { access } = await loadNodeFSPromises();
    await access(path);
    throwIfAborted(signal);
    return true;
  } catch (error) {
    Iif (isAbortError(error)) {
      throw error;
    }
    return false;
  }
}