The Hono server

Startup, the middleware chain, the routes, and two ways to sign in.

intermediate10 min read

You start Pipal and wait for the ready line. By the time the URL appears, the process has read its settings, claimed the data directory, and prepared a way for your browser to sign in. The next boundary is the first request the browser sends.

In this chapter

  • Explain what must open before Pipal listens and what closes after it stops listening
  • Follow the checks a request meets before it reaches Core
  • See how a token or passkey turns into an API session
  • Distinguish the public web build from the private data it displays

The host prepares the workspace before listening

From startup to ready
  • Node
  • Host
  • Core
  • Files
  • HTTP
  1. Node → Host · Import main.ts

    Start the TypeScript entry point

    The launcher tries to set up Node’s compile cache where its checks allow it, then imports main.ts.

  2. Host → Files · Read settings

    Read the configuration

    The host sets umask 077 and reads the configuration. The settings give it a bind address, a browser origin, and paths.

  3. Host → Files · Resolve paths

    Find the build and private data directory

    The host reads and validates pipal-base-path.txt in the build. Then it creates the data directory if needed, resolves its real path, and checks that it sits outside the build.

  4. Host → Core · createRuntime()

    Ask Core to prepare the runtime

    The host passes an initializer so the runtime can take ownership before anything loads host modules.

  5. Core → Files · Store lock

    Take the store lock

    Core takes an exclusive SQLite lock in owner.sqlite. A second Pipal process cannot open the same data directory while the lease is held.

  6. Core → Host · Initialize

    Load profiles, extensions, and workspace settings

    Under the lock, the callback loads profiles and enabled modules, assembles extensions, and calls loadWorkspaceLocations() to probe enabled locations before Core opens the conversation store.

  7. Core → Files · Open durable.sqlite

    Open the conversation store

    Core opens Pi Durable and restores deadline checks before calling harness.resume(). Waiting on a pending submission during that restore can already start scheduling.

  8. Host → Files · Open sign-in store

    Prepare workspace sign-in

    Depending on the mode, load the access token or open the passkey database. Passkey setup or recovery can also write a one-time code file.

  9. Host → HTTP · Listen

    Start taking requests

    The host creates the Hono app and gives its fetch handler to Node’s HTTP server on the loopback address.

  10. HTTP → Host · listening

    Report readiness

    After the listening event, the host starts any applicable provider warmup, then logs ready with the browser URL and the applicable sign-in file path, if any.

Node
Host
Core
Files
HTTP

Node → Host

Start the TypeScript entry point

The launcher tries to set up Node’s compile cache where its checks allow it, then imports main.ts.

Start at the launcher and follow the lock through startup. The ready line comes after the listener opens.

The first file is packages/server/src/start.mjs. It can set up Node’s compile cache, a place to keep compiled code for later starts, before importing main.ts. Then start() sets umask 077, which removes group and other permissions from newly created files, and calls loadConfig(). A missing default config.toml leaves the defaults in place. An explicitly named config must exist. start.mjs config.ts

A recovery request requires passkey mode. After checking that condition, the host looks for the built browser files in packages/web/build. It reads pipal-base-path.txt there to find the URL prefix the client was built for. Build for /ai/ and the app, the API, and the health check all sit under that prefix. The private data directory must resolve outside the build so the static file server can serve the web files freely. main.ts app.ts

Next, createRuntime() takes the store lock. Only then does the host’s callback load profiles, import enabled modules, and assemble extensions. This order matters when a second process points at the same data directory. It fails before the callback can open resources or start loading tools for that directory. index.ts main.ts

Inside the callback, loadWorkspaceLocations() reads the saved locationThe place a chat uses for project tools, either the Pipal host, an account reached over SSH, or a Docker project. selection and probes the enabled destinations before Pi Durable can resume work. A failed probe leaves the location selected. For a connection failure shown as Unavailable, use Retry connection in Settings → Workspace. The callback supplies Core with the location catalog and the project tool registrations. The core runtime follows the object the callback helps build. main.ts workspace-locations.ts

