From 7280f9ad07f2bfa741236638c3d82e267ddb5bea Mon Sep 17 00:00:00 2001 From: feruzm Date: Sun, 15 Nov 2026 06:28:31 +0000 Subject: [PATCH 1/5] Correct the notifications canary note: it requires a valid code now --- CLAUDE.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 97cc8b09..70361048 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -108,11 +108,10 @@ Two cheap checks before assuming a token problem: 401s for the same session, the code validated fine and the failure is downstream of this service. - **Do not use `notifications` as that canary.** It falls back to a - body-supplied `user` when validation fails, and overrides even a validated - username with that field whenever it is present. It can therefore answer - happily for a request whose code was rejected, which tells you nothing about - validation and actively misleads. + `notifications` also 401s without a valid code, but a request whose body + names another account in `user` is still served (the restricted feed, for + Decks columns). Only use it as the canary for a request without `user` or + naming the session's own account. - **Check the failure rate.** A token or session problem affects a subset of users; a backend gate that is misconfigured fails for everyone. An endpoint at 100% 401 while its siblings are at 100% success is not an authentication bug From 5a4283a3aa50e188efbe88766788ef1696685f7c Mon Sep 17 00:00:00 2001 From: feruzm Date: Sun, 15 Nov 2026 06:30:53 +0000 Subject: [PATCH 2/5] Bring READMEs and the stack file in line with the code --- README.md | 2 ++ dotnet/README.md | 57 +++++++++++++++++++++++++-------------- dotnet/docker-compose.yml | 3 +++ dotnet/parity/README.md | 6 +++-- 4 files changed, 46 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 0a1db91f..a21e8118 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ docker run -it --rm -p 4000:4000 \ | `PRIVATE_API_ADDR` | private api endpoint | | `PRIVATE_API_AUTH` | private api auth (base64-encoded JSON header object). Must include `X-Vapi-Auth`: the backends identify this service by it (ePoints compares it to its `VAPI_UPSTREAM_AUTH`, so both hold the same value) and refuse reader-bound calls such as Listen without it. A startup error is logged when it is missing | | `HIVESIGNER_SECRET` | hivesigner client secret | +| `ENOTIFY_INTERNAL_TOKEN` | shared secret sent to enotify on a user's own notifications view to unlock the complete feed (must match enotify's `INTERNAL_TOKEN`; unset = self-views get only the chain-derived feed) | | `SEARCH_API_ADDR` | hivesearcher api endpoint | | `SEARCH_API_SECRET` | hivesearcher api auth token | | `STRIPE_INTERNAL_SECRET` | shared secret for the Stripe money endpoints (unset = they fail closed) | @@ -56,6 +57,7 @@ docker run -it --rm -p 4000:4000 \ | `BLOCKSTREAM_CLIENT_ID` / `BLOCKSTREAM_CLIENT_SECRET` | optional Blockstream Enterprise esplora auth (BTC fallback) | | `HELIUS_API_KEY` | optional Helius API key added as an extra Solana RPC fallback | | `ETH_RPC_URLS` / `BNB_RPC_URLS` / `SOL_RPC_URLS` / `BTC_ESPLORA_URLS` | optional comma-separated endpoint lists overriding the built-in chain provider pools | +| `PUBLIC_DIR` | static assets directory (default `/public`) | | `Logging__LogLevel__Default` | log level (default `Warning`; set `Information` for per-request logs) | | `SSR_INTERNAL_SECRET` | shared header secret that switches on the internal SSR RPC cache routes (`/private-api/ssr/*`); unset = they answer like unknown routes | | `SSR_CACHE_BYTES` | byte budget of the SSR RPC cache, LRU beyond it (default 512 MiB) | diff --git a/dotnet/README.md b/dotnet/README.md index 2d01f943..3beaa4cb 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -20,22 +20,26 @@ win is a faster, more predictable proxy under concurrent load. dotnet/ EcencyApi/ the service Program.cs host, middleware, static files, error handler - Config.cs mirror of src/config.ts (same env vars + defaults) + Config.cs env-var configuration (started as a mirror of src/config.ts) Handlers/ Routes.cs 1:1 map of src/server/index.tsx route table SearchApi.cs search-api.ts AuthApi.cs auth-api.ts (HiveSigner code create/refresh) PrivateApi.*.cs private-api.ts, split by concern WalletApi.*.cs wallet-api.ts (market helpers, portfolio layers, engine) + SsrRpc.cs internal SSR RPC read cache (/private-api/ssr/*) Announcements.cs / Spotlights.cs / HiveExplorer.cs / Constants.cs / ChainProviders.cs Infrastructure/ Upstream.cs axios baseApiRequest + Express pipe() parity ApiClient.cs helper.ts apiRequest (PRIVATE_API_AUTH header injection) + NodeHealthTracker.cs per-node health state + pool ordering (see below) HiveRpcClient.cs dhive-style Client with node failover (see below) + EngineRpcClient.cs Hive-Engine RPC with the same failover + ServerErrors.cs 500/503 error responses HiveCrypto.cs dhive crypto: key-from-login, canonical ECDSA, recovery JsJson.cs JS-identical JSON.stringify (for signed messages) JsVal.cs JS parseFloat / Number / typeof coercions - B64u.cs, MemCache.cs, HttpContextExtensions.cs + B64u.cs, MemCache.cs, BytesCache.cs, HttpContextExtensions.cs, ... Models/HiveEngine.cs hiveEngine.types.ts + converters.ts EcencyApi.Tests/ xUnit: crypto golden vectors, failover, JS semantics parity/ differential HTTP parity harness (Node vs C#) @@ -57,28 +61,39 @@ failover with a health tracker adopted from the vision-web SDK's without a throttle). Parked nodes sort last but remain a final resort. - **Recent failures deprioritize** (30s window) — one bad response moves traffic away without banning the node; it re-enters when the window lapses. -- **Latency EWMA ranking** (alpha 0.3, trusted after 3 samples, stale after - 5 min): a proven-slow node (>1s) is demoted behind unexplored nodes; config - order breaks ties so cold start behaves like the configured list. +- **Repeated failures park the node**: 3 in a row park it for 30s, doubling to + 120s (a success clears the streak), and it is not tried while any other node + is available. +- **Latency EWMA ranking per call class** (`CallClass.Cheap` point reads vs + `CallClass.Heavy` feed-shaped queries, each with its own profile; alpha 0.3, + trusted after 3 samples, stale after 5 min): a proven-slow node (>1s) is + demoted behind unexplored nodes; config order breaks ties so cold start behaves like the configured list. - **Overload responses** (429/502/503/504) advance to the next node immediately — no wasted local retry on a throttled node. - **RPC-level errors** (a JSON `error` field) surface without failover — an application error, not an unhealthy node (matches dhive). +- **Result shape is validated** by the typed helpers (`get_accounts` must be an + array, `get_dynamic_global_properties` an object): a 200 with no usable + result is a node failure and fails over. + +`EngineRpcClient` applies the same tracker to the Hive-Engine `/contracts` and +history pools. Not adopted from the SDK (overkill at proxy call rates, documented for later: -request hedging, per-API failure profiles, head-block staleness checks). +request hedging, head-block staleness checks). The chain-balance providers (`ChainProviders.cs` / `PrivateApi.Chain.cs`) have their own equivalent provider-pool failover for the EVM/Solana/BTC endpoints. Covered by `EcencyApi.Tests/HiveRpcFailoverTests.cs` (rate-limit parking, -failure deprioritization, timeout rollover, EWMA demotion, all-down error). +failure deprioritization, timeout rollover, EWMA demotion, all-down error) and +`EngineFailoverTests.cs`. ## Verifying identical responses Two layers of verification: -**1. Unit tests** (`dotnet test`, 40 tests): +**1. Unit tests** (`dotnet test`): - Crypto is checked **byte-for-byte against dhive**. `tools/gen-vectors.js` runs the exact `@hiveio/dhive` the Node service uses and emits golden vectors (key-from-login, canonical ECDSA signatures, public-key recovery, the full @@ -88,7 +103,7 @@ Two layers of verification: `parseFloat("")` is `NaN`, etc.) that the wallet numeric parity depends on. - `HiveRpcFailoverTests` exercise the failover against local stub nodes. -**2. Differential HTTP parity** (`parity/`): fires an identical catalog of 301 +**2. Differential HTTP parity** (`parity/`): fires an identical catalog of request variants (every route × empty/populated/bad-auth bodies, plus error and fallback probes) at the running Node image and the C# build, then diffs status, content-type, and body. @@ -115,8 +130,9 @@ python3 parity/driver.py run csharp http://127.0.0.1:14001 python3 parity/driver.py diff node csharp node2 ``` -Latest result: **0 unexplained mismatches / 301 cases** (the intentional -divergences listed above are recorded in the harness). A handful of cases compare "loose" +Result at the migration cutover: **0 unexplained mismatches / 301 cases** (the +intentional divergences listed below are recorded in the harness). The catalog +has grown with the route table since. A handful of cases compare "loose" (status + content-type only) because they are inherently nondeterministic — timestamped HiveSigner tokens, random promoted-entry shuffles, and live portfolio data. The full `portfolio-v2` aggregation was additionally compared @@ -166,8 +182,9 @@ same CPU budget**. `:permlink` route params their POST routes never declared, so they always queried `undefined/undefined` upstream. -All three are recorded in the parity harness (`KNOWN_DIVERGENCES` / -route-table-driven catalog). +All three are recorded in the parity harness's `KNOWN_DIVERGENCES`, together +with every later intentional change (mostly routes added after the port, which +the Node reference answers as unknown). ## Remaining edges (low-risk, documented) @@ -198,13 +215,14 @@ Run from this `dotnet/` directory: ```bash dotnet build EcencyApi/EcencyApi.csproj # compile -dotnet test EcencyApi.Tests/EcencyApi.Tests.csproj # 40 tests: crypto vectors, failover, JS semantics +dotnet test EcencyApi.Tests/EcencyApi.Tests.csproj # crypto vectors, failover, JS semantics, handlers ``` ### Run locally -Configuration comes entirely from environment variables — the same set, with -the same defaults, as the Node service (`Config.cs` mirrors `src/config.ts`): +Configuration comes entirely from environment variables. The variables the +Node service had keep its names and defaults. This table covers the common +ones; the root `README.md` has the complete list: | variable | purpose | default | |---|---|---| @@ -255,9 +273,8 @@ docker run -d --name vapi-csharp -p 4000:4000 \ ecency/api-csharp ``` -For swarm, `docker-compose.yml` in this directory is a drop-in equivalent of -the repo-root stack file (same service shape, ports, env list, and deploy -policy) pointing at the C# image. +For swarm, `docker-compose.yml` in this directory is the stack file (see the +root `README.md`). ### Deployment tags & rollback @@ -286,7 +303,7 @@ API_PORT=4000 ... dotnet /opt/vapi-csharp/EcencyApi.dll ### Regenerate crypto golden vectors -Only needed if the dhive dependency of the Node service changes: +Only needed to refresh the vectors against a different dhive version: ```bash # the repo no longer carries Node dependencies; install the two packages anywhere diff --git a/dotnet/docker-compose.yml b/dotnet/docker-compose.yml index e4e83bf4..ce67f861 100644 --- a/dotnet/docker-compose.yml +++ b/dotnet/docker-compose.yml @@ -39,10 +39,13 @@ services: - SSR_RPC_NODES - SSR_RPC_MAX_FILLS - SSR_RPC_MAX_QUEUED_FILLS + - SSR_RPC_CALL_CLASSES # Curation desk (Handlers/PrivateApi.CurationDesk.cs): the shared token switches # the routes on (unset = 503); the byte budget tunes the two memo stores. - DESK_INTERNAL_TOKEN - DESK_MEMO_BYTES + # Unlocks the complete notifications feed on self-views (enotify INTERNAL_TOKEN). + - ENOTIFY_INTERNAL_TOKEN ports: - "4000:4000" # Bound container logs so they can never grow unchecked on the host diff --git a/dotnet/parity/README.md b/dotnet/parity/README.md index 7a5e7d98..8a3010ec 100644 --- a/dotnet/parity/README.md +++ b/dotnet/parity/README.md @@ -6,8 +6,10 @@ whole route surface. - `mock_upstream.py` — a stub for every upstream (private API, search, chain RPC/esplora) that records each proxied request and returns deterministic bodies, so both services observe identical upstreams. -- `driver.py` — generates a catalog of 305 request variants from the Express - route table (`src/server/index.tsx`), fires it at a target, and diffs two runs. +- `driver.py` — generates the request catalog from the C# route table + (`EcencyApi/Handlers/Routes.cs`; `VAPI_ROUTES_CS` overrides it, `VAPI_INDEX_TSX` + points it at a legacy Express `index.tsx`), fires it at a target, and diffs two + runs. `python3 driver.py catalog` shows the current cases. ```bash python3 driver.py catalog # inspect the generated cases From 260d5b4d080f9248011571a97cd509704f8a79bd Mon Sep 17 00:00:00 2001 From: feruzm Date: Sun, 15 Nov 2026 06:34:22 +0000 Subject: [PATCH 3/5] enotify token is optional: enotify trusts its private network, not a secret --- README.md | 2 +- dotnet/EcencyApi/Config.cs | 9 +++++---- dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs | 6 +++--- dotnet/docker-compose.yml | 3 --- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index a21e8118..bf7756b5 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ docker run -it --rm -p 4000:4000 \ | `PRIVATE_API_ADDR` | private api endpoint | | `PRIVATE_API_AUTH` | private api auth (base64-encoded JSON header object). Must include `X-Vapi-Auth`: the backends identify this service by it (ePoints compares it to its `VAPI_UPSTREAM_AUTH`, so both hold the same value) and refuse reader-bound calls such as Listen without it. A startup error is logged when it is missing | | `HIVESIGNER_SECRET` | hivesigner client secret | -| `ENOTIFY_INTERNAL_TOKEN` | shared secret sent to enotify on a user's own notifications view to unlock the complete feed (must match enotify's `INTERNAL_TOKEN`; unset = self-views get only the chain-derived feed) | +| `ENOTIFY_INTERNAL_TOKEN` | optional, normally unset. enotify serves a user's complete notifications feed to callers on its private network, which is how this service reaches it; the token (sent on self-views, must match enotify's `INTERNAL_TOKEN`) is only for a deployment that reaches enotify from outside that network | | `SEARCH_API_ADDR` | hivesearcher api endpoint | | `SEARCH_API_SECRET` | hivesearcher api auth token | | `STRIPE_INTERNAL_SECRET` | shared secret for the Stripe money endpoints (unset = they fail closed) | diff --git a/dotnet/EcencyApi/Config.cs b/dotnet/EcencyApi/Config.cs index af613269..f37be78f 100644 --- a/dotnet/EcencyApi/Config.cs +++ b/dotnet/EcencyApi/Config.cs @@ -15,10 +15,11 @@ public static class Config Env("PRIVATE_API_AUTH") ?? "privateapiauth"; /// - /// Shared secret presented to enotify to unlock a user's complete notification feed. - /// enotify has no authentication of its own and defaults to chain-derived activity - /// only, so without this a self-view silently loses favorites, bookmarks, Points - /// transfers and the aggregates. Must match [APP] INTERNAL_TOKEN there. + /// Optional secret presented to enotify on a self-view's scope=full request. + /// enotify grants the complete feed to callers on its private network (the normal + /// path, through the private-API gateway) and fails closed to chain-derived + /// activity for everyone else; this token is its override for an entitled caller + /// outside that network. Normally unset. Must match [APP] INTERNAL_TOKEN there. /// public static string EnotifyInternalToken { get; } = Env("ENOTIFY_INTERNAL_TOKEN") ?? ""; diff --git a/dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs b/dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs index 5d8e0c14..ae01a0f8 100644 --- a/dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs +++ b/dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs @@ -143,9 +143,9 @@ await ValidateCode(body), return; } - // The secret rides alongside scope=full. enotify honours the parameter only when - // the header matches, and fails closed otherwise, so a missing or wrong token - // costs this user their own private activity rather than exposing anyone else's. + // enotify honours scope=full only for a caller on its private network, or one + // presenting its optional INTERNAL_TOKEN, and fails closed otherwise. The token + // rides along when configured; the normal path needs none. var extraHeaders = fullScope && Config.EnotifyInternalToken.Length > 0 ? new[] { new KeyValuePair(EnotifyInternalTokenHeader, Config.EnotifyInternalToken) } : null; diff --git a/dotnet/docker-compose.yml b/dotnet/docker-compose.yml index ce67f861..e4e83bf4 100644 --- a/dotnet/docker-compose.yml +++ b/dotnet/docker-compose.yml @@ -39,13 +39,10 @@ services: - SSR_RPC_NODES - SSR_RPC_MAX_FILLS - SSR_RPC_MAX_QUEUED_FILLS - - SSR_RPC_CALL_CLASSES # Curation desk (Handlers/PrivateApi.CurationDesk.cs): the shared token switches # the routes on (unset = 503); the byte budget tunes the two memo stores. - DESK_INTERNAL_TOKEN - DESK_MEMO_BYTES - # Unlocks the complete notifications feed on self-views (enotify INTERNAL_TOKEN). - - ENOTIFY_INTERNAL_TOKEN ports: - "4000:4000" # Bound container logs so they can never grow unchecked on the host From 572355646801df98816775bac0f9440f13150d2c Mon Sep 17 00:00:00 2001 From: feruzm Date: Sun, 15 Nov 2026 06:41:04 +0000 Subject: [PATCH 4/5] Remove the unused ENOTIFY_INTERNAL_TOKEN: enotify trusts the gateway's private address --- README.md | 1 - dotnet/EcencyApi/Config.cs | 10 ---------- dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs | 14 +++----------- 3 files changed, 3 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index bf7756b5..20b9a9ef 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,6 @@ docker run -it --rm -p 4000:4000 \ | `PRIVATE_API_ADDR` | private api endpoint | | `PRIVATE_API_AUTH` | private api auth (base64-encoded JSON header object). Must include `X-Vapi-Auth`: the backends identify this service by it (ePoints compares it to its `VAPI_UPSTREAM_AUTH`, so both hold the same value) and refuse reader-bound calls such as Listen without it. A startup error is logged when it is missing | | `HIVESIGNER_SECRET` | hivesigner client secret | -| `ENOTIFY_INTERNAL_TOKEN` | optional, normally unset. enotify serves a user's complete notifications feed to callers on its private network, which is how this service reaches it; the token (sent on self-views, must match enotify's `INTERNAL_TOKEN`) is only for a deployment that reaches enotify from outside that network | | `SEARCH_API_ADDR` | hivesearcher api endpoint | | `SEARCH_API_SECRET` | hivesearcher api auth token | | `STRIPE_INTERNAL_SECRET` | shared secret for the Stripe money endpoints (unset = they fail closed) | diff --git a/dotnet/EcencyApi/Config.cs b/dotnet/EcencyApi/Config.cs index f37be78f..cd3ed8ad 100644 --- a/dotnet/EcencyApi/Config.cs +++ b/dotnet/EcencyApi/Config.cs @@ -14,16 +14,6 @@ public static class Config public static string PrivateApiAuth { get; } = Env("PRIVATE_API_AUTH") ?? "privateapiauth"; - /// - /// Optional secret presented to enotify on a self-view's scope=full request. - /// enotify grants the complete feed to callers on its private network (the normal - /// path, through the private-API gateway) and fails closed to chain-derived - /// activity for everyone else; this token is its override for an entitled caller - /// outside that network. Normally unset. Must match [APP] INTERNAL_TOKEN there. - /// - public static string EnotifyInternalToken { get; } = - Env("ENOTIFY_INTERNAL_TOKEN") ?? ""; - /// /// Shared secret presented to the curation desk backend on every desk call, /// public reads included: the desk answers only requests that carry it, so diff --git a/dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs b/dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs index ae01a0f8..7dbe3878 100644 --- a/dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs +++ b/dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs @@ -57,9 +57,6 @@ public static bool IsOwnDeviceRequest(string? validatedUsername, string? request internal static Func> DeviceUpstream = (endpoint, method, payload) => ApiClient.ApiRequest(endpoint, method, null, payload); - /// Header enotify reads the shared secret from. - public const string EnotifyInternalTokenHeader = "X-Ecency-Internal-Token"; - /// /// Upstream path for the notifications feed, or null when a value cannot be /// expressed as a single path segment. @@ -143,14 +140,9 @@ await ValidateCode(body), return; } - // enotify honours scope=full only for a caller on its private network, or one - // presenting its optional INTERNAL_TOKEN, and fails closed otherwise. The token - // rides along when configured; the normal path needs none. - var extraHeaders = fullScope && Config.EnotifyInternalToken.Length > 0 - ? new[] { new KeyValuePair(EnotifyInternalTokenHeader, Config.EnotifyInternalToken) } - : null; - - await Upstream.Pipe(ApiClient.ApiRequest(u, HttpMethod.Get, extraHeaders), ctx); + // enotify honours scope=full only for a request arriving from the private-API + // gateway's private address, and fails closed to the chain-derived feed otherwise. + await Upstream.Pipe(ApiClient.ApiRequest(u, HttpMethod.Get), ctx); } // GET ^/private-api/pub-notifications/:username From e1a37a117b72f70a495cbfa9d8bb06a7d28e2717 Mon Sep 17 00:00:00 2001 From: feruzm Date: Sun, 15 Nov 2026 06:45:13 +0000 Subject: [PATCH 5/5] Docs: exact failure-parking condition; notifications canary wording --- CLAUDE.md | 6 +++--- dotnet/README.md | 8 +++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 70361048..28418b6c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -108,9 +108,9 @@ Two cheap checks before assuming a token problem: 401s for the same session, the code validated fine and the failure is downstream of this service. - `notifications` also 401s without a valid code, but a request whose body - names another account in `user` is still served (the restricted feed, for - Decks columns). Only use it as the canary for a request without `user` or + `notifications` also 401s without a valid code. With a valid code, a body + `user` naming another account is still served (the restricted feed, for + Decks columns), so only use it as the canary for a request without `user` or naming the session's own account. - **Check the failure rate.** A token or session problem affects a subset of users; a backend gate that is misconfigured fails for everyone. An endpoint at diff --git a/dotnet/README.md b/dotnet/README.md index 3beaa4cb..0d149606 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -61,9 +61,11 @@ failover with a health tracker adopted from the vision-web SDK's without a throttle). Parked nodes sort last but remain a final resort. - **Recent failures deprioritize** (30s window) — one bad response moves traffic away without banning the node; it re-enters when the window lapses. -- **Repeated failures park the node**: 3 in a row park it for 30s, doubling to - 120s (a success clears the streak), and it is not tried while any other node - is available. +- **Repeated failures park a node that is not answering**: 3 failures in a row + park it for 30s, doubling to 120s, but only when it has never succeeded or its + failure-rate EWMA (alpha 0.1) is at least 50%, so a node that is usually + healthy rides out a short burst. A parked node is not tried while any other + node is available; a success clears the streak. - **Latency EWMA ranking per call class** (`CallClass.Cheap` point reads vs `CallClass.Heavy` feed-shaped queries, each with its own profile; alpha 0.3, trusted after 3 samples, stale after 5 min): a proven-slow node (>1s) is