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/ |
| Incremental splitter for the backup document: hands out one record at a time. | |
| file | src/ |
| Whether a CSV on the card raises a question only its owner can answer. | |
| file | src/ |
| Turning one mapped CSV row into a stored credential. | |
| file | src/ |
| Vendor CSV signatures and header-keyed column mapping. | |
| file | src/ |
| Device-generated export passphrase (diceware) for encrypted SD backups. | |
| file | src/ |
| A streaming JSON writer and a streaming reader with no allocation. | |
| file | src/ |
| SD-card vault backup/ | |
| file | src/ |
| The SD file browser: SdVault:: | |
| file | src/ |
| The CSV import from the card: SdVault:: | |
| file | src/ |
| Firmware from the card: SdVault:: | |
| file | src/ |
| SdVault:: | |
| file | src/ |
| What the sources of SdVault share: the log tag, the card probe and the whole-write helper. | |
| file | src/ |
| 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/ |
| The streamed seal and open of a .kexp backup (see sealed_ | |
| file | src/ |
| Seal the vault into a .kexp envelope, and open one back into the vault — streamed, the one implementation every surface uses. | |
| file | src/ |
| JSON backup boundary for the vault — human-readable export / import. | |
| file | src/ |
| What the export and restore sources of the backup boundary share. | |
| file | src/ |
| The restore side of the JSON backup boundary: the streamed parse of a backup document into the vault (part of vault_ | |
Classes | |
| struct | kleidos:: |
Consumer of the split document. Every callback may refuse (return false), which stops the split; user is forwarded untouched. More about kleidos:: | |
| class | kleidos:: |
| Cuts the backup document into its members as bytes arrive. More about kleidos:: | |
| struct | kleidos:: |
| Caller-chosen policy for one import run. More about kleidos:: | |
| struct | kleidos:: |
| Column mapping: which CSV column index holds each credential field. More about kleidos:: | |
| struct | kleidos:: |
| Tells where one CSV record ends in a byte stream. More about kleidos:: | |
| struct | kleidos:: |
Injectable wordlist source for generateExportPassphrase. More about kleidos:: | |
| class | kleidos:: |
| Streams JSON text to a sink, value by value. More about kleidos:: | |
| struct | kleidos:: |
| Where one string value goes as a StreamReader unescapes it. More about kleidos:: | |
| class | kleidos:: |
| Reads one JSON value as its bytes arrive, a piece at a time. More about kleidos:: | |
| struct | kleidos:: |
| Outcome of a CSV import run. More about kleidos:: | |
| struct | kleidos:: |
| What one open of the card's .kexp tells the attempt that follows it. More about kleidos:: | |
| class | kleidos:: |
| Static facade for SD-card vault backup/ | |
| struct | kleidos:: |
| How far a seal or an open is, as it goes. More about kleidos:: | |
| struct | kleidos:: |
| Where a sealed vault goes. More about kleidos:: | |
| struct | kleidos:: |
| Where a sealed backup comes from. More about kleidos:: | |
| struct | kleidos:: |
| How an open ended. More about kleidos:: | |
| class | kleidos:: |
| A 4 KB rolling buffer in front of a sink that pays per call. More about kleidos:: | |
| struct | kleidos:: |
| 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:: | |
| struct | kleidos:: |
| 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:: | |
Typedefs | |
| using | kleidos:: |
Pull the wordlist word at index into buf (NUL-terminated). | |
| using | kleidos:: |
| Where the writer's text goes. Returns false to stop the writer. | |
| using | kleidos:: |
| Called as a whole-set card copy advances, once per file. | |
| using | kleidos:: |
| Runs one key-derivation job and answers what it returned; null runs it inline. | |
| using | kleidos:: |
| Step the vault's whole freshness anchor and persist meta once. | |
| using | kleidos:: |
| Destination for backup bytes as they are produced. | |
Functions | |
| constexpr bool | kleidos:: |
| Whether the owner has to be asked about passwordless rows. | |
| CsvRowOutcome | kleidos:: |
| Ingest one mapped CSV line into the vault. | |
| const char * | kleidos:: |
Parse a single CSV field starting at p. | |
| CsvFormat | kleidos:: |
Detect CSV format from the header line and fill in map. | |
| const char * | kleidos:: |
| Human-readable name for a detected export format. | |
| const char * | kleidos:: |
Find the end of the CSV record starting at start in a buffer. | |
| void | kleidos:: |
| Reduce a URL to the host a person would call the site by. | |
| bool | kleidos:: |
Parse one CSV data row into out using a header-derived column map. | |
| void | kleidos:: |
| Reduce a group/ | |
| bool | kleidos:: |
| Decide whether a row's type cell denotes an importable login. | |
| bool | kleidos:: |
| Interpret a CSV boolean cell (favorite / archived flags). | |
| bool | kleidos:: |
| Copy one mapped column of a CSV row into a caller-sized buffer. | |
| size_t | kleidos:: |
Generate a diceware passphrase into out. | |
| double | kleidos:: |
| Shannon entropy (bits) of a diceware passphrase. | |
| size_t | kleidos:: |
| Select and generate the device export passphrase. | |
| SealResult | kleidos:: |
Seal the unlocked vault under passphrase into target. | |
| constexpr RejectedOpen | kleidos:: |
Classify the report of an open that answered Rejected. | |
| OpenReport | kleidos:: |
Open the envelope source carries under passphrase and replace the vault with it. | |
| bool | kleidos:: |
| Emit the JSON backup document — one record at a time. | |
| bool | kleidos:: |
| Open a streamed restore: validate the target, allocate the session. | |
| bool | kleidos:: |
| Feed the next piece of the backup document. | |
| ImportStatus | kleidos:: |
| Close the document and finish the full replace: purge the slots the backup did not carry, write the index, reclaim what the restore superseded. | |
| ImportStatus | kleidos:: |
| Parse a JSON backup envelope and merge credential bodies into the target vault, re-encrypted under the target's own keys. | |
Variables | |
| constexpr uint8_t | kleidos:: |
| Default length of a password minted for a row that carries none. | |
| constexpr uint32_t | kleidos:: |
| Default diceware word count (~77.5 bits with the 7776-word EFF large list). | |
| constexpr char | kleidos:: |
| Separator inserted between diceware words (hyphen: unambiguous when written). | |
| constexpr size_t | kleidos:: |
| constexpr uint32_t | kleidos:: |
| constexpr uint8_t | kleidos:: |
| Length of the alphanumeric fallback passphrase (~119 bits over the 62-char set). | |
| constexpr size_t | kleidos:: |
| Deepest object/array nesting either side accepts. | |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
Typedef Documentation
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
-
Name Direction Meaning owner in The cookie handed to importAll.
- Return values
-
Value Meaning true Every counter advanced and the new meta is on flash. false The commit did not land; the counters are unchanged and the caller must refuse the restore before writing anything.
BackupSink #
Destination for backup bytes as they are produced.
- Return values
-
Value Meaning false The sink could not take the bytes; the export stops.
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
-
Name Meaning user Opaque cookie the caller handed to the copy.
WordReader #
Pull the wordlist word at index into buf (NUL-terminated).
- Parameters
-
Name Direction Meaning index in 0-based word index in [0, lineCount).buf out Destination buffer for the word (NUL-terminated, no trailing newline). bufLen in Capacity of bufin bytes.userCtx in Opaque caller context (e.g. the wordlist name); may be nullptr.
- Return values
-
Value Meaning true A word was written. false Index out of range or a read error.
Enumeration Type Documentation
CsvFormat #
CSV format identifiers.
CsvRowOutcome #
What became of one row. Callers keep their own tallies from these.
PasswordlessRow #
RejectedOpen #
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.
SealResult #
Function Documentation
csvCellTruthy() #
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
-
Name Direction Meaning value in NUL-terminated cell text (may be nullptr).
- Returns
- true when the cell holds a set flag.
csvFormatName() #
Human-readable name for a detected export format.
- Parameters
-
Name Direction Meaning fmt in Detected format.
- Returns
- A short vendor label, or
"generic".
csvGroupFirstValue() #
Reduce a group/
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
-
Name Direction Meaning cell in, out NUL-terminated cell text, rewritten to the single name.
csvLabelFromUrl() #
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/
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
-
Name Direction Meaning url in NUL-terminated URL, may be empty. out out Receives the label, always NUL-terminated. outCap in Capacity of outin bytes, including the NUL.
csvNeedsPasswordlessAnswer() #
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
-
Name Direction Meaning passwordlessRows in Count from SdVault::.csvPasswordlessRows
- Return values
-
Value Meaning true Ask; both answers change what ends up in the vault. false Nothing to ask about — go straight to the import.
csvRecordEnd() #
Find the end of the CSV record starting at start in a buffer.
- Parameters
-
Name Direction Meaning start in First byte of the record. end in One past the last byte of the buffer.
- Returns
- The line break that ends the record, or
endwhen the buffer ends first. Never splits inside a quoted cell.
- See also
- CsvRecordScanner
csvTypeCellIsLogin() #
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
-
Name Direction Meaning value in NUL-terminated type cell text (may be nullptr).
- Returns
- true when the row is a login and should be imported.
detectCsvFormat() #
Detect CSV format from the header line and fill in map.
- Parameters
-
Name Direction Meaning header in First line of the CSV file (NUL-terminated). map in, out Receives the column index mapping; cleared on entry.
- Return values
-
Value Meaning CsvFormat:: BITWARDEN Header matches the Bitwarden export signature. CsvFormat:: KEEPASS Header matches the KeePass export signature. CsvFormat:: ONEPASSWORD Header matches the 1Password export signature. CsvFormat:: LASTPASS Header matches the LastPass export signature. CsvFormat:: PROTONPASS Header matches the Proton Pass export signature. CsvFormat:: CHROME Header matches the Chrome export signature. CsvFormat:: FIREFOX Header matches the Firefox export signature. CsvFormat:: GENERIC Header matches a generic name/ user/ pass/ URL signature (simple fallback). CsvFormat:: UNKNOWN No signature matched.
dicewareEntropyBits() #
Shannon entropy (bits) of a diceware passphrase.
- Parameters
-
Name Direction Meaning lineCount in Wordlist size (distinct words). wordCount in Number of words drawn.
- Returns
wordCount* log2(lineCount), or 0 whenlineCount< 2 orwordCountis 0.
extractCsvColumn() #
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
-
Name Direction Meaning line in Start of the row (not NUL-terminated). length in Row length in bytes, excluding the line break. col in Column index from a CsvColumnMap (-1 = unmapped). out out Receives the cell text, always NUL-terminated (clamped to outCap; over-long cells are truncated, never split).outCap in Capacity of outin bytes, including the NUL.
- Return values
-
Value Meaning true The row reaches column col(the cell may still be empty).false colis unmapped, the row ends before it, or scratch allocation failed;outholds "".
- Warning
- SECURITY: the row may hold a password in another column; the scratch copy is wiped before release on every path.
generateDiceware() #
Generate a diceware passphrase into out.
Draws wordCount uniformly-random indices in [0, lineCount) from the hardware RNG (kleidos::reader, and joins them with separator.
- Parameters
-
Name Direction Meaning reader in Word source (typically an SD wordlist adapter). userCtx in Opaque context forwarded to reader.lineCount in Number of words available in the wordlist (must be >= 2). wordCount in Number of words to draw (must be >= 1). separator in Byte inserted between words (not before the first). out out Destination buffer; NUL-terminated on success, set to an empty string on failure. outCap in Capacity of outin bytes.
- Returns
- Length written (excluding the NUL), or 0 on failure (bad arguments, a reader error, or insufficient capacity).
- Warning
- SECURITY:
outholds credential-grade material; the caller owns zeroizing it. The internal per-word scratch is wiped before return.
generateExportPassphrase() #
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
-
Name Direction Meaning provider in Wordlist source (injectable for testing). out out Destination buffer; NUL-terminated on success. cap in Capacity of outin bytes.
- Returns
- Length written (excluding NUL), or 0 on error.
- Warning
- SECURITY:
outholds credential-grade material; the caller owns zeroizing it. Randomness comes exclusively from the hardware RNG.
importAll() #
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.
advanceAnchorcloses 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
-
Name Direction Meaning jsonData in Backup JSON (not necessarily NUL-terminated). jsonLen in Length of jsonDatain bytes.keys in Unlocked session sub-keys (enc/mac) for re-encryption. currentMeta in Target's cached meta record, or null when locked. advanceAnchorMUST leave this record reading the ADVANCED counters — the records below are bound to them.advanceAnchor in Steps every credGen / totpGen entry once and persists meta atomically; null, or a false return, refuses the restore before any write. anchorOwner in Opaque cookie forwarded to advanceAnchor.policy in What a backup bigger than this device does (restoreBegin). tally out Optional: 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() #
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
-
Name Direction Meaning key in Vault key (32 bytes) of the unlocked session. lineStart in Start of the CSV line (not NUL-terminated). lineLen in Length of the line in bytes. colMap in Column mapping from detectCsvFormat. opts in Policy for this run.
- Returns
- What happened to this row.
parseCsvField() #
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
-
Name Direction Meaning p in Current position in the CSV line. out out Output buffer (always NUL-terminated). maxLen in Capacity of outin bytes (excluding NUL).
- Returns
- Pointer to the byte right after the consumed field.
parseMappedCsvLine() #
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
-
Name Direction Meaning line in Start of the row (not NUL-terminated). length in Row length in bytes, excluding the line break. map in Column mapping from detectCsvFormat. out out Receives the credential; wiped on entry.
- Return values
-
Value Meaning true A usable row: it had a name (or a URL to fall back on). false Empty or unusable; outis left wiped.
rejectedOpen() #
Classify the report of an open that answered Rejected.
- Parameters
-
Name Direction Meaning report in What unseal reported.
- Returns
- The one case the report shows.
restoreBegin() #
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::
- Parameters
-
Name Direction Meaning ctx in Where the restore writes and what it writes under. policy in What a backup holding more than this device stores does: OverCapacity:: Refuse answers DoesNotFitwith 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
-
Value Meaning false The target is locked / its meta is unavailable / the filesystem could not be mounted / no memory — ImportStatus:: Rejected.
restoreEnd() #
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
-
Name Direction Meaning ctx in The session opened by restoreBegin.onProgress in Called 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. progressUser in Cookie handed to onProgress.tally out Optional: 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() #
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
-
Name Direction Meaning ctx in The session opened by restoreBegin.data in Next bytes of the backup document. len in Bytes in data.
- Return values
-
Value Meaning false Stop feeding — the document is malformed or a record refused; restoreEndstill has to be called for the verdict.
seal() #
Seal the unlocked vault under passphrase into target.
- Parameters
-
Name Direction Meaning vaultKey in 32-byte vault key of the unlocked session. passphrase in, out Export passphrase (need not be NUL-terminated); wiped as soon as the key is derived. passLen in Its length. target in Where the envelope goes. runKdf in Where the key derivation runs; null for inline. progress in Records sealed, as a percentage of the vault. stats out Optional: records and time, for the caller's log line.
- Returns
- How it ended.
streamAll() #
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:: 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::, 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
-
Name Direction Meaning key in 32-byte vault key of the unlocked session. sink in Where the JSON goes, in emission order and in small pieces. user in Cookie forwarded to sink.stats out Optional: records emitted and the time spent reading and serializing them. onProgress in Called during the counting prologue, before anything is emitted, or nullptr.progressUser in Cookie forwarded to onProgress.
- Return values
-
Value Meaning true Every record was emitted and the document was closed. false The 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() #
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
-
Name Direction Meaning source in Where the envelope comes from. passphrase in, out Export passphrase (need not be NUL-terminated); wiped as soon as the key is derived. passLen in Its length. runKdf in Where the key derivation runs; null for inline. progress in Envelope consumed, then the closing passes. policy in What a backup holding more than this device stores does ( kleidos::): 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.vault:: backup:: OverCapacity
- Returns
- What it did.
- Precondition
- The vault is mounted (
VaultStore::).begin
Variable Documentation
kBackupElementOverhead #
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 #
Output-buffer capacity for a generated export passphrase, matching the web egress cap (127 chars + NUL). Large enough for six EFF words + separators.
kJsonEscapeFactor #
Worst-case JSON expansion of one stored byte: a control byte serializes as a six-character \uXXXX escape.
kMinExportWordlistLines #
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 #
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.