How Portless Works: Scripts, Ports, Routes and a Local CA

Portless turns port numbers into named HTTPS URLs using a CLI wrapper, a file-backed route registry, a root-owned proxy and a local CA. A system design tour of every moving part.

On this page
  1. The shape of the system
  2. 1. Which script runs
  3. 2. Which port the app gets
  4. 3. The registry is a file
  5. 4. TLS and the certificate authority
  6. 5. What it changes on the machine
  7. 6. Failure modes
  8. 7. Design lessons
  9. Sources

The shape of the system

portless myapp next dev looks like a convenience wrapper. Underneath it is a small service discovery system for one machine: a CLI that chooses a port, a JSON file that maps names to ports, a daemon that terminates TLS on 443, and a local certificate authority that makes the names trusted.

Part Runs as Owns
CLI wrapper your user reading config, choosing a port, spawning the app, registering the route
Route registry a JSON file in ~/.portless the mapping from hostname to loopback port
Proxy daemon usually root, on port 443 TLS termination, host routing, error pages
Local CA files in ~/.portless signing certificates for names under the configured TLD

The design follows from two constraints. Browsers choose a destination by name and port, 443 by default. Dev servers choose a port and know nothing about names. Portless sits between them and translates.

assigns port, writes routespawns with PORT and HOSTfs.watch, 3s poll fallbackHost: myapp.localhostHTTP/1.1 to 127.0.0.1:4317signs SNI certsportless CLIuser processroutes.json~/.portlessdev server127.0.0.1:4317proxy daemonroot on :443browserlocal CAca.pem

Two details matter early. Portless does not scan the machine to discover which port an app chose. It assigns the port, then tells the app. And the proxy knows nothing about projects, scripts, or configs. It knows a hostname and a loopback port.

1. Which script runs

Bare portless is the zero-config path. It reads the dev script from the nearest package.json and asks the detected package manager to run it, so the child process is effectively pnpm run dev, npm run dev, or bun run dev depending on the lockfile. portless --script start selects a different script. portless run does the same with name inference. portless myapp next dev skips inference and runs the command directly.

Precedence is closest-wins, like Prettier or ESLint:

Setting Order
name --name > package.json portless key > portless.json app entry > package name > git root > directory
script --script > package.json portless key > portless.json app entry > dev
app port --app-port > PORTLESS_APP_PORT > package.json portless key > portless.json > random

Name inference is deliberately boring. It uses the package name without the @scope/ prefix, then the git root directory name, then the current directory. Every candidate is sanitized to a DNS label: lowercase, invalid characters become hyphens, runs collapse, edges are trimmed, and labels past 63 characters get a stable hash suffix.

Linked worktrees add a prefix from the branch. The primary checkout keeps myapp.localhost, and a linked worktree on fix-ui gets fix-ui.myapp.localhost, with no config change. main and master are treated as primary. --prefix or PORTLESS_PREFIX overrides detection.

From a workspace root, portless discovers packages from pnpm-workspace.yaml or the workspaces field, starts every package that has the target script, and names them <package>.<project>.localhost. Turbo is reused when its config is present, so task ordering does not change.

$ portless
portless
-- myapp.localhost (auto-resolves to 127.0.0.1)
-- Name "myapp" (from package.json)
-- Prefix "fix-ui" (from git branch)
-- Using port 4317
Running: PORT=4317 HOST=127.0.0.1 PORTLESS_URL=https://fix-ui.myapp.localhost pnpm run dev

2. Which port the app gets

The app never searches for a port. findFreePort picks one in 4000 to 4999, which also sits below the usual ephemeral ranges on macOS and Linux (49152 and up, 32768 and up respectively), so outbound sockets rarely collide with dev servers.

The algorithm tries 50 random ports first, then scans the range sequentially. A candidate must bind on four addresses, 127.0.0.1, ::1, 0.0.0.0 and ::, because a port can look free on one loopback family while another process holds it. Probes run sequentially because a dual-stack :: bind collides with a concurrent 0.0.0.0 bind.

