@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.
@@ -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
+ };
@@ -12,6 +12,7 @@ import {
12
12
  emptyLwwMapDoc,
13
13
  encodePayloadDoc,
14
14
  lwwMapDocsEqual,
15
+ lwwMapLatestTs,
15
16
  lwwMapValues,
16
17
  LwwClock,
17
18
  mergeLwwMapDocs,
@@ -29,6 +30,14 @@ export type BucketTransportLike = {
29
30
  pullHead(wireObjectId: string): Promise<TransportHeadResult>;
30
31
  pullPayload(wireObjectId: string, versionId: string): Promise<TransportPayloadResult>;
31
32
  push(wireObjectId: string, plaintext: Uint8Array, expectedHeadVersionId: string | null): Promise<TransportPushResult>;
33
+ listHeads?(): Promise<Map<string, string>>;
34
+ };
35
+
36
+ export type ChangeSource = "local" | "remote";
37
+
38
+ export type SyncPassOptions = {
39
+ skipWireIds?: Iterable<string>;
40
+ resolveUnknown?: (wireObjectId: string, versionId: string) => Promise<string | null>;
32
41
  };
33
42
 
34
43
  export type BucketClientOptions = {
@@ -40,7 +49,10 @@ export type BucketClientOptions = {
40
49
  mergeStrategyFor?: (appObjectId: string) => MergeStrategy;
41
50
  maxCasAttempts?: number;
42
51
  pushDebounceMs?: number;
43
- onChange?: (appObjectId: string) => void;
52
+ autoSync?: boolean;
53
+ localOnlyObjectIds?: Iterable<string>;
54
+ validateRemote?: (appObjectId: string, doc: PayloadDoc) => void;
55
+ onChange?: (appObjectId: string, source: ChangeSource) => void;
44
56
  onSyncError?: (appObjectId: string | null, error: unknown) => void;
45
57
  };
46
58
 
@@ -66,15 +78,20 @@ export class BucketClient {
66
78
  private readonly maxCasAttempts: number;
67
79
  private readonly pushDebounceMs: number;
68
80
  private readonly maxEncodedObjectBytes = DEFAULT_MAX_ENCODED_OBJECT_BYTES;
69
- private readonly onChange?: (appObjectId: string) => void;
81
+ private readonly localOnly: Set<string>;
82
+ private readonly validateRemote?: (appObjectId: string, doc: PayloadDoc) => void;
83
+ private readonly onChange?: (appObjectId: string, source: ChangeSource) => void;
70
84
  private readonly onSyncError?: (appObjectId: string | null, error: unknown) => void;
71
85
  private readonly clock = new LwwClock();
72
86
  private readonly inFlightSync = new Map<string, Promise<boolean>>();
73
87
  private readonly objectLocks = new Map<string, Promise<void>>();
74
88
  private readonly pendingPushTimers = new Map<string, ReturnType<typeof setTimeout>>();
75
89
  private readonly watched = new Set<string>();
90
+ // Avoids re-downloading an unresolvable object until its head changes.
91
+ private readonly unresolved = new Map<string, string>();
76
92
  private triggerCleanup: (() => void) | null = null;
77
93
  private disposed = false;
94
+ private autoSync: boolean;
78
95
 
79
96
  constructor(options: BucketClientOptions) {
80
97
  this.transport = options.transport;
@@ -85,8 +102,11 @@ export class BucketClient {
85
102
  this.mergeStrategyFor = options.mergeStrategyFor || (() => ({ kind: "lww-map" }));
86
103
  this.maxCasAttempts = options.maxCasAttempts ?? DEFAULT_MAX_CAS_ATTEMPTS;
87
104
  this.pushDebounceMs = options.pushDebounceMs ?? DEFAULT_PUSH_DEBOUNCE_MS;
105
+ this.localOnly = new Set(options.localOnlyObjectIds || []);
106
+ this.validateRemote = options.validateRemote;
88
107
  this.onChange = options.onChange;
89
108
  this.onSyncError = options.onSyncError;
109
+ this.autoSync = options.autoSync ?? true;
90
110
  }
91
111
 
92
112
  // ---- local reads -------------------------------------------------------
@@ -103,6 +123,11 @@ export class BucketClient {
103
123
  return record.doc.data;
104
124
  }
105
125
 
126
+ async lastModified(appObjectId: string): Promise<number | null> {
127
+ const record = await this.readRecord(appObjectId);
128
+ return record && record.doc.t === "lww-map" ? lwwMapLatestTs(record.doc) : null;
129
+ }
130
+
106
131
  async knownObjectIds(): Promise<string[]> {
107
132
  const keys = await this.storage.keys(`${this.prefix}:obj:`);
108
133
  return keys.map((key) => decodeURIComponent(key.slice(`${this.prefix}:obj:`.length)));
@@ -142,7 +167,7 @@ export class BucketClient {
142
167
  dirty: true,
143
168
  });
144
169
  this.schedulePush(appObjectId);
145
- this.onChange?.(appObjectId);
170
+ this.onChange?.(appObjectId, "local");
146
171
  return lwwMapValues(nextDoc);
147
172
  });
148
173
  }
@@ -159,7 +184,7 @@ export class BucketClient {
159
184
  dirty: true,
160
185
  });
