@civic/auth 0.0.1-beta.1 → 0.0.1-beta.11

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 +26 -0
  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-DFVNodC9.d.mts → index-Bfi0hVMZ.d.mts} +5 -13
  19. package/dist/{index-DFVNodC9.d.ts → index-Bfi0hVMZ.d.ts} +5 -13
  20. package/dist/index.css +63 -63
  21. package/dist/index.css.map +1 -1
  22. package/dist/index.d.mts +1 -1
  23. package/dist/index.d.ts +1 -1
  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 +22 -37
  28. package/dist/nextjs.d.ts +22 -37
  29. package/dist/nextjs.js +166 -848
  30. package/dist/nextjs.js.map +1 -1
  31. package/dist/nextjs.mjs +162 -805
  32. package/dist/nextjs.mjs.map +1 -1
  33. package/dist/react.d.mts +42 -58
  34. package/dist/react.d.ts +42 -58
  35. package/dist/react.js +668 -1103
  36. package/dist/react.js.map +1 -1
  37. package/dist/react.mjs +608 -1005
  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 +28 -18
package/dist/nextjs.js CHANGED
@@ -1,865 +1,78 @@
1
- "use server";
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __defProps = Object.defineProperties;
6
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
8
- var __getOwnPropNames = Object.getOwnPropertyNames;
9
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
10
- var __getProtoOf = Object.getPrototypeOf;
11
- var __hasOwnProp = Object.prototype.hasOwnProperty;
12
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
13
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
- var __spreadValues = (a, b) => {
15
- for (var prop in b || (b = {}))
16
- if (__hasOwnProp.call(b, prop))
17
- __defNormalProp(a, prop, b[prop]);
18
- if (__getOwnPropSymbols)
19
- for (var prop of __getOwnPropSymbols(b)) {
20
- if (__propIsEnum.call(b, prop))
21
- __defNormalProp(a, prop, b[prop]);
22
- }
23
- return a;
24
- };
25
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
26
- var __export = (target, all) => {
27
- for (var name in all)
28
- __defProp(target, name, { get: all[name], enumerable: true });
29
- };
30
- var __copyProps = (to, from, except, desc) => {
31
- if (from && typeof from === "object" || typeof from === "function") {
32
- for (let key of __getOwnPropNames(from))
33
- if (!__hasOwnProp.call(to, key) && key !== except)
34
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
35
- }
36
- return to;
37
- };
38
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
39
- // If the importer is in node compatibility mode or this is not an ESM
40
- // file that has been converted to a CommonJS file using a Babel-
41
- // compatible transform (i.e. "__esModule" has not been set), then set
42
- // "default" to the CommonJS "module.exports" for node compatibility.
43
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
44
- mod
45
- ));
46
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
47
- var __async = (__this, __arguments, generator) => {
48
- return new Promise((resolve, reject) => {
49
- var fulfilled = (value) => {
50
- try {
51
- step(generator.next(value));
52
- } catch (e) {
53
- reject(e);
54
- }
55
- };
56
- var rejected = (value) => {
57
- try {
58
- step(generator.throw(value));
59
- } catch (e) {
60
- reject(e);
61
- }
62
- };
63
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
64
- step((generator = generator.apply(__this, __arguments)).next());
65
- });
66
- };
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
67
2
 
68
- // src/nextjs/index.ts
69
- var nextjs_exports = {};
70
- __export(nextjs_exports, {
71
- auth: () => auth,
72
- authMiddleware: () => authMiddleware,
73
- createCivicAuthPlugin: () => createCivicAuthPlugin,
74
- getUser: () => getUser,
75
- handler: () => handler,
76
- withAuth: () => withAuth
77
- });
78
- module.exports = __toCommonJS(nextjs_exports);
79
3
 
80
- // src/lib/logger.ts
81
- var import_debug = __toESM(require("debug"));
82
- var PACKAGE_NAME = "@civic/auth";
83
- var DebugLogger = class {
84
- constructor(namespace) {
85
- this.debugLogger = (0, import_debug.default)(`${PACKAGE_NAME}:${namespace}:debug`);
86
- this.infoLogger = (0, import_debug.default)(`${PACKAGE_NAME}:${namespace}:info`);
87
- this.warnLogger = (0, import_debug.default)(`${PACKAGE_NAME}:${namespace}:warn`);
88
- this.errorLogger = (0, import_debug.default)(`${PACKAGE_NAME}:${namespace}:error`);
89
- this.debugLogger.color = "4";
90
- this.infoLogger.color = "2";
91
- this.warnLogger.color = "3";
92
- this.errorLogger.color = "1";
93
- }
94
- debug(message, ...args) {
95
- this.debugLogger(message, ...args);
96
- }
97
- info(message, ...args) {
98
- this.infoLogger(message, ...args);
99
- }
100
- warn(message, ...args) {
101
- this.warnLogger(message, ...args);
102
- }
103
- error(message, ...args) {
104
- this.errorLogger(message, ...args);
105
- }
106
- };
107
- var createLogger = (namespace) => new DebugLogger(namespace);
108
- var loggers = {
109
- // Next.js specific loggers
110
- nextjs: {
111
- routes: createLogger("api:routes"),
112
- middleware: createLogger("api:middleware"),
113
- handlers: {
114
- auth: createLogger("api:handlers:auth")
115
- }
116
- },
117
- // React specific loggers
118
- react: {
119
- components: createLogger("react:components"),
120
- hooks: createLogger("react:hooks"),
121
- context: createLogger("react:context")
122
- },
123
- // Shared utilities loggers
124
- services: {
125
- validation: createLogger("utils:validation"),
126
- network: createLogger("utils:network")
127
- }
128
- };
129
4
 
