diff --git a/docs/using-seerr/users/editing-users.md b/docs/using-seerr/users/editing-users.md index 8e0b556cc8..cb7826caeb 100644 --- a/docs/using-seerr/users/editing-users.md +++ b/docs/using-seerr/users/editing-users.md @@ -53,6 +53,12 @@ All "local users" are assigned passwords upon creation, but users imported from Passwords must be a minimum of 8 characters long. +## API Key + +Users can generate a personal API key for scripts and integrations. The key authenticates as that user, with their permissions, and is only shown once. Regenerating or revoking it stops the old key from working. + +Each user manages their own key. To act as the owner, use the API key in [General settings](/using-seerr/settings/general#api-key) instead. + ## Notifications Users can configure their personal notification settings here. Please see [Notifications](/using-seerr/notifications/) for details on configuring and enabling notifications. diff --git a/seerr-api.yml b/seerr-api.yml index 24b825c79c..4241cf0a29 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -5199,6 +5199,63 @@ paths: application/json: schema: $ref: '#/components/schemas/UserSettings' + /user/{userId}/settings/api-key: + get: + summary: Check for a personal API key + description: Returns whether the user has a personal API key. Only available for your own account. + tags: + - users + parameters: + - in: path + name: userId + required: true + schema: + type: number + responses: + '200': + description: API key status returned + content: + application/json: + schema: + type: object + properties: + hasApiKey: + type: boolean + post: + summary: Generate a personal API key + description: Generates a key that authenticates as this user, replacing any existing key. The key is only returned once. Only available for your own account. + tags: + - users + parameters: + - in: path + name: userId + required: true + schema: + type: number + responses: + '200': + description: API key generated + content: + application/json: + schema: + type: object + properties: + apiKey: + type: string + delete: + summary: Revoke a personal API key + description: Only available for your own account. + tags: + - users + parameters: + - in: path + name: userId + required: true + schema: + type: number + responses: + '204': + description: API key revoked /user/{userId}/settings/password: get: summary: Get password page informatiom diff --git a/server/entity/UserSettings.ts b/server/entity/UserSettings.ts index d0f2ef1f7e..5f2c4d6098 100644 --- a/server/entity/UserSettings.ts +++ b/server/entity/UserSettings.ts @@ -4,6 +4,7 @@ import { NotificationAgentKey } from '@server/lib/settings'; import { Column, Entity, + Index, JoinColumn, OneToOne, PrimaryGeneratedColumn, @@ -52,6 +53,10 @@ export class UserSettings { @Column({ nullable: true }) public originalLanguage?: string; + @Index({ unique: true }) + @Column({ type: 'varchar', nullable: true, select: false }) + public apiKeyHash?: string | null; + @Column({ nullable: true }) public pgpKey?: string; diff --git a/server/middleware/auth.ts b/server/middleware/auth.ts index 326d460d8b..c6bf84ed6f 100644 --- a/server/middleware/auth.ts +++ b/server/middleware/auth.ts @@ -5,12 +5,17 @@ import type { PermissionCheckOptions, } from '@server/lib/permissions'; import { getSettings } from '@server/lib/settings'; +import { createHash } from 'crypto'; + +export const hashApiKey = (apiKey: string) => + createHash('sha256').update(apiKey).digest('hex'); export const checkUser: Middleware = async (req, _res, next) => { const settings = getSettings(); let user: User | undefined | null; + const apiKey = req.header('X-API-Key'); - if (req.header('X-API-Key') === settings.main.apiKey) { + if (apiKey === settings.main.apiKey) { const userRepository = getRepository(User); let userId = 1; // Work on original administrator account @@ -21,7 +26,13 @@ export const checkUser: Middleware = async (req, _res, next) => { } user = await userRepository.findOne({ where: { id: userId } }); - } else if (req.session?.userId) { + } else if (apiKey) { + user = await getRepository(User).findOne({ + where: { settings: { apiKeyHash: hashApiKey(apiKey) } }, + }); + } + + if (!user && apiKey !== settings.main.apiKey && req.session?.userId) { const userRepository = getRepository(User); user = await userRepository.findOne({ diff --git a/server/migration/postgres/1792348651934-AddUserApiKeyHash.ts b/server/migration/postgres/1792348651934-AddUserApiKeyHash.ts new file mode 100644 index 0000000000..f085083040 --- /dev/null +++ b/server/migration/postgres/1792348651934-AddUserApiKeyHash.ts @@ -0,0 +1,21 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddUserApiKeyHash1792348651934 implements MigrationInterface { + name = 'AddUserApiKeyHash1792348651934'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "user_settings" ADD "apiKeyHash" varchar` + ); + await queryRunner.query( + `CREATE UNIQUE INDEX "IDX_fa5a2d13c60c9ec6f04637de8e" ON "user_settings" ("apiKeyHash") ` + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP INDEX "IDX_fa5a2d13c60c9ec6f04637de8e"`); + await queryRunner.query( + `ALTER TABLE "user_settings" DROP COLUMN "apiKeyHash"` + ); + } +} diff --git a/server/migration/sqlite/1792348646818-AddUserApiKeyHash.ts b/server/migration/sqlite/1792348646818-AddUserApiKeyHash.ts new file mode 100644 index 0000000000..fe7ee88cb6 --- /dev/null +++ b/server/migration/sqlite/1792348646818-AddUserApiKeyHash.ts @@ -0,0 +1,21 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddUserApiKeyHash1792348646818 implements MigrationInterface { + name = 'AddUserApiKeyHash1792348646818'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "user_settings" ADD "apiKeyHash" varchar` + ); + await queryRunner.query( + `CREATE UNIQUE INDEX "IDX_fa5a2d13c60c9ec6f04637de8e" ON "user_settings" ("apiKeyHash") ` + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP INDEX "IDX_fa5a2d13c60c9ec6f04637de8e"`); + await queryRunner.query( + `ALTER TABLE "user_settings" DROP COLUMN "apiKeyHash"` + ); + } +} diff --git a/server/routes/user/usersettings.test.ts b/server/routes/user/usersettings.test.ts index f624c8fd0e..e784e3719a 100644 --- a/server/routes/user/usersettings.test.ts +++ b/server/routes/user/usersettings.test.ts @@ -6,9 +6,14 @@ import { MediaServerType } from '@server/constants/server'; import { UserType } from '@server/constants/user'; import { getRepository } from '@server/datasource'; import { User } from '@server/entity/User'; +import { UserSettings } from '@server/entity/UserSettings'; import { Permission } from '@server/lib/permissions'; import { getSettings } from '@server/lib/settings'; -import { checkUser, isAuthenticated } from '@server/middleware/auth'; +import { + checkUser, + hashApiKey, + isAuthenticated, +} from '@server/middleware/auth'; import authRoutes from '@server/routes/auth'; import { setupTestDb } from '@server/test/db'; import { permissionsOf, seedManagerAndAdmin } from '@server/test/users'; @@ -252,3 +257,44 @@ describe('POST /user/:id/settings/password', () => { assert.ok(await user.passwordMatch('reset12345')); }); }); + +describe('/user/:id/settings/api-key', () => { + const me = (apiKey: string) => + request(app).get('/auth/me').set('X-API-Key', apiKey); + + it('authenticates as the user until regenerated or revoked', async () => { + const { agent, userId } = await loginAs('demo@seerr.dev', 'test1234'); + const url = `/user/${userId}/settings/api-key`; + + const first = (await agent.post(url).expect(200)).body.apiKey; + assert.strictEqual((await me(first)).body.id, userId); + assert.deepStrictEqual((await agent.get(url)).body, { hasApiKey: true }); + + const settings = await getRepository(UserSettings).findOneOrFail({ + where: { user: { id: userId } }, + select: ['id', 'apiKeyHash'], + }); + assert.strictEqual(settings.apiKeyHash, hashApiKey(first)); + + const second = (await agent.post(url).expect(200)).body.apiKey; + assert.strictEqual((await me(first)).status, 403); + assert.strictEqual((await me(second)).body.id, userId); + + await agent.delete(url).expect(204); + assert.strictEqual((await me(second)).status, 403); + assert.strictEqual( + (await agent.get('/auth/me').set('X-API-Key', second)).body.id, + userId + ); + assert.deepStrictEqual((await agent.get(url)).body, { hasApiKey: false }); + }); + + it("returns 403 for another user's key", async () => { + const { agent } = await loginAs('demo@seerr.dev', 'test1234'); + const admin = await getRepository(User).findOneOrFail({ + where: { email: 'admin@seerr.dev' }, + }); + + await agent.post(`/user/${admin.id}/settings/api-key`).expect(403); + }); +}); diff --git a/server/routes/user/usersettings.ts b/server/routes/user/usersettings.ts index 0ecf3ea563..b44378c78c 100644 --- a/server/routes/user/usersettings.ts +++ b/server/routes/user/usersettings.ts @@ -13,7 +13,7 @@ import type { import { Permission } from '@server/lib/permissions'; import { getSettings } from '@server/lib/settings'; import logger from '@server/logger'; -import { isAuthenticated } from '@server/middleware/auth'; +import { hashApiKey, isAuthenticated } from '@server/middleware/auth'; import { quickConnectSecret } from '@server/routes/auth'; import { ApiError } from '@server/types/error'; import { getHostname } from '@server/utils/getHostname'; @@ -21,9 +21,10 @@ import { isOwnProfile, isOwnProfileOrAdmin, } from '@server/utils/profileMiddleware'; +import { randomBytes } from 'crypto'; import { Router } from 'express'; import net from 'net'; -import { Not } from 'typeorm'; +import { IsNull, Not } from 'typeorm'; import { canMakePermissionsChange, canModifyUser } from '.'; const userSettingsRoutes = Router({ mergeParams: true }); @@ -168,6 +169,57 @@ userSettingsRoutes.post< } }); +const setApiKeyHash = async (user: User, apiKeyHash: string | null) => { + user.settings ??= new UserSettings({ user }); + user.settings.apiKeyHash = apiKeyHash; + await getRepository(User).save(user); +}; + +userSettingsRoutes.get<{ id: string }, { hasApiKey: boolean }>( + '/api-key', + isOwnProfile(), + async (req, res, next) => { + try { + const hasApiKey = await getRepository(UserSettings).exists({ + where: { + user: { id: Number(req.params.id) }, + apiKeyHash: Not(IsNull()), + }, + }); + return res.status(200).json({ hasApiKey }); + } catch (e) { + next({ status: 500, message: e.message }); + } + } +); + +userSettingsRoutes.post<{ id: string }, { apiKey: string }>( + '/api-key', + isOwnProfile(), + async (req, res, next) => { + const apiKey = randomBytes(32).toString('base64url'); + try { + await setApiKeyHash(req.user as User, hashApiKey(apiKey)); + return res.status(200).json({ apiKey }); + } catch (e) { + next({ status: 500, message: e.message }); + } + } +); + +userSettingsRoutes.delete<{ id: string }>( + '/api-key', + isOwnProfile(), + async (req, res, next) => { + try { + await setApiKeyHash(req.user as User, null); + return res.status(204).send(); + } catch (e) { + next({ status: 500, message: e.message }); + } + } +); + userSettingsRoutes.get<{ id: string }, { hasPassword: boolean }>( '/password', isOwnProfileOrAdmin(), diff --git a/src/components/UserProfile/UserSettings/UserApiKey/index.tsx b/src/components/UserProfile/UserSettings/UserApiKey/index.tsx new file mode 100644 index 0000000000..8f22ed9540 --- /dev/null +++ b/src/components/UserProfile/UserSettings/UserApiKey/index.tsx @@ -0,0 +1,122 @@ +import Button from '@app/components/Common/Button'; +import LoadingSpinner from '@app/components/Common/LoadingSpinner'; +import PageTitle from '@app/components/Common/PageTitle'; +import SensitiveInput from '@app/components/Common/SensitiveInput'; +import CopyButton from '@app/components/Settings/CopyButton'; +import useToasts from '@app/hooks/useToasts'; +import { useUser } from '@app/hooks/useUser'; +import globalMessages from '@app/i18n/globalMessages'; +import ErrorPage from '@app/pages/_error'; +import defineMessages from '@app/utils/defineMessages'; +import axios from 'axios'; +import { useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +const messages = defineMessages( + 'components.UserProfile.UserSettings.UserApiKey', + { + apiKey: 'API Key', + generate: 'Generate', + regenerate: 'Regenerate', + revoke: 'Revoke', + copyNow: 'Copy this key now. It will not be shown again.', + copied: 'API key copied to clipboard.', + } +); + +const UserApiKey = () => { + const intl = useIntl(); + const { addToast } = useToasts(); + const { user } = useUser(); + const url = `/api/v1/user/${user?.id}/settings/api-key`; + const { data, error, mutate } = useSWR<{ hasApiKey: boolean }>( + user ? url : null + ); + const [apiKey, setApiKey] = useState(); + const [isSubmitting, setIsSubmitting] = useState(false); + + const submit = async (method: 'post' | 'delete') => { + setIsSubmitting(true); + try { + const res = await axios.request<{ apiKey?: string }>({ method, url }); + setApiKey(res.data?.apiKey); + mutate(); + } catch { + addToast(intl.formatMessage(globalMessages.error), { + autoDismiss: true, + appearance: 'error', + }); + } finally { + setIsSubmitting(false); + } + }; + + if (!data && !error) { + return ; + } + + if (!data) { + return ; + } + + return ( + <> + +
+

