@civic/auth 0.0.1-beta.0 → 0.0.1-beta.10
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/README.md +36 -10
- package/dist/chunk-CRTRMMJ7.js +59 -0
- package/dist/chunk-CRTRMMJ7.js.map +1 -0
- package/dist/chunk-EAANLFR5.mjs +148 -0
- package/dist/chunk-EAANLFR5.mjs.map +1 -0
- package/dist/chunk-EGFTMH5S.mjs +214 -0
- package/dist/chunk-EGFTMH5S.mjs.map +1 -0
- package/dist/chunk-KCSGIIPA.js +214 -0
- package/dist/chunk-KCSGIIPA.js.map +1 -0
- package/dist/chunk-MVO4UZ2A.js +148 -0
- package/dist/chunk-MVO4UZ2A.js.map +1 -0
- package/dist/chunk-PMDIR5XE.mjs +502 -0
- package/dist/chunk-PMDIR5XE.mjs.map +1 -0
- package/dist/chunk-RGHW4PYM.mjs +59 -0
- package/dist/chunk-RGHW4PYM.mjs.map +1 -0
- package/dist/chunk-YNLXRD5L.js +502 -0
- package/dist/chunk-YNLXRD5L.js.map +1 -0
- package/dist/{index-yT0eVchS.d.mts → index-Bfi0hVMZ.d.mts} +14 -8
- package/dist/{index-yT0eVchS.d.ts → index-Bfi0hVMZ.d.ts} +14 -8
- package/dist/index.css +66 -66
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -19
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/nextjs.d.mts +220 -4
- package/dist/nextjs.d.ts +220 -4
- package/dist/nextjs.js +228 -104
- package/dist/nextjs.js.map +1 -1
- package/dist/nextjs.mjs +228 -82
- package/dist/nextjs.mjs.map +1 -1
- package/dist/react.d.mts +60 -24
- package/dist/react.d.ts +60 -24
- package/dist/react.js +759 -895
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +726 -828
- package/dist/react.mjs.map +1 -1
- package/dist/server.d.mts +56 -0
- package/dist/server.d.ts +56 -0
- package/dist/server.js +20 -0
- package/dist/server.js.map +1 -0
- package/dist/server.mjs +20 -0
- package/dist/server.mjs.map +1 -0
- package/package.json +20 -6
package/dist/nextjs.d.ts
CHANGED
|
@@ -1,8 +1,224 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as next_dist_shared_lib_image_config from 'next/dist/shared/lib/image-config';
|
|
2
|
+
import * as next_dist_lib_load_custom_routes from 'next/dist/lib/load-custom-routes';
|
|
3
|
+
import * as next_dist_server_config_shared from 'next/dist/server/config-shared';
|
|
4
|
+
import { NextConfig } from 'next';
|
|
5
|
+
import { U as User } from './index-Bfi0hVMZ.js';
|
|
6
|
+
import { NextRequest, NextResponse } from 'next/server.js';
|
|
7
|
+
import 'oslo/oauth2';
|
|
2
8
|
|
|
3
|
-
|
|
9
|
+
interface CookieConfig {
|
|
10
|
+
secure?: boolean;
|
|
11
|
+
sameSite?: "strict" | "lax" | "none";
|
|
12
|
+
domain?: string;
|
|
13
|
+
path?: string;
|
|
14
|
+
maxAge?: number;
|
|
15
|
+
}
|
|
16
|
+
type AuthConfigWithDefaults = {
|
|
17
|
+
clientId: string;
|
|
18
|
+
oauthServer: string;
|
|
19
|
+
callbackUrl: string;
|
|
4
20
|
loginUrl: string;
|
|
21
|
+
logoutUrl: string;
|
|
22
|
+
appUrl?: string;
|
|
23
|
+
challengeUrl: string;
|
|
24
|
+
include: string[];
|
|
25
|
+
exclude: string[];
|
|
26
|
+
cookies: {
|
|
27
|
+
tokens: CookieConfig;
|
|
28
|
+
user: CookieConfig;
|
|
29
|
+
};
|
|
5
30
|
};
|
|
6
|
-
|
|
31
|
+
type AuthConfig = Partial<AuthConfigWithDefaults>;
|
|
32
|
+
/**
|
|
33
|
+
* Creates a Next.js plugin that handles auth configuration.
|
|
34
|
+
*
|
|
35
|
+
* This is the main configuration point for the auth system.
|
|
36
|
+
* Do not set _civic_auth_* environment variables directly - instead,
|
|
37
|
+
* pass your configuration here:
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```js
|
|
41
|
+
* // next.config.js
|
|
42
|
+
* export default createCivicAuthPlugin({
|
|
43
|
+
* clientId: 'my-client-id',
|
|
44
|
+
* callbackUrl: '/custom/callback',
|
|
45
|
+
* loginUrl: '/custom/login',
|
|
46
|
+
* logoutUrl: '/custom/logout',
|
|
47
|
+
* include: ['/protected/*'],
|
|
48
|
+
* exclude: ['/public/*']
|
|
49
|
+
* })
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* The plugin sets internal environment variables that are used by
|
|
53
|
+
* the auth system. These variables should not be set manually.
|
|
54
|
+
*/
|
|
55
|
+
declare const createCivicAuthPlugin: (clientId: string, authConfig?: AuthConfig) => (nextConfig?: NextConfig) => {
|
|
56
|
+
env: {
|
|
57
|
+
_civic_auth_client_id: string;
|
|
58
|
+
_civic_oauth_server: string;
|
|
59
|
+
_civic_auth_callback_url: string;
|
|
60
|
+
_civic_auth_challenge_url: string;
|
|
61
|
+
_civic_auth_login_url: string;
|
|
62
|
+
_civic_auth_logout_url: string;
|
|
63
|
+
_civic_auth_app_url: string | undefined;
|
|
64
|
+
_civic_auth_includes: string;
|
|
65
|
+
_civic_auth_excludes: string;
|
|
66
|
+
_civic_auth_cookie_config: string;
|
|
67
|
+
};
|
|
68
|
+
exportPathMap?: (defaultMap: next_dist_server_config_shared.ExportPathMap, ctx: {
|
|
69
|
+
dev: boolean;
|
|
70
|
+
dir: string;
|
|
71
|
+
outDir: string | null;
|
|
72
|
+
distDir: string;
|
|
73
|
+
buildId: string;
|
|
74
|
+
}) => Promise<next_dist_server_config_shared.ExportPathMap> | next_dist_server_config_shared.ExportPathMap;
|
|
75
|
+
i18n?: next_dist_server_config_shared.I18NConfig | null;
|
|
76
|
+
eslint?: next_dist_server_config_shared.ESLintConfig;
|
|
77
|
+
typescript?: next_dist_server_config_shared.TypeScriptConfig;
|
|
78
|
+
headers?: () => Promise<next_dist_lib_load_custom_routes.Header[]>;
|
|
79
|
+
rewrites?: () => Promise<next_dist_lib_load_custom_routes.Rewrite[] | {
|
|
80
|
+
beforeFiles: next_dist_lib_load_custom_routes.Rewrite[];
|
|
81
|
+
afterFiles: next_dist_lib_load_custom_routes.Rewrite[];
|
|
82
|
+
fallback: next_dist_lib_load_custom_routes.Rewrite[];
|
|
83
|
+
}>;
|
|
84
|
+
redirects?: () => Promise<next_dist_lib_load_custom_routes.Redirect[]>;
|
|
85
|
+
excludeDefaultMomentLocales?: boolean;
|
|
86
|
+
webpack?: next_dist_server_config_shared.NextJsWebpackConfig | null;
|
|
87
|
+
trailingSlash?: boolean;
|
|
88
|
+
distDir?: string;
|
|
89
|
+
cleanDistDir?: boolean;
|
|
90
|
+
assetPrefix?: string;
|
|
91
|
+
cacheHandler?: string | undefined;
|
|
92
|
+
cacheMaxMemorySize?: number;
|
|
93
|
+
useFileSystemPublicRoutes?: boolean;
|
|
94
|
+
generateBuildId?: () => string | null | Promise<string | null>;
|
|
95
|
+
generateEtags?: boolean;
|
|
96
|
+
pageExtensions?: string[];
|
|
97
|
+
compress?: boolean;
|
|
98
|
+
analyticsId?: string;
|
|
99
|
+
poweredByHeader?: boolean;
|
|
100
|
+
images?: next_dist_shared_lib_image_config.ImageConfig;
|
|
101
|
+
devIndicators?: {
|
|
102
|
+
buildActivity?: boolean;
|
|
103
|
+
buildActivityPosition?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
|
|
104
|
+
};
|
|
105
|
+
onDemandEntries?: {
|
|
106
|
+
maxInactiveAge?: number;
|
|
107
|
+
pagesBufferLength?: number;
|
|
108
|
+
};
|
|
109
|
+
amp?: {
|
|
110
|
+
canonicalBase?: string;
|
|
111
|
+
};
|
|
112
|
+
deploymentId?: string;
|
|
113
|
+
basePath?: string;
|
|
114
|
+
sassOptions?: {
|
|
115
|
+
[key: string]: any;
|
|
116
|
+
};
|
|
117
|
+
productionBrowserSourceMaps?: boolean;
|
|
118
|
+
optimizeFonts?: boolean;
|
|
119
|
+
reactProductionProfiling?: boolean;
|
|
120
|
+
reactStrictMode?: boolean | null;
|
|
121
|
+
publicRuntimeConfig?: {
|
|
122
|
+
[key: string]: any;
|
|
123
|
+
};
|
|
124
|
+
serverRuntimeConfig?: {
|
|
125
|
+
[key: string]: any;
|
|
126
|
+
};
|
|
127
|
+
httpAgentOptions?: {
|
|
128
|
+
keepAlive?: boolean;
|
|
129
|
+
};
|
|
130
|
+
outputFileTracing?: boolean;
|
|
131
|
+
staticPageGenerationTimeout?: number;
|
|
132
|
+
crossOrigin?: "anonymous" | "use-credentials";
|
|
133
|
+
swcMinify?: boolean;
|
|
134
|
+
compiler?: {
|
|
135
|
+
reactRemoveProperties?: boolean | {
|
|
136
|
+
properties?: string[];
|
|
137
|
+
};
|
|
138
|
+
relay?: {
|
|
139
|
+
src: string;
|
|
140
|
+
artifactDirectory?: string;
|
|
141
|
+
language?: "typescript" | "javascript" | "flow";
|
|
142
|
+
eagerEsModules?: boolean;
|
|
143
|
+
};
|
|
144
|
+
removeConsole?: boolean | {
|
|
145
|
+
exclude?: string[];
|
|
146
|
+
};
|
|
147
|
+
styledComponents?: boolean | next_dist_server_config_shared.StyledComponentsConfig;
|
|
148
|
+
emotion?: boolean | next_dist_server_config_shared.EmotionConfig;
|
|
149
|
+
styledJsx?: boolean | {
|
|
150
|
+
useLightningcss?: boolean;
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
output?: "standalone" | "export";
|
|
154
|
+
transpilePackages?: string[];
|
|
155
|
+
skipMiddlewareUrlNormalize?: boolean;
|
|
156
|
+
skipTrailingSlashRedirect?: boolean;
|
|
157
|
+
modularizeImports?: Record<string, {
|
|
158
|
+
transform: string | Record<string, string>;
|
|
159
|
+
preventFullImport?: boolean;
|
|
160
|
+
skipDefaultConversion?: boolean;
|
|
161
|
+
}>;
|
|
162
|
+
logging?: {
|
|
163
|
+
fetches?: {
|
|
164
|
+
fullUrl?: boolean;
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
experimental?: next_dist_server_config_shared.ExperimentalConfig;
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Used on the server-side to get the user object from the cookie
|
|
172
|
+
*/
|
|
173
|
+
|
|
174
|
+
declare const getUser: () => User | null;
|
|
175
|
+
|
|
176
|
+
type Middleware = (request: NextRequest) => Promise<NextResponse> | NextResponse;
|
|
177
|
+
/**
|
|
178
|
+
*
|
|
179
|
+
* Use this when auth is the only middleware you need.
|
|
180
|
+
* Usage:
|
|
181
|
+
*
|
|
182
|
+
* export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();
|
|
183
|
+
*
|
|
184
|
+
*/
|
|
185
|
+
declare const authMiddleware: (authConfig?: Omit<AuthConfigWithDefaults, "clientId">) => (request: NextRequest) => Promise<NextResponse>;
|
|
186
|
+
/**
|
|
187
|
+
* Usage:
|
|
188
|
+
*
|
|
189
|
+
* export default withAuth(async (request) => {
|
|
190
|
+
* console.log('my middleware');
|
|
191
|
+
* return NextResponse.next();
|
|
192
|
+
* })
|
|
193
|
+
*/
|
|
194
|
+
declare function withAuth(middleware: Middleware): (request: NextRequest) => Promise<NextResponse>;
|
|
195
|
+
/**
|
|
196
|
+
* Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)
|
|
197
|
+
*
|
|
198
|
+
* Usage:
|
|
199
|
+
*
|
|
200
|
+
* const withAuth = auth({ loginUrl = '/login' }); // or just auth();
|
|
201
|
+
*
|
|
202
|
+
* export default withAuth(async (request) => {
|
|
203
|
+
* console.log('my middleware');
|
|
204
|
+
* return NextResponse.next();
|
|
205
|
+
* })
|
|
206
|
+
*
|
|
207
|
+
*/
|
|
208
|
+
declare function auth(authConfig?: AuthConfig): (middleware: Middleware) => ((request: NextRequest) => Promise<NextResponse>);
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Creates an authentication handler for Next.js API routes
|
|
212
|
+
*
|
|
213
|
+
* Usage:
|
|
214
|
+
* ```ts
|
|
215
|
+
* // app/api/auth/[...civicauth]/route.ts
|
|
216
|
+
* import { handler } from '@civic/auth/nextjs'
|
|
217
|
+
* export const GET = handler({
|
|
218
|
+
* // optional config overrides
|
|
219
|
+
* })
|
|
220
|
+
* ```
|
|
221
|
+
*/
|
|
222
|
+
declare const handler: (authConfig?: {}) => (request: NextRequest) => Promise<NextResponse>;
|
|
7
223
|
|
|
8
|
-
export {
|
|
224
|
+
export { auth, authMiddleware, createCivicAuthPlugin, getUser, handler, withAuth };
|
package/dist/nextjs.js
CHANGED
|
@@ -1,121 +1,245 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
var
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
var
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
var _chunkMVO4UZ2Ajs = require('./chunk-MVO4UZ2A.js');
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
var _chunkKCSGIIPAjs = require('./chunk-KCSGIIPA.js');
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
var _chunkYNLXRD5Ljs = require('./chunk-YNLXRD5L.js');
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
var _chunkCRTRMMJ7js = require('./chunk-CRTRMMJ7.js');
|
|
23
|
+
|
|
24
|
+
// src/nextjs/cookies.ts
|
|
25
|
+
var _headersjs = require('next/headers.js');
|
|
26
|
+
var clearAuthCookies = () => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
|
|
27
|
+
const cookieStorage = new NextjsCookieStorage();
|
|
28
|
+
_chunkYNLXRD5Ljs.clearTokens.call(void 0, cookieStorage);
|
|
29
|
+
const clientStorage = new NextjsClientStorage();
|
|
30
|
+
const userSession = new (0, _chunkYNLXRD5Ljs.GenericUserSession)(clientStorage);
|
|
31
|
+
userSession.set(null);
|
|
32
|
+
});
|
|
33
|
+
var NextjsCookieStorage = class extends _chunkKCSGIIPAjs.CookieStorage {
|
|
34
|
+
constructor(config = {}) {
|
|
35
|
+
super(_chunkCRTRMMJ7js.__spreadProps.call(void 0, _chunkCRTRMMJ7js.__spreadValues.call(void 0, {}, config), {
|
|
36
|
+
secure: true,
|
|
37
|
+
httpOnly: true
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
40
|
+
get(key) {
|
|
41
|
+
var _a;
|
|
42
|
+
return ((_a = _headersjs.cookies.call(void 0, ).get(key)) == null ? void 0 : _a.value) || null;
|
|
43
|
+
}
|
|
44
|
+
set(key, value) {
|
|
45
|
+
_headersjs.cookies.call(void 0, ).set(key, value, this.settings);
|
|
46
|
+
}
|
|
27
47
|
};
|
|
28
|
-
var
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
48
|
+
var NextjsClientStorage = class extends _chunkKCSGIIPAjs.CookieStorage {
|
|
49
|
+
constructor(config = {}) {
|
|
50
|
+
super(_chunkCRTRMMJ7js.__spreadProps.call(void 0, _chunkCRTRMMJ7js.__spreadValues.call(void 0, {}, config), {
|
|
51
|
+
secure: false,
|
|
52
|
+
httpOnly: false
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
55
|
+
get(key) {
|
|
56
|
+
var _a;
|
|
57
|
+
return ((_a = _headersjs.cookies.call(void 0, ).get(key)) == null ? void 0 : _a.value) || null;
|
|
58
|
+
}
|
|
59
|
+
set(key, value) {
|
|
60
|
+
_headersjs.cookies.call(void 0, ).set(key, value, this.settings);
|
|
33
61
|
}
|
|
34
|
-
return to;
|
|
35
62
|
};
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
} catch (e) {
|
|
43
|
-
reject(e);
|
|
44
|
-
}
|
|
45
|
-
};
|
|
46
|
-
var rejected = (value) => {
|
|
47
|
-
try {
|
|
48
|
-
step(generator.throw(value));
|
|
49
|
-
} catch (e) {
|
|
50
|
-
reject(e);
|
|
51
|
-
}
|
|
52
|
-
};
|
|
53
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
54
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
55
|
-
});
|
|
63
|
+
|
|
64
|
+
// src/nextjs/GetUser.ts
|
|
65
|
+
var getUser2 = () => {
|
|
66
|
+
const clientStorage = new NextjsClientStorage();
|
|
67
|
+
const userSession = new (0, _chunkYNLXRD5Ljs.GenericUserSession)(clientStorage);
|
|
68
|
+
return userSession.get();
|
|
56
69
|
};
|
|
57
70
|
|
|
58
|
-
// src/nextjs/
|
|
59
|
-
var
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
var import_server = require("next/server");
|
|
65
|
-
var import_jwt = require("oslo/jwt");
|
|
66
|
-
var defaults = {
|
|
67
|
-
loginUrl: "/"
|
|
68
|
-
// by default, redirect to the root
|
|
71
|
+
// src/nextjs/middleware.ts
|
|
72
|
+
var _serverjs = require('next/server.js');
|
|
73
|
+
var _picomatch = require('picomatch'); var _picomatch2 = _interopRequireDefault(_picomatch);
|
|
74
|
+
var matchGlob = (pathname, globPattern) => {
|
|
75
|
+
const matches = _picomatch2.default.call(void 0, globPattern);
|
|
76
|
+
return matches(pathname);
|
|
69
77
|
};
|
|
70
|
-
var
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
78
|
+
var matchesGlobs = (pathname, patterns) => patterns.some((pattern) => {
|
|
79
|
+
if (!pattern) return false;
|
|
80
|
+
console.log("matching", {
|
|
81
|
+
pattern,
|
|
82
|
+
pathname,
|
|
83
|
+
match: matchGlob(pathname, pattern)
|
|
84
|
+
});
|
|
85
|
+
return matchGlob(pathname, pattern);
|
|
86
|
+
});
|
|
87
|
+
var applyAuth = (authConfig, request) => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
|
|
88
|
+
const authConfigWithDefaults = _chunkMVO4UZ2Ajs.resolveAuthConfig.call(void 0, authConfig);
|
|
89
|
+
const isAuthenticated = !!request.cookies.get("id_token");
|
|
90
|
+
if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl) {
|
|
91
|
+
console.log("\u2192 Skipping auth check - this is the login URL");
|
|
92
|
+
return void 0;
|
|
93
|
+
}
|
|
94
|
+
if (!matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.include)) {
|
|
95
|
+
console.log("\u2192 Skipping auth check - path not in include patterns");
|
|
96
|
+
return void 0;
|
|
97
|
+
}
|
|
98
|
+
if (matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.exclude)) {
|
|
99
|
+
console.log("\u2192 Skipping auth check - path in exclude patterns");
|
|
100
|
+
return void 0;
|
|
101
|
+
}
|
|
102
|
+
if (!isAuthenticated) {
|
|
103
|
+
console.log("\u2192 No valid token found - redirecting to login");
|
|
104
|
+
const loginUrl = new URL(authConfigWithDefaults.loginUrl, request.url);
|
|
105
|
+
return _serverjs.NextResponse.redirect(loginUrl);
|
|
106
|
+
}
|
|
107
|
+
console.log("\u2192 Auth check passed");
|
|
108
|
+
return void 0;
|
|
109
|
+
});
|
|
110
|
+
var authMiddleware = (authConfig = _chunkMVO4UZ2Ajs.defaultAuthConfig) => (request) => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
|
|
111
|
+
const response = yield applyAuth(authConfig, request);
|
|
112
|
+
if (response) return response;
|
|
113
|
+
return _serverjs.NextResponse.next();
|
|
114
|
+
});
|
|
115
|
+
function withAuth(middleware) {
|
|
116
|
+
return (request) => _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
|
|
117
|
+
const response = yield applyAuth({}, request);
|
|
118
|
+
if (response) return response;
|
|
119
|
+
return middleware(request);
|
|
74
120
|
});
|
|
75
|
-
|
|
76
|
-
|
|
121
|
+
}
|
|
122
|
+
function auth(authConfig = {}) {
|
|
123
|
+
return (middleware) => {
|
|
124
|
+
return (request) => _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
|
|
125
|
+
const response = yield applyAuth(authConfig, request);
|
|
126
|
+
if (response) return response;
|
|
127
|
+
return middleware(request);
|
|
128
|
+
});
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/nextjs/routeHandler.ts
|
|
133
|
+
|
|
134
|
+
var _cachejs = require('next/cache.js');
|
|
135
|
+
var logger = _chunkMVO4UZ2Ajs.loggers.nextjs.handlers.auth;
|
|
136
|
+
var AuthError = class extends Error {
|
|
137
|
+
constructor(message, status = 401) {
|
|
138
|
+
super(message);
|
|
139
|
+
this.status = status;
|
|
140
|
+
this.name = "AuthError";
|
|
77
141
|
}
|
|
78
142
|
};
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
)
|
|
91
|
-
|
|
92
|
-
|
|
143
|
+
function handleChallenge() {
|
|
144
|
+
return _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
|
|
145
|
+
const cookieStorage = new NextjsCookieStorage();
|
|
146
|
+
const pkceProducer = new (0, _chunkYNLXRD5Ljs.GenericPublicClientPKCEProducer)(cookieStorage);
|
|
147
|
+
const challenge = yield pkceProducer.getCodeChallenge();
|
|
148
|
+
return _serverjs.NextResponse.json({ status: "success", challenge });
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
function handleCallback(request, config) {
|
|
152
|
+
return _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
|
|
153
|
+
const tokenExchange = request.nextUrl.searchParams.get("tokenExchange");
|
|
154
|
+
if (!tokenExchange) {
|
|
155
|
+
const response2 = new (0, _serverjs.NextResponse)(`<html></html>`);
|
|
156
|
+
response2.headers.set("Content-Type", "text/html; charset=utf-8");
|
|
157
|
+
return response2;
|
|
158
|
+
}
|
|
159
|
+
const code = request.nextUrl.searchParams.get("code");
|
|
160
|
+
const state = request.nextUrl.searchParams.get("state");
|
|
161
|
+
if (!code || !state) throw new AuthError("Bad parameters", 400);
|
|
162
|
+
const cookieStorage = new NextjsCookieStorage();
|
|
163
|
+
const resolvedConfigs = _chunkMVO4UZ2Ajs.resolveAuthConfig.call(void 0, config);
|
|
164
|
+
const callbackUrl = _chunkMVO4UZ2Ajs.resolveCallbackUrl.call(void 0, resolvedConfigs, request.url);
|
|
165
|
+
try {
|
|
166
|
+
yield _chunkKCSGIIPAjs.resolveOAuthAccessCode.call(void 0, code, state, cookieStorage, _chunkCRTRMMJ7js.__spreadProps.call(void 0, _chunkCRTRMMJ7js.__spreadValues.call(void 0, {}, resolvedConfigs), {
|
|
167
|
+
redirectUrl: callbackUrl
|
|
168
|
+
}));
|
|
169
|
+
} catch (error) {
|
|
170
|
+
logger.error("Token exchange failed:", error);
|
|
171
|
+
throw new AuthError("Failed to authenticate user", 401);
|
|
93
172
|
}
|
|
94
|
-
|
|
95
|
-
|
|
173
|
+
const user = yield _chunkYNLXRD5Ljs.getUser.call(void 0, cookieStorage);
|
|
174
|
+
if (!user) {
|
|
175
|
+
throw new AuthError("Failed to get user info", 401);
|
|
96
176
|
}
|
|
97
|
-
|
|
98
|
-
|
|
177
|
+
const clientStorage = new NextjsClientStorage();
|
|
178
|
+
const userSession = new (0, _chunkYNLXRD5Ljs.GenericUserSession)(clientStorage);
|
|
179
|
+
userSession.set(user);
|
|
180
|
+
const response = new (0, _serverjs.NextResponse)(`<html></html>`);
|
|
181
|
+
response.headers.set("Content-Type", "text/html; charset=utf-8");
|
|
182
|
+
return response;
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
var getAbsoluteRedirectPath = (redirectPath, currentBasePath) => {
|
|
186
|
+
if (/^(https?:\/\/|www\.).+/i.test(redirectPath)) {
|
|
187
|
+
return redirectPath;
|
|
188
|
+
}
|
|
189
|
+
return new URL(redirectPath, currentBasePath).href;
|
|
190
|
+
};
|
|
191
|
+
function handleLogout(request, config) {
|
|
192
|
+
return _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
|
|
193
|
+
var _a;
|
|
194
|
+
const resolvedConfigs = _chunkMVO4UZ2Ajs.resolveAuthConfig.call(void 0, config);
|
|
195
|
+
const defaultRedirectPath = (_a = resolvedConfigs.loginUrl) != null ? _a : "/";
|
|
196
|
+
const redirectTarget = new URL(request.url).searchParams.get("redirect") || defaultRedirectPath;
|
|
197
|
+
const isAbsoluteRedirect = /^(https?:\/\/|www\.).+/i.test(redirectTarget);
|
|
198
|
+
const finalRedirectUrl = getAbsoluteRedirectPath(
|
|
199
|
+
redirectTarget,
|
|
200
|
+
new URL(request.url).origin
|
|
201
|
+
);
|
|
202
|
+
const response = _serverjs.NextResponse.redirect(finalRedirectUrl);
|
|
203
|
+
clearAuthCookies();
|
|
204
|
+
try {
|
|
205
|
+
_cachejs.revalidatePath.call(void 0, isAbsoluteRedirect ? finalRedirectUrl : redirectTarget);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
logger.warn("Failed to revalidate path after logout:", error);
|
|
99
208
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
209
|
+
return response;
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
var handler = (authConfig = {}) => (request) => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
|
|
213
|
+
const config = _chunkMVO4UZ2Ajs.resolveAuthConfig.call(void 0, authConfig);
|
|
214
|
+
try {
|
|
215
|
+
const pathname = request.nextUrl.pathname;
|
|
216
|
+
const pathSegments = pathname.split("/");
|
|
217
|
+
const lastSegment = pathSegments[pathSegments.length - 1];
|
|
218
|
+
switch (lastSegment) {
|
|
219
|
+
case "challenge":
|
|
220
|
+
return yield handleChallenge();
|
|
221
|
+
case "callback":
|
|
222
|
+
return yield handleCallback(request, config);
|
|
223
|
+
case "logout":
|
|
224
|
+
return yield handleLogout(request, config);
|
|
225
|
+
default:
|
|
226
|
+
throw new AuthError(`Invalid auth route: ${pathname}`, 404);
|
|
103
227
|
}
|
|
104
|
-
const requestHeaders = new Headers(req.headers);
|
|
105
|
-
requestHeaders.set("x-user-id", token.id);
|
|
106
|
-
return import_server.NextResponse.next({
|
|
107
|
-
request: __spreadProps(__spreadValues({}, req), {
|
|
108
|
-
// New request headers
|
|
109
|
-
headers: requestHeaders
|
|
110
|
-
})
|
|
111
|
-
});
|
|
112
228
|
} catch (error) {
|
|
113
|
-
|
|
114
|
-
|
|
229
|
+
logger.error("Auth handler error:", error);
|
|
230
|
+
const status = error instanceof AuthError ? error.status : 500;
|
|
231
|
+
const message = error instanceof Error ? error.message : "Authentication failed";
|
|
232
|
+
const response = _serverjs.NextResponse.json({ error: message }, { status });
|
|
233
|
+
clearAuthCookies();
|
|
234
|
+
return response;
|
|
115
235
|
}
|
|
116
236
|
});
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
exports.auth = auth; exports.authMiddleware = authMiddleware; exports.createCivicAuthPlugin = _chunkMVO4UZ2Ajs.createCivicAuthPlugin; exports.getUser = getUser2; exports.handler = handler; exports.withAuth = withAuth;
|
|
121
245
|
//# sourceMappingURL=nextjs.js.map
|
package/dist/nextjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/nextjs/index.ts"],"sourcesContent":["import { NextRequest, NextResponse } from \"next/server\";\n\nimport { type User } from \"@/types\";\n\nimport { validateJWT } from \"oslo/jwt\";\n\ntype AuthMiddlewareConfig = {\n loginUrl: string;\n};\n\nconst defaults = {\n loginUrl: \"/\", // by default, redirect to the root\n};\n\n// redirect if we are not already there, to avoid loops.\nconst redirectNoLoops = (newUrl: string, req: NextRequest) => {\n const redirectUrl = new URL(newUrl, req.url);\n // Append original query parameters to the new URL\n req.nextUrl.searchParams.forEach((value, key) => {\n redirectUrl.searchParams.append(key, value);\n });\n\n if (redirectUrl.toString() !== req.url) {\n return NextResponse.redirect(redirectUrl);\n }\n};\n\nconst authMiddleware =\n (config: AuthMiddlewareConfig = defaults) =>\n async (req: NextRequest) => {\n // Retrieve the id_token from the cookies\n const idToken = req.cookies.get(\"id_token\")?.value;\n\n if (!idToken) {\n return redirectNoLoops(config.loginUrl, req); // Redirect to login if no token is found\n }\n\n try {\n const jwt = await validateJWT(\n \"HS256\",\n Buffer.from(process.env.LOGIN_JWT_SECRET!),\n idToken,\n );\n\n // Check if the JWT is malformed\n if (!jwt) {\n return NextResponse.json(\"Malformed token\", { status: 400 });\n }\n\n // Check if the JWT is missing the expiration\n if (!jwt.expiresAt) {\n return NextResponse.json(\"Token missing expiration\", { status: 400 });\n }\n\n // Check expiration time\n if (jwt.expiresAt.getTime() < Date.now()) {\n return redirectNoLoops(config.loginUrl, req); // Redirect to login the token has expired\n }\n\n const token = jwt.payload as User;\n\n if (!token.id) {\n return NextResponse.json(\"Unauthorized\", { status: 401 });\n }\n\n // Store the email claim in the request headers\n const requestHeaders = new Headers(req.headers);\n\n requestHeaders.set(\"x-user-id\", token.id);\n\n // Continue to the next middleware or route handler\n return NextResponse.next({\n request: {\n ...req,\n\n // New request headers\n headers: requestHeaders,\n },\n });\n } catch (error) {\n console.error(\"Failed to decode id_token:\", error);\n\n return redirectNoLoops(config.loginUrl, req); // Redirect to login on error\n }\n };\n\nexport type { AuthMiddlewareConfig };\n\nexport { authMiddleware };\n"],"mappings":";;;;;;;;;;;;;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AI,OAAO;AAE9C,mBAAe,IAAI,aAAa,MAAM,EAAE;AAGxC,WAAO,2BAAa,KAAK;AAAA,MACvB,SAAS,iCACJ,MADI;AAAA;AAAA,QAIP,SAAS;AAAA,MACX;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AACd,YAAQ,MAAM,8BAA8B,KAAK;AAEjD,WAAO,gBAAgB,OAAO,UAAU,GAAG;AAAA,EAC7C;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["/Users/kevincolgan/code/civic-auth/packages/civic-auth-client/dist/nextjs.js","../src/nextjs/cookies.ts","../src/nextjs/GetUser.ts","../src/nextjs/middleware.ts","../src/nextjs/routeHandler.ts"],"names":["getUser","NextResponse","response"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACA;AACF,sDAA4B;AAC5B;AACE;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACA;AACA;AACF,sDAA4B;AAC5B;AACA;ACnBA,4CAAwB;AA4ExB,IAAM,iBAAA,EAAmB,CAAA,EAAA,GAAY,sCAAA,KAAA,CAAA,EAAA,IAAA,EAAA,QAAA,EAAA,CAAA,EAAA;AAEnC,EAAA,MAAM,cAAA,EAAgB,IAAI,mBAAA,CAAoB,CAAA;AAC9C,EAAA,0CAAA,aAAyB,CAAA;AAGzB,EAAA,MAAM,cAAA,EAAgB,IAAI,mBAAA,CAAoB,CAAA;AAC9C,EAAA,MAAM,YAAA,EAAc,IAAI,wCAAA,CAAmB,aAAa,CAAA;AACxD,EAAA,WAAA,CAAY,GAAA,CAAI,IAAI,CAAA;AACtB,CAAA,CAAA;AAEA,IAAM,oBAAA,EAAN,MAAA,QAAkC,+BAAc;AAAA,EAC9C,WAAA,CAAY,OAAA,EAAyC,CAAC,CAAA,EAAG;AACvD,IAAA,KAAA,CAAM,4CAAA,6CAAA,CAAA,CAAA,EACD,MAAA,CAAA,EADC;AAAA,MAEJ,MAAA,EAAQ,IAAA;AAA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AQ,WAAA,EAAa;AAAA,MACnB,KAAK,WAAA;AACH,QAAA,OAAO,MAAM,eAAA,CAAgB,CAAA;AAAA,MAC/B,KAAK,UAAA;AACH,QAAA,OAAO,MAAM,cAAA,CAAe,OAAA,EAAS,MAAM,CAAA;AAAA,MAC7C,KAAK,QAAA;AACH,QAAA,OAAO,MAAM,YAAA,CAAa,OAAA,EAAS,MAAM,CAAA;AAAA,MAC3C,OAAA;AACE,QAAA,MAAM,IAAI,SAAA,CAAU,CAAA,oBAAA,EAAuB,QAAQ,CAAA,CAAA;AACvD,IAAA;AACc,EAAA;AAC2B,IAAA;AAES,IAAA;AAEjB,IAAA;AAEsB,IAAA;AAEtC,IAAA;AACV,IAAA;AACT,EAAA;AACF;AJ0D0D;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/kevincolgan/code/civic-auth/packages/civic-auth-client/dist/nextjs.js","sourcesContent":[null,"import { SessionData, UnknownObject, User } from \"@/types\";\nimport { NextResponse } from \"next/server\";\nimport { AuthConfig } from \"@/nextjs/config\";\nimport { CookieStorage, CookieStorageSettings } from \"@/server\";\nimport { cookies } from \"next/headers.js\";\nimport { GenericUserSession } from \"@/shared/UserSession\";\nimport { clearTokens } from \"@/shared/util\";\n\n/**\n * Creates HTTP-only cookies for authentication tokens\n */\nconst createTokenCookies = (\n response: NextResponse,\n sessionData: SessionData,\n config: AuthConfig,\n) => {\n const maxAge = sessionData.expiresIn ?? 3600;\n const cookieOptions = {\n ...config.cookies?.tokens,\n maxAge,\n };\n\n if (sessionData.accessToken) {\n response.cookies.set(\"access_token\", sessionData.accessToken, {\n ...cookieOptions,\n httpOnly: true,\n });\n }\n\n if (sessionData.idToken) {\n response.cookies.set(\"id_token\", sessionData.idToken, {\n ...cookieOptions,\n httpOnly: true,\n });\n }\n\n if (sessionData.refreshToken) {\n response.cookies.set(\"refresh_token\", sessionData.refreshToken, {\n ...cookieOptions,\n httpOnly: true,\n });\n }\n};\n\n/**\n * Creates a client-readable cookie with user info\n */\nconst createUserInfoCookie = (\n response: NextResponse,\n user: User<UnknownObject> | null,\n sessionData: SessionData,\n config: AuthConfig,\n) => {\n if (!user) {\n response.cookies.set(\"user\", \"\", {\n ...config.cookies?.user,\n maxAge: 0,\n });\n return;\n }\n const maxAge = sessionData.expiresIn ?? 3600;\n\n // TODO select fields to include in the user cookie\n const frontendUser = {\n ...user,\n };\n\n // TODO make call to get user info from the\n // auth server /userinfo endpoint when it's available\n // then add to the default claims above\n\n response.cookies.set(\"user\", JSON.stringify(frontendUser), {\n ...config.cookies?.user,\n maxAge,\n });\n};\n\n/**\n * Clears all authentication cookies\n */\nconst clearAuthCookies = async () => {\n // clear session, and tokens\n const cookieStorage = new NextjsCookieStorage();\n clearTokens(cookieStorage);\n\n // clear user\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n userSession.set(null);\n};\n\nclass NextjsCookieStorage extends CookieStorage {\n constructor(config: Partial<CookieStorageSettings> = {}) {\n super({\n ...config,\n secure: true,\n httpOnly: true,\n });\n }\n\n get(key: string): string | null {\n return cookies().get(key)?.value || null;\n }\n\n set(key: string, value: string): void {\n cookies().set(key, value, this.settings);\n }\n}\n\nclass NextjsClientStorage extends CookieStorage {\n constructor(config: Partial<CookieStorageSettings> = {}) {\n super({\n ...config,\n secure: false,\n httpOnly: false,\n });\n }\n\n get(key: string): string | null {\n return cookies().get(key)?.value || null;\n }\n\n set(key: string, value: string): void {\n cookies().set(key, value, this.settings);\n }\n}\n\nexport {\n createTokenCookies,\n createUserInfoCookie,\n clearAuthCookies,\n NextjsCookieStorage,\n NextjsClientStorage,\n};\n","/**\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\";\n\nexport const getUser = (): User | null => {\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n return userSession.get();\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\";\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 const tokenExchange = request.nextUrl.searchParams.get(\"tokenExchange\");\n // if the client hasn't request token exchange, return an empty HTML response\n // the next call should include the tokenExchange query parameter from the same-domain\n if (!tokenExchange) {\n const response = new NextResponse(`<html></html>`);\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\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 const callbackUrl = resolveCallbackUrl(resolvedConfigs, request.url);\n\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\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"]}
|