Skip to content

About

Dockerized Routstrd for teams

Resources

Security policy

Stars

6 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

193 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

routstrd-auth

Standalone auth proxy for routstrd. Sits in front of the daemon, validates Authorization: Bearer sk-... tokens, and forwards requests.

Why?

Keeps auth as a separate, replaceable layer. The daemon itself runs unauthenticated on localhost only; the proxy is the public-facing gatekeeper.

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Clients   β”‚ ───► β”‚  routstrd-auth   β”‚ ───► β”‚  routstrd    β”‚
β”‚ (CLI, Pi,   β”‚      β”‚  :8008 (public)  β”‚      β”‚  :8009 (local)β”‚
β”‚  OpenCode)  β”‚      β”‚  Bearer token    β”‚      β”‚  No auth     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Configuration

All values have sensible defaults and can be overridden via environment variables or CLI flags.

Variable Default Description
ROUTSTRD_AUTH_PORT 8008 Public port
ROUTSTRD_AUTH_HOST 0.0.0.0 Bind host
ROUTSTRD_UPSTREAM http://localhost:8009 Upstream routstrd URL
ROUTSTRD_DB_PATH ~/.routstrd/routstr.db Shared SQLite DB
ROUTSTRD_AUTH_MODEL_ALLOWLIST false Enable model allowlist enforcement (true/false)
ROUTSTRD_AUTH_PUBLIC_URL CLOUDRON_APP_ORIGIN, then request headers Origin NIP-98 signatures must bind to, e.g. https://routstr.example.com
ROUTSTRD_AUTH_REPLAY_CACHE_MAX 16384 Maximum retained NIP-98 IDs per proxy (1–1000000); fails closed when full
ROUTSTRD_AUTH_BOOTSTRAP_TOKEN generated One-time token required to claim the first admin while no npub is registered
ROUTSTRD_DIR ~/.routstrd Base config directory

First admin registration

Starting the auth proxy seeds the identity in config.json as the first admin, so an instance has an admin from its first boot and the first-admin slot is never claimable by an anonymous caller.

