In development. It changes without notice.
Topic
Wi-Fi Admin Portal
The web pages the board serves to one browser over its own Wi-Fi: to edit the vault, back it up, change settings and install an update.
The portal runs only in its state. It starts an access point that is WPA3 only and admits one station, and an HTTP server behind it. Bluetooth is fully shut down before either.
Who may ask. Each route names the checks it wants (AuthPolicy), and the dispatcher runs them before the handler: how often an address may ask, the session token, and for an upload the password of updates as well. The token is 128 random bits, made when the portal starts, given to the page and expired by 5 minutes without activity. The password of an update is derived from the vault key and the token, so it changes with each session.
What it serves
| For | Routes under |
|---|---|
| The session | /api/init, /api/bootstrap, /api/idle, /api/keepalive, /api/session/ |
| Logins, codes and groups | /api/credentials, /api/totp, /api/groups, /api/generate-password |
| Backups and imports | /api/backup, /api/export/, /api/restore, /api/import/, /api/sd/ |
| Settings | /api/settings/ |
| The device | /api/status, /api/capabilities, /api/system, /api/time, /api/telemetry, /api/gps/ |
| Networks and hosts | /api/ap, /api/wifi/networks, /api/ntp/, /api/ble/ |
| Security | /api/security/, /api/audit, /api/rekey, /api/rotate, /api/vault/, /api/factory-reset/ |
| The update | /update, /api/ota/status |
These routes are the portal's own page's and change with it. Any other address a browser asks for, the check a phone makes on joining a network among them, leads to the portal's page.
The portal holds the vault's key only for its session, and whoever started it wipes it. What it shows of the device's state and settings comes through an interface that the states implement (AdminAppHost), so it knows no screen.
Topics | |
| Admin Portal Rules | |
| The decisions the portal's routes take, with no server behind them. | |
| Display Stream | |
| The video of the display that a debug build sends to the tests. | |
Files | |
| file | src/ |
| Per-request dependency bundle handed to every admin route handler. | |
| file | src/ |
| Free-function request handlers for the admin portal REST API. | |
| file | src/ |
| What the portal's route units share: two bounds and the helpers more than one calls. | |
| file | src/ |
| What the admin portal reads from, and asks of, the running application. | |
| file | src/ |
| Stateful authentication / rate-limit / secret-generation adapter for the admin portal. | |
| file | src/ |
| BLE identity endpoints for the admin portal (advertised name, host labels). | |
| file | src/ |
| Implementation of the destructive-endpoint confirmation gate. | |
| file | src/ |
| The proof-of-intent gate every destructive admin endpoint must pass. | |
| file | src/ |
| Implementation of the widened credential list and the confirmed batch delete. | |
| file | src/ |
| Widened credential list and confirmed batch delete for the portal. | |
| file | src/ |
| Implementation of the portal's clock/ | |
| file | src/ |
| Admin-portal read surfaces for clock, security posture, AP and session. | |
| file | src/ |
| The portal's backup and export routes. | |
| file | src/ |
| Admin-portal bridge to the one-shot GPS time-sync engine (HAS_GPS). | |
| file | src/ |
| Implementation of the admin-portal group routes. | |
| file | src/ |
| Admin-portal group routes: list, rename-or-create, delete-with-fallback. | |
| file | src/ |
| The DNS-rebinding Host guard of the admin portal, on one request. | |
| file | src/ |
| HTTP request/ | |
| file | src/ |
| The admin portal's HTTP server: its route table and its one dispatcher. | |
| file | src/ |
| Implementation of the normalized merge-import endpoint. | |
| file | src/ |
| Admin-portal endpoint: normalized merge-import of credential items. | |
| file | src/ |
| One JSON response written straight from the own JSON writer. | |
| file | src/ |
| Streaming JSON responses for the admin portal. | |
| file | src/ |
| Transport port the admin portal depends on for network bring-up and status. | |
| file | src/ |
| Implementation of the saved-WiFi and time-server admin routes. | |
| file | src/ |
| Saved WiFi networks and time servers, over the admin portal. | |
| file | src/ |
| OTA firmware-upload request handlers for the admin portal. | |
| file | src/ |
| AP-mode web portal for credential CRUD and OTA updates. | |
| file | src/ |
| Encapsulated shared state for the AP-mode admin portal. | |
| file | src/ |
| Small value types shared between the admin portal and its state owner. | |
| file | src/ |
| The portal's key-rotation and secret-change routes. | |
| file | src/ |
| SD-card admin portal request handlers (HAS_SDCARD variants only). | |
| file | src/ |
| Implementation of the settings-model projection onto the admin portal. | |
| file | src/ |
| Admin-portal endpoints that project the settings model onto HTTP. | |
| file | src/ |
| Device-information REST API for the admin portal (/api/system*). | |
| file | src/ |
| Battery-history admin portal request handlers. | |
| file | src/ |
| Admin portal endpoints for live one-time codes and TOTP metadata. | |
| file | src/ |
| Debug-only transport selector implementation. | |
| file | src/ |
| Debug-only transport selector: the admin portal over the SoftAP or over a debug link. | |
| file | src/ |
| What the portal answers when a request body cannot be read or parsed. | |
| file | src/ |
| The largest request body each buffered portal route accepts. | |
| file | src/ |
| Which settings rows the admin portal lists, and the dial style it reports. | |
| file | src/ |
| WiFi SoftAP + captive-DNS adapter for the admin portal transport port. | |
Classes | |
| struct | kleidos:: |
| Per-request context passed by reference to every admin route handler. More about kleidos:: | |
| class | kleidos:: |
| The running application, as the admin portal sees it. More about kleidos:: | |
| class | kleidos:: |
| Stateful security gatekeeper operating on a referenced AdminPortalState. More about kleidos:: | |
| class | kleidos:: |
RAII owner for a heap-allocated HTTP body that may hold plaintext credentials: the buffer is zeroized with mbedtls_ before it is released, both on reset and on destruction. Move-only. More about kleidos:: | |
| class | kleidos:: |
| Single reusable header-value slot, zeroized on wipe (may hold secrets). More about kleidos:: | |
| struct | kleidos:: |
| What one header read found, and the slot when it holds the value. More about kleidos:: | |
| class | kleidos:: |
| Peer-address holder for a request (per-IP rate limiting). More about kleidos:: | |
| class | kleidos:: |
| Response builder; owns sensitive body bytes wiped on destruction. More about kleidos:: | |
| class | kleidos:: |
| Bounded view over one platform HTTP request with a lazily-read body. More about kleidos:: | |
| class | kleidos:: |
| The portal's HTTP server: a static route table behind one dispatcher. More about kleidos:: | |
| class | kleidos:: |
| A JSON response the caller writes through a json::Writer. More about kleidos:: | |
| class | kleidos:: |
| Streaming sink for the own JSON writer: forwards its text to the chunked response through a small rolling buffer. More about kleidos:: | |
| class | kleidos:: |
| Stream a JSON array element by element over a chunked response. More about kleidos:: | |
| struct | kleidos:: |
| Link-agnostic snapshot of a transport's reachability and identity. More about kleidos:: | |
| class | kleidos:: |
| Abstract transport port for the admin portal. More about kleidos:: | |
| class | kleidos:: |
| Static AP-mode admin portal. More about kleidos:: | |
| struct | kleidos:: |
| Single owner of all admin-portal runtime state. More about kleidos:: | |
| struct | kleidos:: |
| OTA progress snapshot for the display callback. More about kleidos:: | |
| struct | kleidos:: |
| Battery charge and charger state, as one sample recorded them. More about kleidos:: | |
| struct | kleidos:: |
| A status and its JSON body. More about kleidos:: | |
| struct | kleidos:: |
| One row of a settings patch: the key as sent, and its value. More about kleidos:: | |
| class | kleidos:: |
| Reads the body of POST /api/settings/options: one object whose members are rows (a key and an integer or boolean value), beside the unlock secret. More about kleidos:: | |
| class | kleidos:: |
| WiFi-AP transport adapter (SoftAP + captive DNS). More about kleidos:: | |
Typedefs | |
| using | kleidos:: |
| using | kleidos:: |
Functions | |
| uint16_t | kleidos:: |
Parse a credential index from a /api/credentials/:id URL. | |
| void | kleidos:: |
| void | kleidos:: |
| void | kleidos:: |
| void | kleidos:: |
POST /api/vault/reindex — rebuild the encrypted list index. | |
| void | kleidos:: |
| GET /api/audit — the audit history, content-negotiated. | |
| void | kleidos:: |
| Answer with a 302 to the portal root, so a browser that asked for anything at all lands on the admin panel. | |
| void | kleidos:: |
| Not-found dispatcher: redirects unknown non-API GETs to the panel, then enforces Session and dispatches the dynamic per-resource routes. | |
| void | kleidos:: |
| Dynamic route handler for GET /api/credentials/:id. | |
| bool | kleidos:: |
| Parse a decimal numeric suffix appended after a URL prefix (e.g. "/api/credentials/3"). | |
| void | kleidos:: |
Append a JSON-escaped string literal (with surrounding quotes) to output. | |
| void | kleidos:: |
| The NUL-terminated form of appendJsonEscapedSpan. | |
| void | kleidos:: |
| Append a pool entry's value as a JSON string, or "" when it is absent. | |
| bool | kleidos:: |
| Return true when the request carries an explicit plaintext-export consent token. | |
| bool | kleidos:: |
| Prove the unlock secret for an edit that destroys a stored secret. | |
| constexpr NameCheck | kleidos:: |
| Validate a BLE identity string against the name rules of every board. | |
| constexpr const char * | kleidos:: |
| Machine-readable reason token for a rejected name. | |
| constexpr bool | kleidos:: |
Match /api/ble/hosts/<idx>/name and extract the host index. | |
| void | kleidos:: |
GET /api/ble/name — report the advertised BLE device name. | |
| void | kleidos:: |
POST /api/ble/name — persist a new advertised BLE device name. | |
| bool | kleidos:: |
Dynamic route handler for POST /api/ble/hosts/:idx/name. | |
| void | kleidos:: |
| GET /api/ble/hosts: the bonded hosts in the owner's order. | |
| bool | kleidos:: |
| Dynamic route handler for DELETE /api/ble/hosts/:idx. | |
| bool | kleidos:: |
| Verify the unlock secret carried by a destructive request. | |
| bool | kleidos:: |
| Take the unlock secret out of a JSON request body. | |
| bool | kleidos:: |
| Verify the unlock secret carried in a JSON request body. | |
| void | kleidos:: |
Mint a one-shot nonce for action, bound to the live session. | |
| bool | kleidos:: |
Consume the nonce for action. | |
| void | kleidos:: |
| Wipe any pending confirmation. | |
| uint32_t | kleidos:: |
| Seconds a minted nonce stays valid. | |
| void | kleidos:: |
| GET /api/credentials — list every stored credential, widened. | |
| void | kleidos:: |
| POST /api/credentials/delete/prepare — stage a delete batch. | |
| void | kleidos:: |
| POST /api/credentials/delete/commit — erase the staged batch. | |
| void | kleidos:: |
| Drop any staged delete batch. | |
| void | kleidos:: |
GET /api/time — clock, trust, provenance and the zone table. | |
| void | kleidos:: |
GET /api/time/diag — hardware-clock health (VL flag, alarm, timer). | |
| void | kleidos:: |
GET /api/security/posture — secret kind, KDF, binding, boot flags. | |
| void | kleidos:: |
GET /api/security/lockout — attempts used, lock remaining, policy. | |
| void | kleidos:: |
GET /api/ap — access-point identity and client count (no password). | |
| void | kleidos:: |
POST /api/session/end — leave admin mode cleanly. | |
| void | kleidos:: |
POST /api/session/lock — relock the vault and end admin mode. | |
| void | kleidos:: |
POST /api/vault/wipe/prepare — verify the secret, mint a nonce. | |
| void | kleidos:: |
POST /api/vault/wipe/commit — the vault-only wipe. | |
| void | kleidos:: |
POST /api/settings/reset — restore preference defaults. | |
| void | kleidos:: |
POST /api/factory-reset/prepare — verify the secret, mint a nonce. | |
| void | kleidos:: |
POST /api/factory-reset/commit — erase everything and restart. | |
| void | kleidos:: |
POST /api/ap/credentials — pin the access point's SSID and password. | |
| void | kleidos:: |
DELETE /api/ap/credentials — back to a random password per session. | |
| void | kleidos:: |
POST /api/ble/hosts/forget-all — de-bond every paired host. | |
| void | kleidos:: |
| Ask the FSM to tear the portal down on its next tick. | |
| bool | kleidos:: |
| Whether a handler asked the FSM to leave admin mode. | |
| bool | kleidos:: |
| Whether the pending exit also asked for the vault to be relocked. | |
| void | kleidos:: |
| End the session with a restart: what every factory reset from the portal owes. | |
| void | kleidos:: |
| Destroy the vault once a remote unlock verify spends the last attempt. | |
| void | kleidos:: |
POST /api/export/encrypted — stream the whole vault sealed under a passphrase. | |
| void | kleidos:: |
GET /api/backup — stream the whole vault as a plaintext backup, with consent. | |
| void | kleidos:: |
GET /api/export/csv — stream the credentials as CSV, with consent. | |
| void | kleidos:: |
| GET /api/export/json: every credential in plaintext, streamed a row at a time behind the plaintext consent header. | |
| void | kleidos:: |
GET /api/gps/status — receiver identity and live sync state. | |
| void | kleidos:: |
POST /api/gps/sync — start a one-shot clock sync from GPS. | |
| void | kleidos:: |
POST /api/gps/redetect — forget the cached receiver identity and re-run the auto-detect baud sweep. | |
| void | kleidos:: |
| Drain pending portal requests and advance a running sync. | |
| void | kleidos:: |
| Cancel any in-flight sync (powers the receiver down) and clear all pending flags and the published snapshot. | |
| void | kleidos:: |
| GET /api/groups — list every defined group with its member count. | |
| void | kleidos:: |
| Buffered body handler for POST /api/groups (rename or create). | |
| void | kleidos:: |
| Buffered body handler for DELETE /api/groups (label delete). | |
| void | kleidos:: |
| Buffered body handler for POST /api/groups/reset (drop the table). | |
| bool | kleidos:: |
Whether request may be served, by its Host authority. | |
| void | kleidos:: |
| Buffered body handler for POST /api/import/items. | |
| uint8_t | kleidos:: |
| Resolve a group NAME to its id, creating the group on first use. | |
| bool | kleidos:: |
A member whose value is text, or null when there is none. | |
| void | kleidos:: |
GET /api/wifi/networks — saved SSIDs (never their passphrases). | |
| void | kleidos:: |
POST /api/wifi/networks — save one network. | |
| void | kleidos:: |
DELETE /api/wifi/networks/:idx — forget one saved network. | |
| void | kleidos:: |
GET /api/ntp/servers — the effective time servers and their source. | |
| void | kleidos:: |
POST /api/ntp/servers — set one server slot. | |
| void | kleidos:: |
DELETE /api/ntp/servers — fall back to the built-in defaults. | |
| void | kleidos:: |
POST /api/ntp/sync — schedule a network clock sync for admin exit. | |
| bool | kleidos:: |
| Whether an on-exit NTP sync is armed (peek; does not clear). | |
| bool | kleidos:: |
| Take the on-exit NTP sync request, clearing it. | |
| void | kleidos:: |
| Drop a scheduled on-exit sync (admin exit safety net / debug jumps). | |
| void | kleidos:: |
| Serve the minimal OTA upload page (GET /update). | |
| void | kleidos:: |
| Receive a firmware image, stream it into an OTA session and finalize (POST /update). | |
| void | kleidos:: |
| GET /api/rotate — is a key rotation live, and how far has it gone? | |
| void | kleidos:: |
| POST /api/rotate — begin an in-place key rotation. | |
| void | kleidos:: |
| POST /api/rotate/step — advance the live rotation. | |
| void | kleidos:: |
| POST /api/rotate/finish — retire the previous vault key. | |
| void | kleidos:: |
| Put the vault on a new unlock secret (change PIN / passphrase / rekey). | |
| void | kleidos:: |
GET /api/sd/status: whether a card is seated, its size and use, and what it holds (backup, CSV files, keyfile, staged firmware). | |
| void | kleidos:: |
POST /api/sd/csv/import: import the CSV files in /kleidos/import/. | |
| void | kleidos:: |
POST /api/sd/audit/export: write the audit log to the card. | |
| void | kleidos:: |
| Body handler: creates the SD keyfile after proof of the unlock secret. | |
| void | kleidos:: |
| Body handler: deletes the SD keyfile after proof of the unlock secret. | |
| void | kleidos:: |
| Body handler: formats the card after proof of the unlock secret. | |
| void | kleidos:: |
Body handler: installs the firmware staged on the SD card (POST /api/sd/firmware/apply). | |
| void | kleidos:: |
| Fill the shared device-status object (version, counts, capacities). | |
| void | kleidos:: |
GET /api/bootstrap — model, capabilities, values and status in one. | |
| void | kleidos:: |
GET /api/capabilities — capability flags and vault capacities. | |
| void | kleidos:: |
GET /api/settings/schema — the offered options and their values. | |
| void | kleidos:: |
POST /api/settings/options — write a subset of option values. | |
| void | kleidos:: |
| GET /api/system — the six device-information blocks. | |
| void | kleidos:: |
| GET /api/system/partitions — the flash partition table. | |
| void | kleidos:: |
| GET /api/system/hardware — the board hardware inventory. | |
| void | kleidos:: |
| GET /api/system/crash — the address-only crash ring. | |
| void | kleidos:: |
| GET /api/ota/status — the firmware panel's read-out. | |
| void | kleidos:: |
| POST /api/system/selftest — run a named diagnostic suite. | |
| void | kleidos:: |
| POST /api/system/beep — queue an audible "locate me" cue. | |
| void | kleidos:: |
| POST /api/system/reboot — restart the device. | |
| void | kleidos:: |
| POST /api/system/sleep — lock the device and sleep. | |
| void | kleidos:: |
Populate the identity block: board, firmware, build flavor, address. | |
| void | kleidos:: |
Populate the storage block: filesystem bytes, record counts, image. | |
| void | kleidos:: |
Populate the security block: eFuse posture and KDF identification. | |
| void | kleidos:: |
Populate the power block from the FSM-refreshed snapshot. | |
| void | kleidos:: |
Populate the runtime block: uptime, restart cause, heap. | |
| void | kleidos:: |
Populate the soc block: silicon model, clocks, radios, die heat. | |
| BatterySnapshot | kleidos:: |
The battery figures of the device snapshot, for a route outside the power block. | |
| void | kleidos:: |
| Refresh the cross-core device snapshot; call from the FSM tick. | |
| bool | kleidos:: |
| Take the pending reboot request, clearing it. | |
| void | kleidos:: |
| Arm the pending reboot request (drained by the FSM's ADMIN_MODE tick). | |
| bool | kleidos:: |
| Take the pending beep request, clearing it. | |
| void | kleidos:: |
| Drop any queued action and the whole sampled snapshot; call when the portal stops. | |
| void | kleidos:: |
GET /api/telemetry — run state and recorded history. | |
| void | kleidos:: |
POST /api/telemetry/start — begin a capture. | |
| void | kleidos:: |
POST /api/telemetry/stop — end the capture this portal started. | |
| void | kleidos:: |
| Stop a telemetry run this portal started, if any. | |
| void | kleidos:: |
| GET /api/totp — list every stored TOTP entry with its parameters. | |
| bool | kleidos:: |
| Dynamic route handler for every :id-bearing TOTP route. | |
| bool | kleidos:: |
True when url is one of the live-code routes the SPA polls. | |
| constexpr Answer | kleidos:: |
| The answer to a body that could not be buffered. | |
| Answer | kleidos:: |
| The answer to a body the binder refused. | |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| constexpr bool | kleidos:: |
Whether the portal lists opt on a board with caps. | |
| constexpr std:: | kleidos:: |
| The schema's twoHolds field: whether the dial style is two holds. | |
| constexpr kleidos:: | kleidos:: |
| The parent a portal row names in its dependsOn. | |
| constexpr bool | kleidos:: |
| Whether the portal's schema lists an offered row right now. | |
| constexpr bool | kleidos:: |
| Whether a settings patch must carry proof of the unlock secret. | |
Variables | |
| constexpr size_t | kleidos:: |
| constexpr int64_t | kleidos:: |
| constexpr size_t | kleidos:: |
| constexpr const char * | kleidos:: |
| URL prefix of the dynamic per-host rename route. | |
| constexpr const char * | kleidos:: |
| URL suffix that follows the host index on the dynamic rename route. | |
| constexpr size_t | kleidos:: |
| Longest confirmation nonce, hex text plus terminator. | |
| constexpr size_t | kleidos:: |
| Largest number of ids accepted in one delete batch. | |
| constexpr const char * | kleidos:: |
| Confirmation action id the delete nonce is minted and spent under. | |
| constexpr size_t | kleidos:: |
| Maximum admin HTTP request body buffered in RAM (bytes). | |
| constexpr size_t | kleidos:: |
| Maximum length of a single inspected request/ | |
| constexpr size_t | kleidos:: |
| Maximum admin request URI length retained after stripping the query (bytes). | |
| constexpr uint8_t | kleidos:: |
| Consecutive receive timeouts tolerated while reading a body before giving up. | |
| constexpr const char * | kleidos:: |
| constexpr size_t | kleidos:: |
| constexpr const char * | kleidos:: |
| Log tag shared by the streaming responses (the portal's own tag). | |
| constexpr uint32_t | kleidos:: |
| Minimum spacing between two device-snapshot samples, in milliseconds. | |
| constexpr uint32_t | kleidos:: |
| Minimum spacing between two vault mounts for the storage figures, in milliseconds. | |
| constexpr uint32_t | kleidos:: |
| constexpr uint32_t | kleidos:: |
| Longest sampling period the API accepts, in milliseconds (one hour). | |
| constexpr uint32_t | kleidos:: |
| Sampling period used when the request body does not specify one. | |
| constexpr uint32_t | kleidos:: |
| constexpr uint32_t | kleidos:: |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| constexpr const char * | kleidos:: |
| Body of every out-of-memory answer, buffered or parsed. | |
| constexpr const char * | kleidos:: |
| Body of the answer to a body over its route's cap. | |
| constexpr const char * | kleidos:: |
| Body of the answer to a body that stopped arriving. | |
| constexpr const char * | kleidos:: |
| Body most routes answer text that is not JSON with. | |
| constexpr size_t | kleidos:: |
| The blank bytes the portal page puts before every JSON body and every restore's secrets. | |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| One credential with its notes (512 B alone) and its embedded TOTP block. | |
| constexpr size_t | kleidos:: |
| A group label and its id. | |
| constexpr size_t | kleidos:: |
| A batch delete: the selection's ids, or the confirmation nonce. | |
| constexpr size_t | kleidos:: |
| Text a slot id takes in a ranking of this build's slots. | |
| constexpr size_t | kleidos:: |
| A ranking naming every credential slot the build holds, plus its wrapper. | |
| constexpr size_t | kleidos:: |
| A settings patch: every option of the schema at once. | |
| constexpr size_t | kleidos:: |
| constexpr const char * | kleidos:: |
| constexpr size_t | kleidos:: |
| Most rows one settings patch may write. | |
Typedef Documentation
HostVerdict #
A transport's own verdict on a readable Host value (a debug link compares the address it was given); nullptr for a transport that has none.
UnlockSecret #
An unlock secret taken from a request. Holds the longest secret any entry surface accepts, security:: characters; a request carrying a longer one is refused before it is copied, never cut to fit.
Enumeration Type Documentation
AdminState #
AuthPolicy #
Declarative authentication policy applied to an admin route.
Each value is the ordered list of checks a route asks for: the per-address rate limit (AdminAuth::
BodyRead #
LinkKind #
Discriminator for the kind of transport behind an AdminLink.
The UI uses this to decide whether to show WiFi-only fields (SSID / password) or a generic link-reachability status.
| Enumerator | |
|---|---|
| WifiAp | WiFi SoftAP (WifiApLink). |
| WifiSta | WiFi station (debug LAN link). |
| Ethernet | Wired Ethernet; no link of this kind is built. |
| Null | No link / unset. |
NameCheck #
Outcome of validating a user-supplied BLE identity string.
| Enumerator | |
|---|---|
| Ok | Usable as-is; no truncation or substitution needed. |
| Empty | Zero length, or nothing but spaces. |
| TooLong | More than web:: |
| NotAscii | Holds a byte outside printable ASCII (0x20..0x7E). |
PatchShape #
What a settings patch said.
| Enumerator | |
|---|---|
| Rows | One object of rows, read into PatchReader:: |
| NotObject | One JSON value that is not an object. |
| Malformed | Not JSON, or a row whose value is not an integer or a boolean. |
Function Documentation
answerFor() [1/2] #
The answer to a body that could not be buffered.
- Parameters
-
Name Direction Meaning read in How buffering ended.
- Returns
- {0, nullptr} for
Ok; otherwise 413, 503 or 400 with its body.
answerFor() [2/2] #
The answer to a body the binder refused.
The binder allocates nothing, so a refusal is always the body's: text that is not JSON, a value of the wrong type or range, a key twice, a key the route does not take, too many entries. Each is answered 400 with the route's own words; a hook that refused an entry has said what it refused itself, and the route answers that before this is asked.
- Parameters
-
Name Direction Meaning result in What the bind returned. malformed in The route's own body for a body it cannot take.
- Returns
- {0, nullptr} when it bound; otherwise 400 with
malformed.
appendJsonEscapedSpan() #
Append a JSON-escaped string literal (with surrounding quotes) to output.
Append len bytes of value to output as a quoted, escaped JSON string.
Handles all RFC 8259 control characters: ", \\endiskip, \b, \f, \n, \r, \t, and codepoints below 0x20 which are emitted as \uXXXX sequences.
- Parameters
-
Name Direction Meaning output in, out The text being built. value in The bytes; nullptr reads as empty. len in Bytes of valueto write.
appendJsonEscapedString() #
The NUL-terminated form of appendJsonEscapedSpan.
- Parameters
-
Name Direction Meaning output in, out The text being built. value in The text; nullptr reads as empty.
appendPoolString() #
Append a pool entry's value as a JSON string, or "" when it is absent.
Append a pool entry's value as a JSON string, or "" when it is absent. The entry is escaped from the pool's own bytes: no copy, whatever its size.
- Parameters
-
Name Direction Meaning output in, out The text being built. pool in The credential's extras pool. type in The entry to write.
batteryReading() #
The battery figures of the device snapshot, for a route outside the power block.
The same values fillPowerBlock emits as percent and charging, so /api/status and /api/system report one sample and cannot disagree. Reads the snapshot only; it never reaches the PowerManager, so it is safe on the httpd task.
- Returns
- The last sampled reading;
knownis false until the battery has read once (a route reports the figures as unknown then, never 0 %).
checkName() #
Validate a BLE identity string against the name rules of every board.
A name is accepted when it is 1..web::
Side-effect free and header-only so the rule is native-testable without the BLE stack.
- Parameters
-
Name Meaning name Candidate name; need not be NUL-terminated within length.length Number of bytes to inspect.
- Returns
- The first rule the candidate breaks, or
NameCheck::Ok.
confirmNonceTtlSeconds() #
Seconds a minted nonce stays valid.
- Returns
- The TTL in seconds, for the
expires_sfield of a prepare response.
decimalDigits() #
Decimal digits value is written with.
- Parameters
-
Name Direction Meaning value in The number.
- Returns
- Its digit count, 1 for 0.
endPortalSession() #
Stop a telemetry run this portal started, if any.
Called from AdminPortal:: so the sampler task and its ring cannot outlive the admin session (and so nothing samples the PMIC across a deep sleep). Ownership-guarded: a run started from the debug serial console is left alone. Idempotent and safe to call when telemetry was never used.
Does not wait for the sampler — AdminPortal:: runs on the Core-1 loop task. The stop is latched here and completed by the loop task's own telemetry pump; see ::
Always leaves the ownership claim cleared: the session that held it is over, so no claim may survive into the next one (see the file-header Ownership notes).
endSessionWithRestart() #
End the session with a restart: what every factory reset from the portal owes.
Asks the FSM for a reboot (web::) and for the relocking teardown (requestSessionEnd), so the restart that finishes a factory reset (the NVS erase at the top of the next boot) follows the reply at once, instead of a relock and a deep sleep that could hold the previous owner's NVS on the flash for days. Called after the response is sent.
fillIdentityBlock() #
Populate the identity block: board, firmware, build flavor, address.
Emits model, variant, version, flavor, build_date, git_sha and mac. build_date and git_sha are null until the build injects them, and mac is the Bluetooth identity address — the one a host's pairing list shows — read from the SoC base MAC, which works with the BLE host down as it always is in ADMIN_MODE.
These helpers only write into the object they are handed — they never send a response — so any other endpoint can compose them into its own payload.
- Parameters
-
Name Direction Meaning out in, out Writer inside the object to fill.
fillPowerBlock() #
Populate the power block from the FSM-refreshed snapshot.
percent, batt_mv, charging and pmic are emitted on every board; the per-PMIC extras are emitted as null when the back-end cannot sample them, never omitted, so one page renders every board.
- Parameters
-
Name Direction Meaning out in, out Writer inside the object to fill.
fillRuntimeBlock() #
Populate the runtime block: uptime, restart cause, heap.
uptime is in seconds, and wake_reason is the empty string on a boot that was a reset rather than a deep-sleep wake.
- Parameters
-
Name Direction Meaning out in, out Writer inside the object to fill.
fillSecurityBlock() #
Populate the security block: eFuse posture and KDF identification.
Posture only. The attempt counter and the lockout thresholds are GET /api/security/posture and /api/security/lockout; a second copy here would be a second source of truth and an NVS read per poll.
- Parameters
-
Name Direction Meaning out in, out Writer inside the object to fill.
- Warning
- SECURITY: booleans and public constants only — never key material.
fillSocBlock() #
Populate the soc block: silicon model, clocks, radios, die heat.
The die temperature lives here rather than in power because it is the SoC's own sensor, not the PMIC's; it is still sampled on the UI core, since reading it installs and removes a driver.
- Parameters
-
Name Direction Meaning out in, out Writer inside the object to fill.
fillStatusPayload() #
Fill the shared device-status object (version, counts, capacities).
One builder behind both /api/status and the status block of /api/bootstrap, so a polled dashboard and a first paint can never disagree about how full the vault is.
The battery and charging members come from the device snapshot (web::), the same sample /api/system reports, so the dashboard and the System page cannot disagree either.
- Parameters
-
Name Direction Meaning out in, out Writer inside the object the members go into.
fillStorageBlock() #
Populate the storage block: filesystem bytes, record counts, image.
total / used / free describe the vault filesystem. They need the vault mounted, which is why they are sampled at most once per kStorageSampleIntervalMs and served from a cache in between: this block sits behind a route the page polls. All five vault-derived members become null when the mount fails, so a failure reads as "unknown", not "empty".
- Parameters
-
Name Direction Meaning out in, out Writer inside the object to fill.
handleApCredentialsClear() #
DELETE /api/ap/credentials — back to a random password per session.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleApCredentialsSet() #
POST /api/ap/credentials — pin the access point's SSID and password.
Opt-in convenience for joining from a computer, where re-reading a fresh password off the device every session is unpleasant. It is a real reduction in posture — a pinned password is reusable by anyone who reads it once — so it takes the unlock secret like any other change that weakens a defense, and the password is write-only: it is never returned, only shown on the device.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleApStatus() #
GET /api/ap — access-point identity and client count (no password).
The AP password is deliberately absent. It is the real authentication boundary and is shown on the device screen precisely so it never crosses the network it protects.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleAudit() #
GET /api/audit — the audit history, content-negotiated.
Answers the JSON array (ts / event / attempts per entry) by default; when the request's Accept header names text/csv it answers a real CSV document instead, in the exact wire shape of the SD-card audit export (security/), with a Content-Disposition attachment filename. Event names come from auditEventName in both forms.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleBackupGet() #
GET /api/backup — stream the whole vault as a plaintext backup, with consent.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleBeep() #
POST /api/system/beep — queue an audible "locate me" cue.
Records a beep request and answers immediately; the FSM plays the tone on the UI core (the I2S/PWM speaker path may block briefly and shares the crypto hardware lock, so it must not run on the httpd task). A board with neither speaker nor buzzer answers 404 rather than pretending to queue a tone nothing will ever play.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleBleForgetAll() #
POST /api/ble/hosts/forget-all — de-bond every paired host.
Re-pairing recovers it, so this is not two-step — but it still proves the unlock secret, and it records AuditEvent:: before acting: a pairing is what lets the device type into a machine, and all of them vanishing at once is what a non-repudiation record exists to capture.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleBleHostsGet() #
GET /api/ble/hosts: the bonded hosts in the owner's order.
- Parameters
-
Name Direction Meaning ctx in, out The request's context.
handleBleNameGet() #
GET /api/ble/name — report the advertised BLE device name.
Answers {"name":..,"max_
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleBleNameSave() #
POST /api/ble/name — persist a new advertised BLE device name.
Body: {"name":"..."}. Replies 400 (reason from web::
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleBootstrap() #
GET /api/bootstrap — model, capabilities, values and status in one.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleCapabilities() #
GET /api/capabilities — capability flags and vault capacities.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleCrashGet() #
GET /api/system/crash — the address-only crash ring.
Emits {boot, count, capacity, firmware:{...}, records:[...]}, where each record is {reason, core, uptime, boot, truncated, elf_sha,
fw_version, current, frames:[{pc, sp}, ...]} taken from kleidos::. A production build prints no panic output on the serial port, so this is the only way to learn why a production device restarted. Addresses are hex text; resolve them against the matching firmware.elf with the toolchain's addr2line.
The top-level firmware object describes the image running now (version, full elf_sha256, project, IDF version, build stamp, secure version); each record carries its own elf_sha / fw_version, because a record captured before an OTA describes a binary the device no longer runs. current is false exactly in that case — resolve those addresses against the older ELF, not the running one.
- Warning
- SECURITY: the payload is program counters, stack POINTERS, an enum and three counters — never a byte read through those pointers. The stacks they point into hold secret-derived and key-equivalent material while the vault is unlocked, which is why this route reports addresses only and why the ESP-IDF core dump (which stores those bytes verbatim) stays debug-only. Session-authenticated like every other
/api/systemread.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleCredentialBatchDeleteCommit() #
POST /api/credentials/delete/commit — erase the staged batch.
Body {"nonce":"<hex>"}. The nonce is spent through web:: (one shot, TTL-bound, matched to this action and this session); the ids come from what the prepare staged, never from this body.
The staged ids are erased through VaultStore:: — one meta commit and one index rewrite for the whole batch, so the flash cost on this HTTP task stays flat in the batch size instead of two encrypted rewrites per id.
What stays per id is whole-segment work: an index segment the batch cannot trust is repaired from a full record scan, and each targeted segment is then judged for compaction. On a full vault the batch runs longer than the portal's idle timeout, which the UI core enforces while this HTTP task is blocked, so the call carries a heartbeat that stamps the session clock as it walks.
The reply is {"ok":true,"atomic":false,"deleted":[...],"failed":[...]}. failed holds the ids that had no record to erase (absent slots). atomic is always false and is in the payload on purpose: the record removals are independent, so a client must read the two arrays rather than assume the whole batch shares one outcome.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the whole body. total in Total declared body length in bytes.
handleCredentialBatchDeletePrepare() #
POST /api/credentials/delete/prepare — stage a delete batch.
Body {"current":"<unlock secret>","ids":[...]}. The ids are validated first (at most kMaxBatchDeleteIds, each a whole number inside the vault's slot range, no duplicates) so a malformed request is refused before the ~1.4 s key derivation runs. The secret is then verified through web::, which owns the lockout, the attempt counter and the single generic 403.
On success the batch is staged and the reply is {"nonce":"<hex>","expires_
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the whole body. total in Total declared body length in bytes.
handleCredentialFavorite() #
POST /api/credentials/favorite — set or clear one record's favorite flag. The flag lives in the credential record, so this is a record write, and the reply carries the list column back for the panel to re-render from.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleCredentialOrder() #
POST /api/credentials/order — realize a ranking with the fewest record writes. A plan wider than kleidos::
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleCredentialOrderRespace() #
POST /api/credentials/order/respace — RE-SPACE a ranking: every row back onto the evenly spaced label of its position, with no cap on how many records that rewrites. The ordinary ordering route realizes a ranking with the fewest record writes and refuses a plan wider than kleidos::
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleCredentialRoute() #
Dynamic route handler for GET /api/credentials/:id.
Reads the live vault key from ctx.state to service the request. GET only: a bare DELETE would destroy a credential on nothing but a session token, so deletes — single or batch — go through the confirmed POST /api/credentials/delete/{prepare,commit} pair instead (a single delete is a batch of one); any other method answers 405.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. id in Credential index parsed from the request URL.
handleExportCsv() #
GET /api/export/csv — stream the credentials as CSV, with consent.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleExportEncrypted() #
POST /api/export/encrypted — stream the whole vault sealed under a passphrase.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleExportJson() #
GET /api/export/json: every credential in plaintext, streamed a row at a time behind the plaintext consent header.
GET /api/export/json — stream the credentials as JSON, with consent.
- Parameters
-
Name Direction Meaning ctx in, out The request's context.
handleFactoryResetCommit() #
POST /api/factory-reset/commit — erase everything and restart.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleFactoryResetPrepare() #
POST /api/factory-reset/prepare — verify the secret, mint a nonce.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleGpsRedetect() #
POST /api/gps/redetect — forget the cached receiver identity and re-run the auto-detect baud sweep.
Raises the redetect flag; the ADMIN_MODE tick runs the sweep (bounded, and refused while a sync holds the UART).
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleGpsStatus() #
GET /api/gps/status — receiver identity and live sync state.
SessionReadOnly: the page renders it on panel load and may poll it while a sync runs, and a poll must not hold the idle window open.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleGpsSyncStart() #
POST /api/gps/sync — start a one-shot clock sync from GPS.
Raises the start flag; the ADMIN_MODE tick starts the engine. Answers 202 with the accepted intent (or a busy refusal while a sync is running).
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleGroupDelete() #
Buffered body handler for DELETE /api/groups (label delete).
- Parameters
-
Name Direction Meaning ctx in Request context. data in Body bytes received so far. len in Length of data.index in Offset of datawithin the whole body.total in Total body length.
handleGroupList() #
GET /api/groups — list every defined group with its member count.
- Parameters
-
Name Direction Meaning ctx in Request context (session already validated by the dispatcher).
handleGroupSave() #
Buffered body handler for POST /api/groups (rename or create).
- Parameters
-
Name Direction Meaning ctx in Request context. data in Body bytes received so far. len in Length of data.index in Offset of datawithin the whole body.total in Total body length.
handleGroupTableReset() #
Buffered body handler for POST /api/groups/reset (drop the table).
Verifies the unlock secret through the shared destructive-confirm gate, then removes the label file. Records keep their group bytes; the list blanks the group column while no id carries a label.
- Parameters
-
Name Direction Meaning ctx in Request context. data in Body bytes received so far. len in Length of data.index in Offset of datawithin the whole body.total in Total body length.
handleHardwareGet() #
GET /api/system/hardware — the board hardware inventory.
Emits a JSON array of {part, chip, bus, detail} rows built from the variant feature map and enriched with the chip-probe observations the UI core sampled from the register-map registry and the drivers' own presence probes. Only parts this board actually fits are listed: the page renders an inventory of what the device has, not of what it lacks. A chip name is either a per-variant hardware constant or a probed identity — a part whose probe has not answered reads "unidentified", never a name guessed from a build flag.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleImportItems() #
Buffered body handler for POST /api/import/items.
- Parameters
-
Name Direction Meaning ctx in, out Per-request context (request + portal state + auth). data in Body bytes buffered so far. len in Length of the newest chunk. index in Offset of the newest chunk within the body. total in Declared body length; the handler answers only once the final chunk arrived.
handleListCredentials() #
GET /api/credentials — list every stored credential, widened.
Serves one JSON array of objects {id, name, user, favorite, order, hasTotp, mtime}, sourced entirely from the encrypted list index (VaultStore::), so the whole response costs a single file read plus a single decrypt regardless of vault size.
There is no row buffer: each row is serialized into the document as the index decodes it. A capacity-sized one would be sizeof(IndexEntry) per vault slot, which neither fits the 8 KB HTTP server task stack nor, on a PSRAM-less board, the largest contiguous internal block an admin session leaves free.
A response is only sent once the whole array is known to have been built: a document that ran out of heap part-way is refused with 500 rather than sent, because a silently short array reads as "these are all your credentials".
- Note
- mtime is emitted but is 0 on every row: both writers pass now = 0 to
CredentialRepository::, and the column is not cached in the index either. Read 0 as "unknown".saveTo
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context (reads the live vault key from ctx.state).
handleNotFound() #
Not-found dispatcher: redirects unknown non-API GETs to the panel, then enforces Session and dispatches the dynamic per-resource routes.
Registered as the onNotFound handler with AuthPolicy:: so the non-API GET shortcut stays pre-auth; the dynamic /api/ sub-routes are gated by an explicit Session policy run inside this handler. /api/ paths keep honest 404s — a redirect would hand the panel's own fetches an HTML body they cannot parse.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleNtpListGet() #
GET /api/ntp/servers — the effective time servers and their source.
Reports whether the list in effect is the owner's or the built-in defaults: an empty list with no explanation is exactly the confusion the device's own screen avoids.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleNtpReset() #
DELETE /api/ntp/servers — fall back to the built-in defaults.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleNtpSet() #
POST /api/ntp/servers — set one server slot.
Body: {"idx": n, "ip": "a.b.c.d"}. Literal IPv4 only — enforced by VaultStore:: itself, so a hostname cannot enter the clock path through this route any more than through the device's own.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleNtpSyncSchedule() #
POST /api/ntp/sync — schedule a network clock sync for admin exit.
The device cannot run its own access point and join the owner's network at the same time, so an NTP sync can never run WHILE the portal is up. This route arms a deferred sync instead: the ADMIN_MODE teardown drains the flag after the portal (and its access point) is down and runs the one-shot engine (kleidos::
Body: {"when":"on-exit"} (the only supported value; an absent field means the same). Refused with 400 when the saved-network store is empty — a scheduled sync that could only fail after the session ended would fail with nobody watching.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleOtaPageGet() #
Serve the minimal OTA upload page (GET /update).
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleOtaStatus() #
GET /api/ota/status — the firmware panel's read-out.
Emits {running, image_size, next_POST /update behind its own password.
Registered only on OTA-capable variants (NO_OTA == 0); a 4 MB single-slot board answers 404 and the page hides the panel from the same capability.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleOtaUpload() #
Receive a firmware image, stream it into an OTA session and finalize (POST /update).
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handlePartitionsGet() #
GET /api/system/partitions — the flash partition table.
Emits a JSON array of partition descriptors in esp_ order, flagging the running app partition. type and subtype are the tokens the layout CSV spells ("app"/"data", "ota_0", "littlefs"), not the raw bytes, and addr is the hex offset as text — the page prints all three verbatim.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleReboot() #
POST /api/system/reboot — restart the device.
Answers 200 first, then raises the reboot flag. The restart itself happens on the FSM tick so the portal is torn down and the vault key zeroized before the SoC resets — esp_restart() preserves RAM until .bss init, so the order matters.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleRekey() #
Put the vault on a new unlock secret (change PIN / passphrase / rekey).
Buffered JSON body handler for POST /api/rekey. The request carries the CURRENT unlock secret, the NEW unlock secret and an optional numeric PIN length ({"current":..,"next":..,"pin_next value plus the presence of pin_length.
It runs VaultStore::, which is the opening of a rotation: one write of the vault metadata puts the vault under the new secret and a NEW vault key, with the retired key sealed beside it. The new key becomes the session token, and the reply is the rotation's opening, as handleRotateBegin answers it (live, frontier, end, skips, the one-shot nonce, expires_s), so the page walks it with handleRotateStep and retires the old key with handleRotateFinish. A change while a rotation is live is refused with 409 before the current secret is weighed.
reencrypt is refused with 400: every change re-encrypts now, so there is nothing left for the flag to ask, and a request that sends it was written for the route as it was.
- Warning
- SECURITY: verifies the CURRENT secret with
VaultStore::before re-keying — the admin session token alone is NOT sufficient, so a hijacked session cannot silently change the unlock secret. A failed verification feeds the sharedunlockVault BruteForceGuardcounter exactly like a failed on-device unlock (escalating lockout, a factory reset at the tenth failure). No secret (current, new, or derived key) is ever placed in the response body or a log line; every transient is zeroized.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context (reads the live vault key pointer from ctx.stateand updates it on success).data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleRotateBegin() #
POST /api/rotate — begin an in-place key rotation.
Proves the unlock secret through the shared destructive gate (brute-force counter, one generic 403, no oracle) and then mints a NEW vault key with the SAME secret: a rotation replaces the key the records are encrypted under, not the way in. On success it returns a one-shot nonce for handleRotateFinish — the irreversible half of this two-step flow — so that half cannot be replayed or aimed at another action.
Mutations are refused for the whole rotation, so a caller that begins one owes it a finish.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleRotateFinish() #
POST /api/rotate/finish — retire the previous vault key.
The irreversible half: after it, any copy of the old meta.bin plus the old secret opens nothing that was rotated. Consumes the nonce handleRotateBegin minted, refuses while the frontier is short of the end, and refuses over any recorded skip unless the body carries an explicit acknowledgement — those artifacts are still under the retired key and become unreadable the moment it is destroyed.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleRotateStatus() #
GET /api/rotate — is a key rotation live, and how far has it gone?
Read-only and session-authed. Reports the frontier as a fraction of the whole order plus whether any artifact was skipped, which is what the caller needs to decide between finishing and finishing with consent.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleRotateStep() #
POST /api/rotate/step — advance the live rotation.
Session-authed only, and deliberately so: stepping proves nothing new and destroys nothing. It is time-boxed rather than run to completion, because a full vault is minutes of work and an HTTP request that holds for minutes is a request that times out somewhere and leaves the caller guessing. The reply carries the frontier, so the caller drives the loop and can show real progress instead of a spinner.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleSdAuditExport() #
POST /api/sd/audit/export: write the audit log to the card.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleSdCsvImport() #
POST /api/sd/csv/import: import the CSV files in /kleidos/import/.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleSdFirmwareApply() #
Body handler: installs the firmware staged on the SD card (POST /api/sd/firmware/apply).
Writes /kleidos/firmware/firmware.bin to the inactive OTA slot via SdVault::, removes the staged file, answers, and arms the FSM reboot (the same teardown ordering as POST /api/system/reboot: the response leaves the socket, then the portal comes down, key material is wiped, and the device restarts into the new image under the rollback guard).
Replacing the running firmware from the network is as consequential as any wipe, so the body carries the unlock secret through the admin_confirm gate ({"current":"<unlock secret>"}); a bare session token is refused.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleSdFormat() #
Body handler: formats the card after proof of the unlock secret.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleSdKeyfileDelete() #
Body handler: deletes the SD keyfile after proof of the unlock secret.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleSdKeyfileGenerate() #
Body handler: creates the SD keyfile after proof of the unlock secret.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleSdStatusGet() #
GET /api/sd/status: whether a card is seated, its size and use, and what it holds (backup, CSV files, keyfile, staged firmware).
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleSecurityLockout() #
GET /api/security/lockout — attempts used, lock remaining, policy.
Strengthens the brute-force defense rather than weakening it: an owner who can see "3 of 10 used" can act before the tenth failure resets the device. Read-only by contract; the thresholds are compile-time constants.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleSecurityPosture() #
GET /api/security/posture — secret kind, KDF, binding, boot flags.
Reports protections; it can never change one. The length and modality of the unlock secret are not the secret — the digit count is observable to anyone watching an unlock — and the page needs them to show a PIN form or a passphrase form.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleSelfTest() #
POST /api/system/selftest — run a named diagnostic suite.
Body: {"suite":"crypto"}. Only "crypto" exists; any other value is rejected with 400. The crypto suite runs the published known-answer vectors through the production primitives and answers {"pass":…,"cases":…,"detail":"…","vectors":[{"name":…,"pass":…}]} — the summary the page prints plus the per-vector rows behind it.
- Note
- The suite runs inline on the httpd task. That is only acceptable because the vectors pin their own iteration counts (both the PBKDF2 vector and the vault-envelope round trip derive with c=1), so the work is sub-millisecond — it is NOT the production work factor. The one slow path is contention: the primitives take the shared crypto/audio hardware lock, so if a vault derivation is running when the request lands, the handler blocks until that derivation finishes.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleSessionEnd() #
POST /api/session/end — leave admin mode cleanly.
Sets a flag the FSM consumes on its next tick; it never tears the server down from inside a handler. The response is sent first, so the browser sees the acknowledgement before the access point goes away underneath it.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleSessionLock() #
POST /api/session/lock — relock the vault and end admin mode.
The same teardown as handleSessionEnd — leaving admin mode puts the device to sleep, which is what wipes the vault key. Two endpoints because the page offers two intents, one behavior because the device has one exit.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleSettingsOptions() #
POST /api/settings/options — write a subset of option values.
Accepts any subset of the keys this board offers; an unknown or gated-out key is a 400 with the offending key named, never a silent no-op. Each accepted value is applied on the UI core and the response echoes the stored values read back afterwards, so a clamp or a cross-row timer repair is visible to the page instead of leaving it showing a value the device rejected.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the whole body. total in Total body length in bytes.
handleSettingsReset() #
POST /api/settings/reset — restore preference defaults.
One step, not two: it destroys no credential, so the secret alone is the right weight of proof. It can still turn shake-to-lock off and shorten a relock timer, which is why it is gated at all.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleSettingsSchema() #
GET /api/settings/schema — the offered options and their values.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleSleep() #
POST /api/system/sleep — lock the device and sleep.
The same intent as POST /api/session/lock, so it is that handler: one flag, one FSM drain, one teardown ordering (radios down, key wiped, filesystem unmounted). The route exists separately because the page groups it with the other device actions.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleSystemGet() #
GET /api/system — the six device-information blocks.
Emits one JSON object with the identity, storage, security, power, runtime and soc members produced by the fill helpers below. Cheap enough for the page to poll: no bus traffic, no crypto, and the vault mount behind the record counts is rate-limited to one per kStorageSampleIntervalMs.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleTelemetryGet() #
GET /api/telemetry — run state and recorded history.
Answers with the columnar body built by web:: (see telemetry_ for the size arithmetic), streamed out in ::
The body carries the newest ::fill reports how many the ring actually holds, so a page can tell it is looking at a window. Both bounds exist because this is the route the page polls once a second for a whole session — see the two constants for the reasoning.
Also finishes any teardown a previous stop left pending — that is a no-op unless a stop was already requested, so this stays a read of the service and never ends a healthy run.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleTelemetryStart() #
POST /api/telemetry/start — begin a capture.
Body (all fields optional):
period_ms is clamped to [::channels selects every registered channel. Replies 409 when a run is already active, 400 when channels resolves to no known channel.
- Warning
- SECURITY: streaming is hard-coded off; see the file-header warning.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context. data in Body chunk pointer. len in Length of this chunk. index in Offset of this chunk within the full body. total in Full declared body length.
handleTelemetryStop() #
POST /api/telemetry/stop — end the capture this portal started.
Waits at most ::409 when no run is active or when the active run belongs to the debug console. If the sampler has not exited within the budget the reply carries "pending":true — the run's teardown is latched and completes on the next poll of handleTelemetryGet().
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleTimeDiag() #
GET /api/time/diag — hardware-clock health (VL flag, alarm, timer).
The one bit that matters is vl: the BM8563's voltage-low flag latches when the coin cell dies, and from then on lockout timers silently stop surviving a full power-off. The page renders it as "replace the coin cell". Also reports the alarm and countdown-timer state as human-readable text (shaped by the host-tested admin_chip:"internal", vl:false) — the page hides the card via the rtc capability anyway.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleTimeGet() #
GET /api/time — clock, trust, provenance and the zone table.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleTotpList() #
GET /api/totp — list every stored TOTP entry with its parameters.
Emits [{"id","name","digits","period","hasSecret"}, …]. One vault worker pass: the listing decrypts each record once and keeps the generator parameters, instead of following the listing with a per-id load.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleVaultReindex() #
POST /api/vault/reindex — rebuild the encrypted list index.
The portal's way to run the recovery action that rebuilds the index. VaultStore:: marshals itself onto the vault worker (which feeds the caller's watchdog), so the httpd task blocks on the completion, not on flash I/O. Rebuilding is not destructive at all: every column of every row, favorites and manual order included, is read back out of the credential records the rebuild decrypts.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
handleVaultWipeCommit() #
POST /api/vault/wipe/commit — the vault-only wipe.
Body {"nonce","current"}: the nonce is taken first (one shot), then kleidos:: runs on the secret sent again (the server stores none between the two requests). Credentials, one-time codes and saved networks go; the unlock secret, the pairings, the access-point identity and every preference stay. 200 with secret_kept on a proven secret (the device restarts), 500 when the erase did not finish (the next boot does), 403 for a wrong secret (the FULL wipe at the threshold), 429 under a lockout, 409 / 503 when nothing could be weighed.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleVaultWipePrepare() #
POST /api/vault/wipe/prepare — verify the secret, mint a nonce.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleWifiAdd() #
POST /api/wifi/networks — save one network.
Body: {"ssid": "...", "pass": "..."}. An empty pass means an open network; otherwise WPA's own 8..63 range applies. The passphrase reaches the same encrypted store as the vault's own secrets; only the SSID and the length are ever logged.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body chunk bytes. len in Length of datain bytes.index in Byte offset of this chunk within the body. total in Total body length in bytes.
handleWifiDelete() #
DELETE /api/wifi/networks/:idx — forget one saved network.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
handleWifiListGet() #
GET /api/wifi/networks — saved SSIDs (never their passphrases).
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context.
hasPlaintextConsent() #
Return true when the request carries an explicit plaintext-export consent token.
True when the request carries the page's plaintext-export consent header; documented at its definition.
Plaintext credential exports (backup JSON, export CSV, export JSON) require the client to send the X-Confirm-Plaintext: true header, which the SPA sets only after a confirm() dialog that warns the user and points to the safer encrypted export endpoint.
SECURITY: this is a UI confirmation and CSRF speed bump only — it is a client-set header, NOT a device-side second factor. Any client already holding a valid session token can set it, so it does not raise the bar beyond the session gate. It is a deliberate guard against accidental clicks and naive cross-origin requests, not an out-of-band approval. A true second factor would require a physical button confirmation on the device before the export completes, which is not built.
- Parameters
-
Name Direction Meaning ctx in The incoming request context.
- Return values
-
Value Meaning true Header present and equal to "true".false Header absent or has a different value.
isPolledTotpCodeRoute() #
True when url is one of the live-code routes the SPA polls.
Lets the not-found dispatcher pick AuthPolicy:: for the polled routes and AuthPolicy:: for everything else.
- Parameters
-
Name Direction Meaning url in Request URL, already stripped of its query string.
- Return values
-
Value Meaning true /api/totp/:id/code or /api/credentials/:id/totp/code. false Any other URL.
listedForPortal() #
Whether the portal's schema lists an offered row right now.
A row whose parent the page can see is always listed (the page hides it while the parent is off). A row whose parent is device-only is listed only while that parent holds the value the device lists it under, as the device's own menu does.
- Parameters
-
Name Direction Meaning opt in A settings row. caps in The board's capabilities. parentValue in The stored value of opt'sparent (ignored when it has none).
- Return values
-
Value Meaning true The schema carries the row now.
memberOrNull() #
A member whose value is text, or null when there is none.
The shape a document model gave a null const char*: a client reads null as "not known", where an empty string would read as "known to be empty".
- Parameters
-
Name Direction Meaning out in, out The writer. name in Key. text in Stored text, or nullptr.
- Returns
- False when the writer refused.
mintConfirmNonce() #
Mint a one-shot nonce for action, bound to the live session.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context (source of the session token). action in Action id the nonce authorizes (e.g. "wipe").out out Destination buffer for the hex nonce. cap in Capacity of out; use kConfirmNonceCap.
nameCheckReason() #
Machine-readable reason token for a rejected name.
Returned to the client as the reason field so the SPA can pick its own wording instead of parsing prose.
- Parameters
-
Name Meaning check Validation outcome to describe.
- Returns
- Static lowercase token;
"ok"whencheckisNameCheck::Ok.
ntpSyncOnExitArmed() #
Whether an on-exit NTP sync is armed (peek; does not clear).
- Return values
-
Value Meaning true A sync is scheduled for the admin teardown. false Nothing scheduled.
offered() #
Whether the portal lists opt on a board with caps.
- Parameters
-
Name Direction Meaning opt in A settings row. caps in The board's capabilities.
- Return values
-
Value Meaning true The row carries a value, is persisted, is offered on this board and is not one the device keeps to itself.
orderBytesPerId() #
Text one slot id takes in a ranking of slots slots at most: the digits of the largest id, its comma, a space a client may write after it, and one byte of margin.
- Parameters
-
Name Direction Meaning slots in The slot count the ranking names.
- Returns
- Bytes per id.
parseCredentialId() #
Parse a credential index from a /api/credentials/:id URL.
- Parameters
-
Name Direction Meaning url in Request URL to parse the trailing numeric id from.
- Returns
- Parsed credential index, or ::
kInvalidSlot if the URL has no valid id.
parseHostNamePath() #
Match /api/ble/hosts/<idx>/name and extract the host index.
Matches the whole path exactly — a trailing segment, a missing index, or a non-decimal index is not a match — so the caller can fall through to the other dynamic routes. Values that do not fit a uint8_t are rejected as a non-match; no bond slot can ever reach them.
- Parameters
-
Name Direction Meaning url in Request URL, already stripped of any query string. outSlot out Receives the parsed index on a match; untouched otherwise.
- Return values
-
Value Meaning true urlis exactly this route andoutSlotholds the index.false urlis some other path.
parseUnsignedSuffix() #
Parse a decimal numeric suffix appended after a URL prefix (e.g. "/api/credentials/3").
Parse the decimal id that follows prefix in url; documented at its definition.
- Parameters
-
Name Direction Meaning url in NUL-terminated URL string. prefix in Required leading prefix; urlmust start with this.maxExclusive in Maximum acceptable value (exclusive). out out Receives the parsed number on success.
- Returns
- true if a valid decimal number in the range
[0, maxExclusive) followed the prefix.
patchNeedsSecret() #
Whether a settings patch must carry proof of the unlock secret.
- Parameters
-
Name Direction Meaning ids in The rows the patch writes, already resolved. count in Number of entries in ids.
- Return values
-
Value Meaning true At least one row is one the portal changes only behind the secret (kleidos:: settings:: needsUnlockSecret).
portalDependsOn() #
The parent a portal row names in its dependsOn.
The page lists a dependent row only while the value it names is on, and it never sees a row the device keeps to itself: a row depending on one (the PIN dial speed, which depends on the dial style) would never be listed. Such a row names no parent; the device resolves the dependency itself (listedForPortal).
- Parameters
-
Name Direction Meaning opt in A settings row.
- Returns
- The row's parent, or
OptionId::when it has none or the parent is device-only.None
proveSecretForLoss() #
Prove the unlock secret for an edit that destroys a stored secret.
Prove the unlock secret for an edit that destroys a stored secret; documented at its definition.
The bar a delete of the same content sets, through the same gate: the secret travels in the body as "current", the brute-force counter weighs it and a wrong one gets the generic 403. A body that carries no secret is answered 400 naming what the edit would destroy, so the page can say it before it asks. The gate mounts the vault itself, so the caller's mount is ended here and taken again once the secret is proven.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context; any refusal is sent here. data in Body bytes. len in Length of data.loss in What the edit would destroy; at least one field is set.
- Return values
-
Value Meaning true The secret is proven and the vault is mounted again. false Refused; a response was sent and the vault is not mounted.
pump() #
Drain pending portal requests and advance a running sync.
Called once per ADMIN_MODE tick on the Core-1 loop task — the only task allowed to touch the GPS engine. Costs two relaxed loads when idle.
readUnlockSecretFromBody() #
Take the unlock secret out of a JSON request body.
Reads {"current": "..."} through a zeroizing allocator — the pool briefly holds the secret — and copies it into out. A secret longer than security:: is refused here, before the copy, with the same 400 verifyUnlockSecret sends, so no buffer size decides what is verified. An absent or empty secret is not refused here; the verify answers it.
For a route that uses the verified bytes afterwards (the key rotation seals its new vault key under them): read once, verify, use the same buffer, so the bytes verified are the bytes used. The caller wipes out with secureZeroize on every path.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context (receives the reject response). data in Body bytes. len in Length of data.out out Receives the secret; empty on refusal.
- Return values
-
Value Meaning true outholds the body's secret, possibly empty.false Refused; a 400 was sent.
refreshDeviceSnapshot() #
Refresh the cross-core device snapshot; call from the FSM tick.
Samples everything /api/system and /api/system/hardware may not read for themselves: the PMIC over I2C, the SoC temperature sensor (which installs and removes a driver), the register-map registry, and the probed part identities. The PMIC name comes from its back-end's chip-id probe; the IMU, touch and keyboard names come from the resolved driver instances in the board record, which — like the registry — bring-up and input polling keep Core-1-owned.
The registry read belongs here rather than in the handler because the registry is a plain non-atomic array that is written after bring-up: a PowerManager back-end whose boot probe transiently NACKed re-probes lazily on its next battery read, and a successful re-probe registers the chip's map. Both that write and every other registry reader (a debug build's console) live on the UI core, so sampling here keeps the structure single-threaded instead of introducing the first cross-core reader.
Self-throttling: samples at most once per kPowerSampleIntervalMs, so it is safe to call on every loop iteration. AdminPortal:: calls it once before the access point comes up, so the first authenticated request already finds a sample; the ADMIN_MODE tick keeps it fresh from then on.
- Parameters
-
Name Direction Meaning pm in, out Power back-end for the running board.
requestHostIsAllowed() #
Whether request may be served, by its Host authority.
- Parameters
-
Name Direction Meaning request in The request; its one header slot is reused. apIp in The address the link reports; empty admits nothing by address. apName in The captive host name the SoftAP's DNS answers with. linkVerdict in The transport's own verdict, asked only of a value that was read whole; nullptr when there is none.
- Return values
-
Value Meaning true No Host, or one the portal answers at.false A foreign authority, or a Hostthat could not be read.
requestReboot() #
Arm the pending reboot request (drained by the FSM's ADMIN_MODE tick).
For handlers that finish an action whose effect requires a restart (e.g. the SD-staged firmware install setting the boot partition): answer the request first, then call this — the next FSM tick tears the portal down, wipes key material, and restarts, exactly as POST /api/system/reboot does.
requestSessionEnd() #
Ask the FSM to tear the portal down on its next tick.
Handlers never tear the HTTP server down themselves: the response has not left the socket yet, and the stack the handler runs on belongs to the server. Raising this flag hands the teardown to AdminStateHandler, which (for relock) wipes the FSM-held vault session key before ending the portal — the only path that destroys the vault key an ended session leaves behind.
- Parameters
-
Name Direction Meaning relock in True when the vault must relock with the teardown (session lock, destructive commits, a displaced vault); false for a plain exit.
resetConfirm() #
Wipe any pending confirmation.
The pending entry holds the nonce and a copy of the session token it is bound to. AdminPortal::
resetCredentialBatchStaging() #
Drop any staged delete batch.
Called on portal teardown so a batch staged in one session can never be committed from the next one.
resetPendingState() #
Drop any queued action and the whole sampled snapshot; call when the portal stops.
Keeps a request that arrived microseconds before teardown from rebooting the device after the session ended, and clears every sampled value — not just the "have we sampled" flag — so the next session cannot serve a battery reading, a PMIC name, or a probe result taken during the previous one.
resetSession() #
Cancel any in-flight sync (powers the receiver down) and clear all pending flags and the published snapshot.
Called from the ADMIN_MODE exit path so no GPS state leaks into the next session and the receiver is never left drawing acquisition current.
resolveOrCreateGroup() #
Resolve a group NAME to its id, creating the group on first use.
Case-insensitive match against the stored table (so "Work" and "work" do not silently fork into two groups); a miss allocates the lowest free id via the VaultStore facade. Shared by the item import and the CSV import (both map a 1Password vault or a Tags first-value to a group name).
- Parameters
-
Name Direction Meaning vaultKey in Unlocked session vault key. name in Group name (clamped to the table's capacity on store).
- Returns
- The group id (1..100), or 0 when the table is full, unreadable, or unwritable. A table that will not read yields 0 rather than a fresh id: listing no names there is not evidence that the name is new.
sendPortalRedirect() #
Answer with a 302 to the portal root, so a browser that asked for anything at all lands on the admin panel.
The captive-DNS responder already resolves every name to the AP, so this is what turns "any request" into "the panel": the OS connectivity probes see a redirect instead of the success body they expect and raise the sign-in notification, and a browser opened on any URL arrives at the panel.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
sessionEndWantsLock() #
Whether the pending exit also asked for the vault to be relocked.
- Returns
- True when the request came from
/api/session/lock.
takeConfirmNonce() #
Consume the nonce for action.
Single use: a matching nonce is invalidated whether or not the action then succeeds. On failure the 403 has already been sent.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. action in Action id the nonce must have been minted for. nonce in Nonce from the request body.
- Return values
-
Value Meaning true Valid, unexpired, session- and action-matched; now consumed. false Refused; a response was sent.
takeNtpSyncOnExit() #
Take the on-exit NTP sync request, clearing it.
- Return values
-
Value Meaning true A sync was scheduled since the last call. false Nothing scheduled.
takePendingBeep() #
Take the pending beep request, clearing it.
- Return values
-
Value Meaning true A beep was requested since the last call. false Nothing pending.
takeRebootRequest() #
Take the pending reboot request, clearing it.
- Return values
-
Value Meaning true A restart was requested since the last call. false Nothing pending.
takeSessionEndRequest() #
Whether a handler asked the FSM to leave admin mode.
- Return values
-
Value Meaning true An exit was requested (and the flag is cleared by this call). false Nothing pending.
tryHandleBleHostDelete() #
Dynamic route handler for DELETE /api/ble/hosts/:idx.
- Parameters
-
Name Direction Meaning req in, out Active admin HTTP request whose URL is matched.
- Returns
- true if the URL matched and the response was sent; false otherwise.
tryHandleBleHostRename() #
Dynamic route handler for POST /api/ble/hosts/:idx/name.
Renames one bonded host and then flushes the name table to NVS under a short bounded wait, because the rename itself only reaches RAM plus the RTC mirror and would be lost on a power cycle. The flush result is reported as persisted so the client can distinguish "saved" from "saved, not yet
durable" instead of silently losing the label.
- Parameters
-
Name Direction Meaning req in, out Active admin HTTP request whose URL is matched.
- Return values
-
Value Meaning true The URL matched this route and a response was sent. false The URL is some other path; the caller keeps dispatching.
tryHandleTotpRoute() #
Dynamic route handler for every :id-bearing TOTP route.
Matches /api/totp/:id (GET metadata, POST metadata update, DELETE), /api/totp/:id/code and /api/credentials/:id/totp/code, and answers the request when one matches. An id at or above the relevant vault capacity does not match, so it falls through to the dispatcher's plain 404 without touching the vault.
Takes the full context (not just the request) because the code and metadata routes need the live vault key from ctx.state.
- Parameters
-
Name Direction Meaning ctx in, out Per-request admin API context.
- Return values
-
Value Meaning true The URL matched a TOTP route and the response was sent. false The URL is not a TOTP route; the caller must keep dispatching.
twoHoldsField() #
The schema's twoHolds field: whether the dial style is two holds.
- Parameters
-
Name Direction Meaning caps in The board's capabilities. pinMethod in The stored value of the PIN dial style.
- Returns
- The field's value on a board whose unlock is the timing dial, or no value (the field is absent) on a keyboard or touch board.
verifyUnlockSecret() #
Verify the unlock secret carried by a destructive request.
On any failure the HTTP response has already been sent — 429 during a lockout, 400 for a missing or over-long secret, 403 for anything else — so the caller must simply return.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context (receives the reject response). secret in The candidate secret from the request body. len in Length of secretin bytes.tag in Log tag for the caller's endpoint.
- Return values
-
Value Meaning true The secret is correct; the brute-force counter has been reset. false Refused; a response was sent. Nothing was changed.
verifyUnlockSecretFromBody() #
Verify the unlock secret carried in a JSON request body.
Reads it with readUnlockSecretFromBody and hands it to verifyUnlockSecret, wiping the copy either way. This is the entry point handlers should use; taking the raw pointer is for callers that already hold the parsed secret.
- Parameters
-
Name Direction Meaning ctx in, out Admin API request context. data in Body bytes. len in Length of data.tag in Log tag for the caller's endpoint.
- Return values
-
Value Meaning true The secret is correct. false Refused; a response was sent and nothing was changed.
wipeVaultAfterSpentBudget() #
Destroy the vault once a remote unlock verify spends the last attempt.
Runs the same factory reset as every other change-of-owner surface: the vault partition now, then the whole NVS partition at the top of the next boot.
The caller then sends its generic 403 and only after that calls endSessionWithRestart, the order every handler in this file keeps: the response leaves the socket before the FSM takes the access point down, and the device restarts into the boot that finishes the reset. The portal disappearing afterwards is the one visible sign of a wipe, accepted because once the vault is gone that silence protects nothing.
- Parameters
-
Name Direction Meaning auth in, out The session's authenticator, kept alive across the erase, which takes minutes at the per-record cost of every board.
Variable Documentation
kAdminCsp #
Content-Security-Policy of every admin response that is not a page: a JSON answer, a file, a redirect runs nothing and loads nothing, and nothing may frame it. The two pages the portal serves replace it with their own, which pin their inline blocks by hash (kIndexHtmlCsp for the SPA, generated with it; kOtaPageCsp for /update) through AdminHttpResponse::
kBodyChunkBytes #
Scratch window the response body is streamed through, in bytes.
Lives on the handler's stack: the body is chunked out as this fills, so the body costs a fixed few hundred bytes however much history it carries.
kControl #
A control body: a nonce, an unlock secret, a slot id, a flag, a name, a TOTP secret, a time, a passphrase of at most 128 characters.
kHttpRouteCapacity #
Headroom, not a target. The portal registers 61 routes today on the widest variant (SD + OTA + profiling); the planned device-info, destructive, BLE-name, SD-wizard and telemetry groups add roughly 20 more. Overflow is invisible at compile time — a dropped route is a silent 404 at runtime — so the ceiling carries slack and addRoute() refuses to fail quietly.
kImportFile #
A CSV or flat JSON import file, which the routes parse whole, after the page's blank lead-in.
kLeadIn #
The blank bytes the portal page puts before every JSON body and every restore's secrets.
A body opens with this many blank bytes before any password, secret or passphrase it carries. JSON allows whitespace before a value, so a body read without its lead-in parses the same.
kMaxExportPassphrase #
Maximum accepted export-passphrase length (bytes, exclusive) for the encrypted export. InplaceString<128> holds 127 chars + NUL; a longer passphrase is truncated silently without this guard, so we reject it instead.
kMaxSnapshotSamples #
Largest ring snapshot a single GET response will copy and encode.
The route is polled on a timer for the whole session, so its cost per poll is what matters, not its cost once. Capping the window here puts a hard ceiling on the only heap the handler takes (kMaxSnapshotSamples * sizeof(Sample), ~3 KB) that no future growth of the ring can raise, and the window is taken from the newest end so a poll always shows current history.
kMinPeriodMs #
Shortest sampling period the API accepts, in milliseconds.
Channels read the PMIC over I2C, so an unbounded period would let an authenticated station saturate the bus and the Core-0 sampler task. 100 ms is far finer than any battery trend needs.
kNameMaxChars #
Longest BLE identity string the portal accepts, in characters. The BLE name buffer is kNameMaxBytes wide including its NUL terminator, and the same buffer backs both the advertised device name and every host label, so this one cap holds on every board.
kPowerSampleIntervalMs #
Minimum spacing between two device-snapshot samples, in milliseconds.
The portal's only battery cadence: /api/status and /api/system both read the one snapshot it paces. The readings move slowly, and every sample costs an I2C transaction plus a temperature-sensor install cycle.
kRequestStopBudgetMs #
Bounded wait a request handler gives the sampler to exit.
Handlers run on the single Core-0 HTTP server task, which serves every admin request: blocking it indefinitely would wedge the portal. The sampler checks for a stop every kStopPollSliceMs (100 ms), so this budget covers a normal stop several times over.
kSecretMember #
The settings-patch member that carries the unlock secret. It names no row, so the patch skips it when it resolves the rows it writes.
kSessionStopBudgetMs #
Wait the session teardown gives the sampler to exit: none.
endPortalSession() runs inside AdminPortal:: on the Core-1 loop task, where the project's rule is to never block for more than ~50 ms. So the teardown only latches the stop and returns; the sampler notices it within one kStopPollSliceMs and the loop task's own telemetry:: pump completes the release a tick or two later, off the critical path.
kStorageSampleIntervalMs #
Minimum spacing between two vault mounts for the storage figures, in milliseconds.
GET /api/system is polled, and the filesystem/
kWideIntBound #
An integer as a request spells it, wide enough that the route, not the binder, judges a value out of its own range.