selfstore 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +4 -0
  2. package/dist/advanced.d.ts +5 -5
  3. package/dist/advanced.js +7 -7
  4. package/dist/backups.d.ts +1 -1
  5. package/dist/backups.js +1 -1
  6. package/dist/backups.js.map +1 -1
  7. package/dist/{cache-lock-LZILZNLP.js → cache-lock-NXIR6JRB.js} +3 -3
  8. package/dist/{cache-lock-LZILZNLP.js.map → cache-lock-NXIR6JRB.js.map} +1 -1
  9. package/dist/{chunk-SGISYMT5.js → chunk-43BJDRPT.js} +2 -2
  10. package/dist/{chunk-SGISYMT5.js.map → chunk-43BJDRPT.js.map} +1 -1
  11. package/dist/{chunk-FDPAKHQS.js → chunk-6746AL4I.js} +9 -4
  12. package/dist/chunk-6746AL4I.js.map +1 -0
  13. package/dist/{chunk-ATUPHVLG.js → chunk-CUFKME4S.js} +5 -5
  14. package/dist/chunk-CUFKME4S.js.map +1 -0
  15. package/dist/{chunk-OWLX6PNT.js → chunk-KHER6MWR.js} +26 -8
  16. package/dist/chunk-KHER6MWR.js.map +1 -0
  17. package/dist/{chunk-IBIEKK36.js → chunk-SKWHKM25.js} +24 -5
  18. package/dist/chunk-SKWHKM25.js.map +1 -0
  19. package/dist/{chunk-JB4JHM7V.js → chunk-SRKUHFRG.js} +17 -8
  20. package/dist/chunk-SRKUHFRG.js.map +1 -0
  21. package/dist/{chunk-CUWB5EWF.js → chunk-TEIAFKFS.js} +63 -22
  22. package/dist/chunk-TEIAFKFS.js.map +1 -0
  23. package/dist/{chunk-BJ3RUMGI.js → chunk-UWVAKBU4.js} +3 -3
  24. package/dist/{chunk-BJ3RUMGI.js.map → chunk-UWVAKBU4.js.map} +1 -1
  25. package/dist/{chunk-N4RPMX3Y.js → chunk-XI3MGK4M.js} +120 -30
  26. package/dist/chunk-XI3MGK4M.js.map +1 -0
  27. package/dist/{drive-Bv94UM8b.d.ts → drive-DNiDXBDe.d.ts} +7 -2
  28. package/dist/flows.d.ts +2 -2
  29. package/dist/flows.js +7 -7
  30. package/dist/flows.js.map +1 -1
  31. package/dist/groups.js +3 -3
  32. package/dist/groups.js.map +1 -1
  33. package/dist/households.d.ts +1 -1
  34. package/dist/households.js +10 -4
  35. package/dist/households.js.map +1 -1
  36. package/dist/index.d.ts +4 -4
  37. package/dist/index.js +14 -11
  38. package/dist/index.js.map +1 -1
  39. package/dist/{local-2py_vGGy.d.ts → local-DsXG7QW7.d.ts} +2 -2
  40. package/dist/local-KIP25T7I.js +7 -0
  41. package/dist/{local-AM22RWRR.js.map → local-KIP25T7I.js.map} +1 -1
  42. package/dist/{store-ChIGEOph.d.ts → store-2RnED1Vq.d.ts} +5 -0
  43. package/dist/sync.js +1 -1
  44. package/dist/widgets.d.ts +2 -2
  45. package/dist/widgets.js +445 -86
  46. package/dist/widgets.js.map +1 -1
  47. package/package.json +129 -97
  48. package/dist/chunk-ATUPHVLG.js.map +0 -1
  49. package/dist/chunk-CUWB5EWF.js.map +0 -1
  50. package/dist/chunk-FDPAKHQS.js.map +0 -1
  51. package/dist/chunk-IBIEKK36.js.map +0 -1
  52. package/dist/chunk-JB4JHM7V.js.map +0 -1
  53. package/dist/chunk-N4RPMX3Y.js.map +0 -1
  54. package/dist/chunk-OWLX6PNT.js.map +0 -1
  55. package/dist/local-AM22RWRR.js +0 -7
package/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # selfstore
2
2
 
