@lenne.tech/nuxt-extensions 1.27.0 → 4.0.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
@@ -29,7 +29,7 @@ src/
29
29
  | `useLtAuthClient()` | Raw Better Auth client access (`twoFactor.*`, `admin.*`, `passkey`) |
30
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
- | `useLtFile()` | File utilities (size formatting, URLs) |
32
+ | `useLtFile()` | File utilities (size formatting; file links on the API, the public URL also during SSR) |
33
33
  | `useLtShare()` | Web Share API with clipboard fallback |
34
34
  | `useLtErrorTranslation()` | Translate backend error codes |
35
35
 
@@ -62,10 +62,10 @@ export default defineNuxtConfig({
62
62
  modules: ['@lenne.tech/nuxt-extensions'],
63
63
  ltExtensions: {
64
64
  auth: {
65
- enabled: true,
65
+ enabled: true, // only gates the 401 interceptor (= interceptor.enabled); the auth composables stay
66
66
  basePath: '/iam', // Better-Auth endpoint prefix
67
67
  loginPath: '/auth/login',
68
- enableAdmin: true,
68
+ enableAdmin: false, // nest-server serves no admin routes (DEV-4076)
69
69
  enablePasskey: true,
70
70
  enableTwoFactor: true,
71
71
  },
@@ -74,7 +74,7 @@ export default defineNuxtConfig({
74
74
  defaultLocale: 'de',
75
75
  },
76
76
  tus: {
77
- defaultEndpoint: '/files/upload',
77
+ defaultEndpoint: '/tus', // nest-server's TUS path (default)
78
78
  defaultChunkSize: 5 * 1024 * 1024, // 5MB
79
79
  },
80
80
  i18n: {
@@ -121,6 +121,27 @@ The API base URL is resolved at runtime from `NUXT_PUBLIC_API_URL` (client + SSR
121
121
  3. The backend sets the session as an `httpOnly` cookie (`iam.session_token`); `lt-auth-state` is the non-httpOnly client-side cache used by middleware
122
122
  4. Subsequent authenticated requests use `ltAuthFetch` (Cookie mode by default, JWT fallback)
123
123
 
124
+ ### One authenticated fetch (DEV-4074)
125
+
126
+ `useLtAuth().fetchWithAuth` and `ltAuthFetch` / `createLtAuthFetch` are ONE implementation:
127
+ `createLtAuthFetchFor` in `lib/auth-state.ts`. They used to be two copies, and only one of them
128
+ renewed an expired JWT. Do not write a third one; a caller with its own state passes it in.
129
+
130
+ - **A 401 while signed in fetches a JWT once and retries once.** Cookie mode: the switch to JWT.
131
+ JWT mode: the bearer had expired (15 minutes against a 7-day session). One `GET <basePath>/token`
132
+ per burst, shared by every caller (`requestLtJwtAfter401`); each caller stores the token where it
133
+ keeps its own (`adoptJwt`: the cookies, or the composable's `useCookie` refs).
134
+ - **A 401 the bearer did not cause is never retried in JWT mode.** `ltAuthFetch`: Better-Auth's own
135
+ routes (under the auth base), where a 401 is the verdict of sign-in, 2FA or passkey; sending a wrong
136
+ password or code again counts twice against the rate limit. `fetchWithAuth`: the cookie-bound paths.
137
+ - **Cookies in JWT mode differ on purpose.** `ltAuthFetch` always sends them: nest-server
138
+ (>= 11.13.1) falls back to the session cookie when the bearer fails, and Better-Auth's own routes
139
+ read the session from it. `fetchWithAuth` sends them only to passkey, 2FA and `/get-session`
140
+ (`cookiesInJwtMode: 'auth-paths'`, as ng-base does). Changing either is a behaviour change.
141
+ - **The JWT comes from `auth.basePath`.** Without an argument, `ltAuthFetch`, `createLtAuthFetch()`
142
+ and `attemptLtJwtSwitch()` read it from the runtime config. `requestLtJwt()` is the only place a
143
+ JWT is fetched, `useLtAuth().switchToJwtMode()` included.
144
+
124
145
  ## AI Assistant Flow
125
146
 
126
147
  - All AI composables route through `ltAuthFetch` (Cookie/JWT dual mode) and `buildLtAiUrl` (SSR/public URL resolution), so they inherit the same auth + URL behaviour as the rest of the library.
@@ -184,12 +205,29 @@ A service worker must never cache `/sync` or `/iam` responses (nest-server
184
205
 
185
206
  ## Testing Helpers
186
207
 
187
- Import from `@lenne.tech/nuxt-extensions/testing`:
208
+ Playwright helpers, imported from `@lenne.tech/nuxt-extensions/testing` (the starter's E2E tests use
209
+ them this way):
188
210
 
189
211
  ```typescript
190
- import { createTestUser, loginTestUser } from '@lenne.tech/nuxt-extensions/testing';
212
+ import { fillInput, generateTestUser, gotoAndWaitForHydration, waitForURLAndHydration } from '@lenne.tech/nuxt-extensions/testing';
213
+
214
+ const user = generateTestUser('e2e');
215
+ await gotoAndWaitForHydration(page, '/auth/register');
216
+ await fillInput(page, 'input[name="email"]', user.email);
191
217
  ```
192
218
 
219
+ | Group | Exports |
220
+ |-------|---------|
221
+ | Hydration | `waitForHydration`, `gotoAndWaitForHydration`, `waitForURLAndHydration`, `DEFAULT_HYDRATION_TIMEOUT` |
222
+ | Input | `fillInput`, `fillInputs` |
223
+ | Test data | `generateTestUser` (type `TestUser`), `generateRandomString` |
224
+ | TOTP / 2FA | `generateTOTP`, `extractTOTPSecret`, `parseTOTPUrl` |
225
+ | Waiting, reading | `waitForElement`, `waitForNetworkIdle`, `hasText`, `getAllText` |
226
+
227
+ There is no `createTestUser` or `loginTestUser`. A test registers and signs in through the pages, as
228
+ the starter's specs do. `test/doc-imports.test.ts` fails when this file or the README imports a
229
+ name that `/testing` or `/lib` does not export.
230
+
193
231
  ## Authentication Cookie Rules
194
232
 
195
233
  The `useLtAuth()` composable manages the `lt-auth-state` cookie for authentication state. Projects that implement custom auth middleware MUST follow these rules:
@@ -340,9 +378,11 @@ passwords this library does **not** hash. (The setup token of `useSystemSetup().
340
378
  unhashed too, by design — see "First Admin Setup" below.)
341
379
 
342
380
  Today that is harmless: `@lenne.tech/nest-server` does not register better-auth's `admin()`
343
- plugin and has no option to enable it, so those routes 404. But `auth.enableAdmin` defaults to
344
- `true`, meaning the admin *client* plugin is registered in every consuming project — the trap is
345
- armed and waiting for a server that answers.
381
+ plugin and has no option to enable it, so those routes 404. Until DEV-4076 `auth.enableAdmin`
382
+ defaulted to `true`, so the admin *client* plugin was registered in every consuming project — a
383
+ trap armed and waiting for a server that answers. It now defaults to `false`, and `useLtAuth()`
384
+ warns once when a project switches it on while `/iam/features` reports no admin plugin
385
+ (`warnLtAdminPluginUnserved`). Do not flip the default back without the lock-step below.
346
386
 
347
387
  **Enabling `admin()` server-side is therefore a lock-step change across both repos in one
348
388
  release:** the two routes join nest-server's password-normalisation table, and these two methods
@@ -381,6 +421,57 @@ optionally behind a setup token (`LTNS_0054` when wrong). `GET /system-setup/sta
381
421
  configuration. Pass the error itself to `translateError(error)`: the `#LTNS_` code is in the
382
422
  body, `error.message` holds only the transport line.
383
423
 
424
+ ## Package Entry Points (DEV-4079)
425
+
426
+ - **npm `.`** is `dist/module.mjs`, built from `src/module.ts`: the module and every type
427
+ (`export type * from './runtime/types'`). Runtime values come from auto-imports or `./lib`;
428
+ `./testing` holds the Playwright helpers.
429
+ - **`src/index.ts` is the entry of the VENDORED core, not dead code.** npm mode never builds it,
430
+ but the lt CLI copies it to `app/core/index.ts` and rewrites `from '@lenne.tech/nuxt-extensions'`
431
+ to `app/core`. Deleting it breaks every type import of a vendored project. It re-exports whole
432
+ barrels (`export *`); never turn it back into a hand-written list, which lost three composables.
433
+ - **Every package `src/` imports is declared**, as a dependency or a peer. A package that is only
434
+ there when the project installs it is an optional peer, with a stub alias in `module.ts` if it is
435
+ imported statically (`test/optional-peers.test.ts`).
436
+ - **One declaration per type** under `src/runtime/types`. `test/package-exports.test.ts` holds
437
+ the last three rules.
438
+
439
+ ## Versioning (since 4.0.0)
440
+
441
+ **MAJOR is the Nuxt major, and nothing else moves it.** `4.x` is the line for Nuxt 4. A MINOR is a
442
+ change a project has to act on when it updates (behaviour, code or configuration) and always comes
443
+ with a migration guide; a PATCH is a fix or addition it takes as it is. The same scheme as
444
+ nest-server (major = NestJS) and ng-base (major = Angular). Full rules and the release steps:
445
+ `.claude/rules/versioning.md` (in the repository, not in the npm package).
446
+
447
+ - **A breaking change is a MINOR.** Never raise the major for it, however big the change feels.
448
+ - **2.x and 3.x do not exist.** 4.0.0 follows 1.28.0 directly: 1.x was the Nuxt 4 line, but its
449
+ major did not say so. Older docs here saying "the major digit tracks Nuxt (1.x is Nuxt 4)" mean
450
+ that offset.
451
+ - **When updating a project, read the migration guide of every MINOR in between**
452
+ (`migration-guides/<from>.x-to-<to>.0.md`, from 1.x: `1.x-to-4.0.0.md`). A caret range takes
453
+ MINORs, so the starters pin the exact version.
454
+
455
+ ## Error Translation: loaded after mount (DEV-4078)
456
+
457
+ `plugins/error-translation.client.ts` starts `loadTranslations()` in `app:mounted` and does not
458
+ await it. `test/error-translation-loading.test.ts` holds both halves.
459
+
460
+ - **Never make the plugin async again, and never start the load before the mount.** Awaited, it
461
+ held back every client start for one API request. Started early but not awaited, it races
462
+ hydration: the server renders the developer message (it loads no translations), and
463
+ translations arriving before hydration render another text on the client.
464
+ - **Loads are shared per Nuxt app and locale** (`inFlightLoads`), and `isLoading` is shared
465
+ state. A second caller waits for the request in flight instead of returning before the
466
+ translations are there. A load for another locale is never swallowed by one in flight.
467
+ - **Until the load is done, `translateError` returns the developer message.** That is the
468
+ documented fallback, not a bug. `loadTranslations()` never rejects; a failure is logged, and
469
+ the next call tries again.
470
+ - **SSR translates nothing by default** (one request and the whole table in every payload). The
471
+ README shows the opt-in: a project's own `.server` plugin awaits `loadTranslations()`, and the
472
+ payload carries the state to the client. It needs `@nuxtjs/i18n`, so both sides pick the same
473
+ locale.
474
+
384
475
  ## Form Label Repair
385
476
 
386
477
  **The defect:** Nuxt UI's `FormField` derives the label's `for` and the control's `id` from one
@@ -506,6 +597,19 @@ fields at `app:beforeMount` and restores them at `app:mounted`, dispatching a sy
506
597
  else.** Vendoring turns them into project source, where they cause TS2310, and the cli removes a
507
598
  block only while it holds that one interface. Type server-only config where it is read.
508
599
 
600
+ ## Transition Components and Tailwind 4
601
+
602
+ The `LtTransition*` components are the only place this module uses Tailwind classes.
603
+
604
+ - **Tailwind 4 syntax: `duration-(--start-duration)`, never `duration-[--start-duration]`.**
605
+ Tailwind 4 compiles the v3 shorthand to `transition-duration: --start-duration`, which the browser
606
+ drops: the fade ran in 0 s and the duration props did nothing (DEV-4071).
607
+ `test/transition-classes.test.ts` compiles every class with the stack's Tailwind version.
608
+ - **npm mode needs a `@source` line** for `node_modules/@lenne.tech/nuxt-extensions/dist/runtime` in
609
+ the stylesheet that imports Tailwind (README, "Transition Components"). Nuxt UI only adds the
610
+ layers' `app` directories, without a hook a module could use. A missing `@source` path is
611
+ ignored, so the line is harmless in vendor mode.
612
+
509
613
  ## Development Rules
510
614
 
511
615
  1. **ALWAYS read source code** in `dist/runtime/` to understand available composables and components
package/README.md CHANGED
@@ -32,6 +32,8 @@ Reusable Nuxt 4 composables, components, and Better-Auth integration for lenne.t
32
32
  | `better-auth` | `>=1.7.16 <1.8.0` | **required peer** — pin it, see below |
33
33
  | `@better-auth/passkey` | `>=1.7.16 <1.8.0` | optional peer, passkey/WebAuthn only |
34
34
  | `tus-js-client` | `>=4.0.0` | optional peer, resumable uploads only |
35
+ | `@nuxt/ui` | `>=3.0.0` | optional peer: toasts of `showErrorToast` and the auth flows; without it they go to the console |
36
+ | `tailwindcss` | `>=4.0.0` | optional peer, `LtTransition*` components only (Tailwind 4 class syntax, see "Transition Components") |
35
37
  | `@lenne.tech/nest-server` | `>= 11.37.0` | **only if you use the backend** — see the lock-step rule |
36
38
 
37
39
  **Why `better-auth` is pinned to one minor line, and why you must not widen it:**
@@ -89,6 +91,24 @@ overrides:
89
91
  '@better-auth/core': 1.7.16 # the api of nest-server-starter projects depends on it directly
90
92
  ```
91
93
 
94
+ ## Versioning
95
+
96
+ Since 4.0.0 the version follows the scheme of `@lenne.tech/nest-server` and `@lenne.tech/ng-base`:
97
+
98
+ | Part | Meaning |
99
+ |---|---|
100
+ | **MAJOR** | The Nuxt major this module is built for: `4.x.x` = Nuxt 4. It moves only with Nuxt. |
101
+ | **MINOR** | A change you have to act on when you update (behaviour, code or configuration), always with a migration guide in [`migration-guides/`](./migration-guides). A breaking change is a minor. |
102
+ | **PATCH** | A fix or addition you can take as it is. |
103
+
104
+ **2.x and 3.x do not exist.** 4.0.0 follows 1.28.0 directly; 1.x was already the Nuxt 4 line. Coming
105
+ from 1.x, read [`migration-guides/1.x-to-4.0.0.md`](./migration-guides/1.x-to-4.0.0.md).
106
+
107
+ **Pin the exact version** (`npm install --save-exact @lenne.tech/nuxt-extensions`), as the starters
108
+ do: a caret range takes minors, which are exactly the changes you have to act on.
109
+ [nuxt-base-starter](https://github.com/lenneTech/nuxt-base-starter) carries the same version as the
110
+ nuxt-extensions release it pins.
111
+
92
112
  ## Features
93
113
 
94
114
  - **Better-Auth Integration** - Login, 2FA, Passkey/WebAuthn support
@@ -166,14 +186,14 @@ export default defineNuxtConfig({
166
186
  ltExtensions: {
167
187
  // Auth configuration
168
188
  auth: {
169
- enabled: true, // Enable auth features
189
+ enabled: true, // Only gates the 401 interceptor below; useLtAuth() etc. stay available
170
190
  baseURL: '', // API base URL (empty = use env vars)
171
191
  basePath: '/iam', // Better-Auth endpoint prefix
172
192
  loginPath: '/auth/login', // Login redirect path
173
193
  twoFactorRedirectPath: '/auth/2fa', // 2FA redirect path
174
194
 
175
195
  // Plugin options
176
- enableAdmin: true, // Admin plugin
196
+ enableAdmin: false, // Admin client plugin (off: nest-server serves no admin routes)
177
197
  enableTwoFactor: true, // 2FA plugin
178
198
  enablePasskey: true, // Passkey/WebAuthn plugin
179
199
 
@@ -198,7 +218,7 @@ export default defineNuxtConfig({
198
218
 
199
219
  // TUS upload configuration
200
220
  tus: {
201
- defaultEndpoint: '/tus', // nest-server's TUS path (module default: '/files/upload')
221
+ defaultEndpoint: '/tus', // nest-server's TUS path (the module default)
202
222
  defaultChunkSize: 5 * 1024 * 1024, // 5MB
203
223
  resolveAgainstApi: true, // relative endpoint = path on the API, like auth/AI requests
204
224
  },
@@ -522,6 +542,54 @@ JWT from `/iam/token`.
522
542
  session token.**
523
543
  - **`authenticateWithPasskey()` returns no `session`.**
524
544
 
545
+ #### Authenticated requests: `fetchWithAuth` and `ltAuthFetch`
546
+
547
+ `useLtAuth().fetchWithAuth` and `ltAuthFetch` (from `/lib`, also used by the Better-Auth client,
548
+ the AI composables and offline sync) run through one implementation.
549
+
550
+ - **JWT mode sends `Authorization: Bearer <jwt>`.** `ltAuthFetch` always sends the cookies as well,
551
+ so nest-server (>= 11.13.1) falls back to the session cookie when the bearer fails.
552
+ `fetchWithAuth` sends them in JWT mode only to passkey, 2FA and `/get-session`.
553
+ - **A 401 while signed in fetches a JWT once and retries the request once.** In cookie mode that
554
+ is the switch to JWT; in JWT mode it renews an expired JWT, which lives 15 minutes while the
555
+ session lasts 7 days. Requests that fail in the same burst share one `GET <basePath>/token`. A
556
+ 401 that survives the fresh token reaches the caller unchanged, and so does a 401 in JWT mode from
557
+ Better-Auth's own routes (sign-in, 2FA, passkey): there it is the flow's verdict, and a wrong
558
+ password or code must not be sent twice.
559
+ - **The JWT comes from `auth.basePath`.** Without an argument, `ltAuthFetch`, `createLtAuthFetch()`
560
+ and `attemptLtJwtSwitch()` read it from the module config; they used to fetch it from `/iam`
561
+ whatever was configured. A path passed explicitly still wins.
562
+
563
+ #### Server-side rendering: backend calls are anonymous
564
+
565
+ During SSR, `ltAuthFetch`, the AI composables and offline sync call the API **without** a session:
566
+ on the server `getLtAuthMode()` is `'cookie'`, `getLtJwtToken()` is `null` and `isLtAuthenticated()`
567
+ is `false`. The one exception is `useLtAuth().fetchWithAuth` (see the last point below). That is deliberate. The auth helpers are module singletons shared by every request a
568
+ Nitro process renders, so they may not carry one request's cookies. And the session cookie
569
+ (`iam.session_token`) belongs to the API host: nest-server sets it host-only unless
570
+ `crossSubDomainCookies` is configured, so the app server never receives it. `validateSession()` on
571
+ the server therefore relies on the `lt-auth-state` cookie only, which is a display cache, not proof
572
+ of a session.
573
+
574
+ For pages that show user data:
575
+
576
+ - **Load it in the browser.** `useAsyncData(key, fetcher, { server: false })` or `onMounted`, with a
577
+ skeleton or loading state for the first paint. This is what nuxt-base-starter does.
578
+ `useLazyAsyncData` alone is not enough: `lazy` only stops it from blocking navigation, the
579
+ fetcher still runs during SSR, and its anonymous answer (a 401 or the public subset) goes into
580
+ the payload, which the browser does not fetch again. Add `server: false` there too.
581
+ - **Render only public data on the server**, and never decide access there: an SSR guard that reads
582
+ `lt-auth-state` decides what to render, the API decides what the user may see.
583
+ - If a page truly needs user data in the SSR HTML, that needs a server route of the app that
584
+ forwards the request's own session to the API, set up per project together with a shared cookie
585
+ domain. `ltAuthFetch` does not do it.
586
+ - **`useLtAuth().fetchWithAuth` during SSR is not anonymous.** It reads the request's cookies through
587
+ `useCookie`, and in JWT mode (the normal state after sign-in) it sends the request's `lt-jwt-token`
588
+ as the bearer. It cannot renew that token on the server, so the call works until the JWT expires
589
+ (15 minutes) and then answers 401. Do not use it for SSR-rendered user data, and never cache
590
+ (`swr`, `isr`, a CDN) a route whose SSR output went through it: one user's data would be served to
591
+ the next.
592
+
525
593
  #### Admin detection (`role` vs `roles`)
526
594
 
527
595
  `isAdmin` accepts **both** user shapes, so the same frontend works against either backend:
@@ -771,6 +839,17 @@ from the `X-File-Id` response header (nest-server 11.42.13+). Use it for file li
771
839
  is undefined when the backend sends no such header (an older nest-server, or an `onUploadComplete()`
772
840
  override that never calls `super.onUploadComplete(upload)`).
773
841
 
842
+ **File links.** `useLtFile().getFileUrl(id)`, `getDownloadUrl(id, filename?)` and `getFileInfo(id)`
843
+ follow the same rule: they are paths on the API, below the base derived from an endpoint ending in
844
+ `/upload`, otherwise `/files`. The two link helpers point at nest-server's `GET /files/id/<id>`
845
+ (since 11.8.0), which sends the file with the stored filename; nest-server has no rename
846
+ parameter, so `getDownloadUrl()` returns the same URL and ignores `filename`. `getFileInfo()` reads
847
+ `GET /files/info/<id>` (the starter's file controller). `tus.resolveAgainstApi: false` keeps them
848
+ on the app origin, and an absolute base is used as it is.
849
+ The two link helpers return the URL the browser uses, during SSR too: they never contain the
850
+ server-only `NUXT_API_URL`, and server and browser render the same `src`. Only the request
851
+ `getFileInfo()` makes on the server goes to the server-side API URL.
852
+
774
853
  ### Transition Components
775
854
 
776
855
  ```vue
@@ -802,6 +881,22 @@ override that never calls `super.onUploadComplete(upload)`).
802
881
  </template>
803
882
  ```
804
883
 
884
+ The components style themselves with Tailwind 4 utilities. Tailwind only generates the classes it
885
+ finds in your sources, and a package in `node_modules` is not among them, so in npm mode add the
886
+ package's runtime to the stylesheet that imports Tailwind:
887
+
888
+ ```css
889
+ /* app/assets/css/tailwind.css */
890
+ @import 'tailwindcss';
891
+ @import '@nuxt/ui';
892
+ @source '../../../node_modules/@lenne.tech/nuxt-extensions/dist/runtime';
893
+ ```
894
+
895
+ The path is relative to that stylesheet. A vendored core (`app/core`) is scanned with the app
896
+ anyway, and Tailwind ignores a `@source` path that does not exist, so the line can stay after a
897
+ switch to vendor mode. Without it, a transition whose classes the app does not use elsewhere runs
898
+ without its duration or easing.
899
+
805
900
  ### Web Share API
806
901
 
807
902
  ```vue
@@ -827,6 +922,48 @@ const base64 = ltArrayBufferToBase64Url(buffer);
827
922
  const uint8 = ltBase64UrlToUint8Array(base64String);
828
923
  ```
829
924
 
925
+ ### Error Translation
926
+
927
+ `useLtErrorTranslation()` turns a backend error such as `#LTNS_0100: Unauthorized - User is
928
+ not logged in` into the text for the user's locale, loaded from the API's
929
+ `GET /i18n/errors/<locale>`.
930
+
931
+ ```typescript
932
+ const { translateError, showErrorToast } = useLtErrorTranslation();
933
+
934
+ const message = translateError(error); // "Sie sind nicht angemeldet."
935
+ showErrorToast(error, 'Anmeldung fehlgeschlagen');
936
+ ```
937
+
938
+ **The translations load after the app is mounted, and the start does not wait for them.**
939
+ Until they are there, `translateError` returns the developer message (`Unauthorized - User is
940
+ not logged in`), never an empty string. A template that renders `translateError(...)` switches
941
+ to the translation as soon as it arrives. A toast takes the text it had when it was shown. Code
942
+ that has to have the translations first awaits them; a load already in flight is shared, not
943
+ repeated:
944
+
945
+ ```typescript
946
+ const { loadTranslations, translateError } = useLtErrorTranslation();
947
+ await loadTranslations(); // resolves once loaded, or once the load failed (logged, never thrown)
948
+ ```
949
+
950
+ **Messages rendered during SSR carry the developer message.** The server loads no translations
951
+ by default: that would cost one API request and the whole table in the payload of every page,
952
+ for messages that almost always appear after an action in the browser. The client translates
953
+ them after the mount. A project that renders errors on the server, such as an `error.vue` for a
954
+ failed `useAsyncData`, loads the table there itself, in a plugin of its own:
955
+
956
+ ```typescript
957
+ // plugins/error-translations-ssr.server.ts
958
+ export default defineNuxtPlugin(async () => {
959
+ await useLtErrorTranslation().loadTranslations();
960
+ });
961
+ ```
962
+
963
+ The state reaches the client in the payload, so the browser fetches nothing again and hydration
964
+ sees the same text as the server. This needs `@nuxtjs/i18n`: without it, the server takes
965
+ `errorTranslation.defaultLocale` and the browser its own language, and the two can differ.
966
+
830
967
  ## AI Assistant
831
968
 
832
969
  Headless, provider-agnostic composables for the `@lenne.tech/nest-server` **AI module**
@@ -1131,20 +1268,23 @@ The package works **with or without** `@nuxtjs/i18n`:
1131
1268
  ## Development
1132
1269
 
1133
1270
  ```bash
1134
- # Install dependencies
1135
- npm install
1271
+ # Install dependencies (the repository pins pnpm in `packageManager`)
1272
+ pnpm install
1136
1273
 
1137
1274
  # Generate type stubs
1138
- npm run dev:prepare
1275
+ pnpm run dev:prepare
1139
1276
 
1140
1277
  # Develop with playground
1141
- npm run dev
1278
+ pnpm run dev
1142
1279
 
1143
1280
  # Build the module
1144
- npm run build
1281
+ pnpm run build
1145
1282
 
1146
1283
  # Run tests
1147
- npm run test
1284
+ pnpm test
1285
+
1286
+ # Everything a merge needs: audit, lint, types, tests, build, package manifest
1287
+ pnpm run check
1148
1288
  ```
1149
1289
 
1150
1290
  ## License
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.27.0";
6
+ declare const version = "4.0.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.27.0",
4
+ "version": "4.0.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.27.0";
6
+ const version = "4.0.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";
@@ -20,7 +20,7 @@ const defaultOptions = {
20
20
  token: DEFAULT_LT_JWT_TOKEN_COOKIE
21
21
  },
22
22
  enabled: true,
23
- enableAdmin: true,
23
+ enableAdmin: false,
24
24
  enablePasskey: true,
25
25
  enableTwoFactor: true,
26
26
  interceptor: {
@@ -61,7 +61,7 @@ const defaultOptions = {
61
61
  tus: {
62
62
  defaultChunkSize: 5 * 1024 * 1024,
63
63
  // 5MB
64
- defaultEndpoint: "/files/upload",
64
+ defaultEndpoint: "/tus",
65
65
  resolveAgainstApi: true
66
66
  }
67
67
  };
@@ -133,7 +133,7 @@ const module$1 = defineNuxtModule({
133
133
  token: resolvedOptions.auth?.cookieNames?.token || DEFAULT_LT_JWT_TOKEN_COOKIE
134
134
  },
135
135
  enabled: resolvedOptions.auth?.enabled ?? true,
136
- enableAdmin: resolvedOptions.auth?.enableAdmin ?? true,
136
+ enableAdmin: resolvedOptions.auth?.enableAdmin ?? false,
137
137
  enablePasskey,
138
138
  enableTwoFactor: resolvedOptions.auth?.enableTwoFactor ?? true,
139
139
  interceptor: {
@@ -166,7 +166,7 @@ const module$1 = defineNuxtModule({
166
166
  },
167
167
  tus: {
168
168
  defaultChunkSize: resolvedOptions.tus?.defaultChunkSize || 5 * 1024 * 1024,
169
- defaultEndpoint: resolvedOptions.tus?.defaultEndpoint || "/files/upload",
169
+ defaultEndpoint: resolvedOptions.tus?.defaultEndpoint || "/tus",
170
170
  resolveAgainstApi: resolvedOptions.tus?.resolveAgainstApi ?? true
171
171
  }
172
172
  };
@@ -301,7 +301,7 @@ const module$1 = defineNuxtModule({
301
301
  console.log(`[${name}] v${version}`);
302
302
  if (nuxt.options.dev) {
303
303
  console.log(`[${name}] Module loaded with config:`, {
304
- auth: resolvedOptions.auth?.enabled ? "enabled" : "disabled",
304
+ authInterceptor: resolvedOptions.auth?.enabled && resolvedOptions.auth?.interceptor?.enabled ? "on" : "off",
305
305
  i18nAutoMerge: resolvedOptions.i18n?.autoMerge,
306
306
  tusEndpoint: resolvedOptions.tus?.defaultEndpoint
307
307
  });
@@ -8,10 +8,10 @@ const props = defineProps({
8
8
  <template>
9
9
  <div :style="`--start-duration: ${props.startDuration}ms; --leave-duration: ${props.leaveDuration}ms;`">
10
10
  <Transition
11
- enter-active-class="transition ease-out duration-[--start-duration]"
11
+ enter-active-class="transition ease-out duration-(--start-duration)"
12
12
  enter-from-class="transform opacity-0"
13
13
  enter-to-class="transform opacity-100"
14
- leave-active-class="transition ease-in duration-[--leave-duration]"
14
+ leave-active-class="transition ease-in duration-(--leave-duration)"
15
15
  leave-from-class="transform opacity-100"
16
16
  leave-to-class="transform opacity-0"
17
17
  >
@@ -8,10 +8,10 @@ const props = defineProps({
8
8
  <template>
9
9
  <div :style="`--start-duration: ${props.startDuration}ms; --leave-duration: ${props.leaveDuration}ms;`">
10
10
  <Transition
11
- enter-active-class="transition ease-out duration-[--start-duration]"
11
+ enter-active-class="transition ease-out duration-(--start-duration)"
12
12
  enter-from-class="transform opacity-0 scale-95"
13
13
  enter-to-class="transform opacity-100 scale-100"
14
- leave-active-class="transition ease-in duration-[--leave-duration]"
14
+ leave-active-class="transition ease-in duration-(--leave-duration)"
15
15
  leave-from-class="transform opacity-100 scale-100"
16
16
  leave-to-class="transform opacity-0 scale-95"
17
17
  >
@@ -1,6 +1,16 @@
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, getLtJwtToken, isLtJwtShaped, resolveLtAuthState } from "../../lib/auth-state.js";
3
+ import {
4
+ clearLtAuthCookies,
5
+ createLtAuthFetchFor,
6
+ getLtApiBase,
7
+ getLtAuthCookieNames,
8
+ getLtJwtToken,
9
+ isLtJwtShaped,
10
+ requestLtJwt,
11
+ resolveLtAuthState,
12
+ warnLtAdminPluginUnserved
13
+ } from "../../lib/auth-state.js";
4
14
  import { useLtAuthClient } from "../use-lt-auth-client.js";
5
15
  const VALIDATE_SESSION_TIMEOUT_MS = 1e4;
6
16
  const LT_SYNC_SIGN_OUT_FLUSH_MS = 5e3;
@@ -12,7 +22,6 @@ function isLtSyncEnabled() {
12
22
  return false;
13
23
  }
14
24
  }
15
- let staleJwtRefresh = null;
16
25
  function useTranslation() {
17
26
  const nuxtApp = useNuxtApp();
18
27
  const i18n = nuxtApp.$i18n;
@@ -114,88 +123,35 @@ export function useLtAuth() {
114
123
  clearLtAuthCookies();
115
124
  }
116
125
  }
126
+ function adoptJwt(token) {
127
+ if (jwtToken.value !== token) {
128
+ jwtToken.value = token;
129
+ }
130
+ if (authState.value && authState.value.authMode !== "jwt") {
131
+ authState.value = { ...authState.value, authMode: "jwt" };
132
+ }
133
+ }
117
134
  async function switchToJwtMode() {
118
- try {
119
- const apiBase = getLtApiBase();
120
- const response = await fetch(`${apiBase}/token`, {
121
- method: "GET",
122
- credentials: "include"
123
- });
124
- if (response.ok) {
125
- const data = await response.json();
126
- if (isLtJwtShaped(data.token)) {
127
- jwtToken.value = data.token;
128
- if (authState.value) {
129
- authState.value = { ...authState.value, authMode: "jwt" };
130
- }
131
- return true;
132
- }
133
- }
134
- return false;
135
- } catch {
135
+ const token = await requestLtJwt();
136
+ if (!token) {
136
137
  return false;
137
138
  }
139
+ adoptJwt(token);
140
+ return true;
138
141
  }
139
142
  async function refreshJwtToken() {
140
143
  if (!isJwtMode.value || !jwtToken.value) return false;
141
144
  return switchToJwtMode();
142
145
  }
143
- const PATHS_REQUIRING_COOKIES = ["/passkey/", "/two-factor/", "/2fa/", "/get-session"];
144
- function urlRequiresCookies(url) {
145
- return PATHS_REQUIRING_COOKIES.some((path) => url.includes(path));
146
- }
147
- async function fetchWithAuth(url, options = {}) {
148
- const headers = new Headers(options.headers);
149
- if (isJwtMode.value && jwtToken.value) {
150
- headers.set("Authorization", `Bearer ${jwtToken.value}`);
146
+ const fetchWithAuth = createLtAuthFetchFor({
147
+ cookiesInJwtMode: "auth-paths",
148
+ state: {
149
+ adoptJwt,
150
+ isAuthenticated: () => isAuthenticated.value,
151
+ jwtToken: () => jwtToken.value,
152
+ mode: () => isJwtMode.value ? "jwt" : "cookie"
151
153
  }
152
- const needsCookies = !isJwtMode.value || urlRequiresCookies(url);
153
- const response = await fetch(url, {
154
- ...options,
155
- headers,
156
- credentials: needsCookies ? "include" : "omit"
157
- });
158
- if (response.status === 401 && !isJwtMode.value && isAuthenticated.value) {
159
- const switched = await switchToJwtMode();
160
- if (switched) {
161
- headers.set("Authorization", `Bearer ${jwtToken.value}`);
162
- const retryNeedsCookies = urlRequiresCookies(url);
163
- return fetch(url, {
164
- ...options,
165
- headers,
166
- credentials: retryNeedsCookies ? "include" : "omit"
167
- });
168
- }
169
- }
170
- if (response.status === 401 && isJwtMode.value && isAuthenticated.value && !needsCookies) {
171
- const freshToken = await refreshStaleJwt();
172
- if (freshToken) {
173
- headers.set("Authorization", `Bearer ${freshToken}`);
174
- return fetch(url, {
175
- ...options,
176
- headers,
177
- credentials: "omit"
178
- });
179
- }
180
- }
181
- return response;
182
- }
183
- async function refreshStaleJwt() {
184
- const mint = async () => await switchToJwtMode() ? jwtToken.value : null;
185
- if (!import.meta.client) {
186
- return mint();
187
- }
188
- if (!staleJwtRefresh) {
189
- staleJwtRefresh = mint().finally(() => {
190
- staleJwtRefresh = null;
191
- });
192
- }
193
- const token = await staleJwtRefresh;
194
- if (token && jwtToken.value !== token) {
195
- jwtToken.value = token;
196
- }
197
- return token;
198
- }
154
+ });
199
155
  const AUTHZ_KEYS = ["banExpires", "banReason", "banned", "emailVerified", "role", "roles", "twoFactorEnabled"];
200
156
  function mergeSessionUser(sessionUser) {
201
157
  const cached = resolvedAuthState.value?.user;
@@ -259,6 +215,7 @@ export function useLtAuth() {
259
215
  if (result) {
260
216
  features.value = result;
261
217
  featuresFetched.value = true;
218
+ warnLtAdminPluginUnserved(result);
262
219
  }
263
220
  return features.value;
264
221
  } catch {
@@ -455,7 +412,7 @@ export function useLtAuth() {
455
412
  if (!credential) {
456
413
  return {
457
414
  success: false,
458
- error: t("lt.auth.passkeyCreationAborted", "Passkey-Erstellung abgebrochen")
415
+ error: t("lt.auth.passkeyCreationAborted", "Passkey-Erstellung wurde abgebrochen")
459
416
  };
460
417
  }
461
418
  const attestationResponse = credential.response;