@myfield/sdk 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/API.md ADDED
@@ -0,0 +1,210 @@
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.
137
+ - Object ids and field names starting with `~` are reserved and rejected.
138
+
139
+ ## Connection API
140
+
141
+ ```ts
142
+ bucket.resume(): Promise<void>;
143
+
144
+ bucket.connect(options?: {
145
+ authBase?: string; // default "https://myfield.one/auth/"
146
+ autoSync?: boolean; // default true
147
+ }): Promise<void>;
148
+
149
+ bucket.sync(): Promise<void>;
150
+ bucket.setAutoSync(enabled: boolean): void;
151
+ bucket.disconnect(): Promise<void>;
152
+
153
+ bucket.state; // "disconnected" | "connecting" | "connected"
154
+
155
+ const offState = bucket.on("state", (state, detail?) => {});
156
+ const offChange = bucket.on("change", (objectId) => {});
157
+ ```
158
+
159
+ - Call `resume()` on app boot. It completes pending auth callbacks and restores
160
+ existing authorization without prompting.
161
+ - Call `connect()` from a user gesture. It may open the Myfield auth page.
162
+ - `authBase` defaults to `https://myfield.one/auth/`. API endpoints are not
163
+ public SDK options.
164
+ - With `autoSync`, the SDK syncs after connecting and after local writes.
165
+ - Browser lifecycle sync is app-owned. Apps may call `bucket.sync()` on focus,
166
+ visibility, or online events.
167
+ - `disconnect()` drops the remote binding and authorization. Local data stays.
168
+
169
+ ## Events
170
+
171
+ ```ts
172
+ bucket.on("state", (state, detail) => {
173
+ // state: "disconnected" | "connecting" | "connected"
174
+ });
175
+
176
+ bucket.on("change", (objectId) => {
177
+ // Re-read with bucket.get(objectId)
178
+ });
179
+ ```
180
+
181
+ The returned function unsubscribes the listener.
182
+
183
+ ## Errors
184
+
185
+ - Invalid bucket ids, object ids, field names, or oversized objects reject the
186
+ returned promise.
187
+ - `sync()` while disconnected rejects with `NotConnectedError`.
188
+ - Retryable sync failures, such as offline, rate limits, or 5xx responses, are
189
+ surfaced through state details and retried by auto-sync.
190
+ - A cloud miss is not an error. `get()` returns `null`, and another device that
191
+ still has the object can re-upload it on sync.
192
+
193
+ ## Boundaries
194
+
195
+ - Myfield sync is a relay, not a backup. Apps should keep their own export or
196
+ durability story when user data must be archival.
197
+ - Content and object ids are encrypted/blinded before reaching Myfield. Traffic
198
+ timing, sizes, and counts are still visible to the platform.
199
+ - Web clients cannot hide the browser `Origin` header from sync/auth requests.
200
+ - v1 is freshness sync, not realtime collaborative editing.
201
+
202
+ ## Not In V1
203
+
204
+ - Custom storage adapters.
205
+ - Query, pagination, ordering, or full-text search.
206
+ - Public subpaths such as `@myfield/sdk/auth` or `@myfield/sdk/bucket`.
207
+ - Capability negotiation APIs.
208
+ - External KV mutation detection.
209
+ - Public feed, batch, snapshot, or version-history APIs.
210
+ - `setFields()` / `getFields()` as the quickstart path.
@@ -0,0 +1,153 @@
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
+ `put()` and `update()` preserve timestamps for JSON-unchanged fields.
58
+ Deleting a field writes a tombstone and removes the field entry; rewriting a
59
+ field removes its tombstone.
60
+
61
+ ## Clock
62
+
63
+ Each bucket client has an actor id. Field timestamps use a hybrid clock:
64
+
65
+ ```text
66
+ ts = max(local wall clock in ms, max observed ts + 1)
67
+ ```
68
+
69
+ Observed timestamps include every field and tombstone in docs the client has
70
+ read or merged. This prevents a slow device clock from losing all merges.
71
+
72
+ ## Reserved Object And Field Names
73
+
74
+ The root package facade reserves app object ids and field names starting with
75
+ `~`.
76
+
77
+ - `~index` is the bucket-maintained encrypted object index used by `list()`
78
+ and new-device restore.
79
+ - `~deleted` is the bucket-maintained deleted marker for object tombstones.
80
+
81
+ Apps cannot write these names through `put()` / `update()` / `delete()`.
82
+ Lower-level source modules must preserve the same reservations when used by
83
+ facade code.
84
+
85
+ ## Object Id Blinding
86
+
87
+ Apps address objects by semantic ids. The worker only sees blinded ids:
88
+
89
+ ```text
90
+ idKey = HKDF-SHA-256(
91
+ ikm = raw 256-bit bucket key,
92
+ salt = "myfield.sdk.v1",
93
+ info = "object-id|" + remoteBucketId
94
+ ) -> HMAC-SHA-256 key
95
+
96
+ wireId = "ob_" + lowercase-hex(
97
+ HMAC-SHA-256(idKey, utf8(appObjectId))
98
+ )[0..32)
99
+ ```
100
+
101
+ `remoteBucketId` is `bucketAccessGrant.envelope.bucketId`, not necessarily
102
+ the app-local `createBucket({ id })` label.
103
+
104
+ The mapping is deterministic for every authorized device and one-way for the
105
+ platform. The semantic app object id must not be sent in URL paths, headers,
106
+ or plaintext metadata.
107
+
108
+ ## Encryption Envelope
109
+
110
+ Object payloads use the established bucket sync envelope shape:
111
+
112
+ - AES-GCM-256 with the bucket payload key.
113
+ - 96-bit random IV per write.
114
+ - AAD: `myfield.bucket.sync.v1|<remoteBucketId>|<wireObjectId>`.
115
+ - Envelope JSON fields:
116
+ - `ciphertext`
117
+ - `cipherMeta { alg, iv, keyId, bucketId, aad }`
118
+ - `wrappedDEK`
119
+ - `wrappedDEKMeta { alg, keyId, bucketId }`
120
+
121
+ The SDK uses direct-bucket-key mode: `wrappedDEK` is the key id and
122
+ `wrappedDEKMeta.alg` is `"direct-bucket-key"`.
123
+
124
+ Worker-visible version metadata is transport metadata only. LWW timestamps,
125
+ field names, object semantics, and app metadata live inside ciphertext.
126
+
127
+ ## Bucket Keys
128
+
129
+ The authorization callback provides a bucket access grant. Its envelope wraps
130
+ a raw 256-bit bucket key to the instance wrapping key using ECDH P-256,
131
+ HKDF-SHA-256, and AES-GCM-256.
132
+
133
+ The SDK derives:
134
+
135
+ - payload key: raw key imported as non-extractable AES-GCM-256 key.
136
+ - object-id key: HKDF/HMAC key described above.
137
+
138
+ Raw key bytes are zeroed after derivation.
139
+
140
+ ## Sync Behavior Relevant To Format
141
+
142
+ The worker is a relay, not a database/query engine. It does not list objects
143
+ or interpret bucket indexes. The SDK sync loop is:
144
+
145
+ ```text
146
+ pull current -> merge with local -> CAS push
147
+ ```
148
+
149
+ On CAS conflict, the SDK pulls the current remote payload, merges, and
150
+ retries. On remote miss with surviving local state, the SDK re-creates the
151
+ object. The internal `~index` object has the same weak relay/eviction
152
+ semantics as every other object; dangling index entries are tolerated and
153
+ read as absent data.
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@myfield/sdk",
3
+ "version": "0.9.0",
4
+ "description": "Myfield open SDK: instance auth and end-to-end-encrypted bucket sync for third-party web apps.",
5
+ "license": "Apache-2.0",
6
+ "author": "OPENTECH AI PTE. LTD.",
7
+ "homepage": "https://github.com/myfield-one/sdk",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/myfield-one/sdk.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/myfield-one/sdk/issues"
14
+ },
15
+ "type": "module",
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "main": "./dist/index.js",
20
+ "types": "./types/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./types/index.d.ts",
24
+ "import": "./dist/index.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist/",
29
+ "src/",
30
+ "types/",
31
+ "docs/",
32
+ "README.md",
33
+ "LICENSE",
34
+ "CHANGELOG.md"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "keywords": [
40
+ "myfield",
41
+ "local-first",
42
+ "encrypted-sync",
43
+ "sdk"
44
+ ],
45
+ "sideEffects": false,
46
+ "scripts": {
47
+ "build": "esbuild src/index.ts --bundle --format=esm --platform=browser --target=es2022 --outfile=dist/index.js",
48
+ "prepack": "npm run build",
49
+ "test": "node --experimental-strip-types --test test/*.test.mjs",
50
+ "typecheck": "tsc --noEmit"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "^25.5.2",
54
+ "esbuild": "^0.28.1",
55
+ "fake-indexeddb": "6.2.4",
56
+ "typescript": "5.5.4"
57
+ }
58
+ }
@@ -0,0 +1,17 @@
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";