diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e5f915a..8467a21 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,7 +50,9 @@ Routes use the bare query, for example `/webapp/?/library/artist/123#section`. E - Read Cache collections directly; change them through explicit methods. Session owns account details; Cache accepts an opaque account key and hashes it for storage. An undefined key creates an empty, non-persisting fallback. A defined key does not mean hydration succeeded. - Library, queue, playlist, and image memory updates checkpoint asynchronously. Downloads instead await explicit queued/failed/completed commits in one versioned store; failed jobs require explicit Retry or a bulk Download action. Interrupted queued jobs restart from scratch, never adopting unregistered bytes. Successful byte close wins cancellation while completed metadata commits; cancellation joins that work. Unknown queued/failed job fields, including old attempts, are ignored on load and omitted on subsequent writes; orphan-file reclamation after old attempts or abrupt termination is intentionally out of scope. Work offline disables all server domains and pauses queued downloads, retaining durable intent. One Network-owned connection serves every domain; reconnect resumes queued, never failed jobs. All music/Downloaded is a separate browsing preference and never filters or rewrites the queue. Cached playback may continue offline; remote playback stops. Do not treat visible state as proof of persistence. Unreadable download documents are preserved, not reset; readable saved files remain usable. - Credentials use localStorage only, until disconnect. Token login stores username/token/salt; verified direct-password fallback stores the actual password. localStorage is not encrypted and is readable by same-origin scripts. Never log credentials or credential-bearing URLs. Legacy token records migrate without changing account keys; migration writeback is best-effort. -- Disconnect retains local data for offline use. Same-account reconnects reuse the live cache to preserve edits. Account changes drain old writes and retire resources before committing the new workspace. Late results must not leak into a different account. +- Session acquires an exclusive Web Lock with `ifAvailable`, named from the same SHA-256 account identity as OPFS, before hydration or authenticated producers. Only one tab activates a persistent account; another is blocked, not a read-only replica. Retry is explicit after closing the owner; there is no polling/takeover. Missing Web Locks blocks activation honestly. Browser document termination releases its lock; it does not guarantee the last in-memory edit survived a crash. +- Disconnect retains local data and ownership for offline use. Same-account reconnects reuse the live cache and lease to preserve edits. Different-account preparation acquires its lease first; failures retain the original workspace. Account changes stop producers and drain old writes before releasing ownership. Disposal stops producers, checkpoints globally and cancels/drains disk operations before releasing. Deletion retains ownership even on failure. Late results must not leak into a different account. +- `Cache.flushQueue()` checkpoints only the queue document, independent of other domains’ pending/failing checkpoints. Playback progress, pause, visibility and explicit queue commands use it. Global `flush()` remains for workspace retirement/disposal. These guarantees apply to Session-owned persistent workspaces; direct Cache construction in focused storage fixtures does not acquire a lease. - Startup and manual refresh pull library/artwork/playlist state only. The device queue is authoritative: no automatic server queue reads or writes on startup, refresh, reconnect, progress, pause or visibility changes. Local resume checkpoints remain automatic. Queue in navigation opens Now Playing even when empty/stopped; only confirmed Load server queue and explicit Save queue to server exchange queues. Empty saves confirm clearing the server queue. One exchange runs at a time; local edits remain available. Loads discard stale account/connection/revision/playback results and never autoplay. Saves send a stable starting snapshot without changing local playback. Subsonic selects by track ID, not occurrence: retain a matching local occurrence when membership matches, otherwise select the first match. Preserve unknown IDs. Demo exchange controls are disabled. - Preserve queue IDs and occurrence indexes, including duplicates and unavailable tracks. Filtering the UI must not rewrite the saved queue. - Release browser resources explicitly. The service worker caches the app shell, not API responses or music; offline audio downloads are explicit user actions. @@ -108,6 +110,8 @@ Select suites for the behavior being changed: | `website-cascade.test.cjs` | Script-free landing layout, keyboard/FAQ behavior, and standalone demo journeys | | `design-improvements.test.cjs` | Compact details, full-height player, queue anchors, confirmation, gradients, popover timing, titles, and demo guidance (website server) | +`account-ownership.test.cjs` runs against the app **dev** server with real Web Locks and OPFS: two pages, blocked activation/deletion, explicit keyboard Retry after owner close, preserved duplicate/unknown queue entries and resume, unsupported-browser UI and 320px reflow. Set `ARTIFACT_DIR` to capture screenshots and evidence. The deliberate callback delay used for the Checking screenshot is fixture-only; acquisition remains native. + `cache-downloads.test.cjs` exercises native OPFS close/publication boundaries and restart-from-scratch behavior by importing the owning modules. Run it against the app **dev** server; Downloads, Settings, and navigation checks can run against production preview. Run the website suite against the website server, not the app: diff --git a/README.md b/README.md index e9262c9..1dc1a2b 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ You'll need a reachable **HTTPS server with a Subsonic-compatible API**, such as ### Browser support -Safari 26.0 or newer is required; older Safari versions are not supported. The app uses native URLPattern and OPFS writable files. Safari 26.0–26.1 load Navigation API and invoker commands polyfills on demand; Safari 26.2+ use the native APIs. The dialog `closedby` polyfill and relative `rgb()` colors remain necessary for Safari 26. The standalone styleguide uses native browser features without polyfills. +Safari 26.0 or newer is required; older Safari versions are not supported. The app uses native URLPattern, OPFS writable files, and Web Locks. Without Web Locks, account activation is blocked rather than risking conflicting writes. Safari 26.0–26.1 load Navigation API and invoker commands polyfills on demand; Safari 26.2+ use the native APIs. The dialog `closedby` polyfill and relative `rgb()` colors remain necessary for Safari 26. The standalone styleguide uses native browser features without polyfills. ### Authentication and device storage @@ -57,7 +57,7 @@ Download music while connected, then choose **Work offline** in navigation or Se - **Manage downloads:** Settings → Downloads. - **Refresh library:** Automatic when opening online, or via Settings → Refresh library. -- **Disconnect:** Clears credentials and optionally deletes this account’s local cache and downloads. Remembered identity, preferences, other accounts and server data are unchanged. Close other Libras tabs before deleting local data. +- **Disconnect:** Clears credentials and optionally deletes this account’s local cache and downloads. Remembered identity, preferences, other accounts and server data are unchanged. Only one tab can open an account’s local data at a time, including while deleting it. A second tab is blocked: close the owning tab, then select **Retry**. There is no automatic takeover or live cross-tab queue replication. - **Storage:** Each server/account has its own offline library, saved only in this browser on this device. **Clearing site data deletes it.** ## App updates diff --git a/src/_settings.svelte b/src/_settings.svelte index c190d08..1e348f7 100644 --- a/src/_settings.svelte +++ b/src/_settings.svelte @@ -73,7 +73,7 @@ if (!deleteLocalData) return; cleaning = true; try { - await session.cache?.clear(); + await session.clearLocalData(); } catch { // Disconnect succeeds even if optional local deletion fails. } finally { diff --git a/src/account-ownership.ts b/src/account-ownership.ts new file mode 100644 index 0000000..4d61327 --- /dev/null +++ b/src/account-ownership.ts @@ -0,0 +1,41 @@ +import { hashAccountKey } from "./cache.svelte"; + +export class AccountOwnershipError extends Error { + constructor(readonly reason: "blocked" | "unsupported") { + super( + reason === "blocked" + ? "This account is open in another tab" + : "This browser cannot safely open this account’s local data.", + ); + } +} + +/** One browser-managed exclusive lease, never queued or taken over. */ +export async function acquireAccountOwnership(key: string): Promise<() => Promise> { + if (!navigator.locks) throw new AccountOwnershipError("unsupported"); + const name = `libras-account:${await hashAccountKey(key)}`; + let release!: () => void; + const held = new Promise((resolve) => { + release = resolve; + }); + let accept!: (release: () => Promise) => void; + let reject!: (error: unknown) => void; + const acquired = new Promise<() => Promise>((resolve, fail) => { + accept = resolve; + reject = fail; + }); + const request = navigator.locks.request( + name, + { mode: "exclusive", ifAvailable: true }, + async (lock) => { + if (!lock) throw new AccountOwnershipError("blocked"); + accept(async () => { + release(); + await request; + }); + await held; + }, + ); + void request.catch(reject); + return acquired; +} diff --git a/src/app.svelte b/src/app.svelte index f302c1e..59a1b1b 100644 --- a/src/app.svelte +++ b/src/app.svelte @@ -1,6 +1,6 @@