Kleidos API Search

In development. It changes without notice.

Topic

Admin Portal Rules

The decisions the portal's routes take, with no server behind them.

Whether a session's token is good, what an idle session is told, whether a restore may start, how a field of a CSV or of a code is read, and how much a backup may hold. They are tested on a computer.

See also
Wi-Fi Admin Portal

Files

file src/web/logic/admin_auth_logic.cpp
Implementation of the admin-portal pure security-decision logic.
file src/web/logic/admin_auth_logic.h
Pure security-decision logic for the admin portal (auth gatekeeper).
file src/web/logic/admin_authority_logic.h
Pure logic for the authority the admin portal answers at (host-testable).
file src/web/logic/admin_backup_limits.h
Worst-case size of this device's own backup, from the schema itself.
file src/web/logic/admin_credential_batch_logic.h
Pure id-batch validation and staging for the credential delete batch.
file src/web/logic/admin_header_read.h
What reading one request header found: a value, no header, or one the portal could not read (host-testable).
file src/web/logic/admin_idle_logic.h
Pure logic for the admin portal idle (timeout) endpoint.
file src/web/logic/admin_import_logic.h
Pure request/item validation for the normalized merge-import endpoint.
file src/web/logic/admin_ota_status_logic.h
Pure shaping of the firmware-status read-out (host-testable).
file src/web/logic/admin_rekey_logic.h
Which new PIN lengths the portal's secret change takes on each kind of board, and the refusal it answers otherwise (host-testable).
file src/web/logic/admin_restore_gate_logic.h
Pure refusal logic for the vault-restore endpoints (host-testable).
file src/web/logic/admin_secret_edit_logic.h
Which edits of a stored record destroy a secret the device cannot give back.
file src/web/logic/admin_system_logic.h
Pure, host-testable logic behind the admin portal's device-information API.
file src/web/logic/admin_time_diag_logic.h
Pure formatting of the RTC-health read-out (host-testable).
file src/web/logic/admin_totp_logic.h
Pure decision + formatting logic behind the admin portal TOTP endpoints.
file src/web/logic/csv_credential_parser.h
RFC 4180 CSV credential line parser, extracted for testability.
file src/web/logic/telemetry_encode.h
Pure columnar JSON encoder for the telemetry history response.
file src/web/logic/totp_field_logic.h
Pure parser for the shared embedded-TOTP wire contract.

Namespaces

namespace kleidos::web::rekey
The portal secret change's PIN-length rule, per kind of board.

Classes

struct kleidos::web::authlogic::RateLimitEntry
Per-client-IP rate-limit bookkeeping (one slot per tracked client). More about kleidos::web::authlogic::RateLimitEntry
struct kleidos::web::authlogic::RateLimitConfig
Rate-limit thresholds: max requests per window for each route family. More about kleidos::web::authlogic::RateLimitConfig
class kleidos::web::admincred::BatchIdCollector< MaxIds >
Validating accumulator for a batch of credential slot ids. More about kleidos::web::admincred::BatchIdCollector< MaxIds >
class kleidos::web::admincred::StagedIdBatch< MaxIds >
The single batch a prepare staged, waiting for its commit. More about kleidos::web::admincred::StagedIdBatch< MaxIds >
struct kleidos::web::IdleResponse
Result of an idle-timeout evaluation for the admin portal. More about kleidos::web::IdleResponse
struct kleidos::web::adminimport::TruncationReport
Bounded collector of field names whose submitted value was truncated. More about kleidos::web::adminimport::TruncationReport
struct kleidos::web::adminimport::CustomBody
One custom entry, as the binder reads it. More about kleidos::web::adminimport::CustomBody
struct kleidos::web::adminimport::KeptCustom
One custom entry kept until its record is assembled. More about kleidos::web::adminimport::KeptCustom
struct kleidos::web::adminimport::HistoryBody
One history entry, as the binder reads it. More about kleidos::web::adminimport::HistoryBody
struct kleidos::web::adminimport::ImportItemBody
One item of POST /api/import/items, as the binder reads it. More about kleidos::web::adminimport::ImportItemBody
struct kleidos::web::adminimport::KeptHistory
One history entry kept until its record is assembled. More about kleidos::web::adminimport::KeptHistory
struct kleidos::web::adminimport::ItemArrays
What one item's arrays held. More about kleidos::web::adminimport::ItemArrays
struct kleidos::web::adminimport::ParsedImportItem
One normalized import item, decoded and ready for the vault. More about kleidos::web::adminimport::ParsedImportItem
struct kleidos::web::adminimport::ImportPass
One pass over the request. More about kleidos::web::adminimport::ImportPass
struct kleidos::web::adminimport::ImportBody
The body of POST /api/import/items: the items go to the hook one by one. More about kleidos::web::adminimport::ImportBody
struct kleidos::web::otastatus::AttemptView
Snapshot of the portal's OTA upload state (mirrors OtaProgress fields). More about kleidos::web::otastatus::AttemptView
struct kleidos::web::secretedit::SecretLoss
What a credential edit would destroy, field by field. More about kleidos::web::secretedit::SecretLoss
struct kleidos::web::adminsystem::HardwareRow
One row of the board hardware inventory reported by GET /api/system/hardware. More about kleidos::web::adminsystem::HardwareRow
struct kleidos::web::adminsystem::AudioOutputLabel
The part and bus the inventory's audio row names. More about kleidos::web::adminsystem::AudioOutputLabel
struct kleidos::web::adminsystem::ChipProbe
What the register-map registry said about one chip, as plain values. More about kleidos::web::adminsystem::ChipProbe
struct kleidos::web::timediag::AlarmView
Decoded alarm registers, HAL-type-free (mirrors RtcAlarm field for field). More about kleidos::web::timediag::AlarmView
struct kleidos::web::totp::Route
A matched dynamic TOTP route: its shape plus the slot id parsed from the URL. More about kleidos::web::totp::Route
struct kleidos::web::totp::WriteParams
A TOTP write body's digits and period after the strict read. More about kleidos::web::totp::WriteParams
struct kleidos::web::CsvRow
In-progress CSV row accumulator: four bounded fields plus a field cursor. More about kleidos::web::CsvRow
struct kleidos::web::telemetryencode::EncodeInput
Everything the encoder needs about the run and its ring snapshot. More about kleidos::web::telemetryencode::EncodeInput
struct kleidos::web::telemetryencode::EncodeResult
Outcome of one encodeTelemetryBody call. More about kleidos::web::telemetryencode::EncodeResult
class kleidos::web::telemetryencode::JsonBodyWriter
Bounded append-only text sink that can never overrun its buffer. More about kleidos::web::telemetryencode::JsonBodyWriter
struct kleidos::web::totpfield::FieldParse
Outcome of parseTotpField. When error is non-null the request (or the one import item) is refused with that text; nothing was decided. More about kleidos::web::totpfield::FieldParse
struct kleidos::web::totpfield::TotpBody
The "totp" object of a credential-write body, as the binder reads it. More about kleidos::web::totpfield::TotpBody
struct kleidos::web::totpfield::TotpMember
What a write body said of its "totp" member. More about kleidos::web::totpfield::TotpMember

Typedefs

usingkleidos::web::adminimport::ItemFn
usingkleidos::web::telemetryencode::ChannelNameFn
Resolves a registry index to a channel name (kleidos::diag::telemetry::channelName).
usingkleidos::web::telemetryencode::ChunkSink
Destination for one completed chunk of body text.

Enumerations

enum class kleidos::web::admincred::BatchIdError : uint8_t { kleidos::web::admincred::BatchIdError::None, kleidos::web::admincred::BatchIdError::Empty, kleidos::web::admincred::BatchIdError::TooMany, kleidos::web::admincred::BatchIdError::NotAnId, kleidos::web::admincred::BatchIdError::Duplicate }
Why a submitted id batch was rejected. More about kleidos::web::admincred::BatchIdError
enum class kleidos::web::headerread::HeaderRead : uint8_t { kleidos::web::headerread::HeaderRead::Absent , kleidos::web::headerread::HeaderRead::Value , kleidos::web::headerread::HeaderRead::Unreadable }
What a read of one request header found. More about kleidos::web::headerread::HeaderRead
enum kleidos::web::adminimport::ImportItemMember : uint8_t
enum class kleidos::web::restoregate::Refusal : uint8_t { Refusal::None , Refusal::BodyTooLarge , Refusal::SecretMissing , Refusal::SecretTooLong }
Outcome of the cheap pre-verification checks on a restore request. More about kleidos::web::restoregate::Refusal
enum class kleidos::web::restoregate::Outcome : uint8_t { Outcome::Restored, Outcome::Rejected, Outcome::PartiallyWritten, Outcome::DoesNotFit, Outcome::PartiallyRefused, Outcome::LeftOut }
What the device tells the client about a FINISHED restore attempt. More about kleidos::web::restoregate::Outcome
enum class kleidos::web::secretedit::SeedWrite : uint8_t { kleidos::web::secretedit::SeedWrite::Keep , kleidos::web::secretedit::SeedWrite::Detach , kleidos::web::secretedit::SeedWrite::NewSecret }
What an edit does to the embedded seed. More about kleidos::web::secretedit::SeedWrite
enum class kleidos::web::adminsystem::BuildFlavor : uint8_t { kleidos::web::adminsystem::BuildFlavor::Debug, kleidos::web::adminsystem::BuildFlavor::SecureDev, kleidos::web::adminsystem::BuildFlavor::Secure, kleidos::web::adminsystem::BuildFlavor::Release, kleidos::web::adminsystem::BuildFlavor::Dev }
Which of the five kinds of build produced the running firmware. More about kleidos::web::adminsystem::BuildFlavor
enum class kleidos::web::totp::RouteKind : uint8_t { kleidos::web::totp::RouteKind::None , kleidos::web::totp::RouteKind::Entry , kleidos::web::totp::RouteKind::EntryCode , kleidos::web::totp::RouteKind::CredentialCode }
URL shapes the dynamic TOTP dispatcher understands. More about kleidos::web::totp::RouteKind
enum class kleidos::web::totpfield::FieldAction : uint8_t { kleidos::web::totpfield::FieldAction::Absent , kleidos::web::totpfield::FieldAction::Detach , kleidos::web::totpfield::FieldAction::Set }
What the optional "totp" field asked for. More about kleidos::web::totpfield::FieldAction

Functions

