@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.
Files changed (45) hide show
  1. package/README.md +36 -10
  2. package/dist/chunk-CRTRMMJ7.js +59 -0
  3. package/dist/chunk-CRTRMMJ7.js.map +1 -0
  4. package/dist/chunk-EAANLFR5.mjs +148 -0
  5. package/dist/chunk-EAANLFR5.mjs.map +1 -0
  6. package/dist/chunk-EGFTMH5S.mjs +214 -0
  7. package/dist/chunk-EGFTMH5S.mjs.map +1 -0
  8. package/dist/chunk-KCSGIIPA.js +214 -0
  9. package/dist/chunk-KCSGIIPA.js.map +1 -0
  10. package/dist/chunk-MVO4UZ2A.js +148 -0
  11. package/dist/chunk-MVO4UZ2A.js.map +1 -0
  12. package/dist/chunk-PMDIR5XE.mjs +502 -0
  13. package/dist/chunk-PMDIR5XE.mjs.map +1 -0
  14. package/dist/chunk-RGHW4PYM.mjs +59 -0
  15. package/dist/chunk-RGHW4PYM.mjs.map +1 -0
  16. package/dist/chunk-YNLXRD5L.js +502 -0
  17. package/dist/chunk-YNLXRD5L.js.map +1 -0
  18. package/dist/{index-yT0eVchS.d.mts → index-Bfi0hVMZ.d.mts} +14 -8
  19. package/dist/{index-yT0eVchS.d.ts → index-Bfi0hVMZ.d.ts} +14 -8
  20. package/dist/index.css +66 -66
  21. package/dist/index.css.map +1 -1
  22. package/dist/index.d.mts +2 -2
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +1 -19
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +1 -1
  27. package/dist/nextjs.d.mts +220 -4
  28. package/dist/nextjs.d.ts +220 -4
  29. package/dist/nextjs.js +228 -104
  30. package/dist/nextjs.js.map +1 -1
  31. package/dist/nextjs.mjs +228 -82
  32. package/dist/nextjs.mjs.map +1 -1
  33. package/dist/react.d.mts +60 -24
  34. package/dist/react.d.ts +60 -24
  35. package/dist/react.js +759 -895
  36. package/dist/react.js.map +1 -1
  37. package/dist/react.mjs +726 -828
  38. package/dist/react.mjs.map +1 -1
  39. package/dist/server.d.mts +56 -0
  40. package/dist/server.d.ts +56 -0
  41. package/dist/server.js +20 -0
  42. package/dist/server.js.map +1 -0
  43. package/dist/server.mjs +20 -0
  44. package/dist/server.mjs.map +1 -0
  45. package/package.json +20 -6
