In development. It changes without notice.
Topic
One-Time Codes
Time-based one-time codes (RFC 6238): making one from the secret in the vault, and the gate that refuses when the clock cannot be trusted.
A code is made in five steps:
- the gate issues the time, or refuses;
- the time step is that time divided by 30 or 60 s;
- HMAC-SHA1, or HMAC-SHA256, of the step under the decrypted secret;
- dynamic truncation (RFC 4226);
- the remainder of 10 to the power of 6 or 8, with its leading zeros.
The gate is the only source of the time a code is made from, so no screen can make a code without asking it. It asks that the setting is on (it is by default on the boards with a clock chip, and off on the others), that the clock is set and, on a board without a clock chip, that a source which knows the time to the second set it since the last deep sleep: a network time answer, the portal's browser or a GPS receiver. A time set by hand does not count there, and enough light sleep after the sync spends it.
Codes are made by a worker of their own, so one never waits behind an unlock.
- See also
- Vault Storage, Clock & Time Zone, Network Services
Files | |
| file | src/ |
| The time base a one-time code is made from, issued only by the gate. | |
| file | src/ |
| The one place a stored TOTP's parameters are judged, its current code produced and that code turned into text. | |
| file | src/ |
| The TOTP gate: implementation of totp_gate.h. | |
| file | src/ |
| The one gate every one-time code goes through: the 2FA codes setting and whether the clock is good enough for a code. | |
| file | src/ |
| The TOTP gate's verdicts and its rule, pure and host-tested. | |
| file | src/ |
| RFC 6238 time-based one-time password generator (HMAC-SHA1 / HMAC-SHA256). | |
| file | src/ |
| Off-core TOTP worker so HMAC work never jitters the UI render ticks. | |
Classes | |
| class | kleidos:: |
| Proof that the TOTP gate passed: the Unix time a code is made from. More about kleidos:: | |
| struct | kleidos:: |
| Everything currentCode needs from a stored entry, as a view. More about kleidos:: | |
| struct | kleidos:: |
The gate's answer: the verdict, and the time base when it is Ready. More about kleidos:: | |
| class | kleidos:: |
| Stateless RFC 6238 TOTP generator. More about kleidos:: | |
Typedefs | |
| using | kleidos:: |
| Text of one code: up to kDigits8 characters plus the terminator. | |
Enumerations | |
| enum class | kleidos:: |
| enum class | kleidos:: |
| HMAC hash function driving the RFC 6238 pipeline. More about kleidos:: | |
Functions | |
| constexpr CodeClock | kleidos:: |
| Native tests only: a time base for a fixed epoch (an RFC vector's). | |
| constexpr uint8_t | kleidos:: |
| Clamp a stored digit count to the only two legal RFC 6238 values. | |
| constexpr uint16_t | kleidos:: |
| Clamp a stored time step to the only two legal RFC 6238 values. | |
| constexpr bool | kleidos:: |
| Whether a write may set this digit count. | |
| constexpr bool | kleidos:: |
| Whether a write may set this time step. | |
| void | kleidos:: |
| Render a code as its fixed-width, zero-padded decimal text. | |
| bool | kleidos:: |
| Generate the code valid at the gate's time base on the TOTP worker. | |
| Verdict | kleidos:: |
| Ask the gate, once per frame or request. | |
| bool | kleidos:: |
| The 2FA codes setting. | |
| bool | kleidos:: |
| Store the 2FA codes setting. | |
| constexpr Gate | kleidos:: |
| The gate's rule: the setting first, then the clock, then the sync. | |
| constexpr const char * | kleidos:: |
| The verdict's wire and console spelling. | |
| constexpr TotpAlgorithm | kleidos:: |
| Map the vault's stored algorithm byte onto TotpAlgorithm. | |
| bool | kleidos:: |
| Bring up the TOTP worker. Idempotent. | |
| void | kleidos:: |
| Stop the worker: drain the queue, signal exit, join (bounded timeout) and tear down the queue. | |
| bool | kleidos:: |
| Return whether the worker task is currently running. | |
| rtos:: | kleidos:: |
| Return the worker task handle. | |
| uint32_t | kleidos:: |
| Return the number of requests currently queued (diagnostics only). | |
| bool | kleidos:: |
| Whether running the work inline is safe right now. | |
| template<typename Fn> | |
| bool | kleidos:: |
Run fn on the TOTP worker thread and return its result. | |
| void | kleidos:: |
| Host builds only: make execute report a dispatch that did not run. | |
Variables | |
| constexpr uint8_t | kleidos:: |
| Short RFC 6238 code length (the default). | |
| constexpr uint8_t | kleidos:: |
| Long RFC 6238 code length. | |
| constexpr uint16_t | kleidos:: |
| Default RFC 6238 time step, in seconds. | |
| constexpr uint32_t | kleidos:: |
| How often a list of codes repaints its countdowns, in milliseconds. | |
| constexpr uint16_t | kleidos:: |
| Long RFC 6238 time step, in seconds. | |
| constexpr bool | kleidos:: |
| The setting's default: on where a battery-backed RTC keeps the time. | |
| constexpr std::array< const char *, 4 > | kleidos:: |
| The verdicts' wire and console spellings, in Gate order. | |
Enumeration Type Documentation
Gate #
Whether a one-time code may be made now, and why not.
| Value | Meaning |
|---|---|
Ready | A code may be made; the gate's verdict carries the time base. |
Disabled | The 2FA codes setting is off on this device. |
ClockUnset | The clock is not set (trust None). |
NeedsSync | The clock is only Volatile and no precise sync holds since the last sleep. |
TotpAlgorithm #
HMAC hash function driving the RFC 6238 pipeline.
The enumerator values are the vault's on-record algorithm byte (see kleidos::
Function Documentation
begin() #
Bring up the TOTP worker. Idempotent.
Default placement matches the canonical Kleidos task ladder: Core 0 (PRO_CPU), priority 4: one band above the vault worker (3), which shares that core.
- Parameters
-
Name Direction Meaning core in Target core. Defaults to PRO_CPU. priority in Application priority.
- Return values
-
Value Meaning true Worker is running on exit (started by this call, or idempotent re-entry). false Worker spawn failed (e.g. queue allocation error).
- See also
- shutdown
clampDigits() #
Clamp a stored digit count to the only two legal RFC 6238 values.
Applied on READ: a record written by an older build (or restored from a hand-edited backup) may carry any byte, and an unclamped value would desynchronize the code from every other authenticator.
- Parameters
-
Name Direction Meaning digits in Raw digit count from the record.
clampPeriod() #
Clamp a stored time step to the only two legal RFC 6238 values.
Applied on READ. A zero or absurd period would otherwise wrap the remaining-seconds arithmetic (period - epoch % period) and report a countdown that never expires.
- Parameters
-
Name Direction Meaning period in Raw period from the record, in seconds.
codeClock() #
Ask the gate, once per frame or request.
Reads the setting, the clock's trust, the clock and then the precise-sync record, in that order: a clock write clears the record before it moves the clock, so a time read here is never paired with a sync made before it.
- Returns
- The verdict;
clockholds the time base exactly when it isGate::Ready.
codeClockForTest() #
Native tests only: a time base for a fixed epoch (an RFC vector's).
- Parameters
-
Name Meaning epoch Unix seconds. msIntoSecond Milliseconds into that second, for the countdown arc.
- Returns
- A time base for
epoch.
currentCode() #
Generate the code valid at the gate's time base on the TOTP worker.
Runs TotpGenerator::
- Parameters
-
Name Direction Meaning seed in The stored secret and parameters. clock in The time base a Gate::Readyverdict carried (kleidos::).totp:: codeClock() code out The code on success; 0 when there is none. remaining out Optional: seconds left in the clamped period, written whether or not a code came out.
- Return values
-
Value Meaning true codeis the current code.false There is no code to show or type: the worker dispatch did not run the generator (its completion semaphore could not be allocated, or the worker shut down with the request queued), or PSA could not compute the HMAC (an empty secret included).
- See also
- formatCode
decideGate() #
The gate's rule: the setting first, then the clock, then the sync.
A battery-backed RTC keeps the time through every sleep, so a Backed clock needs no sync. A Volatile one (the boards without an RTC chip) is good for a code only while a precise sync holds (time/): a time a person sets on the device never is.
- Parameters
-
Name Meaning enabled The 2FA codes setting. trust The clock's trust. preciseSyncHolds Whether a precise sync holds ( precise::).fresh()
- Returns
- The verdict.
enabled() #
The 2FA codes setting.
Read from NVS once and cached; an absent key, or an NVS that cannot be opened, reads as kEnabledByDefault.
- Return values
-
Value Meaning true The device shows and types codes. false It makes none.
execute() #
Run fn on the TOTP worker thread and return its result.
Capturing lambdas are allowed: the worker invokes them through a captureless trampoline, so all closure state stays on the caller's stack. Falls back to inline execution when onWorker returns true (worker not running or caller IS the worker).
On a host build no FreeRTOS worker exists and fn always runs inline, unless setDispatchFailureForTest armed a failed dispatch.
- Template Parameters
-
Name Meaning Fn Callable as bool fn(); capturing lambdas are allowed.
- Parameters
-
Name Direction Meaning fn in Work to execute; runs inline when on the worker or when the worker is not running.
- Return values
-
Value Meaning true fnreturnedtrue.false fnreturnedfalse, or the semaphore/queue dispatch failed and the call did not run (on a host build: setDispatchFailureForTest armed a failed dispatch).
- See also
- onWorker
formatCode() #
Render a code as its fixed-width, zero-padded decimal text.
RFC 6238 codes are compared as text, so a code below 10^(digits-1) keeps its leading zeros ("012345", not "12345"). A value wider than the width is reduced modulo 10^width, matching the generator's own truncation.
- Parameters
-
Name Direction Meaning code in Code value from currentCode. digits in Stored digit count; clamped by clampDigits. out out Receives exactly clampDigits(digits) characters.
gateLabel() #
The verdict's wire and console spelling.
- Parameters
-
Name Meaning gate The verdict.
- Returns
- "ready", "disabled", "clock_unset" or "needs_sync" (never nullptr).
isRunning() #
isValidDigits() #
Whether a write may set this digit count.
Writes are strict where reads are lenient: anything but 6 or 8 is refused rather than silently clamped. Pass the value at full width; a narrowing cast first would read 264 as 8.
- Parameters
-
Name Direction Meaning digits in Requested digit count.
- Return values
-
Value Meaning true digitsis 6 or 8.false Any other value.
isValidPeriod() #
Whether a write may set this time step.
- Parameters
-
Name Direction Meaning period in Requested period, in seconds.
- Return values
-
Value Meaning true periodis 30 or 60.false Any other value.
onWorker() #
Whether running the work inline is safe right now.
- Return values
-
Value Meaning true When the worker is not running, or the caller IS the worker (so dispatching would deadlock on its own semaphore wait). Always, on a host build: no worker thread exists there. false When a dispatch is required.
- See also
- execute, taskHandle
pendingRequests() #
Return the number of requests currently queued (diagnostics only).
- Returns
- Number of pending dispatch requests. A queue-depth probe for diagnostics surfaces (e.g. the serial debug console).
setDispatchFailureForTest() #
Host builds only: make execute report a dispatch that did not run.
A device dispatch fails when the caller's completion semaphore cannot be allocated, or when the worker shuts down with the request queued; the work never runs and execute returns false. The host build runs everything inline, so a native test reaches that path through this switch.
- Parameters
-
Name Direction Meaning fail in True to fail every following execute without running its work; false to run inline again.
setEnabled() #
Store the 2FA codes setting.
- Parameters
-
Name Meaning on The new value.
- Return values
-
Value Meaning true NVS took it (the cache follows). false NVS refused; the setting is unchanged.
shutdown() #
Stop the worker: drain the queue, signal exit, join (bounded timeout) and tear down the queue.
Posts a nullptr sentinel to wake the worker, waits up to 200 ms for the task to delete itself, and force-deletes if it does not exit in time. Stale queued requests have their completion semaphores given so blocked callers can unwind.
- Note
- Safe to call when the worker is not running. Must be called before deep sleep.
- See also
- begin
taskHandle() #
Return the worker task handle.
- Returns
- The worker task handle, or
nullptrwhen not running.
- See also
- onWorker
totpAlgorithmFromByte() #
Map the vault's stored algorithm byte onto TotpAlgorithm.
Any value other than 1 clamps to SHA-1, mirroring the record decoder's unknown-value clamp so both layers agree on the fallback.
- Parameters
-
Name Direction Meaning value in Stored algorithm byte (0 = SHA-1, 1 = SHA-256).
- Returns
- The corresponding enumerator (SHA-1 for any unknown value).
Variable Documentation
kCountdownTickMs #
How often a list of codes repaints its countdowns, in milliseconds.
Five times a second, not once. The arc that draws a code's remaining window is the one thing on a 2FA page that moves, and from whole seconds it has one position per second, a step so small that a reader sees a page that is not moving and a recording of the page shows a still. At 200 ms the arc has five positions a second, which is the design system's own motion floor, and the region it repaints is the code and its ring and nothing else.
Paid only while a 2FA list is on the glass and the display is on; the three views that draw one share this rather than each naming a number.