boolkleidos::web::authlogic::decideRateLimit (RateLimitEntry *entries, uint8_t count, uint32_t clientIp, uint32_t nowMs, bool isBootstrap, const RateLimitConfig &cfg)
Decide whether a request is within its per-IP rate limit, updating the slots.
boolkleidos::web::authlogic::isSessionTokenValid (uint32_t nowMs, uint32_t createdMs, uint32_t timeoutMs, const char *providedToken, size_t providedLen, const char *expectedToken, size_t expectedLen)
Constant-time validity check for an X-Session-Token header value.
boolkleidos::web::authlogic::verifyBasicAuth (const char *authHeaderValue, const char *expectedPassword)
Validate an HTTP Basic-Auth header value against the derived OTA password.
voidkleidos::web::authlogic::toHexLower (char *dst, const uint8_t *bytes, size_t byteCount)
Write byteCount bytes as lowercase hex into dst (NUL-terminated).
constexpr boolkleidos::web::authority::hasNamedAddress (const char *address)
Whether the portal has an address it can name in an absolute URL.
constexpr boolkleidos::web::authority::hostAuthorityMatches (const char *host, const char *expected)
Case-insensitive compare of a Host value against one authority.
constexpr boolkleidos::web::authority::isLoopbackAuthority (const char *host)
Whether a Host value names the client's own loopback.
constexpr boolkleidos::web::authority::hostIsAllowed (headerread::HeaderRead read, const char *host, const char *apIp, const char *apName, bool linkAccepts)
Whether a request's Host authority is one the portal answers at.
constexpr const char *kleidos::web::authority::redirectTarget (char *out, size_t capacity, const char *address)
Where a request is redirected to reach the panel.
constexpr HeaderReadkleidos::web::headerread::classifyRead (platform::http::HeaderPresence presence, size_t valueLength, size_t slotBytes)
Classify a header by whether the transport reports it and how long its value is.
constexpr IdleResponsekleidos::web::decideIdleResponse (uint32_t elapsedMs, uint32_t timeoutMs, uint32_t warningThresholdMs)
Evaluate the admin-portal idle timer.
size_tkleidos::web::adminimport::boundLen (const json::Bound &bound, size_t index, const char *text, size_t capacity)
The length a truncation check is told for a bound text member.
boolkleidos::web::adminimport::overflowed (const json::Bound &bound, size_t index)
boolkleidos::web::adminimport::present (const json::Bound &bound, size_t index)
uint32_tkleidos::web::adminimport::unsignedOrZero (int64_t value)
uint16_tkleidos::web::adminimport::flagsOf (int64_t value)
voidkleidos::web::adminimport::customFieldOf (const KeptCustom &kept, const char *token, TruncationReport &truncated, CustomField &field)
A custom field from its bound entry, and its truncation checks.
const char *kleidos::web::adminimport::validateItemCount (size_t count)
Judge the size of the items array of POST /api/import/items.
const char *kleidos::web::adminimport::parseImportItem (ImportItemBody &item, const json::Bound &bound, const ItemArrays &arrays, bool generateMissing, ParsedImportItem &out)
Decode and validate one normalized item.
boolkleidos::web::adminimport::takeCustom (void *user, const void *element, const json::Bound &bound)
A custom entry closed: kept while the record has room for it.
boolkleidos::web::adminimport::takeUrl (void *user, const json::Entry &entry)
A urls entry arrived: an empty one is not one; the first ones the record holds are kept, the rest dropped.
boolkleidos::web::adminimport::takeHistory (void *user, const void *element, const json::Bound &bound)
A history entry closed: one with no password records nothing; the first ones the record holds are kept.
boolkleidos::web::adminimport::takeItem (void *user, const void *element, const json::Bound &bound)
An item closed: handed on with its arrays, which are then forgotten.
constexpr boolkleidos::web::otastatus::rollbackPending (kleidos::platform::ota::ImageState state)
Whether the running image is still on rollback trial.
constexpr const char *kleidos::web::otastatus::stageLabel (const AttemptView &attempt)
One-word stage of the last/current OTA attempt for the status row.
constexpr const char *kleidos::web::rekey::pinLengthRefusal (security::pin_policy::SetSurface surface)
The refusal for a pin_length surface does not take.
constexpr boolkleidos::web::rekey::pinLengthAccepted (security::pin_policy::SetSurface surface, int requested)
Whether a requested pin_length is one surface takes.
constexpr boolkleidos::web::rekey::passphraseAccepted (security::pin_policy::SetSurface surface)
Whether surface can collect a new passphrase (a body without pin_length).
constexpr security::pin_policy::SecretKindkleidos::web::rekey::newSecretKind (bool pinLengthGiven)
The kind the new secret is recorded as: the one the body asked for.
constexpr size_tkleidos::web::restoregate::frameLength (const uint8_t *data, size_t len)
Length of the secrets frame at the start of data.
constexpr boolkleidos::web::restoregate::hasLeadIn (const uint8_t *data, size_t len)
Whether a secrets frame opens with the lead-in: bodycap::kLeadIn spaces.
constexpr Refusalkleidos::web::restoregate::checkRestoreSize (size_t bodyLen, size_t bodyCap)
The size check a restore request takes before a byte of it is read.
constexpr Refusalkleidos::web::restoregate::checkRestoreSecret (size_t secretLen, size_t secretCap)
The shape check on the unlock secret the frame carried.
constexpr Refusalkleidos::web::restoregate::checkRestoreRequest (size_t bodyLen, size_t bodyCap, size_t secretLen, size_t secretCap)
Run the size and secret-shape checks for a restore request.
constexpr uint16_tkleidos::web::restoregate::refusalStatus (Refusal refusal)
HTTP status code for a refusal.
constexpr const char *kleidos::web::restoregate::refusalBody (Refusal refusal)
JSON error body for a refusal.
constexpr Outcomekleidos::web::restoregate::outcomeFor (kleidos::vault::backup::ImportStatus status)
Translate a vault restore result into the client-facing outcome.
constexpr uint16_tkleidos::web::restoregate::outcomeStatus (Outcome outcome)
HTTP status code for a finished restore.
constexpr const char *kleidos::web::restoregate::outcomeBody (Outcome outcome)
JSON response body for a finished restore.
boolkleidos::web::restoregate::fillRequested (const char *value)
Whether a kFillHeader value says "go on".
const char *kleidos::web::restoregate::formatOutcomeBody (Outcome outcome, const kleidos::vault::backup::RestoreTally &tally, char *out, size_t cap)
JSON body for a finished restore, with the counts the owner is told.
constexpr boolkleidos::web::secretedit::seedLost (bool storedSeed, SeedWrite write)
Whether an edit loses the stored seed.
boolkleidos::web::secretedit::stringLost (const kleidos::vault::CredentialPool &stored, kleidos::vault::CredPoolType type, const char *next)
Whether writing next over a single-string pool entry loses it.
template<typename NextValues>
boolkleidos::web::secretedit::hiddenValueLost (const kleidos::vault::CredentialPool &stored, const NextValues &next)
Whether a new custom-field set loses a stored hidden value.
constexpr BuildFlavorkleidos::web::adminsystem::selectBuildFlavor (bool debugBuild, bool secureDev, bool secure, bool release)
Resolve the build flavor from the four build-time predicates.
constexpr const char *kleidos::web::adminsystem::buildFlavorName (BuildFlavor flavor)
Stable wire token for a build flavor.
constexpr const char *kleidos::web::adminsystem::busKindName (kleidos::drivers::regmap::BusKind bus)
Stable wire token for a register-map bus kind.
constexpr AudioOutputLabelkleidos::web::adminsystem::describeAudioOutput (device::AudioOutput kind, bool driven)
Name the audio output a board carries, and whether this firmware drives it.
constexpr ChipProbekleidos::web::adminsystem::chipProbeFrom (const kleidos::drivers::regmap::ChipRegmap *map)
Turn a register-map lookup result into a core-crossing observation.
constexpr ChipProbekleidos::web::adminsystem::driverProbe (bool responded)
Turn a driver's own presence probe into a core-crossing observation.
constexpr voidkleidos::web::adminsystem::applyChipProbe (HardwareRow &row, const ChipProbe &probe)
Apply a sampled observation to a compile-time inventory row.
voidkleidos::web::timediag::formatAlarm (const AlarmView &alarm, char *out, size_t cap)
Render the alarm state as one human-readable line.
constexpr const char *kleidos::web::timediag::countdownLabel (bool readOk, bool running)
One-word countdown-timer state.
Routekleidos::web::totp::matchRoute (const char *url, uint16_t maxTotp, uint16_t maxCredentials)
Match a request URL against the dynamic TOTP route shapes.
boolkleidos::web::totp::isPolledCodeRoute (const char *url, uint16_t maxTotp, uint16_t maxCredentials)
True when url is a live-code route the SPA polls on a timer.
constexpr intkleidos::web::totp::decideCodeStatus (kleidos::totp::Gate gate, bool entryFound, bool hasSecret)
Decide the HTTP status of a live-code request.
constexpr const char *kleidos::web::totp::gateRefusalJson (kleidos::totp::Gate gate, bool hasRtc)
The ::kStatusClockUntrusted body for a refused verdict.
WriteParamskleidos::web::totp::readWriteParams (const char *body, size_t len)
Read and judge the digits and period of a TOTP write body.
std::stringkleidos::web::totp::formatCode (uint32_t code, uint8_t digits)
Render a code as its fixed-width, zero-padded decimal string.
std::stringkleidos::web::totp::buildMetadataJson (uint16_t id, const char *name, uint8_t digits, uint32_t period, uint8_t algorithm, bool hasSecret)
Build the GET /api/totp/:id metadata body.
std::stringkleidos::web::totp::buildCodeJson (uint16_t id, uint32_t code, uint8_t digits, uint32_t period, uint8_t remaining)
Build a live-code body for either code route.
boolkleidos::web::isCsvTrimChar (char ch)
True when ch is a CSV line-trimming character (space, tab, CR, LF).
voidkleidos::web::appendCsvQuotedChar (char ch, const char *line, size_t length, size_t &index, CsvRow &row, bool &inQuote)
Handle one character inside a quoted CSV field (RFC 4180 §2.7).
boolkleidos::web::parseCsvCredentialLine (const char *line, size_t length, Credential &credential)
Parse one CSV line into a Credential (name, user, pass, url) using RFC 4180 quoting.
size_tkleidos::web::telemetryencode::decimationStride (size_t sampleCount, size_t maxEmitted)
Smallest decimation stride that keeps sampleCount within maxEmitted.
size_tkleidos::web::telemetryencode::bodyBufferBytes (size_t sampleCount)
Buffer size to allocate for a body holding sampleCount samples.
EncodeResultkleidos::web::telemetryencode::encodeTelemetryBody (const EncodeInput &in, char *out, size_t outCapacity)
Encode a ring snapshot as the GET /api/telemetry body.
EncodeResultkleidos::web::telemetryencode::streamTelemetryBody (const EncodeInput &in, char *scratch, size_t scratchBytes, ChunkSink sink, void *sinkCtx)
Emit the GET /api/telemetry body through a chunk sink.
boolkleidos::web::totpfield::algorithmFromString (const char *text, uint8_t &out)
Map a wire algorithm name to its stored value (forwards to TotpGenerator).
constexpr const char *kleidos::web::totpfield::algorithmName (uint8_t algorithm)
The wire name of a stored algorithm value.
voidkleidos::web::totpfield::percentDecode (const char *in, size_t inLen, char *out, size_t outCap)
Decode XX escapes of a URI component (forwards to TotpGenerator).
boolkleidos::web::totpfield::isOtpauthUri (const char *text)
Whether text begins with otpauth:// (forwards to TotpGenerator).
const char *kleidos::web::totpfield::parseOtpauthUri (const char *uri, TotpEntry &entry)
Parse an otpauth:// URI into entry.
FieldParsekleidos::web::totpfield::parseTotpField (const TotpMember &member, bool hasStoredSecret, TotpEntry &entry)
Decode the optional "totp" field of a credential-write body.

