When I started building Dogood, I wanted a promise precise enough that anyone could check it: for each feature, what exactly leaves the device, who receives it, what they keep, and for how long.

Dogood is a journal that lives in the browser. You write a few lines a day, it brings old entries back on the same date each year, files them into the chapters of your life and lays the whole thing out as a book you can print. There is no account. The journal is kept in IndexedDB on the device, and can be encrypted there with a passphrase.

That architecture does most of the privacy work by itself, but not all of it. A product still needs to be paid for, to know roughly whether anyone uses it, to fix what breaks, and sometimes to move data between devices. Each of those needs sends something off the device, and that is usually where privacy promises stop being true.

So each of them gets written down. This article is that list for Dogood today, with the method behind it and the places where it falls short. Two parts get far more room than the rest, because their choices need the most explanation and their code is worth showing: how the journal is encrypted in the browser, and how it syncs through the writer’s own cloud drive. Each of them ends with what I would change.

The rule the list protects

The rule fits on one line:

The journal never leaves the device unless the writer sends it somewhere they chose.

“Somewhere they chose” means a backup file they download, a folder they pick, or their own cloud drive. It never means a Dogood server.

Dogood’s API exists, on Cloudflare Workers with a D1 database, and it is deliberately not a journal database. It handles payments, counts, feedback and a few small features described below, and it never receives a word written in a journal.

It is also optional in the code itself, not only in the settings. A build of Dogood without the API’s address makes no API request at all. Every call site checks for it first. You can delete the Worker and still write, search, read last year’s entries and print your book.

One entry per thing that leaves the device

The method is simple on purpose. Every flow that sends something off the device, or keeps something anywhere other than the journal, gets an entry in a ledger. One entry per flow: a feature that sends two different things gets two entries.

An entry answers the same questions every time. Here is a real one:

flow: usage counts
what_leaves: an event name ("entry_created"), a few allowlisted properties,
  a timestamp, a random id made on this device, a session id
to: api.dogood.day (Cloudflare Worker + D1)
when: batched, when the app is hidden, every 5 minutes or every 20 events
default: off
turned_on_by: the writer, at onboarding or in Your Dogood → Usage sharing
kept: one row per event
for_how_long: 396 days, then deleted by an hourly job
a_leak_would_show: that some device used some features at some times
never_in_it: words, titles, photos, moods, searches, name, email
the_writer_sees: the dialog listing what a count looks like and what is never sent
proved_by: an allowlist test on the Worker, a browser test on the dialog and the batching

Four of those fields do most of the work.

what_leaves is written as data. “Anonymous analytics” only says what I mean to do. “An event name, a timestamp and a random number made on this device” says what is actually sent, and anyone can check it against the browser’s network panel. Writing it as data also stops me from using the wrong word: that random number makes the counts pseudonymous, not anonymous, and the dialog says so.

a_leak_would_show is the field I write first. I assume every server I run will one day be read by somebody who should not read it. If the answer to “what would they learn?” is “who this person is and what they wrote”, the feature does not ship in that form.

the_writer_sees makes the interface part of the contract. If the ledger says a count never contains a mood, the dialog says so in those words, and the two can be compared. If they ever say different things, one of them has to be fixed.

proved_by keeps the ledger from becoming a document nobody reads. Each entry has a test, so the next change cannot break it without me noticing, even a change I make in a hurry.

Three questions before an entry exists

Before writing an entry, three questions, always in this order:

  1. Can it work without leaving the device? Search, the “on this day” pages, chapters, the yearly recap, the book layout with its page numbers and bleed: all of it runs in the browser on data that is already there. Most features end here, with no entry at all.
  2. If not, can it work with less? A writing buddy needs to know whether a friend wrote today. It does not need to know what they wrote.
  3. Can the writer see it, and say no? Anything optional is off until the writer turns it on, and the place where it is turned on says what it sends.

I ask them in this order because asking “can the writer opt out?” first leads to consent dialogs in front of data you should not be collecting at all.

On the left, this browser holds entries, photos, chapters, goals, habits and the key. On the right, the few things that go out: to api.dogood.day, to dictation, to Creem when buying, and to the writer's own cloud drive when Sync is on.
What stays on the device and what leaves it. Each line on the right has an entry in the ledger.

The journal stays in the browser, sealed if the writer wants

Nothing in this section has a ledger entry, because none of it leaves the device unless the writer exports it. It still takes the most explaining. “Encrypted on the device” covers a dozen decisions, and each one changes what the promise means.

Where it lives

Entries, chapters, goals, habits and photos are in IndexedDB, in the browser that wrote them. Photos are resized on the device to 2048 pixels before they are stored, which keeps them at print quality and usually under 1.5 MB.

Dogood asks the browser to keep its data from automatic clean-up (persistent storage) at the end of onboarding and on later visits. The Storage panel shows whether that was granted, because a browser short of space may otherwise delete data from sites it thinks you stopped using.

What encryption in a browser protects, and what it cannot

Encryption in a web app protects data while it is stored, not while your code is using it. Writing down what that covers comes before any code, because it decides everything else.

It protects against:

  • someone who picks up a locked device, or copies the browser’s storage from it;
  • copies that leave the device: backup files, cloud sync, a profile synced by the browser;
  • other people using the same computer and browser profile.

It does not protect against:

  • code running on your origin: a cross-site scripting bug, a compromised dependency or build, a malicious deployment. That code runs with your app’s rights and can read what the person types or sees once the data is unlocked;
  • browser extensions with access to the page;
  • an unlocked device in someone else’s hands;
  • malware on the machine.

The second list is the reason the interface has to say exactly what the encryption does. “Your entries are encrypted on this device, so nobody else can read them, not even us” is accurate. Saying “military-grade security” would not be accurate. The first item on that list is also why Dogood’s site has a strict Content Security Policy and keeps its admin on another host, as described in “The site around the app” below.

How Dogood makes the key today, and where it keeps it

Encryption is optional. The writer chooses a passphrase of at least ten characters, and Dogood suggests a short sentence, which is easier to remember and harder to guess than a password with symbols.

