Kleidos API Search

In development. It changes without notice.

Topic

Backup, Import & Export

The sealed backup the portal and the SD card share, the import of other managers' CSV files, and the SD card's flows.

A backup is sealed under a passphrase typed for it, with a key derivation of its own (Cryptography), and is read one record at a time. A CSV import knows the columns of several vendors and decides, for each row, what to do with a login the vault already holds.

See also
Vault Storage, Wi-Fi Admin Portal

Files

file src/vault/backup_document_splitter.h
Incremental splitter for the backup document: hands out one record at a time.
file src/vault/csv_import_policy.h
Whether a CSV on the card raises a question only its owner can answer.
file src/vault/csv_ingest.h
Turning one mapped CSV row into a stored credential.
file src/vault/csv_vendor_format.h
Vendor CSV signatures and header-keyed column mapping.
file src/vault/export_passphrase.h
Device-generated export passphrase (diceware) for encrypted SD backups.
file src/vault/json_lite.h
A streaming JSON writer and a streaming reader with no allocation.
file src/vault/sd_vault.h
SD-card vault backup/restore, CSV import, audit export, and 2FA key files.
file src/vault/sd_vault_browser.cpp
The SD file browser: SdVault::listDir, readTextFile and isTextFile (part of sd_vault.h).
file src/vault/sd_vault_csv.cpp
The CSV import from the card: SdVault::hasCsvFiles, csvPasswordlessRows and importCsv (part of sd_vault.h).
file src/vault/sd_vault_firmware.cpp
Firmware from the card: SdVault::hasFirmware, firmwareSize, applyFirmware and removeFirmware (part of sd_vault.h).
file src/vault/sd_vault_format.cpp
SdVault::formatCard: the FAT32 format of the card, behind the key-file gate (part of sd_vault.h).
file src/vault/sd_vault_internal.h
What the sources of SdVault share: the log tag, the card probe and the whole-write helper.
file src/vault/sd_vault_sealed.cpp
The sealed export and import of the vault on the card, and the switch that replaces a backup (part of sd_vault.h).
file src/vault/sealed_backup.cpp
The streamed seal and open of a .kexp backup (see sealed_backup.h).
file src/vault/sealed_backup.h
Seal the vault into a .kexp envelope, and open one back into the vault — streamed, the one implementation every surface uses.
file src/vault/vault_backup.h
JSON backup boundary for the vault — human-readable export / import.
file src/vault/vault_backup_internal.h
What the export and restore sources of the backup boundary share.
file src/vault/vault_backup_restore.cpp
The restore side of the JSON backup boundary: the streamed parse of a backup document into the vault (part of vault_backup.h).

Classes

struct kleidos::vault::backup::DocumentSink
Consumer of the split document. Every callback may refuse (return false), which stops the split; user is forwarded untouched. More about kleidos::vault::backup::DocumentSink
class kleidos::vault::backup::BackupDocumentSplitter
Cuts the backup document into its members as bytes arrive. More about kleidos::vault::backup::BackupDocumentSplitter
struct kleidos::vault::CsvIngestOptions
Caller-chosen policy for one import run. More about kleidos::vault::CsvIngestOptions
struct kleidos::vault::CsvColumnMap
Column mapping: which CSV column index holds each credential field. More about kleidos::vault::CsvColumnMap
struct kleidos::vault::CsvRecordScanner
Tells where one CSV record ends in a byte stream. More about kleidos::vault::CsvRecordScanner
struct kleidos::vault::passgen::WordlistProvider
Injectable wordlist source for generateExportPassphrase. More about kleidos::vault::passgen::WordlistProvider
class kleidos::vault::jsonlite::Writer
Streams JSON text to a sink, value by value. More about kleidos::vault::jsonlite::Writer
struct kleidos::vault::jsonlite::StringTarget
Where one string value goes as a StreamReader unescapes it. More about kleidos::vault::jsonlite::StringTarget
class kleidos::vault::jsonlite::StreamReader< Handler >
Reads one JSON value as its bytes arrive, a piece at a time. More about kleidos::vault::jsonlite::StreamReader< Handler >
struct kleidos::CsvImportResult
Outcome of a CSV import run. More about kleidos::CsvImportResult
struct kleidos::SdEnvelopeOpen
What one open of the card's .kexp tells the attempt that follows it. More about kleidos::SdEnvelopeOpen
class kleidos::SdVault
Static facade for SD-card vault backup/restore and related I/O. More about kleidos::SdVault
struct kleidos::vault::sealed::Progress
How far a seal or an open is, as it goes. More about kleidos::vault::sealed::Progress
struct kleidos::vault::sealed::SealTarget
Where a sealed vault goes. More about kleidos::vault::sealed::SealTarget
struct kleidos::vault::sealed::OpenSource
Where a sealed backup comes from. More about kleidos::vault::sealed::OpenSource
struct kleidos::vault::sealed::OpenReport
How an open ended. More about kleidos::vault::sealed::OpenReport
class kleidos::vault::backup::CoalescingSink
A 4 KB rolling buffer in front of a sink that pays per call. More about kleidos::vault::backup::CoalescingSink
struct kleidos::vault::backup::BackupStats
Where a streamed backup spent its time, for the one summary log line the route prints: records emitted, milliseconds reading + decrypting them on the vault worker, milliseconds serializing them into the sink (which, on the encrypted route, includes the cipher and the socket). More about kleidos::vault::backup::BackupStats
struct kleidos::vault::backup::RestoreContext
What every step of a streamed restore needs from its owner: the session keys, the cached MAC-verified meta, and the anchor commit. Built per call — the keys are never held between steps. More about kleidos::vault::backup::RestoreContext