With Core open, the host prepares the selected sign-in method and creates the Hono app. Node listens only on loopback, an address that accepts connections from the same machine. The local listener speaks HTTP. A reverse proxy can supply HTTPS at the configured browser origin, so the page and its API share one origin. Deploying Pipal shows that arrangement. config.ts main.ts

Deep diveWhat the ready line and shutdown signal guarantee

If extensions.enabled includes pipal.public-web, the setup callback adds publicWebExtension to the list it returns to core. The host contacts Exa for a search or Jina Reader for a page when Developer calls the tool. Tools and extensions follows both requests. main.ts public-web.ts

ready gives the configured origin and the workspace URL with its base path. It gives the token file path in token mode and the code file path when the passkey store issued a grant. The log follows the listening event and the start of any background provider module warmup. The host then installs the shutdown handlers, flushes the compile cache, and waits for the listener to close. main.ts

The first SIGINT or SIGTERM aborts the host’s shutdown signal and stops the HTTP listener. Event streams use that signal and can end immediately. A timer closes any remaining HTTP connections after five seconds. If runtime.closed reports failure, the host logs storage_failed, sets exit code 1, and calls the same stop function. main.ts app.ts

After HTTP closes, the host removes its signal handlers and enters cleanup. It aborts the shutdown signal, closes pending provider sign-in, closes the passkey store if open, and then closes Core. Core cancels deadline timers and waits for the admission queue, searches, and workspace settings changes before closing Pi Durable and releasing the lock. The outer cleanup also closes the Code Mode sandbox if one was opened. Durable by default follows the tasks that are still pending when Core closes. main.ts index.ts

The request passes through checks in order

Code that runs around or before a route is called middlewareCode that runs around or before an HTTP route and can end the request before the route runs.. Pipal’s first middleware sets X-Content-Type-Options: nosniff, X-Frame-Options: DENY, and Referrer-Policy: no-referrer. It then checks the requested host against the configured origin’s host and the local listener’s host. An unrecognized host gets 403. That applies even to a health check or an app shell request. GET /healthz can answer {"ok":true} as soon as it passes that check. app.ts

Under /api, Hono tells caches to keep no copy of the response. For methods other than GET and HEAD it requires the exact configured Origin, or returns 403. It then checks the session and returns 401 if it is missing or expired. Only GET and HEAD for /api/v1/access and the public sign-in and enrollment POSTs for the configured mode skip that session check. Next comes the route-specific body limit, then the route handler. A public sign-in POST still has to pass the origin check. The security model explains the boundaries those checks enforce. app.ts

A route expecting JSON calls body() to check the media type, parse the JSON, and validate its fields with a schema. Hono keeps the status and message of a known request error or Core’s RuntimeError, plus the runtime error code when present. Unexpected errors become a generic 500, with the method recorded in the log. The HTTP API at a glance lists what each route accepts. request.ts app.ts

Route What it does
GET /api/v1/settings/workspace Read the revision, enabled locations, connection details and new-chat defaults.
PUT /api/v1/settings/workspace Save the location and approval preferences using the revision the owner loaded, or retry the current selection.
GET /api/v1/profiles Report enabled locations, the default location and any YOLO default for workspace-capable profiles.
GET /api/v1/extensions List enabled extensions, omitting project tool extensions while no enabled location is open.
Four protected routes expose the owner’s selection and its effect on what a chat can use.

start() passes the configured extension list to Hono. The GET /extensions handler filters it against Core’s current view each time, so the list can reflect a location opening or closing while the host runs. main.ts app.ts

A refresh on /chats/:id gets index.html again, so the client can open that chat from the URL. Other paths fall through to the static files. Hono marks successful responses under /assets/, where Vite writes its hashed bundles, as public and immutable for 31,536,000 seconds. It asks caches to revalidate other successful static responses and sets Vary: Accept-Encoding if there is no Vary header. Hono can serve precompressed files when available. With a base path, it redirects the bare prefix to its trailing-slash URL with 308 and preserves the query string. An unknown API path gets a JSON 404 after the applicable API checks. app.ts

