selfstore 1.8.0 → 1.8.2

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 (47) hide show
  1. package/README.md +6 -1
  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 +2 -2
  6. package/dist/{cache-lock-7D6N42ZP.js → cache-lock-RCN3JJ4Q.js} +4 -4
  7. package/dist/{cache-lock-7D6N42ZP.js.map → cache-lock-RCN3JJ4Q.js.map} +1 -1
  8. package/dist/{chunk-CT2HTWA7.js → chunk-453KRCMM.js} +4 -4
  9. package/dist/{chunk-CT2HTWA7.js.map → chunk-453KRCMM.js.map} +1 -1
  10. package/dist/{chunk-XBPJRUA3.js → chunk-5NS7YQNP.js} +18 -10
  11. package/dist/chunk-5NS7YQNP.js.map +1 -0
  12. package/dist/{chunk-ZV2S3I76.js → chunk-7N2YR3QW.js} +31 -10
  13. package/dist/chunk-7N2YR3QW.js.map +1 -0
  14. package/dist/{chunk-ZDHTKFAL.js → chunk-BNDFMU3J.js} +6 -6
  15. package/dist/{chunk-ZDHTKFAL.js.map → chunk-BNDFMU3J.js.map} +1 -1
  16. package/dist/{chunk-SFF7KKM4.js → chunk-CPN2KUD5.js} +2 -2
  17. package/dist/chunk-CPN2KUD5.js.map +1 -0
  18. package/dist/{chunk-53WWPEML.js → chunk-HDR75TQ7.js} +3 -3
  19. package/dist/{chunk-53WWPEML.js.map → chunk-HDR75TQ7.js.map} +1 -1
  20. package/dist/{chunk-CM3HSBCE.js → chunk-HK4VPO65.js} +3 -3
  21. package/dist/{chunk-CM3HSBCE.js.map → chunk-HK4VPO65.js.map} +1 -1
  22. package/dist/{chunk-OZS7BSC2.js → chunk-JMJZIZKY.js} +19 -6
  23. package/dist/chunk-JMJZIZKY.js.map +1 -0
  24. package/dist/{chunk-OIAXYI35.js → chunk-U5F4GI7C.js} +3 -3
  25. package/dist/{chunk-OIAXYI35.js.map → chunk-U5F4GI7C.js.map} +1 -1
  26. package/dist/{drive-DF08V8-L.d.ts → drive-l_4-m1eT.d.ts} +1 -1
  27. package/dist/{flows-dwgDgv6_.d.ts → flows-C_uookek.d.ts} +2 -2
  28. package/dist/flows.d.ts +3 -3
  29. package/dist/flows.js +8 -8
  30. package/dist/groups.js +4 -4
  31. package/dist/households.d.ts +1 -1
  32. package/dist/index.d.ts +4 -4
  33. package/dist/index.js +21 -12
  34. package/dist/index.js.map +1 -1
  35. package/dist/local-2YREU4Q2.js +7 -0
  36. package/dist/{local-5QN7V24I.js.map → local-2YREU4Q2.js.map} +1 -1
  37. package/dist/{local-ipQv_Pbv.d.ts → local-bfv4Ld7s.d.ts} +2 -2
  38. package/dist/{store-CbGrlMME.d.ts → store-BiQ-BuVl.d.ts} +8 -2
  39. package/dist/widgets.d.ts +3 -3
  40. package/dist/widgets.js +11 -9
  41. package/dist/widgets.js.map +1 -1
  42. package/package.json +2 -2
  43. package/dist/chunk-OZS7BSC2.js.map +0 -1
  44. package/dist/chunk-SFF7KKM4.js.map +0 -1
  45. package/dist/chunk-XBPJRUA3.js.map +0 -1
  46. package/dist/chunk-ZV2S3I76.js.map +0 -1
  47. package/dist/local-5QN7V24I.js +0 -7
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/selfstore/archive.ts","../src/selfstore/box.ts","../src/selfstore/types.ts","../src/selfstore/password-policy.ts","../src/selfstore/index.ts","../src/selfstore/verify.ts","../src/selfstore/fluent.ts"],"names":["utf8"],"mappings":";;;;;AAQA,IAAM,QAAA,GAAW,gBAAA;AAGjB,IAAM,OAAA,GAAU,WAAA;AAChB,IAAM,eAAA,GAAkB,CAAA;AAKjB,IAAM,eAAA,GAAkB,MAAM,IAAA,GAAO,IAAA;AACrC,IAAM,eAAA,GAAkB,OAAO,IAAA,GAAO,IAAA;AAE7C,IAAM,IAAA,GAAO,EAAE,GAAA,EAAK,IAAI,aAAY,EAAG,GAAA,EAAK,IAAI,WAAA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D,CAAA;AAEO,IAAM,iBAAN,MAAqB;AAAA,EAG3B,YAA6B,KAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAAA,EAA2B;AAAA,EAA3B,KAAA;AAAA,EAFrB,QAAA;AAAA;AAAA,EAKR,aAAa,QAAA,EAAyB;AACrC,IAAA,IAAA,CAAK,WAAW,QAAA,IAAY,MAAA;AAC5B,IAAA,OAAO,IAAA;AAAA,EACR;AAAA;AAAA,EAGA,MAAM,IAAA,GAAwB;AAC7B,IAAA,OAAO,WAAA,CAAY,MAAM,OAAA,CAAQ,IAAA,CAAK,KAAK,CAAC,CAAA;AAAA,EAC7C;AAAA;AAAA,EAGA,MAAM,WAAA,GAAgC;AACrC,IAAA,OAAA,CAAQ,MAAM,IAAA,CAAK,IAAA,EAAK,EAAG,UAAA,KAAe,MAAA;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,IAAA,GAA0B;AAC/B,IAAA,MAAM,IAAA,GAAO,MAAM,OAAA,CAAQ,MAAM,QAAQ,IAAA,CAAK,KAAK,CAAA,EAAG,IAAA,CAAK,QAAQ,CAAA;AACnE,IAAA,MAAM,cAAc,MAAA,CAAO,WAAA;AAAA,MAC1B,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,WAAW,CAAA,CAAE,MAAA;AAAA,QAChC,CAAC,CAAC,IAAI,MAAM,CAAC,IAAA,CAAK,WAAW,0BAA0B;AAAA;AACxD,KACD;AACA,IAAA,OAAO,EAAE,WAAA,EAAa,KAAA,EAAO,IAAA,CAAK,KAAA,EAAM;AAAA,EACzC;AACD,CAAA","file":"chunk-ZDHTKFAL.js","sourcesContent":["// The inner archive: a JSON manifest (selfstore.json) plus one entry per\n// binary file, as a plain ZIP. Encrypted backups wrap these same bytes in\n// AES-GCM (box.ts). fflate is imported dynamically - only needed at\n// export/import time.\n\nimport type { Snapshot, SnapshotFile } from './types';\nimport { SelfstoreError } from './errors';\n\nconst MANIFEST = 'selfstore.json';\n// Opaque caller bookkeeping (createLocalStore's schema version + merge\n// metadata). Its own entry, so the manifest holds nothing but app data.\nconst SIDECAR = 'sync.json';\nconst ARCHIVE_VERSION = 1;\n\n// Zip-bomb guards. Backups are user data measured in MB; half a GiB per\n// entry and 1 GiB total are far above legitimate use and bound worst-case\n// inflation (many individually-legal entries must not add up to a bomb).\nexport const MAX_ENTRY_BYTES = 512 * 1024 * 1024;\nexport const MAX_TOTAL_BYTES = 1024 * 1024 * 1024;\n\nconst utf8 = { enc: new TextEncoder(), dec: new TextDecoder() };\n\ninterface FileMeta {\n\tid: string;\n\tname: string;\n\tmime: string;\n}\n\n/**\n * ZIP a set of named entries. `level` applies to the JSON entries; file\n * attachments are stored uncompressed - photos and PDFs are usually already\n * compressed, and re-deflating them was the biggest chunk of per-save\n * main-thread time for near-zero size gain. Still a plain readable ZIP.\n */\nexport async function zip(\n\tentries: Record<string, Uint8Array>,\n\tlevel: 0 | 6 = 6\n): Promise<Uint8Array> {\n\tconst { zipSync } = await import('fflate');\n\tconst input: Record<string, Uint8Array | [Uint8Array, { level: 0 }]> = {};\n\tfor (const [name, bytes] of Object.entries(entries)) {\n\t\tinput[name] = level !== 0 && name.startsWith('files/') ? [bytes, { level: 0 }] : bytes;\n\t}\n\treturn zipSync(input as Parameters<typeof zipSync>[0], { level });\n}\n\n/** Unzip to named entries. BAD_FORMAT on unreadable bytes, TOO_LARGE past the bomb guards. */\nexport async function unzip(\n\tbytes: Uint8Array,\n\tmaxEntryBytes: number = MAX_ENTRY_BYTES,\n\tmaxTotalBytes: number = MAX_TOTAL_BYTES\n): Promise<Record<string, Uint8Array>> {\n\tconst { unzipSync } = await import('fflate');\n\tlet total = 0;\n\ttry {\n\t\treturn unzipSync(bytes, {\n\t\t\tfilter: (f) => {\n\t\t\t\tif (f.originalSize > maxEntryBytes) {\n\t\t\t\t\tthrow new SelfstoreError('TOO_LARGE', `Archive entry \"${f.name}\" is too large.`);\n\t\t\t\t}\n\t\t\t\ttotal += f.originalSize;\n\t\t\t\tif (total > maxTotalBytes) {\n\t\t\t\t\tthrow new SelfstoreError('TOO_LARGE', 'Archive total size exceeds the guard.');\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t});\n\t} catch (e) {\n\t\tif (e instanceof SelfstoreError) throw e;\n\t\tthrow new SelfstoreError('BAD_FORMAT', 'Unreadable archive.');\n\t}\n}\n\n/** Manifest + file entries for a snapshot; `sidecar` rides its own sync.json entry. */\nexport function buildEntries(snap: Snapshot, sidecar?: unknown): Record<string, Uint8Array> {\n\tconst entries: Record<string, Uint8Array> = {};\n\tentries[MANIFEST] = utf8.enc.encode(\n\t\tJSON.stringify({\n\t\t\tversion: ARCHIVE_VERSION,\n\t\t\tcollections: snap.collections,\n\t\t\tfiles: snap.files.map(({ id, name, mime }): FileMeta => ({ id, name, mime }))\n\t\t})\n\t);\n\tif (sidecar !== undefined && sidecar !== null) {\n\t\tentries[SIDECAR] = utf8.enc.encode(JSON.stringify(sidecar));\n\t}\n\tfor (const f of snap.files) entries[`files/${f.id}`] = f.bytes;\n\treturn entries;\n}\n\n/** The sync.json sidecar if present, else null. Unreadable content reads as absent. */\nexport function readSidecar(entries: Record<string, Uint8Array>): unknown {\n\tconst bytes = entries[SIDECAR];\n\tif (!bytes) return null;\n\ttry {\n\t\treturn JSON.parse(utf8.dec.decode(bytes));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Rebuild a snapshot from ZIP entries (the inverse of buildEntries). */\nexport function entriesToSnapshot(entries: Record<string, Uint8Array>): Snapshot {\n\tconst manifestBytes = entries[MANIFEST];\n\tif (!manifestBytes) throw new SelfstoreError('BAD_FORMAT', 'Missing manifest.');\n\tconst manifest = JSON.parse(utf8.dec.decode(manifestBytes)) as {\n\t\tcollections?: Record<string, unknown[]>;\n\t\tfiles?: FileMeta[];\n\t};\n\tconst files: SnapshotFile[] = (manifest.files ?? []).map((m) => ({\n\t\t...m,\n\t\tbytes: entries[`files/${m.id}`] ?? new Uint8Array()\n\t}));\n\treturn { collections: manifest.collections ?? {}, files };\n}\n\n/** Pack a snapshot (plus an optional opaque sidecar) into ZIP bytes. */\nexport async function pack(snap: Snapshot, sidecar?: unknown): Promise<Uint8Array> {\n\treturn zip(buildEntries(snap, sidecar), 6);\n}\n\n/** Unpack ZIP bytes into a snapshot plus its sidecar (null when absent). */\nexport async function unpackWithSidecar(\n\tzipBytes: Uint8Array\n): Promise<{ snapshot: Snapshot; sidecar: unknown }> {\n\tconst entries = await unzip(zipBytes);\n\treturn { snapshot: entriesToSnapshot(entries), sidecar: readSidecar(entries) };\n}\n","// The portable backup container - a real ZIP in both cases, never a mystery\n// blob:\n//\n// unencrypted: meta.json + selfstore.json + files/* (browsable, format 1)\n// encrypted: meta.json + data.enc + LISEZMOI.txt (AES-256-GCM / Argon2id)\n//\n// Encrypted means the password envelope (format 3): a random data key seals\n// the inner ZIP, wrapped once per password in keys[], and the exact meta.json\n// bytes ride as GCM AAD so the slot table is tamper-evident. Format 2 is the\n// passwordless group variant. Anything else is refused.\n\nimport type { Snapshot, Header, EncodeOptions, PasswordSlot, ExternalSlot, KeySlot } from './types';\nimport {\n\tbuildEntries,\n\tentriesToSnapshot,\n\treadSidecar,\n\tpack,\n\tunpackWithSidecar,\n\tzip,\n\tunzip\n} from './archive';\nimport {\n\tmintSlot,\n\topenSlot,\n\topenExternalSlot,\n\tMAX_KEY_SLOTS,\n\tgcmSealAad,\n\tgcmOpenAad,\n\ttoBase64,\n\tfromBase64\n} from './crypto';\nimport {\n\tGROUP_KEYING,\n\tgcmSealRaw,\n\tgcmOpenRaw,\n\tsealDataKey,\n\topenDataKey,\n\tsignBox,\n\tverifyBox,\n\ttype GroupIdentity\n} from './group';\nimport { SelfstoreError } from './errors';\n\n// Genuine ZIPs get the honest extension.\nexport const BACKUP_EXTENSION = '.zip';\nexport const BACKUP_MIME = 'application/zip';\n\nconst META = 'meta.json';\nconst DATA = 'data.enc';\nconst SIG = 'sig.bin';\nconst README = 'LISEZMOI.txt';\n\n// Format identifier, which is also the discriminant: 1 plain ZIP, 2 group\n// mode, 3 authenticated password envelope (header bound as GCM AAD). These are\n// fixed wire ids; anything else is refused.\nconst BOX_FORMAT_PLAIN = 1;\nconst BOX_FORMAT_GROUP = 2;\nconst BOX_FORMAT_ENVELOPE_AUTH = 3;\n\nconst ZIP_MAGIC = [0x50, 0x4b, 0x03, 0x04]; // \"PK\\x03\\x04\"\n\nconst utf8 = { enc: new TextEncoder(), dec: new TextDecoder() };\n\n// Shipped inside encrypted backups for whoever opens the ZIP by hand. ASCII\n// only so it renders in any viewer; apps brand it via EncodeOptions.readme.\nconst DEFAULT_README =\n\t'Encrypted backup / Sauvegarde chiffree\\n\\n' +\n\t'This is a valid ZIP archive.\\n' +\n\t'\"data.enc\" holds your encrypted data (AES-256-GCM, key derived with Argon2id);\\n' +\n\t'\"meta.json\" holds the decryption parameters (cleartext).\\n' +\n\t'To read it, import this file into the application that created it\\n' +\n\t'(named in meta.json) with your password.\\n\\n' +\n\t'Ce fichier est une archive ZIP valide.\\n' +\n\t'\"data.enc\" contient vos donnees chiffrees (AES-256-GCM, cle derivee par Argon2id) ;\\n' +\n\t'\"meta.json\" contient les parametres de dechiffrement (en clair).\\n' +\n\t\"Pour la lire, importez ce fichier dans l'application qui l'a creee\\n\" +\n\t'(nommee dans meta.json) avec votre mot de passe.\\n';\n\n/** Coerce an accepted input (a picked File, a fetched Blob, raw bytes) to bytes. */\nexport async function asBytes(input: Blob | Uint8Array): Promise<Uint8Array> {\n\treturn input instanceof Uint8Array ? input : new Uint8Array(await input.arrayBuffer());\n}\n\nfunction startsWith(bytes: Uint8Array, magic: number[]): boolean {\n\treturn bytes.length >= magic.length && magic.every((b, i) => bytes[i] === b);\n}\n\n// An unknown cipher or per-slot KDF means a newer writer: UNSUPPORTED_VERSION,\n// not a misleading DECRYPT_FAILED from feeding foreign params to AES-GCM.\nfunction assertKnownCrypto(header: Header): void {\n\tif (header.encryption !== 'none' && header.encryption !== 'aes-256-gcm') {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Encryption \"${header.encryption}\" is newer than this reader supports.`\n\t\t);\n\t}\n\tif (header.keying !== undefined && header.keying !== GROUP_KEYING) {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Key envelope \"${header.keying}\" is newer than this reader supports.`\n\t\t);\n\t}\n\tfor (const slot of header.keys ?? []) {\n\t\t// External slots carry no KDF (KEK comes from the caller's secret).\n\t\tif (!slot || (slot as ExternalSlot).kind === 'external') continue;\n\t\tif ((slot as PasswordSlot).kdf?.algo !== 'argon2id') {\n\t\t\tthrow new SelfstoreError(\n\t\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t\t`Key derivation \"${(slot as PasswordSlot).kdf?.algo}\" is newer than this reader supports.`\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Serialize a snapshot to backup bytes. The optional `sidecar`\n * (createLocalStore's bookkeeping) rides its own sync.json entry - inside the\n * envelope when encrypting, so it never leaks in cleartext.\n */\nexport async function writeBox(\n\tsnapshot: Snapshot,\n\topts: EncodeOptions,\n\tsidecar?: unknown\n): Promise<Uint8Array> {\n\tconst header: Header = {\n\t\tformat: BOX_FORMAT_PLAIN,\n\t\tapp: opts.app,\n\t\tappVersion: opts.appVersion,\n\t\tschemaVersion: opts.schemaVersion,\n\t\tcreatedAt: new Date().toISOString(),\n\t\tencryption: 'none'\n\t};\n\n\tif (opts.group) {\n\t\tif (opts.password) {\n\t\t\tthrow new TypeError('writeBox(): `group` and `password` are mutually exclusive.');\n\t\t}\n\t\t// Fresh data key enveloped once per recipient; the author's signature\n\t\t// covers the exact meta.json + data.enc bytes, so nothing a reader\n\t\t// trusts (recipients, author claim, iv, ciphertext) can be altered.\n\t\tconst dataKey = crypto.getRandomValues(new Uint8Array(32));\n\t\tconst enc = await gcmSealRaw(dataKey, await pack(snapshot, sidecar));\n\t\tconst meta: Header = {\n\t\t\t...header,\n\t\t\tformat: BOX_FORMAT_GROUP,\n\t\t\tencryption: 'aes-256-gcm',\n\t\t\tkeying: GROUP_KEYING,\n\t\t\tauthor: opts.group.sign.pub,\n\t\t\trecipients: await sealDataKey(dataKey, opts.group.recipients),\n\t\t\tiv: enc.iv\n\t\t};\n\t\tconst metaBytes = utf8.enc.encode(JSON.stringify(meta));\n\t\treturn zip(\n\t\t\t{\n\t\t\t\t[META]: metaBytes,\n\t\t\t\t[DATA]: enc.ciphertext,\n\t\t\t\t[SIG]: await signBox(metaBytes, enc.ciphertext, opts.group.sign.priv),\n\t\t\t\t[README]: utf8.enc.encode(opts.readme || DEFAULT_README)\n\t\t\t},\n\t\t\t0\n\t\t);\n\t}\n\n\tif (opts.envelope && opts.password) {\n\t\tthrow new TypeError('writeBox(): `envelope` and `password` are mutually exclusive.');\n\t}\n\n\tif (opts.envelope || opts.password) {\n\t\t// A rewrite passes `envelope` (held data key + carried slot table) so a\n\t\t// writer that knows only one password preserves every other slot; a\n\t\t// plain `password` mints a fresh single-slot envelope, i.e. a data-key\n\t\t// rotation - that is what makes setEncryption actually revoke.\n\t\t// The iv is minted before meta.json is serialized so it sits inside the\n\t\t// AAD; seal and open then agree on the exact header bytes.\n\t\tconst dataKey = opts.envelope?.dataKey ?? crypto.getRandomValues(new Uint8Array(32));\n\t\t// Every extra secret gets its own slot around the SAME data key: either\n\t\t// one opens the file, and neither can be derived from the other. A rewrite\n\t\t// (`envelope`) already carries the slot table, so extras only apply when\n\t\t// minting a fresh envelope.\n\t\tconst slots = opts.envelope?.slots ?? [\n\t\t\tawait mintSlot(opts.password!, dataKey),\n\t\t\t...(await Promise.all((opts.extraSecrets ?? []).map((s) => mintSlot(s, dataKey))))\n\t\t];\n\t\tif (slots.length === 0 || slots.length > MAX_KEY_SLOTS) {\n\t\t\tthrow new TypeError(`writeBox(): between 1 and ${MAX_KEY_SLOTS} password slots.`);\n\t\t}\n\t\tconst iv = crypto.getRandomValues(new Uint8Array(12));\n\t\tconst meta: Header = {\n\t\t\t...header,\n\t\t\tformat: BOX_FORMAT_ENVELOPE_AUTH,\n\t\t\tencryption: 'aes-256-gcm',\n\t\t\tkeys: slots,\n\t\t\tiv: toBase64(iv)\n\t\t};\n\t\tconst metaBytes = utf8.enc.encode(JSON.stringify(meta));\n\t\tconst ciphertext = await gcmSealAad(dataKey, iv, await pack(snapshot, sidecar), metaBytes);\n\t\treturn zip(\n\t\t\t{\n\t\t\t\t[META]: metaBytes,\n\t\t\t\t[DATA]: ciphertext,\n\t\t\t\t[README]: utf8.enc.encode(opts.readme || DEFAULT_README)\n\t\t\t},\n\t\t\t0\n\t\t);\n\t}\n\n\t// The file is the browsable archive: manifest + files (+ sync.json), plus meta.json.\n\tconst entries = buildEntries(snapshot, sidecar);\n\tentries[META] = utf8.enc.encode(JSON.stringify(header));\n\treturn zip(entries, 6);\n}\n\n/** Read the cleartext metadata (app, date, whether encrypted) without decrypting. */\nexport async function readBoxMeta(bytes: Uint8Array): Promise<Header> {\n\tif (!startsWith(bytes, ZIP_MAGIC)) {\n\t\tthrow new SelfstoreError(\n\t\t\t'BAD_FORMAT',\n\t\t\t'Not a selfstore backup: expected a ZIP. Pass the exact bytes/Blob produced by ' +\n\t\t\t\t'backup().toBlob() / exportSnapshot(), not a decoded object.'\n\t\t);\n\t}\n\treturn metaOf(await unzip(bytes));\n}\n\n/**\n * Group-mode read inputs: the reader's identity and the trusted author keys\n * (manifest members' Ed25519 publics). `authors` is mandatory - a valid\n * signature over an attacker-chosen author proves nothing (SPEC.md 12.6), so\n * there is no \"decrypt without checking who signed\" mode.\n */\nexport interface GroupReadOptions {\n\tidentity: Pick<GroupIdentity, 'encPub' | 'encPriv'>;\n\tauthors: string[];\n}\n\n/**\n * Key material captured at read time: the data key that opened the file plus\n * the slot table verbatim. Carried into rewrites so a session that knows only\n * one key preserves every slot.\n */\nexport interface BoxEnvelope {\n\tdataKey: Uint8Array;\n\tslots: KeySlot[];\n}\n\n/**\n * App-supplied secret fetch for an external-key slot (the WebAuthn/hardware\n * exchange lives app-side). Return null to skip the slot (wrong key, user\n * cancelled).\n */\nexport type ExternalKeyResolver = (slot: ExternalSlot) => Promise<Uint8Array | null>;\n\n/**\n * Read a backup into a snapshot plus its sync.json sidecar (null when the\n * file carries none). Group copies need `group` and return the verified\n * author; envelope copies accept a held `dataKey` (KDF-free re-read) and\n * return the envelope for later rewrites.\n */\nexport async function readBoxWithSync(\n\tbytes: Uint8Array,\n\tpassword?: string,\n\tgroup?: GroupReadOptions,\n\tdataKey?: Uint8Array,\n\texternalResolver?: ExternalKeyResolver\n): Promise<{\n\tsnapshot: Snapshot;\n\tsidecar: unknown;\n\tauthor?: string;\n\tenvelope?: BoxEnvelope;\n\tformat: number;\n}> {\n\tconst entries = await unzip(bytes);\n\tconst meta = metaOf(entries);\n\tconst format = meta.format ?? BOX_FORMAT_PLAIN;\n\tif (\n\t\tformat !== BOX_FORMAT_PLAIN &&\n\t\tformat !== BOX_FORMAT_GROUP &&\n\t\tformat !== BOX_FORMAT_ENVELOPE_AUTH\n\t) {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Backup format ${format} is not supported by this reader.`\n\t\t);\n\t}\n\t// Bind security mode to format generation both ways, so neither `keying`\n\t// nor `format` can be stripped to route a box down the wrong path.\n\tif ((format === BOX_FORMAT_GROUP) !== !!meta.keying) {\n\t\tthrow new SelfstoreError(\n\t\t\t'BAD_FORMAT',\n\t\t\t'Group mode (format 2) and the keying field must agree.'\n\t\t);\n\t}\n\tif ((format === BOX_FORMAT_ENVELOPE_AUTH) !== Array.isArray(meta.keys)) {\n\t\tthrow new SelfstoreError(\n\t\t\t'BAD_FORMAT',\n\t\t\t'Password envelope (format 3) and the keys field must agree.'\n\t\t);\n\t}\n\tif (meta.keying) return { ...(await readGroupBox(entries, meta, group)), format };\n\tif (format === BOX_FORMAT_ENVELOPE_AUTH) {\n\t\treturn {\n\t\t\t...(await readEnvelopeBox(entries, meta, password, dataKey, externalResolver)),\n\t\t\tformat\n\t\t};\n\t}\n\tif (meta.encryption === 'none') {\n\t\treturn { snapshot: entriesToSnapshot(entries), sidecar: readSidecar(entries), format };\n\t}\n\t// Encrypted content in a container claiming the plain format: never written\n\t// by this library. Refuse cleanly rather than half-read.\n\tthrow new SelfstoreError('BAD_FORMAT', 'Encrypted content in a plain-format container.');\n}\n\n// Envelope read path: bounds first, the held data key as a KDF-free fast\n// path, then one trial per slot. All slots failing is DECRYPT_FAILED - wrong\n// key and tampering stay one case.\nasync function readEnvelopeBox(\n\tentries: Record<string, Uint8Array>,\n\tmeta: Header,\n\tpassword?: string,\n\tdataKey?: Uint8Array,\n\texternalResolver?: ExternalKeyResolver\n): Promise<{ snapshot: Snapshot; sidecar: unknown; envelope: BoxEnvelope }> {\n\tconst dataEnc = entries[DATA];\n\tconst metaBytes = entries[META];\n\tconst slots = meta.keys;\n\tif (\n\t\t!dataEnc ||\n\t\t!metaBytes ||\n\t\t!Array.isArray(slots) ||\n\t\tslots.length === 0 ||\n\t\ttypeof meta.iv !== 'string' ||\n\t\tmeta.encryption !== 'aes-256-gcm'\n\t) {\n\t\tthrow new SelfstoreError('BAD_FORMAT', 'Missing or malformed envelope entries or parameters.');\n\t}\n\tif (slots.length > MAX_KEY_SLOTS) {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Backup declares ${slots.length} key slots; this reader caps at ${MAX_KEY_SLOTS} ` +\n\t\t\t\t'(each password slot is one memory-hard trial).'\n\t\t);\n\t}\n\t// The exact meta.json bytes are bound as GCM AAD: a tampered header (an\n\t// altered slot table, a swapped KDF) fails the decrypt instead of opening.\n\tconst aad = metaBytes;\n\tconst iv = fromBase64(meta.iv);\n\t// A caller re-reading its own file skips the KDF entirely. On failure fall\n\t// through to the slot trials - another device may have rotated the key.\n\tif (dataKey) {\n\t\ttry {\n\t\t\tconst r = await unpackWithSidecar(await gcmOpenAad(dataKey, iv, dataEnc, aad));\n\t\t\treturn { ...r, envelope: { dataKey, slots } };\n\t\t} catch {\n\t\t\t/* rotated, foreign, or tampered file: the slot path decides */\n\t\t}\n\t}\n\tif (!password && !externalResolver) {\n\t\tthrow new SelfstoreError(\n\t\t\t'PASSWORD_REQUIRED',\n\t\t\t'This backup is encrypted. Provide the password, or the external key (e.g. a passkey), to open it.'\n\t\t);\n\t}\n\tfor (const slot of slots) {\n\t\tlet opened: Uint8Array | null = null;\n\t\tif ((slot as ExternalSlot).kind === 'external') {\n\t\t\tif (externalResolver) {\n\t\t\t\tconst secret = await externalResolver(slot as ExternalSlot);\n\t\t\t\tif (secret) opened = await openExternalSlot(slot as ExternalSlot, secret);\n\t\t\t}\n\t\t} else if (password) {\n\t\t\topened = await openSlot(slot as PasswordSlot, password);\n\t\t}\n\t\tif (!opened) continue;\n\t\t// Every slot wraps the same data key, so if the decrypt below fails\n\t\t// (header tamper surfaces here on format 3) trying another slot gains\n\t\t// nothing - let it throw.\n\t\tconst r = await unpackWithSidecar(await gcmOpenAad(opened, iv, dataEnc, aad));\n\t\treturn { ...r, envelope: { dataKey: opened, slots } };\n\t}\n\tthrow new SelfstoreError(\n\t\t'DECRYPT_FAILED',\n\t\t'Wrong key (no slot opened), or the backup is corrupted.'\n\t);\n}\n\n// Group read path, in trust order: shape, membership, signature, then\n// envelope + decrypt.\nasync function readGroupBox(\n\tentries: Record<string, Uint8Array>,\n\tmeta: Header,\n\tgroup?: GroupReadOptions\n): Promise<{ snapshot: Snapshot; sidecar: unknown; author: string }> {\n\tif (!group || !Array.isArray(group.authors)) {\n\t\tthrow new SelfstoreError(\n\t\t\t'IDENTITY_REQUIRED',\n\t\t\t'This copy is group-encrypted (per-member keys, no password). Open it with the member ' +\n\t\t\t\t'identity AND the trusted author list: the store does this when attached with { group }.'\n\t\t);\n\t}\n\tconst metaBytes = entries[META];\n\tconst dataEnc = entries[DATA];\n\tconst sig = entries[SIG];\n\t// Trusted fields must be well-typed, not merely truthy: malformed input\n\t// fails closed as BAD_FORMAT, never reaches the crypto as a TypeError.\n\tif (\n\t\t!metaBytes ||\n\t\t!dataEnc ||\n\t\t!sig ||\n\t\tmeta.format !== BOX_FORMAT_GROUP ||\n\t\ttypeof meta.author !== 'string' ||\n\t\tmeta.author.length === 0 ||\n\t\t!Array.isArray(meta.recipients) ||\n\t\tmeta.recipients.length === 0 ||\n\t\ttypeof meta.iv !== 'string'\n\t) {\n\t\tthrow new SelfstoreError(\n\t\t\t'BAD_FORMAT',\n\t\t\t'Missing or malformed group encryption entries or parameters.'\n\t\t);\n\t}\n\t// Membership before any crypto: a valid signature over an attacker-chosen\n\t// author proves nothing.\n\tif (!group.authors.includes(meta.author)) {\n\t\tthrow new SelfstoreError(\n\t\t\t'SIGNATURE_INVALID',\n\t\t\t'Copy author is not a trusted group member (check the membership manifest).'\n\t\t);\n\t}\n\tif (!(await verifyBox(metaBytes, dataEnc, sig, meta.author))) {\n\t\tthrow new SelfstoreError('SIGNATURE_INVALID', 'Copy signature verification failed.');\n\t}\n\tconst dataKey = await openDataKey(meta.recipients, group.identity);\n\tconst inner = await gcmOpenRaw(dataKey, meta.iv, dataEnc);\n\tconst r = await unpackWithSidecar(inner);\n\treturn { ...r, author: meta.author };\n}\n\n/** Read a backup into a snapshot, ignoring the sync sidecar. */\nexport async function readBox(bytes: Uint8Array, password?: string): Promise<Snapshot> {\n\treturn (await readBoxWithSync(bytes, password)).snapshot;\n}\n\nfunction metaOf(entries: Record<string, Uint8Array>): Header {\n\tconst metaBytes = entries[META];\n\tif (!metaBytes) throw new SelfstoreError('BAD_FORMAT', 'Missing backup metadata.');\n\tconst meta = JSON.parse(utf8.dec.decode(metaBytes)) as Header;\n\tif ((meta.format ?? BOX_FORMAT_PLAIN) > BOX_FORMAT_ENVELOPE_AUTH) {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Backup format v${meta.format} is newer than this reader supports.`\n\t\t);\n\t}\n\tassertKnownCrypto(meta);\n\treturn meta;\n}\n","// Public types. selfstore is schema-agnostic: named collections of opaque\n// documents plus binary files. The app owns the schema and its migrations.\n\n/** A binary attachment (image, PDF, any bytes). */\nexport interface SnapshotFile {\n\tid: string;\n\tname: string;\n\tmime: string;\n\tbytes: Uint8Array;\n}\n\n/**\n * Collection names starting with `__` are reserved for library bookkeeping\n * (createLocalStore keeps its sync metadata under `__store`). The fluent\n * `backup()` rejects them and `read()` strips them.\n */\nexport const RESERVED_COLLECTION_PREFIX = '__';\n\n/** Everything a backup carries. Collection names must not start with `__`. */\nexport interface Snapshot {\n\tcollections: Record<string, unknown[]>;\n\tfiles: SnapshotFile[];\n}\n\n/** Key-derivation parameters. Stored cleartext so older files still decode. */\nexport interface KdfParams {\n\talgo: 'argon2id';\n\tsalt: string;\n\tm: number;\n\tt: number;\n\tp: number;\n}\n\n/**\n * One wrap of the random data key under one password; any slot's password\n * opens the backup. Adding or removing a slot leaves the data key alone.\n * Changing a password rotates the data key (setEncryption) - that is the\n * operation that actually revokes access.\n */\nexport interface PasswordSlot {\n\t/** Random id so an app can list or drop a slot without knowing its\n\t * password. Cleartext, not authenticated. */\n\tid: string;\n\t/** Absent on password slots, so files written before external keys\n\t * existed still parse. */\n\tkind?: 'password';\n\tkdf: KdfParams;\n\t/** 96-bit IV of the wrap, base64. */\n\tiv: string;\n\t/** AES-256-GCM(KEK, dataKey) with tag appended: 48 bytes, base64. */\n\twrapped: string;\n}\n\n/**\n * Data key wrapped under a caller-supplied 32-byte secret (passkey PRF,\n * hardware token). The library never performs the WebAuthn or hardware\n * exchange; the app derives the secret and hands it in. KEK is\n * HKDF-SHA256 of the secret - no Argon2, the input is already\n * high-entropy. Shares the `keys[]` table with password slots, so a\n * backup can hold e.g. a passkey plus a recovery password.\n */\nexport interface ExternalSlot {\n\tid: string;\n\tkind: 'external';\n\t/** App-owned locator for re-deriving the secret (say, a WebAuthn\n\t * credential id). Cleartext, never a security input. */\n\tkeyRef: string;\n\t/** 96-bit IV of the wrap, base64. */\n\tiv: string;\n\t/** AES-256-GCM(KEK, dataKey) with tag appended: 48 bytes, base64. */\n\twrapped: string;\n}\n\nexport type KeySlot = PasswordSlot | ExternalSlot;\n\n/**\n * Group mode (format 2): the per-publication AES key wrapped for one\n * recipient. `kid` = first 8 bytes of SHA-256(recipient X25519 public),\n * base64 - a locator, not a name. `epk` is the ephemeral X25519 public;\n * `wrap` is AES-256-GCM(dataKey) under HKDF of the ECDH shared secret.\n */\nexport interface RecipientStanza {\n\tkid: string;\n\tepk: string;\n\tiv: string;\n\twrap: string;\n}\n\n/**\n * Cleartext metadata: the `meta.json` entry of the ZIP.\n *\n * app/appVersion/createdAt are cosmetic and unauthenticated - never base a\n * security decision on them. In password-envelope mode the wrapped data key\n * authenticates the payload; in group mode the author's Ed25519 signature\n * (sig.bin) covers the exact meta.json and data.enc bytes.\n */\nexport interface Header {\n\t/** Format generation: 2 = plain ZIP, 3 = group, 4 = password envelope.\n\t * Absent means 2. */\n\tformat?: number;\n\tapp: string;\n\t/** Writing app's release version, informational. */\n\tappVersion?: string;\n\t/** Writing app's data schema version (createLocalStore `version`).\n\t * Distinct from appVersion: this one drives migration. */\n\tschemaVersion?: number;\n\tcreatedAt: string;\n\tencryption: 'none' | 'aes-256-gcm';\n\t/** 96-bit IV of data.enc, base64. Present when encrypted. */\n\tiv?: string;\n\t/** Group mode: data-key envelope scheme ('x25519-hkdf-sha256'). */\n\tkeying?: string;\n\t/** Group mode: author's Ed25519 public key. Trust only after verifying\n\t * sig.bin and membership in the group manifest. */\n\tauthor?: string;\n\t/** Group mode: one data-key envelope per recipient. */\n\trecipients?: RecipientStanza[];\n\t/** Password envelope only: the data key wrapped once per password.\n\t * Present iff format === 4. */\n\tkeys?: KeySlot[];\n}\n\n/** Options for writing a backup. */\nexport interface EncodeOptions {\n\tapp: string;\n\tappVersion?: string;\n\tschemaVersion?: number;\n\t/** Omit or leave empty for an unencrypted backup (a plain, readable ZIP). */\n\tpassword?: string;\n\t/** Group mode: encrypt to these recipients (raw X25519 publics, base64)\n\t * under a fresh data key and sign with the author's Ed25519 key.\n\t * Mutually exclusive with `password`. */\n\tgroup?: {\n\t\trecipients: string[];\n\t\tsign: { pub: string; priv: string };\n\t};\n\t/** README text shipped inside an encrypted backup, for whoever opens the\n\t * ZIP by hand. Defaults to a neutral note; apps should brand it. */\n\treadme?: string;\n\t/** Rewrite path: reuse this exact envelope (held data key + slot table\n\t * from the last read) so a writer that knows only one password keeps\n\t * every other slot. Mutually exclusive with `password` and `group`. */\n\tenvelope?: { dataKey: Uint8Array; slots: KeySlot[] };\n\t/** Read the bytes back before returning them, and throw VERIFY_FAILED if\n\t * they do not hold what went in. Carried in the options rather than on the\n\t * builder so it survives every link of the chain: set on one link and lost\n\t * by the next is the silent failure this whole feature exists to prevent. */\n\tverify?: boolean;\n\t/** Extra secrets that ALSO open this backup, each getting its own key slot\n\t * around the same data key - typically a recovery code the user printed.\n\t * Only meaningful alongside `password`. */\n\textraSecrets?: string[];\n}\n","// A password strength policy the store can enforce and a UI can preview from\n// the same rules. Deliberately small: length plus character-class requirements,\n// no dictionary or breach checks (those need data the library does not ship).\n// Unicode-aware so an accented letter counts as a letter and an emoji counts as\n// one character, not two.\n\nexport interface PasswordPolicy {\n\t/** Minimum length in code points (so an emoji counts as one). Default 0. */\n\tminLength?: number;\n\t/** Require at least one lowercase letter (any script with case). */\n\trequireLowercase?: boolean;\n\t/** Require at least one uppercase letter (any script with case). */\n\trequireUppercase?: boolean;\n\t/** Require at least one digit. */\n\trequireDigit?: boolean;\n\t/** Require at least one symbol: anything that is not a letter or a number. */\n\trequireSymbol?: boolean;\n}\n\n/** A stable code for each unmet requirement, so the app maps it to its own copy\n * (like the error codes). `minLength` covers the length rule. */\nexport type PasswordRequirement = 'minLength' | 'lowercase' | 'uppercase' | 'digit' | 'symbol';\n\nexport interface PasswordCheck {\n\tok: boolean;\n\t/** The requirements the password fails, in a stable order. Empty when ok. */\n\tunmet: PasswordRequirement[];\n}\n\n/** Measure a password against a policy. Pure and synchronous: the same call\n * drives a live strength hint in the UI and the store's enforcement. An empty\n * or absent policy passes everything. */\nexport function checkPasswordPolicy(password: string, policy: PasswordPolicy): PasswordCheck {\n\tconst unmet: PasswordRequirement[] = [];\n\t// Count code points, not UTF-16 units, so a password of emoji is not\n\t// over-counted and a min-length rule stays intuitive.\n\tif ([...password].length < (policy.minLength ?? 0)) unmet.push('minLength');\n\tif (policy.requireLowercase && !/\\p{Ll}/u.test(password)) unmet.push('lowercase');\n\tif (policy.requireUppercase && !/\\p{Lu}/u.test(password)) unmet.push('uppercase');\n\tif (policy.requireDigit && !/\\p{Nd}/u.test(password)) unmet.push('digit');\n\tif (policy.requireSymbol && !/[^\\p{L}\\p{N}]/u.test(password)) unmet.push('symbol');\n\treturn { ok: unmet.length === 0, unmet };\n}\n","// The backup format: Snapshot in, portable ZIP out, and back. Plain archive\n// without a password, AES-256-GCM (over Argon2id) with one.\n//\n// const blob = await exportSnapshot(snapshot, { app: 'my-app', password });\n// const back = await importSnapshot(blob, { password });\n//\n// or fluent, same engine:\n//\n// const blob = await backup(snapshot).as('my-app').encryptedWith(password).toBlob();\n// const back = await restore(blob).withPassword(password).read();\n\nimport type { Snapshot, Header, EncodeOptions } from './types';\nimport { writeBox, readBox, readBoxMeta, asBytes } from './box';\n\nexport type {\n\tSnapshot,\n\tSnapshotFile,\n\tHeader,\n\tKdfParams,\n\tRecipientStanza,\n\tEncodeOptions,\n\tPasswordSlot,\n\tExternalSlot,\n\tKeySlot\n} from './types';\nexport { RESERVED_COLLECTION_PREFIX } from './types';\nexport {\n\tSelfstoreError,\n\tAuthExpiredError,\n\tisSelfstoreError,\n\tisAuthExpired,\n\terrorLabelKey,\n\ttype SelfstoreErrorCode\n} from './errors';\nexport { BACKUP_EXTENSION, BACKUP_MIME } from './box';\nexport {\n\tcheckPasswordPolicy,\n\ttype PasswordPolicy,\n\ttype PasswordCheck,\n\ttype PasswordRequirement\n} from './password-policy';\nexport {\n\tbackup,\n\trestore,\n\ttype BackupDraft,\n\ttype BackupBuilder,\n\ttype EncryptedBackupBuilder,\n\ttype RestoreBuilder\n} from './fluent';\nexport { verifyBackup, countsOf, type ExpectedContents } from './verify';\n\n/** Serialize a snapshot to a portable backup blob (compressed; encrypted if a password is given). */\nexport async function exportSnapshot(snapshot: Snapshot, opts: EncodeOptions): Promise<Blob> {\n\treturn new Blob([(await writeBox(snapshot, opts)) as BlobPart], { type: 'application/zip' });\n}\n\n/** Read a backup blob (or raw bytes) back into a snapshot. */\nexport async function importSnapshot(\n\tinput: Blob | Uint8Array,\n\topts: { password?: string } = {}\n): Promise<Snapshot> {\n\treturn readBox(await asBytes(input), opts.password);\n}\n\n/** Peek at a backup's cleartext metadata (app, date, whether it's encrypted) without decrypting. */\nexport async function inspect(input: Blob | Uint8Array): Promise<Header> {\n\treturn readBoxMeta(await asBytes(input));\n}\n\n/** True if the backup needs a password to import. */\nexport async function isEncrypted(input: Blob | Uint8Array): Promise<boolean> {\n\treturn (await inspect(input)).encryption !== 'none';\n}\n\n/** Re-encrypt under a new password. `from` opens the file, `to` protects the\n * result; omit `to` for an unencrypted backup. */\nexport async function changePassword(\n\tinput: Blob | Uint8Array,\n\topts: { from?: string; to?: string; readme?: string }\n): Promise<Blob> {\n\tconst bytes = await asBytes(input);\n\tconst meta = await readBoxMeta(bytes);\n\tconst snapshot = await readBox(bytes, opts.from);\n\treturn exportSnapshot(snapshot, {\n\t\tapp: meta.app,\n\t\tappVersion: meta.appVersion,\n\t\tschemaVersion: meta.schemaVersion,\n\t\tpassword: opts.to,\n\t\treadme: opts.readme\n\t});\n}\n","/**\n * Read a freshly written backup back, before anyone is told it exists.\n *\n * A backup encrypted with a key nobody can reproduce, truncated, or built from\n * an empty snapshot looks exactly like a good one: right name, right date,\n * plausible size. The difference only shows up on the day of the disaster, when\n * it is far too late to make another. The only way to know is to open it.\n *\n * The cost is one decrypt of data the app already holds - a few hundred\n * milliseconds at these sizes, once per save. Cheap enough that the honest\n * default is to do it, and cheap enough that a host doing it on every write is\n * not being wasteful.\n */\n\nimport { SelfstoreError } from './errors';\nimport { importSnapshot } from './index';\nimport type { Snapshot } from './types';\n\n/** What the caller believes it just wrote. */\nexport interface ExpectedContents {\n\t/** Per-collection record counts. Only the named collections are checked, so\n\t * a caller can pin the two that matter instead of listing everything. */\n\tcounts?: Record<string, number>;\n\t/** Number of binary files. */\n\tfiles?: number;\n}\n\n/**\n * Open `bytes` and check they hold what was meant to be written. Throws\n * VERIFY_FAILED otherwise - never returns false, because a caller that ignores\n * a boolean is exactly how a backup that lies gets announced as done.\n */\nexport async function verifyBackup(\n\tbytes: Blob | Uint8Array,\n\topts: { password?: string; expect?: ExpectedContents } = {}\n): Promise<void> {\n\tlet read: Snapshot;\n\ttry {\n\t\tread = await importSnapshot(bytes, { password: opts.password });\n\t} catch {\n\t\t// The password is the likeliest culprit and the most expensive one to\n\t\t// discover late: an archive nobody can open is not a backup.\n\t\tthrow new SelfstoreError('VERIFY_FAILED', 'The backup just written could not be read back.');\n\t}\n\tconst expect = opts.expect;\n\tif (!expect) return;\n\tfor (const [name, count] of Object.entries(expect.counts ?? {})) {\n\t\tconst got = read.collections[name]?.length ?? 0;\n\t\tif (got !== count) {\n\t\t\tthrow new SelfstoreError(\n\t\t\t\t'VERIFY_FAILED',\n\t\t\t\t`The backup just written holds ${got} \"${name}\" where ${count} were expected.`\n\t\t\t);\n\t\t}\n\t}\n\tif (expect.files !== undefined && read.files.length !== expect.files) {\n\t\tthrow new SelfstoreError(\n\t\t\t'VERIFY_FAILED',\n\t\t\t`The backup just written holds ${read.files.length} files where ${expect.files} were expected.`\n\t\t);\n\t}\n}\n\n/** Every collection's record count, for a caller that wants the whole snapshot\n * checked rather than picking which parts matter. */\nexport function countsOf(snapshot: Snapshot): ExpectedContents {\n\tconst counts: Record<string, number> = {};\n\tfor (const [name, rows] of Object.entries(snapshot.collections)) {\n\t\tcounts[name] = rows.length;\n\t}\n\treturn { counts, files: snapshot.files.length };\n}\n","// Fluent facade over the functional API. The chain is staged so an illegal\n// call order does not compile: backup() exposes only .as(), and .withReadme()\n// appears only after .encryptedWith() (the readme ships inside the encrypted\n// ZIP, so it means nothing on a plain one).\n//\n// const blob = await backup(snapshot).as('my-app', '1.2.0').encryptedWith(pw).toBlob();\n// const snap = await restore(file).withPassword(pw).read();\n\nimport type { Snapshot, Header, EncodeOptions } from './types';\nimport { RESERVED_COLLECTION_PREFIX } from './types';\nimport { writeBox, readBox, readBoxMeta, asBytes, BACKUP_MIME, BACKUP_EXTENSION } from './box';\nimport { verifyBackup, countsOf } from './verify';\n\n/** Start writing a backup. Naming the app via .as() is the required next step. */\nexport function backup(snapshot: Snapshot): BackupDraft {\n\treturn new BackupDraft(snapshot);\n}\n\n/** Start reading a backup (a picked File, a fetched Blob, or raw bytes). */\nexport function restore(input: Blob | Uint8Array): RestoreBuilder {\n\treturn new RestoreBuilder(input);\n}\n\n// Validation lives in the constructor, not the factory, so direct\n// construction cannot bypass it.\nexport class BackupDraft {\n\tconstructor(private readonly snapshot: Snapshot) {\n\t\tfor (const name of Object.keys(snapshot.collections)) {\n\t\t\tif (name.startsWith(RESERVED_COLLECTION_PREFIX)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`backup(): collection \"${name}\" uses the reserved \"${RESERVED_COLLECTION_PREFIX}\" prefix (library bookkeeping) - rename it`\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Name the writing app (stored cleartext in the backup's metadata). */\n\tas(app: string, appVersion?: string): BackupBuilder {\n\t\treturn new BackupBuilder(this.snapshot, { app, appVersion });\n\t}\n}\n\nexport class BackupBuilder {\n\tconstructor(\n\t\tprotected readonly snapshot: Snapshot,\n\t\tprotected readonly opts: EncodeOptions\n\t) {}\n\n\t/** Encrypt the backup (AES-256-GCM over an Argon2id-derived key). */\n\tencryptedWith(password: string): EncryptedBackupBuilder {\n\t\treturn new EncryptedBackupBuilder(this.snapshot, { ...this.opts, password });\n\t}\n\n\t/**\n\t * Read the backup back before handing it over, and throw VERIFY_FAILED if it\n\t * does not hold what went in.\n\t *\n\t * A backup encrypted with a key nobody can reproduce, truncated, or built\n\t * from an empty snapshot looks exactly like a good one: right name, right\n\t * date, plausible size. The difference only shows up on the day of the\n\t * disaster, when it is too late to make another. The only way to know is to\n\t * open it, and it costs one decrypt of data the app already holds.\n\t *\n\t * Applies to every terminal below, so a host cannot verify and then write a\n\t * different set of bytes by accident.\n\t */\n\tverified(): BackupBuilder {\n\t\treturn new BackupBuilder(this.snapshot, { ...this.opts, verify: true });\n\t}\n\n\t/** The backup as raw bytes. */\n\tasync toBytes(): Promise<Uint8Array> {\n\t\tconst bytes = await writeBox(this.snapshot, this.opts);\n\t\tif (this.opts.verify) {\n\t\t\tawait verifyBackup(bytes, { password: this.opts.password, expect: countsOf(this.snapshot) });\n\t\t}\n\t\treturn bytes;\n\t}\n\n\t/** The backup as a Blob, ready to upload or hand to a save dialog. */\n\tasync toBlob(): Promise<Blob> {\n\t\treturn new Blob([(await this.toBytes()) as BlobPart], { type: BACKUP_MIME });\n\t}\n\n\t/** Save the backup to disk (File System Access API, else a download).\n\t * Browser-only terminal; defaults to `<app>-<date>.zip`. False when the\n\t * user closed the save dialog: nothing was written, so do not tell them\n\t * they have a backup.\n\t *\n\t * Asks WHERE first, encrypts after. The save dialog needs the transient\n\t * activation of the click that led here, and building an encrypted backup\n\t * outlives it (Argon2id is deliberately slow): encrypting first made the\n\t * browser refuse the dialog and silently download instead, turning a file\n\t * the user chose into one they have to go and find. */\n\tasync toDisk(filename?: string): Promise<boolean> {\n\t\tconst name =\n\t\t\tfilename ?? `${this.opts.app}-${new Date().toISOString().slice(0, 10)}${BACKUP_EXTENSION}`;\n\t\tconst { pickSaveHandle, writeToHandle, downloadBlob } = await import('./targets/local');\n\t\tconst cible = await pickSaveHandle(name);\n\t\tif (cible === 'CANCELLED') return false;\n\t\tconst blob = await this.toBlob();\n\t\tif (cible) {\n\t\t\tawait writeToHandle(cible.handle, blob);\n\t\t\treturn true;\n\t\t}\n\t\tdownloadBlob(blob, name);\n\t\treturn true;\n\t}\n}\n\nexport class EncryptedBackupBuilder extends BackupBuilder {\n\tconstructor(snapshot: Snapshot, opts: EncodeOptions) {\n\t\tif (!opts.password) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'EncryptedBackupBuilder: a password is required - use backup(snapshot).as(app).encryptedWith(password)'\n\t\t\t);\n\t\t}\n\t\tsuper(snapshot, opts);\n\t}\n\n\t/** Same guarantee, keeping the encrypted chain's own links reachable. */\n\toverride verified(): EncryptedBackupBuilder {\n\t\treturn new EncryptedBackupBuilder(this.snapshot, { ...this.opts, verify: true });\n\t}\n\n\t/** Brand the README shipped inside the encrypted ZIP. */\n\twithReadme(text: string): EncryptedBackupBuilder {\n\t\treturn new EncryptedBackupBuilder(this.snapshot, { ...this.opts, readme: text });\n\t}\n\n\t/**\n\t * A second secret that also opens this backup - a recovery code the user\n\t * printed and put away.\n\t *\n\t * A password that only lives in one person's memory is the likeliest way a\n\t * local-first backup dies: no server can reset it, so the day it is\n\t * forgotten the data is gone for good. The envelope has always held several\n\t * key slots (see `keys[]` in the header); this exposes them where a backup\n\t * is actually written. Each secret wraps the SAME data key, so either one\n\t * opens the file and neither can read the other.\n\t *\n\t * Call it more than once for more than one recovery secret. Reading needs no\n\t * change: `restore(...).withPassword(code)` already tries every slot.\n\t */\n\talsoOpenedWith(secret: string): EncryptedBackupBuilder {\n\t\tif (!secret) {\n\t\t\tthrow new TypeError('alsoOpenedWith(): a non-empty secret is required.');\n\t\t}\n\t\treturn new EncryptedBackupBuilder(this.snapshot, {\n\t\t\t...this.opts,\n\t\t\textraSecrets: [...(this.opts.extraSecrets ?? []), secret]\n\t\t});\n\t}\n}\n\nexport class RestoreBuilder {\n\tprivate password?: string;\n\n\tconstructor(private readonly input: Blob | Uint8Array) {}\n\n\t/** Accepts undefined so callers can pass straight through from an optional field. */\n\twithPassword(password?: string): this {\n\t\tthis.password = password || undefined;\n\t\treturn this;\n\t}\n\n\t/** The cleartext metadata (app, date, encryption), without decrypting. */\n\tasync meta(): Promise<Header> {\n\t\treturn readBoxMeta(await asBytes(this.input));\n\t}\n\n\t/** True if reading will require a password. */\n\tasync isEncrypted(): Promise<boolean> {\n\t\treturn (await this.meta()).encryption !== 'none';\n\t}\n\n\t/** Read the backup into a snapshot. Reserved `__*` collections (library\n\t * bookkeeping) are stripped. PASSWORD_REQUIRED when encrypted and no\n\t * password given, DECRYPT_FAILED on a wrong one. */\n\tasync read(): Promise<Snapshot> {\n\t\tconst snap = await readBox(await asBytes(this.input), this.password);\n\t\tconst collections = Object.fromEntries(\n\t\t\tObject.entries(snap.collections).filter(\n\t\t\t\t([name]) => !name.startsWith(RESERVED_COLLECTION_PREFIX)\n\t\t\t)\n\t\t);\n\t\treturn { collections, files: snap.files };\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../src/selfstore/archive.ts","../src/selfstore/box.ts","../src/selfstore/types.ts","../src/selfstore/password-policy.ts","../src/selfstore/index.ts","../src/selfstore/verify.ts","../src/selfstore/fluent.ts"],"names":["utf8"],"mappings":";;;;;AAQA,IAAM,QAAA,GAAW,gBAAA;AAGjB,IAAM,OAAA,GAAU,WAAA;AAChB,IAAM,eAAA,GAAkB,CAAA;AAKjB,IAAM,eAAA,GAAkB,MAAM,IAAA,GAAO,IAAA;AACrC,IAAM,eAAA,GAAkB,OAAO,IAAA,GAAO,IAAA;AAE7C,IAAM,IAAA,GAAO,EAAE,GAAA,EAAK,IAAI,aAAY,EAAG,GAAA,EAAK,IAAI,WAAA,EAAY,EAAE;AAc9D,eAAsB,GAAA,CACrB,OAAA,EACA,KAAA,GAAe,CAAA,EACO;AACtB,EAAA,MAAM,EAAE,OAAA,EAAQ,GAAI,MAAM,OAAO,QAAQ,CAAA;AACzC,EAAA,MAAM,QAAiE,EAAC;AACxE,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AACpD,IAAA,KAAA,C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;AAAA,EAGA,MAAM,IAAA,GAAwB;AAC7B,IAAA,OAAO,WAAA,CAAY,MAAM,OAAA,CAAQ,IAAA,CAAK,KAAK,CAAC,CAAA;AAAA,EAC7C;AAAA;AAAA,EAGA,MAAM,WAAA,GAAgC;AACrC,IAAA,OAAA,CAAQ,MAAM,IAAA,CAAK,IAAA,EAAK,EAAG,UAAA,KAAe,MAAA;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,IAAA,GAA0B;AAC/B,IAAA,MAAM,IAAA,GAAO,MAAM,OAAA,CAAQ,MAAM,QAAQ,IAAA,CAAK,KAAK,CAAA,EAAG,IAAA,CAAK,QAAQ,CAAA;AACnE,IAAA,MAAM,cAAc,MAAA,CAAO,WAAA;AAAA,MAC1B,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,WAAW,CAAA,CAAE,MAAA;AAAA,QAChC,CAAC,CAAC,IAAI,MAAM,CAAC,IAAA,CAAK,WAAW,0BAA0B;AAAA;AACxD,KACD;AACA,IAAA,OAAO,EAAE,WAAA,EAAa,KAAA,EAAO,IAAA,CAAK,KAAA,EAAM;AAAA,EACzC;AACD,CAAA","file":"chunk-BNDFMU3J.js","sourcesContent":["// The inner archive: a JSON manifest (selfstore.json) plus one entry per\n// binary file, as a plain ZIP. Encrypted backups wrap these same bytes in\n// AES-GCM (box.ts). fflate is imported dynamically - only needed at\n// export/import time.\n\nimport type { Snapshot, SnapshotFile } from './types';\nimport { SelfstoreError } from './errors';\n\nconst MANIFEST = 'selfstore.json';\n// Opaque caller bookkeeping (createLocalStore's schema version + merge\n// metadata). Its own entry, so the manifest holds nothing but app data.\nconst SIDECAR = 'sync.json';\nconst ARCHIVE_VERSION = 1;\n\n// Zip-bomb guards. Backups are user data measured in MB; half a GiB per\n// entry and 1 GiB total are far above legitimate use and bound worst-case\n// inflation (many individually-legal entries must not add up to a bomb).\nexport const MAX_ENTRY_BYTES = 512 * 1024 * 1024;\nexport const MAX_TOTAL_BYTES = 1024 * 1024 * 1024;\n\nconst utf8 = { enc: new TextEncoder(), dec: new TextDecoder() };\n\ninterface FileMeta {\n\tid: string;\n\tname: string;\n\tmime: string;\n}\n\n/**\n * ZIP a set of named entries. `level` applies to the JSON entries; file\n * attachments are stored uncompressed - photos and PDFs are usually already\n * compressed, and re-deflating them was the biggest chunk of per-save\n * main-thread time for near-zero size gain. Still a plain readable ZIP.\n */\nexport async function zip(\n\tentries: Record<string, Uint8Array>,\n\tlevel: 0 | 6 = 6\n): Promise<Uint8Array> {\n\tconst { zipSync } = await import('fflate');\n\tconst input: Record<string, Uint8Array | [Uint8Array, { level: 0 }]> = {};\n\tfor (const [name, bytes] of Object.entries(entries)) {\n\t\tinput[name] = level !== 0 && name.startsWith('files/') ? [bytes, { level: 0 }] : bytes;\n\t}\n\treturn zipSync(input as Parameters<typeof zipSync>[0], { level });\n}\n\n/** Unzip to named entries. BAD_FORMAT on unreadable bytes, TOO_LARGE past the bomb guards. */\nexport async function unzip(\n\tbytes: Uint8Array,\n\tmaxEntryBytes: number = MAX_ENTRY_BYTES,\n\tmaxTotalBytes: number = MAX_TOTAL_BYTES\n): Promise<Record<string, Uint8Array>> {\n\tconst { unzipSync } = await import('fflate');\n\tlet total = 0;\n\ttry {\n\t\treturn unzipSync(bytes, {\n\t\t\tfilter: (f) => {\n\t\t\t\tif (f.originalSize > maxEntryBytes) {\n\t\t\t\t\tthrow new SelfstoreError('TOO_LARGE', `Archive entry \"${f.name}\" is too large.`);\n\t\t\t\t}\n\t\t\t\ttotal += f.originalSize;\n\t\t\t\tif (total > maxTotalBytes) {\n\t\t\t\t\tthrow new SelfstoreError('TOO_LARGE', 'Archive total size exceeds the guard.');\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t});\n\t} catch (e) {\n\t\tif (e instanceof SelfstoreError) throw e;\n\t\tthrow new SelfstoreError('BAD_FORMAT', 'Unreadable archive.');\n\t}\n}\n\n/** Manifest + file entries for a snapshot; `sidecar` rides its own sync.json entry. */\nexport function buildEntries(snap: Snapshot, sidecar?: unknown): Record<string, Uint8Array> {\n\tconst entries: Record<string, Uint8Array> = {};\n\tentries[MANIFEST] = utf8.enc.encode(\n\t\tJSON.stringify({\n\t\t\tversion: ARCHIVE_VERSION,\n\t\t\tcollections: snap.collections,\n\t\t\tfiles: snap.files.map(({ id, name, mime }): FileMeta => ({ id, name, mime }))\n\t\t})\n\t);\n\tif (sidecar !== undefined && sidecar !== null) {\n\t\tentries[SIDECAR] = utf8.enc.encode(JSON.stringify(sidecar));\n\t}\n\tfor (const f of snap.files) entries[`files/${f.id}`] = f.bytes;\n\treturn entries;\n}\n\n/** The sync.json sidecar if present, else null. Unreadable content reads as absent. */\nexport function readSidecar(entries: Record<string, Uint8Array>): unknown {\n\tconst bytes = entries[SIDECAR];\n\tif (!bytes) return null;\n\ttry {\n\t\treturn JSON.parse(utf8.dec.decode(bytes));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Rebuild a snapshot from ZIP entries (the inverse of buildEntries). */\nexport function entriesToSnapshot(entries: Record<string, Uint8Array>): Snapshot {\n\tconst manifestBytes = entries[MANIFEST];\n\tif (!manifestBytes) throw new SelfstoreError('BAD_FORMAT', 'Missing manifest.');\n\tconst manifest = JSON.parse(utf8.dec.decode(manifestBytes)) as {\n\t\tcollections?: Record<string, unknown[]>;\n\t\tfiles?: FileMeta[];\n\t};\n\tconst files: SnapshotFile[] = (manifest.files ?? []).map((m) => ({\n\t\t...m,\n\t\tbytes: entries[`files/${m.id}`] ?? new Uint8Array()\n\t}));\n\treturn { collections: manifest.collections ?? {}, files };\n}\n\n/** Pack a snapshot (plus an optional opaque sidecar) into ZIP bytes. */\nexport async function pack(snap: Snapshot, sidecar?: unknown): Promise<Uint8Array> {\n\treturn zip(buildEntries(snap, sidecar), 6);\n}\n\n/** Unpack ZIP bytes into a snapshot plus its sidecar (null when absent). */\nexport async function unpackWithSidecar(\n\tzipBytes: Uint8Array\n): Promise<{ snapshot: Snapshot; sidecar: unknown }> {\n\tconst entries = await unzip(zipBytes);\n\treturn { snapshot: entriesToSnapshot(entries), sidecar: readSidecar(entries) };\n}\n","// The portable backup container - a real ZIP in both cases, never a mystery\n// blob:\n//\n// unencrypted: meta.json + selfstore.json + files/* (browsable, format 1)\n// encrypted: meta.json + data.enc + LISEZMOI.txt (AES-256-GCM / Argon2id)\n//\n// Encrypted means the password envelope (format 3): a random data key seals\n// the inner ZIP, wrapped once per password in keys[], and the exact meta.json\n// bytes ride as GCM AAD so the slot table is tamper-evident. Format 2 is the\n// passwordless group variant. Anything else is refused.\n\nimport type { Snapshot, Header, EncodeOptions, PasswordSlot, ExternalSlot, KeySlot } from './types';\nimport {\n\tbuildEntries,\n\tentriesToSnapshot,\n\treadSidecar,\n\tpack,\n\tunpackWithSidecar,\n\tzip,\n\tunzip\n} from './archive';\nimport {\n\tmintSlot,\n\topenSlot,\n\topenExternalSlot,\n\tMAX_KEY_SLOTS,\n\tgcmSealAad,\n\tgcmOpenAad,\n\ttoBase64,\n\tfromBase64\n} from './crypto';\nimport {\n\tGROUP_KEYING,\n\tgcmSealRaw,\n\tgcmOpenRaw,\n\tsealDataKey,\n\topenDataKey,\n\tsignBox,\n\tverifyBox,\n\ttype GroupIdentity\n} from './group';\nimport { SelfstoreError } from './errors';\n\n// Genuine ZIPs get the honest extension.\nexport const BACKUP_EXTENSION = '.zip';\nexport const BACKUP_MIME = 'application/zip';\n\nconst META = 'meta.json';\nconst DATA = 'data.enc';\nconst SIG = 'sig.bin';\nconst README = 'LISEZMOI.txt';\n\n// Format identifier, which is also the discriminant: 1 plain ZIP, 2 group\n// mode, 3 authenticated password envelope (header bound as GCM AAD). These are\n// fixed wire ids; anything else is refused.\nconst BOX_FORMAT_PLAIN = 1;\nconst BOX_FORMAT_GROUP = 2;\nconst BOX_FORMAT_ENVELOPE_AUTH = 3;\n\nconst ZIP_MAGIC = [0x50, 0x4b, 0x03, 0x04]; // \"PK\\x03\\x04\"\n\nconst utf8 = { enc: new TextEncoder(), dec: new TextDecoder() };\n\n// Shipped inside encrypted backups for whoever opens the ZIP by hand. ASCII\n// only so it renders in any viewer; apps brand it via EncodeOptions.readme.\nconst DEFAULT_README =\n\t'Encrypted backup / Sauvegarde chiffree\\n\\n' +\n\t'This is a valid ZIP archive.\\n' +\n\t'\"data.enc\" holds your encrypted data (AES-256-GCM, key derived with Argon2id);\\n' +\n\t'\"meta.json\" holds the decryption parameters (cleartext).\\n' +\n\t'To read it, import this file into the application that created it\\n' +\n\t'(named in meta.json) with your password.\\n\\n' +\n\t'Ce fichier est une archive ZIP valide.\\n' +\n\t'\"data.enc\" contient vos donnees chiffrees (AES-256-GCM, cle derivee par Argon2id) ;\\n' +\n\t'\"meta.json\" contient les parametres de dechiffrement (en clair).\\n' +\n\t\"Pour la lire, importez ce fichier dans l'application qui l'a creee\\n\" +\n\t'(nommee dans meta.json) avec votre mot de passe.\\n';\n\n/** Coerce an accepted input (a picked File, a fetched Blob, raw bytes) to bytes. */\nexport async function asBytes(input: Blob | Uint8Array): Promise<Uint8Array> {\n\treturn input instanceof Uint8Array ? input : new Uint8Array(await input.arrayBuffer());\n}\n\nfunction startsWith(bytes: Uint8Array, magic: number[]): boolean {\n\treturn bytes.length >= magic.length && magic.every((b, i) => bytes[i] === b);\n}\n\n// An unknown cipher or per-slot KDF means a newer writer: UNSUPPORTED_VERSION,\n// not a misleading DECRYPT_FAILED from feeding foreign params to AES-GCM.\nfunction assertKnownCrypto(header: Header): void {\n\tif (header.encryption !== 'none' && header.encryption !== 'aes-256-gcm') {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Encryption \"${header.encryption}\" is newer than this reader supports.`\n\t\t);\n\t}\n\tif (header.keying !== undefined && header.keying !== GROUP_KEYING) {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Key envelope \"${header.keying}\" is newer than this reader supports.`\n\t\t);\n\t}\n\tfor (const slot of header.keys ?? []) {\n\t\t// External slots carry no KDF (KEK comes from the caller's secret).\n\t\tif (!slot || (slot as ExternalSlot).kind === 'external') continue;\n\t\tif ((slot as PasswordSlot).kdf?.algo !== 'argon2id') {\n\t\t\tthrow new SelfstoreError(\n\t\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t\t`Key derivation \"${(slot as PasswordSlot).kdf?.algo}\" is newer than this reader supports.`\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Serialize a snapshot to backup bytes. The optional `sidecar`\n * (createLocalStore's bookkeeping) rides its own sync.json entry - inside the\n * envelope when encrypting, so it never leaks in cleartext.\n */\nexport async function writeBox(\n\tsnapshot: Snapshot,\n\topts: EncodeOptions,\n\tsidecar?: unknown\n): Promise<Uint8Array> {\n\tconst header: Header = {\n\t\tformat: BOX_FORMAT_PLAIN,\n\t\tapp: opts.app,\n\t\tappVersion: opts.appVersion,\n\t\tschemaVersion: opts.schemaVersion,\n\t\tcreatedAt: new Date().toISOString(),\n\t\tencryption: 'none'\n\t};\n\n\tif (opts.group) {\n\t\tif (opts.password) {\n\t\t\tthrow new TypeError('writeBox(): `group` and `password` are mutually exclusive.');\n\t\t}\n\t\t// Fresh data key enveloped once per recipient; the author's signature\n\t\t// covers the exact meta.json + data.enc bytes, so nothing a reader\n\t\t// trusts (recipients, author claim, iv, ciphertext) can be altered.\n\t\tconst dataKey = crypto.getRandomValues(new Uint8Array(32));\n\t\tconst enc = await gcmSealRaw(dataKey, await pack(snapshot, sidecar));\n\t\tconst meta: Header = {\n\t\t\t...header,\n\t\t\tformat: BOX_FORMAT_GROUP,\n\t\t\tencryption: 'aes-256-gcm',\n\t\t\tkeying: GROUP_KEYING,\n\t\t\tauthor: opts.group.sign.pub,\n\t\t\trecipients: await sealDataKey(dataKey, opts.group.recipients),\n\t\t\tiv: enc.iv\n\t\t};\n\t\tconst metaBytes = utf8.enc.encode(JSON.stringify(meta));\n\t\treturn zip(\n\t\t\t{\n\t\t\t\t[META]: metaBytes,\n\t\t\t\t[DATA]: enc.ciphertext,\n\t\t\t\t[SIG]: await signBox(metaBytes, enc.ciphertext, opts.group.sign.priv),\n\t\t\t\t[README]: utf8.enc.encode(opts.readme || DEFAULT_README)\n\t\t\t},\n\t\t\t0\n\t\t);\n\t}\n\n\tif (opts.envelope && opts.password) {\n\t\tthrow new TypeError('writeBox(): `envelope` and `password` are mutually exclusive.');\n\t}\n\n\tif (opts.envelope || opts.password) {\n\t\t// A rewrite passes `envelope` (held data key + carried slot table) so a\n\t\t// writer that knows only one password preserves every other slot; a\n\t\t// plain `password` mints a fresh single-slot envelope, i.e. a data-key\n\t\t// rotation - that is what makes setEncryption actually revoke.\n\t\t// The iv is minted before meta.json is serialized so it sits inside the\n\t\t// AAD; seal and open then agree on the exact header bytes.\n\t\tconst dataKey = opts.envelope?.dataKey ?? crypto.getRandomValues(new Uint8Array(32));\n\t\t// Every extra secret gets its own slot around the SAME data key: either\n\t\t// one opens the file, and neither can be derived from the other. A rewrite\n\t\t// (`envelope`) already carries the slot table, so extras only apply when\n\t\t// minting a fresh envelope.\n\t\tconst slots = opts.envelope?.slots ?? [\n\t\t\tawait mintSlot(opts.password!, dataKey),\n\t\t\t...(await Promise.all((opts.extraSecrets ?? []).map((s) => mintSlot(s, dataKey))))\n\t\t];\n\t\tif (slots.length === 0 || slots.length > MAX_KEY_SLOTS) {\n\t\t\tthrow new TypeError(`writeBox(): between 1 and ${MAX_KEY_SLOTS} password slots.`);\n\t\t}\n\t\tconst iv = crypto.getRandomValues(new Uint8Array(12));\n\t\tconst meta: Header = {\n\t\t\t...header,\n\t\t\tformat: BOX_FORMAT_ENVELOPE_AUTH,\n\t\t\tencryption: 'aes-256-gcm',\n\t\t\tkeys: slots,\n\t\t\tiv: toBase64(iv)\n\t\t};\n\t\tconst metaBytes = utf8.enc.encode(JSON.stringify(meta));\n\t\tconst ciphertext = await gcmSealAad(dataKey, iv, await pack(snapshot, sidecar), metaBytes);\n\t\treturn zip(\n\t\t\t{\n\t\t\t\t[META]: metaBytes,\n\t\t\t\t[DATA]: ciphertext,\n\t\t\t\t[README]: utf8.enc.encode(opts.readme || DEFAULT_README)\n\t\t\t},\n\t\t\t0\n\t\t);\n\t}\n\n\t// The file is the browsable archive: manifest + files (+ sync.json), plus meta.json.\n\tconst entries = buildEntries(snapshot, sidecar);\n\tentries[META] = utf8.enc.encode(JSON.stringify(header));\n\treturn zip(entries, 6);\n}\n\n/** Read the cleartext metadata (app, date, whether encrypted) without decrypting. */\nexport async function readBoxMeta(bytes: Uint8Array): Promise<Header> {\n\tif (!startsWith(bytes, ZIP_MAGIC)) {\n\t\tthrow new SelfstoreError(\n\t\t\t'BAD_FORMAT',\n\t\t\t'Not a selfstore backup: expected a ZIP. Pass the exact bytes/Blob produced by ' +\n\t\t\t\t'backup().toBlob() / exportSnapshot(), not a decoded object.'\n\t\t);\n\t}\n\treturn metaOf(await unzip(bytes));\n}\n\n/**\n * Group-mode read inputs: the reader's identity and the trusted author keys\n * (manifest members' Ed25519 publics). `authors` is mandatory - a valid\n * signature over an attacker-chosen author proves nothing (SPEC.md 12.6), so\n * there is no \"decrypt without checking who signed\" mode.\n */\nexport interface GroupReadOptions {\n\tidentity: Pick<GroupIdentity, 'encPub' | 'encPriv'>;\n\tauthors: string[];\n}\n\n/**\n * Key material captured at read time: the data key that opened the file plus\n * the slot table verbatim. Carried into rewrites so a session that knows only\n * one key preserves every slot.\n */\nexport interface BoxEnvelope {\n\tdataKey: Uint8Array;\n\tslots: KeySlot[];\n}\n\n/**\n * App-supplied secret fetch for an external-key slot (the WebAuthn/hardware\n * exchange lives app-side). Return null to skip the slot (wrong key, user\n * cancelled).\n */\nexport type ExternalKeyResolver = (slot: ExternalSlot) => Promise<Uint8Array | null>;\n\n/**\n * Read a backup into a snapshot plus its sync.json sidecar (null when the\n * file carries none). Group copies need `group` and return the verified\n * author; envelope copies accept a held `dataKey` (KDF-free re-read) and\n * return the envelope for later rewrites.\n */\nexport async function readBoxWithSync(\n\tbytes: Uint8Array,\n\tpassword?: string,\n\tgroup?: GroupReadOptions,\n\tdataKey?: Uint8Array,\n\texternalResolver?: ExternalKeyResolver\n): Promise<{\n\tsnapshot: Snapshot;\n\tsidecar: unknown;\n\tauthor?: string;\n\tenvelope?: BoxEnvelope;\n\tformat: number;\n}> {\n\tconst entries = await unzip(bytes);\n\tconst meta = metaOf(entries);\n\tconst format = meta.format ?? BOX_FORMAT_PLAIN;\n\tif (\n\t\tformat !== BOX_FORMAT_PLAIN &&\n\t\tformat !== BOX_FORMAT_GROUP &&\n\t\tformat !== BOX_FORMAT_ENVELOPE_AUTH\n\t) {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Backup format ${format} is not supported by this reader.`\n\t\t);\n\t}\n\t// Bind security mode to format generation both ways, so neither `keying`\n\t// nor `format` can be stripped to route a box down the wrong path.\n\tif ((format === BOX_FORMAT_GROUP) !== !!meta.keying) {\n\t\tthrow new SelfstoreError(\n\t\t\t'BAD_FORMAT',\n\t\t\t'Group mode (format 2) and the keying field must agree.'\n\t\t);\n\t}\n\tif ((format === BOX_FORMAT_ENVELOPE_AUTH) !== Array.isArray(meta.keys)) {\n\t\tthrow new SelfstoreError(\n\t\t\t'BAD_FORMAT',\n\t\t\t'Password envelope (format 3) and the keys field must agree.'\n\t\t);\n\t}\n\tif (meta.keying) return { ...(await readGroupBox(entries, meta, group)), format };\n\tif (format === BOX_FORMAT_ENVELOPE_AUTH) {\n\t\treturn {\n\t\t\t...(await readEnvelopeBox(entries, meta, password, dataKey, externalResolver)),\n\t\t\tformat\n\t\t};\n\t}\n\tif (meta.encryption === 'none') {\n\t\treturn { snapshot: entriesToSnapshot(entries), sidecar: readSidecar(entries), format };\n\t}\n\t// Encrypted content in a container claiming the plain format: never written\n\t// by this library. Refuse cleanly rather than half-read.\n\tthrow new SelfstoreError('BAD_FORMAT', 'Encrypted content in a plain-format container.');\n}\n\n// Envelope read path: bounds first, the held data key as a KDF-free fast\n// path, then one trial per slot. All slots failing is DECRYPT_FAILED - wrong\n// key and tampering stay one case.\nasync function readEnvelopeBox(\n\tentries: Record<string, Uint8Array>,\n\tmeta: Header,\n\tpassword?: string,\n\tdataKey?: Uint8Array,\n\texternalResolver?: ExternalKeyResolver\n): Promise<{ snapshot: Snapshot; sidecar: unknown; envelope: BoxEnvelope }> {\n\tconst dataEnc = entries[DATA];\n\tconst metaBytes = entries[META];\n\tconst slots = meta.keys;\n\tif (\n\t\t!dataEnc ||\n\t\t!metaBytes ||\n\t\t!Array.isArray(slots) ||\n\t\tslots.length === 0 ||\n\t\ttypeof meta.iv !== 'string' ||\n\t\tmeta.encryption !== 'aes-256-gcm'\n\t) {\n\t\tthrow new SelfstoreError('BAD_FORMAT', 'Missing or malformed envelope entries or parameters.');\n\t}\n\tif (slots.length > MAX_KEY_SLOTS) {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Backup declares ${slots.length} key slots; this reader caps at ${MAX_KEY_SLOTS} ` +\n\t\t\t\t'(each password slot is one memory-hard trial).'\n\t\t);\n\t}\n\t// The exact meta.json bytes are bound as GCM AAD: a tampered header (an\n\t// altered slot table, a swapped KDF) fails the decrypt instead of opening.\n\tconst aad = metaBytes;\n\tconst iv = fromBase64(meta.iv);\n\t// A caller re-reading its own file skips the KDF entirely. On failure fall\n\t// through to the slot trials - another device may have rotated the key.\n\tif (dataKey) {\n\t\ttry {\n\t\t\tconst r = await unpackWithSidecar(await gcmOpenAad(dataKey, iv, dataEnc, aad));\n\t\t\treturn { ...r, envelope: { dataKey, slots } };\n\t\t} catch {\n\t\t\t/* rotated, foreign, or tampered file: the slot path decides */\n\t\t}\n\t}\n\tif (!password && !externalResolver) {\n\t\tthrow new SelfstoreError(\n\t\t\t'PASSWORD_REQUIRED',\n\t\t\t'This backup is encrypted. Provide the password, or the external key (e.g. a passkey), to open it.'\n\t\t);\n\t}\n\tfor (const slot of slots) {\n\t\tlet opened: Uint8Array | null = null;\n\t\tif ((slot as ExternalSlot).kind === 'external') {\n\t\t\tif (externalResolver) {\n\t\t\t\tconst secret = await externalResolver(slot as ExternalSlot);\n\t\t\t\tif (secret) opened = await openExternalSlot(slot as ExternalSlot, secret);\n\t\t\t}\n\t\t} else if (password) {\n\t\t\topened = await openSlot(slot as PasswordSlot, password);\n\t\t}\n\t\tif (!opened) continue;\n\t\t// Every slot wraps the same data key, so if the decrypt below fails\n\t\t// (header tamper surfaces here on format 3) trying another slot gains\n\t\t// nothing - let it throw.\n\t\tconst r = await unpackWithSidecar(await gcmOpenAad(opened, iv, dataEnc, aad));\n\t\treturn { ...r, envelope: { dataKey: opened, slots } };\n\t}\n\tthrow new SelfstoreError(\n\t\t'DECRYPT_FAILED',\n\t\t'Wrong key (no slot opened), or the backup is corrupted.'\n\t);\n}\n\n// Group read path, in trust order: shape, membership, signature, then\n// envelope + decrypt.\nasync function readGroupBox(\n\tentries: Record<string, Uint8Array>,\n\tmeta: Header,\n\tgroup?: GroupReadOptions\n): Promise<{ snapshot: Snapshot; sidecar: unknown; author: string }> {\n\tif (!group || !Array.isArray(group.authors)) {\n\t\tthrow new SelfstoreError(\n\t\t\t'IDENTITY_REQUIRED',\n\t\t\t'This copy is group-encrypted (per-member keys, no password). Open it with the member ' +\n\t\t\t\t'identity AND the trusted author list: the store does this when attached with { group }.'\n\t\t);\n\t}\n\tconst metaBytes = entries[META];\n\tconst dataEnc = entries[DATA];\n\tconst sig = entries[SIG];\n\t// Trusted fields must be well-typed, not merely truthy: malformed input\n\t// fails closed as BAD_FORMAT, never reaches the crypto as a TypeError.\n\tif (\n\t\t!metaBytes ||\n\t\t!dataEnc ||\n\t\t!sig ||\n\t\tmeta.format !== BOX_FORMAT_GROUP ||\n\t\ttypeof meta.author !== 'string' ||\n\t\tmeta.author.length === 0 ||\n\t\t!Array.isArray(meta.recipients) ||\n\t\tmeta.recipients.length === 0 ||\n\t\ttypeof meta.iv !== 'string'\n\t) {\n\t\tthrow new SelfstoreError(\n\t\t\t'BAD_FORMAT',\n\t\t\t'Missing or malformed group encryption entries or parameters.'\n\t\t);\n\t}\n\t// Membership before any crypto: a valid signature over an attacker-chosen\n\t// author proves nothing.\n\tif (!group.authors.includes(meta.author)) {\n\t\tthrow new SelfstoreError(\n\t\t\t'SIGNATURE_INVALID',\n\t\t\t'Copy author is not a trusted group member (check the membership manifest).'\n\t\t);\n\t}\n\tif (!(await verifyBox(metaBytes, dataEnc, sig, meta.author))) {\n\t\tthrow new SelfstoreError('SIGNATURE_INVALID', 'Copy signature verification failed.');\n\t}\n\tconst dataKey = await openDataKey(meta.recipients, group.identity);\n\tconst inner = await gcmOpenRaw(dataKey, meta.iv, dataEnc);\n\tconst r = await unpackWithSidecar(inner);\n\treturn { ...r, author: meta.author };\n}\n\n/** Read a backup into a snapshot, ignoring the sync sidecar. */\nexport async function readBox(bytes: Uint8Array, password?: string): Promise<Snapshot> {\n\treturn (await readBoxWithSync(bytes, password)).snapshot;\n}\n\nfunction metaOf(entries: Record<string, Uint8Array>): Header {\n\tconst metaBytes = entries[META];\n\tif (!metaBytes) throw new SelfstoreError('BAD_FORMAT', 'Missing backup metadata.');\n\tconst meta = JSON.parse(utf8.dec.decode(metaBytes)) as Header;\n\tif ((meta.format ?? BOX_FORMAT_PLAIN) > BOX_FORMAT_ENVELOPE_AUTH) {\n\t\tthrow new SelfstoreError(\n\t\t\t'UNSUPPORTED_VERSION',\n\t\t\t`Backup format v${meta.format} is newer than this reader supports.`\n\t\t);\n\t}\n\tassertKnownCrypto(meta);\n\treturn meta;\n}\n","// Public types. selfstore is schema-agnostic: named collections of opaque\n// documents plus binary files. The app owns the schema and its migrations.\n\n/** A binary attachment (image, PDF, any bytes). */\nexport interface SnapshotFile {\n\tid: string;\n\tname: string;\n\tmime: string;\n\tbytes: Uint8Array;\n}\n\n/**\n * Collection names starting with `__` are reserved for library bookkeeping\n * (createLocalStore keeps its sync metadata under `__store`). The fluent\n * `backup()` rejects them and `read()` strips them.\n */\nexport const RESERVED_COLLECTION_PREFIX = '__';\n\n/** Everything a backup carries. Collection names must not start with `__`. */\nexport interface Snapshot {\n\tcollections: Record<string, unknown[]>;\n\tfiles: SnapshotFile[];\n}\n\n/** Key-derivation parameters. Stored cleartext so older files still decode. */\nexport interface KdfParams {\n\talgo: 'argon2id';\n\tsalt: string;\n\tm: number;\n\tt: number;\n\tp: number;\n}\n\n/**\n * One wrap of the random data key under one password; any slot's password\n * opens the backup. Adding or removing a slot leaves the data key alone.\n * Changing a password rotates the data key (setEncryption) - that is the\n * operation that actually revokes access.\n */\nexport interface PasswordSlot {\n\t/** Random id so an app can list or drop a slot without knowing its\n\t * password. Cleartext, not authenticated. */\n\tid: string;\n\t/** Absent on password slots, so files written before external keys\n\t * existed still parse. */\n\tkind?: 'password';\n\tkdf: KdfParams;\n\t/** 96-bit IV of the wrap, base64. */\n\tiv: string;\n\t/** AES-256-GCM(KEK, dataKey) with tag appended: 48 bytes, base64. */\n\twrapped: string;\n}\n\n/**\n * Data key wrapped under a caller-supplied 32-byte secret (passkey PRF,\n * hardware token). The library never performs the WebAuthn or hardware\n * exchange; the app derives the secret and hands it in. KEK is\n * HKDF-SHA256 of the secret - no Argon2, the input is already\n * high-entropy. Shares the `keys[]` table with password slots, so a\n * backup can hold e.g. a passkey plus a recovery password.\n */\nexport interface ExternalSlot {\n\tid: string;\n\tkind: 'external';\n\t/** App-owned locator for re-deriving the secret (say, a WebAuthn\n\t * credential id). Cleartext, never a security input. */\n\tkeyRef: string;\n\t/** 96-bit IV of the wrap, base64. */\n\tiv: string;\n\t/** AES-256-GCM(KEK, dataKey) with tag appended: 48 bytes, base64. */\n\twrapped: string;\n}\n\nexport type KeySlot = PasswordSlot | ExternalSlot;\n\n/**\n * Group mode (format 2): the per-publication AES key wrapped for one\n * recipient. `kid` = first 8 bytes of SHA-256(recipient X25519 public),\n * base64 - a locator, not a name. `epk` is the ephemeral X25519 public;\n * `wrap` is AES-256-GCM(dataKey) under HKDF of the ECDH shared secret.\n */\nexport interface RecipientStanza {\n\tkid: string;\n\tepk: string;\n\tiv: string;\n\twrap: string;\n}\n\n/**\n * Cleartext metadata: the `meta.json` entry of the ZIP.\n *\n * app/appVersion/createdAt are cosmetic and unauthenticated - never base a\n * security decision on them. In password-envelope mode the wrapped data key\n * authenticates the payload; in group mode the author's Ed25519 signature\n * (sig.bin) covers the exact meta.json and data.enc bytes.\n */\nexport interface Header {\n\t/** Format generation: 2 = plain ZIP, 3 = group, 4 = password envelope.\n\t * Absent means 2. */\n\tformat?: number;\n\tapp: string;\n\t/** Writing app's release version, informational. */\n\tappVersion?: string;\n\t/** Writing app's data schema version (createLocalStore `version`).\n\t * Distinct from appVersion: this one drives migration. */\n\tschemaVersion?: number;\n\tcreatedAt: string;\n\tencryption: 'none' | 'aes-256-gcm';\n\t/** 96-bit IV of data.enc, base64. Present when encrypted. */\n\tiv?: string;\n\t/** Group mode: data-key envelope scheme ('x25519-hkdf-sha256'). */\n\tkeying?: string;\n\t/** Group mode: author's Ed25519 public key. Trust only after verifying\n\t * sig.bin and membership in the group manifest. */\n\tauthor?: string;\n\t/** Group mode: one data-key envelope per recipient. */\n\trecipients?: RecipientStanza[];\n\t/** Password envelope only: the data key wrapped once per password.\n\t * Present iff format === 4. */\n\tkeys?: KeySlot[];\n}\n\n/** Options for writing a backup. */\nexport interface EncodeOptions {\n\tapp: string;\n\tappVersion?: string;\n\tschemaVersion?: number;\n\t/** Omit or leave empty for an unencrypted backup (a plain, readable ZIP). */\n\tpassword?: string;\n\t/** Group mode: encrypt to these recipients (raw X25519 publics, base64)\n\t * under a fresh data key and sign with the author's Ed25519 key.\n\t * Mutually exclusive with `password`. */\n\tgroup?: {\n\t\trecipients: string[];\n\t\tsign: { pub: string; priv: string };\n\t};\n\t/** README text shipped inside an encrypted backup, for whoever opens the\n\t * ZIP by hand. Defaults to a neutral note; apps should brand it. */\n\treadme?: string;\n\t/** Rewrite path: reuse this exact envelope (held data key + slot table\n\t * from the last read) so a writer that knows only one password keeps\n\t * every other slot. Mutually exclusive with `password` and `group`. */\n\tenvelope?: { dataKey: Uint8Array; slots: KeySlot[] };\n\t/** Read the bytes back before returning them, and throw VERIFY_FAILED if\n\t * they do not hold what went in. Carried in the options rather than on the\n\t * builder so it survives every link of the chain: set on one link and lost\n\t * by the next is the silent failure this whole feature exists to prevent. */\n\tverify?: boolean;\n\t/** Extra secrets that ALSO open this backup, each getting its own key slot\n\t * around the same data key - typically a recovery code the user printed.\n\t * Only meaningful alongside `password`. */\n\textraSecrets?: string[];\n}\n","// A password strength policy the store can enforce and a UI can preview from\n// the same rules. Deliberately small: length plus character-class requirements,\n// no dictionary or breach checks (those need data the library does not ship).\n// Unicode-aware so an accented letter counts as a letter and an emoji counts as\n// one character, not two.\n\nexport interface PasswordPolicy {\n\t/** Minimum length in code points (so an emoji counts as one). Default 0. */\n\tminLength?: number;\n\t/** Require at least one lowercase letter (any script with case). */\n\trequireLowercase?: boolean;\n\t/** Require at least one uppercase letter (any script with case). */\n\trequireUppercase?: boolean;\n\t/** Require at least one digit. */\n\trequireDigit?: boolean;\n\t/** Require at least one symbol: anything that is not a letter or a number. */\n\trequireSymbol?: boolean;\n}\n\n/** A stable code for each unmet requirement, so the app maps it to its own copy\n * (like the error codes). `minLength` covers the length rule. */\nexport type PasswordRequirement = 'minLength' | 'lowercase' | 'uppercase' | 'digit' | 'symbol';\n\nexport interface PasswordCheck {\n\tok: boolean;\n\t/** The requirements the password fails, in a stable order. Empty when ok. */\n\tunmet: PasswordRequirement[];\n}\n\n/** Measure a password against a policy. Pure and synchronous: the same call\n * drives a live strength hint in the UI and the store's enforcement. An empty\n * or absent policy passes everything. */\nexport function checkPasswordPolicy(password: string, policy: PasswordPolicy): PasswordCheck {\n\tconst unmet: PasswordRequirement[] = [];\n\t// Count code points, not UTF-16 units, so a password of emoji is not\n\t// over-counted and a min-length rule stays intuitive.\n\tif ([...password].length < (policy.minLength ?? 0)) unmet.push('minLength');\n\tif (policy.requireLowercase && !/\\p{Ll}/u.test(password)) unmet.push('lowercase');\n\tif (policy.requireUppercase && !/\\p{Lu}/u.test(password)) unmet.push('uppercase');\n\tif (policy.requireDigit && !/\\p{Nd}/u.test(password)) unmet.push('digit');\n\tif (policy.requireSymbol && !/[^\\p{L}\\p{N}]/u.test(password)) unmet.push('symbol');\n\treturn { ok: unmet.length === 0, unmet };\n}\n","// The backup format: Snapshot in, portable ZIP out, and back. Plain archive\n// without a password, AES-256-GCM (over Argon2id) with one.\n//\n// const blob = await exportSnapshot(snapshot, { app: 'my-app', password });\n// const back = await importSnapshot(blob, { password });\n//\n// or fluent, same engine:\n//\n// const blob = await backup(snapshot).as('my-app').encryptedWith(password).toBlob();\n// const back = await restore(blob).withPassword(password).read();\n\nimport type { Snapshot, Header, EncodeOptions } from './types';\nimport { writeBox, readBox, readBoxMeta, asBytes } from './box';\n\nexport type {\n\tSnapshot,\n\tSnapshotFile,\n\tHeader,\n\tKdfParams,\n\tRecipientStanza,\n\tEncodeOptions,\n\tPasswordSlot,\n\tExternalSlot,\n\tKeySlot\n} from './types';\nexport { RESERVED_COLLECTION_PREFIX } from './types';\nexport {\n\tSelfstoreError,\n\tAuthExpiredError,\n\tisSelfstoreError,\n\tisAuthExpired,\n\terrorLabelKey,\n\ttype SelfstoreErrorCode\n} from './errors';\nexport { BACKUP_EXTENSION, BACKUP_MIME } from './box';\nexport {\n\tcheckPasswordPolicy,\n\ttype PasswordPolicy,\n\ttype PasswordCheck,\n\ttype PasswordRequirement\n} from './password-policy';\nexport {\n\tbackup,\n\trestore,\n\ttype BackupDraft,\n\ttype BackupBuilder,\n\ttype EncryptedBackupBuilder,\n\ttype RestoreBuilder\n} from './fluent';\nexport { verifyBackup, countsOf, type ExpectedContents } from './verify';\n\n/** Serialize a snapshot to a portable backup blob (compressed; encrypted if a password is given). */\nexport async function exportSnapshot(snapshot: Snapshot, opts: EncodeOptions): Promise<Blob> {\n\treturn new Blob([(await writeBox(snapshot, opts)) as BlobPart], { type: 'application/zip' });\n}\n\n/** Read a backup blob (or raw bytes) back into a snapshot. */\nexport async function importSnapshot(\n\tinput: Blob | Uint8Array,\n\topts: { password?: string } = {}\n): Promise<Snapshot> {\n\treturn readBox(await asBytes(input), opts.password);\n}\n\n/** Peek at a backup's cleartext metadata (app, date, whether it's encrypted) without decrypting. */\nexport async function inspect(input: Blob | Uint8Array): Promise<Header> {\n\treturn readBoxMeta(await asBytes(input));\n}\n\n/** True if the backup needs a password to import. */\nexport async function isEncrypted(input: Blob | Uint8Array): Promise<boolean> {\n\treturn (await inspect(input)).encryption !== 'none';\n}\n\n/** Re-encrypt under a new password. `from` opens the file, `to` protects the\n * result; omit `to` for an unencrypted backup. */\nexport async function changePassword(\n\tinput: Blob | Uint8Array,\n\topts: { from?: string; to?: string; readme?: string }\n): Promise<Blob> {\n\tconst bytes = await asBytes(input);\n\tconst meta = await readBoxMeta(bytes);\n\tconst snapshot = await readBox(bytes, opts.from);\n\treturn exportSnapshot(snapshot, {\n\t\tapp: meta.app,\n\t\tappVersion: meta.appVersion,\n\t\tschemaVersion: meta.schemaVersion,\n\t\tpassword: opts.to,\n\t\treadme: opts.readme\n\t});\n}\n","/**\n * Read a freshly written backup back, before anyone is told it exists.\n *\n * A backup encrypted with a key nobody can reproduce, truncated, or built from\n * an empty snapshot looks exactly like a good one: right name, right date,\n * plausible size. The difference only shows up on the day of the disaster, when\n * it is far too late to make another. The only way to know is to open it.\n *\n * The cost is one decrypt of data the app already holds - a few hundred\n * milliseconds at these sizes, once per save. Cheap enough that the honest\n * default is to do it, and cheap enough that a host doing it on every write is\n * not being wasteful.\n */\n\nimport { SelfstoreError } from './errors';\nimport { importSnapshot } from './index';\nimport type { Snapshot } from './types';\n\n/** What the caller believes it just wrote. */\nexport interface ExpectedContents {\n\t/** Per-collection record counts. Only the named collections are checked, so\n\t * a caller can pin the two that matter instead of listing everything. */\n\tcounts?: Record<string, number>;\n\t/** Number of binary files. */\n\tfiles?: number;\n}\n\n/**\n * Open `bytes` and check they hold what was meant to be written. Throws\n * VERIFY_FAILED otherwise - never returns false, because a caller that ignores\n * a boolean is exactly how a backup that lies gets announced as done.\n */\nexport async function verifyBackup(\n\tbytes: Blob | Uint8Array,\n\topts: { password?: string; expect?: ExpectedContents } = {}\n): Promise<void> {\n\tlet read: Snapshot;\n\ttry {\n\t\tread = await importSnapshot(bytes, { password: opts.password });\n\t} catch {\n\t\t// The password is the likeliest culprit and the most expensive one to\n\t\t// discover late: an archive nobody can open is not a backup.\n\t\tthrow new SelfstoreError('VERIFY_FAILED', 'The backup just written could not be read back.');\n\t}\n\tconst expect = opts.expect;\n\tif (!expect) return;\n\tfor (const [name, count] of Object.entries(expect.counts ?? {})) {\n\t\tconst got = read.collections[name]?.length ?? 0;\n\t\tif (got !== count) {\n\t\t\tthrow new SelfstoreError(\n\t\t\t\t'VERIFY_FAILED',\n\t\t\t\t`The backup just written holds ${got} \"${name}\" where ${count} were expected.`\n\t\t\t);\n\t\t}\n\t}\n\tif (expect.files !== undefined && read.files.length !== expect.files) {\n\t\tthrow new SelfstoreError(\n\t\t\t'VERIFY_FAILED',\n\t\t\t`The backup just written holds ${read.files.length} files where ${expect.files} were expected.`\n\t\t);\n\t}\n}\n\n/** Every collection's record count, for a caller that wants the whole snapshot\n * checked rather than picking which parts matter. */\nexport function countsOf(snapshot: Snapshot): ExpectedContents {\n\tconst counts: Record<string, number> = {};\n\tfor (const [name, rows] of Object.entries(snapshot.collections)) {\n\t\tcounts[name] = rows.length;\n\t}\n\treturn { counts, files: snapshot.files.length };\n}\n","// Fluent facade over the functional API. The chain is staged so an illegal\n// call order does not compile: backup() exposes only .as(), and .withReadme()\n// appears only after .encryptedWith() (the readme ships inside the encrypted\n// ZIP, so it means nothing on a plain one).\n//\n// const blob = await backup(snapshot).as('my-app', '1.2.0').encryptedWith(pw).toBlob();\n// const snap = await restore(file).withPassword(pw).read();\n\nimport type { Snapshot, Header, EncodeOptions } from './types';\nimport { RESERVED_COLLECTION_PREFIX } from './types';\nimport { writeBox, readBox, readBoxMeta, asBytes, BACKUP_MIME, BACKUP_EXTENSION } from './box';\nimport { verifyBackup, countsOf } from './verify';\n\n/** Start writing a backup. Naming the app via .as() is the required next step. */\nexport function backup(snapshot: Snapshot): BackupDraft {\n\treturn new BackupDraft(snapshot);\n}\n\n/** Start reading a backup (a picked File, a fetched Blob, or raw bytes). */\nexport function restore(input: Blob | Uint8Array): RestoreBuilder {\n\treturn new RestoreBuilder(input);\n}\n\n// Validation lives in the constructor, not the factory, so direct\n// construction cannot bypass it.\nexport class BackupDraft {\n\tconstructor(private readonly snapshot: Snapshot) {\n\t\tfor (const name of Object.keys(snapshot.collections)) {\n\t\t\tif (name.startsWith(RESERVED_COLLECTION_PREFIX)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`backup(): collection \"${name}\" uses the reserved \"${RESERVED_COLLECTION_PREFIX}\" prefix (library bookkeeping) - rename it`\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Name the writing app (stored cleartext in the backup's metadata). */\n\tas(app: string, appVersion?: string): BackupBuilder {\n\t\treturn new BackupBuilder(this.snapshot, { app, appVersion });\n\t}\n}\n\nexport class BackupBuilder {\n\tconstructor(\n\t\tprotected readonly snapshot: Snapshot,\n\t\tprotected readonly opts: EncodeOptions\n\t) {}\n\n\t/** Encrypt the backup (AES-256-GCM over an Argon2id-derived key). */\n\tencryptedWith(password: string): EncryptedBackupBuilder {\n\t\treturn new EncryptedBackupBuilder(this.snapshot, { ...this.opts, password });\n\t}\n\n\t/**\n\t * Read the backup back before handing it over, and throw VERIFY_FAILED if it\n\t * does not hold what went in.\n\t *\n\t * A backup encrypted with a key nobody can reproduce, truncated, or built\n\t * from an empty snapshot looks exactly like a good one: right name, right\n\t * date, plausible size. The difference only shows up on the day of the\n\t * disaster, when it is too late to make another. The only way to know is to\n\t * open it, and it costs one decrypt of data the app already holds.\n\t *\n\t * Applies to every terminal below, so a host cannot verify and then write a\n\t * different set of bytes by accident.\n\t */\n\tverified(): BackupBuilder {\n\t\treturn new BackupBuilder(this.snapshot, { ...this.opts, verify: true });\n\t}\n\n\t/** The backup as raw bytes. */\n\tasync toBytes(): Promise<Uint8Array> {\n\t\tconst bytes = await writeBox(this.snapshot, this.opts);\n\t\tif (this.opts.verify) {\n\t\t\tawait verifyBackup(bytes, { password: this.opts.password, expect: countsOf(this.snapshot) });\n\t\t}\n\t\treturn bytes;\n\t}\n\n\t/** The backup as a Blob, ready to upload or hand to a save dialog. */\n\tasync toBlob(): Promise<Blob> {\n\t\treturn new Blob([(await this.toBytes()) as BlobPart], { type: BACKUP_MIME });\n\t}\n\n\t/** Save the backup to disk (File System Access API, else a download).\n\t * Browser-only terminal; defaults to `<app>-<date>.zip`. False when the\n\t * user closed the save dialog: nothing was written, so do not tell them\n\t * they have a backup.\n\t *\n\t * Asks WHERE first, encrypts after. The save dialog needs the transient\n\t * activation of the click that led here, and building an encrypted backup\n\t * outlives it (Argon2id is deliberately slow): encrypting first made the\n\t * browser refuse the dialog and silently download instead, turning a file\n\t * the user chose into one they have to go and find. */\n\tasync toDisk(filename?: string): Promise<boolean> {\n\t\tconst name =\n\t\t\tfilename ?? `${this.opts.app}-${new Date().toISOString().slice(0, 10)}${BACKUP_EXTENSION}`;\n\t\tconst { pickSaveHandle, writeToHandle, downloadBlob } = await import('./targets/local');\n\t\tconst cible = await pickSaveHandle(name);\n\t\tif (cible === 'CANCELLED') return false;\n\t\tconst blob = await this.toBlob();\n\t\tif (cible) {\n\t\t\tawait writeToHandle(cible.handle, blob);\n\t\t\treturn true;\n\t\t}\n\t\tdownloadBlob(blob, name);\n\t\treturn true;\n\t}\n}\n\nexport class EncryptedBackupBuilder extends BackupBuilder {\n\tconstructor(snapshot: Snapshot, opts: EncodeOptions) {\n\t\tif (!opts.password) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'EncryptedBackupBuilder: a password is required - use backup(snapshot).as(app).encryptedWith(password)'\n\t\t\t);\n\t\t}\n\t\tsuper(snapshot, opts);\n\t}\n\n\t/** Same guarantee, keeping the encrypted chain's own links reachable. */\n\toverride verified(): EncryptedBackupBuilder {\n\t\treturn new EncryptedBackupBuilder(this.snapshot, { ...this.opts, verify: true });\n\t}\n\n\t/** Brand the README shipped inside the encrypted ZIP. */\n\twithReadme(text: string): EncryptedBackupBuilder {\n\t\treturn new EncryptedBackupBuilder(this.snapshot, { ...this.opts, readme: text });\n\t}\n\n\t/**\n\t * A second secret that also opens this backup - a recovery code the user\n\t * printed and put away.\n\t *\n\t * A password that only lives in one person's memory is the likeliest way a\n\t * local-first backup dies: no server can reset it, so the day it is\n\t * forgotten the data is gone for good. The envelope has always held several\n\t * key slots (see `keys[]` in the header); this exposes them where a backup\n\t * is actually written. Each secret wraps the SAME data key, so either one\n\t * opens the file and neither can read the other.\n\t *\n\t * Call it more than once for more than one recovery secret. Reading needs no\n\t * change: `restore(...).withPassword(code)` already tries every slot.\n\t */\n\talsoOpenedWith(secret: string): EncryptedBackupBuilder {\n\t\tif (!secret) {\n\t\t\tthrow new TypeError('alsoOpenedWith(): a non-empty secret is required.');\n\t\t}\n\t\treturn new EncryptedBackupBuilder(this.snapshot, {\n\t\t\t...this.opts,\n\t\t\textraSecrets: [...(this.opts.extraSecrets ?? []), secret]\n\t\t});\n\t}\n}\n\nexport class RestoreBuilder {\n\tprivate password?: string;\n\n\tconstructor(private readonly input: Blob | Uint8Array) {}\n\n\t/** Accepts undefined so callers can pass straight through from an optional field. */\n\twithPassword(password?: string): this {\n\t\tthis.password = password || undefined;\n\t\treturn this;\n\t}\n\n\t/** The cleartext metadata (app, date, encryption), without decrypting. */\n\tasync meta(): Promise<Header> {\n\t\treturn readBoxMeta(await asBytes(this.input));\n\t}\n\n\t/** True if reading will require a password. */\n\tasync isEncrypted(): Promise<boolean> {\n\t\treturn (await this.meta()).encryption !== 'none';\n\t}\n\n\t/** Read the backup into a snapshot. Reserved `__*` collections (library\n\t * bookkeeping) are stripped. PASSWORD_REQUIRED when encrypted and no\n\t * password given, DECRYPT_FAILED on a wrong one. */\n\tasync read(): Promise<Snapshot> {\n\t\tconst snap = await readBox(await asBytes(this.input), this.password);\n\t\tconst collections = Object.fromEntries(\n\t\t\tObject.entries(snap.collections).filter(\n\t\t\t\t([name]) => !name.startsWith(RESERVED_COLLECTION_PREFIX)\n\t\t\t)\n\t\t);\n\t\treturn { collections, files: snap.files };\n\t}\n}\n"]}
@@ -25,5 +25,5 @@ function isAuthExpired(e) {
25
25
  }
