768 Commits
Author SHA1 Message Date
9qeklajc 4cc9aef61f fix: make payouts and proxy sessions safe 2026-07-30 02:57:49 +02:00
9qeklajc 5ea5024608 resolve review comments 2026-07-29 22:50:33 +02:00
9qeklajc 39f801561b fix: recreate refund sweep migration on latest head 2026-07-26 12:52:24 +02:00
9qeklajc ff55788e2d fix: address PR 634 review feedback 2026-07-26 12:44:37 +02:00
9qeklajc 7108d554c8 merge: combine PR #632 with broader pool-exhaustion fixes 2026-07-24 23:22:01 +02:00
9qeklajc b0c70ecddc fix: send Cashu token creation payload in request body 2026-07-24 23:01:10 +02:00
Jeroen UbbinkandClaude Opus 4.8 a2cedd6769 feat: make the DB connection pool env-configurable
Add DATABASE_POOL_SIZE / DATABASE_MAX_OVERFLOW / DATABASE_POOL_TIMEOUT,
consumed like every other typed env var through the pydantic Settings
(constrained Fields, defaults 5/10/30 matching SQLAlchemy's own baseline
so leaving them unset is behaviour-neutral). An out-of-range or
non-integer value fails validation and refuses to boot — the same
fail-loud behaviour a malformed DATABASE_URL already has — rather than
silently starting up misconfigured. create_db_engine sizes the pool from
these and logs the effective values at startup so they can be confirmed
from the boot output during an incident. In-memory SQLite (StaticPool,
which rejects the pool kwargs) is detected and built without them.

pool_pre_ping is deliberately not exposed: the default backend is a local
SQLite file with no network peer to drop idle connections, so it would add
a SELECT 1 per checkout for no benefit — and it detects dead connections,
not the live-but-wedged ones behind the exhaustion this series addresses.

These knobs are infrastructure the node needs before it can open a DB
session, so they can never be sourced from the DB (chicken-and-egg). A new
ENV_ONLY_FIELDS set keeps them out of the persisted settings blob and
stops a DB value from shadowing env in both SettingsService.initialize and
.update, so env stays authoritative.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 22:26:57 +02:00
Jeroen UbbinkandClaude Opus 4.8 7b0ade3987 fix: stop AsyncSession pool exhaustion in balance reads
fetch_all_balances shared a single AsyncSession across the tasks it ran
with asyncio.gather. AsyncSession is not safe for concurrent use: the
overlapping queries raised "concurrent operations are not permitted" and
left connections wedged until the QueuePool was exhausted, after which
admin/API endpoints returned 500/502 until a container restart.

Read all outstanding user liabilities up front in one short-lived session
with a single grouped query (balances_by_mint_and_unit), then run the
per-mint balance checks concurrently with no session in scope. A failure
reading liabilities now degrades gracefully — the page still reports the
known wallet custody and blanks only the unknowable user/owner split,
tagging each mint with the error — instead of 500-ing the whole page.