130
- // src/nextjs/config.ts
131
- var logger = loggers.nextjs.handlers.auth;
132
- var defaultAuthConfig = {
133
- oauthServer: "https://auth-dev.civic.com/oauth",
134
- callbackUrl: "/api/auth/callback",
135
- challengeUrl: "/api/auth/challenge",
136
- logoutUrl: "/api/auth/logout",
137
- loginUrl: "/",
138
- include: ["/*"],
139
- exclude: [],
140
- cookies: {
141
- tokens: {
142
- sameSite: "strict",
143
- path: "/",
144
- maxAge: 60 * 60
145
- // 1 hour
146
- },
147
- user: {
148
- sameSite: "strict",
149
- path: "/",
150
- maxAge: 60 * 60
151
- // 1 hour
152
- }
153
- }
154
- };
155
- var withoutUndefined = (obj) => {
156
- const result = {};
157
- for (const key in obj) {
158
- if (obj[key] !== void 0) {
159
- result[key] = obj[key];
160
- }
161
- }
162
- return result;
163
- };
164
- var resolveAuthConfig = (config = {}) => {
165
- var _a, _b, _c, _d;
166
- const configFromEnv = withoutUndefined({
167
- clientId: process.env._civic_auth_client_id,
168
- oauthServer: process.env._civic_oauth_server,
169
- callbackUrl: process.env._civic_auth_callback_url,
170
- loginUrl: process.env._civic_auth_login_url,
171
- logoutUrl: process.env._civic_auth_logout_url,
172
- include: (_a = process.env._civic_auth_includes) == null ? void 0 : _a.split(","),
173
- exclude: (_b = process.env._civic_auth_excludes) == null ? void 0 : _b.split(","),
174
- cookies: process.env._civic_auth_cookie_config ? JSON.parse(process.env._civic_auth_cookie_config) : void 0
175
- });
176
- const mergedConfig = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultAuthConfig), configFromEnv), config), {
177
- // Override with directly passed config
178
- cookies: {
179
- tokens: __spreadValues(__spreadValues({}, defaultAuthConfig.cookies.tokens), ((_c = config.cookies) == null ? void 0 : _c.tokens) || {}),
180
- user: __spreadValues(__spreadValues({}, defaultAuthConfig.cookies.user), ((_d = config.cookies) == null ? void 0 : _d.user) || {})
181
- }
182
- });
183
- logger.debug("Config from environment:", configFromEnv);
184
- logger.debug("Resolved config:", mergedConfig);
185
- if (mergedConfig.clientId === void 0) {
186
- throw new Error("Civic Auth client ID is required");
187
- }
188
- return mergedConfig;
189
- };
190
- var createCivicAuthPlugin = (clientId, authConfig = {}) => {
191
- return (nextConfig) => {
192
- const resolvedConfig = resolveAuthConfig(__spreadProps(__spreadValues({}, authConfig), { clientId }));
193
- return __spreadProps(__spreadValues({}, nextConfig), {
194
- env: __spreadProps(__spreadValues({}, nextConfig == null ? void 0 : nextConfig.env), {
195
- // Internal environment variables - do not set these manually
196
- _civic_auth_client_id: clientId,
197
- _civic_oauth_server: resolvedConfig.oauthServer,
198
- _civic_auth_callback_url: resolvedConfig.callbackUrl,
199
- _civic_auth_login_url: resolvedConfig.loginUrl,
200
- _civic_auth_logout_url: resolvedConfig.logoutUrl,
201
- _civic_auth_includes: resolvedConfig.include.join(","),
202
- _civic_auth_excludes: resolvedConfig.exclude.join(","),
203
- _civic_auth_cookie_config: JSON.stringify(resolvedConfig.cookies)
204
- })
205
- });
206
- };
207
- };
208
5
 
209
- // src/nextjs/routeHandler.ts
210
- var import_server = require("next/server.js");
211
- var import_cache = require("next/cache.js");
212
6
 
213
- // src/nextjs/NextJSSessionService.ts
214
- var import_headers = require("next/headers.js");
7
+ var _chunkMVO4UZ2Ajs = require('./chunk-MVO4UZ2A.js');
215
8
 
216
- // src/services/UserInfoService.ts
217
- var import_jwt = require("oslo/jwt");
218
- var UserInfoServiceImpl = class {
219
- constructor(endpoints) {
220
- this.endpoints = endpoints;
221
- }
222
- extractUserFromIdToken(idToken) {
223
- const parsedJWT = (0, import_jwt.parseJWT)(idToken);
224
- if (!parsedJWT) {
225
- return null;
226
- }
227
- return parsedJWT.payload;
228
- }
229
- getUserInfo(accessToken, idToken) {
230
- return __async(this, null, function* () {
231
- if (idToken) {
232
- return this.extractUserFromIdToken(idToken);
233
- }
234
- const userInfo = yield fetch(this.endpoints.userinfo, {
235
- headers: { Authorization: `Bearer ${accessToken}` }
236
- });
237
- return userInfo.json();
238
- });
239
- }
240
- };
241
9
 
242
- // src/services/SessionService.ts
243
- var import_oauth2 = require("oslo/oauth2");
244
- var jose = __toESM(require("jose"));
245
10
 