From that passphrase and a random salt, Dogood derives a key with PBKDF2-SHA-256 at 310,000 iterations. That key encrypts entries, photos, chapters, goals and habits with AES-256-GCM, with a fresh random IV for every write, and it stays in memory only while the journal is open.

The salt and the derivation parameters are stored unencrypted beside the data, with a small verifier: a known value encrypted with the key. If it decrypts, the passphrase is right. A new device uses the same parameters and the same verifier to check a passphrase before it touches any real data.

The verifier has a cost. It works offline for an attacker too: anyone holding a copy of the data can test passphrases against it as fast as their hardware allows. That is true of every passphrase scheme, and it is why the derivation has to be slow and the passphrase long.

PBKDF2 is the slow function WebCrypto offers, and it is fine if you give it enough work. Its weakness is that graphics cards compute it very fast, so someone with the salt and a copy of the data can try passphrases at a rate no phone can match. OWASP’s current guidance for PBKDF2-HMAC-SHA256 is 600,000 iterations. Dogood’s 310,000 is the figure from the previous edition of that guidance, and it is on my list below.

One more fact about today’s design: the key derived from the passphrase is the key that encrypts everything. That was my first version, and it works. Its costs show up later, and the fix is also below.

Here are two details about holding a key in a browser.

importKey(..., extractable: false, ...) gives you a CryptoKey that JavaScript can use but not read. Script on the page can still encrypt and decrypt with it while it exists, so this is no defence against XSS during a session. What it prevents is someone copying the key out and using it somewhere else later.

You can also store a non-extractable CryptoKey in IndexedDB. Scripts cannot export it, but the browser writes the key material into its profile on disk, so someone who copies the profile copies the key. Do not count it as protection against a stolen device.

The rule that follows: keep the key in memory only, as a non-extractable key, for as long as the journal is unlocked, and drop it on lock.

What stays readable, on purpose

The calendar and the Lifetime view need to show which days were written, even while the journal is locked. Encrypting everything would make the locked screen a blank page. So each day’s date, mood and word count stay unencrypted, and the protection dialog says it in one line: “Left readable, for the calendar and Lifetime: each day’s date, mood and word count.”

Dogood's Protect this journal window: what is encrypted, what is left readable, the passphrase fields and a checkbox saying there is no recovery key.
Dogood's "Protect this journal" window: what gets encrypted, what stays readable and why, and the no-recovery-key checkbox.

A list like that has to be checked against what is really stored, because new bits of metadata get added over time without anyone noticing. Timestamps to the millisecond reveal when someone writes. Photo sizes and dimensions travel with the photo record. A preference such as “start my story on my birthday” is a date of birth. Names typed into a social feature end up in localStorage. When I audited Dogood’s storage for this article, the real list was longer than the one-line promise.

A PIN is a screen lock, and the settings say so

A PIN or Face ID can open the journal on one device. Each wraps a copy of the key on that device only.

People want to open their journal with six digits instead of a sentence. That is a reasonable wish. But a PIN on the web is only a convenience lock: six digits cannot keep a key safe from someone who has copied it.

The numbers are simple. Six digits are a million possibilities; eight are a hundred million. An attempt counter (“five wrong tries and the PIN stops working”) only works against someone typing in your interface. Someone who copies the storage reads the wrapped key, the salt and the counter, and guesses offline, where your counter does not exist.

Slowing each guess helps less than it seems. Dogood derives the PIN key with a million PBKDF2 iterations, which is as slow as a phone allows at unlock time. Public benchmarks put a single high-end graphics card at several billion PBKDF2-SHA256 iterations per second. A million PINs at a million iterations each is 10¹² iterations, which puts every six-digit PIN within reach in minutes and every eight-digit PIN in hours.

There is no client-only fix for that, because the web gives an app no hardware-backed secret to mix into a PIN. The options are:

  • Treat the PIN as a screen lock, and say so where it is set. Dogood’s settings put it this way: “A PIN is a screen lock: it stops the people around you, not someone who copies this browser’s data, who could try every PIN. Face ID or a fingerprint is stronger, and your passphrase stays the real key: keep it long.”
  • Only let the PIN wrap a copy of the key that is useless on its own, for example one that also needs a passkey, if you can require both.
  • Add a server that rate-limits PIN attempts and holds half of the secret. That is a real design, and it brings back the server a local-first app was built to avoid.
  • Prefer passkeys where the device supports them.

Face ID and fingerprints: a passkey with the PRF extension

WebAuthn’s PRF extension is the closest thing the web has to a hardware-backed key, and it is what Dogood uses for Face ID and fingerprints. When the person authenticates with a passkey (Face ID, a fingerprint, Windows Hello, a security key), the authenticator returns a secret derived from a salt the app chooses. The secret never exists on disk in a form an attacker can brute-force, so it makes a strong key-encryption key.

// Registration: ask for PRF, then check that the authenticator really supports it.
const cred = (await navigator.credentials.create({
  publicKey: {
    challenge: crypto.getRandomValues(new Uint8Array(32)),
    rp: { name: "Your app" },
    user: { id: crypto.getRandomValues(new Uint8Array(16)), name: "journal", displayName: "Journal" },
    pubKeyCredParams: [{ type: "public-key", alg: -7 }, { type: "public-key", alg: -257 }],
    authenticatorSelection: { residentKey: "required", userVerification: "required" },
    extensions: { prf: {} },
  },
})) as PublicKeyCredential;
if (!cred.getClientExtensionResults().prf?.enabled) throw new Error("This device cannot unlock with a passkey");

// Unlocking: evaluate the PRF with a stored salt, then turn the output into a KEK.
const assertion = (await navigator.credentials.get({
  publicKey: {
    challenge: crypto.getRandomValues(new Uint8Array(32)),
    allowCredentials: [{ type: "public-key", id: credentialId }],
    userVerification: "required",
    extensions: { prf: { eval: { first: prfSalt } } },
  },
})) as PublicKeyCredential;
const secret = assertion.getClientExtensionResults().prf?.results?.first as ArrayBuffer;

