everysync: phases 1-3 cross-platform program
- Commit
e060476d7d09b5441ba2bfa68136938ddc772fc4- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-16 21:01 UTC (1 month ago)
- Parents
d3b36df
Diff
CROSS_PLATFORM_STATUS.md
diff --git a/CROSS_PLATFORM_STATUS.md b/CROSS_PLATFORM_STATUS.mdnew file mode 100644index 0000000000..995a8a9cb6--- /dev/null+++ b/CROSS_PLATFORM_STATUS.md@@ -0,0 +1,54 @@+# EverySync Cross-Platform Status++Single source of truth for the shared-core + system-sink + shell program+(Phases 1–3). Relay contract and invariants are restated here verbatim so no+target re-derives them.++## Phase table++| Phase | Scope | Status |+|-------|-------|--------|+| 1 — core | Shared KMP sync brain (`library/everysync-core`): relay merge, vault policy, DTOs, iCal/vCard formats, PQC transport surface | DONE (`6eb6023d2`, `5ff387959`, `82a121367`) |+| 1D — bindings | Platform actuals: OkHttp (Android/JVM), Darwin (Apple), JNI/JNA PQC, secure stores, scheduler | DONE |+| 2 — desktop shells | JVM providers binding `sinks/` interfaces to EDS `libecal`/`libebook` (Linux) and `AppointmentStore`/`ContactStore` read-only v1 + Notes-view todos (Windows) | planned (`desktop/`) |+| 2c/3b — system sinks (this change) | `sinks/SystemSinks.kt` interface docs: `CalendarSystemSink`, `ContactsSystemSink`, `TodoSystemSink` over existing `SyncSink<T>` | DONE |+| 3 — Apple shells | Swift/KMP providers binding `sinks/` to EventKit `EKEvent`/`EKReminder` + `CNContactStore` | planned (`apple/`) |++## Relay contract++- Base `https://findfamily.cc/personal`, WS `wss://…/ws`.+- Endpoints: `POST /register | /getkey | /append | /pull`.+- Channels: `<type>:<vaultId>` records, `members:`, `keys:`, `owner:`, `title:`, `inbox:<device>`, `notes-blobs:<vaultId>`.+- The relay is an untrusted append-only log: records are never rewritten, only appended; authority is client-side (owner-signed roster/epochs/transfers); vault keys never user-visible.++## Invariants (verbatim)++1. A failed pull returns null = abort, never empty. Folding a failure as empty reads every baseline-present id as deleted.+2. A failed local read surfaces as failure (`LocalReadException` / `listLocalOk == false`), never as an empty list. An empty list means "provably holds nothing locally".+3. Only explicit tombstones delete; absence without a tombstone resurrects (soft-delete types) or quarantines — never deletes.+4. `remoteOut` appends to the relay BEFORE persisting locally.+5. Passwords hard-delete (no tombstone rows); notes/todos soft-delete (tombstone rows persist and propagate); calendar/contacts soft-delete via provider `DELETED` flags.+6. Passwords vaults never grant VIEWER.++## Sink mapping summary++- `CalendarSystemSink : SyncSink<RemoteEvent>` — `RemoteEvent` <-> iCal VEVENT (`core.format.ICalendar`; UID + RECURRENCE-ID identity; RRULE verbatim, duration-instead-of-end for masters). Android: `_SYNC_ID`/`SYNC_DATA1`/`SYNC_DATA2` + `CALLER_IS_SYNCADAPTER` + `DIRTY`/`DELETED`. Apple: `EKEvent`. Linux: `libecal`. Windows: `AppointmentStore` read-only v1.+- `ContactsSystemSink : SyncSink<RemoteContact>` — `RemoteContact` <-> vCard (`core.format.VCard`; shared `PhoneKind`/`EmailKind`/`PostalKind` ints). Android: `SOURCE_ID`/`SYNC1`/`SYNC2` + `CALLER_IS_SYNCADAPTER` + `DIRTY`/`DELETED`. Apple: `CNContactStore`. Linux: `libebook`. Windows: `ContactStore` read-only v1.+- `TodoSystemSink : SyncSink<RemoteTodo>` — `RemoteTodo` JSON on `todos:<vaultId>` <-> native reminder (`EKReminder` / `libecal` todo / Notes-view row). `notes` + `createdAt` must persist (envelope + hash inputs); tombstones are real rows; `position` is ordering-only.++## Drift fixes applied++- Todo `notes`/`createdAt`: persisted in the envelope AND the merge hash (`TodoKind.canonical`); native stores must persist both or LWW on those fields never converges.+- Passwords KDoc: `RemotePassword` documents the native vault-field mirror (no KDBX mapping) and the password/passkey halves; `PasswordKind`/`EntryMapper` document hard-delete + tombstone-marker semantics.++## Verification matrix++- Slices: `:library:everysync-core:compileKotlinJvm`, `:library:everysync-core:lint` (no Gradle run in this change per scope).+- Tests (existing, must stay green): `RelayConformanceTest`, `SharedTransportTest`, `SyncDigestTest`, `TodoKindTest` (commonTest, 25 tests) + `JvmPqcVectorConformanceTest` (jvmTest, 6 tests).+- Live-relay checklist: register → getkey → append → pull round-trip against `https://findfamily.cc/personal`; null-pull abort; tombstone propagation per type; re-enable repopulation after purge.++## Next steps++1. Desktop providers (`desktop/`): implement `sinks/` over EDS (Linux) and read-only stores + Notes-view todos (Windows v1).+2. Apple providers (`apple/`): implement `sinks/` over EventKit + `CNContactStore`.+3. Live-relay pass per target using the checklist above.
apple/Hub/HubSync.swift
diff --git a/apple/Hub/HubSync.swift b/apple/Hub/HubSync.swiftnew file mode 100644index 0000000000..fad2a4f918--- /dev/null+++ b/apple/Hub/HubSync.swift@@ -0,0 +1,64 @@+// EverySync Hub — Phase 3a sync-hub shell.+//+// Zero sync logic in Swift. All merge / transport / crypto lives in the+// shared XCFramework (everysync-core KMP). This file only declares the hub+// entry point — SyncDriver scheduling plus EKReminder / CNContact / EKEvent+// sinks — and, in comments, the exact KMP entry points Phase 3 will call.+// Nothing here merges, hashes, or encrypts. There is no Todo UI: tasks+// surface in the system Reminders app.++import EventKit+import Contacts+import EverysyncCore++// MARK: - KMP entry points (Phase 3 wiring, for reference only)+//+// data: com.vayunmathur.everysync.core.data.RemoteTodo+// com.vayunmathur.everysync.core.data.RemoteContact+// com.vayunmathur.everysync.core.data.RemoteEvent+// kinds: com.vayunmathur.everysync.core.sync.adapters.TodoKind+// (channel "todos:<vaultId>"; soft-delete; reorder is not an edit)+// driver: com.vayunmathur.everysync.core.provider.SyncDriver+// cursors: com.vayunmathur.everysync.core.platform.RelayCursorStore+// securestore: com.vayunmathur.everysync.core.platform.SecureStore (Keychain actual)+// transport: com.vayunmathur.everysync.core.network.IosRelayTransport+// channels: recordChannel / membersChannel / keysChannel / ownerChannel+// / titleChannel / inboxChannel / blobChannel ("notes-blobs:<vaultId>")+// roles: RelayRoles — passwords offer EDITOR only, never VIEWER+// links: RelayLinks.parseJoinLink / .shareLinkFor+// pqc: 10 fns per IOS_PQC_NOTES.md (e2eePqc cinterop)++/// Sync hub: runs XCFramework SyncDriver cycles, owns the App-Group envelope+/// store (see ../IPC_CONTRACT.md), and sinks todos/contacts/calendar into+/// the system stores. Scheduling + mapping only.+final class HubSync {+ let eventStore = EKEventStore()+ let contactStore = CNContactStore()++ // TODO(Phase 3): create SyncDriver + IosRelayTransport from the+ // XCFramework; open the App-Group envelope store; register+ // BGTaskScheduler handlers (see README.md).++ func requestSystemAccess() {+ // TODO(Phase 3): eventStore.requestAccess(to: .reminder),+ // eventStore.requestAccess(to: .event),+ // contactStore.requestAccess(for: .contacts),+ // then start SyncDriver cycles.+ }++ func syncTodosToReminders(vaultId: String) {+ // TODO(Phase 3): pull "todos:<vaultId>" via SyncDriver; upsert+ // EKReminder per the README mapping table; persist known syncIds so+ // a vanished EKReminder folds back as a tombstone envelope.+ }++ func syncContacts(vaultId: String) {+ // TODO(Phase 3): apply SyncDriver contact output to CNContactStore;+ // keep the syncId<->identifier map hub-local.+ }++ func syncCalendarEvents(vaultId: String) {+ // TODO(Phase 3): apply SyncDriver event output to EKEventStore in the+ // hub-managed calendar.+ }+}
apple/Hub/README.md
diff --git a/apple/Hub/README.md b/apple/Hub/README.mdnew file mode 100644index 0000000000..cec160fae9--- /dev/null+++ b/apple/Hub/README.md@@ -0,0 +1,104 @@+# EverySync Hub — Apple shell (Phase 3a)++Sync hub. **All merge / transport / crypto lives in the shared XCFramework**+(`everysync-core` KMP); this target runs `SyncDriver` cycles, owns the+App-Group envelope store, and sinks todos / contacts / calendar into the+system stores (Reminders, Contacts, Calendar). There is **no standalone Todo+app** — tasks surface in the system Reminders app, matching the plan.++## Architecture++```+HubSync ──► EverysyncCore.xcframework ──► relay+ │ │+ │ schedules │ merge / TOTP / PQC /+ │ cycles only │ transport / cursors+ ▼ ▼+App-Group envelope store ◄── Passwords / Notes shells (IPC, see ../IPC_CONTRACT.md)+ │+ ├──► EKReminder sink (todos) ──► Reminders app+ ├──► CNContact sink (contacts)+ └──► EKEvent sink (calendar)+```++The hub is the only process that talks to the relay. Passwords/Notes shells+read and write envelopes through the IPC store; the hub pushes/pulls.++## KMP entry points this shell will call (nothing else)++| Kotlin FQN | Used for |+|---|---|+| `core.data.RemoteTodo` | Envelope on `todos:<vaultId>`: `uid / title / notes / done / dueAt (epoch ms, nullable) / position / createdAt / deleted / updatedAt`. |+| `core.sync.adapters.TodoKind` | `syncId=uid`, LWW on `updatedAt`, canonical strips identity/position/timestamps (reorder is not an edit), `contentKey = "todo␀" + title + "␀" + createdAt`. Todos soft-delete. |+| `core.data.RemoteContact` | Envelope: name parts + organization + note + `phones/emails/addresses` (`TypedValue(value, type)`; type ints mirror Android `ContactsContract`) + ISO-8601 `birthday` + `etag/href/deleted/updatedAt`. |+| `core.data.RemoteEvent` | Envelope: `calendarId / summary / description / location / startMillis / endMillis / allDay / timezone / rrule (no RRULE: prefix) / recurrenceId / etag / href / deleted / updatedAt`. |+| `core.provider.SyncDriver` + `core.platform.RelayCursorStore` | Sync cycles; cursor keys `relay_cursor:<type>:<vault>:<channel>`. |+| `core.network.IosRelayTransport` | Ktor-Darwin + trust pinning (lands Phase 3; stub today). Channels via `recordChannel` (`passwords:`/`notes:`/`todos:` per vault), `members:`/`keys:`/`owner:`/`title:` per vault, `inbox:<deviceId>`, blobs `notes-blobs:<vaultId>`. |+| `core.network.RelayRoles` / `RelayLinks` | Role checks and `everysync://join/…` + share-link parsing stay in Kotlin. Passwords vaults offer EDITOR only, never VIEWER. |+| PQC cinterop (`IOS_PQC_NOTES.md`) | Same 10 fns as Passwords/Notes. |++## Todos → Reminders sink (no Todo app)++`EKEventStore` + `requestAccess(to: .reminder)`; synced tasks live in a+dedicated hub-managed `EKCalendar` (or the default list) and appear in the+system Reminders app. Field mapping:++| `RemoteTodo` | `EKReminder` |+|---|---|+| `uid` | `calendarItemIdentifier` via the hub's syncId↔identifier map (identifiers are hub-local state, not IPC columns) |+| `title` | `title` |+| `notes` | `notes` |+| `done` | `completed` (+ `completionDate`) |+| `dueAt` (epoch ms, nullable) | `dueDateComponents` (via `Calendar`; nil clears) |+| `position` | not mapped — sort client-side (excluded from the merge hash, so reorder is never an edit) |+| `createdAt` | read-only reference (part of the adoption content key; never written back) |+| `deleted=true` envelope | remove the `EKReminder` |++### Tombstone mapping++`EKReminder` has no tombstone: a user-deleted reminder simply vanishes from+the store. The hub therefore persists the set of known syncIds per vault;+after a healthy fetch, any known syncId with no matching `EKReminder` is a+genuine local delete and is folded into the next merge as a tombstone+envelope. Merge-driven deletes always arrive as tombstone envelopes, never+raw deletes. Same healthy-read discipline as `SyncSink.listLocalOk`: an+unhealthy fetch aborts the cycle instead of reading absence as deletion.++## Contacts sink++`CNContactStore` + `requestAccess(for: .contacts)`. Maps `RemoteContact`+name parts / organization / note / typed phones-emails-addresses / birthday+onto `CNMutableContact`; syncId↔`CNContact.identifier` lives in the hub map+(Swift never scribbles syncIds into user-visible contact fields). Delete and+conflict semantics follow the XCFramework entity kind — Swift holds no+opinion beyond faithfully applying `SyncDriver` output.++## Calendar sink++`EKEventStore` + calendar access. Maps `RemoteEvent` summary / description /+location / start-end millis / allDay / timezone / RRULE / recurrenceId onto+`EKEvent` in a hub-managed calendar. Same driver-applies, Swift-renders+split as above.++## Keychain / BGTaskScheduler++KMP `SecureStore` actual = Keychain `kSecClassGenericPassword` (shared+Keychain group with Passwords/Notes). `BGAppRefreshTaskRequest(identifier:+"com.vayunmathur.everysync.hub.refresh")` for periodic cycles plus a+`BGProcessingTaskRequest` for uploads after local system-store changes.+Scheduling only — cycles run in the XCFramework.++## Info.plist / entitlements notes++- `NSRemindersUsageDescription` — todos sink ("EverySync syncs shared task lists into Reminders").+- `NSCalendarsUsageDescription` — calendar sink.+- `NSContactsUsageDescription` — contacts sink.+- `com.apple.security.application-groups`: `group.<team>.everysync.shared` (envelope IPC store).+- `keychain-access-groups`: `$(AppIdentifierPrefix)com.vayunmathur.everysync.hub`.+- `UIBackgroundModes`: `fetch` + `processing` (BGTaskScheduler periodic work).++## Swift must NOT++Run merge/LWW, compute content hashes, encrypt envelopes, parse join links,+check roles, or re-implement TOTP/block parsing. Driver output in, system+stores out — nothing else.
apple/IPC_CONTRACT.md
diff --git a/apple/IPC_CONTRACT.md b/apple/IPC_CONTRACT.mdnew file mode 100644index 0000000000..201a17a8c3--- /dev/null+++ b/apple/IPC_CONTRACT.md@@ -0,0 +1,60 @@+# Apple envelope IPC contract (Phase 3a)++How the Passwords / Notes / Hub processes share vault envelopes on-device.+Mirrors the Android relay-provider ops and the KMP `SyncSink` interface+(`querySince` / `upsertRaw` / `deleteByVault`) with **identical columns**.+The hub is the only process that talks to the relay; shells read and write+envelopes here; the Credential Provider extension reads over XPC.++## Transport++- **Location:** App-Group shared container+ `group.<team>.everysync.shared`, one SQLite file per vault at+ `vault/<vaultId>/envelopes.sqlite`, plus a `blobs/` sidecar dir for note+ image bytes keyed by `fileName`.+- **Coordination:** `NSFileCoordinator` for file-level coordination between+ the apps and their extensions.+- **XPC for the Credential Provider:** the autofill extension cannot assume+ direct store access, so the containing Passwords app exposes an XPC service+ (`com.vayunmathur.everysync.envelope-ipc`) with exactly the three ops below.+ The extension never touches the relay.++## Ops (map 1:1 to KMP `SyncSink`)++| IPC op | KMP `SyncSink` | Semantics |+|---|---|---|+| `querySince(vaultId, table, since)` | `listLocal` + `localChanges` | Rows with `updatedAt > since`, tombstones included; drives both baseline reads and delta detection. An unhealthy read aborts the merge (never fold failure as empty). |+| `upsertRaw(vaultId, table, rows)` | `upsert` | Idempotent upsert keyed on `syncId`; preserves pulled timestamps. |+| `deleteByVault(vaultId, table, syncId)` | `delete` | Passwords table: **hard-delete** the row. Notes/todos tables: set `deleted=1` tombstone. Merge-driven deletes ALWAYS arrive here as tombstone envelopes, never raw deletes. |++## Columns (identical everywhere)++| Column | Type | Semantics | KMP source |+|---|---|---|---|+| `syncId` | TEXT PRIMARY KEY | Relay sync identity (opaque 32-char id) | `EntityKind.syncId` → `RemoteX.uid` |+| `updatedAt` | INTEGER | Last modification, epoch ms; drives relay LWW | `RemoteX.updatedAt` |+| `deleted` | INTEGER 0/1 | Tombstone flag | `RemoteX.deleted` |+| `payloadJson` | TEXT | Full `RemoteX` JSON envelope, plaintext at rest (protected by sandbox + Data Protection; encryption happens at the relay layer, not here) | `PasswordKind` / `NoteKind` / `TodoKind.toJson` |+| `contentHash` | TEXT | `relayContentHash(canonical + "\0deleted=…")`; canonical strips identity/ordering/timestamps | `EntityKind.contentHash` |++## Tables ↔ relay channels++| Table | Relay channel | Envelope | Delete |+|---|---|---|---|+| `passwords` | `passwords:<vaultId>` | `RemotePassword` (`isPasskey` selects the password vs passkey half) | **HARD** — rows vanish; only the app-side snapshot remembers them (`localDeletesAreAuthoritative == false`, so a healthy-read absence IS a genuine local delete) |+| `notes` | `notes:<vaultId>` | `RemoteNote` (title + content + `blocksJson`; image bytes in `blobs/` + `notes-blobs:<vaultId>`) | **SOFT** — `deleted=1` tombstones persist and propagate |+| `todos` | `todos:<vaultId>` | `RemoteTodo` | **SOFT** — tombstones persist and propagate |+| `contacts` / `calendars` | per `recordChannel` | `RemoteContact` / `RemoteEvent` | Hub-managed; same columns; delete semantics per the XCFramework entity kind (Swift holds no opinion) |++Contacts/calendar rows are hub-internal (system stores are the UI); shells+for those types do not exist in Phase 3a.++## Concurrency rules++1. Single writer to the relay: the hub. Shells only touch the IPC store.+2. All IPC access goes through `NSFileCoordinator` (or the XPC service,+ which does it internally).+3. Cursor keys (`relay_cursor:<type>:<vault>:<channel>`) live in the Keychain+ `SecureStore` via `RelayCursorStore`, not in these tables.+4. Vault AES keys never appear here or in share links — keys move exclusively+ via PQC-sealed inbox invites (`inbox:<deviceId>`).
apple/Notes/NotesApp.swift
diff --git a/apple/Notes/NotesApp.swift b/apple/Notes/NotesApp.swiftnew file mode 100644index 0000000000..69db8ee2e0--- /dev/null+++ b/apple/Notes/NotesApp.swift@@ -0,0 +1,48 @@+// EverySync Notes — Phase 3a SwiftUI shell.+//+// Zero sync logic in Swift. All blocks parsing, merge, transport, and crypto+// lives in the shared XCFramework (everysync-core KMP). This file only+// declares the UI entry point and — in comments — the exact KMP entry points+// Phase 3 will call, plus the PencilKit mapping contract (see README.md).+// Nothing here parses JSON, merges, hashes, or encrypts.++import SwiftUI+import PencilKit+import EverysyncCore++// MARK: - KMP entry points (Phase 3 wiring, for reference only)+//+// data: com.vayunmathur.everysync.core.data.RemoteNote+// blocks: com.vayunmathur.everysync.core.notes.parseNoteBody+// com.vayunmathur.everysync.core.notes.serializeNoteBody+// com.vayunmathur.everysync.core.notes.noteBodyText+// com.vayunmathur.everysync.core.notes.NoteBlock+// com.vayunmathur.everysync.core.notes.InkStroke+// com.vayunmathur.everysync.core.notes.InkPoint+// kind: com.vayunmathur.everysync.core.sync.adapters.NoteKind+// blobs: NoteKind.imageNames(blocksJson); channel "notes-blobs:<vaultId>"+// driver: com.vayunmathur.everysync.core.provider.SyncDriver+// cursors: com.vayunmathur.everysync.core.platform.RelayCursorStore+// securestore: com.vayunmathur.everysync.core.platform.SecureStore (Keychain actual)+// transport: com.vayunmathur.everysync.core.network.IosRelayTransport+// channels: recordChannel("notes", vaultId) -> "notes:<vaultId>"++@main+struct NotesApp: App {+ // TODO(Phase 3): create SyncDriver + IosRelayTransport from the+ // XCFramework; register BGTaskScheduler handlers (see README.md).+ var body: some Scene {+ WindowGroup {+ NotesRootView()+ }+ }+}++struct NotesRootView: View {+ // TODO(Phase 3): note list driven by SyncDriver snapshots; editor binds+ // PKCanvasView and maps PKStroke -> InkStroke per README mapping table,+ // then serializes via serializeNoteBody in the XCFramework.+ var body: some View {+ Text("EverySync Notes")+ }+}
apple/Notes/README.md
diff --git a/apple/Notes/README.md b/apple/Notes/README.mdnew file mode 100644index 0000000000..8d8f074761--- /dev/null+++ b/apple/Notes/README.md@@ -0,0 +1,105 @@+# EverySync Notes — Apple shell (Phase 3a)++SwiftUI shell. **All merge / transport / crypto lives in the shared+XCFramework** (`everysync-core` KMP); this target renders the editor, maps+PencilKit strokes to the shared ink model, hosts the Share extension, and+schedules background sync. Zero sync logic in Swift.++## Architecture++```+NotesApp (SwiftUI, PencilKit canvas) ──► EverysyncCore.xcframework ──► relay+ │ │+ │ render + thin PencilKit mapping │ NoteBody parse/serialize,+ │ │ merge, transport, cursors+ ▼ ▼+Keychain (SecureStore) App-Group envelope IPC+BGTaskScheduler periodic (see ../IPC_CONTRACT.md)+Share extension Blob store (image bytes by fileName)+```++## KMP entry points this shell will call (nothing else)++| Kotlin FQN | Used for |+|---|---|+| `core.data.RemoteNote` | Envelope: `uid / title / content / blocksJson / position / deleted / updatedAt`. |+| `core.notes.parseNoteBody` / `serializeNoteBody` / `noteBodyText` | Blocks JSON ⇄ editor model; plain-text projection for search/preview/share. `ignoreUnknownKeys` keeps legacy notes parsing. |+| `core.notes.NoteBlock` (`Text`/`Image`/`Ink`), `InkStroke`, `InkPoint` | Canonical model. Swift never defines its own block schema. |+| `core.sync.adapters.NoteKind` | `syncId=uid`, LWW on `updatedAt`, hash over canonical JSON (identity/position/timestamps stripped; reorder is not an edit), `imageNames(blocksJson)` for blob prefetch. |+| `core.provider.SyncDriver` + `core.platform.RelayCursorStore` | Sync cycles; cursor keys `relay_cursor:<type>:<vault>:<channel>`. |+| `core.network` | `IosRelayTransport`; record channel `notes:<vaultId>` via `recordChannel`; blob channel `notes-blobs:<vaultId>` for image bytes (never inline in envelopes). |+| PQC / roles / links | Same surface as Passwords (see `../Passwords/README.md`); notes vaults may offer EDITOR or VIEWER. |++## Wire shape (mirrored verbatim — do not extend in Swift)++```json+{"blocks":[+ {"type":"text","id":"…","markdown":"…"},+ {"type":"image","id":"…","fileName":"<sha256>.jpg","widthFraction":1.0},+ {"type":"ink","id":"…","strokes":[],"heightDp":300}+]}+```++`InkStroke`: `brushFamily` (default `"pressurePen"`), `brushSize`, `brushColor`+(argb int), `brushEpsilon` (default `0.1`), `points: InkPoint[]`.+`InkPoint`: `x, y, timeMillis, pressure, tiltRadians, orientationRadians`.++## PencilKit → InkPoint mapping (thin platform layer, in Swift)++PencilKit has no shared counterpart, so the stroke converter lives here, but+it maps 1:1 onto `InkPoint`/`InkStroke` and performs no merge/hash/crypto:++| `PKStrokePoint` | `InkPoint` |+|---|---|+| `location.x / .y` | `x / y` |+| `timeOffset + stroke start` | `timeMillis` |+| `force` (fallback `size`) | `pressure` |+| `π/2 − altitude` | `tiltRadians` |+| `azimuth` | `orientationRadians` |++| `PKStroke` / `PKInk` | `InkStroke` |+|---|---|+| `ink.inkType` | `brushFamily` |+| `ink` line width | `brushSize` |+| `ink.color` → argb int | `brushColor` |+| constant | `brushEpsilon = 0.1` |++Serialization of the mapped strokes (`serializeNoteBody`) stays in the+XCFramework. Canvas height maps to the ink block's `heightDp` (default 300).++## Images++Image bytes ride the blob channel keyed by `fileName`; envelopes carry only+the name + `widthFraction`. Prefetch via `NoteKind.imageNames(blocksJson)`.++## Delete semantics — SOFT delete++Notes soft-delete: tombstone rows (`deleted=true`) persist locally and+propagate. `NoteKind.localDeletesAreAuthoritative == true`.+`SyncSink.delete` tombstones; never raw-deletes. See `../IPC_CONTRACT.md`.++## Share extension++Share-extension target receives text/URLs/images, converts to `NoteBlock`s via+the XCFramework parsers, and writes through the App-Group envelope IPC. It+never talks to the relay directly.++## Keychain / BGTaskScheduler++Same pattern as Passwords: KMP `SecureStore` actual = Keychain+`kSecClassGenericPassword`; `BGAppRefreshTaskRequest(identifier:+"com.vayunmathur.everysync.notes.refresh")` for periodic pulls, one-shot+processing task after local edits. Scheduling only.++## Info.plist / entitlements notes++- `com.apple.security.application-groups`: `group.<team>.everysync.shared` (envelope IPC + blob store).+- `keychain-access-groups`: `$(AppIdentifierPrefix)com.vayunmathur.everysync.notes`.+- `NSExtension` (`com.apple.share-services`) on the Share-extension target, sharing the App Group.+- No camera/photo-library keys in this shell (image blocks reference shared-store files; capture UI adds its own usage strings later).++## Swift must NOT++Parse/serialize blocks JSON by hand, compute content hashes, run merge/LWW,+encrypt envelopes, or invent block types. All of that is `NoteBlocks.kt` ++`NoteKind` in the XCFramework.
apple/Passwords/PasswordsApp.swift
diff --git a/apple/Passwords/PasswordsApp.swift b/apple/Passwords/PasswordsApp.swiftnew file mode 100644index 0000000000..1dc5d4aedd--- /dev/null+++ b/apple/Passwords/PasswordsApp.swift@@ -0,0 +1,67 @@+// EverySync Passwords — Phase 3a SwiftUI shell.+//+// Zero sync logic in Swift. All merge / transport / crypto lives in the+// shared XCFramework (everysync-core KMP). This file only declares the UI+// entry point, the Credential Provider host, and — in comments — the exact+// KMP entry points Phase 3 will call. Nothing here computes, merges,+// hashes, or encrypts.++import SwiftUI+import AuthenticationServices+import EverysyncCore++// MARK: - KMP entry points (Phase 3 wiring, for reference only)+//+// data: com.vayunmathur.everysync.core.data.RemotePassword+// merge: com.vayunmathur.everysync.core.passwords.mergeCredentials+// com.vayunmathur.everysync.core.passwords.passkeysFor+// com.vayunmathur.everysync.core.passwords.PasskeyLink+// com.vayunmathur.everysync.core.passwords.DomainMatch+// totp: com.vayunmathur.everysync.core.passwords.Totp.generate+// kind: com.vayunmathur.everysync.core.sync.adapters.PasswordKind+// driver: com.vayunmathur.everysync.core.provider.SyncDriver+// cursors: com.vayunmathur.everysync.core.platform.RelayCursorStore+// securestore: com.vayunmathur.everysync.core.platform.SecureStore (Keychain actual)+// transport: com.vayunmathur.everysync.core.network.IosRelayTransport+// channels: recordChannel("passwords", vaultId) -> "passwords:<vaultId>"+// roles: RelayRoles — passwords offer EDITOR only, never VIEWER+// links: RelayLinks.parseJoinLink / .shareLinkFor+// pqc: 10 fns per IOS_PQC_NOTES.md (e2eePqc cinterop)++@main+struct PasswordsApp: App {+ // TODO(Phase 3): create SyncDriver + IosRelayTransport from the+ // XCFramework; register BGTaskScheduler handlers (see README.md).+ var body: some Scene {+ WindowGroup {+ PasswordsRootView()+ }+ }+}++struct PasswordsRootView: View {+ // TODO(Phase 3): vault list driven by SyncDriver snapshots via+ // RelayCursorStore; rows rendered from RemotePassword envelopes.+ var body: some View {+ Text("EverySync Passwords")+ }+}++// MARK: - Credential Provider extension host++/// Autofill extension. Reads credentials over XPC from the containing app+/// (App-Group container + NSFileCoordinator); matching via XCFramework+/// `DomainMatch`. No Swift matching logic.+final class EverySyncCredentialProvider: ASCredentialProviderViewController {+ override func prepareCredentialList(for serviceIdentifiers: [ASCredentialServiceIdentifier]) {+ // TODO(Phase 3): query containing app over XPC, rank via DomainMatch.+ }++ override func provideCredentialWithoutUserInteraction(for credentialIdentity: ASPasswordCredentialIdentity) {+ // TODO(Phase 3): return the stored credential for this identity.+ }++ override func prepareInterfaceToProvideCredential(for credentialIdentity: ASPasswordCredentialIdentity) {+ // TODO(Phase 3): present confirmation UI, then provide the credential.+ }+}
apple/Passwords/README.md
diff --git a/apple/Passwords/README.md b/apple/Passwords/README.mdnew file mode 100644index 0000000000..0e4af11db5--- /dev/null+++ b/apple/Passwords/README.md@@ -0,0 +1,76 @@+# EverySync Passwords — Apple shell (Phase 3a)++SwiftUI shell. **All merge / transport / crypto lives in the shared+XCFramework** (`everysync-core` KMP); this target renders UI, talks Keychain,+hosts the Credential Provider extension, and schedules background sync. Zero+sync logic in Swift.++## Architecture++```+PasswordsApp (SwiftUI) ──► EverysyncCore.xcframework ──► relay+ │ │+ │ UI state only │ merge / TOTP / PQC /+ │ │ transport / cursors+ ▼ ▼+Keychain (SecureStore) App-Group envelope IPC+BGTaskScheduler periodic (see ../IPC_CONTRACT.md)+ASCredentialProvider ext.+```++## KMP entry points this shell will call (nothing else)++| Kotlin FQN | Used for |+|---|---|+| `core.data.RemotePassword` | Envelope JSON on `passwords:<vaultId>` (see `recordChannel`) |+| `core.passwords.mergeCredentials` / `passkeysFor` | List + detail pairing. Explicit `PasskeyLink` wins both directions; auto-match needs domain AND username agreement on exactly one candidate; ties stay standalone. Deterministic order `(creationTime, syncId)`. Swift never re-implements this. |+| `core.passwords.Totp.generate(secret, epochSecond)` | 6-digit codes. Base32 RFC 4648 (padding stripped, unknown chars ignored), 30 s step, big-endian counter, dynamic truncation. HMAC-SHA1 actual is `HmacIos` (CryptoKit `HMAC<Insecure.SHA1>`). Swift only passes `Date().epochSeconds`. |+| `core.passwords.DomainMatch` / `PasskeyLink` | Autofill candidate matching + explicit link/detach. |+| `core.sync.adapters.PasswordKind` | `syncId=uid`, LWW on `updatedAt`, `contentHash = relayContentHash(canonical + "\0deleted=…")`, `contentKey` password `name␀username` / passkey `rpId␀credentialId`. Only explicit `deleted=true` envelopes are deletes (`isTombstoneEnvelope`). |+| `core.provider.SyncDriver` + `core.platform.RelayCursorStore` | Sync cycles; cursor keys `relay_cursor:<type>:<vault>:<channel>`. |+| `core.network.IosRelayTransport` | Ktor-Darwin + trust pinning (lands Phase 3; stub today). Envelopes: `Base64(AES_GCM)` per item; invites PQC-sealed to `inbox:<deviceId>`. |+| `core.network.RelayRoles` | Passwords vaults offer **EDITOR only — never VIEWER** (read-only passwords still disclose every secret). |+| `core.network.RelayLinks` | `everysync://join/<vault>?owner=…&type=…` + `https://ma.vayunmathur.com/es/share#id=…&owner=…&type=…`. |+| PQC cinterop (`IOS_PQC_NOTES.md`) | Exactly 10 fns: `pqc_kem_keygen/encaps/decaps`, `pqc_dsa_keygen/sign/verify`, `pqc_bundle_build/split`, `pqc_free/secure_zero` via `e2eePqc.def`. Never `identity_keygen`, `link_*`, `security_code`. |++## Delete semantics — HARD delete++Passwords hard-delete: rows vanish locally; only the app-side snapshot+remembers them. `PasswordKind.localDeletesAreAuthoritative == false`, so a+healthy-read absence IS a genuine local delete. `SyncSink.delete` removes the+row; merge-driven deletes always arrive as tombstone envelopes, never raw+deletes. See `../IPC_CONTRACT.md`.++## Credential Provider extension++`ASCredentialProviderViewController` subclass (see `PasswordsApp.swift`) links+the same XCFramework and calls `DomainMatch` — no Swift matching logic. It+reads via XPC from the containing app (App-Group container ++`NSFileCoordinator`; the extension never touches the relay directly).++## Keychain SecureStore++KMP `SecureStore` actual = Keychain `kSecClassGenericPassword`.+Keychain group shared with the Credential Provider extension; vault AES keys+never user-visible (share links carry ids only; keys move via PQC-sealed+inbox invites).++## BGTaskScheduler++`BGAppRefreshTaskRequest(identifier: "com.vayunmathur.everysync.passwords.refresh")`+periodic pull → hands records to `SyncDriver`; one-shot+`BGProcessingTaskRequest` after local edits. Scheduling only — the cycle runs+in the XCFramework.++## Info.plist / entitlements notes++- `NSFaceIDUsageDescription` — vault unlock (no password material leaves Keychain).+- `com.apple.security.application-groups`: `group.<team>.everysync.shared` (envelope IPC).+- `keychain-access-groups`: `$(AppIdentifierPrefix)com.vayunmathur.everysync.passwords(.autofill)`.+- `com.apple.developer.authentication-services.autofill-credential-provider` = YES (extension target).++## Swift must NOT++Re-implement merge pairing, TOTP framing/math, canonical JSON/hash, envelope+Base64/AES, role checks, or link parsing. If logic exists in Swift that also+exists in `everysync-core`, delete the Swift copy.
desktop/notes/AGENTS.md
diff --git a/desktop/notes/AGENTS.md b/desktop/notes/AGENTS.mdnew file mode 100644index 0000000000..2b0fd953b2--- /dev/null+++ b/desktop/notes/AGENTS.md@@ -0,0 +1,42 @@+# AGENTS.md — desktop/notes/ (':desktop:notes')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `desktop/notes/` + `settings.gradle.kts` (append include only) plus+> read-only access to the shared contracts. Do NOT touch+> `library/everysync-core`, `todo/`, `notes/`, `desktop/passwords`, or Apple dirs.++- Gradle: :desktop:notes / dir: desktop/notes/+- Targets: JVM desktop only (applies `common-conventions-jvm`)+- Package: `com.vayunmathur.desktop.notes`+- Entry files: `Main.kt` (CLI), `NoteSync.kt` (driver), `NoteVault.kt`, `TodoView.kt`+- Deps: `:library:everysync-core` (merge, DTOs, `JvmRelayTransport`), kotlinx-serialization+- Metadata: none (desktop shells have none by design)+- Rust: no (PQC via core's JVM actual)++## Overview+**Purpose:** Phase 2b desktop Notes JVM shell on the shared core: syncs the+`notes:<vaultId>` + `todos:<vaultId>` relay channels once via `SyncDriver`+and prints counts. Windows renders todos inside the Notes UI+(`TodoView.todosAsNotes` projection, writes back via `updateTodoFromNote`).++**Key files**+- `NoteVault.kt` — `SyncSink<RemoteNote>` + `RelayStore<RemoteNote>` with+ SOFT-delete (tombstones persist; `listLocal` includes deleted).+- `TodoView.kt` — `SyncSink<RemoteTodo>` + `RelayStore<RemoteTodo>`, same+ tombstone semantics, plus the Windows todos-view projection.+- `NoteSync.kt` — drives both channels via `SyncDriver` + `JvmRelayTransport`;+ blob images by `fileName` via `BlobStore` (`notes-blobs:<vaultId>` LWW).+- `MarkdownBridge.kt` — `NoteBody` → markdown export (no Android deps).+- `Main.kt` — CLI: sync once, print counts.++**Invariants (from the shared core, preserved here):** failed pull = abort,+never empty; tombstone-only delete; reorder is not an edit+(`position` stripped from merge hashes); `notes`/`createdAt` persist verbatim+on todos (Phase 1 drift fix).++## Verify (this module only)+Do NOT run Gradle (per task scope). When enabled:+```+./gradlew :desktop:notes:compileKotlin+```+Files <350 lines, no Android imports.
desktop/notes/build.gradle.kts
diff --git a/desktop/notes/build.gradle.kts b/desktop/notes/build.gradle.ktsnew file mode 100644index 0000000000..61cc93532c--- /dev/null+++ b/desktop/notes/build.gradle.kts@@ -0,0 +1,13 @@+plugins {+ id("common-conventions-jvm")+ application+}++dependencies {+ implementation(project(":library:everysync-core"))+ implementation(libs.kotlinx.coroutines.core)+}++application {+ mainClass.set("com.vayunmathur.desktop.notes.MainKt")+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/Main.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/Main.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/Main.ktnew file mode 100644index 0000000000..d9e3695073--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/Main.kt@@ -0,0 +1,58 @@+package com.vayunmathur.desktop.notes++import com.vayunmathur.everysync.core.network.JvmRelayTransport+import com.vayunmathur.everysync.core.platform.MemorySecureStore+import java.io.File+import kotlin.io.encoding.Base64+import kotlinx.coroutines.runBlocking++/**+ * Desktop Notes JVM shell entry point (Phase 2b).+ *+ * Syncs the notes channel (`notes:<vaultId>`) and the todos channel+ * (`todos:<vaultId>`) once through the shared [NoteSync] driver, then prints+ * counts. The Windows todos-view ([TodoView.todosAsNotes]) renders inside the+ * Notes UI; writes flow back through the same todos channel.+ *+ * Usage: `:desktop:notes:run --args="<vaultId> <vaultKeyB64> [dataDir]"`+ *+ * Vault-key note: takes the epoch-0 vault key as base64 (same bytes the+ * Android `TokenStore` holds pre-wrap). Roster/epoch resolution is future+ * work — rotated shared vaults need it before this shell can read them.+ */+fun main(args: Array<String>) {+ if (args.size < 2) {+ println("usage: desktop-notes <vaultId> <vaultKeyB64> [dataDir]")+ return+ }+ val vaultId = args[0]+ val vaultKey = runCatching { Base64.decode(args[1]) }.getOrNull()+ if (vaultKey == null || vaultKey.isEmpty()) {+ println("error: vaultKeyB64 is not valid base64")+ return+ }+ val dataDir = File(args.getOrElse(2) { defaultDataDir() }).apply { mkdirs() }+ val result = runBlocking {+ val transport = JvmRelayTransport(MemorySecureStore())+ if (!transport.init()) {+ println("error: relay unavailable (register failed)")+ return@runBlocking null+ }+ val sync = NoteSync(transport, dataDir, FileBlobStore(dataDir, vaultId))+ sync.syncOnce(vaultId, vaultKey)+ }+ if (result == null) return+ println("notes: ok=${result.notes.ok} local=${result.notes.localCount}")+ println("todos: ok=${result.todos.ok} local=${result.todos.localCount} view=${result.todosViewCount}")+ val blobs = result.blobs+ if (blobs == null) {+ println("blobs: no store wired (TODO)")+ } else {+ println("blobs: ok=${blobs.ok} pulled=${blobs.pulled} pushed=${blobs.pushed} deleted=${blobs.deleted}")+ }+}++private fun defaultDataDir(): String {+ val home = System.getProperty("user.home") ?: "."+ return File(File(home, ".everysync"), "notes").absolutePath+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/MarkdownBridge.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/MarkdownBridge.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/MarkdownBridge.ktnew file mode 100644index 0000000000..68c5618f7f--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/MarkdownBridge.kt@@ -0,0 +1,53 @@+package com.vayunmathur.desktop.notes++import com.vayunmathur.everysync.core.data.RemoteNote+import com.vayunmathur.everysync.core.notes.NoteBlock+import com.vayunmathur.everysync.core.notes.noteBodyText+import com.vayunmathur.everysync.core.notes.parseNoteBody++/**+ * JVM export of a note body to Markdown, mirroring Android+ * `NoteMarkdownExporter` minus the Android-only parts.+ *+ * - Text blocks emit verbatim (via the shared [noteBodyText] equivalent —+ * the same plain-text projection used for search/previews/sharing).+ * - Image blocks emit a `` reference; bytes stay in the+ * [BlobStore] keyed by `fileName` and are never inlined (no base64 data+ * URIs here — the desktop shell has no downscaler yet).+ * - Ink blocks emit a one-line placeholder with the stroke count (no SVG+ * rasterizer on the JVM yet).+ *+ * Export-only: the stored `blocksJson` stays the source of truth; this never+ * touches storage. No Android imports (`Bitmap`, `Context`, `FileProvider`).+ */+object MarkdownBridge {++ /** Full markdown document for [note]: title heading + body blocks. */+ fun exportNote(+ note: RemoteNote,+ imageMarkdown: (fileName: String) -> String = { fileName -> "" },+ ): String {+ val body = parseNoteBody(note.blocksJson, note.content)+ val parts = body.blocks.map { block ->+ when (block) {+ is NoteBlock.Text -> block.markdown+ is NoteBlock.Image -> imageMarkdown(block.fileName)+ is NoteBlock.Ink -> inkPlaceholder(block)+ }+ }.filter { it.isNotBlank() }+ val title = note.title.ifBlank { "Untitled" }+ return (listOf("# $title") + parts).joinToString("\n\n").trim() + "\n"+ }++ /** Plain-text projection (search, previews, list rows). */+ fun plainText(note: RemoteNote): String {+ if (note.blocksJson.isNullOrBlank()) return note.content.trim()+ return noteBodyText(parseNoteBody(note.blocksJson, note.content))+ }++ private fun inkPlaceholder(block: NoteBlock.Ink): String {+ val strokes = block.strokes.size+ val points = block.strokes.sumOf { it.points.size }+ return "_[handwriting: $strokes stroke(s), $points point(s)]_"+ }+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteSync.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteSync.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteSync.ktnew file mode 100644index 0000000000..97d16b1879--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteSync.kt@@ -0,0 +1,207 @@+package com.vayunmathur.desktop.notes++import com.vayunmathur.everysync.core.data.RemoteNote+import com.vayunmathur.everysync.core.network.RelayTransport+import com.vayunmathur.everysync.core.network.appendRecords+import com.vayunmathur.everysync.core.network.blobChannel+import com.vayunmathur.everysync.core.network.pullRecords+import com.vayunmathur.everysync.core.network.recordChannel+import com.vayunmathur.everysync.core.provider.SyncDriver+import com.vayunmathur.everysync.core.sync.EntityKind+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.NoteKind+import com.vayunmathur.everysync.core.sync.adapters.TodoKind+import java.io.File+import java.security.MessageDigest+import kotlin.io.encoding.Base64+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Image bytes by file name. Note bodies ([RemoteNote]) reference images by+ * `fileName` only; the bytes ride the `notes-blobs:<vaultId>` side channel so+ * the record log stays small and mergeable (mirrors Android `RelayBlobStore`).+ */+interface BlobStore {+ fun read(name: String): ByteArray?+ fun write(name: String, bytes: ByteArray)+ fun delete(name: String)+}++/** [BlobStore] over `dataDir/blobs/<vaultId>/<name>` (JVM files, no Android). */+class FileBlobStore(dataDir: File, vaultId: String) : BlobStore {+ private val dir = File(File(dataDir, "blobs"), vaultId).apply { mkdirs() }++ override fun read(name: String): ByteArray? {+ val f = File(dir, name)+ return if (f.isFile) runCatching { f.readBytes() }.getOrNull() else null+ }++ override fun write(name: String, bytes: ByteArray) {+ runCatching { File(dir, name).writeBytes(bytes) }+ }++ override fun delete(name: String) {+ runCatching { File(dir, name).delete() }+ }+}++/**+ * Drives the notes + todos channels through the shared [SyncDriver] over the+ * shared [RelayTransport] (JVM: [com.vayunmathur.everysync.core.network.JvmRelayTransport]).+ *+ * Per-channel cycle (mirrors `E2eeProvider.driveMerge`):+ * 1. Fold the FULL decrypted record log from 0 (tombstones included — full+ * state, never a delta, so absence vs deletion stays decidable).+ * 2. A failed pull (null) or a fully-undecryptable log aborts the channel+ * with zero writes — never merge a failure as empty.+ * 3. [SyncDriver.drive] merges against the sink's full local state ++ * baseline, appends `remoteOut` BEFORE persisting locally, then applies+ * the local half.+ *+ * Blob sync is last-writer-wins per file name (latest [BlobEnvelope.updatedAt]+ * wins; remote wins on differing bytes; referenced-but-absent uploads). A+ * real UI would track local mtimes for finer conflicts — the shell keeps the+ * simple rule and documents it.+ *+ * Vault-key note: the caller supplies the epoch-0 vault key directly. Roster+ * / key-epoch / ownership resolution (`VaultRoster`, `VaultKeys`,+ * `OwnerTransfer`) is future work for the desktop shell — shared vaults that+ * rotated keys need that before this shell can read them.+ */+class NoteSync(+ private val transport: RelayTransport,+ private val dataDir: File,+ private val blobStore: BlobStore? = null,+) {+ data class ChannelResult(val ok: Boolean, val localCount: Int)+ data class BlobResult(val ok: Boolean, val pulled: Int, val pushed: Int, val deleted: Int)+ data class SyncResult(+ val notes: ChannelResult,+ val todos: ChannelResult,+ val todosViewCount: Int,+ val blobs: BlobResult?,+ )++ private val blobJson = Json { ignoreUnknownKeys = true }++ suspend fun syncOnce(vaultId: String, vaultKey: ByteArray): SyncResult {+ val notes = NoteVault(dataDir, vaultId)+ val todos = TodoView(dataDir, vaultId)+ val now = System.currentTimeMillis()+ val notesOk = syncChannel(NoteKind, notes, recordChannel("notes", vaultId), vaultKey, now)+ val todosOk = syncChannel(TodoKind, todos, TodoKind.channel(vaultId), vaultKey, now)+ val blobs = syncBlobs(vaultId, vaultKey, notes)+ return SyncResult(+ notes = ChannelResult(notesOk, notes.listLocal().size),+ todos = ChannelResult(todosOk, todos.listLocal().size),+ todosViewCount = todos.todosAsNotes().size,+ blobs = blobs,+ )+ }++ private suspend fun <T> syncChannel(+ kind: EntityKind<T>,+ store: RelayStore<T>,+ channel: String,+ key: ByteArray,+ now: Long,+ ): Boolean {+ val pulled = transport.pullRecords(channel, key, 0) ?: return false+ if (pulled.fullyUndecryptable) return false+ val remote = pulled.items.mapNotNull { store.parseRemote(it) }+ return SyncDriver.drive(+ kind = kind,+ store = store,+ remoteEntities = remote,+ appendRemote = { items -> transport.appendRecords(channel, key, items) != null },+ now = now,+ )+ }++ /**+ * Blob side-channel sync. Returns null when no [BlobStore] is wired —+ * TODO: default the CLI to [FileBlobStore] so images follow notes.+ */+ private suspend fun syncBlobs(+ vaultId: String,+ vaultKey: ByteArray,+ notes: NoteVault,+ ): BlobResult? {+ val store = blobStore ?: return null+ val channel = blobChannel(vaultId)+ val pulled = transport.pullRecords(channel, vaultKey, 0)+ ?: return BlobResult(ok = false, pulled = 0, pushed = 0, deleted = 0)+ if (pulled.fullyUndecryptable) {+ return BlobResult(ok = false, pulled = 0, pushed = 0, deleted = 0)+ }+ // Fold to latest envelope per name (LWW by updatedAt).+ val remoteByName = LinkedHashMap<String, BlobEnvelope>()+ for (raw in pulled.items) {+ val env = decodeBlob(raw) ?: continue+ if (env.name.isBlank()) continue+ val prev = remoteByName[env.name]+ if (prev == null || env.updatedAt >= prev.updatedAt) remoteByName[env.name] = env+ }+ var pulledCount = 0+ var deletedCount = 0+ for ((name, env) in remoteByName) {+ if (env.deleted) {+ if (store.read(name) != null) {+ store.delete(name)+ deletedCount+++ }+ continue+ }+ val bytes = runCatching { Base64.decode(env.bytesB64) }.getOrNull() ?: continue+ val local = store.read(name)+ if (local == null || sha256Hex(local) != env.sha256) {+ store.write(name, bytes)+ pulledCount+++ }+ }+ // Push images local notes reference but the relay has never seen.+ val referenced = notes.listLocal()+ .flatMap { NoteKind.imageNames(it.blocksJson) }+ .distinct()+ var pushedCount = 0+ val out = mutableListOf<String>()+ for (name in referenced) {+ if (name in remoteByName) continue+ val bytes = store.read(name) ?: continue+ out += blobJson.encodeToString(+ BlobEnvelope(name, sha256Hex(bytes), Base64.encode(bytes), System.currentTimeMillis()),+ )+ }+ if (out.isNotEmpty()) {+ if (transport.appendRecords(channel, vaultKey, out) == null) {+ return BlobResult(ok = false, pulled = pulledCount, pushed = 0, deleted = deletedCount)+ }+ pushedCount = out.size+ }+ return BlobResult(ok = true, pulled = pulledCount, pushed = pushedCount, deleted = deletedCount)+ }++ private fun decodeBlob(raw: String): BlobEnvelope? = runCatching {+ blobJson.decodeFromString<BlobEnvelope>(raw)+ }.getOrNull()++ private fun sha256Hex(bytes: ByteArray): String {+ val digest = MessageDigest.getInstance("SHA-256")+ return digest.digest(bytes).joinToString("") { "%02x".format(it) }+ }++ /**+ * Blob envelope, field-for-field compatible with Android+ * `RelayBlobStore.BlobEnvelope` (same channel, same vault key, same JSON).+ */+ @Serializable+ private data class BlobEnvelope(+ val name: String,+ val sha256: String = "",+ val bytesB64: String = "",+ val updatedAt: Long = 0L,+ val deleted: Boolean = false,+ )+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteVault.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteVault.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteVault.ktnew file mode 100644index 0000000000..6f189de285--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/NoteVault.kt@@ -0,0 +1,222 @@+package com.vayunmathur.desktop.notes++import com.vayunmathur.everysync.core.data.RemoteNote+import com.vayunmathur.everysync.core.platform.LocalChange+import com.vayunmathur.everysync.core.platform.SyncSink+import com.vayunmathur.everysync.core.sync.LocalReadException+import com.vayunmathur.everysync.core.sync.RelaySnapshot+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.NoteKind+import java.io.File+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * JVM mirror of the notes `RelayNoteProvider` relay semantics, in-process.+ *+ * Column/op semantics preserved verbatim from `RelayNoteProvider`:+ * - `querySince` → [localChanges]: rows with `updatedAt` past `since`,+ * tombstones included.+ * - `upsertRaw` → [upsert]: idempotent on the relay sync identity+ * ([RemoteNote.uid]); pulled `updatedAt` timestamps are preserved verbatim+ * so LWW stays comparable across sides.+ * - single delete → [delete]: tombstones the row so the deletion propagates+ * via the next [localChanges] read.+ * - `deleteByVault` → [purge]: drops every row *and* its snapshots.+ *+ * Soft-delete rule (tombstone-only delete): delete paths NEVER hard-remove a+ * live row. Tombstones persist in [listLocal] output so the merge can tell "we+ * deleted this" apart from "we never saw this" — an id absent WITHOUT a+ * tombstone is a missed read, never a delete (see+ * `EntityKind.localDeletesAreAuthoritative`, which holds for notes). Only+ * [RelayStore.deleteLocal] hard-removes, and only for ids the merge already+ * proved fully acknowledged on both sides.+ *+ * Reorder-is-not-edit: [RemoteNote.position] is stripped from the merge hash+ * (see `NoteKind.canonical`), so this store persists position verbatim and+ * never bumps `updatedAt` for a pure reorder.+ */+class NoteVault(+ private val dataDir: File,+ private val vaultId: String,+) : SyncSink<RemoteNote>, RelayStore<RemoteNote> {++ private val storeFile: File get() = File(dataDir, "notes-$vaultId.json")+ private val snapshotFile: File get() = File(dataDir, "snapshots-note-$vaultId.tsv")+ private val rows = LinkedHashMap<String, RemoteNote>()+ private val snapshots = LinkedHashMap<String, RelaySnapshot>()+ private val mutex = Mutex()+ private val json = Json { ignoreUnknownKeys = true }++ @Volatile private var lastReadOk: Boolean = true++ // --- SyncSink (provider-shaped surface) ---++ /**+ * Full local state, tombstones included. A failed read surfaces as a+ * thrown [LocalReadException] (never an empty list): merging a read+ * failure as empty would delete every baseline-present relay record.+ */+ override suspend fun listLocal(vaultId: String): List<RemoteNote> = mutex.withLock {+ loadLocked()+ lastReadOk = true+ rows.values.toList()+ }++ override val listLocalOk: Boolean get() = lastReadOk++ /** `querySince` semantics: rows past [since], tombstones included. */+ override suspend fun localChanges(vaultId: String, since: Long): List<LocalChange<RemoteNote>> =+ mutex.withLock {+ loadLocked()+ rows.values.filter { it.updatedAt > since }.map {+ LocalChange(it.uid, it.updatedAt, it.deleted, it)+ }+ }++ /**+ * `upsertRaw` semantics: idempotent upsert keyed on the relay sync+ * identity, preserving the pulled `updatedAt`. A payload with+ * `deleted = true` tombstones the row instead of removing it.+ */+ override suspend fun upsert(vaultId: String, item: RemoteNote) {+ if (item.uid.isBlank()) return+ mutex.withLock {+ loadLocked()+ rows[item.uid] = item+ saveLocked()+ }+ }++ /**+ * Single-delete semantics: tombstones the row (soft-delete). The tombstone+ * survives in [listLocal] until the merge proves both sides acknowledged+ * it. Merge-driven pulled tombstones ALWAYS arrive here as+ * `deleted = true` envelopes via [upsert], never as raw deletes.+ */+ override suspend fun delete(vaultId: String, syncId: String) {+ mutex.withLock {+ loadLocked()+ val existing = rows[syncId] ?: return+ rows[syncId] = NoteKind.withUpdatedAt(+ NoteKind.withDeleted(existing, true),+ maxOf(existing.updatedAt, System.currentTimeMillis()),+ )+ saveLocked()+ }+ }++ /** `deleteByVault` semantics: drops every row *and* its snapshots. */+ override suspend fun purge(vaultId: String) {+ mutex.withLock {+ rows.clear()+ snapshots.clear()+ storeFile.delete()+ snapshotFile.delete()+ }+ }++ // --- RelayStore (merge-driver surface) ---++ override suspend fun listLocal(): List<RemoteNote> = listLocal(vaultId)++ override suspend fun upsertLocal(items: List<RemoteNote>) {+ for (item in items) upsert(vaultId, item)+ }++ /**+ * Merge-confirmed removals only: every id here carries a baseline proving+ * both sides acknowledged the tombstone, so hard-removal is safe. Live+ * rows are NEVER removed through any other path.+ */+ override suspend fun deleteLocal(items: List<RemoteNote>) {+ mutex.withLock {+ loadLocked()+ for (item in items) rows.remove(item.uid)+ saveLocked()+ }+ }++ override suspend fun loadBaseline(): Map<String, RelaySnapshot> = mutex.withLock {+ loadSnapshotsLocked()+ snapshots.toMap()+ }++ override suspend fun saveSnapshots(snapshots: List<RelaySnapshot>) {+ mutex.withLock {+ loadSnapshotsLocked()+ for (s in snapshots) this.snapshots[s.syncId] = s+ saveSnapshotsLocked()+ }+ }++ override suspend fun removeSnapshots(syncIds: List<String>) {+ mutex.withLock {+ loadSnapshotsLocked()+ for (id in syncIds) snapshots.remove(id)+ saveSnapshotsLocked()+ }+ }++ override fun parseRemote(json: String): RemoteNote? =+ NoteKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }++ override fun serializeForRemote(entity: RemoteNote): String = NoteKind.toJson(entity)++ // --- File persistence (JSON rows, TSV snapshots) ---++ private fun loadLocked() {+ val file = storeFile+ if (!file.isFile) return+ try {+ val decoded = json.decodeFromString<List<RemoteNote>>(file.readText())+ rows.clear()+ for (note in decoded) {+ if (note.uid.isNotBlank()) rows[note.uid] = note+ }+ lastReadOk = true+ } catch (_: Exception) {+ lastReadOk = false+ throw LocalReadException("NoteVault read failed for $vaultId")+ }+ }++ private fun saveLocked() {+ dataDir.mkdirs()+ storeFile.writeText(json.encodeToString(rows.values.toList()))+ }++ private fun loadSnapshotsLocked() {+ val file = snapshotFile+ if (!file.isFile) return+ snapshots.clear()+ for (line in file.readLines()) {+ val parts = line.split("\t")+ if (parts.size != 7) continue+ snapshots[parts[0]] = RelaySnapshot(+ syncId = parts[0],+ kind = parts[1],+ contentHash = parts[2],+ localUpdatedAt = parts[3].toLongOrNull() ?: 0L,+ remoteModified = parts[4].toLongOrNull() ?: 0L,+ lastSyncedAt = parts[5].toLongOrNull() ?: 0L,+ deleted = parts[6] == "1",+ )+ }+ }++ private fun saveSnapshotsLocked() {+ dataDir.mkdirs()+ snapshotFile.writeText(+ snapshots.values.joinToString("\n") {+ listOf(+ it.syncId, it.kind, it.contentHash,+ it.localUpdatedAt.toString(), it.remoteModified.toString(),+ it.lastSyncedAt.toString(), if (it.deleted) "1" else "0",+ ).joinToString("\t")+ },+ )+ }+}
desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/TodoView.kt
diff --git a/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/TodoView.kt b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/TodoView.ktnew file mode 100644index 0000000000..787f6ea721--- /dev/null+++ b/desktop/notes/src/main/kotlin/com/vayunmathur/desktop/notes/TodoView.kt@@ -0,0 +1,298 @@+package com.vayunmathur.desktop.notes++import com.vayunmathur.everysync.core.data.RemoteNote+import com.vayunmathur.everysync.core.data.RemoteTodo+import com.vayunmathur.everysync.core.platform.LocalChange+import com.vayunmathur.everysync.core.platform.SyncSink+import com.vayunmathur.everysync.core.sync.LocalReadException+import com.vayunmathur.everysync.core.sync.RelaySnapshot+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.TodoKind+import java.io.File+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * JVM mirror of the todo `RelayTodoProvider` relay semantics, in-process,+ * plus the Windows todos-view projection into the Notes UI.+ *+ * Column/op semantics preserved verbatim from `RelayTodoProvider`:+ * - `querySince` → [localChanges]: rows with `updatedAt` past `since`,+ * tombstones included.+ * - `upsertRaw` → [upsert]: idempotent on the relay sync identity+ * ([RemoteTodo.uid]); pulled `updatedAt` preserved verbatim for LWW.+ * - single delete → [delete]: tombstones the row for propagation.+ * - `deleteByVault` → [purge]: drops every row *and* its snapshots.+ *+ * Soft-delete rule (tombstone-only delete): identical to [NoteVault] — delete+ * paths tombstone, never hard-remove; tombstones persist in [listLocal] so+ * absence-without-tombstone is a missed read, never a delete (see+ * `EntityKind.localDeletesAreAuthoritative`, which holds for todos). Only+ * [RelayStore.deleteLocal] hard-removes, for merge-acknowledged ids only.+ *+ * Reorder-is-not-edit: [RemoteTodo.position] is stripped from the merge hash+ * (see `TodoKind.canonical`), so position persists verbatim and a pure+ * reorder never bumps `updatedAt`.+ *+ * Phase 1 drift note: [RemoteTodo.notes] and [RemoteTodo.createdAt] are part+ * of the envelope AND the merge hash (see `TodoKind.canonical`) — this store+ * persists both verbatim, so LWW on those fields converges locally.+ *+ * Windows todos-view: on Windows there is no system task provider, so the+ * Notes shell renders the `todos:<vaultId>` channel inside the Notes UI via+ * [todosAsNotes]. Each non-deleted todo projects to one read-model+ * [RemoteNote] (uid namespaced `"todo:<uid>"`, title = task title, content =+ * [RemoteTodo.notes] with a done/due header line). This is a PROJECTION, not+ * a second copy: edits write back through [updateTodoFromNote], which parses+ * the projection back onto the SAME `todos:<vaultId>` channel row. Deleted+ * todos project to nothing (their tombstone stays on the todos channel).+ *+ * Linux future: a real task provider exists on Linux (EDS via libecal). When+ * a libecal JVM binding lands, replace the projection with a two-way EDS+ * adapter behind this same [SyncSink] surface; the relay channel and+ * tombstone semantics stay unchanged.+ */+class TodoView(+ private val dataDir: File,+ private val vaultId: String,+) : SyncSink<RemoteTodo>, RelayStore<RemoteTodo> {++ private val storeFile: File get() = File(dataDir, "todos-$vaultId.json")+ private val snapshotFile: File get() = File(dataDir, "snapshots-todo-$vaultId.tsv")+ private val rows = LinkedHashMap<String, RemoteTodo>()+ private val snapshots = LinkedHashMap<String, RelaySnapshot>()+ private val mutex = Mutex()+ private val json = Json { ignoreUnknownKeys = true }++ @Volatile private var lastReadOk: Boolean = true++ // --- SyncSink (provider-shaped surface) ---++ /**+ * Full local state, tombstones included. Failed reads throw+ * [LocalReadException], never an empty list (see [NoteVault.listLocal]).+ */+ override suspend fun listLocal(vaultId: String): List<RemoteTodo> = mutex.withLock {+ loadLocked()+ lastReadOk = true+ rows.values.toList()+ }++ override val listLocalOk: Boolean get() = lastReadOk++ /** `querySince` semantics: rows past [since], tombstones included. */+ override suspend fun localChanges(vaultId: String, since: Long): List<LocalChange<RemoteTodo>> =+ mutex.withLock {+ loadLocked()+ rows.values.filter { it.updatedAt > since }.map {+ LocalChange(it.uid, it.updatedAt, it.deleted, it)+ }+ }++ /**+ * `upsertRaw` semantics: idempotent on [RemoteTodo.uid], preserving the+ * pulled `updatedAt`. `deleted = true` tombstones instead of removing.+ */+ override suspend fun upsert(vaultId: String, item: RemoteTodo) {+ if (item.uid.isBlank()) return+ mutex.withLock {+ loadLocked()+ rows[item.uid] = item+ saveLocked()+ }+ }++ /**+ * Single-delete semantics: tombstones the row. Pulled tombstones arrive+ * via [upsert] as `deleted = true` envelopes, never as raw deletes.+ */+ override suspend fun delete(vaultId: String, syncId: String) {+ mutex.withLock {+ loadLocked()+ val existing = rows[syncId] ?: return+ rows[syncId] = TodoKind.withUpdatedAt(+ TodoKind.withDeleted(existing, true),+ maxOf(existing.updatedAt, System.currentTimeMillis()),+ )+ saveLocked()+ }+ }++ /** `deleteByVault` semantics: drops every row *and* its snapshots. */+ override suspend fun purge(vaultId: String) {+ mutex.withLock {+ rows.clear()+ snapshots.clear()+ storeFile.delete()+ snapshotFile.delete()+ }+ }++ // --- Windows todos-view projection (render todos inside Notes UI) ---++ /**+ * Read-model projection of the todos channel as notes for the Windows+ * Notes UI. Live (non-deleted) todos only; tombstones project to nothing.+ * The uid is namespaced `"todo:<uid>"` so projected rows never collide+ * with real note uids.+ */+ suspend fun todosAsNotes(): List<RemoteNote> = mutex.withLock {+ loadLocked()+ rows.values.filter { !it.deleted }.sortedBy { it.position }.map { it.asNote() }+ }++ /**+ * Writes a projection edit back onto the SAME todos-channel row:+ * re-parses the note body into ([RemoteTodo.title], [RemoteTodo.notes])+ * and upserts the todo with a fresh local `updatedAt`. Unknown+ * (non-projected) note uids are ignored — real notes go through+ * [NoteVault], never here.+ */+ suspend fun updateTodoFromNote(note: RemoteNote) {+ val uid = note.uid.removePrefix(TODO_NOTE_PREFIX)+ if (uid == note.uid) return+ mutex.withLock {+ loadLocked()+ val existing = rows[uid] ?: return+ val (title, notes) = splitProjection(note)+ rows[uid] = existing.copy(+ title = title,+ notes = notes,+ updatedAt = maxOf(existing.updatedAt, System.currentTimeMillis()),+ )+ saveLocked()+ }+ }++ // --- RelayStore (merge-driver surface) ---++ override suspend fun listLocal(): List<RemoteTodo> = listLocal(vaultId)++ override suspend fun upsertLocal(items: List<RemoteTodo>) {+ for (item in items) upsert(vaultId, item)+ }++ /**+ * Merge-confirmed removals only (see [NoteVault.deleteLocal]): every id+ * here is baseline-proved acknowledged on both sides.+ */+ override suspend fun deleteLocal(items: List<RemoteTodo>) {+ mutex.withLock {+ loadLocked()+ for (item in items) rows.remove(item.uid)+ saveLocked()+ }+ }++ override suspend fun loadBaseline(): Map<String, RelaySnapshot> = mutex.withLock {+ loadSnapshotsLocked()+ snapshots.toMap()+ }++ override suspend fun saveSnapshots(snapshots: List<RelaySnapshot>) {+ mutex.withLock {+ loadSnapshotsLocked()+ for (s in snapshots) this.snapshots[s.syncId] = s+ saveSnapshotsLocked()+ }+ }++ override suspend fun removeSnapshots(syncIds: List<String>) {+ mutex.withLock {+ loadSnapshotsLocked()+ for (id in syncIds) snapshots.remove(id)+ saveSnapshotsLocked()+ }+ }++ override fun parseRemote(json: String): RemoteTodo? =+ TodoKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }++ override fun serializeForRemote(entity: RemoteTodo): String = TodoKind.toJson(entity)++ // --- File persistence ---++ private fun loadLocked() {+ val file = storeFile+ if (!file.isFile) return+ try {+ val decoded = json.decodeFromString<List<RemoteTodo>>(file.readText())+ rows.clear()+ for (todo in decoded) {+ if (todo.uid.isNotBlank()) rows[todo.uid] = todo+ }+ lastReadOk = true+ } catch (_: Exception) {+ lastReadOk = false+ throw LocalReadException("TodoView read failed for $vaultId")+ }+ }++ private fun saveLocked() {+ dataDir.mkdirs()+ storeFile.writeText(json.encodeToString(rows.values.toList()))+ }++ private fun loadSnapshotsLocked() {+ val file = snapshotFile+ if (!file.isFile) return+ snapshots.clear()+ for (line in file.readLines()) {+ val parts = line.split("\t")+ if (parts.size != 7) continue+ snapshots[parts[0]] = RelaySnapshot(+ syncId = parts[0],+ kind = parts[1],+ contentHash = parts[2],+ localUpdatedAt = parts[3].toLongOrNull() ?: 0L,+ remoteModified = parts[4].toLongOrNull() ?: 0L,+ lastSyncedAt = parts[5].toLongOrNull() ?: 0L,+ deleted = parts[6] == "1",+ )+ }+ }++ private fun saveSnapshotsLocked() {+ dataDir.mkdirs()+ snapshotFile.writeText(+ snapshots.values.joinToString("\n") {+ listOf(+ it.syncId, it.kind, it.contentHash,+ it.localUpdatedAt.toString(), it.remoteModified.toString(),+ it.lastSyncedAt.toString(), if (it.deleted) "1" else "0",+ ).joinToString("\t")+ },+ )+ }++ companion object {+ const val TODO_NOTE_PREFIX = "todo:"++ private fun RemoteTodo.asNote(): RemoteNote {+ val header = buildString {+ if (done) append("[done]") else append("[todo]")+ dueAt?.let { append(" due=$it") }+ }+ val body = if (notes.isBlank()) header else "$header\n\n$notes"+ return RemoteNote(+ uid = TODO_NOTE_PREFIX + uid,+ title = title,+ content = body,+ position = position,+ updatedAt = updatedAt,+ )+ }++ private fun splitProjection(note: RemoteNote): Pair<String, String> {+ val lines = note.content.lines()+ val body = if (lines.isNotEmpty() && lines[0].startsWith("[")) {+ lines.drop(1).joinToString("\n").trimStart('\n')+ } else {+ note.content+ }+ return note.title to body+ }+ }+}
desktop/passwords/AGENTS.md
diff --git a/desktop/passwords/AGENTS.md b/desktop/passwords/AGENTS.mdnew file mode 100644index 0000000000..9227c1982b--- /dev/null+++ b/desktop/passwords/AGENTS.md@@ -0,0 +1,38 @@+# AGENTS.md — desktop/passwords/ (':desktop:passwords')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `desktop/passwords/` + allowed shared modules. Do not root-scan.++<!-- last-reviewed: 2026-10-16 -->+- Gradle: :desktop:passwords / dir: desktop/passwords/+- Package roots present: com.vayunmathur.desktop.passwords (plain Kotlin, no Compose)+- Entry files: Main.kt, PasswordSync.kt, PasswordVault.kt, KdbxCompat.kt+- Deps: :library:everysync-core, kotlinx-serialization-json, okhttp, jna (all via catalog)+- Metadata: none (CLI shell, no app metadata)+- Rust: no (consumes e2ee_pqc host lib via core's JvmPqcCrypto) / screenshotTest: no++## Overview+**Purpose:** Desktop JVM shell on the shared EverySync core for the passwords vault (Phase 2a). Syncs `RemotePassword` records over `JvmRelayTransport` through the shared `SyncDriver` + `PasswordKind` merge. No Compose UI yet — UI lands after the core proves.+**Key features:**+- File-backed `PasswordVault` implementing core `SyncSink<RemotePassword>` with hard-delete semantics+- One-shot `PasswordSync.drive` via shared `SyncDriver` (null-pull aborts, never merges a failed pull)+- `KdbxCompat` KeePass-style CSV/JSON interchange using verbatim shared `EntryMapper` key names+- `Main.kt` CLI: init transport, sync once, print counts+**Architecture / data-flow:** `Main` (FileSecureStore + JvmRelayTransport.init) → `PasswordSync.syncOnce` (vault key load-or-create → pullRecords since 0 → fold → SyncDriver.drive → append) → `PasswordVault` (rows + `MemoryBaselineStore` snapshots on disk).+**Entry points + reading order:** `Main.kt` → `PasswordSync.kt` → `PasswordVault.kt` → `KdbxCompat.kt`.+**Gotchas:**+- Passwords HARD-delete: `listLocal` never returns deleted rows; `delete()` removes the row and keeps the baseline snapshot so the merge reads "baseline present + row absent" as a local delete. Only explicit `deleted=true` relay envelopes delete (see `PasswordKind`).+- Relay log is append-only: `syncOnce` folds the FULL log (last envelope per uid wins) before driving; a null pull aborts the cycle.+- `KdbxCompat` carries field maps only — no new crypto, no KDBX encryption. File protection stays out of scope.+- JVM-only module: no `Toast`, no `Icon`/`Scaffold`, no Compose, no Room strings.++## Key files+- com/vayunmathur/desktop/passwords/PasswordVault.kt — file JSON store + SyncSink with hard-delete rule+- com/vayunmathur/desktop/passwords/PasswordSync.kt — FileSecureStore, RelayStore adapter, syncOnce drive+- com/vayunmathur/desktop/passwords/KdbxCompat.kt — KeePassXC-compat field-map import/export+- com/vayunmathur/desktop/passwords/Main.kt — CLI entry (sync once, print counts)++## Verify (this module only)+```+./gradlew :desktop:passwords:compileKotlin+```+(Orchestrator verifies; do not run Gradle from this task.)
desktop/passwords/build.gradle.kts
diff --git a/desktop/passwords/build.gradle.kts b/desktop/passwords/build.gradle.ktsnew file mode 100644index 0000000000..a605784f87--- /dev/null+++ b/desktop/passwords/build.gradle.kts@@ -0,0 +1,16 @@+plugins {+ id("common-conventions-jvm")+ application+}++dependencies {+ implementation(project(":library:everysync-core"))+ implementation(libs.kotlinx.coroutines.core)+ implementation(libs.kotlinx.serialization.json)+ implementation(libs.okhttp)+ implementation(libs.jna)+}++application {+ mainClass.set("com.vayunmathur.desktop.passwords.MainKt")+}
desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/KdbxCompat.kt
diff --git a/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/KdbxCompat.kt b/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/KdbxCompat.ktnew file mode 100644index 0000000000..715ddb2b2f--- /dev/null+++ b/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/KdbxCompat.kt@@ -0,0 +1,201 @@+package com.vayunmathur.desktop.passwords++import com.vayunmathur.everysync.core.data.RemotePassword+import com.vayunmathur.everysync.core.passwords.EntryMapper+import java.util.Base64+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * KeePass-style CSV/JSON file-sync interchange using the shared core+ * [EntryMapper] field map, verbatim.+ *+ * KeePassXC-compat contract (no new crypto):+ * - Every key name below is exactly the shared [EntryMapper] key — including+ * the `_Type` / `_SyncId` / `_Modified` identity markers and the+ * `KPEX_PASSKEY_*` passkey half. Renaming any key here breaks the merge+ * hash comparison across sides, so keep names verbatim and import new keys+ * only by extending the shared mapper first.+ * - Only [EntryMapper.OWNED_KEYS] are written; foreign keys encountered on+ * import are carried through into the vault rows untouched.+ * - This layer carries field maps only — plaintext export with NO KDBX+ * encryption. File protection stays out of scope for Phase 2a.+ * - Tombstone imports (`_Tombstone = deleted` with a `_SyncId`) delete the+ * matching vault row; any other value under `_Tombstone` is live data.+ */+object KdbxCompat {+ private val json = Json { ignoreUnknownKeys = true; prettyPrint = true }++ // Verbatim KeePassXC-compat column names (shared EntryMapper keys).+ const val COL_TITLE = "Title"+ const val COL_USERNAME = "UserName"+ const val COL_EMAIL = "Email"+ const val COL_PASSWORD = "Password"+ const val COL_NOTES = "Notes"+ const val COL_URL = "URL"+ const val COL_WEBSITES = "Websites"+ const val COL_OTP = "otp"+ const val COL_TOTP_SEED = "TOTP Seed"++ /** KeePassXC CSV header order for the password half. */+ val CSV_HEADERS = listOf(COL_TITLE, COL_USERNAME, COL_EMAIL, COL_PASSWORD, COL_NOTES, COL_URL, COL_OTP)++ /** A vault row as a field map (KeePass entry shape). Foreign keys ride along. */+ fun toFields(entry: RemotePassword): Map<String, String> = buildMap {+ if (entry.isPasskey) {+ put(COL_TITLE, entry.rpName)+ put(COL_USERNAME, entry.userDisplayName)+ put(COL_URL, entry.rpId)+ put(EntryMapper.FIELD_TYPE, "passkey")+ put("KPEX_PASSKEY_USERNAME", entry.userName)+ put("KPEX_PASSKEY_PRIVATE_KEY_PEM", entry.privateKeyB64)+ put("KPEX_PASSKEY_CREDENTIAL_ID", entry.credentialId)+ put("KPEX_PASSKEY_USER_HANDLE", entry.userId)+ put("KPEX_PASSKEY_RELYING_PARTY", entry.rpId)+ entry.linkedPasswordSyncId?.takeIf { it.isNotBlank() }?.let {+ put("_LinkedPassword", it)+ }+ } else {+ put(COL_TITLE, entry.name)+ put(COL_USERNAME, entry.username)+ put(COL_EMAIL, entry.email)+ put(COL_PASSWORD, entry.password)+ put(COL_NOTES, entry.note)+ if (entry.websites.isNotEmpty()) {+ put(COL_URL, entry.websites.first())+ if (entry.websites.size > 1) put(COL_WEBSITES, entry.websites.joinToString("\n"))+ }+ entry.totpSecret?.takeIf { it.isNotBlank() }?.let {+ put(COL_OTP, "otpauth://totp/?secret=$it")+ }+ put(EntryMapper.FIELD_TYPE, "password")+ }+ put(EntryMapper.FIELD_SYNC_ID, entry.uid)+ put(EntryMapper.FIELD_MODIFIED, entry.updatedAt.toString())+ }++ /** Field map back to a vault row; null skips tombstones the caller already handled. */+ fun fromFields(fields: Map<String, String>, now: Long): RemotePassword? {+ if (EntryMapper.isTombstoneEntry(fields)) return null+ val syncId = fields[EntryMapper.FIELD_SYNC_ID].orEmpty()+ if (syncId.isBlank()) return null+ val updatedAt = fields[EntryMapper.FIELD_MODIFIED]?.toLongOrNull() ?: now+ return if (EntryMapper.isPasskeyEntry(fields)) {+ RemotePassword(+ uid = syncId,+ isPasskey = true,+ rpId = fields["KPEX_PASSKEY_RELYING_PARTY"].orEmpty().ifEmpty { fields[COL_URL].orEmpty() },+ rpName = fields[COL_TITLE].orEmpty(),+ credentialId = fields["KPEX_PASSKEY_CREDENTIAL_ID"].orEmpty(),+ userId = fields["KPEX_PASSKEY_USER_HANDLE"].orEmpty(),+ userName = fields["KPEX_PASSKEY_USERNAME"].orEmpty().ifEmpty { fields[COL_USERNAME].orEmpty() },+ userDisplayName = fields[COL_USERNAME].orEmpty(),+ privateKeyB64 = fields["KPEX_PASSKEY_PRIVATE_KEY_PEM"].orEmpty(),+ linkedPasswordSyncId = fields["_LinkedPassword"]?.takeIf { it.isNotBlank() },+ updatedAt = updatedAt,+ )+ } else {+ val websites = mutableListOf<String>()+ fields[COL_URL]?.takeIf { it.isNotEmpty() }?.let { websites.add(it) }+ fields[COL_WEBSITES]?.split("\n")?.filter { it.isNotBlank() }?.forEach {+ if (it !in websites) websites.add(it)+ }+ val otp = fields[COL_OTP]+ val totpSecret = if (!otp.isNullOrEmpty()) {+ Regex("[?&]secret=([^&]+)").find(otp)?.groupValues?.get(1) ?: otp+ } else {+ fields[COL_TOTP_SEED]?.takeIf { it.isNotBlank() }+ }+ RemotePassword(+ uid = syncId,+ name = fields[COL_TITLE].orEmpty(),+ username = fields[COL_USERNAME].orEmpty(),+ email = fields[COL_EMAIL].orEmpty(),+ password = fields[COL_PASSWORD].orEmpty(),+ note = fields[COL_NOTES].orEmpty(),+ totpSecret = totpSecret,+ websites = websites,+ updatedAt = updatedAt,+ )+ }+ }++ /** True when this imported map is an own-client deletion marker. */+ fun isTombstone(fields: Map<String, String>): Boolean = EntryMapper.isTombstoneEntry(fields)++ fun tombstoneSyncId(fields: Map<String, String>): String? =+ fields[EntryMapper.FIELD_SYNC_ID]?.takeIf { isTombstone(fields) }++ /** Exports rows as KeePassXC-compat CSV (password half columns; passkeys skipped). */+ fun exportCsv(entries: List<RemotePassword>): String {+ val sb = StringBuilder()+ sb.append(CSV_HEADERS.joinToString(",") { csvCell(it) }).append("\n")+ for (entry in entries.filter { !it.isPasskey }) {+ val fields = toFields(entry)+ sb.append(CSV_HEADERS.joinToString(",") { csvCell(fields[it].orEmpty()) }).append("\n")+ }+ return sb.toString()+ }++ /** Imports a KeePassXC-compat CSV into field maps keyed by column name. */+ fun importCsv(text: String): List<Map<String, String>> {+ val lines = text.lineSequence().filter { it.isNotBlank() }.toList()+ if (lines.isEmpty()) return emptyList()+ val headers = parseCsvLine(lines.first())+ return lines.drop(1).map { line ->+ val cells = parseCsvLine(line)+ headers.mapIndexed { idx, header -> header to (cells.getOrNull(idx).orEmpty()) }.toMap()+ }+ }++ /** Exports rows as a JSON array of field maps (passwords + passkeys). */+ fun exportJson(entries: List<RemotePassword>): String =+ json.encodeToString(entries.map { toFields(it) })++ /** Imports a JSON array of field maps (as produced by [exportJson]). */+ fun importJson(text: String): List<Map<String, String>> = runCatching {+ json.decodeFromString<List<Map<String, String>>>(text)+ }.getOrDefault(emptyList())++ private fun csvCell(value: String): String =+ if (value.any { it == ',' || it == '"' || it == '\n' }) {+ "\"" + value.replace("\"", "\"\"") + "\""+ } else {+ value+ }++ private fun parseCsvLine(line: String): List<String> {+ val out = mutableListOf<String>()+ val cur = StringBuilder()+ var inQuotes = false+ var i = 0+ while (i < line.length) {+ val c = line[i]+ when {+ inQuotes && c == '"' && line.getOrNull(i + 1) == '"' -> {+ cur.append('"')+ i += 2+ }+ c == '"' -> {+ inQuotes = !inQuotes+ i+++ }+ c == ',' && !inQuotes -> {+ out.add(cur.toString())+ cur.clear()+ i+++ }+ else -> {+ cur.append(c)+ i+++ }+ }+ }+ out.add(cur.toString())+ return out+ }++ /** JVM base64 (mirrors the Android helper's NO_WRAP form). */+ fun b64decode(raw: String): ByteArray =+ runCatching { Base64.getDecoder().decode(raw) }.getOrDefault(ByteArray(0))+}
desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/Main.kt
diff --git a/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/Main.kt b/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/Main.ktnew file mode 100644index 0000000000..a22c4fc38c--- /dev/null+++ b/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/Main.kt@@ -0,0 +1,59 @@+package com.vayunmathur.desktop.passwords++import java.io.File+import kotlin.io.encoding.Base64+import kotlinx.coroutines.runBlocking++/**+ * Desktop Passwords JVM shell entry point (Phase 2a).+ *+ * Syncs the passwords channel (`passwords:<vaultId>`) once through the+ * shared [PasswordSync] driver, then prints counts. No Compose UI yet — the+ * UI lands after the core proves.+ *+ * Usage: `:desktop:passwords:run --args="<vaultId> [vaultKeyB64] [dataDir]"`+ *+ * The vault key resolves as: explicit arg → `vault-<vaultId>.key` in the data+ * dir → fresh random key (saved for next run). Roster/epoch resolution is+ * future work — rotated shared vaults need it before this shell can read them.+ */+fun main(args: Array<String>) {+ if (args.isEmpty()) {+ println("usage: desktop-passwords <vaultId> [vaultKeyB64] [dataDir]")+ return+ }+ val vaultId = args[0]+ val dataDir = File(args.getOrElse(2) { defaultDataDir() }).apply { mkdirs() }+ val vaultKey = resolveVaultKey(args.getOrNull(1), dataDir, vaultId)+ if (vaultKey == null) {+ println("error: vaultKeyB64 is not valid base64")+ return+ }+ val result = runBlocking {+ val transport = PasswordSync.defaultTransport(FileSecureStore(dataDir))+ if (!transport.init()) {+ println("error: relay unavailable (register failed)")+ return@runBlocking null+ }+ PasswordSync(transport, dataDir).syncOnce(vaultId, vaultKey)+ }+ if (result == null) return+ println("passwords: ok=${result.ok} passwords=${result.passwords} passkeys=${result.passkeys}")+}++private fun resolveVaultKey(arg: String?, dataDir: File, vaultId: String): ByteArray? {+ if (arg != null) {+ if (arg.isBlank()) return null+ return runCatching { Base64.decode(arg) }.getOrNull()?.takeIf { it.isNotEmpty() }+ }+ VaultKeyFile.load(dataDir, vaultId)?.let { return it }+ val fresh = ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }+ VaultKeyFile.save(dataDir, vaultId, fresh)+ println("note: generated fresh vault key at ${VaultKeyFile.fileFor(dataDir, vaultId)}")+ return fresh+}++private fun defaultDataDir(): String {+ val home = System.getProperty("user.home") ?: "."+ return File(File(home, ".everysync"), "passwords").absolutePath+}
desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/PasswordSync.kt
diff --git a/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/PasswordSync.kt b/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/PasswordSync.ktnew file mode 100644index 0000000000..692ee8d89f--- /dev/null+++ b/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/PasswordSync.kt@@ -0,0 +1,154 @@+package com.vayunmathur.desktop.passwords++import com.vayunmathur.everysync.core.network.JvmRelayTransport+import com.vayunmathur.everysync.core.network.RelayTransport+import com.vayunmathur.everysync.core.network.appendRecords+import com.vayunmathur.everysync.core.network.pullRecords+import com.vayunmathur.everysync.core.network.recordChannel+import com.vayunmathur.everysync.core.platform.MemorySecureStore+import com.vayunmathur.everysync.core.platform.SecureStore+import com.vayunmathur.everysync.core.provider.SyncDriver+import com.vayunmathur.everysync.core.sync.adapters.PasswordKind+import java.io.File+import kotlin.io.encoding.Base64+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * File-backed [SecureStore] for the desktop shell's PQC identity + device id.+ * Keys persist as files under `dataDir/secure/<name>` (bytes raw, strings+ * UTF-8, longs decimal) with `onlyIfAbsent` honored atomically.+ *+ * NOTE: this is persistence, not encryption — a production desktop client+ * would wrap this in DPAPI / Keychain / libsecret (see the `SecureStore`+ * contract in the shared core). Phase 2a keeps the plain-file form and+ * documents the gap.+ */+class FileSecureStore(dataDir: File) : SecureStore {+ private val dir = File(dataDir, "secure").apply { mkdirs() }+ private val mutex = Mutex()++ override suspend fun getBytes(name: String): ByteArray? = mutex.withLock {+ val f = File(dir, name)+ if (f.isFile) runCatching { f.readBytes() }.getOrNull() else null+ }++ override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+ mutex.withLock {+ val f = File(dir, name)+ if (onlyIfAbsent && f.isFile) return+ runCatching { f.writeBytes(value) }+ }+ }++ override suspend fun delete(name: String) {+ mutex.withLock { runCatching { File(dir, name).delete() } }+ }++ override suspend fun getString(name: String): String? = mutex.withLock {+ val f = File(dir, "$name.str")+ if (f.isFile) runCatching { f.readText() }.getOrNull() else null+ }++ override suspend fun setString(name: String, value: String, onlyIfAbsent: Boolean) {+ mutex.withLock {+ val f = File(dir, "$name.str")+ if (onlyIfAbsent && f.isFile) return+ runCatching { f.writeText(value) }+ }+ }++ override suspend fun getLong(name: String): Long? = mutex.withLock {+ val f = File(dir, "$name.num")+ if (f.isFile) runCatching { f.readText().trim().toLong() }.getOrNull() else null+ }++ override suspend fun setLong(name: String, value: Long) {+ mutex.withLock { runCatching { File(dir, "$name.num").writeText(value.toString()) } }+ }+}++/**+ * Drives the `passwords:<vaultId>` channel through the shared [SyncDriver]+ * over the shared [RelayTransport] (JVM: [JvmRelayTransport] with+ * [com.vayunmathur.everysync.core.network.JvmPqcCrypto] defaults).+ *+ * Cycle (mirrors `E2eeProvider.driveMerge`):+ * 1. Fold the FULL decrypted record log from 0 — tombstones included, last+ * envelope per uid wins — into remote state (never a delta, so absence+ * vs deletion stays decidable against the baseline).+ * 2. A failed pull (null) or a fully-undecryptable log aborts with zero+ * writes — never merge a failure as empty (see `RelayMerge`).+ * 3. [SyncDriver.drive] merges against the vault's full local state ++ * baseline, appends `remoteOut` BEFORE persisting locally, then applies+ * the local half.+ *+ * Vault-key note: the caller supplies the epoch-0 vault key directly. Roster+ * / key-epoch / ownership resolution (`VaultRoster`, `VaultKeys`,+ * `OwnerTransfer`) is future work for the desktop shell — shared vaults that+ * rotated keys need that before this shell can read them.+ */+class PasswordSync(+ private val transport: RelayTransport,+ private val dataDir: File,+) {+ data class SyncResult(val ok: Boolean, val passwords: Int, val passkeys: Int)++ companion object {+ fun channelFor(vaultId: String): String = recordChannel("passwords", vaultId)++ /** Builds a transport with production JVM PQC + pinned HTTP defaults. */+ fun defaultTransport(store: SecureStore = MemorySecureStore()): JvmRelayTransport =+ JvmRelayTransport(store)+ }++ suspend fun syncOnce(vaultId: String, vaultKey: ByteArray): SyncResult {+ val vault = PasswordVault(dataDir, vaultId)+ val channel = channelFor(vaultId)+ val now = System.currentTimeMillis()++ // Null pull (any transport failure) aborts — never merge a failure.+ val pulled = transport.pullRecords(channel, vaultKey, 0) ?: return SyncResult(false, 0, 0)+ if (pulled.fullyUndecryptable) return SyncResult(false, 0, 0)++ // Fold to FULL state: last envelope per uid wins (append-only log).+ val folded = LinkedHashMap<String, String>()+ for (raw in pulled.items) {+ val entity = vault.parseRemote(raw) ?: continue+ folded[entity.uid] = raw+ }+ val remote = folded.values.mapNotNull { vault.parseRemote(it) }++ val ok = SyncDriver.drive(+ kind = PasswordKind,+ store = vault,+ remoteEntities = remote,+ appendRemote = { items -> transport.appendRecords(channel, vaultKey, items) != null },+ now = now,+ )+ if (!ok) return SyncResult(false, 0, 0)+ val local = vault.listLocal()+ return SyncResult(true, local.count { !it.isPasskey }, local.count { it.isPasskey })+ }+}++/** Vault-key file helpers (`dataDir/vault-<vaultId>.key`, base64). */+object VaultKeyFile {+ private val json = Json { ignoreUnknownKeys = true }++ fun fileFor(dataDir: File, vaultId: String): File = File(dataDir, "vault-$vaultId.key")++ fun load(dataDir: File, vaultId: String): ByteArray? {+ val f = fileFor(dataDir, vaultId)+ if (!f.isFile) return null+ return runCatching { Base64.decode(f.readText().trim()) }.getOrNull()+ ?.takeIf { it.isNotEmpty() }+ }++ fun save(dataDir: File, vaultId: String, key: ByteArray) {+ dataDir.mkdirs()+ fileFor(dataDir, vaultId).writeText(json.encodeToString(Base64.encode(key)))+ }+}
desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/PasswordVault.kt
diff --git a/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/PasswordVault.kt b/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/PasswordVault.ktnew file mode 100644index 0000000000..05dcc1c766--- /dev/null+++ b/desktop/passwords/src/main/kotlin/com/vayunmathur/desktop/passwords/PasswordVault.kt@@ -0,0 +1,223 @@+package com.vayunmathur.desktop.passwords++import com.vayunmathur.everysync.core.data.RemotePassword+import com.vayunmathur.everysync.core.platform.LocalChange+import com.vayunmathur.everysync.core.platform.SyncSink+import com.vayunmathur.everysync.core.sync.LocalReadException+import com.vayunmathur.everysync.core.sync.RelaySnapshot+import com.vayunmathur.everysync.core.sync.RelayStore+import com.vayunmathur.everysync.core.sync.adapters.PasswordKind+import java.io.File+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * JVM mirror of the passwords `RelayPasswordProvider` relay semantics, in-process.+ *+ * Op semantics preserved verbatim from `RelayPasswordProvider` / `PasswordSink`:+ * - full-state list → [listLocal]: live rows only (passwords hard-delete, so no+ * tombstone filtering is ever needed — deleted rows simply do not exist).+ * - `upsertRaw` → [upsert]: idempotent on the relay sync identity+ * ([RemotePassword.uid]); pulled `updatedAt` timestamps are preserved verbatim+ * so LWW stays comparable across sides. A `deleted = true` envelope+ * hard-deletes the row instead of storing it.+ * - single delete (`syncId = ?`) → [delete]: hard-deletes the row. The baseline+ * snapshot is intentionally retained so the merge reads "baseline present ++ * row absent" as a local delete and propagates a tombstone to the relay+ * (see `PasswordKind.localDeletesAreAuthoritative = false`).+ * - `deleteByVault` → [purge]: drops every row *and* its snapshots.+ *+ * Hard-delete rule: delete paths NEVER write tombstone rows. Tombstones live+ * only on the relay side as `deleted = true` envelopes, and merges only ever+ * delete through those explicit envelopes (see `RelayMerge`: absence without a+ * tombstone never deletes). Only [RelayStore.deleteLocal] removes rows on the+ * merge's behalf, and only for ids the merge proved fully acknowledged.+ */+class PasswordVault(+ private val dataDir: File,+ private val vaultId: String,+) : SyncSink<RemotePassword>, RelayStore<RemotePassword> {++ private val storeFile: File get() = File(dataDir, "passwords-$vaultId.json")+ private val snapshotFile: File get() = File(dataDir, "snapshots-password-$vaultId.tsv")+ private val rows = LinkedHashMap<String, RemotePassword>()+ private val snapshots = LinkedHashMap<String, RelaySnapshot>()+ private val mutex = Mutex()+ private val json = Json { ignoreUnknownKeys = true }++ @Volatile private var lastReadOk: Boolean = true++ // --- SyncSink (provider-shaped surface) ---++ /**+ * Full local state: live rows only. A failed read surfaces as a thrown+ * [LocalReadException] (never an empty list): merging a read failure as+ * empty would delete every baseline-present relay record.+ */+ override suspend fun listLocal(vaultId: String): List<RemotePassword> = mutex.withLock {+ loadLocked()+ lastReadOk = true+ rows.values.filter { !it.deleted }+ }++ override val listLocalOk: Boolean get() = lastReadOk++ /**+ * `querySince` semantics: rows with `updatedAt` past [since]. Passwords+ * never report tombstones (hard deletes); a delete is observed as+ * "present at baseline, absent now" by the merge.+ */+ override suspend fun localChanges(vaultId: String, since: Long): List<LocalChange<RemotePassword>> =+ mutex.withLock {+ loadLocked()+ rows.values.filter { !it.deleted && it.updatedAt > since }.map {+ LocalChange(it.uid, it.updatedAt, false, it)+ }+ }++ /**+ * `upsertRaw` semantics: idempotent upsert keyed on the relay sync+ * identity, preserving the pulled `updatedAt`. A payload with+ * `deleted = true` hard-deletes the row instead (snapshot retained — see+ * [delete]). Merge-driven pulled tombstones ALWAYS arrive here as+ * `deleted = true` envelopes via upsert, never as raw deletes.+ */+ override suspend fun upsert(vaultId: String, item: RemotePassword) {+ if (item.uid.isBlank()) return+ mutex.withLock {+ loadLocked()+ if (item.deleted) {+ rows.remove(item.uid)+ } else {+ rows[item.uid] = item+ }+ saveLocked()+ }+ }++ /**+ * Single-delete semantics: hard-deletes the row but keeps its snapshot —+ * the relay merge reads that as a deletion and propagates a tombstone.+ */+ override suspend fun delete(vaultId: String, syncId: String) {+ mutex.withLock {+ loadLocked()+ rows.remove(syncId)+ saveLocked()+ }+ }++ /** `deleteByVault` semantics: drops every row *and* its snapshots. */+ override suspend fun purge(vaultId: String) {+ mutex.withLock {+ rows.clear()+ snapshots.clear()+ storeFile.delete()+ snapshotFile.delete()+ }+ }++ // --- RelayStore (merge-driver surface) ---++ override suspend fun listLocal(): List<RemotePassword> = listLocal(vaultId)++ override suspend fun upsertLocal(items: List<RemotePassword>) {+ for (item in items) upsert(vaultId, item)+ }++ /**+ * Merge-confirmed removals only: every id here carries a baseline proving+ * both sides acknowledged the tombstone, so hard-removal is safe. Live+ * rows are NEVER removed through any other path.+ */+ override suspend fun deleteLocal(items: List<RemotePassword>) {+ mutex.withLock {+ loadLocked()+ for (item in items) rows.remove(item.uid)+ saveLocked()+ }+ }++ override suspend fun loadBaseline(): Map<String, RelaySnapshot> = mutex.withLock {+ loadSnapshotsLocked()+ snapshots.toMap()+ }++ override suspend fun saveSnapshots(snapshots: List<RelaySnapshot>) {+ mutex.withLock {+ loadSnapshotsLocked()+ for (s in snapshots) this.snapshots[s.syncId] = s+ saveSnapshotsLocked()+ }+ }++ override suspend fun removeSnapshots(syncIds: List<String>) {+ mutex.withLock {+ loadSnapshotsLocked()+ for (id in syncIds) snapshots.remove(id)+ saveSnapshotsLocked()+ }+ }++ override fun parseRemote(json: String): RemotePassword? =+ PasswordKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }++ override fun serializeForRemote(entity: RemotePassword): String = PasswordKind.toJson(entity)++ // --- File persistence (JSON rows, TSV snapshots) ---++ private fun loadLocked() {+ val file = storeFile+ if (!file.isFile) return+ try {+ val decoded = json.decodeFromString<List<RemotePassword>>(file.readText())+ rows.clear()+ for (entry in decoded) {+ if (entry.uid.isNotBlank() && !entry.deleted) rows[entry.uid] = entry+ }+ lastReadOk = true+ } catch (_: Exception) {+ lastReadOk = false+ throw LocalReadException("PasswordVault read failed for $vaultId")+ }+ }++ private fun saveLocked() {+ dataDir.mkdirs()+ storeFile.writeText(json.encodeToString(rows.values.toList()))+ }++ private fun loadSnapshotsLocked() {+ val file = snapshotFile+ if (!file.isFile) return+ snapshots.clear()+ for (line in file.readLines()) {+ val parts = line.split("\t")+ if (parts.size != 7) continue+ snapshots[parts[0]] = RelaySnapshot(+ syncId = parts[0],+ kind = parts[1],+ contentHash = parts[2],+ localUpdatedAt = parts[3].toLongOrNull() ?: 0L,+ remoteModified = parts[4].toLongOrNull() ?: 0L,+ lastSyncedAt = parts[5].toLongOrNull() ?: 0L,+ deleted = parts[6] == "1",+ )+ }+ }++ private fun saveSnapshotsLocked() {+ dataDir.mkdirs()+ snapshotFile.writeText(+ snapshots.values.joinToString("\n") {+ listOf(+ it.syncId, it.kind, it.contentHash,+ it.localUpdatedAt.toString(), it.remoteModified.toString(),+ it.lastSyncedAt.toString(), if (it.deleted) "1" else "0",+ ).joinToString("\t")+ },+ )+ }+}
library/everysync-core/AGENTS.md
diff --git a/library/everysync-core/AGENTS.md b/library/everysync-core/AGENTS.mdindex 3b648ba3c2..4286e9ae4a 100644--- a/library/everysync-core/AGENTS.md+++ b/library/everysync-core/AGENTS.md@@ -20,3 +20,6 @@ ./gradlew :library:everysync-core:compileKotlinJvm ./gradlew :library:everysync-core:lint ```++## Cross-platform+Program status: root `CROSS_PLATFORM_STATUS.md`. System-sink interfaces: `src/commonMain/kotlin/com/vayunmathur/everysync/core/sinks/SystemSinks.kt`. Shells: `desktop/` (EDS/Windows), `apple/` (EventKit/CNContactStore).
library/everysync-core/LIVE_RELAY_CONFORMANCE.md
diff --git a/library/everysync-core/LIVE_RELAY_CONFORMANCE.md b/library/everysync-core/LIVE_RELAY_CONFORMANCE.mdnew file mode 100644index 0000000000..a41c5e14ef--- /dev/null+++ b/library/everysync-core/LIVE_RELAY_CONFORMANCE.md@@ -0,0 +1,93 @@+# Live-relay conformance — staging `https://findfamily.cc/personal`++Scripted manual checklist for a human (or a scripted device pair) to verify a+real relay deployment speaks the shared-core protocol. **No automation runs+this file** — each step lists the exact endpoint, channel, and envelope shape+to exercise, and the assertion to record. Automated coverage of the same+contract lives in `src/commonTest/.../network/RelayConformanceTest.kt` (fake+transport) and `SharedTransportTest.kt`.++Prerequisites: two clean installs (device A = owner, device B = joiner),+`SharedRelayTransport.init()` succeeding on both (PQC identity in+`SecureStore` under `personalKemPub/Priv`, `personalDsaPub/Priv`; stable id+under `personalDeviceId`). Record both device ids.++## 1. `POST /register` + `POST /getkey`++1. A: `register()` → HTTP 200.+2. B: `register()` → HTTP 200.+3. A: `getKey(B)` → non-empty bundle; B: `getKey(A)` → non-empty bundle.+4. A: `getKey("nonexistent-device")` → null (unknown id, no crash).++## 2. Record channels — `POST /append` + `POST /pull`++Channel names (`RelayContract.kt`): records `passwords:<vault>` /+`notes:<vault>` / `todos:<vault>` / `contacts:<vault>` / `calendar:<vault>`,+`members:<vault>`, `keys:<vault>`, `owner:<vault>`, `title:<vault>`,+`inbox:<device>`, blobs `notes-blobs:<vault>`.++1. A creates vault V (`newVaultId()`), key K (`newVaultKey()`, 32 bytes).+2. A: `appendRecords(recordChannel("notes", V), K, [noteJsonA, noteJsonB])` → seq S1 > 0.+3. B (same K, out of band = sealed invite, step 5): `pullRecords(channel, K, 0)`+ → `items == [noteJsonA, noteJsonB]`, `rawCount == 2`, `undecryptable == 0`,+ `fullyUndecryptable == false`, `seq == S1`.+4. B: `pullRecords(channel, WRONG_KEY, 0)` → `items.isEmpty()`,+ `undecryptable == 2`, `fullyUndecryptable == true` → caller MUST abort, not merge.++## 3. B64 AES record shape++1. `pullRaw(channel, 0)` → each envelope is valid Base64+ (`Base64.decode` succeeds) and `AesGcm.decrypt(K, bytes)` yields the+ plaintext JSON; IV-prepended layout (`[12B iv][ct||tag]`), same as Android+ `E2ee` and both `AesGcm` actuals.++## 4. Double-wrapped roster + epoch (`VaultPolicy.kt`)++1. A: `VaultRoster.recordMembers(V, [Member(B, role=editor)])` → true.+2. B: `fetchRoster(V, ownerKey)` → contains B as editor; tamper with one+ envelope on a scratch channel (append garbage) → skipped, roster still resolves.+3. A: `VaultKeys.rotateKey(V, epoch=0, {A: bundleA, B: bundleB})` → new key K2.+4. B: `fetchCurrentKey(V, inviteKey=K, ownerKey)` → `(1, K2)`; `K2 != K`.+5. Records appended under K2 do not decrypt under K (epoch isolation).++## 5. Sealed invite + join request (`RelayEnvelopes.kt`)++1. B: `sendJoinRequest(ownerId=A, V, "notes", B, name)` → true; lands on+ `inbox:A` with `kind:"req"` discriminator.+2. A: `pullInbox(0)` → `requests` contains B's request, `invites` empty.+3. A: `sendInvite(B, V, "notes", K_current, title, editor, ownerKeyB64, A)` → true.+4. B: `pullInvites(0)` → one invite, `vaultId == V`, `key` Base64-decodes to+ `K_current`. Relay log shows only ciphertext (spot-check: no plaintext+ title/key in raw `pullRaw(inbox:B, 0)` output).++## 6. `everysync://join` link parse (`RelayLinks`)++1. `shareLinkFor(V, A, "notes")` → `https://ma.vayunmathur.com/es/share#id=V&owner=A&type=notes`;+ contains no `key` (case-insensitive).+2. `parseJoinLink("everysync", "join", V, A, "notes")` → `Triple(V, A, "notes")`;+ wrong scheme / blank vault / blank owner → null.++## 7. The three invariants (abort conditions — verify each against staging)++1. **Failed pull returns null, never empty**: kill network mid-`pullRaw` (or+ point at a bad host) → null → `SyncDriver.drive` returns false and merges+ nothing. Provably-empty channel → empty list (merge proceeds).+2. **Only explicit tombstones delete**: delete a note locally, sync, pull on B+ → B's row is tombstoned (`deleted=true` envelope in the folded log), never+ silently dropped; an id absent from the log with no tombstone is resurrected,+ not deleted (`RelayMerge.reconcileLocalOnly` / `reconcileRemoteOnly`).+3. **Vault keys never user-visible**: share links carry ids only (step 6);+ keys move exclusively via PQC-sealed inbox invites (step 5); no key material+ in logcat, share sheets, or error messages.++## Sign-off++| Step | Date | Relay build | Pass? | Notes |+| ---- | ---- | ----------- | ----- | ----- |+| 1 register/getkey | | | | |+| 2 append/pull | | | | |+| 3 B64 AES shape | | | | |+| 4 roster/epoch | | | | |+| 5 invite/join | | | | |+| 6 join parse | | | | |+| 7 invariants | | | | |
library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/platform/AndroidSecureStore.kt
diff --git a/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/platform/AndroidSecureStore.kt b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/platform/AndroidSecureStore.ktnew file mode 100644index 0000000000..84dfc5c215--- /dev/null+++ b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/platform/AndroidSecureStore.kt@@ -0,0 +1,77 @@+package com.vayunmathur.everysync.core.platform++import android.content.Context+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlin.io.encoding.Base64++/**+ * [SecureStore] for Android shells, over plain `SharedPreferences`.+ *+ * Key names are used verbatim (`personalDeviceId`, `personalKemPub`,+ * `personalKemPriv`, `personalDsaPub`, `personalDsaPriv`,+ * `relay_cursor:…`, `relay_baseline:…`), matching the layouts+ * `SharedRelayTransport`, `PqcIdentityHandle`, `RelayCursorStore` and+ * `SnapshotFileStore` expect — the same names the everysync Android stores+ * (`VaultStore`/`TokenStore` family) use — so a future migration of those+ * shells to the shared core adopts existing values unchanged.+ *+ * Bytes are stored as Base64 strings under the same key (SharedPreferences+ * has no byte[] type); strings/longs use the native types. `onlyIfAbsent` is+ * honored atomically within this process (Mutex + `contains` check).+ *+ * TODO: migrate to EncryptedSharedPreferences+ * (androidx.security:security-crypto) once that dependency is added to+ * `:library:everysync-core`. Plain SharedPreferences is sufficient for+ * Phase 1: E2EE does not depend on it — the relay is an untrusted log, vault+ * payloads are AES-256-GCM, and PQC private keys sealed at rest add defense+ * in depth, not correctness.+ */+class AndroidSecureStore(+ context: Context,+ prefsName: String = DEFAULT_PREFS_NAME,+) : SecureStore {++ companion object {+ const val DEFAULT_PREFS_NAME = "everysync_secure"+ }++ private val prefs = context.applicationContext.getSharedPreferences(prefsName, Context.MODE_PRIVATE)+ private val mutex = Mutex()++ override suspend fun getBytes(name: String): ByteArray? = mutex.withLock {+ val raw = prefs.getString(name, null) ?: return null+ runCatching { Base64.decode(raw) }.getOrNull()+ }++ override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+ mutex.withLock {+ if (onlyIfAbsent && prefs.contains(name)) return+ prefs.edit().putString(name, Base64.encode(value)).apply()+ }+ }++ override suspend fun delete(name: String) {+ mutex.withLock { prefs.edit().remove(name).apply() }+ }++ override suspend fun getString(name: String): String? = mutex.withLock {+ prefs.getString(name, null)+ }++ override suspend fun setString(name: String, value: String, onlyIfAbsent: Boolean) {+ mutex.withLock {+ if (onlyIfAbsent && prefs.contains(name)) return+ prefs.edit().putString(name, value).apply()+ }+ }++ override suspend fun getLong(name: String): Long? = mutex.withLock {+ if (!prefs.contains(name)) return null+ prefs.getLong(name, 0L)+ }++ override suspend fun setLong(name: String, value: Long) {+ mutex.withLock { prefs.edit().putLong(name, value).apply() }+ }+}
library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/sync/AndroidFileBlobStore.kt
diff --git a/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/sync/AndroidFileBlobStore.kt b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/sync/AndroidFileBlobStore.ktnew file mode 100644index 0000000000..e8e7eab3b2--- /dev/null+++ b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/sync/AndroidFileBlobStore.kt@@ -0,0 +1,68 @@+package com.vayunmathur.everysync.core.sync++import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.io.File++/**+ * [BlobStore] over the app's `filesDir` (`<filesDir>/everysync-blobs/<vaultId>/<name>`).+ *+ * Shells construct with `context.filesDir` (pass the `File`, not the+ * `Context`, so this stays unit-testable without Robolectric). No Android+ * framework imports — plain `java.io` under `Dispatchers.IO`.+ *+ * TWIN: `jvmMain/.../JvmFileBlobStore.kt` carries the same validation ++ * atomic-write shape over the user-data dir; keep them in sync.+ */+class AndroidFileBlobStore(+ filesDir: File,+) : BlobStore {++ companion object {+ const val BLOBS_DIR = "everysync-blobs"++ internal fun checkName(vaultId: String, name: String) {+ require(vaultId.isNotBlank() && '/' !in vaultId && '\\' !in vaultId &&+ vaultId != ".." && vaultId != ".") { "invalid vaultId" }+ require(name.isNotBlank() && '/' !in name && '\\' !in name &&+ name != ".." && name != ".") { "invalid blob name: $name" }+ }+ }++ private val rootDir = File(filesDir, BLOBS_DIR)++ private fun fileFor(vaultId: String, name: String): File {+ checkName(vaultId, name)+ return File(File(rootDir, vaultId), name)+ }++ override suspend fun put(vaultId: String, name: String, bytes: ByteArray) =+ withContext(Dispatchers.IO) {+ val f = fileFor(vaultId, name)+ val dir = f.parentFile ?: rootDir+ dir.mkdirs()+ val tmp = File.createTempFile("blob-", ".tmp", dir)+ try {+ tmp.writeBytes(bytes)+ if (!tmp.renameTo(f)) {+ f.delete()+ tmp.renameTo(f)+ }+ } finally {+ if (tmp.exists()) tmp.delete()+ }+ }++ override suspend fun get(vaultId: String, name: String): ByteArray? =+ withContext(Dispatchers.IO) {+ val f = runCatching { fileFor(vaultId, name) }.getOrNull() ?: return@withContext null+ if (!f.isFile) return@withContext null+ runCatching { f.readBytes() }.getOrNull()+ }++ override suspend fun delete(vaultId: String, name: String) {+ withContext(Dispatchers.IO) {+ runCatching { fileFor(vaultId, name).delete() }+ }+ }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sinks/SystemSinks.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sinks/SystemSinks.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sinks/SystemSinks.ktnew file mode 100644index 0000000000..9fd04f1211--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sinks/SystemSinks.kt@@ -0,0 +1,73 @@+package com.vayunmathur.everysync.core.sinks++import com.vayunmathur.everysync.core.data.RemoteContact+import com.vayunmathur.everysync.core.data.RemoteEvent+import com.vayunmathur.everysync.core.data.RemoteTodo+import com.vayunmathur.everysync.core.platform.SyncSink++/**+ * System-provider sink contracts for every EverySync target.+ *+ * Pure Kotlin, `expect`-free: platform actuals (Android `CalendarSink` /+ * `ContactsSink`, desktop JVM, Apple Swift/KMP) implement these interfaces+ * against their native stores. All three reuse [SyncSink], so the shared+ * [com.vayunmathur.everysync.core.provider.SyncDriver] merge cycle is+ * identical on every OS; only the store binding differs.+ *+ * Canonical interchange (shared, in `core.format`):+ * - events: [RemoteEvent] <-> iCal VEVENT (`ICalendar`; RRULE carried verbatim).+ * - contacts: [RemoteContact] <-> vCard (`VCard`; type ints mirror+ * ContactsContract codes so Android passes them through unchanged).+ * - todos: [RemoteTodo] JSON on the `todos:<vaultId>` channel (no system+ * interchange format; each OS maps to its native reminder row).+ *+ * Sync-identity columns (uid = relay sync id, stamp = relay updatedAt):+ * - Android calendar: `Events._SYNC_ID` = uid, `SYNC_DATA1` = stamp,+ * `SYNC_DATA2` = vault id; writes via `CALLER_IS_SYNCADAPTER` URIs so relay+ * writes never set `DIRTY`. Local edits surface via `DIRTY`/`DELETED`.+ * - Android contacts: `RawContacts.SOURCE_ID` = uid, `SYNC1` = stamp,+ * `SYNC2` = vault id; same sync-adapter + `DIRTY`/`DELETED` discipline.+ * - Other targets persist the same (uid, stamp, vault) triple in the store's+ * own sync-id fields; see the per-OS table below.+ *+ * Per-OS store backends:+ *+ * | OS | Calendar | Contacts | Todos |+ * |---------|---------------------------------|----------------------|------------------------------------|+ * | Android | CalendarContract provider | ContactsContract | todo/ app vault (no system provider) |+ * | Apple | EventKit `EKEvent` | `CNContactStore` | EventKit `EKReminder` |+ * | Linux | EDS `libecal` | EDS `libebook` | EDS task list (`libecal` todos) |+ * | Windows | `AppointmentStore` (read-only v1) | `ContactStore` (read-only v1) | Notes-view task list (read-only v1) |+ *+ * Delete discipline (matches the merge's `EntityKind` flags): calendar and+ * contacts soft-delete (provider `DELETED` flags / tombstone rows survive in+ * `listLocal`); todos soft-delete (tombstone rows persist). Passwords are NOT+ * system sinks — they hard-delete in the app vault.+ */+interface CalendarSystemSink : SyncSink<RemoteEvent> {+ /**+ * [RemoteEvent] <-> iCal VEVENT <-> native event (`EKEvent` / `libecal` /+ * `AppointmentStore` appointment): `uid` (+ `recurrenceId` for overridden+ * instances) is the identity, `ICalendar` is the canonical text form for+ * hashing, recurring masters store `RRULE` with duration instead of end.+ */+}++interface ContactsSystemSink : SyncSink<RemoteContact> {+ /**+ * [RemoteContact] <-> vCard <-> native contact (`CNContact` / `libebook` /+ * `ContactStore` contact): `uid` is the identity, `VCard` is the canonical+ * text form for hashing, phone/email/postal type ints ride the shared+ * `PhoneKind`/`EmailKind`/`PostalKind` codes.+ */+}++interface TodoSystemSink : SyncSink<RemoteTodo> {+ /**+ * [RemoteTodo] <-> native reminder (`EKReminder` / `libecal` todo /+ * Notes-view row): `uid` is the identity, `notes` + `createdAt` MUST be+ * persisted (both are envelope fields AND merge-hash inputs — dropping+ * them breaks LWW convergence), tombstones (`deleted = true`) persist as+ * real rows. `position` is ordering-only and excluded from the merge hash.+ */+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/BlobStore.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/BlobStore.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/BlobStore.ktnew file mode 100644index 0000000000..5d87d83281--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/BlobStore.kt@@ -0,0 +1,24 @@+package com.vayunmathur.everysync.core.sync++/**+ * Content bytes for note image blocks, keyed by `(vaultId, name)`.+ *+ * The relay side of these bytes is the `notes-blobs:<vaultId>` channel (see+ * `blobChannel`); this interface is the local half shells compose into their+ * note stores. Names are the `fileName` values referenced inside+ * `NoteBody` blocks JSON (see `NoteKind.imageNames`).+ *+ * Platform impls: [JvmFileBlobStore] (desktop user-data dir) and+ * [AndroidFileBlobStore] (app `filesDir`). Both reject path separators in+ * `vaultId`/`name` so a malicious envelope can never traverse out of the root.+ */+interface BlobStore {+ /** Stores (or replaces) the bytes for `(vaultId, name)`. */+ suspend fun put(vaultId: String, name: String, bytes: ByteArray)++ /** Returns the bytes for `(vaultId, name)`, or null when absent/invalid. */+ suspend fun get(vaultId: String, name: String): ByteArray?++ /** Deletes `(vaultId, name)`; no-op when absent. */+ suspend fun delete(vaultId: String, name: String)+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelaySnapshot.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelaySnapshot.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelaySnapshot.ktindex e8673a8b1c..10db2fddae 100644--- a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelaySnapshot.kt+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelaySnapshot.kt@@ -1,5 +1,6 @@ package com.vayunmathur.everysync.core.sync +import kotlinx.serialization.Serializable import kotlin.uuid.Uuid /**@@ -10,6 +11,7 @@ import kotlin.uuid.Uuid * could never propagate. [deleted] marks a retained tombstone alongside the * snapshot rows so a delete survives until both sides have acknowledged it. */+@Serializable data class RelaySnapshot( val syncId: String, val kind: String,
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SnapshotFileStore.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SnapshotFileStore.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SnapshotFileStore.ktnew file mode 100644index 0000000000..8c94116048--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SnapshotFileStore.kt@@ -0,0 +1,84 @@+package com.vayunmathur.everysync.core.sync++import com.vayunmathur.everysync.core.platform.SecureStore+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.decodeFromString+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * [RelaySnapshot] list persistence over any [SecureStore], for `RelayStore`+ * adapters whose driver is [com.vayunmathur.everysync.core.provider.SyncDriver].+ *+ * One instance covers one `(vaultId, kind)` pair and persists under key+ * `relay_baseline:<vault>:<kind>` (JSON array of [RelaySnapshot] via+ * kotlinx.serialization) — the layout `RelayCursorStore` documents, so values+ * created here are adoptable by the Android shells unchanged.+ *+ * API mirrors+ * [com.vayunmathur.everysync.core.provider.MemoryBaselineStore.load/save/remove]+ * (which stays for tests and drivers that manage their own persistence), but+ * suspending and durable: `save` upserts by `syncId`, `remove` drops ids and+ * deletes the key when the baseline empties.+ *+ * Corrupt/missing payloads load as an empty baseline (self-healing: the next+ * successful merge re-baselines; the merge never treats a read failure as a+ * delete, so this direction is loss-safe).+ */+class SnapshotFileStore(+ private val store: SecureStore,+ private val vaultId: String,+ private val kind: String,+) {+ companion object {+ /** Key layout shared with the Android stores. */+ fun key(vaultId: String, kind: String): String = "relay_baseline:$vaultId:$kind"+ }++ private val key = key(vaultId, kind)+ private val json = Json { ignoreUnknownKeys = true }+ private val mutex = Mutex()++ /** Loads the baseline; empty when nothing was persisted (or it is corrupt). */+ suspend fun load(): Map<String, RelaySnapshot> = mutex.withLock { currentLocked() }++ /** Upserts [list] by `syncId`, preserving previously baselined ids. */+ suspend fun save(list: List<RelaySnapshot>) {+ if (list.isEmpty()) return+ mutex.withLock {+ val merged = currentLocked().toMutableMap()+ for (s in list) merged[s.syncId] = s+ persistLocked(merged.values.toList())+ }+ }++ /** Drops [ids] from the baseline; deletes the key when it empties. */+ suspend fun remove(ids: List<String>) {+ if (ids.isEmpty()) return+ mutex.withLock {+ val merged = currentLocked().toMutableMap()+ var changed = false+ for (id in ids) if (merged.remove(id) != null) changed = true+ if (!changed) return+ persistLocked(merged.values.toList())+ }+ }++ /** Lock must be held. */+ private suspend fun currentLocked(): Map<String, RelaySnapshot> {+ val raw = store.getString(key) ?: return emptyMap()+ if (raw.isBlank()) return emptyMap()+ return runCatching { json.decodeFromString<List<RelaySnapshot>>(raw) }+ .getOrNull()?.associateBy { it.syncId } ?: emptyMap()+ }++ /** Lock must be held. */+ private suspend fun persistLocked(all: List<RelaySnapshot>) {+ if (all.isEmpty()) {+ store.delete(key)+ } else {+ store.setString(key, json.encodeToString(all))+ }+ }+}
library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/platform/JvmFileSecureStore.kt
diff --git a/library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/platform/JvmFileSecureStore.kt b/library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/platform/JvmFileSecureStore.ktnew file mode 100644index 0000000000..805d0f292b--- /dev/null+++ b/library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/platform/JvmFileSecureStore.kt@@ -0,0 +1,125 @@+package com.vayunmathur.everysync.core.platform++import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import java.io.File+import java.util.prefs.Preferences+import kotlin.io.encoding.Base64++/**+ * File-backed [SecureStore] for desktop JVM shells (desktop/CLI targets that+ * build on the shared core).+ *+ * Layout:+ * - strings/longs live in `java.util.prefs.Preferences` under [PREFS_NODE]+ * (registry on Windows, plist/XML elsewhere — no files to manage);+ * - bytes (PQC identity keys `personalKemPub/Priv`, `personalDsaPub/Priv`)+ * live as individual files under [bytesDir], one file per key, written+ * atomically (temp + rename) so a crash never leaves a half key.+ *+ * Key names are used verbatim (`personalDeviceId`, `personalKemPub`, …), the+ * same layout `SharedRelayTransport` and `RelayCursorStore` expect, so values+ * created here are adoptable by other shells unchanged.+ *+ * Path resolution is runtime-only (`EVERYSYNC_DATA_DIR` env override, else+ * `~/.everysync`): no hardcoded absolute paths, and no Gradle `Project`/`File`+ * captured here, so this stays configuration-cache safe by construction (it is+ * runtime code, not build logic).+ *+ * Failure contract: a missing key returns null; an I/O error throws (never+ * synthesized as "absent" — returning null on failure would mint a fresh PQC+ * identity and orphan every vault).+ */+class JvmFileSecureStore(+ private val prefs: Preferences = Preferences.userRoot().node(PREFS_NODE),+ private val bytesDir: File = defaultBytesDir(),+) : SecureStore {++ companion object {+ const val PREFS_NODE = "com/vayunmathur/everysync"++ /** Env override for the user-data dir (tests/CI point it at a temp dir). */+ const val ENV_DATA_DIR = "EVERYSYNC_DATA_DIR"++ /**+ * Resolved at call time (not configuration time): `$EVERYSYNC_DATA_DIR`+ * when set, else `~/.everysync`. Callers that need a custom root pass+ * [bytesDir] explicitly.+ */+ fun defaultBytesDir(): File {+ val override = System.getenv(ENV_DATA_DIR)?.takeIf { it.isNotBlank() }?.let(::File)+ val base = override ?: File(System.getProperty("user.home") ?: ".", ".everysync")+ return File(base, "securestore-bytes")+ }++ /**+ * Collision-free file name for a key: URL-safe Base64 (`-`/`_`, never+ * `/`), so any key string maps to exactly one file and no key can+ * traverse out of [bytesDir].+ */+ internal fun fileNameFor(name: String): String =+ Base64.UrlSafe.encode(name.encodeToByteArray()) + ".bin"+ }++ private val mutex = Mutex()++ private fun fileFor(name: String): File = File(bytesDir, fileNameFor(name))++ override suspend fun getBytes(name: String): ByteArray? = mutex.withLock {+ val f = fileFor(name)+ if (!f.isFile) return null+ f.readBytes()+ }++ override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+ mutex.withLock {+ val f = fileFor(name)+ if (onlyIfAbsent && f.isFile) return+ val dir = f.parentFile ?: bytesDir+ dir.mkdirs()+ val tmp = File.createTempFile("es-", ".tmp", dir)+ try {+ tmp.writeBytes(value)+ if (!tmp.renameTo(f)) {+ f.delete()+ tmp.renameTo(f)+ }+ } finally {+ if (tmp.exists()) tmp.delete()+ }+ }+ }++ override suspend fun delete(name: String) {+ mutex.withLock {+ runCatching { prefs.remove(name) }+ runCatching { fileFor(name).delete() }+ runCatching { prefs.flush() }+ }+ }++ override suspend fun getString(name: String): String? = mutex.withLock {+ runCatching { prefs.get(name, null) }.getOrNull()+ }++ override suspend fun setString(name: String, value: String, onlyIfAbsent: Boolean) {+ mutex.withLock {+ if (onlyIfAbsent && runCatching { prefs.get(name, null) }.getOrNull() != null) return+ prefs.put(name, value)+ runCatching { prefs.flush() }+ }+ }++ override suspend fun getLong(name: String): Long? = mutex.withLock {+ val exists = runCatching { prefs.keys().contains(name) }.getOrDefault(false)+ if (!exists) return null+ runCatching { prefs.getLong(name, 0L) }.getOrNull()+ }++ override suspend fun setLong(name: String, value: Long) {+ mutex.withLock {+ prefs.putLong(name, value)+ runCatching { prefs.flush() }+ }+ }+}
library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/sync/JvmFileBlobStore.kt
diff --git a/library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/sync/JvmFileBlobStore.kt b/library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/sync/JvmFileBlobStore.ktnew file mode 100644index 0000000000..ca4784bf53--- /dev/null+++ b/library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/sync/JvmFileBlobStore.kt@@ -0,0 +1,75 @
Diff truncated.