26
26
 
27
27
  export { AuthExpiredError, SelfstoreError, errorLabelKey, isAuthExpired, isSelfstoreError };
28
- //# sourceMappingURL=chunk-SFF7KKM4.js.map
29
- //# sourceMappingURL=chunk-SFF7KKM4.js.map
28
+ //# sourceMappingURL=chunk-CPN2KUD5.js.map
29
+ //# sourceMappingURL=chunk-CPN2KUD5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/selfstore/errors.ts"],"names":[],"mappings":";AAmCO,SAAS,cAAc,IAAA,EAAkC;AAC/D,EAAA,OAAO,QAAA,GAAW,IAAA,CAAK,WAAA,EAAY,CAAE,OAAA,CAAQ,WAAA,EAAa,CAAC,EAAA,EAAI,CAAA,KAAc,CAAA,CAAE,WAAA,EAAa,CAAA;AAC7F;AAEO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EACzC,WAAA,CACU,MACT,OAAA,EACC;AACD,IAAA,KAAA,CAAM,OAAO,CAAA;AAHJ,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAIT,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AAAA,EACb;AAAA,EALU,IAAA;AAMX;AASO,IAAM,gBAAA,GAAN,cAA+B,cAAA,CAAe;AAAA,EACpD,WAAA,CAAY,UAAU,mDAAA,EAAqD;AAC1E,IAAA,KAAA,CAAM,gBAAgB,OAAO,CAAA;AAC7B,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AAAA,EACb;AACD;AAMO,SAAS,iBAAiB,CAAA,EAAiC;AACjE,EAAA,OACC,CAAA,YAAa,KAAA,IACb,OAAQ,CAAA,CAAyB,IAAA,KAAS,aACzC,CAAA,CAAE,IAAA,KAAS,gBAAA,IAAoB,CAAA,CAAE,IAAA,KAAS,kBAAA,CAAA;AAE7C;AAGO,SAAS,cAAc,CAAA,EAAqB;AAClD,EAAA,IAAI,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,MAAM,OAAO,KAAA;AAChD,EAAA,OAAQ,EAAyB,IAAA,KAAS,cAAA;AAC3C","file":"chunk-CPN2KUD5.js","sourcesContent":["// One stable error-code enum for the whole library, format layer and\n// persistence layer alike. Codes may be added in a minor release (keep a\n// default branch in exhaustive switches); existing codes never change meaning.\n\nexport type SelfstoreErrorCode =\n\t// backup format / crypto\n\t| 'BAD_FORMAT' // not a backup file / corrupt framing\n\t| 'UNSUPPORTED_VERSION' // file (or cipher/KDF) from a newer format version\n\t| 'PASSWORD_REQUIRED' // encrypted backup opened without a password, or vault used before unlock()\n\t| 'DECRYPT_FAILED' // wrong password, or tampered/corrupt ciphertext\n\t| 'TOO_LARGE' // archive entry exceeds the size guard (zip-bomb defence)\n\t| 'VERIFY_FAILED' // a freshly written backup did not read back as expected: do not announce it\n\t| 'FOREIGN_BACKUP' // the backup names another app in its header: refused before any password is asked\n\t// durable targets / store lifecycle\n\t| 'AUTH_EXPIRED' // access genuinely lost: only a user gesture (reconnect) fixes it\n\t| 'TARGET_UNAVAILABLE' // transient: offline, cold start, 5xx - retry later\n\t| 'TARGET_WRITE_FAILED' // destination refused or failed the write (non-auth), retryable\n\t| 'TARGET_GONE' // destination permanently unwritable (file deleted, permission withdrawn, storage full); retrying cannot fix it\n\t| 'NOT_CONNECTED' // no connected destination (no file id, no config)\n\t| 'WEAK_PASSWORD' // password fails the store's configured passwordPolicy\n\t| 'ENCRYPTION_REQUIRED' // store set requireEncryption: a plaintext attach, backup or export is refused\n\t| 'UNEXPECTEDLY_UNENCRYPTED' // downgrade guard: expected encrypted, found plaintext\n\t| 'SCHEMA_TOO_NEW' // data written by a newer app schema: update the app to sync again\n\t// passwordless groups (see PEERS.md)\n\t| 'IDENTITY_REQUIRED' // group-encrypted copy opened without a member identity\n\t| 'SIGNATURE_INVALID' // copy/manifest signature failed, or author not a trusted member\n\t| 'NOT_A_RECIPIENT' // valid group copy, but no envelope for this identity\n\t| 'MANIFEST_ROLLBACK'; // membership manifest older than one already applied\n\n/**\n * i18n key for an error code: lower-camel-cased under `error.`, e.g.\n * 'error.authExpired'. The library ships the key, the app owns the copy;\n * consumers never have to show the raw developer message. Deterministic, so\n * codes added later get a key for free - keep a fallback for unknown ones.\n */\nexport function errorLabelKey(code: SelfstoreErrorCode): string {\n\treturn 'error.' + code.toLowerCase().replace(/_([a-z])/g, (_m, c: string) => c.toUpperCase());\n}\n\nexport class SelfstoreError extends Error {\n\tconstructor(\n\t\treadonly code: SelfstoreErrorCode,\n\t\tmessage: string\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'SelfstoreError';\n\t}\n}\n\n/**\n * Genuine loss of access to a destination (session gone, token revoked):\n * only a user gesture fixes it. Anything else a target throws is treated as\n * transient and retried, so a network hiccup never raises the blocking\n * reconnect gate over a still-valid connection. Custom targets and DriveAuth\n * implementations throw this to signal the genuine case.\n */\nexport class AuthExpiredError extends SelfstoreError {\n\tconstructor(message = 'Access to the destination expired or was revoked.') {\n\t\tsuper('AUTH_EXPIRED', message);\n\t\tthis.name = 'AuthExpiredError';\n\t}\n}\n\n/**\n * Shape check rather than instanceof, so it survives two bundled copies of\n * the library. The name check keeps foreign coded errors (ENOENT...) out.\n */\nexport function isSelfstoreError(e: unknown): e is SelfstoreError {\n\treturn (\n\t\te instanceof Error &&\n\t\ttypeof (e as { code?: unknown }).code === 'string' &&\n\t\t(e.name === 'SelfstoreError' || e.name === 'AuthExpiredError')\n\t);\n}\n\n/** True on genuine access loss, false on transient blips. */\nexport function isAuthExpired(e: unknown): boolean {\n\tif (typeof e !== 'object' || e === null) return false;\n\treturn (e as { code?: unknown }).code === 'AUTH_EXPIRED';\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { BACKUP_EXTENSION, BACKUP_MIME } from './chunk-ZDHTKFAL.js';
1
+ import { BACKUP_EXTENSION, BACKUP_MIME } from './chunk-BNDFMU3J.js';
2
2
 
