@nebulr-group/bridge-svelte 0.9.0-beta.4 → 0.9.0-beta.5

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.
@@ -176,8 +176,8 @@ export function startBridgeRuntime(options = {}) {
176
176
  // of parking. A signed-out session has nothing to refresh. Loop safety:
177
177
  // the refreshed token lands in the tokenStore subscription below, whose
178
178
  // reauthorize() is a no-op while that episode is still connecting, and
179
- // the reconnect it produces is flagged self-induced so setOnOpen does not
180
- // refresh a second time.
179
+ // the reconcile after the reconnect (TBP-700) mints once more and stops
180
+ // there — a token that changes nothing does not replace the socket.
181
181
  refreshAuthToken: options.realtime?.refreshAuthToken ??
182
182
  (async () => {
183
183
  if (!_currentAuthToken)
@@ -191,11 +191,10 @@ export function startBridgeRuntime(options = {}) {
191
191
  }
192
192
  }),
193
193
  });
194
- let _connectedOnce = false;
195
- // Set just before we call _realtime.reauthorize() so the resulting
196
- // reconnect's setOnOpen handler knows the token is already fresh and skips
197
- // its proactive refresh — see the loop note in setOnOpen below.
198
- let _reauthInFlight = false;
194
+ // TBP-700 — bookkeeping for reconcileUserState() below.
195
+ let _reconciling = 0;
196
+ let _reconcileSawChange = false;
197
+ let _reconcileSwapsInARow = 0;
199
198
  // TBP-660 — catch up after ANY reconnect, including the one our own
200
199
  // reauthorize() causes. AppSync Events has no replay, so a push published
201
200
  // while the socket is being replaced is gone for good — and a plan change
@@ -240,11 +239,12 @@ export function startBridgeRuntime(options = {}) {
240
239
  return;
241
240
  const data = (await res.json());
242
241
  // Stopped, or the session changed while this was in flight: the answer
243
- // describes a session we no longer have. A token change reauthorizes,
244
- // and that reconnect catches up again with the right token.
245
- if (_realtime !== rt || _currentAuthToken !== token)
242
+ // describes a session we no longer have. A new token for the SAME user,
243
+ // workspace and app is not a new session — the reconcile below rotates
244
+ // the token on every open, concurrently with this read (TBP-700).
245
+ if (_realtime !== rt || !sameSession(token, _currentAuthToken))
246
246
  return;
247
- const { planChanged, entitlementsChanged } = applyCatchUpSnapshot(data);
247
+ const { planChanged, entitlementsChanged, initial } = applyCatchUpSnapshot(data);
248
248
  if (entitlementsChanged && data?.tenant?.entitlements) {
249
249
  // Keep auth-core's copy (what flag targeting reads) in step too.
250
250
  try {
@@ -254,6 +254,14 @@ export function startBridgeRuntime(options = {}) {
254
254
  }
255
255
  // TBP-654 — a recovered change must reach the route guard exactly like
256
256
  // the push it replaces would have. Nothing changed → nothing to redo.
257
+ //
258
+ // TBP-700 — and filling empty stores for the first time recovers no
259
+ // change: nothing was decided against a plan this page never knew. It
260
+ // used to count as a plan change, which refreshed the token and swapped
261
+ // the socket right after every first connect — the window a role change
262
+ // was lost in on stage. The access token is reconciled below instead.
263
+ if (initial)
264
+ return;
257
265
  if (planChanged)
258
266
  authorizationChanged('subscription.plan_changed');
259
267
  else if (entitlementsChanged)
@@ -335,7 +343,7 @@ export function startBridgeRuntime(options = {}) {
335
343
  const data = (await res.json());
336
344
  // Stopped, or the session changed while this was in flight: the
337
345
  // answer describes a workspace we no longer have.
338
- if (_realtime !== rt || _currentAuthToken !== token)
346
+ if (_realtime !== rt || !sameSession(token, _currentAuthToken))
339
347
  return;
340
348
  if (quotas.getAll().get(metric) !== before)
341
349
  return; // a push won the race
@@ -348,6 +356,57 @@ export function startBridgeRuntime(options = {}) {
348
356
  }
349
357
  }));
350
358
  };
359
+ // TBP-700 — the same repair for the user's own state: role, privileges,
360
+ // anything that bumps the server's tokenVersion and publishes
361
+ // `user.state_changed`. That push is lost exactly like the others when it
362
+ // is published while the socket is being replaced, and before this nothing
363
+ // recovered it: the session snapshot's `user` is read from the token being
364
+ // presented, and a reconnect our own reauthorize() caused skipped the token
365
+ // refresh (the TBP-644 loop guard). On stage a role change landed in that
366
+ // window in 4 of 4 runs once the first connect started swapping its socket
367
+ // (TBP-686), and the user kept the old role until a reload.
368
+ //
369
+ // The server's current tokenVersion and claims are only available by
370
+ // minting: the refresh endpoint reads them from the database, uncached. So
371
+ // every connect and reconnect ends with ONE refresh, and the token that
372
+ // comes back is compared with the one we had:
373
+ // - same authority (only iat/exp/jti moved): nothing was missed, and the
374
+ // socket that was just subscribed stays — no swap, so no loop;
375
+ // - anything else (tv, role, plan…): that IS the missed change. It is
376
+ // handled like the push would have been — the route guard re-checks and
377
+ // the socket is re-authorized with the new token — and the reconnect
378
+ // reconciles again, which then finds nothing new.
379
+ //
380
+ // `fresh: true` (auth-core, TBP-700) keeps this from joining a
381
+ // refresh that started before the channels were live, whose token could
382
+ // predate the very change we are looking for. An older auth-core ignores
383
+ // the option and joins it — best effort, as before.
384
+ const reconcileUserState = async () => {
385
+ if (_realtime !== rt || !_currentAuthToken)
386
+ return; // signed out: no user state
387
+ let auth;
388
+ try {
389
+ auth = getBridgeAuth();
390
+ }
391
+ catch {
392
+ return; // BridgeAuth not constructed — nothing to refresh with.
393
+ }
394
+ _reconciling += 1;
395
+ _reconcileSawChange = false;
396
+ try {
397
+ const refresh = auth.refreshTokens;
398
+ await refresh.call(auth, { fresh: true });
399
+ }
400
+ catch {
401
+ // Best-effort: the TOKEN_VERSION_STALE retry in bridgeAuthFetch and the
402
+ // next reconnect are the fallbacks.
403
+ }
404
+ finally {
405
+ _reconciling -= 1;
406
+ if (!_reconcileSawChange)
407
+ _reconcileSwapsInARow = 0;
408
+ }
409
+ };
351
410
  const requestCatchUp = () => {
352
411
  if (!_currentAuthToken)
353
412
  return; // signed out: no tenant or user scope to fetch
@@ -356,9 +415,9 @@ export function startBridgeRuntime(options = {}) {
356
415
  return;
357
416
  }
358
417
  _catchUpInFlight = true;
359
- // Both repairs ride the one in-flight/queued gate, so an open storm still
360
- // costs one round of requests, and neither can starve the other.
361
- void Promise.all([catchUpSessionSnapshot(), catchUpQuotaSnapshots()]).catch(() => {
418
+ // Every repair rides the one in-flight/queued gate, so an open storm still
419
+ // costs one round of requests, and none can starve the others.
420
+ void Promise.all([catchUpSessionSnapshot(), catchUpQuotaSnapshots(), reconcileUserState()]).catch(() => {
362
421
  // Both halves are already best-effort internally; this is the backstop
363
422
  // that keeps a repair failure from surfacing as an unhandled rejection
364
423
  // in the consuming app. `.finally` below still drains the queue.
@@ -370,41 +429,29 @@ export function startBridgeRuntime(options = {}) {
370
429
  }
371
430
  });
372
431
  };
432
+ // TBP-700 — when to catch up. Everything above only works if it reads the
433
+ // server AFTER every channel is live: anything published before that is
434
+ // already in the database and the read sees it, anything after arrives on
435
+ // the socket. `open` fires on the FIRST accepted subscription, with the user
436
+ // channel possibly still pending, so an auth-core that can say "all
437
+ // subscribed" is asked; an older one falls back to `open`.
438
+ //
439
+ // One trigger for the initial connect, a genuine reconnect and the one our
440
+ // own reauthorize() causes alike: losing pushes is a property of the socket
441
+ // swap, whoever caused it (TBP-660), and the first connect is where the
442
+ // snapshot push always loses its race (TBP-686). `requestCatchUp` returns
443
+ // early when signed out and coalesces concurrent calls.
444
+ const realtimeWithSubscribed = _realtime;
445
+ const catchUpOnSubscribed = typeof realtimeWithSubscribed.setOnSubscribed === 'function';
446
+ if (catchUpOnSubscribed)
447
+ realtimeWithSubscribed.setOnSubscribed(() => requestCatchUp());
373
448
  _realtime.setOnOpen(() => {
374
449
  _setRealtimeStatus('open');
375
- // On reconnect (not initial connect), proactively refresh tokens.
376
- // If the WS was down when tokenVersion was bumped on the server, the
377
- // client missed the user.state_changed broadcast. Refreshing here
378
- // syncs tokens before the first post-reconnect request can fail with
379
- // TOKEN_VERSION_STALE.
380
- //
381
- // EXCEPT when this reconnect was caused by our OWN reauthorize() below
382
- // (a token-only refresh). In that case the token is already current, so
383
- // refreshing again would mint yet another JWT, which the tokenStore
384
- // subscription would see as a change and reauthorize() again → reconnect
385
- // → setOnOpen → refresh → … an unbounded loop that hammers /auth/token
386
- // (observed ~32 cycles/sec, jamming the page's main thread and stalling
387
- // every downstream wait). Only genuine, externally-triggered reconnects
388
- // (network blips, server restarts) should trigger the catch-up refresh.
389
- const causedByReauthorize = _reauthInFlight;
390
- _reauthInFlight = false;
391
- if (_connectedOnce && !causedByReauthorize) {
392
- getBridgeAuth().refreshTokens().catch(() => { });
393
- }
394
- // TBP-660 — the TOKEN refresh above is skipped for a self-induced
395
- // reconnect; the STATE catch-up is not. Losing pushes is a property of
396
- // the socket swap, whoever caused it, and the catch-up cannot loop.
397
- //
398
- // TBP-686 — and it runs on the FIRST connect too. It used to be gated on
399
- // `_connectedOnce`, which read as "only repair a reconnect" — but the
400
- // first connect is exactly where the snapshot goes missing: the server
401
- // publishes it fire-and-forget during authorize, before the subscription
402
- // is live, so it loses the race and there is nothing to replay. The result
403
- // was a signed-in page with a null workspace id, name and branding for the
404
- // whole session. `requestCatchUp` already returns early when signed out
405
- // and coalesces concurrent calls, so this costs one request per session.
406
- requestCatchUp();
407
- _connectedOnce = true;
450
+ // No token refresh here any more (TBP-700): the reconcile in
451
+ // requestCatchUp mints on EVERY open, the self-induced ones included, and
452
+ // cannot loop — see reconcileUserState.
453
+ if (!catchUpOnSubscribed)
454
+ requestCatchUp();
408
455
  for (const fn of _onOpenSubs) {
409
456
  try {
410
457
  fn();
@@ -437,10 +484,6 @@ export function startBridgeRuntime(options = {}) {
437
484
  // open/close/degraded mirrors above keep `realtimeStatus` working there).
438
485
  _realtime.setOnStatusChange?.((status) => {
439
486
  _setRealtimeStatusDetail(status);
440
- // A parked client never opens, so a reauthorize that ended in a refusal
441
- // must not leave the self-induced flag set for the next genuine reconnect.
442
- if (status.state === 'unauthorized')
443
- _reauthInFlight = false;
444
487
  for (const fn of _onStatusSubs) {
445
488
  try {
446
489
  fn(status);
@@ -560,10 +603,7 @@ export function startBridgeRuntime(options = {}) {
560
603
  // (none → A) and sign-out (A → none). Keying this on rotation only meant a
561
604
  // session that signed in after page load kept the anonymous connection —
562
605
  // or stayed parked after a refusal — until something else reconnected it.
563
- // Flagged self-induced so setOnOpen skips its catch-up refresh (see the
564
- // loop note there): the token we reconnect with is already current.
565
606
  const reauthorizeForTokenChange = () => {
566
- _reauthInFlight = true;
567
607
  void _realtime.reauthorize();
568
608
  };
569
609
  // `subscribe` emits the current value synchronously, before `start()` below.
@@ -572,7 +612,30 @@ export function startBridgeRuntime(options = {}) {
572
612
  _unsubscribeAuth = tokenStore.subscribe((tokens) => {
573
613
  const prevAuthToken = _currentAuthToken;
574
614
  _currentAuthToken = tokens?.accessToken ?? undefined;
575
- const tokenChanged = _tokenSubscriptionLive && prevAuthToken !== _currentAuthToken;
615
+ let tokenChanged = _tokenSubscriptionLive && prevAuthToken !== _currentAuthToken;
616
+ let reauthorize = tokenChanged;
617
+ // TBP-700 — the token minted by the post-(re)connect reconcile.
618
+ if (tokenChanged && _reconciling > 0) {
619
+ if (_realtime.getState?.() === 'open' && sameAuthorization(prevAuthToken, _currentAuthToken)) {
620
+ // Only its timing moved: nothing was missed, every verdict taken with
621
+ // the old token stands, and the socket that was just subscribed has
622
+ // exactly this authority. Replacing it would open the very window
623
+ // this repair exists for — and loop.
624
+ tokenChanged = false;
625
+ reauthorize = false;
626
+ }
627
+ else {
628
+ // The server moved on while we were not listening: the lost
629
+ // `user.state_changed`, recovered. Re-authorize like the push would
630
+ // have — bounded, so a claim that differs on every mint cannot turn
631
+ // this into a reconnect loop.
632
+ _reconcileSawChange = true;
633
+ if (_reconcileSwapsInARow >= MAX_RECONCILE_SWAPS)
634
+ reauthorize = false;
635
+ else
636
+ _reconcileSwapsInARow += 1;
637
+ }
638
+ }
576
639
  // TBP-654 + TBP-653 — a new token (sign-in, refresh after a plan change,
577
640
  // sign-out) invalidates every verdict taken with the old one, and the
578
641
  // current route is re-evaluated: a signed-out session on a protected page
@@ -616,7 +679,7 @@ export function startBridgeRuntime(options = {}) {
616
679
  // setUserId is a no-op when the user is unchanged (token-only refresh),
617
680
  // and a setter-driven reconnect waits out a backoff and cannot lift a
618
681
  // parked refusal — so reauthorize explicitly on every value change.
619
- if (tokenChanged)
682
+ if (reauthorize)
620
683
  reauthorizeForTokenChange();
621
684
  });
622
685
  _tokenSubscriptionLive = true;
@@ -739,6 +802,48 @@ export function __resetBridgeRuntime() {
739
802
  _realtime = undefined;
740
803
  }
741
804
  // ── helpers ─────────────────────────────────────────────────────────────────
805
+ /**
806
+ * TBP-700 — how many reconcile-driven socket replacements may follow one
807
+ * another before the reconcile stops replacing the socket (it still adopts the
808
+ * token). A genuine missed change costs one; a second is a change published
809
+ * during that swap. More than a few in a row means a claim differs on every
810
+ * mint, and replacing the socket forever would be the TBP-644 loop again.
811
+ */
812
+ const MAX_RECONCILE_SWAPS = 3;
813
+ /** Claims that differ on every mint without meaning anything changed. */
814
+ const PER_MINT_CLAIMS = new Set(['iat', 'exp', 'nbf', 'jti', 'auth_time']);
815
+ /** Same user, workspace and app — the scope a catch-up read belongs to. */
816
+ function sameSession(a, b) {
817
+ if (!a || !b)
818
+ return false;
819
+ if (a === b)
820
+ return true;
821
+ const ca = decodeJwtPayload(a);
822
+ const cb = decodeJwtPayload(b);
823
+ if (!ca || !cb)
824
+ return false;
825
+ return ca.sub === cb.sub && ca.tid === cb.tid && ca.aid === cb.aid;
826
+ }
827
+ /**
828
+ * TBP-700 — two tokens carry the same authority: every claim is equal except
829
+ * the per-mint ones. Unreadable tokens are never the same.
830
+ */
831
+ function sameAuthorization(a, b) {
832
+ if (!a || !b)
833
+ return false;
834
+ const ca = decodeJwtPayload(a);
835
+ const cb = decodeJwtPayload(b);
836
+ if (!ca || !cb)
837
+ return false;
838
+ const keys = new Set([...Object.keys(ca), ...Object.keys(cb)]);
839
+ for (const k of keys) {
840
+ if (PER_MINT_CLAIMS.has(k))
841
+ continue;
842
+ if (JSON.stringify(ca[k]) !== JSON.stringify(cb[k]))
843
+ return false;
844
+ }
845
+ return true;
846
+ }
742
847
  /** Decode a JWT payload without signature verification (client context only). */
743
848
  function decodeJwtPayload(token) {
744
849
  try {
@@ -104,6 +104,13 @@ export declare function applyEntitlementsChanged(msg: {
104
104
  export declare function applyCatchUpSnapshot(data: SessionSnapshotData): {
105
105
  planChanged: boolean;
106
106
  entitlementsChanged: boolean;
107
+ /**
108
+ * TBP-700 — the tenant stores were empty: this filled them for the first
109
+ * time rather than changing anything the page had already seen. The
110
+ * `*Changed` flags still say whether the values moved, so a caller can seed
111
+ * other copies; a first fill is not a recovered change.
112
+ */
113
+ initial: boolean;
107
114
  };
108
115
  /** Test-only: reset every snapshot store to `null`. Vitest hook. */
109
116
  export declare function __resetSnapshotStores(): void;
@@ -104,6 +104,7 @@ export function applyCatchUpSnapshot(data) {
104
104
  const subAfter = get(_tenantSubscription);
105
105
  const entAfter = get(_tenantEntitlements);
106
106
  return {
107
+ initial: subBefore === null && entBefore === null,
107
108
  planChanged: (subBefore?.plan?.slug ?? null) !== (subAfter?.plan?.slug ?? null) ||
108
109
  (subBefore?.status ?? null) !== (subAfter?.status ?? null),
109
110
  entitlementsChanged: !sameFlags(entBefore, entAfter),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nebulr-group/bridge-svelte",
3
- "version": "0.9.0-beta.4",
3
+ "version": "0.9.0-beta.5",
4
4
  "description": "Bridge Svelte library, This library helps you to add bridge authentication and feature flags, and payments to your svelte application.",
5
5
  "author": "Iman Pouya",
6
6
  "license": "MIT",
@@ -79,7 +79,7 @@
79
79
  "typescript": "^6.0.0",
80
80
  "vite": "^6.2.6",
81
81
  "vitest": "^4.1.4",
82
- "@nebulr-group/bridge-auth-core": "0.8.0-beta.0"
82
+ "@nebulr-group/bridge-auth-core": "0.8.0-beta.2"
83
83
  },
84
84
  "keywords": [
85
85
  "svelte",