@poolse/crypto 0.0.0-stage → 3.9.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,446 @@
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
+ ## Format
285
+
286
+ Everything the library writes is a binary envelope (base64url it with
287
+ `toBase64Url` for JSON APIs) that starts with the same four bytes:
288
+
289
+ | Byte | Meaning |
290
+ | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
291
+ | 0 | `0x70` magic |
292
+ | 1 | format version, `1` |
293
+ | 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 |
294
+ | 3 | algorithm suite: 0 none, 1 AES-256-GCM + HKDF-SHA-256, 2 P-256 (ECDH + HKDF + AES-GCM, ECDSA), 3 HMAC-SHA-256 |
295
+
296
+ The header and every field up to the ciphertext are part of the AES-GCM
297
+ associated data, together with the caller's associated data. A newer format
298
+ version or an unknown algorithm is refused with `unsupported`, so an old app
299
+ fails loudly rather than misreading new data. `inspectEnvelope` reads the
300
+ header (kind, key version, recipient, revision) without decrypting.
301
+
302
+ The layouts are documented at the top of each source file (`item.ts`,
303
+ `wrap.ts`, `attachment.ts`, `approval.ts`, `sync.ts`, `keys.ts`).
304
+ `test/vectors.ts` holds frozen envelopes of format 1 that every build must
305
+ still decrypt.
306
+
307
+ ### Algorithms, and why
308
+
309
+ - **P-256 ECDH and ECDSA**, not X25519/Ed25519. P-256 is the curve every
310
+ WebCrypto implementation supports: all browsers, Safari and WKWebView
311
+ (Tauri on macOS), WebKitGTK, Node, and the React Native polyfills. X25519
312
+ and Ed25519 arrived in WebCrypto only recently and unevenly. Signatures are
313
+ raw r‖s (64 bytes).
314
+ - **Public-key wrapping** is ECIES: a fresh ephemeral P-256 key per wrap, HKDF
315
+ over the shared secret with both public keys as salt and the purpose in the
316
+ info, then AES-256-GCM.
317
+ - **AES-256-GCM** with random 96-bit IVs for content and wraps. Each item key
318
+ encrypts only that item's versions, far below GCM's 2³² messages per key.
319
+ Attachments use a fresh HKDF-derived key per file and counter nonces.
320
+ - **HKDF-SHA-256** for every derived key, each on its own `poolse-crypto/v1/…`
321
+ label.
322
+ - **Key check values**: each envelope stores a 16-byte value derived from the
323
+ key on a separate HKDF branch. It turns "wrong key" into its own error and
324
+ commits the envelope to one key, which AES-GCM on its own doesn't do.
325
+ - **Padding**: item and sync plaintexts are padded (Padmé) so stored sizes
326
+ only roughly reflect the content (at most ~12% overhead).
327
+ - **Recovery key**: 128 random bits, not a password, so no password KDF
328
+ (PBKDF2/Argon2) is needed: 2¹²⁸ guesses is out of reach at any hashing
329
+ cost. A 32-bit checksum catches typos.
330
+
331
+ ## Security notes
332
+
333
+ ### Threat model
334
+
335
+ The server, the workspace admin, and anyone who gets a copy of the database
336
+ or the backups are treated as adversaries for personal notes and synced data.
337
+ They can read, change, delete, replay and reorder anything stored, and decide
338
+ what each client receives.
339
+
340
+ Protected against them:
341
+
342
+ - **Confidentiality** of titles, bodies, metadata, attachments, versions,
343
+ synced blobs and blob names.
344
+ - **Integrity**: any change to a ciphertext, a wrap, a QR code or a grant is
345
+ detected; so is moving a ciphertext to another item, version, attachment,
346
+ account or blob key (associated data).
347
+ - **Forged shares**: `openSharedItemKey` requires a signature from one of the
348
+ author's devices.
349
+ - **Forged device approvals**: grants are authenticated with a secret that
350
+ only goes through the QR code.
351
+ - **Rollback of synced blobs**, when the app keeps a persistent
352
+ `RevisionStore`.
353
+
354
+ ### What the server still sees
355
+
356
+ - That a user has personal notes or synced data, how many items, blobs,
357
+ attachments and versions, and their approximate sizes (padded, not hidden).
358
+ - When each was created, changed or deleted, by which session, from which IP.
359
+ - Who shares with whom, how many devices each user has, and when a device was
360
+ added or a share revoked.
361
+ - Item ids, attachment ids, key versions and blob keys (opaque, but stable).
362
+ - Device public keys and fingerprints.
363
+
364
+ ### What is not protected
365
+
366
+ - **The key directory is trusted.** A device learns other people's device
367
+ public keys from the server. A malicious server could list a key of its own
368
+ for a recipient (so a share would be wrapped to it) or for an author (so a
369
+ forged share would verify). The app should show device fingerprints
370
+ (`deviceFingerprint`) and let people compare them for sensitive shares, and
371
+ should warn when someone's device list changes. Own devices are added only by
372
+ QR approval or the recovery key, which don't trust the directory.
373
+ - **Withholding and forking.** The server can withhold updates, pretend
374
+ something was deleted (`purge`), or show two devices different histories.
375
+ Revisions catch rollback only per blob and only against what a device has
376
+ already seen.
377
+ - **Notes item rollback.** For notes, binding the version number into the
378
+ associated data stops one version being served as another, but the app has to
379
+ remember the newest version it has seen to notice an old one being served as
380
+ current.
381
+ - **Compromised devices.** Anyone who unlocks a device, or malware on it,
382
+ reads everything that device can. Removing a device from the account doesn't
383
+ erase what it already holds; to protect future data, make a new account key
384
+ and rotate item keys.
385
+ - **Revoked recipients** keep everything they already decrypted.
386
+ - **Metadata** listed above, and anything the app sends unencrypted next to the
387
+ ciphertext (keep folder names, tags and titles inside the encrypted content).
388
+ - **Side channels in JavaScript.** Secret keys are held as bytes in the JS
389
+ heap (non-extractable `CryptoKey`s for device keys after import). JS gives
390
+ no reliable memory wiping. The comparisons this library makes on secrets are
391
+ constant-time; WebCrypto does the rest.
392
+ - **Search and agents.** The server can't index personal notes; search runs on
393
+ the device. Dictation sends audio to Soniox before it is encrypted.
394
+
395
+ ### Losing keys
396
+
397
+ - **Every device and the recovery key lost: the personal notes and synced data
398
+ are gone for good.** Nobody, including the workspace admin and poolse, can
399
+ recover them. The app must say so clearly and nudge the user to save the
400
+ recovery key.
401
+ - **One device lost**: approve a new one from another device or with the
402
+ recovery key. Then remove the lost device's wrap, and if the device may be in
403
+ someone else's hands, make a new account key, re-wrap the item keys under it,
404
+ and rotate the items' keys.
405
+ - **Recovery key lost (devices fine)**: make a new one and replace the
406
+ server's recovery wrap. The old recovery key no longer works once its wrap is
407
+ deleted — unless someone kept a copy of the old wrap, so rotate the account
408
+ key too if the old recovery key may have leaked.
409
+ - **Recovery key leaked**: anyone with it and the server's wrap gets the
410
+ account key. Make a new account key and a new recovery key.
411
+
412
+ ## Errors
413
+
414
+ Everything throws `PoolseCryptoError` with a `code`: `malformed`,
415
+ `unsupported`, `wrong-key`, `tampered`, `bad-signature`, `expired`,
416
+ `checksum`, `rollback` or `unavailable`. Decryption failures are deliberately
417
+ coarse (`tampered` covers both changed data and wrong associated data).
418
+ `BlobConflictError` (not a crypto error) means another device wrote first.
419
+
420
+ ## React Native
421
+
422
+ React Native has no WebCrypto of its own. Install a polyfill that provides
423
+ `crypto.subtle` with ECDH and ECDSA on P-256, HKDF, HMAC, AES-GCM and SHA-256,
424
+ and JWK import/export of EC keys — for example
425
+ [react-native-quick-crypto](https://github.com/margelo/react-native-quick-crypto)
426
+ — before importing this package:
427
+
428
+ ```ts
429
+ import { install } from 'react-native-quick-crypto';
430
+ install();
431
+ ```
432
+
433
+ Then check once at start-up; it tries every operation and lists what's missing:
434
+
435
+ ```ts
436
+ import { checkCryptoSupport } from '@poolse/crypto';
437
+ const { ok, missing } = await checkCryptoSupport();
438
+ ```
439
+
440
+ The library also needs `BigInt` (Hermes has it); it brings its own UTF-8 code
441
+ for runtimes without `TextDecoder`. Keep the device-key bytes in the
442
+ Keychain/Keystore (e.g. `expo-secure-store`), not in AsyncStorage.
443
+
444
+ ## License
445
+
446
+ [poolse SDK License](./LICENSE).