@civic/auth 0.0.1-beta.18 → 0.0.1-beta.2

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 (52) hide show
  1. package/README.md +0 -26
  2. package/dist/chunk-5NUJ7LFF.mjs +17 -0
  3. package/dist/chunk-5NUJ7LFF.mjs.map +1 -0
  4. package/dist/chunk-KS7ERXGZ.js +481 -0
  5. package/dist/chunk-KS7ERXGZ.js.map +1 -0
  6. package/dist/chunk-NINRO7GS.js +209 -0
  7. package/dist/chunk-NINRO7GS.js.map +1 -0
  8. package/dist/chunk-NXBKSUKI.mjs +481 -0
  9. package/dist/chunk-NXBKSUKI.mjs.map +1 -0
  10. package/dist/chunk-T7HUHQ3J.mjs +209 -0
  11. package/dist/chunk-T7HUHQ3J.mjs.map +1 -0
  12. package/dist/chunk-WZLC5B4C.js +17 -0
  13. package/dist/chunk-WZLC5B4C.js.map +1 -0
  14. package/dist/index-DoDoIY_K.d.mts +79 -0
  15. package/dist/index-DoDoIY_K.d.ts +79 -0
  16. package/dist/index.css +70 -63
  17. package/dist/index.css.map +1 -1
  18. package/dist/index.d.mts +1 -3
  19. package/dist/index.d.ts +1 -3
  20. package/dist/nextjs.d.mts +11 -10
  21. package/dist/nextjs.d.ts +11 -10
  22. package/dist/nextjs.js +173 -62
  23. package/dist/nextjs.js.map +1 -1
  24. package/dist/nextjs.mjs +171 -60
  25. package/dist/nextjs.mjs.map +1 -1
  26. package/dist/react.d.mts +65 -39
  27. package/dist/react.d.ts +65 -39
  28. package/dist/react.js +212 -433
  29. package/dist/react.js.map +1 -1
  30. package/dist/react.mjs +235 -456
  31. package/dist/react.mjs.map +1 -1
  32. package/dist/server.d.mts +12 -13
  33. package/dist/server.d.ts +12 -13
  34. package/dist/server.js +186 -3
  35. package/dist/server.js.map +1 -1
  36. package/dist/server.mjs +192 -9
  37. package/dist/server.mjs.map +1 -1
  38. package/package.json +4 -4
  39. package/dist/chunk-5XL2ST72.mjs +0 -226
  40. package/dist/chunk-5XL2ST72.mjs.map +0 -1
  41. package/dist/chunk-G3P5TIO2.mjs +0 -708
  42. package/dist/chunk-G3P5TIO2.mjs.map +0 -1
  43. package/dist/chunk-RF23Q4V6.js +0 -708
  44. package/dist/chunk-RF23Q4V6.js.map +0 -1
  45. package/dist/chunk-SEKF2WZX.js +0 -226
  46. package/dist/chunk-SEKF2WZX.js.map +0 -1
  47. package/dist/index-DTimUlkB.d.ts +0 -17
  48. package/dist/index-DvjkKpkk.d.mts +0 -17
  49. package/dist/types-HdCjGldB.d.mts +0 -58
  50. package/dist/types-HdCjGldB.d.ts +0 -58
  51. package/dist/types-b4c1koXj.d.mts +0 -19
  52. package/dist/types-b4c1koXj.d.ts +0 -19
