New PRICES_PROVIDER=neroswap arm fetches every rate in one call from the
canonical oracle at prices.neroswap.com (Kraken majors; WOW from Nonlogs
plus volume-weighted CexSwap), so every Such Software product quotes the
same WOW number. GRIN, which the oracle doesn't publish, falls back to
the direct nonlogs leg converted via the oracle's BTC/USD. coingecko and
kraken arms unchanged and still selectable.
CI gates on cargo fmt --all -- --check and it was already failing on main before
this branch: rustfmt 1.9.0 reformats three call chains that an older rustfmt
left alone. Same housekeeping as 586d29e.
utoipa derives the /auth/extension operation description and the
rotation_signature / seed_fingerprint property docs from the doc comments, which
changed when the rotation proof became instance- and target-bound. CI has an
openapi-drift job that diffs a fresh gen_openapi against the committed spec, so
this keeps that gate green.
Deploying the previous version showed nip05_domain = api.smirk.cash, but handles
are name@smirk.cash: that is what v0.2 used, what the wallet derived by stripping
'api.' client-side, and what the kind-0 profiles already on relays carry. Since
the wallet now PREFERS this field, shipping it would have silently re-rendered
every handle as @api.smirk.cash and disagreed with the published profiles.
Caught by checking the deployed output rather than assuming the change was inert.
Default is now PUBLIC_API_URL's host with a leading 'api.' removed, preserving
the established behaviour, and NIP05_DOMAIN overrides it for operators whose
well-known lives elsewhere. Still explicit where it matters; the default just
stops being a regression.
public-free and paid-relay both set SERVER_PORT=8081, which is the ADMIN_BIND
default (config.rs). An operator following either example with the admin plane
enabled gets 'Address already in use' at startup and no obvious cause. Moves
ADMIN_BIND rather than SERVER_PORT so the nginx config in the example still
matches.
The sid revocation check added in e2589d4 rejected EVERY authenticated request
with 401. issue_session generated session_id = Uuid::new_v4(), minted the access
token with it as sid, then called create_session WITHOUT passing it, so Postgres
assigned the row a different primary key. is_session_live(sid) therefore never
matched and the liveness check failed closed on every call.
Both halves were individually correct, which is why unit tests did not catch it:
303 backend tests passed throughout. The e2e suite caught it, as a wallet that
authenticated successfully and then showed 0 for every asset.
NewSession now carries the id explicitly and create_session binds it, at all
three call sites (extension/website login and the refresh rotation, which shares
the helper).
Verified: fiat-balance e2e goes from all-zero to $108.21.
Falling back to public Electrum is a PRIVACY decision, not just an availability
one: the queries carry user addresses. It is easy to miss because the failover
is silent and correct, so the only symptom is that balances keep working. Our own
LTC Fulcrum was dead for 11 days with every lookup going to third parties, and
nothing surfaced it.
- startup: log how many third-party fallbacks are configured and how to fail
closed instead, so the posture is visible in the operator's own logs
- .env.example: state the tradeoff at the setting, with both choices spelled out
rather than a default presented as obviously correct
- OPERATOR_SETUP: same note where an operator configures chains
Also expands the shipped fallback lists (BTC 3 -> 8, LTC 4 -> 7), which is both
more resilience and a wider spread of which server sees any given query.
The wallet cannot derive the handle domain; guessing by stripping 'api.' only
works for a smirk.cash-shaped deployment. The host of PUBLIC_API_URL is the
answer, so state it.
The note said to check the LWS setting without saying how. Adds the one-liner and
records that the backend probes it at provision time and refuses loudly, so a
wrong setting is not a silent half-working state.
A grin kernel excess is also a 66-hex Pedersen point, so validate_hex(66) cannot distinguish it from an output commitment; a kernel excess never matches a rewind scan and yields a silent not_found. A send slate also carries the sender's change output. tx_ref MUST be the recipient's received (non-change) output commitment — document the footgun so the payer/frontend sets it correctly.
verify_access_token was a pure signature + expiry check, so an access token could
not be revoked. Sign-out and logout revoked the DB session row, and an erasure
request revoked all of them, but the bearer token kept working for the rest of its
24h life on every authenticated route. The refresh token has always carried a sid
for exactly this; the access token, which actually guards the API, did not.
Adds sid to AccessTokenClaims and checks it against the sessions table on each
authenticated request (one indexed primary-key lookup).
sid is Option so tokens minted before this deploy still verify rather than logging
every user out mid-session; they simply remain unrevocable until they expire,
which is the pre-existing behaviour.
Wire the family="grin" arm of POST /api/v1/verify, replacing the stub.
Grin has no address and no txid, so the request identifies a payment by its output COMMITMENT (tx_ref) and the recipient's rewind_hash (view_key). scan_rewind_hash proves recipient ownership AND the true received amount in one scan (only the recipient's rewind_hash recognizes the commitment), then gates on grin's 10-confirmation depth via get_height.
No get_kernel: MW aggregation/cut-through leaves no on-chain join binding a kernel excess to a specific output, so a kernel-only check can't soundly gate amount or recipient. Sender is unenforceable (MW reveals none -> sender:null) and dest_address is ignored (no addresses); a missing view_key returns not_found, never a false verify, mirroring the cryptonote arm.
Adds grin_for resolver + grin_amount_outcome helper + unit tests. 8/8 verify tests pass, clippy and rustfmt clean.
default_relays_are_wss still referenced DEFAULT_RELAYS, removed when the constant was renamed INTEROP_RELAY_HINTS, which broke the `cargo test`/--tests build. Repoint it (interop_relay_hints_are_wss); behaviour unchanged.
relay_hints appended damus/nos.lol unconditionally, so every self-hosted instance
published a NIP-05 document pointing its own users at third-party relays, and a
correspondent would deliver there instead of to the operator's relay. An operator
running a private deployment had no way to stop it.
Now opt-in: NIP05_INTEROP_HINTS (default off) for the built-in interop pair, plus
NIP05_EXTRA_RELAY_HINTS for the operator's own list.
GET /premium/status gains write_allowlisted + can_post_general.
The wallet was re-deriving posting rights from write_policy + premium, which
cannot see RELAY_WRITE_ALLOWLIST_NPUBS. An allowlisted operator was shown
"posting needs a premium subscription" with the composer hidden, while the
relay's own admission check would have accepted the event. Compute the answer
server-side from the same RelayProvider the admission service consults so the
two cannot drift.
Add POST /api/v1/verify, the server side of moon.vote's delegated
settlement check: confirm a specific tx_ref paid at least the expected
base-unit amount to dest_address, confirmed to this backend's per-asset
depth.
- UTXO (btc/ltc): mirror ElectrumClient semantics; consult get_history
first to distinguish not_found from a node error, then attribute the
exact amount via VerboseTransaction::total_received_at.
- CryptoNote (xmr/wow): require a private view_key, scan via
get_address_txs, match tx_ref, gate on mempool/height and the daemon
confirmation depth (XMR 10, WOW 4).
- grin: deferred (reports not_found with a warn).
Business outcomes (incl. failures) are always 200 with a fixed reason
vocabulary; only infrastructure failures return non-2xx AppError so
moon.vote retries. Unauthenticated by design (nginx allow-list gates it);
no utoipa/openapi wiring (server-to-server, not in the wallet client).
Backend support for two address-privacy features. Both are behind env flags
that default to off, so an unconfigured instance behaves exactly as before:
the routes are not mounted and no provisioning is attempted.
FEATURE_XMR_SUBADDR_PROVISIONING
Adds POST /wallet/lws/provision_subaddrs and provisions account-0 subaddress
indices on the LWS at register/import.
Three money-safety properties worth calling out:
* The provisioned ceiling is read from the LWS response, never echoed back
from the request. It is the contiguous run starting at minor 0, not
max(hi): given ranges [[0,99],[200,299]], reporting 299 would let a wallet
hand out indices 100..199 that the LWS never scans, so funds sent there
would be invisible. No usable run is a hard error, not a guess.
* import_account now always runs the backward rescan even when provisioning
fails. Previously a provisioning error aborted first, leaving the account
registered at the chain tip while every retry returned 200 OK, so a
restoring wallet would show a zero balance permanently.
* A capacity probe reads max_subaddresses from the LWS and refuses up front
with a message naming the required --max-subaddresses value, rather than
failing per-account later. The option defaults to 0 upstream.
Spent outputs now carry their subaddress index. monero-lws emits this as
`sender` (the index the spent output was received at), not `recipient`;
without it a client recomputes a primary key image for a subaddress spend,
treats the mismatch as a decoy, and never subtracts the amount.
FEATURE_UTXO_MULTI_ADDRESS
Adds balance_multi / utxos_multi / history_multi for HD gap-limit wallets.
Capped at 32 addresses, summed with checked_add, per-UTXO address tag
preserved so the client never has to re-guess which key owns an output.
Bounded concurrency with a per-batch deadline returning 504, so a slow
Electrum server cannot stack n * IO_TIMEOUT.
Both flags are advertised in /capabilities so a client can negotiate instead
of calling routes that 404.
The published privacy policy states that IP addresses are retained only as a
salted one-way hash for rate limiting. That was true of the login-event path
but not of sessions.ip_address or audit_logs.ip_address, both of which stored
a raw client IP tied to user_id on every login.
Drop both columns and all writer/model code, so the schema enforces the policy
rather than relying on convention. The hashed rate-limit path (login_events,
restore_attempts) is unchanged and remains the only IP retention.
Also drops the `wallets` table, which was created in the initial schema and
never read or written: a latent user_id -> address / view_key store.
The operator forensic trail (admin_audit_logs, admin_sessions) deliberately
keeps its raw IP. Privileged-action forensics is a different threat model and
is not covered by the user-facing claim.
XMR/WOW atomic amounts (piconero/wownoshi) can exceed 2^53, which a
JavaScript number cannot hold exactly, so a large balance or output was
silently rounded when the wallet JSON.parsed it. Serialize every atomic
amount (balance total_received/locked/pending, spent + unspent output
amounts, history totals) as a decimal string; heights, indices, counts,
and fee params stay numbers. utoipa value_type=String keeps the OpenAPI
honest. Tests assert the string wire contract for a 2^53+1 value.
- tools/secret-scan.sh now also flags nsec1 Nostr secret keys and
*_PEPPER/*_SALT/*INTEGRITY_SECRET hex assignments, the secret classes
this backend actually handles (previously only PEM/seed shapes).
- .gitignore: *.hex + admin-key* so an operator running inside the
checkout cannot commit the raw admin key (create-admin-wallet --out).
- PRIVACY.md pointing to the canonical smirk.cash/privacy, framed for
self-hosting operators as independent data controllers.
- New docs/operations/CONSOLE.md: reaching /admin, NIP-98 login, the
defaults->env->DB precedence model, per-section runtime-safe vs
restart-required table, expected_versions concurrency, restart_apply_mode
(with the systemd Restart=always requirement for auto), clearing a DB
override. Linked from README + OPERATOR_SETUP.
- All six example recipes gained an explicit chain-enablement block
(FEATURE_XMR/WOW on, BTC/LTC/GRIN off) so they no longer hard-fail
Config::validate in production (default-on chains with empty sources).
- Documented all 16 previously-undocumented env vars in .env.example
(RESTART_APPLY_MODE, TOR_ADMIN_ONION, DEPLOYMENT_MODE, TIP_SHARE_BASE_URL,
...); RELAY.md gained the premium-post policy + RELAY_WRITE_ALLOWLIST_NPUBS;
ADMIN_PUBKEYS noted as reserved/inert.
- Keys tab crashed on render: api.keys() expected an array but the
backend returns {keys:[...]}; unwrap it (KeysTab maps over the array).
- Config save now sends only CHANGED fields, not the whole section, so
the backend stops spuriously flagging restarts and pinning env-sourced
values into the DB overlay.
- Config edit state survives a reload (saving one section no longer
discards unsaved edits in others); numeric inputs ignore empty/NaN
instead of silently coercing to 0.
- Mint and Revoke now surface errors instead of swallowing them.
Rebuilt admin-ui/dist.
A runtime-safe config PUT rebuilt the effective config from config_base +
the FULL persisted overlay and stored it, which live-applied any
restart-required section persisted by an earlier PUT (features/relay/
premium) while the boot-built clients still ran the old value — and
cleared restart_pending in the process. The exact desync RuntimeClass
exists to prevent.
Now the hot-swap applies ONLY the (all-runtime-safe) patch onto the
currently-running config, and restart_pending is computed honestly via a
shared helper (GET and PUT agree). Also reclassify registration.
require_payment as restart-required: it gates the boot-built payment
client (None unless require_payment||premium at boot), so hot-enabling it
would 500 every registration until restart. Regression tests for both.
The repo pins channel=stable (no rustfmt version), so CI now pulls
rustfmt 1.9.0, which reformats code last touched by an older rustfmt.
main itself failed `cargo fmt --check` under the current toolchain;
this is a formatting-only sweep across 24 files to make the fmt gate
green. No behavior change; tests + clippy -D warnings still pass.
Extends the operator settings overlay with five sections, all non-secret
by construction (api_key, ALTCHA hmac_key, peppers, and processor wiring
stay in env):
- registration: require_invite, gate_mode, require_payment + payment
amount/currency/confirmations/expires (runtime-safe: read per-request)
- pow: enabled, required, cost (runtime-safe)
- features: prices + provider/interval/currency, tips, nostr_identity,
grin_relay, and per-chain enablement (restart-required: boot workers)
- relay: enabled, mode, advertised_url, write_policy, inbound_pow_bits,
max_event_bytes, retention (restart-required; bind + allowlist excluded)
- premium: enabled, currency (restart-required; priced plans stay in env)
Every PUT re-runs Config::validate, so enabling a gate with incomplete
wiring (e.g. pow without a key, pay-to-register without a processor) is
rejected at save, never booted disarmed. Tests: identity round-trip
(proves read-field == write-field for every entry), a hard assert that
no secret can appear in the editable overlay, gate_mode typo rejection,
and pow-without-key fail-closed.
- admin.rs: make the config/invite JSON response structs pub (they are
returned from pub handlers; matches the already-pub AdminKeyView etc.)
- invite_codes/operator_settings: drop redundant reborrow (&mut *tx -> &mut tx)
- electrum: minimize a boolean (De Morgan, behavior-identical)
- relay: move the test module to end of file (items_after_test_module)
Pure lint hygiene surfaced by the current stable toolchain; no behavior
change. cargo clippy --all-targets -- -D warnings is now clean.
New console-drift job rebuilds admin-ui from the lockfile (npm ci) and
fails if the committed admin-ui/dist drifts. rust-embed bakes dist into
the binary, so a stale dist ships an old console; this mirrors the
openapi-drift gate. Pinned to Node 22 (the version that built the
committed bundle) so the byte-diff is deterministic.
The SPA issued GET /admin/auth/challenge but the route is POST (nonce
issuance is a write). Left as-is the login flow 405'd at step one. Fixed
the client verb and rebuilt dist.
Route-level test (tower oneshot, no DB) confirms GET /admin returns the
console HTML with text/html, and GET /admin/assets/<hash>.js returns the
built bundle with a JS content-type. Pairs with the embed test so both
'not built' and 'not wired' regressions fail CI.
Preact + Vite standalone admin-ui bundled into the server binary via
rust-embed. Login is NIP-07 (Smirk wallet signs the NIP-98 admin
challenge); tabs cover instance status, admin keys, invite codes, and
the effective-config editor (live vs restart-required per field).
admin-ui/dist is committed because rust-embed reads it at compile time;
node_modules is gitignored (npm ci reproduces it). A lib test asserts
index.html and the /admin/ asset base are embedded so an unbuilt
console fails the build instead of an operator.
The console is served on the admin plane only (loopback bind), behind
the existing NIP-98 admin_guard + MAC allowlist.
- console section: restart_apply_mode (manual | auto), an operator setting (runtime-safe,
DB-overridable via /admin/config), env RESTART_APPLY_MODE default manual.
- Graceful shutdown: main serve now awaits SIGTERM/Ctrl-C OR an in-app shutdown signal
(AppState.shutdown Notify) via with_graceful_shutdown, draining in-flight requests.
- PUT /admin/config in `auto` mode self-restarts shortly after responding to apply a
restart-required change (systemd Restart=always brings it back with the new config);
`manual` just flags restart_pending. The console warns before an auto save.
Stage 3 complete: operator config is readable + editable through the real validated,
audited, precedence-based layer; runtime-safe edits apply live, infra edits restart.
cargo all-targets clean, lib tests pass.
The operator-editable config surface, on the effective-config layer:
- GET /admin/config: per-field effective value + the DB overlay (source=db) + per-section
version + runtime_class map + restart_pending (persisted-but-unapplied change).
- PUT /admin/config: a sparse patch is field-merged onto the persisted overlay, validated
with the SAME Config::validate boot uses (400 on invalid, nothing persists), then each
changed section is persisted audited + version-guarded (409 on a stale expected_version).
Runtime-safe edits HOT-SWAP the effective config atomically (arc-swap, live next request);
any restart-required field is persisted + flagged restart_pending (operator restarts to
apply). Records the editing admin key as updated_by.
- config_overlay: editable_overlay() (effective values as an overlay) + EDITABLE_FIELDS.
- operator_settings: optimistic-concurrency (expected_version) + settings_versions().
Secrets remain unreachable (overlays carry no secret fields). cargo all-targets clean,
lib 256/0. Next (3b): restart_apply_mode (manual|auto self-restart) + graceful shutdown.
Wire the settings overlay into the live config path:
- AppState.config: Config -> Arc<ArcSwap<Config>> (hot-swappable effective config) +
config_base: Arc<Config> (immutable env-only). New AppState::cfg() accessor; every
config read goes through it (state.cfg().field), so a runtime-safe operator edit is
seen on the next request. One Config type, no parallel path.
- Boot (main.rs): load_settings_overlay -> Config::apply_overlay(validate) -> build
every client/worker/router from the EFFECTIVE config. A persisted overlay that no
longer validates is ignored (boot env-only + loud log), never bricks. Env-only when
ADMIN_KEY_INTEGRITY_SECRET is unset.
- Migrated ~59 state.config.X reads to state.cfg().X across api/*; bound guards where a
reference outlives the statement; integrity_secret returns owned String.
- Test harness builds AppState with ArcSwap + config_base (arc-swap dev-dep).
Behavior-preserving: with no operator_settings rows, effective == env config.
cargo check --all-targets clean; lib tests 256/0.
Stage 1 of the operator-editable config layer (additive; no behavior change yet):
- migration operator_settings: one MAC(ADMIN_KEY_INTEGRITY_SECRET) JSONB row per
section, FK to admin_keys, audited on write. Missing section = env-only.
- OperatorSettingRow model.
- SettingsOverlay + section overlays (landing/retention/restore) with secrets
EXCLUDED BY CONSTRUCTION; Config::apply_overlay merges onto the env-derived Config
then re-runs the SAME Config::validate boot uses (a bad edit yields the identical
error, nothing persists, the instance cannot be bricked).
- runtime_class() single source of truth (RuntimeSafe hot-swap vs RestartRequired).
- operator_settings storage: canonical-JSON MAC (stable across JSONB key reorder),
load_settings_overlay (fail-closed per section -> env fallback), put_setting_audited
(upsert + admin_audit append in one tx).
- sqlx json feature.
cargo check clean; 4 new unit tests pass. Next stages: ArcSwap AppState + ~59
read-site migration, GET/PUT /admin/config (+ restart_apply_mode), remaining sections.
The BTC/LTC balance path dials a configured primary (our Fulcrum) then randomized
public fallbacks. When the primary was unreachable, every request paid the full
10s CONNECT_TIMEOUT before falling back, so a down/overwhelmed primary meant a
~10s user-facing stall on every balance read.
- CONNECT_TIMEOUT 10s -> 4s (primary is a warm mesh node; fallbacks answer in ~1s)
- Add a per-primary circuit breaker: after 2 consecutive primary failures, skip
the primary for a 30s cooldown and go straight to fallbacks, so a down primary
costs a stall at most once per cooldown instead of on every request. Success
clears it immediately. Only skips the primary when a fallback exists.
Protects the small such-nodes-one Fulcrum box: if it is overwhelmed or drops, the
backend fails over to public electrum in ~1s instead of stalling users. 22/22
electrum unit tests pass (incl. a new breaker state-machine test).
- config: grin is a supported tip chain (voucher model verified against the node),
so FEATURE_TIPS with only grin enabled no longer fails closed at boot.
- social_tips: revert_sweep_on_reorg now preserves sweep_txid instead of nulling
it. Address-scan chains (btc/ltc/xmr/wow) overwrite it via confirm_sweep_onchain
on the next cycle, so preserving the orphaned value is harmless; grin needs the
kernel excess to re-date a re-mined sweep via get_kernel, so nulling it stranded
reorged grin tips in 'claiming'. Test updated to assert preservation.
- lws import_account: retry the birthday backfill rescan (3 attempts, backoff) so
a transient failure no longer strands a new account at the chain tip. The
already-registered Some(_) no-op is unchanged, so this cannot reintroduce the
balance-reset bug.
Public-only instances have no targeted-recipient inbox (public tips are claimed
via share URL, never delivered to a user), so the client's inbox poll of
/received + /claimable 404'd. Serve them 200-empty instead so the poll succeeds
quietly. Matches the client contract ({tips:[]}).
Grin as a new asset arm in the tips machinery (no grin-lws change, no custodial
grin_transactions/grin_outputs port):
- GrinClient::get_outputs([commit]) (funding: present+height=confirmed) +
get_kernel(excess) (sweep spend-height); reached via state.chains.grin.
- create-gating (supported_tip_asset grin, validate 66-hex commitment,
confirmations_for_asset grin=10), grin_commitment column (migration).
- confirmation worker grin arm: get_outputs present -> confs; amount AUTO-VERIFY
with warn (voucher hides amount; not a theft vector; matches legacy).
- sweep reconciler grin arm: get_outputs-absent + get_kernel height at depth 10 ->
settle; absence-without-kernel -> no settle (recoverable, never missettle);
reorg revert only on commitment reappearing; probe error never settles/reverts.
- 5 grin tests + pure-helper unit tests; 251 lib + 24 tips green.
Amount-verification note: the voucher's bulletproof rewind nonce is random +
untransmitted, so it can't be rewound today; a clean non-custodial fast-follow is
to have the client send the per-voucher rewind nonce and verify via rangeproof
rewind (nonce reveals amount only, not spend authority).
Escrow settlement, audited guards ported verbatim:
- mark_tip_claiming: status IN('pending','claiming') AND confs>=required AND
funding_amount_verified AND sweep_confirmed_at IS NULL (double-claim guard).
- confirm_tip_sweep: RECORD-not-settle, first-recorder-wins (COALESCE +
sweep_txid IS NULL OR =$3) — RBF-steal safe; reconciler owns claiming->claimed.
- confirm_sweep_onchain: SOLE writer of 'claimed', one-way status='claiming' AND
sweep_confirmed_at IS NULL lock; settles only after on-chain sweep confirms to
per-asset depth (btc/ltc 1, wow 4, xmr 10).
- clawback: 5-status set incl 'cancelled', blocked once sweep_confirmed_at set.
- revert_sweep_on_reorg: only from 'claimed', re-opens to 'claiming' + clears txid.
- sweep_reconciler: address-history-driven (not recorded txid), pick_winner
(earliest height, lexi-smallest tie), pg advisory locks on a pinned conn for
single-instance safety; reorg pass reverts only on affirmative vanish, never on
probe error. DMs stubbed, exactly-once stamps kept.
- POST claim/confirm-sweep/clawback endpoints + openapi.
- 16 integration + 12 reconciler unit tests; build clean; SocialTipRow dead_code
allow removed (all fields now read).
- attach_funding_to_tip: atomic guarded UPDATE (COALESCE + CASE), idempotent on
same txid, 400 on a different txid; non-drafts land pending_confirmation so the
verifier (not the caller) owns the ->pending transition.
- worker (src/tips/confirmation.rs): XMR/WOW confirmation counting via LWS;
amount verification for BTC/LTC (Electrum full history, confirmed-only) +
XMR/WOW (classify_funding_amount, separate-then-subtract net). Verified->pending,
Short->funding_mismatch; Unfunded/Drained/LwsError never mutate status (outage-
safe). Spawned behind FEATURE_TIPS on a 60s loop w/ catch_unwind guard.
- POST /tips/social/:id/attach-funding endpoint + openapi.
- 5 DB tests + 6 classify unit tests; build clean.
Re-registering an XMR/WOW account carrying the fixed wallet birthday triggered a
backwards rescan (`if start_height < current { rescan }`), resetting the scan
cursor to the birthday. Because the wallet re-registers before every balance
read, an old-birthday account was reset on each poll: it read a 0 balance, slowly
re-backfilled, then got reset again and never caught up (users saw 0 XMR/WOW
despite real funds).
Only a NEWLY added account needs the backwards rescan (monero-lws add_account
starts at the chain tip). An account that already exists has already been
imported from its birthday, so re-registration is now a no-op here. Genuine
re-restore to an earlier birthday uses the explicit admin rescan path.
Add a GrinLwsClient (a faithful mirror of the XMR LwsClient) + GrinLwsConfig
(enabled when GRIN_LWS_URL is set). /wallet/grin/scan now defaults to grin-lws
when configured and returns derivation paths (key_id/n_child) + spendability,
letting the wallet skip its client-side output-identify search.
Money-safety: the restore-depth/PoW gate runs once and is terminal (never
masked by fallback); grin-lws is trusted only when provably synced
(scanned_height + margin >= tip), otherwise the scan falls back to the
authoritative grin-wallet scan_rewind_hash; a grin-lws transport error also
falls back; grin-wallet errors propagate as 503. No path ever synthesizes an
empty/zero balance.
Off unless GRIN_LWS_URL is configured (prod grin behavior unchanged until
pointed at a grin-lws instance). Capabilities advertise `grin_lws`.
openapi.json regenerated.
Enhance the grin address→user lookup to return the owner's linked npub (not just a
bool), so a bare grin slatepack address can resolve to its owner's npub and route
over the federated Nostr gift-wrap rail instead of only manual handoff. Doc-comment
the backend slatepack relay as a same-instance-only convenience — the federated
default transport is Nostr gift-wrap; the relay needs a recipient user_id and both
parties on this instance, so it is not the primary path in a public-backend world.
The electrum client did strict webpki TLS verification (CA chain + hostname). But
public electrum servers are self-signed by ecosystem convention — e.g. emzy.de
presents a cert webpki rejects with `UnsupportedCertVersion`. So the ssl:// fallback
layer was non-functional: whenever the trusted primary Fulcrum hiccuped (the
recurring nebula-firewall issue), every fallback failed the TLS handshake and
BTC/LTC returned 503 NODE_UNAVAILABLE (observed live on api.smirk.cash).
TLS here is transport encryption, not the trust boundary — the client already
treats every server byte as hostile (size bounds, id correlation, checked amount
conversion, address validation), so CA-authenticating an untrusted PUBLIC fallback
buys nothing while breaking it. Default to accepting any server cert; gate strict
webpki behind ELECTRUM_STRICT_TLS=1 for operators who run a CA-cert'd Fulcrum.
Verified (network-gated test): the lenient connector completes get_tip_height
against blockstream (CA-signed) AND emzy.de (self-signed) where strict fails.
cargo check + electrum/config unit tests green.
The integration harness dropped response headers (returned only status + JSON body),
which is exactly why CORS/security-header behavior couldn't be tested. Add:
- request_full(method, uri, extra_headers, body) -> (status, HeaderMap, body):
sends arbitrary request headers (e.g. an Origin) and returns response headers.
- try_app_with(|cfg| ...): tweak the validated Config before building the router
(e.g. restrict cors_allowed_origins). try_app now delegates to it.
New tests/cors.rs proves the well-known fix end-to-end: with the API CORS restricted
to one origin, /.well-known/nostr.json still serves ACAO: * to a foreign origin
(federation works) while /api/v1/* does NOT — the two policies are genuinely
distinct. Verified against Postgres (passes); existing auth_flow/capabilities unaffected.
The NIP-05 directory (/.well-known/nostr.json) is public, read-only, unauth'd data
that MUST be cross-origin fetchable — any Nostr client on any domain resolves
`user@this-instance` by fetching it. It was covered by the single global CORS layer,
so it only got `Access-Control-Allow-Origin: *` when CORS_ALLOWED_ORIGINS was empty
(the default). An operator who restricts CORS to their own frontend would silently
break NIP-05 resolution for every other domain/wallet — federation dies for that
instance with no error.
Split CORS into two route groups: the public surface (well-known + health + landing)
always serves `*`; the /api/v1 surface keeps the operator's configurable policy. The
API's CORS behavior is unchanged (it still gets the same `cors` layer); only the
public directory is now unconditionally cross-origin. cargo check clean.
RELAY_WRITE_ALLOWLIST_NPUBS (npub1… or hex, comma-separated): listed authors may
publish ANY kind regardless of write policy or premium status. The use case is a
feed-owner / announcements account that seeds a premium-post feed without holding
a subscription — the admission engine previously had no owner/allowlist bypass
(FEED_OWNER_NPUB is read-side only).
- policy.rs: decide() gains author_allowlisted, checked first (permit-any).
- mod.rs: RelayProvider::is_write_allowlisted; entries decoded npub→hex once at
boot (bech32), malformed entries logged + skipped. npub-decode KAT.
- nauthz.rs: resolves the flag (in-memory set, no DB) and short-circuits the
registration/premium/recipient lookups when exempt.
- .env.example: document the var + the premium-post policy.
Relay tests 21/21.
CoinGecko (the only v3 provider) 403s requests with no User-Agent — reqwest
sends none — so the feed never populated. Port the working v0.2.x approach:
- Add a browser User-Agent to the price HTTP client.
- Add a "kraken" provider: Kraken for the majors (BTC/LTC/XMR, USD, one
multi-pair call) + nonlogs.io for WOW/GRIN (Kraken doesn't list them; priced
via each coin's -BTC ×BTC/USD and -USDT quotes, averaged).
- Config validation accepts PRICES_PROVIDER=kraken.
Deployed to api.smirk.cash with PRICES_PROVIDER=kraken.
The prior fixes closed the common cases with pre-checks; this closes the
residual races by consuming the single-use gate token(s) AND creating the
user AND persisting keys in ONE transaction, so a failure never burns a
token without an account.
- New Database::create_user_consuming_gates: claims the invite + consumes
the payment invoice + inserts the user + upserts keys inside a tx;
rolls the whole thing back on a username collision (mapped to 409) or a
raced/already-spent token.
- New plan_gate_consume: resolves which tokens to spend WITHOUT consuming
(the payment settled-check stays non-consuming), so `all`-mode verifies
the payment is settled before anything is spent, then both tokens are
consumed atomically at creation.
- extension_register + nostr_register route NEW users through the atomic
path (returning users keep the ordinary backfill path); the npub F2
fail-closed check runs before the tx. Removed the now-dead
enforce_method_gates / enforce_invite / enforce_payment.
- tests/registration_atomicity.rs proves the rollback: a username
collision keeps the invite; an already-spent payment keeps the invite.
Validated against Postgres: full suite 286 passed / 0 failed.
Adversarial review of the auth/registration surface (findings tracked
privately). Backend half:
- F2: npub-native register no longer binds an npub onto an existing
wallet row on a seed_fingerprint match alone (unauthenticated account
takeover). get_or_create_user_by_nostr_pubkey fails closed (409);
linking an npub goes through the authenticated /auth/nostr/link flow.
Integration test rewritten to assert the refuse-and-409 contract.
- F3: `all`-mode gate verifies payment is settled (non-consuming) BEFORE
consuming the single-use invite, so a still-confirming payment can't
permanently burn the invite. verify_payment_settled split out.
- F4: username availability is pre-checked before any gate token is
consumed; collisions return 409, not 500 — a taken username no longer
burns a paid invoice / invite.
- F6: nostr_register now persists the submitted chain keys, so
receive-by-username and restore self-verification work for npub wallets.
- F10: the pay-to-register not-yet-settled response carries a stable
PAYMENT_PENDING code so polling clients don't parse a free-text string.
Validated against Postgres: full suite 283 passed / 0 failed.
The wallet gates its bootstrap on this: when true it registers via NIP-98
(no BTC signature); a legacy backend that omits the flag gets the BTC path.
Shares the NIP-98 infra requirement (PUBLIC_API_URL) with nostr_identity.
Make npub the identity anchor: a wallet can register from its seed-derived Nostr
key alone, no BTC signature. Breaks the link chicken-and-egg (nostr_login is
create-never; nostr_link needs a prior BTC-authed JWT). Additive - /auth/extension
(BTC) and the link flow keep working for legacy backends during the transition.
- get_or_create_user_by_nostr_pubkey (db twin of the BTC path): keys/inserts on
nostr_pubkey (raw, never peppered), pubkey_hash NULL. THE load-bearing dedup:
looks up by seed_fingerprint and MERGES the npub onto an existing (BTC-anchored
or link-less) row rather than splitting one wallet into two identities; a
different npub already on that row fails closed (409). backfill_optionals shared
helper.
- POST /auth/nostr/register + GET /auth/nostr/register-challenge: verify a NIP-98
signed-action over a subject-less single-use nonce (replay-safe), then re-run
the abuse gates keyed on the npub (a create path must not bypass PoW/invite/
payment); pay-to-register invoices still bind to the BTC key carried in keys[].
Empty-body descriptor contract (mirrors /auth/nostr/link); binding the key list
into the proof is a documented hardening follow-up.
- Housekeeping: get_user_count counts npub-only users; record_login_event labels
the nostr path.
3 integration KATs (create-by-npub + idempotent, replay rejected, seed_fingerprint
MERGE dedup) pass against a real DB; 211 lib tests pass; openapi regenerated.
The invite + payment gates were strictly conjunctive: a new wallet had to satisfy
EVERY enabled gate. Add a REGISTRATION_GATE_MODE knob so an operator can offer the
enabled gates as ALTERNATIVES instead (e.g. "an invite code OR pay to register").
PoW stays orthogonal and always applies on top, regardless of mode.
- config: GateMode { All (default) | Any } on RegistrationConfig, from
REGISTRATION_GATE_MODE (default "all", back-compatible).
- capabilities: advertise registration_mode ("all"|"any") so the wallet can route
onboarding (multiple gates + "any" => "pick a method"; "all" => satisfy each).
- enforcement: enforce_method_gates composes invite+payment per mode. Extracted a
pure plan_gates() decision so the fund-critical dispatch is unit-tested. In
"any" with both gates on, the client presents exactly ONE credential and only
that gate runs (and only it consumes its single-use token); presenting BOTH is
rejected so a one-of choice can never burn two tokens (an invite AND a paid
invoice). Single-gate configs behave identically in both modes.
6 KATs on plan_gates (open / conjunction / single-gate / dispatch / reject-both /
require-one). openapi.json regenerated. 211 lib tests pass.
A read-only web feed (feed.<domain>) is a backend-operator knob: FEED_ENABLED
plus curation switches (show owner / show premium members / a featured npub
allowlist / extra relays) surface in /capabilities.feed so the feed page adapts
per instance. Reads from the relay, so validate() fail-closes FEED_ENABLED
without RELAY_ENABLED. Off by default; all public display config, no secrets.
A payment processor reached over a loopback hop (an SSH tunnel or a local
reverse proxy) is safe to call over plaintext in production — the request never
leaves the host. Relax the https requirement for 127.0.0.0/8, ::1, and
localhost in both the pay-to-register and premium payment validation paths.
Add ready-to-run .env + README recipes (personal, public-free, friends,
paid-access, paid-relay, community) and the premium-relay design overview,
with audit fixes to the config template and spec:
- Drop the inert INSTANCE_ID knob (config never read it) and document the real
per-node id, which is derived from ADMIN_PUBLIC_URL.
- Warn that a placeholder PUBLIC_API_URL is rejected at boot in production
(Nostr identity is on by default); soften the recipe "boots today" status.
- Remove dead template vars: BTC/LTC Core-RPC settings and the non-existent
PUBLIC_EXPOSE_FEATURES (replaced with the real per-field landing switches).
- Mark ALTCHA_HMAC_KEY conditional in PoW-off recipes; blank placeholder
payment creds so a recipe doesn't ship a key that fails validation.
- Fix premium-relay spec drift: the migration creates no premium_until index,
disabled endpoints return 400/200 (not 404), and neutralize operator voice.
- Reject boot when POW_REQUIRED (or the per-pubkey PoW list) is set while
FEATURE_POW is off: the gate would silently never apply and /capabilities
would report pow_required:false — a signup endpoint the operator believes
is protected but isn't.
- Validate the premium PAYMENT_API_KEY through the same require_secret path
the pay-to-register flow uses, so a placeholder key cannot reach production.
- Advertise the premium-post write policy in MessagingCapability and
regenerate openapi.json to match.
- Give the premium integration fixtures unique per-run ids so the suite is
re-runnable against a persistent local test database.
examples/: an operator "cookbook" turning the backend's composable knobs
(registration gates, relay write policy, restore policy, feature flags) into
ready-to-run recipes per persona — personal, public-free (what the reference
instance runs), friends, paid-access, community, and paid-relay (the flagship:
free wallet + paid premium Nostr posting). Plus LEGAL_AND_OPS.md, a
not-legal-advice considerations checklist that points operators at their own
counsel and at the project's own published docs as a worked example. Recipes use
placeholders only.
docs/design/premium-relay.md: the premium-relay feature spec (reconciled to the
shipped design — dedicated premium_invoices table, transactional activate).
A paid premium tier gating GENERAL Nostr posting to the operator's relay, while
wallet-functional events (encrypted DMs, tips, swap coordination) stay free for
registered users. Registration itself stays free (PoW-gated). Off by default.
- Admission: a new `premium-post` write policy gates on kind x membership —
premium author -> any kind; registered + WALLET_KINDS (1059 gift-wrap, 10050
DM-relay-list) -> free; registered + general -> premium required; external ->
gift-wrap DM inbox only. nauthz resolves is_premium_npub (only under premium-post),
fail-closed.
- Payment: reuses the PaymentProvider seam (PULL model, non-custodial — only reads
invoice status). POST /premium/invoice {plan} mints a tier invoice bound to the
JWT user_id; POST /premium/activate verifies Settled + consumes single-use AND
extends premium_until in ONE transaction (a mid-flight failure keeps the paid
invoice redeemable); GET /premium/status reads it. Per-user pending-invoice cap.
- Tiered plans (PREMIUM_PLANS id:days:amount) = a built-in discount feature;
advertised via /capabilities (premium_relay + premium{currency,plans,relay_url}).
- Config fail-closes: PREMIUM_ENABLED needs relay on + premium-post + processor
creds + >=1 positive-decimal plan + unique ids + days<=3660, and the 0-conf /
expiry processor floors apply on the premium path too (its common case is
require_payment=false).
- Tests: 15 policy unit (incl. 5 premium-post) + config fail-closed matrix + plan
parser + L1 integration (activate single-use/stacking/cross-user, is_premium by
expiry, feature gate). OpenAPI + migration updated.
Adversarially reviewed (correctness / security-payment / operational-config); the
0-conf-on-premium-path double-spend footgun, non-transactional activate, and
unbounded plan days were caught and fixed before commit.
`smirk-admin migrate-legacy --source-url <pg> [--commit] [--limit N]` copies
user identity from a legacy v0.2.x backend database into this v0.3 DB, so users
keep their handle (and NIP-05 name@domain) when they move to a v0.3 client.
- Identity-only, joined on the derivation-independent seed_fingerprint; also
carries pubkey_hash (v3 wallets reclaim their row with no rotation step),
username, nostr_pubkey, wallet_birthday and chain restore heights. Socials/
tips/keys/wallets are intentionally not carried (no v0.3 home, or re-registered
by the client on first unlock).
- pubkey_hash + seed_fingerprint are peppered at rest, so the importer builds its
target with the real SEED_FINGERPRINT_PEPPER (run with the v0.3 .env).
- Idempotent (skips users already present by either peppered identity column),
dry-run unless --commit, best-effort per row: a transient error or a concurrent
native onboarding is reconciled, never aborting the pass. Reserved/taken/
malformed usernames and already-linked npubs are dropped; the user still lands.
- Exports validate_username so the importer applies the identical format +
reserved-name rules the HTTP handler does.
- docs/operations/LEGACY_MIGRATION.md + scripts/test-legacy-migration.sh, a
self-contained E2E that seeds alice/bob/carol plus edge cases and asserts
import, peppering, collision handling, and idempotency.
Reviewed adversarially (correctness / security / operational) before commit.
Adversarial review of the relay admission surface:
- FAIL-SAFE on admission death: nostr-rs-relay fails OPEN if its gRPC admission
server is unreachable, so a dead admission = an unrestricted relay. The backend
now EXITS if the admission service stops (supervisor restarts a clean pair);
documented in RELAY.md. Pin the relay image to a digest (compose note).
- Registration-oracle protection: validate() now refuses a non-loopback
RELAY_ADMISSION_BIND unless RELAY_ADMISSION_ALLOW_PUBLIC=true (+ test).
- No N+1 on crafted events: recipient p-tags are capped (20, deduped) and resolved
in ONE batched query (db.any_registered_npub) instead of one-per-tag.
- Defence-in-depth size cap: admission denies events over max_event_bytes before
any DB work (the relay enforces its own limit too).
- Docs: RELAY.md Security section (fail-open, loopback oracle, default PoW=0 spam
footgun, client sender-verification); config.toml relay port 8088 (not 8080);
Docker Hub image; .env.example RELAY_ADMISSION_ALLOW_PUBLIC.
Note: the client-side sender-impersonation blocker is fixed separately in the
monorepo (verifying gift-wrap unwrap).
Completes the operator side of the relay integration:
- deploy/relay/: reference docker-compose + config.toml for a locked-down
nostr-rs-relay wired to the backend's gRPC admission (host networking so the
loopback admission socket stays private). Clearly marked a template to pin/
verify against the operator's nostr-rs-relay version.
- docs/operations/RELAY.md: what it is (inbox relay, not the only relay), the
admission architecture, the three write policies + NIP-13 PoW, bundled vs
external, verification, and the seam's modularity. Linked from OPERATOR_SETUP.
- .env.example: the RELAY_* block (all off/placeholder).
Backend relay integration (config → seam → policy → gRPC admission →
capabilities → NIP-05 → packaging/docs) is now complete. Client DM stack next.
So clients can discover + connect to the relay (and self-adapt when it's off):
- /capabilities: features.nostr_relay + a messaging{ relay_url, write_policy,
inbound_pow_bits, supported_nips } object, with the same config-presence
downgrade as chains/nostr_identity (advertised only when enabled AND a URL is
configured — never advertise a relay clients can't reach). OpenAPI regenerated.
- nip05.rs: /.well-known/nostr.json relay hints are now config-driven — this
instance's own relay (the user's DM inbox) first when enabled, then the public
interop relays (damus/nos.lol) so cross-wallet delivery still works. Replaces
the hardcoded-only default.
nostr-rs-relay's [grpc] event_admission_server calls Authorization.EventAdmit
once per inbound event; we answer PERMIT/DENY so the write policy is enforced at
ingest (dynamic, per-event — a static pubkey whitelist can't do inbox/PoW).
- proto/nauthz.proto (matches nostr-rs-relay's contract) compiled by build.rs;
protoc is vendored (protoc-bin-vendored) so a source build needs no system
protobuf-compiler. tonic/prost added (reuse the hyper/tower/h2 stack axum
already pulls in); server-only codegen.
- infra/relay/nauthz: AdmissionService resolves author + recipient (p-tag)
registration via the DB, runs the pure policy engine, returns the decision;
served on a loopback socket (spawned in main only when relay enabled + policy
!= open), mirroring the admin plane. Fail-closed on a malformed request.
- db: is_registered_npub(hex) — a no-PII membership check safe to call per event.
- tests/relay_admission.rs: L1 handler tests (is_registered_npub membership +
outbox/inbox/deny-non-giftwrap/deny-unregistered-recipient through the real
event_admit handler against live Postgres).
First slice of the optional Nostr relay (messaging plane), behind a swappable
seam mirroring the PaymentProvider pattern so nostr-rs-relay can be replaced by
another relay (strfry/external) or another messaging protocol later.
- config: MessagingConfig { relay: RelayConfig } — RELAY_ENABLED (off by default),
mode (bundled|external), advertised ws(s):// URL, write_policy
(inbox-outbox default | author-allowlist | open), inbound_pow_bits (NIP-13),
admission_bind, resource caps. validate() fail-closes (URL required + ws(s)://
+ wss in prod, known policy, PoW <= 40, admission bind for non-open). +7 tests.
- infra/relay: RelayProvider trait + from_config (feature-gated, fail-closed) +
the default nostr-rs-relay/external adapter; AppState.relay wired
(lib/main/tests).
- infra/relay/policy: PURE admission engine (WritePolicy, decide, NIP-13
leading_zero_bits): open permits all; author-allowlist gates on a registered
npub; inbox-outbox permits a registered author's outbox OR a kind-1059 gift-wrap
addressed to a registered user (inbox), the external-inbound branch optionally
behind a PoW gate. Registration lookups are resolved by the caller and passed as
booleans so the decision is pure + fully unit-tested (10 tests).
The gRPC event-admission service that calls this engine, capabilities/NIP-05
advertising, packaging, and the client DM stack land in the following slices.
Adversarial review (Identity Phase 1 flow) findings:
- Canonicalize the pubkey returned by verify_nip98 / verify_signed_action to
lowercase hex. BIP-340 hex-decode is case-insensitive, so an UPPER-case-hex
pubkey is a fully self-consistent, verifying event — but stored/looked-up
verbatim it would let ONE key bind to two accounts via case variance (bypassing
the UNIQUE index + 409) and yield non-canonical NIP-05 output. Now every
downstream store/compare/lookup is on the canonical form. +KAT.
- nostr_link records a login event on success: a session-authed link (including a
rotation that REPLACES an existing npub) is a security-relevant binding change
and must not be silent.
- Tighten NIP98_LOGIN_MAX_AGE_SECS 60 -> 30s: a captured login token is a bearer
credential within the window; match it to the state-change grade.
The link flow was stubbed: consume_link_nonce always returned false and no nonce
issuer existed, so nostr_login worked only for already-linked npubs and nothing
could link one. Complete it:
- GET /auth/nostr/link-challenge (authenticated) issues a single-use nonce via
the existing challenge store, bound to the caller (subject) + the nostr_link
purpose, 5-minute TTL.
- nostr_link now consumes it atomically (DELETE … RETURNING, so a replay loses
the race), cross-checks the nonce was issued to THIS user, then verifies the
signed-action proof (unchanged) and stores the npub.
- Route registered + OpenAPI regenerated (no drift).
tests/nostr_auth.rs: pins the empty-body descriptor hash as a cross-impl KAT (the
wallet binds the identical value), and covers a full challenge→link round-trip
plus replay and wrong-user-nonce rejection.
create-admin-wallet registered a pending admin key but never latched setup, so on
a fresh instance it left the bootstrap half-open and a later `setup` collided with
it (setup's guard only checked for an ACTIVE admin; the cli key was pending).
- New atomic Database::create_admin_key_bootstrapping: under the admin-keys
advisory lock, insert the pending generated key AND latch `locked` (unless
already validly locked), append audit, commit — one transaction. Fails CLOSED on
a tampered latch (defers to reset-setup) instead of silently healing it.
- bootstrap_admin (setup) now refuses on ANY live admin key (active OR pending),
not just active, so setup composes with create-admin-wallet. The adopt-existing-
deployment path (users but no admin keys) is unaffected: no live key -> proceeds.
- reset_setup now takes the same advisory lock (all latch writers serialize) and
documents the live-key recovery path.
- CLI prints bootstrapped-vs-added and a terminating lost-secret recovery hint.
- Docs (README + OPERATOR_SETUP section 5): both mutually-exclusive bootstrap paths.
Adversarially reviewed (atomicity / lockout / regression — all ship). L1 test
extended: fresh-latch, no-relatch-when-locked, pending semantics, composition
guard, and tamper-refuse (fails closed + rolls back the key insert).
- .env.example: add the required at-rest identity secrets (SEED_FINGERPRINT_PEPPER,
REFRESH_TOKEN_PEPPER, IP_SALT). They were missing, so `cp .env.example .env` on a
fresh setup boot-failed closed on the first required-secret check.
- README: correct the first-admin bootstrap to `smirk-admin setup --pubkey`.
create-admin-wallet registers a pending key but does not latch, so on a fresh
instance it leaves the bootstrap uninitialized.
- docs/operations/OPERATOR_SETUP.md: full deployment guide — database, secrets,
per-chain backends, run + verify, admin bootstrap, registration policy, and
smoke-testing an instance (SMOKE_API_STYLE=namespaced).
Surfaced by a clean-room operator setup against a fresh instance.
Optional REGISTRATION_REQUIRE_PAYMENT gate: a new wallet must settle an
invoice on an external, non-custodial payment processor before it can
register. Pull model — the grant reads the processor's authenticated API as
the source of truth, so there is no inbound webhook to secure and a settled
invoice cannot be forged over HTTP. Returning wallets and self-hosting bypass
it, exactly like the invite and PoW gates.
- infra/payment: a pluggable PaymentProvider seam (neutral Invoice /
InvoiceStatus / InvoiceRequest) with a BTCPay-compatible first adapter that
also serves this project's xmrcheckout/wowcheckout apps + the BTCPay Monero
plugin, so "operator picks any coin" costs one adapter. A future ETH/native
adapter (BTCPay serves neither) implements the same trait. Only `Settled`
grants (unknown status fails safe); the API key rides in a redacting Secret
and hostile responses are size-capped.
- payment_invoices: invoice<->pubkey_hash binding + atomic single-use consume
(UPDATE ... WHERE consumed_at IS NULL AND pubkey_hash=$ RETURNING), so one
invoice grants at most one registration and never a different identity.
- POST /auth/payment-invoice mints + binds; enforce_payment (bind -> processor
`Settled` -> atomic consume) runs beside enforce_invite; payment_invoice_id
on the register request.
- Fail-closed config: https-in-prod, positive-decimal price, >= 1 confirmation
(bars a 0-conf settled-then-double-spent free registration), bounded expiry.
/capabilities advertises payment_required + price; OpenAPI + .env.example.
Tests: adapter status/speedPolicy mapping + config validation (unit), and L1
binding + atomic single-use (concurrent-consume-one-wins, mis-bind rejected).
Reviewed adversarially across payment-integrity, leak/oracle, and config/DoS
lenses; the confirmed findings (0-conf, expiry bound, Settled-means-paid-in-full
adapter contract, rotation-branch bypass guard) are addressed here.
Default restore policy is now create-only — which betrays no self-sovereignty,
since that lives at the ECOSYSTEM level (run your own backend). On top of the
create-only|bounded|unlimited depth gate, restore depth can be PRICED in hashcash
PoW so an importer pays compute proportional to the chain-scan cost they impose
on the operator (deeper restore => more work).
- core::restore_pow: a self-contained hashcash bound to (asset, address,
start_height) — a solved nonce is valid only for that exact restore, so no
challenge state, no replay, no depth-downgrade. Difficulty = leading zero bits.
- RestoreConfig: pow_free_days / pow_days_per_bit (0 = off) / pow_max_bits curve;
required_restore_pow_bits + enforce_restore_pow (literal errors, no oracle).
- Enforced at xmr/wow register + grin scan via a new restore_pow_nonce; the curve
is advertised via /capabilities so the wallet computes + solves it.
- Default WALLET_RESTORE_POLICY flipped bounded -> create-only.
- Unit tests (curve scaling/cap, off-when-zero, valid/invalid nonce, hashcash
roundtrip + param-binding); .env.example; OpenAPI drift clean.
First of the operator-configurable registration gates (PoW-priced restore and
pay-to-register follow). A NEW wallet must present a valid invite code when
REGISTRATION_REQUIRE_INVITE is on; returning wallets and self-hosting bypass it,
and the active gates are advertised via /capabilities so the wallet shapes
onboarding.
- migration + db: invite_codes table storing only sha256(code) (128-bit codes,
no pepper needed). Redemption is an atomic single-statement claim
(UPDATE ... WHERE used_at IS NULL RETURNING) — single-use even under concurrent
submission (L1 test fires 8 concurrent claims; exactly one wins).
- core::invite: generate (base58, 128-bit) + sha256 hash.
- enforce_invite in extension_register, mirroring enforce_pow (returning bypass;
ONE literal error for not-found/used/expired — never an oracle).
- RegistrationConfig.require_invite + RegistrationCapability in /capabilities.
- smirk-admin mint-invite --count/--label (prints raw codes once; stores hashes).
- L1 tests (single-use + concurrency race), .env.example, OpenAPI (drift clean).
The 1.1-alpha LWS dropped the start_height param from add_account (every account
starts scanning at the chain TIP) and moved restore to a separate /rescan admin
command. The backend's import_account still passed start_height to add_account —
a no-op there, so imported/restored wallets never scanned their history (balance
read as 0).
Rework import_account: register only if the account is new (add_account errors
on a duplicate), then lower its scan height to the wallet birthday with a
backwards /rescan when that strictly lowers it (honoring rescan's backwards-only
invariant). Drop the now-unused start_height from add_account / AddAccountParams.
Verified live against a freshly-built wownero-lws 1.1-alpha: registering with a
start_height drives the rescan and the historical outputs are found.
POST /wallet/lws/balance returned a server-summarized {unlocked, locked} where
unlocked = total_received - locked OVER-COUNTED: a non-custodial backend cannot
verify spends without the spend key, so it never subtracted them. Reshape to the
wallet's verification-passthrough contract — aggregate get_address_info +
get_address_txs (parallel) and return total_received, locked_balance,
pending_balance (0-conf summed directly from mempool rows: webhook-free, cleaner
than the private backend's DB table), and spent_outputs[] for client-side
key-image verification. The wallet nets its own spends (privacy-correct).
spent_outputs fixes the over-count immediately; pending_balance activates once
the parity LWS mempool feature is deployed. Adversarially reviewed (3 lenses,
0 confirmed findings).
How far back a wallet may ask THIS instance to scan on import is an operator
decision — the backfill cost lands on its LWS/node. Add WALLET_RESTORE_POLICY
(create-only | bounded | unlimited, default bounded) + WALLET_MAX_RESTORE_DEPTH_DAYS,
advertise it via /capabilities so the wallet adapts its import UX, and enforce
it at the scan path (xmr/wow register, grin scan): a too-deep start_height is a
ValidationError naming the bound, never the caller's value. Create needs no
check (no tip lookup). Self-sovereignty stays intact at the ecosystem level —
a deeper restore means self-hosting or a looser operator. Fail-closed config
validation; a unit test per policy; OpenAPI drift clean.
The wallet's ChainProvider seam fetches all chain tips in one call
(getBlockchainHeights) and selects per asset; the backend exposed per-chain
height endpoints but no aggregate, so the client's call 404'd. Add a
best-effort /wallet/heights returning {btc,ltc,xmr,wow,grin} concurrently — a
disabled or unreachable chain is null, never failing the others. JWT-gated,
OpenAPI-annotated (drift clean).
The spec carried no security scheme, so generated clients/docs could not tell
which endpoints require a session token — e.g. /wallet/utxo/balance read as
public while its handler enforces auth via extract_user_id_from_token. Add a
`bearer_auth` HTTP/JWT scheme through a Modify addon and annotate every route
that resolves a session; auth-bootstrap, public username/key lookups, and
system routes stay open. Regenerated openapi.json (drift clean).
Source comments pointed at gitignored docs/private/*.md design docs — harmless
(no secret) but dangling references in a public tree. Inlined the rationale and
dropped the pointers. Comment-only.
6 confirmed findings (review wqrd2gka3), 3 root-cause fixes:
- HIGH: execute_erasure had no status recheck and the sweeper's SKIP LOCKED row
lock was released before execution (separate connection), so (a) a request
CANCELLED after the sweep's SELECT was still executed, and (b) a fleet could
double-execute one erasure (duplicate hash-chained audit row, double count).
Fixed by making execution atomically CLAIM the row as its first statement —
`UPDATE ... SET status='completed' WHERE id=$1 AND status='confirmed'
RETURNING user_id` — and skipping (returns false) when 0 rows match. Only the
first executor of a still-confirmed request proceeds; a cancelled/already-done
row is a no-op; on any later failure the whole tx (claim included) rolls back.
- account-existence oracle: the absent-user request path returned a FRESH random
erasure_id + advancing scheduled_for each call, while a real account returned a
STABLE get-or-create id — a re-call distinguisher. The request response is now
constant-shape: a STABLE id (real, or a deterministic integrity-secret-keyed
synthetic for the absent path), a fixed "pending" status, and NO scheduled_for
(it's meaningful only at confirm, where grace starts, and is returned there).
- config: ERASURE_GRACE_PERIOD_HOURS is bounded (<= 10 years) in validate(), so
the u64->i64 cast can't wrap negative (defeating grace) and Duration::hours
can't panic.
Dismissed after verification: ERASURE_ENABLED without FEATURE_NOSTR_IDENTITY
(validate already requires PUBLIC_API_URL; the nostr_identity coupling is a
nicety). Tests extended: cancelled-request-not-executed (HIGH regression),
double-execute no-op. 140 lib + 140 integration green, no drift, scans clean.
The last operator subsystem: a user who no longer trusts the backend can reach in
and delete their data. Action-bound and two-phase.
- migration 20260626000003: erasure_requests (user_id ON DELETE SET NULL so the
completed tombstone survives the user delete; one-live-request-per-user partial
unique index; due index).
- Proof model (§5.2): every action is a fresh NIP-98 signed action (purpose
erasure_request/confirm/cancel/export) bound to a single-use challenge nonce +
canonical descriptor + (confirm/cancel) the explicit erasure_id. A session
token is NEVER sufficient. Erasure targets only the users.id the proof's key
resolves to (via linked nostr_pubkey); leaked identifiers are never selectors.
Nonce consumed AFTER signature checks (forged sig can't burn a victim's nonce).
- Public routes (proof-gated): POST /account/erasure/challenge, /account/erasure
(request; ABSENT-user path returns identical shape — no account-existence
oracle), /account/erasure/:id/confirm (revokes live sessions), DELETE
/account/erasure/:id (cancel during grace), POST /account/export (see-before-
delete; omits view keys; audited).
- Execution (§5.7): a background sweeper claims confirmed-past-grace rows
(FOR UPDATE SKIP LOCKED) and runs ONE fail-closed tx: purge login_events
(the origin/asset/time quasi-identifier; default) or anonymize; scrub audit
PII; DELETE users (schema cascades wallets/sessions/keys/owned slatepacks,
SET NULL on counterparty/audit/login links); tombstone; hash-chained
account_erasure_completed audit.
- config: ERASURE_GRACE_PERIOD_HOURS (72h default); validate() requires the
integrity secret + PUBLIC_API_URL when erasure is enabled.
- 1 L1 test: export -> request -> confirm -> execute -> account gone, plus the
absent-user constant-shape path.
Scope (v1, documented): live primary. No at-rest view key exists to crypto-shred
(stateless-forward), so backup residue is bounded by retention-window docs, not
crypto-shred (non-v1 per decisions ledger). Deferred: LWS de-registration queue +
read-back probe (operators run their own LWS), audit cross-reference scrub on
OTHER users' rows, restore_attempt salted-rotated fingerprint, retention sweepers,
NIP-17 DM warning, in-flight-value blockers (no swaps/tips in the clean core),
hard per-day export rate cap, /admin/erasure/stuck observability. Routes are off
the public OpenAPI for now (stable contract; annotate later).
9 confirmed findings (review wbdf3c0sd), all fixed:
S4 (capabilities):
- REGRESSION: /capabilities reported grin_relay:false for a working relay (S4
wrongly coupled it to Grin chain serviceability). The relay is a non-custodial
mailbox — wallet broadcasts locally — so it is decoupled again. Removed the now-
dead grin_relay downgrade note.
S3 (bootstrap latch):
- A DELETE of the latch row escaped Locked without Tampered detection on a
CLI-bootstrapped-but-no-users instance (adoption keyed off `users` only). Boot
now adopts on has_any_users() OR has_any_admin_keys(), so a deleted latch
re-latches Locked instead of silently dropping to uninitialized.
- bootstrap_admin's single-bootstrap guard was a check-then-insert race (two
concurrent `setup` could seed two admins). It now takes the admin-keys mutation
advisory lock (shared with add/revoke/rotate) at the top of its tx.
S2 (admin posture + landing):
- Hard bind guard matched loopback by string prefix ("localhost".starts_with) —
"localhost.evil.com" slipped past. Now resolves via to_socket_addrs and requires
EVERY resolved addr to be loopback.
- host_allowed's IPv6 loopback check was an unanchored prefix ("[::1]" matched
"[::1].evil"); now anchored to exactly "[::1]" / "[::1]:port". +regression tests.
- Anti-clickjacking headers (X-Frame-Options/CSP) are now applied on the 403
Host-reject path too (computed on both branches, headers added once).
- GET /api/v1/server-info now returns a BARE 404 when landing is off (the
{error,code} envelope itself hinted the route exists).
- Public landing `chains` now uses the SAME serviceability predicate as
/capabilities (no over-advertising an unserviceable chain).
- Removed the dead/misleading PUBLIC_EXPOSE_FEATURES toggle (never read; the
feature tuple is intentionally never emitted anonymously).
Dismissed after verification: latch chains-by-flag (dup), title length bound
(operator-owned + escaped), prices:true with empty PRICES_ASSETS (documented).
140 lib + 140 integration green, no openapi drift, scans clean.
Make /capabilities fail-closed and add the admin features surface.
- Secret-presence downgrade (§4.2): a chain whose flag is on but whose source is
unconfigured (btc/ltc no electrum URL, xmr/wow no LWS admin key, grin no owner
secret) now reports enabled:false — so /capabilities never advertises a chain
that would 404, and a missing-secret downgrade is indistinguishable from a
deliberately-off chain. grin_relay requires serviceable Grin; nostr_identity
requires PUBLIC_API_URL. effective_capabilities() is the single explicit mapper.
- contract_version stamp on the public document (clients soft-notice a higher
value, ignore unknown additive keys).
- GET /admin/features (admin_guard): the resolved effective state PLUS admin-only
downgrade reasons (the public surface hides the reason, per §4.3).
- Golden test: the public capabilities JSON, built from a fully-secret-seeded
config, contains no secret value (asserts no "integration-test-" substring).
openapi regenerated (contract_version). Admin features view stays off the public
OpenAPI.
Deferred (documented): runtime mutation — PUT /admin/features + a DB feature-
override table + resolve() precedence + Arc hot-swap + CLI `features set`. Flags
are env/config-driven for v1; runtime tuning (and its fleet propagation, itself a
deferred LB decision) is a later addition.
Admin posture (§2.1/§2.2):
- Hard fail-closed bind guard in main: a non-loopback ADMIN_BIND refuses startup
unless ADMIN_ALLOW_PUBLIC_BIND=true (was a warning).
- admin_plane_guard middleware on the admin router: Host allowlist
(localhost/127.0.0.1/[::1]/configured TOR_ADMIN_ONION; a missing Host is allowed
since rebinding must supply one and the bind is the primary control) to defeat
DNS-rebinding against the loopback socket, plus X-Frame-Options: DENY +
CSP frame-ancestors 'none' (anti-clickjacking). Still no CORS on the admin plane.
Public landing (§2.3), default-OFF, one fingerprint surface:
- GET /api/v1/server-info — built from a hand-written ServerInfo allowlist (never
by serializing config/state). Default projection is minimal { software.name,
status }; version (coarse major.minor), chains, price_feed, and uptime (bool
`up` only) are each individually opt-in. The enabled-feature tuple is NEVER
emitted anonymously (connected clients use /capabilities).
- GET / — minimal HTML (operator title HTML-escaped); bare 404 when off (does not
hint an admin plane exists). server-info also 404s when off.
- config: ADMIN_ALLOW_PUBLIC_BIND, TOR_ADMIN_ONION; PUBLIC_LANDING_TITLE +
per-field PUBLIC_EXPOSE_VERSION/CHAINS/PRICE_FEED toggles.
Tests: host_allowlist + html_escape unit tests; landing off->on minimal-projection
(asserts only software+status, no version/chains/features); admin-plane Host-403 +
anti-clickjacking headers. Landing/admin stay off the public OpenAPI.
Deferred (documented): §2.5 NIP-05 consent-gating (changes existing
/.well-known/nostr.json behavior — needs the standing v0.2.4-compat verification
first), §2.3 k-anon public stats, response-header/TLS-fingerprint stripping (proxy
/ops-doc concern).
No trust-on-first-use: bootstrap mode is an explicit, MAC-protected latch
(server_config singleton), NOT inferred from "no admin keys". The latch MAC
(ADMIN_KEY_INTEGRITY_SECRET over setup_state|bootstrap_completed_at) means a
DB-write attacker who restores a pre-bootstrap backup or flips the state to
re-open TOFU produces a mismatch the boot path detects and fails closed on.
- migration 20260626000002: server_config (id=1 singleton; setup_state +
bootstrap_completed_at + integrity_mac).
- db::server_config: read_setup_state -> {Fresh,Uninitialized,Locked,Tampered}
(MAC-verified); has_any_users; init_server_config (adoption: a live upgrade
latches `locked` so it never exposes a setup window; a truly empty DB begins
uninitialized); bootstrap_admin (insert the FIRST active admin AND latch
locked + hash-chained audit, ONE tx; refuses if an active admin already
exists); reset_setup (shell recovery; recomputes MAC, preserves admin keys).
- main boot (admin enabled): adopt/await-bootstrap, and FAIL CLOSED on a tampered
latch.
- smirk-admin: `setup --pubkey` (the supported headless bootstrap) + `reset-setup
--i-understand`.
- 1 L1 test: Fresh -> locked(valid) -> wrong-secret Tampered -> raw-flip Tampered
-> reset Uninitialized -> bootstrap refused while an active admin exists.
Deferred (documented): the HTTP /setup/* wizard. Per the spec the CLI / `docker
exec` is the SUPPORTED bootstrap (pure-PaaS without shell is explicitly
unsupported), so the loopback TTY wizard is a later convenience, not load-bearing.
A binary that talks to Postgres directly, bypassing the HTTP admin plane and all
network rate limits — the recovery path when the network plane is unreachable or
a solo admin key is compromised. Authority = shell + DB creds +
ADMIN_KEY_INTEGRITY_SECRET. Every mutation writes a hash-chained audit row
(actor_kind=cli).
Commands:
- list-keys
- add-key --pubkey <64hex> [--label]
- revoke-key --id <uuid> — MAY revoke the last key (keep_min_live=false;
the network DELETE refuses that, the CLI is the authority)
- replace-key --old <uuid> --pubkey <64hex> [--revoke-all] — atomic rotate; with
--revoke-all, the global break-glass that revokes every other live key
- create-admin-wallet --out <path> — generate a schnorr keypair from OS entropy,
write the secret hex to a NEW 0600 file (create_new, never clobber/stdout/log),
register only the pubkey; seed + secret buffers zeroized (zeroize crate)
- doctor — DB reachability, live-key count, audit-chain verification
Preflight refuses to run if a present .env is group/other-readable. No new dep
beyond zeroize; bin auto-discovered as `smirk-admin`. Smoke-tested end to end
(wallet file is 0600; bad pubkey rejected; doctor detects a wrong-secret chain).
Deferred (documented): remac-keys (integrity-secret rotation must also re-chain
the audit log) and setup/reset-setup (first-run bootstrap = Subsystem 3).
From a 5-lens adversarial review of the admin surface (6 confirmed findings,
collapsing to 4 fixes; 2 dismissed after verification):
- HIGH: last-key-revoke TOCTOU (lockout). The count(live)<=1 floor was checked in
the handler, then revoke ran separately — two concurrent revokes could both pass
and empty the allowlist. Moved the floor INTO revoke_admin_key_full under a
per-tx advisory lock (admin_keys_mutate_lock); returns RevokeKeyOutcome
{Revoked,NotFound,WouldEmptyAllowlist}.
- LOW: ADMIN_MAX_KEYS cap TOCTOU. Same check-then-mutate race on add. Cap is now
counted INSIDE create_admin_key_audited under the same lock; returns
AddKeyOutcome {Created,CapReached}. rotate takes the lock too, so all
add/revoke/rotate serialize.
- LOW: integrity MAC didn't cover activation_deadline — a DB-write attacker could
null/extend the deadline to revive an expired pending key without breaking the
MAC. Added activation_deadline to AdminKeyMacInput + the canonical input +
every compute/verify site; new KAT binds it.
- LOW: get_active_admin_key (and create_*) logged the full pubkey via #[instrument]
(params weren't skipped), defeating the prefix-only / no-social-graph design.
Skipped pubkey/input from those spans.
Dismissed (both skeptics not-a-bug): audit-chain JSONB `details` round-trip — the
handlers always pass details:None and serde's sorted-key default makes the
string case round-trip (the L1 chain test proves it). Documented v1 deferrals
(login timing-oracle hardening, per-pubkey backoff, hard non-loopback bind guard)
remain tracked, not regressions.
All gates green: 138 lib + 138 integration, no openapi drift, secret-scan, leak.
Admin-plane key management, all admin_guard-protected and fail-closed audited:
- POST /admin/keys: add a pending key (validated 64-char lowercase x-only hex;
created_by_kind=admin; activation_deadline = now + ADMIN_PENDING_KEY_TTL_DAYS).
Capped at ADMIN_MAX_KEYS live keys (anti allowlist-stuffing).
- GET /admin/keys: list active/pending/revoked (sanitized view + status).
- DELETE /admin/keys/🆔 soft-revoke + cascade-revoke its sessions + audit in ONE
tx. Refuses to revoke the LAST live key over the network (CLI-only), so an
operator can't lock everyone out.
- POST /admin/keys/:id/rotate: atomic revoke-old(+sessions)+add-new(pending)+audit
in one tx — permitted on the last key (add+revoke, not bare revoke), the in-band
recovery for a compromised solo key.
db: create_admin_key refactored onto a shared insert_admin_key(&mut PgConnection)
helper; create_admin_key_audited / revoke_admin_key_full / rotate_admin_key run
their state change + session cascade + hash-chained audit in a single transaction.
1 L1 test extended to cover add/list/rotate/revoke + malformed-pubkey rejection.
NOTE: the live-key cap and last-key revoke guard are count-based on a table the
shared test DB pollutes across suites, so their boundaries aren't integration-
asserted (covered by review); the happy path raises the cap.
"Sign in with Smirk" for operators. Auth is a NIP-98 signed action over a
single-use nonce (AUTHN) + the MAC'd allowlist (AUTHZ), composed in admin_guard
so a protected route physically cannot run without both. All rejections collapse
to one opaque 401 (no enumeration oracle).
- src/api/admin.rs: admin_guard (verify access token -> live session by jti ->
live MAC-verified, activated allowlist entry) + AdminContext; handlers:
- challenge: mint a 120s admin_login nonce + return the {url, instance_id} the
wallet must bind.
- verify: verify_signed_action (purpose/nonce/descriptor/instance) THEN consume
the nonce (forged sig can't burn a victim's nonce; replay loses the race) ->
authorize (pending key allowed for first login, which activates it) -> mint +
persist session AND the login audit row in ONE tx (fail-closed) -> bump
last_used.
- refresh: re-run FULL authorization before minting (closes the "8h refresh is
the real blast radius" gap) + constant-time refresh-hash bind + rotate jti so
the old access token dies.
- logout: revoke the session; audit. me: guarded whoami.
- admin_router (lib): served on a SEPARATE loopback socket in main (confidentiality
by socket, not middleware); no CORS layer (cross-origin browser calls blocked);
warns if bound non-loopback (hard bind-guard lands with admin posture). Routes
are intentionally absent from the public OpenAPI.
- config: ADMIN_PUBLIC_URL (the signed-action u-tag base; validated when enabled).
AppState.admin_sessions (Some only when enabled). AdminSessionManager.mint_access
(refresh) + db helpers (create_admin_session_audited, touch_admin_key_last_used).
- test harness: admin_router() + request_on(router); 1 L1 test exercising the full
flow end-to-end incl. user-token rejection, replay rejection, jti rotation, and
post-logout revocation.
NOTE (for the upcoming S1 review): admin-login timing-oracle hardening (fixed-cost
allowlist probe + jittered 401 floor, spec §1.3) is deferred — the loopback/onion
exposure + single-use nonce + signature gate are the v1 boundary. Per-pubkey
backoff (§0.5) also pending.
A separate, low-volume audit trail for admin/setup/erasure actions, hash-chained
so a DB-write attacker cannot silently rewrite history. Kept distinct from the
high-volume user audit_logs (which keeps its enum action) — the chain applies
only where the privacy-maximalist mandate requires it.
- migration 20260626000001: admin_audit_logs (free-text action, actor_kind,
actor_pubkey_prefix [prefix only, no social graph], target, details, real-peer
ip, prev_hash, row_hash; monotonic seq).
- db::admin_audit: append_admin_audit(&mut PgConnection) so the audit row commits
in the SAME transaction as the state change it records (fail-closed, not a
best-effort side effect); record_admin_audit (own tx) for standalone audits;
verify_admin_audit_chain (boot/doctor walk — detects edit/delete/reorder/broken
linkage); list_admin_audit (panel). row_hash = HMAC(integrity_secret,
prev_hash || canonical(row)); appends serialize on a tx advisory lock so
seq/prev_hash cannot race.
- AdminAuditLog/NewAdminAudit models; 1 L1 test (link + verify + tamper-detect +
restore).
Admin tokens are cryptographically distinct from user tokens: a dedicated
ADMIN_JWT_SECRET, a distinct audience (smirk-admin) plus an explicit scope, and
the centralized strict Validation (HS256 pinned, zero leeway, aud required) —
Validation::default() is never used on this path. Access TTL 15 min (carries a
jti recorded in the session row, so a soft-revoked admin's still-valid token is
rejected at the next call), refresh TTL 8 h (binds a session id).
- core::admin_session: AdminSessionManager (mint/verify access+refresh) with the
four required regressions + scope check: user token fails admin decode;
wrong/absent aud fails; HS512 (alg confusion) fails; expired fails at zero
leeway; non-admin scope fails.
- core::session::strict_validation made pub(crate) and shared (no drift).
- db::admin_sessions: create, find-active-by-jti (guard), find-active-by-id +
rotate-jti (refresh), revoke (logout), revoke-all-for-key (key cascade), and a
dead-session sweep. Lookups return only live (unrevoked, unexpired) rows.
- NewAdminSession model; 2 L1 tests (lookup/rotate/logout, key->session cascade).
The admin authorization data model. The server stores only public keys; an admin
is authorized by presence in admin_keys, and each row carries an HMAC
(ADMIN_KEY_INTEGRITY_SECRET, separate from DATABASE_URL) over
id|pubkey|scope|created_at|activated_at|revoked_at. Because the MAC covers the
revocation/activation state, a DB-write attacker who clears revoked_at (un-revoke)
or revives a key produces a mismatch the guard rejects — the MAC proves a pubkey
is *currently* authorized, not merely once.
- migration 20260625000002: admin_keys (partial unique index = one active row per
pubkey; soft revoke keeps history) + admin_sessions (separate table/secret from
user sessions; cascade-on-key-delete).
- core::crypto::admin_mac: compute/verify over a JSON-canonical field set,
timestamps as microsecond epochs; constant-time compare; KATs bind
revoked/activated state.
- db::admin_keys: create / get_active (re-verifies MAC, fail-closed + logs tamper)
/ list / count_live / activate / revoke. Every covered-field write recomputes
the MAC centrally; timestamps truncated to microseconds so the signed value
round-trips; revoke/activate are FOR UPDATE transactions.
- 5 L1 tests incl. the load-bearing raw-SQL un-revoke -> MAC mismatch -> rejected.