Skip to content

path-sink ​

A file path given to node:fs (every function @types/node declares with a path parameter, at each such argument: readFile, writeFile, rm, cp, rename, createReadStream, ..., promises and callbacks alike), new DatabaseSync(file), or the program spawn and execFile run, in code that input from outside the program can reach, from a value that isn't a constant the source shows or a SafePath. Idiomatic: reported where the project turns the idiomatic rules on. Reported by safe-ts check only, which sees the whole program: what a handler calls is a question about every file, so the editor and the lint plugin don't report it.

Why: ../ in the text leaves the directory the path was meant to stay in. readFile(`${uploads}/${name}`) with a name of ../../.env from a request reads the server's secrets, and the same in writeFile or rm changes files the program was never meant to touch.

Where it reports ​

Code is reachable when it is, or is called from (transitively, across files, through the calls the failure rules follow), a handler the runtime calls with data from outside:

  • an HTTP, HTTPS or HTTP/2 request handler: createServer(handler), createSecureServer, a server's request, upgrade, connect, checkContinue and checkExpectation events;
  • a net or tls server's connection, a net socket's data, a dgram socket's message (and createSocket(type, handler));
  • a WebSocket's message and a WebSocket server's connection (the ws pack);
  • a worker's or a MessagePort's message, a child process's message, and process's message (IPC from the parent).

A line read from stdin is not one: whoever runs the program types it, and what they give it is theirs here as everywhere. A process that does take hostile lines on stdin (a filter at the end of a pipeline) declares the slot in a pack of its own: "node:readline Interface#on": { "callback": "argument 1", "on": ["line"] }.

