Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readNode

Restrict file access with --permission

Allow a Node script to read its reports directory and see how a read outside that directory fails.

You have a Node script that reads a folder of reports. Give it read access to the reports directory so an accidental read of a sibling file fails.

Give the script two read paths

Use Node 22.13 or later in the 22 line. That release stabilized --permission. In a fresh directory, create a report and a sibling file for the denied read.

mkdir reports
printf 'weekly totals\n' > reports/week.txt
printf 'local settings\n' > settings.txt

You now have two files at different paths, with only the report inside the intended input folder.

// read-report.mjs
import { readFileSync } from 'node:fs'

const file = process.argv[2] ?? './reports/week.txt'

try {
  console.log(readFileSync(file, 'utf8').trim())
} catch (error) {
  if (error.code !== 'ERR_ACCESS_DENIED') throw error
  console.error(error.code, error.permission, file)
  process.exitCode = 1
}

The script prints the file contents on success or reports the denied permission and exits with code 1.

node --permission --allow-fs-read=./read-report.mjs --allow-fs-read=./reports/ ./read-report.mjs
node --permission --allow-fs-read=./read-report.mjs --allow-fs-read=./reports/ ./read-report.mjs ./settings.txt

The first invocation prints weekly totals. The second prints ERR_ACCESS_DENIED FileSystemRead ./settings.txt.

Keep the grant tied to the job

Each --allow-fs-read adds a path. The script gets permission to load its entry file and read the report directory. The explicit entry-file grant covers Node releases that require permission to load the script. Writes require a separate grant.

Run from the same directory as the fixture because both the grants and the example input paths are relative. For a scheduled job, use absolute paths or set its working directory. If your script imports more local modules, include their paths in the read grants and repeat the check with a file outside the input directory.

The Node permission model guards against accidental access by trusted code. Node follows symbolic links, so keep links to sensitive paths out of granted directories. Use OS-level isolation for untrusted code.