246
- // src/lib/oauth.ts
247
- var import_uuid = require("uuid");
248
- var getIssuerVariations = (issuer) => {
249
- const issuerWithoutSlash = issuer.endsWith("/") ? issuer.slice(0, issuer.length - 1) : issuer;
250
- const issuerWithSlash = `${issuerWithoutSlash}/`;
251
- return [issuerWithoutSlash, issuerWithSlash];
252
- };
253
- var addSlashIfNeeded = (url) => url.endsWith("/") ? url : `${url}/`;
254
- var getOauthEndpoints = (oauthServer) => __async(void 0, null, function* () {
255
- const openIdConfigResponse = yield fetch(
256
- `${addSlashIfNeeded(oauthServer)}.well-known/openid-configuration`
257
- );
258
- const openIdConfig = yield openIdConfigResponse.json();
259
- return {
260
- jwks: openIdConfig.jwks_uri,
261
- auth: openIdConfig.authorization_endpoint,
262
- token: openIdConfig.token_endpoint,
263
- userinfo: openIdConfig.userinfo_endpoint
264
- };
265
- });
266
- var generateState = (displayMode) => {
267
- const jsonString = JSON.stringify({
268
- uuid: (0, import_uuid.v4)(),
269
- displayMode
270
- });
271
- return btoa(jsonString);
272
- };
273
- var displayModeFromState = (state, sessionDisplayMode) => {
274
- try {
275
- const jsonString = btoa(state);
276
- return JSON.parse(jsonString).displayMode;
277
- } catch (e) {
278
- console.error("Failed to parse displayMode from state:", e);
279
- return sessionDisplayMode;
280
- }
281
- };
11
+ var _chunkKCSGIIPAjs = require('./chunk-KCSGIIPA.js');
12
+
13
+
14
+
15
+
16
+
17
+ var _chunkYNLXRD5Ljs = require('./chunk-YNLXRD5L.js');
18
+
282
19
 
283
- // src/utils.ts
284
- var import_clsx = require("clsx");
285
- var import_tailwind_merge = require("tailwind-merge");
286
- var isPopupBlocked = () => {
287
- const popup = window.open("", "", "width=1,height=1");
288
- if (!popup) {
289
- return true;
290
- }
291
- try {
292
- if (typeof popup.closed === "undefined") {
293
- throw new Error("Popup is blocked");
294
- }
295
- } catch (e) {
296
- return true;
297
- }
298
- popup.close();
299
- return false;
300
- };
301
20
 