Variables

constexpr const char *kleidos::web::authority::kSelfPath
Target a request is given when the portal has no address to name in a URL.
constexpr const char *kleidos::web::authority::kHttpScheme
Scheme and separator of the absolute URL redirectTarget builds.
constexpr const char *kleidos::web::authority::kLoopbackIp
Dotted quad a forwarder on the client's own machine is reached at.
constexpr const char *kleidos::web::authority::kLoopbackName
Name that same forwarder is reached by.
constexpr size_tkleidos::web::backuplimits::kJsonEscapeFactor
Worst-case JSON expansion of one stored byte (\uXXXX for control bytes).
constexpr size_tkleidos::web::backuplimits::kTotpSecretB64Max
Base64 length of a maximum raw TOTP secret (4 chars per 3 bytes, rounded up).
constexpr size_tkleidos::web::backuplimits::kBackupCredFixedOverhead
constexpr size_tkleidos::web::backuplimits::kBackupTotpFixedOverhead
constexpr size_tkleidos::web::backuplimits::kBackupEnvelopeFixedOverhead
constexpr size_tkleidos::web::backuplimits::kBackupCredentialMaxBytes
constexpr size_tkleidos::web::backuplimits::kBackupTotpMaxBytes
Worst-case serialized size of one standalone-TOTP row.
constexpr size_tkleidos::web::backuplimits::kBackupMetaB64Bytes
constexpr size_tkleidos::web::backuplimits::kBackupCarriedMetaB64MaxBytes
constexpr size_tkleidos::web::backuplimits::kRestoreBodyCapBytes
Body cap for POST /api/restore — the largest plaintext backup any board writes: as many records as the biggest board has slots, each at its schema maximum, under the longest meta any board's backup carries.
constexpr size_tkleidos::web::backuplimits::kRestoreEncryptedBodyCapBytes
constexpr size_tkleidos::web::adminimport::kMaxItemsPerRequest
Largest accepted items array per request; bigger imports arrive batched.
constexpr size_tkleidos::web::adminimport::kImportBodyCap
constexpr uint8_tkleidos::web::adminimport::kGeneratedPassLen
constexpr const char *kleidos::web::adminimport::kErrNoItems
Missing/empty array.
constexpr const char *kleidos::web::adminimport::kErrTooManyItems
Batch cap hit.
constexpr const char *kleidos::web::adminimport::kErrNameRequired
Empty name.
constexpr const char *kleidos::web::adminimport::kErrPasswordMissing
Passwordless without opt-in.
constexpr const char *kleidos::web::adminimport::kErrVaultFull
No free slot for this item.
constexpr const char *kleidos::web::adminimport::kErrSaveFailed
Vault write failed.
constexpr uint32_tkleidos::web::adminimport::kMaxArrayEntries
constexpr size_tkleidos::web::adminimport::kCustomLabel
Index of label in kCustomMembers.
constexpr size_tkleidos::web::adminimport::kCustomValue
Index of value in kCustomMembers.
constexpr json::Memberkleidos::web::adminimport::kCustomMembers []
The members of one custom entry.
constexpr json::ObjectSpeckleidos::web::adminimport::kCustomSpec
The table of one custom entry.
constexpr std::array< const char *, kMaxCustomFields >kleidos::web::adminimport::kCustomTokens
The static report token of each of the twelve custom fields.
constexpr size_tkleidos::web::adminimport::kHistoryPass
Index of pass in kHistoryMembers.
constexpr json::Memberkleidos::web::adminimport::kHistoryMembers []
The members of one history entry.
constexpr json::ObjectSpeckleidos::web::adminimport::kHistorySpec
The table of one history entry.
constexpr size_tkleidos::web::adminimport::kColumnSlack
constexpr json::Memberkleidos::web::adminimport::kImportItemMembers []
The members of one item.
constexpr json::ObjectSpeckleidos::web::adminimport::kImportItemSpec
The table of one item.
constexpr size_tkleidos::web::adminimport::kImportItems
Index of items in kImportMembers.
constexpr json::Memberkleidos::web::adminimport::kImportMembers []
The members of the request.
constexpr json::ObjectSpeckleidos::web::adminimport::kImportSpec
The table of the request.
constexpr std::array< const char *, 3 >kleidos::web::rekey::kPinLengthRefusal
constexpr const char *kleidos::web::rekey::kPassphraseRefusal
constexpr size_tkleidos::web::restoregate::kFrameCap
The most bytes a restore body's secrets frame may take.
constexpr const char *kleidos::web::restoregate::kFillHeader
The request header that answers a DoesNotFit refusal with "go on": the value 1 restores the backup's entries in its own order until the device is full and leaves the rest out (OverCapacity::FillInOrder).
constexpr size_tkleidos::web::restoregate::kOutcomeBodyCap
Bytes a finished restore's body may take with its counts appended: the longest static body plus three count objects of ten-digit numbers.
constexpr size_tkleidos::web::timediag::kAlarmTextCap
Longest alarm text: "monthly day 31, weekday 6 at 23:59" + terminator.
constexpr intkleidos::web::totp::kStatusOk
Request served.
constexpr intkleidos::web::totp::kStatusBadRequest
Malformed body or illegal field value.
constexpr intkleidos::web::totp::kStatusNotFound
No such slot, or the slot has no secret.
constexpr intkleidos::web::totp::kStatusMethodNotAllowed
URL matched, method did not.
constexpr intkleidos::web::totp::kStatusClockUntrusted
The TOTP gate refused a code.
constexpr intkleidos::web::totp::kStatusPayloadTooLarge
Declared body exceeds the cap.
constexpr intkleidos::web::totp::kStatusInternalError
Vault mount / save failure.
constexpr intkleidos::web::totp::kStatusServiceUnavailable
Body buffer could not be allocated.
constexpr const char *kleidos::web::totp::kCodesOffJson
Body paired with ::kStatusClockUntrusted when the 2FA codes setting is off.
constexpr const char *kleidos::web::totp::kClockUnsetJson
constexpr const char *kleidos::web::totp::kClockUnsetPreciseJson
constexpr const char *kleidos::web::totp::kClockNotSyncedJson
constexpr const char *kleidos::web::totp::kNotFoundJson
Body paired with ::kStatusNotFound.
constexpr const char *kleidos::web::totp::kDigitsRefusedJson
Body paired with ::kStatusBadRequest for a written digits other than 6 or 8.
constexpr const char *kleidos::web::totp::kPeriodRefusedJson
Body paired with ::kStatusBadRequest for a written period other than 30 or 60.
constexpr const char *kleidos::web::totp::kAlgorithmRefusedJson
Body paired with ::kStatusBadRequest for a written algorithm other than SHA-1 or SHA-256.
constexpr size_tkleidos::web::totp::kCodeBodyReserve
constexpr size_tkleidos::web::telemetryencode::kResponseBudgetBytes
Total byte budget for the response body (also the buffer the caller allocates).
constexpr size_tkleidos::web::telemetryencode::kBytesPerEmittedSample
Planning estimate for one emitted sample: time delta + value, both with commas.
constexpr size_tkleidos::web::telemetryencode::kEnvelopeBytes
Allowance for the scalar header, the channel-name array, and series scaffolding.
constexpr size_tkleidos::web::telemetryencode::kMaxEmittedSamples
Largest number of samples the budget admits (see the file-header arithmetic).
constexpr uint8_tkleidos::web::telemetryencode::kMaxEncodeAttempts
Stride doublings attempted before giving up on fitting the budget.
constexpr uint8_tkleidos::web::totpfield::kAlgSha1
HMAC-SHA1, RFC 6238 default.
constexpr uint8_tkleidos::web::totpfield::kAlgSha256
HMAC-SHA256.
constexpr size_tkleidos::web::totpfield::kSecretFieldBytes
constexpr size_tkleidos::web::totpfield::kAccountFieldBytes
constexpr size_tkleidos::web::totpfield::kAlgorithmFieldBytes
Room for the longest algorithm name and more; a longer one is refused.
constexpr size_tkleidos::web::totpfield::kTotpBodySecret
Index of each member in kTotpBodyMembers.
constexpr size_tkleidos::web::totpfield::kTotpBodyAccount
account.
constexpr size_tkleidos::web::totpfield::kTotpBodyAlgorithm
algorithm.
constexpr size_tkleidos::web::totpfield::kTotpBodyDigits
digits.
constexpr size_tkleidos::web::totpfield::kTotpBodyPeriod
period.
constexpr int64_tkleidos::web::totpfield::kWideIntBound
constexpr json::Memberkleidos::web::totpfield::kTotpBodyMembers []
The members of the "totp" object.
constexpr json::ObjectSpeckleidos::web::totpfield::kTotpBodySpec
The nested table of the "totp" object.

Back to the top

Typedef Documentation

ChunkSink #

using kleidos::web::telemetryencode::ChunkSink

Destination for one completed chunk of body text.

Parameters
NameDirectionMeaning
ctxinOpaque caller context.
datainChunk bytes; not NUL-terminated.
lengthinNumber of bytes in data.
Return values
ValueMeaning
trueChunk accepted; emission continues.
falseSink failed (e.g. the peer disconnected); emission stops and the result is reported as unusable.

ItemFn #

using kleidos::web::adminimport::ItemFn

Called as each item closes, with what it held.

Parameters
NameDirectionMeaning
userinThe pass's user pointer.
itemin, outThe bound item.
boundinWhat it held.
arraysinIts array entries.
Returns
False to stop the bind.

Back to the top

Enumeration Type Documentation

BatchIdError #

enum class kleidos::web::admincred::BatchIdError : uint8_t

