From d2b0d9a2e322ece1152843713ce0e7af220c0ee7 Mon Sep 17 00:00:00 2001 From: kualta Date: Wed, 4 Nov 2026 12:09:44 -0500 Subject: [PATCH 01/16] sync the vault both ways with NOTE through the device client --- .github/workflows/ci.yml | 1 + .github/workflows/release.yml | 1 + AGENTS.md | 12 +- README.md | 73 +++++- bun.lock | 8 + package.json | 9 +- scripts/build.ts | 2 + scripts/smoke.ts | 35 +++ src/account.ts | 73 ++++++ src/conflicts.ts | 28 +++ src/controller.ts | 381 +++++++++++++++++++++++++++++ src/custody.ts | 176 +++++++++++++ src/device.ts | 31 +++ src/engine.ts | 449 ++++++++++++++++++++++++++++++++++ src/fetch.ts | 71 ++++++ src/hash.ts | 9 + src/index-store.ts | 89 +++++++ src/lock.ts | 25 ++ src/main.ts | 161 +++++++++++- src/obsidian/modals.ts | 207 ++++++++++++++++ src/obsidian/settings.ts | 155 ++++++++++++ src/obsidian/vault.ts | 156 ++++++++++++ src/paths.ts | 62 +++++ src/plan.ts | 261 ++++++++++++++++++++ tests/controller.test.ts | 243 ++++++++++++++++++ tests/custody.test.ts | 117 +++++++++ tests/e2e.test.ts | 233 ++++++++++++++++++ tests/engine.test.ts | 296 ++++++++++++++++++++++ tests/fakes.ts | 122 +++++++++ tests/fetch.test.ts | 105 ++++++++ tests/paths.test.ts | 68 +++++ tests/plan.test.ts | 258 +++++++++++++++++++ 32 files changed, 3903 insertions(+), 14 deletions(-) create mode 100644 scripts/smoke.ts create mode 100644 src/account.ts create mode 100644 src/conflicts.ts create mode 100644 src/controller.ts create mode 100644 src/custody.ts create mode 100644 src/device.ts create mode 100644 src/engine.ts create mode 100644 src/fetch.ts create mode 100644 src/hash.ts create mode 100644 src/index-store.ts create mode 100644 src/lock.ts create mode 100644 src/obsidian/modals.ts create mode 100644 src/obsidian/settings.ts create mode 100644 src/obsidian/vault.ts create mode 100644 src/paths.ts create mode 100644 src/plan.ts create mode 100644 tests/controller.test.ts create mode 100644 tests/custody.test.ts create mode 100644 tests/e2e.test.ts create mode 100644 tests/engine.test.ts create mode 100644 tests/fakes.ts create mode 100644 tests/fetch.test.ts create mode 100644 tests/paths.test.ts create mode 100644 tests/plan.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad36489..6e5ea65 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,3 +23,4 @@ jobs: - run: bun run typecheck - run: bun test - run: bun run build + - run: bun run smoke diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bc6789e..d0e5db4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -31,6 +31,7 @@ jobs: - run: bun run typecheck - run: bun test - run: bun run build + - run: bun run smoke - uses: actions/attest@v4 with: subject-path: | diff --git a/AGENTS.md b/AGENTS.md index 90efbae..dc6f4d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,9 +2,13 @@ NOTE Sync is an Obsidian community plugin (id `flow-note`). This repository is public: keep in-house tooling, internal hosts and private links out of code, docs and commit messages. -- Use Bun 1.4.2. Before a PR, run `bun run lint`, `bun run typecheck`, `bun test` and `bun run build`. +- Use Bun 1.4.2. Before a PR, run `bun run lint`, `bun run typecheck`, `bun test`, `bun run build` and `bun run smoke`. - `manifest.json` stays at the root. Never change the plugin `id`. A release tag equals the manifest `version`, with no `v`. -- Keep Obsidian API calls in `src/obsidian/`; everything else is tested without Obsidian. -- Secrets (the device seed, Flow ID device tokens) live only in Obsidian's secret storage, never in `data.json` or anywhere inside the vault folder. -- Never execute note content. Notes, MDX and code blocks are text to this plugin. +- Obsidian's API is used only in `src/main.ts` and `src/obsidian/`. Everything else (path rules, the planner, the engine, custody, the controller) runs under `bun test`, and `tests/e2e.test.ts` drives the real device client from `@flow-industries/seal` against its in-memory Flow ID and PDS. +- `src/device.ts` is the only module that imports `@flow-industries/seal`. +- Secrets (the device seed, Flow ID device tokens) live only in Obsidian's secret storage, never in `data.json` or anywhere inside the vault folder. The plugin keeps no `data.json`. +- One device transport per credential store: `SyncController` owns the only open device vault, and a Web Lock keeps a second window or vault from opening the same account. +- Nothing syncs before the person confirms the linked account (`Custody.account()`). +- Never execute note content. Notes, MDX and code blocks are text to this plugin, and nothing is ever written into Obsidian's config folder. +- `main.js` is loaded as CommonJS: `scripts/build.ts` replaces `import.meta.url`, and `bun run smoke` fails if the bundle needs anything at load beyond what Obsidian provides. - No WHAT comments; doc comments for exported APIs and short WHY comments only. diff --git a/README.md b/README.md index 7072a84..9b95223 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,68 @@ # NOTE Sync -An Obsidian plugin that keeps a vault in sync with your end-to-end encrypted [NOTE](https://note.flow.talk) notepad. +An Obsidian plugin that keeps a vault in sync, both ways, with your end-to-end encrypted [NOTE](https://note.flow.talk) notepad. You approve it once in your browser; after that it syncs without asking for your passkey. Notes are encrypted on this device before they leave it. -Work in progress: nothing syncs yet. +NOTE Sync needs a Flow ID account with a NOTE notepad, and Obsidian 1.11.5 or later. + +## Linking + +1. Open **Settings → NOTE Sync** and select **Link**, or run **NOTE Sync: Link this vault** from the command palette. +2. The plugin shows a code and a 12-digit device code, and opens `note.flow.talk/link` in your browser. +3. On that page, sign in if asked, check the code, type the device code and approve with your passkey. The device code never leaves this device any other way: Flow ID only ever sees a slow hash of it, so it can't swap in keys or a notepad of its own. +4. Back in Obsidian, the plugin shows the account it was linked to (its handle, when the handle checks out both ways, and its DID). **Nothing syncs until you confirm it is yours.** A code someone else guessed and approved would otherwise bind your vault to their notepad. + +A link has to be approved within ten minutes. + +## What syncs + +- **Notes:** every Markdown (`.md`) and MDX (`.mdx`) file, both ways. +- **Renames** carry across, including folder renames. A rename the plugin didn't see (Obsidian was closed) is recognised by the note's unchanged text. +- **Deletions** move the note to the trash on the other side: Obsidian's trash here, NOTE's trash there. An edit beats a deletion: if one side edited a note the other deleted, the note comes back. Before a sync would trash more than ten notes and more than a tenth of the vault at once, the plugin asks. +- **Conflicts:** when both sides edited the same note, NOTE's text keeps the note's name and this vault's text is saved beside it as ` conflict <8 hex>.md`, the way NOTE names its own conflict copies. Nothing is overwritten while you type: a file that changes during a sync is left alone until the next one. + +**Not synced:** + +- Obsidian's config folder (`.obsidian/`) and anything hidden. The config folder holds plugin code, so nothing from NOTE is ever written into it. +- Attachments. This version syncs notes only; images, PDFs and other files stay on this device, and **Settings → NOTE Sync** counts them. +- Names NOTE can't store (such as `con.md` or a name ending in a dot), and NOTE notes whose names this vault can't hold. Settings lists them. + +## Note content never runs + +The plugin treats every note as text. It never evaluates MDX, code blocks or anything else in a note. Other plugins you install may: Dataview's JavaScript queries or Templater, for example, run code from notes, and with sync on, those notes can come from your other devices. + +## Where the device key lives + +Linking creates a device seed (the key that opens your notepad) and Flow ID device tokens. The plugin keeps them, the account you confirmed, and the access statement this device accepted, in Obsidian's secret storage. It never writes them to `data.json` or anywhere in the vault folder, which git and other sync tools copy. The plugin has no `data.json` at all. + +| Platform | Where the secrets are kept | +| --- | --- | +| macOS | Obsidian's app data, encrypted with a key in the macOS Keychain (Electron `safeStorage`) | +| Windows | Obsidian's app data, encrypted with Windows DPAPI | +| Linux | Obsidian's app data, encrypted with your keyring (libsecret or KWallet) | +| Linux without a keyring | Obsidian's app data, **unencrypted**: the plugin says so and asks before linking | +| iOS | The iOS Keychain, through Obsidian's native secure storage | +| Android | Android's secure storage, through Obsidian's native secure storage | + +Trade-offs to know: + +- **Plugins aren't isolated from each other.** Any plugin you install runs with the same access as this one and could read Obsidian's secret storage. Install plugins you trust. +- **Mobile secret storage is shared by every vault on the device**, so each vault's link lives under its own random name. +- **On mobile, Obsidian saves a secret in the background.** Flow ID rotates the refresh token on every refresh; if the app is killed in the instant between a refresh and that save, the next start presents the old token, Flow ID refuses it, and you link again. Nothing is lost: your notes are on both sides. + +The plugin also keeps two caches in Obsidian's app data, never in the vault: the device client's encrypted local database, and an index of what was last synced. + +## Removing access + +- **Unlink** (in settings or the command palette) stops syncing and forgets the device seed and tokens on this device. Your files stay. Remove the device under **Access** in NOTE too. +- **Removing the device** under Access in NOTE, or Flow ID revoking it, stops the plugin at its next sync: it wipes the seed and tokens, writes nothing more, and asks you to link again. Your files stay. + +## Network use + +- **id.flow.industries** (Flow ID): links the device, refreshes its tokens, and relays your encrypted notepad to and from your PDS. Only the device name, its public keys, a slow hash of the device code and ciphertext leave this device. +- **note.flow.talk**: opened in your browser to approve the link. The plugin itself doesn't contact it. +- **plc.directory**, or a `did:web` account's own domain, and **your handle's domain** (`https:///.well-known/atproto-did`): read once at linking to show the account's handle. + +The plugin sends no telemetry. ## Development @@ -10,17 +70,18 @@ Use Bun 1.4.2. ```bash bun install --frozen-lockfile -bun run build # main.js at the repository root bun run lint bun run typecheck -bun test +bun test # unit tests and the end-to-end run against an in-memory Flow ID and PDS +bun run build # main.js at the repository root +bun run smoke # loads main.js as Obsidian does, with no Node modules ``` -To try it, copy `main.js`, `manifest.json` and `styles.css` into `/.obsidian/plugins/flow-note/` and enable **NOTE Sync** under **Settings → Community plugins**. +Obsidian's API is used only under `src/obsidian/` and `src/main.ts`; everything else runs under `bun test`. To try a build, copy `main.js`, `manifest.json` and `styles.css` into `/.obsidian/plugins/flow-note/` and enable **NOTE Sync** under **Settings → Community plugins**. ## Releasing -`bun run version x.y.z` updates `package.json`, `manifest.json` and `versions.json`. Merge that, then push a tag named exactly `x.y.z`: the release workflow builds and attaches `main.js`, `manifest.json` and `styles.css` to a draft release. +`bun run version x.y.z` updates `package.json`, `manifest.json` and `versions.json`. Merge that, then push a tag named exactly `x.y.z`: the release workflow checks it, builds, and attaches `main.js`, `manifest.json` and `styles.css` to a draft release. ## License diff --git a/bun.lock b/bun.lock index 6d5c31f..34a1ffa 100644 --- a/bun.lock +++ b/bun.lock @@ -4,10 +4,14 @@ "workspaces": { "": { "name": "flow-note-sync", + "dependencies": { + "@flow-industries/seal": "link:@flow-industries/seal", + }, "devDependencies": { "@biomejs/biome": "2.5.8", "@flow-industries/lint": "0.3.1", "@types/bun": "1.3.14", + "fake-indexeddb": "6.2.4", "obsidian": "1.14.4", "typescript": "5.9.3", }, @@ -38,6 +42,8 @@ "@flow-industries/lint": ["@flow-industries/lint@0.3.1", "", {}, "sha512-oKTw7fMCZBlshRixumpXrUJUmbJx3HqiGs72F43d920yy1fCtOuAjlnbY8SXBZZ7TnEibuYY2FVjAZcQSg6COQ=="], + "@flow-industries/seal": ["@flow-industries/seal@link:@flow-industries/seal", {}], + "@marijn/find-cluster-break": ["@marijn/find-cluster-break@1.0.4", "", {}, "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ=="], "@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], @@ -54,6 +60,8 @@ "crelt": ["crelt@1.0.7", "", {}, "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA=="], + "fake-indexeddb": ["fake-indexeddb@6.2.4", "", {}, "sha512-INKeIKEtSViN4yVtEWEUqbsqmaIy7Ls+MfU0yxQVXg67pOJ/sH1ZxcVrP8XrKULUFohcPD9gnmym+qBfEybACw=="], + "moment": ["moment@2.31.0", "", {}, "sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw=="], "obsidian": ["obsidian@1.14.4", "", { "dependencies": { "@types/codemirror": "5.60.8", "moment": "2.31.0" }, "peerDependencies": { "@codemirror/state": "6.7.6", "@codemirror/view": "6.43.13" } }, "sha512-Kyo+5t0wFW2On5irLOPrgtwWDnaJsvE9n/P1OVvdPytx+NqeHJXvxVqADNOqLp9bU1+I64B6i+dHb0fxR/ss3w=="], diff --git a/package.json b/package.json index c4c1fb1..a37c947 100644 --- a/package.json +++ b/package.json @@ -12,13 +12,18 @@ "check": "biome check --write", "typecheck": "tsc --noEmit", "test": "bun test", - "version": "bun run scripts/version-bump.ts" + "version": "bun run scripts/version-bump.ts", + "smoke": "bun run scripts/smoke.ts" }, "devDependencies": { "@biomejs/biome": "2.5.8", "@flow-industries/lint": "0.3.1", "@types/bun": "1.3.14", "obsidian": "1.14.4", - "typescript": "5.9.3" + "typescript": "5.9.3", + "fake-indexeddb": "6.2.4" + }, + "dependencies": { + "@flow-industries/seal": "link:@flow-industries/seal" } } diff --git a/scripts/build.ts b/scripts/build.ts index 82b0f3c..2cfcbcf 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -29,6 +29,8 @@ const result = await Bun.build({ external, minify: production, sourcemap: production ? "none" : "inline", + // Obsidian loads main.js as CommonJS, where `import.meta` is a syntax error; no local path leaks in its place. + define: { "import.meta.url": JSON.stringify("app://obsidian.md/main.js") }, banner: "/* Bundled from https://github.com/flow-industries/sync; read the source there. */", }); diff --git a/scripts/smoke.ts b/scripts/smoke.ts new file mode 100644 index 0000000..0b68a73 --- /dev/null +++ b/scripts/smoke.ts @@ -0,0 +1,35 @@ +/** + * Loads the built main.js the way Obsidian does, as CommonJS with only the + * modules Obsidian provides, as on mobile where Node's are missing, and + * checks it exports a plugin class. Run after `bun run build`. + */ +class Plugin {} +const stub = (exports: Record) => + new Proxy(exports, { + get: (target, key) => (key in target ? target[key as string] : class {}), + }); +const provided = /^(obsidian|@codemirror\/[a-z]+|@lezer\/[a-z]+)$/u; +/** Obsidian's own copies of the editor packages, here whichever copy the dependencies resolve to. */ +function editorPackage(name: string) { + const from = Bun.resolveSync("@flow-industries/seal", import.meta.dir); + return require(Bun.resolveSync(name, from)); +} +const required = new Set(); +const module = { exports: {} as Record }; +const code = await Bun.file("main.js").text(); +new Function("module", "exports", "require", code)( + module, + module.exports, + (name: string) => { + if (!provided.test(name)) + throw new Error(`main.js requires ${name} at load`); + required.add(name); + return name === "obsidian" ? stub({ Plugin }) : editorPackage(name); + }, +); +const plugin = module.exports.default; +if (typeof plugin !== "function" || !(plugin.prototype instanceof Plugin)) + throw new Error("main.js doesn't export a Plugin subclass as default"); +console.log( + `main.js loads (${(code.length / 1024).toFixed(0)} KiB), requiring only ${[...required].join(", ")}`, +); diff --git a/src/account.ts b/src/account.ts new file mode 100644 index 0000000..aa80b56 --- /dev/null +++ b/src/account.ts @@ -0,0 +1,73 @@ +import type { NoteDeviceFetch } from "./device"; + +/** The account a link bound this vault to, as shown before the first upload. */ +export interface LinkedAccount { + did: string; + /** Set only when the DID document names it and the handle points back at the DID. */ + handle?: string; +} + +const PLC_DIRECTORY = "https://plc.directory"; +const HANDLE = + /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]*[a-z0-9]$/u; +const TIMEOUT_MS = 8_000; + +async function getJson(fetch: NoteDeviceFetch, url: string): Promise { + const response = await fetch(url, { + method: "GET", + headers: { Accept: "application/json" }, + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + if (!response.ok) throw new Error(`${url} answered ${response.status}`); + return response.json(); +} + +function documentUrl(did: string): string | null { + if (/^did:plc:[a-z2-7]{24}$/u.test(did)) return `${PLC_DIRECTORY}/${did}`; + const web = /^did:web:([a-z0-9.-]+)$/u.exec(did)?.[1]; + return web && HANDLE.test(web) ? `https://${web}/.well-known/did.json` : null; +} + +function claimedHandle(document: unknown, did: string): string | null { + if (typeof document !== "object" || document === null) return null; + const { id, alsoKnownAs } = document as { + id?: unknown; + alsoKnownAs?: unknown; + }; + if (id !== did || !Array.isArray(alsoKnownAs)) return null; + const handle = alsoKnownAs + .find( + (alias): alias is string => + typeof alias === "string" && alias.startsWith("at://"), + ) + ?.slice("at://".length) + .toLowerCase(); + return handle && HANDLE.test(handle) ? handle : null; +} + +/** + * Names the account behind `did` by its handle, checked both ways: the DID + * document claims the handle, and the handle's domain answers with the DID. + * A DID document alone could claim anyone's handle. Anything unverifiable + * leaves just the DID, which is what the link actually bound. + */ +export async function linkedAccount( + did: string, + fetch: NoteDeviceFetch, +): Promise { + try { + const url = documentUrl(did); + if (!url) return { did }; + const handle = claimedHandle(await getJson(fetch, url), did); + if (!handle) return { did }; + const response = await fetch(`https://${handle}/.well-known/atproto-did`, { + method: "GET", + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + if (response.ok && (await response.text()).trim() === did) + return { did, handle }; + } catch { + // An account that can't be named still shows its DID. + } + return { did }; +} diff --git a/src/conflicts.ts b/src/conflicts.ts new file mode 100644 index 0000000..d7d1ca7 --- /dev/null +++ b/src/conflicts.ts @@ -0,0 +1,28 @@ +import { nameOf, parentOf } from "./paths"; + +const encoder = new TextEncoder(); +const MAX_NAME_BYTES = 255; + +/** + * Where a conflicting copy of `path` goes: beside it, named as NOTE names its + * own conflict copies, ` conflict <8 hex>`, with the name + * shortened until it fits 255 bytes. + */ +export function conflictPath( + path: string, + id: () => string = () => crypto.randomUUID(), +): string { + const name = nameOf(path); + const extension = /\.mdx?$/iu.exec(name)?.[0] ?? ""; + const suffix = ` conflict ${id().slice(0, 8)}${extension.toLowerCase()}`; + const characters = Array.from(name.slice(0, name.length - extension.length)); + while ( + encoder.encode(`${characters.join("")}${suffix}`).length > MAX_NAME_BYTES + ) { + if (!characters.length) throw new Error("Name suffix exceeds bounds"); + characters.pop(); + } + const parent = parentOf(path); + const copy = `${characters.join("")}${suffix}`; + return parent ? `${parent}/${copy}` : copy; +} diff --git a/src/controller.ts b/src/controller.ts new file mode 100644 index 0000000..ce5745e --- /dev/null +++ b/src/controller.ts @@ -0,0 +1,381 @@ +import { type LinkedAccount, linkedAccount } from "./account"; +import type { Custody } from "./custody"; +import type { + DeviceOptions, + DeviceVault, + LinkOptions, + LinkPrompt, + NoteDeviceFetch, + TrustLoss, +} from "./device"; +import { + type Deletions, + type LocalVault, + type RoundResult, + SyncEngine, + type SyncIndex, +} from "./engine"; + +/** The device client calls the controller makes. */ +export interface DeviceClient { + createDeviceSeed(): Uint8Array; + linkDevice(seed: Uint8Array, options: LinkOptions): Promise; + openDeviceVault( + seed: Uint8Array, + options: DeviceOptions, + ): Promise; + /** The status the device's sync reports once it lost access and wiped its keys. */ + locked: string; + /** Whether a status means the device's last sync read the vault, so its local copy is current. */ + pulled(status: string): boolean; +} + +export type Phase = + | { kind: "unlinked" } + | { kind: "linking"; prompt?: LinkPrompt } + | { kind: "confirm"; account: LinkedAccount } + | { kind: "opening" } + | { kind: "open"; status: string } + | { kind: "removed"; message: string } + | { kind: "stopped"; message: string }; + +export type RemovalReason = "removed" | "revoked" | "unverified"; +export const REMOVED: Record = { + removed: + "This vault was removed from your NOTE notepad's access. Link it again to keep syncing.", + revoked: "Flow ID unlinked this vault. Link it again to keep syncing.", + unverified: + "This vault's link couldn't be verified. Link it again, and remove the unverified entry under Access in NOTE.", +}; +export const STRANDED = + "NOTE's key changed while edits from this vault were still waiting to sync. Nothing is overwritten this time: where NOTE has different text, this vault's is kept as a conflict copy beside it."; +export const LOCKED_ELSEWHERE = + "Another Obsidian vault on this device is syncing this NOTE account. Close it or unlink it there first."; + +export interface ControllerOptions { + custody: Custody; + device: DeviceClient; + /** Flow ID's origin. */ + host: string; + fetch: NoteDeviceFetch; + local: LocalVault; + configDir: string; + /** The index for one NOTE vault, so relinking to another vault never reuses it. */ + indexFor(did: string, vault: string): SyncIndex; + /** + * Holds `name` for as long as the vault is open, across every window and + * vault of this app, or answers null when another holder has it. + */ + hold(name: string): Promise<(() => void) | null>; + /** Deletes the device client's local database for this account's vault. */ + forgetLocalDatabase(did: string, vault: string): Promise; + confirmDeletions(deletions: Deletions): Promise; + onChange(): void; + onTrustLoss(loss: TrustLoss): void; + /** Tells the person something sync did that they didn't ask for. */ + notify(message: string): void; +} + +const LOCAL_DEBOUNCE_MS = 1_500; +const REMOTE_DEBOUNCE_MS = 500; +const RETRY_MS = 30_000; + +/** + * Links, opens and syncs one Obsidian vault with its NOTE vault, and owns the + * only open device vault, so a single device transport ever refreshes the + * stored tokens. Nothing syncs until the person confirmed the account the + * link bound, no round runs until the device has read the vault once since + * it opened, and everything stops when the device loses access. + */ +export class SyncController { + phase: Phase = { kind: "unlinked" }; + lastRound: RoundResult | null = null; + private vault: DeviceVault | null = null; + private engine: SyncEngine | null = null; + private release: (() => void) | null = null; + private unsubscribe: (() => void)[] = []; + private timer: ReturnType | undefined; + private opening: Promise | null = null; + /** Bumped by every `close`, so work started before it notices and stops. */ + private generation = 0; + private ready = false; + private linking = false; + + constructor(private readonly options: ControllerOptions) {} + + /** The account the person confirmed, while linked. */ + account(): LinkedAccount | null { + return this.options.custody.account(); + } + + private set(phase: Phase) { + this.phase = phase; + this.options.onChange(); + } + + private live(generation: number) { + return generation === this.generation; + } + + /** Opens the linked vault, if there is one the person confirmed. */ + async start() { + if (this.linking) return; + const generation = this.generation; + try { + const { custody } = this.options; + const credentials = await custody.credentials.read(); + if (!this.live(generation)) return; + if (!custody.seed() || !credentials) + return this.set({ kind: "unlinked" }); + if (custody.account()?.did !== credentials.did) { + const account = await linkedAccount( + credentials.did, + this.options.fetch, + ); + if (this.live(generation)) this.set({ kind: "confirm", account }); + return; + } + await this.open(); + } catch (error) { + if (!this.live(generation)) return; + this.close(); + this.set({ kind: "stopped", message: messageOf(error) }); + } + } + + /** + * Links this vault as a new device: shows the prompt through the phase, + * waits for approval in the browser, then names the account it was bound + * to. Nothing syncs until `confirm`. + */ + async link(label: string, signal: AbortSignal): Promise { + if (this.linking || this.vault) + throw new Error("This vault is already linked."); + const { custody, device } = this.options; + this.close(); + this.linking = true; + custody.wipe(); + const seed = device.createDeviceSeed(); + custody.saveSeed(seed); + this.set({ kind: "linking" }); + try { + await device.linkDevice(seed, { + ...this.deviceOptions(), + label, + signal, + onPrompt: (prompt) => this.set({ kind: "linking", prompt }), + }); + const credentials = await custody.credentials.read(); + if (!credentials) throw new Error("Linking stored no credentials."); + const account = await linkedAccount(credentials.did, this.options.fetch); + this.set({ kind: "confirm", account }); + return account; + } catch (error) { + custody.wipe(); + if (this.phase.kind !== "removed") this.set({ kind: "unlinked" }); + throw error; + } finally { + this.linking = false; + seed.fill(0); + } + } + + /** The person recognised the account: remember it and start syncing. */ + async confirm() { + if (this.phase.kind !== "confirm") return; + this.options.custody.confirmAccount(this.phase.account); + await this.open(); + } + + /** Stops syncing and forgets the seed, the tokens, the sync index and the device's local database; the files stay. */ + async unlink() { + await this.forget(); + this.set({ kind: "unlinked" }); + } + + async syncNow() { + if (this.phase.kind === "stopped") return this.start(); + const { vault, engine } = this; + if (!vault || !engine) return; + engine.reconsiderDeletions(); + engine.remoteChanged(); + await vault.sync().catch(() => {}); + await this.round(); + // The round's writes would sync on their own; this sends them now. + await vault.sync().catch(() => {}); + } + + localChanged() { + this.schedule(LOCAL_DEBOUNCE_MS); + } + + renamed(from: string, to: string) { + this.engine?.renamed(from, to); + this.schedule(LOCAL_DEBOUNCE_MS); + } + + /** Closes the vault and stops any round or open in flight; unsynced writes wait in the local database. */ + close() { + this.generation++; + this.ready = false; + clearTimeout(this.timer); + for (const unsubscribe of this.unsubscribe.splice(0)) unsubscribe(); + this.engine?.stop(); + this.vault?.stop(); + this.vault = null; + this.engine = null; + this.release?.(); + this.release = null; + } + + /** + * Wipes the keys and drops the sync index, whose base the device's database + * no longer backs. The database goes too, unless another vault on this + * device holds the account: the device client names it by account and + * vault only, so it is that vault's database as well. + */ + private async forget() { + const { custody, hold, indexFor, forgetLocalDatabase } = this.options; + const credentials = await custody.credentials.read(); + const checkpoint = await custody.checkpoints.read(); + this.close(); + custody.wipe(); + if (!credentials || !checkpoint) return; + const { did } = credentials; + await indexFor(did, checkpoint.vault) + .clear() + .catch(() => {}); + const release = await hold(`flow-note:${did}`); + if (!release) return; + try { + await forgetLocalDatabase(did, checkpoint.vault); + } catch { + // A database another window still holds open is left for the next unlink. + } finally { + release(); + } + } + + private deviceOptions(): DeviceOptions { + const { custody, host, fetch } = this.options; + return { + host, + fetch, + ...custody.scope(), + onRemoved: async (reason) => { + await this.forget(); + this.set({ kind: "removed", message: REMOVED[reason] }); + }, + }; + } + + private open(): Promise { + this.opening ??= this.openOnce().finally(() => { + this.opening = null; + }); + return this.opening; + } + + private async openOnce() { + const { custody, device } = this.options; + this.close(); + const generation = this.generation; + const seed = custody.seed(); + let vault: DeviceVault | undefined; + try { + const credentials = await custody.credentials.read(); + if (!this.live(generation)) return; + if (!seed || !credentials) return this.set({ kind: "unlinked" }); + if (custody.account()?.did !== credentials.did) return void this.start(); + this.set({ kind: "opening" }); + const release = await this.options.hold(`flow-note:${credentials.did}`); + if (!this.live(generation)) return release?.(); + if (!release) + return this.set({ kind: "stopped", message: LOCKED_ELSEWHERE }); + this.release = release; + vault = await device.openDeviceVault(seed, this.deviceOptions()); + const checkpoint = await custody.checkpoints.read(); + if (!checkpoint) throw new Error("This vault's pin is missing."); + const engine = new SyncEngine({ + local: this.options.local, + remote: vault, + index: this.options.indexFor(credentials.did, checkpoint.vault), + configDir: this.options.configDir, + confirmDeletions: this.options.confirmDeletions, + }); + await engine.load(); + if (!this.live(generation)) return vault.stop(); + if (vault.stranded) { + engine.rebase(); + this.options.notify(STRANDED); + } + this.vault = vault; + this.engine = engine; + this.unsubscribe.push( + vault.subscribe((status) => this.statusChanged(status)), + vault.subscribeChanges(() => { + this.engine?.remoteChanged(); + this.schedule(REMOTE_DEBOUNCE_MS); + }), + vault.subscribeTrustLoss((loss) => this.options.onTrustLoss(loss)), + ); + if (this.phase.kind === "opening") + this.set({ kind: "open", status: "Connecting" }); + // Pull first, so edits made here while closed meet the remote's as a conflict copy beside the note. + void this.syncNow(); + } catch (error) { + if (!this.live(generation)) return vault?.stop(); + this.close(); + vault?.stop(); + if (this.phase.kind !== "removed") + this.set({ kind: "stopped", message: messageOf(error) }); + } finally { + seed?.fill(0); + } + } + + private statusChanged(status: string) { + if (status === this.options.device.locked) { + // Locked means access changed and the keys are gone: opening again learns whether the device was removed. + this.close(); + void this.open(); + return; + } + if (!this.ready && this.options.device.pulled(status)) { + this.ready = true; + this.schedule(0); + } + if (this.phase.kind === "open") this.set({ kind: "open", status }); + } + + private schedule(delay: number) { + if (!this.engine) return; + clearTimeout(this.timer); + this.timer = setTimeout(() => void this.round(), delay); + } + + private async round() { + const { engine, vault, generation } = this; + if (!engine || !vault || !this.ready) return; + try { + this.lastRound = await engine.run(); + if (!this.live(generation)) return; + if (this.lastRound.applied) void vault.sync().catch(() => {}); + if (this.lastRound.failed.length) this.schedule(RETRY_MS); + } catch (error) { + if (!this.live(generation)) return; + this.lastRound = { + applied: 0, + failed: [{ path: "", error: messageOf(error) }], + attachments: 0, + unsyncable: [], + held: { local: 0, remote: 0 }, + }; + this.schedule(RETRY_MS); + } + this.options.onChange(); + } +} + +const messageOf = (error: unknown) => + error instanceof Error ? error.message : String(error); diff --git a/src/custody.ts b/src/custody.ts new file mode 100644 index 0000000..523a6a7 --- /dev/null +++ b/src/custody.ts @@ -0,0 +1,176 @@ +import type { LinkedAccount } from "./account"; +import type { + DeviceCheckpoint, + DeviceCheckpointStore, + NoteDeviceCredentialStore, + NoteDeviceCredentials, +} from "./device"; + +/** + * A string store outside the vault folder. In Obsidian this is its secret + * storage: on desktop encrypted with the OS keychain (Electron `safeStorage`), + * on mobile the platform's secure storage. + */ +export interface SecretBackend { + get(id: string): string | null; + set(id: string, value: string): void; + delete(id: string): void; +} + +function toBase64Url(bytes: Uint8Array): string { + return btoa(String.fromCharCode(...bytes)) + .replaceAll("+", "-") + .replaceAll("/", "_") + .replace(/=+$/u, ""); +} +function fromBase64Url(text: string): Uint8Array { + const binary = atob(text.replaceAll("-", "+").replaceAll("_", "/")); + return Uint8Array.from(binary, (char) => char.charCodeAt(0)); +} +function parsed(text: string | null): unknown { + if (!text) return null; + try { + return JSON.parse(text); + } catch { + return null; + } +} +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +function asCredentials(value: unknown): NoteDeviceCredentials | null { + if (!isRecord(value)) return null; + const { accessToken, refreshToken, deviceId, userId, did, accessExpiresAt } = + value; + return typeof accessToken === "string" && + typeof refreshToken === "string" && + typeof deviceId === "string" && + typeof userId === "string" && + typeof did === "string" && + did.startsWith("did:") && + typeof accessExpiresAt === "number" + ? { accessToken, refreshToken, deviceId, userId, did, accessExpiresAt } + : null; +} +function asCheckpoint(value: unknown): DeviceCheckpoint | null { + return isRecord(value) && + typeof value.vault === "string" && + typeof value.epoch === "number" && + isRecord(value.pinned) && + typeof value.trust === "string" && + Array.isArray(value.runners) + ? (value as unknown as DeviceCheckpoint) + : null; +} + +/** + * Everything a linked device keeps: its seed, Flow ID device tokens, the pin + * it accepted and the account the person confirmed, each a secret under this + * vault's own namespace. Obsidian's mobile secret storage is shared by every + * vault on the device, so the namespace keeps two vaults' links apart. + */ +export class Custody { + readonly credentials: NoteDeviceCredentialStore; + readonly checkpoints: DeviceCheckpointStore; + private readonly ids: Record< + "seed" | "credentials" | "checkpoint" | "account", + string + >; + private generation = 0; + + constructor( + private readonly backend: SecretBackend, + namespace: string, + ) { + if (!/^[a-z0-9]{8,32}$/u.test(namespace)) + throw new Error("Invalid custody namespace"); + const id = (name: string) => `flow-note-${namespace}-${name}`; + this.ids = { + seed: id("seed"), + credentials: id("tokens"), + checkpoint: id("pin"), + account: id("account"), + }; + this.credentials = { + read: async () => + asCredentials(parsed(this.backend.get(this.ids.credentials))), + write: async (credentials) => { + if (!asCredentials(credentials)) + throw new Error("Invalid device credentials"); + this.backend.set(this.ids.credentials, JSON.stringify(credentials)); + }, + }; + this.checkpoints = { + read: async () => + asCheckpoint(parsed(this.backend.get(this.ids.checkpoint))), + write: async (checkpoint) => { + this.backend.set(this.ids.checkpoint, JSON.stringify(checkpoint)); + }, + }; + } + + /** + * The stores to hand one device transport. A refresh that lands after + * `wipe` (an unlink or a removal mid-refresh) writes nothing, so wiped + * tokens stay wiped and a stale session can't overwrite a newer pin. + */ + scope(): Pick { + const generation = this.generation; + const current = () => generation === this.generation; + return { + credentials: { + read: this.credentials.read, + write: async (value) => { + if (current()) await this.credentials.write(value); + }, + }, + checkpoints: { + read: this.checkpoints.read, + write: async (value) => { + if (current()) await this.checkpoints.write(value); + }, + }, + }; + } + + seed(): Uint8Array | null { + const text = this.backend.get(this.ids.seed); + if (!text) return null; + try { + const seed = fromBase64Url(text); + return seed.length === 32 ? seed : null; + } catch { + return null; + } + } + + saveSeed(seed: Uint8Array) { + if (seed.length !== 32) throw new Error("Invalid device seed"); + this.backend.set(this.ids.seed, toBase64Url(seed)); + } + + /** The account the person confirmed this vault syncs with; nothing uploads before it is set. */ + account(): LinkedAccount | null { + const value = parsed(this.backend.get(this.ids.account)); + if (!isRecord(value) || typeof value.did !== "string") return null; + return typeof value.handle === "string" + ? { did: value.did, handle: value.handle } + : { did: value.did }; + } + + confirmAccount(account: LinkedAccount) { + this.backend.set(this.ids.account, JSON.stringify(account)); + } + + /** + * Forgets the seed, the tokens and the confirmed account. The pin stays, as + * the device client asks, so a later link can't be walked back to an older + * access statement; it is public and opens nothing. + */ + wipe() { + this.generation++; + this.backend.delete(this.ids.seed); + this.backend.delete(this.ids.credentials); + this.backend.delete(this.ids.account); + } +} diff --git a/src/device.ts b/src/device.ts new file mode 100644 index 0000000..f293599 --- /dev/null +++ b/src/device.ts @@ -0,0 +1,31 @@ +import { parseSyncBackoff, SYNCED } from "@flow-industries/seal"; + +/** The one place the plugin imports the NOTE device client from. */ +export { + AccessRemovedError, + createDeviceSeed, + type DeviceCheckpoint, + type DeviceCheckpointStore, + type DeviceOptions, + type DeviceVault, + LINK_EXPIRED, + LINK_UNVERIFIED, + type LinkOptions, + type LinkPrompt, + linkDevice, + type NoteDeviceCredentialStore, + type NoteDeviceCredentials, + type NoteDeviceFetch, + openDeviceVault, + SYNC_LOCKED, + type SyncListener, + type TrustLoss, +} from "@flow-industries/seal"; + +/** + * Whether the device's last sync read the vault: it synced, or only its + * uploads were refused for a while. Pending, blocked or unauthorized syncs + * may not have, so the local copy could still be the one from before. + */ +export const pulledStatus = (status: string) => + status === SYNCED || parseSyncBackoff(status) !== undefined; diff --git a/src/engine.ts b/src/engine.ts new file mode 100644 index 0000000..a9441f3 --- /dev/null +++ b/src/engine.ts @@ -0,0 +1,449 @@ +import { sha256 } from "./hash"; +import { exclusion, isNotePath, pathKey } from "./paths"; +import { + type Entry, + type LocalNote, + plan, + type RemoteNote, + type Step, +} from "./plan"; + +export interface LocalFile { + path: string; + mtime: number; + size: number; +} +/** + * The Obsidian vault as sync sees it. Every write is conditional, so an edit + * the person makes while a round runs is never overwritten: the write + * reports false and the next round picks the edit up. + */ +export interface LocalVault { + /** Every file Obsidian knows of; its config folder and hidden files aren't among them. */ + list(): Promise; + read(path: string): Promise; + /** Creates the file and any missing folders; false when something is already there. */ + create(path: string, source: string): Promise; + /** Replaces the text only if it is still exactly `expected`. */ + replace(path: string, expected: string, next: string): Promise; + /** Renames without rewriting links elsewhere; false when `to` is taken or `from` is gone. */ + move(from: string, to: string): Promise; + /** Moves the file to the trash Obsidian is set to use. */ + trash(path: string): Promise; +} +export interface RemoteNoteView { + id: string; + path: string; + source: string; + revision?: string; + digest?: string; +} +/** The linked NOTE vault, as the device client's `DeviceVault` offers it. */ +export interface RemoteVault { + read(): Promise<{ notes: RemoteNoteView[] }>; + /** Resolves with the revision the saved text now has. */ + saveNote(note: RemoteNoteView): Promise<{ revision: string; digest: string }>; + rename(id: string, path: string): Promise; + remove(id: string): Promise; +} +/** Where the entries live between rounds: outside the vault folder, per linked device. */ +export interface SyncIndex { + load(): Promise; + save(entries: Entry[]): Promise; + clear(): Promise; +} +export interface Deletions { + local: number; + remote: number; +} +export interface RoundResult { + applied: number; + failed: { path: string; error: string }[]; + /** Attachments, which this version doesn't sync yet. */ + attachments: number; + /** Notes whose names NOTE can't store, or notes in NOTE whose names this vault can't hold. */ + unsyncable: string[]; + /** Deletions waiting for the person to confirm them. */ + held: Deletions; +} +export interface EngineOptions { + local: LocalVault; + remote: RemoteVault; + index: SyncIndex; + configDir: string; + /** + * Asked before a round deletes many notes at once, since a vault that + * suddenly reads as empty looks exactly like everything deleted. + */ + confirmDeletions?(deletions: Deletions): Promise; + newId?(): string; +} + +/** More deletions than this, and more than a tenth of the synced notes, need confirming. */ +const MASS_DELETION = 10; +const MAX_PASSES = 3; + +const deletionsOf = (steps: readonly Step[]): Deletions => ({ + local: steps.filter((step) => step.kind === "delete-local").length, + remote: steps.filter((step) => step.kind === "delete-remote").length, +}); +const isDeletion = (step: Step) => + step.kind === "delete-local" || step.kind === "delete-remote"; + +/** + * Two-way sync between the Obsidian vault and the NOTE vault, one round at a + * time. Each round reads both sides, plans against the last agreed state + * (`Entry`), applies the plan, and repeats until nothing is left, so the + * index learns the revisions its own writes produced. + */ +export class SyncEngine { + private entries = new Map(); + private remoteHashes = new Map(); + private cached: RemoteNote[] | null = null; + private running: Promise | null = null; + private again = false; + private declined = new Set(); + private approved = new Set(); + private dirty = false; + private stopped = false; + private readonly newId: () => string; + + constructor(private readonly options: EngineOptions) { + this.newId = options.newId ?? (() => crypto.randomUUID()); + } + + async load() { + this.entries = new Map( + (await this.options.index.load()).map((entry) => [entry.id, entry]), + ); + } + + /** The NOTE vault changed: the next round reads it again. */ + remoteChanged() { + this.cached = null; + } + + /** A file or folder Obsidian renamed, so the round carries the rename instead of a delete and a create. */ + renamed(from: string, to: string) { + const prefix = `${from}/`; + for (const entry of this.entries.values()) { + const current = entry.moved ?? entry.path; + const next = + current === from + ? to + : current.startsWith(prefix) + ? `${to}/${current.slice(prefix.length)}` + : null; + if (next === null) continue; + if (next === entry.path) delete entry.moved; + else entry.moved = next; + } + } + + /** Runs a round, or joins the one running and queues another after it. */ + run(): Promise { + if (this.running) { + this.again = true; + return this.running; + } + const round = (async () => { + try { + let result: RoundResult; + do { + this.again = false; + result = await this.round(); + } while (this.again); + return result; + } finally { + this.running = null; + } + })(); + this.running = round; + return round; + } + + /** Asks again about deletions the person declined before. */ + reconsiderDeletions() { + this.declined.clear(); + } + + /** Stops the round in progress before its next write; nothing runs after. */ + stop() { + this.stopped = true; + } + + /** + * Forgets what the last sync agreed on, so the next round compares both + * sides' text directly: equal text binds, different text keeps both. For + * when the device's local database lost writes the index counts as synced. + */ + rebase() { + for (const entry of this.entries.values()) + Object.assign(entry, { + hash: "", + revision: "", + digest: "", + mtime: 0, + size: 0, + }); + this.dirty = true; + } + + private async round(): Promise { + const result: RoundResult = { + applied: 0, + failed: [], + attachments: 0, + unsyncable: [], + held: { local: 0, remote: 0 }, + }; + for (let pass = 0; pass < MAX_PASSES && !this.stopped; pass++) { + result.unsyncable = []; + const remote = await this.readRemote(result); + const local = await this.scanLocal(result); + const planned = plan({ + entries: [...this.entries.values()], + local, + remote, + newId: this.newId, + }); + const steps = await this.confirmed(planned, result); + if (steps === "asked") { + // Either side may have moved on while the person decided: plan again from fresh reads. + this.remoteChanged(); + pass--; + continue; + } + if (!steps.length) break; + const failures = result.failed.length; + for (const step of steps) { + if (this.stopped) break; + await this.apply(step, result); + } + this.dirty = true; + if (result.failed.length > failures) break; + } + if (this.dirty) { + this.dirty = false; + await this.options.index.save([...this.entries.values()]); + } + return result; + } + + /** + * The steps to apply now. A mass deletion waits for the person; once they + * answer, the answer sticks for those notes and the caller plans again. + */ + private async confirmed( + steps: Step[], + result: RoundResult, + ): Promise { + const keyOf = (step: Step) => `${step.kind}:${step.id}`; + const deletions = steps.filter(isDeletion); + const massive = + deletions.length > MASS_DELETION && + deletions.length > this.entries.size / 10; + if (!massive) { + this.declined.clear(); + this.approved.clear(); + } else if ( + deletions.some( + (step) => + !this.declined.has(keyOf(step)) && !this.approved.has(keyOf(step)), + ) + ) { + const yes = await this.options.confirmDeletions?.(deletionsOf(deletions)); + for (const step of deletions) + (yes ? this.approved : this.declined).add(keyOf(step)); + return "asked"; + } + const held = new Set( + deletions.filter((step) => this.declined.has(keyOf(step))), + ); + result.held = deletionsOf([...held]); + return steps.filter((step) => !held.has(step)); + } + + private async readRemote(result: RoundResult): Promise { + if (!this.cached) { + const { notes } = await this.options.remote.read(); + const hashed: RemoteNote[] = []; + for (const note of notes) { + const revision = note.revision ?? ""; + const known = this.remoteHashes.get(note.id); + const hash = + known && known.revision === revision && revision + ? known.hash + : await sha256(note.source); + this.remoteHashes.set(note.id, { revision, hash }); + hashed.push({ ...note, hash }); + } + this.cached = hashed; + } + return this.cached.filter((note) => { + if (!exclusion(note.path, this.options.configDir)) return true; + result.unsyncable.push(note.path); + return false; + }); + } + + private async scanLocal(result: RoundResult): Promise { + const byPath = new Map( + [...this.entries.values()].map((entry) => [ + pathKey(entry.moved ?? entry.path), + entry, + ]), + ); + result.attachments = 0; + const files = new Map(); + for (const file of await this.options.local.list()) { + if (exclusion(file.path, this.options.configDir)) { + if (isNotePath(file.path)) result.unsyncable.push(file.path); + continue; + } + if (!isNotePath(file.path)) { + result.attachments++; + continue; + } + const key = pathKey(file.path); + files.set(key, [...(files.get(key) ?? []), file]); + } + const notes: LocalNote[] = []; + for (const [key, group] of files) { + const entry = byPath.get(key); + // Names that differ only in case are one note to NOTE: only the synced one syncs. + const file = + group.length === 1 + ? group[0] + : group.find( + (candidate) => candidate.path === (entry?.moved ?? entry?.path), + ); + for (const other of group) + if (other !== file) result.unsyncable.push(other.path); + if (!file) continue; + if (entry && entry.mtime === file.mtime && entry.size === file.size) { + notes.push({ path: file.path, hash: entry.hash }); + continue; + } + const source = await this.options.local.read(file.path); + const hash = await sha256(source); + // The listing's stat predates the read, so a later edit still shows as a new stat. + if (entry?.hash === hash) { + entry.mtime = file.mtime; + entry.size = file.size; + this.dirty = true; + } + notes.push({ path: file.path, hash, source }); + } + return notes; + } + + private async apply(step: Step, result: RoundResult) { + try { + if (step.kind === "forget") this.entries.delete(step.id); + else if (step.kind === "delete-remote") { + await this.options.remote.remove(step.id); + this.remoteChanged(); + this.entries.delete(step.id); + } else if (step.kind === "delete-local") { + if ((await this.unchanged(step.local)) && !this.stopped) { + await this.options.local.trash(step.local.path); + this.entries.delete(step.id); + } + } else await this.update(step); + result.applied++; + } catch (error) { + result.failed.push({ + path: + step.kind === "update" + ? step.path + : step.kind === "delete-local" + ? step.local.path + : step.id, + error: error instanceof Error ? error.message : String(error), + }); + this.remoteChanged(); + } + } + + /** The local file still holds what the plan saw: its text, or the hash of text it didn't need to read. */ + private async unchanged(local: LocalNote): Promise { + const current = await this.options.local.read(local.path); + return (await sha256(current)) === local.hash ? current : null; + } + + private async update(step: Extract) { + const { id, path, content, local, remote, copy } = step; + const { local: files, remote: vault } = this.options; + let revision = remote?.revision ?? ""; + let digest = remote?.digest ?? ""; + let hash = remote?.hash ?? local?.hash ?? ""; + if (copy) { + const source = local?.source; + if (source === undefined) throw new Error("Conflict without local text"); + if (!(await files.create(copy, source))) + throw new Error(`${copy} already exists`); + const copyId = this.newId(); + const saved = await vault.saveNote({ id: copyId, path: copy, source }); + this.remoteChanged(); + this.record({ + id: copyId, + path: copy, + hash: local?.hash ?? "", + ...saved, + }); + } + if (content === "local") { + const source = local?.source; + if (source === undefined) throw new Error("Push without local text"); + ({ revision, digest } = await vault.saveNote({ + id, + path, + source, + revision: remote?.revision, + digest: remote?.digest, + })); + this.remoteChanged(); + hash = local?.hash ?? ""; + } else if (remote && remote.path !== path) { + await vault.rename(id, path); + this.remoteChanged(); + } + if (this.stopped) throw new Error("Sync stopped"); + if (local && local.path !== path) { + if (!(await files.move(local.path, path))) + throw new Error(`Couldn't move ${local.path} to ${path}`); + // Recorded now, so a write that fails next still finds the file where it went. + const entry = this.entries.get(id); + if (entry) entry.moved = path; + } + if (content === "remote" && remote) { + const written = local + ? await this.replaceAt(path, local, remote.source) + : await files.create(path, remote.source); + if (!written) throw new Error(`${path} changed while syncing`); + } + this.record({ id, path, hash, revision, digest }); + } + + private async replaceAt(path: string, local: LocalNote, next: string) { + const current = await this.unchanged({ ...local, path }); + if (current === null) return false; + return current === next || this.options.local.replace(path, current, next); + } + + /** + * Records what a step left on both sides. Its stat stays unknown, so the + * next scan reads the file once and takes the stat from that listing: one + * taken now could already include an edit made after this write. + */ + private record(entry: Pick & Partial) { + this.entries.set(entry.id, { + revision: "", + digest: "", + ...entry, + mtime: 0, + size: 0, + }); + } +} diff --git a/src/fetch.ts b/src/fetch.ts new file mode 100644 index 0000000..ab17ec5 --- /dev/null +++ b/src/fetch.ts @@ -0,0 +1,71 @@ +import type { NoteDeviceFetch } from "./device"; + +/** The part of Obsidian's `requestUrl` this adapter uses. */ +export type RequestUrl = (request: { + url: string; + method: string; + headers: Record; + body?: string | ArrayBuffer; + throw: false; +}) => Promise<{ + status: number; + headers: Record; + arrayBuffer: ArrayBuffer; +}>; + +const NULL_BODY = new Set([101, 103, 204, 205, 304]); + +async function bodyOf( + body: RequestInit["body"], +): Promise { + if (body === undefined || body === null) return undefined; + if (typeof body === "string") return body; + if (body instanceof ArrayBuffer) return body; + if (ArrayBuffer.isView(body)) + return body.buffer.slice( + body.byteOffset, + body.byteOffset + body.byteLength, + ) as ArrayBuffer; + if (body instanceof Blob) return body.arrayBuffer(); + if (body instanceof URLSearchParams) return body.toString(); + throw new Error("Unsupported request body"); +} + +function aborted(signal: AbortSignal | null | undefined): Promise { + return new Promise((_, reject) => { + if (!signal) return; + if (signal.aborted) reject(signal.reason); + signal.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + }); +} + +/** + * `fetch` over Obsidian's `requestUrl`, which isn't held to CORS on desktop + * or mobile. `requestUrl` can't be cancelled, so an abort only stops waiting: + * the device client already refuses anything that arrives after its deadline. + */ +export function requestUrlFetch(requestUrl: RequestUrl): NoteDeviceFetch { + return async (url, init) => { + init.signal?.throwIfAborted(); + const headers: Record = {}; + new Headers(init.headers).forEach((value, key) => { + headers[key] = value; + }); + const response = await Promise.race([ + requestUrl({ + url, + method: init.method ?? "GET", + headers, + body: await bodyOf(init.body), + throw: false, + }), + aborted(init.signal), + ]); + return new Response( + NULL_BODY.has(response.status) ? null : response.arrayBuffer, + { status: response.status, headers: response.headers }, + ); + }; +} diff --git a/src/hash.ts b/src/hash.ts new file mode 100644 index 0000000..18d5b54 --- /dev/null +++ b/src/hash.ts @@ -0,0 +1,9 @@ +const encoder = new TextEncoder(); + +/** Hex SHA-256 of `text`'s UTF-8 bytes. */ +export async function sha256(text: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", encoder.encode(text)); + return Array.from(new Uint8Array(digest), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); +} diff --git a/src/index-store.ts b/src/index-store.ts new file mode 100644 index 0000000..b458f28 --- /dev/null +++ b/src/index-store.ts @@ -0,0 +1,89 @@ +import type { SyncIndex } from "./engine"; +import type { Entry } from "./plan"; + +const STORE = "index"; +const KEY = "entries"; + +function request(req: IDBRequest): Promise { + return new Promise((resolve, reject) => { + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); +} + +/** + * The sync index in this app's IndexedDB, one database per linked device: + * outside the vault folder, so git or another sync tool never copies it to a + * machine where it would describe a different link. + */ +export class IndexedDbIndex implements SyncIndex { + constructor( + private readonly name: string, + private readonly factory: IDBFactory = indexedDB, + ) {} + + private async open(): Promise { + const req = this.factory.open(this.name, 1); + req.onupgradeneeded = () => req.result.createObjectStore(STORE); + return request(req); + } + + async load(): Promise { + const db = await this.open(); + try { + const value = await request( + db.transaction(STORE).objectStore(STORE).get(KEY), + ); + return Array.isArray(value) ? (value as Entry[]) : []; + } finally { + db.close(); + } + } + + async save(entries: Entry[]): Promise { + const db = await this.open(); + try { + const transaction = db.transaction(STORE, "readwrite"); + transaction.objectStore(STORE).put(entries, KEY); + await new Promise((resolve, reject) => { + transaction.oncomplete = () => resolve(); + transaction.onerror = () => reject(transaction.error); + transaction.onabort = () => reject(transaction.error); + }); + } finally { + db.close(); + } + } + + async clear(): Promise { + await request(this.factory.deleteDatabase(this.name)); + } +} + +/** + * Deletes the device client's local database for one NOTE vault, every key + * epoch of it, so an unlinked vault leaves no ciphertext in this app. A + * database another window still holds open is left after `timeoutMs`. + */ +export async function forgetVaultDatabases( + did: string, + vault: string, + factory: IDBFactory = indexedDB, + timeoutMs = 5_000, +) { + const name = `flow-note:${did}:${vault}`; + const names = (await factory.databases?.()) ?? []; + await Promise.all( + names + .map((database) => database.name) + .filter( + (database) => database === name || database?.startsWith(`${name}:`), + ) + .map((database) => + Promise.race([ + request(factory.deleteDatabase(database ?? name)), + new Promise((resolve) => setTimeout(resolve, timeoutMs)), + ]), + ), + ); +} diff --git a/src/lock.ts b/src/lock.ts new file mode 100644 index 0000000..042115b --- /dev/null +++ b/src/lock.ts @@ -0,0 +1,25 @@ +/** + * Takes the Web Lock `name` without waiting and holds it until the returned + * function is called; null when someone else holds it. Locks span every + * window of this app's origin, so two vaults open at once can't both run a + * device transport on the same account. Without Web Locks, nothing is held. + */ +export function holdLock( + name: string, + locks: LockManager | undefined = globalThis.navigator?.locks, +): Promise<(() => void) | null> { + if (!locks) return Promise.resolve(() => {}); + return new Promise((resolve, reject) => { + let release = () => {}; + const held = new Promise((done) => { + release = done; + }); + locks + .request(name, { ifAvailable: true }, async (lock) => { + if (!lock) return resolve(null); + resolve(release); + await held; + }) + .catch(reject); + }); +} diff --git a/src/main.ts b/src/main.ts index a556c21..bcd828a 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,3 +1,160 @@ -import { Plugin } from "obsidian"; +import { Notice, Plugin, requestUrl, type TAbstractFile } from "obsidian"; +import { SyncController } from "./controller"; +import { Custody } from "./custody"; +import { + createDeviceSeed, + linkDevice, + openDeviceVault, + pulledStatus, + SYNC_LOCKED, + type TrustLoss, +} from "./device"; +import { requestUrlFetch } from "./fetch"; +import { forgetVaultDatabases, IndexedDbIndex } from "./index-store"; +import { holdLock } from "./lock"; +import { confirm, LinkModal } from "./obsidian/modals"; +import { NoteSyncSettingTab, statusText } from "./obsidian/settings"; +import { + custodyNote, + defaultLabel, + deviceNamespace, + obsidianSecrets, + obsidianVault, +} from "./obsidian/vault"; -export default class NoteSyncPlugin extends Plugin {} +/** Flow ID, which links devices and relays the encrypted vault to the person's PDS. */ +const FLOW_ID = "https://id.flow.industries"; + +export default class NoteSyncPlugin extends Plugin { + controller!: SyncController; + private settingTab!: NoteSyncSettingTab; + private linkModal: LinkModal | null = null; + + override async onload() { + const namespace = deviceNamespace(this.app); + const statusBar = this.addStatusBarItem(); + statusBar.onClickEvent(() => void this.controller.syncNow()); + this.controller = new SyncController({ + custody: new Custody(obsidianSecrets(this.app), namespace), + device: { + createDeviceSeed, + linkDevice, + openDeviceVault, + locked: SYNC_LOCKED, + pulled: pulledStatus, + }, + host: FLOW_ID, + fetch: requestUrlFetch(requestUrl), + local: obsidianVault(this.app), + configDir: this.app.vault.configDir, + indexFor: (did, vault) => + new IndexedDbIndex(`flow-note-sync:${namespace}:${did}:${vault}`), + hold: holdLock, + forgetLocalDatabase: (did, vault) => forgetVaultDatabases(did, vault), + confirmDeletions: ({ local, remote }) => + confirm( + this.app, + "Delete these notes?", + `This sync would move ${local} notes here and ${remote} notes in NOTE to the trash. That can mean they were deleted on purpose, or that one side looks empty when it isn't. Nothing is deleted unless you confirm.`, + "Move to trash", + { warning: true }, + ), + onChange: () => { + statusBar.setText( + statusText(this.controller.phase, this.controller.lastRound), + ); + this.linkModal?.render(); + if (this.settingTab.containerEl.isShown()) this.settingTab.display(); + }, + onTrustLoss: (loss) => trustLossNotice(loss), + notify: (message) => new Notice(`NOTE Sync: ${message}`, 0), + }); + this.settingTab = new NoteSyncSettingTab(this.app, this); + this.addSettingTab(this.settingTab); + + this.addCommand({ + id: "sync-now", + name: "Sync now", + callback: () => void this.controller.syncNow(), + }); + this.addCommand({ + id: "link", + name: "Link this vault", + callback: () => this.openLink(), + }); + this.addCommand({ + id: "unlink", + name: "Unlink this vault", + callback: async () => { + if ( + await confirm( + this.app, + "Unlink this vault?", + "Syncing stops and this vault forgets its device key. Your files stay here and in NOTE.", + "Unlink", + { warning: true }, + ) + ) + await this.controller.unlink(); + }, + }); + + this.app.workspace.onLayoutReady(() => { + const changed = (file: TAbstractFile) => { + if (file.path) this.controller.localChanged(); + }; + this.registerEvent(this.app.vault.on("create", changed)); + this.registerEvent(this.app.vault.on("modify", changed)); + this.registerEvent(this.app.vault.on("delete", changed)); + this.registerEvent( + this.app.vault.on("rename", (file, oldPath) => + this.controller.renamed(oldPath, file.path), + ), + ); + void this.controller.start(); + }); + } + + override onunload() { + this.linkModal?.close(); + this.controller.close(); + } + + openLink() { + this.linkModal?.close(); + const modal = new LinkModal( + this.app, + this.controller, + defaultLabel(), + () => + custodyNote(this.app).safe + ? Promise.resolve(true) + : confirm( + this.app, + "Store the device key unencrypted?", + custodyNote(this.app).text, + "Link anyway", + { warning: true }, + ), + ); + const close = modal.onClose.bind(modal); + modal.onClose = () => { + close(); + if (this.linkModal === modal) this.linkModal = null; + }; + this.linkModal = modal; + modal.open(); + } +} + +function trustLossNotice({ unsigned, stale }: TrustLoss) { + const lines = [ + unsigned.length + ? `Saved without another admin's signature, so their code there won't run by itself in NOTE until someone trusts it: ${unsigned.join(", ")}.` + : "", + stale.length + ? `Links to moved code were left as they were: ${stale.join(", ")}.` + : "", + ].filter(Boolean); + if (lines.length) new Notice(`NOTE Sync: ${lines.join(" ")}`, 15_000); +} diff --git a/src/obsidian/modals.ts b/src/obsidian/modals.ts new file mode 100644 index 0000000..36b54d5 --- /dev/null +++ b/src/obsidian/modals.ts @@ -0,0 +1,207 @@ +import { type App, Modal, Notice, Setting } from "obsidian"; +import type { LinkedAccount } from "../account"; +import type { SyncController } from "../controller"; +import type { LinkPrompt } from "../device"; + +/** Where approving a link happens; a verification address anywhere else is shown, never opened. */ +export const NOTE_ORIGIN = "https://note.flow.talk"; + +const linkPage = (prompt: LinkPrompt) => { + try { + const url = new URL(prompt.verificationUri); + return url.origin === NOTE_ORIGIN ? url.href : null; + } catch { + return null; + } +}; + +/** Asks a yes-or-no question; closing the modal answers no. */ +export function confirm( + app: App, + title: string, + message: string, + yes: string, + options: { warning?: boolean } = {}, +): Promise { + return new Promise((resolve) => { + let answered = false; + const modal = new Modal(app); + modal.setTitle(title); + modal.contentEl.createEl("p", { text: message }); + new Setting(modal.contentEl) + .addButton((button) => + button.setButtonText("Cancel").onClick(() => modal.close()), + ) + .addButton((button) => { + button.setButtonText(yes).onClick(() => { + answered = true; + modal.close(); + }); + if (options.warning) button.setWarning(); + else button.setCta(); + }); + modal.onClose = () => resolve(answered); + modal.open(); + }); +} + +export function accountName(account: LinkedAccount): string { + return account.handle ? `@${account.handle} (${account.did})` : account.did; +} + +/** + * Links this vault: asks for a label, shows the codes while the person + * approves in their browser, then asks them to confirm the account before + * anything syncs. + */ +export class LinkModal extends Modal { + private abort: AbortController | null = null; + private label: string; + private error: string | null = null; + private opened = false; + + constructor( + app: App, + private readonly controller: SyncController, + label: string, + private readonly beforeLink: () => Promise, + ) { + super(app); + this.label = label; + this.setTitle("Link to NOTE"); + } + + override onOpen() { + this.render(); + } + + override onClose() { + this.abort?.abort(new Error("Linking was cancelled.")); + this.contentEl.empty(); + } + + /** Redraws for the controller's current phase. */ + render() { + const { contentEl } = this; + const { phase } = this.controller; + contentEl.empty(); + if (this.error) + contentEl.createEl("p", { cls: "mod-warning", text: this.error }); + if (phase.kind === "linking") return this.renderPrompt(phase.prompt); + if (phase.kind === "confirm") return this.renderConfirm(phase.account); + if (phase.kind === "open" || phase.kind === "opening") { + contentEl.createEl("p", { text: "This vault is linked and syncing." }); + return; + } + contentEl.createEl("p", { + text: "This vault becomes a device on your NOTE notepad. You approve it once in your browser; after that it syncs without asking for your passkey.", + }); + new Setting(contentEl) + .setName("Device name") + .setDesc("Shown under Access in NOTE.") + .addText((text) => + text.setValue(this.label).onChange((value) => { + this.label = value; + }), + ); + new Setting(contentEl).addButton((button) => + button + .setButtonText("Link") + .setCta() + .onClick(() => void this.link()), + ); + } + + private renderPrompt(prompt: LinkPrompt | undefined) { + const { contentEl } = this; + if (!prompt) { + contentEl.createEl("p", { text: "Asking Flow ID for a code…" }); + return; + } + const page = linkPage(prompt); + if (page && !this.opened) { + this.opened = true; + window.open(page); + } + contentEl.createEl("p", { + text: page + ? "Your browser opened NOTE's link page. Sign in there if asked, check the code matches, and type the device code below." + : `Open ${NOTE_ORIGIN}/link in your browser, enter the code below, and type the device code.`, + }); + new Setting(contentEl).setName("Code").setDesc(prompt.userCode); + const secret = new Setting(contentEl) + .setName("Device code") + .setDesc( + "Type it on the link page. Never send it to anyone: it proves this vault is the device you approve.", + ); + secret.controlEl.createEl("span", { + cls: "flow-note-code", + text: prompt.pairingCode, + }); + const row = new Setting(contentEl); + if (page) + row.addButton((button) => + button + .setButtonText("Open link page again") + .onClick(() => window.open(page)), + ); + row.addButton((button) => + button.setButtonText("Cancel").onClick(() => this.close()), + ); + } + + private renderConfirm(account: LinkedAccount) { + const { contentEl } = this; + contentEl.createEl("p", { text: "This vault is linked to this account:" }); + contentEl.createEl("p", { + cls: "flow-note-code", + text: accountName(account), + }); + contentEl.createEl("p", { + text: account.handle + ? "Your notes will sync with this account's NOTE notepad. Continue only if it's yours." + : "The account's handle couldn't be confirmed, so this is its DID. Your notes will sync with this account's NOTE notepad. Continue only if it's yours.", + }); + new Setting(contentEl) + .addButton((button) => + button + .setButtonText("This isn't my account") + .setWarning() + .onClick(async () => { + await this.controller.unlink(); + new Notice( + "Unlinked. Remove this device under Access in NOTE, in the account it was linked to, if you can.", + 0, + ); + this.close(); + }), + ) + .addButton((button) => + button + .setButtonText("Start syncing") + .setCta() + .onClick(async () => { + this.close(); + await this.controller.confirm(); + }), + ); + } + + private async link() { + if (!(await this.beforeLink())) return; + this.error = null; + this.abort = new AbortController(); + try { + await this.controller.link( + this.label.trim() || "Obsidian", + this.abort.signal, + ); + } catch (error) { + if (!this.abort.signal.aborted) + this.error = error instanceof Error ? error.message : String(error); + } finally { + this.abort = null; + this.render(); + } + } +} diff --git a/src/obsidian/settings.ts b/src/obsidian/settings.ts new file mode 100644 index 0000000..2799390 --- /dev/null +++ b/src/obsidian/settings.ts @@ -0,0 +1,155 @@ +import { type App, type Plugin, PluginSettingTab, Setting } from "obsidian"; +import type { Phase, SyncController } from "../controller"; +import type { RoundResult } from "../engine"; +import { accountName, confirm } from "./modals"; +import { custodyNote } from "./vault"; + +/** The status bar's words for each phase. */ +export function statusText(phase: Phase, round: RoundResult | null): string { + switch (phase.kind) { + case "unlinked": + return "NOTE: not linked"; + case "linking": + return "NOTE: linking"; + case "confirm": + return "NOTE: confirm account"; + case "opening": + return "NOTE: connecting"; + case "removed": + return "NOTE: device removed"; + case "stopped": + return "NOTE: stopped"; + case "open": { + const failed = round?.failed.length ?? 0; + const held = (round?.held.local ?? 0) + (round?.held.remote ?? 0); + return [ + `NOTE: ${phase.status}`, + failed ? `${failed} not synced` : "", + held ? `${held} deletions held` : "", + ] + .filter(Boolean) + .join(" · "); + } + } +} + +export interface SettingsHost extends Plugin { + controller: SyncController; + openLink(): void; +} + +export class NoteSyncSettingTab extends PluginSettingTab { + constructor( + app: App, + private readonly host: SettingsHost, + ) { + super(app, host); + } + + override display() { + const { containerEl } = this; + const { controller } = this.host; + const { phase } = controller; + containerEl.empty(); + const account = controller.account(); + new Setting(containerEl) + .setName("Status") + .setDesc( + phase.kind === "removed" || phase.kind === "stopped" + ? phase.message + : statusText(phase, controller.lastRound), + ); + if (account) + new Setting(containerEl).setName("Account").setDesc(accountName(account)); + + const linked = phase.kind === "open" || phase.kind === "opening"; + if (!linked) + new Setting(containerEl) + .setName( + phase.kind === "confirm" + ? "Confirm the linked account" + : "Link this vault", + ) + .setDesc( + "Approve this vault once in your browser at note.flow.talk. Nothing syncs until you confirm which account it linked to.", + ) + .addButton((button) => + button + .setButtonText(phase.kind === "confirm" ? "Review" : "Link") + .setCta() + .onClick(() => this.host.openLink()), + ); + if (phase.kind === "stopped") + new Setting(containerEl).setName("Try again").addButton((button) => + button.setButtonText("Retry").onClick(async () => { + await controller.syncNow(); + this.display(); + }), + ); + if (linked) { + new Setting(containerEl) + .setName("Sync now") + .setDesc( + "Syncs both ways now, and asks again about any deletions you held back.", + ) + .addButton((button) => + button.setButtonText("Sync now").onClick(async () => { + await controller.syncNow(); + this.display(); + }), + ); + this.roundDetails(containerEl, controller.lastRound); + } + if (account || phase.kind === "confirm" || linked) + new Setting(containerEl) + .setName("Unlink") + .setDesc( + "Stops syncing and forgets this vault's device key and tokens. Your files stay. Remove the device under Access in NOTE too.", + ) + .addButton((button) => + button + .setButtonText("Unlink") + .setWarning() + .onClick(async () => { + if ( + await confirm( + this.app, + "Unlink this vault?", + "Syncing stops and this vault forgets its device key. Your files stay here and in NOTE.", + "Unlink", + { warning: true }, + ) + ) + await controller.unlink(); + this.display(); + }), + ); + + const custody = custodyNote(this.app); + new Setting(containerEl) + .setName("Device key") + .setDesc(custody.text) + .setClass(custody.safe ? "flow-note-safe" : "mod-warning"); + } + + private roundDetails(containerEl: HTMLElement, round: RoundResult | null) { + if (!round) return; + const lines = [ + ...round.failed + .slice(0, 5) + .map(({ path, error }) => `${path || "Sync"}: ${error}`), + round.attachments + ? `${round.attachments} attachments stay on this device: this version syncs Markdown and MDX notes only.` + : "", + round.unsyncable.length + ? `Not synced, because one side can't store the name: ${round.unsyncable.slice(0, 5).join(", ")}${round.unsyncable.length > 5 ? "…" : ""}` + : "", + round.held.local || round.held.remote + ? `Held back: ${round.held.local} deletions here and ${round.held.remote} in NOTE. Sync now to review them.` + : "", + ].filter(Boolean); + if (!lines.length) return; + const details = new Setting(containerEl).setName("Last sync"); + for (const line of lines) details.descEl.createDiv({ text: line }); + } +} diff --git a/src/obsidian/vault.ts b/src/obsidian/vault.ts new file mode 100644 index 0000000..ba3ead5 --- /dev/null +++ b/src/obsidian/vault.ts @@ -0,0 +1,156 @@ +import { type App, MarkdownView, normalizePath, Platform } from "obsidian"; +import type { SecretBackend } from "../custody"; +import type { LocalVault } from "../engine"; +import { parentOf, pathKey } from "../paths"; + +/** The Obsidian vault through its Vault API; renames never rewrite links, since NOTE already repaired them. */ +export function obsidianVault(app: App): LocalVault { + const { vault, fileManager } = app; + const fileAt = (path: string) => vault.getFileByPath(normalizePath(path)); + const free = async (path: string) => + !vault.getAbstractFileByPath(path) && !(await vault.adapter.exists(path)); + /** An editor holding text it hasn't saved yet: writing under it could lose the typing. */ + const unsaved = (path: string, disk: string) => + app.workspace + .getLeavesOfType("markdown") + .some( + (leaf) => + leaf.view instanceof MarkdownView && + leaf.view.file?.path === path && + leaf.view.getViewData() !== disk, + ); + const ensureFolder = async (path: string) => { + const folder = parentOf(path); + if (folder && !vault.getAbstractFileByPath(folder)) + await vault.createFolder(folder); + }; + return { + async list() { + return vault.getFiles().map((file) => ({ + path: file.path, + mtime: file.stat.mtime, + size: file.stat.size, + })); + }, + async read(path) { + const file = fileAt(path); + if (!file) throw new Error(`${path} is gone`); + return vault.read(file); + }, + async create(path, source) { + const target = normalizePath(path); + if (!(await free(target))) return false; + await ensureFolder(target); + await vault.create(target, source); + return true; + }, + async replace(path, expected, next) { + const file = fileAt(path); + if (!file) return false; + let replaced = false; + await vault.process(file, (current) => { + if (current !== expected || unsaved(file.path, current)) return current; + replaced = true; + return next; + }); + return replaced; + }, + async move(from, to) { + const file = fileAt(from); + const target = normalizePath(to); + const caseOnly = pathKey(from) === pathKey(target); + if (!file || (!caseOnly && !(await free(target)))) return false; + await ensureFolder(target); + await vault.rename(file, target); + return true; + }, + async trash(path) { + const file = fileAt(path); + if (!file) return; + if (unsaved(file.path, await vault.read(file))) + throw new Error(`${path} has unsaved changes`); + await fileManager.trashFile(file); + }, + }; +} + +type Secrets = App["secretStorage"] & { + deleteSecret?(id: string): boolean; + isEncryptionAvailable?(): boolean; +}; + +/** Obsidian's secret storage, kept outside the vault folder in the app's own storage. */ +export function obsidianSecrets(app: App): SecretBackend { + const storage: Secrets = app.secretStorage; + return { + get: (id) => storage.getSecret(id) || null, + set: (id, value) => storage.setSecret(id, value), + delete: (id) => { + if (storage.deleteSecret) storage.deleteSecret(id); + else storage.setSecret(id, ""); + }, + }; +} + +/** Where this platform's secret storage keeps the device's keys, in words for settings. */ +export function custodyNote(app: App): { text: string; safe: boolean } { + const storage: Secrets = app.secretStorage; + if (Platform.isIosApp) + return { + text: "Stored in the iOS Keychain through Obsidian's secret storage.", + safe: true, + }; + if (Platform.isAndroidApp) + return { + text: "Stored in Android's Keystore-backed secure storage through Obsidian's secret storage.", + safe: true, + }; + const keychain = Platform.isMacOS + ? "the macOS Keychain" + : Platform.isWin + ? "Windows DPAPI" + : "your keyring (libsecret or KWallet)"; + const encrypted = storage.isEncryptionAvailable?.(); + if (encrypted === undefined && Platform.isLinux) + return { + text: "Obsidian's secret storage encrypts the device key with your keyring (libsecret or KWallet) when it finds one; this version of Obsidian doesn't say whether it did. Without one, the key is kept unencrypted in Obsidian's app data, outside the vault.", + safe: false, + }; + if (encrypted === false) + return { + text: "Obsidian can't reach a keyring on this computer, so its secret storage keeps the device key unencrypted in Obsidian's app data, outside the vault. Install a keyring (libsecret or KWallet) before linking to have it encrypted.", + safe: false, + }; + return { + text: `Encrypted with ${keychain} through Obsidian's secret storage, in Obsidian's app data outside the vault.`, + safe: true, + }; +} + +/** A random name for this vault's link on this device, kept in Obsidian's per-vault local storage, never in the vault folder. */ +export function deviceNamespace(app: App): string { + const key = "flow-note-device"; + const saved: unknown = app.loadLocalStorage(key); + if (typeof saved === "string" && /^[0-9a-f]{16}$/u.test(saved)) return saved; + const fresh = Array.from(crypto.getRandomValues(new Uint8Array(8)), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); + app.saveLocalStorage(key, fresh); + return fresh; +} + +/** The label NOTE shows for this vault under Access. */ +export function defaultLabel(): string { + const platform = Platform.isIosApp + ? "iOS" + : Platform.isAndroidApp + ? "Android" + : Platform.isMacOS + ? "macOS" + : Platform.isWin + ? "Windows" + : Platform.isLinux + ? "Linux" + : "this device"; + return `Obsidian on ${platform}`; +} diff --git a/src/paths.ts b/src/paths.ts new file mode 100644 index 0000000..a784a16 --- /dev/null +++ b/src/paths.ts @@ -0,0 +1,62 @@ +/** Notes NOTE stores as text; every other file is an attachment. */ +export const isNotePath = (path: string) => /\.mdx?$/iu.test(path); + +/** + * The key NOTE compares paths by: two paths with the same key can't both + * exist in a vault, and a case-insensitive file system treats them as one. + */ +export function pathKey(path: string): string { + return /^\p{ASCII}*$/u.test(path) + ? path.toLowerCase() + : path.normalize("NFC").toLocaleLowerCase("en-US"); +} + +const MAX_SEGMENT_BYTES = 255; +const MAX_DEPTH = 64; +const MAX_PATH_LENGTH = 4096; +const encoder = new TextEncoder(); + +/** Whether NOTE accepts `name` as one file or folder name, by the same rules its vault model enforces. */ +export function isNoteSafeName(name: string): boolean { + return !( + !name || + encoder.encode(name).length > MAX_SEGMENT_BYTES || + name === "." || + name === ".." || + /[/\\<>:"|?*]/u.test(name) || + Array.from(name).some((char) => { + const code = char.charCodeAt(0); + return code < 32 || code === 127; + }) || + /[. ]$/u.test(name) || + /^[A-Za-z]:/u.test(name) || + /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(name) + ); +} + +export type Exclusion = "config" | "hidden" | "unsafe-name"; + +/** + * Why a path stays out of sync in either direction, or null when it syncs. + * Obsidian's config folder holds plugin code, so nothing is ever read from + * or written into it, and neither is any hidden file or folder. + */ +export function exclusion(path: string, configDir: string): Exclusion | null { + const segments = path.split("/"); + const config = pathKey(configDir.replace(/\/+$/u, "")); + if (pathKey(segments[0] ?? "") === config) return "config"; + if (segments.some((segment) => segment.startsWith("."))) return "hidden"; + if ( + path.length > MAX_PATH_LENGTH || + segments.length > MAX_DEPTH || + !segments.every(isNoteSafeName) + ) + return "unsafe-name"; + return null; +} + +export const parentOf = (path: string) => { + const slash = path.lastIndexOf("/"); + return slash === -1 ? "" : path.slice(0, slash); +}; +export const nameOf = (path: string) => path.slice(path.lastIndexOf("/") + 1); diff --git a/src/plan.ts b/src/plan.ts new file mode 100644 index 0000000..d4cf658 --- /dev/null +++ b/src/plan.ts @@ -0,0 +1,261 @@ +import { conflictPath } from "./conflicts"; +import { pathKey } from "./paths"; + +/** What both sides agreed a note was at the last sync. */ +export interface Entry { + id: string; + path: string; + /** Where the file is now, when it was renamed here since the last sync. */ + moved?: string; + /** The remote revision synced; empty until a read or a save names it. */ + revision: string; + digest: string; + /** SHA-256 of the source synced. */ + hash: string; + /** The local file's stat at the last sync, so an unchanged file isn't read again. */ + mtime: number; + size: number; +} +/** A note file in the Obsidian vault; `source` is read whenever it may have changed. */ +export interface LocalNote { + path: string; + hash: string; + source?: string; +} +export interface RemoteNote { + id: string; + path: string; + source: string; + revision?: string; + digest?: string; + hash: string; +} + +/** + * One note's change. An update writes `content`'s side over the other at + * `path` (`same`: only paths or the index change), and `copy` keeps the + * local text as a new note beside it when both sides edited it. + */ +export type Step = + | { + kind: "update"; + id: string; + path: string; + content: "local" | "remote" | "same"; + local?: LocalNote; + remote?: RemoteNote; + copy?: string; + } + | { kind: "delete-local"; id: string; local: LocalNote } + | { kind: "delete-remote"; id: string } + | { kind: "forget"; id: string }; + +export interface PlanInput { + entries: readonly Entry[]; + local: readonly LocalNote[]; + remote: readonly RemoteNote[]; + newId?: () => string; +} + +const currentPath = (entry: Entry) => entry.moved ?? entry.path; +/** The same name, whatever Unicode normalization the file system or another device chose; case still counts. */ +const samePath = (a: string, b: string) => + a.normalize("NFC") === b.normalize("NFC"); + +/** + * Pairs each entry with its local file. A rename Obsidian reported claims its + * file before an entry still at that path, which the person deleted first. A + * file renamed while sync wasn't watching shows up as its entry's file gone + * and a new file with the same text: they pair when exactly one matches. + */ +function claimLocal( + entries: readonly Entry[], + local: Map, +): Map { + const owners = new Map(); + const byMove = [...entries].sort( + (a, b) => Number(!a.moved) - Number(!b.moved), + ); + for (const entry of byMove) { + const key = pathKey(currentPath(entry)); + if (local.has(key) && !owners.has(key)) owners.set(key, entry); + } + const found = new Map(); + for (const [key, entry] of owners) { + const note = local.get(key); + if (note) found.set(entry.id, note); + } + const unclaimed = [...local] + .filter(([key]) => !owners.has(key)) + .map(([, note]) => note); + const taken = new Set(); + for (const entry of entries) { + if (found.has(entry.id)) continue; + const matches = unclaimed.filter((note) => note.hash === entry.hash); + const [match] = matches; + if (matches.length !== 1 || !match || taken.has(match)) continue; + taken.add(match); + found.set(entry.id, match); + } + return found; +} + +function updateOf( + entry: Entry, + local: LocalNote, + remote: RemoteNote, + newId: () => string, +): Step | null { + const localChanged = local.hash !== entry.hash; + const remoteChanged = remote.hash !== entry.hash; + const localMoved = !samePath(local.path, entry.path); + const remoteMoved = !samePath(remote.path, entry.path); + // Both renamed: the remote name wins, as every other device converges on it. + const path = remoteMoved || !localMoved ? remote.path : local.path; + let content: "local" | "remote" | "same" = "same"; + let copy: string | undefined; + if (localChanged && !remoteChanged) content = "local"; + else if (remoteChanged && !localChanged) content = "remote"; + else if (localChanged && remoteChanged && local.hash !== remote.hash) { + content = "remote"; + copy = conflictPath(path, newId); + } + if ( + content === "same" && + samePath(path, local.path) && + samePath(path, remote.path) && + samePath(path, entry.path) && + !entry.moved && + (remote.revision ?? "") === entry.revision + ) + return null; + return { kind: "update", id: entry.id, path, content, local, remote, copy }; +} + +/** + * Three-way reconciliation of one sync round: each entry is the base its + * note was at, and either side's change since then wins over the other's + * silence. An edit beats a deletion, a remote rename beats a local one, and + * when both sides edited, the remote text keeps the path while the local + * text becomes a conflict copy beside it, as NOTE resolves its own. Local + * paths must be unique by `pathKey`. + */ +export function plan({ + entries, + local: localNotes, + remote: remoteNotes, + newId = () => crypto.randomUUID(), +}: PlanInput): Step[] { + const local = new Map(localNotes.map((note) => [pathKey(note.path), note])); + const remote = new Map(remoteNotes.map((note) => [note.id, note])); + const claimed = claimLocal(entries, local); + const claimedLocal = new Set(); + const claimedRemote = new Set(); + const steps: Step[] = []; + + for (const entry of entries) { + const r = remote.get(entry.id); + const l = claimed.get(entry.id); + if (r) claimedRemote.add(r.id); + if (l) claimedLocal.add(pathKey(l.path)); + if (!l && !r) steps.push({ kind: "forget", id: entry.id }); + else if (!l && r) + steps.push( + r.hash === entry.hash + ? { kind: "delete-remote", id: entry.id } + : { + kind: "update", + id: r.id, + path: r.path, + content: "remote", + remote: r, + }, + ); + else if (l && !r) { + if (l.hash === entry.hash) + steps.push({ kind: "delete-local", id: entry.id, local: l }); + else { + steps.push({ kind: "forget", id: entry.id }); + steps.push({ + kind: "update", + id: newId(), + path: l.path, + content: "local", + local: l, + }); + } + } else if (l && r) { + const step = updateOf(entry, l, r, newId); + if (step) steps.push(step); + } + } + + for (const r of remoteNotes) { + if (claimedRemote.has(r.id)) continue; + const key = pathKey(r.path); + const l = claimedLocal.has(key) ? undefined : local.get(key); + if (l) claimedLocal.add(key); + if (!l) + steps.push({ + kind: "update", + id: r.id, + path: r.path, + content: "remote", + remote: r, + }); + else if (l.hash === r.hash) + steps.push({ + kind: "update", + id: r.id, + path: r.path, + content: "same", + local: l, + remote: r, + }); + else + steps.push({ + kind: "update", + id: r.id, + path: r.path, + content: "remote", + local: l, + remote: r, + copy: conflictPath(r.path, newId), + }); + } + + // A new file where a synced note is headed, or already is in NOTE, steps aside as a conflict copy. + const headed = new Set([ + ...remoteNotes.map((note) => pathKey(note.path)), + ...steps.flatMap((step) => + step.kind === "update" ? [pathKey(step.path)] : [], + ), + ]); + for (const [key, l] of local) + if (!claimedLocal.has(key)) + steps.push({ + kind: "update", + id: newId(), + path: headed.has(key) ? conflictPath(l.path, newId) : l.path, + content: "local", + local: l, + }); + + return steps.sort((a, b) => order(a) - order(b)); +} + +/** + * Remote deletions free their paths first, local edits land before remote + * renames (NOTE repairs links when it renames, which would otherwise race + * Obsidian's own link updates), and remote creates follow the renames that + * free their paths. Local writes come last, once the remote is settled. + */ +function order(step: Step): number { + if (step.kind === "delete-remote") return 0; + if (step.kind !== "update") return 4; + if (step.content === "local" && step.remote) + return step.remote.path === step.path ? 1 : 2; + if (step.remote && step.remote.path !== step.path) return 2; + if (step.content === "local") return 3; + return 5; +} diff --git a/tests/controller.test.ts b/tests/controller.test.ts new file mode 100644 index 0000000..d738f53 --- /dev/null +++ b/tests/controller.test.ts @@ -0,0 +1,243 @@ +import { describe, expect, test } from "bun:test"; +import type { SyncListener } from "@flow-industries/seal"; +import { + type ControllerOptions, + LOCKED_ELSEWHERE, + STRANDED, + SyncController, +} from "../src/controller"; +import { Custody, type SecretBackend } from "../src/custody"; +import type { DeviceVault } from "../src/device"; +import { sha256 } from "../src/hash"; +import { MemoryIndex, MemoryRemote, MemoryVault } from "./fakes"; + +class Secrets implements SecretBackend { + values = new Map(); + get = (id: string) => this.values.get(id) ?? null; + set = (id: string, value: string) => void this.values.set(id, value); + delete = (id: string) => void this.values.delete(id); +} +const did = "did:plc:abcdefghijklmnopqrstuvwx"; +const credentials = { + accessToken: "fnd_a", + refreshToken: "fndr_r", + deviceId: "device", + userId: "owner", + did, + accessExpiresAt: 1, +}; +const checkpoint = { + vault: "vault", + epoch: 1, + pinned: { statement: "s", sequence: 1, admins: ["a"], recipients: ["a"] }, + trust: "handed" as const, + runners: [], +}; + +/** A device vault over `MemoryRemote` whose sync reports `SYNCED` once `pull` lets it. */ +function deviceVault(remote: MemoryRemote, stranded = false) { + const listeners = new Set(); + const state = { stopped: false, pull: true }; + const vault = { + read: () => remote.read().then((view) => ({ ...view, folders: [] })), + saveNote: (note) => remote.saveNote(note), + rename: (id, path) => remote.rename(id, path), + remove: (id) => remote.remove(id), + compose: async () => ({ selectedId: "" }), + sync: async () => { + if (state.pull) + for (const listener of listeners) await listener("Synced"); + }, + subscribe: (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + subscribeChanges: () => () => {}, + subscribeTrustLoss: () => () => {}, + stop: () => { + state.stopped = true; + }, + ...(stranded && { + stranded: { count: 1, download: async () => new Blob() }, + }), + } as DeviceVault; + return { vault, state }; +} + +async function harness( + options: { + opened?: Promise; + stranded?: boolean; + held?: boolean; + confirmed?: boolean; + } = {}, +) { + const secrets = new Secrets(); + const custody = new Custody(secrets, "0123456789abcdef"); + custody.saveSeed(new Uint8Array(32).fill(1)); + await custody.credentials.write(credentials); + await custody.checkpoints.write(checkpoint); + if (options.confirmed ?? true) custody.confirmAccount({ did }); + const local = new MemoryVault(); + const remote = new MemoryRemote(); + const index = new MemoryIndex(); + const device = deviceVault(remote, options.stranded); + const forgotten: string[] = []; + const notices: string[] = []; + const controllerOptions: ControllerOptions = { + custody, + device: { + createDeviceSeed: () => new Uint8Array(32).fill(2), + linkDevice: () => new Promise(() => {}), + openDeviceVault: async () => { + await options.opened; + return device.vault; + }, + locked: "Locked", + pulled: (status) => status === "Synced", + }, + host: "https://id.example", + fetch: async () => new Response(null, { status: 404 }), + local, + configDir: ".obsidian", + indexFor: () => index, + hold: async () => (options.held ? null : () => {}), + forgetLocalDatabase: async (owner, vault) => { + forgotten.push(`${owner}:${vault}`); + }, + confirmDeletions: async () => true, + onChange: () => {}, + onTrustLoss: () => {}, + notify: (message) => notices.push(message), + }; + const controller = new SyncController(controllerOptions); + return { + controller, + custody, + secrets, + local, + remote, + index, + device, + forgotten, + notices, + }; +} + +describe("controller", () => { + test("syncs only after the device has read the vault since it opened", async () => { + const h = await harness(); + h.device.state.pull = false; + h.local.put("Here.md", "local"); + await h.controller.start(); + await h.controller.syncNow(); + expect(h.remote.notes.size).toBe(0); + h.device.state.pull = true; + await h.controller.syncNow(); + expect(h.remote.byPath("Here.md")?.source).toBe("local"); + h.controller.close(); + }); + + test("an unconfirmed link stays unconfirmed across a restart", async () => { + const h = await harness({ confirmed: false }); + h.local.put("Here.md", "local"); + await h.controller.start(); + expect(h.controller.phase.kind).toBe("confirm"); + await h.controller.syncNow(); + expect(h.remote.notes.size).toBe(0); + }); + + test("a vault closed or unlinked while it opens never opens", async () => { + for (const interrupt of ["close", "unlink"] as const) { + const opened = Promise.withResolvers(); + const h = await harness({ opened: opened.promise }); + h.local.put("Here.md", "local"); + const starting = h.controller.start(); + await Bun.sleep(0); + if (interrupt === "close") h.controller.close(); + else await h.controller.unlink(); + opened.resolve(); + await starting; + await Bun.sleep(5); + expect(h.controller.phase.kind).not.toBe("open"); + expect(h.device.state.stopped).toBe(true); + expect(h.remote.notes.size).toBe(0); + if (interrupt === "unlink") { + expect(h.controller.phase.kind).toBe("unlinked"); + expect(h.custody.seed()).toBeNull(); + } + } + }); + + test("a link started while a restart names the old account wins", async () => { + const h = await harness({ confirmed: false }); + const restarting = h.controller.start(); + void h.controller.link("Obsidian", new AbortController().signal); + await restarting; + expect(h.controller.phase.kind).toBe("linking"); + }); + + test("another vault syncing the same account stops this one, and keeps its database on unlink", async () => { + const h = await harness({ held: true }); + await h.controller.start(); + expect(h.controller.phase).toEqual({ + kind: "stopped", + message: LOCKED_ELSEWHERE, + }); + await h.controller.unlink(); + expect(h.forgotten).toEqual([]); + expect(h.custody.seed()).toBeNull(); + }); + + test("unlinking forgets the device's database and the sync index", async () => { + const h = await harness(); + await h.controller.start(); + await h.controller.syncNow(); + h.index.entries = [ + { + id: "a", + path: "A.md", + revision: "r", + digest: "d", + hash: "h", + mtime: 1, + size: 1, + }, + ]; + await h.controller.unlink(); + expect(h.forgotten).toEqual([`${did}:vault`]); + expect(h.index.entries).toEqual([]); + expect(h.secrets.values.has("flow-note-0123456789abcdef-tokens")).toBe( + false, + ); + }); + + test("edits a key rotation stranded are kept as conflict copies, not overwritten", async () => { + const h = await harness({ stranded: true }); + const edit = "edit the rotation stranded"; + h.local.put("A.md", edit); + h.remote.put("a", "A.md", "NOTE's older text"); + // The index counts the edit as synced: it reached the device's outbox before the rotation. + const [file] = await h.local.list(); + h.index.entries = [ + { + id: "a", + path: "A.md", + revision: "gone", + digest: "gone", + hash: await sha256(edit), + mtime: file?.mtime ?? 0, + size: file?.size ?? 0, + }, + ]; + await h.controller.start(); + await h.controller.syncNow(); + expect(h.notices).toEqual([STRANDED]); + expect(h.local.text("A.md")).toBe("NOTE's older text"); + const copy = [...h.local.files.keys()].find((path) => + path.startsWith("A conflict "), + ); + expect(h.local.text(copy ?? "")).toBe("edit the rotation stranded"); + h.controller.close(); + }); +}); diff --git a/tests/custody.test.ts b/tests/custody.test.ts new file mode 100644 index 0000000..2507c18 --- /dev/null +++ b/tests/custody.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, test } from "bun:test"; +import { Custody, type SecretBackend } from "../src/custody"; +import type { DeviceCheckpoint, NoteDeviceCredentials } from "../src/device"; + +/** Obsidian's secret storage: ids are lowercase alphanumeric with dashes, at most 64 characters. */ +class Secrets implements SecretBackend { + values = new Map(); + get(id: string) { + return this.values.get(id) ?? null; + } + set(id: string, value: string) { + if (!/^[a-z0-9-]+$/u.test(id) || id.length > 64) + throw new Error(`Invalid secret id ${id}`); + this.values.set(id, value); + } + delete(id: string) { + this.values.delete(id); + } +} +const credentials: NoteDeviceCredentials = { + accessToken: "fnd_access", + refreshToken: "fndr_refresh", + deviceId: "device", + userId: "owner", + did: "did:plc:abcdefghijklmnopqrstuvwx", + accessExpiresAt: 1, +}; +const checkpoint: DeviceCheckpoint = { + vault: "vault", + epoch: 1, + pinned: { + statement: "s", + sequence: 1, + admins: ["a"], + recipients: ["a", "d"], + }, + trust: "handed", + runners: [{ recipientId: "a", signPublicKey: "k" }], +}; + +describe("custody", () => { + test("keeps the seed, tokens, pin and confirmed account under valid secret ids", async () => { + const secrets = new Secrets(); + const custody = new Custody(secrets, "0123456789abcdef"); + const seed = crypto.getRandomValues(new Uint8Array(32)); + custody.saveSeed(seed); + await custody.credentials.write(credentials); + await custody.checkpoints.write(checkpoint); + custody.confirmAccount({ + did: credentials.did, + handle: "alice.example.com", + }); + expect(custody.seed()).toEqual(seed); + expect(await custody.credentials.read()).toEqual(credentials); + expect(await custody.checkpoints.read()).toEqual(checkpoint); + expect(custody.account()).toEqual({ + did: credentials.did, + handle: "alice.example.com", + }); + expect( + [...secrets.values.keys()].every((id) => + id.startsWith("flow-note-0123456789abcdef-"), + ), + ).toBe(true); + }); + + test("keeps two vaults' links apart in one shared store", async () => { + const secrets = new Secrets(); + const one = new Custody(secrets, "aaaaaaaaaaaaaaaa"); + const two = new Custody(secrets, "bbbbbbbbbbbbbbbb"); + await one.credentials.write(credentials); + expect(await two.credentials.read()).toBeNull(); + }); + + test("unlinking wipes the seed, tokens and account but keeps the public pin", async () => { + const secrets = new Secrets(); + const custody = new Custody(secrets, "0123456789abcdef"); + custody.saveSeed(new Uint8Array(32).fill(1)); + await custody.credentials.write(credentials); + await custody.checkpoints.write(checkpoint); + custody.confirmAccount({ did: credentials.did }); + custody.wipe(); + expect(custody.seed()).toBeNull(); + expect(await custody.credentials.read()).toBeNull(); + expect(custody.account()).toBeNull(); + expect(await custody.checkpoints.read()).toEqual(checkpoint); + }); + + test("reads anything malformed as absent, and refuses to store malformed credentials", async () => { + const secrets = new Secrets(); + const custody = new Custody(secrets, "0123456789abcdef"); + secrets.set("flow-note-0123456789abcdef-seed", "c2hvcnQ"); + secrets.set("flow-note-0123456789abcdef-tokens", "{not json"); + secrets.set("flow-note-0123456789abcdef-pin", JSON.stringify({ vault: 1 })); + expect(custody.seed()).toBeNull(); + expect(await custody.credentials.read()).toBeNull(); + expect(await custody.checkpoints.read()).toBeNull(); + await expect( + custody.credentials.write({ ...credentials, did: "nope" }), + ).rejects.toThrow("Invalid device credentials"); + expect(() => new Custody(secrets, "Has Spaces")).toThrow(); + }); +}); + +test("a refresh that lands after a wipe writes nothing", async () => { + const secrets = new Secrets(); + const custody = new Custody(secrets, "0123456789abcdef"); + const transport = custody.scope(); + await transport.credentials.write(credentials); + custody.wipe(); + await transport.credentials.write({ ...credentials, refreshToken: "late" }); + await transport.checkpoints.write(checkpoint); + expect(await custody.credentials.read()).toBeNull(); + expect(await custody.checkpoints.read()).toBeNull(); + await custody.scope().credentials.write(credentials); + expect(await custody.credentials.read()).toEqual(credentials); +}); diff --git a/tests/e2e.test.ts b/tests/e2e.test.ts new file mode 100644 index 0000000..8755c79 --- /dev/null +++ b/tests/e2e.test.ts @@ -0,0 +1,233 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { + adminBrowser, + approveLink, + dropDevices, + type FakeFlowId, + fakeFlowId, + host, + useStorage, +} from "@flow-industries/seal/testing"; +import { IDBFactory, IDBKeyRange } from "fake-indexeddb"; +import { REMOVED, SyncController } from "../src/controller"; +import { Custody, type SecretBackend } from "../src/custody"; +import { + createDeviceSeed, + type LinkPrompt, + linkDevice, + openDeviceVault, + pulledStatus, + SYNC_LOCKED, + type TrustLoss, +} from "../src/device"; +import type { SyncIndex } from "../src/engine"; +import { MemoryIndex, MemoryVault } from "./fakes"; + +/** + * Two Obsidian vaults linked as two devices of one NOTE notepad, syncing + * through the device client against an in-memory Flow ID and PDS. One + * process plays both, so each gets its own IndexedDB and they take turns. + */ +class Secrets implements SecretBackend { + values = new Map(); + get = (id: string) => this.values.get(id) ?? null; + set = (id: string, value: string) => void this.values.set(id, value); + delete = (id: string) => void this.values.delete(id); +} + +function obsidian(note: FakeFlowId, name: string) { + const local = new MemoryVault(); + const secrets = new Secrets(); + const custody = new Custody(secrets, `${name}0000000000`); + const indexes = new Map(); + const storage = new IDBFactory(); + const prompts: LinkPrompt[] = []; + const losses: TrustLoss[] = []; + const notices: string[] = []; + const controller: SyncController = new SyncController({ + custody, + device: { + createDeviceSeed, + linkDevice, + openDeviceVault, + locked: SYNC_LOCKED, + pulled: pulledStatus, + }, + host, + fetch: note.fetch, + local, + configDir: ".obsidian", + indexFor: (did, vault) => { + const key = `${did}:${vault}`; + const index = indexes.get(key) ?? new MemoryIndex(); + indexes.set(key, index); + return index; + }, + hold: async () => () => {}, + forgetLocalDatabase: async () => {}, + confirmDeletions: async () => true, + onChange: () => { + if (controller?.phase.kind === "linking" && controller.phase.prompt) + prompts.push(controller.phase.prompt); + }, + onTrustLoss: (loss) => losses.push(loss), + notify: (message) => notices.push(message), + }); + /** Opens this vault's link, lets `work` run, then closes it for the other vault's turn. */ + async function turn(work: () => Promise = async () => {}) { + await useStorage(storage, IDBKeyRange); + await controller.start(); + expect(controller.phase.kind).toBe("open"); + await controller.syncNow(); + await work(); + await controller.syncNow(); + controller.close(); + } + return { + local, + secrets, + custody, + controller, + prompts, + losses, + storage, + turn, + }; +} +type Obsidian = ReturnType; + +async function link( + note: FakeFlowId, + admin: Awaited>, + vault: Obsidian, +) { + await useStorage(vault.storage, IDBKeyRange); + const linking = vault.controller.link( + "Obsidian on test", + new AbortController().signal, + ); + while (!vault.prompts.length) + await new Promise((resolve) => setTimeout(resolve, 10)); + const [prompt] = vault.prompts; + if (!prompt) throw new Error("No prompt"); + expect(prompt.pairingCode).toMatch(/^\d{4} \d{4} \d{4}$/); + await approveLink(note, admin, prompt); + return linking; +} + +const opened: Obsidian[] = []; +afterEach(() => { + for (const vault of opened.splice(0)) vault.controller.close(); +}); + +describe("two Obsidian vaults synced through NOTE", () => { + test("link, confirm the account, sync both ways, rename, resolve a conflict, and stop on revocation", async () => { + const note = fakeFlowId(); + const admin = await adminBrowser(note); + const a = obsidian(note, "aaaaaa"); + const b = obsidian(note, "bbbbbb"); + opened.push(a, b); + + a.local.put("Inbox/First.md", "# Written in vault A"); + a.local.put("Code.mdx", "export const x = 1\n\n"); + const account = await link(note, admin, a); + expect(account.did).toBe("did:plc:devicee2e"); + expect(a.controller.phase.kind).toBe("confirm"); + // Linked but unconfirmed: a restart still asks, and nothing has synced. + await a.controller.start(); + expect(a.controller.phase.kind).toBe("confirm"); + expect(a.custody.account()).toBeNull(); + await a.controller.confirm(); + expect(a.custody.account()).toEqual({ did: "did:plc:devicee2e" }); + await a.controller.syncNow(); + a.controller.close(); + + await link(note, admin, b); + await b.controller.confirm(); + await b.controller.syncNow(); + b.controller.close(); + expect(b.local.text("Inbox/First.md")).toBe("# Written in vault A"); + expect(b.local.text("Code.mdx")).toBe( + "export const x = 1\n\n", + ); + + await b.turn(async () => { + b.local.put("Inbox/First.md", "# Edited in vault B"); + b.local.put("From B.md", "new in B"); + }); + await a.turn(); + expect(a.local.text("Inbox/First.md")).toBe("# Edited in vault B"); + expect(a.local.text("From B.md")).toBe("new in B"); + + await a.turn(async () => { + await a.local.move("From B.md", "Archive/From B.md"); + a.controller.renamed("From B.md", "Archive/From B.md"); + }); + await b.turn(); + expect(b.local.text("From B.md")).toBeUndefined(); + expect(b.local.text("Archive/From B.md")).toBe("new in B"); + + await a.turn(async () => a.local.put("Inbox/First.md", "A's edit")); + b.local.put("Inbox/First.md", "B's edit"); + await b.turn(); + await a.turn(); + for (const vault of [a, b]) { + expect(vault.local.text("Inbox/First.md")).toBe("A's edit"); + const copies = [...vault.local.files.keys()].filter((path) => + /^Inbox\/First conflict [0-9a-f]{8}\.md$/u.test(path), + ); + expect(copies.length).toBe(1); + expect(vault.local.text(copies[0] ?? "")).toBe("B's edit"); + } + expect(note.violations).toEqual([]); + + note.revokeAll(); + await useStorage(a.storage, IDBKeyRange); + await a.controller.start(); + expect(a.controller.phase.kind).toBe("removed"); + expect(a.custody.seed()).toBeNull(); + expect(await a.custody.credentials.read()).toBeNull(); + a.local.put("After.md", "never leaves"); + await a.controller.syncNow(); + expect(a.controller.phase.kind).toBe("removed"); + + await useStorage(b.storage, IDBKeyRange); + await b.controller.unlink(); + expect(b.controller.phase.kind).toBe("unlinked"); + expect(b.secrets.values.has("flow-note-bbbbbb0000000000-seed")).toBe(false); + expect(b.secrets.values.has("flow-note-bbbbbb0000000000-tokens")).toBe( + false, + ); + }, 120_000); + + test("a vault removed under Access while syncing stops and wipes its keys, keeping its files", async () => { + const note = fakeFlowId(); + const admin = await adminBrowser(note); + const a = obsidian(note, "cccccc"); + opened.push(a); + a.local.put("Kept.md", "synced before removal"); + await link(note, admin, a); + await a.controller.confirm(); + await a.controller.syncNow(); + expect(a.controller.phase.kind).toBe("open"); + + await dropDevices(note, admin); + a.local.put("Late.md", "written after removal"); + await a.controller.syncNow(); + for ( + let wait = 0; + a.controller.phase.kind !== "removed" && wait < 100; + wait++ + ) + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(a.controller.phase).toEqual({ + kind: "removed", + message: REMOVED.removed, + }); + expect(a.custody.seed()).toBeNull(); + expect(await a.custody.credentials.read()).toBeNull(); + expect(await a.custody.checkpoints.read()).not.toBeNull(); + expect(a.local.text("Kept.md")).toBe("synced before removal"); + expect(note.violations).toEqual([]); + }, 60_000); +}); diff --git a/tests/engine.test.ts b/tests/engine.test.ts new file mode 100644 index 0000000..31648dc --- /dev/null +++ b/tests/engine.test.ts @@ -0,0 +1,296 @@ +import { describe, expect, test } from "bun:test"; +import { type Deletions, SyncEngine } from "../src/engine"; +import { MemoryIndex, MemoryRemote, MemoryVault } from "./fakes"; + +async function setup( + options: { confirm?: (deletions: Deletions) => Promise } = {}, +) { + const local = new MemoryVault(); + const remote = new MemoryRemote(); + const index = new MemoryIndex(); + const asked: Deletions[] = []; + const engine = new SyncEngine({ + local, + remote, + index, + configDir: ".obsidian", + confirmDeletions: async (deletions) => { + asked.push(deletions); + return (await options.confirm?.(deletions)) ?? true; + }, + }); + await engine.load(); + return { local, remote, index, engine, asked }; +} +type Setup = Awaited>; +const settled = async ({ engine }: Setup) => { + const first = await engine.run(); + engine.remoteChanged(); + const second = await engine.run(); + expect(second.applied).toBe(0); + return first; +}; +const remotePaths = (remote: MemoryRemote) => + [...remote.notes.values()] + .map((note) => `${note.path}: ${note.source}`) + .sort(); +const localPaths = (local: MemoryVault) => + [...local.files].map(([path, file]) => `${path}: ${file.source}`).sort(); + +describe("engine: a first sync", () => { + test("pushes local notes, pulls remote ones, and leaves attachments and config alone", async () => { + const w = await setup(); + w.local.put("Here.md", "local"); + w.local.put("Dir/Deep.mdx", ""); + w.local.put("photo.png", "binary"); + w.local.put("con.md", "a name NOTE refuses"); + w.remote.put("t", "There.md", "remote"); + w.remote.put("hidden", ".obsidian/plugins/x/main.md", "never written"); + const result = await settled(w); + expect(remotePaths(w.remote)).toEqual([ + ".obsidian/plugins/x/main.md: never written", + "Dir/Deep.mdx: ", + "Here.md: local", + "There.md: remote", + ]); + expect(localPaths(w.local)).toEqual([ + "Dir/Deep.mdx: ", + "Here.md: local", + "There.md: remote", + "con.md: a name NOTE refuses", + "photo.png: binary", + ]); + expect(result.attachments).toBe(1); + expect(result.unsyncable.sort()).toEqual([ + ".obsidian/plugins/x/main.md", + "con.md", + ]); + }); + + test("an existing note on both sides with different text keeps both", async () => { + const w = await setup(); + w.local.put("Plan.md", "mine"); + w.remote.put("p", "plan.md", "theirs"); + await settled(w); + const copy = [...w.local.files.keys()].find((path) => + path.includes("conflict"), + ); + expect(copy).toMatch(/^plan conflict [0-9a-f]{8}\.md$/); + expect(w.local.text("plan.md")).toBe("theirs"); + expect(w.local.text(copy ?? "")).toBe("mine"); + expect(w.remote.byPath(copy ?? "")?.source).toBe("mine"); + }); +}); + +describe("engine: after the first sync", () => { + async function synced() { + const w = await setup(); + w.local.put("A.md", "one"); + w.remote.put("b", "B.md", "two"); + await settled(w); + return w; + } + + test("carries edits both ways on the revision they were made on", async () => { + const w = await synced(); + w.local.put("A.md", "one, edited here"); + w.remote.put("b", "B.md", "two, edited there"); + w.engine.remoteChanged(); + await settled(w); + expect(w.remote.byPath("A.md")?.source).toBe("one, edited here"); + expect(w.local.text("B.md")).toBe("two, edited there"); + }); + + test("carries renames both ways", async () => { + const w = await synced(); + await w.local.move("A.md", "Moved/A2.md"); + w.engine.renamed("A.md", "Moved/A2.md"); + const b = w.remote.byPath("B.md"); + await w.remote.rename(b?.id ?? "", "Elsewhere/B.md"); + w.engine.remoteChanged(); + await settled(w); + expect(remotePaths(w.remote)).toEqual([ + "Elsewhere/B.md: two", + "Moved/A2.md: one", + ]); + expect(localPaths(w.local)).toEqual([ + "Elsewhere/B.md: two", + "Moved/A2.md: one", + ]); + }); + + test("carries a folder rename Obsidian reported once", async () => { + const w = await setup(); + w.local.put("Old/x.md", "x"); + w.local.put("Old/Sub/y.md", "y"); + await settled(w); + await w.local.move("Old/x.md", "New/x.md"); + await w.local.move("Old/Sub/y.md", "New/Sub/y.md"); + w.engine.renamed("Old", "New"); + await settled(w); + expect(remotePaths(w.remote)).toEqual(["New/Sub/y.md: y", "New/x.md: x"]); + }); + + test("a conflict keeps the remote text in place and the local text in a NOTE-style copy", async () => { + const w = await synced(); + w.local.put("A.md", "local edit"); + const a = w.remote.byPath("A.md"); + w.remote.put(a?.id ?? "", "A.md", "remote edit"); + w.engine.remoteChanged(); + await settled(w); + expect(w.local.text("A.md")).toBe("remote edit"); + const copy = [...w.local.files.keys()].find((path) => + path.startsWith("A conflict "), + ); + expect(w.local.text(copy ?? "")).toBe("local edit"); + expect(w.remote.byPath(copy ?? "")?.source).toBe("local edit"); + }); + + test("deletes both ways, into each side's trash", async () => { + const w = await synced(); + await w.local.trash("A.md"); + const b = w.remote.byPath("B.md"); + await w.remote.remove(b?.id ?? ""); + w.engine.remoteChanged(); + await settled(w); + expect(w.remote.notes.size).toBe(0); + expect(w.local.files.size).toBe(0); + expect(w.local.trashed).toEqual(["A.md", "B.md"]); + }); + + test("never overwrites an edit made while the round runs", async () => { + const w = await synced(); + w.remote.put("b", "B.md", "remote edit"); + w.engine.remoteChanged(); + w.local.beforeWrite = (path) => { + if (path === "B.md") w.local.put("B.md", "typed meanwhile"); + w.local.beforeWrite = undefined; + }; + const result = await w.engine.run(); + expect(result.failed.map((failure) => failure.path)).toEqual(["B.md"]); + expect(w.local.text("B.md")).toBe("typed meanwhile"); + await settled(w); + const copy = [...w.local.files.keys()].find((path) => + path.startsWith("B conflict "), + ); + expect(w.local.text("B.md")).toBe("remote edit"); + expect(w.local.text(copy ?? "")).toBe("typed meanwhile"); + }); + + test("resumes from the saved index without redoing anything", async () => { + const w = await synced(); + const engine = new SyncEngine({ + local: w.local, + remote: w.remote, + index: w.index, + configDir: ".obsidian", + }); + await engine.load(); + expect((await engine.run()).applied).toBe(0); + }); +}); + +describe("engine: mass deletions", () => { + async function many(confirm: (deletions: Deletions) => Promise) { + const w = await setup({ confirm }); + for (let n = 0; n < 12; n++) w.remote.put(`n${n}`, `N${n}.md`, `${n}`); + await settled(w); + w.remote.notes.clear(); + w.engine.remoteChanged(); + return w; + } + + test("wait for confirmation, and are held when declined", async () => { + const w = await many(async () => false); + const result = await w.engine.run(); + expect(w.asked).toEqual([{ local: 12, remote: 0 }]); + expect(result.held).toEqual({ local: 12, remote: 0 }); + expect(w.local.files.size).toBe(12); + await w.engine.run(); + expect(w.asked.length).toBe(1); + w.engine.reconsiderDeletions(); + await w.engine.run(); + expect(w.asked.length).toBe(2); + }); + + test("go ahead once confirmed", async () => { + const w = await many(async () => true); + await w.engine.run(); + expect(w.local.files.size).toBe(0); + expect(w.local.trashed.length).toBe(12); + }); +}); + +describe("engine: collisions", () => { + test("a file whose name differs only in case from a synced note stays out", async () => { + const w = await setup(); + w.local.put("Note.md", "original"); + await settled(w); + w.local.put("note.md", "a different note"); + const result = await w.engine.run(); + expect(result.unsyncable).toEqual(["note.md"]); + expect(remotePaths(w.remote)).toEqual(["Note.md: original"]); + }); + + test("a new file where a remote rename is headed steps aside as a conflict copy", async () => { + const w = await setup(); + w.local.put("A.md", "a"); + await settled(w); + const a = w.remote.byPath("A.md"); + await w.remote.rename(a?.id ?? "", "B.md"); + w.local.put("B.md", "unrelated"); + w.engine.remoteChanged(); + await settled(w); + const aside = [...w.local.files.keys()].find((path) => + path.startsWith("B conflict "), + ); + expect(w.local.text("B.md")).toBe("a"); + expect(w.local.text(aside ?? "")).toBe("unrelated"); + expect(remotePaths(w.remote)).toEqual([`${aside}: unrelated`, "B.md: a"]); + }); + + test("deleting B, then renaming A to B, trashes B in NOTE and moves A there", async () => { + const w = await setup(); + w.local.put("A.md", "a"); + w.local.put("B.md", "b"); + await settled(w); + await w.local.trash("B.md"); + await w.local.move("A.md", "B.md"); + w.engine.renamed("A.md", "B.md"); + await settled(w); + expect(remotePaths(w.remote)).toEqual(["B.md: a"]); + }); + + test("a move that succeeds before its write fails is remembered", async () => { + const w = await setup(); + w.local.put("A.md", "a"); + await settled(w); + const a = w.remote.byPath("A.md"); + await w.remote.rename(a?.id ?? "", "B.md"); + w.remote.put(a?.id ?? "", "B.md", "edited there"); + w.engine.remoteChanged(); + w.local.beforeWrite = (path) => { + if (path === "B.md") w.local.put("B.md", "typed here"); + w.local.beforeWrite = undefined; + }; + await w.engine.run(); + await settled(w); + const copy = [...w.local.files.keys()].find((path) => + path.startsWith("B conflict "), + ); + expect(w.local.text("B.md")).toBe("edited there"); + expect(w.local.text(copy ?? "")).toBe("typed here"); + }); + + test("a stopped engine writes nothing more", async () => { + const w = await setup(); + w.remote.put("a", "A.md", "a"); + w.remote.put("b", "B.md", "b"); + w.local.beforeWrite = () => w.engine.stop(); + await w.engine.run(); + expect(w.local.files.size).toBeLessThanOrEqual(1); + w.local.beforeWrite = undefined; + await w.engine.run(); + expect(w.local.files.size).toBeLessThanOrEqual(1); + }); +}); diff --git a/tests/fakes.ts b/tests/fakes.ts new file mode 100644 index 0000000..b3ea655 --- /dev/null +++ b/tests/fakes.ts @@ -0,0 +1,122 @@ +import type { + LocalFile, + LocalVault, + RemoteNoteView, + RemoteVault, + SyncIndex, +} from "../src/engine"; +import { pathKey } from "../src/paths"; +import type { Entry } from "../src/plan"; + +/** An Obsidian vault in memory; `beforeWrite` lets a test edit a file between a read and a write. */ +export class MemoryVault implements LocalVault { + files = new Map(); + trashed: string[] = []; + beforeWrite?: (path: string) => void; + private clock = 1; + + put(path: string, source: string) { + this.files.set(path, { source, mtime: this.clock++ }); + } + text(path: string) { + return this.files.get(path)?.source; + } + async list(): Promise { + return [...this.files].map(([path, file]) => ({ + path, + mtime: file.mtime, + size: file.source.length, + })); + } + async read(path: string) { + const file = this.files.get(path); + if (!file) throw new Error(`No file ${path}`); + return file.source; + } + private taken(path: string) { + return [...this.files.keys()].some((key) => pathKey(key) === pathKey(path)); + } + async create(path: string, source: string) { + this.beforeWrite?.(path); + if (this.taken(path)) return false; + this.put(path, source); + return true; + } + async replace(path: string, expected: string, next: string) { + this.beforeWrite?.(path); + if (this.files.get(path)?.source !== expected) return false; + this.put(path, next); + return true; + } + async move(from: string, to: string) { + const file = this.files.get(from); + if (!file || (pathKey(from) !== pathKey(to) && this.taken(to))) + return false; + this.files.delete(from); + this.put(to, file.source); + return true; + } + async trash(path: string) { + this.files.delete(path); + this.trashed.push(path); + } +} + +/** A NOTE vault in memory that refuses saves on a revision it can't place, as the device client does. */ +export class MemoryRemote implements RemoteVault { + notes = new Map>(); + removed: string[] = []; + private revisions = 0; + + put(id: string, path: string, source: string) { + this.notes.set(id, { id, path, source, ...this.revision() }); + } + byPath(path: string) { + return [...this.notes.values()].find((note) => note.path === path); + } + private revision() { + const revision = `r${++this.revisions}`; + return { revision, digest: `d-${revision}` }; + } + private collides(id: string, path: string) { + return [...this.notes.values()].some( + (note) => note.id !== id && pathKey(note.path) === pathKey(path), + ); + } + async read() { + return { notes: [...this.notes.values()].map((note) => ({ ...note })) }; + } + async saveNote(note: RemoteNoteView) { + const current = this.notes.get(note.id); + if (current && current.revision !== note.revision) + throw new Error("This note changed. Read it again."); + if (this.collides(note.id, note.path)) + throw new Error("Filesystem path collision"); + const saved = this.revision(); + this.notes.set(note.id, { ...note, ...saved }); + return saved; + } + async rename(id: string, path: string) { + const current = this.notes.get(id); + if (!current) throw new Error("Missing note"); + if (this.collides(id, path)) throw new Error("Filesystem path collision"); + this.notes.set(id, { ...current, path, ...this.revision() }); + } + async remove(id: string) { + this.notes.delete(id); + this.removed.push(id); + } +} + +export class MemoryIndex implements SyncIndex { + entries: Entry[] = []; + async load() { + return structuredClone(this.entries); + } + async save(entries: Entry[]) { + this.entries = structuredClone(entries); + } + async clear() { + this.entries = []; + } +} diff --git a/tests/fetch.test.ts b/tests/fetch.test.ts new file mode 100644 index 0000000..b2c7f9e --- /dev/null +++ b/tests/fetch.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, test } from "bun:test"; +import { IDBFactory } from "fake-indexeddb"; +import { linkedAccount } from "../src/account"; +import type { NoteDeviceFetch } from "../src/device"; +import { type RequestUrl, requestUrlFetch } from "../src/fetch"; +import { IndexedDbIndex } from "../src/index-store"; + +describe("fetch over requestUrl", () => { + test("passes method, headers and bytes through, and answers a real Response", async () => { + const seen: Parameters[0][] = []; + const fetch = requestUrlFetch(async (request) => { + seen.push(request); + return { + status: 409, + headers: { "content-type": "application/json" }, + arrayBuffer: new TextEncoder().encode('{"code":"CONFLICT"}') + .buffer as ArrayBuffer, + }; + }); + const bytes = new Uint8Array([9, 8, 7, 6]).subarray(1, 3); + const response = await fetch("https://id.example/upload", { + method: "POST", + headers: { Authorization: "Bearer fnd_x" }, + body: bytes, + }); + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ code: "CONFLICT" }); + expect(seen[0]?.method).toBe("POST"); + expect(seen[0]?.headers.authorization).toBe("Bearer fnd_x"); + expect(seen[0]?.throw).toBe(false); + expect([...new Uint8Array(seen[0]?.body as ArrayBuffer)]).toEqual([8, 7]); + }); + + test("stops waiting when aborted, and keeps bodiless statuses bodiless", async () => { + const never = requestUrlFetch(() => new Promise(() => {})); + const controller = new AbortController(); + const pending = never("https://id.example/token", { + signal: controller.signal, + }); + controller.abort(new Error("gone")); + await expect(pending).rejects.toThrow("gone"); + const empty = requestUrlFetch(async () => ({ + status: 204, + headers: {}, + arrayBuffer: new ArrayBuffer(0), + })); + expect((await empty("https://id.example/x", {})).status).toBe(204); + }); +}); + +describe("the linked account", () => { + const did = "did:plc:abcdefghijklmnopqrstuvwx"; + const serve = + (routes: Record Response>): NoteDeviceFetch => + async (url) => + routes[url]?.() ?? new Response("not found", { status: 404 }); + + test("names the handle only when the handle points back at the DID", async () => { + const document = { id: did, alsoKnownAs: ["at://alice.example.com"] }; + const verified = serve({ + [`https://plc.directory/${did}`]: () => Response.json(document), + "https://alice.example.com/.well-known/atproto-did": () => + new Response(`${did}\n`), + }); + expect(await linkedAccount(did, verified)).toEqual({ + did, + handle: "alice.example.com", + }); + const claimedOnly = serve({ + [`https://plc.directory/${did}`]: () => Response.json(document), + "https://alice.example.com/.well-known/atproto-did": () => + new Response("did:plc:someoneelse"), + }); + expect(await linkedAccount(did, claimedOnly)).toEqual({ did }); + expect( + await linkedAccount(did, async () => { + throw new Error("offline"); + }), + ).toEqual({ did }); + expect(await linkedAccount("did:example:x", verified)).toEqual({ + did: "did:example:x", + }); + }); +}); + +describe("the sync index", () => { + test("persists in its own IndexedDB database", async () => { + const factory = new IDBFactory(); + const index = new IndexedDbIndex("flow-note-sync:test", factory); + expect(await index.load()).toEqual([]); + const entry = { + id: "a", + path: "A.md", + revision: "r", + digest: "d", + hash: "h", + mtime: 1, + size: 2, + }; + await index.save([entry]); + expect( + await new IndexedDbIndex("flow-note-sync:test", factory).load(), + ).toEqual([entry]); + }); +}); diff --git a/tests/paths.test.ts b/tests/paths.test.ts new file mode 100644 index 0000000..17b7169 --- /dev/null +++ b/tests/paths.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from "bun:test"; +import { conflictPath } from "../src/conflicts"; +import { exclusion, isNotePath, pathKey } from "../src/paths"; + +describe("which files sync", () => { + test("Markdown and MDX are notes; everything else is an attachment", () => { + expect(isNotePath("a/b.md")).toBe(true); + expect(isNotePath("Plan.MDX")).toBe(true); + expect(isNotePath("photo.png")).toBe(false); + expect(isNotePath("notes.md.bak")).toBe(false); + }); + + test("Obsidian's config folder and hidden paths never sync, whatever the case", () => { + expect(exclusion(".obsidian/app.json", ".obsidian")).toBe("config"); + expect(exclusion(".Obsidian/plugins/x/main.md", ".obsidian")).toBe( + "config", + ); + expect(exclusion("config/workspace.md", "config/")).toBe("config"); + expect(exclusion(".trash/old.md", ".obsidian")).toBe("hidden"); + expect(exclusion("a/.git/HEAD.md", ".obsidian")).toBe("hidden"); + expect(exclusion("Projects/Plan.md", ".obsidian")).toBeNull(); + }); + + test("names NOTE can't store stay out, as NOTE's own path rules decide", () => { + expect(exclusion("a/../b.md", ".obsidian")).not.toBeNull(); + for (const path of [ + "trailing./x.md", + "space /x.md", + "con.md", + "LPT1/x.md", + "C:drive.md", + "what?.md", + `${"x".repeat(256)}.md`, + "tab\there.md", + ]) + expect(exclusion(path, ".obsidian")).toBe("unsafe-name"); + expect(exclusion(`${"d/".repeat(64)}x.md`, ".obsidian")).toBe( + "unsafe-name", + ); + expect(exclusion("Ünïcode/Notiz.md", ".obsidian")).toBeNull(); + }); + + test("paths compare as NOTE compares them: case-insensitive, Unicode-normalized", () => { + expect(pathKey("Folder/Note.md")).toBe(pathKey("folder/note.MD")); + expect(pathKey("Café.md")).toBe(pathKey("Café.md")); + expect(pathKey("a.md")).not.toBe(pathKey("b.md")); + }); +}); + +describe("conflict copies", () => { + const id = () => "0123abcd-0000-4000-8000-000000000000"; + + test("sit beside the note, named as NOTE names its own", () => { + expect(conflictPath("Projects/Plan.md", id)).toBe( + "Projects/Plan conflict 0123abcd.md", + ); + expect(conflictPath("Top.MDX", id)).toBe("Top conflict 0123abcd.mdx"); + }); + + test("shorten the name to fit NOTE's 255-byte limit", () => { + const long = `${"é".repeat(200)}.md`; + const copy = conflictPath(`dir/${long}`, id); + const name = copy.slice("dir/".length); + expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(255); + expect(name.endsWith(" conflict 0123abcd.md")).toBe(true); + expect(exclusion(copy, ".obsidian")).toBeNull(); + }); +}); diff --git a/tests/plan.test.ts b/tests/plan.test.ts new file mode 100644 index 0000000..5cc6fa4 --- /dev/null +++ b/tests/plan.test.ts @@ -0,0 +1,258 @@ +import { describe, expect, test } from "bun:test"; +import { + type Entry, + type LocalNote, + plan, + type RemoteNote, + type Step, +} from "../src/plan"; + +const entry = ( + id: string, + path: string, + hash: string, + extra: Partial = {}, +): Entry => ({ + id, + path, + revision: `rev-${hash}`, + digest: `digest-${hash}`, + hash, + mtime: 1, + size: 1, + ...extra, +}); +const local = (path: string, hash: string): LocalNote => ({ + path, + hash, + source: `text ${hash}`, +}); +const remote = (id: string, path: string, hash: string): RemoteNote => ({ + id, + path, + hash, + source: `text ${hash}`, + revision: `rev-${hash}`, + digest: `digest-${hash}`, +}); +let counter = 0; +const newId = () => `0000000${++counter}-new`; +const run = (input: Omit[0], "newId">) => { + counter = 0; + return plan({ ...input, newId }); +}; +const summary = (steps: Step[]) => + steps.map((step) => + step.kind === "update" + ? `${step.kind} ${step.id} ${step.path} ${step.content}${step.copy ? ` copy ${step.copy}` : ""}` + : `${step.kind} ${step.id}`, + ); + +describe("plan: one note's change on one side", () => { + const base = [entry("a", "A.md", "1")]; + + test("nothing changed: nothing to do", () => { + expect( + run({ + entries: base, + local: [local("A.md", "1")], + remote: [remote("a", "A.md", "1")], + }), + ).toEqual([]); + }); + + test("a local edit pushes on the revision it was made on", () => { + const steps = run({ + entries: base, + local: [local("A.md", "2")], + remote: [remote("a", "A.md", "1")], + }); + expect(summary(steps)).toEqual(["update a A.md local"]); + const [step] = steps; + expect(step?.kind === "update" && step.remote?.revision).toBe("rev-1"); + }); + + test("a remote edit pulls", () => { + expect( + summary( + run({ + entries: base, + local: [local("A.md", "1")], + remote: [remote("a", "A.md", "2")], + }), + ), + ).toEqual(["update a A.md remote"]); + }); + + test("a new revision with the same text only moves the index forward", () => { + const steps = run({ + entries: [entry("a", "A.md", "1", { revision: "" })], + local: [local("A.md", "1")], + remote: [remote("a", "A.md", "1")], + }); + expect(summary(steps)).toEqual(["update a A.md same"]); + }); + + test("a local delete trashes the note in NOTE; a remote delete trashes the file", () => { + expect( + summary( + run({ entries: base, local: [], remote: [remote("a", "A.md", "1")] }), + ), + ).toEqual(["delete-remote a"]); + expect( + summary(run({ entries: base, local: [local("A.md", "1")], remote: [] })), + ).toEqual(["delete-local a"]); + expect(summary(run({ entries: base, local: [], remote: [] }))).toEqual([ + "forget a", + ]); + }); + + test("an edit beats a delete on the other side", () => { + expect( + summary( + run({ entries: base, local: [], remote: [remote("a", "A.md", "2")] }), + ), + ).toEqual(["update a A.md remote"]); + expect( + summary(run({ entries: base, local: [local("A.md", "2")], remote: [] })), + ).toEqual(["update 00000001-new A.md local", "forget a"]); + }); +}); + +describe("plan: renames", () => { + const base = [entry("a", "A.md", "1")]; + + test("a local rename Obsidian reported renames the note in NOTE", () => { + const steps = run({ + entries: [entry("a", "A.md", "1", { moved: "Dir/B.md" })], + local: [local("Dir/B.md", "1")], + remote: [remote("a", "A.md", "1")], + }); + expect(summary(steps)).toEqual(["update a Dir/B.md same"]); + }); + + test("a rename made while sync wasn't watching is found by its unchanged text", () => { + const steps = run({ + entries: base, + local: [local("B.md", "1")], + remote: [remote("a", "A.md", "1")], + }); + expect(summary(steps)).toEqual(["update a B.md same"]); + }); + + test("two files with the same text aren't guessed as the rename", () => { + const steps = run({ + entries: base, + local: [local("B.md", "1"), local("C.md", "1")], + remote: [remote("a", "A.md", "1")], + }); + expect(summary(steps)).toEqual([ + "delete-remote a", + "update 00000001-new B.md local", + "update 00000002-new C.md local", + ]); + }); + + test("a remote rename moves the file, keeping a local edit", () => { + const steps = run({ + entries: base, + local: [local("A.md", "2")], + remote: [remote("a", "B.md", "1")], + }); + expect(summary(steps)).toEqual(["update a B.md local"]); + }); + + test("when both sides renamed, the remote name wins", () => { + const steps = run({ + entries: [entry("a", "A.md", "1", { moved: "Local.md" })], + local: [local("Local.md", "1")], + remote: [remote("a", "Remote.md", "1")], + }); + expect(summary(steps)).toEqual(["update a Remote.md same"]); + }); + + test("a case-only rename is still a rename", () => { + const steps = run({ + entries: [entry("a", "A.md", "1", { moved: "a.md" })], + local: [local("a.md", "1")], + remote: [remote("a", "A.md", "1")], + }); + expect(summary(steps)).toEqual(["update a a.md same"]); + }); +}); + +describe("plan: conflicts", () => { + test("both sides edited: the remote text keeps the path, the local text becomes a conflict copy", () => { + const steps = run({ + entries: [entry("a", "Dir/A.md", "1")], + local: [local("Dir/A.md", "2")], + remote: [remote("a", "Dir/A.md", "3")], + }); + expect(summary(steps)).toEqual([ + "update a Dir/A.md remote copy Dir/A conflict 00000001.md", + ]); + }); + + test("both sides made the same edit: no conflict", () => { + const steps = run({ + entries: [entry("a", "A.md", "1")], + local: [local("A.md", "2")], + remote: [remote("a", "A.md", "2")], + }); + expect(summary(steps)).toEqual(["update a A.md same"]); + }); + + test("a first sync binds identical notes and keeps both texts of different ones", () => { + const steps = run({ + entries: [], + local: [ + local("Same.md", "1"), + local("Differs.md", "2"), + local("OnlyHere.md", "4"), + ], + remote: [ + remote("s", "Same.md", "1"), + remote("d", "differs.md", "3"), + remote("t", "OnlyThere.md", "5"), + ], + }); + expect(summary(steps)).toEqual([ + "update 00000002-new OnlyHere.md local", + "update s Same.md same", + "update d differs.md remote copy differs conflict 00000001.md", + "update t OnlyThere.md remote", + ]); + }); +}); + +describe("plan: order", () => { + test("remote deletes free paths before creates, and local edits land before remote renames", () => { + const steps = run({ + entries: [ + entry("gone", "Old.md", "1"), + entry("edit", "E.md", "1"), + entry("move", "M.md", "1", { moved: "N.md" }), + ], + local: [local("E.md", "2"), local("N.md", "1"), local("New.md", "9")], + remote: [ + remote("gone", "Old.md", "1"), + remote("edit", "E.md", "1"), + remote("move", "M.md", "1"), + remote("pull", "P.md", "7"), + ], + }); + expect( + summary( + steps.filter( + (step) => step.kind !== "delete-remote" || step.id === "gone", + ), + ), + ).toEqual([ + "delete-remote gone", + "update edit E.md local", + "update move N.md same", + "update 00000001-new New.md local", + "update pull P.md remote", + ]); + }); +}); From ad95dcaed8a5d5308094e44774b30be0116de639 Mon Sep 17 00:00:00 2001 From: kualta Date: Wed, 4 Nov 2026 12:25:32 -0500 Subject: [PATCH 02/16] sync attachments and forget per-device storage on unlink --- AGENTS.md | 4 +- README.md | 17 ++- bunfig.toml | 2 + src/conflicts.ts | 12 +- src/controller.ts | 43 +++---- src/device.ts | 1 + src/engine.ts | 249 +++++++++++++++++++++++++++------------ src/hash.ts | 7 +- src/index-store.ts | 28 ----- src/lock.ts | 3 +- src/main.ts | 11 +- src/obsidian/settings.ts | 5 +- src/obsidian/vault.ts | 21 +++- src/plan.ts | 58 +++++---- tests/controller.test.ts | 30 +++-- tests/e2e.test.ts | 108 ++++++++--------- tests/engine.test.ts | 101 ++++++++++++---- tests/fakes.ts | 145 ++++++++++++++++++----- tests/plan.test.ts | 12 +- tests/setup.ts | 2 + 20 files changed, 547 insertions(+), 312 deletions(-) create mode 100644 bunfig.toml create mode 100644 tests/setup.ts diff --git a/AGENTS.md b/AGENTS.md index dc6f4d8..c5b03ac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,10 +4,10 @@ NOTE Sync is an Obsidian community plugin (id `flow-note`). This repository is p - Use Bun 1.4.2. Before a PR, run `bun run lint`, `bun run typecheck`, `bun test`, `bun run build` and `bun run smoke`. - `manifest.json` stays at the root. Never change the plugin `id`. A release tag equals the manifest `version`, with no `v`. -- Obsidian's API is used only in `src/main.ts` and `src/obsidian/`. Everything else (path rules, the planner, the engine, custody, the controller) runs under `bun test`, and `tests/e2e.test.ts` drives the real device client from `@flow-industries/seal` against its in-memory Flow ID and PDS. +- Obsidian's API is used only in `src/main.ts` and `src/obsidian/`. Everything else (path rules, the planner, the engine, custody, the controller) runs under `bun test`, and `tests/e2e.test.ts` drives the real device client against `@flow-industries/seal/testing`'s in-memory Flow ID and PDS. `bunfig.toml` preloads `fake-indexeddb` for it. - `src/device.ts` is the only module that imports `@flow-industries/seal`. - Secrets (the device seed, Flow ID device tokens) live only in Obsidian's secret storage, never in `data.json` or anywhere inside the vault folder. The plugin keeps no `data.json`. -- One device transport per credential store: `SyncController` owns the only open device vault, and a Web Lock keeps a second window or vault from opening the same account. +- One device transport per credential store: `SyncController` owns the only open device vault, and a Web Lock on the vault's credential namespace keeps a second window from opening another. The device client names its local database per device; unlink and removal delete it with `deleteDeviceStorage`. - Nothing syncs before the person confirms the linked account (`Custody.account()`). - Never execute note content. Notes, MDX and code blocks are text to this plugin, and nothing is ever written into Obsidian's config folder. - `main.js` is loaded as CommonJS: `scripts/build.ts` replaces `import.meta.url`, and `bun run smoke` fails if the bundle needs anything at load beyond what Obsidian provides. diff --git a/README.md b/README.md index 9b95223..2821ff4 100644 --- a/README.md +++ b/README.md @@ -15,16 +15,15 @@ A link has to be approved within ten minutes. ## What syncs -- **Notes:** every Markdown (`.md`) and MDX (`.mdx`) file, both ways. -- **Renames** carry across, including folder renames. A rename the plugin didn't see (Obsidian was closed) is recognised by the note's unchanged text. -- **Deletions** move the note to the trash on the other side: Obsidian's trash here, NOTE's trash there. An edit beats a deletion: if one side edited a note the other deleted, the note comes back. Before a sync would trash more than ten notes and more than a tenth of the vault at once, the plugin asks. -- **Conflicts:** when both sides edited the same note, NOTE's text keeps the note's name and this vault's text is saved beside it as ` conflict <8 hex>.md`, the way NOTE names its own conflict copies. Nothing is overwritten while you type: a file that changes during a sync is left alone until the next one. +- **Notes and attachments:** every Markdown (`.md`) and MDX (`.mdx`) note, and every other file (images, PDFs, audio and the rest) up to 32 MB, both ways. +- **Renames** carry across, including folder renames. A rename the plugin didn't see (Obsidian was closed) is recognised by the file's unchanged content. When you rename an attachment here, Obsidian updates the links to it, and those edits sync like any other. +- **Deletions** move the file to the trash on the other side: Obsidian's trash here, NOTE's trash there. An edit beats a deletion: if one side edited a file the other deleted, it comes back. Before a sync would trash more than ten files and more than a tenth of the vault at once, the plugin asks. +- **Conflicts:** when both sides changed the same file, NOTE's version keeps the name and this vault's is saved beside it. A note's copy is named ` conflict <8 hex>.md`, the way NOTE names its own conflict copies; an attachment's keeps its extension last, ` conflict <8 hex>.png`, so Obsidian still opens it. Nothing is overwritten while you type: a file that changes during a sync, or an open note with unsaved typing, is left alone until the next sync. **Not synced:** - Obsidian's config folder (`.obsidian/`) and anything hidden. The config folder holds plugin code, so nothing from NOTE is ever written into it. -- Attachments. This version syncs notes only; images, PDFs and other files stay on this device, and **Settings → NOTE Sync** counts them. -- Names NOTE can't store (such as `con.md` or a name ending in a dot), and NOTE notes whose names this vault can't hold. Settings lists them. +- Attachments over 32 MB, names NOTE can't store (such as `con.md` or a name ending in a dot), names that differ from a synced file's only in case, and NOTE files whose names this vault can't hold. Settings lists them. A synced file that becomes one of these is left as it is on both sides, never deleted. ## Note content never runs @@ -49,12 +48,12 @@ Trade-offs to know: - **Mobile secret storage is shared by every vault on the device**, so each vault's link lives under its own random name. - **On mobile, Obsidian saves a secret in the background.** Flow ID rotates the refresh token on every refresh; if the app is killed in the instant between a refresh and that save, the next start presents the old token, Flow ID refuses it, and you link again. Nothing is lost: your notes are on both sides. -The plugin also keeps two caches in Obsidian's app data, never in the vault: the device client's encrypted local database, and an index of what was last synced. +The plugin also keeps two caches in Obsidian's app data, never in the vault: the device client's encrypted local database, named for this device alone, and an index of what was last synced. ## Removing access -- **Unlink** (in settings or the command palette) stops syncing and forgets the device seed and tokens on this device. Your files stay. Remove the device under **Access** in NOTE too. -- **Removing the device** under Access in NOTE, or Flow ID revoking it, stops the plugin at its next sync: it wipes the seed and tokens, writes nothing more, and asks you to link again. Your files stay. +- **Unlink** (in settings or the command palette) stops syncing and forgets the device seed, its tokens, its local database and the sync index on this device. Your files stay. Remove the device under **Access** in NOTE too. +- **Removing the device** under Access in NOTE, or Flow ID revoking it, stops the plugin at its next sync: it wipes the same, writes nothing more, and asks you to link again. Your files stay. ## Network use diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 0000000..8370a01 --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,2 @@ +[test] +preload = ["./tests/setup.ts"] diff --git a/src/conflicts.ts b/src/conflicts.ts index d7d1ca7..2b0d1f2 100644 --- a/src/conflicts.ts +++ b/src/conflicts.ts @@ -5,16 +5,20 @@ const MAX_NAME_BYTES = 255; /** * Where a conflicting copy of `path` goes: beside it, named as NOTE names its - * own conflict copies, ` conflict <8 hex>`, with the name - * shortened until it fits 255 bytes. + * own conflict copies of notes, ` conflict <8 hex>.md`, with the name + * shortened until it fits 255 bytes. An attachment keeps its extension last + * too, where NOTE would append the suffix, so Obsidian still opens it. */ export function conflictPath( path: string, id: () => string = () => crypto.randomUUID(), ): string { const name = nameOf(path); - const extension = /\.mdx?$/iu.exec(name)?.[0] ?? ""; - const suffix = ` conflict ${id().slice(0, 8)}${extension.toLowerCase()}`; + const extension = /(?<=.)\.[^.]+$/u.exec(name)?.[0] ?? ""; + const ending = /^\.mdx?$/iu.test(extension) + ? extension.toLowerCase() + : extension; + const suffix = ` conflict ${id().slice(0, 8)}${ending}`; const characters = Array.from(name.slice(0, name.length - extension.length)); while ( encoder.encode(`${characters.join("")}${suffix}`).length > MAX_NAME_BYTES diff --git a/src/controller.ts b/src/controller.ts index ce5745e..b037e67 100644 --- a/src/controller.ts +++ b/src/controller.ts @@ -50,7 +50,7 @@ export const REMOVED: Record = { export const STRANDED = "NOTE's key changed while edits from this vault were still waiting to sync. Nothing is overwritten this time: where NOTE has different text, this vault's is kept as a conflict copy beside it."; export const LOCKED_ELSEWHERE = - "Another Obsidian vault on this device is syncing this NOTE account. Close it or unlink it there first."; + "This vault is already syncing in another Obsidian window."; export interface ControllerOptions { custody: Custody; @@ -63,12 +63,13 @@ export interface ControllerOptions { /** The index for one NOTE vault, so relinking to another vault never reuses it. */ indexFor(did: string, vault: string): SyncIndex; /** - * Holds `name` for as long as the vault is open, across every window and - * vault of this app, or answers null when another holder has it. + * Holds this vault's credential store for as long as the vault is open, + * across every window of this app, or answers null when another holder has + * it, so only one device transport ever refreshes its tokens. */ - hold(name: string): Promise<(() => void) | null>; - /** Deletes the device client's local database for this account's vault. */ - forgetLocalDatabase(did: string, vault: string): Promise; + hold(): Promise<(() => void) | null>; + /** Deletes the device client's local databases for this seed, unsynced edits included. */ + forgetDevice(seed: Uint8Array): Promise; confirmDeletions(deletions: Deletions): Promise; onChange(): void; onTrustLoss(loss: TrustLoss): void; @@ -229,30 +230,25 @@ export class SyncController { } /** - * Wipes the keys and drops the sync index, whose base the device's database - * no longer backs. The database goes too, unless another vault on this - * device holds the account: the device client names it by account and - * vault only, so it is that vault's database as well. + * Wipes the keys, the device's local databases and the sync index, whose + * base those databases no longer back. Unsynced edits in them are dropped; + * the files here still hold them. */ private async forget() { - const { custody, hold, indexFor, forgetLocalDatabase } = this.options; + const { custody, indexFor, forgetDevice } = this.options; const credentials = await custody.credentials.read(); const checkpoint = await custody.checkpoints.read(); + const seed = custody.seed(); this.close(); custody.wipe(); - if (!credentials || !checkpoint) return; - const { did } = credentials; - await indexFor(did, checkpoint.vault) - .clear() - .catch(() => {}); - const release = await hold(`flow-note:${did}`); - if (!release) return; try { - await forgetLocalDatabase(did, checkpoint.vault); - } catch { - // A database another window still holds open is left for the next unlink. + if (credentials && checkpoint) + await indexFor(credentials.did, checkpoint.vault) + .clear() + .catch(() => {}); + if (seed) await forgetDevice(seed).catch(() => {}); } finally { - release(); + seed?.fill(0); } } @@ -288,7 +284,7 @@ export class SyncController { if (!seed || !credentials) return this.set({ kind: "unlinked" }); if (custody.account()?.did !== credentials.did) return void this.start(); this.set({ kind: "opening" }); - const release = await this.options.hold(`flow-note:${credentials.did}`); + const release = await this.options.hold(); if (!this.live(generation)) return release?.(); if (!release) return this.set({ kind: "stopped", message: LOCKED_ELSEWHERE }); @@ -367,7 +363,6 @@ export class SyncController { this.lastRound = { applied: 0, failed: [{ path: "", error: messageOf(error) }], - attachments: 0, unsyncable: [], held: { local: 0, remote: 0 }, }; diff --git a/src/device.ts b/src/device.ts index f293599..d38a1b8 100644 --- a/src/device.ts +++ b/src/device.ts @@ -8,6 +8,7 @@ export { type DeviceCheckpointStore, type DeviceOptions, type DeviceVault, + deleteDeviceStorage, LINK_EXPIRED, LINK_UNVERIFIED, type LinkOptions, diff --git a/src/engine.ts b/src/engine.ts index a9441f3..e27d704 100644 --- a/src/engine.ts +++ b/src/engine.ts @@ -1,10 +1,11 @@ import { sha256 } from "./hash"; import { exclusion, isNotePath, pathKey } from "./paths"; import { + type Body, type Entry, - type LocalNote, + type LocalItem, plan, - type RemoteNote, + type RemoteItem, type Step, } from "./plan"; @@ -14,23 +15,30 @@ export interface LocalFile { size: number; } /** - * The Obsidian vault as sync sees it. Every write is conditional, so an edit - * the person makes while a round runs is never overwritten: the write + * The Obsidian vault as sync sees it. Writes over text are conditional, so an + * edit the person makes while a round runs is never overwritten: the write * reports false and the next round picks the edit up. */ export interface LocalVault { /** Every file Obsidian knows of; its config folder and hidden files aren't among them. */ list(): Promise; read(path: string): Promise; + readBinary(path: string): Promise; /** Creates the file and any missing folders; false when something is already there. */ - create(path: string, source: string): Promise; + create(path: string, body: Body): Promise; /** Replaces the text only if it is still exactly `expected`. */ replace(path: string, expected: string, next: string): Promise; + /** Replaces an attachment's bytes, which the caller checked just before. */ + overwrite(path: string, bytes: Uint8Array): Promise; /** Renames without rewriting links elsewhere; false when `to` is taken or `from` is gone. */ move(from: string, to: string): Promise; /** Moves the file to the trash Obsidian is set to use. */ trash(path: string): Promise; } +export interface RevisionBase { + revision: string; + digest: string; +} export interface RemoteNoteView { id: string; path: string; @@ -38,12 +46,27 @@ export interface RemoteNoteView { revision?: string; digest?: string; } +export interface RemoteAttachmentView { + id: string; + path: string; + revision: string; + digest: string; +} /** The linked NOTE vault, as the device client's `DeviceVault` offers it. */ export interface RemoteVault { read(): Promise<{ notes: RemoteNoteView[] }>; - /** Resolves with the revision the saved text now has. */ - saveNote(note: RemoteNoteView): Promise<{ revision: string; digest: string }>; - rename(id: string, path: string): Promise; + listAttachments(): Promise; + readAttachment(id: string): Promise; + /** Each save resolves with the revision the content now has. */ + saveNote(note: RemoteNoteView): Promise; + saveAttachment(attachment: { + id: string; + path: string; + bytes: Uint8Array; + revision?: string; + digest?: string; + }): Promise; + rename(id: string, path: string): Promise; remove(id: string): Promise; } /** Where the entries live between rounds: outside the vault folder, per linked device. */ @@ -59,9 +82,12 @@ export interface Deletions { export interface RoundResult { applied: number; failed: { path: string; error: string }[]; - /** Attachments, which this version doesn't sync yet. */ - attachments: number; - /** Notes whose names NOTE can't store, or notes in NOTE whose names this vault can't hold. */ + /** + * Files left out: names NOTE can't store, names that differ only in case, + * attachments over `MAX_ATTACHMENT_BYTES`, and NOTE items under names this + * vault can't hold. A synced item that becomes one of these is left alone + * on both sides, never deleted. + */ unsyncable: string[]; /** Deletions waiting for the person to confirm them. */ held: Deletions; @@ -79,8 +105,10 @@ export interface EngineOptions { newId?(): string; } -/** More deletions than this, and more than a tenth of the synced notes, need confirming. */ +/** More deletions than this, and more than a tenth of the synced items, need confirming. */ const MASS_DELETION = 10; +/** NOTE imports files up to this size; a larger attachment stays on this device. */ +export const MAX_ATTACHMENT_BYTES = 32_000_000; const MAX_PASSES = 3; const deletionsOf = (steps: readonly Step[]): Deletions => ({ @@ -99,7 +127,7 @@ const isDeletion = (step: Step) => export class SyncEngine { private entries = new Map(); private remoteHashes = new Map(); - private cached: RemoteNote[] | null = null; + private cached: RemoteItem[] | null = null; private running: Promise | null = null; private again = false; private declined = new Set(); @@ -193,18 +221,26 @@ export class SyncEngine { const result: RoundResult = { applied: 0, failed: [], - attachments: 0, unsyncable: [], held: { local: 0, remote: 0 }, }; for (let pass = 0; pass < MAX_PASSES && !this.stopped; pass++) { result.unsyncable = []; - const remote = await this.readRemote(result); - const local = await this.scanLocal(result); + const frozen = new Set(); + const remote = await this.readRemote(result, frozen); + const local = await this.scanLocal(result, frozen); + const frozenPaths = new Set( + [...frozen].flatMap((id) => { + const entry = this.entries.get(id); + return entry ? [pathKey(entry.moved ?? entry.path)] : []; + }), + ); const planned = plan({ - entries: [...this.entries.values()], - local, - remote, + entries: [...this.entries.values()].filter( + (entry) => !frozen.has(entry.id), + ), + local: local.filter((item) => !frozenPaths.has(pathKey(item.path))), + remote: remote.filter((item) => !frozen.has(item.id)), newId: this.newId, }); const steps = await this.confirmed(planned, result); @@ -264,54 +300,95 @@ export class SyncEngine { return steps.filter((step) => !held.has(step)); } - private async readRemote(result: RoundResult): Promise { + /** + * Both kinds of NOTE item, each with the hash of its content: a note's from + * its text, an attachment's from the index when its revision is the one + * synced, otherwise from its bytes, read once per revision. + */ + private async readRemote( + result: RoundResult, + frozen: Set, + ): Promise { if (!this.cached) { - const { notes } = await this.options.remote.read(); - const hashed: RemoteNote[] = []; - for (const note of notes) { - const revision = note.revision ?? ""; - const known = this.remoteHashes.get(note.id); - const hash = - known && known.revision === revision && revision - ? known.hash - : await sha256(note.source); - this.remoteHashes.set(note.id, { revision, hash }); - hashed.push({ ...note, hash }); - } - this.cached = hashed; + const { remote } = this.options; + const [{ notes }, attachments] = await Promise.all([ + remote.read(), + remote.listAttachments(), + ]); + const items: RemoteItem[] = []; + for (const note of notes) + items.push({ + id: note.id, + path: note.path, + revision: note.revision, + digest: note.digest, + body: note.source, + hash: await this.remoteHash( + note.id, + note.revision, + () => note.source, + ), + }); + for (const attachment of attachments) + items.push({ + ...attachment, + hash: await this.remoteHash(attachment.id, attachment.revision, () => + remote.readAttachment(attachment.id), + ), + }); + this.cached = items; } - return this.cached.filter((note) => { - if (!exclusion(note.path, this.options.configDir)) return true; - result.unsyncable.push(note.path); + return this.cached.filter((item) => { + if (!exclusion(item.path, this.options.configDir)) return true; + result.unsyncable.push(item.path); + if (this.entries.has(item.id)) frozen.add(item.id); return false; }); } - private async scanLocal(result: RoundResult): Promise { + private async remoteHash( + id: string, + revision: string | undefined, + body: () => Body | Promise, + ): Promise { + const synced = this.entries.get(id); + if (revision && synced?.revision === revision && synced.hash) + return synced.hash; + const known = this.remoteHashes.get(id); + if (revision && known?.revision === revision) return known.hash; + const hash = await sha256(await body()); + this.remoteHashes.set(id, { revision: revision ?? "", hash }); + return hash; + } + + private async scanLocal( + result: RoundResult, + frozen: Set, + ): Promise { const byPath = new Map( [...this.entries.values()].map((entry) => [ pathKey(entry.moved ?? entry.path), entry, ]), ); - result.attachments = 0; const files = new Map(); for (const file of await this.options.local.list()) { - if (exclusion(file.path, this.options.configDir)) { - if (isNotePath(file.path)) result.unsyncable.push(file.path); - continue; - } - if (!isNotePath(file.path)) { - result.attachments++; + const key = pathKey(file.path); + if ( + exclusion(file.path, this.options.configDir) || + (!isNotePath(file.path) && file.size > MAX_ATTACHMENT_BYTES) + ) { + result.unsyncable.push(file.path); + const entry = byPath.get(key); + if (entry) frozen.add(entry.id); continue; } - const key = pathKey(file.path); files.set(key, [...(files.get(key) ?? []), file]); } - const notes: LocalNote[] = []; + const items: LocalItem[] = []; for (const [key, group] of files) { const entry = byPath.get(key); - // Names that differ only in case are one note to NOTE: only the synced one syncs. + // Names that differ only in case are one item to NOTE: only the synced one syncs. const file = group.length === 1 ? group[0] @@ -322,20 +399,26 @@ export class SyncEngine { if (other !== file) result.unsyncable.push(other.path); if (!file) continue; if (entry && entry.mtime === file.mtime && entry.size === file.size) { - notes.push({ path: file.path, hash: entry.hash }); + items.push({ path: file.path, hash: entry.hash }); continue; } - const source = await this.options.local.read(file.path); - const hash = await sha256(source); + const body = await this.readLocal(file.path); + const hash = await sha256(body); // The listing's stat predates the read, so a later edit still shows as a new stat. if (entry?.hash === hash) { entry.mtime = file.mtime; entry.size = file.size; this.dirty = true; } - notes.push({ path: file.path, hash, source }); + items.push({ path: file.path, hash, body }); } - return notes; + return items; + } + + private readLocal(path: string): Promise { + return isNotePath(path) + ? this.options.local.read(path) + : this.options.local.readBinary(path); } private async apply(step: Step, result: RoundResult) { @@ -366,25 +449,41 @@ export class SyncEngine { } } - /** The local file still holds what the plan saw: its text, or the hash of text it didn't need to read. */ - private async unchanged(local: LocalNote): Promise { - const current = await this.options.local.read(local.path); + /** The local file's content, if it still is what the plan saw; null once it changed. */ + private async unchanged(local: LocalItem): Promise { + const current = await this.readLocal(local.path); return (await sha256(current)) === local.hash ? current : null; } + private save( + id: string, + path: string, + body: Body, + base?: Partial, + ) { + const { remote } = this.options; + const revision = base?.revision; + const digest = base?.digest; + return typeof body === "string" + ? remote.saveNote({ id, path, source: body, revision, digest }) + : remote.saveAttachment({ id, path, bytes: body, revision, digest }); + } + private async update(step: Extract) { const { id, path, content, local, remote, copy } = step; const { local: files, remote: vault } = this.options; - let revision = remote?.revision ?? ""; - let digest = remote?.digest ?? ""; + let base: RevisionBase = { + revision: remote?.revision ?? "", + digest: remote?.digest ?? "", + }; let hash = remote?.hash ?? local?.hash ?? ""; if (copy) { - const source = local?.source; - if (source === undefined) throw new Error("Conflict without local text"); - if (!(await files.create(copy, source))) + const body = local?.body; + if (body === undefined) throw new Error("Conflict without local content"); + if (!(await files.create(copy, body))) throw new Error(`${copy} already exists`); const copyId = this.newId(); - const saved = await vault.saveNote({ id: copyId, path: copy, source }); + const saved = await this.save(copyId, copy, body); this.remoteChanged(); this.record({ id: copyId, @@ -394,19 +493,13 @@ export class SyncEngine { }); } if (content === "local") { - const source = local?.source; - if (source === undefined) throw new Error("Push without local text"); - ({ revision, digest } = await vault.saveNote({ - id, - path, - source, - revision: remote?.revision, - digest: remote?.digest, - })); + const body = local?.body; + if (body === undefined) throw new Error("Push without local content"); + base = await this.save(id, path, body, remote); this.remoteChanged(); hash = local?.hash ?? ""; } else if (remote && remote.path !== path) { - await vault.rename(id, path); + base = await vault.rename(id, path); this.remoteChanged(); } if (this.stopped) throw new Error("Sync stopped"); @@ -418,17 +511,23 @@ export class SyncEngine { if (entry) entry.moved = path; } if (content === "remote" && remote) { + const body = remote.body ?? (await vault.readAttachment(id)); const written = local - ? await this.replaceAt(path, local, remote.source) - : await files.create(path, remote.source); + ? await this.replaceAt(path, local, body) + : await files.create(path, body); if (!written) throw new Error(`${path} changed while syncing`); } - this.record({ id, path, hash, revision, digest }); + this.record({ id, path, hash, ...base }); } - private async replaceAt(path: string, local: LocalNote, next: string) { + private async replaceAt(path: string, local: LocalItem, next: Body) { const current = await this.unchanged({ ...local, path }); if (current === null) return false; + if (typeof current !== "string" || typeof next !== "string") { + if (this.stopped) return false; + await this.options.local.overwrite(path, next as Uint8Array); + return true; + } return current === next || this.options.local.replace(path, current, next); } diff --git a/src/hash.ts b/src/hash.ts index 18d5b54..9c8d39a 100644 --- a/src/hash.ts +++ b/src/hash.ts @@ -1,8 +1,9 @@ const encoder = new TextEncoder(); -/** Hex SHA-256 of `text`'s UTF-8 bytes. */ -export async function sha256(text: string): Promise { - const digest = await crypto.subtle.digest("SHA-256", encoder.encode(text)); +/** Hex SHA-256 of a note's UTF-8 text or an attachment's bytes. */ +export async function sha256(body: string | Uint8Array): Promise { + const bytes = typeof body === "string" ? encoder.encode(body) : body; + const digest = await crypto.subtle.digest("SHA-256", bytes as BufferSource); return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0"), ).join(""); diff --git a/src/index-store.ts b/src/index-store.ts index b458f28..5eb0237 100644 --- a/src/index-store.ts +++ b/src/index-store.ts @@ -59,31 +59,3 @@ export class IndexedDbIndex implements SyncIndex { await request(this.factory.deleteDatabase(this.name)); } } - -/** - * Deletes the device client's local database for one NOTE vault, every key - * epoch of it, so an unlinked vault leaves no ciphertext in this app. A - * database another window still holds open is left after `timeoutMs`. - */ -export async function forgetVaultDatabases( - did: string, - vault: string, - factory: IDBFactory = indexedDB, - timeoutMs = 5_000, -) { - const name = `flow-note:${did}:${vault}`; - const names = (await factory.databases?.()) ?? []; - await Promise.all( - names - .map((database) => database.name) - .filter( - (database) => database === name || database?.startsWith(`${name}:`), - ) - .map((database) => - Promise.race([ - request(factory.deleteDatabase(database ?? name)), - new Promise((resolve) => setTimeout(resolve, timeoutMs)), - ]), - ), - ); -} diff --git a/src/lock.ts b/src/lock.ts index 042115b..cfc2b7d 100644 --- a/src/lock.ts +++ b/src/lock.ts @@ -1,8 +1,7 @@ /** * Takes the Web Lock `name` without waiting and holds it until the returned * function is called; null when someone else holds it. Locks span every - * window of this app's origin, so two vaults open at once can't both run a - * device transport on the same account. Without Web Locks, nothing is held. + * window of this app's origin. Without Web Locks, nothing is held. */ export function holdLock( name: string, diff --git a/src/main.ts b/src/main.ts index bcd828a..f4e797a 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3,6 +3,7 @@ import { SyncController } from "./controller"; import { Custody } from "./custody"; import { createDeviceSeed, + deleteDeviceStorage, linkDevice, openDeviceVault, pulledStatus, @@ -10,7 +11,7 @@ import { type TrustLoss, } from "./device"; import { requestUrlFetch } from "./fetch"; -import { forgetVaultDatabases, IndexedDbIndex } from "./index-store"; +import { IndexedDbIndex } from "./index-store"; import { holdLock } from "./lock"; import { confirm, LinkModal } from "./obsidian/modals"; import { NoteSyncSettingTab, statusText } from "./obsidian/settings"; @@ -49,13 +50,13 @@ export default class NoteSyncPlugin extends Plugin { configDir: this.app.vault.configDir, indexFor: (did, vault) => new IndexedDbIndex(`flow-note-sync:${namespace}:${did}:${vault}`), - hold: holdLock, - forgetLocalDatabase: (did, vault) => forgetVaultDatabases(did, vault), + hold: () => holdLock(`flow-note:${namespace}`), + forgetDevice: deleteDeviceStorage, confirmDeletions: ({ local, remote }) => confirm( this.app, - "Delete these notes?", - `This sync would move ${local} notes here and ${remote} notes in NOTE to the trash. That can mean they were deleted on purpose, or that one side looks empty when it isn't. Nothing is deleted unless you confirm.`, + "Delete these files?", + `This sync would move ${local} files here and ${remote} in NOTE to the trash. That can mean they were deleted on purpose, or that one side looks empty when it isn't. Nothing is deleted unless you confirm.`, "Move to trash", { warning: true }, ), diff --git a/src/obsidian/settings.ts b/src/obsidian/settings.ts index 2799390..e5040fd 100644 --- a/src/obsidian/settings.ts +++ b/src/obsidian/settings.ts @@ -138,11 +138,8 @@ export class NoteSyncSettingTab extends PluginSettingTab { ...round.failed .slice(0, 5) .map(({ path, error }) => `${path || "Sync"}: ${error}`), - round.attachments - ? `${round.attachments} attachments stay on this device: this version syncs Markdown and MDX notes only.` - : "", round.unsyncable.length - ? `Not synced, because one side can't store the name: ${round.unsyncable.slice(0, 5).join(", ")}${round.unsyncable.length > 5 ? "…" : ""}` + ? `Not synced (a name one side can't store, a name that differs only in case, or an attachment over 32 MB): ${round.unsyncable.slice(0, 5).join(", ")}${round.unsyncable.length > 5 ? "…" : ""}` : "", round.held.local || round.held.remote ? `Held back: ${round.held.local} deletions here and ${round.held.remote} in NOTE. Sync now to review them.` diff --git a/src/obsidian/vault.ts b/src/obsidian/vault.ts index ba3ead5..e0e44df 100644 --- a/src/obsidian/vault.ts +++ b/src/obsidian/vault.ts @@ -3,6 +3,12 @@ import type { SecretBackend } from "../custody"; import type { LocalVault } from "../engine"; import { parentOf, pathKey } from "../paths"; +const arrayBufferOf = (bytes: Uint8Array) => + bytes.buffer.slice( + bytes.byteOffset, + bytes.byteOffset + bytes.byteLength, + ) as ArrayBuffer; + /** The Obsidian vault through its Vault API; renames never rewrite links, since NOTE already repaired them. */ export function obsidianVault(app: App): LocalVault { const { vault, fileManager } = app; @@ -37,13 +43,24 @@ export function obsidianVault(app: App): LocalVault { if (!file) throw new Error(`${path} is gone`); return vault.read(file); }, - async create(path, source) { + async readBinary(path) { + const file = fileAt(path); + if (!file) throw new Error(`${path} is gone`); + return new Uint8Array(await vault.readBinary(file)); + }, + async create(path, body) { const target = normalizePath(path); if (!(await free(target))) return false; await ensureFolder(target); - await vault.create(target, source); + if (typeof body === "string") await vault.create(target, body); + else await vault.createBinary(target, arrayBufferOf(body)); return true; }, + async overwrite(path, bytes) { + const file = fileAt(path); + if (!file) throw new Error(`${path} is gone`); + await vault.modifyBinary(file, arrayBufferOf(bytes)); + }, async replace(path, expected, next) { const file = fileAt(path); if (!file) return false; diff --git a/src/plan.ts b/src/plan.ts index d4cf658..bbbd8c2 100644 --- a/src/plan.ts +++ b/src/plan.ts @@ -1,7 +1,7 @@ import { conflictPath } from "./conflicts"; -import { pathKey } from "./paths"; +import { isNotePath, pathKey } from "./paths"; -/** What both sides agreed a note was at the last sync. */ +/** What both sides agreed a note or attachment was at the last sync. */ export interface Entry { id: string; path: string; @@ -10,31 +10,34 @@ export interface Entry { /** The remote revision synced; empty until a read or a save names it. */ revision: string; digest: string; - /** SHA-256 of the source synced. */ + /** SHA-256 of the text or bytes synced. */ hash: string; /** The local file's stat at the last sync, so an unchanged file isn't read again. */ mtime: number; size: number; } -/** A note file in the Obsidian vault; `source` is read whenever it may have changed. */ -export interface LocalNote { +/** A note's text or an attachment's bytes. */ +export type Body = string | Uint8Array; +/** A file in the Obsidian vault; `body` is read whenever it may have changed. */ +export interface LocalItem { path: string; hash: string; - source?: string; + body?: Body; } -export interface RemoteNote { +/** A note or attachment in NOTE; an attachment's bytes are read only when a step needs them. */ +export interface RemoteItem { id: string; path: string; - source: string; + hash: string; revision?: string; digest?: string; - hash: string; + body?: Body; } /** - * One note's change. An update writes `content`'s side over the other at + * One item's change. An update writes `content`'s side over the other at * `path` (`same`: only paths or the index change), and `copy` keeps the - * local text as a new note beside it when both sides edited it. + * local version as a new item beside it when both sides changed it. */ export type Step = | { @@ -42,18 +45,18 @@ export type Step = id: string; path: string; content: "local" | "remote" | "same"; - local?: LocalNote; - remote?: RemoteNote; + local?: LocalItem; + remote?: RemoteItem; copy?: string; } - | { kind: "delete-local"; id: string; local: LocalNote } + | { kind: "delete-local"; id: string; local: LocalItem } | { kind: "delete-remote"; id: string } | { kind: "forget"; id: string }; export interface PlanInput { entries: readonly Entry[]; - local: readonly LocalNote[]; - remote: readonly RemoteNote[]; + local: readonly LocalItem[]; + remote: readonly RemoteItem[]; newId?: () => string; } @@ -70,17 +73,22 @@ const samePath = (a: string, b: string) => */ function claimLocal( entries: readonly Entry[], - local: Map, -): Map { + local: Map, +): Map { const owners = new Map(); const byMove = [...entries].sort( (a, b) => Number(!a.moved) - Number(!b.moved), ); + // A note never pairs with an attachment: NOTE can't turn one into the other. + const sameKind = (entry: Entry, item: LocalItem) => + isNotePath(entry.path) === isNotePath(item.path); for (const entry of byMove) { const key = pathKey(currentPath(entry)); - if (local.has(key) && !owners.has(key)) owners.set(key, entry); + const item = local.get(key); + if (item && sameKind(entry, item) && !owners.has(key)) + owners.set(key, entry); } - const found = new Map(); + const found = new Map(); for (const [key, entry] of owners) { const note = local.get(key); if (note) found.set(entry.id, note); @@ -88,10 +96,12 @@ function claimLocal( const unclaimed = [...local] .filter(([key]) => !owners.has(key)) .map(([, note]) => note); - const taken = new Set(); + const taken = new Set(); for (const entry of entries) { if (found.has(entry.id)) continue; - const matches = unclaimed.filter((note) => note.hash === entry.hash); + const matches = unclaimed.filter( + (item) => item.hash === entry.hash && sameKind(entry, item), + ); const [match] = matches; if (matches.length !== 1 || !match || taken.has(match)) continue; taken.add(match); @@ -102,8 +112,8 @@ function claimLocal( function updateOf( entry: Entry, - local: LocalNote, - remote: RemoteNote, + local: LocalItem, + remote: RemoteItem, newId: () => string, ): Step | null { const localChanged = local.hash !== entry.hash; diff --git a/tests/controller.test.ts b/tests/controller.test.ts index d738f53..2c558b4 100644 --- a/tests/controller.test.ts +++ b/tests/controller.test.ts @@ -41,6 +41,14 @@ function deviceVault(remote: MemoryRemote, stranded = false) { const vault = { read: () => remote.read().then((view) => ({ ...view, folders: [] })), saveNote: (note) => remote.saveNote(note), + listAttachments: async () => + (await remote.listAttachments()).map((item) => ({ + ...item, + mime: "application/octet-stream", + size: 0, + })), + readAttachment: (id) => remote.readAttachment(id), + saveAttachment: (attachment) => remote.saveAttachment(attachment), rename: (id, path) => remote.rename(id, path), remove: (id) => remote.remove(id), compose: async () => ({ selectedId: "" }), @@ -102,8 +110,8 @@ async function harness( configDir: ".obsidian", indexFor: () => index, hold: async () => (options.held ? null : () => {}), - forgetLocalDatabase: async (owner, vault) => { - forgotten.push(`${owner}:${vault}`); + forgetDevice: async (seed) => { + forgotten.push(`seed ${seed[0]}`); }, confirmDeletions: async () => true, onChange: () => {}, @@ -131,10 +139,10 @@ describe("controller", () => { h.local.put("Here.md", "local"); await h.controller.start(); await h.controller.syncNow(); - expect(h.remote.notes.size).toBe(0); + expect(h.remote.items.size).toBe(0); h.device.state.pull = true; await h.controller.syncNow(); - expect(h.remote.byPath("Here.md")?.source).toBe("local"); + expect(h.remote.text("Here.md")).toBe("local"); h.controller.close(); }); @@ -144,7 +152,7 @@ describe("controller", () => { await h.controller.start(); expect(h.controller.phase.kind).toBe("confirm"); await h.controller.syncNow(); - expect(h.remote.notes.size).toBe(0); + expect(h.remote.items.size).toBe(0); }); test("a vault closed or unlinked while it opens never opens", async () => { @@ -161,7 +169,7 @@ describe("controller", () => { await Bun.sleep(5); expect(h.controller.phase.kind).not.toBe("open"); expect(h.device.state.stopped).toBe(true); - expect(h.remote.notes.size).toBe(0); + expect(h.remote.items.size).toBe(0); if (interrupt === "unlink") { expect(h.controller.phase.kind).toBe("unlinked"); expect(h.custody.seed()).toBeNull(); @@ -177,19 +185,17 @@ describe("controller", () => { expect(h.controller.phase.kind).toBe("linking"); }); - test("another vault syncing the same account stops this one, and keeps its database on unlink", async () => { + test("a second window of the same vault doesn't open a second transport", async () => { const h = await harness({ held: true }); await h.controller.start(); expect(h.controller.phase).toEqual({ kind: "stopped", message: LOCKED_ELSEWHERE, }); - await h.controller.unlink(); - expect(h.forgotten).toEqual([]); - expect(h.custody.seed()).toBeNull(); + expect(h.device.state.stopped).toBe(false); }); - test("unlinking forgets the device's database and the sync index", async () => { + test("unlinking forgets the device's databases, by its seed, and the sync index", async () => { const h = await harness(); await h.controller.start(); await h.controller.syncNow(); @@ -205,7 +211,7 @@ describe("controller", () => { }, ]; await h.controller.unlink(); - expect(h.forgotten).toEqual([`${did}:vault`]); + expect(h.forgotten).toEqual(["seed 1"]); expect(h.index.entries).toEqual([]); expect(h.secrets.values.has("flow-note-0123456789abcdef-tokens")).toBe( false, diff --git a/tests/e2e.test.ts b/tests/e2e.test.ts index 8755c79..dd3616f 100644 --- a/tests/e2e.test.ts +++ b/tests/e2e.test.ts @@ -1,18 +1,19 @@ import { afterEach, describe, expect, test } from "bun:test"; import { + type AdminBrowser, adminBrowser, approveLink, - dropDevices, type FakeFlowId, fakeFlowId, - host, - useStorage, + openAdminVault, + TEST_DID, + TEST_HOST, } from "@flow-industries/seal/testing"; -import { IDBFactory, IDBKeyRange } from "fake-indexeddb"; -import { REMOVED, SyncController } from "../src/controller"; +import { SyncController } from "../src/controller"; import { Custody, type SecretBackend } from "../src/custody"; import { createDeviceSeed, + deleteDeviceStorage, type LinkPrompt, linkDevice, openDeviceVault, @@ -25,8 +26,9 @@ import { MemoryIndex, MemoryVault } from "./fakes"; /** * Two Obsidian vaults linked as two devices of one NOTE notepad, syncing - * through the device client against an in-memory Flow ID and PDS. One - * process plays both, so each gets its own IndexedDB and they take turns. + * through the device client against seal's in-memory Flow ID and PDS. Each + * device keeps its own local database; the vaults take turns so each step's + * order is fixed. */ class Secrets implements SecretBackend { values = new Map(); @@ -40,7 +42,6 @@ function obsidian(note: FakeFlowId, name: string) { const secrets = new Secrets(); const custody = new Custody(secrets, `${name}0000000000`); const indexes = new Map(); - const storage = new IDBFactory(); const prompts: LinkPrompt[] = []; const losses: TrustLoss[] = []; const notices: string[] = []; @@ -53,7 +54,7 @@ function obsidian(note: FakeFlowId, name: string) { locked: SYNC_LOCKED, pulled: pulledStatus, }, - host, + host: TEST_HOST, fetch: note.fetch, local, configDir: ".obsidian", @@ -64,7 +65,7 @@ function obsidian(note: FakeFlowId, name: string) { return index; }, hold: async () => () => {}, - forgetLocalDatabase: async () => {}, + forgetDevice: deleteDeviceStorage, confirmDeletions: async () => true, onChange: () => { if (controller?.phase.kind === "linking" && controller.phase.prompt) @@ -75,7 +76,6 @@ function obsidian(note: FakeFlowId, name: string) { }); /** Opens this vault's link, lets `work` run, then closes it for the other vault's turn. */ async function turn(work: () => Promise = async () => {}) { - await useStorage(storage, IDBKeyRange); await controller.start(); expect(controller.phase.kind).toBe("open"); await controller.syncNow(); @@ -90,18 +90,13 @@ function obsidian(note: FakeFlowId, name: string) { controller, prompts, losses, - storage, + notices, turn, }; } type Obsidian = ReturnType; -async function link( - note: FakeFlowId, - admin: Awaited>, - vault: Obsidian, -) { - await useStorage(vault.storage, IDBKeyRange); +async function link(admin: AdminBrowser, vault: Obsidian) { const linking = vault.controller.link( "Obsidian on test", new AbortController().signal, @@ -111,7 +106,7 @@ async function link( const [prompt] = vault.prompts; if (!prompt) throw new Error("No prompt"); expect(prompt.pairingCode).toMatch(/^\d{4} \d{4} \d{4}$/); - await approveLink(note, admin, prompt); + await approveLink(admin, prompt); return linking; } @@ -130,26 +125,54 @@ describe("two Obsidian vaults synced through NOTE", () => { a.local.put("Inbox/First.md", "# Written in vault A"); a.local.put("Code.mdx", "export const x = 1\n\n"); - const account = await link(note, admin, a); - expect(account.did).toBe("did:plc:devicee2e"); + const photo = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 1, 2, 3]); + a.local.put("img/photo.png", photo); + const account = await link(admin, a); + expect(account.did).toBe(TEST_DID); expect(a.controller.phase.kind).toBe("confirm"); // Linked but unconfirmed: a restart still asks, and nothing has synced. await a.controller.start(); expect(a.controller.phase.kind).toBe("confirm"); expect(a.custody.account()).toBeNull(); await a.controller.confirm(); - expect(a.custody.account()).toEqual({ did: "did:plc:devicee2e" }); + expect(a.custody.account()).toEqual({ did: TEST_DID }); await a.controller.syncNow(); + console.log( + "A", + JSON.stringify(a.controller.lastRound), + JSON.stringify(a.controller.phase), + ); a.controller.close(); - await link(note, admin, b); + await link(admin, b); await b.controller.confirm(); await b.controller.syncNow(); + console.log( + "B", + JSON.stringify(b.controller.lastRound), + JSON.stringify(b.controller.phase), + [...b.local.files.keys()], + ); b.controller.close(); expect(b.local.text("Inbox/First.md")).toBe("# Written in vault A"); expect(b.local.text("Code.mdx")).toBe( "export const x = 1\n\n", ); + expect(b.local.files.get("img/photo.png")?.body).toEqual(photo); + + // A note written in NOTE itself, signed by the passkey, reaches both vaults. + const web = await openAdminVault(admin); + await web.sync(); + await web.save({ + id: crypto.randomUUID(), + path: "From NOTE.md", + source: "# Written in NOTE", + kind: "md", + }); + await web.sync(); + web.lock(); + await a.turn(); + expect(a.local.text("From NOTE.md")).toBe("# Written in NOTE"); await b.turn(async () => { b.local.put("Inbox/First.md", "# Edited in vault B"); @@ -182,7 +205,6 @@ describe("two Obsidian vaults synced through NOTE", () => { expect(note.violations).toEqual([]); note.revokeAll(); - await useStorage(a.storage, IDBKeyRange); await a.controller.start(); expect(a.controller.phase.kind).toBe("removed"); expect(a.custody.seed()).toBeNull(); @@ -191,43 +213,17 @@ describe("two Obsidian vaults synced through NOTE", () => { await a.controller.syncNow(); expect(a.controller.phase.kind).toBe("removed"); - await useStorage(b.storage, IDBKeyRange); + const databases = async () => + (await indexedDB.databases()).filter((db) => + db.name?.startsWith("flow-note:"), + ).length; + const before = await databases(); await b.controller.unlink(); expect(b.controller.phase.kind).toBe("unlinked"); + expect(await databases()).toBeLessThan(before); expect(b.secrets.values.has("flow-note-bbbbbb0000000000-seed")).toBe(false); expect(b.secrets.values.has("flow-note-bbbbbb0000000000-tokens")).toBe( false, ); }, 120_000); - - test("a vault removed under Access while syncing stops and wipes its keys, keeping its files", async () => { - const note = fakeFlowId(); - const admin = await adminBrowser(note); - const a = obsidian(note, "cccccc"); - opened.push(a); - a.local.put("Kept.md", "synced before removal"); - await link(note, admin, a); - await a.controller.confirm(); - await a.controller.syncNow(); - expect(a.controller.phase.kind).toBe("open"); - - await dropDevices(note, admin); - a.local.put("Late.md", "written after removal"); - await a.controller.syncNow(); - for ( - let wait = 0; - a.controller.phase.kind !== "removed" && wait < 100; - wait++ - ) - await new Promise((resolve) => setTimeout(resolve, 50)); - expect(a.controller.phase).toEqual({ - kind: "removed", - message: REMOVED.removed, - }); - expect(a.custody.seed()).toBeNull(); - expect(await a.custody.credentials.read()).toBeNull(); - expect(await a.custody.checkpoints.read()).not.toBeNull(); - expect(a.local.text("Kept.md")).toBe("synced before removal"); - expect(note.violations).toEqual([]); - }, 60_000); }); diff --git a/tests/engine.test.ts b/tests/engine.test.ts index 31648dc..52219e9 100644 --- a/tests/engine.test.ts +++ b/tests/engine.test.ts @@ -1,5 +1,9 @@ import { describe, expect, test } from "bun:test"; -import { type Deletions, SyncEngine } from "../src/engine"; +import { + type Deletions, + MAX_ATTACHMENT_BYTES, + SyncEngine, +} from "../src/engine"; import { MemoryIndex, MemoryRemote, MemoryVault } from "./fakes"; async function setup( @@ -31,42 +35,89 @@ const settled = async ({ engine }: Setup) => { return first; }; const remotePaths = (remote: MemoryRemote) => - [...remote.notes.values()] - .map((note) => `${note.path}: ${note.source}`) + [...remote.items.values()] + .map((item) => `${item.path}: ${remote.text(item.path)}`) .sort(); const localPaths = (local: MemoryVault) => - [...local.files].map(([path, file]) => `${path}: ${file.source}`).sort(); + [...local.files.keys()].map((path) => `${path}: ${local.text(path)}`).sort(); describe("engine: a first sync", () => { - test("pushes local notes, pulls remote ones, and leaves attachments and config alone", async () => { + test("pushes local files, pulls remote ones, and leaves config and unstorable names alone", async () => { const w = await setup(); + const png = new Uint8Array([137, 80, 78, 71, 1, 2, 3]); + const pdf = new Uint8Array([37, 80, 68, 70, 9]); w.local.put("Here.md", "local"); w.local.put("Dir/Deep.mdx", ""); - w.local.put("photo.png", "binary"); + w.local.put("Dir/photo.png", png); w.local.put("con.md", "a name NOTE refuses"); + w.local.put("huge.bin", new Uint8Array(MAX_ATTACHMENT_BYTES + 1)); w.remote.put("t", "There.md", "remote"); - w.remote.put("hidden", ".obsidian/plugins/x/main.md", "never written"); + w.remote.put("p", "Papers/paper.pdf", pdf); + w.remote.put("hidden", ".obsidian/plugins/x/main.js", "never written"); const result = await settled(w); - expect(remotePaths(w.remote)).toEqual([ - ".obsidian/plugins/x/main.md: never written", - "Dir/Deep.mdx: ", - "Here.md: local", - "There.md: remote", + expect( + [...w.remote.items.values()].map((item) => item.path).sort(), + ).toEqual([ + ".obsidian/plugins/x/main.js", + "Dir/Deep.mdx", + "Dir/photo.png", + "Here.md", + "Papers/paper.pdf", + "There.md", ]); - expect(localPaths(w.local)).toEqual([ - "Dir/Deep.mdx: ", - "Here.md: local", - "There.md: remote", - "con.md: a name NOTE refuses", - "photo.png: binary", + expect(w.remote.byPath("Dir/photo.png")?.body).toEqual(png); + expect([...w.local.files.keys()].sort()).toEqual([ + "Dir/Deep.mdx", + "Dir/photo.png", + "Here.md", + "Papers/paper.pdf", + "There.md", + "con.md", + "huge.bin", ]); - expect(result.attachments).toBe(1); + expect(w.local.files.get("Papers/paper.pdf")?.body).toEqual(pdf); + expect(w.local.text("There.md")).toBe("remote"); expect(result.unsyncable.sort()).toEqual([ - ".obsidian/plugins/x/main.md", + ".obsidian/plugins/x/main.js", "con.md", + "huge.bin", ]); }); + test("carries attachment edits, renames and conflicts, keeping the extension last", async () => { + const w = await setup(); + w.local.put("a.png", new Uint8Array([1])); + await settled(w); + w.local.put("a.png", new Uint8Array([2])); + await settled(w); + expect(w.remote.byPath("a.png")?.body).toEqual(new Uint8Array([2])); + const id = w.remote.byPath("a.png")?.id ?? ""; + await w.remote.rename(id, "img/b.png"); + w.engine.remoteChanged(); + await settled(w); + expect([...w.local.files.keys()]).toEqual(["img/b.png"]); + w.local.put("img/b.png", new Uint8Array([3])); + w.remote.put(id, "img/b.png", new Uint8Array([4])); + w.engine.remoteChanged(); + await settled(w); + const copy = [...w.local.files.keys()].find((path) => path !== "img/b.png"); + expect(copy).toMatch(/^img\/b conflict [0-9a-f]{8}\.png$/); + expect(w.local.files.get("img/b.png")?.body).toEqual(new Uint8Array([4])); + expect(w.local.files.get(copy ?? "")?.body).toEqual(new Uint8Array([3])); + expect(w.remote.byPath(copy ?? "")?.body).toEqual(new Uint8Array([3])); + }); + + test("a synced attachment that grows past the limit is left alone on both sides", async () => { + const w = await setup(); + w.local.put("big.bin", new Uint8Array([1])); + await settled(w); + w.local.put("big.bin", new Uint8Array(MAX_ATTACHMENT_BYTES + 1)); + const result = await w.engine.run(); + expect(result.unsyncable).toEqual(["big.bin"]); + expect(w.remote.byPath("big.bin")?.body).toEqual(new Uint8Array([1])); + expect(w.local.files.has("big.bin")).toBe(true); + }); + test("an existing note on both sides with different text keeps both", async () => { const w = await setup(); w.local.put("Plan.md", "mine"); @@ -78,7 +129,7 @@ describe("engine: a first sync", () => { expect(copy).toMatch(/^plan conflict [0-9a-f]{8}\.md$/); expect(w.local.text("plan.md")).toBe("theirs"); expect(w.local.text(copy ?? "")).toBe("mine"); - expect(w.remote.byPath(copy ?? "")?.source).toBe("mine"); + expect(w.remote.text(copy ?? "")).toBe("mine"); }); }); @@ -97,7 +148,7 @@ describe("engine: after the first sync", () => { w.remote.put("b", "B.md", "two, edited there"); w.engine.remoteChanged(); await settled(w); - expect(w.remote.byPath("A.md")?.source).toBe("one, edited here"); + expect(w.remote.text("A.md")).toBe("one, edited here"); expect(w.local.text("B.md")).toBe("two, edited there"); }); @@ -143,7 +194,7 @@ describe("engine: after the first sync", () => { path.startsWith("A conflict "), ); expect(w.local.text(copy ?? "")).toBe("local edit"); - expect(w.remote.byPath(copy ?? "")?.source).toBe("local edit"); + expect(w.remote.text(copy ?? "")).toBe("local edit"); }); test("deletes both ways, into each side's trash", async () => { @@ -153,7 +204,7 @@ describe("engine: after the first sync", () => { await w.remote.remove(b?.id ?? ""); w.engine.remoteChanged(); await settled(w); - expect(w.remote.notes.size).toBe(0); + expect(w.remote.items.size).toBe(0); expect(w.local.files.size).toBe(0); expect(w.local.trashed).toEqual(["A.md", "B.md"]); }); @@ -195,7 +246,7 @@ describe("engine: mass deletions", () => { const w = await setup({ confirm }); for (let n = 0; n < 12; n++) w.remote.put(`n${n}`, `N${n}.md`, `${n}`); await settled(w); - w.remote.notes.clear(); + w.remote.items.clear(); w.engine.remoteChanged(); return w; } diff --git a/tests/fakes.ts b/tests/fakes.ts index b3ea655..e88ec84 100644 --- a/tests/fakes.ts +++ b/tests/fakes.ts @@ -3,57 +3,79 @@ import type { LocalVault, RemoteNoteView, RemoteVault, + RevisionBase, SyncIndex, } from "../src/engine"; -import { pathKey } from "../src/paths"; -import type { Entry } from "../src/plan"; +import { isNotePath, pathKey } from "../src/paths"; +import type { Body, Entry } from "../src/plan"; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); /** An Obsidian vault in memory; `beforeWrite` lets a test edit a file between a read and a write. */ export class MemoryVault implements LocalVault { - files = new Map(); + files = new Map(); trashed: string[] = []; beforeWrite?: (path: string) => void; private clock = 1; - put(path: string, source: string) { - this.files.set(path, { source, mtime: this.clock++ }); + put(path: string, body: Body) { + this.files.set(path, { body, mtime: this.clock++ }); } text(path: string) { - return this.files.get(path)?.source; + const body = this.files.get(path)?.body; + return body === undefined || typeof body === "string" + ? body + : decoder.decode(body); } async list(): Promise { return [...this.files].map(([path, file]) => ({ path, mtime: file.mtime, - size: file.source.length, + size: + typeof file.body === "string" + ? encoder.encode(file.body).length + : file.body.length, })); } - async read(path: string) { + private body(path: string) { const file = this.files.get(path); if (!file) throw new Error(`No file ${path}`); - return file.source; + return file.body; + } + async read(path: string) { + const body = this.body(path); + return typeof body === "string" ? body : decoder.decode(body); + } + async readBinary(path: string) { + const body = this.body(path); + return typeof body === "string" ? encoder.encode(body) : body.slice(); } private taken(path: string) { return [...this.files.keys()].some((key) => pathKey(key) === pathKey(path)); } - async create(path: string, source: string) { + async create(path: string, body: Body) { this.beforeWrite?.(path); if (this.taken(path)) return false; - this.put(path, source); + this.put(path, typeof body === "string" ? body : body.slice()); return true; } async replace(path: string, expected: string, next: string) { this.beforeWrite?.(path); - if (this.files.get(path)?.source !== expected) return false; + if (this.files.get(path)?.body !== expected) return false; this.put(path, next); return true; } + async overwrite(path: string, bytes: Uint8Array) { + this.beforeWrite?.(path); + this.put(path, bytes.slice()); + } async move(from: string, to: string) { const file = this.files.get(from); if (!file || (pathKey(from) !== pathKey(to) && this.taken(to))) return false; this.files.delete(from); - this.put(to, file.source); + this.put(to, file.body); return true; } async trash(path: string) { @@ -62,48 +84,109 @@ export class MemoryVault implements LocalVault { } } +interface RemoteRow extends RevisionBase { + id: string; + path: string; + body: Body; +} + /** A NOTE vault in memory that refuses saves on a revision it can't place, as the device client does. */ export class MemoryRemote implements RemoteVault { - notes = new Map>(); + items = new Map(); removed: string[] = []; private revisions = 0; - put(id: string, path: string, source: string) { - this.notes.set(id, { id, path, source, ...this.revision() }); + put(id: string, path: string, body: Body) { + this.items.set(id, { id, path, body, ...this.revision() }); } byPath(path: string) { - return [...this.notes.values()].find((note) => note.path === path); + return [...this.items.values()].find((item) => item.path === path); } - private revision() { + text(path: string) { + const body = this.byPath(path)?.body; + return body === undefined || typeof body === "string" + ? body + : decoder.decode(body); + } + private revision(): RevisionBase { const revision = `r${++this.revisions}`; return { revision, digest: `d-${revision}` }; } private collides(id: string, path: string) { - return [...this.notes.values()].some( - (note) => note.id !== id && pathKey(note.path) === pathKey(path), + return [...this.items.values()].some( + (item) => item.id !== id && pathKey(item.path) === pathKey(path), ); } - async read() { - return { notes: [...this.notes.values()].map((note) => ({ ...note })) }; - } - async saveNote(note: RemoteNoteView) { - const current = this.notes.get(note.id); - if (current && current.revision !== note.revision) + private write( + row: Omit, + base: Partial, + ) { + const current = this.items.get(row.id); + if (current && current.revision !== base.revision) throw new Error("This note changed. Read it again."); - if (this.collides(note.id, note.path)) + if (this.collides(row.id, row.path)) throw new Error("Filesystem path collision"); const saved = this.revision(); - this.notes.set(note.id, { ...note, ...saved }); + this.items.set(row.id, { ...row, ...saved }); return saved; } + async read() { + const notes: RemoteNoteView[] = []; + for (const { id, path, body, revision, digest } of this.items.values()) + if (typeof body === "string") + notes.push({ id, path, source: body, revision, digest }); + return { notes }; + } + async listAttachments() { + return [...this.items.values()] + .filter((item) => typeof item.body !== "string") + .map(({ id, path, revision, digest }) => ({ + id, + path, + revision, + digest, + })); + } + async readAttachment(id: string) { + const body = this.items.get(id)?.body; + if (!(body instanceof Uint8Array)) throw new Error("Missing attachment"); + return body.slice(); + } + async saveNote(note: RemoteNoteView) { + if (!isNotePath(note.path)) throw new Error("Note path must end in .md"); + return this.write( + { id: note.id, path: note.path, body: note.source }, + note, + ); + } + async saveAttachment(attachment: { + id: string; + path: string; + bytes: Uint8Array; + revision?: string; + digest?: string; + }) { + if (isNotePath(attachment.path)) + throw new Error("This path is reserved for notes and preferences."); + return this.write( + { + id: attachment.id, + path: attachment.path, + body: attachment.bytes.slice(), + }, + attachment, + ); + } async rename(id: string, path: string) { - const current = this.notes.get(id); + const current = this.items.get(id); if (!current) throw new Error("Missing note"); if (this.collides(id, path)) throw new Error("Filesystem path collision"); - this.notes.set(id, { ...current, path, ...this.revision() }); + const saved = this.revision(); + this.items.set(id, { ...current, path, ...saved }); + return saved; } async remove(id: string) { - this.notes.delete(id); + this.items.delete(id); this.removed.push(id); } } diff --git a/tests/plan.test.ts b/tests/plan.test.ts index 5cc6fa4..21da3ec 100644 --- a/tests/plan.test.ts +++ b/tests/plan.test.ts @@ -1,9 +1,9 @@ import { describe, expect, test } from "bun:test"; import { type Entry, - type LocalNote, + type LocalItem, plan, - type RemoteNote, + type RemoteItem, type Step, } from "../src/plan"; @@ -22,16 +22,16 @@ const entry = ( size: 1, ...extra, }); -const local = (path: string, hash: string): LocalNote => ({ +const local = (path: string, hash: string): LocalItem => ({ path, hash, - source: `text ${hash}`, + body: `text ${hash}`, }); -const remote = (id: string, path: string, hash: string): RemoteNote => ({ +const remote = (id: string, path: string, hash: string): RemoteItem => ({ id, path, hash, - source: `text ${hash}`, + body: `text ${hash}`, revision: `rev-${hash}`, digest: `digest-${hash}`, }); diff --git a/tests/setup.ts b/tests/setup.ts new file mode 100644 index 0000000..c12bc3d --- /dev/null +++ b/tests/setup.ts @@ -0,0 +1,2 @@ +// The device client keeps its local database in IndexedDB, which Bun lacks; it must exist before Dexie loads. +import "fake-indexeddb/auto"; From 6b11fa46a3590a2ebafb2e6b5178a3d8cec22fa2 Mon Sep 17 00:00:00 2001 From: kualta Date: Wed, 4 Nov 2026 13:06:30 -0500 Subject: [PATCH 03/16] make every write compare-and-swap and test removal under Access --- src/controller.ts | 3 + src/device.ts | 9 ++- src/engine.ts | 85 +++++++++++++++-------- src/main.ts | 6 +- src/plan.ts | 4 +- tests/controller.test.ts | 12 ++-- tests/e2e.test.ts | 142 +++++++++++++++++++++++++++++++++++---- tests/engine.test.ts | 66 +++++++++++++++++- tests/fakes.ts | 85 ++++++++++++++++------- 9 files changed, 338 insertions(+), 74 deletions(-) diff --git a/src/controller.ts b/src/controller.ts index b037e67..b72300e 100644 --- a/src/controller.ts +++ b/src/controller.ts @@ -28,6 +28,8 @@ export interface DeviceClient { locked: string; /** Whether a status means the device's last sync read the vault, so its local copy is current. */ pulled(status: string): boolean; + /** Whether a write was refused because the item changed since it was read (`NoteChangedError`). */ + stale(error: unknown): boolean; } export type Phase = @@ -298,6 +300,7 @@ export class SyncController { index: this.options.indexFor(credentials.did, checkpoint.vault), configDir: this.options.configDir, confirmDeletions: this.options.confirmDeletions, + stale: device.stale, }); await engine.load(); if (!this.live(generation)) return vault.stop(); diff --git a/src/device.ts b/src/device.ts index d38a1b8..23663bd 100644 --- a/src/device.ts +++ b/src/device.ts @@ -1,4 +1,8 @@ -import { parseSyncBackoff, SYNCED } from "@flow-industries/seal"; +import { + NoteChangedError, + parseSyncBackoff, + SYNCED, +} from "@flow-industries/seal"; /** The one place the plugin imports the NOTE device client from. */ export { @@ -30,3 +34,6 @@ export { */ export const pulledStatus = (status: string) => status === SYNCED || parseSyncBackoff(status) !== undefined; +/** Whether a compare-and-swap write was refused because the item changed in NOTE since it was read. */ +export const isStaleWrite = (error: unknown) => + error instanceof NoteChangedError; diff --git a/src/engine.ts b/src/engine.ts index e27d704..6dbe724 100644 --- a/src/engine.ts +++ b/src/engine.ts @@ -52,22 +52,33 @@ export interface RemoteAttachmentView { revision: string; digest: string; } -/** The linked NOTE vault, as the device client's `DeviceVault` offers it. */ +/** `current`: the write is refused unless its base is the stored revision. */ +export interface WriteOptions { + current?: boolean; +} +/** + * The linked NOTE vault, as the device client's `DeviceVault` offers it. + * Every write the engine makes is compare-and-swap: a save with + * `{ current: true }`, a rename or remove with the base the plan read. + */ export interface RemoteVault { read(): Promise<{ notes: RemoteNoteView[] }>; listAttachments(): Promise; readAttachment(id: string): Promise; /** Each save resolves with the revision the content now has. */ - saveNote(note: RemoteNoteView): Promise; - saveAttachment(attachment: { - id: string; - path: string; - bytes: Uint8Array; - revision?: string; - digest?: string; - }): Promise; - rename(id: string, path: string): Promise; - remove(id: string): Promise; + saveNote(note: RemoteNoteView, options?: WriteOptions): Promise; + saveAttachment( + attachment: { + id: string; + path: string; + bytes: Uint8Array; + revision?: string; + digest?: string; + }, + options?: WriteOptions, + ): Promise; + rename(id: string, path: string, base?: RevisionBase): Promise; + remove(id: string, base?: RevisionBase): Promise; } /** Where the entries live between rounds: outside the vault folder, per linked device. */ export interface SyncIndex { @@ -102,6 +113,11 @@ export interface EngineOptions { * suddenly reads as empty looks exactly like everything deleted. */ confirmDeletions?(deletions: Deletions): Promise; + /** + * Whether a write was refused because the item changed in NOTE since the + * round read it; the round reads again and plans from there. + */ + stale?(error: unknown): boolean; newId?(): string; } @@ -115,6 +131,10 @@ const deletionsOf = (steps: readonly Step[]): Deletions => ({ local: steps.filter((step) => step.kind === "delete-local").length, remote: steps.filter((step) => step.kind === "delete-remote").length, }); +const baseOf = (item: RemoteItem): RevisionBase | undefined => + item.revision && item.digest + ? { revision: item.revision, digest: item.digest } + : undefined; const isDeletion = (step: Step) => step.kind === "delete-local" || step.kind === "delete-remote"; @@ -425,7 +445,7 @@ export class SyncEngine { try { if (step.kind === "forget") this.entries.delete(step.id); else if (step.kind === "delete-remote") { - await this.options.remote.remove(step.id); + await this.options.remote.remove(step.id, baseOf(step.remote)); this.remoteChanged(); this.entries.delete(step.id); } else if (step.kind === "delete-local") { @@ -436,6 +456,8 @@ export class SyncEngine { } else await this.update(step); result.applied++; } catch (error) { + this.remoteChanged(); + if (this.options.stale?.(error)) return; result.failed.push({ path: step.kind === "update" @@ -445,7 +467,6 @@ export class SyncEngine { : step.id, error: error instanceof Error ? error.message : String(error), }); - this.remoteChanged(); } } @@ -455,6 +476,10 @@ export class SyncEngine { return (await sha256(current)) === local.hash ? current : null; } + /** + * Compare-and-swap: an edit that reached NOTE after the round read `base` + * refuses the save instead of being replaced, and the round plans again. + */ private save( id: string, path: string, @@ -462,11 +487,16 @@ export class SyncEngine { base?: Partial, ) { const { remote } = this.options; - const revision = base?.revision; - const digest = base?.digest; + const { revision, digest } = base ?? {}; return typeof body === "string" - ? remote.saveNote({ id, path, source: body, revision, digest }) - : remote.saveAttachment({ id, path, bytes: body, revision, digest }); + ? remote.saveNote( + { id, path, source: body, revision, digest }, + { current: true }, + ) + : remote.saveAttachment( + { id, path, bytes: body, revision, digest }, + { current: true }, + ); } private async update(step: Extract) { @@ -477,6 +507,17 @@ export class SyncEngine { digest: remote?.digest ?? "", }; let hash = remote?.hash ?? local?.hash ?? ""; + // The item's own compare-and-swap write goes first, so a refused one leaves no conflict copy for the next plan to duplicate. + if (content === "local") { + const body = local?.body; + if (body === undefined) throw new Error("Push without local content"); + base = await this.save(id, path, body, remote); + this.remoteChanged(); + hash = local?.hash ?? ""; + } else if (remote && remote.path !== path) { + base = await vault.rename(id, path, baseOf(remote)); + this.remoteChanged(); + } if (copy) { const body = local?.body; if (body === undefined) throw new Error("Conflict without local content"); @@ -492,16 +533,6 @@ export class SyncEngine { ...saved, }); } - if (content === "local") { - const body = local?.body; - if (body === undefined) throw new Error("Push without local content"); - base = await this.save(id, path, body, remote); - this.remoteChanged(); - hash = local?.hash ?? ""; - } else if (remote && remote.path !== path) { - base = await vault.rename(id, path); - this.remoteChanged(); - } if (this.stopped) throw new Error("Sync stopped"); if (local && local.path !== path) { if (!(await files.move(local.path, path))) diff --git a/src/main.ts b/src/main.ts index f4e797a..b1d9a2b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,6 +4,7 @@ import { Custody } from "./custody"; import { createDeviceSeed, deleteDeviceStorage, + isStaleWrite, linkDevice, openDeviceVault, pulledStatus, @@ -43,6 +44,7 @@ export default class NoteSyncPlugin extends Plugin { openDeviceVault, locked: SYNC_LOCKED, pulled: pulledStatus, + stale: isStaleWrite, }, host: FLOW_ID, fetch: requestUrlFetch(requestUrl), @@ -68,7 +70,7 @@ export default class NoteSyncPlugin extends Plugin { if (this.settingTab.containerEl.isShown()) this.settingTab.display(); }, onTrustLoss: (loss) => trustLossNotice(loss), - notify: (message) => new Notice(`NOTE Sync: ${message}`, 0), + notify: (message) => new Notice(`FLOW NOTE Sync: ${message}`, 0), }); this.settingTab = new NoteSyncSettingTab(this.app, this); this.addSettingTab(this.settingTab); @@ -157,5 +159,5 @@ function trustLossNotice({ unsigned, stale }: TrustLoss) { ? `Links to moved code were left as they were: ${stale.join(", ")}.` : "", ].filter(Boolean); - if (lines.length) new Notice(`NOTE Sync: ${lines.join(" ")}`, 15_000); + if (lines.length) new Notice(`FLOW NOTE Sync: ${lines.join(" ")}`, 15_000); } diff --git a/src/plan.ts b/src/plan.ts index bbbd8c2..9e79b78 100644 --- a/src/plan.ts +++ b/src/plan.ts @@ -50,7 +50,7 @@ export type Step = copy?: string; } | { kind: "delete-local"; id: string; local: LocalItem } - | { kind: "delete-remote"; id: string } + | { kind: "delete-remote"; id: string; remote: RemoteItem } | { kind: "forget"; id: string }; export interface PlanInput { @@ -172,7 +172,7 @@ export function plan({ else if (!l && r) steps.push( r.hash === entry.hash - ? { kind: "delete-remote", id: entry.id } + ? { kind: "delete-remote", id: entry.id, remote: r } : { kind: "update", id: r.id, diff --git a/tests/controller.test.ts b/tests/controller.test.ts index 2c558b4..7376b7d 100644 --- a/tests/controller.test.ts +++ b/tests/controller.test.ts @@ -9,7 +9,7 @@ import { import { Custody, type SecretBackend } from "../src/custody"; import type { DeviceVault } from "../src/device"; import { sha256 } from "../src/hash"; -import { MemoryIndex, MemoryRemote, MemoryVault } from "./fakes"; +import { isStale, MemoryIndex, MemoryRemote, MemoryVault } from "./fakes"; class Secrets implements SecretBackend { values = new Map(); @@ -40,7 +40,7 @@ function deviceVault(remote: MemoryRemote, stranded = false) { const state = { stopped: false, pull: true }; const vault = { read: () => remote.read().then((view) => ({ ...view, folders: [] })), - saveNote: (note) => remote.saveNote(note), + saveNote: (note, options) => remote.saveNote(note, options), listAttachments: async () => (await remote.listAttachments()).map((item) => ({ ...item, @@ -48,9 +48,10 @@ function deviceVault(remote: MemoryRemote, stranded = false) { size: 0, })), readAttachment: (id) => remote.readAttachment(id), - saveAttachment: (attachment) => remote.saveAttachment(attachment), - rename: (id, path) => remote.rename(id, path), - remove: (id) => remote.remove(id), + saveAttachment: (attachment, options) => + remote.saveAttachment(attachment, options), + rename: (id, path, base) => remote.rename(id, path, base), + remove: (id, base) => remote.remove(id, base), compose: async () => ({ selectedId: "" }), sync: async () => { if (state.pull) @@ -103,6 +104,7 @@ async function harness( }, locked: "Locked", pulled: (status) => status === "Synced", + stale: isStale, }, host: "https://id.example", fetch: async () => new Response(null, { status: 404 }), diff --git a/tests/e2e.test.ts b/tests/e2e.test.ts index dd3616f..e3f6589 100644 --- a/tests/e2e.test.ts +++ b/tests/e2e.test.ts @@ -3,25 +3,30 @@ import { type AdminBrowser, adminBrowser, approveLink, + dropDevices, type FakeFlowId, fakeFlowId, + memoryStore, openAdminVault, TEST_DID, TEST_HOST, } from "@flow-industries/seal/testing"; -import { SyncController } from "../src/controller"; +import { REMOVED, SyncController } from "../src/controller"; import { Custody, type SecretBackend } from "../src/custody"; import { createDeviceSeed, + type DeviceCheckpoint, deleteDeviceStorage, + isStaleWrite, type LinkPrompt, linkDevice, + type NoteDeviceCredentials, openDeviceVault, pulledStatus, SYNC_LOCKED, type TrustLoss, } from "../src/device"; -import type { SyncIndex } from "../src/engine"; +import { SyncEngine, type SyncIndex } from "../src/engine"; import { MemoryIndex, MemoryVault } from "./fakes"; /** @@ -53,6 +58,7 @@ function obsidian(note: FakeFlowId, name: string) { openDeviceVault, locked: SYNC_LOCKED, pulled: pulledStatus, + stale: isStaleWrite, }, host: TEST_HOST, fetch: note.fetch, @@ -137,22 +143,11 @@ describe("two Obsidian vaults synced through NOTE", () => { await a.controller.confirm(); expect(a.custody.account()).toEqual({ did: TEST_DID }); await a.controller.syncNow(); - console.log( - "A", - JSON.stringify(a.controller.lastRound), - JSON.stringify(a.controller.phase), - ); a.controller.close(); await link(admin, b); await b.controller.confirm(); await b.controller.syncNow(); - console.log( - "B", - JSON.stringify(b.controller.lastRound), - JSON.stringify(b.controller.phase), - [...b.local.files.keys()], - ); b.controller.close(); expect(b.local.text("Inbox/First.md")).toBe("# Written in vault A"); expect(b.local.text("Code.mdx")).toBe( @@ -226,4 +221,125 @@ describe("two Obsidian vaults synced through NOTE", () => { false, ); }, 120_000); + + test("a vault removed under Access while syncing stops and wipes its keys, keeping its files", async () => { + const note = fakeFlowId(); + const admin = await adminBrowser(note); + const a = obsidian(note, "cccccc"); + opened.push(a); + a.local.put("Kept.md", "synced before removal"); + await link(admin, a); + await a.controller.confirm(); + await a.controller.syncNow(); + expect(a.controller.phase.kind).toBe("open"); + + await dropDevices(admin); + a.local.put("Late.md", "written after removal"); + await a.controller.syncNow(); + for ( + let wait = 0; + a.controller.phase.kind !== "removed" && wait < 100; + wait++ + ) + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(a.controller.phase).toEqual({ + kind: "removed", + message: REMOVED.removed, + }); + expect(a.custody.seed()).toBeNull(); + expect(await a.custody.credentials.read()).toBeNull(); + expect(await a.custody.checkpoints.read()).not.toBeNull(); + expect(a.local.text("Kept.md")).toBe("synced before removal"); + expect(a.local.text("Late.md")).toBe("written after removal"); + const web = await openAdminVault(admin); + await web.sync(); + expect((await web.read()).notes.map((item) => item.path)).toEqual([ + "Kept.md", + ]); + web.lock(); + expect(note.violations).toEqual([]); + }, 60_000); + + test("an edit that reaches the device mid-round becomes a conflict copy, never overwritten", async () => { + const note = fakeFlowId(); + const admin = await adminBrowser(note); + const seed = createDeviceSeed(); + const options = { + host: TEST_HOST, + fetch: note.fetch, + credentials: memoryStore(), + checkpoints: memoryStore(), + }; + const prompt = Promise.withResolvers(); + const linking = linkDevice(seed, { + ...options, + label: "Obsidian on test", + onPrompt: prompt.resolve, + }); + await approveLink(admin, await prompt.promise); + await linking; + const device = await openDeviceVault(seed, options); + const web = await openAdminVault(admin); + try { + const local = new MemoryVault(); + const index = new MemoryIndex(); + local.put("Plan.md", "first"); + const engine = new SyncEngine({ + local, + remote: device, + index, + configDir: ".obsidian", + stale: isStaleWrite, + }); + await engine.load(); + await engine.run(); + await device.sync(); + + // NOTE's edit lands in the device's copy after the round has read it, but before it pushes. + local.put("Plan.md", "edited here"); + let interleave = true; + const remote: typeof device = { + ...device, + read: async () => { + const view = await device.read(); + if (interleave) { + interleave = false; + await web.sync(); + const plan = (await web.read()).notes.find( + (item) => item.path === "Plan.md", + ); + if (!plan) throw new Error("Missing Plan.md"); + await web.save({ ...plan, source: "edited in NOTE" }); + await web.sync(); + await device.sync(); + } + return view; + }, + }; + const racing = new SyncEngine({ + local, + remote, + index, + configDir: ".obsidian", + stale: isStaleWrite, + }); + await racing.load(); + await racing.run(); + const copy = [...local.files.keys()].find((path) => + path.startsWith("Plan conflict "), + ); + expect(local.text("Plan.md")).toBe("edited in NOTE"); + expect(local.text(copy ?? "")).toBe("edited here"); + await device.sync(); + await web.sync(); + const sources = new Map( + (await web.read()).notes.map((item) => [item.path, item.source]), + ); + expect(sources.get("Plan.md")).toBe("edited in NOTE"); + expect(sources.get(copy ?? "")).toBe("edited here"); + } finally { + web.lock(); + device.stop(); + } + }, 60_000); }); diff --git a/tests/engine.test.ts b/tests/engine.test.ts index 52219e9..111f025 100644 --- a/tests/engine.test.ts +++ b/tests/engine.test.ts @@ -4,7 +4,7 @@ import { MAX_ATTACHMENT_BYTES, SyncEngine, } from "../src/engine"; -import { MemoryIndex, MemoryRemote, MemoryVault } from "./fakes"; +import { isStale, MemoryIndex, MemoryRemote, MemoryVault } from "./fakes"; async function setup( options: { confirm?: (deletions: Deletions) => Promise } = {}, @@ -18,6 +18,7 @@ async function setup( remote, index, configDir: ".obsidian", + stale: isStale, confirmDeletions: async (deletions) => { asked.push(deletions); return (await options.confirm?.(deletions)) ?? true; @@ -228,6 +229,69 @@ describe("engine: after the first sync", () => { expect(w.local.text(copy ?? "")).toBe("typed meanwhile"); }); + test("a NOTE edit that lands between the read and the push becomes a conflict, never overwritten", async () => { + const w = await synced(); + const a = w.remote.byPath("A.md")?.id ?? ""; + w.local.put("A.md", "local edit"); + w.remote.beforeWrite = (id) => { + if (id !== a) return; + w.remote.beforeWrite = undefined; + w.remote.put(a, "A.md", "remote edit"); + }; + const result = await settled(w); + expect(result.failed).toEqual([]); + const copy = [...w.local.files.keys()].find((path) => + path.startsWith("A conflict "), + ); + expect(w.remote.text("A.md")).toBe("remote edit"); + expect(w.local.text("A.md")).toBe("remote edit"); + expect(w.local.text(copy ?? "")).toBe("local edit"); + expect(w.remote.text(copy ?? "")).toBe("local edit"); + }); + + test("a NOTE edit that lands before a deletion reaches it comes back instead", async () => { + const w = await synced(); + const a = w.remote.byPath("A.md")?.id ?? ""; + await w.local.trash("A.md"); + w.remote.beforeWrite = (id) => { + if (id !== a) return; + w.remote.beforeWrite = undefined; + w.remote.put(a, "A.md", "edited there"); + }; + const result = await settled(w); + expect(result.failed).toEqual([]); + expect(w.remote.removed).toEqual([]); + expect(w.remote.text("A.md")).toBe("edited there"); + expect(w.local.text("A.md")).toBe("edited there"); + }); + + test("a NOTE edit that lands while a conflict is resolved leaves one copy", async () => { + const w = await synced(); + const a = w.remote.byPath("A.md")?.id ?? ""; + await w.local.move("A.md", "Moved.md"); + w.engine.renamed("A.md", "Moved.md"); + w.local.put("Moved.md", "local edit"); + w.remote.put(a, "A.md", "remote edit"); + w.engine.remoteChanged(); + w.remote.beforeWrite = (id) => { + if (id !== a) return; + w.remote.beforeWrite = undefined; + w.remote.put(a, "A.md", "remote edit, again"); + }; + await settled(w); + const copies = [...w.local.files.keys()].filter((path) => + path.startsWith("Moved conflict "), + ); + expect(copies.length).toBe(1); + expect(w.local.text(copies[0] ?? "")).toBe("local edit"); + expect(w.local.text("Moved.md")).toBe("remote edit, again"); + expect(remotePaths(w.remote)).toEqual([ + "B.md: two", + `${copies[0]}: local edit`, + "Moved.md: remote edit, again", + ]); + }); + test("resumes from the saved index without redoing anything", async () => { const w = await synced(); const engine = new SyncEngine({ diff --git a/tests/fakes.ts b/tests/fakes.ts index e88ec84..2774926 100644 --- a/tests/fakes.ts +++ b/tests/fakes.ts @@ -5,6 +5,7 @@ import type { RemoteVault, RevisionBase, SyncIndex, + WriteOptions, } from "../src/engine"; import { isNotePath, pathKey } from "../src/paths"; import type { Body, Entry } from "../src/plan"; @@ -84,20 +85,35 @@ export class MemoryVault implements LocalVault { } } +/** What the device client throws for a compare-and-swap write that lost: `NoteChangedError`. */ +export class StaleError extends Error { + constructor() { + super("This note changed. Read it again."); + } +} +export const isStale = (error: unknown) => error instanceof StaleError; + interface RemoteRow extends RevisionBase { id: string; path: string; body: Body; } -/** A NOTE vault in memory that refuses saves on a revision it can't place, as the device client does. */ +/** + * A NOTE vault in memory that places bases as the device client does: a save + * names any revision the item has had, or with `{ current: true }` the stored + * one; a rename or remove with a base, the stored one. `beforeWrite` lets a + * test land a NOTE edit between a round's read and its write. + */ export class MemoryRemote implements RemoteVault { items = new Map(); removed: string[] = []; + beforeWrite?: (id: string) => void; private revisions = 0; + private history = new Map>(); put(id: string, path: string, body: Body) { - this.items.set(id, { id, path, body, ...this.revision() }); + this.commit({ id, path, body }); } byPath(path: string) { return [...this.items.values()].find((item) => item.path === path); @@ -108,9 +124,15 @@ export class MemoryRemote implements RemoteVault { ? body : decoder.decode(body); } - private revision(): RevisionBase { + private commit(row: Omit): RevisionBase { const revision = `r${++this.revisions}`; - return { revision, digest: `d-${revision}` }; + const saved = { revision, digest: `d-${revision}` }; + this.items.set(row.id, { ...row, ...saved }); + this.history.set( + row.id, + (this.history.get(row.id) ?? new Set()).add(revision), + ); + return saved; } private collides(id: string, path: string) { return [...this.items.values()].some( @@ -120,15 +142,25 @@ export class MemoryRemote implements RemoteVault { private write( row: Omit, base: Partial, + options: WriteOptions = {}, ) { - const current = this.items.get(row.id); - if (current && current.revision !== base.revision) - throw new Error("This note changed. Read it again."); + this.beforeWrite?.(row.id); + this.check(row.id, base, options.current); if (this.collides(row.id, row.path)) throw new Error("Filesystem path collision"); - const saved = this.revision(); - this.items.set(row.id, { ...row, ...saved }); - return saved; + return this.commit(row); + } + private check( + id: string, + base: Partial | undefined, + current = false, + ) { + const stored = this.items.get(id); + if (!stored) return; + const placed = current + ? base?.revision === stored.revision + : !!base?.revision && !!this.history.get(id)?.has(base.revision); + if (!placed) throw new StaleError(); } async read() { const notes: RemoteNoteView[] = []; @@ -152,20 +184,24 @@ export class MemoryRemote implements RemoteVault { if (!(body instanceof Uint8Array)) throw new Error("Missing attachment"); return body.slice(); } - async saveNote(note: RemoteNoteView) { + async saveNote(note: RemoteNoteView, options?: WriteOptions) { if (!isNotePath(note.path)) throw new Error("Note path must end in .md"); return this.write( { id: note.id, path: note.path, body: note.source }, note, + options, ); } - async saveAttachment(attachment: { - id: string; - path: string; - bytes: Uint8Array; - revision?: string; - digest?: string; - }) { + async saveAttachment( + attachment: { + id: string; + path: string; + bytes: Uint8Array; + revision?: string; + digest?: string; + }, + options?: WriteOptions, + ) { if (isNotePath(attachment.path)) throw new Error("This path is reserved for notes and preferences."); return this.write( @@ -175,17 +211,20 @@ export class MemoryRemote implements RemoteVault { body: attachment.bytes.slice(), }, attachment, + options, ); } - async rename(id: string, path: string) { + async rename(id: string, path: string, base?: RevisionBase) { + this.beforeWrite?.(id); const current = this.items.get(id); if (!current) throw new Error("Missing note"); + if (base) this.check(id, base, true); if (this.collides(id, path)) throw new Error("Filesystem path collision"); - const saved = this.revision(); - this.items.set(id, { ...current, path, ...saved }); - return saved; + return this.commit({ ...current, path }); } - async remove(id: string) { + async remove(id: string, base?: RevisionBase) { + this.beforeWrite?.(id); + if (base) this.check(id, base, true); this.items.delete(id); this.removed.push(id); } From f8878956eb2c8a3e4c3d9a61fbf9e754cd929d41 Mon Sep 17 00:00:00 2001 From: kualta Date: Wed, 4 Nov 2026 13:06:30 -0500 Subject: [PATCH 04/16] rename the plugin to FLOW NOTE Sync --- AGENTS.md | 3 ++- README.md | 10 +++++----- manifest.json | 2 +- package.json | 2 +- src/obsidian/settings.ts | 14 +++++++------- tests/manifest.test.ts | 1 + 6 files changed, 17 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c5b03ac..90ce5dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md -NOTE Sync is an Obsidian community plugin (id `flow-note`). This repository is public: keep in-house tooling, internal hosts and private links out of code, docs and commit messages. +FLOW NOTE Sync is an Obsidian community plugin (id `flow-note`). This repository is public: keep in-house tooling, internal hosts and private links out of code, docs and commit messages. - Use Bun 1.4.2. Before a PR, run `bun run lint`, `bun run typecheck`, `bun test`, `bun run build` and `bun run smoke`. - `manifest.json` stays at the root. Never change the plugin `id`. A release tag equals the manifest `version`, with no `v`. @@ -9,6 +9,7 @@ NOTE Sync is an Obsidian community plugin (id `flow-note`). This repository is p - Secrets (the device seed, Flow ID device tokens) live only in Obsidian's secret storage, never in `data.json` or anywhere inside the vault folder. The plugin keeps no `data.json`. - One device transport per credential store: `SyncController` owns the only open device vault, and a Web Lock on the vault's credential namespace keeps a second window from opening another. The device client names its local database per device; unlink and removal delete it with `deleteDeviceStorage`. - Nothing syncs before the person confirms the linked account (`Custody.account()`). +- Every write to NOTE is compare-and-swap: saves pass `{ current: true }`, `rename` and `remove` pass the base the round read. A `NoteChangedError` means NOTE moved on, so the round reads again and plans from there; never retry the same write. - Never execute note content. Notes, MDX and code blocks are text to this plugin, and nothing is ever written into Obsidian's config folder. - `main.js` is loaded as CommonJS: `scripts/build.ts` replaces `import.meta.url`, and `bun run smoke` fails if the bundle needs anything at load beyond what Obsidian provides. - No WHAT comments; doc comments for exported APIs and short WHY comments only. diff --git a/README.md b/README.md index 2821ff4..bf74acc 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ -# NOTE Sync +# FLOW NOTE Sync An Obsidian plugin that keeps a vault in sync, both ways, with your end-to-end encrypted [NOTE](https://note.flow.talk) notepad. You approve it once in your browser; after that it syncs without asking for your passkey. Notes are encrypted on this device before they leave it. -NOTE Sync needs a Flow ID account with a NOTE notepad, and Obsidian 1.11.5 or later. +FLOW NOTE Sync needs a Flow ID account with a NOTE notepad, and Obsidian 1.11.5 or later. ## Linking -1. Open **Settings → NOTE Sync** and select **Link**, or run **NOTE Sync: Link this vault** from the command palette. +1. Open **Settings → FLOW NOTE Sync** and select **Link**, or run **FLOW NOTE Sync: Link this vault** from the command palette. 2. The plugin shows a code and a 12-digit device code, and opens `note.flow.talk/link` in your browser. 3. On that page, sign in if asked, check the code, type the device code and approve with your passkey. The device code never leaves this device any other way: Flow ID only ever sees a slow hash of it, so it can't swap in keys or a notepad of its own. 4. Back in Obsidian, the plugin shows the account it was linked to (its handle, when the handle checks out both ways, and its DID). **Nothing syncs until you confirm it is yours.** A code someone else guessed and approved would otherwise bind your vault to their notepad. @@ -18,7 +18,7 @@ A link has to be approved within ten minutes. - **Notes and attachments:** every Markdown (`.md`) and MDX (`.mdx`) note, and every other file (images, PDFs, audio and the rest) up to 32 MB, both ways. - **Renames** carry across, including folder renames. A rename the plugin didn't see (Obsidian was closed) is recognised by the file's unchanged content. When you rename an attachment here, Obsidian updates the links to it, and those edits sync like any other. - **Deletions** move the file to the trash on the other side: Obsidian's trash here, NOTE's trash there. An edit beats a deletion: if one side edited a file the other deleted, it comes back. Before a sync would trash more than ten files and more than a tenth of the vault at once, the plugin asks. -- **Conflicts:** when both sides changed the same file, NOTE's version keeps the name and this vault's is saved beside it. A note's copy is named ` conflict <8 hex>.md`, the way NOTE names its own conflict copies; an attachment's keeps its extension last, ` conflict <8 hex>.png`, so Obsidian still opens it. Nothing is overwritten while you type: a file that changes during a sync, or an open note with unsaved typing, is left alone until the next sync. +- **Conflicts:** when both sides changed the same file, NOTE's version keeps the name and this vault's is saved beside it. A note's copy is named ` conflict <8 hex>.md`, the way NOTE names its own conflict copies; an attachment's keeps its extension last, ` conflict <8 hex>.png`, so Obsidian still opens it. Nothing is overwritten while you type: a file that changes during a sync, or an open note with unsaved typing, is left alone until the next sync. The same holds in NOTE: every write names the version it was planned from, so an edit that reaches NOTE during a sync is never replaced or trashed; the sync reads again and plans from there. **Not synced:** @@ -76,7 +76,7 @@ bun run build # main.js at the repository root bun run smoke # loads main.js as Obsidian does, with no Node modules ``` -Obsidian's API is used only under `src/obsidian/` and `src/main.ts`; everything else runs under `bun test`. To try a build, copy `main.js`, `manifest.json` and `styles.css` into `/.obsidian/plugins/flow-note/` and enable **NOTE Sync** under **Settings → Community plugins**. +Obsidian's API is used only under `src/obsidian/` and `src/main.ts`; everything else runs under `bun test`. To try a build, copy `main.js`, `manifest.json` and `styles.css` into `/.obsidian/plugins/flow-note/` and enable **FLOW NOTE Sync** under **Settings → Community plugins**. ## Releasing diff --git a/manifest.json b/manifest.json index 0f480f6..b9be327 100644 --- a/manifest.json +++ b/manifest.json @@ -1,6 +1,6 @@ { "id": "flow-note", - "name": "NOTE Sync", + "name": "FLOW NOTE Sync", "version": "0.1.0", "minAppVersion": "1.11.5", "description": "Sync your vault both ways with your end-to-end encrypted NOTE notepad, linked once through your browser.", diff --git a/package.json b/package.json index a37c947..141fb99 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "flow-note-sync", "private": true, "version": "0.1.0", - "description": "NOTE Sync for Obsidian", + "description": "FLOW NOTE Sync for Obsidian", "license": "MIT", "type": "module", "scripts": { diff --git a/src/obsidian/settings.ts b/src/obsidian/settings.ts index e5040fd..5ce9c03 100644 --- a/src/obsidian/settings.ts +++ b/src/obsidian/settings.ts @@ -8,22 +8,22 @@ import { custodyNote } from "./vault"; export function statusText(phase: Phase, round: RoundResult | null): string { switch (phase.kind) { case "unlinked": - return "NOTE: not linked"; + return "FLOW NOTE: not linked"; case "linking": - return "NOTE: linking"; + return "FLOW NOTE: linking"; case "confirm": - return "NOTE: confirm account"; + return "FLOW NOTE: confirm account"; case "opening": - return "NOTE: connecting"; + return "FLOW NOTE: connecting"; case "removed": - return "NOTE: device removed"; + return "FLOW NOTE: device removed"; case "stopped": - return "NOTE: stopped"; + return "FLOW NOTE: stopped"; case "open": { const failed = round?.failed.length ?? 0; const held = (round?.held.local ?? 0) + (round?.held.remote ?? 0); return [ - `NOTE: ${phase.status}`, + `FLOW NOTE: ${phase.status}`, failed ? `${failed} not synced` : "", held ? `${held} deletions held` : "", ] diff --git a/tests/manifest.test.ts b/tests/manifest.test.ts index 353b35c..b75316b 100644 --- a/tests/manifest.test.ts +++ b/tests/manifest.test.ts @@ -6,6 +6,7 @@ import versions from "../versions.json"; test("the manifest follows Obsidian's directory rules", () => { expect(manifest.id).toBe("flow-note"); expect(manifest.id).not.toMatch(/obsidian|plugin$/i); + expect(manifest.name).toBe("FLOW NOTE Sync"); expect(manifest.version).toMatch(/^\d+\.\d+\.\d+$/); expect(manifest.version).toBe(pkg.version); expect(manifest.description.length).toBeLessThanOrEqual(250); From e595002d417e273a48476983cae0de84ac4bc1e4 Mon Sep 17 00:00:00 2001 From: kualta Date: Wed, 4 Nov 2026 14:09:30 -0500 Subject: [PATCH 05/16] key the sync index per device and say every stop out loud --- src/account.ts | 62 ++++++++-- src/controller.ts | 130 +++++++++++++------- src/custody.ts | 11 +- src/device.ts | 20 ++- src/index-store.ts | 43 +++++-- src/lock.ts | 20 +-- src/main.ts | 12 +- src/obsidian/modals.ts | 23 ++-- src/obsidian/settings.ts | 15 ++- src/obsidian/vault.ts | 14 +++ src/traffic.ts | 36 ++++++ tests/controller.test.ts | 259 +++++++++++++++++++++++++++++++++++++-- tests/device.test.ts | 19 +++ tests/e2e.test.ts | 9 +- tests/fetch.test.ts | 52 +++++++- 15 files changed, 625 insertions(+), 100 deletions(-) create mode 100644 src/traffic.ts create mode 100644 tests/device.test.ts diff --git a/src/account.ts b/src/account.ts index aa80b56..80fbd0b 100644 --- a/src/account.ts +++ b/src/account.ts @@ -45,29 +45,75 @@ function claimedHandle(document: unknown, did: string): string | null { return handle && HANDLE.test(handle) ? handle : null; } +/** A DNS TXT lookup, where the platform offers one (desktop): each record as its chunks. */ +export type ResolveTxt = (name: string) => Promise; + +async function answersOverHttps( + handle: string, + did: string, + fetch: NoteDeviceFetch, +): Promise { + try { + const response = await fetch(`https://${handle}/.well-known/atproto-did`, { + method: "GET", + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + return response.ok && (await response.text()).trim() === did; + } catch { + return false; + } +} + +/** The DNS method: exactly one `did=` record at `_atproto.`, naming `did`. */ +async function answersOverDns( + handle: string, + did: string, + resolveTxt: ResolveTxt, +): Promise { + try { + const claims = (await resolveTxt(`_atproto.${handle}`)) + .map((chunks) => chunks.join("")) + .filter((record) => record.startsWith("did=")); + return claims.length === 1 && claims[0] === `did=${did}`; + } catch { + return false; + } +} + /** * Names the account behind `did` by its handle, checked both ways: the DID - * document claims the handle, and the handle's domain answers with the DID. - * A DID document alone could claim anyone's handle. Anything unverifiable - * leaves just the DID, which is what the link actually bound. + * document claims the handle, and the handle's domain answers with the DID, + * over HTTPS or, where the platform can look it up, DNS. A DID document + * alone could claim anyone's handle. Anything unverifiable leaves just the + * DID, which is what the link actually bound. */ export async function linkedAccount( did: string, fetch: NoteDeviceFetch, + resolveTxt?: ResolveTxt, ): Promise { try { const url = documentUrl(did); if (!url) return { did }; const handle = claimedHandle(await getJson(fetch, url), did); if (!handle) return { did }; - const response = await fetch(`https://${handle}/.well-known/atproto-did`, { - method: "GET", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - if (response.ok && (await response.text()).trim() === did) + if ( + (await answersOverHttps(handle, did, fetch)) || + (resolveTxt && (await answersOverDns(handle, did, resolveTxt))) + ) return { did, handle }; } catch { // An account that can't be named still shows its DID. } return { did }; } + +/** + * The domain that vouched for a handle: everything after its first label, + * or the whole handle when that leaves a bare top-level domain. A lookalike + * such as `alice-flow.talk.example` reads as `talk.example` here. + */ +export function handleDomain(handle: string): string { + const rest = handle.slice(handle.indexOf(".") + 1); + return rest.includes(".") ? rest : handle; +} diff --git a/src/controller.ts b/src/controller.ts index b72300e..2f6b648 100644 --- a/src/controller.ts +++ b/src/controller.ts @@ -1,4 +1,4 @@ -import { type LinkedAccount, linkedAccount } from "./account"; +import { type LinkedAccount, linkedAccount, type ResolveTxt } from "./account"; import type { Custody } from "./custody"; import type { DeviceOptions, @@ -15,21 +15,23 @@ import { SyncEngine, type SyncIndex, } from "./engine"; +import type { IndexKey } from "./index-store"; +import { Traffic } from "./traffic"; /** The device client calls the controller makes. */ export interface DeviceClient { - createDeviceSeed(): Uint8Array; - linkDevice(seed: Uint8Array, options: LinkOptions): Promise; - openDeviceVault( + createDeviceSeed: () => Uint8Array; + linkDevice: (seed: Uint8Array, options: LinkOptions) => Promise; + openDeviceVault: ( seed: Uint8Array, options: DeviceOptions, - ): Promise; + ) => Promise; /** The status the device's sync reports once it lost access and wiped its keys. */ locked: string; /** Whether a status means the device's last sync read the vault, so its local copy is current. */ - pulled(status: string): boolean; + pulled: (status: string) => boolean; /** Whether a write was refused because the item changed since it was read (`NoteChangedError`). */ - stale(error: unknown): boolean; + stale: (error: unknown) => boolean; } export type Phase = @@ -53,6 +55,8 @@ export const STRANDED = "NOTE's key changed while edits from this vault were still waiting to sync. Nothing is overwritten this time: where NOTE has different text, this vault's is kept as a conflict copy beside it."; export const LOCKED_ELSEWHERE = "This vault is already syncing in another Obsidian window."; +export const ALREADY_LINKED = + "This vault is still linked. Unlink it before linking it again."; export interface ControllerOptions { custody: Custody; @@ -60,28 +64,34 @@ export interface ControllerOptions { /** Flow ID's origin. */ host: string; fetch: NoteDeviceFetch; + /** DNS TXT lookups, for handles verified that way; absent where the platform has none. */ + resolveTxt?: ResolveTxt; local: LocalVault; configDir: string; - /** The index for one NOTE vault, so relinking to another vault never reuses it. */ - indexFor(did: string, vault: string): SyncIndex; + /** The index of one linked device: a new link never plans against another device's base. */ + indexFor: (key: IndexKey) => SyncIndex; + /** Deletes every index this Obsidian vault holds, for every device it was linked as. */ + forgetIndexes: () => Promise; /** * Holds this vault's credential store for as long as the vault is open, - * across every window of this app, or answers null when another holder has - * it, so only one device transport ever refreshes its tokens. + * across every window of this app, or answers null when another holder + * keeps it, so only one device transport ever refreshes its tokens. */ - hold(): Promise<(() => void) | null>; + hold: () => Promise<(() => void) | null>; /** Deletes the device client's local databases for this seed, unsynced edits included. */ - forgetDevice(seed: Uint8Array): Promise; - confirmDeletions(deletions: Deletions): Promise; - onChange(): void; - onTrustLoss(loss: TrustLoss): void; + forgetDevice: (seed: Uint8Array) => Promise; + confirmDeletions: (deletions: Deletions) => Promise; + onChange: () => void; + onTrustLoss: (loss: TrustLoss) => void; /** Tells the person something sync did that they didn't ask for. */ - notify(message: string): void; + notify: (message: string) => void; } const LOCAL_DEBOUNCE_MS = 1_500; const REMOTE_DEBOUNCE_MS = 500; const RETRY_MS = 30_000; +/** How long a closed device's lock waits for a token refresh it already sent. */ +const DRAIN_MS = 15_000; /** * Links, opens and syncs one Obsidian vault with its NOTE vault, and owns the @@ -103,9 +113,18 @@ export class SyncController { private generation = 0; private ready = false; private linking = false; + private traffic = new Traffic(); + /** Settles once the last closed device's lock is released. */ + private released: Promise = Promise.resolve(); + /** The last stop or removal told to the person, so a retry that fails the same way stays quiet. */ + private told: string | null = null; constructor(private readonly options: ControllerOptions) {} + private nameAccount(did: string) { + return linkedAccount(did, this.options.fetch, this.options.resolveTxt); + } + /** The account the person confirmed, while linked. */ account(): LinkedAccount | null { return this.options.custody.account(); @@ -113,6 +132,17 @@ export class SyncController { private set(phase: Phase) { this.phase = phase; + // Mobile has no status bar: a stop is only seen if it's said. + const notice = + phase.kind === "removed" + ? phase.message + : phase.kind === "stopped" + ? `Syncing stopped. ${phase.message}` + : null; + if (notice && notice !== this.told) this.options.notify(notice); + if (notice) this.told = notice; + else if (phase.kind === "open" || phase.kind === "unlinked") + this.told = null; this.options.onChange(); } @@ -131,10 +161,7 @@ export class SyncController { if (!custody.seed() || !credentials) return this.set({ kind: "unlinked" }); if (custody.account()?.did !== credentials.did) { - const account = await linkedAccount( - credentials.did, - this.options.fetch, - ); + const account = await this.nameAccount(credentials.did); if (this.live(generation)) this.set({ kind: "confirm", account }); return; } @@ -152,16 +179,17 @@ export class SyncController { * to. Nothing syncs until `confirm`. */ async link(label: string, signal: AbortSignal): Promise { - if (this.linking || this.vault) - throw new Error("This vault is already linked."); const { custody, device } = this.options; - this.close(); + if (this.linking || this.vault || custody.linked()) + throw new Error(ALREADY_LINKED); this.linking = true; - custody.wipe(); - const seed = device.createDeviceSeed(); - custody.saveSeed(seed); + let seed: Uint8Array | undefined; this.set({ kind: "linking" }); try { + // Whatever an earlier link left (an interrupted link, or tokens the secret store lost) goes before a new one starts. + await this.forget(); + seed = device.createDeviceSeed(); + custody.saveSeed(seed); await device.linkDevice(seed, { ...this.deviceOptions(), label, @@ -170,7 +198,7 @@ export class SyncController { }); const credentials = await custody.credentials.read(); if (!credentials) throw new Error("Linking stored no credentials."); - const account = await linkedAccount(credentials.did, this.options.fetch); + const account = await this.nameAccount(credentials.did); this.set({ kind: "confirm", account }); return account; } catch (error) { @@ -179,7 +207,7 @@ export class SyncController { throw error; } finally { this.linking = false; - seed.fill(0); + seed?.fill(0); } } @@ -217,7 +245,11 @@ export class SyncController { this.schedule(LOCAL_DEBOUNCE_MS); } - /** Closes the vault and stops any round or open in flight; unsynced writes wait in the local database. */ + /** + * Closes the vault and stops any round or open in flight; unsynced writes + * wait in the local database. The lock is released once the device's + * requests settle, so a token refresh it already sent lands first. + */ close() { this.generation++; this.ready = false; @@ -227,8 +259,15 @@ export class SyncController { this.vault?.stop(); this.vault = null; this.engine = null; - this.release?.(); + const release = this.release; this.release = null; + if (release) { + const earlier = this.released; + this.released = this.traffic + .idle(DRAIN_MS) + .then(() => earlier) + .then(release); + } } /** @@ -237,29 +276,31 @@ export class SyncController { * the files here still hold them. */ private async forget() { - const { custody, indexFor, forgetDevice } = this.options; - const credentials = await custody.credentials.read(); - const checkpoint = await custody.checkpoints.read(); + const { custody, forgetIndexes, forgetDevice } = this.options; const seed = custody.seed(); this.close(); custody.wipe(); try { - if (credentials && checkpoint) - await indexFor(credentials.did, checkpoint.vault) - .clear() - .catch(() => {}); + await forgetIndexes().catch(() => {}); if (seed) await forgetDevice(seed).catch(() => {}); } finally { seed?.fill(0); } } + /** Options for one device transport, whose requests and token writes count toward its traffic. */ private deviceOptions(): DeviceOptions { const { custody, host, fetch } = this.options; + const traffic = this.traffic; + const { credentials, checkpoints } = custody.scope(); return { host, - fetch, - ...custody.scope(), + fetch: (url, init) => traffic.track(() => fetch(url, init)), + credentials: { + read: credentials.read, + write: (value) => traffic.track(() => credentials.write(value)), + }, + checkpoints, onRemoved: async (reason) => { await this.forget(); this.set({ kind: "removed", message: REMOVED[reason] }); @@ -286,18 +327,25 @@ export class SyncController { if (!seed || !credentials) return this.set({ kind: "unlinked" }); if (custody.account()?.did !== credentials.did) return void this.start(); this.set({ kind: "opening" }); + await this.released; + if (!this.live(generation)) return; const release = await this.options.hold(); if (!this.live(generation)) return release?.(); if (!release) return this.set({ kind: "stopped", message: LOCKED_ELSEWHERE }); this.release = release; + this.traffic = new Traffic(); vault = await device.openDeviceVault(seed, this.deviceOptions()); const checkpoint = await custody.checkpoints.read(); if (!checkpoint) throw new Error("This vault's pin is missing."); const engine = new SyncEngine({ local: this.options.local, remote: vault, - index: this.options.indexFor(credentials.did, checkpoint.vault), + index: this.options.indexFor({ + did: credentials.did, + vault: checkpoint.vault, + deviceId: credentials.deviceId, + }), configDir: this.options.configDir, confirmDeletions: this.options.confirmDeletions, stale: device.stale, diff --git a/src/custody.ts b/src/custody.ts index 523a6a7..5c0490c 100644 --- a/src/custody.ts +++ b/src/custody.ts @@ -119,13 +119,13 @@ export class Custody { const current = () => generation === this.generation; return { credentials: { - read: this.credentials.read, + read: () => this.credentials.read(), write: async (value) => { if (current()) await this.credentials.write(value); }, }, checkpoints: { - read: this.checkpoints.read, + read: () => this.checkpoints.read(), write: async (value) => { if (current()) await this.checkpoints.write(value); }, @@ -149,6 +149,13 @@ export class Custody { this.backend.set(this.ids.seed, toBase64Url(seed)); } + /** Whether a link's tokens are stored, whether or not its account was confirmed. */ + linked(): boolean { + return ( + asCredentials(parsed(this.backend.get(this.ids.credentials))) !== null + ); + } + /** The account the person confirmed this vault syncs with; nothing uploads before it is set. */ account(): LinkedAccount | null { const value = parsed(this.backend.get(this.ids.account)); diff --git a/src/device.ts b/src/device.ts index 23663bd..dbacf68 100644 --- a/src/device.ts +++ b/src/device.ts @@ -1,6 +1,8 @@ import { NoteChangedError, parseSyncBackoff, + SYNC_QUOTA_REACHED, + SYNC_TOO_LARGE, SYNCED, } from "@flow-industries/seal"; @@ -28,12 +30,20 @@ export { } from "@flow-industries/seal"; /** - * Whether the device's last sync read the vault: it synced, or only its - * uploads were refused for a while. Pending, blocked or unauthorized syncs - * may not have, so the local copy could still be the one from before. + * Whether the device's last sync read the whole vault: it synced, or only + * its upload was refused, which a full quota or an oversized notepad can do + * only after the read. A rate limit can refuse the read itself, and pending, + * blocked or unauthorized syncs may not have read anything, so the local + * copy could still be the one from before, or empty on a new link. */ -export const pulledStatus = (status: string) => - status === SYNCED || parseSyncBackoff(status) !== undefined; +export function pulledStatus(status: string): boolean { + const refusal = parseSyncBackoff(status)?.refusal; + return ( + status === SYNCED || + refusal === SYNC_QUOTA_REACHED || + refusal === SYNC_TOO_LARGE + ); +} /** Whether a compare-and-swap write was refused because the item changed in NOTE since it was read. */ export const isStaleWrite = (error: unknown) => error instanceof NoteChangedError; diff --git a/src/index-store.ts b/src/index-store.ts index 5eb0237..24535ff 100644 --- a/src/index-store.ts +++ b/src/index-store.ts @@ -4,13 +4,44 @@ import type { Entry } from "./plan"; const STORE = "index"; const KEY = "entries"; +const failure = (error: DOMException | null) => + error ?? new Error("IndexedDB request failed"); + function request(req: IDBRequest): Promise { return new Promise((resolve, reject) => { req.onsuccess = () => resolve(req.result); - req.onerror = () => reject(req.error); + req.onerror = () => reject(failure(req.error)); }); } +const PREFIX = "flow-note-sync"; + +/** Which link an index belongs to: a new link is a new device, with a base of its own. */ +export interface IndexKey { + did: string; + vault: string; + deviceId: string; +} + +/** The database name of one linked device's index, under this Obsidian vault's namespace. */ +export const indexName = ( + namespace: string, + { did, vault, deviceId }: IndexKey, +) => `${PREFIX}:${namespace}:${did}:${vault}:${deviceId}`; + +/** + * Deletes every index this Obsidian vault holds, for each device it was ever + * linked as, so no later link can plan against a base its device never had. + */ +export async function deleteIndexes( + namespace: string, + factory: IDBFactory = indexedDB, +): Promise { + const prefix = `${PREFIX}:${namespace}:`; + for (const { name } of await factory.databases()) + if (name?.startsWith(prefix)) await request(factory.deleteDatabase(name)); +} + /** * The sync index in this app's IndexedDB, one database per linked device: * outside the vault folder, so git or another sync tool never copies it to a @@ -31,7 +62,7 @@ export class IndexedDbIndex implements SyncIndex { async load(): Promise { const db = await this.open(); try { - const value = await request( + const value = await request( db.transaction(STORE).objectStore(STORE).get(KEY), ); return Array.isArray(value) ? (value as Entry[]) : []; @@ -47,15 +78,11 @@ export class IndexedDbIndex implements SyncIndex { transaction.objectStore(STORE).put(entries, KEY); await new Promise((resolve, reject) => { transaction.oncomplete = () => resolve(); - transaction.onerror = () => reject(transaction.error); - transaction.onabort = () => reject(transaction.error); + transaction.onerror = () => reject(failure(transaction.error)); + transaction.onabort = () => reject(failure(transaction.error)); }); } finally { db.close(); } } - - async clear(): Promise { - await request(this.factory.deleteDatabase(this.name)); - } } diff --git a/src/lock.ts b/src/lock.ts index cfc2b7d..05ca7a6 100644 --- a/src/lock.ts +++ b/src/lock.ts @@ -1,11 +1,14 @@ /** - * Takes the Web Lock `name` without waiting and holds it until the returned - * function is called; null when someone else holds it. Locks span every - * window of this app's origin. Without Web Locks, nothing is held. + * Takes the Web Lock `name` and holds it until the returned function is + * called; null when someone else still holds it after `wait` ms. Locks span + * every window of this app's origin, and a plugin reloaded in this window + * waits here while its predecessor's last requests settle. Without Web + * Locks, nothing is held. */ export function holdLock( name: string, - locks: LockManager | undefined = globalThis.navigator?.locks, + wait: number, + locks: LockManager | undefined = window.navigator?.locks, ): Promise<(() => void) | null> { if (!locks) return Promise.resolve(() => {}); return new Promise((resolve, reject) => { @@ -14,11 +17,14 @@ export function holdLock( release = done; }); locks - .request(name, { ifAvailable: true }, async (lock) => { - if (!lock) return resolve(null); + .request(name, { signal: AbortSignal.timeout(wait) }, async () => { resolve(release); await held; }) - .catch(reject); + .catch((error: unknown) => { + if (error instanceof DOMException && error.name === "TimeoutError") + resolve(null); + else reject(error instanceof Error ? error : new Error(String(error))); + }); }); } diff --git a/src/main.ts b/src/main.ts index b1d9a2b..0fdacec 100644 --- a/src/main.ts +++ b/src/main.ts @@ -12,13 +12,14 @@ import { type TrustLoss, } from "./device"; import { requestUrlFetch } from "./fetch"; -import { IndexedDbIndex } from "./index-store"; +import { deleteIndexes, IndexedDbIndex, indexName } from "./index-store"; import { holdLock } from "./lock"; import { confirm, LinkModal } from "./obsidian/modals"; import { NoteSyncSettingTab, statusText } from "./obsidian/settings"; import { custodyNote, defaultLabel, + desktopResolveTxt, deviceNamespace, obsidianSecrets, obsidianVault, @@ -26,6 +27,8 @@ import { /** Flow ID, which links devices and relays the encrypted vault to the person's PDS. */ const FLOW_ID = "https://id.flow.industries"; +/** How long opening waits for another holder of this vault's link before saying it's syncing elsewhere. */ +const LOCK_WAIT_MS = 20_000; export default class NoteSyncPlugin extends Plugin { controller!: SyncController; @@ -48,11 +51,12 @@ export default class NoteSyncPlugin extends Plugin { }, host: FLOW_ID, fetch: requestUrlFetch(requestUrl), + resolveTxt: desktopResolveTxt(), local: obsidianVault(this.app), configDir: this.app.vault.configDir, - indexFor: (did, vault) => - new IndexedDbIndex(`flow-note-sync:${namespace}:${did}:${vault}`), - hold: () => holdLock(`flow-note:${namespace}`), + indexFor: (key) => new IndexedDbIndex(indexName(namespace, key)), + forgetIndexes: () => deleteIndexes(namespace), + hold: () => holdLock(`flow-note:${namespace}`, LOCK_WAIT_MS), forgetDevice: deleteDeviceStorage, confirmDeletions: ({ local, remote }) => confirm( diff --git a/src/obsidian/modals.ts b/src/obsidian/modals.ts index 36b54d5..096491f 100644 --- a/src/obsidian/modals.ts +++ b/src/obsidian/modals.ts @@ -1,5 +1,5 @@ import { type App, Modal, Notice, Setting } from "obsidian"; -import type { LinkedAccount } from "../account"; +import { handleDomain, type LinkedAccount } from "../account"; import type { SyncController } from "../controller"; import type { LinkPrompt } from "../device"; @@ -93,6 +93,12 @@ export class LinkModal extends Modal { contentEl.createEl("p", { text: "This vault is linked and syncing." }); return; } + if (phase.kind === "stopped") { + contentEl.createEl("p", { + text: `This vault is still linked, but syncing stopped: ${phase.message} Retry from this plugin's settings, or unlink the vault there before linking it again.`, + }); + return; + } contentEl.createEl("p", { text: "This vault becomes a device on your NOTE notepad. You approve it once in your browser; after that it syncs without asking for your passkey.", }); @@ -134,7 +140,7 @@ export class LinkModal extends Modal { .setDesc( "Type it on the link page. Never send it to anyone: it proves this vault is the device you approve.", ); - secret.controlEl.createEl("span", { + secret.controlEl.createSpan({ cls: "flow-note-code", text: prompt.pairingCode, }); @@ -153,14 +159,15 @@ export class LinkModal extends Modal { private renderConfirm(account: LinkedAccount) { const { contentEl } = this; contentEl.createEl("p", { text: "This vault is linked to this account:" }); - contentEl.createEl("p", { - cls: "flow-note-code", - text: accountName(account), - }); + if (account.handle) + new Setting(contentEl) + .setName(`@${account.handle}`) + .setDesc(`Vouched for by the domain ${handleDomain(account.handle)}`); + new Setting(contentEl).setName("DID").setDesc(account.did); contentEl.createEl("p", { text: account.handle - ? "Your notes will sync with this account's NOTE notepad. Continue only if it's yours." - : "The account's handle couldn't be confirmed, so this is its DID. Your notes will sync with this account's NOTE notepad. Continue only if it's yours.", + ? "Your notes will sync with this account's NOTE notepad. Check it is the account NOTE shows you, and that you know the domain: a handle under a domain you don't, however close it looks, isn't yours." + : "The account's handle couldn't be confirmed, so this is its DID. Check it is the account NOTE shows you: your notes will sync with this account's NOTE notepad.", }); new Setting(contentEl) .addButton((button) => diff --git a/src/obsidian/settings.ts b/src/obsidian/settings.ts index 5ce9c03..b99529f 100644 --- a/src/obsidian/settings.ts +++ b/src/obsidian/settings.ts @@ -63,7 +63,9 @@ export class NoteSyncSettingTab extends PluginSettingTab { new Setting(containerEl).setName("Account").setDesc(accountName(account)); const linked = phase.kind === "open" || phase.kind === "opening"; - if (!linked) + // A stopped vault is still linked: linking again would orphan its device, so it offers Retry and Unlink instead. + const linkable = !linked && phase.kind !== "stopped"; + if (linkable) new Setting(containerEl) .setName( phase.kind === "confirm" @@ -71,7 +73,7 @@ export class NoteSyncSettingTab extends PluginSettingTab { : "Link this vault", ) .setDesc( - "Approve this vault once in your browser at note.flow.talk. Nothing syncs until you confirm which account it linked to.", + "Approve this vault once in your browser, on NOTE's link page. Nothing syncs until you confirm which account it linked to.", ) .addButton((button) => button @@ -100,7 +102,12 @@ export class NoteSyncSettingTab extends PluginSettingTab { ); this.roundDetails(containerEl, controller.lastRound); } - if (account || phase.kind === "confirm" || linked) + if ( + account || + linked || + phase.kind === "confirm" || + phase.kind === "stopped" + ) new Setting(containerEl) .setName("Unlink") .setDesc( @@ -139,7 +146,7 @@ export class NoteSyncSettingTab extends PluginSettingTab { .slice(0, 5) .map(({ path, error }) => `${path || "Sync"}: ${error}`), round.unsyncable.length - ? `Not synced (a name one side can't store, a name that differs only in case, or an attachment over 32 MB): ${round.unsyncable.slice(0, 5).join(", ")}${round.unsyncable.length > 5 ? "…" : ""}` + ? `Not synced (a script another plugin could run, a name one side can't store, a name that differs only in case, or an attachment over 32 MB): ${round.unsyncable.slice(0, 5).join(", ")}${round.unsyncable.length > 5 ? "…" : ""}` : "", round.held.local || round.held.remote ? `Held back: ${round.held.local} deletions here and ${round.held.remote} in NOTE. Sync now to review them.` diff --git a/src/obsidian/vault.ts b/src/obsidian/vault.ts index e0e44df..0e21591 100644 --- a/src/obsidian/vault.ts +++ b/src/obsidian/vault.ts @@ -1,4 +1,5 @@ import { type App, MarkdownView, normalizePath, Platform } from "obsidian"; +import type { ResolveTxt } from "../account"; import type { SecretBackend } from "../custody"; import type { LocalVault } from "../engine"; import { parentOf, pathKey } from "../paths"; @@ -171,3 +172,16 @@ export function defaultLabel(): string { : "this device"; return `Obsidian on ${platform}`; } + +/** Node's DNS lookups on desktop, for handles verified by a TXT record; mobile has none. */ +export function desktopResolveTxt(): ResolveTxt | undefined { + if (!Platform.isDesktopApp) return undefined; + const { require } = window as unknown as { + require?: (id: string) => unknown; + }; + const dns = require?.("node:dns") as + | { promises?: { resolveTxt?: ResolveTxt } } + | undefined; + const lookup = dns?.promises?.resolveTxt; + return lookup && ((name) => lookup.call(dns?.promises, name)); +} diff --git a/src/traffic.ts b/src/traffic.ts new file mode 100644 index 0000000..2ead9d2 --- /dev/null +++ b/src/traffic.ts @@ -0,0 +1,36 @@ +/** Quiet this long after the last request settles before a closed device counts as idle. */ +const SETTLE_MS = 250; +const POLL_MS = 50; + +/** + * A device transport's requests and credential writes still in flight. Its + * lock must outlive a token refresh it already sent: a second transport that + * read the store before that refresh's write would present the rotated + * token, which Flow ID takes for a replay and revokes the device. + */ +export class Traffic { + private pending = 0; + private last = 0; + + /** Runs `work` as part of this traffic. */ + async track(work: () => Promise): Promise { + this.pending++; + this.last = Date.now(); + try { + return await work(); + } finally { + this.pending--; + this.last = Date.now(); + } + } + + /** Settles once nothing has been in flight for a moment, or after `limit` ms at most. */ + async idle(limit: number): Promise { + const deadline = Date.now() + limit; + while ( + Date.now() < deadline && + (this.pending > 0 || Date.now() - this.last < SETTLE_MS) + ) + await new Promise((resolve) => setTimeout(resolve, POLL_MS)); + } +} diff --git a/tests/controller.test.ts b/tests/controller.test.ts index 7376b7d..fc0659a 100644 --- a/tests/controller.test.ts +++ b/tests/controller.test.ts @@ -3,11 +3,12 @@ import type { SyncListener } from "@flow-industries/seal"; import { type ControllerOptions, LOCKED_ELSEWHERE, + REMOVED, STRANDED, SyncController, } from "../src/controller"; import { Custody, type SecretBackend } from "../src/custody"; -import type { DeviceVault } from "../src/device"; +import type { DeviceOptions, DeviceVault } from "../src/device"; import { sha256 } from "../src/hash"; import { isStale, MemoryIndex, MemoryRemote, MemoryVault } from "./fakes"; @@ -79,6 +80,9 @@ async function harness( stranded?: boolean; held?: boolean; confirmed?: boolean; + fetch?: ControllerOptions["fetch"]; + hold?: ControllerOptions["hold"]; + onOpen?: (options: DeviceOptions) => void; } = {}, ) { const secrets = new Secrets(); @@ -98,8 +102,9 @@ async function harness( device: { createDeviceSeed: () => new Uint8Array(32).fill(2), linkDevice: () => new Promise(() => {}), - openDeviceVault: async () => { + openDeviceVault: async (_seed, deviceOptions) => { await options.opened; + options.onOpen?.(deviceOptions); return device.vault; }, locked: "Locked", @@ -107,11 +112,12 @@ async function harness( stale: isStale, }, host: "https://id.example", - fetch: async () => new Response(null, { status: 404 }), + fetch: options.fetch ?? (async () => new Response(null, { status: 404 })), local, configDir: ".obsidian", indexFor: () => index, - hold: async () => (options.held ? null : () => {}), + forgetIndexes: async () => index.clear(), + hold: options.hold ?? (async () => (options.held ? null : () => {})), forgetDevice: async (seed) => { forgotten.push(`seed ${seed[0]}`); }, @@ -179,12 +185,22 @@ describe("controller", () => { } }); - test("a link started while a restart names the old account wins", async () => { + test("a link started over a stored link is refused, and the stored link stays", async () => { const h = await harness({ confirmed: false }); const restarting = h.controller.start(); - void h.controller.link("Obsidian", new AbortController().signal); + const linking = h.controller + .link("Obsidian", new AbortController().signal) + .then( + () => "linked", + (error: Error) => error.message, + ); await restarting; - expect(h.controller.phase.kind).toBe("linking"); + expect( + await Promise.race([linking, Bun.sleep(500).then(() => "linking")]), + ).toMatch(/still linked/u); + expect(h.controller.phase.kind).toBe("confirm"); + expect(h.custody.seed()).not.toBeNull(); + expect(h.forgotten).toEqual([]); }); test("a second window of the same vault doesn't open a second transport", async () => { @@ -248,4 +264,233 @@ describe("controller", () => { expect(h.local.text(copy ?? "")).toBe("edit the rotation stranded"); h.controller.close(); }); + + test("a stop or a removal is told once in a notice, since mobile has no status bar", async () => { + const h = await harness({ held: true }); + await h.controller.start(); + await h.controller.syncNow(); + expect(h.notices).toEqual([`Syncing stopped. ${LOCKED_ELSEWHERE}`]); + + let removed: DeviceOptions["onRemoved"]; + const r = await harness({ + onOpen: (options) => { + removed = options.onRemoved; + }, + }); + await r.controller.start(); + await removed?.("removed"); + expect(r.controller.phase.kind).toBe("removed"); + expect(r.notices).toEqual([REMOVED.removed]); + }); + + test("a reopen waits for a token refresh the closed device already sent", async () => { + const refresh = Promise.withResolvers(); + let opens = 0; + let held = false; + const h = await harness({ + fetch: () => refresh.promise, + hold: async () => { + if (held) return null; + held = true; + return () => { + held = false; + }; + }, + onOpen: (options) => { + if (++opens === 1) + void options.fetch?.("https://id.example/refresh", { + method: "POST", + }); + }, + }); + await h.controller.start(); + h.controller.close(); + const reopening = h.controller.start(); + await Bun.sleep(100); + expect(opens).toBe(1); + expect(h.controller.phase.kind).not.toBe("stopped"); + refresh.resolve(new Response("{}")); + await reopening; + expect(opens).toBe(2); + expect(h.controller.phase.kind).toBe("open"); + h.controller.close(); + }); +}); + +/** A device vault over `remote`; `beforeSave` can hold a save open mid-round. */ +function deviceOver( + remote: MemoryRemote, + hooks: { beforeSave?: () => Promise } = {}, +) { + const listeners = new Set(); + return { + read: () => remote.read().then((view) => ({ ...view, folders: [] })), + saveNote: async (note, options) => { + await hooks.beforeSave?.(); + return remote.saveNote(note, options); + }, + listAttachments: async () => + (await remote.listAttachments()).map((item) => ({ + ...item, + mime: "application/octet-stream", + size: 0, + })), + readAttachment: (id) => remote.readAttachment(id), + saveAttachment: (attachment, options) => + remote.saveAttachment(attachment, options), + rename: (id, path, base) => remote.rename(id, path, base), + remove: (id, base) => remote.remove(id, base), + compose: async () => ({ selectedId: "" }), + sync: async () => { + for (const listener of listeners) await listener("Synced"); + }, + subscribe: (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + subscribeChanges: () => () => {}, + subscribeTrustLoss: () => () => {}, + stop: () => {}, + } as DeviceVault; +} + +/** + * A linked, confirmed vault whose opens answer from `opens` in turn, and + * whose next link is device 2. Indexes are named by whatever the controller + * passes, as the plugin names their databases. + */ +function linkedVault(local: MemoryVault, opens: (() => DeviceVault)[]) { + const secrets = new Secrets(); + const custody = new Custody(secrets, "0123456789abcdef"); + const credentialsOf = (deviceId: string) => ({ ...credentials, deviceId }); + custody.saveSeed(new Uint8Array(32).fill(1)); + void custody.credentials.write(credentialsOf("device-1")); + void custody.checkpoints.write(checkpoint); + custody.confirmAccount({ did }); + const indexes = new Map(); + const controller = new SyncController({ + custody, + device: { + createDeviceSeed: () => new Uint8Array(32).fill(2), + linkDevice: async (_seed, options) => { + await options.credentials.write(credentialsOf("device-2")); + await options.checkpoints.write(checkpoint); + return checkpoint; + }, + openDeviceVault: async () => { + const open = opens.shift(); + if (!open) throw new Error("No more opens"); + return open(); + }, + locked: "Locked", + pulled: (status) => status === "Synced", + stale: isStale, + }, + host: "https://id.example", + fetch: async () => new Response(null, { status: 404 }), + local, + configDir: ".obsidian", + indexFor: (...key: unknown[]) => { + const name = JSON.stringify(key); + const index = indexes.get(name) ?? new MemoryIndex(); + indexes.set(name, index); + return index; + }, + forgetIndexes: async () => indexes.clear(), + hold: async () => () => {}, + forgetDevice: async () => {}, + confirmDeletions: async () => true, + onChange: () => {}, + onTrustLoss: () => {}, + notify: () => {}, + }); + return { controller, secrets, indexes }; +} + +describe("controller: linking again", () => { + for (const way of ["over a stopped link", "after the secrets were lost"]) + test(`${way} never plans against the old device's index, so edits that never left it survive`, async () => { + const local = new MemoryVault(); + // NOTE on the PDS, and device 1's own database, whose writes never got uploaded. + const server = new MemoryRemote(); + const outbox = new MemoryRemote(); + server.put("a", "A.md", "v1"); + outbox.put("a", "A.md", "v1"); + local.put("A.md", "v1"); + const offline = () => { + throw new Error("Failed to fetch"); + }; + const { controller, secrets } = linkedVault( + local, + way === "over a stopped link" + ? [() => deviceOver(outbox), offline, () => deviceOver(server)] + : [() => deviceOver(outbox), () => deviceOver(server)], + ); + await controller.start(); + await controller.syncNow(); + local.put("A.md", "v2, typed offline"); + local.put("New.md", "a new note, typed offline"); + await controller.syncNow(); + expect(outbox.text("A.md")).toBe("v2, typed offline"); + expect(server.text("A.md")).toBe("v1"); + controller.close(); + + if (way === "over a stopped link") { + await controller.start(); + expect(controller.phase.kind).toBe("stopped"); + } else { + secrets.values.clear(); + await controller.start(); + expect(controller.phase.kind).toBe("unlinked"); + } + const signal = new AbortController().signal; + // Settings offer only Retry and Unlink on a stopped link; the person unlinks, then links. + await controller + .link("Obsidian", signal) + .catch(() => + controller.unlink().then(() => controller.link("Obsidian", signal)), + ); + await controller.confirm(); + await controller.syncNow(); + await Bun.sleep(5); + controller.close(); + + const texts = [...local.files.keys()].map((path) => local.text(path)); + expect(texts).toContain("v2, typed offline"); + expect(texts).toContain("a new note, typed offline"); + expect(local.trashed).toEqual([]); + expect(server.text("New.md")).toBe("a new note, typed offline"); + }); + + test("an unlink during a round's write leaves no sync index behind", async () => { + const local = new MemoryVault(); + const remote = new MemoryRemote(); + let release = () => {}; + let blocked = false; + const { controller, indexes } = linkedVault(local, [ + () => + deviceOver(remote, { + beforeSave: () => + blocked + ? new Promise((resolve) => { + release = resolve; + }) + : Promise.resolve(), + }), + ]); + local.put("Old.md", "synced before"); + await controller.start(); + await controller.syncNow(); + expect(indexes.size).toBe(1); + local.put("A.md", "a"); + blocked = true; + const syncing = controller.syncNow(); + await Bun.sleep(5); + await controller.unlink(); + release(); + await syncing; + await Bun.sleep(5); + expect(controller.phase.kind).toBe("unlinked"); + expect([...indexes.values()].flatMap((index) => index.entries)).toEqual([]); + }); }); diff --git a/tests/device.test.ts b/tests/device.test.ts new file mode 100644 index 0000000..fd4d8c7 --- /dev/null +++ b/tests/device.test.ts @@ -0,0 +1,19 @@ +import { expect, test } from "bun:test"; +import { + SYNC_PENDING, + SYNC_QUOTA_REACHED, + SYNC_RATE_LIMITED, + SYNC_TOO_LARGE, + SYNCED, +} from "@flow-industries/seal"; +import { pulledStatus } from "../src/device"; + +test("only a sync that read the whole vault counts as pulled", () => { + const backoff = (refusal: string) => `${refusal} · Next sync 12:00`; + expect(pulledStatus(SYNCED)).toBe(true); + expect(pulledStatus(backoff(SYNC_QUOTA_REACHED))).toBe(true); + expect(pulledStatus(backoff(SYNC_TOO_LARGE))).toBe(true); + // A rate limit can refuse the read itself, so a new link would plan against an empty vault. + expect(pulledStatus(backoff(SYNC_RATE_LIMITED))).toBe(false); + expect(pulledStatus(SYNC_PENDING)).toBe(false); +}); diff --git a/tests/e2e.test.ts b/tests/e2e.test.ts index e3f6589..df18484 100644 --- a/tests/e2e.test.ts +++ b/tests/e2e.test.ts @@ -64,12 +64,13 @@ function obsidian(note: FakeFlowId, name: string) { fetch: note.fetch, local, configDir: ".obsidian", - indexFor: (did, vault) => { - const key = `${did}:${vault}`; - const index = indexes.get(key) ?? new MemoryIndex(); - indexes.set(key, index); + indexFor: (key) => { + const name = JSON.stringify(key); + const index = indexes.get(name) ?? new MemoryIndex(); + indexes.set(name, index); return index; }, + forgetIndexes: async () => indexes.clear(), hold: async () => () => {}, forgetDevice: deleteDeviceStorage, confirmDeletions: async () => true, diff --git a/tests/fetch.test.ts b/tests/fetch.test.ts index b2c7f9e..dc49db4 100644 --- a/tests/fetch.test.ts +++ b/tests/fetch.test.ts @@ -1,9 +1,9 @@ import { describe, expect, test } from "bun:test"; import { IDBFactory } from "fake-indexeddb"; -import { linkedAccount } from "../src/account"; +import { handleDomain, linkedAccount } from "../src/account"; import type { NoteDeviceFetch } from "../src/device"; import { type RequestUrl, requestUrlFetch } from "../src/fetch"; -import { IndexedDbIndex } from "../src/index-store"; +import { deleteIndexes, IndexedDbIndex, indexName } from "../src/index-store"; describe("fetch over requestUrl", () => { test("passes method, headers and bytes through, and answers a real Response", async () => { @@ -83,6 +83,36 @@ describe("the linked account", () => { }); }); +describe("the linked account's handle", () => { + const did = "did:plc:abcdefghijklmnopqrstuvwx"; + const document = { id: did, alsoKnownAs: ["at://alice.example.com"] }; + const documentOnly: NoteDeviceFetch = async (url) => + url === `https://plc.directory/${did}` + ? Response.json(document) + : new Response("not found", { status: 404 }); + + test("is also verified by DNS where the platform can look it up", async () => { + const dns = async (name: string) => + name === "_atproto.alice.example.com" ? [[`did=${did}`], ["v=spf1"]] : []; + expect(await linkedAccount(did, documentOnly, dns)).toEqual({ + did, + handle: "alice.example.com", + }); + expect(await linkedAccount(did, documentOnly)).toEqual({ did }); + const two = async () => [[`did=${did}`], ["did=did:plc:other"]]; + expect(await linkedAccount(did, documentOnly, two)).toEqual({ did }); + const elsewhere = async () => [["did=did:plc:other"]]; + expect(await linkedAccount(did, documentOnly, elsewhere)).toEqual({ did }); + }); + + test("shows the domain that vouched for it, so a lookalike reads as itself", () => { + expect(handleDomain("alice.flow.talk")).toBe("flow.talk"); + expect(handleDomain("alice-flow.talk.example")).toBe("talk.example"); + expect(handleDomain("alice.example.co.uk")).toBe("example.co.uk"); + expect(handleDomain("example.org")).toBe("example.org"); + }); +}); + describe("the sync index", () => { test("persists in its own IndexedDB database", async () => { const factory = new IDBFactory(); @@ -102,4 +132,22 @@ describe("the sync index", () => { await new IndexedDbIndex("flow-note-sync:test", factory).load(), ).toEqual([entry]); }); + + test("is one database per linked device, and forgetting deletes only this vault's", async () => { + const factory = new IDBFactory(); + const link = { did: "did:plc:x", vault: "v" }; + const first = indexName("aaaaaaaaaaaaaaaa", { ...link, deviceId: "d1" }); + const second = indexName("aaaaaaaaaaaaaaaa", { ...link, deviceId: "d2" }); + const other = indexName("bbbbbbbbbbbbbbbb", { ...link, deviceId: "d1" }); + expect(new Set([first, second, other]).size).toBe(3); + for (const name of [ + first, + second, + other, + "flow-note-sync:aaaaaaaaaaaaaaaa:did:plc:x:v", + ]) + await new IndexedDbIndex(name, factory).save([]); + await deleteIndexes("aaaaaaaaaaaaaaaa", factory); + expect((await factory.databases()).map((db) => db.name)).toEqual([other]); + }); }); From 07578bf5f673778f5cf177c33ce2a017c5c05776 Mon Sep 17 00:00:00 2001 From: kualta Date: Wed, 4 Nov 2026 14:09:30 -0500 Subject: [PATCH 06/16] converge rename cycles and keep vault scripts out of sync --- src/conflicts.ts | 35 ++++++---- src/engine.ts | 149 +++++++++++++++++++++++++++++++++++++------ src/paths.ts | 14 +++- tests/engine.test.ts | 100 +++++++++++++++++++++++++++++ tests/paths.test.ts | 22 +++++++ 5 files changed, 285 insertions(+), 35 deletions(-) diff --git a/src/conflicts.ts b/src/conflicts.ts index 2b0d1f2..88e6afa 100644 --- a/src/conflicts.ts +++ b/src/conflicts.ts @@ -4,21 +4,18 @@ const encoder = new TextEncoder(); const MAX_NAME_BYTES = 255; /** - * Where a conflicting copy of `path` goes: beside it, named as NOTE names its - * own conflict copies of notes, ` conflict <8 hex>.md`, with the name - * shortened until it fits 255 bytes. An attachment keeps its extension last - * too, where NOTE would append the suffix, so Obsidian still opens it. + * `path` renamed beside itself, `