@ocap/chain-node 0.0.0-stage → 1.32.0

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.
package/README.md CHANGED
@@ -1,3 +1,235 @@
1
- # Temporary Holding Version
1
+ # `@ocap/chain-node`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@ocap/chain-node` is the single canonical runtime assembly layer for OCAP blockchain nodes (`validator`, `standby`, keyless `follower`, and `hotstuff`). It owns deterministic storage boot, snapshot trust-anchor bootstrap, role runtime wiring, Express HTTP + WebSocket mounting, fail-closed `NODE_HALTED` enforcement, and ordered graceful shutdown.
4
+
5
+ For full architectural rationale and design history, see [`docs/chain-node-design.md`](../../docs/chain-node-design.md).
6
+
7
+ ## Responsibilities & Boundaries
8
+
9
+ ### Owned by `@ocap/chain-node`
10
+
11
+ - **Storage & single-writer lease lifecycle**: `SqliteLedgerStorage` (`SqliteSingleWriterLease`), `SqliteTrustedStorage` (`trusted.sqlite`), `SqliteStateDB` (`statedb.sqlite`), `SqliteIndexDB` (`indexdb.sqlite`), `NodePreferencesManager`, `INodeMaintenanceController`, and `Blacklist` (`filter.json`).
12
+ - **Role-specific consensus & replication runtimes**:
13
+ - Single-validator `Ledger` checkpointing (`periodicTimer` + witness quorum policy).
14
+ - Follower snapshot bootstrap (`prepareFollowerDataDirectory`), `FollowerSyncService`, single-hop `LeaderRouter` (`writePolicy: 'forward'`), and monotonic follower high-water mark persistence.
15
+ - Multi-validator `HotStuffNodeRuntime` + `SqliteHotStuffStateStore` with split consensus listener isolation (`/consensus` returns `404` on the public HTTP port).
16
+ - **`OCAPResolver` orchestration**: Deferred initialization (`deferInitialize: true`), keyless follower `statedb` chain-config rehydration without mutating `process.env`, and Promise-based startup validation (never calling `process.exit()` from library code).
17
+ - **HTTP + WebSocket server assembly**: CORS, shutdown fence (`503` + `Connection: close`), active HTTP response tracking, Socket.IO (`createSocketHandler`), REST `/api` (`createAPIHandler`), `/node` (`createNodeDashboardRouter`), optional `/dashboard` and `/node/explorer`, and `/` GraphQL (`createHttpHandler`, serving `/`, `/api`, and `/api/gql`).
18
+ - **Fail-closed `NODE_HALTED` gate**: Blocks all non-diagnostic GraphQL operations (`CustomError('NODE_HALTED', 'Chain node is halted fail-closed')`) and returns HTTP `503` (`{ code: 'NODE_HALTED', halted: true }`, `Cache-Control: no-store`) on `/api/ledger/status`, `/api/follower/status`, and non-diagnostic `/api/*` data endpoints whenever the underlying runtime halts.
19
+ - **LIFO partial-boot rollback & 9-step reverse graceful shutdown**.
20
+
21
+ ### Explicitly Kept Out of `@ocap/chain-node`
22
+
23
+ - **`.env` file loading & implicit `process.env` reads**: `startChainNode` never reads `process.env` for configuration (the sole environment check is rejecting `testHooks` when `process.env.NODE_ENV === 'production'`). Callers parse env vars explicitly or pass an env dictionary into pure helpers (`roleConfigFromEnv(env)`, `leaseConfigFromEnv(env)`).
24
+ - **Secret-key / mnemonic derivation**: Callers construct `ChainNodeSignerConfig` (`ed25519`, `secp256k1`, or `eth`) before calling `startChainNode`.
25
+ - **Pre-Resolver immutable chain-config merging**: Application-specific `applyImmutable` / `checkChainImmutables` logic (for example `bridge/ocap-node/src/immutable.ts`) runs before passing `chainConfig` into `startChainNode`.
26
+ - **Application-specific HTTP/admin routes**: Mounted by the caller via `profile.configureApp(app, ctx)`.
27
+ - **Telemetry SDKs & optional index pruning packages**: `@sentry/*` stays in application entrypoints; `@ocap/indexdb-prune` is injected via `profile.maintenance.pruneIndexDbFn` rather than hard-depended on by `@ocap/chain-node`.
28
+ - **Global process signal handlers**: `startChainNode` does not bind `process.on('SIGINT' | 'SIGTERM')` automatically; CLI entrypoints opt in via `installProcessSignalHandlers(node, options?)`.
29
+
30
+ ---
31
+
32
+ ## Exports & Configuration Surface
33
+
34
+ ### Main Entrypoint (`@ocap/chain-node`)
35
+
36
+ ```ts
37
+ import {
38
+ installProcessSignalHandlers,
39
+ leaseConfigFromEnv,
40
+ roleConfigFromEnv,
41
+ startChainNode,
42
+ type ChainNodeRoleConfig,
43
+ type ChainProfile,
44
+ type RunningChainNode,
45
+ } from '@ocap/chain-node';
46
+ ```
47
+
48
+ - `startChainNode(profile)` / `startChainNode({ profile, testHooks })`: Boots a chain node and resolves to a `RunningChainNode` handle (`endpoint`, `rpcUrl`, `wsUrl`, `port`, `host`, `chainId`, `role`, `nodeId`, `dataDir`, `proposerDid`, `proposerPublicKey`, `signatureKeyType`, `app`, `server`, `ledger`, `ledgerStorage`, `statedb`, `trustedStorage`, `indexdb`, `resolver`, `followerSync`, `hotstuffRuntime`, `preferencesManager`, `maintenanceController`, `ledgerHealth()`, `advanceClock?(seconds)`, `restart(nextProfile?)`, `stop()`).
49
+ - `roleConfigFromEnv(env, { signer? })`: Pure parser mapping explicit `env` keys (`CHAIN_ROLE` / `CHAIN_MODE`, `CONSENSUS_MODE`, `CHAIN_CONSENSUS_SK` + `CHAIN_CONSENSUS_PROPOSER` + `CHAIN_CONSENSUS_KEY_TYPE`, `CHAIN_WRITE_POLICY`, `ALLOW_PRIVATE_PEER_URLS`, `DISALLOW_KEYLESS_CASCADED_UPSTREAM`, `FOLLOWER_POLL_INTERVAL_MS`, `FOLLOWER_MAX_SYNC_LAG`, `FOLLOWER_MAX_UPSTREAM_STALE_MS`, `CONSENSUS_BIND_HOST`, `CONSENSUS_PORT`, `HOTSTUFF_VALIDATORS`, `HOTSTUFF_QUORUM_THRESHOLD`, witness variables) into a typed `ChainNodeRoleConfig`.
50
+ - `leaseConfigFromEnv(env)`: Pure parser mapping explicit `env` keys (`LEDGER_WRITER_LEASE`, `LEDGER_WRITER_LEASE_TTL_MS`, `LEDGER_WRITER_LEASE_STARTUP_WAIT_MS`, `CHAIN_LEASE_HOLDER_ID`) into `ILedgerLeaseOptions | false`.
51
+ - `installProcessSignalHandlers(node, options?)`: Attaches idempotent `SIGTERM`/`SIGINT` handlers that invoke `node.stop()` and returns an `uninstall()` disposer.
52
+
53
+ ### `ChainProfile` & Node Roles
54
+
55
+ ```ts
56
+ interface ChainProfileBase {
57
+ nodeId?: string; // defaults to persisted <dataDir>/.node-id
58
+ dataDir: string;
59
+ http: {
60
+ host?: string; // defaults to '127.0.0.1'
61
+ port: number; // 0 binds an OS-assigned ephemeral port (preserved across node.restart())
62
+ corsOrigins?: string | string[] | boolean;
63
+ drainTimeoutMs?: number; // HTTP active-response drain timeout on stop() (default: 5000ms)
64
+ enableDashboard?: boolean;
65
+ enableExplorer?: boolean;
66
+ explorerDistDir?: string;
67
+ enableAccessLog?: boolean;
68
+ adminEnv?: Record<string, string | undefined>;
69
+ onGraphqlError?: (err: Error & { originalError?: Error }) => void;
70
+ };
71
+ storage?: ChainProfileBase['storage'];
72
+ checkpoint?: {
73
+ batchSize?: number;
74
+ timeoutMs?: number;
75
+ auto?: boolean;
76
+ periodicTimer?: boolean;
77
+ timerIntervalMs?: number;
78
+ };
79
+ da?: ChainProfileBase['da'];
80
+ blacklist?: ChainProfileBase['blacklist'];
81
+ txQueue?: ChainProfileBase['txQueue'];
82
+ maintenance?: ChainProfileBase['maintenance'];
83
+ validateTokenConfig?: boolean;
84
+ logger?: IPipelineLogger;
85
+ configureApp?: (app: Express, ctx: ChainAppHookContext) => void | Promise<void>;
86
+ }
87
+ ```
88
+
89
+ | Role (`role.kind`) | Signer | `chainConfig` | Write Behavior & Runtime Semantics |
90
+ | --- | --- | --- | --- |
91
+ | `'validator'` | Required (`ed25519` \| `secp256k1` \| `eth`) | Required | Single-validator leader. Executes transactions, seals signed checkpoints (`batchSize` / `timeoutMs` + optional `periodicTimer`), and enforces `witnessQuorum` / `trustedWitnesses` when configured. |
92
+ | `'follower'` (keyless, default `runtimeRole: 'follower'`) | Omitted | Optional (rehydrated from `statedb.sqlite`) | Read-scaling / Sentinel verification node. Bootstraps from a signed snapshot, runs `FollowerSyncService` against `upstreamChainUrl`, and enforces `writePolicy: 'reject'` (`FOLLOWER_READ_ONLY`) or `'forward'` (single-hop `LeaderRouter` proxy to `upstreamChainUrl`). Auto-generates `<dataDir>/.follower-trusted.key` (`0600`) for local `trusted.sqlite` MAC verification. |
93
+ | `'follower'` (`runtimeRole: 'standby'`) | Required | Optional / Partial | Consensus standby follower. Runs `FollowerSyncService` with validator identity keys loaded; merges `.follower-trusted.key` into `legacyTrustedSecretKeys` so promoting a former keyless follower data directory preserves `trusted.sqlite` readability. |
94
+ | `'hotstuff'` | Required | Required | Multi-validator HotStuff BFT consensus node (`HotStuffNodeRuntime` + `SqliteHotStuffStateStore` + dedicated `consensusBindHost:consensusPort` listener). |
95
+
96
+ ---
97
+
98
+ ## Trust-Anchor & Snapshot Bootstrap Contract
99
+
100
+ Keyless followers and standby nodes never trust an unverified upstream stream:
101
+
102
+ 1. **Lease-first safety**: If `<dataDir>/ledger.sqlite` already exists on disk, `startChainNode` acquires the `SqliteSingleWriterLease` **before** `prepareFollowerDataDirectory` inspects or mutates any files, ensuring a duplicate concurrent boot fails immediately with `LEDGER_LEASE_HELD`.
103
+ 2. **Signed snapshot verification (`prepareFollowerDataDirectory`)**:
104
+ - Downloads `latest-snapshot.json`, signed `manifest.json`, `SHA256SUMS`, `statedb.sqlite.zst`, and `ledger.sqlite.zst` from `snapshotBaseUrl` (protected by SSRF private-IP filtering unless `allowPrivatePeers: true` is explicitly set in local harnesses).
105
+ - Verifies the snapshot `manifest.json` signature against the pinned `trustedProposer` / `trustedProposerPublicKey` (and optional `hotstuffValidators`) **before** decompressing archives.
106
+ - Verifies `.zst` SHA-256 checksums against `SHA256SUMS`, decompresses `statedb.sqlite` and `ledger.sqlite`, verifies checkpoint signatures inside `ledger.sqlite`, and writes `<dataDir>/.follower-bootstrap.json` (`0600`) recording `chainId`, `snapshotSequence`, `checkpointHeight`, `checkpointHash`, `stateCommitHash`, `proposer`, `proposerPublicKey`, `bootstrappedAt`, `lastKnownSequence`, and `lastKnownCheckpointHeight`.
107
+ - Cold follower boot without an existing bootstrapped DB and without `snapshotBaseUrl` fails closed; tampered manifests, `.zst` archives, or mismatched `trustedProposerPublicKey` abort startup before `OCAPResolver` opens.
108
+ 3. **Anti-cascading upstream guard (`disallowKeylessCascadedUpstream`)**:
109
+ - When enabled (`true` on Sentinel verification followers), `FollowerSyncService` verifies `/api/ledger/status` upstream signatures and refuses to sync from another keyless/unauthenticated follower, requiring a cryptographic `'validator'` upstream.
110
+ 4. **Fail-closed `NODE_HALTED`**:
111
+ - If `FollowerSyncService` or `LedgerEntryReplayer` detects an offline `statedb.sqlite` tamper, `stateRoot` mismatch against a verified checkpoint, or unrecoverable upstream divergence, it transitions to `halted = true`.
112
+ - Once halted, all non-diagnostic GraphQL queries/mutations throw `CustomError('NODE_HALTED', 'Chain node is halted fail-closed')` and `/api/ledger/status`, `/api/follower/status`, and non-diagnostic `/api/*` data endpoints return HTTP `503` with `{ code: 'NODE_HALTED', halted: true }` (`Cache-Control: no-store`).
113
+
114
+ ---
115
+
116
+ ## Deterministic Boot & Shutdown Order
117
+
118
+ ### 12-Step Boot Sequence (with LIFO Rollback)
119
+
120
+ Every resource opened during `startChainNode` pushes a cleanup closure onto a LIFO rollback stack. If any step throws, all previously opened resources are closed in reverse order and `SqliteSingleWriterLease` is released before the Promise rejects:
121
+
122
+ 1. Validate `testHooks` token (`FORBIDDEN_IN_PRODUCTION` in `NODE_ENV=production`), verify `dataDir` is not a symlink (`assertSafeNonSymlinkDirectory`), and validate `ChainNodeRoleConfig`.
123
+ 2. Load or atomically persist `<dataDir>/.node-id` (`0600`).
124
+ 3. Resolve consensus proposer identity (`ed25519`, `secp256k1`, or `eth`) purely in memory without mutating `process.env`.
125
+ 4. For `role.kind === 'follower'`, acquire pre-existing ledger writer lease if present, run `prepareFollowerDataDirectory`, and provision `.follower-trusted.key` when keyless.
126
+ 5. Initialize writable `SqliteLedgerStorage` (`ledger.sqlite`) and acquire `SqliteSingleWriterLease`.
127
+ 6. Open `SqliteTrustedStorage` (`trusted.sqlite`), open `SqliteStateDB` (`statedb.sqlite`), rehydrate `IChainConfig` from `statedb` for keyless followers, and initialize `Ledger` (wiring logical clock + periodic checkpoint timer).
128
+ 7. Initialize `SqliteIndexDB` (`indexdb.sqlite`), `NodePreferencesManager`, and `Blacklist` (`filter.json`).
129
+ 8. Initialize `OCAPResolver` (`deferInitialize: true`, `skipInitializeStateDB: true` on followers).
130
+ 9. Wire role runtime (`FollowerSyncService` + optional `LeaderRouter` + initial `rebuildIndex()` / orphan replay for followers; `HotStuffNodeRuntime` + `SqliteHotStuffStateStore` for HotStuff).
131
+ 10. Start background sync/consensus loops (`followerSync.start()` or `hotstuffRuntime.start()`).
132
+ 11. Assemble Express + Socket.IO HTTP server and bind `http.host:http.port` (**no global `express.json()`** is mounted so route-specific body limits like the 256 KB `/api/ledger/witness/attestations` endpoint remain intact).
133
+ 12. Run optional `testHooks.onAfterBoot` and return `RunningChainNode`.
134
+
135
+ ### Access log and client IP (#1922)
136
+
137
+ `http.enableAccessLog` (`CHAIN_ACCESS_LOG=1` in the apps) writes one line per finished response through the
138
+ profile logger, in a fixed positional format:
139
+
140
+ ```
141
+ [access] <method> <path> <status> <ms>ms <bytes> <clientIp> <host> <cfRay> "<userAgent>"
142
+ [access] POST /api 200 12ms 1834 203.0.113.7 main.abtnetwork.io 8f1c2d3e4a5b6c7d-SJC "ArcWallet/5.10.9 (iOS 18.1)"
143
+ ```
144
+
145
+ `bytes` is the response body size. Missing values are `-`. All fields except the user agent are free of whitespace
146
+ (whitespace, `"`, `\` and control characters are %-encoded); the user agent is last and quoted with `"`, `\` and
147
+ control characters escaped, so a client cannot end the line or forge a field. The app's logger may put a prefix before
148
+ `[access]` (`qldb-chain-api` prints `[chain] [access] …`), so count fields from the `[access]` token, not from the
149
+ start of the line: `sed -n 's/.*\[access\] //p' | awk '{print $6}'` is the client IP (`$3` status, `$4` duration).
150
+
151
+ The client IP is resolved by `@ocap/util/lib/client-ip` and is the same value the GraphQL context
152
+ (`ctx.request.ip`), the slow-request log and the admin auth failure limiter use:
153
+
154
+ 1. the trusted proxy headers in `CHAIN_CLIENT_IP_HEADERS` order — **only when the TCP peer is a loopback address**,
155
+ and only when the value is a bare IP literal;
156
+ 2. otherwise `req.ip` (equal to the socket address unless the app sets `trust proxy`), then the socket address.
157
+ A socket whose address is gone (the client reset the connection) counts as an unknown peer: headers are ignored.
158
+
159
+ `CHAIN_CLIENT_IP_HEADERS` (comma-separated, ordered; `none` or empty trusts no header):
160
+
161
+ | Deployment | Value | Why |
162
+ |---|---|---|
163
+ | Blocklet Server nginx (default) | unset = `x-real-ip` | nginx sets `X-Real-IP $remote_addr` but passes a client-supplied `CF-Connecting-IP` through, so trusting `cf-connecting-ip` there would let a client pick its own IP |
164
+ | Cloudflare Tunnel (cloudflared on the same host) | `cf-connecting-ip` | see below; must be set explicitly |
165
+
166
+ Why `cf-connecting-ip` can be trusted under the tunnel: the chain process listens on `127.0.0.1` only and is reached
167
+ through the cloudflared daemon on the same host (#1875 decision E4). Cloudflare's edge sets `cf-connecting-ip` to the
168
+ real client address, and a request that already carries its own `cf-connecting-ip` is rejected at the edge (403,
169
+ error 1000); a client's `x-real-ip` did not reach the origin either (both checked with a local quick tunnel on
170
+ 2026-11-19). If the tunnel opt-in is forgotten, the default `x-real-ip` is absent and every request resolves to
171
+ `127.0.0.1`: one shared bucket and a useless log column, but nothing a client can spoof. cloudflared forwards the
172
+ original `Host` header unchanged (unless an ingress rule sets `originRequest.httpHostHeader`), so the same-origin
173
+ check of mutating admin session requests keeps working.
174
+
175
+ Limits of the loopback rule: **any process on the same host can connect over loopback and set any client IP** (a
176
+ builder host runs ~30 other blocklets); that is accepted by #1875 E4. A non-loopback peer talks to the process
177
+ directly (e.g. a node bound to `0.0.0.0`), so its headers are its own claim and are ignored.
178
+
179
+ The admin auth failure limiter (`createAdminAuthGuard`, 10 failures per minute) buckets by this client IP. A correct
180
+ token is compared before the limiter is consulted, so the limiter never locks out a correct token, not even from a
181
+ rate-limited address. What a shared bucket breaks is fairness: when every request appears as `127.0.0.1` (the tunnel
182
+ without the opt-in, or any proxy without a trusted header), one client's wrong guesses rate-limit everyone else's
183
+ mistyped attempts. Resolving the real client restores per-client buckets.
184
+
185
+ WebSocket per-IP connection limits (`@arcblock/ws`, 64 per IP) use their own setting: set `WS_TRUST_PROXY=1` with
186
+ `WS_TRUSTED_PROXIES=127.0.0.1/32,::1/128`, or every subscriber behind the tunnel counts against one address.
187
+
188
+ ### 9-Step Reverse Graceful Shutdown (`node.stop()`)
189
+
190
+ 1. Stop `followerSync` / `hotstuffRuntime` background loops and clear maintenance/HWM timers.
191
+ 2. Flip `isShuttingDown = true` (new HTTP requests receive `503` + `Connection: close`), close idle keep-alive sockets, and wait up to `http.drainTimeoutMs` (`5000ms` default) for `activeResponses === 0` **before** calling `server.close()` (preventing Socket.IO/`WsServer.attach` `closeAllConnections()` from resetting in-flight responses).
192
+ 3. Close the HTTP + WebSocket listener (`server.close()`).
193
+ 4. Call `resolver.shutdown()` (drains in-flight pre-flights, transaction queue, and `flushIndexWrites()`).
194
+ 5. Demote ledger role (`ledger.setNodeRole('readonly')`) to fence new writes and periodic checkpoint timers.
195
+ 6. Dispose `Blacklist` file watchers (`filter.dispose()`).
196
+ 7. Close `statedb` and `trustedStorage`.
197
+ 8. Close `indexdb` and flush final follower high-water mark.
198
+ 9. In `finally`, call `ledger.close()` to drain any in-flight checkpoint and release `SqliteSingleWriterLease` last.
199
+
200
+ ---
201
+
202
+ ## Extension & Test Injection Hooks
203
+
204
+ ### Application Hook (`profile.configureApp`)
205
+
206
+ `configureApp(app, ctx)` runs after CORS and the shutdown fence, and before `/api`, `/node`, and `/` GraphQL. Handlers receive `ChainAppHookContext` (`nodeId`, `dataDir`, `role`, `config`, `statedb`, `indexdb`, `ledger`, `resolver`, `preferencesManager`, `maintenanceController`).
207
+
208
+ Because `@ocap/chain-node` intentionally avoids mounting a global `express.json()`, any custom POST/PUT route registered inside `configureApp` should attach route-scoped body parsing (for example `app.post('/admin/foo', express.json({ limit: '64kb' }), handler)`).
209
+
210
+ ### Non-Production Test Hooks (`@ocap/chain-node/testing`)
211
+
212
+ Deterministic fault-injection and clock hooks live behind a dedicated subpath export:
213
+
214
+ ```ts
215
+ import { startChainNode } from '@ocap/chain-node';
216
+ import { createChainNodeTestHooks } from '@ocap/chain-node/testing';
217
+
218
+ const testHooks = createChainNodeTestHooks({
219
+ initialClockOffsetSeconds: 0,
220
+ followerSync: { startPaused: true },
221
+ });
222
+ const node = await startChainNode({ profile, testHooks });
223
+ node.advanceClock?.(120);
224
+ ```
225
+
226
+ - **Unforgeable capability**: `createChainNodeTestHooks` stamps objects with a private module-scoped `Symbol('@ocap/chain-node/test-hooks-token')` (not `Symbol.for`), so test hooks cannot be injected via JSON configs, CLI flags, or environment variables.
227
+ - **Production hard block**: Passing `testHooks` or calling `createChainNodeTestHooks` when `process.env.NODE_ENV === 'production'` immediately throws `CustomError('FORBIDDEN_IN_PRODUCTION', ...)`.
228
+
229
+ ---
230
+
231
+ ## Relationship to OCAP Packages & Applications
232
+
233
+ - **`bridge/ocap-node` (`@arcblock/bridge-ocap-node`)**: Migrated onto `@ocap/chain-node` (`#1812`). Wraps `startChainNode` with bridge rollup immutable state (`bridge/ocap-node/src/immutable.ts`) and exposes a CLI supporting both `--role validator` and keyless `--role follower` (`--write-policy reject|forward`, `--upstream`, `--snapshot-base-url`, `--trusted-proposer`, `--trusted-proposer-pk`).
234
+ - **`apps/qldb-chain-api` & `apps/asset-chain-api`**: Production OCAP chain applications. `@ocap/chain-node` extracts their shared storage, role runtime, HTTP/WS, and graceful shutdown stack (`roleConfigFromEnv`, `leaseConfigFromEnv`, `configureApp`, `maintenance.pruneIndexDbFn`), with full app entrypoint cutover tracked in `#1820` and `#1821` (production apps never import `@ocap/chain-node/testing`).
235
+ - **Retired legacy apps**: `apps/fs-chain-api` and `apps/fs-chain-manager` were removed in `#1809`.
@@ -0,0 +1,34 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+
3
+ //#region src/access-log.d.ts
4
+
5
+ /**
6
+ * `CHAIN_ACCESS_LOG=1` line (#1922). Behind Cloudflare Tunnel there is no nginx access log, so this line carries what
7
+ * slow-request analysis (#1874) needs. Fixed positional format, one request per line:
8
+ *
9
+ * [access] <method> <path> <status> <ms>ms <bytes> <clientIp> <host> <cfRay> "<userAgent>"
10
+ *
11
+ * - `bytes`: response body bytes written (like nginx `$body_bytes_sent`).
12
+ * - `clientIp`: `@ocap/util/lib/client-ip` (`CHAIN_CLIENT_IP_HEADERS`, default `x-real-ip`, read from a loopback peer only, else socket).
13
+ * - absent values are `-`. Every field except the user agent is whitespace-free (whitespace, `"`, `\` and control
14
+ * characters are %-encoded), so `awk '{print $7}'` is the client IP; the user agent is last, quoted, with `"`, `\`
15
+ * and control characters backslash-escaped, so a client cannot end the line or forge a field.
16
+ */
17
+ interface AccessLogFields {
18
+ method: string;
19
+ path: string;
20
+ status: number;
21
+ durationMs: number;
22
+ bytes: number;
23
+ clientIp: string;
24
+ host?: string;
25
+ cfRay?: string;
26
+ userAgent?: string;
27
+ }
28
+ declare function formatAccessLogLine(f: AccessLogFields): string;
29
+ /** Express middleware writing one `formatAccessLogLine` per finished response through `logger.info`. */
30
+ declare function createAccessLogMiddleware(logger: {
31
+ info: (msg: string) => void;
32
+ }): (req: Request, res: Response, next: NextFunction) => void;
33
+ //#endregion
34
+ export { AccessLogFields, createAccessLogMiddleware, formatAccessLogLine };
@@ -0,0 +1,71 @@
1
+ import { resolveClientIp } from "@ocap/util/lib/client-ip";
2
+
3
+ //#region src/access-log.ts
4
+ const MAX_PATH = 2048;
5
+ const MAX_HOST = 255;
6
+ const MAX_CF_RAY = 64;
7
+ const MAX_UA = 256;
8
+ const pctByte = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
9
+ const token = (value, max) => {
10
+ if (!value) return "-";
11
+ return value.replace(/[\s"\\\u0000-\u001f\u007f]/g, pctByte).slice(0, max);
12
+ };
13
+ const quoted = (value, max) => {
14
+ if (!value) return "\"-\"";
15
+ return `"${value.slice(0, max).replace(/["\\\u0000-\u001f\u007f]/g, (c) => c === "\"" || c === "\\" ? `\\${c}` : `\\x${c.charCodeAt(0).toString(16).padStart(2, "0")}`)}"`;
16
+ };
17
+ function formatAccessLogLine(f) {
18
+ return [
19
+ "[access]",
20
+ token(f.method, 16),
21
+ token(f.path, MAX_PATH),
22
+ String(f.status),
23
+ `${Math.max(0, Math.round(f.durationMs))}ms`,
24
+ String(f.bytes),
25
+ token(f.clientIp, 45),
26
+ token(f.host, MAX_HOST),
27
+ token(f.cfRay, MAX_CF_RAY),
28
+ quoted(f.userAgent, MAX_UA)
29
+ ].join(" ");
30
+ }
31
+ const headerString = (v) => Array.isArray(v) ? v[0] : v;
32
+ const chunkBytes = (chunk, encoding) => {
33
+ if (chunk === void 0 || chunk === null || typeof chunk === "function") return 0;
34
+ if (typeof chunk === "string") return Buffer.byteLength(chunk, typeof encoding === "string" ? encoding : "utf8");
35
+ if (chunk instanceof Uint8Array) return chunk.byteLength;
36
+ return 0;
37
+ };
38
+ /** Express middleware writing one `formatAccessLogLine` per finished response through `logger.info`. */
39
+ function createAccessLogMiddleware(logger) {
40
+ return (req, res, next) => {
41
+ const startedAt = Date.now();
42
+ let bytes = 0;
43
+ const origWrite = res.write;
44
+ const origEnd = res.end;
45
+ res.write = function write(...args) {
46
+ bytes += chunkBytes(args[0], args[1]);
47
+ return origWrite.apply(this, args);
48
+ };
49
+ res.end = function end(...args) {
50
+ bytes += chunkBytes(args[0], args[1]);
51
+ return origEnd.apply(this, args);
52
+ };
53
+ res.once("finish", () => {
54
+ logger.info(formatAccessLogLine({
55
+ method: req.method,
56
+ path: req.originalUrl,
57
+ status: res.statusCode,
58
+ durationMs: Date.now() - startedAt,
59
+ bytes,
60
+ clientIp: resolveClientIp(req),
61
+ host: headerString(req.headers.host),
62
+ cfRay: headerString(req.headers["cf-ray"]),
63
+ userAgent: headerString(req.headers["user-agent"])
64
+ }));
65
+ });
66
+ next();
67
+ };
68
+ }
69
+
70
+ //#endregion
71
+ export { createAccessLogMiddleware, formatAccessLogLine };
package/esm/env.d.mts ADDED
@@ -0,0 +1,32 @@
1
+ import { ChainNodeRoleConfig, ILedgerLeaseOptions, RunningChainNode, ValidatorSignerConfig } from "./types.mjs";
2
+
3
+ //#region src/env.d.ts
4
+
5
+ /**
6
+ * Pure environment-to-role parser (`@ocap/chain-node`).
7
+ *
8
+ * Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
9
+ */
10
+ declare function roleConfigFromEnv(env: Record<string, string | undefined>, options?: {
11
+ signer?: ValidatorSignerConfig;
12
+ }): ChainNodeRoleConfig;
13
+ /**
14
+ * Pure environment-to-SQLite-writer-lease parser (`@ocap/chain-node`).
15
+ *
16
+ * Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
17
+ */
18
+ declare function leaseConfigFromEnv(env: Record<string, string | undefined>): ILedgerLeaseOptions | false;
19
+ interface InstallProcessSignalHandlersOptions {
20
+ timeoutMs?: number;
21
+ signals?: NodeJS.Signals[];
22
+ exitProcess?: boolean;
23
+ onExit?: (exitCode: number) => void;
24
+ logger?: Pick<Console, 'info' | 'error'>;
25
+ }
26
+ /**
27
+ * Install idempotent `SIGTERM` / `SIGINT` graceful shutdown handlers for a running chain node.
28
+ * Returns a cleanup callback that removes the signal listeners.
29
+ */
30
+ declare function installProcessSignalHandlers(node: Pick<RunningChainNode, 'stop'>, options?: InstallProcessSignalHandlersOptions): () => void;
31
+ //#endregion
32
+ export { InstallProcessSignalHandlersOptions, installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv };
package/esm/env.mjs ADDED
@@ -0,0 +1,218 @@
1
+ import { normalizeDidForCompare, resolveConsensusProposer, resolveConsensusProposerFromSigner, resolveEnvWitnessWallet, resolveNodeRoleConfig } from "@arcblock/ledger-core";
2
+ import { resolveLedgerLeaseConfig } from "@arcblock/ledger-sqlite";
3
+ import { CustomError } from "@ocap/util/lib/error";
4
+
5
+ //#region src/env.ts
6
+ function parseOptionalPositiveInt(raw, label) {
7
+ const trimmed = (raw ?? "").trim();
8
+ if (!trimmed) return void 0;
9
+ if (!/^[1-9]\d*$/.test(trimmed)) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a positive integer >= 1`);
10
+ const parsed = Number(trimmed);
11
+ if (!Number.isSafeInteger(parsed) || parsed < 1) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a positive safe integer >= 1`);
12
+ return parsed;
13
+ }
14
+ function parseOptionalNonNegativeInt(raw, label) {
15
+ const trimmed = (raw ?? "").trim();
16
+ if (!trimmed) return void 0;
17
+ if (!/^(?:0|[1-9]\d*)$/.test(trimmed)) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a non-negative integer >= 0`);
18
+ const parsed = Number(trimmed);
19
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a non-negative safe integer >= 0`);
20
+ return parsed;
21
+ }
22
+ function parseBoolEnv(raw) {
23
+ const norm = (raw ?? "").trim().toLowerCase();
24
+ return norm === "1" || norm === "true";
25
+ }
26
+ function hasSigningSecretKey(signer) {
27
+ return Boolean(signer && typeof signer.secretKey === "string" && signer.secretKey.trim().length > 0);
28
+ }
29
+ function normalizeConsensusKeyType(rawValue) {
30
+ const trimmed = (rawValue ?? "").trim().toLowerCase();
31
+ if (!trimmed) return void 0;
32
+ if (trimmed === "ethereum") return "eth";
33
+ if (trimmed === "ed25519" || trimmed === "secp256k1" || trimmed === "eth") return trimmed;
34
+ throw new CustomError("INVALID_CONFIG", `Unsupported CHAIN_CONSENSUS_KEY_TYPE="${rawValue}": expected ed25519, secp256k1, or eth`);
35
+ }
36
+ function resolveSignerFromEnvRecord(env, explicitSigner) {
37
+ const keyType = normalizeConsensusKeyType(env.CHAIN_CONSENSUS_KEY_TYPE);
38
+ const secretKey = (env.CHAIN_CONSENSUS_SK ?? "").trim();
39
+ const address = (env.CHAIN_CONSENSUS_PROPOSER ?? "").trim();
40
+ if (!secretKey) {
41
+ if (keyType) throw new CustomError("INVALID_CONFIG", `CHAIN_CONSENSUS_KEY_TYPE (${env.CHAIN_CONSENSUS_KEY_TYPE}) requires CHAIN_CONSENSUS_SK to be set`);
42
+ if (address) {
43
+ if (!hasSigningSecretKey(explicitSigner) || normalizeDidForCompare(explicitSigner.address) !== normalizeDidForCompare(address)) throw new CustomError("INVALID_CONFIG", `CHAIN_CONSENSUS_PROPOSER (${env.CHAIN_CONSENSUS_PROPOSER}) requires a matching CHAIN_CONSENSUS_SK`);
44
+ }
45
+ return explicitSigner;
46
+ }
47
+ if (hasSigningSecretKey(explicitSigner)) return explicitSigner;
48
+ if (address) {
49
+ const resolved = resolveConsensusProposerFromSigner({
50
+ address,
51
+ secretKey,
52
+ ...keyType ? { keyType } : {}
53
+ });
54
+ return {
55
+ address: resolved.address,
56
+ secretKey: resolved.secretKey,
57
+ publicKey: resolved.publicKey,
58
+ ...keyType ? { keyType } : {}
59
+ };
60
+ }
61
+ const derived = resolveConsensusProposer({
62
+ moderator: { address: explicitSigner?.address || "" },
63
+ env: {
64
+ ...env,
65
+ ...keyType ? { CHAIN_CONSENSUS_KEY_TYPE: keyType } : {}
66
+ }
67
+ });
68
+ if (derived.secretKey) return {
69
+ address: derived.address,
70
+ secretKey: derived.secretKey,
71
+ publicKey: derived.publicKey,
72
+ ...keyType ? { keyType } : {}
73
+ };
74
+ return explicitSigner;
75
+ }
76
+ /**
77
+ * Pure environment-to-role parser (`@ocap/chain-node`).
78
+ *
79
+ * Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
80
+ */
81
+ function roleConfigFromEnv(env, options) {
82
+ if (!env || typeof env !== "object") throw new CustomError("INVALID_CONFIG", "roleConfigFromEnv requires an explicit env record");
83
+ const resolved = resolveNodeRoleConfig(env);
84
+ const allowPrivatePeers = parseBoolEnv(env.ALLOW_PRIVATE_PEER_URLS);
85
+ const explicitOrEnvSigner = resolveSignerFromEnvRecord(env, options?.signer);
86
+ if (resolved.role === "validator") {
87
+ if (!explicitOrEnvSigner) throw new CustomError("INVALID_CONFIG", "Validator role requires options.signer or explicit CHAIN_CONSENSUS_SK + CHAIN_CONSENSUS_PROPOSER in env");
88
+ if (resolved.consensusMode === "hotstuff") {
89
+ if (!hasSigningSecretKey(explicitOrEnvSigner)) throw new CustomError("INVALID_CONFIG", "HotStuff validator role requires a signing secretKey in options.signer or CHAIN_CONSENSUS_SK");
90
+ if (!resolved.consensusBindHost || resolved.consensusPort === null) throw new CustomError("INVALID_CONFIG", "HotStuff validator role requires CONSENSUS_BIND_HOST and CONSENSUS_PORT");
91
+ return {
92
+ kind: "hotstuff",
93
+ signer: explicitOrEnvSigner,
94
+ validators: resolved.hotstuffValidators,
95
+ ...resolved.hotstuffQuorumThreshold !== void 0 ? { quorumThreshold: resolved.hotstuffQuorumThreshold } : {},
96
+ consensusBindHost: resolved.consensusBindHost,
97
+ consensusPort: resolved.consensusPort,
98
+ allowPublicConsensusBind: resolved.allowPublicConsensusBind,
99
+ writePolicy: resolved.writePolicy,
100
+ allowPrivatePeers,
101
+ retentionMode: resolved.retentionMode,
102
+ hotWindowEntries: resolved.hotWindowEntries,
103
+ hotWindowCheckpoints: resolved.hotWindowCheckpoints,
104
+ snapshotBaseUrl: resolved.snapshotBaseUrl,
105
+ witnessQuorum: resolved.witnessQuorum,
106
+ ...resolved.trustedWitnesses !== void 0 ? { trustedWitnesses: resolved.trustedWitnesses } : {},
107
+ witnessSubmitUrls: resolved.witnessSubmitUrls
108
+ };
109
+ }
110
+ return {
111
+ kind: "validator",
112
+ signer: explicitOrEnvSigner,
113
+ retentionMode: resolved.retentionMode,
114
+ hotWindowEntries: resolved.hotWindowEntries,
115
+ hotWindowCheckpoints: resolved.hotWindowCheckpoints,
116
+ snapshotBaseUrl: resolved.snapshotBaseUrl,
117
+ witnessQuorum: resolved.witnessQuorum,
118
+ ...resolved.trustedWitnesses !== void 0 ? { trustedWitnesses: resolved.trustedWitnesses } : {},
119
+ witnessSubmitUrls: resolved.witnessSubmitUrls,
120
+ anchorWebhookUrl: resolved.anchorWebhookUrl
121
+ };
122
+ }
123
+ const pollIntervalMs = parseOptionalPositiveInt(env.FOLLOWER_POLL_INTERVAL_MS, "FOLLOWER_POLL_INTERVAL_MS");
124
+ const maxSyncLag = parseOptionalNonNegativeInt(env.FOLLOWER_MAX_SYNC_LAG, "FOLLOWER_MAX_SYNC_LAG");
125
+ const maxUpstreamStaleMs = parseOptionalPositiveInt(env.FOLLOWER_MAX_UPSTREAM_STALE_MS, "FOLLOWER_MAX_UPSTREAM_STALE_MS");
126
+ const witnessWallet = resolveEnvWitnessWallet(env) ?? void 0;
127
+ const snapshotPrefix = (env.SNAPSHOT_S3_PREFIX ?? "").trim() || void 0;
128
+ const disallowKeylessCascadedUpstream = parseBoolEnv(env.DISALLOW_KEYLESS_CASCADED_UPSTREAM);
129
+ return {
130
+ kind: "follower",
131
+ runtimeRole: resolved.role === "standby" ? "standby" : "follower",
132
+ writePolicy: resolved.writePolicy,
133
+ upstreamChainUrl: resolved.upstreamChainUrl,
134
+ clusterPeerUrls: resolved.clusterPeerUrls,
135
+ snapshotBaseUrl: resolved.snapshotBaseUrl,
136
+ ...snapshotPrefix ? { snapshotPrefix } : {},
137
+ trustedProposer: resolved.trustedProposer,
138
+ trustedProposerPublicKey: resolved.trustedProposerPublicKey,
139
+ ...resolved.hotstuffValidators.length > 0 ? { hotstuffValidators: resolved.hotstuffValidators } : {},
140
+ ...resolved.hotstuffQuorumThreshold !== void 0 ? { hotstuffQuorumThreshold: resolved.hotstuffQuorumThreshold } : {},
141
+ allowPrivatePeers,
142
+ disallowKeylessCascadedUpstream,
143
+ allowUnauthenticatedBootstrap: resolved.allowUnauthenticatedBootstrap,
144
+ syncMode: resolved.syncMode,
145
+ ...pollIntervalMs !== void 0 ? { pollIntervalMs } : {},
146
+ ...maxSyncLag !== void 0 ? { maxSyncLag } : {},
147
+ ...maxUpstreamStaleMs !== void 0 ? { maxUpstreamStaleMs } : {},
148
+ retentionMode: resolved.retentionMode,
149
+ hotWindowEntries: resolved.hotWindowEntries,
150
+ hotWindowCheckpoints: resolved.hotWindowCheckpoints,
151
+ ...witnessWallet ? { witnessWallet } : {},
152
+ witnessSubmitUrls: resolved.witnessSubmitUrls,
153
+ ...hasSigningSecretKey(explicitOrEnvSigner) ? { signer: explicitOrEnvSigner } : {}
154
+ };
155
+ }
156
+ /**
157
+ * Pure environment-to-SQLite-writer-lease parser (`@ocap/chain-node`).
158
+ *
159
+ * Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
160
+ */
161
+ function leaseConfigFromEnv(env) {
162
+ if (!env || typeof env !== "object") throw new CustomError("INVALID_CONFIG", "leaseConfigFromEnv requires an explicit env record");
163
+ const parsed = resolveLedgerLeaseConfig(env);
164
+ if (!parsed.enabled) return false;
165
+ return {
166
+ enabled: true,
167
+ autoAcquire: true,
168
+ holderId: parsed.holderId,
169
+ ttlMs: parsed.ttlMs,
170
+ startupWaitMs: parsed.startupWaitMs
171
+ };
172
+ }
173
+ /**
174
+ * Install idempotent `SIGTERM` / `SIGINT` graceful shutdown handlers for a running chain node.
175
+ * Returns a cleanup callback that removes the signal listeners.
176
+ */
177
+ function installProcessSignalHandlers(node, options) {
178
+ const timeoutMs = typeof options?.timeoutMs === "number" && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 15e3;
179
+ const signals = options?.signals ?? ["SIGTERM", "SIGINT"];
180
+ const exitProcess = options?.exitProcess !== false;
181
+ const log = options?.logger ?? console;
182
+ let shuttingDown = false;
183
+ const handleSignal = (signal) => {
184
+ if (shuttingDown) return;
185
+ shuttingDown = true;
186
+ log.info(`\n${signal} received, shutting down chain node gracefully...`);
187
+ const forceTimer = setTimeout(() => {
188
+ log.error("Chain node graceful shutdown timed out, forcing exit");
189
+ options?.onExit?.(1);
190
+ if (exitProcess) process.exit(1);
191
+ }, timeoutMs);
192
+ if (typeof forceTimer.unref === "function") forceTimer.unref();
193
+ node.stop().then(() => {
194
+ clearTimeout(forceTimer);
195
+ log.info("Chain node graceful shutdown complete");
196
+ options?.onExit?.(0);
197
+ if (exitProcess) process.exit(0);
198
+ }).catch((err) => {
199
+ clearTimeout(forceTimer);
200
+ log.error("Error during chain node graceful shutdown:", err);
201
+ options?.onExit?.(1);
202
+ if (exitProcess) process.exit(1);
203
+ });
204
+ };
205
+ const listeners = /* @__PURE__ */ new Map();
206
+ for (const sig of signals) {
207
+ const listener = () => handleSignal(sig);
208
+ listeners.set(sig, listener);
209
+ process.on(sig, listener);
210
+ }
211
+ return () => {
212
+ for (const [sig, listener] of listeners) process.off(sig, listener);
213
+ listeners.clear();
214
+ };
215
+ }
216
+
217
+ //#endregion
218
+ export { installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv };
@@ -0,0 +1,5 @@
1
+ import { ChainAppHookContext, ChainNodeHandle, ChainNodeProfile, ChainNodeRoleConfig, ChainNodeSegmentPublisher, ChainNodeSignerConfig, ChainNodeTestHooks, ChainNodeTestHooksInput, ChainProfile, ChainProfileBase, FollowerRoleConfig, FollowerSyncTestController, FollowerUpstreamInterceptorContext, HotStuffValidatorRoleConfig, ILedgerHealthStatus, ILedgerLeaseOptions, PublicKeyOnlyValidatorSignerConfig, RunningChainNode, StartChainNodeOptions, TNodeRetentionMode, TrustedAccountConfig, ValidatorRoleConfig, ValidatorSignerConfig } from "./types.mjs";
2
+ import { InstallProcessSignalHandlersOptions, installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv } from "./env.mjs";
3
+ import { startChainNode } from "./start-chain-node.mjs";
4
+ import { BLOCKLET_ENV_CHAIN_FALLBACKS, BlockletEnvLeftovers, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, resolveTrustedSubject } from "./standalone-env.mjs";
5
+ export { BLOCKLET_ENV_CHAIN_FALLBACKS, type BlockletEnvLeftovers, type ChainAppHookContext, type ChainNodeHandle, type ChainNodeProfile, type ChainNodeRoleConfig, type ChainNodeSegmentPublisher, type ChainNodeSignerConfig, type ChainNodeTestHooks, type ChainNodeTestHooksInput, type ChainProfile, type ChainProfileBase, type FollowerRoleConfig, type FollowerSyncTestController, type FollowerUpstreamInterceptorContext, type HotStuffValidatorRoleConfig, type ILedgerHealthStatus, type ILedgerLeaseOptions, type InstallProcessSignalHandlersOptions, type PublicKeyOnlyValidatorSignerConfig, type RunningChainNode, STANDALONE_ENV_MARKERS, type StartChainNodeOptions, type TNodeRetentionMode, type TrustedAccountConfig, type ValidatorRoleConfig, type ValidatorSignerConfig, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, installProcessSignalHandlers, leaseConfigFromEnv, resolveTrustedSubject, roleConfigFromEnv, startChainNode };
package/esm/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ import { installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv } from "./env.mjs";
2
+ import { startChainNode } from "./start-chain-node.mjs";
3
+ import { BLOCKLET_ENV_CHAIN_FALLBACKS, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, resolveTrustedSubject } from "./standalone-env.mjs";
4
+
5
+ export { BLOCKLET_ENV_CHAIN_FALLBACKS, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, installProcessSignalHandlers, leaseConfigFromEnv, resolveTrustedSubject, roleConfigFromEnv, startChainNode };
@@ -0,0 +1,39 @@
1
+ //#region src/standalone-env.d.ts
2
+ type Env = Record<string, string | undefined>;
3
+ /**
4
+ * Standalone replacement for the Blocklet Server app DID that seeds the trusted-storage wallet.
5
+ * Returns '' when unset/blank so callers fall back to BLOCKLET_APP_PID / BLOCKLET_APP_ID / moderator exactly as
6
+ * before. The subject is hashed as a raw string by `fromAppDid`, so a `did:abt:` prefix or a typo would silently
7
+ * yield a different trusted key: only a bare, valid DID address is accepted.
8
+ */
9
+ declare function resolveTrustedSubject(env?: Env): string;
10
+ /**
11
+ * Standalone-only replacements for Blocklet Server variables. Blocklet Server sets none of them on beta or main
12
+ * (checked against both live process envs), so seeing one means the operator runs (or migrates to) a standalone
13
+ * env file. `CHAIN_VAULT_PSK` is deliberately not a marker: main's blocklet.yml declares it, so it is present there.
14
+ */
15
+ declare const STANDALONE_ENV_MARKERS: readonly string[];
16
+ /** Blocklet Server variables both chain apps still read as fallbacks behind a CHAIN_* variable. */
17
+ declare const BLOCKLET_ENV_CHAIN_FALLBACKS: ReadonlySet<string>;
18
+ interface BlockletEnvLeftovers {
19
+ standaloneMarkers: string[];
20
+ leftovers: string[];
21
+ readByChain: string[];
22
+ }
23
+ /**
24
+ * Detect a standalone env that still carries Blocklet Server variables, so two key sources are never mixed
25
+ * silently. Returns null under Blocklet Server (no standalone marker) and for a clean standalone env.
26
+ * Only variable names are returned, never values.
27
+ */
28
+ declare function findBlockletEnvLeftovers(env?: Env, {
29
+ readByChain
30
+ }?: {
31
+ readByChain?: Iterable<string>;
32
+ }): BlockletEnvLeftovers | null;
33
+ declare function formatBlockletEnvLeftoversWarning({
34
+ standaloneMarkers,
35
+ leftovers,
36
+ readByChain
37
+ }: BlockletEnvLeftovers): string;
38
+ //#endregion
39
+ export { BLOCKLET_ENV_CHAIN_FALLBACKS, BlockletEnvLeftovers, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, resolveTrustedSubject };