The framework can reject a malformed request, a dangerous attribute or a file path. It cannot decide whether an authenticated person is allowed to edit a particular note, whether a proxy really removed client-supplied headers, or whether a public page includes private database data. Those are different trust boundaries. TradJS 4.7.0 puts default checks at the boundaries it owns and leaves the application's identity and authorization policy visible. Across the supplied repository run, 1,902 tests passed. The security run exercised 46 attack tests. With the relevant fixes removed, 12 of those tests failed. The trusted-proxy matrix separately exercised 1,120 header combinations. These numbers describe the supplied runs on Windows 11 with Bun 1.4.3, not a certification or a claim that every possible attack has been tested.
Threats and ownership#
| Attack | Framework action | Proof in repository | App responsibility |
|---|---|---|---|
| Cookie-bearing cross-site write | Rejects foreign Origin or cross-site metadata/Referer with 403 |
tests/csrf.test.ts; tests/security-4.7.test.ts SESSION-09/10 |
Add tokens for high-risk actions; keep writes off GET |
Script URL, unsafe srcdoc, CSS URL |
Drops unsafe props during SSR and DOM updates | tests/ssr-parity-matrix.test.ts; src/shared/attributes.ts; src/client/props.ts |
Sanitize deliberate raw HTML and control user-authored links |
| Server code or secret entering client bundle | Blocks server/private imports, environment access and known secret literals | tests/security-4.7.test.ts BOUNDARY-01/02 |
Never pass credentials as public props or API data |
| Request-specific HTML shared by prerender | Rejects implicit middleware SSG, guarded request/locals access, Set-Cookie and detected secret output |
tests/ssg-safety.test.ts |
Keep dynamic data out of public output and module globals |
| Traversal or swap while serving a file | Opens descriptor first, checks root and file identity, serves checked bytes | tests/rooted-file-interleavings.test.ts; PUBLIC/ASSET tests |
Restrict writes to public/ and dist/ |
| Fake WebSocket origin or abusive socket | Checks origin before upgrade and enforces route limits | tests/websocket-origin.test.ts; tests/websocket-limits-matrix.test.ts |
Authenticate upgrade, authorize every message |
| Forged forwarded scheme, host or address | Accepts only validated chains from configured trusted socket peers | tests/trust-proxy-matrix.test.ts |
Isolate listener, overwrite ingress headers, set correct trust |
| Session fixation, stale token or another user's note ID | Starter rotates and revokes sessions, checks ownership, limits note inputs | tests/security-4.7.test.ts SESSION-01 through SESSION-11 |
Production account recovery, abuse controls, identity assurance |
| The table is a threat model, not a blanket declaration that arbitrary application JSX is safe. The relevant external rules come from the OWASP CSRF, XSS, WebSocket and Session Management cheat sheets. The source files and tests show the narrower TradJS behavior. |
Cookie writes and source origin#
The default CSRF middleware examines unsafe methods only when a Cookie header is present. It compares against the effective public origin, which may depend on a separately verified proxy identity. The actual check is:
import { isAllowedWebSocketOrigin } from "./serve";
import { requestClient } from "./trust-proxy";
export interface CsrfOptions {
/** Extra origins allowed to send cookie-bearing writes, e.g. "https://admin.example". */
allowedOrigins?: string[];
}
const UNSAFE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
/**
* Cross-site request forgery check. A browser attaches the user's cookies
* to a form post or fetch from any site; this refuses such writes unless
* they come from the app's own origin (or an allowed one).
*
* Refused: POST/PUT/PATCH/DELETE that carry a Cookie header and either an
* Origin from another site, Origin "null", or (without Origin)
* `Sec-Fetch-Site: cross-site`. Allowed: safe methods, requests without
* cookies, and requests with neither header (servers, scripts, old clients).
*/
export function csrfRejection(
req: Request,
url: URL,
options: CsrfOptions = {},
): Response | undefined {
if (!UNSAFE_METHODS.has(req.method.toUpperCase())) return undefined;
if (!req.headers.has("cookie")) return undefined;
const effectiveUrl = new URL(requestClient(req).origin + url.pathname);
const origin = req.headers.get("origin");
const referer = req.headers.get("referer");
const crossSite = origin !== null
? !isAllowedWebSocketOrigin(origin, effectiveUrl, options.allowedOrigins)
: req.headers.get("sec-fetch-site") === "cross-site" ||
(referer !== null && !isAllowedWebSocketOrigin(referer, effectiveUrl, options.allowedOrigins));
if (!crossSite) return undefined;
return new Response("Forbidden: cross-site request", {
status: 403,
headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
});
}
Source: src/server/csrf.ts, lines 1–40.
The order is precise. First, Origin decides when present, including refusing an opaque null origin. A same-origin Origin passes this check even if another provenance header disagrees. Only without Origin does Sec-Fetch-Site: cross-site reject; when that does not reject, a present foreign Referer rejects. The latter conditions are connected by OR, so either can refuse. With none of these indicators the request passes. Requests without cookies also pass this particular check. Safe HTTP methods do not enter the check.
RFC 6454 defines a web origin in terms of scheme, host and port, rather than host alone. A request from plain HTTP is not same-origin with the HTTPS site, even on the same hostname. The Fetch Metadata working draft defines Sec-Fetch-Site; MDN's Fetch Metadata guide explains how servers use it for cross-site request handling. The OWASP CSRF guidance recommends origin verification and Fetch Metadata as defenses, but also favors CSRF tokens for state-changing operations where appropriate.
TradJS intentionally does not force a synchronizer token into every HTML form. The starter relies on same-origin provenance for cookie-bearing writes and SameSite=Lax cookies. This makes ordinary native forms work without an inserted token, including scripts that omit modern browser headers. It also means a request with no Origin, no usable Referer and no cross-site metadata is not rejected on provenance alone. For payments, destructive administration or endpoints whose clients supply ambiguous headers, add an application-controlled CSRF token and verify it on the server. Do not disable the framework check as a substitute.
A Content-Type: text/plain request containing JSON-looking text is not exempt. The tests send such cross-site writes to verify that the check is method/cookie/provenance based, not dependent on JSON preflight behavior. The allowedOrigins option is an explicit trust decision: only configure it for origins that should be allowed to send authenticated writes.
URL, HTML and browser boundaries#
Server HTML rendering and browser updates use the same unsafe-URL predicate. The shared source identifies the attributes whose values can navigate or load content:
const SAFE_NAME = /^[A-Za-z][A-Za-z0-9:._-]*$/;
const URL_ATTRIBUTES = new Set([
"href", "src", "action", "formaction", "xlink:href",
"poster", "data", "cite", "background", "srcset",
]);
const IMAGE_ATTRIBUTES = new Set(["src", "srcset", "poster"]);
const SAFE_IMAGE_DATA = /^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|x-icon|vnd\.microsoft\.icon)[;,]/i;
function hasUnsafeCssUrl(value: unknown): boolean {
const css = String(value)
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/\\([0-9a-f]{1,6})\s?/gi, (_match, hex) => {
const cp = parseInt(hex, 16);
return String.fromCodePoint(
cp === 0 || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)
? 0xfffd
: cp,
);
})
.replace(/\\([^\r\n])/g, "$1")
.replace(/[\u0000-\u0020\u007f]/g, "")
.toLowerCase();
// javascript:/vbscript: never; data: only for raster images (inline
// backgrounds are common; data:image/svg+xml and data:text/html are not safe).
return [...css.matchAll(/url\(["']?([a-z]+):([^)"']*)/g)].some(([, scheme, rest]) => {
if (scheme === "javascript" || scheme === "vbscript") return true;
if (scheme !== "data") return false;
return !SAFE_IMAGE_DATA.test(`data:${rest}`);
});
}
/** URL attributes that would run code: javascript:/vbscript: anywhere, and
* data: except raster images in src, srcset and poster (data:image/svg+xml
* and data:text/html can run script). */
export function isUnsafeUrlAttribute(name: string, value: unknown): boolean {
const lower = name.toLowerCase();
if (lower === "style") return hasUnsafeCssUrl(value);
if (!URL_ATTRIBUTES.has(lower)) return false;
const urls = lower === "srcset" ? String(value).split(",") : [String(value)];
return urls.some((raw) => {
const url = raw.replace(/[\u0000-\u0020\u007f]/g, "");
if (/^(?:javascript|vbscript):/i.test(url)) return true;
if (!/^data:/i.test(url)) return false;
return !(IMAGE_ATTRIBUTES.has(lower) && SAFE_IMAGE_DATA.test(url));
});
}
Source: src/shared/attributes.ts, lines 1–47.
The policy refuses javascript: and vbscript: URLs and data: URLs except recognized raster-image data in image positions. It also checks CSS url(...) values after removing comments and decoding CSS escapes. srcdoc is dropped rather than trying to sanitize an entire embedded HTML document. The client path removes an unsafe attribute that was set by an earlier render; it does not only check the first mount.
This is narrower than a universal HTML sanitizer. The OWASP XSS guidance recommends context-aware output encoding, URL validation and an allowlist sanitizer for untrusted HTML. A string inserted as text is a different case from HTML supplied to dangerouslySetInnerHTML. Code that intentionally accepts rich HTML must provide its own trusted sanitization policy. TradJS's attribute rules cannot decide which HTML elements are acceptable in an application's editor.
Client entries are subject to another boundary. Browser code cannot import local server/, private/ or secrets/ modules, route/middleware/database-named modules, or read server environment variables other than the permitted build-time NODE_ENV handling. Canonical real paths prevent a symlink alias from disguising a private folder. A bundle is also checked for literal values of sensitive environment variables. The relevant implementation is:
const lexicalRelative = path.relative(path.dirname(path.resolve(entry)), path.resolve(file));
if (actualFile !== actualEntry &&
(isServerOnlyClientModule(relativeToEntry) || isServerOnlyClientModule(lexicalRelative))) {
throw new Error(
`Server-only local module "${file}" imported by browser entry "${entry}". Move sensitive operations to an API route.`,
);
}
// NODE_ENV is replaced by the browser builder. Other env access is forbidden.
const withoutNodeEnv = source.replace(/\bprocess\s*\.\s*env\s*\.\s*NODE_ENV\b/g, "");
if (/\b(?:process|Bun)\s*(?:\.\s*env\b|\[\s*["']env["']\s*\])|\bimport\s*\.\s*meta\s*\.\s*env\b/.test(withoutNodeEnv)) {
throw new Error(
`Server environment access in browser module "${file}". Pass explicitly public data through a safe API instead.`,
);
}
}
/** Shared predicate for both client bundles and server-prerendered HTML. */
export function isSensitiveEnvironmentVariable(name: string): boolean {
return /(?:SECRET|TOKEN|PASSWORD|CREDENTIAL|PRIVATE|API_KEY|DATABASE_URL|CANARY)/i.test(name);
}
/** Detect sensitive literal values that survive an otherwise valid client build. */
export function assertNoEnvironmentSecretsInBundle(
source: string,
environment: NodeJS.ProcessEnv = process.env,
): void {
for (const [key, value] of Object.entries(environment)) {
if (!isSensitiveEnvironmentVariable(key)) continue;
if (typeof value === "string" && value.length >= 8 && source.includes(value)) {
throw new Error(`Client output contains the value of sensitive environment variable ${key}`);
}
}
}
Source: src/server/client-boundary.ts, lines 20–52.
This catches direct and transitive imports and known literal disclosures; it is not information-flow analysis. A value explicitly rendered into page props, returned from a public API or assembled indirectly may still leak. Keep secrets in server modules and send only the fields the browser is authorized to read. The bootstrap separately escapes closing script tags and JavaScript line separators; tests/security-4.7.test.ts BOOT-01/02 checks that serialized route data remains data.
Prerendered output is shared#
Static generation changes the privacy model. A rendered response may later be reused for visitors with different cookies and roles. In 4.7.0, any middleware ancestor makes an SSG route suspect. Production build/start refuses it unless the page explicitly declares its shared HTML to be public. Development warns rather than silently treating it as safe. An explicit public assertion does not bypass middleware on requests. The safety gate is:
/** Conservatively treat any ancestor middleware as capable of rejecting or writing locals. */
export function assertSSGMiddlewareSafety(route: Route, config: SSGConfig | null, mode: "production" | "development"): boolean {
if (!config || !route.middlewares.length || config.public) return true;
const message = `SSG page ${route.pattern} (${route.filePath}) has middleware (${route.middlewares.join(", ")}) that may deny requests or write locals; use ssg = { public: true } ONLY for deliberately public HTML`;
if (mode === "production") throw new SSGSafetyError(message);
console.warn(`[tradjs] SECURITY WARNING: ${message}`);
return false;
}
export async function inspectSSGRoutes(routes: Route[], mode: "production" | "development"): Promise<void> {
for (const route of routes) {
if (route.type !== "page" || !route.middlewares.length) continue;
const module = await import(route.filePath);
assertSSGMiddlewareSafety(route, resolveSSGConfig(module.ssg), mode);
}
}
Source: src/server/ssg.ts, lines 57–72.
Prerender receives guarded locals and request objects: reading, writing or enumerating their properties throws with the route and property. It rejects a prerender result that sets Set-Cookie. It scans the output for known sensitive environment-variable values, including common HTML/JSON encodings. The cache key includes route identity and ordered parameter values rather than mixing parameterized paths.
The deliberate difference from a general static-site build is the fail-closed check for middleware-backed pages. A public page can opt in using ssg = { public: true }, but it must be independent of account data. No static analysis can prove that a module-level database query has no visitor-specific contents. The app must not prerender account dashboards or role-specific menus. The OWASP Authorization guidance supports enforcing access at each request; the framework protects cache sharing but cannot replace the application's authorization rule.
Files, link swaps and immutable builds#
A path can be safe when checked and unsafe when opened. TradJS's rooted reader avoids the check-then-reopen pattern. It opens the candidate, verifies the open descriptor is a file, checks the canonical root and target, compares device/inode and size, reads from that same descriptor and checks it again afterward. Build artifacts additionally require an approved manifest entry and a matching content digest.
function inside(root: string, file: string): boolean {
const relative = path.relative(root, file);
return relative !== "" && relative !== ".." &&
!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
}
function sameFile(a: BigIntStats, b: BigIntStats): boolean {
return a.dev === b.dev && a.ino === b.ino && a.size === b.size;
}
/**
* Open first; verify the OPEN descriptor against the canonical path under root;
* read ONLY that descriptor, never reopen the filename. The post-read fstat
* detects growth/truncation between verification and reading. No O_NOFOLLOW is
* used, so this also works with Windows junctions and native Windows fs APIs.
*
* A same-inode/same-length in-place rewrite is not detectable for public
* files; immutable built assets additionally verify the served bytes' digest.
*/
export function openRooted(
root: string,
relativePath: string,
ops: RootedFileOperations = rootedFileOperations,
options: OpenRootedOptions = {},
): OpenedRootedFile {
const parts = validatedRelative(relativePath);
const candidate = path.resolve(root, ...parts);
let fd: number | undefined;
try {
fd = ops.openSync(candidate, "r");
const opened = ops.fstatSync(fd, { bigint: true });
if (!opened.isFile()) throw new RootedFileError("Opened entry is not a regular file");
const canonicalRoot = ops.realpathSync(path.resolve(root));
if (options.pinnedRoot) {
const { realPath, dev, ino } = options.pinnedRoot;
const rootNow = ops.statSync(canonicalRoot, { bigint: true });
if (path.relative(realPath, canonicalRoot) !== "" ||
rootNow.dev !== dev || rootNow.ino !== ino || !rootNow.isDirectory())
throw new RootedFileError("Rooted directory was replaced");
}
// A build may include nested directories; none may be a link.
if (options.forbidLinks) {
let current = path.resolve(root);
for (const part of parts) {
current = path.join(current, part);
if (ops.lstatSync(current, { bigint: true }).isSymbolicLink())
throw new RootedFileError("Symlink in rooted asset path");
}
}
const canonicalFile = ops.realpathSync(candidate);
if (!inside(canonicalRoot, canonicalFile))
throw new RootedFileError("Opened entry escapes rooted directory");
const resolved = ops.statSync(canonicalFile, { bigint: true });
if (!resolved.isFile() || !sameFile(opened, resolved))
throw new RootedFileError("Opened file differs from checked rooted path");
if (opened.size > BigInt(Number.MAX_SAFE_INTEGER))
throw new RootedFileError("Rooted file too large");
const bytes = ops.readFileSync(fd);
const after = ops.fstatSync(fd, { bigint: true });
if (!after.isFile() || !sameFile(opened, after) || BigInt(bytes.byteLength) !== opened.size)
throw new RootedFileError("Opened file changed size during reading");
return {
bytes,
size: Number(opened.size),
mtimeMs: Number(opened.mtimeNs) / 1_000_000,
realPath: canonicalFile,
};
} finally {
if (fd !== undefined) ops.closeSync(fd);
}
}
Source: src/server/rooted-file.ts, lines 64–133.
The swap-mid-request matrix in tests/rooted-file-interleavings.test.ts crosses operation boundaries with replacement by file, directory, symlink, junction or hard link, plus truncation and growth. It uses injected filesystem operations so the dangerous ordering is deterministic rather than dependent on winning a race in a live process. The same descriptor is read throughout. tests/security-4.7.test.ts also checks traversal encodings, hidden files, planted assets and tampered manifest data.
The limit is concrete. A preexisting hard link inside an authorized public tree is a real file in that namespace, and a same-length in-place rewrite of an ordinary public file can escape size checks. Immutable built files have a digest check, but an untrusted writer must not be allowed to alter the build directory or public root. OS file permissions are part of the security model, not a redundant layer.
WebSockets, proxy identity and sessions#
The browser WebSocket API can initiate a handshake from a foreign page. RFC 6455 defines the Origin-based handshake and policy close codes; the OWASP WebSocket cheat sheet requires both origin validation and authentication. TradJS checks the origin before the route's upgrade guard and uses same-origin by default. The starter guard reads the session cookie, not an asserted user ID. The route also enforces message, payload, buffer, connection and upgrade limits as documented in chapter 12.
Those limits are local to each process. An ingress shared across workers needs a separate quota when abuse across processes matters. An application accepting WebSocket commands must authorize each command and validate its input after the connection opens. The live-notes endpoint avoids that problem by accepting only the sync request and never granting a client-selected subscription.
Proxy metadata is not identity unless the socket peer is trusted. RFC 7239 specifies Forwarded, including a chain of intermediaries, but does not make received header values trustworthy. TradJS defaults to ignoring forwarding headers. With trustProxy configured, it parses Forwarded or the complete X-Forwarded-* trio, walks right to left from the verified peer, stops at the first untrusted hop and rejects malformed or conflicting representations.
export function resolveClient(
request: Request, setting: TrustProxy = false, peerAddress?: string,
): RequestClient {
return makeClientResolver(setting)(request, peerAddress);
}
export function makeClientResolver(setting: TrustProxy = false) {
const checker = trustChecker(setting);
return (request: Request, peerAddress?: string): RequestClient => {
const url = new URL(request.url);
const base: RequestClient = {
ip: peerAddress ? (parseIp(peerAddress)?.text ?? peerAddress) : "",
protocol: url.protocol === "https:" ? "https" : "http",
host: url.host,
origin: url.origin,
};
const peer = base.ip;
if (!peer || setting === false || setting === 0) return base;
const forwarded = request.headers.get("forwarded");
const hasX = ["x-forwarded-for", "x-forwarded-proto", "x-forwarded-host"]
.some((key) => request.headers.has(key));
const f = forwarded === null ? undefined : parseForwarded(forwarded);
const x = hasX ? parseXForwarded(request) : undefined;
if ((forwarded !== null && !f) || (hasX && !x)) return base;
if (!f && !x) return base;
const fromForwarded = f && trace(base, peer, f, checker);
const fromX = x && trace(base, peer, x, checker);
// Competing header families must agree, otherwise do not trust either.
if (fromForwarded && fromX &&
(fromForwarded.ip !== fromX.ip || fromForwarded.origin !== fromX.origin)) return base;
return fromForwarded ?? fromX ?? base;
};
}
Source: src/server/trust-proxy.ts, lines 258–289.
That rule is deliberately stricter than adopting the leftmost X-Forwarded-For value. If a user can connect directly to a listener configured to trust a numeric hop count, they can spoof the claimed public scheme and host. Put the listener behind the designated proxy and have the proxy overwrite all forwarding fields. The proxy test's 1,120 header combinations and separate spoofing cases are evidence of parser behavior, not proof that a deployment's ingress is correct. The deployment chapter gives concrete hops.
The starter's own sessions use tokens stored in SQLite, generated on authentication, with an HttpOnly, SameSite=Lax cookie. Secure is attached only when the verified public request is HTTPS. Login invalidates a supplied prior session and issues a new token; logout removes it. Read checks expiration and user existence, and the live WebSocket revalidates session authority before delivering frames. Tests check rotation, revocation, foreign-user note IDs, mass-assignment attempts and fixed error messages.
The starter is a reference for a local authenticated CRUD app, not a complete production identity service. It does not add email verification, account recovery, production login rate limiting or operational monitoring. Follow the OWASP Session Management guidance for the broader lifecycle and the application's own risk assessment.
Before promoting an app, run bunx tradjs upgrade-check ., review all errors and reviews in UPGRADING.md, build for production, and repeat session, origin, file and proxy tests against the actual ingress. The checker can find risky imports and static-page declarations in source; it cannot inspect the deployed certificate, live proxy forwarding chain or every possible user-data dependency.