> ## Documentation Index
> Fetch the complete documentation index at: https://fairyfly.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Fairyfly v0.3.0-beta: Deny-by-Default Permissions, 4× Lower Linux RSS, and Production Hardening

> What is new in Fairyfly v0.3.0-beta and why we built it that way — deny-by-default permissions, 10 MB Linux cold RSS, request headers and 1 MB body spill, async native bcrypt, Postgres TLS, AbortSignal, and graceful shutdown.

> **v0.3.0-beta · Release deep dive** — published 2026-11-08

**Fairyfly `v0.3.0-beta`** is out. Where `v0.2.0-beta` rounded out the core primitive set (UDP, `child_process`, HTTP proxies, and direct package sources), **`v0.3.0-beta` is about production readiness, security boundaries, and serverless density**.

Across 29 commits, the codebase grew from \~24k lines across 54 Zig files to **\~32k lines across 73 Zig files** — still small enough to read end-to-end, while closing the gaps that matter when you put a single-binary runtime in front of real traffic.

This post walks through **what is new in `v0.3.0-beta`** and **why each piece is designed the way it is**. You can also read the [release notes on GitHub](https://github.com/AbdElMajidOuhamane/ff/releases/tag/v0.3.0-beta).

***

## At a glance: what changed in `v0.3.0-beta`

| Area | What's new in `v0.3.0-beta` | Why it matters |
| - | - | - |
| **Security** | Deny-by-default `--allow-*` permissions (`read`, `write`, `net`, `env`, `run`, `ffi`, `all`) and `globalThis.permissions` | Scripts cannot touch files, sockets, env vars, subprocesses, or FFI without an explicit CLI grant |
| **Memory & density** | Lazy `MessagePort` buffers and bounded network thread stacks | Cuts Linux static-musl cold RSS from **40.0 MB → 10.1 MB** (\~4× higher instance density per GB) |
| **HTTP server** | `(url, method, body, headers)` handler signature, `reusePort`, 1 MB H1 request body spill, H2 body/header caps | Zero-alloc header pooling after warm-up; handles real webhooks and uploads without giving up fixed budgets |
| **Lifecycle** | `server.close()` graceful drain, `port: 0`, POSIX signals (`process.on` / `once` / `off`, `process.kill`) | Clean scale-to-zero on `SIGTERM` without dropping in-flight HTTP/1.1 or HTTP/2 requests |
| **Crypto** | Off-loop native `crypto.bcrypt` (`hash`, `verify`) + `crypto.subtle` HMAC (`importKey`, `sign`, `verify`, `exportKey`) | Password hashing (cost 4–14) never blocks the event loop; constant-time webhook signature verification |
| **Postgres** | TLS 1.2 via BearSSL (`sslmode=verify-full` + `sslrootcert`) and IPv4-first DNS resolution | Encrypted, SAN-verified connections to managed/serverless Postgres (Neon, RDS, Supabase) |
| **Web standards** | `AbortController` / `AbortSignal` (`timeout(ms)`, `throwIfAborted()`) and `structuredClone` | Per-request deadlines across `fetch`, timers, and `http.serve`; 4 MB deep clones on main thread and workers |
| **Hardening** | Strict HTTP/1.1 framing, cross-origin `fetch` credential stripping, WS generation-tagged handles, `ff upgrade` SHA-256 check | Defends against request smuggling, credential leaks on redirect, use-after-close slot reuse, and bad upgrades |

***

## 1. Deny-by-default permissions (`--allow-*`)

### What's new

Every native capability in Fairyfly is now **deny-by-default**. A script that only runs pure JavaScript (`ff hello.js`) needs no flags. Touching the filesystem, network, environment variables, subprocesses, or FFI requires an explicit CLI grant:

```sh theme={null}
# Allow listening on port 3000 and reading static assets
ff server.js --allow-net=0.0.0.0:3000 --allow-read=./public

# Allow reading PORT from the environment and outbound HTTPS to an API
ff worker.js --allow-env=PORT --allow-net=api.example.com:443

# Full test suite
ff test --allow-all
```

The seven flags are:

| Flag | Grants | Scope syntax |
| - | - | - |
| `--allow-read` | `fs` reads, `process.chdir`, TLS file paths in `http.serve`, Postgres `sslrootcert` | Comma-separated paths (`--allow-read=src,./public`) |
| `--allow-write` | `fs` writes, SQLite database files and their parent directory (for WAL/`-shm`) | Comma-separated paths (`--allow-write=./data`) |
| `--allow-net` | `fetch`, `WebSocket`, `http.serve`, `udp`, Postgres | `host`, `host:port`, `*.domain[:port]`, `[ipv6]:port` |
| `--allow-env` | `process.env`, Postgres env vars (`DATABASE_URL`, `PG*`) for the global `sql` | Exact variable names (`--allow-env=PORT,DATABASE_URL`) |
| `--allow-run` | `child_process.spawn` / `exec` / `execSync`, `process.kill` on external PIDs (`kill`) | Binary basenames or absolute paths (`--allow-run=git`) |
| `--allow-ffi` | Every `ffi` entry point except `ffi.allowed` | Bare flag only |
| `--allow-all` | Every category above, including FFI | Bare flag only |

When code attempts an operation outside its scope, Fairyfly throws a `PermissionDenied` error (`e.name === "PermissionDenied"`, `e.code === "PERMISSION_DENIED"`) **synchronously before any I/O, socket, or thread job is created**:

```js theme={null}
try {
  fs.readFile("/etc/passwd");
} catch (e) {
  console.log(e.name);    // "PermissionDenied"
  console.log(e.code);    // "PERMISSION_DENIED"
  console.log(e.message); // "fs.readFile requires --allow-read for '/etc/passwd'"
}
```

### Why we designed it this way

1. **CLI-only, never in `ff.json` or environment variables:** If a project manifest or environment variable could grant permissions, a compromised dependency or environment injection could silently escalate its own privileges. Making the command line the single source of truth means the operator launching `ff` always sees the exact authority of the process in `ps` or the container entrypoint.
2. **Immutable at startup:** Scopes are parsed once before the QuickJS runtime is initialized. Path scopes are canonicalized against the **launch** working directory, so a later `process.chdir()` cannot move the allowed roots. Workers inherit the exact same policy.
3. **Program loading is a deliberate carve-out:** `import`, `new Worker("./worker.js")`, `ff start` reading `ff.json`, and `ff test` loading `test/*.test.js` do **not** require `--allow-read`. Permissions govern what the code can do at runtime, not whether the entrypoint can boot.
4. **Honest threat model:** We document permissions as an **in-process policy layer, not an OS sandbox**. `--allow-run` and `--allow-ffi` execute native code with the full authority of the OS process, so granting them is trust-equivalent to `--allow-all`.

Full details: [Permissions](https://fairyfly.dev/concepts/permissions.md).

***

## 2. Cutting Linux serverless RSS by 4× (40 MB → 10.1 MB)

### What's new

While benchmarking Fairyfly on Linux serverless workloads with our static-musl build, we found and eliminated a hidden per-thread memory multiplier:

| Metric (Neon Linux serverless suite, aarch64) | Before | `v0.3.0-beta` |
| - | - | - |
| **Cold peak RSS** | 40.03 MB | **10.10 MB** |
| **Warm post-burst RSS** | 39.83 MB | **10.16 MB** |
| **Post-init RSS drift** | +33.08 MB | **+0.25 MB** |
| **Instance density (per 1 GB RAM)** | \~25 instances | **\~101 instances** |
| **ELF `PT_TLS` segment size** | 4,456,532 B (\~4.25 MB) | **262,244 B (\~256 KB)** |

### Why it happened and how we fixed it

`src/worker/message_port.zig` previously declared a **4 MiB `threadlocal` receive scratch buffer** for structured-clone worker messages. Because it was `threadlocal`, the compiler emitted a 4.25 MiB `PT_TLS` block into the binary — which the C runtime allocated for **every OS thread in the process**, including the 16 `fetch` worker threads and `std.Io` threads that never touch a `MessagePort`.

In `v0.3.0-beta`:

* **Lazy `MessagePort` scratch allocation:** The receive scratch buffer is now allocated lazily on first message use, grown up to the high-water frame size (capped at `MAX_FRAME` = 4 MiB), reused without reallocating on subsequent frames, and freed when the worker thread exits. Threads that never receive a worker message pay **0 bytes**.
* **Explicit network thread stack sizing:** Instead of inheriting Zig's 16 MiB default thread stack size on `std.Io` worker threads, the pool is bounded to 32 workers with explicit 1 MiB stacks (and 1 MiB stacks on the 16 `fetch` workers).

The result is a **4× reduction in Linux memory footprint** and near-zero RSS drift under sustained burst load.

***

## 3. HTTP server: request `headers`, `reusePort`, and 1 MB body spill

### What's new

#### Request `headers` in `http.serve`

The `http.serve` handler now receives a fourth argument — `headers`, a web-standard `Headers` instance populated for both **HTTP/1.1 and HTTP/2**:

```js theme={null}
http.serve({ port: 3000, reusePort: true }, (url, method, body, headers) => {
  const auth = headers.get("authorization");
  const cookies = headers.get("cookie"); // joined with "; " per RFC 9113
  if (!auth) {
    return Response.json({ error: "unauthorized" }, { status: 401 });
  }
  return Response.json({ ok: true, ua: headers.get("user-agent") });
});
```

* `headers.get(name)` is case-insensitive and joins duplicate headers with `", "` (`Cookie` joins with `"; "` per RFC 9113 §8.2.3; `Set-Cookie` returns the first value while `headers.getAll("set-cookie")` returns all).
* **Zero-allocation warm path:** `HeadersData` objects are pooled and retain capacity across requests (with hit/miss counters exposed in `process.stats().http`), so parsing request headers allocates nothing after warm-up.
* **Header size bounds:** Capped at **4 KB** for HTTP/1.1 and **64 KiB** for HTTP/2. Requests exceeding the cap receive `431 Request Header Fields Too Large` instead of dropping the session.
* **`reusePort` option:** Passing `{ reusePort: true }` enables `SO_REUSEPORT` so multiple `ff` processes can bind the same port with kernel load balancing.

#### 1 MB HTTP/1.1 request body spill & HTTP/2 bounds

Previously, HTTP/1.1 request headers and bodies shared the per-slot 4 KB static read buffer (`413` above \~4 KB). In `v0.3.0-beta`:

| Protocol | Static buffer | Max request body | Global budget | Over-cap response |
| - | - | - | - | - |
| **HTTP/1.1** | 4 KB per slot | **1 MB** per request (64 KB retained per idle slot) | **64 MB** across all connections | `413 Payload Too Large` (> 1 MB) / `503 Service Unavailable` (global budget full) |
| **HTTP/2** | — | **10 MB** per stream | **16 MB** per H2 session | Stream reset / `413` |

### Why this two-tier design

A 4 KB buffer is ideal for 95% of API traffic (GET requests, small JSON POSTs) because it stays inside the preallocated 512-slot connection table with zero heap activity. But webhook payloads, batch inserts, and form submissions routinely exceed 4 KB.

By keeping requests ≤ 4 KB in the static slot buffer and spilling larger payloads to the heap up to 1 MB (retaining up to 64 KB per slot and enforcing a hard 64 MB process-wide ceiling), Fairyfly handles real-world request bodies while still guaranteeing a strict upper bound on memory under a slow-POST flood. Spill telemetry is exposed directly via `process.stats().http.reqSpill`.

Full reference: [HTTP Server guide](https://fairyfly.dev/guides/http-server.md) · [`http` API](https://fairyfly.dev/api/http).

***

## 4. Graceful shutdown and POSIX signal handling

### What's new

`http.serve` now returns `{ port, close }`, supports ephemeral OS port assignment via `port: 0`, accepts an `AbortSignal`, and drains in-flight requests cleanly:

```js theme={null}
const server = http.serve({ port: 3000 }, (url, method, body, headers) => {
  return Response.json({ ok: true });
});

process.once("SIGTERM", async () => {
  console.log("draining connections...");
  await server.close();
  console.log("shutdown complete");
});
```

And `process` now supports POSIX signals (`SIGINT`, `SIGTERM`, `SIGHUP`, `SIGUSR1`, `SIGUSR2`):

* `process.on(sig, fn)`, `process.once(sig, fn)`, `process.off(sig, fn)` (up to 8 listeners per signal, dispatched safely on the event-loop thread).
* `process.kill(pid, sig?)` (self-signaling `process.pid` is ungated; signaling external PIDs requires `--allow-run=kill`).

When `server.close()` is called (or when `SIGINT`/`SIGTERM` arrives and no custom signal listener is registered):

1. The listening socket closes immediately so new connections are refused.
2. Idle HTTP/1.1 keep-alive sockets and active WebSockets close.
3. In-flight HTTP/1.1 responses are marked `Connection: close` and allowed to finish flushing.
4. Active HTTP/2 sessions send a `GOAWAY` frame and close once in-flight streams complete.
5. `server.close()` resolves its `Promise` once all 512 connection slots are free, allowing the event loop to exit naturally with code `0`.

### Why it matters

In container and serverless environments, the orchestrator sends `SIGTERM` before stopping an instance. Exiting immediately mid-request causes upstream 502 errors. Built-in connection draining makes zero-downtime deploys and scale-to-zero clean by default.

Full reference: [`process` API](https://fairyfly.dev/api/process) · [`http` API](https://fairyfly.dev/api/http).

***

## 5. Off-loop native `crypto.bcrypt` and Web Crypto HMAC

### What's new

#### `crypto.bcrypt.hash` and `crypto.bcrypt.verify`

Fairyfly now includes native, promise-based bcrypt password hashing backed by Zig's `std.crypto.pwhash.bcrypt` on a dedicated background worker pool:

```js theme={null}
// Hash with default cost 12 ($2b$12$...)
const hash = await crypto.bcrypt.hash("correct-horse-battery-staple", { cost: 12 });

// Verify ($2b$, $2a$, and $2y$ hashes supported)
const ok = await crypto.bcrypt.verify("correct-horse-battery-staple", hash);
console.log(ok); // true
```

* **Dedicated bounded pool:** 2–4 worker threads (256 KiB stacks) with a fixed 16-slot ring queue and preallocated buffers — **zero heap allocation per hash after initialization**.
* **Event loop stays responsive:** At cost 12 (\~250 ms) or 4× concurrent cost 11 (134 ms total), timer jitter on the main event loop stays under \~8 ms.
* **Fail-fast safety:** Passwords > 72 bytes reject immediately (`Error: bcrypt: password exceeds 72 bytes`); a 17th concurrent request when the ring queue is full rejects immediately (`Error: crypto.bcrypt: queue full`). No `hashSync` / `verifySync` exists.

#### `crypto.subtle` HMAC (`importKey`, `sign`, `verify`, `exportKey`)

`crypto.subtle` now supports HMAC with `SHA-1`, `SHA-256`, `SHA-384`, and `SHA-512`, including constant-time signature verification:

```js theme={null}
const enc = new TextEncoder();
const key = await crypto.subtle.importKey(
  "raw",
  enc.encode(process.env.WEBHOOK_SECRET),
  { name: "HMAC", hash: "SHA-256" },
  false,
  ["sign", "verify"],
);

const valid = await crypto.subtle.verify("HMAC", key, signatureBytes, bodyBytes);
```

### Why we built both into the binary

Authentication and webhook verification are universal backend tasks. In pure JS on an interpreted engine, bcrypt is too slow and blocks the single event loop thread; via npm, native addons don't work and pure-JS fallbacks starve I/O. Putting HMAC on `crypto.subtle` and bcrypt on a tiny, zero-alloc native worker pool solves auth without a single external package.

Full reference: [`crypto` API](https://fairyfly.dev/api/crypto).

***

## 6. Postgres TLS (`sslmode=verify-full`) and IPv4-first resolution

### What's new

The built-in Postgres wire client (`sql` and `new SQL(...)`) now supports **TLS 1.2 via BearSSL** with full certificate chain and SAN verification:

```js theme={null}
const db = new SQL({
  host: "ep-cool-Frog-123456.us-east-2.aws.neon.tech",
  port: 5432,
  user: "app",
  password: process.env.PGPASSWORD,
  database: "production",
  sslmode: "verify-full",
  sslrootcert: "/etc/ssl/certs/ca-certificates.crt",
});

const rows = await db`SELECT current_setting('ssl') AS ssl`;
```

```sh theme={null}
ff app.js \
  --allow-net=ep-cool-frog-123456.us-east-2.aws.neon.tech:5432 \
  --allow-read=/etc/ssl/certs/ca-certificates.crt \
  --allow-env=PGPASSWORD
```

* Supports `sslmode=verify-full` (via DSN query param, options object, or `PGSSLMODE` / `PGSSLROOTCERT`) and `sslmode=disable`.
* **Refuses weak TLS modes:** libpq's `require`, `prefer`, and `verify-ca` modes (which skip hostname verification or silently downgrade) are explicitly rejected.
* **IPv4-first DNS resolution & byte-order fix:** Fixed a network-byte-order swap bug in `resolveHost` for IPv4 `getaddrinfo` results and updated host resolution to prefer IPv4 addresses before falling back to IPv6.

Full reference: [Postgres API](https://fairyfly.dev/api/postgres.md).

***

## 7. `AbortController`, `AbortSignal`, and `structuredClone`

### What's new

* **`AbortController` and `AbortSignal`:** Full web-standard cancellation including `AbortSignal.abort(reason?)`, `AbortSignal.timeout(ms)`, `signal.throwIfAborted()`, and `"abort"` event listeners. Integrated across:
  * `fetch(url, { signal })` and `new Request(url, { signal })` — aborts in-flight requests and frees the fetch slot.
  * `setTimeout(fn, ms, { signal })` / `setInterval` — cancels the timer when aborted.
  * `http.serve({ port, signal }, handler)` — triggers `server.close()` when aborted.
* **`structuredClone(value)`:** Global deep binary clone (up to 4 MB per call) available on both the main thread and inside `Worker` threads, sharing the same serializer used by `postMessage`.

```js theme={null}
const res = await fetch("https://api.example.com/slow", {
  signal: AbortSignal.timeout(1500),
});
```

### Why it matters

Serverless functions run under strict wall-clock budgets. Relying on the global 30-second socket timeout means one slow upstream can eat your entire function invocation. `AbortSignal.timeout(ms)` gives every outbound `fetch` and timer a composable, per-call deadline.

Full reference: [`fetch` API](https://fairyfly.dev/api/fetch) · [`Worker` API](https://fairyfly.dev/api/worker).

***

## 8. Protocol, filesystem, and supply-chain hardening

Finally, `v0.3.0-beta` includes a comprehensive security and correctness pass across every I/O boundary:

* **HTTP/1.1 framing strictness:** Rejects duplicate or conflicting `Content-Length` headers, `Transfer-Encoding`, obsolete line folding (`obs-fold`), and bad whitespace (`BWS`) with `400 Bad Request`, plus a 30-second read deadline for incomplete headers or bodies.
* **Cross-origin `fetch` hygiene & 16 MB cap:** Outbound `fetch` now strips sensitive headers (`authorization`, `cookie`, `x-api-key`) when following a redirect across origins, validates header characters per RFC 7230, and enforces a 16 MB cap on both declared `Content-Length` and decompressed response bodies.
* **WebSocket hardening:** Enforces RFC 6455 client frame masking on the server, caps control frames at 125 bytes, validates UTF-8 strictly on text frames, bounds the per-socket outbound buffer at 32 KB (`TX_BUF_SIZE`), and uses **generation-tagged `{slot, gen}` socket handles** so a retained JS reference can never address a recycled socket slot.
* **No silent truncation in `fs`:** `fs.writeFile` and `fs.writeFileAsync` now throw/reject if payloads exceed the 10 MB cap instead of silently truncating.
* **Package containment:** The module resolver and `ff imprint` reject `package.json` manifest targets (`main`, `module`, `exports`) or bare subpaths that contain `..` or escape the package directory root.
* **Verified self-updates:** `ff upgrade` now downloads `sha256sums.txt` from the GitHub release and verifies the binary's SHA-256 digest before replacing `ff`.
* **Entry module auto-detection by parsing:** `ff <file.js>` now detects whether an entry file is an ES module or a classic script by parsing it with QuickJS rather than brittle keyword scanning.

***

## Upgrade or install

If you already have `ff` installed:

```sh theme={null}
curl -fsSL https://www.fairyfly.dev/install.sh | sh
ff --version
# ff 0.3.0-beta
```

When upgrading an existing project from `v0.2.0-beta`, add the `--allow-*` flags your app uses to your start command or Dockerfile `CMD`:

```sh theme={null}
ff start --allow-net=0.0.0.0:3000 --allow-env=PORT
```

Explore the updated docs:

* [Permissions](https://fairyfly.dev/concepts/permissions.md) — flags, scopes, and the `PermissionDenied` contract
* [HTTP Server guide](https://fairyfly.dev/guides/http-server.md) — `(url, method, body, headers)`, `reusePort`, and body spill
* [`crypto` API](https://fairyfly.dev/api/crypto) — `crypto.bcrypt` and `crypto.subtle` HMAC
* [Postgres API](https://fairyfly.dev/api/postgres.md) — `sslmode=verify-full` TLS configuration
* [Limitations](https://fairyfly.dev/reference/limitations.md) — every hard cap in `v0.3.0-beta`


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.