mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-08 10:27:08 +02:00
* feat(persistence): store hashed API keys on players * feat(core): refresh key-bound players without renaming them Add Players.Touch, which records usage for a player already identified by an API key without guessing its identity or overwriting its name. Register also stops renaming players that have an API key. Register no longer returns player save errors (or a stale FindMatch ErrNotFound when the save is rate-limited); save failures are only logged, and only the transcoding lookup error is returned, same as Touch. * feat(subsonic): authenticate with OpenSubsonic API keys Co-authored-by: amCap1712 <amCap1712@users.noreply.github.com> * feat(subsonic): add tokenInfo and advertise apiKeyAuthentication * feat(server): add endpoints to generate and revoke player API keys * feat(ui): manage player API keys Co-authored-by: amCap1712 <amCap1712@users.noreply.github.com> * fix(subsonic): throttle API keys per key and IP A stale key on one device exhausted the shared per-IP bucket and locked out every valid key from the same IP. The limiter only stores a hash of the bucket string, so the key is not retained. Also adds e2e coverage of API key auth through the real repository, and clarifies the player resolution log message. * fix(ui): keep the new API key dialog open until closed The key is shown only once, so Escape and backdrop clicks no longer dismiss it. Also clarifies when the key can be used as a password. * refactor: simplify API key code paths Share the player refresh tail between Register and Touch, fold the ownership-filtered write tail into execOwned, parse the query once for apiKey conflicts, derive HasAPIKey in the player mock, share the player form inputs between create and edit, and pick the delete button by key state instead of spreading conditional props. * feat(players): set API keys through the player record The key is a write-only apiKey field applied on save: required and owner-only on create, optional on edit, empty to revoke. Replaces the generate/revoke endpoints. * fix(players): reject API keys already in use Creating or editing a player with a key another player already has now returns a validation error instead of a 500, and a create that loses the race no longer leaves a keyless player behind. Ownership is checked before the key on create. * feat(ui): edit player API keys as a form field Replaces the show-once dialog, whose icon-less Close button was invisible on mobile. The key is generated in the browser, required and pre-filled on create. * fix(ui): keep new player API keys out of the record cache The json-server create response echoes the request body, and undoable edits merge the payload into the cache, so the key could reappear on the edit page. Strip it from the create result and save player edits pessimistically. Also fall back to a prompt when the clipboard write fails. * fix(ui): polish player API key field Set userId on the created player record so owner actions show immediately, and show a neutral no-key message to non-owners. * refactor: simplify player API key create and field Write the key hash in the create INSERT so the unique index settles races, re-read the created player instead of hand-building the cached record, reuse isWritable for the revoke check, and collapse the key field's derived state and generate/regenerate buttons. * fix(ui): let the API key field size like other inputs fullWidth is now opt-in instead of forced. * fix(ui): align the API key field with other player inputs Apply react-admin's input className, move the actions (now including Copy) below the field, and use a monospace font so the whole key fits. * fix(ui): redirect to the player list after create Matches the other create pages. * refactor(persistence): name the write-access rule for owned rows Owned-row writes now say which row they target and who may write it: ownedRow(rowID, ownerOrAdmin|ownerOnly) builds the WHERE, updateOwnedRow applies it, and SetAPIKey uses ownerOnly instead of a hand-built user_id filter. updateOwned/deleteOwned keep their signatures. * fix(players): apply an edit's key change and fields atomically Update now runs SetAPIKey and the column update in one transaction. Also shares the key format check, drops FindByAPIKey's unneeded empty-key guard, and sets the context username only on the apiKey path. * fix(subsonic): treat any credential param sent with apiKey as a conflict The spec requires error 43 when u, p, t or s is present with apiKey, even with an empty value. * refactor(subsonic): leave the player cookie code unchanged for key-bound requests Return early instead of wrapping the cookie block, so the diff (and CodeQL's view of it) matches master. * fix(subsonic): don't count key lookup errors as failed logins A database error while checking a key sent as the password now surfaces as a server error instead of a bad password, so it no longer feeds the failed-login limiter. * feat(players): use nds_ as the API key prefix Part of a Navidrome secret prefix family (nd + a letter for the kind), alongside ndg_ for API v1 grants. * feat(ui): make player API keys easier to find Label the Settings menu entry "Players & API keys", add an API key filter to the player list, show the key icon in the mobile list, and add Brazilian Portuguese translations for the new player strings. Signed-off-by: Deluan <deluan@navidrome.org> * feat(ui): always show the player API key filter Signed-off-by: Deluan <deluan@navidrome.org> * fix(ui): hide the unset Last Seen date in the player list Players created by hand have no last_seen yet, which showed as 12/31/1. Signed-off-by: Deluan <deluan@navidrome.org> --------- Signed-off-by: Deluan <deluan@navidrome.org> Co-authored-by: amCap1712 <amCap1712@users.noreply.github.com>
252 lines
7.6 KiB
JavaScript
252 lines
7.6 KiB
JavaScript
import jsonServerProvider from 'ra-data-json-server'
|
|
import httpClient from './httpClient'
|
|
import { REST_URL } from '../consts'
|
|
|
|
const dataProvider = jsonServerProvider(REST_URL, httpClient)
|
|
|
|
const REFRESH_KIND = { album: 'al', artist: 'ar' }
|
|
|
|
const isAdmin = () => {
|
|
const role = localStorage.getItem('role')
|
|
return role === 'admin'
|
|
}
|
|
|
|
const getSelectedLibraries = () => {
|
|
try {
|
|
const state = JSON.parse(localStorage.getItem('state'))
|
|
const selectedLibraries = state?.library?.selectedLibraries || []
|
|
const userLibraries = state?.library?.userLibraries || []
|
|
|
|
// Validate selected libraries against current user libraries
|
|
const userLibraryIds = userLibraries.map((lib) => lib.id)
|
|
const validatedSelection = selectedLibraries.filter((id) =>
|
|
userLibraryIds.includes(id),
|
|
)
|
|
|
|
// If user has only one library, return empty array (no filter needed)
|
|
if (userLibraryIds.length === 1) {
|
|
return []
|
|
}
|
|
|
|
return validatedSelection
|
|
} catch (err) {
|
|
return []
|
|
}
|
|
}
|
|
|
|
// Function to apply library filtering to appropriate resources
|
|
const applyLibraryFilter = (resource, params) => {
|
|
// Content resources that should be filtered by selected libraries
|
|
const filteredResources = ['album', 'song', 'artist', 'playlistTrack', 'tag']
|
|
|
|
// Get selected libraries from localStorage
|
|
const selectedLibraries = getSelectedLibraries()
|
|
|
|
// Add library filter for content resources if libraries are selected
|
|
if (filteredResources.includes(resource) && selectedLibraries.length > 0) {
|
|
if (!params.filter) {
|
|
params.filter = {}
|
|
}
|
|
params.filter.library_id = selectedLibraries
|
|
}
|
|
|
|
return params
|
|
}
|
|
|
|
const mapResource = (resource, params) => {
|
|
switch (resource) {
|
|
// /api/playlistTrack?playlist_id=123 => /api/playlist/123/tracks
|
|
case 'playlistTrack': {
|
|
params.filter = params.filter || {}
|
|
|
|
let plsId = '0'
|
|
plsId = params.filter.playlist_id
|
|
if (!isAdmin()) {
|
|
params.filter.missing = false
|
|
}
|
|
params = applyLibraryFilter(resource, params)
|
|
|
|
return [`playlist/${plsId}/tracks`, params]
|
|
}
|
|
case 'album':
|
|
case 'song':
|
|
case 'artist':
|
|
case 'tag': {
|
|
params.filter = params.filter || {}
|
|
if (!isAdmin()) {
|
|
params.filter.missing = false
|
|
}
|
|
params = applyLibraryFilter(resource, params)
|
|
|
|
return [resource, params]
|
|
}
|
|
default:
|
|
return [resource, params]
|
|
}
|
|
}
|
|
|
|
const callDeleteMany = (resource, params) => {
|
|
const ids = (params.ids || []).map((id) => `id=${id}`)
|
|
const query = ids.length > 0 ? `?${ids.join('&')}` : ''
|
|
return httpClient(`${REST_URL}/${resource}${query}`, {
|
|
method: 'DELETE',
|
|
}).then((response) => ({ data: response.json.ids || [] }))
|
|
}
|
|
|
|
// Helper function to handle user-library associations
|
|
const handleUserLibraryAssociation = async (userId, libraryIds) => {
|
|
if (!libraryIds || libraryIds.length === 0) {
|
|
return // Admin users or users without library assignments
|
|
}
|
|
|
|
try {
|
|
await httpClient(`${REST_URL}/user/${userId}/library`, {
|
|
method: 'PUT',
|
|
body: JSON.stringify({ libraryIds }),
|
|
})
|
|
} catch (error) {
|
|
console.error('Error setting user libraries:', error) //eslint-disable-line no-console
|
|
throw error
|
|
}
|
|
}
|
|
|
|
// Enhanced user creation that handles library associations
|
|
const createUser = async (params) => {
|
|
const { data } = params
|
|
const { libraryIds, ...userData } = data
|
|
|
|
// First create the user
|
|
const userResponse = await dataProvider.create('user', { data: userData })
|
|
const userId = userResponse.data.id
|
|
|
|
// Then set library associations for non-admin users
|
|
if (!userData.isAdmin && libraryIds && libraryIds.length > 0) {
|
|
await handleUserLibraryAssociation(userId, libraryIds)
|
|
}
|
|
|
|
return userResponse
|
|
}
|
|
|
|
// Enhanced user update that handles library associations
|
|
const updateUser = async (params) => {
|
|
const { data } = params
|
|
const { libraryIds, ...userData } = data
|
|
const userId = params.id
|
|
|
|
// First update the user
|
|
const userResponse = await dataProvider.update('user', {
|
|
...params,
|
|
data: userData,
|
|
})
|
|
|
|
// Then handle library associations for non-admin users. Only admins can call
|
|
// this endpoint; for self-edits the server manages library assignments
|
|
if (isAdmin() && !userData.isAdmin && libraryIds !== undefined) {
|
|
await handleUserLibraryAssociation(userId, libraryIds)
|
|
}
|
|
|
|
return userResponse
|
|
}
|
|
|
|
// ra-data-json-server merges the request body into the result; re-read so the plaintext key is never cached
|
|
const createPlayer = async (resource, params) => {
|
|
const { data } = await dataProvider.create(resource, params)
|
|
return dataProvider.getOne(resource, { id: data.id })
|
|
}
|
|
|
|
const wrapperDataProvider = {
|
|
...dataProvider,
|
|
getList: (resource, params) => {
|
|
const [r, p] = mapResource(resource, params)
|
|
return dataProvider.getList(r, p)
|
|
},
|
|
getOne: (resource, params) => {
|
|
const [r, p] = mapResource(resource, params)
|
|
const response = dataProvider.getOne(r, p)
|
|
|
|
// Transform user data to ensure libraryIds is present for form compatibility
|
|
if (resource === 'user') {
|
|
return response.then((result) => {
|
|
if (result.data.libraries && Array.isArray(result.data.libraries)) {
|
|
result.data.libraryIds = result.data.libraries.map((lib) => lib.id)
|
|
}
|
|
return result
|
|
})
|
|
}
|
|
|
|
return response
|
|
},
|
|
getMany: (resource, params) => {
|
|
const [r, p] = mapResource(resource, params)
|
|
return dataProvider.getMany(r, p)
|
|
},
|
|
getManyReference: (resource, params) => {
|
|
const [r, p] = mapResource(resource, params)
|
|
return dataProvider.getManyReference(r, p)
|
|
},
|
|
update: (resource, params) => {
|
|
if (resource === 'user') {
|
|
return updateUser(params)
|
|
}
|
|
const [r, p] = mapResource(resource, params)
|
|
return dataProvider.update(r, p)
|
|
},
|
|
updateMany: (resource, params) => {
|
|
const [r, p] = mapResource(resource, params)
|
|
return dataProvider.updateMany(r, p)
|
|
},
|
|
create: (resource, params) => {
|
|
if (resource === 'user') {
|
|
return createUser(params)
|
|
}
|
|
const [r, p] = mapResource(resource, params)
|
|
if (resource === 'player') {
|
|
return createPlayer(r, p)
|
|
}
|
|
return dataProvider.create(r, p)
|
|
},
|
|
delete: (resource, params) => {
|
|
const [r, p] = mapResource(resource, params)
|
|
return dataProvider.delete(r, p)
|
|
},
|
|
deleteMany: (resource, params) => {
|
|
const [r, p] = mapResource(resource, params)
|
|
if (r.endsWith('/tracks') || resource === 'missing') {
|
|
return callDeleteMany(r, p)
|
|
}
|
|
return dataProvider.deleteMany(r, p)
|
|
},
|
|
addToPlaylist: (playlistId, data) => {
|
|
return httpClient(`${REST_URL}/playlist/${playlistId}/tracks`, {
|
|
method: 'POST',
|
|
body: JSON.stringify(data),
|
|
}).then(({ json }) => ({ data: json }))
|
|
},
|
|
getPlaylists: (songId) => {
|
|
return httpClient(`${REST_URL}/song/${songId}/playlists`).then(
|
|
({ 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,
|
|
}))
|
|
},
|
|
// The endpoint answers 204 with no body, but react-admin rejects any response without a
|
|
// `data` key, so the id stands in for one.
|
|
refreshMetadata: (resource, id) =>
|
|
httpClient(`${REST_URL}/metadata/${REFRESH_KIND[resource]}/${id}/refresh`, {
|
|
method: 'POST',
|
|
}).then(() => ({ data: { id } })),
|
|
}
|
|
|
|
export default wrapperDataProvider
|