diff --git a/.gitignore b/.gitignore index 5fb198c8..b4ea36f5 100644 --- a/.gitignore +++ b/.gitignore @@ -26,15 +26,7 @@ dist # Generated files .docusaurus .cache-loader -packages/next-auth/providers -packages/next-auth/src/providers/oauth-types.ts -packages/next-auth/client -packages/next-auth/css -packages/next-auth/utils -packages/next-auth/core -packages/next-auth/jwt -packages/next-auth/react -packages/next-auth/next + packages/*/*.js packages/*/*.d.ts packages/*/*.d.ts.map @@ -85,10 +77,10 @@ packages/core/providers packages/core/src/lib/pages/styles.ts docs/docs/reference/core docs/docs/reference/sveltekit -docs/docs/reference/nextjs +docs/docs/reference/next-auth # Next.js -packages/frameworks-nextjs/lib +packages/next-auth/lib # SvelteKit packages/frameworks-sveltekit/index.* diff --git a/.prettierignore b/.prettierignore index fa687a93..cb1da958 100644 --- a/.prettierignore +++ b/.prettierignore @@ -40,10 +40,6 @@ packages/core/src/lib/pages/styles.ts packages/frameworks-sveltekit/package packages/frameworks-sveltekit/vite.config.{js,ts}.timestamp-* -# next-auth -packages/next-auth/src/providers/oauth-types.ts -packages/next-auth/css/index.css - # Adapters .branches diff --git a/.vscode/settings.json b/.vscode/settings.json index 14d20346..fbd922c3 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,8 +1,7 @@ { "files.exclude": { "packages/core/{lib,providers,*.js,*.d.ts*}": true, - "packages/frameworks-nextjs/{lib,*.js,*.d.ts*}": true, - "packages/next-auth/{client,core,css,jwt,next,providers,react,utils,*.js,*.d.ts}": true + "packages/next-auth/{lib,*.js,*.d.ts*}": true, }, "typescript.tsdk": "node_modules/typescript/lib", "openInGitHub.remote.branch": "main" diff --git a/apps/dev/nextjs/app/server-component/page.tsx b/apps/dev/nextjs/app/server-component/page.tsx index 34bcc64d..9023730f 100644 --- a/apps/dev/nextjs/app/server-component/page.tsx +++ b/apps/dev/nextjs/app/server-component/page.tsx @@ -35,5 +35,3 @@ export default async function Page() { } return Sign in with github } - -export const runtime = "experimental-edge" diff --git a/apps/dev/nextjs/auth.ts b/apps/dev/nextjs/auth.ts index 06f3b80e..2419756c 100644 --- a/apps/dev/nextjs/auth.ts +++ b/apps/dev/nextjs/auth.ts @@ -1,4 +1,4 @@ -import { NextAuth } from "@auth/nextjs" +import { NextAuth } from "next-auth" import GitHub from "@auth/core/providers/github" export const { handlers, auth } = NextAuth({ diff --git a/apps/dev/nextjs/components/access-denied.js b/apps/dev/nextjs/components/access-denied.js index 6224511e..4c9c0d79 100644 --- a/apps/dev/nextjs/components/access-denied.js +++ b/apps/dev/nextjs/components/access-denied.js @@ -1,4 +1,4 @@ -import { signIn } from "@auth/nextjs/client" +import { signIn } from "next-auth/react" export default function AccessDenied() { return ( diff --git a/apps/dev/nextjs/components/footer.js b/apps/dev/nextjs/components/footer.js index c9e3f1d4..1303c60e 100644 --- a/apps/dev/nextjs/components/footer.js +++ b/apps/dev/nextjs/components/footer.js @@ -1,6 +1,6 @@ import Link from "next/link" import styles from "./footer.module.css" -import packageJSON from "@auth/nextjs/package.json" +import packageJSON from "next-auth/package.json" export default function Footer() { return ( diff --git a/apps/dev/nextjs/components/header.js b/apps/dev/nextjs/components/header.js index 69fc4d31..0255d6a4 100644 --- a/apps/dev/nextjs/components/header.js +++ b/apps/dev/nextjs/components/header.js @@ -1,5 +1,5 @@ import Link from "next/link" -import { useSession } from "@auth/nextjs/client" +import { useSession } from "next-auth/react" import styles from "./header.module.css" // The approach used in this component shows how to built a sign in and sign out diff --git a/apps/dev/nextjs/package.json b/apps/dev/nextjs/package.json index 6389c53a..f5ea5717 100644 --- a/apps/dev/nextjs/package.json +++ b/apps/dev/nextjs/package.json @@ -15,7 +15,7 @@ "license": "ISC", "dependencies": { "@auth/core": "workspace:*", - "@auth/nextjs": "workspace:*", + "next-auth": "workspace:*", "@next-auth/fauna-adapter": "workspace:*", "@next-auth/prisma-adapter": "workspace:*", "@next-auth/supabase-adapter": "workspace:*", @@ -23,7 +23,7 @@ "@prisma/client": "^3", "@supabase/supabase-js": "^2.0.5", "faunadb": "^4", - "next": "13.3.0", + "next": "13.3.2-canary.12", "next-auth": "workspace:*", "nodemailer": "^6", "react": "^18", diff --git a/apps/dev/nextjs/pages/_app.js b/apps/dev/nextjs/pages/_app.js index 44984949..5a467b7a 100644 --- a/apps/dev/nextjs/pages/_app.js +++ b/apps/dev/nextjs/pages/_app.js @@ -1,4 +1,4 @@ -import { SessionProvider } from "@auth/nextjs/client" +import { SessionProvider } from "next-auth/react" import "./styles.css" export default function App({ Component, pageProps }) { diff --git a/apps/dev/nextjs/pages/credentials.js b/apps/dev/nextjs/pages/credentials.js index 216dcfc8..97656665 100644 --- a/apps/dev/nextjs/pages/credentials.js +++ b/apps/dev/nextjs/pages/credentials.js @@ -1,6 +1,6 @@ // eslint-disable-next-line no-use-before-define import * as React from "react" -import { signIn, signOut, useSession } from "@auth/nextjs/client" +import { signIn, signOut, useSession } from "next-auth/react" import Layout from "components/layout" export default function Page() { diff --git a/apps/dev/nextjs/pages/email.js b/apps/dev/nextjs/pages/email.js index 0eb27fe7..a83dc550 100644 --- a/apps/dev/nextjs/pages/email.js +++ b/apps/dev/nextjs/pages/email.js @@ -1,6 +1,6 @@ // eslint-disable-next-line no-use-before-define import * as React from "react" -import { signIn, signOut, useSession } from "@auth/nextjs/client" +import { signIn, signOut, useSession } from "next-auth/react" import Layout from "components/layout" export default function Page() { diff --git a/apps/dev/nextjs/pages/protected-ssr.js b/apps/dev/nextjs/pages/protected-ssr.js index 781a77b3..545d5a1c 100644 --- a/apps/dev/nextjs/pages/protected-ssr.js +++ b/apps/dev/nextjs/pages/protected-ssr.js @@ -1,6 +1,6 @@ // This is an example of how to protect content using server rendering import { getServerSession } from "next-auth/next" -import { authOptions } from "./api/auth/[...nextauth]" +import { authConfig } from "./api/auth-old/[...nextauth]" import Layout from "../components/layout" import AccessDenied from "../components/access-denied" @@ -26,7 +26,7 @@ export default function Page({ content, session }) { } export async function getServerSideProps(context) { - const session = await getServerSession(context.req, context.res, authOptions) + const session = await getServerSession(context.req, context.res, authConfig) let content = null if (session) { diff --git a/apps/dev/nextjs/pages/protected.js b/apps/dev/nextjs/pages/protected.js index 80b44740..88951afb 100644 --- a/apps/dev/nextjs/pages/protected.js +++ b/apps/dev/nextjs/pages/protected.js @@ -1,5 +1,5 @@ import { useState, useEffect } from "react" -import { useSession } from "@auth/nextjs/client" +import { useSession } from "next-auth/react" import Layout from "../components/layout" export default function Page() { diff --git a/apps/dev/nextjs/pages/server.js b/apps/dev/nextjs/pages/server.js index df263f08..7d029254 100644 --- a/apps/dev/nextjs/pages/server.js +++ b/apps/dev/nextjs/pages/server.js @@ -1,6 +1,6 @@ import { getServerSession } from "next-auth/next" import Layout from "../components/layout" -import { authOptions } from "./api/auth-old/[...nextauth]" +import { authConfig } from "./api/auth-old/[...nextauth]" export default function Page() { // As this page uses Server Side Rendering, the `session` will be already @@ -40,7 +40,7 @@ export default function Page() { export async function getServerSideProps(context) { return { props: { - session: await getServerSession(context.req, context.res, authOptions), + session: await getServerSession(context.req, context.res, authConfig), }, } } diff --git a/apps/examples/next.config.js b/apps/examples/next.config.js new file mode 100644 index 00000000..0e5c476c --- /dev/null +++ b/apps/examples/next.config.js @@ -0,0 +1,4 @@ +/** @type {import("next").NextConfig} */ +module.exports = { + reactStrictMode: true, +} diff --git a/apps/examples/nextjs/.env.local.example b/apps/examples/nextjs/.env.local.example index 83ad1b28..4372a5cc 100644 --- a/apps/examples/nextjs/.env.local.example +++ b/apps/examples/nextjs/.env.local.example @@ -1,10 +1,6 @@ NEXTAUTH_URL=http://localhost:3000 NEXTAUTH_SECRET= # Linux: `openssl rand -hex 32` or go to https://generate-secret.vercel.app/32 -APPLE_ID= -APPLE_TEAM_ID= -APPLE_PRIVATE_KEY= -APPLE_KEY_ID= AUTH0_ID= AUTH0_SECRET= @@ -21,8 +17,3 @@ GOOGLE_SECRET= TWITTER_ID= TWITTER_SECRET= - -EMAIL_SERVER=smtp://username:password@smtp.example.com:587 -EMAIL_FROM=NextAuth - -DATABASE_URL=sqlite://localhost/:memory:?synchronize=true diff --git a/apps/examples/nextjs/README.md b/apps/examples/nextjs/README.md index 2c700394..be22914b 100644 --- a/apps/examples/nextjs/README.md +++ b/apps/examples/nextjs/README.md @@ -8,21 +8,21 @@ -

@auth/nextjs - Example App

+

next-auth - Example App

Open Source. Full Stack. Own Your Data.

- - npm + + npm - Bundle Size + Bundle Size - - Downloads + + Downloads - + TypeScript

