@civic/auth 0.5.4-beta.1 → 0.5.5-beta.0

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 (49) hide show
  1. package/CHANGELOG.md +50 -6
  2. package/dist/constants.d.ts +2 -1
  3. package/dist/constants.d.ts.map +1 -1
  4. package/dist/constants.js +2 -1
  5. package/dist/constants.js.map +1 -1
  6. package/dist/lib/oauth.d.ts +8 -2
  7. package/dist/lib/oauth.d.ts.map +1 -1
  8. package/dist/lib/oauth.js +8 -10
  9. package/dist/lib/oauth.js.map +1 -1
  10. package/dist/nextjs/config.d.ts +3 -0
  11. package/dist/nextjs/config.d.ts.map +1 -1
  12. package/dist/nextjs/config.js +3 -0
  13. package/dist/nextjs/config.js.map +1 -1
  14. package/dist/nextjs/providers/NextAuthProvider.d.ts.map +1 -1
  15. package/dist/nextjs/providers/NextAuthProvider.js +2 -2
  16. package/dist/nextjs/providers/NextAuthProvider.js.map +1 -1
  17. package/dist/nextjs/routeHandler.d.ts.map +1 -1
  18. package/dist/nextjs/routeHandler.js +157 -103
  19. package/dist/nextjs/routeHandler.js.map +1 -1
  20. package/dist/reactjs/components/UserButton.d.ts.map +1 -1
  21. package/dist/reactjs/components/UserButton.js +1 -0
  22. package/dist/reactjs/components/UserButton.js.map +1 -1
  23. package/dist/services/AuthenticationService.d.ts +1 -0
  24. package/dist/services/AuthenticationService.d.ts.map +1 -1
  25. package/dist/services/AuthenticationService.js +5 -1
  26. package/dist/services/AuthenticationService.js.map +1 -1
  27. package/dist/shared/components/CivicAuthIframeContainer.d.ts.map +1 -1
  28. package/dist/shared/components/CivicAuthIframeContainer.js +5 -1
  29. package/dist/shared/components/CivicAuthIframeContainer.js.map +1 -1
  30. package/dist/shared/components/CivicAuthLogoutIframeContainer.d.ts.map +1 -1
  31. package/dist/shared/components/CivicAuthLogoutIframeContainer.js +31 -1
  32. package/dist/shared/components/CivicAuthLogoutIframeContainer.js.map +1 -1
  33. package/dist/shared/components/IFrameAndLoading.d.ts.map +1 -1
  34. package/dist/shared/components/IFrameAndLoading.js +11 -1
  35. package/dist/shared/components/IFrameAndLoading.js.map +1 -1
  36. package/dist/shared/hooks/useSignIn.d.ts.map +1 -1
  37. package/dist/shared/hooks/useSignIn.js +2 -1
  38. package/dist/shared/hooks/useSignIn.js.map +1 -1
  39. package/dist/shared/lib/types.d.ts +1 -0
  40. package/dist/shared/lib/types.d.ts.map +1 -1
  41. package/dist/shared/lib/types.js.map +1 -1
  42. package/dist/shared/providers/CivicAuthConfigContext.d.ts +2 -1
  43. package/dist/shared/providers/CivicAuthConfigContext.d.ts.map +1 -1
  44. package/dist/shared/providers/CivicAuthConfigContext.js +3 -1
  45. package/dist/shared/providers/CivicAuthConfigContext.js.map +1 -1
  46. package/dist/shared/version.d.ts +1 -1
  47. package/dist/shared/version.js +1 -1
  48. package/dist/shared/version.js.map +1 -1
  49. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,76 +1,107 @@
1
+ # 0.5.5 loginSuccessUrl property
2
+ - Add a new setting for loginSuccessUrl in NextJS, redirecting the user to a page of the customer's choice after login
3
+ - Fix bug where logout would hang in modes other than iframe.
4
+
5
+ # 0.5.4 Sign In Promise Fix
6
+
7
+ - Fix Sign In Promise Fix
8
+
9
+ # 0.5.3 UserButton component styling
10
+
11
+ - fix the UserButton styling to make it look better with darkmode and more consistent with the other buttons.
12
+
1
13
  # 0.5.2 Fix NextJS multiple router refresh bug
14
+
2
15
  - fix a bug that was causing the NextJS router to refresh multiple times post-login
3
16
 
4
17
  # 0.5.1 Fix issue with typescript config
18
+
5
19
  - allow cookies to be partially defined in the config
6
20
 
7
21
  # 0.5.0 NextJS fetch user fixes & basePath config support
22
+
8
23
  - when the NextJS provider loads if the user is already authenticated the user should be available immediately
9
24
  - block UI display correctly in iframe when the SDK loads in app during NextJS flow
10
25
  - use useIsClient from usehooks-ts
11
- - add support for a basePath config where it was not being correctly applied to the logout callback URL
26
+ - add support for a basePath config where it was not being correctly applied to the logout callback URL
12
27
 
13
28
  # 0.4.7 Standalone react fixes
29
+
14
30
  - Fix case where standalone react app isn't recognising existing session
15
31
  - Fix react standalone case where it's initiating startSignIn twice leading to duplicate calls to the auth-server
16
32
  - Add refresh timeout in useSignIn for initial signIn call so that the code-verifier doesn't get stale if the user leaves the tab open on a page and doesn't sign in right away
17
33
 
18
34
  # 0.4.6 Refresh fixes
35
+
19
36
  - if a valid refresh token exists, automatically try to re-hydrate the user's session by doing an oauth refresh
20
37
 
21
38
  # 0.4.5 Block display fix
39
+
22
40
  - if the iframe has already been used on a page and it's re-opened we shouldn't show the previous app content
23
41
 
24
42
  # 0.4.4 Custom civic iframe resizer (fix)
43
+
25
44
  - use a custom civic-iframe-resizer to avoid the problems and warnings with the commercial resizer
26
45
  - fix positioning of iframe overlay
27
46
 
28
47
  # 0.4.3 Custom civic iframe resizer
48
+
29
49
  - use a custom civic-iframe-resizer to avoid the problems and warnings with the commercial resizer
30
50
 
31
51
  # 0.4.2 Download iframe-resizer & fix infinite redirect loop in NextJS
52
+
32
53
  - download iframe-resizer lib as it was failing to resize on load
33
54
  - don't use dynamic API in NextJS middleware as it's not supported
34
55
 
35
56
  # 0.4.1 NextJS server function token validation
57
+
36
58
  - add existing validation to NextJS server functions, getUser and getTokens. Also exposes a new NextJS server function 'isLoggedIn'
37
-
59
+
38
60
  # 0.4.0 server-side token validation
61
+
39
62
  - add server-side token validation to any calls to check whether the user is authenticated
40
63
  - implement and expose a server/CivicAuth class that exposes methods without needing to add config and storage to every call
41
64
 
42
65
  # 0.3.8 Fix NextJS cookie expiration behaviour
66
+
43
67
  - fix the civic-auth SDK NextJS cookie expiration behaviour for embedded iframes: when the iframe mounts, it will trigger the auto sign-in process to start again
44
68
  - change NextJS console.logs to logger.debug statements
45
69
 
46
70
  # 0.3.7 Fix user auth refresh
71
+
47
72
  - Fix issue where a 500 occurred during token refresh
48
- - UI fixes
73
+ - UI fixes
49
74
 
50
75
  # 0.3.6 Remove CJS build
76
+
51
77
  - Remove CommonJS build from @civic/auth
52
78
 
53
79
  # 0.3.5 NextJS middleware redirect fix + Iframe padding + use-client fixes
80
+
54
81
  - remove padding and background colours on iframe wrapper: the login-app must handle its own padding and background colour to support light/dark mode
55
82
  - fix issue where 'use client' was required to use the CivicProvider in react apps
56
83
  - fix NextJS middleware so that visiting a page with an expired idToken doesn't trigger a redirect loop
57
84
  - accept design options messages from the login-app via postMessage in order to set the color-mode for the iframe chrome
58
85
 
59
86
  # 0.3.4 Refresh bugfix, Update User type
87
+
60
88
  - Update User type to correctly support type extensions
61
89
  - User Button: Show a loading state if the user initiates an action and is authenticating or signing out
62
90
  - Prevent multiple in-flight refresh requests
63
91
 
64
92
  # 0.3.3 fix user cookie refresh
65
- - Ensured that the critical path "/api/auth/**" is always included in the exclude list, enhancing security by preventing accidental exposure of authentication endpoints
93
+
94
+ - Ensured that the critical path "/api/auth/\*\*" is always included in the exclude list, enhancing security by preventing accidental exposure of authentication endpoints
66
95
  - Allowed the include list to be completely replaced by user-provided configurations, maintaining flexibility without compromising security.
67
96
 
68
97
  # 0.3.1 iframe-modal mode start authentication in background
98
+
69
99
  - for displayMode = 'iframe', start authentication in the background on page load for fast perceived login-app loading
70
100
  - upgrade iframe resizer to 5.3.3
71
101
  - fix bug in NextJSCookies storage where the call to cookies() wasn't awaited
72
102
 
73
103
  # 0.3.0 iframe resizer support
104
+
74
105
  - add support for auto-resizing the login-app iframe using the react iframe resizer library
75
106
  - rename NextKS cookie EXPIRES_IN -> ACCESS_TOKEN_EXPIRES_AT
76
107
  - user session fixes
@@ -79,52 +110,65 @@
79
110
  - fix compilation to only include src directory
80
111
 
81
112
  # 0.2.5 fix idToken retrieval from cookie storage
113
+
82
114
  - fix a bug where the client was trying to retrieve the idToken using the server-only cookies() method
83
115
  - fix an issue with the build including the src and test files in the package
84
116
 
85
117
  # 0.2.4 fix multiple auth-signIn calls
118
+
86
119
  - fix a bug where signIn is called multiple times in embedded iframe mode
87
120
 
88
121
  # 0.2.3 remove unnecessary logging
122
+
89
123
  - remove unnecessary logging
90
124
 
91
125
  # 0.2.2 authStatus and UserButton updates
126
+
92
127
  - expose authStatus value from useUser
93
128
  - show loading icon in UserButton, SignInButton and SignOutButton during sign in and sign out
94
129
 
95
130
  # 0.2.1 Server getTokens
131
+
96
132
  - expose server/getTokens function
97
133
  - remove unused SDK exports
98
134
  - Add support for showing error messages in the IDP
99
-
135
+
100
136
  # 0.2.0 Refresh and Logout improvements
137
+
101
138
  - improve the token auto-refresh funcionality
102
139
  - improve logout functionality and added redirect on logout
103
140
 
104
141
  # 0.1.6 Fix printVersion usage
142
+
105
143
  - Only print the SDK version once
106
144
  - fix useUserCookie re-rendering too often
107
145
  - add auto-refresh to nextjs and standalone providers
108
146
 
109
147
  # 0.1.5 Logout updates and faster user cookie retrieval
148
+
110
149
  - Implement client & auth-server logout functionality to invalidate tokens on logout
111
150
  - fetch the user on component mount for faster useUserCookie user retrieval
112
151
 
113
- # 0.1.4 Refactor hooks and providers
152
+ # 0.1.4 Refactor hooks and providers
153
+
114
154
  - Refactor the internal hooks and providers implementation
115
155
  - change modalIframe prop to new iframeMode that can be either 'embedded' or 'modal' (default)
116
156
  - output the current lib version to the command line