Why a submitted id batch was rejected.

Enumerator
None 

The batch is well-formed.

Empty 

No ids were submitted.

TooMany 

More ids than the batch cap allows.

NotAnId 

A value is negative, fractional, or past the slot range.

Duplicate 

The same slot id appears twice.

BuildFlavor #

enum class kleidos::web::adminsystem::BuildFlavor : uint8_t

Which of the five kinds of build produced the running firmware.

The base open build, the debug build, the open release build, the hardened build, and the hardened build's bench twin with Flash Encryption in development mode.

Enumerator
Debug 

Debug build: serial console, fast key derivation. Never shipped.

SecureDev 

Bench build: Secure Boot + development-mode Flash Encryption.

Secure 

Hardened build (eFuses burned).

Release 

Open release build, re-flashable.

Dev 

The base open build.

FieldAction #

enum class kleidos::web::totpfield::FieldAction : uint8_t

What the optional "totp" field asked for.

Enumerator
Absent 

Field omitted — preserve whatever is stored.

Detach 

Explicit "totp": null — remove the stored TOTP.

Set 

A TOTP object — write entry as the new embedded TOTP.

HeaderRead #

enum class kleidos::web::headerread::HeaderRead : uint8_t

What a read of one request header found.

Enumerator
Absent 

The request carries no such header.

Value 

The value was read whole into the slot; it may be empty.

Unreadable 

Present but longer than the slot, or the transport could not say.

ImportItemMember #

enum kleidos::web::adminimport::ImportItemMember : uint8_t

Index of each member in the item table, as the report and presence checks name them.

Outcome #

enum class kleidos::web::restoregate::Outcome : uint8_t

What the device tells the client about a FINISHED restore attempt.

The gate above decides whether a restore may start; this decides what the client is told once one has run. The failures are not interchangeable: a rejected backup leaves the vault exactly as it was, while the two partial answers have already replaced it with a strict subset of the backup. Answering either of those with the first ("invalid backup", 400) is both the wrong reason and a dangerous understatement — the owner is not told that their vault changed, so they never learn the backup file is the whole copy.

The two partial answers carry the same fact about the vault and opposite advice about what to do next, which is why they are separate outcomes rather than one with two sentences:

  • PartiallyWritten — the DEVICE did not manage to write what the file carried. Sending the same file again can complete the vault, so that is what the owner is told.
  • PartiallyRefused — the device wrote everything it accepted, and the entries that are missing are ones this build does not read. Nothing failed here, and sending the same file again produces the same vault and the same answer. Telling this owner to "restore it again" sends them round a loop with no exit.
Enumerator
Restored 

The vault now holds exactly the backup.

Rejected 

Refused before any write; the vault is untouched.

PartiallyWritten 

A write did not land; the vault was rewritten.

DoesNotFit 

A good backup of a bigger device; refused, untouched.

PartiallyRefused 

Entries this build refuses were dropped; vault rewritten.

LeftOut 

The device filled up: the backup's first entries landed, in its order, and the rest were left out; vault rewritten.

Refusal #

enum class kleidos::web::restoregate::Refusal : uint8_t

Outcome of the cheap pre-verification checks on a restore request.

Enumerator
None 

Shape is acceptable; proceed to the secret verify.

BodyTooLarge 

Declared body exceeds the biggest backup bound of any board.

SecretMissing 

No secrets frame, one without its lead-in, or one without a secret.

SecretTooLong 

Secret exceeds the unlock-secret cap (would truncate).

RouteKind #

enum class kleidos::web::totp::RouteKind : uint8_t

URL shapes the dynamic TOTP dispatcher understands.

Enumerator
None 

Not a TOTP URL (the caller must keep dispatching).

Entry 

/api/totp/:id — metadata read / metadata update / delete.

EntryCode 

/api/totp/:id/code — live code for a standalone entry.

CredentialCode 

/api/credentials/:id/totp/code — live code for an embedded TOTP.

SeedWrite #

enum class kleidos::web::secretedit::SeedWrite : uint8_t

What an edit does to the embedded seed.

Enumerator
Keep 

The seed stays (field absent, or a parameters-only object).

Detach 

An explicit "totp": null.

NewSecret 

The body carries a secret that replaces whatever is stored.

Back to the top

Function Documentation

algorithmFromString() #

bool kleidos::web::totpfield::algorithmFromString(const char * text, uint8_t & out)
inline

Map a wire algorithm name to its stored value (forwards to TotpGenerator).

Parameters
NameDirectionMeaning
textinNUL-terminated name: SHA1 / SHA-1 / SHA256 / SHA-256, any case.
outoutReceives ::kAlgSha1 or ::kAlgSha256 on success.
Return values
ValueMeaning
trueRecognized name.
falseUnknown name; out untouched.

algorithmName() #

const char * kleidos::web::totpfield::algorithmName(uint8_t algorithm)
inlineconstexpr

The wire name of a stored algorithm value.

Parameters
NameDirectionMeaning
algorithmin::kAlgSha1 or ::kAlgSha256; any other value reads as SHA-1, the value an unknown stored id is clamped to.
Returns
"SHA256" for ::kAlgSha256, otherwise "SHA1".

appendCsvQuotedChar() #

void kleidos::web::appendCsvQuotedChar(char ch, const char * line, size_t length, size_t & index, CsvRow & row, bool & inQuote)
inline

Handle one character inside a quoted CSV field (RFC 4180 §2.7).

A doubled "" escape emits one literal " and advances index past both. A lone " closes the quoted region.

Parameters
NameDirectionMeaning
chinCurrent character.
lineinStart of the CSV line buffer.
lengthinLength of the line buffer in bytes.
indexin, outCurrent position within the line; may advance by 1 on a "" escape.
rowoutAccumulator receiving the unescaped character.
inQuoteoutSet to false when the closing " is consumed.

applyChipProbe() #

void kleidos::web::adminsystem::applyChipProbe(HardwareRow & row, const ChipProbe & probe)
constexpr

Apply a sampled observation to a compile-time inventory row.

Only ever adds information: present is left untouched, so a chip whose driver has no register map (or has not run yet) still reports the board's fitted hardware. An observed row gains probeKnown and a real probed value; a registered map additionally overrides bus and, for bus-addressed chips, address with the values the driver actually talks to. An unobserved probe leaves the row exactly as the caller built it, so a part that proves its own presence by other means (PSRAM, a mounted card) keeps the probe result it already set.

Parameters
NameDirectionMeaning
rowin, outRow to enrich in place.
probeinObservation sampled by chipProbeFrom.

bodyBufferBytes() #

size_t kleidos::web::telemetryencode::bodyBufferBytes(size_t sampleCount)
inline

Buffer size to allocate for a body holding sampleCount samples.

The budget is the ceiling, not the allocation: a poll against an idle or barely-filled ring should not cost a full 12 KB on the Core-0 HTTP task while the WiFi AP holds most of the heap. This right-sizes to the estimate plus half again, so a run of unusually wide values still fits without forcing a needless decimation retry, and clamps to ::kResponseBudgetBytes.

Parameters
NameDirectionMeaning
sampleCountinSamples the body will carry.
Returns
Bytes to allocate, including the NUL slot.

boundLen() #

size_t kleidos::web::adminimport::boundLen(const json::Bound & bound, size_t index, const char * text, size_t capacity)
inline

The length a truncation check is told for a bound text member.

A text member binds into a field one byte past its vault column, clamping a longer one; the binder marks it overflowed. A check needs only to know that it was longer than the column, so an overflowed member reports one past it.

Parameters
NameDirectionMeaning
boundinWhat the object held.
indexinThe member's index in its table.
textinThe bound text.
capacityinThe vault's column for the member.
Returns
The text's length, or capacity + 1 when it overflowed.

buildCodeJson() #

std::string kleidos::web::totp::buildCodeJson(uint16_t id, uint32_t code, uint8_t digits, uint32_t period, uint8_t remaining)
inline

Build a live-code body for either code route.

The body is a validity window, not a snapshot: it carries the code together with the seconds left in its time step, so the page draws the countdown from its own timer and refetches once per period. A page that had to poll for the countdown would spend 60 of the 80 requests the per-IP limiter allows in a 60-second window on one open panel.

The countdown field is named remaining_s (seconds) to match the rest of the admin API's _s duration suffix.

Parameters
NameDirectionMeaning
idinSlot id (TOTP slot, or credential slot for the embedded route).
codeinRaw code value from the generator.
digitsinStored digit count (clamped on the way out).
periodinStored time step (clamped on the way out).
remaininginSeconds left in the current step; capped at the clamped period.
Returns
The serialized JSON object.

buildFlavorName() #

const char * kleidos::web::adminsystem::buildFlavorName(BuildFlavor flavor)
constexpr

Stable wire token for a build flavor.

Parameters
NameDirectionMeaning
flavorinFlavor to name.
Returns
NUL-terminated lowercase token ("debug", "secure-dev", "secure", "release", "dev"); never nullptr.

buildMetadataJson() #

std::string kleidos::web::totp::buildMetadataJson(uint16_t id, const char * name, uint8_t digits, uint32_t period, uint8_t algorithm, bool hasSecret)
inline

Build the GET /api/totp/:id metadata body.

The name is unvalidated free text (a quote, a backslash or a control byte would break a hand-rolled body and let the caller inject JSON structure), so it is serialized through the JSON writer's escaping.

Parameters
NameDirectionMeaning
idinSlot id.
nameinDisplay name; nullptr is treated as empty.
digitsinStored digit count (clamped on the way out).
periodinStored time step (clamped on the way out).
algorithminStored HMAC hash, reported by its wire name.
hasSecretinWhether the record carries a usable secret.
Returns
The serialized JSON object. Never contains the secret itself.

busKindName() #

const char * kleidos::web::adminsystem::busKindName(kleidos::drivers::regmap::BusKind bus)
constexpr

Stable wire token for a register-map bus kind.

Parameters
NameDirectionMeaning
businBus kind from a chip's register map.
Returns
NUL-terminated lowercase token; never nullptr.

checkRestoreRequest() #

Refusal kleidos::web::restoregate::checkRestoreRequest(size_t bodyLen, size_t bodyCap, size_t secretLen, size_t secretCap)
constexpr

Run the size and secret-shape checks for a restore request.

Ordering is deliberate: the size refusal comes first (free), then the secret shape (free), and only a Refusal::None result may reach the PBKDF2 verify — a locked-out or absent-secret request never costs a derivation.

Parameters
NameDirectionMeaning
bodyLeninDeclared request body length in bytes.
bodyCapinThe honest backup bound, the biggest backup of any board (see admin_backup_limits.h).
secretLeninLength of the presented unlock secret (0 = absent).
secretCapinMaximum unlock-secret length the vault accepts.
Returns
The first refusal that applies, or Refusal::None.

