@lenne.tech/nuxt-extensions 4.0.4 → 4.0.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.
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,40 @@ 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
+ - **`useLtAuthClient().twoFactor.verify*` / `enable` / `disable`, `changePassword` and
307
+ `signIn.social` strip a non-JWT `token` from the answer**, and `authenticateWithPasskey()`
308
+ returns no `session`. Keep all of them: application code that never receives the session token
309
+ cannot store it.
310
+ - **`useLtAuthClient().twoFactor.verify*` / `enable` / `disable` and `changePassword` store a JWT
311
+ the answer carries** (`storingAnswerJwt`, since 4.0.5), strip any other token
312
+ (`withoutSessionToken`) and leave the auth mode alone. Since nest-server 12.11.0 every JWT is
313
+ bound to its session (`sid`), and turning 2FA on or off or changing the password with
314
+ `revokeOtherSessions` replaces the session. From then on the JWT stored before is refused. The starter turns 2FA on through this client, not
315
+ through `useLtAuth()`, so without the store its next request in JWT mode would carry the refused
316
+ JWT. `useLtAuth().twoFactor.verify*` takes the same JWT in `completeForwardedSignIn()`, with no
317
+ `/iam/token` request. Only `result.data` is read: with `throw: true` nothing is stored.
318
+ The store writes `document.cookie`; the composable's `useCookie` refs follow through Nuxt's
319
+ cookieStore change event, not in the same tick. The client side is held by
320
+ `test/auth-client-session-token.test.ts`, the composable side by
321
+ `test/session-token-guard.test.ts`.
298
322
 
299
323
  ### How Auth Cookies Work:
300
324
  1. `setUser()` writes the cookie via both `useCookie().value` (for SSR sync) and `document.cookie` (for immediate availability)
@@ -357,6 +381,12 @@ holds. `useLtAuthClient().signIn.social` is the same call without the auth state
357
381
  JWT from `/iam/token`, exactly as after 2FA. `withoutSessionToken` strips only `result.data`, as
358
382
  for 2FA: with `throw: true` (as `options` or in `fetchOptions`) the body comes back with the
359
383
  token, and a caller's `onSuccess` hook sees the answer before the token is removed.
384
+ **nest-server 12.11.0 closes this shape by default** (`ID_TOKEN_NOT_SUPPORTED`). A project opens
385
+ it per provider with `disableIdTokenSignIn: false`. The redirect shape is not affected.
386
+ - **`emailAndPassword` in `/iam/features`** (nest-server 12.11.0 or later): `false` means the API
387
+ offers no sign-in with email and password. The starter's login page hides the form when it
388
+ sees that; a missing field (older API) means on. `features` is a
389
+ `Record<string, boolean | number | string[]>`, so no type in this module has to change.
360
390
  - **Silent attempt: `additionalParams: { prompt: 'none' }`.** The provider answers without showing
361
391
  anything, and the way back without a provider session is `errorCallbackURL` with
362
392
  `?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,18 @@ 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
+ - **`useLtAuthClient().twoFactor.verifyTotp()`, `verifyBackupCode()`, `enable()`, `disable()`
555
+ and `changePassword()` return no session token.** A JWT in the answer stays, and the client
556
+ stores it in `lt-jwt-token` (since 4.0.5); the auth mode is left as it is. From nest-server
557
+ 12.11.0 on, every JWT is bound to its session. Turning 2FA on or off, or changing the password
558
+ with `revokeOtherSessions`, replaces that session, and the API refuses the JWT stored before. A
559
+ settings page that does this through the client keeps working in JWT mode. Turning 2FA off
560
+ needs nest-server 12.11.1 for that: 12.11.0 answers `two-factor/disable` without the new JWT.
561
+ With `throw: true` the client reads no answer and stores nothing.
549
562
  - **`authenticateWithPasskey()` returns no `session`.**
550
563
 
551
564
  #### Sign-in through a social provider
@@ -556,6 +569,10 @@ Entra ID for single sign-on (`betterAuth.socialProviders` in nest-server). `GET
556
569
  lists the enabled providers as `socialProviders`; `useLtAuth().features` holds that answer, so a
557
570
  login page can show one button per entry.
558
571
 
572
+ The same answer also reports `emailAndPassword` (nest-server 12.11.0 or later). When it is `false`,
573
+ the API offers no sign-in with email and password: hide that form, the "forgot password" link and
574
+ registration. An older API does not send the field, so treat a missing value as `true`.
575
+
559
576
  Both shapes go to `POST <basePath>/sign-in/social`:
560
577
 
561
578
  - **Redirect, the usual one.** The answer is the provider's authorization URL, and Better Auth's
@@ -568,7 +585,9 @@ Both shapes go to `POST <basePath>/sign-in/social`:
568
585
  session token Better Auth puts into that answer is removed, as in the 2FA answers. This covers
569
586
  the default `{ data, error }` answer only: with `throw: true` (as `options` or in `fetchOptions`)
570
587
  the body comes back unchanged, token included, and an `onSuccess` hook sees the answer before the
571
- token is removed.
588
+ token is removed. **nest-server 12.11.0 and later refuse this shape** with
589
+ `ID_TOKEN_NOT_SUPPORTED` unless the provider sets `disableIdTokenSignIn: false`. The redirect
590
+ shape is not affected.
572
591
 
573
592
  ```vue
574
593
  <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.5";
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.5",
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.5";
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
  }
@@ -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: {
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.5",
4
4
  "description": "Reusable Nuxt 4 composables, components, and Better-Auth integration for lenne.tech projects",
5
5
  "repository": {
6
6
  "type": "git",
@@ -113,7 +113,7 @@
113
113
  "@better-auth/passkey": "1.7.19",
114
114
  "@nuxt/module-builder": "1.0.4",
115
115
  "@nuxt/schema": "4.6.4",
116
- "@nuxt/ui": "4.12.2",
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",
@@ -123,8 +123,8 @@
123
123
  "fake-indexeddb": "6.2.8",
124
124
  "happy-dom": "21.0.4",
125
125
  "nuxt": "4.6.4",
126
- "oxfmt": "0.79.0",
127
- "oxlint": "1.94.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",