From 78b7b36884fd0c27562cfddbff5d77e88bea85db Mon Sep 17 00:00:00 2001 From: Tevin Flores Date: Sun, 23 Mar 2025 20:15:06 -0400 Subject: [PATCH 1/2] Implemented feature adding oidc --- jellyseerr-api.yml | 103 ++++ scripts/add-oidc-column.ts | 39 ++ scripts/check-oidc-column.ts | 28 + server/constants/user.ts | 1 + server/entity/User.ts | 3 + server/interfaces/api/oidcInterfaces.ts | 221 +++++++ server/interfaces/api/settingsInterfaces.ts | 3 + server/lib/settings/index.ts | 30 + server/migration/add-oidc.sql | 1 + server/routes/auth.ts | 185 ++++++ server/routes/settings/index.ts | 81 ++- server/utils/oidc.ts | 280 +++++++++ src/components/Login/ErrorCallout.tsx | 25 + src/components/Login/OidcLogin.tsx | 87 +++ src/components/Login/index.tsx | 17 +- src/components/Settings/OidcModal/index.tsx | 547 ++++++++++++++++++ .../Settings/SettingsUsers/index.tsx | 75 ++- src/context/SettingsContext.tsx | 3 + src/i18n/globalMessages.ts | 2 + src/pages/_app.tsx | 3 + src/pages/login/oidc/callback.tsx | 52 ++ src/utils/oidc.ts | 64 ++ src/utils/popupWindow.ts | 66 +++ 23 files changed, 1909 insertions(+), 7 deletions(-) create mode 100644 scripts/add-oidc-column.ts create mode 100644 scripts/check-oidc-column.ts create mode 100644 server/interfaces/api/oidcInterfaces.ts create mode 100644 server/migration/add-oidc.sql create mode 100644 server/utils/oidc.ts create mode 100644 src/components/Login/ErrorCallout.tsx create mode 100644 src/components/Login/OidcLogin.tsx create mode 100644 src/components/Settings/OidcModal/index.tsx create mode 100644 src/pages/login/oidc/callback.tsx create mode 100644 src/utils/oidc.ts create mode 100644 src/utils/popupWindow.ts diff --git a/jellyseerr-api.yml b/jellyseerr-api.yml index 00b0959686..b38eb2520f 100644 --- a/jellyseerr-api.yml +++ b/jellyseerr-api.yml @@ -149,6 +149,36 @@ components: type: string streamingRegion: type: string + OidcSettings: + type: object + properties: + providerName: + type: string + example: Keycloak + providerUrl: + type: string + example: https://auth.example.com + clientId: + type: string + example: your-client-id + clientSecret: + type: string + example: your-client-secret + userIdentifier: + type: string + example: email + requiredClaims: + type: string + example: email_verified + scopes: + type: string + example: id email + matchJellyfinUsername: + type: boolean + example: false + automaticLogin: + type: boolean + example: false MainSettings: type: object properties: @@ -3782,6 +3812,79 @@ paths: type: string required: - password + /auth/oidc-login: + get: + security: [] + summary: Redirect to the OpenID Connect provider + description: Constructs the redirect URL to the OpenID Connect provider, and redirects the user to it. + tags: + - auth + responses: + '302': + description: Redirect to the authentication url for the OpenID Connect provider + headers: + Location: + schema: + type: string + example: https://example.com/auth/oidc/callback?response_type=code&client_id=client_id&redirect_uri=https%3A%2F%2Fexample.com%2Fauth%2Foidc%2Fcallback&scope=openid%20email&state=state + Set-Cookie: + schema: + type: string + example: 'oidc-state=123456789; HttpOnly; max-age=60000; Secure' + /auth/oidc-callback: + get: + security: [] + summary: The callback endpoint for the OpenID Connect provider redirect + description: Takes the `code` and `state` parameters from the OpenID Connect provider, and exchanges them for a token. + x-allow-unknown-query-parameters: true + parameters: + - in: query + name: code + required: true + schema: + type: string + example: '123456789' + - in: query + name: state + required: true + schema: + type: string + example: '123456789' + - in: cookie + name: oidc-state + required: true + schema: + type: string + example: '123456789' + tags: + - auth + responses: + '302': + description: A redirect to the home page if successful or back to the login page if not + headers: + Location: + schema: + type: string + example: / + Set-Cookie: + schema: + type: string + example: 'oidc-state=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT' + /auth/oidc-logout: + get: + security: [] + summary: Redirect to the OpenID Connect provider logout page + description: Determines the logout redirect URL for to the OpenID Connect provider, and redirects the user to it. + tags: + - auth + responses: + '302': + description: Redirect to the logout url for the OpenID Connect provider + headers: + Location: + schema: + type: string + example: https://example.com/auth/oidc/invalidate_session /user: get: summary: Get all users diff --git a/scripts/add-oidc-column.ts b/scripts/add-oidc-column.ts new file mode 100644 index 0000000000..8d5ef65a05 --- /dev/null +++ b/scripts/add-oidc-column.ts @@ -0,0 +1,39 @@ +import Database from 'better-sqlite3'; +import path from 'path'; + +try { + const db = new Database(path.join(process.cwd(), 'config/db/db.sqlite3')); + + // Check if column exists + const columnExists = db.prepare(` + SELECT COUNT(*) as count + FROM pragma_table_info('user') + WHERE name = 'oidcId' + `).get().count > 0; + + if (columnExists) { + console.log('oidcId column already exists in user table'); + db.close(); + process.exit(0); + } + + // Create backup + db.backup(path.join(process.cwd(), 'config/db/db.sqlite3.backup')) + .then(() => { + console.log('Database backup created'); + + // Add the column + db.exec('ALTER TABLE user ADD COLUMN oidcId VARCHAR;'); + console.log('Added oidcId column to user table'); + + db.close(); + }) + .catch((err) => { + console.error('Backup failed:', err); + db.close(); + process.exit(1); + }); +} catch (err) { + console.error('Failed to modify database:', err); + process.exit(1); +} diff --git a/scripts/check-oidc-column.ts b/scripts/check-oidc-column.ts new file mode 100644 index 0000000000..3c8ce2262c --- /dev/null +++ b/scripts/check-oidc-column.ts @@ -0,0 +1,28 @@ +import Database from 'better-sqlite3'; +import path from 'path'; + +try { + const db = new Database(path.join(process.cwd(), 'config/db/db.sqlite3')); + + // Get table info + const tableInfo = db.prepare(` + SELECT * FROM pragma_table_info('user') + `).all(); + + console.log('User table structure:'); + console.table(tableInfo); + + // Check for any existing OIDC users + const oidcUsers = db.prepare(` + SELECT id, email, oidcId + FROM user + WHERE oidcId IS NOT NULL + `).all(); + + console.log('\nOIDC Users:', oidcUsers.length ? oidcUsers : 'None found'); + + db.close(); +} catch (err) { + console.error('Failed to read database:', err); + process.exit(1); +} diff --git a/server/constants/user.ts b/server/constants/user.ts index 90b33dc8d3..f9dcbd45a8 100644 --- a/server/constants/user.ts +++ b/server/constants/user.ts @@ -3,4 +3,5 @@ export enum UserType { LOCAL = 2, JELLYFIN = 3, EMBY = 4, + OIDC = 5 // Add this line } diff --git a/server/entity/User.ts b/server/entity/User.ts index 91b6674037..d582e75e32 100644 --- a/server/entity/User.ts +++ b/server/entity/User.ts @@ -140,6 +140,9 @@ export class User { public warnings: string[] = []; + @Column({ nullable: true }) + public oidcId?: string; + constructor(init?: Partial) { Object.assign(this, init); } diff --git a/server/interfaces/api/oidcInterfaces.ts b/server/interfaces/api/oidcInterfaces.ts new file mode 100644 index 0000000000..75c1833b8d --- /dev/null +++ b/server/interfaces/api/oidcInterfaces.ts @@ -0,0 +1,221 @@ +/** + * @internal + */ +type Mandatory = Required> & Omit; + +/** + * Standard OpenID Connect discovery document. + * + * @public + * @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +export interface OidcProviderMetadata { + issuer: string; // REQUIRED + + authorization_endpoint: string; // REQUIRED + + token_endpoint: string; // REQUIRED + + token_endpoint_auth_methods_supported?: string[]; // OPTIONAL + + token_endpoint_auth_signing_alg_values_supported?: string[]; // OPTIONAL + + userinfo_endpoint: string; // RECOMMENDED + + check_session_iframe: string; // REQUIRED + + end_session_endpoint: string; // REQUIRED + + jwks_uri: string; // REQUIRED + + registration_endpoint: string; // RECOMMENDED + + scopes_supported: string[]; // RECOMMENDED + + response_types_supported: string[]; // REQUIRED + + acr_values_supported?: string[]; // OPTIONAL + + subject_types_supported: string[]; // REQUIRED + + request_object_signing_alg_values_supported?: string[]; // OPTIONAL + + display_values_supported?: string[]; // OPTIONAL + + claim_types_supported?: string[]; // OPTIONAL + + claims_supported: string[]; // RECOMMENDED + + claims_parameter_supported?: boolean; // OPTIONAL + + service_documentation?: string; // OPTIONAL + + ui_locales_supported?: string[]; // OPTIONAL + + revocation_endpoint: string; // REQUIRED + + introspection_endpoint: string; // REQUIRED + + frontchannel_logout_supported?: boolean; // OPTIONAL + + frontchannel_logout_session_supported?: boolean; // OPTIONAL + + backchannel_logout_supported?: boolean; // OPTIONAL + + backchannel_logout_session_supported?: boolean; // OPTIONAL + + grant_types_supported?: string[]; // OPTIONAL + + response_modes_supported?: string[]; // OPTIONAL + + code_challenge_methods_supported?: string[]; // OPTIONAL +} + +/** + * Standard OpenID Connect address claim. + * The Address Claim represents a physical mailing address. + * + * @public + * @see https://openid.net/specs/openid-connect-core-1_0.html#AddressClaim + */ +export interface OidcAddressClaim { + /** Full mailing address, formatted for display or use on a mailing label. This field MAY contain multiple lines, separated by newlines. Newlines can be represented either as a carriage return/line feed pair ("\\r\\n") or as a single line feed character ("\\n"). */ + formatted?: string; + /** Full street address component, which MAY include house number, street name, Post Office Box, and multi-line extended street address information. This field MAY contain multiple lines, separated by newlines. Newlines can be represented either as a carriage return/line feed pair ("\\r\\n") or as a single line feed character ("\\n"). */ + street_address?: string; + /** City or locality component. */ + locality?: string; + /** State, province, prefecture, or region component. */ + region?: string; + /** Zip code or postal code component. */ + postal_code?: string; + /** Country name component. */ + country?: string; +} + +/** + * Standard OpenID Connect claims. + * They can be requested to be returned either in the UserInfo Response or in the ID Token. + * + * @public + * @see https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims + */ +export interface OidcStandardClaims { + /** Subject - Identifier for the End-User at the Issuer. */ + sub?: string; + /** End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences. */ + name?: string; + /** Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters. */ + given_name?: string; + /** Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters. */ + family_name?: string; + /** Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used. */ + middle_name?: string; + /** Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael. */ + nickname?: string; + /** Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as \@, /, or whitespace. */ + preferred_username?: string; + /** URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User. */ + profile?: string; + /** URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User. */ + picture?: string; + /** URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with. */ + website?: string; + /** End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 addr-spec syntax. */ + email?: string; + /** True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. */ + email_verified?: boolean; + /** End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable. */ + gender?: string; + /** End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates. */ + birthdate?: string; + /** String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles. */ + zoneinfo?: string; + /** End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639-1 Alpha-2 [ISO639‑1] language code in lowercase and an ISO 3166-1 Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; */ + locale?: string; + /** End-User's preferred telephone number. E.164 [E.164] is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678. */ + phone_number?: string; + /** True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed. The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format. */ + phone_number_verified?: boolean; + /** End-User's preferred postal address. The value of the address member is a JSON [RFC4627] structure containing some or all of the members defined in Section 5.1.1. */ + address?: OidcAddressClaim; + /** Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. */ + updated_at?: number; +} + +/** + * Standard JWT claims. + * + * @public + * @see https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 + */ +export interface JwtClaims { + [claim: string]: unknown; + + /** The "iss" (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The "iss" value is a case-sensitive string containing a StringOrURI value. */ + iss?: string; + /** The "sub" (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The "sub" value is a case-sensitive string containing a StringOrURI value. */ + sub?: string; + /** The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case-sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. */ + aud?: string | string[]; + /** The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the expiration date/time listed in the "exp" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. */ + exp?: number; + /** The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the "nbf" claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the "nbf" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. */ + nbf?: number; + /** The "iat" (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. */ + iat?: number; + /** The "jti" (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The "jti" claim can be used to prevent the JWT from being replayed. The "jti" value is a case-sensitive string. */ + jti?: string; +} + +/** + * Standard ID Token claims. + * + * @public + * @see https://openid.net/specs/openid-connect-core-1_0.html#IDToken + */ +export interface IdTokenClaims + extends Mandatory, + Mandatory { + [claim: string]: unknown; + + /** Time when the End-User authentication occurred. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. When a max_age request is made or when auth_time is requested as an Essential Claim, then this Claim is REQUIRED; otherwise, its inclusion is OPTIONAL. (The auth_time Claim semantically corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] auth_time response parameter.) */ + auth_time?: number; + /** String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. If present in the ID Token, Clients MUST verify that the nonce Claim Value is equal to the value of the nonce parameter sent in the Authentication Request. If present in the Authentication Request, Authorization Servers MUST include a nonce Claim in the ID Token with the Claim Value being the nonce value sent in the Authentication Request. Authorization Servers SHOULD perform no other processing on nonce values used. The nonce value is a case sensitive string. */ + nonce?: string; + /** Authentication Context Class Reference. String specifying an Authentication Context Class Reference value that identifies the Authentication Context Class that the authentication performed satisfied. The value "0" indicates the End-User authentication did not meet the requirements of ISO/IEC 29115 [ISO29115] level 1. Authentication using a long-lived browser cookie, for instance, is one example where the use of "level 0" is appropriate. Authentications with level 0 SHOULD NOT be used to authorize access to any resource of any monetary value. (This corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] nist_auth_level 0.) An absolute URI or an RFC 6711 [RFC6711] registered name SHOULD be used as the acr value; registered names MUST NOT be used with a different meaning than that which is registered. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The acr value is a case sensitive string. */ + acr?: string; + /** Authentication Methods References. JSON array of strings that are identifiers for authentication methods used in the authentication. For instance, values might indicate that both password and OTP authentication methods were used. The definition of particular values to be used in the amr Claim is beyond the scope of this specification. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The amr value is an array of case sensitive strings. */ + amr?: unknown; + /** Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value. */ + azp?: string; + /** + * Session ID - String identifier for a Session. This represents a Session of a User Agent or device for a logged-in End-User at an RP. Different sid values are used to identify distinct sessions at an OP. The sid value need only be unique in the context of a particular issuer. Its contents are opaque to the RP. Its syntax is the same as an OAuth 2.0 Client Identifier. + * @see https://openid.net/specs/openid-connect-frontchannel-1_0.html#OPLogout + * */ + sid?: string; +} + +export interface OidcTokenSuccessResponse { + access_token: string; + token_type: string; + id_token: string; + expires_in?: number; + refresh_token?: string; + scope?: string; +} + +export interface OidcTokenErrorResponse { + error: string; + error_description?: string; +} + +/** + * Standard response from the OpenID Connect token request endpoint. + * + * @public + * @see https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse + */ +export type OidcTokenResponse = + | OidcTokenSuccessResponse + | OidcTokenErrorResponse; diff --git a/server/interfaces/api/settingsInterfaces.ts b/server/interfaces/api/settingsInterfaces.ts index 0e97c2bf44..43d4cd9ed9 100644 --- a/server/interfaces/api/settingsInterfaces.ts +++ b/server/interfaces/api/settingsInterfaces.ts @@ -31,6 +31,9 @@ export interface PublicSettingsResponse { hideAvailable: boolean; localLogin: boolean; mediaServerLogin: boolean; + oidcLogin: boolean; + oidcProviderName: string; + oidcAutomaticLogin: boolean; movie4kEnabled: boolean; series4kEnabled: boolean; discoverRegion: string; diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index d85f71379e..16af54c498 100644 --- a/server/lib/settings/index.ts +++ b/server/lib/settings/index.ts @@ -124,7 +124,19 @@ export interface MainSettings { hideAvailable: boolean; localLogin: boolean; mediaServerLogin: boolean; + oidcLogin: boolean; newPlexLogin: boolean; + oidc: { + providerName: string; + providerUrl: string; + clientId: string; + clientSecret: string; + userIdentifier: string; + requiredClaims: string; + scopes: string; + matchJellyfinUsername: boolean; + automaticLogin: boolean; + }; discoverRegion: string; streamingRegion: string; originalLanguage: string; @@ -151,6 +163,9 @@ interface FullPublicSettings extends PublicSettings { hideAvailable: boolean; localLogin: boolean; mediaServerLogin: boolean; + oidcLogin: boolean; + oidcProviderName: string; + oidcAutomaticLogin: boolean; movie4kEnabled: boolean; series4kEnabled: boolean; discoverRegion: string; @@ -346,6 +361,18 @@ class Settings { localLogin: true, mediaServerLogin: true, newPlexLogin: true, + oidcLogin: false, + oidc: { + providerName: 'OpenID Connect', + providerUrl: '', + clientId: '', + clientSecret: '', + userIdentifier: 'email', + requiredClaims: 'email_verified', + scopes: 'email openid profile', + matchJellyfinUsername: false, + automaticLogin: false, + }, discoverRegion: '', streamingRegion: '', originalLanguage: '', @@ -590,6 +617,9 @@ class Settings { hideAvailable: this.data.main.hideAvailable, localLogin: this.data.main.localLogin, mediaServerLogin: this.data.main.mediaServerLogin, + oidcLogin: this.data.main.oidcLogin, + oidcProviderName: this.data.main.oidc.providerName, + oidcAutomaticLogin: this.data.main.oidc.automaticLogin, jellyfinExternalHost: this.data.jellyfin.externalHostname, jellyfinForgotPasswordUrl: this.data.jellyfin.jellyfinForgotPasswordUrl, movie4kEnabled: this.data.radarr.some( diff --git a/server/migration/add-oidc.sql b/server/migration/add-oidc.sql new file mode 100644 index 0000000000..e6c66f23ed --- /dev/null +++ b/server/migration/add-oidc.sql @@ -0,0 +1 @@ +ALTER TABLE user ADD COLUMN oidcId VARCHAR; diff --git a/server/routes/auth.ts b/server/routes/auth.ts index 4e470831a6..4afeba3bd1 100644 --- a/server/routes/auth.ts +++ b/server/routes/auth.ts @@ -5,16 +5,31 @@ import { MediaServerType, ServerType } from '@server/constants/server'; import { UserType } from '@server/constants/user'; import { getRepository } from '@server/datasource'; import { User } from '@server/entity/User'; +import type { IdTokenClaims } from '@server/interfaces/api/oidcInterfaces'; import { startJobs } from '@server/job/schedule'; import { Permission } from '@server/lib/permissions'; import { getSettings } from '@server/lib/settings'; import logger from '@server/logger'; import { isAuthenticated } from '@server/middleware/auth'; import { ApiError } from '@server/types/error'; +import { + createIdTokenSchema, + fetchOIDCTokenData, + getOIDCRedirectUrl, + getOIDCUserInfo, + getOIDCWellknownConfiguration, + tryGetUserIdentifiers, + validateUserClaims, + type FullUserInfo, +} from '@server/utils/oidc'; import { getHostname } from '@server/utils/getHostname'; import * as EmailValidator from 'email-validator'; import { Router } from 'express'; import net from 'net'; +import { randomBytes } from 'crypto'; +import gravatarUrl from 'gravatar-url'; +import { jwtDecode } from "jwt-decode"; +import { In } from 'typeorm'; const authRoutes = Router(); @@ -796,4 +811,174 @@ authRoutes.post('/reset-password/:guid', async (req, res, next) => { return res.status(200).json({ status: 'ok' }); }); +authRoutes.get('/oidc-login', async (req, res, next) => { + const settings = getSettings(); + + if (!settings.main.oidcLogin) { + return next({ + status: 403, + message: 'OpenID Connect sign-in is disabled.', + }); + } + + const state = randomBytes(32).toString('hex'); + let redirectUrl; + + try { + redirectUrl = await getOIDCRedirectUrl(req, state); + } catch (err) { + logger.info('Failed OIDC login attempt', { + cause: 'Failed to fetch OIDC redirect url', + ip: req.ip, + errorMessage: err.message, + }); + return next({ + status: 500, + message: 'Configuration error.', + }); + } + + res.cookie('oidc-state', state, { + maxAge: 60000, + httpOnly: true, + secure: req.protocol === 'https', + }); + return res.redirect(redirectUrl); +}); + +authRoutes.get('/oidc-callback', async (req, res, next) => { + const settings = getSettings(); + const { oidcLogin, oidc } = settings.main; + const userRepository = getRepository(User); + + logger.debug('OIDC Callback Started:', { + query: req.query, + cookies: req.cookies + }); + + if (!oidcLogin) { + return next({ + status: 403, + message: 'OpenID Connect sign-in is disabled.', + }); + } + + try { + // Validate state parameter + const cookieState = req.cookies['oidc-state']; + const state = req.query.state as string; + + if (!state || cookieState !== state) { + logger.warn('Invalid OIDC state parameter', { + cookieState, + state, + ip: req.ip + }); + throw new Error('Invalid state parameter'); + } + res.clearCookie('oidc-state'); + + // Get and validate authorization code + const code = req.query.code as string; + if (!code) { + logger.warn('Missing OIDC authorization code', { ip: req.ip }); + throw new Error('Missing authorization code'); + } + + const wellKnownInfo = await getOIDCWellknownConfiguration(oidc.providerUrl); + const tokenResponse = await fetchOIDCTokenData(req, wellKnownInfo, code); + + if ('error' in tokenResponse) { + throw new Error(`Token error: ${tokenResponse.error}`); + } + + const decoded = jwtDecode(tokenResponse.id_token); + const userInfo = await getOIDCUserInfo(wellKnownInfo, tokenResponse.access_token); + const fullUserInfo: FullUserInfo = { ...decoded, ...userInfo }; + + logger.debug('OIDC User Info Merged:', { + email: fullUserInfo.email, + name: fullUserInfo.name, + sub: fullUserInfo.sub + }); + + // Find or create user + let user = await userRepository.findOne({ + where: [ + { email: fullUserInfo.email?.toLowerCase() }, + { oidcId: fullUserInfo.sub } + ] + }); + + if (!user) { + // Create new user + user = new User({ + email: fullUserInfo.email, + oidcId: fullUserInfo.sub, + username: fullUserInfo.preferred_username || fullUserInfo.name, + permissions: await userRepository.count() === 0 + ? Permission.ADMIN + : settings.main.defaultPermissions, + avatar: fullUserInfo.picture || gravatarUrl(fullUserInfo.email || ''), + userType: UserType.OIDC + }); + logger.info('Creating new user from OIDC login', { + label: 'Auth', + email: user.email, + oidcId: user.oidcId + }); + } else { + // Update existing user + user.oidcId = fullUserInfo.sub; + user.email = fullUserInfo.email || user.email; + user.avatar = fullUserInfo.picture || user.avatar; + if (user.username === user.oidcId) { + user.username = fullUserInfo.preferred_username || fullUserInfo.name; + } + logger.info('Updating existing user from OIDC login', { + label: 'Auth', + email: user.email, + oidcId: user.oidcId + }); + } + + await userRepository.save(user); + + // Set logged in session + if (req.session) { + req.session.userId = user.id; + } + + return res.redirect('/'); + } catch (error) { + logger.error('OIDC Callback Error:', { + message: error.message, + stack: error.stack, + ip: req.ip + }); + + return next({ + status: 500, + message: 'OIDC authentication failed: ' + error.message + }); + } +}); + +authRoutes.get('/oidc-logout', async (req, res, next) => { + const settings = getSettings(); + + if (!settings.main.oidcLogin || !settings.main.oidc.automaticLogin) { + return next({ + status: 403, + message: 'OpenID Connect sign-in is disabled.', + }); + } + + const oidcEndpoints = await getOIDCWellknownConfiguration( + settings.main.oidc.providerUrl + ); + + return res.redirect(oidcEndpoints.end_session_endpoint); +}); + export default authRoutes; diff --git a/server/routes/settings/index.ts b/server/routes/settings/index.ts index d74d328f35..b567434ba6 100644 --- a/server/routes/settings/index.ts +++ b/server/routes/settings/index.ts @@ -29,6 +29,7 @@ import { ApiError } from '@server/types/error'; import { appDataPath } from '@server/utils/appDataVolume'; import { getAppVersion } from '@server/utils/appVersion'; import { getHostname } from '@server/utils/getHostname'; +import { getOIDCWellknownConfiguration } from '@server/utils/oidc'; import { Router } from 'express'; import rateLimit from 'express-rate-limit'; import fs from 'fs'; @@ -69,13 +70,36 @@ settingsRoutes.get('/main', (req, res, next) => { res.status(200).json(filteredMainSettings(req.user, settings.main)); }); -settingsRoutes.post('/main', async (req, res) => { +settingsRoutes.post('/main', isAuthenticated(Permission.ADMIN), async (req, res, next) => { const settings = getSettings(); - settings.main = merge(settings.main, req.body); - await settings.save(); + try { + // Update main settings + if (req.body.oidc) { + settings.main.oidc = { + ...settings.main.oidc, + ...req.body.oidc + }; + settings.main.oidcLogin = req.body.oidcLogin ?? settings.main.oidcLogin; + } + + await settings.save(); + + return res.status(200).json({ + success: true, + message: 'Settings saved successfully' + }); + } catch (error) { + logger.error('Failed to save settings:', { + label: 'Settings', + error: error.message + }); - return res.status(200).json(settings.main); + return next({ + status: 500, + message: 'Failed to save settings' + }); + } }); settingsRoutes.get('/network', (req, res) => { @@ -807,4 +831,53 @@ settingsRoutes.get('/about', async (req, res) => { } as SettingsAboutResponse); }); +settingsRoutes.post( + '/oidc', + isAuthenticated(Permission.ADMIN), + async (req, res, next) => { + const settings = getSettings(); + + try { + // Validate the provider URL works + await getOIDCWellknownConfiguration(req.body.providerUrl); + + // Update OIDC settings + settings.main.oidc = { + ...settings.main.oidc, + providerName: req.body.providerName, + providerUrl: req.body.providerUrl, + clientId: req.body.clientId, + clientSecret: req.body.clientSecret, + userIdentifier: req.body.identificationClaims, + requiredClaims: req.body.requiredClaims, + scopes: req.body.scopes || 'openid profile email', + matchJellyfinUsername: req.body.matchMediaServerUsername, + automaticLogin: req.body.automaticLogin + }; + + // Enable OIDC login + settings.main.oidcLogin = true; + + await settings.save(); + + logger.info('OIDC settings updated successfully', { label: 'Settings' }); + + return res.status(200).json({ + success: true, + message: 'OIDC settings saved successfully' + }); + + } catch (error) { + logger.error('Failed to save OIDC settings:', { + label: 'Settings', + error: error.message, + }); + + return next({ + status: 500, + message: 'Failed to save OIDC settings' + }); + } +}); + export default settingsRoutes; diff --git a/server/utils/oidc.ts b/server/utils/oidc.ts new file mode 100644 index 0000000000..e27e1348af --- /dev/null +++ b/server/utils/oidc.ts @@ -0,0 +1,280 @@ +import type { + IdTokenClaims, + OidcProviderMetadata, + OidcStandardClaims, + OidcTokenResponse, + OidcTokenErrorResponse, + OidcTokenSuccessResponse, +} from '@server/interfaces/api/oidcInterfaces'; +import { getSettings } from '@server/lib/settings'; +import axios from 'axios'; +import type { Request } from 'express'; +import * as yup from 'yup'; + +/** Fetch the oidc configuration blob */ +export async function getOIDCWellknownConfiguration(domain: string) { + // remove trailing slash from url if it exists and add /.well-known/openid-configuration path + const wellKnownUrl = new URL( + domain.replace(/\/$/, '') + '/.well-known/openid-configuration' + ).toString(); + + const wellKnownInfo: OidcProviderMetadata = await axios + .get(wellKnownUrl, { + headers: { + 'Content-Type': 'application/json', + }, + }) + .then((r) => r.data); + + return wellKnownInfo; +} + +/** Generate authentication request url */ +export async function getOIDCRedirectUrl(req: Request, state: string) { + const settings = getSettings(); + const { oidc } = settings.main; + + const wellKnownInfo = await getOIDCWellknownConfiguration(oidc.providerUrl); + const url = new URL(wellKnownInfo.authorization_endpoint); + url.searchParams.set('response_type', 'code'); + url.searchParams.set('client_id', oidc.clientId); + + const callbackUrl = new URL( + '/login/oidc/callback', + `${req.protocol}://${req.headers.host}` + ).toString(); + url.searchParams.set('redirect_uri', callbackUrl); + url.searchParams.set('scope', 'openid profile email'); + url.searchParams.set('state', state); + return url.toString(); +} + +/** Exchange authorization code for token data */ +export async function fetchOIDCTokenData( + req: Request, + wellKnownInfo: OidcProviderMetadata, + code: string +): Promise { + const settings = getSettings(); + const { oidc } = settings.main; + + const callbackUrl = new URL( + '/login/oidc/callback', + `${req.protocol}://${req.headers.host}` + ); + + const formData = new URLSearchParams(); + formData.append('client_secret', oidc.clientSecret); + formData.append('grant_type', 'authorization_code'); + formData.append('redirect_uri', callbackUrl.toString()); + formData.append('client_id', oidc.clientId); + formData.append('code', code); + + try { + console.log('OIDC Token Request:', { + endpoint: wellKnownInfo.token_endpoint, + redirect_uri: callbackUrl.toString(), + client_id: oidc.clientId + }); + + const response = await axios.post( + wellKnownInfo.token_endpoint, + formData + ); + + // Type guard to check if response is success or error + const isErrorResponse = (data: OidcTokenResponse): data is OidcTokenErrorResponse => { + return 'error' in data; + }; + + if (isErrorResponse(response.data)) { + console.error('OIDC Token Error Response:', response.data); + throw new Error(response.data.error_description || response.data.error); + } + + console.log('OIDC Token Success:', { + status: response.status, + hasIdToken: !!response.data.id_token, + hasAccessToken: !!response.data.access_token + }); + + return response.data; + } catch (error) { + console.error('OIDC Token Error:', { + error: error.message, + response: error.response?.data + }); + throw error; + } +} + +export async function getOIDCUserInfo( + wellKnownInfo: OidcProviderMetadata, + authToken: string +) { + try { + console.log('OIDC UserInfo Request:', { + endpoint: wellKnownInfo.userinfo_endpoint + }); + + const response = await axios.get(wellKnownInfo.userinfo_endpoint, { + headers: { + Authorization: `Bearer ${authToken}`, + Accept: 'application/json', + }, + }); + + console.log('OIDC UserInfo Response:', { + status: response.status, + claims: Object.keys(response.data) + }); + + return response.data; + } catch (error) { + console.error('OIDC UserInfo Error:', { + error: error.message, + response: error.response?.data + }); + throw error; + } +} + +class OidcAuthorizationError extends Error {} + +class OidcMissingKeyError extends OidcAuthorizationError { + constructor(public userInfo: FullUserInfo, public key: string) { + super(`Key ${key} was missing on OIDC userinfo but was expected.`); + } +} + +export function tryGetUserIdentifiers( + userInfo: FullUserInfo, + identifierKeys: string[] +): string[] { + return identifierKeys.map((userIdentifier) => { + if ( + !Object.hasOwn(userInfo, userIdentifier) || + typeof userInfo[userIdentifier] !== 'string' + ) { + throw new OidcMissingKeyError(userInfo, userIdentifier); + } + + return userInfo[userIdentifier] as string; + }); +} + +type PrimitiveString = 'string' | 'boolean'; +type TypeFromName = T extends 'string' + ? string + : T extends 'boolean' + ? boolean + : unknown; + +export function tryGetUserInfoKey( + userInfo: FullUserInfo, + key: string, + expectedType: T +): TypeFromName { + if (!Object.hasOwn(userInfo, key) || typeof userInfo[key] !== expectedType) { + throw new OidcMissingKeyError(userInfo, key); + } + + return userInfo[key] as TypeFromName; +} + +export function validateUserClaims( + userInfo: FullUserInfo, + requiredClaims: string[] +) { + requiredClaims.some((claim) => { + const value = tryGetUserInfoKey(userInfo, claim, 'boolean'); + if (!value) + throw new OidcAuthorizationError('User was missing a required claim.'); + }); +} + +/** Generates a schema to validate ID token JWT and userinfo claims */ +export const createIdTokenSchema = ({ + oidcDomain, + oidcClientId, + identifierClaims, + requiredClaims, +}: { + oidcDomain: string; + oidcClientId: string; + identifierClaims: string[]; + requiredClaims: string[]; +}) => { + return yup.object().shape({ + iss: yup + .string() + .oneOf( + [oidcDomain, `${oidcDomain}/`], + `The token iss value doesn't match the oidc_DOMAIN (${oidcDomain})` + ) + .required("The token didn't come with an iss value."), + aud: yup.lazy((val) => { + // single audience + if (typeof val === 'string') + return yup + .string() + .oneOf( + [oidcClientId], + `The token aud value doesn't match the oidc_CLIENT_ID (${oidcClientId})` + ) + .required("The token didn't come with an aud value."); + // several audiences + if (typeof val === 'object' && Array.isArray(val)) + return yup + .array() + .of(yup.string()) + .test( + 'contains-client-id', + `The token aud value doesn't contain the oidc_CLIENT_ID (${oidcClientId})`, + (value) => !!(value && value.includes(oidcClientId)) + ); + // invalid type + return yup + .mixed() + .typeError('The token aud value is not a string or array.'); + }), + exp: yup + .number() + .required() + .test( + 'is_before_date', + 'Token exp value is before current time.', + (value) => { + if (!value) return false; + if (value < Math.ceil(Date.now() / 1000)) return false; + return true; + } + ), + iat: yup + .number() + .required() + .test( + 'is_before_one_day', + 'Token was issued before one day ago and is now invalid.', + (value) => { + if (!value) return false; + const date = new Date(); + date.setDate(date.getDate() - 1); + if (value < Math.ceil(Number(date) / 1000)) return false; + return true; + } + ), + // ensure all identifier claims are present and are strings + ...identifierClaims.reduce( + (a, v) => ({ ...a, [v]: yup.string().required() }), + {} + ), + // ensure all required claims are present and are booleans + ...requiredClaims.reduce( + (a, v) => ({ ...a, [v]: yup.boolean().required() }), + {} + ), + }); +}; + +export type FullUserInfo = IdTokenClaims & OidcStandardClaims; diff --git a/src/components/Login/ErrorCallout.tsx b/src/components/Login/ErrorCallout.tsx new file mode 100644 index 0000000000..9407881fe0 --- /dev/null +++ b/src/components/Login/ErrorCallout.tsx @@ -0,0 +1,25 @@ +import Alert from '@app/components/Common/Alert'; +import { Transition } from '@headlessui/react'; + +interface LoginErrorProps { + error: string; +} + +const LoginError: React.FC = ({ error }) => { + return ( + + {error} + + ); +}; + +export default LoginError; diff --git a/src/components/Login/OidcLogin.tsx b/src/components/Login/OidcLogin.tsx new file mode 100644 index 0000000000..4dda47129b --- /dev/null +++ b/src/components/Login/OidcLogin.tsx @@ -0,0 +1,87 @@ +import Button from '@app/components/Common/Button'; +import useSettings from '@app/hooks/useSettings'; +import globalMessages from '@app/i18n/globalMessages'; +import OIDCAuth from '@app/utils/oidc'; +import { ArrowLeftOnRectangleIcon } from '@heroicons/react/24/outline'; +import { useEffect } from 'react'; +import { defineMessages, useIntl } from 'react-intl'; + +// Modify the messages definition to include proper IDs +const messages = defineMessages({ + signinwithoidc: { + id: 'components.Login.signinwithoidc', + defaultMessage: 'Sign in with {OIDCProvider}' + }, + signingin: { + id: 'components.Login.signingin', + defaultMessage: 'Signing in…' + }, + loginerror: { + id: 'components.Login.loginerror', + defaultMessage: 'Something went wrong while trying to sign in.' + } +}); + +interface OidcLoginProps { + revalidate: () => void; + isProcessing: boolean; + setProcessing: (state: boolean) => void; + hasError: boolean; + onError: (message: string) => void; +} + +const oidcAuth = new OIDCAuth(); + +const OidcLogin = ({ + revalidate, + isProcessing, + setProcessing, + hasError, + onError, +}: OidcLoginProps) => { + const intl = useIntl(); + const settings = useSettings(); + + useEffect(() => { + const { oidcLogin, oidcAutomaticLogin } = settings.currentSettings; + if (oidcLogin && oidcAutomaticLogin) + // redirect to login page + window.location.href = '/api/v1/auth/oidc-login'; + }, [settings.currentSettings]); + + const handleClick = async () => { + setProcessing(true); + try { + await oidcAuth.preparePopup(); + revalidate(); + } catch (e) { + let message = 'Unknown Error'; + if (e instanceof Error) message = e.message; + onError(message); + setProcessing(false); + return; + } + }; + + return ( + + + + ); +}; + +export default OidcLogin; diff --git a/src/components/Login/index.tsx b/src/components/Login/index.tsx index 0b51e86f11..f2594752bc 100644 --- a/src/components/Login/index.tsx +++ b/src/components/Login/index.tsx @@ -8,6 +8,7 @@ import LanguagePicker from '@app/components/Layout/LanguagePicker'; import JellyfinLogin from '@app/components/Login/JellyfinLogin'; import LocalLogin from '@app/components/Login/LocalLogin'; import PlexLoginButton from '@app/components/Login/PlexLoginButton'; +import OidcLogin from '@app/components/Login/OidcLogin'; import useSettings from '@app/hooks/useSettings'; import { useUser } from '@app/hooks/useUser'; import defineMessages from '@app/utils/defineMessages'; @@ -27,6 +28,8 @@ const messages = defineMessages('components.Login', { signinwithplex: 'Use your Plex account', signinwithjellyfin: 'Use your {mediaServerName} account', signinwithoverseerr: 'Use your {applicationTitle} account', + useoidcaccount: 'Use your {OIDCProvider} account', + authprocessing: 'Authentication in progress...', orsigninwith: 'Or sign in with', }); @@ -122,7 +125,8 @@ const Login = () => { const loginFormVisible = (isJellyfin && settings.currentSettings.mediaServerLogin) || - settings.currentSettings.localLogin; + settings.currentSettings.localLogin || + settings.currentSettings.oidcLogin; const additionalLoginOptions = [ settings.currentSettings.mediaServerLogin && (settings.currentSettings.mediaServerType === MediaServerType.PLEX ? ( @@ -161,6 +165,17 @@ const Login = () => { )) )), + // Add OIDC Login option + settings.currentSettings.oidcLogin && ( + + ), ].filter((o): o is JSX.Element => !!o); return ( diff --git a/src/components/Settings/OidcModal/index.tsx b/src/components/Settings/OidcModal/index.tsx new file mode 100644 index 0000000000..d4ac264bfd --- /dev/null +++ b/src/components/Settings/OidcModal/index.tsx @@ -0,0 +1,547 @@ +import React, { useEffect } from 'react'; +import Accordion from '@app/components/Common/Accordion'; +import Modal from '@app/components/Common/Modal'; +import globalMessages from '@app/i18n/globalMessages'; +import { Transition } from '@headlessui/react'; +import { ChevronDownIcon } from '@heroicons/react/24/solid'; +import type { MainSettings } from '@server/lib/settings'; +import { + ErrorMessage, + type FormikErrors, +} from 'formik'; +import { + defineMessages, + useIntl, + type IntlShape, + type MessageDescriptor, +} from 'react-intl'; +import * as yup from 'yup'; + +const messages = defineMessages({ + configureoidc: { + id: 'settings.oidc.configureoidc', + defaultMessage: 'Configure OpenID Connect' + }, + oidcDomain: { + id: 'settings.oidc.domain', + defaultMessage: 'Issuer URL' + }, + oidcDomainTip: { + id: 'settings.oidc.domainTip', + defaultMessage: "The base URL of the identity provider's OIDC endpoint" + }, + oidcName: { + id: 'settings.oidc.name', + defaultMessage: 'Provider Name' + }, + oidcNameTip: { + id: 'settings.oidc.nameTip', + defaultMessage: 'Name of the OIDC Provider which appears on the login screen' + }, + oidcClientId: { + id: 'settings.oidc.clientId', + defaultMessage: 'Client ID' + }, + oidcClientIdTip: { + id: 'settings.oidc.clientIdTip', + defaultMessage: 'The OIDC Client ID assigned to Jellyseerr' + }, + oidcClientSecret: { + id: 'settings.oidc.clientSecret', + defaultMessage: 'Client Secret' + }, + oidcClientSecretTip: { + id: 'settings.oidc.clientSecretTip', + defaultMessage: 'The OIDC Client Secret assigned to Jellyseerr' + }, + oidcScopes: { + id: 'settings.oidc.scopes', + defaultMessage: 'Scopes' + }, + oidcScopesTip: { + id: 'settings.oidc.scopesTip', + defaultMessage: 'The scopes to request from the identity provider.' + }, + oidcIdentificationClaims: { + id: 'settings.oidc.identificationClaims', + defaultMessage: 'Identification Claims' + }, + oidcIdentificationClaimsTip: { + id: 'settings.oidc.identificationClaimsTip', + defaultMessage: 'OIDC claims to use as unique identifiers for the given user. Will be matched against the user\'s email and, optionally, their media server username.' + }, + oidcRequiredClaims: { + id: 'settings.oidc.requiredClaims', + defaultMessage: 'Required Claims' + }, + oidcRequiredClaimsTip: { + id: 'settings.oidc.requiredClaimsTip', + defaultMessage: 'Claims that are required for a user to log in.' + }, + oidcMatchUsername: { + id: 'settings.oidc.matchUsername', + defaultMessage: 'Allow {mediaServerName} Usernames' + }, + oidcMatchUsernameTip: { + id: 'settings.oidc.matchUsernameTip', + defaultMessage: 'Match OIDC users with their {mediaServerName} accounts by username' + }, + oidcAutomaticLogin: { + id: 'settings.oidc.automaticLogin', + defaultMessage: 'Automatic Login' + }, + oidcAutomaticLoginTip: { + id: 'settings.oidc.automaticLoginTip', + defaultMessage: 'Automatically navigate to the OIDC login and logout pages. This functionality only supported when OIDC is the exclusive login method.' + }, +}); + +type OidcSettings = MainSettings['oidc']; + +interface OidcModalProps { + values: Partial; + errors?: FormikErrors; + setFieldValue: ( + field: keyof OidcSettings, + value: string | boolean, + shouldValidate?: boolean + ) => void; + mediaServerName: string; + onClose?: () => void; + onOk?: () => void; +} + +export const oidcSettingsSchema = (intl: IntlShape) => { + const requiredMessage = (message: MessageDescriptor) => + intl.formatMessage(globalMessages.fieldRequired, { + fieldName: intl.formatMessage(message), + }); + + return yup.object().shape({ + providerName: yup.string().required(requiredMessage(messages.oidcName)), + providerUrl: yup + .string() + .required(requiredMessage(messages.oidcDomain)) + .url('Issuer URL must be a valid URL.') + .test({ + message: 'Issuer URL may not have search parameters.', + test: (val) => { + if (!val) return false; + try { + const url = new URL(val); + return url.search === ''; + } catch { + return false; + } + }, + }) + .test({ + message: 'Issuer URL protocol must be http / https.', + test: (val) => { + if (!val) return false; + try { + const url = new URL(val); + return ['http:', 'https:'].includes(url.protocol); + } catch { + return false; + } + }, + }), + clientId: yup.string().required(requiredMessage(messages.oidcClientId)), + clientSecret: yup + .string() + .required(requiredMessage(messages.oidcClientSecret)), + scopes: yup.string().required(requiredMessage(messages.oidcScopes)), + userIdentifier: yup + .string() + .required(requiredMessage(messages.oidcIdentificationClaims)), + requiredClaims: yup.string().required(requiredMessage(messages.oidcRequiredClaims)), + matchJellyfinUsername: yup.boolean(), + automaticLogin: yup.boolean(), + }); +}; + +type OidcAction = + | { type: 'UPDATE_ALL'; payload: Partial } + | { type: 'UPDATE_FIELD'; field: keyof OidcSettings; value: string | boolean }; + +function oidcReducer(state: OidcSettings, action: OidcAction): OidcSettings { + switch (action.type) { + case 'UPDATE_ALL': + return { + ...state, + ...action.payload + }; + case 'UPDATE_FIELD': + return { + ...state, + [action.field]: action.value + }; + default: + return state; + } +} + +const OidcModal = ({ + onClose, + onOk, + values, + errors, + setFieldValue, + mediaServerName, +}: OidcModalProps) => { + const intl = useIntl(); + + // Replace useState with useReducer + const [localValues, dispatch] = React.useReducer(oidcReducer, { + providerUrl: values.providerUrl ?? '', + providerName: values.providerName ?? '', + clientId: values.clientId ?? '', + clientSecret: values.clientSecret ?? '', + scopes: values.scopes ?? 'email openid profile', + userIdentifier: values.userIdentifier ?? 'email', + requiredClaims: values.requiredClaims ?? 'email_verified', + matchJellyfinUsername: values.matchJellyfinUsername ?? false, + automaticLogin: values.automaticLogin ?? false + }); + + // Update effect to use reducer + useEffect(() => { + dispatch({ type: 'UPDATE_ALL', payload: values }); + }, [values]); + + const handleInputChange = (e: React.ChangeEvent) => { + const { name, value } = e.target; + dispatch({ type: 'UPDATE_FIELD', field: name as keyof OidcSettings, value }); + setFieldValue(name as keyof OidcSettings, value, true); + }; + + const handleCheckboxChange = (name: keyof OidcSettings) => { + const newValue = !localValues[name]; + dispatch({ type: 'UPDATE_FIELD', field: name, value: newValue }); + setFieldValue(name, newValue, true); + }; + + const canClose = (errors: OidcModalProps['errors']) => { + if (errors == null) return true; + return Object.keys(errors).length === 0; + }; + + // Move handleSubmit inside component if needed + const handleSubmit = async (data: OidcSettings): Promise => { + try { + const response = await fetch('/api/v1/settings/main', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + oidc: data, + oidcLogin: true + }), + }); + + if (!response.ok) { + throw new Error(response.statusText); + } + + return await response.json(); + } catch (error) { + return { + success: false, + message: error instanceof Error ? error.message : 'Failed to save OIDC settings' + }; + } + }; + + // Use handleSubmit in onOk if needed + const handleOk = async () => { + if (onOk) { + const response = await handleSubmit(localValues); + if (response.success) { + onOk(); + } + } + }; + + return ( + + + +
+
+
+ +
+ {/* Replace Field with a controlled input */} + + +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ + {({ openIndexes, handleClick, AccordionContent }) => ( + <> + + +
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ handleCheckboxChange('matchJellyfinUsername')} + /> +
+
+
+ +
+ handleCheckboxChange('automaticLogin')} + /> +
+
+
+
+ + )} +
+
+
+
+
+ ); +}; + +export default OidcModal; + +interface OidcResponse { + success: boolean; + message: string; + data?: Record; +} diff --git a/src/components/Settings/SettingsUsers/index.tsx b/src/components/Settings/SettingsUsers/index.tsx index 8203360bd7..c5256f6ce2 100644 --- a/src/components/Settings/SettingsUsers/index.tsx +++ b/src/components/Settings/SettingsUsers/index.tsx @@ -4,6 +4,9 @@ import LoadingSpinner from '@app/components/Common/LoadingSpinner'; import PageTitle from '@app/components/Common/PageTitle'; import PermissionEdit from '@app/components/PermissionEdit'; import QuotaSelector from '@app/components/QuotaSelector'; +import OidcModal, { + oidcSettingsSchema, +} from '@app/components/Settings/OidcModal'; import useSettings from '@app/hooks/useSettings'; import globalMessages from '@app/i18n/globalMessages'; import defineMessages from '@app/utils/defineMessages'; @@ -15,6 +18,8 @@ import { useIntl } from 'react-intl'; import { useToasts } from 'react-toast-notifications'; import useSWR, { mutate } from 'swr'; import * as yup from 'yup'; +import { useState } from 'react'; +import { CogIcon } from '@heroicons/react/24/solid'; const messages = defineMessages('components.Settings.SettingsUsers', { users: 'Users', @@ -30,6 +35,8 @@ const messages = defineMessages('components.Settings.SettingsUsers', { mediaServerLogin: 'Enable {mediaServerName} Sign-In', mediaServerLoginTip: 'Allow users to sign in using their {mediaServerName} account', + oidcLogin: 'Enable OIDC Sign-In', + oidcLoginTip: 'Allow users to sign in using an OIDC identity provider', atLeastOneAuth: 'At least one authentication method must be selected.', newPlexLogin: 'Enable New {mediaServerName} Sign-In', newPlexLoginTip: @@ -49,26 +56,48 @@ const SettingsUsers = () => { mutate: revalidate, } = useSWR('/api/v1/settings/main'); const settings = useSettings(); + const [showOidcDialog, setShowOidcDialog] = useState(false); const schema = yup .object() .shape({ localLogin: yup.boolean(), mediaServerLogin: yup.boolean(), + oidcLogin: yup.boolean(), + oidc: yup.object().when('oidcLogin', { + is: true, + // Call the function with the intl object + then: () => oidcSettingsSchema(intl), + }), }) .test({ name: 'atLeastOneAuth', test: function (values) { - const isValid = ['localLogin', 'mediaServerLogin'].some( + const isValid = ['localLogin', 'mediaServerLogin', 'oidcLogin'].some( (field) => !!values[field] ); if (isValid) return true; return this.createError({ - path: 'localLogin | mediaServerLogin', + path: 'localLogin | mediaServerLogin | oidcLogin', message: intl.formatMessage(messages.atLeastOneAuth), }); }, + }) + .test({ + name: 'automaticLoginExclusive', + test: function (values) { + const isValid = + !values.oidcLogin || + !values.oidc?.automaticLogin || + !['localLogin', 'mediaServerLogin'].some((field) => !!values[field]); + + if (isValid) return true; + return this.createError({ + path: 'localLogin | mediaServerLogin | oidcLogin', + message: 'Only OIDC login may be enabled when automatic login is enabled.', + }); + }, }); if (!data && !error) { @@ -106,6 +135,8 @@ const SettingsUsers = () => { localLogin: data?.localLogin, mediaServerLogin: data?.mediaServerLogin, newPlexLogin: data?.newPlexLogin, + oidcLogin: data?.oidcLogin, + oidc: data?.oidc ?? {}, movieQuotaLimit: data?.defaultQuotas.movie.quotaLimit ?? 0, movieQuotaDays: data?.defaultQuotas.movie.quotaDays ?? 7, tvQuotaLimit: data?.defaultQuotas.tv.quotaLimit ?? 0, @@ -125,6 +156,8 @@ const SettingsUsers = () => { localLogin: values.localLogin, mediaServerLogin: values.mediaServerLogin, newPlexLogin: values.newPlexLogin, + oidcLogin: values.oidcLogin, + oidc: values.oidc, defaultQuotas: { movie: { quotaLimit: values.movieQuotaLimit, @@ -206,6 +239,24 @@ const SettingsUsers = () => { ) } /> +
+
+ { + const newValue = !values.oidcLogin; + setFieldValue('oidcLogin', newValue); + if (newValue) setShowOidcDialog(true); + }} + /> +
+ setShowOidcDialog(true)} + /> +
@@ -234,6 +285,26 @@ const SettingsUsers = () => { /> + + {values.oidcLogin && values.oidc && showOidcDialog && ( + { + setFieldValue(`oidc.${field}`, value); + }} + mediaServerName={ + settings.currentSettings.mediaServerType === MediaServerType.JELLYFIN + ? 'Jellyfin' + : settings.currentSettings.mediaServerType === MediaServerType.EMBY + ? 'Emby' + : 'Plex' + } + onOk={() => setShowOidcDialog(false)} + onClose={() => setFieldValue('oidcLogin', false)} + /> + )} +