@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.
@@ -0,0 +1,73 @@
1
+ import { ClientError } from "../errors.ts";
2
+ import { sha256Hex, stableStringify } from "../internal/encoding.ts";
3
+
4
+ export type AuthInstance = {
5
+ v: 1;
6
+ instanceId: string;
7
+ signingPublicJwk: JsonWebKey;
8
+ signingPrivateKey: CryptoKey;
9
+ wrappingPublicJwk: JsonWebKey;
10
+ wrappingPrivateKey: CryptoKey;
11
+ createdAt: string;
12
+ };
13
+
14
+ export async function createInstanceKey(): Promise<AuthInstance> {
15
+ const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
16
+ const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
17
+ const signingPublicJwk = (await crypto.subtle.exportKey("jwk", signing.publicKey)) as JsonWebKey;
18
+ const wrappingPublicJwk = (await crypto.subtle.exportKey("jwk", wrapping.publicKey)) as JsonWebKey;
19
+ return {
20
+ v: 1,
21
+ instanceId: await deriveInstanceId(signingPublicJwk),
22
+ signingPublicJwk,
23
+ signingPrivateKey: signing.privateKey,
24
+ wrappingPublicJwk,
25
+ wrappingPrivateKey: wrapping.privateKey,
26
+ createdAt: new Date().toISOString(),
27
+ };
28
+ }
29
+
30
+ export async function deriveInstanceId(signingPublicJwk: JsonWebKey): Promise<string> {
31
+ const core = {
32
+ kty: String(signingPublicJwk.kty || ""),
33
+ crv: String(signingPublicJwk.crv || ""),
34
+ x: String(signingPublicJwk.x || ""),
35
+ y: String(signingPublicJwk.y || ""),
36
+ };
37
+ const digest = await sha256Hex(stableStringify(core));
38
+ return `inst_${digest.slice(0, 32)}`;
39
+ }
40
+
41
+ export type InstanceKey = Omit<AuthInstance, "v">;
42
+
43
+ export function toInstanceKey(value: AuthInstance): InstanceKey {
44
+ return { instanceId: value.instanceId, signingPublicJwk: { ...value.signingPublicJwk },
45
+ signingPrivateKey: value.signingPrivateKey, wrappingPublicJwk: { ...value.wrappingPublicJwk },
46
+ wrappingPrivateKey: value.wrappingPrivateKey, createdAt: value.createdAt };
47
+ }
48
+
49
+ export async function validateInstanceKey(value: InstanceKey): Promise<AuthInstance> {
50
+ const invalid = (cause?: unknown) => new ClientError("INVALID_INPUT", "Invalid instance key", { cause });
51
+ try {
52
+ if (!value || typeof value !== "object" || typeof value.createdAt !== "string"
53
+ || !value.createdAt.endsWith("Z") || !Number.isFinite(Date.parse(value.createdAt))) throw invalid();
54
+ value = { ...value, signingPublicJwk: { ...value.signingPublicJwk }, wrappingPublicJwk: { ...value.wrappingPublicJwk } };
55
+ const { signingPrivateKey: sign, wrappingPrivateKey: wrap } = value;
56
+ for (const [key, name, usage] of [[sign, "ECDSA", "sign"], [wrap, "ECDH", "deriveBits"]] as const) {
57
+ if (!(key instanceof CryptoKey) || key.type !== "private" || key.extractable || key.algorithm.name !== name
58
+ || (key.algorithm as EcKeyAlgorithm).namedCurve !== "P-256" || !key.usages.includes(usage)) throw invalid();
59
+ }
60
+ if (value.instanceId !== await deriveInstanceId(value.signingPublicJwk)) throw invalid();
61
+ const publicSign = await crypto.subtle.importKey("jwk", value.signingPublicJwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
62
+ const challenge = crypto.getRandomValues(new Uint8Array(32));
63
+ const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, sign, challenge);
64
+ if (!await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, publicSign, signature, challenge)) throw invalid();
65
+ const publicWrap = await crypto.subtle.importKey("jwk", value.wrappingPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
66
+ const ephemeral = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
67
+ const left = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeral.publicKey }, wrap, 256));
68
+ const right = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: publicWrap }, ephemeral.privateKey, 256));
69
+ if (!left.every((byte, i) => byte === right[i])) throw invalid();
70
+ return { v: 1, instanceId: value.instanceId, signingPublicJwk: { ...value.signingPublicJwk }, signingPrivateKey: sign,
71
+ wrappingPublicJwk: { ...value.wrappingPublicJwk }, wrappingPrivateKey: wrap, createdAt: value.createdAt };
72
+ } catch (cause) { throw cause instanceof ClientError ? cause : invalid(cause); }
73
+ }
@@ -0,0 +1,26 @@
1
+ import { bytesToB64url, normalizeIsoDateTime, stableStringify, utf8Encode } from "../internal/encoding.ts";
2
+ import type { AuthInstance } from "./keys.ts";
3
+ import type { InstanceProof } from "../remote/session.ts";
4
+
5
+ export async function signInstanceChallenge(input: {
6
+ instance: Pick<AuthInstance, "instanceId" | "signingPrivateKey">;
7
+ challenge: string;
8
+ mfid: string;
9
+ resourceId: string;
10
+ challengeId?: string;
11
+ signedAt?: string;
12
+ }): Promise<InstanceProof> {
13
+ const signedAt = normalizeIsoDateTime(input.signedAt) || new Date().toISOString();
14
+ const payload = stableStringify({
15
+ v: 1,
16
+ type: "instance-proof",
17
+ instanceId: input.instance.instanceId,
18
+ challenge: input.challenge,
19
+ challengeId: input.challengeId || "",
20
+ mfid: input.mfid,
21
+ resourceId: input.resourceId,
22
+ signedAt,
23
+ });
24
+ const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
25
+ return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
26
+ }
@@ -0,0 +1,16 @@
1
+ import type { AuthInstance } from "./keys.ts";
2
+ import { signInstanceChallenge } from "./proof.ts";
3
+ import type { CloudSessionCredential, SessionClient } from "../remote/session.ts";
4
+ export type { CloudSessionCredential } from "../remote/session.ts";
5
+
6
+ export async function createSession(input: {
7
+ instance: Pick<AuthInstance, "instanceId" | "signingPrivateKey">;
8
+ mfid: string;
9
+ resourceId: string;
10
+ }, client: SessionClient): Promise<CloudSessionCredential> {
11
+ const { instance, mfid, resourceId } = input;
12
+ const identity = { mfid, resourceId, instanceId: instance.instanceId };
13
+ const challenge = await client.createChallenge(identity);
14
+ const proof = await signInstanceChallenge({ instance, mfid, resourceId, challengeId: challenge.challengeId, challenge: challenge.challenge });
15
+ return client.createSession({ ...identity, challengeId: challenge.challengeId, proof });
16
+ }
@@ -0,0 +1,90 @@
1
+ import type { StorageAdapter } from "../bucket/store.ts";
2
+ import { ClientError } from "../errors.ts";
3
+ import { createInstanceKey, type AuthInstance } from "./keys.ts";
4
+ import { isPublicP256EcJwk, isValidInstanceId } from "./identifiers.ts";
5
+
6
+ type StoredInstance = AuthInstance & { updatedAt: string };
7
+
8
+ export function authRecordKeys(appId: string) {
9
+ const prefix = `instance:${encodeURIComponent(appId)}:`;
10
+ const segment = encodeURIComponent;
11
+ return {
12
+ prefix,
13
+ active: `${prefix}active-instance:current`,
14
+ keyPrefix: `${prefix}instance-key:`,
15
+ key: (id: string) => `${prefix}instance-key:${segment(id)}`,
16
+ pending: (resource: string, id: string) => `${prefix}pending-auth:${segment(resource)}:${segment(id)}`,
17
+ callback: (id: string) => `${prefix}callback-pointer:${segment(id)}`,
18
+ context: (resource: string, id: string) => `${prefix}context:${segment(resource)}:${segment(id)}`,
19
+ session: (resource: string, id: string) => `${prefix}session:${segment(resource)}:${segment(id)}`,
20
+ endpoints: (bucket: string) => `meta:${bucket}:endpoints`,
21
+ };
22
+ }
23
+
24
+ export function createInstanceKeyStore(storage: StorageAdapter, appId: string) {
25
+ const keys = authRecordKeys(appId);
26
+ async function read(id: string): Promise<StoredInstance | null> {
27
+ const value = await storage.get<StoredInstance>(keys.key(id));
28
+ if (!value) return null;
29
+ if (value.v !== 1 || value.instanceId !== id || !isValidInstanceId(id)
30
+ || !isPublicP256EcJwk(value.signingPublicJwk) || !isPublicP256EcJwk(value.wrappingPublicJwk)
31
+ || !(value.signingPrivateKey instanceof CryptoKey) || !(value.wrappingPrivateKey instanceof CryptoKey)) {
32
+ throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance key is invalid");
33
+ }
34
+ return value;
35
+ }
36
+ async function active(): Promise<StoredInstance | null> {
37
+ let pointer = await storage.get<{ v: number; instanceId: string }>(keys.active);
38
+ if (pointer === null) {
39
+ if (!(await storage.keys(keys.keyPrefix)).length) return null;
40
+ pointer = await storage.get<{ v: number; instanceId: string }>(keys.active);
41
+ if (pointer === null) throw new ClientError("INVALID_INSTANCE_KEY", "Instance key has no active pointer");
42
+ }
43
+ if (pointer.v !== 1 || !isValidInstanceId(pointer.instanceId)) throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance pointer is invalid");
44
+ const value = await read(pointer.instanceId);
45
+ if (!value) throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance key is missing");
46
+ return value;
47
+ }
48
+ async function insert(instance: AuthInstance): Promise<boolean> {
49
+ if (await storage.get(keys.active) !== null) return false;
50
+ const now = new Date().toISOString();
51
+ const entries = [{ key: keys.key(instance.instanceId), value: { ...instance, updatedAt: now } },
52
+ { key: keys.active, value: { v: 1, instanceId: instance.instanceId, updatedAt: now } }];
53
+ if (storage.insertIfEmpty) return storage.insertIfEmpty(keys.keyPrefix, entries);
54
+ if ((await storage.keys(keys.keyPrefix)).length) return false;
55
+ const written: string[] = [];
56
+ try {
57
+ for (const entry of entries) { await storage.set(entry.key, entry.value); written.push(entry.key); }
58
+ } catch (error) { for (const key of written) await storage.remove(key); throw error; }
59
+ return true;
60
+ }
61
+ let ensuring: Promise<StoredInstance> | undefined;
62
+ async function save(instance: AuthInstance) {
63
+ if (!await insert(instance)) throw new ClientError("KEY_EXISTS", "An instance key already exists for this appId");
64
+ }
65
+ async function create(beforeWrite: () => void = () => {}) {
66
+ const instance = await createInstanceKey();
67
+ beforeWrite();
68
+ await save(instance);
69
+ return instance;
70
+ }
71
+ return {
72
+ keys, read, active,
73
+ import: save, create,
74
+ async remove() {
75
+ if (storage.removePrefix) return storage.removePrefix(keys.prefix);
76
+ for (const key of await storage.keys(keys.prefix)) await storage.remove(key);
77
+ },
78
+ ensure(): Promise<StoredInstance> {
79
+ return ensuring ??= (async () => {
80
+ const saved = await active();
81
+ if (saved) return saved;
82
+ try { await create(); }
83
+ catch (error) { if (!(error instanceof ClientError) || error.code !== "KEY_EXISTS") throw error; }
84
+ const value = await active();
85
+ if (!value) throw new ClientError("INVALID_INSTANCE_KEY", "Instance key was not saved");
86
+ return value;
87
+ })().finally(() => { ensuring = undefined; });
88
+ },
89
+ };
90
+ }
@@ -0,0 +1,47 @@
1
+ import type { BucketKeyGrantEnvelope, BucketKeys } from "../bucket/keys.ts";
2
+
3
+ export type AuthCapability = "read" | "write";
4
+
5
+ export type InstanceAuthContext = {
6
+ v: 1;
7
+ mfid: string;
8
+ resourceId: string;
9
+ remoteResourceId?: string;
10
+ resourceApiUrl?: string;
11
+ instanceId: string;
12
+ requestId: string;
13
+ authorizedAt: string;
14
+ bucketAccessGrant?: BucketAccessGrant;
15
+ };
16
+
17
+ export type BucketAccess = {
18
+ mfid: string;
19
+ instanceId: string;
20
+ bucketId: string;
21
+ resourceId: string;
22
+ resourceApiUrl?: string;
23
+ capabilities: AuthCapability[];
24
+ grantRecordId: string;
25
+ keys: BucketKeys;
26
+ };
27
+
28
+ export type AuthCallbackResult = {
29
+ requestId: string;
30
+ state: string;
31
+ result: "approved" | "denied" | "error";
32
+ resourceId?: string;
33
+ error?: string;
34
+ errorDescription?: string;
35
+ };
36
+
37
+ export type BucketAccessGrant = {
38
+ v: 1;
39
+ grantRecordId: string;
40
+ mfid: string;
41
+ resourceId: string;
42
+ instanceId: string;
43
+ issuedAt: string;
44
+ keyId: string;
45
+ capabilities: AuthCapability[];
46
+ envelope: BucketKeyGrantEnvelope;
47
+ };
@@ -49,6 +49,7 @@ export type BucketClientOptions = {
49
49
  mergeStrategyFor?: (appObjectId: string) => MergeStrategy;
50
50
  maxCasAttempts?: number;
51
51
  pushDebounceMs?: number;
52
+ autoSync?: boolean;
52
53
  localOnlyObjectIds?: Iterable<string>;
53
54
  validateRemote?: (appObjectId: string, doc: PayloadDoc) => void;
54
55
  onChange?: (appObjectId: string, source: ChangeSource) => void;
@@ -90,6 +91,7 @@ export class BucketClient {
90
91
  private readonly unresolved = new Map<string, string>();
91
92
  private triggerCleanup: (() => void) | null = null;
92
93
  private disposed = false;
94
+ private autoSync: boolean;
93
95
 
94
96
  constructor(options: BucketClientOptions) {
95
97
  this.transport = options.transport;
@@ -104,6 +106,7 @@ export class BucketClient {
104
106
  this.validateRemote = options.validateRemote;
105
107
  this.onChange = options.onChange;
106
108
  this.onSyncError = options.onSyncError;
109
+ this.autoSync = options.autoSync ?? true;
107
110
  }
108
111
 
109
112
  // ---- local reads -------------------------------------------------------
@@ -260,6 +263,7 @@ export class BucketClient {
260
263
  // are scheduled by setFields/setData.
261
264
  start(options: { intervalMs?: number; run: () => Promise<void> }): void {
262
265
  if (this.triggerCleanup || this.disposed) return;
266
+ this.autoSync = true;
263
267
  const run = options.run;
264
268
  const kick = () => void run().catch((error) => this.onSyncError?.(null, error));
265
269
  const intervalMs = options.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
@@ -271,6 +275,7 @@ export class BucketClient {
271
275
  }
272
276
 
273
277
  stop(): void {
278
+ this.autoSync = false;
274
279
  this.triggerCleanup?.();
275
280
  this.triggerCleanup = null;
276
281
  for (const timer of this.pendingPushTimers.values()) clearTimeout(timer);
@@ -297,7 +302,7 @@ export class BucketClient {
297
302
  // ---- internals ---------------------------------------------------------
298
303
 
299
304
  private schedulePush(appObjectId: string): void {
300
- if (this.disposed || this.localOnly.has(appObjectId)) return;
305
+ if (this.disposed || !this.autoSync || this.localOnly.has(appObjectId)) return;
301
306
  const existing = this.pendingPushTimers.get(appObjectId);
302
307
  if (existing) clearTimeout(existing);
303
308
  this.pendingPushTimers.set(
@@ -6,7 +6,9 @@ export type StorageAdapter = {
6
6
  get<T = unknown>(key: string): Promise<T | null>;
7
7
  set(key: string, value: unknown): Promise<void>;
8
8
  remove(key: string): Promise<void>;
9
+ removePrefix?(prefix: string): Promise<void>;
9
10
  keys(prefix: string): Promise<string[]>;
11
+ insertIfEmpty?(prefix: string, entries: { key: string; value: unknown }[]): Promise<boolean>;
10
12
  };
11
13
 
12
14
  // Per-process registry so memory-backed instances behave like persistent
@@ -29,6 +31,15 @@ export function createMemoryStorageAdapter(): StorageAdapter {
29
31
 
30
32
  function memoryAdapterOver(map: Map<string, unknown>): StorageAdapter {
31
33
  return {
34
+ async removePrefix(prefix) {
35
+ for (const key of map.keys()) if (key.startsWith(prefix)) map.delete(key);
36
+ },
37
+ async insertIfEmpty(prefix, entries) {
38
+ if ([...map.keys()].some(key => key.startsWith(prefix))) return false;
39
+ const cloned = entries.map(({ key, value }) => ({ key, value: structuredClone(value) }));
40
+ for (const { key, value } of cloned) map.set(key, value);
41
+ return true;
42
+ },
32
43
  async get<T>(key: string): Promise<T | null> {
33
44
  return map.has(key) ? (structuredClone(map.get(key)) as T) : null;
34
45
  },
@@ -51,6 +62,26 @@ export function createIndexedDbStorageAdapter(options: { dbName: string; storeNa
51
62
  const dbName = options.dbName;
52
63
  const storeName = options.storeName || "kv";
53
64
  return {
65
+ removePrefix: prefix => withIdb(dbName, storeName, db => new Promise<void>((resolve, reject) => {
66
+ const tx = db.transaction(storeName, "readwrite");
67
+ tx.objectStore(storeName).delete(IDBKeyRange.bound(prefix, `${prefix}\uffff`));
68
+ tx.oncomplete = () => resolve();
69
+ tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic removal failed"));
70
+ })),
71
+ insertIfEmpty: (prefix, entries) => withIdb(dbName, storeName, db => new Promise((resolve, reject) => {
72
+ const tx = db.transaction(storeName, "readwrite"), store = tx.objectStore(storeName);
73
+ let inserted = false;
74
+ const count = store.count(IDBKeyRange.bound(prefix, `${prefix}\uffff`));
75
+ count.onsuccess = () => {
76
+ if (count.result) return;
77
+ try {
78
+ for (const { key, value } of entries) store.put(value, key);
79
+ inserted = true;
80
+ } catch (error) { tx.abort(); reject(error); }
81
+ };
82
+ tx.oncomplete = () => resolve(inserted);
83
+ tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic write failed"));
84
+ })),
54
85
  get: <T>(key: string) =>
55
86
  withIdb<T | null>(dbName, storeName, (db) =>
56
87
  requestPromise<T | null>((resolve, reject) => {
@@ -7,12 +7,13 @@
7
7
  import { fnv1a32Bytes, utf8Encode } from "../internal/encoding.ts";
8
8
  import { decryptEnvelope, encryptEnvelopeFields } from "./crypto.ts";
9
9
  import type { BucketKeys } from "./keys.ts";
10
+ import { REVOKED_AUTHORIZATION_CODES } from "../errors.ts";
10
11
 
11
12
  export type SessionCredential = { carrier: "bearer"; token: string } | { carrier: "cookie" };
12
13
 
13
14
  export type SessionProvider = {
14
15
  getSession(options?: { forceRefresh?: boolean }): Promise<SessionCredential>;
15
- onUnauthorized?: () => void;
16
+ onUnauthorized?: () => void | Promise<void>;
16
17
  };
17
18
 
18
19
  export type TransportHeadResult = { found: false } | { found: true; versionId: string };
@@ -35,10 +36,10 @@ export class BucketTransportError extends Error {
35
36
  readonly status: number;
36
37
  readonly retryable: boolean;
37
38
 
38
- constructor(message: string, status: number) {
39
+ constructor(message: string, status: number, retryable = status === 429 || status >= 500) {
39
40
  super(message);
40
41
  this.status = status;
41
- this.retryable = status === 429 || status >= 500;
42
+ this.retryable = retryable;
42
43
  }
43
44
  }
44
45
 
@@ -47,6 +48,7 @@ export type BucketTransportOptions = {
47
48
  mfid: string;
48
49
  keys: BucketKeys;
49
50
  sessionProvider: SessionProvider;
51
+ fetch?: typeof fetch;
50
52
  };
51
53
 
52
54
  export class BucketTransport {
@@ -54,12 +56,14 @@ export class BucketTransport {
54
56
  private readonly mfid: string;
55
57
  private readonly keys: BucketKeys;
56
58
  private readonly sessionProvider: SessionProvider;
59
+ private readonly fetch: typeof fetch;
57
60
 
58
61
  constructor(options: BucketTransportOptions) {
59
62
  this.apiBase = options.apiBase.replace(/\/+$/, "");
60
63
  this.mfid = options.mfid;
61
64
  this.keys = options.keys;
62
65
  this.sessionProvider = options.sessionProvider;
66
+ this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
63
67
  }
64
68
 
65
69
  async pullHead(wireObjectId: string): Promise<TransportHeadResult> {
@@ -137,7 +141,17 @@ export class BucketTransport {
137
141
  return { ok: false, conflict: true, remoteVersionId: body?.headVersionId ?? null };
138
142
  }
139
143
  if (!res.ok) throw new BucketTransportError(`push failed: ${res.status}`, res.status);
140
- return { ok: true, versionId };
144
+ const result = await readJsonObject(res, "push");
145
+ if (result.ok === true) return { ok: true, versionId };
146
+ if (result.ok === false && ["version-mismatch", "conflict"].includes(String(result.reason))) {
147
+ return { ok: false, conflict: true, remoteVersionId: typeof result.headVersionId === "string" ? result.headVersionId : null };
148
+ }
149
+ if (result.ok === false && result.reason === "unauthorized") {
150
+ await this.sessionProvider.onUnauthorized?.();
151
+ throw new BucketTransportError("push was not authorized", 401, false);
152
+ }
153
+ throw new BucketTransportError(`push returned an unconfirmed acknowledgement${typeof result.reason === "string" ? `: ${result.reason}` : ""}`,
154
+ res.status, result.reason !== "invalid-input");
141
155
  }
142
156
 
143
157
  async listHeads(): Promise<Map<string, string>> {
@@ -178,13 +192,21 @@ export class BucketTransport {
178
192
  let session = await this.sessionProvider.getSession();
179
193
  let res = await this.send(build(), session);
180
194
  if (res.status === 401) {
195
+ void res.body?.cancel().catch(() => {});
181
196
  session = await this.sessionProvider.getSession({ forceRefresh: true });
182
197
  res = await this.send(build(), session);
183
198
  if (res.status === 401) {
184
- this.sessionProvider.onUnauthorized?.();
199
+ await this.sessionProvider.onUnauthorized?.();
185
200
  throw new BucketTransportError("bucket session unauthorized", 401);
186
201
  }
187
202
  }
203
+ if (res.status === 403) {
204
+ const body = await res.clone().json().catch(() => null) as { code?: string } | null;
205
+ if (REVOKED_AUTHORIZATION_CODES.includes(body?.code || "")) {
206
+ await this.sessionProvider.onUnauthorized?.();
207
+ throw new BucketTransportError("bucket authorization revoked", 403);
208
+ }
209
+ }
188
210
  return res;
189
211
  }
190
212
 
@@ -192,7 +214,7 @@ export class BucketTransport {
192
214
  const headers = new Headers(req.init.headers);
193
215
  headers.set("x-myfield-mfid", this.mfid);
194
216
  if (session.carrier === "bearer") headers.set("Authorization", `Bearer ${session.token}`);
195
- return fetch(req.url, {
217
+ return this.fetch(req.url, {
196
218
  ...req.init,
197
219
  headers,
198
220
  ...(session.carrier === "cookie" ? { credentials: "include" as RequestCredentials } : {}),
package/src/errors.ts CHANGED
@@ -7,3 +7,34 @@ export class NotConnectedError extends Error {
7
7
  this.name = "NotConnectedError";
8
8
  }
9
9
  }
10
+
11
+ export const REVOKED_AUTHORIZATION_CODES: readonly string[] = ["GRANT_REVOKED", "GRANT_NOT_FOUND", "AUTH_FAILED"];
12
+
13
+ export type ClientErrorOptions = {
14
+ status?: number;
15
+ requestId?: string;
16
+ retryable?: boolean;
17
+ retryAfterMs?: number;
18
+ maxBytes?: number;
19
+ cause?: unknown;
20
+ };
21
+
22
+ export class ClientError extends Error {
23
+ readonly code: string;
24
+ readonly status?: number;
25
+ readonly requestId?: string;
26
+ readonly retryable: boolean;
27
+ readonly retryAfterMs?: number;
28
+ readonly maxBytes?: number;
29
+
30
+ constructor(code: string, message: string, options: ClientErrorOptions = {}) {
31
+ super(message, { cause: options.cause });
32
+ this.name = "ClientError";
33
+ this.code = code;
34
+ this.status = options.status;
35
+ this.requestId = options.requestId;
36
+ this.retryable = options.retryable ?? false;
37
+ this.retryAfterMs = options.retryAfterMs;
38
+ this.maxBytes = options.maxBytes;
39
+ }
40
+ }