@lenne.tech/nuxt-extensions 4.0.4 → 4.0.6

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/CLAUDE.md CHANGED
@@ -270,7 +270,7 @@ The `useLtAuth()` composable manages the `lt-auth-state` cookie for authenticati
270
270
  - Don't call `useCookie('lt-auth-state')` with different options than `useLtAuth()` uses (`maxAge: 604800, sameSite: 'lax'`)
271
271
  - Don't URL-decode or JSON-parse the cookie value manually on the server — `useCookie` handles this automatically
272
272
  - Don't write to `authState.value` from custom middleware — this generates a `Set-Cookie` header in the SSR response that may overwrite the browser's cookie
273
- - Don't store the `token` of a 2FA or passkey answer anywhere. Finish a 2FA sign-in with `useLtAuth().twoFactor.verifyTotp()` / `verifyBackupCode()`.
273
+ - Don't store the `token` of a 2FA or passkey answer yourself. Finish a 2FA sign-in with `useLtAuth().twoFactor.verifyTotp()` / `verifyBackupCode()`; a JWT in the answer is stored by the client (below), a session token never.
274
274
 
275
275
  ### The session token never reaches `lt-jwt-token`:
276
276
  Better-Auth answers `two-factor/verify-totp` and `verify-backup-code` with `{ token, user }`, and
@@ -285,16 +285,62 @@ unchanged. That token is the session token, the value the API keeps in the httpO
285
285
  `isLtJwtShaped()` says so. That is the same test as nest-server's `isJwtShaped`: three segments,
286
286
  header `eyJ`. Test fixtures need JWT-shaped tokens too; `'a.b.c'` is refused.
