Kleidos API Search

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.

See also
Update Policy, Wi-Fi & HTTP Server, Admin Portal Rules

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/web/admin_api_context.h
Per-request dependency bundle handed to every admin route handler.
file src/web/admin_api_handlers.h
Free-function request handlers for the admin portal REST API.
file src/web/admin_api_handlers_internal.h
What the portal's route units share: two bounds and the helpers more than one calls.
file src/web/admin_app_host.h
What the admin portal reads from, and asks of, the running application.
file src/web/admin_auth.h
Stateful authentication / rate-limit / secret-generation adapter for the admin portal.
file src/web/admin_ble_api.h
BLE identity endpoints for the admin portal (advertised name, host labels).
file src/web/admin_confirm.cpp
Implementation of the destructive-endpoint confirmation gate.
file src/web/admin_confirm.h
The proof-of-intent gate every destructive admin endpoint must pass.
file src/web/admin_credentials_api.cpp
Implementation of the widened credential list and the confirmed batch delete.
file src/web/admin_credentials_api.h
Widened credential list and confirmed batch delete for the portal.
file src/web/admin_device_api.cpp
Implementation of the portal's clock/security/AP/session read surfaces.
file src/web/admin_device_api.h
Admin-portal read surfaces for clock, security posture, AP and session.
file src/web/admin_export_api.h
The portal's backup and export routes.
file src/web/admin_gps_api.h
Admin-portal bridge to the one-shot GPS time-sync engine (HAS_GPS).
file src/web/admin_groups_api.cpp
Implementation of the admin-portal group routes.
file src/web/admin_groups_api.h
Admin-portal group routes: list, rename-or-create, delete-with-fallback.
file src/web/admin_host_guard.h
The DNS-rebinding Host guard of the admin portal, on one request.
file src/web/admin_http_request.h
HTTP request/response wrapper classes for the admin portal.
file src/web/admin_http_router.h
The admin portal's HTTP server: its route table and its one dispatcher.
file src/web/admin_import_api.cpp
Implementation of the normalized merge-import endpoint.
file src/web/admin_import_api.h
Admin-portal endpoint: normalized merge-import of credential items.
file src/web/admin_json_reply.h
One JSON response written straight from the own JSON writer.
file src/web/admin_json_stream.h
Streaming JSON responses for the admin portal.
file src/web/admin_network_api.cpp
Implementation of the saved-WiFi and time-server admin routes.
file src/web/admin_network_api.h
Saved WiFi networks and time servers, over the admin portal.
file src/web/admin_ota_upload.h
OTA firmware-upload request handlers for the admin portal.
file src/web/admin_portal.h
AP-mode web portal for credential CRUD and OTA updates.
file src/web/admin_portal_state.h
Encapsulated shared state for the AP-mode admin portal.
file src/web/admin_portal_types.h
Small value types shared between the admin portal and its state owner.
file src/web/admin_rekey_api.h
The portal's key-rotation and secret-change routes.
file src/web/admin_sd_api.h
SD-card admin portal request handlers (HAS_SDCARD variants only).
file src/web/admin_settings_api.cpp
Implementation of the settings-model projection onto the admin portal.
file src/web/admin_settings_api.h
Admin-portal endpoints that project the settings model onto HTTP.
file src/web/admin_system_api.h
Device-information REST API for the admin portal (/api/system*).
file src/web/admin_telemetry_api.h
Battery-history admin portal request handlers.
file src/web/admin_totp_api.h
Admin portal endpoints for live one-time codes and TOTP metadata.
file src/web/logic/admin_body_answer.h
What the portal answers when a request body cannot be read or parsed.
file src/web/logic/admin_body_caps.h
The largest request body each buffered portal route accepts.
file src/web/logic/admin_settings_logic.h
Which settings rows the admin portal lists, and the dial style it reports.

Classes

struct kleidos::AdminApiContext
Per-request context passed by reference to every admin route handler. More about kleidos::AdminApiContext
class kleidos::AdminAppHost
The running application, as the admin portal sees it. More about kleidos::AdminAppHost
class kleidos::AdminAuth
Stateful security gatekeeper operating on a referenced AdminPortalState. More about kleidos::AdminAuth
class kleidos::SecureHttpBody
RAII owner for a heap-allocated HTTP body that may hold plaintext credentials: the buffer is zeroized with mbedtls_platform_zeroize before it is released, both on reset and on destruction. Move-only. More about kleidos::SecureHttpBody
class kleidos::AdminHttpHeader
Single reusable header-value slot, zeroized on wipe (may hold secrets). More about kleidos::AdminHttpHeader
struct kleidos::HeaderLookup
What one header read found, and the slot when it holds the value. More about kleidos::HeaderLookup
class kleidos::AdminHttpClient
Peer-address holder for a request (per-IP rate limiting). More about kleidos::AdminHttpClient
class kleidos::AdminHttpResponse
Response builder; owns sensitive body bytes wiped on destruction. More about kleidos::AdminHttpResponse
class kleidos::AdminHttpRequest
Bounded view over one platform HTTP request with a lazily-read body. More about kleidos::AdminHttpRequest
class kleidos::web::AdminHttpServer
The portal's HTTP server: a static route table behind one dispatcher. More about kleidos::web::AdminHttpServer
class kleidos::web::adminapi::JsonReply
A JSON response the caller writes through a json::Writer. More about kleidos::web::adminapi::JsonReply
class kleidos::web::adminapi::ChunkedJsonWriter
Streaming sink for the own JSON writer: forwards its text to the chunked response through a small rolling buffer. More about kleidos::web::adminapi::ChunkedJsonWriter
class kleidos::web::adminapi::JsonArrayStream
Stream a JSON array element by element over a chunked response. More about kleidos::web::adminapi::JsonArrayStream
struct kleidos::LinkSnapshot
Link-agnostic snapshot of a transport's reachability and identity. More about kleidos::LinkSnapshot
Abstract transport port for the admin portal. More about kleidos::AdminLink
class kleidos::AdminPortal
Static AP-mode admin portal. More about kleidos::AdminPortal
struct kleidos::AdminPortalState
Single owner of all admin-portal runtime state. More about kleidos::AdminPortalState
struct kleidos::OtaProgress
OTA progress snapshot for the display callback. More about kleidos::OtaProgress
struct kleidos::web::adminsystem::BatterySnapshot
Battery charge and charger state, as one sample recorded them. More about kleidos::web::adminsystem::BatterySnapshot
struct kleidos::web::bodyread::Answer
A status and its JSON body. More about kleidos::web::bodyread::Answer
struct kleidos::web::settingslogic::PatchRow
One row of a settings patch: the key as sent, and its value. More about kleidos::web::settingslogic::PatchRow
class kleidos::web::settingslogic::PatchReader
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::web::settingslogic::PatchReader
WiFi-AP transport adapter (SoftAP + captive DNS). More about kleidos::WifiApLink

Typedefs

usingkleidos::web::adminapi::UnlockSecret
usingkleidos::web::HostVerdict

Enumerations

enum class kleidos::AuthPolicy : uint8_t { kleidos::AuthPolicy::Public, kleidos::AuthPolicy::RateLimited, kleidos::AuthPolicy::Session, kleidos::AuthPolicy::SessionReadOnly, kleidos::AuthPolicy::OtaBasicAuth, kleidos::AuthPolicy::OtaUpload }
Declarative authentication policy applied to an admin route. More about kleidos::AuthPolicy
enum class kleidos::web::adminble::NameCheck : uint8_t { NameCheck::Ok , NameCheck::Empty , NameCheck::TooLong , NameCheck::NotAscii }
Outcome of validating a user-supplied BLE identity string. More about kleidos::web::adminble::NameCheck
enum class kleidos::LinkKind : uint8_t { kleidos::LinkKind::WifiAp , kleidos::LinkKind::WifiSta , kleidos::LinkKind::Ethernet , kleidos::LinkKind::Null }
Discriminator for the kind of transport behind an AdminLink. More about kleidos::LinkKind
enum class kleidos::AdminState : uint8_t { kleidos::AdminState::OFF, kleidos::AdminState::STARTING, kleidos::AdminState::RUNNING, kleidos::AdminState::OtaInProgress, kleidos::AdminState::STOPPING }
Lifecycle state of the admin portal. More about kleidos::AdminState
enum class kleidos::web::bodyread::BodyRead : uint8_t { kleidos::web::bodyread::BodyRead::Ok , kleidos::web::bodyread::BodyRead::TooLarge , kleidos::web::bodyread::BodyRead::NoMemory , kleidos::web::bodyread::BodyRead::Incomplete }
How buffering a request body ended. More about kleidos::web::bodyread::BodyRead
enum class kleidos::web::settingslogic::PatchShape : uint8_t { kleidos::web::settingslogic::PatchShape::Rows , kleidos::web::settingslogic::PatchShape::NotObject , kleidos::web::settingslogic::PatchShape::Malformed }
What a settings patch said. More about kleidos::web::settingslogic::PatchShape