Everywhere else (a script's top level, a build tool, the start-up code that reads its config, a test) the rule is silent: a path there is the program's own, or what whoever runs it gave it. Calls are followed as the failure rules follow them: a function by name, a method through a receiver whose class or type is written (this.store.read(), deps.repo.load()), and a call through a declared function type (a field api: () => Handler called as deps.api()(req, res), an entry of a Record or a Map of handlers, an interface's member), which runs every function the program puts into that type: a function declared with it (const handle: Handler = ...), one given where it is expected (an object literal's member, an array's item, an argument), and the methods of the classes given as, or implementing, the interface.

Inside reachable code it is as strict as everywhere: a string path is reported, what the operator gives it is accepted where the code shows it, and a check of the project's own counts when it hands back a SafePath.

Which callback slots those are is data: the handlers of the Node map's sinks section, copied into the pack. A pack declares its framework's the same way (a router's handler, an RPC method), and the code those handlers run is reached too:

jsonc
"sinks": {
  "handlers": {
    "node:http createServer": { "callback": "every argument" },
    "node:http Server#on": { "callback": "argument 1", "on": ["request", "upgrade", "connect", "checkContinue", "checkExpectation"] },
    "my-router Router#get": { "callback": "arguments from 1" }   // a framework's, in its pack
  }
}

callback says which arguments are the handler (argument N, arguments N M, arguments from N, every argument); on, for an event emitter's on / once / addListener / prependListener, the events whose listener gets the outside data (the first argument names the event).

❌ Rejected: a name from the request, joined under a directory (a program rule, so not checked here)

ts
import { createServer } from "node:http";
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
import { isErr } from "@evobug_com/safe-ts-std/result";

async function servePublic(root: string, name: string): Promise<string> {
  const text = await readFile(`${root}/public/${name}`, "utf8"); // path-sink
  return isErr(text) ? "" : text;
}

export const server = createServer((req, res) => {
  servePublic(process.cwd(), req.url ?? "").then(
    (text) => res.end(text),
    () => res.end(),
  );
});

✅ Accepted: joined under the directory and checked to stay there

✓ Accepted0 diagnostics
ts
import { createServer } from "node:http";
import { join } from "node:path";
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
import { pathUnder } from "@evobug_com/safe-ts-std/path";
import { isErr } from "@evobug_com/safe-ts-std/result";

const PUBLIC = join(import.meta.dirname, "public");

async function servePublic(name: string): Promise<string> {
  const file = pathUnder(PUBLIC, name);
  if (isErr(file)) return "";
  const text = await readFile(file, "utf8");
  return isErr(text) ? "" : text;
}

export const server = createServer((req, res) => {
  servePublic(req.url ?? "").then(
    (text) => res.end(text),
    () => res.end(),
  );
});

✅ Accepted: a build step, which no handler reaches

✓ Accepted0 diagnostics
ts
import { readFileSync, writeFileSync } from "@evobug_com/safe-ts-feature-node/fs";
import { isErr } from "@evobug_com/safe-ts-std/result";

export function copy(from: string, to: string): boolean {
  const text = readFileSync(from, "utf8");
  return !isErr(text) && !isErr(writeFileSync(to, text));
}

Accepted: a SafePath (from pathUnder(root, ...parts), which resolves . and .. in the text and refuses what would leave root, an absolute part and a NUL), a constant the source shows, a number, a value of a literal type, and what whoever runs the program gives it: they can already open any file, so a path from them is theirs. Where the code shows it, that is process.argv (and parseArgs of it), process.env, where the module is (import.meta.dirname, import.meta.filename, __dirname), the working and temporary directories (process.cwd(), os.tmpdir(), os.homedir()), a directory mkdtemp just made, a name readdir or glob returned for such a directory, the text of a file at such a path and what JSON.parse or std's parseJson make of it, and path.join / resolve / normalize, fileURLToPath, new URL, templates and + of those: directly at the sink, through a const (or a let whose every value is one), an imported const, a destructuring (const [, , file] = process.argv), a for...of item, and a function (of this file or another) whose every return is one.

✅ Accepted: the operator's input, where the code shows it

✓ Accepted0 diagnostics
ts
import { readdirSync, readFileSync } from "@evobug_com/safe-ts-feature-node/fs";
import { join } from "node:path";
import { isErr } from "@evobug_com/safe-ts-std/result";

function dataDir(): string {
  return process.env.DATA_DIR ?? join(import.meta.dirname, "data");
}

export function loadAll(): readonly string[] {
  const names = readdirSync(dataDir());
  if (isErr(names)) return [];
  return names.map((name) => {
    const text = readFileSync(join(dataDir(), name), "utf8");
    return isErr(text) ? "" : text;
  });
}

In reachable code, a path that travels further than that (a parameter, a field, a function's string result) is the brand's: type it SafePath when it was checked under a root, or FromOperator when it is the operator's (fromOperator(text), from @evobug_com/safe-ts-std/operator, counted with the escape hatches: nothing checks the claim). A helper that takes a string path and reads it is reported in the helper; with the brand, its callers make one.

Migrating a resolver of your own ​

A server that serves files usually has a function that resolves a name under a root and refuses what leaves it, returning a string. The check is there, but its result is a plain string again, so every function it is handed to is a path-sink finding. Make the resolver the place the brand is made, and type what it is handed to with the brand:

❌ Rejected (a program rule, so not checked here)

ts
import { createServer } from "node:http";
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
import { relative, resolve } from "node:path";
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";

function resolveInside(root: string, rel: string): Result<string, "outside"> {
  const resolved = resolve(root, rel);
  return relative(root, resolved).startsWith("..") ? err("outside") : resolved;
}

async function serveFile(file: string): Promise<string> {
  const data = await readFile(file, "utf8"); // path-sink
  return isErr(data) ? "" : data;
}

async function serve(root: string, rel: string): Promise<string> {
  const file = resolveInside(root, rel);
  return isErr(file) ? "" : serveFile(file);
}

export const server = createServer((req, res) => {
  serve(process.env.PUBLIC_DIR ?? "public", req.url ?? "").then(
    (text) => res.end(text),
    () => res.end(),
  );
});

✅ Accepted: the resolver returns a SafePath, the root is the operator's

✓ Accepted0 diagnostics
ts
import { createServer } from "node:http";
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
import { type FromOperator, fromOperator } from "@evobug_com/safe-ts-std/operator";
import { pathUnder, type SafePath } from "@evobug_com/safe-ts-std/path";
import { isErr, mapErr, type Result } from "@evobug_com/safe-ts-std/result";

function resolveInside(root: FromOperator, rel: string): Result<SafePath, "outside"> {
  return mapErr(pathUnder(root, rel), () => "outside" as const);
}

async function serveFile(file: SafePath): Promise<string> {
  const data = await readFile(file, "utf8");
  return isErr(data) ? "" : data;
}

async function serve(rel: string): Promise<string> {
  const file = resolveInside(fromOperator(process.env.PUBLIC_DIR ?? "public"), rel);
  return isErr(file) ? "" : serveFile(file);
}

export const server = createServer((req, res) => {
  serve(req.url ?? "").then(
    (text) => res.end(text),
    () => res.end(),
  );
});

The same for a backup file named by an admin request (pathUnder(backupDir, name), which refuses .. and an absolute name: the name check is what the brand stands for now), and for the paths in the server's own config: read them once at the entry point (fromOperator(process.env.DB_FILE)), and type the fields and parameters that carry them FromOperator.

Its level. On an adopter (a game server, its admin app and its build scripts), 61 paths were reported before the rule looked at reach: every one from the program's own configuration, environment or command line, or checked by a function of the project that returns a string, none from a request without a check. With reach, 2 remain, both in the server's static file handler, on a request's path, where the name from the URL is checked by the project's own resolver, which returns a string: the migration above. So the rule is idiomatic: on where the project asks for the idiomatic rules, a warning there.

What the rule can't see:

  • A framework whose handlers no pack describes. Its handlers look like ordinary functions, so the rule is silent in them. Declare its slots in its pack (sinks.handlers, above).
  • A call through a value whose type isn't written. A route picked from a table by a value inference alone would type (ROUTES.flatMap(...).find(...), then found.route.run(c)) runs nothing the rule follows; write its type (const route: Option<Route> = ...) and every run the table holds is reached. The same for a handler bound (handle.bind(x)) and a listener whose event name isn't a constant.
  • A port or a server typed with the project's own type (port: PortLike): no pack says its on("message", ...) is a slot, so what it runs is silent, and so is a worker that answers through one. Declare it in a pack of the project's own, as for a framework.
  • A value stored at start-up and used by a handler (a field set from the config, read in a request): it is reported in the handler, where it reaches the sink. Type the field FromOperator (or SafePath), and it is accepted there.
  • Symbolic links (pathUnder checks the text, not the disk: keep links out of directories whose names come from data, or compare realpaths); a class's method that returns a path (this.backupDir(): type its result).

The list of members and of handler slots is data in the Node pack, complete for node:fs (Libraries: Sinks).

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra