@myfield/sdk 0.9.0 → 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,47 +119,76 @@ 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
 
133
128
  - `get(id)` returns the local object or `null` when absent, deleted, or not
134
129
  locally available.
135
130
  - `list()` returns the local known-object index, newest first. It is not a
136
- query/search API.
131
+ query/search API. Objects from other devices appear once a sync pulls
132
+ them; their `change` event fires after `list()` includes them.
137
133
  - Object ids and field names starting with `~` are reserved and rejected.
138
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
+
139
153
  ## Connection API
140
154
 
141
155
  ```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>;
156
+ instance.resume(options?: { autoSync?: boolean }): Promise<BucketState>;
157
+ instance.connect(options?: { autoSync?: boolean }): Promise<BucketState>;
158
+ instance.disconnect(): Promise<void>;
148
159
 
149
160
  bucket.sync(): Promise<void>;
150
161
  bucket.setAutoSync(enabled: boolean): void;
151
- bucket.disconnect(): Promise<void>;
152
162
 
153
- bucket.state; // "disconnected" | "connecting" | "connected"
163
+ instance.state; // "disconnected" | "connecting" | "connected"
154
164
 
155
- const offState = bucket.on("state", (state, detail?) => {});
165
+ const offState = instance.on("state", (state, error?) => {});
156
166
  const offChange = bucket.on("change", (objectId) => {});
157
167
  ```
158
168
 
159
169
  - 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.
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.
165
177
  - Browser lifecycle sync is app-owned. Apps may call `bucket.sync()` on focus,
166
178
  visibility, or online events.
167
- - `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.
168
192
 
169
193
  ## Events
170
194
 
@@ -190,15 +214,6 @@ The returned function unsubscribes the listener.
190
214
  - A cloud miss is not an error. `get()` returns `null`, and another device that
191
215
  still has the object can re-upload it on sync.
192
216
 
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
217
  ## Not In V1
203
218
 
204
219
  - Custom storage adapters.
@@ -206,5 +221,78 @@ The returned function unsubscribes the listener.
206
221
  - Public subpaths such as `@myfield/sdk/auth` or `@myfield/sdk/bucket`.
207
222
  - Capability negotiation APIs.
208
223
  - External KV mutation detection.
209
- - Public feed, batch, snapshot, or version-history APIs.
224
+ - Remote batch or snapshot APIs.
210
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
+ ```
@@ -54,6 +54,13 @@ The serialized-value tie-break only keeps malformed duplicate `(ts, actor)`
54
54
  input deterministic. Normal writers do not emit two values at the same
55
55
  `(ts, actor)`.
56
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
+
57
64
  `put()` and `update()` preserve timestamps for JSON-unchanged fields.
58
65
  Deleting a field writes a tombstone and removes the field entry; rewriting a
59
66
  field removes its tombstone.
@@ -74,9 +81,14 @@ read or merged. This prevents a slow device clock from losing all merges.
74
81
  The root package facade reserves app object ids and field names starting with
75
82
  `~`.
76
83
 
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.
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.
80
92
 
81
93
  Apps cannot write these names through `put()` / `update()` / `delete()`.
82
94
  Lower-level source modules must preserve the same reservations when used by
@@ -137,17 +149,25 @@ The SDK derives:
137
149
 
138
150
  Raw key bytes are zeroed after derivation.
139
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
+
140
157
  ## Sync Behavior Relevant To Format
141
158
 
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:
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`).
144
161
 
145
- ```text
146
- pull current -> merge with local -> CAS push
147
- ```
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:
148
166
 
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.
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myfield/sdk",
3
- "version": "0.9.0",
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
+ }