A password for each app or device #11

Merged
squid merged 1 commit from feat/device-passwords into main 2026-11-16 08:15:39 +00:00
22 changed files with 1368 additions and 11 deletions

View file

@ -21,6 +21,7 @@ import (
"git.kmalloc.org/squid/sonda/internal/auth"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/config"
"git.kmalloc.org/squid/sonda/internal/devices"
"git.kmalloc.org/squid/sonda/internal/discover"
"git.kmalloc.org/squid/sonda/internal/discovery"
"git.kmalloc.org/squid/sonda/internal/duplicates"
@ -306,6 +307,7 @@ func run() error {
Tokens: tokens,
Listening: listening.NewService(storage.NewListeningRepo(db), cfg.Listening.MinListen()),
Mastodon: mastodonSvc,
Devices: devices.NewService(storage.NewDevicesRepo(db), []byte(cfg.Auth.JWTSecret)),
Scan: scanControl{ctx: ctx, m: scans},
Libraries: libraries,
Catalog: catalog.NewService(storage.NewCatalogRepo(db)),

View file

@ -19,6 +19,7 @@ import (
"git.kmalloc.org/squid/sonda/internal/affinity"
"git.kmalloc.org/squid/sonda/internal/auth"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/devices"
"git.kmalloc.org/squid/sonda/internal/discover"
"git.kmalloc.org/squid/sonda/internal/discovery"
"git.kmalloc.org/squid/sonda/internal/duplicates"
@ -115,6 +116,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
Settings: usersettings.NewService(storage.NewUserSettingsRepo(db)),
Streams: streaming.NewService(noFiles{}),
Federation: federation.NewService(storage.NewFederationRepo(db), federation.NewClient()),
Devices: devices.NewService(storage.NewDevicesRepo(db), []byte(strings.Repeat("k", 32))),
Mastodon: mastodon.NewService(storage.NewMastodonRepo(db), &fakeMastodon{handle: "@test@mastodon.social"}, zap.NewNop()),
}
libRepo := storage.NewLibraryRepo(db)

View file

@ -888,6 +888,22 @@ func TestResponsesMatchTheSpec(t *testing.T) {
c.expect(c.call("DELETE", "/me/mastodon", token, nil), 204, "disconnect Mastodon")
c.expect(c.call("GET", "/me/mastodon", "", nil), 401, "Mastodon without a token", "unauthorized")
// The passwords of other apps: the secret is shown once, and a device is taken back by its owner only.
if got := c.expect(c.call("GET", "/me/devices", token, nil), 200, "no devices yet"); len(got["devices"].([]any)) != 0 {
c.t.Errorf("devices = %v", got)
}
made := c.expect(c.call("POST", "/me/devices", token, map[string]any{"name": "Phone"}), 201, "make a device")
if len(made["secret"].(string)) != 48 {
c.t.Errorf("secret = %v", made["secret"])
}
c.expect(c.call("POST", "/me/devices", token, map[string]any{"name": " "}), 400, "a device with no name", "invalid_name")
if got := c.expect(c.call("GET", "/me/devices", token, nil), 200, "the devices"); len(got["devices"].([]any)) != 1 {
c.t.Errorf("devices = %v", got)
}
c.expect(c.call("DELETE", "/me/devices/"+idOf(made), token, nil), 204, "take back a device")
c.expect(c.call("DELETE", "/me/devices/"+idOf(made), token, nil), 404, "take back a device twice", "device_not_found")
c.expect(c.call("GET", "/me/devices", "", nil), 401, "devices without a token", "unauthorized")
// Bringing a Spotify export in: what it did, and what is refused.
export := `[{"ts":"2023-05-01T10:00:00Z","ms_played":200000,"master_metadata_track_name":"Nowhere","master_metadata_album_artist_name":"Nobody"}]`
imported := c.expect(c.upload("/me/import/spotify", token, export, `{"playlists":[{"name":"P","items":[{"track":{"trackName":"Nowhere","artistName":"Nobody"}}]}]}`), 200, "import a Spotify export")

View file

@ -0,0 +1,102 @@
package httpapi
import (
"net/http"
"strings"
"testing"
)
func TestDevicesNeedASignedInUser(t *testing.T) {
h := newTestAPI(t)
for _, c := range [][2]string{{"GET", "/api/v1/me/devices"}, {"POST", "/api/v1/me/devices"}, {"DELETE", "/api/v1/me/devices/1"}} {
if r := do(t, h, c[0], c[1], "", map[string]any{}); r.Code != http.StatusUnauthorized {
t.Errorf("%s %s without a token: %d", c[0], c[1], r.Code)
}
}
}
func TestADeviceIsMadeShownOnceAndTakenBack(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
r := do(t, h, "GET", "/api/v1/me/devices", alice, nil)
if r.Code != http.StatusOK {
t.Fatalf("%d %v", r.Code, r.Body)
}
if list, ok := r.Body["devices"].([]any); !ok || len(list) != 0 {
t.Fatalf("devices at the start: %v", r.Body)
}
r = do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "Phone"})
if r.Code != http.StatusCreated {
t.Fatalf("create: %d %v", r.Code, r.Body)
}
sameKeys(t, "created device", r.Body, "id", "name", "created_at", "secret")
secret, _ := r.Body["secret"].(string)
if len(secret) != 48 || r.Body["name"] != "Phone" {
t.Fatalf("created = %v", r.Body)
}
r = do(t, h, "GET", "/api/v1/me/devices", alice, nil)
list, _ := r.Body["devices"].([]any)
if len(list) != 1 {
t.Fatalf("list = %v", r.Body)
}
one := list[0].(map[string]any)
sameKeys(t, "listed device", one, "id", "name", "created_at")
if strings.Contains(r.Body["devices"].([]any)[0].(map[string]any)["name"].(string), secret) {
t.Fatal("the secret is in the list")
}
id := int64(one["id"].(float64))
path := "/api/v1/me/devices/" + itoa(id)
if r := do(t, h, "DELETE", path, alice, nil); r.Code != http.StatusNoContent {
t.Fatalf("delete: %d %v", r.Code, r.Body)
}
if r := do(t, h, "DELETE", path, alice, nil); r.Code != http.StatusNotFound || errCode(r) != "device_not_found" {
t.Fatalf("delete twice: %d %v", r.Code, r.Body)
}
}
func TestADeviceNeedsAName(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
for _, body := range []any{map[string]any{"name": " "}, map[string]any{}, map[string]any{"name": strings.Repeat("a", 61)}} {
if r := do(t, h, "POST", "/api/v1/me/devices", alice, body); r.Code != http.StatusBadRequest || errCode(r) != "invalid_name" {
t.Errorf("%v: %d %v", body, r.Code, r.Body)
}
}
if r := do(t, h, "POST", "/api/v1/me/devices", alice, "{not json"); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("bad json: %d %v", r.Code, r.Body)
}
if r := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "ok", "extra": 1}); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("unknown name: %d %v", r.Code, r.Body)
}
}
func TestADeviceOfSomeoneElseIsNotFound(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
r := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "Phone"})
id := int64(r.Body["id"].(float64))
_, bob := addUser(t, h, alice, "bob", false)
if r := do(t, h, "DELETE", "/api/v1/me/devices/"+itoa(id), bob, nil); r.Code != http.StatusNotFound {
t.Fatalf("bob deleted alice's device: %d", r.Code)
}
if r := do(t, h, "GET", "/api/v1/me/devices", bob, nil); len(r.Body["devices"].([]any)) != 0 {
t.Fatalf("bob sees %v", r.Body)
}
}
func TestTooManyDevices(t *testing.T) {
h := newTestAPI(t)
alice := registerAndLogin(t, h)
for i := 0; i < 20; i++ {
if r := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "d"}); r.Code != http.StatusCreated {
t.Fatalf("%d: %d", i, r.Code)
}
}
if r := do(t, h, "POST", "/api/v1/me/devices", alice, map[string]any{"name": "d"}); r.Code != http.StatusConflict || errCode(r) != "too_many_devices" {
t.Fatalf("over the limit: %d %v", r.Code, r.Body)
}
}