checkRestoreSecret() #

Refusal kleidos::web::restoregate::checkRestoreSecret(size_t secretLen, size_t secretCap)
constexpr

The shape check on the unlock secret the frame carried.

Parameters
NameDirectionMeaning
secretLeninLength of the presented unlock secret (0 = absent).
secretCapinMaximum unlock-secret length the vault accepts.
Returns
The secret's refusal, or Refusal::None.

checkRestoreSize() #

Refusal kleidos::web::restoregate::checkRestoreSize(size_t bodyLen, size_t bodyCap)
constexpr

The size check a restore request takes before a byte of it is read.

Parameters
NameDirectionMeaning
bodyLeninDeclared request body length in bytes.
bodyCapinThe honest backup bound (see admin_backup_limits.h); the frame's own bound is added to it here.
Returns
Refusal::BodyTooLarge or Refusal::None.

chipProbeFrom() #

ChipProbe kleidos::web::adminsystem::chipProbeFrom(const kleidos::drivers::regmap::ChipRegmap * map)
constexpr

Turn a register-map lookup result into a core-crossing observation.

Call on the core that owns the registry, with the result of looking the row's chip up; map is nullptr when the registry holds no entry, which is a result ("not registered"), not a failure.

Parameters
NameDirectionMeaning
mapinRegistered map for the row's chip, or nullptr when none.
Returns
The observation to publish for the other core.

classifyRead() #

HeaderRead kleidos::web::headerread::classifyRead(platform::http::HeaderPresence presence, size_t valueLength, size_t slotBytes)
constexpr

Classify a header by whether the transport reports it and how long its value is.

Only a header the transport reports as not carried is absent: one sent empty is a value (an empty one), and one the transport could not answer for is unreadable. A value fits only with room for its NUL, so a value of slotBytes characters or more is unreadable.

Parameters
NameMeaning
presenceWhether the transport reports the header.
valueLengthThe value's length in bytes, as the transport reports it.
slotBytesBytes of the slot the value is read into, NUL included.
Returns
Absent only for a header not carried; Value when it fits; Unreadable otherwise.

countdownLabel() #

const char * kleidos::web::timediag::countdownLabel(bool readOk, bool running)
constexpr

One-word countdown-timer state.

The BM8563 exposes the timer-enable bit but not a readable remaining count, so the honest vocabulary is armed/off — plus "unreadable" when the register read itself failed.

Parameters
NameDirectionMeaning
readOkinThe TE bit was read successfully.
runninginThe TE bit (valid only when readOk).
Returns
"armed", "off", or "unreadable".

customFieldOf() #

void kleidos::web::adminimport::customFieldOf(const KeptCustom & kept, const char * token, TruncationReport & truncated, CustomField & field)
inline

A custom field from its bound entry, and its truncation checks.

Parameters
NameDirectionMeaning
keptinThe entry.
tokeninIts static report token.
truncatedin, outThe report.
fieldoutReceives the field.

decideCodeStatus() #

int kleidos::web::totp::decideCodeStatus(kleidos::totp::Gate gate, bool entryFound, bool hasSecret)
constexpr

Decide the HTTP status of a live-code request.

The TOTP gate is the first term by design: the handler asks it BEFORE it mounts the vault, so a refused code costs no vault I/O and can never be derived from a time base the gate did not pass.

Parameters
NameDirectionMeaning
gateinThe TOTP gate's verdict.
entryFoundinTrue when the slot decrypted into an entry.
hasSecretinTrue when that entry carries a non-empty secret.
Returns
::kStatusClockUntrusted for any refused verdict, ::kStatusNotFound, or ::kStatusOk.

decideIdleResponse() #

IdleResponse kleidos::web::decideIdleResponse(uint32_t elapsedMs, uint32_t timeoutMs, uint32_t warningThresholdMs)
constexpr

Evaluate the admin-portal idle timer.

Side-effect free, header-only. The web client polls GET /api/idle every 10 s; the response drives the warning banner and the eventual auto-shutdown.

Parameters
NameMeaning
elapsedMsMilliseconds since last observed client activity.
timeoutMsTotal idle timeout (e.g. 5 min = 300000 ms).
warningThresholdMsMilliseconds before timeout at which to arm the banner.
Returns
Remaining seconds and whether the web client should show the warning banner.
See also
IdleResponse

decideRateLimit() #

bool kleidos::web::authlogic::decideRateLimit(RateLimitEntry * entries, uint8_t count, uint32_t clientIp, uint32_t nowMs, bool isBootstrap, const RateLimitConfig & cfg)

Decide whether a request is within its per-IP rate limit, updating the slots.

One pure function over the slot array: a request from a tracked client is judged by that client's sliding windows; a request from a new client claims a free slot, or a slot whose client has been quiet long enough that its windows no longer count anything (two full windows since its last window opened).

A slot whose client still has requests in its windows is never handed to another client. Taking it would start the newcomer with an empty budget, so a client that rotates through more addresses than there are slots would never be limited. While every slot is live, a new client is refused instead, until one of them goes quiet.

Parameters
NameDirectionMeaning
entriesin, outSlot array (mutated in place).
countinNumber of slots in entries.
clientIpinRequesting client IPv4 (network order); 0 for a peer the server could not read.
nowMsinMonotonic time of the request in milliseconds.
isBootstrapinTrue for /api/init (the bootstrap family).
cfginLimits and window length.
Return values
ValueMeaning
trueRequest is allowed (slot updated/claimed accordingly).
falseRequest exceeds its client's limit, or it comes from a new client while every slot is live; slots unchanged.

decimationStride() #

size_t kleidos::web::telemetryencode::decimationStride(size_t sampleCount, size_t maxEmitted)
inline

Smallest decimation stride that keeps sampleCount within maxEmitted.

Parameters
NameDirectionMeaning
sampleCountinSamples available.
maxEmittedinLargest number of samples the budget admits.
Returns
Stride in ticks; always >= 1, and 1 whenever everything already fits.

describeAudioOutput() #

AudioOutputLabel kleidos::web::adminsystem::describeAudioOutput(device::AudioOutput kind, bool driven)
constexpr

Name the audio output a board carries, and whether this firmware drives it.

The label follows the board's audio output kind, which names the part: a buzzer is driven by PWM on a GPIO; a speaker sits behind an I2S amplifier, directly or behind a codec. Which board has which is on The boards. A part the firmware leaves alone (AUDIO_OUTPUT_DRIVEN 0) is still listed, marked as not driven.

Parameters
NameDirectionMeaning
kindinThe board's audio output (device::kAudioOutput).
driveninTrue when this firmware drives it (device::kAudioOutputDriven).
Returns
The row's part name and bus token; both nullptr when nothing is fitted.

driverProbe() #

ChipProbe kleidos::web::adminsystem::driverProbe(bool responded)
constexpr

Turn a driver's own presence probe into a core-crossing observation.

For parts that register no register map but whose driver (or resolving factory) proves presence itself — the IMU WHO_AM_I classification, the touch controller probe, the keyboard-controller probe. Only the "did it answer" half is known, so bus and address stay unset and applyChipProbe leaves the row's variant-declared wiring untouched.

Parameters
NameDirectionMeaning
respondedinTrue when the driver's probe verified the chip.
Returns
The observation to publish for the other core.

encodeTelemetryBody() #

EncodeResult kleidos::web::telemetryencode::encodeTelemetryBody(const EncodeInput & in, char * out, size_t outCapacity)
inline

Encode a ring snapshot as the GET /api/telemetry body.

Picks a stride from the budget, writes the body, and — should it still not fit — retries at successively coarser strides. The buffer is never overrun and a partially written body is never reported as usable.

Parameters
NameDirectionMeaning
ininRun state and oldest-first ring snapshot.
outoutDestination buffer.
outCapacityinSize of out in bytes, including the NUL slot.
Returns
Body length, applied stride, and whether the body may be sent.

fillRequested() #

bool kleidos::web::restoregate::fillRequested(const char * value)
inline

Whether a kFillHeader value says "go on".

Only the exact value 1, the one the API reference documents: the answer replaces the vault and leaves entries out, so a value that merely reads as true somewhere (yes, true, on, 1) is not taken as the owner's choice.

Parameters
NameDirectionMeaning
valueinThe header's value; null when the request carries none.
Return values
ValueMeaning
trueFill in the backup's order.
falseRefuse with the counts.

flagsOf() #

uint16_t kleidos::web::adminimport::flagsOf(int64_t value)
inline

The behavior flags as an int-or-0 read saw them, narrowed to the column.

Parameters
NameDirectionMeaning
valueinThe bound integer.
Returns
The 16-bit flags.

formatAlarm() #

void kleidos::web::timediag::formatAlarm(const AlarmView & alarm, char * out, size_t cap)
inline

Render the alarm state as one human-readable line.

Disabled fields are wildcards on the chip, so the text names only the enabled ones: "daily 07:30" (time only), "monthly day 12 at 07:30", "weekday 3 at 07:30", or "not armed" when nothing matches (that is how the HAL disarms it). A failed register read reports "unreadable" rather than a fabricated "not armed".

Parameters
NameDirectionMeaning
alarminDecoded alarm registers.
outoutDestination text buffer.
capinCapacity of out (use kAlarmTextCap).

formatCode() #

std::string kleidos::web::totp::formatCode(uint32_t code, uint8_t digits)
inline

Render a code as its fixed-width, zero-padded decimal string.

The JSON body's spelling of kleidos::totp::formatCode: leading zeros kept ("012345", not "12345"), a wider value reduced modulo 10^digits.

Parameters
NameDirectionMeaning
codeinRaw code value.
digitsinRequested width; clamped by kleidos::totp::clampDigits.
Returns
The padded decimal string, exactly clampDigits(digits) characters.

formatOutcomeBody() #

const char * kleidos::web::restoregate::formatOutcomeBody(Outcome outcome, const kleidos::vault::backup::RestoreTally & tally, char * out, size_t cap)
inline

JSON body for a finished restore, with the counts the owner is told.

The static body of outcomeBody, and — on the two outcomes where the numbers ARE the answer, and on every partial one that left an entry out — the counts beside it: what the backup holds (held), what this device stores (capacity) and, once a restore filled the device, what it left out (left_out). A client offers the choice from them: the admin portal, where the owner picks which entries to bring over, or the same restore again with kFillHeader, which takes the first ones in the backup's order.

