nuxt-umbu 0.0.1

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.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -0
  3. package/dist/module.d.mts +22 -0
  4. package/dist/module.json +9 -0
  5. package/dist/module.mjs +114 -0
  6. package/dist/runtime/composables/autx.d.ts +3 -0
  7. package/dist/runtime/composables/autx.js +62 -0
  8. package/dist/runtime/composables/useConfig.d.ts +4 -0
  9. package/dist/runtime/composables/useConfig.js +4 -0
  10. package/dist/runtime/composables/useEnsureCsrf.d.ts +2 -0
  11. package/dist/runtime/composables/useEnsureCsrf.js +11 -0
  12. package/dist/runtime/composables/useStates.d.ts +2 -0
  13. package/dist/runtime/composables/useStates.js +6 -0
  14. package/dist/runtime/passport/middleware/2fa.d.ts +2 -0
  15. package/dist/runtime/passport/middleware/2fa.js +46 -0
  16. package/dist/runtime/passport/middleware/auth.d.ts +2 -0
  17. package/dist/runtime/passport/middleware/auth.js +46 -0
  18. package/dist/runtime/passport/plugin.d.ts +2 -0
  19. package/dist/runtime/passport/plugin.js +282 -0
  20. package/dist/runtime/passport/server/api/2fa.d.ts +5 -0
  21. package/dist/runtime/passport/server/api/2fa.js +78 -0
  22. package/dist/runtime/passport/server/api/login.d.ts +6 -0
  23. package/dist/runtime/passport/server/api/login.js +63 -0
  24. package/dist/runtime/passport/server/api/logout.d.ts +10 -0
  25. package/dist/runtime/passport/server/api/logout.js +37 -0
  26. package/dist/runtime/passport/server/api/refresh.d.ts +6 -0
  27. package/dist/runtime/passport/server/api/refresh.js +72 -0
  28. package/dist/runtime/passport/server/api/session.d.ts +7 -0
  29. package/dist/runtime/passport/server/api/session.js +16 -0
  30. package/dist/runtime/passport/server/middleware/protected.d.ts +2 -0
  31. package/dist/runtime/passport/server/middleware/protected.js +17 -0
  32. package/dist/runtime/passport/server/utils/index.d.ts +14 -0
  33. package/dist/runtime/passport/server/utils/index.js +14 -0
  34. package/dist/runtime/passport/utils/index.d.ts +1 -0
  35. package/dist/runtime/passport/utils/index.js +1 -0
  36. package/dist/runtime/passport/utils/middleware.d.ts +22 -0
  37. package/dist/runtime/passport/utils/middleware.js +36 -0
  38. package/dist/runtime/sanctum/middleware/2fa.d.ts +2 -0
  39. package/dist/runtime/sanctum/middleware/2fa.js +37 -0
  40. package/dist/runtime/sanctum/middleware/auth.d.ts +2 -0
  41. package/dist/runtime/sanctum/middleware/auth.js +43 -0
  42. package/dist/runtime/sanctum/plugin.d.ts +2 -0
  43. package/dist/runtime/sanctum/plugin.js +272 -0
  44. package/dist/runtime/sanctum/utils/index.d.ts +1 -0
  45. package/dist/runtime/sanctum/utils/index.js +1 -0
  46. package/dist/runtime/sanctum/utils/middleware.d.ts +32 -0
  47. package/dist/runtime/sanctum/utils/middleware.js +48 -0
  48. package/dist/runtime/types/core/auth-instance.d.ts +1 -0
  49. package/dist/runtime/types/core/auth-instance.js +0 -0
  50. package/dist/runtime/types/core/plugin.d.ts +0 -0
  51. package/dist/runtime/types/core/state.d.ts +5 -0
  52. package/dist/runtime/types/core/state.js +0 -0
  53. package/dist/runtime/types/index.d.ts +28 -0
  54. package/dist/runtime/types/index.js +4 -0
  55. package/dist/runtime/types/providers/passport.d.ts +50 -0
  56. package/dist/runtime/types/providers/passport.js +0 -0
  57. package/dist/runtime/types/providers/sanctum.d.ts +29 -0
  58. package/dist/runtime/types/providers/sanctum.js +0 -0
  59. package/dist/runtime/types/shared.d.ts +19 -0
  60. package/dist/runtime/types/shared.js +0 -0
  61. package/dist/types.d.mts +7 -0
  62. package/package.json +74 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aslan Gama
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # Nuxt Umbu
2
+
3
+ Nuxt Umbu is an authentication module for **Nuxt** designed to work seamlessly with **Laravel Sanctum** and **Laravel Passport**.
4
+
5
+ It provides a secure and SSR-compatible authentication layer with built-in support for cookies, tokens, middleware, composables, and optional Two-Factor Authentication (2FA).
6
+
7
+ ## Features
8
+
9
+ - 🔐 Authentication for **Nuxt**
10
+ - ⚡ Built for **SSR and SPA**
11
+ - 🍪 Secure **HTTP-only cookie authentication (Sanctum)**
12
+ - 🔑 **OAuth2 token authentication (Passport)**
13
+ - 🧩 Strategy-based architecture
14
+ - 🛡 Built-in **CSRF protection**
15
+ - 📦 `$auth` instance available globally
16
+ - 🧠 Route middleware for protected pages
17
+ - 🔄 Automatic user fetching
18
+ - 🔑 Optional **Two-Factor Authentication (2FA)**
19
+ - 🪝 Extensible for future authentication providers
20
+
21
+ ---
@@ -0,0 +1,22 @@
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
+ import { AuthSecretConfig, ModuleOptions } from '../dist/runtime/types/index.js';
3
+
4
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions & {
5
+ twoFactorAuth: boolean;
6
+ }, ModuleOptions & {
7
+ twoFactorAuth: boolean;
8
+ }, false>;
9
+
10
+ declare module 'nuxt/schema' {
11
+ interface RuntimeConfig {
12
+ secret?: Record<string, AuthSecretConfig>;
13
+ }
14
+ interface PublicRuntimeConfig {
15
+ baseURL: string;
16
+ }
17
+ interface NuxtConfig {
18
+ auth?: ModuleOptions;
19
+ }
20
+ }
21
+
22
+ export { _default as default };
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "nuxt-umbu",
3
+ "configKey": "auth",
4
+ "version": "0.0.1",
5
+ "builder": {
6
+ "@nuxt/module-builder": "1.0.2",
7
+ "unbuild": "unknown"
8
+ }
9
+ }
@@ -0,0 +1,114 @@
1
+ import { defineNuxtModule, useLogger, createResolver, addImportsDir, addRouteMiddleware, addServerHandler, addPluginTemplate, addTypeTemplate } from '@nuxt/kit';
2
+ import { defu } from 'defu';
3
+ import kebabCase from 'lodash.kebabcase';
4
+ import fs from 'fs';
5
+
6
+ const PACKAGE_NAME = "nuxt-umbu";
7
+ const module$1 = defineNuxtModule({
8
+ meta: {
9
+ name: PACKAGE_NAME,
10
+ configKey: "auth"
11
+ },
12
+ async setup(options, nuxt) {
13
+ const logger = useLogger(PACKAGE_NAME);
14
+ const { resolve } = createResolver(import.meta.url);
15
+ const isDev = nuxt.options.dev;
16
+ const provider = options.provider || "sanctum";
17
+ options = defu(options, {
18
+ cookie: {
19
+ options: {
20
+ httpOnly: false,
21
+ secure: false,
22
+ sameSite: "Lax",
23
+ priority: "high"
24
+ },
25
+ prefix: "auth."
26
+ },
27
+ twoFactorAuth: false
28
+ });
29
+ options.cookie = options.cookie ?? { prefix: "auth.", options: {} };
30
+ options.cookie.options = options.cookie.options ?? {
31
+ httpOnly: false,
32
+ secure: false,
33
+ sameSite: "Lax",
34
+ priority: "high"
35
+ };
36
+ if (isDev) {
37
+ options.cookie.prefix = "auth.";
38
+ options.cookie.options.secure = false;
39
+ }
40
+ addImportsDir(resolve("./runtime/composables"));
41
+ addRouteMiddleware({
42
+ name: "auth",
43
+ path: resolve("./runtime/" + provider + "/middleware/auth")
44
+ });
45
+ if (provider === "passport") {
46
+ const runtimeConfig = nuxt.options.runtimeConfig;
47
+ if (!runtimeConfig.secret || typeof runtimeConfig.secret !== "object" || Object.keys(runtimeConfig.secret).length === 0) {
48
+ logger.error(`Missing "runtimeConfig.secret" in nuxt.config.ts`);
49
+ return;
50
+ }
51
+ Object.entries(runtimeConfig.secret).forEach(([key, config]) => {
52
+ if (!options.strategies[key]) {
53
+ logger.error(
54
+ `[${PACKAGE_NAME}] Strategy "${key}" found in "runtimeConfig.secret" but not in "options.strategies". Skipping validation.`
55
+ );
56
+ return;
57
+ }
58
+ if (!config.client_id || !config.client_secret || !config.grant_type) {
59
+ logger.error(
60
+ `[${PACKAGE_NAME}] Invalid "secret.${key}" configuration. Required keys: client_id, client_secret, grant_type.`
61
+ );
62
+ return;
63
+ }
64
+ });
65
+ Object.entries(options.strategies).forEach(
66
+ ([strategyName, strategy]) => {
67
+ strategy.handler = strategy.handler ?? [];
68
+ strategy.endpoints = strategy.endpoints || {};
69
+ strategy.endpoints = defu(strategy.endpoints, {
70
+ logout: { alias: "logout" }
71
+ });
72
+ Object.entries(strategy.endpoints).filter(
73
+ ([key, endpoint]) => key !== "user" && (key === "logout" || endpoint.url && endpoint.method)
74
+ ).forEach(([key, endpoint]) => {
75
+ const typedEndpoint = endpoint;
76
+ const route = `/api/${kebabCase(typedEndpoint.alias) || typedEndpoint.url.replace(/^\/(api|oauth)\//, "")}`;
77
+ const handlerFile = resolve(`./runtime/passport/server/api/${key}`);
78
+ strategy.handler.push({ [key]: route });
79
+ addServerHandler({
80
+ route,
81
+ handler: handlerFile
82
+ });
83
+ });
84
+ }
85
+ );
86
+ }
87
+ const has2FA = Object.values(options.strategies).some(
88
+ (strategy) => strategy.endpoints?.["2fa"]?.url && strategy.endpoints?.["2fa"]?.method
89
+ );
90
+ if (has2FA) {
91
+ options.twoFactorAuth = true;
92
+ addRouteMiddleware({
93
+ name: "_2fa",
94
+ path: resolve("./runtime/" + provider + "/middleware/2fa")
95
+ });
96
+ logger.success("Middleware `_2fa` enabled");
97
+ }
98
+ nuxt.options.runtimeConfig.public[PACKAGE_NAME] = options;
99
+ const hasTsPlugin = fs.existsSync(resolve(`./runtime/${provider}/plugin.ts`));
100
+ addPluginTemplate({
101
+ src: resolve(`./runtime/${provider}/plugin.${hasTsPlugin ? "ts" : "js"}`),
102
+ filename: `plugin.${hasTsPlugin ? "ts" : "js"}`,
103
+ mode: "all"
104
+ });
105
+ addTypeTemplate({
106
+ src: resolve("./auth.d.ts"),
107
+ filename: "auth.d.ts"
108
+ });
109
+ nuxt.options.alias["#auth-utils"] = resolve("./runtime/" + provider + "/utils");
110
+ logger.success("`nuxt-umbu` setup done");
111
+ }
112
+ });
113
+
114
+ export { module$1 as default };
@@ -0,0 +1,3 @@
1
+ import { type FetchOptions } from 'ofetch';
2
+ export type AutxOptions<T = any> = FetchOptions<'json', T>;
3
+ export declare function $autx<T = any>(request: string, options?: AutxOptions<T>): Promise<T>;
@@ -0,0 +1,62 @@
1
+ import { $fetch } from "ofetch";
2
+ import { useNuxtApp, useRuntimeConfig, reloadNuxtApp, useAuthConfig, createError } from "#imports";
3
+ import { useEnsureCsrf } from "../composables/useEnsureCsrf.js";
4
+ const CSRF_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
5
+ export async function $autx(request, options = {}) {
6
+ const { $auth } = useNuxtApp();
7
+ const baseURL = useRuntimeConfig().public.baseURL;
8
+ const { provider } = useAuthConfig();
9
+ if (!$auth || !$auth.headers) {
10
+ throw new Error("Auth instance is not available or missing headers.");
11
+ }
12
+ const method = (options.method || "GET").toUpperCase();
13
+ if (provider === "sanctum" && CSRF_METHODS.includes(method)) {
14
+ await useEnsureCsrf($auth);
15
+ }
16
+ const authHeaders = $auth.headers instanceof Headers ? Object.fromEntries($auth.headers.entries()) : $auth.headers;
17
+ const runtimeBaseURL = typeof baseURL === "string" ? baseURL : void 0;
18
+ const fetchOptions = {
19
+ ...options,
20
+ baseURL: options.baseURL ?? runtimeBaseURL,
21
+ credentials: options.credentials ?? (provider === "sanctum" ? "include" : void 0),
22
+ headers: {
23
+ ...authHeaders,
24
+ ...options.headers
25
+ }
26
+ };
27
+ return $fetch(request, {
28
+ ...fetchOptions,
29
+ async onResponseError(context) {
30
+ const { request: request2, response } = context;
31
+ let errorBody;
32
+ try {
33
+ errorBody = response._data ?? await response.text();
34
+ } catch (e) {
35
+ errorBody = "Unknown error";
36
+ }
37
+ console.error("[API Error]", {
38
+ request: request2,
39
+ status: response.status,
40
+ body: errorBody,
41
+ fullResponse: response
42
+ });
43
+ if (response.status === 401) {
44
+ if (import.meta.client) {
45
+ console.warn("[auth] 401 Unauthorized \u2013 reloading app");
46
+ const strategy = $auth.strategy;
47
+ if (strategy) {
48
+ await $auth.logout(strategy);
49
+ }
50
+ if (provider === "sanctum") {
51
+ reloadNuxtApp();
52
+ }
53
+ }
54
+ return;
55
+ }
56
+ throw createError({
57
+ statusCode: response.status,
58
+ data: errorBody
59
+ });
60
+ }
61
+ });
62
+ }
@@ -0,0 +1,4 @@
1
+ import type { ModuleOptions } from '../types/index.js';
2
+ export declare const useAuthConfig: () => ModuleOptions & {
3
+ twoFactorAuth: boolean;
4
+ };
@@ -0,0 +1,4 @@
1
+ import { useRuntimeConfig } from "#imports";
2
+ export const useAuthConfig = () => {
3
+ return useRuntimeConfig().public["nuxt-umbu"];
4
+ };
@@ -0,0 +1,2 @@
1
+ import type { AuthInstance } from '../types/index.js';
2
+ export declare function useEnsureCsrf(auth?: AuthInstance): Promise<void>;
@@ -0,0 +1,11 @@
1
+ import { useCookie, useNuxtApp } from "#imports";
2
+ export async function useEnsureCsrf(auth) {
3
+ const { $auth } = useNuxtApp();
4
+ if (!$auth) return;
5
+ const xsrf = useCookie("XSRF-TOKEN").value;
6
+ if (xsrf) {
7
+ $auth.headers.set("X-XSRF-TOKEN", decodeURIComponent(xsrf));
8
+ return;
9
+ }
10
+ await $auth.csrfToken();
11
+ }
@@ -0,0 +1,2 @@
1
+ import type { AuthState } from '../types/index.js';
2
+ export declare const useAuthStore: () => import("vue").Ref<AuthState, AuthState>;
@@ -0,0 +1,6 @@
1
+ import { useState } from "#imports";
2
+ export const useAuthStore = () => useState("auth", () => ({
3
+ user: null,
4
+ loggedIn: false,
5
+ strategy: ""
6
+ }));
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/app").RouteMiddleware;
2
+ export default _default;
@@ -0,0 +1,46 @@
1
+ import {
2
+ useNuxtApp,
3
+ useCookie,
4
+ useAuthStore,
5
+ createError,
6
+ useRequestEvent,
7
+ defineNuxtRouteMiddleware
8
+ } from "#imports";
9
+ import { handleLogout, validateSession, getRedirectPath } from "#auth-utils";
10
+ export default defineNuxtRouteMiddleware(async () => {
11
+ const { $auth } = useNuxtApp();
12
+ const store = useAuthStore();
13
+ if (!$auth) {
14
+ throw createError({
15
+ statusCode: 500,
16
+ statusMessage: "Auth plugin is not initialized"
17
+ });
18
+ }
19
+ if (import.meta.server) {
20
+ const event = useRequestEvent();
21
+ if (!event) return;
22
+ const strategyName = useCookie($auth.prefix + `strategy`).value;
23
+ const token = strategyName ? useCookie($auth.prefix + `_2fa.` + strategyName).value : null;
24
+ const expires = strategyName ? useCookie($auth.prefix + `_2fa_expiration.` + strategyName).value : null;
25
+ if (!validateSession(strategyName, token, expires)) {
26
+ return await handleLogout(strategyName, getRedirectPath(strategyName), "has2FA");
27
+ }
28
+ if (token) {
29
+ $auth.headers.set("2fa", token);
30
+ }
31
+ }
32
+ if (import.meta.client) {
33
+ const strategy = localStorage.getItem($auth.prefix + `strategy`);
34
+ const token = strategy ? localStorage.getItem($auth.prefix + `_2fa.` + strategy) : null;
35
+ const expires = strategy ? localStorage.getItem($auth.prefix + `_2fa_expiration.` + strategy) : null;
36
+ if (!validateSession(strategy, token, expires) || $auth.strategy !== strategy || $auth.strategy !== store.value.strategy) {
37
+ return await handleLogout(strategy, getRedirectPath(strategy), "has2FA");
38
+ }
39
+ if (token) {
40
+ $auth.headers.set("2fa", token);
41
+ }
42
+ if (!$auth.user || !$auth.loggedIn || !store.value.user || !store.value.loggedIn) {
43
+ return await handleLogout(strategy, getRedirectPath(strategy), "has2FA");
44
+ }
45
+ }
46
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/app").RouteMiddleware;
2
+ export default _default;
@@ -0,0 +1,46 @@
1
+ import {
2
+ useNuxtApp,
3
+ useCookie,
4
+ useAuthStore,
5
+ createError,
6
+ useRequestEvent,
7
+ defineNuxtRouteMiddleware
8
+ } from "#imports";
9
+ import { handleLogout, validateSession, getRedirectPath } from "#auth-utils";
10
+ export default defineNuxtRouteMiddleware(async () => {
11
+ const { $auth } = useNuxtApp();
12
+ const store = useAuthStore();
13
+ if (!$auth) {
14
+ throw createError({
15
+ statusCode: 500,
16
+ statusMessage: "Auth plugin is not initialized"
17
+ });
18
+ }
19
+ if (import.meta.server) {
20
+ const event = useRequestEvent();
21
+ if (!event) return;
22
+ const strategyName = useCookie($auth.prefix + `strategy`).value;
23
+ const token = strategyName ? useCookie($auth.prefix + `_token.` + strategyName).value : null;
24
+ const expires = strategyName ? useCookie($auth.prefix + `_token_expiration.` + strategyName).value : null;
25
+ if (!validateSession(strategyName, token, expires)) {
26
+ return await handleLogout(strategyName, getRedirectPath(strategyName), "auth");
27
+ }
28
+ if (token) {
29
+ $auth.headers.set("Authorization", token);
30
+ }
31
+ }
32
+ if (import.meta.client) {
33
+ const strategy = localStorage.getItem($auth.prefix + `strategy`);
34
+ const token = strategy ? localStorage.getItem($auth.prefix + `_token.` + strategy) : null;
35
+ const expires = strategy ? localStorage.getItem($auth.prefix + `_token_expiration.` + strategy) : null;
36
+ if (!validateSession(strategy, token, expires) || $auth.strategy !== strategy || $auth.strategy !== store.value.strategy) {
37
+ return await handleLogout(strategy, getRedirectPath(strategy), "auth");
38
+ }
39
+ if (token) {
40
+ $auth.headers.set("Authorization", token);
41
+ }
42
+ if (!$auth.user || !$auth.loggedIn || !store.value.user || !store.value.loggedIn) {
43
+ return await handleLogout(strategy, getRedirectPath(strategy), "auth");
44
+ }
45
+ }
46
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
2
+ export default _default;