akanjs 3.3.0-rc.12 → 3.3.0-rc.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/ARCHITECTURE.md +1 -0
  2. package/CHANGELOG.md +124 -0
  3. package/client/clientRuntime.ts +2 -0
  4. package/client/cookie.ts +15 -6
  5. package/client/index.ts +1 -0
  6. package/client/scriptPolicy.ts +14 -0
  7. package/common/Logger.ts +1 -1
  8. package/common/TraceContext.ts +5 -3
  9. package/common/index.ts +1 -0
  10. package/common/sessionTokenContract.ts +7 -0
  11. package/fetch/client/fetchClient.ts +1 -1
  12. package/fetch/client/httpClient.ts +15 -1
  13. package/fetch/client/wsClient.ts +10 -1
  14. package/fetch/requestStorage.ts +20 -0
  15. package/package.json +6 -1
  16. package/server/SSR_MEMORY_DIAGNOSIS.md +4 -0
  17. package/server/akanApp.ts +9 -0
  18. package/server/akanOption.ts +28 -0
  19. package/server/akanServer.ts +13 -1
  20. package/server/assetHeaders.ts +8 -3
  21. package/server/clientErrorReport.ts +191 -0
  22. package/server/clientReportId.ts +54 -0
  23. package/server/devtools/studio/studioDocument.tsx +3 -1
  24. package/server/devtools/studio/studioRoute.ts +4 -1
  25. package/server/flightSanitizeRecorded.fixture.json +36 -34
  26. package/server/forwardedError.ts +43 -0
  27. package/server/gateway/gatewayConfig.ts +5 -0
  28. package/server/gateway/gatewayHttpProxy.ts +1 -1
  29. package/server/gateway/gatewayStatus.ts +11 -1
  30. package/server/gateway/gatewayStatusPage.ts +18 -11
  31. package/server/hmr/clientReport.ts +9 -9
  32. package/server/hmr/csrDevShell.ts +7 -4
  33. package/server/htmlResultCache.ts +40 -7
  34. package/server/index.ts +1 -0
  35. package/server/lifecycle/secretEnv.ts +98 -0
  36. package/server/lifecycle/shutdownManager.ts +6 -0
  37. package/server/logging/logForwarder.ts +2 -2
  38. package/server/metrics/pubsubGauges.ts +20 -0
  39. package/server/metrics/slowStatementLog.ts +63 -0
  40. package/server/metrics/statementMetrics.ts +261 -0
  41. package/server/metrics/statementPlanCheck.ts +141 -0
  42. package/server/metrics/statementReport.ts +105 -0
  43. package/server/migration/migrationRunner.ts +13 -10
  44. package/server/oauth/OAuthErrors.ts +5 -1
  45. package/server/ops/statusAccess.ts +10 -2
  46. package/server/otlp/otlpBatcher.ts +221 -0
  47. package/server/otlp/otlpConfig.ts +185 -0
  48. package/server/otlp/otlpEncode.ts +114 -0
  49. package/server/otlp/otlpExporter.ts +98 -0
  50. package/server/otlp/otlpSampler.ts +50 -0
  51. package/server/pageFailure.ts +33 -0
  52. package/server/renderBusyResponse.ts +7 -2
  53. package/server/reportText.ts +27 -0
  54. package/server/resolver/timedQuery.ts +7 -3
  55. package/server/routeCacheTally.ts +1 -0
  56. package/server/routing/apiRouter.ts +1 -4
  57. package/server/routing/builtinRoutes.ts +3 -1
  58. package/server/routing/devSurfaces.ts +2 -0
  59. package/server/routing/roomReplay.ts +4 -0
  60. package/server/routing/serverListener.ts +13 -0
  61. package/server/routing/soloAppRoutes.ts +7 -1
  62. package/server/rscClient.tsx +6 -1
  63. package/server/rscClientChunks.ts +8 -1
  64. package/server/rscClientErrorSender.ts +77 -0
  65. package/server/rscClientErrors.ts +26 -0
  66. package/server/rscFirstRenderMemory.ts +49 -0
  67. package/server/rscFlightRenderer.ts +21 -4
  68. package/server/rscFlightStream.ts +2 -2
  69. package/server/rscRenderHandler.ts +19 -3
  70. package/server/rscRenderStats.ts +3 -0
  71. package/server/rscWorker.tsx +5 -1
  72. package/server/rscWorkerCache.ts +2 -0
  73. package/server/rscWorkerHost.ts +19 -2
  74. package/server/rscWorkerProcess.ts +12 -0
  75. package/server/rscWorkerRecycler.ts +3 -3
  76. package/server/scriptPolicy.ts +128 -0
  77. package/server/serverConfig.ts +11 -0
  78. package/server/serverMetrics.ts +16 -2
  79. package/server/ssrFromRscRenderer.tsx +29 -165
  80. package/server/ssrInlineScripts.ts +195 -0
  81. package/server/ssrTypes.ts +9 -2
  82. package/server/systemPageDocument.tsx +6 -2
  83. package/server/systemPages.tsx +9 -4
  84. package/server/webCsrSurface.ts +34 -12
  85. package/server/webDocumentRoute.ts +40 -16
  86. package/server/webRouteContext.ts +11 -4
  87. package/server/webRscRoute.ts +4 -1
  88. package/service/ipcTypes.ts +34 -0
  89. package/service/predefinedAdaptor/database.adaptor.ts +41 -9
  90. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +49 -11
  91. package/service/predefinedAdaptor/sql/driver/postgres.ts +47 -10
  92. package/service/predefinedAdaptor/sql/statementFingerprint.ts +117 -0
  93. package/service/predefinedAdaptor/sql/statementPlans.ts +71 -0
  94. package/service/predefinedAdaptor/sql/statementProbe.ts +110 -0
  95. package/service/predefinedAdaptor/sql/statementScrub.ts +149 -0
  96. package/service/predefinedAdaptor/websocket.adaptor.ts +6 -0
  97. package/signal/CrossSiteGuard.ts +5 -0
  98. package/signal/browserError.ts +24 -0
  99. package/signal/errorReporting.ts +168 -0
  100. package/signal/index.ts +2 -0
  101. package/signal/requestTrace.ts +40 -3
  102. package/signal/signalContext.ts +4 -4
  103. package/signal/spanExport.ts +137 -0
  104. package/signal/trace.ts +41 -10
  105. package/types/client/clientRuntime.d.ts +4 -0
  106. package/types/client/cookie.d.ts +4 -3
  107. package/types/client/index.d.ts +1 -0
  108. package/types/client/scriptPolicy.d.ts +4 -0
  109. package/types/common/TraceContext.d.ts +1 -0
  110. package/types/common/index.d.ts +1 -0
  111. package/types/common/sessionTokenContract.d.ts +6 -0
  112. package/types/fetch/client/httpClient.d.ts +1 -0
  113. package/types/fetch/client/wsClient.d.ts +3 -1
  114. package/types/fetch/requestStorage.d.ts +6 -0
  115. package/types/server/akanOption.d.ts +16 -1
  116. package/types/server/assetHeaders.d.ts +5 -3
  117. package/types/server/clientErrorReport.d.ts +27 -0
  118. package/types/server/clientReportId.d.ts +9 -0
  119. package/types/server/devtools/studio/studioDocument.d.ts +1 -0
  120. package/types/server/forwardedError.d.ts +13 -0
  121. package/types/server/gateway/gatewayConfig.d.ts +1 -0
  122. package/types/server/gateway/gatewayStatus.d.ts +1 -0
  123. package/types/server/hmr/clientReport.d.ts +2 -0
  124. package/types/server/hmr/csrDevShell.d.ts +3 -1
  125. package/types/server/htmlResultCache.d.ts +8 -1
  126. package/types/server/index.d.ts +1 -0
  127. package/types/server/lifecycle/secretEnv.d.ts +23 -0
  128. package/types/server/logging/logForwarder.d.ts +1 -0
  129. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  130. package/types/server/metrics/pubsubGauges.d.ts +5 -0
  131. package/types/server/metrics/slowStatementLog.d.ts +18 -0
  132. package/types/server/metrics/statementMetrics.d.ts +45 -0
  133. package/types/server/metrics/statementPlanCheck.d.ts +16 -0
  134. package/types/server/metrics/statementReport.d.ts +28 -0
  135. package/types/server/ops/statusAccess.d.ts +1 -0
  136. package/types/server/otlp/otlpBatcher.d.ts +18 -0
  137. package/types/server/otlp/otlpConfig.d.ts +25 -0
  138. package/types/server/otlp/otlpEncode.d.ts +13 -0
  139. package/types/server/otlp/otlpExporter.d.ts +18 -0
  140. package/types/server/otlp/otlpSampler.d.ts +10 -0
  141. package/types/server/pageFailure.d.ts +14 -0
  142. package/types/server/reportText.d.ts +4 -0
  143. package/types/server/resolver/timedQuery.d.ts +1 -0
  144. package/types/server/routeCacheTally.d.ts +1 -1
  145. package/types/server/routing/roomReplay.d.ts +1 -0
  146. package/types/server/routing/serverListener.d.ts +2 -0
  147. package/types/server/routing/soloAppRoutes.d.ts +2 -1
  148. package/types/server/rscClient.d.ts +1 -0
  149. package/types/server/rscClientChunks.d.ts +3 -1
  150. package/types/server/rscClientErrorSender.d.ts +8 -0
  151. package/types/server/rscClientErrors.d.ts +3 -0
  152. package/types/server/rscFirstRenderMemory.d.ts +16 -0
  153. package/types/server/rscFlightStream.d.ts +1 -1
  154. package/types/server/rscRenderStats.d.ts +2 -0
  155. package/types/server/rscWorkerCache.d.ts +2 -0
  156. package/types/server/rscWorkerProcess.d.ts +1 -0
  157. package/types/server/rscWorkerRecycler.d.ts +1 -1
  158. package/types/server/scriptPolicy.d.ts +31 -0
  159. package/types/server/serverConfig.d.ts +1 -0
  160. package/types/server/serverMetrics.d.ts +3 -1
  161. package/types/server/ssrFromRscRenderer.d.ts +2 -6
  162. package/types/server/ssrInlineScripts.d.ts +39 -0
  163. package/types/server/ssrTypes.d.ts +9 -2
  164. package/types/server/systemPageDocument.d.ts +3 -1
  165. package/types/server/systemPages.d.ts +2 -1
  166. package/types/server/webRouteContext.d.ts +4 -3
  167. package/types/service/ipcTypes.d.ts +32 -0
  168. package/types/service/predefinedAdaptor/database.adaptor.d.ts +2 -0
  169. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +3 -1
  170. package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +3 -1
  171. package/types/service/predefinedAdaptor/sql/statementFingerprint.d.ts +21 -0
  172. package/types/service/predefinedAdaptor/sql/statementPlans.d.ts +17 -0
  173. package/types/service/predefinedAdaptor/sql/statementProbe.d.ts +37 -0
  174. package/types/service/predefinedAdaptor/sql/statementScrub.d.ts +5 -0
  175. package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +3 -0
  176. package/types/signal/CrossSiteGuard.d.ts +1 -0
  177. package/types/signal/browserError.d.ts +17 -0
  178. package/types/signal/errorReporting.d.ts +27 -0
  179. package/types/signal/index.d.ts +2 -0
  180. package/types/signal/requestTrace.d.ts +3 -1
  181. package/types/signal/spanExport.d.ts +47 -0
  182. package/types/signal/trace.d.ts +8 -2
package/ARCHITECTURE.md CHANGED
@@ -173,6 +173,7 @@ Declared in [server/rscWorkerHost.ts](server/rscWorkerHost.ts).
173
173
  | `not-found` | `RscRenderFallbacks` | `RscWorker` |
174
174
  | `metrics` | `RscRenderer` | `RscWorker` |
175
175
  | `log.records` | `LogForwarder` | `RscWorker` |
176
+ | `render-error` | `RscFlightRenderer` | `RscWorker` |
176
177
  | `page-prompts.result` | `RscRenderer` | `RscWorker` |
177
178
  | `page-prompt.result` | `RscRenderer` | `RscWorker` |
178
179
  | `page-prompt.draw.result` | `RscRenderer` | `RscWorker` |
package/CHANGELOG.md CHANGED
@@ -96,6 +96,39 @@
96
96
 
97
97
  **Upgrading.** An interactive `akan code` session shows `approve? run: <command> [y/n/a]` before each shell command; `a` answers yes and stops asking about that command until the session ends. Pass `--no-ask-commands` to run them unasked as before, or `--no-ask` to stop the network questions as well. A one-shot `akan code "<prompt>"` and a sub-agent have nobody to ask, so their commands run as before. A program that drives `akan code --rpc` on the `local` profile receives an `approval` event for each command and answers it with `approve`, as it does for the `web` profile's writes; `codeAgentPresets.local(root).approval` is now `"commands"`.
98
98
 