Parameters
NameDirectionMeaning
outcomeinThe outcome to map.
tallyinThe restore's counts.
outoutBuffer for the body, at least kOutcomeBodyCap bytes to never truncate.
capinBytes of out; at least 1.
Returns
out, NUL-terminated: the body with its counts, or the static body alone when the counts do not apply or would not fit.

frameLength() #

size_t kleidos::web::restoregate::frameLength(const uint8_t * data, size_t len)
constexpr

Length of the secrets frame at the start of data.

Parameters
NameDirectionMeaning
datainBytes the body opens with.
leninBytes at data.
Returns
The frame's length including its line feed, or 0 when no line feed is among the first len bytes.

gateRefusalJson() #

const char * kleidos::web::totp::gateRefusalJson(kleidos::totp::Gate gate, bool hasRtc)
constexpr

The ::kStatusClockUntrusted body for a refused verdict.

Each refusal carries its own machine reason (the gate's wire spelling, kleidos::totp::gateLabel) and its own hint, so the page says what is wrong and what fixes it from inside the portal: on a board without an RTC chip only a precise set counts, and the portal's "Set from this browser" is one, where a time typed by hand is not.

Parameters
NameDirectionMeaning
gateinThe TOTP gate's verdict (a passing one gets the clock-unset body; no handler sends it).
hasRtcinThe board keeps the time in a battery-backed RTC.
Returns
A static JSON body.

hasLeadIn() #

bool kleidos::web::restoregate::hasLeadIn(const uint8_t * data, size_t len)
constexpr

Whether a secrets frame opens with the lead-in: bodycap::kLeadIn spaces.

The secrets come after the lead-in, never among the body's first bytes. A frame that does not open with the lead-in counts as no frame, so a client that leaves it out is refused before any verify and learns to send it, whatever it sends next.

Parameters
NameDirectionMeaning
datainThe frame's bytes.
leninIts length.
Returns
True when the first kLeadIn bytes are all spaces and something follows them.

hasNamedAddress() #

bool kleidos::web::authority::hasNamedAddress(const char * address)
constexpr

Whether the portal has an address it can name in an absolute URL.

Parameters
NameMeaning
addressThe address the transport reports.
Return values
ValueMeaning
trueThere is one to print.
falseThe transport reports none (absent or empty).

hiddenValueLost() #

template<typename NextValues>
bool kleidos::web::secretedit::hiddenValueLost(const kleidos::vault::CredentialPool & stored, const NextValues & next)
nodiscard

Whether a new custom-field set loses a stored hidden value.

A present custom array replaces the whole set. Each stored hidden value must still be the value of some field of the new set; its label, its kind and whether it stays hidden are metadata and may change.

Template Parameters
NameMeaning
NextValuesA view of the new set: size() and value( i ) answering a NUL-terminated string (never nullptr).
Parameters
NameDirectionMeaning
storedinThe record's pool before the edit.
nextinThe set the body writes.
Return values
ValueMeaning
trueA stored hidden value is not in next.
falseEvery stored hidden value survives.

hostAuthorityMatches() #

bool kleidos::web::authority::hostAuthorityMatches(const char * host, const char * expected)
constexpr

Case-insensitive compare of a Host value against one authority.

Tolerates an optional ":<port>" suffix on the header value, so "192.168.4.1:80" matches "192.168.4.1". An absent or empty expected authority matches nothing: a transport with no address to report must admit no request on the strength of it.

Parameters
NameMeaning
hostThe header value.
expectedThe authority to compare it with.
Return values
ValueMeaning
truehost names expected, with or without a port.
falseIt names something else, or either side is absent or empty.

hostIsAllowed() #

bool kleidos::web::authority::hostIsAllowed(headerread::HeaderRead read, const char * host, const char * apIp, const char * apName, bool linkAccepts)
constexpr

Whether a request's Host authority is one the portal answers at.

A rebound page carries the attacker's own host name in Host (a page cannot forge it), so refusing anything but our own authorities blocks it. A missing header is no rebind vector — HTTP/1.0 and command-line clients send none — and is allowed. A header that is present but could not be read is refused: a browser always sends one, and a page chooses its own name's length, so a name too long for the header slot (192 characters or more, DNS allows 253) would otherwise pass as "no header". A header sent empty names no authority and is refused.

Parameters
NameMeaning
readWhat the read of Host found.
hostThe header value when read is Value, else nullptr.
apIpThe address the link serves, as its interface reports it; an absent or empty one admits no request by address.
apNameThe captive host name the SoftAP's DNS answers with.
linkAcceptsThe transport's own verdict on host; a debug link compares the address it was given, which it never reports.
Return values
ValueMeaning
trueServe the request.
falseThe authority is someone else's, or could not be read.

isCsvTrimChar() #

bool kleidos::web::isCsvTrimChar(char ch)
inline

True when ch is a CSV line-trimming character (space, tab, CR, LF).

Parameters
NameDirectionMeaning
chinCandidate character.
Returns
true when ch is one of space, tab, CR or LF.

isLoopbackAuthority() #

bool kleidos::web::authority::isLoopbackAuthority(const char * host)
constexpr

Whether a Host value names the client's own loopback.

A harness that cannot reach the portal's network directly forwards a loopback port to it, so the browser or client it drives presents a loopback authority for a portal that is elsewhere. Only a transport that admits one named peer anyway accepts this.

Parameters
NameMeaning
hostThe header value.
Return values
ValueMeaning
trueIt names 127.0.0.1 or localhost, with or without a port.
falseAnything else.

isOtpauthUri() #

bool kleidos::web::totpfield::isOtpauthUri(const char * text)
inline

Whether text begins with otpauth:// (forwards to TotpGenerator).

Parameters
NameDirectionMeaning
textinNUL-terminated candidate, may be null.
Returns
true when text starts with the scheme, in any case.

isPolledCodeRoute() #

bool kleidos::web::totp::isPolledCodeRoute(const char * url, uint16_t maxTotp, uint16_t maxCredentials)
inline

True when url is a live-code route the SPA polls on a timer.

The polled routes carry AuthPolicy::SessionReadOnly: a once-per-second poll under the idle-refreshing AuthPolicy::Session would reset the admin idle clock forever and hold the WiFi radio up for as long as the page stays open.

Parameters
NameDirectionMeaning
urlinRequest URL, already stripped of its query string.
maxTotpinTOTP slot capacity.
maxCredentialsinCredential slot capacity.
Return values
ValueMeaning
trueurl is /api/totp/:id/code or /api/credentials/:id/totp/code.
falseAny other URL.

isSessionTokenValid() #

bool kleidos::web::authlogic::isSessionTokenValid(uint32_t nowMs, uint32_t createdMs, uint32_t timeoutMs, const char * providedToken, size_t providedLen, const char * expectedToken, size_t expectedLen)

Constant-time validity check for an X-Session-Token header value.

Returns true only when the session has not expired, a token was supplied, its length is exactly expectedLen, and it matches expectedToken byte for byte. The comparison is constant-time once the lengths agree.

Parameters
NameDirectionMeaning
nowMsinCurrent monotonic time in milliseconds.
createdMsinTime the session token was issued.
timeoutMsinIdle timeout; the session is expired once nowMs-createdMs exceeds it (unsigned semantics).
providedTokeninToken from the request header, or nullptr if absent.
providedLeninLength of providedToken in bytes.
expectedTokeninThe live session token (NUL-terminated).
expectedLeninExpected token length (e.g. 32 hex chars).
Return values
ValueMeaning
trueToken is present, unexpired, correctly sized, and matches.
falseOtherwise.

matchRoute() #

Route kleidos::web::totp::matchRoute(const char * url, uint16_t maxTotp, uint16_t maxCredentials)
inline

Match a request URL against the dynamic TOTP route shapes.

Rejects (returns ::RouteKind::None for) any id at or above the matching capacity, so an out-of-range id falls through to the dispatcher's plain 404 instead of reaching the vault.

Parameters
NameDirectionMeaning
urlinRequest URL, already stripped of its query string.
maxTotpinTOTP slot capacity (exclusive upper bound on the id).
maxCredentialsinCredential slot capacity (exclusive upper bound).
Returns
The matched route, or a ::RouteKind::None route.

newSecretKind() #

security::pin_policy::SecretKind kleidos::web::rekey::newSecretKind(bool pinLengthGiven)
constexpr

The kind the new secret is recorded as: the one the body asked for.

Passed to the secret change explicitly, never carried from the record: a PIN vault changed to a passphrase (or the reverse) on the touch keypad must open on the layer that types the new secret.

Parameters
NameDirectionMeaning
pinLengthGiveninThe body carried pin_length.
Returns
Pin when it did, else Passphrase.

outcomeBody() #

const char * kleidos::web::restoregate::outcomeBody(Outcome outcome)
constexpr

JSON response body for a finished restore.

Both partial bodies carry vault_modified so a client can branch on the fact rather than on prose, and say plainly that the vault was changed — the backup file is still the whole copy. They also carry retry_may_help, because "keep the file and restore it again" is right for one of them and a loop with no exit for the other, and a client must be able to tell which without parsing English.

Parameters
NameDirectionMeaning
outcomeinThe outcome to map.
Returns
A static JSON body; never nullptr.

outcomeFor() #

Outcome kleidos::web::restoregate::outcomeFor(kleidos::vault::backup::ImportStatus status)
constexpr

Translate a vault restore result into the client-facing outcome.

Parameters
NameDirectionMeaning
statusinResult of kleidos::vault::backup::importAll.
Returns
The matching Outcome.

outcomeStatus() #

uint16_t kleidos::web::restoregate::outcomeStatus(Outcome outcome)
constexpr

HTTP status code for a finished restore.

Four distinct codes, so a client that reads nothing but the status line still branches correctly: 200 restored, 400 refused with the vault untouched, 500 for a device failure, 422 for a file this device could only partly represent.

422 rather than 500 for the last one is the deliberate part. 500 is this file's promise that the DEVICE failed, and for a refused entry nothing did: every write landed and the device is healthy, so a 500 would send the owner (and any log reader) hunting a fault that is not there. It is also not a 2xx, although the request was processed: the vault was replaced by something other than what the file describes, and a portal that reads 2xx as success would congratulate the owner on a restore that silently dropped entries. 422 "Unprocessable Content" is exactly the remaining case — the request was well-formed and authorized, and its content could not be fully acted upon.

Parameters
NameDirectionMeaning
outcomeinThe outcome to map.
Returns
200 when restored, 400 when the backup was rejected (the client sent something this device cannot read), 500 when a write failed part-way (the request was fine; the DEVICE failed, and destructively), 422 when the vault was replaced and entries outside this device's record grammar were dropped, or the device filled up and the backup's last entries were left out (nothing failed; the file is what it is).

overflowed() #

bool kleidos::web::adminimport::overflowed(const json::Bound & bound, size_t index)
inline

True when member index of bound was clamped.

Parameters
NameDirectionMeaning
boundinWhat the object held.
indexinThe member.
Returns
Whether its text was longer than its field.

parseCsvCredentialLine() #

bool kleidos::web::parseCsvCredentialLine(const char * line, size_t length, Credential & credential)
inline

Parse one CSV line into a Credential (name, user, pass, url) using RFC 4180 quoting.

Leading and trailing whitespace / CR / LF are stripped before tokenising. An empty line or a line whose first (name) field is empty returns false. Extra columns beyond the fourth are silently discarded.

Parameters
NameDirectionMeaning
lineinStart of the CSV line (need not be NUL-terminated).
lengthinLength of the line in bytes.
credentialoutReceives the parsed fields; zero-initialized on entry.
Return values
ValueMeaning
trueAt least the name field was non-empty; credential is populated.
falseEmpty line or empty name field; credential is unmodified.
Warning
SECURITY: parses user-uploaded CSV. The caller MUST zeroize credential.pass (and the other fields) after use.

parseImportItem() #

const char * kleidos::web::adminimport::parseImportItem(ImportItemBody & item, const json::Bound & bound, const ItemArrays & arrays, bool generateMissing, ParsedImportItem & out)
inline

Decode and validate one normalized item.

Field semantics: name is mandatory; user/url/notes default to empty; over-long text fields are clamped to the vault's field capacities and reported. A missing or empty pass is refused per-item unless generateMissing is set, in which case ParsedImportItem::generate tells the caller to fill it from the on-device generator. The optional totp follows the shared contract (omitted and explicit null both mean "no TOTP" here — an import item has no stored entry to preserve).

Parameters
NameDirectionMeaning
itemin, outThe bound item; its TOTP secret text is wiped once decoded (web::totpfield::parseTotpField).
boundinWhat the item object held.
arraysinIts custom, urls and history entries.
generateMissinginThe request-level generation opt-in.
outoutReceives the decoded item; wiped first.
Returns
nullptr when the item is importable, else a static per-item refusal text (the batch continues — one bad row never sinks the request).

parseOtpauthUri() #

const char * kleidos::web::totpfield::parseOtpauthUri(const char * uri, TotpEntry & entry)
inline

Parse an otpauth:// URI into entry.

Fields the caller already populated win over the URI: a JSON request that named the entry keeps that name even when the link carries an issuer.

Parameters
NameDirectionMeaning
uriinNUL-terminated URI.
entryin, outReceives secret, digits, period, algorithm; name and account only when still empty.
Return values
ValueMeaning
nullptrParsed.
!nullptrStatic refusal text.

parseTotpField() #

FieldParse kleidos::web::totpfield::parseTotpField(const TotpMember & member, bool hasStoredSecret, TotpEntry & entry)
inline

Decode the optional "totp" field of a credential-write body.

Implements the shared wire contract: an omitted field preserves the stored TOTP, an explicit null detaches it, and an object sets it. Inside the object, secret accepts base32 or a full otpauth:// URI (URI parameters win over the sibling digits/period/algorithm fields). An object with no (or an empty) secret keeps the stored secret when one exists and adjusts only the parameters. A member of the wrong JSON type never reaches here: the binder refuses the body.

Parameters
NameDirectionMeaning
memberin, outThe "totp" member as bound; its secret text is wiped once decoded.
hasStoredSecretinWhether a stored TOTP secret exists to fall back on when the object omits secret.
entryin, outPre-filled by the caller with the stored TOTP (or defaults); updated in place on Set.
Returns
Decision + optional static error text (see FieldParse).
Warning
SECURITY: the caller wipes entry.

passphraseAccepted() #

bool kleidos::web::rekey::passphraseAccepted(security::pin_policy::SetSurface surface)
constexpr

Whether surface can collect a new passphrase (a body without pin_length).

The secret the portal sets must be one the board's own entry can type again: a keyboard and the touch keypad's letter layer can, a dial cannot.

Parameters
NameDirectionMeaning
surfaceinThe board's entry surface.
Returns
false on the dial.

percentDecode() #

void kleidos::web::totpfield::percentDecode(const char * in, size_t inLen, char * out, size_t outCap)
inline

Decode XX escapes of a URI component (forwards to TotpGenerator).

Parameters
NameDirectionMeaning
ininComponent start (not necessarily NUL-terminated).
inLeninComponent length in bytes.
outoutReceives the decoded text, always NUL-terminated.
outCapinCapacity of out in bytes, including the NUL.

pinLengthAccepted() #

bool kleidos::web::rekey::pinLengthAccepted(security::pin_policy::SetSurface surface, int requested)
constexpr

Whether a requested pin_length is one surface takes.

Parameters
NameDirectionMeaning
surfaceinThe board's entry surface.
requestedinThe decoded field (any int; negative or past a byte refuses).
Returns
true when security::pin_policy::newPinLengthAllowed takes requested on surface.

pinLengthRefusal() #

const char * kleidos::web::rekey::pinLengthRefusal(security::pin_policy::SetSurface surface)
constexpr

The refusal for a pin_length surface does not take.

Parameters
NameDirectionMeaning
surfaceinThe board's entry surface.
Returns
A JSON body naming the lengths surface takes.

present() #

bool kleidos::web::adminimport::present(const json::Bound & bound, size_t index)
inline

True when member index of bound is in the object, even as null.

Parameters
NameDirectionMeaning
boundinWhat the object held.
indexinThe member.
Returns
Whether the key was there.

readWriteParams() #

WriteParams kleidos::web::totp::readWriteParams(const char * body, size_t len)
inline

Read and judge the digits and period of a TOTP write body.

Writes are strict: a present field must be a JSON integer that is 6 or 8 (digits) or 30 or 60 (period), and anything else (a string such as "8", a fraction, a boolean, a null, an array, an object) is refused with the same ::kStatusBadRequest body an out-of-range number gets, never clamped or coerced. The digits verdict wins when both fields are refused. A body that is not JSON reads as one with neither field; the route's binder refuses it.

Parameters
NameDirectionMeaning
bodyinThe write body.
leninIts bytes.
Returns
The two fields, their presence and the refusal body, if any.

redirectTarget() #

const char * kleidos::web::authority::redirectTarget(char * out, size_t capacity, const char * address)
constexpr

Where a request is redirected to reach the panel.

Absolute while the portal has an address to name, because the request that needs the redirect most is a captive-portal probe for some other host entirely, and a relative target would resolve against that host rather than against us. With no address to name — or no room to write one — the target is kSelfPath, which resolves against whatever authority the client used.

Parameters
NameDirectionMeaning
outoutBuffer the absolute URL is written into.
capacityBytes available in out, NUL included.
addressThe address the transport reports.
Returns
out holding http://<address>/, or kSelfPath.

refusalBody() #

const char * kleidos::web::restoregate::refusalBody(Refusal refusal)
constexpr

JSON error body for a refusal.

Parameters
NameDirectionMeaning
refusalinThe refusal to map.
Returns
A static JSON body naming what the client must fix; nullptr for Refusal::None.

refusalStatus() #

uint16_t kleidos::web::restoregate::refusalStatus(Refusal refusal)
constexpr

HTTP status code for a refusal.

Parameters
NameDirectionMeaning
refusalinThe refusal to map.
Returns
413 for the size refusal, 400 for the secret-shape refusals, 200 for Refusal::None (the caller proceeds; nothing is sent).

rollbackPending() #

bool kleidos::web::otastatus::rollbackPending(kleidos::platform::ota::ImageState state)
constexpr

Whether the running image is still on rollback trial.

Only PendingVerify means the bootloader would revert on the next reset; every other state — including Undefined on builds without rollback bookkeeping — reads as confirmed, because claiming a pending rollback that does not exist would tell the owner their firmware is on trial when it is not.

Parameters
NameDirectionMeaning
stateinRunning-partition OTA state from the platform facade.
Return values
ValueMeaning
trueThe image boots on trial; an unconfirmed reset rolls back.
falseThe image is confirmed (or the state is not tracked).

seedLost() #

bool kleidos::web::secretedit::seedLost(bool storedSeed, SeedWrite write)
nodiscardconstexpr

Whether an edit loses the stored seed.

Parameters
NameDirectionMeaning
storedSeedinThe record holds a seed now.
writeinWhat the body does to it.
Return values
ValueMeaning
trueA stored seed is detached or replaced.
falseNothing stored, or the seed stays.

selectBuildFlavor() #

BuildFlavor kleidos::web::adminsystem::selectBuildFlavor(bool debugBuild, bool secureDev, bool secure, bool release)
constexpr

Resolve the build flavor from the four build-time predicates.

The order is most-specific-first and is load-bearing: a hardened build also sets the release flag, and its bench twin also sets the hardened flag, so a ladder that tested release before secure would report "release" on hardened firmware. The web page raises its "you are running a debug build" warning off this value, so the Debug arm has to win over everything else as well.

Parameters
NameDirectionMeaning
debugBuildinTrue when the serial-console debug build flag is set.
secureDevinTrue when the bench DEV-mode secure flag is set.
secureinTrue when the hardened secure flag is set.
releaseinTrue when the open-production release flag is set.
Returns
The most specific flavor the predicates describe.

stageLabel() #

const char * kleidos::web::otastatus::stageLabel(const AttemptView & attempt)
constexpr

One-word stage of the last/current OTA attempt for the status row.

Parameters
NameDirectionMeaning
attemptinLive upload state.
Returns
"idle" (nothing attempted), "uploading" (streaming now), "success" or "failed" (finished). A finished attempt wins over a stale active flag so a torn snapshot never reports both.

streamTelemetryBody() #

EncodeResult kleidos::web::telemetryencode::streamTelemetryBody(const EncodeInput & in, char * scratch, size_t scratchBytes, ChunkSink sink, void * sinkCtx)
inline

Emit the GET /api/telemetry body through a chunk sink.

Same bytes as ::encodeTelemetryBody, but flushed through sink as scratch fills, so the caller's memory cost is scratchBytes regardless of how much history the body carries. Because a flushed chunk cannot be recalled, the stride is settled by a dry run first and the body is written exactly once.

Parameters
NameDirectionMeaning
ininRun state and oldest-first ring snapshot.
scratchoutRolling window the sink is fed from.
scratchBytesinSize of scratch in bytes, including the NUL slot.
sinkinChunk destination.
sinkCtxinOpaque context handed back to sink.
Returns
Total body length, applied stride, and whether the whole body reached the sink.

stringLost() #

bool kleidos::web::secretedit::stringLost(const kleidos::vault::CredentialPool & stored, kleidos::vault::CredPoolType type, const char * next)
inlinenodiscard

Whether writing next over a single-string pool entry loses it.

Nothing stored is not a loss (adding is not destroying); the same text written back is not a loss either.

Parameters
NameDirectionMeaning
storedinThe record's pool before the edit.
typeinA single-string entry type (notes, recovery codes).
nextinThe text the body writes; nullptr reads as empty.
Return values
ValueMeaning
trueA stored, non-empty value would be replaced or removed.
falseNothing is lost.

takeCustom() #

bool kleidos::web::adminimport::takeCustom(void * user, const void * element, const json::Bound & bound)
inline

A custom entry closed: kept while the record has room for it.

Parameters
NameDirectionMeaning
userinThe ImportPass.
elementinThe entry's CustomBody.
boundinWhich of its members it carried.
Returns
Always true: a surplus entry is dropped, never refused.

takeHistory() #

bool kleidos::web::adminimport::takeHistory(void * user, const void * element, const json::Bound & bound)
inline

A history entry closed: one with no password records nothing; the first ones the record holds are kept.

Parameters
NameDirectionMeaning
userinThe ImportPass.
elementinThe entry's HistoryBody.
boundinWhich of its members it carried.
Returns
Always true.

takeItem() #

bool kleidos::web::adminimport::takeItem(void * user, const void * element, const json::Bound & bound)
inline

An item closed: handed on with its arrays, which are then forgotten.

Parameters
NameDirectionMeaning
userinThe ImportPass.
elementinThe item's ImportItemBody.
boundinWhich of its members it carried.
Returns
What the pass's item hook returned; true when it only counts.

takeUrl() #

bool kleidos::web::adminimport::takeUrl(void * user, const json::Entry & entry)
inline

A urls entry arrived: an empty one is not one; the first ones the record holds are kept, the rest dropped.

Parameters
NameDirectionMeaning
userinThe ImportPass.
entryinThe entry's text.
Returns
Always true.

toHexLower() #

void kleidos::web::authlogic::toHexLower(char * dst, const uint8_t * bytes, size_t byteCount)

Write byteCount bytes as lowercase hex into dst (NUL-terminated).

Parameters
NameDirectionMeaning
dstoutDestination buffer; needs byteCount*2+1 bytes.
bytesinSource bytes.
byteCountinNumber of bytes to format.

unsignedOrZero() #

uint32_t kleidos::web::adminimport::unsignedOrZero(int64_t value)
inline

value read as a field of 32 unsigned bits: out of that width it reads 0, as a default-or-value read always did.

Parameters
NameDirectionMeaning
valueinThe bound integer.
Returns
The field's value.

validateItemCount() #

const char * kleidos::web::adminimport::validateItemCount(size_t count)
inline

Judge the size of the items array of POST /api/import/items.

Parameters
NameDirectionMeaning
countinEntries the array held (0 when absent or null).
Returns
nullptr when it is importable, else a static refusal text (the whole request is answered 400 — nothing was imported yet).

verifyBasicAuth() #

bool kleidos::web::authlogic::verifyBasicAuth(const char * authHeaderValue, const char * expectedPassword)

Validate an HTTP Basic-Auth header value against the derived OTA password.

Expects authHeaderValue shaped "Basic base64(\"admin:<password>\")". Decoding, the username comparison and the password comparison are all length-validated and constant-time. The decoded scratch buffer is zeroized before returning.

Parameters
NameDirectionMeaning
authHeaderValueinThe raw Authorization header value, or nullptr.
expectedPasswordinNUL-terminated expected password; must be non-empty.
Return values
ValueMeaning
trueHeader is present, well-formed, user is "admin", password matches.
falseOtherwise.
Warning
SECURITY: a false positive lets an attacker on the admin WiFi push arbitrary firmware. Keep the comparisons constant-time.

Back to the top

Variable Documentation

kAccountFieldBytes #

size_t kleidos::web::totpfield::kAccountFieldBytes
inlineconstexpr

Room for the account label past its stored column, so a longer one is cut to the column as the stored copy cuts it, and reported.

kBackupCarriedMetaB64MaxBytes #

size_t kleidos::web::backuplimits::kBackupCarriedMetaB64MaxBytes
inlineconstexpr

Longest meta string a restore here reads, from any board: the element budget the restore holds every member of the document to. A backup carries the meta of the board that WROTE it, whose generation tables are sized by that board's capacities, so a bound taken from this board's own record would refuse a backup from a bigger board that fits here record for record.

kBackupCredentialMaxBytes #

size_t kleidos::web::backuplimits::kBackupCredentialMaxBytes
inlineconstexpr

Worst-case serialized size of one credential row: the four fixed text fields at their caps plus the WHOLE pool budget (notes, custom fields, recovery codes, extra URLs, SSO provider and history share it), every byte escaped, embedded TOTP present. (kBackupCredFixedOverhead already carries the base64 TOTP secret.)

kBackupCredFixedOverhead #

size_t kleidos::web::backuplimits::kBackupCredFixedOverhead
inlineconstexpr

Ceiling for one credential row's fixed JSON scaffolding: its key names with quotes/colons/commas, every brace and bracket, the per-entry keys of the custom / urls / history arrays, the numeric and boolean maxima and the quoted algorithm name.

kBackupEnvelopeFixedOverhead #

size_t kleidos::web::backuplimits::kBackupEnvelopeFixedOverhead
inlineconstexpr

Envelope scaffolding outside the arrays: version, the four top-level keys, braces/brackets and the quotes around the meta blob — 64 covers it.

kBackupMetaB64Bytes #

size_t kleidos::web::backuplimits::kBackupMetaB64Bytes
inlineconstexpr

Base64 length of the exported meta record (its size scales with the generation tables, i.e. with this board's slot capacities).

kBackupTotpFixedOverhead #

size_t kleidos::web::backuplimits::kBackupTotpFixedOverhead
inlineconstexpr

Counted ceiling for one standalone-TOTP row's fixed JSON scaffolding (6 keys, braces, numeric maxima, quoted algorithm) — 110 counted, rounded up.

kClockNotSyncedJson #

const char* kleidos::web::totp::kClockNotSyncedJson
inlineconstexpr

Body paired with ::kStatusClockUntrusted for a volatile clock no precise sync holds for (it was set by hand, or the board slept since).

kClockUnsetJson #

const char* kleidos::web::totp::kClockUnsetJson
inlineconstexpr

Body paired with ::kStatusClockUntrusted for an unset clock on a board whose RTC keeps the time: any set on the Time panel makes codes readable.

kClockUnsetPreciseJson #

const char* kleidos::web::totp::kClockUnsetPreciseJson
inlineconstexpr

Body paired with ::kStatusClockUntrusted for an unset clock on a board without an RTC chip: only a precise set counts there, and this browser is one.

kCodeBodyReserve #

size_t kleidos::web::totp::kCodeBodyReserve
inlineconstexpr

Room for the longest live-code body, reserved once so the string that holds the code never grows into a fresh block and frees the old one unwiped.

kColumnSlack #

size_t kleidos::web::adminimport::kColumnSlack
inlineconstexpr

Room a staged text keeps past the record column it is copied into. The binder clamps on whole code points; the record cuts by bytes, as it always has. One code point of room (at most four bytes) means the staged head is always longer than the column, so the record's byte cut, not the binder's, decides where a long name, user, password or URL ends.

kFrameCap #

size_t kleidos::web::restoregate::kFrameCap
inlineconstexpr

The most bytes a restore body's secrets frame may take.

A restore body is the frame and then the backup. The frame is one line: the blank lead-in (bodycap::kLeadIn), a JSON object holding the unlock secret as current and, on the encrypted route, the backup passphrase as passphrase, and a line feed. JSON text cannot hold a raw line feed, so the first one ends the frame. The bound holds the lead-in and both secrets at their caps with every character escaped as a six-byte \uXXXX sequence, with room to spare.

kGeneratedPassLen #

uint8_t kleidos::web::adminimport::kGeneratedPassLen
inlineconstexpr

Length of an on-device generated password for a passwordless item: the one a CSV import by card mints (kleidos::vault::kGeneratedPassLen).

kImportBodyCap #

size_t kleidos::web::adminimport::kImportBodyCap
inlineconstexpr

Request-body cap in bytes (32 normalized items fit comfortably), after the page's blank lead-in.

kMaxArrayEntries #

uint32_t kleidos::web::adminimport::kMaxArrayEntries
inlineconstexpr

Most entries an array of the import or the credential save may carry: the body caps bound them long before, and what is past what a record holds is dropped or refused by the route, never by the binder.

kPassphraseRefusal #

const char* kleidos::web::rekey::kPassphraseRefusal
inlineconstexpr

The body of the refusal for a new passphrase on a board that dials its PIN: a dial collects digits only, so the vault could never be opened again.

kPinLengthRefusal #

std::array<const char*, 3> kleidos::web::rekey::kPinLengthRefusal
inlineconstexpr

The body of the refusal for a pin_length this surface does not take, in security::pin_policy::SetSurface order.

kRestoreBodyCapBytes #

size_t kleidos::web::backuplimits::kRestoreBodyCapBytes
inlineconstexpr

Body cap for POST /api/restore — the largest plaintext backup any board writes: as many records as the biggest board has slots, each at its schema maximum, under the longest meta any board's backup carries.

A backup bigger than this device is not refused for its size: the restore takes its first entries in its own order and counts the rest (backup::OverCapacity), so the body it must be ready to read is the largest of any board, the same on every board: a cap from this board's own slots would refuse a full backup of a 500-slot board on a 90-slot one before a byte was read.

That is 12,394,162 bytes (about 11.82 MiB) on every board, computed by the compiler from the field constants and the largest slot counts of any board (500 credentials and 50 one-time codes), so raising either moves it.

kRestoreEncryptedBodyCapBytes #

size_t kleidos::web::backuplimits::kRestoreEncryptedBodyCapBytes
inlineconstexpr

Body cap for POST /api/restore/encrypted — the plaintext bound wrapped in the .kexp envelope (header, one framed and tagged chunk per 4 KB of plaintext, PKCS#7 padding up to one AES block).

kSecretFieldBytes #

size_t kleidos::web::totpfield::kSecretFieldBytes
inlineconstexpr

Room for a base32 secret or a whole otpauth:// URI; a longer text refuses the body.

kTotpBodySecret #

size_t kleidos::web::totpfield::kTotpBodySecret
inlineconstexpr

Index of each member in kTotpBodyMembers.

secret.

kWideIntBound #

int64_t kleidos::web::totpfield::kWideIntBound
inlineconstexpr

Wide enough for any integer a client sends: a value out of a field's width is judged by the field, never refused as a body.

Back to the top