287
287
  - **A JWT comes from `GET /iam/token`, or from a body the server already converted** (sign-in with
288
- `cookies: false`; nest-server's `resolveJwtToken` never returns the session token there).
288
+ `cookies: false`; nest-server's `resolveJwtToken` never returns the session token there). The
289
+ forwarded routes count too: where the body may carry a token (`cookies: false` or
290
+ `exposeTokenInBody`), nest-server's `presentSessionTokens` (12.6.1, rotation 12.7.1) answers
291
+ `verify-totp`, `verify-backup-code` and `change-password` with the JWT of the session that is
292
+ valid after the answer, from 12.11.1 on also `two-factor/disable` and `two-factor/enable` when
293
+ they replaced the session (12.11.0 sends no token there).
289
294
  - **Anything else found in `lt-jwt-token` is deleted** on start (`useLtAuth()`) and on read
290
295
  (`getLtJwtToken()`), along with its JWT mode, because leaked values from before 1.26.0 are
291
296
  still in users' browsers. Never write such a value there "temporarily".
292
297
  - **`setUser(user, 'jwt')` without a stored JWT falls back to `'cookie'`** and fetches the JWT.
293
298
  Without that fallback, the refusal above would turn a hand-written 2FA page into a sign-in that
294
299
  sends no credentials at all.
295
- - **`useLtAuthClient().twoFactor.verify*` and `signIn.social` strip a non-JWT `token` from the
296
- answer**, and `authenticateWithPasskey()` returns no `session`. Keep all three: application code
297
- that never receives the session token cannot store it.
300
+ - **`setUser(user)` without a mode keeps the mode for the signed-in user (same `id`), and starts
301
+ any other user on `'cookie'`** (since 4.0.5). The starter's security.vue calls
302
+ `setUser({ ...user.value, twoFactorEnabled: true })` after turning 2FA on; with the old default
303
+ `'cookie'` that left JWT mode, and the JWT the client had just stored was no longer sent: the
304
+ app then depended on a session cookie, which JWT mode exists not to rely on. Never let another
305
+ user keep JWT mode: the stored JWT is the previous user's.
306
+ - **`validateSession()` keeps the mode for the signed-in user while a JWT is stored** (since
307
+ 4.0.6; ng-base does the same since 22.0.0). Up to 4.0.5 it set `'cookie'` and fetched a new JWT,
308
+ so after every page load in JWT mode requests went out without the bearer until `/iam/token`
309
+ answered; the starter's E2E measured `two-factor/disable` without an `Authorization` header.
310
+ With `cookies: false` those requests, and the cookie-only `/iam/token` itself, then worked only
311
+ because nest-server reads the JWT cookie when no bearer comes, and before 12.11.2 it ignored
312
+ `COOKIE_PREFIX` there. Another user, or JWT mode without a stored JWT, starts on `'cookie'`.
313
+ **The `/iam/token` request on every page load stays, in JWT mode too.** With `cookies: false`
314
+ nest-server sets no session cookie, so `/iam/token` can only be paid for by a JWT cookie that is
315
+ still valid, and an expired JWT cannot be renewed at all; ng-base renews before sending
316
+ (`currentJwt()`), this module has nothing like it. Asking `/iam/token` only in cookie mode was
317
+ tried during 4.0.6 and ended every such sign-in with its first JWT, however often the page was
318
+ loaded. `test/validate-session-mode.test.ts` holds this.
319
+ - **`validateSession()` signs out a cached user the API has no session for** (since 4.0.6): a
320
+ `get-session` that ANSWERED without a session (not pending, no `error`), outside JWT mode with a
321
+ stored JWT, and confirmed by a direct `get-session` (`probeSession()`, the 401 interceptor's
322
+ rules: 401/403 or an empty 200 is dead, 5xx/429/network decides nothing) → `clearUser()`,
323
+ `false`. Up to 4.0.5 the cached user was trusted there: a project's API session had expired, the
324
+ page greeted the user by name, and every protected call failed (its API answered 403, so the
325
+ interceptor never fired either). **Never drop the confirming probe**: Better Auth's session atom
326
+ can hold a stale empty answer after a sign-in that does not refetch it, and a page load must not
327
+ undo a sign-in. `clearUser()`, not `signOut()`: an expired session deletes no offline-sync data.
328
+ - **`useLtAuthClient().twoFactor.verify*` / `enable` / `disable`, `changePassword` and
329
+ `signIn.social` strip a non-JWT `token` from the answer**, and `authenticateWithPasskey()`
330
+ returns no `session`. Keep all of them: application code that never receives the session token
331
+ cannot store it.
332
+ - **`useLtAuthClient().twoFactor.verify*` / `enable` / `disable` and `changePassword` store a JWT
333
+ the answer carries** (`storingAnswerJwt`, since 4.0.5), strip any other token
334
+ (`withoutSessionToken`) and leave the auth mode alone. Since nest-server 12.11.0 every JWT is
335
+ bound to its session (`sid`), and turning 2FA on or off or changing the password with
336
+ `revokeOtherSessions` replaces the session. From then on the JWT stored before is refused. The starter turns 2FA on through this client, not
337
+ through `useLtAuth()`, so without the store its next request in JWT mode would carry the refused
338
+ JWT. `useLtAuth().twoFactor.verify*` takes the same JWT in `completeForwardedSignIn()`, with no
339
+ `/iam/token` request. Only `result.data` is read: with `throw: true` nothing is stored.
340
+ The store writes `document.cookie`; the composable's `useCookie` refs follow through Nuxt's
341
+ cookieStore change event, not in the same tick. The client side is held by
342
+ `test/auth-client-session-token.test.ts`, the composable side by
343
+ `test/session-token-guard.test.ts`.
298
344
 
299
345
  ### How Auth Cookies Work:
300
346
  1. `setUser()` writes the cookie via both `useCookie().value` (for SSR sync) and `document.cookie` (for immediate availability)
@@ -357,6 +403,12 @@ holds. `useLtAuthClient().signIn.social` is the same call without the auth state
357
403
  JWT from `/iam/token`, exactly as after 2FA. `withoutSessionToken` strips only `result.data`, as
358
404
  for 2FA: with `throw: true` (as `options` or in `fetchOptions`) the body comes back with the
359
405
  token, and a caller's `onSuccess` hook sees the answer before the token is removed.
406
+ **nest-server 12.11.0 closes this shape by default** (`ID_TOKEN_NOT_SUPPORTED`). A project opens
407
+ it per provider with `disableIdTokenSignIn: false`. The redirect shape is not affected.
408
+ - **`emailAndPassword` in `/iam/features`** (nest-server 12.11.0 or later): `false` means the API
409
+ offers no sign-in with email and password. The starter's login page hides the form when it
410
+ sees that; a missing field (older API) means on. `features` is a
411
+ `Record<string, boolean | number | string[]>`, so no type in this module has to change.
360
412
  - **Silent attempt: `additionalParams: { prompt: 'none' }`.** The provider answers without showing
361
413
  anything, and the way back without a provider session is `errorCallbackURL` with
362
414
  `?error=login_required` (or `interaction_required`). A page that starts the attempt on load must
package/README.md CHANGED
@@ -529,13 +529,16 @@ async function handlePasskeyLogin() {
529
529
 
530
530
  Finish a sign-in that stopped at the second factor with `useLtAuth().twoFactor.verifyTotp()` or
531
531
  `verifyBackupCode()`. They put the user into the auth state on the cookie session and fetch the
532
- JWT from `/iam/token`.
533
-
534
- - **Never store the `token` of a 2FA or passkey answer.** Better-Auth answers `verify-totp` and
535
- `verify-backup-code` with `{ token, user }`, and `passkey/verify-authentication` with
536
- `{ session, user }`. That token is its session token, the value the API keeps in the httpOnly
537
- cookie. Stored as the "JWT", it lands in the readable `lt-jwt-token` cookie, where any script
538
- on the page can take it for the session's whole lifetime.
532
+ JWT from `/iam/token`. When the answer already carries a JWT, they take it as it is, with no
533
+ `/iam/token` request. nest-server sends one where the body may carry a token (`cookies: false`,
534
+ or `exposeTokenInBody`): the JWT of the session that is valid after the answer.
535
+
536
+ - **Never store the `token` of a 2FA or passkey answer yourself.** Better-Auth answers
537
+ `verify-totp` and `verify-backup-code` with `{ token, user }`, and `passkey/verify-authentication`
538
+ with `{ session, user }`. That token is its session token, the value the API keeps in the
539
+ httpOnly cookie. Stored as the "JWT", it lands in the readable `lt-jwt-token` cookie, where any
540
+ script on the page can take it for the session's whole lifetime. A JWT in the answer is stored
541
+ by the client itself (below).
539
542
  - **`lt-jwt-token` holds a JWT or nothing.** `jwtToken`, `setLtJwtToken()` and the sign-in
540
543
  methods refuse anything else; `isLtJwtShaped()` (from `/lib`) is the test, the same as
541
544
  nest-server's `isJwtShaped`.
@@ -544,8 +547,31 @@ JWT from `/iam/token`.
544
547
  - **`setUser(user, 'jwt')` without a stored JWT signs in on the cookie session** and fetches the
545
548
  JWT. A hand-written 2FA page that stored the body token therefore still works, without the
546
549
  leak; move it to the helpers anyway.
547
- - **`useLtAuthClient().twoFactor.verifyTotp()` / `verifyBackupCode()` no longer return the
548
- session token.**
550
+ - **`setUser(user)` without a mode keeps the auth mode when it updates the signed-in user**
551
+ (same `id`), as `setUser({ ...user.value, twoFactorEnabled: true })` after turning 2FA on does.
552
+ Any other user starts on the cookie session (since 4.0.5; before, every call without a mode
553
+ meant cookie mode, and a settings page in JWT mode stopped sending its JWT).
554
+ - **`validateSession()` keeps the auth mode of the signed-in user** (since 4.0.6). After a page
555
+ load in JWT mode the stored JWT goes out with the first request, while a new one is fetched from
556
+ `/iam/token` in the background. Up to 4.0.5 every page load switched to cookie mode until
557
+ `/iam/token` answered, and requests in that window went out without the JWT. Another user, or
558
+ JWT mode with no JWT stored, starts on the cookie session.
559
+ - **`validateSession()` signs out a user the API no longer has a session for** (since 4.0.6).
560
+ When `get-session` answers without a session while `lt-auth-state` still holds a user (the
561
+ session expired or was deleted on the server), it calls `clearUser()` and returns `false`, after
562
+ a second, direct `get-session` confirmed it. Up to 4.0.5 it returned `true` for the cached user:
563
+ the page showed the user as signed in while every protected request failed, until one of them
564
+ answered 401. JWT mode with a stored JWT keeps the user, and so does an answer that is not a
565
+ verdict (a timeout, a network error, a 5xx). Unsent offline-sync changes stay, as after any
566
+ expired session.
567
+ - **`useLtAuthClient().twoFactor.verifyTotp()`, `verifyBackupCode()`, `enable()`, `disable()`
568
+ and `changePassword()` return no session token.** A JWT in the answer stays, and the client
569
+ stores it in `lt-jwt-token` (since 4.0.5); the auth mode is left as it is. From nest-server
570
+ 12.11.0 on, every JWT is bound to its session. Turning 2FA on or off, or changing the password
571
+ with `revokeOtherSessions`, replaces that session, and the API refuses the JWT stored before. A
572
+ settings page that does this through the client keeps working in JWT mode. Turning 2FA off
573
+ needs nest-server 12.11.1 for that: 12.11.0 answers `two-factor/disable` without the new JWT.
574
+ With `throw: true` the client reads no answer and stores nothing.
549
575
  - **`authenticateWithPasskey()` returns no `session`.**
550
576
 
551
577
  #### Sign-in through a social provider
@@ -556,6 +582,10 @@ Entra ID for single sign-on (`betterAuth.socialProviders` in nest-server). `GET
556
582
  lists the enabled providers as `socialProviders`; `useLtAuth().features` holds that answer, so a
557
583
  login page can show one button per entry.
558
584
 
585
+ The same answer also reports `emailAndPassword` (nest-server 12.11.0 or later). When it is `false`,
586
+ the API offers no sign-in with email and password: hide that form, the "forgot password" link and
587
+ registration. An older API does not send the field, so treat a missing value as `true`.
588
+
559
589
  Both shapes go to `POST <basePath>/sign-in/social`:
560
590
 
561
591
  - **Redirect, the usual one.** The answer is the provider's authorization URL, and Better Auth's
@@ -568,7 +598,9 @@ Both shapes go to `POST <basePath>/sign-in/social`:
568
598
  session token Better Auth puts into that answer is removed, as in the 2FA answers. This covers
569
599
  the default `{ data, error }` answer only: with `throw: true` (as `options` or in `fetchOptions`)
570
600
  the body comes back unchanged, token included, and an `onSuccess` hook sees the answer before the
571
- token is removed.
601
+ token is removed. **nest-server 12.11.0 and later refuse this shape** with
602
+ `ID_TOKEN_NOT_SUPPORTED` unless the provider sets `disableIdTokenSignIn: false`. The redirect
603
+ shape is not affected.
572
604
 
573
605
  ```vue
574
606
  <script setup lang="ts">
package/dist/module.d.mts CHANGED
@@ -3,7 +3,7 @@ import { LtExtensionsModuleOptions } from '../dist/runtime/types/index.js';
3
3
  export * from '../dist/runtime/types/index.js';
4
4
 
5
5
  declare const name = "@lenne.tech/nuxt-extensions";
6
- declare const version = "4.0.4";
6
+ declare const version = "4.0.6";
7
7
  declare const configKey = "ltExtensions";
8
8
  declare const DEFAULT_LT_AUTH_STATE_COOKIE = "lt-auth-state";
9
9
  declare const DEFAULT_LT_JWT_TOKEN_COOKIE = "lt-jwt-token";
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "configKey": "ltExtensions",
3
3
  "name": "@lenne.tech/nuxt-extensions",
4
- "version": "4.0.4",
4
+ "version": "4.0.6",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.4",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -3,7 +3,7 @@ import { pathToFileURL } from 'node:url';
3
3
  import { SECURITY_TXT_DEFAULT_VALID_DAYS, SECURITY_TXT_DEFAULT_LANGUAGES, SECURITY_TXT_DEFAULT_CONTACT, SECURITY_TXT_PATH } from '../dist/runtime/server/lib/security-txt.js';
4
4
 
5
5
  const name = "@lenne.tech/nuxt-extensions";
6
- const version = "4.0.4";
6
+ const version = "4.0.6";
7
7
  const configKey = "ltExtensions";
8
8
  const DEFAULT_LT_AUTH_STATE_COOKIE = "lt-auth-state";
9
9
  const DEFAULT_LT_JWT_TOKEN_COOKIE = "lt-jwt-token";
@@ -97,12 +97,13 @@ export function useLtAuth() {
97
97
  const is2FAEnabled = computed(() => user.value?.twoFactorEnabled ?? false);
98
98
  const features = useState("lt-auth-features", () => ({}));
99
99
  const featuresFetched = useState("lt-auth-features-fetched", () => false);
100
- function setUser(userData, requestedMode = "cookie") {
101
- const mode = requestedMode === "jwt" && !jwtToken.value ? "cookie" : requestedMode;
102
- if (mode !== requestedMode && import.meta.client && userData) {
100
+ function setUser(userData, mode) {
101
+ const requestedMode = mode ?? (userData && user.value && userData.id === user.value.id ? authMode.value : "cookie");
102
+ const storedMode = requestedMode === "jwt" && !jwtToken.value ? "cookie" : requestedMode;
103
+ if (storedMode !== requestedMode && import.meta.client && userData) {
103
104
  void switchToJwtMode();
104
105
  }
105
- const newState = toLtStoredAuthState({ user: userData, authMode: mode });
106
+ const newState = toLtStoredAuthState({ user: userData, authMode: storedMode });
106
107
  if (import.meta.client || userData) {
107
108
  authState.value = newState;
108
109
  }
@@ -168,6 +169,36 @@ export function useLtAuth() {
168
169
  }
169
170
  return merged;
170
171
  }
172
+ async function probeSession() {
173
+ const controller = new AbortController();
174
+ let timer;
175
+ const timeout = new Promise((resolve) => {
176
+ timer = setTimeout(() => {
177
+ controller.abort();
178
+ resolve(null);
179
+ }, VALIDATE_SESSION_TIMEOUT_MS);
180
+ });
181
+ const verdict = (async () => {
182
+ try {
183
+ const response = await fetchWithAuth(`${getLtApiBase()}/get-session`, { method: "GET", signal: controller.signal });
184
+ if (response.status === 401 || response.status === 403) {
185
+ return false;
186
+ }
187
+ if (!response.ok) {
188
+ return null;
189
+ }
190
+ const data = await response.json().catch(() => null);
191
+ return Boolean(data && (data.user || data.session));
192
+ } catch {
193
+ return null;
194
+ }
195
+ })();
196
+ try {
197
+ return await Promise.race([verdict, timeout]);
198
+ } finally {
199
+ clearTimeout(timer);
200
+ }
201
+ }
171
202
  async function validateSession() {
172
203
  if (import.meta.server) {
173
204
  return !!resolvedAuthState.value?.user;
@@ -195,12 +226,19 @@ export function useLtAuth() {
195
226
  });
196
227
  }
197
228
  if (session.value.data?.user) {
198
- setUser(mergeSessionUser(session.value.data.user), "cookie");
229
+ const sessionUser = mergeSessionUser(session.value.data.user);
230
+ const keepsJwt = isJwtMode.value && !!jwtToken.value && user.value?.id === sessionUser.id;
231
+ setUser(sessionUser, keepsJwt ? "jwt" : "cookie");
199
232
  switchToJwtMode().catch(() => {
200
233
  });
201
234
  return true;
202
235
  }
203
236
  if (resolvedAuthState.value?.user) {
237
+ const answeredWithoutSession = !session.value.isPending && !session.value.error;
238
+ if (answeredWithoutSession && !(isJwtMode.value && jwtToken.value) && await probeSession() === false) {
239
+ clearUser();
240
+ return false;
241
+ }
204
242
  switchToJwtMode().catch(() => {
205
243
  });
206
244
  return true;
@@ -455,7 +455,9 @@ export declare function createLtAuthClient(config?: LtAuthClientConfig): {
455
455
  * Change password for an authenticated user (both passwords are hashed).
456
456
  *
457
457
  * `revokeOtherSessions` is the option that made the whitelist bug matter — see the
458
- * file header.
458
+ * file header. With it, Better-Auth deletes every session of the user and answers with the
459
+ * token of a new one: a session token is removed ({@link withoutSessionToken}), a JWT is
460
+ * stored ({@link storingAnswerJwt}).
459
461
  */
460
462
  changePassword: <T extends {
461
463
  currentPassword: string;
@@ -764,13 +766,18 @@ export declare function createLtAuthClient(config?: LtAuthClientConfig): {
764
766
  };
765
767
  twoFactor: {
766
768
  /**
767
- * Disable 2FA (password is hashed before sending)
769
+ * Disable 2FA (password is hashed before sending). Better-Auth replaces the session; a JWT
770
+ * of the new session in the answer (nest-server >= 12.11.1) is stored, see
771
+ * {@link storingAnswerJwt}, and any other token is removed ({@link withoutSessionToken}).
768
772
  */
769
773
  disable: <T extends {
770
774
  password: string;
771
775
  }>(params: T, options?: any) => Promise<any>;
772
776
  /**
773
- * Enable 2FA (password is hashed before sending)
777
+ * Enable 2FA (password is hashed before sending). With `method: 'otp'` or
778
+ * `skipVerificationOnEnable`, Better-Auth replaces the session here already; a JWT of the
779
+ * new session in the answer (nest-server >= 12.11.1) is stored, see {@link storingAnswerJwt},
780
+ * and any other token is removed ({@link withoutSessionToken}).
774
781
  */
775
782
  enable: <T extends {
776
783
  password: string;
@@ -783,7 +790,8 @@ export declare function createLtAuthClient(config?: LtAuthClientConfig): {
783
790
  }>(params: T, options?: any) => Promise<any>;
784
791
  /**
785
792
  * Verify TOTP code. The session token Better-Auth puts into the answer is removed first,
786
- * see {@link withoutSessionToken}.
793
+ * see {@link withoutSessionToken}; a JWT the answer carries is stored, see
794
+ * {@link storingAnswerJwt}.
787
795
  */
788
796
  verifyTotp: (...args: unknown[]) => Promise<any>;
789
797
  /**
@@ -3,7 +3,7 @@ import { adminClient, twoFactorClient } from "better-auth/client/plugins";
3
3
  import { createAuthClient } from "better-auth/vue";
4
4
  import { navigateTo } from "#imports";
5
5
  import { ltSha256 } from "../utils/crypto.js";
6
- import { createLtAuthFetch, isLocalDevApiProxy, isLtJwtShaped } from "./auth-state.js";
6
+ import { createLtAuthFetch, isLocalDevApiProxy, isLtJwtShaped, setLtJwtToken } from "./auth-state.js";
7
7
  let _ltAuthPluginRegistry = [];
8
8
  let _pluginsChangedAfterCreation = false;
9
9
  let _authClientSingleton = null;
@@ -147,14 +147,16 @@ export function createLtAuthClient(config = {}) {
147
147
  * Change password for an authenticated user (both passwords are hashed).
148
148
  *
149
149
  * `revokeOtherSessions` is the option that made the whitelist bug matter — see the
150
- * file header.
150
+ * file header. With it, Better-Auth deletes every session of the user and answers with the
151
+ * token of a new one: a session token is removed ({@link withoutSessionToken}), a JWT is
152
+ * stored ({@link storingAnswerJwt}).
151
153
  */
152
154
  changePassword: async (params, options) => {
153
155
  const [hashedCurrent, hashedNew] = await Promise.all([ltSha256(params.currentPassword), ltSha256(params.newPassword)]);
154
156
  if (!baseClient.changePassword) {
155
157
  throw new Error("[lt-auth] changePassword is unavailable on the Better-Auth client \u2014 the password was NOT changed.");
156
158
  }
157
- return baseClient.changePassword({ ...params, currentPassword: hashedCurrent, newPassword: hashedNew }, options);
159
+ return storingAnswerJwt(withoutSessionToken(await baseClient.changePassword({ ...params, currentPassword: hashedCurrent, newPassword: hashedNew }, options)));
158
160
  },
159
161
  /**
160
162
  * Reset password with token (new password is hashed before sending).
@@ -222,18 +224,23 @@ export function createLtAuthClient(config = {}) {
222
224
  // this package then keeps across versions. Ask, and it gets a line.
223
225
  twoFactor: {
224
226
  /**
225
- * Disable 2FA (password is hashed before sending)
227
+ * Disable 2FA (password is hashed before sending). Better-Auth replaces the session; a JWT
228
+ * of the new session in the answer (nest-server >= 12.11.1) is stored, see
229
+ * {@link storingAnswerJwt}, and any other token is removed ({@link withoutSessionToken}).
226
230
  */
227
231
  disable: async (params, options) => {
228
232
  const hashedPassword = await ltSha256(params.password);
229
- return baseClient.twoFactor.disable({ ...params, password: hashedPassword }, options);
233
+ return storingAnswerJwt(withoutSessionToken(await baseClient.twoFactor.disable({ ...params, password: hashedPassword }, options)));
230
234
  },
231
235
  /**
232
- * Enable 2FA (password is hashed before sending)
236
+ * Enable 2FA (password is hashed before sending). With `method: 'otp'` or
237
+ * `skipVerificationOnEnable`, Better-Auth replaces the session here already; a JWT of the
238
+ * new session in the answer (nest-server >= 12.11.1) is stored, see {@link storingAnswerJwt},
239
+ * and any other token is removed ({@link withoutSessionToken}).
233
240
  */
234
241
  enable: async (params, options) => {
235
242
  const hashedPassword = await ltSha256(params.password);
236
- return baseClient.twoFactor.enable({ ...params, password: hashedPassword }, options);
243
+ return storingAnswerJwt(withoutSessionToken(await baseClient.twoFactor.enable({ ...params, password: hashedPassword }, options)));
237
244
  },
238
245
  /**
239
246
  * Generate backup codes (password is hashed before sending)
@@ -244,13 +251,14 @@ export function createLtAuthClient(config = {}) {
244
251
  },
245
252
  /**
246
253
  * Verify TOTP code. The session token Better-Auth puts into the answer is removed first,
247
- * see {@link withoutSessionToken}.
254
+ * see {@link withoutSessionToken}; a JWT the answer carries is stored, see
255
+ * {@link storingAnswerJwt}.
248
256
  */
249
- verifyTotp: async (...args) => withoutSessionToken(await baseClient.twoFactor.verifyTotp(...args)),
257
+ verifyTotp: async (...args) => storingAnswerJwt(withoutSessionToken(await baseClient.twoFactor.verifyTotp(...args))),
250
258
  /**
251
259
  * Verify backup code. Same as `verifyTotp`.
252
260
  */
253
- verifyBackupCode: async (...args) => withoutSessionToken(await baseClient.twoFactor.verifyBackupCode(...args))
261
+ verifyBackupCode: async (...args) => storingAnswerJwt(withoutSessionToken(await baseClient.twoFactor.verifyBackupCode(...args)))
254
262
  }
255
263
  };
256
264
  }
@@ -261,3 +269,11 @@ function withoutSessionToken(result) {
261
269
  }
262
270
  return result;
263
271
  }
272
+ function storingAnswerJwt(result) {
273
+ const data = result?.data;
274
+ const token = data && typeof data === "object" ? data.token : void 0;
275
+ if (isLtJwtShaped(token)) {
276
+ setLtJwtToken(token);
277
+ }
278
+ return result;
279
+ }
@@ -337,6 +337,11 @@ export interface UseLtAuthReturn {
337
337
  * Better Auth writes "no picture" as `image: null`, which this normalises to `undefined`
338
338
  * before storing. Readers of {@link LtUser} keep a single empty case. An inline `data:` image
339
339
  * is not stored either (see {@link LtUser.image}).
340
+ *
341
+ * Without `mode`, an update of the signed-in user (same `id`, e.g. `{ ...user.value,
342
+ * twoFactorEnabled: true }`) keeps the current auth mode, and any other user starts on the
343
+ * cookie session (since 4.0.5; before, every call without `mode` meant `'cookie'`). `'jwt'`
344
+ * without a stored JWT falls back to `'cookie'` and fetches the JWT.
340
345
  */
341
346
  setUser: (userData: LtUserInput | null, mode?: LtAuthMode) => void;
342
347
  signIn: {
@@ -362,6 +367,20 @@ export interface UseLtAuthReturn {
362
367
  }>(params: NoStrayCredential<T, 'password'>, options?: unknown) => Promise<unknown>;
363
368
  };
364
369
  switchToJwtMode: () => Promise<boolean>;
370
+ /**
371
+ * Re-validates the session (app start, hard reload) through `get-session` and merges the
372
+ * session user onto the cached one. `true` while signed in.
373
+ *
374
+ * The signed-in user keeps JWT mode while a JWT is stored, and the stored JWT is sent while a
375
+ * new one is fetched in the background (since 4.0.6; before, every page load switched to cookie
376
+ * mode until the new JWT came). Another user, or JWT mode without a stored JWT, starts on the
377
+ * cookie session.
378
+ *
379
+ * When the API has no session for the cached user any more (confirmed by a direct
380
+ * `get-session`), the user is cleared and the result is `false` (since 4.0.6; before, the cached
381
+ * user counted as signed in). JWT mode with a stored JWT, a timeout and a failed request keep
382
+ * the user.
383
+ */
365
384
  validateSession: () => Promise<boolean>;
366
385
  passkey?: unknown;
367
386
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nuxt-extensions",
3
- "version": "4.0.4",
3
+ "version": "4.0.6",
4
4
  "description": "Reusable Nuxt 4 composables, components, and Better-Auth integration for lenne.tech projects",
5
5
  "repository": {
6
6
  "type": "git",
@@ -112,8 +112,8 @@
112
112
  "devDependencies": {
113
113
  "@better-auth/passkey": "1.7.19",
114
114
  "@nuxt/module-builder": "1.0.4",
115
- "@nuxt/schema": "4.6.4",
116
- "@nuxt/ui": "4.12.2",
115
+ "@nuxt/schema": "4.7.0",
116
+ "@nuxt/ui": "4.13.1",
117
117
  "@playwright/test": "1.65.1",
118
118
  "@types/node": "26.6.6",
119
119
  "@vitest/coverage-v8": "5.1.1",
@@ -122,9 +122,9 @@
122
122
  "cross-spawn": "7.0.6",
123
123
  "fake-indexeddb": "6.2.8",
124
124
  "happy-dom": "21.0.4",
125
- "nuxt": "4.6.4",
126
- "oxfmt": "0.79.0",
127
- "oxlint": "1.94.0",
125
+ "nuxt": "4.7.0",
126
+ "oxfmt": "0.80.0",
127
+ "oxlint": "1.95.0",
128
128
  "oxlint-tsgolint": "7.0.2008",
129
129
  "reka-ui": "2.11.0",
130
130
  "semver": "7.8.6",
@@ -151,5 +151,5 @@
151
151
  "node": ">= 22",
152
152
  "pnpm": "^11.0.0"
153
153
  },
154
- "packageManager": "pnpm@11.28.10+sha512.672216f06e15c109b85471d49d3fbed17e6f03ead258df08c2bf5b4a5c33321ebfbf59476bce81325efada16ace0ac78548fd0bfcd7a51369e939182a3dd50e4"
154
+ "packageManager": "pnpm@11.29.0+sha512.d913f9b37cd5fe6780052e809774edabb7bdcf69a6e6d9b8fd3b38bc052fa8a7d891b6c201a38fb504a07ffce2e5e8c262ef54fb8f57db62f22d353a30bc8a96"
155
155
  }