302
- // src/services/SessionService.ts
303
- var AuthSessionServiceImpl = class {
304
- constructor(clientId, redirectUrl, oauthServer, inputEndpoints) {
305
- this.clientId = clientId;
306
- this.redirectUrl = redirectUrl;
307
- this.oauthServer = oauthServer;
308
- this.inputEndpoints = inputEndpoints;
309
- this.codeVerifier = void 0;
310
- this.refreshTokenTimeout = null;
311
- this.codeVerifier = this.getCodeVerifier();
312
- this.endpoints = inputEndpoints;
313
- }
314
- getCodeVerifier() {
315
- return (0, import_oauth2.generateCodeVerifier)();
316
- }
317
- getUserInfoService() {
318
- return __async(this, null, function* () {
319
- if (this.userInfoService) {
320
- return this.userInfoService;
321
- }
322
- const endpoints = yield this.getEndpoints();
323
- this.userInfoService = new UserInfoServiceImpl(endpoints);
324
- return this.userInfoService;
325
- });
326
- }
327
- getEndpoints() {
328
- return __async(this, null, function* () {
329
- var _a;
330
- if ((_a = this.endpoints) == null ? void 0 : _a.auth) {
331
- return this.endpoints;
332
- }
333
- const jwksEndpoints = yield getOauthEndpoints(this.oauthServer);
334
- return this.endpoints ? __spreadValues(__spreadValues({}, this.endpoints), jwksEndpoints) : jwksEndpoints;
335
- });
336
- }
337
- getOauth2Client() {
338
- return __async(this, null, function* () {
339
- if (this.oauth2Client) {
340
- return this.oauth2Client;
341
- }
342
- const endpoints = yield this.getEndpoints();
343
- this.oauth2Client = new import_oauth2.OAuth2Client(
344
- this.clientId,
345
- endpoints.auth,
346
- endpoints.token,
347
- // this
348
- { redirectURI: this.redirectUrl }
349
- );
350
- return this.oauth2Client;
351
- });
352
- }
353
- getSessionData() {
354
- return JSON.parse(
355
- localStorage.getItem(`civic-auth:${this.clientId}`) || "{}"
356
- );
357
- }
358
- updateSessionData(data) {
359
- localStorage.setItem(
360
- `civic-auth:${this.clientId}`,
361
- JSON.stringify(__spreadValues({}, data))
362
- );
363
- }
364
- getUser() {
365
- return JSON.parse(
366
- localStorage.getItem(`civic-auth:${this.clientId}:user`) || "{}"
367
- );
368
- }
369
- setUser(data) {
370
- localStorage.setItem(
371
- `civic-auth:${this.clientId}:user`,
372
- JSON.stringify(data === null ? {} : data)
373
- );
374
- }
375
- clearSessionData() {
376
- localStorage.setItem(`civic-auth:${this.clientId}`, JSON.stringify({}));
377
- }
378
- getAuthorizationUrlWithChallenge(state, scopes) {
379
- return __async(this, null, function* () {
380
- var _a;
381
- const oauth2Client = yield this.getOauth2Client();
382
- if ((_a = this.endpoints) == null ? void 0 : _a.challenge) {
383
- const challenge = yield fetch(this.endpoints.challenge).then(
384
- (res) => res.json().then((data) => data.challenge)
385
- );
386
- const oAuthUrl2 = yield oauth2Client.createAuthorizationURL({
387
- state,
388
- scopes
389
- });
390
- oAuthUrl2.searchParams.append("code_challenge", challenge);
391
- oAuthUrl2.searchParams.append("code_challenge_method", "S256");
392
- return oAuthUrl2;
393
- }
394
- const oAuthUrl = yield oauth2Client.createAuthorizationURL({
395
- state,
396
- codeVerifier: this.codeVerifier,
397
- codeChallengeMethod: "S256",
398
- scopes
399
- });
400
- return oAuthUrl;
401
- });
402
- }
403
- getAuthorizationUrl(scopes, displayMode, nonce) {
404
- return __async(this, null, function* () {
405
- const state = generateState(displayMode);
406
- const existingSessionData = this.getSessionData();
407
- this.updateSessionData(__spreadProps(__spreadValues({}, existingSessionData), {
408
- codeVerifier: this.codeVerifier,
409
- displayMode
410
- }));
411
- const oAuthUrl = yield this.getAuthorizationUrlWithChallenge(state, scopes);
412
- if (nonce) {
413
- oAuthUrl.searchParams.append("nonce", nonce);
414
- }
415
- oAuthUrl.searchParams.append("prompt", "consent");
416
- return oAuthUrl.toString();
417
- });
418
- }
419
- // TODO fix the Window reference
420
- loadAuthorizationUrl(authorizationURL, displayMode) {
421
- switch (displayMode) {
422
- case "iframe":
423
- break;
424
- case "redirect":
425
- window.location.href = authorizationURL;
426
- break;
427
- case "new_tab":
428
- window.open(authorizationURL, "_blank");
429
- break;
430
- case "custom_tab":
431
- break;
432
- }
433
- }
434
- init() {
435
- return __async(this, null, function* () {
436
- this.updateSessionData({ authenticated: false });
437
- });
438
- }
439
- determineDisplayMode(displayMode) {
440
- if (isPopupBlocked() && displayMode === "iframe") {
441
- displayMode = "redirect";
442
- }
443
- return displayMode;
444
- }
445
- signIn(displayMode, scopes, nonce) {
446
- return __async(this, null, function* () {
447
- const authorizationURL = yield this.getAuthorizationUrl(
448
- scopes,
449
- displayMode,
450
- nonce
451
- );
452
- this.loadAuthorizationUrl(authorizationURL, displayMode);
453
- });
454
- }
455
- tokenExchange(responseUrl) {
456
- return __async(this, null, function* () {
457
- let session = this.getSessionData();
458
- if (!session.authenticated) {
459
- const url = new URL(responseUrl);
460
- const authorizationCode = url.searchParams.get("code");
461
- const returnedState = url.searchParams.get("state");
462
- if (!authorizationCode || !returnedState) {
463
- throw new Error("Invalid authorization response");
464
- }
465
- const codeVerifier = session.codeVerifier;
466
- const oauth2Client = yield this.getOauth2Client();
467
- const tokens = yield oauth2Client.validateAuthorizationCode(
468
- authorizationCode,
469
- {
470
- codeVerifier
471
- }
472
- );
473
- try {
474
- yield this.validateTokens(tokens);
475
- } catch (error) {
476
- console.error("tokenExchange tokens", { error, tokens });
477
- throw new Error(
478
- `OIDC tokens validation failed: ${error.message}`
479
- );
480
- }
481
- const parsedDisplayMode = displayModeFromState(
482
- returnedState,
483
- session.displayMode
484
- );
485
- session = __spreadProps(__spreadValues({}, session), {
486
- displayMode: parsedDisplayMode,
487
- idToken: tokens.id_token,
488
- authenticated: true,
489
- state: returnedState,
490
- accessToken: tokens.access_token,
491
- refreshToken: tokens.refresh_token,
492
- timestamp: Date.now(),
493
- expiresIn: tokens.expires_in
494
- });
495
- this.updateSessionData(session);
496
- const user = yield (yield this.getUserInfoService()).getUserInfo(tokens.access_token, tokens.id_token || null);
497
- this.setUser(user);
498
- }
499
- this.setupTokenRefresh(session);
500
- if (session.displayMode === "new_tab") {
501
- window.close();
502
- } else if (session.displayMode === "redirect") {
503
- }
504
- return session;
505
- });
506
- }
507
- setupTokenRefresh(session) {
508
- if (this.refreshTokenTimeout) {
509
- clearTimeout(this.refreshTokenTimeout);
510
- }
511
- if (session.expiresIn) {
512
- const elapsedTime = Date.now() - (session.timestamp || 0);
513
- const remainingTime = session.expiresIn * 1e3 - elapsedTime;
514
- const refreshTime = Math.max(0, remainingTime - 6e4);
515
- this.refreshTokenTimeout = setTimeout(() => {
516
- this.refreshToken().then((newSession) => {
517
- console.log("Token refreshed successfully", newSession);
518
- }).catch((error) => {
519
- console.error("Failed to refresh token:", error);
520
- this.updateSessionData({});
521
- });
522
- }, refreshTime);
523
- }
524
- }
525
- refreshToken() {
526
- return __async(this, null, function* () {
527
- const sessionData = this.getSessionData();
528
- if (!sessionData.refreshToken) {
529
- throw new Error("No refresh token available");
530
- }
531
- const oauth2Client = yield this.getOauth2Client();
532
- const tokens = yield oauth2Client.refreshAccessToken(
533
- sessionData.refreshToken
534
- );
535
- const session = __spreadProps(__spreadValues({}, sessionData), {
536
- idToken: tokens.id_token,
537
- authenticated: true,
538
- accessToken: tokens.access_token,
539
- refreshToken: tokens.refresh_token,
540
- timestamp: Date.now(),
541
- expiresIn: tokens.expires_in
542
- });
543
- this.updateSessionData(session);
544
- this.setupTokenRefresh(session);
545
- return session;
546
- });
547
- }
548
- getUserInfo() {
549
- return __async(this, null, function* () {
550
- const sessionData = this.getSessionData();
551
- if (!sessionData.accessToken) {
552
- throw new Error("No access token available");
553
- }
554
- const userInfoService = yield this.getUserInfoService();
555
- return userInfoService.getUserInfo(
556
- sessionData.accessToken,
557
- sessionData.idToken || null
558
- );
559
- });
560
- }
561
- /**
562
- * Uses the jose library to validate a JWT token using the OAuth JWKS endpoint
563
- * @param {string} token
564
- * @returns {Promise<jose.JWTPayload>}
565
- * @throws {Error} if the token is invalid
566
- */
567
- validateTokens(tokens) {
568
- return __async(this, null, function* () {
569
- const endpoints = yield this.getEndpoints();
570
- const JWKS = jose.createRemoteJWKSet(new URL(endpoints.jwks));
571
- const returnPayload = {};
572
- console.log("issuer", getIssuerVariations(this.oauthServer));
573
- const idTokenResponse = yield jose.jwtVerify(tokens.id_token, JWKS, {
574
- issuer: getIssuerVariations(this.oauthServer),
575
- audience: this.clientId
576
- });
577
- returnPayload.idToken = idTokenResponse.payload;
578
- const accessTokenResponse = yield jose.jwtVerify(
579
- tokens.access_token,
580
- JWKS,
581
- {
582
- issuer: getIssuerVariations(this.oauthServer)
583
- }
584
- );
585
- returnPayload.accessToken = accessTokenResponse.payload;
586
- if (tokens.refresh_token) {
587
- returnPayload.refreshToken = tokens.refresh_token;
588
- }
589
- return returnPayload;
590
- });
591
- }
592
- validateExistingSession() {
593
- return __async(this, null, function* () {
594
- const sessionData = this.getSessionData();
595
- try {
596
- if (!sessionData.idToken || !sessionData.accessToken) {
597
- const unAuthenticatedSession = __spreadProps(__spreadValues({}, sessionData), { authenticated: false });
598
- this.updateSessionData(unAuthenticatedSession);
599
- return unAuthenticatedSession;
600
- }
601
- yield this.validateTokens({
602
- id_token: sessionData.idToken,
603
- access_token: sessionData.accessToken,
604
- refresh_token: sessionData.refreshToken
605
- });
606
- sessionData.authenticated = true;
607
- return sessionData;
608
- } catch (error) {
609
- console.warn("Failed to validate existing tokens", error);
610
- const unAuthenticatedSession = {
611
- authenticated: false
612
- };
613
- this.updateSessionData(unAuthenticatedSession);
614
- return unAuthenticatedSession;
615
- }
616
- });
617
- }
618
- };
21
+
22
+ var _chunkCRTRMMJ7js = require('./chunk-CRTRMMJ7.js');
619
23
 