@@ -32,7 +32,7 @@ NextAuth.js is a complete open-source authentication solution. -This is an example application that shows how `@auth/nextjs` is applied to a basic Next.js app. +This is an example application that shows how `next-auth` is applied to a basic Next.js app. The deployed version can be found at [`next-auth-example.vercel.app`](https://next-auth-example.vercel.app) diff --git a/apps/examples/nextjs/auth.ts b/apps/examples/nextjs/auth.ts index 06f3b80e..cf7a8ccf 100644 --- a/apps/examples/nextjs/auth.ts +++ b/apps/examples/nextjs/auth.ts @@ -1,4 +1,4 @@ -import { NextAuth } from "@auth/nextjs" +import NextAuth from "next-auth" import GitHub from "@auth/core/providers/github" export const { handlers, auth } = NextAuth({ diff --git a/apps/examples/nextjs/components/access-denied.tsx b/apps/examples/nextjs/components/access-denied.tsx index 6224511e..4c9c0d79 100644 --- a/apps/examples/nextjs/components/access-denied.tsx +++ b/apps/examples/nextjs/components/access-denied.tsx @@ -1,4 +1,4 @@ -import { signIn } from "@auth/nextjs/client" +import { signIn } from "next-auth/react" export default function AccessDenied() { return ( diff --git a/apps/examples/nextjs/components/footer.tsx b/apps/examples/nextjs/components/footer.tsx index c9e3f1d4..1303c60e 100644 --- a/apps/examples/nextjs/components/footer.tsx +++ b/apps/examples/nextjs/components/footer.tsx @@ -1,6 +1,6 @@ import Link from "next/link" import styles from "./footer.module.css" -import packageJSON from "@auth/nextjs/package.json" +import packageJSON from "next-auth/package.json" export default function Footer() { return ( diff --git a/apps/examples/nextjs/package.json b/apps/examples/nextjs/package.json index bbb063aa..400d00e1 100644 --- a/apps/examples/nextjs/package.json +++ b/apps/examples/nextjs/package.json @@ -20,15 +20,14 @@ ], "dependencies": { "@auth/core": "workspace:*", - "@auth/nextjs": "workspace:*", "next": "latest", - "nodemailer": "^6", - "react": "^18", - "react-dom": "^18" + "next-auth": "workspace:*", + "react": "^18.2.0", + "react-dom": "^18.2.0" }, "devDependencies": { - "@types/node": "^17", - "@types/react": "^18.0.37", - "typescript": "^4" + "@types/node": "^18.16.2", + "@types/react": "^18.2.0", + "typescript": "^5.0.4" } } diff --git a/docs/docs/concepts/faq.md b/docs/docs/concepts/faq.md index 4279eb7e..3c86a4c4 100644 --- a/docs/docs/concepts/faq.md +++ b/docs/docs/concepts/faq.md @@ -269,7 +269,7 @@ Ultimately if your request is not accepted or is not actively in development, yo

-Auth.js by default uses JSON Web Tokens for saving the user's session. However, if you use a [database adapter](/guides/adapters/using-a-database-adapter), the database will be used to persist the user's session. You can force the usage of JWT when using a database [through the configuration options](/reference/configuration/auth-config#session). Since v4 all our JWT tokens are now encrypted by default with A256GCM. +Auth.js by default uses JSON Web Tokens for saving the user's session. However, if you use a [database adapter](/guides/adapters/using-a-database-adapter), the database will be used to persist the user's session. You can force the usage of JWT when using a database [through the configuration options](/reference/configuration/auth-config#session). Since v4 all our JWTs are now encrypted by default with A256GCM.

diff --git a/docs/docs/getting-started/oauth-tutorial.mdx b/docs/docs/getting-started/oauth-tutorial.mdx index 0bbb3251..ddafeafd 100644 --- a/docs/docs/getting-started/oauth-tutorial.mdx +++ b/docs/docs/getting-started/oauth-tutorial.mdx @@ -36,10 +36,6 @@ This tutorial assumes you have a Next.js application set up. If you don't, you c npm install next-auth ``` -:::info -We are working on a new `@auth/nextjs` package that will make it easier to set up Auth.js with Next.js. Stay tuned! For now, you can use the `next-auth` package. -::: - ### Creating the server config Create the following [API route](https://nextjs.org/docs/api-routes/dynamic-api-routes#catch-all-api-routes) file. This route contains the necessary configuration for NextAuth.js, as well as the dynamic route handler: @@ -270,7 +266,7 @@ Note that, for each provider, the configuration process will be similar to what 2. Create create your OAuth application within it 3. Set the callback URL 4. Get the Client ID and Generate a Client Secret -::: + ::: ## 3. Wiring all together diff --git a/docs/docs/guides/adapters/creating-a-database-adapter.md b/docs/docs/guides/adapters/creating-a-database-adapter.md index e8620008..b31ca33f 100644 --- a/docs/docs/guides/adapters/creating-a-database-adapter.md +++ b/docs/docs/guides/adapters/creating-a-database-adapter.md @@ -6,7 +6,7 @@ Using a custom adapter you can connect to any database back-end or even several ## How to create an adapter -For more information about the data these methods need to manage see [models](/reference/adapters/models). +For more information about the data these methods need to manage see [models](/reference/adapters#models). _See the code below for practical example._ diff --git a/docs/docs/guides/basics/events.md b/docs/docs/guides/basics/events.md index 33305562..2d699eac 100644 --- a/docs/docs/guides/basics/events.md +++ b/docs/docs/guides/basics/events.md @@ -29,7 +29,7 @@ Sent when the user signs out. The message object will contain one of these depending on if you use JWT or database persisted sessions: -- `token`: The JWT token for this session. +- `token`: The JWT for this session. - `session`: The session object from your adapter that is being ended ### createUser @@ -60,5 +60,5 @@ Sent at the end of a request for the current session. The message object will contain one of these depending on if you use JWT or database persisted sessions: -- `token`: The JWT token for this session. +- `token`: The JWT for this session. - `session`: The session object from your adapter. diff --git a/docs/docs/reference/adapters/index.md b/docs/docs/reference/adapters/index.md index 1ad11728..17662141 100644 --- a/docs/docs/reference/adapters/index.md +++ b/docs/docs/reference/adapters/index.md @@ -2,7 +2,7 @@ title: Overview --- -Using a Auth.js / NextAuth.js adapter you can connect to any database service or even several different services at the same time. The following listed official adapters are created and maintained by the community: +Using an Auth.js / NextAuth.js adapter you can connect to any database service or even several different services at the same time. The following listed official adapters are created and maintained by the community:
@@ -71,7 +71,7 @@ If you don't find an adapter for the database or service you use, you can always ## Models -Auth.js can be used with any database. Models tell you what structures Auth.js expects from your database. Models will vary slightly depending on which adapter you use, but in general, will look something like this. Each adapter's model/schema will be slightly adapted for its needs, but will look very much like this schema below: +Auth.js can be used with any database. Models tell you what structures Auth.js expects from your database. Models will vary slightly depending on which adapter you use, but in general, will look something like this: ```mermaid erDiagram @@ -96,15 +96,8 @@ erDiagram string type string provider string providerAccountId - string refresh_token string access_token - int expires_at - string token_type - string scope string id_token - string session_state - string oauth_token_secret - string oauth_token } VerificationToken { string identifier @@ -113,10 +106,10 @@ erDiagram } ``` -More information about each Model / Table can be found below. +More information about each Model/Table can be found below. :::note -You can [create your own adapter](/guides/adapters/creating-a-database-adapter) if you want to use Auth.js with a database that is not supported out of the box, or you have to change fields on any of the models. +You can [create your adapter](/guides/adapters/creating-a-database-adapter) if you want to use Auth.js with a database that is not supported out of the box, or you have to change fields on any of the models. ::: --- @@ -125,30 +118,31 @@ You can [create your own adapter](/guides/adapters/creating-a-database-adapter) The User model is for information such as the user's name and email address. -Email address is optional, but if one is specified for a User then it must be unique. +Email address is optional, but if one is specified for a User, then it must be unique. :::note -If a user first signs in with OAuth then their email address is automatically populated using the one from their OAuth profile, if the OAuth provider returns one. +If a user first signs in with an OAuth provider, then their email address is automatically populated using the one from their OAuth profile if the OAuth provider returns one. -This provides a way to contact users and for users to maintain access to their account and sign in using email in the event they are unable to sign in with the OAuth provider in future (if the [Email Provider](/getting-started/email-tutorial) is configured). +This provides a way to contact users and for users to maintain access to their account and sign in using email in the event they are unable to sign in with the OAuth provider in the future (if the [Email Provider](/reference/core/providers_email) is configured). ::: -User creation in the database is automatic, and happens when the user is logging in for the first time with a provider. The default data saved is `id`, `name`, `email` and `image`. You can add more profile data by returning extra fields in your [OAuth provider](/guides/providers/custom-provider)'s [`profile()`](/reference/core/providers#profile) callback. +User creation in the database is automatic and happens when the user is logging in for the first time with a provider. +If the first sign-in is via the [OAuth Provider](/reference/core/providers_oauth), the default data saved is `id`, `name`, `email` and `image`. You can add more profile data by returning extra fields in your [OAuth provider](/guides/providers/custom-provider)'s [`profile()`](/reference/core/providers#profile) callback. + +If the first sign-in is via the [Email Provider](/reference/core/providers_email), then the saved user will have `id`, `email`, `emailVerified`, where `emailVerified` is the timestamp of when the user was created. ### Account -The Account model is for information about OAuth accounts associated with a User. It will usually contain `access_token`, `id_token` and other OAuth specific data. [`TokenSet`](https://github.com/panva/node-openid-client/blob/main/docs/README.md#new-tokensetinput) from `openid-client` might give you an idea of all the fields. - -:::note -In case of an OAuth 1.0 provider (like Twitter), you will have to look for `oauth_token` and `oauth_token_secret` string fields. GitHub also has an extra `refresh_token_expires_in` integer field. You have to make sure that your database schema includes these fields. -::: +The Account model is for information about OAuth accounts associated with a User A single User can have multiple Accounts, but each Account can only have one User. -Linking Accounts to Users happen automatically, only when they have the same e-mail address, and the user is currently signed in. Check the [FAQ](/concepts/faq#security) for more information why this is a requirement. +Account creation in the database is automatic and happens when the user is logging in for the first time with a provider, or the [`Adapter.linkAccount`](/reference/core/adapters#linkaccount) method is invoked. The default data saved is `access_token`, `refresh_token`, `id_token` and `expires_at`. You can save other fields by returning them in the [OAuth provider](/guides/providers/custom-provider)'s [`account()`](/reference/core/providers#account) callback. + +Linking Accounts to Users happen automatically, only when they have the same e-mail address, and the user is currently signed in. Check the [FAQ](/concepts/faq#security) for more information on why this is a requirement. :::tip -You can manually unlink accounts, if your adapter implements the `unlinkAccount` method. Make sure to take all the necessary security steps to avoid data loss. +You can manually unlink accounts if your adapter implements the `unlinkAccount` method. Make sure to take all the necessary security steps to avoid data loss. ::: :::note @@ -162,7 +156,7 @@ The Session model is used for database sessions. It is not used if JSON Web Toke A single User can have multiple Sessions, each Session can only have one User. :::tip -When a Session is read, we check if it's `expires` field indicates an invalid session, and delete it from the database. You can also do this clean-up periodically in the background to avoid our extra delete call to the database during an active session retrieval. This might result in a slight performance increase in a few cases. +When a Session is read, we check if its `expires` field indicates an invalid session, and delete it from the database. You can also do this clean-up periodically in the background to avoid our extra delete call to the database during an active session retrieval. This might result in a slight performance increase in a few cases. ::: ### Verification Token @@ -171,7 +165,7 @@ The Verification Token model is used to store tokens for passwordless sign in. A single User can have multiple open Verification Tokens (e.g. to sign in to different devices). -It has been designed to be extendable for other verification purposes in the future (e.g. 2FA / short codes). +It has been designed to be extendable for other verification purposes in the future (e.g. 2FA / magic codes, etc.). :::note Auth.js makes sure that every token is usable only once, and by default has a short (1 day, can be configured by [`maxAge`](/guides/providers/email)) lifetime. If your user did not manage to finish the sign-in flow in time, they will have to start the sign-in process again. @@ -183,8 +177,7 @@ Due to users forgetting or failing at the sign-in flow, you might end up with un ## RDBMS Naming Convention -Auth.js / NextAuth.js uses `camelCase` for its own database rows, while respecting the conventional `snake_case` formatting for OAuth related values. If mixed casing is an issue for you, most adapters have a dedicated section on how to use a single naming convention. - +Auth.js / NextAuth.js uses `camelCase` for its database rows while respecting the conventional `snake_case` formatting for OAuth-related values. If the mixed casing is an issue for you, most adapters have a dedicated documentation section on how to force a casing convention. ## TypeScript diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index eca23d45..d2999e7f 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -7,7 +7,7 @@ const path = require("path") const coreSrc = "../packages/core/src" const providers = fs .readdirSync(path.join(__dirname, coreSrc, "/providers")) - .filter((file) => file.endsWith(".ts") && !file.startsWith("oauth")) + .filter((file) => file.endsWith(".ts")) .map((p) => `${coreSrc}/providers/${p}`) const typedocConfig = require("./typedoc.json") @@ -249,7 +249,7 @@ const docusaurusConfig = { plugins: [ typedocFramework("core", ["index.ts", "adapters.ts", "errors.ts", "jwt.ts", "types.ts"]), typedocFramework("frameworks-sveltekit", ["lib/index.ts", "lib/client.ts"]), - typedocFramework("frameworks-nextjs", ["index.ts", "client.tsx"]), + typedocFramework("next-auth", ["index.ts", "react.tsx", "jwt.ts", "adapters.ts", "next.ts", "types.ts", "middleware.ts"]), ...(process.env.TYPEDOC_SKIP_ADAPTERS ? [] : [ diff --git a/docs/sidebars.js b/docs/sidebars.js index 99939249..dbb12bbb 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -35,9 +35,9 @@ module.exports = { }, { type: "category", - label: "@auth/nextjs", - link: { type: "doc", id: "reference/nextjs/index" }, - items: [{ type: "autogenerated", dirName: "reference/nextjs" }], + label: "next-auth", + link: { type: "doc", id: "reference/next-auth/index" }, + items: [{ type: "autogenerated", dirName: "reference/next-auth" }], }, ...(process.env.TYPEDOC_SKIP_ADAPTERS ? [] diff --git a/docs/src/components/ProviderMarquee.js b/docs/src/components/ProviderMarquee.js index 9afcdfaa..319716ee 100644 --- a/docs/src/components/ProviderMarquee.js +++ b/docs/src/components/ProviderMarquee.js @@ -19,23 +19,29 @@ const icons = [ "/img/providers/twitter.svg", ] -export default React.memo(function ProviderMarquee() { - let scale = 0.4 - +function changeScale() { if (typeof window !== "undefined") { const width = window.outerWidth - if (width > 800) { - scale = 0.6 - } - if (width > 1100) { - scale = 0.7 - } - - if (width > 1400) { - scale = 0.8 - } + if (width > 800) return 0.6 + else if (width > 1100) return 0.7 + else if (width > 1400) return 0.8 } +} + +export default React.memo(function ProviderMarquee() { + // Get initial scale on load + const [scale, setScale] = React.useState(changeScale) + + React.useEffect(() => { + // Account for window size change + function handleEvent() { + setScale(changeScale) + } + + window.addEventListener("resize", handleEvent) + return () => window.removeEventListener("resize", handleEvent) + }, []) return (
diff --git a/docs/src/css/index.css b/docs/src/css/index.css index 08486c3a..7852a5e4 100644 --- a/docs/src/css/index.css +++ b/docs/src/css/index.css @@ -124,6 +124,9 @@ html[data-theme="dark"] hr { font-size: 1rem; font-weight: 700; width: 100%; + display: flex; + justify-content: space-between; + flex-wrap: wrap; } .home-main .code .code-heading span { diff --git a/docs/static/img/providers/authentik.svg b/docs/static/img/providers/authentik.svg new file mode 100644 index 00000000..517eb179 --- /dev/null +++ b/docs/static/img/providers/authentik.svg @@ -0,0 +1 @@ + diff --git a/package.json b/package.json index 3a196b2e..b4263104 100644 --- a/package.json +++ b/package.json @@ -97,8 +97,6 @@ "packages/core/src/lib/pages/styles.ts", "packages/frameworks-sveltekit/package", "packages/frameworks-sveltekit/vite.config.{js,ts}.timestamp-*", - "packages/next-auth/src/providers/oauth-types.ts", - "packages/next-auth/css/index.css", ".branches", "db.sqlite", "dev.db", @@ -252,7 +250,7 @@ "apps/dev/nextjs/pages/api/auth-old/[...nextauth].ts", "apps/dev/nextjs/app/api/auth/[...nextauth]/route.ts", "docs/{sidebars,docusaurus.config}.js", - "packages/frameworks-nextjs/src/lib/env.ts" + "packages/next-auth/src/lib/env.ts" ], "options": { "printWidth": 150 diff --git a/packages/next-auth/.npmrc b/packages/adapter-neo4j/.npmrc similarity index 100% rename from packages/next-auth/.npmrc rename to packages/adapter-neo4j/.npmrc diff --git a/packages/adapter-neo4j/package.json b/packages/adapter-neo4j/package.json index 531ad58d..0133bdc8 100644 --- a/packages/adapter-neo4j/package.json +++ b/packages/adapter-neo4j/package.json @@ -1,6 +1,6 @@ { "name": "@next-auth/neo4j-adapter", - "version": "1.0.5", + "version": "1.0.6", "description": "neo4j adapter for next-auth.", "homepage": "https://authjs.dev", "repository": "https://github.com/nextauthjs/next-auth", @@ -33,7 +33,7 @@ "dist" ], "peerDependencies": { - "neo4j-driver": "^4.0.0", + "neo4j-driver": "^4.0.0 || ^5.7.0", "next-auth": "^4" }, "devDependencies": { @@ -41,7 +41,7 @@ "@next-auth/tsconfig": "workspace:*", "@types/uuid": "^8.3.3", "jest": "^27.4.3", - "neo4j-driver": "^4.4.0", + "neo4j-driver": "^5.7.0", "next-auth": "workspace:*" }, "dependencies": { @@ -50,4 +50,4 @@ "jest": { "preset": "@next-auth/adapter-test/jest" } -} +} \ No newline at end of file diff --git a/packages/adapter-xata/src/index.ts b/packages/adapter-xata/src/index.ts index 860c728d..fefea69c 100644 --- a/packages/adapter-xata/src/index.ts +++ b/packages/adapter-xata/src/index.ts @@ -195,7 +195,7 @@ import type { XataClient } from "./xata" * xata init --schema=./path/to/your/schema.json * ``` * - * The CLI will walk you through a setup process where you choose a [workspace](https://docs.xata.io/concepts/workspaces) (kind of like a GitHub org or a Vercel team) and an appropriate database. We recommend using a fresh database for this, as we'll augment it with tables that Auth.js needs. + * The CLI will walk you through a setup process where you choose a [workspace](https://xata.io/docs/api-reference/workspaces) (kind of like a GitHub org or a Vercel team) and an appropriate database. We recommend using a fresh database for this, as we'll augment it with tables that Auth.js needs. * * Once you're done, you can continue using Auth.js in your project as expected, like creating a `./pages/api/auth/[...nextauth]` route. * diff --git a/packages/core/package.json b/packages/core/package.json index ffcdbbd5..9c3253ad 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@auth/core", - "version": "0.7.0", + "version": "0.7.1", "description": "Authentication for the Web.", "keywords": [ "authentication", @@ -93,4 +93,4 @@ "postcss": "8.4.19", "postcss-nested": "6.0.0" } -} +} \ No newline at end of file diff --git a/packages/core/src/adapters.ts b/packages/core/src/adapters.ts index 4d67cbce..8dfa65db 100644 --- a/packages/core/src/adapters.ts +++ b/packages/core/src/adapters.ts @@ -228,6 +228,10 @@ export interface Adapter { deleteUser?( userId: string ): Promise | Awaitable + /** + * This method is invoked internally (but optionally can be used for manual linking). + * It creates an [Account](https://authjs.dev/reference/adapters#models) in the database. + */ linkAccount?( account: AdapterAccount ): Promise | Awaitable diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts index 35589432..d6c2d5dd 100644 --- a/packages/core/src/errors.ts +++ b/packages/core/src/errors.ts @@ -20,13 +20,6 @@ export class AuthError extends Error { } } -/** - * @todo - * Thrown when an Email address is already associated with an account - * but the user is trying an OAuth account that is not linked to it. - */ -export class AccountNotLinked extends AuthError {} - /** * @todo * One of the database `Adapter` methods failed. @@ -37,8 +30,8 @@ export class AdapterError extends AuthError {} export class AuthorizedCallbackError extends AuthError {} /** - * There was an error while trying to finish up authenticating the user. - * Depending on the type of provider, this could be for multiple reasons. + * This error occurs when the user cannot finish the sign-in process. + * Depending on the provider type, this could have happened for multiple reasons. * * :::tip * Check out `[auth][details]` in the error message to know which provider failed. @@ -48,7 +41,7 @@ export class AuthorizedCallbackError extends AuthError {} * ``` * ::: * - * For an **OAuth provider**, possible causes are: + * For an [OAuth provider](https://authjs.dev/reference/core/providers_oauth), possible causes are: * - The user denied access to the application * - There was an error parsing the OAuth Profile: * Check out the provider's `profile` or `userinfo.request` method to make sure @@ -56,7 +49,7 @@ export class AuthorizedCallbackError extends AuthError {} * - The `signIn` or `jwt` callback methods threw an uncaught error: * Check the callback method implementations. * - * For an **Email provider**, possible causes are: + * For an [Email provider](https://authjs.dev/reference/core/providers_email), possible causes are: * - The provided email/token combination was invalid/missing: * Check if the provider's `sendVerificationRequest` method correctly sends the email. * - The provided email/token combination has expired: @@ -64,7 +57,7 @@ export class AuthorizedCallbackError extends AuthError {} * - There was an error with the database: * Check the database logs. * - * For a **Credentials provider**, possible causes are: + * For a [Credentials provider](https://authjs.dev/reference/core/providers_credentials), possible causes are: * - The `authorize` method threw an uncaught error: * Check the provider's `authorize` method. * - The `signIn` or `jwt` callback methods threw an uncaught error: @@ -107,11 +100,30 @@ export class MissingAPIRoute extends AuthError {} /** @todo */ export class MissingAuthorize extends AuthError {} -/** @todo */ +/** + * Auth.js requires a secret to be set, but none was not found. This is used to encrypt cookies, JWTs and other sensitive data. + * + * :::note + * If you are using a framework like Next.js, we try to automatically infer the secret from the `AUTH_SECRET` environment variable. + * Alternatively, you can also explicitly set the [`AuthConfig.secret`](https://authjs.dev/reference/core#secret). + * ::: + * + * + * :::tip + * You can generate a good secret value: + * - On Unix systems: type `openssl rand -hex 32` in the terminal + * - Or generate one [online](https://generate-secret.vercel.app/32) + * + * ::: + */ export class MissingSecret extends AuthError {} -/** @todo */ -export class OAuthSignInError extends AuthError {} +/** + * @todo + * Thrown when an Email address is already associated with an account + * but the user is trying an OAuth account that is not linked to it. + */ +export class OAuthAccountNotLinked extends AuthError {} /** @todo */ export class OAuthCallbackError extends AuthError {} @@ -119,19 +131,51 @@ export class OAuthCallbackError extends AuthError {} /** @todo */ export class OAuthCreateUserError extends AuthError {} -/** @todo */ +/** + * This error occurs during an OAuth sign in attempt when the provdier's + * response could not be parsed. This could for example happen if the provider's API + * changed, or the [`OAuth2Config.profile`](https://authjs.dev/reference/core/providers_oauth#profile) method is not implemented correctly. + */ export class OAuthProfileParseError extends AuthError {} /** @todo */ export class SessionTokenError extends AuthError {} -/** @todo */ +/** + * This error occurs when the user cannot initiate the sign-in process. + * Depending on the provider type, this could have happened for multiple reasons. + * + * :::tip + * Check out `[auth][details]` in the error message to know which provider failed. + * @example + * ```sh + * [auth][details]: { "provider": "github" } + * ``` + * ::: + * + * For an [OAuth provider](https://authjs.dev/reference/core/providers_oauth), possible causes are: + * - The Authorization Server is not compliant with the [OAuth 2.0 specifcation](https://www.ietf.org/rfc/rfc6749.html) + * Check the details in the error message. + * - A runtime error occurred in Auth.js. This should be reported as a bug. + * + * For an [Email provider](https://authjs.dev/reference/core/providers_email), possible causes are: + * - The email sent from the client is invalid, could not be normalized by [`EmailConfig.normalizeIdentifier`](https://authjs.dev/reference/core/providers_email#normalizeidentifier) + * - The provided email/token combination has expired: + * Ask the user to log in again. + * - There was an error with the database: + * Check the database logs. + * + */ export class SignInError extends AuthError {} /** @todo */ export class SignOutError extends AuthError {} -/** @todo */ +/** + * Auth.js was requested to handle an operation that it does not support. + * + * See [`AuthAction`](https://authjs.dev/reference/core/types#authaction) for the supported actions. + */ export class UnknownAction extends AuthError {} /** @todo */ diff --git a/packages/core/src/jwt.ts b/packages/core/src/jwt.ts index 73f566ce..87f8cd1a 100644 --- a/packages/core/src/jwt.ts +++ b/packages/core/src/jwt.ts @@ -190,7 +190,7 @@ export interface JWTEncodeParams { /** * The maximum age of the Auth.js issued JWT in seconds. * - * @default 30 * 24 * 30 * 60 // 30 days + * @default 30 * 24 * 60 * 60 // 30 days */ maxAge?: number } @@ -213,7 +213,7 @@ export interface JWTOptions { /** * The maximum age of the Auth.js issued JWT in seconds. * - * @default 30 * 24 * 30 * 60 // 30 days + * @default 30 * 24 * 60 * 60 // 30 days */ maxAge: number /** Override this method to control the Auth.js issued JWT encoding. */ diff --git a/packages/core/src/lib/callback-handler.ts b/packages/core/src/lib/callback-handler.ts index 2344a81d..bae3ade9 100644 --- a/packages/core/src/lib/callback-handler.ts +++ b/packages/core/src/lib/callback-handler.ts @@ -1,4 +1,4 @@ -import { AccountNotLinked } from "../errors.js" +import { OAuthAccountNotLinked } from "../errors.js" import { fromDate } from "./utils/date.js" import type { @@ -49,7 +49,7 @@ export async function handleLogin( } const profile = _profile as AdapterUser - const account = _account as AdapterAccount + let account = _account as AdapterAccount const { createUser, @@ -122,113 +122,116 @@ export async function handleLogin( }) return { session, user, isNewUser } - } else if (account.type === "oauth" || account.type === "oidc") { - // If signing in with OAuth account, check to see if the account exists already - const userByAccount = await getUserByAccount({ - providerAccountId: account.providerAccountId, - provider: account.provider, - }) - if (userByAccount) { - if (user) { - // If the user is already signed in with this account, we don't need to do anything - if (userByAccount.id === user.id) { - return { session, user, isNewUser } - } - // If the user is currently signed in, but the new account they are signing in - // with is already associated with another user, then we cannot link them - // and need to return an error. - throw new AccountNotLinked( - "The account is already associated with another user", - { provider: account.provider } - ) - } - // If there is no active session, but the account being signed in with is already - // associated with a valid user then create session to sign the user in. - session = useJwtSession - ? {} - : await createSession({ - sessionToken: generateSessionToken(), - userId: userByAccount.id, - expires: fromDate(options.session.maxAge), - }) + } - return { session, user: userByAccount, isNewUser } - } else { - if (user) { - // If the user is already signed in and the OAuth account isn't already associated - // with another user account then we can go ahead and link the accounts safely. - await linkAccount({ ...account, userId: user.id }) - await events.linkAccount?.({ user, account, profile }) - - // As they are already signed in, we don't need to do anything after linking them + // If signing in with OAuth account, check to see if the account exists already + const userByAccount = await getUserByAccount({ + providerAccountId: account.providerAccountId, + provider: account.provider, + }) + if (userByAccount) { + if (user) { + // If the user is already signed in with this account, we don't need to do anything + if (userByAccount.id === user.id) { return { session, user, isNewUser } } + // If the user is currently signed in, but the new account they are signing in + // with is already associated with another user, then we cannot link them + // and need to return an error. + throw new OAuthAccountNotLinked( + "The account is already associated with another user", + { provider: account.provider } + ) + } + // If there is no active session, but the account being signed in with is already + // associated with a valid user then create session to sign the user in. + session = useJwtSession + ? {} + : await createSession({ + sessionToken: generateSessionToken(), + userId: userByAccount.id, + expires: fromDate(options.session.maxAge), + }) - // If the user is not signed in and it looks like a new OAuth account then we - // check there also isn't an user account already associated with the same - // email address as the one in the OAuth profile. - // - // This step is often overlooked in OAuth implementations, but covers the following cases: - // - // 1. It makes it harder for someone to accidentally create two accounts. - // e.g. by signin in with email, then again with an oauth account connected to the same email. - // 2. It makes it harder to hijack a user account using a 3rd party OAuth account. - // e.g. by creating an oauth account then changing the email address associated with it. - // - // It's quite common for services to automatically link accounts in this case, but it's - // better practice to require the user to sign in *then* link accounts to be sure - // someone is not exploiting a problem with a third party OAuth service. - // - // OAuth providers should require email address verification to prevent this, but in - // practice that is not always the case; this helps protect against that. - const userByEmail = profile.email - ? await getUserByEmail(profile.email) - : null - if (userByEmail) { - const provider = options.provider as OAuthConfig - if (provider?.allowDangerousEmailAccountLinking) { - // If you trust the oauth provider to correctly verify email addresses, you can opt-in to - // account linking even when the user is not signed-in. - user = userByEmail - } else { - // We end up here when we don't have an account with the same [provider].id *BUT* - // we do already have an account with the same email address as the one in the - // OAuth profile the user has just tried to sign in with. - // - // We don't want to have two accounts with the same email address, and we don't - // want to link them in case it's not safe to do so, so instead we prompt the user - // to sign in via email to verify their identity and then link the accounts. - throw new AccountNotLinked( - "Another account already exists with the same e-mail address", - { provider: account.provider } - ) - } - } else { - // If the current user is not logged in and the profile isn't linked to any user - // accounts (by email or provider account id)... - // - // If no account matching the same [provider].id or .email exists, we can - // create a new account for the user, link it to the OAuth account and - // create a new session for them so they are signed in with it. - const { id: _, ...newUser } = { ...profile, emailVerified: null } - user = await createUser(newUser) - } - await events.createUser?.({ user }) + return { session, user: userByAccount, isNewUser } + } else { + const { provider: p } = options as InternalOptions<"oauth" | "oidc"> + const { type, provider, providerAccountId, userId, ...tokenSet } = account + const defaults = { providerAccountId, provider, type, userId } + account = Object.assign(p.account(tokenSet), defaults) + if (user) { + // If the user is already signed in and the OAuth account isn't already associated + // with another user account then we can go ahead and link the accounts safely. await linkAccount({ ...account, userId: user.id }) await events.linkAccount?.({ user, account, profile }) - session = useJwtSession - ? {} - : await createSession({ - sessionToken: generateSessionToken(), - userId: user.id, - expires: fromDate(options.session.maxAge), - }) - - return { session, user, isNewUser: true } + // As they are already signed in, we don't need to do anything after linking them + return { session, user, isNewUser } } - } - throw new Error("Unsupported account type") + // If the user is not signed in and it looks like a new OAuth account then we + // check there also isn't an user account already associated with the same + // email address as the one in the OAuth profile. + // + // This step is often overlooked in OAuth implementations, but covers the following cases: + // + // 1. It makes it harder for someone to accidentally create two accounts. + // e.g. by signin in with email, then again with an oauth account connected to the same email. + // 2. It makes it harder to hijack a user account using a 3rd party OAuth account. + // e.g. by creating an oauth account then changing the email address associated with it. + // + // It's quite common for services to automatically link accounts in this case, but it's + // better practice to require the user to sign in *then* link accounts to be sure + // someone is not exploiting a problem with a third party OAuth service. + // + // OAuth providers should require email address verification to prevent this, but in + // practice that is not always the case; this helps protect against that. + const userByEmail = profile.email + ? await getUserByEmail(profile.email) + : null + if (userByEmail) { + const provider = options.provider as OAuthConfig + if (provider?.allowDangerousEmailAccountLinking) { + // If you trust the oauth provider to correctly verify email addresses, you can opt-in to + // account linking even when the user is not signed-in. + user = userByEmail + } else { + // We end up here when we don't have an account with the same [provider].id *BUT* + // we do already have an account with the same email address as the one in the + // OAuth profile the user has just tried to sign in with. + // + // We don't want to have two accounts with the same email address, and we don't + // want to link them in case it's not safe to do so, so instead we prompt the user + // to sign in via email to verify their identity and then link the accounts. + throw new OAuthAccountNotLinked( + "Another account already exists with the same e-mail address", + { provider: account.provider } + ) + } + } else { + // If the current user is not logged in and the profile isn't linked to any user + // accounts (by email or provider account id)... + // + // If no account matching the same [provider].id or .email exists, we can + // create a new account for the user, link it to the OAuth account and + // create a new session for them so they are signed in with it. + const { id: _, ...newUser } = { ...profile, emailVerified: null } + user = await createUser(newUser) + } + await events.createUser?.({ user }) + + await linkAccount({ ...account, userId: user.id }) + await events.linkAccount?.({ user, account, profile }) + + session = useJwtSession + ? {} + : await createSession({ + sessionToken: generateSessionToken(), + userId: user.id, + expires: fromDate(options.session.maxAge), + }) + + return { session, user, isNewUser: true } + } } diff --git a/packages/core/src/lib/index.ts b/packages/core/src/lib/index.ts index 1bcb468b..2a44f7c1 100644 --- a/packages/core/src/lib/index.ts +++ b/packages/core/src/lib/index.ts @@ -110,14 +110,11 @@ export async function AuthInternal< if ( [ "Signin", - "OAuthSignin", "OAuthCallback", "OAuthCreateAccount", "EmailCreateAccount", "Callback", "OAuthAccountNotLinked", - "EmailSignin", - "CredentialsSignin", "SessionRequired", ].includes(error as string) ) { diff --git a/packages/core/src/lib/oauth/callback.ts b/packages/core/src/lib/oauth/callback.ts index 04f5079d..44ed06d3 100644 --- a/packages/core/src/lib/oauth/callback.ts +++ b/packages/core/src/lib/oauth/callback.ts @@ -3,6 +3,7 @@ import * as o from "oauth4webapi" import { OAuthCallbackError, OAuthProfileParseError } from "../../errors.js" import type { + Account, InternalOptions, LoggerInstance, Profile, @@ -123,8 +124,8 @@ export async function handleOAuth( throw new Error("TODO: Handle www-authenticate challenges as needed") } - let profile: Profile = {} - let tokens: TokenSet + let profile: Profile + let tokens: TokenSet & Pick if (provider.type === "oidc") { const nonce = await checks.nonce.use(cookies, resCookies, options) @@ -162,37 +163,49 @@ export async function handleOAuth( (tokens as any).access_token ) profile = await userinfoResponse.json() + } else { + throw new TypeError("No userinfo endpoint configured") } } - const profileResult = await getProfile(profile, provider, tokens, logger) + if (tokens.expires_in) { + tokens.expires_at = + Math.floor(Date.now() / 1000) + Number(tokens.expires_in) + } + + const profileResult = await getUserAndProfile( + profile, + provider, + tokens, + logger + ) return { ...profileResult, cookies: resCookies } } /** Returns profile, raw profile and auth provider details */ -async function getProfile( +async function getUserAndProfile( OAuthProfile: Profile, provider: OAuthConfigInternal, tokens: TokenSet, logger: LoggerInstance ) { try { - const profile = await provider.profile(OAuthProfile, tokens) - profile.email = profile.email?.toLowerCase() + const user = await provider.profile(OAuthProfile, tokens) + user.email = user.email?.toLowerCase() - if (!profile.id) { + if (!user.id) { throw new TypeError( - `Profile id is missing in ${provider.name} OAuth profile response` + `User id is missing in ${provider.name} OAuth profile response` ) } return { - profile, + user, account: { provider: provider.id, type: provider.type, - providerAccountId: profile.id.toString(), + providerAccountId: user.id.toString(), ...tokens, }, OAuthProfile, @@ -206,6 +219,8 @@ async function getProfile( // redirected back to the sign up page. We log the error to help developers // who might be trying to debug this when configuring a new provider. logger.debug("getProfile error details", OAuthProfile) - logger.error(new OAuthProfileParseError(e as Error)) + logger.error( + new OAuthProfileParseError(e as Error, { provider: provider.id }) + ) } } diff --git a/packages/core/src/lib/providers.ts b/packages/core/src/lib/providers.ts index 2da2d80b..496e34b2 100644 --- a/packages/core/src/lib/providers.ts +++ b/packages/core/src/lib/providers.ts @@ -1,13 +1,15 @@ import { merge } from "./utils/merge.js" import type { + AccountCallback, OAuthConfig, OAuthConfigInternal, OAuthEndpointType, OAuthUserConfig, + ProfileCallback, Provider, } from "../providers/index.js" -import type { AuthConfig, InternalProvider } from "../types.js" +import type { AuthConfig, InternalProvider, Profile } from "../types.js" /** * Adds `signinUrl` and `callbackUrl` to each provider @@ -77,18 +79,47 @@ function normalizeOAuth( checks, userinfo, profile: c.profile ?? defaultProfile, + account: c.account ?? defaultAccount, } } -function defaultProfile(profile: any) { - return { +/** + * Returns basic user profile from the userinfo response/`id_token` claims. + * @see https://authjs.dev/reference/adapters#user + * @see https://openid.net/specs/openid-connect-core-1_0.html#IDToken + * @see https://openid.net/specs/openid-connect-core-1_0.html#UserInfo + */ +const defaultProfile: ProfileCallback = (profile) => { + return stripUndefined({ id: profile.sub ?? profile.id, - name: - profile.name ?? profile.nickname ?? profile.preferred_username ?? null, - email: profile.email ?? null, - image: profile.picture ?? null, - } + name: profile.name ?? profile.nickname ?? profile.preferred_username, + email: profile.email, + image: profile.picture, + }) } + +/** + * Returns basic OAuth/OIDC values from the token response. + * @see https://www.ietf.org/rfc/rfc6749.html#section-5.1 + * @see https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse + * @see https://authjs.dev/reference/adapters#account + * + * @todo Return `refresh_token` and `expires_at` as well when built-in + * refresh token support is added. (Can make it opt-in first with a flag). + */ +const defaultAccount: AccountCallback = (account) => { + return stripUndefined({ + access_token: account.access_token, + id_token: account.id_token, + }) +} + +function stripUndefined(o: T): T { + const result = {} as any + for (let [k, v] of Object.entries(o)) v !== undefined && (result[k] = v) + return result as T +} + function normalizeEndpoint( e?: OAuthConfig[OAuthEndpointType], issuer?: string diff --git a/packages/core/src/lib/routes/callback.ts b/packages/core/src/lib/routes/callback.ts index 4b0fead9..8b708a45 100644 --- a/packages/core/src/lib/routes/callback.ts +++ b/packages/core/src/lib/routes/callback.ts @@ -68,14 +68,18 @@ export async function callback(params: { logger.debug("authorization result", authorizationResult) - const { profile, account, OAuthProfile } = authorizationResult + const { + user: userFromProvider, + account, + OAuthProfile, + } = authorizationResult // If we don't have a profile object then either something went wrong // or the user cancelled signing in. We don't know which, so we just // direct the user to the signin page for now. We could do something // else in future. // TODO: Handle user cancelling signin - if (!profile || !account || !OAuthProfile) { + if (!userFromProvider || !account || !OAuthProfile) { return { redirect: `${url}/signin`, cookies } } @@ -83,7 +87,7 @@ export async function callback(params: { // Attempt to get Profile from OAuth provider details before invoking // signIn callback - but if no user object is returned, that is fine // (that just means it's a new user signing in for the first time). - let userOrProfile = profile + let userByAccountOrFromProvider if (adapter) { const { getUserByAccount } = adapter const userByAccount = await getUserByAccount({ @@ -91,11 +95,15 @@ export async function callback(params: { provider: provider.id, }) - if (userByAccount) userOrProfile = userByAccount + if (userByAccount) userByAccountOrFromProvider = userByAccount } const unauthorizedOrError = await handleAuthorized( - { user: userOrProfile, account, profile: OAuthProfile }, + { + user: userByAccountOrFromProvider, + account, + profile: OAuthProfile, + }, options ) @@ -104,7 +112,7 @@ export async function callback(params: { // Sign user in const { user, session, isNewUser } = await handleLogin( sessionStore.value, - profile, + userFromProvider, account, options ) @@ -152,7 +160,7 @@ export async function callback(params: { }) } - await events.signIn?.({ user, account, profile, isNewUser }) + await events.signIn?.({ user, account, profile: OAuthProfile, isNewUser }) // Handle first logins on new accounts // e.g. option to send users to a new account landing page on initial login @@ -362,6 +370,7 @@ export async function callback(params: { } catch (e) { const error = new CallbackRouteError(e as Error, { provider: provider.id }) + logger.debug("callback route error details", { method, query, body }) logger.error(error) url.searchParams.set("error", CallbackRouteError.name) url.pathname += "/error" diff --git a/packages/core/src/lib/routes/signin.ts b/packages/core/src/lib/routes/signin.ts index f5533236..f31aeb8d 100644 --- a/packages/core/src/lib/routes/signin.ts +++ b/packages/core/src/lib/routes/signin.ts @@ -55,8 +55,9 @@ export async function signin( } catch (e) { const error = new SignInError(e as Error, { provider: provider.id }) logger.error(error) - url.searchParams.set("error", error.name) - url.pathname += "/error" + const code = provider.type === "email" ? "EmailSignin" : "OAuthSignin" + url.searchParams.set("error", code) + url.pathname += "/signin" return { redirect: url.toString() } } } diff --git a/packages/core/src/lib/web.ts b/packages/core/src/lib/web.ts index 5191d15e..475c35a3 100644 --- a/packages/core/src/lib/web.ts +++ b/packages/core/src/lib/web.ts @@ -33,6 +33,8 @@ export async function toInternalRequest( // TODO: url.toString() should not include action and providerId // see init.ts const url = new URL(req.url.replace(/\/$/, "")) + // FIXME: Upstream issue in Next.js, pathname segments get included as part of the query string + url.searchParams.delete("nextauth") const { pathname } = url const action = actions.find((a) => pathname.includes(a)) diff --git a/packages/core/src/providers/42-school.ts b/packages/core/src/providers/42-school.ts index 59ce0a63..76f0e519 100644 --- a/packages/core/src/providers/42-school.ts +++ b/packages/core/src/providers/42-school.ts @@ -1,13 +1,11 @@ /** - *
+ *
* Built-in 42School integration. - * TODO: SVG logo * * * *
* - * --- * @module providers/42-school */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -167,9 +165,15 @@ export interface FortyTwoProfile extends UserData, Record { /** * Add 42School login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/42-school + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import 42School from "@auth/core/providers/42-school" * @@ -179,13 +183,13 @@ export interface FortyTwoProfile extends UserData, Record { * }) * ``` * - * ## Resources + * ### Resources * * - [42School OAuth documentation](https://api.intra.42.fr/apidoc/guides/web_application_flow) * - * ## Notes + * ### Notes + * * - * * :::note * 42 returns a field on `Account` called `created_at` which is a number. See the [docs](https://api.intra.42.fr/apidoc/guides/getting_started#make-basic-requests). Make sure to add this field to your database schema, in case if you are using an [Adapter](https://authjs.dev/reference/adapters). * ::: diff --git a/packages/core/src/providers/apple.ts b/packages/core/src/providers/apple.ts index ed71dcc7..9391cf4c 100644 --- a/packages/core/src/providers/apple.ts +++ b/packages/core/src/providers/apple.ts @@ -97,7 +97,14 @@ export interface AppleProfile extends Record { } /** - * ## Setup + * ### Setup + * + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/apple + * ``` + * + * #### Configuration * * Import the provider and configure it in your **Auth.js** initialization file: * @@ -115,14 +122,14 @@ export interface AppleProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - Sign in with Apple [Overview](https://developer.apple.com/sign-in-with-apple/get-started/) * - Sign in with Apple [REST API](https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api) * - [How to retrieve](https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api/authenticating_users_with_sign_in_with_apple#3383773) the user's information from Apple ID servers * - [Learn more about OAuth](https://authjs.dev/concepts/oauth) - * ## Notes + * ### Notes * * The Apple provider comes with a [default configuration](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/apple.ts). To override the defaults for your use case, check out [customizing a built-in OAuth provider](https://authjs.dev/guides/providers/custom-provider#override-default-options). * diff --git a/packages/core/src/providers/asgardeo.ts b/packages/core/src/providers/asgardeo.ts index 2acf5514..2b8fb4db 100644 --- a/packages/core/src/providers/asgardeo.ts +++ b/packages/core/src/providers/asgardeo.ts @@ -35,7 +35,14 @@ export interface AsgardeoProfile extends Record { /** * - * ## Setup + * ### Setup + * + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/asgardeo + * ``` + * + * #### Configuration * * Import the provider and configure it in your **Auth.js** initialization file: * @@ -75,12 +82,12 @@ export interface AsgardeoProfile extends Record { * ASGARDEO_ISSUER="Copy the issuer url from the info tab here" * ``` * - * ## Resources + * ### Resources * * - [Asgardeo - Authentication Guide](https://wso2.com/asgardeo/docs/guides/authentication) * - [Learn more about OAuth](https://authjs.dev/concepts/oauth) * - * ## Notes + * ### Notes * * The Asgardeo provider comes with a [default configuration](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/asgardeo.ts). To override the defaults for your use case, check out [customizing a built-in OAuth provider](https://authjs.dev/guides/providers/custom-provider#override-default-options). * diff --git a/packages/core/src/providers/atlassian.ts b/packages/core/src/providers/atlassian.ts index 38daa260..c3f4daef 100644 --- a/packages/core/src/providers/atlassian.ts +++ b/packages/core/src/providers/atlassian.ts @@ -33,7 +33,14 @@ export interface AtlassianProfile extends Record { } /** - * ## Setup + * ### Setup + * + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/atlassian + * ``` + * + * #### Configuration * * Import the provider and configure it in your **Auth.js** initialization file: * @@ -51,11 +58,11 @@ export interface AtlassianProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Atlassian docs](https://developer.atlassian.com/server/jira/platform/oauth/) * - * ## Notes + * ### Notes * * The Atlassian provider comes with a [default configuration](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/atlassian.ts). To override the defaults for your use case, check out [customizing a built-in OAuth provider](https://authjs.dev/guides/providers/custom-provider#override-default-options). * diff --git a/packages/core/src/providers/auth0.ts b/packages/core/src/providers/auth0.ts index cf0aa8ba..956ddca3 100644 --- a/packages/core/src/providers/auth0.ts +++ b/packages/core/src/providers/auth0.ts @@ -75,7 +75,14 @@ export interface Auth0Profile extends Record { } /** - * ## Setup + * ### Setup + * + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/auth0 + * ``` + * + * #### Configuration * * Import the provider and configure it in your **Auth.js** initialization file: * @@ -93,11 +100,11 @@ export interface Auth0Profile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Auth0 docs](https://auth0.com/docs/authenticate) * - * ## Notes + * ### Notes * * The Auth0 provider comes with a [default configuration](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/auth0.ts). To override the defaults for your use case, check out [customizing a built-in OAuth provider](https://authjs.dev/guides/providers/custom-provider#override-default-options). * diff --git a/packages/core/src/providers/authentik.ts b/packages/core/src/providers/authentik.ts index 948c6a9c..767998bb 100644 --- a/packages/core/src/providers/authentik.ts +++ b/packages/core/src/providers/authentik.ts @@ -1,13 +1,11 @@ /** - *
+ *
* Built-in Authentik integration. - * TODO: SVG logo * * * *
* - * --- * @module providers/authentik */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -36,9 +34,15 @@ export interface AuthentikProfile extends Record { /** * Add Authentik login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/authentik + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Authentik from "@auth/core/providers/authentik" * @@ -47,16 +51,16 @@ export interface AuthentikProfile extends Record { * providers: [Authentik({ clientId: AUTHENTIK_CLIENT_ID, clientSecret: AUTHENTIK_CLIENT_SECRET, issuer: AUTHENTIK_ISSUER })], * }) * ``` - * + * * :::note * issuer should include the slug without a trailing slash – e.g., https://my-authentik-domain.com/application/o/My_Slug * ::: * - * ## Resources + * ### Resources * * - [Authentik OAuth documentation](https://goauthentik.io/docs/providers/oauth2) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Authentik provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. diff --git a/packages/core/src/providers/azure-ad-b2c.ts b/packages/core/src/providers/azure-ad-b2c.ts index 3d341794..c817346d 100644 --- a/packages/core/src/providers/azure-ad-b2c.ts +++ b/packages/core/src/providers/azure-ad-b2c.ts @@ -6,7 +6,6 @@ * *
* - * --- * @module providers/azure-ad-b2c */ @@ -60,7 +59,7 @@ export interface AzureADB2CProfile { * - Identity Provider Access Token * - User's Object ID * - * ## Example + * @example * * ```ts * import { Auth } from "@auth/core" @@ -75,13 +74,13 @@ export interface AzureADB2CProfile { * * --- * - * ## Resources + * ### Resources * * - [Azure Active Directory B2C documentation](https://learn.microsoft.com/en-us/azure/active-directory-b2c) * * --- * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Azure AD B2C provider is * based on the [OIDC](https://openid.net/specs/openid-connect-core-1_0.html) specification. diff --git a/packages/core/src/providers/azure-ad.ts b/packages/core/src/providers/azure-ad.ts index 9e38d39c..6ac6bbde 100644 --- a/packages/core/src/providers/azure-ad.ts +++ b/packages/core/src/providers/azure-ad.ts @@ -6,7 +6,6 @@ * *
* - * --- * @module providers/azure-ad */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -21,9 +20,15 @@ export interface AzureADProfile extends Record { /** * Add AzureAd login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/azure-ad + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import AzureAd from "@auth/core/providers/azure-ad" * @@ -33,15 +38,15 @@ export interface AzureADProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [AzureAd OAuth documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow/) * - [AzureAd OAuth apps](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app/) * - * ## Example - * + * @example + * * ### To allow specific Active Directory users access: - * + * * - In https://portal.azure.com/ search for "Azure Active Directory", and select your organization. * - Next, go to "App Registration" in the left menu, and create a new one. * - Pay close attention to "Who can use this application or access this API?" @@ -53,26 +58,26 @@ export interface AzureADProfile extends Record { * - Application (client) ID * - Directory (tenant) ID * - Client secret (value) - * + * * In `.env.local` create the following entries: - * + * * ``` * AZURE_AD_CLIENT_ID= * AZURE_AD_CLIENT_SECRET= * AZURE_AD_TENANT_ID= * ``` - * + * * That will default the tenant to use the `common` authorization endpoint. [For more details see here](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols#endpoints). - * + * * :::note * Azure AD returns the profile picture in an ArrayBuffer, instead of just a URL to the image, so our provider converts it to a base64 encoded image string and returns that instead. See: https://docs.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0#examples. The default image size is 48x48 to avoid [running out of space](https://next-auth.js.org/faq#:~:text=What%20are%20the%20disadvantages%20of%20JSON%20Web%20Tokens%3F) in case the session is saved as a JWT. * ::: - * + * * In `pages/api/auth/[...nextauth].js` find or add the `AzureAD` entries: - * + * * ```js * import AzureADProvider from "next-auth/providers/azure-ad"; - * + * * ... * providers: [ * AzureADProvider({ @@ -82,10 +87,10 @@ export interface AzureADProfile extends Record { * }), * ] * ... - * + * * ``` - * - * ## Notes + * + * ### Notes * * By default, Auth.js assumes that the AzureAd provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/battlenet.ts b/packages/core/src/providers/battlenet.ts index b06aa9fb..36712359 100644 --- a/packages/core/src/providers/battlenet.ts +++ b/packages/core/src/providers/battlenet.ts @@ -1,13 +1,11 @@ /** *
* Built-in Battle.net integration. - * TODO: SVG logo * * * *
* - * --- * @module providers/battlenet */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -25,9 +23,15 @@ export type BattleNetIssuer = /** * Add Battle.net login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/battlenet + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import BattleNet from "@auth/core/providers/battlenet" * @@ -46,11 +50,11 @@ export type BattleNetIssuer = * | "https://tw.battle.net/oauth" * ``` * - * ## Resources + * ### Resources * * - [BattleNet OAuth documentation](https://develop.battle.net/documentation/guides/using-oauth) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the BattleNet provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/beyondidentity.ts b/packages/core/src/providers/beyondidentity.ts index b26b1859..8b39a377 100644 --- a/packages/core/src/providers/beyondidentity.ts +++ b/packages/core/src/providers/beyondidentity.ts @@ -6,7 +6,6 @@ * *
* - * --- * @module providers/beyondidentity */ @@ -27,7 +26,7 @@ export interface BeyondIdentityProfile { /** * Add Beyond Identity login to your page. * - * ## Example + * @example * * ```ts * import { Auth } from "@auth/core" @@ -41,13 +40,13 @@ export interface BeyondIdentityProfile { * * --- * - * ## Resources + * ### Resources * * - [Beyond Identity Developer Docs](https://developer.beyondidentity.com/) * * --- * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the BeyondIdentity provider is * based on the [OIDC](https://openid.net/specs/openid-connect-core-1_0.html) specification. diff --git a/packages/core/src/providers/box.ts b/packages/core/src/providers/box.ts index 490fa59d..d0e55721 100644 --- a/packages/core/src/providers/box.ts +++ b/packages/core/src/providers/box.ts @@ -1,13 +1,11 @@ /** *
* Built-in Box integration. - * TODO: SVG logo * * * *
* - * --- * @module providers/box */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -15,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Box login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/box + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Box from "@auth/core/providers/box" * @@ -27,12 +31,12 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Box developers documentation](https://developer.box.com/reference/) * - [Box OAuth documentation](https://developer.box.com/guides/sso-identities-and-app-users/connect-okta-to-app-users/configure-box/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Box provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. @@ -54,7 +58,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Box(options: OAuthUserConfig> +export default function Box( + options: OAuthUserConfig> ): OAuthConfig> { return { id: "box", diff --git a/packages/core/src/providers/boxyhq-saml.ts b/packages/core/src/providers/boxyhq-saml.ts index 3bf0ca93..e53b8701 100644 --- a/packages/core/src/providers/boxyhq-saml.ts +++ b/packages/core/src/providers/boxyhq-saml.ts @@ -1,13 +1,11 @@ /** *
* Built-in BoxyHQ SAML integration. - * TODO: SVG logo * * * *
* - * --- * @module providers/boxyhq-saml */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -23,12 +21,18 @@ export interface BoxyHQSAMLProfile extends Record { * Add BoxyHQ SAML login to your page. * * BoxyHQ SAML is an open source service that handles the SAML login flow as an OAuth 2.0 flow, abstracting away all the complexities of the SAML protocol. - * - * You can deploy BoxyHQ SAML as a separate service or embed it into your app using our NPM library. [Check out the documentation for more details](https://boxyhq.com/docs/jackson/deploy) - * - * @example * - * ```js + * You can deploy BoxyHQ SAML as a separate service or embed it into your app using our NPM library. [Check out the documentation for more details](https://boxyhq.com/docs/jackson/deploy) + * + * ### Setup + * + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/boxyhq-saml + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import BoxyHQ from "@auth/core/providers/boxyhq-saml" * @@ -38,23 +42,23 @@ export interface BoxyHQSAMLProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [BoxyHQ OAuth documentation](https://example.com) * * ## Configuration - * + * * SAML login requires a configuration for every tenant of yours. One common method is to use the domain for an email address to figure out which tenant they belong to. You can also use a unique tenant ID (string) from your backend for this, typically some kind of account or organization ID. - * + * * Check out the [documentation](https://boxyhq.com/docs/jackson/saml-flow#2-saml-config-api) for more details. - * - * + * + * * On the client side you'll need to pass additional parameters `tenant` and `product` to the `signIn` function. This will allow BoxyHQL SAML to figure out the right SAML configuration and take your user to the right SAML Identity Provider to sign them in. - * + * * ```tsx * import { signIn } from "next-auth/react"; * ... - * + * * // Map your users's email to a tenant and product * const tenant = email.split("@")[1]; * const product = 'my_awesome_product'; @@ -62,12 +66,12 @@ export interface BoxyHQSAMLProfile extends Record { *
* - * --- * @module providers/cognito */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -21,9 +20,15 @@ export interface CognitoProfile extends Record { /** * Add Cognito login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/cognito + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Cognito from "@auth/core/providers/cognito" * @@ -33,13 +38,13 @@ export interface CognitoProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Cognito OAuth documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html) * - * ## Notes + * ### Notes * You need to select your AWS region to go the the Cognito dashboard. - * + * * :::tip * The issuer is a URL, that looks like this: https://cognito-idp.{region}.amazonaws.com/{PoolId} * ::: @@ -47,7 +52,7 @@ export interface CognitoProfile extends Record { * :::warning * Make sure you select all the appropriate client settings or the OAuth flow will not work. * ::: - * + * * By default, Auth.js assumes that the Cognito provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. * diff --git a/packages/core/src/providers/coinbase.ts b/packages/core/src/providers/coinbase.ts index 778d7b13..aa7a2829 100644 --- a/packages/core/src/providers/coinbase.ts +++ b/packages/core/src/providers/coinbase.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/coinbase */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Coinbase login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/coinbase + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Coinbase from "@auth/core/providers/coinbase" * @@ -26,16 +31,16 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Coinbase OAuth documentation](https://developers.coinbase.com/api/v2) * - * ## Notes + * ### Notes * * :::tip * This Provider template has a 2 hour access token to it. A refresh token is also returned. * ::: - * + * * By default, Auth.js assumes that the Coinbase provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. * @@ -56,7 +61,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Coinbase(options: OAuthUserConfig> +export default function Coinbase( + options: OAuthUserConfig> ): OAuthConfig> { return { id: "coinbase", diff --git a/packages/core/src/providers/credentials.ts b/packages/core/src/providers/credentials.ts index e8d48d00..0d92ec11 100644 --- a/packages/core/src/providers/credentials.ts +++ b/packages/core/src/providers/credentials.ts @@ -1,6 +1,6 @@ import type { CommonProviderOptions } from "./index.js" import type { Awaitable, User } from "../types.js" -import type { JSXInternal } from "preact/src/jsx.js" +import type { JSX } from "preact" /** * Besides providing type safety inside {@link CredentialsConfig.authorize} @@ -8,7 +8,7 @@ import type { JSXInternal } from "preact/src/jsx.js" * on the default sign in page. */ export interface CredentialInput - extends Partial { + extends Partial { label?: string } diff --git a/packages/core/src/providers/discord.ts b/packages/core/src/providers/discord.ts index b36c9110..3e60db73 100644 --- a/packages/core/src/providers/discord.ts +++ b/packages/core/src/providers/discord.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/discord */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -88,9 +87,15 @@ export interface DiscordProfile extends Record { /** * Add Discord login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/discord + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Discord from "@auth/core/providers/discord" * @@ -100,12 +105,12 @@ export interface DiscordProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Discord OAuth documentation](https://discord.com/developers/docs/topics/oauth2) * - [Discord OAuth apps](https://discord.com/developers/applications) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Discord provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/dropbox.ts b/packages/core/src/providers/dropbox.ts index eecc1ab8..8e88b2c4 100644 --- a/packages/core/src/providers/dropbox.ts +++ b/packages/core/src/providers/dropbox.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/dropbox */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Dropbox login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/dropbox + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Dropbox from "@auth/core/providers/dropbox" * @@ -26,11 +31,11 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Dropbox OAuth documentation](https://developers.dropbox.com/oauth-guide) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Dropbox provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. @@ -52,7 +57,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Dropbox(options: OAuthUserConfig> +export default function Dropbox( + options: OAuthUserConfig> ): OAuthConfig> { return { id: "dropbox", diff --git a/packages/core/src/providers/duende-identity-server6.ts b/packages/core/src/providers/duende-identity-server6.ts index 4246674c..be0b0992 100644 --- a/packages/core/src/providers/duende-identity-server6.ts +++ b/packages/core/src/providers/duende-identity-server6.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/duende-identity-server6 */ import type { OAuthConfig, OAuthUserConfig } from "./oauth.js" @@ -21,9 +20,15 @@ export interface DuendeISUser extends Record { /** * Add DuendeIdentityServer6 login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/duende-identity-server6 + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import DuendeIdentityServer6 from "@auth/core/providers/duende-identity-server6" * @@ -33,21 +38,21 @@ export interface DuendeISUser extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [DuendeIdentityServer6 documentation](https://docs.duendesoftware.com/identityserver/v6) * - * ## Notes + * ### Notes + * * - * * ## Demo IdentityServer - * + * * The configuration below is for the demo server at https://demo.duendesoftware.com/ - * + * * If you want to try it out, you can copy and paste the configuration below. - * + * * You can sign in to the demo service with either bob/bob or alice/alice. - * + * * ```js title=pages/api/auth/[...nextauth].js * import DuendeIDS6Provider from "next-auth/providers/duende-identity-server6" * providers: [ diff --git a/packages/core/src/providers/email.ts b/packages/core/src/providers/email.ts index 8942b758..d77c4fe2 100644 --- a/packages/core/src/providers/email.ts +++ b/packages/core/src/providers/email.ts @@ -29,7 +29,7 @@ export interface SendVerificationRequestParams { export interface EmailConfig extends CommonProviderOptions { type: "email" // TODO: Make use of https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html - server: string | SMTPTransportOptions + server?: string | SMTPTransportOptions /** @default `"Auth.js "` */ from?: string /** @@ -72,7 +72,7 @@ export interface EmailConfig extends CommonProviderOptions { * By default, we treat email addresses as all lower case, * but you can override this function to change this behavior. * - * [Documentation](https://authjs.dev/guides/providers/email#normalizing-the-e-mail-address) | [RFC 2821](https://tools.ietf.org/html/rfc2821) | [Email syntax](https://en.wikipedia.org/wiki/Email_address#Syntax) + * [Normalizing the email address](https://authjs.dev/reference/core/providers_email#normalizing-the-email-address) | [RFC 2821](https://tools.ietf.org/html/rfc2821) | [Email syntax](https://en.wikipedia.org/wiki/Email_address#Syntax) */ normalizeIdentifier?: (identifier: string) => string } @@ -287,7 +287,7 @@ export type EmailProviderType = "email" * * ## Normalizing the email address * - * By default, NextAuth.js will normalize the email address. It treats values as case-insensitive (which is technically not compliant to the [RFC 2821 spec](https://datatracker.ietf.org/doc/html/rfc2821), but in practice this causes more problems than it solves, eg. when looking up users by e-mail from databases.) and also removes any secondary email address that was passed in as a comma-separated list. You can apply your own normalization via the `normalizeIdentifier` method on the `EmailProvider`. The following example shows the default behavior: + * By default, Auth.js will normalize the email address. It treats values as case-insensitive (which is technically not compliant to the [RFC 2821 spec](https://datatracker.ietf.org/doc/html/rfc2821), but in practice this causes more problems than it solves, eg. when looking up users by e-mail from databases.) and also removes any secondary email address that was passed in as a comma-separated list. You can apply your own normalization via the `normalizeIdentifier` method on the `EmailProvider`. The following example shows the default behavior: * ```ts * EmailProvider({ * // ... @@ -301,7 +301,7 @@ export type EmailProviderType = "email" * return `${local}@${domain}` * * // You can also throw an error, which will redirect the user - * // to the error page with error=EmailSignin in the URL + * // to the sign-in page with error=EmailSignin in the URL * // if (identifier.split("@").length > 2) { * // throw new Error("Only one email allowed") * // } diff --git a/packages/core/src/providers/eveonline.ts b/packages/core/src/providers/eveonline.ts index a8309a9d..d7291996 100644 --- a/packages/core/src/providers/eveonline.ts +++ b/packages/core/src/providers/eveonline.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/eveonline */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -24,9 +23,15 @@ export interface EVEOnlineProfile extends Record { /** * Add EveOnline login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/eveonline + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import EveOnline from "@auth/core/providers/eveonline" * @@ -36,18 +41,18 @@ export interface EVEOnlineProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [EveOnline OAuth documentation](https://developers.eveonline.com/blog/article/sso-to-authenticated-calls) * - * ## Notes + * ### Notes * * :::tip * When creating your application, make sure to select `Authentication Only` as the connection type. * ::: - * + * * :::tip - * If using JWT for the session, you can add the `CharacterID` to the JWT token and session. Example: + * If using JWT for the session, you can add the `CharacterID` to the JWT and session. Example: * ```js * options: { * jwt: { diff --git a/packages/core/src/providers/facebook.ts b/packages/core/src/providers/facebook.ts index cb7bef25..1811b84f 100644 --- a/packages/core/src/providers/facebook.ts +++ b/packages/core/src/providers/facebook.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/facebook */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -26,9 +25,15 @@ export interface FacebookProfile extends Record { /** * Add Facebook login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/facebook + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Facebook from "@auth/core/providers/facebook" * @@ -38,20 +43,20 @@ export interface FacebookProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Facebook OAuth documentation](https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/) * - * ## Notes + * ### Notes * - * :::tip - * Production applications cannot use localhost URLs to sign in with Facebook. You need to use a dedicated development application in Facebook to use localhost callback URLs. + * :::tip + * Production applications cannot use localhost URLs to sign in with Facebook. You need to use a dedicated development application in Facebook to use localhost callback URLs. * ::: - * - * :::tip + * + * :::tip * Email address may not be returned for accounts created on mobile. * ::: - * + * * By default, Auth.js assumes that the Facebook provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. * diff --git a/packages/core/src/providers/faceit.ts b/packages/core/src/providers/faceit.ts index 573b3ac2..7bce6c12 100644 --- a/packages/core/src/providers/faceit.ts +++ b/packages/core/src/providers/faceit.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/faceit */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add FACEIT login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/faceit + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import FACEIT from "@auth/core/providers/faceit" * @@ -26,11 +31,11 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [FACEIT OAuth documentation](https://cdn.faceit.com/third_party/docs/FACEIT_Connect_3.0.pdf) * - * ## Notes + * ### Notes * * Grant type: Authorization Code * Scopes to have basic infos (email, nickname, guid and avatar) : openid, email, profile @@ -54,7 +59,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function FACEIT(options: OAuthUserConfig> +export default function FACEIT( + options: OAuthUserConfig> ): OAuthConfig> { return { id: "faceit", diff --git a/packages/core/src/providers/foursquare.ts b/packages/core/src/providers/foursquare.ts index d7f4a8fa..6a034fb9 100644 --- a/packages/core/src/providers/foursquare.ts +++ b/packages/core/src/providers/foursquare.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/foursquare */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add FourSquare login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/foursquare + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import FourSquare from "@auth/core/providers/foursquare" * @@ -26,16 +31,16 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [FourSquare OAuth documentation](https://developer.foursquare.com/docs/places-api/authentication/#web-applications) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the FourSquare provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. - * - * :::warning + * + * :::warning * Foursquare requires an additional apiVersion parameter in YYYYMMDD format, which essentially states "I'm prepared for API changes up to this date". * ::: * @@ -56,7 +61,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Foursquare(options: OAuthUserConfig> & { apiVersion?: string } +export default function Foursquare( + options: OAuthUserConfig> & { apiVersion?: string } ): OAuthConfig> { const { apiVersion = "20230131" } = options return { diff --git a/packages/core/src/providers/freshbooks.ts b/packages/core/src/providers/freshbooks.ts index 2d0eafe2..75dab908 100644 --- a/packages/core/src/providers/freshbooks.ts +++ b/packages/core/src/providers/freshbooks.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/freshbooks */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add FreshBooks login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/freshbooks + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import FreshBooks from "@auth/core/providers/freshbooks" * @@ -26,12 +31,12 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [FreshBooks OAuth documentation](https://www.freshbooks.com/api/authenticating-with-oauth-2-0-on-the-new-freshbooks-api ) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the FreshBooks provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. @@ -53,7 +58,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Freshbooks(options: OAuthUserConfig> +export default function Freshbooks( + options: OAuthUserConfig> ): OAuthConfig> { return { id: "freshbooks", diff --git a/packages/core/src/providers/fusionauth.ts b/packages/core/src/providers/fusionauth.ts index d14d2ed5..bdf610c1 100644 --- a/packages/core/src/providers/fusionauth.ts +++ b/packages/core/src/providers/fusionauth.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/fushionauth */ import type { OAuthConfig, OAuthUserConfig } from "./oauth.js" @@ -35,9 +34,15 @@ export interface FusionAuthProfile extends Record { /** * Add FusionAuth login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/fusionauth + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import FusionAuth from "@auth/core/providers/fusionauth" * @@ -50,11 +55,11 @@ export interface FusionAuthProfile extends Record { * If you're using multi-tenancy, you need to pass in the tenantId option to apply the proper theme. * ::: * - * ## Resources + * ### Resources * * - [FusionAuth OAuth documentation](https://fusionauth.io/docs/v1/tech/oauth/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the FusionAuth provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. @@ -62,17 +67,17 @@ export interface FusionAuthProfile extends Record { * ## Configuration * :::tip * An application can be created at https://your-fusionauth-server-url/admin/application. - * + * * For more information, follow the [FusionAuth 5-minute setup guide](https://fusionauth.io/docs/v1/tech/5-minute-setup-guide). * ::: - * + * * In the OAuth settings for your application, configure the following. - * + * * - Redirect URL * - https://localhost:3000/api/auth/callback/fusionauth * - Enabled grants * - Make sure _Authorization Code_ is enabled. - * + * * If using JSON Web Tokens, you need to make sure the signing algorithm is RS256, you can create an RS256 key pair by * going to Settings, Key Master, generate RSA and choosing SHA-256 as algorithm. After that, go to the JWT settings of * your application and select this key as Access Token signing key and Id Token signing key. diff --git a/packages/core/src/providers/github.ts b/packages/core/src/providers/github.ts index f12d6b1c..c6820a08 100644 --- a/packages/core/src/providers/github.ts +++ b/packages/core/src/providers/github.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/github */ @@ -71,8 +70,14 @@ export interface GitHubProfile { /** * Add GitHub login to your page and make requests to [GitHub APIs](https://docs.github.com/en/rest). * - * ## Example + * ### Setup * + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/github + * ``` + * + * #### Configuration * ```ts * import { Auth } from "@auth/core" * import GitHub from "@auth/core/providers/github" @@ -83,7 +88,7 @@ export interface GitHubProfile { * }) * ``` * - * ## Resources + * ### Resources * * - [GitHub - Creating an OAuth App](https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app) * - [GitHub - Authorizing OAuth Apps](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps) @@ -91,7 +96,7 @@ export interface GitHubProfile { * - [Learn more about OAuth](https://authjs.dev/concepts/oauth) * - [Source code](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/github.ts) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the GitHub provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. @@ -129,14 +134,20 @@ export default function GitHub( url: "https://api.github.com/user", async request({ tokens, provider }) { const profile = await fetch(provider.userinfo?.url as URL, { - headers: { Authorization: `Bearer ${tokens.access_token}`, 'User-Agent': 'authjs' }, + headers: { + Authorization: `Bearer ${tokens.access_token}`, + "User-Agent": "authjs", + }, }).then(async (res) => await res.json()) if (!profile.email) { // If the user does not have a public email, get another via the GitHub API // See https://docs.github.com/en/rest/users/emails#list-public-email-addresses-for-the-authenticated-user const res = await fetch("https://api.github.com/user/emails", { - headers: { Authorization: `Bearer ${tokens.access_token}`, 'User-Agent': 'authjs' }, + headers: { + Authorization: `Bearer ${tokens.access_token}`, + "User-Agent": "authjs", + }, }) if (res.ok) { diff --git a/packages/core/src/providers/gitlab.ts b/packages/core/src/providers/gitlab.ts index df8f85b8..9c5c2b88 100644 --- a/packages/core/src/providers/gitlab.ts +++ b/packages/core/src/providers/gitlab.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/gitlab */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -59,9 +58,15 @@ export interface GitLabProfile extends Record { /** * Add GitLab login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/gitlab + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import GitLab from "@auth/core/providers/gitlab" * @@ -71,19 +76,19 @@ export interface GitLabProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [GitLab OAuth documentation](https://docs.gitlab.com/ee/api/oauth2.html) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the GitLab provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. * - * :::tip + * :::tip * Enable the `read_user` option in scope if you want to save the users email address on sign up. * ::: - * + * * :::tip * * The GitLab provider comes with a [default configuration](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/gitlab.ts). diff --git a/packages/core/src/providers/google.ts b/packages/core/src/providers/google.ts index 8dc35560..b06386a9 100644 --- a/packages/core/src/providers/google.ts +++ b/packages/core/src/providers/google.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/google */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -32,9 +31,15 @@ export interface GoogleProfile extends Record { /** * Add Google login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/google + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Google from "@auth/core/providers/google" * @@ -44,32 +49,32 @@ export interface GoogleProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Google OAuth documentation](https://developers.google.com/identity/protocols/oauth2) * - [Google OAuth Configuration](https://console.developers.google.com/apis/credentials) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Google provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. * - * + * * The "Authorized redirect URIs" used when creating the credentials must include your full domain and end in the callback path. For example; - * + * * - For production: `https://{YOUR_DOMAIN}/api/auth/callback/google` * - For development: `http://localhost:3000/api/auth/callback/google` - * + * * :::warning * Google only provides Refresh Token to an application the first time a user signs in. - * + * * To force Google to re-issue a Refresh Token, the user needs to remove the application from their account and sign in again: * https://myaccount.google.com/permissions - * + * * Alternatively, you can also pass options in the `params` object of `authorization` which will force the Refresh Token to always be provided on sign in, however this will ask all users to confirm if they wish to grant your application access every time they sign in. - * + * * If you need access to the RefreshToken or AccessToken for a Google account and you are not using a database to persist user accounts, this may be something you need to do. - * + * * ```js title="pages/api/auth/[...nextauth].js" * const options = { * providers: [ @@ -87,14 +92,14 @@ export interface GoogleProfile extends Record { * ], * } * ``` - * + * * ::: - * + * * :::tip * Google also returns a `email_verified` boolean property in the OAuth profile. - * + * * You can use this property to restrict access to people with verified accounts at a particular domain. - * + * * ```js * const options = { * ... @@ -109,7 +114,7 @@ export interface GoogleProfile extends Record { * ... * } * ``` - * + * * ::: * :::tip * diff --git a/packages/core/src/providers/hubspot.ts b/packages/core/src/providers/hubspot.ts index 7f910574..5e16ce1a 100644 --- a/packages/core/src/providers/hubspot.ts +++ b/packages/core/src/providers/hubspot.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/hubspot */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -22,9 +21,15 @@ interface HubSpotProfile extends Record { /** * Add HubSpot login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/hubspot + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import HubSpot from "@auth/core/providers/hubspot" * @@ -34,11 +39,11 @@ interface HubSpotProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [HubSpot OAuth documentation](https://developers.hubspot.com/docs/api/oauth-quickstart-guide) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the HubSpot provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/identity-server4.ts b/packages/core/src/providers/identity-server4.ts index 1ca78782..4dba56db 100644 --- a/packages/core/src/providers/identity-server4.ts +++ b/packages/core/src/providers/identity-server4.ts @@ -1,13 +1,11 @@ /** *
* Built-in IdentityServer4 integration. - * TODO: SVG LOGO * * * *
* - * --- * @module providers/identity-server4 */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -15,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add IdentityServer4 login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/identity-server4 + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import IdentityServer4 from "@auth/core/providers/identity-server4" * @@ -27,11 +31,11 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [IdentityServer4 OAuth documentation](https://identityserver4.readthedocs.io/en/latest/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the IdentityServer4 provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. @@ -56,7 +60,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function IdentityServer4(options: OAuthUserConfig> +export default function IdentityServer4( + options: OAuthUserConfig> ): OAuthConfig> { return { id: "identity-server4", diff --git a/packages/core/src/providers/instagram.ts b/packages/core/src/providers/instagram.ts index de3570e8..cc8ae3aa 100644 --- a/packages/core/src/providers/instagram.ts +++ b/packages/core/src/providers/instagram.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/instagram */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Instagram login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/instagram + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Instagram from "@auth/core/providers/instagram" * @@ -26,21 +31,21 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Instagram OAuth documentation](https://developers.facebook.com/docs/instagram-basic-display-api/getting-started) * - [Instagram OAuth apps](https://developers.facebook.com/apps/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Instagram provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. * - * + * * :::warning * Email address is not returned by the Instagram API. * ::: - * + * * :::tip * Instagram display app required callback URL to be configured in your Facebook app and Facebook required you to use **https** even for localhost! In order to do that, you either need to [add an SSL to your localhost](https://www.freecodecamp.org/news/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec/) or use a proxy such as [ngrok](https://ngrok.com/docs). * ::: @@ -61,7 +66,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Instagram(config: OAuthUserConfig> +export default function Instagram( + config: OAuthUserConfig> ): OAuthConfig> { return { id: "instagram", diff --git a/packages/core/src/providers/kakao.ts b/packages/core/src/providers/kakao.ts index ed51e13f..0be793b6 100644 --- a/packages/core/src/providers/kakao.ts +++ b/packages/core/src/providers/kakao.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/kakao */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -81,9 +80,15 @@ export interface KakaoProfile extends Record { /** * Add Kakao login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/kakao + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Kakao from "@auth/core/providers/kakao" * @@ -93,15 +98,15 @@ export interface KakaoProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Kakao OAuth documentation](https://developers.kakao.com/product/kakaoLogin) * - [Kakao OAuth configuration](https://developers.kakao.com/docs/latest/en/kakaologin/common) - * + * * ## Configuration * Create a provider and a Kakao application at https://developers.kakao.com/console/app. In the settings of the app under Kakao Login, activate web app, change consent items and configure callback URL. * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Kakao provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/keycloak.ts b/packages/core/src/providers/keycloak.ts index 315be709..46e5d9ba 100644 --- a/packages/core/src/providers/keycloak.ts +++ b/packages/core/src/providers/keycloak.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/keycloak */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -38,9 +37,15 @@ export interface KeycloakProfile extends Record { /** * Add Keycloak login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/keycloak + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Keycloak from "@auth/core/providers/keycloak" * @@ -50,22 +55,22 @@ export interface KeycloakProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Keycloak OIDC documentation](https://www.keycloak.org/docs/latest/server_admin/#_oidc_clients) - * - * :::tip - * + * + * :::tip + * * Create an openid-connect client in Keycloak with "confidential" as the "Access Type". - * + * * ::: - * + * * :::note - * + * * issuer should include the realm – e.g. https://my-keycloak-domain.com/realms/My_Realm - * + * * ::: - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Keycloak provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. diff --git a/packages/core/src/providers/line.ts b/packages/core/src/providers/line.ts index 167d1924..5f60187a 100644 --- a/packages/core/src/providers/line.ts +++ b/packages/core/src/providers/line.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/line */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -26,9 +25,15 @@ export interface LineProfile extends Record { /** * Add LINE login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/line + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import LINE from "@auth/core/providers/line" * @@ -38,15 +43,15 @@ export interface LineProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [LINE Login documentation](https://developers.line.biz/en/docs/line-login/integrate-line-login/) * - [LINE app console](https://developers.line.biz/console/) - * + * * ## Configuration * Create a provider and a LINE login channel at https://developers.line.biz/console/. In the settings of the channel under LINE Login, activate web app and configure the following: Callback URL `http://localhost:3000/api/auth/callback/line` * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the LINE provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. diff --git a/packages/core/src/providers/linkedin.ts b/packages/core/src/providers/linkedin.ts index bcd75cd7..30dc9f93 100644 --- a/packages/core/src/providers/linkedin.ts +++ b/packages/core/src/providers/linkedin.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/linkedin */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -33,9 +32,15 @@ export interface LinkedInProfile extends Record { /** * Add Linkedin login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/linkedin + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Linkedin from "@auth/core/providers/linkedin" * @@ -45,12 +50,12 @@ export interface LinkedInProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Linkedin OAuth documentation](https://docs.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow) * - [Linkedin app console](https://www.linkedin.com/developers/apps/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Linkedin provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/mailchimp.ts b/packages/core/src/providers/mailchimp.ts index dc9dc319..ad72fa61 100644 --- a/packages/core/src/providers/mailchimp.ts +++ b/packages/core/src/providers/mailchimp.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/mailchimp */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Mailchimp login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/mailchimp + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Mailchimp from "@auth/core/providers/mailchimp" * @@ -26,12 +31,12 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Mailchimp OAuth documentation](https://admin.mailchimp.com/account/oauth2/client/) * - [Mailchimp documentation: Access user data](https://mailchimp.com/developer/marketing/guides/access-user-data-oauth-2/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Mailchimp provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. @@ -53,7 +58,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Mailchimp(config: OAuthUserConfig> +export default function Mailchimp( + config: OAuthUserConfig> ): OAuthConfig> { return { id: "mailchimp", diff --git a/packages/core/src/providers/mailru.ts b/packages/core/src/providers/mailru.ts index 871dd8ed..f52fb607 100644 --- a/packages/core/src/providers/mailru.ts +++ b/packages/core/src/providers/mailru.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/mailru */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Mailru login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/mailru + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Mailru from "@auth/core/providers/mailru" * @@ -26,12 +31,12 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Mailru OAuth documentation](https://o2.mail.ru/docs) * - [Mailru app console](https://o2.mail.ru/app/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Mailru provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. @@ -53,7 +58,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Mailru(config: OAuthUserConfig> +export default function Mailru( + config: OAuthUserConfig> ): OAuthConfig> { return { id: "mailru", diff --git a/packages/core/src/providers/mattermost.ts b/packages/core/src/providers/mattermost.ts index 30200e4e..d7acc2a6 100644 --- a/packages/core/src/providers/mattermost.ts +++ b/packages/core/src/providers/mattermost.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/mattermost */ import type { OAuthConfig, OAuthUserConfig } from "./oauth" @@ -70,9 +69,15 @@ export interface MattermostProfile { /** * Add Mattermost login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/mattermost + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Mattermost from "@auth/core/providers/mattermost" * @@ -82,23 +87,23 @@ export interface MattermostProfile { * }) * ``` * - * ## Resources + * ### Resources * * - [Mattermost OAuth documentation](https://example.com) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Mattermost provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. - * + * * To create your Mattermost OAuth2 app visit `http:////integrations/oauth2-apps` * * :::warning - * + * * The Mattermost provider requires the `issuer` option to be set. This is the base url of your Mattermost instance. e.g https://my-cool-server.cloud.mattermost.com - * + * * ::: - * + * * :::tip * * The Mattermost provider comes with a [default configuration](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/mattermost.ts). diff --git a/packages/core/src/providers/medium.ts b/packages/core/src/providers/medium.ts index 62092510..8094d3a6 100644 --- a/packages/core/src/providers/medium.ts +++ b/packages/core/src/providers/medium.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/medium */ @@ -15,9 +14,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Medium login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/medium + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Medium from "@auth/core/providers/medium" * @@ -27,11 +32,11 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Medium OAuth documentation](https://example.com) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Medium provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. @@ -59,7 +64,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Medium(config: OAuthUserConfig> +export default function Medium( + config: OAuthUserConfig> ): OAuthConfig> { return { id: "medium", diff --git a/packages/core/src/providers/naver.ts b/packages/core/src/providers/naver.ts index 155acb22..b5ac6d91 100644 --- a/packages/core/src/providers/naver.ts +++ b/packages/core/src/providers/naver.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/naver */ @@ -33,9 +32,15 @@ export interface NaverProfile extends Record { /** * Add Naver login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/naver + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Naver from "@auth/core/providers/naver" * @@ -45,12 +50,12 @@ export interface NaverProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Naver OAuth documentation](https://developers.naver.com/docs/login/overview/overview.md) * - [Naver OAuth documentation 2](https://developers.naver.com/docs/login/api/api.md) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Naver provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/netlify.ts b/packages/core/src/providers/netlify.ts index 57294e72..8c67dfac 100644 --- a/packages/core/src/providers/netlify.ts +++ b/packages/core/src/providers/netlify.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/netlify */ @@ -15,9 +14,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Netlify login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/netlify + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Netlify from "@auth/core/providers/netlify" * @@ -27,12 +32,12 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Netlify OAuth blog](https://www.netlify.com/blog/2016/10/10/integrating-with-netlify-oauth2/) * - [Netlify OAuth example](https://github.com/netlify/netlify-oauth-example/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Netlify provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. @@ -54,7 +59,8 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * * ::: */ -export default function Netlify(config: OAuthUserConfig> +export default function Netlify( + config: OAuthUserConfig> ): OAuthConfig> { return { id: "netlify", diff --git a/packages/core/src/providers/notion.ts b/packages/core/src/providers/notion.ts index 4d97b65f..e6ba7b47 100644 --- a/packages/core/src/providers/notion.ts +++ b/packages/core/src/providers/notion.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/notion */ @@ -60,7 +59,7 @@ const NOTION_API_VERSION = "2022-06-28" /** * Add Notion login to your page. * - * ## Example + * @example * * ```ts * import { Auth } from "@auth/core" @@ -74,15 +73,15 @@ const NOTION_API_VERSION = "2022-06-28" * * --- * - * ## Resources + * ### Resources * - [Notion Docs](https://developers.notion.com/docs) * - [Notion Authorization Docs](https://developers.notion.com/docs/authorization) * - [Notion Integrations](https://www.notion.so/my-integrations) * * --- * - * ## Notes - * You need to select "Public Integration" on the configuration page to get an `oauth_id` and `oauth_secret`. Private integrations do not provide these details. + * ### Notes + * You need to select "Public Integration" on the configuration page to get an `oauth_id` and `oauth_secret`. Private integrations do not provide these details. * You must provide a `clientId` and `clientSecret` to use this provider, as-well as a redirect URI (due to this being required by Notion endpoint to fetch tokens). * * :::tip diff --git a/packages/core/src/providers/oauth.ts b/packages/core/src/providers/oauth.ts index 8069abef..0f13eae6 100644 --- a/packages/core/src/providers/oauth.ts +++ b/packages/core/src/providers/oauth.ts @@ -52,7 +52,10 @@ interface AdvancedEndpointHandler

{ conform?: (response: Response) => Awaitable } -/** Either an URL (containing all the parameters) or an object with more granular control. */ +/** + * Either an URL (containing all the parameters) or an object with more granular control. + * @internal + */ export type EndpointHandler< P extends UrlParams, C = any, @@ -92,6 +95,8 @@ export type ProfileCallback = ( tokens: TokenSet ) => Awaitable +export type AccountCallback = (account: TokenSet) => TokenSet + export interface OAuthProviderButtonStyles { logo: string logoDark: string @@ -138,13 +143,25 @@ export interface OAuth2Config userinfo?: string | UserinfoEndpointHandler type: "oauth" /** - * Receives the profile object returned by the OAuth provider, and returns the user object. - * This will be used to create the user in the database. + * Receives the full {@link Profile} returned by the OAuth provider, and returns a subset. + * It is used to create the user in the database. + * * Defaults to: `id`, `email`, `name`, `image` * - * [Documentation](https://authjs.dev/reference/adapters/models#user) + * @see [Database Adapter: User model](https://authjs.dev/reference/adapters#user) */ profile?: ProfileCallback + /** + * Receives the full {@link TokenSet} returned by the OAuth provider, and returns a subset. + * It is used to create the account associated with a user in the database. + * + * Defaults to: `access_token` and `id_token` + * + * @see [Database Adapter: Account model](https://authjs.dev/reference/adapters#account) + * @see https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse + * @see https://www.ietf.org/rfc/rfc6749.html#section-5.1 + */ + account?: AccountCallback /** * The CSRF protection performed on the callback endpoint. * @default ["pkce"] @@ -190,7 +207,11 @@ export interface OAuth2Config options?: OAuthUserConfig } -/** TODO: Document */ +/** + * Extension of the {@link OAuth2Config}. + * + * @see https://openid.net/specs/openid-connect-core-1_0.html + */ export interface OIDCConfig extends Omit, "type" | "checks"> { type: "oidc" @@ -204,6 +225,7 @@ export type OAuthEndpointType = "authorization" | "token" | "userinfo" /** * We parsed `authorization`, `token` and `userinfo` * to always contain a valid `URL`, with the params + * @internal */ export type OAuthConfigInternal = Omit< OAuthConfig, @@ -229,7 +251,10 @@ export type OAuthConfigInternal = Omit< * */ redirectProxyUrl?: OAuth2Config["redirectProxyUrl"] -} & Pick>, "clientId" | "checks" | "profile"> +} & Pick< + Required>, + "clientId" | "checks" | "profile" | "account" + > export type OIDCConfigInternal = OAuthConfigInternal & { checks: OIDCConfig["checks"] diff --git a/packages/core/src/providers/okta.ts b/packages/core/src/providers/okta.ts index 2ab77390..3028e2d9 100644 --- a/packages/core/src/providers/okta.ts +++ b/packages/core/src/providers/okta.ts @@ -1,13 +1,11 @@ /** *

* Built-in Okta integration. - * TODO: SVG LOGO * * * *
* - * --- * @module providers/okta */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -49,9 +47,15 @@ export interface OktaProfile extends Record { /** * Add Okta login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/okta + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Okta from "@auth/core/providers/okta" * @@ -61,11 +65,11 @@ export interface OktaProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Okta OAuth documentation](https://developer.okta.com/docs/reference/api/oidc) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Okta provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. diff --git a/packages/core/src/providers/onelogin.ts b/packages/core/src/providers/onelogin.ts index 5bd059d1..64699d21 100644 --- a/packages/core/src/providers/onelogin.ts +++ b/packages/core/src/providers/onelogin.ts @@ -1,13 +1,11 @@ /** *
* Built-in OneLogin integration. - * TODO: SVG LOGO * * * *
* - * --- * @module providers/onelogin */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -15,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add OneLogin login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/onelogin + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import OneLogin from "@auth/core/providers/onelogin" * @@ -27,11 +31,11 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [OneLogin OAuth documentation](https://example.com) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the OneLogin provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. diff --git a/packages/core/src/providers/osso.ts b/packages/core/src/providers/osso.ts index 0bc0a868..d02bf6f0 100644 --- a/packages/core/src/providers/osso.ts +++ b/packages/core/src/providers/osso.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/osso */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Osso login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/osso + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Osso from "@auth/core/providers/osso" * @@ -26,7 +31,7 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * Osso is an open source service that handles SAML authentication against Identity Providers, normalizes profiles, and makes those profiles available to you in an OAuth 2.0 code grant flow. * * - If you don't yet have an Osso instance, you can use [Osso's Demo App](https://demo.ossoapp.com) for your testing purposes. For documentation on deploying an Osso instance, see https://ossoapp.com/docs/deploy/overview/ @@ -37,7 +42,7 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * See Osso's complete configuration and testing documentation at https://ossoapp.com/docs/configure/overview * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Osso provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/osu.ts b/packages/core/src/providers/osu.ts index 6c22cbb5..1e4bdd85 100644 --- a/packages/core/src/providers/osu.ts +++ b/packages/core/src/providers/osu.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/osu */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -63,9 +62,15 @@ export interface OsuProfile extends OsuUserCompact, Record { /** * Add Osu login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/osu + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Osu! from "@auth/core/providers/osu" * @@ -75,12 +80,12 @@ export interface OsuProfile extends OsuUserCompact, Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Osu OAuth documentation](https://osu.ppy.sh/docs/index.html#authentication) * - [Osu app console](https://osu.ppy.sh/home/account/edit#new-oauth-application) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Osu provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/patreon.ts b/packages/core/src/providers/patreon.ts index c59248ae..837c71dc 100644 --- a/packages/core/src/providers/patreon.ts +++ b/packages/core/src/providers/patreon.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/patreon */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -21,9 +20,15 @@ export interface PatreonProfile extends Record { /** * Add Patreon login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/patreon + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Patreon from "@auth/core/providers/patreon" * @@ -33,13 +38,13 @@ export interface PatreonProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Patreon OAuth documentation](https://docs.patreon.com/#apiv2-oauth) * - [Patreon Platform](https://www.patreon.com/portal/registration/register-clients) * - [ApiV2 Scopes](https://docs.patreon.com/#scopes) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Patreon provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/pinterest.ts b/packages/core/src/providers/pinterest.ts index 3471d75e..92670c30 100644 --- a/packages/core/src/providers/pinterest.ts +++ b/packages/core/src/providers/pinterest.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/pinterest */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -21,9 +20,15 @@ export interface PinterestProfile extends Record { /** * Add Pinterest login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/pinterest + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Pinterest from "@auth/core/providers/pinterest" * @@ -33,23 +38,23 @@ export interface PinterestProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Pinterest OAuth documentation](https://developers.pinterest.com/docs/getting-started/authentication/) * - [Pinterest app console](https://developers.pinterest.com/apps/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Pinterest provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. * - * + * * :::tip - * + * * To use in production, make sure the app has standard API access and not trial access - * + * * ::: - * + * * :::tip * * The Pinterest provider comes with a [default configuration](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/pinterest.ts). diff --git a/packages/core/src/providers/pipedrive.ts b/packages/core/src/providers/pipedrive.ts index 0c4bd35f..1d9ac8b9 100644 --- a/packages/core/src/providers/pipedrive.ts +++ b/packages/core/src/providers/pipedrive.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/pipedrive */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -49,9 +48,15 @@ export interface PipedriveProfile extends Record { /** * Add Pipedrive login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/pipedrive + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Pipedrive from "@auth/core/providers/pipedrive" * @@ -61,11 +66,11 @@ export interface PipedriveProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Pipedrive OAuth documentation](https://pipedrive.readme.io/docs/marketplace-oauth-authorization) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Pipedrive provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/reddit.ts b/packages/core/src/providers/reddit.ts index 72fd54b2..15d7e0e0 100644 --- a/packages/core/src/providers/reddit.ts +++ b/packages/core/src/providers/reddit.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/reddit */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add Reddit login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/reddit + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Reddit from "@auth/core/providers/reddit" * @@ -26,12 +31,12 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Reddit API documentation](https://www.reddit.com/dev/api/) * - [Reddit app console](https://www.reddit.com/prefs/apps/ ) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Reddit provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/salesforce.ts b/packages/core/src/providers/salesforce.ts index ec1fe419..ca6c336c 100644 --- a/packages/core/src/providers/salesforce.ts +++ b/packages/core/src/providers/salesforce.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/saleforce */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -21,9 +20,15 @@ export interface SalesforceProfile extends Record { /** * Add SaleForce login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/saleforce + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import SaleForce from "@auth/core/providers/saleforce" * @@ -33,11 +38,11 @@ export interface SalesforceProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [SaleForce OAuth documentation](https://help.salesforce.com/articleView?id=remoteaccess_authenticate.htm&type=5) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the SaleForce provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/slack.ts b/packages/core/src/providers/slack.ts index bb298718..4675c731 100644 --- a/packages/core/src/providers/slack.ts +++ b/packages/core/src/providers/slack.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/slack */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -46,9 +45,15 @@ export interface SlackProfile extends Record { /** * Add Slack login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/slack + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Slack from "@auth/core/providers/slack" * @@ -58,19 +63,19 @@ export interface SlackProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Slack OAuth documentation](https://api.slack.com/authentication https://api.slack.com/docs/sign-in-with-slack) * - [Slack app console](https://api.slack.com/apps) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Slack provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. * * :::danger * - * Slack requires that the redirect URL of your app uses https, even for local development. + * Slack requires that the redirect URL of your app uses https, even for local development. * An easy workaround for this is using a service like [ngrok](https://ngrok.com/) that creates a secure tunnel to your app, using https. Remember to set the url as `NEXTAUTH_URL` as well. * * ::: diff --git a/packages/core/src/providers/spotify.ts b/packages/core/src/providers/spotify.ts index 5247506a..a90b55fa 100644 --- a/packages/core/src/providers/spotify.ts +++ b/packages/core/src/providers/spotify.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/spotify */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -25,9 +24,15 @@ export interface SpotifyProfile extends Record { /** * Add Spotify login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/spotify + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Spotify from "@auth/core/providers/spotify" * @@ -37,12 +42,12 @@ export interface SpotifyProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Spotify OAuth documentation](https://developer.spotify.com/documentation/general/guides/authorization-guide) * - [Spotify app console](https://developer.spotify.com/dashboard/applications) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Spotify provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/strava.ts b/packages/core/src/providers/strava.ts index f7e07c00..a67ee7df 100644 --- a/packages/core/src/providers/strava.ts +++ b/packages/core/src/providers/strava.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/strava */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -21,9 +20,15 @@ export interface StravaProfile extends Record { /** * Add Strava login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/strava + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Strava from "@auth/core/providers/strava" * @@ -33,11 +38,11 @@ export interface StravaProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Strava API documentation](http://developers.strava.com/docs/reference/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Strava provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/todoist.ts b/packages/core/src/providers/todoist.ts index 22c7d3ac..d21251f4 100644 --- a/packages/core/src/providers/todoist.ts +++ b/packages/core/src/providers/todoist.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/todoist */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -24,9 +23,15 @@ interface TodoistProfile extends Record { /** * Add Todoist login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/todoist + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Todoist from "@auth/core/providers/todoist" * @@ -36,12 +41,12 @@ interface TodoistProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Todoist OAuth documentation](https://developer.todoist.com/guides/#oauth) * - [Todoist configuration](https://developer.todoist.com/appconsole.html) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Todoist provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/trakt.ts b/packages/core/src/providers/trakt.ts index 67e585da..c4bd7b83 100644 --- a/packages/core/src/providers/trakt.ts +++ b/packages/core/src/providers/trakt.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/trakt */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -29,9 +28,15 @@ export interface TraktUser extends Record { /** * Add Trakt login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/trakt + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Trakt from "@auth/core/providers/trakt" * @@ -41,15 +46,15 @@ export interface TraktUser extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Trakt OAuth documentation](https://trakt.docs.apiary.io/#reference/authentication-oauth) - * + * * If you're using the api in production by calling `api.trakt.tv`. Follow the example. If you wish to develop on Trakt's sandbox environment by calling `api-staging.trakt.tv`, change the URLs. - * + * * Start by creating an OAuth app on Trakt for production or development. Then set the Client ID and Client Secret as TRAKT_ID and TRAKT_SECRET in .env. * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Trakt provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/twitch.ts b/packages/core/src/providers/twitch.ts index af435ec4..46972671 100644 --- a/packages/core/src/providers/twitch.ts +++ b/packages/core/src/providers/twitch.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/twitch */ import type { OIDCConfig, OIDCUserConfig } from "./index.js" @@ -21,9 +20,15 @@ export interface TwitchProfile extends Record { /** * Add Twitch login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/twitch + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Twitch from "@auth/core/providers/twitch" * @@ -33,14 +38,14 @@ export interface TwitchProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Twitch app documentation](https://dev.twitch.tv/console/apps) - * - * Add the following redirect URL into the console `http:///api/auth/callback/twitch` - * * - * ## Notes + * Add the following redirect URL into the console `http:///api/auth/callback/twitch` + * + * + * ### Notes * * By default, Auth.js assumes that the Twitch provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. diff --git a/packages/core/src/providers/twitter.ts b/packages/core/src/providers/twitter.ts index 2fe769ec..c3061380 100644 --- a/packages/core/src/providers/twitter.ts +++ b/packages/core/src/providers/twitter.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/twitter */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -105,9 +104,15 @@ export interface TwitterProfile { /** * Add Twitter login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/twitter + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Twitter from "@auth/core/providers/twitter" * @@ -117,7 +122,7 @@ export interface TwitterProfile { * }) * ``` * - * ## Resources + * ### Resources * * - [Twitter App documentation](https://developer.twitter.com/en/apps) * @@ -131,19 +136,19 @@ export interface TwitterProfile { * }) * ``` * Keep in mind that although this change is easy, it changes how and with which of Twitter APIs you can interact with. Read the official Twitter OAuth 2 documentation for more details. - * - * + * + * * :::note - * - * Email is currently not supported by Twitter OAuth 2.0. + * + * Email is currently not supported by Twitter OAuth 2.0. * * ::: - * - * ## Notes * - * Twitter is currently the only built-in provider using the OAuth 1.0 spec. + * ### Notes + * + * Twitter is currently the only built-in provider using the OAuth 1.0 spec. * This means that you won't receive an `access_token` or `refresh_token`, but an `oauth_token` and `oauth_token_secret` respectively. Remember to add these to your database schema, in case if you are using an [Adapter](https://authjs.dev/reference/adapters). - * + * * :::tip * * You must enable the "Request email address from users" option in your app permissions if you want to obtain the users email address. diff --git a/packages/core/src/providers/united-effects.ts b/packages/core/src/providers/united-effects.ts index 8e74c554..f8338aac 100644 --- a/packages/core/src/providers/united-effects.ts +++ b/packages/core/src/providers/united-effects.ts @@ -1,15 +1,13 @@ /** *
* Built-in United Effects integration. - * TODO: SVG LOGO * * * *
-* -* --- -* @module providers/united-effects -*/ + * + * @module providers/united-effects + */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" export interface UnitedEffectsProfile extends Record { sub: string @@ -18,9 +16,15 @@ export interface UnitedEffectsProfile extends Record { /** * Add United Effects login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/united-effects + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import UnitedEffects from "@auth/core/providers/united-effects" * @@ -30,11 +34,11 @@ export interface UnitedEffectsProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [UnitedEffects Auth.js documentation](https://docs.unitedeffects.com/integrations/nextauthjs)", * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the UnitedEffects provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. diff --git a/packages/core/src/providers/vk.ts b/packages/core/src/providers/vk.ts index ffab573d..9330c82e 100644 --- a/packages/core/src/providers/vk.ts +++ b/packages/core/src/providers/vk.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/vk */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -295,9 +294,15 @@ export interface VkProfile { /** * Add VK login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/vk + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import VK from "@auth/core/providers/vk" * @@ -307,12 +312,12 @@ export interface VkProfile { * }) * ``` * - * ## Resources + * ### Resources * * - [VK API documentation](https://vk.com/dev/first_guide) * - [VK App configuration](https://vk.com/apps?act=manage) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the VK provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/wikimedia.ts b/packages/core/src/providers/wikimedia.ts index f1c8bf32..3f4d8db2 100644 --- a/packages/core/src/providers/wikimedia.ts +++ b/packages/core/src/providers/wikimedia.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/wikimedia */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -164,13 +163,18 @@ export interface WikimediaProfile extends Record { email: string } - /** * Add Wikimedia login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/wikimedia + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Wikimedia from "@auth/core/providers/wikimedia" * @@ -180,30 +184,30 @@ export interface WikimediaProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Wikimedia OAuth documentation](https://www.mediawiki.org/wiki/Extension:OAuth) * * ## Configuration steps * - Go to and accept the Consumer Registration doc: https://meta.wikimedia.org/wiki/Special:OAuthConsumerRegistration - * - Request a new OAuth 2.0 consumer to get the `clientId` and `clientSecret`: https://meta.wikimedia.org/wiki/Special:OAuthConsumerRegistration/propose/oauth2 + * - Request a new OAuth 2.0 consumer to get the `clientId` and `clientSecret`: https://meta.wikimedia.org/wiki/Special:OAuthConsumerRegistration/propose/oauth2 * - Add the following redirect URL into the console: `http:///api/auth/callback/wikimedia` - * - Do not check the box next to This consumer is only for __your username__ + * - Do not check the box next to This consumer is only for __your username__ * - Unless you explicitly need a larger scope, feel free to select the radio button labelled User identity verification only - no ability to read pages or act on the users behalf. - * + * * After registration, you can initially test your application only with your own Wikimedia account. * You may have to wait several days for the application to be approved for it to be used by everyone. * - * ## Notes + * ### Notes * This provider also supports all Wikimedia projects: * - Wikipedia * - Wikidata * - Wikibooks * - Wiktionary * - etc.. - * + * * Please be aware that Wikimedia accounts do not have to have an associated email address. So you may want to add check if the user has an email address before allowing them to login. - * + * * By default, Auth.js assumes that the Wikimedia provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. * diff --git a/packages/core/src/providers/wordpress.ts b/packages/core/src/providers/wordpress.ts index 2979732c..21cffb3d 100644 --- a/packages/core/src/providers/wordpress.ts +++ b/packages/core/src/providers/wordpress.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/wordpress */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add WordPress login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/wordpress + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import WordPress from "@auth/core/providers/wordpress" * @@ -26,11 +31,11 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [WordPress OAuth documentation](https://developer.wordpress.com/docs/oauth2/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the WordPress provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/workos.ts b/packages/core/src/providers/workos.ts index f0f5347e..3c713416 100644 --- a/packages/core/src/providers/workos.ts +++ b/packages/core/src/providers/workos.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/workos */ import type { OAuthConfig, OAuthUserConfig } from "./index.js" @@ -35,9 +34,15 @@ export interface WorkOSProfile extends Record { /** * Add WorkOS login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/workos + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import WorkOS from "@auth/core/providers/workos" * @@ -47,19 +52,19 @@ export interface WorkOSProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [WorkOS SSO OAuth documentation](https://workos.com/docs/reference/sso) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the WorkOS provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. - * - * WorkOS is not an identity provider itself, but, rather, a bridge to multiple single sign-on (SSO) providers. + * + * WorkOS is not an identity provider itself, but, rather, a bridge to multiple single sign-on (SSO) providers. * As a result, we need to make some additional changes to authenticate users using WorkOS. - * - * In order to sign a user in using WorkOS, we need to specify which WorkOS Connection to use. + * + * In order to sign a user in using WorkOS, we need to specify which WorkOS Connection to use. * A common way to do this is to collect the user's email address and extract the domain. This can be done using a custom login page. * To add a custom login page, you can use the `pages` option: * ```js title="pages/api/auth/[...nextauth].js" @@ -67,15 +72,15 @@ export interface WorkOSProfile extends Record { * signIn: "/auth/signin", * } * ``` - * We can then add a custom login page that displays an input where the user can enter their email address. + * We can then add a custom login page that displays an input where the user can enter their email address. * We then extract the domain from the user's email address and pass it to the `authorizationParams` parameter on the `signIn` function: * ```js title="pages/auth/signin.js" * import { useState } from "react" * import { getProviders, signIn } from "next-auth/react" - * + * * export default function SignIn({ providers }) { * const [email, setEmail] = useState("") - * + * * return ( * <> * {Object.values(providers).map((provider) => { @@ -100,7 +105,7 @@ export interface WorkOSProfile extends Record { * * ) * } - * + * * return ( *
*
* - * --- * @module providers/yandex */ @@ -45,7 +44,7 @@ export interface YandexProfile { * ID of the Yandex user's profile picture. * Format for downloading user avatars: `https://avatars.yandex.net/get-yapic//` * @example "https://avatars.yandex.net/get-yapic/31804/BYkogAC6AoB17bN1HKRFAyKiM4-1/islands-200" - * Available sizes: + * Available sizes: * `islands-small`: 28×28 pixels. * `islands-34`: 34×34 pixels. * `islands-middle`: 42×42 pixels. @@ -99,7 +98,7 @@ export interface YandexProfile { * }) * ``` * - * ## Resources + * ### Resources * * - [Yandex - Creating an OAuth app](https://yandex.com/dev/id/doc/en/register-client#create) * - [Yandex - Manage OAuth apps](https://oauth.yandex.com/) diff --git a/packages/core/src/providers/zitadel.ts b/packages/core/src/providers/zitadel.ts index 94af1c03..2f8536f3 100644 --- a/packages/core/src/providers/zitadel.ts +++ b/packages/core/src/providers/zitadel.ts @@ -6,14 +6,13 @@ * * * - * --- * @module providers/zitadel */ import type { OIDCConfig, OAuthUserConfig } from "./index.js" /** - * The returned user profile from ZITADEL when using the profile callback. See the standard claims reference [here](https://zitadel.com/docs/apis/openidoauth/claims#standard-claims). + * The returned user profile from ZITADEL when using the profile callback. See the standard claims reference [here](https://zitadel.com/docs/apis/openidoauth/claims#standard-claims). * If you need access to ZITADEL APIs or need additional information, make sure to add the corresponding scopes. */ export interface ZitadelProfile extends Record { @@ -43,9 +42,15 @@ export interface ZitadelProfile extends Record { /** * Add ZITADEL login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/zitadel + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import ZITADEL from "@auth/core/providers/zitadel" * @@ -55,19 +60,19 @@ export interface ZitadelProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * - [ZITADEL OpenID Endpoints](https://zitadel.com/docs/apis/openidoauth/endpoints) * - [ZITADEL recommended OAuth Flows](https://docs.zitadel.com/docs/guides/integrate/oauth-recommended-flows) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the ZITADEL provider is * based on the [Open ID Connect](https://openid.net/specs/openid-connect-core-1_0.html) specification. - * + * * The Redirect URIs used when creating the credentials must include your full domain and end in the callback path. For example: * - For production: `https://{YOUR_DOMAIN}/api/auth/callback/zitadel` * - For development: `http://localhost:3000/api/auth/callback/zitadel` - * + * * Make sure to enable dev mode in ZITADEL console to allow redirects for local development. * * :::tip diff --git a/packages/core/src/providers/zoho.ts b/packages/core/src/providers/zoho.ts index 09c95148..18accca9 100644 --- a/packages/core/src/providers/zoho.ts +++ b/packages/core/src/providers/zoho.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/zoho */ @@ -14,9 +13,15 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" /** * Add ZOHO login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/zoho + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import ZOHO from "@auth/core/providers/zoho" * @@ -26,12 +31,12 @@ import type { OAuthConfig, OAuthUserConfig } from "./index.js" * }) * ``` * - * ## Resources + * ### Resources * * - [Zoho OAuth 2.0 Integration Guide](https://www.zoho.com/accounts/protocol/oauth/web-server-applications.html) * - [Zoho API Console](https://api-console.zoho.com) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the ZOHO provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/providers/zoom.ts b/packages/core/src/providers/zoom.ts index 46f4336e..57ecdbae 100644 --- a/packages/core/src/providers/zoom.ts +++ b/packages/core/src/providers/zoom.ts @@ -6,7 +6,6 @@ * * * - * --- * @module providers/zoom */ @@ -47,9 +46,15 @@ export interface ZoomProfile extends Record { /** * Add Zoom login to your page. * - * @example + * ### Setup * - * ```js + * #### Callback URL + * ``` + * https://example.com/api/auth/callback/zoom + * ``` + * + * #### Configuration + *```js * import Auth from "@auth/core" * import Zoom from "@auth/core/providers/zoom" * @@ -59,11 +64,11 @@ export interface ZoomProfile extends Record { * }) * ``` * - * ## Resources + * ### Resources * * - [Zoom OAuth 2.0 Integration Guide](https://developers.zoom.us/docs/integrations/oauth/) * - * ## Notes + * ### Notes * * By default, Auth.js assumes that the Zoom provider is * based on the [OAuth 2](https://www.rfc-editor.org/rfc/rfc6749.html) specification. diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 8d5a5b43..5933d9ea 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -116,16 +116,58 @@ export interface Account extends Partial { providerAccountId: string /** Provider's type for this account */ type: ProviderType - /** id of the user this account belongs to */ + /** + * id of the user this account belongs to + * + * @see https://authjs.dev/reference/adapters#user + */ userId?: string + /** + * Calculated value based on {@link OAuth2TokenEndpointResponse.expires_in}. + * + * It is the absolute timestamp (in seconds) when the {@link OAuth2TokenEndpointResponse.access_token} expires. + * + * This value can be used for implementing token rotation together with {@link OAuth2TokenEndpointResponse.refresh_token}. + * + * @see https://authjs.dev/guides/basics/refresh-token-rotation#database-strategy + * @see https://www.rfc-editor.org/rfc/rfc6749#section-5.1 + */ + expires_at?: number } -/** The OAuth profile returned from your provider */ +/** + * The user info returned from your OAuth provider. + * + * @see https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims + */ export interface Profile { - sub?: string | null - name?: string | null - email?: string | null - image?: string | null + sub: string + name?: string + given_name?: string + family_name?: string + middle_name?: string + nickname?: string + preferred_username?: string + profile?: string + picture?: string + website?: string + email?: string + email_verified?: boolean + gender?: string + birthdate?: string + zoneinfo?: string + locale?: string + phone_number?: string + updated_at?: number + address?: { + formatted?: string + street_address?: string + locality?: string + region?: string + postal_code?: string + country?: string + } + [claim: string]: unknown } /** [Documentation](https://authjs.dev/guides/basics/callbacks) */ @@ -262,7 +304,7 @@ export interface EventCallbacks { /** * The message object will contain one of these depending on * if you use JWT or database persisted sessions: - * - `token`: The JWT token for this session. + * - `token`: The JWT for this session. * - `session`: The session object from your adapter that is being ended. */ signOut: ( @@ -280,7 +322,7 @@ export interface EventCallbacks { /** * The message object will contain one of these depending on * if you use JWT or database persisted sessions: - * - `token`: The JWT token for this session. + * - `token`: The JWT for this session. * - `session`: The session object from your adapter. */ session: (message: { session: Session; token: JWT }) => Awaitable @@ -385,15 +427,40 @@ export type InternalProvider = (T extends "oauth" callbackUrl: string } +/** + * Supported actions by Auth.js. Each action map to a REST API endpoint. + * Some actions have a `GET` and `POST` variant, depending on if the action + * changes the state of the server. + * + * - **`"callback"`**: + * - **`GET`**: Handles the callback from an [OAuth provider](https://authjs.dev/reference/core/providers_oauth). + * - **`POST`**: Handles the callback from a [Credentials provider](https://authjs.dev/reference/core/providers_credentials). + * - **`"csrf"`**: Returns the raw CSRF token, which is saved in a cookie (encrypted). + * It is used for CSRF protection, implementing the [double submit cookie](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie) technique. + * :::note + * Some frameworks have built-in CSRF protection and can therefore disable this action. In this case, the corresponding endpoint will return a 404 response. Read more at [`skipCSRFCheck`](https://authjs.dev/reference/core#skipcsrfcheck). + * _⚠ We don't recommend manually disabling CSRF protection, unless you know what you're doing._ + * ::: + * - **`"error"`**: Renders the built-in error page. + * - **`"providers"`**: Returns a client-safe list of all configured providers. + * - **`"session"`**: Returns the user's session if it exists, otherwise `null`. + * - **`"signin"`**: + * - **`GET`**: Renders the built-in sign-in page. + * - **`POST`**: Initiates the sign-in flow. + * - **`"signout"`**: + * - **`GET`**: Renders the built-in sign-out page. + * - **`POST`**: Initiates the sign-out flow. This will invalidate the user's session (deleting the cookie, and if there is a session in the database, it will be deleted as well). + * - **`"verify-request"`**: Renders the built-in verification request page. + */ export type AuthAction = + | "callback" + | "csrf" + | "error" | "providers" | "session" - | "csrf" | "signin" | "signout" - | "callback" | "verify-request" - | "error" /** @internal */ export interface RequestInternal { diff --git a/packages/frameworks-nextjs/package.json b/packages/frameworks-nextjs/package.json deleted file mode 100644 index f793ca22..00000000 --- a/packages/frameworks-nextjs/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@auth/nextjs", - "version": "0.0.0-6f96004d", - "description": "Authentication for Next.js.", - "keywords": [ - "authentication", - "authjs", - "jwt", - "nextjs", - "oauth", - "oidc", - "passwordless", - "react" - ], - "homepage": "https://nextjs.authjs.dev", - "repository": "https://github.com/nextauthjs/next-auth.git", - "author": "Balázs Orbán ", - "scripts": { - "dev": "tsc -w", - "clean": "rm -rf *.js *.d.ts lib", - "build": "pnpm clean && tsc" - }, - "devDependencies": { - "@types/react": "18.0.37", - "typescript": "^4", - "next": "13.3.0" - }, - "dependencies": { - "@auth/core": "workspace:*" - }, - "peerDependencies": { - "next": "^13.3.0", - "react": "^18.2.0" - }, - "type": "module", - "types": "./index.d.ts", - "files": [ - "*.js", - "*.d.ts", - "lib", - "src" - ], - "exports": { - ".": { - "types": "./index.d.ts", - "import": "./index.js" - }, - "./client": { - "types": "./client.d.ts", - "import": "./client.js" - }, - "./package.json": "./package.json" - } -} diff --git a/packages/frameworks-nextjs/src/index.ts b/packages/frameworks-nextjs/src/index.ts deleted file mode 100644 index 15cdeea5..00000000 --- a/packages/frameworks-nextjs/src/index.ts +++ /dev/null @@ -1,149 +0,0 @@ -/** - * ## Signing in and signing out - * - * - * The App Router embraces Server Actions that can be leveraged to decrease the amount of JavaScript sent to the browser. - * - * :::info - * Next.js Server Actions is **under development**. In the future, Next.js Auth will integrate with Server Actions and provide first-party APIs. - * The below is a workaround until then. - * ::: - * - * ```ts title="app/auth-components.tsx" - * import { auth } from "../auth" - * import { cookies, headers } from "next/headers" - * - * function CSRF() { - * const value = cookies().get("next-auth.csrf-token")?.value.split("|")[0] - * return - * } - * - * export function SignIn({ provider, ...props }: any) { - * return ( - *
- *
- - ) - } - return ( - <> - Not signed in
- - - ) -} -``` - -### Share/configure session state - -Use the `` to allow instances of `useSession()` to share the session object across components. It also takes care of keeping the session updated and synced between tabs/windows. - -```jsx title="pages/_app.js" -import { SessionProvider } from "next-auth/react" - -export default function App({ - Component, - pageProps: { session, ...pageProps }, -}) { - return ( - - - - ) -} -``` - -## Security - -If you think you have found a vulnerability (or not sure) in NextAuth.js or any of the related packages (i.e. Adapters), we ask you to have a read of our [Security Policy](https://github.com/nextauthjs/next-auth/blob/main/SECURITY.md) to reach out responsibly. Please do not open Pull Requests/Issues/Discussions before consulting with us. - -## Acknowledgments - -[NextAuth.js is made possible thanks to all of its contributors.](https://next-auth.js.org/contributors) - - - - -
- -
- -### Support - -We're happy to announce we've recently created an [OpenCollective](https://opencollective.com/nextauth) for individuals and companies looking to contribute financially to the project! - - - - - - - - - - - - - - -
- - Vercel Logo -
-
Vercel

- 🥉 Bronze Financial Sponsor
☁️ Infrastructure Support
-
- - Prisma Logo -
-
Prisma

- 🥉 Bronze Financial Sponsor -
- - Clerk Logo -
-
Clerk

- 🥉 Bronze Financial Sponsor -
- - Lowdefy Logo -
-
Lowdefy

- 🥉 Bronze Financial Sponsor -
- - WorkOS Logo -
-
WorkOS

- 🥉 Bronze Financial Sponsor -
- - Checkly Logo -
-
Checkly

- ☁️ Infrastructure Support -
- - superblog Logo -
-
superblog

- ☁️ Infrastructure Support -
-
- - -## Contributing - -We're open to all community contributions! If you'd like to contribute in any way, please first read -our [Contributing Guide](https://github.com/nextauthjs/.github/blob/main/CONTRIBUTING.md). - -## License - -ISC diff --git a/packages/next-auth/config/babel.config.js b/packages/next-auth/config/babel.config.js deleted file mode 100644 index 965aef77..00000000 --- a/packages/next-auth/config/babel.config.js +++ /dev/null @@ -1,62 +0,0 @@ -// @ts-check -// We aim to have the same support as Next.js -// https://nextjs.org/docs/getting-started#system-requirements -// https://nextjs.org/docs/basic-features/supported-browsers-features - -/** @type {import("@babel/core").ConfigFunction} */ -module.exports = (api) => { - const isTest = api.env("test") - if (isTest) { - return { - presets: [ - "@babel/preset-env", - ["@babel/preset-react", { runtime: "automatic" }], - ["@babel/preset-typescript", { isTSX: true, allExtensions: true }], - ], - } - } - return { - presets: [ - ["@babel/preset-env", { targets: { node: 12 } }], - "@babel/preset-typescript", - ], - plugins: [ - "@babel/plugin-proposal-optional-catch-binding", - "@babel/plugin-transform-runtime", - ], - ignore: [ - "../src/**/__tests__/**", - "../src/adapters.ts", - "../src/providers/oauth-types.ts", - ], - comments: false, - overrides: [ - { - test: [ - "../src/react/index.tsx", - "../src/utils/logger.ts", - "../src/core/errors.ts", - "../src/client/**", - ], - presets: [ - ["@babel/preset-env", { targets: { ie: 11 } }], - ["@babel/preset-react", { runtime: "automatic" }], - ], - }, - { - test: ["../src/core/pages/*.tsx"], - presets: ["preact"], - plugins: [ - [ - "jsx-pragmatic", - { - module: "preact", - export: "h", - import: "h", - }, - ], - ], - }, - ], - } -} diff --git a/packages/next-auth/config/generate-providers.js b/packages/next-auth/config/generate-providers.js deleted file mode 100644 index edd3c4fd..00000000 --- a/packages/next-auth/config/generate-providers.js +++ /dev/null @@ -1,18 +0,0 @@ -const path = require("path") -const fs = require("fs") - -const providersPath = path.join(process.cwd(), "src/providers") - -const files = fs.readdirSync(providersPath, "utf8") - -const providers = files.map((file) => { - const strippedProviderName = file.substring(0, file.indexOf(".")) - return `"${strippedProviderName}"` -}) - -const result = ` -// THIS FILE IS AUTOGENERATED. DO NOT EDIT. -export type OAuthProviderType = - | ${providers.join("\n | ")}` - -fs.writeFileSync(path.join(providersPath, "oauth-types.ts"), result) diff --git a/packages/next-auth/config/jest-setup.js b/packages/next-auth/config/jest-setup.js deleted file mode 100644 index 54051de0..00000000 --- a/packages/next-auth/config/jest-setup.js +++ /dev/null @@ -1,3 +0,0 @@ -import "regenerator-runtime/runtime" -import "@testing-library/jest-dom" -import "whatwg-fetch" diff --git a/packages/next-auth/config/jest.config.js b/packages/next-auth/config/jest.config.js deleted file mode 100644 index 951c929d..00000000 --- a/packages/next-auth/config/jest.config.js +++ /dev/null @@ -1,43 +0,0 @@ -const swcConfig = require("./swc.config") - -/** @type {import('jest').Config} */ -module.exports = { - projects: [ - { - displayName: "core", - testMatch: ["/tests/**/*.test.ts"], - rootDir: ".", - transform: { - "\\.(js|jsx|ts|tsx)$": ["@swc/jest", swcConfig], - }, - coveragePathIgnorePatterns: ["tests"], - testEnvironment: "@edge-runtime/jest-environment", - transformIgnorePatterns: ["node_modules/(?!uuid)/"], - /** @type {import("@edge-runtime/vm").EdgeVMOptions} */ - testEnvironmentOptions: { - codeGeneration: { - strings: true, - }, - }, - }, - { - displayName: "client", - testMatch: ["/src/client/**/*.test.js"], - setupFilesAfterEnv: ["./config/jest-setup.js"], - rootDir: ".", - transform: { - "\\.(js|jsx|ts|tsx)$": ["@swc/jest", swcConfig], - }, - testEnvironment: "jsdom", - coveragePathIgnorePatterns: ["__tests__"], - }, - ], - watchPlugins: [ - "jest-watch-typeahead/filename", - "jest-watch-typeahead/testname", - ], - collectCoverage: true, - coverageDirectory: "../coverage", - coverageReporters: ["html", "text-summary"], - collectCoverageFrom: ["src/**/*.(js|jsx|ts|tsx)"], -} diff --git a/packages/next-auth/config/postcss.config.js b/packages/next-auth/config/postcss.config.js deleted file mode 100644 index c9110b1c..00000000 --- a/packages/next-auth/config/postcss.config.js +++ /dev/null @@ -1,7 +0,0 @@ -module.exports = { - plugins: [ - require('autoprefixer'), - require('postcss-nested'), - require('cssnano')({ preset: 'default' }) - ] -} diff --git a/packages/next-auth/config/swc.config.js b/packages/next-auth/config/swc.config.js deleted file mode 100644 index 5aeeac2d..00000000 --- a/packages/next-auth/config/swc.config.js +++ /dev/null @@ -1,18 +0,0 @@ -/** @type {import("@swc/core").Config} */ -module.exports = { - jsc: { - parser: { - syntax: "typescript", - tsx: true, - }, - transform: { - react: { - runtime: "automatic", - pragma: "React.createElement", - pragmaFrag: "React.Fragment", - throwIfNamespace: true, - useBuiltins: true, - }, - }, - }, -} diff --git a/packages/next-auth/config/wrap-css.js b/packages/next-auth/config/wrap-css.js deleted file mode 100644 index d59d7892..00000000 --- a/packages/next-auth/config/wrap-css.js +++ /dev/null @@ -1,17 +0,0 @@ -// Serverless target in Next.js does not work if you try to read in files at runtime -// that are not JavaScript or JSON (e.g. CSS files). -// https://github.com/nextauthjs/next-auth/issues/281 -// -// To work around this issue, this script is a manual step that wraps CSS in a -// JavaScript file that has the compiled CSS embedded in it, and exports only -// a function that returns the CSS as a string. -const fs = require("fs") -const path = require("path") - -const pathToCss = path.join(__dirname, "../css/index.css") -const css = fs.readFileSync(pathToCss, "utf8") -const cssWithEscapedQuotes = css.replace(/"/gm, '\\"') - -const js = `module.exports = function() { return "${cssWithEscapedQuotes}" }` -const pathToCssJs = path.join(__dirname, "../css/index.js") -fs.writeFileSync(pathToCssJs, js) diff --git a/packages/next-auth/package.json b/packages/next-auth/package.json index 0394fa50..e5f951c6 100644 --- a/packages/next-auth/package.json +++ b/packages/next-auth/package.json @@ -2,7 +2,7 @@ "name": "next-auth", "version": "4.22.1", "description": "Authentication for Next.js", - "homepage": "https://next-auth.js.org", + "homepage": "https://nextjs.authjs.dev", "repository": "https://github.com/nextauthjs/next-auth.git", "author": "Iain Collins ", "contributors": [ @@ -11,9 +11,6 @@ "Lluis Agusti ", "Thang Huu Vu " ], - "main": "index.js", - "module": "index.js", - "types": "index.d.ts", "keywords": [ "react", "nodejs", @@ -26,104 +23,59 @@ "oidc", "nextauth" ], + "type": "module", + "types": "./index.d.ts", "exports": { - ".": "./index.js", - "./jwt": "./jwt/index.js", - "./react": "./react/index.js", - "./core": "./core/index.js", - "./next": "./next/index.js", - "./middleware": "./middleware.js", - "./client/_utils": "./client/_utils.js", - "./providers/*": "./providers/*.js" + ".": { + "types": "./index.d.ts", + "import": "./index.js" + }, + "./adapters": { + "types": "./adapters.d.ts" + }, + "./jwt": { + "types": "./jwt.d.ts", + "import": "./jwt.js" + }, + "./middleware": { + "types": "./middleware.d.ts", + "import": "./middleware.js" + }, + "./next": { + "types": "./next.d.ts", + "import": "./next.js" + }, + "./providers": { + "types": "./providers.d.ts" + }, + "./react": { + "types": "./react.d.ts", + "import": "./react.js" + }, + "./package.json": "./package.json" }, "scripts": { - "build": "pnpm clean && pnpm build:js && pnpm build:css", - "build:js": "pnpm clean && pnpm generate-providers && pnpm tsc --project tsconfig.json && babel --config-file ./config/babel.config.js src --out-dir . --extensions \".tsx,.ts,.js,.jsx\"", - "clean": "rm -rf coverage client css utils providers core jwt react next index.d.ts index.js adapters.d.ts middleware.d.ts middleware.js", - "build:css": "postcss --config config/postcss.config.js src/**/*.css --base src --dir . && node config/wrap-css.js", - "dev": "pnpm clean && pnpm generate-providers && concurrently \"pnpm watch:css\" \"pnpm watch:ts\"", - "watch:ts": "pnpm tsc --project tsconfig.dev.json", - "watch:css": "postcss --config config/postcss.config.js --watch src/**/*.css --base src --dir .", - "test": "jest --config ./config/jest.config.js", - "prepublishOnly": "pnpm build", - "generate-providers": "node ./config/generate-providers.js", - "lint": "eslint src config tests" + "dev": "tsc -w", + "clean": "rm -rf *.js *.d.ts lib", + "build": "pnpm clean && tsc" }, "files": [ - "client", - "core", - "css", - "jwt", + "*.js", + "*.d.ts", "lib", - "next", - "providers", - "react", - "src", - "utils", - "*.d.ts*", - "*.js" + "src" ], + "devDependencies": { + "@types/react": "18.0.37", + "typescript": "^4", + "next": "13.3.3" + }, "license": "ISC", "dependencies": { - "@babel/runtime": "^7.20.13", - "@panva/hkdf": "^1.0.2", - "cookie": "^0.5.0", - "jose": "^4.11.4", - "oauth": "^0.9.15", - "openid-client": "^5.4.0", - "preact": "^10.6.3", - "preact-render-to-string": "^5.1.19", - "uuid": "^8.3.2" + "@auth/core": "workspace:*" }, "peerDependencies": { - "next": "^12.2.5 || ^13", - "nodemailer": "^6.6.5", - "react": "^17.0.2 || ^18", - "react-dom": "^17.0.2 || ^18" - }, - "peerDependenciesMeta": { - "nodemailer": { - "optional": true - } - }, - "devDependencies": { - "@babel/cli": "^7.17.10", - "@babel/core": "^7.18.2", - "@babel/plugin-proposal-optional-catch-binding": "^7.16.7", - "@babel/plugin-transform-runtime": "^7.18.2", - "@babel/preset-env": "^7.18.2", - "@babel/preset-react": "^7.17.12", - "@babel/preset-typescript": "^7.17.12", - "@edge-runtime/jest-environment": "1.1.0-beta.35", - "@next-auth/tsconfig": "workspace:*", - "@swc/core": "^1.2.198", - "@swc/jest": "^0.2.21", - "@testing-library/dom": "^8.13.0", - "@testing-library/jest-dom": "^5.16.4", - "@testing-library/react": "^13.3.0", - "@testing-library/react-hooks": "^8.0.0", - "@testing-library/user-event": "^14.2.0", - "@types/jest": "^28.1.3", - "@types/node": "^17.0.42", - "@types/nodemailer": "^6.4.4", - "@types/oauth": "^0.9.1", - "@types/react": "18.0.37", - "@types/react-dom": "^18.0.6", - "autoprefixer": "^10.4.7", - "babel-plugin-jsx-pragmatic": "^1.0.2", - "babel-preset-preact": "^2.0.0", - "concurrently": "^7", - "cssnano": "^5.1.11", - "jest": "^28.1.1", - "jest-environment-jsdom": "^28.1.1", - "jest-watch-typeahead": "^1.1.0", - "msw": "^0.42.3", - "next": "13.3.0", - "postcss": "^8.4.14", - "postcss-cli": "^9.1.0", - "postcss-nested": "^5.0.6", - "react": "^18", - "react-dom": "^18", - "whatwg-fetch": "^3.6.2" + "next": "^13.3.3", + "react": "^18.2.0" } } diff --git a/packages/next-auth/provider-logos/apple-dark.svg b/packages/next-auth/provider-logos/apple-dark.svg deleted file mode 100644 index 60b1a36a..00000000 --- a/packages/next-auth/provider-logos/apple-dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - Apple icon - - diff --git a/packages/next-auth/provider-logos/apple.svg b/packages/next-auth/provider-logos/apple.svg deleted file mode 100644 index 4d08570d..00000000 --- a/packages/next-auth/provider-logos/apple.svg +++ /dev/null @@ -1,4 +0,0 @@ - - Apple icon - - diff --git a/packages/next-auth/provider-logos/atlassian-dark.svg b/packages/next-auth/provider-logos/atlassian-dark.svg deleted file mode 100644 index 9c41c735..00000000 --- a/packages/next-auth/provider-logos/atlassian-dark.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/packages/next-auth/provider-logos/atlassian.svg b/packages/next-auth/provider-logos/atlassian.svg deleted file mode 100644 index 37a5e7fd..00000000 --- a/packages/next-auth/provider-logos/atlassian.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/provider-logos/auth0-dark.svg b/packages/next-auth/provider-logos/auth0-dark.svg deleted file mode 100644 index 1b4a7b6d..00000000 --- a/packages/next-auth/provider-logos/auth0-dark.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/packages/next-auth/provider-logos/auth0.svg b/packages/next-auth/provider-logos/auth0.svg deleted file mode 100644 index 102518ef..00000000 --- a/packages/next-auth/provider-logos/auth0.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/azure-dark.svg b/packages/next-auth/provider-logos/azure-dark.svg deleted file mode 100644 index fb3329d8..00000000 --- a/packages/next-auth/provider-logos/azure-dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/azure.svg b/packages/next-auth/provider-logos/azure.svg deleted file mode 100644 index 9b29e54f..00000000 --- a/packages/next-auth/provider-logos/azure.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/battlenet-dark.svg b/packages/next-auth/provider-logos/battlenet-dark.svg deleted file mode 100644 index 58fe8c84..00000000 --- a/packages/next-auth/provider-logos/battlenet-dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/battlenet.svg b/packages/next-auth/provider-logos/battlenet.svg deleted file mode 100644 index 299d5f72..00000000 --- a/packages/next-auth/provider-logos/battlenet.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/box-dark.svg b/packages/next-auth/provider-logos/box-dark.svg deleted file mode 100644 index 20a66a6a..00000000 --- a/packages/next-auth/provider-logos/box-dark.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/next-auth/provider-logos/box.svg b/packages/next-auth/provider-logos/box.svg deleted file mode 100644 index da4cc596..00000000 --- a/packages/next-auth/provider-logos/box.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/next-auth/provider-logos/cognito.svg b/packages/next-auth/provider-logos/cognito.svg deleted file mode 100644 index 012dc5a4..00000000 --- a/packages/next-auth/provider-logos/cognito.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/packages/next-auth/provider-logos/discord-dark.svg b/packages/next-auth/provider-logos/discord-dark.svg deleted file mode 100644 index 49f14c27..00000000 --- a/packages/next-auth/provider-logos/discord-dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/discord.svg b/packages/next-auth/provider-logos/discord.svg deleted file mode 100644 index b313eeb9..00000000 --- a/packages/next-auth/provider-logos/discord.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/facebook-dark.svg b/packages/next-auth/provider-logos/facebook-dark.svg deleted file mode 100644 index db842250..00000000 --- a/packages/next-auth/provider-logos/facebook-dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/provider-logos/facebook.svg b/packages/next-auth/provider-logos/facebook.svg deleted file mode 100644 index 24434914..00000000 --- a/packages/next-auth/provider-logos/facebook.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/packages/next-auth/provider-logos/foursquare-dark.svg b/packages/next-auth/provider-logos/foursquare-dark.svg deleted file mode 100644 index ffe01fbf..00000000 --- a/packages/next-auth/provider-logos/foursquare-dark.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - diff --git a/packages/next-auth/provider-logos/foursquare.svg b/packages/next-auth/provider-logos/foursquare.svg deleted file mode 100644 index 5f63b452..00000000 --- a/packages/next-auth/provider-logos/foursquare.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - diff --git a/packages/next-auth/provider-logos/freshbooks-dark.svg b/packages/next-auth/provider-logos/freshbooks-dark.svg deleted file mode 100644 index c673c4d2..00000000 --- a/packages/next-auth/provider-logos/freshbooks-dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/freshbooks.svg b/packages/next-auth/provider-logos/freshbooks.svg deleted file mode 100644 index ff80db28..00000000 --- a/packages/next-auth/provider-logos/freshbooks.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/github-dark.svg b/packages/next-auth/provider-logos/github-dark.svg deleted file mode 100644 index 41128ce9..00000000 --- a/packages/next-auth/provider-logos/github-dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - GitHub icon - - diff --git a/packages/next-auth/provider-logos/github.svg b/packages/next-auth/provider-logos/github.svg deleted file mode 100644 index a6f58d97..00000000 --- a/packages/next-auth/provider-logos/github.svg +++ /dev/null @@ -1,4 +0,0 @@ - - GitHub dark icon - - diff --git a/packages/next-auth/provider-logos/gitlab-dark.svg b/packages/next-auth/provider-logos/gitlab-dark.svg deleted file mode 100644 index a9d45541..00000000 --- a/packages/next-auth/provider-logos/gitlab-dark.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/packages/next-auth/provider-logos/gitlab.svg b/packages/next-auth/provider-logos/gitlab.svg deleted file mode 100644 index 3b684907..00000000 --- a/packages/next-auth/provider-logos/gitlab.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/packages/next-auth/provider-logos/google.svg b/packages/next-auth/provider-logos/google.svg deleted file mode 100644 index 60d0ec13..00000000 --- a/packages/next-auth/provider-logos/google.svg +++ /dev/null @@ -1,7 +0,0 @@ - - Google icon - - - - - diff --git a/packages/next-auth/provider-logos/hubspot-dark.svg b/packages/next-auth/provider-logos/hubspot-dark.svg deleted file mode 100644 index e8ef5e7f..00000000 --- a/packages/next-auth/provider-logos/hubspot-dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/hubspot.svg b/packages/next-auth/provider-logos/hubspot.svg deleted file mode 100644 index 3ab02c3b..00000000 --- a/packages/next-auth/provider-logos/hubspot.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/instagram.svg b/packages/next-auth/provider-logos/instagram.svg deleted file mode 100644 index 9801b04b..00000000 --- a/packages/next-auth/provider-logos/instagram.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/packages/next-auth/provider-logos/keycloak.svg b/packages/next-auth/provider-logos/keycloak.svg deleted file mode 100644 index 4a558aef..00000000 --- a/packages/next-auth/provider-logos/keycloak.svg +++ /dev/null @@ -1,260 +0,0 @@ - - - - - - - - - - - - keycloak_deliverables - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/packages/next-auth/provider-logos/line.svg b/packages/next-auth/provider-logos/line.svg deleted file mode 100644 index afbd2758..00000000 --- a/packages/next-auth/provider-logos/line.svg +++ /dev/null @@ -1,6 +0,0 @@ - - Line icon - - - - diff --git a/packages/next-auth/provider-logos/linkedin-dark.svg b/packages/next-auth/provider-logos/linkedin-dark.svg deleted file mode 100644 index 3240302d..00000000 --- a/packages/next-auth/provider-logos/linkedin-dark.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/next-auth/provider-logos/linkedin.svg b/packages/next-auth/provider-logos/linkedin.svg deleted file mode 100644 index 1bc626bc..00000000 --- a/packages/next-auth/provider-logos/linkedin.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/next-auth/provider-logos/mailchimp-dark.svg b/packages/next-auth/provider-logos/mailchimp-dark.svg deleted file mode 100644 index adf1fa2b..00000000 --- a/packages/next-auth/provider-logos/mailchimp-dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/mailchimp.svg b/packages/next-auth/provider-logos/mailchimp.svg deleted file mode 100644 index 27a2f9bc..00000000 --- a/packages/next-auth/provider-logos/mailchimp.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/okta-dark.svg b/packages/next-auth/provider-logos/okta-dark.svg deleted file mode 100644 index a976f88b..00000000 --- a/packages/next-auth/provider-logos/okta-dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/okta.svg b/packages/next-auth/provider-logos/okta.svg deleted file mode 100644 index 2321a153..00000000 --- a/packages/next-auth/provider-logos/okta.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/patreon.svg b/packages/next-auth/provider-logos/patreon.svg deleted file mode 100644 index 4fa72b52..00000000 --- a/packages/next-auth/provider-logos/patreon.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/provider-logos/slack.svg b/packages/next-auth/provider-logos/slack.svg deleted file mode 100644 index b80883e7..00000000 --- a/packages/next-auth/provider-logos/slack.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/packages/next-auth/provider-logos/spotify.svg b/packages/next-auth/provider-logos/spotify.svg deleted file mode 100644 index 2421491e..00000000 --- a/packages/next-auth/provider-logos/spotify.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/provider-logos/todoist.svg b/packages/next-auth/provider-logos/todoist.svg deleted file mode 100644 index e229dc2c..00000000 --- a/packages/next-auth/provider-logos/todoist.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/packages/next-auth/provider-logos/trakt-dark.svg b/packages/next-auth/provider-logos/trakt-dark.svg deleted file mode 100644 index 9722816d..00000000 --- a/packages/next-auth/provider-logos/trakt-dark.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - diff --git a/packages/next-auth/provider-logos/trakt.svg b/packages/next-auth/provider-logos/trakt.svg deleted file mode 100644 index 5cb7e1fe..00000000 --- a/packages/next-auth/provider-logos/trakt.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - diff --git a/packages/next-auth/provider-logos/twitch-dark.svg b/packages/next-auth/provider-logos/twitch-dark.svg deleted file mode 100644 index 41488e9d..00000000 --- a/packages/next-auth/provider-logos/twitch-dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/provider-logos/twitch.svg b/packages/next-auth/provider-logos/twitch.svg deleted file mode 100644 index 8c08a260..00000000 --- a/packages/next-auth/provider-logos/twitch.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/provider-logos/twitter-dark.svg b/packages/next-auth/provider-logos/twitter-dark.svg deleted file mode 100644 index 07f05a86..00000000 --- a/packages/next-auth/provider-logos/twitter-dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/twitter.svg b/packages/next-auth/provider-logos/twitter.svg deleted file mode 100644 index 35e715f2..00000000 --- a/packages/next-auth/provider-logos/twitter.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/next-auth/provider-logos/vk-dark.svg b/packages/next-auth/provider-logos/vk-dark.svg deleted file mode 100644 index 6ef4ef9e..00000000 --- a/packages/next-auth/provider-logos/vk-dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/provider-logos/vk.svg b/packages/next-auth/provider-logos/vk.svg deleted file mode 100644 index f567c75c..00000000 --- a/packages/next-auth/provider-logos/vk.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/provider-logos/wikimedia-dark.svg b/packages/next-auth/provider-logos/wikimedia-dark.svg deleted file mode 100644 index 55de1b63..00000000 --- a/packages/next-auth/provider-logos/wikimedia-dark.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/packages/next-auth/provider-logos/wikimedia.svg b/packages/next-auth/provider-logos/wikimedia.svg deleted file mode 100644 index 3ae4b1ba..00000000 --- a/packages/next-auth/provider-logos/wikimedia.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/packages/next-auth/provider-logos/workos-dark.svg b/packages/next-auth/provider-logos/workos-dark.svg deleted file mode 100644 index b9047adc..00000000 --- a/packages/next-auth/provider-logos/workos-dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/provider-logos/workos.svg b/packages/next-auth/provider-logos/workos.svg deleted file mode 100644 index 42f799f2..00000000 --- a/packages/next-auth/provider-logos/workos.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/next-auth/src/adapters.ts b/packages/next-auth/src/adapters.ts index b4389f2b..6e8d24a0 100644 --- a/packages/next-auth/src/adapters.ts +++ b/packages/next-auth/src/adapters.ts @@ -1,130 +1,47 @@ -import { Account, User, Awaitable } from "." +/** + * :::warning Deprecated + * This module is being replaced by [`@auth/core/adapters`](https://authjs.dev/reference/core/adapters) and only kept for backwards compatibility. + * ::: + * + * @module adapters + */ -export interface AdapterUser extends User { - id: string - email: string - emailVerified: Date | null -} +// TODO: remove this file and replace references with `@auth/core/adapters` -export interface AdapterAccount extends Account { - userId: string -} - -export interface AdapterSession { - /** A randomly generated value that is used to get hold of the session. */ - sessionToken: string - /** Used to connect the session to a particular user */ - userId: string - expires: Date -} - -export interface VerificationToken { - identifier: string - expires: Date - token: string -} +import { + Adapter as CoreAdapter, + AdapterAccount as CoreAdapterAccount, + AdapterSession as CoreAdapterSession, + AdapterUser as CoreAdapterUser, + VerificationToken as CoreVerificationToken, +} from "@auth/core/adapters" /** - * Using a custom adapter you can connect to any database backend or even several different databases. - * Custom adapters created and maintained by our community can be found in the adapters repository. - * Feel free to add a custom adapter from your project to the repository, - * or even become a maintainer of a certain adapter. - * Custom adapters can still be created and used in a project without being added to the repository. - * - * **Required methods** - * - * _(These methods are required for all sign in flows)_ - * - `createUser` - * - `getUser` - * - `getUserByEmail` - * - `getUserByAccount` - * - `linkAccount` - * - `createSession` - * - `getSessionAndUser` - * - `updateSession` - * - `deleteSession` - * - `updateUser` - * - * _(Required to support email / passwordless sign in)_ - * - * - `createVerificationToken` - * - `useVerificationToken` - * - * **Unimplemented methods** - * - * _(These methods will be required in a future release, but are not yet invoked)_ - * - `deleteUser` - * - `unlinkAccount` - * - * [Adapters Overview](https://next-auth.js.org/adapters/overview) | - * [Create a custom adapter](https://next-auth.js.org/tutorials/creating-a-database-adapter) + * @deprecated use `@auth/core/adapters` + * Read more at: https://nextjs.authjs.dev/v5 */ -export type Adapter = DefaultAdapter & - (WithVerificationToken extends true - ? { - createVerificationToken: ( - verificationToken: VerificationToken - ) => Awaitable - /** - * Return verification token from the database - * and delete it so it cannot be used again. - */ - useVerificationToken: (params: { - identifier: string - token: string - }) => Awaitable - } - : {}) +export type Adapter = CoreAdapter -export interface DefaultAdapter { - createUser: (user: Omit) => Awaitable - getUser: (id: string) => Awaitable - getUserByEmail: (email: string) => Awaitable - /** Using the provider id and the id of the user for a specific account, get the user. */ - getUserByAccount: ( - providerAccountId: Pick - ) => Awaitable - updateUser: (user: Partial & Pick) => Awaitable - /** @todo Implement */ - deleteUser?: ( - userId: string - ) => Promise | Awaitable - linkAccount: ( - account: AdapterAccount - ) => Promise | Awaitable - /** @todo Implement */ - unlinkAccount?: ( - providerAccountId: Pick - ) => Promise | Awaitable - /** Creates a session for the user and returns it. */ - createSession: (session: { - sessionToken: string - userId: string - expires: Date - }) => Awaitable - getSessionAndUser: ( - sessionToken: string - ) => Awaitable<{ session: AdapterSession; user: AdapterUser } | null> - updateSession: ( - session: Partial & Pick - ) => Awaitable - /** - * Deletes a session from the database. - * It is preferred that this method also returns the session - * that is being deleted for logging purposes. - */ - deleteSession: ( - sessionToken: string - ) => Promise | Awaitable - createVerificationToken?: ( - verificationToken: VerificationToken - ) => Awaitable - /** - * Return verification token from the database - * and delete it so it cannot be used again. - */ - useVerificationToken?: (params: { - identifier: string - token: string - }) => Awaitable -} +/** + * @deprecated use `@auth/core/adapters` + * Read more at: https://nextjs.authjs.dev/v5 + */ +export type AdapterAccount = CoreAdapterAccount + +/** + * @deprecated use `@auth/core/adapters` + * Read more at: https://nextjs.authjs.dev/v5 + */ +export type AdapterSession = CoreAdapterSession + +/** + * @deprecated use `@auth/core/adapters` + * Read more at: https://nextjs.authjs.dev/v5 + */ +export type AdapterUser = CoreAdapterUser + +/** + * @deprecated use `@auth/core/adapters` + * Read more at: https://nextjs.authjs.dev/v5 + */ +export type VerificationToken = CoreVerificationToken diff --git a/packages/next-auth/src/client/__tests__/client-provider.test.js b/packages/next-auth/src/client/__tests__/client-provider.test.js deleted file mode 100644 index e7dac687..00000000 --- a/packages/next-auth/src/client/__tests__/client-provider.test.js +++ /dev/null @@ -1,188 +0,0 @@ -import { rest } from "msw" -import { render, screen, waitFor } from "@testing-library/react" -import { server, mockSession } from "./helpers/mocks" -import { printFetchCalls } from "./helpers/utils" -import { SessionProvider, useSession, signOut, getSession } from "../../react" - -const origDocumentVisibility = document.visibilityState -const fetchSpy = jest.spyOn(global, "fetch") - -beforeAll(() => { - server.listen() -}) - -afterEach(() => { - server.resetHandlers() - changeTabVisibility(origDocumentVisibility) - fetchSpy.mockClear() -}) - -afterAll(() => { - server.close() -}) - -test("fetches the session once and re-uses it for different consumers", async () => { - render() - - expect(screen.getByTestId("session-1")).toHaveTextContent("loading") - expect(screen.getByTestId("session-2")).toHaveTextContent("loading") - - return waitFor(() => { - expect(fetchSpy).toHaveBeenCalledTimes(1) - - expect(fetchSpy).toHaveBeenCalledWith( - "/api/auth/session", - expect.anything() - ) - - const session1 = screen.getByTestId("session-1").textContent - const session2 = screen.getByTestId("session-2").textContent - - expect(session1).toEqual(session2) - }) -}) - -test("when there's an existing session, it won't try to fetch a new one straightaway", async () => { - render() - - expect(fetchSpy).not.toHaveBeenCalled() -}) - -test("will refetch the session when the browser tab becomes active again", async () => { - render() - - expect(fetchSpy).not.toHaveBeenCalled() - - // Hide the current tab - changeTabVisibility("hidden") - - // Given the current tab got hidden, it should not attempt to re-fetch the session - expect(fetchSpy).not.toHaveBeenCalled() - - // Make the tab again visible - changeTabVisibility("visible") - - // Given the user made the tab visible again, now attempts to sync and re-fetch the session - return waitFor(() => { - expect(fetchSpy).toHaveBeenCalledTimes(1) - expect(fetchSpy).toHaveBeenCalledWith( - "/api/auth/session", - expect.anything() - ) - }) -}) - -test("will refetch the session if told to do so programmatically from another window", async () => { - render() - - expect(fetchSpy).not.toHaveBeenCalled() - - // Hide the current tab - changeTabVisibility("hidden") - - // Given the current tab got hidden, it should not attempt to re-fetch the session - expect(fetchSpy).not.toHaveBeenCalled() - - // simulate sign-out triggered by another tab - signOut({ redirect: false }) - - // Given signed out in another tab, it attempts to sync and re-fetch the session - return waitFor(() => { - expect(fetchSpy).toHaveBeenCalledWith( - "/api/auth/session", - expect.anything() - ) - - // We should have a call to sign-out and a call to refetch the session accordingly - expect(printFetchCalls(fetchSpy.mock.calls)).toMatchInlineSnapshot(` - Array [ - "GET /api/auth/csrf", - "POST /api/auth/signout", - "GET /api/auth/session", - ] - `) - }) -}) - -test("allows to customize how often the session will be re-fetched through polling", () => { - jest.useFakeTimers() - - render() - - // we provided a mock session so it shouldn't try to fetch a new one - expect(fetchSpy).not.toHaveBeenCalled() - - jest.advanceTimersByTime(1000) - - expect(fetchSpy).toHaveBeenCalledTimes(1) - expect(fetchSpy).toHaveBeenCalledWith("/api/auth/session", expect.anything()) - - jest.advanceTimersByTime(1000) - - // it should have tried to refetch the session, hence counting 2 calls to the session endpoint - expect(fetchSpy).toHaveBeenCalledTimes(2) - expect(printFetchCalls(fetchSpy.mock.calls)).toMatchInlineSnapshot(` - Array [ - "GET /api/auth/session", - "GET /api/auth/session", - ] - `) -}) - -test("allows to customize the URL for session fetching", async () => { - const myPath = "/api/v1/auth" - - server.use( - rest.get(`${myPath}/session`, (req, res, ctx) => - res(ctx.status(200), ctx.json(mockSession)) - ) - ) - - render() - - // there's an existing session so it should not try to fetch a new one - expect(fetchSpy).not.toHaveBeenCalled() - - // force a session refetch across all clients... - getSession() - - return waitFor(() => { - expect(fetchSpy).toHaveBeenCalledTimes(1) - expect(fetchSpy).toHaveBeenCalledWith( - `${myPath}/session`, - expect.anything() - ) - }) -}) - -function ProviderFlow(props) { - return ( - - - - - ) -} - -function SessionConsumer({ testId = 1, ...rest }) { - const { data: session, status } = useSession(rest) - - return ( -
- {status === "loading" ? "loading" : JSON.stringify(session)} -
- ) -} - -function changeTabVisibility(status) { - const visibleStates = ["visible", "hidden"] - - if (!visibleStates.includes(status)) return - - Object.defineProperty(document, "visibilityState", { - configurable: true, - value: status, - }) - - document.dispatchEvent(new Event("visibilitychange")) -} diff --git a/packages/next-auth/src/client/__tests__/csrf.test.js b/packages/next-auth/src/client/__tests__/csrf.test.js deleted file mode 100644 index 1d6b1261..00000000 --- a/packages/next-auth/src/client/__tests__/csrf.test.js +++ /dev/null @@ -1,104 +0,0 @@ -import { useState } from "react" -import userEvent from "@testing-library/user-event" -import { render, screen, waitFor } from "@testing-library/react" -import { server, mockCSRFToken } from "./helpers/mocks" -import logger from "../../utils/logger" -import { getCsrfToken } from "../../react" -import { rest } from "msw" - -jest.mock("../../utils/logger", () => ({ - __esModule: true, - default: { - warn: jest.fn(), - debug: jest.fn(), - error: jest.fn(), - }, - proxyLogger(logger) { - return logger - }, -})) - -beforeAll(() => { - server.listen() -}) - -afterEach(() => { - server.resetHandlers() - jest.clearAllMocks() -}) - -afterAll(() => { - server.close() -}) - -test("returns the Cross Site Request Forgery Token (CSRF Token) required to make POST requests", async () => { - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(screen.getByTestId("csrf-result").textContent).toEqual( - mockCSRFToken.csrfToken - ) - }) -}) - -test("when there's no CSRF token returned, it'll reflect that", async () => { - server.use( - rest.get("*/api/auth/csrf", (req, res, ctx) => - res( - ctx.status(200), - ctx.json({ - ...mockCSRFToken, - csrfToken: null, - }) - ) - ) - ) - - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(screen.getByTestId("csrf-result").textContent).toBe("null-response") - }) -}) - -test("when the fetch fails it'll throw a client fetch error", async () => { - server.use( - rest.get("*/api/auth/csrf", (req, res, ctx) => - res(ctx.status(500), ctx.text("some error happened")) - ) - ) - - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(logger.error).toHaveBeenCalledTimes(1) - expect(logger.error).toBeCalledWith("CLIENT_FETCH_ERROR", { - url: "/api/auth/csrf", - error: new SyntaxError("Unexpected token s in JSON at position 0"), - }) - }) -}) - -function CSRFFlow() { - const [response, setResponse] = useState() - - async function handleCSRF() { - const result = await getCsrfToken() - setResponse(result) - } - - return ( - <> -

- {response === null ? "null-response" : response || "no response"} -

- - - ) -} diff --git a/packages/next-auth/src/client/__tests__/helpers/mocks.js b/packages/next-auth/src/client/__tests__/helpers/mocks.js deleted file mode 100644 index 79c532fd..00000000 --- a/packages/next-auth/src/client/__tests__/helpers/mocks.js +++ /dev/null @@ -1,90 +0,0 @@ -import { setupServer } from "msw/node" -import { rest } from "msw" -import { randomBytes } from "crypto" - -export const mockSession = { - ok: true, - user: { - image: null, - name: "John", - email: "john@email.com", - }, - expires: 123213139, -} - -export const mockProviders = { - ok: true, - github: { - id: "github", - name: "Github", - type: "oauth", - signinUrl: "path/to/signin", - callbackUrl: "path/to/callback", - }, - credentials: { - id: "credentials", - name: "Credentials", - type: "credentials", - authorize: null, - credentials: null, - }, - email: { - id: "email", - type: "email", - name: "Email", - }, -} - -export const mockCSRFToken = { - ok: true, - csrfToken: randomBytes(32).toString("hex"), -} - -export const mockGithubResponse = { - ok: true, - status: 200, - url: "https://path/to/github/url", -} - -export const mockCredentialsResponse = { - ok: true, - status: 200, - url: "https://path/to/credentials/url", -} - -export const mockEmailResponse = { - ok: true, - status: 200, - url: "https://path/to/email/url", -} - -export const mockSignOutResponse = { - ok: true, - status: 200, - url: "https://path/to/signout/url", -} - -export const server = setupServer( - rest.post("*/api/auth/signout", (req, res, ctx) => - res(ctx.status(200), ctx.json(mockSignOutResponse)) - ), - rest.get("*/api/auth/session", (req, res, ctx) => - res(ctx.status(200), ctx.json(mockSession)) - ), - rest.get("*/api/auth/csrf", (req, res, ctx) => - res(ctx.status(200), ctx.json(mockCSRFToken)) - ), - rest.get("*/api/auth/providers", (req, res, ctx) => - res(ctx.status(200), ctx.json(mockProviders)) - ), - rest.post("*/api/auth/signin/github", (req, res, ctx) => - res(ctx.status(200), ctx.json(mockGithubResponse)) - ), - rest.post("*/api/auth/callback/credentials", (req, res, ctx) => - res(ctx.status(200), ctx.json(mockCredentialsResponse)) - ), - rest.post("*/api/auth/signin/email", (req, res, ctx) => - res(ctx.status(200), ctx.json(mockEmailResponse)) - ), - rest.post("*/api/auth/_log", (req, res, ctx) => res(ctx.status(200))) -) diff --git a/packages/next-auth/src/client/__tests__/helpers/utils.js b/packages/next-auth/src/client/__tests__/helpers/utils.js deleted file mode 100644 index df2844a1..00000000 --- a/packages/next-auth/src/client/__tests__/helpers/utils.js +++ /dev/null @@ -1,14 +0,0 @@ -export function getBroadcastEvents() { - return window.localStorage.setItem.mock.calls - .filter((call) => call[0] === "nextauth.message") - .map(([eventName, value]) => { - const { timestamp, ...rest } = JSON.parse(value) - return { eventName, value: rest } - }) -} - -export function printFetchCalls(mockCalls) { - return mockCalls.map(([path, { method = "GET" }]) => { - return `${method.toUpperCase()} ${path}` - }) -} diff --git a/packages/next-auth/src/client/__tests__/providers.test.js b/packages/next-auth/src/client/__tests__/providers.test.js deleted file mode 100644 index 45d05508..00000000 --- a/packages/next-auth/src/client/__tests__/providers.test.js +++ /dev/null @@ -1,84 +0,0 @@ -import { useState } from "react" -import userEvent from "@testing-library/user-event" -import { render, screen, waitFor } from "@testing-library/react" -import { server, mockProviders } from "./helpers/mocks" -import { getProviders } from "../../react" -import logger from "../../utils/logger" -import { rest } from "msw" - -jest.mock("../../utils/logger", () => ({ - __esModule: true, - default: { - warn: jest.fn(), - debug: jest.fn(), - error: jest.fn(), - }, - proxyLogger(logger) { - return logger - }, -})) - -beforeAll(() => { - server.listen() -}) - -afterEach(() => { - server.resetHandlers() - jest.clearAllMocks() -}) - -afterAll(() => { - server.close() -}) - -test("when called it'll return the currently configured providers for sign in", async () => { - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(screen.getByTestId("providers-result").textContent).toEqual( - JSON.stringify(mockProviders) - ) - }) -}) - -test("when failing to fetch the providers, it'll log the error", async () => { - server.use( - rest.get("*/api/auth/providers", (req, res, ctx) => - res(ctx.status(500), ctx.text("some error happened")) - ) - ) - - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(logger.error).toHaveBeenCalledTimes(1) - expect(logger.error).toBeCalledWith("CLIENT_FETCH_ERROR", { - url: "/api/auth/providers", - error: new SyntaxError("Unexpected token s in JSON at position 0"), - }) - }) -}) - -function ProvidersFlow() { - const [response, setResponse] = useState() - - async function handleGerProviders() { - const result = await getProviders() - setResponse(result) - } - - return ( - <> -

- {response === null - ? "null-response" - : JSON.stringify(response) || "no response"} -

- - - ) -} diff --git a/packages/next-auth/src/client/__tests__/session.test.js b/packages/next-auth/src/client/__tests__/session.test.js deleted file mode 100644 index 4940f81b..00000000 --- a/packages/next-auth/src/client/__tests__/session.test.js +++ /dev/null @@ -1,97 +0,0 @@ -import { render, screen, waitFor } from "@testing-library/react" -import { rest } from "msw" -import { server, mockSession } from "./helpers/mocks" -import logger from "../../utils/logger" -import { useState, useEffect } from "react" -import { getSession } from "../../react" -import { getBroadcastEvents } from "./helpers/utils" - -jest.mock("../../utils/logger", () => ({ - __esModule: true, - default: { - warn: jest.fn(), - debug: jest.fn(), - error: jest.fn(), - }, - proxyLogger(logger) { - return logger - }, -})) - -beforeAll(() => server.listen()) - -beforeEach(() => { - // eslint-disable-next-line no-proto - jest.spyOn(window.localStorage.__proto__, "setItem") -}) - -afterEach(() => { - server.resetHandlers() - jest.clearAllMocks() -}) - -afterAll(() => { - server.close() -}) - -test("if it can fetch the session, it should store it in `localStorage`", async () => { - render() - - // In the start, there is no session - const noSession = await screen.findByText("No session") - expect(noSession).toBeInTheDocument() - - // After we fetched the session, it should have been rendered by `` - const session = await screen.findByText(new RegExp(mockSession.user.name)) - expect(session).toBeInTheDocument() - - const broadcastCalls = getBroadcastEvents() - const [broadcastedEvent] = broadcastCalls - - expect(broadcastCalls).toHaveLength(1) - expect(broadcastCalls).toHaveLength(1) - expect(broadcastedEvent.eventName).toBe("nextauth.message") - expect(broadcastedEvent.value).toStrictEqual({ - data: { - trigger: "getSession", - }, - event: "session", - }) -}) - -test("if there's an error fetching the session, it should log it", async () => { - server.use( - rest.get("*/api/auth/session", (req, res, ctx) => { - return res(ctx.status(500), ctx.body("Server error")) - }) - ) - - render() - - await waitFor(() => { - expect(logger.error).toHaveBeenCalledTimes(1) - expect(logger.error).toBeCalledWith("CLIENT_FETCH_ERROR", { - url: "/api/auth/session", - error: new SyntaxError("Unexpected token S in JSON at position 0"), - }) - }) -}) - -function SessionFlow() { - const [session, setSession] = useState(null) - useEffect(() => { - async function fetchUserSession() { - try { - const result = await getSession() - setSession(result) - } catch (e) { - console.error(e) - } - } - fetchUserSession() - }, []) - - if (session) return
{JSON.stringify(session, null, 2)}
- - return

No session

-} diff --git a/packages/next-auth/src/client/__tests__/sign-in.test.js b/packages/next-auth/src/client/__tests__/sign-in.test.js deleted file mode 100644 index 0422fe90..00000000 --- a/packages/next-auth/src/client/__tests__/sign-in.test.js +++ /dev/null @@ -1,290 +0,0 @@ -import { useState } from "react" -import userEvent from "@testing-library/user-event" -import { render, screen, waitFor } from "@testing-library/react" -import logger from "../../utils/logger" -import { - server, - mockCredentialsResponse, - mockEmailResponse, - mockGithubResponse, -} from "./helpers/mocks" -import { signIn } from "../../react" -import { rest } from "msw" - -const { location } = window - -jest.mock("../../utils/logger", () => ({ - __esModule: true, - default: { - warn: jest.fn(), - debug: jest.fn(), - error: jest.fn(), - }, - proxyLogger(logger) { - return logger - }, -})) - -beforeAll(() => { - server.listen() - - let _href = window.location.href - // Allows to mutate `window.location`... - delete window.location - - window.location = { - reload: jest.fn(), - } - Object.defineProperty(window.location, "href", { - get: () => _href, - // whatwg-fetch or whatwg-url does not seem to work with relative URLs - set: (href) => { - _href = href.startsWith("/") ? `http://localhost${href}` : href - return _href - }, - }) -}) - -beforeEach(() => { - jest.clearAllMocks() - server.resetHandlers() -}) - -afterAll(() => { - window.location = location - server.close() -}) - -const callbackUrl = "https://redirects/to" - -test.each` - provider | type - ${""} | ${"no"} - ${"foo"} | ${"unknown"} -`( - "if $type provider, it redirects to the default sign-in page", - async ({ provider }) => { - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).toBe( - `http://localhost/api/auth/signin?${new URLSearchParams({ - callbackUrl, - })}` - ) - }) - } -) - -test.each` - provider | type - ${""} | ${"no"} - ${"foo"} | ${"unknown"} -`( - "if $type provider supplied and no callback URL, redirects using the current location", - async ({ provider }) => { - render() - - const callbackUrl = window.location.href - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).toBe( - `http://localhost/api/auth/signin?${new URLSearchParams({ - callbackUrl, - })}` - ) - }) - } -) - -test.each` - provider | mockUrl - ${`email`} | ${mockEmailResponse.url} - ${`credentials`} | ${mockCredentialsResponse.url} -`( - "$provider provider redirects if `redirect` is `true`", - async ({ provider, mockUrl }) => { - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).toBe(mockUrl) - }) - } -) - -test("redirection can't be stopped using an oauth provider", async () => { - render( - - ) - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).toBe(mockGithubResponse.url) - }) -}) - -test("redirection can be stopped using the 'credentials' provider", async () => { - render( - - ) - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).not.toBe(mockCredentialsResponse.url) - - expect(screen.getByTestId("signin-result").textContent).not.toBe( - "no response" - ) - }) - - // snapshot the expected return shape from `signIn` - expect(JSON.parse(screen.getByTestId("signin-result").textContent)) - .toMatchInlineSnapshot(` - Object { - "error": null, - "ok": true, - "status": 200, - "url": "https://path/to/credentials/url", - } - `) -}) - -test("redirection can be stopped using the 'email' provider", async () => { - render( - - ) - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).not.toBe(mockEmailResponse.url) - - expect(screen.getByTestId("signin-result").textContent).not.toBe( - "no response" - ) - }) - - // snapshot the expected return shape from `signIn` oauth - expect(JSON.parse(screen.getByTestId("signin-result").textContent)) - .toMatchInlineSnapshot(` - Object { - "error": null, - "ok": true, - "status": 200, - "url": "https://path/to/email/url", - } - `) -}) - -test("if callback URL contains a hash we force a window reload when re-directing", async () => { - const mockUrlWithHash = "https://path/to/email/url#foo-bar-baz" - - server.use( - rest.post("*/api/auth/signin/email", (req, res, ctx) => { - return res( - ctx.status(200), - ctx.json({ - ...mockEmailResponse, - url: mockUrlWithHash, - }) - ) - }) - ) - - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).toBe(mockUrlWithHash) - // the browser will not refresh the page if the redirect URL contains a hash, hence we force it on the client, see #1289 - expect(window.location.reload).toHaveBeenCalledTimes(1) - }) -}) - -test("params are propagated to the signin URL when supplied", async () => { - let matchedParams = "" - const authParams = "foo=bar&bar=foo" - - server.use( - rest.post("*/auth/signin/github", (req, res, ctx) => { - matchedParams = req.url.search - return res(ctx.status(200), ctx.json(mockGithubResponse)) - }) - ) - - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(matchedParams).toEqual(`?${authParams}`) - }) -}) - -test("when it fails to fetch the providers, it redirected back to signin page", async () => { - const errorMsg = "Error when retrieving providers" - - server.use( - rest.get("*/api/auth/providers", (req, res, ctx) => - res(ctx.status(500), ctx.json(errorMsg)) - ) - ) - - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).toBe(`http://localhost/api/auth/error`) - - expect(logger.error).toHaveBeenCalledTimes(1) - expect(logger.error).toBeCalledWith("CLIENT_FETCH_ERROR", { - error: "Error when retrieving providers", - url: "/api/auth/providers", - }) - }) -}) - -function SignInFlow({ - providerId, - callbackUrl, - redirect = true, - authorizationParams = {}, -}) { - const [response, setResponse] = useState(null) - - async function handleSignIn() { - const result = await signIn( - providerId, - { callbackUrl, redirect }, - authorizationParams - ) - - setResponse(result) - } - - return ( - <> -

- {response ? JSON.stringify(response) : "no response"} -

- - - ) -} diff --git a/packages/next-auth/src/client/__tests__/sign-out.test.js b/packages/next-auth/src/client/__tests__/sign-out.test.js deleted file mode 100644 index 508ed254..00000000 --- a/packages/next-auth/src/client/__tests__/sign-out.test.js +++ /dev/null @@ -1,124 +0,0 @@ -import { useState } from "react" -import userEvent from "@testing-library/user-event" -import { render, screen, waitFor } from "@testing-library/react" -import { server, mockSignOutResponse } from "./helpers/mocks" -import { signOut } from "../../react" -import { rest } from "msw" -import { getBroadcastEvents } from "./helpers/utils" - -const { location } = window - -beforeAll(() => { - server.listen() - // Allows to mutate `window.location`... - delete window.location - window.location = { - reload: jest.fn(), - href: location.href, - } -}) - -beforeEach(() => { - // eslint-disable-next-line no-proto - jest.spyOn(window.localStorage.__proto__, "setItem") -}) - -afterEach(() => { - jest.clearAllMocks() - server.resetHandlers() -}) - -afterAll(() => { - window.location = location - server.close() -}) - -const callbackUrl = "https://redirects/to" - -test("by default it redirects to the current URL if the server did not provide one", async () => { - server.use( - rest.post("*/api/auth/signout", (req, res, ctx) => - res(ctx.status(200), ctx.json({ ...mockSignOutResponse, url: undefined })) - ) - ) - - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).toBe(window.location.href) - }) -}) - -test("it redirects to the URL allowed by the server", async () => { - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).toBe(mockSignOutResponse.url) - }) -}) - -test("if url contains a hash during redirection a page reload happens", async () => { - const mockUrlWithHash = "https://path/to/email/url#foo-bar-baz" - - server.use( - rest.post("*/api/auth/signout", (req, res, ctx) => { - return res( - ctx.status(200), - ctx.json({ - ...mockSignOutResponse, - url: mockUrlWithHash, - }) - ) - }) - ) - - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - expect(window.location.href).toBe(mockUrlWithHash) - }) -}) - -test("will broadcast the signout event to other tabs", async () => { - render() - - userEvent.click(screen.getByRole("button")) - - await waitFor(() => { - const broadcastCalls = getBroadcastEvents() - const [broadcastedEvent] = broadcastCalls - - expect(broadcastCalls).toHaveLength(1) - expect(broadcastedEvent.eventName).toBe("nextauth.message") - expect(broadcastedEvent.value).toStrictEqual({ - data: { - trigger: "signout", - }, - event: "session", - }) - }) -}) - -function SignOutFlow({ callbackUrl, redirect = true }) { - const [response, setResponse] = useState(null) - - async function handleSignOut() { - const result = await signOut({ callbackUrl, redirect }) - setResponse(result) - } - - return ( - <> -

- {response ? JSON.stringify(response) : "no response"} -

- - - ) -} diff --git a/packages/next-auth/src/client/__tests__/use-session-hook.test.js b/packages/next-auth/src/client/__tests__/use-session-hook.test.js deleted file mode 100644 index 86bd06b7..00000000 --- a/packages/next-auth/src/client/__tests__/use-session-hook.test.js +++ /dev/null @@ -1,140 +0,0 @@ -import { rest } from "msw" -import { renderHook } from "@testing-library/react-hooks" -import { render, waitFor } from "@testing-library/react" -import { SessionProvider, useSession, signOut } from "../../react" -import { server, mockSession } from "./helpers/mocks" - -const origConsoleError = console.error -const { location } = window - -let _href = window.location.href -beforeAll(() => { - // Prevent noise on the terminal... `next-auth` will log to `console.error` - // every time a request fails, which makes the tests output very noisy... - console.error = jest.fn() - - // Allows to mutate `window.location`... - delete window.location - window.location = {} - Object.defineProperty(window.location, "href", { - get: () => _href, - // whatwg-fetch or whatwg-url does not seem to work with relative URLs - set: (href) => { - _href = href.startsWith("/") ? `http://localhost${href}` : href - return _href - }, - }) - - server.listen() -}) - -afterEach(() => { - server.resetHandlers() - _href = "http://localhost/" - - // clear the internal session cache... - signOut({ redirect: false }) -}) - -afterAll(() => { - console.error = origConsoleError - window.location = location - server.close() -}) - -test("it won't allow to fetch the session in isolation without a session context", () => { - function App() { - useSession() - return null - } - - expect(() => render()).toThrow( - "[next-auth]: `useSession` must be wrapped in a " - ) -}) - -test("when fetching the session, there won't be `data` and `status` will be 'loading'", () => { - const { result } = renderHook(() => useSession(), { - wrapper: SessionProvider, - }) - - expect(result.current.data).toBe(undefined) - expect(result.current.status).toBe("loading") -}) - -test("when session is fetched, `data` will contain the session data and `status` will be 'authenticated'", async () => { - const { result } = renderHook(() => useSession(), { - wrapper: SessionProvider, - }) - - await waitFor(() => { - expect(result.current.data).toEqual(mockSession) - expect(result.current.status).toBe("authenticated") - }) -}) - -test("when it fails to fetch the session, `data` will be null and `status` will be 'unauthenticated'", async () => { - server.use( - rest.get(`http://localhost/api/auth/session`, (_, res, ctx) => - res(ctx.status(401), ctx.json({})) - ) - ) - - const { result } = renderHook(() => useSession(), { - wrapper: SessionProvider, - }) - - return waitFor(() => { - expect(result.current.data).toEqual(null) - expect(result.current.status).toBe("unauthenticated") - }) -}) - -test("it'll redirect to sign-in page if the session is required and the user is not authenticated", async () => { - server.use( - rest.get(`http://localhost/api/auth/session`, (req, res, ctx) => - res(ctx.status(401), ctx.json({})) - ) - ) - - const callbackUrl = window.location.href - const { result } = renderHook(() => useSession({ required: true }), { - wrapper: SessionProvider, - }) - - await waitFor(() => { - expect(result.current.data).toEqual(null) - expect(result.current.status).toBe("loading") - }) - - expect(window.location.href).toBe( - `http://localhost/api/auth/signin?${new URLSearchParams({ - error: "SessionRequired", - callbackUrl, - })}` - ) -}) - -test("will call custom redirect logic if supplied when the user could not authenticate", async () => { - server.use( - rest.get(`http://localhost/api/auth/session`, (_, res, ctx) => - res(ctx.status(401), ctx.json({})) - ) - ) - - const customRedirect = jest.fn() - - const { result } = renderHook( - () => useSession({ required: true, onUnauthenticated: customRedirect }), - { - wrapper: SessionProvider, - } - ) - - await waitFor(() => { - expect(result.current.data).toEqual(null) - expect(result.current.status).toBe("loading") - }) - - expect(customRedirect).toHaveBeenCalledTimes(1) -}) diff --git a/packages/next-auth/src/client/_utils.ts b/packages/next-auth/src/client/_utils.ts deleted file mode 100644 index 1f3819e0..00000000 --- a/packages/next-auth/src/client/_utils.ts +++ /dev/null @@ -1,120 +0,0 @@ -import type { IncomingMessage } from "http" -import type { LoggerInstance, Session } from ".." - -export interface AuthClientConfig { - baseUrl: string - basePath: string - baseUrlServer: string - basePathServer: string - /** Stores last session response */ - _session?: Session | null | undefined - /** Used for timestamp since last sycned (in seconds) */ - _lastSync: number - /** - * Stores the `SessionProvider`'s session update method to be able to - * trigger session updates from places like `signIn` or `signOut` - */ - _getSession: (...args: any[]) => any -} - -export interface CtxOrReq { - req?: Partial & { body?: any } - ctx?: { req: Partial & { body?: any } } -} - -/** - * If passed 'appContext' via getInitialProps() in _app.js - * then get the req object from ctx and use that for the - * req value to allow `fetchData` to - * work seemlessly in getInitialProps() on server side - * pages *and* in _app.js. - */ -export async function fetchData( - path: string, - __NEXTAUTH: AuthClientConfig, - logger: LoggerInstance, - { ctx, req = ctx?.req }: CtxOrReq = {} -): Promise { - const url = `${apiBaseUrl(__NEXTAUTH)}/${path}` - try { - const options: RequestInit = { - headers: { - "Content-Type": "application/json", - ...(req?.headers?.cookie ? { cookie: req.headers.cookie } : {}), - }, - } - - if (req?.body) { - options.body = JSON.stringify(req.body) - options.method = "POST" - } - - const res = await fetch(url, options) - const data = await res.json() - if (!res.ok) throw data - return Object.keys(data).length > 0 ? data : null // Return null if data empty - } catch (error) { - logger.error("CLIENT_FETCH_ERROR", { error: error as Error, url }) - return null - } -} - -export function apiBaseUrl(__NEXTAUTH: AuthClientConfig) { - if (typeof window === "undefined") { - // Return absolute path when called server side - return `${__NEXTAUTH.baseUrlServer}${__NEXTAUTH.basePathServer}` - } - // Return relative path when called client side - return __NEXTAUTH.basePath -} - -/** Returns the number of seconds elapsed since January 1, 1970 00:00:00 UTC. */ -export function now() { - return Math.floor(Date.now() / 1000) -} - -export interface BroadcastMessage { - event?: "session" - data?: { trigger?: "signout" | "getSession" } - clientId: string - timestamp: number -} - -/** - * Inspired by [Broadcast Channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API) - * Only not using it directly, because Safari does not support it. - * - * https://caniuse.com/?search=broadcastchannel - */ -export function BroadcastChannel(name = "nextauth.message") { - return { - /** Get notified by other tabs/windows. */ - receive(onReceive: (message: BroadcastMessage) => void) { - const handler = (event: StorageEvent) => { - if (event.key !== name) return - const message: BroadcastMessage = JSON.parse(event.newValue ?? "{}") - if (message?.event !== "session" || !message?.data) return - - onReceive(message) - } - window.addEventListener("storage", handler) - return () => window.removeEventListener("storage", handler) - }, - /** Notify other tabs/windows. */ - post(message: Record) { - if (typeof window === "undefined") return - try { - localStorage.setItem( - name, - JSON.stringify({ ...message, timestamp: now() }) - ) - } catch { - /** - * The localStorage API isn't always available. - * It won't work in private mode prior to Safari 11 for example. - * Notifications are simply dropped if an error is encountered. - */ - } - }, - } -} diff --git a/packages/next-auth/src/core/errors.ts b/packages/next-auth/src/core/errors.ts deleted file mode 100644 index b2eaf0ba..00000000 --- a/packages/next-auth/src/core/errors.ts +++ /dev/null @@ -1,127 +0,0 @@ -import type { EventCallbacks, LoggerInstance } from ".." - -/** - * Same as the default `Error`, but it is JSON serializable. - * @source https://iaincollins.medium.com/error-handling-in-javascript-a6172ccdf9af - */ -export class UnknownError extends Error { - code: string - constructor(error: Error | string) { - // Support passing error or string - super((error as Error)?.message ?? error) - this.name = "UnknownError" - this.code = (error as any).code - if (error instanceof Error) { - this.stack = error.stack - } - } - - toJSON() { - return { - name: this.name, - message: this.message, - stack: this.stack, - } - } -} - -export class OAuthCallbackError extends UnknownError { - name = "OAuthCallbackError" -} - -/** - * Thrown when an Email address is already associated with an account - * but the user is trying an OAuth account that is not linked to it. - */ -export class AccountNotLinkedError extends UnknownError { - name = "AccountNotLinkedError" -} - -export class MissingAPIRoute extends UnknownError { - name = "MissingAPIRouteError" - code = "MISSING_NEXTAUTH_API_ROUTE_ERROR" -} - -export class MissingSecret extends UnknownError { - name = "MissingSecretError" - code = "NO_SECRET" -} - -export class MissingAuthorize extends UnknownError { - name = "MissingAuthorizeError" - code = "CALLBACK_CREDENTIALS_HANDLER_ERROR" -} - -export class MissingAdapter extends UnknownError { - name = "MissingAdapterError" - code = "EMAIL_REQUIRES_ADAPTER_ERROR" -} - -export class MissingAdapterMethods extends UnknownError { - name = "MissingAdapterMethodsError" - code = "MISSING_ADAPTER_METHODS_ERROR" -} - -export class UnsupportedStrategy extends UnknownError { - name = "UnsupportedStrategyError" - code = "CALLBACK_CREDENTIALS_JWT_ERROR" -} - -export class InvalidCallbackUrl extends UnknownError { - name = "InvalidCallbackUrl" - code = "INVALID_CALLBACK_URL_ERROR" -} - -type Method = (...args: any[]) => Promise - -export function upperSnake(s: string) { - return s.replace(/([A-Z])/g, "_$1").toUpperCase() -} - -export function capitalize(s: string) { - return `${s[0].toUpperCase()}${s.slice(1)}` -} - -/** - * Wraps an object of methods and adds error handling. - */ -export function eventsErrorHandler( - methods: Partial, - logger: LoggerInstance -): Partial { - return Object.keys(methods).reduce((acc, name) => { - acc[name] = async (...args: any[]) => { - try { - const method: Method = methods[name as keyof Method] - return await method(...args) - } catch (e) { - logger.error(`${upperSnake(name)}_EVENT_ERROR`, e as Error) - } - } - return acc - }, {}) -} - -/** Handles adapter induced errors. */ -export function adapterErrorHandler( - adapter: TAdapter | undefined, - logger: LoggerInstance -): TAdapter | undefined { - if (!adapter) return - - return Object.keys(adapter).reduce((acc, name) => { - acc[name] = async (...args: any[]) => { - try { - logger.debug(`adapter_${name}`, { args }) - const method: Method = adapter[name as keyof Method] - return await method(...args) - } catch (error) { - logger.error(`adapter_error_${name}`, error as Error) - const e = new UnknownError(error as Error) - e.name = `${capitalize(name)}Error` - throw e - } - } - return acc - }, {}) -} diff --git a/packages/next-auth/src/core/index.ts b/packages/next-auth/src/core/index.ts deleted file mode 100644 index 27ff069f..00000000 --- a/packages/next-auth/src/core/index.ts +++ /dev/null @@ -1,322 +0,0 @@ -import logger, { setLogger } from "../utils/logger" -import { detectOrigin } from "../utils/detect-origin" -import * as routes from "./routes" -import renderPage from "./pages" -import { init } from "./init" -import { assertConfig } from "./lib/assert" -import { SessionStore } from "./lib/cookie" - -import type { AuthAction, AuthOptions } from "./types" -import type { Cookie } from "./lib/cookie" -import type { ErrorType } from "./pages/error" -import { parse as parseCookie } from "cookie" - -export interface RequestInternal { - /** @default "http://localhost:3000" */ - origin?: string - method?: string - cookies?: Partial> - headers?: Record - query?: Record - body?: Record - action: AuthAction - providerId?: string - error?: string -} - -export interface NextAuthHeader { - key: string - value: string -} - -export interface ResponseInternal< - Body extends string | Record | any[] = any -> { - status?: number - headers?: NextAuthHeader[] - body?: Body - redirect?: string - cookies?: Cookie[] -} - -export interface NextAuthHandlerParams { - req: Request | RequestInternal - options: AuthOptions -} - -async function getBody(req: Request): Promise | undefined> { - try { - return await req.json() - } catch {} -} - -// TODO: -async function toInternalRequest( - req: RequestInternal | Request -): Promise { - if (req instanceof Request) { - const url = new URL(req.url) - // TODO: handle custom paths? - const nextauth = url.pathname.split("/").slice(3) - const headers = Object.fromEntries(req.headers) - const query: Record = Object.fromEntries(url.searchParams) - query.nextauth = nextauth - - return { - action: nextauth[0] as AuthAction, - method: req.method, - headers, - body: await getBody(req), - cookies: parseCookie(req.headers.get("cookie") ?? ""), - providerId: nextauth[1], - error: url.searchParams.get("error") ?? nextauth[1], - origin: detectOrigin( - headers["x-forwarded-host"] ?? headers.host, - headers["x-forwarded-proto"] - ), - query, - } - } - - const { headers } = req - const host = headers?.["x-forwarded-host"] ?? headers?.host - req.origin = detectOrigin(host, headers?.["x-forwarded-proto"]) - - return req -} - -export async function AuthHandler< - Body extends string | Record | any[] ->(params: NextAuthHandlerParams): Promise> { - const { options: authOptions, req: incomingRequest } = params - - const req = await toInternalRequest(incomingRequest) - - setLogger(authOptions.logger, authOptions.debug) - - const assertionResult = assertConfig({ options: authOptions, req }) - - if (Array.isArray(assertionResult)) { - assertionResult.forEach(logger.warn) - } else if (assertionResult instanceof Error) { - // Bail out early if there's an error in the user config - logger.error(assertionResult.code, assertionResult) - - const htmlPages = ["signin", "signout", "error", "verify-request"] - if (!htmlPages.includes(req.action) || req.method !== "GET") { - const message = `There is a problem with the server configuration. Check the server logs for more information.` - return { - status: 500, - headers: [{ key: "Content-Type", value: "application/json" }], - body: { message } as any, - } - } - const { pages, theme } = authOptions - - const authOnErrorPage = - pages?.error && req.query?.callbackUrl?.startsWith(pages.error) - - if (!pages?.error || authOnErrorPage) { - if (authOnErrorPage) { - logger.error( - "AUTH_ON_ERROR_PAGE_ERROR", - new Error( - `The error page ${pages?.error} should not require authentication` - ) - ) - } - const render = renderPage({ theme }) - return render.error({ error: "configuration" }) - } - - return { - redirect: `${pages.error}?error=Configuration`, - } - } - - const { action, providerId, error, method = "GET" } = req - - const { options, cookies } = await init({ - authOptions, - action, - providerId, - origin: req.origin, - callbackUrl: req.body?.callbackUrl ?? req.query?.callbackUrl, - csrfToken: req.body?.csrfToken, - cookies: req.cookies, - isPost: method === "POST", - }) - - const sessionStore = new SessionStore( - options.cookies.sessionToken, - req, - options.logger - ) - - if (method === "GET") { - const render = renderPage({ ...options, query: req.query, cookies }) - const { pages } = options - switch (action) { - case "providers": - return (await routes.providers(options.providers)) as any - case "session": { - const session = await routes.session({ options, sessionStore }) - if (session.cookies) cookies.push(...session.cookies) - return { ...session, cookies } as any - } - case "csrf": - return { - headers: [{ key: "Content-Type", value: "application/json" }], - body: { csrfToken: options.csrfToken } as any, - cookies, - } - case "signin": - if (pages.signIn) { - let signinUrl = `${pages.signIn}${ - pages.signIn.includes("?") ? "&" : "?" - }callbackUrl=${encodeURIComponent(options.callbackUrl)}` - if (error) - signinUrl = `${signinUrl}&error=${encodeURIComponent(error)}` - return { redirect: signinUrl, cookies } - } - - return render.signin() - case "signout": - if (pages.signOut) return { redirect: pages.signOut, cookies } - - return render.signout() - case "callback": - if (options.provider) { - const callback = await routes.callback({ - body: req.body, - query: req.query, - headers: req.headers, - cookies: req.cookies, - method, - options, - sessionStore, - }) - if (callback.cookies) cookies.push(...callback.cookies) - return { ...callback, cookies } - } - break - case "verify-request": - if (pages.verifyRequest) { - return { redirect: pages.verifyRequest, cookies } - } - return render.verifyRequest() - case "error": - // These error messages are displayed in line on the sign in page - if ( - [ - "Signin", - "OAuthSignin", - "OAuthCallback", - "OAuthCreateAccount", - "EmailCreateAccount", - "Callback", - "OAuthAccountNotLinked", - "EmailSignin", - "CredentialsSignin", - "SessionRequired", - ].includes(error as string) - ) { - return { redirect: `${options.url}/signin?error=${error}`, cookies } - } - - if (pages.error) { - return { - redirect: `${pages.error}${ - pages.error.includes("?") ? "&" : "?" - }error=${error}`, - cookies, - } - } - - return render.error({ error: error as ErrorType }) - default: - } - } else if (method === "POST") { - switch (action) { - case "signin": - // Verified CSRF Token required for all sign-in routes - if (options.csrfTokenVerified && options.provider) { - const signin = await routes.signin({ - query: req.query, - body: req.body, - options, - }) - if (signin.cookies) cookies.push(...signin.cookies) - return { ...signin, cookies } - } - - return { redirect: `${options.url}/signin?csrf=true`, cookies } - case "signout": - // Verified CSRF Token required for signout - if (options.csrfTokenVerified) { - const signout = await routes.signout({ options, sessionStore }) - if (signout.cookies) cookies.push(...signout.cookies) - return { ...signout, cookies } - } - return { redirect: `${options.url}/signout?csrf=true`, cookies } - case "callback": - if (options.provider) { - // Verified CSRF Token required for credentials providers only - if ( - options.provider.type === "credentials" && - !options.csrfTokenVerified - ) { - return { redirect: `${options.url}/signin?csrf=true`, cookies } - } - - const callback = await routes.callback({ - body: req.body, - query: req.query, - headers: req.headers, - cookies: req.cookies, - method, - options, - sessionStore, - }) - if (callback.cookies) cookies.push(...callback.cookies) - return { ...callback, cookies } - } - break - case "_log": { - if (authOptions.logger) { - try { - const { code, level, ...metadata } = req.body ?? {} - logger[level](code, metadata) - } catch (error) { - // If logging itself failed... - logger.error("LOGGER_ERROR", error as Error) - } - } - return {} - } - case "session": { - // Verified CSRF Token required for session updates - if (options.csrfTokenVerified) { - const session = await routes.session({ - options, - sessionStore, - newSession: req.body?.data, - isUpdate: true, - }) - if (session.cookies) cookies.push(...session.cookies) - return { ...session, cookies } as any - } - - // If CSRF token is invalid, return a 400 status code - // we should not redirect to a page as this is an API route - return { status: 400, body: {} as any, cookies } - } - default: - } - } - - return { - status: 400, - body: `Error: This action with HTTP ${method} is not supported by NextAuth.js` as any, - } -} diff --git a/packages/next-auth/src/core/init.ts b/packages/next-auth/src/core/init.ts deleted file mode 100644 index 15a97a29..00000000 --- a/packages/next-auth/src/core/init.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { randomBytes, randomUUID } from "crypto" -import { AuthOptions } from ".." -import logger from "../utils/logger" -import { adapterErrorHandler, eventsErrorHandler } from "./errors" -import parseProviders from "./lib/providers" -import { createSecret } from "./lib/utils" -import * as cookie from "./lib/cookie" -import * as jwt from "../jwt" -import { defaultCallbacks } from "./lib/default-callbacks" -import { createCSRFToken } from "./lib/csrf-token" -import { createCallbackUrl } from "./lib/callback-url" -import { RequestInternal } from "." - -import type { InternalOptions } from "./types" -import parseUrl from "../utils/parse-url" - -interface InitParams { - origin?: string - authOptions: AuthOptions - providerId?: string - action: InternalOptions["action"] - /** Callback URL value extracted from the incoming request. */ - callbackUrl?: string - /** CSRF token value extracted from the incoming request. From body if POST, from query if GET */ - csrfToken?: string - /** Is the incoming request a POST request? */ - isPost: boolean - cookies: RequestInternal["cookies"] -} - -/** Initialize all internal options and cookies. */ -export async function init({ - authOptions, - providerId, - action, - origin, - cookies: reqCookies, - callbackUrl: reqCallbackUrl, - csrfToken: reqCsrfToken, - isPost, -}: InitParams): Promise<{ - options: InternalOptions - cookies: cookie.Cookie[] -}> { - const url = parseUrl(origin) - - const secret = createSecret({ authOptions, url }) - - const { providers, provider } = parseProviders({ - providers: authOptions.providers, - url, - providerId, - }) - - const maxAge = 30 * 24 * 60 * 60 // Sessions expire after 30 days of being idle by default - - // User provided options are overriden by other options, - // except for the options with special handling above - const options: InternalOptions = { - debug: false, - pages: {}, - theme: { - colorScheme: "auto", - logo: "", - brandColor: "", - buttonText: "", - }, - // Custom options override defaults - ...authOptions, - // These computed settings can have values in authOptions but we override them - // and are request-specific. - url, - action, - // @ts-expect-errors - provider, - cookies: { - ...cookie.defaultCookies( - authOptions.useSecureCookies ?? url.base.startsWith("https://") - ), - // Allow user cookie options to override any cookie settings above - ...authOptions.cookies, - }, - secret, - providers, - // Session options - session: { - // If no adapter specified, force use of JSON Web Tokens (stateless) - strategy: authOptions.adapter ? "database" : "jwt", - maxAge, - updateAge: 24 * 60 * 60, - generateSessionToken: () => { - // Use `randomUUID` if available. (Node 15.6+) - return randomUUID?.() ?? randomBytes(32).toString("hex") - }, - ...authOptions.session, - }, - // JWT options - jwt: { - secret, // Use application secret if no keys specified - maxAge, // same as session maxAge, - encode: jwt.encode, - decode: jwt.decode, - ...authOptions.jwt, - }, - // Event messages - events: eventsErrorHandler(authOptions.events ?? {}, logger), - adapter: adapterErrorHandler(authOptions.adapter, logger), - // Callback functions - callbacks: { ...defaultCallbacks, ...authOptions.callbacks }, - logger, - callbackUrl: url.origin, - } - - // Init cookies - - const cookies: cookie.Cookie[] = [] - - const { - csrfToken, - cookie: csrfCookie, - csrfTokenVerified, - } = createCSRFToken({ - options, - cookieValue: reqCookies?.[options.cookies.csrfToken.name], - isPost, - bodyValue: reqCsrfToken, - }) - - options.csrfToken = csrfToken - options.csrfTokenVerified = csrfTokenVerified - - if (csrfCookie) { - cookies.push({ - name: options.cookies.csrfToken.name, - value: csrfCookie, - options: options.cookies.csrfToken.options, - }) - } - - const { callbackUrl, callbackUrlCookie } = await createCallbackUrl({ - options, - cookieValue: reqCookies?.[options.cookies.callbackUrl.name], - paramValue: reqCallbackUrl, - }) - options.callbackUrl = callbackUrl - if (callbackUrlCookie) { - cookies.push({ - name: options.cookies.callbackUrl.name, - value: callbackUrlCookie, - options: options.cookies.callbackUrl.options, - }) - } - - return { options, cookies } -} diff --git a/packages/next-auth/src/core/lib/assert.ts b/packages/next-auth/src/core/lib/assert.ts deleted file mode 100644 index 9da40824..00000000 --- a/packages/next-auth/src/core/lib/assert.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { - MissingAdapter, - MissingAPIRoute, - MissingAuthorize, - MissingSecret, - UnsupportedStrategy, - InvalidCallbackUrl, - MissingAdapterMethods, -} from "../errors" -import parseUrl from "../../utils/parse-url" -import { defaultCookies } from "./cookie" - -import type { RequestInternal } from ".." -import type { WarningCode } from "../../utils/logger" -import type { AuthOptions } from "../types" - -type ConfigError = - | MissingAPIRoute - | MissingSecret - | UnsupportedStrategy - | MissingAuthorize - | MissingAdapter - -let warned = false - -function isValidHttpUrl(url: string, baseUrl: string) { - try { - return /^https?:/.test( - new URL(url, url.startsWith("/") ? baseUrl : undefined).protocol - ) - } catch { - return false - } -} - -/** - * Verify that the user configured `next-auth` correctly. - * Good place to mention deprecations as well. - * - * REVIEW: Make some of these and corresponding docs less Next.js specific? - */ -export function assertConfig(params: { - options: AuthOptions - req: RequestInternal -}): ConfigError | WarningCode[] { - const { options, req } = params - - const warnings: WarningCode[] = [] - - if (!warned) { - if (!req.origin) warnings.push("NEXTAUTH_URL") - - // TODO: Make this throw an error in next major. This will also get rid of `NODE_ENV` - if (!options.secret && process.env.NODE_ENV !== "production") - warnings.push("NO_SECRET") - - if (options.debug) warnings.push("DEBUG_ENABLED") - } - - if (!options.secret && process.env.NODE_ENV === "production") { - return new MissingSecret("Please define a `secret` in production.") - } - - // req.query isn't defined when asserting `getServerSession` for example - if (!req.query?.nextauth && !req.action) { - return new MissingAPIRoute( - "Cannot find [...nextauth].{js,ts} in `/pages/api/auth`. Make sure the filename is written correctly." - ) - } - - const callbackUrlParam = req.query?.callbackUrl as string | undefined - - const url = parseUrl(req.origin) - - if (callbackUrlParam && !isValidHttpUrl(callbackUrlParam, url.base)) { - return new InvalidCallbackUrl( - `Invalid callback URL. Received: ${callbackUrlParam}` - ) - } - - const { callbackUrl: defaultCallbackUrl } = defaultCookies( - options.useSecureCookies ?? url.base.startsWith("https://") - ) - const callbackUrlCookie = - req.cookies?.[options.cookies?.callbackUrl?.name ?? defaultCallbackUrl.name] - - if (callbackUrlCookie && !isValidHttpUrl(callbackUrlCookie, url.base)) { - return new InvalidCallbackUrl( - `Invalid callback URL. Received: ${callbackUrlCookie}` - ) - } - - let hasCredentials, hasEmail - let hasTwitterOAuth2 - - for (const provider of options.providers) { - if (provider.type === "credentials") hasCredentials = true - else if (provider.type === "email") hasEmail = true - else if (provider.id === "twitter" && provider.version === "2.0") - hasTwitterOAuth2 = true - } - - if (hasCredentials) { - const dbStrategy = options.session?.strategy === "database" - const onlyCredentials = !options.providers.some( - (p) => p.type !== "credentials" - ) - if (dbStrategy && onlyCredentials) { - return new UnsupportedStrategy( - "Signin in with credentials only supported if JWT strategy is enabled" - ) - } - - const credentialsNoAuthorize = options.providers.some( - (p) => p.type === "credentials" && !p.authorize - ) - if (credentialsNoAuthorize) { - return new MissingAuthorize( - "Must define an authorize() handler to use credentials authentication provider" - ) - } - } - - if (hasEmail) { - const { adapter } = options - if (!adapter) { - return new MissingAdapter("E-mail login requires an adapter.") - } - - const missingMethods = [ - "createVerificationToken", - "useVerificationToken", - "getUserByEmail", - ].filter((method) => !adapter[method]) - - if (missingMethods.length) { - return new MissingAdapterMethods( - `Required adapter methods were missing: ${missingMethods.join(", ")}` - ) - } - } - - if (!warned) { - if (hasTwitterOAuth2) warnings.push("TWITTER_OAUTH_2_BETA") - warned = true - } - - return warnings -} diff --git a/packages/next-auth/src/core/lib/callback-handler.ts b/packages/next-auth/src/core/lib/callback-handler.ts deleted file mode 100644 index f8c88a90..00000000 --- a/packages/next-auth/src/core/lib/callback-handler.ts +++ /dev/null @@ -1,229 +0,0 @@ -import { AccountNotLinkedError } from "../errors" -import { fromDate } from "./utils" - -import type { InternalOptions } from "../types" -import type { AdapterSession, AdapterUser } from "../../adapters" -import type { JWT } from "../../jwt" -import type { Account, User } from "../.." -import type { SessionToken } from "./cookie" -import { OAuthConfig } from "src/providers" - -/** - * This function handles the complex flow of signing users in, and either creating, - * linking (or not linking) accounts depending on if the user is currently logged - * in, if they have account already and the authentication mechanism they are using. - * - * It prevents insecure behaviour, such as linking OAuth accounts unless a user is - * signed in and authenticated with an existing valid account. - * - * All verification (e.g. OAuth flows or email address verificaiton flows) are - * done prior to this handler being called to avoid additonal complexity in this - * handler. - */ -export default async function callbackHandler(params: { - sessionToken?: SessionToken - profile: User | AdapterUser | { email: string } - account: Account | null - options: InternalOptions -}) { - const { sessionToken, profile: _profile, account, options } = params - // Input validation - if (!account?.providerAccountId || !account.type) - throw new Error("Missing or invalid provider account") - if (!["email", "oauth"].includes(account.type)) - throw new Error("Provider not supported") - - const { - adapter, - jwt, - events, - session: { strategy: sessionStrategy, generateSessionToken }, - } = options - - // If no adapter is configured then we don't have a database and cannot - // persist data; in this mode we just return a dummy session object. - if (!adapter) { - return { user: _profile as User, account } - } - - const profile = _profile as AdapterUser - - const { - createUser, - updateUser, - getUser, - getUserByAccount, - getUserByEmail, - linkAccount, - createSession, - getSessionAndUser, - deleteSession, - } = adapter - - let session: AdapterSession | JWT | null = null - let user: AdapterUser | null = null - let isNewUser = false - - const useJwtSession = sessionStrategy === "jwt" - - if (sessionToken) { - if (useJwtSession) { - try { - session = await jwt.decode({ ...jwt, token: sessionToken }) - if (session && "sub" in session && session.sub) { - user = await getUser(session.sub) - } - } catch { - // If session can't be verified, treat as no session - } - } else { - const userAndSession = await getSessionAndUser(sessionToken) - if (userAndSession) { - session = userAndSession.session - user = userAndSession.user - } - } - } - - if (account.type === "email") { - // If signing in with an email, check if an account with the same email address exists already - const userByEmail = await getUserByEmail(profile.email) - if (userByEmail) { - // If they are not already signed in as the same user, this flow will - // sign them out of the current session and sign them in as the new user - if (user?.id !== userByEmail.id && !useJwtSession && sessionToken) { - // Delete existing session if they are currently signed in as another user. - // This will switch user accounts for the session in cases where the user was - // already logged in with a different account. - await deleteSession(sessionToken) - } - - // Update emailVerified property on the user object - user = await updateUser({ id: userByEmail.id, emailVerified: new Date() }) - await events.updateUser?.({ user }) - } else { - const { id: _, ...newUser } = { ...profile, emailVerified: new Date() } - // Create user account if there isn't one for the email address already - user = await createUser(newUser) - await events.createUser?.({ user }) - isNewUser = true - } - - // Create new session - session = useJwtSession - ? {} - : await createSession({ - sessionToken: await generateSessionToken(), - userId: user.id, - expires: fromDate(options.session.maxAge), - }) - - return { session, user, isNewUser } - } else if (account.type === "oauth") { - // If signing in with OAuth account, check to see if the account exists already - const userByAccount = await getUserByAccount({ - providerAccountId: account.providerAccountId, - provider: account.provider, - }) - if (userByAccount) { - if (user) { - // If the user is already signed in with this account, we don't need to do anything - if (userByAccount.id === user.id) { - return { session, user, isNewUser } - } - // If the user is currently signed in, but the new account they are signing in - // with is already associated with another user, then we cannot link them - // and need to return an error. - throw new AccountNotLinkedError( - "The account is already associated with another user" - ) - } - // If there is no active session, but the account being signed in with is already - // associated with a valid user then create session to sign the user in. - session = useJwtSession - ? {} - : await createSession({ - sessionToken: await generateSessionToken(), - userId: userByAccount.id, - expires: fromDate(options.session.maxAge), - }) - - return { session, user: userByAccount, isNewUser } - } else { - if (user) { - // If the user is already signed in and the OAuth account isn't already associated - // with another user account then we can go ahead and link the accounts safely. - await linkAccount({ ...account, userId: user.id }) - await events.linkAccount?.({ user, account, profile }) - - // As they are already signed in, we don't need to do anything after linking them - return { session, user, isNewUser } - } - - // If the user is not signed in and it looks like a new OAuth account then we - // check there also isn't an user account already associated with the same - // email address as the one in the OAuth profile. - // - // This step is often overlooked in OAuth implementations, but covers the following cases: - // - // 1. It makes it harder for someone to accidentally create two accounts. - // e.g. by signin in with email, then again with an oauth account connected to the same email. - // 2. It makes it harder to hijack a user account using a 3rd party OAuth account. - // e.g. by creating an oauth account then changing the email address associated with it. - // - // It's quite common for services to automatically link accounts in this case, but it's - // better practice to require the user to sign in *then* link accounts to be sure - // someone is not exploiting a problem with a third party OAuth service. - // - // OAuth providers should require email address verification to prevent this, but in - // practice that is not always the case; this helps protect against that. - const userByEmail = profile.email - ? await getUserByEmail(profile.email) - : null - if (userByEmail) { - const provider = options.provider as OAuthConfig - if (provider?.allowDangerousEmailAccountLinking) { - // If you trust the oauth provider to correctly verify email addresses, you can opt-in to - // account linking even when the user is not signed-in. - user = userByEmail - } else { - // We end up here when we don't have an account with the same [provider].id *BUT* - // we do already have an account with the same email address as the one in the - // OAuth profile the user has just tried to sign in with. - // - // We don't want to have two accounts with the same email address, and we don't - // want to link them in case it's not safe to do so, so instead we prompt the user - // to sign in via email to verify their identity and then link the accounts. - throw new AccountNotLinkedError( - "Another account already exists with the same e-mail address" - ) - } - } else { - // If the current user is not logged in and the profile isn't linked to any user - // accounts (by email or provider account id)... - // - // If no account matching the same [provider].id or .email exists, we can - // create a new account for the user, link it to the OAuth acccount and - // create a new session for them so they are signed in with it. - const { id: _, ...newUser } = { ...profile, emailVerified: null } - user = await createUser(newUser) - } - await events.createUser?.({ user }) - - await linkAccount({ ...account, userId: user.id }) - await events.linkAccount?.({ user, account, profile }) - - session = useJwtSession - ? {} - : await createSession({ - sessionToken: await generateSessionToken(), - userId: user.id, - expires: fromDate(options.session.maxAge), - }) - - return { session, user, isNewUser: true } - } - } - - throw new Error("Unsupported account type") -} diff --git a/packages/next-auth/src/core/lib/callback-url.ts b/packages/next-auth/src/core/lib/callback-url.ts deleted file mode 100644 index a89983d4..00000000 --- a/packages/next-auth/src/core/lib/callback-url.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type { InternalOptions } from "../types" - -interface CreateCallbackUrlParams { - options: InternalOptions - /** Try reading value from request body (POST) then from query param (GET) */ - paramValue?: string - cookieValue?: string -} - -/** - * Get callback URL based on query param / cookie + validation, - * and add it to `req.options.callbackUrl`. - */ -export async function createCallbackUrl({ - options, - paramValue, - cookieValue, -}: CreateCallbackUrlParams) { - const { url, callbacks } = options - - let callbackUrl = url.origin - - if (paramValue) { - // If callbackUrl form field or query parameter is passed try to use it if allowed - callbackUrl = await callbacks.redirect({ - url: paramValue, - baseUrl: url.origin, - }) - } else if (cookieValue) { - // If no callbackUrl specified, try using the value from the cookie if allowed - callbackUrl = await callbacks.redirect({ - url: cookieValue, - baseUrl: url.origin, - }) - } - - return { - callbackUrl, - // Save callback URL in a cookie so that it can be used for subsequent requests in signin/signout/callback flow - callbackUrlCookie: callbackUrl !== cookieValue ? callbackUrl : undefined, - } -} diff --git a/packages/next-auth/src/core/lib/cookie.ts b/packages/next-auth/src/core/lib/cookie.ts deleted file mode 100644 index c7ae681c..00000000 --- a/packages/next-auth/src/core/lib/cookie.ts +++ /dev/null @@ -1,237 +0,0 @@ -import type { CookiesOptions } from "../.." -import type { CookieOption, LoggerInstance, SessionStrategy } from "../types" -import type { NextRequest } from "next/server" -import type { NextApiRequest } from "next" - -// Uncomment to recalculate the estimated size -// of an empty session cookie -// import { serialize } from "cookie" -// console.log( -// "Cookie estimated to be ", -// serialize(`__Secure.next-auth.session-token.0`, "", { -// expires: new Date(), -// httpOnly: true, -// maxAge: Number.MAX_SAFE_INTEGER, -// path: "/", -// sameSite: "strict", -// secure: true, -// domain: "example.com", -// }).length, -// " bytes" -// ) - -const ALLOWED_COOKIE_SIZE = 4096 -// Based on commented out section above -const ESTIMATED_EMPTY_COOKIE_SIZE = 163 -const CHUNK_SIZE = ALLOWED_COOKIE_SIZE - ESTIMATED_EMPTY_COOKIE_SIZE - -// REVIEW: Is there any way to defer two types of strings? - -/** Stringified form of `JWT`. Extract the content with `jwt.decode` */ -export type JWTString = string - -export type SetCookieOptions = Partial & { - expires?: Date | string - encode?: (val: unknown) => string -} - -/** - * If `options.session.strategy` is set to `jwt`, this is a stringified `JWT`. - * In case of `strategy: "database"`, this is the `sessionToken` of the session in the database. - */ -export type SessionToken = T extends "jwt" - ? JWTString - : string - -/** - * Use secure cookies if the site uses HTTPS - * This being conditional allows cookies to work non-HTTPS development URLs - * Honour secure cookie option, which sets 'secure' and also adds '__Secure-' - * prefix, but enable them by default if the site URL is HTTPS; but not for - * non-HTTPS URLs like http://localhost which are used in development). - * For more on prefixes see https://googlechrome.github.io/samples/cookie-prefixes/ - * - * @TODO Review cookie settings (names, options) - */ -export function defaultCookies(useSecureCookies: boolean): CookiesOptions { - const cookiePrefix = useSecureCookies ? "__Secure-" : "" - return { - // default cookie options - sessionToken: { - name: `${cookiePrefix}next-auth.session-token`, - options: { - httpOnly: true, - sameSite: "lax", - path: "/", - secure: useSecureCookies, - }, - }, - callbackUrl: { - name: `${cookiePrefix}next-auth.callback-url`, - options: { - httpOnly: true, - sameSite: "lax", - path: "/", - secure: useSecureCookies, - }, - }, - csrfToken: { - // Default to __Host- for CSRF token for additional protection if using useSecureCookies - // NB: The `__Host-` prefix is stricter than the `__Secure-` prefix. - name: `${useSecureCookies ? "__Host-" : ""}next-auth.csrf-token`, - options: { - httpOnly: true, - sameSite: "lax", - path: "/", - secure: useSecureCookies, - }, - }, - pkceCodeVerifier: { - name: `${cookiePrefix}next-auth.pkce.code_verifier`, - options: { - httpOnly: true, - sameSite: "lax", - path: "/", - secure: useSecureCookies, - maxAge: 60 * 15, // 15 minutes in seconds - }, - }, - state: { - name: `${cookiePrefix}next-auth.state`, - options: { - httpOnly: true, - sameSite: "lax", - path: "/", - secure: useSecureCookies, - maxAge: 60 * 15, // 15 minutes in seconds - }, - }, - nonce: { - name: `${cookiePrefix}next-auth.nonce`, - options: { - httpOnly: true, - sameSite: "lax", - path: "/", - secure: useSecureCookies, - }, - } - } -} - -export interface Cookie extends CookieOption { - value: string -} - -type Chunks = Record - -export class SessionStore { - #chunks: Chunks = {} - #option: CookieOption - #logger: LoggerInstance | Console - - constructor( - option: CookieOption, - req: Partial<{ - cookies: NextRequest["cookies"] | NextApiRequest["cookies"] - headers: NextRequest["headers"] | NextApiRequest["headers"] - }>, - logger: LoggerInstance | Console - ) { - this.#logger = logger - this.#option = option - - const { cookies } = req - const { name: cookieName } = option - - if (typeof cookies?.getAll === "function") { - // Next.js ^v13.0.1 (Edge Env) - for (const { name, value } of cookies.getAll()) { - if (name.startsWith(cookieName)) { - this.#chunks[name] = value - } - } - } else if (cookies instanceof Map) { - for (const name of cookies.keys()) { - if (name.startsWith(cookieName)) this.#chunks[name] = cookies.get(name) - } - } else { - for (const name in cookies) { - if (name.startsWith(cookieName)) this.#chunks[name] = cookies[name] - } - } - } - - get value() { - return Object.values(this.#chunks)?.join("") - } - - /** Given a cookie, return a list of cookies, chunked to fit the allowed cookie size. */ - #chunk(cookie: Cookie): Cookie[] { - const chunkCount = Math.ceil(cookie.value.length / CHUNK_SIZE) - - if (chunkCount === 1) { - this.#chunks[cookie.name] = cookie.value - return [cookie] - } - - const cookies: Cookie[] = [] - for (let i = 0; i < chunkCount; i++) { - const name = `${cookie.name}.${i}` - const value = cookie.value.substr(i * CHUNK_SIZE, CHUNK_SIZE) - cookies.push({ ...cookie, name, value }) - this.#chunks[name] = value - } - - this.#logger.debug("CHUNKING_SESSION_COOKIE", { - message: `Session cookie exceeds allowed ${ALLOWED_COOKIE_SIZE} bytes.`, - emptyCookieSize: ESTIMATED_EMPTY_COOKIE_SIZE, - valueSize: cookie.value.length, - chunks: cookies.map((c) => c.value.length + ESTIMATED_EMPTY_COOKIE_SIZE), - }) - - return cookies - } - - /** Returns cleaned cookie chunks. */ - #clean(): Record { - const cleanedChunks: Record = {} - for (const name in this.#chunks) { - delete this.#chunks?.[name] - cleanedChunks[name] = { - name, - value: "", - options: { ...this.#option.options, maxAge: 0 }, - } - } - return cleanedChunks - } - - /** - * Given a cookie value, return new cookies, chunked, to fit the allowed cookie size. - * If the cookie has changed from chunked to unchunked or vice versa, - * it deletes the old cookies as well. - */ - chunk(value: string, options: Partial): Cookie[] { - // Assume all cookies should be cleaned by default - const cookies: Record = this.#clean() - - // Calculate new chunks - const chunked = this.#chunk({ - name: this.#option.name, - value, - options: { ...this.#option.options, ...options }, - }) - - // Update stored chunks / cookies - for (const chunk of chunked) { - cookies[chunk.name] = chunk - } - - return Object.values(cookies) - } - - /** Returns a list of cookies that should be cleaned. */ - clean(): Cookie[] { - return Object.values(this.#clean()) - } -} diff --git a/packages/next-auth/src/core/lib/csrf-token.ts b/packages/next-auth/src/core/lib/csrf-token.ts deleted file mode 100644 index cd614922..00000000 --- a/packages/next-auth/src/core/lib/csrf-token.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { createHash, randomBytes } from "crypto" - -import type { InternalOptions } from "../types" - -interface CreateCSRFTokenParams { - options: InternalOptions - cookieValue?: string - isPost: boolean - bodyValue?: string -} - -/** - * Ensure CSRF Token cookie is set for any subsequent requests. - * Used as part of the strategy for mitigation for CSRF tokens. - * - * Creates a cookie like 'next-auth.csrf-token' with the value 'token|hash', - * where 'token' is the CSRF token and 'hash' is a hash made of the token and - * the secret, and the two values are joined by a pipe '|'. By storing the - * value and the hash of the value (with the secret used as a salt) we can - * verify the cookie was set by the server and not by a malicous attacker. - * - * For more details, see the following OWASP links: - * https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie - * https://owasp.org/www-chapter-london/assets/slides/David_Johansson-Double_Defeat_of_Double-Submit_Cookie.pdf - */ -export function createCSRFToken({ - options, - cookieValue, - isPost, - bodyValue, -}: CreateCSRFTokenParams) { - if (cookieValue) { - const [csrfToken, csrfTokenHash] = cookieValue.split("|") - const expectedCsrfTokenHash = createHash("sha256") - .update(`${csrfToken}${options.secret}`) - .digest("hex") - if (csrfTokenHash === expectedCsrfTokenHash) { - // If hash matches then we trust the CSRF token value - // If this is a POST request and the CSRF Token in the POST request matches - // the cookie we have already verified is the one we have set, then the token is verified! - const csrfTokenVerified = isPost && csrfToken === bodyValue - - return { csrfTokenVerified, csrfToken } - } - } - - // New CSRF token - const csrfToken = randomBytes(32).toString("hex") - const csrfTokenHash = createHash("sha256") - .update(`${csrfToken}${options.secret}`) - .digest("hex") - const cookie = `${csrfToken}|${csrfTokenHash}` - - return { cookie, csrfToken } -} diff --git a/packages/next-auth/src/core/lib/default-callbacks.ts b/packages/next-auth/src/core/lib/default-callbacks.ts deleted file mode 100644 index d00298c7..00000000 --- a/packages/next-auth/src/core/lib/default-callbacks.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { CallbacksOptions } from "../.." - -export const defaultCallbacks: CallbacksOptions = { - signIn() { - return true - }, - redirect({ url, baseUrl }) { - if (url.startsWith("/")) return `${baseUrl}${url}` - else if (new URL(url).origin === baseUrl) return url - return baseUrl - }, - session({ session }) { - return session - }, - jwt({ token }) { - return token - }, -} diff --git a/packages/next-auth/src/core/lib/email/getUserFromEmail.ts b/packages/next-auth/src/core/lib/email/getUserFromEmail.ts deleted file mode 100644 index 2119c28c..00000000 --- a/packages/next-auth/src/core/lib/email/getUserFromEmail.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { AdapterUser } from "../../../adapters" -import type { InternalOptions } from "../../types" - -/** - * Query the database for a user by email address. - * If is an existing user return a user object (otherwise use placeholder). - */ -export default async function getAdapterUserFromEmail({ - email, - adapter, -}: { - email: string - adapter: InternalOptions<"email">["adapter"] -}): Promise { - const { getUserByEmail } = adapter - const adapterUser = email ? await getUserByEmail(email) : null - if (adapterUser) return adapterUser - - return { id: email, email, emailVerified: null } -} diff --git a/packages/next-auth/src/core/lib/email/signin.ts b/packages/next-auth/src/core/lib/email/signin.ts deleted file mode 100644 index fa4ba151..00000000 --- a/packages/next-auth/src/core/lib/email/signin.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { randomBytes } from "crypto" -import { hashToken } from "../utils" -import type { InternalOptions } from "../../types" - -/** - * Starts an e-mail login flow, by generating a token, - * and sending it to the user's e-mail (with the help of a DB adapter) - */ -export default async function email( - identifier: string, - options: InternalOptions<"email"> -): Promise { - const { url, adapter, provider, callbackUrl, theme } = options - // Generate token - const token = - (await provider.generateVerificationToken?.()) ?? - randomBytes(32).toString("hex") - - const ONE_DAY_IN_SECONDS = 86400 - const expires = new Date( - Date.now() + (provider.maxAge ?? ONE_DAY_IN_SECONDS) * 1000 - ) - - // Generate a link with email, unhashed token and callback url - const params = new URLSearchParams({ callbackUrl, token, email: identifier }) - const _url = `${url}/callback/${provider.id}?${params}` - - await Promise.all([ - // Send to user - provider.sendVerificationRequest({ - identifier, - token, - expires, - url: _url, - provider, - theme, - }), - // Save in database - adapter.createVerificationToken({ - identifier, - token: hashToken(token, options), - expires, - }), - ]) - - return `${url}/verify-request?${new URLSearchParams({ - provider: provider.id, - type: provider.type, - })}` -} diff --git a/packages/next-auth/src/core/lib/oauth/authorization-url.ts b/packages/next-auth/src/core/lib/oauth/authorization-url.ts deleted file mode 100644 index 0fc022f9..00000000 --- a/packages/next-auth/src/core/lib/oauth/authorization-url.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { openidClient } from "./client" -import { oAuth1Client, oAuth1TokenStore } from "./client-legacy" -import * as checks from "./checks" - -import type { AuthorizationParameters } from "openid-client" -import type { InternalOptions } from "../../types" -import type { RequestInternal } from "../.." -import type { Cookie } from "../cookie" - -/** - * - * Generates an authorization/request token URL. - * - * [OAuth 2](https://www.oauth.com/oauth2-servers/authorization/the-authorization-request/) | [OAuth 1](https://oauth.net/core/1.0a/#auth_step2) - */ -export default async function getAuthorizationUrl({ - options, - query, -}: { - options: InternalOptions<"oauth"> - query: RequestInternal["query"] -}) { - const { logger, provider } = options - let params: any = {} - - if (typeof provider.authorization === "string") { - const parsedUrl = new URL(provider.authorization) - const parsedParams = Object.fromEntries(parsedUrl.searchParams) - params = { ...params, ...parsedParams } - } else { - params = { ...params, ...provider.authorization?.params } - } - - params = { ...params, ...query } - - // Handle OAuth v1.x - if (provider.version?.startsWith("1.")) { - const client = oAuth1Client(options) - const tokens = (await client.getOAuthRequestToken(params)) as any - const url = `${provider.authorization?.url}?${new URLSearchParams({ - oauth_token: tokens.oauth_token, - oauth_token_secret: tokens.oauth_token_secret, - ...tokens.params, - })}` - oAuth1TokenStore.set(tokens.oauth_token, tokens.oauth_token_secret) - logger.debug("GET_AUTHORIZATION_URL", { url, provider }) - return { redirect: url } - } - - const client = await openidClient(options) - - const authorizationParams: AuthorizationParameters = params - const cookies: Cookie[] = [] - - await checks.state.create(options, cookies, authorizationParams) - await checks.pkce.create(options, cookies, authorizationParams) - await checks.nonce.create(options, cookies, authorizationParams) - - const url = client.authorizationUrl(authorizationParams) - - logger.debug("GET_AUTHORIZATION_URL", { url, cookies, provider }) - return { redirect: url, cookies } -} diff --git a/packages/next-auth/src/core/lib/oauth/callback.ts b/packages/next-auth/src/core/lib/oauth/callback.ts deleted file mode 100644 index 3038150b..00000000 --- a/packages/next-auth/src/core/lib/oauth/callback.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { TokenSet } from "openid-client" -import { openidClient } from "./client" -import { oAuth1Client, oAuth1TokenStore } from "./client-legacy" -import * as _checks from "./checks" -import { OAuthCallbackError } from "../../errors" - -import type { CallbackParamsType } from "openid-client" -import type { LoggerInstance, Profile } from "../../.." -import type { OAuthChecks, OAuthConfig } from "../../../providers" -import type { InternalOptions } from "../../types" -import type { RequestInternal } from "../.." -import type { Cookie } from "../cookie" - -export default async function oAuthCallback(params: { - options: InternalOptions<"oauth"> - query: RequestInternal["query"] - body: RequestInternal["body"] - method: Required["method"] - cookies: RequestInternal["cookies"] -}) { - const { options, query, body, method, cookies } = params - const { logger, provider } = options - - const errorMessage = body?.error ?? query?.error - if (errorMessage) { - const error = new Error(errorMessage) - logger.error("OAUTH_CALLBACK_HANDLER_ERROR", { - error, - error_description: query?.error_description, - providerId: provider.id, - }) - logger.debug("OAUTH_CALLBACK_HANDLER_ERROR", { body }) - throw error - } - - if (provider.version?.startsWith("1.")) { - try { - const client = await oAuth1Client(options) - // Handle OAuth v1.x - const { oauth_token, oauth_verifier } = query ?? {} - const tokens = (await (client as any).getOAuthAccessToken( - oauth_token, - oAuth1TokenStore.get(oauth_token), - oauth_verifier - )) as TokenSet - let profile: Profile = await (client as any).get( - provider.profileUrl, - tokens.oauth_token, - tokens.oauth_token_secret - ) - - if (typeof profile === "string") { - profile = JSON.parse(profile) - } - - const newProfile = await getProfile({ profile, tokens, provider, logger }) - return { ...newProfile, cookies: [] } - } catch (error) { - logger.error("OAUTH_V1_GET_ACCESS_TOKEN_ERROR", error as Error) - throw error - } - } - - if (query?.oauth_token) oAuth1TokenStore.delete(query.oauth_token) - - try { - const client = await openidClient(options) - - let tokens: TokenSet - - const checks: OAuthChecks = {} - const resCookies: Cookie[] = [] - - await _checks.state.use(cookies, resCookies, options, checks) - await _checks.pkce.use(cookies, resCookies, options, checks) - await _checks.nonce.use(cookies, resCookies, options, checks) - - const params: CallbackParamsType = { - ...client.callbackParams({ - url: `http://n?${new URLSearchParams(query)}`, - // TODO: Ask to allow object to be passed upstream: - // https://github.com/panva/node-openid-client/blob/3ae206dfc78c02134aa87a07f693052c637cab84/types/index.d.ts#L439 - // @ts-expect-error - body, - method, - }), - ...provider.token?.params, - } - - if (provider.token?.request) { - const response = await provider.token.request({ - provider, - params, - checks, - client, - }) - tokens = new TokenSet(response.tokens) - } else if (provider.idToken) { - tokens = await client.callback(provider.callbackUrl, params, checks) - } else { - tokens = await client.oauthCallback(provider.callbackUrl, params, checks) - } - - // REVIEW: How can scope be returned as an array? - if (Array.isArray(tokens.scope)) { - tokens.scope = tokens.scope.join(" ") - } - - let profile: Profile - if (provider.userinfo?.request) { - profile = await provider.userinfo.request({ - provider, - tokens, - client, - }) - } else if (provider.idToken) { - profile = tokens.claims() - } else { - profile = await client.userinfo(tokens, { - params: provider.userinfo?.params, - }) - } - - const profileResult = await getProfile({ - profile, - provider, - tokens, - logger, - }) - return { ...profileResult, cookies: resCookies } - } catch (error) { - throw new OAuthCallbackError(error as Error) - } -} - -export interface GetProfileParams { - profile: Profile - tokens: TokenSet - provider: OAuthConfig - logger: LoggerInstance -} - -/** Returns profile, raw profile and auth provider details */ -async function getProfile({ - profile: OAuthProfile, - tokens, - provider, - logger, -}: GetProfileParams) { - try { - logger.debug("PROFILE_DATA", { OAuthProfile }) - const profile = await provider.profile(OAuthProfile, tokens) - profile.email = profile.email?.toLowerCase() - if (!profile.id) - throw new TypeError( - `Profile id is missing in ${provider.name} OAuth profile response` - ) - - // Return profile, raw profile and auth provider details - return { - profile, - account: { - provider: provider.id, - type: provider.type, - providerAccountId: profile.id.toString(), - ...tokens, - }, - OAuthProfile, - } - } catch (error) { - // If we didn't get a response either there was a problem with the provider - // response *or* the user cancelled the action with the provider. - // - // Unfortuately, we can't tell which - at least not in a way that works for - // all providers, so we return an empty object; the user should then be - // redirected back to the sign up page. We log the error to help developers - // who might be trying to debug this when configuring a new provider. - logger.error("OAUTH_PARSE_PROFILE_ERROR", { - error: error as Error, - OAuthProfile, - }) - } -} diff --git a/packages/next-auth/src/core/lib/oauth/checks.ts b/packages/next-auth/src/core/lib/oauth/checks.ts deleted file mode 100644 index f4970126..00000000 --- a/packages/next-auth/src/core/lib/oauth/checks.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { - AuthorizationParameters, - generators, - OpenIDCallbackChecks, -} from "openid-client" -import * as jwt from "../../../jwt" - -import type { RequestInternal } from "../.." -import type { OAuthChecks } from "../../../providers" -import type { CookiesOptions, InternalOptions } from "../../types" -import type { Cookie } from "../cookie" - -/** Returns a signed cookie. */ -export async function signCookie( - type: keyof CookiesOptions, - value: string, - maxAge: number, - options: InternalOptions<"oauth"> -): Promise { - const { cookies, logger } = options - - logger.debug(`CREATE_${type.toUpperCase()}`, { value, maxAge }) - - const expires = new Date() - expires.setTime(expires.getTime() + maxAge * 1000) - return { - name: cookies[type].name, - value: await jwt.encode({ ...options.jwt, maxAge, token: { value } }), - options: { ...cookies[type].options, expires }, - } -} - -const PKCE_MAX_AGE = 60 * 15 // 15 minutes in seconds -export const PKCE_CODE_CHALLENGE_METHOD = "S256" -export const pkce = { - async create( - options: InternalOptions<"oauth">, - cookies: Cookie[], - resParams: AuthorizationParameters - ) { - if (!options.provider?.checks?.includes("pkce")) return - const code_verifier = generators.codeVerifier() - const value = generators.codeChallenge(code_verifier) - resParams.code_challenge = value - resParams.code_challenge_method = PKCE_CODE_CHALLENGE_METHOD - - const maxAge = - options.cookies.pkceCodeVerifier.options.maxAge ?? PKCE_MAX_AGE - - cookies.push( - await signCookie("pkceCodeVerifier", code_verifier, maxAge, options) - ) - }, - /** - * Returns code_verifier if the provider is configured to use PKCE, - * and clears the container cookie afterwards. - * An error is thrown if the code_verifier is missing or invalid. - * @see https://www.rfc-editor.org/rfc/rfc7636 - * @see https://danielfett.de/2020/05/16/pkce-vs-nonce-equivalent-or-not/#pkce - */ - async use( - cookies: RequestInternal["cookies"], - resCookies: Cookie[], - options: InternalOptions<"oauth">, - checks: OAuthChecks - ): Promise { - if (!options.provider?.checks?.includes("pkce")) return - - const codeVerifier = cookies?.[options.cookies.pkceCodeVerifier.name] - - if (!codeVerifier) - throw new TypeError("PKCE code_verifier cookie was missing.") - - const value = (await jwt.decode({ - ...options.jwt, - token: codeVerifier, - })) as any - - if (!value?.value) - throw new TypeError("PKCE code_verifier value could not be parsed.") - - resCookies.push({ - name: options.cookies.pkceCodeVerifier.name, - value: "", - options: { ...options.cookies.pkceCodeVerifier.options, maxAge: 0 }, - }) - - checks.code_verifier = value.value - }, -} - -const STATE_MAX_AGE = 60 * 15 // 15 minutes in seconds -export const state = { - async create( - options: InternalOptions<"oauth">, - cookies: Cookie[], - resParams: AuthorizationParameters - ) { - if (!options.provider.checks?.includes("state")) return - const value = generators.state() - resParams.state = value - const maxAge = options.cookies.state.options.maxAge ?? STATE_MAX_AGE - cookies.push(await signCookie("state", value, maxAge, options)) - }, - /** - * Returns state if the provider is configured to use state, - * and clears the container cookie afterwards. - * An error is thrown if the state is missing or invalid. - * @see https://www.rfc-editor.org/rfc/rfc6749#section-10.12 - * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1 - */ - async use( - cookies: RequestInternal["cookies"], - resCookies: Cookie[], - options: InternalOptions<"oauth">, - checks: OAuthChecks - ) { - if (!options.provider.checks?.includes("state")) return - - const state = cookies?.[options.cookies.state.name] - - if (!state) throw new TypeError("State cookie was missing.") - - const value = (await jwt.decode({ ...options.jwt, token: state })) as any - - if (!value?.value) throw new TypeError("State value could not be parsed.") - - resCookies.push({ - name: options.cookies.state.name, - value: "", - options: { ...options.cookies.state.options, maxAge: 0 }, - }) - - checks.state = value.value - }, -} - -const NONCE_MAX_AGE = 60 * 15 // 15 minutes in seconds -export const nonce = { - async create( - options: InternalOptions<"oauth">, - cookies: Cookie[], - resParams: AuthorizationParameters - ) { - if (!options.provider.checks?.includes("nonce")) return - const value = generators.nonce() - resParams.nonce = value - const maxAge = options.cookies.nonce.options.maxAge ?? NONCE_MAX_AGE - cookies.push(await signCookie("nonce", value, maxAge, options)) - }, - /** - * Returns nonce if the provider is configured to use nonce, - * and clears the container cookie afterwards. - * An error is thrown if the nonce is missing or invalid. - * @see https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes - * @see https://danielfett.de/2020/05/16/pkce-vs-nonce-equivalent-or-not/#nonce - */ - async use( - cookies: RequestInternal["cookies"], - resCookies: Cookie[], - options: InternalOptions<"oauth">, - checks: OpenIDCallbackChecks - ): Promise { - if (!options.provider?.checks?.includes("nonce")) return - - const nonce = cookies?.[options.cookies.nonce.name] - if (!nonce) throw new TypeError("Nonce cookie was missing.") - - const value = (await jwt.decode({ ...options.jwt, token: nonce })) as any - - if (!value?.value) throw new TypeError("Nonce value could not be parsed.") - - resCookies.push({ - name: options.cookies.nonce.name, - value: "", - options: { ...options.cookies.nonce.options, maxAge: 0 }, - }) - - checks.nonce = value.value - }, -} diff --git a/packages/next-auth/src/core/lib/oauth/client-legacy.ts b/packages/next-auth/src/core/lib/oauth/client-legacy.ts deleted file mode 100644 index 6716fb27..00000000 --- a/packages/next-auth/src/core/lib/oauth/client-legacy.ts +++ /dev/null @@ -1,73 +0,0 @@ -// This is kept around for being backwards compatible with OAuth 1.0 providers. -// We have the intentions to provide only minor fixes for this in the future. - -import { OAuth } from "oauth" -import type { InternalOptions } from "../../types" - -/** - * Client supporting OAuth 1.x - */ -export function oAuth1Client(options: InternalOptions<"oauth">) { - const provider = options.provider - - const oauth1Client = new OAuth( - provider.requestTokenUrl as string, - provider.accessTokenUrl as string, - provider.clientId as string, - provider.clientSecret as string, - provider.version ?? "1.0", - provider.callbackUrl, - provider.encoding ?? "HMAC-SHA1" - ) - - // Promisify get() for OAuth1 - const originalGet = oauth1Client.get.bind(oauth1Client) - // @ts-expect-error - oauth1Client.get = async (...args) => { - return await new Promise((resolve, reject) => { - originalGet(...args, (error, result) => { - if (error) { - return reject(error) - } - resolve(result) - }) - }) - } - // Promisify getOAuth1AccessToken() for OAuth1 - const originalGetOAuth1AccessToken = - oauth1Client.getOAuthAccessToken.bind(oauth1Client) - // eslint-disable-next-line @typescript-eslint/no-misused-promises - oauth1Client.getOAuthAccessToken = async (...args: any[]) => { - return await new Promise((resolve, reject) => { - originalGetOAuth1AccessToken( - ...args, - (error: any, oauth_token: any, oauth_token_secret: any) => { - if (error) { - return reject(error) - } - resolve({ oauth_token, oauth_token_secret } as any) - } - ) - }) - } - - const originalGetOAuthRequestToken = - oauth1Client.getOAuthRequestToken.bind(oauth1Client) - // eslint-disable-next-line @typescript-eslint/no-misused-promises - oauth1Client.getOAuthRequestToken = async (params = {}) => { - return await new Promise((resolve, reject) => { - originalGetOAuthRequestToken( - params, - (error, oauth_token, oauth_token_secret, params) => { - if (error) { - return reject(error) - } - resolve({ oauth_token, oauth_token_secret, params } as any) - } - ) - }) - } - return oauth1Client -} - -export const oAuth1TokenStore = new Map() diff --git a/packages/next-auth/src/core/lib/oauth/client.ts b/packages/next-auth/src/core/lib/oauth/client.ts deleted file mode 100644 index f00e1b90..00000000 --- a/packages/next-auth/src/core/lib/oauth/client.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { Issuer, custom } from "openid-client" -import type { Client } from "openid-client" -import type { InternalOptions } from "../../types" - -/** - * NOTE: We can add auto discovery of the provider's endpoint - * that requires only one endpoint to be specified by the user. - * Check out `Issuer.discover` - * - * Client supporting OAuth 2.x and OIDC - */ -export async function openidClient( - options: InternalOptions<"oauth"> -): Promise { - const provider = options.provider - - if (provider.httpOptions) custom.setHttpOptionsDefaults(provider.httpOptions) - - let issuer: Issuer - if (provider.wellKnown) { - issuer = await Issuer.discover(provider.wellKnown) - } else { - issuer = new Issuer({ - issuer: provider.issuer as string, - authorization_endpoint: provider.authorization?.url, - token_endpoint: provider.token?.url, - userinfo_endpoint: provider.userinfo?.url, - jwks_uri: provider.jwks_endpoint, - }) - } - - const client = new issuer.Client( - { - client_id: provider.clientId as string, - client_secret: provider.clientSecret as string, - redirect_uris: [provider.callbackUrl], - ...provider.client, - }, - provider.jwks - ) - - // allow a 10 second skew - // See https://github.com/nextauthjs/next-auth/issues/3032 - // and https://github.com/nextauthjs/next-auth/issues/3067 - client[custom.clock_tolerance] = 10 - - return client -} diff --git a/packages/next-auth/src/core/lib/providers.ts b/packages/next-auth/src/core/lib/providers.ts deleted file mode 100644 index 57769905..00000000 --- a/packages/next-auth/src/core/lib/providers.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { merge } from "../../utils/merge" - -import type { InternalProvider, OAuthConfigInternal } from "../types" -import type { OAuthConfig, Provider } from "../../providers" -import type { InternalUrl } from "../../utils/parse-url" - -/** - * Adds `signinUrl` and `callbackUrl` to each provider - * and deep merge user-defined options. - */ -export default function parseProviders(params: { - providers: Provider[] - url: InternalUrl - providerId?: string -}): { - providers: InternalProvider[] - provider?: InternalProvider -} { - const { url, providerId } = params - - const providers = params.providers.map( - ({ options: userOptions, ...rest }) => { - if (rest.type === "oauth") { - const normalizedOptions = normalizeOAuthOptions(rest) - const normalizedUserOptions = normalizeOAuthOptions(userOptions, true) - const id = normalizedUserOptions?.id ?? rest.id - return merge(normalizedOptions, { - ...normalizedUserOptions, - signinUrl: `${url}/signin/${id}`, - callbackUrl: `${url}/callback/${id}`, - }) - } - const id = (userOptions?.id as string) ?? rest.id - return merge(rest, { - ...userOptions, - signinUrl: `${url}/signin/${id}`, - callbackUrl: `${url}/callback/${id}`, - }) - } - ) - - return { - providers, - provider: providers.find(({ id }) => id === providerId), - } -} - -/** - * Transform OAuth options `authorization`, `token` and `profile` strings to `{ url: string; params: Record }` - */ -function normalizeOAuthOptions( - oauthOptions?: Partial> | Record, - isUserOptions = false -) { - if (!oauthOptions) return - - const normalized = Object.entries(oauthOptions).reduce< - OAuthConfigInternal> - >( - (acc, [key, value]) => { - if ( - ["authorization", "token", "userinfo"].includes(key) && - typeof value === "string" - ) { - const url = new URL(value) - acc[key] = { - url: `${url.origin}${url.pathname}`, - params: Object.fromEntries(url.searchParams ?? []), - } - } else { - acc[key] = value - } - - return acc - }, - // eslint-disable-next-line @typescript-eslint/prefer-reduce-type-parameter - {} as any - ) - - if (!isUserOptions && !normalized.version?.startsWith("1.")) { - // If provider has as an "openid-configuration" well-known endpoint - // or an "openid" scope request, it will also likely be able to receive an `id_token` - // Only do this if this function is not called with user options to avoid overriding in later stage. - normalized.idToken = Boolean( - normalized.idToken ?? - normalized.wellKnown?.includes("openid-configuration") ?? - normalized.authorization?.params?.scope?.includes("openid") - ) - - if (!normalized.checks) normalized.checks = ["state"] - } - return normalized -} diff --git a/packages/next-auth/src/core/lib/utils.ts b/packages/next-auth/src/core/lib/utils.ts deleted file mode 100644 index c8296a76..00000000 --- a/packages/next-auth/src/core/lib/utils.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { createHash } from "crypto" - -import type { AuthOptions } from "../.." -import type { InternalOptions } from "../types" -import type { InternalUrl } from "../../utils/parse-url" - -/** - * Takes a number in seconds and returns the date in the future. - * Optionally takes a second date parameter. In that case - * the date in the future will be calculated from that date instead of now. - */ -export function fromDate(time: number, date = Date.now()) { - return new Date(date + time * 1000) -} - -export function hashToken(token: string, options: InternalOptions<"email">) { - const { provider, secret } = options - return ( - createHash("sha256") - // Prefer provider specific secret, but use default secret if none specified - .update(`${token}${provider.secret ?? secret}`) - .digest("hex") - ) -} - -/** - * Secret used salt cookies and tokens (e.g. for CSRF protection). - * If no secret option is specified then it creates one on the fly - * based on options passed here. If options contains unique data, such as - * OAuth provider secrets and database credentials it should be sufficent. If no secret provided in production, we throw an error. */ -export function createSecret(params: { - authOptions: AuthOptions - url: InternalUrl -}) { - const { authOptions, url } = params - - return ( - authOptions.secret ?? - // TODO: Remove falling back to default secret, and error in dev if one isn't provided - createHash("sha256") - .update(JSON.stringify({ ...url, ...authOptions })) - .digest("hex") - ) -} diff --git a/packages/next-auth/src/core/pages/error.tsx b/packages/next-auth/src/core/pages/error.tsx deleted file mode 100644 index ee78e458..00000000 --- a/packages/next-auth/src/core/pages/error.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import { Theme } from "../.." -import { InternalUrl } from "../../utils/parse-url" - -/** - * The following errors are passed as error query parameters to the default or overridden error page. - * - * [Documentation](https://next-auth.js.org/configuration/pages#error-page) */ -export type ErrorType = - | "default" - | "configuration" - | "accessdenied" - | "verification" - -export interface ErrorProps { - url?: InternalUrl - theme?: Theme - error?: ErrorType -} - -interface ErrorView { - status: number - heading: string - message: JSX.Element - signin?: JSX.Element -} - -/** Renders an error page. */ -export default function ErrorPage(props: ErrorProps) { - const { url, error = "default", theme } = props - const signinPageUrl = `${url}/signin` - - const errors: Record = { - default: { - status: 200, - heading: "Error", - message: ( -

- - {url?.host} - -

- ), - }, - configuration: { - status: 500, - heading: "Server error", - message: ( -
-

There is a problem with the server configuration.

-

Check the server logs for more information.

-
- ), - }, - accessdenied: { - status: 403, - heading: "Access Denied", - message: ( -
-

You do not have permission to sign in.

-

- - Sign in - -

-
- ), - }, - verification: { - status: 403, - heading: "Unable to sign in", - message: ( -
-

The sign in link is no longer valid.

-

It may have been used already or it may have expired.

-
- ), - signin: ( -

- - Sign in - -

- ), - }, - } - - const { status, heading, message, signin } = - errors[error.toLowerCase()] ?? errors.default - - return { - status, - html: ( -
- {theme?.brandColor && ( - ${title}
${renderToString(html)}
`, - } - } - - return { - signin(props?: any) { - return send({ - html: SigninPage({ - csrfToken: params.csrfToken, - providers: params.providers, - callbackUrl: params.callbackUrl, - theme, - ...query, - ...props, - }), - title: "Sign In", - }) - }, - signout(props?: any) { - return send({ - html: SignoutPage({ - csrfToken: params.csrfToken, - url, - theme, - ...props, - }), - title: "Sign Out", - }) - }, - verifyRequest(props?: any) { - return send({ - html: VerifyRequestPage({ url, theme, ...props }), - title: "Verify Request", - }) - }, - error(props?: { error?: ErrorType }) { - return send({ - ...ErrorPage({ url, theme, ...props }), - title: "Error", - }) - }, - } -} diff --git a/packages/next-auth/src/core/pages/signin.tsx b/packages/next-auth/src/core/pages/signin.tsx deleted file mode 100644 index 2ad59a72..00000000 --- a/packages/next-auth/src/core/pages/signin.tsx +++ /dev/null @@ -1,222 +0,0 @@ -import type { InternalProvider, Theme } from "../types" -import type React from "react" - -/** - * The following errors are passed as error query parameters to the default or overridden sign-in page. - * - * [Documentation](https://next-auth.js.org/configuration/pages#sign-in-page) */ -export type SignInErrorTypes = - | "Signin" - | "OAuthSignin" - | "OAuthCallback" - | "OAuthCreateAccount" - | "EmailCreateAccount" - | "Callback" - | "OAuthAccountNotLinked" - | "EmailSignin" - | "CredentialsSignin" - | "SessionRequired" - | "default" - -export interface SignInServerPageParams { - csrfToken: string - providers: InternalProvider[] - callbackUrl: string - email: string - error: SignInErrorTypes - theme: Theme -} - -export default function SigninPage(props: SignInServerPageParams) { - const { - csrfToken, - providers, - callbackUrl, - theme, - email, - error: errorType, - } = props - // We only want to render providers - const providersToRender = providers.filter((provider) => { - if (provider.type === "oauth" || provider.type === "email") { - // Always render oauth and email type providers - return true - } else if (provider.type === "credentials" && provider.credentials) { - // Only render credentials type provider if credentials are defined - return true - } - // Don't render other provider types - return false - }) - - if (typeof document !== "undefined" && theme.buttonText) { - document.documentElement.style.setProperty( - "--button-text-color", - theme.buttonText - ) - } - - if (typeof document !== "undefined" && theme.brandColor) { - document.documentElement.style.setProperty( - "--brand-color", - theme.brandColor - ) - } - - const errors: Record = { - Signin: "Try signing in with a different account.", - OAuthSignin: "Try signing in with a different account.", - OAuthCallback: "Try signing in with a different account.", - OAuthCreateAccount: "Try signing in with a different account.", - EmailCreateAccount: "Try signing in with a different account.", - Callback: "Try signing in with a different account.", - OAuthAccountNotLinked: - "To confirm your identity, sign in with the same account you used originally.", - EmailSignin: "The e-mail could not be sent.", - CredentialsSignin: - "Sign in failed. Check the details you provided are correct.", - SessionRequired: "Please sign in to access this page.", - default: "Unable to sign in.", - } - - const error = errorType && (errors[errorType] ?? errors.default) - - const logos = "https://authjs.dev/img/providers" - return ( -
- {theme.brandColor && ( -