117
157
 
118
158
  # 0.1.3 Update README
159
+
119
160
  - Synchronise the README with docs.civic.com
120
161
 
121
162
  # 0.1.2 Fix AuthConfig defaults
163
+
122
164
  - Update AuthConfig type to make oauthServer optional
123
165
  - Export AuthConfig type from server
124
166
  - Make next an optional rather than a peer dependency
125
167
 
126
168
  # 0.1.1 Fix Firefox loading overlay issues
169
+
127
170
  - Iframe loading overlay was obscuring loaded login app in Firefox
128
171
 
129
172
  # 0.1.0 Initial release
173
+
130
174
  - Authentication using PKCE for standalone ReactJS and NextJS apps
@@ -4,6 +4,7 @@ declare const DEFAULT_OAUTH_GET_PARAMS: string[];
4
4
  declare const DEFAULT_EXPIRES_IN = 3600;
5
5
  declare const TOKEN_EXCHANGE_TRIGGER_TEXT = "sameDomainCodeExchangeRequired";
6
6
  declare const TOKEN_EXCHANGE_SUCCESS_TEXT = "serverSideTokenExchangeSuccess";
7
+ declare const LOGOUT_SUCCESS_TEXT = "serverSideLogoutSuccess";
7
8
  declare const DEFAULT_DISPLAY_MODE = "iframe";
8
9
  declare const JWT_PAYLOAD_KNOWN_CLAIM_KEYS: readonly ["iss", "aud", "sub", "iat", "exp"];
9
10
  declare const AUTOREFRESH_TIMEOUT_NAME = "civicAuthAutorefreshTimeout";
@@ -11,5 +12,5 @@ declare const REFRESH_IN_PROGRESS = "civicAuthRefreshInProgress";
11
12
  declare const LOGOUT_STATE = "logout_state";
12
13
  declare const DARK_BACKGROUND_COLOR = "rgb(30, 41, 59)";
13
14
  declare const LIGHT_BACKGROUND_COLOR = "white";
14
- export { DEFAULT_SCOPES, DEFAULT_OAUTH_GET_PARAMS, DEFAULT_DISPLAY_MODE, DEFAULT_AUTH_SERVER, DEFAULT_EXPIRES_IN, TOKEN_EXCHANGE_TRIGGER_TEXT, TOKEN_EXCHANGE_SUCCESS_TEXT, JWT_PAYLOAD_KNOWN_CLAIM_KEYS, AUTOREFRESH_TIMEOUT_NAME, REFRESH_IN_PROGRESS, DARK_BACKGROUND_COLOR, LIGHT_BACKGROUND_COLOR, LOGOUT_STATE, };
15
+ export { DEFAULT_SCOPES, DEFAULT_OAUTH_GET_PARAMS, DEFAULT_DISPLAY_MODE, DEFAULT_AUTH_SERVER, DEFAULT_EXPIRES_IN, TOKEN_EXCHANGE_TRIGGER_TEXT, TOKEN_EXCHANGE_SUCCESS_TEXT, LOGOUT_SUCCESS_TEXT, JWT_PAYLOAD_KNOWN_CLAIM_KEYS, AUTOREFRESH_TIMEOUT_NAME, REFRESH_IN_PROGRESS, DARK_BACKGROUND_COLOR, LIGHT_BACKGROUND_COLOR, LOGOUT_STATE, };
15
16
  //# sourceMappingURL=constants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"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B,+BAA+B,CAAC;AACzD,QAAA,MAAM,YAAY,iBAAiB,CAAC;AACpC,QAAA,MAAM,qBAAqB,oBAAoB,CAAC;AAChD,QAAA,MAAM,sBAAsB,UAAU,CAAC;AACvC,OAAO,EACL,cAAc,EACd,wBAAwB,EACxB,oBAAoB,EACpB,mBAAmB,EACnB,kBAAkB,EAClB,2BAA2B,EAC3B,2BAA2B,EAC3B,mBAAmB,EACnB,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,qBAAqB,EACrB,sBAAsB,EACtB,YAAY,GACb,CAAC"}
package/dist/constants.js CHANGED
@@ -12,6 +12,7 @@ const DEFAULT_EXPIRES_IN = 3600; // 1 hour in seconds
12
12
  // for the iframe case where cookies are not sent along with the initial redirect.
13
13
  const TOKEN_EXCHANGE_TRIGGER_TEXT = "sameDomainCodeExchangeRequired";
14
14
  const TOKEN_EXCHANGE_SUCCESS_TEXT = "serverSideTokenExchangeSuccess";
15
+ const LOGOUT_SUCCESS_TEXT = "serverSideLogoutSuccess";
15
16
  const DEFAULT_DISPLAY_MODE = "iframe";
