@lenne.tech/nuxt-extensions 1.24.1 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -27,7 +27,7 @@ src/
27
27
  |-----------|---------|
28
28
  | `useLtAuth()` | Authentication state, login, logout, session management, password change + reset |
29
29
  | `useLtAuthClient()` | Raw Better Auth client access (`twoFactor.*`, `admin.*`, `passkey`) |
30
- | `useSystemSetup()` | First-admin setup flow |
30
+ | `useSystemSetup()` | First-admin setup flow: status, HTTP-setup release + setup token (nest-server >= 12.4.0) |
31
31
  | `useLtTusUpload()` | TUS resumable file uploads |
32
32
  | `useLtFile()` | File utilities (size formatting, URLs) |
33
33
  | `useLtShare()` | Web Share API with clipboard fallback |
@@ -204,6 +204,31 @@ The `useLtAuth()` composable manages the `lt-auth-state` cookie for authenticati
204
204
  - Don't call `useCookie('lt-auth-state')` with different options than `useLtAuth()` uses (`maxAge: 604800, sameSite: 'lax'`)
205
205
  - Don't URL-decode or JSON-parse the cookie value manually on the server — `useCookie` handles this automatically
206
206
  - 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
207
+ - Don't store the `token` of a 2FA or passkey answer anywhere. Finish a 2FA sign-in with `useLtAuth().twoFactor.verifyTotp()` / `verifyBackupCode()`.
208
+
209
+ ### The session token never reaches `lt-jwt-token`:
210
+ Better-Auth answers `two-factor/verify-totp` and `verify-backup-code` with `{ token, user }`, and
211
+ `passkey/verify-authentication` with `{ session, user }`; nest-server forwards these routes
212
+ unchanged. That token is the session token, the value the API keeps in the httpOnly
213
+ `iam.session_token` cookie. The starter's 2FA page stored it as the "JWT" in the readable
214
+ `lt-jwt-token` cookie, so one XSS was enough to take the session for its whole lifetime
215
+ (nuxt-extensions 1.26.0 closes it).
216
+
217
+ - **`lt-jwt-token` holds a JWT or nothing.** The `jwtToken` ref, `setLtJwtToken()`,
218
+ `switchToJwtMode()`, `attemptLtJwtSwitch()` and `signIn` / `signUp` take a value only when
219
+ `isLtJwtShaped()` says so. That is the same test as nest-server's `isJwtShaped`: three segments,
220
+ header `eyJ`. Test fixtures need JWT-shaped tokens too; `'a.b.c'` is refused.
221
+ - **A JWT comes from `GET /iam/token`, or from a body the server already converted** (sign-in with
222
+ `cookies: false`; nest-server's `resolveJwtToken` never returns the session token there).
223
+ - **Anything else found in `lt-jwt-token` is deleted** on start (`useLtAuth()`) and on read
224
+ (`getLtJwtToken()`), along with its JWT mode, because leaked values from before 1.26.0 are
225
+ still in users' browsers. Never write such a value there "temporarily".
226
+ - **`setUser(user, 'jwt')` without a stored JWT falls back to `'cookie'`** and fetches the JWT.
227
+ Without that fallback, the refusal above would turn a hand-written 2FA page into a sign-in that
228
+ sends no credentials at all.
229
+ - **`useLtAuthClient().twoFactor.verify*` strips a non-JWT `token` from the answer**, and
230
+ `authenticateWithPasskey()` returns no `session`. Keep both: application code that never
231
+ receives the session token cannot store it.
207
232
 
208
233
  ### How Auth Cookies Work:
209
234
  1. `setUser()` writes the cookie via both `useCookie().value` (for SSR sync) and `document.cookie` (for immediate availability)
@@ -311,7 +336,8 @@ This is a consequence of client-side hashing, not a bug in either backend, and t
311
336
  ### `admin.*` is passed through UNHASHED — an armed trap, not a live one
312
337
 
313
338
  `admin.createUser` (`password`) and `admin.setUserPassword` (`newPassword`) are the only
314
- credential-carrying methods this library does **not** hash.
339
+ passwords this library does **not** hash. (The setup token of `useSystemSetup().initSetup()` is
340
+ unhashed too, by design — see "First Admin Setup" below.)
315
341
 
316
342
  Today that is harmless: `@lenne.tech/nest-server` does not register better-auth's `admin()`
317
343
  plugin and has no option to enable it, so those routes 404. But `auth.enableAdmin` defaults to
@@ -333,6 +359,28 @@ replaces ONE field and forwards the rest — `{ ...params, password: hashed }`.
333
359
  shipped defects), and never `{ password: hashed, ...params }`, which looks almost identical and
334
360
  puts the **plaintext** back on the wire.
335
361
 