View file

@ -0,0 +1,105 @@
package httpapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/devices"
)
// deviceService is what the handlers need from devices.Service.
type deviceService interface {
Create(ctx context.Context, userID int64, name string) (devices.Device, string, error)
List(ctx context.Context, userID int64) ([]devices.Device, error)
Revoke(ctx context.Context, userID, id int64) error
}
// deviceHandlers serve the passwords of the signed-in user's apps and devices.
type deviceHandlers struct{ svc deviceService }
// deviceJSON is a device as a person sees it: never with its secret, except in the answer that makes it.
type deviceJSON struct {
ID int64 `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
}
type createdDeviceJSON struct {
deviceJSON
Secret string `json:"secret"`
}
func toDeviceJSON(d devices.Device) deviceJSON {
return deviceJSON{ID: d.ID, Name: d.Name, CreatedAt: d.CreatedAt.UTC(), LastUsedAt: d.LastUsedAt}
}
func (h *deviceHandlers) list(c *gin.Context) {
list, err := h.svc.List(c.Request.Context(), currentUserID(c))
if err != nil {
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
out := make([]deviceJSON, len(list))
for i, d := range list {
out[i] = toDeviceJSON(d)
}
c.JSON(http.StatusOK, gin.H{"devices": out})
}
func (h *deviceHandlers) create(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
if err != nil {
writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body")
return
}
// One object with the name and nothing else: what comes back is a secret.
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
var req struct {
Name string `json:"name"`
}
if err := dec.Decode(&req); err != nil || dec.More() {
writeError(c, http.StatusBadRequest, "invalid_input", "send the name of the device")
return
}
d, secret, err := h.svc.Create(c.Request.Context(), currentUserID(c), req.Name)
switch {
case errors.Is(err, devices.ErrInvalidName):
writeError(c, http.StatusBadRequest, "invalid_name", err.Error())
case errors.Is(err, devices.ErrTooMany):
writeError(c, http.StatusConflict, "too_many_devices", err.Error())
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
default:
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusCreated, createdDeviceJSON{deviceJSON: toDeviceJSON(d), Secret: secret})
}
}
func (h *deviceHandlers) revoke(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || id < 1 {
writeError(c, http.StatusNotFound, "device_not_found", "device not found")
return
}
switch err := h.svc.Revoke(c.Request.Context(), currentUserID(c), id); {
case errors.Is(err, devices.ErrNotFound):
writeError(c, http.StatusNotFound, "device_not_found", "device not found")
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
default:
c.Status(http.StatusNoContent)
}
}

View file

@ -228,6 +228,7 @@ type Deps struct {
Tokens tokenParser
Listening listenService
Mastodon mastodonService
Devices deviceService
Scan scanService
Libraries libraryService
Catalog catalogService
@ -393,6 +394,10 @@ func NewRouter(d Deps) *gin.Engine {
protected.GET("/me/mastodon", ma.get)
protected.PUT("/me/mastodon", ma.connect)
protected.DELETE("/me/mastodon", ma.disconnect)
dv := &deviceHandlers{svc: d.Devices}
protected.GET("/me/devices", dv.list)
protected.POST("/me/devices", dv.create)
protected.DELETE("/me/devices/:id", dv.revoke)
lib := &libraryHandlers{scan: d.Scan}
protected.GET("/library/scan", lib.scanStatus)

View file

@ -2271,6 +2271,73 @@ paths:
'204': {description: Disconnected.}
'401': {$ref: '#/components/responses/Unauthorized'}
/me/devices:
get:
tags: [Taste]
operationId: listMyDevices
summary: The passwords of your apps and devices
description: |
The device passwords you made for other apps (OpenSubsonic clients), newest first. The secret is never sent
back: it was shown once, when the password was made.
security: [{bearerAuth: []}]
responses:
'200':
description: Your devices.
content:
application/json:
schema: {$ref: '#/components/schemas/DeviceList'}
'401': {$ref: '#/components/responses/Unauthorized'}
post:
tags: [Taste]
operationId: createMyDevice
summary: Make a password for an app or device
description: |
Makes a password for one app or device and returns it. **The secret is shown only in this answer**: copy it into
the app now. It opens the music API for other apps and nothing else: it cannot sign in to Sonda, change your
account or make more passwords. Make one for each app, so that you can take back one without the others. You can
have up to 20. The body must be one JSON object with the name and nothing else.
security: [{bearerAuth: []}]
requestBody:
required: true
content:
application/json:
schema: {$ref: '#/components/schemas/CreateDevice'}
responses:
'201':
description: The device, with its secret.
content:
application/json:
schema: {$ref: '#/components/schemas/CreatedDevice'}
'400':
description: The body is malformed (`invalid_input`) or the name is empty or longer than 60 characters (`invalid_name`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
'401': {$ref: '#/components/responses/Unauthorized'}
'409':
description: You have 20 devices already (`too_many_devices`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/me/devices/{id}:
delete:
tags: [Taste]
operationId: deleteMyDevice
summary: Take back the password of a device
description: "Takes back the password, so the app that had it can no longer connect. Only your own devices."
security: [{bearerAuth: []}]
parameters:
- {name: id, in: path, required: true, schema: {type: integer, format: int64}}
responses:
'204': {description: Taken back.}
'401': {$ref: '#/components/responses/Unauthorized'}
'404':
description: There is no such device of yours (`device_not_found`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/me/import/spotify:
get:
tags: [Taste]
@ -6016,6 +6083,42 @@ components:
name: {type: string}
count: {type: integer, description: 'Plays and playlist songs of this artist that were not found.'}
Device:
type: object
additionalProperties: false
required: [id, name, created_at]
properties:
id: {type: integer, format: int64}
name: {type: string, maxLength: 60}
created_at: {type: string, format: date-time}
last_used_at: {type: string, format: date-time, description: "When an app last connected with it. Absent until it does."}
DeviceList:
type: object
additionalProperties: false
required: [devices]
properties:
devices:
type: array
items: {$ref: '#/components/schemas/Device'}
CreateDevice:
type: object
additionalProperties: false
required: [name]
properties:
name: {type: string, maxLength: 60, description: "What this password is for, like `Phone` or `Feishin on the laptop`."}
CreatedDevice:
type: object
additionalProperties: false
required: [id, name, created_at, secret]
properties:
id: {type: integer, format: int64}
name: {type: string, maxLength: 60}
created_at: {type: string, format: date-time}
secret: {type: string, description: "The password, 48 characters. Shown only here: it is never sent again."}
MastodonAccount:
type: object
additionalProperties: false

173
internal/devices/devices.go Normal file
View file

@ -0,0 +1,173 @@
// Package devices keeps the passwords a person makes for the apps and devices that connect to their server.
//
// A device password is a long random secret, shown once, that opens the music API for other apps (the OpenSubsonic
// one) and nothing else: it cannot sign in to Sonda, change the account or make more passwords. A person can have one
// for each phone or app and take it back at any time, so the account password never goes to an app.
//
// Subsonic's token login sends md5(secret + salt), so the server must know the secret itself, not a hash of it. The
// secret is therefore kept sealed (AES-256-GCM, with a key derived from the server's jwt secret): a copy of the
// database alone does not tell it. A hash of the secret is kept too, to find the device of an API key without trying
// every one.
package devices
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/hkdf"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"sort"
"strings"
"time"
"unicode/utf8"
)
// Errors returned by the service.
var (
ErrNotFound = errors.New("device not found")
ErrInvalidName = errors.New("the name must have 1 to 60 characters")
ErrTooMany = errors.New("there are too many devices: remove one first")
)
const (
// MaxDevices is how many a person can have: far more than anyone uses, and a bound on the work of a login.
MaxDevices = 20
// MaxName is the longest name, in characters.
MaxName = 60
secretSize = 24
)
// Device is what a person sees of a device: never the secret.
type Device struct {
ID int64
Name string
CreatedAt time.Time
LastUsedAt *time.Time // nil until the device is used
}
// Row is a device as it is stored.
type Row struct {
ID int64
UserID int64
Name string
KeyHash string // hex sha256 of the secret, to find it when only the secret is known
Sealed []byte // the secret, sealed
CreatedAt time.Time
LastUsedAt *time.Time
}
// Store keeps the devices.
type Store interface {
// Create stores a device and returns it with its id.
Create(ctx context.Context, r Row) (Row, error)
// List returns the devices of a person.
List(ctx context.Context, userID int64) ([]Row, error)
// Delete removes a device of a person, with ErrNotFound when there is none.
Delete(ctx context.Context, userID, id int64) error
}
// Service makes and takes back device passwords.
type Service struct {
store Store
aead cipher.AEAD
now func() time.Time
}
// NewService builds a Service. secret is the server's jwt secret: the key that seals the passwords comes from it, so
// a server that changes it makes the people make their device passwords again.
func NewService(store Store, secret []byte) *Service {
key, err := hkdf.Key(sha256.New, secret, nil, "sonda device passwords", 32)
if err != nil {
panic(fmt.Sprintf("devices: derive key: %v", err)) // only for a length that is out of range
}
block, err := aes.NewCipher(key)
if err != nil {
panic(fmt.Sprintf("devices: cipher: %v", err)) // a 32-byte key is always valid
}
aead, err := cipher.NewGCM(block)
if err != nil {
panic(fmt.Sprintf("devices: gcm: %v", err))
}
return &Service{store: store, aead: aead, now: time.Now}
}
// Create makes a device for a person and returns it with its secret, which is never given again.
func (s *Service) Create(ctx context.Context, userID int64, name string) (Device, string, error) {
name = strings.TrimSpace(name)
if n := utf8.RuneCountInString(name); n == 0 || n > MaxName {
return Device{}, "", ErrInvalidName
}
rows, err := s.store.List(ctx, userID)
if err != nil {
return Device{}, "", fmt.Errorf("list devices: %w", err)
}
if len(rows) >= MaxDevices {
return Device{}, "", ErrTooMany
}
raw := make([]byte, secretSize)
if _, err := rand.Read(raw); err != nil {
return Device{}, "", fmt.Errorf("generate secret: %w", err)
}
secret := hex.EncodeToString(raw)
row, err := s.store.Create(ctx, Row{
UserID: userID, Name: name, KeyHash: KeyHash(secret), Sealed: s.seal(secret), CreatedAt: s.now(),
})
if err != nil {
return Device{}, "", fmt.Errorf("create device: %w", err)
}
return device(row), secret, nil
}
// List returns the devices of a person, the newest first.
func (s *Service) List(ctx context.Context, userID int64) ([]Device, error) {
rows, err := s.store.List(ctx, userID)
if err != nil {
return nil, fmt.Errorf("list devices: %w", err)
}
sort.Slice(rows, func(i, j int) bool { return rows[i].ID > rows[j].ID })
out := make([]Device, len(rows))
for i, r := range rows {
out[i] = device(r)
}
return out, nil
}
// Revoke takes back the password of a device of a person: the app that had it can no longer connect.
func (s *Service) Revoke(ctx context.Context, userID, id int64) error {
return s.store.Delete(ctx, userID, id)
}
// Reveal opens a sealed secret.
func (s *Service) Reveal(sealed []byte) (string, error) {
n := s.aead.NonceSize()
if len(sealed) < n+s.aead.Overhead() {
return "", errors.New("devices: sealed secret is too short")
}
plain, err := s.aead.Open(nil, sealed[:n], sealed[n:], nil)
if err != nil {
return "", errors.New("devices: cannot open the sealed secret")
}
return string(plain), nil
}
func (s *Service) seal(secret string) []byte {
nonce := make([]byte, s.aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
panic(fmt.Sprintf("devices: nonce: %v", err)) // the system source of randomness failed: nothing is safe
}
return s.aead.Seal(nonce, nonce, []byte(secret), nil)
}
// KeyHash is what is kept to find a device by its secret.
func KeyHash(secret string) string {
sum := sha256.Sum256([]byte(secret))
return hex.EncodeToString(sum[:])
}
func device(r Row) Device {
return Device{ID: r.ID, Name: r.Name, CreatedAt: r.CreatedAt, LastUsedAt: r.LastUsedAt}
}

View file

@ -0,0 +1,148 @@
package devices
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"time"
)
// memStore keeps the rows in memory, like the database would, and lets a test look at what was stored.
type memStore struct {
rows []Row
nextID int64
}
func (m *memStore) Create(_ context.Context, r Row) (Row, error) {
m.nextID++
r.ID = m.nextID
m.rows = append(m.rows, r)
return r, nil
}
func (m *memStore) List(_ context.Context, userID int64) ([]Row, error) {
var out []Row
for _, r := range m.rows {
if r.UserID == userID {
out = append(out, r)
}
}
return out, nil
}
func (m *memStore) Delete(_ context.Context, userID, id int64) error {
for i, r := range m.rows {
if r.ID == id && r.UserID == userID {
m.rows = append(m.rows[:i], m.rows[i+1:]...)
return nil
}
}
return ErrNotFound
}
func newService() (*Service, *memStore) {
st := &memStore{}
s := NewService(st, []byte(strings.Repeat("k", 32)))
s.now = func() time.Time { return time.Unix(1_700_000_000, 0) }
return s, st
}
func TestCreateGivesTheSecretOnceAndKeepsItSealed(t *testing.T) {
s, st := newService()
d, secret, err := s.Create(context.Background(), 1, " Phone ")
if err != nil {
t.Fatal(err)
}
if d.Name != "Phone" || d.ID == 0 || !d.CreatedAt.Equal(time.Unix(1_700_000_000, 0)) {
t.Fatalf("device %+v", d)
}
if len(secret) != 48 {
t.Fatalf("secret %q is not 24 bytes in hex", secret)
}
row := st.rows[0]
if bytes.Contains(row.Sealed, []byte(secret)) {
t.Fatal("the secret is stored in clear")
}
if row.KeyHash == "" || strings.Contains(row.KeyHash, secret) {
t.Fatalf("the lookup hash is %q", row.KeyHash)
}
back, err := s.Reveal(row.Sealed)
if err != nil || back != secret {
t.Fatalf("Reveal = %q, %v", back, err)
}
}
func TestTwoDevicesHaveDifferentSecrets(t *testing.T) {
s, st := newService()
_, a, _ := s.Create(context.Background(), 1, "A")
_, b, _ := s.Create(context.Background(), 1, "B")
if a == b || st.rows[0].KeyHash == st.rows[1].KeyHash {
t.Fatal("two devices share a secret")
}
}
func TestAnotherKeyCannotOpenASealedSecret(t *testing.T) {
s, st := newService()
_, _, _ = s.Create(context.Background(), 1, "Phone")
other := NewService(&memStore{}, []byte(strings.Repeat("z", 32)))
if _, err := other.Reveal(st.rows[0].Sealed); err == nil {
t.Fatal("a different key opened the secret")
}
if _, err := s.Reveal([]byte("short")); err == nil {
t.Fatal("a bad value was opened")
}
}
func TestTheNameIsRequiredAndShort(t *testing.T) {
s, _ := newService()
for _, name := range []string{"", " ", strings.Repeat("a", 61)} {
if _, _, err := s.Create(context.Background(), 1, name); !errors.Is(err, ErrInvalidName) {
t.Errorf("name %q: %v", name, err)
}
}
if _, _, err := s.Create(context.Background(), 1, strings.Repeat("à", 60)); err != nil {
t.Errorf("60 letters: %v", err)
}
}
func TestThereIsALimitOfDevicesForEachPerson(t *testing.T) {
s, _ := newService()
for i := 0; i < MaxDevices; i++ {
if _, _, err := s.Create(context.Background(), 1, "d"); err != nil {
t.Fatal(err)
}
}
if _, _, err := s.Create(context.Background(), 1, "one more"); !errors.Is(err, ErrTooMany) {
t.Fatalf("over the limit: %v", err)
}
if _, _, err := s.Create(context.Background(), 2, "someone else"); err != nil {
t.Fatalf("another person: %v", err)
}
}
func TestListShowsOwnDevicesNewestFirstWithoutSecrets(t *testing.T) {
s, _ := newService()
_, _, _ = s.Create(context.Background(), 1, "first")
_, _, _ = s.Create(context.Background(), 2, "not mine")
_, _, _ = s.Create(context.Background(), 1, "second")
got, err := s.List(context.Background(), 1)
if err != nil || len(got) != 2 || got[0].Name != "second" || got[1].Name != "first" {
t.Fatalf("List = %+v, %v", got, err)
}
}
func TestRevokeIsForTheOwnerOnly(t *testing.T) {
s, _ := newService()
d, _, _ := s.Create(context.Background(), 1, "Phone")
if err := s.Revoke(context.Background(), 2, d.ID); !errors.Is(err, ErrNotFound) {
t.Fatalf("someone else: %v", err)
}
if err := s.Revoke(context.Background(), 1, d.ID); err != nil {
t.Fatal(err)
}
if err := s.Revoke(context.Background(), 1, d.ID); !errors.Is(err, ErrNotFound) {
t.Fatalf("twice: %v", err)
}
}

View file

@ -0,0 +1,72 @@
package storage
import (
"context"
"fmt"
"time"
"github.com/uptrace/bun"
"git.kmalloc.org/squid/sonda/internal/devices"
)
type deviceRow struct {
bun.BaseModel `bun:"table:device_passwords"`
ID int64 `bun:"id,pk,autoincrement"`
UserID int64 `bun:"user_id,notnull"`
Name string `bun:"name,notnull"`
KeyHash string `bun:"key_hash,notnull"`
Sealed []byte `bun:"sealed,notnull"`
CreatedAt int64 `bun:"created_at,notnull"`
LastUsedAt *int64 `bun:"last_used_at"`
}
func (r deviceRow) device() devices.Row {
out := devices.Row{ID: r.ID, UserID: r.UserID, Name: r.Name, KeyHash: r.KeyHash, Sealed: r.Sealed, CreatedAt: time.Unix(r.CreatedAt, 0)}
if r.LastUsedAt != nil {
t := time.Unix(*r.LastUsedAt, 0)
out.LastUsedAt = &t
}
return out
}
// DevicesRepo keeps the passwords of apps and devices. It implements devices.Store.
type DevicesRepo struct{ db *bun.DB }
// NewDevicesRepo builds a DevicesRepo.
func NewDevicesRepo(db *bun.DB) *DevicesRepo { return &DevicesRepo{db: db} }
// Create stores a device and returns it with its id.
func (r *DevicesRepo) Create(ctx context.Context, d devices.Row) (devices.Row, error) {
row := &deviceRow{UserID: d.UserID, Name: d.Name, KeyHash: d.KeyHash, Sealed: d.Sealed, CreatedAt: d.CreatedAt.Unix()}
if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil {
return devices.Row{}, fmt.Errorf("insert device: %w", err)
}
return row.device(), nil
}
// List returns the devices of a person.
func (r *DevicesRepo) List(ctx context.Context, userID int64) ([]devices.Row, error) {
var rows []deviceRow
if err := r.db.NewSelect().Model(&rows).Where("user_id = ?", userID).Order("id DESC").Scan(ctx); err != nil {
return nil, fmt.Errorf("select devices: %w", err)
}
out := make([]devices.Row, len(rows))
for i, row := range rows {
out[i] = row.device()
}
return out, nil
}
// Delete removes a device of a person, with devices.ErrNotFound when there is none.
func (r *DevicesRepo) Delete(ctx context.Context, userID, id int64) error {
res, err := r.db.NewDelete().Model((*deviceRow)(nil)).Where("id = ? AND user_id = ?", id, userID).Exec(ctx)
if err != nil {
return fmt.Errorf("delete device: %w", err)
}
if n, _ := res.RowsAffected(); n == 0 {
return devices.ErrNotFound
}
return nil
}

View file

@ -0,0 +1,82 @@
package storage
import (
"context"
"errors"
"testing"
"time"
"github.com/uptrace/bun"
"git.kmalloc.org/squid/sonda/internal/devices"
)
func TestDevicesAreKeptListedAndTakenBack(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewDevicesRepo(db)
alice, bob := seedUser(t, db, "a@example.org"), seedUser(t, db, "b@example.org")
at := time.Unix(1_700_000_000, 0)
first, err := repo.Create(ctx, devices.Row{UserID: alice, Name: "Phone", KeyHash: "h1", Sealed: []byte{1, 2, 3}, CreatedAt: at})
if err != nil || first.ID == 0 {
t.Fatalf("Create = %+v, %v", first, err)
}
if _, err := repo.Create(ctx, devices.Row{UserID: bob, Name: "Tablet", KeyHash: "h2", Sealed: []byte{4}, CreatedAt: at}); err != nil {
t.Fatal(err)
}
got, err := repo.List(ctx, alice)
if err != nil || len(got) != 1 {
t.Fatalf("List = %+v, %v", got, err)
}
if g := got[0]; g.ID != first.ID || g.Name != "Phone" || g.KeyHash != "h1" || string(g.Sealed) != "\x01\x02\x03" || !g.CreatedAt.Equal(at) || g.LastUsedAt != nil {
t.Fatalf("row %+v", g)
}
if err := repo.Delete(ctx, bob, first.ID); !errors.Is(err, devices.ErrNotFound) {
t.Fatalf("someone else's device: %v", err)
}
if err := repo.Delete(ctx, alice, first.ID); err != nil {
t.Fatal(err)
}
if err := repo.Delete(ctx, alice, first.ID); !errors.Is(err, devices.ErrNotFound) {
t.Fatalf("twice: %v", err)
}
if got, _ := repo.List(ctx, alice); len(got) != 0 {
t.Fatalf("after delete: %+v", got)
}
})
}
func TestTwoDevicesCannotShareASecret(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewDevicesRepo(db)
uid := seedUser(t, db, "a@example.org")
row := devices.Row{UserID: uid, Name: "A", KeyHash: "same", Sealed: []byte{1}, CreatedAt: time.Unix(1, 0)}
if _, err := repo.Create(ctx, row); err != nil {
t.Fatal(err)
}
if _, err := repo.Create(ctx, row); err == nil {
t.Fatal("the same secret was kept twice")
}
})
}
func TestDevicesGoWithTheirPerson(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewDevicesRepo(db)
uid := seedUser(t, db, "a@example.org")
if _, err := repo.Create(ctx, devices.Row{UserID: uid, Name: "A", KeyHash: "h", Sealed: []byte{1}, CreatedAt: time.Unix(1, 0)}); err != nil {
t.Fatal(err)
}
if _, err := db.ExecContext(ctx, "DELETE FROM users WHERE id = ?", uid); err != nil {
t.Fatal(err)
}
var n int
if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM device_passwords").Scan(&n); err != nil || n != 0 {
t.Fatalf("%d devices left, %v", n, err)
}
})
}

View file

@ -156,8 +156,8 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) {
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil {
t.Fatal(err)
}
if applied != 33 {
t.Errorf("applied migrations = %d, want 33", applied)
if applied != 34 {
t.Errorf("applied migrations = %d, want 34", applied)
}
})
}

View file

@ -0,0 +1,16 @@
-- The passwords a person makes for the apps and devices that connect to their server (OpenSubsonic clients). A password
-- opens the music API and nothing else. Token login needs the secret itself, so it is kept sealed (sealed), and a hash of
-- it (key_hash) finds the device of an API key.
CREATE TABLE device_passwords (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
key_hash TEXT NOT NULL,
sealed BYTEA NOT NULL,
created_at BIGINT NOT NULL,
last_used_at BIGINT
);
CREATE UNIQUE INDEX idx_device_passwords_key ON device_passwords(key_hash);
CREATE INDEX idx_device_passwords_user ON device_passwords(user_id);

View file

@ -0,0 +1,16 @@
-- The passwords a person makes for the apps and devices that connect to their server (OpenSubsonic clients). A password
-- opens the music API and nothing else. Token login needs the secret itself, so it is kept sealed (sealed), and a hash of
-- it (key_hash) finds the device of an API key.
CREATE TABLE device_passwords (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
key_hash TEXT NOT NULL,
sealed BLOB NOT NULL,
created_at INTEGER NOT NULL, -- unix seconds
last_used_at INTEGER -- unix seconds, NULL until it is used
);
CREATE UNIQUE INDEX idx_device_passwords_key ON device_passwords(key_hash);
CREATE INDEX idx_device_passwords_user ON device_passwords(user_id);

31
web/src/api/devices.ts Normal file
View file

@ -0,0 +1,31 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '@/api/client'
import type { components } from '@/api/schema'
export type Device = components['schemas']['Device']
export type CreatedDevice = components['schemas']['CreatedDevice']
type DeviceList = components['schemas']['DeviceList']
const KEY = ['me', 'devices']
/** The passwords this person made for their apps and devices. The secrets are never in the list. */
export function useDevices() {
return useQuery({ queryKey: KEY, queryFn: async () => (await api.get<DeviceList>('/me/devices')).devices })
}
/** Makes a password. The answer holds the secret, which the server never sends again. */
export function useCreateDevice() {
const client = useQueryClient()
return useMutation({
mutationFn: (name: string) => api.post<CreatedDevice>('/me/devices', { name }),
onSuccess: () => client.invalidateQueries({ queryKey: KEY }),
})
}
export function useDeleteDevice() {
const client = useQueryClient()
return useMutation({
mutationFn: (id: number) => api.del<void>(`/me/devices/${id}`),
onSuccess: () => client.invalidateQueries({ queryKey: KEY }),
})
}

View file

@ -1620,6 +1620,54 @@ export interface paths {
patch?: never;
trace?: never;
};
"/me/devices": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The passwords of your apps and devices
* @description The device passwords you made for other apps (OpenSubsonic clients), newest first. The secret is never sent
* back: it was shown once, when the password was made.
*/
get: operations["listMyDevices"];
put?: never;
/**
* Make a password for an app or device
* @description Makes a password for one app or device and returns it. **The secret is shown only in this answer**: copy it into
* the app now. It opens the music API for other apps and nothing else: it cannot sign in to Sonda, change your
* account or make more passwords. Make one for each app, so that you can take back one without the others. You can
* have up to 20. The body must be one JSON object with the name and nothing else.
*/
post: operations["createMyDevice"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/me/devices/{id}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
post?: never;
/**
* Take back the password of a device
* @description Takes back the password, so the app that had it can no longer connect. Only your own devices.
*/
delete: operations["deleteMyDevice"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/me/import/spotify": {
parameters: {
query?: never;
@ -4206,6 +4254,34 @@ export interface components {
}[];
};
};
Device: {
/** Format: int64 */
id: number;
name: string;
/** Format: date-time */
created_at: string;
/**
* Format: date-time
* @description When an app last connected with it. Absent until it does.
*/
last_used_at?: string;
};
DeviceList: {
devices: components["schemas"]["Device"][];
};
CreateDevice: {
/** @description What this password is for, like `Phone` or `Feishin on the laptop`. */
name: string;
};
CreatedDevice: {
/** Format: int64 */
id: number;
name: string;
/** Format: date-time */
created_at: string;
/** @description The password, 48 characters. Shown only here: it is never sent again. */
secret: string;
};
MastodonAccount: {
connected: boolean;
/** @description The instance, like `https://mastodon.social`. Only when connected. */
@ -7124,6 +7200,100 @@ export interface operations {
401: components["responses"]["Unauthorized"];
};
};
listMyDevices: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Your devices. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["DeviceList"];
};
};
401: components["responses"]["Unauthorized"];
};
};
createMyDevice: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["CreateDevice"];
};
};
responses: {
/** @description The device, with its secret. */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["CreatedDevice"];
};
};
/** @description The body is malformed (`invalid_input`) or the name is empty or longer than 60 characters (`invalid_name`). */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
401: components["responses"]["Unauthorized"];
/** @description You have 20 devices already (`too_many_devices`). */
409: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
deleteMyDevice: {
parameters: {
query?: never;
header?: never;
path: {
id: number;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Taken back. */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
401: components["responses"]["Unauthorized"];
/** @description There is no such device of yours (`device_not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
listMySpotifyImports: {
parameters: {
query?: {

View file

@ -0,0 +1,125 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, 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 DevicesBlock from './DevicesBlock'
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: false } })
})
interface Dev {
id: number
name: string
created_at: string
last_used_at?: string
}
const phone: Dev = { id: 2, name: 'Phone', created_at: '2026-11-10T12:00:00Z', last_used_at: '2026-11-15T12:00:00Z' }
const laptop: Dev = { id: 1, name: 'Laptop', created_at: '2026-11-01T12:00:00Z' }
function setup(initial: Dev[], over: MockRoutes = {}) {
let devices = initial
const mocked = mockFetch({
'GET /api/v1/me/devices': () => ({ devices }),
'POST /api/v1/me/devices': ({ init }) => {
const made = { id: 9, name: JSON.parse(String(init.body)).name, created_at: '2026-11-16T09:00:00Z' }
devices = [made, ...devices]
return new Response(JSON.stringify({ ...made, secret: 'ab'.repeat(24) }), { status: 201, headers: { 'Content-Type': 'application/json' } })
},
'DELETE /api/v1/me/devices/2': () => {
devices = devices.filter((d) => d.id !== 2)
return new Response(null, { status: 204 })
},
...over,
})
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })}>
<DevicesBlock />
</QueryClientProvider>,
)
return mocked
}
test('it says what a device password is for, and lists the devices with when they were used', async () => {
setup([phone, laptop])
expect(await screen.findByText('Phone')).toBeInTheDocument()
const list = screen.getByRole('list', { name: 'Your devices' })
const rows = within(list).getAllByRole('listitem')
expect(rows).toHaveLength(2)
expect(rows[0]).toHaveTextContent(/Last used Nov 15, 2026/)
expect(rows[1]).toHaveTextContent('Never used')
expect(screen.getByText(/other apps/)).toBeInTheDocument()
})
test('with no device there is no list, only the form', async () => {
setup([])
expect(await screen.findByLabelText('Name of the app or device')).toBeInTheDocument()
expect(screen.queryByRole('list', { name: 'Your devices' })).not.toBeInTheDocument()
})
test('making a password shows it once with the sign-in details, and the list gets the device', async () => {
const { calls } = setup([laptop])
await userEvent.type(await screen.findByLabelText('Name of the app or device'), ' Feishin ')
await userEvent.click(screen.getByRole('button', { name: 'Make password' }))
const shown = await screen.findByRole('region', { name: 'Password for Feishin' })
expect(within(shown).getByText('ab'.repeat(24))).toBeInTheDocument()
expect(within(shown).getByText('tom@example.org')).toBeInTheDocument()
expect(within(shown).getByText(window.location.origin)).toBeInTheDocument()
expect(within(shown).getByText(/only time/)).toBeInTheDocument()
expect(JSON.parse(String(calls.find((c) => c.key === 'POST /api/v1/me/devices')!.init.body))).toEqual({ name: 'Feishin' })
await userEvent.click(within(shown).getByRole('button', { name: 'Done' }))
expect(screen.queryByRole('region', { name: 'Password for Feishin' })).not.toBeInTheDocument()
expect(screen.queryByText('ab'.repeat(24))).not.toBeInTheDocument()
expect(await screen.findByText('Feishin')).toBeInTheDocument()
})
test('the form is empty again after a password is made', async () => {
setup([])
const name = await screen.findByLabelText('Name of the app or device')
await userEvent.type(name, 'Phone')
await userEvent.click(screen.getByRole('button', { name: 'Make password' }))
await screen.findByRole('region', { name: 'Password for Phone' })
expect(screen.getByLabelText('Name of the app or device')).toHaveValue('')
})
test('copying the password puts it on the clipboard', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
setup([])
await userEvent.type(await screen.findByLabelText('Name of the app or device'), 'Phone')
await userEvent.click(screen.getByRole('button', { name: 'Make password' }))
await userEvent.click(await screen.findByRole('button', { name: 'Copy password' }))
expect(writeText).toHaveBeenCalledWith('ab'.repeat(24))
})
test('taking back a password removes the device from the list', async () => {
const { calls } = setup([phone, laptop])
await userEvent.click(await screen.findByRole('button', { name: 'Remove Phone' }))
expect(await screen.findByText('Laptop')).toBeInTheDocument()
expect(screen.queryByText('Phone')).not.toBeInTheDocument()
expect(calls.some((c) => c.key === 'DELETE /api/v1/me/devices/2')).toBe(true)
})
test('a name that is refused says why, and a full list says to remove one', async () => {
setup([], { 'POST /api/v1/me/devices': () => apiError(409, 'too_many_devices', 'x') })
await userEvent.type(await screen.findByLabelText('Name of the app or device'), 'Phone')
await userEvent.click(screen.getByRole('button', { name: 'Make password' }))
expect(await screen.findByRole('alert')).toHaveTextContent('You have 20 devices. Remove one first.')
})
test('a list that cannot be read has a way to try again', async () => {
let fail = true
setup([], { 'GET /api/v1/me/devices': () => (fail ? apiError(500, 'internal', 'x') : { devices: [laptop] }) })
const retry = await screen.findByRole('button', { name: 'Try again' })
fail = false
await userEvent.click(retry)
expect(await screen.findByText('Laptop')).toBeInTheDocument()
})

View file

@ -0,0 +1,128 @@
import { useState, type FormEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { ApiError } from '@/api/client'
import { useCreateDevice, useDeleteDevice, useDevices, type CreatedDevice } from '@/api/devices'
import { useSession } from '@/auth/session'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { errorMessageKey } from '@/i18n'
/** One line of the details an app asks for: what it is called there, and the value to type. */
function Detail({ label, value }: { label: string; value: string }) {
return (
<div className="flex flex-col gap-0.5">
<dt className="text-sm text-muted-foreground">{label}</dt>
<dd className="break-all font-semibold select-all">{value}</dd>
</div>
)
}
/** The password that was just made, with what to type in the app. It is shown here once and never again. */
function NewPassword({ device, onDone }: { device: CreatedDevice; onDone: () => void }) {
const { t } = useTranslation()
const { user } = useSession()
const [copied, setCopied] = useState(false)
function copy() {
void navigator.clipboard?.writeText(device.secret).then(() => setCopied(true), () => undefined)
}
return (
<section aria-label={t('devices.passwordFor', { name: device.name })} className="flex max-w-xl flex-col gap-4">
<p className="font-semibold">{t('devices.once')}</p>
<dl className="flex flex-col gap-3">
<Detail label={t('devices.server')} value={window.location.origin} />
<Detail label={t('devices.username')} value={user?.email ?? ''} />
<Detail label={t('devices.password')} value={device.secret} />
</dl>
<div className="flex flex-wrap gap-3">
<Button onClick={copy}>{copied ? t('devices.copied') : t('devices.copy')}</Button>
<Button variant="outline" onClick={onDone}>
{t('devices.done')}
</Button>
</div>
</section>
)
}
/**
* The passwords for other apps. Each app gets its own, shown once when it is made, so that one can be taken back
* without the others. A device password opens the music of this server in that app and nothing else.
*/
export default function DevicesBlock() {
const { t, i18n } = useTranslation()
const devices = useDevices()
const create = useCreateDevice()
const remove = useDeleteDevice()
const [name, setName] = useState('')
const [made, setMade] = useState<CreatedDevice | null>(null)
function submit(event: FormEvent) {
event.preventDefault()
create.mutate(name.trim(), {
onSuccess: (device) => {
setName('')
setMade(device)
},
})
}
if (devices.isError) return <ErrorMessage error={devices.error} onRetry={() => void devices.refetch()} />
if (devices.isPending) return <Loading />
const when = (iso: string) => new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium' }).format(new Date(iso))
const error = create.error ?? remove.error
return (
<div className="flex max-w-xl flex-col gap-6">
<p className="text-muted-foreground">{t('devices.intro')}</p>
{made && <NewPassword device={made} onDone={() => setMade(null)} />}
{devices.data.length === 0 ? (
!made && <EmptyMessage>{t('devices.none')}</EmptyMessage>
) : (
<ul aria-label={t('devices.list')} className="flex flex-col gap-3">
{devices.data.map((d) => (
<li key={d.id} className="flex items-center justify-between gap-4">
<div className="flex min-w-0 flex-col">
<span className="truncate font-semibold">{d.name}</span>
<span className="text-sm text-muted-foreground">
{d.last_used_at ? t('devices.lastUsed', { date: when(d.last_used_at) }) : t('devices.neverUsed')}
</span>
</div>
<Button variant="outline" aria-label={t('devices.removeNamed', { name: d.name })} disabled={remove.isPending} onClick={() => remove.mutate(d.id)}>
{t('devices.remove')}
</Button>
</li>
))}
</ul>
)}
<form onSubmit={submit} className="flex flex-col gap-3">
<div className="flex flex-col gap-2">
<Label htmlFor="device-name">{t('devices.name')}</Label>
<Input
id="device-name"
autoComplete="off"
maxLength={60}
placeholder={t('devices.namePlaceholder')}
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</div>
{error && (
<p role="alert" className="text-sm text-destructive">
{t(errorMessageKey(error instanceof ApiError ? error.code : 'unknown'))}
</p>
)}
<Button type="submit" className="self-start" disabled={create.isPending || name.trim() === ''}>
{create.isPending ? t('devices.making') : t('devices.make')}
</Button>
</form>
</div>
)
}

View file

@ -84,6 +84,27 @@
"connectedHelp": "Each song that counts as a listen is posted as an unlisted status with #NowPlaying. Music of a friend is never posted.",
"disconnect": "Disconnect"
},
"devices": {
"intro": "Make a password for each of your other apps that plays music from this server, like Feishin, Symfonium or Amperfy. It opens the music of this server in that app and nothing else: it cannot sign in here or change your account. You can take it back at any time.",
"none": "No app has a password yet.",
"list": "Your devices",
"lastUsed": "Last used {{date}}",
"neverUsed": "Never used",
"remove": "Remove",
"removeNamed": "Remove {{name}}",
"name": "Name of the app or device",
"namePlaceholder": "Phone",
"make": "Make password",
"making": "Making…",
"passwordFor": "Password for {{name}}",
"once": "This is the only time the password is shown. Copy it into the app now.",
"server": "Server",
"username": "Username",
"password": "Password",
"copy": "Copy password",
"copied": "Copied",
"done": "Done"
},
"settings": {
"account": "Account",
"admin": "Admin",
@ -116,7 +137,8 @@
"passwordLength": "The new password needs 8 to 256 characters.",
"currentPasswordWrong": "The current password is wrong.",
"changePassword": "Change password",
"about": "About"
"about": "About",
"devices": "Apps and devices"
},
"admin": {
"title": "Admin",
@ -809,7 +831,10 @@
"mix_empty": "This mix has no songs to keep.",
"smart_playlist_not_found": "This smart playlist does not exist.",
"suggested_not_found": "This suggested smart playlist does not exist.",
"smart_playlist_empty": "These rules give no songs to keep."
"smart_playlist_empty": "These rules give no songs to keep.",
"invalid_name": "The name needs 1 to 60 characters.",
"too_many_devices": "You have 20 devices. Remove one first.",
"device_not_found": "That device is already removed."
},
"spotify": {
"intro": "Bring in your listening history and your playlists from Spotify, so that your mixes, Discover and smart playlists know what you listened to before. Ask Spotify for your data (Account, Privacy, “Extended streaming history” and “Account data”), then choose the zip it sends you, or the JSON files inside it.",

View file

@ -84,6 +84,27 @@
"connectedHelp": "Ogni brano che conta come ascolto viene pubblicato come post non in elenco con #NowPlaying. La musica di un amico non viene mai pubblicata.",
"disconnect": "Scollega"
},
"devices": {
"intro": "Crea una password per ognuna delle altre app che riproduce la musica di questo server, come Feishin, Symfonium o Amperfy. Apre la musica di questo server in quell'app e nient'altro: non può accedere qui né cambiare il tuo account. Puoi ritirarla quando vuoi.",
"none": "Nessuna app ha ancora una password.",
"list": "I tuoi dispositivi",
"lastUsed": "Ultimo uso {{date}}",
"neverUsed": "Mai usata",
"remove": "Rimuovi",
"removeNamed": "Rimuovi {{name}}",
"name": "Nome dell'app o del dispositivo",
"namePlaceholder": "Telefono",
"make": "Crea password",
"making": "Creo…",
"passwordFor": "Password per {{name}}",
"once": "Questa è l'unica volta che la password viene mostrata. Copiala subito nell'app.",
"server": "Server",
"username": "Nome utente",
"password": "Password",
"copy": "Copia password",
"copied": "Copiata",
"done": "Fatto"
},
"settings": {
"account": "Account",
"admin": "Admin",
@ -116,7 +137,8 @@
"passwordLength": "La nuova password deve avere da 8 a 256 caratteri.",
"currentPasswordWrong": "La password attuale è sbagliata.",
"changePassword": "Cambia password",
"about": "Informazioni"
"about": "Informazioni",
"devices": "App e dispositivi"
},
"admin": {
"title": "Admin",
@ -809,7 +831,10 @@
"mix_empty": "Questo mix non ha brani da salvare.",
"smart_playlist_not_found": "Questa playlist smart non esiste.",
"suggested_not_found": "Questa playlist smart suggerita non esiste.",
"smart_playlist_empty": "Con queste regole non ci sono brani da salvare."
"smart_playlist_empty": "Con queste regole non ci sono brani da salvare.",
"invalid_name": "Il nome deve avere da 1 a 60 caratteri.",
"too_many_devices": "Hai già 20 dispositivi. Rimuovine uno.",
"device_not_found": "Quel dispositivo è già stato rimosso."
},
"spotify": {
"intro": "Porta qui la cronologia di ascolto e le playlist di Spotify, così i tuoi mix, Discover e le playlist smart sanno cosa ascoltavi prima. Chiedi a Spotify i tuoi dati (Account, Privacy, «Cronologia di streaming estesa» e «Dati dell'account»), poi scegli lo zip che ti manda, oppure i file JSON che contiene.",

Some files were not shown because too many files have changed in this diff Show more