@abraca/dabra 2.35.0 → 2.36.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/dist/index.d.ts CHANGED
@@ -2707,6 +2707,23 @@ declare class AbracadabraBaseProvider extends EventEmitter {
2707
2707
  authorizedScope: AuthorizedScope | undefined;
2708
2708
  manageSocket: boolean;
2709
2709
  private _isAttached;
2710
+ /**
2711
+ * Bounded retry of a multiplexed child's INITIAL subscribe handshake after a
2712
+ * *transient* server denial. On a clustered server a just-created doc's row
2713
+ * (or its permission cascade) can be briefly invisible on the replica this
2714
+ * socket landed on; a dropped "send AUTH for this document first" ordering
2715
+ * yields the same denial. Before this, a child gave up permanently on the
2716
+ * first denial and was left with a blank body until a full reload re-ran the
2717
+ * handshake — exactly the "open a freshly-created doc, see only the title,
2718
+ * blinking dot, never syncs until reload" report. We instead replay the
2719
+ * subscribe a few times with backoff; the instant the server catches up the
2720
+ * child authenticates and syncs, no reconnect. Only ever fires for the
2721
+ * INITIAL subscribe (never a mid-session write denial) and is bounded, so a
2722
+ * genuinely forbidden/absent doc still settles into give-up, just later.
2723
+ */
2724
+ private static readonly MAX_RESUBSCRIBE_ATTEMPTS;
2725
+ private _resubscribeAttempts;
2726
+ private _resubscribeTimer;
2710
2727
  intervals: {
2711
2728
  forceSync: ReturnType<typeof setInterval> | null;
2712
2729
  };
@@ -2806,6 +2823,20 @@ declare class AbracadabraBaseProvider extends EventEmitter {
2806
2823
  detach(): void;
2807
2824
  attach(): void;
2808
2825
  permissionDeniedHandler(reason: string): void;
2826
+ /**
2827
+ * Whether a permission-denied reason reflects a *transient* server condition
2828
+ * a retry can clear (a freshly-created doc not yet visible on this replica, or
2829
+ * a dropped subscribe-ordering) rather than a permanent authorization failure.
2830
+ */
2831
+ private static isTransientSubscribeDenial;
2832
+ /**
2833
+ * Schedule one backed-off replay of the initial subscribe handshake. A single
2834
+ * timer is in flight at a time; each denial that slips past the guard above
2835
+ * arms the next attempt until {@link MAX_RESUBSCRIBE_ATTEMPTS} is reached.
2836
+ */
2837
+ private scheduleResubscribe;
2838
+ /** Cancel any pending resubscribe and reset the attempt budget. */
2839
+ private clearResubscribe;
2809
2840
  authenticatedHandler(scope: string): void;
2810
2841
  setAwarenessField(key: string, value: any): void;
2811
2842
  }
@@ -3263,6 +3294,16 @@ declare class E2EAbracadabraProvider extends AbracadabraProvider {
3263
3294
  /** Quiescence debounce: reset on every update, fires the actual compaction. */
3264
3295
  private compactionDebounceTimer;
3265
3296
  private destroyed;
3297
+ /**
3298
+ * Plaintext local updates produced while this doc is not yet authenticated
3299
+ * on the connection. Unlike the plaintext provider, E2E does not convey
3300
+ * local state via SyncStep2 (it ships discrete encrypted update frames keyed
3301
+ * by server-assigned seq), so a pre-auth update that loses the AUTH race and
3302
+ * gets "not subscribed"-rejected would be lost. We queue them here and flush
3303
+ * (encrypt + send) once `authenticatedHandler` confirms the doc is
3304
+ * subscribed. Survives reconnects (only cleared on flush or destroy).
3305
+ */
3306
+ private _pendingPreAuthUpdates;
3266
3307
  constructor(configuration: E2EAbracadabraProviderConfiguration);
3267
3308
  /** Fetch the doc key from the server (requires WebAuthn if not cached). */
3268
3309
  private ensureDocKey;
@@ -3272,6 +3313,11 @@ declare class E2EAbracadabraProvider extends AbracadabraProvider {
3272
3313
  private _decryptAndApply;
3273
3314
  /** Encrypt local updates before sending over WebSocket. */
3274
3315
  documentUpdateHandler(update: Uint8Array, origin: unknown): void;
3316
+ /**
3317
+ * Flush updates buffered while unauthenticated once the server confirms the
3318
+ * doc is subscribed, then resume normal live sends.
3319
+ */
3320
+ authenticatedHandler(scope: string): void;
3275
3321
  private _encryptAndSend;
3276
3322
  /**
3277
3323
  * Force an immediate compaction attempt, bypassing the threshold and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/dabra",
3
- "version": "2.35.0",
3
+ "version": "2.36.0",
4
4
  "description": "abracadabra provider",
5
5
  "keywords": [
6
6
  "abracadabra",
@@ -41,7 +41,7 @@
41
41
  "yjs": "^13.6.8"
42
42
  },
43
43
  "devDependencies": {
44
- "@abraca/schema": "2.35.0"
44
+ "@abraca/schema": "2.36.0"
45
45
  },
46
46
  "scripts": {
47
47
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -35,8 +35,10 @@ import type {
35
35
  onStatusParameters,
36
36
  onSyncedParameters,
37
37
  onUnsyncedChangesParameters,
38
- WebSocketStatus,
39
38
  } from "./types.ts";
39
+ // Value import (not `import type`): `WebSocketStatus` is a runtime string enum
40
+ // read in scheduleResubscribe's connection check, not just a type annotation.
41
+ import { WebSocketStatus } from "./types.ts";
40
42
 
41
43
  export type AbracadabraBaseProviderConfiguration = Required<
42
44
  Pick<CompleteAbracadabraBaseProviderConfiguration, "name">
@@ -178,6 +180,24 @@ export class AbracadabraBaseProvider extends EventEmitter {
178
180
 
179
181
  private _isAttached = false;
180
182
 
183
+ /**
184
+ * Bounded retry of a multiplexed child's INITIAL subscribe handshake after a
185
+ * *transient* server denial. On a clustered server a just-created doc's row
186
+ * (or its permission cascade) can be briefly invisible on the replica this
187
+ * socket landed on; a dropped "send AUTH for this document first" ordering
188
+ * yields the same denial. Before this, a child gave up permanently on the
189
+ * first denial and was left with a blank body until a full reload re-ran the
190
+ * handshake — exactly the "open a freshly-created doc, see only the title,
191
+ * blinking dot, never syncs until reload" report. We instead replay the
192
+ * subscribe a few times with backoff; the instant the server catches up the
193
+ * child authenticates and syncs, no reconnect. Only ever fires for the
194
+ * INITIAL subscribe (never a mid-session write denial) and is bounded, so a
195
+ * genuinely forbidden/absent doc still settles into give-up, just later.
196
+ */
197
+ private static readonly MAX_RESUBSCRIBE_ATTEMPTS = 6;
198
+ private _resubscribeAttempts = 0;
199
+ private _resubscribeTimer: ReturnType<typeof setTimeout> | null = null;
200
+
181
201
  intervals: { forceSync: ReturnType<typeof setInterval> | null } = {
182
202
  forceSync: null,
183
203
  };
@@ -414,11 +434,33 @@ export class AbracadabraBaseProvider extends EventEmitter {
414
434
  return;
415
435
  }
416
436
 
437
+ // Don't push live updates over a connection that hasn't authenticated this
438
+ // document yet. On the shared multiplexed socket, onOpen() does
439
+ // `await sendToken()` before the doc's AUTH frame actually goes out; an edit
440
+ // firing in that async window would race ahead of the AUTH frame and the
441
+ // server rejects it with "not subscribed: send AUTH for this document
442
+ // first". State is NOT lost: subclasses persist to the offline store before
443
+ // calling super (and re-flush pending updates on `synced`), and the
444
+ // post-AUTH SyncStep1/2 handshake conveys all local state regardless. So
445
+ // skipping the live wire-send here is safe — it only closes the race.
446
+ if (!this.isAuthenticated) {
447
+ return;
448
+ }
449
+
417
450
  this.incrementUnsyncedChanges();
418
451
  this.send(UpdateMessage, { update, documentName: this.configuration.name });
419
452
  }
420
453
 
421
454
  awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {
455
+ // Same AUTH-ordering guard as documentUpdateHandler. Awareness churn
456
+ // (cursor / presence / focus) during the connect AUTH window must not race
457
+ // ahead of the doc's AUTH frame. Awareness is ephemeral and re-sent in full
458
+ // by startSync() immediately after AUTH plus on the next local change, so
459
+ // dropping pre-auth awareness frames loses nothing.
460
+ if (!this.isAuthenticated) {
461
+ return;
462
+ }
463
+
422
464
  const changedClients = added.concat(updated).concat(removed);
423
465
 
424
466
  this.send(AwarenessMessage, {
@@ -618,6 +660,9 @@ export class AbracadabraBaseProvider extends EventEmitter {
618
660
  // permissionDeniedHandler can correctly identify a fresh-connection
619
661
  // denial as a config error.
620
662
  this._hasEverAuthenticated = false;
663
+ // The socket's own reconnect re-runs onOpen → subscribe for every doc, so
664
+ // any in-flight initial-subscribe retry from this lifetime is moot.
665
+ this.clearResubscribe();
621
666
 
622
667
  // update awareness (all users except local left)
623
668
  if (this.awareness) {
@@ -692,6 +737,7 @@ export class AbracadabraBaseProvider extends EventEmitter {
692
737
  this.configuration.websocketProvider.detach(this);
693
738
 
694
739
  this._isAttached = false;
740
+ this.clearResubscribe();
695
741
  }
696
742
 
697
743
  attach() {
@@ -764,12 +810,92 @@ export class AbracadabraBaseProvider extends EventEmitter {
764
810
  }
765
811
  catch { /* WS may already be torn down — best effort */ }
766
812
  }
813
+
814
+ // Transient-denial recovery (see _resubscribeAttempts doc). Fires only for
815
+ // a multiplexed child (shared socket; the root is handled above) that has
816
+ // NOT yet completed its initial sync, and only for denials whose reason is
817
+ // transient — "document not found" (a just-created doc whose row/permission
818
+ // is briefly invisible on the replica this socket hit) or "not subscribed"
819
+ // (a dropped AUTH-ordering). We deliberately do NOT key off
820
+ // `_hasEverAuthenticated`: the server sends AUTHENTICATED *before* it runs
821
+ // the initial sync, so a not-found denial lands after that flag is already
822
+ // set. `!isSynced` is the true "never got my content" signal and also
823
+ // excludes mid-session write denials (those docs are already synced).
824
+ // Permanent denials ("permission denied"/"write permission denied") are
825
+ // NOT matched, so a genuinely forbidden doc still gives up immediately.
826
+ if (
827
+ !this.manageSocket &&
828
+ !this.isSynced &&
829
+ this._isAttached &&
830
+ this._resubscribeAttempts < AbracadabraBaseProvider.MAX_RESUBSCRIBE_ATTEMPTS &&
831
+ AbracadabraBaseProvider.isTransientSubscribeDenial(reason)
832
+ ) {
833
+ this.scheduleResubscribe();
834
+ }
835
+ }
836
+
837
+ /**
838
+ * Whether a permission-denied reason reflects a *transient* server condition
839
+ * a retry can clear (a freshly-created doc not yet visible on this replica, or
840
+ * a dropped subscribe-ordering) rather than a permanent authorization failure.
841
+ */
842
+ private static isTransientSubscribeDenial(reason: string): boolean {
843
+ const r = reason.toLowerCase();
844
+ return r.includes("not found") || r.includes("not subscribed");
845
+ }
846
+
847
+ /**
848
+ * Schedule one backed-off replay of the initial subscribe handshake. A single
849
+ * timer is in flight at a time; each denial that slips past the guard above
850
+ * arms the next attempt until {@link MAX_RESUBSCRIBE_ATTEMPTS} is reached.
851
+ */
852
+ private scheduleResubscribe() {
853
+ if (this._resubscribeTimer) return;
854
+ const attempt = this._resubscribeAttempts++;
855
+ // 250, 500, 1000, 2000, 4000, 4000 ms — recovers within ~750ms for a
856
+ // typical sub-second replica lag, ~11s total before final give-up.
857
+ const delay = Math.min(4000, 250 * 2 ** attempt);
858
+ this._resubscribeTimer = setTimeout(() => {
859
+ this._resubscribeTimer = null;
860
+ // Bail if anything changed under us: detached, already recovered, or the
861
+ // socket dropped (its reconnect re-runs onOpen for every doc anyway).
862
+ // `isSynced` — not the auth flags — is the success signal: the server
863
+ // sends AUTHENTICATED *before* the initial-sync attempt, so a not-found
864
+ // denial leaves isAuthenticated/_hasEverAuthenticated set yet unsynced;
865
+ // bailing on those would (and did) skip the very retry we scheduled.
866
+ if (
867
+ !this._isAttached ||
868
+ this.isSynced ||
869
+ this.connectionStatus !== WebSocketStatus.Connected
870
+ ) {
871
+ return;
872
+ }
873
+ // Replay onOpen's subscribe: re-send AUTH (server re-runs subscribe_doc,
874
+ // now that the doc/permission may be visible) then SyncStep1.
875
+ void this.sendToken()
876
+ .then(() => {
877
+ if (this._isAttached && !this.isAuthenticated) this.startSync();
878
+ })
879
+ .catch(() => { /* a fresh denial re-enters permissionDeniedHandler */ });
880
+ }, delay);
881
+ }
882
+
883
+ /** Cancel any pending resubscribe and reset the attempt budget. */
884
+ private clearResubscribe() {
885
+ if (this._resubscribeTimer) {
886
+ clearTimeout(this._resubscribeTimer);
887
+ this._resubscribeTimer = null;
888
+ }
889
+ this._resubscribeAttempts = 0;
767
890
  }
768
891
 
769
892
  authenticatedHandler(scope: string) {
770
893
  this.isAuthenticated = true;
771
894
  this._hasEverAuthenticated = true;
772
895
  this.authorizedScope = scope as AuthorizedScope;
896
+ // Initial subscribe succeeded (possibly via a resubscribe retry) — stop
897
+ // retrying and restore the budget for a future socket lifetime.
898
+ this.clearResubscribe();
773
899
 
774
900
  this.emit("authenticated", { scope });
775
901
  }
@@ -110,6 +110,16 @@ export class E2EAbracadabraProvider extends AbracadabraProvider {
110
110
  /** Quiescence debounce: reset on every update, fires the actual compaction. */
111
111
  private compactionDebounceTimer: ReturnType<typeof setTimeout> | null = null;
112
112
  private destroyed = false;
113
+ /**
114
+ * Plaintext local updates produced while this doc is not yet authenticated
115
+ * on the connection. Unlike the plaintext provider, E2E does not convey
116
+ * local state via SyncStep2 (it ships discrete encrypted update frames keyed
117
+ * by server-assigned seq), so a pre-auth update that loses the AUTH race and
118
+ * gets "not subscribed"-rejected would be lost. We queue them here and flush
119
+ * (encrypt + send) once `authenticatedHandler` confirms the doc is
120
+ * subscribed. Survives reconnects (only cleared on flush or destroy).
121
+ */
122
+ private _pendingPreAuthUpdates: Uint8Array[] = [];
113
123
 
114
124
  constructor(configuration: E2EAbracadabraProviderConfiguration) {
115
125
  // Disable the parent's offline store — E2E uses its own encrypted store.
@@ -245,12 +255,39 @@ export class E2EAbracadabraProvider extends AbracadabraProvider {
245
255
  /** Encrypt local updates before sending over WebSocket. */
246
256
  override documentUpdateHandler(update: Uint8Array, origin: unknown): void {
247
257
  if (origin === this) return;
258
+
259
+ // AUTH-ordering guard (see _pendingPreAuthUpdates): until the doc is
260
+ // authenticated on the connection, an encrypted update would race ahead
261
+ // of the AUTH frame on the shared multiplexed socket and be rejected with
262
+ // "not subscribed". Queue it and flush on authenticatedHandler instead of
263
+ // racing (and losing) it.
264
+ if (!this.isAuthenticated) {
265
+ this._pendingPreAuthUpdates.push(update);
266
+ return;
267
+ }
268
+
248
269
  // Don't call super (which would send plaintext); encrypt first
249
270
  this._encryptAndSend(update).catch((e) => {
250
271
  console.error("[E2EAbracadabraProvider] failed to encrypt update:", e);
251
272
  });
252
273
  }
253
274
 
275
+ /**
276
+ * Flush updates buffered while unauthenticated once the server confirms the
277
+ * doc is subscribed, then resume normal live sends.
278
+ */
279
+ override authenticatedHandler(scope: string): void {
280
+ super.authenticatedHandler(scope);
281
+ if (this._pendingPreAuthUpdates.length === 0) return;
282
+ const pending = this._pendingPreAuthUpdates;
283
+ this._pendingPreAuthUpdates = [];
284
+ for (const update of pending) {
285
+ this._encryptAndSend(update).catch((e) => {
286
+ console.error("[E2EAbracadabraProvider] failed to flush pre-auth update:", e);
287
+ });
288
+ }
289
+ }
290
+
254
291
  private async _encryptAndSend(update: Uint8Array): Promise<void> {
255
292
  const key = await this.ensureDocKey();
256
293
  if (!key) {