Typedefs

usingkleidos::vault::passgen::WordReader
Pull the wordlist word at index into buf (NUL-terminated).
usingkleidos::vault::jsonlite::Sink
Where the writer's text goes. Returns false to stop the writer.
usingkleidos::SdCopyProgress
Called as a whole-set card copy advances, once per file.
usingkleidos::vault::sealed::KdfRunner
Runs one key-derivation job and answers what it returned; null runs it inline.
usingkleidos::vault::backup::AnchorAdvance
Step the vault's whole freshness anchor and persist meta once.
usingkleidos::vault::backup::BackupSink
Destination for backup bytes as they are produced.

Enumerations

enum class kleidos::vault::backup::RecordKind : uint8_t
Which record array an element came from.
enum class kleidos::vault::PasswordlessRow : uint8_t { kleidos::vault::PasswordlessRow::Skip , kleidos::vault::PasswordlessRow::Generate }
What to do with a row whose password cell is empty. More about kleidos::vault::PasswordlessRow
enum class kleidos::vault::CsvRowOutcome : uint8_t { kleidos::vault::CsvRowOutcome::Imported, kleidos::vault::CsvRowOutcome::ImportedGenerated, kleidos::vault::CsvRowOutcome::SkippedType, kleidos::vault::CsvRowOutcome::SkippedArchived, kleidos::vault::CsvRowOutcome::SkippedMalformed, kleidos::vault::CsvRowOutcome::SkippedNoPassword, kleidos::vault::CsvRowOutcome::Dropped, kleidos::vault::CsvRowOutcome::Failed }
What became of one row. Callers keep their own tallies from these. More about kleidos::vault::CsvRowOutcome
enum class kleidos::vault::CsvFormat : uint8_t { }
CSV format identifiers. More about kleidos::vault::CsvFormat
enum class kleidos::vault::sealed::SealResult : uint8_t { kleidos::vault::sealed::SealResult::Sealed , kleidos::vault::sealed::SealResult::KeyFailed , kleidos::vault::sealed::SealResult::Refused , kleidos::vault::sealed::SealResult::Cut }
How a seal ended. More about kleidos::vault::sealed::SealResult
enum class kleidos::vault::sealed::RejectedOpen : uint8_t { kleidos::vault::sealed::RejectedOpen::NotTried, kleidos::vault::sealed::RejectedOpen::KeyNotDerived, kleidos::vault::sealed::RejectedOpen::EndedBeforeFirstChunk, kleidos::vault::sealed::RejectedOpen::WrongOrTampered, kleidos::vault::sealed::RejectedOpen::DeviceRefused, kleidos::vault::sealed::RejectedOpen::EndedBeforeRecord }

Functions

constexpr boolkleidos::vault::csvNeedsPasswordlessAnswer (uint16_t passwordlessRows)
Whether the owner has to be asked about passwordless rows.
CsvRowOutcomekleidos::vault::ingestCsvRow (const uint8_t *key, const char *lineStart, size_t lineLen, const CsvColumnMap &colMap, const CsvIngestOptions &opts)
Ingest one mapped CSV line into the vault.
const char *kleidos::vault::parseCsvField (const char *p, char *out, size_t maxLen)
Parse a single CSV field starting at p.
CsvFormatkleidos::vault::detectCsvFormat (const char *header, CsvColumnMap &map)
Detect CSV format from the header line and fill in map.
const char *kleidos::vault::csvFormatName (CsvFormat fmt)
Human-readable name for a detected export format.
const char *kleidos::vault::csvRecordEnd (const char *start, const char *end)
Find the end of the CSV record starting at start in a buffer.
voidkleidos::vault::csvLabelFromUrl (const char *url, char *out, size_t outCap)
Reduce a URL to the host a person would call the site by.
boolkleidos::vault::parseMappedCsvLine (const char *line, size_t length, const CsvColumnMap &map, Credential &out)
Parse one CSV data row into out using a header-derived column map.
voidkleidos::vault::csvGroupFirstValue (char *cell)
Reduce a group/vault/folder/tags cell to one group name, in place.
boolkleidos::vault::csvTypeCellIsLogin (const char *value)
Decide whether a row's type cell denotes an importable login.
boolkleidos::vault::csvCellTruthy (const char *value)
Interpret a CSV boolean cell (favorite / archived flags).
boolkleidos::vault::extractCsvColumn (const char *line, size_t length, int8_t col, char *out, size_t outCap)
Copy one mapped column of a CSV row into a caller-sized buffer.
size_tkleidos::vault::passgen::generateDiceware (WordReader reader, const void *userCtx, uint32_t lineCount, uint32_t wordCount, char separator, char *out, size_t outCap)
Generate a diceware passphrase into out.
doublekleidos::vault::passgen::dicewareEntropyBits (uint32_t lineCount, uint32_t wordCount)
Shannon entropy (bits) of a diceware passphrase.
size_tkleidos::vault::passgen::generateExportPassphrase (const WordlistProvider &provider, char *out, size_t cap)
Select and generate the device export passphrase.
SealResultkleidos::vault::sealed::seal (const uint8_t *vaultKey, char *passphrase, size_t passLen, const SealTarget &target, KdfRunner runKdf, const Progress &progress, kleidos::vault::backup::BackupStats *stats=nullptr)
Seal the unlocked vault under passphrase into target.
constexpr RejectedOpenkleidos::vault::sealed::rejectedOpen (const OpenReport &report)
Classify the report of an open that answered Rejected.
OpenReportkleidos::vault::sealed::unseal (const OpenSource &source, char *passphrase, size_t passLen, KdfRunner runKdf, const Progress &progress, kleidos::vault::backup::OverCapacity policy=kleidos::vault::backup::OverCapacity::Refuse)
Open the envelope source carries under passphrase and replace the vault with it.
boolkleidos::vault::backup::streamAll (const uint8_t *key, BackupSink sink, void *user, BackupStats *stats=nullptr, void(*onProgress)(void *progressUser)=nullptr, void *progressUser=nullptr)
Emit the JSON backup document — one record at a time.
boolkleidos::vault::backup::restoreBegin (const RestoreContext &ctx, OverCapacity policy=OverCapacity::Refuse)
Open a streamed restore: validate the target, allocate the session.
boolkleidos::vault::backup::restoreFeed (const RestoreContext &ctx, const char *data, size_t len)
Feed the next piece of the backup document.
ImportStatuskleidos::vault::backup::restoreEnd (const RestoreContext &ctx, void(*onProgress)(void *progressUser)=nullptr, void *progressUser=nullptr, RestoreTally *tally=nullptr)
Close the document and finish the full replace: purge the slots the backup did not carry, write the index, reclaim what the restore superseded.
ImportStatuskleidos::vault::backup::importAll (const char *jsonData, size_t jsonLen, const DerivedKeys &keys, const VaultMetaRecord *currentMeta, AnchorAdvance advanceAnchor, void *anchorOwner, OverCapacity policy=OverCapacity::Refuse, RestoreTally *tally=nullptr)
Parse a JSON backup envelope and merge credential bodies into the target vault, re-encrypted under the target's own keys.