package/dist/nextjs.mjs CHANGED
@@ -1,21 +1,13 @@
1
1
  import {
2
- NextjsClientStorage,
3
- NextjsCookieStorage,
4
- clearAuthCookies,
2
+ AuthSessionServiceImpl,
5
3
  createCivicAuthPlugin,
6
4
  defaultAuthConfig,
7
5
  loggers,
8
- resolveAuthConfig,
9
- resolveCallbackUrl
10
- } from "./chunk-5XL2ST72.mjs";
6
+ resolveAuthConfig
7
+ } from "./chunk-NXBKSUKI.mjs";
11
8
  import {
12
- GenericPublicClientPKCEProducer,
13
- GenericUserSession,
14
- TOKEN_EXCHANGE_TRIGGER_TEXT,
15
- getUser,
16
- resolveOAuthAccessCode,
17
- retrieveTokens
18
- } from "./chunk-G3P5TIO2.mjs";
9
+ deriveCodeChallenge
10
+ } from "./chunk-T7HUHQ3J.mjs";
19
11
  import {
20
12
  __async,
21
13
  __spreadProps,
@@ -23,18 +15,12 @@ import {
23
15
  } from "./chunk-RGHW4PYM.mjs";
24
16
 
25
17
  // src/nextjs/GetUser.ts
26
- var getUser2 = () => {
18
+ import { cookies } from "next/headers.js";
19
+ var getUser = () => {
27
20
  var _a;
28
- const clientStorage = new NextjsClientStorage();
29
- const userSession = new GenericUserSession(clientStorage);
30
- const tokens = retrieveTokens(clientStorage);
31
- const user = userSession.get();
32
- if (!user || !tokens) return null;
33
- return __spreadProps(__spreadValues({}, user), {
34
- idToken: tokens.id_token,
35
- accessToken: tokens.access_token,
36
- refreshToken: (_a = tokens.refresh_token) != null ? _a : ""
37
- });
21
+ const user = (_a = cookies().get("user")) == null ? void 0 : _a.value;
22
+ if (!user) return null;
23
+ return JSON.parse(user);
38
24
  };
39
25
 
40
26
  // src/nextjs/middleware.ts
@@ -56,7 +42,7 @@ var matchesGlobs = (pathname, patterns) => patterns.some((pattern) => {
56
42
  var applyAuth = (authConfig, request) => __async(void 0, null, function* () {
57
43
  const authConfigWithDefaults = resolveAuthConfig(authConfig);
58
44
  const isAuthenticated = !!request.cookies.get("id_token");
59
- if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl && request.method === "GET") {
45
+ if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl) {
60
46
  console.log("\u2192 Skipping auth check - this is the login URL");
61
47
  return void 0;
62
48
  }
@@ -101,6 +87,129 @@ function auth(authConfig = {}) {
101
87
  // src/nextjs/routeHandler.ts
102
88
  import { NextResponse as NextResponse2 } from "next/server.js";
103
89
  import { revalidatePath } from "next/cache.js";
90
+
91
+ // src/nextjs/NextJSSessionService.ts
92
+ import { cookies as cookies2 } from "next/headers.js";
93
+
94
+ // src/nextjs/cookies.ts
95
+ var createTokenCookies = (response, sessionData, config) => {
96
+ var _a, _b;
97
+ const maxAge = (_a = sessionData.expiresIn) != null ? _a : 3600;
98
+ const cookieOptions = __spreadProps(__spreadValues({}, (_b = config.cookies) == null ? void 0 : _b.tokens), {
99
+ maxAge
100
+ });
101
+ if (sessionData.accessToken) {
102
+ response.cookies.set("access_token", sessionData.accessToken, __spreadProps(__spreadValues({}, cookieOptions), {
103
+ httpOnly: true
104
+ }));
105
+ }
106
+ if (sessionData.idToken) {
107
+ response.cookies.set("id_token", sessionData.idToken, __spreadProps(__spreadValues({}, cookieOptions), {
108
+ httpOnly: true
109
+ }));
110
+ }
111
+ if (sessionData.refreshToken) {
112
+ response.cookies.set("refresh_token", sessionData.refreshToken, __spreadProps(__spreadValues({}, cookieOptions), {
113
+ httpOnly: true
114
+ }));
115
+ }
116
+ };
117
+ var createUserInfoCookie = (response, user, sessionData, config) => {
118
+ var _a, _b, _c;
119
+ if (!user) {
120
+ response.cookies.set("user", "", __spreadProps(__spreadValues({}, (_a = config.cookies) == null ? void 0 : _a.user), {
121
+ maxAge: 0
122
+ }));
123
+ return;
124
+ }
125
+ const maxAge = (_b = sessionData.expiresIn) != null ? _b : 3600;
126
+ const frontendUser = __spreadValues({}, user);
127
+ response.cookies.set("user", JSON.stringify(frontendUser), __spreadProps(__spreadValues({}, (_c = config.cookies) == null ? void 0 : _c.user), {
128
+ maxAge
129
+ }));
130
+ };
131
+ var clearAuthCookies = (response, config) => {
132
+ var _a, _b;
133
+ const clearOptions = __spreadProps(__spreadValues({}, (_a = config.cookies) == null ? void 0 : _a.tokens), {
134
+ maxAge: 0
135
+ });
136
+ response.cookies.set("access_token", "", clearOptions);
137
+ response.cookies.set("id_token", "", clearOptions);
138
+ response.cookies.set("refresh_token", "", clearOptions);
139
+ response.cookies.set("codeVerifier", "", clearOptions);
140
+ response.cookies.set("user", "", __spreadProps(__spreadValues({}, (_b = config.cookies) == null ? void 0 : _b.user), {
141
+ maxAge: 0
142
+ }));
143
+ };
144
+
145
+ // src/nextjs/NextJSSessionService.ts
146
+ var NextJSAuthSessionServiceImpl = class extends AuthSessionServiceImpl {
147
+ constructor(authConfig, request, response, inputEndpoints) {
148
+ super(
149
+ authConfig.clientId,
150
+ authConfig.callbackUrl,
151
+ authConfig.oauthServer,
152
+ inputEndpoints
153
+ );
154
+ this.authConfig = authConfig;
155
+ this.request = request;
156
+ this.response = response;
157
+ this.inputEndpoints = inputEndpoints;
158
+ }
159
+ getCodeVerifier() {
160
+ const codeVerifier = cookies2().get("codeVerifier");
161
+ if (!codeVerifier) {
162
+ throw new Error("Code verifier not found in cookies");
163
+ }
164
+ return codeVerifier.value;
165
+ }
166
+ getSessionData() {
167
+ var _a, _b, _c, _d;
168
+ const authenticated = cookies2().get("access_token") !== void 0;
169
+ return {
170
+ authenticated,
171
+ codeVerifier: (_a = cookies2().get("codeVerifier")) == null ? void 0 : _a.value,
172
+ accessToken: (_b = cookies2().get("access_token")) == null ? void 0 : _b.value,
173
+ idToken: (_c = cookies2().get("id_token")) == null ? void 0 : _c.value,
174
+ refreshToken: (_d = cookies2().get("refresh_token")) == null ? void 0 : _d.value
175
+ };
176
+ }
177
+ updateSessionData(data) {
178
+ createTokenCookies(
179
+ this.response,
180
+ data,
181
+ this.authConfig
182
+ );
183
+ }
184
+ getUser() {
185
+ const userCookie = cookies2().get("user");
186
+ if (!userCookie) return null;
187
+ return JSON.parse(userCookie.value);
188
+ }
189
+ setUser(user) {
190
+ createUserInfoCookie(
191
+ this.response,
192
+ user,
193
+ { authenticated: true },
194
+ this.authConfig
195
+ );
196
+ }
197
+ clearSessionData() {
198
+ clearAuthCookies(this.response, this.authConfig);
199
+ }
200
+ // TODO fix the Window reference
201
+ loadAuthorizationUrl() {
202
+ throw new Error("Not implemented");
203
+ }
204
+ logout() {
205
+ return __async(this, null, function* () {
206
+ this.updateSessionData({ authenticated: false });
207
+ });
208
+ }
209
+ };
210
+
211
+ // src/nextjs/routeHandler.ts
212
+ import { generateCodeVerifier } from "oslo/oauth2";
104
213
  var logger = loggers.nextjs.handlers.auth;
105
214
  var AuthError = class extends Error {
106
215
  constructor(message, status = 401) {
@@ -111,48 +220,47 @@ var AuthError = class extends Error {
111
220
  };
112
221
  function handleChallenge() {
113
222
  return __async(this, null, function* () {
114
- const cookieStorage = new NextjsCookieStorage();
115
- const pkceProducer = new GenericPublicClientPKCEProducer(cookieStorage);
116
- const challenge = yield pkceProducer.getCodeChallenge();
117
- return NextResponse2.json({ status: "success", challenge });
223
+ const codeVerifier = generateCodeVerifier();
224
+ console.log("handleChallenge codeVerifier", codeVerifier);
225
+ const challenge = yield deriveCodeChallenge(codeVerifier);
226
+ const response = NextResponse2.json({ status: "success", challenge });
227
+ response.cookies.set("codeVerifier", codeVerifier, {
228
+ httpOnly: true,
229
+ secure: true,
230
+ sameSite: "strict"
231
+ });
232
+ return response;
118
233
  });
119
234
  }
120
235
  function handleCallback(request, config) {
121
236
  return __async(this, null, function* () {
122
- if (!request.cookies.get("code_verifier")) {
123
- const response2 = new NextResponse2(
124
- `<html><body><span style="display:none">${TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`
125
- );
126
- response2.headers.set("Content-Type", "text/html; charset=utf-8");
127
- console.log(
128
- `handleCallback no code_verifier found, returning ${TOKEN_EXCHANGE_TRIGGER_TEXT}`
129
- );
130
- return response2;
131
- }
132
237
  const code = request.nextUrl.searchParams.get("code");
133
- const state = request.nextUrl.searchParams.get("state");
134
- if (!code || !state) throw new AuthError("Bad parameters", 400);
135
- const resolvedConfigs = resolveAuthConfig(config);
136
- const cookieStorage = new NextjsCookieStorage(resolvedConfigs.cookies.tokens);
137
- const callbackUrl = resolveCallbackUrl(resolvedConfigs, request.url);
238
+ if (!code) throw new AuthError("Missing authorization code");
138
239
  try {
139
- yield resolveOAuthAccessCode(code, state, cookieStorage, __spreadProps(__spreadValues({}, resolvedConfigs), {
140
- redirectUrl: callbackUrl
141
- }));
240
+ const response = new NextResponse2(`<html></html>`);
241
+ response.headers.set("Content-Type", "text/html; charset=utf-8");
242
+ const resolvedConfigs = resolveAuthConfig(config);
243
+ const callbackUrl = new URL(
244
+ resolvedConfigs == null ? void 0 : resolvedConfigs.callbackUrl,
245
+ request.url
246
+ ).toString();
247
+ const authService = getDefaultAuthSessionService(
248
+ __spreadProps(__spreadValues({}, resolvedConfigs), {
249
+ callbackUrl
250
+ }),
251
+ request,
252
+ response
253
+ );
254
+ console.log("handleCallback authService", authService);
255
+ const tokens = yield authService.tokenExchange(request.nextUrl.toString());
256
+ if (!tokens.accessToken) {
257
+ throw new AuthError("Missing access token");
258
+ }
259
+ return response;
142
260
  } catch (error) {
143
261
  logger.error("Token exchange failed:", error);
144
262
  throw new AuthError("Failed to authenticate user", 401);
145
263
  }
146
- const user = yield getUser(cookieStorage);
147
- if (!user) {
148
- throw new AuthError("Failed to get user info", 401);
149
- }
150
- const clientStorage = new NextjsClientStorage();
151
- const userSession = new GenericUserSession(clientStorage);
152
- userSession.set(user);
153
- const response = new NextResponse2(`<html></html>`);
154
- response.headers.set("Content-Type", "text/html; charset=utf-8");
155
- return response;
156
264
  });
157
265
  }
158
266
  var getAbsoluteRedirectPath = (redirectPath, currentBasePath) => {
@@ -173,7 +281,7 @@ function handleLogout(request, config) {
173
281
  new URL(request.url).origin
174
282
  );
175
283
  const response = NextResponse2.redirect(finalRedirectUrl);
176
- clearAuthCookies();
284
+ clearAuthCookies(response, resolvedConfigs);
177
285
  try {
178
286
  revalidatePath(isAbsoluteRedirect ? finalRedirectUrl : redirectTarget);
179
287
  } catch (error) {
@@ -182,6 +290,9 @@ function handleLogout(request, config) {
182
290
  return response;
183
291
  });
184
292
  }
293
+ var getDefaultAuthSessionService = (authConfig, request, response) => {
294
+ return new NextJSAuthSessionServiceImpl(authConfig, request, response);
295
+ };
185
296
  var handler = (authConfig = {}) => (request) => __async(void 0, null, function* () {
186
297
  const config = resolveAuthConfig(authConfig);
187
298
  try {
@@ -203,7 +314,7 @@ var handler = (authConfig = {}) => (request) => __async(void 0, null, function*
203
314
  const status = error instanceof AuthError ? error.status : 500;
204
315
  const message = error instanceof Error ? error.message : "Authentication failed";
205
316
  const response = NextResponse2.json({ error: message }, { status });
206
- clearAuthCookies();
317
+ clearAuthCookies(response, config);
207
318
  return response;
208
319
  }
209
320
  });
@@ -211,7 +322,7 @@ export {
211
322
  auth,
212
323
  authMiddleware,
213
324
  createCivicAuthPlugin,
214
- getUser2 as getUser,
325
+ getUser,
215
326
  handler,
216
327
  withAuth
217
328
  };
@@ -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 redirect to login url\n if (\n request.nextUrl.pathname === authConfigWithDefaults.loginUrl &&\n request.method === \"GET\"\n ) {\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;A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A,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","../src/nextjs/NextJSSessionService.ts","../src/nextjs/cookies.ts"],"sourcesContent":["/**\n * Used on the server-side to get the user object from the cookie\n */\nimport { cookies } from \"next/headers.js\";\nimport { UnknownObject, User } from \"../types\";\n\nexport const getUser = (): User<UnknownObject> | null => {\n // TODO validate the token?\n const user = cookies().get(\"user\")?.value;\n if (!user) return null;\n return JSON.parse(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 {\n AuthConfig,\n DefinedAuthConfig,\n resolveAuthConfig,\n} from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { AuthSessionService } from \"@/types\";\nimport { NextJSAuthSessionServiceImpl } from \"./NextJSSessionService.js\";\nimport { clearAuthCookies } from \"./cookies.js\";\nimport { generateCodeVerifier } from \"oslo/oauth2\";\nimport { deriveCodeChallenge } from \"@/shared/util.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 codeVerifier = generateCodeVerifier();\n console.log(\"handleChallenge codeVerifier\", codeVerifier);\n const challenge = await deriveCodeChallenge(codeVerifier);\n const response = NextResponse.json({ status: \"success\", challenge });\n response.cookies.set(\"codeVerifier\", codeVerifier, {\n httpOnly: true,\n secure: true,\n sameSite: \"strict\",\n });\n return response;\n}\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const code = request.nextUrl.searchParams.get(\"code\");\n if (!code) throw new AuthError(\"Missing authorization code\");\n\n try {\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\n const resolvedConfigs = resolveAuthConfig(config);\n const callbackUrl = new URL(\n resolvedConfigs?.callbackUrl,\n request.url,\n ).toString();\n\n const authService = getDefaultAuthSessionService(\n {\n ...resolvedConfigs,\n callbackUrl,\n },\n request,\n response,\n );\n console.log(\"handleCallback authService\", authService);\n const tokens = await authService.tokenExchange(request.nextUrl.toString());\n\n if (!tokens.accessToken) {\n throw new AuthError(\"Missing access token\");\n }\n\n return response;\n } catch (error) {\n logger.error(\"Token exchange failed:\", error);\n throw new AuthError(\"Failed to authenticate user\", 401);\n }\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 clearAuthCookies(response, resolvedConfigs);\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\nconst getDefaultAuthSessionService = (\n authConfig: DefinedAuthConfig,\n request?: NextRequest,\n response?: NextResponse,\n): AuthSessionService => {\n return new NextJSAuthSessionServiceImpl(authConfig, request, 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(response, config);\n return response;\n }\n };\n","import { cookies } from \"next/headers.js\";\nimport { SessionData, UnknownObject, Endpoints, User } from \"../types.js\";\nimport { NextRequest, NextResponse } from \"next/server.js\";\nimport { AuthConfigWithDefaults } from \"./config.js\";\nimport { AuthSessionServiceImpl } from \"@/services\";\nimport {\n clearAuthCookies,\n createTokenCookies,\n createUserInfoCookie,\n} from \"./cookies.js\";\n\nexport type StorageInterface = {\n get(): SessionData;\n getUser(): User<UnknownObject> | null;\n set(data: Partial<SessionData>): void;\n setUser(data: User<UnknownObject> | null): void;\n clear(): void;\n};\n\nexport class NextJSAuthSessionServiceImpl extends AuthSessionServiceImpl {\n constructor(\n readonly authConfig: AuthConfigWithDefaults,\n readonly request: NextRequest | undefined,\n readonly response: NextResponse | undefined,\n readonly inputEndpoints?: Endpoints | undefined,\n ) {\n super(\n authConfig.clientId,\n authConfig.callbackUrl,\n authConfig.oauthServer,\n inputEndpoints,\n );\n }\n\n protected getCodeVerifier(): string {\n const codeVerifier = cookies().get(\"codeVerifier\");\n if (!codeVerifier) {\n throw new Error(\"Code verifier not found in cookies\");\n }\n return codeVerifier.value;\n }\n\n getSessionData(): SessionData {\n const authenticated = cookies().get(\"access_token\") !== undefined;\n return {\n authenticated,\n codeVerifier: cookies().get(\"codeVerifier\")?.value,\n accessToken: cookies().get(\"access_token\")?.value,\n idToken: cookies().get(\"id_token\")?.value,\n refreshToken: cookies().get(\"refresh_token\")?.value,\n };\n }\n\n updateSessionData(data: Partial<SessionData>): void {\n createTokenCookies(\n this.response as NextResponse,\n data as SessionData,\n this.authConfig,\n );\n }\n\n getUser(): User<UnknownObject> | null {\n const userCookie = cookies().get(\"user\");\n if (!userCookie) return null;\n return JSON.parse(userCookie.value);\n }\n\n setUser(user: User<UnknownObject> | null): void {\n createUserInfoCookie(\n this.response as NextResponse,\n user,\n { authenticated: true },\n this.authConfig,\n );\n }\n\n clearSessionData(): void {\n clearAuthCookies(this.response as NextResponse, this.authConfig);\n }\n\n // TODO fix the Window reference\n loadAuthorizationUrl() {\n throw new Error(\"Not implemented\");\n }\n\n async logout(): Promise<void> {\n this.updateSessionData({ authenticated: false });\n }\n}\n","import { SessionData, UnknownObject, User } from \"@/types\";\nimport { NextResponse } from \"next/server\";\nimport { AuthConfig } from \"./config\";\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 = (response: NextResponse, config: AuthConfig) => {\n const clearOptions = {\n ...config.cookies?.tokens,\n maxAge: 0,\n };\n\n response.cookies.set(\"access_token\", \"\", clearOptions);\n response.cookies.set(\"id_token\", \"\", clearOptions);\n response.cookies.set(\"refresh_token\", \"\", clearOptions);\n response.cookies.set(\"codeVerifier\", \"\", clearOptions);\n response.cookies.set(\"user\", \"\", {\n ...config.cookies?.user,\n maxAge: 0,\n });\n};\n\nexport { createTokenCookies, createUserInfoCookie, clearAuthCookies };\n"],"mappings":";;;;;;;;;;;;;;;;;AAGA,SAAS,eAAe;AAGjB,IAAM,UAAU,MAAkC;AANzD;AAQE,QAAM,QAAO,aAAQ,EAAE,IAAI,MAAM,MAApB,mBAAuB;AACpC,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,KAAK,MAAM,IAAI;AACxB;;;ACUA,SAAsB,oBAAoB;AAC1C,OAAO,eAAe;AAgBtB,IAAM,YAAY,CAAC,UAAkB,gBAAwB;AAC3D,QAAM,UAAU,UAAU,WAAW;AACrC,SAAO,QAAQ,QAAQ;AACzB;AAOA,IAAM,eAAe,CAAC,UAAkB,aACtC,SAAS,KAAK,CAAC,YAAY;AACzB,MAAI,CAAC,QAAS,QAAO;AACrB,UAAQ,IAAI,YAAY;AAAA,IACtB;AAAA,IACA;AAAA,IACA,OAAO,UAAU,UAAU,OAAO;AAAA,EACpC,CAAC;AACD,SAAO,UAAU,UAAU,OAAO;AACpC,CAAC;AAGH,IAAM,YAAY,CAChB,YACA,YACsC;AACtC,QAAM,yBAAyB,kBAAkB,UAAU;AAG3D,QAAM,kBAAkB,CAAC,CAAC,QAAQ,QAAQ,IAAI,UAAU;AAGxD,MAAI,QAAQ,QAAQ,aAAa,uBAAuB,UAAU;AAChE,YAAQ,IAAI,oDAA+C;AAC3D,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,aAAa,QAAQ,QAAQ,UAAU,uBAAuB,OAAO,GAAG;AAC3E,YAAQ,IAAI,2DAAsD;AAClE,WAAO;AAAA,EAC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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,UAAU,MAAM;AACjC,WAAO;AAAA,EACT;AACF;","names":["NextResponse","cookies","cookies","NextResponse"]}
package/dist/react.d.mts CHANGED
@@ -1,10 +1,20 @@
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';
4
- import { ReactNode, RefObject, Dispatch, SetStateAction } from 'react';
1
+ import { JWT } from 'oslo/jwt';
2
+ import { D as DisplayMode, U as User, F as ForwardedTokens, A as AuthSessionService, E as Endpoints, b as UserInfoService, S as SessionData, a as UnknownObject, O as OIDCTokenResponseBody, P as ParsedTokens, C as Config } from './index-DoDoIY_K.mjs';
5
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
6
- import 'oslo/jwt';
7
- import 'oslo/oauth2';
4
+ import { ReactNode } from 'react';
5
+ import { OAuth2Client } from 'oslo/oauth2';
6
+
7
+ type AuthContextType = {
8
+ signIn: (displayMode?: DisplayMode) => Promise<void>;
9
+ isAuthenticated: boolean;
10
+ isLoading: boolean;
11
+ error: Error | null;
12
+ signOut: () => Promise<void>;
13
+ };
14
+
15
+ type UserContextType$1<T extends Record<string, unknown> & JWT["payload"] = Record<string, unknown> & JWT["payload"]> = {
16
+ user: User<T> | null;
17
+ } & Omit<AuthContextType, "isAuthenticated">;
8
18
 
9
19
  type TokenContextType = {
10
20
  accessToken: string | null;
@@ -15,8 +25,45 @@ type TokenContextType = {
15
25
  error: Error | null;
16
26
  };
17
27
 
18
- interface PKCEConsumer {
19
- getCodeChallenge(): Promise<string>;
28
+ declare class AuthSessionServiceImpl implements AuthSessionService {
29
+ readonly clientId: string;
30
+ readonly redirectUrl: string;
31
+ readonly oauthServer: string;
32
+ readonly inputEndpoints?: Partial<Endpoints> | undefined;
33
+ private endpoints;
34
+ private oauth2Client;
35
+ private userInfoService;
36
+ private codeVerifier;
37
+ private refreshTokenTimeout;
38
+ constructor(clientId: string, redirectUrl: string, oauthServer: string, inputEndpoints?: Partial<Endpoints> | undefined);
39
+ protected getCodeVerifier(): string;
40
+ getUserInfoService(): Promise<UserInfoService>;
41
+ protected getEndpoints(): Promise<Endpoints>;
42
+ protected getOauth2Client(): Promise<OAuth2Client>;
43
+ getSessionData(): SessionData;
44
+ updateSessionData(data: Partial<SessionData>): void;
45
+ getUser(): User<UnknownObject> | null;
46
+ setUser(data: User<UnknownObject> | null): void;
47
+ clearSessionData(): void;
48
+ getAuthorizationUrlWithChallenge(state: string, scopes: string[]): Promise<URL>;
49
+ getAuthorizationUrl(scopes: string[], displayMode: DisplayMode, nonce?: string): Promise<string>;
50
+ loadAuthorizationUrl(authorizationURL: string, displayMode: DisplayMode): void;
51
+ init(): Promise<this>;
52
+ logout(): Promise<void>;
53
+ determineDisplayMode(displayMode: DisplayMode): DisplayMode;
54
+ signIn(displayMode: DisplayMode, scopes: string[], nonce: string): Promise<void>;
55
+ tokenExchange(responseUrl: string): Promise<SessionData>;
56
+ private setupTokenRefresh;
57
+ refreshToken(): Promise<SessionData>;
58
+ getUserInfo<T extends UnknownObject>(): Promise<User<T> | null>;
59
+ /**
60
+ * Uses the jose library to validate a JWT token using the OAuth JWKS endpoint
61
+ * @returns {Promise<jose.JWTPayload>}
62
+ * @throws {Error} if the token is invalid
63
+ * @param tokens
64
+ */
65
+ validateTokens(tokens: OIDCTokenResponseBody): Promise<ParsedTokens>;
66
+ validateExistingSession(): Promise<SessionData>;
20
67
  }
21
68
 
22
69
  type AuthProviderProps = {
@@ -27,20 +74,23 @@ type AuthProviderProps = {
27
74
  config?: Config;
28
75
  onSignIn?: (error?: Error) => void;
29
76
  onSignOut?: () => void;
30
- pkceConsumer?: PKCEConsumer;
31
- modalIframe?: boolean;
32
- sessionData?: SessionData;
77
+ authServiceImpl?: AuthSessionServiceImpl;
78
+ serverSideTokenExchange?: boolean;
33
79
  };
34
80
 
35
- type CivicAuthProviderProps = Omit<AuthProviderProps, "pkceConsumer">;
81
+ type CivicAuthProviderProps = Omit<AuthProviderProps, "authServiceImpl" | "serverSideTokenExchange">;
36
82
  declare const CivicAuthProvider: ({ children, ...props }: CivicAuthProviderProps) => react_jsx_runtime.JSX.Element;
37
83
 
84
+ type UserContextType = {
85
+ user: User<UnknownObject> | null;
86
+ };
38
87
  type NextCivicAuthProviderProps = Omit<AuthProviderProps, "clientId">;
39
88
  declare const CivicNextAuthProvider: ({ children, ...props }: NextCivicAuthProviderProps) => react_jsx_runtime.JSX.Element;
89
+ declare const useNextUser: () => UserContextType;
40
90
 
41
- declare const useUser: <T extends Record<string, unknown> = Record<string, never>>() => UserContextType<T>;
91
+ declare const useUser: <T extends Record<string, unknown> = Record<string, never>>() => UserContextType$1<T>;
42
92
 
43
- declare const useUserCookie: <T extends EmptyObject>() => User<T> | null;
93
+ declare const useUserCookie: () => any;
44
94
 
45
95
  declare const useToken: () => TokenContextType;
46
96
 
@@ -48,30 +98,6 @@ declare const useAuth: () => AuthContextType;
48
98
 
49
99
  declare const useSession: () => SessionData;
50
100
 
51
- type ConfigProviderOutput = {
52
- config: Config;
53
- redirectUrl: string;
54
- modalIframe: boolean;
55
- serverTokenExchange: boolean;
56
- };
57
-
58
- declare const useConfig: () => ConfigProviderOutput;
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
-
69
- type CivicAuthIframeContainerProps = {
70
- onClose?: () => void;
71
- closeOnRedirect?: boolean;
72
- };
73
- declare const CivicAuthIframeContainer: ({ onClose, closeOnRedirect, }: CivicAuthIframeContainerProps) => react_jsx_runtime.JSX.Element;
74
-
75
101
  declare const UserButton: ({ displayMode, className, }: {
76
102
  displayMode?: DisplayMode;
77
103
  className?: string;
@@ -90,4 +116,4 @@ declare const NextLogOut: ({ children }: {
90
116
  children: ReactNode;
91
117
  }) => react_jsx_runtime.JSX.Element;
92
118
 
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 };
119
+ export { type AuthContextType, CivicAuthProvider, CivicNextAuthProvider, NextLogOut, SignInButton, SignOutButton, type TokenContextType, UserButton, type UserContextType$1 as UserContextType, useAuth, useNextUser, useSession, useToken, useUser, useUserCookie };