3
3
  // src/selfstore/targets/local.ts
4
4
  async function pickSaveHandle(filename) {
@@ -61,5 +61,5 @@ function pickFromDisk() {
61
61
  }
62
62
 
63
63
  export { datedName, downloadBlob, pickFromDisk, pickSaveHandle, saveToDisk, writeToHandle };
64
- //# sourceMappingURL=chunk-53WWPEML.js.map
65
- //# sourceMappingURL=chunk-53WWPEML.js.map
64
+ //# sourceMappingURL=chunk-HDR75TQ7.js.map
65
+ //# sourceMappingURL=chunk-HDR75TQ7.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/selfstore/targets/local.ts"],"names":[],"mappings":";;;AA0BA,eAAsB,eACrB,QAAA,EACuD;AACvD,EAAA,MAAM,SACL,MAAA,CAGC,kBAAA;AACF,EAAA,IAAI,CAAC,QAAQ,OAAO,IAAA;AACpB,EAAA,IAAI;AACH,IAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO;AAAA,MAC3B,aAAA,EAAe,QAAA;AAAA,MACf,KAAA,EAAO,CAAC,EAAE,WAAA,EAAa,oBAAoB,MAAA,EAAQ,EAAE,CAAC,WAAW,GAAG,CAAC,gBAAgB,CAAA,IAAK;AAAA,KAC1F,CAAA;AACD,IAAA,OAAO,EAAE,MAAA,EAAO;AAAA,EACjB,SAAS,CAAA,EAAG;AACX,IAAA,IAAI,CAAA,YAAa,YAAA,IAAgB,CAAA,CAAE,IAAA,KAAS,cAAc,OAAO,WAAA;AAEjE,IAAA,OAAO,IAAA;AAAA,EACR;AACD;AAGA,eAAsB,aAAA,CAAc,QAAoB,IAAA,EAA2B;AAClF,EAAA,MAAM,QAAA,GAAW,MAAM,MAAA,CAAO,cAAA,EAAe;AAC7C,EAAA,MAAM,QAAA,CAAS,MAAM,IAAI,CAAA;AACzB,EAAA,MAAM,SAA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AA,CAAK,IAAA,CAAK,QAAA,EAAU,CAAC,CAAA,CAAA,EAAI,IAAA,CAAK,IAAA,CAAK,UAAA,EAAY,CAAC,CAAA,CAAA;AACrD,EAAA,MAAM,GAAA,GAAM,QAAA,CAAS,WAAA,CAAY,GAAG,CAAA;AACpC,EAAA,OAAO,OAAO,CAAA,GACX,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,KAAK,KACpB,CAAA,EAAG,QAAA,CAAS,MAAM,CAAA,EAAG,GAAG,CAAC,CAAA,CAAA,EAAI,KAAK,GAAG,QAAA,CAAS,KAAA,CAAM,GAAG,CAAC,CAAA,CAAA;AAC5D;AAGO,SAAS,YAAA,GAAqC;AACpD,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY;AAC/B,IAAA,MAAM,KAAA,GAAQ,QAAA,CAAS,aAAA,CAAc,OAAO,CAAA;AAC5C,IAAA,KAAA,CAAM,IAAA,GAAO,MAAA;AAEb,IAAA,KAAA,CAAM,MAAA,GAAS,+CAAA;AACf,IAAA,KAAA,CAAM,WAAW,MAAM,OAAA,CAAQ,MAAM,KAAA,GAAQ,CAAC,KAAK,IAAI,CAAA;AAEvD,IAAA,KAAA,CAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,IAAI,CAAA;AAEnC,IAAA,KAAA,CAAM,MAAM,OAAA,GAAU,MAAA;AACtB,IAAA,QAAA,CAAS,IAAA,CAAK,YAAY,KAAK,CAAA;AAC/B,IAAA,KAAA,CAAM,KAAA,EAAM;AACZ,IAAA,KAAA,CAAM,MAAA,EAAO;AAAA,EACd,CAAC,CAAA;AACF","file":"chunk-53WWPEML.js","sourcesContent":["/**\n * Local-disk helpers: the DOM edge of selfstore, kept out of the core so the\n * core stays environment-agnostic and testable.\n */\n\nimport { BACKUP_EXTENSION, BACKUP_MIME } from '../index';\n\n/** The slice of FileSystemFileHandle this module needs. */\nexport interface SaveHandle {\n\tcreateWritable(): Promise<{ write(d: Blob): Promise<void>; close(): Promise<void> }>;\n}\n\n/**\n * Ask the user where to save, and nothing else.\n *\n * Split out because ORDER decides whether the dialog opens at all. The picker\n * needs the transient user activation of the click, and that activation expires\n * while an encrypted backup is being built (Argon2id is deliberately slow). Ask\n * first, build after, and the dialog is still allowed; build first and the\n * browser refuses it. Hosts that saw a silent download instead of the save\n * dialog were hitting exactly that.\n *\n * Null when the browser has no picker at all (Firefox, Safari) or when it\n * refuses for any reason other than a cancellation - the caller then falls back\n * to a download. Throws nothing; a cancelled dialog is reported as CANCELLED.\n */\nexport async function pickSaveHandle(\n\tfilename: string\n): Promise<{ handle: SaveHandle } | 'CANCELLED' | null> {\n\tconst picker = (\n\t\twindow as unknown as {\n\t\t\tshowSaveFilePicker?: (o: unknown) => Promise<SaveHandle>;\n\t\t}\n\t).showSaveFilePicker;\n\tif (!picker) return null;\n\ttry {\n\t\tconst handle = await picker({\n\t\t\tsuggestedName: filename,\n\t\t\ttypes: [{ description: 'selfstore backup', accept: { [BACKUP_MIME]: [BACKUP_EXTENSION] } }]\n\t\t});\n\t\treturn { handle };\n\t} catch (e) {\n\t\tif (e instanceof DOMException && e.name === 'AbortError') return 'CANCELLED';\n\t\t// Anything else (no activation left, policy): the download still works.\n\t\treturn null;\n\t}\n}\n\n/** Write a blob through a handle obtained earlier by pickSaveHandle. */\nexport async function writeToHandle(handle: SaveHandle, blob: Blob): Promise<void> {\n\tconst writable = await handle.createWritable();\n\tawait writable.write(blob);\n\tawait writable.close();\n}\n\n/** Hand the blob to the browser's download machinery. No cancel to observe:\n * once taken, the host has done all it can. */\nexport function downloadBlob(blob: Blob, filename: string): void {\n\tconst url = URL.createObjectURL(blob);\n\tconst a = document.createElement('a');\n\ta.href = url;\n\ta.download = filename;\n\tdocument.body.appendChild(a);\n\ta.click();\n\ta.remove();\n\tURL.revokeObjectURL(url);\n}\n\n/**\n * Save a backup blob to disk via the File System Access API, else a download.\n *\n * Resolves TRUE when bytes were handed to the browser, FALSE when the user\n * closed the save dialog. Callers must branch on it: a host that records \"last\n * backup: today\" after a cancelled dialog tells the user they are safe when no\n * file exists, and that lie only surfaces the day they need the file.\n *\n * Takes a ready blob, so the dialog opens only after the blob was built. When\n * that blob is an encrypted backup, prefer asking first: see pickSaveHandle.\n */\nexport async function saveToDisk(blob: Blob, filename: string): Promise<boolean> {\n\tconst picked = await pickSaveHandle(filename);\n\tif (picked === 'CANCELLED') return false;\n\tif (picked) {\n\t\tawait writeToHandle(picked.handle, blob);\n\t\treturn true;\n\t}\n\tdownloadBlob(blob, datedName(filename));\n\treturn true;\n}\n\n/**\n * The same name, stamped to the minute.\n *\n * Used only on the download path, and the reasoning is worth stating because it\n * looks backwards. Through a handle the app rewrites the SAME file, so the name\n * must stay stable. A download never replaces anything: the browser appends\n * \" (1)\", \" (2)\", and no web API can stop it. The pile forms either way - so it\n * may as well be readable. A dated series says at a glance which one is the\n * latest and lets the user step back to an earlier one; \"backup (7).zip\" says\n * neither when, nor in what order.\n */\nexport function datedName(filename: string, when = new Date()): string {\n\tconst deux = (n: number) => String(n).padStart(2, '0');\n\tconst stamp =\n\t\t`${when.getFullYear()}-${deux(when.getMonth() + 1)}-${deux(when.getDate())}` +\n\t\t`-${deux(when.getHours())}h${deux(when.getMinutes())}`;\n\tconst dot = filename.lastIndexOf('.');\n\treturn dot <= 0\n\t\t? `${filename}-${stamp}`\n\t\t: `${filename.slice(0, dot)}-${stamp}${filename.slice(dot)}`;\n}\n\n/** Prompt the user to pick a backup file from disk. Resolves null if cancelled. */\nexport function pickFromDisk(): Promise<File | null> {\n\treturn new Promise((resolve) => {\n\t\tconst input = document.createElement('input');\n\t\tinput.type = 'file';\n\t\t// octet-stream: some providers serve a downloaded ZIP under that type.\n\t\tinput.accept = '.zip,application/zip,application/octet-stream';\n\t\tinput.onchange = () => resolve(input.files?.[0] ?? null);\n\t\t// Without this, a cancelled dialog leaves the promise pending forever.\n\t\tinput.oncancel = () => resolve(null);\n\t\t// Some browsers need the input in the DOM for the dialog to open.\n\t\tinput.style.display = 'none';\n\t\tdocument.body.appendChild(input);\n\t\tinput.click();\n\t\tinput.remove();\n\t});\n}\n"]}
1
+ {"version":3,"sources":["../src/selfstore/targets/local.ts"],"names":[],"mappings":";;;AA0BA,eAAsB,eACrB,QAAA,EACuD;AACvD,EAAA,MAAM,SACL,MAAA,CAGC,kBAAA;AACF,EAAA,IAAI,CAAC,QAAQ,OAAO,IAAA;AACpB,EAAA,IAAI;AACH,IAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO;AAAA,MAC3B,aAAA,EAAe,QAAA;AAAA,MACf,KAAA,EAAO,CAAC,EAAE,WAAA,EAAa,oBAAoB,MAAA,EAAQ,EAAE,CAAC,WAAW,GAAG,CAAC,gBAAgB,CAAA,IAAK;AAAA,KAC1F,CAAA;AACD,IAAA,OAAO,EAAE,MAAA,EAAO;AAAA,EACjB,SAAS,CAAA,EAAG;AACX,IAAA,IAAI,CAAA,YAAa,YAAA,IAAgB,CAAA,CAAE,IAAA,KAAS,cAAc,OAAO,WAAA;AAEjE,IAAA,OAAO,IAAA;AAAA,EACR;AACD;AAGA,eAAsB,aAAA,CAAc,QAAoB,IAAA,EAA2B;AAClF,EAAA,MAAM,QAAA,GAAW,MAAM,MAAA,CAAO,cAAA,EAAe;AAC7C,EAAA,MAAM,QAAA,CAAS,MAAM,IAAI,CAAA;AACzB,EAAA,MAAM,SAAS,KAAA,EAAM;AACtB;AAIO,SAAS,YAAA,CAAa,MAAY,QAAA,EAAwB;AAChE,EAAA,MAAM,GAAA,GAAM,GAAA,CAAI,eAAA,CAAgB,IAAI,CAAA;AACpC,EAAA,MAAM,CAAA,GAAI,QAAA,CAAS,aAAA,CAAc,GAAG,CAAA;AACpC,EAAA,CAAA,CAAE,IAAA,GAAO,GAAA;AACT,EAAA,CAAA,CAAE,QAAA,GAAW,QAAA;AACb,EAAA,QAAA,CAAS,IAAA,CAAK,YAAY,CAAC,CAAA;AAC3B,EAAA,CAAA,CAAE,KAAA,EAAM;AACR,EAAA,CAAA,CAA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AA;AAC5D;AAGO,SAAS,YAAA,GAAqC;AACpD,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY;AAC/B,IAAA,MAAM,KAAA,GAAQ,QAAA,CAAS,aAAA,CAAc,OAAO,CAAA;AAC5C,IAAA,KAAA,CAAM,IAAA,GAAO,MAAA;AAEb,IAAA,KAAA,CAAM,MAAA,GAAS,+CAAA;AACf,IAAA,KAAA,CAAM,WAAW,MAAM,OAAA,CAAQ,MAAM,KAAA,GAAQ,CAAC,KAAK,IAAI,CAAA;AAEvD,IAAA,KAAA,CAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,IAAI,CAAA;AAEnC,IAAA,KAAA,CAAM,MAAM,OAAA,GAAU,MAAA;AACtB,IAAA,QAAA,CAAS,IAAA,CAAK,YAAY,KAAK,CAAA;AAC/B,IAAA,KAAA,CAAM,KAAA,EAAM;AACZ,IAAA,KAAA,CAAM,MAAA,EAAO;AAAA,EACd,CAAC,CAAA;AACF","file":"chunk-HDR75TQ7.js","sourcesContent":["/**\n * Local-disk helpers: the DOM edge of selfstore, kept out of the core so the\n * core stays environment-agnostic and testable.\n */\n\nimport { BACKUP_EXTENSION, BACKUP_MIME } from '../index';\n\n/** The slice of FileSystemFileHandle this module needs. */\nexport interface SaveHandle {\n\tcreateWritable(): Promise<{ write(d: Blob): Promise<void>; close(): Promise<void> }>;\n}\n\n/**\n * Ask the user where to save, and nothing else.\n *\n * Split out because ORDER decides whether the dialog opens at all. The picker\n * needs the transient user activation of the click, and that activation expires\n * while an encrypted backup is being built (Argon2id is deliberately slow). Ask\n * first, build after, and the dialog is still allowed; build first and the\n * browser refuses it. Hosts that saw a silent download instead of the save\n * dialog were hitting exactly that.\n *\n * Null when the browser has no picker at all (Firefox, Safari) or when it\n * refuses for any reason other than a cancellation - the caller then falls back\n * to a download. Throws nothing; a cancelled dialog is reported as CANCELLED.\n */\nexport async function pickSaveHandle(\n\tfilename: string\n): Promise<{ handle: SaveHandle } | 'CANCELLED' | null> {\n\tconst picker = (\n\t\twindow as unknown as {\n\t\t\tshowSaveFilePicker?: (o: unknown) => Promise<SaveHandle>;\n\t\t}\n\t).showSaveFilePicker;\n\tif (!picker) return null;\n\ttry {\n\t\tconst handle = await picker({\n\t\t\tsuggestedName: filename,\n\t\t\ttypes: [{ description: 'selfstore backup', accept: { [BACKUP_MIME]: [BACKUP_EXTENSION] } }]\n\t\t});\n\t\treturn { handle };\n\t} catch (e) {\n\t\tif (e instanceof DOMException && e.name === 'AbortError') return 'CANCELLED';\n\t\t// Anything else (no activation left, policy): the download still works.\n\t\treturn null;\n\t}\n}\n\n/** Write a blob through a handle obtained earlier by pickSaveHandle. */\nexport async function writeToHandle(handle: SaveHandle, blob: Blob): Promise<void> {\n\tconst writable = await handle.createWritable();\n\tawait writable.write(blob);\n\tawait writable.close();\n}\n\n/** Hand the blob to the browser's download machinery. No cancel to observe:\n * once taken, the host has done all it can. */\nexport function downloadBlob(blob: Blob, filename: string): void {\n\tconst url = URL.createObjectURL(blob);\n\tconst a = document.createElement('a');\n\ta.href = url;\n\ta.download = filename;\n\tdocument.body.appendChild(a);\n\ta.click();\n\ta.remove();\n\tURL.revokeObjectURL(url);\n}\n\n/**\n * Save a backup blob to disk via the File System Access API, else a download.\n *\n * Resolves TRUE when bytes were handed to the browser, FALSE when the user\n * closed the save dialog. Callers must branch on it: a host that records \"last\n * backup: today\" after a cancelled dialog tells the user they are safe when no\n * file exists, and that lie only surfaces the day they need the file.\n *\n * Takes a ready blob, so the dialog opens only after the blob was built. When\n * that blob is an encrypted backup, prefer asking first: see pickSaveHandle.\n */\nexport async function saveToDisk(blob: Blob, filename: string): Promise<boolean> {\n\tconst picked = await pickSaveHandle(filename);\n\tif (picked === 'CANCELLED') return false;\n\tif (picked) {\n\t\tawait writeToHandle(picked.handle, blob);\n\t\treturn true;\n\t}\n\tdownloadBlob(blob, datedName(filename));\n\treturn true;\n}\n\n/**\n * The same name, stamped to the minute.\n *\n * Used only on the download path, and the reasoning is worth stating because it\n * looks backwards. Through a handle the app rewrites the SAME file, so the name\n * must stay stable. A download never replaces anything: the browser appends\n * \" (1)\", \" (2)\", and no web API can stop it. The pile forms either way - so it\n * may as well be readable. A dated series says at a glance which one is the\n * latest and lets the user step back to an earlier one; \"backup (7).zip\" says\n * neither when, nor in what order.\n */\nexport function datedName(filename: string, when = new Date()): string {\n\tconst deux = (n: number) => String(n).padStart(2, '0');\n\tconst stamp =\n\t\t`${when.getFullYear()}-${deux(when.getMonth() + 1)}-${deux(when.getDate())}` +\n\t\t`-${deux(when.getHours())}h${deux(when.getMinutes())}`;\n\tconst dot = filename.lastIndexOf('.');\n\treturn dot <= 0\n\t\t? `${filename}-${stamp}`\n\t\t: `${filename.slice(0, dot)}-${stamp}${filename.slice(dot)}`;\n}\n\n/** Prompt the user to pick a backup file from disk. Resolves null if cancelled. */\nexport function pickFromDisk(): Promise<File | null> {\n\treturn new Promise((resolve) => {\n\t\tconst input = document.createElement('input');\n\t\tinput.type = 'file';\n\t\t// octet-stream: some providers serve a downloaded ZIP under that type.\n\t\tinput.accept = '.zip,application/zip,application/octet-stream';\n\t\tinput.onchange = () => resolve(input.files?.[0] ?? null);\n\t\t// Without this, a cancelled dialog leaves the promise pending forever.\n\t\tinput.oncancel = () => resolve(null);\n\t\t// Some browsers need the input in the DOM for the dialog to open.\n\t\tinput.style.display = 'none';\n\t\tdocument.body.appendChild(input);\n\t\tinput.click();\n\t\tinput.remove();\n\t});\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { SelfstoreError } from './chunk-SFF7KKM4.js';
1
+ import { SelfstoreError } from './chunk-CPN2KUD5.js';
2
2
 
3
3
  // src/selfstore/base64.ts
4
4
  function toBase64(bytes) {
@@ -231,5 +231,5 @@ async function openExternalSlot(slot, secret) {
231
231
  }
232
232
 
233
233
  export { MAX_KEY_SLOTS, assertKdfBounds, deriveKey, freshKdfParams, fromBase64, gcmOpenAad, gcmSealAad, mintExternalSlot, mintSlot, openExternalSlot, openSlot, toBase64 };
234
- //# sourceMappingURL=chunk-CM3HSBCE.js.map
235
- //# sourceMappingURL=chunk-CM3HSBCE.js.map
234
+ //# sourceMappingURL=chunk-HK4VPO65.js.map
235
+ //# sourceMappingURL=chunk-HK4VPO65.js.map
@@ -1 +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,CAAW,GAAA,CAAI,IAAI,CAAA;AAAA,IACzB,aAAa,GAAA,CAAI,CAAA;AAAA,IACjB,YAAY,GAAA,CAAI,CAAA;AAAA,IAChB,YAAY,GAAA,CAAI,CAAA;AAAA,IAChB,UAAA,EAAY,SAAA;AAAA,IACZ,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,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-CM3HSBCE.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
+ {"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,GAA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(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,7 +1,7 @@
1
- import { connect4, connect3, isSupported, connect, openExisting, connect2 } from './chunk-XBPJRUA3.js';
2
- import { restore } from './chunk-ZDHTKFAL.js';
3
- import { makeMachine, withDeadline, toStoreError } from './chunk-OIAXYI35.js';
4
- import { SelfstoreError, isSelfstoreError } from './chunk-SFF7KKM4.js';
1
+ import { connect4, connect3, isSupported, connect, openExisting, connect2 } from './chunk-5NS7YQNP.js';
2
+ import { restore } from './chunk-BNDFMU3J.js';
3
+ import { makeMachine, withDeadline, toStoreError } from './chunk-U5F4GI7C.js';
4
+ import { SelfstoreError, isSelfstoreError } from './chunk-CPN2KUD5.js';
5
5
 
6
6
  // src/flows/connect.ts
7
7
  var DEFAULT_DEADLINE_MS = 3e4;
@@ -101,6 +101,19 @@ function connectFlow(store, targets, options = {}) {
101
101
  await attach(gen, "replace-remote", "started");
102
102
  return;
103
103
  }
104
+ if (info.app !== null && info.app !== host.engine.app) {
105
+ m.set({
106
+ step: "error",
107
+ busy: false,
108
+ error: toStoreError(
109
+ new SelfstoreError(
110
+ "FOREIGN_BACKUP",
111
+ `This backup was written by "${info.app}", not "${host.engine.app}". Open it in its own application.`
112
+ )
113
+ )
114
+ });
115
+ return;
116
+ }
104
117
  if (info.encrypted) {
105
118
  if (options.deferUnlock) {
106
119
  await attach(gen, "replace-local", "resumed");
@@ -455,5 +468,5 @@ function joinFlow(link, engine, options = {}) {
455
468
  }
456
469
 
457
470
  export { connectFlow, joinFlow, shareFlow };
458
- //# sourceMappingURL=chunk-OZS7BSC2.js.map
459
- //# sourceMappingURL=chunk-OZS7BSC2.js.map
471
+ //# sourceMappingURL=chunk-JMJZIZKY.js.map
472
+ //# sourceMappingURL=chunk-JMJZIZKY.js.map