@lenne.tech/nuxt-extensions 1.25.0 → 1.27.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
@@ -43,7 +43,7 @@ src/
43
43
  | `useLtAiSettings()` | The user's own AI settings: MCP confirmation switch (`GET/PUT /ai/settings`, `enforced` → show disabled) |
44
44
  | `useLtAiStatus()` | Whether the API's AI module is on (`GET /ai/status`, public; 404 = off): `enabled`, `mcp`, shared `useState`, one request per app start, fails closed |
45
45
  | `useLtAiUsage()` | Full token/prompt usage breakdown (`GET /ai/usage`) |
46
- | `useLtAiPrompts()` | User-facing CRUD for re-usable prompt snippets ("Vorlagen", `scope: 'user'` / `'tenant'`) |
46
+ | `useLtAiPrompts()` | User-facing CRUD for re-usable prompt snippets ("Vorlagen", `scope: 'user'` / `'tenant'`). `load()` = active only (chat picker); `load({ includeDisabled: true })` = management list (nest-server >= 12.7.0), kept for the reload after create/update/remove |
47
47
  | `useLtAiPlaceholders()` | Loads the backend's `{{placeholder}}` registry for editor sidebars |
48
48
  | `useLtAiAdmin()` | Admin CRUD: connections, preferences, budget limits, slots, prompt hints, interactions — server-gated |
49
49
 
@@ -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)
@@ -459,7 +484,24 @@ fields at `app:beforeMount` and restores them at `app:mounted`, dispatching a sy
459
484
  - **nuxt-base-starter lints `app/core/**` with a subset of the plugins in `.oxlintrc.json`, never
460
485
  more**, and `lint` here runs with `--deny-warnings`. A plugin only the starter applies reports its
461
486
  warnings in every generated project after the release; the 1.24.0 smoke test found three. A plugin
462
- 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.
463
505
  - **The `nuxt/schema` blocks in `runtime/types/module.ts` augment `PublicRuntimeConfig` and nothing
464
506
  else.** Vendoring turns them into project source, where they cause TS2310, and the cli removes a
465
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:
@@ -831,6 +866,21 @@ await load();
831
866
  is private to the owner; `scope: 'tenant'` is shared across the owner's tenant. The list
832
867
  returned by `load()` is already server-filtered to what the user is allowed to see.
833
868
 
869
+ `load()` lists active prompts only, which is what a chat picker offers. A management screen
870
+ calls `load({ includeDisabled: true })` (nest-server >= 12.7.0), so a prompt saved with
871
+ `enabled: false` stays in the list and can be switched on again:
872
+
873
+ ```typescript
874
+ // Settings page: every prompt, disabled ones included
875
+ const { load, prompts, update } = useLtAiPrompts();
876
+ onMounted(() => load({ includeDisabled: true }));
877
+ // The reload after create / update / remove asks for the same list
878
+ await update(prompt.id, { enabled: false });
879
+ ```
880
+
881
+ Each `useLtAiPrompts()` call has its own list, so the chat picker on the same page stays on
882
+ active prompts. An API before 12.7.0 ignores the parameter and lists active prompts only.
883
+
834
884
  ### AI status
835
885
 
836
886
  `useLtAiStatus()` says whether the API's AI module is on, so AI pages and navigation entries can
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.25.0";
6
+ declare const version = "1.27.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.25.0",
4
+ "version": "1.27.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.25.0";
6
+ const version = "1.27.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
  }
@@ -3,8 +3,10 @@
3
3
  *
4
4
  * Any signed-in user can author re-usable prompts ("Vorlagen") for themselves
5
5
  * (`scope: 'user'` = private) or for their tenant (`scope: 'tenant'` = public).
6
- * `load()` returns every prompt the current user is allowed to see (own +
7
- * tenant), already filtered by the server.
6
+ * `load()` returns every active prompt the current user is allowed to see (own +
7
+ * tenant), already filtered by the server. That is what a chat picker offers.
8
+ * A management screen calls `load({ includeDisabled: true })` (nest-server >= 12.7.0),
9
+ * so a prompt switched off stays in the list and can be switched on again.
8
10
  *
