@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/CHANGELOG.md +19 -0
- package/LICENSE +201 -0
- package/README.md +125 -0
- package/dist/index.js +2254 -0
- package/docs/API.md +210 -0
- package/docs/BUCKET-SPEC.md +153 -0
- package/package.json +58 -0
- package/src/auth/index.ts +17 -0
- package/src/auth/instance.ts +876 -0
- package/src/bucket/binary.ts +253 -0
- package/src/bucket/client.ts +383 -0
- package/src/bucket/crypto.ts +58 -0
- package/src/bucket/format.ts +275 -0
- package/src/bucket/index.ts +40 -0
- package/src/bucket/keys.ts +104 -0
- package/src/bucket/store.ts +159 -0
- package/src/bucket/transport.ts +187 -0
- package/src/errors.ts +9 -0
- package/src/facade.ts +691 -0
- package/src/index.ts +23 -0
- package/src/internal/encoding.ts +95 -0
- package/types/index.d.ts +70 -0
package/src/facade.ts
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
// Public facade (docs/API.md): createInstance / Instance / Bucket.
|
|
2
|
+
//
|
|
3
|
+
// A bucket is a local-first end-to-end-encrypted object KV. Local CRUD works
|
|
4
|
+
// with no account and no network; connect() is the single network/identity
|
|
5
|
+
// boundary. `namespace` scopes ALL local persistence (instance keys, auth
|
|
6
|
+
// context, sessions, objects, the internal index) and never reaches the
|
|
7
|
+
// wire; bucket `id` is the app-local authorization label, while sync uses
|
|
8
|
+
// the remote bucket id returned in the grant envelope.
|
|
9
|
+
|
|
10
|
+
import { BucketClient, type BucketTransportLike } from "./bucket/client.ts";
|
|
11
|
+
import {
|
|
12
|
+
canonicalizeFieldValue,
|
|
13
|
+
createBucketBinaryValue,
|
|
14
|
+
fieldValueToCanonicalJson,
|
|
15
|
+
type BinaryInput,
|
|
16
|
+
type BinaryOptions,
|
|
17
|
+
type BucketBinaryValue,
|
|
18
|
+
} from "./bucket/binary.ts";
|
|
19
|
+
import {
|
|
20
|
+
createIndexedDbStorageAdapter,
|
|
21
|
+
createNamespacedMemoryStorageAdapter,
|
|
22
|
+
type StorageAdapter,
|
|
23
|
+
} from "./bucket/store.ts";
|
|
24
|
+
import { BucketTransport, OfflineError } from "./bucket/transport.ts";
|
|
25
|
+
import { createInstanceAuthClient, isValidBucketId, type AuthCallbackResult, type InstanceAuthClient } from "./auth/instance.ts";
|
|
26
|
+
import { NotConnectedError } from "./errors.ts";
|
|
27
|
+
import { randomId } from "./internal/encoding.ts";
|
|
28
|
+
|
|
29
|
+
const DEFAULT_AUTH_BASE = "https://myfield.one/auth/";
|
|
30
|
+
const DEFAULT_API_BASE = "https://api.myfield.one";
|
|
31
|
+
const INDEX_OBJECT_ID = "~index";
|
|
32
|
+
const DELETED_FIELD = "~deleted";
|
|
33
|
+
const RESERVED_PREFIX = "~";
|
|
34
|
+
|
|
35
|
+
export type CreateInstanceOptions = {
|
|
36
|
+
namespace?: string;
|
|
37
|
+
storage?: "indexeddb" | "memory";
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export type BucketState = "disconnected" | "connecting" | "connected";
|
|
41
|
+
|
|
42
|
+
export type ListEntry = { id: string; updatedAt: string; deleted?: true };
|
|
43
|
+
|
|
44
|
+
export type ConnectOptions = {
|
|
45
|
+
authBase?: string;
|
|
46
|
+
autoSync?: boolean;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export type { BinaryInput, BinaryOptions, BucketBinaryValue };
|
|
50
|
+
|
|
51
|
+
export type Bucket = {
|
|
52
|
+
readonly id: string;
|
|
53
|
+
readonly state: BucketState;
|
|
54
|
+
binary(input: BinaryInput | BucketBinaryValue, options?: BinaryOptions): BucketBinaryValue;
|
|
55
|
+
ready(): Promise<void>;
|
|
56
|
+
put(objectId: string, object: Record<string, unknown>): Promise<void>;
|
|
57
|
+
get(objectId: string): Promise<Record<string, unknown> | null>;
|
|
58
|
+
update(objectId: string, fields: Record<string, unknown>): Promise<void>;
|
|
59
|
+
delete(objectId: string): Promise<void>;
|
|
60
|
+
list(options?: { prefix?: string; includeDeleted?: boolean }): Promise<ListEntry[]>;
|
|
61
|
+
resume(): Promise<BucketState>;
|
|
62
|
+
connect(options?: ConnectOptions): Promise<BucketState>;
|
|
63
|
+
disconnect(): Promise<void>;
|
|
64
|
+
sync(): Promise<void>;
|
|
65
|
+
setAutoSync(enabled: boolean): void;
|
|
66
|
+
on(event: "state", handler: (state: BucketState, detail?: string) => void): () => void;
|
|
67
|
+
on(event: "change", handler: (objectId: string) => void): () => void;
|
|
68
|
+
dispose(): void;
|
|
69
|
+
// Internal test seam: binds a transport as if connect() succeeded, with
|
|
70
|
+
// identity wire ids (blinding has its own unit tests). Not public API.
|
|
71
|
+
__bindTestTransport(transport: BucketTransportLike): void;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export type Instance = {
|
|
75
|
+
readonly namespace: string;
|
|
76
|
+
createBucket(options: { id: string }): Bucket;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export function createInstance(options: CreateInstanceOptions = {}): Instance {
|
|
80
|
+
const namespace = normalizeNamespace(options.namespace);
|
|
81
|
+
const storageKind = options.storage || "indexeddb";
|
|
82
|
+
|
|
83
|
+
const baseAdapter =
|
|
84
|
+
storageKind === "memory"
|
|
85
|
+
? createNamespacedMemoryStorageAdapter(`myfield-sdk:${namespace}`)
|
|
86
|
+
: createIndexedDbStorageAdapter({ dbName: `myfield-sdk:${namespace}` });
|
|
87
|
+
const authAdapter = prefixedAdapter(baseAdapter, "auth:");
|
|
88
|
+
|
|
89
|
+
// One handle per bucket id: separate facades over the same storage would
|
|
90
|
+
// split event listeners and duplicate clients/clocks/debounce timers.
|
|
91
|
+
const buckets = new Map<string, Bucket>();
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
namespace,
|
|
95
|
+
createBucket(bucketOptions) {
|
|
96
|
+
const bucketId = String(bucketOptions?.id || "").trim();
|
|
97
|
+
if (!bucketId) throw new Error("bucket id is required");
|
|
98
|
+
if (!isValidBucketId(bucketId)) throw new Error("invalid bucketId");
|
|
99
|
+
const existing = buckets.get(bucketId);
|
|
100
|
+
if (existing) return existing;
|
|
101
|
+
const bucket = createBucketFacade({ namespace, bucketId, dataAdapter: baseAdapter, authAdapter });
|
|
102
|
+
buckets.set(bucketId, bucket);
|
|
103
|
+
return bucket;
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ---------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
type BucketDeps = {
|
|
111
|
+
namespace: string;
|
|
112
|
+
bucketId: string;
|
|
113
|
+
dataAdapter: StorageAdapter;
|
|
114
|
+
authAdapter: StorageAdapter;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
function createBucketFacade(deps: BucketDeps): Bucket {
|
|
118
|
+
const { bucketId, dataAdapter, authAdapter } = deps;
|
|
119
|
+
const endpointsKey = `meta:${bucketId}:endpoints`;
|
|
120
|
+
const actorKey = `meta:actor`;
|
|
121
|
+
|
|
122
|
+
let state: BucketState = "disconnected";
|
|
123
|
+
let client: BucketClient | null = null;
|
|
124
|
+
let clientInit: Promise<BucketClient> | null = null;
|
|
125
|
+
let liveTransport: BucketTransportLike | null = null;
|
|
126
|
+
let liveWireId: ((appObjectId: string) => Promise<string>) | null = null;
|
|
127
|
+
let autoSync = true;
|
|
128
|
+
let syncIntervalMs: number | undefined;
|
|
129
|
+
let disposed = false;
|
|
130
|
+
|
|
131
|
+
// Browser auth machinery (lazy; never touched by the test seam path).
|
|
132
|
+
let authClient: InstanceAuthClient | null = null;
|
|
133
|
+
let popupAuthClient: InstanceAuthClient | null = null;
|
|
134
|
+
let authPageOrigin = "";
|
|
135
|
+
let authPopupWindow: Window | null = null;
|
|
136
|
+
let authPopupPollTimer: ReturnType<typeof setInterval> | null = null;
|
|
137
|
+
let pendingConnect: { resolve: (state: BucketState) => void } | null = null;
|
|
138
|
+
let pendingConnectDone: Promise<BucketState> | null = null;
|
|
139
|
+
let popupMessageListener: ((event: MessageEvent<unknown>) => void) | null = null;
|
|
140
|
+
|
|
141
|
+
const listeners = { state: new Set<(s: BucketState, d?: string) => void>(), change: new Set<(id: string) => void>() };
|
|
142
|
+
|
|
143
|
+
function emitState(next: BucketState, detail?: string): void {
|
|
144
|
+
if (state !== next) {
|
|
145
|
+
state = next;
|
|
146
|
+
for (const handler of listeners.state) handler(next, detail);
|
|
147
|
+
} else if (detail) {
|
|
148
|
+
for (const handler of listeners.state) handler(next, detail);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function emitChange(objectId: string): void {
|
|
153
|
+
if (objectId.startsWith(RESERVED_PREFIX)) return;
|
|
154
|
+
for (const handler of listeners.change) handler(objectId);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function settlePendingConnect(): void {
|
|
158
|
+
if (!pendingConnect) return;
|
|
159
|
+
const settle = pendingConnect;
|
|
160
|
+
pendingConnect = null;
|
|
161
|
+
settle.resolve(state);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function ensureClient(): Promise<BucketClient> {
|
|
165
|
+
if (clientInit) return clientInit;
|
|
166
|
+
clientInit = (async () => {
|
|
167
|
+
let actorId = await dataAdapter.get<string>(actorKey);
|
|
168
|
+
if (typeof actorId !== "string" || !actorId) {
|
|
169
|
+
actorId = randomId("actor");
|
|
170
|
+
await dataAdapter.set(actorKey, actorId);
|
|
171
|
+
}
|
|
172
|
+
client = new BucketClient({
|
|
173
|
+
transport: {
|
|
174
|
+
pullHead(wireObjectId) {
|
|
175
|
+
if (!liveTransport) return Promise.reject(new OfflineError());
|
|
176
|
+
return liveTransport.pullHead(wireObjectId);
|
|
177
|
+
},
|
|
178
|
+
pullPayload(wireObjectId, versionId) {
|
|
179
|
+
if (!liveTransport) return Promise.reject(new OfflineError());
|
|
180
|
+
return liveTransport.pullPayload(wireObjectId, versionId);
|
|
181
|
+
},
|
|
182
|
+
push(wireObjectId, plaintext, expectedHeadVersionId) {
|
|
183
|
+
if (!liveTransport) return Promise.reject(new OfflineError());
|
|
184
|
+
return liveTransport.push(wireObjectId, plaintext, expectedHeadVersionId);
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
storage: dataAdapter,
|
|
188
|
+
actorId,
|
|
189
|
+
wireObjectId: (appObjectId) => {
|
|
190
|
+
if (!liveWireId) return Promise.reject(new OfflineError());
|
|
191
|
+
return liveWireId(appObjectId);
|
|
192
|
+
},
|
|
193
|
+
storagePrefix: `data:${bucketId}`,
|
|
194
|
+
onChange: emitChange,
|
|
195
|
+
onSyncError: (objectId, error) => {
|
|
196
|
+
if (error instanceof OfflineError) return;
|
|
197
|
+
// Retryable sync failures surface as state detail without a state
|
|
198
|
+
// change; local data is never affected.
|
|
199
|
+
emitState(state, `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`);
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
return client;
|
|
203
|
+
})();
|
|
204
|
+
return clientInit;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ---- local object API ---------------------------------------------------
|
|
208
|
+
|
|
209
|
+
function assertObjectId(objectId: string): void {
|
|
210
|
+
if (typeof objectId !== "string" || !objectId) throw new Error("objectId must be a non-empty string");
|
|
211
|
+
if (objectId.startsWith(RESERVED_PREFIX)) throw new Error(`object ids starting with "${RESERVED_PREFIX}" are reserved`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function assertFieldNames(fields: Record<string, unknown>): void {
|
|
215
|
+
if (!fields || typeof fields !== "object" || Array.isArray(fields)) throw new Error("fields must be a plain object");
|
|
216
|
+
for (const name of Object.keys(fields)) {
|
|
217
|
+
if (name.startsWith(RESERVED_PREFIX)) throw new Error(`field names starting with "${RESERVED_PREFIX}" are reserved`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function upsertIndexEntry(objectId: string, deleted: boolean): Promise<void> {
|
|
222
|
+
const c = await ensureClient();
|
|
223
|
+
await c.setFields(INDEX_OBJECT_ID, {
|
|
224
|
+
[objectId]: { updatedAt: new Date().toISOString(), ...(deleted ? { deleted: true } : {}) },
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function publicView(raw: Record<string, unknown>): Record<string, unknown> {
|
|
229
|
+
return Object.fromEntries(Object.entries(raw).filter(([name]) => !name.startsWith(RESERVED_PREFIX)));
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Fields whose JSON value is unchanged keep their existing LWW
|
|
233
|
+
// timestamp/source (API.md): re-stamping unchanged fields would let a
|
|
234
|
+
// device that re-saves whole objects steamroll other devices' concurrent
|
|
235
|
+
// field edits.
|
|
236
|
+
async function dropUnchanged(updates: Record<string, unknown>, known: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
237
|
+
const changed: Record<string, unknown> = {};
|
|
238
|
+
for (const [name, value] of Object.entries(updates)) {
|
|
239
|
+
if (value === undefined) {
|
|
240
|
+
if (name in known) changed[name] = undefined;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
const canonicalValue = await canonicalizeFieldValue(value);
|
|
244
|
+
if (name in known && JSON.stringify(fieldValueToCanonicalJson(await canonicalizeFieldValue(known[name]))) === JSON.stringify(fieldValueToCanonicalJson(canonicalValue))) continue;
|
|
245
|
+
changed[name] = value;
|
|
246
|
+
}
|
|
247
|
+
return changed;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function put(objectId: string, object: Record<string, unknown>): Promise<void> {
|
|
251
|
+
assertObjectId(objectId);
|
|
252
|
+
assertFieldNames(object);
|
|
253
|
+
const c = await ensureClient();
|
|
254
|
+
const known = (await c.getFields(objectId)) || {};
|
|
255
|
+
const updates: Record<string, unknown> = { ...object };
|
|
256
|
+
for (const name of Object.keys(known)) {
|
|
257
|
+
if (!(name in object)) updates[name] = undefined; // deletes locally known omitted fields (incl. a live ~deleted marker)
|
|
258
|
+
}
|
|
259
|
+
const changed = await dropUnchanged(updates, known);
|
|
260
|
+
if (Object.keys(changed).length === 0) return; // full no-op: do not advance LWW state or the index entry
|
|
261
|
+
await c.setFields(objectId, changed);
|
|
262
|
+
await upsertIndexEntry(objectId, false);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function update(objectId: string, fields: Record<string, unknown>): Promise<void> {
|
|
266
|
+
assertObjectId(objectId);
|
|
267
|
+
assertFieldNames(fields);
|
|
268
|
+
const c = await ensureClient();
|
|
269
|
+
const known = (await c.getFields(objectId)) || {};
|
|
270
|
+
const updates: Record<string, unknown> = { ...fields };
|
|
271
|
+
if (DELETED_FIELD in known) updates[DELETED_FIELD] = undefined; // update recreates a deleted object
|
|
272
|
+
const changed = await dropUnchanged(updates, known);
|
|
273
|
+
if (Object.keys(changed).length === 0) return;
|
|
274
|
+
await c.setFields(objectId, changed);
|
|
275
|
+
await upsertIndexEntry(objectId, false);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function getObject(objectId: string): Promise<Record<string, unknown> | null> {
|
|
279
|
+
assertObjectId(objectId);
|
|
280
|
+
const c = await ensureClient();
|
|
281
|
+
const raw = await c.getFields(objectId);
|
|
282
|
+
if (!raw) return null;
|
|
283
|
+
if (raw[DELETED_FIELD]) return null;
|
|
284
|
+
const view = publicView(raw);
|
|
285
|
+
return Object.keys(view).length === 0 && !(await hasIndexEntry(objectId)) ? null : view;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function hasIndexEntry(objectId: string): Promise<boolean> {
|
|
289
|
+
const c = await ensureClient();
|
|
290
|
+
const index = (await c.getFields(INDEX_OBJECT_ID)) || {};
|
|
291
|
+
return objectId in index;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function deleteObject(objectId: string): Promise<void> {
|
|
295
|
+
assertObjectId(objectId);
|
|
296
|
+
const c = await ensureClient();
|
|
297
|
+
const known = (await c.getFields(objectId)) || {};
|
|
298
|
+
const updates: Record<string, unknown> = { [DELETED_FIELD]: true };
|
|
299
|
+
for (const name of Object.keys(known)) {
|
|
300
|
+
if (!name.startsWith(RESERVED_PREFIX)) updates[name] = undefined;
|
|
301
|
+
}
|
|
302
|
+
await c.setFields(objectId, updates);
|
|
303
|
+
await upsertIndexEntry(objectId, true);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async function list(options?: { prefix?: string; includeDeleted?: boolean }): Promise<ListEntry[]> {
|
|
307
|
+
const c = await ensureClient();
|
|
308
|
+
const index = (await c.getFields(INDEX_OBJECT_ID)) || {};
|
|
309
|
+
const rows: ListEntry[] = [];
|
|
310
|
+
for (const [objectId, value] of Object.entries(index)) {
|
|
311
|
+
if (objectId.startsWith(RESERVED_PREFIX)) continue;
|
|
312
|
+
if (options?.prefix && !objectId.startsWith(options.prefix)) continue;
|
|
313
|
+
const entry = value as { updatedAt?: unknown; deleted?: unknown } | null;
|
|
314
|
+
if (!entry || typeof entry.updatedAt !== "string") continue;
|
|
315
|
+
const deleted = entry.deleted === true;
|
|
316
|
+
if (deleted && !options?.includeDeleted) continue;
|
|
317
|
+
rows.push({ id: objectId, updatedAt: entry.updatedAt, ...(deleted ? { deleted: true as const } : {}) });
|
|
318
|
+
}
|
|
319
|
+
rows.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));
|
|
320
|
+
return rows;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ---- sync ---------------------------------------------------------------
|
|
324
|
+
|
|
325
|
+
async function sync(): Promise<void> {
|
|
326
|
+
if (!liveTransport) throw new NotConnectedError();
|
|
327
|
+
const c = await ensureClient();
|
|
328
|
+
const dirtyObjectIds = (await c.dirtyObjectIds()).filter((id) => id !== INDEX_OBJECT_ID && !id.startsWith(RESERVED_PREFIX));
|
|
329
|
+
await c.syncAuto({ indexObjectId: INDEX_OBJECT_ID });
|
|
330
|
+
for (const id of dirtyObjectIds) {
|
|
331
|
+
const raw = await c.getFields(id);
|
|
332
|
+
await upsertIndexEntry(id, raw?.[DELETED_FIELD] === true);
|
|
333
|
+
}
|
|
334
|
+
if (dirtyObjectIds.length > 0) await c.syncObject(INDEX_OBJECT_ID);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function startAutoSync(): void {
|
|
338
|
+
if (!autoSync || !client) return;
|
|
339
|
+
client.watch([INDEX_OBJECT_ID]);
|
|
340
|
+
client.start({ indexObjectId: INDEX_OBJECT_ID, ...(syncIntervalMs !== undefined ? { intervalMs: syncIntervalMs } : {}) });
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ---- connection (browser) ----------------------------------------------
|
|
344
|
+
|
|
345
|
+
async function readStoredEndpoints(): Promise<{ authBase: string; apiBase: string }> {
|
|
346
|
+
const stored = await dataAdapter.get<{ authBase?: string; apiBase?: string }>(endpointsKey);
|
|
347
|
+
const authBase = stored?.authBase || DEFAULT_AUTH_BASE;
|
|
348
|
+
return {
|
|
349
|
+
authBase,
|
|
350
|
+
apiBase: stored?.apiBase || apiBaseForAuthBase(authBase),
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async function ensureAuthClients(endpoints: { authBase: string; apiBase: string }): Promise<InstanceAuthClient> {
|
|
355
|
+
if (authClient) return authClient;
|
|
356
|
+
if (typeof window === "undefined") throw new Error("connect()/resume() require a browser environment");
|
|
357
|
+
const origin = window.location.origin;
|
|
358
|
+
const authPageUrl = normalizeAuthBase(endpoints.authBase);
|
|
359
|
+
authPageOrigin = new URL(authPageUrl, window.location.href).origin;
|
|
360
|
+
const baseOptions = {
|
|
361
|
+
appId: new URL(origin).hostname,
|
|
362
|
+
apiBase: endpoints.apiBase,
|
|
363
|
+
redirectUri: origin + window.location.pathname,
|
|
364
|
+
origin,
|
|
365
|
+
storage: authAdapter,
|
|
366
|
+
};
|
|
367
|
+
authClient = createInstanceAuthClient({
|
|
368
|
+
...baseOptions,
|
|
369
|
+
authPageUrl: addCallbackTransport(authPageUrl, "same-tab"),
|
|
370
|
+
});
|
|
371
|
+
popupAuthClient = createInstanceAuthClient({
|
|
372
|
+
...baseOptions,
|
|
373
|
+
authPageUrl: addCallbackTransport(authPageUrl, "popup"),
|
|
374
|
+
openAuthUrl: (url) => openAuthPopupUrl(url),
|
|
375
|
+
});
|
|
376
|
+
popupMessageListener = (event: MessageEvent<unknown>) => void onPopupMessage(event);
|
|
377
|
+
window.addEventListener("message", popupMessageListener);
|
|
378
|
+
return authClient;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function clearPopupMonitor(): void {
|
|
382
|
+
if (authPopupPollTimer != null) {
|
|
383
|
+
clearInterval(authPopupPollTimer);
|
|
384
|
+
authPopupPollTimer = null;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function tryOpenPopupShell(): boolean {
|
|
389
|
+
clearPopupMonitor();
|
|
390
|
+
authPopupWindow?.close();
|
|
391
|
+
const width = 520;
|
|
392
|
+
const height = 720;
|
|
393
|
+
const left = Math.max(0, Math.floor(window.screenX + (window.outerWidth - width) / 2));
|
|
394
|
+
const top = Math.max(0, Math.floor(window.screenY + (window.outerHeight - height) / 2));
|
|
395
|
+
authPopupWindow = window.open(
|
|
396
|
+
"about:blank",
|
|
397
|
+
"myfield-sdk-auth",
|
|
398
|
+
`popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
|
|
399
|
+
);
|
|
400
|
+
if (!authPopupWindow || authPopupWindow.closed) {
|
|
401
|
+
authPopupWindow = null;
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
authPopupWindow.document.title = "Opening Myfield...";
|
|
406
|
+
authPopupWindow.document.body.textContent = "Opening Myfield authorization...";
|
|
407
|
+
} catch {
|
|
408
|
+
// Same-origin about:blank in normal browsers; ignore if blocked.
|
|
409
|
+
}
|
|
410
|
+
authPopupWindow.focus();
|
|
411
|
+
authPopupPollTimer = setInterval(() => {
|
|
412
|
+
if (!authPopupWindow?.closed) return;
|
|
413
|
+
clearPopupMonitor();
|
|
414
|
+
if (state === "connecting") {
|
|
415
|
+
emitState("disconnected", "authorization window closed");
|
|
416
|
+
settlePendingConnect();
|
|
417
|
+
}
|
|
418
|
+
}, 500);
|
|
419
|
+
return true;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function openAuthPopupUrl(url: string): void {
|
|
423
|
+
if (!authPopupWindow || authPopupWindow.closed) {
|
|
424
|
+
if (!tryOpenPopupShell()) throw new Error("authorization popup was blocked");
|
|
425
|
+
}
|
|
426
|
+
try {
|
|
427
|
+
authPopupWindow!.location.href = url;
|
|
428
|
+
authPopupWindow!.focus();
|
|
429
|
+
} catch {
|
|
430
|
+
authPopupWindow = window.open(url, "myfield-sdk-auth");
|
|
431
|
+
if (!authPopupWindow) throw new Error("authorization popup was blocked");
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async function onPopupMessage(event: MessageEvent<unknown>): Promise<void> {
|
|
436
|
+
if (event.origin !== authPageOrigin) return;
|
|
437
|
+
const message = event.data as { type?: unknown; callbackUrl?: unknown } | null;
|
|
438
|
+
if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
|
|
439
|
+
clearPopupMonitor();
|
|
440
|
+
authPopupWindow?.close();
|
|
441
|
+
authPopupWindow = null;
|
|
442
|
+
await handleCallbackUrl(message.callbackUrl);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
async function handleCallbackUrl(callbackUrl: string): Promise<AuthCallbackResult | null> {
|
|
446
|
+
try {
|
|
447
|
+
const auth = await ensureAuthClients(await readStoredEndpoints());
|
|
448
|
+
const callback = await auth.handleCallback(callbackUrl);
|
|
449
|
+
if (!callback) return null;
|
|
450
|
+
if (callback.result === "approved") {
|
|
451
|
+
await establish({ forceRefresh: true });
|
|
452
|
+
} else {
|
|
453
|
+
emitState("disconnected", callback.errorDescription || callback.error || callback.result);
|
|
454
|
+
settlePendingConnect();
|
|
455
|
+
}
|
|
456
|
+
return callback;
|
|
457
|
+
} catch (error) {
|
|
458
|
+
emitState("disconnected", formatError(error));
|
|
459
|
+
settlePendingConnect();
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function establish(sessionOptions: { forceRefresh?: boolean } = {}): Promise<void> {
|
|
465
|
+
emitState("connecting");
|
|
466
|
+
try {
|
|
467
|
+
const endpoints = await readStoredEndpoints();
|
|
468
|
+
const auth = await ensureAuthClients(endpoints);
|
|
469
|
+
const c = await ensureClient();
|
|
470
|
+
await auth.getSession(bucketId, sessionOptions);
|
|
471
|
+
const access = await auth.getBucketAccess(bucketId);
|
|
472
|
+
if (!access.resourceApiUrl) throw new Error("auth callback missing resourceApiUrl; reconnect through the current Myfield auth page");
|
|
473
|
+
const transport = new BucketTransport({
|
|
474
|
+
apiBase: access.resourceApiUrl,
|
|
475
|
+
mfid: access.mfid,
|
|
476
|
+
keys: access.keys,
|
|
477
|
+
sessionProvider: {
|
|
478
|
+
getSession: (sessionOpts) => auth.getSession(bucketId, sessionOpts),
|
|
479
|
+
onUnauthorized: () => {
|
|
480
|
+
// Grant revoked: drop back to local-first; reconnecting needs a
|
|
481
|
+
// user gesture through connect() again.
|
|
482
|
+
liveTransport = null;
|
|
483
|
+
liveWireId = null;
|
|
484
|
+
c.stop();
|
|
485
|
+
emitState("disconnected", "unauthorized");
|
|
486
|
+
},
|
|
487
|
+
},
|
|
488
|
+
});
|
|
489
|
+
await verifyConnectedTransport(transport, access.keys.wireObjectId);
|
|
490
|
+
liveTransport = transport;
|
|
491
|
+
liveWireId = access.keys.wireObjectId;
|
|
492
|
+
startAutoSync();
|
|
493
|
+
emitState("connected");
|
|
494
|
+
} catch (error) {
|
|
495
|
+
client?.stop();
|
|
496
|
+
emitState("disconnected", formatError(error));
|
|
497
|
+
} finally {
|
|
498
|
+
settlePendingConnect();
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function verifyConnectedTransport(transport: BucketTransport, wireObjectId: (appObjectId: string) => Promise<string>): Promise<void> {
|
|
503
|
+
await transport.pullHead(await wireObjectId(INDEX_OBJECT_ID));
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async function handleStartupCallback(): Promise<boolean> {
|
|
507
|
+
const href = window.location.href;
|
|
508
|
+
if (!href.includes("mf_auth_result") && !new URL(href).searchParams.get("mf_request_id")) return false;
|
|
509
|
+
const callback = await handleCallbackUrl(href);
|
|
510
|
+
if (callback) stripCallbackFromUrl();
|
|
511
|
+
return !!callback;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function stripCallbackFromUrl(): void {
|
|
515
|
+
try {
|
|
516
|
+
const url = new URL(window.location.href);
|
|
517
|
+
url.hash = "";
|
|
518
|
+
for (const param of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) url.searchParams.delete(param);
|
|
519
|
+
window.history.replaceState(null, "", url.toString());
|
|
520
|
+
} catch {
|
|
521
|
+
// Cosmetic only.
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// ---- public object ------------------------------------------------------
|
|
526
|
+
|
|
527
|
+
return {
|
|
528
|
+
id: bucketId,
|
|
529
|
+
get state() {
|
|
530
|
+
return state;
|
|
531
|
+
},
|
|
532
|
+
binary(input, options) {
|
|
533
|
+
return createBucketBinaryValue(input, options);
|
|
534
|
+
},
|
|
535
|
+
async ready() {
|
|
536
|
+
await ensureClient();
|
|
537
|
+
},
|
|
538
|
+
put,
|
|
539
|
+
get: getObject,
|
|
540
|
+
update,
|
|
541
|
+
delete: deleteObject,
|
|
542
|
+
list,
|
|
543
|
+
async resume() {
|
|
544
|
+
if (disposed) throw new Error("disposed");
|
|
545
|
+
await ensureClient();
|
|
546
|
+
if (typeof window === "undefined") return state;
|
|
547
|
+
if (state !== "disconnected") return state;
|
|
548
|
+
const auth = await ensureAuthClients(await readStoredEndpoints());
|
|
549
|
+
if (await handleStartupCallback()) return state;
|
|
550
|
+
const context = await auth.getContext(bucketId);
|
|
551
|
+
if (context) await establish();
|
|
552
|
+
return state;
|
|
553
|
+
},
|
|
554
|
+
async connect(options) {
|
|
555
|
+
if (disposed) throw new Error("disposed");
|
|
556
|
+
if (options?.autoSync !== undefined) autoSync = options.autoSync;
|
|
557
|
+
if (options?.authBase) {
|
|
558
|
+
const endpoints = await readStoredEndpoints();
|
|
559
|
+
const authBase = normalizeAuthBase(options.authBase);
|
|
560
|
+
await dataAdapter.set(endpointsKey, {
|
|
561
|
+
authBase,
|
|
562
|
+
apiBase: apiBaseForAuthBase(authBase) || endpoints.apiBase,
|
|
563
|
+
});
|
|
564
|
+
// Endpoints changed: force fresh auth clients bound to them.
|
|
565
|
+
if (popupMessageListener && typeof window !== "undefined") {
|
|
566
|
+
window.removeEventListener("message", popupMessageListener);
|
|
567
|
+
popupMessageListener = null;
|
|
568
|
+
}
|
|
569
|
+
authClient = null;
|
|
570
|
+
popupAuthClient = null;
|
|
571
|
+
}
|
|
572
|
+
if (state === "connected") return state;
|
|
573
|
+
// Re-entrant connect (e.g. a double-clicked button) joins the pending
|
|
574
|
+
// flow instead of orphaning the first caller's promise.
|
|
575
|
+
if (pendingConnectDone) return pendingConnectDone;
|
|
576
|
+
const resumed = await this.resume();
|
|
577
|
+
if (resumed !== "disconnected") return resumed;
|
|
578
|
+
if (pendingConnectDone) return pendingConnectDone;
|
|
579
|
+
const auth = await ensureAuthClients(await readStoredEndpoints());
|
|
580
|
+
emitState("connecting");
|
|
581
|
+
const done = new Promise<BucketState>((resolve) => {
|
|
582
|
+
pendingConnect = { resolve };
|
|
583
|
+
}).finally(() => {
|
|
584
|
+
if (pendingConnectDone === done) pendingConnectDone = null;
|
|
585
|
+
});
|
|
586
|
+
pendingConnectDone = done;
|
|
587
|
+
try {
|
|
588
|
+
if (shouldUseSameTabAuth() || !tryOpenPopupShell()) {
|
|
589
|
+
clearPopupMonitor();
|
|
590
|
+
authPopupWindow = null;
|
|
591
|
+
await auth.authorize({ bucketId });
|
|
592
|
+
// Same-tab navigates away; resolution happens on reload via resume().
|
|
593
|
+
} else {
|
|
594
|
+
await popupAuthClient!.authorize({ bucketId });
|
|
595
|
+
}
|
|
596
|
+
} catch (error) {
|
|
597
|
+
authPopupWindow?.close();
|
|
598
|
+
authPopupWindow = null;
|
|
599
|
+
clearPopupMonitor();
|
|
600
|
+
emitState("disconnected", formatError(error));
|
|
601
|
+
settlePendingConnect();
|
|
602
|
+
}
|
|
603
|
+
return done;
|
|
604
|
+
},
|
|
605
|
+
async disconnect() {
|
|
606
|
+
liveTransport = null;
|
|
607
|
+
liveWireId = null;
|
|
608
|
+
client?.stop();
|
|
609
|
+
if (authClient) await authClient.clearContext(bucketId);
|
|
610
|
+
emitState("disconnected");
|
|
611
|
+
settlePendingConnect();
|
|
612
|
+
},
|
|
613
|
+
async sync() {
|
|
614
|
+
await sync();
|
|
615
|
+
},
|
|
616
|
+
setAutoSync(enabled) {
|
|
617
|
+
autoSync = enabled;
|
|
618
|
+
if (!client) return;
|
|
619
|
+
if (enabled && liveTransport) startAutoSync();
|
|
620
|
+
if (!enabled) client.stop();
|
|
621
|
+
},
|
|
622
|
+
on(event: "state" | "change", handler: (...args: never[]) => void): () => void {
|
|
623
|
+
const set = listeners[event] as Set<(...args: unknown[]) => void>;
|
|
624
|
+
set.add(handler as (...args: unknown[]) => void);
|
|
625
|
+
return () => set.delete(handler as (...args: unknown[]) => void);
|
|
626
|
+
},
|
|
627
|
+
dispose() {
|
|
628
|
+
disposed = true;
|
|
629
|
+
client?.dispose();
|
|
630
|
+
clearPopupMonitor();
|
|
631
|
+
if (popupMessageListener && typeof window !== "undefined") window.removeEventListener("message", popupMessageListener);
|
|
632
|
+
},
|
|
633
|
+
__bindTestTransport(transport) {
|
|
634
|
+
liveTransport = transport;
|
|
635
|
+
liveWireId = async (appObjectId) => appObjectId;
|
|
636
|
+
emitState("connected");
|
|
637
|
+
},
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function normalizeNamespace(value: string | undefined): string {
|
|
642
|
+
const namespace = value === undefined ? "default" : String(value).trim();
|
|
643
|
+
if (!namespace) throw new Error("namespace is required");
|
|
644
|
+
if (!/^[a-z0-9]{1,32}$/.test(namespace)) {
|
|
645
|
+
throw new Error("namespace must use lowercase letters and digits only (a-z0-9, max 32)");
|
|
646
|
+
}
|
|
647
|
+
return namespace;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function prefixedAdapter(adapter: StorageAdapter, prefix: string): StorageAdapter {
|
|
651
|
+
return {
|
|
652
|
+
get: (key) => adapter.get(`${prefix}${key}`),
|
|
653
|
+
set: (key, value) => adapter.set(`${prefix}${key}`, value),
|
|
654
|
+
remove: (key) => adapter.remove(`${prefix}${key}`),
|
|
655
|
+
keys: async (keyPrefix) => (await adapter.keys(`${prefix}${keyPrefix}`)).map((key) => key.slice(prefix.length)),
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function addCallbackTransport(url: string, transport: "same-tab" | "popup"): string {
|
|
660
|
+
const parsed = new URL(url, typeof window === "undefined" ? "https://localhost/" : window.location.href);
|
|
661
|
+
parsed.searchParams.set("callbackTransport", transport);
|
|
662
|
+
return parsed.toString();
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function normalizeAuthBase(value: string): string {
|
|
666
|
+
const parsed = new URL(String(value || DEFAULT_AUTH_BASE), typeof window === "undefined" ? DEFAULT_AUTH_BASE : window.location.href);
|
|
667
|
+
const pathname = parsed.pathname.replace(/\/+$/, "");
|
|
668
|
+
parsed.pathname = pathname.endsWith("/auth") ? `${pathname}/` : `${pathname}/auth/`;
|
|
669
|
+
parsed.search = "";
|
|
670
|
+
parsed.hash = "";
|
|
671
|
+
return parsed.toString();
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function apiBaseForAuthBase(authBase: string): string {
|
|
675
|
+
const parsed = new URL(authBase);
|
|
676
|
+
if (parsed.hostname === "myfield.one") return DEFAULT_API_BASE;
|
|
677
|
+
if (parsed.hostname === "dev.myfield.space") return "https://api-dev.myfield.space";
|
|
678
|
+
if (parsed.hostname === "staging.myfield.space") return "https://api-staging.myfield.space";
|
|
679
|
+
return `${parsed.protocol}//api.${parsed.host}`;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
function shouldUseSameTabAuth(): boolean {
|
|
683
|
+
if (typeof navigator === "undefined") return false;
|
|
684
|
+
const platform = navigator.platform || "";
|
|
685
|
+
const userAgent = navigator.userAgent || "";
|
|
686
|
+
return /iPad|iPhone|iPod/.test(userAgent) || (platform === "MacIntel" && navigator.maxTouchPoints > 1);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function formatError(error: unknown): string {
|
|
690
|
+
return error instanceof Error ? error.message : String(error);
|
|
691
|
+
}
|