@civic/auth 0.4.5 → 0.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/nextjs/cookies.d.ts.map +1 -1
- package/dist/nextjs/cookies.js +2 -4
- package/dist/nextjs/cookies.js.map +1 -1
- package/dist/nextjs/hooks/useRefresh.d.ts +1 -2
- package/dist/nextjs/hooks/useRefresh.d.ts.map +1 -1
- package/dist/nextjs/hooks/useRefresh.js +3 -1
- package/dist/nextjs/hooks/useRefresh.js.map +1 -1
- package/dist/nextjs/index.js +1 -1
- package/dist/nextjs/index.js.map +1 -1
- package/dist/nextjs/middleware.d.ts +3 -2
- package/dist/nextjs/middleware.d.ts.map +1 -1
- package/dist/nextjs/middleware.js +16 -6
- package/dist/nextjs/middleware.js.map +1 -1
- package/dist/nextjs/providers/NextAuthProvider.js +1 -1
- package/dist/nextjs/providers/NextAuthProvider.js.map +1 -1
- package/dist/nextjs/routeHandler.d.ts.map +1 -1
- package/dist/nextjs/routeHandler.js +29 -8
- package/dist/nextjs/routeHandler.js.map +1 -1
- package/dist/reactjs/providers/AuthProvider.d.ts +1 -1
- package/dist/reactjs/providers/AuthProvider.d.ts.map +1 -1
- package/dist/reactjs/providers/AuthProvider.js +4 -26
- package/dist/reactjs/providers/AuthProvider.js.map +1 -1
- package/dist/reactjs/providers/CivicAuthProvider.d.ts.map +1 -1
- package/dist/reactjs/providers/CivicAuthProvider.js +2 -2
- package/dist/reactjs/providers/CivicAuthProvider.js.map +1 -1
- package/dist/reactjs/providers/ClientTokenExchangeSessionProvider.d.ts +1 -1
- package/dist/reactjs/providers/ClientTokenExchangeSessionProvider.d.ts.map +1 -1
- package/dist/reactjs/providers/ClientTokenExchangeSessionProvider.js +50 -14
- package/dist/reactjs/providers/ClientTokenExchangeSessionProvider.js.map +1 -1
- package/dist/server/ServerAuthenticationResolver.d.ts +7 -1
- package/dist/server/ServerAuthenticationResolver.d.ts.map +1 -1
- package/dist/server/ServerAuthenticationResolver.js +66 -4
- package/dist/server/ServerAuthenticationResolver.js.map +1 -1
- package/dist/services/AuthenticationService.d.ts +2 -0
- package/dist/services/AuthenticationService.d.ts.map +1 -1
- package/dist/services/AuthenticationService.js +78 -13
- package/dist/services/AuthenticationService.js.map +1 -1
- package/dist/services/types.d.ts +2 -1
- package/dist/services/types.d.ts.map +1 -1
- package/dist/services/types.js.map +1 -1
- package/dist/shared/hooks/index.d.ts +1 -0
- package/dist/shared/hooks/index.d.ts.map +1 -1
- package/dist/shared/hooks/index.js +1 -0
- package/dist/shared/hooks/index.js.map +1 -1
- package/dist/shared/hooks/useSignIn.d.ts +1 -1
- package/dist/shared/hooks/useSignIn.d.ts.map +1 -1
- package/dist/shared/hooks/useSignIn.js +3 -1
- package/dist/shared/hooks/useSignIn.js.map +1 -1
- package/dist/shared/lib/AuthenticationRefresherImpl.d.ts.map +1 -1
- package/dist/shared/lib/AuthenticationRefresherImpl.js +25 -11
- package/dist/shared/lib/AuthenticationRefresherImpl.js.map +1 -1
- package/dist/shared/lib/GenericAuthenticationRefresher.d.ts.map +1 -1
- package/dist/shared/lib/GenericAuthenticationRefresher.js +13 -2
- package/dist/shared/lib/GenericAuthenticationRefresher.js.map +1 -1
- package/dist/shared/lib/session.d.ts +5 -0
- package/dist/shared/lib/session.d.ts.map +1 -1
- package/dist/shared/lib/session.js +11 -2
- package/dist/shared/lib/session.js.map +1 -1
- package/dist/shared/lib/types.d.ts +2 -1
- package/dist/shared/lib/types.d.ts.map +1 -1
- package/dist/shared/lib/types.js.map +1 -1
- package/dist/shared/lib/util.d.ts +18 -1
- package/dist/shared/lib/util.d.ts.map +1 -1
- package/dist/shared/lib/util.js +53 -24
- package/dist/shared/lib/util.js.map +1 -1
- package/dist/shared/providers/CivicAuthConfigContext.d.ts +3 -1
- package/dist/shared/providers/CivicAuthConfigContext.d.ts.map +1 -1
- package/dist/shared/providers/CivicAuthConfigContext.js +3 -1
- package/dist/shared/providers/CivicAuthConfigContext.js.map +1 -1
- package/dist/shared/version.d.ts +1 -1
- package/dist/shared/version.js +1 -1
- package/dist/shared/version.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookies.d.ts","sourceRoot":"","sources":["../../src/nextjs/cookies.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"cookies.d.ts","sourceRoot":"","sources":["../../src/nextjs/cookies.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAExD;;GAEG;AACH,QAAA,MAAM,gBAAgB,qBAGrB,CAAC;AAEF,cAAM,mBAAoB,SAAQ,aAAa;IAC1B,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;gBAAhD,MAAM,GAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,CAAM;IAOlE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAKxC,GAAG,CACP,GAAG,EAAE,SAAS,EACd,KAAK,EAAE,MAAM,EACb,oBAAoB,GAAE,OAAO,CAAC,YAAY,CAAM,GAC/C,OAAO,CAAC,IAAI,CAAC;IASV,MAAM,CAAC,GAAG,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;CAI5C;AAED,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,CAAC"}
|
package/dist/nextjs/cookies.js
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
import { cookies } from "next/headers.js";
|
|
2
|
-
import { clearAuthServerSession, clearTokens, clearUser, } from "../shared/lib/util.js";
|
|
3
2
|
import {} from "../shared/lib/types.js";
|
|
4
3
|
import { CookieStorage } from "../shared/lib/storage.js";
|
|
4
|
+
import * as session from "../shared/lib/session.js";
|
|
5
5
|
/**
|
|
6
6
|
* Clears all authentication cookies on server. Note, this can only be called by the server
|
|
7
7
|
*/
|
|
8
8
|
const clearAuthCookies = async () => {
|
|
9
9
|
const cookieStorage = new NextjsCookieStorage(); // no cookie storage needed to simply clear it
|
|
10
|
-
await
|
|
11
|
-
await clearUser(cookieStorage);
|
|
12
|
-
await clearAuthServerSession(cookieStorage);
|
|
10
|
+
await session.clearAuthCookies(cookieStorage);
|
|
13
11
|
};
|
|
14
12
|
class NextjsCookieStorage extends CookieStorage {
|
|
15
13
|
config;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookies.js","sourceRoot":"","sources":["../../src/nextjs/cookies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"cookies.js","sourceRoot":"","sources":["../../src/nextjs/cookies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAG1C,OAAO,EAAqB,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,KAAK,OAAO,MAAM,yBAAyB,CAAC;AACnD;;GAEG;AACH,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;IAClC,MAAM,aAAa,GAAG,IAAI,mBAAmB,EAAE,CAAC,CAAC,8CAA8C;IAC/F,MAAM,OAAO,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;AAChD,CAAC,CAAC;AAEF,MAAM,mBAAoB,SAAQ,aAAa;IAC1B;IAAnB,YAAmB,SAAmD,EAAE;QACtE,KAAK,CAAC;YACJ,MAAM,EAAE,IAAI;YACZ,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QAJc,WAAM,GAAN,MAAM,CAA+C;IAKxE,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAW;QACnB,MAAM,WAAW,GAAG,MAAM,OAAO,EAAE,CAAC;QACpC,OAAO,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC;IAC7C,CAAC;IAED,KAAK,CAAC,GAAG,CACP,GAAc,EACd,KAAa,EACb,uBAA8C,EAAE;QAEhD,MAAM,WAAW,GAAG,MAAM,OAAO,EAAE,CAAC;QACpC,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,GAAgB,CAAC,IAAI;YACxD,GAAG,IAAI,CAAC,QAAQ;SACjB,CAAC;QACF,MAAM,iBAAiB,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,oBAAoB,EAAE,CAAC;QACzE,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,iBAAiB,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAc;QACzB,MAAM,WAAW,GAAG,MAAM,OAAO,EAAE,CAAC;QACpC,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC1B,CAAC;CACF;AAED,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,CAAC","sourcesContent":["import { cookies } from \"next/headers.js\";\n\nimport type { KeySetter } from \"@/shared/lib/types.js\";\nimport { type CookieConfig } from \"@/shared/lib/types.js\";\nimport { CookieStorage } from \"@/shared/lib/storage.js\";\nimport * as session from \"@/shared/lib/session.js\";\n/**\n * Clears all authentication cookies on server. Note, this can only be called by the server\n */\nconst clearAuthCookies = async () => {\n const cookieStorage = new NextjsCookieStorage(); // no cookie storage needed to simply clear it\n await session.clearAuthCookies(cookieStorage);\n};\n\nclass NextjsCookieStorage extends CookieStorage {\n constructor(public config: Partial<Record<KeySetter, CookieConfig>> = {}) {\n super({\n secure: true,\n httpOnly: true,\n });\n }\n\n async get(key: string): Promise<string | null> {\n const cookieStore = await cookies();\n return cookieStore.get(key)?.value || null;\n }\n\n async set(\n key: KeySetter,\n value: string,\n cookieConfigOverride: Partial<CookieConfig> = {},\n ): Promise<void> {\n const cookieStore = await cookies();\n const cookieSettings = this.config?.[key as KeySetter] || {\n ...this.settings,\n };\n const useCookieSettings = { ...cookieSettings, ...cookieConfigOverride };\n cookieStore.set(key, value, useCookieSettings);\n }\n\n async delete(key: KeySetter): Promise<void> {\n const cookieStore = await cookies();\n cookieStore.delete(key);\n }\n}\n\nexport { clearAuthCookies, NextjsCookieStorage };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRefresh.d.ts","sourceRoot":"","sources":["../../../src/nextjs/hooks/useRefresh.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useRefresh.d.ts","sourceRoot":"","sources":["../../../src/nextjs/hooks/useRefresh.ts"],"names":[],"mappings":"AAOA,QAAA,MAAM,UAAU;;CAsDf,CAAC;AAEF,OAAO,EAAE,UAAU,EAAE,CAAC"}
|
|
@@ -3,8 +3,10 @@ import { useEffect, useState } from "react";
|
|
|
3
3
|
import { BrowserCookieStorage } from "../../shared/index.js";
|
|
4
4
|
import { resolveAuthConfig } from "../config.js";
|
|
5
5
|
import { NextClientAuthenticationRefresher } from "../NextClientAuthenticationRefresher.js";
|
|
6
|
-
|
|
6
|
+
import { useSession } from "../../shared/hooks/useSession.js";
|
|
7
|
+
const useRefresh = () => {
|
|
7
8
|
const [error, setError] = useState();
|
|
9
|
+
const { data: session } = useSession();
|
|
8
10
|
const authConfig = useCivicAuthConfig();
|
|
9
11
|
// setup token autorefresh
|
|
10
12
|
const [refresher, setRefresher] = useState(undefined);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRefresh.js","sourceRoot":"","sources":["../../../src/nextjs/hooks/useRefresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;
|
|
1
|
+
{"version":3,"file":"useRefresh.js","sourceRoot":"","sources":["../../../src/nextjs/hooks/useRefresh.ts"],"names":[],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EACjB,OAAO,EACP,OAAO,CACR,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE;YACtB,IAAI,eAAe,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO;YAE3C,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;YACrC,YAAY,CAAC,YAAY,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;QAEH,OAAO,GAAG,EAAE;YACV,eAAe,CAAC,KAAK,EAAE,CAAC;YACxB,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;QACvC,CAAC,CAAC;QACF,uDAAuD;IACzD,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,uCAAuC;IAEzD,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,OAAO,EAAE,aAAa,EAAE,CAAC;YAC3B,SAAS,EAAE,gBAAgB,EAAE,CAAC;QAChC,CAAC;aAAM,CAAC;YACN,SAAS,EAAE,gBAAgB,EAAE,CAAC;QAChC,CAAC;QAED,OAAO,GAAG,EAAE,CAAC,SAAS,EAAE,gBAAgB,EAAE,CAAC;IAC7C,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC,CAAC;IAExC,OAAO;QACL,KAAK;KACN,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,UAAU,EAAE,CAAC","sourcesContent":["import { useCivicAuthConfig } from \"@/shared/hooks/useCivicAuthConfig.js\";\nimport { useEffect, useState } from \"react\";\nimport { BrowserCookieStorage } from \"@/shared/index.js\";\nimport { resolveAuthConfig } from \"../config.js\";\nimport { NextClientAuthenticationRefresher } from \"../NextClientAuthenticationRefresher.js\";\nimport { useSession } from \"@/shared/hooks/useSession.js\";\n\nconst useRefresh = () => {\n const [error, setError] = useState<Error>();\n const { data: session } = useSession();\n const authConfig = useCivicAuthConfig();\n\n // setup token autorefresh\n const [refresher, setRefresher] = useState<\n NextClientAuthenticationRefresher | undefined\n >(undefined);\n\n useEffect(() => {\n if (!authConfig) return;\n const abortController = new AbortController();\n const currentRefresher = refresher;\n const config = resolveAuthConfig(authConfig ?? {});\n const storage = new BrowserCookieStorage(\n config.cookies.tokens.access_token,\n );\n const onError = async (error: Error) => {\n console.error(\"Error refreshing token\", error);\n refresher?.clearAutorefresh();\n setError(error);\n };\n NextClientAuthenticationRefresher.build(\n { ...authConfig },\n storage,\n onError,\n ).then((newRefresher) => {\n if (abortController.signal.aborted) return;\n\n currentRefresher?.clearAutorefresh();\n setRefresher(newRefresher);\n });\n\n return () => {\n abortController.abort();\n currentRefresher?.clearAutorefresh();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [authConfig]); // Only depend on what actually changes\n\n useEffect(() => {\n if (session?.authenticated) {\n refresher?.setupAutorefresh();\n } else {\n refresher?.clearAutorefresh();\n }\n\n return () => refresher?.clearAutorefresh();\n }, [refresher, session?.authenticated]);\n\n return {\n error,\n };\n};\n\nexport { useRefresh };\n"]}
|
package/dist/nextjs/index.js
CHANGED
|
@@ -13,7 +13,7 @@ const getAuthResolver = async () => {
|
|
|
13
13
|
};
|
|
14
14
|
export const isLoggedIn = async () => {
|
|
15
15
|
const authResolver = await getAuthResolver();
|
|
16
|
-
const existingSession = await authResolver.validateExistingSession();
|
|
16
|
+
const existingSession = await authResolver.validateExistingSession(false);
|
|
17
17
|
return existingSession.authenticated;
|
|
18
18
|
};
|
|
19
19
|
export const getUser = async () => {
|
package/dist/nextjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/nextjs/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AAExF,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,CAAC;AACf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,MAAM,aAAa,GAAG,IAAI,mBAAmB,EAAE,CAAC;IAChD,OAAO,4BAA4B,CAAC,KAAK,CACvC,EAAE,GAAG,MAAM,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,EAAE,EAC9C,aAAa,CACd,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,UAAU,GAAG,KAAK,IAAsB,EAAE;IACrD,MAAM,YAAY,GAAG,MAAM,eAAe,EAAE,CAAC;IAC7C,MAAM,eAAe,GAAG,MAAM,YAAY,CAAC,uBAAuB,CAAC,KAAK,CAAC,CAAC;IAC1E,OAAO,eAAe,CAAC,aAAa,CAAC;AACvC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,OAAO,GAAG,KAAK,IAEC,EAAE;IAC7B,MAAM,eAAe,GAAG,MAAM,UAAU,EAAE,CAAC;IAC3C,IAAI,CAAC,eAAe;QAAE,OAAO,IAAI,CAAC;IAClC,MAAM,aAAa,GAAG,IAAI,mBAAmB,EAAE,CAAC;IAChD,OAAO,cAAc,CAAI,aAAa,CAAC,CAAC;AAC1C,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,IAAiC,EAAE;IAC/D,MAAM,eAAe,GAAG,MAAM,UAAU,EAAE,CAAC;IAC3C,IAAI,CAAC,eAAe;QAAE,OAAO,IAAI,CAAC;IAClC,MAAM,aAAa,GAAG,IAAI,mBAAmB,EAAE,CAAC;IAChD,OAAO,gBAAgB,CAAC,aAAa,CAAC,CAAC;AACzC,CAAC,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAM1D,OAAO,EACL,qBAAqB,IAAI,iBAAiB,GAE3C,MAAM,wCAAwC,CAAC","sourcesContent":["import { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { NextjsCookieStorage } from \"@/nextjs/cookies.js\";\nimport { ServerAuthenticationResolver } from \"@/server/ServerAuthenticationResolver.js\";\nimport type { AuthenticationResolver } from \"@/services/types.js\";\nimport { printVersion } from \"@/shared/index.js\";\nprintVersion();\nimport {\n getTokens as getSessionTokens,\n getUser as getSessionUser,\n} from \"@/shared/lib/session.js\";\nimport type { EmptyObject, OAuthTokens, UnknownObject, User } from \"@/types.js\";\nexport { resolveAuthConfig };\n\nexport { createCivicAuthPlugin, defaultAuthConfig } from \"@/nextjs/config.js\";\n\nconst getAuthResolver = async (): Promise<AuthenticationResolver> => {\n const config = resolveAuthConfig();\n const clientStorage = new NextjsCookieStorage();\n return ServerAuthenticationResolver.build(\n { ...config, redirectUrl: config.callbackUrl },\n clientStorage,\n );\n};\n\nexport const isLoggedIn = async (): Promise<boolean> => {\n const authResolver = await getAuthResolver();\n const existingSession = await authResolver.validateExistingSession(false);\n return existingSession.authenticated;\n};\n\nexport const getUser = async <\n T extends UnknownObject = EmptyObject,\n>(): Promise<User<T> | null> => {\n const hasValidSession = await isLoggedIn();\n if (!hasValidSession) return null;\n const clientStorage = new NextjsCookieStorage();\n return getSessionUser<T>(clientStorage);\n};\n\nexport const getTokens = async (): Promise<OAuthTokens | null> => {\n const hasValidSession = await isLoggedIn();\n if (!hasValidSession) return null;\n const clientStorage = new NextjsCookieStorage();\n return getSessionTokens(clientStorage);\n};\n\nexport { handler } from \"@/nextjs/routeHandler.js\";\nexport { NextjsCookieStorage } from \"@/nextjs/cookies.js\";\nexport type {\n AuthConfig,\n CookiesConfigObject,\n AuthConfigWithDefaults,\n} from \"@/nextjs/config.js\";\nexport {\n CivicNextAuthProvider as CivicAuthProvider,\n type NextCivicAuthProviderProps as AuthProviderProps,\n} from \"@/nextjs/providers/NextAuthProvider.js\";\n"]}
|
|
@@ -22,15 +22,16 @@
|
|
|
22
22
|
import type { NextRequest } from "next/server.js";
|
|
23
23
|
import { NextResponse } from "next/server.js";
|
|
24
24
|
import type { AuthConfigWithDefaults, OptionalAuthConfig } from "../nextjs/config.js";
|
|
25
|
+
import type { SessionData } from "../types.js";
|
|
25
26
|
type Middleware = (request: NextRequest) => Promise<NextResponse> | NextResponse;
|
|
26
27
|
/**
|
|
27
28
|
* use a ServerAuthenticationResolver to validate the existing session
|
|
28
29
|
* using NextJS cookie storage
|
|
29
30
|
* @param authConfigWithDefaults
|
|
30
31
|
* @param request NextRequest object from middleware
|
|
31
|
-
* @returns {Promise<
|
|
32
|
+
* @returns {Promise<SessionData>}
|
|
32
33
|
*/
|
|
33
|
-
export declare const validateAuthTokensIfPresent: (authConfigWithDefaults: AuthConfigWithDefaults, request: NextRequest) => Promise<
|
|
34
|
+
export declare const validateAuthTokensIfPresent: (authConfigWithDefaults: AuthConfigWithDefaults, request: NextRequest) => Promise<SessionData>;
|
|
34
35
|
/**
|
|
35
36
|
*
|
|
36
37
|
* Use this when auth is the only middleware you need.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/nextjs/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,KAAK,EACV,sBAAsB,EACtB,kBAAkB,EACnB,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/nextjs/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,KAAK,EACV,sBAAsB,EACtB,kBAAkB,EACnB,MAAM,oBAAoB,CAAC;AAI5B,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,YAAY,CAAC;AA+B3D,KAAK,UAAU,GAAG,CAChB,OAAO,EAAE,WAAW,KACjB,OAAO,CAAC,YAAY,CAAC,GAAG,YAAY,CAAC;AAuB1C;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B,GACtC,wBAAwB,sBAAsB,EAC9C,SAAS,WAAW,KACnB,OAAO,CAAC,WAAW,CAoBrB,CAAC;AA8DF;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,GACxB,aAAY,kBAAuB,MAC7B,SAAS,WAAW,KAAG,OAAO,CAAC,YAAY,CAOjD,CAAC;AAEJ;;;;;;;GAOG;AAEH,wBAAgB,QAAQ,CACtB,UAAU,EAAE,UAAU,GACrB,CAAC,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,CAEjD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,IAAI,CAAC,UAAU,GAAE,kBAAuB,IAEpD,YAAY,UAAU,KACrB,CAAC,CAAC,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC,CAQrD"}
|
|
@@ -54,7 +54,7 @@ const matchesGlobs = (pathname, patterns) => patterns.some((pattern) => {
|
|
|
54
54
|
* using NextJS cookie storage
|
|
55
55
|
* @param authConfigWithDefaults
|
|
56
56
|
* @param request NextRequest object from middleware
|
|
57
|
-
* @returns {Promise<
|
|
57
|
+
* @returns {Promise<SessionData>}
|
|
58
58
|
*/
|
|
59
59
|
export const validateAuthTokensIfPresent = async (authConfigWithDefaults, request) => {
|
|
60
60
|
try {
|
|
@@ -65,19 +65,20 @@ export const validateAuthTokensIfPresent = async (authConfigWithDefaults, reques
|
|
|
65
65
|
...authConfigWithDefaults,
|
|
66
66
|
redirectUrl: authConfigWithDefaults.callbackUrl,
|
|
67
67
|
}, storage);
|
|
68
|
-
|
|
69
|
-
|
|
68
|
+
// validate the existing session but don't auto-refresh as we can't set cookies in middleware
|
|
69
|
+
const existingSession = await authSessionService.validateExistingSession(false);
|
|
70
|
+
return existingSession;
|
|
70
71
|
}
|
|
71
72
|
catch (error) {
|
|
72
73
|
logger.error("Error validating tokens", error);
|
|
73
|
-
return false;
|
|
74
|
+
return { authenticated: false };
|
|
74
75
|
}
|
|
75
76
|
};
|
|
76
77
|
// internal - used by all exported functions
|
|
77
78
|
const applyAuth = async (authConfig, request) => {
|
|
78
79
|
const authConfigWithDefaults = resolveAuthConfig(authConfig);
|
|
79
80
|
// Check for any valid auth token
|
|
80
|
-
const
|
|
81
|
+
const session = await validateAuthTokensIfPresent(authConfigWithDefaults, request);
|
|
81
82
|
// skip auth check for redirect to login url
|
|
82
83
|
if (request.nextUrl.pathname === authConfigWithDefaults.loginUrl &&
|
|
83
84
|
request.method === "GET") {
|
|
@@ -93,7 +94,16 @@ const applyAuth = async (authConfig, request) => {
|
|
|
93
94
|
return undefined;
|
|
94
95
|
}
|
|
95
96
|
// Check for either token type
|
|
96
|
-
if (!
|
|
97
|
+
if (!session.authenticated) {
|
|
98
|
+
if (session.refreshToken) {
|
|
99
|
+
const refreshUrl = new URL(authConfigWithDefaults.refreshUrl, request.nextUrl.origin);
|
|
100
|
+
// set targetUrl to the original request URL without search params
|
|
101
|
+
// to avoid redirect loops
|
|
102
|
+
refreshUrl.searchParams.set("targetUrl", request.nextUrl.origin + request.nextUrl.pathname);
|
|
103
|
+
const redirectUrl = `${refreshUrl.toString()}`;
|
|
104
|
+
logger.debug(`→ Refresh token found - redirecting to "${redirectUrl}"`);
|
|
105
|
+
return NextResponse.redirect(redirectUrl);
|
|
106
|
+
}
|
|
97
107
|
const loginUrl = new URL(authConfigWithDefaults.loginUrl, request.nextUrl.origin);
|
|
98
108
|
const redirectUrl = `${loginUrl.toString()}`;
|
|
99
109
|
logger.debug(`→ No valid token found - redirecting to "${redirectUrl}"`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/nextjs/middleware.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,SAAS,MAAM,WAAW,CAAC;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H,sDAAsD;AACtD,MAAM,UAAU,QAAQ,CACtB,UAAsB;IAEtB,OAAO,IAAI,EAAE,CAAC,UAAU,CAAC,CAAC;AAC5B,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,IAAI,CAAC,aAAiC,EAAE;IACtD,OAAO,CACL,UAAsB,EAC6B,EAAE;QACrD,OAAO,KAAK,EAAE,OAAoB,EAAyB,EAAE;YAC3D,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;YACtD,IAAI,QAAQ;gBAAE,OAAO,QAAQ,CAAC;YAE9B,OAAO,UAAU,CAAC,OAAO,CAAC,CAAC;QAC7B,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Authenticates the user on all requests by checking the token cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * logger.debug('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * logger.debug('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport picomatch from \"picomatch\";\nimport type {\n AuthConfigWithDefaults,\n OptionalAuthConfig,\n} from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { ServerAuthenticationResolver } from \"@/server/ServerAuthenticationResolver.js\";\nimport type { AuthStorage } from \"@/types.js\";\n\nconst logger = loggers.nextjs.middleware;\n\n/**\n * CookieStorage implementation for NextJS middleware context that works with NextRequest\n */\nclass NextjsReadOnlyRequestCookieStorage implements AuthStorage {\n constructor(private request: NextRequest) {}\n\n async get(key: string): Promise<string | null> {\n return this.request.cookies.get(key)?.value || null;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async set(key: string, value: string): Promise<void> {\n // In middleware, we can only set cookies via response objects\n // This method can't be used directly in middleware\n logger.error(\"Cannot set cookies directly in middleware\");\n throw new Error(\"Cannot set cookies directly in middleware\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async delete(key: string): Promise<void> {\n // In middleware, we can only delete cookies via response objects\n // This method can't be used directly in middleware\n logger.error(\"Cannot delete cookies directly in middleware\");\n throw new Error(\"Cannot delete cookies directly in middleware\");\n }\n}\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchGlob = (pathname: string, globPattern: string) => {\n const matches = picomatch(globPattern);\n return matches(pathname);\n};\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchesGlobs = (pathname: string, patterns: string[]) =>\n patterns.some((pattern) => {\n if (!pattern) return false;\n return matchGlob(pathname, pattern);\n });\n\n/**\n * use a ServerAuthenticationResolver to validate the existing session\n * using NextJS cookie storage\n * @param authConfigWithDefaults\n * @param request NextRequest object from middleware\n * @returns {Promise<boolean>}\n */\nexport const validateAuthTokensIfPresent = async (\n authConfigWithDefaults: AuthConfigWithDefaults,\n request: NextRequest,\n): Promise<boolean> => {\n try {\n // TODO: evaluate a more performant way to validate tokens\n // than having to call and verify the JWT tokens on every request\n const storage = new NextjsReadOnlyRequestCookieStorage(request);\n const authSessionService = await ServerAuthenticationResolver.build(\n {\n ...authConfigWithDefaults,\n redirectUrl: authConfigWithDefaults.callbackUrl,\n },\n storage,\n );\n const existingSession = await authSessionService.validateExistingSession();\n return existingSession.authenticated;\n } catch (error) {\n logger.error(\"Error validating tokens\", error);\n return false;\n }\n};\n// internal - used by all exported functions\nconst applyAuth = async (\n authConfig: OptionalAuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n // Check for any valid auth token\n const isAuthenticated = await validateAuthTokensIfPresent(\n authConfigWithDefaults,\n request,\n );\n\n // skip auth check for redirect to login url\n if (\n request.nextUrl.pathname === authConfigWithDefaults.loginUrl &&\n request.method === \"GET\"\n ) {\n logger.debug(\"→ Skipping auth check - this is the login URL\");\n return undefined;\n }\n\n if (!matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.include)) {\n logger.debug(\"→ Skipping auth check - path not in include patterns\");\n return undefined;\n }\n\n if (matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.exclude)) {\n logger.debug(\"→ Skipping auth check - path in exclude patterns\");\n return undefined;\n }\n\n // Check for either token type\n if (!isAuthenticated) {\n const loginUrl = new URL(\n authConfigWithDefaults.loginUrl,\n request.nextUrl.origin,\n );\n const redirectUrl = `${loginUrl.toString()}`;\n logger.debug(`→ No valid token found - redirecting to \"${redirectUrl}\"`);\n return NextResponse.redirect(redirectUrl);\n }\n\n logger.debug(\"→ Auth check passed\");\n return undefined;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig: OptionalAuthConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return auth()(middleware);\n}\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * export default auth(authConfig: AuthConfig ) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: OptionalAuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n return middleware(request);\n };\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/nextjs/middleware.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,SAAS,MAAM,WAAW,CAAC;AAKlC,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AAGxF,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC;AAEzC;;GAEG;AACH,MAAM,kCAAkC;IAClB;IAApB,YAAoB,OAAoB;QAApB,YAAO,GAAP,OAAO,CAAa;IAAG,CAAC;IAE5C,KAAK,CAAC,GAAG,CAAC,GAAW;QACnB,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC;IACtD,CAAC;IAED,6DAA6D;IAC7D,KAAK,CAAC,GAAG,CAAC,GAAW,EAAE,KAAa;QAClC,8DAA8D;QAC9D,mDAAmD;QACnD,MAAM,CAAC,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC1D,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;IAC/D,CAAC;IAED,6DAA6D;IAC7D,KAAK,CAAC,MAAM,CAAC,GAAW;QACtB,iEAAiE;QACjE,mDAAmD;QACnD,MAAM,CAAC,KAAK,CAAC,8CAA8C,CAAC,CAAC;QAC7D,MAAM,IAAI,KAAK,CAAC,8CAA8C,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AAM,SAAS,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;YACtD,IAAI,QAAQ;gBAAE,OAAO,QAAQ,CAAC;YAE9B,OAAO,UAAU,CAAC,OAAO,CAAC,CAAC;QAC7B,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Authenticates the user on all requests by checking the token cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * logger.debug('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * logger.debug('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport picomatch from \"picomatch\";\nimport type {\n AuthConfigWithDefaults,\n OptionalAuthConfig,\n} from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { ServerAuthenticationResolver } from \"@/server/ServerAuthenticationResolver.js\";\nimport type { AuthStorage, SessionData } from \"@/types.js\";\n\nconst logger = loggers.nextjs.middleware;\n\n/**\n * CookieStorage implementation for NextJS middleware context that works with NextRequest\n */\nclass NextjsReadOnlyRequestCookieStorage implements AuthStorage {\n constructor(private request: NextRequest) {}\n\n async get(key: string): Promise<string | null> {\n return this.request.cookies.get(key)?.value || null;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async set(key: string, value: string): Promise<void> {\n // In middleware, we can only set cookies via response objects\n // This method can't be used directly in middleware\n logger.error(\"Cannot set cookies directly in middleware\");\n throw new Error(\"Cannot set cookies directly in middleware\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async delete(key: string): Promise<void> {\n // In middleware, we can only delete cookies via response objects\n // This method can't be used directly in middleware\n logger.error(\"Cannot delete cookies directly in middleware\");\n throw new Error(\"Cannot delete cookies directly in middleware\");\n }\n}\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchGlob = (pathname: string, globPattern: string) => {\n const matches = picomatch(globPattern);\n return matches(pathname);\n};\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchesGlobs = (pathname: string, patterns: string[]) =>\n patterns.some((pattern) => {\n if (!pattern) return false;\n return matchGlob(pathname, pattern);\n });\n\n/**\n * use a ServerAuthenticationResolver to validate the existing session\n * using NextJS cookie storage\n * @param authConfigWithDefaults\n * @param request NextRequest object from middleware\n * @returns {Promise<SessionData>}\n */\nexport const validateAuthTokensIfPresent = async (\n authConfigWithDefaults: AuthConfigWithDefaults,\n request: NextRequest,\n): Promise<SessionData> => {\n try {\n // TODO: evaluate a more performant way to validate tokens\n // than having to call and verify the JWT tokens on every request\n const storage = new NextjsReadOnlyRequestCookieStorage(request);\n const authSessionService = await ServerAuthenticationResolver.build(\n {\n ...authConfigWithDefaults,\n redirectUrl: authConfigWithDefaults.callbackUrl,\n },\n storage,\n );\n // validate the existing session but don't auto-refresh as we can't set cookies in middleware\n const existingSession =\n await authSessionService.validateExistingSession(false);\n return existingSession;\n } catch (error) {\n logger.error(\"Error validating tokens\", error);\n return { authenticated: false };\n }\n};\n// internal - used by all exported functions\nconst applyAuth = async (\n authConfig: OptionalAuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n // Check for any valid auth token\n const session = await validateAuthTokensIfPresent(\n authConfigWithDefaults,\n request,\n );\n\n // skip auth check for redirect to login url\n if (\n request.nextUrl.pathname === authConfigWithDefaults.loginUrl &&\n request.method === \"GET\"\n ) {\n logger.debug(\"→ Skipping auth check - this is the login URL\");\n return undefined;\n }\n\n if (!matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.include)) {\n logger.debug(\"→ Skipping auth check - path not in include patterns\");\n return undefined;\n }\n\n if (matchesGlobs(request.nextUrl.pathname, authConfigWithDefaults.exclude)) {\n logger.debug(\"→ Skipping auth check - path in exclude patterns\");\n return undefined;\n }\n\n // Check for either token type\n if (!session.authenticated) {\n if (session.refreshToken) {\n const refreshUrl = new URL(\n authConfigWithDefaults.refreshUrl,\n request.nextUrl.origin,\n );\n // set targetUrl to the original request URL without search params\n // to avoid redirect loops\n refreshUrl.searchParams.set(\n \"targetUrl\",\n request.nextUrl.origin + request.nextUrl.pathname,\n );\n const redirectUrl = `${refreshUrl.toString()}`;\n logger.debug(`→ Refresh token found - redirecting to \"${redirectUrl}\"`);\n return NextResponse.redirect(redirectUrl);\n }\n const loginUrl = new URL(\n authConfigWithDefaults.loginUrl,\n request.nextUrl.origin,\n );\n const redirectUrl = `${loginUrl.toString()}`;\n logger.debug(`→ No valid token found - redirecting to \"${redirectUrl}\"`);\n return NextResponse.redirect(redirectUrl);\n }\n\n logger.debug(\"→ Auth check passed\");\n return undefined;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig: OptionalAuthConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return auth()(middleware);\n}\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * export default auth(authConfig: AuthConfig ) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: OptionalAuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n return middleware(request);\n };\n };\n}\n"]}
|
|
@@ -51,6 +51,7 @@ const CivicNextAuthTokenProviderInternal = ({ children, isLoading, displayMode =
|
|
|
51
51
|
pkceConsumer,
|
|
52
52
|
displayMode,
|
|
53
53
|
});
|
|
54
|
+
const { error: refreshError } = useRefresh();
|
|
54
55
|
useEffect(() => {
|
|
55
56
|
const ref = getIframeRef(iframeRef?.current, true);
|
|
56
57
|
if (isIframeMounted &&
|
|
@@ -74,7 +75,6 @@ const CivicNextAuthTokenProviderInternal = ({ children, isLoading, displayMode =
|
|
|
74
75
|
startSignIn,
|
|
75
76
|
displayMode,
|
|
76
77
|
]);
|
|
77
|
-
const { error: refreshError } = useRefresh(session);
|
|
78
78
|
useEffect(() => {
|
|
79
79
|
if (refreshError) {
|
|
80
80
|
console.error("Error refreshing token, signing out...", refreshError);
|
|
@@ -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,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAChE,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,CAA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/**\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, { useCallback, useEffect, useState } 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\";\n\ntype CivicNextAuthTokenProviderInternalProps<TUser extends UnknownObject> =\n NextCivicAuthProviderInternalProps & {\n isLoading: boolean;\n idToken?: string;\n user: User<TUser> | null;\n fetchUser: () => Promise<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 isLoading,\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(challengeUrl);\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 await 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 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 const { error: refreshError } = useRefresh(session);\n\n useEffect(() => {\n if (refreshError) {\n console.error(\"Error refreshing token, signing out...\", refreshError);\n signOut();\n }\n }, [refreshError, signOut]);\n\n return (\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={isLoading} />\n {isLoading && (\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 // if the SDK loads in an iframe, we show the loading spinner as the iframe\n // will be waiting to be minimized\n const isLoading = useIsInIframe();\n const { user, idToken, fetchUser } = useUserCookie();\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 <IframeProvider iframeMode={props.iframeMode}>\n <CivicNextAuthProviderInternal\n {...props}\n resolvedConfig={resolvedConfig}\n >\n {children}\n </CivicNextAuthProviderInternal>\n </IframeProvider>\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,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAChE,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,WAAW,EAAE,MAAM,oCAAoC,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAExD,OAAO,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAChE,OAAO,EAAE,UAAU,EAAiC,MAAM,YAAY,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,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AC,EAAE,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;IAElC,OAAO,CACL,KAAC,uBAAuB,IACtB,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,QAAQ,EAClB,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,cAAc,IAAC,UAAU,EAAE,KAAK,CAAC,UAAU,YAC1C,KAAC,6BAA6B,OACxB,KAAK,EACT,cAAc,EAAE,cAAc,YAE7B,QAAQ,GACqB,GACjB,GACO,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, { useCallback, useEffect, useState } 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\";\n\ntype CivicNextAuthTokenProviderInternalProps<TUser extends UnknownObject> =\n NextCivicAuthProviderInternalProps & {\n isLoading: boolean;\n idToken?: string;\n user: User<TUser> | null;\n fetchUser: () => Promise<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 isLoading,\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(challengeUrl);\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 await 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 return (\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={isLoading} />\n {isLoading && (\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 // if the SDK loads in an iframe, we show the loading spinner as the iframe\n // will be waiting to be minimized\n const isLoading = useIsInIframe();\n const { user, idToken, fetchUser } = useUserCookie();\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 <IframeProvider iframeMode={props.iframeMode}>\n <CivicNextAuthProviderInternal\n {...props}\n resolvedConfig={resolvedConfig}\n >\n {children}\n </CivicNextAuthProviderInternal>\n </IframeProvider>\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;
|
|
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;AAsS9C,wBAAsB,YAAY,CAChC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CAiCvB;AAED,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CAmDvB;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,OAAO,GACjB,eAAe,MACT,SAAS,WAAW,KAAG,OAAO,CAAC,YAAY,CAkCjD,CAAC"}
|
|
@@ -9,7 +9,7 @@ import { resolveOAuthAccessCode } from "../server/login.js";
|
|
|
9
9
|
import { GenericPublicClientPKCEProducer } from "../services/PKCE.js";
|
|
10
10
|
import { CodeVerifier, OAuthTokenTypes } from "../shared/lib/types.js";
|
|
11
11
|
import { GenericUserSession } from "../shared/lib/UserSession.js";
|
|
12
|
-
import { generateOauthLogoutUrl } from "../shared/lib/util.js";
|
|
12
|
+
import { clearTokens, generateOauthLogoutUrl } from "../shared/lib/util.js";
|
|
13
13
|
import { revalidatePath } from "next/cache.js";
|
|
14
14
|
import { NextResponse } from "next/server.js";
|
|
15
15
|
import { NextServerAuthenticationRefresherImpl } from "./NextServerAuthenticationRefresherImpl.js";
|
|
@@ -43,15 +43,19 @@ async function handleChallenge(request, config) {
|
|
|
43
43
|
}
|
|
44
44
|
return NextResponse.json({ status: "success", challenge });
|
|
45
45
|
}
|
|
46
|
+
const getCookieStorageWithUserOverrides = (config) => {
|
|
47
|
+
const resolvedConfigs = resolveAuthConfig(config);
|
|
48
|
+
return new NextjsCookieStorage({
|
|
49
|
+
...resolvedConfigs.cookies.tokens,
|
|
50
|
+
user: resolvedConfigs.cookies.user,
|
|
51
|
+
});
|
|
52
|
+
};
|
|
46
53
|
async function performTokenExchangeAndSetCookies(config, code, state, appUrl) {
|
|
47
54
|
const resolvedConfigs = resolveAuthConfig(config);
|
|
48
55
|
// TODO This is messy, better would be to fix the config.cookies type to always be <name: settings>
|
|
49
56
|
// rather than nesting the tokens-related ones *and* code-verifier inside "tokens"
|
|
50
57
|
// (despite code-verifier not relating directly to tokens)
|
|
51
|
-
const cookieStorage =
|
|
52
|
-
...resolvedConfigs.cookies.tokens,
|
|
53
|
-
user: resolvedConfigs.cookies.user,
|
|
54
|
-
});
|
|
58
|
+
const cookieStorage = getCookieStorageWithUserOverrides(config);
|
|
55
59
|
const callbackUrl = resolveCallbackUrl(resolvedConfigs, appUrl);
|
|
56
60
|
try {
|
|
57
61
|
await resolveOAuthAccessCode(code, state, cookieStorage, {
|
|
@@ -70,9 +74,10 @@ async function performTokenExchangeAndSetCookies(config, code, state, appUrl) {
|
|
|
70
74
|
const userSession = new GenericUserSession(cookieStorage);
|
|
71
75
|
await userSession.set(user);
|
|
72
76
|
}
|
|
73
|
-
async function handleRefresh(
|
|
77
|
+
async function handleRefresh(request, config) {
|
|
74
78
|
const resolvedConfigs = resolveAuthConfig(config);
|
|
75
|
-
const cookieStorage =
|
|
79
|
+
const cookieStorage = getCookieStorageWithUserOverrides(config);
|
|
80
|
+
const userSession = new GenericUserSession(cookieStorage);
|
|
76
81
|
try {
|
|
77
82
|
const onError = (error) => {
|
|
78
83
|
logger.error("handleRefresh: Token refresh failed:", error);
|
|
@@ -85,11 +90,27 @@ async function handleRefresh(_request, config) {
|
|
|
85
90
|
refreshUrl: resolvedConfigs.refreshUrl,
|
|
86
91
|
}, cookieStorage, onError);
|
|
87
92
|
const tokens = await refresher.refreshAccessToken();
|
|
93
|
+
const user = await getUser();
|
|
94
|
+
if (!user) {
|
|
95
|
+
throw new AuthError("Failed to get user info", 401);
|
|
96
|
+
}
|
|
97
|
+
await userSession.set(user);
|
|
98
|
+
const targetUrl = request.nextUrl.searchParams.get("targetUrl");
|
|
99
|
+
if (targetUrl) {
|
|
100
|
+
return NextResponse.redirect(targetUrl);
|
|
101
|
+
}
|
|
88
102
|
return NextResponse.json({ status: "success", tokens });
|
|
89
103
|
}
|
|
90
104
|
catch (error) {
|
|
91
105
|
logger.error("handleRefresh: Token refresh failed:", error);
|
|
92
|
-
|
|
106
|
+
const targetUrl = request.nextUrl.searchParams.get("targetUrl");
|
|
107
|
+
if (targetUrl) {
|
|
108
|
+
logger.warn("clearing tokens and redirecting to targetUrl", targetUrl);
|
|
109
|
+
await clearTokens(cookieStorage);
|
|
110
|
+
await userSession.clear();
|
|
111
|
+
return NextResponse.redirect(targetUrl);
|
|
112
|
+
}
|
|
113
|
+
return NextResponse.json({ status: "failed" });
|
|
93
114
|
}
|
|
94
115
|
}
|
|
95
116
|
const generateHtmlResponseWithCallback = (request, callbackUrl) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routeHandler.js","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EACL,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OA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Q,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;QAEnE,MAAM,gBAAgB,EAAE,CAAC;QACzB,OAAO,QAAQ,CAAC;IAClB,CAAC;AACH,CAAC,CAAC","sourcesContent":["import {\n TOKEN_EXCHANGE_SUCCESS_TEXT,\n TOKEN_EXCHANGE_TRIGGER_TEXT,\n} from \"@/constants.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport {\n displayModeFromState,\n serverTokenExchangeFromState,\n} from \"@/lib/oauth.js\";\nimport type { AuthConfig } from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { clearAuthCookies, NextjsCookieStorage } from \"@/nextjs/cookies.js\";\nimport { getUser } from \"@/nextjs/index.js\";\nimport { resolveCallbackUrl } from \"@/nextjs/utils.js\";\nimport { resolveOAuthAccessCode } from \"@/server/login.js\";\nimport { GenericPublicClientPKCEProducer } from \"@/services/PKCE.js\";\nimport { CodeVerifier, OAuthTokenTypes } from \"@/shared/lib/types.js\";\nimport { GenericUserSession } from \"@/shared/lib/UserSession.js\";\nimport { generateOauthLogoutUrl } from \"@/shared/lib/util.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport { NextServerAuthenticationRefresherImpl } from \"./NextServerAuthenticationRefresherImpl.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\nconst getAppUrl = (request: NextRequest): string | null =>\n request.cookies.get(CodeVerifier.APP_URL)?.value ||\n request.nextUrl.searchParams.get(\"appUrl\");\n\nconst getIdToken = async (config: AuthConfig): Promise<string | null> => {\n const cookieStorage = new NextjsCookieStorage(config.cookies?.tokens ?? {});\n return cookieStorage.get(OAuthTokenTypes.ID_TOKEN);\n};\n\n/**\n * create a code verifier and challenge for PKCE\n * saving the verifier in a cookie for later use\n * @returns {Promise<NextResponse>}\n */\nasync function handleChallenge(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const cookieStorage = new NextjsCookieStorage(config.cookies?.tokens ?? {});\n const pkceProducer = new GenericPublicClientPKCEProducer(cookieStorage);\n\n const challenge = await pkceProducer.getCodeChallenge();\n const appUrl = request.nextUrl.searchParams.get(\"appUrl\");\n if (appUrl) {\n await cookieStorage.set(CodeVerifier.APP_URL, appUrl);\n }\n return NextResponse.json({ status: \"success\", challenge });\n}\n\nasync function performTokenExchangeAndSetCookies(\n config: AuthConfig,\n code: string,\n state: string,\n appUrl: string,\n) {\n const resolvedConfigs = resolveAuthConfig(config);\n // TODO This is messy, better would be to fix the config.cookies type to always be <name: settings>\n // rather than nesting the tokens-related ones *and* code-verifier inside \"tokens\"\n // (despite code-verifier not relating directly to tokens)\n const cookieStorage = new NextjsCookieStorage({\n ...resolvedConfigs.cookies.tokens,\n user: resolvedConfigs.cookies.user,\n });\n\n const callbackUrl = resolveCallbackUrl(resolvedConfigs, appUrl);\n try {\n await resolveOAuthAccessCode(code, state, cookieStorage, {\n ...resolvedConfigs,\n redirectUrl: callbackUrl,\n });\n } catch (error) {\n logger.error(\"Token exchange failed:\", error);\n throw new AuthError(\"Failed to authenticate user\", 401);\n }\n\n const user = await getUser();\n if (!user) {\n throw new AuthError(\"Failed to get user info\", 401);\n }\n const userSession = new GenericUserSession(cookieStorage);\n await userSession.set(user);\n}\nasync function handleRefresh(\n _request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const cookieStorage = new NextjsCookieStorage(config.cookies?.tokens ?? {});\n try {\n const onError = (error: Error) => {\n logger.error(\"handleRefresh: Token refresh failed:\", error);\n throw new AuthError(\"Failed to refresh tokens\", 500);\n };\n const refresher = await NextServerAuthenticationRefresherImpl.build(\n {\n clientId: resolvedConfigs.clientId,\n oauthServer: resolvedConfigs.oauthServer,\n redirectUrl: resolvedConfigs.callbackUrl,\n refreshUrl: resolvedConfigs.refreshUrl,\n },\n cookieStorage,\n onError,\n );\n\n const tokens = await refresher.refreshAccessToken();\n return NextResponse.json({ status: \"success\", tokens });\n } catch (error) {\n logger.error(\"handleRefresh: Token refresh failed:\", error);\n throw new AuthError(\"Failed to refresh tokens\", 500);\n }\n}\n\nconst generateHtmlResponseWithCallback = (\n request: NextRequest,\n callbackUrl: string,\n) => {\n // we need to replace the URL with resolved config in case the server is hosted\n // behind a reverse proxy or load balancer\n const requestUrl = new URL(request.url);\n const fetchUrl = `${callbackUrl}?${requestUrl.searchParams.toString()}&sameDomainCallback=true`;\n return new NextResponse(\n `<html lang=\"en\">\n <body>\n <span style=\"display:none\">\n <script>\n window.onload = function () {\n const appUrl = globalThis.window?.location?.origin;\n fetch('${fetchUrl}&appUrl=' + appUrl).then((response) => {\n response.json().then((jsonResponse) => {\n if (jsonResponse.redirectUrl) {\n window.location.href = jsonResponse.redirectUrl;\n }\n });\n });\n };\n </script>\n </span>\n </body>\n </html>\n `,\n );\n};\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n // appUrl is passed from the client to the server in the query string\n // this is necessary because the server does not have access to the client's window.location.origin\n // and can not accurately determine the appUrl (specially if the app is behind a reverse proxy)\n const appUrl = getAppUrl(request);\n\n // If we have a code_verifier cookie and the appUrl, we can do a token exchange.\n // Otherwise, just render an empty page.\n // The initial redirect back from the auth server does not send cookies, because the redirect is from a 3rd-party domain.\n // The client will make an additional call to this route with cookies included, at which point we do the token exchange.\n const codeVerifier = request.cookies.get(CodeVerifier.COOKIE_NAME);\n\n if (!codeVerifier || !appUrl) {\n logger.debug(\"handleCallback no code_verifier found\", {\n state,\n serverTokenExchange: serverTokenExchangeFromState(`${state}`),\n });\n let response = new NextResponse(\n `<html lang=\"en\"><body><span style=\"display:none\">${TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`,\n );\n\n // in server-side token exchange mode we need to launch a page that will trigger the token exchange\n // from the same domain, allowing it access to the code_verifier cookie\n // we only need to do this in redirect mode, as the iframe already triggers a client-side token exchange\n // if no code-verifier cookie is found\n if (state && serverTokenExchangeFromState(state)) {\n logger.debug(\n \"handleCallback serverTokenExchangeFromState, launching redirect page...\",\n {\n requestUrl: request.url,\n configCallbackUrl: resolvedConfigs.callbackUrl,\n },\n );\n // generate a page that will callback to the same domain, allowing access\n // to the code_verifier cookie and passing the appUrl.\n response = generateHtmlResponseWithCallback(\n request,\n resolvedConfigs.callbackUrl,\n );\n }\n\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n logger.debug(\n `handleCallback no code_verifier found, returning ${TOKEN_EXCHANGE_TRIGGER_TEXT}`,\n );\n return response;\n }\n\n await performTokenExchangeAndSetCookies(resolvedConfigs, code, state, appUrl);\n\n if (request.url.includes(\"sameDomainCallback=true\")) {\n logger.debug(\n \"handleCallback sameDomainCallback = true, returning redirectUrl\",\n appUrl,\n );\n return NextResponse.json({\n status: \"success\",\n redirectUrl: appUrl,\n });\n }\n\n // this is the case where a 'normal' redirect is happening\n if (serverTokenExchangeFromState(state)) {\n logger.debug(\n \"handleCallback serverTokenExchangeFromState, redirect to appUrl\",\n appUrl,\n );\n if (!appUrl) {\n throw new Error(\"appUrl undefined. Cannot redirect.\");\n }\n return NextResponse.redirect(`${appUrl}`);\n }\n // return an empty HTML response so the iframe doesn't show any response\n // in the short moment between the redirect and the parent window\n // acknowledging the redirect and closing the iframe\n const response = new NextResponse(\n `<html lang=\"en\"><span style=\"display:none\">${TOKEN_EXCHANGE_SUCCESS_TEXT}</span></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n return response;\n}\n\n/**\n * If redirectPath is an absolute path, return it as-is.\n * Otherwise for relative paths, append it to the current domain.\n * @param redirectPath\n * @param currentBasePath\n * @returns\n */\nconst getAbsoluteRedirectPath = (\n redirectPath: string,\n currentBasePath: string,\n) => new URL(redirectPath, currentBasePath).href;\n\nconst getPostLogoutRedirectUrl = (\n request: NextRequest,\n config: AuthConfig,\n): string | null => {\n const { loginUrl } = resolveAuthConfig(config);\n const redirectTarget = loginUrl ?? \"/\";\n\n // if the optional loginUrl is provided and it is an absolute URL,\n // use it as the redirect target\n const isAbsoluteRedirect = /^(https?:\\/\\/|www\\.).+/i.test(redirectTarget);\n if (isAbsoluteRedirect) {\n return redirectTarget;\n }\n\n // if loginUrl is not defined, the appUrl is passed from the client to the server\n // in the query string or cookies. This is necessary because the server does not\n // have access to the client's window.location and can not accurately determine\n // the appUrl (specially if the app is behind a reverse proxy).\n const appUrl = getAppUrl(request);\n if (appUrl) return getAbsoluteRedirectPath(redirectTarget, appUrl);\n\n return null;\n};\n\nconst revalidateUrlPath = async (url: string) => {\n try {\n const path = new URL(url).pathname;\n revalidatePath(path);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n};\n\nexport async function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n const postLogoutUrl = new URL(\n resolvedConfigs.logoutCallbackUrl,\n getAppUrl(request) || request.url,\n );\n\n // read the id_token from the cookies\n const idToken = await getIdToken(resolvedConfigs);\n\n // read the state from the query parameters\n const state = request.nextUrl.searchParams.get(\"state\");\n\n if (!state || !idToken) {\n logger.error(\"handleLogout: missing state or idToken\", { state, idToken });\n // if token or state is missing, the logout call to the server will fail,\n // (token has potentially expired already) so go straight to the postLogoutUrl\n // so the user can be signed out.\n return NextResponse.redirect(\n `${postLogoutUrl}${state ? \"?state=\" + state : \"\"}`,\n );\n }\n\n const logoutUrl = await generateOauthLogoutUrl({\n clientId: resolvedConfigs.clientId,\n idToken,\n state,\n redirectUrl: postLogoutUrl.href,\n oauthServer: resolvedConfigs.oauthServer,\n });\n\n return NextResponse.redirect(`${logoutUrl.href}`);\n}\n\nexport async function handleLogoutCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n const state = request.nextUrl.searchParams.get(\"state\") || \"\";\n const displayMode = displayModeFromState(state, \"iframe\");\n\n const canAccessCookies = !!(await getIdToken(resolvedConfigs));\n const isSameDomainCallback = request.url.includes(\"sameDomainCallback=true\");\n\n if (canAccessCookies || isSameDomainCallback) {\n await clearAuthCookies();\n }\n\n let response;\n\n // handle logout for iframe display mode\n if (displayMode === \"iframe\") {\n // try to read the token from cookies. If cookies cant be read/written\n // because the request cames from a cross-origin redirect,\n // we need to show a page that will trigger the logout from the same domain\n if (canAccessCookies || isSameDomainCallback) {\n // just return success\n return NextResponse.json({ status: \"success\" });\n }\n\n // return a page that will trigger the logout from the same domain\n response = generateHtmlResponseWithCallback(\n request,\n resolvedConfigs.logoutCallbackUrl,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n return response;\n }\n\n // handle logout for non-iframe display mode\n const redirectUrl = getPostLogoutRedirectUrl(request, resolvedConfigs);\n\n if (redirectUrl && (canAccessCookies || isSameDomainCallback)) {\n // just redirect to the app url\n response = NextResponse.redirect(`${redirectUrl}`);\n revalidateUrlPath(redirectUrl);\n } else {\n logger.debug(\"handleLogout no redirectUrl found\", { state });\n response = generateHtmlResponseWithCallback(\n request,\n resolvedConfigs.logoutCallbackUrl,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n }\n\n return response;\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n return await handleChallenge(request, config);\n case \"callback\":\n return await handleCallback(request, config);\n case \"refresh\":\n return await handleRefresh(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n case \"logoutcallback\":\n return await handleLogoutCallback(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n await clearAuthCookies();\n return response;\n }\n };\n"]}
|
|
1
|
+
{"version":3,"file":"routeHandler.js","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EACL,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,WAA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zB,OAAO,QAAQ,CAAC;IAClB,CAAC;AACH,CAAC,CAAC","sourcesContent":["import {\n TOKEN_EXCHANGE_SUCCESS_TEXT,\n TOKEN_EXCHANGE_TRIGGER_TEXT,\n} from \"@/constants.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport {\n displayModeFromState,\n serverTokenExchangeFromState,\n} from \"@/lib/oauth.js\";\nimport type { AuthConfig } from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { clearAuthCookies, NextjsCookieStorage } from \"@/nextjs/cookies.js\";\nimport { getUser } from \"@/nextjs/index.js\";\nimport { resolveCallbackUrl } from \"@/nextjs/utils.js\";\nimport { resolveOAuthAccessCode } from \"@/server/login.js\";\nimport { GenericPublicClientPKCEProducer } from \"@/services/PKCE.js\";\nimport { CodeVerifier, OAuthTokenTypes } from \"@/shared/lib/types.js\";\nimport { GenericUserSession } from \"@/shared/lib/UserSession.js\";\nimport { clearTokens, generateOauthLogoutUrl } from \"@/shared/lib/util.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport { NextServerAuthenticationRefresherImpl } from \"./NextServerAuthenticationRefresherImpl.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\nconst getAppUrl = (request: NextRequest): string | null =>\n request.cookies.get(CodeVerifier.APP_URL)?.value ||\n request.nextUrl.searchParams.get(\"appUrl\");\n\nconst getIdToken = async (config: AuthConfig): Promise<string | null> => {\n const cookieStorage = new NextjsCookieStorage(config.cookies?.tokens ?? {});\n return cookieStorage.get(OAuthTokenTypes.ID_TOKEN);\n};\n\n/**\n * create a code verifier and challenge for PKCE\n * saving the verifier in a cookie for later use\n * @returns {Promise<NextResponse>}\n */\nasync function handleChallenge(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const cookieStorage = new NextjsCookieStorage(config.cookies?.tokens ?? {});\n const pkceProducer = new GenericPublicClientPKCEProducer(cookieStorage);\n\n const challenge = await pkceProducer.getCodeChallenge();\n const appUrl = request.nextUrl.searchParams.get(\"appUrl\");\n if (appUrl) {\n await cookieStorage.set(CodeVerifier.APP_URL, appUrl);\n }\n return NextResponse.json({ status: \"success\", challenge });\n}\n\nconst getCookieStorageWithUserOverrides = (config: AuthConfig) => {\n const resolvedConfigs = resolveAuthConfig(config);\n return new NextjsCookieStorage({\n ...resolvedConfigs.cookies.tokens,\n user: resolvedConfigs.cookies.user,\n });\n};\nasync function performTokenExchangeAndSetCookies(\n config: AuthConfig,\n code: string,\n state: string,\n appUrl: string,\n) {\n const resolvedConfigs = resolveAuthConfig(config);\n // TODO This is messy, better would be to fix the config.cookies type to always be <name: settings>\n // rather than nesting the tokens-related ones *and* code-verifier inside \"tokens\"\n // (despite code-verifier not relating directly to tokens)\n const cookieStorage = getCookieStorageWithUserOverrides(config);\n\n const callbackUrl = resolveCallbackUrl(resolvedConfigs, appUrl);\n try {\n await resolveOAuthAccessCode(code, state, cookieStorage, {\n ...resolvedConfigs,\n redirectUrl: callbackUrl,\n });\n } catch (error) {\n logger.error(\"Token exchange failed:\", error);\n throw new AuthError(\"Failed to authenticate user\", 401);\n }\n\n const user = await getUser();\n if (!user) {\n throw new AuthError(\"Failed to get user info\", 401);\n }\n const userSession = new GenericUserSession(cookieStorage);\n await userSession.set(user);\n}\nasync function handleRefresh(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const cookieStorage = getCookieStorageWithUserOverrides(config);\n const userSession = new GenericUserSession(cookieStorage);\n try {\n const onError = (error: Error) => {\n logger.error(\"handleRefresh: Token refresh failed:\", error);\n throw new AuthError(\"Failed to refresh tokens\", 500);\n };\n const refresher = await NextServerAuthenticationRefresherImpl.build(\n {\n clientId: resolvedConfigs.clientId,\n oauthServer: resolvedConfigs.oauthServer,\n redirectUrl: resolvedConfigs.callbackUrl,\n refreshUrl: resolvedConfigs.refreshUrl,\n },\n cookieStorage,\n onError,\n );\n\n const tokens = await refresher.refreshAccessToken();\n const user = await getUser();\n if (!user) {\n throw new AuthError(\"Failed to get user info\", 401);\n }\n await userSession.set(user);\n const targetUrl = request.nextUrl.searchParams.get(\"targetUrl\");\n if (targetUrl) {\n return NextResponse.redirect(targetUrl);\n }\n return NextResponse.json({ status: \"success\", tokens });\n } catch (error) {\n logger.error(\"handleRefresh: Token refresh failed:\", error);\n const targetUrl = request.nextUrl.searchParams.get(\"targetUrl\");\n if (targetUrl) {\n logger.warn(\"clearing tokens and redirecting to targetUrl\", targetUrl);\n await clearTokens(cookieStorage);\n await userSession.clear();\n return NextResponse.redirect(targetUrl);\n }\n return NextResponse.json({ status: \"failed\" });\n }\n}\n\nconst generateHtmlResponseWithCallback = (\n request: NextRequest,\n callbackUrl: string,\n) => {\n // we need to replace the URL with resolved config in case the server is hosted\n // behind a reverse proxy or load balancer\n const requestUrl = new URL(request.url);\n const fetchUrl = `${callbackUrl}?${requestUrl.searchParams.toString()}&sameDomainCallback=true`;\n return new NextResponse(\n `<html lang=\"en\">\n <body>\n <span style=\"display:none\">\n <script>\n window.onload = function () {\n const appUrl = globalThis.window?.location?.origin;\n fetch('${fetchUrl}&appUrl=' + appUrl).then((response) => {\n response.json().then((jsonResponse) => {\n if (jsonResponse.redirectUrl) {\n window.location.href = jsonResponse.redirectUrl;\n }\n });\n });\n };\n </script>\n </span>\n </body>\n </html>\n `,\n );\n};\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n // appUrl is passed from the client to the server in the query string\n // this is necessary because the server does not have access to the client's window.location.origin\n // and can not accurately determine the appUrl (specially if the app is behind a reverse proxy)\n const appUrl = getAppUrl(request);\n\n // If we have a code_verifier cookie and the appUrl, we can do a token exchange.\n // Otherwise, just render an empty page.\n // The initial redirect back from the auth server does not send cookies, because the redirect is from a 3rd-party domain.\n // The client will make an additional call to this route with cookies included, at which point we do the token exchange.\n const codeVerifier = request.cookies.get(CodeVerifier.COOKIE_NAME);\n\n if (!codeVerifier || !appUrl) {\n logger.debug(\"handleCallback no code_verifier found\", {\n state,\n serverTokenExchange: serverTokenExchangeFromState(`${state}`),\n });\n let response = new NextResponse(\n `<html lang=\"en\"><body><span style=\"display:none\">${TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`,\n );\n\n // in server-side token exchange mode we need to launch a page that will trigger the token exchange\n // from the same domain, allowing it access to the code_verifier cookie\n // we only need to do this in redirect mode, as the iframe already triggers a client-side token exchange\n // if no code-verifier cookie is found\n if (state && serverTokenExchangeFromState(state)) {\n logger.debug(\n \"handleCallback serverTokenExchangeFromState, launching redirect page...\",\n {\n requestUrl: request.url,\n configCallbackUrl: resolvedConfigs.callbackUrl,\n },\n );\n // generate a page that will callback to the same domain, allowing access\n // to the code_verifier cookie and passing the appUrl.\n response = generateHtmlResponseWithCallback(\n request,\n resolvedConfigs.callbackUrl,\n );\n }\n\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n logger.debug(\n `handleCallback no code_verifier found, returning ${TOKEN_EXCHANGE_TRIGGER_TEXT}`,\n );\n return response;\n }\n\n await performTokenExchangeAndSetCookies(resolvedConfigs, code, state, appUrl);\n\n if (request.url.includes(\"sameDomainCallback=true\")) {\n logger.debug(\n \"handleCallback sameDomainCallback = true, returning redirectUrl\",\n appUrl,\n );\n return NextResponse.json({\n status: \"success\",\n redirectUrl: appUrl,\n });\n }\n\n // this is the case where a 'normal' redirect is happening\n if (serverTokenExchangeFromState(state)) {\n logger.debug(\n \"handleCallback serverTokenExchangeFromState, redirect to appUrl\",\n appUrl,\n );\n if (!appUrl) {\n throw new Error(\"appUrl undefined. Cannot redirect.\");\n }\n return NextResponse.redirect(`${appUrl}`);\n }\n // return an empty HTML response so the iframe doesn't show any response\n // in the short moment between the redirect and the parent window\n // acknowledging the redirect and closing the iframe\n const response = new NextResponse(\n `<html lang=\"en\"><span style=\"display:none\">${TOKEN_EXCHANGE_SUCCESS_TEXT}</span></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n return response;\n}\n\n/**\n * If redirectPath is an absolute path, return it as-is.\n * Otherwise for relative paths, append it to the current domain.\n * @param redirectPath\n * @param currentBasePath\n * @returns\n */\nconst getAbsoluteRedirectPath = (\n redirectPath: string,\n currentBasePath: string,\n) => new URL(redirectPath, currentBasePath).href;\n\nconst getPostLogoutRedirectUrl = (\n request: NextRequest,\n config: AuthConfig,\n): string | null => {\n const { loginUrl } = resolveAuthConfig(config);\n const redirectTarget = loginUrl ?? \"/\";\n\n // if the optional loginUrl is provided and it is an absolute URL,\n // use it as the redirect target\n const isAbsoluteRedirect = /^(https?:\\/\\/|www\\.).+/i.test(redirectTarget);\n if (isAbsoluteRedirect) {\n return redirectTarget;\n }\n\n // if loginUrl is not defined, the appUrl is passed from the client to the server\n // in the query string or cookies. This is necessary because the server does not\n // have access to the client's window.location and can not accurately determine\n // the appUrl (specially if the app is behind a reverse proxy).\n const appUrl = getAppUrl(request);\n if (appUrl) return getAbsoluteRedirectPath(redirectTarget, appUrl);\n\n return null;\n};\n\nconst revalidateUrlPath = async (url: string) => {\n try {\n const path = new URL(url).pathname;\n revalidatePath(path);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n};\n\nexport async function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n const postLogoutUrl = new URL(\n resolvedConfigs.logoutCallbackUrl,\n getAppUrl(request) || request.url,\n );\n\n // read the id_token from the cookies\n const idToken = await getIdToken(resolvedConfigs);\n\n // read the state from the query parameters\n const state = request.nextUrl.searchParams.get(\"state\");\n\n if (!state || !idToken) {\n logger.error(\"handleLogout: missing state or idToken\", { state, idToken });\n // if token or state is missing, the logout call to the server will fail,\n // (token has potentially expired already) so go straight to the postLogoutUrl\n // so the user can be signed out.\n return NextResponse.redirect(\n `${postLogoutUrl}${state ? \"?state=\" + state : \"\"}`,\n );\n }\n\n const logoutUrl = await generateOauthLogoutUrl({\n clientId: resolvedConfigs.clientId,\n idToken,\n state,\n redirectUrl: postLogoutUrl.href,\n oauthServer: resolvedConfigs.oauthServer,\n });\n\n return NextResponse.redirect(`${logoutUrl.href}`);\n}\n\nexport async function handleLogoutCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n const state = request.nextUrl.searchParams.get(\"state\") || \"\";\n const displayMode = displayModeFromState(state, \"iframe\");\n\n const canAccessCookies = !!(await getIdToken(resolvedConfigs));\n const isSameDomainCallback = request.url.includes(\"sameDomainCallback=true\");\n\n if (canAccessCookies || isSameDomainCallback) {\n await clearAuthCookies();\n }\n\n let response;\n\n // handle logout for iframe display mode\n if (displayMode === \"iframe\") {\n // try to read the token from cookies. If cookies cant be read/written\n // because the request cames from a cross-origin redirect,\n // we need to show a page that will trigger the logout from the same domain\n if (canAccessCookies || isSameDomainCallback) {\n // just return success\n return NextResponse.json({ status: \"success\" });\n }\n\n // return a page that will trigger the logout from the same domain\n response = generateHtmlResponseWithCallback(\n request,\n resolvedConfigs.logoutCallbackUrl,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n return response;\n }\n\n // handle logout for non-iframe display mode\n const redirectUrl = getPostLogoutRedirectUrl(request, resolvedConfigs);\n\n if (redirectUrl && (canAccessCookies || isSameDomainCallback)) {\n // just redirect to the app url\n response = NextResponse.redirect(`${redirectUrl}`);\n revalidateUrlPath(redirectUrl);\n } else {\n logger.debug(\"handleLogout no redirectUrl found\", { state });\n response = generateHtmlResponseWithCallback(\n request,\n resolvedConfigs.logoutCallbackUrl,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n }\n\n return response;\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n return await handleChallenge(request, config);\n case \"callback\":\n return await handleCallback(request, config);\n case \"refresh\":\n return await handleRefresh(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n case \"logoutcallback\":\n return await handleLogoutCallback(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n await clearAuthCookies();\n return response;\n }\n };\n"]}
|
|
@@ -5,6 +5,6 @@ export type InternalAuthProviderProps = AuthProviderProps & {
|
|
|
5
5
|
sessionData?: SessionData;
|
|
6
6
|
pkceConsumer?: PKCEConsumer;
|
|
7
7
|
};
|
|
8
|
-
declare const AuthProvider: ({ children, onSignIn, onSignOut, pkceConsumer,
|
|
8
|
+
declare const AuthProvider: ({ children, onSignIn, onSignOut, pkceConsumer, displayMode, }: InternalAuthProviderProps) => import("@emotion/react/jsx-runtime").JSX.Element;
|
|
9
9
|
export { AuthProvider };
|
|
10
10
|
//# sourceMappingURL=AuthProvider.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthProvider.d.ts","sourceRoot":"","sources":["../../../src/reactjs/providers/AuthProvider.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"AuthProvider.d.ts","sourceRoot":"","sources":["../../../src/reactjs/providers/AuthProvider.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAKxD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAerE,MAAM,MAAM,yBAAyB,GAAG,iBAAiB,GAAG;IAC1D,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B,CAAC;AAEF,QAAA,MAAM,YAAY,GAAI,+DAMnB,yBAAyB,qDA0E3B,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}
|