99
+ - c7dee50: A browser's access token now lives one hour instead of seven days, and `@libs/shared` gains `session.cookieOnly`: with it on, a server-rendered web app holds its session in HttpOnly cookies alone.
100
+
101
+ - **One hour, one source.** `accessTokenSeconds` in `@libs/util/common` is the lifetime `signAccessToken` uses by default. The refresh token still lives 30 days, the session cookies keep their 30 day `Max-Age`, and an OAuth client's token still follows `oauth.accessTokenSeconds`.
102
+ - **Seven days still, for a caller that keeps its tokens itself.** A native shell, a client-rendered app on another origin, a server (`fetch.clone`) and a test keep the seven day token in this release (`WebSession.cookielessAccessTokenSeconds`), with `session.cookieOnly` on or off. The request has to ask for body tokens (the header below, or an allowlisted origin other than the server's own), carry no session cookie, and not come from a page on the server's own host. A page on the server's own host is a request whose `Origin` is that host, with or without its default port and whatever the letter case, or one the browser marks `Sec-Fetch-Site: same-origin`, as it does a same-origin `GET` that carries no `Origin`. A page on a sibling subdomain (`same-site`) is another origin's app and keeps seven days, and so does a caller that names no origin at all. Every other caller gets one hour: a server-rendered page, any request that carries a session cookie, a page load's renewal, a call sent over the websocket, and a hand-written call that does not ask. `AccountMiddleware` decides per request and the `@libs/shared` user and admin services sign with `WebSession.accessTokenExpiresAt()`.
103
+ - **Renewal.** A page refreshes two minutes before the token expires. It rechecks the expiry when its tab becomes visible, when the window takes focus, when the network comes back and once a minute, so a device that slept past the expiry renews as soon as it wakes. The page counts the token's lifetime on the server's clock, not the device's: each refresh answer measures how far the device clock is off (the token's `iat` against the moment the refresh was asked), the measurement is kept in client storage for the next page load, and a token found at load that disagrees with it is refreshed once to measure again. A device clock that is fast by less than half the token's lifetime is taken as it reads, which only renews early. An answered refresh is not asked again within a minute. New: `@libs/shared` registers `option.setSessionRefresh`, so a page load or RSC navigation that arrives with an expired access token is renewed from the request's refresh cookies before it renders. A user and an admin identity held together each come back on their own refresh cookie. An app's own `setSessionRefresh` wins over the lib's, and `setSessionRefresh(null)` turns it off.
104
+ - **Renewal that holds together.** A browser signed in as user and admin sends its two refreshes one after the other, in one tab and across tabs, so both identities survive a tab that wakes after the expiry. When one of the two sessions has ended, only that identity goes: `refreshAdminJwt` answers a session held in cookies whose admin session ended with the user identity alone, signed to the expiry it already had, and expires the admin refresh cookie; with no live user identity it ends the session as before. `refreshJwt` refuses an ended user session without changing a cookie, so the admin stays signed in. `Auth.TokenRefresh` redraws the page when a refresh leaves the session without its own identity, before the old token's expiry too. A refresh that failed is tried again after three seconds, then after 30 seconds doubling up to ten minutes, and at once when the window takes focus or the network comes back. `refreshAdminJwt` answers a refresh token presented twice within ten seconds, as `refreshJwt` does. A call whose `Authorization` token is this app's own and past its expiry is read by its session cookie instead, so a tab that has not refreshed yet follows the session a page load or another tab renewed; a token that is malformed, signed with another key, minted for another app or environment, or revoked is still answered as signed out.
105
+ - **`session.cookieOnly`** (`env.server.*`, off by default). Sign-in, SSO completion and refresh (`signinWithPassword`, `signinWithPhoneCode`, `signinWithSignToken`, `exchangeSsoCode`, `activateUser`, `activateUserWithAgreePolicies`, `refreshJwt`, `signinAdmin`, `refreshAdminJwt` and the other answers built by `makeAccessTokenResponse`) answer a server-rendered page with the session and refresh cookies and a body of `{ jwt: "", expiresAt }`: no token and no `refreshToken` field. The page's calls, file uploads, agent stream and websocket authenticate by cookie, and the page sends no `Authorization` header. One endpoint still answers an admin's page with tokens in the body: `getAccessTokenByAdmin` hands the admin another user's session, which a cookie could not carry without replacing the admin's own.
106
+ - **Who still gets tokens in the body.** A caller that holds no session cookie and asks for them with the request header `x-akan-session-tokens: body`. The framework's `fetch` sends it to its own server from a native shell, a client-rendered app, a server (`fetch.clone`) and a test, and never from a server-rendered page. A page on an allowlisted origin other than the server's own counts as asking, so a native app released before this version keeps working. Such an answer sets no session cookie.
107
+ - **Framework.** `sessionTokenContract` in `akanjs/common` names the header. `setAuth()` with no token beside a session the server holds stops `fetch` from sending one and reconnects the socket so its handshake carries the cookie. `WsClient.connect({ fresh: true })` replaces an open socket. `CrossSiteGuard.isFromOwnHost(req, url)` in `akanjs/signal` answers whether a request's `Origin` is the serving host. `@libs/shared` adds `ServerClock` (`common`) and `SessionClock` (`webkit`), which `refreshSession` and `Auth.TokenRefresh` read a token's expiry through.
108
+
109
+ **Upgrading.**
110
+
111
+ 1. For everyone: a browser's access token expires after an hour. Nothing changes in an app that mounts `Auth.User` / `Auth.Admin` (they mount `Auth.TokenRefresh`) and uses the `@libs/shared` sign-in endpoints. In an app that mounts neither, an open tab's calls and socket go anonymous an hour after sign-in until the next navigation or reload, which renews the session: mount them, or call `refreshSession` from your own code. A native app, a client-rendered app on another origin and a script that signs in through the framework's `fetch` keep seven days. A hand-written HTTP call that keeps its own token and does not send `x-akan-session-tokens: body` gets one hour, and must refresh with `refreshJwt` / `refreshAdminJwt` or sign in again. `getAccessTokenByAdmin` signs for the kind of caller the admin is: one hour for a page on the server's own host or a caller that holds a session cookie, seven days for an admin app on another origin that keeps its tokens itself.
112
+ 2. `RevokedSessions.accessTokenDays` is gone. `RevokedSessions.deniedSeconds` is how long a revoked session's tokens stay refused, and stays seven days.
113
+ 3. A deployment that answers CORS preflights from its own edge list adds `x-akan-session-tokens` to the allowed request headers: a native shell and a client-rendered app on another origin send it with every call. The chart's `ingress.cors.enabled: true` list names it now, and the app's own CORS answer already allows every header a preflight asks for.
114
+ 4. Your own endpoint that answers with `makeAccessTokenResponse` or `makeAdminAccessTokenResponse` passes the request, `makeAccessTokenResponse(token, { req })` (`.with(Req)`). With `session.cookieOnly` on, an answer that names no request never carries tokens in its body.
115
+ 5. To turn the option on, set `session: { cookieOnly: true }` in `env/env.server.<env>.ts`. Client code that reads `jwt` or `refreshToken` from a sign-in or refresh answer in a server-rendered page gets an empty string and no field: hand the answer to `setAuth` as the `@libs/shared` stores do, and read the signed-in account with `getAccount()` / `getSelf()`.
116
+ 6. Do not turn it on yet if your web pages are served as the client-rendered view on the server's own host (`?csr=true`, `/__csr`) in a browser that also holds the session cookie, if a client of yours on another origin that is not in the allowlist reads body tokens with a hand-written HTTP call, or if page code needs the token itself, for example to put it in a URL or hand it to another service. Tabs still running the code from before the deploy keep their session by cookie, but at their first refresh they lose their live subscriptions and stop scheduling refreshes, so their calls go anonymous about an hour later until a navigation or reload.
117
+ 7. In 3.5.0 `session.cookieOnly` is on unless you set it to `false`.
118
+
119
+ - c30e4df: An operator can name the slowest SQL statement and the endpoint that sent it: every statement is counted by its shape, a slow one writes one log line, a local run warns of a full table scan, and the reconnect replay and the Redis publish buffer get gauges.
120
+
121
+ - **One timing point per driver.** `BunSqliteStatement` and the Postgres statement time each statement where it is sent, and the `db:<model>.<op>` spans, the new counters and the slow-statement log all read that one point. A statement's write-turn wait (the SQLite writer turn, the Postgres pool) is timed apart from its run; a transaction's wait shows on its `BEGIN`.
122
+ - **Statements are named by fingerprint**: 12 hex characters of a SHA-1 of the text with every literal `?` and each placeholder, `IN (…)` or repeated `VALUES` list collapsed to one, so `LIMIT 10` and `LIMIT 20` are one statement. The text sent is unchanged. `StatementFingerprint` keeps at most 500 shapes and 2,000 texts, and keeps none of a text over 8 KB.
123
+ - **New series**, labelled `model` and `op` only, so their number follows the app's models and not its statements: `akan_db_statements_total`, `akan_db_statement_seconds_total`, `akan_db_statement_wait_seconds_total`, `akan_db_statement_rows_total` and the `akan_db_statement_duration_seconds` histogram (16 buckets, 0.1 ms to 10 s). A statement sent outside a model call is named by its table and verb (`memo.select`).
124
+ - **`GET /_akan/app/statements`**, behind the metrics token, answers the 20 statements with the most total time and the 20 slowest at p95, each with its normalized text, model, op, wait, rows, its top 3 senders and `sinceMs`. A process keeps 500 statements, the cheapest going first; behind a gateway each replica sends its top 50 with every report and the gateway adds them by fingerprint. These are report values, not counters: they cover the statements a process lists now, since it started or since it last admitted the statement again (`sinceMs`), so a sum can fall when a statement drops out of a list; use the `akan_db_statement*` series for rates.
125
+ - **`AKAN_LOG_SLOW_STATEMENT_MS`** (default 200; `off` or `0` turns it off) writes one `SlowStatement` warning for a statement whose wait and run reach it, at most once a minute per fingerprint, with `suppressed` for the lines held back, `sentBy` (`none` outside a request) and the request's `traceId`.
126
+ - **A query-plan check in the local dev runtime** explains a statement the first time its fingerprint runs and again after a schema change (`EXPLAIN QUERY PLAN` on SQLite, `EXPLAIN` on Postgres) and warns once, as `QueryPlan`, on a full table scan or a temporary sort. It skips tables under 1,000 rows, inserts, an unfiltered `count`, migrations, tables no model owns, the search tables and in-memory SQLite. `AKAN_QUERY_PLAN_IGNORE=<fingerprint>,…` accepts a deliberate scan; `all` turns the check off.
127
+ - **`akan_room_replay_bytes` and `akan_pubsub_buffered_messages`** gauge the frame bytes kept for reconnecting sockets and the publishes waiting for the Redis link; the metrics report carries them as `replayBytes` and `pubsubBufferedCount`. `WebSocketRedisAdaptor.bufferedCount` and the optional `WebsocketAdaptor.bufferedCount` expose the buffer depth.
128
+ - A statement's text is shown with every literal replaced by `?`: strings (dollar-quoted and escaped ones too), numbers in any form, comments and the field paths of JSON filters, so two filters that differ only by field share one entry; a quote that never closes hides the rest of the statement. A Postgres plan is logged with every quoted value replaced, array literals included. No value, id or user data reaches a series, the report or either log line.
129
+
130
+ **Upgrading.** Under `AKAN_TRACE=1` or `x-akan-debug`, a `db:<model>.<op>` span, the request line's `db` and `dbMs` and the `Server-Timing` db entries now count SQL statements, not model calls: a call that sends two statements shows two spans, up to 32 `db:` spans a request so render and cache spans keep their room, and `BEGIN` and `COMMIT` count in `db` and `dbMs` without a span (a store that sends none through the SQLite or Postgres driver still shows one per call), and `dbMs` includes the time spent waiting for the write turn or a pool connection. A dashboard reading `db` as a count of model calls reads higher. A statement taking 200 ms or longer now writes a `SlowStatement` warning; set `AKAN_LOG_SLOW_STATEMENT_MS` higher or to `off` to keep the old log. A custom `WebsocketAdaptor` needs no change; `bufferedCount` is optional.
131
+
99
132
  - 0baacae: Every dev route (`/_akan/devtools`, `/_akan/constant`, `/_akan/signal`, `/_akan/dictionary`, `/_akan/deps`, `/_akan/studio`, `/_akan/hmr`, `/_akan/ssr-dev`, `/_akan/csr-dev` and `/__rsc/manifest`) is listed once, in `akanjs/server/routing/devSurfaces`, and takes its gate, its Host check and its `akan dev --share` rule from that entry. A dev route answers only localhost, an IP address or a host the app names, on a deployed server too. A share reads the same list, so it now also refuses `/__rsc/manifest`; it still serves `/_akan/ssr-dev` and `/_akan/csr-dev`, which a shared dev page loads its modules from.
100
133
 
101
134
  The framework keeps `/_akan/`, `/__rsc` and `/__csr` for its own routes: a server now refuses at start an endpoint, a framework route or a web route under them that is neither mounted as a dev route nor on the list of production routes next to the registry, and the error names the path. A dev server starts its on-demand CSR build only for a Host a dev route answers. A share refuses `/__csr` and drops `csr=true` from a page's query, so a shared page renders on the server instead of starting that build.
@@ -109,6 +142,29 @@
109
142
  **Upgrading.** `BlobStorage` now has an `onInit` that makes this check. A subclass of your own that defines `onInit` calls `super.onInit()` first. A deployment whose data directory another user owns stops at boot with the message above: run the `chown` it names once, or let the chart's `volumePermissions` init container do it.
110
143
 
111
144
  - 5c7c6cf: `SignalSerializer.httpRoutesOf(EndpointClass, apiPrefix?)` from `akanjs/server` lists the HTTP routes an endpoint class declares: each query and mutation's `key`, `method` and `path`, the path being the one the route table mounts, with `apiPrefix` joined unless the endpoint opts out of the global prefix. It reads the class's declarations alone, so a test can check an endpoint's routes without booting an app or importing a file `akanjs/server` does not publish.