There is an inherent time-of-check to time-of-use race between closing the probe socket and the child binding the port. Random-first selection minimizes the window. If the child loses the race, it exits with EADDRINUSE; the next run gets a new random port. Fixed ports are available with --app-port or PORTLESS_APP_PORT.

Once chosen, the port reaches the app three ways:

  • PORT and usually HOST=127.0.0.1 in the environment.
  • PORTLESS_URL with the public name.
  • Framework-specific CLI flags when the framework ignores PORT.
Command What portless adds
Next.js, Express, Nuxt nothing; they read PORT
Vite, VitePress, React Router --port, --strictPort, --host 127.0.0.1
Astro --port, --host 127.0.0.1
Expo (outside LAN mode) --port, --host localhost
Wrangler --port, --ip 127.0.0.1

What portless actually spawns

Portless sets PORT and HOST, then adds CLI flags only when the framework ignores PORT. Vite gets --port, --strictPort and --host; Next.js gets no extra flags; Astro gets --port and --host; Expo gets --port and --host localhost; Wrangler gets --port and --ip. Changing the assigned port rewrites every flag.

The flag injector is the messiest part of the system because CLI grammars differ. It looks through known package runners (npx, bunx, pnpm dlx, yarn dlx, npm exec) and through a package script whose first command is the framework. It only appends flags to server subcommands. vite build, astro check, vp test, compound commands with && or |, env prefixes such as NODE_ENV=production vite, delegating scripts such as npm run dev:vite, and flag grammars it cannot classify are left alone. Those keep their own port, and the docs tell you to set it yourself.

The conservatism is the right call. A wrong flag can break a build command that was never meant to serve. A missed flag produces an app on its default port and a 502 at the named URL, which is easier to diagnose.

3. The registry is a file

Each app writes one entry to ~/.portless/routes.json:

[
  {
    "hostname": "myapp.localhost",
    "port": 4317,
    "pid": 91234,
    "registeredAt": 1763083200000
  }
]

Routes are keyed by hostname, not by port. That inversion is the product. The name is stable; the port is disposable.

Writes take a lock implemented as mkdir routes.lock, which is atomic across processes. The lock retries with jittered backoff, gives up after 15 seconds, and treats a lock older than 10 seconds as stale. A hostname already owned by a live PID is a conflict. --force sends SIGTERM to the owner before replacing the entry, then the replacement records its own PID.

A route is a lease, not a permanent record. Loading the file filters out entries whose owning PID is gone. The proxy caches the file in memory, watches it with fs.watch debounced by 100 ms, and falls back to a 3 second poll where watching is unavailable. Before serving from the cache it checks that every route owner is still alive, and reloads if any are not. A crashed CLI stops serving its routes even if nobody rewrites the file.

A named request uses the cached route to port 4317

A named request uses the cached route to port 4317
  1. The browser sends an HTTPS request with Host myapp.localhost to the proxy on port 443. 2. The proxy looks up that name in its in-memory route cache and finds port 4317. 3. It forwards HTTP to 127.0.0.1:4317, not to the other app on port 4402. File changes refresh the cache from routes.json; normal routing does not read the file on every request.

On every request the proxy narrows by Host. It lowercases the authority, drops an explicit :443, then tries an exact hostname, a Tailscale authority tier for .ts.net routes, and, when --wildcard is on, the longest registered parent. A named host outside every configured TLD gets 421 Misdirected Request instead of the app list, so a hosts file or DNS blocklist pointing example.com at 127.0.0.1 cannot expose your local apps. An unknown name under the TLD gets 404 plus the list of active routes.

Route a Host header against routes.json

With routes myapp.localhost:4317, api.myapp.localhost:4402 and docs.localhost:4120, an exact Host wins. With --wildcard, a longer name such as tenant1.myapp.localhost falls back to the most specific registered parent. A named external host gets 421; an unknown name under .localhost gets 404.

Each proxied request carries an x-portless-hops header. At five hops the proxy returns 508 and names changeOrigin: true as the fix. This is the usual failure when a Vite dev server proxies /api to another portless app without rewriting Host: the request returns to the proxy looking like the frontend again.