Deep diveThe body limit depends on the route

The API middleware selects 128 KiB for ordinary requests, 10 MiB for POST /api/v1/uploads, and 8 MiB for extension paths. These limits count bytes. The checks inside Core and the schema can apply different limits to individual fields. A body over its route’s limit gets 413, a JSON route with the wrong media type gets 415, and malformed JSON or a schema mismatch gets 400. app.ts contracts.ts request.ts

packages/server/src/request.ts
export async function body<T>(c: Context, schema: Validator<T>): Promise<T> {
if (c.req.header('Content-Type')?.split(';')[0]?.trim().toLowerCase()
!== 'application/json') {
throw new HTTPException(415, { message: 'Use application/json.' });
}
const value: unknown = await c.req.json().catch(() => {
throw new HTTPException(400, { message: 'Invalid JSON.' });
});
if (!schema.check(value))
throw new HTTPException(400, { message: 'Invalid request fields.' });
return value;
}

Both sign-in methods open the same workspace

Two ways to sign in
FeatureAccess token server.auth = "token"Passkey server.auth = "passkey"
First entryRead data/access-token on the host and enter it in the browser.Use the host’s setup code to register a passkey.
Later sign-inSend the same secret to POST /api/v1/session as {token}.Ask for a challenge and have your authenticator sign it.
What the host keepsThe token file. The app compares SHA-256 digests when you sign in.Public credentials and counters in data/passkeys/auth.sqlite.
What the browser getsA pipal_session cookie.The same kind of pipal_session cookie, linked to the credential.

Choose up to two columns

FeatureAccess token server.auth = "token"Passkey server.auth = "passkey"
First entryRead data/access-token on the host and enter it in the browser.Use the host’s setup code to register a passkey.
Later sign-inSend the same secret to POST /api/v1/session as {token}.Ask for a challenge and have your authenticator sign it.
What the host keepsThe token file. The app compares SHA-256 digests when you sign in.Public credentials and counters in data/passkeys/auth.sqlite.
What the browser getsA pipal_session cookie.The same kind of pipal_session cookie, linked to the credential.
Compare what proves your identity at sign-in and what the browser uses afterward.

Token mode is the default. If the token file is absent, Pipal writes a secret generated from 32 random bytes to data/access-token with mode 0600. On startup it opens the file without following symlinks and requires a regular file with one link, no group or other permissions, and at most 256 bytes. After trimming, the token must be 43 base64url characters. config.ts auth.ts

The sign-in screen fetches GET /api/v1/access to find the mode. Access.svelte

In token mode, the browser trims what you enter and sends {token} to POST /api/v1/session. A bad token gets 401. A match creates a session and returns 200 with {ok: true}. App.svelte app.ts

Deep diveWhat token sign-in returns and what sign-out clears

The route accepts a token string of 0 to 256 UTF-16 code units. It hashes the received string with SHA-256 and compares it to the stored digest with timingSafeEqual(). Successful token sign-in issues a new session record and sets the cookie. A previous token session can still exist in the host’s map until it expires or is evicted. Sign-out uses DELETE /api/v1/session, ends the session named by the cookie, clears that cookie, and returns {ok: true}. app.ts request.ts auth.ts

A browser sessionA sign-in record in server memory that the browser refers to with a cookie. is an in-memory record that lets your tab keep making requests after sign-in. The browser sends its random ID in the pipal_session cookie. The ID comes from 32 random bytes encoded as base64url. The server record lasts 12 hours from issue, and requests use the same expiry. The host holds at most 32 records and evicts the oldest issued session before creating another at capacity. auth.ts