Functions

uint16_tkleidos::web::adminapi::parseCredentialId (const char *url)
Parse a credential index from a /api/credentials/:id URL.
voidkleidos::web::adminapi::handleCredentialFavorite (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
voidkleidos::web::adminapi::handleCredentialOrder (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
voidkleidos::web::adminapi::handleCredentialOrderRespace (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
voidkleidos::web::adminapi::handleVaultReindex (AdminApiContext &ctx)
POST /api/vault/reindex — rebuild the encrypted list index.
voidkleidos::web::adminapi::handleAudit (AdminApiContext &ctx)
GET /api/audit — the audit history, content-negotiated.
voidkleidos::web::adminapi::sendPortalRedirect (AdminApiContext &ctx)
Answer with a 302 to the portal root, so a browser that asked for anything at all lands on the admin panel.
voidkleidos::web::adminapi::handleNotFound (AdminApiContext &ctx)
Not-found dispatcher: redirects unknown non-API GETs to the panel, then enforces Session and dispatches the dynamic per-resource routes.
voidkleidos::web::adminapi::handleCredentialRoute (AdminApiContext &ctx, uint16_t id)
Dynamic route handler for GET /api/credentials/:id.
boolkleidos::web::adminapi::parseUnsignedSuffix (const char *url, const char *prefix, uint16_t maxExclusive, uint16_t &out)
Parse a decimal numeric suffix appended after a URL prefix (e.g. "/api/credentials/3").
voidkleidos::web::adminapi::appendJsonEscapedSpan (std::string &output, const char *value, size_t len)
Append a JSON-escaped string literal (with surrounding quotes) to output.
voidkleidos::web::adminapi::appendJsonEscapedString (std::string &output, const char *value)
The NUL-terminated form of appendJsonEscapedSpan.
voidkleidos::web::adminapi::appendPoolString (std::string &output, const kleidos::vault::CredentialPool &pool, kleidos::vault::CredPoolType type)
Append a pool entry's value as a JSON string, or "" when it is absent.
boolkleidos::web::adminapi::hasPlaintextConsent (AdminApiContext &ctx)
Return true when the request carries an explicit plaintext-export consent token.
boolkleidos::web::adminapi::proveSecretForLoss (AdminApiContext &ctx, const uint8_t *data, size_t len, const kleidos::web::secretedit::SecretLoss &loss)
Prove the unlock secret for an edit that destroys a stored secret.
constexpr NameCheckkleidos::web::adminble::checkName (const char *name, size_t length)
Validate a BLE identity string against the name rules of every board.
constexpr const char *kleidos::web::adminble::nameCheckReason (NameCheck check)
Machine-readable reason token for a rejected name.
constexpr boolkleidos::web::adminble::parseHostNamePath (const char *url, uint8_t &outSlot)
Match /api/ble/hosts/<idx>/name and extract the host index.
voidkleidos::web::adminble::handleBleNameGet (AdminApiContext &ctx)
GET /api/ble/name — report the advertised BLE device name.
voidkleidos::web::adminble::handleBleNameSave (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/ble/name — persist a new advertised BLE device name.
boolkleidos::web::adminble::tryHandleBleHostRename (AdminHttpRequest *req)
Dynamic route handler for POST /api/ble/hosts/:idx/name.
voidkleidos::web::adminapi::handleBleHostsGet (AdminApiContext &ctx)
GET /api/ble/hosts: the bonded hosts in the owner's order.
boolkleidos::web::adminapi::tryHandleBleHostDelete (AdminHttpRequest *req)
Dynamic route handler for DELETE /api/ble/hosts/:idx.
boolkleidos::web::adminapi::verifyUnlockSecret (AdminApiContext &ctx, const char *secret, size_t len, const char *tag)
Verify the unlock secret carried by a destructive request.
boolkleidos::web::adminapi::readUnlockSecretFromBody (AdminApiContext &ctx, const uint8_t *data, size_t len, UnlockSecret &out)
Take the unlock secret out of a JSON request body.
boolkleidos::web::adminapi::verifyUnlockSecretFromBody (AdminApiContext &ctx, const uint8_t *data, size_t len, const char *tag)
Verify the unlock secret carried in a JSON request body.
voidkleidos::web::adminapi::mintConfirmNonce (AdminApiContext &ctx, const char *action, char *out, size_t cap)
Mint a one-shot nonce for action, bound to the live session.
boolkleidos::web::adminapi::takeConfirmNonce (AdminApiContext &ctx, const char *action, const char *nonce)
Consume the nonce for action.
voidkleidos::web::adminapi::resetConfirm ()
Wipe any pending confirmation.
uint32_tkleidos::web::adminapi::confirmNonceTtlSeconds ()
Seconds a minted nonce stays valid.
voidkleidos::web::admincred::handleListCredentials (AdminApiContext &ctx)
GET /api/credentials — list every stored credential, widened.
voidkleidos::web::admincred::handleCredentialBatchDeletePrepare (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/credentials/delete/prepare — stage a delete batch.
voidkleidos::web::admincred::handleCredentialBatchDeleteCommit (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/credentials/delete/commit — erase the staged batch.
voidkleidos::web::admincred::resetCredentialBatchStaging ()
Drop any staged delete batch.
voidkleidos::web::adminapi::handleTimeGet (AdminApiContext &ctx)
GET /api/time — clock, trust, provenance and the zone table.
voidkleidos::web::adminapi::handleTimeDiag (AdminApiContext &ctx)
GET /api/time/diag — hardware-clock health (VL flag, alarm, timer).
voidkleidos::web::adminapi::handleSecurityPosture (AdminApiContext &ctx)
GET /api/security/posture — secret kind, KDF, binding, boot flags.
voidkleidos::web::adminapi::handleSecurityLockout (AdminApiContext &ctx)
GET /api/security/lockout — attempts used, lock remaining, policy.
voidkleidos::web::adminapi::handleApStatus (AdminApiContext &ctx)
GET /api/ap — access-point identity and client count (no password).
voidkleidos::web::adminapi::handleSessionEnd (AdminApiContext &ctx)
POST /api/session/end — leave admin mode cleanly.
voidkleidos::web::adminapi::handleSessionLock (AdminApiContext &ctx)
POST /api/session/lock — relock the vault and end admin mode.
voidkleidos::web::adminapi::handleVaultWipePrepare (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/vault/wipe/prepare — verify the secret, mint a nonce.
voidkleidos::web::adminapi::handleVaultWipeCommit (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/vault/wipe/commit — the vault-only wipe.
voidkleidos::web::adminapi::handleSettingsReset (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/settings/reset — restore preference defaults.
voidkleidos::web::adminapi::handleFactoryResetPrepare (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/factory-reset/prepare — verify the secret, mint a nonce.
voidkleidos::web::adminapi::handleFactoryResetCommit (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/factory-reset/commit — erase everything and restart.
voidkleidos::web::adminapi::handleApCredentialsSet (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/ap/credentials — pin the access point's SSID and password.
voidkleidos::web::adminapi::handleApCredentialsClear (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
DELETE /api/ap/credentials — back to a random password per session.
voidkleidos::web::adminapi::handleBleForgetAll (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/ble/hosts/forget-all — de-bond every paired host.
voidkleidos::web::adminapi::requestSessionEnd (bool relock)
Ask the FSM to tear the portal down on its next tick.
boolkleidos::web::adminapi::takeSessionEndRequest ()
Whether a handler asked the FSM to leave admin mode.
boolkleidos::web::adminapi::sessionEndWantsLock ()
Whether the pending exit also asked for the vault to be relocked.
voidkleidos::web::adminapi::endSessionWithRestart ()
End the session with a restart: what every factory reset from the portal owes.
voidkleidos::web::adminapi::wipeVaultAfterSpentBudget (AdminAuth &auth)
Destroy the vault once a remote unlock verify spends the last attempt.
voidkleidos::web::adminapi::handleExportEncrypted (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/export/encrypted — stream the whole vault sealed under a passphrase.
voidkleidos::web::adminapi::handleBackupGet (AdminApiContext &ctx)
GET /api/backup — stream the whole vault as a plaintext backup, with consent.
voidkleidos::web::adminapi::handleExportCsv (AdminApiContext &ctx)
GET /api/export/csv — stream the credentials as CSV, with consent.
voidkleidos::web::adminapi::handleExportJson (AdminApiContext &ctx)
GET /api/export/json: every credential in plaintext, streamed a row at a time behind the plaintext consent header.
voidkleidos::web::admingps::handleGpsStatus (AdminApiContext &ctx)
GET /api/gps/status — receiver identity and live sync state.
voidkleidos::web::admingps::handleGpsSyncStart (AdminApiContext &ctx)
POST /api/gps/sync — start a one-shot clock sync from GPS.
voidkleidos::web::admingps::handleGpsRedetect (AdminApiContext &ctx)
POST /api/gps/redetect — forget the cached receiver identity and re-run the auto-detect baud sweep.
voidkleidos::web::admingps::pump ()
Drain pending portal requests and advance a running sync.
voidkleidos::web::admingps::resetSession ()
Cancel any in-flight sync (powers the receiver down) and clear all pending flags and the published snapshot.
voidkleidos::web::admingroups::handleGroupList (AdminApiContext &ctx)
GET /api/groups — list every defined group with its member count.
voidkleidos::web::admingroups::handleGroupSave (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
Buffered body handler for POST /api/groups (rename or create).
voidkleidos::web::admingroups::handleGroupDelete (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
Buffered body handler for DELETE /api/groups (label delete).
voidkleidos::web::admingroups::handleGroupTableReset (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
Buffered body handler for POST /api/groups/reset (drop the table).
boolkleidos::web::requestHostIsAllowed (AdminHttpRequest &request, const char *apIp, const char *apName, HostVerdict linkVerdict)
Whether request may be served, by its Host authority.
voidkleidos::web::adminimport::handleImportItems (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
Buffered body handler for POST /api/import/items.
uint8_tkleidos::web::adminimport::resolveOrCreateGroup (const uint8_t *vaultKey, const char *name)
Resolve a group NAME to its id, creating the group on first use.
boolkleidos::web::adminapi::memberOrNull (json::Writer &out, const char *name, const char *text)
A member whose value is text, or null when there is none.
voidkleidos::web::adminapi::handleWifiListGet (AdminApiContext &ctx)
GET /api/wifi/networks — saved SSIDs (never their passphrases).
voidkleidos::web::adminapi::handleWifiAdd (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/wifi/networks — save one network.
voidkleidos::web::adminapi::handleWifiDelete (AdminApiContext &ctx)
DELETE /api/wifi/networks/:idx — forget one saved network.
voidkleidos::web::adminapi::handleNtpListGet (AdminApiContext &ctx)
GET /api/ntp/servers — the effective time servers and their source.
voidkleidos::web::adminapi::handleNtpSet (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/ntp/servers — set one server slot.
voidkleidos::web::adminapi::handleNtpReset (AdminApiContext &ctx)
DELETE /api/ntp/servers — fall back to the built-in defaults.
voidkleidos::web::adminapi::handleNtpSyncSchedule (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/ntp/sync — schedule a network clock sync for admin exit.
boolkleidos::web::adminapi::ntpSyncOnExitArmed ()
Whether an on-exit NTP sync is armed (peek; does not clear).
boolkleidos::web::adminapi::takeNtpSyncOnExit ()
Take the on-exit NTP sync request, clearing it.
voidkleidos::web::adminapi::clearNtpSyncOnExit ()
Drop a scheduled on-exit sync (admin exit safety net / debug jumps).
voidkleidos::web::adminota::handleOtaPageGet (AdminApiContext &ctx)
Serve the minimal OTA upload page (GET /update).
voidkleidos::web::adminota::handleOtaUpload (AdminApiContext &ctx)
Receive a firmware image, stream it into an OTA session and finalize (POST /update).
voidkleidos::web::adminapi::handleRotateStatus (AdminApiContext &ctx)
GET /api/rotate — is a key rotation live, and how far has it gone?
voidkleidos::web::adminapi::handleRotateBegin (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/rotate — begin an in-place key rotation.
voidkleidos::web::adminapi::handleRotateStep (AdminApiContext &ctx)
POST /api/rotate/step — advance the live rotation.
voidkleidos::web::adminapi::handleRotateFinish (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/rotate/finish — retire the previous vault key.
voidkleidos::web::adminapi::handleRekey (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
Put the vault on a new unlock secret (change PIN / passphrase / rekey).
voidkleidos::web::adminsd::handleSdStatusGet (AdminApiContext &ctx)
GET /api/sd/status: whether a card is seated, its size and use, and what it holds (backup, CSV files, keyfile, staged firmware).
voidkleidos::web::adminsd::handleSdCsvImport (AdminApiContext &ctx)
POST /api/sd/csv/import: import the CSV files in /kleidos/import/.
voidkleidos::web::adminsd::handleSdAuditExport (AdminApiContext &ctx)
POST /api/sd/audit/export: write the audit log to the card.
voidkleidos::web::adminsd::handleSdKeyfileGenerate (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
Body handler: creates the SD keyfile after proof of the unlock secret.
voidkleidos::web::adminsd::handleSdKeyfileDelete (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
Body handler: deletes the SD keyfile after proof of the unlock secret.
voidkleidos::web::adminsd::handleSdFormat (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
Body handler: formats the card after proof of the unlock secret.
voidkleidos::web::adminsd::handleSdFirmwareApply (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
Body handler: installs the firmware staged on the SD card (POST /api/sd/firmware/apply).
voidkleidos::web::adminapi::fillStatusPayload (json::Writer &out)
Fill the shared device-status object (version, counts, capacities).
voidkleidos::web::adminapi::handleBootstrap (AdminApiContext &ctx)
GET /api/bootstrap — model, capabilities, values and status in one.
voidkleidos::web::adminapi::handleCapabilities (AdminApiContext &ctx)
GET /api/capabilities — capability flags and vault capacities.
voidkleidos::web::adminapi::handleSettingsSchema (AdminApiContext &ctx)
GET /api/settings/schema — the offered options and their values.
voidkleidos::web::adminapi::handleSettingsOptions (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/settings/options — write a subset of option values.
voidkleidos::web::adminsystem::handleSystemGet (AdminApiContext &ctx)
GET /api/system — the six device-information blocks.
voidkleidos::web::adminsystem::handlePartitionsGet (AdminApiContext &ctx)
GET /api/system/partitions — the flash partition table.
voidkleidos::web::adminsystem::handleHardwareGet (AdminApiContext &ctx)
GET /api/system/hardware — the board hardware inventory.
voidkleidos::web::adminsystem::handleCrashGet (AdminApiContext &ctx)
GET /api/system/crash — the address-only crash ring.
voidkleidos::web::adminsystem::handleOtaStatus (AdminApiContext &ctx)
GET /api/ota/status — the firmware panel's read-out.
voidkleidos::web::adminsystem::handleSelfTest (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/system/selftest — run a named diagnostic suite.
voidkleidos::web::adminsystem::handleBeep (AdminApiContext &ctx)
POST /api/system/beep — queue an audible "locate me" cue.
voidkleidos::web::adminsystem::handleReboot (AdminApiContext &ctx)
POST /api/system/reboot — restart the device.
voidkleidos::web::adminsystem::handleSleep (AdminApiContext &ctx)
POST /api/system/sleep — lock the device and sleep.
voidkleidos::web::adminsystem::fillIdentityBlock (json::Writer &out)
Populate the identity block: board, firmware, build flavor, address.
voidkleidos::web::adminsystem::fillStorageBlock (json::Writer &out)
Populate the storage block: filesystem bytes, record counts, image.
voidkleidos::web::adminsystem::fillSecurityBlock (json::Writer &out)
Populate the security block: eFuse posture and KDF identification.
voidkleidos::web::adminsystem::fillPowerBlock (json::Writer &out)
Populate the power block from the FSM-refreshed snapshot.
voidkleidos::web::adminsystem::fillRuntimeBlock (json::Writer &out)
Populate the runtime block: uptime, restart cause, heap.
voidkleidos::web::adminsystem::fillSocBlock (json::Writer &out)
Populate the soc block: silicon model, clocks, radios, die heat.
BatterySnapshotkleidos::web::adminsystem::batteryReading ()
The battery figures of the device snapshot, for a route outside the power block.
voidkleidos::web::adminsystem::refreshDeviceSnapshot (PowerManager &pm)
Refresh the cross-core device snapshot; call from the FSM tick.
boolkleidos::web::adminsystem::takeRebootRequest ()
Take the pending reboot request, clearing it.
voidkleidos::web::adminsystem::requestReboot ()
Arm the pending reboot request (drained by the FSM's ADMIN_MODE tick).
boolkleidos::web::adminsystem::takePendingBeep ()
Take the pending beep request, clearing it.
voidkleidos::web::adminsystem::resetPendingState ()
Drop any queued action and the whole sampled snapshot; call when the portal stops.
voidkleidos::web::admintelemetry::handleTelemetryGet (AdminApiContext &ctx)
GET /api/telemetry — run state and recorded history.
voidkleidos::web::admintelemetry::handleTelemetryStart (AdminApiContext &ctx, const uint8_t *data, size_t len, size_t index, size_t total)
POST /api/telemetry/start — begin a capture.
voidkleidos::web::admintelemetry::handleTelemetryStop (AdminApiContext &ctx)
POST /api/telemetry/stop — end the capture this portal started.
voidkleidos::web::admintelemetry::endPortalSession ()
Stop a telemetry run this portal started, if any.
voidkleidos::web::adminapi::handleTotpList (AdminApiContext &ctx)
GET /api/totp — list every stored TOTP entry with its parameters.
boolkleidos::web::adminapi::tryHandleTotpRoute (AdminApiContext &ctx)
Dynamic route handler for every :id-bearing TOTP route.
boolkleidos::web::adminapi::isPolledTotpCodeRoute (const char *url)
True when url is one of the live-code routes the SPA polls.
constexpr Answerkleidos::web::bodyread::answerFor (BodyRead read)
The answer to a body that could not be buffered.
Answerkleidos::web::bodyread::answerFor (const json::BindResult &result, const char *malformed)
The answer to a body the binder refused.
constexpr size_tkleidos::web::bodycap::decimalDigits (size_t value)
constexpr size_tkleidos::web::bodycap::orderBytesPerId (size_t slots)
constexpr boolkleidos::web::settingslogic::offered (const kleidos::settings::SettingsOption &opt, const kleidos::settings::SettingsCapabilities &caps)
Whether the portal lists opt on a board with caps.
constexpr std::optional< bool >kleidos::web::settingslogic::twoHoldsField (const kleidos::settings::SettingsCapabilities &caps, int32_t pinMethod)
The schema's twoHolds field: whether the dial style is two holds.
constexpr kleidos::settings::OptionIdkleidos::web::settingslogic::portalDependsOn (const kleidos::settings::SettingsOption &opt)
The parent a portal row names in its dependsOn.
constexpr boolkleidos::web::settingslogic::listedForPortal (const kleidos::settings::SettingsOption &opt, const kleidos::settings::SettingsCapabilities &caps, int32_t parentValue)
Whether the portal's schema lists an offered row right now.
constexpr boolkleidos::web::settingslogic::patchNeedsSecret (const kleidos::settings::OptionId *ids, size_t count)
Whether a settings patch must carry proof of the unlock secret.

Variables

constexpr size_tkleidos::web::adminapi::kMaxExportPassphrase
constexpr int64_tkleidos::web::adminapi::kWideIntBound
constexpr size_tkleidos::web::adminble::kNameMaxChars
constexpr const char *kleidos::web::adminble::kHostNamePrefix
URL prefix of the dynamic per-host rename route.
constexpr const char *kleidos::web::adminble::kHostNameSuffix
URL suffix that follows the host index on the dynamic rename route.
constexpr size_tkleidos::web::adminapi::kConfirmNonceCap
Longest confirmation nonce, hex text plus terminator.
constexpr size_tkleidos::web::admincred::kMaxBatchDeleteIds
Largest number of ids accepted in one delete batch.
constexpr const char *kleidos::web::admincred::kBatchDeleteAction
Confirmation action id the delete nonce is minted and spent under.
constexpr size_tkleidos::kMaxHttpBodyBytes
Maximum admin HTTP request body buffered in RAM (bytes).
constexpr size_tkleidos::kMaxHttpHeaderValue
Maximum length of a single inspected request/response header value (bytes).
constexpr size_tkleidos::kMaxHttpUrlBytes
Maximum admin request URI length retained after stripping the query (bytes).
constexpr uint8_tkleidos::kHttpRecvTimeoutLimit
Consecutive receive timeouts tolerated while reading a body before giving up.
constexpr const char *kleidos::kAdminCsp
constexpr size_tkleidos::web::kHttpRouteCapacity
constexpr const char *kleidos::web::adminapi::kStreamTag
Log tag shared by the streaming responses (the portal's own tag).
constexpr uint32_tkleidos::web::adminsystem::kPowerSampleIntervalMs
Minimum spacing between two device-snapshot samples, in milliseconds.
constexpr uint32_tkleidos::web::adminsystem::kStorageSampleIntervalMs
Minimum spacing between two vault mounts for the storage figures, in milliseconds.
constexpr uint32_tkleidos::web::admintelemetry::kMinPeriodMs
constexpr uint32_tkleidos::web::admintelemetry::kMaxPeriodMs
Longest sampling period the API accepts, in milliseconds (one hour).
constexpr uint32_tkleidos::web::admintelemetry::kDefaultPeriodMs
Sampling period used when the request body does not specify one.
constexpr uint32_tkleidos::web::admintelemetry::kRequestStopBudgetMs
constexpr uint32_tkleidos::web::admintelemetry::kSessionStopBudgetMs
constexpr size_tkleidos::web::admintelemetry::kMaxSnapshotSamples
constexpr size_tkleidos::web::admintelemetry::kBodyChunkBytes
constexpr const char *kleidos::web::bodyread::kOutOfMemoryJson
Body of every out-of-memory answer, buffered or parsed.
constexpr const char *kleidos::web::bodyread::kTooLargeJson
Body of the answer to a body over its route's cap.
constexpr const char *kleidos::web::bodyread::kIncompleteJson
Body of the answer to a body that stopped arriving.
constexpr const char *kleidos::web::bodyread::kInvalidJson
Body most routes answer text that is not JSON with.
constexpr size_tkleidos::web::bodycap::kLeadIn
The blank bytes the portal page puts before every JSON body and every restore's secrets.
constexpr size_tkleidos::web::bodycap::kControl
constexpr size_tkleidos::web::bodycap::kCredentialSave
One credential with its notes (512 B alone) and its embedded TOTP block.
constexpr size_tkleidos::web::bodycap::kGroup
A group label and its id.
constexpr size_tkleidos::web::bodycap::kBatchDelete
A batch delete: the selection's ids, or the confirmation nonce.
constexpr size_tkleidos::web::bodycap::kOrderBytesPerId
Text a slot id takes in a ranking of this build's slots.
constexpr size_tkleidos::web::bodycap::kOrder
A ranking naming every credential slot the build holds, plus its wrapper.
constexpr size_tkleidos::web::bodycap::kSettingsPatch
A settings patch: every option of the schema at once.
constexpr size_tkleidos::web::bodycap::kImportFile
constexpr const char *kleidos::web::settingslogic::kSecretMember
constexpr size_tkleidos::web::settingslogic::kMaxPatchRows
Most rows one settings patch may write.

Back to the top

Typedef Documentation

HostVerdict #

using kleidos::web::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 #

using kleidos::web::adminapi::UnlockSecret

An unlock secret taken from a request. Holds the longest secret any entry surface accepts, security::pin_policy::kPassphraseMax characters; a request carrying a longer one is refused before it is copied, never cut to fit.

Back to the top

Enumeration Type Documentation

AdminState #

enum class kleidos::AdminState : uint8_t

Lifecycle state of the admin portal.

Enumerator
OFF 

Portal stopped.

STARTING 

Access point coming up.

RUNNING 

Serving requests.

OtaInProgress 

OTA upload in progress.

STOPPING 

Tearing down.

AuthPolicy #

enum class kleidos::AuthPolicy : uint8_t

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::checkRateLimit), the session token (AdminAuth::validateSessionToken, or its read-only twin that does not renew the idle clock) and the OTA password (AdminAuth::validateOtaBasicAuth). The dispatcher runs them, through AdminAuth::runPolicy, before the route's handler and before the not-found handler: a request that fails one gets its refusal (429, a 401 JSON body, or the OTA Basic-Auth challenge) and reaches no handler.

Enumerator
Public 

No checks; always allowed (captive-portal probes, etc.).

RateLimited 

Per-IP rate limit only (auto-selects 30 for /api/init, else 80).

Session 

Rate limit, then session-token check WITH idle refresh.

SessionReadOnly 

Rate limit, then session-token check WITHOUT idle refresh.

OtaBasicAuth 

Rate limit, then the OTA HTTP Basic-Auth challenge gate.

OtaUpload 

The firmware upload: rate limit, the OTA Basic-Auth gate, then the session token. A browser replays a remembered Basic credential on a cross-site POST; it cannot replay the token, which another origin can neither read nor send without a preflight the portal never answers.

BodyRead #

enum class kleidos::web::bodyread::BodyRead : uint8_t

How buffering a request body ended.

Enumerator
Ok 

The body is in memory (or there was none).

TooLarge 

The declared length is over the route's cap; nothing was reserved.

NoMemory 

Within the cap, but no block of that size was free.

Incomplete 

The client stopped sending, or the transfer timed out.

LinkKind #

enum class kleidos::LinkKind : uint8_t

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 #

enum class kleidos::web::adminble::NameCheck : uint8_t

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::adminble::kNameMaxChars characters.

NotAscii 

Holds a byte outside printable ASCII (0x20..0x7E).

PatchShape #

enum class kleidos::web::settingslogic::PatchShape : uint8_t

What a settings patch said.

Enumerator
Rows 

One object of rows, read into PatchReader::rows.

NotObject 

One JSON value that is not an object.

Malformed 

Not JSON, or a row whose value is not an integer or a boolean.

Back to the top

Function Documentation

answerFor() [1/2] #

Answer kleidos::web::bodyread::answerFor(BodyRead read)
constexpr

The answer to a body that could not be buffered.

Parameters
NameDirectionMeaning
readinHow buffering ended.
Returns
{0, nullptr} for Ok; otherwise 413, 503 or 400 with its body.

answerFor() [2/2] #

Answer kleidos::web::bodyread::answerFor(const json::BindResult & result, const char * malformed)
inline

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
NameDirectionMeaning
resultinWhat the bind returned.
malformedinThe route's own body for a body it cannot take.
Returns
{0, nullptr} when it bound; otherwise 400 with malformed.

appendJsonEscapedSpan() #

void kleidos::web::adminapi::appendJsonEscapedSpan(std::string & output, const char * value, size_t len)

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
NameDirectionMeaning
outputin, outThe text being built.
valueinThe bytes; nullptr reads as empty.
leninBytes of value to write.

appendJsonEscapedString() #

void kleidos::web::adminapi::appendJsonEscapedString(std::string & output, const char * value)

The NUL-terminated form of appendJsonEscapedSpan.

Parameters
NameDirectionMeaning
outputin, outThe text being built.
valueinThe text; nullptr reads as empty.

appendPoolString() #

void kleidos::web::adminapi::appendPoolString(std::string & output, const kleidos::vault::CredentialPool & pool, kleidos::vault::CredPoolType type)

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
NameDirectionMeaning
outputin, outThe text being built.
poolinThe credential's extras pool.
typeinThe entry to write.

batteryReading() #

BatterySnapshot kleidos::web::adminsystem::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; known is false until the battery has read once (a route reports the figures as unknown then, never 0 %).

checkName() #

NameCheck kleidos::web::adminble::checkName(const char * name, size_t length)
constexpr

Validate a BLE identity string against the name rules of every board.

A name is accepted when it is 1..web::adminble::kNameMaxChars bytes of printable ASCII and is not made up entirely of spaces. Bytes at or above 0x80 (any UTF-8 continuation or lead byte) and C0 control codes are rejected because the BLE layer truncates the string at the first such byte, which would silently store a prefix of what the user typed.

Side-effect free and header-only so the rule is native-testable without the BLE stack.

Parameters
NameMeaning
nameCandidate name; need not be NUL-terminated within length.
lengthNumber of bytes to inspect.
Returns
The first rule the candidate breaks, or NameCheck::Ok.

confirmNonceTtlSeconds() #

uint32_t kleidos::web::adminapi::confirmNonceTtlSeconds()
nodiscard

Seconds a minted nonce stays valid.

Returns
The TTL in seconds, for the expires_s field of a prepare response.

decimalDigits() #

size_t kleidos::web::bodycap::decimalDigits(size_t value)
constexpr

Decimal digits value is written with.

Parameters
NameDirectionMeaning
valueinThe number.
Returns
Its digit count, 1 for 0.

endPortalSession() #

void kleidos::web::admintelemetry::endPortalSession()

Stop a telemetry run this portal started, if any.

Called from AdminPortal::end 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::end runs on the Core-1 loop task. The stop is latched here and completed by the loop task's own telemetry pump; see ::kSessionStopBudgetMs.

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() #

void kleidos::web::adminapi::endSessionWithRestart()

End the session with a restart: what every factory reset from the portal owes.

Asks the FSM for a reboot (web::adminsystem::requestReboot) 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() #

void kleidos::web::adminsystem::fillIdentityBlock(json::Writer & out)

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
NameDirectionMeaning
outin, outWriter inside the object to fill.

fillPowerBlock() #

void kleidos::web::adminsystem::fillPowerBlock(json::Writer & out)

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
NameDirectionMeaning
outin, outWriter inside the object to fill.

fillRuntimeBlock() #

void kleidos::web::adminsystem::fillRuntimeBlock(json::Writer & out)

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
NameDirectionMeaning
outin, outWriter inside the object to fill.

fillSecurityBlock() #

void kleidos::web::adminsystem::fillSecurityBlock(json::Writer & out)

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
NameDirectionMeaning
outin, outWriter inside the object to fill.
Warning
SECURITY: booleans and public constants only — never key material.

fillSocBlock() #

void kleidos::web::adminsystem::fillSocBlock(json::Writer & out)

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
NameDirectionMeaning
outin, outWriter inside the object to fill.

fillStatusPayload() #

void kleidos::web::adminapi::fillStatusPayload(json::Writer & out)

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::adminsystem::batteryReading), the same sample /api/system reports, so the dashboard and the System page cannot disagree either.

Parameters
NameDirectionMeaning
outin, outWriter inside the object the members go into.

fillStorageBlock() #

void kleidos::web::adminsystem::fillStorageBlock(json::Writer & out)

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
NameDirectionMeaning
outin, outWriter inside the object to fill.

handleApCredentialsClear() #

void kleidos::web::adminapi::handleApCredentialsClear(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

DELETE /api/ap/credentials — back to a random password per session.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleApCredentialsSet() #

void kleidos::web::adminapi::handleApCredentialsSet(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleApStatus() #

void kleidos::web::adminapi::handleApStatus(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outAdmin API request context.

handleAudit() #

void kleidos::web::adminapi::handleAudit(AdminApiContext & ctx)

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/audit_csv.h), with a Content-Disposition attachment filename. Event names come from auditEventName in both forms.

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleBackupGet() #

void kleidos::web::adminapi::handleBackupGet(AdminApiContext & ctx)

GET /api/backup — stream the whole vault as a plaintext backup, with consent.

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleBeep() #

void kleidos::web::adminsystem::handleBeep(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleBleForgetAll() #

void kleidos::web::adminapi::handleBleForgetAll(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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::BondsForgotten 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
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleBleHostsGet() #

void kleidos::web::adminapi::handleBleHostsGet(AdminApiContext & ctx)

GET /api/ble/hosts: the bonded hosts in the owner's order.

Parameters
NameDirectionMeaning
ctxin, outThe request's context.

handleBleNameGet() #

void kleidos::web::adminble::handleBleNameGet(AdminApiContext & ctx)

GET /api/ble/name — report the advertised BLE device name.

Answers {"name":..,"max_len":..,"applies_at":"next_ble_start"}. The name is the resolved one (the stored value, or the compile-time default when nothing is stored); the BLE layer exposes no accessor that distinguishes the two, so the response cannot flag "still default".

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleBleNameSave() #

void kleidos::web::adminble::handleBleNameSave(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/ble/name — persist a new advertised BLE device name.

Body: {"name":"..."}. Replies 400 (reason from web::adminble::nameCheckReason) when the name breaks a rule, 500 when the NVS write fails, otherwise 200 with the stored name. The new name takes effect at the next BLE bring-up.

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleBootstrap() #

void kleidos::web::adminapi::handleBootstrap(AdminApiContext & ctx)

GET /api/bootstrap — model, capabilities, values and status in one.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleCapabilities() #

void kleidos::web::adminapi::handleCapabilities(AdminApiContext & ctx)

GET /api/capabilities — capability flags and vault capacities.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleCrashGet() #

void kleidos::web::adminsystem::handleCrashGet(AdminApiContext & ctx)

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::platform::crash_record. 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/system read.
Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleCredentialBatchDeleteCommit() #

void kleidos::web::admincred::handleCredentialBatchDeleteCommit(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/credentials/delete/commit — erase the staged batch.

Body {"nonce":"<hex>"}. The nonce is spent through web::adminapi::takeConfirmNonce (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::deleteCredentialBatch — 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
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the whole body.
totalinTotal declared body length in bytes.

handleCredentialBatchDeletePrepare() #

void kleidos::web::admincred::handleCredentialBatchDeletePrepare(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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::adminapi::verifyUnlockSecretFromBody, 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_s":N,"count":M,"ids":[...],"scope":["…"]}. Nothing has been deleted.

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the whole body.
totalinTotal declared body length in bytes.

handleCredentialFavorite() #

void kleidos::web::adminapi::handleCredentialFavorite(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleCredentialOrder() #

void kleidos::web::adminapi::handleCredentialOrder(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/credentials/order — realize a ranking with the fewest record writes. A plan wider than kleidos::vault::kOrderRenumberMaxRows records is refused rather than half-applied, because its wall clock would outrun the request; the re-space route below is the explicit way to ask for that work.

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleCredentialOrderRespace() #

void kleidos::web::adminapi::handleCredentialOrderRespace(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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::vault::kOrderRenumberMaxRows records because its wall clock would outrun the request; this is the work that clears the crowding behind that refusal, asked for explicitly, with the write count and the time bound shown to the owner first.

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleCredentialRoute() #

void kleidos::web::adminapi::handleCredentialRoute(AdminApiContext & ctx, uint16_t id)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.
idinCredential index parsed from the request URL.

handleExportCsv() #

void kleidos::web::adminapi::handleExportCsv(AdminApiContext & ctx)

GET /api/export/csv — stream the credentials as CSV, with consent.

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleExportEncrypted() #

void kleidos::web::adminapi::handleExportEncrypted(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/export/encrypted — stream the whole vault sealed under a passphrase.

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleExportJson() #

void kleidos::web::adminapi::handleExportJson(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outThe request's context.

handleFactoryResetCommit() #

void kleidos::web::adminapi::handleFactoryResetCommit(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/factory-reset/commit — erase everything and restart.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleFactoryResetPrepare() #

void kleidos::web::adminapi::handleFactoryResetPrepare(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/factory-reset/prepare — verify the secret, mint a nonce.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleGpsRedetect() #

void kleidos::web::admingps::handleGpsRedetect(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outAdmin API request context.

handleGpsStatus() #

void kleidos::web::admingps::handleGpsStatus(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outAdmin API request context.

handleGpsSyncStart() #

void kleidos::web::admingps::handleGpsSyncStart(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outAdmin API request context.

handleGroupDelete() #

void kleidos::web::admingroups::handleGroupDelete(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

Buffered body handler for DELETE /api/groups (label delete).

Parameters
NameDirectionMeaning
ctxinRequest context.
datainBody bytes received so far.
leninLength of data.
indexinOffset of data within the whole body.
totalinTotal body length.

handleGroupList() #

void kleidos::web::admingroups::handleGroupList(AdminApiContext & ctx)

GET /api/groups — list every defined group with its member count.

Parameters
NameDirectionMeaning
ctxinRequest context (session already validated by the dispatcher).

handleGroupSave() #

void kleidos::web::admingroups::handleGroupSave(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

Buffered body handler for POST /api/groups (rename or create).

Parameters
NameDirectionMeaning
ctxinRequest context.
datainBody bytes received so far.
leninLength of data.
indexinOffset of data within the whole body.
totalinTotal body length.

handleGroupTableReset() #

void kleidos::web::admingroups::handleGroupTableReset(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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
NameDirectionMeaning
ctxinRequest context.
datainBody bytes received so far.
leninLength of data.
indexinOffset of data within the whole body.
totalinTotal body length.

handleHardwareGet() #

void kleidos::web::adminsystem::handleHardwareGet(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleImportItems() #

void kleidos::web::adminimport::handleImportItems(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

Buffered body handler for POST /api/import/items.

Parameters
NameDirectionMeaning
ctxin, outPer-request context (request + portal state + auth).
datainBody bytes buffered so far.
leninLength of the newest chunk.
indexinOffset of the newest chunk within the body.
totalinDeclared body length; the handler answers only once the final chunk arrived.

handleListCredentials() #

void kleidos::web::admincred::handleListCredentials(AdminApiContext & ctx)

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::forEachIndexRow), 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::saveTo, and the column is not cached in the index either. Read 0 as "unknown".
Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context (reads the live vault key from ctx.state).

handleNotFound() #

void kleidos::web::adminapi::handleNotFound(AdminApiContext & ctx)

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::Public 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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleNtpListGet() #

void kleidos::web::adminapi::handleNtpListGet(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outAdmin API request context.

handleNtpReset() #

void kleidos::web::adminapi::handleNtpReset(AdminApiContext & ctx)

DELETE /api/ntp/servers — fall back to the built-in defaults.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleNtpSet() #

void kleidos::web::adminapi::handleNtpSet(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/ntp/servers — set one server slot.

Body: {"idx": n, "ip": "a.b.c.d"}. Literal IPv4 only — enforced by VaultStore::setNtpServer itself, so a hostname cannot enter the clock path through this route any more than through the device's own.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleNtpSyncSchedule() #

void kleidos::web::adminapi::handleNtpSyncSchedule(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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::net::ntp::begin) before the device sleeps.

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
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleOtaPageGet() #

void kleidos::web::adminota::handleOtaPageGet(AdminApiContext & ctx)

Serve the minimal OTA upload page (GET /update).

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleOtaStatus() #

void kleidos::web::adminsystem::handleOtaStatus(AdminApiContext & ctx)

GET /api/ota/status — the firmware panel's read-out.

Emits {running, image_size, next_capacity, rollback_pending, stage, percent}: the running partition label, the verified size of the running image, the capacity of the slot the next update would land in, whether the running image still boots on rollback trial, and the state of the last or current browser-push upload (see web::otastatus::stageLabel). Numbers come from the platform OTA/system facades; nothing here starts an update — the upload itself stays on 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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleOtaUpload() #

void kleidos::web::adminota::handleOtaUpload(AdminApiContext & ctx)

Receive a firmware image, stream it into an OTA session and finalize (POST /update).

Parameters
NameDirectionMeaning
ctxin, outPer-request admin API context.

handlePartitionsGet() #

void kleidos::web::adminsystem::handlePartitionsGet(AdminApiContext & ctx)

GET /api/system/partitions — the flash partition table.

Emits a JSON array of partition descriptors in esp_partition_find 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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleReboot() #

void kleidos::web::adminsystem::handleReboot(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleRekey() #

void kleidos::web::adminapi::handleRekey(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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_length":4|6|8}). A change-PIN and a change-passphrase are the same operation and differ only in the next value plus the presence of pin_length.

It runs VaultStore::changeSecret, 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::unlockVault 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 shared BruteForceGuard counter 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
NameDirectionMeaning
ctxin, outPer-request admin API context (reads the live vault key pointer from ctx.state and updates it on success).
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleRotateBegin() #

void kleidos::web::adminapi::handleRotateBegin(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleRotateFinish() #

void kleidos::web::adminapi::handleRotateFinish(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleRotateStatus() #

void kleidos::web::adminapi::handleRotateStatus(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleRotateStep() #

void kleidos::web::adminapi::handleRotateStep(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleSdAuditExport() #

void kleidos::web::adminsd::handleSdAuditExport(AdminApiContext & ctx)

POST /api/sd/audit/export: write the audit log to the card.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleSdCsvImport() #

void kleidos::web::adminsd::handleSdCsvImport(AdminApiContext & ctx)

POST /api/sd/csv/import: import the CSV files in /kleidos/import/.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleSdFirmwareApply() #

void kleidos::web::adminsd::handleSdFirmwareApply(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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::applyFirmware, 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
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleSdFormat() #

void kleidos::web::adminsd::handleSdFormat(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

Body handler: formats the card after proof of the unlock secret.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleSdKeyfileDelete() #

void kleidos::web::adminsd::handleSdKeyfileDelete(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

Body handler: deletes the SD keyfile after proof of the unlock secret.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleSdKeyfileGenerate() #

void kleidos::web::adminsd::handleSdKeyfileGenerate(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

Body handler: creates the SD keyfile after proof of the unlock secret.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleSdStatusGet() #

void kleidos::web::adminsd::handleSdStatusGet(AdminApiContext & ctx)

GET /api/sd/status: whether a card is seated, its size and use, and what it holds (backup, CSV files, keyfile, staged firmware).

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleSecurityLockout() #

void kleidos::web::adminapi::handleSecurityLockout(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outAdmin API request context.

handleSecurityPosture() #

void kleidos::web::adminapi::handleSecurityPosture(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outAdmin API request context.

handleSelfTest() #

void kleidos::web::adminsystem::handleSelfTest(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleSessionEnd() #

void kleidos::web::adminapi::handleSessionEnd(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outAdmin API request context.

handleSessionLock() #

void kleidos::web::adminapi::handleSessionLock(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outAdmin API request context.

handleSettingsOptions() #

void kleidos::web::adminapi::handleSettingsOptions(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the whole body.
totalinTotal body length in bytes.

handleSettingsReset() #

void kleidos::web::adminapi::handleSettingsReset(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleSettingsSchema() #

void kleidos::web::adminapi::handleSettingsSchema(AdminApiContext & ctx)

GET /api/settings/schema — the offered options and their values.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleSleep() #

void kleidos::web::adminsystem::handleSleep(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleSystemGet() #

void kleidos::web::adminsystem::handleSystemGet(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleTelemetryGet() #

void kleidos::web::admintelemetry::handleTelemetryGet(AdminApiContext & ctx)

GET /api/telemetry — run state and recorded history.

Answers with the columnar body built by web::telemetryencode (see telemetry_encode.h for the size arithmetic), streamed out in ::kBodyChunkBytes chunks. Reports the run whoever owns it, so a capture started from the debug console is still visible to the page.

The body carries the newest ::kMaxSnapshotSamples samples at most; 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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleTelemetryStart() #

void kleidos::web::admintelemetry::handleTelemetryStart(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/telemetry/start — begin a capture.

Body (all fields optional):

{ "period_ms": 1000, "channels": "batt_mv,batt_ma" }

period_ms is clamped to [::kMinPeriodMs, ::kMaxPeriodMs]; an absent or empty 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
NameDirectionMeaning
ctxin, outPer-request admin API context.
datainBody chunk pointer.
leninLength of this chunk.
indexinOffset of this chunk within the full body.
totalinFull declared body length.

handleTelemetryStop() #

void kleidos::web::admintelemetry::handleTelemetryStop(AdminApiContext & ctx)

POST /api/telemetry/stop — end the capture this portal started.

Waits at most ::kRequestStopBudgetMs. Replies 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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleTimeDiag() #

void kleidos::web::adminapi::handleTimeDiag(AdminApiContext & ctx)

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_time_diag_logic.h formatters) and the chip behind the reading. RTC-less boards answer honestly (chip:"internal", vl:false) — the page hides the card via the rtc capability anyway.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleTimeGet() #

void kleidos::web::adminapi::handleTimeGet(AdminApiContext & ctx)

GET /api/time — clock, trust, provenance and the zone table.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleTotpList() #

void kleidos::web::adminapi::handleTotpList(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleVaultReindex() #

void kleidos::web::adminapi::handleVaultReindex(AdminApiContext & ctx)

POST /api/vault/reindex — rebuild the encrypted list index.

The portal's way to run the recovery action that rebuilds the index. VaultStore::rebuildIndex 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
NameDirectionMeaning
ctxin, outPer-request admin API context.

handleVaultWipeCommit() #

void kleidos::web::adminapi::handleVaultWipeCommit(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/vault/wipe/commit — the vault-only wipe.

Body {"nonce","current"}: the nonce is taken first (one shot), then kleidos::reset::emptyVaultKeepingSecret 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
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleVaultWipePrepare() #

void kleidos::web::adminapi::handleVaultWipePrepare(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

POST /api/vault/wipe/prepare — verify the secret, mint a nonce.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleWifiAdd() #

void kleidos::web::adminapi::handleWifiAdd(AdminApiContext & ctx, const uint8_t * data, size_t len, size_t index, size_t total)

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
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody chunk bytes.
leninLength of data in bytes.
indexinByte offset of this chunk within the body.
totalinTotal body length in bytes.

handleWifiDelete() #

void kleidos::web::adminapi::handleWifiDelete(AdminApiContext & ctx)

DELETE /api/wifi/networks/:idx — forget one saved network.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

handleWifiListGet() #

void kleidos::web::adminapi::handleWifiListGet(AdminApiContext & ctx)

GET /api/wifi/networks — saved SSIDs (never their passphrases).

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context.

hasPlaintextConsent() #

bool kleidos::web::adminapi::hasPlaintextConsent(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxinThe incoming request context.
Return values
ValueMeaning
trueHeader present and equal to "true".
falseHeader absent or has a different value.

isPolledTotpCodeRoute() #

bool kleidos::web::adminapi::isPolledTotpCodeRoute(const char * url)

True when url is one of the live-code routes the SPA polls.

Lets the not-found dispatcher pick AuthPolicy::SessionReadOnly for the polled routes and AuthPolicy::Session for everything else.

Parameters
NameDirectionMeaning
urlinRequest URL, already stripped of its query string.
Return values
ValueMeaning
true/api/totp/:id/code or /api/credentials/:id/totp/code.
falseAny other URL.

listedForPortal() #

bool kleidos::web::settingslogic::listedForPortal(const kleidos::settings::SettingsOption & opt, const kleidos::settings::SettingsCapabilities & caps, int32_t parentValue)
constexpr

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
NameDirectionMeaning
optinA settings row.
capsinThe board's capabilities.
parentValueinThe stored value of opt's parent (ignored when it has none).
Return values
ValueMeaning
trueThe schema carries the row now.

memberOrNull() #

bool kleidos::web::adminapi::memberOrNull(json::Writer & out, const char * name, const char * text)
inline

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
NameDirectionMeaning
outin, outThe writer.
nameinKey.
textinStored text, or nullptr.
Returns
False when the writer refused.

mintConfirmNonce() #

void kleidos::web::adminapi::mintConfirmNonce(AdminApiContext & ctx, const char * action, char * out, size_t cap)

Mint a one-shot nonce for action, bound to the live session.

Parameters
NameDirectionMeaning
ctxin, outAdmin API request context (source of the session token).
actioninAction id the nonce authorizes (e.g. "wipe").
outoutDestination buffer for the hex nonce.
capinCapacity of out; use kConfirmNonceCap.

nameCheckReason() #

const char * kleidos::web::adminble::nameCheckReason(NameCheck check)
constexpr

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
NameMeaning
checkValidation outcome to describe.
Returns
Static lowercase token; "ok" when check is NameCheck::Ok.

ntpSyncOnExitArmed() #

bool kleidos::web::adminapi::ntpSyncOnExitArmed()

Whether an on-exit NTP sync is armed (peek; does not clear).

Return values
ValueMeaning
trueA sync is scheduled for the admin teardown.
falseNothing scheduled.

offered() #

bool kleidos::web::settingslogic::offered(const kleidos::settings::SettingsOption & opt, const kleidos::settings::SettingsCapabilities & caps)
constexpr

Whether the portal lists opt on a board with caps.

Parameters
NameDirectionMeaning
optinA settings row.
capsinThe board's capabilities.
Return values
ValueMeaning
trueThe row carries a value, is persisted, is offered on this board and is not one the device keeps to itself.

orderBytesPerId() #

size_t kleidos::web::bodycap::orderBytesPerId(size_t slots)
constexpr

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
NameDirectionMeaning
slotsinThe slot count the ranking names.
Returns
Bytes per id.

parseCredentialId() #

uint16_t kleidos::web::adminapi::parseCredentialId(const char * url)

Parse a credential index from a /api/credentials/:id URL.

Parameters
NameDirectionMeaning
urlinRequest URL to parse the trailing numeric id from.
Returns
Parsed credential index, or ::kInvalidSlot if the URL has no valid id.

parseHostNamePath() #

bool kleidos::web::adminble::parseHostNamePath(const char * url, uint8_t & outSlot)
constexpr

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
NameDirectionMeaning
urlinRequest URL, already stripped of any query string.
outSlotoutReceives the parsed index on a match; untouched otherwise.
Return values
ValueMeaning
trueurl is exactly this route and outSlot holds the index.
falseurl is some other path.

parseUnsignedSuffix() #

bool kleidos::web::adminapi::parseUnsignedSuffix(const char * url, const char * prefix, uint16_t maxExclusive, uint16_t & out)

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
NameDirectionMeaning
urlinNUL-terminated URL string.
prefixinRequired leading prefix; url must start with this.
maxExclusiveinMaximum acceptable value (exclusive).
outoutReceives the parsed number on success.
Returns
true if a valid decimal number in the range [0, maxExclusive) followed the prefix.

patchNeedsSecret() #

bool kleidos::web::settingslogic::patchNeedsSecret(const kleidos::settings::OptionId * ids, size_t count)
constexpr

Whether a settings patch must carry proof of the unlock secret.

Parameters
NameDirectionMeaning
idsinThe rows the patch writes, already resolved.
countinNumber of entries in ids.
Return values
ValueMeaning
trueAt least one row is one the portal changes only behind the secret (kleidos::settings::needsUnlockSecret).

portalDependsOn() #

kleidos::settings::OptionId kleidos::web::settingslogic::portalDependsOn(const kleidos::settings::SettingsOption & opt)
constexpr

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
NameDirectionMeaning
optinA settings row.
Returns
The row's parent, or OptionId::None when it has none or the parent is device-only.

proveSecretForLoss() #

bool kleidos::web::adminapi::proveSecretForLoss(AdminApiContext & ctx, const uint8_t * data, size_t len, const kleidos::web::secretedit::SecretLoss & loss)

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
NameDirectionMeaning
ctxin, outAdmin API request context; any refusal is sent here.
datainBody bytes.
leninLength of data.
lossinWhat the edit would destroy; at least one field is set.
Return values
ValueMeaning
trueThe secret is proven and the vault is mounted again.
falseRefused; a response was sent and the vault is not mounted.

pump() #

void kleidos::web::admingps::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() #

bool kleidos::web::adminapi::readUnlockSecretFromBody(AdminApiContext & ctx, const uint8_t * data, size_t len, UnlockSecret & out)
nodiscard

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::pin_policy::kPassphraseMax 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
NameDirectionMeaning
ctxin, outAdmin API request context (receives the reject response).
datainBody bytes.
leninLength of data.
outoutReceives the secret; empty on refusal.
Return values
ValueMeaning
trueout holds the body's secret, possibly empty.
falseRefused; a 400 was sent.

refreshDeviceSnapshot() #

void kleidos::web::adminsystem::refreshDeviceSnapshot(PowerManager & pm)

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::begin 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
NameDirectionMeaning
pmin, outPower back-end for the running board.

requestHostIsAllowed() #

bool kleidos::web::requestHostIsAllowed(AdminHttpRequest & request, const char * apIp, const char * apName, HostVerdict linkVerdict)
inline

Whether request may be served, by its Host authority.

Parameters
NameDirectionMeaning
requestinThe request; its one header slot is reused.
apIpinThe address the link reports; empty admits nothing by address.
apNameinThe captive host name the SoftAP's DNS answers with.
linkVerdictinThe transport's own verdict, asked only of a value that was read whole; nullptr when there is none.
Return values
ValueMeaning
trueNo Host, or one the portal answers at.
falseA foreign authority, or a Host that could not be read.

requestReboot() #

void kleidos::web::adminsystem::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() #

void kleidos::web::adminapi::requestSessionEnd(bool relock)

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
NameDirectionMeaning
relockinTrue when the vault must relock with the teardown (session lock, destructive commits, a displaced vault); false for a plain exit.

resetConfirm() #

void kleidos::web::adminapi::resetConfirm()

Wipe any pending confirmation.

The pending entry holds the nonce and a copy of the session token it is bound to. AdminPortal::end calls this so neither outlives the session in RAM; a nonce minted before it can no longer be spent.

resetCredentialBatchStaging() #

void kleidos::web::admincred::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() #

void kleidos::web::adminsystem::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() #

void kleidos::web::admingps::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() #

uint8_t kleidos::web::adminimport::resolveOrCreateGroup(const uint8_t * vaultKey, const char * name)

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
NameDirectionMeaning
vaultKeyinUnlocked session vault key.
nameinGroup 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() #

void kleidos::web::adminapi::sendPortalRedirect(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.

sessionEndWantsLock() #

bool kleidos::web::adminapi::sessionEndWantsLock()

Whether the pending exit also asked for the vault to be relocked.

Returns
True when the request came from /api/session/lock.

takeConfirmNonce() #

bool kleidos::web::adminapi::takeConfirmNonce(AdminApiContext & ctx, const char * action, const char * nonce)

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
NameDirectionMeaning
ctxin, outAdmin API request context.
actioninAction id the nonce must have been minted for.
nonceinNonce from the request body.
Return values
ValueMeaning
trueValid, unexpired, session- and action-matched; now consumed.
falseRefused; a response was sent.

takeNtpSyncOnExit() #

bool kleidos::web::adminapi::takeNtpSyncOnExit()

Take the on-exit NTP sync request, clearing it.

Return values
ValueMeaning
trueA sync was scheduled since the last call.
falseNothing scheduled.

takePendingBeep() #

bool kleidos::web::adminsystem::takePendingBeep()

Take the pending beep request, clearing it.

Return values
ValueMeaning
trueA beep was requested since the last call.
falseNothing pending.

takeRebootRequest() #

bool kleidos::web::adminsystem::takeRebootRequest()

Take the pending reboot request, clearing it.

Return values
ValueMeaning
trueA restart was requested since the last call.
falseNothing pending.

takeSessionEndRequest() #

bool kleidos::web::adminapi::takeSessionEndRequest()

Whether a handler asked the FSM to leave admin mode.

Return values
ValueMeaning
trueAn exit was requested (and the flag is cleared by this call).
falseNothing pending.

tryHandleBleHostDelete() #

bool kleidos::web::adminapi::tryHandleBleHostDelete(AdminHttpRequest * req)

Dynamic route handler for DELETE /api/ble/hosts/:idx.

Parameters
NameDirectionMeaning
reqin, outActive admin HTTP request whose URL is matched.
Returns
true if the URL matched and the response was sent; false otherwise.

tryHandleBleHostRename() #

bool kleidos::web::adminble::tryHandleBleHostRename(AdminHttpRequest * req)

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
NameDirectionMeaning
reqin, outActive admin HTTP request whose URL is matched.
Return values
ValueMeaning
trueThe URL matched this route and a response was sent.
falseThe URL is some other path; the caller keeps dispatching.

tryHandleTotpRoute() #

bool kleidos::web::adminapi::tryHandleTotpRoute(AdminApiContext & ctx)

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
NameDirectionMeaning
ctxin, outPer-request admin API context.
Return values
ValueMeaning
trueThe URL matched a TOTP route and the response was sent.
falseThe URL is not a TOTP route; the caller must keep dispatching.

twoHoldsField() #

std::optional< bool > kleidos::web::settingslogic::twoHoldsField(const kleidos::settings::SettingsCapabilities & caps, int32_t pinMethod)
constexpr

The schema's twoHolds field: whether the dial style is two holds.

Parameters
NameDirectionMeaning
capsinThe board's capabilities.
pinMethodinThe 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() #

bool kleidos::web::adminapi::verifyUnlockSecret(AdminApiContext & ctx, const char * secret, size_t len, const char * tag)

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
NameDirectionMeaning
ctxin, outAdmin API request context (receives the reject response).
secretinThe candidate secret from the request body.
leninLength of secret in bytes.
taginLog tag for the caller's endpoint.
Return values
ValueMeaning
trueThe secret is correct; the brute-force counter has been reset.
falseRefused; a response was sent. Nothing was changed.

verifyUnlockSecretFromBody() #

bool kleidos::web::adminapi::verifyUnlockSecretFromBody(AdminApiContext & ctx, const uint8_t * data, size_t len, const char * tag)

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
NameDirectionMeaning
ctxin, outAdmin API request context.
datainBody bytes.
leninLength of data.
taginLog tag for the caller's endpoint.
Return values
ValueMeaning
trueThe secret is correct.
falseRefused; a response was sent and nothing was changed.

wipeVaultAfterSpentBudget() #

void kleidos::web::adminapi::wipeVaultAfterSpentBudget(AdminAuth & auth)

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
NameDirectionMeaning
authin, outThe session's authenticator, kept alive across the erase, which takes minutes at the per-record cost of every board.

Back to the top

Variable Documentation

kAdminCsp #

const char* kleidos::kAdminCsp
inlineconstexpr

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::setContentSecurityPolicy.

kBodyChunkBytes #

size_t kleidos::web::admintelemetry::kBodyChunkBytes
inlineconstexpr

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 #

size_t kleidos::web::bodycap::kControl
inlineconstexpr

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 #

size_t kleidos::web::kHttpRouteCapacity
inlineconstexpr

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 #

size_t kleidos::web::bodycap::kImportFile
inlineconstexpr

A CSV or flat JSON import file, which the routes parse whole, after the page's blank lead-in.

kLeadIn #

size_t kleidos::web::bodycap::kLeadIn
inlineconstexpr

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 #

size_t kleidos::web::adminapi::kMaxExportPassphrase
inlineconstexpr

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 #

size_t kleidos::web::admintelemetry::kMaxSnapshotSamples
inlineconstexpr

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 #

uint32_t kleidos::web::admintelemetry::kMinPeriodMs
inlineconstexpr

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 #

size_t kleidos::web::adminble::kNameMaxChars
inlineconstexpr

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 #

uint32_t kleidos::web::adminsystem::kPowerSampleIntervalMs
inlineconstexpr

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 #

uint32_t kleidos::web::admintelemetry::kRequestStopBudgetMs
inlineconstexpr

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 #

const char* kleidos::web::settingslogic::kSecretMember
inlineconstexpr

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 #

uint32_t kleidos::web::admintelemetry::kSessionStopBudgetMs
inlineconstexpr

Wait the session teardown gives the sampler to exit: none.

endPortalSession() runs inside AdminPortal::end() 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::serviceFromUiTask() pump completes the release a tick or two later, off the critical path.

kStorageSampleIntervalMs #

uint32_t kleidos::web::adminsystem::kStorageSampleIntervalMs
inlineconstexpr

Minimum spacing between two vault mounts for the storage figures, in milliseconds.

GET /api/system is polled, and the filesystem/record figures are the only part of it that needs the vault mounted. Sampling on a cadence keeps a poll from mounting and unmounting LittleFS on every request while still tracking a credential added from another tab within one interval.

kWideIntBound #

int64_t kleidos::web::adminapi::kWideIntBound
inlineconstexpr

An integer as a request spells it, wide enough that the route, not the binder, judges a value out of its own range.

Back to the top