That identity is the one routstrd itself holds and signs NIP-98 with, so the bundled CLI is an admin out of the box. From a shell in the container (Cloudron: the app's Web Terminal, or cloudron exec --app <domain>):

routstrd npubs list          # shows the container's own npub, marked "β†’ you"
routstrd status              # balances, daemon state

# Add a person as an admin. Their npub comes from `routstrd remote <url>`
# on their own machine.
routstrd npubs add npub1... --role admin --name "Alice"

# Optional: name the container's own identity so the startup warning stops.
routstrd npubs update <container npub> --name "Routstr Box"

Nothing to copy out of a log, and no token: the first admin already exists, and NIP-98 from it is what authorises adding more. ROUTSTRD_AUTH_ADMIN_NPUBS (or ROUTSTRD_AUTH_ADMIN_PUBKEYS) still adds admins from outside the container, and those are re-applied at every start.

Why this is safe: the window the token used to guard existed because a freshly installed app is publicly reachable before its operator has configured anything. Seeding an admin at boot means the npub table is never empty, so POST /npubs always requires NIP-98 from an existing admin β€” the anonymous claim path is never reachable on a normal install.

The token machinery is still in the proxy and still works, but it is a fallback rather than the normal path: it only appears when the proxy starts with an empty npub table and no seeded admin in ROUTSTRD_AUTH_ADMIN_NPUBS β€” that is, when the app is run outside the packaged entrypoints, or when every npub has been deleted and the seed cannot be re-applied.

If you delete every npub, the table is empty again until the next start re-seeds the container identity (which happens on every boot, so the window re-closes by itself). A proxy started without that seed prints a one-time token instead, as documented below.

Cloudron

Cloudron runs the routstrd server. Team members connect to it as clients using the routstrd CLI.

Initial Setup (first person)

The app's own Nostr identity is already the first admin, so nobody has to claim a slot over HTTP. From the app's Web Terminal:

routstrd npubs add <your npub> --role admin --name "Alice"

Your npub comes from the CLI on your own machine:

# Install the CLI client globally
bun i -g routstrd

# Connect to your Cloudron instance (this prints your npub)
routstrd remote <cloudron-url>

Then, on your machine, routstrd npubs list, add and update work as an admin.

routstrd clients add --pi-agent    # for Pi Agent
routstrd clients add --claude-code # for Claude Code
# ...and more

Adding Team Members

Anyone joining an existing routstrd Cloudron instance does the same initial steps:

  1. bun i -g routstrd β€” install the CLI
  2. routstrd remote <cloudron-url> β€” connect to the instance (this generates a unique npub for the new person)
  3. Give that npub to someone who already has access
  4. That person runs: routstrd npubs add <npub> β€” grants access
  5. The new member can now add clients (e.g. routstrd clients add --claude-code) and start using routstrd

Tracking Usage

Every team member gets their own npub, and every client they register gets a unique ID β€” making it easy to track team usage from the Cloudron terminal.

# Individual: see your own usage
routstrd top

# Anyone with access to the Cloudron terminal: see everything
# The clients tab shows individual usage, with the last 7 chars of each npub
# appended to client IDs for easy identification
routstrd top

Monthly spend limits per npub

Admins can cap how many sats each npub may spend per calendar month. The proxy checks the cap before forwarding a paid request and returns 402 once the npub has reached it, so every client that member owns is blocked together.

# Cap a new team member at 5,000 sats/month
routstrd npubs add npub1... --limit-sats 5000

# Change or remove the cap later
routstrd npubs update npub1... --limit-sats 20000
routstrd npubs update npub1... --clear-limit

# See limits and current-month spend
routstrd npubs list

The --limit-sats/--clear-limit flags require a routstrd CLI release that includes them (the proxy accepts the same fields over HTTP regardless).

The same controls are available over HTTP when you do not want to use the CLI:

# Set (or clear with null) the cap
curl -X PATCH "$AUTH_URL/npubs" -H "Authorization: Nostr <base64-event>" \
  -H 'Content-Type: application/json' \
  -d '{"npub":"npub1...","monthlyLimitSats":5000}'

# POST /npubs also accepts "monthlyLimitSats" when adding a member
curl "$AUTH_URL/npubs" -H "Authorization: Nostr <base64-event>" \
  -H 'Content-Type: application/json' \
  -d '{"npub":"npub1...","role":"user","monthlyLimitSats":5000}'

Semantics:

  • The month follows the proxy server's local timezone (UTC in the Cloudron container unless TZ is set). Spend resets to zero at 00:00 on the first of each month and no admin action is needed.
  • Spend is the daemon's usage_tracking.sats_cost for every client owned by the npub, attributed by ownerNpub and falling back to the 7-character npub suffix on client ids (so deleting and re-creating a client does not reset the total).
  • The request that crosses the cap is allowed to finish β€” its cost is only known after it completes. Every following paid request is blocked until the month rolls over or an admin raises/clears the limit.
  • Only paid inference requests (POST to model endpoints) are blocked. Wallet, client, usage, provider and npub management routes keep working, so an npub that is over its limit can still list clients or ask an admin for help (and an admin can always fix the limit).
  • If monthly usage cannot be read (including a missing usage table), capped API-key inference returns 503 with code: "quota_accounting_unavailable". Unlimited inference and management routes remain available. Npub list/update responses omit monthlyUsedSats when accounting is unavailable rather than reporting zero. Errors are logged; enforcement resumes when reads recover.
  • monthlyLimitSats: 0 blocks all paid requests. Omit it or set it to null for unlimited.
  • Paid NIP-98 requests from capped npubs are rejected with 403 and code: "capped_npub_requires_api_key", regardless of current spend. Use an API-key client so the daemon can account for spend. Unlimited npubs can still use NIP-98 inference, and management routes remain available to capped npubs.

Usage

Vanilla Docker

This project is intended to be run with plain Docker. Docker Compose is not required.

Build the image:

docker build -t routstrd-pro-image .

Run the container with a persistent bind mount:

docker run -d \
  --name routstrd-pro \
  --restart unless-stopped \
  -p 18008:8008 \
  -v $HOME/routstrd-data:/app/data \
  routstrd-pro-image

Important: The bind mount $HOME/routstrd-data:/app/data is crucial for persisting data across container restarts and updates. Without this volume mount, all data will be lost when the container is removed.

The service is now available on the host at:

http://localhost:18008

Check the health endpoint:

curl http://localhost:18008/health

Follow logs:

docker logs -f routstrd-pro

Stop and remove the container:

docker stop routstrd-pro
docker rm routstrd-pro

Rebuild and restart after changes:

docker stop routstrd-pro
docker rm routstrd-pro
docker build -t routstrd-pro-image .
docker run -d \
  --name routstrd-pro \
  --restart unless-stopped \
  -p 18008:8008 \
  -v $HOME/routstrd-data:/app/data \
  routstrd-pro-image

Note: EXPOSE 8008 in the Dockerfile only documents the container port. Host port publishing, restart policy, container name, and volume mounting are configured with docker run flags.

Local development

# Install dependencies
bun install

# Validate config & DB connectivity
bun run src/index.ts validate

# Start the proxy
bun run src/index.ts start

# Start on a different port
bun run src/index.ts start -p 8080

# Point at a custom DB
bun run src/index.ts start -d /path/to/routstr.db

Manage clients with routstrd

Use the routstrd CLI to add and list clients through the auth proxy:

routstrd remote https://your-app.example.com
routstrd clients add --name "My Laptop"
routstrd clients list

routstrd remote prints your npub. If it isn't registered yet, ask an admin to add it before running the client commands. Registered members can add and list their own clients; admin access isn't required.

The CLI signs requests automatically with its configured Nostr identity. This proxy validates the NIP-98 signatures in src/nip98.ts.

Running alongside routstrd

  1. Start routstrd on a local-only port (e.g. 8009).
  2. Start routstrd-auth on the public port (8008).
  3. Clients send Authorization: Bearer sk-... to :8008 as normal.

Auth behaviour

  • Public endpoints (GET /health, /ping, /models, /v1/models, /models/:model/providers, /models/:model/paths, and HEAD /v1/models) β€” forwarded immediately, no token needed. Balance routes are not public: they need a registered-npub NIP-98 identity.
  • Forwarded endpoints β€” client API keys (Bearer or x-api-key) are limited to the method/path pairs Routstr Core's own allowlist forwards (_ALLOWED_ENDPOINTS in core's routstr/proxy.py); anything else is a 403. That covers the inference routes (chat/completions, completions, responses, messages, messages/count_tokens, embeddings, systemone, decisions) and the image routes. Daemon state and control routes β€” GET /balance, /keys/balance, /providers, /cooldowns, /status, /version, /settings/*, /wallet/*, /requests/* β€” are npub-only. Only method/path pairs classified in src/daemon-routes.ts can reach the daemon. Unclassified operations are refused even for signed admins. Among the classified routes, these require an admin npub:
    • anything that moves value: POST /wallet/send/cashu, /wallet/send/bolt11, /wallet/sweep-offline, /wallet/send/cashu/<id>/mark-spent, /wallet/recover, /wallet/recover/operations
    • wallet integrity: POST /wallet/unlock, /wallet/cleanup, /wallet/check-proofs, and the mint setters POST /wallet/mints and /wallet/mints/default (the GET reads and /wallet/mints/info stay open to any registered npub). check-proofs is not a read despite the name: it marks mint-reported proofs spent, which reclaims balance and finalizes reserved sends
    • provider API-key listing and deletion
  • Registered npubs β€” stored in the shared routstr.db table routstr_auth_npubs. Env-configured admins are bootstrapped into that table at startup. Removing a pubkey from ROUTSTRD_AUTH_ADMIN_NPUBS takes admin away but keeps the registration: on the next start the row becomes an ordinary user (source flips from env to api, name and monthly limit are kept), so the npub's existing API keys keep working and the npub table never empties out and re-opens the first-admin bootstrap. A startup warning names every npub this happened to. To revoke the npub completely, use DELETE /npubs/<npub>; to keep it as an admin managed in the database, PATCH /npubs it with role: "admin". Listing a pubkey in the variable always makes it an env-managed admin, even if it was registered through the API before. The exception is a pubkey on the retirement list in src/store.ts, which is deleted outright β€” that list exists for known-compromised admins such as the default docker-entrypoint.sh used to ship, and adding to it is a permanent, deliberate act.
  • List npubs β€” GET /npubs returns { "npubs": [...] } with each npub's npub, name, role, monthlyLimitSats (null = unlimited), plus a top-level monthlyResetAt (Unix seconds). Admins also get every npub's monthlyUsedSats; a member only gets their own. Requires NIP-98 auth from a registered npub.
  • Add npubs β€” POST /npubs with { "npub": "npub1..." } or { "pubkey": "<64-char hex>" }, optionally { "role": "user", "name": "Alice", "monthlyLimitSats": 5000 }. If no npubs are configured yet, this first add requires the one-time bootstrap token in the x-routstr-bootstrap-token header (see First admin registration); after that it requires NIP-98 auth from an existing admin. Duplicate npubs return 409; use PATCH /npubs to update an existing entry.
  • Body limits β€” the npub and client management routes accept at most 1 MiB of JSON and answer 413 beyond that. Credentials are checked before the body is read, so an unauthenticated caller cannot make the proxy buffer a payload.
  • Update npubs β€” PATCH /npubs with { "npub": "npub1..." } or { "pubkey": "<64-char hex>" } plus role, name and/or monthlyLimitSats. Requires NIP-98 auth from an existing admin. Set name to null to clear it and monthlyLimitSats to null to remove the monthly cap.
  • Monthly spend cap β€” paid requests are checked against the npub's cap and return 402 with code: "monthly_quota_exceeded" and X-Routstr-Quota-* headers once it is reached. See Monthly spend limits per npub.
  • Remove npubs β€” DELETE /npubs/<npub-or-pubkey> (or DELETE /npubs?npub=...) requires NIP-98 auth from an existing admin. Removal takes effect on the next request: every API key whose recorded owner is that npub is refused with 403 and code: "client_owner_not_registered" until the npub is registered again, so removing a member also stops the clients they already created. The keys themselves stay in the daemon's storage. Clients created before owner attribution existed record no owner and are unaffected, because the id suffix is the only signal they carry; the proxy warns at startup about keys whose recorded owner is missing. The last admin cannot be removed or demoted (409, code: "last_admin"): with no admin left nobody can add an npub, so the instance has to be recovered out-of-band. Add another admin first.
  • Forwarded headers β€” the proxy strips Authorization and injects x-routstr-client-id so the daemon knows which client made the request.
  • NIP-98 URL binding β€” the u tag must match the public URL of the request. Set ROUTSTRD_AUTH_PUBLIC_URL (e.g. https://routstr.example.com) to bind to a fixed origin. Only an HTTP(S) origin is accepted: no credentials, non-root path, query, or fragment. On Cloudron, CLOUDRON_APP_ORIGIN is used automatically when this override is unset or blank. If neither is set, the proxy derives the URL from the request's Host / x-forwarded-* headers, which the caller supplies, so a deployment that does not sit behind a proxy which overwrites them can have events signed for another host replayed here. The startup log says which mode is in effect.
  • Replay β€” authenticated NIP-98 events are single-use. Sign a fresh event with a random nonce tag for every request, including identical requests within the same second. Duplicate IDs return 401, code: "nip98_replayed". Events are recorded only after registration and role checks, before executing the action; later failures still consume the event. The read-only empty-table bootstrap GET /npubs is exempt. Each proxy keeps its own in-memory cache: protection does not survive restarts or span instances. IDs are retained for 125 seconds, never evicted early. At capacity, new events return 503, code: "replay_cache_saturated", with Retry-After; saturation warnings are limited to once per minute. Expired IDs are removed lazily on the next authorized request. Logical authentication time never moves backwards: after a clock rollback it waits for wall time to catch up, and a forward jump permanently invalidates older events within that proxy instance. Correct a bad clock before restarting; restarts lose replay history.
  • Replay capacity β€” ROUTSTRD_AUTH_REPLAY_CACHE_MAX accepts integers 1–1000000 (default 16384). This initial policy accommodates about 131 accepted requests/second sustained over the 125-second retention period, not a measured traffic guarantee. Size it for your peak traffic; authorized members share the global budget. Replay protection is not payment idempotency: automatically re-signing/retrying a money-moving request after a lost response can execute it twice.
  • Release prerequisite β€” ship the routstrd signer nonce fix (9a60f13, NGIT PR linked in NIP98.md) in the bundled daemon before releasing this replay guard. The signer PR is not a released dependency yet; no bundled version is changed here. Older clients without unique event tags can receive false replay refusals for identical same-second requests. Unknown tags remain accepted; the server does not require a particular nonce tag.

License

MIT

About

Dockerized Routstrd for teams

Resources

Security policy

Stars

6 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages