@terreno/syncdb 57.16.2 → 57.18.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.
@@ -58,6 +58,56 @@ describe("betterAuthAdapter", () => {
58
58
  expect(await adapter.getUserId()).toBeNull();
59
59
  });
60
60
 
61
+ it("keeps the confirmed user id when a later read fails, so offline is not a sign-out", async () => {
62
+ let next: () => Promise<BetterAuthGetSessionResult> = async () => ({
63
+ data: {session: {token: "tok"}, user: {id: "u1"}},
64
+ });
65
+ const adapter = betterAuthAdapter(makeClient(() => next()));
66
+ expect(await adapter.getUserId()).toBe("u1");
67
+
68
+ next = async () => {
69
+ throw new TypeError("Failed to fetch");
70
+ };
71
+ expect(await adapter.getUserId()).toBe("u1");
72
+ expect(await adapter.getToken()).toBeNull();
73
+
74
+ next = async () =>
75
+ ({
76
+ data: null,
77
+ error: {status: 0, statusText: "Failed to fetch"},
78
+ }) as BetterAuthGetSessionResult;
79
+ expect(await adapter.getUserId()).toBe("u1");
80
+ });
81
+
82
+ it("returns null after the server confirms sign-out, even if a later read fails", async () => {
83
+ let next: () => Promise<BetterAuthGetSessionResult> = async () => ({
84
+ data: {session: {token: "tok"}, user: {id: "u1"}},
85
+ });
86
+ const adapter = betterAuthAdapter(makeClient(() => next()));
87
+ expect(await adapter.getUserId()).toBe("u1");
88
+
89
+ next = async () => ({data: null});
90
+ expect(await adapter.getUserId()).toBeNull();
91
+ next = async () => {
92
+ throw new TypeError("Failed to fetch");
93
+ };
94
+ expect(await adapter.getUserId()).toBeNull();
95
+ });
96
+
97
+ it("treats a 401 error envelope as signed out", async () => {
98
+ let next: () => Promise<BetterAuthGetSessionResult> = async () => ({
99
+ data: {session: {token: "tok"}, user: {id: "u1"}},
100
+ });
101
+ const adapter = betterAuthAdapter(makeClient(() => next()));
102
+ expect(await adapter.getUserId()).toBe("u1");
103
+ next = async () =>
104
+ ({
105
+ data: null,
106
+ error: {status: 401, statusText: "Unauthorized"},
107
+ }) as BetterAuthGetSessionResult;
108
+ expect(await adapter.getUserId()).toBeNull();
109
+ });
110
+
61
111
  it("returns null when getSession resolves to a non-object", async () => {
62
112
  const adapter = betterAuthAdapter(
63
113
  makeClient(async () => "nonsense" as unknown as BetterAuthGetSessionResult)
@@ -66,6 +116,76 @@ describe("betterAuthAdapter", () => {
66
116
  });
67
117
  });
68
118
 
119
+ describe("getBearerToken option", () => {
120
+ const makeCountingClient = (): {client: BetterAuthClientLike; calls: () => number} => {
121
+ let count = 0;
122
+ return {
123
+ calls: (): number => count,
124
+ client: makeClient(async () => {
125
+ count += 1;
126
+ return {data: {session: {token: "session-tok"}, user: {id: "u1"}}};
127
+ }),
128
+ };
129
+ };
130
+
131
+ it("returns the bearer token without calling getSession", async () => {
132
+ const {client, calls} = makeCountingClient();
133
+ const adapter = betterAuthAdapter(client, {getBearerToken: () => "t1"});
134
+ expect(await adapter.getToken()).toBe("t1");
135
+ expect(calls()).toBe(0);
136
+ });
137
+
138
+ it("reads the getter on every call, so a rotated token is picked up", async () => {
139
+ const {client, calls} = makeCountingClient();
140
+ let bearer = "t1";
141
+ const adapter = betterAuthAdapter(client, {getBearerToken: () => bearer});
142
+ expect(await adapter.getToken()).toBe("t1");
143
+ bearer = "t2";
144
+ expect(await adapter.getToken()).toBe("t2");
145
+ expect(calls()).toBe(0);
146
+ });
147
+
148
+ it("reads getSession when the getter returns null", async () => {
149
+ const {client, calls} = makeCountingClient();
150
+ const adapter = betterAuthAdapter(client, {getBearerToken: () => null});
151
+ expect(await adapter.getToken()).toBe("session-tok");
152
+ expect(calls()).toBe(1);
153
+ });
154
+
155
+ it("reads getSession when the getter returns an empty string", async () => {
156
+ const {client, calls} = makeCountingClient();
157
+ const adapter = betterAuthAdapter(client, {getBearerToken: () => ""});
158
+ expect(await adapter.getToken()).toBe("session-tok");
159
+ expect(calls()).toBe(1);
160
+ });
161
+
162
+ it("reads getSession when the getter throws", async () => {
163
+ const {client, calls} = makeCountingClient();
164
+ const adapter = betterAuthAdapter(client, {
165
+ getBearerToken: () => {
166
+ throw new Error("storage blocked");
167
+ },
168
+ });
169
+ expect(await adapter.getToken()).toBe("session-tok");
170
+ expect(calls()).toBe(1);
171
+ });
172
+
173
+ it("reads getSession without the option", async () => {
174
+ const {client, calls} = makeCountingClient();
175
+ const adapter = betterAuthAdapter(client);
176
+ expect(await adapter.getToken()).toBe("session-tok");
177
+ expect(calls()).toBe(1);
178
+ });
179
+
180
+ it("leaves getUserId and refresh reading getSession", async () => {
181
+ const {client, calls} = makeCountingClient();
182
+ const adapter = betterAuthAdapter(client, {getBearerToken: () => "t1"});
183
+ expect(await adapter.getUserId()).toBe("u1");
184
+ expect(await adapter.refresh?.()).toBe(true);
185
+ expect(calls()).toBe(2);
186
+ });
187
+ });
188
+
69
189
  describe("refresh (A4)", () => {
70
190
  it("returns true when a re-fetched session carries a token", async () => {
71
191
  const adapter = betterAuthAdapter(
@@ -228,6 +348,38 @@ describe("betterAuthAdapter", () => {
228
348
  expect(count).toBe(2);
229
349
  });
230
350
 
351
+ it("answers an auth-change callback's getUserId from the emission when the read fails", async () => {
352
+ // The syncdb client re-reads getUserId inside its auth-change handler. When the
353
+ // device goes offline between the emission and that read, a null answer would be
354
+ // taken as a sign-out.
355
+ const atom = makeAtom();
356
+ const adapter = betterAuthAdapter(
357
+ makeClient(
358
+ async () => {
359
+ throw new TypeError("Failed to fetch");
360
+ },
361
+ {
362
+ subscribe: (listener) => {
363
+ atom.listeners.add(listener);
364
+ return () => atom.listeners.delete(listener);
365
+ },
366
+ }
367
+ )
368
+ );
369
+ const seen: (string | null)[] = [];
370
+ adapter.onAuthChange(() => {
371
+ void adapter.getUserId().then((userId) => seen.push(userId));
372
+ });
373
+
374
+ atom.emit({data: {session: {token: "tok"}, user: {id: "u1"}}});
375
+ await flush();
376
+ expect(seen).toEqual(["u1"]);
377
+
378
+ atom.emit({data: null});
379
+ await flush();
380
+ expect(seen).toEqual(["u1", null]);
381
+ });
382
+
231
383
  it("forwards opaque emissions it cannot parse (back-compat)", () => {
232
384
  const atom = makeAtom();
233
385
  const adapter = betterAuthAdapter(
@@ -452,4 +604,236 @@ describe("betterAuthAdapter", () => {
452
604
  expect(calls).toBeGreaterThanOrEqual(1);
453
605
  });
454
606
  });
607
+
608
+ describe("confirmed user id ordering", () => {
609
+ interface ScriptedClient {
610
+ client: BetterAuthClientLike;
611
+ /** Answer every getSession() call that is not held with this result (or a rejection). */
612
+ answerWith: (result: () => Promise<BetterAuthGetSessionResult>) => void;
613
+ /** Hold the next getSession() call until the returned release function runs. */
614
+ holdNext: () => (result: BetterAuthGetSessionResult) => void;
615
+ emit: (value: unknown) => void;
616
+ }
617
+
618
+ const makeScriptedClient = (): ScriptedClient => {
619
+ const listeners = new Set<(value: unknown) => void>();
620
+ const queue: (() => Promise<BetterAuthGetSessionResult>)[] = [];
621
+ let fallback: () => Promise<BetterAuthGetSessionResult> = async () => null;
622
+ return {
623
+ answerWith: (result): void => {
624
+ fallback = result;
625
+ },
626
+ client: {
627
+ getSession: () => (queue.shift() ?? fallback)(),
628
+ useSession: {
629
+ subscribe: (listener): (() => void) => {
630
+ listeners.add(listener);
631
+ return () => listeners.delete(listener);
632
+ },
633
+ },
634
+ },
635
+ emit: (value: unknown): void => {
636
+ for (const listener of listeners) {
637
+ listener(value);
638
+ }
639
+ },
640
+ holdNext: (): ((result: BetterAuthGetSessionResult) => void) => {
641
+ let release: (result: BetterAuthGetSessionResult) => void = () => {};
642
+ const held = new Promise<BetterAuthGetSessionResult>((resolve) => {
643
+ release = resolve;
644
+ });
645
+ queue.push(() => held);
646
+ return (result) => release(result);
647
+ },
648
+ };
649
+ };
650
+
651
+ const offline = async (): Promise<BetterAuthGetSessionResult> => {
652
+ throw new TypeError("Failed to fetch");
653
+ };
654
+
655
+ const u1Session = {data: {session: {token: "tok-1"}, user: {id: "u1"}}};
656
+
657
+ it("drops a read that started before a sign-out emission and resolved after it", async () => {
658
+ const scripted = makeScriptedClient();
659
+ const adapter = betterAuthAdapter(scripted.client);
660
+ adapter.onAuthChange(() => {});
661
+ scripted.emit(u1Session);
662
+
663
+ const release = scripted.holdNext();
664
+ const staleRead = adapter.getUserId();
665
+ scripted.emit({data: null});
666
+ release(u1Session);
667
+ // The read still answers its own caller with what the server returned.
668
+ expect(await staleRead).toBe("u1");
669
+
670
+ scripted.answerWith(offline);
671
+ expect(await adapter.getUserId()).toBeNull();
672
+ });
673
+
674
+ it("drops a read that resolved after a newer read confirmed sign-out", async () => {
675
+ const scripted = makeScriptedClient();
676
+ const adapter = betterAuthAdapter(scripted.client);
677
+ scripted.answerWith(async () => u1Session);
678
+ expect(await adapter.getUserId()).toBe("u1");
679
+
680
+ const release = scripted.holdNext();
681
+ const staleRead = adapter.getUserId();
682
+ scripted.answerWith(async () => ({data: null}));
683
+ expect(await adapter.getUserId()).toBeNull();
684
+ release(u1Session);
685
+ expect(await staleRead).toBe("u1");
686
+
687
+ scripted.answerWith(offline);
688
+ expect(await adapter.getUserId()).toBeNull();
689
+ });
690
+
691
+ it("keeps the switched-to user when a read from before the switch resolves late", async () => {
692
+ const scripted = makeScriptedClient();
693
+ const adapter = betterAuthAdapter(scripted.client);
694
+ adapter.onAuthChange(() => {});
695
+ scripted.emit(u1Session);
696
+
697
+ const release = scripted.holdNext();
698
+ const staleRead = adapter.getUserId();
699
+ scripted.emit({data: {session: {token: "tok-2"}, user: {id: "u2"}}});
700
+ release(u1Session);
701
+ expect(await staleRead).toBe("u1");
702
+
703
+ scripted.answerWith(offline);
704
+ expect(await adapter.getUserId()).toBe("u2");
705
+ });
706
+
707
+ it("does not drop a newer read because an older read resolved first", async () => {
708
+ const scripted = makeScriptedClient();
709
+ const adapter = betterAuthAdapter(scripted.client);
710
+ const releaseOlder = scripted.holdNext();
711
+ const releaseNewer = scripted.holdNext();
712
+ const olderRead = adapter.getUserId();
713
+ const newerRead = adapter.getUserId();
714
+ releaseOlder({data: {session: {token: "tok-2"}, user: {id: "u2"}}});
715
+ expect(await olderRead).toBe("u2");
716
+ releaseNewer(u1Session);
717
+ expect(await newerRead).toBe("u1");
718
+
719
+ scripted.answerWith(offline);
720
+ expect(await adapter.getUserId()).toBe("u1");
721
+ });
722
+
723
+ it("lets an in-flight read confirm sign-out when an emission only re-confirmed the same user", async () => {
724
+ const scripted = makeScriptedClient();
725
+ const adapter = betterAuthAdapter(scripted.client);
726
+ adapter.onAuthChange(() => {});
727
+ scripted.emit(u1Session);
728
+
729
+ const release = scripted.holdNext();
730
+ const read = adapter.getUserId();
731
+ scripted.emit(u1Session);
732
+ release({data: null});
733
+ expect(await read).toBeNull();
734
+
735
+ scripted.answerWith(offline);
736
+ expect(await adapter.getUserId()).toBeNull();
737
+ });
738
+
739
+ it("keeps a read-confirmed user when a late atom fetch repeats the atom's own value", async () => {
740
+ const scripted = makeScriptedClient();
741
+ const adapter = betterAuthAdapter(scripted.client);
742
+ adapter.onAuthChange(() => {});
743
+ scripted.emit(u1Session);
744
+
745
+ scripted.answerWith(async () => ({data: {session: {token: "tok-2"}, user: {id: "u2"}}}));
746
+ expect(await adapter.getUserId()).toBe("u2");
747
+ // An atom fetch that started before that read settles late with the atom's old value.
748
+ scripted.emit(u1Session);
749
+
750
+ scripted.answerWith(offline);
751
+ expect(await adapter.getUserId()).toBe("u2");
752
+ });
753
+
754
+ it("treats a 401 session-atom emission as a sign-out", async () => {
755
+ const scripted = makeScriptedClient();
756
+ const adapter = betterAuthAdapter(scripted.client);
757
+ let calls = 0;
758
+ adapter.onAuthChange(() => {
759
+ calls += 1;
760
+ });
761
+ scripted.emit(u1Session);
762
+ expect(calls).toBe(1);
763
+
764
+ scripted.answerWith(offline);
765
+ scripted.emit({data: null, error: {status: 401, statusText: "Unauthorized"}});
766
+ expect(calls).toBe(2);
767
+ expect(await adapter.getUserId()).toBeNull();
768
+
769
+ // Repeated 401s, and a plain signed-out emission, share one identity and are deduped.
770
+ scripted.emit({data: null, error: {status: 401, statusText: "Unauthorized"}});
771
+ scripted.emit({data: null});
772
+ expect(calls).toBe(2);
773
+ });
774
+
775
+ it("ignores the stale data a refetch-start emission carries", async () => {
776
+ const scripted = makeScriptedClient();
777
+ const adapter = betterAuthAdapter(scripted.client);
778
+ adapter.onAuthChange(() => {});
779
+ scripted.emit(u1Session);
780
+
781
+ // A direct read sees the session revoked while the atom still holds u1.
782
+ scripted.answerWith(async () => ({data: null}));
783
+ expect(await adapter.getUserId()).toBeNull();
784
+ // Better Auth starts every refetch by re-emitting the previous data.
785
+ scripted.emit({...u1Session, error: null, isPending: false, isRefetching: true});
786
+
787
+ scripted.answerWith(offline);
788
+ expect(await adapter.getUserId()).toBeNull();
789
+ });
790
+
791
+ it("does not let a new subscriber's replay of the cached session restore a signed-out user", async () => {
792
+ // nanostores replays the atom's current value to each new listener synchronously.
793
+ const atomValue: unknown = u1Session;
794
+ const listeners = new Set<(value: unknown) => void>();
795
+ let next: () => Promise<BetterAuthGetSessionResult> = async () => u1Session;
796
+ const adapter = betterAuthAdapter({
797
+ getSession: () => next(),
798
+ useSession: {
799
+ subscribe: (listener): (() => void) => {
800
+ listeners.add(listener);
801
+ listener(atomValue);
802
+ return () => listeners.delete(listener);
803
+ },
804
+ },
805
+ });
806
+ let calls = 0;
807
+ adapter.onAuthChange(() => {
808
+ calls += 1;
809
+ });
810
+ expect(calls).toBe(1);
811
+ expect(await adapter.getUserId()).toBe("u1");
812
+
813
+ next = async () => ({data: null});
814
+ expect(await adapter.getUserId()).toBeNull();
815
+ // A second consumer subscribes while the atom still holds the old session.
816
+ adapter.onAuthChange(() => {
817
+ calls += 1;
818
+ });
819
+ expect(calls).toBe(2);
820
+
821
+ next = offline;
822
+ expect(await adapter.getUserId()).toBeNull();
823
+ });
824
+
825
+ it("uses a subscriber's replay as the first confirmation when nothing is confirmed yet", async () => {
826
+ const adapter = betterAuthAdapter({
827
+ getSession: offline,
828
+ useSession: {
829
+ subscribe: (listener): (() => void) => {
830
+ listener(u1Session);
831
+ return () => {};
832
+ },
833
+ },
834
+ });
835
+ adapter.onAuthChange(() => {});
836
+ expect(await adapter.getUserId()).toBe("u1");
837
+ });
838
+ });
455
839
  });
@@ -1,5 +1,9 @@
1
1
  import type {AuthProvider} from "../types";
2
- import type {BetterAuthClientLike, BetterAuthSessionDataLike} from "./types";
2
+ import type {
3
+ BetterAuthClientLike,
4
+ BetterAuthGetSessionResult,
5
+ BetterAuthSessionDataLike,
6
+ } from "./types";
3
7
 
4
8
  /** Default polling cadence when the client exposes no session subscription. */
5
9
  export const DEFAULT_AUTH_POLL_INTERVAL_MS = 5_000;
@@ -11,6 +15,14 @@ export interface BetterAuthAdapterOptions {
11
15
  setIntervalFn?: (handler: () => void, ms: number) => unknown;
12
16
  /** Interval canceller matching `setIntervalFn` (default global clearInterval). */
13
17
  clearIntervalFn?: (handle: unknown) => void;
18
+ /**
19
+ * Synchronous bearer-token reader, for clients that keep the session token locally
20
+ * (for example rtk's `getBetterAuthBearerToken` in web bearer mode). When it returns a
21
+ * token, `getToken` uses it without calling `getSession()`. A null or empty result, or a
22
+ * throw, falls back to reading `getSession()`. `getUserId`, `onAuthChange` and `refresh`
23
+ * always read the session.
24
+ */
25
+ getBearerToken?: () => string | null;
14
26
  }
15
27
 
16
28
  /**
@@ -28,13 +40,39 @@ const unwrapSession = (result: unknown): BetterAuthSessionDataLike | null => {
28
40
  return result as BetterAuthSessionDataLike;
29
41
  };
30
42
 
43
+ /** True for an error whose status says the server has no session for this client. */
44
+ const isUnauthorizedError = (error: unknown): boolean => {
45
+ return (
46
+ Boolean(error) && typeof error === "object" && (error as {status?: unknown}).status === 401
47
+ );
48
+ };
49
+
50
+ /**
51
+ * True for a `{error}` envelope from a fetch that failed: Better Auth's client returns one
52
+ * instead of rejecting for many failures. A 401 is the server saying "signed out", so it
53
+ * stays a successful (signed-out) read.
54
+ */
55
+ const isFailedReadEnvelope = (result: unknown): boolean => {
56
+ if (!result || typeof result !== "object" || !("error" in result)) {
57
+ return false;
58
+ }
59
+ const error = (result as {error?: unknown}).error;
60
+ if (!error) {
61
+ return false;
62
+ }
63
+ return !isUnauthorizedError(error);
64
+ };
65
+
31
66
  /**
32
67
  * Adapt a Better Auth client to syncdb's {@link AuthProvider} contract.
33
- * Tokens/user ids are read per call via `getSession()` (never cached, so
34
- * Better Auth session refresh is picked up transparently); auth changes are
68
+ * Tokens and user ids are read per call via `getSession()`, unless
69
+ * `options.getBearerToken` supplies the token. Tokens are never cached, so
70
+ * Better Auth session refresh is picked up transparently. Auth changes are
35
71
  * delivered through the client's nanostore session atom when available, with
36
- * an injectable polling fallback otherwise. All read errors degrade to null —
37
- * a broken auth client behaves like "signed out", never a crash.
72
+ * an injectable polling fallback otherwise. Read errors never throw: a failed
73
+ * token read returns null, and a failed user-id read returns the user id the
74
+ * server last confirmed (null before the first confirmation), so a request that
75
+ * fails while offline is never reported as a sign-out.
38
76
  */
39
77
  export const betterAuthAdapter = (
40
78
  authClient: BetterAuthClientLike,
@@ -48,20 +86,77 @@ export const betterAuthAdapter = (
48
86
  options.clearIntervalFn ??
49
87
  ((handle: unknown): void => clearInterval(handle as ReturnType<typeof setInterval>));
50
88
 
89
+ /**
90
+ * The user id the server last confirmed: set by successful session reads and by
91
+ * session-atom emissions, cleared when either reports signed out. `undefined` until the
92
+ * first confirmation. {@link getUserId} answers with it when a read fails.
93
+ */
94
+ let confirmedUserId: string | null | undefined;
95
+ /**
96
+ * Ordering for {@link confirmedUserId}. Every session read takes a ticket when it starts,
97
+ * and every emission that changes or clears the identity takes one when it arrives. The
98
+ * cache keeps the answer with the highest ticket, so a read that started before a sign-out
99
+ * or user switch and resolves after it cannot restore the previous user.
100
+ */
101
+ let lastTicket = 0;
102
+ let confirmedTicket = 0;
103
+
104
+ const takeTicket = (): number => {
105
+ lastTicket += 1;
106
+ return lastTicket;
107
+ };
108
+
109
+ const confirmUserId = (userId: string | null, ticket: number): void => {
110
+ if (ticket < confirmedTicket) {
111
+ return;
112
+ }
113
+ confirmedTicket = ticket;
114
+ confirmedUserId = userId;
115
+ };
116
+
117
+ /**
118
+ * Record an emission's identity. An emission that only re-confirms the cached user takes no
119
+ * ticket, so it does not discard an in-flight read that may carry a newer sign-out. A
120
+ * signed-out emission always takes one, so it discards every read that started before it.
121
+ *
122
+ * A replay (the atom's current value, delivered synchronously to a new subscriber) is not a
123
+ * new server answer: it may be older than a read that already confirmed a sign-out. It
124
+ * counts as the oldest answer, so it only fills the cache before anything is confirmed.
125
+ */
126
+ const confirmUserIdFromEmission = (userId: string | null, isReplay: boolean): void => {
127
+ if (isReplay) {
128
+ confirmUserId(userId, 0);
129
+ return;
130
+ }
131
+ if (userId !== null && userId === confirmedUserId) {
132
+ return;
133
+ }
134
+ confirmUserId(userId, takeTicket());
135
+ };
136
+
51
137
  /**
52
138
  * Read the session, distinguishing "read failed" from "signed out". Both surface as
53
139
  * a null session, but only the latter is an identity change — see
54
- * {@link classifyEmission}.
140
+ * {@link classifyEmission}. Better Auth reports a failed fetch either by rejecting or
141
+ * as a `{data: null, error}` envelope; a 401 error means signed out.
55
142
  */
56
143
  const readSessionResult = async (): Promise<{
57
144
  ok: boolean;
58
145
  session: BetterAuthSessionDataLike | null;
59
146
  }> => {
147
+ const ticket = takeTicket();
148
+ let result: BetterAuthGetSessionResult;
60
149
  try {
61
- return {ok: true, session: unwrapSession(await authClient.getSession())};
150
+ result = await authClient.getSession();
62
151
  } catch {
63
152
  return {ok: false, session: null};
64
153
  }
154
+ if (isFailedReadEnvelope(result)) {
155
+ return {ok: false, session: null};
156
+ }
157
+ const session = unwrapSession(result);
158
+ confirmUserId(session?.user?.id ?? null, ticket);
159
+ return {ok: true, session};
65
160
  };
66
161
 
67
162
  const readSession = async (): Promise<BetterAuthSessionDataLike | null> => {
@@ -80,13 +175,41 @@ export const betterAuthAdapter = (
80
175
  return Boolean(session?.session?.token);
81
176
  };
82
177
 
178
+ /**
179
+ * Read the caller's bearer token, treating a throw (for example blocked storage) like a
180
+ * missing token so the session read still gets a chance.
181
+ */
182
+ const readBearerToken = (): string | null => {
183
+ if (!options.getBearerToken) {
184
+ return null;
185
+ }
186
+ try {
187
+ return options.getBearerToken() || null;
188
+ } catch {
189
+ return null;
190
+ }
191
+ };
192
+
83
193
  const getToken = async (): Promise<string | null> => {
194
+ const bearerToken = readBearerToken();
195
+ if (bearerToken) {
196
+ return bearerToken;
197
+ }
84
198
  const session = await readSession();
85
199
  return session?.session?.token ?? null;
86
200
  };
87
201
 
202
+ /**
203
+ * A failed read answers with the last confirmed user id instead of null: callers such as
204
+ * the syncdb client treat null as a sign-out, and a request that fails while the device is
205
+ * offline proves nothing about the session (INV-2). Before any read has succeeded, a failed
206
+ * read still answers null.
207
+ */
88
208
  const getUserId = async (): Promise<string | null> => {
89
- const session = await readSession();
209
+ const {ok, session} = await readSessionResult();
210
+ if (!ok) {
211
+ return confirmedUserId ?? null;
212
+ }
90
213
  return session?.user?.id ?? null;
91
214
  };
92
215
 
@@ -105,9 +228,12 @@ export const betterAuthAdapter = (
105
228
 
106
229
  /**
107
230
  * Classify a session-atom emission for the subscribe path:
108
- * - "pending": an in-flight fetch state (`isPending: true`) or a FAILED read
109
- * (`error` set) — never a change;
110
- * - `{key}`: a parseable session envelope reduced to its identity (userId|token);
231
+ * - "pending": an in-flight fetch state (`isPending: true`), a refetch start
232
+ * (`isRefetching: true`, which re-emits the previous data rather than a server answer),
233
+ * or a FAILED read (`error` set, other than a 401) — never a change;
234
+ * - `{key}`: a parseable session envelope reduced to its identity (userId|token). A 401
235
+ * error is the server saying "signed out", so it reduces to the signed-out identity,
236
+ * matching how a 401 from `getSession()` is read;
111
237
  * - null: an opaque value the adapter cannot interpret.
112
238
  *
113
239
  * A failed read is deliberately indistinguishable from "pending" here. Better Auth
@@ -118,19 +244,25 @@ export const betterAuthAdapter = (
118
244
  * recoverable state, not a sign-out (INV-2), so the identity is left unchanged and the
119
245
  * next successful emission decides.
120
246
  */
121
- const classifyEmission = (value: unknown): {key: string} | "pending" | null => {
247
+ const classifyEmission = (
248
+ value: unknown
249
+ ): {key: string; userId: string | null} | "pending" | null => {
122
250
  if (!value || typeof value !== "object") {
123
251
  return null;
124
252
  }
125
253
  const emission = value as {
126
254
  isPending?: unknown;
255
+ isRefetching?: unknown;
127
256
  data?: unknown;
128
257
  user?: unknown;
129
258
  error?: unknown;
130
259
  };
131
- if (emission.isPending === true) {
260
+ if (emission.isPending === true || emission.isRefetching === true) {
132
261
  return "pending";
133
262
  }
263
+ if (isUnauthorizedError(emission.error)) {
264
+ return {key: "|", userId: null};
265
+ }
134
266
  if (emission.error) {
135
267
  return "pending";
136
268
  }
@@ -145,7 +277,10 @@ export const betterAuthAdapter = (
145
277
  } else {
146
278
  return null;
147
279
  }
148
- return {key: `${payload?.user?.id ?? ""}|${payload?.session?.token ?? ""}`};
280
+ return {
281
+ key: `${payload?.user?.id ?? ""}|${payload?.session?.token ?? ""}`,
282
+ userId: payload?.user?.id ?? null,
283
+ };
149
284
  };
150
285
 
151
286
  const onAuthChange = (callback: () => void): (() => void) => {
@@ -159,6 +294,7 @@ export const betterAuthAdapter = (
159
294
  // token rotation) may fire the callback. In-flight (`isPending`) states are
160
295
  // skipped; opaque values the adapter cannot parse are forwarded as before.
161
296
  let lastKey: string | undefined;
297
+ let isSubscribing = true;
162
298
  const unsubscribe = subscribe((value) => {
163
299
  const parsed = classifyEmission(value);
164
300
  if (parsed === "pending") {
@@ -168,12 +304,17 @@ export const betterAuthAdapter = (
168
304
  callback();
169
305
  return;
170
306
  }
307
+ // An emission repeating the atom's own last value is not a new server answer (a
308
+ // fetch that started before a newer read can settle late), so it must not
309
+ // overwrite what that read confirmed.
171
310
  if (parsed.key === lastKey) {
172
311
  return;
173
312
  }
313
+ confirmUserIdFromEmission(parsed.userId, isSubscribing);
174
314
  lastKey = parsed.key;
175
315
  callback();
176
316
  });
317
+ isSubscribing = false;
177
318
  return typeof unsubscribe === "function" ? unsubscribe : (): void => {};
178
319
  }
179
320