161
186
  this.schedulePush(appObjectId);
162
- this.onChange?.(appObjectId);
187
+ this.onChange?.(appObjectId, "local");
163
188
  });
164
189
  }
165
190
 
@@ -186,28 +211,49 @@ export class BucketClient {
186
211
  await this.syncObjects(ids);
187
212
  }
188
213
 
189
- async syncAuto(options?: { indexObjectId?: string }): Promise<void> {
190
- const indexObjectId = options?.indexObjectId;
191
- const dirtyIdsBefore = await this.dirtyObjectIds();
192
- const changedIds = new Set<string>();
193
- if (indexObjectId) {
194
- const before = await this.indexFields(indexObjectId);
195
- const beforeRecord = await this.readRecord(indexObjectId);
196
- const changed = await this.syncObject(indexObjectId);
197
- const after = await this.indexFields(indexObjectId);
198
- const afterRecord = await this.readRecord(indexObjectId);
199
- if (changed) {
200
- for (const id of diffIndexObjectIds(before, after)) changedIds.add(id);
201
- }
202
- if (!changed && beforeRecord && beforeRecord.remoteVersionId !== afterRecord?.remoteVersionId) {
203
- for (const id of Object.keys(after)) changedIds.add(id);
214
+ async syncPass(options: SyncPassOptions = {}): Promise<void> {
215
+ if (!this.transport.listHeads) throw new Error("transport does not list current heads");
216
+ const heads = await this.transport.listHeads();
217
+ for (const wireObjectId of options.skipWireIds || []) heads.delete(wireObjectId);
218
+ const known = new Map<string, string>();
219
+ const ids = new Set([...this.watched].filter((id) => !this.localOnly.has(id)));
220
+ for (const id of await this.knownObjectIds()) {
221
+ if (this.localOnly.has(id)) continue;
222
+ const record = await this.readRecord(id);
223
+ if (!record) continue;
224
+ const wireObjectId = await this.wireId(id);
225
+ known.set(wireObjectId, id);
226
+ const head = heads.get(wireObjectId);
227
+ if (record.dirty || head === undefined || head !== record.remoteVersionId) ids.add(id);
228
+ }
229
+ for (const [wireObjectId, versionId] of heads) {
230
+ if (known.has(wireObjectId) || !options.resolveUnknown || this.unresolved.get(wireObjectId) === versionId) continue;
231
+ try {
232
+ const id = await options.resolveUnknown(wireObjectId, versionId);
233
+ if (id && !this.localOnly.has(id) && (await this.wireId(id)) === wireObjectId) {
234
+ this.unresolved.delete(wireObjectId);
235
+ ids.add(id);
236
+ } else {
237
+ this.unresolved.set(wireObjectId, versionId);
238
+ }
239
+ } catch (error) {
240
+ this.onSyncError?.(null, error);
204
241
  }
205
242
  }
206
- const ids = new Set([...this.watched, ...dirtyIdsBefore, ...changedIds]);
207
- if (indexObjectId) ids.delete(indexObjectId);
208
243
  await this.syncObjects(ids);
209
244
  }
210
245
 
246
+ async pullDoc(wireObjectId: string, versionId: string): Promise<PayloadDoc | null> {
247
+ const payload = await this.transport.pullPayload(wireObjectId, versionId);
248
+ return payload.found ? decodePayloadDoc(payload.plaintext) : null;
249
+ }
250
+
251
+ async pullRemoteDoc(appObjectId: string): Promise<PayloadDoc | null> {
252
+ const wireObjectId = await this.wireId(appObjectId);
253
+ const head = await this.transport.pullHead(wireObjectId);
254
+ return head.found ? this.pullDoc(wireObjectId, head.versionId) : null;
255
+ }
256
+
211
257
  watch(appObjectIds: Iterable<string>): void {
212
258
  for (const id of appObjectIds) this.watched.add(id);
213
259
  }
@@ -215,10 +261,12 @@ export class BucketClient {
215
261
  // Sync-trigger model: launch (start itself) and a timer fallback.
216
262
  // Browser/app lifecycle triggers are owned by the app; post-write pushes
217
263
  // are scheduled by setFields/setData.
218
- start(options?: { intervalMs?: number; indexObjectId?: string }): void {
264
+ start(options: { intervalMs?: number; run: () => Promise<void> }): void {
219
265
  if (this.triggerCleanup || this.disposed) return;
220
- const kick = () => void this.syncAuto(options).catch((error) => this.onSyncError?.(null, error));
221
- const intervalMs = options?.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
266
+ this.autoSync = true;
267
+ const run = options.run;
268
+ const kick = () => void run().catch((error) => this.onSyncError?.(null, error));
269
+ const intervalMs = options.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
222
270
  const timer = intervalMs > 0 ? setInterval(kick, intervalMs) : null;
223
271
  this.triggerCleanup = () => {
224
272
  if (timer) clearInterval(timer);
@@ -227,6 +275,7 @@ export class BucketClient {
227
275
  }
228
276
 
229
277
  stop(): void {
278
+ this.autoSync = false;
230
279
  this.triggerCleanup?.();
231
280
  this.triggerCleanup = null;
232
281
  for (const timer of this.pendingPushTimers.values()) clearTimeout(timer);
@@ -253,7 +302,7 @@ export class BucketClient {
253
302
  // ---- internals ---------------------------------------------------------
254
303
 
255
304
  private schedulePush(appObjectId: string): void {
256
- if (this.disposed) return;
305
+ if (this.disposed || !this.autoSync || this.localOnly.has(appObjectId)) return;
257
306
  const existing = this.pendingPushTimers.get(appObjectId);
258
307
  if (existing) clearTimeout(existing);
259
308
  this.pendingPushTimers.set(
@@ -266,6 +315,7 @@ export class BucketClient {
266
315
  }
267
316
 
268
317
  private async performSync(appObjectId: string): Promise<boolean> {
318
+ if (this.localOnly.has(appObjectId)) return false;
269
319
  const wireObjectId = await this.wireId(appObjectId);
270
320
  let remoteChangedLocal = false;
271
321
  for (let attempt = 0; attempt < this.maxCasAttempts; attempt += 1) {
@@ -293,6 +343,7 @@ export class BucketClient {
293
343
  const payload = await this.transport.pullPayload(wireObjectId, head.versionId);
294
344
  if (!payload.found) return "retry";
295
345
  const remoteDoc = decodePayloadDoc(payload.plaintext);
346
+ this.validateRemote?.(appObjectId, remoteDoc);
296
347
  const merged = record ? this.merge(appObjectId, record.doc, remoteDoc) : remoteDoc;
297
348
  const localViewChanged = !record || !docsEqual(merged, record.doc);
298
349
  const remoteNeedsUpdate = !docsEqual(merged, remoteDoc);
@@ -303,7 +354,7 @@ export class BucketClient {
303
354
  await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: head.versionId, dirty: false });
304
355
  if (localViewChanged) {
305
356
  remoteChangedLocal = true;
306
- this.onChange?.(appObjectId);
357
+ this.onChange?.(appObjectId, "remote");
307
358
  }
308
359
  return remoteChangedLocal;
309
360
  }
@@ -313,7 +364,7 @@ export class BucketClient {
313
364
  await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: result.versionId, dirty: false });
314
365
  if (localViewChanged) {
315
366
  remoteChangedLocal = true;
316
- this.onChange?.(appObjectId);
367
+ this.onChange?.(appObjectId, "remote");
317
368
  }
318
369
  return remoteChangedLocal;
319
370
  }
@@ -342,17 +393,13 @@ export class BucketClient {
342
393
  async dirtyObjectIds(): Promise<string[]> {
343
394
  const ids: string[] = [];
344
395
  for (const id of await this.knownObjectIds()) {
396
+ if (this.localOnly.has(id)) continue;
345
397
  const record = await this.readRecord(id);
346
398
  if (record?.dirty) ids.push(id);
347
399
  }
348
400
  return ids;
349
401
  }
350
402
 
351
- private async indexFields(indexObjectId: string): Promise<Record<string, unknown>> {
352
- const record = await this.readRecord(indexObjectId);
353
- return record?.doc.t === "lww-map" ? lwwMapValues(record.doc) : {};
354
- }
355
-
356
403
  private async readRecord(appObjectId: string): Promise<LocalObjectRecord | null> {
357
404
  const record = await this.storage.get<LocalObjectRecord>(this.recordKey(appObjectId));
358
405
  if (!record || record.v !== 1 || !record.doc) return null;
@@ -377,7 +424,3 @@ function docsEqual(a: PayloadDoc, b: PayloadDoc): boolean {
377
424
  return false;
378
425
  }
379
426
 
380
- function diffIndexObjectIds(before: Record<string, unknown>, after: Record<string, unknown>): string[] {
381
- const ids = new Set([...Object.keys(before), ...Object.keys(after)]);
382
- return [...ids].filter((id) => JSON.stringify(before[id]) !== JSON.stringify(after[id]));
383
- }