@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/CHANGELOG.md +60 -0
- package/LICENSE +206 -0
- package/README.md +529 -2
- package/dist/index.cjs +2574 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1088 -0
- package/dist/index.d.ts +1088 -0
- package/dist/index.js +2487 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -3
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,1088 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why an operation was refused. Decryption errors are deliberately coarse:
|
|
3
|
+
* `tampered` covers a modified ciphertext, a wrong associated-data value and
|
|
4
|
+
* a forged tag alike, because telling them apart would help an attacker.
|
|
5
|
+
*
|
|
6
|
+
* - `malformed` — not something this library wrote (bad length, encoding,
|
|
7
|
+
* trailing bytes, truncated stream).
|
|
8
|
+
* - `unsupported` — written by a newer format version or with an algorithm
|
|
9
|
+
* this build doesn't know. Update the library rather than retrying.
|
|
10
|
+
* - `wrong-key` — the key's check value doesn't match: a different key (or a
|
|
11
|
+
* different key version) was used to encrypt this.
|
|
12
|
+
* - `tampered` — authentication failed: the data, or the associated data it
|
|
13
|
+
* was bound to (item id, version…), isn't what was encrypted.
|
|
14
|
+
* - `bad-signature` — a signature is invalid, or the signer isn't one the
|
|
15
|
+
* caller said to trust.
|
|
16
|
+
* - `expired` — a device approval request is too old (or from the future).
|
|
17
|
+
* - `checksum` — a recovery key was mistyped.
|
|
18
|
+
* - `rollback` — the blob store returned an older revision than this device
|
|
19
|
+
* has already seen.
|
|
20
|
+
* - `unavailable` — WebCrypto (or an algorithm it needs) is missing.
|
|
21
|
+
*/
|
|
22
|
+
type PoolseCryptoErrorCode = 'malformed' | 'unsupported' | 'wrong-key' | 'tampered' | 'bad-signature' | 'expired' | 'checksum' | 'rollback' | 'unavailable';
|
|
23
|
+
declare class PoolseCryptoError extends Error {
|
|
24
|
+
readonly code: PoolseCryptoErrorCode;
|
|
25
|
+
readonly name = "PoolseCryptoError";
|
|
26
|
+
constructor(code: PoolseCryptoErrorCode, message: string);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The blob changed on the server since it was read (`If-Match` failed, or a
|
|
30
|
+
* create found the key already taken). Read it again, merge, and retry.
|
|
31
|
+
*/
|
|
32
|
+
declare class BlobConflictError extends Error {
|
|
33
|
+
readonly key: string;
|
|
34
|
+
/** The server's current version, when the transport knows it. */
|
|
35
|
+
readonly currentVersion: string | null;
|
|
36
|
+
readonly name = "BlobConflictError";
|
|
37
|
+
constructor(key: string,
|
|
38
|
+
/** The server's current version, when the transport knows it. */
|
|
39
|
+
currentVersion?: string | null);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A byte array backed by a plain `ArrayBuffer` — what WebCrypto accepts.
|
|
44
|
+
* Every function here returns one, and inputs are copied into one before
|
|
45
|
+
* they reach `subtle`.
|
|
46
|
+
*/
|
|
47
|
+
type Bytes = Uint8Array<ArrayBuffer>;
|
|
48
|
+
/**
|
|
49
|
+
* Compare two byte arrays without an early exit, so the time taken doesn't
|
|
50
|
+
* say where the first difference is. Lengths are not secret here.
|
|
51
|
+
*/
|
|
52
|
+
declare function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean;
|
|
53
|
+
/** Encode bytes as base64url without padding — safe in URLs and JSON. */
|
|
54
|
+
declare function toBase64Url(bytes: Uint8Array): string;
|
|
55
|
+
/**
|
|
56
|
+
* Decode base64url (padding and the standard `+/` alphabet are accepted
|
|
57
|
+
* too). Throws `PoolseCryptoError('malformed')` on anything else.
|
|
58
|
+
*/
|
|
59
|
+
declare function fromBase64Url(text: string): Bytes;
|
|
60
|
+
declare function toBase32(bytes: Uint8Array): string;
|
|
61
|
+
/**
|
|
62
|
+
* Decode Crockford base32. Case-insensitive; `O` reads as `0`, `I` and `L`
|
|
63
|
+
* as `1`; spaces and hyphens are ignored, so grouped keys paste as typed.
|
|
64
|
+
*/
|
|
65
|
+
declare function fromBase32(text: string): Bytes;
|
|
66
|
+
declare function toHex(bytes: Uint8Array): string;
|
|
67
|
+
declare function fromHex(hex: string): Bytes;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Thin wrappers over WebCrypto. This is the only file that touches
|
|
71
|
+
* `crypto.subtle`; every primitive the library uses is listed here:
|
|
72
|
+
*
|
|
73
|
+
* AES-256-GCM content and key wrapping (96-bit IV, 128-bit tag)
|
|
74
|
+
* HKDF-SHA-256 every derived key, domain-separated by `info`
|
|
75
|
+
* ECDH P-256 key agreement for wrapping to a public key
|
|
76
|
+
* ECDSA P-256 / SHA-256 signatures (raw r||s, 64 bytes)
|
|
77
|
+
* HMAC-SHA-256 device-approval MAC, opaque blob names
|
|
78
|
+
* SHA-256 key ids and fingerprints
|
|
79
|
+
* getRandomValues keys, IVs, salts
|
|
80
|
+
*/
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Check that every algorithm the library needs is present. Useful at app
|
|
84
|
+
* start on React Native, where a missing polyfill otherwise surfaces as a
|
|
85
|
+
* confusing failure much later.
|
|
86
|
+
*/
|
|
87
|
+
declare function checkCryptoSupport(): Promise<{
|
|
88
|
+
ok: boolean;
|
|
89
|
+
missing: string[];
|
|
90
|
+
}>;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The envelope format shared by everything this library writes.
|
|
94
|
+
*
|
|
95
|
+
* Every binary object starts with the same four bytes:
|
|
96
|
+
*
|
|
97
|
+
* 0x70 ('p') magic
|
|
98
|
+
* 0x01 format version — bumped for any incompatible change
|
|
99
|
+
* kind what follows (item, key wrap, attachment, …)
|
|
100
|
+
* alg the algorithm suite it was made with
|
|
101
|
+
*
|
|
102
|
+
* A reader refuses a newer format version or an unknown algorithm with
|
|
103
|
+
* `unsupported`, so old clients fail loudly instead of misreading new data.
|
|
104
|
+
* The header (and every field after it up to the ciphertext) is part of the
|
|
105
|
+
* AES-GCM associated data, so it can't be changed without detection either.
|
|
106
|
+
*/
|
|
107
|
+
|
|
108
|
+
declare const FORMAT_VERSION = 1;
|
|
109
|
+
declare const Kind: {
|
|
110
|
+
readonly Item: 1;
|
|
111
|
+
readonly KeyWrap: 2;
|
|
112
|
+
readonly PublicKeyWrap: 3;
|
|
113
|
+
readonly Attachment: 4;
|
|
114
|
+
readonly DeviceRequest: 5;
|
|
115
|
+
readonly DeviceGrant: 6;
|
|
116
|
+
readonly DevicePublicKeys: 7;
|
|
117
|
+
readonly SyncRecord: 8;
|
|
118
|
+
readonly DeviceSecret: 9;
|
|
119
|
+
};
|
|
120
|
+
type EnvelopeKind = (typeof Kind)[keyof typeof Kind];
|
|
121
|
+
/**
|
|
122
|
+
* Algorithm suites. A new suite gets a new id; existing ids never change
|
|
123
|
+
* meaning.
|
|
124
|
+
*/
|
|
125
|
+
declare const Alg: {
|
|
126
|
+
/** No encryption (only for the device-key export when no wrapping key is given). */
|
|
127
|
+
readonly None: 0;
|
|
128
|
+
/** AES-256-GCM, keys derived with HKDF-SHA-256. */
|
|
129
|
+
readonly Aes256GcmHkdfSha256: 1;
|
|
130
|
+
/** P-256: ECDH + HKDF-SHA-256 + AES-256-GCM for wrapping, ECDSA/SHA-256 for signatures. */
|
|
131
|
+
readonly P256: 2;
|
|
132
|
+
/** HMAC-SHA-256 over a P-256 payload (device grants). */
|
|
133
|
+
readonly HmacSha256: 3;
|
|
134
|
+
};
|
|
135
|
+
type AlgorithmId = (typeof Alg)[keyof typeof Alg];
|
|
136
|
+
/** What `inspectEnvelope` reports without decrypting anything. */
|
|
137
|
+
interface EnvelopeInfo {
|
|
138
|
+
formatVersion: number;
|
|
139
|
+
kind: 'item' | 'key-wrap' | 'public-key-wrap' | 'attachment' | 'device-request' | 'device-grant' | 'device-public-keys' | 'sync-record' | 'device-secret';
|
|
140
|
+
alg: number;
|
|
141
|
+
/** Item key version, for items, attachments and key wraps. */
|
|
142
|
+
keyVersion?: number;
|
|
143
|
+
/** Device id of the recipient, for public key wraps. */
|
|
144
|
+
recipientId?: string;
|
|
145
|
+
/** Revision, for sync records. */
|
|
146
|
+
revision?: number;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Values the ciphertext is bound to without being stored in it — typically
|
|
150
|
+
* the item id and version. Decrypting with different values fails, which
|
|
151
|
+
* stops a server from swapping one item's ciphertext in for another's or
|
|
152
|
+
* serving an old version under a new number.
|
|
153
|
+
*
|
|
154
|
+
* Keys starting with `@` are reserved for the library.
|
|
155
|
+
*/
|
|
156
|
+
type AssociatedData = Readonly<Record<string, string | number>>;
|
|
157
|
+
/**
|
|
158
|
+
* Canonical encoding: a domain label, then the entries sorted by key, each
|
|
159
|
+
* key and value length-prefixed and each value tagged with its type (so
|
|
160
|
+
* `1` and `"1"` differ).
|
|
161
|
+
*/
|
|
162
|
+
declare function encodeAssociatedData(domain: string, data: AssociatedData, internal?: AssociatedData): Bytes;
|
|
163
|
+
declare function padmeLength(length: number): number;
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Throws `malformed` for data this library didn't write and `unsupported`
|
|
167
|
+
* for a newer format version. The values returned are unauthenticated until
|
|
168
|
+
* the envelope is actually decrypted.
|
|
169
|
+
*/
|
|
170
|
+
declare function inspectEnvelope(data: Uint8Array): EnvelopeInfo;
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Key types.
|
|
174
|
+
*
|
|
175
|
+
* DeviceKeys one per device, made on it and never sent anywhere: a P-256
|
|
176
|
+
* ECDH pair (others wrap keys to it) and a P-256 ECDSA pair
|
|
177
|
+
* (it signs what it wraps and approves). The app keeps the
|
|
178
|
+
* exported bytes in the OS keychain / Keystore.
|
|
179
|
+
* AccountKey the user's "notes key": 256 random bits, wrapped for each of
|
|
180
|
+
* their devices and for their recovery key. Item keys are
|
|
181
|
+
* wrapped under it, and ST6 sync derives its keys from it.
|
|
182
|
+
* ItemKey one per note (or other item), 256 random bits with a
|
|
183
|
+
* version number that goes up on every rotation.
|
|
184
|
+
*
|
|
185
|
+
* Secret bytes are held in module-private WeakMaps rather than properties,
|
|
186
|
+
* so they don't show up in logs, `JSON.stringify` or devtools previews.
|
|
187
|
+
*/
|
|
188
|
+
|
|
189
|
+
declare class AccountKey {
|
|
190
|
+
/** Public identifier (base64url) — safe to store next to wraps of this key. */
|
|
191
|
+
readonly id: string;
|
|
192
|
+
private constructor();
|
|
193
|
+
static generate(): Promise<AccountKey>;
|
|
194
|
+
/**
|
|
195
|
+
* From raw bytes, e.g. a copy the app cached in the keychain. Prefer
|
|
196
|
+
* keeping only the device-wrapped copy and unwrapping it at start.
|
|
197
|
+
*/
|
|
198
|
+
static fromBytes(bytes: Uint8Array): Promise<AccountKey>;
|
|
199
|
+
/** A copy of the 32 secret bytes. Handle with care. */
|
|
200
|
+
toBytes(): Uint8Array;
|
|
201
|
+
toJSON(): {
|
|
202
|
+
id: string;
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
declare class ItemKey {
|
|
206
|
+
/** Starts at 1 and goes up by one on every `rotateItemKey`. */
|
|
207
|
+
readonly version: number;
|
|
208
|
+
private constructor();
|
|
209
|
+
static generate(version?: number): ItemKey;
|
|
210
|
+
static fromBytes(bytes: Uint8Array, version: number): ItemKey;
|
|
211
|
+
/** A copy of the 32 secret bytes. Handle with care. */
|
|
212
|
+
toBytes(): Uint8Array;
|
|
213
|
+
toJSON(): {
|
|
214
|
+
version: number;
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* A fresh key with the next version number. Use it when a share is revoked
|
|
219
|
+
* (or expires): re-encrypt the item with the new key and wrap it again for
|
|
220
|
+
* the people who still have access. The removed person keeps whatever they
|
|
221
|
+
* already decrypted; they just can't read anything written from now on.
|
|
222
|
+
*/
|
|
223
|
+
declare function rotateItemKey(previous: ItemKey): ItemKey;
|
|
224
|
+
/** What other devices and the server's directory know about a device. */
|
|
225
|
+
interface DevicePublicKeys {
|
|
226
|
+
/** 16-byte id (base64url) derived from both public keys. */
|
|
227
|
+
readonly id: string;
|
|
228
|
+
/** ECDH P-256 public key, uncompressed (65 bytes). */
|
|
229
|
+
readonly encryption: Uint8Array;
|
|
230
|
+
/** ECDSA P-256 public key, uncompressed (65 bytes). */
|
|
231
|
+
readonly signing: Uint8Array;
|
|
232
|
+
}
|
|
233
|
+
/** Build (and validate) a DevicePublicKeys from its two raw public keys. */
|
|
234
|
+
declare function devicePublicKeys(encryption: Uint8Array, signing: Uint8Array): Promise<DevicePublicKeys>;
|
|
235
|
+
/** Serialise a device's public keys for the Workspace API's key directory. */
|
|
236
|
+
declare function encodeDevicePublicKeys(keys: DevicePublicKeys): string;
|
|
237
|
+
declare function decodeDevicePublicKeys(text: string): Promise<DevicePublicKeys>;
|
|
238
|
+
/** True when both describe the same device (compares the keys themselves). */
|
|
239
|
+
declare function sameDevice(a: DevicePublicKeys, b: DevicePublicKeys): boolean;
|
|
240
|
+
/**
|
|
241
|
+
* A short code people can compare on two screens: 32 base32 characters
|
|
242
|
+
* (160 bits of SHA-256) in groups of four.
|
|
243
|
+
*/
|
|
244
|
+
declare function deviceFingerprint(keys: DevicePublicKeys): Promise<string>;
|
|
245
|
+
interface ExportDeviceKeysOptions {
|
|
246
|
+
/**
|
|
247
|
+
* 32 bytes to encrypt the export with (AES-256-GCM), e.g. a key the OS
|
|
248
|
+
* keeps in the Secure Enclave or a random value in a second keychain item.
|
|
249
|
+
* Without it the export is plain bytes and relies on the keychain alone.
|
|
250
|
+
*/
|
|
251
|
+
wrappingKey?: Uint8Array;
|
|
252
|
+
}
|
|
253
|
+
interface ImportDeviceKeysOptions extends ExportDeviceKeysOptions {
|
|
254
|
+
/** Allow `export()` on the imported keys. Default `false`. */
|
|
255
|
+
extractable?: boolean;
|
|
256
|
+
}
|
|
257
|
+
declare class DeviceKeys {
|
|
258
|
+
readonly publicKeys: DevicePublicKeys;
|
|
259
|
+
private constructor();
|
|
260
|
+
get id(): string;
|
|
261
|
+
/**
|
|
262
|
+
* New key pairs for this device. They are extractable so the app can
|
|
263
|
+
* `export()` them once into the keychain; later loads with `import()` are
|
|
264
|
+
* non-extractable by default.
|
|
265
|
+
*/
|
|
266
|
+
static generate(): Promise<DeviceKeys>;
|
|
267
|
+
/** Bytes for the OS keychain. Only works on keys from `generate()` or an extractable import. */
|
|
268
|
+
export(options?: ExportDeviceKeysOptions): Promise<Uint8Array>;
|
|
269
|
+
static import(bytes: Uint8Array, options?: ImportDeviceKeysOptions): Promise<DeviceKeys>;
|
|
270
|
+
toJSON(): {
|
|
271
|
+
id: string;
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Key wrapping.
|
|
277
|
+
*
|
|
278
|
+
* Symmetric wrap (kind 2) — a key encrypted under another secret key:
|
|
279
|
+
*
|
|
280
|
+
* header(4) | purpose u8 | keyVersion u32 | kekCheck(16) | iv(12) | u16 len | ct
|
|
281
|
+
*
|
|
282
|
+
* Public-key wrap (kind 3) — a key encrypted to a device's ECDH public key
|
|
283
|
+
* (ECIES: a fresh ephemeral P-256 key per wrap, HKDF over the shared secret
|
|
284
|
+
* with both public keys as salt, AES-256-GCM), optionally signed by the
|
|
285
|
+
* sending device:
|
|
286
|
+
*
|
|
287
|
+
* header(4) | purpose u8 | flags u8 | keyVersion u32 | recipientId(16) |
|
|
288
|
+
* ephemeralPublic(65) | [signerPublic(65) if signed] | iv(12) |
|
|
289
|
+
* u16 len | ct | [signature(64) if signed]
|
|
290
|
+
*
|
|
291
|
+
* In both, everything before the ciphertext is AES-GCM associated data
|
|
292
|
+
* together with the caller's associated data (account id, item id), and the
|
|
293
|
+
* signature covers the whole wrap plus that associated data.
|
|
294
|
+
*/
|
|
295
|
+
|
|
296
|
+
/** What a wrapped key is for. Part of the format: never renumber. */
|
|
297
|
+
declare const WrapPurpose: {
|
|
298
|
+
/** The account key, under a recovery key. */
|
|
299
|
+
readonly AccountKeyRecovery: 1;
|
|
300
|
+
/** An item key, under the account key. */
|
|
301
|
+
readonly ItemKey: 2;
|
|
302
|
+
/** An older item key, under its successor (so history stays readable). */
|
|
303
|
+
readonly PreviousItemKey: 3;
|
|
304
|
+
/** The account key, to one of the user's devices. */
|
|
305
|
+
readonly AccountKeyDevice: 4;
|
|
306
|
+
/** An item key, to a recipient's device (sharing). */
|
|
307
|
+
readonly ItemKeyShare: 5;
|
|
308
|
+
};
|
|
309
|
+
type WrapPurposeId = (typeof WrapPurpose)[keyof typeof WrapPurpose];
|
|
310
|
+
interface UnwrapResult<K> {
|
|
311
|
+
key: K;
|
|
312
|
+
/**
|
|
313
|
+
* The signing device, when the caller passed `requireSignatureFrom` (it is
|
|
314
|
+
* one of those). `null` otherwise.
|
|
315
|
+
*/
|
|
316
|
+
signer: DevicePublicKeys | null;
|
|
317
|
+
/** The raw signing key the wrap was signed with, or `null` if unsigned. */
|
|
318
|
+
signingKey: Uint8Array | null;
|
|
319
|
+
}
|
|
320
|
+
interface AccountContext {
|
|
321
|
+
/** The user's account id — binds the wrap to this account. */
|
|
322
|
+
accountId: string;
|
|
323
|
+
}
|
|
324
|
+
interface ItemContext {
|
|
325
|
+
/** The item's stable id — binds the wrap (or ciphertext) to this item. */
|
|
326
|
+
itemId: string;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Wrap the account key for one of the user's devices. Pass `signer` (the
|
|
330
|
+
* device doing the wrapping) so the recipient can check where it came from.
|
|
331
|
+
*/
|
|
332
|
+
declare function wrapAccountKeyForDevice(accountKey: AccountKey, recipient: DevicePublicKeys, options: AccountContext & {
|
|
333
|
+
signer?: DeviceKeys;
|
|
334
|
+
}): Promise<Uint8Array>;
|
|
335
|
+
declare function unwrapAccountKeyForDevice(wrap: Uint8Array, device: DeviceKeys, options: AccountContext & {
|
|
336
|
+
/** Refuse the wrap unless it is signed by one of these devices. */
|
|
337
|
+
requireSignatureFrom?: DevicePublicKeys | readonly DevicePublicKeys[];
|
|
338
|
+
}): Promise<UnwrapResult<AccountKey>>;
|
|
339
|
+
/** Wrap an item key under the account key — how the owner keeps it. */
|
|
340
|
+
declare function wrapItemKey(itemKey: ItemKey, accountKey: AccountKey, options: ItemContext): Promise<Uint8Array>;
|
|
341
|
+
declare function unwrapItemKey(wrap: Uint8Array, accountKey: AccountKey, options: ItemContext): Promise<ItemKey>;
|
|
342
|
+
/**
|
|
343
|
+
* Share an item: wrap its key to one recipient device, signed by the
|
|
344
|
+
* sharing device. For a person, wrap to each of their devices; for a group,
|
|
345
|
+
* to each member's devices (`shareItemKeyWithDevices`).
|
|
346
|
+
*/
|
|
347
|
+
declare function shareItemKey(itemKey: ItemKey, recipient: DevicePublicKeys, options: ItemContext & {
|
|
348
|
+
signer: DeviceKeys;
|
|
349
|
+
}): Promise<Uint8Array>;
|
|
350
|
+
/** `shareItemKey` for many devices: one wrap per device, keyed by device id. */
|
|
351
|
+
declare function shareItemKeyWithDevices(itemKey: ItemKey, recipients: readonly DevicePublicKeys[], options: ItemContext & {
|
|
352
|
+
signer: DeviceKeys;
|
|
353
|
+
}): Promise<{
|
|
354
|
+
deviceId: string;
|
|
355
|
+
wrap: Uint8Array;
|
|
356
|
+
}[]>;
|
|
357
|
+
/**
|
|
358
|
+
* Open a shared item key on the recipient's device. `requireSignatureFrom`
|
|
359
|
+
* is the sharer's devices as the key directory lists them; a wrap signed by
|
|
360
|
+
* anyone else (or unsigned) is refused with `bad-signature`.
|
|
361
|
+
*/
|
|
362
|
+
declare function openSharedItemKey(wrap: Uint8Array, device: DeviceKeys, options: ItemContext & {
|
|
363
|
+
requireSignatureFrom: DevicePublicKeys | readonly DevicePublicKeys[];
|
|
364
|
+
}): Promise<UnwrapResult<ItemKey>>;
|
|
365
|
+
/**
|
|
366
|
+
* After `rotateItemKey`, wrap the old key under the new one so anyone with
|
|
367
|
+
* the new key can still read the item's older versions (NT8).
|
|
368
|
+
*/
|
|
369
|
+
declare function wrapPreviousItemKey(previous: ItemKey, current: ItemKey, options: ItemContext): Promise<Uint8Array>;
|
|
370
|
+
declare function unwrapPreviousItemKey(wrap: Uint8Array, current: ItemKey, options: ItemContext): Promise<ItemKey>;
|
|
371
|
+
|
|
372
|
+
type JsonValue = string | number | boolean | null | JsonValue[] | {
|
|
373
|
+
[key: string]: JsonValue;
|
|
374
|
+
};
|
|
375
|
+
/** What a note (or any item) holds. Titles are encrypted too. */
|
|
376
|
+
interface ItemContent {
|
|
377
|
+
title: string;
|
|
378
|
+
/** The body as your editor stores it: Markdown text or a document tree. */
|
|
379
|
+
body: JsonValue;
|
|
380
|
+
/** Tags, folder, pinned, checklist state… anything the server mustn't read. */
|
|
381
|
+
metadata?: {
|
|
382
|
+
[key: string]: JsonValue;
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* The associated data for an item. `itemId` is required; add `version` for
|
|
387
|
+
* version history (NT8) so one version can't be served as another, and
|
|
388
|
+
* anything else that identifies the slot the ciphertext belongs in.
|
|
389
|
+
*/
|
|
390
|
+
type ItemAssociatedData = AssociatedData & {
|
|
391
|
+
readonly itemId: string;
|
|
392
|
+
};
|
|
393
|
+
/** Encrypt a note's title, body and metadata as one envelope. */
|
|
394
|
+
declare function encryptItem(key: ItemKey, content: ItemContent, ad: ItemAssociatedData): Promise<Uint8Array>;
|
|
395
|
+
declare function decryptItem(key: ItemKey, envelope: Uint8Array, ad: ItemAssociatedData): Promise<ItemContent>;
|
|
396
|
+
/** Encrypt arbitrary small bytes with an item key (e.g. an encrypted folder name). */
|
|
397
|
+
declare function encryptBytes(key: ItemKey, plaintext: Uint8Array, ad: ItemAssociatedData): Promise<Uint8Array>;
|
|
398
|
+
declare function decryptBytes(key: ItemKey, envelope: Uint8Array, ad: ItemAssociatedData): Promise<Uint8Array>;
|
|
399
|
+
|
|
400
|
+
declare const DEFAULT_CHUNK_SIZE: number;
|
|
401
|
+
declare const MIN_CHUNK_SIZE = 16;
|
|
402
|
+
declare const MAX_CHUNK_SIZE: number;
|
|
403
|
+
declare const ATTACHMENT_HEADER_LENGTH: number;
|
|
404
|
+
/** Anything a file's bytes can come from. */
|
|
405
|
+
type ByteSource = Uint8Array | Blob | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array> | Iterable<Uint8Array>;
|
|
406
|
+
/** Associated data for an attachment: the item plus the attachment's own id. */
|
|
407
|
+
type AttachmentAssociatedData = ItemAssociatedData & {
|
|
408
|
+
readonly attachmentId: string;
|
|
409
|
+
};
|
|
410
|
+
interface EncryptAttachmentOptions {
|
|
411
|
+
/** Plaintext bytes per chunk. Default 64 KiB; 16 bytes to 16 MiB. */
|
|
412
|
+
chunkSize?: number;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Encrypt a file as a stream of pieces: the header first, then one piece per
|
|
416
|
+
* chunk. Concatenate them for upload (see `encryptedAttachmentSize` for the
|
|
417
|
+
* total length up front).
|
|
418
|
+
*/
|
|
419
|
+
declare function encryptAttachment(key: ItemKey, source: ByteSource, ad: AttachmentAssociatedData, options?: EncryptAttachmentOptions): AsyncGenerator<Uint8Array>;
|
|
420
|
+
/** Decrypt a stream produced by `encryptAttachment`, chunk by chunk. */
|
|
421
|
+
declare function decryptAttachment(key: ItemKey, source: ByteSource, ad: AttachmentAssociatedData): AsyncGenerator<Uint8Array>;
|
|
422
|
+
/** `encryptAttachment` into one byte array, for files that fit in memory. */
|
|
423
|
+
declare function encryptAttachmentBytes(key: ItemKey, source: ByteSource, ad: AttachmentAssociatedData, options?: EncryptAttachmentOptions): Promise<Uint8Array>;
|
|
424
|
+
/** `decryptAttachment` into one byte array. */
|
|
425
|
+
declare function decryptAttachmentBytes(key: ItemKey, source: ByteSource, ad: AttachmentAssociatedData): Promise<Uint8Array>;
|
|
426
|
+
/** The encrypted size of a `plainSize`-byte file — for Content-Length. */
|
|
427
|
+
declare function encryptedAttachmentSize(plainSize: number, chunkSize?: number): number;
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Recovery key: 128 random bits shown to the user once, so they can restore
|
|
431
|
+
* their account key when every device is gone.
|
|
432
|
+
*
|
|
433
|
+
* It is a random secret, not a password, so no password KDF is needed: 2^128
|
|
434
|
+
* guesses is out of reach whatever the hashing cost. HKDF turns it into the
|
|
435
|
+
* wrapping key.
|
|
436
|
+
*
|
|
437
|
+
* Display form: the 16 secret bytes plus a 4-byte checksum (the first bytes
|
|
438
|
+
* of SHA-256 over a versioned label and the secret), 160 bits in Crockford
|
|
439
|
+
* base32 — 32 characters in eight groups of four:
|
|
440
|
+
*
|
|
441
|
+
* 7K2M-9QXD-4HB0-RT6W-…
|
|
442
|
+
*
|
|
443
|
+
* Parsing ignores case, spaces and hyphens and reads O as 0 and I/L as 1;
|
|
444
|
+
* the checksum catches typos (a mistyped key fails with `checksum`, not by
|
|
445
|
+
* silently deriving a different key).
|
|
446
|
+
*/
|
|
447
|
+
|
|
448
|
+
declare class RecoveryKey {
|
|
449
|
+
#private;
|
|
450
|
+
/** Public identifier (base64url): which recovery key a wrap belongs to. */
|
|
451
|
+
readonly id: string;
|
|
452
|
+
private constructor();
|
|
453
|
+
/** @internal */
|
|
454
|
+
static create(raw: Bytes): Promise<RecoveryKey>;
|
|
455
|
+
/** The key as the user writes it down. Show it once; never log it. */
|
|
456
|
+
toDisplayString(): string;
|
|
457
|
+
/** Deliberately not the secret, so string interpolation can't leak it. */
|
|
458
|
+
toString(): string;
|
|
459
|
+
toJSON(): {
|
|
460
|
+
id: string;
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
declare function generateRecoveryKey(): Promise<RecoveryKey>;
|
|
464
|
+
/** Read a recovery key the user typed or pasted. */
|
|
465
|
+
declare function parseRecoveryKey(text: string): Promise<RecoveryKey>;
|
|
466
|
+
/** Wrap the account key under the recovery key; store the result on the server. */
|
|
467
|
+
declare function wrapAccountKeyWithRecoveryKey(accountKey: AccountKey, recoveryKey: RecoveryKey, options: AccountContext): Promise<Uint8Array>;
|
|
468
|
+
declare function unwrapAccountKeyWithRecoveryKey(wrap: Uint8Array, recoveryKey: RecoveryKey, options: AccountContext): Promise<AccountKey>;
|
|
469
|
+
|
|
470
|
+
/** Requests older than this are refused (and ones further than 2 min in the future). */
|
|
471
|
+
declare const DEFAULT_REQUEST_MAX_AGE_MS: number;
|
|
472
|
+
/** Kept in memory on the new device until the grant arrives. Never persist or send it. */
|
|
473
|
+
interface PendingDeviceRequest {
|
|
474
|
+
readonly device: DevicePublicKeys;
|
|
475
|
+
readonly createdAt: Date;
|
|
476
|
+
}
|
|
477
|
+
/** What the approving device learns from the QR code. */
|
|
478
|
+
interface DeviceRequest {
|
|
479
|
+
readonly device: DevicePublicKeys;
|
|
480
|
+
readonly createdAt: Date;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* On the new device: the QR code text (uppercase base32, which fits a QR
|
|
484
|
+
* code's alphanumeric mode, ~350 characters) and the pending request to keep
|
|
485
|
+
* in memory.
|
|
486
|
+
*/
|
|
487
|
+
declare function createDeviceRequest(device: DeviceKeys, options?: {
|
|
488
|
+
now?: number;
|
|
489
|
+
}): Promise<{
|
|
490
|
+
qr: string;
|
|
491
|
+
pending: PendingDeviceRequest;
|
|
492
|
+
}>;
|
|
493
|
+
/**
|
|
494
|
+
* On the existing device: read and check a scanned QR code. Show
|
|
495
|
+
* `deviceFingerprint(request.device)` and ask the user before approving.
|
|
496
|
+
*/
|
|
497
|
+
declare function readDeviceRequest(qr: string, options?: {
|
|
498
|
+
now?: number;
|
|
499
|
+
maxAgeMs?: number;
|
|
500
|
+
}): Promise<DeviceRequest>;
|
|
501
|
+
/**
|
|
502
|
+
* On the existing device, after the user approved: the grant to send to the
|
|
503
|
+
* new device through the server.
|
|
504
|
+
*/
|
|
505
|
+
declare function approveDeviceRequest(request: DeviceRequest, approver: DeviceKeys, accountKey: AccountKey, options: AccountContext): Promise<Uint8Array>;
|
|
506
|
+
interface AcceptedDeviceGrant {
|
|
507
|
+
accountKey: AccountKey;
|
|
508
|
+
/** The device that approved this one. */
|
|
509
|
+
approver: DevicePublicKeys;
|
|
510
|
+
/** This device's own wrap of the account key — store it to unwrap at the next start. */
|
|
511
|
+
accountKeyWrap: Uint8Array;
|
|
512
|
+
}
|
|
513
|
+
/** On the new device: check the grant and recover the account key. */
|
|
514
|
+
declare function acceptDeviceGrant(grant: Uint8Array, pending: PendingDeviceRequest, device: DeviceKeys, options: AccountContext & {
|
|
515
|
+
now?: number;
|
|
516
|
+
maxAgeMs?: number;
|
|
517
|
+
}): Promise<AcceptedDeviceGrant>;
|
|
518
|
+
|
|
519
|
+
/** One blob as the server lists it. */
|
|
520
|
+
interface BlobInfo {
|
|
521
|
+
key: string;
|
|
522
|
+
/** Opaque version for `If-Match` (the server's ETag, unquoted). */
|
|
523
|
+
version: string;
|
|
524
|
+
size?: number;
|
|
525
|
+
updatedAt?: string;
|
|
526
|
+
}
|
|
527
|
+
/** One entry of the change feed: a blob written or deleted. */
|
|
528
|
+
interface BlobChange extends BlobInfo {
|
|
529
|
+
deleted: boolean;
|
|
530
|
+
}
|
|
531
|
+
/** The server's limits, as it reports them with a listing. */
|
|
532
|
+
interface BlobLimits {
|
|
533
|
+
maxBlobBytes?: number;
|
|
534
|
+
maxUserBytes?: number;
|
|
535
|
+
maxBlobs?: number;
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Preconditions for a write. `ifMatch`: only if the blob is still at that
|
|
539
|
+
* version. `ifNoneMatch: '*'`: only if it doesn't exist yet. Neither:
|
|
540
|
+
* unconditionally.
|
|
541
|
+
*/
|
|
542
|
+
interface BlobPrecondition {
|
|
543
|
+
ifMatch?: string;
|
|
544
|
+
ifNoneMatch?: '*';
|
|
545
|
+
}
|
|
546
|
+
interface BlobListOptions {
|
|
547
|
+
cursor?: string;
|
|
548
|
+
limit?: number;
|
|
549
|
+
/** Only keys starting with this. */
|
|
550
|
+
prefix?: string;
|
|
551
|
+
}
|
|
552
|
+
interface BlobListPage {
|
|
553
|
+
blobs: BlobInfo[];
|
|
554
|
+
/** Pass back for the next page; `null` on the last one. */
|
|
555
|
+
cursor: string | null;
|
|
556
|
+
limits?: BlobLimits;
|
|
557
|
+
}
|
|
558
|
+
interface BlobChangesPage {
|
|
559
|
+
changes: BlobChange[];
|
|
560
|
+
/** Keep it and pass it next time — returned even when nothing changed. */
|
|
561
|
+
cursor: string;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* How the store reaches the server. `createHttpBlobTransport` talks to the
|
|
565
|
+
* poolse server; `MemoryBlobTransport` is an in-memory one for tests.
|
|
566
|
+
*
|
|
567
|
+
* `put` and `delete` must throw `BlobConflictError` when a precondition
|
|
568
|
+
* fails (HTTP 412, or 409 for a create that found the key taken); `get`
|
|
569
|
+
* returns `null` for a missing blob (404). `changes` is optional: a feed of
|
|
570
|
+
* writes and deletions since a cursor, oldest first.
|
|
571
|
+
*/
|
|
572
|
+
interface BlobTransport {
|
|
573
|
+
get(key: string): Promise<{
|
|
574
|
+
data: Uint8Array;
|
|
575
|
+
version: string;
|
|
576
|
+
} | null>;
|
|
577
|
+
put(key: string, data: Uint8Array, precondition: BlobPrecondition): Promise<{
|
|
578
|
+
version: string;
|
|
579
|
+
}>;
|
|
580
|
+
delete(key: string, precondition: BlobPrecondition): Promise<void>;
|
|
581
|
+
list(options: BlobListOptions): Promise<BlobListPage>;
|
|
582
|
+
changes?(options: {
|
|
583
|
+
cursor?: string;
|
|
584
|
+
limit?: number;
|
|
585
|
+
}): Promise<BlobChangesPage>;
|
|
586
|
+
}
|
|
587
|
+
/** An in-memory BlobTransport with the server's If-Match semantics. */
|
|
588
|
+
declare class MemoryBlobTransport implements BlobTransport {
|
|
589
|
+
readonly blobs: Map<string, {
|
|
590
|
+
data: Uint8Array;
|
|
591
|
+
version: string;
|
|
592
|
+
updatedAt: string;
|
|
593
|
+
}>;
|
|
594
|
+
private counter;
|
|
595
|
+
private readonly log;
|
|
596
|
+
private check;
|
|
597
|
+
get(key: string): Promise<{
|
|
598
|
+
data: Uint8Array<ArrayBuffer>;
|
|
599
|
+
version: string;
|
|
600
|
+
} | null>;
|
|
601
|
+
put(key: string, data: Uint8Array, precondition: BlobPrecondition): Promise<{
|
|
602
|
+
version: string;
|
|
603
|
+
}>;
|
|
604
|
+
delete(key: string, precondition: BlobPrecondition): Promise<void>;
|
|
605
|
+
list(options: BlobListOptions): Promise<{
|
|
606
|
+
blobs: {
|
|
607
|
+
key: string;
|
|
608
|
+
version: string;
|
|
609
|
+
size: number;
|
|
610
|
+
updatedAt: string;
|
|
611
|
+
}[];
|
|
612
|
+
cursor: string | null;
|
|
613
|
+
}>;
|
|
614
|
+
changes(options: {
|
|
615
|
+
cursor?: string;
|
|
616
|
+
limit?: number;
|
|
617
|
+
}): Promise<{
|
|
618
|
+
changes: {
|
|
619
|
+
deleted: boolean;
|
|
620
|
+
key: string;
|
|
621
|
+
/** Opaque version for `If-Match` (the server's ETag, unquoted). */
|
|
622
|
+
version: string;
|
|
623
|
+
size?: number;
|
|
624
|
+
updatedAt?: string;
|
|
625
|
+
}[];
|
|
626
|
+
cursor: string;
|
|
627
|
+
}>;
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Where the highest revision seen per blob is remembered. The default is in
|
|
631
|
+
* memory, which catches rollbacks within one session only; give the store a
|
|
632
|
+
* persistent one (IndexedDB, AsyncStorage, a file) to catch them across
|
|
633
|
+
* restarts.
|
|
634
|
+
*/
|
|
635
|
+
interface RevisionStore {
|
|
636
|
+
get(key: string): number | undefined | Promise<number | undefined>;
|
|
637
|
+
set(key: string, revision: number): void | Promise<void>;
|
|
638
|
+
}
|
|
639
|
+
interface EncryptedBlobStoreOptions {
|
|
640
|
+
transport: BlobTransport;
|
|
641
|
+
accountKey: AccountKey;
|
|
642
|
+
/** Separates kinds of data (e.g. `"settings"`, `"drafts"`): each gets its own key. Default `"default"`. */
|
|
643
|
+
namespace?: string;
|
|
644
|
+
revisions?: RevisionStore;
|
|
645
|
+
/** Prefix for every blob key, e.g. `"st6."`. Default none. */
|
|
646
|
+
keyPrefix?: string;
|
|
647
|
+
}
|
|
648
|
+
/** A decrypted blob. */
|
|
649
|
+
interface SyncedBlob {
|
|
650
|
+
name: string;
|
|
651
|
+
data: Uint8Array;
|
|
652
|
+
/** The server's version — pass it as `ifVersion` to write on top of exactly this. */
|
|
653
|
+
version: string;
|
|
654
|
+
revision: number;
|
|
655
|
+
}
|
|
656
|
+
interface PutOptions {
|
|
657
|
+
/**
|
|
658
|
+
* `string`: write only if the blob is still at this version. `null`: only
|
|
659
|
+
* if it doesn't exist. Omitted: on top of the version this store last read
|
|
660
|
+
* or wrote for the name, or as a new blob if it has seen none.
|
|
661
|
+
*/
|
|
662
|
+
ifVersion?: string | null;
|
|
663
|
+
}
|
|
664
|
+
declare class EncryptedBlobStore {
|
|
665
|
+
private readonly transport;
|
|
666
|
+
private readonly accountKey;
|
|
667
|
+
private readonly namespace;
|
|
668
|
+
private readonly keyPrefix;
|
|
669
|
+
private readonly revisions;
|
|
670
|
+
private readonly known;
|
|
671
|
+
private keyPromise;
|
|
672
|
+
private nameKeyPromise;
|
|
673
|
+
constructor(options: EncryptedBlobStoreOptions);
|
|
674
|
+
private contentKey;
|
|
675
|
+
/**
|
|
676
|
+
* The blob key for a name: an HMAC of the namespace and name under a key
|
|
677
|
+
* derived from the account key, so the server can't read names or tell
|
|
678
|
+
* which blob is which across namespaces.
|
|
679
|
+
*/
|
|
680
|
+
blobKey(name: string): Promise<string>;
|
|
681
|
+
private aad;
|
|
682
|
+
private seal;
|
|
683
|
+
private open;
|
|
684
|
+
/** Read by blob key (as `list` returns them). Deleted blobs read as `null`. */
|
|
685
|
+
getByKey(blobKey: string): Promise<SyncedBlob | null>;
|
|
686
|
+
/** Download and decrypt a blob. `null` if it doesn't exist or was deleted. */
|
|
687
|
+
get(name: string): Promise<SyncedBlob | null>;
|
|
688
|
+
getJson<T = unknown>(name: string): Promise<(Omit<SyncedBlob, 'data'> & {
|
|
689
|
+
value: T;
|
|
690
|
+
}) | null>;
|
|
691
|
+
/**
|
|
692
|
+
* Encrypt and upload. Throws `BlobConflictError` when another device wrote
|
|
693
|
+
* first: `get` the newer version, merge, and `put` again (or use `update`).
|
|
694
|
+
*/
|
|
695
|
+
put(name: string, data: Uint8Array, options?: PutOptions): Promise<SyncedBlob>;
|
|
696
|
+
putJson(name: string, value: unknown, options?: PutOptions): Promise<SyncedBlob>;
|
|
697
|
+
/**
|
|
698
|
+
* Delete by writing an encrypted tombstone, so the deletion is authenticated
|
|
699
|
+
* and the revision keeps counting (a plain DELETE could be forged or undone
|
|
700
|
+
* by the server). `purge` removes the blob for real.
|
|
701
|
+
*/
|
|
702
|
+
delete(name: string, options?: PutOptions): Promise<void>;
|
|
703
|
+
/** Remove the blob from the server. Unauthenticated: prefer `delete`. */
|
|
704
|
+
purge(name: string, options?: PutOptions): Promise<void>;
|
|
705
|
+
/**
|
|
706
|
+
* Read, change, write — retried on conflict. `change` gets the current
|
|
707
|
+
* data (`null` if none) and returns the new data, or `null` to delete.
|
|
708
|
+
* It may run more than once, so keep it free of side effects.
|
|
709
|
+
*/
|
|
710
|
+
update(name: string, change: (current: Uint8Array | null) => Uint8Array | null | Promise<Uint8Array | null>, options?: {
|
|
711
|
+
retries?: number;
|
|
712
|
+
}): Promise<SyncedBlob | null>;
|
|
713
|
+
updateJson<T>(name: string, change: (current: T | null) => T | null | Promise<T | null>, options?: {
|
|
714
|
+
retries?: number;
|
|
715
|
+
}): Promise<T | null>;
|
|
716
|
+
/**
|
|
717
|
+
* One page of this user's blobs (under `keyPrefix`, if set). Read each with
|
|
718
|
+
* `getByKey`.
|
|
719
|
+
*/
|
|
720
|
+
list(options?: {
|
|
721
|
+
cursor?: string;
|
|
722
|
+
limit?: number;
|
|
723
|
+
}): Promise<BlobListPage>;
|
|
724
|
+
/**
|
|
725
|
+
* What changed since `cursor` (writes and deletions, oldest first), under
|
|
726
|
+
* `keyPrefix` if set. Keep the returned cursor; read changed blobs with
|
|
727
|
+
* `getByKey` (a deleted one reads as `null`). Needs a transport with
|
|
728
|
+
* `changes` (the HTTP one has it).
|
|
729
|
+
*/
|
|
730
|
+
changes(options?: {
|
|
731
|
+
cursor?: string;
|
|
732
|
+
limit?: number;
|
|
733
|
+
}): Promise<BlobChangesPage>;
|
|
734
|
+
private write;
|
|
735
|
+
private remember;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Why a blob request failed (other than a version conflict, which is
|
|
740
|
+
* `BlobConflictError`).
|
|
741
|
+
*
|
|
742
|
+
* - `too_large` — the blob is over the server's per-blob limit (413).
|
|
743
|
+
* - `quota_exceeded` — the user's encrypted storage is full (413).
|
|
744
|
+
* - `sync_disabled` — the workspace turned encrypted sync off (403).
|
|
745
|
+
* - `rate_limited` — too many requests (429); see `retryAfterMs`.
|
|
746
|
+
* - `invalid_key` — the key isn't 1–128 of `a–z 0–9 .` (checked before sending, and 422).
|
|
747
|
+
* - `unauthorized` — the token was refused, even after asking `getToken` again (401).
|
|
748
|
+
* - `forbidden` — any other 403.
|
|
749
|
+
* - `not_found` — a 404 where one isn't expected (e.g. a list endpoint).
|
|
750
|
+
* - `server` — a 5xx.
|
|
751
|
+
* - `network` — `fetch` itself failed (offline, DNS, CORS).
|
|
752
|
+
* - `bad_response` — a success without the ETag or JSON the contract promises
|
|
753
|
+
* (in a browser, usually `ETag` missing from `Access-Control-Expose-Headers`).
|
|
754
|
+
* - `http` — any other status.
|
|
755
|
+
*/
|
|
756
|
+
type BlobTransportErrorCode = 'too_large' | 'quota_exceeded' | 'sync_disabled' | 'rate_limited' | 'invalid_key' | 'unauthorized' | 'forbidden' | 'not_found' | 'server' | 'network' | 'bad_response' | 'http';
|
|
757
|
+
declare class BlobTransportError extends Error {
|
|
758
|
+
readonly code: BlobTransportErrorCode;
|
|
759
|
+
/** HTTP status, or 0 when no response arrived. */
|
|
760
|
+
readonly status: number;
|
|
761
|
+
/** The server's own `error.code`, when it sent one. */
|
|
762
|
+
readonly serverCode: string | null;
|
|
763
|
+
/** From `Retry-After`, for `rate_limited`. */
|
|
764
|
+
readonly retryAfterMs: number | null;
|
|
765
|
+
readonly name = "BlobTransportError";
|
|
766
|
+
constructor(code: BlobTransportErrorCode, message: string,
|
|
767
|
+
/** HTTP status, or 0 when no response arrived. */
|
|
768
|
+
status?: number,
|
|
769
|
+
/** The server's own `error.code`, when it sent one. */
|
|
770
|
+
serverCode?: string | null,
|
|
771
|
+
/** From `Retry-After`, for `rate_limited`. */
|
|
772
|
+
retryAfterMs?: number | null);
|
|
773
|
+
/** Worth retrying later as is (rate limit, server error, network). */
|
|
774
|
+
get retryable(): boolean;
|
|
775
|
+
}
|
|
776
|
+
interface HttpBlobTransportOptions {
|
|
777
|
+
/** The poolse server, e.g. `https://chat.example.com` (no trailing `/v1`). */
|
|
778
|
+
apiUrl: string;
|
|
779
|
+
/** The signed-in user's token (Bearer). Called per request and again once after a 401. */
|
|
780
|
+
getToken: () => string | Promise<string>;
|
|
781
|
+
/** Defaults to `globalThis.fetch`. */
|
|
782
|
+
fetch?: typeof fetch;
|
|
783
|
+
}
|
|
784
|
+
/** True when the server accepts `key`: 1–128 of `a–z 0–9 .`, no leading/trailing dot, no `..`. */
|
|
785
|
+
declare function isValidBlobKey(key: string): boolean;
|
|
786
|
+
/**
|
|
787
|
+
* The BlobTransport for `EncryptedBlobStore` against a poolse server.
|
|
788
|
+
*
|
|
789
|
+
* - `get`: 200 → bytes and the ETag's version; 404 → `null`.
|
|
790
|
+
* - `put`: sends `If-Match: "<version>"` or `If-None-Match: *`; 200/201 →
|
|
791
|
+
* the new version (ETag, else the JSON `version`); 412/409 →
|
|
792
|
+
* `BlobConflictError`.
|
|
793
|
+
* - `delete`: 204 → done; 412/409 → `BlobConflictError`; 404 → done when no
|
|
794
|
+
* `ifMatch` was given (already gone), else `BlobConflictError`.
|
|
795
|
+
* - `list` / `changes`: the JSON pages, versions taken from each `etag`.
|
|
796
|
+
* - Anything else throws `BlobTransportError`. Nothing is retried except one
|
|
797
|
+
* new token after a 401; on `rate_limited` wait `retryAfterMs`.
|
|
798
|
+
*/
|
|
799
|
+
declare function createHttpBlobTransport(options: HttpBlobTransportOptions): BlobTransport & {
|
|
800
|
+
changes(options: {
|
|
801
|
+
cursor?: string;
|
|
802
|
+
limit?: number;
|
|
803
|
+
}): Promise<BlobChangesPage>;
|
|
804
|
+
};
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* Workspace notes (apps/workspace/NOTES.md) on top of the primitives: the
|
|
808
|
+
* associated data every note ciphertext binds, sealing and opening a note's
|
|
809
|
+
* `meta` and `content`, folder names, share wraps for recipients' devices,
|
|
810
|
+
* key rotation on revoke or expiry (NT5, NT15), walking `key_history` for
|
|
811
|
+
* versions (NT8), the recovery-key auth and the device signatures the server
|
|
812
|
+
* checks (NT10), and the plain document handed to an agent (NT12).
|
|
813
|
+
*
|
|
814
|
+
* Everything here returns base64url strings in the field names the
|
|
815
|
+
* Workspace API uses, so a result can go straight into a request body.
|
|
816
|
+
*/
|
|
817
|
+
|
|
818
|
+
/** `{itemId: note.id, version: revision, slot: "meta" | "content"}`. */
|
|
819
|
+
declare function noteAssociatedData(noteId: string, revision: number, slot: 'meta' | 'content'): {
|
|
820
|
+
readonly itemId: string;
|
|
821
|
+
readonly version: number;
|
|
822
|
+
readonly slot: "meta" | "content";
|
|
823
|
+
};
|
|
824
|
+
/** `{itemId: note.id, attachmentId}` for `encryptAttachment` / `decryptAttachment`. */
|
|
825
|
+
declare function noteAttachmentAssociatedData(noteId: string, attachmentId: string): {
|
|
826
|
+
readonly itemId: string;
|
|
827
|
+
readonly attachmentId: string;
|
|
828
|
+
};
|
|
829
|
+
/** `{itemId: folder.id, slot: "folder"}`. */
|
|
830
|
+
declare function folderAssociatedData(folderId: string): {
|
|
831
|
+
readonly itemId: string;
|
|
832
|
+
readonly slot: "folder";
|
|
833
|
+
};
|
|
834
|
+
/** What a note holds: title, body and metadata (tags, pinned, attachment names…). */
|
|
835
|
+
type NoteContent = ItemContent;
|
|
836
|
+
/** The encrypted fields of an e2e note write. */
|
|
837
|
+
interface SealedNote {
|
|
838
|
+
/** `{title, body: null, metadata}` — what lists show. */
|
|
839
|
+
meta: string;
|
|
840
|
+
/** The whole note. */
|
|
841
|
+
content: string;
|
|
842
|
+
key_version: number;
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Encrypt a note for the revision this write creates (`base_revision + 1`).
|
|
846
|
+
* `meta` carries the title and metadata without the body, so lists can show
|
|
847
|
+
* a title and tags without fetching the content.
|
|
848
|
+
*/
|
|
849
|
+
declare function sealNote(key: ItemKey, note: NoteContent, options: {
|
|
850
|
+
noteId: string;
|
|
851
|
+
revision: number;
|
|
852
|
+
}): Promise<SealedNote>;
|
|
853
|
+
/** Decrypt a note's `meta` (listing form): title and metadata. */
|
|
854
|
+
declare function openNoteMeta(key: ItemKey, meta: string, options: {
|
|
855
|
+
noteId: string;
|
|
856
|
+
revision: number;
|
|
857
|
+
}): Promise<{
|
|
858
|
+
title: string;
|
|
859
|
+
metadata: {
|
|
860
|
+
[key: string]: JsonValue;
|
|
861
|
+
};
|
|
862
|
+
}>;
|
|
863
|
+
/**
|
|
864
|
+
* Decrypt a note's `content` — the note itself, or one of its versions
|
|
865
|
+
* (NT8: pass the version's own `revision`, and the key for its
|
|
866
|
+
* `key_version` from `noteKeyForVersion`).
|
|
867
|
+
*/
|
|
868
|
+
declare function openNoteContent(key: ItemKey, content: string, options: {
|
|
869
|
+
noteId: string;
|
|
870
|
+
revision: number;
|
|
871
|
+
}): Promise<NoteContent>;
|
|
872
|
+
/** The key version an envelope (`meta`, `content`, a version) was written with. */
|
|
873
|
+
declare function envelopeKeyVersion(envelope: string): number;
|
|
874
|
+
/**
|
|
875
|
+
* The key a version was written with (NT8): `current` when the versions
|
|
876
|
+
* match, else unwrap `key_history` back one step at a time
|
|
877
|
+
* (`key_history[v]` is key `v` wrapped under key `v + 1`).
|
|
878
|
+
*/
|
|
879
|
+
declare function noteKeyForVersion(current: ItemKey, keyHistory: Readonly<Record<string, string>>, version: number, options: {
|
|
880
|
+
noteId: string;
|
|
881
|
+
}): Promise<ItemKey>;
|
|
882
|
+
/** A new folder key, its name envelope and its key wrap under the account key. */
|
|
883
|
+
declare function sealFolder(name: string, accountKey: AccountKey, options: {
|
|
884
|
+
folderId: string;
|
|
885
|
+
key?: ItemKey;
|
|
886
|
+
}): Promise<{
|
|
887
|
+
key: ItemKey;
|
|
888
|
+
name_envelope: string;
|
|
889
|
+
key_wrap: string;
|
|
890
|
+
}>;
|
|
891
|
+
declare function openFolderName(key: ItemKey, nameEnvelope: string, options: {
|
|
892
|
+
folderId: string;
|
|
893
|
+
}): Promise<string>;
|
|
894
|
+
/** A recipient from `POST /notes/keys/lookup`: their approved devices. */
|
|
895
|
+
interface NoteRecipient {
|
|
896
|
+
memberId: string;
|
|
897
|
+
devices: readonly DevicePublicKeys[];
|
|
898
|
+
}
|
|
899
|
+
/** One entry of `wraps` / `share_wraps`. */
|
|
900
|
+
interface NoteShareWrap {
|
|
901
|
+
member_id: string;
|
|
902
|
+
device_id: string;
|
|
903
|
+
wrap: string;
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* The note key wrapped to every device of every recipient, signed by this
|
|
907
|
+
* device — the `wraps` of `POST /notes/:id/shares` and `POST /notes/:id/wraps`.
|
|
908
|
+
* Viewers and editors (NT16) get the same wrap: an editor writes content
|
|
909
|
+
* with the same key, and the server enforces who may write.
|
|
910
|
+
*/
|
|
911
|
+
declare function shareWrapsFor(key: ItemKey, recipients: readonly NoteRecipient[], options: {
|
|
912
|
+
noteId: string;
|
|
913
|
+
signer: DeviceKeys;
|
|
914
|
+
}): Promise<NoteShareWrap[]>;
|
|
915
|
+
/** The fields of a `PUT /notes/:id` that rotates the key. */
|
|
916
|
+
interface RotatedNote extends SealedNote {
|
|
917
|
+
key: ItemKey;
|
|
918
|
+
key_wrap: string;
|
|
919
|
+
key_history: Record<string, string>;
|
|
920
|
+
share_wraps: NoteShareWrap[];
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* Rotate a note's key after a revoke or an expired share (`notes:rotate`):
|
|
924
|
+
* a new key one version up, the note re-encrypted for `revision`, the new
|
|
925
|
+
* key wrapped for the owner, the old key kept readable under the new one
|
|
926
|
+
* (`key_history`), and wraps for the people who keep access. Send it with
|
|
927
|
+
* the note's current `base_revision`; nothing written after this is
|
|
928
|
+
* readable with the old key.
|
|
929
|
+
*/
|
|
930
|
+
declare function rotateNoteKey(previous: ItemKey, note: NoteContent, options: {
|
|
931
|
+
noteId: string;
|
|
932
|
+
revision: number;
|
|
933
|
+
accountKey: AccountKey;
|
|
934
|
+
signer: DeviceKeys;
|
|
935
|
+
/** Everyone still shared with, with their devices. */
|
|
936
|
+
remaining: readonly NoteRecipient[];
|
|
937
|
+
}): Promise<RotatedNote>;
|
|
938
|
+
/** Whether a share has ended by `now` (NT15): the owner then rotates like on a revoke. */
|
|
939
|
+
declare function shareExpired(expiresAt: string | null | undefined, now?: number): boolean;
|
|
940
|
+
/**
|
|
941
|
+
* 32 bytes the server keeps the SHA-256 of, proving a device holds the
|
|
942
|
+
* recovery key without revealing it: HKDF-SHA-256 of the key's secret
|
|
943
|
+
* (empty salt, info `poolse-crypto/v1/recovery-auth`). Send as
|
|
944
|
+
* `recovery.auth` / `recovery_auth` (base64url).
|
|
945
|
+
*/
|
|
946
|
+
declare function recoveryAuth(recoveryKey: RecoveryKey): Promise<Uint8Array>;
|
|
947
|
+
/** Raw ECDSA P-256 / SHA-256 signature (`r‖s`, 64 bytes) by this device's signing key. */
|
|
948
|
+
declare function signForServer(device: DeviceKeys, message: Uint8Array): Promise<Uint8Array>;
|
|
949
|
+
/**
|
|
950
|
+
* `"poolse-notes/v1/approve" ‖ 0 ‖ member_id ‖ 0 ‖ new device_id ‖ 0 ‖ SHA-256(grant)` —
|
|
951
|
+
* what the approving device signs for `POST …/devices/:id/grant`.
|
|
952
|
+
*/
|
|
953
|
+
declare function deviceApprovalMessage(memberId: string, newDeviceId: string, grant: Uint8Array): Promise<Bytes>;
|
|
954
|
+
/**
|
|
955
|
+
* `"poolse-notes/v1/recovery" ‖ 0 ‖ member_id ‖ 0 ‖ key_id ‖ 0 ‖ SHA-256(wrap) ‖ SHA-256(auth)` —
|
|
956
|
+
* what an approved device signs for `PUT /notes/keys/me/recovery`.
|
|
957
|
+
*/
|
|
958
|
+
declare function recoveryReplaceMessage(memberId: string, keyId: string, wrap: Uint8Array, auth: Uint8Array): Promise<Bytes>;
|
|
959
|
+
/** The body of `POST …/devices/:id/grant`, signed by `approver`. */
|
|
960
|
+
declare function signedDeviceGrant(grant: Uint8Array, options: {
|
|
961
|
+
memberId: string;
|
|
962
|
+
newDeviceId: string;
|
|
963
|
+
approver: DeviceKeys;
|
|
964
|
+
}): Promise<{
|
|
965
|
+
grant: string;
|
|
966
|
+
approver_device_id: string;
|
|
967
|
+
signature: string;
|
|
968
|
+
}>;
|
|
969
|
+
/**
|
|
970
|
+
* A decrypted note as a plain Markdown document for one agent task. Only
|
|
971
|
+
* this note leaves the device, decrypted; call it only after the member
|
|
972
|
+
* explicitly chose to hand it over. A body that isn't a string (an editor
|
|
973
|
+
* document tree) needs `toMarkdown`.
|
|
974
|
+
*/
|
|
975
|
+
declare function noteAsDocument(note: NoteContent, toMarkdown?: (body: JsonValue) => string): {
|
|
976
|
+
title: string;
|
|
977
|
+
markdown: string;
|
|
978
|
+
};
|
|
979
|
+
|
|
980
|
+
/** Lowercased, accent-free words of `text` (letters and digits). */
|
|
981
|
+
declare function searchWords(text: string): string[];
|
|
982
|
+
/** What one note contributes to the index. */
|
|
983
|
+
interface SearchDocument {
|
|
984
|
+
title: string;
|
|
985
|
+
/** Plain text of the body (and anything else searchable: tags, attachment names). */
|
|
986
|
+
text: string;
|
|
987
|
+
/** For ordering ties: ISO time or ms. */
|
|
988
|
+
updatedAt?: string | number;
|
|
989
|
+
}
|
|
990
|
+
interface SearchHit {
|
|
991
|
+
id: string;
|
|
992
|
+
score: number;
|
|
993
|
+
}
|
|
994
|
+
declare class NoteSearchIndex {
|
|
995
|
+
#private;
|
|
996
|
+
/** Notes in the index. */
|
|
997
|
+
get size(): number;
|
|
998
|
+
/** Add or replace a note. */
|
|
999
|
+
put(id: string, doc: SearchDocument): void;
|
|
1000
|
+
remove(id: string): void;
|
|
1001
|
+
has(id: string): boolean;
|
|
1002
|
+
clear(): void;
|
|
1003
|
+
/** Note ids matching every word of `query`, best first. Empty query → nothing. */
|
|
1004
|
+
search(query: string, limit?: number): SearchHit[];
|
|
1005
|
+
/** The index encrypted for this device's storage. `name` keeps several indexes apart. */
|
|
1006
|
+
seal(accountKey: AccountKey, name?: string): Promise<Uint8Array>;
|
|
1007
|
+
static open(sealed: Uint8Array, accountKey: AccountKey, name?: string): Promise<NoteSearchIndex>;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/** One waiting write. `data` is whatever the app needs to seal it (plaintext). */
|
|
1011
|
+
interface OutboxEntry<T> {
|
|
1012
|
+
noteId: string;
|
|
1013
|
+
op: 'put' | 'delete';
|
|
1014
|
+
/** The revision the edit was made on (0 for a note made offline). */
|
|
1015
|
+
baseRevision: number;
|
|
1016
|
+
data: T | null;
|
|
1017
|
+
/** When it was queued (ms). */
|
|
1018
|
+
queuedAt: number;
|
|
1019
|
+
/** Failed attempts so far. */
|
|
1020
|
+
attempts: number;
|
|
1021
|
+
}
|
|
1022
|
+
/** Where the sealed queue lives: a file, IndexedDB, AsyncStorage… */
|
|
1023
|
+
interface OutboxStorage {
|
|
1024
|
+
read(): Promise<Uint8Array | null>;
|
|
1025
|
+
write(data: Uint8Array): Promise<void>;
|
|
1026
|
+
}
|
|
1027
|
+
/** What `send` reports for one write. */
|
|
1028
|
+
type OutboxSendResult<T> = {
|
|
1029
|
+
status: 'ok';
|
|
1030
|
+
revision: number;
|
|
1031
|
+
}
|
|
1032
|
+
/** `409 revision_conflict`: the server's current note, decrypted by the app. */
|
|
1033
|
+
| {
|
|
1034
|
+
status: 'conflict';
|
|
1035
|
+
revision: number;
|
|
1036
|
+
current: T | null;
|
|
1037
|
+
}
|
|
1038
|
+
/** Gone for good (deleted, access lost): drop the entry. */
|
|
1039
|
+
| {
|
|
1040
|
+
status: 'gone';
|
|
1041
|
+
};
|
|
1042
|
+
interface FlushOptions<T> {
|
|
1043
|
+
/** Seal and send one write (`PUT /notes/:id` with `base_revision`, or `DELETE`). Throw to stop and retry later. */
|
|
1044
|
+
send: (entry: OutboxEntry<T>) => Promise<OutboxSendResult<T>>;
|
|
1045
|
+
/**
|
|
1046
|
+
* Merge a conflicting edit with the server's version (`current`). Return
|
|
1047
|
+
* the data to write on top of `revision`, or `null` to drop the local
|
|
1048
|
+
* edit. Default: keep the local edit (last writer wins).
|
|
1049
|
+
*/
|
|
1050
|
+
resolve?: (local: T | null, current: T | null, entry: OutboxEntry<T>) => T | null | Promise<T | null>;
|
|
1051
|
+
/** Called after each accepted write with the note's new revision. */
|
|
1052
|
+
onWritten?: (noteId: string, revision: number) => void;
|
|
1053
|
+
/** Conflicts retried per entry before it's dropped. Default 3. */
|
|
1054
|
+
maxConflicts?: number;
|
|
1055
|
+
}
|
|
1056
|
+
interface FlushResult {
|
|
1057
|
+
written: string[];
|
|
1058
|
+
dropped: string[];
|
|
1059
|
+
/** Entries still waiting (the send threw). */
|
|
1060
|
+
pending: number;
|
|
1061
|
+
error?: unknown;
|
|
1062
|
+
}
|
|
1063
|
+
declare class NoteOutbox<T> {
|
|
1064
|
+
#private;
|
|
1065
|
+
private constructor();
|
|
1066
|
+
static load<T>(options: {
|
|
1067
|
+
storage: OutboxStorage;
|
|
1068
|
+
accountKey: AccountKey;
|
|
1069
|
+
}): Promise<NoteOutbox<T>>;
|
|
1070
|
+
/** Waiting writes, oldest first. */
|
|
1071
|
+
get entries(): readonly OutboxEntry<T>[];
|
|
1072
|
+
/** Whether a note has unsent edits (show "Not synced yet"). */
|
|
1073
|
+
isPending(noteId: string): boolean;
|
|
1074
|
+
/** Queue an edit (or a new note, `baseRevision` 0). Replaces an earlier queued edit of the note. */
|
|
1075
|
+
put(noteId: string, baseRevision: number, data: T): Promise<void>;
|
|
1076
|
+
/** Queue a delete. A note made offline and never sent is just forgotten. */
|
|
1077
|
+
delete(noteId: string, baseRevision: number): Promise<void>;
|
|
1078
|
+
/** Send everything, in order. Concurrent calls share one run. */
|
|
1079
|
+
flush(options: FlushOptions<T>): Promise<FlushResult>;
|
|
1080
|
+
}
|
|
1081
|
+
/** An in-memory `OutboxStorage` for tests. */
|
|
1082
|
+
declare class MemoryOutboxStorage implements OutboxStorage {
|
|
1083
|
+
data: Uint8Array | null;
|
|
1084
|
+
read(): Promise<Uint8Array | null>;
|
|
1085
|
+
write(data: Uint8Array): Promise<void>;
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
export { ATTACHMENT_HEADER_LENGTH, type AcceptedDeviceGrant, type AccountContext, AccountKey, Alg, type AlgorithmId, type AssociatedData, type AttachmentAssociatedData, type BlobChange, type BlobChangesPage, BlobConflictError, type BlobInfo, type BlobLimits, type BlobListOptions, type BlobListPage, type BlobPrecondition, type BlobTransport, BlobTransportError, type BlobTransportErrorCode, type ByteSource, DEFAULT_CHUNK_SIZE, DEFAULT_REQUEST_MAX_AGE_MS, DeviceKeys, type DevicePublicKeys, type DeviceRequest, type EncryptAttachmentOptions, EncryptedBlobStore, type EncryptedBlobStoreOptions, type EnvelopeInfo, type EnvelopeKind, type ExportDeviceKeysOptions, FORMAT_VERSION, type FlushOptions, type FlushResult, type HttpBlobTransportOptions, type ImportDeviceKeysOptions, type ItemAssociatedData, type ItemContent, type ItemContext, ItemKey, type JsonValue, Kind, MAX_CHUNK_SIZE, MIN_CHUNK_SIZE, MemoryBlobTransport, MemoryOutboxStorage, type NoteContent, NoteOutbox, type NoteRecipient, NoteSearchIndex, type NoteShareWrap, type OutboxEntry, type OutboxSendResult, type OutboxStorage, type PendingDeviceRequest, PoolseCryptoError, type PoolseCryptoErrorCode, type PutOptions, RecoveryKey, type RevisionStore, type RotatedNote, type SealedNote, type SearchDocument, type SearchHit, type SyncedBlob, type UnwrapResult, WrapPurpose, type WrapPurposeId, acceptDeviceGrant, approveDeviceRequest, checkCryptoSupport, constantTimeEqual, createDeviceRequest, createHttpBlobTransport, decodeDevicePublicKeys, decryptAttachment, decryptAttachmentBytes, decryptBytes, decryptItem, deviceApprovalMessage, deviceFingerprint, devicePublicKeys, encodeAssociatedData, encodeDevicePublicKeys, encryptAttachment, encryptAttachmentBytes, encryptBytes, encryptItem, encryptedAttachmentSize, envelopeKeyVersion, folderAssociatedData, fromBase32, fromBase64Url, fromHex, generateRecoveryKey, inspectEnvelope, isValidBlobKey, noteAsDocument, noteAssociatedData, noteAttachmentAssociatedData, noteKeyForVersion, openFolderName, openNoteContent, openNoteMeta, openSharedItemKey, padmeLength, parseRecoveryKey, readDeviceRequest, recoveryAuth, recoveryReplaceMessage, rotateItemKey, rotateNoteKey, sameDevice, sealFolder, sealNote, searchWords, shareExpired, shareItemKey, shareItemKeyWithDevices, shareWrapsFor, signForServer, signedDeviceGrant, toBase32, toBase64Url, toHex, unwrapAccountKeyForDevice, unwrapAccountKeyWithRecoveryKey, unwrapItemKey, unwrapPreviousItemKey, wrapAccountKeyForDevice, wrapAccountKeyWithRecoveryKey, wrapItemKey, wrapPreviousItemKey };
|