@civic/auth 0.0.1-beta.16 → 0.0.1-beta.17
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/{chunk-FBU2CKWK.mjs → chunk-5XL2ST72.mjs} +45 -14
- package/dist/chunk-5XL2ST72.mjs.map +1 -0
- package/dist/chunk-CRTRMMJ7.js.map +1 -1
- package/dist/{chunk-RKQDQJOM.mjs → chunk-G3P5TIO2.mjs} +1 -1
- package/dist/chunk-G3P5TIO2.mjs.map +1 -0
- package/dist/{chunk-CHY6AHA7.js → chunk-RF23Q4V6.js} +1 -1
- package/dist/chunk-RF23Q4V6.js.map +1 -0
- package/dist/{chunk-N4SAZYOX.js → chunk-SEKF2WZX.js} +50 -19
- package/dist/chunk-SEKF2WZX.js.map +1 -0
- package/dist/{index-Bq3T3FPG.d.ts → index-DTimUlkB.d.ts} +2 -1
- package/dist/{index-GtnyFGD2.d.mts → index-DvjkKpkk.d.mts} +2 -1
- package/dist/index.d.mts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js.map +1 -1
- package/dist/nextjs.d.mts +3 -9
- package/dist/nextjs.d.ts +3 -9
- package/dist/nextjs.js +24 -24
- package/dist/nextjs.js.map +1 -1
- package/dist/nextjs.mjs +3 -3
- package/dist/nextjs.mjs.map +1 -1
- package/dist/react.d.mts +16 -10
- package/dist/react.d.ts +16 -10
- package/dist/react.js +152 -89
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +167 -104
- package/dist/react.mjs.map +1 -1
- package/dist/server.d.mts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +2 -2
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +1 -1
- package/dist/{types-Bfi0hVMZ.d.mts → types-HdCjGldB.d.mts} +2 -2
- package/dist/{types-Bfi0hVMZ.d.ts → types-HdCjGldB.d.ts} +2 -2
- package/dist/types-b4c1koXj.d.mts +19 -0
- package/dist/types-b4c1koXj.d.ts +19 -0
- package/package.json +1 -1
- package/dist/chunk-CHY6AHA7.js.map +0 -1
- package/dist/chunk-FBU2CKWK.mjs.map +0 -1
- package/dist/chunk-N4SAZYOX.js.map +0 -1
- package/dist/chunk-RKQDQJOM.mjs.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export { A as AuthStorage, C as Config, D as DisplayMode, E as Endpoints, F as ForwardedTokens, T as Tokens, U as User } from './types-
|
|
2
|
-
export { U as
|
|
1
|
+
export { A as AuthStorage, C as Config, D as DisplayMode, E as Endpoints, F as ForwardedTokens, T as Tokens, U as User } from './types-HdCjGldB.js';
|
|
2
|
+
export { C as CookieConfig, O as OAuthTokens, T as TokensCookieConfig, U as UserStorage } from './types-b4c1koXj.js';
|
|
3
|
+
export { U as UserContextType } from './index-DTimUlkB.js';
|
|
3
4
|
import 'oslo/oauth2';
|
|
4
5
|
import 'oslo/jwt';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/
|
|
1
|
+
{"version":3,"sources":["/Users/kevincolgan/code/civic-auth/packages/civic-auth-client/dist/index.js"],"names":[],"mappings":"AAAA,4CAA4B","file":"/Users/kevincolgan/code/civic-auth/packages/civic-auth-client/dist/index.js"}
|
package/dist/nextjs.d.mts
CHANGED
|
@@ -2,17 +2,11 @@ import * as next_dist_shared_lib_image_config from 'next/dist/shared/lib/image-c
|
|
|
2
2
|
import * as next_dist_lib_load_custom_routes from 'next/dist/lib/load-custom-routes';
|
|
3
3
|
import * as next_dist_server_config_shared from 'next/dist/server/config-shared';
|
|
4
4
|
import { NextConfig } from 'next';
|
|
5
|
-
import {
|
|
5
|
+
import { T as TokensCookieConfig, C as CookieConfig } from './types-b4c1koXj.mjs';
|
|
6
|
+
import { U as User } from './types-HdCjGldB.mjs';
|
|
6
7
|
import { NextRequest, NextResponse } from 'next/server.js';
|
|
7
8
|
import 'oslo/oauth2';
|
|
8
9
|
|
|
9
|
-
interface CookieConfig {
|
|
10
|
-
secure?: boolean;
|
|
11
|
-
sameSite?: "strict" | "lax" | "none";
|
|
12
|
-
domain?: string;
|
|
13
|
-
path?: string;
|
|
14
|
-
maxAge?: number;
|
|
15
|
-
}
|
|
16
10
|
type AuthConfigWithDefaults = {
|
|
17
11
|
clientId: string;
|
|
18
12
|
oauthServer: string;
|
|
@@ -24,7 +18,7 @@ type AuthConfigWithDefaults = {
|
|
|
24
18
|
include: string[];
|
|
25
19
|
exclude: string[];
|
|
26
20
|
cookies: {
|
|
27
|
-
tokens:
|
|
21
|
+
tokens: TokensCookieConfig;
|
|
28
22
|
user: CookieConfig;
|
|
29
23
|
};
|
|
30
24
|
};
|
package/dist/nextjs.d.ts
CHANGED
|
@@ -2,17 +2,11 @@ import * as next_dist_shared_lib_image_config from 'next/dist/shared/lib/image-c
|
|
|
2
2
|
import * as next_dist_lib_load_custom_routes from 'next/dist/lib/load-custom-routes';
|
|
3
3
|
import * as next_dist_server_config_shared from 'next/dist/server/config-shared';
|
|
4
4
|
import { NextConfig } from 'next';
|
|
5
|
-
import {
|
|
5
|
+
import { T as TokensCookieConfig, C as CookieConfig } from './types-b4c1koXj.js';
|
|
6
|
+
import { U as User } from './types-HdCjGldB.js';
|
|
6
7
|
import { NextRequest, NextResponse } from 'next/server.js';
|
|
7
8
|
import 'oslo/oauth2';
|
|
8
9
|
|
|
9
|
-
interface CookieConfig {
|
|
10
|
-
secure?: boolean;
|
|
11
|
-
sameSite?: "strict" | "lax" | "none";
|
|
12
|
-
domain?: string;
|
|
13
|
-
path?: string;
|
|
14
|
-
maxAge?: number;
|
|
15
|
-
}
|
|
16
10
|
type AuthConfigWithDefaults = {
|
|
17
11
|
clientId: string;
|
|
18
12
|
oauthServer: string;
|
|
@@ -24,7 +18,7 @@ type AuthConfigWithDefaults = {
|
|
|
24
18
|
include: string[];
|
|
25
19
|
exclude: string[];
|
|
26
20
|
cookies: {
|
|
27
|
-
tokens:
|
|
21
|
+
tokens: TokensCookieConfig;
|
|
28
22
|
user: CookieConfig;
|
|
29
23
|
};
|
|
30
24
|
};
|
package/dist/nextjs.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
var
|
|
10
|
+
var _chunkSEKF2WZXjs = require('./chunk-SEKF2WZX.js');
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
|
|
@@ -15,7 +15,7 @@ var _chunkN4SAZYOXjs = require('./chunk-N4SAZYOX.js');
|
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
|
|
18
|
-
var
|
|
18
|
+
var _chunkRF23Q4V6js = require('./chunk-RF23Q4V6.js');
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
|
|
@@ -25,9 +25,9 @@ var _chunkCRTRMMJ7js = require('./chunk-CRTRMMJ7.js');
|
|
|
25
25
|
// src/nextjs/GetUser.ts
|
|
26
26
|
var getUser2 = () => {
|
|
27
27
|
var _a;
|
|
28
|
-
const clientStorage = new (0,
|
|
29
|
-
const userSession = new (0,
|
|
30
|
-
const tokens =
|
|
28
|
+
const clientStorage = new (0, _chunkSEKF2WZXjs.NextjsClientStorage)();
|
|
29
|
+
const userSession = new (0, _chunkRF23Q4V6js.GenericUserSession)(clientStorage);
|
|
30
|
+
const tokens = _chunkRF23Q4V6js.retrieveTokens.call(void 0, clientStorage);
|
|
31
31
|
const user = userSession.get();
|
|
32
32
|
if (!user || !tokens) return null;
|
|
33
33
|
return _chunkCRTRMMJ7js.__spreadProps.call(void 0, _chunkCRTRMMJ7js.__spreadValues.call(void 0, {}, user), {
|
|
@@ -54,7 +54,7 @@ var matchesGlobs = (pathname, patterns) => patterns.some((pattern) => {
|
|
|
54
54
|
return matchGlob(pathname, pattern);
|
|
55
55
|
});
|
|
56
56
|
var applyAuth = (authConfig, request) => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
|
|
57
|
-
const authConfigWithDefaults =
|
|
57
|
+
const authConfigWithDefaults = _chunkSEKF2WZXjs.resolveAuthConfig.call(void 0, authConfig);
|
|
58
58
|
const isAuthenticated = !!request.cookies.get("id_token");
|
|
59
59
|
if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl) {
|
|
60
60
|
console.log("\u2192 Skipping auth check - this is the login URL");
|
|
@@ -76,7 +76,7 @@ var applyAuth = (authConfig, request) => _chunkCRTRMMJ7js.__async.call(void 0, v
|
|
|
76
76
|
console.log("\u2192 Auth check passed");
|
|
77
77
|
return void 0;
|
|
78
78
|
});
|
|
79
|
-
var authMiddleware = (authConfig =
|
|
79
|
+
var authMiddleware = (authConfig = _chunkSEKF2WZXjs.defaultAuthConfig) => (request) => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
|
|
80
80
|
const response = yield applyAuth(authConfig, request);
|
|
81
81
|
if (response) return response;
|
|
82
82
|
return _serverjs.NextResponse.next();
|
|
@@ -101,7 +101,7 @@ function auth(authConfig = {}) {
|
|
|
101
101
|
// src/nextjs/routeHandler.ts
|
|
102
102
|
|
|
103
103
|
var _cachejs = require('next/cache.js');
|
|
104
|
-
var logger =
|
|
104
|
+
var logger = _chunkSEKF2WZXjs.loggers.nextjs.handlers.auth;
|
|
105
105
|
var AuthError = class extends Error {
|
|
106
106
|
constructor(message, status = 401) {
|
|
107
107
|
super(message);
|
|
@@ -111,8 +111,8 @@ var AuthError = class extends Error {
|
|
|
111
111
|
};
|
|
112
112
|
function handleChallenge() {
|
|
113
113
|
return _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
|
|
114
|
-
const cookieStorage = new (0,
|
|
115
|
-
const pkceProducer = new (0,
|
|
114
|
+
const cookieStorage = new (0, _chunkSEKF2WZXjs.NextjsCookieStorage)();
|
|
115
|
+
const pkceProducer = new (0, _chunkRF23Q4V6js.GenericPublicClientPKCEProducer)(cookieStorage);
|
|
116
116
|
const challenge = yield pkceProducer.getCodeChallenge();
|
|
117
117
|
return _serverjs.NextResponse.json({ status: "success", challenge });
|
|
118
118
|
});
|
|
@@ -121,34 +121,34 @@ function handleCallback(request, config) {
|
|
|
121
121
|
return _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
|
|
122
122
|
if (!request.cookies.get("code_verifier")) {
|
|
123
123
|
const response2 = new (0, _serverjs.NextResponse)(
|
|
124
|
-
`<html><body><span style="display:none">${
|
|
124
|
+
`<html><body><span style="display:none">${_chunkRF23Q4V6js.TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`
|
|
125
125
|
);
|
|
126
126
|
response2.headers.set("Content-Type", "text/html; charset=utf-8");
|
|
127
127
|
console.log(
|
|
128
|
-
`handleCallback no code_verifier found, returning ${
|
|
128
|
+
`handleCallback no code_verifier found, returning ${_chunkRF23Q4V6js.TOKEN_EXCHANGE_TRIGGER_TEXT}`
|
|
129
129
|
);
|
|
130
130
|
return response2;
|
|
131
131
|
}
|
|
132
132
|
const code = request.nextUrl.searchParams.get("code");
|
|
133
133
|
const state = request.nextUrl.searchParams.get("state");
|
|
134
134
|
if (!code || !state) throw new AuthError("Bad parameters", 400);
|
|
135
|
-
const
|
|
136
|
-
const
|
|
137
|
-
const callbackUrl =
|
|
135
|
+
const resolvedConfigs = _chunkSEKF2WZXjs.resolveAuthConfig.call(void 0, config);
|
|
136
|
+
const cookieStorage = new (0, _chunkSEKF2WZXjs.NextjsCookieStorage)(resolvedConfigs.cookies.tokens);
|
|
137
|
+
const callbackUrl = _chunkSEKF2WZXjs.resolveCallbackUrl.call(void 0, resolvedConfigs, request.url);
|
|
138
138
|
try {
|
|
139
|
-
yield
|
|
139
|
+
yield _chunkRF23Q4V6js.resolveOAuthAccessCode.call(void 0, code, state, cookieStorage, _chunkCRTRMMJ7js.__spreadProps.call(void 0, _chunkCRTRMMJ7js.__spreadValues.call(void 0, {}, resolvedConfigs), {
|
|
140
140
|
redirectUrl: callbackUrl
|
|
141
141
|
}));
|
|
142
142
|
} catch (error) {
|
|
143
143
|
logger.error("Token exchange failed:", error);
|
|
144
144
|
throw new AuthError("Failed to authenticate user", 401);
|
|
145
145
|
}
|
|
146
|
-
const user = yield
|
|
146
|
+
const user = yield _chunkRF23Q4V6js.getUser.call(void 0, cookieStorage);
|
|
147
147
|
if (!user) {
|
|
148
148
|
throw new AuthError("Failed to get user info", 401);
|
|
149
149
|
}
|
|
150
|
-
const clientStorage = new (0,
|
|
151
|
-
const userSession = new (0,
|
|
150
|
+
const clientStorage = new (0, _chunkSEKF2WZXjs.NextjsClientStorage)();
|
|
151
|
+
const userSession = new (0, _chunkRF23Q4V6js.GenericUserSession)(clientStorage);
|
|
152
152
|
userSession.set(user);
|
|
153
153
|
const response = new (0, _serverjs.NextResponse)(`<html></html>`);
|
|
154
154
|
response.headers.set("Content-Type", "text/html; charset=utf-8");
|
|
@@ -164,7 +164,7 @@ var getAbsoluteRedirectPath = (redirectPath, currentBasePath) => {
|
|
|
164
164
|
function handleLogout(request, config) {
|
|
165
165
|
return _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
|
|
166
166
|
var _a;
|
|
167
|
-
const resolvedConfigs =
|
|
167
|
+
const resolvedConfigs = _chunkSEKF2WZXjs.resolveAuthConfig.call(void 0, config);
|
|
168
168
|
const defaultRedirectPath = (_a = resolvedConfigs.loginUrl) != null ? _a : "/";
|
|
169
169
|
const redirectTarget = new URL(request.url).searchParams.get("redirect") || defaultRedirectPath;
|
|
170
170
|
const isAbsoluteRedirect = /^(https?:\/\/|www\.).+/i.test(redirectTarget);
|
|
@@ -173,7 +173,7 @@ function handleLogout(request, config) {
|
|
|
173
173
|
new URL(request.url).origin
|
|
174
174
|
);
|
|
175
175
|
const response = _serverjs.NextResponse.redirect(finalRedirectUrl);
|
|
176
|
-
|
|
176
|
+
_chunkSEKF2WZXjs.clearAuthCookies.call(void 0, );
|
|
177
177
|
try {
|
|
178
178
|
_cachejs.revalidatePath.call(void 0, isAbsoluteRedirect ? finalRedirectUrl : redirectTarget);
|
|
179
179
|
} catch (error) {
|
|
@@ -183,7 +183,7 @@ function handleLogout(request, config) {
|
|
|
183
183
|
});
|
|
184
184
|
}
|
|
185
185
|
var handler = (authConfig = {}) => (request) => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
|
|
186
|
-
const config =
|
|
186
|
+
const config = _chunkSEKF2WZXjs.resolveAuthConfig.call(void 0, authConfig);
|
|
187
187
|
try {
|
|
188
188
|
const pathname = request.nextUrl.pathname;
|
|
189
189
|
const pathSegments = pathname.split("/");
|
|
@@ -203,7 +203,7 @@ var handler = (authConfig = {}) => (request) => _chunkCRTRMMJ7js.__async.call(vo
|
|
|
203
203
|
const status = error instanceof AuthError ? error.status : 500;
|
|
204
204
|
const message = error instanceof Error ? error.message : "Authentication failed";
|
|
205
205
|
const response = _serverjs.NextResponse.json({ error: message }, { status });
|
|
206
|
-
|
|
206
|
+
_chunkSEKF2WZXjs.clearAuthCookies.call(void 0, );
|
|
207
207
|
return response;
|
|
208
208
|
}
|
|
209
209
|
});
|
|
@@ -214,5 +214,5 @@ var handler = (authConfig = {}) => (request) => _chunkCRTRMMJ7js.__async.call(vo
|
|
|
214
214
|
|
|
215
215
|
|
|
216
216
|
|
|
217
|
-
exports.auth = auth; exports.authMiddleware = authMiddleware; exports.createCivicAuthPlugin =
|
|
217
|
+
exports.auth = auth; exports.authMiddleware = authMiddleware; exports.createCivicAuthPlugin = _chunkSEKF2WZXjs.createCivicAuthPlugin; exports.getUser = getUser2; exports.handler = handler; exports.withAuth = withAuth;
|
|
218
218
|
//# sourceMappingURL=nextjs.js.map
|
package/dist/nextjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/pedroapfilho/dev/civic-auth/packages/civic-auth-client/dist/nextjs.js","../src/nextjs/GetUser.ts","../src/nextjs/middleware.ts","../src/nextjs/routeHandler.ts"],"names":["getUser","NextResponse","response"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,sDAA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A;AACA,IAAA;AACA,IAAA;AAEA,IAAA;AAEA,IAAA;AAEA,IAAA;AACA,IAAA;AACE,MAAA;AAAyD,QAAA;AAE1C,MAAA;AACd,IAAA;AAED,MAAA;AACA,MAAA;AAAsD,IAAA;AAGxD,IAAA;AACA,IAAA;AACE,MAAA;AAAkD,IAAA;AAGpD,IAAA;AACA,IAAA;AACA,IAAA;AAKA,IAAA;AACA,IAAA;AACA,IAAA;AAAO,EAAA;AACT;AAQA;AAKE,EAAA;AACE,IAAA;AAAO,EAAA;AAET,EAAA;AACF;AAEA;AAGyB,EAAA;AApHzB,IAAA;AAqHE,IAAA;AACA,IAAA;AACA,IAAA;AAEA,IAAA;AACA,IAAA;AAAyB,MAAA;AACvB,MAAA;AACqB,IAAA;AAGvB,IAAA;AAEA,IAAA;AAEA,IAAA;AACE,MAAA;AAAqE,IAAA;AAErE,MAAA;AAA4D,IAAA;AAG9D,IAAA;AAAO,EAAA;AACT;AAcO;AAGH,EAAA;AAEA,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AAEA,IAAA;AAAqB,MAAA;AAEjB,QAAA;AAA6B,MAAA;AAE7B,QAAA;AAA2C,MAAA;AAE3C,QAAA;AAAyC,MAAA;AAEzC,QAAA;AAA0D,IAAA;AAC9D,EAAA;AAEA,IAAA;AAEA,IAAA;AACA,IAAA;AAGA,IAAA;AAEA,IAAA;AACA,IAAA;AAAO,EAAA;AAEX;AHyBF;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/pedroapfilho/dev/civic-auth/packages/civic-auth-client/dist/nextjs.js","sourcesContent":[null,"/**\n * Used on the server-side to get the user object from the cookie\n */\nimport { User } from \"@/types\";\nimport { GenericUserSession } from \"@/shared/UserSession\";\nimport { NextjsClientStorage } from \"@/nextjs/cookies\";\nimport { retrieveTokens } from \"@/shared/util\";\n\nexport const getUser = (): User | null => {\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n const tokens = retrieveTokens(clientStorage);\n const user = userSession.get();\n if (!user || !tokens) return null;\n\n return {\n ...user!,\n idToken: tokens.id_token,\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? \"\",\n } as User;\n};\n","/**\n * Authenticates the user on all requests by checking the token cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * console.log('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * console.log('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport { NextRequest, NextResponse } from \"next/server.js\";\nimport picomatch from \"picomatch\";\nimport {\n AuthConfig,\n defaultAuthConfig,\n resolveAuthConfig,\n} from \"@/nextjs/config.js\";\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchGlob = (pathname: string, globPattern: string) => {\n const matches = picomatch(globPattern);\n return matches(pathname);\n};\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchesGlobs = (pathname: string, patterns: string[]) =>\n patterns.some((pattern) => {\n if (!pattern) return false;\n console.log(\"matching\", {\n pattern,\n pathname,\n match: matchGlob(pathname, pattern),\n });\n return matchGlob(pathname, pattern);\n });\n\n// internal - used by all exported functions\nconst applyAuth = async (\n authConfig: AuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n\n // Check for any valid auth token\n const isAuthenticated = !!request.cookies.get(\"id_token\");\n\n // skip auth check for login url\n if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl) {\n console.log(\"→ Skipping auth check - this is the login URL\");\n return undefined;\n }\n\n if (!matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.include)) {\n console.log(\"→ Skipping auth check - path not in include patterns\");\n return undefined;\n }\n\n if (matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.exclude)) {\n console.log(\"→ Skipping auth check - path in exclude patterns\");\n return undefined;\n }\n\n // Check for either token type\n if (!isAuthenticated) {\n console.log(\"→ No valid token found - redirecting to login\");\n const loginUrl = new URL(authConfigWithDefaults.loginUrl, request.url);\n return NextResponse.redirect(loginUrl);\n }\n\n console.log(\"→ Auth check passed\");\n return undefined;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig = defaultAuthConfig) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * console.log('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth({}, request);\n if (response) return response;\n return middleware(request);\n };\n}\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * const withAuth = auth({ loginUrl = '/login' }); // or just auth();\n *\n * export default withAuth(async (request) => {\n * console.log('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: AuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n return middleware(request);\n };\n };\n}\n","import { NextRequest, NextResponse } from \"next/server.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport { AuthConfig, resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport {\n clearAuthCookies,\n NextjsClientStorage,\n NextjsCookieStorage,\n} from \"@/nextjs/cookies.js\";\nimport { GenericPublicClientPKCEProducer } from \"@/services/PKCE.js\";\nimport { resolveOAuthAccessCode } from \"@/server/login.js\";\nimport { getUser } from \"@/shared/session.js\";\nimport { resolveCallbackUrl } from \"@/nextjs/utils.js\";\nimport { GenericUserSession } from \"@/shared/UserSession.js\";\nimport { TOKEN_EXCHANGE_TRIGGER_TEXT } from \"@/constants\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * create a code verifier and challenge for PKCE\n * saving the verifier in a cookie for later use\n * @returns {Promise<NextResponse>}\n */\nasync function handleChallenge(): Promise<NextResponse> {\n const cookieStorage = new NextjsCookieStorage();\n const pkceProducer = new GenericPublicClientPKCEProducer(cookieStorage);\n\n const challenge = await pkceProducer.getCodeChallenge();\n\n return NextResponse.json({ status: \"success\", challenge });\n}\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n // If we have a code_verifier cookie, we can do a token exchange.\n // Otherwise, just render an empty page.\n // The initial redirect back from the auth server does not send cookies, because the redirect is from a 3rd-party domain.\n // The client will make an additional call to this route with cookies included, at which point we do the token exchange.\n if (!request.cookies.get(\"code_verifier\")) {\n const response = new NextResponse(\n `<html><body><span style=\"display:none\">${TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n console.log(\n `handleCallback no code_verifier found, returning ${TOKEN_EXCHANGE_TRIGGER_TEXT}`,\n );\n return response;\n }\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n const cookieStorage = new NextjsCookieStorage();\n\n const resolvedConfigs = resolveAuthConfig(config);\n\n const callbackUrl = resolveCallbackUrl(resolvedConfigs, request.url);\n try {\n await resolveOAuthAccessCode(code, state, cookieStorage, {\n ...resolvedConfigs,\n redirectUrl: callbackUrl,\n });\n } catch (error) {\n logger.error(\"Token exchange failed:\", error);\n throw new AuthError(\"Failed to authenticate user\", 401);\n }\n\n const user = await getUser(cookieStorage);\n if (!user) {\n throw new AuthError(\"Failed to get user info\", 401);\n }\n\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n userSession.set(user);\n\n // return an empty HTML response so the iframe doesn't show any response\n // in the short moment between the redirect and the parent window\n // acknowledging the redirect and closing the iframe\n const response = new NextResponse(`<html></html>`);\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n return response;\n}\n\n/**\n * If redirectPath is an absolute path, return it as-is.\n * Otherwise for relative paths, append it to the current domain.\n * @param redirectPath\n * @returns\n */\nconst getAbsoluteRedirectPath = (\n redirectPath: string,\n currentBasePath: string,\n) => {\n // Check if the redirectPath is an absolute URL\n if (/^(https?:\\/\\/|www\\.).+/i.test(redirectPath)) {\n return redirectPath; // Return as-is if it's an absolute URL\n }\n return new URL(redirectPath, currentBasePath).href;\n};\n\nasync function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const defaultRedirectPath = resolvedConfigs.loginUrl ?? \"/\";\n const redirectTarget =\n new URL(request.url).searchParams.get(\"redirect\") || defaultRedirectPath;\n const isAbsoluteRedirect = /^(https?:\\/\\/|www\\.).+/i.test(redirectTarget);\n const finalRedirectUrl = getAbsoluteRedirectPath(\n redirectTarget,\n new URL(request.url).origin,\n );\n\n const response = NextResponse.redirect(finalRedirectUrl);\n\n clearAuthCookies();\n\n try {\n revalidatePath(isAbsoluteRedirect ? finalRedirectUrl : redirectTarget);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n\n return response;\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n return await handleChallenge();\n case \"callback\":\n return await handleCallback(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n clearAuthCookies();\n return response;\n }\n };\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/kevincolgan/code/civic-auth/packages/civic-auth-client/dist/nextjs.js","../src/nextjs/GetUser.ts","../src/nextjs/middleware.ts","../src/nextjs/routeHandler.ts"],"names":["getUser","NextResponse","response"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACA;AACA;AACF,sDAA4B;AAC5B;AACA;AChBO,IAAMA,SAAAA,EAAU,CAAA,EAAA,GAAmB;AAR1C,EAAA,IAAA,EAAA;AASE,EAAA,MAAM,cAAA,EAAgB,IAAI,yCAAA,CAAoB,CAAA;AAC9C,EAAA,MAAM,YAAA,EAAc,IAAI,wCAAA,CAAmB,aAAa,CAAA;AACxD,EAAA,MAAM,OAAA,EAAS,6CAAA,aAA4B,CAAA;AAC3C,EAAA,MAAM,KAAA,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AO,EAAA;AAET,EAAA;AACF;AAEA;AAGyB,EAAA;AAnHzB,IAAA;AAoHE,IAAA;AACA,IAAA;AACA,IAAA;AAEA,IAAA;AACA,IAAA;AAAyB,MAAA;AACvB,MAAA;AACqB,IAAA;AAGvB,IAAA;AAEA,IAAA;AAEA,IAAA;AACE,MAAA;AAAqE,IAAA;AAErE,MAAA;AAA4D,IAAA;AAG9D,IAAA;AAAO,EAAA;AACT;AAcO;AAGH,EAAA;AAEA,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AAEA,IAAA;AAAqB,MAAA;AAEjB,QAAA;AAA6B,MAAA;AAE7B,QAAA;AAA2C,MAAA;AAE3C,QAAA;AAAyC,MAAA;AAEzC,QAAA;AAA0D,IAAA;AAC9D,EAAA;AAEA,IAAA;AAEA,IAAA;AACA,IAAA;AAGA,IAAA;AAEA,IAAA;AACA,IAAA;AAAO,EAAA;AAEX;AH0BF;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/kevincolgan/code/civic-auth/packages/civic-auth-client/dist/nextjs.js","sourcesContent":[null,"/**\n * Used on the server-side to get the user object from the cookie\n */\nimport { User } from \"@/types\";\nimport { GenericUserSession } from \"@/shared/UserSession\";\nimport { NextjsClientStorage } from \"@/nextjs/cookies\";\nimport { retrieveTokens } from \"@/shared/util\";\n\nexport const getUser = (): User | null => {\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n const tokens = retrieveTokens(clientStorage);\n const user = userSession.get();\n if (!user || !tokens) return null;\n\n return {\n ...user!,\n idToken: tokens.id_token,\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? \"\",\n } as User;\n};\n","/**\n * Authenticates the user on all requests by checking the token cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * console.log('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * console.log('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport { NextRequest, NextResponse } from \"next/server.js\";\nimport picomatch from \"picomatch\";\nimport {\n AuthConfig,\n defaultAuthConfig,\n resolveAuthConfig,\n} from \"@/nextjs/config.js\";\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchGlob = (pathname: string, globPattern: string) => {\n const matches = picomatch(globPattern);\n return matches(pathname);\n};\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchesGlobs = (pathname: string, patterns: string[]) =>\n patterns.some((pattern) => {\n if (!pattern) return false;\n console.log(\"matching\", {\n pattern,\n pathname,\n match: matchGlob(pathname, pattern),\n });\n return matchGlob(pathname, pattern);\n });\n\n// internal - used by all exported functions\nconst applyAuth = async (\n authConfig: AuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n\n // Check for any valid auth token\n const isAuthenticated = !!request.cookies.get(\"id_token\");\n\n // skip auth check for login url\n if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl) {\n console.log(\"→ Skipping auth check - this is the login URL\");\n return undefined;\n }\n\n if (!matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.include)) {\n console.log(\"→ Skipping auth check - path not in include patterns\");\n return undefined;\n }\n\n if (matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.exclude)) {\n console.log(\"→ Skipping auth check - path in exclude patterns\");\n return undefined;\n }\n\n // Check for either token type\n if (!isAuthenticated) {\n console.log(\"→ No valid token found - redirecting to login\");\n const loginUrl = new URL(authConfigWithDefaults.loginUrl, request.url);\n return NextResponse.redirect(loginUrl);\n }\n\n console.log(\"→ Auth check passed\");\n return undefined;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig = defaultAuthConfig) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * console.log('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth({}, request);\n if (response) return response;\n return middleware(request);\n };\n}\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * const withAuth = auth({ loginUrl = '/login' }); // or just auth();\n *\n * export default withAuth(async (request) => {\n * console.log('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: AuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n return middleware(request);\n };\n };\n}\n","import { NextRequest, NextResponse } from \"next/server.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport { AuthConfig, resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport {\n clearAuthCookies,\n NextjsClientStorage,\n NextjsCookieStorage,\n} from \"@/nextjs/cookies.js\";\nimport { GenericPublicClientPKCEProducer } from \"@/services/PKCE.js\";\nimport { resolveOAuthAccessCode } from \"@/server/login.js\";\nimport { getUser } from \"@/shared/session.js\";\nimport { resolveCallbackUrl } from \"@/nextjs/utils.js\";\nimport { GenericUserSession } from \"@/shared/UserSession.js\";\nimport { TOKEN_EXCHANGE_TRIGGER_TEXT } from \"@/constants\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * create a code verifier and challenge for PKCE\n * saving the verifier in a cookie for later use\n * @returns {Promise<NextResponse>}\n */\nasync function handleChallenge(): Promise<NextResponse> {\n const cookieStorage = new NextjsCookieStorage();\n const pkceProducer = new GenericPublicClientPKCEProducer(cookieStorage);\n\n const challenge = await pkceProducer.getCodeChallenge();\n\n return NextResponse.json({ status: \"success\", challenge });\n}\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n // If we have a code_verifier cookie, we can do a token exchange.\n // Otherwise, just render an empty page.\n // The initial redirect back from the auth server does not send cookies, because the redirect is from a 3rd-party domain.\n // The client will make an additional call to this route with cookies included, at which point we do the token exchange.\n if (!request.cookies.get(\"code_verifier\")) {\n const response = new NextResponse(\n `<html><body><span style=\"display:none\">${TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n console.log(\n `handleCallback no code_verifier found, returning ${TOKEN_EXCHANGE_TRIGGER_TEXT}`,\n );\n return response;\n }\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n const resolvedConfigs = resolveAuthConfig(config);\n const cookieStorage = new NextjsCookieStorage(resolvedConfigs.cookies.tokens);\n\n const callbackUrl = resolveCallbackUrl(resolvedConfigs, request.url);\n try {\n await resolveOAuthAccessCode(code, state, cookieStorage, {\n ...resolvedConfigs,\n redirectUrl: callbackUrl,\n });\n } catch (error) {\n logger.error(\"Token exchange failed:\", error);\n throw new AuthError(\"Failed to authenticate user\", 401);\n }\n\n const user = await getUser(cookieStorage);\n if (!user) {\n throw new AuthError(\"Failed to get user info\", 401);\n }\n\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n userSession.set(user);\n\n // return an empty HTML response so the iframe doesn't show any response\n // in the short moment between the redirect and the parent window\n // acknowledging the redirect and closing the iframe\n const response = new NextResponse(`<html></html>`);\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n return response;\n}\n\n/**\n * If redirectPath is an absolute path, return it as-is.\n * Otherwise for relative paths, append it to the current domain.\n * @param redirectPath\n * @returns\n */\nconst getAbsoluteRedirectPath = (\n redirectPath: string,\n currentBasePath: string,\n) => {\n // Check if the redirectPath is an absolute URL\n if (/^(https?:\\/\\/|www\\.).+/i.test(redirectPath)) {\n return redirectPath; // Return as-is if it's an absolute URL\n }\n return new URL(redirectPath, currentBasePath).href;\n};\n\nasync function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const defaultRedirectPath = resolvedConfigs.loginUrl ?? \"/\";\n const redirectTarget =\n new URL(request.url).searchParams.get(\"redirect\") || defaultRedirectPath;\n const isAbsoluteRedirect = /^(https?:\\/\\/|www\\.).+/i.test(redirectTarget);\n const finalRedirectUrl = getAbsoluteRedirectPath(\n redirectTarget,\n new URL(request.url).origin,\n );\n\n const response = NextResponse.redirect(finalRedirectUrl);\n\n clearAuthCookies();\n\n try {\n revalidatePath(isAbsoluteRedirect ? finalRedirectUrl : redirectTarget);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n\n return response;\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n return await handleChallenge();\n case \"callback\":\n return await handleCallback(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n clearAuthCookies();\n return response;\n }\n };\n"]}
|
package/dist/nextjs.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
loggers,
|
|
8
8
|
resolveAuthConfig,
|
|
9
9
|
resolveCallbackUrl
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-5XL2ST72.mjs";
|
|
11
11
|
import {
|
|
12
12
|
GenericPublicClientPKCEProducer,
|
|
13
13
|
GenericUserSession,
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
getUser,
|
|
16
16
|
resolveOAuthAccessCode,
|
|
17
17
|
retrieveTokens
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-G3P5TIO2.mjs";
|
|
19
19
|
import {
|
|
20
20
|
__async,
|
|
21
21
|
__spreadProps,
|
|
@@ -132,8 +132,8 @@ function handleCallback(request, config) {
|
|
|
132
132
|
const code = request.nextUrl.searchParams.get("code");
|
|
133
133
|
const state = request.nextUrl.searchParams.get("state");
|
|
134
134
|
if (!code || !state) throw new AuthError("Bad parameters", 400);
|
|
135
|
-
const cookieStorage = new NextjsCookieStorage();
|
|
136
135
|
const resolvedConfigs = resolveAuthConfig(config);
|
|
136
|
+
const cookieStorage = new NextjsCookieStorage(resolvedConfigs.cookies.tokens);
|
|
137
137
|
const callbackUrl = resolveCallbackUrl(resolvedConfigs, request.url);
|
|
138
138
|
try {
|
|
139
139
|
yield resolveOAuthAccessCode(code, state, cookieStorage, __spreadProps(__spreadValues({}, resolvedConfigs), {
|
package/dist/nextjs.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/nextjs/GetUser.ts","../src/nextjs/middleware.ts","../src/nextjs/routeHandler.ts"],"sourcesContent":["/**\n * Used on the server-side to get the user object from the cookie\n */\nimport { User } from \"@/types\";\nimport { GenericUserSession } from \"@/shared/UserSession\";\nimport { NextjsClientStorage } from \"@/nextjs/cookies\";\nimport { retrieveTokens } from \"@/shared/util\";\n\nexport const getUser = (): User | null => {\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n const tokens = retrieveTokens(clientStorage);\n const user = userSession.get();\n if (!user || !tokens) return null;\n\n return {\n ...user!,\n idToken: tokens.id_token,\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? \"\",\n } as User;\n};\n","/**\n * Authenticates the user on all requests by checking the token cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * console.log('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * console.log('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport { NextRequest, NextResponse } from \"next/server.js\";\nimport picomatch from \"picomatch\";\nimport {\n AuthConfig,\n defaultAuthConfig,\n resolveAuthConfig,\n} from \"@/nextjs/config.js\";\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchGlob = (pathname: string, globPattern: string) => {\n const matches = picomatch(globPattern);\n return matches(pathname);\n};\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchesGlobs = (pathname: string, patterns: string[]) =>\n patterns.some((pattern) => {\n if (!pattern) return false;\n console.log(\"matching\", {\n pattern,\n pathname,\n match: matchGlob(pathname, pattern),\n });\n return matchGlob(pathname, pattern);\n });\n\n// internal - used by all exported functions\nconst applyAuth = async (\n authConfig: AuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n\n // Check for any valid auth token\n const isAuthenticated = !!request.cookies.get(\"id_token\");\n\n // skip auth check for login url\n if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl) {\n console.log(\"→ Skipping auth check - this is the login URL\");\n return undefined;\n }\n\n if (!matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.include)) {\n console.log(\"→ Skipping auth check - path not in include patterns\");\n return undefined;\n }\n\n if (matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.exclude)) {\n console.log(\"→ Skipping auth check - path in exclude patterns\");\n return undefined;\n }\n\n // Check for either token type\n if (!isAuthenticated) {\n console.log(\"→ No valid token found - redirecting to login\");\n const loginUrl = new URL(authConfigWithDefaults.loginUrl, request.url);\n return NextResponse.redirect(loginUrl);\n }\n\n console.log(\"→ Auth check passed\");\n return undefined;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig = defaultAuthConfig) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * console.log('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth({}, request);\n if (response) return response;\n return middleware(request);\n };\n}\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * const withAuth = auth({ loginUrl = '/login' }); // or just auth();\n *\n * export default withAuth(async (request) => {\n * console.log('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: AuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n return middleware(request);\n };\n };\n}\n","import { NextRequest, NextResponse } from \"next/server.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport { AuthConfig, resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport {\n clearAuthCookies,\n NextjsClientStorage,\n NextjsCookieStorage,\n} from \"@/nextjs/cookies.js\";\nimport { GenericPublicClientPKCEProducer } from \"@/services/PKCE.js\";\nimport { resolveOAuthAccessCode } from \"@/server/login.js\";\nimport { getUser } from \"@/shared/session.js\";\nimport { resolveCallbackUrl } from \"@/nextjs/utils.js\";\nimport { GenericUserSession } from \"@/shared/UserSession.js\";\nimport { TOKEN_EXCHANGE_TRIGGER_TEXT } from \"@/constants\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * create a code verifier and challenge for PKCE\n * saving the verifier in a cookie for later use\n * @returns {Promise<NextResponse>}\n */\nasync function handleChallenge(): Promise<NextResponse> {\n const cookieStorage = new NextjsCookieStorage();\n const pkceProducer = new GenericPublicClientPKCEProducer(cookieStorage);\n\n const challenge = await pkceProducer.getCodeChallenge();\n\n return NextResponse.json({ status: \"success\", challenge });\n}\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n // If we have a code_verifier cookie, we can do a token exchange.\n // Otherwise, just render an empty page.\n // The initial redirect back from the auth server does not send cookies, because the redirect is from a 3rd-party domain.\n // The client will make an additional call to this route with cookies included, at which point we do the token exchange.\n if (!request.cookies.get(\"code_verifier\")) {\n const response = new NextResponse(\n `<html><body><span style=\"display:none\">${TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n console.log(\n `handleCallback no code_verifier found, returning ${TOKEN_EXCHANGE_TRIGGER_TEXT}`,\n );\n return response;\n }\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n const cookieStorage = new NextjsCookieStorage();\n\n const resolvedConfigs = resolveAuthConfig(config);\n\n const callbackUrl = resolveCallbackUrl(resolvedConfigs, request.url);\n try {\n await resolveOAuthAccessCode(code, state, cookieStorage, {\n ...resolvedConfigs,\n redirectUrl: callbackUrl,\n });\n } catch (error) {\n logger.error(\"Token exchange failed:\", error);\n throw new AuthError(\"Failed to authenticate user\", 401);\n }\n\n const user = await getUser(cookieStorage);\n if (!user) {\n throw new AuthError(\"Failed to get user info\", 401);\n }\n\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n userSession.set(user);\n\n // return an empty HTML response so the iframe doesn't show any response\n // in the short moment between the redirect and the parent window\n // acknowledging the redirect and closing the iframe\n const response = new NextResponse(`<html></html>`);\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n return response;\n}\n\n/**\n * If redirectPath is an absolute path, return it as-is.\n * Otherwise for relative paths, append it to the current domain.\n * @param redirectPath\n * @returns\n */\nconst getAbsoluteRedirectPath = (\n redirectPath: string,\n currentBasePath: string,\n) => {\n // Check if the redirectPath is an absolute URL\n if (/^(https?:\\/\\/|www\\.).+/i.test(redirectPath)) {\n return redirectPath; // Return as-is if it's an absolute URL\n }\n return new URL(redirectPath, currentBasePath).href;\n};\n\nasync function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const defaultRedirectPath = resolvedConfigs.loginUrl ?? \"/\";\n const redirectTarget =\n new URL(request.url).searchParams.get(\"redirect\") || defaultRedirectPath;\n const isAbsoluteRedirect = /^(https?:\\/\\/|www\\.).+/i.test(redirectTarget);\n const finalRedirectUrl = getAbsoluteRedirectPath(\n redirectTarget,\n new URL(request.url).origin,\n );\n\n const response = NextResponse.redirect(finalRedirectUrl);\n\n clearAuthCookies();\n\n try {\n revalidatePath(isAbsoluteRedirect ? finalRedirectUrl : redirectTarget);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n\n return response;\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n return await handleChallenge();\n case \"callback\":\n return await handleCallback(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n clearAuthCookies();\n return response;\n }\n };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAMA,WAAU,MAAmB;AAR1C;AASE,QAAM,gBAAgB,IAAI,oBAAoB;AAC9C,QAAM,cAAc,IAAI,mBAAmB,aAAa;AACxD,QAAM,SAAS,eAAe,aAAa;AA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mB;AAAA,MACvB;AAAA,MACA,IAAI,IAAI,QAAQ,GAAG,EAAE;AAAA,IACvB;AAEA,UAAM,WAAWA,cAAa,SAAS,gBAAgB;AAEvD,qBAAiB;AAEjB,QAAI;AACF,qBAAe,qBAAqB,mBAAmB,cAAc;AAAA,IACvE,SAAS,OAAO;AACd,aAAO,KAAK,2CAA2C,KAAK;AAAA,IAC9D;AAEA,WAAO;AAAA,EACT;AAAA;AAcO,IAAM,UACX,CAAC,aAAa,CAAC,MACf,CAAO,YAAgD;AACrD,QAAM,SAAS,kBAAkB,UAAU;AAE3C,MAAI;AACF,UAAM,WAAW,QAAQ,QAAQ;AACjC,UAAM,eAAe,SAAS,MAAM,GAAG;AACvC,UAAM,cAAc,aAAa,aAAa,SAAS,CAAC;AAExD,YAAQ,aAAa;AAAA,MACnB,KAAK;AACH,eAAO,MAAM,gBAAgB;AAAA,MAC/B,KAAK;AACH,eAAO,MAAM,eAAe,SAAS,MAAM;AAAA,MAC7C,KAAK;AACH,eAAO,MAAM,aAAa,SAAS,MAAM;AAAA,MAC3C;AACE,cAAM,IAAI,UAAU,uBAAuB,QAAQ,IAAI,GAAG;AAAA,IAC9D;AAAA,EACF,SAAS,OAAO;AACd,WAAO,MAAM,uBAAuB,KAAK;AAEzC,UAAM,SAAS,iBAAiB,YAAY,MAAM,SAAS;AAC3D,UAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,UAAM,WAAWA,cAAa,KAAK,EAAE,OAAO,QAAQ,GAAG,EAAE,OAAO,CAAC;AAEjE,qBAAiB;AACjB,WAAO;AAAA,EACT;AACF;","names":["getUser","NextResponse","NextResponse","response"]}
|
|
1
|
+
{"version":3,"sources":["../src/nextjs/GetUser.ts","../src/nextjs/middleware.ts","../src/nextjs/routeHandler.ts"],"sourcesContent":["/**\n * Used on the server-side to get the user object from the cookie\n */\nimport { User } from \"@/types\";\nimport { GenericUserSession } from \"@/shared/UserSession\";\nimport { NextjsClientStorage } from \"@/nextjs/cookies\";\nimport { retrieveTokens } from \"@/shared/util\";\n\nexport const getUser = (): User | null => {\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n const tokens = retrieveTokens(clientStorage);\n const user = userSession.get();\n if (!user || !tokens) return null;\n\n return {\n ...user!,\n idToken: tokens.id_token,\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? \"\",\n } as User;\n};\n","/**\n * Authenticates the user on all requests by checking the token cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * console.log('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * console.log('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport { NextRequest, NextResponse } from \"next/server.js\";\nimport picomatch from \"picomatch\";\nimport {\n AuthConfig,\n defaultAuthConfig,\n resolveAuthConfig,\n} from \"@/nextjs/config.js\";\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchGlob = (pathname: string, globPattern: string) => {\n const matches = picomatch(globPattern);\n return matches(pathname);\n};\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchesGlobs = (pathname: string, patterns: string[]) =>\n patterns.some((pattern) => {\n if (!pattern) return false;\n console.log(\"matching\", {\n pattern,\n pathname,\n match: matchGlob(pathname, pattern),\n });\n return matchGlob(pathname, pattern);\n });\n\n// internal - used by all exported functions\nconst applyAuth = async (\n authConfig: AuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n\n // Check for any valid auth token\n const isAuthenticated = !!request.cookies.get(\"id_token\");\n\n // skip auth check for login url\n if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl) {\n console.log(\"→ Skipping auth check - this is the login URL\");\n return undefined;\n }\n\n if (!matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.include)) {\n console.log(\"→ Skipping auth check - path not in include patterns\");\n return undefined;\n }\n\n if (matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.exclude)) {\n console.log(\"→ Skipping auth check - path in exclude patterns\");\n return undefined;\n }\n\n // Check for either token type\n if (!isAuthenticated) {\n console.log(\"→ No valid token found - redirecting to login\");\n const loginUrl = new URL(authConfigWithDefaults.loginUrl, request.url);\n return NextResponse.redirect(loginUrl);\n }\n\n console.log(\"→ Auth check passed\");\n return undefined;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig = defaultAuthConfig) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * console.log('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth({}, request);\n if (response) return response;\n return middleware(request);\n };\n}\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * const withAuth = auth({ loginUrl = '/login' }); // or just auth();\n *\n * export default withAuth(async (request) => {\n * console.log('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: AuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n return middleware(request);\n };\n };\n}\n","import { NextRequest, NextResponse } from \"next/server.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport { AuthConfig, resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport {\n clearAuthCookies,\n NextjsClientStorage,\n NextjsCookieStorage,\n} from \"@/nextjs/cookies.js\";\nimport { GenericPublicClientPKCEProducer } from \"@/services/PKCE.js\";\nimport { resolveOAuthAccessCode } from \"@/server/login.js\";\nimport { getUser } from \"@/shared/session.js\";\nimport { resolveCallbackUrl } from \"@/nextjs/utils.js\";\nimport { GenericUserSession } from \"@/shared/UserSession.js\";\nimport { TOKEN_EXCHANGE_TRIGGER_TEXT } from \"@/constants\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * create a code verifier and challenge for PKCE\n * saving the verifier in a cookie for later use\n * @returns {Promise<NextResponse>}\n */\nasync function handleChallenge(): Promise<NextResponse> {\n const cookieStorage = new NextjsCookieStorage();\n const pkceProducer = new GenericPublicClientPKCEProducer(cookieStorage);\n\n const challenge = await pkceProducer.getCodeChallenge();\n\n return NextResponse.json({ status: \"success\", challenge });\n}\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n // If we have a code_verifier cookie, we can do a token exchange.\n // Otherwise, just render an empty page.\n // The initial redirect back from the auth server does not send cookies, because the redirect is from a 3rd-party domain.\n // The client will make an additional call to this route with cookies included, at which point we do the token exchange.\n if (!request.cookies.get(\"code_verifier\")) {\n const response = new NextResponse(\n `<html><body><span style=\"display:none\">${TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n console.log(\n `handleCallback no code_verifier found, returning ${TOKEN_EXCHANGE_TRIGGER_TEXT}`,\n );\n return response;\n }\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n const resolvedConfigs = resolveAuthConfig(config);\n const cookieStorage = new NextjsCookieStorage(resolvedConfigs.cookies.tokens);\n\n const callbackUrl = resolveCallbackUrl(resolvedConfigs, request.url);\n try {\n await resolveOAuthAccessCode(code, state, cookieStorage, {\n ...resolvedConfigs,\n redirectUrl: callbackUrl,\n });\n } catch (error) {\n logger.error(\"Token exchange failed:\", error);\n throw new AuthError(\"Failed to authenticate user\", 401);\n }\n\n const user = await getUser(cookieStorage);\n if (!user) {\n throw new AuthError(\"Failed to get user info\", 401);\n }\n\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n userSession.set(user);\n\n // return an empty HTML response so the iframe doesn't show any response\n // in the short moment between the redirect and the parent window\n // acknowledging the redirect and closing the iframe\n const response = new NextResponse(`<html></html>`);\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n return response;\n}\n\n/**\n * If redirectPath is an absolute path, return it as-is.\n * Otherwise for relative paths, append it to the current domain.\n * @param redirectPath\n * @returns\n */\nconst getAbsoluteRedirectPath = (\n redirectPath: string,\n currentBasePath: string,\n) => {\n // Check if the redirectPath is an absolute URL\n if (/^(https?:\\/\\/|www\\.).+/i.test(redirectPath)) {\n return redirectPath; // Return as-is if it's an absolute URL\n }\n return new URL(redirectPath, currentBasePath).href;\n};\n\nasync function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const defaultRedirectPath = resolvedConfigs.loginUrl ?? \"/\";\n const redirectTarget =\n new URL(request.url).searchParams.get(\"redirect\") || defaultRedirectPath;\n const isAbsoluteRedirect = /^(https?:\\/\\/|www\\.).+/i.test(redirectTarget);\n const finalRedirectUrl = getAbsoluteRedirectPath(\n redirectTarget,\n new URL(request.url).origin,\n );\n\n const response = NextResponse.redirect(finalRedirectUrl);\n\n clearAuthCookies();\n\n try {\n revalidatePath(isAbsoluteRedirect ? finalRedirectUrl : redirectTarget);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n\n return response;\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n return await handleChallenge();\n case \"callback\":\n return await handleCallback(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n clearAuthCookies();\n return response;\n }\n };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAMA,WAAU,MAAmB;AAR1C;AASE,QAAM,gBAAgB,IAAI,oBAAoB;AAC9C,QAAM,cAAc,IAAI,mBAAmB,aAAa;AACxD,QAAM,SAAS,eAAe,aAAa;AAC3C,QAAM,OAAO,YAAY,IAAI;AAC7B,MAAI,CAAC,QAAQ,CAAC,OAAQ,QAAO;AAE7B,SAAO,iCACF,OADE;AAAA,IAEL,SAAS,OAAO;AAAA,IAChB,aAAa,OAAO;AAAA,IACpB,eAAc,YAAO,kBAAP,YAAwB;AAAA,EACxC;AACF;;;ACAA,SAAsB,oBAAoB;AAC1C,OAAO,eAAe;AAgBtB,IAAM,YAA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AAEA,WAAO;AAAA,EACT;AAAA;AAcO,IAAM,UACX,CAAC,aAAa,CAAC,MACf,CAAO,YAAgD;AACrD,QAAM,SAAS,kBAAkB,UAAU;AAE3C,MAAI;AACF,UAAM,WAAW,QAAQ,QAAQ;AACjC,UAAM,eAAe,SAAS,MAAM,GAAG;AACvC,UAAM,cAAc,aAAa,aAAa,SAAS,CAAC;AAExD,YAAQ,aAAa;AAAA,MACnB,KAAK;AACH,eAAO,MAAM,gBAAgB;AAAA,MAC/B,KAAK;AACH,eAAO,MAAM,eAAe,SAAS,MAAM;AAAA,MAC7C,KAAK;AACH,eAAO,MAAM,aAAa,SAAS,MAAM;AAAA,MAC3C;AACE,cAAM,IAAI,UAAU,uBAAuB,QAAQ,IAAI,GAAG;AAAA,IAC9D;AAAA,EACF,SAAS,OAAO;AACd,WAAO,MAAM,uBAAuB,KAAK;AAEzC,UAAM,SAAS,iBAAiB,YAAY,MAAM,SAAS;AAC3D,UAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,UAAM,WAAWA,cAAa,KAAK,EAAE,OAAO,QAAQ,GAAG,EAAE,OAAO,CAAC;AAEjE,qBAAiB;AACjB,WAAO;AAAA,EACT;AACF;","names":["getUser","NextResponse","NextResponse","response"]}
|
package/dist/react.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { U as UserContextType, A as AuthContextType } from './index-
|
|
2
|
-
import { F as ForwardedTokens, C as Config, S as SessionData, D as DisplayMode } from './types-
|
|
1
|
+
import { U as UserContextType, A as AuthContextType } from './index-DvjkKpkk.mjs';
|
|
2
|
+
import { F as ForwardedTokens, C as Config, S as SessionData, b as EmptyObject, U as User, D as DisplayMode } from './types-HdCjGldB.mjs';
|
|
3
|
+
import { O as OAuthTokens } from './types-b4c1koXj.mjs';
|
|
3
4
|
import { ReactNode, RefObject, Dispatch, SetStateAction } from 'react';
|
|
4
5
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
5
6
|
import 'oslo/jwt';
|
|
@@ -28,11 +29,7 @@ type AuthProviderProps = {
|
|
|
28
29
|
onSignOut?: () => void;
|
|
29
30
|
pkceConsumer?: PKCEConsumer;
|
|
30
31
|
modalIframe?: boolean;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
type SessionProviderOutput = SessionData & {
|
|
34
|
-
iframeRef: RefObject<HTMLIFrameElement> | null;
|
|
35
|
-
setAuthResponseUrl: Dispatch<SetStateAction<string | null>>;
|
|
32
|
+
sessionData?: SessionData;
|
|
36
33
|
};
|
|
37
34
|
|
|
38
35
|
type CivicAuthProviderProps = Omit<AuthProviderProps, "pkceConsumer">;
|
|
@@ -43,13 +40,13 @@ declare const CivicNextAuthProvider: ({ children, ...props }: NextCivicAuthProvi
|
|
|
43
40
|
|
|
44
41
|
declare const useUser: <T extends Record<string, unknown> = Record<string, never>>() => UserContextType<T>;
|
|
45
42
|
|
|
46
|
-
declare const useUserCookie: () =>
|
|
43
|
+
declare const useUserCookie: <T extends EmptyObject>() => User<T> | null;
|
|
47
44
|
|
|
48
45
|
declare const useToken: () => TokenContextType;
|
|
49
46
|
|
|
50
47
|
declare const useAuth: () => AuthContextType;
|
|
51
48
|
|
|
52
|
-
declare const useSession: () =>
|
|
49
|
+
declare const useSession: () => SessionData;
|
|
53
50
|
|
|
54
51
|
type ConfigProviderOutput = {
|
|
55
52
|
config: Config;
|
|
@@ -60,6 +57,15 @@ type ConfigProviderOutput = {
|
|
|
60
57
|
|
|
61
58
|
declare const useConfig: () => ConfigProviderOutput;
|
|
62
59
|
|
|
60
|
+
declare const useTokenCookie: (tokenName: OAuthTokens) => string | null;
|
|
61
|
+
|
|
62
|
+
type IframeProviderOutput = {
|
|
63
|
+
iframeRef: RefObject<HTMLIFrameElement> | null;
|
|
64
|
+
setAuthResponseUrl: Dispatch<SetStateAction<string | null>>;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
declare const useIframe: () => IframeProviderOutput;
|
|
68
|
+
|
|
63
69
|
type CivicAuthIframeContainerProps = {
|
|
64
70
|
onClose?: () => void;
|
|
65
71
|
closeOnRedirect?: boolean;
|
|
@@ -84,4 +90,4 @@ declare const NextLogOut: ({ children }: {
|
|
|
84
90
|
children: ReactNode;
|
|
85
91
|
}) => react_jsx_runtime.JSX.Element;
|
|
86
92
|
|
|
87
|
-
export { AuthContextType, CivicAuthIframeContainer, CivicAuthProvider, type CivicAuthProviderProps, CivicNextAuthProvider, type NextCivicAuthProviderProps, NextLogOut, SignInButton, SignOutButton, type TokenContextType, UserButton, UserContextType, useAuth, useConfig, useSession, useToken, useUser, useUserCookie };
|
|
93
|
+
export { AuthContextType, CivicAuthIframeContainer, CivicAuthProvider, type CivicAuthProviderProps, CivicNextAuthProvider, type NextCivicAuthProviderProps, NextLogOut, SignInButton, SignOutButton, type TokenContextType, UserButton, UserContextType, useAuth, useConfig, useIframe, useSession, useToken, useTokenCookie, useUser, useUserCookie };
|
package/dist/react.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { U as UserContextType, A as AuthContextType } from './index-
|
|
2
|
-
import { F as ForwardedTokens, C as Config, S as SessionData, D as DisplayMode } from './types-
|
|
1
|
+
import { U as UserContextType, A as AuthContextType } from './index-DTimUlkB.js';
|
|
2
|
+
import { F as ForwardedTokens, C as Config, S as SessionData, b as EmptyObject, U as User, D as DisplayMode } from './types-HdCjGldB.js';
|
|
3
|
+
import { O as OAuthTokens } from './types-b4c1koXj.js';
|
|
3
4
|
import { ReactNode, RefObject, Dispatch, SetStateAction } from 'react';
|
|
4
5
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
5
6
|
import 'oslo/jwt';
|
|
@@ -28,11 +29,7 @@ type AuthProviderProps = {
|
|
|
28
29
|
onSignOut?: () => void;
|
|
29
30
|
pkceConsumer?: PKCEConsumer;
|
|
30
31
|
modalIframe?: boolean;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
type SessionProviderOutput = SessionData & {
|
|
34
|
-
iframeRef: RefObject<HTMLIFrameElement> | null;
|
|
35
|
-
setAuthResponseUrl: Dispatch<SetStateAction<string | null>>;
|
|
32
|
+
sessionData?: SessionData;
|
|
36
33
|
};
|
|
37
34
|
|
|
38
35
|
type CivicAuthProviderProps = Omit<AuthProviderProps, "pkceConsumer">;
|
|
@@ -43,13 +40,13 @@ declare const CivicNextAuthProvider: ({ children, ...props }: NextCivicAuthProvi
|
|
|
43
40
|
|
|
44
41
|
declare const useUser: <T extends Record<string, unknown> = Record<string, never>>() => UserContextType<T>;
|
|
45
42
|
|
|
46
|
-
declare const useUserCookie: () =>
|
|
43
|
+
declare const useUserCookie: <T extends EmptyObject>() => User<T> | null;
|
|
47
44
|
|
|
48
45
|
declare const useToken: () => TokenContextType;
|
|
49
46
|
|
|
50
47
|
declare const useAuth: () => AuthContextType;
|
|
51
48
|
|
|
52
|
-
declare const useSession: () =>
|
|
49
|
+
declare const useSession: () => SessionData;
|
|
53
50
|
|
|
54
51
|
type ConfigProviderOutput = {
|
|
55
52
|
config: Config;
|
|
@@ -60,6 +57,15 @@ type ConfigProviderOutput = {
|
|
|
60
57
|
|
|
61
58
|
declare const useConfig: () => ConfigProviderOutput;
|
|
62
59
|
|
|
60
|
+
declare const useTokenCookie: (tokenName: OAuthTokens) => string | null;
|
|
61
|
+
|
|
62
|
+
type IframeProviderOutput = {
|
|
63
|
+
iframeRef: RefObject<HTMLIFrameElement> | null;
|
|
64
|
+
setAuthResponseUrl: Dispatch<SetStateAction<string | null>>;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
declare const useIframe: () => IframeProviderOutput;
|
|
68
|
+
|
|
63
69
|
type CivicAuthIframeContainerProps = {
|
|
64
70
|
onClose?: () => void;
|
|
65
71
|
closeOnRedirect?: boolean;
|
|
@@ -84,4 +90,4 @@ declare const NextLogOut: ({ children }: {
|
|
|
84
90
|
children: ReactNode;
|
|
85
91
|
}) => react_jsx_runtime.JSX.Element;
|
|
86
92
|
|
|
87
|
-
export { AuthContextType, CivicAuthIframeContainer, CivicAuthProvider, type CivicAuthProviderProps, CivicNextAuthProvider, type NextCivicAuthProviderProps, NextLogOut, SignInButton, SignOutButton, type TokenContextType, UserButton, UserContextType, useAuth, useConfig, useSession, useToken, useUser, useUserCookie };
|
|
93
|
+
export { AuthContextType, CivicAuthIframeContainer, CivicAuthProvider, type CivicAuthProviderProps, CivicNextAuthProvider, type NextCivicAuthProviderProps, NextLogOut, SignInButton, SignOutButton, type TokenContextType, UserButton, UserContextType, useAuth, useConfig, useIframe, useSession, useToken, useTokenCookie, useUser, useUserCookie };
|