16
17
  const JWT_PAYLOAD_KNOWN_CLAIM_KEYS = [
17
18
  "iss",
@@ -25,5 +26,5 @@ const REFRESH_IN_PROGRESS = "civicAuthRefreshInProgress";
25
26
  const LOGOUT_STATE = "logout_state";
26
27
  const DARK_BACKGROUND_COLOR = "rgb(30, 41, 59)";
27
28
  const LIGHT_BACKGROUND_COLOR = "white";
28
- export { DEFAULT_SCOPES, DEFAULT_OAUTH_GET_PARAMS, DEFAULT_DISPLAY_MODE, DEFAULT_AUTH_SERVER, DEFAULT_EXPIRES_IN, TOKEN_EXCHANGE_TRIGGER_TEXT, TOKEN_EXCHANGE_SUCCESS_TEXT, JWT_PAYLOAD_KNOWN_CLAIM_KEYS, AUTOREFRESH_TIMEOUT_NAME, REFRESH_IN_PROGRESS, DARK_BACKGROUND_COLOR, LIGHT_BACKGROUND_COLOR, LOGOUT_STATE, };
29
+ export { DEFAULT_SCOPES, DEFAULT_OAUTH_GET_PARAMS, DEFAULT_DISPLAY_MODE, DEFAULT_AUTH_SERVER, DEFAULT_EXPIRES_IN, TOKEN_EXCHANGE_TRIGGER_TEXT, TOKEN_EXCHANGE_SUCCESS_TEXT, LOGOUT_SUCCESS_TEXT, JWT_PAYLOAD_KNOWN_CLAIM_KEYS, AUTOREFRESH_TIMEOUT_NAME, REFRESH_IN_PROGRESS, DARK_BACKGROUND_COLOR, LIGHT_BACKGROUND_COLOR, LOGOUT_STATE, };
29
30
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,MAAM,cAAc,GAAG;IACrB,QAAQ;IACR,SAAS;IACT,OAAO;IACP,iBAAiB;IACjB,gBAAgB;CACjB,CAAC;AACF,MAAM,mBAAmB,GAAG,8BAA8B,CAAC;AAE3D,MAAM,wBAAwB,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAE1D,MAAM,kBAAkB,GAAG,IAAI,CAAC,CAAC,oBAAoB;AAErD,uHAAuH;AACvH,kFAAkF;AAClF,MAAM,2BAA2B,GAAG,gCAAgC,CAAC;AAErE,MAAM,2BAA2B,GAAG,gCAAgC,CAAC;AAErE,MAAM,oBAAoB,GAAG,QAAQ,CAAC;AACtC,MAAM,4BAA4B,GAAG;IACnC,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;CACG,CAAC;AAEX,MAAM,wBAAwB,GAAG,6BAA6B,CAAC;AAC/D,MAAM,mBAAmB,GAAG,4BAA4B,CAAC;AACzD,MAAM,YAAY,GAAG,cAAc,CAAC;AACpC,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAChD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AACvC,OAAO,EACL,cAAc,EACd,wBAAwB,EACxB,oBAAoB,EACpB,mBAAmB,EACnB,kBAAkB,EAClB,2BAA2B,EAC3B,2BAA2B,EAC3B,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,qBAAqB,EACrB,sBAAsB,EACtB,YAAY,GACb,CAAC","sourcesContent":["const DEFAULT_SCOPES = [\n \"openid\",\n \"profile\",\n \"email\",\n \"forwardedTokens\",\n \"offline_access\",\n];\nconst DEFAULT_AUTH_SERVER = \"https://auth.civic.com/oauth\";\n\nconst DEFAULT_OAUTH_GET_PARAMS = [\"code\", \"state\", \"iss\"];\n\nconst DEFAULT_EXPIRES_IN = 3600; // 1 hour in seconds\n\n// The server's callback handler renders this text if it needs the front-end to make an additional token exchange call,\n// for the iframe case where cookies are not sent along with the initial redirect.\nconst TOKEN_EXCHANGE_TRIGGER_TEXT = \"sameDomainCodeExchangeRequired\";\n\nconst TOKEN_EXCHANGE_SUCCESS_TEXT = \"serverSideTokenExchangeSuccess\";\n\nconst DEFAULT_DISPLAY_MODE = \"iframe\";\nconst JWT_PAYLOAD_KNOWN_CLAIM_KEYS = [\n \"iss\",\n \"aud\",\n \"sub\",\n \"iat\",\n \"exp\",\n] as const;\n\nconst AUTOREFRESH_TIMEOUT_NAME = \"civicAuthAutorefreshTimeout\";\nconst REFRESH_IN_PROGRESS = \"civicAuthRefreshInProgress\";\nconst LOGOUT_STATE = \"logout_state\";\nconst DARK_BACKGROUND_COLOR = \"rgb(30, 41, 59)\";\nconst LIGHT_BACKGROUND_COLOR = \"white\";\nexport {\n DEFAULT_SCOPES,\n DEFAULT_OAUTH_GET_PARAMS,\n DEFAULT_DISPLAY_MODE,\n DEFAULT_AUTH_SERVER,\n DEFAULT_EXPIRES_IN,\n TOKEN_EXCHANGE_TRIGGER_TEXT,\n TOKEN_EXCHANGE_SUCCESS_TEXT,\n JWT_PAYLOAD_KNOWN_CLAIM_KEYS,\n AUTOREFRESH_TIMEOUT_NAME,\n REFRESH_IN_PROGRESS,\n DARK_BACKGROUND_COLOR,\n LIGHT_BACKGROUND_COLOR,\n LOGOUT_STATE,\n};\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,MAAM,cAAc,GAAG;IACrB,QAAQ;IACR,SAAS;IACT,OAAO;IACP,iBAAiB;IACjB,gBAAgB;CACjB,CAAC;AACF,MAAM,mBAAmB,GAAG,8BAA8B,CAAC;AAE3D,MAAM,wBAAwB,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAE1D,MAAM,kBAAkB,GAAG,IAAI,CAAC,CAAC,oBAAoB;AAErD,uHAAuH;AACvH,kFAAkF;AAClF,MAAM,2BAA2B,GAAG,gCAAgC,CAAC;AAErE,MAAM,2BAA2B,GAAG,gCAAgC,CAAC;AAErE,MAAM,mBAAmB,GAAG,yBAAyB,CAAC;AAEtD,MAAM,oBAAoB,GAAG,QAAQ,CAAC;AACtC,MAAM,4BAA4B,GAAG;IACnC,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;CACG,CAAC;AAEX,MAAM,wBAAwB,GAAG,6BAA6B,CAAC;AAC/D,MAAM,mBAAmB,GAAG,4BAA4B,CAAC;AACzD,MAAM,YAAY,GAAG,cAAc,CAAC;AACpC,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAChD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AACvC,OAAO,EACL,cAAc,EACd,wBAAwB,EACxB,oBAAoB,EACpB,mBAAmB,EACnB,kBAAkB,EAClB,2BAA2B,EAC3B,2BAA2B,EAC3B,mBAAmB,EACnB,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,qBAAqB,EACrB,sBAAsB,EACtB,YAAY,GACb,CAAC","sourcesContent":["const DEFAULT_SCOPES = [\n \"openid\",\n \"profile\",\n \"email\",\n \"forwardedTokens\",\n \"offline_access\",\n];\nconst DEFAULT_AUTH_SERVER = \"https://auth.civic.com/oauth\";\n\nconst DEFAULT_OAUTH_GET_PARAMS = [\"code\", \"state\", \"iss\"];\n\nconst DEFAULT_EXPIRES_IN = 3600; // 1 hour in seconds\n\n// The server's callback handler renders this text if it needs the front-end to make an additional token exchange call,\n// for the iframe case where cookies are not sent along with the initial redirect.\nconst TOKEN_EXCHANGE_TRIGGER_TEXT = \"sameDomainCodeExchangeRequired\";\n\nconst TOKEN_EXCHANGE_SUCCESS_TEXT = \"serverSideTokenExchangeSuccess\";\n\nconst LOGOUT_SUCCESS_TEXT = \"serverSideLogoutSuccess\";\n\nconst DEFAULT_DISPLAY_MODE = \"iframe\";\nconst JWT_PAYLOAD_KNOWN_CLAIM_KEYS = [\n \"iss\",\n \"aud\",\n \"sub\",\n \"iat\",\n \"exp\",\n] as const;\n\nconst AUTOREFRESH_TIMEOUT_NAME = \"civicAuthAutorefreshTimeout\";\nconst REFRESH_IN_PROGRESS = \"civicAuthRefreshInProgress\";\nconst LOGOUT_STATE = \"logout_state\";\nconst DARK_BACKGROUND_COLOR = \"rgb(30, 41, 59)\";\nconst LIGHT_BACKGROUND_COLOR = \"white\";\nexport {\n DEFAULT_SCOPES,\n DEFAULT_OAUTH_GET_PARAMS,\n DEFAULT_DISPLAY_MODE,\n DEFAULT_AUTH_SERVER,\n DEFAULT_EXPIRES_IN,\n TOKEN_EXCHANGE_TRIGGER_TEXT,\n TOKEN_EXCHANGE_SUCCESS_TEXT,\n LOGOUT_SUCCESS_TEXT,\n JWT_PAYLOAD_KNOWN_CLAIM_KEYS,\n AUTOREFRESH_TIMEOUT_NAME,\n REFRESH_IN_PROGRESS,\n DARK_BACKGROUND_COLOR,\n LIGHT_BACKGROUND_COLOR,\n LOGOUT_STATE,\n};\n"]}
@@ -6,7 +6,12 @@ declare const getOauthEndpoints: (oauthServer: string) => Promise<Endpoints>;
6
6
  * @param {DisplayMode} displayMode
7
7
  * @returns {string}
8
8
  */
9
- declare const generateState: (displayMode: DisplayMode, serverTokenExchange?: boolean) => string;
9
+ type GenerateStateInput = {
10
+ displayMode: DisplayMode;
11
+ serverTokenExchange?: boolean;
12
+ loginSuccessUrl?: string;
13
+ };
14
+ declare const generateState: ({ displayMode, serverTokenExchange, loginSuccessUrl, }: GenerateStateInput) => string;
10
15
  /**
11
16
  * parses the state string from the OAuth2 flow, decoding the display mode too
12
17
  * @param state
@@ -15,5 +20,6 @@ declare const generateState: (displayMode: DisplayMode, serverTokenExchange?: bo
15
20
  */
16
21
  declare const displayModeFromState: (state: string, sessionDisplayMode: DisplayMode | undefined) => DisplayMode | undefined;
17
22
  declare const serverTokenExchangeFromState: (state: string) => boolean | undefined;
18
- export { serverTokenExchangeFromState, getIssuerVariations, getOauthEndpoints, displayModeFromState, generateState, };
23
+ declare const loginSuccessUrlFromState: (state: string | null) => string | undefined;
24
+ export { serverTokenExchangeFromState, loginSuccessUrlFromState, getIssuerVariations, getOauthEndpoints, displayModeFromState, generateState, };
19
25
  //# sourceMappingURL=oauth.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/lib/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAuB,MAAM,YAAY,CAAC;AAG9E,QAAA,MAAM,mBAAmB,WAAY,MAAM,KAAG,MAAM,EAQnD,CAAC;AAMF,QAAA,MAAM,iBAAiB,gBAAuB,MAAM,KAAG,OAAO,CAAC,SAAS,CAmBvE,CAAC;AAEF;;;;GAIG;AACH,QAAA,MAAM,aAAa,gBACJ,WAAW,wBACF,OAAO,KAC5B,MAOF,CAAC;AAEF;;;;;GAKG;AACH,QAAA,MAAM,oBAAoB,UACjB,MAAM,sBACO,WAAW,GAAG,SAAS,KAC1C,WAAW,GAAG,SAQhB,CAAC;AAEF,QAAA,MAAM,4BAA4B,UAAW,MAAM,KAAG,OAAO,GAAG,SAQ/D,CAAC;AAEF,OAAO,EACL,4BAA4B,EAC5B,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,aAAa,GACd,CAAC"}
1
+ {"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/lib/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAuB,MAAM,YAAY,CAAC;AAG9E,QAAA,MAAM,mBAAmB,WAAY,MAAM,KAAG,MAAM,EAQnD,CAAC;AAMF,QAAA,MAAM,iBAAiB,gBAAuB,MAAM,KAAG,OAAO,CAAC,SAAS,CAmBvE,CAAC;AAEF;;;;GAIG;AACH,KAAK,kBAAkB,GAAG;IACxB,WAAW,EAAE,WAAW,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AACF,QAAA,MAAM,aAAa,2DAIhB,kBAAkB,KAAG,MAQvB,CAAC;AAEF;;;;;GAKG;AACH,QAAA,MAAM,oBAAoB,UACjB,MAAM,sBACO,WAAW,GAAG,SAAS,KAC1C,WAAW,GAAG,SAQhB,CAAC;AAcF,QAAA,MAAM,4BAA4B,UAAW,MAAM,KAAG,OAAO,GAAG,SACvB,CAAC;AAC1C,QAAA,MAAM,wBAAwB,UAAW,MAAM,GAAG,IAAI,KAAG,MAAM,GAAG,SACT,CAAC;AAE1D,OAAO,EACL,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,aAAa,GACd,CAAC"}
package/dist/lib/oauth.js CHANGED
@@ -24,16 +24,12 @@ const getOauthEndpoints = async (oauthServer) => {
24
24
  cache[oauthServer] = endpoints;
25
25
  return endpoints;
26
26
  };
27
- /**
28
- * creates a state string for the OAuth2 flow, encoding the display mode too for future use
29
- * @param {DisplayMode} displayMode
30
- * @returns {string}
31
- */
32
- const generateState = (displayMode, serverTokenExchange) => {
27
+ const generateState = ({ displayMode, serverTokenExchange, loginSuccessUrl, }) => {
33
28
  const jsonString = JSON.stringify({
34
29
  uuid: uuid(),
35
30
  displayMode,
36
31
  ...(serverTokenExchange ? { serverTokenExchange } : {}),
32
+ ...(loginSuccessUrl ? { loginSuccessUrl } : {}),
37
33
  });
38
34
  return btoa(jsonString);
39
35
  };
@@ -53,15 +49,17 @@ const displayModeFromState = (state, sessionDisplayMode) => {
53
49
  return sessionDisplayMode;
54
50
  }
55
51
  };
56
- const serverTokenExchangeFromState = (state) => {
52
+ const decodeState = (state) => {
57
53
  try {
58
54
  const jsonString = atob(state);
59
- return JSON.parse(jsonString).serverTokenExchange;
55
+ return JSON.parse(jsonString);
60
56
  }
61
57
  catch {
62
- console.error("Failed to parse serverTokenExchange from state:", state);
58
+ console.error("Failed to parse state string to json:", state);
63
59
  return undefined;
64
60
  }
65
61
  };
66
- export { serverTokenExchangeFromState, getIssuerVariations, getOauthEndpoints, displayModeFromState, generateState, };
62
+ const serverTokenExchangeFromState = (state) => decodeState(state)?.serverTokenExchange;
63
+ const loginSuccessUrlFromState = (state) => state ? decodeState(state)?.loginSuccessUrl : undefined;
64
+ export { serverTokenExchangeFromState, loginSuccessUrlFromState, getIssuerVariations, getOauthEndpoints, displayModeFromState, generateState, };
67
65
  //# sourceMappingURL=oauth.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../src/lib/oauth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAC;AAElC,MAAM,mBAAmB,GAAG,CAAC,MAAc,EAAY,EAAE;IACvD,MAAM,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;QAC7C,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;QACpC,CAAC,CAAC,MAAM,CAAC;IAEX,MAAM,eAAe,GAAG,GAAG,kBAAkB,GAAG,CAAC;IAEjD,OAAO,CAAC,kBAAkB,EAAE,eAAe,CAAC,CAAC;AAC/C,CAAC,CAAC;AAEF,MAAM,gBAAgB,GAAG,CAAC,GAAW,EAAU,EAAE,CAC/C,GAAG,CAAC,QAA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M,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;QAC/B,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,WAAW,CAAC;IAC5C,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,CAAC,KAAK,CAAC,yCAAyC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QACnE,OAAO,kBAAkB,CAAC;IAC5B,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,4BAA4B,GAAG,CAAC,KAAa,EAAuB,EAAE;IAC1E,IAAI,CAAC;QACH,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;QAC/B,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,mBAAmB,CAAC;IACpD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,CAAC,KAAK,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;QACxE,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC,CAAC;AAEF,OAAO,EACL,4BAA4B,EAC5B,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,aAAa,GACd,CAAC","sourcesContent":["import type { DisplayMode, Endpoints, OpenIdConfiguration } from \"@/types.js\";\nimport { v4 as uuid } from \"uuid\";\n\nconst getIssuerVariations = (issuer: string): string[] => {\n const issuerWithoutSlash = issuer.endsWith(\"/\")\n ? issuer.slice(0, issuer.length - 1)\n : issuer;\n\n const issuerWithSlash = `${issuerWithoutSlash}/`;\n\n return [issuerWithoutSlash, issuerWithSlash];\n};\n\nconst addSlashIfNeeded = (url: string): string =>\n url.endsWith(\"/\") ? url : `${url}/`;\n\nconst cache: { [key: string]: Endpoints } = {};\nconst getOauthEndpoints = async (oauthServer: string): Promise<Endpoints> => {\n if (cache[oauthServer]) {\n return cache[oauthServer];\n }\n const openIdConfigResponse = await fetch(\n `${addSlashIfNeeded(oauthServer)}.well-known/openid-configuration`,\n );\n const openIdConfig =\n (await openIdConfigResponse.json()) as OpenIdConfiguration;\n const endpoints: Endpoints = {\n jwks: openIdConfig.jwks_uri,\n auth: openIdConfig.authorization_endpoint,\n token: openIdConfig.token_endpoint,\n userinfo: openIdConfig.userinfo_endpoint,\n endsession: openIdConfig.end_session_endpoint,\n };\n\n cache[oauthServer] = endpoints;\n return endpoints;\n};\n\n/**\n * creates a state string for the OAuth2 flow, encoding the display mode too for future use\n * @param {DisplayMode} displayMode\n * @returns {string}\n */\nconst generateState = (\n displayMode: DisplayMode,\n serverTokenExchange?: boolean,\n): string => {\n const jsonString = JSON.stringify({\n uuid: uuid(),\n displayMode,\n ...(serverTokenExchange ? { serverTokenExchange } : {}),\n });\n return btoa(jsonString);\n};\n\n/**\n * parses the state string from the OAuth2 flow, decoding the display mode too\n * @param state\n * @param sessionDisplayMode\n * @returns { uuid: string, displayMode: DisplayMode }\n */\nconst displayModeFromState = (\n state: string,\n sessionDisplayMode: DisplayMode | undefined,\n): DisplayMode | undefined => {\n try {\n const jsonString = atob(state);\n return JSON.parse(jsonString).displayMode;\n } catch (e) {\n console.error(\"Failed to parse displayMode from state:\", state, e);\n return sessionDisplayMode;\n }\n};\n\nconst serverTokenExchangeFromState = (state: string): boolean | undefined => {\n try {\n const jsonString = atob(state);\n return JSON.parse(jsonString).serverTokenExchange;\n } catch {\n console.error(\"Failed to parse serverTokenExchange from state:\", state);\n return undefined;\n }\n};\n\nexport {\n serverTokenExchangeFromState,\n getIssuerVariations,\n getOauthEndpoints,\n displayModeFromState,\n generateState,\n};\n"]}
1
+ {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../src/lib/oauth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAC;AAElC,MAAM,mBAAmB,GAAG,CAAC,MAAc,EAAY,EAAE;IACvD,MAAM,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;QAC7C,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAA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AE1D,OAAO,EACL,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,aAAa,GACd,CAAC","sourcesContent":["import type { DisplayMode, Endpoints, OpenIdConfiguration } from \"@/types.js\";\nimport { v4 as uuid } from \"uuid\";\n\nconst getIssuerVariations = (issuer: string): string[] => {\n const issuerWithoutSlash = issuer.endsWith(\"/\")\n ? issuer.slice(0, issuer.length - 1)\n : issuer;\n\n const issuerWithSlash = `${issuerWithoutSlash}/`;\n\n return [issuerWithoutSlash, issuerWithSlash];\n};\n\nconst addSlashIfNeeded = (url: string): string =>\n url.endsWith(\"/\") ? url : `${url}/`;\n\nconst cache: { [key: string]: Endpoints } = {};\nconst getOauthEndpoints = async (oauthServer: string): Promise<Endpoints> => {\n if (cache[oauthServer]) {\n return cache[oauthServer];\n }\n const openIdConfigResponse = await fetch(\n `${addSlashIfNeeded(oauthServer)}.well-known/openid-configuration`,\n );\n const openIdConfig =\n (await openIdConfigResponse.json()) as OpenIdConfiguration;\n const endpoints: Endpoints = {\n jwks: openIdConfig.jwks_uri,\n auth: openIdConfig.authorization_endpoint,\n token: openIdConfig.token_endpoint,\n userinfo: openIdConfig.userinfo_endpoint,\n endsession: openIdConfig.end_session_endpoint,\n };\n\n cache[oauthServer] = endpoints;\n return endpoints;\n};\n\n/**\n * creates a state string for the OAuth2 flow, encoding the display mode too for future use\n * @param {DisplayMode} displayMode\n * @returns {string}\n */\ntype GenerateStateInput = {\n displayMode: DisplayMode;\n serverTokenExchange?: boolean;\n loginSuccessUrl?: string;\n};\nconst generateState = ({\n displayMode,\n serverTokenExchange,\n loginSuccessUrl,\n}: GenerateStateInput): string => {\n const jsonString = JSON.stringify({\n uuid: uuid(),\n displayMode,\n ...(serverTokenExchange ? { serverTokenExchange } : {}),\n ...(loginSuccessUrl ? { loginSuccessUrl } : {}),\n });\n return btoa(jsonString);\n};\n\n/**\n * parses the state string from the OAuth2 flow, decoding the display mode too\n * @param state\n * @param sessionDisplayMode\n * @returns { uuid: string, displayMode: DisplayMode }\n */\nconst displayModeFromState = (\n state: string,\n sessionDisplayMode: DisplayMode | undefined,\n): DisplayMode | undefined => {\n try {\n const jsonString = atob(state);\n return JSON.parse(jsonString).displayMode;\n } catch (e) {\n console.error(\"Failed to parse displayMode from state:\", state, e);\n return sessionDisplayMode;\n }\n};\n\nconst decodeState = (\n state: string,\n): { serverTokenExchange?: boolean; loginSuccessUrl?: string } | undefined => {\n try {\n const jsonString = atob(state);\n return JSON.parse(jsonString);\n } catch {\n console.error(\"Failed to parse state string to json:\", state);\n return undefined;\n }\n};\n\nconst serverTokenExchangeFromState = (state: string): boolean | undefined =>\n decodeState(state)?.serverTokenExchange;\nconst loginSuccessUrlFromState = (state: string | null): string | undefined =>\n state ? decodeState(state)?.loginSuccessUrl : undefined;\n\nexport {\n serverTokenExchangeFromState,\n loginSuccessUrlFromState,\n getIssuerVariations,\n getOauthEndpoints,\n displayModeFromState,\n generateState,\n};\n"]}
@@ -12,6 +12,7 @@ export type AuthConfigWithDefaults = {
12
12
  clientId: string;
13
13
  oauthServer: string;
14
14
  callbackUrl: string;
15
+ loginSuccessUrl?: string;
15
16
  loginUrl: string;
16
17
  logoutUrl: string;
17
18
  logoutCallbackUrl: string;
@@ -32,6 +33,7 @@ export type OptionalAuthConfig = Partial<AuthConfigWithDefaults | {
32
33
  };
33
34
  }> & {
34
35
  callbackUrl?: string;
36
+ loginSuccessUrl?: string;
35
37
  loginUrl?: string;
36
38
  logoutUrl?: string;
37
39
  logoutCallbackUrl?: string;
@@ -118,6 +120,7 @@ export declare const createCivicAuthPlugin: (authConfig: AuthConfig) => (nextCon
118
120
  _civic_auth_client_id: string;
119
121
  _civic_oauth_server: string;
120
122
  _civic_auth_callback_url: string;
123
+ _civic_auth_login_success_url: string | undefined;
121
124
  _civic_auth_challenge_url: string;
122
125
  _civic_auth_login_url: string;
123
126
  _civic_auth_logout_url: string;
@@ -1 +1 @@
1
- {"version":3,"file":"config.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;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,kBAAkB,GAAG;IAC5C,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC;AAKF;;GAEG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,sBAAsB,EAAE,UAAU,CAiEtE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,iBAAiB,YACpB,OAAO,CAAC,UAAU,CAAC,KAC1B,sBAiDF,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,eAAO,MAAM,qBAAqB,eAAgB,UAAU,mBACrC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAyDy7T,CAAC;6BAAsG,CAAC;;;sBAAke,CAAC;yBAA4H,CAAC;;;qBAA+H,CAAC;;;;;;;;;;;;;;;;;;iBAA8pE,CAAC;;;;;;;6BAAg6C,CAAC;sBAAoC,CAAC;;aAAoC,CAAC;;6BAA0D,CAAC;oBAA8B,CAAC;0BAAkE,CAAC;;qBAA2C,CAAC;mBAAiC,CAAC;;wBAA+C,CAAC;eAAmD,CAAC;iBAA4C,CAAC;2BAAyC,CAAC;;;;;;;;;yBAA4zC,CAAC;6BAAwC,CAAC;;;eAAkD,CAAC;mBAAuB,CAAC;;;;CADlwgB,CAAC"}
@@ -13,6 +13,7 @@ const defaultCookiesMaxAge = 60 * 60; // 1 hour
13
13
  export const defaultAuthConfig = {
14
14
  oauthServer: DEFAULT_AUTH_SERVER,
15
15
  callbackUrl: "/api/auth/callback",
16
+ loginSuccessUrl: undefined, // By default, the user is sent to the redirect_url
16
17
  challengeUrl: "/api/auth/challenge",
17
18
  refreshUrl: "/api/auth/refresh",
18
19
  logoutUrl: "/api/auth/logout",
@@ -101,6 +102,7 @@ export const resolveAuthConfig = (config = {}) => {
101
102
  clientId: process.env._civic_auth_client_id,
102
103
  oauthServer: process.env._civic_oauth_server,
103
104
  callbackUrl: process.env._civic_auth_callback_url,
105
+ loginSuccessUrl: process.env._civic_auth_login_success_url,
104
106
  challengeUrl: process.env._civic_auth_challenge_url,
105
107
  loginUrl: process.env._civic_auth_login_url,
106
108
  logoutUrl: process.env._civic_auth_logout_url,
@@ -204,6 +206,7 @@ export const createCivicAuthPlugin = (authConfig) => {
204
206
  _civic_auth_client_id: resolvedConfig.clientId,
205
207
  _civic_oauth_server: resolvedConfig.oauthServer,
206
208
  _civic_auth_callback_url: resolvedConfig.callbackUrl,
209
+ _civic_auth_login_success_url: resolvedConfig.loginSuccessUrl,
207
210
  _civic_auth_challenge_url: resolvedConfig.challengeUrl,
208
211
  _civic_auth_login_url: resolvedConfig.loginUrl,
209
212
  _civic_auth_logout_url: resolvedConfig.logoutUrl,
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/nextjs/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EACL,YAAY,EAEZ,eAAe,GAEhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;AA6D5C,MAAM,mBAAmB,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,CAAC,CAAC;AACtE,MAAM,oBAAoB,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,SAAS;AAE/C;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAA6C;IACzE,WAAW,EAAE,mB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CAAC,QAAQ;gBAC9C,sBAAsB,EAAE,cAAc,CAAC,SAAS;gBAChD,+BAA+B,EAAE,cAAc,CAAC,iBAAiB;gBACjE,uBAAuB,EAAE,cAAc,CAAC,UAAU;gBAClD,oBAAoB,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC;gBACtD,oBAAoB,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC;gBACtD,yBAAyB,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC;gBACjE,qBAAqB,EAAE,cAAc,CAAC,QAAQ;aAC/C;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/* eslint-disable turbo/no-undeclared-env-vars */\nimport type { NextConfig } from \"next\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { withoutUndefined } from \"@/utils.js\";\nimport {\n CodeVerifier,\n type CookieConfig,\n OAuthTokenTypes,\n type TokensCookieConfig,\n} from \"@/shared/lib/types.js\";\nimport { DEFAULT_AUTH_SERVER } from \"@/constants.js\";\nimport { merge } from \"ts-deepmerge\";\nimport { sanitizeBasePath } from \"./utils.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nexport type CookiesConfigObject = {\n tokens: TokensCookieConfig;\n user: CookieConfig;\n};\n\n/**\n * Configuration values for Civic Auth.\n * Only clientId is required, all others are optional.\n */\nexport type AuthConfigWithDefaults = {\n clientId: string;\n oauthServer: string;\n callbackUrl: string;\n loginUrl: string;\n logoutUrl: string;\n logoutCallbackUrl: string;\n challengeUrl: string;\n refreshUrl: string;\n include: string[];\n exclude: string[];\n cookies: CookiesConfigObject;\n basePath?: string;\n};\n\n/**\n * All possible config values for Civic Auth\n */\nexport type OptionalAuthConfig = Partial<\n | AuthConfigWithDefaults\n | {\n cookies?: {\n tokens?: Partial<TokensCookieConfig>;\n user?: CookieConfig;\n };\n }\n> & {\n // Ensure TypeScript understands these properties are available\n // This doesn't change the public API, just helps TypeScript internally\n callbackUrl?: string;\n loginUrl?: string;\n logoutUrl?: string;\n logoutCallbackUrl?: string;\n challengeUrl?: string;\n refreshUrl?: string;\n include?: string[];\n exclude?: string[];\n basePath?: string;\n oauthServer?: string;\n};\n\n/**\n * Configuration values for Civic Auth.\n * Only clientId is required, all others are optional.\n */\nexport type AuthConfig = OptionalAuthConfig & {\n clientId: string;\n exclude?: string[];\n};\n\nconst defaultServerSecure = !(process.env.NODE_ENV === \"development\");\nconst defaultCookiesMaxAge = 60 * 60; // 1 hour\n\n/**\n * Default configuration values that will be used if not overridden\n */\nexport const defaultAuthConfig: Omit<AuthConfigWithDefaults, \"clientId\"> = {\n oauthServer: DEFAULT_AUTH_SERVER,\n callbackUrl: \"/api/auth/callback\",\n challengeUrl: \"/api/auth/challenge\",\n refreshUrl: \"/api/auth/refresh\",\n logoutUrl: \"/api/auth/logout\",\n logoutCallbackUrl: \"/api/auth/logoutcallback\",\n loginUrl: \"/\",\n include: [\"/**\"],\n exclude: [\"/api/auth/**\"],\n basePath: \"\",\n cookies: {\n tokens: {\n [OAuthTokenTypes.ID_TOKEN]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [OAuthTokenTypes.ACCESS_TOKEN]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [OAuthTokenTypes.REFRESH_TOKEN]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [OAuthTokenTypes.ACCESS_TOKEN_EXPIRES_AT]: {\n secure: defaultServerSecure,\n httpOnly: false, // we need this to be available client-side\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [CodeVerifier.COOKIE_NAME]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [CodeVerifier.APP_URL]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n },\n user: {\n secure: defaultServerSecure,\n httpOnly: false, // we need this to be available client-side\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n },\n};\n\n/**\n * Resolves the authentication configuration by combining:\n * 1. Default values\n * 2. Environment variables (set internally by the plugin)\n * 3. Explicitly passed configuration\n *\n * Config will be merged deeply, with arrays not merged, so that the\n * default include list (for example) [\"/*\"] will not be added\n *\n * Note: Developers should not set _civic_auth_* environment variables directly.\n * Instead, pass configuration to the createCivicAuthPlugin in next.config.js:\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * callbackUrl: '/custom/callback',\n * })\n * ```\n */\nexport const resolveAuthConfig = (\n config: Partial<AuthConfig> = {},\n): AuthConfigWithDefaults => {\n // Read configuration that was set by the plugin via environment variables\n const configFromEnv = withoutUndefined({\n clientId: process.env._civic_auth_client_id,\n oauthServer: process.env._civic_oauth_server,\n callbackUrl: process.env._civic_auth_callback_url,\n challengeUrl: process.env._civic_auth_challenge_url,\n loginUrl: process.env._civic_auth_login_url,\n logoutUrl: process.env._civic_auth_logout_url,\n logoutCallbackUrl: process.env._civic_auth_logout_callback_url,\n refreshUrl: process.env._civic_auth_refresh_url,\n include: process.env._civic_auth_includes?.split(\",\"),\n exclude: process.env._civic_auth_excludes?.split(\",\"),\n cookies: process.env._civic_auth_cookie_config\n ? JSON.parse(process.env._civic_auth_cookie_config)\n : undefined,\n basePath: process.env._civic_auth_base_path || \"\",\n }) as AuthConfig;\n\n // Ensure \"/api/auth/**\" is always excluded\n const finalExclude = new Set([\n ...defaultAuthConfig.exclude,\n ...(configFromEnv.exclude || []),\n ...(config.exclude ?? []),\n ]);\n\n // Perform a deep merge of the configurations\n const mergedConfig = merge.withOptions(\n { mergeArrays: false },\n defaultAuthConfig,\n configFromEnv,\n config,\n );\n\n // Override the exclude list with the ensured list\n mergedConfig.exclude = Array.from(finalExclude);\n\n logger.debug(\n \"Config from environment:\",\n JSON.stringify(configFromEnv, null, 2),\n );\n logger.debug(\"Resolved config:\", JSON.stringify(mergedConfig, null, 2));\n\n if (mergedConfig.clientId === undefined) {\n throw new Error(\"Civic Auth client ID is required\");\n }\n\n return mergedConfig as AuthConfigWithDefaults & { clientId: string };\n};\n\n/**\n * Creates a Next.js plugin that handles auth configuration.\n *\n * This is the main configuration point for the auth system.\n * Do not set _civic_auth_* environment variables directly - instead,\n * pass your configuration here.\n *\n * The only required field is clientId.\n *\n * Notes:\n * - If you provide explicit URLs, they will be used exactly as provided.\n * - Default URLs will automatically include the basePath from your Next.js config.\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * clientId: 'my-client-id',\n * });\n * ```\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * clientId: 'my-client-id',\n * callbackUrl: '/custom/callback',\n * loginUrl: '/custom/login',\n * logoutUrl: '/custom/logout',\n * logoutCallbackUrl: '/custom/logoutcallback',\n * include: ['/protected/*'],\n * exclude: ['/public/*']\n * })\n * ```\n *\n * The plugin sets internal environment variables that are used by\n * the auth system. These variables should not be set manually.\n */\nexport const createCivicAuthPlugin = (authConfig: AuthConfig) => {\n return (nextConfig?: NextConfig) => {\n logger.debug(\n \"createCivicAuthPlugin nextConfig\",\n JSON.stringify(nextConfig, null, 2),\n );\n\n // Extract basePath from Next.js config\n const basePath = sanitizeBasePath(nextConfig?.basePath || \"\");\n\n // Create a copy of default URLs with basePath added\n const defaultUrlsWithBasePath: Partial<AuthConfig> = {};\n\n // Only apply to URLs that aren't explicitly set in authConfig\n if (basePath) {\n if (!authConfig.callbackUrl)\n defaultUrlsWithBasePath.callbackUrl = `${basePath}/api/auth/callback`;\n if (!authConfig.challengeUrl)\n defaultUrlsWithBasePath.challengeUrl = `${basePath}/api/auth/challenge`;\n if (!authConfig.refreshUrl)\n defaultUrlsWithBasePath.refreshUrl = `${basePath}/api/auth/refresh`;\n if (!authConfig.logoutUrl)\n defaultUrlsWithBasePath.logoutUrl = `${basePath}/api/auth/logout`;\n if (!authConfig.logoutCallbackUrl)\n defaultUrlsWithBasePath.logoutCallbackUrl = `${basePath}/api/auth/logoutcallback`;\n if (!authConfig.loginUrl && authConfig.loginUrl !== \"\")\n defaultUrlsWithBasePath.loginUrl = basePath;\n }\n\n // Create final config with basePath and possibly modified URLs\n const resolvedConfig = resolveAuthConfig({\n ...defaultUrlsWithBasePath,\n ...authConfig,\n basePath,\n });\n\n return {\n ...nextConfig,\n env: {\n ...nextConfig?.env,\n // Internal environment variables - do not set these manually\n _civic_auth_client_id: resolvedConfig.clientId,\n _civic_oauth_server: resolvedConfig.oauthServer,\n _civic_auth_callback_url: resolvedConfig.callbackUrl,\n _civic_auth_challenge_url: resolvedConfig.challengeUrl,\n _civic_auth_login_url: resolvedConfig.loginUrl,\n _civic_auth_logout_url: resolvedConfig.logoutUrl,\n _civic_auth_logout_callback_url: resolvedConfig.logoutCallbackUrl,\n _civic_auth_refresh_url: resolvedConfig.refreshUrl,\n _civic_auth_includes: resolvedConfig.include.join(\",\"),\n _civic_auth_excludes: resolvedConfig.exclude.join(\",\"),\n _civic_auth_cookie_config: JSON.stringify(resolvedConfig.cookies),\n _civic_auth_base_path: resolvedConfig.basePath,\n },\n };\n };\n};\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/nextjs/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EACL,YAAY,EAEZ,eAAe,GAEhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM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ACpD,uBAAuB,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAChD,CAAC;QAED,+DAA+D;QAC/D,MAAM,cAAc,GAAG,iBAAiB,CAAC;YACvC,GAAG,uBAAuB;YAC1B,GAAG,UAAU;YACb,QAAQ;SACT,CAAC,CAAC;QAEH,OAAO;YACL,GAAG,UAAU;YACb,GAAG,EAAE;gBACH,GAAG,UAAU,EAAE,GAAG;gBAClB,6DAA6D;gBAC7D,qBAAqB,EAAE,cAAc,CAAC,QAAQ;gBAC9C,mBAAmB,EAAE,cAAc,CAAC,WAAW;gBAC/C,wBAAwB,EAAE,cAAc,CAAC,WAAW;gBACpD,6BAA6B,EAAE,cAAc,CAAC,eAAe;gBAC7D,yBAAyB,EAAE,cAAc,CAAC,YAAY;gBACtD,qBAAqB,EAAE,cAAc,CAAC,QAAQ;gBAC9C,sBAAsB,EAAE,cAAc,CAAC,SAAS;gBAChD,+BAA+B,EAAE,cAAc,CAAC,iBAAiB;gBACjE,uBAAuB,EAAE,cAAc,CAAC,UAAU;gBAClD,oBAAoB,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC;gBACtD,oBAAoB,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC;gBACtD,yBAAyB,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC;gBACjE,qBAAqB,EAAE,cAAc,CAAC,QAAQ;aAC/C;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/* eslint-disable turbo/no-undeclared-env-vars */\nimport type { NextConfig } from \"next\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { withoutUndefined } from \"@/utils.js\";\nimport {\n CodeVerifier,\n type CookieConfig,\n OAuthTokenTypes,\n type TokensCookieConfig,\n} from \"@/shared/lib/types.js\";\nimport { DEFAULT_AUTH_SERVER } from \"@/constants.js\";\nimport { merge } from \"ts-deepmerge\";\nimport { sanitizeBasePath } from \"./utils.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nexport type CookiesConfigObject = {\n tokens: TokensCookieConfig;\n user: CookieConfig;\n};\n\n/**\n * Configuration values for Civic Auth.\n * Only clientId is required, all others are optional.\n */\nexport type AuthConfigWithDefaults = {\n clientId: string;\n oauthServer: string;\n callbackUrl: string; // where Civic's internal OAuth callback is hosted\n loginSuccessUrl?: string; // where the user should be sent after the entire login completes, including the token exchange\n loginUrl: string;\n logoutUrl: string;\n logoutCallbackUrl: string;\n challengeUrl: string;\n refreshUrl: string;\n include: string[];\n exclude: string[];\n cookies: CookiesConfigObject;\n basePath?: string;\n};\n\n/**\n * All possible config values for Civic Auth\n */\nexport type OptionalAuthConfig = Partial<\n | AuthConfigWithDefaults\n | {\n cookies?: {\n tokens?: Partial<TokensCookieConfig>;\n user?: CookieConfig;\n };\n }\n> & {\n // Ensure TypeScript understands these properties are available\n // This doesn't change the public API, just helps TypeScript internally\n callbackUrl?: string; // where Civic's internal OAuth callback is hosted\n loginSuccessUrl?: string; // where the user should be sent after the entire login completes, including the token exchange\n loginUrl?: string;\n logoutUrl?: string;\n logoutCallbackUrl?: string;\n challengeUrl?: string;\n refreshUrl?: string;\n include?: string[];\n exclude?: string[];\n basePath?: string;\n oauthServer?: string;\n};\n\n/**\n * Configuration values for Civic Auth.\n * Only clientId is required, all others are optional.\n */\nexport type AuthConfig = OptionalAuthConfig & {\n clientId: string;\n exclude?: string[];\n};\n\nconst defaultServerSecure = !(process.env.NODE_ENV === \"development\");\nconst defaultCookiesMaxAge = 60 * 60; // 1 hour\n\n/**\n * Default configuration values that will be used if not overridden\n */\nexport const defaultAuthConfig: Omit<AuthConfigWithDefaults, \"clientId\"> = {\n oauthServer: DEFAULT_AUTH_SERVER,\n callbackUrl: \"/api/auth/callback\",\n loginSuccessUrl: undefined, // By default, the user is sent to the redirect_url\n challengeUrl: \"/api/auth/challenge\",\n refreshUrl: \"/api/auth/refresh\",\n logoutUrl: \"/api/auth/logout\",\n logoutCallbackUrl: \"/api/auth/logoutcallback\",\n loginUrl: \"/\",\n include: [\"/**\"],\n exclude: [\"/api/auth/**\"],\n basePath: \"\",\n cookies: {\n tokens: {\n [OAuthTokenTypes.ID_TOKEN]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [OAuthTokenTypes.ACCESS_TOKEN]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [OAuthTokenTypes.REFRESH_TOKEN]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [OAuthTokenTypes.ACCESS_TOKEN_EXPIRES_AT]: {\n secure: defaultServerSecure,\n httpOnly: false, // we need this to be available client-side\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [CodeVerifier.COOKIE_NAME]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n [CodeVerifier.APP_URL]: {\n secure: defaultServerSecure,\n httpOnly: true,\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n },\n user: {\n secure: defaultServerSecure,\n httpOnly: false, // we need this to be available client-side\n sameSite: \"strict\",\n path: \"/\",\n maxAge: defaultCookiesMaxAge,\n },\n },\n};\n\n/**\n * Resolves the authentication configuration by combining:\n * 1. Default values\n * 2. Environment variables (set internally by the plugin)\n * 3. Explicitly passed configuration\n *\n * Config will be merged deeply, with arrays not merged, so that the\n * default include list (for example) [\"/*\"] will not be added\n *\n * Note: Developers should not set _civic_auth_* environment variables directly.\n * Instead, pass configuration to the createCivicAuthPlugin in next.config.js:\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * callbackUrl: '/custom/callback',\n * })\n * ```\n */\nexport const resolveAuthConfig = (\n config: Partial<AuthConfig> = {},\n): AuthConfigWithDefaults => {\n // Read configuration that was set by the plugin via environment variables\n const configFromEnv = withoutUndefined({\n clientId: process.env._civic_auth_client_id,\n oauthServer: process.env._civic_oauth_server,\n callbackUrl: process.env._civic_auth_callback_url,\n loginSuccessUrl: process.env._civic_auth_login_success_url,\n challengeUrl: process.env._civic_auth_challenge_url,\n loginUrl: process.env._civic_auth_login_url,\n logoutUrl: process.env._civic_auth_logout_url,\n logoutCallbackUrl: process.env._civic_auth_logout_callback_url,\n refreshUrl: process.env._civic_auth_refresh_url,\n include: process.env._civic_auth_includes?.split(\",\"),\n exclude: process.env._civic_auth_excludes?.split(\",\"),\n cookies: process.env._civic_auth_cookie_config\n ? JSON.parse(process.env._civic_auth_cookie_config)\n : undefined,\n basePath: process.env._civic_auth_base_path || \"\",\n }) as AuthConfig;\n\n // Ensure \"/api/auth/**\" is always excluded\n const finalExclude = new Set([\n ...defaultAuthConfig.exclude,\n ...(configFromEnv.exclude || []),\n ...(config.exclude ?? []),\n ]);\n\n // Perform a deep merge of the configurations\n const mergedConfig = merge.withOptions(\n { mergeArrays: false },\n defaultAuthConfig,\n configFromEnv,\n config,\n );\n\n // Override the exclude list with the ensured list\n mergedConfig.exclude = Array.from(finalExclude);\n\n logger.debug(\n \"Config from environment:\",\n JSON.stringify(configFromEnv, null, 2),\n );\n logger.debug(\"Resolved config:\", JSON.stringify(mergedConfig, null, 2));\n\n if (mergedConfig.clientId === undefined) {\n throw new Error(\"Civic Auth client ID is required\");\n }\n\n return mergedConfig as AuthConfigWithDefaults & { clientId: string };\n};\n\n/**\n * Creates a Next.js plugin that handles auth configuration.\n *\n * This is the main configuration point for the auth system.\n * Do not set _civic_auth_* environment variables directly - instead,\n * pass your configuration here.\n *\n * The only required field is clientId.\n *\n * Notes:\n * - If you provide explicit URLs, they will be used exactly as provided.\n * - Default URLs will automatically include the basePath from your Next.js config.\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * clientId: 'my-client-id',\n * });\n * ```\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * clientId: 'my-client-id',\n * callbackUrl: '/custom/callback',\n * loginUrl: '/custom/login',\n * logoutUrl: '/custom/logout',\n * logoutCallbackUrl: '/custom/logoutcallback',\n * include: ['/protected/*'],\n * exclude: ['/public/*']\n * })\n * ```\n *\n * The plugin sets internal environment variables that are used by\n * the auth system. These variables should not be set manually.\n */\nexport const createCivicAuthPlugin = (authConfig: AuthConfig) => {\n return (nextConfig?: NextConfig) => {\n logger.debug(\n \"createCivicAuthPlugin nextConfig\",\n JSON.stringify(nextConfig, null, 2),\n );\n\n // Extract basePath from Next.js config\n const basePath = sanitizeBasePath(nextConfig?.basePath || \"\");\n\n // Create a copy of default URLs with basePath added\n const defaultUrlsWithBasePath: Partial<AuthConfig> = {};\n\n // Only apply to URLs that aren't explicitly set in authConfig\n if (basePath) {\n if (!authConfig.callbackUrl)\n defaultUrlsWithBasePath.callbackUrl = `${basePath}/api/auth/callback`;\n if (!authConfig.challengeUrl)\n defaultUrlsWithBasePath.challengeUrl = `${basePath}/api/auth/challenge`;\n if (!authConfig.refreshUrl)\n defaultUrlsWithBasePath.refreshUrl = `${basePath}/api/auth/refresh`;\n if (!authConfig.logoutUrl)\n defaultUrlsWithBasePath.logoutUrl = `${basePath}/api/auth/logout`;\n if (!authConfig.logoutCallbackUrl)\n defaultUrlsWithBasePath.logoutCallbackUrl = `${basePath}/api/auth/logoutcallback`;\n if (!authConfig.loginUrl && authConfig.loginUrl !== \"\")\n defaultUrlsWithBasePath.loginUrl = basePath;\n }\n\n // Create final config with basePath and possibly modified URLs\n const resolvedConfig = resolveAuthConfig({\n ...defaultUrlsWithBasePath,\n ...authConfig,\n basePath,\n });\n\n return {\n ...nextConfig,\n env: {\n ...nextConfig?.env,\n // Internal environment variables - do not set these manually\n _civic_auth_client_id: resolvedConfig.clientId,\n _civic_oauth_server: resolvedConfig.oauthServer,\n _civic_auth_callback_url: resolvedConfig.callbackUrl,\n _civic_auth_login_success_url: resolvedConfig.loginSuccessUrl,\n _civic_auth_challenge_url: resolvedConfig.challengeUrl,\n _civic_auth_login_url: resolvedConfig.loginUrl,\n _civic_auth_logout_url: resolvedConfig.logoutUrl,\n _civic_auth_logout_callback_url: resolvedConfig.logoutCallbackUrl,\n _civic_auth_refresh_url: resolvedConfig.refreshUrl,\n _civic_auth_includes: resolvedConfig.include.join(\",\"),\n _civic_auth_excludes: resolvedConfig.exclude.join(\",\"),\n _civic_auth_cookie_config: JSON.stringify(resolvedConfig.cookies),\n _civic_auth_base_path: resolvedConfig.basePath,\n },\n };\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"NextAuthProvider.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProvider.tsx"],"names":[],"mappings":"AAWA,OAAO,EAEL,KAAK,sBAAsB,EAC5B,MAAM,oBAAoB,CAAC;AAe5B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAkBrE,KAAK,kCAAkC,GAAG,IAAI,CAC5C,iBAAiB,EACjB,UAAU,CACX,GAAG;IACF,cAAc,EAAE,sBAAsB,CAAC;CACxC,CAAC;AACF,KAAK,0BAA0B,GAAG,IAAI,CACpC,kCAAkC,EAClC,UAAU,GAAG,gBAAgB,GAAG,aAAa,CAC9C,CAAC;AAuJF,QAAA,MAAM,qBAAqB,2BAGxB,0BAA0B,qDA4C5B,CAAC;AAEF,OAAO,EAAE,qBAAqB,EAAE,KAAK,0BAA0B,EAAE,CAAC"}
1
+ {"version":3,"file":"NextAuthProvider.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProvider.tsx"],"names":[],"mappings":"AAWA,OAAO,EAEL,KAAK,sBAAsB,EAC5B,MAAM,oBAAoB,CAAC;AAe5B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAkBrE,KAAK,kCAAkC,GAAG,IAAI,CAC5C,iBAAiB,EACjB,UAAU,CACX,GAAG;IACF,cAAc,EAAE,sBAAsB,CAAC;CACxC,CAAC;AACF,KAAK,0BAA0B,GAAG,IAAI,CACpC,kCAAkC,EAClC,UAAU,GAAG,gBAAgB,GAAG,aAAa,CAC9C,CAAC;AAuJF,QAAA,MAAM,qBAAqB,2BAGxB,0BAA0B,qDA8C5B,CAAC;AAEF,OAAO,EAAE,qBAAqB,EAAE,KAAK,0BAA0B,EAAE,CAAC"}
@@ -120,7 +120,7 @@ const CivicNextAuthProviderInternal = ({ children, ...props }) => {
120
120
  };
121
121
  const CivicNextAuthProvider = ({ children, ...props }) => {
122
122
  const resolvedConfig = resolveAuthConfig();
123
- const { clientId, oauthServer, callbackUrl, challengeUrl, logoutUrl, refreshUrl, logoutCallbackUrl, } = resolvedConfig;
123
+ const { clientId, oauthServer, callbackUrl, loginSuccessUrl, challengeUrl, logoutUrl, refreshUrl, logoutCallbackUrl, } = resolvedConfig;
124
124
  const [redirectUrl, setRedirectUrl] = useState("");
125
125
  useEffect(() => {
126
126
  if (typeof globalThis.window !== "undefined") {
@@ -128,7 +128,7 @@ const CivicNextAuthProvider = ({ children, ...props }) => {
128
128
  setRedirectUrl(resolveCallbackUrl(resolvedConfig, appUrl));
129
129
  }
130
130
  }, [callbackUrl, resolvedConfig]);
131
- return (_jsx(CivicAuthConfigProvider, { oauthServer: oauthServer, clientId: clientId, redirectUrl: redirectUrl, logoutRedirectUrl: logoutCallbackUrl, nonce: props?.nonce, challengeUrl: challengeUrl, refreshUrl: refreshUrl, logoutUrl: logoutUrl, logoutCallbackUrl: logoutCallbackUrl, children: _jsx(AuthStatusProvider, { children: _jsx(IframeProvider, { iframeMode: props.iframeMode, children: _jsx(CivicNextAuthProviderInternal, { ...props, resolvedConfig: resolvedConfig, children: children }) }) }) }));
131
+ return (_jsx(CivicAuthConfigProvider, { oauthServer: oauthServer, clientId: clientId, loginSuccessUrl: loginSuccessUrl, redirectUrl: redirectUrl, logoutRedirectUrl: logoutCallbackUrl, nonce: props?.nonce, challengeUrl: challengeUrl, refreshUrl: refreshUrl, logoutUrl: logoutUrl, logoutCallbackUrl: logoutCallbackUrl, children: _jsx(AuthStatusProvider, { children: _jsx(IframeProvider, { iframeMode: props.iframeMode, children: _jsx(CivicNextAuthProviderInternal, { ...props, resolvedConfig: resolvedConfig, children: children }) }) }) }));
132
132
  };
133
133
  export { CivicNextAuthProvider };
134
134
  //# sourceMappingURL=NextAuthProvider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"NextAuthProvider.js","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProvider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AACb;;GAEG;AACH,OAAO,KAAK,EAAE,EACZ,eAAe,EACf,WAAW,EACX,SAAS,EACT,MAAM,EACN,QAAQ,GACT,MAAM,OAAO,CAAC;AACf,OAAO,EACL,iBAAiB,GAElB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,8CAA8C,CAAC;AACvF,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AACnE,OAAO,EAAE,W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AW,EACxB,iBAAiB,EAAE,iBAAiB,EACpC,KAAK,EAAE,KAAK,EAAE,KAAK,EACnB,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,UAAU,EACtB,SAAS,EAAE,SAAS,EACpB,iBAAiB,EAAE,iBAAiB,YAEpC,KAAC,kBAAkB,cACjB,KAAC,cAAc,IAAC,UAAU,EAAE,KAAK,CAAC,UAAU,YAC1C,KAAC,6BAA6B,OACxB,KAAK,EACT,cAAc,EAAE,cAAc,YAE7B,QAAQ,GACqB,GACjB,GACE,GACG,CAC3B,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,qBAAqB,EAAmC,CAAC","sourcesContent":["\"use client\";\n/**\n * A very small context provider for the user object - it takes the user object from the cookie and provides it to the app.\n */\nimport React, {\n startTransition,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\nimport {\n resolveAuthConfig,\n type AuthConfigWithDefaults,\n} from \"@/nextjs/config.js\";\nimport { resolveCallbackUrl } from \"@/nextjs/utils.js\";\nimport { ConfidentialClientPKCEConsumer } from \"@/services/PKCE.js\";\nimport { UserProvider } from \"@/shared/providers/UserProvider.js\";\nimport { useUserCookie } from \"@/nextjs/hooks/useUserCookie.js\";\nimport { CivicAuthConfigProvider } from \"@/shared/providers/CivicAuthConfigContext.js\";\nimport { SessionProvider } from \"@/shared/providers/SessionProvider.js\";\nimport { IframeProvider } from \"@/shared/providers/IframeProvider.js\";\nimport { TokenProvider } from \"@/shared/providers/TokenProvider.js\";\nimport { useSignIn } from \"@/shared/hooks/useSignIn.js\";\nimport { useCivicAuthConfig } from \"@/shared/hooks/useCivicAuthConfig.js\";\nimport { IFrameAndLoading } from \"@/shared/components/IFrameAndLoading.js\";\nimport { BlockDisplay } from \"@/shared/components/BlockDisplay.js\";\nimport { LoadingIcon } from \"@/shared/components/LoadingIcon.js\";\nimport { useIframe } from \"@/shared/hooks/useIframe.js\";\nimport type { AuthProviderProps } from \"@/shared/providers/types.js\";\nimport { useIsInIframe } from \"@/shared/hooks/useIsInIframe.js\";\nimport { AuthStatus, type UnknownObject, type User } from \"@/types.js\";\nimport { useRefresh } from \"@/nextjs/hooks/useRefresh.js\";\nimport { useCurrentUrl, useSession } from \"@/shared/hooks/index.js\";\nimport { BrowserCookieStorage } from \"@/shared/index.js\";\nimport { getIframeRef } from \"@/shared/lib/iframeUtils.js\";\nimport { AuthStatusProvider } from \"@/shared/providers/AuthStatusContext.js\";\nimport { useIsClient } from \"usehooks-ts\";\nimport { useRouter } from \"next/navigation.js\";\n\ntype CivicNextAuthTokenProviderInternalProps<TUser extends UnknownObject> =\n NextCivicAuthProviderInternalProps & {\n isLoading: boolean;\n idToken?: string;\n user: User<TUser> | null;\n fetchUser: () => void;\n };\ntype NextCivicAuthProviderInternalProps = Omit<\n AuthProviderProps,\n \"clientId\"\n> & {\n resolvedConfig: AuthConfigWithDefaults;\n};\ntype NextCivicAuthProviderProps = Omit<\n NextCivicAuthProviderInternalProps,\n \"clientId\" | \"resolvedConfig\" | \"redirectUrl\"\n>;\n\nconst CivicNextAuthTokenProviderInternal = <\n TUser extends UnknownObject = UnknownObject,\n>({\n children,\n displayMode = \"iframe\",\n user,\n fetchUser,\n ...props\n}: CivicNextAuthTokenProviderInternalProps<TUser>) => {\n const { iframeMode, resolvedConfig } = props;\n const { iframeRef, setIframeIsVisible, isIframeMounted, setIframeMounted } =\n useIframe();\n const civicAuthConfig = useCivicAuthConfig();\n const { challengeUrl } = resolvedConfig;\n const pkceConsumer = new ConfidentialClientPKCEConsumer(\n challengeUrl,\n resolvedConfig.basePath,\n );\n const { data: session } = useSession();\n const currentUrl = useCurrentUrl();\n\n useEffect(() => {\n if (session?.authenticated) {\n setIframeMounted(false);\n // the session is authenticated, so don't show the login iframe\n setIframeIsVisible(false);\n return;\n }\n }, [session?.authenticated, setIframeIsVisible, setIframeMounted]);\n\n const postSignOut = useCallback(async () => {\n // user is signed out, manually update the user from cookies to not wait for polling\n fetchUser();\n await props?.onSignOut?.();\n }, [fetchUser, props]);\n\n const { signIn, startSignIn, signOut, authStatus } = useSignIn({\n postSignOut,\n pkceConsumer,\n displayMode,\n });\n\n const { error: refreshError } = useRefresh();\n\n useEffect(() => {\n const ref = getIframeRef(iframeRef?.current, true);\n if (\n isIframeMounted &&\n civicAuthConfig &&\n !session?.authenticated &&\n ref &&\n authStatus === AuthStatus.UNAUTHENTICATED &&\n displayMode === \"iframe\" &&\n !currentUrl?.includes(\"code=\")\n ) {\n startSignIn();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n isIframeMounted,\n currentUrl,\n iframeMode,\n iframeRef,\n civicAuthConfig,\n session?.authenticated,\n authStatus,\n startSignIn,\n displayMode,\n ]);\n\n useEffect(() => {\n if (refreshError) {\n console.error(\"Error refreshing token, signing out...\", refreshError);\n signOut();\n }\n }, [refreshError, signOut]);\n\n // if the SDK loads in an iframe, we show the loading spinner as the iframe\n // will be waiting to be minimized\n const isInIframe = useIsInIframe();\n // we need this as server-side rendering will not have a window object\n // and will throw an error if we try to access it\n const isClient = useIsClient();\n return !isClient ? null : (\n <TokenProvider>\n <UserProvider\n storage={new BrowserCookieStorage()}\n user={user}\n signOut={signOut}\n signIn={signIn}\n displayMode={displayMode}\n authStatus={authStatus}\n >\n <IFrameAndLoading error={null} isLoading={isInIframe} />\n {isInIframe && (\n <BlockDisplay>\n <LoadingIcon />\n </BlockDisplay>\n )}\n {children}\n </UserProvider>\n </TokenProvider>\n );\n};\n\nconst CivicNextAuthProviderInternal = ({\n children,\n ...props\n}: NextCivicAuthProviderInternalProps) => {\n const { user, idToken, fetchUser, isLoading, userChanged } = useUserCookie();\n const hasRunRef = useRef(false);\n const router = useRouter();\n\n // if there are any changes in the user object, we need to refresh the page\n // to handle both login and logout cases. We use a 'hasRun' ref to prevent\n // the refresh from running multiple times in a row\n useEffect(() => {\n if (userChanged) {\n if (!hasRunRef.current) {\n hasRunRef.current = true;\n startTransition(() => {\n router.refresh();\n });\n }\n } else {\n hasRunRef.current = false;\n }\n }, [userChanged, router]);\n\n const session = {\n authenticated: !!user,\n idToken,\n };\n\n return (\n <SessionProvider data={session} isLoading={isLoading}>\n <CivicNextAuthTokenProviderInternal\n {...props}\n user={user}\n idToken={idToken}\n fetchUser={fetchUser}\n isLoading={isLoading}\n >\n {children}\n </CivicNextAuthTokenProviderInternal>\n </SessionProvider>\n );\n};\n\nconst CivicNextAuthProvider = ({\n children,\n ...props\n}: NextCivicAuthProviderProps) => {\n const resolvedConfig = resolveAuthConfig();\n const {\n clientId,\n oauthServer,\n callbackUrl,\n challengeUrl,\n logoutUrl,\n refreshUrl,\n logoutCallbackUrl,\n } = resolvedConfig;\n const [redirectUrl, setRedirectUrl] = useState<string>(\"\");\n\n useEffect(() => {\n if (typeof globalThis.window !== \"undefined\") {\n const appUrl = globalThis.window.location.origin;\n setRedirectUrl(resolveCallbackUrl(resolvedConfig, appUrl));\n }\n }, [callbackUrl, resolvedConfig]);\n\n return (\n <CivicAuthConfigProvider\n oauthServer={oauthServer}\n clientId={clientId}\n redirectUrl={redirectUrl}\n logoutRedirectUrl={logoutCallbackUrl}\n nonce={props?.nonce}\n challengeUrl={challengeUrl}\n refreshUrl={refreshUrl}\n logoutUrl={logoutUrl}\n logoutCallbackUrl={logoutCallbackUrl}\n >\n <AuthStatusProvider>\n <IframeProvider iframeMode={props.iframeMode}>\n <CivicNextAuthProviderInternal\n {...props}\n resolvedConfig={resolvedConfig}\n >\n {children}\n </CivicNextAuthProviderInternal>\n </IframeProvider>\n </AuthStatusProvider>\n </CivicAuthConfigProvider>\n );\n};\n\nexport { CivicNextAuthProvider, type NextCivicAuthProviderProps };\n"]}
1
+ {"version":3,"file":"NextAuthProvider.js","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProvider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AACb;;GAEG;AACH,OAAO,KAAK,EAAE,EACZ,eAAe,EACf,WAAW,EACX,SAAS,EACT,MAAM,EACN,QAAQ,GACT,MAAM,OAA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AC7B,QAAQ,EACR,GAAG,KAAK,EACmB,EAAE,EAAE;IAC/B,MAAM,cAAc,GAAG,iBAAiB,EAAE,CAAC;IAC3C,MAAM,EACJ,QAAQ,EACR,WAAW,EACX,WAAW,EACX,eAAe,EACf,YAAY,EACZ,SAAS,EACT,UAAU,EACV,iBAAiB,GAClB,GAAG,cAAc,CAAC;IACnB,MAAM,CAAC,WAAW,EAAE,cAAc,CAAC,GAAG,QAAQ,CAAS,EAAE,CAAC,CAAC;IAE3D,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,OAAO,UAAU,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;YAC7C,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;YACjD,cAAc,CAAC,kBAAkB,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC,CAAC;QAC7D,CAAC;IACH,CAAC,EAAE,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;IAElC,OAAO,CACL,KAAC,uBAAuB,IACtB,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,QAAQ,EAClB,eAAe,EAAE,eAAe,EAChC,WAAW,EAAE,WAAW,EACxB,iBAAiB,EAAE,iBAAiB,EACpC,KAAK,EAAE,KAAK,EAAE,KAAK,EACnB,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,UAAU,EACtB,SAAS,EAAE,SAAS,EACpB,iBAAiB,EAAE,iBAAiB,YAEpC,KAAC,kBAAkB,cACjB,KAAC,cAAc,IAAC,UAAU,EAAE,KAAK,CAAC,UAAU,YAC1C,KAAC,6BAA6B,OACxB,KAAK,EACT,cAAc,EAAE,cAAc,YAE7B,QAAQ,GACqB,GACjB,GACE,GACG,CAC3B,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,qBAAqB,EAAmC,CAAC","sourcesContent":["\"use client\";\n/**\n * A very small context provider for the user object - it takes the user object from the cookie and provides it to the app.\n */\nimport React, {\n startTransition,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\nimport {\n resolveAuthConfig,\n type AuthConfigWithDefaults,\n} from \"@/nextjs/config.js\";\nimport { resolveCallbackUrl } from \"@/nextjs/utils.js\";\nimport { ConfidentialClientPKCEConsumer } from \"@/services/PKCE.js\";\nimport { UserProvider } from \"@/shared/providers/UserProvider.js\";\nimport { useUserCookie } from \"@/nextjs/hooks/useUserCookie.js\";\nimport { CivicAuthConfigProvider } from \"@/shared/providers/CivicAuthConfigContext.js\";\nimport { SessionProvider } from \"@/shared/providers/SessionProvider.js\";\nimport { IframeProvider } from \"@/shared/providers/IframeProvider.js\";\nimport { TokenProvider } from \"@/shared/providers/TokenProvider.js\";\nimport { useSignIn } from \"@/shared/hooks/useSignIn.js\";\nimport { useCivicAuthConfig } from \"@/shared/hooks/useCivicAuthConfig.js\";\nimport { IFrameAndLoading } from \"@/shared/components/IFrameAndLoading.js\";\nimport { BlockDisplay } from \"@/shared/components/BlockDisplay.js\";\nimport { LoadingIcon } from \"@/shared/components/LoadingIcon.js\";\nimport { useIframe } from \"@/shared/hooks/useIframe.js\";\nimport type { AuthProviderProps } from \"@/shared/providers/types.js\";\nimport { useIsInIframe } from \"@/shared/hooks/useIsInIframe.js\";\nimport { AuthStatus, type UnknownObject, type User } from \"@/types.js\";\nimport { useRefresh } from \"@/nextjs/hooks/useRefresh.js\";\nimport { useCurrentUrl, useSession } from \"@/shared/hooks/index.js\";\nimport { BrowserCookieStorage } from \"@/shared/index.js\";\nimport { getIframeRef } from \"@/shared/lib/iframeUtils.js\";\nimport { AuthStatusProvider } from \"@/shared/providers/AuthStatusContext.js\";\nimport { useIsClient } from \"usehooks-ts\";\nimport { useRouter } from \"next/navigation.js\";\n\ntype CivicNextAuthTokenProviderInternalProps<TUser extends UnknownObject> =\n NextCivicAuthProviderInternalProps & {\n isLoading: boolean;\n idToken?: string;\n user: User<TUser> | null;\n fetchUser: () => void;\n };\ntype NextCivicAuthProviderInternalProps = Omit<\n AuthProviderProps,\n \"clientId\"\n> & {\n resolvedConfig: AuthConfigWithDefaults;\n};\ntype NextCivicAuthProviderProps = Omit<\n NextCivicAuthProviderInternalProps,\n \"clientId\" | \"resolvedConfig\" | \"redirectUrl\"\n>;\n\nconst CivicNextAuthTokenProviderInternal = <\n TUser extends UnknownObject = UnknownObject,\n>({\n children,\n displayMode = \"iframe\",\n user,\n fetchUser,\n ...props\n}: CivicNextAuthTokenProviderInternalProps<TUser>) => {\n const { iframeMode, resolvedConfig } = props;\n const { iframeRef, setIframeIsVisible, isIframeMounted, setIframeMounted } =\n useIframe();\n const civicAuthConfig = useCivicAuthConfig();\n const { challengeUrl } = resolvedConfig;\n const pkceConsumer = new ConfidentialClientPKCEConsumer(\n challengeUrl,\n resolvedConfig.basePath,\n );\n const { data: session } = useSession();\n const currentUrl = useCurrentUrl();\n\n useEffect(() => {\n if (session?.authenticated) {\n setIframeMounted(false);\n // the session is authenticated, so don't show the login iframe\n setIframeIsVisible(false);\n return;\n }\n }, [session?.authenticated, setIframeIsVisible, setIframeMounted]);\n\n const postSignOut = useCallback(async () => {\n // user is signed out, manually update the user from cookies to not wait for polling\n fetchUser();\n await props?.onSignOut?.();\n }, [fetchUser, props]);\n\n const { signIn, startSignIn, signOut, authStatus } = useSignIn({\n postSignOut,\n pkceConsumer,\n displayMode,\n });\n\n const { error: refreshError } = useRefresh();\n\n useEffect(() => {\n const ref = getIframeRef(iframeRef?.current, true);\n if (\n isIframeMounted &&\n civicAuthConfig &&\n !session?.authenticated &&\n ref &&\n authStatus === AuthStatus.UNAUTHENTICATED &&\n displayMode === \"iframe\" &&\n !currentUrl?.includes(\"code=\")\n ) {\n startSignIn();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n isIframeMounted,\n currentUrl,\n iframeMode,\n iframeRef,\n civicAuthConfig,\n session?.authenticated,\n authStatus,\n startSignIn,\n displayMode,\n ]);\n\n useEffect(() => {\n if (refreshError) {\n console.error(\"Error refreshing token, signing out...\", refreshError);\n signOut();\n }\n }, [refreshError, signOut]);\n\n // if the SDK loads in an iframe, we show the loading spinner as the iframe\n // will be waiting to be minimized\n const isInIframe = useIsInIframe();\n // we need this as server-side rendering will not have a window object\n // and will throw an error if we try to access it\n const isClient = useIsClient();\n return !isClient ? null : (\n <TokenProvider>\n <UserProvider\n storage={new BrowserCookieStorage()}\n user={user}\n signOut={signOut}\n signIn={signIn}\n displayMode={displayMode}\n authStatus={authStatus}\n >\n <IFrameAndLoading error={null} isLoading={isInIframe} />\n {isInIframe && (\n <BlockDisplay>\n <LoadingIcon />\n </BlockDisplay>\n )}\n {children}\n </UserProvider>\n </TokenProvider>\n );\n};\n\nconst CivicNextAuthProviderInternal = ({\n children,\n ...props\n}: NextCivicAuthProviderInternalProps) => {\n const { user, idToken, fetchUser, isLoading, userChanged } = useUserCookie();\n const hasRunRef = useRef(false);\n const router = useRouter();\n\n // if there are any changes in the user object, we need to refresh the page\n // to handle both login and logout cases. We use a 'hasRun' ref to prevent\n // the refresh from running multiple times in a row\n useEffect(() => {\n if (userChanged) {\n if (!hasRunRef.current) {\n hasRunRef.current = true;\n startTransition(() => {\n router.refresh();\n });\n }\n } else {\n hasRunRef.current = false;\n }\n }, [userChanged, router]);\n\n const session = {\n authenticated: !!user,\n idToken,\n };\n\n return (\n <SessionProvider data={session} isLoading={isLoading}>\n <CivicNextAuthTokenProviderInternal\n {...props}\n user={user}\n idToken={idToken}\n fetchUser={fetchUser}\n isLoading={isLoading}\n >\n {children}\n </CivicNextAuthTokenProviderInternal>\n </SessionProvider>\n );\n};\n\nconst CivicNextAuthProvider = ({\n children,\n ...props\n}: NextCivicAuthProviderProps) => {\n const resolvedConfig = resolveAuthConfig();\n const {\n clientId,\n oauthServer,\n callbackUrl,\n loginSuccessUrl,\n challengeUrl,\n logoutUrl,\n refreshUrl,\n logoutCallbackUrl,\n } = resolvedConfig;\n const [redirectUrl, setRedirectUrl] = useState<string>(\"\");\n\n useEffect(() => {\n if (typeof globalThis.window !== \"undefined\") {\n const appUrl = globalThis.window.location.origin;\n setRedirectUrl(resolveCallbackUrl(resolvedConfig, appUrl));\n }\n }, [callbackUrl, resolvedConfig]);\n\n return (\n <CivicAuthConfigProvider\n oauthServer={oauthServer}\n clientId={clientId}\n loginSuccessUrl={loginSuccessUrl}\n redirectUrl={redirectUrl}\n logoutRedirectUrl={logoutCallbackUrl}\n nonce={props?.nonce}\n challengeUrl={challengeUrl}\n refreshUrl={refreshUrl}\n logoutUrl={logoutUrl}\n logoutCallbackUrl={logoutCallbackUrl}\n >\n <AuthStatusProvider>\n <IframeProvider iframeMode={props.iframeMode}>\n <CivicNextAuthProviderInternal\n {...props}\n resolvedConfig={resolvedConfig}\n >\n {children}\n </CivicNextAuthProviderInternal>\n </IframeProvider>\n </AuthStatusProvider>\n </CivicAuthConfigProvider>\n );\n};\n\nexport { CivicNextAuthProvider, type NextCivicAuthProviderProps };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"routeHandler.d.ts","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAWrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAqU9C,wBAAsB,YAAY,CAChC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CAkCvB;AAED,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CAmDvB;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,OAAO,iCAEF,WAAW,KAAG,OAAO,CAAC,YAAY,CAkCjD,CAAC"}
1
+ {"version":3,"file":"routeHandler.d.ts","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,UAAU,EAA0B,MAAM,oBAAoB,CAAC;AAW7E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AA6Z9C,wBAAsB,YAAY,CAChC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CAiCvB;AA6CD,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CAkBvB;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,OAAO,iCAEF,WAAW,KAAG,OAAO,CAAC,YAAY,CAkCjD,CAAC"}