feat(federation): shared libraries and the signed read API for friends

A friend's server can now read what an admin chose to share.

- A library has a shared flag, off by default (migration 0024), set with
  PATCH /libraries/{id}. Changing it never waits for a scan.
- Requests between friends are signed with each server's Ed25519 key: the
  method, the path and query from /api/v1/peer on, a date, a nonce and the
  hash of the empty body. A date more than two minutes off, a nonce used
  before, an unknown or removed key and a bad signature all get the same
  401. A friend still waiting for approval gets 403, and while federation is
  off the routes are missing.
- Routes under /api/v1/peer: info, artists, albums, tracks, covers and
  streaming with Range. The catalogue, the counts and the format come from
  the shared libraries only, and the file served is the one in a shared
  library. No path, library id, listen, taste, user or provider data is part
  of an answer.
- A friend never makes this server build a cover, read an audio file or ask
  a provider: only covers already built from the audio files are served.
- Per-friend limits, set by the admin: parallel streams (default 3) and KiB
  a second (default 4096, 0 for none), shared by all the streams of a friend.
- A log of the last requests friends made (route, status, bytes; never the
  query), kept for 7 days, in GET /federation/requests.
- POST /federation/friends/{id}/check lets the side that pasted an invite
  find out that the other admin approved; a signed call from a friend this
  server is waiting for makes it active too.
- Admin: a Shared with friends switch on each library, which asks first, and
  limits, recent requests and a Check button in the Federation section, in
  English and Italian.
- OpenAPI paths and schemas, contract test, two real servers checked end to
  end with tagged audio files.
This commit is contained in:
tgiachi 2026-11-13 15:04:07 +01:00
commit 89826fcd07
12 changed files with 3970 additions and 60 deletions

View file

@ -5,12 +5,17 @@ import type { components } from './schema'
export type Federation = components['schemas']['Federation']
export type FederationFriend = components['schemas']['FederationFriend']
export type FederationInvite = components['schemas']['FederationInvite']
export type FederationRequest = components['schemas']['FederationRequest']
/** What `PUT /federation` takes: any of these, and what is left out is kept. */
export interface FederationChanges {
enabled?: boolean
name?: string
address?: string
/** Streams one friend may have open at a time, 1 to 20. */
max_streams?: number
/** KiB a second one friend may take; 0 means no limit, otherwise 64 or more. */
max_kib_per_sec?: number
}
const FEDERATION = ['federation']
@ -60,3 +65,21 @@ export function useRemoveFriend() {
onSuccess: () => client.invalidateQueries({ queryKey: FEDERATION }),
})
}
/** Asks a friend that is waiting, signed, whether it approved: an answer makes it a friend. */
export function useCheckFriend() {
const client = useQueryClient()
return useMutation({
mutationFn: (id: number) => api.post<FederationFriend>(`/federation/friends/${id}/check`),
onSuccess: () => client.invalidateQueries({ queryKey: FEDERATION }),
})
}
/** The last requests friends made to this server, newest first. */
export function useFederationRequests() {
return useQuery({
queryKey: [...FEDERATION, 'requests'],
queryFn: () => api.get<{ requests: FederationRequest[] }>('/federation/requests'),
select: (data) => data.requests,
})
}

View file

@ -26,11 +26,11 @@ export function useAddLibrary() {
})
}
/** Rename, move, or both: only the fields given are sent. */
/** Rename, move, share with friends, or any of them: only the fields given are sent. */
export function useUpdateLibrary() {
const client = useQueryClient()
return useMutation({
mutationFn: ({ id, ...changes }: { id: number; name?: string; path?: string }) => api.patch<Library>(`/libraries/${id}`, changes),
mutationFn: ({ id, ...changes }: { id: number; name?: string; path?: string; shared?: boolean }) => api.patch<Library>(`/libraries/${id}`, changes),
onSuccess: () => client.invalidateQueries({ queryKey: LIBRARIES }),
})
}

View file