Variables

constexpr uint8_tkleidos::vault::kGeneratedPassLen
Default length of a password minted for a row that carries none.
constexpr uint32_tkleidos::vault::passgen::kExportDicewareWords
Default diceware word count (~77.5 bits with the 7776-word EFF large list).
constexpr charkleidos::vault::passgen::kDicewareSeparator
Separator inserted between diceware words (hyphen: unambiguous when written).
constexpr size_tkleidos::vault::passgen::kExportPassphraseCap
constexpr uint32_tkleidos::vault::passgen::kMinExportWordlistLines
constexpr uint8_tkleidos::vault::passgen::kFallbackPassLen
Length of the alphanumeric fallback passphrase (~119 bits over the 62-char set).
constexpr size_tkleidos::vault::jsonlite::kMaxDepth
Deepest object/array nesting either side accepts.
constexpr size_tkleidos::vault::backup::kJsonEscapeFactor
constexpr size_tkleidos::vault::backup::kBackupElementOverhead
constexpr size_tkleidos::vault::backup::kRestoreElementCapBytes

Back to the top

Typedef Documentation

AnchorAdvance #

using kleidos::vault::backup::AnchorAdvance

Step the vault's whole freshness anchor and persist meta once.

The seam a restore needs and this module must not implement: meta.bin is the vault's root of trust and VaultStore owns every byte of its I/O. The implementation adds exactly ONE step to every credGen and totpGen entry and commits the record atomically, rolling the in-RAM copy back when the commit does not land.

Exactly one step per slot is a hard requirement, not a convention: an index segment is sealed under the SUM of its slots' counters and accepts a lag of at most one step per cached slot, so two steps would push every segment out of that window, where a segment is not read at all and every row it caches is re-derived from the records — correct, and a decrypt per row.

A plain function pointer plus an opaque cookie, matching the row sink in vault_index.h — no allocation, no std::function (see sonar-project.properties, rule S5205/S5008).

Parameters
NameDirectionMeaning
ownerinThe cookie handed to importAll.
Return values
ValueMeaning
trueEvery counter advanced and the new meta is on flash.
falseThe commit did not land; the counters are unchanged and the caller must refuse the restore before writing anything.

BackupSink #

using kleidos::vault::backup::BackupSink

Destination for backup bytes as they are produced.

Return values
ValueMeaning
falseThe sink could not take the bytes; the export stops.

SdCopyProgress #

using kleidos::SdCopyProgress

Called as a whole-set card copy advances, once per file.

A copy of the whole vault outlasts timers the caller owns — the admin session's five-minute idle window above all — and nothing else runs while it does, the HTTP server answering one request at a time. The hook is what lets the caller keep those timers as alive as the work is.

Parameters
NameMeaning
userOpaque cookie the caller handed to the copy.

WordReader #

using kleidos::vault::passgen::WordReader

Pull the wordlist word at index into buf (NUL-terminated).

Parameters
NameDirectionMeaning
indexin0-based word index in [0, lineCount).
bufoutDestination buffer for the word (NUL-terminated, no trailing newline).
bufLeninCapacity of buf in bytes.
userCtxinOpaque caller context (e.g. the wordlist name); may be nullptr.
Return values
ValueMeaning
trueA word was written.
falseIndex out of range or a read error.

Back to the top

Enumeration Type Documentation

CsvFormat #

enum class kleidos::vault::CsvFormat : uint8_t