9
11
  * Pair this with your own prompt picker / settings UI. The nuxt-base-starter
10
12
  * ships a reference picker inside the AI chat and a settings page.
@@ -4,11 +4,17 @@ export function useLtAiPrompts() {
4
4
  const prompts = ref([]);
5
5
  const loading = ref(false);
6
6
  const error = ref(null);
7
- async function load() {
7
+ let includeDisabled = false;
8
+ async function load(options) {
9
+ includeDisabled = options?.includeDisabled === true;
10
+ await fetchPrompts();
11
+ }
12
+ async function fetchPrompts() {
8
13
  loading.value = true;
9
14
  error.value = null;
10
15
  try {
11
- prompts.value = await ltAiRequest("GET", "/prompts") || [];
16
+ const path = includeDisabled ? "/prompts?includeDisabled=true" : "/prompts";
17
+ prompts.value = await ltAiRequest("GET", path) || [];
12
18
  } catch (err) {
13
19
  error.value = err.message;
14
20
  prompts.value = [];
@@ -21,7 +27,7 @@ export function useLtAiPrompts() {
21
27
  error.value = null;
22
28
  try {
23
29
  const created = await ltAiRequest("POST", "/prompts", input);
24
- await load();
30
+ await fetchPrompts();
25
31
  return created;
26
32
  } catch (err) {
27
33
  error.value = err.message;
@@ -35,7 +41,7 @@ export function useLtAiPrompts() {
35
41
  error.value = null;
36
42
  try {
37
43
  const updated = await ltAiRequest("PUT", `/prompts/${encodeURIComponent(id)}`, input);
38
- await load();
44
+ await fetchPrompts();
39
45
  return updated;
40
46
  } catch (err) {
41
47
  error.value = err.message;
@@ -49,7 +55,7 @@ export function useLtAiPrompts() {
49
55
  error.value = null;
50
56
  try {
51
57
  const removed = await ltAiRequest("DELETE", `/prompts/${encodeURIComponent(id)}`);
52
- await load();
58
+ await fetchPrompts();
53
59
  return removed;
54
60
  } catch (err) {
55
61
  error.value = err.message;
@@ -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,
@@ -366,7 +366,10 @@ export interface LtAiPrompt {
366
366
  createdAt?: string;
367
367
  /** Optional description. */
368
368
  description?: string;
369
- /** Whether the prompt is active (disabled prompts are hidden). */
369
+ /**
370
+ * Whether the prompt is active. The server lists disabled prompts only on request
371
+ * (`useLtAiPrompts().load({ includeDisabled: true })`, nest-server >= 12.7.0).
372
+ */
370
373
  enabled?: boolean;
371
374
  /** Optional icon hint (lucide name or single emoji). */
372
375
  icon?: string;
@@ -477,6 +480,18 @@ export interface UseLtAiUsageReturn {
477
480
  load: () => Promise<void>;
478
481
  usage: DeepReadonly<Ref<LtAiUsageInfo | null>>;
479
482
  }
483
+ /**
484
+ * Options of `useLtAiPrompts().load()`.
485
+ */
486
+ export interface LtAiPromptsLoadOptions {
487
+ /**
488
+ * Also list disabled prompts (`GET /ai/prompts?includeDisabled=true`, nest-server >= 12.7.0).
489
+ * For a management screen, where a disabled prompt must stay editable. A chat picker leaves it
490
+ * off, because it must offer active prompts only. A server before 12.7.0 ignores the parameter
491
+ * and lists active prompts only.
492
+ */
493
+ includeDisabled?: boolean;
494
+ }
480
495
  /**
481
496
  * User-facing prompt composable. Lets any signed-in user manage their own
482
497
  * prompts ("Vorlagen") and use the visible ones (own private + tenant public)
@@ -485,7 +500,11 @@ export interface UseLtAiUsageReturn {
485
500
  export interface UseLtAiPromptsReturn {
486
501
  create: (input: LtAiPromptInput) => Promise<LtAiPrompt>;
487
502
  error: DeepReadonly<Ref<null | string>>;
488
- load: () => Promise<void>;
503
+ /**
504
+ * Loads the prompts the user may see. Its options also apply to the reload after `create`,
505
+ * `update` and `remove`, so a prompt saved as disabled stays in a management list.
506
+ */
507
+ load: (options?: LtAiPromptsLoadOptions) => Promise<void>;
489
508
  loading: DeepReadonly<Ref<boolean>>;
490
509
  prompts: DeepReadonly<Ref<LtAiPrompt[]>>;
491
510
  remove: (id: string) => Promise<LtAiPrompt>;
@@ -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 {};
@@ -3,4 +3,4 @@ export type { LtFileInfo, LtUploadItem, LtUploadOptions, LtUploadProgress, LtUpl
3
3
  export type { LtAiModuleOptions, LtAuthCookieNamesOptions, LtAuthModuleOptions, LtErrorTranslationModuleOptions, LtExtensionsModuleOptions, LtExtensionsPublicRuntimeConfig, LtFormLabelAssociationOptions, LtI18nModuleOptions, LtPreHydrationInputOptions, LtSecurityTxtOptions, LtSystemSetupModuleOptions, LtTusModuleOptions, } from './module.js';
4
4
  export type { LtErrorTranslationResponse, LtParsedError, UseLtErrorTranslationReturn } from './error.js';
5
5
  export type { LtSyncConflict, LtSyncConflictResolution, LtSyncIdFormat, LtSyncItemStatus, LtSyncModuleOptions, LtSyncPushResult, LtSyncRecord, LtSyncResult, UseLtOfflineSyncOptions, UseLtOfflineSyncReturn, } from './sync.js';
6
- export type { LtAiAction, LtAiAvailableConnection, LtAiBudgetLimit, LtAiBudgetSummary, LtAiConnection, LtAiConnectionInput, LtAiConnectionPreference, LtAiEffectiveSlot, LtAiInteraction, LtAiMessage, LtAiMode, LtAiPlaceholder, LtAiPrompt, LtAiPromptHint, LtAiPromptHintInput, LtAiPromptInput, LtAiPromptRunInput, LtAiResponse, LtAiSettings, LtAiSettingsInput, LtAiSlot, LtAiStatus, LtAiSlotInput, LtAiStreamEvent, LtAiStreamHandlers, LtAiUsage, LtAiUsageInfo, LtAiUsageScope, UseLtAiAdminReturn, UseLtAiChatOptions, UseLtAiChatReturn, UseLtAiConnectionsReturn, UseLtAiPlaceholdersReturn, UseLtAiPromptsReturn, UseLtAiReturn, UseLtAiSettingsReturn, UseLtAiStatusReturn, UseLtAiUsageReturn, } from './ai.js';
6
+ export type { LtAiAction, LtAiAvailableConnection, LtAiBudgetLimit, LtAiBudgetSummary, LtAiConnection, LtAiConnectionInput, LtAiConnectionPreference, LtAiEffectiveSlot, LtAiInteraction, LtAiMessage, LtAiMode, LtAiPlaceholder, LtAiPrompt, LtAiPromptHint, LtAiPromptHintInput, LtAiPromptInput, LtAiPromptRunInput, LtAiPromptsLoadOptions, LtAiResponse, LtAiSettings, LtAiSettingsInput, LtAiSlot, LtAiStatus, LtAiSlotInput, LtAiStreamEvent, LtAiStreamHandlers, LtAiUsage, LtAiUsageInfo, LtAiUsageScope, UseLtAiAdminReturn, UseLtAiChatOptions, UseLtAiChatReturn, UseLtAiConnectionsReturn, UseLtAiPlaceholdersReturn, UseLtAiPromptsReturn, UseLtAiReturn, UseLtAiSettingsReturn, UseLtAiStatusReturn, UseLtAiUsageReturn, } from './ai.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nuxt-extensions",
3
- "version": "1.25.0",
3
+ "version": "1.27.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",