package/dist/nextjs.mjs CHANGED
@@ -1,99 +1,245 @@
1
- 'use client'
2
- var __defProp = Object.defineProperty;
3
- var __defProps = Object.defineProperties;
4
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __spreadValues = (a, b) => {
10
- for (var prop in b || (b = {}))
11
- if (__hasOwnProp.call(b, prop))
12
- __defNormalProp(a, prop, b[prop]);
13
- if (__getOwnPropSymbols)
14
- for (var prop of __getOwnPropSymbols(b)) {
15
- if (__propIsEnum.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- }
18
- return a;
1
+ import {
2
+ createCivicAuthPlugin,
3
+ defaultAuthConfig,
4
+ loggers,
5
+ resolveAuthConfig,
6
+ resolveCallbackUrl
7
+ } from "./chunk-EAANLFR5.mjs";
8
+ import {
9
+ CookieStorage,
10
+ resolveOAuthAccessCode
11
+ } from "./chunk-EGFTMH5S.mjs";
12
+ import {
13
+ GenericPublicClientPKCEProducer,
14
+ GenericUserSession,
15
+ clearTokens,
16
+ getUser
17
+ } from "./chunk-PMDIR5XE.mjs";
18
+ import {
19
+ __async,
20
+ __spreadProps,
21
+ __spreadValues
22
+ } from "./chunk-RGHW4PYM.mjs";
23
+
24
+ // src/nextjs/cookies.ts
25
+ import { cookies } from "next/headers.js";
26
+ var clearAuthCookies = () => __async(void 0, null, function* () {
27
+ const cookieStorage = new NextjsCookieStorage();
28
+ clearTokens(cookieStorage);
29
+ const clientStorage = new NextjsClientStorage();
30
+ const userSession = new GenericUserSession(clientStorage);
31
+ userSession.set(null);
32
+ });
33
+ var NextjsCookieStorage = class extends CookieStorage {
34
+ constructor(config = {}) {
35
+ super(__spreadProps(__spreadValues({}, config), {
36
+ secure: true,
37
+ httpOnly: true
38
+ }));
39
+ }
40
+ get(key) {
41
+ var _a;
42
+ return ((_a = cookies().get(key)) == null ? void 0 : _a.value) || null;
43
+ }
44
+ set(key, value) {
45
+ cookies().set(key, value, this.settings);
46
+ }
19
47
  };
20
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
- var __async = (__this, __arguments, generator) => {
22
- return new Promise((resolve, reject) => {
23
- var fulfilled = (value) => {
24
- try {
25
- step(generator.next(value));
26
- } catch (e) {
27
- reject(e);
28
- }
29
- };
30
- var rejected = (value) => {
31
- try {
32
- step(generator.throw(value));
33
- } catch (e) {
34
- reject(e);
35
- }
36
- };
37
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
38
- step((generator = generator.apply(__this, __arguments)).next());
39
- });
48
+ var NextjsClientStorage = class extends CookieStorage {
49
+ constructor(config = {}) {
50
+ super(__spreadProps(__spreadValues({}, config), {
51
+ secure: false,
52
+ httpOnly: false
53
+ }));
54
+ }
55
+ get(key) {
56
+ var _a;
57
+ return ((_a = cookies().get(key)) == null ? void 0 : _a.value) || null;
58
+ }
59
+ set(key, value) {
60
+ cookies().set(key, value, this.settings);
61
+ }
62
+ };
63
+
64
+ // src/nextjs/GetUser.ts
65
+ var getUser2 = () => {
66
+ const clientStorage = new NextjsClientStorage();
67
+ const userSession = new GenericUserSession(clientStorage);
68
+ return userSession.get();
40
69
  };
41
70
 
42
- // src/nextjs/index.ts
43
- import { NextResponse } from "next/server";
44
- import { validateJWT } from "oslo/jwt";
45
- var defaults = {
46
- loginUrl: "/"
47
- // by default, redirect to the root
71
+ // src/nextjs/middleware.ts
72
+ import { NextResponse } from "next/server.js";
73
+ import picomatch from "picomatch";
74
+ var matchGlob = (pathname, globPattern) => {
75
+ const matches = picomatch(globPattern);
76
+ return matches(pathname);
48
77
  };
49
- var redirectNoLoops = (newUrl, req) => {
50
- const redirectUrl = new URL(newUrl, req.url);
51
- req.nextUrl.searchParams.forEach((value, key) => {
52
- redirectUrl.searchParams.append(key, value);
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)
53
84
  });
54
- if (redirectUrl.toString() !== req.url) {
55
- return NextResponse.redirect(redirectUrl);
85
+ return matchGlob(pathname, pattern);
86
+ });
87
+ var applyAuth = (authConfig, request) => __async(void 0, null, function* () {
88
+ const authConfigWithDefaults = resolveAuthConfig(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;
56
93
  }
57
- };
58
- var authMiddleware = (config = defaults) => (req) => __async(void 0, null, function* () {
59
- var _a;
60
- const idToken = (_a = req.cookies.get("id_token")) == null ? void 0 : _a.value;
61
- if (!idToken) {
62
- return redirectNoLoops(config.loginUrl, req);
94
+ if (!matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.include)) {
95
+ console.log("\u2192 Skipping auth check - path not in include patterns");
96
+ return void 0;
63
97
  }
64
- try {
65
- const jwt = yield validateJWT(
66
- "HS256",
67
- Buffer.from(process.env.LOGIN_JWT_SECRET),
68
- idToken
69
- );
70
- if (!jwt) {
71
- return NextResponse.json("Malformed token", { status: 400 });
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 NextResponse.redirect(loginUrl);
106
+ }
107
+ console.log("\u2192 Auth check passed");
108
+ return void 0;
109
+ });
110
+ var authMiddleware = (authConfig = defaultAuthConfig) => (request) => __async(void 0, null, function* () {
111
+ const response = yield applyAuth(authConfig, request);
112
+ if (response) return response;
113
+ return NextResponse.next();
114
+ });
115
+ function withAuth(middleware) {
116
+ return (request) => __async(this, null, function* () {
117
+ const response = yield applyAuth({}, request);
118
+ if (response) return response;
119
+ return middleware(request);
120
+ });
121
+ }
122
+ function auth(authConfig = {}) {
123
+ return (middleware) => {
124
+ return (request) => __async(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
+ import { NextResponse as NextResponse2 } from "next/server.js";
134
+ import { revalidatePath } from "next/cache.js";
135
+ var logger = 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";
141
+ }
142
+ };
143
+ function handleChallenge() {
144
+ return __async(this, null, function* () {
145
+ const cookieStorage = new NextjsCookieStorage();
146
+ const pkceProducer = new GenericPublicClientPKCEProducer(cookieStorage);
147
+ const challenge = yield pkceProducer.getCodeChallenge();
148
+ return NextResponse2.json({ status: "success", challenge });
149
+ });
150
+ }
151
+ function handleCallback(request, config) {
152
+ return __async(this, null, function* () {
153
+ const tokenExchange = request.nextUrl.searchParams.get("tokenExchange");
154
+ if (!tokenExchange) {
155
+ const response2 = new NextResponse2(`<html></html>`);
156
+ response2.headers.set("Content-Type", "text/html; charset=utf-8");
157
+ return response2;
72
158
  }
73
- if (!jwt.expiresAt) {
74
- return NextResponse.json("Token missing expiration", { status: 400 });
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 = resolveAuthConfig(config);
164
+ const callbackUrl = resolveCallbackUrl(resolvedConfigs, request.url);
165
+ try {
166
+ yield resolveOAuthAccessCode(code, state, cookieStorage, __spreadProps(__spreadValues({}, resolvedConfigs), {
167
+ redirectUrl: callbackUrl
168
+ }));
169
+ } catch (error) {
170
+ logger.error("Token exchange failed:", error);
171
+ throw new AuthError("Failed to authenticate user", 401);
75
172
  }
76
- if (jwt.expiresAt.getTime() < Date.now()) {
77
- return redirectNoLoops(config.loginUrl, req);
173
+ const user = yield getUser(cookieStorage);
174
+ if (!user) {
175
+ throw new AuthError("Failed to get user info", 401);
78
176
  }
79
- const token = jwt.payload;
80
- if (!token.id) {
81
- return NextResponse.json("Unauthorized", { status: 401 });
177
+ const clientStorage = new NextjsClientStorage();
178
+ const userSession = new GenericUserSession(clientStorage);
179
+ userSession.set(user);
180
+ const response = new NextResponse2(`<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 __async(this, null, function* () {
193
+ var _a;
194
+ const resolvedConfigs = resolveAuthConfig(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 = NextResponse2.redirect(finalRedirectUrl);
203
+ clearAuthCookies();
204
+ try {
205
+ revalidatePath(isAbsoluteRedirect ? finalRedirectUrl : redirectTarget);
206
+ } catch (error) {
207
+ logger.warn("Failed to revalidate path after logout:", error);
208
+ }
209
+ return response;
210
+ });
211
+ }
212
+ var handler = (authConfig = {}) => (request) => __async(void 0, null, function* () {
213
+ const config = resolveAuthConfig(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);
82
227
  }
83
- const requestHeaders = new Headers(req.headers);
84
- requestHeaders.set("x-user-id", token.id);
85
- return NextResponse.next({
86
- request: __spreadProps(__spreadValues({}, req), {
87
- // New request headers
88
- headers: requestHeaders
89
- })
90
- });
91
228
  } catch (error) {
92
- console.error("Failed to decode id_token:", error);
93
- return redirectNoLoops(config.loginUrl, req);
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 = NextResponse2.json({ error: message }, { status });
233
+ clearAuthCookies();
234
+ return response;
94
235
  }
95
236
  });
96
237
  export {
97
- authMiddleware
238
+ auth,
239
+ authMiddleware,
240
+ createCivicAuthPlugin,
241
+ getUser2 as getUser,
242
+ handler,
243
+ withAuth
98
244
  };
99
245
  //# sourceMappingURL=nextjs.mjs.map
@@ -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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAsB,oBAAoB;AAI1C,SAAS,mBAAmB;AAM5B,IAAM,WAAW;AAAA,EACf,UAAU;AAAA;AACZ;AAGA,IAAM,kBAAkB,CAAC,QAAg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AA8B,KAAK;AAEjD,WAAO,gBAAgB,OAAO,UAAU,GAAG;AAAA,EAC7C;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/nextjs/cookies.ts","../src/nextjs/GetUser.ts","../src/nextjs/middleware.ts","../src/nextjs/routeHandler.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,eAAe;AA4ExB,IAAM,mBAAmB,MAAY;AAEnC,QAAM,gBA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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,7 +1,8 @@
1
- import { D as DisplayMode, C as Config, U as User, F as ForwardedTokens, S as SessionData } from './index-yT0eVchS.mjs';
2
1
  import { JWT } from 'oslo/jwt';
3
- import { ReactNode } from 'react';
2
+ import { D as DisplayMode, U as User, F as ForwardedTokens, C as Config, S as SessionData, a as UnknownObject } from './index-Bfi0hVMZ.mjs';
3
+ import { ReactNode, RefObject, Dispatch, SetStateAction } from 'react';
4
4
  import * as react_jsx_runtime from 'react/jsx-runtime';
5
+ import 'oslo/oauth2';
5
6
 
6
7
  type AuthContextType = {
7
8
  signIn: (displayMode?: DisplayMode) => Promise<void>;
@@ -10,22 +11,10 @@ type AuthContextType = {
10
11
  error: Error | null;
11
12
  signOut: () => Promise<void>;
12
13
  };
13
- type AuthProviderProps = {
14
- children: ReactNode;
15
- clientId: string;
16
- redirectUrl?: string;
17
- nonce?: string;
18
- config?: Config;
19
- onSignIn?: (error?: Error) => void;
20
- onSignOut?: () => void;
21
- };
22
14
 
23
- type UserContextType<T extends Record<string, unknown> & JWT["payload"] = Record<string, unknown> & JWT["payload"]> = {
15
+ type UserContextType$1<T extends Record<string, unknown> & JWT["payload"] = Record<string, unknown> & JWT["payload"]> = {
24
16
  user: User<T> | null;
25
- isLoading: boolean;
26
- error: Error | null;
27
- refetch: () => void;
28
- } & AuthContextType;
17
+ } & Omit<AuthContextType, "isAuthenticated">;
29
18
 
30
19
  type TokenContextType = {
31
20
  accessToken: string | null;
@@ -36,31 +25,78 @@ type TokenContextType = {
36
25
  error: Error | null;
37
26
  };
38
27
 
39
- type ParamsProviderProps = {
28
+ interface PKCEConsumer {
29
+ getCodeChallenge(): Promise<string>;
30
+ }
31
+
32
+ type AuthProviderProps = {
40
33
  children: ReactNode;
41
34
  clientId: string;
42
35
  redirectUrl?: string;
43
36
  nonce?: string;
44
37
  config?: Config;
38
+ onSignIn?: (error?: Error) => void;
39
+ onSignOut?: () => void;
40
+ pkceConsumer?: PKCEConsumer;
41
+ modalIframe?: boolean;
42
+ };
43
+
44
+ type SessionProviderOutput = SessionData & {
45
+ iframeRef: RefObject<HTMLIFrameElement> | null;
46
+ setAuthResponseUrl: Dispatch<SetStateAction<string | null>>;
45
47
  };
46
- type ParamsContextType = Omit<ParamsProviderProps, "children">;
47
48
 
48
- type CivicProviderProps = AuthProviderProps;
49
- declare const CivicProvider: ({ children, ...props }: CivicProviderProps) => react_jsx_runtime.JSX.Element;
49
+ type CivicAuthProviderProps = Omit<AuthProviderProps, "pkceConsumer">;
50
+ declare const CivicAuthProvider: ({ children, ...props }: CivicAuthProviderProps) => react_jsx_runtime.JSX.Element;
50
51
 
51
- declare const useUser: <T extends Record<string, unknown> = Record<string, never>>() => UserContextType<T>;
52
+ type UserContextType = {
53
+ user: User<UnknownObject> | null;
54
+ };
55
+ type NextCivicAuthProviderProps = Omit<AuthProviderProps, "clientId">;
56
+ declare const CivicNextAuthProvider: ({ children, ...props }: NextCivicAuthProviderProps) => react_jsx_runtime.JSX.Element;
57
+ declare const useNextUser: () => UserContextType;
58
+
59
+ declare const useUser: <T extends Record<string, unknown> = Record<string, never>>() => UserContextType$1<T>;
60
+
61
+ declare const useUserCookie: () => any;
52
62
 
53
63
  declare const useToken: () => TokenContextType;
54
64
 
55
65
  declare const useAuth: () => AuthContextType;
56
66
 
57
- declare const useParams: () => ParamsContextType;
67
+ declare const useSession: () => SessionProviderOutput;
68
+
69
+ type ConfigProviderOutput = {
70
+ config: Config;
71
+ redirectUrl: string;
72
+ modalIframe: boolean;
73
+ serverTokenExchange: boolean;
74
+ };
58
75
 
59
- declare const useSession: () => SessionData;
76
+ declare const useConfig: () => ConfigProviderOutput;
77
+
78
+ type CivicAuthIframeContainerProps = {
79
+ onClose?: () => void;
80
+ closeOnRedirect?: boolean;
81
+ };
82
+ declare const CivicAuthIframeContainer: ({ onClose, closeOnRedirect, }: CivicAuthIframeContainerProps) => react_jsx_runtime.JSX.Element;
60
83
 
61
84
  declare const UserButton: ({ displayMode, className, }: {
62
85
  displayMode?: DisplayMode;
63
86
  className?: string;
64
87
  }) => react_jsx_runtime.JSX.Element;
65
88
 
66
- export { type AuthContextType, CivicProvider, type ParamsContextType, type TokenContextType, UserButton, type UserContextType, useAuth, useParams, useSession, useToken, useUser };
89
+ declare const SignInButton: ({ displayMode, className, }: {
90
+ displayMode?: DisplayMode;
91
+ className?: string;
92
+ }) => react_jsx_runtime.JSX.Element;
93
+
94
+ declare const SignOutButton: ({ className }: {
95
+ className?: string;
96
+ }) => react_jsx_runtime.JSX.Element;
97
+
98
+ declare const NextLogOut: ({ children }: {
99
+ children: ReactNode;
100
+ }) => react_jsx_runtime.JSX.Element;
101
+
102
+ export { type AuthContextType, CivicAuthIframeContainer, CivicAuthProvider, type CivicAuthProviderProps, CivicNextAuthProvider, type NextCivicAuthProviderProps, NextLogOut, SignInButton, SignOutButton, type TokenContextType, UserButton, type UserContextType$1 as UserContextType, useAuth, useConfig, useNextUser, useSession, useToken, useUser, useUserCookie };
package/dist/react.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { D as DisplayMode, C as Config, U as User, F as ForwardedTokens, S as SessionData } from './index-yT0eVchS.js';
2
1
  import { JWT } from 'oslo/jwt';
3
- import { ReactNode } from 'react';
2
+ import { D as DisplayMode, U as User, F as ForwardedTokens, C as Config, S as SessionData, a as UnknownObject } from './index-Bfi0hVMZ.js';
3
+ import { ReactNode, RefObject, Dispatch, SetStateAction } from 'react';
4
4
  import * as react_jsx_runtime from 'react/jsx-runtime';
5
+ import 'oslo/oauth2';
5
6
 
6
7
  type AuthContextType = {
7
8
  signIn: (displayMode?: DisplayMode) => Promise<void>;
@@ -10,22 +11,10 @@ type AuthContextType = {
10
11
  error: Error | null;
11
12
  signOut: () => Promise<void>;
12
13
  };
13
- type AuthProviderProps = {
14
- children: ReactNode;
15
- clientId: string;
16
- redirectUrl?: string;
17
- nonce?: string;
18
- config?: Config;
19
- onSignIn?: (error?: Error) => void;
20
- onSignOut?: () => void;
21
- };
22
14
 
23
- type UserContextType<T extends Record<string, unknown> & JWT["payload"] = Record<string, unknown> & JWT["payload"]> = {
15
+ type UserContextType$1<T extends Record<string, unknown> & JWT["payload"] = Record<string, unknown> & JWT["payload"]> = {
24
16
  user: User<T> | null;
25
- isLoading: boolean;
26
- error: Error | null;
27
- refetch: () => void;
28
- } & AuthContextType;
17
+ } & Omit<AuthContextType, "isAuthenticated">;
29
18
 
30
19
  type TokenContextType = {
31
20
  accessToken: string | null;
@@ -36,31 +25,78 @@ type TokenContextType = {
36
25
  error: Error | null;
37
26
  };
38
27
 
39
- type ParamsProviderProps = {
28
+ interface PKCEConsumer {
29
+ getCodeChallenge(): Promise<string>;
30
+ }
31
+
32
+ type AuthProviderProps = {
40
33
  children: ReactNode;
41
34
  clientId: string;
42
35
  redirectUrl?: string;
43
36
  nonce?: string;
44
37
  config?: Config;
38
+ onSignIn?: (error?: Error) => void;
39
+ onSignOut?: () => void;
40
+ pkceConsumer?: PKCEConsumer;
41
+ modalIframe?: boolean;
42
+ };
43
+
44
+ type SessionProviderOutput = SessionData & {
45
+ iframeRef: RefObject<HTMLIFrameElement> | null;
46
+ setAuthResponseUrl: Dispatch<SetStateAction<string | null>>;
45
47
  };
46
- type ParamsContextType = Omit<ParamsProviderProps, "children">;
47
48
 
48
- type CivicProviderProps = AuthProviderProps;
49
- declare const CivicProvider: ({ children, ...props }: CivicProviderProps) => react_jsx_runtime.JSX.Element;
49
+ type CivicAuthProviderProps = Omit<AuthProviderProps, "pkceConsumer">;
50
+ declare const CivicAuthProvider: ({ children, ...props }: CivicAuthProviderProps) => react_jsx_runtime.JSX.Element;
50
51
 
51
- declare const useUser: <T extends Record<string, unknown> = Record<string, never>>() => UserContextType<T>;
52
+ type UserContextType = {
53
+ user: User<UnknownObject> | null;
54
+ };
55
+ type NextCivicAuthProviderProps = Omit<AuthProviderProps, "clientId">;
56
+ declare const CivicNextAuthProvider: ({ children, ...props }: NextCivicAuthProviderProps) => react_jsx_runtime.JSX.Element;
57
+ declare const useNextUser: () => UserContextType;
58
+
59
+ declare const useUser: <T extends Record<string, unknown> = Record<string, never>>() => UserContextType$1<T>;
60
+
61
+ declare const useUserCookie: () => any;
52
62
 
53
63
  declare const useToken: () => TokenContextType;
54
64
 
55
65
  declare const useAuth: () => AuthContextType;
56
66
 
57
- declare const useParams: () => ParamsContextType;
67
+ declare const useSession: () => SessionProviderOutput;
68
+
69
+ type ConfigProviderOutput = {
70
+ config: Config;
71
+ redirectUrl: string;
72
+ modalIframe: boolean;
73
+ serverTokenExchange: boolean;
74
+ };
58
75
 
59
- declare const useSession: () => SessionData;
76
+ declare const useConfig: () => ConfigProviderOutput;
77
+
78
+ type CivicAuthIframeContainerProps = {
79
+ onClose?: () => void;
80
+ closeOnRedirect?: boolean;
81
+ };
82
+ declare const CivicAuthIframeContainer: ({ onClose, closeOnRedirect, }: CivicAuthIframeContainerProps) => react_jsx_runtime.JSX.Element;
60
83
 
61
84
  declare const UserButton: ({ displayMode, className, }: {
62
85
  displayMode?: DisplayMode;
63
86
  className?: string;
64
87
  }) => react_jsx_runtime.JSX.Element;
65
88
 
66
- export { type AuthContextType, CivicProvider, type ParamsContextType, type TokenContextType, UserButton, type UserContextType, useAuth, useParams, useSession, useToken, useUser };
89
+ declare const SignInButton: ({ displayMode, className, }: {
90
+ displayMode?: DisplayMode;
91
+ className?: string;
92
+ }) => react_jsx_runtime.JSX.Element;
93
+
94
+ declare const SignOutButton: ({ className }: {
95
+ className?: string;
96
+ }) => react_jsx_runtime.JSX.Element;
97
+
98
+ declare const NextLogOut: ({ children }: {
99
+ children: ReactNode;
100
+ }) => react_jsx_runtime.JSX.Element;
101
+
102
+ export { type AuthContextType, CivicAuthIframeContainer, CivicAuthProvider, type CivicAuthProviderProps, CivicNextAuthProvider, type NextCivicAuthProviderProps, NextLogOut, SignInButton, SignOutButton, type TokenContextType, UserButton, type UserContextType$1 as UserContextType, useAuth, useConfig, useNextUser, useSession, useToken, useUser, useUserCookie };