@myfield/sdk 0.9.1 → 0.9.2

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 CHANGED
@@ -4,43 +4,39 @@
4
4
  writes work without an account. `connect()` binds the bucket to Myfield auth and
5
5
  encrypted sync.
6
6
 
7
- ## Quickstart
7
+ For an overview, quickstart and service boundaries, see the [README](../README.md).
8
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?)`
9
+ ## `createInstance`
23
10
 
24
11
  ```ts
25
- function createInstance(options?: {
26
- namespace?: string; // default "default"
27
- storage?: "indexeddb" | "memory"; // default "indexeddb"
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/.
28
18
  }): Instance;
29
19
  ```
30
20
 
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.
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()`.
36
30
 
37
- ## `instance.createBucket(options)`
31
+ ## Buckets
38
32
 
39
33
  ```ts
34
+ instance.getBucket(): Bucket;
40
35
  instance.createBucket(options: { id: string }): Bucket;
41
36
  ```
42
37
 
43
- - `id` is required. Use a stable domain-shaped id, usually the app host, for
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
44
40
  example `"app.example.com"`.
45
41
  - Creating a bucket is local-only: no network and no account.
46
42
  - The local bucket id is the user-facing resource label. Myfield may bind it to
@@ -50,11 +46,10 @@ instance.createBucket(options: { id: string }): Bucket;
50
46
 
51
47
  ## Local Object API
52
48
 
53
- Local operations work before `connect()` and never wait for network sync.
49
+ Local operations work before `connect()` and never wait for network sync. They
50
+ initialize storage lazily; storage errors surface on first use.
54
51
 
55
52
  ```ts
56
- bucket.ready(): Promise<void>;
57
-
58
53
  bucket.put(id: string, object: Record<string, unknown>): Promise<void>;
59
54
  bucket.update(id: string, fields: Record<string, unknown>): Promise<void>;
60
55
  bucket.delete(id: string): Promise<void>;
@@ -124,9 +119,9 @@ Binary fields are inline in the same encrypted SDK object payload. They use the
124
119
  same field-level LWW ordering as other fields. The worker API is unchanged and
125
120
  continues to see only opaque encrypted object payloads.
126
121
 
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.
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.
130
125
 
131
126
  ### Read And List
132
127
 
@@ -137,35 +132,63 @@ application-owned and is not a public SDK API concept.
137
132
  them; their `change` event fires after `list()` includes them.
138
133
  - Object ids and field names starting with `~` are reserved and rejected.
139
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
+
140
153
  ## Connection API
141
154
 
142
155
  ```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>;
156
+ instance.resume(options?: { autoSync?: boolean }): Promise<BucketState>;
157
+ instance.connect(options?: { autoSync?: boolean }): Promise<BucketState>;
158
+ instance.disconnect(): Promise<void>;
149
159
 
150
160
  bucket.sync(): Promise<void>;
151
161
  bucket.setAutoSync(enabled: boolean): void;
152
- bucket.disconnect(): Promise<void>;
153
162
 
154
- bucket.state; // "disconnected" | "connecting" | "connected"
163
+ instance.state; // "disconnected" | "connecting" | "connected"
155
164
 
156
- const offState = bucket.on("state", (state, detail?) => {});
165
+ const offState = instance.on("state", (state, error?) => {});
157
166
  const offChange = bucket.on("change", (objectId) => {});
158
167
  ```
159
168
 
160
169
  - 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.
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.
166
177
  - Browser lifecycle sync is app-owned. Apps may call `bucket.sync()` on focus,
167
178
  visibility, or online events.
168
- - `disconnect()` drops the remote binding and authorization. Local data stays.
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.
169
192
 
170
193
  ## Events
171
194
 
@@ -191,15 +214,6 @@ The returned function unsubscribes the listener.
191
214
  - A cloud miss is not an error. `get()` returns `null`, and another device that
192
215
  still has the object can re-upload it on sync.
193
216
 
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
217
  ## Not In V1
204
218
 
205
219
  - Custom storage adapters.
@@ -207,5 +221,78 @@ The returned function unsubscribes the listener.
207
221
  - Public subpaths such as `@myfield/sdk/auth` or `@myfield/sdk/bucket`.
208
222
  - Capability negotiation APIs.
209
223
  - External KV mutation detection.
210
- - Public feed, batch, snapshot, or version-history APIs.
224
+ - Remote batch or snapshot APIs.
211
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
+ ```
@@ -149,6 +149,11 @@ The SDK derives:
149
149
 