{intl.formatMessage(messages.apiKey)}

+
+
+ {apiKey && ( + <> +
+ + +
+

+ {intl.formatMessage(messages.copyNow)} +

+ + )} +
+ + {data.hasApiKey && ( + + )} +
+
+ + ); +}; + +export default UserApiKey; diff --git a/src/components/UserProfile/UserSettings/index.tsx b/src/components/UserProfile/UserSettings/index.tsx index 8df54eb03b..c0d56d3b28 100644 --- a/src/components/UserProfile/UserSettings/index.tsx +++ b/src/components/UserProfile/UserSettings/index.tsx @@ -18,6 +18,7 @@ import useSWR from 'swr'; const messages = defineMessages('components.UserProfile.UserSettings', { menuGeneralSettings: 'General', menuChangePass: 'Password', + menuApiKey: 'API Key', menuLinkedAccounts: 'Linked Accounts', menuNotifications: 'Notifications', menuPermissions: 'Permissions', @@ -64,6 +65,12 @@ const UserSettings = ({ children }: UserSettingsProps) => { currentUser?.id !== user?.id && hasPermission(Permission.ADMIN, user?.permissions ?? 0)), }, + { + text: intl.formatMessage(messages.menuApiKey), + route: '/settings/api-key', + regex: /\/settings\/api-key/, + hidden: currentUser?.id !== user?.id, + }, { text: intl.formatMessage(messages.menuLinkedAccounts), route: '/settings/linked-accounts', diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index 4a1a0eec9d..1e16c342a5 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -1489,6 +1489,12 @@ "components.UserProfile.UserSettings.LinkJellyfinQuickConnectModal.subtitle": "Quick Connect", "components.UserProfile.UserSettings.LinkJellyfinQuickConnectModal.title": "Link {mediaServerName} Account", "components.UserProfile.UserSettings.LinkJellyfinQuickConnectModal.usePassword": "Use Password Instead", + "components.UserProfile.UserSettings.UserApiKey.apiKey": "API Key", + "components.UserProfile.UserSettings.UserApiKey.copied": "API key copied to clipboard.", + "components.UserProfile.UserSettings.UserApiKey.copyNow": "Copy this key now. It will not be shown again.", + "components.UserProfile.UserSettings.UserApiKey.generate": "Generate", + "components.UserProfile.UserSettings.UserApiKey.regenerate": "Regenerate", + "components.UserProfile.UserSettings.UserApiKey.revoke": "Revoke", "components.UserProfile.UserSettings.UserGeneralSettings.accounttype": "Account Type", "components.UserProfile.UserSettings.UserGeneralSettings.admin": "Admin", "components.UserProfile.UserSettings.UserGeneralSettings.applanguage": "Display Language", @@ -1618,6 +1624,7 @@ "components.UserProfile.UserSettings.UserPermissions.toastSettingsFailure": "Something went wrong while saving settings.", "components.UserProfile.UserSettings.UserPermissions.toastSettingsSuccess": "Permissions saved successfully!", "components.UserProfile.UserSettings.UserPermissions.unauthorizedDescription": "You cannot modify your own permissions.", + "components.UserProfile.UserSettings.menuApiKey": "API Key", "components.UserProfile.UserSettings.menuChangePass": "Password", "components.UserProfile.UserSettings.menuGeneralSettings": "General", "components.UserProfile.UserSettings.menuLinkedAccounts": "Linked Accounts", diff --git a/src/pages/profile/settings/api-key.tsx b/src/pages/profile/settings/api-key.tsx new file mode 100644 index 0000000000..622d3904b0 --- /dev/null +++ b/src/pages/profile/settings/api-key.tsx @@ -0,0 +1,13 @@ +import UserSettings from '@app/components/UserProfile/UserSettings'; +import UserApiKey from '@app/components/UserProfile/UserSettings/UserApiKey'; +import type { NextPage } from 'next'; + +const UserApiKeyPage: NextPage = () => { + return ( + + + + ); +}; + +export default UserApiKeyPage; diff --git a/src/pages/users/[userId]/settings/api-key.tsx b/src/pages/users/[userId]/settings/api-key.tsx new file mode 100644 index 0000000000..274fb5c86d --- /dev/null +++ b/src/pages/users/[userId]/settings/api-key.tsx @@ -0,0 +1,16 @@ +import UserSettings from '@app/components/UserProfile/UserSettings'; +import UserApiKey from '@app/components/UserProfile/UserSettings/UserApiKey'; +import useRouteGuard from '@app/hooks/useRouteGuard'; +import { Permission } from '@app/hooks/useUser'; +import type { NextPage } from 'next'; + +const UserApiKeyPage: NextPage = () => { + useRouteGuard(Permission.MANAGE_USERS); + return ( + + + + ); +}; + +export default UserApiKeyPage;