nuxt-bearer-auth 0.1.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.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +265 -0
  3. package/dist/module.cjs +5 -0
  4. package/dist/module.d.mts +134 -0
  5. package/dist/module.d.ts +134 -0
  6. package/dist/module.json +12 -0
  7. package/dist/module.mjs +222 -0
  8. package/dist/runtime/composables/useBearerAuth.d.ts +34 -0
  9. package/dist/runtime/composables/useBearerAuth.js +259 -0
  10. package/dist/runtime/middleware/bearer-auth.global.d.ts +3 -0
  11. package/dist/runtime/middleware/bearer-auth.global.js +28 -0
  12. package/dist/runtime/plugins/bearer-auth.server.d.ts +3 -0
  13. package/dist/runtime/plugins/bearer-auth.server.js +26 -0
  14. package/dist/runtime/server/api/auth/forgot-password.post.d.ts +3 -0
  15. package/dist/runtime/server/api/auth/forgot-password.post.js +16 -0
  16. package/dist/runtime/server/api/auth/login.post.d.ts +15 -0
  17. package/dist/runtime/server/api/auth/login.post.js +54 -0
  18. package/dist/runtime/server/api/auth/logout.post.d.ts +6 -0
  19. package/dist/runtime/server/api/auth/logout.post.js +20 -0
  20. package/dist/runtime/server/api/auth/me.get.d.ts +5 -0
  21. package/dist/runtime/server/api/auth/me.get.js +37 -0
  22. package/dist/runtime/server/api/auth/otp-verification.post.d.ts +8 -0
  23. package/dist/runtime/server/api/auth/otp-verification.post.js +38 -0
  24. package/dist/runtime/server/api/auth/refresh.post.d.ts +7 -0
  25. package/dist/runtime/server/api/auth/refresh.post.js +37 -0
  26. package/dist/runtime/server/api/auth/register.post.d.ts +8 -0
  27. package/dist/runtime/server/api/auth/register.post.js +32 -0
  28. package/dist/runtime/server/api/auth/resend-otp/[identifier].post.d.ts +3 -0
  29. package/dist/runtime/server/api/auth/resend-otp/[identifier].post.js +21 -0
  30. package/dist/runtime/server/api/auth/reset-password.post.d.ts +3 -0
  31. package/dist/runtime/server/api/auth/reset-password.post.js +16 -0
  32. package/dist/runtime/server/api/auth/sessions/[id].delete.d.ts +6 -0
  33. package/dist/runtime/server/api/auth/sessions/[id].delete.js +20 -0
  34. package/dist/runtime/server/api/auth/sessions.get.d.ts +5 -0
  35. package/dist/runtime/server/api/auth/sessions.get.js +11 -0
  36. package/dist/runtime/server/api/auth/social-login.post.d.ts +7 -0
  37. package/dist/runtime/server/api/auth/social-login.post.js +41 -0
  38. package/dist/runtime/server/middleware/auth.d.ts +3 -0
  39. package/dist/runtime/server/middleware/auth.js +29 -0
  40. package/dist/runtime/server/plugins/redis.d.ts +3 -0
  41. package/dist/runtime/server/plugins/redis.js +23 -0
  42. package/dist/runtime/server/utils/config.d.ts +16 -0
  43. package/dist/runtime/server/utils/config.js +24 -0
  44. package/dist/runtime/server/utils/errors.d.ts +2 -0
  45. package/dist/runtime/server/utils/errors.js +20 -0
  46. package/dist/runtime/server/utils/external-api.d.ts +15 -0
  47. package/dist/runtime/server/utils/external-api.js +31 -0
  48. package/dist/runtime/server/utils/normalize.d.ts +16 -0
  49. package/dist/runtime/server/utils/normalize.js +30 -0
  50. package/dist/runtime/server/utils/paths.d.ts +4 -0
  51. package/dist/runtime/server/utils/paths.js +23 -0
  52. package/dist/runtime/server/utils/sessions.d.ts +4645 -0
  53. package/dist/runtime/server/utils/sessions.js +207 -0
  54. package/dist/runtime/types/auth.d.ts +49 -0
  55. package/dist/runtime/types/auth.js +0 -0
  56. package/dist/runtime/types/h3.d.ts +7 -0
  57. package/dist/types.d.mts +7 -0
  58. package/dist/types.d.ts +7 -0
  59. package/package.json +58 -0
