All files / kernel-platforms/src/capabilities/fs nodejs.ts

100% Statements 22/22
100% Branches 4/4
100% Functions 9/9
100% Lines 22/22

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                        2x 12x 10x   10x 10x 3x                     2x 12x 7x 7x 7x 3x                     2x 12x 12x   12x 10x 10x       2x 3x   4x 3x        
import { existsSync, lstatSync } from 'node:fs';
import fs from 'node:fs/promises';
import { relative } from 'node:path';
 
import { makeFsSpecification } from './shared.ts';
import type { PathLike, SyncPathCaveat } from './types.ts';
 
/**
 * Node.js specific symlink caveat factory using node:fs
 *
 * @returns A caveat function that validates a path against symlinks
 */
const makeNoSymlinksCaveat = (): SyncPathCaveat => {
  return (path: PathLike): void => {
    const pathString = path.toString();
    // eslint-disable-next-line n/no-sync
    const stats = lstatSync(pathString);
    if (stats.isSymbolicLink()) {
      throw new Error(`Symlinks are prohibited: ${pathString}`);
    }
  };
};
 
/**
 * Node.js specific root directory caveat factory using node:path
 *
 * @param rootDir - The root directory to validate paths against
 * @returns A caveat function that validates a path against the root directory
 */
const makeRootCaveat = (rootDir: string): SyncPathCaveat => {
  return (path: PathLike): void => {
    const pathString = path.toString();
    const relativePath = relative(rootDir, pathString);
    if (relativePath.startsWith('..')) {
      throw new Error(`Path ${pathString} is outside allowed root ${rootDir}`);
    }
  };
};
 
/**
 * Node.js specific path caveat factory using node:path tools
 *
 * @param rootDir - The root directory to validate paths against
 * @returns A caveat function that validates a path against configured constraints
 */
const makeNodejsPathCaveat = (rootDir: string): SyncPathCaveat => {
  const noSymlinks = makeNoSymlinksCaveat();
  const withinRoot = makeRootCaveat(rootDir);
 
  return harden((path: PathLike) => {
    noSymlinks(path);
    withinRoot(path);
  });
};
 
export const { configStruct, capabilityFactory } = makeFsSpecification({
  makeExistsSync: () => existsSync,
  promises: {
    makeReadFile: () => fs.readFile,
    makeAccess: () => fs.access,
  },
  makePathCaveat: makeNodejsPathCaveat,
});