feat(federation): keys, invites and pairing between Sonda servers
Two servers can become friends. Federation is off by default; turning it
on makes an Ed25519 key pair, kept in the database and never returned.
- Admin routes: GET and PUT /federation (on or off, name, public address),
POST /federation/invites, POST /federation/friends (use an invite),
POST /federation/friends/{id}/approve and DELETE /federation/friends/{id}.
- POST /api/v1/peer/pair, the one route without a login: the code of an
invite is the proof. An invite works once and expires in 24 hours; only
a hash of its code is stored. At most 10 attempts a minute.
- The server that uses an invite checks that the key it gets back is the
one named in the invite. A friend is kept as incoming or outgoing until
both admins have agreed.
- https only, except plain http on a network of one's own (private,
loopback or link-local address, or a local name).
- A client of its own for friends, with no redirects, no proxy from the
environment, a size limit and a time limit; the providers' client stays
as it is.
- Migration 0023 for SQLite and PostgreSQL, OpenAPI paths and schemas,
contract test with two real servers.
- Admin > Federation in the web app, in English and Italian, and a
section in the README.
This commit is contained in:
parent
822f6094e5
commit
695a012f6c
11 changed files with 3987 additions and 20 deletions
62
web/src/api/adminFederation.ts
Normal file
62
web/src/api/adminFederation.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api } from './client'
|
||||
import type { components } from './schema'
|
||||
|
||||
export type Federation = components['schemas']['Federation']
|
||||
export type FederationFriend = components['schemas']['FederationFriend']
|
||||
export type FederationInvite = components['schemas']['FederationInvite']
|
||||
|
||||
/** What `PUT /federation` takes: any of these, and what is left out is kept. */
|
||||
export interface FederationChanges {
|
||||
enabled?: boolean
|
||||
name?: string
|
||||
address?: string
|
||||
}
|
||||
|
||||
const FEDERATION = ['federation']
|
||||
|
||||
/** The federation settings of this server, with its friends. The private key is never in the answer. */
|
||||
export function useFederation() {
|
||||
return useQuery({ queryKey: FEDERATION, queryFn: () => api.get<Federation>('/federation') })
|
||||
}
|
||||
|
||||
/** Turns federation on or off, names this server, gives its address. The first time it is on, the server makes its key. */
|
||||
export function useUpdateFederation() {
|
||||
const client = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (changes: FederationChanges) => api.put<Federation>('/federation', changes),
|
||||
onSuccess: () => client.invalidateQueries({ queryKey: FEDERATION }),
|
||||
})
|
||||
}
|
||||
|
||||
/** Makes an invite for another server: one piece of text, good once, for 24 hours. */
|
||||
export function useCreateInvite() {
|
||||
return useMutation({ mutationFn: () => api.post<FederationInvite>('/federation/invites') })
|
||||
}
|
||||
|
||||
/** Uses an invite made by another server: that server is asked, and the friend waits for its approval. */
|
||||
export function useUseInvite() {
|
||||
const client = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (invite: string) => api.post<FederationFriend>('/federation/friends', { invite }),
|
||||
onSuccess: () => client.invalidateQueries({ queryKey: FEDERATION }),
|
||||
})
|
||||
}
|
||||
|
||||
/** The second confirmation: a server that used an invite of this one becomes a friend. */
|
||||
export function useApproveFriend() {
|
||||
const client = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => api.post<FederationFriend>(`/federation/friends/${id}/approve`),
|
||||
onSuccess: () => client.invalidateQueries({ queryKey: FEDERATION }),
|
||||
})
|
||||
}
|
||||
|
||||
/** Declines a request, withdraws one, or ends a friendship. The other server is not told. */
|
||||
export function useRemoveFriend() {
|
||||
const client = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => api.del<void>(`/federation/friends/${id}`),
|
||||
onSuccess: () => client.invalidateQueries({ queryKey: FEDERATION }),
|
||||
})
|
||||
}
|
||||
490
web/src/api/schema.d.ts
vendored
490
web/src/api/schema.d.ts
vendored
|
|
@ -2018,6 +2018,151 @@ export interface paths {
|
|||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/federation": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* Federation, its key and its friends
|
||||
* @description Admin only. Federation is off until an admin turns it on. `sends` says in plain words what a friend's server is
|
||||
* sent. `key_id` names the key of this server (the first 16 hex characters of the SHA-256 of its public key); it is
|
||||
* empty until federation was first turned on. The private key is never returned. `name` is the one saved, or the
|
||||
* host name.
|
||||
*/
|
||||
get: operations["getFederation"];
|
||||
/**
|
||||
* Turn federation on or off, name this server, give its address
|
||||
* @description Admin only. Fields you leave out are kept. The key pair is made the first time `enabled` becomes true and is kept
|
||||
* after that, so turning it off and on again does not change the key. `address` is where friends reach this server:
|
||||
* `https://`, or `http://` only on a network of your own (a private, loopback or link-local address, or a name that
|
||||
* is local: no dot, or ending `.local`, `.lan`, `.home.arpa`); without user, query or fragment. A closing slash is
|
||||
* dropped; an empty address clears it. An empty `name` goes back to the host name (at most 60 characters).
|
||||
*/
|
||||
put: operations["updateFederation"];
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/federation/invites": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Make an invite for another server
|
||||
* @description Admin only. The invite is one piece of text to give to the other admin, who pastes it into
|
||||
* `POST /federation/friends`. It works once and expires in 24 hours; only a hash of its code is kept here. It needs
|
||||
* federation on (`federation_off`) and an address (`address_required`).
|
||||
*/
|
||||
post: operations["createFederationInvite"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/federation/friends": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Use an invite made by another server
|
||||
* @description Admin only. Asks the server the invite came from to accept this one, checks that the key it answers with is the one
|
||||
* the invite names, and keeps it as a friend in state `outgoing`: it waits for the other admin to approve. This is
|
||||
* the only request federation sends at an admin's command, and it sends this server's name, address and public key
|
||||
* and the code of the invite. It needs federation on and an address, like making an invite.
|
||||
*/
|
||||
post: operations["useFederationInvite"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/federation/friends/{id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
post?: never;
|
||||
/**
|
||||
* Decline, withdraw or end a friendship
|
||||
* @description Admin only. Removes the friend of any state. The other server is not told: its requests are no longer answered.
|
||||
* The same server can be invited again afterwards.
|
||||
*/
|
||||
delete: operations["removeFederationFriend"];
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/federation/friends/{id}/approve": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Approve a server that used an invite of this one
|
||||
* @description Admin only. The second confirmation: a friend in state `incoming` becomes `active`. A friend in any other state
|
||||
* is a `409` (`not_waiting`).
|
||||
*/
|
||||
post: operations["approveFederationFriend"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/peer/pair": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Pair with this server (called by another Sonda server)
|
||||
* @description Not for people: another Sonda server calls this when its admin pastes an invite made here. There is no login: the
|
||||
* code of the invite is the proof, and it works once. The other server is kept as a friend in state `incoming`
|
||||
* until an admin here approves it. While federation is off, or has no address, the route answers `404 not_found`,
|
||||
* as a missing route does. At most 10 attempts a minute, from anyone.
|
||||
*/
|
||||
post: operations["peerPair"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
}
|
||||
export type webhooks = Record<string, never>;
|
||||
export interface components {
|
||||
|
|
@ -3051,6 +3196,64 @@ export interface components {
|
|||
limit: number;
|
||||
offset: number;
|
||||
};
|
||||
Federation: {
|
||||
/** @description Whether this server may pair with others. Off by default. */
|
||||
enabled: boolean;
|
||||
/** @description How friends see this server. */
|
||||
name: string;
|
||||
/** @description Where friends reach this server; empty until set. */
|
||||
address: string;
|
||||
/** @description Names this server's key; empty until federation was first turned on. Compare it with the one the other admin sees. */
|
||||
key_id: string;
|
||||
/** @description What a friend's server is sent, and what it never learns. */
|
||||
sends: string;
|
||||
friends: components["schemas"]["FederationFriend"][];
|
||||
};
|
||||
FederationUpdate: {
|
||||
enabled?: boolean;
|
||||
/** @description At most 60 characters, no control characters. Empty goes back to the host name. */
|
||||
name?: string;
|
||||
address?: string;
|
||||
} | unknown | unknown | unknown;
|
||||
FederationInvite: {
|
||||
/** @description One piece of text to give to the other admin. Starts with `sonda1.`. */
|
||||
invite: string;
|
||||
/** Format: date-time */
|
||||
expires_at: string;
|
||||
};
|
||||
FederationUseInvite: {
|
||||
invite: string;
|
||||
};
|
||||
FederationFriend: {
|
||||
id: number;
|
||||
name: string;
|
||||
address: string;
|
||||
/** @description Names the friend's key. */
|
||||
key_id: string;
|
||||
/**
|
||||
* @description `incoming`: it used an invite of this server and waits for approval here. `outgoing`: this server used its invite
|
||||
* and waits for it. `active`: both agreed.
|
||||
* @enum {string}
|
||||
*/
|
||||
state: "incoming" | "outgoing" | "active";
|
||||
/** Format: date-time */
|
||||
created_at: string;
|
||||
/** Format: date-time */
|
||||
approved_at: string | null;
|
||||
};
|
||||
PeerPairRequest: {
|
||||
code: string;
|
||||
name: string;
|
||||
address: string;
|
||||
/** @description The Ed25519 public key, 32 bytes, base64url without padding. */
|
||||
public_key: string;
|
||||
};
|
||||
PeerPairReply: {
|
||||
name: string;
|
||||
address: string;
|
||||
/** @description The Ed25519 public key, 32 bytes, base64url without padding. */
|
||||
public_key: string;
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description The request is malformed or a value is out of range (`invalid_input`). */
|
||||
|
|
@ -6550,4 +6753,291 @@ export interface operations {
|
|||
};
|
||||
};
|
||||
};
|
||||
getFederation: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The settings and the friends, oldest first. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Federation"];
|
||||
};
|
||||
};
|
||||
401: components["responses"]["Unauthorized"];
|
||||
403: components["responses"]["AdminRequired"];
|
||||
};
|
||||
};
|
||||
updateFederation: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["FederationUpdate"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description The settings as they are now. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Federation"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
403: components["responses"]["AdminRequired"];
|
||||
};
|
||||
};
|
||||
createFederationInvite: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The invite. */
|
||||
201: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["FederationInvite"];
|
||||
};
|
||||
};
|
||||
401: components["responses"]["Unauthorized"];
|
||||
403: components["responses"]["AdminRequired"];
|
||||
/** @description Federation is off (`federation_off`) or this server has no address yet (`address_required`). */
|
||||
409: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
useFederationInvite: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["FederationUseInvite"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description The new friend, waiting for approval. */
|
||||
201: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["FederationFriend"];
|
||||
};
|
||||
};
|
||||
/** @description Malformed body (`invalid_input`) or not an invite of a Sonda server (`invalid_invite`). */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
401: components["responses"]["Unauthorized"];
|
||||
403: components["responses"]["AdminRequired"];
|
||||
/** @description Federation is off (`federation_off`), no address (`address_required`) or the server is already a friend (`already_friends`). */
|
||||
409: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description The other server turned the invite down: used, expired, or federation off there (`invite_refused`). */
|
||||
422: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description The other server asked to slow down (`too_many_requests`). */
|
||||
429: {
|
||||
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`), or its key is not the one in the invite (`key_mismatch`). */
|
||||
502: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
removeFederationFriend: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description Removed. */
|
||||
204: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content?: never;
|
||||
};
|
||||
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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
approveFederationFriend: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The friend, now active. */
|
||||
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 The friend is not waiting for approval (`not_waiting`). */
|
||||
409: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
peerPair: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["PeerPairRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description This server's name, address and public key. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["PeerPairReply"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
/** @description The code is unknown, used or expired (`invalid_invite`). */
|
||||
403: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description Federation is off here (`not_found`). */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description This key is already a friend (`already_friends`). */
|
||||
409: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description Too many attempts (`too_many_requests`). */
|
||||
429: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -77,6 +77,7 @@
|
|||
"sectionLibraries": "Libraries",
|
||||
"sectionUsers": "Users",
|
||||
"sectionProviders": "Providers",
|
||||
"sectionFederation": "Federation",
|
||||
"sectionCosts": "Costs",
|
||||
"sectionJobs": "Jobs",
|
||||
"costs": {
|
||||
|
|
@ -366,6 +367,63 @@
|
|||
"failed": "{{count}} could not be read",
|
||||
"skipped": "{{count}} skipped (links and special files)"
|
||||
}
|
||||
},
|
||||
"federation": {
|
||||
"intro": "Federation lets the listeners of another Sonda server play the libraries you choose to share, and yours play theirs. It is off until you turn it on, and each friend needs an invite and two approvals.",
|
||||
"on": "On",
|
||||
"off": "Off",
|
||||
"turnOnTitle": "Turn on federation?",
|
||||
"turnOn": "Turn on",
|
||||
"name": "Name",
|
||||
"nameHint": "How friends see this server. Empty uses the host name.",
|
||||
"address": "Public address",
|
||||
"addressHint": "Where friends reach this server, like https://music.example.org. Plain http is only for a network of your own.",
|
||||
"saveSettings": "Save settings",
|
||||
"keyOfThis": "Key of this server: {{id}}.",
|
||||
"keyHint": "The other admin sees the same key for your server: compare them to be sure.",
|
||||
"invites": "Invites",
|
||||
"makeInvite": "Make an invite",
|
||||
"invite": "Invite",
|
||||
"copy": "Copy",
|
||||
"copied": "Copied",
|
||||
"copyInvite": "Copy invite",
|
||||
"inviteExpires": "Give it to the other admin. Works once, until {{when}}.",
|
||||
"use": "Paste an invite from another server",
|
||||
"addFriend": "Add friend",
|
||||
"useHint": "The other server is asked to accept this one, and its admin then has to approve.",
|
||||
"friends": "Friends",
|
||||
"none": "No friends yet.",
|
||||
"state": {
|
||||
"incoming": "Wants to be your friend",
|
||||
"outgoing": "Waiting for their approval",
|
||||
"active": "Friend"
|
||||
},
|
||||
"keyOf": "Key {{id}}",
|
||||
"approve": "Approve",
|
||||
"approveOne": "Approve {{name}}",
|
||||
"remove": {
|
||||
"incoming": "Decline",
|
||||
"incomingOne": "Decline {{name}}",
|
||||
"outgoing": "Withdraw",
|
||||
"outgoingOne": "Withdraw {{name}}",
|
||||
"active": "Remove",
|
||||
"activeOne": "Remove {{name}}"
|
||||
},
|
||||
"removeTitle": "Remove {{name}}?",
|
||||
"removeBody": "{{name}} will no longer be asked or answered. The other server is not told. You can invite it again.",
|
||||
"errors": {
|
||||
"federation_off": "Turn federation on first.",
|
||||
"address_required": "Set the public address of this server first.",
|
||||
"invalid_input": "Check the name and the address: the address starts with https:// (http:// only on your own network), with no user, query or fragment.",
|
||||
"invalid_invite": "That is not an invite from a Sonda server.",
|
||||
"invite_refused": "That server turned the invite down: it may be used, expired, or federation may be off there.",
|
||||
"key_mismatch": "That server's key is not the one in the invite. Nothing was added.",
|
||||
"friend_unreachable": "That server did not answer as a Sonda server.",
|
||||
"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."
|
||||
}
|
||||
}
|
||||
},
|
||||
"lidarr": {
|
||||
|
|
@ -617,14 +675,38 @@
|
|||
"makeMine": "Make it mine",
|
||||
"notFoundSuggested": "This suggested smart playlist does not exist.",
|
||||
"suggested": {
|
||||
"on-rotation": { "name": "In rotation", "description": "The songs you have played most in the last 30 days." },
|
||||
"top-year": { "name": "Top of the year", "description": "The songs you have played most over the last year." },
|
||||
"recently-added": { "name": "Recently added", "description": "Songs added in the last 30 days, the newest first." },
|
||||
"never-played": { "name": "Never played", "description": "Songs you have never listened to." },
|
||||
"most-played": { "name": "Most played", "description": "The songs you have played most." },
|
||||
"forgotten": { "name": "Not heard in a while", "description": "Songs you played once, but not in the last 90 days." },
|
||||
"high-quality": { "name": "High quality", "description": "Files of 900 kbps or more." },
|
||||
"long-tracks": { "name": "Long tracks", "description": "Songs of 6 minutes or more." }
|
||||
"on-rotation": {
|
||||
"name": "In rotation",
|
||||
"description": "The songs you have played most in the last 30 days."
|
||||
},
|
||||
"top-year": {
|
||||
"name": "Top of the year",
|
||||
"description": "The songs you have played most over the last year."
|
||||
},
|
||||
"recently-added": {
|
||||
"name": "Recently added",
|
||||
"description": "Songs added in the last 30 days, the newest first."
|
||||
},
|
||||
"never-played": {
|
||||
"name": "Never played",
|
||||
"description": "Songs you have never listened to."
|
||||
},
|
||||
"most-played": {
|
||||
"name": "Most played",
|
||||
"description": "The songs you have played most."
|
||||
},
|
||||
"forgotten": {
|
||||
"name": "Not heard in a while",
|
||||
"description": "Songs you played once, but not in the last 90 days."
|
||||
},
|
||||
"high-quality": {
|
||||
"name": "High quality",
|
||||
"description": "Files of 900 kbps or more."
|
||||
},
|
||||
"long-tracks": {
|
||||
"name": "Long tracks",
|
||||
"description": "Songs of 6 minutes or more."
|
||||
}
|
||||
},
|
||||
"empty": "You have no smart playlists yet. A smart playlist is a set of rules, like “rock I have never played”, and its songs change by themselves.",
|
||||
"new": "New smart playlist",
|
||||
|
|
|
|||
|
|
@ -77,6 +77,7 @@
|
|||
"sectionLibraries": "Librerie",
|
||||
"sectionUsers": "Utenti",
|
||||
"sectionProviders": "Provider",
|
||||
"sectionFederation": "Federazione",
|
||||
"sectionCosts": "Costi",
|
||||
"sectionJobs": "Lavori",
|
||||
"costs": {
|
||||
|
|
@ -366,6 +367,63 @@
|
|||
"failed": "{{count}} illeggibili",
|
||||
"skipped": "{{count}} saltati (collegamenti e file speciali)"
|
||||
}
|
||||
},
|
||||
"federation": {
|
||||
"intro": "La federazione permette agli ascoltatori di un altro server Sonda di riprodurre le librerie che scegli di condividere, e ai tuoi di riprodurre le loro. È spenta finché non la accendi, e ogni amico richiede un invito e due approvazioni.",
|
||||
"on": "Accesa",
|
||||
"off": "Spenta",
|
||||
"turnOnTitle": "Accendere la federazione?",
|
||||
"turnOn": "Accendi",
|
||||
"name": "Nome",
|
||||
"nameHint": "Come gli amici vedono questo server. Vuoto usa il nome della macchina.",
|
||||
"address": "Indirizzo pubblico",
|
||||
"addressHint": "Dove gli amici raggiungono questo server, come https://musica.example.org. Il semplice http va bene solo su una rete tua.",
|
||||
"saveSettings": "Salva le impostazioni",
|
||||
"keyOfThis": "Chiave di questo server: {{id}}.",
|
||||
"keyHint": "L'altro admin vede la stessa chiave per il tuo server: confrontatele per essere sicuri.",
|
||||
"invites": "Inviti",
|
||||
"makeInvite": "Crea un invito",
|
||||
"invite": "Invito",
|
||||
"copy": "Copia",
|
||||
"copied": "Copiato",
|
||||
"copyInvite": "Copia l'invito",
|
||||
"inviteExpires": "Daglielo all'altro admin. Vale una volta sola, fino a {{when}}.",
|
||||
"use": "Incolla un invito di un altro server",
|
||||
"addFriend": "Aggiungi amico",
|
||||
"useHint": "All'altro server viene chiesto di accettare questo, e il suo admin deve poi approvare.",
|
||||
"friends": "Amici",
|
||||
"none": "Ancora nessun amico.",
|
||||
"state": {
|
||||
"incoming": "Vuole essere tuo amico",
|
||||
"outgoing": "In attesa della sua approvazione",
|
||||
"active": "Amico"
|
||||
},
|
||||
"keyOf": "Chiave {{id}}",
|
||||
"approve": "Approva",
|
||||
"approveOne": "Approva {{name}}",
|
||||
"remove": {
|
||||
"incoming": "Rifiuta",
|
||||
"incomingOne": "Rifiuta {{name}}",
|
||||
"outgoing": "Ritira",
|
||||
"outgoingOne": "Ritira la richiesta a {{name}}",
|
||||
"active": "Rimuovi",
|
||||
"activeOne": "Rimuovi {{name}}"
|
||||
},
|
||||
"removeTitle": "Rimuovere {{name}}?",
|
||||
"removeBody": "{{name}} non verrà più interrogato né ascolterà le richieste. L'altro server non viene avvisato. Puoi invitarlo di nuovo.",
|
||||
"errors": {
|
||||
"federation_off": "Accendi prima la federazione.",
|
||||
"address_required": "Imposta prima l'indirizzo pubblico di questo server.",
|
||||
"invalid_input": "Controlla il nome e l'indirizzo: l'indirizzo comincia con https:// (http:// solo sulla tua rete), senza utente, query o frammento.",
|
||||
"invalid_invite": "Questo non è un invito di un server Sonda.",
|
||||
"invite_refused": "Quel server ha rifiutato l'invito: può essere già usato, scaduto, o la federazione può essere spenta lì.",
|
||||
"key_mismatch": "La chiave di quel server non è quella dell'invito. Non è stato aggiunto nulla.",
|
||||
"friend_unreachable": "Quel server non ha risposto come un server Sonda.",
|
||||
"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."
|
||||
}
|
||||
}
|
||||
},
|
||||
"lidarr": {
|
||||
|
|
@ -617,14 +675,38 @@
|
|||
"makeMine": "Fanne una tua",
|
||||
"notFoundSuggested": "Questa playlist smart suggerita non esiste.",
|
||||
"suggested": {
|
||||
"on-rotation": { "name": "In rotazione", "description": "I brani che hai ascoltato di più negli ultimi 30 giorni." },
|
||||
"top-year": { "name": "Top dell'anno", "description": "I brani che hai ascoltato di più nell'ultimo anno." },
|
||||
"recently-added": { "name": "Aggiunti da poco", "description": "Brani aggiunti negli ultimi 30 giorni, i più nuovi per primi." },
|
||||
"never-played": { "name": "Mai ascoltati", "description": "Brani che non hai mai ascoltato." },
|
||||
"most-played": { "name": "I più ascoltati", "description": "I brani che hai ascoltato di più." },
|
||||
"forgotten": { "name": "Non li senti da un po'", "description": "Brani ascoltati almeno una volta, ma non negli ultimi 90 giorni." },
|
||||
"high-quality": { "name": "Alta qualità", "description": "File da 900 kbps o più." },
|
||||
"long-tracks": { "name": "Brani lunghi", "description": "Brani da 6 minuti o più." }
|
||||
"on-rotation": {
|
||||
"name": "In rotazione",
|
||||
"description": "I brani che hai ascoltato di più negli ultimi 30 giorni."
|
||||
},
|
||||
"top-year": {
|
||||
"name": "Top dell'anno",
|
||||
"description": "I brani che hai ascoltato di più nell'ultimo anno."
|
||||
},
|
||||
"recently-added": {
|
||||
"name": "Aggiunti da poco",
|
||||
"description": "Brani aggiunti negli ultimi 30 giorni, i più nuovi per primi."
|
||||
},
|
||||
"never-played": {
|
||||
"name": "Mai ascoltati",
|
||||
"description": "Brani che non hai mai ascoltato."
|
||||
},
|
||||
"most-played": {
|
||||
"name": "I più ascoltati",
|
||||
"description": "I brani che hai ascoltato di più."
|
||||
},
|
||||
"forgotten": {
|
||||
"name": "Non li senti da un po'",
|
||||
"description": "Brani ascoltati almeno una volta, ma non negli ultimi 90 giorni."
|
||||
},
|
||||
"high-quality": {
|
||||
"name": "Alta qualità",
|
||||
"description": "File da 900 kbps o più."
|
||||
},
|
||||
"long-tracks": {
|
||||
"name": "Brani lunghi",
|
||||
"description": "Brani da 6 minuti o più."
|
||||
}
|
||||
},
|
||||
"empty": "Non hai ancora playlist smart. Una playlist smart è un insieme di regole, come «rock che non ho mai ascoltato», e i suoi brani cambiano da soli.",
|
||||
"new": "Nuova playlist smart",
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ const SECTIONS = [
|
|||
{ to: '/admin/libraries', key: 'admin.sectionLibraries' },
|
||||
{ to: '/admin/users', key: 'admin.sectionUsers' },
|
||||
{ to: '/admin/providers', key: 'admin.sectionProviders' },
|
||||
{ to: '/admin/federation', key: 'admin.sectionFederation' },
|
||||
{ to: '/admin/jobs', key: 'admin.sectionJobs' },
|
||||
{ to: '/admin/costs', key: 'admin.sectionCosts' },
|
||||
]
|
||||
|
|
|
|||
73
web/src/pages/admin/FederationFriends.tsx
Normal file
73
web/src/pages/admin/FederationFriends.tsx
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useApproveFriend, useRemoveFriend, type FederationFriend } from '@/api/adminFederation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import Confirm from './Confirm'
|
||||
import { errorText } from './errorText'
|
||||
|
||||
const SCOPES = ['admin.federation.errors', 'admin.errors']
|
||||
|
||||
/** The other servers: each with where it is, its key, and what can be done with it in its state. */
|
||||
export default function FederationFriends({ friends }: { friends: FederationFriend[] }) {
|
||||
const { t } = useTranslation()
|
||||
const approve = useApproveFriend()
|
||||
const remove = useRemoveFriend()
|
||||
const [removing, setRemoving] = useState<FederationFriend | null>(null)
|
||||
const error = approve.error ?? remove.error
|
||||
|
||||
return (
|
||||
<section aria-label={t('admin.federation.friends')} className="flex flex-col gap-3">
|
||||
<h3 className="text-lg font-bold">{t('admin.federation.friends')}</h3>
|
||||
{friends.length === 0 ? (
|
||||
<p className="text-muted-foreground">{t('admin.federation.none')}</p>
|
||||
) : (
|
||||
<ul className="flex flex-col gap-3">
|
||||
{friends.map((friend) => (
|
||||
<li key={friend.id} className="flex flex-wrap items-center justify-between gap-3 rounded-xl bg-secondary p-4 text-secondary-foreground">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<span className="font-bold">{friend.name}</span>
|
||||
<span className="break-all text-sm">{friend.address}</span>
|
||||
<span className="flex flex-wrap gap-x-3 text-sm text-muted-foreground">
|
||||
<span>{t(`admin.federation.state.${friend.state}`)}</span>
|
||||
<span>{t('admin.federation.keyOf', { id: friend.key_id })}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{friend.state === 'incoming' && (
|
||||
<Button aria-label={t('admin.federation.approveOne', { name: friend.name })} disabled={approve.isPending} onClick={() => approve.mutate(friend.id)}>
|
||||
{t('admin.federation.approve')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
aria-label={t(`admin.federation.remove.${friend.state}One`, { name: friend.name })}
|
||||
onClick={() => setRemoving(friend)}
|
||||
>
|
||||
{t(`admin.federation.remove.${friend.state}`)}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorText(t, error, SCOPES)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{removing && (
|
||||
<Confirm
|
||||
title={t('admin.federation.removeTitle', { name: removing.name })}
|
||||
body={t('admin.federation.removeBody', { name: removing.name })}
|
||||
confirm={t(`admin.federation.remove.${removing.state}`)}
|
||||
onClose={() => setRemoving(null)}
|
||||
onConfirm={() => {
|
||||
remove.mutate(removing.id)
|
||||
setRemoving(null)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
107
web/src/pages/admin/FederationInvites.tsx
Normal file
107
web/src/pages/admin/FederationInvites.tsx
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import { useState, type FormEvent } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useCreateInvite, useUseInvite } 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']
|
||||
|
||||
/** Makes an invite for another server. It is shown here and nowhere else: the server keeps only a hash of its code. */
|
||||
function MakeInvite() {
|
||||
const { t, i18n } = useTranslation()
|
||||
const create = useCreateInvite()
|
||||
const [copied, setCopied] = useState(false)
|
||||
const invite = create.data
|
||||
|
||||
async function copy() {
|
||||
if (!invite) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(invite.invite)
|
||||
setCopied(true)
|
||||
} catch {
|
||||
// No clipboard (a plain http page): the text is selected for the admin to copy by hand.
|
||||
}
|
||||
}
|
||||
|
||||
const until = invite ? new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(invite.expires_at)) : ''
|
||||
|
||||
return (
|
||||
<div className="flex max-w-xl flex-col gap-3">
|
||||
<div>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={create.isPending}
|
||||
onClick={() => {
|
||||
setCopied(false)
|
||||
create.mutate()
|
||||
}}
|
||||
>
|
||||
{t('admin.federation.makeInvite')}
|
||||
</Button>
|
||||
</div>
|
||||
{create.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorText(t, create.error, SCOPES)}
|
||||
</p>
|
||||
)}
|
||||
{invite && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="federation-invite">{t('admin.federation.invite')}</Label>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Input id="federation-invite" className="min-w-60 flex-1" readOnly value={invite.invite} onFocus={(e) => e.currentTarget.select()} />
|
||||
<Button variant="outline" aria-label={t('admin.federation.copyInvite')} onClick={() => void copy()}>
|
||||
{t(copied ? 'admin.federation.copied' : 'admin.federation.copy')}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{t('admin.federation.inviteExpires', { when: until })}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Uses an invite made by another server: the field is emptied as soon as it worked. */
|
||||
function UseInvite() {
|
||||
const { t } = useTranslation()
|
||||
const use = useUseInvite()
|
||||
const [text, setText] = useState('')
|
||||
|
||||
function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
const typed = text.trim()
|
||||
if (typed === '') return
|
||||
use.mutate(typed, { onSuccess: () => setText('') })
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="flex max-w-xl flex-col gap-2">
|
||||
<Label htmlFor="federation-use">{t('admin.federation.use')}</Label>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Input id="federation-use" className="min-w-60 flex-1" value={text} autoCapitalize="off" spellCheck={false} onChange={(e) => setText(e.target.value)} />
|
||||
<Button type="submit" variant="outline" disabled={text.trim() === '' || use.isPending}>
|
||||
{t('admin.federation.addFriend')}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{t('admin.federation.useHint')}</p>
|
||||
{use.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorText(t, use.error, SCOPES)}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
/** Both ways to start a friendship: make an invite for someone, or use the one someone gave. */
|
||||
export default function FederationInvites() {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<section aria-label={t('admin.federation.invites')} className="flex flex-col gap-4">
|
||||
<h3 className="text-lg font-bold">{t('admin.federation.invites')}</h3>
|
||||
<MakeInvite />
|
||||
<UseInvite />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
260
web/src/pages/admin/FederationPage.test.tsx
Normal file
260
web/src/pages/admin/FederationPage.test.tsx
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
|
||||
import FederationPage from './FederationPage'
|
||||
|
||||
const SENDS = 'Nothing is sent until an admin makes an invite or uses one. It never learns who listens.'
|
||||
|
||||
type Friend = { id: number; name: string; address: string; key_id: string; state: string; created_at: string; approved_at: string | null }
|
||||
const friend = (over: Partial<Friend> = {}): Friend => ({
|
||||
id: 1,
|
||||
name: 'Anna',
|
||||
address: 'https://anna.example.org',
|
||||
key_id: '0123456789abcdef',
|
||||
state: 'active',
|
||||
created_at: '2026-11-13T10:00:00Z',
|
||||
approved_at: '2026-11-13T11:00:00Z',
|
||||
...over,
|
||||
})
|
||||
|
||||
interface State {
|
||||
enabled: boolean
|
||||
name: string
|
||||
address: string
|
||||
key_id: string
|
||||
sends: string
|
||||
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 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,
|
||||
'PUT /api/v1/federation': ({ init }) => {
|
||||
record('PUT', init)
|
||||
const body = JSON.parse(String(init.body)) as Partial<State>
|
||||
Object.assign(state, body)
|
||||
if (state.enabled && state.key_id === '') state.key_id = 'abcdef0123456789'
|
||||
return state
|
||||
},
|
||||
...over,
|
||||
})
|
||||
return { state, bodies, calls }
|
||||
}
|
||||
|
||||
function renderPage() {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<FederationPage />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } })
|
||||
})
|
||||
|
||||
test('it starts off, says what a friend is sent, and offers no invite while it is off', async () => {
|
||||
server()
|
||||
renderPage()
|
||||
expect(await screen.findByText(/It never learns who listens/)).toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'Federation' })).toHaveAttribute('aria-checked', 'false')
|
||||
expect(screen.queryByRole('button', { name: 'Make an invite' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(/Key of this server/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('turning it on asks first with what is sent, and nothing is sent before the answer', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { bodies } = server()
|
||||
renderPage()
|
||||
await user.click(await screen.findByRole('switch', { name: 'Federation' }))
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
expect(within(dialog).getByText(/It never learns who listens/)).toBeInTheDocument()
|
||||
expect(bodies.PUT).toBeUndefined()
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Turn on' }))
|
||||
await waitFor(() => expect(bodies.PUT).toEqual([{ enabled: true }]))
|
||||
expect(await screen.findByText(/Key of this server: abcdef0123456789/)).toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'Federation' })).toHaveAttribute('aria-checked', 'true')
|
||||
})
|
||||
|
||||
test('cancelling the question leaves it off', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { bodies } = server()
|
||||
renderPage()
|
||||
await user.click(await screen.findByRole('switch', { name: 'Federation' }))
|
||||
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Cancel' }))
|
||||
expect(bodies.PUT).toBeUndefined()
|
||||
expect(screen.getByRole('switch', { name: 'Federation' })).toHaveAttribute('aria-checked', 'false')
|
||||
})
|
||||
|
||||
test('turning it off asks nothing', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { bodies } = server({ enabled: true, key_id: 'abcdef0123456789' })
|
||||
renderPage()
|
||||
await user.click(await screen.findByRole('switch', { name: 'Federation' }))
|
||||
await waitFor(() => expect(bodies.PUT).toEqual([{ enabled: false }]))
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the name and the address are saved together and shown as the server keeps them', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { bodies } = server({ enabled: true, key_id: 'abcdef0123456789' })
|
||||
renderPage()
|
||||
const address = await screen.findByLabelText('Public address')
|
||||
expect(screen.getByLabelText('Name')).toHaveValue('nas')
|
||||
expect(screen.getByRole('button', { name: 'Save settings' })).toBeDisabled()
|
||||
|
||||
await user.type(address, 'https://music.example.org')
|
||||
await user.clear(screen.getByLabelText('Name'))
|
||||
await user.type(screen.getByLabelText('Name'), 'Home')
|
||||
await user.click(screen.getByRole('button', { name: 'Save settings' }))
|
||||
await waitFor(() => expect(bodies.PUT).toEqual([{ name: 'Home', address: 'https://music.example.org' }]))
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Save settings' })).toBeDisabled())
|
||||
})
|
||||
|
||||
test('an address 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()
|
||||
await user.type(await screen.findByLabelText('Public address'), 'ftp://x')
|
||||
await user.click(screen.getByRole('button', { name: 'Save settings' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/address starts with https:\/\//)
|
||||
})
|
||||
|
||||
test('an invite is made on request, shown once with when it stops working, and can be copied', async () => {
|
||||
const user = userEvent.setup()
|
||||
server(
|
||||
{ enabled: true, key_id: 'abcdef0123456789', address: 'https://anna.example.org' },
|
||||
{ 'POST /api/v1/federation/invites': () => ({ invite: 'sonda1.abc', expires_at: '2026-11-14T10:00:00Z' }) },
|
||||
)
|
||||
renderPage()
|
||||
await user.click(await screen.findByRole('button', { name: 'Make an invite' }))
|
||||
const field = await screen.findByLabelText('Invite')
|
||||
expect(field).toHaveValue('sonda1.abc')
|
||||
expect(field).toHaveAttribute('readonly')
|
||||
expect(screen.getByText(/Works once/)).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Copy invite' }))
|
||||
expect(await navigator.clipboard.readText()).toBe('sonda1.abc')
|
||||
})
|
||||
|
||||
test('an invite cannot be made before the address is set, and the page says why', async () => {
|
||||
const user = userEvent.setup()
|
||||
server({ enabled: true, key_id: 'abcdef0123456789' }, { 'POST /api/v1/federation/invites': () => apiError(409, 'address_required') })
|
||||
renderPage()
|
||||
await user.click(await screen.findByRole('button', { name: 'Make an invite' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Set the public address of this server first.')
|
||||
})
|
||||
|
||||
test('an invite from another server is pasted, sent, and the field is emptied; the friend then waits for approval', async () => {
|
||||
const user = userEvent.setup()
|
||||
const s = server({ enabled: true, key_id: 'abcdef0123456789', address: 'https://bruno.example.org' }, {
|
||||
'POST /api/v1/federation/friends': ({ init }) => {
|
||||
expect(JSON.parse(String(init.body))).toEqual({ invite: 'sonda1.xyz' })
|
||||
s.state.friends = [friend({ state: 'outgoing', approved_at: null })]
|
||||
return s.state.friends[0]
|
||||
},
|
||||
})
|
||||
renderPage()
|
||||
await user.type(await screen.findByLabelText('Paste an invite from another server'), ' sonda1.xyz ')
|
||||
await user.click(screen.getByRole('button', { name: 'Add friend' }))
|
||||
expect(await screen.findByText('Waiting for their approval')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Paste an invite from another server')).toHaveValue('')
|
||||
expect(screen.queryByRole('button', { name: /^Approve/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['invite_refused', 422, /turned the invite down/],
|
||||
['invalid_invite', 400, /not an invite from a Sonda server/],
|
||||
['friend_unreachable', 502, /did not answer/],
|
||||
['key_mismatch', 502, /not the one in the invite/],
|
||||
['already_friends', 409, /already a friend/],
|
||||
])('using an invite that fails with %s is said in words', async (code, status, text) => {
|
||||
const user = userEvent.setup()
|
||||
server({ enabled: true, key_id: 'abcdef0123456789', address: 'https://b.example.org' }, { 'POST /api/v1/federation/friends': () => apiError(status, code) })
|
||||
renderPage()
|
||||
await user.type(await screen.findByLabelText('Paste an invite from another server'), 'sonda1.xyz')
|
||||
await user.click(screen.getByRole('button', { name: 'Add friend' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(text)
|
||||
})
|
||||
|
||||
test('the button to add a friend waits for something to paste', async () => {
|
||||
server({ enabled: true, key_id: 'abcdef0123456789' })
|
||||
renderPage()
|
||||
expect(await screen.findByRole('button', { name: 'Add friend' })).toBeDisabled()
|
||||
})
|
||||
|
||||
test('a request from another server is approved with one click, and then it is a friend', async () => {
|
||||
const user = userEvent.setup()
|
||||
const s = server(
|
||||
{ enabled: true, key_id: 'abcdef0123456789', address: 'https://anna.example.org', friends: [friend({ id: 7, name: 'Bruno', state: 'incoming', approved_at: null })] },
|
||||
{
|
||||
'POST /api/v1/federation/friends/7/approve': () => {
|
||||
s.state.friends = [friend({ id: 7, name: 'Bruno' })]
|
||||
return s.state.friends[0]
|
||||
},
|
||||
},
|
||||
)
|
||||
renderPage()
|
||||
expect(await screen.findByText('Wants to be your friend')).toBeInTheDocument()
|
||||
expect(screen.getByText('https://anna.example.org')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Approve Bruno' }))
|
||||
expect(await screen.findByText('Friend')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Approve Bruno' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('each friend shows where it is and its key, so two admins can compare them', async () => {
|
||||
server({ enabled: true, key_id: 'abcdef0123456789', friends: [friend({ name: 'Anna', key_id: 'feedfeedfeedfeed' })] })
|
||||
renderPage()
|
||||
const item = (await screen.findByText('Anna')).closest('li') as HTMLElement
|
||||
expect(within(item).getByText('https://anna.example.org')).toBeInTheDocument()
|
||||
expect(within(item).getByText(/feedfeedfeedfeed/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('removing a friend asks first and says the other server is not told', async () => {
|
||||
const user = userEvent.setup()
|
||||
const s = server(
|
||||
{ enabled: true, key_id: 'abcdef0123456789', friends: [friend({ id: 3 })] },
|
||||
{
|
||||
'DELETE /api/v1/federation/friends/3': () => {
|
||||
s.state.friends = []
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
},
|
||||
)
|
||||
renderPage()
|
||||
await user.click(await screen.findByRole('button', { name: 'Remove Anna' }))
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
expect(within(dialog).getByText(/The other server is not told/)).toBeInTheDocument()
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Remove' }))
|
||||
await waitFor(() => expect(screen.queryByText('Anna')).not.toBeInTheDocument())
|
||||
expect(screen.getByText('No friends yet.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a request is declined and a request one made is withdrawn, with words that fit', async () => {
|
||||
server({
|
||||
enabled: true,
|
||||
key_id: 'abcdef0123456789',
|
||||
friends: [friend({ id: 1, name: 'Bruno', state: 'incoming', approved_at: null }), friend({ id: 2, name: 'Carla', state: 'outgoing', approved_at: null })],
|
||||
})
|
||||
renderPage()
|
||||
expect(await screen.findByRole('button', { name: 'Decline Bruno' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Withdraw Carla' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a failure to read the settings says so, with a way to try again', async () => {
|
||||
mockFetch({ 'GET /api/v1/federation': () => apiError(500, 'internal') })
|
||||
renderPage()
|
||||
expect(await screen.findByRole('alert')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
|
||||
})
|
||||
76
web/src/pages/admin/FederationPage.tsx
Normal file
76
web/src/pages/admin/FederationPage.tsx
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useFederation, useUpdateFederation } from '@/api/adminFederation'
|
||||
import Section from '@/components/Section'
|
||||
import { ErrorMessage, Loading } from '@/components/Status'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import Confirm from './Confirm'
|
||||
import { errorText } from './errorText'
|
||||
import FederationFriends from './FederationFriends'
|
||||
import FederationInvites from './FederationInvites'
|
||||
import FederationSettings from './FederationSettings'
|
||||
|
||||
const FEDERATION_ERRORS = ['admin.federation.errors', 'admin.errors']
|
||||
|
||||
/**
|
||||
* Federation with other Sonda servers. It is off until an admin turns it on (and turning on says what a friend's
|
||||
* server is sent); once it is on, the admin names this server, gives its address, makes or uses invites, and
|
||||
* approves or removes friends.
|
||||
*/
|
||||
export default function FederationPage() {
|
||||
const { t } = useTranslation()
|
||||
const federation = useFederation()
|
||||
const update = useUpdateFederation()
|
||||
const [asking, setAsking] = useState(false)
|
||||
const label = t('admin.sectionFederation')
|
||||
|
||||
return (
|
||||
<Section title={label}>
|
||||
<p className="text-sm text-muted-foreground">{t('admin.federation.intro')}</p>
|
||||
{federation.isError ? (
|
||||
<ErrorMessage error={federation.error} onRetry={() => void federation.refetch()} />
|
||||
) : federation.isPending ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<Switch
|
||||
checked={federation.data.enabled}
|
||||
aria-label={label}
|
||||
disabled={update.isPending}
|
||||
onClick={() => (federation.data.enabled ? update.mutate({ enabled: false }) : setAsking(true))}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">{t(federation.data.enabled ? 'admin.federation.on' : 'admin.federation.off')}</span>
|
||||
</div>
|
||||
<p className="max-w-prose text-sm">{federation.data.sends}</p>
|
||||
{update.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorText(t, update.error, FEDERATION_ERRORS)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{federation.data.enabled && (
|
||||
<>
|
||||
<FederationSettings federation={federation.data} />
|
||||
<FederationInvites />
|
||||
<FederationFriends friends={federation.data.friends} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{asking && federation.data && (
|
||||
<Confirm
|
||||
title={t('admin.federation.turnOnTitle')}
|
||||
body={federation.data.sends}
|
||||
confirm={t('admin.federation.turnOn')}
|
||||
onClose={() => setAsking(false)}
|
||||
onConfirm={() => {
|
||||
update.mutate({ enabled: true })
|
||||
setAsking(false)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
64
web/src/pages/admin/FederationSettings.tsx
Normal file
64
web/src/pages/admin/FederationSettings.tsx
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
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 [name, setName] = useState(federation.name)
|
||||
const [address, setAddress] = useState(federation.address)
|
||||
const unchanged = name.trim() === federation.name && address.trim() === federation.address
|
||||
|
||||
function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
update.mutate({ name: name.trim(), address: address.trim() })
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="flex max-w-xl flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="federation-name">{t('admin.federation.name')}</Label>
|
||||
<Input id="federation-name" value={name} maxLength={60} autoCapitalize="off" spellCheck={false} onChange={(e) => setName(e.target.value)} />
|
||||
<p className="text-sm text-muted-foreground">{t('admin.federation.nameHint')}</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="federation-address">{t('admin.federation.address')}</Label>
|
||||
<Input
|
||||
id="federation-address"
|
||||
value={address}
|
||||
maxLength={300}
|
||||
inputMode="url"
|
||||
autoCapitalize="off"
|
||||
spellCheck={false}
|
||||
onChange={(e) => setAddress(e.target.value)}
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">{t('admin.federation.addressHint')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Button type="submit" variant="outline" disabled={unchanged || update.isPending}>
|
||||
{t('admin.federation.saveSettings')}
|
||||
</Button>
|
||||
</div>
|
||||
{update.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorText(t, update.error, SCOPES)}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('admin.federation.keyOfThis', { id: federation.key_id })} {t('admin.federation.keyHint')}
|
||||
</p>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
/** The name friends see, the address they reach this server at, and the key of this server. */
|
||||
export default function FederationSettings({ federation }: { federation: Federation }) {
|
||||
// Remounts the form when the server's values change, so it always starts from what the server keeps.
|
||||
return <Form key={`${federation.name}|${federation.address}`} federation={federation} />
|
||||
}
|
||||
|
|
@ -39,6 +39,7 @@ export const routes: RouteObject[] = [
|
|||
{ path: 'libraries', lazy: page(() => import('@/pages/admin/LibrariesPage')) },
|
||||
{ path: 'users', lazy: page(() => import('@/pages/admin/UsersPage')) },
|
||||
{ path: 'providers', lazy: page(() => import('@/pages/admin/ProvidersPage')) },
|
||||
{ path: 'federation', lazy: page(() => import('@/pages/admin/FederationPage')) },
|
||||
{ path: 'jobs', lazy: page(() => import('@/pages/admin/JobsPage')) },
|
||||
{ path: 'costs', lazy: page(() => import('@/pages/admin/CostsPage')) },
|
||||
],
|
||||
|
|
|
|||
Loading…
Reference in a new issue