CSV format identifiers.

Enumerator
BITWARDEN 

folder,favorite,type,name,...,login_uri,login_username,login_password,...

KEEPASS 

"Group","Title","Username","Password","URL","Notes"

ONEPASSWORD 

Title,Website,Username,Password,Notes,...

LASTPASS 

url,username,password,totp,extra,name,grouping,fav

PROTONPASS 

type,name,url,email,username,password,note,totpUri,...,vault

CHROME 

name,url,username,password

FIREFOX 

"url","username","password",...

GENERIC 

name,username,password,url (simple fallback)

CsvRowOutcome #

enum class kleidos::vault::CsvRowOutcome : uint8_t

What became of one row. Callers keep their own tallies from these.

Enumerator
Imported 

Stored as the export described it.

ImportedGenerated 

Stored, with a password this device minted.

SkippedType 

Not a login row (Bitwarden note, card, identity).

SkippedArchived 

Retired in the source; it would eat a bounded slot.

SkippedMalformed 

No usable name/password after mapping.

SkippedNoPassword 

Empty password and the policy says skip.

Dropped 

The vault has no free slot left. Decided before the row's group is created or a password is minted for it.

Failed 

The write itself failed.

PasswordlessRow #

enum class kleidos::vault::PasswordlessRow : uint8_t

What to do with a row whose password cell is empty.

Enumerator
Skip 

Leave it out and count it. Storing an empty password would type nothing over BLE and still read as a success.

Generate 

Mint a random password on the device and import the row.

RejectedOpen #

enum class kleidos::vault::sealed::RejectedOpen : uint8_t

Why an open that wrote nothing went no further, as far as its report can tell. A wrong passphrase and a forged or damaged file are one answer: the envelope cannot tell them apart.

Enumerator
NotTried 

It stopped before the passphrase was tried.

KeyNotDerived 

The header arrived; the key derivation did not run.

EndedBeforeFirstChunk 

The key was derived; the envelope ended or its source failed before a whole first chunk.

WrongOrTampered 

A chunk did not authenticate under the passphrase.

DeviceRefused 

The passphrase was right; this device refused the restore.

EndedBeforeRecord 

The passphrase was right; the file failed or ended before its first record.

SealResult #

enum class kleidos::vault::sealed::SealResult : uint8_t

How a seal ended.

Enumerator
Sealed 

The envelope is whole: every record, then the tag.

KeyFailed 

The key could not be derived (or the passphrase is short); nothing written.

Refused 

The target would not open; nothing written.

Cut 

Stopped part-way: what the target holds has no tag and is not a backup.

Back to the top

Function Documentation

csvCellTruthy() #

bool kleidos::vault::csvCellTruthy(const char * value)
inline

Interpret a CSV boolean cell (favorite / archived flags).

Vendors disagree on the spelling: Bitwarden writes 1, 1Password writes true / TRUE, other tools write yes. An empty cell and the explicit negatives are false; any other non-empty text counts as set.

Parameters
NameDirectionMeaning
valueinNUL-terminated cell text (may be nullptr).
Returns
true when the cell holds a set flag.

csvFormatName() #

const char * kleidos::vault::csvFormatName(CsvFormat fmt)
inline

Human-readable name for a detected export format.

Parameters
NameDirectionMeaning
fmtinDetected format.
Returns
A short vendor label, or "generic".

csvGroupFirstValue() #

void kleidos::vault::csvGroupFirstValue(char * cell)
inline

Reduce a group/vault/folder/tags cell to one group name, in place.

The mapping: a multi-value Tags cell contributes its FIRST value (split at , or ;), and a KeePass-style Root/Web group path contributes its LEAF segment. Surrounding spaces are trimmed.

Parameters
NameDirectionMeaning
cellin, outNUL-terminated cell text, rewritten to the single name.

csvLabelFromUrl() #

void kleidos::vault::csvLabelFromUrl(const char * url, char * out, size_t outCap)
inline

Reduce a URL to the host a person would call the site by.

Used when a row carries no name of its own — every Firefox export, and any row whose name cell came out empty. The whole URL would make a poor label: on a 135x240 screen https://github.com/login truncates to noise where github.com reads at a glance. The full URL is not lost: it stays in the credential's own URL field; only the label changes.

Strips any scheme://, then stops at the first /, ? or #. A URL that reduces to nothing (a bare https://) is copied through unchanged, so the caller never gets an empty label back from a non-empty URL.

Parameters
NameDirectionMeaning
urlinNUL-terminated URL, may be empty.
outoutReceives the label, always NUL-terminated.
outCapinCapacity of out in bytes, including the NUL.

csvNeedsPasswordlessAnswer() #

bool kleidos::vault::csvNeedsPasswordlessAnswer(uint16_t passwordlessRows)
constexpr

Whether the owner has to be asked about passwordless rows.

A vendor export mixes in entries with no password: a secure note filed as a login, a row the source itself lost. The device cannot store one as it stands — an empty password types nothing over BLE and still reports a successful import — so there are exactly two honest answers, and only the owner can pick: leave those rows out, or let the device mint a random password for each.

Asked ONCE, before the first row lands, never per row. Kept here rather than inside the import because raising the question means putting a modal on screen, and the import does not run on the task that owns the screen.

Parameters
NameDirectionMeaning
passwordlessRowsinCount from SdVault::csvPasswordlessRows.
Return values
ValueMeaning
trueAsk; both answers change what ends up in the vault.
falseNothing to ask about — go straight to the import.