const hkdfKey = await crypto.subtle.importKey("raw", secret, "HKDF", false, ["deriveKey"]);
const passkeyKek = await crypto.subtle.deriveKey(
  { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(32), info: new TextEncoder().encode("journal data key v1") },
  hkdfKey,
  { name: "AES-GCM", length: 256 },
  false,
  ["encrypt", "decrypt"],
);

Two lessons from shipping it, with a third under “What I would change”:

  • Support is good but not universal. Recent Chrome, Edge and Safari handle it with platform authenticators; some combinations of browser, password manager and operating system still do not. Keep the passphrase as the way in that always works.
  • Use a distinct HKDF info string per purpose, so the same PRF output can never be reused as a different key by accident.

Locking clears everything from memory

“Lock” is a promise that, from now on, nothing readable remains in the page. Making it true takes more than dropping one key:

  • Drop every key: the main key, any key kept for a background job such as sync, any old key kept during a passphrase change.
  • Drop decrypted caches: lists, settings, anything you decrypted to render.
  • Lock every tab: a BroadcastChannel message is enough. Locking one tab while another stays open surprises people.
  • Lock on idle and when hidden, with delays the person can understand (“after ten minutes without a tap”).

When I audited Dogood for this article, locking cleared the main key in the visible tab, while some secondary keys and decrypted lists stayed in memory until the tab closed. This gap is easy to miss, and a test catches it: lock, then search the page’s memory for any key or decrypted string you can still reach.

No recovery key, and an interface built around that

Dogood keeps no recovery key. If I never hold the key, I cannot recover it. That is on purpose, so the interface has to make it clear to the writer before they ever need it:

  • Ask for agreement in their own words. Dogood’s checkbox reads: “If I forget this passphrase, nobody can open the journal, not even Dogood. I will keep it somewhere safe.”
  • Prompt a backup before encryption starts, and remind people later.
  • Give a second way in on the device (a passkey), so a forgotten passphrase is not the end on the device they use every day, while being clear that the passphrase is still needed elsewhere.

Backups are files the writer owns

A backup is one file with everything in it (pages, photos, habits, goals, the Plus licence), downloaded, shared to a phone’s Files app, or written each day to a folder the writer picks, keeping the last 14. After a few days without a backup, Dogood reminds you once, then leaves you alone for a week.

The cleanest rule for backups and sync: what leaves the device is the same ciphertext that sits on it, plus the public parameters needed to open it (the salt, the iterations, the verifier). A backup is then useless without the passphrase, and restoring it is a copy, with no re-encryption.

Anything stored unencrypted beside the ciphertext (dates, sizes, licence data, ids) leaves with it.

Turning encryption on is a migration

When someone turns encryption on, the unencrypted pages they already have become a risk. Handle it like a database migration:

  • Never pass through an unencrypted state you cannot roll back from. Write the encrypted copy, verify it, then remove the plaintext. Adopting a passphrase set on another device must follow the same rule. Dogood’s first version decrypted everything and then re-encrypted it, which left a window where a crash meant an unencrypted journal; it now re-encrypts without ever writing an unencrypted page, and a browser test watches the local database during the change to prove it.
  • Find the other copies. Earlier backups, a folder of daily backups, exports. Offer to replace them, or at least tell the person they exist.
  • Resume after interruption. Keep a small progress record so a closed tab finishes the job next time instead of leaving data half in each state.

What I would change

If I started Dogood’s encryption again today, four things would be there from the first commit.

A random data key, wrapped once per way of unlocking. Today the passphrase’s key encrypts everything, and that design has costs that show up later:

  • Changing the passphrase re-encrypts everything. Every record, every photo. On a phone with years of data, that is slow, and a crash in the middle needs careful recovery code.
  • Every unlock method holds the master key. A PIN or a passkey that opens the journal has to wrap the one key that encrypts everything, including backups and cloud copies.
  • Nothing can be rotated without touching all the data.

The standard fix costs a few lines. Generate a random data key once. Encrypt data with it. Then wrap that data key with one key-encryption key (KEK) per way of unlocking: one from the passphrase, one from a passkey, one from a PIN.

A random data key encrypts the records. It is wrapped three times: by a key derived from the passphrase, by a key from a passkey's PRF output, and by a key derived from a PIN.
One random data key, wrapped once per way of unlocking. Changing the passphrase rewraps 32 bytes instead of re-encrypting every record.
// Once, when the person turns encryption on.
const dataKey = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]);
const raw = new Uint8Array(await crypto.subtle.exportKey("raw", dataKey));

// One wrapped copy per unlock method, each with its own key-encryption key (KEK).
const wrapped = await seal(raw, passphraseKek, aad("data-key", "passphrase"));
raw.fill(0);

// Day to day, keep only a non-extractable copy in memory.
const working = await crypto.subtle.importKey("raw", unwrapped, "AES-GCM", false, ["encrypt", "decrypt"]);

With this shape, changing the passphrase means unwrapping the data key with the old KEK and wrapping it with the new one. It is atomic and instant, and there is never a moment when half the data is under one key and half under the other. (seal and aad are in the next block.)

A version field and additional data in the envelope. AES-GCM is the right default in the browser: it is authenticated and built into WebCrypto. The details around it are where designs differ, and Dogood’s envelope has neither of these two today.

type Envelope = { v: 1; iv: string; data: string };

const aad = (...parts: string[]) => new TextEncoder().encode(parts.join("\u0000"));

async function seal(value: Uint8Array, key: CryptoKey, context: Uint8Array): Promise<Envelope> {
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const data = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: context }, key, value);
  return { v: 1, iv: b64(iv), data: b64(new Uint8Array(data)) };
}

async function open(box: Envelope, key: CryptoKey, context: Uint8Array): Promise<Uint8Array> {
  if (box.v !== 1) throw new Error(`Unknown envelope version ${box.v}`);
  return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: unb64(box.iv), additionalData: context }, key, unb64(box.data)));
}

// A record is bound to its place: copied under another id, it no longer decrypts.
await seal(bytes, dataKey, aad("entries", entry.id, "v1"));

