diff --git a/AGENTS.md b/AGENTS.md index a6672d81..6b93bc33 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,7 @@ Always adhere to the following stylistic and spelling rules: 4. **Specific Terminology and Spelling**: - Use **'dialogue'** in documentation, user-facing messages, and general text. Use **'dialog'** only inside source code (e.g. class names, methods). - Use the hyphenated form **'plug-in'** in user-facing text. Use **'plugin'** only in codebase files, configuration settings, or technical contexts. + - Use **'Self-hosted LiveSync'** or, where the context is clear, **'this plug-in'** when referring to this product. Preserve exact interface labels, code identifiers, commands, package names, and quotations. In explanatory prose, write **'LiveSync mode'** for the Sync Mode. 5. **User Communication Language**: - Always reply to the user in the language in which they asked the question. diff --git a/README.md b/README.md index 82c42bb3..f84b0267 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,8 @@ Synchronisation status is shown in the status bar with the following icons. - 🛫 Pending read storage processes - 📬 Batched read storage processes - ⚙️ Working or pending storage processes for hidden files - - 🧩 Waiting chunks + - 🛄 Pending initial on-demand chunk requests + - 🔁 Pending chunk retries, including retry delays - 🔌 Working customisation items (configuration, snippets, and plug-ins) To prevent file and database corruption, please avoid closing Obsidian until all progress indicators have disappeared as much as possible (although the plug-in will attempt to resume if interrupted). This is especially important if you have deleted or renamed files. diff --git a/devs.md b/devs.md index 56a4dbf1..713eb6cc 100644 --- a/devs.md +++ b/devs.md @@ -235,6 +235,18 @@ Commonlib owns the typed English fallback for messages requested by its services ### Logging & Debugging +#### ID generation measurements on a device + +Enable **Enable Developers' Debug Tools.**, restart Obsidian, and run **Open review harness** from the command palette. Choose **Run** beside **ID generation performance**, keep Obsidian in the foreground, and use **Copy Markdown report** to retain the results. The **Automatic** action does not run this measurement; **Full review** includes it. + +The measurement uses fixed in-memory inputs and keys, with no Vault, database, settings, or remote writes. It compares legacy `xxhash64` and independent Chunk IDs for 256-byte, 4-KiB, and 32-KiB inputs, and compares obfuscated document IDs. Each result reports the median and range of three 1,000-ID samples and the median time per ID. Key derivation at save time is measured separately. Warm-up and pauses between batches are excluded from the timings. These measurements do not represent a full Rebuild. + +Where `performance.memory` is available, the report includes approximate JavaScript heap samples before, during, and after measurement. These may include other Obsidian activity and garbage collection; they are neither total process RAM nor an exact peak. Unsupported devices explicitly report that heap measurements are unavailable. + +The developer-only adapter in `src/features/ReviewHarness/reviewHarnessIdBenchmarkRuntime.ts` imports `HashManager` from Commonlib's public `/hashing` entry. Compilation, packed-package checks, and runtime tests cover this boundary. The algorithms remain owned by Commonlib. + +#### Logs + - Use `this._log(msg, LOG_LEVEL_INFO)` in modules (automatically prefixes with module name) - Log levels: `LOG_LEVEL_DEBUG`, `LOG_LEVEL_VERBOSE`, `LOG_LEVEL_INFO`, `LOG_LEVEL_NOTICE`, `LOG_LEVEL_URGENT` - LOG_LEVEL_NOTICE and above are reported to the user via Obsidian notices diff --git a/docs/adr/2026_07_bounded_remote_activity.md b/docs/adr/2026_07_bounded_remote_activity.md index 07fcf60e..140136af 100644 --- a/docs/adr/2026_07_bounded_remote_activity.md +++ b/docs/adr/2026_07_bounded_remote_activity.md @@ -43,7 +43,7 @@ Applying downloaded document changes enters one local-application boundary from Manual P2P commands which bypass `ReplicationService` enter the broad boundary. Direct P2P pull and push entry points are therefore both protected as finite remote work, covering the Obsidian panes, CLI, and Webapp. A pull or bidirectional synchronisation also enters the narrower finite-replication boundary because it can place documents in the local database. A push-only request remains broad-only: it cannot satisfy a local missing-chunk read and must not present itself as a delivery source. Automatic synchronisation on peer discovery, a pull requested by a remote peer, and a watched pull following a peer progress notification enter both boundaries because each can deliver local documents. A normal P2P peer-selection dialogue represents one broad finite session: it remains inside the boundary while waiting for a peer and while the person may perform repeated synchronisations, then settles when the dialogue closes and any in-flight synchronisation has finished. Closing without synchronising returns a failed result and releases the boundary. The 'Start Sync & Close' action completes its synchronisation before closing. This deliberately protects peer discovery and selection, because display sleep can interrupt discovery or connection establishment and require the person to start detection again. It may therefore retain a Wake Lock longer than the network transfer alone. A transfer performed inside that session temporarily adds a nested activity; the count remains a logical-operation count rather than a connection total. -`ChunkFetcher` enters the broad boundary synchronously when it accepts newly missing chunk identifiers, but it does not increment the finite-replication count. A typed per-identifier claim keeps the broad boundary active through queue waiting, interval throttling, `fetchRemoteChunks`, validation, local persistence, and terminal event delivery. Duplicate requests share the existing claim. Explicit absence, failure, cancellation, or a conservative five-minute period without fetcher-observable progress settles the affected claim. The five-minute value is only a last-resort leak fuse: it prevents a never-settling integration from retaining the per-identifier claim and waiter indefinitely and, once the activity runner has entered the claim task, lets the associated Wake Lock, lifecycle deferral, and indicator finish. It is not an arrival estimate, proof of remote absence, or a transport deadline. This scope is defined in detail by the chunk-arrival-quiescence ADR. +`ChunkFetcher` enters the broad boundary synchronously when it accepts newly missing chunk identifiers, but it does not increment the finite-replication count. A typed per-identifier claim keeps the broad boundary active through queue waiting, interval throttling, `fetchRemoteChunks`, validation, local persistence, and terminal event delivery. Duplicate requests share the existing claim. A first successful omission schedules a two-second retry; further omissions increase the per-identifier delay up to ten seconds while finite replication remains active. Backoff releases physical concurrency without releasing the bounded task. Observed finite completion interrupts backoff for a local recheck and, if needed, a final remote probe. A current final successful omission settles the claim; failure, cancellation, or a conservative five-minute period without fetcher-observable progress also settles it. The five-minute value is only an inactivity leak fuse, not a total retry budget: it prevents a never-settling integration from retaining the per-identifier claim and waiter indefinitely and, once the activity runner has entered the claim task, lets the associated Wake Lock, lifecycle deferral, and indicator finish. It is not an arrival estimate, proof of remote absence, or a transport deadline. This scope is defined in detail by the chunk-arrival-quiescence ADR. Rebuild operations use the same boundary at their destructive or remote phase: @@ -105,7 +105,7 @@ Unit tests cover: - direct P2P pull and push entry points entering the broad boundary, while only pull and bidirectional operations enter the finite-delivery boundary; - automatic synchronisation on peer discovery, remote pull requests, and watched peer progress entering the boundary; - P2P peer-selection sessions settling on close, including cancellation, repeated synchronisation, and a close during in-flight work; -- remote chunk fetching remaining inside the shared boundary from synchronous queue acceptance through local persistence and terminal notification; +- remote chunk fetching remaining inside the shared boundary from synchronous queue acceptance through the delayed retry of omitted identifiers, local persistence, and terminal notification; - missing-chunk waiters rechecking local storage when observed per-identifier claims and finite replication have settled; - the finite-replication count excluding other bounded work; - replicated document application sharing one local boundary, settling after the final recovery snapshot, and releasing around processing suspension; diff --git a/docs/adr/2026_07_chunk_arrival_quiescence.md b/docs/adr/2026_07_chunk_arrival_quiescence.md index bbb77426..55e9937a 100644 --- a/docs/adr/2026_07_chunk_arrival_quiescence.md +++ b/docs/adr/2026_07_chunk_arrival_quiescence.md @@ -12,6 +12,8 @@ Before this decision, a missing-chunk waiter used a fixed 5-second or 30-second Finite replication provides a stronger boundary than elapsed wall-clock time. In the absence of an error, a finite replication does not complete until it has reached the latest sequence in its scope. Once it completes, that replication cannot deliver another chunk. An on-demand fetch is a separate finite delivery path and needs its own per-identifier boundary. +A successful CouchDB lookup which omits a requested chunk is a point-in-time observation. Metadata and Chunk documents can become visible separately, so the first such result immediately after Metadata arrives does not prove that a second lookup will return the same result. The on-demand fetch lifecycle therefore needs to distinguish an initial omission from its terminal result. + ## Decision Wait only for a delivery lifecycle which is observable when the local miss is handled. Do not guess how long an unobserved producer might take. @@ -29,7 +31,7 @@ The waiting layer follows these rules: 2. Dispatch `missingChunks` synchronously when direct fetch is permitted. `ChunkFetcher` must claim accepted identifiers before dispatch returns, closing the scheduling gap without a timer. 3. If a matching claim or finite replication is active, wait for that observable producer. 4. A valid chunk arrival resolves the waiter immediately. -5. An explicit remote-missing result resolves it as missing immediately. +5. A terminal explicit remote-missing result resolves it as missing immediately. 6. Once every observed producer completes, read the requested identifier from the local database once more, bypassing the cache. 7. Return the rechecked chunk, or return unavailable. Do not add a fixed grace period after the producer has stopped. 8. If no producer is observable after synchronous dispatch, return unavailable immediately. There is no operation for a duration to represent. @@ -46,17 +48,24 @@ A successful finite replication completion is the authoritative ‘latest’ bou - configured interval throttling; - entry into the injected bounded-activity runner; - `fetchRemoteChunks`; +- scheduled retries for identifiers omitted from successful responses; - response validation; - local database persistence; and - fetched or missing event delivery. -The claim settles on every terminal path, including explicit absence, no active replicator, rejection, invalid results, destruction, and cancellation. Its completion Promise is the task passed to the bounded `chunk-fetch` activity, keeping Wake Lock, application lifecycle deferral, the remote-work indicator, and missing-chunk delivery aligned. +When the first successful response omits an identifier, `ChunkFetcher` keeps that identifier claimed and schedules a retry after two seconds, even if no finite replication is active. Identifiers present in a partial response are persisted and settled immediately. While finite replication remains active, subsequent omissions schedule per-identifier delays of four, six, eight, and then ten seconds, capped at ten seconds. Backoff returns the physical request slot to the queue without releasing the logical claim. Eligible retries can share a batch with new identifiers, and the queue wakes without requiring a new missing-chunk event. + +When the observed finite count falls to zero, the fetcher interrupts any remaining backoff. It rechecks local persistence and, if the identifier is still absent, makes one final remote probe, subject to the configured request interval and concurrency. An already-running lookup cannot overlap another lookup for that identifier. If it began before the latest finite completion, an omitted identifier still needs a post-completion probe. A new finite operation which ends during that probe similarly makes its negative result stale. A successful omission from a current final probe emits `missingChunkRemote` and settles the current read; it does not leave a retry pending for a future synchronisation. + +The retry policy observes only finite replication, not the claim itself or the broader bounded-activity count. It does not treat the continuous live channel as a finite producer. There is no fixed total duration or attempt limit while finite replication continues; the delay cap controls request frequency, not overall lifetime. No retry state is persisted, and transport errors do not enter this missing-result retry policy. + +The claim settles on every terminal path, including explicit absence after the retry, no active Replicator, rejection, invalid results, destruction, and cancellation. Its completion Promise is the task passed to the bounded `chunk-fetch` activity, keeping Wake Lock, application lifecycle deferral, the remote-work indicator, and missing-chunk delivery aligned. ### Five-minute leak fuse An accepted on-demand claim has a separate five-minute inactivity fuse. This is a last-resort leak safety valve, not a chunk-arrival budget or a remote-request timeout. -Its purpose is to prevent a faulty integration, a never-settling Promise, or a stalled transport from retaining logical ownership indefinitely. When it fires, the coordinator releases the per-identifier claim and its waiter. If the bounded activity callback has been entered, resolving the claim also allows the associated Wake Lock, application-lifecycle deferral, and remote-work indicator to be released. `ChunkFetcher` refreshes the fuse only at observable progress points, such as entering the activity boundary, beginning and completing throttling or transfer, and completing persistence. +Its purpose is to prevent a faulty integration, a never-settling Promise, or a stalled transport from retaining logical ownership indefinitely. When it fires, the coordinator releases the per-identifier claim and its waiter. If the bounded activity callback has been entered, resolving the claim also allows the associated Wake Lock, application-lifecycle deferral, and remote-work indicator to be released. `ChunkFetcher` refreshes the fuse at observable progress points, including entry into the activity boundary, request scheduling, transfer, and persistence. Repeated successful missing responses are progress for this fuse, so it is not a five-minute total limit on retries during active finite replication. Five minutes is deliberately a conservative operational limit, not a value derived from a network protocol, a benchmark, or evidence that a missing chunk will arrive within that period. Firing the fuse neither proves remote absence nor makes the underlying request safe to abort. The current `fetchRemoteChunks` contract has no `AbortSignal`, so a physical request may still complete after its logical claim has been released. A future cancellable transport contract should add transport-specific deadlines and explicit cancellation without changing the lifecycle-based wait rule. @@ -64,7 +73,7 @@ Five minutes is deliberately a conservative operational limit, not a value deriv The unbounded live channel is not a quiescence gate because it has no natural end. Its initial pull-only catch-up is finite, however, and must enter `runFiniteReplicationActivity`. This includes the one-shot parameter fallback chain: every retry remains within the catch-up boundary until it succeeds or stops. If continuous replication later restarts with adjusted parameters, the new initial catch-up enters a new finite boundary. -Once the live channel has begun, a chunk delivered through it still resolves an existing waiter immediately, but the channel itself does not keep a new waiter open. CouchDB on-demand fetching supplies its own per-identifier claim. If a future defect demonstrates a delivery race inside a live batch, that batch lifecycle should be exposed explicitly rather than approximated with another elapsed delay. +Once the live channel has begun, a chunk delivered through it still resolves an existing waiter immediately, but the channel itself does not keep a new waiter open. CouchDB on-demand fetching supplies its own per-identifier claim and at least one delayed follow-up lookup. Further retries require active finite replication; the live channel does not extend them. If another future defect requires waiting for a live batch itself, that batch lifecycle should be exposed explicitly rather than approximated with another elapsed delay. ## Ownership @@ -80,7 +89,7 @@ Once the live channel has begun, a chunk delivered through it still resolves an - Treat a positive deprecated `timeout` only as source-compatible opt-in to lifecycle waiting. Its numeric value no longer represents an arrival duration. - Preserve `preventRemoteRequest`: no on-demand request is dispatched, although an already-active finite replication may satisfy the waiter. - Preserve Promise sharing for concurrent reads of the same chunk identifier. -- Preserve immediate explicit remote-missing results. +- Preserve immediate waiter resolution when `ChunkFetcher` emits a terminal explicit remote-missing result. - Do not change which remote types support direct on-demand fetching. ## Historical Evidence and Scope @@ -90,6 +99,7 @@ This decision addresses the lifecycle-race class rather than treating every ‘L - [Issue #166](https://github.com/vrtmrz/obsidian-livesync/issues/166) contained logs where chunk collection failed shortly before related chunk writes appeared. It is evidence for the timing class, although that issue's hidden-file start-up path was repaired separately and is not claimed as a direct regression test here. - The 2021 timing fixes in [commit `39e2eab0`](https://github.com/vrtmrz/obsidian-livesync/commit/39e2eab0238d9c37e3653cdec884cbeed543fc23) and the extended leaf timeout in [commit `9facb577`](https://github.com/vrtmrz/obsidian-livesync/commit/9facb577601d8aceff7df547cd2a6f9357fdaa29) show that elapsed timeout values have historically been used to absorb the same ordering uncertainty. They do not provide a protocol basis for retaining 5-second or 30-second delays. - Replication pacing introduced by [commit `8d66c372`](https://github.com/vrtmrz/obsidian-livesync/commit/8d66c372e15c43a2de84a223c6385077b7724eec) and commonlib [commit `051b50c`](https://github.com/vrtmrz/livesync-commonlib/commit/051b50ca38ec4c05a11e8216ac259b4488b825f0) is a direct precedent for preventing replication progress from outrunning chunk collection. The present design expresses that dependency as an explicit lifecycle and completion recheck. +- [Issue #1224](https://github.com/vrtmrz/obsidian-livesync/issues/1224) reports repeatable burst edits where the receiving device observes Metadata, finds its Chunk absent in the first direct lookup, and then receives the Chunk after the file read has already failed. Retrying addresses that transient ordering case. It does not claim to reconstruct a Chunk which was never uploaded. - [Issue #505](https://github.com/vrtmrz/obsidian-livesync/issues/505) was traced to chunks which were genuinely absent after the former bulk-send option broke the chunks-before-metadata guarantee. Waiting cannot recreate missing data, so this decision does not claim to fix it. - [Issue #771](https://github.com/vrtmrz/obsidian-livesync/issues/771) and [Issue #986](https://github.com/vrtmrz/obsidian-livesync/issues/986) contain ambiguous or version-dependent `Load failed` reports. They remain unclaimed until the original writer and database state can be reproduced. @@ -113,6 +123,8 @@ The broad count includes operations which cannot provide the requested chunk. Us An unobserved producer has no defined start, progress, or completion semantics. A timer would therefore be a guess rather than a safety property. Relevant delivery paths must claim their work synchronously or expose a finite replication boundary; otherwise the read returns unavailable. +The on-demand backoff is not such a fallback timer. `ChunkFetcher` retains the identifier claim throughout each delay and owns the lookup it schedules. Once finite activity ends, the fetcher cuts the delay short and uses a current final probe rather than waiting for an unobserved future producer. + ### Remove every timer The arrival wait has no elapsed timer, but an implementation fault can leave a delivery claim unresolved forever. The five-minute inactivity fuse bounds that leaked logical state without being used as a successful delivery condition. @@ -125,6 +137,15 @@ Unit tests use deterministic clocks and deferred Promises to cover: - successful finite completion causing a cache-bypassing local database recheck; - immediate unavailability when no producer is observable; - per-identifier claims covering queueing, throttling, remote fetch, validation, persistence, and event delivery; +- an autonomous two-second retry after a first successful omission, retaining the claim and bounded remote activity; +- per-identifier backoff capped at ten seconds, with physical concurrency released during each delay; +- mixed retry stages sharing batches without resetting their individual delays or starving eligible retries; +- finite completion interrupting backoff, local persistence avoiding the final request, and pre-completion lookups requiring a current final probe; +- partial results settling available identifiers and retrying only absent identifiers; +- partial-batch completion and expired-request responses preserving replacement claims; +- concurrent request starts respecting the configured interval after retry and throttle waits; +- a final successful omission producing the terminal remote-missing result; +- disjoint initial and retry counts, aggregate ownership across fetchers, and timer cleanup; - explicit missing, no-replicator, rejection, invalid response, cancellation, runner rejection, and teardown paths; - overlapping claims and finite replications; - a runner which never enters the task and a request which never settles; @@ -132,13 +153,16 @@ Unit tests use deterministic clocks and deferred Promises to cover: - continuous replication's finite initial catch-up, including its parameter fallback path; and - the setting and replicator decision matrix. -Integration-style unit tests exercise `LayeredChunkManager`, `ChunkFetcher`, a memory-backed PouchDB database, and a deferred fake replicator together. A real Obsidian test is not required because the change remains behind the existing database, service, and event boundaries and does not alter platform UI or an adapter contract. +Integration-style unit tests exercise `LayeredChunkManager`, `ChunkFetcher`, a memory-backed PouchDB database, and a deferred fake replicator together. The downstream `chunk-fetch-retry` scenario exercises real CouchDB lookup results, local persistence, Vault reflection, and the actual status bar in Obsidian. Deterministic clock tests remain responsible for the exact backoff schedule and overlapping completion races; the real-runtime scenario does not substitute HTTP responses or synthesise finite-activity counts. ## Consequences - A healthy finite replication or on-demand request no longer loses a race against an unrelated wall-clock estimate. +- A Chunk omitted from the first successful CouchDB lookup receives a follow-up lookup while the same delivery claim remains active, and further retries while finite replication continues. - Successful finite replication completion provides a precise latest boundary for missing-chunk reads. - The local recheck closes event-delivery and cache timing gaps without extending the wait after completion. -- Reads no longer pause for 5 or 30 seconds when no observable operation can deliver the chunk. +- Reads no longer pause for the former 5-second or 30-second arrival budgets. Backoff schedules observable requests rather than setting an elapsed arrival deadline. +- With no finite replication active, a genuinely absent remote Chunk takes one additional lookup after two seconds. Active finite replication can extend that lifetime; its completion expedites the final probe. +- The status bar separates initial pending identifiers (`🛄`) from retrying identifiers (`🔁`). Their sum remains the internal pending count used for restart deferral. - Relevant producers must expose a lifecycle and must continue to prove cleanup on every exceptional path. - The five-minute fuse bounds leaked logical activity, but it neither establishes remote absence nor cancels a physical request. diff --git a/docs/adr/2026_07_release_notes_and_database_compatibility.md b/docs/adr/2026_07_release_notes_and_database_compatibility.md index 5a7d80aa..5fa07af2 100644 --- a/docs/adr/2026_07_release_notes_and_database_compatibility.md +++ b/docs/adr/2026_07_release_notes_and_database_compatibility.md @@ -45,18 +45,20 @@ Keep configured-state inference separate from new-Vault initialisation. If an ex - Continue to use the internal database version `VER` for changes which require explicit compatibility review. Changing the plug-in SemVer alone does not increment `VER`. - Store the last acknowledged internal database version through Commonlib's device-local small-configuration contract under `database-compatibility-version`. Copy the legacy raw local-storage value into that contract once, then remove the legacy key after the copy has completed. -- Initialise the marker to the current `VER` only when Commonlib identifies a genuinely new Vault with no pending review. A configured existing Vault with a missing or invalid marker requires review instead of being silently accepted. +- Initialise an absent marker to the current `VER` when no other compatibility reason requires review. This applies to both new and configured existing Vaults. An invalid marker still requires review. - Defer database compatibility evaluation for an existing unconfigured Vault. It cannot replicate, so do not persist a misleading pause or acknowledge its missing marker while onboarding is still pending. Keep the marker absent so a later configured start evaluates the same state before ordinary synchronisation. -- Treat a missing marker on a configured Vault as an ambiguous device transition. Copying or restoring a Vault, or opening it with a new Obsidian profile, can preserve settings and database files without preserving device-local storage. Do not infer acknowledgement from an empty local database: a recovery operation, partial copy, or remote-first setup can also produce that state. Explain these cases and require an explicit decision in the compatibility dialogue. +- A missing device-local marker alone is not evidence of incompatibility. A new device, a copied or restored Vault, a new Obsidian profile, or settings imported into another database namespace may have no marker. Initialise it without opening a review when all other checks permit this. Keep remote format, feature, and settings checks independent of this local baseline. - Derive one structured pause from the acknowledged database version, Commonlib's settings-migration state, and any persisted legacy review message. Persist the generic `versionUpFlash` message without changing any automatic synchronisation setting, because Commonlib already treats that field as a replication gate. - Treat non-empty `versionUpFlash` as a runtime replication gate. Standard and one-shot replication must stop before remote work begins. - Apply the same ordinary replication policy to P2P pull, push, and peer-requested synchronisation. An explicitly confirmed Fetch or Rebuild may bypass the ordinary policy because it is the operation selected to construct or recover the local state. - Present the reason in a dedicated dialogue after the Obsidian layout is ready. The details view is explanatory only and returns to the summary before any decision can be made. The safe default and closing either dialogue keep synchronisation paused. A persistent Notice and a command allow the dialogue to be reopened without using the settings pane. - Let the person read focused compatibility details without presenting the whole release history as a safety instruction. The Change Log remains a manually opened release-history pane and contains no compatibility acknowledgement control. -- Offer an explicit resume action only when every reason is recoverable in the running implementation. An upgrade, a missing or invalid marker on an existing Vault, and a reviewed migration from an older settings schema are resumable after all devices have been updated. A downgrade from a newer acknowledged `VER`, or settings saved by a future schema, cannot be acknowledged by the older installation. +- Offer an explicit resume action only when every reason is recoverable in the running implementation. An upgrade, an invalid marker on an existing Vault, and a reviewed migration from an older settings schema are resumable after all devices have been updated. A downgrade from a newer acknowledged `VER`, or settings saved by a future schema, cannot be acknowledged by the older installation. - On resume, clear `versionUpFlash` and persist that fail-closed change before recording the current `VER` as acknowledged. If saving fails, restore the gate. Reapply settings only after the marker has advanced so that the previously configured synchronisation behaviour can resume without reconstruction. -- Preserve the original legacy review message as a structured reason when no more specific database or settings-schema reason is available. Escape it before including it in Markdown UI. +- Preserve the original legacy review message as a structured reason when no more specific database or settings-schema reason is available. This includes a previously saved generic pause: its original cause cannot be inferred from an absent marker, so it still requires explicit resume. Escape it before including it in Markdown UI. - Continue to reject a remote version document which is newer than the running implementation. That receiver-side check is independent of the local upgrade review. +- From remote generation 13, assess the `used_features` list in that document as a separate compatibility dimension. A client must recognise every listed feature before it interprets the database or runs maintenance which depends on Metadata. Declare a feature before writing its representation, and retain the declaration while older data may depend on it. An unknown identifier is reported as text without requiring a descriptive label in that client. +- Do not advance the device-local `VER` acknowledgement merely because a remote feature is introduced. The remote generation and its feature list govern remote admission; `VER` remains the local compatibility review gate. Connecting to a generation-12 database does not promote it solely because the client understands generation 13. ### Onboarding activation and initialisation @@ -76,7 +78,7 @@ Keep configured-state inference separate from new-Vault initialisation. If an ex - Preserve the existing ordered flag-file recovery handlers: SCRAM at priority 5, fetch-all at priority 10, and rebuild-all at priority 20. These files express an explicit recovery instruction and may invoke their focused storage or rebuild service while ordinary replication remains gated. - Present the compatibility review at priority 30, after any selected recovery operation. A recovery handler which cancels start-up, keeps SCRAM active, or schedules a restart returns `false`, so the current process does not open a competing compatibility dialogue. If recovery completes and start-up continues, the dialogue opens before normal synchronisation is allowed to resume. - Keep database preparation independent of an unanswered compatibility dialogue, because the compatibility gate already blocks replication. Before Config Doctor begins its interactive checks, await the active initial review so that the two update dialogues cannot overlap. -- Never mark compatibility as acknowledged merely because fetch, rebuild, or local database reset completed. The person must still use the explicit resume action. This keeps destructive recovery intent separate from protocol and settings compatibility acknowledgement. +- Never acknowledge a pending compatibility review merely because Fetch, Rebuild, or local database reset completed. The person must still use the explicit resume action for that review. This keeps destructive recovery intent separate from protocol and settings compatibility acknowledgement. ## Consequences @@ -85,20 +87,20 @@ Keep configured-state inference separate from new-Vault initialisation. If an ex - An internal compatibility change remains fail-closed for replication, but it no longer destroys the person's synchronisation preferences. - A new installation has no previous internal-version marker and therefore does not show an upgrade review. Its initial settings and onboarding remain responsible for keeping replication disabled until configuration is complete. - An existing unconfigured installation also remains on onboarding without a compatibility warning. Unlike a genuinely new Vault, it does not receive an acknowledgement marker; activation leaves the compatibility decision for its next configured start. -- A copied or restored configured Vault can show a one-time compatibility review on its new device or profile. This is intentional even when its local database appears empty, because emptiness does not prove how the Vault was produced. +- A copied or restored configured Vault starts without a review when its device-local marker is absent and no other review is pending. Known version differences, invalid markers, settings-schema issues, and saved reviews still require the appropriate action. - A genuinely new Vault receives current recommendations without applying them as fallbacks to an existing configuration. It remains inert until onboarding is accepted. - Accepted new-device and existing-device setup cannot enable ordinary processing before the selected Rebuild or Fetch has been reserved. - An older installation cannot dismiss evidence that a newer implementation or settings schema has already been used on the device. - The Obsidian-specific dialogue depends only on a host-neutral compatibility result and the injected confirmation capability. Commonlib remains responsible for settings migration, device-local storage, and the replication gate. -- A future incompatible database change must increment `VER`, provide an actionable review message, verify the remote version negotiation, and test both the pending and acknowledged states. A major SemVer increase without those changes has no database-compatibility effect. +- A future local database change which requires compatibility review must increment `VER`, provide an actionable review message, and test both the pending and acknowledged states. A new remote representation must declare its feature before use and verify remote admission independently. A major SemVer increase alone has no database-compatibility effect. ## Verification -- Unit tests verify new-Vault initialisation, upgrades, missing and invalid markers, downgrades, future settings schemas, legacy marker migration, acknowledgement ordering, and save-failure recovery while retaining automatic synchronisation choices. +- Unit tests verify initialisation of missing markers in new and existing Vaults, upgrades, invalid markers, downgrades, future settings schemas, retained earlier reviews, legacy marker migration, acknowledgement ordering, and save-failure recovery while retaining automatic synchronisation choices. - Commonlib package tests verify conservative stored-setting completion, independently mutable new-Vault settings, legacy file-name case normalisation, future-schema protection, and the focused settings entry from a clean consumer. - Host unit tests verify new-Vault factory use, conservative import paths, the unconfigured start-up gate, deferred compatibility evaluation and later re-evaluation, flag-before-settings ordering, rollback when the flag cannot be reserved, ordinary configured edits, and compatibility acknowledgement persistence. - Unit tests verify that a pending review is honoured by the packaged Commonlib replication service before remote activity begins. - Unit and Compose tests verify that ordinary P2P replication observes the policy, explicit P2P rebuild uses the setup bypass, and replacement leaves host actions on the current replicator. - A real-Obsidian settings test verifies the dedicated summary and details dialogues, captures representative screenshots, confirms that the acknowledged internal version advances only after explicit resume, and confirms that the Change Log contains no acknowledgement control. -- The real-Obsidian CouchDB workflow starts from configured plug-in data without a device-local marker, verifies the copied-or-restored Vault explanation, resumes through the actual dialogue, and then completes remote metadata, chunk, and activity checks. The two-Vault workflow performs the same review once per isolated Vault before reusing the acknowledged device state for later process launches. +- The real-Obsidian CouchDB workflow starts from configured plug-in data without a device-local marker, verifies that it is initialised without a pause, and completes remote Metadata, Chunk, and activity checks. The two-Vault workflow checks the same automatic initialisation and reuses the profile state on later launches. The Object Storage Setup URI and QR workflows complete Fetch and a two-device round trip without an acknowledgement action, and check the marker after restart. The QR fixture carries a distinct database suffix and checks its namespace and marker before Fetch resets the local database using the receiving device's own suffix. - Unit tests fix configured Vault admission at priority 1, the three flag-file recovery priorities at 5, 10, and 20, and compatibility review at priority 30. A recovery which stops start-up therefore cannot race the compatibility dialogue. diff --git a/docs/design_docs/chunk_retrieval_and_waiting.md b/docs/design_docs/chunk_retrieval_and_waiting.md index 81038d92..17d93c71 100644 --- a/docs/design_docs/chunk_retrieval_and_waiting.md +++ b/docs/design_docs/chunk_retrieval_and_waiting.md @@ -53,7 +53,9 @@ For CouchDB, `readChunksOnline` changes what normal replication includes, not th | `true` | No | Primary chunk delivery after metadata arrives. | | `false` | Yes | Recovery fallback for a chunk which is unexpectedly unavailable locally. | -`concurrencyOfReadChunksOnline` and `minimumIntervalOfReadChunksOnline` affect only the scheduling of CouchDB on-demand requests. They do not change whether a request may be dispatched or which lifecycle a reader observes. Accepted identifiers remain claimed while they wait for a concurrency slot and while the configured interval is applied. A minimum interval of five minutes or more is an exceptional value: the inactivity fuse may release the logical claim before that deliberate pause completes. This safety precedence does not abort the delayed physical request. +`concurrencyOfReadChunksOnline` and `minimumIntervalOfReadChunksOnline` affect only the scheduling of CouchDB on-demand requests. They do not change whether a request may be dispatched or which lifecycle a reader observes. Accepted identifiers remain claimed while they wait for a concurrency slot and while the configured interval is applied. Backoff releases the physical concurrency slot but retains logical ownership. Eligible retries and new identifiers can share a batch of up to 100 identifiers. An owned timer wakes the queue at the earliest eligible retry without requiring a new event. New arrivals do not reset existing retry times, and eligible older work precedes newer queued work. + +After every wait or asynchronous local recheck, the fetcher checks the configured interval against the latest shared request time and reserves its start synchronously. A minimum interval of five minutes or more is an exceptional value: the inactivity fuse may release the logical claim before that deliberate pause completes. An expired claim is not dispatched after the pause; an already-running physical request is not aborted by the fuse. ## Wait State Machine @@ -62,11 +64,12 @@ For CouchDB, `readChunksOnline` changes what normal replication includes, not th 3. Register one shared waiter per missing identifier. 4. If policy permits direct fetch, emit `missingChunks`. `ChunkFetcher` synchronously creates the per-identifier claim before the event dispatch returns. 5. Observe both the matching claim and `finiteReplicationActivityCount`. -6. Resolve immediately if a valid chunk or explicit remote-missing event arrives. -7. If an observed producer remains active, do not charge elapsed time against an arrival budget. -8. When all observed producers end, bypass the cache and read the identifiers from the local database once. -9. Return the rechecked chunk, or return unavailable. Do not add another fixed grace after the authoritative boundary. -10. If no producer is observable after synchronous dispatch, return unavailable immediately. +6. Resolve immediately if a valid chunk or terminal explicit remote-missing event arrives. +7. If a successful direct-fetch response omits an identifier, apply the per-identifier retry policy below. Settle identifiers present in a partial result and retry only those which remain absent. +8. If an observed producer remains active, do not charge elapsed time against a general arrival budget. +9. When all observed producers end, bypass the cache and read the identifiers from the local database once. +10. Return the rechecked chunk, or return unavailable. Do not add another fixed grace after the authoritative boundary. +11. If no producer is observable after synchronous dispatch, return unavailable immediately. If new relevant activity starts while the final database recheck is pending, that result becomes stale. The waiter remains active until the newer producer completes and a current recheck finishes. @@ -84,18 +87,30 @@ The continuous live channel is intentionally excluded because it has no completi ## Meaning of an On-demand Claim -An accepted identifier remains claimed from synchronous queue acceptance through throttling, physical fetch, validation, local persistence, and terminal event delivery. The claim is identifier-scoped because a global remote-work count cannot say whether unrelated work can provide this chunk. +An accepted identifier remains claimed from synchronous queue acceptance through throttling, physical fetch, validation, local persistence, retry delays, and terminal event delivery. The claim is identifier-scoped because a global remote-work count cannot say whether unrelated work can provide this chunk. -The claim finishes when the fetcher has recorded an outcome for the identifier. A transport error, missing active replicator, or invalid result releases the claim without emitting an explicit remote-missing result unless the remote actually supplied that information. +The claim finishes when the fetcher has recorded an outcome for the identifier. A successful first omission schedules a two-second retry even if finite replication is already inactive. While finite replication remains active, each subsequent omission increases that identifier's delay by two seconds, up to ten seconds: `2, 4, 6, 8, 10, 10, ...`. Joining a different batch does not reset its retry stage. Each retry first bypasses the local cache and disables further remote dispatch and delivery waiting for its local recheck. + +When the observed finite count falls to zero, remaining backoff is interrupted. The fetcher rechecks local persistence and makes a final remote probe only for still-absent identifiers, respecting concurrency and minimum request spacing. A pre-completion in-flight lookup cannot count as that final probe: if it omits the identifier, a subsequent post-completion lookup is needed, without overlapping requests for the same identifier. If another finite operation ends during the final probe, its negative result is stale too. The current final successful omission emits the terminal explicit remote-missing result and settles the current read. No retry remains for a future synchronisation. + +A transport error, missing active Replicator, or invalid result releases the claim according to its existing terminal path rather than entering this missing-result retry. The retry gate is finite replication alone: neither the fetcher's own claim nor broader bounded remote work keeps it alive. There is no attempt limit or absolute elapsed limit while finite replication continues. All retry state is in memory; destruction and inactivity expiry remove queued work and its timer. + +Each request retains the identity of the claims it accepted. If another read claims the same identifier after an earlier claim settles or expires, the earlier request cannot release the replacement claim, refresh its fuse, or report unavailability for it. This also applies when a partial batch has already settled one identifier but is still retrying another. + +The status indicators count two disjoint sets of pending on-demand Chunk identifiers. `🛄` shows identifiers with no successful missing response yet; `🔁` shows identifiers omitted at least once, including backoff, retry requests, and the final probe. Thus `🛄3 🔁2` means five pending identifiers. The atomic `chunkFetchCounts` snapshot provides this classification, while `collectingChunks` retains their total for the existing restart-deferral check. Moving between categories does not change that total. + +Each fetcher contributes its unique accepted identifiers from queueing through terminal delivery. Repeated requests and retry attempts do not increase the count. Settled, expired, and destroyed claims leave the count; one fetcher's teardown preserves another fetcher's contribution. These are not counts of replication connections or all missing Chunks. Zero means that no on-demand claims remain, not that every Chunk was retrieved successfully. ## Meaning of the Five-minute Value -The five-minute value is an inactivity leak fuse for an accepted on-demand claim. It is the only elapsed duration in this state machine, and it is not a normal terminal condition. +The five-minute value is an inactivity leak fuse for an accepted on-demand claim. It is not a normal terminal condition and is distinct from the backoff which schedules identified follow-up lookups. The fuse bounds retention if a faulty activity runner never enters its task, a Promise never settles, or a transport stops making observable progress. It prevents the per-identifier claim and waiter from remaining live forever. Once the bounded activity callback has entered, releasing the claim also allows Wake Lock, application-lifecycle deferral, and the remote-work indicator associated with that callback to finish. Observable progress rearms the fuse. Five minutes is a conservative operational ceiling rather than a measured chunk-arrival expectation. It must not be used to infer that the remote lacks a chunk, and it does not abort the physical request. `fetchRemoteChunks` does not yet accept an `AbortSignal`, so the request may complete after the logical state has been released. Transport cancellation and transport-specific deadlines are separate future work. +Backoff does not resolve the waiter by elapsed time or prove that another producer will deliver the Chunk. Successful missing responses refresh the inactivity fuse, so retries can continue beyond five minutes while finite replication remains active. This is an intentional distinction between inactivity protection and a total lifetime limit. + The old 5-second and 30-second constants remain exported for source compatibility only. A positive deprecated `ChunkReadOptions.timeout` opts into lifecycle waiting, but its numeric value is ignored. Zero or a negative value still requests an immediate result. New code uses `waitForDelivery` explicitly. ## Test Obligations @@ -110,6 +125,17 @@ Changes to this behaviour must keep automated coverage for: - overlapping finite operations and overlapping per-identifier claims; - activity restarting while a local recheck is pending; - direct fetch queueing, throttling, persistence, and terminal notification; +- an autonomous two-second retry after a first successful omission, with bounded remote activity retained throughout; +- per-identifier `2, 4, 6, 8, 10, 10, ...` backoff while finite replication is active; +- backoff releasing physical concurrency, mixed-stage batching, and eligible retries not being starved by new work; +- expiry of the earliest queued claim preserving the scheduled retry for later identifiers; +- finite completion interrupting backoff and pre-completion in-flight requests requiring a current final probe; +- local persistence avoiding an unnecessary retry, including completion during request-interval throttling; +- partial fetch results settling available identifiers and retrying only absent identifiers; +- partial-batch completion and expired-request responses preserving replacement claims; +- disjoint initial and retry counts retaining queued identifiers without duplicates and releasing only settled ownership; +- concurrent request starts respecting the configured interval after retry and throttle waits; +- terminal unavailability after a current final successful omission; - explicit remote absence versus transport or replicator failure; - runner rejection, cancellation, teardown, and an operation which never enters its task; - leak-fuse refresh at observable progress points; and diff --git a/docs/design_docs/configurable_id_derivation.md b/docs/design_docs/configurable_id_derivation.md new file mode 100644 index 00000000..8a88ce5f --- /dev/null +++ b/docs/design_docs/configurable_id_derivation.md @@ -0,0 +1,515 @@ +--- +date: 2026-09-29 +commonlib-version: "0.1.33" +self-hosted-livesync-version: "1.0.32" +status: unreleased +--- + +# Configurable ID derivation + +## Purpose and baseline + +Introduce an optional, saved secret for deterministic Chunk IDs and obfuscated +Metadata document IDs. This allows an E2EE passphrase to change without also +changing those IDs, and allows their derivation to use an independent secret. +Identical inputs must produce identical IDs on participating devices so that +Chunks can be reused and edits to the same path share one document identity. + +The baseline is [PR #1222](https://github.com/vrtmrz/obsidian-livesync/pull/1222), +including its passphrase-persistence correction at commit +`126d6eadb858a79a08ad7f600061e54fc8d31196`. Commonlib `0.1.33`, published with +the `next` tag, provides the construction described here. It replaces the +independent Chunk algorithm from the `0.1.32` prerelease without a +compatibility branch or a new settings version. Legacy ID generation remains +unchanged. LiveSync pins the published `0.1.33` package and its registry +integrity in the lockfile. +Its [Internal Metadata encryption design](https://github.com/vrtmrz/obsidian-livesync/blob/126d6eadb858a79a08ad7f600061e54fc8d31196/docs/design_docs/internal_metadata_encryption.md) +remains the basis for Properties encryption and CouchDB feature admission. +This document records an unreleased LiveSync feature. It does not select a +plug-in release version. + +## Feasibility + +The change is feasible within the existing architecture. Commonlib already +centralises Chunk hashing, path-to-ID conversion, settings persistence, and +Setup URI encoding. Chunk reads follow stored IDs, so changing the generator +does not require a new Chunk reader or content representation. + +The work spans Commonlib and its consumers. The principal constraints are +agreement on document IDs, complete propagation of the saved secret, and cache +behaviour after a setting change. The construction and transport-specific +agreement checks are described below. No database migration framework is +required. + +## Scope + +| Value or operation | Proposed behaviour | +| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Encrypted Chunk IDs | Use the saved ID secret in the new mode. Keep legacy generation when the option is absent. | +| Obfuscated Metadata document IDs | Use the same saved secret with a separate derivation purpose. Preserve existing path normalisation and namespace handling, including ordinary files, `i:`, `ix:`, and supported legacy `ps:` entries. | +| Unobfuscated document IDs | Retain the current path-based identity. | +| Content and Properties encryption | Continue using the E2EE passphrase and existing encryption format. | +| CouchDB/PouchDB `_rev` | Retain existing revision generation and replication behaviour. | +| Internal content digests and transport bookkeeping | Retain existing behaviour unless they directly construct one of the IDs above. | + +Document IDs are already assigned in the local database. Properties encryption +protects the path and other fields during transfer, while preserving `_id`. +Consequently, the saved ID secret must reach local path conversion as well as +remote-facing code. Path Obfuscation continues to control whether this +conversion is used; this proposal does not enable it automatically. + +Journal keys which incorporate document IDs inherit the resulting IDs. They do +not need another secret. Content digests inside encrypted Customisation Sync +content also do not need a separate setting. + +Automatic migration or enablement of existing or already migrated users, +Setup URI expiry or revocation, QR format security changes, revision redesign, +remote-only E2EE passphrase rotation, and a new remote configuration management +protocol are outside this change. + +## Input and saved state + +New Vault setup selects independent ID derivation and a random source by +default when E2EE is enabled. An existing Vault with no saved key retains +legacy mode until the user selects a new key explicitly. The setup dialogue +shows three radio choices: + +1. Keep current configuration, selected by default for an existing Vault. It + retains the saved key when present and otherwise retains legacy ID + generation. A small description below this choice shows which configuration + is currently saved. In legacy mode, changing the E2EE passphrase still + changes IDs. +2. Generate a random ID key, selected by default for a new Vault. +3. Set an ID key. Three nested radio choices derive it once from the current + E2EE passphrase, accept a source string, or import a tagged recovery code. + Only the latter two show the text input. + +The action is not persisted. An ordinary source is converted to a key when the +settings are applied, and then discarded. A tagged `sls-id-v1:` recovery code +imports its exact 256-bit key without deriving it again, including when pasted +into the source-string input. The recovery-code choice accepts only tagged +codes. A malformed tagged code is rejected. If either input is empty, a saved +key is kept; without a saved key, the dialogue requests input. Changing the +E2EE passphrase later preserves the saved ID key. Cancelling or failing to +save preserves the previous settings. + +The source itself cannot be recovered from its key. A user can explicitly +display and copy the saved key as a tagged recovery code on the local device; +it is hidden when the dialogue opens. The dialogue warns that anyone who needs +recovery after losing every device should save that code or choose a source +they can reproduce. +Turning E2EE off retains the saved value but suspends its use for ID generation. +The setup dialogue disables new ID-key configuration while E2EE is off. Turning +E2EE on again reactivates the same value. Existing E2EE re-encryption and +Rebuild requirements still apply when the passphrase changes. + +The source-input warning concerns only that input. The E2EE passphrase retains +its separate, existing storage behaviour. The recovery code contains the actual +saved ID key and must be handled as a secret. + +Settings need to represent legacy mode or a supported version plus a derived +secret. Final field names belong in Commonlib. A declared new version with a +missing, malformed, or unavailable secret is an error; it must not silently +fall back to legacy generation. Loading or exporting an already derived value +must not derive it again. + +## Deterministic derivation + +The required contract is: + +```text +source string --versioned derivation at save--> saved ID secret +saved ID secret + Chunk content ------------> Chunk ID +saved ID secret + canonical path -----------> obfuscated document ID +E2EE passphrase ----------------------------> content and Properties encryption +``` + +Derivation is offline and deterministic across supported runtimes. Its version +fixes the text encoding, treatment of Unicode and whitespace, salt, parameters, +and saved representation. It must not depend on server state, the E2EE Security +Seed, a device identifier, time, or device-specific iteration calibration. +Repeated saving of the same source under the same version produces the same +value. Reusing that source in another Vault consequently also reuses the value. + +Version 1 uses PBKDF2-HMAC-SHA-256 with 310,000 iterations, the UTF-8 bytes of +the source after NFC normalisation, the fixed salt +`self-hosted-livesync:id-source:v1`, and a 256-bit output encoded as 64 lowercase +hexadecimal characters. Whitespace is preserved. The existing +`idDerivationVersion: 1` setting, saved-settings fields, and recovery-code format +remain unchanged; this implementation change does not add an ID format version +or migration path. + +Obfuscated document IDs continue to use the saved 256-bit value directly as the +key for full HMAC-SHA-256. Their message remains UTF-8 encoding of +`self-hosted-livesync:id-v1:document`, a NUL byte, and the canonical path. +Agreement proofs likewise retain their existing full-HMAC messages. Neither +path uses the new Chunk-specific cache. + +For encrypted Chunk IDs, first compute xxHash64 over the UTF-8 bytes of the +exact Chunk text with seed 0. Encode its result as a fixed 16-character +lowercase hexadecimal prehash. Derive a Chunk-specific subkey from the saved +32-byte value, then HMAC the domain-separated prehash: + +```text +Kchunk = HMAC-SHA-256( + saved 32-byte key, + UTF8('self-hosted-livesync:id-v1:chunk-key:xxhash64') +) +prehash = fixed16lowerhex(xxHash64(UTF8(exact Chunk text), seed 0)) +Chunk ID = full64lowerhex(HMAC-SHA-256( + Kchunk, + UTF8('self-hosted-livesync:id-v1:chunk:xxhash64' + NUL + prehash) +)) +``` + +The resulting Chunk ID is the full 64-character lowercase hexadecimal HMAC +output. Existing namespace prefixes remain outside the digest. Keyed Chunk IDs +use this fixed prehash regardless of `hashAlg`; legacy mode and its existing +hash selection remain unchanged. + +The Chunk-specific HMAC subkey and imported key, along with the WASM xxHash64 +generator, are cached per `HashManager` and active saved key. Concurrent +preparation is shared. Replacing the manager or key, turning E2EE off, or +returning to legacy mode clears the cache; failed preparation can be retried. +This cache adds no persistent state. The current E2EE setting also selects the +legacy encrypted or plain Chunk route when a manager remains alive while E2EE is +turned off. + +### Security properties and limits + +A derived value remains a secret capable of generating IDs. Hashing does not +increase the entropy of its source. A password KDF adds guessing cost; it does +not make a weak source strong. HKDF alone does not provide that password +stretching. See [RFC 8018](https://www.rfc-editor.org/rfc/rfc8018.html#section-8) +and [RFC 5869](https://www.rfc-editor.org/rfc/rfc5869.html#section-4). + +The random default separates ID generation from the E2EE passphrase. Deriving +both secrets from the same source retains a relationship with the original +passphrase, even after that passphrase changes. An independent source with +sufficient entropy provides the intended separation. HMAC with purpose +separation is the construction for using that secret; see +[RFC 2104](https://www.rfc-editor.org/rfc/rfc2104.html). +The fixed derivation salt means that reusing a source across Vaults reuses the +ID key; use separate sources when independent Vault identities are required. + +CouchDB authentication and database access control remain the first access +boundary. This design also considers exposure through database credentials, +server administration, or backups. It does not promise to conceal equality, +document counts, revision history, or ciphertext lengths from database readers. + +For Chunk IDs, xxHash64 is a public, non-cryptographic prehash. Distinct Chunk +texts which produce the same 64-bit prehash produce the same ID under the same +saved key. The final 256-bit HMAC does not restore distinctions lost at that +stage, so collision resistance for Chunk IDs is bounded by xxHash64 rather than +by the HMAC output width. This limit is an accepted trade-off for bounding the +content processed by HMAC. + +The independent ID key preserves existing file contents, Chunk representation, +and `_rev` behaviour. It does not change the privacy properties of those +formats. Payload and virtual file padding remain outside this change. + +## Sharing, import, and storage + +Include the saved derived value and its version in Setup URIs, protected by the +existing, separate Setup URI passphrase. Import the saved value directly. +Additional devices therefore need neither the original source nor another +derivation step. Manual setup can reproduce it by entering the same source and +version, or by importing the tagged recovery code. After an E2EE passphrase +change, the current passphrase cannot be assumed to reproduce the old ID secret. + +The standalone Setup URI generator uses a fresh random 256-bit ID key by +default, prints its tagged recovery code, and accepts that code for repeatable +generation for the same Vault. `id_mode=legacy` selects the old ID behaviour. +Running it again without the code produces a different key, so the generated +URI must not be treated as an update for an existing remote. + +QR sharing includes the same fields through the existing QR representation and +warnings. Its current payload is not encrypted like a Setup URI. The agreed +scope accepts that existing sharing model and user responsibility for keeping +QR material private; it adds no QR storage or expiry mechanism. + +| Boundary | Required handling | +| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Existing settings and old complete Setup URI/QR/P2P imports | Missing fields select legacy behaviour. Do not inherit an unrelated value already present on the receiving device. | +| Ordinary partial setting updates | Preserve the current secret and version when neither is supplied. | +| New-format imports | Validate version and value together before applying or starting database work. | +| Local persistence | Integrate the secret explicitly with sensitive-configuration encryption and loading. Adding an arbitrary field does not currently provide this protection. | +| Reports, logs, and Markdown settings | Redact the secret in reports and logs; treat it as a credential in the existing Markdown export/import policy. An export which omits credentials must omit this secret. | +| Remote profiles, CLI, WebApp, WebPeer, and direct writers | Carry the effective value and version through every supported configuration path. A selected new mode must never degrade silently to legacy mode. | + +Setup URI JSON encoding can carry ordinary new settings, but QR encoding uses +an explicit key-index table. Append stable QR entries without reordering old +ones. Complete imports and partial edits must have distinct missing-value +semantics even where the current implementation merges settings objects. +In particular, `SetupManager` currently merges decoded URI settings over the +receiving device's settings. Complete imports must normalise the new fields +before that merge to prevent accidental inheritance. + +## Compatibility and changes to existing data + +| Difference or change | Consequence | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| Different Chunk derivation only | Existing content remains readable through Metadata `children`; new writes can duplicate Chunks and reduce reuse. | +| Different obfuscated document ID derivation | The same path can become separate documents. Treat this as an incompatible configuration requiring resolution. | +| New E2EE passphrase, unchanged saved ID secret | IDs remain stable for unchanged content, paths, and other ID settings. Re-encryption still requires the existing E2EE workflow. | +| Enabling, replacing, or disabling the option with Path Obfuscation active | Document identity changes. Use the established authoritative Rebuild and secondary-device Fetch workflow. | +| Existing installation with no new option | Preserve its exact legacy behaviour; do not derive or copy a value during upgrade. | + +Copying the legacy passphrase into the new derivation does not preserve legacy +IDs, because the derivation itself changes. This proposal therefore makes no +automatic or seamless migration promise. Before an explicit transition, update +and stop the participating devices, select the authoritative data, and use the +existing [Rebuild and Fetch procedures](../recovery.md). Share the resulting +configuration before other devices rejoin. One-entry +[Metadata ID repair](metadata_document_id_validation_and_repair.md) does not +perform this transition. + +Commonlib's Chunk cache includes content-to-ID lookup before hashing. Changing +the hash function alone can keep producing old IDs, and reading old Chunks can +populate that lookup again. The implementation must distinguish read reuse +from the ID selected for a new write, including after manager replacement and +restart. Readers continue accepting referenced legacy Chunks. + +## Agreement checks and older clients + +Keep checks focused on preventing incompatible document identities. Reuse the +existing configuration review and replication admission paths. A mismatch +must not be treated as an automatically alignable Chunk setting when document +IDs depend on it. Show a mismatch or unsupported version without exposing the +saved secret. + +The advertised ID version is used for comparison only. Ordinary Tweak alignment +preserves each device's ID version and key together, including when only Chunk +IDs differ. A document ID mode mismatch requires explicit configuration through +a Setup URI or the matching key, rather than adopting a version without its key. + +For CouchDB, extend the supported feature set in the remote feature contract +introduced by PR #1222, then declare the new requirement before writing data +under it. That mechanism rejects unsupported features at admission and provides +a best-effort stop when an unsupported requirement arrives later. It checks +format support, not equality of saved secrets, and does not make a live +migration atomic. Journal can extend its existing milestone compatibility path; +P2P needs its separate admission handling. The CouchDB feature contract alone +cannot protect those transports. + +The implementation checks up to two remote documents in each ordinary and +internal obfuscated-ID namespace before CouchDB replication or direct writes. +This includes a legacy-mode caller connecting to a remote which uses keyed IDs. +For each available sample it recomputes the ID from the decrypted path; any +mismatch rejects the connection. An empty database, or one with no usable +sample, is reported as unverified and may proceed because there is no observed +document identity to conflict with. A sampled match is evidence, not a proof +that every document has the same identity; an unsampled mixture remains a +limitation of this bounded check. + +When E2EE and Path Obfuscation are both active, Journal stores an +E2EE-encrypted, domain-separated proof in its existing milestone. It is +encrypted before the milestone is uploaded and compared on later connections. +An established milestone without this proof requires a Rebuild before the new +document IDs can be used. Journal advertises a new compatibility range for +keyed document IDs so older clients reject it. P2P compares a +purpose-separated HMAC over a fresh challenge during peer admission; the proof +is not stored. When Path Obfuscation is off, different keys affect only Chunk +IDs, so Journal keeps its legacy compatibility range and P2P does not require +key agreement. Neither transport publishes the key or a plaintext verifier in +Tweak values. CouchDB and direct writers use the document sample check above +rather than a stored verifier. The sample check uses the host's path service +with the attempted settings snapshot so stored non-canonical paths are treated +the same way as ID generation. +The existing `_rev` behaviour for ordinary content remains unchanged. + +## Implementation responsibilities + +The following are the confirmed integration points in the reviewed baseline. +Commonlib paths refer to its package implementation, not a source mirror in +this repository. + +| Owner and entry points | Work | +| -------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Commonlib `HashManagerCore`, concrete hash managers, `PathService`, and `path2id_base` | Select legacy or new derivation consistently; preserve path and namespace semantics. | +| Commonlib `EntryManagerImpls`, `LayeredChunkManager`, and `LiveSyncManagers` | Keep referenced Chunks readable and invalidate or partition generation-dependent caches. | +| Commonlib settings definitions/lifecycle, `SettingService`, `pickEncryptionSettings`, and `API/processSetting` | Own version validation, persistence, copying, imports, Setup URI encoding, and QR slots. | +| Commonlib compatibility assessment and replication implementations | Classify identity differences, protect any comparison data, and enforce supported formats at each transport boundary. | +| Commonlib `API/DirectFileManipulatorV2` | Carry the option through its explicit settings and path-obfuscation configuration. | +| LiveSync `SetupRemoteE2EE.svelte`, `PaneRemoteConfig.ts`, and `SetupManager.ts` | Implement the three configuration actions and three nested ID-key inputs, configured state, local recovery-code reveal, and existing Apply/Rebuild/Fetch choices. | +| LiveSync `replicatorConfigurationIdentity.ts`, `reportTool.ts`, and `ModuleObsidianSettingAsMarkdown.ts` | Replace connections when effective settings change, redact the secret, and apply credential-sharing rules. | +| CLI, browser applications, and setup tools | Use the same Commonlib contract in manual setup and imports; generate new Setup URIs with a reusable random ID key by default. | + +Implement Commonlib changes in its own repository, validate its packed artefact, +and validate LiveSync against that exact dependency before adopting a released +version. Translations remain outside this implementation scope. + +## Validation + +The fixed-vector and cache tests first failed against unchanged Commonlib +`0.1.32`, then passed after the implementation change. Commonlib's 2,036 Unit +tests, type check, package boundary, and isolated packed-package checks pass. +Three Integration tests against real CouchDB and Object Storage verify direct +access, Journal agreement, and rejection before control-document changes. +The same-manager E2EE-off regression was reproduced and fixed. + +LiveSync's 1,049 Unit tests, type and lint checks, production build, and iOS 15 +bundle syntax check pass after installing the exact published `0.1.33` +package. Its tarball matches the validated publication candidate, and all 559 +installed package files match the registry artefact. The resulting bundle is +identical to the one checked before publication. + +Real Obsidian two-Vault checks with the accepted Chunk construction cover +matching-key synchronisation, incompatible document key rejection, and +differing Chunk keys with visible paths. The Review Harness also passes with +the published package, verifying actual ID calculations and report copying +without changing live settings. Its adapter imports `HashManager` through +Commonlib's focused `/hashing` entry, whose package checks cover public types, +Node execution, and browser bundling. + +### Current Chunk calculation performance + +The actual Commonlib `HashManager` implementations were compared in Obsidian +1.12.7 on ARM64 Linux. Six samples rotate all three variants through each +execution position twice. The table reports median total ID calculation time; +1,000 means the total for 1,000 IDs, not the time per ID. Inputs are synthetic. + +| Input | IDs per sample | Legacy xxHash64 | Previous independent HMAC | Updated independent ID | +| --------------------------------- | -------------: | --------------: | ------------------------: | ---------------------: | +| 256-byte text | 1,000 | 4.50 ms | 41.40 ms | 24.45 ms | +| 4 KiB text | 1,000 | 10.00 ms | 96.25 ms | 29.70 ms | +| 32 KiB text | 1,000 | 48.40 ms | 494.40 ms | 68.95 ms | +| 10 MiB binary, default splitting | 103 | 19.60 ms | 192.50 ms | 21.45 ms | +| 50 MiB binary, default splitting | 512 | 99.85 ms | 972.75 ms | 106.65 ms | +| 10 MiB binary, Self-hosted preset | 5 | 24.10 ms | 216.90 ms | 18.50 ms | +| 50 MiB binary, Self-hosted preset | 35 | 118.40 ms | 1,067.00 ms | 91.75 ms | + +The first updated ID, including Chunk-key preparation, took 1.3 ms in this +run. Repeated measurements exclude preparation, warm-up, and pauses. Binary +cases use the actual splitter and Base64 representation; all decoded bytes +and repeated IDs were checked. Splitting, Base64 conversion, database work, +payload encryption, and transfer are outside the measured interval. These +results establish lower ID calculation cost on this host, not a complete +Rebuild speedup or native mobile performance. + +### Native-device ID measurements + +User-supplied Review Harness reports compare the previous and updated builds +on Android 13 and iOS 18.7. Each value is the median total time for 1,000 +independent Chunk IDs, using three samples in each run. + +| Input | Android, previous | Android, updated | iOS, previous | iOS, updated | +| ------------- | ----------------: | ---------------: | ------------: | -----------: | +| 256-byte text | 53.6 ms | 37.8 ms | 21 ms | 20 ms | +| 4 KiB text | 70.9 ms | 43.4 ms | 22 ms | 22 ms | +| 32 KiB text | 151.1 ms | 66.5 ms | 36 ms | 39 ms | + +Android's 32-KiB result takes about 56% less time. The corresponding iOS +result increases by 3 ms per 1,000 IDs; separate runs with three samples do +not establish the cause of that difference. Across these sizes, the updated +independent calculation adds approximately 18–25 ms per 1,000 IDs over each +device's legacy xxHash64 calculation. Save-time key derivation has medians of +46.6 ms on Android and 51 ms on iOS. + +These reports measure synthetic ID calculations, excluding database work, +payload encryption, and transfer. Android's heap samples remain constant, +and iOS does not expose them, so the reports do not establish memory usage or +improvement. The updated build has not been measured on Windows. + +The checks below are historical reference evidence for the predecessor +independent-ID implementation, which used full-content HMAC-SHA-256 for Chunk +IDs. They do not validate the current xxHash64-prehash construction. + +### Historical predecessor checks + +Earlier consumer validation used a local Commonlib `0.1.32` candidate. Clean +installations with npm 10 and npm 11, type checking, lint, Svelte checks, the +production build, and the iOS 15 bundle compatibility check passed. LiveSync +had 1,039 passing Unit tests, six passing Integration tests against real +CouchDB, and seven passing Setup URI utility tests with the frozen Deno +lockfile. + +Predecessor Commonlib candidate checks covered deterministic vectors, Unicode +normalisation, legacy behaviour, encrypted settings persistence, imports, +cache transitions, and transport admission. Its Integration tests against real +Object Storage accept a matching Journal key, reject a different document ID +key before changing the milestone, and allow different Chunk keys when paths +remain visible. A direct-access Integration test against real CouchDB reads +with the same key and rejects a different key before changing the version +document. These library tests complemented the consumer checks for that +predecessor; they were not additional LiveSync Unit tests. + +Real Obsidian 1.12.7 on ARM64 Linux verifies the following consumer boundaries: + +| Boundary | Verified behaviour | +| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| CouchDB synchronisation | Two Vaults exchange notes in both directions with matching document and Chunk IDs. Different Chunk keys also work with Path Obfuscation off. | +| CouchDB rejection | Ordinary replication rejects different or legacy document ID keys before downloading files or changing remote documents and checkpoints. | +| Visible onboarding | Both a separate source and the random default persist an encrypted key, transfer it through a Setup URI, complete Fast Fetch, and synchronise in both directions. The `%`-prefixed E2EE passphrase survives restart. | +| Input and recovery | The radio controls and disabled styling are exercised. An empty first source keeps the dialogue open with an error; empty input keeps an existing key. A recovery code restores the same key. | +| Journal upload | The uploaded documents and Chunks have keyed IDs, and the first Object Storage milestone contains the encrypted agreement proof. | +| Credential-free Markdown | Neither the saved ID key nor its encrypted representation appears in exported settings Markdown. | + +A CLI P2P E2E run with a local relay imports encrypted Setup URIs, transfers a +note with matching keys, and rejects a peer with a different document ID key. +A separate check loads the published `0.1.31` DirectFileManipulator in another +process: it reads a legacy remote, and rejects an independent-ID remote with +or without Path Obfuscation, leaving remote documents and checkpoints +unchanged. This checks the previous library API, rather than an older +Obsidian installation. Bounded sampling tests cover empty and mixed document +collections; they do not establish that every document in a remote is +compatible. + +### Performance reference for the predecessor + +The measurements below are historical results for a local predecessor +Commonlib `0.1.32` candidate which used full-content HMAC-SHA-256 for +independent Chunk IDs. They are reference evidence only, not performance +results for the accepted xxHash64-prehash construction. Both modes enable E2EE +and Path Obfuscation; the legacy baseline uses `xxhash64`. Three trials per +mode alternate their order. These are synthetic corpora and serial local +writes, excluding Vault enumeration, remote payload encryption, and transfer; +they are not timings of the complete Rebuild action. + +Saving an ordinary ID source takes 52–57 ms in Node.js 24, with a median of +56 ms. This PBKDF2 operation happens once when saving the source. Per-Chunk +and per-document IDs use the saved key and do not repeat PBKDF2. + +The actual Obsidian renderer gives these median times for 1,000 serial calls +to the Commonlib hash manager or Path Service, after warm-up: + +| Input | Legacy | Independent ID | +| ------------------------ | ------: | -------------: | +| Distinct 256-byte Chunks | 5.4 ms | 43.3 ms | +| Distinct 4 KiB Chunks | 15.0 ms | 104.8 ms | +| Distinct 32 KiB Chunks | 52.8 ms | 581.7 ms | +| Distinct document paths | 36.5 ms | 50.0 ms | + +These direct calls include no Chunk-content cache hits. The predecessor hash +had a measurable cost, especially when there were many small Chunks. The +local-write experiments exercise splitting, ID generation, Chunk reuse, and +PouchDB writes: + +| Workload and adapter | Legacy median (range) | Independent median (range) | +| ------------------------------------------------------------- | --------------------: | -------------------------: | +| 5,000 text/binary files, 100 MiB, Node PouchDB memory adapter | 102.6 s (87.4–109.3) | 86.6 s (75.4–93.1) | +| 1,000 text files, 19.5 MiB, actual Obsidian local database | 78.7 s (52.0–82.8) | 63.2 s (62.8–63.8) | + +The measurements do not show a large overall slowdown for these workloads, +but the variation does not support a general speedup claim. Both experiments +checked document counts, Chunk-reference counts, and sample content readback. +The Node experiment also checked that every referenced Chunk was present. The +100 MiB corpus includes 250 duplicate files and produces 213,788 Chunk +references to 199,468 distinct Chunks in both modes, preserving reuse. + +For that corpus, stored document JSON grows from 133,157,581 to 154,342,743 +UTF-8 bytes, an increase of 15.9%. The text-only Obsidian corpus produces many +small Chunks and grows from 27,893,656 to 33,594,994 bytes, or 20.4%, including +32 warm-up documents. Longer Chunk IDs occur in both Chunk documents and +Metadata references. Ordinary obfuscated document IDs remain 66 characters. +These totals measure serialised document JSON; physical database and index +growth depend on the adapter and have not been measured. + +### Remaining validation + +Larger binary workloads on mobile, a representative user's Vault, physical +storage growth, and the complete Rebuild wall time remain unmeasured. The +native-device reports above verify the synthetic ID calculation scenario; +desktop E2E and mobile viewport checks do not establish other mobile +operating-system behaviour. URI revocation, QR redesign, and automatic +migration remain outside this change. diff --git a/docs/design_docs/internal_metadata_encryption.md b/docs/design_docs/internal_metadata_encryption.md new file mode 100644 index 00000000..e7d16ec6 --- /dev/null +++ b/docs/design_docs/internal_metadata_encryption.md @@ -0,0 +1,170 @@ +--- +date: 2026-09-27 +commonlib-version: "0.1.30" +self-hosted-livesync-version: "1.0.32" +status: unreleased +--- + +# Internal Metadata encryption and remote feature changes + +This document defines the LiveSync integration of Commonlib's remote feature +contract and encrypted Metadata for Hidden File Sync and Customisation Sync. +It describes unreleased behaviour being implemented in this branch. + +Commonlib's companion `docs/remote-feature-compatibility.md` is the +source of truth for the wire document, identifiers, validation, and shared +assessment. This document owns the application behaviour, settings, Doctor +recommendation, and verification of the Obsidian and CLI integrations. + +## Scope and settings + +Add `encryptInternalMetadata` to the shared encryption settings. A genuinely new +Vault or CLI configuration defaults to true. Existing stored settings and old +Setup URI or QR imports complete an absent value as false. Ordinary partial +setting updates retain the current value. + +The preference applies to CouchDB with E2EE V2 and Property Encryption enabled. +Show the preference as unavailable and explain its prerequisites when they are +absent. Keep Journal and P2P's existing +transport protection and avoid unrelated setting mismatches for those remotes. + +Use the existing HKDF Metadata representation to protect path, creation and +modification times, size, and Chunk references for obfuscated internal entries. +Keep the `i:`, `ix:`, and supported legacy `ps:` document IDs, path conversion, +and content Chunk representation. Read encrypted Metadata independently of the +write preference, including after that preference is disabled. + +The protection leaves document IDs, namespaces, revisions, deletion state, +document counts, and ciphertext lengths visible. It does not encrypt device or +Vault names stored in separate participant records. + +## Enabling the preference + +Changing the preference does not automatically reconstruct a database or gather +all devices' data. It affects subsequent Metadata writes. Unchanged documents +and old revisions can retain plaintext; mixed plaintext and encrypted Metadata +are a supported transition state. + +Strongly recommend the existing manual remote Rebuild workflow when the person +wants existing Metadata protected as well. The person prepares the authoritative +data for that workflow. Describe this distinction in the setting, Doctor reason, +and operational documentation. Do not advertise complete historical protection +merely because the preference is enabled. + +Copy the preference with the other encryption settings when preparing a remote +profile. Recreate a connection when its effective encryption settings change. +Use the existing Tweak assessment and manual mismatch resolution; do not change +the remote's shared policy silently when importing or loading settings. + +## Doctor + +Use Commonlib's existing conditional recommendation rules. Recommend true when +the selected CouchDB settings have E2EE V2 and Property Encryption enabled and +the new preference is false. Do not require Hidden File Sync or Customisation +Sync to be active before offering the recommendation. + +Retain the existing E2EE V2 recommendation for a legacy algorithm. After that +change, ensure the newly applicable Metadata recommendation is not hidden by a +premature `doctorProcessedVersion` update. Advance the Doctor rule revision so +an older completed consultation does not suppress this new recommendation. + +Apply the preference only when the person accepts the recommendation. Include +the existing-data limitation, the manual Rebuild recommendation, and the need +for compatible clients in the explanation. Do not set `requireRebuild` or +`requireRebuildLocal` for this rule: the current host wrapper can schedule those +operations and restart. `recommendRebuild` currently exists only as an unused +rule field, so setting it alone does not display an explanation. + +## Admission and received version documents + +The remote version document is the source of feature requirements. Commonlib +checks it before replication, Fast Fetch, and direct access. The milestone keeps +the existing Tweak comparison and Rebuild lock. An accepted writer declares the +feature before using it, including the writer admitted to a locked rebuilt +remote; an unaccepted device remains blocked by that lock. + +Retain the existing received-version path through `parseSynchroniseResult`, +`enqueueAll`, and `processIfNonDocumentChange`. Replace its numeric comparison +with the shared assessment so unknown names at the same generation are also +reported. Known features, reordered lists, and ordinary revision updates do not +retire the connection. Unsupported or malformed control documents request +retirement through the existing Replicator owner and display the reason. +The callback must not await retirement of the operation which delivered it. + +This is an admission check and a best-effort stop for exceptional changes during +an active connection. It does not fence every queued file application, roll back +accepted writes, or guarantee an atomic change across live devices. Feature +changes are an infrequent administrative operation: update all devices first, +then enable the preference and use the recommended manual Rebuild. Rebuild +locks the remote using the existing workflow; changing this preference alone +does not lock it. The action to proceed without rebuilding explicitly reminds +the person to update every other device, including currently connected devices. + +## Persistence and recovery boundaries + +Do not retain a second feature list, highest generation, or rejection flag in +KV storage. Do not add compatibility checks to pending-work snapshot recovery +or make that recovery a new prerequisite for application readiness. Preserve +the existing queue and startup behaviour. A later attempt checks the current +remote declaration, including after restart. Declared features remain on the +remote when the write preference is disabled because older data can still use +them; manually shortening that declaration is not a supported migration. + +After updating clients, use normal reconnection and the existing Hatch +inspection or Fetch workflow if reconciliation is needed. This feature does not +repair unrelated KV inconsistencies or the existing readiness queue behaviour. + +Garbage Collection V3 is a beta manual operation which begins with an ordinary +bidirectional synchronisation. That admission checks the remote feature +contract; no additional per-step GC checks are introduced. The separate +cleaned-remote recovery path checks the local version document before its +first Chunk-reference count because it does not start with that synchronisation. + +Use the same Commonlib assessment at the CLI, Fast Fetch, and direct-access +boundaries. The Obsidian result processor is one consumer, not the only place +which determines compatibility. Keep unrelated Vaults and databases operational. +Fast Fetch checks the remote declaration before opening or resetting the local +database, both for a fresh Fetch and for checkpoint resumption. + +## Verification and documentation + +Keep focused tests for settings defaults and imports, the Doctor condition +matrix, acceptance and dismissal, connection replacement, and absence of an +automatic Rebuild, Fetch, or restart for this rule. + +Exercise the Doctor choices in real Obsidian as well: decline the consultation, +skip the recommendation with a reminder, dismiss the current Doctor version, +and reopen it through **Run Doctor** to accept. Restart the same Vault and +profile between choices to verify persistence and whether the consultation +reappears. Preserve the local database and existing remote documents throughout +acceptance, then verify that subsequent writes encrypt internal Metadata. + +Keep unit tests for known and unknown feature notifications, generic identifier +presentation, retirement without a circular wait, and the unchanged snapshot +behaviour after KV failure or obsolete snapshot fields. The previous batch +fences, physical-database tracking, and persistent rejection tests are outside +this design; they must not imply an atomic live migration guarantee. + +Use real Obsidian Hidden File Sync and Customisation Sync scenarios to inspect +raw CouchDB Metadata and restore content in another Vault. Check the admitted +writer on a locked remote, unknown-feature rejection before and during +replication, and remote-based rejection after restart. Retain the encrypted +CLI-to-Obsidian interoperability scenario. A future client upgrade that adds +support for an unknown feature is a separate validation boundary. + +Also exercise enabling the preference through the settings UI without Rebuild: +retain unchanged plaintext Metadata, encrypt rewritten entries with stable IDs, +reject a second device's mismatched preference, and restore both representations +after alignment. With the preference subsequently OFF, verify that Fast Fetch +still decodes encrypted Metadata and preserves the remote feature declaration. + +Keep the primary-language settings and troubleshooting guides, the +database-compatibility ADR, and Unreleased notes aligned with this behaviour. +Keep the detailed shared protocol in Commonlib and link to it after publication; +do not maintain another copy of its wire schema here. Translations are a separate +change. Update tested-version evidence when the implementation and its +validation have been accepted. + +Related application contracts: [Replicator architecture](replicator_architecture.md), +[Tweak compatibility](tweak_compatibility.md), and +[database compatibility](../adr/2026_07_release_notes_and_database_compatibility.md). diff --git a/docs/design_docs/time_bound_setup_uri.md b/docs/design_docs/time_bound_setup_uri.md new file mode 100644 index 00000000..bf5ceef6 --- /dev/null +++ b/docs/design_docs/time_bound_setup_uri.md @@ -0,0 +1,425 @@ +--- +date: 2026-09-28 +commonlib-version: "0.1.33" +feasibility-probe-version: "0.1.27" +self-hosted-livesync-version: "1.0.32" +status: implementing +--- + +# Time-bound Setup URIs + +## Purpose and status + +Offer two modes when generating a [Setup URI](../glossary.md): + +- **Ephemeral**, selected by default, derives an effective passphrase from the + entered passphrase and the current fixed time window. +- **Persistent** uses the entered passphrase and the existing URI format + unchanged. It also serves as the compatibility mode for older readers. + +The generation mode choice shows the exact time until which an Ephemeral URI +can be opened through the ordinary reader. Import still requires only the URI and +the entered passphrase. Neither the mode nor a timestamp is stored in the URI. + +The design is technically feasible with the existing encryption primitives. +An executable protocol probe passes 22 cases against Commonlib 0.1.27 and +octagonal-wheels 0.1.54. The implementation was first published as Commonlib 0.1.32 +on the npm `next` tag. LiveSync now pins Commonlib 0.1.33 from that tag in its npm +dependency and independent Deno tool imports. A mobile performance bound remains +outstanding. + +This document records the proposed key derivation and integration contract. The +companion probe demonstrates them without changing an application entry point. + +## Scope + +The first version offers Ephemeral and Persistent only. Ephemeral uses one +fixed seven-day window shared by every implementation. Arbitrary start dates, +custom end dates, selectable window lengths, and rolling seven-day lifetimes +are outside this version. + +Keep the current settings filtering, remote profiles, main and P2P selections, +and short/full export variants. Time binding affects opening the exported +settings; it does not alter Vault encryption, remote credentials, replication, +or settings already imported by another device. + +The existing `settingsQR` format and QR aggregator are separate sharing paths. +They remain outside this design and must not be presented as time-bound. + +## Time window + +Use Unix milliseconds and the following protocol constants: + +```text +windowMilliseconds = 604800000 +windowNumber = floor(nowMilliseconds / windowMilliseconds) +windowStart = windowNumber * windowMilliseconds +usableUntil = (windowNumber + 1) * windowMilliseconds +``` + +The anchor is the Unix epoch, `1970-01-01T00:00:00Z`. Consequently, boundaries +fall on Thursdays at 00:00 UTC. This is a protocol convention, independent of +the device's locale, time zone, daylight-saving rules, and calendar week. +The anchor and window length are part of the derivation profile. Changing them +requires an explicit compatibility design; there is no visible version field +from which an importer can discover a different time condition. + +For example, a URI generated at `2026-09-28T12:00:00Z` belongs to the window +`[2026-09-24T00:00:00Z, 2026-10-01T00:00:00Z)`. Ordinary import rejects it at +the end instant. Generating it one second before that instant leaves one +second of availability. The UI must not describe this as seven days from +generation. + +Use safe, non-negative integer timestamps without 32-bit coercion. The +reader tries only its current window. There is no previous-window allowance, +future-window search, modulo wraparound, or grace period. Devices whose clocks +fall on different sides of a boundary can disagree; local date formatting +does not affect the calculation. + +## Passphrase derivation and encryption + +The time factor follows the counter construction used by +[TOTP, RFC 6238 section 4.2](https://www.rfc-editor.org/rfc/rfc6238.html#section-4.2). +This is a time-bound encryption format, not a TOTP authentication protocol: +there is no six-digit code, trusted validation server, or single-use state. + +Reuse Commonlib's current `encryptString` and `decryptString` path. It uses +octagonal-wheels' salted PBKDF2/HKDF and AES-GCM implementation. Persistent +passes the entered passphrase directly to that path. Only Ephemeral applies +a full-length transformation: + +```text +if mode == "persistent": + effectivePassphrase = enteredPassphrase +else: + hmacKey = SHA-256(UTF-8(enteredPassphrase)) + context = JSON.stringify([ + "livesync/setup-uri", + "tb1", + "ephemeral", + windowNumber + ]) + effectivePassphrase = lowercaseHex(HMAC-SHA-256(hmacKey, UTF-8(context))) +encryptedSettings = encryptString(preparedSettingsJSON, effectivePassphrase) +``` + +The mode strings are exactly `ephemeral` and `persistent`. JSON encoding, +field order, lowercase hexadecimal, and the domain/profile strings are part +of the proposed Ephemeral derivation. `tb1` is an internal derivation identifier; +it is not a URI prefix or stored field. Persistent applies no new transformation. + +The initial SHA-256 provides a fixed-length HMAC key, including for an empty +low-level input. It does not replace password stretching: the existing +encryption function still performs PBKDF2. Do not trim or normalise the +entered passphrase within this transformation. Existing host requirements for +a non-empty passphrase remain in force; this design adds no new password +policy. + +At the assessed dependency versions, the encryption path uses PBKDF2-SHA-256 +with 310,000 iterations, HKDF-SHA-256, and AES-256-GCM with a 128-bit tag. Its +`%$` payload includes the material needed for decryption. The PBKDF2 salt may +be reused within a session; the IV and HKDF salt are generated for each +encryption. Retain these existing semantics rather than claiming a new +per-URI PBKDF2 salt or introducing another encryption implementation. + +For the synthetic passphrase `test-passphrase`, fixed derivation vectors are: + +```text +context: ["livesync/setup-uri","tb1","ephemeral",1234] +effectivePassphrase: b39361c51f0b7bd835554db1dffbc9a540fb30789aa62bf53e39e07d1073013b + +mode: persistent +effectivePassphrase: test-passphrase +``` + +The probe checks the Ephemeral Web Crypto output against a value calculated +separately through Node's SHA-256 and HMAC interface, and checks that Persistent +retains the exact input. Encryption remains randomised; these vectors specify +the effective passphrase, not the complete URI. + +This composition needs Commonlib changes but no new cryptographic dependency +or remote service. The prototype verifies interoperability with the existing +encryption path; it is not an independent cryptographic audit. + +## URI format and decoding + +Keep the existing URI prefix and encrypted representation without a new marker: + +```text +obsidian://setuplivesync?settings= +``` + +Both modes use the existing `%$` encrypted representation. There is no mode +flag, timestamp, window number, duration, derivation-version marker, or separate +query parameter. For identical prepared settings, both modes have the same +binary layout and ciphertext length. Percent-encoded text length may vary with +the random ciphertext; equal URI text length is not a requirement. + +Persistent delegates to the existing encoder with the entered passphrase and +the same settings-filtering options. A new marker or a transformed Persistent +passphrase would defeat older readers. Ephemeral uses the same external format +to preserve mode hiding. The protocol handler continues to reconstruct the URI +from the existing `settings` query value. + +For a `%$` payload, including an existing URI made before this feature, the +updated decoder: + +1. validates the envelope and captures the current window; +2. derives the Ephemeral candidate for that window and takes the entered + passphrase unchanged as the Persistent candidate; +3. attempts authenticated decryption with both candidates, without returning + early after the first success; +4. checks the current window again before returning an Ephemeral result; and +5. returns settings only if exactly one candidate is accepted. + +Keep expected candidate failures internal. Two failed candidates produce one +generic opening failure. A wrong passphrase, an out-of-window Ephemeral URI, +and damaged authenticated ciphertext do not receive different user messages. +There is no information from which to report a definite historical end time +for an unreadable URI. + +The raw-passphrase attempt is an intentional part of the two-candidate reader. +An Ephemeral URI from another window still fails both candidates with the +entered passphrase; this attempt does not remove its time condition. There is +no plaintext recovery, time-window search, or additional key fallback. + +Older encryption representations other than `%$` retain their existing +legacy-only decoder and passphrase handling. Unsupported prefixes remain +unsupported. Malformed `%$` payloads fail authentication with both candidates. +Bound time-bound candidate work to two attempts; the existing decoder continues +to own any historical encryption-format compatibility trials. + +Because the derivation profile is not stored, an older reader cannot identify +an Ephemeral URI and give an upgrade-specific error. It reports a decryption +failure. A future change to the Ephemeral profile must define its bounded +candidate policy explicitly; the reader must not infer arbitrary profiles or +scan them without a limit. + +Two trials make the amount of cryptographic work predictable, but do not +constitute a constant-time implementation. This design does not claim to hide +the mode from a caller who can instrument the decoder and knows the passphrase. + +## Generation and import interaction + +Keep the existing passphrase prompt. After it, use the existing confirmation +dialogue to choose Time-bound (the Ephemeral encoder mode) or Compatible (the +Persistent encoder mode). Select Time-bound by default, show its exact absolute +end in the device's local time zone with its time-zone name or UTC offset, and +explain that this is the end of a fixed UTC window rather than seven days from +generation. Compatible has no time condition and remains readable by older +clients. No synchronised setting or permanent Vault preference is needed. + +Commonlib exposes the current window end for this pre-generation choice. +Compare it with the `usableUntil` returned alongside the generated URI. If +the window changed during selection or encryption, show a fresh choice with +the new end before opening the existing copy dialogue. Persistent generation +does not consult the clock and returns `null` for `usableUntil`. + +The existing copy dialogue does not monitor the clock. If it stays open across +the boundary, it can still display and copy a URI whose window has ended; +the reader will reject that URI. The end time was shown at the mode choice. +The copy dialogue does not claim a rolling week or silently switch to +Compatible. + +Import requires no mode selector or date input. Recheck the window at the +end of decryption so that an Ephemeral operation crossing the boundary does +not return settings. Once settings have been returned successfully, subsequent +confirmation, setup, and synchronisation do not remain time-bound: the URI +has already been opened. This is an import boundary, not remote revocation. + +## Security and privacy boundary + +The hidden mode is an external-format property. A passive holder of the URI +does not receive an explicit time condition or Persistent marker. Randomised +encryption and the unchanged prepared settings representation avoid adding +a mode-dependent field or length difference. + +The clock and reader are controlled by the receiving device. Anyone with the +correct passphrase can reproduce historical candidates, modify the reader, +or change the supplied clock. Including Persistent adds one possible +candidate; it does not make a small calendar search cryptographically hard. +Time binding adds no independent secret and is not a substitute for a strong +Setup URI passphrase. + +The same URI can be opened repeatedly within its window. A replayed clock +earlier than generation, but inside that same window, also derives the same +key. Successfully copied settings and remote credentials remain usable after +the window ends, subject to their own remote policies. + +No URI, entered or effective passphrase, derived key, decrypted settings, or +candidate-specific authentication result should enter ordinary logs or reports. +The generation screen necessarily reveals the selected mode and end time to +its user; hiding information in the URI does not hide that screen or a +separately shared message. + +## Ownership and compatibility + +Commonlib owns preparation of exported settings, the time-window calculation, +passphrase derivation, format parsing, and dual-candidate decoding. Make these +changes in the Commonlib repository. LiveSync must consume a validated packed +artefact and then an exact reviewed package version, following +[the Commonlib dependency workflow](../../devs.md#commonlib-dependency). + +Preserve the existing positional encoder API. Its third and fourth arguments +already mean properties to remove and whether to omit default values. Add a +separate encoder, provisionally `encodeTimeBoundSetupURI`, with an options +object containing the mode and the existing export options. Its result is: + +```typescript +type TimeBoundSetupURIResult = { + uri: string; + usableUntil: number | null; +}; +``` + +The new encoder defaults to Ephemeral. Preserve the old encoder's legacy +behaviour for callers which have not migrated. Extend +`decodeSettingsFromSetupURI` to try both candidates for `%$` while retaining its +settings return contract and historical format handling. Persistent generation +through the new API delegates to the old encoder. Time injection belongs in +internal test seams, not an import option exposed to users. + +| Surface | Required work | +| ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Obsidian generation](../../src/serviceFeatures/setupObsidian/setupUri.ts) | Reuse the passphrase and copy dialogues, add a mode choice with the exact current window end, and use the new encoder for all three copy variants and the copy event. Preserve each variant's export filters. | +| [Obsidian import](../../src/modules/features/SetupWizard/dialogs/UseSetupURI.svelte) | Consume the updated decoder and retain one authentication failure message. The existing prefix check indicates URI shape, not successful authentication. | +| [Protocol handler](../../src/serviceFeatures/setupObsidian/setupProtocol.ts) | Keep the existing `settings` reconstruction; test encoded delimiters for both modes. | +| [CLI setup](../../src/apps/cli/commands/runCommand.ts) | Consume the updated decoder and leave settings unchanged after any rejection. | +| [WebPeer generator](../../src/apps/webpeer/src/P2PCheckSetup.ts) | Choose a mode explicitly and return availability to its result UI; keep Ephemeral as the default. | +| [Setup utility](../../utils/setup/generate_setup_uri.ts) | Add an explicit mode input, default to Ephemeral, and return/print the end time. Persistent is an explicit choice for durable provisioning output. | +| [Setup utility package facade](../../utils/setup/livesync-commonlib.ts) | Update its independent Commonlib pin and associated lockfiles; updating the root npm dependency alone is insufficient. | + +The Fly.io wrapper delegates to the setup utility and should inherit the same +contract. All maintained generators must migrate explicitly before this +feature is described as the default across applications. Non-interactive +automation which needs a durable URI must select Persistent. + +WebPeer hides an Ephemeral URI and disables its copy and additional-device +actions after the window ends. Its connection monitor remains available for a +device that imported the URI before the end; opening the URI does not expire +the imported P2P credentials. + +| URI | Updated reader | Reader without time-bound support | +| -------------- | ------------------------------------------------------- | --------------------------------- | +| Legacy | Existing behaviour, without a time condition | Existing behaviour | +| New Ephemeral | Opens in the current window with the correct passphrase | Rejected | +| New Persistent | Opens with the correct passphrase | Existing behaviour | + +The assessed, unchanged Commonlib 0.1.27 decoder opens Persistent with the +entered passphrase and rejects Ephemeral with that same passphrase. Persistent +compatibility means compatibility with readers which already support the +ordinary generated `%$` representation; it does not add that representation +to still older readers. Historical supported versions and their settings +schemas still need compatibility fixtures before rollout. + +Keep the original raw-passphrase behaviour of existing URIs. They are +indistinguishable from newly generated Persistent URIs to the updated reader. +The previous marked-envelope sketch rejected an added Persistent compatibility +case with `Unsupported encryption format`. The same synthetic settings and +entered passphrase now open through the unchanged decoder, while separate +tests retain old-reader rejection of Ephemeral and rejection outside its window. + +## Feasibility evidence and validation + +The [executable design probe](time_bound_setup_uri.probe.mjs) uses Web Crypto +for the proposed transformation and the actual Commonlib encoder/decoder for +settings filtering and encryption. It is an isolated specification exercise; +it is not imported by an application or registered in the production test suite. + +Run it after installing the dependency versions assessed by this document: + +```sh +NODE_OPTIONS=--max-old-space-size=512 node docs/design_docs/time_bound_setup_uri.probe.mjs +``` + +Alternatively, pass the directory of an unpacked Commonlib 0.1.27 package as +the first argument. Its module resolution must supply octagonal-wheels 0.1.54 +and the remaining declared dependencies. The probe verifies the Commonlib +version before running; it does not install or download packages. + +The assessment used Node.js 24.18.0 and registry artefacts for Commonlib 0.1.27 +and octagonal-wheels 0.1.54, verified against the lockfile's SHA-512 values. +All 22 cases passed: + +- fixed Ephemeral derivation checked through Web Crypto and Node HMAC, and an + unchanged Persistent passphrase; +- current-window success, previous/later-window rejection, and exact end; +- Persistent across distant timestamps and both candidate attempts on success; +- wrong-passphrase rejection and a shared external format; +- stable end-time metadata and randomised repeated encryption; +- legacy import, old-reader acceptance of Persistent, and old-reader rejection + of Ephemeral; +- unsupported-prefix, malformed-ciphertext, and ciphertext-tampering rejection; +- Persistent generation without reading the clock; +- protocol query decoding/re-encoding; +- generation and import crossing a boundary; +- equivalent timestamps expressed with different UTC offsets; +- Unicode, whitespace, empty low-level passphrase input, and distinct Ephemeral + and raw-passphrase candidates; +- the deliberate limitation that clock rollback reproduces an old key. + +This demonstrates the proposed mechanism and baseline interoperability, not +completed application support, formal mode indistinguishability, or a mobile +latency bound. The present encryption API may perform two PBKDF2 derivations +on a cold import. Do not infer production performance from this small probe, +whose operations can reuse the dependency's in-memory key cache. + +Implementation validation must cover Commonlib unit and packed-package tests, +plus shared fixed-input protocol vectors across consumers. Add targeted LiveSync +tests for the generation metadata, cancellation, a window change during mode +selection, encoded deep links, and rejected imports without settings writes. Extend CLI, WebPeer, +and Deno setup-tool round trips, including their Persistent selection. + +Then run the required LiveSync checks, unit suite, and production build, one +broad process at a time with `NODE_OPTIONS=--max-old-space-size=3072` and bounded +test workers. Use the existing focused real-Obsidian Setup URI workflow for +copy/paste, deep-link import, cancellation, and successful setup. Verify +selection-boundary handling with an injected test clock and mobile behaviour on a +supported runtime; do not change the host's system clock. No remote database +service is needed for the protocol tests themselves. + +There is no identified blocker in the Time-bound URI protocol. The Commonlib +candidate based on 0.1.31 passed its type, unit, boundary, release-process, +and packed-package gates before the 0.1.32 release. A clean `npm ci` against +the published 0.1.32 artefact and the frozen Deno tool lock resolve the same +registry integrity. LiveSync passes its source checks, production build, and +1,034 unit tests on a local stack with [PR #1222](https://github.com/vrtmrz/obsidian-livesync/pull/1222). +The two CLI installer tests need a runner which permits child processes; both +pass under normal process permissions. The Deno setup-tool suite, CLI setup +and file-operation contract, and WebPeer browser tests passed before stacking. + +Focused real-Obsidian generation checks pass on desktop and emulated mobile, +including the displayed Time-bound end, Compatible output, and mobile touch +targets. A two-device CouchDB workflow now passes on the local stack: the +provisioning tool creates a generation 12 database, the first device generates +a Time-bound Setup URI after declaring its required generation 13 feature, and +the second device imports it. An ordinary note completes a round trip, and a +hidden snippet synchronises. The separate real-Obsidian tests for live remote +feature changes, internal Metadata migration, and a percent-prefixed E2EE +passphrase also pass with published Commonlib 0.1.32. Unit and protocol tests +cover window boundaries and preserve the existing distinction between an empty +passphrase and cancellation. The WebPeer browser test confirms that its monitor +remains available after the URI window ends for a device which has already +imported the URI. + +The current Commonlib 0.1.33 integration includes the merged host changes from +PR #1222 and PR #1225. npm 10 and normal clean installations preserve the lockfile; +source checks, the production build, 1,064 unit tests, and ten Deno setup-tool +tests pass. Both URI modes preserve ID recovery and explicit legacy ID selection. + +Real Obsidian tests cover independent ID keys through Time-bound, Compatible, +and QR setup, encrypted local persistence, natural restarts of both devices, +and bidirectional note transfers with stable document and Chunk IDs. Incorrect +passphrases and past-window URIs leave runtime and persisted settings unchanged. +The past clock belongs to an isolated fixture worker, not Obsidian or the host. +CouchDB tests also cover a custom ID source and recovery code, rejection of +incompatible document keys before remote writes, and the Doctor's decline, +reminder, dismissal, and later acceptance paths. The detailed commands and the +remaining published-artefact and physical-device checks are recorded in the +[real Obsidian test guide](../../test/e2e-obsidian/README.md#combined-setup-and-security-regression-checks). + +Compatible preserves the URI encryption format; each receiving client must +still support the shared settings and the remote's declared features. The host +compatibility checks from PR #1222 remain necessary. These results do not +establish a mobile performance bound. The first implementation changes only +primary-language resources; translation changes require separate scope. diff --git a/docs/design_docs/time_bound_setup_uri.probe.mjs b/docs/design_docs/time_bound_setup_uri.probe.mjs new file mode 100644 index 00000000..d26a1143 --- /dev/null +++ b/docs/design_docs/time_bound_setup_uri.probe.mjs @@ -0,0 +1,272 @@ +// Executable design probe; this file is not part of any application bundle. +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { test } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const packageDirectory = process.argv[2] + ? resolve(process.argv[2]) + : fileURLToPath(new URL(".", import.meta.resolve("@vrtmrz/livesync-commonlib/package.json"))); +const packageURL = pathToFileURL(`${packageDirectory}/`); +const metadata = JSON.parse(await readFile(new URL("package.json", packageURL), "utf8")); +assert.equal(metadata.version, "0.1.27", "Run against the Commonlib version assessed by this design"); +const { encodeSettingsToSetupURI: encodeLegacy, decodeSettingsFromSetupURI: decodeLegacy } = await import( + new URL("dist/API/processSetting.js", packageURL).href +); +const { configURIBase } = await import(new URL("dist/common/types.js", packageURL).href); + +const WEEK_MS = 604_800_000; +const passphrase = "synthetic time-bound URI passphrase"; +const settings = { + couchDB_URI: "https://example.invalid", + couchDB_USER: "synthetic-user", + couchDB_PASSWORD: "synthetic-secret", + isConfigured: true, +}; +const midweek = Date.parse("2026-09-28T12:00:00Z"); +const slot = (now) => { + assert.ok(Number.isSafeInteger(now) && now >= 0, "A supported UTC timestamp is required"); + return Math.floor(now / WEEK_MS); +}; +const end = (slot(midweek) + 1) * WEEK_MS; +const payloadOf = (uri) => { + assert.ok(uri.trim().startsWith(configURIBase)); + return decodeURIComponent(uri.trim().slice(configURIBase.length)); +}; +const wrap = (payload) => configURIBase + encodeURIComponent(payload); +const fixedClock = (now) => () => now; + +async function effectivePassphrase(secret, mode, bucket) { + if (mode === "persistent") return secret; + assert.equal(mode, "ephemeral"); + const text = new TextEncoder(); + const keyBytes = await crypto.subtle.digest("SHA-256", text.encode(secret)); + const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); + const context = JSON.stringify(["livesync/setup-uri", "tb1", "ephemeral", bucket]); + const signed = await crypto.subtle.sign("HMAC", key, text.encode(context)); + return Array.from(new Uint8Array(signed), (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + +async function encode(mode, clock, secret = passphrase) { + assert.ok(mode === "ephemeral" || mode === "persistent"); + if (mode === "persistent") { + return { uri: (await encodeLegacy(settings, secret)).trim(), usableUntil: null }; + } + const bucket = slot(clock()); + const effective = await effectivePassphrase(secret, mode, bucket); + const legacy = await encodeLegacy(settings, effective); + if (mode === "ephemeral" && slot(clock()) !== bucket) throw new Error("Window changed"); + return { + uri: legacy.trim(), + usableUntil: (bucket + 1) * WEEK_MS, + }; +} + +async function decode(uri, secret, clock, attempts = []) { + const payload = payloadOf(uri); + if (!payload.startsWith("%$")) { + return decodeLegacy(uri.trim(), secret); + } + const bucket = slot(clock()); + const authenticated = []; + for (const mode of ["ephemeral", "persistent"]) { + const effective = await effectivePassphrase(secret, mode, bucket); + attempts.push(mode); + try { + const value = await decodeLegacy(uri.trim(), effective); + if (value !== false) authenticated.push({ mode, value }); + } catch { + // Authentication failures are expected while trying the two candidates. + } + } + const currentBucket = slot(clock()); + const accepted = authenticated.filter(({ mode }) => mode === "persistent" || bucket === currentBucket); + if (accepted.length !== 1) throw new Error("Cannot open Setup URI"); + return accepted[0].value; +} + +const ephemeral = await encode("ephemeral", fixedClock(midweek)); +const persistent = await encode("persistent", fixedClock(midweek)); + +await test("Persistent opens in the unchanged legacy decoder with the entered passphrase", async () => { + assert.equal((await decodeLegacy(persistent.uri, passphrase)).couchDB_PASSWORD, settings.couchDB_PASSWORD); +}); + +await test("Web Crypto derivation matches fixed vectors computed through Node HMAC", async () => { + assert.equal( + await effectivePassphrase("test-passphrase", "ephemeral", 1234), + "b39361c51f0b7bd835554db1dffbc9a540fb30789aa62bf53e39e07d1073013b" + ); + assert.equal(await effectivePassphrase("test-passphrase", "persistent", 1234), "test-passphrase"); +}); + +await test("Ephemeral accepts the entire current UTC bucket, including before creation", async () => { + for (const now of [slot(midweek) * WEEK_MS, midweek, end - 1]) { + const attempts = []; + assert.equal( + (await decode(ephemeral.uri, passphrase, fixedClock(now), attempts)).couchDB_PASSWORD, + settings.couchDB_PASSWORD + ); + assert.deepEqual(attempts, ["ephemeral", "persistent"]); + } +}); + +await test("Ephemeral rejects the previous bucket, the exact end, and later buckets", async () => { + for (const now of [slot(midweek) * WEEK_MS - 1, end, end + WEEK_MS, end + 100 * WEEK_MS]) { + const attempts = []; + await assert.rejects(decode(ephemeral.uri, passphrase, fixedClock(now), attempts), /Cannot open/); + assert.deepEqual(attempts, ["ephemeral", "persistent"]); + } +}); + +await test("Persistent accepts distant supported timestamps using the same two attempts", async () => { + for (const now of [0, midweek, end, end + 100 * WEEK_MS]) { + const attempts = []; + assert.equal( + (await decode(persistent.uri, passphrase, fixedClock(now), attempts)).couchDB_PASSWORD, + settings.couchDB_PASSWORD + ); + assert.deepEqual(attempts, ["ephemeral", "persistent"]); + } +}); + +await test("Both modes reject an incorrect passphrase with the same final error", async () => { + for (const generated of [ephemeral, persistent]) { + await assert.rejects(decode(generated.uri, "incorrect", fixedClock(midweek)), /Cannot open Setup URI/); + } +}); + +await test("Generation metadata agrees with the fixed UTC boundary", () => { + assert.equal(ephemeral.usableUntil, end); + assert.equal(new Date(end).toISOString(), "2026-10-01T00:00:00.000Z"); + assert.equal(persistent.usableUntil, null); +}); + +await test("Both modes retain the legacy binary layout without a new marker or timestamp field", () => { + const binaryLength = (uri) => { + const payload = payloadOf(uri); + assert.ok(payload.startsWith("%$")); + return Buffer.from(payload.slice("%$".length), "base64").length; + }; + assert.equal(binaryLength(ephemeral.uri), binaryLength(persistent.uri)); +}); + +await test("Repeated generation has different ciphertext without changing the time limit", async () => { + const again = await encode("ephemeral", fixedClock(midweek)); + assert.notEqual(again.uri, ephemeral.uri); + assert.equal(again.usableUntil, ephemeral.usableUntil); +}); + +await test("Old decoder cannot open Ephemeral with the entered passphrase", async () => { + await assert.rejects(decodeLegacy(ephemeral.uri, passphrase)); +}); + +await test("Legacy URI remains readable without time binding", async () => { + const legacy = await encodeLegacy(settings, passphrase); + const attempts = []; + const value = await decode(legacy, passphrase, fixedClock(end + 100 * WEEK_MS), attempts); + assert.equal(value.couchDB_PASSWORD, settings.couchDB_PASSWORD); + assert.deepEqual(attempts, ["ephemeral", "persistent"]); +}); + +await test("Unsupported prefixes are rejected without time-bound trials", async () => { + for (const payload of ["tb1:" + payloadOf(ephemeral.uri), "tb2:", "", "unlimited"]) { + const attempts = []; + await assert.rejects(decode(wrap(payload), passphrase, fixedClock(midweek), attempts), /format/); + assert.deepEqual(attempts, []); + } +}); + +await test("Missing or truncated legacy-format ciphertext fails both candidates", async () => { + for (const payload of ["%$", "%$AA=="]) { + const attempts = []; + await assert.rejects(decode(wrap(payload), passphrase, fixedClock(midweek), attempts), /Cannot open/); + assert.deepEqual(attempts, ["ephemeral", "persistent"]); + } +}); + +await test("Persistent generation does not consult the clock", async () => { + const generated = await encode("persistent", () => { + throw new Error("The Persistent generator must not read time"); + }); + assert.equal(generated.usableUntil, null); + assert.equal((await decodeLegacy(generated.uri, passphrase)).couchDB_PASSWORD, settings.couchDB_PASSWORD); +}); + +await test("Changing authenticated ciphertext is rejected", async () => { + const payload = payloadOf(ephemeral.uri); + const encoded = payload.slice("%$".length); + const bytes = Buffer.from(encoded, "base64"); + bytes[bytes.length - 1] ^= 1; + await assert.rejects(decode(wrap("%$" + bytes.toString("base64")), passphrase, fixedClock(midweek)), /Cannot open/); +}); + +await test("Protocol query decoding and re-encoding preserve the new payload", async () => { + for (const generated of [ephemeral, persistent]) { + const incomingSettings = new URL(generated.uri).searchParams.get("settings"); + const reconstructed = configURIBase + encodeURIComponent(incomingSettings); + assert.equal( + (await decode(reconstructed, passphrase, fixedClock(midweek))).couchDB_PASSWORD, + settings.couchDB_PASSWORD + ); + } +}); + +await test("Generation crossing the boundary withholds an Ephemeral result", async () => { + let reads = 0; + await assert.rejects( + encode("ephemeral", () => (reads++ === 0 ? end - 1 : end)), + /Window changed/ + ); +}); + +await test("Import crossing the boundary withholds Ephemeral settings but accepts Persistent", async () => { + for (const [generated, succeeds] of [ + [ephemeral, false], + [persistent, true], + ]) { + let reads = 0; + const result = decode(generated.uri, passphrase, () => (reads++ === 0 ? end - 1 : end)); + if (succeeds) assert.equal((await result).couchDB_PASSWORD, settings.couchDB_PASSWORD); + else await assert.rejects(result, /Cannot open/); + } +}); + +await test("Explicit UTC offsets representing the same instant select the same bucket", async () => { + for (const date of ["2026-09-28T12:00:00Z", "2026-09-28T21:00:00+09:00", "2026-09-28T05:00:00-07:00"]) { + assert.equal( + (await decode(ephemeral.uri, passphrase, fixedClock(Date.parse(date)))).couchDB_PASSWORD, + settings.couchDB_PASSWORD + ); + } +}); + +await test("Passphrase transformation preserves Unicode and supports an empty low-level input", async () => { + for (const secret of ["", "合言葉🔑é", "e\u0301", " leading and trailing "]) { + const generated = await encode("ephemeral", fixedClock(midweek), secret); + assert.equal( + (await decode(generated.uri, secret, fixedClock(midweek))).couchDB_PASSWORD, + settings.couchDB_PASSWORD + ); + } + assert.notEqual( + await effectivePassphrase("é", "persistent", 0), + await effectivePassphrase("e\u0301", "persistent", 0) + ); +}); + +await test("Ephemeral derivation differs from the raw Persistent passphrase even for bucket zero", async () => { + assert.notEqual( + await effectivePassphrase(passphrase, "ephemeral", 0), + await effectivePassphrase(passphrase, "persistent", 0) + ); +}); + +await test("Clock rollback reproduces an old Ephemeral key", async () => { + await assert.rejects(decode(ephemeral.uri, passphrase, fixedClock(end)), /Cannot open/); + assert.equal( + (await decode(ephemeral.uri, passphrase, fixedClock(midweek))).couchDB_PASSWORD, + settings.couchDB_PASSWORD + ); +}); diff --git a/docs/glossary.md b/docs/glossary.md index 8af12013..6f3f1c3e 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -92,13 +92,19 @@ recovery guidance, or diagnostics intended for users. reports, and advanced edge-case settings. - **Hidden File Sync:** The feature which synchronises files in hidden directories, such as `.obsidian`. +- **ID key:** A saved secret used to generate encrypted Chunk IDs and + obfuscated Metadata document IDs when independent ID derivation is enabled. + It is separate from the current E2EE passphrase. +- **ID recovery code:** A versioned text form of the saved ID key which can be + shown on the current device and imported without deriving a different key. + Treat it as a secret. - **JWT Authentication:** An experimental CouchDB authentication option which uses a JSON Web Token instead of standard credentials. It requires a private key or secret, algorithm, expiry duration, subject, and key ID. -- **LiveSync:** This name has two established meanings: the shortened plug-in - name for Self-hosted LiveSync, and the Sync Mode for continuous, real-time - synchronisation. Prefer 'Continuous replication' in design documentation - when the mode, rather than the product, is meant. +- **LiveSync:** The exact Sync Mode label for continuous, real-time + synchronisation. Write 'LiveSync mode' in user-facing explanations and + 'Continuous replication' in design documentation. Product references use + 'Self-hosted LiveSync' or 'this plug-in'. - **livesync-serverpeer / WebPeer:** Specialised clients which assist WebRTC peer-to-peer communication. - **Metadata (file metadata):** A database document which stores file @@ -162,13 +168,20 @@ device-local provenance. semantic boundaries, such as paragraphs or sections, rather than arbitrary byte boundaries. - **Self-hosted LiveSync:** The name of this plug-in. 'Self-hosted' is one - hyphenated word. + hyphenated word. Use this full name for product references, or 'this plug-in' + when the context is clear. - **Setting Doctor (Config Doctor):** A diagnostic utility which identifies configuration mismatches or suboptimal settings and presents recommended values and reasons. - **Setup URI:** An encrypted representation of plug-in settings and remote configuration which can be transferred to another device and opened with a passphrase. + - **Time-bound:** A sharing choice which permits opening the URI until the + displayed end of the current fixed seven-day UTC window. Imported settings + and credentials remain usable afterwards. + - **Compatible (no time limit):** A sharing choice which retains the existing + encrypted URI format without a time condition. The receiving device must + still support the shared settings. - **Signalling relay (P2P):** A Nostr-compatible WebSocket relay used for peer discovery and WebRTC connection negotiation. It does not store or transfer Vault content. The project author operates a public relay as a best-effort diff --git a/docs/releases/1.0.md b/docs/releases/1.0.md index 941ac6ff..e6f105ab 100644 --- a/docs/releases/1.0.md +++ b/docs/releases/1.0.md @@ -2,6 +2,130 @@ This document contains earlier published releases from the 1.0 line of the [current Self-hosted LiveSync release history](../../updates.md). Beta and release-candidate builds published before 1.0.0 are recorded in the [1.0 preview history](1.0-previews.md). Earlier release lines continue in the [0.25 history](0.25.md) and the [legacy history](legacy.md). +## 1.0.30 + +18th September, 2026 + +### Synchronisation + +#### Fixed + +- After a restart, unchanged local files no longer overwrite newer synchronised content. (#994) + - When LiveSync cannot establish a local file's origin, it keeps the file as a conflict for you to review. This also applies to ordinary file synchronisation in the command-line tool. +- Fast Fetch completes initial setup with fewer remote requests. +- Object Storage synchronisation makes fewer remote requests while still checking its parameters before writing. + +## 1.0.29 + +16th September, 2026 + +Unusually for this project, I have added a feature that relies on a particular infrastructure provider. I made this choice for the convenience it offers. + +### Peer-to-peer synchronisation + +#### New Feature + +- P2P synchronisation now supports **Managed (Cloudflare)** TURN to help devices connect when a direct connection is unavailable. Enter your TURN Key ID and API token, and LiveSync obtains temporary TURN credentials automatically. (#1182) + + - Managed TURN settings are saved with your encrypted P2P profile and included when you share it through a Setup URI or QR code. + - Your API token is omitted from generated reports. + +### Command-line tool + +#### Fixed + +- The CLI daemon now synchronises files already present at start-up and picks up edits and deletions made while it was stopped. +- CLI Vault scans no longer miss files after an earlier scan or file lookup. This incorporates an adapted version of the fix proposed in PR #1188. Thank you to @YakupEmreYerli for the fix and regression tests, and to @nsanitas for the detailed report and analysis in #1143! + +### Miscellaneous + +In general, I would prefer to avoid features that depend on a particular service. Still, I think there is room for them when they are entirely optional, clearly explained, and maintainable. Even then, I would want open alternatives to remain available. I will write more about this principle separately. + +## 1.0.28 + +9th September, 2026 + +I came across an article online that put its finger on something fundamental. Writing up the details in what seemed the most fitting format helped me organise my thoughts considerably. + +The resulting manuscript and citation information are now available in the project's GitHub repository for researchers and practitioners who would like to cite Self-hosted LiveSync. + +### Setup and compatibility + +#### Fixed + +- A missing legacy file-name case setting no longer makes the configuration mismatch dialogue require a database rebuild when this device already uses case-insensitive handling. Case-sensitive handling now correctly requires a compatibility decision when the remote omits that setting. +- Configuration review now compares the selected remote profile's trial settings, and discards a pending decision if its settings or active connection change before it can be applied. + +## 1.0.27 + +7th September, 2026 + +For now, I am addressing the issues I can resolve first. I hope this helps. + +### Synchronisation and storage + +#### Fixed + +- First-time Object Storage setup now completes when **Use Custom HTTP Handler** is enabled for an empty remote, including a new Cloudflare R2 bucket. LiveSync can now create the remote state required to begin synchronisation. (#1166) + +## 1.0.26 + +~~1.0.25~~ was cancelled because pre-release validation found that LiveSync could appear to finish synchronising even though Android had not written a received file to the Vault; the warning appeared only after restart. + +6th September, 2026 + +### Synchronisation and storage + +#### Fixed + +- Files inside a folder are no longer silently removed from synchronisation when an external tool changes only the letter case of that folder while Obsidian is running. This prevents the stale deletion from reaching other devices or later removing the local file. Moving files into ignored or otherwise excluded locations retains the existing behaviour, and the folder-name case itself may still differ between devices. (#1168) +- A problem processing one file during ordinary start-up no longer prevents every other file from synchronising. LiveSync warns about the affected files and can retry them later; Fetch and Rebuild still stop if they cannot finish safely. (#1164) +- When LiveSync cannot finish preparing this device for synchronisation, it now says that synchronisation is unavailable and directs you to generate a report, instead of remaining at 'Not ready'. (#1164) + +#### Improved + +- When LiveSync cannot write a received file to the Vault, it now warns immediately instead of appearing to have synchronised it successfully. The generated report identifies the affected path, and a later scan can try it again. + +### Conflict handling and recovery + +#### Improved + +- Conflict resolution dialogues now close when the same file is resolved elsewhere or when the plug-in unloads. Requests for different files are shown one at a time, while a newer request for the same file replaces the older one. + +### Setup and compatibility + +#### Improved + +- Unconfigured Vaults now stay focused on setup instead of running Config Doctor or incomplete-document checks before they can be used. Returning a configured Vault to an unconfigured state also stops those checks until the requested restart. (#1161) +- When the active file contains a file or folder name longer than 255 UTF-8 bytes, LiveSync now explains that the path may not work on some Android and Linux file systems. It does not rename or reject the file. (#1164) + +## 1.0.24 + +3rd September, 2026 + +### Interface and translation + +#### Fixed + +- The Setup Wizard now correctly explains that the existing-device path adds this device to an existing synchronisation (PR #1118). Thank you to @nikhilmaddirala for the contribution! +- Spanish translations now resolve the **Display language** placeholder, cover previously untranslated Setup Wizard and CouchDB text, translate user-facing Config Doctor values and confirmation controls, and use Spanish sentence case (PR #1129). Thank you to @zeedif for the contribution! + +#### Improved + +- The Setup Wizard now shows the passphrase and **Obfuscate Properties** controls only after E2EE is enabled, provides a password-visibility button, allows longer translated labels to wrap, and keeps the invitation link compact on desktop while preserving its mobile touch target (PR #1130). Thank you to @zeedif for the contribution! + +### Synchronisation and storage + +#### Fixed + +- **Overwrite Server Data with This Device's Files** now keeps this device's synchronisation settings instead of reapplying settings from the remote database which is about to be replaced. Enabling E2EE before a rebuild therefore remains enabled and uploads encrypted data. (#1146) + +### Command-line tool + +#### Fixed + +- The systemd installer now finds the repository root correctly, installs every generated bundle chunk and required production dependency, checks the installed command before activation, and reports success only when the service remains active. + ## 1.0.23 2nd September, 2026 diff --git a/docs/settings.md b/docs/settings.md index 2ce7e275..0f96a07d 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -71,7 +71,7 @@ This pane always shows the current release history. It does not track whether a Internal database or settings compatibility reviews use a separate safety dialogue, not this pane. After the Obsidian layout is ready, a pending review opens as **Synchronisation paused for compatibility review**. The dialogue explains why remote synchronisation has been paused and preserves the automatic synchronisation choices which were configured before the update. Closing it or selecting **Keep synchronisation paused** leaves synchronisation paused. Use the persistent Notice's **Review why** link, or run the `Review why synchronisation is paused` command, to reopen it. Opening **Change Log** does not acknowledge the review. -A configured Vault which was copied, restored, or opened in a new Obsidian profile can require this review because its device-local acknowledgement is not part of the Vault data. An empty local database is not accepted as evidence that it is safe to continue. An existing unconfigured Vault remains in onboarding without this synchronisation warning; its missing acknowledgement is not filled in automatically, so it is evaluated if the Vault is configured later. When the detected state can be handled by the running version, **Resume synchronisation** records the current internal database version and restores the configured behaviour. An older installation cannot dismiss a pause caused by a newer database or settings version. +An absent device-local acknowledgement alone does not require a review, including when adding a device or opening a copied Vault in a new profile. LiveSync records the current internal database version if no other review is pending. An existing unconfigured Vault remains in onboarding; its next configured start evaluates compatibility before recording an absent marker. Known version differences, an invalid marker, settings-schema issues, and an already saved review still require attention. When the detected state can be handled by the running version, **Resume synchronisation** records the current internal database version and restores the configured behaviour. An older installation cannot dismiss a pause caused by a newer database or settings version. ## 1. Quick Setup and Extra menus @@ -87,10 +87,18 @@ Most preferred method to setup Self-hosted LiveSync. You can setup Self-hosted L #### Connect with Setup URI -Setup the Self-hosted LiveSync with the `setup URI` which is [copied from another device](#copy-current-settings-as-a-new-setup-uri) or the setup script. +Set up Self-hosted LiveSync with a Setup URI [copied from a working device](#copy-the-current-settings-to-a-setup-uri) or generated by the setup script. A current Setup URI retains its remote profiles, display names, and separate main and P2P selections. Older Setup URIs containing only flat connection settings remain supported and are migrated to a remote profile when applied. +Choose the action for the device being configured: + +| Choice | Effect | +| --- | --- | +| **⚠️ Initialise or overwrite the remote** | Initialise the remote from this Vault. Existing data on the remote is overwritten. | +| **🔗 Join this device** | Join an existing remote and Fetch its synchronisation data onto this device. Use this for an additional device. | +| **⚙️ Apply settings only (advanced)** | Apply the settings without rebuilding or fetching. Use this only when this device already has compatible synchronisation data. | + #### Manual setup Step-by-step setup for Self-hosted LiveSync. You can setup Self-hosted LiveSync manually with Minimal setting items. @@ -105,7 +113,16 @@ This button only appears when the setup was not completed. If you have completed #### Copy the current settings to a Setup URI -You can copy the current settings as a new setup URI. And this URI can be used to setup the other devices as [Use the copied setup URI](#use-the-copied-setup-uri). +Copy the current settings from a working device, then [open the Setup URI on the additional device](#connect-with-setup-uri). Keep the URI and its separate passphrase private. + +After entering the passphrase, choose **Time-bound** or **Compatible (no time limit)** in **Setup URI availability**: + +- **Time-bound** is the default. The dialogue shows the exact end time in this device's local time zone. It is the end of the current fixed seven-day UTC window, so the remaining time may be less than seven days. Receiving devices need a version which supports Time-bound Setup URIs. +- **Compatible (no time limit)** uses the existing encrypted URI format without a time condition. Older receiving devices must still support the settings carried by the URI. + +The time condition is checked when opening the URI. Settings and credentials already imported remain usable afterwards. It does not revoke remote access or prevent reuse after rolling the device clock back. Generate a fresh URI from a working device if the displayed time has passed. + +QR code sharing uses its existing format and has no time condition. Keep the QR code private because it carries the shared settings and credentials. ### 3. Extra menus @@ -239,12 +256,34 @@ Setting key: passphrase Encrypting passphrase. If you change the passphrase, you need to rebuild databases (You will be informed). +#### Independent ID derivation + +Setting keys: `idDerivationVersion`, `idDerivationKey` + +This setting saves a separate key for encrypted Chunk IDs and obfuscated Metadata document IDs. New Vault setup selects **Generate a random ID key** by default when E2EE is enabled. Existing Vaults select **Keep current configuration** by default. The radio choices show the available configurations together. A small description under **Keep current configuration** identifies the saved configuration: an existing ID key, or legacy IDs linked to the E2EE passphrase. That choice retains either one; on a new Vault, choosing it explicitly uses legacy IDs. If the configuration is legacy, changing the E2EE passphrase also changes IDs. + +To set a key yourself, choose **Set an ID key**. Three further radio choices then appear: **Derive from current E2EE passphrase**, **Enter an ID source**, and **Import an ID recovery code**. The last two choices show a text input. The source input also recognises a tagged recovery code. An empty input keeps an existing key; a first key requires input. An ordinary source is converted to a key when you apply the settings and cannot be shown again. A recovery code imports the saved key directly. + +Use **Show current recovery code** to display and copy the saved key on this device. The code starts with `sls-id-v1:` and can be pasted into the manual input on another device without deriving a different key. A Setup URI carries the same saved key under its separate passphrase. If you need to restore the configuration after losing every device, save the recovery code or choose a source you can reproduce before relying on the random default. Keep the code private. + +Using the E2EE passphrase as the source keeps IDs stable after later passphrase changes, but it does not separate the original passphrase from guesses based on known IDs. Use a long, unpredictable, separate source when that separation matters. Hashing a weak source does not make it strong. + +Changing the E2EE passphrase later does not change the saved ID key, although the existing re-encryption and Rebuild procedure still applies to the encrypted data. While E2EE is off, the saved ID key is retained but is not used; existing legacy ID generation applies until E2EE is enabled again. Devices with different ID keys can synchronise when Path Obfuscation is off, although identical content may produce duplicate Chunks. Enabling, replacing, or disabling the ID key can change document IDs when Path Obfuscation is active. Update participating devices, Rebuild from the authoritative Vault, and Fetch on other devices before resuming ordinary synchronisation. A QR code includes the saved key under the existing QR sharing rules, so keep the QR code private. + #### Path Obfuscation Setting key: usePathObfuscation In default, the path of the file is not obfuscated to improve the performance. If you enable this, the path of the file will be obfuscated. This is useful when you want to hide the path of the file. +#### Encrypt internal file Properties + +Setting key: encryptInternalMetadata + +For CouchDB, this encrypts paths, times, sizes, and Chunk references in the Metadata used by Hidden File Sync and Customisation Sync. It requires E2EE V2 and **Property Encryption**. New Vaults enable the preference by default, but it has no effect until those prerequisites are enabled. Existing Vaults and older Setup URIs and QR codes keep it disabled unless you enable it. + +Enabling the preference protects future Metadata writes. Existing Metadata and earlier revisions can remain readable in the remote database. If you want to protect existing Metadata too, prepare the authoritative data, update every device to a compatible version, and manually Rebuild the remote database. LiveSync does not gather data or start a Rebuild when you change this preference. The action to enable it without rebuilding explicitly reminds you to update every other synchronising device first, including devices currently running LiveSync. Plaintext and encrypted Metadata can coexist during the transition. Document IDs, revision information, document counts, and ciphertext lengths remain visible. + #### Encryption Algorithm Setting key: E2EEAlgorithm @@ -675,6 +714,8 @@ Save settings to a markdown file. You will be notified when new settings arrive. Setting key: writeCredentialsForSettingSync (Not recommended) If set, credentials will be stored in the file. +When this setting is disabled, the file omits Object Storage keys, authentication headers, other credentials, all connection profiles, and their active selections. Importing it retains the receiving device's local credentials and profiles. When enabled, the file includes credentials and complete connection profiles. For manual sharing, use the settings screen's plain-text export or an encrypted Setup URI. + #### Notify all setting files Setting key: notifyAllSettingSyncFile @@ -1025,6 +1066,8 @@ Setting key: hashAlg `xxhash64` is the supported current value. Older algorithms remain selectable only as an edge-case compatibility path for existing databases. Changing the algorithm can reduce chunk reuse between devices and requires the normal tweak review. +When independent ID derivation is enabled, encrypted Chunk IDs use its versioned HMAC construction instead of `hashAlg`. The selected `hashAlg` continues to apply to legacy IDs. + ### 6. Edge case addressing (Behaviour) #### Fetch database with previous behaviour diff --git a/docs/setup_object_storage.md b/docs/setup_object_storage.md index 0244a766..cad31264 100644 --- a/docs/setup_object_storage.md +++ b/docs/setup_object_storage.md @@ -31,7 +31,8 @@ deno run --minimum-dependency-age=0 --allow-env https://raw.githubusercontent.co For providers which require them, set `force_path_style`, `use_custom_request_handler`, or `bucket_custom_headers` as described in the [setup utility reference](../utils/readme.md#object-storage). -Store the generated Setup URI and Setup URI passphrase separately. The URI is encrypted, but it contains the Object Storage credentials. +Store the generated Setup URI and Setup URI passphrase separately. The URI is encrypted, but it contains the Object Storage credentials. The generator also prints an ID recovery code; reuse it through `id_recovery_code` if you regenerate a URI for the same Vault. A new run without it creates a different ID key. The [setup utility reference](../utils/readme.md#setup-uri-generation) describes the `id_mode=legacy` option for existing Vaults. +The generator prints the exact end time of its default Ephemeral URI. Set `uri_mode=persistent` before running it if the URI must remain usable without a time condition. ## Set up the first device diff --git a/docs/setup_own_server.md b/docs/setup_own_server.md index 0eac36b2..1b7d0e9c 100644 --- a/docs/setup_own_server.md +++ b/docs/setup_own_server.md @@ -190,14 +190,21 @@ deno run --minimum-dependency-age=0 --allow-env https://raw.githubusercontent.co > > If `uri_passphrase` is omitted, the generator creates a cryptographically random value and prints it once. +The generator also prints an ID recovery code for its random ID key. Save that code if you may need to regenerate a Setup URI for the same Vault. Pass it back as `id_recovery_code`; otherwise a later run creates a different key. Set `id_mode=legacy` only when connecting to a Vault which uses the previous ID behaviour. See the [setup utility reference](../utils/readme.md#setup-uri-generation). + The generator consumes the exact registry-pinned Commonlib release used by the provisioning utility. It creates a configured CouchDB remote profile, applies the current defaults for a new Vault, and encodes them with Commonlib's Setup URI contract. +By default, the URI is Ephemeral and can be opened only until the exact UTC time printed by the generator. This is the end of a fixed seven-day window, not seven days after creation. Set `uri_mode=persistent` before running the command if the URI needs no time condition or must be readable by an older client that supports the existing encrypted format. + You will then get the following output: ```bash Generated couchdb Setup URI. +Ephemeral: usable until 2026-10-01T00:00:00.000Z (UTC). Your passphrase for the Setup URI is: H7vX...a-random-32-character-value This passphrase is never shown again, so store it safely. +ID recovery code: sls-id-v1:<64 lowercase hexadecimal characters> +Use id_recovery_code with this value and reuse the same remote settings when generating another Setup URI for the same Vault. obsidian://setuplivesync?settings=%5B%22tm2DpsOE74nJAryprZO2M93wF%2Fvg.......4b26ed33230729%22%5D ``` diff --git a/docs/setup_p2p.md b/docs/setup_p2p.md index fb13a9c1..4797f420 100644 --- a/docs/setup_p2p.md +++ b/docs/setup_p2p.md @@ -135,4 +135,5 @@ export uri_passphrase= deno run --minimum-dependency-age=0 --allow-env https://raw.githubusercontent.com/vrtmrz/obsidian-livesync/main/utils/setup/generate_setup_uri.ts ``` -The generated Setup URI contains the encrypted room, relay, and Vault settings. It deliberately omits the device-specific name. Store the URI and its passphrase separately. After importing it on the first device, continue from the initialisation step above, then generate a fresh Setup URI for an additional device from that working device. +The generated Setup URI contains the encrypted room, relay, and Vault settings. It deliberately omits the device-specific name. Store the URI and its passphrase separately. The generator prints an ID recovery code; pass it as `id_recovery_code` if you regenerate a URI for the same Vault. A run without it creates a different ID key. Also reuse the original `p2p_room_id` and `p2p_passphrase`, since omitted values are generated afresh. The [setup utility reference](../utils/readme.md#setup-uri-generation) describes the `id_mode=legacy` option for existing Vaults. After importing the URI on the first device, continue from the initialisation step above, then generate a fresh Setup URI for an additional device from that working device. +The generator prints the exact end time of its default Ephemeral URI. Set `uri_mode=persistent` before running it if the URI must remain usable without a time condition. diff --git a/docs/terms.md b/docs/terms.md index 959712e4..2ee06621 100644 --- a/docs/terms.md +++ b/docs/terms.md @@ -29,6 +29,9 @@ All guidelines and conventions listed below are disclosed and maintained solely 6. Single quotation marks (`'`) are preferred over double quotation marks (`"`) in general documentation text, unless the context requires double quotes (for example, inside JSON code blocks). +7. **Product name**: References to this product use 'Self-hosted LiveSync' or, where the context is clear, 'this plug-in'. Use this convention in documentation, user-facing messages, release notes, comments, commit messages, and PR or issue text. + - Preserve exact interface labels, existing code identifiers, commands, package names, and quotations. 'LiveSync' is the exact label of the Sync Mode for continuous synchronisation; write 'LiveSync mode' when explaining that mode. + ### Terminology Project-specific meanings are defined separately in the diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index d8f128b5..17407675 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -55,7 +55,7 @@ At start-up, LiveSync can restore a missing device-local revision record when th ## Synchronisation is paused for compatibility review -A compatibility review is separate from the Change Log. It can appear after an internal database or settings-format change, or when a configured Vault is copied, restored, or opened in a new Obsidian profile without its device-local acknowledgement. +A compatibility review is separate from the Change Log. It can appear after an internal database or settings-format change, when the saved version marker is invalid, or when an earlier review remains pending. Adding a device or opening a copied Vault with no device-local acknowledgement does not itself trigger a review. A pause already saved by an earlier release still needs the explicit resume action, because the saved message does not identify its original cause. The **Synchronisation paused for compatibility review** dialogue opens after the Obsidian layout is ready. If it has been closed, use the persistent Notice's **Review why** link, or run `Review why synchronisation is paused` from the command palette. Opening **Change Log** does not clear the pause. @@ -96,6 +96,8 @@ Current releases automatically align compatible settings which control how new c A missing legacy file-name case setting means case-insensitive handling. It matches an explicit disabled setting and does not require a rebuild for that difference. An explicitly enabled setting can use different document IDs and still requires a compatibility decision against either value. Other configuration differences shown in the dialogue must still be resolved. +If the mismatch names **Encrypt internal file Properties**, update every device before accepting that preference. It affects subsequent Metadata writes for Hidden File Sync and Customisation Sync; it does not automatically protect existing Metadata. A manual remote Rebuild is strongly recommended if you need to protect existing paths, times, sizes, and Chunk references. + The `Sync now` command keeps routine replication progress quiet so that it is convenient to assign to a keyboard shortcut; assign one in Obsidian if that suits your workflow. A quiet command may still open this dialogue when a mismatch or another decision requires your attention. The available actions depend on when the mismatch is found: @@ -109,12 +111,20 @@ The available actions depend on when the mismatch is found: Historic defect notices and renamed controls are retained in the [0.25 release history](releases/0.25.md) and [legacy release history](releases/legacy.md), rather than in the current troubleshooting path. +## The remote database uses an unknown feature + +When a notice identifies an unknown feature, update this device and every other client of the same CouchDB database, including the CLI. The notice includes the feature identifier even if this version has no descriptive name for it. New synchronisation is refused, and receiving an unsupported requirement stops active replication, because an older client may not interpret the Metadata and its Chunk references correctly. Already queued file changes are not rolled back. The cleaned-remote recovery path also checks compatibility before counting Chunk references. Do not remove the feature name from the remote version document to bypass the check. After updating, reconnect and review any pending file changes before running Garbage Collection. + ## Setup and settings questions ### Share a configuration with another device Generate an encrypted Setup URI from a working device. This preserves the intended remote profiles and selections while allowing the additional device to keep its own device-specific name. Store the URI and its passphrase separately. +Choose **Time-bound** for sharing until the displayed end time, or **Compatible (no time limit)** when the URI must remain reusable or the receiving client only supports the existing format. If a Time-bound URI can no longer be opened, check the device clock and generate a fresh URI on a working device. See the [Setup URI sharing choices](settings.md#copy-the-current-settings-to-a-setup-uri). + +Adding a device or opening a copied Vault does not require a compatibility pause solely because its device-local version record is absent. If an earlier release already saved a compatibility pause, review the settings and resume synchronisation explicitly. Actual version or settings incompatibilities still require review. + For deliberate setting changes during normal use, use `Sync Settings via Markdown` under `Sync settings`. ### Choose a Setup URI passphrase diff --git a/manifest.json b/manifest.json index 6d9bcb18..63cf5be3 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "obsidian-livesync", "name": "Self-hosted LiveSync", - "version": "1.0.30", + "version": "1.0.35", "minAppVersion": "1.7.2", "description": "Community implementation of self-hosted livesync. Reflect your vault changes to some other devices immediately. Please make sure to disable other synchronize solutions to avoid content corruption or duplication.", "author": "vorotamoroz", diff --git a/package-lock.json b/package-lock.json index 01b9f1d2..26be2de9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "obsidian-livesync", - "version": "1.0.30", + "version": "1.0.35", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "obsidian-livesync", - "version": "1.0.30", + "version": "1.0.35", "license": "MIT", "workspaces": [ "src/apps/cli", @@ -23,12 +23,12 @@ "@smithy/types": "^4.14.3", "@smithy/util-retry": "^4.4.5", "@vrtmrz/browser-ui-kit": "0.1.0", - "@vrtmrz/livesync-commonlib": "0.1.28", + "@vrtmrz/livesync-commonlib": "0.1.36", "@vrtmrz/obsidian-plugin-kit": "0.1.4", "@vrtmrz/ui-interactions": "0.1.2", "diff-match-patch": "^1.0.5", "idb": "^8.0.3", - "markdown-it": "^14.2.0", + "markdown-it": "^14.3.2", "minimatch": "^10.2.5", "obsidian": "^1.13.1", "octagonal-wheels": "^0.1.54", @@ -56,7 +56,7 @@ "@types/pouchdb-replication": "^6.4.7", "@types/transform-pouch": "^1.0.6", "@typescript-eslint/parser": "8.69.0", - "@vitest/coverage-v8": "^4.1.8", + "@vitest/coverage-v8": "^4.1.11", "@vrtmrz/obsidian-test-session": "0.2.6", "dotenv-cli": "^11.0.0", "esbuild": "0.28.1", @@ -93,7 +93,7 @@ "typescript": "6.0.3", "typescript-eslint": "8.69.0", "vite": "^8.0.16", - "vitest": "^4.1.8", + "vitest": "^4.1.11", "yaml": "^2.8.2" } }, @@ -1873,9 +1873,9 @@ "license": "MIT" }, "node_modules/@eslint/config-array/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -1954,9 +1954,9 @@ "license": "MIT" }, "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -4414,14 +4414,14 @@ } }, "node_modules/@vitest/coverage-v8": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.8.tgz", - "integrity": "sha512-lt3kovsyHwYe00wq4D1ti0Z974fWj4NLp6siqiyEufUpyFwK9Yhi7rBhac9JL5aA0zoMrJqc4vYPZRUnI7l7nw==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.11.tgz", + "integrity": "sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==", "dev": true, "license": "MIT", "dependencies": { "@bcoe/v8-coverage": "^1.0.2", - "@vitest/utils": "4.1.8", + "@vitest/utils": "4.1.11", "ast-v8-to-istanbul": "^1.0.0", "istanbul-lib-coverage": "^3.2.2", "istanbul-lib-report": "^3.0.1", @@ -4435,8 +4435,8 @@ "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "@vitest/browser": "4.1.8", - "vitest": "4.1.8" + "@vitest/browser": "4.1.11", + "vitest": "4.1.11" }, "peerDependenciesMeta": { "@vitest/browser": { @@ -4445,16 +4445,16 @@ } }, "node_modules/@vitest/expect": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.8.tgz", - "integrity": "sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", + "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", "dev": true, "license": "MIT", "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" }, @@ -4463,13 +4463,13 @@ } }, "node_modules/@vitest/mocker": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.8.tgz", - "integrity": "sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", + "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/spy": "4.1.8", + "@vitest/spy": "4.1.11", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, @@ -4490,9 +4490,9 @@ } }, "node_modules/@vitest/pretty-format": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.8.tgz", - "integrity": "sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", + "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", "dev": true, "license": "MIT", "dependencies": { @@ -4503,13 +4503,13 @@ } }, "node_modules/@vitest/runner": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.8.tgz", - "integrity": "sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", + "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "4.1.8", + "@vitest/utils": "4.1.11", "pathe": "^2.0.3" }, "funding": { @@ -4517,14 +4517,14 @@ } }, "node_modules/@vitest/snapshot": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.8.tgz", - "integrity": "sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", + "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/pretty-format": "4.1.11", + "@vitest/utils": "4.1.11", "magic-string": "^0.30.21", "pathe": "^2.0.3" }, @@ -4533,9 +4533,9 @@ } }, "node_modules/@vitest/spy": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.8.tgz", - "integrity": "sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", + "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", "dev": true, "license": "MIT", "funding": { @@ -4543,13 +4543,13 @@ } }, "node_modules/@vitest/utils": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.8.tgz", - "integrity": "sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", + "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.8", + "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" }, @@ -4567,9 +4567,9 @@ } }, "node_modules/@vrtmrz/livesync-commonlib": { - "version": "0.1.28", - "resolved": "https://registry.npmjs.org/@vrtmrz/livesync-commonlib/-/livesync-commonlib-0.1.28.tgz", - "integrity": "sha512-3NXswTtOU+fE4KRxBWHfkMx9r2Eu9IFH9N/ibj75C5eLh1tFPH7n87bGib6La7Twz9yCDIJRBsBUc2tx81rxOQ==", + "version": "0.1.36", + "resolved": "https://registry.npmjs.org/@vrtmrz/livesync-commonlib/-/livesync-commonlib-0.1.36.tgz", + "integrity": "sha512-YEVEM3Uq0YnqMP70hOFhmfkyS2X3Ptp/t43EH/6yc/NirQhpTYfYV6hLEuXok5LEw2gkWV7G6wMiYGlEjFCTig==", "license": "MIT", "dependencies": { "@aws-sdk/client-s3": "^3.808.0", @@ -5014,9 +5014,9 @@ "license": "MIT" }, "node_modules/babel-plugin-module-resolver/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -5152,9 +5152,9 @@ "license": "MIT" }, "node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" @@ -5629,9 +5629,9 @@ } }, "node_modules/devalue": { - "version": "5.9.2", - "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.2.tgz", - "integrity": "sha512-po4PAY5c53tw5XMocSnf8A/5OHhbbUftpr93aEN6BBoAdntUmK7vu7wOATqvt7cXO7m1Cl4gMVn6p7n6n4mj0w==", + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.3.tgz", + "integrity": "sha512-xRumYOCUZN/EesqHEU3WOXanOZNvfZFZ/o1AHVFDX1yI0UAkZkOgDXt341CzKoBVIkgQba55/+DjGBKrIoKcHw==", "devOptional": true, "license": "MIT" }, @@ -6326,9 +6326,9 @@ "license": "MIT" }, "node_modules/eslint-plugin-import/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -6423,9 +6423,9 @@ "license": "MIT" }, "node_modules/eslint-plugin-json-schema-validator/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -6489,9 +6489,9 @@ "license": "MIT" }, "node_modules/eslint-plugin-n/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -6666,9 +6666,9 @@ "license": "MIT" }, "node_modules/eslint-plugin-react/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -6868,9 +6868,9 @@ "license": "MIT" }, "node_modules/eslint/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -7087,9 +7087,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.6.tgz", - "integrity": "sha512-7Ical1vFEMr0onbVzEDIreM22I4khW+fzyQPwvAFWBp1iwdshSZRsL4jjRvPG9JP1uiqMHRto+YU6R2/CzDz5Q==", + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", "dev": true, "funding": [ { @@ -7541,9 +7541,9 @@ "license": "MIT" }, "node_modules/globby/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -9199,9 +9199,9 @@ } }, "node_modules/markdown-it": { - "version": "14.2.0", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.2.0.tgz", - "integrity": "sha512-1TGiQiJVRQ3NPmZH6sx5Cfnmg6GQm9jvC1ch4TK511NjSJvjzKLzn5pPfZRNZkRPZP0HqCioSndqH8v2nRaWVQ==", + "version": "14.3.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.3.2.tgz", + "integrity": "sha512-sHHjZ5fJKlgrG4qns2YwVcdNep35h5fERrfkD2YNsb9UFk0UIHarbiTaHKVMlPuWAoiilyK8Fv/jAm11slsY7Q==", "funding": [ { "type": "github", @@ -9215,8 +9215,8 @@ "license": "MIT", "dependencies": { "argparse": "^2.0.1", - "entities": "^4.4.0", - "linkify-it": "^5.0.1", + "entities": "^4.5.0", + "linkify-it": "^5.0.2", "mdurl": "^2.0.0", "punycode.js": "^2.3.1", "uc.micro": "^2.1.0" @@ -9341,9 +9341,9 @@ "license": "MIT" }, "node_modules/moment": { - "version": "2.29.4", - "resolved": "https://registry.npmjs.org/moment/-/moment-2.29.4.tgz", - "integrity": "sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==", + "version": "2.31.0", + "resolved": "https://registry.npmjs.org/moment/-/moment-2.31.0.tgz", + "integrity": "sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw==", "license": "MIT", "engines": { "node": "*" @@ -11107,35 +11107,6 @@ "node": ">= 0.4" } }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/string_decoder/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/string.prototype.matchall": { "version": "4.0.12", "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz", @@ -11234,6 +11205,35 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/strip-bom": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", @@ -12216,19 +12216,19 @@ } }, "node_modules/vitest": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.8.tgz", - "integrity": "sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", + "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.1.8", - "@vitest/mocker": "4.1.8", - "@vitest/pretty-format": "4.1.8", - "@vitest/runner": "4.1.8", - "@vitest/snapshot": "4.1.8", - "@vitest/spy": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/expect": "4.1.11", + "@vitest/mocker": "4.1.11", + "@vitest/pretty-format": "4.1.11", + "@vitest/runner": "4.1.11", + "@vitest/snapshot": "4.1.11", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", @@ -12256,12 +12256,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.8", - "@vitest/browser-preview": "4.1.8", - "@vitest/browser-webdriverio": "4.1.8", - "@vitest/coverage-istanbul": "4.1.8", - "@vitest/coverage-v8": "4.1.8", - "@vitest/ui": "4.1.8", + "@vitest/browser-playwright": "4.1.11", + "@vitest/browser-preview": "4.1.11", + "@vitest/browser-webdriverio": "4.1.11", + "@vitest/coverage-istanbul": "4.1.11", + "@vitest/coverage-v8": "4.1.11", + "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" @@ -12665,7 +12665,7 @@ }, "src/apps/cli": { "name": "self-hosted-livesync-cli", - "version": "1.0.30-cli", + "version": "1.0.35-cli", "dependencies": { "chokidar": "^4.0.0", "minimatch": "^10.2.5", @@ -12685,12 +12685,12 @@ "devDependencies": { "typescript": "6.0.3", "vite": "^8.0.16", - "vitest": "^4.1.8" + "vitest": "^4.1.11" } }, "src/apps/webapp": { "name": "livesync-webapp", - "version": "1.0.30-webapp", + "version": "1.0.35-webapp", "dependencies": { "octagonal-wheels": "^0.1.54" }, @@ -12702,7 +12702,7 @@ } }, "src/apps/webpeer": { - "version": "1.0.30-webpeer", + "version": "1.0.35-webpeer", "dependencies": { "octagonal-wheels": "^0.1.54" }, diff --git a/package.json b/package.json index f2e8dc1b..ea74620e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "obsidian-livesync", - "version": "1.0.30", + "version": "1.0.35", "description": "Reflect your vault changes to some other devices immediately. Please make sure to disable other synchronize solutions to avoid content corruption or duplication.", "main": "main.js", "type": "module", @@ -66,11 +66,15 @@ "test:e2e:obsidian:p2p-pane": "tsx test/e2e-obsidian/scripts/p2p-pane.ts", "test:e2e:obsidian:vault-reflection": "tsx test/e2e-obsidian/scripts/vault-reflection.ts", "test:e2e:obsidian:couchdb-upload": "tsx test/e2e-obsidian/scripts/couchdb-upload.ts", + "test:e2e:obsidian:couchdb-http-cache": "tsx test/e2e-obsidian/scripts/couchdb-http-cache.ts", + "test:e2e:obsidian:chunk-fetch-retry": "tsx test/e2e-obsidian/scripts/chunk-fetch-retry.ts", "test:e2e:obsidian:tweak-compatibility": "tsx test/e2e-obsidian/scripts/tweak-compatibility.ts", "test:e2e:obsidian:couchdb-manual-setup-workflow": "tsx test/e2e-obsidian/scripts/couchdb-manual-setup-workflow.ts", "test:e2e:obsidian:cli-to-obsidian-sync": "tsx test/e2e-obsidian/scripts/cli-to-obsidian-sync.ts", "test:e2e:obsidian:minio-upload": "tsx test/e2e-obsidian/scripts/minio-upload.ts", "test:e2e:obsidian:object-storage-setup-uri-workflow": "tsx test/e2e-obsidian/scripts/object-storage-setup-uri-workflow.ts", + "test:e2e:obsidian:object-storage-compatible-setup-uri-workflow": "tsx test/e2e-obsidian/scripts/object-storage-setup-uri-workflow.ts --compatible", + "test:e2e:obsidian:object-storage-qr-workflow": "tsx test/e2e-obsidian/scripts/object-storage-setup-uri-workflow.ts --qr", "test:e2e:obsidian:object-storage-custom-http-handler-setup-uri-workflow": "tsx test/e2e-obsidian/scripts/object-storage-setup-uri-workflow.ts --custom-http-handler", "test:e2e:obsidian:p2p-setup-uri-workflow": "tsx test/e2e-obsidian/scripts/p2p-setup-uri-workflow.ts", "pretest:e2e:obsidian:p2p-connection-check": "npm run build && npm run build --workspace webpeer", @@ -85,7 +89,12 @@ "test:e2e:obsidian:security-seed-reconnect": "tsx test/e2e-obsidian/scripts/security-seed-reconnect.ts", "test:e2e:obsidian:hidden-file-snippet-sync": "tsx test/e2e-obsidian/scripts/hidden-file-snippet-sync.ts", "test:e2e:obsidian:customisation-sync": "tsx test/e2e-obsidian/scripts/customisation-sync.ts", + "test:e2e:obsidian:received-change-readiness": "tsx test/e2e-obsidian/scripts/received-change-readiness.ts", + "test:e2e:obsidian:remote-feature-change": "tsx test/e2e-obsidian/scripts/remote-feature-change.ts", + "test:e2e:obsidian:internal-metadata-migration": "tsx test/e2e-obsidian/scripts/internal-metadata-migration.ts", + "test:e2e:obsidian:internal-metadata-doctor": "tsx test/e2e-obsidian/scripts/internal-metadata-migration.ts --doctor", "test:e2e:obsidian:setting-markdown-export": "tsx test/e2e-obsidian/scripts/setting-markdown-export.ts", + "test:e2e:obsidian:setting-markdown-roundtrip": "tsx test/e2e-obsidian/scripts/setting-markdown-roundtrip.ts", "test:e2e:obsidian:upgrade-from-stable": "tsx test/e2e-obsidian/scripts/upgrade-from-stable.ts", "test:e2e:obsidian:local-suite": "tsx test/e2e-obsidian/scripts/local-suite.ts", "test:e2e:obsidian:local-suite:services": "tsx test/e2e-obsidian/scripts/local-suite.ts --manage-services", @@ -133,7 +142,7 @@ "@types/pouchdb-replication": "^6.4.7", "@types/transform-pouch": "^1.0.6", "@typescript-eslint/parser": "8.69.0", - "@vitest/coverage-v8": "^4.1.8", + "@vitest/coverage-v8": "^4.1.11", "@vrtmrz/obsidian-test-session": "0.2.6", "dotenv-cli": "^11.0.0", "esbuild": "0.28.1", @@ -170,7 +179,7 @@ "typescript": "6.0.3", "typescript-eslint": "8.69.0", "vite": "^8.0.16", - "vitest": "^4.1.8", + "vitest": "^4.1.11", "yaml": "^2.8.2" }, "dependencies": { @@ -183,12 +192,12 @@ "@smithy/types": "^4.14.3", "@smithy/util-retry": "^4.4.5", "@vrtmrz/browser-ui-kit": "0.1.0", - "@vrtmrz/livesync-commonlib": "0.1.28", + "@vrtmrz/livesync-commonlib": "0.1.36", "@vrtmrz/obsidian-plugin-kit": "0.1.4", "@vrtmrz/ui-interactions": "0.1.2", "diff-match-patch": "^1.0.5", "idb": "^8.0.3", - "markdown-it": "^14.2.0", + "markdown-it": "^14.3.2", "minimatch": "^10.2.5", "obsidian": "^1.13.1", "octagonal-wheels": "^0.1.54", @@ -196,6 +205,12 @@ "xxhash-wasm-102": "npm:xxhash-wasm@^1.0.2" }, "overrides": { + "obsidian": { + "moment": "2.31.0" + }, + "svelte": { + "devalue": "5.9.3" + }, "pouchdb-core": { "uuid": "11.1.1" }, diff --git a/src/apps/cli/commands/runCommand.unit.spec.ts b/src/apps/cli/commands/runCommand.unit.spec.ts index f4d3a45a..61d253a1 100644 --- a/src/apps/cli/commands/runCommand.unit.spec.ts +++ b/src/apps/cli/commands/runCommand.unit.spec.ts @@ -419,6 +419,38 @@ describe("runCommand abnormal cases", () => { expect(appliedSettings.useIndexedDBAdapter).toBe(false); }); + it("setup opens Ephemeral in its window and leaves settings untouched afterwards", async () => { + const end = Date.parse("2026-10-01T00:00:00Z"); + const clock = vi.spyOn(Date, "now").mockReturnValue(end - 1_000); + const passphrase = "time-bound-passphrase"; + try { + const { uri, usableUntil } = await processSetting.encodeTimeBoundSetupURI( + { ...DEFAULT_SETTINGS, isConfigured: true, couchDB_DBNAME: "time-bound-vault" }, + passphrase + ); + expect(usableUntil).toBe(end); + + const inWindow = createCoreMock(); + inWindow.services.context.standardIo.prompt.mockResolvedValue(passphrase); + await runCommand(makeOptions("setup", [uri.trim()]), { ...context, core: inWindow }); + expect(inWindow.services.setting.applyExternalSettings).toHaveBeenCalledWith( + expect.objectContaining({ couchDB_DBNAME: "time-bound-vault" }), + true + ); + + clock.mockReturnValue(end); + const outOfWindow = createCoreMock(); + outOfWindow.services.context.standardIo.prompt.mockResolvedValue(passphrase); + await expect(runCommand(makeOptions("setup", [uri.trim()]), { ...context, core: outOfWindow })).rejects.toThrow( + "Cannot open Setup URI" + ); + expect(outOfWindow.services.setting.applyExternalSettings).not.toHaveBeenCalled(); + expect(outOfWindow.services.control.applySettings).not.toHaveBeenCalled(); + } finally { + clock.mockRestore(); + } + }); + it("setup imports managed TURN through the existing encrypted URI", async () => { const core = createCoreMock(); const profiles = { diff --git a/src/apps/cli/package.json b/src/apps/cli/package.json index 0b4a51f4..208659aa 100644 --- a/src/apps/cli/package.json +++ b/src/apps/cli/package.json @@ -1,7 +1,7 @@ { "name": "self-hosted-livesync-cli", "private": true, - "version": "1.0.30-cli", + "version": "1.0.35-cli", "main": "dist/index.cjs", "type": "module", "scripts": { @@ -53,6 +53,6 @@ "devDependencies": { "typescript": "6.0.3", "vite": "^8.0.16", - "vitest": "^4.1.8" + "vitest": "^4.1.11" } } diff --git a/src/apps/cli/testdeno/helpers/docker.ts b/src/apps/cli/testdeno/helpers/docker.ts index 159d6e60..822f0211 100644 --- a/src/apps/cli/testdeno/helpers/docker.ts +++ b/src/apps/cli/testdeno/helpers/docker.ts @@ -628,7 +628,7 @@ export async function startP2pRelay(): Promise { //TODO: port mapping should be configurable. "4000:7777", "--tmpfs", - "/app/strfry-db:rw,size=256m", + "/app/strfry-db:rw,size=256m,mode=1777", "--entrypoint", "sh", P2P_RELAY_IMAGE, diff --git a/src/apps/cli/testdeno/helpers/settings.ts b/src/apps/cli/testdeno/helpers/settings.ts index 524622c0..bb999b13 100644 --- a/src/apps/cli/testdeno/helpers/settings.ts +++ b/src/apps/cli/testdeno/helpers/settings.ts @@ -13,7 +13,11 @@ export async function initSettingsFile(settingsFile: string): Promise { * Generate a full setup URI from a settings file via the Commonlib package API. * Mirrors the bash flow in test-setup-put-cat-linux.sh. */ -export async function generateSetupUriFromSettings(settingsFile: string, setupPassphrase: string): Promise { +export async function generateSetupUriFromSettings( + settingsFile: string, + setupPassphrase: string, + preserveRemoteSettings = false +): Promise { const script = [ "import { fs } from '@vrtmrz/livesync-commonlib/node';", "import { encodeSettingsToSetupURI } from '@vrtmrz/livesync-commonlib/compat/API/processSetting';", @@ -21,13 +25,17 @@ export async function generateSetupUriFromSettings(settingsFile: string, setupPa " const settingsPath = process.env.SETTINGS_FILE;", " const passphrase = process.env.SETUP_PASSPHRASE;", " const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));", - " settings.couchDB_DBNAME = 'setup-put-cat-db';", - " settings.couchDB_URI = 'http://127.0.0.1:5999';", - " settings.couchDB_USER = 'dummy';", - " settings.couchDB_PASSWORD = 'dummy';", - " settings.liveSync = false;", - " settings.syncOnStart = false;", - " settings.syncOnSave = false;", + ...(preserveRemoteSettings + ? [] + : [ + " settings.couchDB_DBNAME = 'setup-put-cat-db';", + " settings.couchDB_URI = 'http://127.0.0.1:5999';", + " settings.couchDB_USER = 'dummy';", + " settings.couchDB_PASSWORD = 'dummy';", + " settings.liveSync = false;", + " settings.syncOnStart = false;", + " settings.syncOnSave = false;", + ]), " const uri = await encodeSettingsToSetupURI(settings, passphrase);", " process.stdout.write(uri.trim());", "})();", diff --git a/src/apps/cli/testdeno/test-p2p-sync.ts b/src/apps/cli/testdeno/test-p2p-sync.ts index e05c6efe..32f3d1ad 100644 --- a/src/apps/cli/testdeno/test-p2p-sync.ts +++ b/src/apps/cli/testdeno/test-p2p-sync.ts @@ -1,6 +1,11 @@ import { assert } from "@std/assert"; import { TempDir } from "./helpers/temp.ts"; -import { initSettingsFile, applyP2pSettings, applyP2pTestTweaks } from "./helpers/settings.ts"; +import { + initSettingsFile, + applyP2pSettings, + applyP2pTestTweaks, + generateSetupUriFromSettings, +} from "./helpers/settings.ts"; import { startCliInBackground } from "./helpers/backgroundCli.ts"; import { discoverPeer, @@ -9,10 +14,10 @@ import { maybeStartCoturn, stopCoturnIfStarted, } from "./helpers/p2p.ts"; -import { runCli } from "./helpers/cli.ts"; +import { runCli, runCliOrFail, runCliWithInputOrFail, sanitiseCatStdout } from "./helpers/cli.ts"; import { getOptimalLoopbackIp } from "./helpers/net.ts"; -Deno.test("p2p-sync: discovers peer and completes sync", async () => { +Deno.test("p2p-sync: transfers with the same ID key and rejects a different document ID key", async () => { const loopbackIp = await getOptimalLoopbackIp(); const loopbackHost = loopbackIp === "::1" ? "[::1]" : loopbackIp; @@ -32,14 +37,18 @@ Deno.test("p2p-sync: discovers peer and completes sync", async () => { const hostSettings = workDir.join("settings-host.json"); const clientVault = workDir.join("vault-sync"); const clientSettings = workDir.join("settings-sync.json"); + const rejectedVault = workDir.join("vault-rejected"); + const rejectedSettings = workDir.join("settings-rejected.json"); await Deno.mkdir(hostVault, { recursive: true }); await Deno.mkdir(clientVault, { recursive: true }); + await Deno.mkdir(rejectedVault, { recursive: true }); const relayStarted = await maybeStartLocalRelay(relay); const coturnStarted = await maybeStartCoturn(turnServers); try { await initSettingsFile(hostSettings); await initSettingsFile(clientSettings); + await initSettingsFile(rejectedSettings); await applyP2pSettings( hostSettings, roomId, @@ -58,8 +67,52 @@ Deno.test("p2p-sync: discovers peer and completes sync", async () => { "~.*", turnServers ); + await applyP2pSettings( + rejectedSettings, + roomId, + passphrase, + "self-hosted-livesync-cli-tests", + relay, + "~.*", + turnServers + ); await applyP2pTestTweaks(hostSettings, hostPeerName, passphrase); await applyP2pTestTweaks(clientSettings, clientPeerName, passphrase); + await applyP2pTestTweaks(rejectedSettings, "p2p-rejected-" + nonce, passphrase); + for (const [vault, path, key, label] of [ + [hostVault, hostSettings, "ab".repeat(32), "host"], + [clientVault, clientSettings, "ab".repeat(32), "client"], + [rejectedVault, rejectedSettings, "cd".repeat(32), "rejected"], + ]) { + const settings = JSON.parse(await Deno.readTextFile(path)); + settings.idDerivationVersion = 1; + settings.idDerivationKey = key; + const sourcePath = workDir.join("setup-source-" + label + ".json"); + await Deno.writeTextFile(sourcePath, JSON.stringify(settings)); + const setupPassphrase = "independent-id-setup-passphrase"; + const setupUri = await generateSetupUriFromSettings(sourcePath, setupPassphrase, true); + await runCliWithInputOrFail(setupPassphrase + "\n", vault, "--settings", path, "setup", setupUri); + const persisted = JSON.parse(await Deno.readTextFile(path)); + assert(persisted.idDerivationVersion === 1, "The Setup URI lost the ID derivation version."); + assert(persisted.idDerivationKey === "", "The CLI stored the ID key in plain text."); + assert( + typeof persisted.encryptedIdDerivationKey === "string" && persisted.encryptedIdDerivationKey.length > 0, + "The CLI did not encrypt the saved ID key." + ); + assert(persisted.P2P_Enabled === true, "The Setup URI disabled P2P."); + assert(persisted.P2P_roomID === roomId, "The Setup URI changed the P2P room."); + assert(persisted.P2P_relays === relay, "The Setup URI changed the P2P relay."); + assert(persisted.remoteType === "ONLY_P2P", "The Setup URI changed the remote type."); + } + const notePath = "p2p/independent-id-note.md"; + await runCliWithInputOrFail( + "A note transferred with the saved ID key.\n", + clientVault, + "--settings", + clientSettings, + "put", + notePath + ); const host = startCliInBackground(hostVault, "--settings", hostSettings, "p2p-host"); try { @@ -82,9 +135,32 @@ Deno.test("p2p-sync: discovers peer and completes sync", async () => { syncResult.code === 0, `p2p-sync failed\nstdout: ${syncResult.stdout}\nstderr: ${syncResult.stderr}` ); + const rejectedPeer = await discoverPeer(rejectedVault, rejectedSettings, peersTimeout, hostPeerName); + const rejectedSync = await runCli( + rejectedVault, + "--settings", + rejectedSettings, + "p2p-sync", + rejectedPeer.id, + String(syncTimeout) + ); + assert( + rejectedSync.code !== 0, + `P2P accepted a different key for obfuscated document IDs.\nstdout: ${rejectedSync.stdout}\nstderr: ${rejectedSync.stderr}` + ); + assert( + rejectedSync.combined.includes("Tweak values are not matched"), + `P2P failed before checking peer settings.\nstdout: ${rejectedSync.stdout}\nstderr: ${rejectedSync.stderr}` + ); } finally { await host.stop(); } + const received = sanitiseCatStdout( + await runCliOrFail(hostVault, "--settings", hostSettings, "cat", notePath) + ).trimEnd(); + assert(received === "A note transferred with the saved ID key.", "The host did not receive the keyed note."); + const rejectedRead = await runCli(rejectedVault, "--settings", rejectedSettings, "cat", notePath); + assert(rejectedRead.code !== 0, "The rejected device received the keyed note."); } finally { await stopLocalRelayIfStarted(relayStarted); await stopCoturnIfStarted(coturnStarted); diff --git a/src/apps/webapp/package.json b/src/apps/webapp/package.json index 8e05dce8..1c6993bb 100644 --- a/src/apps/webapp/package.json +++ b/src/apps/webapp/package.json @@ -1,7 +1,7 @@ { "name": "livesync-webapp", "private": true, - "version": "1.0.30-webapp", + "version": "1.0.35-webapp", "type": "module", "description": "Browser-based Self-hosted LiveSync using FileSystem API", "scripts": { diff --git a/src/apps/webpeer/package.json b/src/apps/webpeer/package.json index d245db9d..85b3a6ba 100644 --- a/src/apps/webpeer/package.json +++ b/src/apps/webpeer/package.json @@ -1,7 +1,7 @@ { "name": "webpeer", "private": true, - "version": "1.0.30-webpeer", + "version": "1.0.35-webpeer", "type": "module", "scripts": { "dev": "vite", diff --git a/src/apps/webpeer/src/P2PCheck.svelte b/src/apps/webpeer/src/P2PCheck.svelte index 670b306f..151cc1c4 100644 --- a/src/apps/webpeer/src/P2PCheck.svelte +++ b/src/apps/webpeer/src/P2PCheck.svelte @@ -1,7 +1,8 @@ @@ -52,7 +158,11 @@ {translateMessage("Please configure your end-to-end encryption settings.")} - + toggleEncryption(event.currentTarget.checked)} + /> {translateMessage( @@ -87,6 +197,182 @@ {/if} +
+ {translateMessage("ID generation")} + + + +
+ {#if encryptionSettings.encrypt && idConfigurationChoice === "keep" && !idDerivationConfigured} + + {translateMessage("Changing the E2EE passphrase changes IDs generated by the legacy configuration.")} + + {/if} + {#if (encryptionSettings.encrypt && idConfigurationChoice !== "keep") || idDerivationConfigured} + {#if encryptionSettings.encrypt} + + {translateMessage( + "This uses a saved key for new Chunk IDs and obfuscated Metadata document IDs, so changing the E2EE passphrase does not derive a new key automatically." + )} + + {/if} + {#if idDerivationConfigured} + + {translateMessage("The saved ID key is configured. Its source cannot be shown again.")} + + + {#if recoveryCodeVisible} + + + + + {#if recoveryCodeCopied} + {translateMessage("Recovery code copied.")} + {/if} + {/if} + {/if} + {#if encryptionSettings.encrypt} + {#if idConfigurationChoice === "custom"} +
+ {translateMessage("How to set the ID key")} + + + +
+ {#if idCustomChoice === "source" || idCustomChoice === "recovery"} + + + + {/if} + {/if} + {#if idDerivationConfigured && idConfigurationChoice !== "keep"} + + {translateMessage("The displayed recovery code belongs to the current key. Reopen this dialogue after saving to copy the replacement key.")} + + {/if} + {#if idConfigurationChoice === "custom" && idCustomChoice === "source"} + + {translateMessage("Choose a long, unpredictable source. It is used once and cannot be shown again after saving. A recovery code can be displayed on this device later. This input also accepts a tagged recovery code.")} + + {:else if idConfigurationChoice === "custom" && idCustomChoice === "recovery"} + + {translateMessage("Paste a tagged recovery code from an existing device to restore the same ID key.")} + + {:else if idConfigurationChoice === "random"} + + {translateMessage("For recovery after losing every device, save the recovery code after setup or choose an ID source you can reproduce.")} + + {:else if idConfigurationChoice === "custom" && idCustomChoice === "passphrase"} + + {translateMessage( + "The ID key is derived from the current E2EE passphrase and saved separately. Changing that passphrase later does not change the saved ID key. To reduce the risk of guessing that passphrase from known IDs, use a separate, unpredictable ID source instead." + )} + + {/if} + {#if idDerivationConfigured && idConfigurationChoice === "custom" && idCustomChoice !== "passphrase"} + {translateMessage("Leave this input empty to keep the saved ID key.")} + {/if} + {/if} + {idDerivationError} + {/if} + + + + + + This option encrypts file properties used by Hidden File Sync and Customisation Sync. +
+ It applies only to CouchDB and requires End-to-End Encryption, the V2 algorithm, and Property Encryption + (Obfuscate Properties). The remote type is selected later in this setup wizard. +
+ It protects properties written after the option is enabled; existing properties are not rewritten. A manual remote + Rebuild is strongly recommended to protect existing properties. Update every other synchronising device to a compatible + version before enabling this option, including devices currently running LiveSync. +
+