csvRecordEnd() #

const char * kleidos::vault::csvRecordEnd(const char * start, const char * end)
inline

Find the end of the CSV record starting at start in a buffer.

Parameters
NameDirectionMeaning
startinFirst byte of the record.
endinOne past the last byte of the buffer.
Returns
The line break that ends the record, or end when the buffer ends first. Never splits inside a quoted cell.
See also
CsvRecordScanner

csvTypeCellIsLogin() #

bool kleidos::vault::csvTypeCellIsLogin(const char * value)
inline

Decide whether a row's type cell denotes an importable login.

Multi-category exports (Bitwarden, 1Password, Proton Pass) put every item kind — logins, secure notes, cards, identities — into one file with a type column. Only login rows carry a typeable password; the rest would import as junk credentials with empty passwords. The accepted spellings: Bitwarden writes login (numeric 1 in older organization exports), 1Password writes Login (legacy "Web Form"), Proton Pass writes login.

An empty or unrecognized cell is NOT a login: in every format that has the column, logins are labeled explicitly.

Parameters
NameDirectionMeaning
valueinNUL-terminated type cell text (may be nullptr).
Returns
true when the row is a login and should be imported.

detectCsvFormat() #

CsvFormat kleidos::vault::detectCsvFormat(const char * header, CsvColumnMap & map)
inline

Detect CSV format from the header line and fill in map.

Parameters
NameDirectionMeaning
headerinFirst line of the CSV file (NUL-terminated).
mapin, outReceives the column index mapping; cleared on entry.
Return values
ValueMeaning
CsvFormat::BITWARDENHeader matches the Bitwarden export signature.
CsvFormat::KEEPASSHeader matches the KeePass export signature.
CsvFormat::ONEPASSWORDHeader matches the 1Password export signature.
CsvFormat::LASTPASSHeader matches the LastPass export signature.
CsvFormat::PROTONPASSHeader matches the Proton Pass export signature.
CsvFormat::CHROMEHeader matches the Chrome export signature.
CsvFormat::FIREFOXHeader matches the Firefox export signature.
CsvFormat::GENERICHeader matches a generic name/user/pass/URL signature (simple fallback).
CsvFormat::UNKNOWNNo signature matched.

dicewareEntropyBits() #

double kleidos::vault::passgen::dicewareEntropyBits(uint32_t lineCount, uint32_t wordCount)

Shannon entropy (bits) of a diceware passphrase.

Parameters
NameDirectionMeaning
lineCountinWordlist size (distinct words).
wordCountinNumber of words drawn.
Returns
wordCount * log2(lineCount), or 0 when lineCount < 2 or wordCount is 0.

extractCsvColumn() #

bool kleidos::vault::extractCsvColumn(const char * line, size_t length, int8_t col, char * out, size_t outCap)
inline

Copy one mapped column of a CSV row into a caller-sized buffer.

Companion to parseMappedCsvLine for the columns that do not fit the fixed-capacity Credential login fields (notes, otpauth URIs, flag cells): the caller supplies a buffer sized for the one column it wants instead of paying worst-case scratch for all twenty.

Parameters
NameDirectionMeaning
lineinStart of the row (not NUL-terminated).
lengthinRow length in bytes, excluding the line break.
colinColumn index from a CsvColumnMap (-1 = unmapped).
outoutReceives the cell text, always NUL-terminated (clamped to outCap; over-long cells are truncated, never split).
outCapinCapacity of out in bytes, including the NUL.
Return values
ValueMeaning
trueThe row reaches column col (the cell may still be empty).
falsecol is unmapped, the row ends before it, or scratch allocation failed; out holds "".
Warning
SECURITY: the row may hold a password in another column; the scratch copy is wiped before release on every path.

generateDiceware() #

size_t kleidos::vault::passgen::generateDiceware(WordReader reader, const void * userCtx, uint32_t lineCount, uint32_t wordCount, char separator, char * out, size_t outCap)

Generate a diceware passphrase into out.

Draws wordCount uniformly-random indices in [0, lineCount) from the hardware RNG (kleidos::platform::random::bounded, unbiased), fetches each word via reader, and joins them with separator.

Parameters
NameDirectionMeaning
readerinWord source (typically an SD wordlist adapter).
userCtxinOpaque context forwarded to reader.
lineCountinNumber of words available in the wordlist (must be >= 2).
wordCountinNumber of words to draw (must be >= 1).
separatorinByte inserted between words (not before the first).
outoutDestination buffer; NUL-terminated on success, set to an empty string on failure.
outCapinCapacity of out in bytes.
Returns
Length written (excluding the NUL), or 0 on failure (bad arguments, a reader error, or insufficient capacity).
Warning
SECURITY: out holds credential-grade material; the caller owns zeroizing it. The internal per-word scratch is wiped before return.

generateExportPassphrase() #

size_t kleidos::vault::passgen::generateExportPassphrase(const WordlistProvider & provider, char * out, size_t cap)

Select and generate the device export passphrase.

Takes the diceware path when provider reports a wordlist with at least kMinExportWordlistLines entries (producing a kExportDicewareWords-word phrase via generateDiceware); otherwise falls back to a kFallbackPassLen-char alphanumeric string drawn from the hardware RNG.