150
150
  Raw key bytes are zeroed after derivation.
151
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
+
152
157
  ## Sync Behavior Relevant To Format
153
158
 
154
159
  The worker is a relay: it never decrypts payloads, but lists current
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myfield/sdk",
3
- "version": "0.9.1",
3
+ "version": "0.9.2",
4
4
  "description": "Myfield open SDK: instance auth and end-to-end-encrypted bucket sync for third-party web apps.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "OPENTECH AI PTE. LTD.",
@@ -47,7 +47,9 @@
47
47
  "build": "esbuild src/index.ts --bundle --format=esm --platform=browser --target=es2022 --outfile=dist/index.js",
48
48
  "prepack": "npm run build",
49
49
  "test": "node --experimental-strip-types --test test/*.test.mjs",
50
- "typecheck": "tsc --noEmit"
50
+ "verify:remote": "node scripts/verify-remote.mjs",
51
+ "typecheck": "tsc --noEmit",
52
+ "typecheck:api": "tsc --noEmit --strict --allowImportingTsExtensions --module NodeNext --moduleResolution NodeNext --target ES2022 test/remote-consumer.ts"
51
53
  },
52
54
  "devDependencies": {
53
55
  "@types/node": "^25.5.2",
@@ -0,0 +1,254 @@
1
+ import { b64urlToBytes, bytesToB64url, stableStringify, utf8Encode } from "../internal/encoding.ts";
2
+ import type { BucketKeyGrantEnvelope } from "../bucket/keys.ts";
3
+ import type { AuthCapability, BucketAccessGrant } from "./types.ts";
4
+ import { isValidBucketId, isValidInstanceId, isValidMfid, isPublicP256EcJwk, parseBucketResourceId } from "./identifiers.ts";
5
+
6
+ const AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
7
+
8
+ export type StoredAuthAuthorizationResult = {
9
+ v: 1;
10
+ requestId: string;
11
+ state: string;
12
+ result: "approved";
13
+ mfid: string;
14
+ resourceId: string;
15
+ instanceId: string;
16
+ createdAt: string;
17
+ resourceApiUrl?: string;
18
+ bucketAccessGrant?: BucketAccessGrant;
19
+ expiresAt?: string;
20
+ };
21
+
22
+ export type EncryptedAuthAuthorizationResultEnvelope = {
23
+ v: 1;
24
+ typ: "auth.authorization-result.envelope.v1";
25
+ alg: "ECDH-HKDF-SHA-256/AES-GCM-256";
26
+ requestId: string;
27
+ state: string;
28
+ resourceId: string;
29
+ instanceId: string;
30
+ ephemeralPublicJwk: JsonWebKey;
31
+ salt: string;
32
+ iv: string;
33
+ aad: string;
34
+ ciphertext: string;
35
+ };
36
+
37
+ type AuthRequestFields = {
38
+ clientId: string;
39
+ requestId: string;
40
+ state: string;
41
+ redirectUri: string;
42
+ origin: string;
43
+ resourceId: string;
44
+ capabilities: AuthCapability[];
45
+ instanceId: string;
46
+ instanceSigningPublicJwk: JsonWebKey;
47
+ instanceWrappingPublicJwk: JsonWebKey;
48
+ createdAt: string;
49
+ };
50
+
51
+ export function buildAuthRequestFragment(request: AuthRequestFields): string {
52
+ if (!request.requestId || !request.state) throw new Error("auth request state required");
53
+ if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
54
+ if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
55
+ if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
56
+ const redirect = new URL(request.redirectUri);
57
+ const origin = new URL(request.origin);
58
+ if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
59
+ const wire = {
60
+ response_type: "code",
61
+ client_id: request.clientId,
62
+ redirect_uri: request.redirectUri,
63
+ state: request.state,
64
+ scope: request.capabilities.join(" "),
65
+ resource_id: request.resourceId,
66
+ mf_v: 1,
67
+ mf_auth_mode: "v1",
68
+ mf_request_id: request.requestId,
69
+ mf_instance_id: request.instanceId,
70
+ mf_instance_signing_jwk: request.instanceSigningPublicJwk,
71
+ mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
72
+ mf_issued_at: request.createdAt,
73
+ };
74
+ return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
75
+ }
76
+
77
+ export function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl: string): EncryptedAuthAuthorizationResultEnvelope | null {
78
+ const input = String(fragmentOrUrl || "");
79
+ const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
80
+ if (!rawFragment) return null;
81
+ const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
82
+ if (!encoded) return null;
83
+ const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded))) as Partial<EncryptedAuthAuthorizationResultEnvelope> | null;
84
+ if (
85
+ !envelope ||
86
+ envelope.v !== 1 ||
87
+ envelope.typ !== "auth.authorization-result.envelope.v1" ||
88
+ envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" ||
89
+ typeof envelope.requestId !== "string" ||
90
+ typeof envelope.state !== "string" ||
91
+ !parseBucketResourceId(envelope.resourceId) ||
92
+ !isValidInstanceId(envelope.instanceId || "") ||
93
+ !isPublicP256EcJwk(envelope.ephemeralPublicJwk) ||
94
+ typeof envelope.salt !== "string" ||
95
+ typeof envelope.iv !== "string" ||
96
+ typeof envelope.aad !== "string" ||
97
+ typeof envelope.ciphertext !== "string"
98
+ ) {
99
+ throw new Error("auth callback result fragment invalid");
100
+ }
101
+ return envelope as EncryptedAuthAuthorizationResultEnvelope;
102
+ }
103
+
104
+ export async function decryptEncryptedAuthAuthorizationResult(input: {
105
+ envelope: EncryptedAuthAuthorizationResultEnvelope;
106
+ instanceWrappingPrivateKey: CryptoKey;
107
+ expectedRequestId?: string;
108
+ expectedState?: string;
109
+ expectedResourceId?: string;
110
+ expectedInstanceId?: string;
111
+ }): Promise<StoredAuthAuthorizationResult> {
112
+ const { envelope } = input;
113
+ if (
114
+ (input.expectedRequestId && envelope.requestId !== input.expectedRequestId) ||
115
+ (input.expectedState && envelope.state !== input.expectedState) ||
116
+ (input.expectedResourceId && envelope.resourceId !== input.expectedResourceId) ||
117
+ (input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId)
118
+ ) {
119
+ throw new Error("auth callback result mismatch");
120
+ }
121
+ const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
122
+ const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
123
+ const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
124
+ const wrappingKey = await crypto.subtle.deriveKey(
125
+ { name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt) as BufferSource, info: utf8Encode(envelope.aad) },
126
+ material,
127
+ { name: "AES-GCM", length: 256 },
128
+ false,
129
+ ["decrypt"]
130
+ );
131
+ const plaintext = await crypto.subtle.decrypt(
132
+ { name: "AES-GCM", iv: b64urlToBytes(envelope.iv) as BufferSource, additionalData: utf8Encode(envelope.aad) },
133
+ wrappingKey,
134
+ b64urlToBytes(envelope.ciphertext) as BufferSource
135
+ );
136
+ const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
137
+ if (
138
+ !result ||
139
+ result.state !== envelope.state ||
140
+ result.resourceId !== envelope.resourceId ||
141
+ result.instanceId !== envelope.instanceId ||
142
+ (input.expectedState && result.state !== input.expectedState) ||
143
+ (input.expectedResourceId && result.resourceId !== input.expectedResourceId) ||
144
+ (input.expectedInstanceId && result.instanceId !== input.expectedInstanceId)
145
+ ) {
146
+ throw new Error("auth callback result mismatch");
147
+ }
148
+ return result;
149
+ }
150
+
151
+ function normalizeAuthAuthorizationResult(value: unknown, expectedRequestId?: string): StoredAuthAuthorizationResult | null {
152
+ const row = value as Partial<StoredAuthAuthorizationResult> | null;
153
+ if (
154
+ !row ||
155
+ row.v !== 1 ||
156
+ row.result !== "approved" ||
157
+ typeof row.requestId !== "string" ||
158
+ (expectedRequestId && row.requestId !== expectedRequestId) ||
159
+ typeof row.state !== "string" ||
160
+ !isValidMfid(row.mfid || "") ||
161
+ !parseBucketResourceId(row.resourceId) ||
162
+ !isValidInstanceId(row.instanceId || "") ||
163
+ typeof row.createdAt !== "string"
164
+ ) {
165
+ return null;
166
+ }
167
+ if (row.expiresAt !== undefined) {
168
+ const expiresAt = Date.parse(String(row.expiresAt));
169
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
170
+ }
171
+ const resource = parseBucketResourceId(row.resourceId);
172
+ if (!resource) return null;
173
+ const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
174
+ if (!bucketAccessGrant) return null;
175
+ if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
176
+ return null;
177
+ }
178
+ return {
179
+ v: 1,
180
+ requestId: row.requestId,
181
+ state: row.state,
182
+ result: "approved",
183
+ mfid: row.mfid!,
184
+ resourceId: resource.resourceId,
185
+ instanceId: row.instanceId!,
186
+ createdAt: row.createdAt,
187
+ ...(typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {}),
188
+ bucketAccessGrant,
189
+ ...(row.expiresAt ? { expiresAt: row.expiresAt } : {}),
190
+ };
191
+ }
192
+
193
+ export function normalizeBucketAccessGrant(value: unknown): BucketAccessGrant | null {
194
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
195
+ const row = value as Partial<BucketAccessGrant>;
196
+ const resource = parseBucketResourceId(row.resourceId);
197
+ const capabilities = normalizeCapabilities(row.capabilities);
198
+ if (
199
+ row.v !== 1 ||
200
+ !/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) ||
201
+ !isValidMfid(row.mfid) ||
202
+ !resource ||
203
+ !isValidInstanceId(row.instanceId) ||
204
+ !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) ||
205
+ capabilities.length < 1 ||
206
+ !isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)
207
+ ) {
208
+ return null;
209
+ }
210
+ return {
211
+ v: 1,
212
+ grantRecordId: row.grantRecordId!,
213
+ mfid: row.mfid!,
214
+ resourceId: resource.resourceId,
215
+ instanceId: row.instanceId!,
216
+ issuedAt: String(row.issuedAt || ""),
217
+ keyId: row.keyId!,
218
+ capabilities,
219
+ envelope: row.envelope as BucketKeyGrantEnvelope,
220
+ };
221
+ }
222
+
223
+ function isValidBucketKeyGrantEnvelope(value: unknown, instanceId?: string, keyId?: string): value is BucketKeyGrantEnvelope {
224
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
225
+ const row = value as Partial<BucketKeyGrantEnvelope>;
226
+ if (
227
+ row.kind !== "bucket-key" ||
228
+ !isValidBucketId(row.bucketId) ||
229
+ !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) ||
230
+ !isValidInstanceId(row.targetInstanceId) ||
231
+ row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" ||
232
+ !isPublicP256EcJwk(row.targetWrappingPublicJwk) ||
233
+ !isPublicP256EcJwk(row.ephemeralPublicJwk) ||
234
+ typeof row.salt !== "string" ||
235
+ typeof row.iv !== "string" ||
236
+ typeof row.aad !== "string" ||
237
+ typeof row.ciphertext !== "string"
238
+ ) {
239
+ return false;
240
+ }
241
+ if (instanceId && row.targetInstanceId !== instanceId) return false;
242
+ if (keyId && row.keyId !== keyId) return false;
243
+ return true;
244
+ }
245
+
246
+ function normalizeCapabilities(input: unknown): AuthCapability[] {
247
+ if (!Array.isArray(input)) return [];
248
+ const allowed = new Set<AuthCapability>(["read", "write"]);
249
+ const result: AuthCapability[] = [];
250
+ for (const item of input) {
251
+ if (allowed.has(item as AuthCapability) && !result.includes(item as AuthCapability)) result.push(item as AuthCapability);
252
+ }
253
+ return result.sort();
254
+ }
@@ -0,0 +1,93 @@
1
+ import type { InstanceAuthClient } from "./instance.ts";
2
+ import type { StorageAdapter } from "../bucket/store.ts";
3
+ import { ClientError } from "../errors.ts";
4
+ import { authRecordKeys } from "./store.ts";
5
+ import { bucketResourceId } from "./identifiers.ts";
6
+
7
+ const notAuthorized = (message: string, cause?: unknown) => new ClientError("NOT_AUTHORIZED", message, { cause });
8
+
9
+ export function createAuthorizationFlow(deps: { getAppId(): string; getBucketId?(): string; persistent?: boolean }) {
10
+ const getBucketId = deps.getBucketId ?? deps.getAppId;
11
+ let closeAuthorization = () => {};
12
+ async function ownCallback(url: URL, storage: StorageAdapter): Promise<boolean> {
13
+ const resourceId = bucketResourceId(getBucketId());
14
+ const requestId = url.searchParams.get("mf_request_id");
15
+ if (!requestId) return false;
16
+ const keys = authRecordKeys(deps.getAppId());
17
+ const pointer = await storage.get<{ resourceId: string; pendingKey: string; requestId: string }>(keys.callback(requestId));
18
+ if (pointer?.resourceId !== resourceId || pointer.requestId !== requestId) return false;
19
+ const pending = await storage.get<{ resourceId: string }>(pointer.pendingKey);
20
+ if (pending && pending.resourceId !== resourceId) return false;
21
+ return true;
22
+ }
23
+
24
+ function clearCallbackUrl(url: URL) {
25
+ const current = new URL(window.location.href);
26
+ if (current.searchParams.get("mf_request_id") !== url.searchParams.get("mf_request_id")) return;
27
+ for (const key of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) current.searchParams.delete(key);
28
+ const hash = new URLSearchParams(current.hash.slice(1));
29
+ if (hash.has("mf_auth_result")) { hash.delete("mf_auth_result"); current.hash = hash.toString(); }
30
+ window.history.replaceState(null, "", current.href);
31
+ }
32
+
33
+ async function handleCallback(auth: InstanceAuthClient, url: URL, signal: AbortSignal, addressBar: boolean) {
34
+ try {
35
+ const result = await auth.handleCallback(url.href);
36
+ signal.throwIfAborted();
37
+ if (result?.result !== "approved") throw notAuthorized(result?.errorDescription || result?.result || "Invalid authorization callback");
38
+ } catch (error) {
39
+ signal.throwIfAborted();
40
+ if (error instanceof ClientError && error.code === "NOT_AUTHORIZED") throw error;
41
+ throw notAuthorized("Invalid authorization callback", error);
42
+ } finally {
43
+ if (addressBar) clearCallbackUrl(url);
44
+ }
45
+ }
46
+
47
+ function requestAuthorization(auth: InstanceAuthClient, storage: StorageAdapter, url: string, signal: AbortSignal, setPopup: (popup: Window | null) => void): Promise<void> {
48
+ signal.throwIfAborted();
49
+ const ios = typeof navigator !== "undefined" && (/iPad|iPhone|iPod/.test(navigator.userAgent)
50
+ || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1));
51
+ const popup = ios ? null : window.open("about:blank", `myfield-sdk-auth:${getBucketId()}`, "popup=yes,width=520,height=720");
52
+ if (!popup && deps.persistent === false) throw new ClientError("INVALID_STATE", "Redirect authorization requires persistent storage");
53
+ setPopup(popup);
54
+ return new Promise<void>((resolve, reject) => {
55
+ let processing = false;
56
+ let settled = false;
57
+ let timer: ReturnType<typeof setInterval> | undefined;
58
+ const finish = (error?: unknown) => {
59
+ if (settled) return;
60
+ settled = true;
61
+ if (timer) clearInterval(timer);
62
+ window.removeEventListener("message", onMessage);
63
+ signal.removeEventListener("abort", onAbort);
64
+ popup?.close();
65
+ closeAuthorization = () => {};
66
+ if (error) reject(error); else resolve();
67
+ };
68
+ const onAbort = () => finish(signal.reason);
69
+ const onMessage = (event: MessageEvent) => {
70
+ if (!popup || event.source !== popup || ![new URL(url).origin, window.location.origin].includes(event.origin)) return;
71
+ const message = event.data as { type?: string; callbackUrl?: string } | null;
72
+ if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
73
+ void (async () => {
74
+ let callbackUrl: URL;
75
+ try { callbackUrl = new URL(message.callbackUrl!); } catch { return; }
76
+ if (!await ownCallback(callbackUrl, storage) || processing || settled) return;
77
+ processing = true;
78
+ await handleCallback(auth, callbackUrl, signal, false);
79
+ finish();
80
+ })().catch(finish);
81
+ };
82
+ window.addEventListener("message", onMessage);
83
+ signal.addEventListener("abort", onAbort, { once: true });
84
+ closeAuthorization = onAbort;
85
+ if (popup) timer = setInterval(() => {
86
+ if (popup.closed && !processing) finish(notAuthorized("Authorization window closed"));
87
+ }, 250);
88
+ void auth.authorize({ bucketId: getBucketId() }).catch(finish);
89
+ });
90
+ }
91
+
92
+ return { ownCallback, handleCallback, requestAuthorization, close: () => closeAuthorization() };
93
+ }