145
+ - 53bf2de: A problem in an env file is reported without the file's text, so a build or lint log holds no secret.
146
+
147
+ - **Type errors.** `akan build`, `akan typecheck` and `akan verify` report a TypeScript error in `env/env.server.*.ts` or `env/env.client.*.ts` by file, line, column and code alone. The source line and TypeScript's message are left out, because either can quote a value.
148
+ - **Lint.** `akan lint` and `akan verify` report a diagnostic in those files by file, line, column and rule, with no code frame, formatter diff or rule message. The files are still linted and formatted, and their errors still fail the run. Every other file prints as before.
149
+ - **`akan lint` output.** The `Found N errors.` lines are printed once at the end and the "Checked N files in …" line is gone. When Biome cannot read `biome.json`, the error is Biome's own explanation.
150
+
151
+ **Upgrading.** A failed `akan lint` now exits with 3, the code of a failed check, where it exited with 1. A script that tests for a non-zero exit needs no change; one that tests for exactly 1 does. To see what is wrong on a line of an env file, open the file at the position the diagnostic names.
152
+
153
+ - bbc9def: An app hands the errors its users hit to an error tracker of its choice with `option.setErrorReporter`, and with `option.setClientReport` the errors their browsers hit too.
154
+
155
+ - **`option.setErrorReporter((error, context) => …)`** gets each server 5xx, render error, uncaught exception and unhandled rejection as a real `Error` with its `cause` chain. A 4xx never reaches it. `context` is `{ source, traceId, endpoint, routeId, accountId, digest }`: `source` is `server`, `render`, `process` or `client`, `traceId` the request id the response named as `x-request-id`, `endpoint` the `<type>:<key>` that answered, and `routeId` the route pattern, never the URL. `accountId` is set on a `server` report whose request was signed in, and null on the others. A thrown value that is no `Error` arrives as one, with the value as its `cause`.
156
+ - **Each error is reported once, after the response, and a bounded number a minute.** The reporter runs off the request; one that throws or rejects is logged once and changes nothing else. One server process hands it at most 600 errors a minute, at most 10 of them uncaught exceptions and unhandled rejections, and at most 3 render errors of one request; it logs one line when it starts skipping. Await what the reporter sends: a send it does not await, failing, comes back as an unhandled rejection of the process and counts toward those 10. Before a crashed process exits, it waits up to 2 seconds for the reporter.
157
+ - **It runs in the server that answers**, the solo server or each replica. A render error in the RSC worker reaches the replica's reporter with its digest, route pattern and request id, and its cause chain to five levels. So does an error a client component raises while the server renders the page's HTML, and a page the server answers 5xx for because its worker stopped, timed out or refused. The gateway loads no `option.ts` and reports nothing. A page a full render queue turns away (`AKAN_RSC_WORKER_MAX_CONCURRENCY`) is not reported: `akan_rsc_render_refusals_total` counts it.
158
+ - **One fault can arrive more than once, with one `traceId`.** An endpoint that answers 5xx while a page renders arrives as `server` and as `render`; a server error streamed into a page arrives as `render` and, when the browser re-renders that part, as a `client` report of kind `recoverable`. Group by `traceId`.
159
+ - **`option.setClientReport({ sampleRate, perAddress, perServer })`**, off unless set, opens `/_akan/client-report` and makes each page view its sample draws send what its browser hit: a React root's uncaught, caught and recoverable errors, `window.onerror` and unhandled rejections, at most five a page view. The reporter gets each as a `BrowserError` (`akanjs/signal`) with `source: "client"` and the page view's request id; its `data` holds the kind, name, message, stack, route pattern, digest, the server's build id and the user agent. Defaults: every page view, 10 requests a minute per address (an IPv6 address counts as its /64) and 120 reports a minute per server process.
160
+ - **A report is taken only with the id its page view was given.** The page's `Server-Timing` header carries the request id with a signature over it and the half hour it was issued in, and only on a page no shared cache reuses: the default `no-cache` and a signed-in page's `private, no-cache` carry it, a `public` or switched-off `AKAN_HTML_CACHE_CONTROL` does not. The server takes that id for 30 to 60 minutes and five times. The page reads it once, when the document loads, so a report after an in-app navigation carries the first document's id with the current route pattern.
161
+ - **Which servers take a report.** `AKAN_CLIENT_REPORT_KEY` is a secret an operator may set to 32 characters or more: every server that holds it takes an id any of them gave, and a gateway passes it to its replicas unchanged. A shorter value is ignored with one warning that names the variable and never the value. Unset, the replicas behind one gateway share a key the gateway makes at start, and a server run alone uses its own: reports are then taken only behind the gateway, or by the process, that served the page. The app name and environment are signed in either way. The key has nothing to do with `AKAN_LOG_DEBUG_HEADER`.
162
+ - **What a page sends, and what the server keeps.** A report carries no cookies and no referrer. In its name, message and stack, a URL or a path loses its query string and fragment, an email address becomes `[email]`, a `Bearer …` value and a JWT become `[redacted]`, and the characters that reorder how a line displays are removed, in the page before it sends and on the server again; the server also removes terminal escapes and control characters and cuts the name, message, stack and user agent to 100, 1,000, 4,000 and 300 characters. The server keeps only a `text/plain` POST from the app's own origin, of 8 KB or less, with a signed id, within the limits; only such a report counts toward `perServer`. Every request, kept or not, is answered with the same empty 204, and the one log line a kept report writes holds only the cleaned values. The code that sends loads on a page's first error, so a page without errors downloads only the listeners, about 430 bytes compressed.
163
+ - **What the limits leave.** Each server process counts on its own, so N replicas take up to N times `perServer` and five reports per id each; visitors behind one address share its `perAddress`; and `perServer` is one budget for everyone who loaded a page, past which a minute's later reports are dropped, never queued. The cleaning knows a few shapes, not meanings: keep personal data out of error messages.
164
+ - New exports: `ClientReportSetting` from `akanjs/server`, and `BrowserError`, `BrowserErrorData`, `BrowserErrorKind`, `ErrorReporter`, `ErrorReportContext` and `ErrorReportSource` from `akanjs/signal`. The Error Handling cheatsheet has a Report Errors section, the server reference lists both options, and the runtime guideline names them.
165
+
166
+ **Upgrading.** Nothing changes until an app calls one of the options. An app that forwarded errors through a `Logger.addSink` that parsed error lines can move to `setErrorReporter`, which gets the `Error` itself; keep the sink only for lines that are not errors. A lib may set either option; the app's call wins, `setErrorReporter(null)` clears a lib's reporter and `setClientReport(false)` turns a lib's reports off. A page whose `AKAN_HTML_CACHE_CONTROL` is `public, …` sends no browser reports; pages that should send them keep `no-cache`. An app served by more than one gateway or pod sets `AKAN_CLIENT_REPORT_KEY` to the same value of 32 characters or more on each, before it turns `setClientReport` on.
167
+
112
168
  - aff1ba2: An external view opens only origins the app's config lists, in `native.desktop.externalView.allowOrigins`: a view's own `allowOrigins` narrow within them, and an origin outside them is `NOT_ALLOWED`, naming that key. `evaluate` and `initScript` need their own permission, granted by `desktop.externalView.evaluate: true`, and `sendKey` its own, granted by `desktop.externalView.sendKey: true`; both are off by default. While a view is open, opening its id again keeps its origins or narrows them, and refuses one it was not opened for; once closed, the id opens again for any origins the config lists, with the same browser profile, which belongs to the id. Origins compare exactly as the URL parser reads them: scheme, host and port, the host in punycode without a trailing dot, the default port left out, and an origin with user info refused; there are no wildcards. A view loads a URL as the URL parser writes it, so the engine never reads the page's text another way. A page opens a view only over its own window. The desktop shell checks all of this itself on macOS, Windows and Linux, and grants nothing when the build carries no permission list; on Windows a view now takes only the two DevTools calls `sendKey` and `capture` make. A top-level navigation or redirect off a view's origins stays refused, as before.
113
169
 
114
170
  A plugin manifest's `scope` can say `required: true`: then every grant of the plugin, not only `<plugin>:default`, is within its `defaultScope` unless the grant gives its own `allow`, and a scope entry naming no field is a build error. `external-view` says so.
@@ -138,6 +194,19 @@
138
194
 
139
195
  The api report lists additions only: `Device.keyboardAnimationMs`, `Device.keyboardHeight` and `Device.subscribeKeyboard`, the optional `KeyboardFrameState.avoidsContent` and `isPageKeyboardAvoidance` from `akanjs/webkit`; no upgrade step is needed. An iOS app gets the new behavior once it is built with this shell; a page that lifted its own composer by the keyboard's height under the old pan should drop that lift.
140
196
 
