@myfield/sdk 0.9.1 → 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,211 +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
- ## Quickstart
8
-
9
- ```ts
10
- import { createInstance } from "@myfield/sdk";
11
-
12
- const instance = createInstance();
13
- const bucket = instance.createBucket({ id: "app.example.com" });
14
-
15
- await bucket.put("note:1", { title: "hello", body: "world" });
16
- const note = await bucket.get("note:1");
17
- const notes = await bucket.list({ prefix: "note:" });
18
-
19
- await bucket.connect();
20
- ```
21
-
22
- ## `createInstance(options?)`
23
-
24
- ```ts
25
- function createInstance(options?: {
26
- namespace?: string; // default "default"
27
- storage?: "indexeddb" | "memory"; // default "indexeddb"
28
- }): Instance;
29
- ```
30
-
31
- - `namespace` is a local storage scope. It defaults to `"default"` and must
32
- match `a-z0-9`, max 32 chars.
33
- - `storage: "indexeddb"` persists local data, instance keys, auth context, and
34
- sync metadata.
35
- - `storage: "memory"` keeps all state process-local and ephemeral.
36
-
37
- ## `instance.createBucket(options)`
38
-
39
- ```ts
40
- instance.createBucket(options: { id: string }): Bucket;
41
- ```
42
-
43
- - `id` is required. Use a stable domain-shaped id, usually the app host, for
44
- example `"app.example.com"`.
45
- - Creating a bucket is local-only: no network and no account.
46
- - The local bucket id is the user-facing resource label. Myfield may bind it to
47
- a different remote bucket id during `connect()`; apps must not assume they
48
- are the same.
49
- - Valid ids use lowercase `a-z0-9`, `.`, and `-`, max 63 chars.
50
-
51
- ## Local Object API
52
-
53
- Local operations work before `connect()` and never wait for network sync.
54
-
55
- ```ts
56
- bucket.ready(): Promise<void>;
57
-
58
- bucket.put(id: string, object: Record<string, unknown>): Promise<void>;
59
- bucket.update(id: string, fields: Record<string, unknown>): Promise<void>;
60
- bucket.delete(id: string): Promise<void>;
61
-
62
- bucket.get(id: string): Promise<Record<string, unknown> | null>;
63
- bucket.binary(input: Blob | File | ArrayBuffer | Uint8Array, options?: {
64
- mimeType?: string;
65
- name?: string;
66
- lastModified?: number;
67
- }): BucketBinaryValue;
68
- bucket.list(options?: {
69
- prefix?: string;
70
- includeDeleted?: boolean; // default false
71
- }): Promise<Array<{ id: string; updatedAt: string; deleted?: true }>>;
72
- ```
73
-
74
- ### Write Semantics
75
-
76
- - `put(id, object)` writes a whole object from this device's point of view.
77
- Omitted fields that this device already knows are deleted; fields unknown
78
- locally, such as concurrent remote additions, are preserved on merge.
79
- - `update(id, fields)` writes top-level fields and preserves omitted fields.
80
- Setting a field to `undefined` deletes it. Updating a missing/deleted object
81
- recreates it.
82
- - Unchanged field values do not advance field timestamps.
83
- - Merge granularity is top-level fields. Nested values are replaced wholesale.
84
-
85
- ### Binary Fields
86
-
87
- Binary content is stored as a typed field value. The SDK does not interpret file
88
- semantics; app-owned fields such as `name`, `mimeType`, `size`, or `kind` remain
89
- ordinary application data.
90
-
91
- ```ts
92
- await bucket.put("file:1", {
93
- kind: "file",
94
- name: file.name,
95
- mimeType: file.type,
96
- size: file.size,
97
- content: bucket.binary(file),
98
- });
99
-
100
- const saved = await bucket.get("file:1");
101
- const content = saved?.content;
102
- if (content?.kind === "binary") {
103
- const blob = await content.blob();
104
- const bytes = await content.arrayBuffer();
105
- }
106
- ```
107
-
108
- `bucket.binary()` accepts `Blob`, `File`, `ArrayBuffer`, and `Uint8Array`.
109
- Read-side binary values expose:
110
-
111
- ```ts
112
- type BucketBinaryValue = {
113
- kind: "binary";
114
- size: number;
115
- mimeType?: string;
116
- name?: string;
117
- lastModified?: number;
118
- blob(): Promise<Blob>;
119
- arrayBuffer(): Promise<ArrayBuffer>;
120
- };
121
- ```
122
-
123
- Binary fields are inline in the same encrypted SDK object payload. They use the
124
- same field-level LWW ordering as other fields. The worker API is unchanged and
125
- continues to see only opaque encrypted object payloads.
126
-
127
- The SDK enforces a 100 MiB (`100 * 1024 * 1024` bytes) object-level encoded
128
- payload size cap. Apps requiring larger data should model chunks as separate objects; chunking is
129
- application-owned and is not a public SDK API concept.
130
-
131
- ### Read And List
132
-
133
- - `get(id)` returns the local object or `null` when absent, deleted, or not
134
- locally available.
135
- - `list()` returns the local known-object index, newest first. It is not a
136
- query/search API. Objects from other devices appear once a sync pulls
137
- them; their `change` event fires after `list()` includes them.
138
- - Object ids and field names starting with `~` are reserved and rejected.
139
-
140
- ## Connection API
141
-
142
- ```ts
143
- bucket.resume(): Promise<void>;
144
-
145
- bucket.connect(options?: {
146
- authBase?: string; // default "https://myfield.one/auth/"
147
- autoSync?: boolean; // default true
148
- }): Promise<void>;
149
-
150
- bucket.sync(): Promise<void>;
151
- bucket.setAutoSync(enabled: boolean): void;
152
- bucket.disconnect(): Promise<void>;
153
-
154
- bucket.state; // "disconnected" | "connecting" | "connected"
155
-
156
- const offState = bucket.on("state", (state, detail?) => {});
157
- const offChange = bucket.on("change", (objectId) => {});
158
- ```
159
-
160
- - Call `resume()` on app boot. It completes pending auth callbacks and restores
161
- existing authorization without prompting.
162
- - Call `connect()` from a user gesture. It may open the Myfield auth page.
163
- - `authBase` defaults to `https://myfield.one/auth/`. API endpoints are not
164
- public SDK options.
165
- - With `autoSync`, the SDK syncs after connecting and after local writes.
166
- - Browser lifecycle sync is app-owned. Apps may call `bucket.sync()` on focus,
167
- visibility, or online events.
168
- - `disconnect()` drops the remote binding and authorization. Local data stays.
169
-
170
- ## Events
171
-
172
- ```ts
173
- bucket.on("state", (state, detail) => {
174
- // state: "disconnected" | "connecting" | "connected"
175
- });
176
-
177
- bucket.on("change", (objectId) => {
178
- // Re-read with bucket.get(objectId)
179
- });
180
- ```
181
-
182
- The returned function unsubscribes the listener.
183
-
184
- ## Errors
185
-
186
- - Invalid bucket ids, object ids, field names, or oversized objects reject the
187
- returned promise.
188
- - `sync()` while disconnected rejects with `NotConnectedError`.
189
- - Retryable sync failures, such as offline, rate limits, or 5xx responses, are
190
- surfaced through state details and retried by auto-sync.
191
- - A cloud miss is not an error. `get()` returns `null`, and another device that
192
- still has the object can re-upload it on sync.
193
-
194
- ## Boundaries
195
-
196
- - Myfield sync is a relay, not a backup. Apps should keep their own export or
197
- durability story when user data must be archival.
198
- - Content and object ids are encrypted/blinded before reaching Myfield. Traffic
199
- timing, sizes, and counts are still visible to the platform.
200
- - Web clients cannot hide the browser `Origin` header from sync/auth requests.
201
- - v1 is freshness sync, not realtime collaborative editing.
202
-
203
- ## Not In V1
204
-
205
- - Custom storage adapters.
206
- - Query, pagination, ordering, or full-text search.
207
- - Public subpaths such as `@myfield/sdk/auth` or `@myfield/sdk/bucket`.
208
- - Capability negotiation APIs.
209
- - External KV mutation detection.
210
- - Public feed, batch, snapshot, or version-history APIs.
211
- - `setFields()` / `getFields()` as the quickstart path.
@@ -1,168 +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
- ## Sync Behavior Relevant To Format
153
-
154
- The worker is a relay: it never decrypts payloads, but lists current
155
- heads by wire id (`GET objects:index` snapshot plus `GET feed`).
156
-
157
- Each object syncs as `pull current -> merge -> CAS push`, retrying on CAS
158
- conflict and re-creating it from local state on a remote miss.
159
-
160
- A sync pass:
161
-
162
- 1. Read `objects:index`, then `feed` from its `feedCursor` (or from the
163
- start) until `hasMoreFeed` is false; later entries win. Result: wire id
164
- to current version id. No cursor is persisted.
165
- 2. Sync each local object (not `~index`) that changed remotely, is dirty,
166
- or is missing from the result.
167
- 3. For each unknown wire id, decrypt the payload, read `~id`, and sync it;
168
- skip it until a later pass if unresolved.
package/src/auth/index.ts DELETED
@@ -1,17 +0,0 @@
1
- export {
2
- createInstanceAuthClient,
3
- signInstanceChallenge,
4
- decryptEncryptedAuthAuthorizationResult,
5
- normalizeBucketAccessGrant,
6
- bucketResourceId,
7
- isValidBucketId,
8
- type AuthCapability,
9
- type AuthInstance,
10
- type AuthCallbackResult,
11
- type BucketAccess,
12
- type BucketAccessGrant,
13
- type CloudSessionCredential,
14
- type InstanceAuthClient,
15
- type InstanceAuthClientOptions,
16
- type InstanceAuthContext,
17
- } from "./instance.ts";