The habits in that code:

  • A fresh random 12-byte IV for every encryption. Never reuse an IV with the same key; with random IVs, you are safe for far more writes than a personal app will ever make.
  • A version field. You will change something one day (the KDF or the layout). Without a version, you will have to guess which format you are reading.
  • Additional authenticated data. Without it, a ciphertext is valid wherever it is placed: someone with write access to the storage could swap two encrypted records, or replay an old one, and both would decrypt cleanly. Binding each record to its collection and id makes a moved record fail to open.

600,000 iterations, or Argon2id. The derivation I would write now:

async function passphraseKek(passphrase: string, salt: Uint8Array, iterations = 600_000) {
  const material = await crypto.subtle.importKey("raw", new TextEncoder().encode(passphrase.normalize("NFKC")), "PBKDF2", false, ["deriveKey"]);
  return crypto.subtle.deriveKey(
    { name: "PBKDF2", hash: "SHA-256", salt, iterations },
    material,
    { name: "AES-GCM", length: 256 },
    false,
    ["encrypt", "decrypt"],
  );
}
  • Iterations. 600,000, the current OWASP figure. Measure on the slowest phone you support: half a second per unlock is acceptable for a passphrase typed once a session.
  • A random 16-byte salt per journal, stored unencrypted next to the data.
  • Normalise the passphrase (NFKC) so the same characters typed on two keyboards give the same key.
  • A minimum length. Dogood’s ten characters and its suggestion of a short sentence stay.

Argon2id also uses a lot of memory, so graphics cards lose most of the advantage they have with PBKDF2. It is not in WebCrypto, but it runs well in WebAssembly. If you start today and your users may choose weak passphrases, it is worth the extra dependency.

Check PRF support at registration, and stop cleanly if it is missing. That is the prf.enabled line in the registration code above, and it is the lesson from shipping passkeys that I would write first. Without it, a device whose authenticator lacks PRF gets a passkey that can never unlock anything, and the person sees an orphan in their password manager.

None of this makes a web app as hard to break into as a hardware vault, and nobody should claim it does. It does make the journal unreadable without the passphrase in backups and in the cloud, and on the device too, within the limits of a PIN described above. For most people, that is what a private journal means.

Site settings

When the app opens, it reads a small settings document from the API: which cloud drives are offered for sync, what is on sale. It is a GET with no body, no id and no cookie, cached for six hours. It runs in the demo journal too, so I no longer say the demo sends nothing: it sends this request, but nothing about you.

The daily device count

This is the one count that is on by default, so it deserves the most care.

Once per day, the app sends two yes-or-no values: whether this is the device’s first day, and whether Dogood is installed as an app. The Worker adds one to that day’s totals. There is no device id, no per-device row, and the stored table has four columns: the day, the number of devices, new devices and installed ones.

I added it because, with usage sharing off by default, I had no way to know whether anyone opened Dogood at all. It answers one question (“how many devices today?”) and nothing else. It can be turned off in the same Usage sharing dialog, and the change was announced in the app’s privacy policy when it shipped.

Usage sharing

Off unless the writer turns it on, at onboarding or later. The dialog shows what a count looks like and what is never sent, whether sharing is on or off.

Dogood's Usage sharing window: what a count looks like (app_opened, entry_created, view_opened…), what is never sent (your words, titles, photos, moods, searches, who you are), and two switches.
The Usage sharing window says what the ledger entry says, in plain words for the writer.

Events come from an allowlist, and so do their properties; the Worker keeps nothing outside it. Each event carries a random installation id made on the device, so counts can be grouped by device without knowing whose device it is. That makes them pseudonymous, and the dialog says “a random number made on this device groups them, never your name, email or words”. Rows are deleted after 396 days, and turning sharing off erases the id from the device, so turning it back on starts a new one.

Writing buddies

A journal can invite up to ten people to keep each other writing. Each person keeps their own journal and only shares a streak.

Dogood's writing buddies window: five people, who wrote today, streaks and days written, and no text from anyone's journal.
"You see when the other writes, never what they write." Shown here with the demo journal's friends.

For that, the API keeps per person: the first name they chose to show, their streak, how many days they have written, the last day they wrote and when they were last seen. Invitation tokens are stored as SHA-256 hashes. With evening reminders turned on, it also keeps what a push notification needs: the browser’s push endpoint and keys, the hour, the time zone and the language. When someone leaves, these records are deleted.

That is more than “two numbers”, and the ledger entry lists every field. But it never includes a word of anyone’s journal.

Dictation

Dictation (a Dogood Plus feature) records on the device and sends the audio, in small pieces, to the Worker, which passes it to Whisper on Cloudflare Workers AI and returns the text. The recording and the text are not stored. What is stored is the number of seconds dictated per licence per month, because each licence gets 120 minutes a month and the whole service has a monthly cap. The first use asks for agreement, with that explanation.

Paying without an account

Dogood Plus is paid once. There is no account, so the usual design (a user table, a password, a subscription row) does not apply.

The payment happens at Creem, which acts as the merchant. Card details never reach Dogood. After payment, Dogood’s database keeps what it needs to deliver and support the purchase: the buyer’s email, the country, the amount and currency, the item, and a referral code if there was one.

The licence is a token signed by the API with an ECDSA P-256 key and verified on the device with the public key built into the app. It carries a licence id, its origin (a purchase, a gift), the day it was issued and the id of one journal. No name, no email, no device. Because the check is a signature, Plus works offline.

A licence belongs to a journal. A journal has a random 16-character id made on the device. The licence is bound to it, travels in that journal’s backups to any device, and can move to another journal once every 30 days. The app checks its licence with the API every day for the first month (a refund can be requested within 14 days), then every week. If it is offline, or the API does not answer, Plus stays on.

The email carries a link. The link is exchanged for a licence bound to the journal that opens it.

The honest limit: for a purchase made for oneself, the database can join the buyer’s email to a journal id. It never holds anything written in that journal, but the join exists, and the ledger says so. The email itself is erased three years after the purchase, and the privacy policy says so in each of its six languages.

Sync goes through the writer’s own cloud drive

