@auth-gate/nextjs 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.
@@ -0,0 +1,224 @@
1
+ import * as next_server_js from 'next/server.js';
2
+ import * as _auth_gate_core from '@auth-gate/core';
3
+ import { AuthGateClient, AuthGateUser, AuthGateConfig } from '@auth-gate/core';
4
+ export { AuthGateConfig, AuthGateUser, CookieOptions, OAuthProvider, SUPPORTED_PROVIDERS, TokenVerifyResult, createAuthGateClient } from '@auth-gate/core';
5
+ import { NextRequest, NextResponse } from 'next/server';
6
+
7
+ /**
8
+ * Server-side session helpers for Next.js App Router.
9
+ *
10
+ * These functions use the Next.js `cookies()` API to read and write
11
+ * the encrypted session cookie. They must be called from Server Components,
12
+ * Server Actions, or Route Handlers — never from Client Components.
13
+ *
14
+ * @module
15
+ */
16
+
17
+ /**
18
+ * Create session helper functions bound to an {@link AuthGateClient}.
19
+ *
20
+ * @param client - A configured AuthGateClient instance.
21
+ * @returns `{ getSession, setSession, clearSession }` — server-side session helpers.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const { getSession, setSession, clearSession } = createSessionHelpers(client);
26
+ *
27
+ * // In a Server Component
28
+ * const user = await getSession();
29
+ * if (!user) redirect("/login");
30
+ * ```
31
+ */
32
+ declare function createSessionHelpers(client: AuthGateClient): {
33
+ getSession: () => Promise<AuthGateUser | null>;
34
+ setSession: (user: AuthGateUser) => Promise<void>;
35
+ clearSession: () => Promise<void>;
36
+ };
37
+
38
+ /**
39
+ * Next.js App Router request handlers for all AuthGate authentication flows.
40
+ *
41
+ * These handlers are designed to be mounted as API routes. The recommended
42
+ * approach is to use {@link createCatchAllHandler} with a catch-all route:
43
+ *
44
+ * ```ts
45
+ * // app/api/auth/[...authgate]/route.ts
46
+ * import { handlers } from "@/lib/auth";
47
+ * export const { GET, POST } = handlers;
48
+ * ```
49
+ *
50
+ * Supported routes:
51
+ * - `GET /:provider/login` — Initiate OAuth flow
52
+ * - `GET /callback` — Handle OAuth/magic-link callback
53
+ * - `GET /me` — Return current session user
54
+ * - `POST /email/signup` — Email + password registration
55
+ * - `POST /email/signin` — Email + password sign-in
56
+ * - `POST /email/forgot-password` — Send password reset email
57
+ * - `POST /email/reset-password` — Confirm password reset
58
+ * - `POST /email/verify-code` — Verify email with OTP code
59
+ * - `POST /magic-link/send` — Send magic link email
60
+ * - `POST /sms/send-code` — Send SMS verification code
61
+ * - `POST /sms/verify-code` — Verify SMS code
62
+ * - `POST /mfa/verify` — Complete MFA challenge
63
+ * - `POST /refresh` — Refresh JWT using refresh token cookie
64
+ * - `POST /logout` — Revoke session and clear cookies
65
+ *
66
+ * @module
67
+ */
68
+
69
+ /**
70
+ * Create individual route handler functions for each auth endpoint.
71
+ *
72
+ * For most apps, prefer {@link createCatchAllHandler} which maps these
73
+ * handlers to URL paths automatically.
74
+ *
75
+ * @param client - A configured AuthGateClient instance.
76
+ * @param appUrl - Your app's public URL (e.g. `"http://localhost:3000"`).
77
+ */
78
+ declare function createHandlers(client: AuthGateClient, appUrl: string): {
79
+ providerLogin: (_request: Request, { params }: {
80
+ params: Promise<{
81
+ provider: string;
82
+ }>;
83
+ }) => Promise<Response>;
84
+ callback: (request: NextRequest) => Promise<Response>;
85
+ emailSignup: (request: Request) => Promise<Response>;
86
+ emailSignin: (request: Request) => Promise<Response>;
87
+ emailForgotPassword: (request: Request) => Promise<Response>;
88
+ emailResetPassword: (request: Request) => Promise<Response>;
89
+ emailVerifyCode: (request: Request) => Promise<Response>;
90
+ magicLinkSend: (request: Request) => Promise<Response>;
91
+ smsSendCode: (request: Request) => Promise<Response>;
92
+ smsVerifyCode: (request: Request) => Promise<Response>;
93
+ mfaVerify: (request: Request) => Promise<Response>;
94
+ mfaTotpSetup: () => Promise<Response>;
95
+ refresh: () => Promise<Response>;
96
+ logout: () => Promise<Response>;
97
+ me: () => Promise<Response>;
98
+ };
99
+ /**
100
+ * Create a catch-all `{ GET, POST }` handler for the `[...authgate]` route.
101
+ *
102
+ * Mount this at `app/api/auth/[...authgate]/route.ts` to handle all
103
+ * AuthGate authentication endpoints with a single file.
104
+ *
105
+ * @param client - A configured AuthGateClient instance.
106
+ * @param appUrl - Your app's public URL (e.g. `"http://localhost:3000"`).
107
+ * @returns `{ GET, POST }` — Next.js route handlers.
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * // app/api/auth/[...authgate]/route.ts
112
+ * import { client } from "@/lib/auth";
113
+ * import { createCatchAllHandler } from "@auth-gate/nextjs";
114
+ *
115
+ * export const { GET, POST } = createCatchAllHandler(client, process.env.NEXT_PUBLIC_APP_URL!);
116
+ * ```
117
+ */
118
+ declare function createCatchAllHandler(client: AuthGateClient, appUrl: string): {
119
+ GET: (request: NextRequest, context: {
120
+ params: Promise<{
121
+ authgate: string[];
122
+ }>;
123
+ }) => Promise<Response>;
124
+ POST: (request: NextRequest, context: {
125
+ params: Promise<{
126
+ authgate: string[];
127
+ }>;
128
+ }) => Promise<Response>;
129
+ };
130
+
131
+ /**
132
+ * Composable authentication middleware for Next.js.
133
+ *
134
+ * Protects routes by checking for a valid encrypted session cookie.
135
+ * Periodically revalidates the session against the server using the
136
+ * refresh token, so revoked sessions are detected within minutes.
137
+ *
138
+ * Designed to compose with other middleware — returns `null` when no
139
+ * action is needed, or a redirect `NextResponse` when auth is required.
140
+ *
141
+ * @module
142
+ */
143
+
144
+ /**
145
+ * Options for {@link createAuthGateMiddleware}.
146
+ */
147
+ interface AuthGateMiddlewareOptions {
148
+ /**
149
+ * Path to redirect unauthenticated users to.
150
+ * @defaultValue `"/login"`
151
+ */
152
+ loginPath?: string;
153
+ /**
154
+ * URL patterns to protect. Uses Next.js-style matcher syntax
155
+ * (e.g. `"/dashboard/:path*"`).
156
+ * @defaultValue `["/dashboard/:path*"]`
157
+ */
158
+ matcher?: string[];
159
+ }
160
+ /**
161
+ * Creates a composable auth middleware function.
162
+ *
163
+ * Returns `null` when the request path doesn't match or the user is
164
+ * authenticated — letting your own middleware chain continue.
165
+ * Returns a redirect `NextResponse` when a matched path has no valid session.
166
+ *
167
+ * When a refresh token cookie is present, the middleware periodically
168
+ * revalidates the session against the server (every 5 minutes). If the
169
+ * session has been revoked, the user is redirected to the login page.
170
+ *
171
+ * @example
172
+ * ```ts
173
+ * // middleware.ts — compose with other middleware
174
+ * import { authMiddleware } from "@/lib/auth";
175
+ *
176
+ * export default async function middleware(request: NextRequest) {
177
+ * const authResponse = await authMiddleware(request);
178
+ * if (authResponse) return authResponse;
179
+ *
180
+ * // ...other middleware logic
181
+ * return NextResponse.next();
182
+ * }
183
+ *
184
+ * export const config = {
185
+ * matcher: ["/dashboard/:path*", "/settings/:path*"],
186
+ * };
187
+ * ```
188
+ */
189
+ declare function createAuthGateMiddleware(clientOrGetter: AuthGateClient | (() => AuthGateClient), options?: AuthGateMiddlewareOptions): (request: NextRequest) => Promise<NextResponse | null>;
190
+
191
+ /**
192
+ * Initialize AuthGate for a Next.js App Router application.
193
+ *
194
+ * Returns three objects:
195
+ * - `client` — the underlying {@link AuthGateClient} for direct API access.
196
+ * - `handlers` — `{ GET, POST }` route handlers to mount at `app/api/auth/[...authgate]/route.ts`.
197
+ * - `session` — `{ getSession, setSession, clearSession }` helpers for reading/writing the session cookie.
198
+ *
199
+ * @param config - AuthGate config plus `appUrl` (your app's public URL, e.g. `"http://localhost:3000"`).
200
+ */
201
+ declare function createAuthGate(config: AuthGateConfig & {
202
+ appUrl: string;
203
+ }): {
204
+ client: _auth_gate_core.AuthGateClient;
205
+ handlers: {
206
+ GET: (request: next_server_js.NextRequest, context: {
207
+ params: Promise<{
208
+ authgate: string[];
209
+ }>;
210
+ }) => Promise<Response>;
211
+ POST: (request: next_server_js.NextRequest, context: {
212
+ params: Promise<{
213
+ authgate: string[];
214
+ }>;
215
+ }) => Promise<Response>;
216
+ };
217
+ session: {
218
+ getSession: () => Promise<_auth_gate_core.AuthGateUser | null>;
219
+ setSession: (user: _auth_gate_core.AuthGateUser) => Promise<void>;
220
+ clearSession: () => Promise<void>;
221
+ };
222
+ };
223
+
224
+ export { type AuthGateMiddlewareOptions, createAuthGate, createAuthGateMiddleware, createCatchAllHandler, createHandlers, createSessionHelpers };
@@ -0,0 +1,224 @@
1
+ import * as next_server_js from 'next/server.js';
2
+ import * as _auth_gate_core from '@auth-gate/core';
3
+ import { AuthGateClient, AuthGateUser, AuthGateConfig } from '@auth-gate/core';
4
+ export { AuthGateConfig, AuthGateUser, CookieOptions, OAuthProvider, SUPPORTED_PROVIDERS, TokenVerifyResult, createAuthGateClient } from '@auth-gate/core';
5
+ import { NextRequest, NextResponse } from 'next/server';
6
+
7
+ /**
8
+ * Server-side session helpers for Next.js App Router.
9
+ *
10
+ * These functions use the Next.js `cookies()` API to read and write
11
+ * the encrypted session cookie. They must be called from Server Components,
12
+ * Server Actions, or Route Handlers — never from Client Components.
13
+ *
14
+ * @module
15
+ */
16
+
17
+ /**
18
+ * Create session helper functions bound to an {@link AuthGateClient}.
19
+ *
20
+ * @param client - A configured AuthGateClient instance.
21
+ * @returns `{ getSession, setSession, clearSession }` — server-side session helpers.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const { getSession, setSession, clearSession } = createSessionHelpers(client);
26
+ *
27
+ * // In a Server Component
28
+ * const user = await getSession();
29
+ * if (!user) redirect("/login");
30
+ * ```
31
+ */
32
+ declare function createSessionHelpers(client: AuthGateClient): {
33
+ getSession: () => Promise<AuthGateUser | null>;
34
+ setSession: (user: AuthGateUser) => Promise<void>;
35
+ clearSession: () => Promise<void>;
36
+ };
37
+
38
+ /**
39
+ * Next.js App Router request handlers for all AuthGate authentication flows.
40
+ *
41
+ * These handlers are designed to be mounted as API routes. The recommended
42
+ * approach is to use {@link createCatchAllHandler} with a catch-all route:
43
+ *
44
+ * ```ts
45
+ * // app/api/auth/[...authgate]/route.ts
46
+ * import { handlers } from "@/lib/auth";
47
+ * export const { GET, POST } = handlers;
48
+ * ```
49
+ *
50
+ * Supported routes:
51
+ * - `GET /:provider/login` — Initiate OAuth flow
52
+ * - `GET /callback` — Handle OAuth/magic-link callback
53
+ * - `GET /me` — Return current session user
54
+ * - `POST /email/signup` — Email + password registration
55
+ * - `POST /email/signin` — Email + password sign-in
56
+ * - `POST /email/forgot-password` — Send password reset email
57
+ * - `POST /email/reset-password` — Confirm password reset
58
+ * - `POST /email/verify-code` — Verify email with OTP code
59
+ * - `POST /magic-link/send` — Send magic link email
60
+ * - `POST /sms/send-code` — Send SMS verification code
61
+ * - `POST /sms/verify-code` — Verify SMS code
62
+ * - `POST /mfa/verify` — Complete MFA challenge
63
+ * - `POST /refresh` — Refresh JWT using refresh token cookie
64
+ * - `POST /logout` — Revoke session and clear cookies
65
+ *
66
+ * @module
67
+ */
68
+
69
+ /**
70
+ * Create individual route handler functions for each auth endpoint.
71
+ *
72
+ * For most apps, prefer {@link createCatchAllHandler} which maps these
73
+ * handlers to URL paths automatically.
74
+ *
75
+ * @param client - A configured AuthGateClient instance.
76
+ * @param appUrl - Your app's public URL (e.g. `"http://localhost:3000"`).
77
+ */
78
+ declare function createHandlers(client: AuthGateClient, appUrl: string): {
79
+ providerLogin: (_request: Request, { params }: {
80
+ params: Promise<{
81
+ provider: string;
82
+ }>;
83
+ }) => Promise<Response>;
84
+ callback: (request: NextRequest) => Promise<Response>;
85
+ emailSignup: (request: Request) => Promise<Response>;
86
+ emailSignin: (request: Request) => Promise<Response>;
87
+ emailForgotPassword: (request: Request) => Promise<Response>;
88
+ emailResetPassword: (request: Request) => Promise<Response>;
89
+ emailVerifyCode: (request: Request) => Promise<Response>;
90
+ magicLinkSend: (request: Request) => Promise<Response>;
91
+ smsSendCode: (request: Request) => Promise<Response>;
92
+ smsVerifyCode: (request: Request) => Promise<Response>;
93
+ mfaVerify: (request: Request) => Promise<Response>;
94
+ mfaTotpSetup: () => Promise<Response>;
95
+ refresh: () => Promise<Response>;
96
+ logout: () => Promise<Response>;
97
+ me: () => Promise<Response>;
98
+ };
99
+ /**
100
+ * Create a catch-all `{ GET, POST }` handler for the `[...authgate]` route.
101
+ *
102
+ * Mount this at `app/api/auth/[...authgate]/route.ts` to handle all
103
+ * AuthGate authentication endpoints with a single file.
104
+ *
105
+ * @param client - A configured AuthGateClient instance.
106
+ * @param appUrl - Your app's public URL (e.g. `"http://localhost:3000"`).
107
+ * @returns `{ GET, POST }` — Next.js route handlers.
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * // app/api/auth/[...authgate]/route.ts
112
+ * import { client } from "@/lib/auth";
113
+ * import { createCatchAllHandler } from "@auth-gate/nextjs";
114
+ *
115
+ * export const { GET, POST } = createCatchAllHandler(client, process.env.NEXT_PUBLIC_APP_URL!);
116
+ * ```
117
+ */
118
+ declare function createCatchAllHandler(client: AuthGateClient, appUrl: string): {
119
+ GET: (request: NextRequest, context: {
120
+ params: Promise<{
121
+ authgate: string[];
122
+ }>;
123
+ }) => Promise<Response>;
124
+ POST: (request: NextRequest, context: {
125
+ params: Promise<{
126
+ authgate: string[];
127
+ }>;
128
+ }) => Promise<Response>;
129
+ };
130
+
131
+ /**
132
+ * Composable authentication middleware for Next.js.
133
+ *
134
+ * Protects routes by checking for a valid encrypted session cookie.
135
+ * Periodically revalidates the session against the server using the
136
+ * refresh token, so revoked sessions are detected within minutes.
137
+ *
138
+ * Designed to compose with other middleware — returns `null` when no
139
+ * action is needed, or a redirect `NextResponse` when auth is required.
140
+ *
141
+ * @module
142
+ */
143
+
144
+ /**
145
+ * Options for {@link createAuthGateMiddleware}.
146
+ */
147
+ interface AuthGateMiddlewareOptions {
148
+ /**
149
+ * Path to redirect unauthenticated users to.
150
+ * @defaultValue `"/login"`
151
+ */
152
+ loginPath?: string;
153
+ /**
154
+ * URL patterns to protect. Uses Next.js-style matcher syntax
155
+ * (e.g. `"/dashboard/:path*"`).
156
+ * @defaultValue `["/dashboard/:path*"]`
157
+ */
158
+ matcher?: string[];
159
+ }
160
+ /**
161
+ * Creates a composable auth middleware function.
162
+ *
163
+ * Returns `null` when the request path doesn't match or the user is
164
+ * authenticated — letting your own middleware chain continue.
165
+ * Returns a redirect `NextResponse` when a matched path has no valid session.
166
+ *
167
+ * When a refresh token cookie is present, the middleware periodically
168
+ * revalidates the session against the server (every 5 minutes). If the
169
+ * session has been revoked, the user is redirected to the login page.
170
+ *
171
+ * @example
172
+ * ```ts
173
+ * // middleware.ts — compose with other middleware
174
+ * import { authMiddleware } from "@/lib/auth";
175
+ *
176
+ * export default async function middleware(request: NextRequest) {
177
+ * const authResponse = await authMiddleware(request);
178
+ * if (authResponse) return authResponse;
179
+ *
180
+ * // ...other middleware logic
181
+ * return NextResponse.next();
182
+ * }
183
+ *
184
+ * export const config = {
185
+ * matcher: ["/dashboard/:path*", "/settings/:path*"],
186
+ * };
187
+ * ```
188
+ */
189
+ declare function createAuthGateMiddleware(clientOrGetter: AuthGateClient | (() => AuthGateClient), options?: AuthGateMiddlewareOptions): (request: NextRequest) => Promise<NextResponse | null>;
190
+
191
+ /**
192
+ * Initialize AuthGate for a Next.js App Router application.
193
+ *
194
+ * Returns three objects:
195
+ * - `client` — the underlying {@link AuthGateClient} for direct API access.
196
+ * - `handlers` — `{ GET, POST }` route handlers to mount at `app/api/auth/[...authgate]/route.ts`.
197
+ * - `session` — `{ getSession, setSession, clearSession }` helpers for reading/writing the session cookie.
198
+ *
199
+ * @param config - AuthGate config plus `appUrl` (your app's public URL, e.g. `"http://localhost:3000"`).
200
+ */
201
+ declare function createAuthGate(config: AuthGateConfig & {
202
+ appUrl: string;
203
+ }): {
204
+ client: _auth_gate_core.AuthGateClient;
205
+ handlers: {
206
+ GET: (request: next_server_js.NextRequest, context: {
207
+ params: Promise<{
208
+ authgate: string[];
209
+ }>;
210
+ }) => Promise<Response>;
211
+ POST: (request: next_server_js.NextRequest, context: {
212
+ params: Promise<{
213
+ authgate: string[];
214
+ }>;
215
+ }) => Promise<Response>;
216
+ };
217
+ session: {
218
+ getSession: () => Promise<_auth_gate_core.AuthGateUser | null>;
219
+ setSession: (user: _auth_gate_core.AuthGateUser) => Promise<void>;
220
+ clearSession: () => Promise<void>;
221
+ };
222
+ };
223
+
224
+ export { type AuthGateMiddlewareOptions, createAuthGate, createAuthGateMiddleware, createCatchAllHandler, createHandlers, createSessionHelpers };