197
+ - 31097f2: A server can send its spans and log lines to an OpenTelemetry collector over OTLP/HTTP, with no package to add. Nothing is exported until an endpoint is set.
198
+
199
+ - **The settings are OpenTelemetry's.** `OTEL_EXPORTER_OTLP_ENDPOINT` is a base that `/v1/traces` is appended to, and `/v1/logs` once logs are asked for; `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` are full URLs. `OTEL_EXPORTER_OTLP_HEADERS` (and its `_TRACES_` / `_LOGS_` forms) holds credentials, which are never logged. `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` name the service. `OTEL_TRACES_SAMPLER` takes `always_on`, `always_off`, `traceidratio` and their `parentbased_` forms, with `OTEL_TRACES_SAMPLER_ARG` as the ratio; the default is `parentbased_always_on`, and any other value is logged once and exports no spans. `OTEL_TRACES_EXPORTER=none` or `OTEL_LOGS_EXPORTER=none` turns one signal off, `OTEL_EXPORTER_OTLP_TIMEOUT` and the `OTEL_BSP_*` / `OTEL_BLRP_*` batch settings work as in the spec, and `OTEL_SDK_DISABLED=true` turns it all off. With no endpoint set, nothing is created.
200
+ - **One sampling decision per request.** The first process to take a request over TCP, the gateway or a replica running without one, decides, and the sampled flag of `traceparent` carries the decision to the replica and on to the RSC worker, so a trace arrives whole or not at all. A caller's flag counts only when `AKAN_TRACE_ADOPT` trusts the caller. A queued job decides for itself and links the trace that enqueued it.
201
+ - **Each process sends its own**, marked with `akan.process.role` and `akan.replica.index`. The gateway sends a server span per proxied request, named by its method. A replica sends a server span named by the route pattern it matched, a span per endpoint call and a client span per database call; the spans for each stage of a call (guards, handler, serialize) are added only under `AKAN_TRACE=1` or a passed `x-akan-debug`. The RSC worker sends its page span as a child of the replica's. Attributes carry the method, the route pattern, the status and the error type, never a URL with its query, a header value, SQL text or a user id, and a failure's exception event carries its error code, not its message.
202
+ - **Log records are exported only when asked for**: with `OTEL_LOGS_EXPORTER=otlp`, or with `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` set. The generic endpoint alone sends spans only, unlike the OpenTelemetry default. A record carries the line's message as its body, its severity, its attrs, the logger's name and context, the endpoint and origin, a link it was handed, and its trace and span id when written inside a request. Attrs whose key names a secret are redacted, as for every other sink; nothing else is: the message text, and an error's message and stack where the line carries them, are sent as written. The floor is the console level the process started with.
203
+ - **The exporter stays out of a request's way.** Each signal has a bounded queue that sends by size, after the call that filled it returns, and on a timer, with at most two requests in flight. A full queue drops its oldest item and counts it. 429, 502, 503, 504 and an unreachable collector are retried with backoff until the timeout; any other status drops the batch. A failing collector is reported at most once a minute, by host. The exporter's own requests and warnings are not traced or exported. On the way out each process, the RSC worker included, sends what is queued once, for at most 1.5 s, and counts what is still unsent then as dropped; a replica under the gateway takes less when its shutdown has used up the gateway's wait. A worker that has not exited 3 s after it was stopped, as one stuck in a render, is killed.
204
+ - **A caller's trace that is not continued is linked.** Where an untrusted caller sent a `traceparent`, the first span links its trace and span id; an id from `x-request-id`, or a job's link to the trace that enqueued it, names no span and is sent as the `akan.trace.link` attribute instead.
205
+ - A sampled call records its own span and its database spans, so its request line carries `db` and `dbMs`, but it does not join the `AKAN_TRACE` metrics. `SignalTrace.exported` says whether a call was sampled for export. The `x-akan-debug` header does not change what is sampled.
206
+ - Bodies are JSON. `http/protobuf` still sends JSON, with a warning; `grpc` and compression are not supported.
207
+
208
+ **Upgrading.** Nothing changes until an `OTEL_EXPORTER_OTLP_*ENDPOINT` is set. A deployment whose environment already sets one for some other tool starts exporting on upgrade: point it at a collector that accepts OTLP/HTTP JSON, or set `OTEL_SDK_DISABLED=true` for the app. With only `OTEL_EXPORTER_OTLP_ENDPOINT` set, spans are exported and log records are not; set `OTEL_LOGS_EXPORTER=otlp` to send them too. A collector that accepts only protobuf does not work; the OpenTelemetry Collector's `otlp` receiver accepts both.
209
+
141
210
  - 4040f2d: `overlay: true` (or `"top"` / `"bottom"`) in a route's `.config()` lays the page under that side's safe area and inset instead of below them, so a translucent bar (a frosted tab bar, a glass header) has the page's content scrolling beneath it. On an overlaid side the page's padding is 0, `--akan-overlay-top` / `--akan-overlay-bottom` carry the chrome's height for the page's scrollers to pad by, the top inset's container stops painting the background, and the safe area strip is transparent and lets touches through unless the route sets its color. Until now every bar sat over a reserved band of plain background, so a backdrop blur had nothing to show.
142
211
 
143
212
  The key defaults to off, so existing pages are unchanged. The api report lists the new `PageOverlayConfig` type and one new optional property on `PageConfig` and on `CsrState`; no upgrade step is needed.
@@ -213,6 +282,61 @@
213
282
  - A guard's `request.path` no longer carries tracking parameters or the order they came in, so a redirect such as `/login?next=${request.path}` drops `utm_*` on the way: declare each parameter it must pass on with `.search()`, which keys the route on its query as requested, or set `.config({ canonicalQuery: false })` on the route.
214
283
  - On the client, `usePathCtx().location` and the router state keep the sorted query without tracking parameters until the first navigation, and `usePageLocation()` until the URL's query moves: declare the parameter with `.search()` or set `canonicalQuery: false` on the route, or read `window.location` in an effect, after hydration.
215
284
 