Sync keeps a journal the same on several devices through the writer’s own Google Drive, in a folder only Dogood can see, or their Dropbox or OneDrive app folder. Requests go from the browser to the provider. Dogood’s servers never see these files.

This is the one flow where the journal itself leaves the device, and it goes where the rule allows: somewhere the writer chose.

Why the writer’s own drive

At first, a local-first app is easy. Everything lives on the device, with no account and no database to secure. Then someone opens it on their laptop and asks where their phone’s pages went.

The usual answer is a sync server. Even with end-to-end encryption, that means running the one thing a local-first app was trying to avoid: a place that holds everybody’s data and becomes the obvious target.

Peer-to-peer sync avoids the server but needs both devices online at the same time, or a relay, and a relay is just another server.

There is a third option, and few apps use it. The writer already has a place to keep files. Google Drive, Dropbox and OneDrive all give an app a private folder in the user’s own account. Dogood writes there from the browser, the provider stores it, and my infrastructure never sees a byte.

It fits a certain kind of product, and a journal is one:

  • one person’s data, on a handful of their own devices;
  • minutes are fresh enough: changes arrive when you open the other device, not as you type;
  • modest volume: text, small images, settings;
  • no server-side feature needs the data: no search across users, no notifications computed from content.

It does not fit real-time collaboration, many writers on one document, or large files that change constantly. For those, a CRDT with a relay, or a real backend, is the honest answer.

When the product fits, it helps in a few ways. I store nothing, so a breach of my systems cannot expose a journal. Storage, quotas, backups and account security are the provider’s job, done by people who do nothing else. And the writer can revoke Dogood’s access from their account settings without asking me.

The narrowest folder each provider offers

All three providers have a scope that limits an app to its own folder. Use it. People are right to distrust an app that asks for the whole drive just to store its own files.

Google DriveDropboxOneDrive
FolderappDataFolder, hidden from the userApp folder, visible as Apps › YourAppspecial/approot, visible as Apps › YourApp
Scopedrive.appdataan “App folder” app in the consoleFiles.ReadWrite.AppFolder
Sign-in in a browser appIdentity Services token modelOAuth code + PKCEOAuth code + PKCE
Tokenabout an houra few hoursabout an hour
Renewal without a tapnone for a browser apprefresh tokenrefresh token, 24 hours for a SPA
Refuses a write over a newer filenoyes (rev)yes (If-Match)

Two lines in that table shape the whole design.

Google gives a browser app no silent renewal. With the token model, a token lasts about an hour and getting another one needs a user gesture. So sync on Drive works while the app is open and for an hour after sign-in, then needs a tap. I designed the interface around that instead of fighting it: Dogood syncs by itself while the token lasts, then shows a quiet “Sync” button.

Google Drive cannot refuse a stale write. Dropbox lets you upload “on top of revision X” and rejects the write if the file has changed since. OneDrive honours If-Match with an ETag. Drive has no equivalent for file content. The design has to survive two devices writing the same file at the same moment, and the parts on versions and concurrency below show how.

A small detail worth knowing: the hidden Drive folder still counts against the user’s 15 GB, so a full drive will refuse your writes. Show that error in plain words (“Your Google Drive is full: make room there, then sync again”).

A dozen calls hide the provider

Dogood’s sync engine does not know which cloud it talks to. The contract is short enough to read in full:

interface Cloud {
  id: "google" | "dropbox" | "onedrive";
  authorize(hint?: string | null): Promise<void>;
  hasToken(): boolean;
  revoke(): void;
  list(): Promise<CloudFile[]>;                 // every file in the app's folder, with its version
  readJson<T>(id: string): Promise<T>;
  readPhoto(file: CloudFile): Promise<CloudPhoto>;
  version(id: string): Promise<string | null>;  // null when the file is gone
  createJson(name: string, value: unknown): Promise<CloudFile>;
  updateJson(id: string, value: unknown, version: string): Promise<CloudFile>;
  createPhoto(name: string, data: ArrayBuffer, props: Record<string, string>): Promise<CloudFile>;
  remove(id: string): Promise<void>;
}

version is whatever the provider uses to say “this file changed”: Drive’s version, Dropbox’s rev, OneDrive’s eTag. updateJson takes the version the engine read, so the two providers that can refuse a stale write do.

The errors matter just as much. They are normalised into a few types the engine can act on:

  • AuthRequired: a tap is needed. Stop quietly and nudge.
  • Offline: try again on the next trigger.
  • Changed: another device wrote first. Start the run again from a fresh listing.
  • CloudError: everything else, including quota and rate limits, with a message a person can read.

With that in place, adding Dropbox and OneDrive to Dogood after Drive was mostly a matter of mapping their APIs onto the same calls.

Files follow how the data changes

The two obvious layouts do not work: one file per record means a long listing and thousands of small requests on every sync, and one file for everything means rewriting the whole journal on every keystroke.

Records are grouped by how often they change together:

Dogood's folder in Google Drive: hero-journal.json unencrypted; hero-items.json, one entries file per year, photos and device files sealed.
Dogood's folder for a journal protected with a passphrase. Records are sealed on the device; the meta file stays readable so a new device knows which journal it found.
  • a meta file with what a new device needs before anything else: which journal this is, whether it is encrypted and how to check a passphrase;
  • an items file for the small things: goals, habits, chapters, settings;
  • one file per year of days, so writing today rewrites this year’s file and leaves the other years alone;
  • one file per photo, uploaded once and never rewritten;
  • one small file per device, so each device can list the others (“a phone, Safari, synced 2 minutes ago”).

Inside each records file, every record carries three things:

type RemoteRecord =
  | { rev: number; stamp: string; value: unknown }          // a record
  | { rev: number; stamp: null; deletedAt: string };        // a tombstone

stamp identifies a version. For a day it is the entry’s id plus its last update time. For everything else it is a short hash of the record’s canonical JSON (keys sorted), so two devices that hold the same value agree without talking. rev is a counter that goes up with every change. Both are needed, as the next parts show.

One decision saved a lot of trouble: a day is identified by its date, not by a random id. Dogood keys a page as entry:<space>:<date>. If you open the app on your phone and your laptop on the same morning and both create today’s page, they have different ids but the same key, so they meet in one record instead of becoming two pages for one date.

