@myfield/sdk 0.9.2 → 0.9.3

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/docs/API.md DELETED
@@ -1,298 +0,0 @@
1
- # @myfield/sdk API (v1 draft)
2
-
3
- `@myfield/sdk` exposes a local-first encrypted object bucket. Local reads and
4
- writes work without an account. `connect()` binds the bucket to Myfield auth and
5
- encrypted sync.
6
-
7
- For an overview, quickstart and service boundaries, see the [README](../README.md).
8
-
9
- ## `createInstance`
10
-
11
- ```ts
12
- createInstance(appId: string): Instance;
13
- createInstance(options?: {
14
- appId?: string;
15
- namespace?: string; // Existing storage scope.
16
- storage?: "indexeddb" | "memory";
17
- authUrl?: string; // Defaults to https://myfield.one/auth/.
18
- }): Instance;
19
- ```
20
-
21
- `appId` defaults to the browser hostname. Use lowercase ASCII domain-form names,
22
- 1–63 characters.
23
-
24
- `authUrl` is the Auth page opened when authorization is needed, for example a dev page.
25
- It must be an absolute HTTP(S) page URL without credentials, query or fragment, is used
26
- as given and applies to every bucket of the Instance. Saved access keeps the API address
27
- returned by authorization, also after `authUrl` changes. To switch environments on one
28
- origin, use a separate `namespace` per environment, or call `disconnect()` before
29
- `connect()`.
30
-
31
- ## Buckets
32
-
33
- ```ts
34
- instance.getBucket(): Bucket;
35
- instance.createBucket(options: { id: string }): Bucket;
36
- ```
37
-
38
- - `getBucket()` returns the cached default bucket, whose id is appId.
39
- - `createBucket()` remains available for other buckets. Use a stable domain-shaped id, usually the app host, for
40
- example `"app.example.com"`.
41
- - Creating a bucket is local-only: no network and no account.
42
- - The local bucket id is the user-facing resource label. Myfield may bind it to
43
- a different remote bucket id during `connect()`; apps must not assume they
44
- are the same.
45
- - Valid ids use lowercase `a-z0-9`, `.`, and `-`, max 63 chars.
46
-
47
- ## Local Object API
48
-
49
- Local operations work before `connect()` and never wait for network sync. They
50
- initialize storage lazily; storage errors surface on first use.
51
-
52
- ```ts
53
- bucket.put(id: string, object: Record<string, unknown>): Promise<void>;
54
- bucket.update(id: string, fields: Record<string, unknown>): Promise<void>;
55
- bucket.delete(id: string): Promise<void>;
56
-
57
- bucket.get(id: string): Promise<Record<string, unknown> | null>;
58
- bucket.binary(input: Blob | File | ArrayBuffer | Uint8Array, options?: {
59
- mimeType?: string;
60
- name?: string;
61
- lastModified?: number;
62
- }): BucketBinaryValue;
63
- bucket.list(options?: {
64
- prefix?: string;
65
- includeDeleted?: boolean; // default false
66
- }): Promise<Array<{ id: string; updatedAt: string; deleted?: true }>>;
67
- ```
68
-
69
- ### Write Semantics
70
-
71
- - `put(id, object)` writes a whole object from this device's point of view.
72
- Omitted fields that this device already knows are deleted; fields unknown
73
- locally, such as concurrent remote additions, are preserved on merge.
74
- - `update(id, fields)` writes top-level fields and preserves omitted fields.
75
- Setting a field to `undefined` deletes it. Updating a missing/deleted object
76
- recreates it.
77
- - Unchanged field values do not advance field timestamps.
78
- - Merge granularity is top-level fields. Nested values are replaced wholesale.
79
-
80
- ### Binary Fields
81
-
82
- Binary content is stored as a typed field value. The SDK does not interpret file
83
- semantics; app-owned fields such as `name`, `mimeType`, `size`, or `kind` remain
84
- ordinary application data.
85
-
86
- ```ts
87
- await bucket.put("file:1", {
88
- kind: "file",
89
- name: file.name,
90
- mimeType: file.type,
91
- size: file.size,
92
- content: bucket.binary(file),
93
- });
94
-
95
- const saved = await bucket.get("file:1");
96
- const content = saved?.content;
97
- if (content?.kind === "binary") {
98
- const blob = await content.blob();
99
- const bytes = await content.arrayBuffer();
100
- }
101
- ```
102
-
103
- `bucket.binary()` accepts `Blob`, `File`, `ArrayBuffer`, and `Uint8Array`.
104
- Read-side binary values expose:
105
-
106
- ```ts
107
- type BucketBinaryValue = {
108
- kind: "binary";
109
- size: number;
110
- mimeType?: string;
111
- name?: string;
112
- lastModified?: number;
113
- blob(): Promise<Blob>;
114
- arrayBuffer(): Promise<ArrayBuffer>;
115
- };
116
- ```
117
-
118
- Binary fields are inline in the same encrypted SDK object payload. They use the
119
- same field-level LWW ordering as other fields. The worker API is unchanged and
120
- continues to see only opaque encrypted object payloads.
121
-
122
- Upload limits depend on the service (currently up to 64 MiB for MyField).
123
- SDK-level large-file support is under consideration; apps currently handle
124
- splitting files across objects.
125
-
126
- ### Read And List
127
-
128
- - `get(id)` returns the local object or `null` when absent, deleted, or not
129
- locally available.
130
- - `list()` returns the local known-object index, newest first. It is not a
131
- query/search API. Objects from other devices appear once a sync pulls
132
- them; their `change` event fires after `list()` includes them.
133
- - Object ids and field names starting with `~` are reserved and rejected.
134
-
135
- ## Instance Key API
136
-
137
- | Method | Behavior |
138
- | --- | --- |
139
- | `instance.getKey()` | Return the saved `InstanceKey`, or null. |
140
- | `instance.createKey()` | Generate, save and return an `InstanceKey`. |
141
- | `instance.importKey(key)` | Validate and save an existing key. |
142
- | `instance.removeKey()` | Remove the identity and dependent authorization. |
143
-
144
- [`InstanceKey`](../types/index.d.ts) contains instanceId, signing/wrapping public JWKs,
145
- nonextractable private CryptoKeys and createdAt.
146
-
147
- | Error | Meaning |
148
- | --- | --- |
149
- | `KEY_EXISTS` | Creation/import found an existing key, including the same ID. |
150
- | `INVALID_STATE` | Key changes require disconnected Instance and Local connections. |
151
- | `INVALID_INSTANCE_KEY` | Damaged records: getKey/connect reject; resume returns disconnected and reports the error through state. |
152
-
153
- ## Connection API
154
-
155
- ```ts
156
- instance.resume(options?: { autoSync?: boolean }): Promise<BucketState>;
157
- instance.connect(options?: { autoSync?: boolean }): Promise<BucketState>;
158
- instance.disconnect(): Promise<void>;
159
-
160
- bucket.sync(): Promise<void>;
161
- bucket.setAutoSync(enabled: boolean): void;
162
-
163
- instance.state; // "disconnected" | "connecting" | "connected"
164
-
165
- const offState = instance.on("state", (state, error?) => {});
166
- const offChange = bucket.on("change", (objectId) => {});
167
- ```
168
-
169
- - Call `resume()` on app boot. It completes pending auth callbacks and restores
170
- existing authorization without prompting. Concurrent `connect()` waits for it, then
171
- reuses restored access or starts authorization.
172
- - Call `connect()` from a user gesture. It validates the server session when establishing
173
- a connection, opening authorization when needed. Already-connected calls reuse access.
174
- - Automatic sync defaults to true. Set `autoSync: false` to stop automatic triggers;
175
- a pass already running finishes. Local CRUD, manual `bucket.sync()` and Remote
176
- requests remain available.
177
- - Browser lifecycle sync is app-owned. Apps may call `bucket.sync()` on focus,
178
- visibility, or online events.
179
- - `disconnect()` drops this resource's connection and authorization, retaining Local data.
180
-
181
- Automatic sync runs while the bucket is connected and auto-sync is enabled. It starts
182
- when connect/resume completes, when the connection becomes active, or on
183
- `setAutoSync(true)`; handle creation alone does no I/O. `connect({ autoSync })` is
184
- shorthand for `setAutoSync()` followed by connecting.
185
-
186
- Bucket `resume`/`connect`/`disconnect` manage that bucket's own connection; use them for
187
- buckets from `createBucket()` and Instance methods for the default bucket.
188
- `bucket.connect` also accepts `autoSync`; set the Auth page with
189
- `createInstance({ authUrl })`.
190
- Invalid calls reject; authorization failures resolve `"disconnected"` and report the
191
- error through the state event.
192
-
193
- ## Events
194
-
195
- ```ts
196
- bucket.on("state", (state, detail) => {
197
- // state: "disconnected" | "connecting" | "connected"
198
- });
199
-
200
- bucket.on("change", (objectId) => {
201
- // Re-read with bucket.get(objectId)
202
- });
203
- ```
204
-
205
- The returned function unsubscribes the listener.
206
-
207
- ## Errors
208
-
209
- - Invalid bucket ids, object ids, field names, or oversized objects reject the
210
- returned promise.
211
- - `sync()` while disconnected rejects with `NotConnectedError`.
212
- - Retryable sync failures, such as offline, rate limits, or 5xx responses, are
213
- surfaced through state details and retried by auto-sync.
214
- - A cloud miss is not an error. `get()` returns `null`, and another device that
215
- still has the object can re-upload it on sync.
216
-
217
- ## Not In V1
218
-
219
- - Custom storage adapters.
220
- - Query, pagination, ordering, or full-text search.
221
- - Public subpaths such as `@myfield/sdk/auth` or `@myfield/sdk/bucket`.
222
- - Capability negotiation APIs.
223
- - External KV mutation detection.
224
- - Remote batch or snapshot APIs.
225
- - `setFields()` / `getFields()` as the quickstart path.
226
-
227
- ## Remote Object API
228
-
229
- ```ts
230
- import { createInstance } from "@myfield/sdk";
231
-
232
- const instance = createInstance("notes.example.com");
233
- const remote = instance.remote.getBucket();
234
- await instance.resume({ autoSync: false }); // Startup; never prompts.
235
-
236
- if (instance.state === "connected") {
237
- const head = await remote.getCurrent("note:1");
238
- if (head) {
239
- const { meta, payload } = await remote.getVersion("note:1", head.versionId);
240
- console.log(meta.versionId, await payload.arrayBuffer());
241
- }
242
- }
243
- // Call instance.connect({ autoSync: false }) from your Connect button.
244
- ```
245
-
246
- `instance.remote.getBucket()` returns the default bucket's Remote handle. Resume or connect before using
247
- it. Missing current objects return null; missing versions throw. `getVersion()`
248
- returns metadata and a payload Response; consume or cancel its body.
249
-
250
- `resume()` restores access without prompting. Call `connect()` from a user action
251
- to authorize or recover from `NOT_AUTHORIZED`; network failures never open authorization.
252
- Both return the connection state; `on("state")` reports changes and errors.
253
- `disconnect()` clears shared bucket access and pending requests across tabs,
254
- retaining keys and objects.
255
-
256
- `commit()` submits app-encoded metadata and encrypted bytes against
257
- `expectedHeadVersionId`; null requests creation. The app owns encryption and merge.
258
-
259
- `getBucketKey()` returns `{ bucketId, keyId, cryptoKey }` for encrypting Remote
260
- payloads: the remote bucket ID used in API paths and the granted key as a
261
- non-extractable AES-GCM-256 `CryptoKey`, shared with Local sync. Use your own AAD,
262
- store `keyId` with ciphertext (no rotation yet), and get the handle again after each
263
- connect instead of persisting it. It makes no request, so revocation shows up only
264
- after another Remote call fails. Rejections: `NOT_AUTHORIZED`, `AbortError`,
265
- `INVALID_STATE`.
266
-
267
- CAS rejection returns `{ok:false, reason}`; other failures throw `ClientError`.
268
- After an uncertain failure, preserve version IDs, bytes and local edits.
269
- All Remote requests support cancellation with `{ signal }` and do not automatically retry.
270
-
271
- ### Discovery and change hints
272
-
273
- | Method | Result |
274
- | --- | --- |
275
- | `getIndex()` | Current heads, nullable `feedCursor`, `hasMoreFeed`. |
276
- | `listFeed({cursor, limit})` | One page of entries, `cursor`, `hasMore`. |
277
- | `getCurrent(id, {knownVersionId})` | Current head with ancestry evidence in `history`. |
278
- | `listVersions(id, versionId, {cursor, limit})` | Metadata plus `history` and `nextCursor`. |
279
- | `watchFeed()` | Resolves after subscription; returns a stream of `{objectId, versionId}` hints. |
280
-
281
- Cursors are opaque; null or omitted starts at the beginning. Read feed pages from
282
- `index.feedCursor` while `hasMore`. For `listVersions`, keep the same object/version
283
- anchor and continue until `nextCursor` is null.
284
-
285
- With `knownVersionId`, `getCurrent` returns newest-first ancestry evidence: a nonempty
286
- `history` proves ancestry, `[]` means no stored proof, and `null` means incomplete
287
- evidence. `listVersions` lists committed versions, not a complete parent graph.
288
-
289
- Await `watchFeed` before catching up the feed. Each hint prompts another catch-up.
290
- Abort or close the stream to stop; it does not reconnect automatically.
291
-
292
- ```js
293
- const stream = await remote.watchFeed({ signal });
294
- // Catch up the feed before consuming hints.
295
- for await (const hint of stream) {
296
- console.log(hint.objectId, hint.versionId);
297
- }
298
- ```
@@ -1,173 +0,0 @@
1
- # @myfield/sdk Bucket Spec (v1)
2
-
3
- This document is for SDK maintainers and future language-port implementers,
4
- not for app developers using the root `@myfield/sdk` API. It specifies the
5
- encrypted bucket format that SDK versions and compatible ports must reproduce
6
- to read the same local/cloud data. The worker stores ciphertext and validates
7
- transport shape; it does not interpret this plaintext format.
8
-
9
- App-facing API semantics live in `docs/API.md`.
10
-
11
- ## Payload
12
-
13
- Plaintext layout before encryption:
14
-
15
- ```text
16
- byte 0 format version (0x01)
17
- bytes 1..end UTF-8 JSON body
18
- ```
19
-
20
- Decoders reject unknown version bytes. Version 1 body is one of:
21
-
22
- ```jsonc
23
- {
24
- "t": "lww-map",
25
- "fields": {
26
- "<name>": { "v": <json>, "ts": <number>, "actor": "<actorId>" }
27
- },
28
- "tombstones": {
29
- "<name>": { "ts": <number>, "actor": "<actorId>" }
30
- }
31
- }
32
- ```
33
-
34
- or:
35
-
36
- ```jsonc
37
- { "t": "opaque", "data": <json> }
38
- ```
39
-
40
- `opaque` is for internal/custom merge strategies. It is not exposed by the
41
- v1 root package facade.
42
-
43
- ## LWW-Map Merge
44
-
45
- Merge is state-based and must be commutative, associative, and idempotent.
46
-
47
- 1. Union tombstones per field name; keep the max by `(ts, actor)`.
48
- 2. Union field entries per field name; keep the max by
49
- `(ts, actor, serialized v)`.
50
- 3. A field entry survives only if it strictly beats the tombstone for the
51
- same name by `(ts, actor)`. Exact ties delete.
52
-
53
- The serialized-value tie-break only keeps malformed duplicate `(ts, actor)`
54
- input deterministic. Normal writers do not emit two values at the same
55
- `(ts, actor)`.
56
-
57
- Unknown keys are kept, so the body can grow without a format-byte bump:
58
-
59
- 4. Extra keys in a field entry or tombstone travel with the winning entry;
60
- full ties are broken by the canonical JSON of the whole entry.
61
- 5. Unknown top-level keys are unioned; on conflict the larger canonical
62
- JSON wins. New top-level keys should carry their own `(ts, actor)`.
63
-
64
- `put()` and `update()` preserve timestamps for JSON-unchanged fields.
65
- Deleting a field writes a tombstone and removes the field entry; rewriting a
66
- field removes its tombstone.
67
-
68
- ## Clock
69
-
70
- Each bucket client has an actor id. Field timestamps use a hybrid clock:
71
-
72
- ```text
73
- ts = max(local wall clock in ms, max observed ts + 1)
74
- ```
75
-
76
- Observed timestamps include every field and tombstone in docs the client has
77
- read or merged. This prevents a slow device clock from losing all merges.
78
-
79
- ## Reserved Object And Field Names
80
-
81
- The root package facade reserves app object ids and field names starting with
82
- `~`.
83
-
84
- - `~id`: the app object id (e.g. `note:<uuid>`), written with the object.
85
- It maps a blinded object back to its app id without an index. It must
86
- derive to the object's wire id and match the local app id; otherwise the
87
- object is a sync error and is neither adopted nor pushed.
88
- - `~deleted`: the deleted marker for object tombstones.
89
- - `~index`: a local-only index behind `list()`, never pushed. Entries are
90
- `{ updatedAt, rev, deleted? }`; a pulled object's `updatedAt` is its
91
- latest field or tombstone timestamp.
92
-
93
- Apps cannot write these names through `put()` / `update()` / `delete()`.
94
- Lower-level source modules must preserve the same reservations when used by
95
- facade code.
96
-
97
- ## Object Id Blinding
98
-
99
- Apps address objects by semantic ids. The worker only sees blinded ids:
100
-
101
- ```text
102
- idKey = HKDF-SHA-256(
103
- ikm = raw 256-bit bucket key,
104
- salt = "myfield.sdk.v1",
105
- info = "object-id|" + remoteBucketId
106
- ) -> HMAC-SHA-256 key
107
-
108
- wireId = "ob_" + lowercase-hex(
109
- HMAC-SHA-256(idKey, utf8(appObjectId))
110
- )[0..32)
111
- ```
112
-
113
- `remoteBucketId` is `bucketAccessGrant.envelope.bucketId`, not necessarily
114
- the app-local `createBucket({ id })` label.
115
-
116
- The mapping is deterministic for every authorized device and one-way for the
117
- platform. The semantic app object id must not be sent in URL paths, headers,
118
- or plaintext metadata.
119
-
120
- ## Encryption Envelope
121
-
122
- Object payloads use the established bucket sync envelope shape:
123
-
124
- - AES-GCM-256 with the bucket payload key.
125
- - 96-bit random IV per write.
126
- - AAD: `myfield.bucket.sync.v1|<remoteBucketId>|<wireObjectId>`.
127
- - Envelope JSON fields:
128
- - `ciphertext`
129
- - `cipherMeta { alg, iv, keyId, bucketId, aad }`
130
- - `wrappedDEK`
131
- - `wrappedDEKMeta { alg, keyId, bucketId }`
132
-
133
- The SDK uses direct-bucket-key mode: `wrappedDEK` is the key id and
134
- `wrappedDEKMeta.alg` is `"direct-bucket-key"`.
135
-
136
- Worker-visible version metadata is transport metadata only. LWW timestamps,
137
- field names, object semantics, and app metadata live inside ciphertext.
138
-
139
- ## Bucket Keys
140
-
141
- The authorization callback provides a bucket access grant. Its envelope wraps
142
- a raw 256-bit bucket key to the instance wrapping key using ECDH P-256,
143
- HKDF-SHA-256, and AES-GCM-256.
144
-
145
- The SDK derives:
146
-
147
- - payload key: raw key imported as non-extractable AES-GCM-256 key.
148
- - object-id key: HKDF/HMAC key described above.
149
-
150
- Raw key bytes are zeroed after derivation.
151
-
152
- The encrypted callback also returns `resourceApiUrl`; SDKs use it as the API
153
- address and do not encode deployment host rules. `bucketAccessGrant.resourceId`
154
- identifies the remote sync resource; `envelope.bucketId` is optional
155
- compatibility metadata.
156
-
157
- ## Sync Behavior Relevant To Format
158
-
159
- The worker is a relay: it never decrypts payloads, but lists current
160
- heads by wire id (`GET objects:index` snapshot plus `GET feed`).
161
-
162
- Each object syncs as `pull current -> merge -> CAS push`, retrying on CAS
163
- conflict and re-creating it from local state on a remote miss.
164
-
165
- A sync pass:
166
-
167
- 1. Read `objects:index`, then `feed` from its `feedCursor` (or from the
168
- start) until `hasMoreFeed` is false; later entries win. Result: wire id
169
- to current version id. No cursor is persisted.
170
- 2. Sync each local object (not `~index`) that changed remotely, is dirty,
171
- or is missing from the result.
172
- 3. For each unknown wire id, decrypt the payload, read `~id`, and sync it;
173
- skip it until a later pass if unresolved.