620
24
  // src/nextjs/cookies.ts
621
- var createSecureTokenCookies = (response, sessionData, config) => {
622
- var _a, _b;
623
- const maxAge = (_a = sessionData.expiresIn) != null ? _a : 3600;
624
- const cookieOptions = __spreadProps(__spreadValues({}, (_b = config.cookies) == null ? void 0 : _b.tokens), {
625
- maxAge
626
- });
627
- if (sessionData.accessToken) {
628
- response.cookies.set("access_token", sessionData.accessToken, __spreadProps(__spreadValues({}, cookieOptions), {
25
+ var _headersjs = require('next/headers.js');
26
+ var clearAuthCookies = () => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
27
+ const cookieStorage = new NextjsCookieStorage();
28
+ _chunkYNLXRD5Ljs.clearTokens.call(void 0, cookieStorage);
29
+ const clientStorage = new NextjsClientStorage();
30
+ const userSession = new (0, _chunkYNLXRD5Ljs.GenericUserSession)(clientStorage);
31
+ userSession.set(null);
32
+ });
33
+ var NextjsCookieStorage = class extends _chunkKCSGIIPAjs.CookieStorage {
34
+ constructor(config = {}) {
35
+ super(_chunkCRTRMMJ7js.__spreadProps.call(void 0, _chunkCRTRMMJ7js.__spreadValues.call(void 0, {}, config), {
36
+ secure: true,
629
37
  httpOnly: true
630
38
  }));
631
39
  }
632
- if (sessionData.idToken) {
633
- response.cookies.set("id_token", sessionData.idToken, __spreadProps(__spreadValues({}, cookieOptions), {
634
- httpOnly: true
635
- }));
40
+ get(key) {
41
+ var _a;
42
+ return ((_a = _headersjs.cookies.call(void 0, ).get(key)) == null ? void 0 : _a.value) || null;
636
43
  }
637
- if (sessionData.refreshToken) {
638
- response.cookies.set("refresh_token", sessionData.refreshToken, __spreadProps(__spreadValues({}, cookieOptions), {
639
- httpOnly: true
640
- }));
44
+ set(key, value) {
45
+ _headersjs.cookies.call(void 0, ).set(key, value, this.settings);
641
46
  }
642
47
  };
643
- var createUserInfoCookie = (response, user, sessionData, config) => {
644
- var _a, _b, _c;
645
- if (!user) {
646
- response.cookies.set("user", "", __spreadProps(__spreadValues({}, (_a = config.cookies) == null ? void 0 : _a.user), {
647
- maxAge: 0
48
+ var NextjsClientStorage = class extends _chunkKCSGIIPAjs.CookieStorage {
49
+ constructor(config = {}) {
50
+ super(_chunkCRTRMMJ7js.__spreadProps.call(void 0, _chunkCRTRMMJ7js.__spreadValues.call(void 0, {}, config), {
51
+ secure: false,
52
+ httpOnly: false
648
53
  }));
649
- return;
650
- }
651
- const maxAge = (_b = sessionData.expiresIn) != null ? _b : 3600;
652
- const frontendUser = __spreadValues({}, user);
653
- response.cookies.set("user", JSON.stringify(frontendUser), __spreadProps(__spreadValues({}, (_c = config.cookies) == null ? void 0 : _c.user), {
654
- maxAge
655
- }));
656
- };
657
- var clearAuthCookies = (response, config) => {
658
- var _a, _b;
659
- const clearOptions = __spreadProps(__spreadValues({}, (_a = config.cookies) == null ? void 0 : _a.tokens), {
660
- maxAge: 0
661
- });
662
- response.cookies.set("access_token", "", clearOptions);
663
- response.cookies.set("id_token", "", clearOptions);
664
- response.cookies.set("refresh_token", "", clearOptions);
665
- response.cookies.set("codeVerifier", "", clearOptions);
666
- response.cookies.set("user", "", __spreadProps(__spreadValues({}, (_b = config.cookies) == null ? void 0 : _b.user), {
667
- maxAge: 0
668
- }));
669
- };
670
-
671
- // src/nextjs/NextJSSessionService.ts
672
- var NextJSAuthSessionServiceImpl = class extends AuthSessionServiceImpl {
673
- constructor(authConfig, request, response, inputEndpoints) {
674
- super(
675
- authConfig.clientId,
676
- authConfig.callbackUrl,
677
- authConfig.oauthServer,
678
- inputEndpoints
679
- );
680
- this.authConfig = authConfig;
681
- this.request = request;
682
- this.response = response;
683
- this.inputEndpoints = inputEndpoints;
684
- }
685
- getCodeVerifier() {
686
- const codeVerifier = (0, import_headers.cookies)().get("codeVerifier");
687
- if (!codeVerifier) {
688
- throw new Error("Code verifier not found in cookies");
689
- }
690
- return codeVerifier.value;
691
- }
692
- getSessionData() {
693
- var _a, _b, _c, _d;
694
- const authenticated = (0, import_headers.cookies)().get("access_token") !== void 0;
695
- return {
696
- authenticated,
697
- codeVerifier: (_a = (0, import_headers.cookies)().get("codeVerifier")) == null ? void 0 : _a.value,
698
- accessToken: (_b = (0, import_headers.cookies)().get("access_token")) == null ? void 0 : _b.value,
699
- idToken: (_c = (0, import_headers.cookies)().get("id_token")) == null ? void 0 : _c.value,
700
- refreshToken: (_d = (0, import_headers.cookies)().get("refresh_token")) == null ? void 0 : _d.value
701
- };
702
- }
703
- updateSessionData(data) {
704
- createSecureTokenCookies(
705
- this.response,
706
- data,
707
- this.authConfig
708
- );
709
54
  }
710
- getUser() {
711
- const userCookie = (0, import_headers.cookies)().get("user");
712
- if (!userCookie) return null;
713
- return JSON.parse(userCookie.value);
714
- }
715
- setUser(user) {
716
- createUserInfoCookie(
717
- this.response,
718
- user,
719
- { authenticated: true },
720
- this.authConfig
721
- );
722
- }
723
- clearSessionData() {
724
- clearAuthCookies(this.response, this.authConfig);
725
- }
726
- // TODO fix the Window reference
727
- loadAuthorizationUrl() {
728
- throw new Error("Not implemented");
55
+ get(key) {
56
+ var _a;
57
+ return ((_a = _headersjs.cookies.call(void 0, ).get(key)) == null ? void 0 : _a.value) || null;
729
58
  }
730
- init() {
731
- return __async(this, null, function* () {
732
- this.updateSessionData({ authenticated: false });
733
- });
59
+ set(key, value) {
60
+ _headersjs.cookies.call(void 0, ).set(key, value, this.settings);
734
61
  }
735
62
  };
736
63
 
737
- // src/nextjs/routeHandler.ts
738
- var import_oauth22 = require("oslo/oauth2");
739
- var logger2 = loggers.nextjs.handlers.auth;
740
- var AuthError = class extends Error {
741
- constructor(message, status = 401) {
742
- super(message);
743
- this.status = status;
744
- this.name = "AuthError";
745
- }
746
- };
747
- function generateCodeChallenge(codeVerifier) {
748
- return __async(this, null, function* () {
749
- const encoder = new TextEncoder();
750
- const data = encoder.encode(codeVerifier);
751
- const digest = yield crypto.subtle.digest("SHA-256", data);
752
- return btoa(String.fromCharCode(...new Uint8Array(digest))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
753
- });
754
- }
755
- function handleChallenge() {
756
- return __async(this, null, function* () {
757
- const codeVerifier = (0, import_oauth22.generateCodeVerifier)();
758
- console.log("handleChallenge codeVerifier", codeVerifier);
759
- const challenge = yield generateCodeChallenge(codeVerifier);
760
- const response = import_server.NextResponse.json({ status: "success", challenge });
761
- response.cookies.set("codeVerifier", codeVerifier, {
762
- httpOnly: true,
763
- secure: true,
764
- sameSite: "strict"
765
- });
766
- return response;
767
- });
768
- }
769
- function handleCallback(request, config) {
770
- return __async(this, null, function* () {
771
- const code = request.nextUrl.searchParams.get("code");
772
- if (!code) {
773
- throw new AuthError("Missing authorization code");
774
- }
775
- try {
776
- const response = new import_server.NextResponse(`<html></html>`);
777
- response.headers.set("Content-Type", "text/html; charset=utf-8");
778
- const resolvedConfigs = resolveAuthConfig(config);
779
- const callbackUrl = new URL(
780
- resolvedConfigs == null ? void 0 : resolvedConfigs.callbackUrl,
781
- request.url
782
- ).toString();
783
- const authService = getDefaultAuthSessionService(
784
- __spreadProps(__spreadValues({}, resolvedConfigs), {
785
- callbackUrl
786
- }),
787
- request,
788
- response
789
- );
790
- console.log("handleCallback authService", authService);
791
- const tokens = yield authService.tokenExchange(request.nextUrl.toString());
792
- if (!tokens.accessToken) {
793
- throw new AuthError("Missing access token");
794
- }
795
- return response;
796
- } catch (error) {
797
- logger2.error("Token exchange failed:", error);
798
- throw new AuthError("Failed to authenticate user", 401);
799
- }
800
- });
801
- }
802
- function handleLogout(request, config) {
803
- return __async(this, null, function* () {
804
- var _a;
805
- const resolvedConfigs = resolveAuthConfig(config);
806
- const path = (_a = resolvedConfigs.loginUrl) != null ? _a : "/";
807
- const redirectTarget = new URL(path, request.url).toString();
808
- const response = import_server.NextResponse.redirect(redirectTarget);
809
- clearAuthCookies(response, resolvedConfigs);
810
- try {
811
- (0, import_cache.revalidatePath)(path);
812
- } catch (error) {
813
- logger2.warn("Failed to revalidate path after logout:", error);
814
- }
815
- return response;
816
- });
817
- }
818
- var getDefaultAuthSessionService = (authConfig, request, response) => {
819
- return new NextJSAuthSessionServiceImpl(authConfig, request, response);
820
- };
821
- function handler(authConfig = {}) {
822
- return (request) => __async(this, null, function* () {
823
- const config = resolveAuthConfig(authConfig);
824
- try {
825
- const pathname = request.nextUrl.pathname;
826
- const pathSegments = pathname.split("/");
827
- const lastSegment = pathSegments[pathSegments.length - 1];
828
- switch (lastSegment) {
829
- case "challenge":
830
- return yield handleChallenge();
831
- case "callback":
832
- return yield handleCallback(request, config);
833
- case "logout":
834
- return yield handleLogout(request, config);
835
- default:
836
- throw new AuthError(`Invalid auth route: ${pathname}`, 404);
837
- }
838
- } catch (error) {
839
- logger2.error("Auth handler error:", error);
840
- const status = error instanceof AuthError ? error.status : 500;
841
- const message = error instanceof Error ? error.message : "Authentication failed";
842
- const response = import_server.NextResponse.json({ error: message }, { status });
843
- clearAuthCookies(response, config);
844
- return response;
845
- }
846
- });
847
- }
848
-
849
64
  // src/nextjs/GetUser.ts
850
- var import_headers2 = require("next/headers.js");
851
- var getUser = () => {
852
- var _a;
853
- const user = (_a = (0, import_headers2.cookies)().get("user")) == null ? void 0 : _a.value;
854
- if (!user) return null;
855
- return JSON.parse(user);
65
+ var getUser2 = () => {
66
+ const clientStorage = new NextjsClientStorage();
67
+ const userSession = new (0, _chunkYNLXRD5Ljs.GenericUserSession)(clientStorage);
68
+ return userSession.get();
856
69
  };
857
70
 
858
71
  // src/nextjs/middleware.ts
859
- var import_server2 = require("next/server.js");
860
- var import_picomatch = __toESM(require("picomatch"));
72
+ var _serverjs = require('next/server.js');
73
+ var _picomatch = require('picomatch'); var _picomatch2 = _interopRequireDefault(_picomatch);
861
74
  var matchGlob = (pathname, globPattern) => {
862
- const matches = (0, import_picomatch.default)(globPattern);
75
+ const matches = _picomatch2.default.call(void 0, globPattern);
863
76
  return matches(pathname);
864
77
  };
865
78
  var matchesGlobs = (pathname, patterns) => patterns.some((pattern) => {
@@ -871,8 +84,8 @@ var matchesGlobs = (pathname, patterns) => patterns.some((pattern) => {
871
84
  });
872
85
  return matchGlob(pathname, pattern);
873
86
  });
874
- var applyAuth = (authConfig, request) => __async(void 0, null, function* () {
875
- const authConfigWithDefaults = resolveAuthConfig(authConfig);
87
+ var applyAuth = (authConfig, request) => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
88
+ const authConfigWithDefaults = _chunkMVO4UZ2Ajs.resolveAuthConfig.call(void 0, authConfig);
876
89
  const isAuthenticated = !!request.cookies.get("id_token");
877
90
  if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl) {
878
91
  console.log("\u2192 Skipping auth check - this is the login URL");
@@ -889,18 +102,18 @@ var applyAuth = (authConfig, request) => __async(void 0, null, function* () {
889
102
  if (!isAuthenticated) {
890
103
  console.log("\u2192 No valid token found - redirecting to login");
891
104
  const loginUrl = new URL(authConfigWithDefaults.loginUrl, request.url);
892
- return import_server2.NextResponse.redirect(loginUrl);
105
+ return _serverjs.NextResponse.redirect(loginUrl);
893
106
  }
894
107
  console.log("\u2192 Auth check passed");
895
108
  return void 0;
896
109
  });
897
- var authMiddleware = (authConfig = defaultAuthConfig) => (request) => __async(void 0, null, function* () {
110
+ var authMiddleware = (authConfig = _chunkMVO4UZ2Ajs.defaultAuthConfig) => (request) => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
898
111
  const response = yield applyAuth(authConfig, request);
899
112
  if (response) return response;
900
- return import_server2.NextResponse.next();
113
+ return _serverjs.NextResponse.next();
901
114
  });
902
115
  function withAuth(middleware) {
903
- return (request) => __async(this, null, function* () {
116
+ return (request) => _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
904
117
  const response = yield applyAuth({}, request);
905
118
  if (response) return response;
906
119
  return middleware(request);
@@ -908,20 +121,125 @@ function withAuth(middleware) {
908
121
  }
909
122
  function auth(authConfig = {}) {
910
123
  return (middleware) => {
911
- return (request) => __async(this, null, function* () {
124
+ return (request) => _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
912
125
  const response = yield applyAuth(authConfig, request);
913
126
  if (response) return response;
914
127
  return middleware(request);
915
128
  });
916
129
  };
917
130
  }
918
- // Annotate the CommonJS export names for ESM import in node:
919
- 0 && (module.exports = {
920
- auth,
921
- authMiddleware,
922
- createCivicAuthPlugin,
923
- getUser,
924
- handler,
925
- withAuth
131
+
132
+ // src/nextjs/routeHandler.ts
133
+
134
+ var _cachejs = require('next/cache.js');
135
+ var logger = _chunkMVO4UZ2Ajs.loggers.nextjs.handlers.auth;
136
+ var AuthError = class extends Error {
137
+ constructor(message, status = 401) {
138
+ super(message);
139
+ this.status = status;
140
+ this.name = "AuthError";
141
+ }
142
+ };
143
+ function handleChallenge() {
144
+ return _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
145
+ const cookieStorage = new NextjsCookieStorage();
146
+ const pkceProducer = new (0, _chunkYNLXRD5Ljs.GenericPublicClientPKCEProducer)(cookieStorage);
147
+ const challenge = yield pkceProducer.getCodeChallenge();
148
+ return _serverjs.NextResponse.json({ status: "success", challenge });
149
+ });
150
+ }
151
+ function handleCallback(request, config) {
152
+ return _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
153
+ const tokenExchange = request.nextUrl.searchParams.get("tokenExchange");
154
+ if (!tokenExchange) {
155
+ const response2 = new (0, _serverjs.NextResponse)(`<html></html>`);
156
+ response2.headers.set("Content-Type", "text/html; charset=utf-8");
157
+ return response2;
158
+ }
159
+ const code = request.nextUrl.searchParams.get("code");
160
+ const state = request.nextUrl.searchParams.get("state");
161
+ if (!code || !state) throw new AuthError("Bad parameters", 400);
162
+ const cookieStorage = new NextjsCookieStorage();
163
+ const resolvedConfigs = _chunkMVO4UZ2Ajs.resolveAuthConfig.call(void 0, config);
164
+ const callbackUrl = _chunkMVO4UZ2Ajs.resolveCallbackUrl.call(void 0, resolvedConfigs, request.url);
165
+ try {
166
+ yield _chunkKCSGIIPAjs.resolveOAuthAccessCode.call(void 0, code, state, cookieStorage, _chunkCRTRMMJ7js.__spreadProps.call(void 0, _chunkCRTRMMJ7js.__spreadValues.call(void 0, {}, resolvedConfigs), {
167
+ redirectUrl: callbackUrl
168
+ }));
169
+ } catch (error) {
170
+ logger.error("Token exchange failed:", error);
171
+ throw new AuthError("Failed to authenticate user", 401);
172
+ }
173
+ const user = yield _chunkYNLXRD5Ljs.getUser.call(void 0, cookieStorage);
174
+ if (!user) {
175
+ throw new AuthError("Failed to get user info", 401);
176
+ }
177
+ const clientStorage = new NextjsClientStorage();
178
+ const userSession = new (0, _chunkYNLXRD5Ljs.GenericUserSession)(clientStorage);
179
+ userSession.set(user);
180
+ const response = new (0, _serverjs.NextResponse)(`<html></html>`);
181
+ response.headers.set("Content-Type", "text/html; charset=utf-8");
182
+ return response;
183
+ });
184
+ }
185
+ var getAbsoluteRedirectPath = (redirectPath, currentBasePath) => {
186
+ if (/^(https?:\/\/|www\.).+/i.test(redirectPath)) {
187
+ return redirectPath;
188
+ }
189
+ return new URL(redirectPath, currentBasePath).href;
190
+ };
191
+ function handleLogout(request, config) {
192
+ return _chunkCRTRMMJ7js.__async.call(void 0, this, null, function* () {
193
+ var _a;
194
+ const resolvedConfigs = _chunkMVO4UZ2Ajs.resolveAuthConfig.call(void 0, config);
195
+ const defaultRedirectPath = (_a = resolvedConfigs.loginUrl) != null ? _a : "/";
196
+ const redirectTarget = new URL(request.url).searchParams.get("redirect") || defaultRedirectPath;
197
+ const isAbsoluteRedirect = /^(https?:\/\/|www\.).+/i.test(redirectTarget);
198
+ const finalRedirectUrl = getAbsoluteRedirectPath(
199
+ redirectTarget,
200
+ new URL(request.url).origin
201
+ );
202
+ const response = _serverjs.NextResponse.redirect(finalRedirectUrl);
203
+ clearAuthCookies();
204
+ try {
205
+ _cachejs.revalidatePath.call(void 0, isAbsoluteRedirect ? finalRedirectUrl : redirectTarget);
206
+ } catch (error) {
207
+ logger.warn("Failed to revalidate path after logout:", error);
208
+ }
209
+ return response;
210
+ });
211
+ }
212
+ var handler = (authConfig = {}) => (request) => _chunkCRTRMMJ7js.__async.call(void 0, void 0, null, function* () {
213
+ const config = _chunkMVO4UZ2Ajs.resolveAuthConfig.call(void 0, authConfig);
214
+ try {
215
+ const pathname = request.nextUrl.pathname;
216
+ const pathSegments = pathname.split("/");
217
+ const lastSegment = pathSegments[pathSegments.length - 1];
218
+ switch (lastSegment) {
219
+ case "challenge":
220
+ return yield handleChallenge();
221
+ case "callback":
222
+ return yield handleCallback(request, config);
223
+ case "logout":
224
+ return yield handleLogout(request, config);
225
+ default:
226
+ throw new AuthError(`Invalid auth route: ${pathname}`, 404);
227
+ }
228
+ } catch (error) {
229
+ logger.error("Auth handler error:", error);
230
+ const status = error instanceof AuthError ? error.status : 500;
231
+ const message = error instanceof Error ? error.message : "Authentication failed";
232
+ const response = _serverjs.NextResponse.json({ error: message }, { status });
233
+ clearAuthCookies();
234
+ return response;
235
+ }
926
236
  });
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+ exports.auth = auth; exports.authMiddleware = authMiddleware; exports.createCivicAuthPlugin = _chunkMVO4UZ2Ajs.createCivicAuthPlugin; exports.getUser = getUser2; exports.handler = handler; exports.withAuth = withAuth;
927
245
  //# sourceMappingURL=nextjs.js.map