4. TLS and the certificate authority

HTTP/1.1 lets a browser open six connections per host. A dev server serving many unbundled modules hits that limit quickly. The proxy is an HTTP/2 server with HTTP/1.1 fallback, so a cold page load multiplexes over one connection. WebSockets still work. HTTP/1.1 Upgrade requests are forwarded as-is, and HTTP/2 WebSockets use RFC 8441 extended CONNECT, which the proxy bridges to an HTTP/1.1 handshake with the backend.

On the first TLS start, portless runs openssl to create a local CA: an EC P-256 key, self-signed for ten years, with basicConstraints=critical,CA:TRUE and keyUsage=critical,keyCertSign,cRLSign. Private keys land at mode 0600. A default server certificate, valid for one year, covers localhost, *.localhost and *.local.

Trust is a separate step, because generating a CA does not make the OS trust it:

Platform What portless does
macOS security add-trusted-cert into the login keychain, which shows an authorization prompt. As root, the System keychain.
Debian, Ubuntu copies portless-ca.crt to /usr/local/share/ca-certificates and runs update-ca-certificates
Arch copies to /etc/ca-certificates/trust-source/anchors and runs update-ca-trust
Fedora, RHEL, CentOS copies to /etc/pki/ca-trust/source/anchors and runs update-ca-trust
openSUSE copies to /etc/pki/trust/anchors and runs update-ca-certificates
Windows certutil into the current-user Root store
WSL both the Linux store and the Windows current-user Root store

A marker file records the SHA-256 fingerprint of the CA that was trusted, so later starts skip the OS check. Regenerating the CA clears the marker and deletes cached host certificates.

The generated wildcard certificate is not enough on its own. RFC 2606 reserves .localhost as a top-level domain, which puts *.localhost at the public suffix boundary, and TLS clients are not required to honor wildcards there. The proxy therefore installs an SNI callback. localhost itself uses the default certificate; every other name needs a certificate with an exact DNS: SAN.

Generation runs inside the TLS handshake, so it is asynchronous and deduplicated. A promise map collapses concurrent handshakes for the same name. Certificates are cached in memory and on disk under host-certs/. A name with at least three labels also gets a one-level wildcard SAN: api.myapp.localhost gets both DNS:api.myapp.localhost and DNS:*.myapp.localhost. The callback refuses any name outside the configured TLDs, so an unrelated name cannot make the proxy mint a trusted certificate. The CA certificate is appended to the served chain.

TLS certificate selection: first connection and cached reuse

TLS certificate selection: first connection and cached reuse

On a cache miss: 1. The browser sends myapp.localhost as TLS SNI. 2. The proxy finds no usable cached certificate. 3. The local CA signs a certificate with DNS:myapp.localhost. 4. The proxy caches the certificate and presents it to the browser. 5. The browser and proxy complete TLS. 6. The proxy forwards the subsequent HTTP request to 127.0.0.1:4317. A later connection can reuse the valid cached certificate and skip CA signing. The animation illustrates ordering, not elapsed time.

Port 443 needs privilege on macOS and Linux. portless proxy start probes the bind and re-executes itself under sudo only when the probe fails with EACCES. If elevation fails, it exits instead of silently moving to another port, because a URL with the wrong port is worse than a clear error.

--unprivileged is the escape hatch. On macOS a non-root process can bind a low port only on the wildcard address, so the proxy binds 0.0.0.0 and :: and refuses every non-loopback peer at accept, request, and upgrade. Linux needs net.ipv4.ip_unprivileged_port_start to cover the port. That mode serves HTTP on 80 by default, does not install the CA, and never writes the hosts file.

Custom certificates via --cert and --key skip the generated CA and the SNI callback; the proxy serves that one certificate. --no-tls serves plain HTTP on 80.

5. What it changes on the machine

Path or resource Purpose
~/.portless/routes.json hostname to loopback port mapping
~/.portless/routes.lock mutex directory for route writes
~/.portless/proxy.pid, proxy.port daemon discovery and liveness
~/.portless/proxy.log daemon output
~/.portless/proxy.tls, proxy.lan, proxy.unprivileged remembered proxy mode across restarts
~/.portless/ca.pem, ca-key.pem local root of trust
~/.portless/server.pem, server-key.pem default certificate
~/.portless/host-certs/ per-hostname certificates issued on demand
~/.portless/ca.trusted fingerprint of the CA already in the OS store
/etc/hosts managed block names for custom TLDs and some resolvers
OS trust store the CA certificate
ports 443 and 80 HTTPS proxy and HTTP redirect

State is shared under sudo. When the daemon runs as root, portless resolves ~/.portless from the invoking user's home via SUDO_USER, so the user's CLI and the root proxy read the same file. Files created by root are chowned back to the user.

.localhost names resolve to 127.0.0.1 in Chrome, Firefox, and Edge without a hosts entry. Safari uses the system resolver and may not. A custom TLD always needs an entry. The daemon owns the write because it may be root, so the CLI asks it over loopback: POST /.portless/hosts-sync with a token from the state directory, accepted only from a loopback peer, without Origin or Sec-Fetch-Site, and with a timing-safe token comparison. The daemon rewrites exactly the marked block, from # portless-start to # portless-end, verifies the result, and warns the caller if a name still does not resolve. PORTLESS_SYNC_HOSTS=0 disables the sync.

The route is also a process lease. Ctrl+C is forwarded to the child, and the route is removed when the wrapped command exits. If the command self-daemonizes, the route is handed to the surviving server's PID instead of being deleted with the launcher. portless prune terminates orphaned process groups whose route owner is dead, using the recorded PGID and start time so a reused PID is never targeted.

LAN mode is explicit. It binds all interfaces, publishes mDNS names under .local, and does not combine with a custom TLD.

The trust boundary is worth naming. The proxy listens on loopback only by default, and 421 blocks accidental cross-origin exposure. But the proxy is not a security boundary between local apps: it routes by Host, and any process that can write routes.json can choose what the root proxy connects to. The CA private key is a local root of trust. Treat write access to ~/.portless as equivalent to that trust, which is fine on a single-user dev machine and not fine as a shared service.

6. Failure modes

Symptom Cause Fix
404 no route for the Host, or a typo in the name check the printed URL, then portless list
421 a real domain resolves to 127.0.0.1 expected; portless refuses to serve local apps under it
502 app crashed, lost the port race, or is still starting restart the app; check proxy.log
508 a dev-server proxy loops back without rewriting Host set changeOrigin: true on the upstream
certificate warning CA not in the OS store, or a CA regenerated portless trust
stale route CLI died without cleanup routes with dead PIDs are filtered; portless prune
EADDRINUSE in the app another process won the port after probing let the next run pick another random port

portless doctor checks the whole chain without changing state: Node version, state directory permissions, proxy liveness, route validity, CA trust, hostname resolution, and LAN prerequisites. When a 502 is not obvious, proxy start --foreground prints each failed loopback connection and its error code.

7. Design lessons

  • A file is enough of a control plane. routes.json is inspectable, language-agnostic, survives daemon restarts, and needs no client library. The cost is locking, watching, and a polling fallback.
  • Liveness turns records into leases. The PID check is what makes a static file safe after a crash.
  • Put names at the edge and ports inside. Only the proxy knows the port mapping. Apps receive a normal PORT, and the browser receives a normal hostname.
  • TLS termination is also demultiplexing. SNI arrives before HTTP, so certificate selection and route lookup can share one hostname key.
  • Framework detection is where the abstraction leaks. The proxy is small; the flag classifier is not. Conservative skipping beats guessing.
  • Privilege is narrow but real. Only the bind needs root. The unprivileged path makes the trade explicit: wildcard bind plus peer filtering, no CA install, no hosts writes.

The result is not a service mesh. It is a local naming layer with four moving parts, each replaceable and each visible on disk. That is why it fits a dev machine: when something breaks, you can read the route file, the proxy log, and the certificate chain.

Sources

id 6apawahi5egp