Sealed on the device, and what the provider still sees

With a passphrase, each records file is sealed on the device with the same key that protects the local journal, and uploaded as ciphertext. If an app encrypts locally but syncs unencrypted, the local encryption protects almost nothing.

Without a passphrase, the journal sits readable in the writer’s own drive, and the Sync window says so: “Anyone who opens your Drive could read your pages. A passphrase seals them before they leave this device.”

Some things cannot be sealed, because a new device needs them before it has the key: the salt and the parameters used to derive the key from the passphrase, plus the verifier. They stay readable in the meta file.

Encryption hides the content, but the provider can still see some things:

  • file names: with one file per year, the provider knows which years hold data;
  • sizes: how much was written in each file, and how big each photo is;
  • timing: when each file changed, which traces writing sessions quite closely when sync runs a few seconds after typing stops;
  • anything stored as file properties: Dogood keeps each photo’s type, size and the date it was added beside the sealed bytes, so those are visible too;
  • the verifier, which lets anyone holding the files test passphrases offline, as described in the encryption part.

Whatever the design leaves visible, the sentence in the interface has to match it. “Your provider sees file names and sizes, never your words” is a promise you can keep. “Never a date” is not, if a year sits in a file name.

Three versions, and a sync ledger on each device

This is the most important part of the design, and where most hand-written sync goes wrong.

With two versions, local and remote, you cannot tell “I changed it” from “they changed it”. You end up comparing timestamps, and device clocks are wrong more often than you would think.

So each device keeps a sync ledger: for every record, the version both sides last agreed on. (Same word as the privacy ledger this article is about, different object: this one is a table of versions kept on each device.) Then every record has three versions, and it is easy to see which side changed since the two last agreed.

A two by two grid: unchanged on both sides, same; changed in the cloud only, pull; changed here only, push; changed on both, merge by kind of record.
Each record is compared with the version both sides last agreed on. Only the bottom-right case needs rules.

Dogood’s decision function is about twenty lines:

function decide(local: string | null, base?: LedgerRecord, remote?: RemoteRecord): Decision {
  if (!remote) return local !== null ? "push" : base ? "forget" : "none";
  if (local === remote.stamp) return "same";
  if (!base) {                                   // first time we see this record
    if (local === null) return "pull";
    if (remote.stamp === null) return "push";    // a deletion never takes away what we have
    return "merge";
  }
  const localChanged = local !== base.stamp;
  const remoteChanged = remote.stamp !== base.stamp && remote.rev >= base.rev;
  const regressed = remote.stamp !== base.stamp && remote.rev < base.rev;
  if (!localChanged && !remoteChanged) return regressed ? "push" : "same";
  if (!localChanged) return "pull";
  if (!remoteChanged) return "push";
  if (local === null) return "pull";             // writing beats deleting
  if (remote.stamp === null) return "push";
  return "merge";
}

Notice the rev check. If the cloud holds a different version with a lower revision than the one both sides agreed on, an older copy was written over a newer one. That is exactly what happens when two devices write the same Drive file at the same moment and the slower one wins. The device that had the newer version sees the regression at its next sync and pushes it again. Nothing is lost, but the change arrives one sync later.

The sync ledger itself holds every record’s key, which means dates, and the full text of any day waiting in a conflict. If your data is encrypted, encrypt the ledger too. Dogood keeps it with the journal’s own private collections, sealed when the journal is.

Merge rules for each kind of data

The bottom-right case needs rules, and the rules depend on what the data means. With one rule for everything (“last write wins”), people can lose a morning of writing.

Text written by a person. Dogood settles three cases by itself and leaves the rest to the writer:

function mergeEntries(local, remote): "local" | "remote" | "conflict" {
  if (sameTitle(local, remote) && sameBody(local, remote) && sameMedia(local, remote))
    return local.updatedAt > remote.updatedAt ? "local" : "remote";   // the same words
  const remoteCovers = covers(remote, local);
  const localCovers = covers(local, remote);
  if (remoteCovers && !localCovers) return "remote";                  // one only adds to the other
  if (localCovers && !remoteCovers) return "local";
  return "conflict";                                                  // the writer chooses
}

“Covers” means: keeps the other’s title, contains the other’s text, and has all of its photos. A page where you added a paragraph on your laptop covers the version your phone had, so it wins without asking.

Be precise about what “covers” checks. Dogood’s version tests whether one body contains the other as a substring and ignores the mood and the chapter. Two consequences follow: a mood changed on the covered side is dropped, and in a narrow case (words removed at the end on one device while the other appends) the removed words come back. If you copy this approach, decide explicitly how every field participates.

Sets. Habit ticks are a set of dates, and the natural merge for a set is the union. A day ticked on either device stays ticked. The cost: if you untick a day on one device while the other device changes the same habit, the tick comes back.

Small objects. For a goal or a chapter, Dogood keeps the one saved last, whole. “Last” comes from each device’s wall clock, which is the weak spot: a device whose clock runs ahead wins every tie.

Settings and defaults. On the very first sync of a key, take the cloud’s version. A device that just joined only has defaults; letting its blank settings overwrite real ones is a classic first-sync bug.

Conflicts go to the writer, in plain words

Some cases have no right automatic answer. Two different versions of the same day, written on two devices before either synced, belong to the writer.

A window titled A day written on two devices, showing both versions side by side with Keep this device's, Keep the other and Keep both.
Dogood's conflict window, drawn from the app's own copy: both versions, their word counts, and three choices.

A few rules made this window work:

  • Nothing is written while it waits. The page on this device stays, the cloud keeps the other. The conflict, with the cloud’s whole version, lives in the sync ledger, so it survives a reload.
  • One conflict blocks nothing else. Every other record keeps syncing.
  • “Keep both” exists. It joins the two texts, this device’s first, then the other’s (and its title if different), with the photos of both. People rarely want to drop one of two things they wrote.
  • The copy says what happened in the writer’s terms: “Each device changed it before the other synced. Choose what stays; nothing is lost until you do.”