periodic_payout reads each liability fresh, immediately before the payout
decision, rather than from a single pre-loop snapshot: the per-mint round
trip is slow, and a user top-up during the cycle would otherwise let a
later mint/unit act on a stale-low liability and over-send funds owed to
users (related to the payout-safety concern in issue #611).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 22:26:25 +02:00
9qeklajc 2410a4a6ce fix: address review findings on payout liability staleness, sweep races, and cancellation safety
- periodic_payout: fetch liability per mint/unit right before computing
  available balance, so a concurrent top-up can only shrink the payout
- refund sweep: atomically claim each refund before redeeming; release the
  claim on failure so retries still happen and concurrent sweeps cannot
  misreport a sweep as client-collected
- check_invoice_payment: catch BaseException so task cancellation after a
  successful mint still emits the reconciliation alert
- tests: DB-guard race test where both mints succeed (exactly one credit);
  pool_size=1 test proving the fee payout releases its connection during
  the external send
2026-07-24 22:14:57 +02:00
9qeklajc 7394b10e75 fix-concurent-issue 2026-07-24 21:29:21 +02:00
9qeklajc 66ba31d0df Merge remote-tracking branch 'origin/main' into fix/streaming-billing-finalization 2026-07-24 02:05:58 +02:00
9qeklajcandGitHub a9593ab416 Merge pull request #570 from jeroenubbink/feat/config-ownership-secrets
feat(config): store node secrets in an encrypted vault
2026-07-24 02:02:21 +02:00
9qeklajcandGitHub 6221ee8152 Merge pull request #628 from Routstr/fix/cashu-reservation-recovery
fix(wallet): recover stale Cashu reservations safely
2026-07-24 01:12:57 +02:00
9qeklajc 65ea28cb85 add test 2026-07-24 01:10:57 +02:00
9qeklajc 2ed20b1b85 resolve reviews 2026-07-24 00:24:24 +02:00
Jeroen UbbinkandClaude Opus 4.8 f47e16aa61 refactor(admin): remove the unreachable /api/setup endpoint
Generated-password bootstrap now sets an admin password on every fresh node, so
the /admin/api/setup success path is unreachable — it 409s ("already set") on
any booted node. No caller exists across the admin UI, routstr-cli, routstr-sdk,
routstrd, or routstr-chat, so the endpoint (and its SetupRequest model) are dead
surface. First-run is now: the generated password is printed once at boot, log
in via /admin, and change it from the dashboard.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:21 +02:00
Jeroen UbbinkandClaude Opus 4.8 eb6a612e5a fix(secrets): make nsec ownership explicit and claim the admin password atomically
Two bootstrap-correctness fixes on the encrypted Secret store:

- Track nsec ownership with an explicit nsec_state (legacy | encrypted |
  cleared) instead of a nsec_managed bool. The bool could not tell "never
  migrated" apart from "intentionally cleared" — both leave encrypted_nsec
  empty — so a cleared identity could be resurrected on a fresh process from a
  stale legacy NSEC (env or old settings blob) and re-derive its npub. Bootstrap
  now branches purely on the state: encrypted decrypts (a missing ciphertext is
  a fail-fast inconsistency, never a silent fall-through to legacy), cleared
  actively empties the live nsec and npub, and legacy imports the plaintext
  once.
- Claim a generated admin password atomically. When no password exists, the
  generated one is written via a conditional UPDATE (WHERE admin_password_hash
  IS NULL) and only the worker that wins the update (rowcount 1) prints it. A
  racing worker on a shared database adopts the winner's hash and stays silent,
  so the operator never sees a second password that was never stored.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:21 +02:00
Jeroen UbbinkandClaude Opus 4.8 c2a2d76eae fix(vault): harden the auto-generated master key file
Three fixes to how a node provisions its own master key when the operator
sets no ROUTSTR_SECRET_KEY:

- Publish the key atomically. It is written to a same-directory temp file,
  fsynced, then os.link-ed into place and the directory fsynced. os.link
  publishes the complete file in one step, so a crash mid-write can no longer
  strand an empty key at the final path that a later boot would read as corrupt
  and then fail to decrypt every secret under. os.link also refuses to clobber,
  so a racing worker that generated first keeps ownership and the loser adopts
  its key.
- Tighten loose permissions on read. A key file that is group/other-readable is
  repaired to 0600 rather than trusted, keeping an upgrading node booting.
- Stop printing the key value. The one-time notice names the file to back up and
  shouts the backup imperative, but no longer echoes the key itself, which would
  leak it into captured stdout / aggregated container logs; the durable 0600 file
  is the recovery path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:21 +02:00
Jeroen UbbinkandClaude Opus 4.8 7106dfe330 fix(vault): provision a master key on upgrade instead of refusing to boot
A node with a legacy plaintext nsec but no ROUTSTR_SECRET_KEY refused to
boot: bootstrap_secrets raised and vault.encrypt required the env key.
That turned encryption at rest into a hard breaking change on auto-upgrade.

Encryption stays mandatory — the nsec is never persisted in plaintext —
but key custody becomes flexible. When no ROUTSTR_SECRET_KEY is set,
encrypt() generates a Fernet key, writes it owner-only (0600) to a key
file, and prints a one-time back-it-up notice, so an upgrading node keeps
running. The read path stays strict: decrypt()/get_fernet() never mint a
key (a fresh key could not match existing ciphertext) and fail fast with
the generation command when none is configured. A malformed env key still
fails fast rather than silently self-provisioning a different key.

The key file defaults beside the SQLite database (ROUTSTR_SECRET_KEY_FILE
overrides), so it rides whatever volume already persists the data instead
of a working-directory path a container recreate would drop.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:20 +02:00
Jeroen UbbinkandClaude Opus 4.8 1045f1061b fix(settings): derive npub from the vault nsec, not a stale env value
initialize() only filled npub when it was empty, so an existing node
with a stale NSEC still lingering in its env/blob kept that value's
derived npub even after the vault took ownership of a different nsec.
The node then held the vault's private key but announced the old env
key's public key — a split identity that anything reading settings.npub
would broadcast.

npub is a pure derivation of nsec and is never configured on its own, so
derive it from the live (vault) nsec and override rather than only fill.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:20 +02:00
Jeroen UbbinkandClaude Opus 4.8 0415806c5a fix(config): keep the vault the sole owner of node secrets
Two ways a stale legacy NSEC could override or resurrect an nsec the
vault already owns (issue #553):

- initialize() re-applied env/blob values onto live settings after
  bootstrap had decrypted the authoritative nsec, so a stale NSEC left
  in .env would clobber it on restart (e.g. after rotating the key in
  the admin UI). _apply_to_live_settings now never re-applies secret
  fields; bootstrap_secrets is their only writer.

- An empty encrypted_nsec could not distinguish "never migrated" from
  "intentionally cleared", so clearing the identity via the admin API
  and restarting re-imported the old NSEC from env/blob. Record vault
  ownership in a new secrets.nsec_managed column (set on legacy import
  and on every set_nsec write); bootstrap skips the legacy import once
  the vault owns the nsec, so a cleared identity stays cleared.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:20 +02:00
Jeroen UbbinkandClaude Opus 4.8 b8700dde40 harden(admin): cap scrypt work factor, keep generated password off disk
Address review hardening items on the secret-storage path:

- vault.verify_password caps N/r/p at the parameters this module emits, so a
  tampered or corrupt stored hash can't force an unbounded scrypt work factor
  (memory grows with N*r) and turn a login into an OOM/DoS.
- bootstrap prints the generated first-run admin password to stdout instead of
  the logger, so it reaches the operator once without being persisted into the
  on-disk log files.
- admin_login reads the password hash while the DB session is open rather than
  off a detached ORM instance after the context exits.
- drop a stray debug print of the request payload in upsert_provider_model.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:20 +02:00
Jeroen UbbinkandClaude Opus 4.8 4872c318d5 fix(settings): keep npub consistent with a store-only nsec on initialize
When the nsec lives only in the encrypted Secret store (env carries no NSEC) and
the settings blob holds no npub, bootstrap_secrets decrypted the nsec and derived
the npub into memory, but SettingsService.initialize then re-derived settings
from the npub-less blob and overwrote the live npub back to empty — leaving a
private key with no matching public key, so the node silently stopped announcing
a usable Nostr identity.

Derive npub from the live nsec during initialize when the merged settings carry
none, so the public key stays consistent with the identity and is persisted to
the blob.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:20 +02:00
Jeroen UbbinkandClaude Opus 4.8 56a67c0a86 fix(settings): fail fast when an nsec is set but ROUTSTR_SECRET_KEY is missing
Encryption of the Nostr identity at rest is mandatory. When a legacy nsec is
present (env or blob) but no ROUTSTR_SECRET_KEY is set, bootstrap previously
fell into vault.encrypt and surfaced its generic "key not set" error. Raise an
explicit, nsec-contextual error first so the boot failure is intentional and
actionable — it names the missing key and prints the generation command —
rather than relying on vault throwing incidentally. No secret is dropped: the
node refuses to start until the operator sets the key.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:20 +02:00
Jeroen UbbinkandClaude Opus 4.8 afcb3f7cda fix(settings): keep upstream_api_key in the settings blob
upstream_api_key was added to SECRET_FIELDS, so it was stripped from every
blob write — but unlike nsec, nothing migrates it into encrypted storage. A
node carrying it only in the DB blob would load it into memory once, rewrite
the blob without it, and lose it on the next restart, breaking upstream auth.

It is node-scoped config that really belongs on a provider, not a vault
secret, and it has no encrypted home yet. Remove it from SECRET_FIELDS so it
stays in the blob exactly as before; redaction on read and ignore-on-write in
the admin settings endpoint are unchanged. Encrypting it is follow-up work.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:20 +02:00
Jeroen UbbinkandClaude Opus 4.8 a024d5be5e feat(admin): manage nsec via API and redact secrets in responses
Add an admin endpoint to set, rotate and clear the nsec, authenticate against
the stored password hash, and redact secret values (nsec shown as [REDACTED])
in settings responses. Wire the admin UI to the new endpoint.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:51:20 +02:00
Jeroen UbbinkandClaude Opus 4.8 c40723c1e2 feat(settings): bootstrap secrets at startup and require ROUTSTR_SECRET_KEY for stored nsec
Persist and load admin password and nsec from the encrypted Secret store on
boot: generate a temporary admin password on first run (logged once), encrypt
a provided nsec, and fail fast if a stored nsec cannot be decrypted with the
current key. Stop clobbering live secret settings with empty env values.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:50:51 +02:00
Jeroen UbbinkandClaude Opus 4.8 6c5c3f0b5f feat(db): add encrypted Secret store and migration
Introduce a singleton Secret model holding the admin password hash and the
Fernet-encrypted nsec, with a hand-written migration for the secrets table.
Add suite-wide pytest config pinning a valid ROUTSTR_SECRET_KEY.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:50:51 +02:00
Jeroen UbbinkandClaude Opus 4.8 86adee9b1b feat(vault): add Fernet/scrypt secret primitives
Encrypt/decrypt secrets at rest with Fernet keyed by ROUTSTR_SECRET_KEY,
and hash/verify admin passwords with scrypt. Self-contained helpers with
no consumers yet.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 10:50:51 +02:00
9qeklajc e0c74e3a46 Merge branch 'main' into fix/streaming-billing-finalization
# Conflicts:
#	routstr/auth.py
#	routstr/proxy.py
#	routstr/upstream/base.py
#	tests/integration/test_balance_negative_on_cost_overrun.py
#	tests/integration/test_free_response_stale_reservation.py
2026-07-23 00:03:01 +02:00
9qeklajcandGitHub 18965b4ea4 Merge pull request #629 from jeroenubbink/fix/bill-served-candidate
fix: bill and forward failover requests as the provider that actually served
2026-07-22 23:23:07 +02:00
9qeklajc 97dc10a8ad harden impl. 2026-07-22 23:10:27 +02:00
9qeklajc 87850c97b9 Merge branch 'main' into fix/streaming-billing-finalization 2026-07-22 21:21:06 +02:00
9qeklajcandGitHub fcc87718ff Merge pull request #621 from Routstr/fix/propagate-cashu-storage-errors
fix: propagate Cashu storage errors
2026-07-22 21:18:10 +02:00
Jeroen UbbinkandClaude Fable 5 50437a1cc6 refactor: require explicit settlement identity at the billing seams
Make model_obj/provider_fee required (still nullable) on
adjust_payment_for_tokens, get_x_cashu_cost and the private pricing
helpers so a call site that fails to thread the served candidate is a
type error instead of a silent fallback to alias-map re-derivation.
calculate_cost keeps its defaults as the one documented fallback seam.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 15:13:40 +02:00
Jeroen UbbinkandClaude Fable 5 7f5a0cf1ae refactor: drop the dead model-instance alias map
get_model_instance now derives from the candidate map, leaving the
module-level alias map write-only; remove it so there is a single
authoritative alias source.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 15:12:21 +02:00
Jeroen UbbinkandClaude Fable 5 3f850c54f4 fix: re-reserve the serving candidate's max cost on failover
Admission and reservation were sized once to the best-ranked candidate's
max cost while settlement bills the candidate that actually serves, so a
failover to a pricier candidate could settle far beyond the admitted
envelope and consume balance reserved by other in-flight requests. Before
trying a fallback candidate, raise the reservation to its own envelope;
reject candidates the key cannot cover, exactly as admission would have
had they been ranked first.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 15:12:21 +02:00
Jeroen UbbinkandClaude Fable 5 df4d4c44e6 fix: fail over with each candidate provider's own model
The failover loop resolved a single Model for the request and reused it
for every provider: a fallback provider was asked to serve the routing
winner's model id and billed at the winner's pricing and fee. The alias
map now keeps (model, provider) candidate pairs, the proxy rebinds both
per attempt, and forwarding, max-cost echo, and settlement all use the
candidate actually being tried. On a failover serve the response's
model field now names the serving candidate's id.

The unified candidate lookup also applies the version-suffix strip
(-YYYYMMDD) that model resolution already had, so version-suffixed
requests no longer resolve a model yet 400 with "no provider found".

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 15:12:21 +02:00
Jeroen UbbinkandClaude Fable 5 0aebfc6dbe fix: bill the serving provider's fee on the USD-cost path
The USD-cost path (and the litellm pricing fallback) resolved the
provider fee via get_provider_for_model(model_id)[0] — the best-ranked
provider for the alias, not the one that served. Settlement callers in
the upstream handlers now pass their own provider_fee through
adjust_payment_for_tokens / get_x_cashu_cost into calculate_cost; the
string-derived fallback remains for callers without a serving provider.
Configured model pricing is unaffected (the fee is already baked into
cached pricing).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 15:09:41 +02:00
Jeroen UbbinkandClaude Fable 5 b76fa17f81 fix: thread the served model into x-cashu settlement pricing
X-Cashu handlers do not rewrite the upstream's echoed model string, so
get_x_cashu_cost previously priced whatever wire name the upstream
reported — the most collapse-prone alias lookup of all. The routed Model
is now threaded from forward_x_cashu_request through the chat and
Responses handler chains (and the litellm messages path) into
get_x_cashu_cost, so cost and refund are computed from the model that
actually served.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 15:09:41 +02:00
Jeroen UbbinkandClaude Fable 5 ed8ac914f9 fix: thread the served model into bearer settlement pricing
Settlement previously re-derived pricing from the response's model string
through the alias map, which resolves to the best-ranked candidate for
that alias — not necessarily the provider/model that actually served the
request. adjust_payment_for_tokens and calculate_cost now accept the
routed Model and bill its pricing directly; the string lookup remains as
a warning fallback for callers without routed identity (e.g. the generic
streaming finalizer).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 15:09:41 +02:00
thefux 2b4f70442a fix: recover stale Cashu reservations safely 2026-07-22 00:06:33 +00:00
9qeklajc 4defe4f227 fix: identify reservation releases 2026-07-18 14:59:57 +02:00
9qeklajc f8125a8a2d Merge branch 'fix/fee-payout-crash-guard' into fix/streaming-billing-finalization 2026-07-18 14:57:15 +02:00
9qeklajc 999a5634fa fix: snapshot reservation cleanup state 2026-07-18 14:54:06 +02:00
9qeklajc 2c218cce49 fix: make reservation cleanup atomic 2026-07-18 14:48:02 +02:00
9qeklajc fa0b366f9a fix: fail safely on streaming billing errors 2026-07-18 14:42:03 +02:00
9qeklajc a3a4d69ed3 fix: make storage retries idempotent 2026-07-18 14:33:40 +02:00
9qeklajc c9533c872a fix: retry critical Cashu storage writes 2026-07-18 14:28:18 +02:00
9qeklajc 90da3803c6 fix: preserve caller recovery on storage errors 2026-07-18 14:22:16 +02:00