Sign-out, expiry, and eviction end the session and signal its open watches to close. Passkey removal also ends sessions issued to that key, and passkey recovery revokes all existing sessions. Restarting Pipal drops the entire in-memory map. Live streams follows how an open stream ends when its session does. Profiles and models covers sign-in to the model account. auth.ts passkeys.ts

A passkey answers a fresh challenge

From challenge to session
  • Browser
  • Device
  • Hono passkeys.ts
  • Store

Set up

  1. Browser → Hono · Enroll options

    Present the setup code

    POST /api/v1/session/passkey/enroll/options sends {code, name}. The code comes from the host.

  2. Hono → Browser · Challenge and cookie

    Start a registration

    Hono checks the active grant and its code digest, generates registration options, and checks that the grant is still active. It returns the options with a 200 and a temporary pipal_passkey cookie that identifies the enrollment in memory.

  3. Browser → Device · Create credential

    Ask the authenticator to make a key

    The browser hands it the registration options. The authenticator verifies you and creates a credential for this site.

  4. Device → Browser · Registration result

    Return the credential response

    The response carries what Pipal needs to register the public credential.

  5. Browser → Hono · Enroll verify

    Return the registration to Pipal

    POST /api/v1/session/passkey/enroll/verify sends the registration response as JSON. The browser sends the enrollment cookie with it. Hono takes the flow out of memory before verifying the response.

  6. Hono → Store · Save credential

    Keep the public credential

    After SimpleWebAuthn verifies the response, Pipal rechecks the flow, inserts the credential, and clears the grant in the same turn. It then tries to remove the code file.

  7. Hono → Browser · Session cookie

    Enter the workspace

    Pipal ends any prior session named by the browser’s cookie and answers 200 with {ok: true} and a new pipal_session cookie.

Sign in

  1. Browser → Hono · Sign-in options

    Ask for a fresh challenge

    POST /api/v1/session/passkey/options sends {} to request authentication options.

  2. Hono → Browser · Challenge and cookie

    Receive the challenge

    With at least one key enrolled, Hono returns 200 with authentication options. It puts the challenge, expiry, and current epoch in a signed pipal_passkey cookie.

  3. Browser → Device · Request assertion

    Ask the authenticator to prove it has the key

    The browser hands over the options and the authenticator asks you to verify yourself.

  4. Device → Browser · Signed assertion

    Return proof for this challenge

    The authenticator signs using the credential it already holds.

  5. Browser → Hono · Sign-in verify

    Send the proof to Hono

    POST /api/v1/session/passkey/verify sends the assertion as JSON. Pipal checks the signed cookie, loads the credential by ID, checks the user handle, and asks SimpleWebAuthn to verify the assertion.

  6. Hono → Store · Update counter

    Record the successful verification

    Pipal rechecks the flow and updates the counter if the stored key and prior counter still match. Then it records the used challenge in memory.

  7. Hono → Browser · Session cookie

    Enter the workspace

    Pipal ends any prior session named by the browser’s cookie and answers 200 with {ok: true} and a credential-linked pipal_session cookie.

Browser
Device
Hono passkeys.ts
Store

Browser → Hono

Present the setup code

POST /api/v1/session/passkey/enroll/options sends {code, name}. The code comes from the host.

Compare setting up a key with signing in using one. Each path makes an options POST and a verify POST. The device is your authenticator, and the store is auth.sqlite. Follow what the browser holds between the requests.

Use a passkey-capable browser at the configured HTTPS origin or at localhost. config.ts Access.svelte

Passkey setup starts with a code from data/passkeys/setup-code, using the default data directory. The browser asks the host for a challenge, then asks an authenticator, such as your device’s passkey manager, to create a credential. The browser sends the result back so Pipal can verify it and save the public key. This exchange is a passkey ceremonyThe exchange in which a server issues a challenge and a browser returns the authenticator’s response for verification.. On a later sign-in, the authenticator uses the existing key to sign a new challenge. passkey-store.ts Access.svelte

Deep diveWhere the two passkey requests keep their state

Registration requests a discoverable credential and user verification, with no attestation requested. The host stores the enrollment flow in memory for 120 seconds and sends its ID in a temporary pipal_passkey cookie. The verify handler consumes that record before verifying the response. Ordinary sign-in requests user verification with an empty allow-list and puts the challenge, expiry, and recovery epoch in a signed cookie of the same name. Issuing those options needs no entry in the flow map. Both flow cookies inherit the session cookie’s Path, HttpOnly, SameSite, and Secure settings, with Max-Age=120. app.ts passkeys.ts

Authentication checks the saved credential and stored user handle before calling SimpleWebAuthn. Registration and authentication both verify the challenge, configured origin, relying-party ID, and user verification. After an assertion verifies, Pipal checks the flow again and conditionally updates the counter using the previous counter and public key. A successful sign-in challenge is remembered until its expiry to reject reuse. The server caps pending in-memory flows at 128 and concurrent verification calls at eight. Either limit returns 429. Flow expiry or failed verification gets 403, while a duplicate registered credential gets 409. A new key’s trimmed name must be 1–80 UTF-16 code units long. passkeys.ts passkey-store.ts

Passkey startup opens auth.sqlite in the private passkeys/ directory. It removes old code files and issues a setup code if no key exists, or recovery-code if a key exists and PIPAL_PASSKEY_RECOVERY=1. Requesting recovery without an enrolled key fails startup. The code file is created with mode 0600 and holds a 43-character code generated from 32 random bytes, while the in-memory grant holds its digest and expires in ten minutes. Successful enrollment inserts the credential and clears the grant in the same turn, then tries to delete the file. Recovery keeps the existing credentials, increments the recovery epoch, clears pending flows, and revokes sessions before issuing the new session. main.ts passkey-store.ts passkeys.ts

To change keys while signed in, the browser posts {name} to add or {remove} with the target ID to remove at /api/v1/passkeys/change/options. It uses an enrolled key to answer that challenge at /api/v1/passkeys/change/verify. Removal checks the target twice, keeps at least one key, and revokes the removed key’s sessions. The response’s signedOut indicates whether that includes the current session. For an addition, change verification returns new registration options. The browser creates the credential and posts it to /api/v1/passkeys/add/verify. Pipal checks that the same session and confirming key are still valid before saving the new credential and returning {ok: true}. passkeys.ts passkey-store.ts

Once a signed-in message has passed the HTTP checks, what decides whether it can start a run? The core runtime takes the request from there.

Recap

  • The host claims the store and opens Core and workspace sign-in before it listens.
  • Hono checks host, origin, session, size, and request shape at different points. The shell can load before sign-in.
  • A token or verified passkey issues a browser session. The session map lives in the process.
Check yourself
  1. You refresh a saved chat URL after Pipal restarts. What can the old tab still load?
    • The app shell, then it must sign in for the chat data
    • Private chat data using its pre-restart session
    • Only the health check
    Answer and explanation

    The app shell, then it must sign in for the chat data

    The shell is served from the build. Restart removes the map that made the old cookie a valid API session.

  2. The token is correct but its sign-in POST has a different Origin. How far does the request get?
    • It creates a session
    • It fails before the token comparison
    • It waits for Core’s admission queue
    Answer and explanation

    It fails before the token comparison

    The sign-in route is public for session purposes. The Origin check runs first and still applies to the POST.

  3. Two Pipal processes point at one data directory. When does the second discover the conflict?
    • After both start listening
    • When its first message is sent
    • Before it loads host modules in the initializer
    Answer and explanation

    Before it loads host modules in the initializer

    createRuntime acquires the store lock before calling the initializer.

  1. You refresh a saved chat URL after Pipal restarts. What can the old tab still load?

  2. The token is correct but its sign-in POST has a different Origin. How far does the request get?

  3. Two Pipal processes point at one data directory. When does the second discover the conflict?

In the source

Book contents

Search the book