3
+ [![ci](https://github.com/selfstoredev/selfstore/actions/workflows/ci.yml/badge.svg)](https://github.com/selfstoredev/selfstore/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/selfstore)](https://www.npmjs.com/package/selfstore)
5
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
3
7
  **Local-first storage for browser apps, batteries included.** Your data lives
4
8
  on the user's device, syncs across their devices without a server, and leaves
5
9
  as a portable encrypted backup they actually own.
@@ -1,10 +1,10 @@
1
- import { B as BackupTarget } from './store-ChIGEOph.js';
2
- export { A as AuthExpiredError, a as BuiltinTargetKind, E as EncodeOptions, H as Header, K as KdfParams, L as LocalStore, b as LocalStoreOptions, c as LocalStoreState, M as MirrorState, d as Mode, P as PasswordCheck, e as PasswordPolicy, f as PasswordRequirement, g as PeerSource, h as PeerState, R as RESERVED_COLLECTION_PREFIX, i as RESERVED_STORE_MODES, j as RecipientStanza, k as ReplicaState, S as SelfstoreError, l as SelfstoreErrorCode, m as Severity, n as Snapshot, o as SnapshotFile, p as StatusAction, q as StatusDescriptor, r as StatusInput, s as StorageState, t as StoreError, u as StoreGroupConfig, v as SyncJournalEntry, w as SyncSource, T as TargetKind, x as checkPasswordPolicy, y as createLocalStore, z as deriveStatus, C as errorLabelKey, D as isAuthExpired, F as isReservedStoreMode, G as isSelfstoreError } from './store-ChIGEOph.js';
1
+ import { B as BackupTarget } from './store-2RnED1Vq.js';
2
+ export { A as AuthExpiredError, a as BuiltinTargetKind, E as EncodeOptions, H as Header, K as KdfParams, L as LocalStore, b as LocalStoreOptions, c as LocalStoreState, M as MirrorState, d as Mode, P as PasswordCheck, e as PasswordPolicy, f as PasswordRequirement, g as PeerSource, h as PeerState, R as RESERVED_COLLECTION_PREFIX, i as RESERVED_STORE_MODES, j as RecipientStanza, k as ReplicaState, S as SelfstoreError, l as SelfstoreErrorCode, m as Severity, n as Snapshot, o as SnapshotFile, p as StatusAction, q as StatusDescriptor, r as StatusInput, s as StorageState, t as StoreError, u as StoreGroupConfig, v as SyncJournalEntry, w as SyncSource, T as TargetKind, x as checkPasswordPolicy, y as createLocalStore, z as deriveStatus, C as errorLabelKey, D as isAuthExpired, F as isReservedStoreMode, G as isSelfstoreError } from './store-2RnED1Vq.js';
3
3
  import { K as KV } from './cache-De5_sALA.js';
4
4
  export { C as CachedFile, L as LocalCache, e as LockableCache, i as indexedDbCache, f as isLockableCache, m as memoryCache } from './cache-De5_sALA.js';
5
- export { e as exportSnapshot, g as gisDriveAuth, i as importSnapshot, a as inspect, b as isEncrypted, p as pickFromDisk, s as saveToDisk } from './local-2py_vGGy.js';
6
- import { c as connect$1, f as fromSession$1, p as preview, a as adopt, b as findOrCreateOwnFile, l as listBackups, d as createBackup, e as deleteBackup, r as renameBackup, g as connect$2, h as fromSession$2, i as connect$3, j as fromSession$3, k as peer } from './drive-Bv94UM8b.js';
7
- export { D as DriveAuth, m as DriveBackupInfo, n as DriveOptions, S as S3Config, o as S3ConnectOptions, W as WebdavConfig, q as WebdavConnectOptions, s as WebdavPeerOptions } from './drive-Bv94UM8b.js';
5
+ export { e as exportSnapshot, g as gisDriveAuth, i as importSnapshot, a as inspect, b as isEncrypted, p as pickFromDisk, s as saveToDisk } from './local-DsXG7QW7.js';
6
+ import { c as connect$1, f as fromSession$1, p as preview, a as adopt, b as findOrCreateOwnFile, l as listBackups, d as createBackup, e as deleteBackup, r as renameBackup, g as connect$2, h as fromSession$2, i as connect$3, j as fromSession$3, k as peer } from './drive-DNiDXBDe.js';
7
+ export { D as DriveAuth, m as DriveBackupInfo, n as DriveOptions, S as S3Config, o as S3ConnectOptions, W as WebdavConfig, q as WebdavConnectOptions, s as WebdavPeerOptions } from './drive-DNiDXBDe.js';
8
8
  import './sync.js';
9
9
 
10
10
  /**
package/dist/advanced.js CHANGED
@@ -1,11 +1,11 @@
1
- export { RESERVED_STORE_MODES, createLocalStore, deriveStatus, gisDriveAuth, indexedDbCache, isLockableCache, isReservedStoreMode, memoryCache } from './chunk-N4RPMX3Y.js';
2
- export { pickFromDisk, saveToDisk } from './chunk-BJ3RUMGI.js';
3
- import './chunk-IBIEKK36.js';
4
- import { FILE_ID_KEY, renameBackup, deleteBackup, createBackup, listBackups, findOrCreateOwnFile, adopt, preview, fromSession, connect, isSupported, fromSession2, connect2, fromSession4, connect4, peer, fromSession3, connect3 } from './chunk-CUWB5EWF.js';
5
- export { RESERVED_COLLECTION_PREFIX, checkPasswordPolicy, exportSnapshot, importSnapshot, inspect, isEncrypted } from './chunk-JB4JHM7V.js';
6
- import './chunk-OWLX6PNT.js';
1
+ export { RESERVED_STORE_MODES, createLocalStore, deriveStatus, gisDriveAuth, indexedDbCache, isLockableCache, isReservedStoreMode, memoryCache } from './chunk-XI3MGK4M.js';
2
+ export { pickFromDisk, saveToDisk } from './chunk-UWVAKBU4.js';
3
+ import './chunk-SKWHKM25.js';
4
+ import { FILE_ID_KEY, renameBackup, deleteBackup, createBackup, listBackups, findOrCreateOwnFile, adopt, preview, fromSession, connect, isSupported, fromSession2, connect2, fromSession4, connect4, peer, fromSession3, connect3 } from './chunk-TEIAFKFS.js';
5
+ export { RESERVED_COLLECTION_PREFIX, checkPasswordPolicy, exportSnapshot, importSnapshot, inspect, isEncrypted } from './chunk-SRKUHFRG.js';
6
+ import './chunk-KHER6MWR.js';
7
7
  import './chunk-QBCU7OOP.js';
8
- import './chunk-FDPAKHQS.js';
8
+ import './chunk-6746AL4I.js';
9
9
  export { AuthExpiredError, SelfstoreError, errorLabelKey, isAuthExpired, isSelfstoreError } from './chunk-VBFMMR7Q.js';
10
10
 
11
11
  // src/entries/advanced.ts
package/dist/backups.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { K as KV } from './cache-De5_sALA.js';
2
- import { B as BackupTarget, L as LocalStore } from './store-ChIGEOph.js';
2
+ import { B as BackupTarget, L as LocalStore } from './store-2RnED1Vq.js';
3
3
  import { F as FlowStore } from './machine-ALMkT3mk.js';
4
4
  import './sync.js';
5
5
 
package/dist/backups.js CHANGED
@@ -1,4 +1,4 @@
1
- import { makeMachine } from './chunk-SGISYMT5.js';
1
+ import { makeMachine } from './chunk-43BJDRPT.js';
2
2
  import './chunk-VBFMMR7Q.js';
3
3
 
4
4
  // src/backups/manager.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/backups/manager.ts"],"names":[],"mappings":";;;;AAiMA,IAAM,YAAA,GAAsC;AAAA,EAC3C,QAAA,EAAU,+BAAA;AAAA,EACV,SA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AAA,OAAO,KAAA;AAAA,MACR;AAAA,IACD,CAAA;AAAA,IAEA,MAAM,aAAa,MAAA,EAAuB;AACzC,MAAA,MAAM,GAAA,GAAM,MAAM,YAAA,EAAa;AAC/B,MAAA,MAAM,YAAA,CAAa;AAAA,QAClB,gBAAgB,GAAA,CAAI,cAAA;AAAA,QACpB,MAAA,EAAQ,IAAI,MAAA,CAAO,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,WAAW,MAAM;AAAA,OACpD,CAAA;AAAA,IACF;AAAA,GACD;AACD","file":"backups.js","sourcesContent":["// Multi-backup manager: several backup files on one destination account, one\n// attached at a time, each an isolated snapshot - opening one replaces the\n// local data, never merges, never touches the other files.\n//\n// It owns the bookkeeping a backup panel needs: the self-healing registry of\n// files this device has connected to; the per-file memories a listing cannot\n// provide (encrypted? shared? - those bits live inside the files, learned as\n// they are opened or probed and remembered in the kv); and the open / create\n// / rename / delete gestures with their isolation invariants (fixed-id\n// targets, active-id committed only after a successful attach, wipe on every\n// switch so no sync-meta crosses files).\n//\n// Injectable and headless: a LocalStore + a kv + a BackupsHost port for the\n// destination I/O. Errors surface as stable codes, never prose; hosts wrap\n// subscribe in their own reactivity.\n\nimport type { KV } from '../persistence/cache';\nimport type { LocalStore } from '../persistence/store';\nimport type { BackupTarget } from '../persistence/target';\nimport { makeMachine, type FlowStore } from '../flows/machine';\n\n// --- Ports --------------------------------------------------------------------\n\n/** What the destination reports about a listed file (one cheap metadata call). */\nexport interface BackupFileInfo {\n\tid: string;\n\tname: string;\n\t/** RFC 3339 last-write timestamp, when the destination reports one. */\n\tmodifiedTime: string | null;\n}\n\n/** The destination I/O the manager drives - the host wires its own adapter\n * (e.g. over the Drive target ops). Every method may throw; the manager turns\n * failures into stable error codes. */\nexport interface BackupsHost {\n\t/** The target kind the managed files live on (e.g. 'drive'): the manager\n\t * only stamps an active file while the store is attached to this kind. */\n\tkind: string;\n\t/** The kv key the attached file id is persisted under (the same one the\n\t * target's connect path reads first). */\n\tactiveIdKey: string;\n\t/** List candidate backup files on the account. The manager applies the\n\t * naming rules on what comes back; internal files simply do not match. */\n\tlist(): Promise<BackupFileInfo[]>;\n\t/** A target over a FIXED file id - never re-resolved by name. The fixed id\n\t * is what keeps two backups from silently merging mid-switch. */\n\topen(fileId: string): BackupTarget;\n\t/** Create an empty file under this name and return its id. Refuse a name\n\t * the account already carries (a duplicate poisons find-by-name). */\n\tcreate(fileName: string): Promise<{ fileId: string }>;\n\t/** Delete a file for good. */\n\tremove(fileId: string): Promise<void>;\n\t/** Rename a file in place (metadata only: the id must not change). */\n\trename?(fileId: string, fileName: string): Promise<void>;\n\t/** Find (or create) the PERSONAL file by its canonical name, ignoring any\n\t * currently adopted id. Null when the user backs out of the session. */\n\tfindOrCreatePersonal(): Promise<{ fileId: string; created: boolean } | null>;\n\t/** Make sure a usable session exists before a remote call (re-consent when\n\t * it lapsed). False = the user refused; the gesture aborts as 'cancelled'.\n\t * Absent = sessions are the target's own business. */\n\tensureSession?(): Promise<boolean>;\n\t/** Resolve the owner label of a file this account does not own, for the\n\t * shared registry (\"shared by X\"). Best-effort. */\n\tfileOwner?(fileId: string): Promise<{ email: string | null; name: string | null } | null>;\n\t/** File ids that must never enter the registry even though the store may\n\t * attach them (e.g. a sharing engine's published copy file). */\n\texcludedFileIds?(): Promise<(string | null | undefined)[]>;\n}\n\n/** How backup files are named on the destination. */\nexport interface BackupsNaming {\n\t/** The personal, unnamed file (\"App.zip\"). Its label reads as null. */\n\tcanonicalName: string;\n\t/** label -> file name. Default: \"Stem (label).ext\" derived from\n\t * canonicalName (\"App.zip\" + \"family\" -> \"App (family).zip\"). */\n\tnamedFileFor?(label: string): string;\n\t/** file name -> parsed label; null = the personal file; undefined = not one\n\t * of ours (dropped from listings). Default matches the default namedFileFor. */\n\tparseLabel?(name: string): string | null | undefined;\n}\n\n/** The kv keys the manager persists under - override to keep a pre-existing\n * install's records. */\nexport interface BackupsKeys {\n\t/** The known-backups registry. */\n\tregistry?: string;\n\t/** fileId -> encrypted? map. */\n\tencrypted?: string;\n\t/** fileId -> shared? map. */\n\tshared?: string;\n\t/** Set while the ACTIVE file is not the personal one (another account's). */\n\tjoined?: string;\n\t/** Cached owner label of that file. */\n\towner?: string;\n}\n\n// --- Shapes -------------------------------------------------------------------\n\n/** Every backup this device has connected to: its own personal file and each\n * OTHER account's file it was let into. Isolated snapshots, all of them. */\nexport interface KnownBackups {\n\tpersonalFileId: string | null;\n\tshared: { fileId: string; ownerEmail: string | null; ownerName: string | null }[];\n}\n\n/** One row of the \"my backups\" list: a file this account owns. */\nexport interface BackupRow {\n\tfileId: string;\n\tname: string;\n\t/** Parsed display label; null for the personal, unnamed file. */\n\tlabel: string | null;\n\t/** Last-write time, epoch ms (null when the destination did not say). */\n\tmodifiedAt: number | null;\n\t/** true/false once known (opened, created or probed); null until then. */\n\tencrypted: boolean | null;\n\t/** true/false once learned (while this file was the active one); null\n\t * until then. A share link existing is the shared state. */\n\tshared: boolean | null;\n}\n\n/** The owner label of a joined (another account's) file. */\nexport interface BackupOwner {\n\temail: string | null;\n\tname: string | null;\n}\n\n/** Stable failure codes; the host maps them to its own copy. */\nexport type BackupsErrorCode = 'cancelled' | 'gone' | 'failed';\n\nexport interface BackupsSnapshot {\n\tregistry: KnownBackups;\n\t/** The file currently attached, when the store is on the managed kind. */\n\tactiveFileId: string | null;\n\t/** The active file is not the personal one (someone else's). */\n\tjoined: boolean;\n\t/** Who owns the joined file, when known. */\n\towner: BackupOwner | null;\n\t/** The last gesture's failure, or null. Reset at each gesture start. */\n\tlastError: BackupsErrorCode | null;\n}\n\nexport interface BackupsManager extends FlowStore<BackupsSnapshot> {\n\t/** Boot: load registry + joined/owner from kv and stamp the active file.\n\t * Kv-only, no destination call. */\n\thydrate(): Promise<void>;\n\t/** Re-read the registry and restamp the active file. Kv-only, cheap. */\n\trefresh(): Promise<void>;\n\t/** After an attach the manager did not make (a connect widget, a join):\n\t * record the now-active file in the registry and restamp joined/owner. */\n\tmarkActive(fileId: string): Promise<void>;\n\t/** Live list of this account's own files, per the naming rules, decorated\n\t * with the learned memories. One destination listing call. */\n\tlist(): Promise<BackupRow[]>;\n\t/** Learn a listed file's encrypted bit without opening it for real: one\n\t * download + header read, remembered for good. Null when unreachable. */\n\tprobeEncryption(fileId: string): Promise<boolean | null>;\n\t/** Record the ACTIVE file's live share state, keyed by file id, so its row\n\t * stays truthful after a switch away. */\n\tnoteShared(fileId: string, shared: boolean): Promise<void>;\n\t/** Open a known backup: an isolated snapshot replaces the local data.\n\t * 'encrypted' = collect its passphrase and call again with it. A file the\n\t * destination reports GONE is pruned from the registry (lastError 'gone'). */\n\topenBackup(fileId: string, passphrase?: string | null): Promise<'ok' | 'encrypted' | 'failed'>;\n\t/** Open (or create blank) the personal file. */\n\topenPersonal(passphrase?: string | null): Promise<'ok' | 'encrypted' | 'failed'>;\n\t/** Create a brand-new empty named backup and open it (starts blank - never\n\t * seeded from the currently loaded file). */\n\tcreateNamed(label: string): Promise<'ok' | 'failed'>;\n\t/** Record a file in the SHARED registry under the sharer's label, without\n\t * opening it. For a joined portfolio's dedicated wallet: the file may live\n\t * on this very account, yet it presents as \"shared by X\", never as mine. */\n\tregisterShared(fileId: string, owner: BackupOwner): Promise<void>;\n\t/** Create a joined portfolio's dedicated wallet: a file under the given\n\t * name (outside the own-files naming on purpose), attached BLANK - never\n\t * seeded from the previously loaded silo - and recorded in the shared\n\t * registry under the sharer's label. The host stages the shared content\n\t * afterwards (restore the projection, then save). */\n\tcreateShared(fileName: string, owner: BackupOwner): Promise<'ok' | 'failed'>;\n\t/** Rename a file in place (id unchanged, so renaming the ACTIVE file never\n\t * detaches it). The host target refuses a name already carried. */\n\trenameBackup(fileId: string, label: string): Promise<'ok' | 'failed'>;\n\t/** Delete a file for good. Deleting the ACTIVE one detaches first (the app\n\t * goes device-only, local data stays), so nothing writes mid-delete. */\n\tdeleteBackup(fileId: string): Promise<boolean>;\n\t/** Drop a KNOWN shared (another account's) file from this device's\n\t * registry. Forgetting only - the owner's file is never touched. */\n\tforgetShared(fileId: string): Promise<void>;\n\t/** The file name a label produces (the create form's preview line). */\n\tfileNameFor(label: string): string;\n}\n\n// --- Defaults -----------------------------------------------------------------\n\nconst DEFAULT_KEYS: Required<BackupsKeys> = {\n\tregistry: 'selfstore:backups:registry:v1',\n\tencrypted: 'selfstore:backups:encrypted:v1',\n\tshared: 'selfstore:backups:shared:v1',\n\tjoined: 'selfstore:backups:joined:v1',\n\towner: 'selfstore:backups:owner:v1'\n};\n\nconst escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/** The default naming scheme: \"App.zip\" -> personal; \"App (label).zip\" ->\n * named. Derived from the canonical name's stem and extension. */\nfunction defaultNaming(naming: BackupsNaming): Required<Pick<BackupsNaming, 'namedFileFor' | 'parseLabel'>> {\n\tconst dot = naming.canonicalName.lastIndexOf('.');\n\tconst stem = dot > 0 ? naming.canonicalName.slice(0, dot) : naming.canonicalName;\n\tconst ext = dot > 0 ? naming.canonicalName.slice(dot) : '';\n\tconst named = new RegExp(`^${escapeRe(stem)} \\\\((.+)\\\\)${escapeRe(ext)}$`);\n\treturn {\n\t\tnamedFileFor: (label: string) => `${stem} (${label.trim()})${ext}`,\n\t\tparseLabel: (name: string) => {\n\t\t\tif (name === naming.canonicalName) return null;\n\t\t\tconst m = named.exec(name);\n\t\t\treturn m ? m[1] : undefined;\n\t\t}\n\t};\n}\n\n// --- Factory ------------------------------------------------------------------\n\nexport function createBackupsManager(deps: {\n\tstore: LocalStore;\n\tkv: KV;\n\thost: BackupsHost;\n\tnaming: BackupsNaming;\n\tkeys?: BackupsKeys;\n}): BackupsManager {\n\tconst { store, kv, host } = deps;\n\tconst KEYS = { ...DEFAULT_KEYS, ...deps.keys };\n\tconst namingDefaults = defaultNaming(deps.naming);\n\tconst naming = {\n\t\tnamedFileFor: deps.naming.namedFileFor ?? namingDefaults.namedFileFor,\n\t\tparseLabel: deps.naming.parseLabel ?? namingDefaults.parseLabel\n\t};\n\n\tconst m = makeMachine<BackupsSnapshot>({\n\t\tregistry: { personalFileId: null, shared: [] },\n\t\tactiveFileId: null,\n\t\tjoined: false,\n\t\towner: null,\n\t\tlastError: null\n\t});\n\n\tconst fail = (code: BackupsErrorCode): void => m.set({ lastError: code });\n\n\t// Which file ids the destination lists as OURS, and which one carries the\n\t// canonical (personal) name. Filled by list(), refreshed lazily where a\n\t// truthful own/foreign call is needed. Null until first learned.\n\tlet ownIds: Set<string> | null = null;\n\tlet ownCanonicalId: string | null = null;\n\n\tfunction learnOwn(files: BackupFileInfo[]): void {\n\t\tconst ids = new Set<string>();\n\t\tlet canonical: string | null = null;\n\t\tfor (const f of files) {\n\t\t\tconst label = naming.parseLabel(f.name);\n\t\t\tif (label === undefined) continue;\n\t\t\tids.add(f.id);\n\t\t\tif (label === null) canonical = f.id;\n\t\t}\n\t\townIds = ids;\n\t\townCanonicalId = canonical;\n\t}\n\n\tasync function ensureOwnKnown(): Promise<void> {\n\t\tif (ownIds !== null) return;\n\t\ttry {\n\t\t\tlearnOwn(await host.list());\n\t\t} catch {\n\t\t\t// Offline: leave unknown - markActive falls back on the registry alone.\n\t\t}\n\t}\n\n\t/** Load the registry, self-healing: excluded ids (a sharing engine's copy\n\t * file) must never sit in it - recorded as \"personal\" they would mislabel\n\t * the chooser and let a later open treat a shared file as one's own. */\n\tasync function loadRegistry(): Promise<KnownBackups> {\n\t\tconst reg = (await kv.get<KnownBackups>(KEYS.registry)) ?? { personalFileId: null, shared: [] };\n\t\tconst excluded = (await host.excludedFileIds?.()) ?? [];\n\t\tconst bad = new Set(excluded.filter((x): x is string => typeof x === 'string'));\n\t\tif (bad.size === 0) return reg;\n\t\tconst healed: KnownBackups = {\n\t\t\tpersonalFileId: reg.personalFileId && bad.has(reg.personalFileId) ? null : reg.personalFileId,\n\t\t\tshared: reg.shared.filter((s) => !bad.has(s.fileId))\n\t\t};\n\t\tif (healed.personalFileId !== reg.personalFileId || healed.shared.length !== reg.shared.length) {\n\t\t\tawait kv.set(KEYS.registry, healed);\n\t\t}\n\t\treturn healed;\n\t}\n\n\tasync function saveRegistry(next: KnownBackups): Promise<void> {\n\t\tm.set({ registry: next });\n\t\tawait kv.set(KEYS.registry, next);\n\t}\n\n\tasync function noteEncrypted(fileId: string, encrypted: boolean): Promise<void> {\n\t\tconst map = (await kv.get<Record<string, boolean>>(KEYS.encrypted)) ?? {};\n\t\tif (map[fileId] === encrypted) return;\n\t\tmap[fileId] = encrypted;\n\t\tawait kv.set(KEYS.encrypted, map);\n\t}\n\n\t/** Stamp the currently attached file (from the target's own persisted id)\n\t * into the snapshot and the registry. Kv-only. */\n\tasync function registerActive(): Promise<void> {\n\t\tif (store.state.targetKind !== host.kind) {\n\t\t\tm.set({ activeFileId: null });\n\t\t\treturn;\n\t\t}\n\t\tconst fileId = (await kv.get<string>(host.activeIdKey)) ?? null;\n\t\tm.set({ activeFileId: fileId });\n\t\tif (!fileId) return;\n\t\tconst excluded = (await host.excludedFileIds?.()) ?? [];\n\t\tif (excluded.includes(fileId)) return;\n\t\tconst reg = await loadRegistry();\n\t\tif (m.snapshot.joined) {\n\t\t\tconst owner = m.snapshot.owner;\n\t\t\tconst entry = { fileId, ownerEmail: owner?.email ?? null, ownerName: owner?.name ?? null };\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: reg.personalFileId === fileId ? null : reg.personalFileId,\n\t\t\t\tshared: [entry, ...reg.shared.filter((s) => s.fileId !== fileId)]\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\t// Not joined. The personal slot belongs to the CANONICAL file alone: an\n\t\t// own NAMED backup lists live and must not clobber it (the slot is the\n\t\t// escape back to the personal file).\n\t\tconst canonical =\n\t\t\tfileId === ownCanonicalId || reg.personalFileId === fileId || (ownIds === null && reg.personalFileId === null);\n\t\tif (canonical) {\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: fileId,\n\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t});\n\t\t} else if (reg.shared.some((s) => s.fileId === fileId)) {\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: reg.personalFileId,\n\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t});\n\t\t}\n\t}\n\n\t/** Session guard shared by the remote gestures: absent hook = no guard. */\n\tasync function ensureSession(): Promise<boolean> {\n\t\tif (!host.ensureSession) return true;\n\t\treturn host.ensureSession();\n\t}\n\n\tasync function markActive(fileId: string): Promise<void> {\n\t\tconst reg = await loadRegistry();\n\t\tconst knownShared = reg.shared.find((s) => s.fileId === fileId);\n\t\tlet mine = reg.personalFileId === fileId;\n\t\tif (!mine && !knownShared) {\n\t\t\t// Unknown file: ask the destination whose it is (one listing call,\n\t\t\t// cached). An own named backup must never read as joined - labeled\n\t\t\t// \"shared by me\", it would sit in the wrong section for good.\n\t\t\tawait ensureOwnKnown();\n\t\t\tmine = ownIds === null ? reg.personalFileId === null : ownIds.has(fileId);\n\t\t}\n\t\tif (mine || (!knownShared && ownIds?.has(fileId))) {\n\t\t\tawait kv.del(KEYS.joined);\n\t\t\tawait kv.del(KEYS.owner);\n\t\t\tm.set({ joined: false, owner: null });\n\t\t} else {\n\t\t\tconst owner: BackupOwner | null = knownShared\n\t\t\t\t? { email: knownShared.ownerEmail, name: knownShared.ownerName }\n\t\t\t\t: ((await host.fileOwner?.(fileId).catch(() => null)) ?? null);\n\t\t\tm.set({ joined: true, owner });\n\t\t\tawait kv.set(KEYS.joined, true);\n\t\t\tif (owner) await kv.set(KEYS.owner, owner);\n\t\t\telse await kv.del(KEYS.owner);\n\t\t}\n\t\tawait registerActive();\n\t}\n\n\t/** The one attach path every open shares: FIXED-id target, and the\n\t * remembered id committed only after the attach succeeds - committed up\n\t * front, the OUTGOING target (which resolves its file lazily from that\n\t * same key) would flush the old file's data into the one being opened:\n\t * two \"isolated\" backups silently merged. `wipe` keeps sync-meta from\n\t * crossing files (cross-file tombstones erase the other side). */\n\tasync function attachFixed(\n\t\tfileId: string,\n\t\tpassphrase: string | null,\n\t\tstrategy: 'replace-local' | 'replace-remote'\n\t): Promise<void> {\n\t\tconst target = host.open(fileId);\n\t\tawait store.attachTarget(target, {\n\t\t\tpassword: passphrase,\n\t\t\tstrategy,\n\t\t\tkeepSession: store.state.targetKind === host.kind,\n\t\t\twipe: true\n\t\t});\n\t\tawait kv.set(host.activeIdKey, fileId);\n\t}\n\n\treturn {\n\t\tget snapshot() {\n\t\t\treturn m.snapshot;\n\t\t},\n\t\tsubscribe: m.subscribe,\n\n\t\tfileNameFor(label: string): string {\n\t\t\treturn naming.namedFileFor(label.trim());\n\t\t},\n\n\t\tasync hydrate(): Promise<void> {\n\t\t\tconst joined = (await kv.get(KEYS.joined)) === true;\n\t\t\tconst owner = (await kv.get<BackupOwner>(KEYS.owner)) ?? null;\n\t\t\tm.set({ joined, owner, registry: await loadRegistry() });\n\t\t\tawait registerActive();\n\t\t},\n\n\t\tasync refresh(): Promise<void> {\n\t\t\tm.set({ registry: await loadRegistry() });\n\t\t\tawait registerActive();\n\t\t},\n\n\t\tmarkActive,\n\n\t\tasync list(): Promise<BackupRow[]> {\n\t\t\tconst files = await host.list();\n\t\t\tlearnOwn(files);\n\t\t\tconst enc = (await kv.get<Record<string, boolean>>(KEYS.encrypted)) ?? {};\n\t\t\tconst shr = (await kv.get<Record<string, boolean>>(KEYS.shared)) ?? {};\n\t\t\tconst rows: BackupRow[] = [];\n\t\t\tfor (const f of files) {\n\t\t\t\tconst label = naming.parseLabel(f.name);\n\t\t\t\tif (label === undefined) continue; // not one of ours (a copy, a bulletin, ...)\n\t\t\t\trows.push({\n\t\t\t\t\tfileId: f.id,\n\t\t\t\t\tname: f.name,\n\t\t\t\t\tlabel,\n\t\t\t\t\tmodifiedAt: f.modifiedTime ? Date.parse(f.modifiedTime) || null : null,\n\t\t\t\t\tencrypted: enc[f.id] ?? null,\n\t\t\t\t\tshared: shr[f.id] ?? null\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn rows;\n\t\t},\n\n\t\tasync probeEncryption(fileId: string): Promise<boolean | null> {\n\t\t\ttry {\n\t\t\t\tconst info = await store.inspectTarget(host.open(fileId));\n\t\t\t\tif (!info.hasBackup) return null;\n\t\t\t\tawait noteEncrypted(fileId, info.encrypted);\n\t\t\t\treturn info.encrypted;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\n\t\tasync noteShared(fileId: string, shared: boolean): Promise<void> {\n\t\t\tconst map = (await kv.get<Record<string, boolean>>(KEYS.shared)) ?? {};\n\t\t\tif (map[fileId] === shared) return;\n\t\t\tmap[fileId] = shared;\n\t\t\tawait kv.set(KEYS.shared, map);\n\t\t},\n\n\t\tasync openBackup(fileId, passphrase = null): Promise<'ok' | 'encrypted' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\ttry {\n\t\t\t\tif (!(await ensureSession())) {\n\t\t\t\t\tfail('cancelled');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\tconst info = await store.inspectTarget(host.open(fileId));\n\t\t\t\tif (!info.hasBackup) {\n\t\t\t\t\t// Dead entry (deleted, or unshared from this account): prune it so\n\t\t\t\t\t// its row stops re-failing forever. A transient failure throws\n\t\t\t\t\t// instead and never prunes - dropping a good record on a blip\n\t\t\t\t\t// would be far worse than one more failed tap.\n\t\t\t\t\tconst reg = await loadRegistry();\n\t\t\t\t\tawait saveRegistry({\n\t\t\t\t\t\tpersonalFileId: reg.personalFileId === fileId ? null : reg.personalFileId,\n\t\t\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t\t\t});\n\t\t\t\t\tfail('gone');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\tawait noteEncrypted(fileId, info.encrypted); // the listing cannot tell\n\t\t\t\tif (info.encrypted && !passphrase) return 'encrypted';\n\t\t\t\tawait attachFixed(fileId, passphrase, 'replace-local');\n\t\t\t\tawait markActive(fileId);\n\t\t\t\treturn store.state.locked ? 'encrypted' : 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync openPersonal(passphrase = null): Promise<'ok' | 'encrypted' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\ttry {\n\t\t\t\tconst own = await host.findOrCreatePersonal();\n\t\t\t\tif (!own) {\n\t\t\t\t\tfail('cancelled');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\townCanonicalId = own.fileId;\n\t\t\t\townIds?.add(own.fileId);\n\t\t\t\tconst reg = await loadRegistry();\n\t\t\t\tawait saveRegistry({\n\t\t\t\t\tpersonalFileId: own.fileId,\n\t\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== own.fileId)\n\t\t\t\t});\n\t\t\t\tif (!own.created) return await this.openBackup(own.fileId, passphrase);\n\t\t\t\tawait attachFixed(own.fileId, null, 'replace-remote');\n\t\t\t\tawait markActive(own.fileId);\n\t\t\t\treturn 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync createNamed(label): Promise<'ok' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\tconst clean = label.trim();\n\t\t\tif (!clean) {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tif (!(await ensureSession())) {\n\t\t\t\t\tfail('cancelled');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\tconst { fileId } = await host.create(naming.namedFileFor(clean));\n\t\t\t\townIds?.add(fileId);\n\t\t\t\tawait attachFixed(fileId, null, 'replace-remote');\n\t\t\t\tawait noteEncrypted(fileId, false); // a fresh backup starts unprotected\n\t\t\t\tawait markActive(fileId);\n\t\t\t\treturn 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync registerShared(fileId, owner): Promise<void> {\n\t\t\tconst reg = await loadRegistry();\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: reg.personalFileId === fileId ? null : reg.personalFileId,\n\t\t\t\tshared: [\n\t\t\t\t\t{ fileId, ownerEmail: owner.email, ownerName: owner.name },\n\t\t\t\t\t...reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t\t]\n\t\t\t});\n\t\t},\n\n\t\tasync createShared(fileName, owner): Promise<'ok' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\ttry {\n\t\t\t\tif (!(await ensureSession())) {\n\t\t\t\t\tfail('cancelled');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\tconst { fileId } = await host.create(fileName);\n\t\t\t\t// Registered as shared BEFORE the attach: markActive must find it in\n\t\t\t\t// the shared registry, or it would resolve this account as the owner\n\t\t\t\t// and file the joined wallet under \"mine\".\n\t\t\t\tawait this.registerShared(fileId, owner);\n\t\t\t\tawait attachFixed(fileId, null, 'replace-remote');\n\t\t\t\tawait noteEncrypted(fileId, false); // a member wallet is never protected\n\t\t\t\tawait markActive(fileId);\n\t\t\t\treturn 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync renameBackup(fileId, label): Promise<'ok' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\tconst clean = label.trim();\n\t\t\tif (!clean || !host.rename) {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait host.rename(fileId, naming.namedFileFor(clean));\n\t\t\t\treturn 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync deleteBackup(fileId): Promise<boolean> {\n\t\t\tm.set({ lastError: null });\n\t\t\ttry {\n\t\t\t\tif (fileId === m.snapshot.activeFileId) {\n\t\t\t\t\t// Detach first: the app goes device-only (local data stays) so\n\t\t\t\t\t// nothing writes to the file as it is removed. keepSession: a\n\t\t\t\t\t// default detach runs the target's disconnect, which forgets the\n\t\t\t\t\t// destination credentials - the remove below still needs them,\n\t\t\t\t\t// and the user deleted a FILE, not their account connection.\n\t\t\t\t\tm.set({ activeFileId: null });\n\t\t\t\t\tawait store.detachTarget({ keepSession: true });\n\t\t\t\t\t// The remembered file id would normally be cleared by that\n\t\t\t\t\t// disconnect; do it here so nothing dangles on a deleted file.\n\t\t\t\t\tawait kv.del(host.activeIdKey);\n\t\t\t\t}\n\t\t\t\tawait host.remove(fileId);\n\t\t\t\tconst reg = await loadRegistry();\n\t\t\t\tawait saveRegistry({\n\t\t\t\t\tpersonalFileId: reg.personalFileId === fileId ? null : reg.personalFileId,\n\t\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync forgetShared(fileId): Promise<void> {\n\t\t\tconst reg = await loadRegistry();\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: reg.personalFileId,\n\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t});\n\t\t}\n\t};\n}\n"]}
1
+ {"version":3,"sources":["../src/backups/manager.ts"],"names":[],"mappings":";;;;AAiMA,IAAM,YAAA,GAAsC;AAAA,EAC3C,QAAA,EAAU,+BAAA;AAAA,EACV,SAAA,EAAW,gCAAA;AAAA,EACX,MAAA,EAAQ,6BAAA;AAAA,EACR,MAAA,EAAQ,6BAAA;AAAA,EACR,KAAA,EAAO;AACR,CAAA;AAEA,IAAM,WAAW,CAAC,CAAA,KAAsB,CAAA,CAAE,OAAA,CAAQ,uBAAuB,MAAM,CAAA;AAI/E,SAAS,cACR,MAAA,EAC+D;AAC/D,EAAA,MAAM,GAAA,GAAM,MAAA,CAAO,aAA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E,WAAW,MAAM;AAAA,OACpD,CAAA;AAAA,IACF;AAAA,GACD;AACD","file":"backups.js","sourcesContent":["// Multi-backup manager: several backup files on one destination account, one\n// attached at a time, each an isolated snapshot - opening one replaces the\n// local data, never merges, never touches the other files.\n//\n// It owns the bookkeeping a backup panel needs: the self-healing registry of\n// files this device has connected to; the per-file memories a listing cannot\n// provide (encrypted? shared? - those bits live inside the files, learned as\n// they are opened or probed and remembered in the kv); and the open / create\n// / rename / delete gestures with their isolation invariants (fixed-id\n// targets, active-id committed only after a successful attach, wipe on every\n// switch so no sync-meta crosses files).\n//\n// Injectable and headless: a LocalStore + a kv + a BackupsHost port for the\n// destination I/O. Errors surface as stable codes, never prose; hosts wrap\n// subscribe in their own reactivity.\n\nimport type { KV } from '../persistence/cache';\nimport type { LocalStore } from '../persistence/store';\nimport type { BackupTarget } from '../persistence/target';\nimport { makeMachine, type FlowStore } from '../flows/machine';\n\n// --- Ports --------------------------------------------------------------------\n\n/** What the destination reports about a listed file (one cheap metadata call). */\nexport interface BackupFileInfo {\n\tid: string;\n\tname: string;\n\t/** RFC 3339 last-write timestamp, when the destination reports one. */\n\tmodifiedTime: string | null;\n}\n\n/** The destination I/O the manager drives - the host wires its own adapter\n * (e.g. over the Drive target ops). Every method may throw; the manager turns\n * failures into stable error codes. */\nexport interface BackupsHost {\n\t/** The target kind the managed files live on (e.g. 'drive'): the manager\n\t * only stamps an active file while the store is attached to this kind. */\n\tkind: string;\n\t/** The kv key the attached file id is persisted under (the same one the\n\t * target's connect path reads first). */\n\tactiveIdKey: string;\n\t/** List candidate backup files on the account. The manager applies the\n\t * naming rules on what comes back; internal files simply do not match. */\n\tlist(): Promise<BackupFileInfo[]>;\n\t/** A target over a FIXED file id - never re-resolved by name. The fixed id\n\t * is what keeps two backups from silently merging mid-switch. */\n\topen(fileId: string): BackupTarget;\n\t/** Create an empty file under this name and return its id. Refuse a name\n\t * the account already carries (a duplicate poisons find-by-name). */\n\tcreate(fileName: string): Promise<{ fileId: string }>;\n\t/** Delete a file for good. */\n\tremove(fileId: string): Promise<void>;\n\t/** Rename a file in place (metadata only: the id must not change). */\n\trename?(fileId: string, fileName: string): Promise<void>;\n\t/** Find (or create) the PERSONAL file by its canonical name, ignoring any\n\t * currently adopted id. Null when the user backs out of the session. */\n\tfindOrCreatePersonal(): Promise<{ fileId: string; created: boolean } | null>;\n\t/** Make sure a usable session exists before a remote call (re-consent when\n\t * it lapsed). False = the user refused; the gesture aborts as 'cancelled'.\n\t * Absent = sessions are the target's own business. */\n\tensureSession?(): Promise<boolean>;\n\t/** Resolve the owner label of a file this account does not own, for the\n\t * shared registry (\"shared by X\"). Best-effort. */\n\tfileOwner?(fileId: string): Promise<{ email: string | null; name: string | null } | null>;\n\t/** File ids that must never enter the registry even though the store may\n\t * attach them (e.g. a sharing engine's published copy file). */\n\texcludedFileIds?(): Promise<(string | null | undefined)[]>;\n}\n\n/** How backup files are named on the destination. */\nexport interface BackupsNaming {\n\t/** The personal, unnamed file (\"App.zip\"). Its label reads as null. */\n\tcanonicalName: string;\n\t/** label -> file name. Default: \"Stem (label).ext\" derived from\n\t * canonicalName (\"App.zip\" + \"family\" -> \"App (family).zip\"). */\n\tnamedFileFor?(label: string): string;\n\t/** file name -> parsed label; null = the personal file; undefined = not one\n\t * of ours (dropped from listings). Default matches the default namedFileFor. */\n\tparseLabel?(name: string): string | null | undefined;\n}\n\n/** The kv keys the manager persists under - override to keep a pre-existing\n * install's records. */\nexport interface BackupsKeys {\n\t/** The known-backups registry. */\n\tregistry?: string;\n\t/** fileId -> encrypted? map. */\n\tencrypted?: string;\n\t/** fileId -> shared? map. */\n\tshared?: string;\n\t/** Set while the ACTIVE file is not the personal one (another account's). */\n\tjoined?: string;\n\t/** Cached owner label of that file. */\n\towner?: string;\n}\n\n// --- Shapes -------------------------------------------------------------------\n\n/** Every backup this device has connected to: its own personal file and each\n * OTHER account's file it was let into. Isolated snapshots, all of them. */\nexport interface KnownBackups {\n\tpersonalFileId: string | null;\n\tshared: { fileId: string; ownerEmail: string | null; ownerName: string | null }[];\n}\n\n/** One row of the \"my backups\" list: a file this account owns. */\nexport interface BackupRow {\n\tfileId: string;\n\tname: string;\n\t/** Parsed display label; null for the personal, unnamed file. */\n\tlabel: string | null;\n\t/** Last-write time, epoch ms (null when the destination did not say). */\n\tmodifiedAt: number | null;\n\t/** true/false once known (opened, created or probed); null until then. */\n\tencrypted: boolean | null;\n\t/** true/false once learned (while this file was the active one); null\n\t * until then. A share link existing is the shared state. */\n\tshared: boolean | null;\n}\n\n/** The owner label of a joined (another account's) file. */\nexport interface BackupOwner {\n\temail: string | null;\n\tname: string | null;\n}\n\n/** Stable failure codes; the host maps them to its own copy. */\nexport type BackupsErrorCode = 'cancelled' | 'gone' | 'failed';\n\nexport interface BackupsSnapshot {\n\tregistry: KnownBackups;\n\t/** The file currently attached, when the store is on the managed kind. */\n\tactiveFileId: string | null;\n\t/** The active file is not the personal one (someone else's). */\n\tjoined: boolean;\n\t/** Who owns the joined file, when known. */\n\towner: BackupOwner | null;\n\t/** The last gesture's failure, or null. Reset at each gesture start. */\n\tlastError: BackupsErrorCode | null;\n}\n\nexport interface BackupsManager extends FlowStore<BackupsSnapshot> {\n\t/** Boot: load registry + joined/owner from kv and stamp the active file.\n\t * Kv-only, no destination call. */\n\thydrate(): Promise<void>;\n\t/** Re-read the registry and restamp the active file. Kv-only, cheap. */\n\trefresh(): Promise<void>;\n\t/** After an attach the manager did not make (a connect widget, a join):\n\t * record the now-active file in the registry and restamp joined/owner. */\n\tmarkActive(fileId: string): Promise<void>;\n\t/** Live list of this account's own files, per the naming rules, decorated\n\t * with the learned memories. One destination listing call. */\n\tlist(): Promise<BackupRow[]>;\n\t/** Learn a listed file's encrypted bit without opening it for real: one\n\t * download + header read, remembered for good. Null when unreachable. */\n\tprobeEncryption(fileId: string): Promise<boolean | null>;\n\t/** Record the ACTIVE file's live share state, keyed by file id, so its row\n\t * stays truthful after a switch away. */\n\tnoteShared(fileId: string, shared: boolean): Promise<void>;\n\t/** Open a known backup: an isolated snapshot replaces the local data.\n\t * 'encrypted' = collect its passphrase and call again with it. A file the\n\t * destination reports GONE is pruned from the registry (lastError 'gone'). */\n\topenBackup(fileId: string, passphrase?: string | null): Promise<'ok' | 'encrypted' | 'failed'>;\n\t/** Open (or create blank) the personal file. */\n\topenPersonal(passphrase?: string | null): Promise<'ok' | 'encrypted' | 'failed'>;\n\t/** Create a brand-new empty named backup and open it (starts blank - never\n\t * seeded from the currently loaded file). */\n\tcreateNamed(label: string): Promise<'ok' | 'failed'>;\n\t/** Record a file in the SHARED registry under the sharer's label, without\n\t * opening it. For a joined portfolio's dedicated wallet: the file may live\n\t * on this very account, yet it presents as \"shared by X\", never as mine. */\n\tregisterShared(fileId: string, owner: BackupOwner): Promise<void>;\n\t/** Create a joined portfolio's dedicated wallet: a file under the given\n\t * name (outside the own-files naming on purpose), attached BLANK - never\n\t * seeded from the previously loaded silo - and recorded in the shared\n\t * registry under the sharer's label. The host stages the shared content\n\t * afterwards (restore the projection, then save). */\n\tcreateShared(fileName: string, owner: BackupOwner): Promise<'ok' | 'failed'>;\n\t/** Rename a file in place (id unchanged, so renaming the ACTIVE file never\n\t * detaches it). The host target refuses a name already carried. */\n\trenameBackup(fileId: string, label: string): Promise<'ok' | 'failed'>;\n\t/** Delete a file for good. Deleting the ACTIVE one detaches first (the app\n\t * goes device-only, local data stays), so nothing writes mid-delete. */\n\tdeleteBackup(fileId: string): Promise<boolean>;\n\t/** Drop a KNOWN shared (another account's) file from this device's\n\t * registry. Forgetting only - the owner's file is never touched. */\n\tforgetShared(fileId: string): Promise<void>;\n\t/** The file name a label produces (the create form's preview line). */\n\tfileNameFor(label: string): string;\n}\n\n// --- Defaults -----------------------------------------------------------------\n\nconst DEFAULT_KEYS: Required<BackupsKeys> = {\n\tregistry: 'selfstore:backups:registry:v1',\n\tencrypted: 'selfstore:backups:encrypted:v1',\n\tshared: 'selfstore:backups:shared:v1',\n\tjoined: 'selfstore:backups:joined:v1',\n\towner: 'selfstore:backups:owner:v1'\n};\n\nconst escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/** The default naming scheme: \"App.zip\" -> personal; \"App (label).zip\" ->\n * named. Derived from the canonical name's stem and extension. */\nfunction defaultNaming(\n\tnaming: BackupsNaming\n): Required<Pick<BackupsNaming, 'namedFileFor' | 'parseLabel'>> {\n\tconst dot = naming.canonicalName.lastIndexOf('.');\n\tconst stem = dot > 0 ? naming.canonicalName.slice(0, dot) : naming.canonicalName;\n\tconst ext = dot > 0 ? naming.canonicalName.slice(dot) : '';\n\tconst named = new RegExp(`^${escapeRe(stem)} \\\\((.+)\\\\)${escapeRe(ext)}$`);\n\treturn {\n\t\tnamedFileFor: (label: string) => `${stem} (${label.trim()})${ext}`,\n\t\tparseLabel: (name: string) => {\n\t\t\tif (name === naming.canonicalName) return null;\n\t\t\tconst m = named.exec(name);\n\t\t\treturn m ? m[1] : undefined;\n\t\t}\n\t};\n}\n\n// --- Factory ------------------------------------------------------------------\n\nexport function createBackupsManager(deps: {\n\tstore: LocalStore;\n\tkv: KV;\n\thost: BackupsHost;\n\tnaming: BackupsNaming;\n\tkeys?: BackupsKeys;\n}): BackupsManager {\n\tconst { store, kv, host } = deps;\n\tconst KEYS = { ...DEFAULT_KEYS, ...deps.keys };\n\tconst namingDefaults = defaultNaming(deps.naming);\n\tconst naming = {\n\t\tnamedFileFor: deps.naming.namedFileFor ?? namingDefaults.namedFileFor,\n\t\tparseLabel: deps.naming.parseLabel ?? namingDefaults.parseLabel\n\t};\n\n\tconst m = makeMachine<BackupsSnapshot>({\n\t\tregistry: { personalFileId: null, shared: [] },\n\t\tactiveFileId: null,\n\t\tjoined: false,\n\t\towner: null,\n\t\tlastError: null\n\t});\n\n\tconst fail = (code: BackupsErrorCode): void => m.set({ lastError: code });\n\n\t// Which file ids the destination lists as OURS, and which one carries the\n\t// canonical (personal) name. Filled by list(), refreshed lazily where a\n\t// truthful own/foreign call is needed. Null until first learned.\n\tlet ownIds: Set<string> | null = null;\n\tlet ownCanonicalId: string | null = null;\n\n\tfunction learnOwn(files: BackupFileInfo[]): void {\n\t\tconst ids = new Set<string>();\n\t\tlet canonical: string | null = null;\n\t\tfor (const f of files) {\n\t\t\tconst label = naming.parseLabel(f.name);\n\t\t\tif (label === undefined) continue;\n\t\t\tids.add(f.id);\n\t\t\tif (label === null) canonical = f.id;\n\t\t}\n\t\townIds = ids;\n\t\townCanonicalId = canonical;\n\t}\n\n\tasync function ensureOwnKnown(): Promise<void> {\n\t\tif (ownIds !== null) return;\n\t\ttry {\n\t\t\tlearnOwn(await host.list());\n\t\t} catch {\n\t\t\t// Offline: leave unknown - markActive falls back on the registry alone.\n\t\t}\n\t}\n\n\t/** Load the registry, self-healing: excluded ids (a sharing engine's copy\n\t * file) must never sit in it - recorded as \"personal\" they would mislabel\n\t * the chooser and let a later open treat a shared file as one's own. */\n\tasync function loadRegistry(): Promise<KnownBackups> {\n\t\tconst reg = (await kv.get<KnownBackups>(KEYS.registry)) ?? { personalFileId: null, shared: [] };\n\t\tconst excluded = (await host.excludedFileIds?.()) ?? [];\n\t\tconst bad = new Set(excluded.filter((x): x is string => typeof x === 'string'));\n\t\tif (bad.size === 0) return reg;\n\t\tconst healed: KnownBackups = {\n\t\t\tpersonalFileId: reg.personalFileId && bad.has(reg.personalFileId) ? null : reg.personalFileId,\n\t\t\tshared: reg.shared.filter((s) => !bad.has(s.fileId))\n\t\t};\n\t\tif (\n\t\t\thealed.personalFileId !== reg.personalFileId ||\n\t\t\thealed.shared.length !== reg.shared.length\n\t\t) {\n\t\t\tawait kv.set(KEYS.registry, healed);\n\t\t}\n\t\treturn healed;\n\t}\n\n\tasync function saveRegistry(next: KnownBackups): Promise<void> {\n\t\tm.set({ registry: next });\n\t\tawait kv.set(KEYS.registry, next);\n\t}\n\n\tasync function noteEncrypted(fileId: string, encrypted: boolean): Promise<void> {\n\t\tconst map = (await kv.get<Record<string, boolean>>(KEYS.encrypted)) ?? {};\n\t\tif (map[fileId] === encrypted) return;\n\t\tmap[fileId] = encrypted;\n\t\tawait kv.set(KEYS.encrypted, map);\n\t}\n\n\t/** Stamp the currently attached file (from the target's own persisted id)\n\t * into the snapshot and the registry. Kv-only. */\n\tasync function registerActive(): Promise<void> {\n\t\tif (store.state.targetKind !== host.kind) {\n\t\t\tm.set({ activeFileId: null });\n\t\t\treturn;\n\t\t}\n\t\tconst fileId = (await kv.get<string>(host.activeIdKey)) ?? null;\n\t\tm.set({ activeFileId: fileId });\n\t\tif (!fileId) return;\n\t\tconst excluded = (await host.excludedFileIds?.()) ?? [];\n\t\tif (excluded.includes(fileId)) return;\n\t\tconst reg = await loadRegistry();\n\t\tif (m.snapshot.joined) {\n\t\t\tconst owner = m.snapshot.owner;\n\t\t\tconst entry = { fileId, ownerEmail: owner?.email ?? null, ownerName: owner?.name ?? null };\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: reg.personalFileId === fileId ? null : reg.personalFileId,\n\t\t\t\tshared: [entry, ...reg.shared.filter((s) => s.fileId !== fileId)]\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\t// Not joined. The personal slot belongs to the CANONICAL file alone: an\n\t\t// own NAMED backup lists live and must not clobber it (the slot is the\n\t\t// escape back to the personal file).\n\t\tconst canonical =\n\t\t\tfileId === ownCanonicalId ||\n\t\t\treg.personalFileId === fileId ||\n\t\t\t(ownIds === null && reg.personalFileId === null);\n\t\tif (canonical) {\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: fileId,\n\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t});\n\t\t} else if (reg.shared.some((s) => s.fileId === fileId)) {\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: reg.personalFileId,\n\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t});\n\t\t}\n\t}\n\n\t/** Session guard shared by the remote gestures: absent hook = no guard. */\n\tasync function ensureSession(): Promise<boolean> {\n\t\tif (!host.ensureSession) return true;\n\t\treturn host.ensureSession();\n\t}\n\n\tasync function markActive(fileId: string): Promise<void> {\n\t\tconst reg = await loadRegistry();\n\t\tconst knownShared = reg.shared.find((s) => s.fileId === fileId);\n\t\tlet mine = reg.personalFileId === fileId;\n\t\tif (!mine && !knownShared) {\n\t\t\t// Unknown file: ask the destination whose it is (one listing call,\n\t\t\t// cached). An own named backup must never read as joined - labeled\n\t\t\t// \"shared by me\", it would sit in the wrong section for good.\n\t\t\tawait ensureOwnKnown();\n\t\t\tmine = ownIds === null ? reg.personalFileId === null : ownIds.has(fileId);\n\t\t}\n\t\tif (mine || (!knownShared && ownIds?.has(fileId))) {\n\t\t\tawait kv.del(KEYS.joined);\n\t\t\tawait kv.del(KEYS.owner);\n\t\t\tm.set({ joined: false, owner: null });\n\t\t} else {\n\t\t\tconst owner: BackupOwner | null = knownShared\n\t\t\t\t? { email: knownShared.ownerEmail, name: knownShared.ownerName }\n\t\t\t\t: ((await host.fileOwner?.(fileId).catch(() => null)) ?? null);\n\t\t\tm.set({ joined: true, owner });\n\t\t\tawait kv.set(KEYS.joined, true);\n\t\t\tif (owner) await kv.set(KEYS.owner, owner);\n\t\t\telse await kv.del(KEYS.owner);\n\t\t}\n\t\tawait registerActive();\n\t}\n\n\t/** The one attach path every open shares: FIXED-id target, and the\n\t * remembered id committed only after the attach succeeds - committed up\n\t * front, the OUTGOING target (which resolves its file lazily from that\n\t * same key) would flush the old file's data into the one being opened:\n\t * two \"isolated\" backups silently merged. `wipe` keeps sync-meta from\n\t * crossing files (cross-file tombstones erase the other side). */\n\tasync function attachFixed(\n\t\tfileId: string,\n\t\tpassphrase: string | null,\n\t\tstrategy: 'replace-local' | 'replace-remote'\n\t): Promise<void> {\n\t\tconst target = host.open(fileId);\n\t\tawait store.attachTarget(target, {\n\t\t\tpassword: passphrase,\n\t\t\tstrategy,\n\t\t\tkeepSession: store.state.targetKind === host.kind,\n\t\t\twipe: true\n\t\t});\n\t\tawait kv.set(host.activeIdKey, fileId);\n\t}\n\n\treturn {\n\t\tget snapshot() {\n\t\t\treturn m.snapshot;\n\t\t},\n\t\tsubscribe: m.subscribe,\n\n\t\tfileNameFor(label: string): string {\n\t\t\treturn naming.namedFileFor(label.trim());\n\t\t},\n\n\t\tasync hydrate(): Promise<void> {\n\t\t\tconst joined = (await kv.get(KEYS.joined)) === true;\n\t\t\tconst owner = (await kv.get<BackupOwner>(KEYS.owner)) ?? null;\n\t\t\tm.set({ joined, owner, registry: await loadRegistry() });\n\t\t\tawait registerActive();\n\t\t},\n\n\t\tasync refresh(): Promise<void> {\n\t\t\tm.set({ registry: await loadRegistry() });\n\t\t\tawait registerActive();\n\t\t},\n\n\t\tmarkActive,\n\n\t\tasync list(): Promise<BackupRow[]> {\n\t\t\tconst files = await host.list();\n\t\t\tlearnOwn(files);\n\t\t\tconst enc = (await kv.get<Record<string, boolean>>(KEYS.encrypted)) ?? {};\n\t\t\tconst shr = (await kv.get<Record<string, boolean>>(KEYS.shared)) ?? {};\n\t\t\tconst rows: BackupRow[] = [];\n\t\t\tfor (const f of files) {\n\t\t\t\tconst label = naming.parseLabel(f.name);\n\t\t\t\tif (label === undefined) continue; // not one of ours (a copy, a bulletin, ...)\n\t\t\t\trows.push({\n\t\t\t\t\tfileId: f.id,\n\t\t\t\t\tname: f.name,\n\t\t\t\t\tlabel,\n\t\t\t\t\tmodifiedAt: f.modifiedTime ? Date.parse(f.modifiedTime) || null : null,\n\t\t\t\t\tencrypted: enc[f.id] ?? null,\n\t\t\t\t\tshared: shr[f.id] ?? null\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn rows;\n\t\t},\n\n\t\tasync probeEncryption(fileId: string): Promise<boolean | null> {\n\t\t\ttry {\n\t\t\t\tconst info = await store.inspectTarget(host.open(fileId));\n\t\t\t\tif (!info.hasBackup) return null;\n\t\t\t\tawait noteEncrypted(fileId, info.encrypted);\n\t\t\t\treturn info.encrypted;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\n\t\tasync noteShared(fileId: string, shared: boolean): Promise<void> {\n\t\t\tconst map = (await kv.get<Record<string, boolean>>(KEYS.shared)) ?? {};\n\t\t\tif (map[fileId] === shared) return;\n\t\t\tmap[fileId] = shared;\n\t\t\tawait kv.set(KEYS.shared, map);\n\t\t},\n\n\t\tasync openBackup(fileId, passphrase = null): Promise<'ok' | 'encrypted' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\ttry {\n\t\t\t\tif (!(await ensureSession())) {\n\t\t\t\t\tfail('cancelled');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\tconst info = await store.inspectTarget(host.open(fileId));\n\t\t\t\tif (!info.hasBackup) {\n\t\t\t\t\t// Dead entry (deleted, or unshared from this account): prune it so\n\t\t\t\t\t// its row stops re-failing forever. A transient failure throws\n\t\t\t\t\t// instead and never prunes - dropping a good record on a blip\n\t\t\t\t\t// would be far worse than one more failed tap.\n\t\t\t\t\tconst reg = await loadRegistry();\n\t\t\t\t\tawait saveRegistry({\n\t\t\t\t\t\tpersonalFileId: reg.personalFileId === fileId ? null : reg.personalFileId,\n\t\t\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t\t\t});\n\t\t\t\t\tfail('gone');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\tawait noteEncrypted(fileId, info.encrypted); // the listing cannot tell\n\t\t\t\tif (info.encrypted && !passphrase) return 'encrypted';\n\t\t\t\tawait attachFixed(fileId, passphrase, 'replace-local');\n\t\t\t\tawait markActive(fileId);\n\t\t\t\treturn store.state.locked ? 'encrypted' : 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync openPersonal(passphrase = null): Promise<'ok' | 'encrypted' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\ttry {\n\t\t\t\tconst own = await host.findOrCreatePersonal();\n\t\t\t\tif (!own) {\n\t\t\t\t\tfail('cancelled');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\townCanonicalId = own.fileId;\n\t\t\t\townIds?.add(own.fileId);\n\t\t\t\tconst reg = await loadRegistry();\n\t\t\t\tawait saveRegistry({\n\t\t\t\t\tpersonalFileId: own.fileId,\n\t\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== own.fileId)\n\t\t\t\t});\n\t\t\t\tif (!own.created) return await this.openBackup(own.fileId, passphrase);\n\t\t\t\tawait attachFixed(own.fileId, null, 'replace-remote');\n\t\t\t\tawait markActive(own.fileId);\n\t\t\t\treturn 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync createNamed(label): Promise<'ok' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\tconst clean = label.trim();\n\t\t\tif (!clean) {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tif (!(await ensureSession())) {\n\t\t\t\t\tfail('cancelled');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\tconst { fileId } = await host.create(naming.namedFileFor(clean));\n\t\t\t\townIds?.add(fileId);\n\t\t\t\tawait attachFixed(fileId, null, 'replace-remote');\n\t\t\t\tawait noteEncrypted(fileId, false); // a fresh backup starts unprotected\n\t\t\t\tawait markActive(fileId);\n\t\t\t\treturn 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync registerShared(fileId, owner): Promise<void> {\n\t\t\tconst reg = await loadRegistry();\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: reg.personalFileId === fileId ? null : reg.personalFileId,\n\t\t\t\tshared: [\n\t\t\t\t\t{ fileId, ownerEmail: owner.email, ownerName: owner.name },\n\t\t\t\t\t...reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t\t]\n\t\t\t});\n\t\t},\n\n\t\tasync createShared(fileName, owner): Promise<'ok' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\ttry {\n\t\t\t\tif (!(await ensureSession())) {\n\t\t\t\t\tfail('cancelled');\n\t\t\t\t\treturn 'failed';\n\t\t\t\t}\n\t\t\t\tconst { fileId } = await host.create(fileName);\n\t\t\t\t// Registered as shared BEFORE the attach: markActive must find it in\n\t\t\t\t// the shared registry, or it would resolve this account as the owner\n\t\t\t\t// and file the joined wallet under \"mine\".\n\t\t\t\tawait this.registerShared(fileId, owner);\n\t\t\t\tawait attachFixed(fileId, null, 'replace-remote');\n\t\t\t\tawait noteEncrypted(fileId, false); // a member wallet is never protected\n\t\t\t\tawait markActive(fileId);\n\t\t\t\treturn 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync renameBackup(fileId, label): Promise<'ok' | 'failed'> {\n\t\t\tm.set({ lastError: null });\n\t\t\tconst clean = label.trim();\n\t\t\tif (!clean || !host.rename) {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait host.rename(fileId, naming.namedFileFor(clean));\n\t\t\t\treturn 'ok';\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn 'failed';\n\t\t\t}\n\t\t},\n\n\t\tasync deleteBackup(fileId): Promise<boolean> {\n\t\t\tm.set({ lastError: null });\n\t\t\ttry {\n\t\t\t\tif (fileId === m.snapshot.activeFileId) {\n\t\t\t\t\t// Detach first: the app goes device-only (local data stays) so\n\t\t\t\t\t// nothing writes to the file as it is removed. keepSession: a\n\t\t\t\t\t// default detach runs the target's disconnect, which forgets the\n\t\t\t\t\t// destination credentials - the remove below still needs them,\n\t\t\t\t\t// and the user deleted a FILE, not their account connection.\n\t\t\t\t\tm.set({ activeFileId: null });\n\t\t\t\t\tawait store.detachTarget({ keepSession: true });\n\t\t\t\t\t// The remembered file id would normally be cleared by that\n\t\t\t\t\t// disconnect; do it here so nothing dangles on a deleted file.\n\t\t\t\t\tawait kv.del(host.activeIdKey);\n\t\t\t\t}\n\t\t\t\tawait host.remove(fileId);\n\t\t\t\tconst reg = await loadRegistry();\n\t\t\t\tawait saveRegistry({\n\t\t\t\t\tpersonalFileId: reg.personalFileId === fileId ? null : reg.personalFileId,\n\t\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\tfail('failed');\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync forgetShared(fileId): Promise<void> {\n\t\t\tconst reg = await loadRegistry();\n\t\t\tawait saveRegistry({\n\t\t\t\tpersonalFileId: reg.personalFileId,\n\t\t\t\tshared: reg.shared.filter((s) => s.fileId !== fileId)\n\t\t\t});\n\t\t}\n\t};\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { unseal } from './chunk-QBCU7OOP.js';
2
- import { freshKdfParams, deriveKey } from './chunk-FDPAKHQS.js';
2
+ import { freshKdfParams, deriveKey } from './chunk-6746AL4I.js';
3
3
  import './chunk-VBFMMR7Q.js';
4
4
 
5
5
  // src/persistence/cache-lock.ts
@@ -19,5 +19,5 @@ async function opens(key, probe) {
19
19
  }
20
20
 
21
21
  export { freshCacheKdf, keyFromPassword, opens };
22
- //# sourceMappingURL=cache-lock-LZILZNLP.js.map
23
- //# sourceMappingURL=cache-lock-LZILZNLP.js.map
22
+ //# sourceMappingURL=cache-lock-NXIR6JRB.js.map
23
+ //# sourceMappingURL=cache-lock-NXIR6JRB.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/persistence/cache-lock.ts"],"names":[],"mappings":";;;;;AAeO,SAAS,aAAA,GAA0B;AACzC,EAAA,OAAO,cAAA,EAAe;AACvB;AAGO,SAAS,eAAA,CAAgB,UAAkB,GAAA,EAAmC;AACpF,EAAA,OAAO,SAAA,CAAU,UAAU,GAAG,CAAA;AAC/B;AAIA,eAAsB,KAAA,CAAM,KAAgB,KAAA,EAAsC;AACjF,EAAA,IAAI;AACH,IAAA,MAAM,MAAA,CAAO,KAAK,KAAK,CAAA;AACvB,IAAA,OAAO,IAAA;AAAA,EACR,CAAA,CAAA,MAAQ;AACP,IAAA,OAAO,KAAA;AAAA,EACR;AACD","file":"cache-lock-LZILZNLP.js","sourcesContent":["// Seal-key material for a lock-mode cache. The key is derived from a password\n// (the backup's Argon2id KDF) or supplied by the app (e.g. a passkey PRF key),\n// and is held in memory only - never written next to the data. That is what a\n// device-key seal (cache-crypto) cannot give: a copy of the whole browser\n// profile carries the device key, but not a secret kept in RAM. Only the KDF\n// salt is persisted, and a salt is not secret.\n\nimport { unseal, type EncEnvelope } from './cache-crypto';\nimport { deriveKey, freshKdfParams } from '../selfstore/crypto';\nimport type { KdfParams } from '../selfstore/types';\n\n/** Argon2id parameters for a password-locked cache; persisted in the clear. */\nexport type CacheKdf = KdfParams;\n\n/** Fresh Argon2id parameters (random salt, current default cost). */\nexport function freshCacheKdf(): CacheKdf {\n\treturn freshKdfParams();\n}\n\n/** Derive the AES-GCM seal key from a password and its stored parameters. */\nexport function keyFromPassword(password: string, kdf: CacheKdf): Promise<CryptoKey> {\n\treturn deriveKey(password, kdf);\n}\n\n/** True if `key` decrypts `probe`. A wrong key fails AES-GCM authentication;\n * that is a wrong-secret answer, never an error to surface. */\nexport async function opens(key: CryptoKey, probe: EncEnvelope): Promise<boolean> {\n\ttry {\n\t\tawait unseal(key, probe);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../src/persistence/cache-lock.ts"],"names":[],"mappings":";;;;;AAeO,SAAS,aAAA,GAA0B;AACzC,EAAA,OAAO,cAAA,EAAe;AACvB;AAGO,SAAS,eAAA,CAAgB,UAAkB,GAAA,EAAmC;AACpF,EAAA,OAAO,SAAA,CAAU,UAAU,GAAG,CAAA;AAC/B;AAIA,eAAsB,KAAA,CAAM,KAAgB,KAAA,EAAsC;AACjF,EAAA,IAAI;AACH,IAAA,MAAM,MAAA,CAAO,KAAK,KAAK,CAAA;AACvB,IAAA,OAAO,IAAA;AAAA,EACR,CAAA,CAAA,MAAQ;AACP,IAAA,OAAO,KAAA;AAAA,EACR;AACD","file":"cache-lock-NXIR6JRB.js","sourcesContent":["// Seal-key material for a lock-mode cache. The key is derived from a password\n// (the backup's Argon2id KDF) or supplied by the app (e.g. a passkey PRF key),\n// and is held in memory only - never written next to the data. That is what a\n// device-key seal (cache-crypto) cannot give: a copy of the whole browser\n// profile carries the device key, but not a secret kept in RAM. Only the KDF\n// salt is persisted, and a salt is not secret.\n\nimport { unseal, type EncEnvelope } from './cache-crypto';\nimport { deriveKey, freshKdfParams } from '../selfstore/crypto';\nimport type { KdfParams } from '../selfstore/types';\n\n/** Argon2id parameters for a password-locked cache; persisted in the clear. */\nexport type CacheKdf = KdfParams;\n\n/** Fresh Argon2id parameters (random salt, current default cost). */\nexport function freshCacheKdf(): CacheKdf {\n\treturn freshKdfParams();\n}\n\n/** Derive the AES-GCM seal key from a password and its stored parameters. */\nexport function keyFromPassword(password: string, kdf: CacheKdf): Promise<CryptoKey> {\n\treturn deriveKey(password, kdf);\n}\n\n/** True if `key` decrypts `probe`. A wrong key fails AES-GCM authentication;\n * that is a wrong-secret answer, never an error to surface. */\nexport async function opens(key: CryptoKey, probe: EncEnvelope): Promise<boolean> {\n\ttry {\n\t\tawait unseal(key, probe);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"]}
@@ -42,5 +42,5 @@ function toStoreError(e) {
42
42
  }
43
43
 
44
44
  export { makeMachine, toStoreError, withDeadline };
45
- //# sourceMappingURL=chunk-SGISYMT5.js.map
46
- //# sourceMappingURL=chunk-SGISYMT5.js.map
45
+ //# sourceMappingURL=chunk-43BJDRPT.js.map
46
+ //# sourceMappingURL=chunk-43BJDRPT.js.map
@@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CAAA,EAAwB;AACpD,EAAA,IAAI,gBAAA,CAAiB,CAAC,CAAA,EAAG;AACxB,IAAA,OAAO,EAAE,IAAA,EAAM,CAAA,CAAE,IAAA,EAAM,QAAA,EAAU,aAAA,CAAc,CAAA,CAAE,IAAI,CAAA,EAAG,OAAA,EAAS,CAAA,CAAE,OAAA,EAAQ;AAAA,EAC5E;AACA,EAAA,MAAM,UAAU,CAAA,YAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,OAAO,CAAC,CAAA;AACzD,EAAA,OAAO,EAAE,IAAA,EAAM,oBAAA,EAAsB,UAAU,aAAA,CAAc,oBAAoB,GAAG,OAAA,EAAQ;AAC7F","file":"chunk-SGISYMT5.js","sourcesContent":["// Shared plumbing for the flows: a tiny observable snapshot (fits the\n// Svelte store contract and React's useSyncExternalStore), a deadline\n// wrapper for network legs, and the normalizer that turns anything thrown\n// into the stable { code, labelKey, message } shape.\n\nimport type { StoreError } from '../persistence/store';\nimport { SelfstoreError, errorLabelKey, isSelfstoreError } from '../selfstore/errors';\n\n/** What every flow exposes: the current snapshot plus a subscription.\n * `subscribe` calls the listener IMMEDIATELY with the current snapshot and on\n * every change after - that is the Svelte store contract, so a flow works as\n * `$flow` in Svelte; React reads `useSyncExternalStore(flow.subscribe, () =>\n * flow.snapshot)`; everyone else just re-renders in the callback. */\nexport interface FlowStore<T> {\n\treadonly snapshot: T;\n\tsubscribe(listener: (snapshot: T) => void): () => void;\n}\n\nexport interface Machine<T> extends FlowStore<T> {\n\t/** Merge a partial into the snapshot and notify. */\n\tset(patch: Partial<T>): void;\n}\n\nexport function makeMachine<T extends object>(initial: T): Machine<T> {\n\tlet snapshot = initial;\n\tconst listeners = new Set<(s: T) => void>();\n\treturn {\n\t\tget snapshot(): T {\n\t\t\treturn snapshot;\n\t\t},\n\t\tset(patch: Partial<T>): void {\n\t\t\tsnapshot = { ...snapshot, ...patch };\n\t\t\tlisteners.forEach((fn) => fn(snapshot));\n\t\t},\n\t\tsubscribe(listener: (s: T) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\tlistener(snapshot);\n\t\t\treturn () => listeners.delete(listener);\n\t\t}\n\t};\n}\n\n/** Bound a network leg so a stuck destination surfaces as a retryable error\n * instead of a flow frozen on a spinner. The rejection is TARGET_UNAVAILABLE -\n * transient by contract - because \"did not answer in time\" says nothing about\n * access being lost. Never wrap a human step (a consent popup, a picker):\n * people are allowed to be slower than a deadline. */\nexport async function withDeadline<T>(work: Promise<T>, ms: number, what: string): Promise<T> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst gate = new Promise<never>((_resolve, reject) => {\n\t\ttimer = setTimeout(\n\t\t\t() => reject(new SelfstoreError('TARGET_UNAVAILABLE', `${what} did not answer within ${ms}ms.`)),\n\t\t\tms\n\t\t);\n\t});\n\ttry {\n\t\treturn await Promise.race([work, gate]);\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\n/** Normalize anything thrown into the stable StoreError shape the whole\n * library reports with: show `labelKey`, log `message`. Unknown errors map to\n * TARGET_UNAVAILABLE (transient, retryable) - the flow never invents new\n * codes for the app to branch on. */\nexport function toStoreError(e: unknown): StoreError {\n\tif (isSelfstoreError(e)) {\n\t\treturn { code: e.code, labelKey: errorLabelKey(e.code), message: e.message };\n\t}\n\tconst message = e instanceof Error ? e.message : String(e);\n\treturn { code: 'TARGET_UNAVAILABLE', labelKey: errorLabelKey('TARGET_UNAVAILABLE'), message };\n}\n"]}
1
+ {"version":3,"sources":["../src/flows/machine.ts"],"names":[],"mappings":";;;AAuBO,SAAS,YAA8B,OAAA,EAAwB;AACrE,EAAA,IAAI,QAAA,GAAW,OAAA;AACf,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAoB;AAC1C,EAAA,OAAO;AAAA,IACN,IAAI,QAAA,GAAc;AACjB,MAAA,OAAO,QAAA;AAAA,IACR,CAAA;AAAA,IACA,IAAI,KAAA,EAAyB;AAC5B,MAAA,QAAA,GAAW,EAAE,GAAG,QA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O,EAAE,IAAA,EAAM,oBAAA,EAAsB,UAAU,aAAA,CAAc,oBAAoB,GAAG,OAAA,EAAQ;AAC7F","file":"chunk-43BJDRPT.js","sourcesContent":["// Shared plumbing for the flows: a tiny observable snapshot (fits the\n// Svelte store contract and React's useSyncExternalStore), a deadline\n// wrapper for network legs, and the normalizer that turns anything thrown\n// into the stable { code, labelKey, message } shape.\n\nimport type { StoreError } from '../persistence/store';\nimport { SelfstoreError, errorLabelKey, isSelfstoreError } from '../selfstore/errors';\n\n/** What every flow exposes: the current snapshot plus a subscription.\n * `subscribe` calls the listener IMMEDIATELY with the current snapshot and on\n * every change after - that is the Svelte store contract, so a flow works as\n * `$flow` in Svelte; React reads `useSyncExternalStore(flow.subscribe, () =>\n * flow.snapshot)`; everyone else just re-renders in the callback. */\nexport interface FlowStore<T> {\n\treadonly snapshot: T;\n\tsubscribe(listener: (snapshot: T) => void): () => void;\n}\n\nexport interface Machine<T> extends FlowStore<T> {\n\t/** Merge a partial into the snapshot and notify. */\n\tset(patch: Partial<T>): void;\n}\n\nexport function makeMachine<T extends object>(initial: T): Machine<T> {\n\tlet snapshot = initial;\n\tconst listeners = new Set<(s: T) => void>();\n\treturn {\n\t\tget snapshot(): T {\n\t\t\treturn snapshot;\n\t\t},\n\t\tset(patch: Partial<T>): void {\n\t\t\tsnapshot = { ...snapshot, ...patch };\n\t\t\tlisteners.forEach((fn) => fn(snapshot));\n\t\t},\n\t\tsubscribe(listener: (s: T) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\tlistener(snapshot);\n\t\t\treturn () => listeners.delete(listener);\n\t\t}\n\t};\n}\n\n/** Bound a network leg so a stuck destination surfaces as a retryable error\n * instead of a flow frozen on a spinner. The rejection is TARGET_UNAVAILABLE -\n * transient by contract - because \"did not answer in time\" says nothing about\n * access being lost. Never wrap a human step (a consent popup, a picker):\n * people are allowed to be slower than a deadline. */\nexport async function withDeadline<T>(work: Promise<T>, ms: number, what: string): Promise<T> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst gate = new Promise<never>((_resolve, reject) => {\n\t\ttimer = setTimeout(\n\t\t\t() =>\n\t\t\t\treject(new SelfstoreError('TARGET_UNAVAILABLE', `${what} did not answer within ${ms}ms.`)),\n\t\t\tms\n\t\t);\n\t});\n\ttry {\n\t\treturn await Promise.race([work, gate]);\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\n/** Normalize anything thrown into the stable StoreError shape the whole\n * library reports with: show `labelKey`, log `message`. Unknown errors map to\n * TARGET_UNAVAILABLE (transient, retryable) - the flow never invents new\n * codes for the app to branch on. */\nexport function toStoreError(e: unknown): StoreError {\n\tif (isSelfstoreError(e)) {\n\t\treturn { code: e.code, labelKey: errorLabelKey(e.code), message: e.message };\n\t}\n\tconst message = e instanceof Error ? e.message : String(e);\n\treturn { code: 'TARGET_UNAVAILABLE', labelKey: errorLabelKey('TARGET_UNAVAILABLE'), message };\n}\n"]}
@@ -177,7 +177,10 @@ async function gcmOpenAad(key32, iv, ciphertext, aad) {
177
177
  const pt = await crypto.subtle.decrypt(params, key, src(ciphertext));
178
178
  return new Uint8Array(pt);
179
179
  } catch {
180
- throw new SelfstoreError("DECRYPT_FAILED", "Corrupted, wrong-key, or altered-header ciphertext.");
180
+ throw new SelfstoreError(
181
+ "DECRYPT_FAILED",
182
+ "Corrupted, wrong-key, or altered-header ciphertext."
183
+ );
181
184
  }
182
185
  }
183
186
  var MIN_EXTERNAL_SECRET = 16;
@@ -196,7 +199,9 @@ async function externalKek(secret) {
196
199
  }
197
200
  async function mintExternalSlot(secret, keyRef, dataKey, id) {
198
201
  if (secret.length < MIN_EXTERNAL_SECRET) {
199
- throw new TypeError(`mintExternalSlot(): external secret must be >= ${MIN_EXTERNAL_SECRET} bytes.`);
202
+ throw new TypeError(
203
+ `mintExternalSlot(): external secret must be >= ${MIN_EXTERNAL_SECRET} bytes.`
204
+ );
200
205
  }
201
206
  const key = await externalKek(secret);
202
207
  const iv = randomBytes(IV_BYTES);
@@ -226,5 +231,5 @@ async function openExternalSlot(slot, secret) {
226
231
  }
227
232
 
228
233
  export { MAX_KEY_SLOTS, assertKdfBounds, deriveKey, freshKdfParams, fromBase64, gcmOpenAad, gcmSealAad, mintExternalSlot, mintSlot, openExternalSlot, openSlot, toBase64 };
229
- //# sourceMappingURL=chunk-FDPAKHQS.js.map
230
- //# sourceMappingURL=chunk-FDPAKHQS.js.map
234
+ //# sourceMappingURL=chunk-6746AL4I.js.map
235
+ //# sourceMappingURL=chunk-6746AL4I.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/selfstore/base64.ts","../src/selfstore/argon2.ts","../src/selfstore/kdf.ts","../src/selfstore/crypto.ts"],"names":[],"mappings":";;;AAKO,SAAS,SAAS,KAAA,EAA2B;AACnD,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,MAAW,CAAA,IAAK,KAAA,EAAO,GAAA,IAAO,MAAA,CAAO,aAAa,CAAC,CAAA;AACnD,EAAA,OAAO,KAAK,GAAG,CAAA;AAChB;AAEO,SAAS,WAAW,CAAA,EAAuB;AACjD,EAAA,MAAM,GAAA,GAAM,KAAK,CAAC,CAAA;AAClB,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,GAAA,CAAI,MAAM,CAAA;AACrC,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,MAAA,EAAQ,CAAA,EAAA,EAAK,GAAA,CAAI,CAAC,CAAA,GAAI,GAAA,CAAI,UAAA,CAAW,CAAC,CAAA;AAC9D,EAAA,OAAO,GAAA;AACR;;;ACTO,IAAM,SAAA,GAAY,EAAA;AAuBzB,eAAsB,UAAU,GAAA,EAAkC;AACjE,EAAA,MAAM,EAAE,QAAA,EAAS,GAAI,MAAM,OAAO,WAAW,CAAA;AAC7C,EAAA,OAAO,QAAA,CAAS;AAAA,IACf,UAAU,GAAA,CAAI,QAAA;AAAA,IACd,IAAA,EAAM,UAAA,C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AM,QAAA,CAAS,WAAA,CAAY,CAAC,CAAC,CAAA;AAAA,IACjC,IAAA,EAAM,UAAA;AAAA,IACN,MAAA;AAAA,IACA,EAAA,EAAI,SAAS,EAAE,CAAA;AAAA,IACf,OAAA,EAAS,QAAA,CAAS,IAAI,UAAA,CAAW,OAAO,CAAC;AAAA,GAC1C;AACD;AAGA,eAAsB,gBAAA,CACrB,MACA,MAAA,EAC6B;AAC7B,EAAA,IAAI,MAAA,CAAO,MAAA,GAAS,mBAAA,EAAqB,OAAO,IAAA;AAChD,EAAA,IAAI;AACH,IAAA,MAAM,GAAA,GAAM,MAAM,WAAA,CAAY,MAAM,CAAA;AACpC,IAAA,MAAM,EAAA,GAAK,MAAM,MAAA,CAAO,MAAA,CAAO,OAAA;AAAA,MAC9B,EAAE,MAAM,SAAA,EAAW,EAAA,EAAI,IAAI,UAAA,CAAW,IAAA,CAAK,EAAE,CAAC,CAAA,EAAE;AAAA,MAChD,GAAA;AAAA,MACA,GAAA,CAAI,UAAA,CAAW,IAAA,CAAK,OAAO,CAAC;AAAA,KAC7B;AACA,IAAA,MAAM,OAAA,GAAU,IAAI,UAAA,CAAW,EAAE,CAAA;AACjC,IAAA,OAAO,OAAA,CAAQ,MAAA,KAAW,EAAA,GAAK,OAAA,GAAU,IAAA;AAAA,EAC1C,CAAA,CAAA,MAAQ;AACP,IAAA,OAAO,IAAA;AAAA,EACR;AACD","file":"chunk-6746AL4I.js","sourcesContent":["/**\n * Base64 <-> bytes, shared by the crypto layer and the KDF worker (the worker\n * bundle must not drag the whole crypto module in for two helpers).\n */\n\nexport function toBase64(bytes: Uint8Array): string {\n\tlet bin = '';\n\tfor (const b of bytes) bin += String.fromCharCode(b);\n\treturn btoa(bin);\n}\n\nexport function fromBase64(s: string): Uint8Array {\n\tconst bin = atob(s);\n\tconst out = new Uint8Array(bin.length);\n\tfor (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n\treturn out;\n}\n","// The one Argon2id call, shared by the calling-thread fallback and the KDF\n// worker so both derive byte-identical keys. hash-wasm loads dynamically -\n// only when a password is actually used.\n\nimport { fromBase64 } from './base64';\n\n/** AES-256 key length. */\nexport const KEY_BYTES = 32;\n\n/** One key-derivation job (postMessage-friendly: plain fields only). */\nexport interface KdfJob {\n\tid: number;\n\tpassword: string;\n\t/** Base64, exactly as stored in the backup header. */\n\tsalt: string;\n\t/** Memory cost in KiB. */\n\tm: number;\n\t/** Iterations (passes). */\n\tt: number;\n\t/** Parallelism (lanes). */\n\tp: number;\n}\n\n/** The worker's reply: the raw key, or the failure message. */\nexport interface KdfReply {\n\tid: number;\n\tkey?: Uint8Array;\n\terror?: string;\n}\n\nexport async function runKdfJob(job: KdfJob): Promise<Uint8Array> {\n\tconst { argon2id } = await import('hash-wasm');\n\treturn argon2id({\n\t\tpassword: job.password,\n\t\tsalt: fromBase64(job.salt),\n\t\tparallelism: job.p,\n\t\titerations: job.t,\n\t\tmemorySize: job.m,\n\t\thashLength: KEY_BYTES,\n\t\toutputType: 'binary'\n\t});\n}\n","// Off-main-thread key derivation. Argon2id takes about a second at the\n// default cost, which would jank every encrypted push and pull if it ran on\n// the UI thread. One lazy dedicated worker, terminated after an idle window\n// so its ~46 MiB of WASM memory is not held forever. Any failure to spawn,\n// load, or answer falls back to the calling thread, which runs the exact\n// same runKdfJob - the worker is a responsiveness optimization, never a\n// correctness dependency.\n\nimport { runKdfJob, type KdfJob, type KdfReply } from './argon2';\nimport type { KdfParams } from './types';\n\n// Generous: a wedged worker is rerun on the calling thread, and Argon2id at\n// the default cost already takes a second or two on a phone.\nconst JOB_TIMEOUT_MS = 30_000;\nconst IDLE_TERMINATE_MS = 30_000;\n\ninterface Pending {\n\tjob: KdfJob;\n\tresolve: (key: Uint8Array) => void;\n\treject: (e: unknown) => void;\n\ttimer: ReturnType<typeof setTimeout>;\n}\n\nlet worker: Worker | null = null;\n// Once the worker path fails (blocked, missing asset), stay on the calling\n// thread for the rest of the session instead of failing again.\nlet broken = false;\nlet seq = 0;\nconst pending = new Map<number, Pending>();\nlet idleTimer: ReturnType<typeof setTimeout> | undefined;\n\nfunction armIdleStop(): void {\n\tclearTimeout(idleTimer);\n\tidleTimer = setTimeout(() => {\n\t\tif (pending.size === 0 && worker) {\n\t\t\tworker.terminate();\n\t\t\tworker = null; // respawned on the next job\n\t\t}\n\t}, IDLE_TERMINATE_MS);\n}\n\n/** Abandon the worker and finish every queued job on the calling thread. */\nfunction fallBack(): void {\n\tbroken = true;\n\tworker?.terminate();\n\tworker = null;\n\tclearTimeout(idleTimer);\n\tfor (const p of pending.values()) {\n\t\tclearTimeout(p.timer);\n\t\trunKdfJob(p.job).then(p.resolve, p.reject);\n\t}\n\tpending.clear();\n}\n\nfunction ensureWorker(): Worker | null {\n\tif (broken) return null;\n\tif (worker) return worker;\n\tif (typeof Worker === 'undefined') {\n\t\tbroken = true; // Node, old runtimes\n\t\treturn null;\n\t}\n\ttry {\n\t\t// Bundlers (Vite, webpack 5, Rollup) detect this exact\n\t\t// `new Worker(new URL(...), import.meta.url)` shape to ship the worker\n\t\t// file as an asset - do not refactor it away.\n\t\tworker = new Worker(new URL('./kdf-worker.js', import.meta.url), {\n\t\t\ttype: 'module',\n\t\t\tname: 'selfstore-kdf'\n\t\t});\n\t} catch {\n\t\tbroken = true;\n\t\treturn null;\n\t}\n\tworker.onmessage = (ev: MessageEvent<KdfReply>): void => {\n\t\tconst reply = ev.data;\n\t\tconst p = pending.get(reply.id);\n\t\tif (!p) return;\n\t\tpending.delete(reply.id);\n\t\tclearTimeout(p.timer);\n\t\tif (reply.key) p.resolve(reply.key);\n\t\telse p.reject(new Error(reply.error ?? 'key derivation failed in the worker'));\n\t\tarmIdleStop();\n\t};\n\t// Script 404, parse error, CSP: rerun the queued jobs locally.\n\tworker.onerror = (): void => fallBack();\n\treturn worker;\n}\n\n/** Derive the raw AES key for `kdf`, off the main thread when possible. */\nexport function deriveRaw(password: string, kdf: KdfParams): Promise<Uint8Array> {\n\tconst job: KdfJob = { id: ++seq, password, salt: kdf.salt, m: kdf.m, t: kdf.t, p: kdf.p };\n\tconst w = ensureWorker();\n\tif (!w) return runKdfJob(job);\n\treturn new Promise<Uint8Array>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\t// fallBack() clears every OTHER pending timer, so no job runs twice.\n\t\t\tpending.delete(job.id);\n\t\t\tfallBack();\n\t\t\trunKdfJob(job).then(resolve, reject);\n\t\t}, JOB_TIMEOUT_MS);\n\t\tpending.set(job.id, { job, resolve, reject, timer });\n\t\tw.postMessage(job);\n\t});\n}\n","// AES-256-GCM via WebCrypto over an Argon2id-derived key (hash-wasm). The\n// derivation runs in a worker when the platform has one (see kdf.ts); the\n// WASM is imported dynamically so it only loads when a password is used.\n\nimport type { KdfParams, PasswordSlot, ExternalSlot } from './types';\nimport { deriveRaw } from './kdf';\nimport { toBase64, fromBase64 } from './base64';\nimport { SelfstoreError } from './errors';\n\nexport { toBase64, fromBase64 };\n\nconst IV_BYTES = 12;\nconst SALT_BYTES = 16;\n\n/**\n * Cost for new backups: 46 MiB, 3 passes - above the OWASP Argon2id minimum,\n * ~1-2 s on a phone. Params are stored per file, so older backups keep\n * decrypting with their own cost.\n */\nexport const DEFAULT_ARGON2 = { m: 47104, t: 3, p: 1 } as const;\n\n/**\n * Read-side ceiling (m is in KiB: 1 GiB, 10 passes, 4 lanes). Without it a\n * crafted file could declare m = 8_000_000 and make the reader allocate\n * gigabytes before any password check. Out-of-range params are\n * UNSUPPORTED_VERSION, not DECRYPT_FAILED - the file is not corrupt, its\n * parameters are just outside what this reader will run.\n */\nconst KDF_MAX = { m: 1024 * 1024, t: 10, p: 4 } as const;\nconst KDF_MIN = { m: 8, t: 1, p: 1 } as const;\n\n/** Throws UNSUPPORTED_VERSION on out-of-range Argon2 params. Call before touching the WASM. */\nexport function assertKdfBounds(kdf: KdfParams): void {\n\tconst { m, t, p } = kdf;\n\tconst ok =\n\t\tNumber.isInteger(m) &&\n\t\tNumber.isInteger(t) &&\n\t\tNumber.isInteger(p) &&\n\t\tm >= KDF_MIN.m &&\n\t\tm <= KDF_MAX.m &&\n\t\tt >= KDF_MIN.t &&\n\t\tt <= KDF_MAX.t &&\n\t\tp >= KDF_MIN.p &&\n\t\tp <= KDF_MAX.p;\n\tif (!ok) {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Argon2 parameters out of the supported range (m=${m} KiB, t=${t}, p=${p}).`\n\t\t);\n\t}\n}\n\nfunction randomBytes(n: number): Uint8Array {\n\tconst b = new Uint8Array(n);\n\tcrypto.getRandomValues(b);\n\treturn b;\n}\n\n/** Coerce to the ArrayBuffer-backed view WebCrypto's types want (always safe here). */\nfunction src(u8: Uint8Array): Uint8Array<ArrayBuffer> {\n\treturn u8 as Uint8Array<ArrayBuffer>;\n}\n\n/**\n * Derive the AES-256-GCM key for `kdf`, imported non-extractable. Shared by\n * the backup cipher and the identity vault's passphrase lock.\n */\nexport async function deriveKey(password: string, kdf: KdfParams): Promise<CryptoKey> {\n\tconst raw = await deriveRaw(password, kdf);\n\treturn crypto.subtle.importKey('raw', src(raw), 'AES-GCM', false, ['encrypt', 'decrypt']);\n}\n\n/** Fresh salt at the current default cost, for a new password-sealed write. */\nexport function freshKdfParams(): KdfParams {\n\treturn { algo: 'argon2id', salt: toBase64(randomBytes(SALT_BYTES)), ...DEFAULT_ARGON2 };\n}\n\n// --- Password envelope (format 3) slots --------------------------------------\n\n/**\n * Each slot costs one Argon2id trial on open, so an unbounded list would let\n * a crafted file demand unbounded memory-hard work. Same spirit as\n * assertKdfBounds.\n */\nexport const MAX_KEY_SLOTS = 8;\n\n/** Wrap the 32-byte data key under a key derived from `password`, fresh salt and IV. */\nexport async function mintSlot(\n\tpassword: string,\n\tdataKey: Uint8Array,\n\tid?: string\n): Promise<PasswordSlot> {\n\tconst kdf = freshKdfParams();\n\tconst key = await deriveKey(password, kdf);\n\tconst iv = randomBytes(IV_BYTES);\n\tconst wrapped = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: src(iv) }, key, src(dataKey));\n\treturn {\n\t\tid: id ?? toBase64(randomBytes(6)),\n\t\tkdf,\n\t\tiv: toBase64(iv),\n\t\twrapped: toBase64(new Uint8Array(wrapped))\n\t};\n}\n\n/**\n * Returns the data key if `password` opens this slot, else null. GCM keeps\n * wrong-password and tampering indistinguishable (fail closed). Bounds are\n * checked before any derivation, and that refusal is never swallowed - a\n * memory-hard bomb must not hide behind \"wrong password\".\n */\nexport async function openSlot(slot: PasswordSlot, password: string): Promise<Uint8Array | null> {\n\tassertKdfBounds(slot.kdf);\n\ttry {\n\t\tconst key = await deriveKey(password, slot.kdf);\n\t\tconst pt = await crypto.subtle.decrypt(\n\t\t\t{ name: 'AES-GCM', iv: src(fromBase64(slot.iv)) },\n\t\t\tkey,\n\t\t\tsrc(fromBase64(slot.wrapped))\n\t\t);\n\t\tconst dataKey = new Uint8Array(pt);\n\t\treturn dataKey.length === 32 ? dataKey : null;\n\t} catch (e) {\n\t\tif (e instanceof SelfstoreError) throw e;\n\t\treturn null;\n\t}\n}\n\n// --- Authenticated envelope (format 3) data seal -----------------------------\n\n/**\n * Seal the inner ZIP under the data key with the header bytes as AAD. Format\n * 5 passes the exact meta.json bytes here, which binds the slot table to the\n * ciphertext: write access to the file is not enough to strip or swap a key\n * slot without breaking the tag. The caller generates the iv (it rides in\n * meta.json, hence inside the AAD) so seal and open agree byte for byte.\n */\nexport async function gcmSealAad(\n\tkey32: Uint8Array,\n\tiv: Uint8Array,\n\tplaintext: Uint8Array,\n\taad: Uint8Array\n): Promise<Uint8Array> {\n\tconst key = await crypto.subtle.importKey('raw', src(key32), 'AES-GCM', false, ['encrypt']);\n\tconst ct = await crypto.subtle.encrypt(\n\t\t{ name: 'AES-GCM', iv: src(iv), additionalData: src(aad) },\n\t\tkey,\n\t\tsrc(plaintext)\n\t);\n\treturn new Uint8Array(ct);\n}\n\n/**\n * Open sealed data. `aad` is the additional authenticated data bound at seal\n * time (the envelope binds its header bytes); pass none for seals that bound\n * none. Any tag failure - wrong key, corrupt data, altered header - is one\n * DECRYPT_FAILED.\n */\nexport async function gcmOpenAad(\n\tkey32: Uint8Array,\n\tiv: Uint8Array,\n\tciphertext: Uint8Array,\n\taad?: Uint8Array\n): Promise<Uint8Array> {\n\ttry {\n\t\tconst key = await crypto.subtle.importKey('raw', src(key32), 'AES-GCM', false, ['decrypt']);\n\t\tconst params: AesGcmParams = { name: 'AES-GCM', iv: src(iv) };\n\t\tif (aad) params.additionalData = src(aad);\n\t\tconst pt = await crypto.subtle.decrypt(params, key, src(ciphertext));\n\t\treturn new Uint8Array(pt);\n\t} catch {\n\t\tthrow new SelfstoreError(\n\t\t\t'DECRYPT_FAILED',\n\t\t\t'Corrupted, wrong-key, or altered-header ciphertext.'\n\t\t);\n\t}\n}\n\n// --- External-key slots ------------------------------------------------------\n\n// A passkey PRF output is 32 bytes; anything under 16 is too weak to key a backup.\nconst MIN_EXTERNAL_SECRET = 16;\n\nconst EXTERNAL_INFO = new TextEncoder().encode('selfstore-external-slot-v1');\n\n/**\n * KEK for an external slot. The secret is already high-entropy (passkey PRF,\n * hardware token), so one HKDF-SHA256 expansion is enough - Argon2 only\n * exists to stretch low-entropy passwords. The fixed info label\n * domain-separates this use from any other the same secret might see.\n */\nasync function externalKek(secret: Uint8Array): Promise<CryptoKey> {\n\tconst ikm = await crypto.subtle.importKey('raw', src(secret), 'HKDF', false, ['deriveBits']);\n\tconst bits = await crypto.subtle.deriveBits(\n\t\t{ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: src(EXTERNAL_INFO) },\n\t\tikm,\n\t\t256\n\t);\n\treturn crypto.subtle.importKey('raw', src(new Uint8Array(bits)), 'AES-GCM', false, [\n\t\t'encrypt',\n\t\t'decrypt'\n\t]);\n}\n\n/** Wrap the data key under a KEK derived from `secret`; `keyRef` is carried verbatim. */\nexport async function mintExternalSlot(\n\tsecret: Uint8Array,\n\tkeyRef: string,\n\tdataKey: Uint8Array,\n\tid?: string\n): Promise<ExternalSlot> {\n\tif (secret.length < MIN_EXTERNAL_SECRET) {\n\t\tthrow new TypeError(\n\t\t\t`mintExternalSlot(): external secret must be >= ${MIN_EXTERNAL_SECRET} bytes.`\n\t\t);\n\t}\n\tconst key = await externalKek(secret);\n\tconst iv = randomBytes(IV_BYTES);\n\tconst wrapped = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: src(iv) }, key, src(dataKey));\n\treturn {\n\t\tid: id ?? toBase64(randomBytes(6)),\n\t\tkind: 'external',\n\t\tkeyRef,\n\t\tiv: toBase64(iv),\n\t\twrapped: toBase64(new Uint8Array(wrapped))\n\t};\n}\n\n/** Returns the data key if `secret` opens this slot, else null. Fail closed, like openSlot. */\nexport async function openExternalSlot(\n\tslot: ExternalSlot,\n\tsecret: Uint8Array\n): Promise<Uint8Array | null> {\n\tif (secret.length < MIN_EXTERNAL_SECRET) return null;\n\ttry {\n\t\tconst key = await externalKek(secret);\n\t\tconst pt = await crypto.subtle.decrypt(\n\t\t\t{ name: 'AES-GCM', iv: src(fromBase64(slot.iv)) },\n\t\t\tkey,\n\t\t\tsrc(fromBase64(slot.wrapped))\n\t\t);\n\t\tconst dataKey = new Uint8Array(pt);\n\t\treturn dataKey.length === 32 ? dataKey : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { connect4, connect3, isSupported, connect, openExisting, connect2 } from './chunk-CUWB5EWF.js';
2
- import { restore } from './chunk-JB4JHM7V.js';
3
- import { makeMachine, withDeadline, toStoreError } from './chunk-SGISYMT5.js';
1
+ import { connect4, connect3, isSupported, connect, openExisting, connect2 } from './chunk-TEIAFKFS.js';
2
+ import { restore } from './chunk-SRKUHFRG.js';
3
+ import { makeMachine, withDeadline, toStoreError } from './chunk-43BJDRPT.js';
4
4
  import { SelfstoreError, isSelfstoreError } from './chunk-VBFMMR7Q.js';
5
5
 
6
6
  // src/flows/connect.ts
@@ -437,5 +437,5 @@ function joinFlow(link, engine, options = {}) {
437
437
  }
438
438
 
439
439
  export { connectFlow, joinFlow, shareFlow };
440
- //# sourceMappingURL=chunk-ATUPHVLG.js.map
441
- //# sourceMappingURL=chunk-ATUPHVLG.js.map
440
+ //# sourceMappingURL=chunk-CUFKME4S.js.map
441
+ //# sourceMappingURL=chunk-CUFKME4S.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/flows/connect.ts","../src/flows/share.ts","../src/flows/join.ts"],"names":["connect","config","gen","DEFAULT_DEADLINE_MS"],"mappings":";;;;;;AA8JA,IAAM,mBAAA,GAAsB,GAAA;AAG5B,SAAS,QAAQ,GAAA,EAGf;AACD,EAAA,IAAI,QAAQ,QAAA,EAAU,OAAO,EAAE,QAAA,EAAU,eAAA,EAAiB,SAAS,SAAA,EAAU;AAC7E,EAAA,IAAI,QAAQ,SAAA,EAAW,OAAO,EAAE,QAAA,EAAU,gBAAA,EAAkB,SAAS,UAAA,EAAW;AAChF,EAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,OAAA,EAAS,QAAA,EAAS;AAC/C;AAEO,SAAS,WAAA,CACf,KAAA,EACA,OAAA,EACA,OAAA,GAA8B,EAAC,EACjB;AACd,EAAA,MAAM,IAAA,GAAO,UAAA,IAAc,KAAA,GAAQ,KAAA,CAAM,QAAA,GAAW,KAAA;AACpD,EAAA,MAAM,UAAA,GAAa,QAAQ,UAAA,IAAc,mBAAA;AACzC,EAAA,MAAM,KAAA,GAAS,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,CAAoB,MAAA;AAAA,IACrD,CAAC,CAAA,KAAA,CAAO,CAAA,KAAM,OAAA,IAAW,CAAA,KAAM,MAAA,IAAU,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,KAAS,OAAA,CAAQ,CAAC,CAAA,IAAK;AAAA,GACzF;AAEA,EAAA,MAAM,IAAI,WAAA,CAA6B;AAAA,IACtC,IAAA,EAAM,QAAA;AAAA,IACN,KAAA;AAAA,IACA,IAAA,EAAM,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AAA,IAEA,aAAA,GAAsB;AACrB,MAAA,MAAM,QAAA,GAAW,MAAA,CAAO,aAAA,EAAe,IAAA,CAAK,MAAM,CAAA;AAClD,MAAA,IAAI,CAAC,QAAA,EAAU;AACf,MAAA,MAAM,EAAE,IAAA,EAAM,IAAA,EAAK,GAAI,CAAA,CAAE,QAAA;AACzB,MAAA,IAAI,QAAS,IAAA,KAAS,OAAA,IAAW,IAAA,KAAS,WAAA,IAAe,SAAS,OAAA,EAAU;AAC5E,MAAA,MAAM,MAAM,EAAE,UAAA;AACd,MAAA,CAAA,CAAE,IAAI,EAAE,IAAA,EAAM,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AACjC,MAAA,KAAK,QAAA,EAAS,CACZ,IAAA,CAAK,MAAM;AACX,QAAA,IAAI,QAAQ,UAAA,EAAY;AACxB,QAAA,OAAA,EAAQ;AAAA,MACT,CAAC,CAAA,CACA,KAAA,CAAM,CAAC,CAAA,KAAM;AACb,QAAA,IAAI,QAAQ,UAAA,EAAY;AACxB,QAAA,CAAA,CAAE,GAAA,CAAI,EAAE,IAAA,EAAM,OAAA,EAAS,IAAA,EAAM,OAAO,KAAA,EAAO,YAAA,CAAa,CAAC,CAAA,EAAG,CAAA;AAAA,MAC7D,CAAC,CAAA;AAAA,IACH,CAAA;AAAA,IAEA,KAAA,GAAc;AACb,MAAA,IAAI,CAAA,CAAE,QAAA,CAAS,IAAA,KAAS,OAAA,EAAS;AACjC,MAAA,OAAA,EAAQ;AAAA,IACT;AAAA,GACD;AACD","file":"chunk-CUFKME4S.js","sourcesContent":["// connectFlow: the \"where does my data live\" journey as a headless state\n// machine. It owns ordering and failure rules that took a series of\n// production hotfixes to get right, each covered by a test:\n//\n// choose -> (form) -> authorizing -> (password) -> (conflict) -> connected\n// \\-> error\n//\n// One popup per gesture (re-entry ignored while a leg is in flight), and a\n// cancelled popup is not an error - back to 'choose', silently. An encrypted\n// backup's password is proven by a trial read while the store is untouched,\n// so a wrong password can never half-connect (deferUnlock opts out: adopt\n// locked, unlock where the host chooses). overwrite() is the forgotten-\n// password escape: local wiped first, tiny blank write. Merge is the default\n// reconciliation; the destructive choices hide behind 'conflict', which only\n// appears when the app declared local data worth asking about. Network legs\n// run under a deadline; human steps never do. A cancelled journey stays\n// dead - late resolutions are discarded (generation counter).\n\nimport type { LocalStore, StoreError } from '../persistence/store';\nimport type { BackupTarget } from '../persistence/target';\nimport type { KV } from '../persistence/cache';\nimport { restore } from '../selfstore/fluent';\nimport { SelfstoreError, isSelfstoreError } from '../selfstore/errors';\nimport { connect as driveConnect, type DriveAuth } from '../persistence/targets/drive';\nimport {\n\tconnect as fileConnect,\n\tisSupported as fileIsSupported,\n\topenExisting as fileOpenExisting\n} from '../persistence/targets/file';\nimport { connect as webdavConnect, type WebdavConfig } from '../persistence/targets/webdav';\nimport { connect as s3Connect, type S3Config } from '../persistence/targets/s3';\nimport { makeMachine, toStoreError, withDeadline, type FlowStore } from './machine';\n\nexport type ConnectKind = 'drive' | 'file' | 'webdav' | 's3';\n\n/** Produce a connected BackupTarget, or null when the user cancelled the\n * gesture (consent refused, picker closed). Custom connectors slot custom\n * targets - or test fakes - into the same journey. */\nexport type Connector = () => Promise<BackupTarget | null>;\n\n/** Which destinations the flow offers, and how to open each one. The offer\n * renders in this OBJECT's insertion order: the host decides which\n * destination leads by how it writes the object, not by a ranking here. */\nexport interface ConnectTargets {\n\t/** Google Drive: the auth strategy (e.g. gisDriveAuth), or a custom connector. */\n\tdrive?: DriveAuth | Connector;\n\t/** Local file via the browser's picker (true), or a custom connector. On\n\t * browsers without the File System Access API the flow degrades to the\n\t * manual download mode by itself. The object form offers TWO gestures on\n\t * the same destination: `create` (save picker: start or overwrite a backup\n\t * file) and `open` (open picker: adopt an EXISTING backup file - it then\n\t * goes through the same inspect/password/resolution journey). */\n\tfile?: true | Connector | { create?: true | Connector; open?: true | Connector };\n\t/** WebDAV: true renders a 'form' step and expects submitWebdav(config);\n\t * a fixed WebdavConfig skips the form; or a custom connector. */\n\twebdav?: true | WebdavConfig | Connector;\n\t/** S3-compatible bucket (Amazon S3, R2, B2, MinIO): true renders a 'form'\n\t * step and expects submitS3(config); a fixed S3Config skips the form; or a\n\t * custom connector. Offer it alongside `webdav` and the widget groups both\n\t * under one \"your server\" entry with a WebDAV/S3 toggle. */\n\ts3?: true | S3Config | Connector;\n}\n\n/** What the flows need from the store. The simple store exposes this as\n * `store.flowHost`; an advanced-store app builds it by hand. */\nexport interface FlowHost {\n\tengine: LocalStore;\n\tkv: KV;\n\t/** Backup file name on the destination (the simple store uses `app.zip`). */\n\tbackupName: string;\n}\n\nexport interface ConnectFlowOptions {\n\t/** Declare when this device holds data worth a question: only then does an\n\t * existing backup raise the 'conflict' step with the destructive choices.\n\t * Default: never - the flow applies defaultResolution. */\n\thasLocalData?: () => boolean;\n\t/** How to reconcile with a destination that already holds a backup when the\n\t * conflict step is not raised. Default 'merge' - the only choice that\n\t * loses nothing on either side. 'resume' adopts the backup (the\n\t * destination wins; this device's working copy is replaced), 'replace'\n\t * overwrites the backup with this device. An encrypted backup still asks\n\t * for its password first, whatever the resolution; an empty destination\n\t * is not concerned (this device's data simply becomes its content). */\n\tdefaultResolution?: ConnectResolution;\n\t/** Skip the password step on an encrypted backup: adopt it AS is (resume)\n\t * and complete with the store locked - nothing readable, nothing\n\t * clobbered - for the host to unlock on its own surface (engine.unlock)\n\t * after the connect. Adoption is forced whatever defaultResolution says:\n\t * without the proven key a merge is impossible and a replace would\n\t * destroy a backup no one proved they own. Hosts that let a device\n\t * holding real local data connect should keep the password-first\n\t * journey - adoption replaces the working copy. */\n\tdeferUnlock?: boolean;\n\t/** Deadline for each network leg (inspect, trial-read, attach), ms. */\n\tdeadlineMs?: number;\n}\n\nexport type ConnectStep =\n\t'choose' | 'form' | 'authorizing' | 'password' | 'conflict' | 'connected' | 'error';\n\n/** How to reconcile with a destination that already holds a backup. */\nexport type ConnectResolution = 'merge' | 'resume' | 'replace';\n\n/** What connecting did. 'merged': both sides folded. 'started': empty\n * destination now holds this device's data. 'resumed': the backup won,\n * this device adopted it. 'replaced': this device won, the backup was\n * overwritten. 'manual': degraded download-on-demand file mode. */\nexport type ConnectFlowOutcome = 'merged' | 'started' | 'resumed' | 'replaced' | 'manual';\n\nexport interface ConnectSnapshot {\n\tstep: ConnectStep;\n\t/** The destinations to offer, in the order given. */\n\tkinds: readonly ConnectKind[];\n\t/** The destination being connected (null while choosing). */\n\tkind: ConnectKind | null;\n\t/** Set when step === 'connected'. */\n\toutcome: ConnectFlowOutcome | null;\n\t/** Known after inspection: the destination already holds a backup. */\n\thasBackup: boolean;\n\t/** ...and that backup is encrypted. */\n\tencrypted: boolean;\n\t/** The last submitPassword() was wrong (stay on 'password', say so). */\n\tpasswordError: boolean;\n\t/** An async leg is in flight (render a spinner, disable the actions). */\n\tbusy: boolean;\n\t/** Set when step === 'error': show `labelKey`, log `message`. */\n\terror: StoreError | null;\n}\n\nexport interface ConnectFlow extends FlowStore<ConnectSnapshot> {\n\t/** Pick a destination. Call it inside the user's click: the consent popup /\n\t * file picker opens synchronously from the gesture. Ignored while a leg is\n\t * already in flight (one popup per gesture). For a `file` target declared\n\t * with the object form, `variant` picks the gesture: 'create' (default,\n\t * save picker) or 'open' (adopt an existing backup file). */\n\tchoose(kind: ConnectKind, variant?: 'create' | 'open'): void;\n\t/** 'form' step (webdav: true): submit the server config. */\n\tsubmitWebdav(config: WebdavConfig): void;\n\t/** 'form' step (s3: true): submit the bucket config. */\n\tsubmitS3(config: S3Config): void;\n\t/** 'password' step: prove the backup's password. Wrong password sets\n\t * passwordError and stays here; nothing is attached either way. */\n\tsubmitPassword(password: string): void;\n\t/** 'password' step escape hatch: give up on a forgotten password and start a\n\t * fresh backup over the protected one. The encrypted backup is overwritten\n\t * by this device's data (possibly empty) and lost for good - the only way\n\t * out when the password cannot be recovered. */\n\toverwrite(): void;\n\t/** 'conflict' step: pick the reconciliation. */\n\tresolveConflict(how: ConnectResolution): void;\n\t/** Abandon the journey in progress: back to 'choose'. A late resolution of\n\t * the abandoned leg is discarded. */\n\tcancel(): void;\n\t/** 'error' step: back to 'choose' to try again. */\n\tretry(): void;\n}\n\nconst DEFAULT_DEADLINE_MS = 30_000;\n\n/** A resolution's attach plan: which strategy runs, which outcome it names. */\nfunction planFor(how: ConnectResolution): {\n\tstrategy: 'merge' | 'replace-local' | 'replace-remote';\n\toutcome: ConnectFlowOutcome;\n} {\n\tif (how === 'resume') return { strategy: 'replace-local', outcome: 'resumed' };\n\tif (how === 'replace') return { strategy: 'replace-remote', outcome: 'replaced' };\n\treturn { strategy: 'merge', outcome: 'merged' };\n}\n\nexport function connectFlow(\n\tstore: FlowHost | { flowHost: FlowHost },\n\ttargets: ConnectTargets,\n\toptions: ConnectFlowOptions = {}\n): ConnectFlow {\n\tconst host = 'flowHost' in store ? store.flowHost : store;\n\tconst deadlineMs = options.deadlineMs ?? DEFAULT_DEADLINE_MS;\n\tconst kinds = (Object.keys(targets) as ConnectKind[]).filter(\n\t\t(k) => (k === 'drive' || k === 'file' || k === 'webdav' || k === 's3') && targets[k] != null\n\t);\n\n\tconst m = makeMachine<ConnectSnapshot>({\n\t\tstep: 'choose',\n\t\tkinds,\n\t\tkind: null,\n\t\toutcome: null,\n\t\thasBackup: false,\n\t\tencrypted: false,\n\t\tpasswordError: false,\n\t\tbusy: false,\n\t\terror: null\n\t});\n\n\t// The journey's working set. `generation` invalidates in-flight legs on\n\t// cancel(): whoever resolves late compares its captured generation and\n\t// drops its result instead of resurrecting an abandoned journey.\n\tlet generation = 0;\n\tlet target: BackupTarget | null = null;\n\tlet password: string | null = null;\n\n\tconst backToChoose = (): void => {\n\t\tgeneration++;\n\t\ttarget = null;\n\t\tpassword = null;\n\t\tm.set({\n\t\t\tstep: 'choose',\n\t\t\tkind: null,\n\t\t\toutcome: null,\n\t\t\thasBackup: false,\n\t\t\tencrypted: false,\n\t\t\tpasswordError: false,\n\t\t\tbusy: false,\n\t\t\terror: null\n\t\t});\n\t};\n\n\tconst fail = (e: unknown): void => {\n\t\tpassword = null;\n\t\tm.set({ step: 'error', busy: false, error: toStoreError(e) });\n\t};\n\n\tfunction connectorFor(\n\t\tkind: ConnectKind,\n\t\tvariant: 'create' | 'open' = 'create'\n\t): Connector | null {\n\t\tconst spec = targets[kind];\n\t\tif (spec == null) return null;\n\t\tif (typeof spec === 'function') return spec;\n\t\tif (kind === 'drive') {\n\t\t\tconst auth = spec as DriveAuth;\n\t\t\treturn () => driveConnect({ auth, kv: host.kv, fileName: host.backupName });\n\t\t}\n\t\tif (kind === 'file') {\n\t\t\t// Object form: each gesture has its own spec ('open' has no built-in\n\t\t\t// meaning for other kinds, so it resolves here only).\n\t\t\tif (typeof spec === 'object' && !('url' in spec)) {\n\t\t\t\tconst sub = (spec as { create?: true | Connector; open?: true | Connector })[variant];\n\t\t\t\tif (sub == null) return null;\n\t\t\t\tif (typeof sub === 'function') return sub;\n\t\t\t\treturn variant === 'open'\n\t\t\t\t\t? () => fileOpenExisting({ kv: host.kv })\n\t\t\t\t\t: () => fileConnect({ kv: host.kv, fileName: host.backupName });\n\t\t\t}\n\t\t\treturn () => fileConnect({ kv: host.kv, fileName: host.backupName });\n\t\t}\n\t\tif (kind === 's3') {\n\t\t\tconst config = spec as S3Config; // 's3: true' goes through the form step\n\t\t\treturn () => s3Connect({ kv: host.kv, config });\n\t\t}\n\t\tconst config = spec as WebdavConfig; // 'webdav: true' goes through the form step\n\t\treturn () => webdavConnect({ kv: host.kv, config });\n\t}\n\n\t/** After the target is in hand: inspect, then route to password / conflict /\n\t * attach. Everything here is network - deadline-bounded, generation-checked. */\n\tasync function inspectAndRoute(gen: number, t: BackupTarget): Promise<void> {\n\t\tconst info = await withDeadline(host.engine.inspectTarget(t), deadlineMs, 'The destination');\n\t\tif (gen !== generation) return;\n\t\ttarget = t;\n\t\tm.set({ hasBackup: info.hasBackup, encrypted: info.encrypted });\n\t\tif (!info.hasBackup) {\n\t\t\t// Empty destination: this device's data becomes its content. Nothing\n\t\t\t// to ask, nothing to lose.\n\t\t\tawait attach(gen, 'replace-remote', 'started');\n\t\t\treturn;\n\t\t}\n\t\tif (info.encrypted) {\n\t\t\tif (options.deferUnlock) {\n\t\t\t\t// The host owns the unlock surface: adopt the backup as it stands.\n\t\t\t\t// A null password on an encrypted file lands the store locked -\n\t\t\t\t// nothing readable, nothing clobbered - until engine.unlock()\n\t\t\t\t// proves the password wherever the host asks for it. The conflict\n\t\t\t\t// step is moot here: without the key, merge cannot read the remote\n\t\t\t\t// and replace would destroy a backup no one proved they own.\n\t\t\t\tawait attach(gen, 'replace-local', 'resumed');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Ask before touching anything. The password gates every resolution,\n\t\t\t// including 'replace': overwriting an encrypted backup demands proof\n\t\t\t// of ownership, or a typo away from someone's data.\n\t\t\tm.set({ step: 'password', busy: false, passwordError: false });\n\t\t\treturn;\n\t\t}\n\t\trouteAfterUnlock(gen);\n\t}\n\n\t/** Password proven (or none needed): either ask the conflict question, or\n\t * apply the default resolution - 'merge' unless the host chose otherwise,\n\t * the only default that loses nothing on either side. */\n\tfunction routeAfterUnlock(gen: number): void {\n\t\tif (gen !== generation) return;\n\t\tif (options.hasLocalData?.() === true) {\n\t\t\tm.set({ step: 'conflict', busy: false });\n\t\t\treturn;\n\t\t}\n\t\tconst plan = planFor(options.defaultResolution ?? 'merge');\n\t\tvoid attach(gen, plan.strategy, plan.outcome);\n\t}\n\n\tasync function attach(\n\t\tgen: number,\n\t\tstrategy: 'merge' | 'replace-local' | 'replace-remote',\n\t\toutcome: ConnectFlowOutcome,\n\t\twipe = false\n\t): Promise<void> {\n\t\tif (gen !== generation || !target) return;\n\t\tm.set({ busy: true });\n\t\ttry {\n\t\t\tawait withDeadline(\n\t\t\t\thost.engine.attachTarget(target, { password, strategy, wipe }),\n\t\t\t\tdeadlineMs,\n\t\t\t\t'The destination'\n\t\t\t);\n\t\t\tif (gen !== generation) return;\n\t\t\tpassword = null;\n\t\t\tm.set({ step: 'connected', outcome, busy: false, error: null });\n\t\t} catch (e) {\n\t\t\tif (gen !== generation) return;\n\t\t\tfail(e);\n\t\t}\n\t}\n\n\treturn {\n\t\tget snapshot() {\n\t\t\treturn m.snapshot;\n\t\t},\n\t\tsubscribe: m.subscribe,\n\n\t\tchoose(kind: ConnectKind, variant: 'create' | 'open' = 'create'): void {\n\t\t\tconst { step, busy } = m.snapshot;\n\t\t\tif (busy || (step !== 'choose' && step !== 'error')) return; // one popup per gesture\n\t\t\tconst connector = connectorFor(kind, variant);\n\t\t\tif (!connector) return;\n\t\t\tif (\n\t\t\t\t(kind === 'webdav' && targets.webdav === true) ||\n\t\t\t\t(kind === 's3' && targets.s3 === true)\n\t\t\t) {\n\t\t\t\tm.set({ step: 'form', kind, error: null });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Degraded manual mode only makes sense for CREATING a backup through\n\t\t\t// the built-in save picker: adopting an existing file needs the real\n\t\t\t// picker, and a custom connector owns its own fallback.\n\t\t\tconst builtinCreate =\n\t\t\t\ttargets.file === true ||\n\t\t\t\t(typeof targets.file === 'object' &&\n\t\t\t\t\t(targets.file as { create?: unknown }).create !== undefined &&\n\t\t\t\t\ttypeof (targets.file as { create?: unknown }).create !== 'function');\n\t\t\tif (kind === 'file' && variant === 'create' && builtinCreate && !fileIsSupported()) {\n\t\t\t\t// No picker on this browser: degrade to download-on-demand instead of\n\t\t\t\t// a dead button.\n\t\t\t\tconst gen = ++generation;\n\t\t\t\tm.set({ step: 'authorizing', kind, busy: true, error: null });\n\t\t\t\tvoid host.engine\n\t\t\t\t\t.setManualFile()\n\t\t\t\t\t.then(() => {\n\t\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\t\tm.set({ step: 'connected', outcome: 'manual', busy: false });\n\t\t\t\t\t})\n\t\t\t\t\t.catch((e) => {\n\t\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\t\tfail(e);\n\t\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst gen = ++generation;\n\t\t\tm.set({ step: 'authorizing', kind, busy: true, error: null });\n\t\t\t// The connector runs the human gesture (popup, picker): no deadline on\n\t\t\t// people. The network legs after it are bounded in inspectAndRoute.\n\t\t\tvoid connector()\n\t\t\t\t.then(async (t) => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tif (!t) {\n\t\t\t\t\t\t// Drive/file/custom answer null for a cancelled popup or picker:\n\t\t\t\t\t\t// not an error, no message. A FIXED webdav/s3 config answering\n\t\t\t\t\t\t// null means the server did not: that one is a retryable error.\n\t\t\t\t\t\tif (kind === 'webdav' || kind === 's3') {\n\t\t\t\t\t\t\tfail(\n\t\t\t\t\t\t\t\tnew SelfstoreError(\n\t\t\t\t\t\t\t\t\t'TARGET_UNAVAILABLE',\n\t\t\t\t\t\t\t\t\t'The server did not answer (address, credentials or CORS).'\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbackToChoose();\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait inspectAndRoute(gen, t);\n\t\t\t\t})\n\t\t\t\t.catch((e) => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tfail(e);\n\t\t\t\t});\n\t\t},\n\n\t\tsubmitWebdav(config: WebdavConfig): void {\n\t\t\tconst { step, busy } = m.snapshot;\n\t\t\tif (busy || step !== 'form') return;\n\t\t\tconst gen = ++generation;\n\t\t\tm.set({ step: 'authorizing', busy: true });\n\t\t\tvoid withDeadline(webdavConnect({ kv: host.kv, config }), deadlineMs, 'The WebDAV server')\n\t\t\t\t.then(async (t) => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tif (!t) {\n\t\t\t\t\t\t// webdavConnect answers null when the server does not: with an\n\t\t\t\t\t\t// explicit config this is a wrong-address error, not a cancel.\n\t\t\t\t\t\tfail(\n\t\t\t\t\t\t\tnew SelfstoreError(\n\t\t\t\t\t\t\t\t'TARGET_UNAVAILABLE',\n\t\t\t\t\t\t\t\t'The WebDAV server did not answer (URL, credentials or CORS).'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait inspectAndRoute(gen, t);\n\t\t\t\t})\n\t\t\t\t.catch((e) => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tfail(e);\n\t\t\t\t});\n\t\t},\n\n\t\tsubmitS3(config: S3Config): void {\n\t\t\tconst { step, busy } = m.snapshot;\n\t\t\tif (busy || step !== 'form') return;\n\t\t\tconst gen = ++generation;\n\t\t\tm.set({ step: 'authorizing', busy: true });\n\t\t\tvoid withDeadline(s3Connect({ kv: host.kv, config }), deadlineMs, 'The S3 endpoint')\n\t\t\t\t.then(async (t) => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tif (!t) {\n\t\t\t\t\t\t// s3Connect answers null when the endpoint does not: with an\n\t\t\t\t\t\t// explicit config this is a wrong-config error, not a cancel.\n\t\t\t\t\t\tfail(\n\t\t\t\t\t\t\tnew SelfstoreError(\n\t\t\t\t\t\t\t\t'TARGET_UNAVAILABLE',\n\t\t\t\t\t\t\t\t'The S3 endpoint did not answer (endpoint, credentials or CORS).'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait inspectAndRoute(gen, t);\n\t\t\t\t})\n\t\t\t\t.catch((e) => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tfail(e);\n\t\t\t\t});\n\t\t},\n\n\t\tsubmitPassword(pw: string): void {\n\t\t\tconst { step, busy } = m.snapshot;\n\t\t\tif (busy || step !== 'password' || !target) return;\n\t\t\tconst gen = generation;\n\t\t\tm.set({ busy: true, passwordError: false });\n\t\t\tvoid (async () => {\n\t\t\t\ttry {\n\t\t\t\t\t// PROVE the password against the real backup while the store is\n\t\t\t\t\t// still untouched: download and trial-read. A wrong password is a\n\t\t\t\t\t// retype, never a locked store or a gate.\n\t\t\t\t\tconst blob = await withDeadline(target!.load(), deadlineMs, 'The destination');\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tif (!blob) {\n\t\t\t\t\t\tthrow new SelfstoreError('TARGET_UNAVAILABLE', 'The backup could not be downloaded.');\n\t\t\t\t\t}\n\t\t\t\t\tawait restore(blob).withPassword(pw).read();\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tpassword = pw;\n\t\t\t\t\tm.set({ busy: false });\n\t\t\t\t\trouteAfterUnlock(gen);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tif (isSelfstoreError(e) && e.code === 'DECRYPT_FAILED') {\n\t\t\t\t\t\tm.set({ busy: false, passwordError: true }); // stay, say so, retype\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tfail(e);\n\t\t\t\t}\n\t\t\t})();\n\t\t},\n\n\t\toverwrite(): void {\n\t\t\tconst { step, busy } = m.snapshot;\n\t\t\tif (busy || step !== 'password' || !target) return;\n\t\t\t// The password is forgotten: stop proving it and START fresh over the\n\t\t\t// protected backup. wipe:true empties local first (fresh sync meta), so\n\t\t\t// this writes a blank new backup - never this device's existing data -\n\t\t\t// and the owner is never stuck behind a lost secret. A blank write is\n\t\t\t// also tiny, so it cannot time out the way pushing a large local store\n\t\t\t// would.\n\t\t\tpassword = null;\n\t\t\tvoid attach(generation, 'replace-remote', 'replaced', true);\n\t\t},\n\n\t\tresolveConflict(how: ConnectResolution): void {\n\t\t\tconst { step, busy } = m.snapshot;\n\t\t\tif (busy || step !== 'conflict') return;\n\t\t\tconst plan = planFor(how);\n\t\t\tvoid attach(generation, plan.strategy, plan.outcome);\n\t\t},\n\n\t\tcancel(): void {\n\t\t\tif (m.snapshot.step === 'connected') return; // done is done\n\t\t\tbackToChoose();\n\t\t},\n\n\t\tretry(): void {\n\t\t\tif (m.snapshot.step !== 'error') return;\n\t\t\tbackToChoose();\n\t\t}\n\t};\n}\n","// shareFlow: the \"who can see this\" panel as a headless machine over an\n// injected ShareEngine - how links travel (Drive public link, relay,\n// mailbox) is the app's business. The flow owns what every such panel gets\n// wrong first: a transient listing failure never blanks it (last-known\n// links stay, flagged stale - a member who saw an empty panel once will\n// revoke something in panic); one operation at a time, so a double-click\n// cannot create two links; removals leave the snapshot only after the\n// engine confirmed them, never optimistically; removing yourself is refused\n// up front (leaving is its own journey, not a row action). Every leg runs\n// under a deadline and reports the stable { code, labelKey, message } shape.\n\nimport type { StoreError } from '../persistence/store';\nimport { makeMachine, toStoreError, withDeadline, type FlowStore } from './machine';\n\nexport type ShareLevel = 'read' | 'write';\n\nexport interface ShareLinkInfo {\n\t/** Engine-scoped stable id (revoke keys on it). */\n\tid: string;\n\t/** The invitation URL to hand out. */\n\turl: string;\n\tlevel: ShareLevel;\n}\n\nexport interface ShareMemberInfo {\n\t/** Engine-scoped stable id (removeMember keys on it). */\n\tid: string;\n\tlabel?: string;\n\t/** This row is the local user. */\n\tself?: boolean;\n\t/** This row owns the share (the app may render a badge, the flow does not care). */\n\towner?: boolean;\n}\n\n/** The app-side port the flow drives. Implementations wrap whatever transport\n * the app shares through; every method may throw (SelfstoreError preferred,\n * anything is normalized). */\nexport interface ShareEngine {\n\t/** The current truth: active links and members. */\n\tlist(): Promise<{ links: ShareLinkInfo[]; members: ShareMemberInfo[] }>;\n\tcreateLink(opts: { level: ShareLevel }): Promise<ShareLinkInfo>;\n\trevokeLink(id: string): Promise<void>;\n\t/** Optional: engines without member management simply omit it. */\n\tremoveMember?(id: string): Promise<void>;\n\t/** Optional: END the whole share in one gesture - every link dead, every\n\t * member out. Engines whose transport has such a move (an invitation to\n\t * kill, a file to re-privatize) expose it; the widget renders the action\n\t * only then. */\n\trevokeAll?(): Promise<void>;\n}\n\nexport type ShareBusy = 'refresh' | 'create' | 'revoke' | 'remove' | 'revoke-all' | null;\n\nexport interface ShareSnapshot {\n\tlinks: readonly ShareLinkInfo[];\n\tmembers: readonly ShareMemberInfo[];\n\t/** The operation in flight, or null. */\n\tbusy: ShareBusy;\n\t/** The last refresh failed: the lists shown are the last-known good ones. */\n\tstale: boolean;\n\t/** The last operation's problem (the lists are never cleared by an error). */\n\terror: StoreError | null;\n\t/** True once the engine offers removeMember (render the row action at all). */\n\tcanRemoveMembers: boolean;\n\t/** True once the engine offers revokeAll (render the end-the-share action). */\n\tcanRevokeAll: boolean;\n}\n\nexport interface ShareFlow extends FlowStore<ShareSnapshot> {\n\t/** Re-list from the engine. Failure keeps the last-known lists (stale). */\n\trefresh(): Promise<void>;\n\t/** Create an invitation link. Resolves to it, or null when refused (an\n\t * operation was already in flight). */\n\tcreateLink(opts: { level: ShareLevel }): Promise<ShareLinkInfo | null>;\n\t/** Revoke a link. The link leaves the snapshot only once the engine\n\t * confirmed. Resolves to whether it did. */\n\trevokeLink(id: string): Promise<boolean>;\n\t/** Remove a member (never yourself - refused up front). Resolves to whether\n\t * the engine confirmed. */\n\tremoveMember(id: string): Promise<boolean>;\n\t/** End the whole share: every link and member leaves the snapshot only\n\t * once the engine confirmed. Resolves to whether it did. */\n\trevokeAll(): Promise<boolean>;\n}\n\nconst DEFAULT_DEADLINE_MS = 30_000;\n\nexport function shareFlow(engine: ShareEngine, options: { deadlineMs?: number } = {}): ShareFlow {\n\tconst deadlineMs = options.deadlineMs ?? DEFAULT_DEADLINE_MS;\n\n\tconst m = makeMachine<ShareSnapshot>({\n\t\tlinks: [],\n\t\tmembers: [],\n\t\tbusy: 'refresh',\n\t\tstale: false,\n\t\terror: null,\n\t\tcanRemoveMembers: typeof engine.removeMember === 'function',\n\t\tcanRevokeAll: typeof engine.revokeAll === 'function'\n\t});\n\n\t/** Serialize the operations: one at a time, the others answer \"refused\". */\n\tfunction begin(op: Exclude<ShareBusy, null>): boolean {\n\t\tif (m.snapshot.busy !== null && !(op === 'refresh' && m.snapshot.busy === 'refresh')) {\n\t\t\treturn false;\n\t\t}\n\t\tm.set({ busy: op });\n\t\treturn true;\n\t}\n\n\tasync function doRefresh(): Promise<void> {\n\t\ttry {\n\t\t\tconst { links, members } = await withDeadline(engine.list(), deadlineMs, 'The share listing');\n\t\t\tm.set({ links, members, busy: null, stale: false, error: null });\n\t\t} catch (e) {\n\t\t\t// Keep the last-known lists: a hiccup must never paint the share as\n\t\t\t// gone. Just say the view may be behind.\n\t\t\tm.set({ busy: null, stale: true, error: toStoreError(e) });\n\t\t}\n\t}\n\n\tconst flow: ShareFlow = {\n\t\tget snapshot() {\n\t\t\treturn m.snapshot;\n\t\t},\n\t\tsubscribe: m.subscribe,\n\n\t\tasync refresh(): Promise<void> {\n\t\t\tif (m.snapshot.busy !== null && m.snapshot.busy !== 'refresh') return;\n\t\t\tm.set({ busy: 'refresh' });\n\t\t\tawait doRefresh();\n\t\t},\n\n\t\tasync createLink(opts): Promise<ShareLinkInfo | null> {\n\t\t\tif (!begin('create')) return null;\n\t\t\ttry {\n\t\t\t\tconst link = await withDeadline(engine.createLink(opts), deadlineMs, 'Creating the link');\n\t\t\t\tm.set({ links: [...m.snapshot.links, link], busy: null, error: null });\n\t\t\t\treturn link;\n\t\t\t} catch (e) {\n\t\t\t\tm.set({ busy: null, error: toStoreError(e) });\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\n\t\tasync revokeLink(id: string): Promise<boolean> {\n\t\t\tif (!begin('revoke')) return false;\n\t\t\ttry {\n\t\t\t\tawait withDeadline(engine.revokeLink(id), deadlineMs, 'Revoking the link');\n\t\t\t\t// Confirmed: NOW it leaves the snapshot.\n\t\t\t\tm.set({ links: m.snapshot.links.filter((l) => l.id !== id), busy: null, error: null });\n\t\t\t\treturn true;\n\t\t\t} catch (e) {\n\t\t\t\tm.set({ busy: null, error: toStoreError(e) });\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync removeMember(id: string): Promise<boolean> {\n\t\t\tconst remove = engine.removeMember?.bind(engine);\n\t\t\tif (!remove) {\n\t\t\t\tthrow new TypeError('shareFlow: this engine does not manage members (no removeMember).');\n\t\t\t}\n\t\t\tconst row = m.snapshot.members.find((mb) => mb.id === id);\n\t\t\tif (row?.self) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t'shareFlow: refusing to remove yourself - leaving a share is its own journey, not a row action.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!begin('remove')) return false;\n\t\t\ttry {\n\t\t\t\tawait withDeadline(remove(id), deadlineMs, 'Removing the member');\n\t\t\t\tm.set({\n\t\t\t\t\tmembers: m.snapshot.members.filter((mb) => mb.id !== id),\n\t\t\t\t\tbusy: null,\n\t\t\t\t\terror: null\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t} catch (e) {\n\t\t\t\tm.set({ busy: null, error: toStoreError(e) });\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync revokeAll(): Promise<boolean> {\n\t\t\tconst revoke = engine.revokeAll?.bind(engine);\n\t\t\tif (!revoke) {\n\t\t\t\tthrow new TypeError('shareFlow: this engine does not end the share (no revokeAll).');\n\t\t\t}\n\t\t\tif (!begin('revoke-all')) return false;\n\t\t\ttry {\n\t\t\t\tawait withDeadline(revoke(), deadlineMs, 'Ending the share');\n\t\t\t\t// Confirmed: the share is over, every link and member with it.\n\t\t\t\tm.set({ links: [], members: [], busy: null, error: null });\n\t\t\t\treturn true;\n\t\t\t} catch (e) {\n\t\t\t\tm.set({ busy: null, error: toStoreError(e) });\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t};\n\n\t// The panel opens on the truth: list right away (failures land as stale).\n\tvoid doRefresh();\n\n\treturn flow;\n}\n","// joinFlow: opening an invitation link, as a headless machine over an\n// injected JoinEngine. Preview first, join on an explicit yes. The flow\n// holds the link itself, so a re-render, a login roundtrip or an account\n// switch cannot lose the invitation out from under the user. Joining is\n// single-flight. Mismatch (\"this device already follows another share\") and\n// no-invite (\"spent, or not for this account\") are outcomes with their own\n// steps, not generic errors - each has a different way out. Switching\n// accounts re-previews under the new account. A cancelled or superseded leg\n// cannot resurrect the flow, and every network leg runs under a deadline.\n\nimport type { StoreError } from '../persistence/store';\nimport { makeMachine, toStoreError, withDeadline, type FlowStore } from './machine';\nimport type { ShareLevel } from './share';\n\n/** What the user is about to join - enough to render an honest question. */\nexport interface JoinPreview {\n\t/** The share's display name, when the link carries one. */\n\tlabel?: string;\n\t/** Who shared it (a name, an email - whatever the engine knows). */\n\tfrom?: string;\n\tlevel?: ShareLevel;\n}\n\n/** How joining ended, other than plain failure:\n * 'joined' - this device now follows the share.\n * 'mismatch' - this device already follows a DIFFERENT share: joining a\n * second one is refused (leave the first, or use another\n * device/profile).\n * 'no-invite' - the invitation is spent, expired, or aimed at another\n * account (switching accounts may be the fix). */\nexport type JoinOutcome = 'joined' | 'mismatch' | 'no-invite';\n\n/** The app-side port: how a link is read and honoured on this transport. */\nexport interface JoinEngine {\n\t/** Read-only look at the invitation. Must change NOTHING. */\n\tpreview(link: string): Promise<JoinPreview>;\n\t/** Consume the invitation and wire the share. Resolve null when the user\n\t * backed out of a popup the engine had to open (an account chooser, a\n\t * consent screen): the flow returns to 'ready' silently - backing out of\n\t * a human gesture is not an error, here as everywhere in these flows. */\n\tjoin(link: string): Promise<JoinOutcome | null>;\n\t/** Optional: re-run the account chooser (the invite may belong to another\n\t * account). The flow re-previews after it. */\n\tswitchAccount?(): Promise<void>;\n}\n\nexport type JoinStep =\n\t'previewing' | 'ready' | 'joining' | 'joined' | 'mismatch' | 'no-invite' | 'error';\n\nexport interface JoinSnapshot {\n\t/** The invitation this flow was opened with - held here so the UI can\n\t * always find it again. */\n\tlink: string;\n\tstep: JoinStep;\n\t/** Set once previewed (kept through errors, so retry re-renders context). */\n\tpreview: JoinPreview | null;\n\t/** The engine offers an account switch. */\n\tcanSwitchAccount: boolean;\n\tbusy: boolean;\n\t/** Set when step === 'error': show `labelKey`, log `message`. */\n\terror: StoreError | null;\n}\n\nexport interface JoinFlow extends FlowStore<JoinSnapshot> {\n\t/** Say yes: consume the invitation. Only from 'ready'. */\n\taccept(): void;\n\t/** Re-run the account chooser, then preview again under the new account.\n\t * Available from 'ready', 'no-invite' and 'error' when the engine offers it. */\n\tswitchAccount(): void;\n\t/** From 'error': preview again and resume the journey. */\n\tretry(): void;\n}\n\nconst DEFAULT_DEADLINE_MS = 30_000;\n\nexport function joinFlow(\n\tlink: string,\n\tengine: JoinEngine,\n\toptions: { deadlineMs?: number } = {}\n): JoinFlow {\n\tconst deadlineMs = options.deadlineMs ?? DEFAULT_DEADLINE_MS;\n\n\tconst m = makeMachine<JoinSnapshot>({\n\t\tlink,\n\t\tstep: 'previewing',\n\t\tpreview: null,\n\t\tcanSwitchAccount: typeof engine.switchAccount === 'function',\n\t\tbusy: true,\n\t\terror: null\n\t});\n\n\tlet generation = 0;\n\n\tfunction preview(): void {\n\t\tconst gen = ++generation;\n\t\tm.set({ step: 'previewing', busy: true, error: null });\n\t\tvoid withDeadline(engine.preview(link), deadlineMs, 'The invitation')\n\t\t\t.then((p) => {\n\t\t\t\tif (gen !== generation) return;\n\t\t\t\tm.set({ step: 'ready', preview: p, busy: false });\n\t\t\t})\n\t\t\t.catch((e) => {\n\t\t\t\tif (gen !== generation) return;\n\t\t\t\tm.set({ step: 'error', busy: false, error: toStoreError(e) });\n\t\t\t});\n\t}\n\n\tpreview();\n\n\treturn {\n\t\tget snapshot() {\n\t\t\treturn m.snapshot;\n\t\t},\n\t\tsubscribe: m.subscribe,\n\n\t\taccept(): void {\n\t\t\tconst { step, busy } = m.snapshot;\n\t\t\tif (busy || step !== 'ready') return; // single-flight: one join per yes\n\t\t\tconst gen = ++generation;\n\t\t\tm.set({ step: 'joining', busy: true, error: null });\n\t\t\tvoid withDeadline(engine.join(link), deadlineMs, 'Joining')\n\t\t\t\t.then((outcome) => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tif (outcome === null) {\n\t\t\t\t\t\t// The user backed out of the engine's popup: the question is\n\t\t\t\t\t\t// still live, the preview still good - just ask again.\n\t\t\t\t\t\tm.set({ step: 'ready', busy: false });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tm.set({ step: outcome, busy: false });\n\t\t\t\t})\n\t\t\t\t.catch((e) => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tm.set({ step: 'error', busy: false, error: toStoreError(e) });\n\t\t\t\t});\n\t\t},\n\n\t\tswitchAccount(): void {\n\t\t\tconst switcher = engine.switchAccount?.bind(engine);\n\t\t\tif (!switcher) return;\n\t\t\tconst { step, busy } = m.snapshot;\n\t\t\tif (busy || (step !== 'ready' && step !== 'no-invite' && step !== 'error')) return;\n\t\t\tconst gen = ++generation;\n\t\t\tm.set({ busy: true, error: null });\n\t\t\tvoid switcher()\n\t\t\t\t.then(() => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tpreview(); // the other account may hold the right invite: look again\n\t\t\t\t})\n\t\t\t\t.catch((e) => {\n\t\t\t\t\tif (gen !== generation) return;\n\t\t\t\t\tm.set({ step: 'error', busy: false, error: toStoreError(e) });\n\t\t\t\t});\n\t\t},\n\n\t\tretry(): void {\n\t\t\tif (m.snapshot.step !== 'error') return;\n\t\t\tpreview();\n\t\t}\n\t};\n}\n"]}