Deletions are kept as tombstones, for 120 days

If a deleted record simply disappears from the file, the next device that still has it will push it back, and the deletion never sticks. So a deletion is written as a tombstone: the key, a revision, stamp: null and the time of deletion.

Two rules protect the writer from losing data through deletions:

  • Writing beats deleting. If one device deleted a page while another edited it, the edit wins. A deleted page that comes back is only a small annoyance, but losing writing is not acceptable.
  • A first sync deletes nothing. A device with no sync ledger (new, restored from a backup, or one whose ledger could not be read) pushes what it has, even over a tombstone.

Tombstones cannot live forever, or files grow without limit. Dogood prunes them 120 days after the deletion. That creates a horizon: a device that stays away longer than that still holds the record, finds no tombstone, and pushes it back.

Concurrency without a lock

There is no server, so there is no lock across devices. Two kinds of protection are still needed.

Across tabs of one browser, the Web Locks API makes sure only one tab syncs at a time:

await navigator.locks.request("app-sync", () => runOnce());

Across devices, optimistic concurrency. Read the file’s version when you list the folder, and write only if it has not moved. On Dropbox and OneDrive the provider enforces this. On Drive, check the version again just before writing. The gap between that check and the write is small, and the rev check above fixes the rare lost update.

When a write is refused, do not patch the run. Start it again from a fresh listing. Dogood retries the whole run up to three times, then tells the person “Another device was syncing at the same moment. Try again in a minute.”

The order of operations inside a run matters more than it looks. Dogood applies what it pulled, writes the files, updates the meta file, moves photos, and saves the sync ledger last. If anything fails halfway, the next run starts from the previous ledger, finds that the records already match on both sides, and marks them the same. A failed run only costs a few extra reads, and no data is lost.

When sync runs

Syncing on every keystroke uses too many requests and too much quota, and if sync waits for a button, people never press it. Dogood’s triggers, which I would reuse as a starting point:

TriggerDelay
The person stops typing8 seconds after the last change
The app goes to the backgroundat once (last chance on a phone)
The app comes back to the frontunder a second
The browser comes back onlinehalf a second
While the page is visibleevery 3 minutes
The journal is unlockedhalf a second

Before each run, whatever is being typed is saved, so a run never syncs a page that is half in memory.

OAuth with PKCE, and where the tokens live

A single-page app cannot keep a client secret, so Dogood uses the authorization code flow with PKCE for Dropbox and OneDrive, and Google’s token model for Drive. A few details that cost me time:

  • Open the sign-in window synchronously from the tap, then send it to the provider’s page. Browsers block pop-ups opened after an await.
  • Generate a random state and a PKCE verifier for each attempt, and accept the answer only if the state matches and the message comes from your own origin.
  • Hand the answer back two ways. Some providers’ pages cut the link to the opener, so window.opener.postMessage fails silently. Dogood’s small callback page posts on a BroadcastChannel as well, then wipes the code from its address bar.
  • Check the granted scopes. Google lets people untick a scope on the consent screen. If the app folder scope is missing, say so: “Tick it when Google asks.”

Then decide where tokens live. Memory only is the safest and means a tap every time the app opens. Dogood keeps the short-lived token in localStorage until it expires, so reopening within the hour syncs without a tap, and keeps Dropbox’s refresh token there until sync is turned off.

That is convenient, and it means any script running on the origin can read them. If you do the same, keep that origin boring: no third-party scripts, a strict Content Security Policy, and anything with a different trust level (an admin, a marketing tool) on another origin. What Dogood does there is in “The site around the app” below.

A new device joining

The first sync on a new device is where data is most often lost. Dogood handles three situations explicitly:

  • The device is blank: it takes the cloud’s journal whole.
  • The device already has writing: it never overwrites anything. It asks: “Combine the two: every day written on either stays, and where both wrote the same day, you choose.”
  • The cloud copy is encrypted: it asks for the passphrase once, checks it against the verifier, and from then on the device’s own copy is protected with the same key.

What sync does not give, and what I would change

The limits, worth saying to the writer and to myself:

  • No real time. Changes travel on a timer. Two people cannot write together.
  • No three-way text merge. Without a common ancestor of the text, a day is merged whole: identical, one containing the other, or the writer chooses.
  • Whole-object last-writer-wins for small records, judged by device clocks.
  • Whole-file writes. One changed day rewrites that year’s file.
  • A horizon on deletions, at 120 days.
  • Metadata stays visible to the provider: names, sizes, timing, and whatever sits beside the ciphertext.
  • A tap after an hour on Google Drive, by Google’s design for browser apps.

What I would change:

  • A hybrid logical clock for small objects (a counter combined with the time). A device whose clock runs ahead no longer wins every tie. It takes little code, and it is the first thing I would add.
  • Photo properties inside the sealed bytes, and neutral file names, so the provider no longer learns which years hold writing, or each photo’s type and date.

And two decisions for anyone copying the design. Define how every field takes part in a merge, the mood and the chapter included. If deletions must stick even after a device has been away a long time, write the pruning date in the meta file, and make any device whose last sync is older than that rebuild its sync ledger before pushing.

The storage was already there, in the writer’s own drive. Most of the work was deciding, for each kind of record, when two versions count as the same.

The site around the app

The marketing site and the app share one origin, which lets the site send people who already keep a journal straight to it: the app records a yes-or-no marker in localStorage, and nothing is sent.

Dogood sets no cookies. An affiliate’s or a friend’s code in a link is kept in the browser for 30 days only after the visitor agrees (“May we tell them it came from their link?”), and refusing keeps nothing. Visits to the site’s pages, never the app’s, can be counted by Cloudflare Web Analytics, which uses no cookie and keeps nothing on the device.

The live site has a Content Security Policy that, by default, only allows Dogood’s own origin and stops other sites from framing it. The admin is on a separate host, so nothing with a different trust level shares the journal’s origin.

Where each processor fits

The ledger also says who processes what on Dogood’s behalf:

ProcessorForWhat it handles
CloudflareHosting, the API, its database, dictationRequests (IP addresses at the edge), the API’s tables, audio passing through Whisper
CreemPayments, as merchantCard or wallet details, email, country
ResendEmailsThe licence or gift email and its recipient
Google, Dropbox, MicrosoftSync, under the writer’s own accountThe journal’s files in the writer’s drive

How the ledger maps to the GDPR

The ledger was never meant as a compliance exercise. It still matches the GDPR principles almost one to one.

  • Data minimisation (Article 5(1)(c)) is question two: can it work with less?
  • Purpose limitation (Article 5(1)(b)) is one entry per flow, with one reason each.
  • Storage limitation (Article 5(1)(e)) is the for_how_long field. Usage events go after 396 days, feedback and purchase emails after three years, a gift’s address and message once the gift is sent. When a field is empty, I have not decided yet, and the ledger shows it.
  • Data protection by design and by default (Article 25) is question one, and “off until the writer turns it on”.
  • Security of processing (Article 32) is local encryption, signed licences, hashed tokens, and no journal on the server to protect.
  • Transparency (Articles 12 and 13) is the the_writer_sees field: the explanation lives where the choice is made, as well as in a policy page.

For what is stored on the device itself (the ePrivacy rules on terminal equipment), the same split applies. The journal and its settings are what the writer asked the app to do. Codes from referral links are kept only after a yes. Usage sharing is off by default.

None of this is legal advice, and a ledger does not replace a lawyer. But it makes the talk with one much shorter, because the answers are already written down.

The tests that check the promises

About 1,400 browser checks run before each change, in every language, on a wide screen and a phone. Among them, the ones that guard the ledger:

  • the daily count sends exactly two keys, once per day, never from the demo, nothing when it is off;
  • usage events wait and leave in one request, and the dialog lists what is sent;
  • the demo journal sends no writing-buddies request;
  • a friend’s code is kept only after a yes, on the site and in the app;
  • a sealed sync leaves no unencrypted word of the journal in the cloud files;
  • the security headers include the Content Security Policy;
  • on the Worker, unit tests check that events outside the allowlist are refused, that a partner sees only a name and numbers, that tokens are stored hashed, that old rows are purged, and that every environment variable the code reads is declared.

For the crypto itself, unit tests are cheap and catch exactly the bugs that stay invisible in normal use. If you build the same thing, these are the ones to write:

  • encrypt then decrypt returns the same bytes;
  • a wrong passphrase fails cleanly, through the verifier;
  • flipping one byte of a ciphertext makes decryption fail;
  • a record copied under another id fails to decrypt (if you use additional data);
  • a passphrase change interrupted at every step can be resumed;
  • after locking, no key and no decrypted value is reachable;
  • old envelope versions still open.

The next test I want is the simplest one: a browser run that fails if the app contacts any origin that has no entry in the ledger.

The checklist I would start from today

If you are building either of the two hard parts, these are the lists I would start from, with the changes above already included.

Local encryption

  • Threat model written down, and the interface promises only what it covers.
  • Random data key, wrapped once per unlock method; passphrase changes rewrap.
  • PBKDF2 at 600,000 iterations or more, or Argon2id in WebAssembly; random salt; normalised passphrase; a minimum length.
  • AES-GCM with a fresh 12-byte IV per write, a version field and additional data binding each record to its place.
  • Data key in memory only, non-extractable, dropped on lock in every tab, with every cache.
  • PIN presented as a convenience lock; passkeys with PRF as the strong day-to-day option, checked at registration.
  • The readable metadata listed, shown to the person, and audited against real storage.
  • No recovery key, agreed to in plain words, with backups encouraged before and after.
  • Encryption turned on as a resumable migration that never leaves plaintext behind by surprise.
  • Tests for tampering, wrong keys, interruption and locking.

Sync through the user’s own drive

  • Ask for the app-folder scope only, and check it was granted.
  • Hide providers behind one small interface with normalised errors.
  • Group records into files by how they change; key records by meaning, not by random id, where two devices can create the same thing.
  • Seal records with the local key before upload, and write down exactly what stays visible.
  • Keep a per-device sync ledger, compare three versions, and encrypt the ledger.
  • Detect regressions with a revision counter.
  • Write merge rules per kind of data; define how every field takes part.
  • Hand real conflicts to the person, block nothing else, and offer “keep both”.
  • Write deletions as tombstones; writing beats deleting; a first sync deletes nothing; know your tombstone horizon.
  • Lock across tabs, use conditional writes where the provider has them, retry the whole run, save the ledger last.
  • Use PKCE, open pop-ups synchronously, verify state and origin, and keep the origin that stores tokens free of third-party code.

What writing this article taught me

To write this, I re-read Dogood’s code flow by flow, against the README and the app’s own wording. Most of it matched. A few sentences had drifted: one said a sync token stays in memory when it is kept until it expires, another said the demo sends nothing when it reads the site settings, a third described the licence check as daily when it becomes weekly after a month.

The encryption audit also found two gaps in the code itself, and both are described in their place above: locking left some secondary keys and decrypted lists in memory until the tab closed, and the metadata readable on the device made a longer list than the one-line promise.

Re-reading also turned up a few real gaps, which were fixed in one pass after the first draft of this article: the migration step above that could leave a journal unencrypted, a scheduled gift’s page that could be read with its address alone (it now asks for the key from the purchase email), address hashes made without a secret key, a usage id that outlived its switch, and purchase emails kept with no end date.

None of these changes was big, but over a year they make a precise promise vague. That is why I keep the ledger: each promise is written once, next to the code, with a test, and the interface uses the same words.

Using the method on your own product

You do not need a journal app to use this. Before your next feature ships:

  1. List every request it makes and everything it stores outside the user’s device.
  2. For each, write the entry: what leaves (as data), to whom, when, the default, what is kept, for how long, what a leak would show, what the user sees, what proves it.
  3. Ask the three questions: can it work without leaving the device? Can it work with less? Can the user see it and say no?
  4. Put the user-facing sentence where the choice is made, and make it match the entry word for word.
  5. Write the test before you write the next entry.

It takes an afternoon the first time. After that, it is one entry per change, which costs very little.

Ben