285
+ - 31097f2: Under `AKAN_MEMORY_LOG=1`, the RSC worker's metrics name the routes whose first render grew it most.
286
+
287
+ - `rscFirstRenderMemory` on `AkanMetricsReport`, served in `/_akan/app/metrics` beside the last render's fields, lists for each route what its first render in this worker added to `rss`, `heapUsed`, `external` and `arrayBuffers`, with the modules that render loaded. Largest RSS growth comes first, and at most 20 routes are kept. Renders running at the same time land in the same delta, so read it on a quiet replica.
288
+ - With `AKAN_MEMORY_LOG` off, a render pays one check and the field is absent. With it on, a route's first render reads process memory twice. The list lasts for the worker's life, through a pages reload.
289
+
290
+ **Upgrading.** Nothing to change. Code that copies every `AkanMetricsReport` field into a metrics backend gets one more field, an array, and only under `AKAN_MEMORY_LOG=1`.
291
+
292
+ - 6e5da23: `akan build` no longer puts the secret values of `env/env.server.<env>.ts` into the server it builds. The server reads each one from an environment variable when it starts, and says at boot which ones its deployment has not set.
293
+
294
+ - **What counts as a secret.** A string under a secret-sounding key (password, secret, token, apiKey, privateKey, accessKey, webhook, …), at any depth below it, or a URL with a password in it. It is the rule a desktop profile build already applies and the logger masks by, now also for a key named `aesKey`. Numbers, booleans, `null` and every other string stay in the build as before.
295
+ - **Where it is read from.** A variable named after the value's place in the env file, one upper snake case segment per key joined with `__`: `security.sso.google.clientSecret` is read from `SECURITY__SSO__GOOGLE__CLIENT_SECRET`. An array holding a secret is read whole from one variable holding JSON (`discord.tokens` from `DISCORD__TOKENS`). Four settings keep the names the framework already reads: `security.jwtSecret` is `JWT_SECRET`, and `database.postgres.url`, `.password` and `.insightUrl` are `POSTGRES_URL` (or `POSTGRES_URI`), `POSTGRES_PASSWORD` and `POSTGRES_INSIGHT_URL`. In `process.env.MY_VAR ?? "literal"` only the literal is replaced, so your own variable still comes first.
296
+ - **What the build writes.** `akan.env.json` and the Dockerfile gain `AKAN_ENV_NAMES`, the names the server reads (never a value), and the build prints them.
297
+ - **`akan secret-env <app> [--env <env>]`** lists each variable, its kind, its key in the env file and whether the shell sets it. With `--out <file>` it writes the values from the env file: `--format k8s` (the default) a Kubernetes Secret named by `--name` (default `<app>-env`), `--format dotenv` `NAME=value` lines that Bun's loader reads back unchanged. The file is readable by its user alone; a path under `dist/`, a path git would track, and an existing file without `--force` are refused.
298
+ - **At boot** (`AkanApp.start`, before the server is loaded or a replica is spawned) a variable that is not set is one warning naming every such variable. The framework does not stop for them, though whatever reads a value may, as a missing `JWT_SECRET` does. A JSON variable that does not parse is refused with the code `secretEnvInvalid`. A multi-line value that arrives with a backslash and an n in place of its line breaks is warned about by name.
299
+ - **What stops a build.** A secret-named key whose value the env file computes or imports rather than writes as a string stops the build before it writes anything, whatever the value's length, naming the app, the env file and the keys. After the bundles are written, the build looks in them for each secret string it left out: a long mixed one that another key of the env, the app's code or a copied file holds as well stops the build by its keys, and a short or plain one is a warning. No message prints a value.
300
+ - **Your own `process.env` reads stay yours.** A secret-named key the env file reads from `process.env.<NAME>` itself is left as that read: the build does not move it, does not stop at it, and writes no value of it, whether or not the build's shell sets the variable.
301
+ - **How the build finds the secrets.** It loads the env file, first with none of the shell's variables, so the list is the same from any shell, and with them when the file cannot load without (`process.env.HOSTS!.split(",")`). A file that loads neither way stops the build with the error's class and its file and line, never its message. Loading has a 60 second limit.
302
+ - **Unchanged:** your env files, `akan start`, `akan test`, `--profile` builds, and desktop and mobile builds, whose carried server still bundles its env file as written.
303
+
304
+ **Upgrading.** This changes how every app deploys. Before you deploy an image built with this version:
305
+
306
+ 1. Run `akan secret-env <app> --env <env>` for each app and environment you deploy. It lists the variables the server now expects. It prints names, never values.
307
+ 2. Give the server those variables.
308
+ - Kubernetes: `akan secret-env <app> --env <env> --format k8s --name <secret-name> --out <file>`, `kubectl apply -f <file>` in the app's namespace, reference the Secret from the container with `envFrom: [{ secretRef: { name: <secret-name> } }]`, then delete the file.
309
+ - Docker: `docker run -e NAME=value …`. `docker run --env-file` takes each line as written, so of a `--format dotenv` file it reads the values written without quotes and no quoted or multi-line one: pass those with `-e`.
310
+ - `bun main.js` on a host: `bun --env-file=<file> main.js` with the dotenv file, or set the variables in the service's environment. Keep the file outside `dist/apps/<app>`, which the image copies whole.
311
+ - Another platform: set them in its secret settings.
312
+ 3. Deploy. At start the server logs one warning naming any variable it is missing. The framework does not stop for it, though whatever reads the value may. Version 3.5.0 will refuse to start instead.
313
+ 4. When the new images are live, rotate those secrets and delete the old image tags. Images built before this version still contain the values.
314
+ 5. If you cannot change your deployment yet, build with `akan build <app> --inline-secrets`. The image then carries the values as before, and a variable you set still wins. When the env file cannot be loaded, this build warns and bundles the env files as written, reading no variable. Version 3.5.0 removes the flag.
315
+ 6. If a build stops with "holds … this build cannot leave out", each named key is computed or imported in the env file. Write the string at the key, or write `process.env.<NAME>` there and set that variable in the deployment.
316
+ 7. If a build stops with "holds secret values the server reads from its process env", a secret string is also somewhere the build keeps as written: the plain key the message names, the app's code, or a copied file. Take it out there, or read it there from the same variable.
317
+ 8. If a build stops with "could not be evaluated to check it for secrets", the env file throws at the named line when it is loaded. Set the variable it reads there in the build's shell, or give it a fallback.
318
+ 9. If a build stops at a key "a build would read from the environment variable …", two keys map to one variable name, or the name is one the platform or akan owns (`PWD`, `HOSTNAME`, `AKAN_*`, …). Rename the key, or write `process.env.<NAME>` there yourself.
319
+
320
+ A key file an env value points at by path (an Apple sign-in key under `private/`) is not an env value and still ships in the image: mount it instead. A key the rule does not recognise (`stripeKey`, a `salt`) stays in the build; write `process.env.<NAME>` for it.
321
+
322
+ - 48d33a7: Every HTML response now sends `Content-Security-Policy-Report-Only` with a `script-src` that names each script the framework writes, so the browser reports any other inline script a page runs. 3.5.0 will enforce the same policy.
323
+
324
+ - A server-rendered page sends `script-src 'self' 'nonce-…' 'sha256-…' 'strict-dynamic'`: the hashes name the document's bootstrap script, its flush call and the build's import map, and the nonce the scripts React writes to reveal a streamed boundary. A page replayed from the HTML cache carries no nonce and lists the hash of each of those scripts instead; a response names at most 32 hashes, which keeps the header under 2 KB (a proxy in front reads a response's headers into one buffer, 4 KB in nginx unless configured), so a page whose replay would need more is rendered each time, answers `X-Akan-Cache: BYPASS` with `X-Akan-Cache-Reason: script-hashes`, counts under that reason in `akan_route_cache_lookups_total` and is warned about once per route. `akan start` adds `'unsafe-eval'` and runs its dev scripts under the nonce.
325
+ - The document's per-request values (route state, dictionary URL, import map key, API and WebSocket prefixes) and its Flight chunks are now `<script type="application/json">` blocks that the static bootstrap script reads, where they used to be script text. The bootstrap script is the first element of `<head>`, and the client entry module is added by that script once the document ends, where it used to be a `<script type="module">` tag.
326
+ - The CSR document, the system pages, Akan Studio, the gateway's status page and the OAuth error page send the header too, each naming its own script by hash. The OAuth error page now also carries the headers every other HTML page has (`Content-Security-Policy: frame-ancestors 'self'; base-uri 'self'`, `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy`).
327
+ - `scriptHashes("sha256-…")` and `scriptNonce()` from `akanjs/client` let a `.head()` name its own inline script: by hash for a constant snippet, which keeps the page cacheable, or by the response's nonce, which makes the page dynamic. Hashes a page declares past the 32 a response names are left out, with one warning per route.
328
+ - `AKAN_CONTENT_SECURITY_POLICY_SCRIPT_SRC` adds source expressions to every response's `script-src`, such as `'wasm-unsafe-eval'` for a page that compiles WebAssembly or the hash of a snippet every page carries.
329
+ - `AKAN_CONTENT_SECURITY_POLICY_REPORT_ONLY=off` drops the header, and any other value is sent in its place as written. `AKAN_CONTENT_SECURITY_POLICY_REPORT_URI` adds `report-uri` and `report-to` with a `Reporting-Endpoints` header. `AKAN_CONTENT_SECURITY_POLICY` works as before and does not change the report-only header.
330
+
331
+ **Upgrading.** The header only reports in 3.4; what changes for a page is its source and when `load` fires, both below. Load your pages with the browser console open. For each `[Report Only]` line about an inline script of your own, either call `scriptHashes()` in that page's or layout's `.head()` with the hash the line prints, or pass `nonce={scriptNonce()}` to the `<script>`; a `<script src>` written in JSX needs the nonce. Move an `onclick="…"` attribute or a `javascript:` URL into a component's handler. A page that compiles WebAssembly is reported as `wasm-eval`: set `AKAN_CONTENT_SECURITY_POLICY_SCRIPT_SRC="'wasm-unsafe-eval'"`. In the page source, the route state, the dictionary URL and each Flight chunk are now `<script type="application/json">` blocks, and the markup has no `<script type="module">` tag for the client entry: code or a test that read `self.__RSC_PUSH__(…)` text or looked for that tag finds neither. Because the bootstrap script adds the entry module, `DOMContentLoaded` and `load` no longer wait for it and can fire before any client code runs (on a cached docs page, `load` at 31 ms and the entry at 63 ms). A `load` or `DOMContentLoaded` listener that client code adds without checking `document.readyState` may never be called:
332
+
333
+ ```ts
334
+ if (document.readyState === "complete") onLoad();
335
+ else window.addEventListener("load", onLoad, { once: true });
336
+ ```
337
+
338
+ (`document.readyState !== "loading"` for `DOMContentLoaded`.) A browser test that clicks or types as soon as navigation reports `load` can meet a page that has not hydrated: wait for something only the hydrated page does, such as the result of the action under a retrying assertion or a marker a client component sets in an effect, instead of `load`. If a proxy or CDN in front of the app sets its own `Content-Security-Policy-Report-Only`, set `AKAN_CONTENT_SECURITY_POLICY_REPORT_ONLY=off` or let the app's header through.
339
+
216
340
  - 4225827: A trace's spans say where they ran and when, database calls are spans of their own, and a developer can read a call's timing from the response.
217
341
 
218
342
  - `SpanRecord` gains `id`, `parentId`, `startMs` and optional `attrs` beside `name` and `durationMs`. The call's own span is `total`, with the trace's `spanId` as its id and its caller's span as its parent; it is recorded even when the call ran past the 64-span limit.
@@ -38,6 +38,8 @@ type RuntimeErr = {
38
38
 
39
39
  type RuntimeWs = {
40
40
  connected: boolean;
41
+ state?: "connecting" | "open" | "closed" | "gaveUp";
42
+ connect?: (option?: { fresh?: boolean }) => void;
41
43
  on: (event: string, handler: (...args: unknown[]) => void) => void;
42
44
  off: (event: string, handler: (...args: unknown[]) => void) => void;
43
45
  };
package/client/cookie.ts CHANGED
@@ -153,25 +153,34 @@ export interface GetOption {
153
153
  unauthorize: string;
154
154
  }
155
155
  interface SetAuthOption {
156
- jwt: string;
156
+ jwt?: string | null;
157
157
  }
158
158
  const announceAuth = () => {
159
159
  if (typeof window !== "undefined") window.dispatchEvent(new Event("akan:auth"));
160
160
  };
161
+
162
+ const reopenSocket = () => {
163
+ const { ws } = fetch;
164
+ if (ws?.state === "open" || ws?.state === "connecting") ws.connect?.({ fresh: true });
165
+ };
161
166
  /** Sets the active auth token on fetch, then keeps it where the next launch finds it: client storage on a CSR client,
162
- * the session cookie elsewhere unless the server already holds it there (`SessionCookie.issue`). */
163
- export const setAuth = ({ jwt }: SetAuthOption) => {
164
- fetch.setJwt(jwt);
167
+ * the session cookie elsewhere unless the server already holds it there (`SessionCookie.issue`). An answer with no
168
+ * token beside a session the server holds is a cookie-only session: fetch sends no token and the socket reconnects. */
169
+ export const setAuth = ({ jwt }: SetAuthOption = {}) => {
170
+ const token = jwt ?? "";
171
+ const cookieOnly = !token && serverHoldsSession();
172
+ fetch.setJwt(cookieOnly ? null : token);
165
173
 
166
- if (isCsrClient()) void secretStorage.setItem(storedAuthTokenKey(), jwt);
174
+ if (isCsrClient()) void secretStorage.setItem(storedAuthTokenKey(), token);
167
175
  else {
168
176
 
169
177
  void secretStorage.removeItem(storedAuthTokenKey());
170
- if (!serverHoldsSession()) setCookie(authTokenKey(), jwt);
178
+ if (!serverHoldsSession()) setCookie(authTokenKey(), token);
171
179
  }
172
180
 
173
181
  for (const key of retiredAuthTokenKeys()) removeCookie(key);
174
182
  void secretStorage.removeItem(legacyAuthTokenKey);
183
+ if (cookieOnly) reopenSocket();
175
184
  announceAuth();
176
185
  };
177
186
 
package/client/index.ts CHANGED
@@ -218,6 +218,7 @@ export {
218
218
  prefetchRsc,
219
219
  refreshRsc,
220
220
  } from "./rscNavigation";
221
+ export { scriptHashes, scriptNonce } from "./scriptPolicy";
221
222
  export { sharedContext } from "./sharedContext";
222
223
  export { secretStorage, storage } from "./storage";
223
224
  export { type TransitionType, transitionTypes } from "./transitionTypes";
@@ -0,0 +1,14 @@
1
+ import { getEnv } from "akanjs/base";
2
+ import { addRequestScriptHashes, scriptNonce as serverScriptNonce } from "akanjs/fetch";
3
+
4
+ /** The nonce an inline `<script>` a `.head()` or a layout writes needs under the script policy; server only. */
5
+ export const scriptNonce = (): string | undefined => {
6
+ if (getEnv().side !== "server") return undefined;
7
+ return serverScriptNonce();
8
+ };
9
+
10
+ /** Names inline scripts of this page by hash (`sha256-…`) in the response's script policy; call it from `.head()`. */
11
+ export const scriptHashes = (...hashes: string[]): void => {
12
+ if (getEnv().side !== "server") return;
13
+ addRequestScriptHashes(hashes);
14
+ };
package/common/Logger.ts CHANGED
@@ -91,7 +91,7 @@ const consoleMethodMap = {
91
91
  const ansiPattern = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
92
92
 
93
93
  const secretKey =
94
- /password|passwd|passphrase|^pass$|pwd|token|jwt|authorization|cookie|secret|api[-_]?key|private[-_]?key|access[-_]?key|auth[-_]?key|hash[-_]?key|(?:signing|encryption|master|session)[-_]?key|webhook|credential|dsn$|connection[-_]?string|iap[-_]?verify|service[-_]?account/i;
94
+ /password|passwd|passphrase|^pass$|pwd|token|jwt|authorization|cookie|secret|api[-_]?key|aes[-_]?key|private[-_]?key|access[-_]?key|auth[-_]?key|hash[-_]?key|client[-_]?report[-_]?key|(?:signing|encryption|master|session)[-_]?key|webhook|credential|dsn$|connection[-_]?string|iap[-_]?verify|service[-_]?account/i;
95
95
 
96
96
  const credWord = /[cC]reds?(?![a-z])|CREDS?(?![A-Z])/;
97
97
 
@@ -9,6 +9,7 @@ export interface AdoptedTrace {
9
9
  parentSpanId: string | null;
10
10
  sampled: boolean;
11
11
  link: string | null;
12
+ linkSpanId?: string | null;
12
13
  }
13
14
 
14
15
  type OutboundReader = () => string | undefined;
@@ -72,7 +73,7 @@ export class TraceContext {
72
73
  const parent = TraceContext.parseTraceparent(traceparent);
73
74
  const inbound = parent?.traceId ?? TraceContext.parseId(requestId);
74
75
  if (!inbound) return TraceContext.#minted(null);
75
- if (!isTrustedPeer()) return TraceContext.#minted(inbound);
76
+ if (!isTrustedPeer()) return TraceContext.#minted(inbound, parent?.spanId ?? null);
76
77
  return {
77
78
  traceId: inbound,
78
79
  parentSpanId: parent?.spanId ?? null,
@@ -81,8 +82,9 @@ export class TraceContext {
81
82
  };
82
83
  }
83
84
 
84
- static #minted(link: string | null): AdoptedTrace {
85
- return { traceId: TraceContext.mintTraceId(), parentSpanId: null, sampled: false, link };
85
+ static #minted(link: string | null, linkSpanId: string | null = null): AdoptedTrace {
86
+ const minted = { traceId: TraceContext.mintTraceId(), parentSpanId: null, sampled: false, link };
87
+ return linkSpanId ? { ...minted, linkSpanId } : minted;
86
88
  }
87
89
 
88
90
  static registerOutboundReader(reader: OutboundReader | null) {
package/common/index.ts CHANGED
@@ -249,6 +249,7 @@ export {
249
249
  validateSubRoutePageKey,
250
250
  } from "./routeConvention";
251
251
  export { type SessionCookieDuplicate, SessionCookies } from "./sessionCookies";
252
+ export { sessionTokenContract } from "./sessionTokenContract";
252
253
  export { sleep } from "./sleep";
253
254
  export { getBasePathFromPathname, parseBasePaths, parseSubRouteHosts, resolveSubRouteHosts } from "./subRoute";
254
255
  export { TrustedProxy } from "./TrustedProxy";
@@ -0,0 +1,7 @@
1
+
2
+ export const sessionTokenContract = {
3
+ header: "x-akan-session-tokens",
4
+ body: "body",
5
+ makeHeaders: (): Record<string, string> => ({ "x-akan-session-tokens": "body" }),
6
+ asksForBody: (headers: Headers): boolean => headers.get("x-akan-session-tokens") === "body",
7
+ } as const;
@@ -322,7 +322,7 @@ export class FetchClient {
322
322
  }
323
323
  #makeRequestHeaders(option?: FetchPolicy): Record<string, string> {
324
324
  const clientIp = this.#clientIp ? { "x-real-ip": this.#clientIp } : this.#forwardedClientIp(option);
325
- return { ...this.#makeAuthHeaders(option), ...clientIp, ...HttpClient.traceHeaders() };
325
+ return { ...this.#makeAuthHeaders(option), ...clientIp, ...HttpClient.callerHeaders(this.#ownOrigin(option)) };
326
326
  }
327
327
 
328
328
  #forwardedClientIp(option?: FetchPolicy): Record<string, string> {
@@ -1,4 +1,5 @@
1
- import { AbortSignals, Backoff, isRecord, Logger, type RetryPolicy } from "akanjs/common";
1
+ import { getEnv } from "akanjs/base";
2
+ import { AbortSignals, Backoff, isRecord, Logger, type RetryPolicy, sessionTokenContract } from "akanjs/common";
2
3
  import type { HttpMutationMethod, SerializedArg } from "akanjs/signal";
3
4
  import { TraceContext } from "../../common/TraceContext";
4
5
  import {
@@ -76,6 +77,19 @@ export class HttpClient {
76
77
  const traceparent = TraceContext.outbound();
77
78
  return traceparent ? { traceparent } : {};
78
79
  }
80
+ static callerHeaders(ownOrigin: boolean): Record<string, string> {
81
+ const asksForTokens = ownOrigin && !HttpClient.#isServerRenderedPage();
82
+ return { ...HttpClient.traceHeaders(), ...(asksForTokens ? sessionTokenContract.makeHeaders() : {}) };
83
+ }
84
+ static #isServerRenderedPage() {
85
+ try {
86
+ const env = getEnv();
87
+ return env.side === "client" && env.renderMode !== "csr";
88
+ } catch {
89
+
90
+ return false;
91
+ }
92
+ }
79
93
  #resolveUrl(url: string, options: FetchOptions) {
80
94
  return `${(options.baseUrl ?? this.baseUrl).replace(/\/$/, "")}${url}`;
81
95
  }
@@ -171,8 +171,17 @@ export class WsClient {
171
171
  if (this.#outbox.length > 0 || this.#roomSubscribeMap.size > 0) this.connect();
172
172
  }
173
173
 
174
- connect() {
174
+ connect({ fresh = false }: { fresh?: boolean } = {}) {
175
175
  this.#connectRequested = true;
176
+ if (fresh && this.#ws) {
177
+ const stale = this.#ws;
178
+ this.#ws = null;
179
+ this.connected = false;
180
+ this.#stopHeartbeat();
181
+ stale.onopen = null;
182
+ stale.onmessage = null;
183
+ stale.close();
184
+ }
176
185
  if (this.#ws && this.#ws.readyState !== WebSocket.CLOSED) return;
177
186
  this.logger.debug(`Connecting to ${this.url}`);
178
187
  this.#destroyed = false;
@@ -34,6 +34,7 @@ export interface AkanRequestStore {
34
34
  dynamicUsage: AkanDynamicUsage;
35
35
  needsBrowser?: boolean;
36
36
  renderSearch?: string;
37
+ scriptHashes?: Set<string>;
37
38
  }
38
39
 
39
40
  export interface RequestStorage {
@@ -96,6 +97,25 @@ export function getRequestTheme(): AkanTheme | undefined {
96
97
  return getRequestStore()?.theme;
97
98
  }
98
99
 
100
+ /** The request header a document render carries the response's script nonce in; a navigation's render has none. */
101
+ export const SCRIPT_NONCE_HEADER = "x-akan-script-nonce";
102
+
103
+ export function scriptNonce(): string | undefined {
104
+ return headers().get(SCRIPT_NONCE_HEADER);
105
+ }
106
+
107
+ export function addRequestScriptHashes(hashes: string[]): void {
108
+ const store = getRequestStore();
109
+ if (!store) return;
110
+ store.scriptHashes ??= new Set();
111
+ for (const hash of hashes) store.scriptHashes.add(hash);
112
+ }
113
+
114
+ export function getRequestScriptHashes(): string[] | undefined {
115
+ const hashes = getRequestStore()?.scriptHashes;
116
+ return hashes?.size ? [...hashes] : undefined;
117
+ }
118
+
99
119
  export function setRequestRenderSearch(search: string): void {
100
120
  const store = getRequestStore();
101
121
  if (store) store.renderSearch = search;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.3.0-rc.12",
3
+ "version": "3.3.0-rc.13",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -412,6 +412,11 @@
412
412
  "import": "./server/lifecycle/buildEnv.ts",
413
413
  "default": "./server/lifecycle/buildEnv.ts"
414
414
  },
415
+ "./server/lifecycle/secretEnv": {
416
+ "types": "./types/server/lifecycle/secretEnv.d.ts",
417
+ "import": "./server/lifecycle/secretEnv.ts",
418
+ "default": "./server/lifecycle/secretEnv.ts"
419
+ },
415
420
  "./server/artifact/modulePreloadPlan": {
416
421
  "types": "./types/server/artifact/modulePreloadPlan.d.ts",
417
422
  "import": "./server/artifact/modulePreloadPlan.ts",
@@ -35,6 +35,10 @@ Key fields:
35
35
  the same for the worker. `jscExtra` is off-heap, mostly typed-array backing stores.
36
36
  - `rscRenderCount`, `rscInFlightRenderCount`: detect request lifecycle leaks.
37
37
  - `rscLoadedRouteModuleCount`, `rscRouteModuleCacheHits`, `rscRouteModuleCacheMisses`: detect route module warm-up.
38
+ - `rscFirstRenderMemory`, only under `AKAN_MEMORY_LOG=1`: per route, what its first render in this worker grew
39
+ `rss`, `heapUsed`, `external` and `arrayBuffers` by, and the modules it loaded, largest RSS first, at most 20
40
+ routes. Renders running at the same time land in the same delta, so read it on a quiet pod. It starts with the
41
+ worker and is not cleared by a pages reload.
38
42
  - `ssrChunkRegistrySize`, `ssrChunkLoadCount`: full-document SSR client chunk loading. **`…RegistrySize` counts
39
43
  keys, not bytes** — evicting does not unload the module, so it can never fall on its own.
40
44
  - `httpHtmlCacheEntries` / `httpHtmlCacheBytes`, `rscResultCacheEntries` / `rscResultCacheBytes`,
package/server/akanApp.ts CHANGED
@@ -16,11 +16,13 @@ import { GatewayStatus } from "./gateway/gatewayStatus";
16
16
  import { GatewayWebSocketRelay, type GatewayWsData } from "./gateway/gatewayWebSocketRelay";
17
17
  import { ListeningPort } from "./gateway/listeningPort";
18
18
  import { isPortInUseError } from "./lifecycle/portInUse";
19
+ import { SecretEnv } from "./lifecycle/secretEnv";
19
20
  import { LogStreamRoute } from "./logging/logStreamRoute";
20
21
  import { AppInfo } from "./ops/appInfo";
21
22
  import type { OpsHost } from "./ops/opsCommand";
22
23
  import type { OpsRoute } from "./ops/opsRoute";
23
24
  import { StatusAccess } from "./ops/statusAccess";
25
+ import { OtlpExporter } from "./otlp/otlpExporter";
24
26
  import { ProcessMetricsCollector } from "./processMetricsCollector";
25
27
  import { DevSurfacePolicy } from "./routing/devSurfacePolicy";
26
28
  import { DevSurfaces } from "./routing/devSurfaces";
@@ -100,6 +102,7 @@ export class AkanApp {
100
102
  await OpsCommand.run(process.argv.slice(3), { importServer: async () => await this.#importServer() }),
101
103
  );
102
104
  }
105
+ SecretEnv.check(this.logger);
103
106
  if (this.#config.solo) return await this.#startSolo();
104
107
  if (SelfExec.carried)
105
108
  throw new AkanError(
@@ -107,6 +110,7 @@ export class AkanApp {
107
110
  "A desktop app's server runs in one process, and this one was asked for a gateway and replicas, which would start with the `bun` on the user's PATH: by `replica` or `solo: false` in main.ts, or by AKAN_SOLO=false, an AKAN_REPLICA other than one traffic replica, or AKAN_COMMAND_TYPE=start in its env. Leave them out of the app the desktop build carries.",
108
111
  );
109
112
  Logger.role = "gateway";
113
+ OtlpExporter.install();
110
114
  await this.#supervisor.prepareRuntimeDir();
111
115
  await this.#logging.start();
112
116
  await this.#startOps();
@@ -169,6 +173,7 @@ export class AkanApp {
169
173
  this.#server = null;
170
174
  ListeningPort.record(this, undefined);
171
175
  await this.#supervisor.stopAll(signal);
176
+ await OtlpExporter.shutdown();
172
177
  await this.#logging.stop();
173
178
  this.#resolveStopped?.();
174
179
  this.#resolveStopped = null;
@@ -253,6 +258,10 @@ export class AkanApp {
253
258
  "/_akan/app/metrics",
254
259
  (req, client) => this.#statusAccess.metrics(req, () => this.#status.metricsStatus(), client),
255
260
  ],
261
+ [
262
+ "/_akan/app/statements",
263
+ (req, client) => this.#statusAccess.statements(req, () => this.#status.statementsStatus(), client),
264
+ ],
256
265
  [LogStreamRoute.path, (req, client) => this.#logging.stream?.handle(req, client) ?? null],
257
266
  ["/_akan/bench/ping", () => new Response("ok")],
258
267
  [AppInfo.publicPath, () => AppInfo.handlePublic()],
@@ -5,11 +5,13 @@ import type {
5
5
  AgentRequestPolicy,
6
6
  AgentUsageHook,
7
7
  CrossSiteOption,
8
+ ErrorReporter,
8
9
  GuardCls,
9
10
  MiddlewareCls,
10
11
  RateLimitSetting,
11
12
  } from "akanjs/signal";
12
13
  import type { McpServerOption } from "./akanServer";
14
+ import type { ClientReportSetting } from "./clientErrorReport";
13
15
  import type { WebProxyRegistration } from "./proxy";
14
16
  import { HostBasePathWebProxy, LocaleWebProxy } from "./proxy";
15
17
  import type { SessionRefreshHook } from "./sessionRefresh";
@@ -36,6 +38,8 @@ export class AkanOption<Env extends BackendEnv = BackendEnv> {
36
38
  #getRateLimit: ((env: Env) => RateLimitSetting | false) | undefined;
37
39
  #liveRoomLimit: LiveRoomLimitSetting | undefined;
38
40
  #sessionRefresh: SessionRefreshHook | null | undefined;
41
+ #errorReporter: ErrorReporter | null | undefined;
42
+ #clientReport: ClientReportSetting | boolean | undefined;
39
43
  use(fnOrObject: ((env: Env) => Record<string, PromiseOrObject<unknown>>) | Record<string, PromiseOrObject<unknown>>) {
40
44
  if (typeof fnOrObject === "function")
41
45
  this.#getUses.push(fnOrObject as (env: Env) => Record<string, PromiseOrObject<unknown>>);
@@ -123,6 +127,24 @@ export class AkanOption<Env extends BackendEnv = BackendEnv> {
123
127
  this.#sessionRefresh = hook;
124
128
  return this;
125
129
  }
130
+ /**
131
+ * Gets each server 5xx, render error, uncaught exception and unhandled rejection of a server process, and each browser
132
+ * report `setClientReport` lets in, once, after the response. A failing reporter is logged once and changes nothing
133
+ * else. The app's wins over its libs'; `null` clears a lib's.
134
+ */
135
+ setErrorReporter(reporter: ErrorReporter | null) {
136
+ this.#errorReporter = reporter;
137
+ return this;
138
+ }
139
+ /**
140
+ * Opens `/_akan/client-report`, where a page's script sends the errors its browser hit, and makes the page send them:
141
+ * `sampleRate` of page views (1), requests per address (10) and reports per server (120) a minute. Off unless set;
142
+ * `false` turns a lib's off, and the app's wins.
143
+ */
144
+ setClientReport(setting: ClientReportSetting | boolean = true) {
145
+ this.#clientReport = setting;
146
+ return this;
147
+ }
126
148
  /** Injected into the `LlmAdaptorRole` adaptor as the `llmOption` use; merged in mount order, the app's last. */
127
149
  setLlm<Option extends LlmOption>(llmOrFn: Option | ((env: Env) => Option)) {
128
150
  if (typeof llmOrFn === "function") this.#getLlms.push(llmOrFn);
@@ -192,6 +214,12 @@ export class AkanOption<Env extends BackendEnv = BackendEnv> {
192
214
  getSessionRefresh(): SessionRefreshHook | null | undefined {
193
215
  return this.#sessionRefresh;
194
216
  }
217
+ getErrorReporter(): ErrorReporter | null | undefined {
218
+ return this.#errorReporter;
219
+ }
220
+ getClientReport(): ClientReportSetting | boolean | undefined {
221
+ return this.#clientReport;
222
+ }
195
223
  getLlm(env: Env): LlmOption {
196
224
  return Object.assign({}, ...this.#getLlms.map((fn) => fn(env)));
197
225
  }