Moopro: end-to-end encrypted personal finance app
Presentation
Moopro is an app I implemented from scratch to manage all my personal finances.
Built for all platforms (web, Linux, Windows, macOS, Android, and can technically build for iOS but I don’t have an Apple developer account required to publish iOS apps). Backend hosted in the cloud.
This article focuses on the implementation details specific to moopro: end-to-end encryption, financials concepts I had to define, frontend implementation, and tradeoffs I had to decide about. Backend infrastructure is adapted from my other projects, thus it is mentionned but not detailed.
Requirements
- easily track my future spendings and my investments without relying on “balance-based budgeting” and without checking each individual bank account
- easily track my past spendings to know what need to be improved
- virtual budgets for everything (food, bike repairs, transportation, electricity…). “Can I buy this?” should not be “Do I have enough money in my bank account?”, instead it should be “Will I still have enough money planned for this purpose?”
- I need to ensure all of my banks have all the time just enough money
- The cause of my capital growing or declining should not be a mistery. Thus all of my investments should be tracked.
- I need to be able to check my budgets from my mobile phone anywhere and anytime, and manage my accounting from my computer, Thus i need:
- One single source of truth in the cloud that synchronizes all devices
- Compatibility for all platforms (web, desktop and mobile)
- Financial data is confidential, thus I need:
- Data should be encrypted at rest on all of my devices and unlocked upon authentication
- Deleted data can technically be recovered, thus decrypted financial data should never be written to disk. Should only live in RAM while the app is being used.
- Data should be end-to-end encrypted: malicious server or network access should keep my data confidential
- In order to not lose my data, regular backups are needed
- I don’t want to lose time inputting manually every transaction, thus I need a bank statement parser compatible with all my banks
Tech stack
- Languages: JavaScript, dart, Python
- Landing page: Next.js, React
- Frontend: Flutter
- Backend: Python, FastAPI
- Database: ZODB, PostgreSQL
- Infrastructure: mTLS, Traefik, Docker, Ansible, OVH Virtual Private Server, Cloudflare Pages
- Cryptography: Argon2id, AES-256-GCM
- CI running on self-hosted Gitea server for the backend, and on GitHub for the frontend
Links
Architecture overview
Before I dive deep into the implementation details, here is a high level summary of how moopro technically works:
| Work | Where it runs | Why |
|---|---|---|
| Encryption / decryption | On the device | The server must never hold a key |
| Balances, charts, forecasts | On the device | They need plaintext |
| OCR / statement parsing | On the device | Statements never leave unencrypted |
| Market & FX price fetches | On the device, straight to public APIs | The server must not learn which assets you hold |
| Storing and versioning records | Server | It only sees opaque ciphertext blobs |
flowchart LR
subgraph Device["Your device (trusted)"]
direction TB
UI["Flutter UI"]
Dom["Domain logic<br/>balances, charts, forecasts"]
Crypto["Crypto<br/>Argon2id + AES-256-GCM"]
Cache[("In-memory plaintext cache<br/>never written to disk")]
Disk[("On-disk store<br/>ciphertext only")]
UI --> Dom --> Cache
Dom --> Crypto --> Disk
end
subgraph Server["Server (untrusted)"]
Blob[("Opaque ciphertext blobs<br/>+ wrapped key")]
end
Market["Public market / FX APIs"]
Disk <-->|"ciphertext only"| Blob
Dom -->|"direct, never proxied"| MarketThe backend is a pure encrypted blob store with a sync REST API. It contains no financial logic.
Moopro trades convenience, server-side intelligence and password recovery for a system where the server cannot read, alter-undetected or profile your finances, and it keeps the limits of that trade off written down instead of hidden.
Financial concepts
Everything that holds value is represented by an asset
There is no special “currency” type. EUR, USD, AAPL, BTC, bonds and shares are all assets. Assets each have a kind property telling what sort of asset
(fiat, stock, etf, crypto, realEstateBond, other). kind is locked
after creation because it drives precision and price-linking, while the name and
symbol stay freely editable because every other record refers to an asset by its
id, never by its symbol.
The app defines one main currency that will be used to display value of other assets over time.
realEstateBond is the odd one out: unlike a stock, where everyone holding
AAPL holds the same thing, each bond asset is exactly one real-world project.
Its balance reads as “still invested in this project” and reaches zero when
fully repaid.
By following this concept, I can for example define buying a share with a trade transaction between some amount of an asset of kind currency and one unit of an asset of kind stock.
Assets are stored in containers
This is the central idea of Moopro. A container is anything that holds quantities of assets, and there are exactly two kinds:
| Holder | Budget | |
|---|---|---|
| Meaning | Where the money physically is | What the money is for |
| Examples | Bank account, brokerage account, crypto wallet | Housing, Savings, Investments |
| Real? | Yes, matches an external account | No, a user-defined virtual allocation |
Holders are enforced to be a flat list to simplify their management, but budgets (actually the container data model itself) are designed to also have child containers. Which means budgets can be seen as a tree (budgets nest into sub-budgets). For example. Budget Spendings may contain sub-budgets Holidays, Food and Bills.
A bank account and a brokerage account are the same concept: both are just “where assets are held”. There is no separate “broker” type. One holder can hold EUR cash and AAPL shares at the same time (a brokerage account with uninvested cash is the normal case), and a budget can hold a mix too (a “Savings” budget that is part cash, part ETF).
The holders and the budgets are two different slicings of the same pile of value:
flowchart TB
subgraph H["Holders: where it is"]
BA["Bank A<br/>1,200 EUR"]
BR["Broker X<br/>300 EUR + 10 AAPL"]
end
subgraph B["Budgets: what it is for"]
direction TB
INC["Income"]
HOU["Housing<br/>800 EUR"]
SAV["Savings<br/>400 EUR"]
INV["Investments<br/>300 EUR + 10 AAPL"]
INC --> HOU
INC --> SAV
INC --> INV
end
H <==>|"same total, per asset"| BBoth sides always add up to the same:
\sum \text{holder balances} = \sum \text{budget balances}
This equality is enforced by the transaction data model, and doesn’t need to be reconciled.
Any change in containers content is represented by a transaction
Defintion
Every change (money out/in, trades, transfers) is a transaction. Value entering or leaving the tracked
world (a salary arriving, a coffee bought) goes through two reserved
sentinel containers, externalHolder and externalBudget, which are never
shown in the UI.
| Kind | What happens | Holder side | Budget side |
|---|---|---|---|
income | Money in | external → Bank A | external → “Income” |
expense | Money out | Bank A → external | “Spendings” → external |
holderTransfer | Move between accounts | Bank A → Bank B | none |
budgetTransfer | Reallocate between budgets | none | “Income” → “Housing” |
trade | Swap one asset for another | Broker X: EUR → AAPL | “Investments”: EUR → AAPL |
Rules that make the invariant hold
incomeandexpenseare the only operations that change total value, and they move the holder side and the budget side by the same asset and quantity, in the same direction, inside one atomic recordtradekeeps the total but changes composition (less EUR, more AAPL), so it also moves a budget leg. If a trade was really funded from several budgets, you still pick one budget to absorb it: the invariant only needs some budget to move the exact quantity the holder did.- Transfers never cross hierarchies.
holderTransferandbudgetTransferrequire both ends to be the same container type and neither to be a sentinel. There is no transaction that moves value “from a holder into a budget”. “Move money into my Housing budget” is abudgetTransferfrom Income to Housing, after the money arrived viaincome. - Enforced in the model layer, not just by what the form shows, so a client bug or a hand-crafted record cannot create an invalid cross-hierarchy move.
- To protect in case of bugs, a live consistency indicator compares raw per-asset quantities on both sides (not converted totals, which could hide a mismatch behind a coincidentally equal number) and warns if they ever diverge.
Transaction date
Transactions have 2 date fields:
| Field | Meaning |
|---|---|
effectiveDate | The calendar day the movement actually clears the account. All balances are computed from this. |
postedAt | The instant it was recorded. Kept as real data (bank-statement times on import), never overwritten to encode ordering. |
effectiveDate is a pure calendar day (YYYY-MM-DD, no time, no zone), so
“March 1” is the same March 1 on every device. Mixing it up with an instant was
a real bug source: a transaction entered at UTC+2 could land on the previous day
on a UTC−5 device.
Recurring transactions
A recurring transaction template is a dateless pattern (a rule such as “every 3 months from Jan 31”) that can produce real transactions or be projected forward.
- Occurrence k is always computed fresh from the rule’s start date, so a monthly rule anchored on Jan 31 lands on Feb 28, then correctly on Mar 31, instead of drifting to the 28th forever.
- Posting is never silent. Due occurrences are shown behind a confirmation dialog on app open, and only an explicit user action writes transactions.
- Trades are deliberately unsupported as templates, because the received quantity depends on that day’s price, and auto-posting with a fixed rate would fabricate price history.
- Forecasts write nothing. A projection overlays future occurrences on top of current balances in memory only, and feeds the balance-over-time charts.
The concept of recurring transaction together with the possibility to create transactions in the future lets the end user plan their accounting months or even years in advance, making sure all banks and budgets always have enough money.
Balance, value and price
A container’s balance of an asset at a given time is everything that came in, minus everything that went out. Its value converts those balances into one display asset by multiplying each by that asset’s price and adding them up.
where c is a container, a an asset, T a point in time and d the display asset. \mathrm{in}(c, a, T) is the set of quantities of a moved into c by transactions up to T, and \mathrm{out}(c, a, T) the same for quantities moved out of c.
- Balance is a quantity of one asset in one container at a given point in time, past or future.
- Value converts those quantities into a single display asset (say EUR) using the latest known price.
- Debt is kept separate. Positive and negative holdings of a container are summed separately rather than netted into one number.
- Missing prices are surfaced, never guessed. An asset with no known price keeps its raw quantity shown and is flagged, instead of being dropped or silently valued at a default rate.
A price snapshot says “asset X was worth Y (in asset Z) on date D”. It comes either from an on-device fetch against a public API (AlphaVantage today) or from manual entry, which is a first-class path, not a fallback, because some assets will never have public price data. Fetching is manual and per-asset for 2 reasons: the AlphaVantage free tier allows only 25 requests a day, and since moopro was designed to be a privacy-friendly app, it should never perform API requests without the end user being aware of it.
Because this lets you split a change in investment value into two causes, Moopro can answer “why did my portfolio change?”:
flowchart LR
D["Change in value<br/>between two dates"] --> Q["Quantity-driven<br/>you bought or sold"]
D --> P["Price-driven<br/>the market moved"]Data model
Entities
Here is a sumary of the data classes moopro relies on:
erDiagram
ASSET {
u64 id
enum kind "fiat stock etf crypto realEstateBond other"
string symbol
string name
string alphaVantageSymbol "nullable"
string displaySymbol "nullable"
}
CONTAINER {
u64 id
string name
enum containerType "holder or budget"
u64 parentId "budgets nest"
string icon "nullable"
}
TRANSACTION {
u64 id
datetime postedAt
date effectiveDate
enum kind "income expense holderTransfer budgetTransfer trade"
string note
int manualOrderRank
}
LEG {
u64 containerId
u64 assetId
decimal quantity
decimal balanceAfter "cache"
}
PRICE_SNAPSHOT {
u64 assetId
date date
decimal price
u64 currencyAssetId
enum source "fetched or manual"
}
RECURRING_TEMPLATE {
u64 id
enum kind
RecurrenceRule rule
date lastGeneratedOccurrenceDate
bool active
}
SETTING {
u64 id "fixed per key"
string value
}
CONTAINER ||--o{ CONTAINER : "parent of (budgets)"
TRANSACTION ||--|{ LEG : "has 2 or 4"
LEG }o--|| CONTAINER : "moves in or out of"
LEG }o--|| ASSET : "of"
PRICE_SNAPSHOT }o--|| ASSET : "prices"
RECURRING_TEMPLATE ||--o{ TRANSACTION : "may generate"Notable details:
- Each leg is stored inline in its transaction:
legOut/legInfor the holder side (or the only side of abudgetTransfer), plusbudgetLegOut/budgetLegInforincome,expenseandtrade. - Ids are random 64-bit values rendered as 16-character lowercase hex. The zero padding is load-bearing: the id is part of the encryption’s authenticated data, so any layer that strips leading zeros would break decryption for roughly 1 in 16 records. This caused a real multi-device bug once.
- Settings are user settings synced accross devices, also end-to-end encrypted. They use fixed, well-known ids (one per setting key) instead of random ones, so every device upserts the same record rather than each creating its own.
balanceAfteron a leg is a cache of the running balance right after that transaction. It is never authoritative.- The model is generic on purpose. Investments were not bolted on as a
separate subsystem: adding stocks or crypto only means adding assets of a new
kind, with no schema or data migration.
The unit of storage is the record
Every entity above is serialized to JSON and encrypted independently, as one
vault record, with one of these routing tags: asset, container,
transaction, price_snapshot, setting, recurring_transaction_template.
One transaction is one record. That keeps conflicts small (see Sync and conflicts): a rejected push loses at most one entity.
Fast balance computation without replaying full history
Recomputing everything from first transaction on each edit does not scale, so the device keeps derived caches. None of them are authoritative; all are rebuildable from the transaction log.
flowchart LR
Log[("Transaction log<br/>(synced, encrypted)")]
CP["Monthly balance checkpoints<br/>(local only)"]
BA["Per-transaction balanceAfter<br/>(travels inside the record)"]
PS["Price snapshots"]
SS["Step series<br/>(in memory)"]
Chart["Charts / net worth / forecast"]
Log -->|"replay"| CP
Log -->|"replay"| BA
BA --> SS
PS --> SS
SS -->|"binary search<br/>at any date"| Chart- Checkpoints (per container, asset and month) make
currentBalancecheap. Editing a transaction on day D only invalidates checkpoints from D forward, for just the pairs it touched. balanceAfterlets historical balances be read without a replay. When an earlier transaction is edited, the later ones touching the same pair are re-encrypted and re-pushed so their cached value stays right.- Quantity and price are step functions: each changes only at a discrete event (a transaction, a price entry) and is flat in between. A chart reads each sorted series once and answers “value on day D” by binary search, so daily resolution costs essentially the same as monthly.
End-to-end encryption
Threat model
The server operator, a compromised backend process, and a stolen database file must not be able to read financial data and must not be able to forge transactions. The server is trusted only to authenticate users, store opaque bytes, and route and version records correctly. It is not trusted with plaintext, names, amounts, tickers or record contents.
What E2EE does not cover: a compromised or unlocked device, a weak master password, a user who reuses it as the account password, and a malicious server replaying old data (see Security properties and limits for tradeoff information).
The key hierarchy
Two keys, deliberately separate:
- DEK (Data Encryption Key): a random 256-bit key, generated once at signup and never changed. It encrypts every record.
- KEK (Key-Encryption Key): derived from the master password with Argon2id. It encrypts only the DEK.
flowchart TB
PW["Master password<br/>(never leaves the device)"]
SALT["kdf_salt + kdf_params<br/>(not secret)"]
KEK["KEK<br/>256-bit"]
WRAP["wrapped_dek<br/>AES-256-GCM(KEK, DEK)"]
DEK["DEK<br/>random 256-bit"]
R1["Record 1 ciphertext"]
R2["Record 2 ciphertext"]
RN["Record N ciphertext"]
PW -->|Argon2id| KEK
SALT -->|Argon2id| KEK
KEK -->|wraps| WRAP
DEK -->|"is wrapped into"| WRAP
DEK -->|"AES-256-GCM, per record"| R1
DEK --> R2
DEK --> RNArgon2id defaults are memory-hard: 64 MiB, 3 iterations, 4 lanes. The exact parameters are stored per user so they can be strengthened later without breaking existing accounts.
Why two layers instead of encrypting records straight from the password? Changing the password becomes cheap and safe. You derive a new KEK, re-wrap the same DEK, and upload the new wrapped key. No record is re-encrypted.
Record encryption
nonce = random 96 bits, fresh for every encryption
ciphertext = AES-256-GCM(key = DEK, nonce, plaintext = JSON, aad = "<recordId> <type>")AES-GCM is authenticated: tampering is detected, not silently decrypted to garbage. The additional authenticated data binds each ciphertext to its record id and type tag, so the server cannot swap ciphertext between records or relabel a record’s type without the client noticing (wrapping the DEK also uses GCM, avoiding the unauthenticated-mode key wrapping)
What the server can and cannot see
flowchart LR
subgraph Visible["Visible to the server"]
v1["random 64-bit record id"]
v2["type tag (~10 coarse values)"]
v3["version number + updated_at"]
v4["deleted flag"]
v5["ciphertext size & timing"]
v6["wrapped_dek, kdf_salt, kdf_params"]
end
subgraph Hidden["Inside the ciphertext (hidden)"]
h1["amounts and quantities"]
h2["dates"]
h3["names, notes, tags"]
h4["tickers and asset kinds"]
h5["which container a leg touches"]
h6["settings incl. API keys"]
endThe type tag tells the server “this is one of about ten known record shapes”,
nothing about content. It is needed so a client can fetch or replace caches by
type without decrypting everything first. Record counts, sizes and activity
timing are inherently visible, hiding them (padding, dummy traffic) is out of scope.
Life of a write
sequenceDiagram
participant U as You
participant D as Device (DEK in memory)
participant L as Local ciphertext store
participant S as Server
U->>D: Add transaction
D->>D: Validate, update plaintext cache and balances
D->>D: Serialize to JSON, encrypt with DEK (fresh nonce, AAD = id and type)
D->>L: Save ciphertext, mark dirty
D->>S: Push (id, type, ciphertext, nonce, baseVersion)
alt baseVersion matches
S-->>D: Accepted, new version assigned
D->>L: Mark clean
else stale baseVersion
S-->>D: 409 conflict, nothing applied
D->>L: Flag record as conflicted (visible in UI)
D->>S: Pull latest, reconcile
endWhat a record looks like on the wire
Every push and pull moves the same small envelope. The server stores it without ever looking inside the encrypted part.
| Field | Who can read it | Meaning |
|---|---|---|
id | Server | 16-character hex id, chosen by the client |
type | Server | Coarse routing tag (transaction, container, …) |
ciphertext | Nobody but you | The encrypted JSON, with its 16-byte authentication tag appended to the end as one blob |
nonce | Server (not secret) | The 96-bit value used for this encryption, sent separately |
baseVersion | Server | The version the client last saw for this id, or empty for a record it believes was never synced |
version, updated_at | Server | Assigned by the server on write, returned to clients |
deleted | Server | Soft-delete flag; a deletion is an ordinary update with a placeholder payload |
How the pieces behave:
- The server never interprets the ciphertext. To it, the blob is just bytes with a size limit. The “ciphertext plus tag in one blob” layout is a client convention that every Flutter target (mobile, web, Linux, desktop) shares, so a record written on one device decrypts on all of them.
- The nonce travels beside the ciphertext. It is not secret, but it must be unique per encryption, so it is regenerated randomly every time a record is re-encrypted.
- The id is also an input to the encryption. Because it is bound into the authenticated data, the server must hand back exactly the id string it was given. A server or layer that reformatted it (for instance dropping leading zeros) would make the record undecryptable.
- Pushes are batches that succeed or fail as a whole. If any item is stale, the server answers 409 with the list of conflicting ids and their current versions, and applies none of the batch.
- Pulls are cursor-based. A device asks for everything newer than the highest version it has seen; a first sync starts from zero. A tiny “what is the latest version?” request lets a device check cheaply whether a full pull is needed.
- Attachments need no special case. A receipt photo would simply be a record whose ciphertext is the encrypted image bytes.
Sync and conflicts
Each record carries a server-assigned monotonic version. A device remembers the highest version it has pulled and asks for everything newer. A cheap “latest version” probe is polled to learn whether a real pull is worth doing. Deletes are soft (tombstones that sync like any record).
The server is the single source of truth, and a stale push is rejected, never
silently overwritten. Every upsert states the baseVersion the client last
saw. If any item in a batch is out of date, the whole batch is rejected with
HTTP 409 and nothing is applied. The client must pull and reconcile.
This is intentionally not a CRDT or automatic merge: a 409 means “ask the user”, never “the server merged both edits”. That is acceptable because:
- Realistically one person (or one household) edits their own data.
- Each entity is its own record, so a conflict loses at most one pending edit.
On the client, a conflict is made visible: abandoning a push after a 409
sets a local conflictedAt flag that survives the immediate re-pull, because in
a finance app the user must be able to tell “saved on the server” from “silently
discarded”.
Statement import
Statement import parses bank/broker PDFs, CSVs and spreadsheets entirely on the device with per-institution heuristics (no LLM in the parsing path). Parsed rows become staged candidates in memory; the user reviews and assign holders, budgets and assets, and nothing is committed until user accepts.
Automated unlock, offline vaults, multiple vaults
Automated unlock is opt-in. By default the DEK exists only in memory, so each session needs the master password. If you tick “Save master key on this device”, the DEK goes into the OS secure store (Keychain, Keystore, libsecret) and, on platforms that support it, is gated by a biometric or device PIN. The opt-in is per vault, revocable in Settings, and never done silently. On Linux and web there is no real interactive gate, so the app says so plainly instead of implying a prompt that never appears.
Offline-only vaults use no server at all. The same four values the server
would normally hold (kdf_salt, kdf_params, wrapped_dek, wrap_nonce) are
stored on the device. That is no weaker than before: wrapped_dek is itself
ciphertext, and the salt and params are not secret by design, so an attacker with
the disk still needs the master password.
An offline vault can later be attached to a new server account. It is the same operation as a password change: re-wrap the already-unlocked DEK under the account’s password, upload it, push every local record, then delete the local key material. Attaching to an account that already has a vault is refused rather than trying to reconcile two independently encrypted vaults.
Several vaults can coexist on one device. This is useful for, say, a personal online account, a household one, and a private offline scratch vault. Each vault is a sealed compartment:
flowchart TB
REG[("Vault registry (unencrypted)<br/>id, label, online/offline, email")]
subgraph V1["Vault A: online account"]
A1[("Own database<br/>ciphertext only")]
A2["Own cached key<br/>(only if opted in)"]
end
subgraph V2["Vault B: online account"]
B1[("Own database")]
B2["Own cached key"]
end
subgraph V3["Vault C: offline only"]
C1[("Own database")]
C2[("Own key material<br/>wrapped_dek, salt, params")]
C3["Own cached key"]
end
REG --- V1
REG --- V2
REG --- V3- Isolation. Nothing is shared between vaults: separate database, separate key material, separate opt-in key cache. Unlocking one can never apply another vault’s key, and deleting one revokes exactly its own cached key.
- The registry is only a list. It records which vaults exist so the app can show a picker. It holds no keys or data, which is why it can stay unencrypted, and the server never sees it.
- One online account is always one vault. The server keeps a single wrapped key per account, so signing into the same account again on the same device always lands in the same local vault (matched by email), never a second independent one. Several vaults per account would need the server to hold several data keys per user, a much larger protocol change I have not made.
- Leaving is not logging out. Switching vaults locks the current one (drops the key and the decrypted cache from memory) but keeps the account session. Opening the picker releases the current vault, so every vault listed there can be deleted safely.
- Deleting a vault differs by kind. For an online vault it only removes the local copy; the data is still on the server and downloads again on the next sign-in. For an offline vault it is permanent, because no other copy exists.
- Never a dead end. Every screen before a vault is open has a way back to the picker, and “Continue offline” checks for existing vaults first, so you are never dropped into creating a new offline vault while an existing one is hidden behind it.
Backup
The problem it solves
If the server is lost entirely, your data is gone: the local copy is ciphertext, and for an online account the key material (salt, wrapped key) lives only on the server. Copying the local ciphertext would therefore be useless. A real backup has to stand on its own.
How it works
While the vault is unlocked, the app takes the decrypted data and re-encrypts it under a scheme that depends on nothing server-issued:
flowchart LR
V["Unlocked vault<br/>(decrypted data in memory)"] --> P["One JSON document<br/>schema version, export time,<br/>list of entities"]
P -->|"OpenPGP symmetric encryption<br/>key from the master password"| F["ASCII-armored .asc file"]
F --> G["Decryptable with plain gpg,<br/>no Moopro required"]
F -->|"restore"| E["Empty vault"]Format
It’s using ordinary password-only OpenPGP, so
gpg --decrypt opens it even if Moopro no longer exists. I chose that over
inventing a custom format so your backup outlives the app.
Contents
Every asset, container, transaction, price snapshot and similar entity, each with its original id and its normal serialized form. The two reserved sentinel containers are left out, since they are recreated on every unlock and are not user data.
Password
The master password as it was when backup was produced. If the master password is changed later, old backups still need the old one. A separate backup-only passphrase is a possible future feature
Restore
Since backups contain the full data, restoring is expected against an empty vault. If the vault already has real data, the restore is refused and nothing changes. This follows the project’s rule: ask the user to reconcile, never silently merge. Merging into a non-empty vault is a possible future feature.
Order and ids are preserved
Entities are written assets and containers first, then the transactions and prices that reference them, each with its original id, so every cross-reference resolves.
The master password
What it is and what it protects
The master password is the only secret that can unlock your data. It is fed to Argon2id to produce the KEK, which unwraps the DEK, which decrypts the records. It is never sent anywhere and never stored.
flowchart LR
A["Master password"] -->|"Argon2id + salt"| B["KEK"]
B -->|"AES-GCM unwrap"| C["DEK in memory"]
C -->|"AES-GCM decrypt"| D["Records, rebuilt into<br/>in-memory plaintext cache"]
B -.->|"wrong password: auth tag fails,<br/>nothing is decrypted"| X(["Rejected"])A wrong password is detected cleanly: the unwrap’s authentication tag fails, so there is no “garbage data” state.
If you forget it, the data is gone
There is no reset, no server-side escrow, no backdoor. That follows directly from zero knowledge: the server cannot help because it has nothing that can decrypt. This is the price of the guarantee, and also why some end to end encrypted products like MEGA lets users download a recovery key (a second wrapping of the DEK under a random key shown once at setup).
Strength matters more than usual
Anyone who obtains the stored wrapped_dek and salt, for example from a database
leak, can try passwords offline, with no rate limit. Argon2id’s memory-hard
cost slows each guess, but a weak password is still the weakest link in the
system
Master password vs. account password
For an online vault there are two secrets that are independent at the protocol level: account password is only used to authenticate a user, and master password is only used to decrypt the data, similarly to some end to end encrypted products like Proton for example.
Maximum security holds fully only when the master password is different from the account password. Offline-only vaults have no account password at all, so this concern does not apply to them.
Changing the password
Thanks to the DEK/KEK split, a change derives a new KEK, re-wraps the same DEK and uploads the new wrapped key. No record is touched. Existing backups keep needing the password they were exported with.
Where data lives on a device
The device is trusted more than the server, but an audit showed the on-device
database was once readable in plaintext with the sqlite3 CLI. So plaintext is
now held only in memory:
flowchart TB
subgraph Disk["On disk (persistent)"]
direction TB
LV[("LocalVaultRecords<br/>ciphertext + nonce")]
SS[("Sync cursor, version high-water marks")]
KM[("Key material for offline vaults<br/>(wrapped_dek, salt, params)")]
REG[("Vault registry<br/>(unencrypted labels only)")]
SEC[("OS secure storage<br/>DEK only if you opted in")]
end
subgraph Mem["In memory only (gone on lock or exit)"]
direction TB
DEKm["DEK"]
DC[("Decrypted domain cache<br/>assets, containers, transactions,<br/>prices, checkpoints")]
end
LV -->|"decrypt on unlock"| DC
DEKm --> DC- On unlock, the in-memory cache is rebuilt from scratch by decrypting every stored record; on lock, the key is dropped and the cache is disposed, so decrypted contents leave RAM rather than just the key.
- That cache never needs migrations, since it is never persisted.
- A rollback high-water mark records the highest version seen per record id, to spot a server replaying older data.
Security properties and limits
What you get
- The server holds only ciphertext and a wrapped key; no database leak reveals amounts, names, tickers or notes.
- Authenticated encryption everywhere (tampering and ciphertext-swapping are detected).
- The data key never leaves the device, and never touches disk unless you opt in.
- The backend never learns which assets or currencies you hold, because price fetches go straight from the device to public APIs.
- Statement files are parsed on the device and never uploaded in the clear.
- A stale write cannot silently overwrite newer data.
Known limits, stated plainly
| Limit | Impact | Status |
|---|---|---|
| Login password is sent to the server | If reused as master password, the server can decrypt | In my todo list: single-password HKDF/OPAQUE design |
| Weak master password | Offline brute force of a leaked wrapped_dek | Only non-empty is enforced today |
| No recovery path | Forgotten master password means permanent data loss | Recovery key planned in my todo list |
| Rollback is not cryptographically enforced | The AAD binds id and type but not the version (the client encrypts before the server assigns it), so a malicious server could replay an older valid ciphertext of a record | Partly mitigated by the client’s per-record high-water mark, which flags a lower version for a record already seen |
| Dropped records / fresh-device rollback | A server that omits records, or serves stale data to a device with no history, is not detected | An encrypted manifest of record heads is planned in my todo list |
| No auto-lock | An unlocked, unattended device exposes everything | Planned |
| Metadata leaks | Record counts, sizes and timing are visible | Accepted |
| Local unlock on Linux/web | The cached key has no biometric or PIN gate there | Accepted; UI says so |
| Compromised or unlocked device | Out of scope for E2EE | Inherent |
The server can still refuse service, delete data or withhold records; E2EE protects confidentiality and detects tampering, not availability. That is one of the reasons the offline backup exists.
Comparison with MEGA
MEGA is the best-known consumer product with a similar promise (user-controlled keys, the provider cannot read your files), and it publishes a security whitepaper that openly lists its own weaknesses. I used it as inspiration to build moopro and to learn about end to end encryption. The points below are the ones recorded in my design; for MEGA’s side, the whitepaper is the authority.
| Topic | MEGA | Moopro |
|---|---|---|
| Core promise | Provider cannot read user data | Same |
| Key wrapping | Originally used unauthenticated AES-ECB, which enabled an “RSA oracle” attack (decrypt-on-repeated-login), patched in June 2022 | AES-256-GCM from the start for both the data key and records, so tampering is detected and that class of attack is not possible |
| One password or two | Derives separate keys from one password, so the login secret and the encryption key are different values | Two independent passwords today (account and master). Safe if they differ, but if reused the server can decrypt |
| Rollback / freshness | Admitted as a theoretical limitation: a malicious server can replay old data | Same structural limit. The authenticated data binds id and type but not the version, since the client encrypts before the server assigns one. Partly mitigated by a client-side per-record high-water mark |
| Stated openly | Whitepaper has a “theoretical vulnerabilities” section | Limits are written above |
What I took from the comparison:
- Authenticated encryption everywhere is non-negotiable, and I have it.
- One password with two derived keys is the design I would move to. Our
documented proposal splits one Argon2id output into an
auth_key(the only thing sent to the server) and the KEK, which removes the password-reuse trap. It adds no cryptographic strength for users who already pick two strong passwords, but it makes the safe setup the only one. - Rollback protection is partial in both systems and cannot be fully solved by the backend alone. Our planned next step is an encrypted manifest of record heads so that dropped or reverted records can be detected too.
Differences in scope matter as well: MEGA is a file-sharing product with cross-user sharing, while Moopro is a single-person (or household) vault with no sharing between accounts, which removes a whole class of key-exchange problems.
Tradeoffs I made
Each of these was a deliberate choice; none is an oversight.
| Decision | What I gain | What I give up |
|---|---|---|
| Zero-knowledge E2EE | A database leak or hostile operator exposes no financial data | No password reset, no server-side search or analytics, no server-side features that need plaintext |
| All computation on the device | The server stays a dumb blob store; no key exposure | Every client recomputes balances and charts itself; heavier first load; derived caches are needed to stay fast |
| Per-record encryption (not one big blob) | Small conflicts, cheap incremental sync, one lost edit never loses a batch | Server sees record count, size and timing; many small ciphertexts |
| DEK wrapped by a password-derived KEK | Password change re-wraps one key instead of re-encrypting everything | The DEK is permanent for the account’s life; rotating it would mean re-encrypting all records |
| Argon2id with memory-hard params | Strong resistance to offline guessing | Slower unlock, especially on weak devices; params must be tuned and eventually upgraded |
| Reject stale pushes (409), no auto-merge | Server stays the single source of truth; no silent data loss; far simpler than CRDTs | A conflicting edit needs a human decision; fine for one person or household, awkward for heavy concurrent editing |
| Decrypted data only in memory | Disk theft yields only ciphertext | Whole cache rebuilt on every unlock; slower cold start |
| Opt-in key caching | Convenience without a silent security downgrade | More friction by default; on Linux and web the cached key has no interactive gate |
| Server may cache, but only as ciphertext | Allows precomputed chart data later without breaking zero knowledge | Not built yet; every device currently recomputes locally |
| Price fetches on-device, manual by default | Backend never learns your holdings | Subject to public API limits (25/day on the free tier), so no refresh-everything button; manual entry is first class |
| OCR / parsing on-device | Statements never leave unencrypted | Parsers are hand-written per institution and grow one at a time |
| Holders and budgets are two hierarchies over one pile of value | Real accounts and planning stay separate yet provably consistent (Σ holders = Σ budgets) | More rigid: every income, expense and trade needs both a holder and a budget leg; no direct holder-to-budget transfer |
| A single generic multi-asset container | One concept for bank, broker and wallet; investments need no schema change | A holder can hold many assets, so “balance” is always per asset and valuation needs prices |
trade takes exactly one budget | Keeps the invariant simple | It does not model which budget truly funded a split purchase |
| Missing price means “unknown”, not a guess | Numbers are never fabricated | Totals can be incomplete until a price is entered |
| Recurring items require confirmation; trades excluded | Never invents transactions or price history | Slightly more manual than a fully automatic scheduler |
| Backup encrypted with the master password, as OpenPGP | Anyone with gpg can recover without Moopro; no new crypto format | Old backups need the old password after a change; no separate backup passphrase yet; restore only into an empty vault |
| Offline-only vault option | Usable with no server, ever; attachable later | Attach works only against a brand-new account; no merging two vaults |
| One online account = one vault | Matches the server’s single wrapped-key row | No multiple independent vaults per account |
| Soft deletes (tombstones) | Deletions sync like any other change | Deleted records leave a (tiny) trace server-side |
| Self-hosted, single-user assumptions | Simpler concurrency and attach logic (a narrow race on key-material upload is accepted) | Not designed for large teams or hostile co-tenants |
| Prefer built-in widgets and well-known packages | Dismiss gestures, focus, accessibility for free; consistent look | Less freedom than hand-rolled UI |