@@ -0,0 +1,20 @@
1
+ import { callAuthApi, getAuthEndpoint } from "../../utils/external-api.js";
2
+ import { destroyBearerAuthSession } from "../../utils/sessions.js";
3
+ import { defineEventHandler } from "h3";
4
+ export default defineEventHandler(async (event) => {
5
+ try {
6
+ await callAuthApi(getAuthEndpoint("logout"), {
7
+ event,
8
+ method: "POST",
9
+ body: {}
10
+ });
11
+ } catch (error) {
12
+ console.warn("[nuxt-bearer-auth] Remote logout failed:", error);
13
+ } finally {
14
+ await destroyBearerAuthSession(event);
15
+ }
16
+ return {
17
+ success: true,
18
+ message: "Logged out successfully"
19
+ };
20
+ });
@@ -0,0 +1,5 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ user: import("../../../types/auth").BearerAuthUser;
3
+ }>>;
4
+ export default _default;
5
+ //# sourceMappingURL=me.get.d.ts.map
@@ -0,0 +1,37 @@
1
+ import { createError, defineEventHandler, getQuery } from "h3";
2
+ import { callAuthApi, getAuthEndpoint } from "../../utils/external-api.js";
3
+ import { toPublicError } from "../../utils/errors.js";
4
+ import { normalizeAuthResponse } from "../../utils/normalize.js";
5
+ import {
6
+ requireBearerAuthSession,
7
+ updateBearerAuthSession
8
+ } from "../../utils/sessions.js";
9
+ export default defineEventHandler(async (event) => {
10
+ const session = requireBearerAuthSession(event);
11
+ const query = getQuery(event);
12
+ const forceRefresh = query.refresh === "true" || query.refresh === "1";
13
+ if (!forceRefresh && session.profile) {
14
+ return {
15
+ user: session.profile
16
+ };
17
+ }
18
+ try {
19
+ const response = await callAuthApi(getAuthEndpoint("me"), {
20
+ event,
21
+ method: "GET"
22
+ });
23
+ const auth = normalizeAuthResponse(response);
24
+ if (!auth.user) {
25
+ throw createError({
26
+ statusCode: 401,
27
+ statusMessage: auth.message || "User unauthenticated"
28
+ });
29
+ }
30
+ await updateBearerAuthSession(event, { profile: auth.user });
31
+ return {
32
+ user: auth.user
33
+ };
34
+ } catch (error) {
35
+ toPublicError(error, "Fetching authenticated user failed");
36
+ }
37
+ });
@@ -0,0 +1,8 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ success: boolean;
3
+ user: import("../../../types/auth").BearerAuthUser | null;
4
+ message: string;
5
+ data: unknown;
6
+ }>>;
7
+ export default _default;
8
+ //# sourceMappingURL=otp-verification.post.d.ts.map
@@ -0,0 +1,38 @@
1
+ import { createError, defineEventHandler, readBody } from "h3";
2
+ import { callAuthApi, getAuthEndpoint } from "../../utils/external-api.js";
3
+ import { toPublicError } from "../../utils/errors.js";
4
+ import { normalizeAuthResponse } from "../../utils/normalize.js";
5
+ import { createBearerAuthSession } from "../../utils/sessions.js";
6
+ export default defineEventHandler(async (event) => {
7
+ try {
8
+ const body = await readBody(event);
9
+ if (!body.otp || !body.identifier) {
10
+ throw createError({
11
+ statusCode: 422,
12
+ statusMessage: "OTP and identifier are required"
13
+ });
14
+ }
15
+ const response = await callAuthApi(getAuthEndpoint("verifyOtp"), {
16
+ event,
17
+ method: "POST",
18
+ body
19
+ });
20
+ const auth = normalizeAuthResponse(response);
21
+ if (auth.token && auth.userId) {
22
+ await createBearerAuthSession(event, {
23
+ userId: auth.userId,
24
+ token: auth.token,
25
+ refreshToken: auth.refreshToken,
26
+ profile: auth.user
27
+ });
28
+ }
29
+ return {
30
+ success: true,
31
+ user: auth.user || null,
32
+ message: auth.message || "OTP verified successfully",
33
+ data: response
34
+ };
35
+ } catch (error) {
36
+ toPublicError(error, "OTP verification failed");
37
+ }
38
+ });
@@ -0,0 +1,7 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ success: boolean;
3
+ user: import("../../../types/auth").BearerAuthUser | null;
4
+ message: string;
5
+ }>>;
6
+ export default _default;
7
+ //# sourceMappingURL=refresh.post.d.ts.map
@@ -0,0 +1,37 @@
1
+ import { callAuthApi, getAuthEndpoint } from "../../utils/external-api.js";
2
+ import { toPublicError } from "../../utils/errors.js";
3
+ import { normalizeAuthResponse } from "../../utils/normalize.js";
4
+ import {
5
+ requireBearerAuthSession,
6
+ updateBearerAuthSession
7
+ } from "../../utils/sessions.js";
8
+ import { createError, defineEventHandler } from "h3";
9
+ export default defineEventHandler(async (event) => {
10
+ const session = requireBearerAuthSession(event);
11
+ try {
12
+ const response = await callAuthApi(getAuthEndpoint("refresh"), {
13
+ event,
14
+ method: "POST",
15
+ body: session.refreshToken ? { refresh_token: session.refreshToken, refreshToken: session.refreshToken } : {}
16
+ });
17
+ const auth = normalizeAuthResponse(response);
18
+ if (!auth.token) {
19
+ throw createError({
20
+ statusCode: 401,
21
+ statusMessage: auth.message || "Token refresh failed"
22
+ });
23
+ }
24
+ await updateBearerAuthSession(event, {
25
+ token: auth.token,
26
+ refreshToken: auth.refreshToken || session.refreshToken,
27
+ profile: auth.user || session.profile
28
+ });
29
+ return {
30
+ success: true,
31
+ user: auth.user || session.profile,
32
+ message: auth.message || "Session refreshed"
33
+ };
34
+ } catch (error) {
35
+ toPublicError(error, "Refreshing session failed");
36
+ }
37
+ });
@@ -0,0 +1,8 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ success: boolean;
3
+ user: import("../../../types/auth").BearerAuthUser | null;
4
+ message: string;
5
+ data: unknown;
6
+ }>>;
7
+ export default _default;
8
+ //# sourceMappingURL=register.post.d.ts.map
@@ -0,0 +1,32 @@
1
+ import { defineEventHandler, readBody } from "h3";
2
+ import { callAuthApi, getAuthEndpoint } from "../../utils/external-api.js";
3
+ import { toPublicError } from "../../utils/errors.js";
4
+ import { normalizeAuthResponse } from "../../utils/normalize.js";
5
+ import { createBearerAuthSession } from "../../utils/sessions.js";
6
+ export default defineEventHandler(async (event) => {
7
+ try {
8
+ const body = await readBody(event);
9
+ const response = await callAuthApi(getAuthEndpoint("register"), {
10
+ event,
11
+ method: "POST",
12
+ body
13
+ });
14
+ const auth = normalizeAuthResponse(response);
15
+ if (auth.token && auth.userId) {
16
+ await createBearerAuthSession(event, {
17
+ userId: auth.userId,
18
+ token: auth.token,
19
+ refreshToken: auth.refreshToken,
20
+ profile: auth.user
21
+ });
22
+ }
23
+ return {
24
+ success: auth.success,
25
+ user: auth.user || null,
26
+ message: auth.message || "Registration successful",
27
+ data: response
28
+ };
29
+ } catch (error) {
30
+ toPublicError(error, "Registration failed");
31
+ }
32
+ });
@@ -0,0 +1,3 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<unknown>>;
2
+ export default _default;
3
+ //# sourceMappingURL=%5Bidentifier%5D.post.d.ts.map
@@ -0,0 +1,21 @@
1
+ import { defineEventHandler, getRouterParam, readBody } from "h3";
2
+ import { callAuthApi, getAuthEndpoint } from "../../../utils/external-api.js";
3
+ import { toPublicError } from "../../../utils/errors.js";
4
+ import { interpolatePath } from "../../../utils/paths.js";
5
+ export default defineEventHandler(async (event) => {
6
+ try {
7
+ const identifier = getRouterParam(event, "identifier");
8
+ const body = await readBody(event).catch(() => ({}));
9
+ const endpoint = interpolatePath(getAuthEndpoint("resendOtp"), {
10
+ identifier
11
+ });
12
+ const response = await callAuthApi(endpoint, {
13
+ event,
14
+ method: "POST",
15
+ body
16
+ });
17
+ return response;
18
+ } catch (error) {
19
+ toPublicError(error, "Resending OTP failed");
20
+ }
21
+ });
@@ -0,0 +1,3 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<unknown>>;
2
+ export default _default;
3
+ //# sourceMappingURL=reset-password.post.d.ts.map
@@ -0,0 +1,16 @@
1
+ import { defineEventHandler, readBody } from "h3";
2
+ import { callAuthApi, getAuthEndpoint } from "../../utils/external-api.js";
3
+ import { toPublicError } from "../../utils/errors.js";
4
+ export default defineEventHandler(async (event) => {
5
+ try {
6
+ const body = await readBody(event);
7
+ const response = await callAuthApi(getAuthEndpoint("resetPassword"), {
8
+ event,
9
+ method: "POST",
10
+ body
11
+ });
12
+ return response;
13
+ } catch (error) {
14
+ toPublicError(error, "Reset password request failed");
15
+ }
16
+ });
@@ -0,0 +1,6 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ success: boolean;
3
+ message: string;
4
+ }>>;
5
+ export default _default;
6
+ //# sourceMappingURL=%5Bid%5D.delete.d.ts.map
@@ -0,0 +1,20 @@
1
+ import { createError, defineEventHandler, getRouterParam } from "h3";
2
+ import {
3
+ deleteUserBearerAuthSession,
4
+ requireBearerAuthSession
5
+ } from "../../../utils/sessions.js";
6
+ export default defineEventHandler(async (event) => {
7
+ const session = requireBearerAuthSession(event);
8
+ const sessionId = getRouterParam(event, "id");
9
+ if (!sessionId) {
10
+ throw createError({
11
+ statusCode: 400,
12
+ statusMessage: "Session ID is required"
13
+ });
14
+ }
15
+ await deleteUserBearerAuthSession(session.userId, sessionId);
16
+ return {
17
+ success: true,
18
+ message: "Session terminated"
19
+ };
20
+ });
@@ -0,0 +1,5 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ sessions: import("../../../types/auth").PublicSession[];
3
+ }>>;
4
+ export default _default;
5
+ //# sourceMappingURL=sessions.get.d.ts.map
@@ -0,0 +1,11 @@
1
+ import {
2
+ getUserBearerAuthSessions,
3
+ requireBearerAuthSession
4
+ } from "../../utils/sessions.js";
5
+ import { defineEventHandler } from "h3";
6
+ export default defineEventHandler(async (event) => {
7
+ const session = requireBearerAuthSession(event);
8
+ return {
9
+ sessions: await getUserBearerAuthSessions(session.userId)
10
+ };
11
+ });
@@ -0,0 +1,7 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ success: boolean;
3
+ user: import("../../../types/auth").BearerAuthUser | undefined;
4
+ message: string;
5
+ }>>;
6
+ export default _default;
7
+ //# sourceMappingURL=social-login.post.d.ts.map
@@ -0,0 +1,41 @@
1
+ import { createError, defineEventHandler, readBody } from "h3";
2
+ import { callAuthApi, getAuthEndpoint } from "../../utils/external-api.js";
3
+ import { toPublicError } from "../../utils/errors.js";
4
+ import { normalizeAuthResponse } from "../../utils/normalize.js";
5
+ import { createBearerAuthSession } from "../../utils/sessions.js";
6
+ export default defineEventHandler(async (event) => {
7
+ try {
8
+ const body = await readBody(event);
9
+ if (!body.jwt && !body.token && !body.accessToken) {
10
+ throw createError({
11
+ statusCode: 422,
12
+ statusMessage: "Provider token is required"
13
+ });
14
+ }
15
+ const response = await callAuthApi(getAuthEndpoint("socialLogin"), {
16
+ event,
17
+ method: "POST",
18
+ body
19
+ });
20
+ const auth = normalizeAuthResponse(response);
21
+ if (!auth.token || !auth.userId) {
22
+ throw createError({
23
+ statusCode: 401,
24
+ statusMessage: auth.message || "Social login failed"
25
+ });
26
+ }
27
+ await createBearerAuthSession(event, {
28
+ userId: auth.userId,
29
+ token: auth.token,
30
+ refreshToken: auth.refreshToken,
31
+ profile: auth.user
32
+ });
33
+ return {
34
+ success: true,
35
+ user: auth.user,
36
+ message: auth.message || "Login successful"
37
+ };
38
+ } catch (error) {
39
+ toPublicError(error, "Social login failed");
40
+ }
41
+ });
@@ -0,0 +1,3 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<void>>;
2
+ export default _default;
3
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1,29 @@
1
+ import { createError, defineEventHandler, getRequestURL } from "h3";
2
+ import { getBearerAuthSession } from "../utils/sessions.js";
3
+ const SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
4
+ export default defineEventHandler(async (event) => {
5
+ const config = useRuntimeConfig();
6
+ const publicConfig = config.public.bearerAuth;
7
+ const path = getRequestURL(event).pathname;
8
+ const method = event.method.toUpperCase();
9
+ const isProtectedApi = publicConfig.routes.protectedApiPrefixes.some(
10
+ (prefix) => path.startsWith(prefix)
11
+ );
12
+ const isPublicApi = publicConfig.routes.publicApiPrefixes.some(
13
+ (prefix) => path.startsWith(prefix)
14
+ );
15
+ if (isPublicApi || !isProtectedApi && SAFE_METHODS.has(method)) {
16
+ return;
17
+ }
18
+ const session = await getBearerAuthSession(event);
19
+ if (session) {
20
+ event.context.auth = session;
21
+ return;
22
+ }
23
+ if (isProtectedApi) {
24
+ throw createError({
25
+ statusCode: 401,
26
+ statusMessage: "Authentication required"
27
+ });
28
+ }
29
+ });
@@ -0,0 +1,3 @@
1
+ declare const _default: any;
2
+ export default _default;
3
+ //# sourceMappingURL=redis.d.ts.map
@@ -0,0 +1,23 @@
1
+ import {
2
+ ensureBearerAuthRedisConnection,
3
+ getBearerAuthRedisClient
4
+ } from "../utils/sessions.js";
5
+ import { isProductionRuntime } from "../utils/config.js";
6
+ export default defineNitroPlugin(async () => {
7
+ try {
8
+ await ensureBearerAuthRedisConnection();
9
+ } catch (error) {
10
+ console.error("[nuxt-bearer-auth] Redis connection failed:", error);
11
+ }
12
+ if (isProductionRuntime()) {
13
+ const cleanup = async () => {
14
+ try {
15
+ await getBearerAuthRedisClient().quit();
16
+ } catch (error) {
17
+ console.error("[nuxt-bearer-auth] Redis cleanup failed:", error);
18
+ }
19
+ };
20
+ process.once("SIGTERM", cleanup);
21
+ process.once("SIGINT", cleanup);
22
+ }
23
+ });
@@ -0,0 +1,16 @@
1
+ import type { BearerAuthCookieOptions, BearerAuthEndpointOptions, BearerAuthResponsePaths } from "../../../types.js";
2
+ export interface RuntimeBearerAuthConfig {
3
+ apiBaseUrl: string;
4
+ redisUrl: string;
5
+ appEnv: string;
6
+ endpoints: BearerAuthEndpointOptions;
7
+ responsePaths: BearerAuthResponsePaths;
8
+ sessionCookie: BearerAuthCookieOptions;
9
+ verificationRequiredActions: string[];
10
+ twoFactorRequiredActions: string[];
11
+ }
12
+ export declare function getBearerAuthConfig(): RuntimeBearerAuthConfig;
13
+ export declare function requireApiBaseUrl(): string;
14
+ export declare function getSessionCookieName(): string;
15
+ export declare function isProductionRuntime(): boolean;
16
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1,24 @@
1
+ import { createError } from "h3";
2
+ export function getBearerAuthConfig() {
3
+ const config = useRuntimeConfig();
4
+ return config.bearerAuth;
5
+ }
6
+ export function requireApiBaseUrl() {
7
+ const config = getBearerAuthConfig();
8
+ if (!config.apiBaseUrl) {
9
+ throw createError({
10
+ statusCode: 500,
11
+ statusMessage: "bearerAuth.apiBaseUrl is required to proxy authentication requests."
12
+ });
13
+ }
14
+ return config.apiBaseUrl;
15
+ }
16
+ export function getSessionCookieName() {
17
+ const config = getBearerAuthConfig();
18
+ const isDev = config.appEnv === "local" || config.appEnv === "development" || process.env.NODE_ENV !== "production";
19
+ return isDev ? config.sessionCookie.devName || config.sessionCookie.name : config.sessionCookie.name;
20
+ }
21
+ export function isProductionRuntime() {
22
+ const config = getBearerAuthConfig();
23
+ return config.appEnv === "production" || process.env.NODE_ENV === "production";
24
+ }
@@ -0,0 +1,2 @@
1
+ export declare function toPublicError(error: unknown, fallback?: string): never;
2
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,20 @@
1
+ import { FetchError } from "ofetch";
2
+ import { createError } from "h3";
3
+ export function toPublicError(error, fallback = "Request failed") {
4
+ if (error instanceof FetchError) {
5
+ const statusCode = error.response?.status || error.statusCode || 500;
6
+ const data = error.response?._data;
7
+ throw createError({
8
+ statusCode,
9
+ statusMessage: data?.message || error.message || fallback,
10
+ data
11
+ });
12
+ }
13
+ if (typeof error === "object" && error !== null && "statusCode" in error) {
14
+ throw error;
15
+ }
16
+ throw createError({
17
+ statusCode: 500,
18
+ statusMessage: error instanceof Error ? error.message : fallback
19
+ });
20
+ }
@@ -0,0 +1,15 @@
1
+ import type { H3Event } from "h3";
2
+ import type { BearerAuthEndpointOptions } from "../../../types.js";
3
+ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
4
+ export interface ExternalApiOptions {
5
+ event?: H3Event;
6
+ method?: HttpMethod;
7
+ body?: unknown;
8
+ query?: Record<string, unknown>;
9
+ token?: string;
10
+ headers?: Record<string, string>;
11
+ }
12
+ export declare function callAuthApi<T = unknown>(endpoint: string, options?: ExternalApiOptions): Promise<T>;
13
+ export declare function getAuthEndpoint(name: keyof BearerAuthEndpointOptions): string;
14
+ export {};
15
+ //# sourceMappingURL=external-api.d.ts.map
@@ -0,0 +1,31 @@
1
+ import { $fetch } from "ofetch";
2
+ import { getBearerAuthConfig, requireApiBaseUrl } from "./config.js";
3
+ import { getBearerAuthSession } from "./sessions.js";
4
+ export async function callAuthApi(endpoint, options = {}) {
5
+ const baseURL = requireApiBaseUrl();
6
+ const method = options.method || "POST";
7
+ let token = options.token;
8
+ if (!token && options.event) {
9
+ const session = await getBearerAuthSession(options.event);
10
+ token = session?.token;
11
+ }
12
+ const fetchOptions = {
13
+ baseURL,
14
+ method,
15
+ query: options.query,
16
+ headers: {
17
+ Accept: "application/json",
18
+ "Content-Type": "application/json",
19
+ ...token ? { Authorization: `Bearer ${token}` } : {},
20
+ ...options.headers
21
+ },
22
+ retry: 0
23
+ };
24
+ if (options.body !== void 0 && method !== "GET") {
25
+ fetchOptions.body = options.body;
26
+ }
27
+ return await $fetch(endpoint, fetchOptions);
28
+ }
29
+ export function getAuthEndpoint(name) {
30
+ return getBearerAuthConfig().endpoints[name];
31
+ }
@@ -0,0 +1,16 @@
1
+ import type { BearerAuthUser } from "../../types/auth.js";
2
+ export interface NormalizedAuthResponse {
3
+ raw: unknown;
4
+ token?: string;
5
+ refreshToken?: string;
6
+ user?: BearerAuthUser;
7
+ userId?: string;
8
+ message?: string;
9
+ success: boolean;
10
+ code?: string | number;
11
+ nextAction?: string;
12
+ }
13
+ export declare function normalizeAuthResponse(response: unknown): NormalizedAuthResponse;
14
+ export declare function requiresVerification(nextAction?: string): boolean;
15
+ export declare function requiresTwoFactor(nextAction?: string): boolean;
16
+ //# sourceMappingURL=normalize.d.ts.map
@@ -0,0 +1,30 @@
1
+ import { getBearerAuthConfig } from "./config.js";
2
+ import { readFirstPath } from "./paths.js";
3
+ export function normalizeAuthResponse(response) {
4
+ const { responsePaths } = getBearerAuthConfig();
5
+ const user = readFirstPath(response, responsePaths.user);
6
+ const userId = user ? readFirstPath(user, responsePaths.userId) : void 0;
7
+ const successValue = readFirstPath(
8
+ response,
9
+ responsePaths.success
10
+ );
11
+ return {
12
+ raw: response,
13
+ token: readFirstPath(response, responsePaths.token),
14
+ refreshToken: readFirstPath(response, responsePaths.refreshToken),
15
+ user,
16
+ userId: userId === void 0 ? void 0 : String(userId),
17
+ message: readFirstPath(response, responsePaths.message),
18
+ success: successValue === void 0 || successValue === true || successValue === "success" || successValue === "ok",
19
+ code: readFirstPath(response, responsePaths.code),
20
+ nextAction: readFirstPath(response, responsePaths.nextAction)
21
+ };
22
+ }
23
+ export function requiresVerification(nextAction) {
24
+ if (!nextAction) return false;
25
+ return getBearerAuthConfig().verificationRequiredActions.includes(nextAction);
26
+ }
27
+ export function requiresTwoFactor(nextAction) {
28
+ if (!nextAction) return false;
29
+ return getBearerAuthConfig().twoFactorRequiredActions.includes(nextAction);
30
+ }
@@ -0,0 +1,4 @@
1
+ export declare function readPath(source: unknown, path: string): unknown;
2
+ export declare function readFirstPath<T = unknown>(source: unknown, paths?: string[]): T | undefined;
3
+ export declare function interpolatePath(path: string, params: Record<string, string | number | undefined>): string;
4
+ //# sourceMappingURL=paths.d.ts.map
@@ -0,0 +1,23 @@
1
+ export function readPath(source, path) {
2
+ if (!path) return void 0;
3
+ if (path === "$") return source;
4
+ return path.split(".").reduce((current, key) => {
5
+ if (current === null || current === void 0) return void 0;
6
+ if (typeof current !== "object") return void 0;
7
+ return current[key];
8
+ }, source);
9
+ }
10
+ export function readFirstPath(source, paths = []) {
11
+ for (const path of paths) {
12
+ const value = readPath(source, path);
13
+ if (value !== void 0 && value !== null) {
14
+ return value;
15
+ }
16
+ }
17
+ return void 0;
18
+ }
19
+ export function interpolatePath(path, params) {
20
+ return Object.entries(params).reduce((current, [key, value]) => {
21
+ return current.replace(`:${key}`, encodeURIComponent(String(value ?? "")));
22
+ }, path);
23
+ }