Parameters
NameDirectionMeaning
providerinWordlist source (injectable for testing).
outoutDestination buffer; NUL-terminated on success.
capinCapacity of out in bytes.
Returns
Length written (excluding NUL), or 0 on error.
Warning
SECURITY: out holds credential-grade material; the caller owns zeroizing it. Randomness comes exclusively from the hardware RNG.

importAll() #

ImportStatus kleidos::vault::backup::importAll(const char * jsonData, size_t jsonLen, const DerivedKeys & keys, const VaultMetaRecord * currentMeta, AnchorAdvance advanceAnchor, void * anchorOwner, OverCapacity policy = OverCapacity::Refuse, RestoreTally * tally = nullptr)

Parse a JSON backup envelope and merge credential bodies into the target vault, re-encrypted under the target's own keys.

Validates the envelope version and the backup meta field (format check only — the backup meta is never written to flash; the target's meta.bin, secret, KDF salt, hmac salt, secret verifier, and device binding are always preserved). Each credential is re-encrypted under the target device's session keys and bound to the target's per-slot generation counter from its authenticated meta.bin — making the import cross-device portable: any Kleidos device can receive a backup and its own secret continues to unlock the vault after restore.

Full-replace semantics: after the restore the vault holds EXACTLY the backup's contents — slots present in the backup overwrite the same slot on the target, and slots ABSENT from the backup are removed (no stale credentials survive a restore). The target's meta.bin, secret, and device binding are still preserved.

The caller supplies the target's already-unlocked, MAC-verified meta record (the in-RAM cache owned by VaultStore) rather than having this module re-open meta.bin: an SD card mounted for the restore can leave the LittleFS VFS unable to open the vault meta file, so re-reading it here is unreliable. The target's per-slot generation counters come from this record.

The anchor advance is what makes the restore final
A restore replaces or purges EVERY credential and TOTP slot. If the per-slot generation counters stayed put, every pre-restore cred_NN.bin, totp_NN.bin and idx_NN.bin would keep verifying afterwards, so an attacker with raw flash could put the whole pre-restore vault back and it would authenticate — and a list served from a surviving segment would describe the pre-restore records over the post-restore ones. advanceAnchor closes that: it steps every counter once and persists meta ONCE, and it is called as the FIRST write of the restore, so the meta commit is the single point of no return. Everything before it is validation and leaves the vault byte-for-byte untouched; everything after it is written under the advanced counters and the pre-restore vault is cryptographically dead.
Parameters
NameDirectionMeaning
jsonDatainBackup JSON (not necessarily NUL-terminated).
jsonLeninLength of jsonData in bytes.
keysinUnlocked session sub-keys (enc/mac) for re-encryption.
currentMetainTarget's cached meta record, or null when locked. advanceAnchor MUST leave this record reading the ADVANCED counters — the records below are bound to them.
advanceAnchorinSteps every credGen / totpGen entry once and persists meta atomically; null, or a false return, refuses the restore before any write.
anchorOwnerinOpaque cookie forwarded to advanceAnchor.
policyinWhat a backup bigger than this device does (restoreBegin).
tallyoutOptional: the restore's counts (restoreEnd).
Returns
ImportStatus::Ok when the envelope parsed and EVERY record it carries is on flash; ImportStatus::Rejected when the envelope was refused before any write (target locked / meta unavailable, scratch allocation failure, parse failure, unsupported version, malformed backup meta) and the vault is therefore untouched; ImportStatus::PartialWriteFailed when a write this device attempted did not land, and ImportStatus::PartialEntriesRefused when every write landed and an entry fell outside the record grammar this device accepts — the vault then holds a strict subset of the backup either way, because a slot left empty is purged like an absent one so no pre-restore record survives under an id the backup carried.
Warning
Re-encrypts plaintext credentials internally; scratch is wiped before return. Never logs credential fields.

ingestCsvRow() #

CsvRowOutcome kleidos::vault::ingestCsvRow(const uint8_t * key, const char * lineStart, size_t lineLen, const CsvColumnMap & colMap, const CsvIngestOptions & opts)

Ingest one mapped CSV line into the vault.

Carries everything the header mapped: name, user, password, URL, notes, group (resolved or created by name), favorite, the archived filter, the login filter, and an embedded TOTP from either an otpauth:// link or a bare base32 secret.

A malformed 2FA cell never sinks the row — the login still imports, without its seed — because a credential the owner can no longer reach is worse than one missing a second factor they can re-add.

When the TOTP arrives as a bare base32 secret there is no issuer to read, so the entry inherits the credential's own name; an unnamed code in a list is unusable.

Parameters
NameDirectionMeaning
keyinVault key (32 bytes) of the unlocked session.
lineStartinStart of the CSV line (not NUL-terminated).
lineLeninLength of the line in bytes.
colMapinColumn mapping from detectCsvFormat.
optsinPolicy for this run.
Returns
What happened to this row.
See also
kleidos::vault::detectCsvFormat, kleidos::vault::parseMappedCsvLine, VaultStore::saveCredentialWithExtras

parseCsvField() #

const char * kleidos::vault::parseCsvField(const char * p, char * out, size_t maxLen)
inline

Parse a single CSV field starting at p.

Handles quoted fields with embedded commas / newlines and the "" escaped-quote convention. Advances p past the field and returns the new pointer.

Parameters
NameDirectionMeaning
pinCurrent position in the CSV line.
outoutOutput buffer (always NUL-terminated).
maxLeninCapacity of out in bytes (excluding NUL).
Returns
Pointer to the byte right after the consumed field.

parseMappedCsvLine() #

bool kleidos::vault::parseMappedCsvLine(const char * line, size_t length, const CsvColumnMap & map, Credential & out)
inline

Parse one CSV data row into out using a header-derived column map.

Reads whole fields (quotes and embedded commas handled by parseCsvField) and takes each credential field from the column the header said it was in.

Parameters
NameDirectionMeaning
lineinStart of the row (not NUL-terminated).
lengthinRow length in bytes, excluding the line break.
mapinColumn mapping from detectCsvFormat.
outoutReceives the credential; wiped on entry.
Return values
ValueMeaning
trueA usable row: it had a name (or a URL to fall back on).
falseEmpty or unusable; out is left wiped.

rejectedOpen() #

RejectedOpen kleidos::vault::sealed::rejectedOpen(const OpenReport & report)
constexpr

Classify the report of an open that answered Rejected.

Parameters
NameDirectionMeaning
reportinWhat unseal reported.
Returns
The one case the report shows.

restoreBegin() #

bool kleidos::vault::backup::restoreBegin(const RestoreContext & ctx, OverCapacity policy = OverCapacity::Refuse)
nodiscard

Open a streamed restore: validate the target, allocate the session.

Writes nothing. One restore at a time; a session left open by a caller that never reached restoreEnd is replaced by the next restoreBegin. Every caller reaches restoreEnd all the same: a session stopped inside an element still holds the reserved record buffers, and every credential read or write fails until restoreEnd (or the next restoreBegin) gives them back.

Everything reading the document takes from the heap is taken here, before the first write: the per-slot presence maps and the element reader's state, about a kilobyte. The document is read as it arrives and none of it is copied; each record is read straight into the reserved record buffers (kleidos::vault::RecordScratch, kleidos::vault::PlaintextScratch), which the restore holds from an element's first byte to its last. The stores the records are written through still take their own working buffers per write (a group label's table rewrite is the widest, about 8.8 KB).

Parameters
NameDirectionMeaning
ctxinWhere the restore writes and what it writes under.
policyinWhat a backup holding more than this device stores does: OverCapacity::Refuse answers DoesNotFit with the counts before any write, so the owner can be asked; OverCapacity::FillInOrder is the owner's answer, and writes the backup's entries in its order until full.
Return values
ValueMeaning
falseThe target is locked / its meta is unavailable / the filesystem could not be mounted / no memory — ImportStatus::Rejected.

restoreEnd() #

ImportStatus kleidos::vault::backup::restoreEnd(const RestoreContext & ctx, void(* onProgress )(void *progressUser) = nullptr, void * progressUser = nullptr, RestoreTally * tally = nullptr)
nodiscard

Close the document and finish the full replace: purge the slots the backup did not carry, write the index, reclaim what the restore superseded.

The index write is the deferred batch the restore opened closing: a full repository decrypt scan, one 4 KB record per credential, inside the same request. On a full vault that outlasts the admin portal's idle timeout, and nothing else can stamp that clock while the request is in flight, so a caller serving one passes its session's stamp as onProgress.

Parameters
NameDirectionMeaning
ctxinThe session opened by restoreBegin.
onProgressinCalled through all three passes — once per slot the purge weighs, once per index segment while the batch closes, and once per log segment the reclaim weighs — or null when the caller needs no heartbeat.
progressUserinCookie handed to onProgress.
tallyoutOptional: what the backup held, what this device stores and what was left out for lack of room — filled on every answer, the refusals included (zero where nothing was read).
Returns
ImportStatus::Ok when the whole document arrived and every record landed; ImportStatus::Rejected when nothing was written (the vault is untouched); ImportStatus::DoesNotFit when the backup holds more than this device stores and the session was opened to refuse it (untouched; the counts are in tally); ImportStatus::ContentRefused when what the document carries is not a backup this firmware reads (untouched); ImportStatus::PartialWriteFailed when the vault was rewritten and the document stopped short or a write did not commit; ImportStatus::PartialEntriesRefused when every write landed and what is missing are entries outside this device's record grammar; ImportStatus::PartialLeftOut when every write landed and the device filled up before the backup ended (how many were left out is in tally).

restoreFeed() #

bool kleidos::vault::backup::restoreFeed(const RestoreContext & ctx, const char * data, size_t len)
nodiscard

Feed the next piece of the backup document.

Records are written to flash as each one completes, under the target's keys and generation counters; the first record that reads whole is the point of no return (the freshness anchor advances, the index and group table are dropped). A record may arrive across any number of pieces.

Parameters
NameDirectionMeaning
ctxinThe session opened by restoreBegin.
datainNext bytes of the backup document.
leninBytes in data.
Return values
ValueMeaning
falseStop feeding — the document is malformed or a record refused; restoreEnd still has to be called for the verdict.

seal() #

SealResult kleidos::vault::sealed::seal(const uint8_t * vaultKey, char * passphrase, size_t passLen, const SealTarget & target, KdfRunner runKdf, const Progress & progress, kleidos::vault::backup::BackupStats * stats = nullptr)

Seal the unlocked vault under passphrase into target.

Parameters
NameDirectionMeaning
vaultKeyin32-byte vault key of the unlocked session.
passphrasein, outExport passphrase (need not be NUL-terminated); wiped as soon as the key is derived.
passLeninIts length.
targetinWhere the envelope goes.
runKdfinWhere the key derivation runs; null for inline.
progressinRecords sealed, as a percentage of the vault.
statsoutOptional: records and time, for the caller's log line.
Returns
How it ended.

streamAll() #

bool kleidos::vault::backup::streamAll(const uint8_t * key, BackupSink sink, void * user, BackupStats * stats = nullptr, void(* onProgress )(void *progressUser) = nullptr, void * progressUser = nullptr)

Emit the JSON backup document — one record at a time.

The whole vault as one document does not fit at capacity: measured, a 489-credential vault could not be backed up at all that way, which leaves the owner of a full vault with no recovery path. This walks the vault from the CALLING task, fetching one record per worker round-trip and handing its JSON to sink before touching the next, so the peak is one record plus whatever the sink buffers. The JSON reaches sink in small pieces, as it is produced: the sealed backup's envelope gathers them into its own 4 KB chunks, and any other sink that pays per call puts a CoalescingSink in front of itself. Every surface seals it through kleidos::vault::sealed except the portal's plaintext download, which coalesces.

The output is byte-for-byte the shape importAll reads: version, the base64 meta, groups, credentials (full records — login fields, notes, custom fields, timestamps, the embedded TOTP — with favorite and order joined in from the index), then standalone totp entries.

The document opens with a counts header, and deriving it is a whole-vault pass of its own: every index segment is walked before the first byte reaches the sink, and a segment that will not serve is rebuilt from a decrypt of every record it caches. A caller whose own session is kept alive by what it emits therefore has nothing to stamp during that prologue, which is what onProgress is for — it is called once per segment there, and once before the one-time-code listing behind it.

The whole walk runs at the boost clock (kleidos::platform::CpuBoostGuard, held on the calling task, which the chip-wide clock extends to the vault worker): every record is decrypted on its way out, and that crypto is most of a full vault's time. Under a sealed backup, which holds the boost already, the guard changes nothing.

Parameters
NameDirectionMeaning
keyin32-byte vault key of the unlocked session.
sinkinWhere the JSON goes, in emission order and in small pieces.
userinCookie forwarded to sink.
statsoutOptional: records emitted and the time spent reading and serializing them.
onProgressinCalled during the counting prologue, before anything is emitted, or nullptr.
progressUserinCookie forwarded to onProgress.
Return values
ValueMeaning
trueEvery record was emitted and the document was closed.
falseThe vault is locked, a record or the index could not be read, or the sink refused. The document is INCOMPLETE and nothing already emitted should be presented as a backup.
Warning
Runs on the caller's task. Do not call from the vault worker: the sink typically blocks on a transport, and the worker would be held for the whole transfer.

unseal() #

OpenReport kleidos::vault::sealed::unseal(const OpenSource & source, char * passphrase, size_t passLen, KdfRunner runKdf, const Progress & progress, kleidos::vault::backup::OverCapacity policy = kleidos::vault::backup::OverCapacity::Refuse)

Open the envelope source carries under passphrase and replace the vault with it.

A wrong passphrase fails at the first chunk, before the first record, and leaves the vault untouched. An envelope that stops part-way after records landed is reported as PartialWriteFailed: the cut-off part is unknown.

Parameters
NameDirectionMeaning
sourceinWhere the envelope comes from.
passphrasein, outExport passphrase (need not be NUL-terminated); wiped as soon as the key is derived.
passLeninIts length.
runKdfinWhere the key derivation runs; null for inline.
progressinEnvelope consumed, then the closing passes.
policyinWhat a backup holding more than this device stores does (kleidos::vault::backup::OverCapacity): the first open refuses it with its counts so the owner can be asked; the open the owner then chooses writes it in its order until full.
Returns
What it did.
Precondition
The vault is mounted (VaultStore::begin).

Back to the top

Variable Documentation

kBackupElementOverhead #

size_t kleidos::vault::backup::kBackupElementOverhead
inlineconstexpr

Scaffolding around one credential element beyond its stored bytes: the key names, the braces and brackets of the custom / urls / history arrays with their own per-entry keys, the numeric and boolean maxima, and the base64 embedded-TOTP secret (which is not part of the record's text fields).

kExportPassphraseCap #

size_t kleidos::vault::passgen::kExportPassphraseCap
inlineconstexpr

Output-buffer capacity for a generated export passphrase, matching the web egress cap (127 chars + NUL). Large enough for six EFF words + separators.

kJsonEscapeFactor #

size_t kleidos::vault::backup::kJsonEscapeFactor
inlineconstexpr

Worst-case JSON expansion of one stored byte: a control byte serializes as a six-character \uXXXX escape.

kMinExportWordlistLines #

uint32_t kleidos::vault::passgen::kMinExportWordlistLines
inlineconstexpr

Minimum wordlist line count for the diceware path in generateExportPassphrase. A truncated list (< 7776 entries) yields < 12.9 bits/word and is rejected in favor of the kFallbackPassLen-char alphanumeric fallback.

kRestoreElementCapBytes #

size_t kleidos::vault::backup::kRestoreElementCapBytes
inlineconstexpr

Longest single element of the backup document the restore will take: one record's JSON text, or the base64 meta string. Larger is refused, not truncated. Derived from the record itself — its four fixed text fields plus the whole pool budget, every byte escaped — so widening a field or the pool widens this with it. The web layer pins its per-record bound under this. It is a length the restore counts, not a buffer: an element is read as its bytes arrive and never held whole.

Back to the top