mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-27 04:19:58 +01:00
feat(jellyfin): add Quick Connect sign-in (#6174)
* feat(jellyfin): add Quick Connect sign-in Jellyfin clients can now sign in without a password: the client shows a 6-digit code, a signed-in user approves it, and the client redeems a secret for its access token. - core/quickconnect: in-memory store shared by both routers through wire. Codes expire after 10 minutes; a secret redeems only once (Jellyfin allows repeats for 10 minutes); at most 1000 pending requests. - Jellyfin API: Initiate, Connect, Authorize and AuthenticateWithQuickConnect. Admins may approve for another user via UserId, like Swiftfin's admin page. Initiate and redeem share the login rate limiter; Connect does not, since Finamp and Streamyfin poll it every second. - Web UI: a Quick Connect item in the user menu looks up the code and shows the app and device before approving, so a user can't be tricked into approving an unknown device blindly. - Jellyfin.QuickConnect option, on by default like Jellyfin. It only matters when the Jellyfin API is enabled. * refactor(jellyfin): tidy Quick Connect naming and route guards Group the Quick Connect routes under one requireQuickConnect guard, make the request's device a named field so req.Device.ID can't be mistaken for a request id, and rename the web API response type to quickConnectDevice. * refactor(jellyfin): remove duplicated Jellyfin date formatting function * test(jellyfin): set play count and starred in the song fixture literal * refactor(jellyfin): inline the Quick Connect redeem body and use the shared date helper * fix(jellyfin): bound the client fields Quick Connect keeps in memory Initiate is unauthenticated and keeps the Client, Device, DeviceId and Version header fields for up to ten minutes. With no header size limit, each pending request could hold about 1 MB, and even a short field kept the whole header alive because the parsed values are substrings of it. Reject fields over 512 bytes and copy the stored values. Also answer 500 instead of 401 when the redeem user lookup fails for a reason other than the user being gone. * fix(jellyfin): rate-limit Quick Connect code approval Any signed-in user could try codes without limit on the Jellyfin Authorize endpoint and the web UI lookup/authorize endpoints, and so could approve another person's pending device for their own account. Apply the same per-IP limiter as the login (AuthRequestLimit/AuthWindowLength) to both surfaces.
This commit is contained in:
parent
be8ec15168
commit
b76ae14286
43 changed files with 1626 additions and 88 deletions
|
|
@ -38,6 +38,7 @@ const defaultConfig = {
|
|||
devUIShowConfig: true,
|
||||
devNewEventStream: false,
|
||||
enableReplayGain: true,
|
||||
enableQuickConnect: false,
|
||||
defaultDownsamplingFormat: 'opus',
|
||||
publicBaseUrl: '/share',
|
||||
separator: '/',
|
||||
|
|
|
|||
|
|
@ -218,6 +218,15 @@ const wrapperDataProvider = {
|
|||
({ json }) => ({ data: json }),
|
||||
)
|
||||
},
|
||||
lookupQuickConnect: (code) =>
|
||||
httpClient(
|
||||
`${REST_URL}/quickconnect?code=${encodeURIComponent(code)}`,
|
||||
).then(({ json }) => ({ data: json })),
|
||||
authorizeQuickConnect: (code) =>
|
||||
httpClient(`${REST_URL}/quickconnect/authorize`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code }),
|
||||
}).then(({ json }) => ({ data: json })),
|
||||
inspect: (songId) => {
|
||||
return httpClient(`${REST_URL}/inspect?id=${songId}`).then(({ json }) => ({
|
||||
data: json,
|
||||
|
|
|
|||
128
ui/src/dialogs/QuickConnectDialog.jsx
Normal file
128
ui/src/dialogs/QuickConnectDialog.jsx
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import { useState } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import { useDataProvider, useNotify, useTranslate } from 'react-admin'
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogContentText,
|
||||
DialogTitle,
|
||||
TextField,
|
||||
} from '@material-ui/core'
|
||||
|
||||
export const QuickConnectDialog = ({ open, onClose }) => {
|
||||
const translate = useTranslate()
|
||||
const notify = useNotify()
|
||||
const dataProvider = useDataProvider()
|
||||
const [code, setCode] = useState('')
|
||||
const [pending, setPending] = useState(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const handleClose = () => {
|
||||
setCode('')
|
||||
setPending(null)
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handleError = (error) => {
|
||||
setPending(null)
|
||||
const invalid = error?.status === 404 || error?.status === 409
|
||||
notify(
|
||||
invalid ? 'message.quickConnectInvalidCode' : 'message.quickConnectError',
|
||||
'warning',
|
||||
)
|
||||
}
|
||||
|
||||
const run = (request, onSuccess) => {
|
||||
setLoading(true)
|
||||
request
|
||||
.then(({ data }) => onSuccess(data))
|
||||
.catch(handleError)
|
||||
.finally(() => setLoading(false))
|
||||
}
|
||||
|
||||
const lookup = (event) => {
|
||||
event.preventDefault()
|
||||
run(dataProvider.lookupQuickConnect(code), setPending)
|
||||
}
|
||||
|
||||
const approve = () =>
|
||||
run(dataProvider.authorizeQuickConnect(code), (data) => {
|
||||
notify('message.quickConnectApproved', 'success', {
|
||||
app: data.appName,
|
||||
device: data.deviceName,
|
||||
})
|
||||
handleClose()
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
aria-labelledby="quick-connect-dialog"
|
||||
fullWidth
|
||||
maxWidth="xs"
|
||||
>
|
||||
<DialogTitle id="quick-connect-dialog">
|
||||
{translate('menu.quickConnect.name')}
|
||||
</DialogTitle>
|
||||
{pending ? (
|
||||
<>
|
||||
<DialogContent>
|
||||
<DialogContentText>
|
||||
{translate('menu.quickConnect.confirm', {
|
||||
app: pending.appName,
|
||||
version: pending.appVersion,
|
||||
device: pending.deviceName,
|
||||
})}
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setPending(null)} color="primary">
|
||||
{translate('ra.action.back')}
|
||||
</Button>
|
||||
<Button onClick={approve} color="primary" disabled={loading}>
|
||||
{translate('menu.quickConnect.approve')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</>
|
||||
) : (
|
||||
<form onSubmit={lookup}>
|
||||
<DialogContent>
|
||||
<DialogContentText>
|
||||
{translate('menu.quickConnect.help')}
|
||||
</DialogContentText>
|
||||
<TextField
|
||||
id="quickConnectCode"
|
||||
variant="outlined"
|
||||
fullWidth
|
||||
autoFocus
|
||||
label={translate('menu.quickConnect.code')}
|
||||
value={code}
|
||||
onChange={(event) => setCode(event.target.value)}
|
||||
inputProps={{ inputMode: 'numeric', autoComplete: 'off' }}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={handleClose} color="primary">
|
||||
{translate('ra.action.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
color="primary"
|
||||
disabled={!code.trim() || loading}
|
||||
>
|
||||
{translate('menu.quickConnect.continue')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</form>
|
||||
)}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
QuickConnectDialog.propTypes = {
|
||||
open: PropTypes.bool.isRequired,
|
||||
onClose: PropTypes.func.isRequired,
|
||||
}
|
||||
103
ui/src/dialogs/QuickConnectDialog.test.jsx
Normal file
103
ui/src/dialogs/QuickConnectDialog.test.jsx
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import * as React from 'react'
|
||||
import { TestContext } from 'ra-test'
|
||||
import { DataProviderContext } from 'react-admin'
|
||||
import {
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from '@testing-library/react'
|
||||
import { describe, afterEach, it, expect, vi } from 'vitest'
|
||||
import { QuickConnectDialog } from './QuickConnectDialog'
|
||||
|
||||
const finamp = { appName: 'Finamp', appVersion: '1.0.0', deviceName: 'Pixel 7' }
|
||||
|
||||
const renderDialog = (dataProvider, onClose = vi.fn()) => {
|
||||
render(
|
||||
<DataProviderContext.Provider value={dataProvider}>
|
||||
<TestContext initialState={{ admin: { ui: { optimistic: false } } }}>
|
||||
<QuickConnectDialog open={true} onClose={onClose} />
|
||||
</TestContext>
|
||||
</DataProviderContext.Provider>,
|
||||
)
|
||||
return onClose
|
||||
}
|
||||
|
||||
const enterCode = (code) => {
|
||||
fireEvent.change(screen.getByRole('textbox'), { target: { value: code } })
|
||||
fireEvent.click(screen.getByText('menu.quickConnect.continue'))
|
||||
}
|
||||
|
||||
describe('QuickConnectDialog', () => {
|
||||
afterEach(cleanup)
|
||||
|
||||
it('shows the device before approving the code', async () => {
|
||||
const dataProvider = {
|
||||
lookupQuickConnect: vi.fn().mockResolvedValue({ data: finamp }),
|
||||
authorizeQuickConnect: vi.fn().mockResolvedValue({ data: finamp }),
|
||||
}
|
||||
const onClose = renderDialog(dataProvider)
|
||||
|
||||
enterCode('123 456')
|
||||
await screen.findByText('menu.quickConnect.approve')
|
||||
expect(dataProvider.lookupQuickConnect.mock.calls[0][0]).toBe('123 456')
|
||||
expect(dataProvider.authorizeQuickConnect).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.click(screen.getByText('menu.quickConnect.approve'))
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalled())
|
||||
expect(dataProvider.authorizeQuickConnect.mock.calls[0][0]).toBe('123 456')
|
||||
})
|
||||
|
||||
it('goes back to the code input', async () => {
|
||||
const dataProvider = {
|
||||
lookupQuickConnect: vi.fn().mockResolvedValue({ data: finamp }),
|
||||
authorizeQuickConnect: vi.fn(),
|
||||
}
|
||||
renderDialog(dataProvider)
|
||||
|
||||
enterCode('123456')
|
||||
await screen.findByText('menu.quickConnect.approve')
|
||||
fireEvent.click(screen.getByText('ra.action.back'))
|
||||
|
||||
expect(screen.getByRole('textbox')).toHaveValue('123456')
|
||||
expect(dataProvider.authorizeQuickConnect).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stays on the code input when the code is unknown', async () => {
|
||||
const dataProvider = {
|
||||
lookupQuickConnect: vi.fn().mockRejectedValue({ status: 404 }),
|
||||
authorizeQuickConnect: vi.fn(),
|
||||
}
|
||||
const onClose = renderDialog(dataProvider)
|
||||
|
||||
enterCode('000000')
|
||||
await waitFor(() =>
|
||||
expect(dataProvider.lookupQuickConnect).toHaveBeenCalled(),
|
||||
)
|
||||
expect(screen.getByRole('textbox')).toBeInTheDocument()
|
||||
expect(screen.queryByText('menu.quickConnect.approve')).toBeNull()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns to the code input when approval fails', async () => {
|
||||
const dataProvider = {
|
||||
lookupQuickConnect: vi.fn().mockResolvedValue({ data: finamp }),
|
||||
authorizeQuickConnect: vi.fn().mockRejectedValue({ status: 409 }),
|
||||
}
|
||||
const onClose = renderDialog(dataProvider)
|
||||
|
||||
enterCode('123456')
|
||||
fireEvent.click(await screen.findByText('menu.quickConnect.approve'))
|
||||
|
||||
await screen.findByRole('textbox')
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('disables Continue until a code is typed', () => {
|
||||
renderDialog({ lookupQuickConnect: vi.fn() })
|
||||
expect(
|
||||
screen.getByText('menu.quickConnect.continue').closest('button'),
|
||||
).toBeDisabled()
|
||||
})
|
||||
})
|
||||
|
|
@ -2,4 +2,5 @@ export * from './AboutDialog'
|
|||
export * from './SelectPlaylistInput'
|
||||
export * from './ListenBrainzTokenDialog'
|
||||
export * from './SaveQueueDialog'
|
||||
export * from './QuickConnectDialog'
|
||||
export * from './Dialogs'
|
||||
|
|
|
|||
|
|
@ -591,6 +591,9 @@
|
|||
"remove_all_missing_content": "Are you sure you want to remove all missing files from the database? This will permanently remove any references to them, including their play counts and ratings.",
|
||||
"notifications_blocked": "You have blocked Notifications for this site in your browser's settings",
|
||||
"notifications_not_available": "This browser does not support desktop notifications or you are not accessing Navidrome over https",
|
||||
"quickConnectApproved": "%{app} on %{device} is now signed in",
|
||||
"quickConnectInvalidCode": "Invalid or expired code",
|
||||
"quickConnectError": "Could not approve the code",
|
||||
"lastfmLinkSuccess": "Last.fm successfully linked and scrobbling enabled",
|
||||
"lastfmLinkFailure": "Last.fm could not be linked",
|
||||
"lastfmUnlinkSuccess": "Last.fm unlinked and scrobbling disabled",
|
||||
|
|
@ -622,6 +625,14 @@
|
|||
"none": "None"
|
||||
},
|
||||
"settings": "Settings",
|
||||
"quickConnect": {
|
||||
"name": "Quick Connect",
|
||||
"code": "Code",
|
||||
"help": "Enter the code shown by a Jellyfin app to sign it in to your account",
|
||||
"confirm": "Sign in %{app} %{version} on %{device} to your account?",
|
||||
"continue": "Continue",
|
||||
"approve": "Approve"
|
||||
},
|
||||
"version": "Version",
|
||||
"theme": "Theme",
|
||||
"personal": {
|
||||
|
|
|
|||
|
|
@ -6,12 +6,17 @@ import {
|
|||
usePermissions,
|
||||
getResources,
|
||||
} from 'react-admin'
|
||||
import { MdInfo, MdPerson, MdSupervisorAccount } from 'react-icons/md'
|
||||
import {
|
||||
MdInfo,
|
||||
MdPerson,
|
||||
MdPhonelink,
|
||||
MdSupervisorAccount,
|
||||
} from 'react-icons/md'
|
||||
import { useSelector } from 'react-redux'
|
||||
import { makeStyles, MenuItem, ListItemIcon, Divider } from '@material-ui/core'
|
||||
import ViewListIcon from '@material-ui/icons/ViewList'
|
||||
import { Dialogs } from '../dialogs/Dialogs'
|
||||
import { AboutDialog } from '../dialogs'
|
||||
import { AboutDialog, QuickConnectDialog } from '../dialogs'
|
||||
import PersonalMenu from './PersonalMenu'
|
||||
import ActivityPanel from './ActivityPanel'
|
||||
import NowPlayingPanel from './NowPlayingPanel'
|
||||
|
|
@ -33,33 +38,34 @@ const useStyles = makeStyles(
|
|||
},
|
||||
)
|
||||
|
||||
const AboutMenuItem = forwardRef(({ onClick, ...rest }, ref) => {
|
||||
const classes = useStyles(rest)
|
||||
const translate = useTranslate()
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const DialogMenuItem = forwardRef(
|
||||
({ onClick, label, icon, dialog, ...rest }, ref) => {
|
||||
const classes = useStyles(rest)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
|
||||
const handleOpen = () => {
|
||||
setOpen(true)
|
||||
}
|
||||
const handleClose = () => {
|
||||
onClick && onClick()
|
||||
setOpen(false)
|
||||
}
|
||||
const label = translate('menu.about')
|
||||
return (
|
||||
<>
|
||||
<MenuItem ref={ref} onClick={handleOpen} className={classes.root}>
|
||||
<ListItemIcon className={classes.icon}>
|
||||
<MdInfo title={label} size={24} />
|
||||
</ListItemIcon>
|
||||
{label}
|
||||
</MenuItem>
|
||||
<AboutDialog onClose={handleClose} open={open} />
|
||||
</>
|
||||
)
|
||||
})
|
||||
const handleClose = () => {
|
||||
onClick && onClick()
|
||||
setOpen(false)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<MenuItem
|
||||
ref={ref}
|
||||
onClick={() => setOpen(true)}
|
||||
className={classes.root}
|
||||
>
|
||||
<ListItemIcon className={classes.icon}>
|
||||
{createElement(icon, { title: label, size: 24 })}
|
||||
</ListItemIcon>
|
||||
{label}
|
||||
</MenuItem>
|
||||
{createElement(dialog, { onClose: handleClose, open })}
|
||||
</>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
AboutMenuItem.displayName = 'AboutMenuItem'
|
||||
DialogMenuItem.displayName = 'DialogMenuItem'
|
||||
|
||||
const settingsResources = (resource) =>
|
||||
resource.name !== 'user' &&
|
||||
|
|
@ -126,13 +132,24 @@ const CustomUserMenu = ({ onClick, ...rest }) => {
|
|||
{config.devActivityPanel && permissions === 'admin' && <ActivityPanel />}
|
||||
<UserMenu {...rest}>
|
||||
<PersonalMenu sidebarIsOpen={true} onClick={onClick} />
|
||||
{config.enableQuickConnect && (
|
||||
<DialogMenuItem
|
||||
label={translate('menu.quickConnect.name')}
|
||||
icon={MdPhonelink}
|
||||
dialog={QuickConnectDialog}
|
||||
/>
|
||||
)}
|
||||
<Divider />
|
||||
{renderUserMenuItemLink()}
|
||||
{resources
|
||||
.filter(settingsResources)
|
||||
.map((r) => renderSettingsMenuItemLink(r))}
|
||||
<Divider />
|
||||
<AboutMenuItem />
|
||||
<DialogMenuItem
|
||||
label={translate('menu.about')}
|
||||
icon={MdInfo}
|
||||
dialog={AboutDialog}
|
||||
/>
|
||||
</UserMenu>
|
||||
<Dialogs />
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -33,12 +33,14 @@ vi.mock('../dialogs/Dialogs', () => ({
|
|||
}))
|
||||
vi.mock('../dialogs', () => ({
|
||||
AboutDialog: () => <div />,
|
||||
QuickConnectDialog: () => <div />,
|
||||
}))
|
||||
|
||||
describe('<AppBar />', () => {
|
||||
beforeEach(() => {
|
||||
config.devActivityPanel = true
|
||||
config.enableNowPlaying = true
|
||||
config.enableQuickConnect = false
|
||||
store = createStore(combineReducers({ activity: activityReducer }), {
|
||||
activity: { nowPlayingCount: 0 },
|
||||
})
|
||||
|
|
@ -62,4 +64,24 @@ describe('<AppBar />', () => {
|
|||
)
|
||||
expect(screen.queryByTestId('now-playing-panel')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows the Quick Connect menu item when enabled', () => {
|
||||
config.enableQuickConnect = true
|
||||
render(
|
||||
<Provider store={store}>
|
||||
<AppBar />
|
||||
</Provider>,
|
||||
)
|
||||
expect(screen.queryAllByText('menu.quickConnect.name')).not.toHaveLength(0)
|
||||
})
|
||||
|
||||
it('hides the Quick Connect menu item when disabled', () => {
|
||||
render(
|
||||
<Provider store={store}>
|
||||
<AppBar />
|
||||
</Provider>,
|
||||
)
|
||||
expect(screen.queryAllByText('menu.quickConnect.name')).toHaveLength(0)
|
||||
expect(screen.queryAllByText('menu.about')).not.toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue