@poolse/crypto 0.0.0-stage → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,530 @@
1
- # Temporary Holding Version
1
+ # @poolse/crypto
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ End-to-end encryption for poolse personal data: personal notes (NT3), shared
4
+ notes (NT5, NT15), versions (NT8), devices and recovery (NT10), and encrypted
5
+ sync of your own data between your devices (ST6). The desktop and mobile apps
6
+ use this one library, so there is one implementation to review.
7
+
8
+ The server only ever stores ciphertext. Keys are made and kept on the user's
9
+ devices.
10
+
11
+ ```bash
12
+ npm install @poolse/crypto
13
+ ```
14
+
15
+ No dependencies. Every primitive comes from the platform's WebCrypto
16
+ (`globalThis.crypto.subtle`): browsers, Tauri webviews, Node 20+, and React
17
+ Native with a WebCrypto polyfill (see [React Native](#react-native)).
18
+
19
+ ## Keys
20
+
21
+ | Key | What it is | Where it lives |
22
+ | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
23
+ | `DeviceKeys` | One per device: a P-256 ECDH pair (others wrap keys to it) and a P-256 ECDSA pair (it signs what it wraps and approves). Made on the device, never sent anywhere. | The OS keychain / Keystore / Secure Enclave-backed item, as the bytes from `export()`. |
24
+ | `AccountKey` | The user's notes key: 256 random bits. | On the server, only wrapped: once per device (`wrapAccountKeyForDevice`) and once per recovery key. |
25
+ | `ItemKey` | One per note (or other item): 256 random bits with a version that goes up on every rotation. | On the server, only wrapped: under the account key for the owner, and to each recipient device for shares. |
26
+ | `RecoveryKey` | 128 random bits the user writes down, shown as `XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX`. | With the user (paper, password manager). The server keeps the account key wrapped under it. |
27
+
28
+ ```
29
+ RecoveryKey ──wraps──┐
30
+ DeviceKeys ──wraps──► AccountKey ──wraps──► ItemKey ──encrypts──► title, body, metadata, attachments, versions
31
+ └──derives──► sync keys (ST6) ▲
32
+ recipient DeviceKeys ◄──signed share wraps────────────────────┘
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ### A new account (first device)
38
+
39
+ ```ts
40
+ import {
41
+ DeviceKeys,
42
+ AccountKey,
43
+ generateRecoveryKey,
44
+ wrapAccountKeyForDevice,
45
+ wrapAccountKeyWithRecoveryKey,
46
+ encodeDevicePublicKeys,
47
+ } from '@poolse/crypto';
48
+
49
+ const device = await DeviceKeys.generate();
50
+ await keychain.set('poolse.device', await device.export()); // the app stores the bytes
51
+
52
+ const accountKey = await AccountKey.generate();
53
+ const recoveryKey = await generateRecoveryKey();
54
+ showOnce(recoveryKey.toDisplayString()); // make the user save it
55
+
56
+ await api.putDevice({
57
+ id: device.id,
58
+ publicKeys: encodeDevicePublicKeys(device.publicKeys), // for the key directory
59
+ accountKeyWrap: await wrapAccountKeyForDevice(accountKey, device.publicKeys, {
60
+ accountId,
61
+ signer: device,
62
+ }),
63
+ });
64
+ await api.putRecovery({
65
+ id: recoveryKey.id,
66
+ accountKeyWrap: await wrapAccountKeyWithRecoveryKey(accountKey, recoveryKey, { accountId }),
67
+ });
68
+ ```
69
+
70
+ At every start: `DeviceKeys.import(await keychain.get('poolse.device'))`, then
71
+ `unwrapAccountKeyForDevice(wrap, device, { accountId })`.
72
+
73
+ ### Notes
74
+
75
+ ```ts
76
+ import { ItemKey, encryptItem, decryptItem, wrapItemKey, unwrapItemKey } from '@poolse/crypto';
77
+
78
+ const key = ItemKey.generate();
79
+ const envelope = await encryptItem(
80
+ key,
81
+ { title: 'Plan', body: editorDoc, metadata: { tags: ['work'] } },
82
+ { itemId: note.id, version: 4 }, // associated data
83
+ );
84
+ const keyWrap = await wrapItemKey(key, accountKey, { itemId: note.id });
85
+
86
+ // Later, on any of the user's devices:
87
+ const k = await unwrapItemKey(keyWrap, accountKey, { itemId: note.id });
88
+ const content = await decryptItem(k, envelope, { itemId: note.id, version: 4 });
89
+ ```
90
+
91
+ The associated data is not stored in the envelope; it must be supplied again to
92
+ decrypt. Bind every value that says where the ciphertext belongs (item id,
93
+ version number), so the server can't swap two notes' ciphertexts or serve an old
94
+ version as a new one. `encryptBytes` / `decryptBytes` do the same for small raw
95
+ values (an encrypted folder or tag name).
96
+
97
+ For version history (NT8), encrypt each version with `version` in the
98
+ associated data. Use the item key the version was written with:
99
+ `inspectEnvelope(envelope).keyVersion` says which.
100
+
101
+ ### Attachments (streamed)
102
+
103
+ ```ts
104
+ import { encryptAttachment, decryptAttachment, encryptedAttachmentSize } from '@poolse/crypto';
105
+
106
+ const ad = { itemId: note.id, attachmentId };
107
+ const sealed = encryptAttachment(
108
+ key,
109
+ file /* Blob, ReadableStream, Uint8Array, (async) iterable */,
110
+ ad,
111
+ );
112
+ await upload(sealed, { contentLength: encryptedAttachmentSize(file.size) });
113
+
114
+ for await (const chunk of decryptAttachment(key, downloadStream, ad)) write(chunk);
115
+ // Only a loop that finishes without throwing proves the file is complete.
116
+ ```
117
+
118
+ Files are cut into 64 KiB chunks (`chunkSize` from 16 bytes to 16 MiB), each
119
+ authenticated, with the order and the final chunk bound in (STREAM). Truncating,
120
+ reordering, dropping or appending chunks fails. `encryptAttachmentBytes` /
121
+ `decryptAttachmentBytes` work on whole byte arrays. Encrypted attachments are
122
+ opaque to the server, so it can't make previews or thumbnails.
123
+
124
+ ### Sharing and revoking (NT5, NT15)
125
+
126
+ ```ts
127
+ import {
128
+ shareItemKeyWithDevices,
129
+ openSharedItemKey,
130
+ rotateItemKey,
131
+ wrapPreviousItemKey,
132
+ } from '@poolse/crypto';
133
+
134
+ // Share: wrap the note key to every device of every recipient, signed by this device.
135
+ const wraps = await shareItemKeyWithDevices(key, bobDevices, { itemId: note.id, signer: device });
136
+
137
+ // Bob's device opens it, checking it was signed by one of the author's devices.
138
+ const { key: shared } = await openSharedItemKey(wrap, bobDevice, {
139
+ itemId: note.id,
140
+ requireSignatureFrom: authorDevices, // from the key directory
141
+ });
142
+
143
+ // Revoke (or a share expires): new key, re-encrypt, re-wrap for who's left.
144
+ const next = rotateItemKey(key); // version + 1
145
+ const envelope2 = await encryptItem(next, content, { itemId: note.id, version: 5 });
146
+ const ownerWrap = await wrapItemKey(next, accountKey, { itemId: note.id });
147
+ const remaining = await shareItemKeyWithDevices(next, carolDevices, {
148
+ itemId: note.id,
149
+ signer: device,
150
+ });
151
+ const history = await wrapPreviousItemKey(key, next, { itemId: note.id }); // older versions stay readable
152
+ ```
153
+
154
+ Groups are shares to each member's devices. The removed person keeps what they
155
+ already decrypted; they can't read anything written after the rotation. The app
156
+ should say so ("Ana may have kept a copy of what she has already seen").
157
+
158
+ ### A new device (NT10)
159
+
160
+ By QR code from a device the user already has:
161
+
162
+ ```ts
163
+ import {
164
+ createDeviceRequest,
165
+ readDeviceRequest,
166
+ approveDeviceRequest,
167
+ acceptDeviceGrant,
168
+ deviceFingerprint,
169
+ } from '@poolse/crypto';
170
+
171
+ // New device
172
+ const phone = await DeviceKeys.generate();
173
+ const { qr, pending } = await createDeviceRequest(phone); // show `qr` as a QR code; keep `pending` in memory
174
+
175
+ // Existing device, after scanning
176
+ const request = await readDeviceRequest(scanned); // checks the signature and age (10 min)
177
+ confirm(`Approve this device? ${await deviceFingerprint(request.device)}`);
178
+ const grant = await approveDeviceRequest(request, laptop, accountKey, { accountId });
179
+ await api.sendDeviceGrant(request.device.id, grant);
180
+
181
+ // New device, when the grant arrives
182
+ const { accountKey, accountKeyWrap } = await acceptDeviceGrant(grant, pending, phone, {
183
+ accountId,
184
+ });
185
+ ```
186
+
187
+ The QR code carries a 16-byte secret the server never sees, and the grant is
188
+ authenticated with it: the server that relays the grant can neither forge one
189
+ nor substitute its own keys at either end.
190
+
191
+ Or with the recovery key:
192
+
193
+ ```ts
194
+ const rk = await parseRecoveryKey(typed); // ignores case, spaces, hyphens; O→0, I/L→1; `checksum` error on a typo
195
+ const accountKey = await unwrapAccountKeyWithRecoveryKey(recoveryWrap, rk, { accountId });
196
+ ```
197
+
198
+ Either way the new device then stores its own `wrapAccountKeyForDevice` wrap.
199
+
200
+ ### Encrypted sync of your own data (ST6)
201
+
202
+ ```ts
203
+ import { EncryptedBlobStore } from '@poolse/crypto';
204
+
205
+ const store = new EncryptedBlobStore({ transport, accountKey, namespace: 'settings', revisions });
206
+ await store.putJson('layout', { sidebar: 'collapsed' });
207
+ const layout = await store.getJson('layout');
208
+
209
+ // Read, change, write; retried when another device wrote first.
210
+ await store.updateJson<string[]>('pinned', (pins) => [...(pins ?? []), channelId]);
211
+ ```
212
+
213
+ - **Names are hidden.** The blob key is an HMAC of the namespace and name under
214
+ a key derived from the account key (`store.blobKey(name)`); the name itself
215
+ travels inside the ciphertext. `list()` pages through blob keys; read each with
216
+ `getByKey`.
217
+ - **Conflicts.** Every write is conditional: `If-Match` the version last read or
218
+ written, or `If-None-Match: *` for a new blob. A stale write throws
219
+ `BlobConflictError`; `update` / `updateJson` re-read and retry.
220
+ - **Rollback.** Each record carries an authenticated revision that goes up by
221
+ one per write. Pass a persistent `revisions` store (IndexedDB, AsyncStorage, a
222
+ file) and a server serving an older record is refused with `rollback`, also
223
+ across restarts.
224
+ - **Deletes** write an authenticated tombstone (`delete`), so the revision keeps
225
+ counting; `purge` removes the blob for real but can't be told apart from a
226
+ server deleting it.
227
+
228
+ #### The transport
229
+
230
+ Against a poolse server, use the HTTP transport (plain `fetch`, no
231
+ `@poolse/sdk` needed):
232
+
233
+ ```ts
234
+ import { createHttpBlobTransport, EncryptedBlobStore } from '@poolse/crypto';
235
+
236
+ const transport = createHttpBlobTransport({
237
+ apiUrl: 'https://chat.example.com', // the poolse server, without /v1
238
+ getToken: () => client.getToken(), // the signed-in user's token (Bearer)
239
+ // fetch: customFetch, // defaults to globalThis.fetch
240
+ });
241
+ const store = new EncryptedBlobStore({
242
+ transport,
243
+ accountKey,
244
+ namespace: 'settings',
245
+ keyPrefix: 'st6.',
246
+ });
247
+
248
+ // Pick up other devices' changes: keep the cursor between runs.
249
+ const { changes, cursor } = await store.changes({ cursor: saved });
250
+ for (const c of changes) {
251
+ const blob = await store.getByKey(c.key); // null when deleted
252
+ }
253
+ ```
254
+
255
+ | Call | Request | Result |
256
+ | ---------------------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
257
+ | `get(key)` | `GET /v1/me/blobs/:key` | bytes and the `ETag` version; `404` → `null` |
258
+ | `put(key, data, cond)` | `PUT /v1/me/blobs/:key`, octet-stream, `If-Match: "<v>"` or `If-None-Match: *` | the new version (`ETag`, else the JSON `version`); `412`/`409` → `BlobConflictError` |
259
+ | `delete(key, cond)` | `DELETE /v1/me/blobs/:key`, `If-Match` if given | `204`; `412`/`409` → `BlobConflictError`; `404` → done without `If-Match`, `BlobConflictError` with it |
260
+ | `list(opts)` | `GET /v1/me/blobs?prefix=&cursor=&limit=` | `{blobs, cursor, limits}` (`cursor` `null` on the last page) |
261
+ | `changes(opts)` | `GET /v1/me/blob-changes?cursor=&limit=` | `{changes: [{key, version, size, updatedAt, deleted}], cursor}` oldest first; the cursor comes back even when nothing changed |
262
+
263
+ Versions are the `ETag` without quotes. Any other failure throws
264
+ `BlobTransportError` with a `code`: `too_large` / `quota_exceeded` (413),
265
+ `sync_disabled` (403, the workspace turned encrypted sync off), `forbidden`
266
+ (other 403), `rate_limited` (429, with `retryAfterMs` from `Retry-After`),
267
+ `invalid_key` (422, or refused before sending), `unauthorized` (401 even after
268
+ asking `getToken` once more), `not_found`, `server` (5xx), `network` (no
269
+ response), `bad_response`, `http`; plus `status`, `serverCode` and
270
+ `retryable`. Nothing is retried automatically except that one new token after a 401.
271
+
272
+ Keys are 1–128 of `a–z 0–9 .`, not starting or ending with `.`, no `..`
273
+ (`isValidBlobKey`). The store's keys are 32 lowercase base32 characters plus
274
+ your `keyPrefix`, so keep the prefix to those characters too. The server allows
275
+ 25 MiB per blob, 1 GiB and 10 000 blobs per user by default (`list().limits`).
276
+
277
+ In a browser or webview on another origin, the server must expose `ETag`
278
+ (`Access-Control-Expose-Headers`), or `get` fails with `bad_response`.
279
+
280
+ Any other backend works too: implement `BlobTransport` (`get`, `put`,
281
+ `delete`, `list`, optional `changes`). `MemoryBlobTransport` is an in-memory
282
+ one for tests.
283
+
284
+ ### Workspace notes (NOTES.md)
285
+
286
+ Helpers that follow the Workspace API's notes contract
287
+ (`apps/workspace/NOTES.md`): the associated data, field names and
288
+ base64url encodings it expects, so results go straight into request bodies.
289
+
290
+ ```ts
291
+ import {
292
+ sealNote,
293
+ openNoteMeta,
294
+ openNoteContent,
295
+ noteKeyForVersion,
296
+ shareWrapsFor,
297
+ rotateNoteKey,
298
+ recoveryAuth,
299
+ signedDeviceGrant,
300
+ NoteSearchIndex,
301
+ NoteOutbox,
302
+ noteAsDocument,
303
+ } from '@poolse/crypto';
304
+
305
+ // Write (revision = base_revision + 1, bound into the associated data).
306
+ const { meta, content } = await sealNote(
307
+ key,
308
+ { title, body, metadata },
309
+ { noteId, revision: base + 1 },
310
+ );
311
+ await ws.put(`/notes/${noteId}`, { base_revision: base, meta, content, key_wrap });
312
+
313
+ // Share (NT5): one signed wrap per approved device of each recipient.
314
+ const wraps = await shareWrapsFor(key, recipients /* from POST /notes/keys/lookup */, {
315
+ noteId,
316
+ signer: device,
317
+ });
318
+
319
+ // Revoke or expiry (NT15, on notes:rotate): new key, re-encrypted, wraps for who's left.
320
+ const r = await rotateNoteKey(key, note, {
321
+ noteId,
322
+ revision: base + 1,
323
+ accountKey,
324
+ signer: device,
325
+ remaining,
326
+ });
327
+ await ws.put(`/notes/${noteId}`, {
328
+ base_revision: base,
329
+ meta: r.meta,
330
+ content: r.content,
331
+ key_wrap: r.key_wrap,
332
+ key_history: r.key_history,
333
+ share_wraps: r.share_wraps,
334
+ });
335
+
336
+ // Versions (NT8): the key the version was written with, then its own revision.
337
+ const vkey = await noteKeyForVersion(key, note.key_history, version.key_version, { noteId });
338
+ const old = await openNoteContent(vkey, version.content, { noteId, revision: version.revision });
339
+ ```
340
+
341
+ | Helper | For |
342
+ | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
343
+ | `noteAssociatedData`, `noteAttachmentAssociatedData`, `folderAssociatedData` | the associated data of each ciphertext |
344
+ | `sealNote` / `openNoteMeta` / `openNoteContent` / `envelopeKeyVersion` | `meta` (title + metadata, no body) and `content` |
345
+ | `sealFolder` / `openFolderName` | encrypted folder names (`name_envelope`, `key_wrap`) |
346
+ | `shareWrapsFor` | `wraps` / `share_wraps` (`{member_id, device_id, wrap}`); editors (NT16) get the same wrap and write with the same key |
347
+ | `rotateNoteKey`, `shareExpired` | rotation after a revoke or an expired share |
348
+ | `noteKeyForVersion` | walk `key_history` back for a version |
349
+ | `recoveryAuth` | `recovery.auth` / `recovery_auth`: 32 bytes, HKDF-SHA-256 of the recovery secret (empty salt, info `poolse-crypto/v1/recovery-auth`) |
350
+ | `signForServer`, `deviceApprovalMessage`, `recoveryReplaceMessage`, `signedDeviceGrant` | the device signatures the server checks (raw P-256 `r‖s`) |
351
+ | `noteAsDocument` | NT12: one decrypted note as Markdown for an agent task (only after the member chose to hand it over) |
352
+
353
+ **On-device search (NT7).** `NoteSearchIndex` keeps the words of the notes
354
+ this device has decrypted; `put(id, {title, text, updatedAt})`, `remove`,
355
+ `search(query)` (every word must match as a prefix, case and accents
356
+ ignored; title and whole-word matches first). `seal(accountKey)` encrypts it
357
+ for storage on the device (key `HKDF(accountKey, "key/search-index")`);
358
+ `NoteSearchIndex.open(sealed, accountKey)` reads it back.
359
+
360
+ **Offline queue (NT9).** `NoteOutbox.load({storage, accountKey})` keeps
361
+ edits made offline, encrypted at rest; `put(noteId, baseRevision, data)` /
362
+ `delete(...)`; several edits of a note collapse into one write on the first
363
+ `baseRevision`. `flush({send, resolve})` sends them in order: `send` seals
364
+ and writes one entry and answers `ok`, `conflict` (`409 revision_conflict`,
365
+ with the server's note) or `gone`; `resolve` merges a conflict (default:
366
+ keep the local edit). A thrown error stops the flush and keeps the rest.
367
+
368
+ ## Format
369
+
370
+ Everything the library writes is a binary envelope (base64url it with
371
+ `toBase64Url` for JSON APIs) that starts with the same four bytes:
372
+
373
+ | Byte | Meaning |
374
+ | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
375
+ | 0 | `0x70` magic |
376
+ | 1 | format version, `1` |
377
+ | 2 | kind: 1 item, 2 key wrap, 3 public-key wrap, 4 attachment, 5 device request, 6 device grant, 7 device public keys, 8 sync record, 9 device secret |
378
+ | 3 | algorithm suite: 0 none, 1 AES-256-GCM + HKDF-SHA-256, 2 P-256 (ECDH + HKDF + AES-GCM, ECDSA), 3 HMAC-SHA-256 |
379
+
380
+ The header and every field up to the ciphertext are part of the AES-GCM
381
+ associated data, together with the caller's associated data. A newer format
382
+ version or an unknown algorithm is refused with `unsupported`, so an old app
383
+ fails loudly rather than misreading new data. `inspectEnvelope` reads the
384
+ header (kind, key version, recipient, revision) without decrypting.
385
+
386
+ The layouts are documented at the top of each source file (`item.ts`,
387
+ `wrap.ts`, `attachment.ts`, `approval.ts`, `sync.ts`, `keys.ts`).
388
+ `test/vectors.ts` holds frozen envelopes of format 1 that every build must
389
+ still decrypt.
390
+
391
+ ### Algorithms, and why
392
+
393
+ - **P-256 ECDH and ECDSA**, not X25519/Ed25519. P-256 is the curve every
394
+ WebCrypto implementation supports: all browsers, Safari and WKWebView
395
+ (Tauri on macOS), WebKitGTK, Node, and the React Native polyfills. X25519
396
+ and Ed25519 arrived in WebCrypto only recently and unevenly. Signatures are
397
+ raw r‖s (64 bytes).
398
+ - **Public-key wrapping** is ECIES: a fresh ephemeral P-256 key per wrap, HKDF
399
+ over the shared secret with both public keys as salt and the purpose in the
400
+ info, then AES-256-GCM.
401
+ - **AES-256-GCM** with random 96-bit IVs for content and wraps. Each item key
402
+ encrypts only that item's versions, far below GCM's 2³² messages per key.
403
+ Attachments use a fresh HKDF-derived key per file and counter nonces.
404
+ - **HKDF-SHA-256** for every derived key, each on its own `poolse-crypto/v1/…`
405
+ label.
406
+ - **Key check values**: each envelope stores a 16-byte value derived from the
407
+ key on a separate HKDF branch. It turns "wrong key" into its own error and
408
+ commits the envelope to one key, which AES-GCM on its own doesn't do.
409
+ - **Padding**: item and sync plaintexts are padded (Padmé) so stored sizes
410
+ only roughly reflect the content (at most ~12% overhead).
411
+ - **Recovery key**: 128 random bits, not a password, so no password KDF
412
+ (PBKDF2/Argon2) is needed: 2¹²⁸ guesses is out of reach at any hashing
413
+ cost. A 32-bit checksum catches typos.
414
+
415
+ ## Security notes
416
+
417
+ ### Threat model
418
+
419
+ The server, the workspace admin, and anyone who gets a copy of the database
420
+ or the backups are treated as adversaries for personal notes and synced data.
421
+ They can read, change, delete, replay and reorder anything stored, and decide
422
+ what each client receives.
423
+
424
+ Protected against them:
425
+
426
+ - **Confidentiality** of titles, bodies, metadata, attachments, versions,
427
+ synced blobs and blob names.
428
+ - **Integrity**: any change to a ciphertext, a wrap, a QR code or a grant is
429
+ detected; so is moving a ciphertext to another item, version, attachment,
430
+ account or blob key (associated data).
431
+ - **Forged shares**: `openSharedItemKey` requires a signature from one of the
432
+ author's devices.
433
+ - **Forged device approvals**: grants are authenticated with a secret that
434
+ only goes through the QR code.
435
+ - **Rollback of synced blobs**, when the app keeps a persistent
436
+ `RevisionStore`.
437
+
438
+ ### What the server still sees
439
+
440
+ - That a user has personal notes or synced data, how many items, blobs,
441
+ attachments and versions, and their approximate sizes (padded, not hidden).
442
+ - When each was created, changed or deleted, by which session, from which IP.
443
+ - Who shares with whom, how many devices each user has, and when a device was
444
+ added or a share revoked.
445
+ - Item ids, attachment ids, key versions and blob keys (opaque, but stable).
446
+ - Device public keys and fingerprints.
447
+
448
+ ### What is not protected
449
+
450
+ - **The key directory is trusted.** A device learns other people's device
451
+ public keys from the server. A malicious server could list a key of its own
452
+ for a recipient (so a share would be wrapped to it) or for an author (so a
453
+ forged share would verify). The app should show device fingerprints
454
+ (`deviceFingerprint`) and let people compare them for sensitive shares, and
455
+ should warn when someone's device list changes. Own devices are added only by
456
+ QR approval or the recovery key, which don't trust the directory.
457
+ - **Withholding and forking.** The server can withhold updates, pretend
458
+ something was deleted (`purge`), or show two devices different histories.
459
+ Revisions catch rollback only per blob and only against what a device has
460
+ already seen.
461
+ - **Notes item rollback.** For notes, binding the version number into the
462
+ associated data stops one version being served as another, but the app has to
463
+ remember the newest version it has seen to notice an old one being served as
464
+ current.
465
+ - **Compromised devices.** Anyone who unlocks a device, or malware on it,
466
+ reads everything that device can. Removing a device from the account doesn't
467
+ erase what it already holds; to protect future data, make a new account key
468
+ and rotate item keys.
469
+ - **Revoked recipients** keep everything they already decrypted.
470
+ - **Metadata** listed above, and anything the app sends unencrypted next to the
471
+ ciphertext (keep folder names, tags and titles inside the encrypted content).
472
+ - **Side channels in JavaScript.** Secret keys are held as bytes in the JS
473
+ heap (non-extractable `CryptoKey`s for device keys after import). JS gives
474
+ no reliable memory wiping. The comparisons this library makes on secrets are
475
+ constant-time; WebCrypto does the rest.
476
+ - **Search and agents.** The server can't index personal notes; search runs on
477
+ the device. Dictation sends audio to Soniox before it is encrypted.
478
+
479
+ ### Losing keys
480
+
481
+ - **Every device and the recovery key lost: the personal notes and synced data
482
+ are gone for good.** Nobody, including the workspace admin and poolse, can
483
+ recover them. The app must say so clearly and nudge the user to save the
484
+ recovery key.
485
+ - **One device lost**: approve a new one from another device or with the
486
+ recovery key. Then remove the lost device's wrap, and if the device may be in
487
+ someone else's hands, make a new account key, re-wrap the item keys under it,
488
+ and rotate the items' keys.
489
+ - **Recovery key lost (devices fine)**: make a new one and replace the
490
+ server's recovery wrap. The old recovery key no longer works once its wrap is
491
+ deleted — unless someone kept a copy of the old wrap, so rotate the account
492
+ key too if the old recovery key may have leaked.
493
+ - **Recovery key leaked**: anyone with it and the server's wrap gets the
494
+ account key. Make a new account key and a new recovery key.
495
+
496
+ ## Errors
497
+
498
+ Everything throws `PoolseCryptoError` with a `code`: `malformed`,
499
+ `unsupported`, `wrong-key`, `tampered`, `bad-signature`, `expired`,
500
+ `checksum`, `rollback` or `unavailable`. Decryption failures are deliberately
501
+ coarse (`tampered` covers both changed data and wrong associated data).
502
+ `BlobConflictError` (not a crypto error) means another device wrote first.
503
+
504
+ ## React Native
505
+
506
+ React Native has no WebCrypto of its own. Install a polyfill that provides
507
+ `crypto.subtle` with ECDH and ECDSA on P-256, HKDF, HMAC, AES-GCM and SHA-256,
508
+ and JWK import/export of EC keys — for example
509
+ [react-native-quick-crypto](https://github.com/margelo/react-native-quick-crypto)
510
+ — before importing this package:
511
+
512
+ ```ts
513
+ import { install } from 'react-native-quick-crypto';
514
+ install();
515
+ ```
516
+
517
+ Then check once at start-up; it tries every operation and lists what's missing:
518
+
519
+ ```ts
520
+ import { checkCryptoSupport } from '@poolse/crypto';
521
+ const { ok, missing } = await checkCryptoSupport();
522
+ ```
523
+
524
+ The library also needs `BigInt` (Hermes has it); it brings its own UTF-8 code
525
+ for runtimes without `TextDecoder`. Keep the device-key bytes in the
526
+ Keychain/Keystore (e.g. `expo-secure-store`), not in AsyncStorage.
527
+
528
+ ## License
529
+
530
+ [poolse SDK License](./LICENSE).