@ -2163,6 +2163,241 @@ export interface paths {
patch?: never;
trace?: never;
};
"/federation/friends/{id}/check": {
parameters: {
query?: never;
header?: never;
path: {
id: number;
};
cookie?: never;
};
get?: never;
put?: never;
/**
* Ask a friend whether it approved
* @description Admin only. Sends the friend one signed request (`GET /peer/info`). An answer means it approved, and a friend that
* was `outgoing` becomes `active`. The friend is returned. A friend in state `incoming` is a `409` (`not_waiting`):
* it waits for this server's admin, not the other way round.
*/
post: operations["checkFederationFriend"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/federation/requests": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The last requests friends made
* @description Admin only. The last 50 requests that friends made to this server, newest first, kept for 7 days: when, which
* friend, which route (the pattern, never the query, so what was searched for is not kept), the status and how many
* bytes were sent.
*/
get: operations["listFederationRequests"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/info": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Who this server is (called by a friend)
* @description Not for people: a friend's server calls this, signed (see the `friendSignature` scheme), and also to find out whether
* this server's admin approved it. Says the name of this server and how many libraries are shared.
*/
get: operations["peerInfo"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/artists": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The artists of the shared libraries (called by a friend)
* @description Like `GET /artists`, over the libraries that are shared and nothing else: an artist is listed only when it has a
* playable track in one of them, and the counts are of those tracks. Paths, library ids and everything that providers
* said are never part of it. Signed like every `/peer` route.
*/
get: operations["peerListArtists"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/artists/{id}": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
/** One artist of the shared libraries (called by a friend) */
get: operations["peerGetArtist"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/albums": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The albums of the shared libraries (called by a friend)
* @description Like `GET /albums`, over the libraries that are shared. Signed like every `/peer` route.
*/
get: operations["peerListAlbums"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/albums/{id}": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
/** One album of the shared libraries (called by a friend) */
get: operations["peerGetAlbum"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/albums/{id}/cover": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
/**
* The cover of an album of the shared libraries (called by a friend)
* @description Only a cover that this server already built from the audio files of the album: a friend never makes this server
* build one, read an audio file or ask a provider. A cover that came from the Cover Art Archive is not given. Any other
* album answers `cover_not_found`. The bytes go out within the friend's allowance.
*/
get: operations["peerGetAlbumCover"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/tracks": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The tracks of the shared libraries (called by a friend)
* @description Like `GET /tracks`, over the libraries that are shared. Signed like every `/peer` route.
*/
get: operations["peerListTracks"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/tracks/{id}": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
/** One track of the shared libraries (called by a friend) */
get: operations["peerGetTrack"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/tracks/{id}/stream": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
/**
* Stream a track of the shared libraries (called by a friend)
* @description The file of the track that lives in a shared library, with `Range` support, as a listener would get it. A track that is
* only in libraries that are not shared is `track_not_found`. A friend has a few streams open at a time and a number
* of bytes a second to share among them, both set by the admin (`max_streams`, `max_kib_per_sec`): one stream too many
* is a `429` (`too_many_streams`) with `Retry-After`.
*/
get: operations["peerStreamTrack"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@ -2236,6 +2471,8 @@ export interface components {
name: string;
/** @description Absolute directory on the server. */
path: string;
/** @description Whether friends (federation) may read this library. Off until an admin turns it on. */
shared: boolean;
/** Format: date-time */
created_at: string;
};
@ -2247,7 +2484,9 @@ export interface components {
LibraryUpdate: {
name?: string;
path?: string;
} | unknown | unknown;
/** @description Whether friends may read this library. Changing it never needs a scan and never waits for one. */
shared?: boolean;
} | unknown | unknown | unknown;
ScanSummary: {
/** @description Libraries covered by the scan. */
libraries: number;
@ -3207,14 +3446,40 @@ export interface components {
key_id: string;
/** @description What a friend's server is sent, and what it never learns. */
sends: string;
/** @description Streams one friend may have open at a time. */
max_streams: number;
/** @description KiB a second one friend may take over all its streams; 0 means no limit. Otherwise at least 64. */
max_kib_per_sec: number;
friends: components["schemas"]["FederationFriend"][];
};
FederationUpdate: {
enabled?: boolean;
max_streams?: number;
max_kib_per_sec?: number;
/** @description At most 60 characters, no control characters. Empty goes back to the host name. */
name?: string;
address?: string;
} | unknown | unknown | unknown;
} | unknown | unknown | unknown | unknown | unknown;
FederationRequest: {
/** Format: date-time */
at: string;
friend_id: number;
/** @description The name of the friend. */
friend: string;
/** @description The route pattern, like `/api/v1/peer/tracks/:id/stream`. Never the query. */
route: string;
status: number;
/**
* Format: int64
* @description Bytes of the answer.
*/
bytes: number;
};
PeerInfo: {
name: string;
/** @description How many libraries are shared with friends. */
shared_libraries: number;
};
FederationInvite: {
/** @description One piece of text to give to the other admin. Starts with `sonda1.`. */
invite: string;
@ -3256,6 +3521,33 @@ export interface components {
};
};
responses: {
/** @description The request is not signed by a friend: no signature, a bad one, an old date, a nonce used before or an unknown key, all the same answer (`unauthorized`). */
FriendUnauthorized: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description The signature is good but the admin of this server has not approved the friend yet (`not_approved`). */
FriendNotApproved: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Federation is off on this server, so the route is as good as missing (`not_found`). */
FederationOff: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description The request is malformed or a value is out of range (`invalid_input`). */
InvalidInput: {
headers: {
@ -7040,4 +7332,442 @@ export interface operations {
};
};
};
checkFederationFriend: {
parameters: {
query?: never;
header?: never;
path: {
id: number;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The friend, active when it answered. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["FederationFriend"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
403: components["responses"]["AdminRequired"];
/** @description No such friend (`friend_not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/**
* @description Federation is off (`federation_off`), the friend is not waiting for the other admin (`not_waiting`), the other
* admin has not approved yet (`not_approved`), or the other server does not take this one for a friend any more
* (`friend_gone`).
*/
409: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description The other server could not be reached or did not answer as a Sonda server (`friend_unreachable`). */
502: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
listFederationRequests: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The requests. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
requests: components["schemas"]["FederationRequest"][];
};
};
};
401: components["responses"]["Unauthorized"];
403: components["responses"]["AdminRequired"];
};
};
peerInfo: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The name and the number of shared libraries. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PeerInfo"];
};
};
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
404: components["responses"]["FederationOff"];
};
};
peerListArtists: {
parameters: {
query?: {
/**
* @description Case- and accent-insensitive substring of the name or title: `bjork`, `BJORK` and `BJÖRK` all
* find `Björk`, and `strasse` finds `Straße`. At most 200 characters.
*/
q?: components["parameters"]["Q"];
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
limit?: components["parameters"]["Limit"];
offset?: components["parameters"]["Offset"];
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description A page of artists. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ArtistPage"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
404: components["responses"]["FederationOff"];
};
};
peerGetArtist: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The artist. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Artist"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
/** @description No such artist among the shared libraries (`artist_not_found`), or federation is off (`not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
peerListAlbums: {
parameters: {
query?: {
/**
* @description Case- and accent-insensitive substring of the name or title: `bjork`, `BJORK` and `BJÖRK` all
* find `Björk`, and `strasse` finds `Straße`. At most 200 characters.
*/
q?: components["parameters"]["Q"];
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
limit?: components["parameters"]["Limit"];
offset?: components["parameters"]["Offset"];
artist_id?: components["parameters"]["ArtistId"];
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description A page of albums. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["AlbumPage"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
404: components["responses"]["FederationOff"];
};
};
peerGetAlbum: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The album. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Album"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
/** @description No such album among the shared libraries (`album_not_found`), or federation is off (`not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
peerGetAlbumCover: {
parameters: {
query?: {
/** @description `small` or `large`. Large when absent. */
size?: "small" | "large";
};
header?: {
"If-None-Match"?: string;
};
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The cover. */
200: {
headers: {
ETag: components["headers"]["ETag"];
"Cache-Control": components["headers"]["CacheControl"];
"Content-Length": components["headers"]["ContentLength"];
[name: string]: unknown;
};
content: {
"image/jpeg": string;
};
};
/** @description Not modified since `If-None-Match`. */
304: {
headers: {
[name: string]: unknown;
};
content?: never;
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
/** @description No such album among the shared libraries (`album_not_found`), no cover built (`cover_not_found`), or federation is off (`not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
peerListTracks: {
parameters: {
query?: {
/**
* @description Case- and accent-insensitive substring of the name or title: `bjork`, `BJORK` and `BJÖRK` all
* find `Björk`, and `strasse` finds `Straße`. At most 200 characters.
*/
q?: components["parameters"]["Q"];
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
limit?: components["parameters"]["Limit"];
offset?: components["parameters"]["Offset"];
artist_id?: components["parameters"]["ArtistId"];
album_id?: components["parameters"]["AlbumId"];
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description A page of tracks. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["TrackPage"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
404: components["responses"]["FederationOff"];
};
};
peerGetTrack: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The track. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Track"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
/** @description No such track among the shared libraries (`track_not_found`), or federation is off (`not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
peerStreamTrack: {
parameters: {
query?: never;
header?: {
/** @description A byte range, for example `bytes=0-99`. */
Range?: string;
"If-Modified-Since"?: string;
};
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The whole file. */
200: {
headers: {
"Accept-Ranges": components["headers"]["AcceptRanges"];
"Content-Length": components["headers"]["ContentLength"];
"Last-Modified": components["headers"]["LastModified"];
[name: string]: unknown;
};
content: {
"audio/mpeg": string;
"audio/flac": string;
};
};
/** @description The requested byte range. */
206: {
headers: {
/** @description The range sent and the size of the file, for example `bytes 0-99/40635`. */
"Content-Range"?: string;
[name: string]: unknown;
};
content: {
"audio/mpeg": string;
"audio/flac": string;
"multipart/byteranges": string;
};
};
/** @description Not modified since `If-Modified-Since`. */
304: {
headers: {
[name: string]: unknown;
};
content?: never;
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
/** @description No such track among the shared libraries (`track_not_found`), its file is not available (`file_missing`), or federation is off (`not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description The range cannot be satisfied. */
416: {
headers: {
/** @description `bytes *\/<size of the file>`. */
"Content-Range"?: string;
[name: string]: unknown;
};
content?: never;
};
/** @description The friend already has as many streams open as allowed (`too_many_streams`). */
429: {
headers: {
/** @description Seconds to wait. */
"Retry-After"?: number;
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
}

View file

@ -342,7 +342,13 @@
"errors": {
"invalid_input": "The folder must be an existing directory on the server, not the root, and not inside or around another library.",
"library_exists": "Another library already has this name or folder."
}
},
"share": "Share {{name}} with friends",
"shared": "Shared with friends",
"notShared": "Not shared with friends",
"shareTitle": "Share {{name}} with friends?",
"shareBody": "The listeners of your friends' servers will be able to browse this library, play it, and in practice copy its files. Nothing is sent until a friend's server asks, and you can stop sharing at any time.",
"shareConfirm": "Share"
},
"scan": {
"title": "Scan",
@ -422,8 +428,26 @@
"already_friends": "That server is already a friend.",
"too_many_requests": "Too many attempts. Try again in a minute.",
"friend_not_found": "That friend is already gone.",
"not_waiting": "That friend is not waiting for approval."
}
"not_waiting": "That friend is not waiting for approval.",
"not_approved": "The other admin has not approved yet.",
"friend_gone": "That server no longer takes this server for a friend."
},
"check": "Check",
"checkOne": "Check {{name}}",
"limits": "Limits for each friend",
"streams": "Streams at a time",
"streamsHint": "How many songs one friend may play at the same time, from 1 to 20.",
"rate": "KiB a second",
"rateHint": "What one friend may take in all, over all its streams. 0 means no limit; otherwise at least 64.",
"saveLimits": "Save limits",
"requests": "Recent requests",
"requestsHint": "The last requests friends made, kept for 7 days. Only the route is kept, never what was searched for.",
"noRequests": "No friend has asked for anything yet.",
"when": "When",
"friendCol": "Friend",
"route": "Route",
"status": "Status",
"sent": "Sent"
}
},
"lidarr": {

View file

@ -342,7 +342,13 @@
"errors": {
"invalid_input": "La cartella deve essere una directory esistente sul server, non la radice, e non dentro o attorno a un'altra libreria.",
"library_exists": "Un'altra libreria ha già questo nome o questa cartella."
}
},
"share": "Condividi {{name}} con gli amici",
"shared": "Condivisa con gli amici",
"notShared": "Non condivisa con gli amici",
"shareTitle": "Condividere {{name}} con gli amici?",
"shareBody": "Gli ascoltatori dei server dei tuoi amici potranno sfogliare questa libreria, riprodurla e, in pratica, copiarne i file. Non viene inviato nulla finché il server di un amico non lo chiede, e puoi smettere di condividere quando vuoi.",
"shareConfirm": "Condividi"
},
"scan": {
"title": "Scansione",
@ -422,8 +428,26 @@
"already_friends": "Quel server è già un amico.",
"too_many_requests": "Troppi tentativi. Riprova tra un minuto.",
"friend_not_found": "Quell'amico non c'è già più.",
"not_waiting": "Quell'amico non aspetta un'approvazione."
}
"not_waiting": "Quell'amico non aspetta un'approvazione.",
"not_approved": "L'altro admin non ha ancora approvato.",
"friend_gone": "Quel server non considera più questo server un amico."
},
"check": "Controlla",
"checkOne": "Controlla {{name}}",
"limits": "Limiti per ogni amico",
"streams": "Riproduzioni in parallelo",
"streamsHint": "Quante canzoni può riprodurre un amico nello stesso momento, da 1 a 20.",
"rate": "KiB al secondo",
"rateHint": "Quanto può prendere un amico in tutto, su tutte le sue riproduzioni. 0 vuol dire nessun limite; altrimenti almeno 64.",
"saveLimits": "Salva i limiti",
"requests": "Richieste recenti",
"requestsHint": "Le ultime richieste degli amici, tenute per 7 giorni. Si tiene solo il percorso, mai ciò che è stato cercato.",
"noRequests": "Nessun amico ha ancora chiesto nulla.",
"when": "Quando",
"friendCol": "Amico",
"route": "Percorso",
"status": "Esito",
"sent": "Inviato"
}
},
"lidarr": {

View file

@ -1,6 +1,6 @@
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useApproveFriend, useRemoveFriend, type FederationFriend } from '@/api/adminFederation'
import { useApproveFriend, useCheckFriend, useRemoveFriend, type FederationFriend } from '@/api/adminFederation'
import { Button } from '@/components/ui/button'
import Confirm from './Confirm'
import { errorText } from './errorText'
@ -12,8 +12,9 @@ export default function FederationFriends({ friends }: { friends: FederationFrie
const { t } = useTranslation()
const approve = useApproveFriend()
const remove = useRemoveFriend()
const check = useCheckFriend()
const [removing, setRemoving] = useState<FederationFriend | null>(null)
const error = approve.error ?? remove.error
const error = approve.error ?? remove.error ?? check.error
return (
<section aria-label={t('admin.federation.friends')} className="flex flex-col gap-3">
@ -38,6 +39,11 @@ export default function FederationFriends({ friends }: { friends: FederationFrie
{t('admin.federation.approve')}
</Button>
)}
{friend.state === 'outgoing' && (
<Button variant="outline" aria-label={t('admin.federation.checkOne', { name: friend.name })} disabled={check.isPending} onClick={() => check.mutate(friend.id)}>
{t('admin.federation.check')}
</Button>
)}
<Button
variant="outline"
aria-label={t(`admin.federation.remove.${friend.state}One`, { name: friend.name })}

View file

@ -0,0 +1,60 @@
import { useState, type FormEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { useUpdateFederation, type Federation } from '@/api/adminFederation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { errorText } from './errorText'
const SCOPES = ['admin.federation.errors', 'admin.errors']
function Form({ federation }: { federation: Federation }) {
const { t } = useTranslation()
const update = useUpdateFederation()
const [streams, setStreams] = useState(String(federation.max_streams))
const [rate, setRate] = useState(String(federation.max_kib_per_sec))
const unchanged = streams === String(federation.max_streams) && rate === String(federation.max_kib_per_sec)
const ready = streams.trim() !== '' && rate.trim() !== '' && !Number.isNaN(Number(streams)) && !Number.isNaN(Number(rate))
function submit(event: FormEvent) {
event.preventDefault()
if (ready) update.mutate({ max_streams: Number(streams), max_kib_per_sec: Number(rate) })
}
return (
<form onSubmit={submit} className="flex max-w-xl flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="federation-streams">{t('admin.federation.streams')}</Label>
<Input id="federation-streams" type="number" inputMode="numeric" value={streams} onChange={(e) => setStreams(e.target.value)} />
<p className="text-sm text-muted-foreground">{t('admin.federation.streamsHint')}</p>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="federation-rate">{t('admin.federation.rate')}</Label>
<Input id="federation-rate" type="number" inputMode="numeric" value={rate} onChange={(e) => setRate(e.target.value)} />
<p className="text-sm text-muted-foreground">{t('admin.federation.rateHint')}</p>
</div>
<div>
<Button type="submit" variant="outline" disabled={unchanged || !ready || update.isPending}>
{t('admin.federation.saveLimits')}
</Button>
</div>
{update.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, update.error, SCOPES)}
</p>
)}
</form>
)
}
/** How much one friend may take: a few streams at a time, and a rate shared by all of them. */
export default function FederationLimits({ federation }: { federation: Federation }) {
const { t } = useTranslation()
return (
<section aria-label={t('admin.federation.limits')} className="flex flex-col gap-3">
<h3 className="text-lg font-bold">{t('admin.federation.limits')}</h3>
{/* Remounts the form when the server's values change, so it always starts from what the server keeps. */}
<Form key={`${federation.max_streams}|${federation.max_kib_per_sec}`} federation={federation} />
</section>
)
}

View file

@ -27,16 +27,19 @@ interface State {
address: string
key_id: string
sends: string
max_streams: number
max_kib_per_sec: number
friends: Friend[]
}
/** A server that keeps the federation settings and the friends, and applies what is put to it. */
function server(initial: Partial<State> = {}, over: MockRoutes = {}) {
const state: State = { enabled: false, name: 'nas', address: '', key_id: '', sends: SENDS, friends: [], ...initial }
const state: State = { enabled: false, name: 'nas', address: '', key_id: '', sends: SENDS, max_streams: 3, max_kib_per_sec: 4096, friends: [], ...initial }
const bodies: Record<string, unknown[]> = {}
const record = (key: string, init: RequestInit) => (bodies[key] ??= []).push(init.body ? JSON.parse(String(init.body)) : null)
const { calls } = mockFetch({
'GET /api/v1/federation': () => state,
'GET /api/v1/federation/requests': () => ({ requests: [] }),
'PUT /api/v1/federation': ({ init }) => {
record('PUT', init)
const body = JSON.parse(String(init.body)) as Partial<State>
@ -258,3 +261,104 @@ test('a failure to read the settings says so, with a way to try again', async ()
expect(await screen.findByRole('alert')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
})
test('the limits for a friend are shown and saved on their own', async () => {
const user = userEvent.setup()
const { bodies } = server({ enabled: true, key_id: 'abcdef0123456789' })
renderPage()
const streams = await screen.findByLabelText('Streams at a time')
const rate = screen.getByLabelText('KiB a second')
expect(streams).toHaveValue(3)
expect(rate).toHaveValue(4096)
expect(screen.getByRole('button', { name: 'Save limits' })).toBeDisabled()
await user.clear(streams)
await user.type(streams, '2')
await user.clear(rate)
await user.type(rate, '0')
await user.click(screen.getByRole('button', { name: 'Save limits' }))
await waitFor(() => expect(bodies.PUT).toEqual([{ max_streams: 2, max_kib_per_sec: 0 }]))
})
test('a limit the server refuses is said in words', async () => {
const user = userEvent.setup()
server({ enabled: true, key_id: 'abcdef0123456789' }, { 'PUT /api/v1/federation': () => apiError(400, 'invalid_input') })
renderPage()
const streams = await screen.findByLabelText('Streams at a time')
await user.clear(streams)
await user.type(streams, '99')
await user.click(screen.getByRole('button', { name: 'Save limits' }))
expect(await screen.findByRole('alert')).toBeInTheDocument()
})
test('the last requests friends made are listed with the route and the size, never what was asked for', async () => {
server(
{ enabled: true, key_id: 'abcdef0123456789' },
{
'GET /api/v1/federation/requests': () => ({
requests: [
{ at: '2026-11-13T12:00:00Z', friend_id: 1, friend: 'Anna', route: '/api/v1/peer/tracks/:id/stream', status: 200, bytes: 5242880 },
{ at: '2026-11-13T11:00:00Z', friend_id: 1, friend: 'Anna', route: '/api/v1/peer/info', status: 403, bytes: 80 },
],
}),
},
)
renderPage()
const table = await screen.findByRole('table', { name: 'Recent requests' })
const rows = within(table).getAllByRole('row')
expect(rows).toHaveLength(3)
expect(within(rows[1]).getByText('/tracks/:id/stream')).toHaveAttribute('title', '/api/v1/peer/tracks/:id/stream')
expect(within(rows[1]).getByText('5.0 MB')).toBeInTheDocument()
expect(within(rows[1]).getByText('Anna')).toBeInTheDocument()
expect(within(rows[2]).getByText('403')).toBeInTheDocument()
})
test('with no request yet it says so', async () => {
server({ enabled: true, key_id: 'abcdef0123456789' })
renderPage()
expect(await screen.findByText('No friend has asked for anything yet.')).toBeInTheDocument()
})
test('a friend that is waiting for the other admin can be checked, and becomes a friend when it answers', async () => {
const user = userEvent.setup()
const s = server(
{ enabled: true, key_id: 'abcdef0123456789', friends: [friend({ id: 4, name: 'Carla', state: 'outgoing', approved_at: null })] },
{
'POST /api/v1/federation/friends/4/check': () => {
s.state.friends = [friend({ id: 4, name: 'Carla' })]
return s.state.friends[0]
},
},
)
renderPage()
await user.click(await screen.findByRole('button', { name: 'Check Carla' }))
expect(await screen.findByText('Friend')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Check Carla' })).not.toBeInTheDocument()
})
test.each([
['not_approved', 409, /has not approved yet/],
['friend_gone', 409, /no longer takes this server for a friend/],
['friend_unreachable', 502, /did not answer/],
])('checking a friend that answers %s is said in words, and the friend stays', async (code, status, text) => {
const user = userEvent.setup()
server(
{ enabled: true, key_id: 'abcdef0123456789', friends: [friend({ id: 4, name: 'Carla', state: 'outgoing', approved_at: null })] },
{ 'POST /api/v1/federation/friends/4/check': () => apiError(status, code) },
)
renderPage()
await user.click(await screen.findByRole('button', { name: 'Check Carla' }))
expect(await screen.findByRole('alert')).toHaveTextContent(text)
expect(screen.getByText('Waiting for their approval')).toBeInTheDocument()
})
test('an active friend has no Check button, and neither does a request waiting for me', async () => {
server({
enabled: true,
key_id: 'abcdef0123456789',
friends: [friend({ id: 1, name: 'Anna' }), friend({ id: 2, name: 'Bruno', state: 'incoming', approved_at: null })],
})
renderPage()
await screen.findByText('Anna')
expect(screen.queryByRole('button', { name: /^Check/ })).not.toBeInTheDocument()
})

View file

@ -8,6 +8,8 @@ import Confirm from './Confirm'
import { errorText } from './errorText'
import FederationFriends from './FederationFriends'
import FederationInvites from './FederationInvites'
import FederationLimits from './FederationLimits'
import FederationRequests from './FederationRequests'
import FederationSettings from './FederationSettings'
const FEDERATION_ERRORS = ['admin.federation.errors', 'admin.errors']
@ -54,6 +56,8 @@ export default function FederationPage() {
<FederationSettings federation={federation.data} />
<FederationInvites />
<FederationFriends friends={federation.data.friends} />
<FederationLimits federation={federation.data} />
<FederationRequests />
</>
)}
</>

View file

@ -0,0 +1,61 @@
import { useTranslation } from 'react-i18next'
import { useFederationRequests } from '@/api/adminFederation'
import { ErrorMessage, Loading } from '@/components/Status'
/** Every route a friend reads starts like this; the list shows the rest. */
const PEER_PREFIX = '/api/v1/peer'
/** Bytes the way a person reads them: 80 B, 12.3 kB, 5.0 MB. */
function size(bytes: number): string {
if (bytes >= 1 << 20) return `${(bytes / (1 << 20)).toFixed(1)} MB`
if (bytes >= 1 << 10) return `${(bytes / (1 << 10)).toFixed(1)} kB`
return `${bytes} B`
}
/** What friends asked of this server lately: the route (never what was searched for), the answer and its size. */
export default function FederationRequests() {
const { t, i18n } = useTranslation()
const requests = useFederationRequests()
const when = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'short', timeStyle: 'medium' })
return (
<section aria-label={t('admin.federation.requests')} className="flex flex-col gap-3">
<h3 className="text-lg font-bold">{t('admin.federation.requests')}</h3>
<p className="text-sm text-muted-foreground">{t('admin.federation.requestsHint')}</p>
{requests.isError ? (
<ErrorMessage error={requests.error} onRetry={() => void requests.refetch()} />
) : requests.isPending ? (
<Loading />
) : requests.data.length === 0 ? (
<p className="text-muted-foreground">{t('admin.federation.noRequests')}</p>
) : (
<div className="overflow-x-auto">
<table aria-label={t('admin.federation.requests')} className="w-full text-left text-sm">
<thead>
<tr className="text-muted-foreground">
<th className="py-2 pr-4 font-semibold">{t('admin.federation.when')}</th>
<th className="py-2 pr-4 font-semibold">{t('admin.federation.friendCol')}</th>
<th className="py-2 pr-4 font-semibold">{t('admin.federation.route')}</th>
<th className="py-2 pr-4 font-semibold">{t('admin.federation.status')}</th>
<th className="py-2 font-semibold">{t('admin.federation.sent')}</th>
</tr>
</thead>
<tbody>
{requests.data.map((r, i) => (
<tr key={`${r.at}-${i}`} className="border-t border-border">
<td className="py-2 pr-4 whitespace-nowrap">{when.format(new Date(r.at))}</td>
<td className="py-2 pr-4">{r.friend}</td>
<td className="py-2 pr-4 font-mono whitespace-nowrap" title={r.route}>
{r.route.replace(PEER_PREFIX, '')}
</td>
<td className="py-2 pr-4">{r.status}</td>
<td className="py-2 whitespace-nowrap">{size(r.bytes)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
)
}

View file

@ -7,7 +7,7 @@ import { initI18n } from '@/i18n'
import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch'
import LibraryList from './LibraryList'
const lib = (id: number, name: string, path: string) => ({ id, name, path, created_at: '2026-11-12T10:00:00Z' })
const lib = (id: number, name: string, path: string, shared = false) => ({ id, name, path, shared, created_at: '2026-11-12T10:00:00Z' })
const none = () => new Response(null, { status: 204 })
const started = () => new Response(JSON.stringify({ status: 'started' }), { status: 202, headers: { 'Content-Type': 'application/json' } })
@ -172,3 +172,66 @@ test.each([
expect(await within(dialog).findByRole('alert')).toHaveTextContent(text)
expect(screen.getByRole('dialog')).toBeInTheDocument()
})
test('each library says whether friends may read it, and starts as not shared', async () => {
mockFetch(routes({ 'GET /api/v1/libraries': () => ({ libraries: [lib(1, 'Music', '/srv/music'), lib(2, 'Jazz', '/srv/jazz', true)] }) }))
renderList()
const music = await row('Music')
expect(within(music).getByRole('switch', { name: 'Share Music with friends' })).toHaveAttribute('aria-checked', 'false')
expect(music).toHaveTextContent('Not shared with friends')
const jazz = await row('Jazz')
expect(within(jazz).getByRole('switch', { name: 'Share Jazz with friends' })).toHaveAttribute('aria-checked', 'true')
expect(jazz).toHaveTextContent('Shared with friends')
})
test('sharing a library asks first, and says friends may play it and in practice copy it', async () => {
const user = userEvent.setup()
const { calls } = mockFetch(routes({ 'PATCH /api/v1/libraries/1': () => lib(1, 'Music', '/srv/music', true) }))
renderList()
await user.click(within(await row('Music')).getByRole('switch', { name: 'Share Music with friends' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/play it, and in practice copy its files/)).toBeInTheDocument()
expect(bodies(calls, 'PATCH /api/v1/libraries/1')).toEqual([])
await user.click(within(dialog).getByRole('button', { name: 'Share' }))
await waitFor(() => expect(bodies(calls, 'PATCH /api/v1/libraries/1')).toEqual([{ shared: true }]))
})
test('cancelling the question shares nothing', async () => {
const user = userEvent.setup()
const { calls } = mockFetch(routes())
renderList()
await user.click(within(await row('Music')).getByRole('switch', { name: 'Share Music with friends' }))
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Cancel' }))
expect(calls.filter((c) => c.key.startsWith('PATCH'))).toEqual([])
})
test('stopping to share asks nothing and is not held up by a scan', async () => {
const user = userEvent.setup()
const { calls } = mockFetch(
routes({
'GET /api/v1/libraries': () => ({ libraries: [lib(2, 'Jazz', '/srv/jazz', true)] }),
'GET /api/v1/library/scan': () => ({ running: true }),
'PATCH /api/v1/libraries/2': () => lib(2, 'Jazz', '/srv/jazz', false),
}),
)
renderList()
const sw = within(await row('Jazz')).getByRole('switch', { name: 'Share Jazz with friends' })
expect(sw).toBeEnabled()
await user.click(sw)
await waitFor(() => expect(bodies(calls, 'PATCH /api/v1/libraries/2')).toEqual([{ shared: false }]))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
test('a refusal to change sharing is said in words', async () => {
const user = userEvent.setup()
mockFetch(
routes({
'GET /api/v1/libraries': () => ({ libraries: [lib(2, 'Jazz', '/srv/jazz', true)] }),
'PATCH /api/v1/libraries/2': () => apiError(404, 'library_not_found'),
}),
)
renderList()
await user.click(within(await row('Jazz')).getByRole('switch', { name: 'Share Jazz with friends' }))
expect(await screen.findByRole('alert')).toBeInTheDocument()
})

View file

@ -7,6 +7,8 @@ import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import Confirm from './Confirm'
import { errorText } from './errorText'
const SCOPES = ['admin.libraries.errors', 'admin.errors']
@ -94,8 +96,10 @@ export default function LibraryList({ full }: { full: boolean }) {
const remove = useRemoveLibrary()
const [editing, setEditing] = useState<Library | null>(null)
const [removing, setRemoving] = useState<Library | null>(null)
const [sharing, setSharing] = useState<Library | null>(null)
const share = useUpdateLibrary()
const busy = status.data?.running === true || scan.isPending || remove.isPending
const failure = scan.error ?? remove.error
const failure = scan.error ?? remove.error ?? share.error
return (
<Section title={t('admin.libraries.title')}>
@ -113,6 +117,15 @@ export default function LibraryList({ full }: { full: boolean }) {
<span className="text-lg font-bold break-words">{library.name}</span>
<span className="font-mono text-sm break-all text-muted-foreground">{library.path}</span>
</div>
<div className="flex items-center gap-3">
<Switch
checked={library.shared}
aria-label={t('admin.libraries.share', { name: library.name })}
disabled={share.isPending}
onClick={() => (library.shared ? share.mutate({ id: library.id, shared: false }) : setSharing(library))}
/>
<span className="text-sm text-muted-foreground">{t(library.shared ? 'admin.libraries.shared' : 'admin.libraries.notShared')}</span>
</div>
<div className="flex flex-wrap gap-2">
<Button
variant="outline"
@ -140,6 +153,18 @@ export default function LibraryList({ full }: { full: boolean }) {
</p>
) : null}
{sharing && (
<Confirm
title={t('admin.libraries.shareTitle', { name: sharing.name })}
body={t('admin.libraries.shareBody')}
confirm={t('admin.libraries.shareConfirm')}
onClose={() => setSharing(null)}
onConfirm={() => {
share.mutate({ id: sharing.id, shared: true })
setSharing(null)
}}
/>
)}
{editing && <EditDialog key={editing.id} library={editing} onClose={() => setEditing(null)} />}
{removing && (
<RemoveDialog