@qyh213/easyauth-client 1.0.0-beta.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.
package/dist/next.mjs ADDED
@@ -0,0 +1,124 @@
1
+ import {
2
+ EasyAuthClient,
3
+ EasyAuthError,
4
+ LocalStorageTokenStorage,
5
+ MemoryTokenStorage,
6
+ ScopeError
7
+ } from "./chunk-H65ZLXQJ.mjs";
8
+
9
+ // src/next.tsx
10
+ import { NextResponse } from "next/server";
11
+ import { jsx } from "react/jsx-runtime";
12
+ function createEasyAuthMiddleware(options) {
13
+ return async function middleware(request) {
14
+ const {
15
+ baseUrl,
16
+ apiKey,
17
+ protectedPaths = [],
18
+ scopedPaths = {},
19
+ publicPaths = [],
20
+ loginPath = "/login",
21
+ forbiddenPath = "/forbidden"
22
+ } = options;
23
+ const pathname = request.nextUrl.pathname;
24
+ if (publicPaths.some((p) => pathname.startsWith(p))) {
25
+ return NextResponse.next();
26
+ }
27
+ const token = request.cookies.get("easy_auth_token")?.value || request.headers.get("Authorization")?.replace("Bearer ", "");
28
+ if (!token) {
29
+ if (protectedPaths.some((p) => pathname.startsWith(p))) {
30
+ return NextResponse.redirect(new URL(loginPath, request.url));
31
+ }
32
+ if (Object.keys(scopedPaths).some((p) => pathname.startsWith(p))) {
33
+ return NextResponse.redirect(new URL(loginPath, request.url));
34
+ }
35
+ return NextResponse.next();
36
+ }
37
+ const client = new EasyAuthClient({ baseUrl, apiKey });
38
+ const serviceId = apiKey.split(".")[0];
39
+ try {
40
+ const introspectResult = await client.introspect({
41
+ serviceId,
42
+ token
43
+ });
44
+ if (!introspectResult.valid) {
45
+ if (protectedPaths.some((p) => pathname.startsWith(p)) || Object.keys(scopedPaths).some((p) => pathname.startsWith(p))) {
46
+ return NextResponse.redirect(new URL(loginPath, request.url));
47
+ }
48
+ return NextResponse.next();
49
+ }
50
+ for (const [pathPattern, requiredScopes] of Object.entries(scopedPaths)) {
51
+ if (pathname.startsWith(pathPattern)) {
52
+ const hasScopes = requiredScopes.every(
53
+ (scope) => introspectResult.scopes?.includes(scope)
54
+ );
55
+ if (!hasScopes) {
56
+ return NextResponse.redirect(new URL(forbiddenPath, request.url));
57
+ }
58
+ }
59
+ }
60
+ const requestHeaders = new Headers(request.headers);
61
+ requestHeaders.set("x-user-id", introspectResult.userId || "");
62
+ requestHeaders.set("x-user-email", introspectResult.email || "");
63
+ requestHeaders.set("x-user-scopes", JSON.stringify(introspectResult.scopes || []));
64
+ return NextResponse.next({
65
+ request: {
66
+ headers: requestHeaders
67
+ }
68
+ });
69
+ } catch (error) {
70
+ console.error("Auth middleware error:", error);
71
+ if (protectedPaths.some((p) => pathname.startsWith(p)) || Object.keys(scopedPaths).some((p) => pathname.startsWith(p))) {
72
+ return NextResponse.redirect(new URL(loginPath, request.url));
73
+ }
74
+ return NextResponse.next();
75
+ }
76
+ };
77
+ }
78
+ function withScope(Component, _requiredScopes, _config) {
79
+ return function WithScopeWrapper(props) {
80
+ return /* @__PURE__ */ jsx(Component, { ...props });
81
+ };
82
+ }
83
+ async function validateScopes(request, options) {
84
+ const { baseUrl, apiKey, requiredScopes } = options;
85
+ const authHeader = request.headers.get("Authorization");
86
+ const token = authHeader?.replace("Bearer ", "");
87
+ if (!token) {
88
+ return { valid: false, error: "No token provided", status: 401 };
89
+ }
90
+ const client = new EasyAuthClient({ baseUrl, apiKey });
91
+ const serviceId = apiKey.split(".")[0];
92
+ try {
93
+ const result = await client.introspect({
94
+ serviceId,
95
+ token,
96
+ requiredScopes
97
+ });
98
+ if (!result.valid) {
99
+ return {
100
+ valid: false,
101
+ error: result.error || "Invalid token",
102
+ status: result.error?.includes("scope") ? 403 : 401
103
+ };
104
+ }
105
+ return {
106
+ valid: true,
107
+ userId: result.userId,
108
+ email: result.email,
109
+ scopes: result.scopes
110
+ };
111
+ } catch (error) {
112
+ return { valid: false, error: "Validation failed", status: 500 };
113
+ }
114
+ }
115
+ export {
116
+ EasyAuthClient,
117
+ EasyAuthError,
118
+ LocalStorageTokenStorage,
119
+ MemoryTokenStorage,
120
+ ScopeError,
121
+ createEasyAuthMiddleware,
122
+ validateScopes,
123
+ withScope
124
+ };
@@ -0,0 +1,68 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode } from 'react';
3
+ import { e as EasyAuthConfig, T as TokenStorage, E as EasyAuthClient, U as User, V as ValidationResult } from './client-RPDHpVsj.mjs';
4
+ export { A as ApiKey, a as AuthToken, C as CreateApiKeyRequest, b as CreateApiKeyResponse, c as CreateScopeRequest, d as CreateUserRequest, f as EasyAuthError, I as IntrospectRequest, g as IntrospectResponse, L as LocalStorageTokenStorage, h as LoginCredentials, M as MemoryTokenStorage, O as OnboardRequest, i as OnboardResponse, R as RegisterWebhookRequest, S as Scope, j as ScopeError, k as Service, l as UserListResponse, W as Webhook } from './client-RPDHpVsj.mjs';
5
+
6
+ interface EasyAuthContextValue {
7
+ client: EasyAuthClient;
8
+ isAuthenticated: boolean;
9
+ user: User | null;
10
+ isLoading: boolean;
11
+ login: (email: string, password: string) => Promise<void>;
12
+ logout: () => Promise<void>;
13
+ validate: () => Promise<ValidationResult>;
14
+ }
15
+ interface EasyAuthProviderProps {
16
+ config: EasyAuthConfig;
17
+ tokenStorage?: TokenStorage;
18
+ children: ReactNode;
19
+ /**
20
+ * Validate token on mount and periodically
21
+ */
22
+ validateOnMount?: boolean;
23
+ /**
24
+ * Validation interval in milliseconds (default: 5 minutes)
25
+ */
26
+ validationInterval?: number;
27
+ }
28
+ declare function EasyAuthProvider({ config, tokenStorage, children, validateOnMount, validationInterval, }: EasyAuthProviderProps): react_jsx_runtime.JSX.Element;
29
+ /**
30
+ * Access the Easy Auth context
31
+ */
32
+ declare function useEasyAuth(): EasyAuthContextValue;
33
+ /**
34
+ * Get the Easy Auth client instance
35
+ */
36
+ declare function useEasyAuthClient(): EasyAuthClient;
37
+ /**
38
+ * Check if user is authenticated
39
+ */
40
+ declare function useIsAuthenticated(): boolean;
41
+ /**
42
+ * Get current user
43
+ */
44
+ declare function useUser(): User | null;
45
+ /**
46
+ * Login/logout methods
47
+ */
48
+ declare function useAuthActions(): {
49
+ login: (email: string, password: string) => Promise<void>;
50
+ logout: () => Promise<void>;
51
+ isLoading: boolean;
52
+ };
53
+ interface ProtectedProps {
54
+ children: ReactNode;
55
+ fallback?: ReactNode;
56
+ }
57
+ /**
58
+ * Component that only renders children when authenticated
59
+ */
60
+ declare function Protected({ children, fallback }: ProtectedProps): react_jsx_runtime.JSX.Element | null;
61
+ interface LoginFormProps {
62
+ onSuccess?: () => void;
63
+ onError?: (error: Error) => void;
64
+ className?: string;
65
+ }
66
+ declare function LoginForm({ onSuccess, onError, className }: LoginFormProps): react_jsx_runtime.JSX.Element;
67
+
68
+ export { EasyAuthClient, EasyAuthConfig, EasyAuthProvider, LoginForm, Protected, TokenStorage, User, ValidationResult, useAuthActions, useEasyAuth, useEasyAuthClient, useIsAuthenticated, useUser };
@@ -0,0 +1,68 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode } from 'react';
3
+ import { e as EasyAuthConfig, T as TokenStorage, E as EasyAuthClient, U as User, V as ValidationResult } from './client-RPDHpVsj.js';
4
+ export { A as ApiKey, a as AuthToken, C as CreateApiKeyRequest, b as CreateApiKeyResponse, c as CreateScopeRequest, d as CreateUserRequest, f as EasyAuthError, I as IntrospectRequest, g as IntrospectResponse, L as LocalStorageTokenStorage, h as LoginCredentials, M as MemoryTokenStorage, O as OnboardRequest, i as OnboardResponse, R as RegisterWebhookRequest, S as Scope, j as ScopeError, k as Service, l as UserListResponse, W as Webhook } from './client-RPDHpVsj.js';
5
+
6
+ interface EasyAuthContextValue {
7
+ client: EasyAuthClient;
8
+ isAuthenticated: boolean;
9
+ user: User | null;
10
+ isLoading: boolean;
11
+ login: (email: string, password: string) => Promise<void>;
12
+ logout: () => Promise<void>;
13
+ validate: () => Promise<ValidationResult>;
14
+ }
15
+ interface EasyAuthProviderProps {
16
+ config: EasyAuthConfig;
17
+ tokenStorage?: TokenStorage;
18
+ children: ReactNode;
19
+ /**
20
+ * Validate token on mount and periodically
21
+ */
22
+ validateOnMount?: boolean;
23
+ /**
24
+ * Validation interval in milliseconds (default: 5 minutes)
25
+ */
26
+ validationInterval?: number;
27
+ }
28
+ declare function EasyAuthProvider({ config, tokenStorage, children, validateOnMount, validationInterval, }: EasyAuthProviderProps): react_jsx_runtime.JSX.Element;
29
+ /**
30
+ * Access the Easy Auth context
31
+ */
32
+ declare function useEasyAuth(): EasyAuthContextValue;
33
+ /**
34
+ * Get the Easy Auth client instance
35
+ */
36
+ declare function useEasyAuthClient(): EasyAuthClient;
37
+ /**
38
+ * Check if user is authenticated
39
+ */
40
+ declare function useIsAuthenticated(): boolean;
41
+ /**
42
+ * Get current user
43
+ */
44
+ declare function useUser(): User | null;
45
+ /**
46
+ * Login/logout methods
47
+ */
48
+ declare function useAuthActions(): {
49
+ login: (email: string, password: string) => Promise<void>;
50
+ logout: () => Promise<void>;
51
+ isLoading: boolean;
52
+ };
53
+ interface ProtectedProps {
54
+ children: ReactNode;
55
+ fallback?: ReactNode;
56
+ }
57
+ /**
58
+ * Component that only renders children when authenticated
59
+ */
60
+ declare function Protected({ children, fallback }: ProtectedProps): react_jsx_runtime.JSX.Element | null;
61
+ interface LoginFormProps {
62
+ onSuccess?: () => void;
63
+ onError?: (error: Error) => void;
64
+ className?: string;
65
+ }
66
+ declare function LoginForm({ onSuccess, onError, className }: LoginFormProps): react_jsx_runtime.JSX.Element;
67
+
68
+ export { EasyAuthClient, EasyAuthConfig, EasyAuthProvider, LoginForm, Protected, TokenStorage, User, ValidationResult, useAuthActions, useEasyAuth, useEasyAuthClient, useIsAuthenticated, useUser };