@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.
@@ -17,10 +17,6 @@
17
17
  * ```
18
18
  */
19
19
  import { type LtAuthClient } from '../lib/auth-client.js';
20
- /**
21
- * Reset the auth client singleton (useful for testing or config changes)
22
- */
23
- export declare function resetLtAuthClient(): void;
24
20
  /**
25
21
  * Returns the Better-Auth client singleton
26
22
  *
@@ -1,9 +1,6 @@
1
1
  import { useRuntimeConfig } from "#imports";
2
- import { getOrCreateLtAuthClient, resetLtAuthClientSingleton } from "../lib/auth-client.js";
2
+ import { getOrCreateLtAuthClient } from "../lib/auth-client.js";
3
3
  import { isLocalDevApiProxy } from "../lib/auth-state.js";
4
- export function resetLtAuthClient() {
5
- resetLtAuthClientSingleton();
6
- }
7
4
  export function useLtAuthClient() {
8
5
  try {
9
6
  const runtimeConfig = useRuntimeConfig();
@@ -8,6 +8,10 @@
8
8
  * Translations loaded from: GET /i18n/errors/:locale
9
9
  *
10
10
  * URL handling is delegated to {@link buildLtApiUrl} (SSR / proxy / direct).
11
+ *
12
+ * Until the translations for the current locale are loaded, `translateError` returns the
13
+ * developer message. The plugin starts the load after the app is mounted and does not wait
14
+ * for it (DEV-4078); every instance shares that request, see {@link inFlightLoads}.
11
15
  */
12
16
  import type { UseLtErrorTranslationReturn } from '../types/error.js';
13
17
  /**
@@ -1,12 +1,21 @@
1
- import { computed, ref, useState, useNuxtApp, useRuntimeConfig } from "#imports";
1
+ import { computed, useState, useNuxtApp, useRuntimeConfig } from "#imports";
2
2
  import { buildLtApiUrl } from "../lib/auth-state.js";
3
3
  import { ltAddToast } from "../lib/toast.js";
4
4
  const ERROR_CODE_REGEX = /^#([A-Z_]+_\d+):\s*(.+)$/;
5
+ const inFlightLoads = /* @__PURE__ */ new WeakMap();
6
+ function inFlightLoadsOf(app) {
7
+ let loads = inFlightLoads.get(app);
8
+ if (!loads) {
9
+ loads = /* @__PURE__ */ new Map();
10
+ inFlightLoads.set(app, loads);
11
+ }
12
+ return loads;
13
+ }
5
14
  export function useLtErrorTranslation() {
6
15
  const nuxtApp = useNuxtApp();
7
16
  const runtimeConfig = useRuntimeConfig();
8
17
  const translations = useState("lt-error-translations", () => ({}));
9
- const isLoading = ref(false);
18
+ const isLoading = useState("lt-error-translations-loading", () => false);
10
19
  const config = runtimeConfig.public?.ltExtensions?.errorTranslation;
11
20
  function t(key, germanFallback) {
12
21
  const i18n = nuxtApp.$i18n;
@@ -31,17 +40,33 @@ export function useLtErrorTranslation() {
31
40
  function buildErrorUrl(locale) {
32
41
  return buildLtApiUrl(`/i18n/errors/${locale}`);
33
42
  }
34
- async function loadTranslations(locale) {
43
+ function loadTranslations(locale) {
35
44
  const targetLocale = locale || detectLocale();
36
45
  if (translations.value[targetLocale]) {
37
- return;
46
+ return Promise.resolve();
38
47
  }
39
- if (isLoading.value) {
40
- return;
48
+ const loads = inFlightLoadsOf(nuxtApp);
49
+ const pending = loads.get(targetLocale);
50
+ if (pending) {
51
+ return pending;
52
+ }
53
+ let url;
54
+ try {
55
+ url = buildErrorUrl(targetLocale);
56
+ } catch (error) {
57
+ console.warn(`[LtErrorTranslation] Failed to load translations for ${targetLocale}:`, error);
58
+ return Promise.resolve();
41
59
  }
42
60
  isLoading.value = true;
61
+ const load = fetchTranslations(url, targetLocale).finally(() => {
62
+ loads.delete(targetLocale);
63
+ isLoading.value = loads.size > 0;
64
+ });
65
+ loads.set(targetLocale, load);
66
+ return load;
67
+ }
68
+ async function fetchTranslations(url, targetLocale) {
43
69
  try {
44
- const url = buildErrorUrl(targetLocale);
45
70
  const response = await $fetch(url);
46
71
  if (response?.errors) {
47
72
  translations.value = {
@@ -51,8 +76,6 @@ export function useLtErrorTranslation() {
51
76
  }
52
77
  } catch (error) {
53
78
  console.warn(`[LtErrorTranslation] Failed to load translations for ${targetLocale}:`, error);
54
- } finally {
55
- isLoading.value = false;
56
79
  }
57
80
  }
58
81
  function extractMessage(errorOrMessage) {
@@ -1,10 +1,33 @@
1
1
  import { useRuntimeConfig } from "#imports";
2
+ import { resolveLtApiBaseUrl, resolveLtPublicApiBaseUrl, warnMissingLtApiUrl } from "../lib/auth-state.js";
3
+ const ABSOLUTE_URL = /^(?:[a-z][a-z\d+.-]*:|\/\/)/i;
2
4
  export function useLtFile() {
3
5
  const config = useRuntimeConfig();
6
+ const apiBases = (() => {
7
+ try {
8
+ return { link: resolveLtPublicApiBaseUrl(), request: resolveLtApiBaseUrl() };
9
+ } catch {
10
+ return null;
11
+ }
12
+ })();
4
13
  function getFileApiBase() {
5
14
  const endpoint = config.public.ltExtensions?.tus?.defaultEndpoint;
6
15
  return (endpoint?.endsWith("/upload") ? endpoint.slice(0, -"/upload".length) : "") || "/files";
7
16
  }
17
+ function fileApiUrl(path, scope) {
18
+ const url = `${getFileApiBase()}${path}`;
19
+ if (config.public.ltExtensions?.tus?.resolveAgainstApi === false || ABSOLUTE_URL.test(url)) {
20
+ return url;
21
+ }
22
+ if (!apiBases) {
23
+ return url;
24
+ }
25
+ const base = scope === "link" ? apiBases.link : apiBases.request;
26
+ if (base.missing) {
27
+ warnMissingLtApiUrl(scope === "link" ? "client" : apiBases.request.scope);
28
+ }
29
+ return `${base.baseUrl}${url}`;
30
+ }
8
31
  function isValidMongoID(id) {
9
32
  return /^[a-f\d]{24}$/i.test(id);
10
33
  }
@@ -16,8 +39,7 @@ export function useLtFile() {
16
39
  return id;
17
40
  }
18
41
  try {
19
- const apiBase = getFileApiBase();
20
- const response = await $fetch(`${apiBase}/info/${id}`, {
42
+ const response = await $fetch(fileApiUrl(`/info/${id}`, "request"), {
21
43
  credentials: "include",
22
44
  method: "GET"
23
45
  });
@@ -28,13 +50,10 @@ export function useLtFile() {
28
50
  }
29
51
  }
30
52
  function getFileUrl(id) {
31
- const apiBase = getFileApiBase();
32
- return `${apiBase}/${id}`;
53
+ return fileApiUrl(`/id/${encodeURIComponent(id)}`, "link");
33
54
  }
34
- function getDownloadUrl(id, filename) {
35
- const apiBase = getFileApiBase();
36
- const base = `${apiBase}/download/${id}`;
37
- return filename ? `${base}?filename=${encodeURIComponent(filename)}` : base;
55
+ function getDownloadUrl(id, _filename) {
56
+ return getFileUrl(id);
38
57
  }
39
58
  function formatFileSize(bytes) {
40
59
  if (bytes === 0) return "0 B";
@@ -28,7 +28,7 @@ export function useLtTusUpload(defaultOptions = {}) {
28
28
  autoStart: true,
29
29
  chunkSize: tusConfig?.defaultChunkSize || 5 * 1024 * 1024,
30
30
  // 5MB chunks
31
- endpoint: tusConfig?.defaultEndpoint || "/files/upload",
31
+ endpoint: tusConfig?.defaultEndpoint || "/tus",
32
32
  parallelUploads: 3,
33
33
  retryDelays: [0, 1e3, 3e3, 5e3, 1e4],
34
34
  ...Object.fromEntries(Object.entries(defaultOptions).filter(([, value]) => value !== void 0))
@@ -240,9 +240,9 @@ export declare function createLtAuthClient(config?: LtAuthClientConfig): {
240
240
  * normalising those routes, this wrapper would CREATE the credential-store desync it
241
241
  * was meant to prevent.
242
242
  *
243
- * What that costs, stated plainly: `auth.enableAdmin` defaults to `true`, so the admin
244
- * CLIENT plugin is registered in every consuming project. The trap is armed and waiting
245
- * for a server that answers. Enabling `admin()` server-side is therefore a LOCKSTEP
243
+ * What that costs, stated plainly: a project that sets `auth.enableAdmin: true` (the
244
+ * default until DEV-4076) registers the admin CLIENT plugin, and the trap is armed and
245
+ * waiting for a server that answers. Enabling `admin()` server-side is therefore a LOCKSTEP
246
246
  * change — the routes join nest-server's password-normalisation table and these two
247
247
  * methods get `ltSha256` wrappers here, in one release. Half of it produces accounts
248
248
  * whose password nobody can log in with, and nothing warns.
@@ -46,7 +46,7 @@ export function createLtAuthClient(config = {}) {
46
46
  baseURL = defaultBaseURL,
47
47
  basePath = defaultBasePath,
48
48
  twoFactorRedirectPath = "/auth/2fa",
49
- enableAdmin = true,
49
+ enableAdmin = false,
50
50
  enableTwoFactor = true,
51
51
  enablePasskey = true,
52
52
  plugins: externalPlugins = []
@@ -94,9 +94,9 @@ export function createLtAuthClient(config = {}) {
94
94
  * normalising those routes, this wrapper would CREATE the credential-store desync it
95
95
  * was meant to prevent.
96
96
  *
97
- * What that costs, stated plainly: `auth.enableAdmin` defaults to `true`, so the admin
98
- * CLIENT plugin is registered in every consuming project. The trap is armed and waiting
99
- * for a server that answers. Enabling `admin()` server-side is therefore a LOCKSTEP
97
+ * What that costs, stated plainly: a project that sets `auth.enableAdmin: true` (the
98
+ * default until DEV-4076) registers the admin CLIENT plugin, and the trap is armed and
99
+ * waiting for a server that answers. Enabling `admin()` server-side is therefore a LOCKSTEP
100
100
  * change — the routes join nest-server's password-normalisation table and these two
101
101
  * methods get `ltSha256` wrappers here, in one release. Half of it produces accounts
102
102
  * whose password nobody can log in with, and nothing warns.
@@ -90,6 +90,17 @@ export declare function getLtAuthCookieNames(): {
90
90
  * unchanged by the duplicate-tolerant read; it only decides which twin wins.
91
91
  */
92
92
  export declare function resolveLtAuthState(cookieString: string, stateCookieName?: string): LtAuthState | null;
93
+ /**
94
+ * Warn, once, when `auth.enableAdmin` is on but the backend's `/iam/features` reports no admin
95
+ * plugin (DEV-4076).
96
+ *
97
+ * `@lenne.tech/nest-server` does not register Better-Auth's `admin()` plugin: every `admin.*` call
98
+ * answers 404, and `admin.createUser` / `admin.setUserPassword` would send their passwords unhashed
99
+ * if a server ever answered them. A backend that does serve the routes reports `admin: true`.
100
+ *
101
+ * INTERNAL — called by `useLtAuth().fetchFeatures()`. Not part of the public API.
102
+ */
103
+ export declare function warnLtAdminPluginUnserved(features: Record<string, unknown>): void;
93
104
  /**
94
105
  * Clear the one-shot warning state.
95
106
  *
@@ -211,6 +222,33 @@ export declare function warnMissingLtApiUrl(scope: 'client' | 'server'): void;
211
222
  * @param path - The API path (e.g., `/system-setup/status`, `/i18n/errors/de`)
212
223
  */
213
224
  export declare function buildLtApiUrl(path: string): string;
225
+ /**
226
+ * The URL the browser uses for an API path, built the same way during SSR.
227
+ *
228
+ * For links and `src` attributes the server renders and the browser then follows (file links of
229
+ * `useLtFile()`): {@link buildLtApiUrl} would put the server-only `NUXT_API_URL` (an internal
230
+ * cluster address) into the HTML during SSR, and behind the dev proxy the server and the browser
231
+ * would render different strings, a hydration mismatch. Requests the server makes itself keep
232
+ * using {@link buildLtApiUrl}.
233
+ *
234
+ * `/api` + path while the dev proxy is on, otherwise `NUXT_PUBLIC_API_URL` (or `auth.baseURL`) +
235
+ * path; relative (with the one-shot warning) when neither is configured.
236
+ *
237
+ * @param path - The API path (e.g. `/files/abc`)
238
+ */
239
+ export declare function buildLtPublicApiUrl(path: string): string;
240
+ /**
241
+ * The base of {@link buildLtPublicApiUrl}: `'/api'` behind the dev proxy, otherwise the public API
242
+ * URL; `missing` when neither is configured.
243
+ *
244
+ * INTERNAL — for callers that read the base once, while the Nuxt context exists, and build URLs
245
+ * later (`useLtFile()`: after an `await` in a `useAsyncData` handler, `useRuntimeConfig()` throws
246
+ * during SSR). Throws outside a Nuxt runtime-config context; callers catch.
247
+ */
248
+ export declare function resolveLtPublicApiBaseUrl(): {
249
+ baseUrl: string;
250
+ missing: boolean;
251
+ };
214
252
  /**
215
253
  * Get the current auth mode from cookie
216
254
  */
@@ -274,25 +312,82 @@ export declare function setLtAuthMode(mode: LtAuthMode): void;
274
312
  * @param basePath - The auth API base path. If not provided, reads from runtime config (default: '/iam')
275
313
  */
276
314
  export declare function getLtApiBase(basePath?: string): string;
315
+ /**
316
+ * `GET <auth>/token` with the session cookie: a fresh JWT, or `null` (refused, not JWT-shaped, offline).
317
+ *
318
+ * INTERNAL — the one place a JWT is fetched: {@link attemptLtJwtSwitch}, the 401 recovery of
319
+ * {@link createLtAuthFetch} and `useLtAuth().switchToJwtMode()` all go through it. Not part of the
320
+ * public API (absent from the barrels and auto-imports).
321
+ *
322
+ * @param basePath - The auth API base path; `auth.basePath` from the runtime config when omitted
323
+ */
324
+ export declare function requestLtJwt(basePath?: string): Promise<null | string>;
277
325
  /**
278
326
  * Attempt to switch to JWT mode by fetching a token
279
327
  *
280
- * @param basePath - The auth API base path (default: '/iam')
328
+ * @param basePath - The auth API base path; `auth.basePath` from the runtime config when omitted
281
329
  */
282
330
  export declare function attemptLtJwtSwitch(basePath?: string): Promise<boolean>;
283
331
  /**
284
332
  * Check if user is authenticated (has auth-state with user)
285
333
  */
286
334
  export declare function isLtAuthenticated(): boolean;
335
+ /**
336
+ * Where a caller of the authenticated fetch keeps its auth mode and its JWT.
337
+ *
338
+ * INTERNAL — `useLtAuth()` hands in its own `useCookie` refs, so its `fetchWithAuth` reads and
339
+ * writes what the composable shows; every other caller uses the browser cookies. Not part of the
340
+ * public API.
341
+ */
342
+ export interface LtAuthFetchState {
343
+ /** Store a freshly fetched JWT and switch to JWT mode. */
344
+ adoptJwt: (token: string) => void;
345
+ isAuthenticated: () => boolean;
346
+ jwtToken: () => null | string;
347
+ mode: () => LtAuthMode;
348
+ }
349
+ /** INTERNAL — options of {@link createLtAuthFetchFor}. */
350
+ export interface LtAuthFetchOptions {
351
+ /** The auth API base path for the JWT; `auth.basePath` from the runtime config when omitted. */
352
+ basePath?: string;
353
+ /**
354
+ * Cookies in JWT mode. `'always'` (default): the session cookie rides along, and nest-server
355
+ * (>= 11.13.1) falls back to it when the bearer fails; Better-Auth's own routes read the session
356
+ * from it. `'auth-paths'`: only {@link LT_PATHS_REQUIRING_COOKIES} get it, as in
357
+ * `useLtAuth().fetchWithAuth` (and ng-base's auth fetch).
358
+ */
359
+ cookiesInJwtMode?: 'always' | 'auth-paths';
360
+ state: LtAuthFetchState;
361
+ }
362
+ /**
363
+ * The authenticated fetch, one implementation for every caller.
364
+ *
365
+ * INTERNAL — `useLtAuth().fetchWithAuth` builds itself from it with its own state; everyone else
366
+ * uses {@link createLtAuthFetch} / {@link ltAuthFetch}. Not part of the public API.
367
+ *
368
+ * 1. JWT mode adds `Authorization: Bearer <jwt>`; cookies follow `cookiesInJwtMode`.
369
+ * 2. A 401 while signed in fetches a JWT once (shared by the burst, see {@link requestLtJwtAfter401})
370
+ * and retries the request once with it. In cookie mode that is the switch to JWT; in JWT mode the
371
+ * bearer was most likely expired: the JWT lives 15 minutes, the session behind it 7 days, and
372
+ * nothing renews it while the user works.
373
+ * 3. A 401 that survives the fresh token, or one no token can be fetched for, reaches the caller
374
+ * unchanged. So does a 401 in JWT mode that the bearer did not cause: with `'auth-paths'` on a
375
+ * cookie-bound path (the cookie failed there), with `'always'` on Better-Auth's own routes, where
376
+ * the cookie rides along anyway and a 401 is the flow's verdict. A wrong password or 2FA code
377
+ * sent a second time would count twice against the rate limit.
378
+ */
379
+ export declare function createLtAuthFetchFor(options: LtAuthFetchOptions): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
287
380
  /**
288
381
  * Custom fetch function that handles Cookie/JWT dual-mode authentication
289
382
  *
290
383
  * This function:
291
- * 1. In cookie mode: Uses credentials: 'include'
292
- * 2. In JWT mode: Adds Authorization header
293
- * 3. On 401 in cookie mode: Attempts to switch to JWT and retries
384
+ * 1. Always sends the cookies (`credentials: 'include'`)
385
+ * 2. In JWT mode: Adds the Authorization header
386
+ * 3. On 401 while signed in: fetches a JWT once (cookie mode: switch to JWT; JWT mode: renew the
387
+ * expired one) and retries the request once
294
388
  *
295
- * @param basePath - The auth API base path for JWT switch (default: '/iam')
389
+ * @param basePath - The auth API base path for the JWT; `auth.basePath` from the runtime config when omitted
296
390
  */
297
391
  export declare function createLtAuthFetch(basePath?: string): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
392
+ /** Default auth fetch; fetches its JWT from `auth.basePath` (default `/iam`). */
298
393
  export declare const ltAuthFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
@@ -50,6 +50,20 @@ function warnOnce(key, message) {
50
50
  warnedKeys.add(key);
51
51
  console.warn(message);
52
52
  }
53
+ export function warnLtAdminPluginUnserved(features) {
54
+ try {
55
+ const enableAdmin = useRuntimeConfig().public?.ltExtensions?.auth?.enableAdmin;
56
+ if (enableAdmin !== true || features.admin === true) {
57
+ return;
58
+ }
59
+ } catch {
60
+ return;
61
+ }
62
+ warnOnce(
63
+ "admin-plugin-unserved",
64
+ "[LtAuth] ltExtensions.auth.enableAdmin is on, but the API reports no admin plugin (no `admin` in /iam/features). admin.* calls answer 404, and admin.createUser / admin.setUserPassword are not password-hashed by this module. Switch enableAdmin off unless your backend serves the Better-Auth admin routes."
65
+ );
66
+ }
53
67
  export function resetLtWarnOnceState() {
54
68
  warnedKeys.clear();
55
69
  }
@@ -57,6 +71,9 @@ export function isLocalDevApiProxy() {
57
71
  if (import.meta.server) {
58
72
  return false;
59
73
  }
74
+ return isLtApiProxyConfigured();
75
+ }
76
+ function isLtApiProxyConfigured() {
60
77
  try {
61
78
  const runtimeConfig = useRuntimeConfig();
62
79
  const apiProxy = runtimeConfig.public?.apiProxy;
@@ -111,6 +128,25 @@ export function buildLtApiUrl(path) {
111
128
  return path;
112
129
  }
113
130
  }
131
+ export function buildLtPublicApiUrl(path) {
132
+ try {
133
+ const { baseUrl, missing } = resolveLtPublicApiBaseUrl();
134
+ if (missing) {
135
+ warnMissingLtApiUrl("client");
136
+ }
137
+ return `${baseUrl}${path}`;
138
+ } catch {
139
+ return path;
140
+ }
141
+ }
142
+ export function resolveLtPublicApiBaseUrl() {
143
+ if (isLtApiProxyConfigured()) {
144
+ return { baseUrl: "/api", missing: false };
145
+ }
146
+ const pub = useRuntimeConfig().public;
147
+ const publicUrl = pub.apiUrl || pub.ltExtensions?.auth?.baseURL || "";
148
+ return { baseUrl: stripTrailingSlashes(publicUrl), missing: !publicUrl };
149
+ }
114
150
  export function getLtAuthMode() {
115
151
  if (import.meta.server) return "cookie";
116
152
  return resolveLtAuthState(document.cookie)?.authMode || "cookie";
@@ -204,60 +240,105 @@ export function getLtApiBase(basePath) {
204
240
  }
205
241
  return buildLtApiUrl(basePath || "/iam");
206
242
  }
207
- export async function attemptLtJwtSwitch(basePath = "/iam") {
243
+ export async function requestLtJwt(basePath) {
208
244
  try {
209
- const apiBase = getLtApiBase(basePath);
210
- const response = await fetch(`${apiBase}/token`, {
211
- method: "GET",
212
- credentials: "include"
245
+ const response = await fetch(`${getLtApiBase(basePath)}/token`, {
246
+ credentials: "include",
247
+ method: "GET"
213
248
  });
214
- if (response.ok) {
215
- const data = await response.json();
216
- if (isLtJwtShaped(data.token)) {
217
- setLtJwtToken(data.token);
218
- setLtAuthMode("jwt");
219
- console.debug("[LtAuth] Switched to JWT mode");
220
- return true;
221
- }
249
+ if (!response.ok) {
250
+ return null;
222
251
  }
223
- return false;
252
+ const data = await response.json();
253
+ const token = data?.token;
254
+ return isLtJwtShaped(token) ? token : null;
224
255
  } catch {
256
+ return null;
257
+ }
258
+ }
259
+ export async function attemptLtJwtSwitch(basePath) {
260
+ const token = await requestLtJwt(basePath);
261
+ if (!token) {
225
262
  return false;
226
263
  }
264
+ ltCookieAuthFetchState.adoptJwt(token);
265
+ console.debug("[LtAuth] Switched to JWT mode");
266
+ return true;
227
267
  }
228
268
  export function isLtAuthenticated() {
229
269
  if (import.meta.server) return false;
230
270
  return !!resolveLtAuthState(document.cookie)?.user;
231
271
  }
232
- export function createLtAuthFetch(basePath = "/iam") {
272
+ const LT_PATHS_REQUIRING_COOKIES = ["/passkey/", "/two-factor/", "/2fa/", "/get-session"];
273
+ function ltUrlRequiresCookies(url) {
274
+ return LT_PATHS_REQUIRING_COOKIES.some((path) => url.includes(path));
275
+ }
276
+ function ltUrlPath(url) {
277
+ try {
278
+ return new URL(url, "http://lt.invalid").pathname;
279
+ } catch {
280
+ return url;
281
+ }
282
+ }
283
+ function isLtAuthRoute(url, basePath) {
284
+ const base = ltUrlPath(getLtApiBase(basePath)).replace(/\/+$/, "");
285
+ const path = ltUrlPath(url);
286
+ return path === base || path.startsWith(`${base}/`);
287
+ }
288
+ const ltCookieAuthFetchState = {
289
+ adoptJwt: (token) => {
290
+ setLtJwtToken(token);
291
+ setLtAuthMode("jwt");
292
+ },
293
+ isAuthenticated: isLtAuthenticated,
294
+ jwtToken: getLtJwtToken,
295
+ mode: getLtAuthMode
296
+ };
297
+ let ltJwtAfter401 = null;
298
+ function requestLtJwtAfter401(basePath) {
299
+ if (!import.meta.client) {
300
+ return requestLtJwt(basePath);
301
+ }
302
+ if (!ltJwtAfter401) {
303
+ ltJwtAfter401 = requestLtJwt(basePath).finally(() => {
304
+ ltJwtAfter401 = null;
305
+ });
306
+ }
307
+ return ltJwtAfter401;
308
+ }
309
+ export function createLtAuthFetchFor(options) {
310
+ const { basePath, cookiesInJwtMode = "always", state } = options;
311
+ const credentialsFor = (url, jwtMode) => jwtMode && cookiesInJwtMode === "auth-paths" && !ltUrlRequiresCookies(url) ? "omit" : "include";
312
+ const bearerMayHaveFailed = (url) => cookiesInJwtMode === "auth-paths" ? !ltUrlRequiresCookies(url) : !isLtAuthRoute(url, basePath);
233
313
  return async function ltAuthFetch2(input, init) {
234
- const authMode = getLtAuthMode();
235
- const jwtToken = getLtJwtToken();
314
+ const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
315
+ const jwtMode = state.mode() === "jwt";
236
316
  const headers = new Headers(init?.headers);
237
- if (authMode === "jwt" && jwtToken) {
238
- headers.set("Authorization", `Bearer ${jwtToken}`);
317
+ const sentToken = jwtMode ? state.jwtToken() : null;
318
+ if (sentToken) {
319
+ headers.set("Authorization", `Bearer ${sentToken}`);
239
320
  }
240
- const response = await fetch(input, {
241
- ...init,
242
- headers,
243
- credentials: "include"
244
- });
245
- if (response.status === 401 && authMode === "cookie" && isLtAuthenticated()) {
321
+ const response = await fetch(input, { ...init, credentials: credentialsFor(url, jwtMode), headers });
322
+ if (response.status !== 401 || !state.isAuthenticated()) {
323
+ return response;
324
+ }
325
+ if (jwtMode && !bearerMayHaveFailed(url)) {
326
+ return response;
327
+ }
328
+ if (!jwtMode) {
246
329
  console.debug("[LtAuth] Cookie auth failed, attempting JWT fallback...");
247
- const switched = await attemptLtJwtSwitch(basePath);
248
- if (switched) {
249
- const newToken = getLtJwtToken();
250
- if (newToken) {
251
- headers.set("Authorization", `Bearer ${newToken}`);
252
- return fetch(input, {
253
- ...init,
254
- headers,
255
- credentials: "include"
256
- });
257
- }
258
- }
259
330
  }
260
- return response;
331
+ const token = await requestLtJwtAfter401(basePath);
332
+ if (!token) {
333
+ return response;
334
+ }
335
+ state.adoptJwt(token);
336
+ const retryHeaders = new Headers(headers);
337
+ retryHeaders.set("Authorization", `Bearer ${token}`);
338
+ return fetch(input, { ...init, credentials: credentialsFor(url, true), headers: retryHeaders });
261
339
  };
262
340
  }
263
- export const ltAuthFetch = createLtAuthFetch("/iam");
341
+ export function createLtAuthFetch(basePath) {
342
+ return createLtAuthFetchFor({ basePath, state: ltCookieAuthFetchState });
343
+ }
344
+ export const ltAuthFetch = createLtAuthFetch();
@@ -1,19 +1,17 @@
1
1
  {
2
2
  "lt": {
3
3
  "auth": {
4
- "loggingOut": "Abmelden...",
5
4
  "noPasskeySelected": "Kein Passkey ausgewählt",
6
5
  "passkeyAborted": "Passkey-Authentifizierung wurde abgebrochen",
6
+ "passkeyAlreadyRegistered": "Du hast bereits einen Passkey für diese Website registriert. Lösche ihn zuerst oder verwende einen anderen Authenticator.",
7
7
  "passkeyCreationAborted": "Passkey-Erstellung wurde abgebrochen",
8
8
  "passkeyError": "Konnte Passkey-Optionen nicht laden",
9
9
  "passkeyFailed": "Passkey-Anmeldung fehlgeschlagen",
10
10
  "passkeyRegisterFailed": "Passkey-Registrierung fehlgeschlagen",
11
- "registerOptionsError": "Konnte Registrierungsoptionen nicht laden",
12
- "sessionExpired": "Sitzung abgelaufen"
11
+ "registerOptionsError": "Konnte Registrierungsoptionen nicht laden"
13
12
  },
14
13
  "error": {
15
- "title": "Fehler",
16
- "loadFailed": "Fehlerübersetzungen konnten nicht geladen werden"
14
+ "title": "Fehler"
17
15
  },
18
16
  "share": {
19
17
  "copied": "Link kopiert",
@@ -1,19 +1,17 @@
1
1
  {
2
2
  "lt": {
3
3
  "auth": {
4
- "loggingOut": "Logging out...",
5
4
  "noPasskeySelected": "No passkey selected",
6
5
  "passkeyAborted": "Passkey authentication was cancelled",
6
+ "passkeyAlreadyRegistered": "You already registered a passkey for this website. Delete it first or use another authenticator.",
7
7
  "passkeyCreationAborted": "Passkey creation was cancelled",
8
8
  "passkeyError": "Could not load passkey options",
9
9
  "passkeyFailed": "Passkey login failed",
10
10
  "passkeyRegisterFailed": "Passkey registration failed",
11
- "registerOptionsError": "Could not load registration options",
12
- "sessionExpired": "Session expired"
11
+ "registerOptionsError": "Could not load registration options"
13
12
  },
14
13
  "error": {
15
- "title": "Error",
16
- "loadFailed": "Failed to load error translations"
14
+ "title": "Error"
17
15
  },
18
16
  "share": {
19
17
  "copied": "Link copied",
@@ -1,8 +1,18 @@
1
1
  /**
2
2
  * Error Translation Plugin
3
3
  *
4
- * Automatically loads error translations on app start.
5
- * Provides global helper methods: $ltTranslateError, $ltShowErrorToast
4
+ * Loads the error translations for the current locale once the app is mounted, and provides
5
+ * the global helpers $ltTranslateError and $ltShowErrorToast.
6
+ *
7
+ * The load does not hold back the start (DEV-4078). Until it is done, `translateError`
8
+ * returns the developer message, and every template that renders it switches to the
9
+ * translation when it arrives, because the translations live in shared state.
10
+ *
11
+ * It starts after the mount on purpose, not merely without `await`: server-rendered HTML
12
+ * carries the developer message, since the server loads no translations. Translations that
13
+ * arrived before hydration would make the client render a different text than the server
14
+ * did (a hydration mismatch). After the mount, hydration has already seen the server's text.
15
+ * How a project translates messages during SSR: README, "Error Translation".
6
16
  */
7
17
  import type { ObjectPlugin, Plugin } from '#app';
8
18
  declare const _default: Plugin & ObjectPlugin;
@@ -1,17 +1,15 @@
1
1
  import { defineNuxtPlugin, useRuntimeConfig } from "#imports";
2
2
  import { useLtErrorTranslation } from "../composables/use-lt-error-translation.js";
3
- export default defineNuxtPlugin(async (nuxtApp) => {
3
+ export default defineNuxtPlugin((nuxtApp) => {
4
4
  const runtimeConfig = useRuntimeConfig();
5
5
  const config = runtimeConfig.public?.ltExtensions?.errorTranslation;
6
6
  if (config?.enabled === false) {
7
7
  return;
8
8
  }
9
9
  const { loadTranslations, translateError, showErrorToast } = useLtErrorTranslation();
10
- try {
11
- await loadTranslations();
12
- } catch (error) {
13
- console.warn("[LtErrorTranslation] Initial load failed:", error);
14
- }
10
+ nuxtApp.hook("app:mounted", () => {
11
+ void nuxtApp.runWithContext(() => loadTranslations());
12
+ });
15
13
  nuxtApp.provide("ltTranslateError", translateError);
16
14
  nuxtApp.provide("ltShowErrorToast", showErrorToast);
17
15
  });