362
+ ## First Admin Setup: the HTTP init is closed on deployed stages
363
+
364
+ Since nest-server 12.4.0 the anonymous `POST /system-setup/init` is open only in `local`, `ci` and
365
+ `e2e`. A deployed API refuses it with 403 (`LTNS_0053`) unless `systemSetup.httpInit` releases it,
366
+ optionally behind a setup token (`LTNS_0054` when wrong). `GET /system-setup/status` reports
367
+ `httpInitEnabled` and `httpInitTokenRequired`; `useSystemSetup()` exposes both.
368
+
369
+ - **The middleware does not redirect when `httpInitEnabled === false`.** That is deliberate, not a
370
+ bug: a redirect would hold every visitor on a page whose only action fails, and the login would be
371
+ unreachable. The setup page itself must show the notice ("first admin comes from the
372
+ configuration") instead of the form.
373
+ - **The token is a header (`X-System-Setup-Token`), unhashed, never a body field.** Unlike the
374
+ passwords, it is not hashed: the server compares it as given. Do not add it to the SHA256
375
+ wrappers.
376
+ - **A missing field means an API before 12.4.0**, which accepts the HTTP setup: `httpInitEnabled`
377
+ reads `true`. The server's 403 is the boundary, the flag is UX. Only a 200 without the field
378
+ counts as old; a failed status read leaves both values unchanged (`null` initially).
379
+ - **After a 403 from `initSetup()` the composable re-reads the status** before rethrowing, so the
380
+ page switches to the notice or the token field when the API was restarted with another
381
+ configuration. Pass the error itself to `translateError(error)`: the `#LTNS_` code is in the
382
+ body, `error.message` holds only the transport line.
383
+
336
384
  ## Form Label Repair
337
385
 
338
386
  **The defect:** Nuxt UI's `FormField` derives the label's `for` and the control's `id` from one
@@ -436,7 +484,24 @@ fields at `app:beforeMount` and restores them at `app:mounted`, dispatching a sy
436
484
  - **nuxt-base-starter lints `app/core/**` with a subset of the plugins in `.oxlintrc.json`, never
437
485
  more**, and `lint` here runs with `--deny-warnings`. A plugin only the starter applies reports its
438
486
  warnings in every generated project after the release; the 1.24.0 smoke test found three. A plugin
439
- the starter wants for `app/core/**` is added here first.
487
+ the starter wants for `app/core/**` is added here first. `check:vendored-core` (part of `check`)
488
+ holds this: it copies `src/` into a temporary `app/core/` the way `lt fullstack init` does and lints
489
+ it with the template's current `.oxlintrc.json` from GitHub, `--deny-warnings`. Red without a change
490
+ here means the template now applies more to the core; offline it fails rather than passing unseen
491
+ (`LT_TEMPLATE_OXLINTRC=<path>` lints against a local copy).
492
+ - **A version this repository shares with nuxt-base-template is raised in the template first.**
493
+ `lt fullstack init` raises every shared version to this repository's when that is newer, so a
494
+ vendor-mode project gets versions the template's own `check` never ran with: vue-tsc 3.3.14 broke
495
+ a template component after 1.24.0, partly with exit 0. `check:template-pins` (part of `check`)
496
+ applies the CLI's rule to the template's `package.json` on GitHub and fails on every version
497
+ vendoring would raise. When it does, raise the version in nuxt-base-starter (whose `check` runs
498
+ the type check, lint and tests with it), or keep this repository on the template's version until
499
+ then. Offline it fails; `LT_TEMPLATE_PACKAGE_JSON=<path>` compares against a local copy.
500
+ The stack publishes this repository before the starter, so a release here must not wait for the
501
+ template: `scripts/template-pins-pending.json` allows one named version per package until the
502
+ starter release that brings the template along (`"vue-tsc": { "to": "3.3.15",
503
+ "templateFollowsIn": "2.38.0" }`). That release coming out without it fails `check`, and so does
504
+ an entry nobody needs any more: remove it once the template has the version.
440
505
  - **The `nuxt/schema` blocks in `runtime/types/module.ts` augment `PublicRuntimeConfig` and nothing
441
506
  else.** Vendoring turns them into project source, where they cause TS2310, and the cli removes a
442
507
  block only while it holds that one interface. Type server-only config where it is read.
package/README.md CHANGED
@@ -462,11 +462,23 @@ const {
462
462
  resetPassword,
463
463
  } = useLtAuth();
464
464
 
465
- // Login with email/password
465
+ // Login with email/password. For an account with 2FA, nest-server answers
466
+ // `{ requiresTwoFactor: true }` (Better-Auth's own `twoFactorRedirect` makes the two-factor
467
+ // client plugin navigate to `auth.twoFactorRedirectPath` by itself; nest-server does not send it).
466
468
  async function handleLogin(email: string, password: string) {
467
- const result = await signIn.email({ email, password });
468
- if (result.requiresTwoFactor) {
469
- navigateTo('/auth/2fa');
469
+ const { data } = (await signIn.email({ email, password })) as {
470
+ data?: { requiresTwoFactor?: boolean; twoFactorRedirect?: boolean } | null;
471
+ };
472
+ if (data?.requiresTwoFactor || data?.twoFactorRedirect) {
473
+ await navigateTo('/auth/2fa');
474
+ }
475
+ }
476
+
477
+ // On the 2FA page: finishes the sign-in (user, cookie session, JWT from /iam/token)
478
+ async function handleTotp(code: string) {
479
+ const { error } = (await twoFactor.verifyTotp({ code })) as { error?: { message?: string } | null };
480
+ if (!error) {
481
+ navigateTo('/dashboard');
470
482
  }
471
483
  }
472
484
 
@@ -487,6 +499,29 @@ async function handlePasskeyLogin() {
487
499
  </template>
488
500
  ```
489
501
 
502
+ #### Two-factor sign-in, and what `lt-jwt-token` may hold
503
+
504
+ Finish a sign-in that stopped at the second factor with `useLtAuth().twoFactor.verifyTotp()` or
505
+ `verifyBackupCode()`. They put the user into the auth state on the cookie session and fetch the
506
+ JWT from `/iam/token`.
507
+
508
+ - **Never store the `token` of a 2FA or passkey answer.** Better-Auth answers `verify-totp` and
509
+ `verify-backup-code` with `{ token, user }`, and `passkey/verify-authentication` with
510
+ `{ session, user }`. That token is its session token, the value the API keeps in the httpOnly
511
+ cookie. Stored as the "JWT", it lands in the readable `lt-jwt-token` cookie, where any script
512
+ on the page can take it for the session's whole lifetime.
513
+ - **`lt-jwt-token` holds a JWT or nothing.** `jwtToken`, `setLtJwtToken()` and the sign-in
514
+ methods refuse anything else; `isLtJwtShaped()` (from `/lib`) is the test, the same as
515
+ nest-server's `isJwtShaped`.
516
+ - **A value found there that is not a JWT is deleted** on the next start or read, along with the
517
+ JWT mode it came with. The httpOnly session cookie keeps the user signed in.
518
+ - **`setUser(user, 'jwt')` without a stored JWT signs in on the cookie session** and fetches the
519
+ JWT. A hand-written 2FA page that stored the body token therefore still works, without the
520
+ leak; move it to the helpers anyway.
521
+ - **`useLtAuthClient().twoFactor.verifyTotp()` / `verifyBackupCode()` no longer return the
522
+ session token.**
523
+ - **`authenticateWithPasskey()` returns no `session`.**
524
+
490
525
  #### Admin detection (`role` vs `roles`)
491
526
 
492
527
  `isAdmin` accepts **both** user shapes, so the same frontend works against either backend:
@@ -567,6 +602,51 @@ against the value it receives, and because this library hashes first, that value
567
602
  64-character hex string — the check passes on every path. The form is the only place the rule can
568
603
  live.
569
604
 
605
+ ### First Admin Setup
606
+
607
+ With `auth.systemSetup.enabled`, a global middleware sends visitors to `setupPath` while the API
608
+ has no user yet, and `useSystemSetup()` creates the first admin.
609
+
610
+ Since `@lenne.tech/nest-server` 12.4.0 the anonymous `POST /system-setup/init` is open only in
611
+ `local`, `ci` and `e2e`. A deployed API refuses it with 403 (`LTNS_0053`) unless the deployment
612
+ releases it (`systemSetup.httpInit`), optionally behind a setup token. A deployment usually creates
613
+ its first admin from its configuration instead (`systemSetup.initialAdmin`).
614
+ `GET /system-setup/status` reports which applies, and the composable exposes it:
615
+
616
+ ```vue
617
+ <script setup lang="ts">
618
+ const { httpInitEnabled, httpInitTokenRequired, initSetup } = useSystemSetup();
619
+ const { translateError } = useLtErrorTranslation();
620
+ const toast = useToast();
621
+
622
+ async function onSubmit(data: { email: string; name: string; password: string; token?: string }) {
623
+ try {
624
+ // `token` goes out as the X-System-Setup-Token header, unhashed; omit it when not required.
625
+ await initSetup(data);
626
+ } catch (error) {
627
+ // Pass the error itself: the #LTNS_ code is in the response body, not in `error.message`.
628
+ toast.add({ color: 'error', description: translateError(error), title: 'Setup failed' });
629
+ }
630
+ }
631
+ </script>
632
+
633
+ <template>
634
+ <!-- `false`: the deployment creates its first admin from its configuration — no form. -->
635
+ <SetupNotice v-if="httpInitEnabled === false" />
636
+ <SetupForm v-else :with-token="httpInitTokenRequired === true" @submit="onSubmit" />
637
+ </template>
638
+ ```
639
+
640
+ - **Without the HTTP setup the middleware redirects nowhere.** A redirect would hold every visitor
641
+ on a page whose only action fails. The setup page stays reachable, so it must show the notice
642
+ itself.
643
+ - **An API before 12.4.0** reports neither field and accepts the HTTP setup, so `httpInitEnabled`
644
+ reads `true` and `httpInitTokenRequired` `false` — the behaviour before this release.
645
+ - **After a 403 from `initSetup()`** the composable re-reads the status before rethrowing, so a page
646
+ whose API was restarted with another configuration switches to the notice (`LTNS_0053`) or to the
647
+ token field (`LTNS_0054`) without a reload.
648
+ - `null` means the status was not read yet, or reading it failed.
649
+
570
650
  ### Custom Better Auth Plugins
571
651
 
572
652
  You can extend the auth client with additional [Better Auth plugins](https://www.better-auth.com/docs/plugins):
@@ -975,7 +1055,7 @@ The package works **with or without** `@nuxtjs/i18n`:
975
1055
  | `useLtTusUpload()` | TUS protocol file uploads with pause/resume |
976
1056
  | `useLtFile()` | File utilities (size formatting, URLs) |
977
1057
  | `useLtShare()` | Web Share API with clipboard fallback |
978
- | `useSystemSetup()` | System setup flow for initial admin user creation |
1058
+ | `useSystemSetup()` | First admin creation: setup status, HTTP-setup release + token (nest-server >= 12.4.0) |
979
1059
  | `useLtAi()` | One-shot `prompt()` + streaming `promptStream()` for the nest-server AI module |
980
1060
  | `useLtAiChat()` | Multi-turn chat state, streaming, budget summary, confirmation gate, `maxMessages` cap |
981
1061
  | `useLtAiConnections()` | User self-service connection list + `select()` |
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 = "1.24.1";
6
+ declare const version = "1.26.0";
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": "1.24.1",
4
+ "version": "1.26.0",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
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 = "1.24.1";
6
+ const version = "1.26.0";
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";
@@ -1,6 +1,6 @@
1
1
  import { useNuxtApp, useCookie, useState, useRequestHeaders, useRuntimeConfig, ref, computed, watch } from "#imports";
2
2
  import { ltArrayBufferToBase64Url, ltBase64UrlToUint8Array } from "../../utils/crypto.js";
3
- import { clearLtAuthCookies, getLtApiBase, getLtAuthCookieNames, resolveLtAuthState } from "../../lib/auth-state.js";
3
+ import { clearLtAuthCookies, getLtApiBase, getLtAuthCookieNames, getLtJwtToken, isLtJwtShaped, resolveLtAuthState } from "../../lib/auth-state.js";
4
4
  import { useLtAuthClient } from "../use-lt-auth-client.js";
5
5
  const VALIDATE_SESSION_TIMEOUT_MS = 1e4;
6
6
  const LT_SYNC_SIGN_OUT_FLUSH_MS = 5e3;
@@ -42,17 +42,31 @@ export function useLtAuth() {
42
42
  }
43
43
  }
44
44
  const ssrCookieHeader = import.meta.server ? useRequestHeaders(["cookie"]).cookie || "" : "";
45
- const jwtToken = useCookie(tokenCookieName, {
45
+ const jwtTokenCookie = useCookie(tokenCookieName, {
46
46
  maxAge: 60 * 60 * 24 * 7,
47
47
  // 7 days
48
48
  sameSite: "lax"
49
49
  });
50
+ const jwtToken = computed({
51
+ get: () => isLtJwtShaped(jwtTokenCookie.value) ? jwtTokenCookie.value : null,
52
+ set: (value) => {
53
+ jwtTokenCookie.value = isLtJwtShaped(value) ? value : null;
54
+ }
55
+ });
50
56
  const isLoading = ref(false);
51
57
  const resolvedAuthState = computed(() => {
52
58
  const refVal = authState.value;
53
59
  const cookieString = import.meta.client ? document.cookie : ssrCookieHeader;
54
60
  return resolveLtAuthState(cookieString, stateCookieName) ?? refVal ?? null;
55
61
  });
62
+ if (import.meta.client && jwtTokenCookie.value && !isLtJwtShaped(jwtTokenCookie.value)) {
63
+ jwtTokenCookie.value = null;
64
+ getLtJwtToken();
65
+ const resolved = resolveLtAuthState(document.cookie, stateCookieName) ?? authState.value;
66
+ if (resolved?.authMode === "jwt") {
67
+ setUser(resolved.user ?? null, "cookie");
68
+ }
69
+ }
56
70
  const authMode = computed(() => resolvedAuthState.value?.authMode || "cookie");
57
71
  const isJwtMode = computed(() => authMode.value === "jwt");
58
72
  const user = computed(() => resolvedAuthState.value?.user ?? null);
@@ -71,7 +85,11 @@ export function useLtAuth() {
71
85
  const is2FAEnabled = computed(() => user.value?.twoFactorEnabled ?? false);
72
86
  const features = useState("lt-auth-features", () => ({}));
73
87
  const featuresFetched = useState("lt-auth-features-fetched", () => false);
74
- function setUser(userData, mode = "cookie") {
88
+ function setUser(userData, requestedMode = "cookie") {
89
+ const mode = requestedMode === "jwt" && !jwtToken.value ? "cookie" : requestedMode;
90
+ if (mode !== requestedMode && import.meta.client && userData) {
91
+ void switchToJwtMode();
92
+ }
75
93
  const normalised = userData ? { ...userData, image: userData.image ?? void 0 } : null;
76
94
  const newState = { user: normalised, authMode: mode };
77
95
  if (import.meta.client || userData) {
@@ -105,7 +123,7 @@ export function useLtAuth() {
105
123
  });
106
124
  if (response.ok) {
107
125
  const data = await response.json();
108
- if (data.token) {
126
+ if (isLtJwtShaped(data.token)) {
109
127
  jwtToken.value = data.token;
110
128
  if (authState.value) {
111
129
  authState.value = { ...authState.value, authMode: "jwt" };
@@ -256,7 +274,7 @@ export function useLtAuth() {
256
274
  const resultAny = result;
257
275
  const token = resultAny?.token || resultAny?.data?.token;
258
276
  const userData = resultAny?.user || resultAny?.data?.user;
259
- if (token) {
277
+ if (isLtJwtShaped(token)) {
260
278
  jwtToken.value = token;
261
279
  if (userData) {
262
280
  setUser(userData, "jwt");
@@ -281,7 +299,7 @@ export function useLtAuth() {
281
299
  const resultAny = result;
282
300
  const token = resultAny?.token || resultAny?.data?.token;
283
301
  const userData = resultAny?.user || resultAny?.data?.user;
284
- if (token) {
302
+ if (isLtJwtShaped(token)) {
285
303
  jwtToken.value = token;
286
304
  if (userData) {
287
305
  setUser(userData, "jwt");
@@ -365,31 +383,25 @@ export function useLtAuth() {
365
383
  error: result.message || t("lt.auth.passkeyFailed", "Passkey-Anmeldung fehlgeschlagen")
366
384
  };
367
385
  }
368
- if (result.user) {
369
- setUser(result.user, "cookie");
370
- switchToJwtMode().catch(() => {
371
- });
372
- } else if (result.session?.token) {
373
- jwtToken.value = result.session.token;
374
- if (authState.value) {
375
- authState.value = { ...authState.value, authMode: "jwt" };
376
- }
386
+ let signedInUser = result.user;
387
+ if (!signedInUser && result.session) {
377
388
  try {
378
389
  const sessionResponse = await fetchWithAuth(`${apiBase}/get-session`, { method: "GET" });
379
390
  if (sessionResponse.ok) {
380
391
  const sessionData = await sessionResponse.json();
381
392
  if (sessionData?.user) {
382
- const mergedUser = mergeSessionUser(sessionData.user);
383
- result.user = mergedUser;
384
- setUser(mergedUser, "cookie");
385
- switchToJwtMode().catch(() => {
386
- });
393
+ signedInUser = mergeSessionUser(sessionData.user);
387
394
  }
388
395
  }
389
396
  } catch {
390
397
  }
391
398
  }
392
- return { success: true, user: result.user, session: result.session };
399
+ if (signedInUser) {
400
+ setUser(signedInUser, "cookie");
401
+ switchToJwtMode().catch(() => {
402
+ });
403
+ }
404
+ return { success: true, user: signedInUser };
393
405
  } catch (err) {
394
406
  if (err instanceof Error && err.name === "NotAllowedError") {
395
407
  return {
@@ -506,6 +518,35 @@ export function useLtAuth() {
506
518
  isLoading.value = false;
507
519
  }
508
520
  }
521
+ async function completeTwoFactorSignIn(result) {
522
+ const answer = result;
523
+ const data = answer?.data;
524
+ if (answer?.error || !data?.user) {
525
+ return;
526
+ }
527
+ if (isLtJwtShaped(data.token)) {
528
+ jwtToken.value = data.token;
529
+ setUser(data.user, "jwt");
530
+ return;
531
+ }
532
+ setUser(data.user, "cookie");
533
+ await switchToJwtMode();
534
+ }
535
+ const verifyingTwoFactor = (method) => async (params, options) => {
536
+ isLoading.value = true;
537
+ try {
538
+ const result = await authClient.twoFactor[method](params, options);
539
+ await completeTwoFactorSignIn(result);
540
+ return result;
541
+ } finally {
542
+ isLoading.value = false;
543
+ }
544
+ };
545
+ const twoFactor = {
546
+ ...authClient.twoFactor,
547
+ verifyBackupCode: verifyingTwoFactor("verifyBackupCode"),
548
+ verifyTotp: verifyingTwoFactor("verifyTotp")
549
+ };
509
550
  if (import.meta.client && !featuresFetched.value) {
510
551
  featuresFetched.value = true;
511
552
  void fetchFeatures();
@@ -557,6 +598,6 @@ export function useLtAuth() {
557
598
  switchToJwtMode,
558
599
  // Better Auth client passthrough
559
600
  passkey: authClient.passkey,
560
- twoFactor: authClient.twoFactor
601
+ twoFactor
561
602
  };
562
603
  }
@@ -12,13 +12,27 @@ import type { ComputedRef } from 'vue';
12
12
  export interface UseSystemSetupReturn {
13
13
  /** Whether the system needs initial setup (null = not checked yet) */
14
14
  needsSetup: ComputedRef<boolean | null>;
15
+ /**
16
+ * Whether the API accepts the setup over HTTP (null = not checked yet). `false` means the
17
+ * deployment creates its first admin from its configuration, and `initSetup()` would be
18
+ * refused with 403 (`LTNS_0053`): show a notice instead of the form. An API before
19
+ * nest-server 12.4.0 does not report it and accepts the HTTP setup, so it reads as `true`.
20
+ */
21
+ httpInitEnabled: ComputedRef<boolean | null>;
22
+ /** Whether `initSetup()` needs a `token` (null = not checked yet). Only an explicit `true` counts. */
23
+ httpInitTokenRequired: ComputedRef<boolean | null>;
15
24
  /** Check setup status from the backend */
16
25
  checkSetupStatus: () => Promise<boolean>;
17
- /** Initialize the system with the first admin user */
26
+ /**
27
+ * Initialize the system with the first admin user. `token` is the setup token, required when
28
+ * `httpInitTokenRequired` is true. A refusal is rethrown unchanged, so `useLtErrorTranslation()`
29
+ * reads its code (`LTNS_0053` HTTP setup disabled, `LTNS_0054` wrong token) from the body.
30
+ */
18
31
  initSetup: (params: {
19
32
  email: string;
20
33
  password: string;
21
34
  name: string;
35
+ token?: string;
22
36
  }) => Promise<void>;
23
37
  }
24
38
  /**
@@ -26,11 +40,11 @@ export interface UseSystemSetupReturn {
26
40
  *
27
41
  * @example
28
42
  * ```typescript
29
- * const { needsSetup, checkSetupStatus, initSetup } = useSystemSetup();
43
+ * const { needsSetup, httpInitEnabled, httpInitTokenRequired, checkSetupStatus, initSetup } = useSystemSetup();
30
44
  *
31
45
  * await checkSetupStatus();
32
- * if (needsSetup.value) {
33
- * await initSetup({ email: 'admin@example.com', password: 'secret', name: 'Admin' });
46
+ * if (needsSetup.value && httpInitEnabled.value) {
47
+ * await initSetup({ email: 'admin@example.com', password: 'secret', name: 'Admin', token });
34
48
  * }
35
49
  * ```
36
50
  */
@@ -8,9 +8,17 @@ function isApiUrlMissing() {
8
8
  return true;
9
9
  }
10
10
  }
11
+ const SETUP_TOKEN_HEADER = "X-System-Setup-Token";
12
+ function isRefusal(error) {
13
+ const { status, statusCode } = error ?? {};
14
+ return (statusCode ?? status) === 403;
15
+ }
11
16
  export function useSystemSetup() {
12
17
  const needsSetupState = useState("lt-needs-setup", () => null);
18
+ const httpInitState = useState("lt-system-setup-http-init", () => null);
13
19
  const needsSetup = computed(() => needsSetupState.value);
20
+ const httpInitEnabled = computed(() => httpInitState.value?.enabled ?? null);
21
+ const httpInitTokenRequired = computed(() => httpInitState.value?.tokenRequired ?? null);
14
22
  async function checkSetupStatus() {
15
23
  if (import.meta.server && isApiUrlMissing()) {
16
24
  warnMissingLtApiUrl("server");
@@ -19,6 +27,12 @@ export function useSystemSetup() {
19
27
  try {
20
28
  const url = buildLtApiUrl("/system-setup/status");
21
29
  const data = await $fetch(url);
30
+ httpInitState.value = {
31
+ // Missing or malformed reads as released: an API before 12.4.0 accepts the HTTP setup,
32
+ // and the server's 403 is the boundary, not this flag.
33
+ enabled: typeof data.httpInitEnabled === "boolean" ? data.httpInitEnabled : true,
34
+ tokenRequired: data.httpInitTokenRequired === true
35
+ };
22
36
  needsSetupState.value = data.needsSetup;
23
37
  return data.needsSetup;
24
38
  } catch {
@@ -29,18 +43,29 @@ export function useSystemSetup() {
29
43
  async function initSetup(params) {
30
44
  const url = buildLtApiUrl("/system-setup/init");
31
45
  const hashedPassword = await ltSha256(params.password);
32
- await $fetch(url, {
33
- method: "POST",
34
- body: {
35
- email: params.email,
36
- password: hashedPassword,
37
- name: params.name
46
+ const token = params.token?.trim();
47
+ try {
48
+ await $fetch(url, {
49
+ method: "POST",
50
+ body: {
51
+ email: params.email,
52
+ password: hashedPassword,
53
+ name: params.name
54
+ },
55
+ ...token ? { headers: { [SETUP_TOKEN_HEADER]: token } } : {}
56
+ });
57
+ } catch (error) {
58
+ if (isRefusal(error)) {
59
+ await checkSetupStatus();
38
60
  }
39
- });
61
+ throw error;
62
+ }
40
63
  needsSetupState.value = false;
41
64
  }
42
65
  return {
43
66
  needsSetup,
67
+ httpInitEnabled,
68
+ httpInitTokenRequired,
44
69
  checkSetupStatus,
45
70
  initSetup
46
71
  };
@@ -323,31 +323,7 @@ export declare function createLtAuthClient(config?: LtAuthClientConfig): {
323
323
  headers?: {} | {
324
324
  [x: string]: string | undefined;
325
325
  accept?: ((string & {}) | "application/json" | "text/plain" | "application/octet-stream") | undefined;
326
- "content-type"
327
- /**
328
- * Register additional Better Auth plugins before auth client initialization.
329
- *
330
- * Call this in a Nuxt plugin (client-side) or in app.vue setup before
331
- * the auth client is used.
332
- *
333
- * If the auth client was already created, it will be automatically recreated
334
- * with the new plugins on next access.
335
- *
336
- * @example
337
- * ```typescript
338
- * // plugins/auth-plugins.client.ts
339
- * import { registerLtAuthPlugins } from '@lenne.tech/nuxt-extensions/lib';
340
- * import { organizationClient, magicLinkClient } from 'better-auth/client/plugins';
341
- *
342
- * export default defineNuxtPlugin(() => {
343
- * registerLtAuthPlugins([
344
- * organizationClient(),
345
- * magicLinkClient(),
346
- * ]);
347
- * });
348
- * ```
349
- */
350
- ?: ((string & {}) | "application/x-www-form-urlencoded" | "application/json" | "text/plain" | "application/octet-stream" | "multipart/form-data") | undefined;
326
+ "content-type"?: ((string & {}) | "application/x-www-form-urlencoded" | "application/json" | "text/plain" | "application/octet-stream" | "multipart/form-data") | undefined;
351
327
  authorization?: ((string & {}) | `Bearer ${string}` | `Basic ${string}`) | undefined;
352
328
  } | undefined;
353
329
  body?: any;
@@ -794,13 +770,14 @@ export declare function createLtAuthClient(config?: LtAuthClientConfig): {
794
770
  password: string;
795
771
  }>(params: T, options?: any) => Promise<any>;
796
772
  /**
797
- * Verify TOTP code (pass through to base client)
773
+ * Verify TOTP code. The session token Better-Auth puts into the answer is removed first,
774
+ * see {@link withoutSessionToken}.
798
775
  */
799
- verifyTotp: any;
776
+ verifyTotp: (...args: unknown[]) => Promise<any>;
800
777
  /**
801
- * Verify backup code (pass through to base client)
778
+ * Verify backup code. Same as `verifyTotp`.
802
779
  */
803
- verifyBackupCode: any;
780
+ verifyBackupCode: (...args: unknown[]) => Promise<any>;
804
781
  };
805
782
  };
806
783
  export type LtAuthClient = ReturnType<typeof createLtAuthClient>;
@@ -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 } from "./auth-state.js";
6
+ import { createLtAuthFetch, isLocalDevApiProxy, isLtJwtShaped } from "./auth-state.js";
7
7
  let _ltAuthPluginRegistry = [];
8
8
  let _pluginsChangedAfterCreation = false;
9
9
  let _authClientSingleton = null;
@@ -231,13 +231,21 @@ export function createLtAuthClient(config = {}) {
231
231
  return baseClient.twoFactor.generateBackupCodes({ ...params, password: hashedPassword }, options);
232
232
  },
233
233
  /**
234
- * Verify TOTP code (pass through to base client)
234
+ * Verify TOTP code. The session token Better-Auth puts into the answer is removed first,
235
+ * see {@link withoutSessionToken}.
235
236
  */
236
- verifyTotp: baseClient.twoFactor.verifyTotp,
237
+ verifyTotp: async (...args) => withoutSessionToken(await baseClient.twoFactor.verifyTotp(...args)),
237
238
  /**
238
- * Verify backup code (pass through to base client)
239
+ * Verify backup code. Same as `verifyTotp`.
239
240
  */
240
- verifyBackupCode: baseClient.twoFactor.verifyBackupCode
241
+ verifyBackupCode: async (...args) => withoutSessionToken(await baseClient.twoFactor.verifyBackupCode(...args))
241
242
  }
242
243
  };
243
244
  }
245
+ function withoutSessionToken(result) {
246
+ const data = result?.data;
247
+ if (data && typeof data === "object" && "token" in data && !isLtJwtShaped(data.token)) {
248
+ delete data.token;
249
+ }
250
+ return result;
251
+ }
@@ -216,11 +216,29 @@ export declare function buildLtApiUrl(path: string): string;
216
216
  */
217
217
  export declare function getLtAuthMode(): LtAuthMode;
218
218
  /**
219
- * Get the JWT token from cookie
219
+ * Whether `value` has the shape of a JWT: three dot-separated segments, the header starting with
220
+ * `eyJ` (base64url of `{"`). The same test as nest-server's `isJwtShaped`
221
+ * (`core-better-auth-token.helper.ts`), so client and server agree about one token.
222
+ *
223
+ * The token cookie (`lt-jwt-token`) is readable by every script on the page, so it may hold a JWT
224
+ * and nothing else. Better-Auth's opaque session token (what the API keeps in the httpOnly
225
+ * `iam.session_token` cookie) also turns up in response bodies: `two-factor/verify-totp` and
226
+ * `verify-backup-code` answer `{ token, user }`, `passkey/verify-authentication` answers
227
+ * `{ session, user }`. Stored as the "JWT", it was one XSS away from the attacker, for the
228
+ * session's whole lifetime.
229
+ */
230
+ export declare function isLtJwtShaped(value: unknown): value is string;
231
+ /**
232
+ * Get the JWT token from cookie.
233
+ *
234
+ * Anything in the token cookie that is not a JWT is deleted, not returned: a session token an
235
+ * earlier version (or a hand-written 2FA page) stored there stays readable by any script until
236
+ * it expires, so it is removed on the first read.
220
237
  */
221
238
  export declare function getLtJwtToken(): string | null;
222
239
  /**
223
- * Set JWT token in cookie
240
+ * Set JWT token in cookie. A value that is not a JWT is refused and clears the cookie instead
241
+ * (see {@link isLtJwtShaped}).
224
242
  */
225
243
  export declare function setLtJwtToken(token: string | null): void;
226
244
  /**
@@ -115,6 +115,17 @@ export function getLtAuthMode() {
115
115
  if (import.meta.server) return "cookie";
116
116
  return resolveLtAuthState(document.cookie)?.authMode || "cookie";
117
117
  }
118
+ export function isLtJwtShaped(value) {
119
+ return typeof value === "string" && value.startsWith("eyJ") && value.split(".").length === 3;
120
+ }
121
+ function expireLtJwtTokenCookie(tokenCookieName) {
122
+ const secure = globalThis.location?.protocol === "https:" ? "; secure" : "";
123
+ const host = globalThis.location?.hostname;
124
+ document.cookie = `${tokenCookieName}=; path=/; max-age=0; samesite=lax${secure}`;
125
+ if (host) {
126
+ document.cookie = `${tokenCookieName}=; path=/; max-age=0; samesite=lax${secure}; domain=${host}`;
127
+ }
128
+ }
118
129
  export function getLtJwtToken() {
119
130
  if (import.meta.server) return null;
120
131
  try {
@@ -124,9 +135,13 @@ export function getLtJwtToken() {
124
135
  if (!row.startsWith(cookiePrefix)) continue;
125
136
  const raw = decodeURIComponent(row.slice(cookiePrefix.length));
126
137
  const value = raw.startsWith('"') && raw.endsWith('"') ? JSON.parse(raw) : raw;
127
- if (value) {
128
- return value;
138
+ if (!value) continue;
139
+ if (!isLtJwtShaped(value)) {
140
+ expireLtJwtTokenCookie(tokenCookieName);
141
+ if (getLtAuthMode() === "jwt") setLtAuthMode("cookie");
142
+ return null;
129
143
  }
144
+ return value;
130
145
  }
131
146
  } catch {
132
147
  }
@@ -137,10 +152,10 @@ export function setLtJwtToken(token) {
137
152
  const { token: tokenCookieName } = getLtAuthCookieNames();
138
153
  const maxAge = 60 * 60 * 24 * 7;
139
154
  const secure = globalThis.location?.protocol === "https:" ? "; secure" : "";
140
- if (token) {
155
+ if (token && isLtJwtShaped(token)) {
141
156
  document.cookie = `${tokenCookieName}=${encodeURIComponent(JSON.stringify(token))}; path=/; max-age=${maxAge}; samesite=lax${secure}`;
142
157
  } else {
143
- document.cookie = `${tokenCookieName}=; path=/; max-age=0; samesite=lax${secure}`;
158
+ expireLtJwtTokenCookie(tokenCookieName);
144
159
  }
145
160
  }
146
161
  export function clearLtAuthCookies() {
@@ -198,7 +213,7 @@ export async function attemptLtJwtSwitch(basePath = "/iam") {
198
213
  });
199
214
  if (response.ok) {
200
215
  const data = await response.json();
201
- if (data.token) {
216
+ if (isLtJwtShaped(data.token)) {
202
217
  setLtJwtToken(data.token);
203
218
  setLtAuthMode("jwt");
204
219
  console.debug("[LtAuth] Switched to JWT mode");
@@ -1,4 +1,4 @@
1
- export { attemptLtJwtSwitch, clearLtAuthCookies, createLtAuthFetch, getLtApiBase, getLtAuthCookieNames, getLtAuthMode, getLtJwtToken, isLtAuthenticated, LT_AUTH_STATE_COOKIE_DEFAULT, LT_JWT_TOKEN_COOKIE_DEFAULT, ltAuthFetch, setLtAuthMode, setLtJwtToken, } from './auth-state.js';
1
+ export { attemptLtJwtSwitch, clearLtAuthCookies, createLtAuthFetch, getLtApiBase, getLtAuthCookieNames, getLtAuthMode, getLtJwtToken, isLtAuthenticated, isLtJwtShaped, LT_AUTH_STATE_COOKIE_DEFAULT, LT_JWT_TOKEN_COOKIE_DEFAULT, ltAuthFetch, setLtAuthMode, setLtJwtToken, } from './auth-state.js';
2
2
  export { clearLtAuthPluginRegistry, createLtAuthClient, getOrCreateLtAuthClient, getLtAuthPluginRegistry, registerLtAuthPlugins, resetLtAuthClientSingleton, type LtAuthClient, } from './auth-client.js';
3
3
  export { buildLtAiUrl, getLtAiBasePath, ltAiRequest, ltAiResponseError, parseLtAiSseStream } from './ai.js';
4
4
  export { buildLtSyncUrl, flushLtSyncBeforeSignOut, getLtSyncBasePath, ltSyncObjectId, ltSyncUuidV7 } from './sync.js';
@@ -7,6 +7,7 @@ export {
7
7
  getLtAuthMode,
8
8
  getLtJwtToken,
9
9
  isLtAuthenticated,
10
+ isLtJwtShaped,
10
11
  LT_AUTH_STATE_COOKIE_DEFAULT,
11
12
  LT_JWT_TOKEN_COOKIE_DEFAULT,
12
13
  ltAuthFetch,
@@ -5,8 +5,15 @@
5
5
  * needs initial setup (no admin user exists yet).
6
6
  *
7
7
  * - needsSetup === null -> calls checkSetupStatus()
8
- * - needsSetup === true AND route != setupPath -> redirect to setupPath
8
+ * - needsSetup === true AND HTTP init released AND route != setupPath -> redirect to setupPath
9
+ * - needsSetup === true AND HTTP init NOT released -> no redirect
9
10
  * - needsSetup === false AND route === setupPath -> redirect to loginPath
11
+ *
12
+ * Without the HTTP init (nest-server >= 12.4.0 closes it outside `local`, `ci` and `e2e`), the
13
+ * API refuses `POST /system-setup/init` with 403 and the deployment creates its first admin from
14
+ * its configuration. A redirect would then hold every visitor on a page whose only action fails,
15
+ * with the login out of reach. So nothing is redirected; the setup page stays reachable and shows
16
+ * its notice there (`useSystemSetup().httpInitEnabled === false`).
10
17
  */
11
18
  import type { RouteMiddleware } from '#app';
12
19
  declare const _default: RouteMiddleware;
@@ -5,12 +5,12 @@ export default defineNuxtRouteMiddleware(async (to) => {
5
5
  const authConfig = runtimeConfig.public?.ltExtensions?.auth;
6
6
  const setupPath = authConfig?.systemSetup?.setupPath || "/auth/setup";
7
7
  const loginPath = authConfig?.loginPath || "/auth/login";
8
- const { needsSetup, checkSetupStatus } = useSystemSetup();
8
+ const { needsSetup, httpInitEnabled, checkSetupStatus } = useSystemSetup();
9
9
  try {
10
10
  if (needsSetup.value === null) {
11
11
  await checkSetupStatus();
12
12
  }
13
- if (needsSetup.value === true && to.path !== setupPath) {
13
+ if (needsSetup.value === true && httpInitEnabled.value !== false && to.path !== setupPath) {
14
14
  return navigateTo(setupPath);
15
15
  }
16
16
  if (needsSetup.value === false && to.path === setupPath) {
@@ -107,9 +107,6 @@ export interface LtAuthResponse {
107
107
  */
108
108
  export interface LtPasskeyAuthResult {
109
109
  error?: string;
110
- session?: {
111
- token: string;
112
- };
113
110
  success: boolean;
114
111
  user?: LtUser;
115
112
  }
@@ -300,6 +297,23 @@ export interface UseLtAuthReturn {
300
297
  switchToJwtMode: () => Promise<boolean>;
301
298
  validateSession: () => Promise<boolean>;
302
299
  passkey?: unknown;
303
- twoFactor?: unknown;
300
+ /**
301
+ * Better-Auth's two-factor methods (`enable`, `disable` and `generateBackupCodes` hash the
302
+ * password, as on `useLtAuthClient()`).
303
+ *
304
+ * `verifyTotp` and `verifyBackupCode` also finish a sign-in that stopped at the second factor:
305
+ * they put the user into the auth state on the cookie session and fetch the JWT from
306
+ * `/iam/token`. The session token Better-Auth puts into their answer is never stored; in the
307
+ * readable token cookie it would be one XSS away from an attacker. Use these on a 2FA sign-in
308
+ * page rather than `useLtAuthClient().twoFactor` plus `setUser()`.
309
+ */
310
+ twoFactor: Record<string, unknown> & {
311
+ verifyBackupCode: <T extends {
312
+ code: string;
313
+ }>(params: T, options?: unknown) => Promise<unknown>;
314
+ verifyTotp: <T extends {
315
+ code: string;
316
+ }>(params: T, options?: unknown) => Promise<unknown>;
317
+ };
304
318
  }
305
319
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nuxt-extensions",
3
- "version": "1.24.1",
3
+ "version": "1.26.0",
4
4
  "description": "Reusable Nuxt 4 composables, components, and Better-Auth integration for lenne.tech projects",
5
5
  "repository": {
6
6
  "type": "git",
@@ -51,9 +51,9 @@
51
51
  "prepack": "node scripts/sync-module-version.mjs && nuxt-module-build build",
52
52
  "c": "pnpm run check",
53
53
  "check": "node scripts/check.mjs",
54
- "check:raw": "pnpm install --frozen-lockfile && pnpm audit && pnpm run check:suppressions && pnpm peers check && pnpm run format:check && pnpm run dev:prepare && pnpm run lint && pnpm run version:check && pnpm test:types && pnpm test && pnpm run build && pnpm run check:manifest",
55
- "check:fix": "pnpm install && pnpm audit --fix && pnpm run check:suppressions && pnpm peers check && pnpm run format && pnpm run dev:prepare && pnpm run lint:fix && pnpm run version:sync && pnpm test:types && pnpm test && pnpm run build && pnpm run check:manifest",
56
- "check:naf": "pnpm install && pnpm peers check && pnpm run format && pnpm run dev:prepare && pnpm run lint:fix && pnpm run version:sync && pnpm test:types && pnpm test && pnpm run build && pnpm run check:manifest",
54
+ "check:raw": "pnpm install --frozen-lockfile && pnpm audit && pnpm run check:suppressions && pnpm peers check && pnpm run format:check && pnpm run dev:prepare && pnpm run lint && pnpm run check:vendored-core && pnpm run check:template-pins && pnpm run version:check && pnpm test:types && pnpm test && pnpm run build && pnpm run check:manifest",
55
+ "check:fix": "pnpm install && pnpm audit --fix && pnpm run check:suppressions && pnpm peers check && pnpm run format && pnpm run dev:prepare && pnpm run lint:fix && pnpm run check:vendored-core && pnpm run check:template-pins && pnpm run version:sync && pnpm test:types && pnpm test && pnpm run build && pnpm run check:manifest",
56
+ "check:naf": "pnpm install && pnpm peers check && pnpm run format && pnpm run dev:prepare && pnpm run lint:fix && pnpm run check:vendored-core && pnpm run check:template-pins && pnpm run version:sync && pnpm test:types && pnpm test && pnpm run build && pnpm run check:manifest",
57
57
  "cf": "pnpm run check:fix",
58
58
  "cnaf": "pnpm run check:naf",
59
59
  "dev": "pnpm dev:prepare && nuxt dev playground",
@@ -73,7 +73,9 @@
73
73
  "release": "pnpm format:check && pnpm run dev:prepare && pnpm lint && pnpm run version:check && pnpm test:types && pnpm test && pnpm run check:consumer && pnpm prepack",
74
74
  "check:consumer": "node scripts/check-consumer-build.mjs",
75
75
  "check:manifest": "node scripts/check-package-manifest.mjs",
76
- "check:suppressions": "node scripts/check-suppressions.mjs"
76
+ "check:suppressions": "node scripts/check-suppressions.mjs",
77
+ "check:template-pins": "node scripts/check-template-pins.mjs",
78
+ "check:vendored-core": "node scripts/check-vendored-core.mjs"
77
79
  },
78
80
  "dependencies": {
79
81
  "@nuxt/kit": "^4.0.0"
@@ -117,6 +119,7 @@
117
119
  "oxlint": "1.90.0",
118
120
  "oxlint-tsgolint": "7.0.2005",
119
121
  "reka-ui": "2.11.0",
122
+ "semver": "7.8.6",
120
123
  "tus-js-client": "4.3.1",
121
124
  "typescript": "5.9.3",
122
125
  "vitest": "5.1.0",