From 010f2e5057dcfde91ec67e68297987ddc50943f5 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Mon, 16 Nov 2026 09:15:25 +0100 Subject: [PATCH] feat: a password for each app or device A person can make a password for each app that connects to their server, in Settings, Apps and devices. The secret is shown once, can be taken back, and is for the music API of other apps only: it cannot sign in or change the account. Secrets are kept sealed (AES-256-GCM, key derived from the jwt secret) because token login needs them in clear, and a hash finds a device by its key. - migration 0034 device_passwords (sqlite, postgres) - internal/devices service, storage repo - GET/POST /me/devices, DELETE /me/devices/{id}, in the OpenAPI spec - Settings section with copy and remove --- cmd/sondad/main.go | 2 + internal/api/http/api_test.go | 2 + internal/api/http/contract_test.go | 16 ++ internal/api/http/devices_test.go | 102 +++++++++++ internal/api/http/handlers_devices.go | 105 +++++++++++ internal/api/http/router.go | 5 + internal/api/openapi/openapi.yaml | 103 +++++++++++ internal/devices/devices.go | 173 ++++++++++++++++++ internal/devices/devices_test.go | 148 +++++++++++++++ internal/storage/devices.go | 72 ++++++++ internal/storage/devices_test.go | 82 +++++++++ internal/storage/storage_test.go | 4 +- migrations/postgres/0034_device_passwords.sql | 16 ++ migrations/sqlite/0034_device_passwords.sql | 16 ++ web/src/api/devices.ts | 31 ++++ web/src/api/schema.d.ts | 170 +++++++++++++++++ web/src/components/DevicesBlock.test.tsx | 125 +++++++++++++ web/src/components/DevicesBlock.tsx | 128 +++++++++++++ web/src/i18n/locales/en.json | 29 ++- web/src/i18n/locales/it.json | 29 ++- web/src/pages/SettingsPage.test.tsx | 16 +- web/src/pages/SettingsPage.tsx | 5 + 22 files changed, 1368 insertions(+), 11 deletions(-) create mode 100644 internal/api/http/devices_test.go create mode 100644 internal/api/http/handlers_devices.go create mode 100644 internal/devices/devices.go create mode 100644 internal/devices/devices_test.go create mode 100644 internal/storage/devices.go create mode 100644 internal/storage/devices_test.go create mode 100644 migrations/postgres/0034_device_passwords.sql create mode 100644 migrations/sqlite/0034_device_passwords.sql create mode 100644 web/src/api/devices.ts create mode 100644 web/src/components/DevicesBlock.test.tsx create mode 100644 web/src/components/DevicesBlock.tsx diff --git a/cmd/sondad/main.go b/cmd/sondad/main.go index 3daf6ef..3856e8f 100644 --- a/cmd/sondad/main.go +++ b/cmd/sondad/main.go @@ -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)), diff --git a/internal/api/http/api_test.go b/internal/api/http/api_test.go index 33a6d76..2e82e6a 100644 --- a/internal/api/http/api_test.go +++ b/internal/api/http/api_test.go @@ -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) diff --git a/internal/api/http/contract_test.go b/internal/api/http/contract_test.go index 6b9637b..a36f0b8 100644 --- a/internal/api/http/contract_test.go +++ b/internal/api/http/contract_test.go @@ -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") diff --git a/internal/api/http/devices_test.go b/internal/api/http/devices_test.go new file mode 100644 index 0000000..01a5ce8 --- /dev/null +++ b/internal/api/http/devices_test.go @@ -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) + } +} diff --git a/internal/api/http/handlers_devices.go b/internal/api/http/handlers_devices.go new file mode 100644 index 0000000..e61f6a5 --- /dev/null +++ b/internal/api/http/handlers_devices.go @@ -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) + } +} diff --git a/internal/api/http/router.go b/internal/api/http/router.go index 2be2fa1..0cc6d5b 100644 --- a/internal/api/http/router.go +++ b/internal/api/http/router.go @@ -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) diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml index 07d8ec0..20cf518 100644 --- a/internal/api/openapi/openapi.yaml +++ b/internal/api/openapi/openapi.yaml @@ -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 diff --git a/internal/devices/devices.go b/internal/devices/devices.go new file mode 100644 index 0000000..01aa66a --- /dev/null +++ b/internal/devices/devices.go @@ -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} +} diff --git a/internal/devices/devices_test.go b/internal/devices/devices_test.go new file mode 100644 index 0000000..4d676fa --- /dev/null +++ b/internal/devices/devices_test.go @@ -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) + } +} diff --git a/internal/storage/devices.go b/internal/storage/devices.go new file mode 100644 index 0000000..4932b9c --- /dev/null +++ b/internal/storage/devices.go @@ -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 +} diff --git a/internal/storage/devices_test.go b/internal/storage/devices_test.go new file mode 100644 index 0000000..6c83afc --- /dev/null +++ b/internal/storage/devices_test.go @@ -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) + } + }) +} diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index f5ccf3d..a3bd54e 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -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) } }) } diff --git a/migrations/postgres/0034_device_passwords.sql b/migrations/postgres/0034_device_passwords.sql new file mode 100644 index 0000000..2bf37b5 --- /dev/null +++ b/migrations/postgres/0034_device_passwords.sql @@ -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); diff --git a/migrations/sqlite/0034_device_passwords.sql b/migrations/sqlite/0034_device_passwords.sql new file mode 100644 index 0000000..2a9da7b --- /dev/null +++ b/migrations/sqlite/0034_device_passwords.sql @@ -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); diff --git a/web/src/api/devices.ts b/web/src/api/devices.ts new file mode 100644 index 0000000..5d1e567 --- /dev/null +++ b/web/src/api/devices.ts @@ -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('/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('/me/devices', { name }), + onSuccess: () => client.invalidateQueries({ queryKey: KEY }), + }) +} + +export function useDeleteDevice() { + const client = useQueryClient() + return useMutation({ + mutationFn: (id: number) => api.del(`/me/devices/${id}`), + onSuccess: () => client.invalidateQueries({ queryKey: KEY }), + }) +} diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index cc7374f..fe194d0 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -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?: { diff --git a/web/src/components/DevicesBlock.test.tsx b/web/src/components/DevicesBlock.test.tsx new file mode 100644 index 0000000..df469ac --- /dev/null +++ b/web/src/components/DevicesBlock.test.tsx @@ -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( + + + , + ) + 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() +}) diff --git a/web/src/components/DevicesBlock.tsx b/web/src/components/DevicesBlock.tsx new file mode 100644 index 0000000..fc21ec2 --- /dev/null +++ b/web/src/components/DevicesBlock.tsx @@ -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 ( +
+
{label}
+
{value}
+
+ ) +} + +/** 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 ( +
+

{t('devices.once')}

+
+ + + +
+
+ + +
+
+ ) +} + +/** + * 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(null) + + function submit(event: FormEvent) { + event.preventDefault() + create.mutate(name.trim(), { + onSuccess: (device) => { + setName('') + setMade(device) + }, + }) + } + + if (devices.isError) return void devices.refetch()} /> + if (devices.isPending) return + + const when = (iso: string) => new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium' }).format(new Date(iso)) + const error = create.error ?? remove.error + + return ( +
+

{t('devices.intro')}

+ + {made && setMade(null)} />} + + {devices.data.length === 0 ? ( + !made && {t('devices.none')} + ) : ( +
    + {devices.data.map((d) => ( +
  • +
    + {d.name} + + {d.last_used_at ? t('devices.lastUsed', { date: when(d.last_used_at) }) : t('devices.neverUsed')} + +
    + +
  • + ))} +
+ )} + +
+
+ + setName(e.target.value)} + required + /> +
+ {error && ( +

+ {t(errorMessageKey(error instanceof ApiError ? error.code : 'unknown'))} +

+ )} + +
+
+ ) +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 75dbe76..57e7c28 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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.", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 1a9784c..40c786a 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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.", diff --git a/web/src/pages/SettingsPage.test.tsx b/web/src/pages/SettingsPage.test.tsx index edd47b8..f7ed293 100644 --- a/web/src/pages/SettingsPage.test.tsx +++ b/web/src/pages/SettingsPage.test.tsx @@ -26,7 +26,7 @@ function renderSettings() { } beforeEach(async () => { - mockFetch({ 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }), 'GET /api/v1/me/mastodon': () => ({ connected: false }), 'GET /api/v1/version': () => ({ version: '0.1.0', revision: '69c85a7' }) }) + mockFetch({ 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }), 'GET /api/v1/me/mastodon': () => ({ connected: false }), 'GET /api/v1/me/devices': () => ({ devices: [] }), 'GET /api/v1/version': () => ({ version: '0.1.0', revision: '69c85a7' }) }) vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') await initI18n() initTheme() @@ -119,7 +119,7 @@ test('Discover has its own group with the switch for using your listening, off u }) test('a new password of seven characters is refused here, with no request', async () => { - const { calls } = mockFetch({}) + const { calls } = mockFetch({ 'GET /api/v1/me/devices': () => ({ devices: [] }) }) renderSettings() await changePassword('old-password', '1234567') expect(await screen.findByRole('alert')).toHaveTextContent('The new password needs 8 to 256 characters.') @@ -127,7 +127,7 @@ test('a new password of seven characters is refused here, with no request', asyn }) test('a new password longer than 256 bytes is refused here, with no request', async () => { - const { calls } = mockFetch({}) + const { calls } = mockFetch({ 'GET /api/v1/me/devices': () => ({ devices: [] }) }) renderSettings() await userEvent.type(screen.getByLabelText('Current password'), 'old-password') await userEvent.click(screen.getByLabelText('New password')) @@ -153,7 +153,7 @@ test('a changed password signs this session out, because the server ends every s }) test('a wrong current password is explained and keeps the session', async () => { - mockFetch({ 'POST /api/v1/auth/password': () => apiError(403, 'invalid_credentials') }) + mockFetch({ 'GET /api/v1/me/devices': () => ({ devices: [] }), 'POST /api/v1/auth/password': () => apiError(403, 'invalid_credentials') }) renderSettings() await changePassword('not-my-password', 'new-password-1') expect(await screen.findByRole('alert')).toHaveTextContent('The current password is wrong.') @@ -161,7 +161,7 @@ test('a wrong current password is explained and keeps the session', async () => }) test('a password change that fails for another reason says so', async () => { - mockFetch({ 'POST /api/v1/auth/password': () => apiError(500, 'internal') }) + mockFetch({ 'GET /api/v1/me/devices': () => ({ devices: [] }), 'POST /api/v1/auth/password': () => apiError(500, 'internal') }) renderSettings() await changePassword('old-password', 'new-password-1') expect(await screen.findByRole('alert')).toHaveTextContent('Something went wrong. Try again.') @@ -246,3 +246,9 @@ test('the page says which version of Sonda this is', async () => { renderSettings() expect(await screen.findByText('Version 0.1.0 · 69c85a7')).toBeInTheDocument() }) + +test('it has a section for the passwords of other apps', async () => { + renderSettings() + expect(await screen.findByRole('heading', { name: 'Apps and devices' })).toBeInTheDocument() + expect(await screen.findByLabelText('Name of the app or device')).toBeInTheDocument() +}) diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx index 77382b9..82f3769 100644 --- a/web/src/pages/SettingsPage.tsx +++ b/web/src/pages/SettingsPage.tsx @@ -5,6 +5,7 @@ import { api, ApiError } from '@/api/client' import { logout, useSession } from '@/auth/session' import ChoiceGroup from '@/components/ChoiceGroup' import ListeningSwitch from '@/components/ListeningSwitch' +import DevicesBlock from '@/components/DevicesBlock' import MastodonBlock from '@/components/MastodonBlock' import Section from '@/components/Section' import VersionLabel from '@/components/VersionLabel' @@ -185,6 +186,10 @@ export default function SettingsPage() { +
+ +
+

{t('settings.importHint')}

-- 2.54.0