From b26cd02791da4265992b7556ec0afb94d8f66f89 Mon Sep 17 00:00:00 2001 From: Jan Unterbrink Date: Sun, 22 Nov 2026 22:13:19 +0100 Subject: [PATCH 1/7] refactor: layer into domain, adapters and transports; fix token refresh race - internal/account and internal/playback hold the domain: typed values (Profile, InviteCode, URI, DeviceID, Kind), the rules (invites, state + PKCE login, device selection, actionable errors) and the ports they need. - internal/spotify (Web API, OAuth) and internal/filestore (JSON files) implement the ports; wire and file formats are unexported there. - internal/mcpserver and internal/web depend only on small interfaces they define; web no longer touches oauth2 or storage. - internal/config parses env into typed values; main only wires. Race fix: the token refresh now runs inside Tokens.UpdateConnection, which reads, refreshes and writes under one lock (mutex + flock on the data dir). A login during a refresh waits and wins instead of being overwritten by the old account's token, and the invite command's process can no longer lose an invite written concurrently. A 401 invalidates the token and retries once. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 +- cmd/spotify-mcp/main.go | 159 +++------- internal/account/account.go | 149 +++++++++ internal/account/account_test.go | 218 +++++++++++++ internal/account/invite.go | 36 +++ internal/account/option.go | 21 ++ internal/account/service.go | 216 +++++++++++++ internal/account/tokensource.go | 80 +++++ internal/account/tokensource_test.go | 143 +++++++++ internal/config/config.go | 104 ++++++ internal/config/config_test.go | 41 +++ internal/filestore/filestore.go | 289 +++++++++++++++++ internal/filestore/filestore_test.go | 162 ++++++++++ internal/filestore/lock_other.go | 7 + internal/filestore/lock_unix.go | 23 ++ internal/mcpserver/mcpserver.go | 263 +++++++++++++++ internal/mcpserver/mcpserver_test.go | 156 +++++++++ internal/playback/playback.go | 145 +++++++++ internal/playback/playback_test.go | 130 ++++++++ internal/playback/service.go | 196 ++++++++++++ internal/spotify/api.go | 145 +++++++++ internal/spotify/auth.go | 129 ++++++++ internal/spotify/client.go | 459 --------------------------- internal/spotify/client_test.go | 191 ----------- internal/spotify/player.go | 223 +++++++++++++ internal/spotify/spotify_test.go | 239 ++++++++++++++ internal/store/store.go | 238 -------------- internal/store/store_test.go | 90 ------ internal/tools/tools.go | 294 ----------------- internal/tools/tools_test.go | 169 ---------- internal/web/page.html | 42 +++ internal/web/web.go | 405 +++++++---------------- internal/web/web_test.go | 321 +++++++++---------- 33 files changed, 3497 insertions(+), 2004 deletions(-) create mode 100644 internal/account/account.go create mode 100644 internal/account/account_test.go create mode 100644 internal/account/invite.go create mode 100644 internal/account/option.go create mode 100644 internal/account/service.go create mode 100644 internal/account/tokensource.go create mode 100644 internal/account/tokensource_test.go create mode 100644 internal/config/config.go create mode 100644 internal/config/config_test.go create mode 100644 internal/filestore/filestore.go create mode 100644 internal/filestore/filestore_test.go create mode 100644 internal/filestore/lock_other.go create mode 100644 internal/filestore/lock_unix.go create mode 100644 internal/mcpserver/mcpserver.go create mode 100644 internal/mcpserver/mcpserver_test.go create mode 100644 internal/playback/playback.go create mode 100644 internal/playback/playback_test.go create mode 100644 internal/playback/service.go create mode 100644 internal/spotify/api.go create mode 100644 internal/spotify/auth.go delete mode 100644 internal/spotify/client.go delete mode 100644 internal/spotify/client_test.go create mode 100644 internal/spotify/player.go create mode 100644 internal/spotify/spotify_test.go delete mode 100644 internal/store/store.go delete mode 100644 internal/store/store_test.go delete mode 100644 internal/tools/tools.go delete mode 100644 internal/tools/tools_test.go create mode 100644 internal/web/page.html diff --git a/README.md b/README.md index 387ff60..64db157 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ All settings come from environment variables; see [`.env.example`](.env.example) - **The MCP endpoint has no authentication of its own.** Anyone who can reach port 8000 can control the connected account's playback. Run it behind a gateway that checks API keys or OAuth (e.g. [agentgateway](https://agentgateway.dev)), and restrict the port (the chart has an optional NetworkPolicy). - **Least privilege at Spotify:** the server asks only for `user-read-playback-state`, `user-modify-playback-state` and `user-read-currently-playing`. It can't read playlists, the library or the e-mail address. -- **Tokens:** the refresh token lives in `DATA_DIR/tokens/.json` with mode 0600. When Spotify rotates it, the new one is written before it's used, so restarts keep working. Nothing is logged. +- **Tokens:** the refresh token lives in `DATA_DIR/tokens/.json` with mode 0600. A refresh reads, refreshes and writes the token under one lock (a mutex plus `flock`, which also covers the `invite` command's process), so a rotated refresh token is on disk before it's used and a login during a refresh is never overwritten. Nothing is logged. - **Invites** are 256-bit random codes. Only their SHA-256 is stored; each works once and expires. - **Login:** OAuth authorization code flow with PKCE and a `state` tied to the browser by a cookie, so a leaked callback URL can't be replayed in another browser. Cross-site form posts are rejected, and pages send no `Referer`. - **Container:** static binary on `scratch`, non-root, read-only root filesystem, no capabilities, no Kubernetes API token. @@ -106,6 +106,22 @@ Found a security problem? Please open a private security advisory on GitHub rath ## Development +The code is layered so the rules can be tested without HTTP, files or Spotify: + +```mermaid +flowchart LR + main["cmd/spotify-mcp (wiring)"] --> mcpserver & web & config + mcpserver -- "Player interface" --> playback + web -- "Connector interface" --> account + playback -- "Spotify port" --> spotify + account -- "Tokens / Invites ports" --> filestore + account -- "OAuth / Identity ports" --> spotify +``` + +- `internal/playback` and `internal/account` are the domain: typed values (`URI`, `DeviceID`, `Profile`, `InviteCode`), the rules, and the ports (interfaces) they need. +- `internal/spotify` (Web API + OAuth) and `internal/filestore` (JSON files) implement the ports. Wire and file formats stay unexported in them. +- `internal/mcpserver` and `internal/web` are the transports. Each depends on a small interface it defines itself. + ```bash go test -race ./... go vet ./... diff --git a/cmd/spotify-mcp/main.go b/cmd/spotify-mcp/main.go index 7241af2..9080f3f 100644 --- a/cmd/spotify-mcp/main.go +++ b/cmd/spotify-mcp/main.go @@ -3,6 +3,7 @@ // // spotify-mcp [serve] run the MCP server and the connect page // spotify-mcp invite [-ttl] print a one-time link that connects an account +// spotify-mcp version package main import ( @@ -14,89 +15,30 @@ import ( "net/http" "os" "os/signal" - "strings" "syscall" "time" - "github.com/modelcontextprotocol/go-sdk/mcp" - "golang.org/x/oauth2" - + "github.com/subpathdev/spotify-mcp/internal/account" + "github.com/subpathdev/spotify-mcp/internal/config" + "github.com/subpathdev/spotify-mcp/internal/filestore" + "github.com/subpathdev/spotify-mcp/internal/mcpserver" + "github.com/subpathdev/spotify-mcp/internal/playback" "github.com/subpathdev/spotify-mcp/internal/spotify" - "github.com/subpathdev/spotify-mcp/internal/store" - "github.com/subpathdev/spotify-mcp/internal/tools" "github.com/subpathdev/spotify-mcp/internal/web" ) +// version is set at build time. var version = "dev" -type config struct { - clientID string - clientSecret string - redirectURI string - publicURL string - dataDir string - profile string - mcpAddr string - webAddr string -} - -func env(key, def string) string { - if v := strings.TrimSpace(os.Getenv(key)); v != "" { - return v - } - return def -} - -func loadConfig(needSecrets bool) (config, error) { - c := config{ - clientID: env("SPOTIFY_CLIENT_ID", ""), - clientSecret: env("SPOTIFY_CLIENT_SECRET", ""), - redirectURI: env("SPOTIFY_REDIRECT_URI", ""), - publicURL: env("PUBLIC_URL", ""), - dataDir: env("DATA_DIR", "/data"), - profile: env("PROFILE", "default"), - mcpAddr: env("MCP_ADDR", ":8000"), - webAddr: env("WEB_ADDR", ":8080"), - } - var missing []string - if c.redirectURI == "" { - missing = append(missing, "SPOTIFY_REDIRECT_URI") - } - if needSecrets { - if c.clientID == "" { - missing = append(missing, "SPOTIFY_CLIENT_ID") - } - if c.clientSecret == "" { - missing = append(missing, "SPOTIFY_CLIENT_SECRET") - } - } - if len(missing) > 0 { - return c, fmt.Errorf("missing environment variables: %s (see .env.example)", strings.Join(missing, ", ")) - } - if !strings.HasSuffix(c.redirectURI, "/callback") { - return c, errors.New("SPOTIFY_REDIRECT_URI must end in /callback, e.g. https://spotify.example.com/callback") - } - if c.publicURL == "" { - c.publicURL = strings.TrimSuffix(c.redirectURI, "/callback") - } - c.publicURL = strings.TrimRight(c.publicURL, "/") - if !store.ValidProfile(c.profile) { - return c, fmt.Errorf("PROFILE %q: use lower-case letters, digits and dashes", c.profile) - } - return c, nil -} - func main() { - log := slog.New(slog.NewJSONHandler(os.Stderr, nil)) - cmd := "serve" - args := os.Args[1:] - if len(args) > 0 && !strings.HasPrefix(args[0], "-") { + cmd, args := "serve", os.Args[1:] + if len(args) > 0 && args[0] != "" && args[0][0] != '-' { cmd, args = args[0], args[1:] } var err error switch cmd { case "serve": - err = serve(log) + err = serve(slog.New(slog.NewJSONHandler(os.Stderr, nil))) case "invite": err = invite(args) case "version": @@ -116,67 +58,68 @@ func invite(args []string) error { if err := fs.Parse(args); err != nil { return err } - c, err := loadConfig(false) + cfg, err := config.Load(os.Getenv) if err != nil { return err } - st, err := store.Open(c.dataDir) + store, err := filestore.Open(cfg.DataDir) if err != nil { return err } - code, err := st.CreateInvite(c.profile, *ttl) + code, expires, err := account.NewInviter(store).CreateInvite(context.Background(), cfg.Profile, *ttl) if err != nil { return err } - fmt.Printf("%s/connect?invite=%s\n", c.publicURL, code) - fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", c.profile, time.Now().Add(*ttl).Format("2006-01-02 15:04 MST")) + fmt.Println(cfg.InviteURL(code)) + fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", cfg.Profile, expires.Format("2006-01-02 15:04 MST")) return nil } func serve(log *slog.Logger) error { - c, err := loadConfig(true) + cfg, err := config.Load(os.Getenv) if err != nil { return err } - st, err := store.Open(c.dataDir) - if err != nil { + if err := cfg.RequireCredentials(); err != nil { return err } - oc := &oauth2.Config{ - ClientID: c.clientID, - ClientSecret: c.clientSecret, - Endpoint: spotify.Endpoint, - RedirectURL: c.redirectURI, - Scopes: spotify.Scopes, - } - client := spotify.NewClient(oc, st, c.profile, nil) - if _, err := st.Token(c.profile); errors.Is(err, store.ErrNotFound) { - log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", c.profile) + store, err := filestore.Open(cfg.DataDir) + if err != nil { + return err } - srv := mcp.NewServer(&mcp.Implementation{Name: "spotify-mcp", Title: "Spotify", Version: version}, &mcp.ServerOptions{ - Instructions: "Controls Spotify playback on the user's devices (Spotify Connect). Use devices to find a device name, search for URIs, and play/pause/resume/next/previous/transfer to control playback.", + oauth := spotify.NewOAuth(spotify.OAuthConfig{ + ClientID: cfg.ClientID, ClientSecret: cfg.ClientSecret, RedirectURL: cfg.RedirectURL.String(), }) - tools.Register(srv, client) - mcpMux := http.NewServeMux() - mcpMux.Handle("/mcp", mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, &mcp.StreamableHTTPOptions{ - Logger: log, - SessionTimeout: 30 * time.Minute, - })) - mcpMux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok\n")) }) + api := spotify.NewAPI(spotify.DefaultAPIURL, nil) + tokens := account.NewTokenSource(store, oauth, cfg.Profile) + player := playback.NewService(spotify.NewPlayer(api, tokens)) + accounts := account.NewService(store, store, oauth, api) - wh := &web.Handler{ - OAuth: oc, - Store: st, - Log: log, - MeURL: "https://api.spotify.com/v1/me", - OnConnect: func(string) { client.Forget() }, + if _, err := store.Connection(context.Background(), cfg.Profile); errors.Is(err, account.ErrNotFound) { + log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", cfg.Profile) } servers := []*http.Server{ - {Addr: c.mcpAddr, Handler: mcpMux, ReadHeaderTimeout: 10 * time.Second}, - {Addr: c.webAddr, Handler: wh.Routes(), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second}, - } + { + Addr: cfg.MCPAddr, + Handler: mcpserver.Handler(mcpserver.NewServer(player, version), log), + ReadHeaderTimeout: 10 * time.Second, + }, + { + Addr: cfg.WebAddr, + Handler: web.NewHandler(accounts, log), + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, + }, + } + log.Info("spotify-mcp started", "version", version, "profile", cfg.Profile, "connect_url", cfg.PublicURL.JoinPath("connect").String()) + return run(log, servers) +} + +// run serves until SIGINT/SIGTERM or a server fails, then shuts all down. +func run(log *slog.Logger, servers []*http.Server) error { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() errc := make(chan error, len(servers)) @@ -184,11 +127,11 @@ func serve(log *slog.Logger) error { go func() { log.Info("listening", "addr", s.Addr) if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { - errc <- err + errc <- fmt.Errorf("serve %s: %w", s.Addr, err) } }() } - log.Info("spotify-mcp started", "version", version, "profile", c.profile, "connect_url", c.publicURL+"/connect") + var err error select { case <-ctx.Done(): case err = <-errc: @@ -196,7 +139,9 @@ func serve(log *slog.Logger) error { shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() for _, s := range servers { - _ = s.Shutdown(shutdown) + if serr := s.Shutdown(shutdown); serr != nil { + log.Warn("shutdown", "addr", s.Addr, "err", serr) + } } return err } diff --git a/internal/account/account.go b/internal/account/account.go new file mode 100644 index 0000000..fa533d4 --- /dev/null +++ b/internal/account/account.go @@ -0,0 +1,149 @@ +// Package account is the domain of connecting Spotify accounts: profiles, +// one-time invite links, the OAuth login and the stored connection. +// +// It knows nothing about HTTP, files or Spotify's wire format. Those live in +// adapters that implement the ports declared here (Tokens, Invites, OAuth, +// Identity), so the rules below can be tested on their own. +package account + +import ( + "context" + "errors" + "fmt" + "regexp" + "time" +) + +// Profile names one connected account. Phase 1 uses a single profile; the +// type exists so a sign-in system can map people to profiles later. +type Profile string + +var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) + +// ParseProfile checks a profile name. Adapters may use it in file or key +// names, so it is restricted to lower-case letters, digits and dashes. +func ParseProfile(s string) (Profile, error) { + if !profileRe.MatchString(s) { + return "", fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) + } + return Profile(s), nil +} + +// User is the Spotify account behind a connection. +type User struct { + ID string + DisplayName string +} + +// Name is what to show a person: the display name, else the account ID. +func (u User) Name() string { + if u.DisplayName != "" { + return u.DisplayName + } + return u.ID +} + +// Token is an OAuth token pair as Spotify issues it. +type Token struct { + AccessToken string + RefreshToken string // empty when Spotify keeps the old one + Expiry time.Time +} + +// expiryDelta refreshes a little early, so a token doesn't expire in flight. +const expiryDelta = 30 * time.Second + +// Connection is what is stored per profile. +type Connection struct { + Token Token + User User + ConnectedAt time.Time +} + +func (c Connection) accessValid(now time.Time) bool { + return c.Token.AccessToken != "" && now.Add(expiryDelta).Before(c.Token.Expiry) +} + +// InviteCode is the secret part of an invite link. It is only ever shown +// once; repositories see its hash. +type InviteCode string + +// InviteHash identifies an invite in a repository. +type InviteHash string + +// Invite lets whoever holds its code connect or disconnect one profile. +type Invite struct { + Hash InviteHash + Profile Profile + Expires time.Time +} + +// Errors returned by this package and by the ports' implementations. +var ( + // ErrNotFound is returned by repositories for a missing entry. + ErrNotFound = errors.New("not found") + // ErrInvalidInvite covers unknown, used and expired invites alike, so a + // caller can't tell which one it was. + ErrInvalidInvite = errors.New("invite link is invalid or has expired") + // ErrNotConnected means no account is connected to the profile, or + // Spotify revoked the access. + ErrNotConnected = errors.New("no Spotify account is connected yet: create an invite link (spotify-mcp invite) and open it to connect one") + // ErrLoginExpired means a callback doesn't belong to a login started in + // the same browser within the last few minutes. + ErrLoginExpired = errors.New("login expired or was started in another browser") + // ErrLoginCancelled means the person declined at Spotify. + ErrLoginCancelled = errors.New("login cancelled at Spotify") + // ErrTooManyLogins caps the logins waiting for a callback. + ErrTooManyLogins = errors.New("too many logins in progress") + + // ErrRevoked is returned by OAuth when the refresh token is no longer valid. + ErrRevoked = errors.New("access was revoked at Spotify") + // ErrInvalidClient is returned by OAuth when the client ID or secret is wrong. + ErrInvalidClient = errors.New("client ID or secret rejected by Spotify") + // ErrNotAllowlisted is returned by Identity when the account isn't on the + // development-mode user list of the Spotify app. + ErrNotAllowlisted = errors.New("account is not on the Spotify app's user list") +) + +// Tokens stores one Connection per profile. +type Tokens interface { + // Connection returns ErrNotFound if the profile has none. + Connection(ctx context.Context, p Profile) (Connection, error) + // SaveConnection replaces the profile's connection. + SaveConnection(ctx context.Context, p Profile, c Connection) error + // UpdateConnection reads, changes and writes the connection as one step: + // no other write to the profile may happen in between. It returns + // ErrNotFound if the profile has none, and writes nothing if fn fails. + UpdateConnection(ctx context.Context, p Profile, fn func(*Connection) error) error + // DeleteConnection forgets the profile's connection; a missing one is fine. + DeleteConnection(ctx context.Context, p Profile) error +} + +// Invites stores pending invites. +type Invites interface { + AddInvite(ctx context.Context, inv Invite) error + // Invite returns ErrNotFound for an unknown hash. + Invite(ctx context.Context, h InviteHash) (Invite, error) + // TakeInvite returns and removes an invite as one step, so it can be + // taken only once. It returns ErrNotFound for an unknown hash. + TakeInvite(ctx context.Context, h InviteHash) (Invite, error) + // PruneInvites removes invites that expired before t. + PruneInvites(ctx context.Context, t time.Time) error +} + +// OAuth is Spotify's authorization server. +type OAuth interface { + // AuthCodeURL is where the browser logs in. verifier is the PKCE verifier; + // the URL carries its S256 challenge. + AuthCodeURL(state, verifier string) string + // Exchange trades a callback code for a token. + Exchange(ctx context.Context, code, verifier string) (Token, error) + // Refresh returns a new access token, or ErrRevoked. + Refresh(ctx context.Context, refreshToken string) (Token, error) +} + +// Identity tells who an access token belongs to. +type Identity interface { + // User returns ErrNotAllowlisted for accounts the app may not serve. + User(ctx context.Context, accessToken string) (User, error) +} diff --git a/internal/account/account_test.go b/internal/account/account_test.go new file mode 100644 index 0000000..f964542 --- /dev/null +++ b/internal/account/account_test.go @@ -0,0 +1,218 @@ +package account_test + +import ( + "context" + "errors" + "net/url" + "sync" + "testing" + "time" + + "github.com/subpathdev/spotify-mcp/internal/account" + "github.com/subpathdev/spotify-mcp/internal/filestore" +) + +const profile = account.Profile("default") + +// fakeOAuth issues tokens for the code "good" and the verifier of the last +// started login. +type fakeOAuth struct { + mu sync.Mutex + verifiers map[string]string // by state + refresh func(ctx context.Context, rt string) (account.Token, error) +} + +func (f *fakeOAuth) AuthCodeURL(state, verifier string) string { + f.mu.Lock() + defer f.mu.Unlock() + if f.verifiers == nil { + f.verifiers = map[string]string{} + } + f.verifiers[state] = verifier + return "https://auth.test/authorize?" + url.Values{"state": {state}}.Encode() +} + +func (f *fakeOAuth) Exchange(_ context.Context, code, verifier string) (account.Token, error) { + f.mu.Lock() + defer f.mu.Unlock() + for _, v := range f.verifiers { + if v == verifier && code == "good" { + return account.Token{AccessToken: "a1", RefreshToken: "r1", Expiry: time.Now().Add(time.Hour)}, nil + } + } + return account.Token{}, errors.New("bad code or verifier") +} + +func (f *fakeOAuth) Refresh(ctx context.Context, rt string) (account.Token, error) { + return f.refresh(ctx, rt) +} + +type fakeIdentity struct{ err error } + +func (f fakeIdentity) User(context.Context, string) (account.User, error) { + return account.User{ID: "jan", DisplayName: "Jan"}, f.err +} + +type env struct { + store *filestore.Store + oauth *fakeOAuth + inviter *account.Inviter + svc *account.Service + now time.Time +} + +func newEnv(t *testing.T, identityErr error) *env { + t.Helper() + st, err := filestore.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + e := &env{store: st, oauth: &fakeOAuth{}, now: time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)} + clock := account.WithClock(func() time.Time { return e.now }) + e.inviter = account.NewInviter(st, clock) + e.svc = account.NewService(st, st, e.oauth, fakeIdentity{err: identityErr}, clock) + return e +} + +func (e *env) invite(t *testing.T) account.InviteCode { + t.Helper() + code, _, err := e.inviter.CreateInvite(context.Background(), profile, time.Hour) + if err != nil { + t.Fatal(err) + } + return code +} + +// start begins a login and returns the callback a browser would deliver. +func (e *env) start(t *testing.T, code account.InviteCode) account.Callback { + t.Helper() + login, err := e.svc.StartLogin(context.Background(), code) + if err != nil { + t.Fatal(err) + } + u, err := url.Parse(login.URL) + if err != nil { + t.Fatal(err) + } + return account.Callback{State: u.Query().Get("state"), Nonce: login.Nonce, Code: "good"} +} + +func TestLoginConnectsAndUsesUpInvite(t *testing.T) { + ctx := context.Background() + e := newEnv(t, nil) + code := e.invite(t) + + st, err := e.svc.Status(ctx, code) + if err != nil || st.Connected || st.Profile != profile { + t.Fatalf("status before: %+v %v", st, err) + } + user, err := e.svc.FinishLogin(ctx, e.start(t, code)) + if err != nil || user.Name() != "Jan" { + t.Fatalf("finish: %+v %v", user, err) + } + c, err := e.store.Connection(ctx, profile) + if err != nil || c.Token.RefreshToken != "r1" || c.User.ID != "jan" || !c.ConnectedAt.Equal(e.now) { + t.Fatalf("stored: %+v %v", c, err) + } + if _, err := e.svc.Status(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { + t.Fatalf("invite still valid after login: %v", err) + } +} + +func TestFinishLoginNeedsSameBrowserOnce(t *testing.T) { + ctx := context.Background() + e := newEnv(t, nil) + code := e.invite(t) + + cb := e.start(t, code) + foreign := cb + foreign.Nonce = "someone-else" + if _, err := e.svc.FinishLogin(ctx, foreign); !errors.Is(err, account.ErrLoginExpired) { + t.Fatalf("foreign browser: %v", err) + } + // The failed attempt used up the state, so the real browser must start again. + if _, err := e.svc.FinishLogin(ctx, cb); !errors.Is(err, account.ErrLoginExpired) { + t.Fatalf("replayed state: %v", err) + } + + cb = e.start(t, code) + e.now = e.now.Add(account.LoginTTL + time.Second) + if _, err := e.svc.FinishLogin(ctx, cb); !errors.Is(err, account.ErrLoginExpired) { + t.Fatalf("late callback: %v", err) + } +} + +func TestFailedLoginsKeepInvite(t *testing.T) { + ctx := context.Background() + for name, tc := range map[string]struct { + identityErr error + spotifyErr string + want error + }{ + "cancelled": {spotifyErr: "access_denied", want: account.ErrLoginCancelled}, + "not allowlisted": {identityErr: account.ErrNotAllowlisted, want: account.ErrNotAllowlisted}, + } { + t.Run(name, func(t *testing.T) { + e := newEnv(t, tc.identityErr) + code := e.invite(t) + cb := e.start(t, code) + cb.Error = tc.spotifyErr + if _, err := e.svc.FinishLogin(ctx, cb); !errors.Is(err, tc.want) { + t.Fatalf("got %v, want %v", err, tc.want) + } + if _, err := e.svc.Status(ctx, code); err != nil { + t.Fatalf("invite used up: %v", err) + } + }) + } +} + +func TestDisconnect(t *testing.T) { + ctx := context.Background() + e := newEnv(t, nil) + if _, err := e.svc.FinishLogin(ctx, e.start(t, e.invite(t))); err != nil { + t.Fatal(err) + } + code := e.invite(t) + if st, _ := e.svc.Status(ctx, code); !st.Connected || st.User.Name() != "Jan" { + t.Fatalf("status: %+v", st) + } + if p, err := e.svc.Disconnect(ctx, code); err != nil || p != profile { + t.Fatalf("disconnect: %q %v", p, err) + } + if _, err := e.store.Connection(ctx, profile); !errors.Is(err, account.ErrNotFound) { + t.Fatalf("connection kept: %v", err) + } + if _, err := e.svc.Disconnect(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { + t.Fatalf("second disconnect: %v", err) + } +} + +func TestInvites(t *testing.T) { + ctx := context.Background() + e := newEnv(t, nil) + for _, code := range []account.InviteCode{"", "unknown"} { + if _, err := e.svc.Status(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { + t.Fatalf("code %q: %v", code, err) + } + } + code := e.invite(t) + e.now = e.now.Add(2 * time.Hour) + if _, err := e.svc.StartLogin(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { + t.Fatalf("expired invite accepted: %v", err) + } + if _, _, err := e.inviter.CreateInvite(ctx, profile, 0); err == nil { + t.Fatal("zero TTL accepted") + } +} + +func TestParseProfile(t *testing.T) { + for _, s := range []string{"", "A", "../x", "a/b", "-a", string(make([]byte, 64))} { + if _, err := account.ParseProfile(s); err == nil { + t.Errorf("%q accepted", s) + } + } + if p, err := account.ParseProfile("jan-2"); err != nil || p != "jan-2" { + t.Fatalf("valid profile: %q %v", p, err) + } +} diff --git a/internal/account/invite.go b/internal/account/invite.go new file mode 100644 index 0000000..0a9316a --- /dev/null +++ b/internal/account/invite.go @@ -0,0 +1,36 @@ +package account + +import ( + "context" + "fmt" + "time" +) + +// Inviter creates one-time invite links. It needs no Spotify access, so the +// invite command can run it on its own. +type Inviter struct { + invites Invites + now func() time.Time +} + +// NewInviter returns an Inviter storing into invites. +func NewInviter(invites Invites, opts ...Option) *Inviter { + return &Inviter{invites: invites, now: apply(opts).now} +} + +// CreateInvite returns a new one-time code for p and when it expires. +func (i *Inviter) CreateInvite(ctx context.Context, p Profile, ttl time.Duration) (InviteCode, time.Time, error) { + if ttl <= 0 { + return "", time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) + } + code := InviteCode(randomString()) + now := i.now() + inv := Invite{Hash: hashInvite(code), Profile: p, Expires: now.Add(ttl)} + if err := i.invites.PruneInvites(ctx, now); err != nil { + return "", time.Time{}, fmt.Errorf("prune invites: %w", err) + } + if err := i.invites.AddInvite(ctx, inv); err != nil { + return "", time.Time{}, fmt.Errorf("save invite: %w", err) + } + return code, inv.Expires, nil +} diff --git a/internal/account/option.go b/internal/account/option.go new file mode 100644 index 0000000..474946f --- /dev/null +++ b/internal/account/option.go @@ -0,0 +1,21 @@ +package account + +import "time" + +// Option configures a Service, Inviter or TokenSource. +type Option func(*settings) + +type settings struct { + now func() time.Time +} + +// WithClock replaces time.Now, e.g. in tests. +func WithClock(now func() time.Time) Option { return func(s *settings) { s.now = now } } + +func apply(opts []Option) settings { + s := settings{now: time.Now} + for _, o := range opts { + o(&s) + } + return s +} diff --git a/internal/account/service.go b/internal/account/service.go new file mode 100644 index 0000000..a46bac9 --- /dev/null +++ b/internal/account/service.go @@ -0,0 +1,216 @@ +package account + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "sync" + "time" +) + +const ( + // LoginTTL is how long a started login waits for Spotify's callback. + LoginTTL = 10 * time.Minute + maxPending = 100 +) + +// Service runs logins and disconnects for holders of an invite. +type Service struct { + tokens Tokens + invites Invites + oauth OAuth + identity Identity + now func() time.Time + + mu sync.Mutex + pending map[string]pendingLogin // by OAuth state +} + +type pendingLogin struct { + invite InviteHash + profile Profile + verifier string + nonce string + expires time.Time +} + +// NewService returns a Service using the given ports. +func NewService(tokens Tokens, invites Invites, oauth OAuth, identity Identity, opts ...Option) *Service { + return &Service{ + tokens: tokens, invites: invites, oauth: oauth, identity: identity, + now: apply(opts).now, + pending: map[string]pendingLogin{}, + } +} + +// Status is what an invite link's page shows. +type Status struct { + Profile Profile + Connected bool + User User + ConnectedAt time.Time +} + +// Login is a started login: send the browser to URL and bind it to the login +// with Nonce (e.g. in a cookie that only the callback receives). +type Login struct { + URL string + Nonce string +} + +// Callback is what Spotify sends back, plus the browser's nonce. +type Callback struct { + State string + Nonce string + Code string + // Error is Spotify's error parameter, e.g. "access_denied". + Error string +} + +// Status reports the profile an invite belongs to and who is connected, +// without using the invite up. +func (s *Service) Status(ctx context.Context, code InviteCode) (Status, error) { + inv, err := s.checkInvite(ctx, code) + if err != nil { + return Status{}, err + } + st := Status{Profile: inv.Profile} + c, err := s.tokens.Connection(ctx, inv.Profile) + switch { + case errors.Is(err, ErrNotFound): + case err != nil: + return Status{}, fmt.Errorf("load connection: %w", err) + default: + st.Connected, st.User, st.ConnectedAt = true, c.User, c.ConnectedAt + } + return st, nil +} + +// StartLogin begins the OAuth login (state + PKCE) for an invite. The invite +// is only used up when the login succeeds. +func (s *Service) StartLogin(ctx context.Context, code InviteCode) (Login, error) { + inv, err := s.checkInvite(ctx, code) + if err != nil { + return Login{}, err + } + state, nonce, verifier := randomString(), randomString(), randomString() + now := s.now() + + s.mu.Lock() + defer s.mu.Unlock() + for k, p := range s.pending { + if now.After(p.expires) { + delete(s.pending, k) + } + } + if len(s.pending) >= maxPending { + return Login{}, ErrTooManyLogins + } + s.pending[state] = pendingLogin{ + invite: inv.Hash, profile: inv.Profile, + verifier: verifier, nonce: nonce, expires: now.Add(LoginTTL), + } + return Login{URL: s.oauth.AuthCodeURL(state, verifier), Nonce: nonce}, nil +} + +// FinishLogin completes a login: it exchanges the code, checks the account +// may use the app, uses up the invite and stores the connection, replacing +// any previous one. Each state can be finished at most once. +func (s *Service) FinishLogin(ctx context.Context, cb Callback) (User, error) { + s.mu.Lock() + p, ok := s.pending[cb.State] + delete(s.pending, cb.State) + s.mu.Unlock() + if !ok || s.now().After(p.expires) || subtle.ConstantTimeCompare([]byte(cb.Nonce), []byte(p.nonce)) != 1 { + return User{}, ErrLoginExpired + } + if cb.Error == "access_denied" { + return User{}, ErrLoginCancelled + } + if cb.Error != "" { + return User{}, fmt.Errorf("spotify refused the login: %s", cb.Error) + } + + tok, err := s.oauth.Exchange(ctx, cb.Code, p.verifier) + if err != nil { + return User{}, fmt.Errorf("exchange code: %w", err) + } + if tok.RefreshToken == "" { + return User{}, errors.New("spotify sent no refresh token") + } + // Before the invite is used up: an account that isn't allowlisted yet can + // try again with the same link once the owner added it. + user, err := s.identity.User(ctx, tok.AccessToken) + if err != nil { + return User{}, fmt.Errorf("look up account: %w", err) + } + if _, err := s.takeInvite(ctx, p.invite); err != nil { + return User{}, err + } + c := Connection{Token: tok, User: user, ConnectedAt: s.now()} + if err := s.tokens.SaveConnection(ctx, p.profile, c); err != nil { + return User{}, fmt.Errorf("save connection: %w", err) + } + return user, nil +} + +// Disconnect uses up the invite and deletes its profile's connection. +func (s *Service) Disconnect(ctx context.Context, code InviteCode) (Profile, error) { + inv, err := s.takeInvite(ctx, hashInvite(code)) + if err != nil { + return "", err + } + if err := s.tokens.DeleteConnection(ctx, inv.Profile); err != nil { + return "", fmt.Errorf("delete connection: %w", err) + } + return inv.Profile, nil +} + +func (s *Service) checkInvite(ctx context.Context, code InviteCode) (Invite, error) { + if code == "" { + return Invite{}, ErrInvalidInvite + } + inv, err := s.invites.Invite(ctx, hashInvite(code)) + return s.validInvite(inv, err) +} + +func (s *Service) takeInvite(ctx context.Context, h InviteHash) (Invite, error) { + inv, err := s.invites.TakeInvite(ctx, h) + return s.validInvite(inv, err) +} + +func (s *Service) validInvite(inv Invite, err error) (Invite, error) { + switch { + case errors.Is(err, ErrNotFound): + return Invite{}, ErrInvalidInvite + case err != nil: + return Invite{}, fmt.Errorf("load invite: %w", err) + case s.now().After(inv.Expires): + return Invite{}, ErrInvalidInvite + } + return inv, nil +} + +// hashInvite: only the SHA-256 of a code is stored, so reading the storage +// doesn't give anyone a usable link. +func hashInvite(code InviteCode) InviteHash { + sum := sha256.Sum256([]byte(code)) + return InviteHash(hex.EncodeToString(sum[:])) +} + +// randomString returns 256 random bits, base64url-encoded (43 characters, +// which is also a valid PKCE verifier). +func randomString() string { + return base64.RawURLEncoding.EncodeToString(randomBytes(32)) +} + +func randomBytes(n int) []byte { + b := make([]byte, n) + _, _ = rand.Read(b) // never fails, see crypto/rand.Read + return b +} diff --git a/internal/account/tokensource.go b/internal/account/tokensource.go new file mode 100644 index 0000000..44e0f78 --- /dev/null +++ b/internal/account/tokensource.go @@ -0,0 +1,80 @@ +package account + +import ( + "context" + "errors" + "fmt" + "time" +) + +// TokenSource hands out a valid access token for one profile, refreshing it +// when needed. +// +// The refresh runs inside Tokens.UpdateConnection, so it reads, refreshes and +// writes the connection as one step. A login that lands meanwhile waits and +// then replaces the result, instead of being overwritten by the old account's +// refreshed token. It also means two callers never refresh the same token. +type TokenSource struct { + tokens Tokens + oauth OAuth + profile Profile + now func() time.Time +} + +// NewTokenSource returns a TokenSource for p. +func NewTokenSource(tokens Tokens, oauth OAuth, p Profile, opts ...Option) *TokenSource { + return &TokenSource{tokens: tokens, oauth: oauth, profile: p, now: apply(opts).now} +} + +// AccessToken returns a valid access token, or ErrNotConnected. +func (ts *TokenSource) AccessToken(ctx context.Context) (string, error) { + c, err := ts.tokens.Connection(ctx, ts.profile) + if errors.Is(err, ErrNotFound) { + return "", ErrNotConnected + } + if err != nil { + return "", fmt.Errorf("load connection: %w", err) + } + if c.accessValid(ts.now()) { + return c.Token.AccessToken, nil + } + + var access string + err = ts.tokens.UpdateConnection(ctx, ts.profile, func(c *Connection) error { + if c.accessValid(ts.now()) { // refreshed by someone else meanwhile + access = c.Token.AccessToken + return nil + } + tok, err := ts.oauth.Refresh(ctx, c.Token.RefreshToken) + if err != nil { + return err + } + if tok.RefreshToken == "" { // Spotify kept the old one + tok.RefreshToken = c.Token.RefreshToken + } + c.Token, access = tok, tok.AccessToken + return nil + }) + switch { + case errors.Is(err, ErrNotFound), errors.Is(err, ErrRevoked): + return "", ErrNotConnected + case err != nil: + return "", fmt.Errorf("refresh Spotify token: %w", err) + } + return access, nil +} + +// Invalidate marks accessToken as expired after Spotify rejected it, so the +// next call refreshes. It does nothing if the stored token has changed since. +func (ts *TokenSource) Invalidate(ctx context.Context, accessToken string) error { + err := ts.tokens.UpdateConnection(ctx, ts.profile, func(c *Connection) error { + if c.Token.AccessToken == accessToken { + c.Token.Expiry = time.Time{} + } + return nil + }) + if errors.Is(err, ErrNotFound) { + return nil + } + return err +} diff --git a/internal/account/tokensource_test.go b/internal/account/tokensource_test.go new file mode 100644 index 0000000..ed04f5f --- /dev/null +++ b/internal/account/tokensource_test.go @@ -0,0 +1,143 @@ +package account_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/subpathdev/spotify-mcp/internal/account" +) + +func (e *env) connect(t *testing.T, c account.Connection) { + t.Helper() + if err := e.store.SaveConnection(context.Background(), profile, c); err != nil { + t.Fatal(err) + } +} + +func (e *env) tokens() *account.TokenSource { + return account.NewTokenSource(e.store, e.oauth, profile, account.WithClock(func() time.Time { return e.now })) +} + +func expired(rt string) account.Connection { + return account.Connection{ + Token: account.Token{AccessToken: "old", RefreshToken: rt}, + User: account.User{ID: "jan", DisplayName: "Jan"}, + } +} + +func TestAccessTokenRefreshesAndPersists(t *testing.T) { + ctx := context.Background() + for name, tc := range map[string]struct{ sent, stored string }{ + "rotated": {sent: "r2", stored: "r2"}, + "not sent": {sent: "", stored: "r1"}, + } { + t.Run(name, func(t *testing.T) { + e := newEnv(t, nil) + e.connect(t, expired("r1")) + calls := 0 + e.oauth.refresh = func(_ context.Context, rt string) (account.Token, error) { + calls++ + if rt != "r1" { + t.Errorf("refreshed with %q", rt) + } + return account.Token{AccessToken: "new", RefreshToken: tc.sent, Expiry: e.now.Add(time.Hour)}, nil + } + ts := e.tokens() + for range 2 { + if tok, err := ts.AccessToken(ctx); err != nil || tok != "new" { + t.Fatalf("token %q %v", tok, err) + } + } + if calls != 1 { + t.Fatalf("refreshed %d times, want once", calls) + } + c, _ := e.store.Connection(ctx, profile) + if c.Token.RefreshToken != tc.stored || c.User.DisplayName != "Jan" { + t.Fatalf("stored %+v", c) + } + }) + } +} + +func TestAccessTokenNotConnected(t *testing.T) { + ctx := context.Background() + e := newEnv(t, nil) + if _, err := e.tokens().AccessToken(ctx); !errors.Is(err, account.ErrNotConnected) { + t.Fatalf("no connection: %v", err) + } + e.connect(t, expired("r1")) + e.oauth.refresh = func(context.Context, string) (account.Token, error) { return account.Token{}, account.ErrRevoked } + if _, err := e.tokens().AccessToken(ctx); !errors.Is(err, account.ErrNotConnected) { + t.Fatalf("revoked: %v", err) + } +} + +func TestInvalidateForcesRefresh(t *testing.T) { + ctx := context.Background() + e := newEnv(t, nil) + c := expired("r1") + c.Token.Expiry = e.now.Add(time.Hour) + e.connect(t, c) + e.oauth.refresh = func(context.Context, string) (account.Token, error) { + return account.Token{AccessToken: "new", Expiry: e.now.Add(time.Hour)}, nil + } + ts := e.tokens() + if err := ts.Invalidate(ctx, "not-the-stored-one"); err != nil { + t.Fatal(err) + } + if tok, _ := ts.AccessToken(ctx); tok != "old" { + t.Fatalf("invalidating another token changed the stored one: %q", tok) + } + if err := ts.Invalidate(ctx, "old"); err != nil { + t.Fatal(err) + } + if tok, _ := ts.AccessToken(ctx); tok != "new" { + t.Fatalf("after invalidate: %q", tok) + } +} + +// A login that lands while a refresh is running must not be overwritten by the +// old account's refreshed token. +func TestLoginDuringRefreshWins(t *testing.T) { + ctx := context.Background() + e := newEnv(t, nil) + e.connect(t, expired("old-account")) + + refreshing, release := make(chan struct{}), make(chan struct{}) + e.oauth.refresh = func(context.Context, string) (account.Token, error) { + close(refreshing) + <-release + return account.Token{AccessToken: "old-account-access", Expiry: e.now.Add(time.Hour)}, nil + } + refreshed := make(chan error, 1) + go func() { + _, err := e.tokens().AccessToken(ctx) + refreshed <- err + }() + <-refreshing + + login := account.Connection{ + Token: account.Token{AccessToken: "new-access", RefreshToken: "new-account", Expiry: e.now.Add(time.Hour)}, + User: account.User{ID: "someone-else"}, + } + saved := make(chan error, 1) + go func() { saved <- e.store.SaveConnection(ctx, profile, login) }() + select { + case err := <-saved: + t.Fatalf("login saved during the refresh (err %v); it must wait", err) + case <-time.After(50 * time.Millisecond): + } + close(release) + if err := <-refreshed; err != nil { + t.Fatal(err) + } + if err := <-saved; err != nil { + t.Fatal(err) + } + c, err := e.store.Connection(ctx, profile) + if err != nil || c.Token.RefreshToken != "new-account" || c.User.ID != "someone-else" { + t.Fatalf("stored %+v %v, want the new login", c, err) + } +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..0d0344c --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,104 @@ +// Package config reads the server's settings from environment variables. +package config + +import ( + "errors" + "fmt" + "net/url" + "strings" + + "github.com/subpathdev/spotify-mcp/internal/account" +) + +// Config holds every setting. Secrets come from a Kubernetes Secret (or a +// local .env) through the environment, never from files in the repo. +type Config struct { + ClientID string + ClientSecret string + // RedirectURL is the OAuth callback registered in the Spotify app; its + // path is /callback. + RedirectURL *url.URL + // PublicURL is the base of invite links. + PublicURL *url.URL + DataDir string + Profile account.Profile + MCPAddr string + WebAddr string +} + +// Load reads the settings through getenv (os.Getenv in production). It +// doesn't require the client secret, which the invite command doesn't need; +// call RequireCredentials before starting the server. +func Load(getenv func(string) string) (Config, error) { + get := func(key, def string) string { + if v := strings.TrimSpace(getenv(key)); v != "" { + return v + } + return def + } + c := Config{ + ClientID: get("SPOTIFY_CLIENT_ID", ""), + ClientSecret: get("SPOTIFY_CLIENT_SECRET", ""), + DataDir: get("DATA_DIR", "/data"), + MCPAddr: get("MCP_ADDR", ":8000"), + WebAddr: get("WEB_ADDR", ":8080"), + } + + raw := get("SPOTIFY_REDIRECT_URI", "") + if raw == "" { + return Config{}, errors.New("SPOTIFY_REDIRECT_URI is not set (see .env.example)") + } + redirect, err := parseHTTPURL(raw) + if err != nil { + return Config{}, fmt.Errorf("SPOTIFY_REDIRECT_URI: %w", err) + } + if redirect.Path != "/callback" { + return Config{}, errors.New("SPOTIFY_REDIRECT_URI must end in /callback, e.g. https://spotify.example.com/callback") + } + c.RedirectURL = redirect + + c.PublicURL = &url.URL{Scheme: redirect.Scheme, Host: redirect.Host} + if raw := get("PUBLIC_URL", ""); raw != "" { + if c.PublicURL, err = parseHTTPURL(strings.TrimRight(raw, "/")); err != nil { + return Config{}, fmt.Errorf("PUBLIC_URL: %w", err) + } + } + + if c.Profile, err = account.ParseProfile(get("PROFILE", "default")); err != nil { + return Config{}, fmt.Errorf("PROFILE: %w", err) + } + return c, nil +} + +// RequireCredentials reports missing Spotify app credentials. +func (c Config) RequireCredentials() error { + var missing []string + if c.ClientID == "" { + missing = append(missing, "SPOTIFY_CLIENT_ID") + } + if c.ClientSecret == "" { + missing = append(missing, "SPOTIFY_CLIENT_SECRET") + } + if len(missing) > 0 { + return fmt.Errorf("missing environment variables: %s (see .env.example)", strings.Join(missing, ", ")) + } + return nil +} + +// InviteURL is the link that opens the connect page with code. +func (c Config) InviteURL(code account.InviteCode) string { + u := c.PublicURL.JoinPath("connect") + u.RawQuery = url.Values{"invite": {string(code)}}.Encode() + return u.String() +} + +func parseHTTPURL(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil { + return nil, err + } + if (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { + return nil, fmt.Errorf("%q is not an http(s) URL", raw) + } + return u, nil +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..9e8d385 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,41 @@ +package config + +import ( + "strings" + "testing" +) + +func envOf(m map[string]string) func(string) string { + return func(k string) string { return m[k] } +} + +func TestLoadDefaults(t *testing.T) { + c, err := Load(envOf(map[string]string{"SPOTIFY_REDIRECT_URI": "https://spotify.example.com/callback"})) + if err != nil { + t.Fatal(err) + } + if c.PublicURL.String() != "https://spotify.example.com" || c.Profile != "default" || c.DataDir != "/data" || c.MCPAddr != ":8000" { + t.Fatalf("%+v", c) + } + if err := c.RequireCredentials(); err == nil || !strings.Contains(err.Error(), "SPOTIFY_CLIENT_SECRET") { + t.Fatalf("credentials: %v", err) + } + if got := c.InviteURL("a-b_c"); got != "https://spotify.example.com/connect?invite=a-b_c" { + t.Fatalf("invite URL %q", got) + } +} + +func TestLoadRejects(t *testing.T) { + for name, env := range map[string]map[string]string{ + "no redirect": {}, + "redirect path": {"SPOTIFY_REDIRECT_URI": "https://x.example/login"}, + "redirect scheme": {"SPOTIFY_REDIRECT_URI": "ftp://x.example/callback"}, + "bad profile": {"SPOTIFY_REDIRECT_URI": "https://x.example/callback", "PROFILE": "Jan"}, + "bad public URL": {"SPOTIFY_REDIRECT_URI": "https://x.example/callback", "PUBLIC_URL": "x.example"}, + "relative redirect": {"SPOTIFY_REDIRECT_URI": "/callback"}, + } { + if _, err := Load(envOf(env)); err == nil { + t.Errorf("%s: accepted", name) + } + } +} diff --git a/internal/filestore/filestore.go b/internal/filestore/filestore.go new file mode 100644 index 0000000..c96088f --- /dev/null +++ b/internal/filestore/filestore.go @@ -0,0 +1,289 @@ +// Package filestore keeps connections and invites as JSON files in a data +// directory, usually a small persistent volume. It implements account.Tokens +// and account.Invites. +// +// Files are owner-only (0600) and replaced atomically (temp file + rename), so +// a crash never leaves half a file behind. Every operation holds a lock that +// covers both goroutines (a mutex) and other processes (flock on a lock file), +// because the invite command runs as a second process next to the server. +package filestore + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sync" + "time" + + "github.com/subpathdev/spotify-mcp/internal/account" +) + +// Store is safe for concurrent use, also by several processes on one directory. +type Store struct { + dir string + mu sync.Mutex +} + +var ( + _ account.Tokens = (*Store)(nil) + _ account.Invites = (*Store)(nil) +) + +// Open creates the data directory if needed. +func Open(dir string) (*Store, error) { + if err := os.MkdirAll(filepath.Join(dir, "tokens"), 0o700); err != nil { + return nil, fmt.Errorf("create data dir: %w", err) + } + return &Store{dir: dir}, nil +} + +// connectionRecord is the on-disk format of a connection. +type connectionRecord struct { + RefreshToken string `json:"refresh_token"` + AccessToken string `json:"access_token,omitempty"` + Expiry time.Time `json:"expiry,omitzero"` + SpotifyUserID string `json:"spotify_user_id,omitempty"` + DisplayName string `json:"display_name,omitempty"` + ConnectedAt time.Time `json:"connected_at,omitzero"` +} + +func toRecord(c account.Connection) connectionRecord { + return connectionRecord{ + RefreshToken: c.Token.RefreshToken, AccessToken: c.Token.AccessToken, Expiry: c.Token.Expiry, + SpotifyUserID: c.User.ID, DisplayName: c.User.DisplayName, ConnectedAt: c.ConnectedAt, + } +} + +func (r connectionRecord) connection() account.Connection { + return account.Connection{ + Token: account.Token{AccessToken: r.AccessToken, RefreshToken: r.RefreshToken, Expiry: r.Expiry}, + User: account.User{ID: r.SpotifyUserID, DisplayName: r.DisplayName}, + ConnectedAt: r.ConnectedAt, + } +} + +// inviteRecord is the on-disk format of an invite; invites.json maps the +// invite hash to it. +type inviteRecord struct { + Profile string `json:"profile"` + Expires time.Time `json:"expires"` +} + +// lock takes the in-process and the cross-process lock. +func (s *Store) lock() (unlock func(), err error) { + s.mu.Lock() + release, err := lockFile(filepath.Join(s.dir, ".lock")) + if err != nil { + s.mu.Unlock() + return nil, fmt.Errorf("lock data dir: %w", err) + } + return func() { release(); s.mu.Unlock() }, nil +} + +func (s *Store) connectionPath(p account.Profile) (string, error) { + // Profiles are validated when parsed; check again because the value ends + // up in a file name. + if _, err := account.ParseProfile(string(p)); err != nil { + return "", err + } + return filepath.Join(s.dir, "tokens", string(p)+".json"), nil +} + +// Connection implements account.Tokens. +func (s *Store) Connection(_ context.Context, p account.Profile) (account.Connection, error) { + path, err := s.connectionPath(p) + if err != nil { + return account.Connection{}, err + } + unlock, err := s.lock() + if err != nil { + return account.Connection{}, err + } + defer unlock() + var r connectionRecord + if err := readJSON(path, &r); err != nil { + return account.Connection{}, err + } + return r.connection(), nil +} + +// SaveConnection implements account.Tokens. +func (s *Store) SaveConnection(_ context.Context, p account.Profile, c account.Connection) error { + path, err := s.connectionPath(p) + if err != nil { + return err + } + unlock, err := s.lock() + if err != nil { + return err + } + defer unlock() + return writeJSON(path, toRecord(c)) +} + +// UpdateConnection implements account.Tokens. fn runs under the lock. +func (s *Store) UpdateConnection(_ context.Context, p account.Profile, fn func(*account.Connection) error) error { + path, err := s.connectionPath(p) + if err != nil { + return err + } + unlock, err := s.lock() + if err != nil { + return err + } + defer unlock() + var r connectionRecord + if err := readJSON(path, &r); err != nil { + return err + } + c := r.connection() + if err := fn(&c); err != nil { + return err + } + return writeJSON(path, toRecord(c)) +} + +// DeleteConnection implements account.Tokens. +func (s *Store) DeleteConnection(_ context.Context, p account.Profile) error { + path, err := s.connectionPath(p) + if err != nil { + return err + } + unlock, err := s.lock() + if err != nil { + return err + } + defer unlock() + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} + +func (s *Store) invitePath() string { return filepath.Join(s.dir, "invites.json") } + +func (s *Store) loadInvites() (map[account.InviteHash]inviteRecord, error) { + inv := map[account.InviteHash]inviteRecord{} + if err := readJSON(s.invitePath(), &inv); err != nil && !errors.Is(err, account.ErrNotFound) { + return nil, err + } + return inv, nil +} + +// changeInvites runs fn on the invites under the lock and writes them back. +func (s *Store) changeInvites(fn func(map[account.InviteHash]inviteRecord) error) error { + unlock, err := s.lock() + if err != nil { + return err + } + defer unlock() + inv, err := s.loadInvites() + if err != nil { + return err + } + if err := fn(inv); err != nil { + return err + } + return writeJSON(s.invitePath(), inv) +} + +// AddInvite implements account.Invites. +func (s *Store) AddInvite(_ context.Context, i account.Invite) error { + return s.changeInvites(func(inv map[account.InviteHash]inviteRecord) error { + inv[i.Hash] = inviteRecord{Profile: string(i.Profile), Expires: i.Expires} + return nil + }) +} + +// Invite implements account.Invites. +func (s *Store) Invite(_ context.Context, h account.InviteHash) (account.Invite, error) { + unlock, err := s.lock() + if err != nil { + return account.Invite{}, err + } + defer unlock() + inv, err := s.loadInvites() + if err != nil { + return account.Invite{}, err + } + r, ok := inv[h] + if !ok { + return account.Invite{}, account.ErrNotFound + } + return account.Invite{Hash: h, Profile: account.Profile(r.Profile), Expires: r.Expires}, nil +} + +// TakeInvite implements account.Invites. +func (s *Store) TakeInvite(_ context.Context, h account.InviteHash) (account.Invite, error) { + var out account.Invite + err := s.changeInvites(func(inv map[account.InviteHash]inviteRecord) error { + r, ok := inv[h] + if !ok { + return account.ErrNotFound + } + delete(inv, h) + out = account.Invite{Hash: h, Profile: account.Profile(r.Profile), Expires: r.Expires} + return nil + }) + return out, err +} + +// PruneInvites implements account.Invites. +func (s *Store) PruneInvites(_ context.Context, t time.Time) error { + return s.changeInvites(func(inv map[account.InviteHash]inviteRecord) error { + for h, r := range inv { + if r.Expires.Before(t) { + delete(inv, h) + } + } + return nil + }) +} + +func readJSON(path string, v any) error { + b, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return account.ErrNotFound + } + if err != nil { + return err + } + if err := json.Unmarshal(b, v); err != nil { + return fmt.Errorf("read %s: %w", filepath.Base(path), err) + } + return nil +} + +func writeJSON(path string, v any) (err error) { + b, err := json.MarshalIndent(v, "", " ") + if err != nil { + return err + } + f, err := os.CreateTemp(filepath.Dir(path), ".tmp-*") + if err != nil { + return err + } + tmp := f.Name() + defer func() { + if err != nil { + _ = f.Close() + _ = os.Remove(tmp) + } + }() + if err := f.Chmod(0o600); err != nil { + return err + } + if _, err := f.Write(b); err != nil { + return err + } + if err := f.Sync(); err != nil { + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(tmp, path) +} diff --git a/internal/filestore/filestore_test.go b/internal/filestore/filestore_test.go new file mode 100644 index 0000000..9d67c0f --- /dev/null +++ b/internal/filestore/filestore_test.go @@ -0,0 +1,162 @@ +package filestore + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/subpathdev/spotify-mcp/internal/account" +) + +const profile = account.Profile("default") + +func open(t *testing.T, dir string) *Store { + t.Helper() + s, err := Open(dir) + if err != nil { + t.Fatal(err) + } + return s +} + +func TestConnectionRoundTrip(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + s := open(t, dir) + if _, err := s.Connection(ctx, profile); !errors.Is(err, account.ErrNotFound) { + t.Fatalf("empty store: %v", err) + } + want := account.Connection{ + Token: account.Token{AccessToken: "a", RefreshToken: "r", Expiry: time.Date(2026, 11, 22, 13, 0, 0, 0, time.UTC)}, + User: account.User{ID: "jan", DisplayName: "Jan"}, + ConnectedAt: time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC), + } + if err := s.SaveConnection(ctx, profile, want); err != nil { + t.Fatal(err) + } + fi, err := os.Stat(filepath.Join(dir, "tokens", "default.json")) + if err != nil || fi.Mode().Perm() != 0o600 { + t.Fatalf("token file: %v %v", fi, err) + } + // A second store on the same dir, as after a pod restart, sees it. + got, err := open(t, dir).Connection(ctx, profile) + if err != nil || got != want { + t.Fatalf("got %+v %v, want %+v", got, err, want) + } + for range 2 { + if err := s.DeleteConnection(ctx, profile); err != nil { + t.Fatal(err) + } + } +} + +func TestUpdateConnection(t *testing.T) { + ctx := context.Background() + s := open(t, t.TempDir()) + noop := func(*account.Connection) error { return nil } + if err := s.UpdateConnection(ctx, profile, noop); !errors.Is(err, account.ErrNotFound) { + t.Fatalf("missing: %v", err) + } + _ = s.SaveConnection(ctx, profile, account.Connection{Token: account.Token{RefreshToken: "r1"}}) + boom := errors.New("boom") + err := s.UpdateConnection(ctx, profile, func(c *account.Connection) error { + c.Token.RefreshToken = "lost" + return boom + }) + if !errors.Is(err, boom) { + t.Fatalf("fn error: %v", err) + } + if c, _ := s.Connection(ctx, profile); c.Token.RefreshToken != "r1" { + t.Fatalf("failed update was written: %+v", c) + } +} + +func TestRejectsBadProfile(t *testing.T) { + s := open(t, t.TempDir()) + if err := s.SaveConnection(context.Background(), "../x", account.Connection{}); err == nil { + t.Fatal("path traversal accepted") + } +} + +func TestInviteTakenOnce(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + s := open(t, dir) + inv := account.Invite{Hash: "h1", Profile: profile, Expires: time.Now().Add(time.Hour)} + if err := s.AddInvite(ctx, inv); err != nil { + t.Fatal(err) + } + if got, err := s.Invite(ctx, "h1"); err != nil || got.Profile != profile { + t.Fatalf("invite: %+v %v", got, err) + } + + // Half go through a second Store, like the invite command's process. + other := open(t, dir) + var wg sync.WaitGroup + var mu sync.Mutex + taken := 0 + for i := range 20 { + st := s + if i%2 == 1 { + st = other + } + wg.Go(func() { + if _, err := st.TakeInvite(ctx, "h1"); err == nil { + mu.Lock() + taken++ + mu.Unlock() + } + }) + } + wg.Wait() + if taken != 1 { + t.Fatalf("taken %d times, want once", taken) + } +} + +func TestConcurrentInvitesFromTwoStores(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + a, b := open(t, dir), open(t, dir) + var wg sync.WaitGroup + for i := range 20 { + st := a + if i%2 == 1 { + st = b + } + wg.Go(func() { + h := account.InviteHash(strings.Repeat("x", i+1)) + if err := st.AddInvite(ctx, account.Invite{Hash: h, Profile: profile, Expires: time.Now().Add(time.Hour)}); err != nil { + t.Error(err) + } + }) + } + wg.Wait() + for i := range 20 { + if _, err := a.Invite(ctx, account.InviteHash(strings.Repeat("x", i+1))); err != nil { + t.Errorf("invite %d lost: %v", i, err) + } + } +} + +func TestPruneInvites(t *testing.T) { + ctx := context.Background() + s := open(t, t.TempDir()) + now := time.Now() + _ = s.AddInvite(ctx, account.Invite{Hash: "old", Profile: profile, Expires: now.Add(-time.Minute)}) + _ = s.AddInvite(ctx, account.Invite{Hash: "new", Profile: profile, Expires: now.Add(time.Minute)}) + if err := s.PruneInvites(ctx, now); err != nil { + t.Fatal(err) + } + if _, err := s.Invite(ctx, "old"); !errors.Is(err, account.ErrNotFound) { + t.Fatalf("expired invite kept: %v", err) + } + if _, err := s.Invite(ctx, "new"); err != nil { + t.Fatalf("valid invite pruned: %v", err) + } +} diff --git a/internal/filestore/lock_other.go b/internal/filestore/lock_other.go new file mode 100644 index 0000000..d03eac7 --- /dev/null +++ b/internal/filestore/lock_other.go @@ -0,0 +1,7 @@ +//go:build !unix + +package filestore + +// lockFile has no cross-process lock on this platform; the Store's mutex +// still protects one process. +func lockFile(string) (release func(), err error) { return func() {}, nil } diff --git a/internal/filestore/lock_unix.go b/internal/filestore/lock_unix.go new file mode 100644 index 0000000..b820dd8 --- /dev/null +++ b/internal/filestore/lock_unix.go @@ -0,0 +1,23 @@ +//go:build unix + +package filestore + +import ( + "os" + "syscall" +) + +// lockFile takes an exclusive flock on path, creating it if needed. The lock +// belongs to this open file, so it also excludes other goroutines and +// processes that open the same path. +func lockFile(path string) (release func(), err error) { + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600) + if err != nil { + return nil, err + } + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { + _ = f.Close() + return nil, err + } + return func() { _ = f.Close() }, nil // closing releases the lock +} diff --git a/internal/mcpserver/mcpserver.go b/internal/mcpserver/mcpserver.go new file mode 100644 index 0000000..cc6c4b2 --- /dev/null +++ b/internal/mcpserver/mcpserver.go @@ -0,0 +1,263 @@ +// Package mcpserver exposes playback control as MCP tools over Streamable +// HTTP. It only turns tool calls into calls on a Player and results into text. +package mcpserver + +import ( + "context" + "fmt" + "log/slog" + "net/http" + "strings" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/subpathdev/spotify-mcp/internal/playback" +) + +// Player is what the tools need; *playback.Service implements it. +type Player interface { + Devices(ctx context.Context) ([]playback.Device, error) + NowPlaying(ctx context.Context) (*playback.State, error) + Search(ctx context.Context, query string, kind playback.Kind, limit int) ([]playback.Item, error) + Play(ctx context.Context, selector string, uri playback.URI) (*playback.Device, error) + PlayFirst(ctx context.Context, selector, query string, kind playback.Kind) (playback.Item, *playback.Device, error) + Resume(ctx context.Context, selector string) (*playback.Device, error) + Pause(ctx context.Context, selector string) (*playback.Device, error) + Next(ctx context.Context, selector string) (*playback.Device, error) + Previous(ctx context.Context, selector string) (*playback.Device, error) + Transfer(ctx context.Context, selector string, play bool) (playback.Device, error) +} + +const instructions = "Controls Spotify playback on the user's devices (Spotify Connect). " + + "Use devices to find a device name, search for URIs, and play/pause/resume/next/previous/transfer to control playback." + +// NewServer returns an MCP server with the playback tools. +func NewServer(p Player, version string) *mcp.Server { + s := mcp.NewServer( + &mcp.Implementation{Name: "spotify-mcp", Title: "Spotify", Version: version}, + &mcp.ServerOptions{Instructions: instructions}, + ) + register(s, p) + return s +} + +// Handler serves s at /mcp and a liveness check at /healthz. +func Handler(s *mcp.Server, log *slog.Logger) http.Handler { + mux := http.NewServeMux() + mux.Handle("/mcp", mcp.NewStreamableHTTPHandler( + func(*http.Request) *mcp.Server { return s }, + &mcp.StreamableHTTPOptions{Logger: log, SessionTimeout: 30 * time.Minute}, + )) + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok\n")) }) + return mux +} + +type deviceArgs struct { + Device string `json:"device,omitempty" jsonschema:"Device name (e.g. 'Pixel 8'), type (e.g. 'smartphone') or ID from the devices tool. Empty: the active device."` +} + +type playArgs struct { + URI string `json:"uri,omitempty" jsonschema:"Spotify URI to play, e.g. spotify:track:..., spotify:album:..., spotify:playlist:... Takes precedence over query."` + Query string `json:"query,omitempty" jsonschema:"Search text; the first result of the given type is played, e.g. 'Bohemian Rhapsody Queen'."` + Type string `json:"type,omitempty" jsonschema:"What the query searches for: track (default), album, artist, playlist, show or episode."` + Device string `json:"device,omitempty" jsonschema:"Device name, type or ID. Empty: the active device."` +} + +type searchArgs struct { + Query string `json:"query" jsonschema:"Search text, e.g. an artist, song or album name."` + Type string `json:"type,omitempty" jsonschema:"track (default), album, artist, playlist, show or episode."` + Limit int `json:"limit,omitempty" jsonschema:"Number of results, 1-10 (Spotify development mode allows at most 10). Default 5."` +} + +type transferArgs struct { + Device string `json:"device" jsonschema:"Target device name (e.g. 'Pixel 8'), type or ID from the devices tool."` + Play *bool `json:"play,omitempty" jsonschema:"Start playing on the new device. Default true."` +} + +type noArgs struct{} + +func register(s *mcp.Server, p Player) { + t := tools{p: p} + ro := &mcp.ToolAnnotations{ReadOnlyHint: true, OpenWorldHint: ptr(true)} + ctl := &mcp.ToolAnnotations{IdempotentHint: true, DestructiveHint: ptr(false), OpenWorldHint: ptr(true)} + step := &mcp.ToolAnnotations{DestructiveHint: ptr(false), OpenWorldHint: ptr(true)} + + mcp.AddTool(s, &mcp.Tool{Name: "devices", Annotations: ro, + Description: "List the Spotify Connect devices (phone, computer, speakers) that Spotify currently sees, and which one is active."}, t.devices) + mcp.AddTool(s, &mcp.Tool{Name: "now_playing", Annotations: ro, + Description: "Show what is playing on Spotify right now, on which device, and whether it is paused."}, t.nowPlaying) + mcp.AddTool(s, &mcp.Tool{Name: "search", Annotations: ro, + Description: "Search Spotify. Returns up to 10 results with their URIs, which the play tool accepts."}, t.search) + mcp.AddTool(s, &mcp.Tool{Name: "play", Annotations: step, + Description: "Play a Spotify URI, or the first search result for a query, on a device (default: the active one). Without uri and query it resumes playback."}, t.play) + mcp.AddTool(s, &mcp.Tool{Name: "pause", Annotations: ctl, Description: "Pause Spotify playback."}, t.pause) + mcp.AddTool(s, &mcp.Tool{Name: "resume", Annotations: ctl, Description: "Resume Spotify playback where it was paused."}, t.resume) + mcp.AddTool(s, &mcp.Tool{Name: "next", Annotations: step, Description: "Skip to the next track."}, t.next) + mcp.AddTool(s, &mcp.Tool{Name: "previous", Annotations: step, Description: "Go back to the previous track."}, t.previous) + mcp.AddTool(s, &mcp.Tool{Name: "transfer", Annotations: ctl, + Description: "Move playback to another device, e.g. from the computer to the phone."}, t.transfer) +} + +// tools holds the handlers. A returned error becomes a tool result with +// IsError set, so its message reaches the model. +type tools struct{ p Player } + +func (t tools) devices(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) (*mcp.CallToolResult, any, error) { + devs, err := t.p.Devices(ctx) + if err != nil { + return nil, nil, err + } + if len(devs) == 0 { + return text("No Spotify devices are online. Open the Spotify app on a phone, computer or speaker; it then shows up here."), nil, nil + } + lines := make([]string, len(devs)) + for i, d := range devs { + lines[i] = "- " + formatDevice(d) + } + return text("Devices:\n" + strings.Join(lines, "\n")), nil, nil +} + +func (t tools) nowPlaying(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) (*mcp.CallToolResult, any, error) { + st, err := t.p.NowPlaying(ctx) + if err != nil { + return nil, nil, err + } + if st == nil || st.Item == nil { + return text("Nothing is playing on Spotify right now."), nil, nil + } + state := "Paused" + if st.Playing { + state = "Playing" + } + dev := "unknown device" + if st.Device != nil { + dev = st.Device.Name + } + return text(fmt.Sprintf("%s on %s: %s [%s / %s]", state, dev, formatItem(*st.Item), mmss(st.Progress), mmss(st.Item.Duration))), nil, nil +} + +func (t tools) search(ctx context.Context, _ *mcp.CallToolRequest, in searchArgs) (*mcp.CallToolResult, any, error) { + kind, err := playback.ParseKind(in.Type) + if err != nil { + return nil, nil, err + } + items, err := t.p.Search(ctx, in.Query, kind, in.Limit) + if err != nil { + return nil, nil, err + } + if len(items) == 0 { + return text(fmt.Sprintf("No results for %q.", in.Query)), nil, nil + } + lines := make([]string, len(items)) + for i, it := range items { + lines[i] = fmt.Sprintf("%d. %s", i+1, formatItem(it)) + } + return text(fmt.Sprintf("Results for %q:\n%s", in.Query, strings.Join(lines, "\n"))), nil, nil +} + +func (t tools) play(ctx context.Context, _ *mcp.CallToolRequest, in playArgs) (*mcp.CallToolResult, any, error) { + switch { + case strings.TrimSpace(in.URI) != "": + uri, err := playback.ParseURI(in.URI) + if err != nil { + return nil, nil, err + } + dev, err := t.p.Play(ctx, in.Device, uri) + if err != nil { + return nil, nil, err + } + return text("Playing " + uri.String() + on(dev) + "."), nil, nil + case strings.TrimSpace(in.Query) != "": + kind, err := playback.ParseKind(in.Type) + if err != nil { + return nil, nil, err + } + item, dev, err := t.p.PlayFirst(ctx, in.Device, in.Query, kind) + if err != nil { + return nil, nil, err + } + return text("Playing " + formatItem(item) + on(dev) + "."), nil, nil + default: + return t.resume(ctx, nil, deviceArgs{Device: in.Device}) + } +} + +func (t tools) resume(ctx context.Context, _ *mcp.CallToolRequest, in deviceArgs) (*mcp.CallToolResult, any, error) { + dev, err := t.p.Resume(ctx, in.Device) + return done(dev, err, "Resumed playback") +} + +func (t tools) pause(ctx context.Context, _ *mcp.CallToolRequest, in deviceArgs) (*mcp.CallToolResult, any, error) { + dev, err := t.p.Pause(ctx, in.Device) + return done(dev, err, "Paused") +} + +func (t tools) next(ctx context.Context, _ *mcp.CallToolRequest, in deviceArgs) (*mcp.CallToolResult, any, error) { + dev, err := t.p.Next(ctx, in.Device) + return done(dev, err, "Skipped to the next track") +} + +func (t tools) previous(ctx context.Context, _ *mcp.CallToolRequest, in deviceArgs) (*mcp.CallToolResult, any, error) { + dev, err := t.p.Previous(ctx, in.Device) + return done(dev, err, "Went back to the previous track") +} + +func (t tools) transfer(ctx context.Context, _ *mcp.CallToolRequest, in transferArgs) (*mcp.CallToolResult, any, error) { + dev, err := t.p.Transfer(ctx, in.Device, in.Play == nil || *in.Play) + if err != nil { + return nil, nil, err + } + return text("Moved playback to " + dev.Name + "."), nil, nil +} + +// done turns the result of a simple command into a tool result. +func done(dev *playback.Device, err error, msg string) (*mcp.CallToolResult, any, error) { + if err != nil { + return nil, nil, err + } + return text(msg + on(dev) + "."), nil, nil +} + +func on(dev *playback.Device) string { + if dev == nil { + return "" + } + return " on " + dev.Name +} + +func text(s string) *mcp.CallToolResult { + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: s}}} +} + +func formatDevice(d playback.Device) string { + s := fmt.Sprintf("%s (%s, id %s)", d.Name, d.Type, d.ID) + if d.Active { + s += " [active]" + } + if d.Restricted { + s += " [can't be controlled]" + } + return s +} + +func formatItem(it playback.Item) string { + s := it.Name + if len(it.Artists) > 0 { + s += " by " + strings.Join(it.Artists, ", ") + } + if it.Album != "" && it.Kind != playback.KindAlbum { + s += " (" + it.Album + ")" + } + if it.Owner != "" { + s += " (by " + it.Owner + ")" + } + return s + " - " + it.URI.String() +} + +func mmss(d time.Duration) string { + sec := int(d / time.Second) + return fmt.Sprintf("%d:%02d", sec/60, sec%60) +} + +func ptr[T any](v T) *T { return &v } diff --git a/internal/mcpserver/mcpserver_test.go b/internal/mcpserver/mcpserver_test.go new file mode 100644 index 0000000..9f1d452 --- /dev/null +++ b/internal/mcpserver/mcpserver_test.go @@ -0,0 +1,156 @@ +package mcpserver + +import ( + "context" + "errors" + "slices" + "strings" + "testing" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/subpathdev/spotify-mcp/internal/playback" +) + +// fakePlayer records calls; err, if set, is returned by every command. +type fakePlayer struct { + calls []string + err error +} + +var ( + pixel = playback.Device{ID: "ph1", Name: "Jan's Pixel 8", Type: "Smartphone", Active: true} + song = playback.Item{Kind: playback.KindTrack, Name: "Song", Artists: []string{"Band"}, Album: "LP", Duration: 3 * time.Minute} +) + +func (f *fakePlayer) record(s string) { f.calls = append(f.calls, s) } + +func (f *fakePlayer) Devices(context.Context) ([]playback.Device, error) { + return []playback.Device{pixel}, nil +} +func (f *fakePlayer) NowPlaying(context.Context) (*playback.State, error) { + return &playback.State{Playing: true, Device: &pixel, Item: &song, Progress: 61 * time.Second}, nil +} +func (f *fakePlayer) Search(_ context.Context, q string, k playback.Kind, limit int) ([]playback.Item, error) { + f.record("search " + q + " " + string(k)) + return []playback.Item{song}, nil +} +func (f *fakePlayer) Play(_ context.Context, sel string, u playback.URI) (*playback.Device, error) { + f.record("play " + sel + " " + u.String()) + return &pixel, f.err +} +func (f *fakePlayer) PlayFirst(_ context.Context, sel, q string, k playback.Kind) (playback.Item, *playback.Device, error) { + f.record("playfirst " + sel + " " + q + " " + string(k)) + return song, nil, f.err +} +func (f *fakePlayer) Resume(_ context.Context, sel string) (*playback.Device, error) { + f.record("resume " + sel) + return nil, f.err +} +func (f *fakePlayer) Pause(_ context.Context, sel string) (*playback.Device, error) { + f.record("pause " + sel) + return nil, f.err +} +func (f *fakePlayer) Next(_ context.Context, sel string) (*playback.Device, error) { + f.record("next " + sel) + return nil, f.err +} +func (f *fakePlayer) Previous(_ context.Context, sel string) (*playback.Device, error) { + f.record("previous " + sel) + return nil, f.err +} +func (f *fakePlayer) Transfer(_ context.Context, sel string, play bool) (playback.Device, error) { + f.record("transfer " + sel) + return pixel, f.err +} + +func session(t *testing.T, p Player) *mcp.ClientSession { + t.Helper() + ctx := context.Background() + ct, st := mcp.NewInMemoryTransports() + if _, err := NewServer(p, "test").Connect(ctx, st, nil); err != nil { + t.Fatal(err) + } + cs, err := mcp.NewClient(&mcp.Implementation{Name: "c"}, nil).Connect(ctx, ct, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cs.Close() }) + return cs +} + +func call(t *testing.T, cs *mcp.ClientSession, name string, args map[string]any) (string, bool) { + t.Helper() + res, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: name, Arguments: args}) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + var b strings.Builder + for _, c := range res.Content { + if tc, ok := c.(*mcp.TextContent); ok { + b.WriteString(tc.Text) + } + } + return b.String(), res.IsError +} + +func TestToolList(t *testing.T) { + res, err := session(t, &fakePlayer{}).ListTools(context.Background(), nil) + if err != nil { + t.Fatal(err) + } + var names []string + for _, tl := range res.Tools { + names = append(names, tl.Name) + } + slices.Sort(names) + if got := strings.Join(names, ","); got != "devices,next,now_playing,pause,play,previous,resume,search,transfer" { + t.Fatalf("tools %s", got) + } +} + +func TestPlayVariants(t *testing.T) { + f := &fakePlayer{} + cs := session(t, f) + for _, tc := range []struct { + args map[string]any + wantCall string + wantText string + }{ + {map[string]any{"uri": "spotify:album:1", "device": "pixel"}, "play pixel spotify:album:1", "Playing spotify:album:1 on Jan's Pixel 8."}, + {map[string]any{"query": "song", "type": "track"}, "playfirst song track", "Playing Song by Band (LP)"}, + {nil, "resume ", "Resumed playback."}, + } { + out, isErr := call(t, cs, "play", tc.args) + if isErr || !strings.Contains(out, tc.wantText) || f.calls[len(f.calls)-1] != tc.wantCall { + t.Errorf("%v: %v %q, calls %v", tc.args, isErr, out, f.calls) + } + } + for _, args := range []map[string]any{{"uri": "spotify:bogus:1"}, {"query": "x", "type": "podcast"}} { + if _, isErr := call(t, cs, "play", args); !isErr { + t.Errorf("%v accepted", args) + } + } +} + +func TestErrorsReachTheModel(t *testing.T) { + f := &fakePlayer{err: errors.New("No active Spotify device. Open the Spotify app")} + out, isErr := call(t, session(t, f), "pause", nil) + if !isErr || !strings.Contains(out, "Open the Spotify app") { + t.Fatalf("%v %q", isErr, out) + } +} + +func TestReadTools(t *testing.T) { + cs := session(t, &fakePlayer{}) + if out, _ := call(t, cs, "now_playing", nil); !strings.Contains(out, "Playing on Jan's Pixel 8: Song by Band (LP)") || !strings.Contains(out, "1:01 / 3:00") { + t.Errorf("now_playing: %s", out) + } + if out, _ := call(t, cs, "devices", nil); !strings.Contains(out, "Jan's Pixel 8 (Smartphone, id ph1) [active]") { + t.Errorf("devices: %s", out) + } + if out, _ := call(t, cs, "transfer", map[string]any{"device": "pixel"}); out != "Moved playback to Jan's Pixel 8." { + t.Errorf("transfer: %s", out) + } +} diff --git a/internal/playback/playback.go b/internal/playback/playback.go new file mode 100644 index 0000000..e81ca84 --- /dev/null +++ b/internal/playback/playback.go @@ -0,0 +1,145 @@ +// Package playback is the domain of controlling Spotify playback: devices, +// URIs, search results and the rules for choosing a device and turning +// Spotify's failures into messages a person can act on. +// +// It talks to Spotify through the Spotify port, which an adapter implements. +package playback + +import ( + "context" + "errors" + "fmt" + "strings" + "time" +) + +// Kind is the type of a Spotify item. +type Kind string + +// The kinds this server can search for and play. +const ( + KindTrack Kind = "track" + KindAlbum Kind = "album" + KindArtist Kind = "artist" + KindPlaylist Kind = "playlist" + KindShow Kind = "show" + KindEpisode Kind = "episode" +) + +// Kinds lists every Kind, in the order shown to people. +var Kinds = []Kind{KindTrack, KindAlbum, KindArtist, KindPlaylist, KindShow, KindEpisode} + +// ParseKind checks a kind name. An empty name means KindTrack. +func ParseKind(s string) (Kind, error) { + if s == "" { + return KindTrack, nil + } + for _, k := range Kinds { + if string(k) == s { + return k, nil + } + } + names := make([]string, len(Kinds)) + for i, k := range Kinds { + names[i] = string(k) + } + return "", fmt.Errorf("unknown type %q (use one of %s)", s, strings.Join(names, ", ")) +} + +// IsContext reports whether items of this kind play as a context (a list +// Spotify continues through) rather than on their own. +func (k Kind) IsContext() bool { return k != KindTrack && k != KindEpisode } + +// URI is a parsed spotify:: URI. The zero URI is not valid. +type URI struct { + kind Kind + id string +} + +// ParseURI parses a spotify:: URI. +func ParseURI(s string) (URI, error) { + parts := strings.Split(strings.TrimSpace(s), ":") + if len(parts) != 3 || parts[0] != "spotify" || parts[2] == "" { + return URI{}, fmt.Errorf("%q is not a Spotify URI like spotify:track:", s) + } + k, err := ParseKind(parts[1]) + if err != nil || parts[1] == "" { + return URI{}, fmt.Errorf("unsupported Spotify URI type %q", parts[1]) + } + return URI{kind: k, id: parts[2]}, nil +} + +// Kind of the URI's item. +func (u URI) Kind() Kind { return u.kind } + +// IsZero reports whether u is the zero URI. +func (u URI) IsZero() bool { return u.id == "" } + +func (u URI) String() string { + if u.IsZero() { + return "" + } + return "spotify:" + string(u.kind) + ":" + u.id +} + +// DeviceID is Spotify's ID of a Connect device. +type DeviceID string + +// Device is a Spotify Connect device. +type Device struct { + ID DeviceID + Name string + // Type is Spotify's device type, e.g. "Computer" or "Smartphone". + Type string + Active bool + // Restricted devices don't accept commands from the Web API. + Restricted bool +} + +// Item is a search result or the playing item. +type Item struct { + Kind Kind + Name string + URI URI + Artists []string + // Album is the album of a track, or the show of an episode. + Album string + Owner string // of a playlist + Duration time.Duration +} + +// State is what is playing right now. +type State struct { + Playing bool + Device *Device // nil if Spotify doesn't say + Item *Item // nil between items or for unsupported types + Progress time.Duration +} + +// MaxSearchResults is the most results Spotify returns per search for apps in +// development mode (February 2026 rules). +const MaxSearchResults = 10 + +const defaultSearchResults = 5 + +// Errors the Spotify port returns for Spotify's documented failures. +var ( + ErrNoActiveDevice = errors.New("no active Spotify device") + ErrPremiumRequired = errors.New("playback control needs Spotify Premium (both for the app owner and the connected account)") +) + +// Spotify is the port to the Spotify Web API. +type Spotify interface { + Devices(ctx context.Context) ([]Device, error) + // Search returns up to limit (1..MaxSearchResults) items of one kind. + Search(ctx context.Context, query string, kind Kind, limit int) ([]Item, error) + // Play plays uri; an empty device means the active one. + Play(ctx context.Context, device DeviceID, uri URI) error + Resume(ctx context.Context, device DeviceID) error + Pause(ctx context.Context, device DeviceID) error + Next(ctx context.Context, device DeviceID) error + Previous(ctx context.Context, device DeviceID) error + Transfer(ctx context.Context, device DeviceID, play bool) error + // State returns nil when nothing is playing on any device. + State(ctx context.Context) (*State, error) +} diff --git a/internal/playback/playback_test.go b/internal/playback/playback_test.go new file mode 100644 index 0000000..c4c0216 --- /dev/null +++ b/internal/playback/playback_test.go @@ -0,0 +1,130 @@ +package playback + +import ( + "context" + "errors" + "strings" + "testing" +) + +type fakeSpotify struct { + devices []Device + noActive bool + results []Item + calls []string +} + +func (f *fakeSpotify) Devices(context.Context) ([]Device, error) { return f.devices, nil } +func (f *fakeSpotify) Search(_ context.Context, q string, k Kind, limit int) ([]Item, error) { + f.calls = append(f.calls, "search "+q+" "+string(k)) + return f.results[:min(limit, len(f.results))], nil +} +func (f *fakeSpotify) cmd(name string, id DeviceID) error { + f.calls = append(f.calls, name+" "+string(id)) + if f.noActive && id == "" { + return ErrNoActiveDevice + } + return nil +} +func (f *fakeSpotify) Play(_ context.Context, id DeviceID, u URI) error { + return f.cmd("play "+u.String(), id) +} +func (f *fakeSpotify) Resume(_ context.Context, id DeviceID) error { return f.cmd("resume", id) } +func (f *fakeSpotify) Pause(_ context.Context, id DeviceID) error { return f.cmd("pause", id) } +func (f *fakeSpotify) Next(_ context.Context, id DeviceID) error { return f.cmd("next", id) } +func (f *fakeSpotify) Previous(_ context.Context, id DeviceID) error { return f.cmd("previous", id) } +func (f *fakeSpotify) Transfer(_ context.Context, id DeviceID, _ bool) error { + return f.cmd("transfer", id) +} +func (f *fakeSpotify) State(context.Context) (*State, error) { return nil, nil } + +func (f *fakeSpotify) lastCall() string { return f.calls[len(f.calls)-1] } + +func devices() []Device { + return []Device{ + {ID: "pc1", Name: "mobile", Type: "Computer"}, + {ID: "ph1", Name: "Jan's Pixel 8", Type: "Smartphone"}, + {ID: "sp1", Name: "Kitchen speaker", Type: "Speaker"}, + {ID: "sp2", Name: "Bath speaker", Type: "Speaker"}, + } +} + +func TestResolveDevice(t *testing.T) { + ctx := context.Background() + f := &fakeSpotify{devices: devices()} + s := NewService(f) + for selector, want := range map[string]DeviceID{ + "ph1": "ph1", "MOBILE": "pc1", "pixel": "ph1", "smartphone": "ph1", "kitchen": "sp1", "": "", + } { + if _, err := s.Pause(ctx, selector); err != nil { + t.Fatalf("%q: %v", selector, err) + } + if got := f.lastCall(); got != "pause "+string(want) { + t.Errorf("%q: called %q", selector, got) + } + } + var nf *DeviceNotFoundError + if _, err := s.Pause(ctx, "speaker"); !errors.As(err, &nf) || !nf.Ambiguous { + t.Errorf("ambiguous: %v", err) + } + if _, err := s.Pause(ctx, "car"); !errors.As(err, &nf) || nf.Ambiguous || !strings.Contains(err.Error(), `"mobile" (Computer)`) { + t.Errorf("unknown: %v", err) + } +} + +func TestNoActiveDeviceListsDevices(t *testing.T) { + f := &fakeSpotify{devices: devices(), noActive: true} + _, err := NewService(f).Resume(context.Background(), "") + if !errors.Is(err, ErrNoActiveDevice) || !strings.Contains(err.Error(), "Open the Spotify app") || !strings.Contains(err.Error(), `"Jan's Pixel 8"`) { + t.Fatalf("got %v", err) + } +} + +func TestPlayFirst(t *testing.T) { + uri, _ := ParseURI("spotify:track:1") + f := &fakeSpotify{devices: devices(), results: []Item{{Kind: KindTrack, Name: "Song", URI: uri}}} + item, dev, err := NewService(f).PlayFirst(context.Background(), "pixel", "song", KindTrack) + if err != nil || item.Name != "Song" || dev.ID != "ph1" || f.lastCall() != "play spotify:track:1 ph1" { + t.Fatalf("%+v %+v %v %v", item, dev, err, f.calls) + } + f.results = nil + if _, _, err := NewService(f).PlayFirst(context.Background(), "", "nothing", KindTrack); err == nil { + t.Fatal("empty search played something") + } +} + +func TestTransferNeedsDevice(t *testing.T) { + s := NewService(&fakeSpotify{devices: devices()}) + if _, err := s.Transfer(context.Background(), " ", true); err == nil { + t.Fatal("transfer without device accepted") + } + if d, err := s.Transfer(context.Background(), "pixel", true); err != nil || d.ID != "ph1" { + t.Fatalf("%+v %v", d, err) + } +} + +func TestParseURI(t *testing.T) { + u, err := ParseURI(" spotify:album:abc ") + if err != nil || u.Kind() != KindAlbum || u.String() != "spotify:album:abc" || !u.Kind().IsContext() { + t.Fatalf("%v %v", u, err) + } + for _, s := range []string{"", "spotify:track:", "spotify::1", "spotify:local:1", "https://open.spotify.com/track/1", "spotify:track:1:2"} { + if _, err := ParseURI(s); err == nil { + t.Errorf("%q accepted", s) + } + } +} + +func TestSearchLimits(t *testing.T) { + f := &fakeSpotify{results: make([]Item, 20)} + s := NewService(f) + for limit, want := range map[int]int{0: 5, 3: 3, 50: MaxSearchResults} { + items, err := s.Search(context.Background(), "x", KindTrack, limit) + if err != nil || len(items) != want { + t.Errorf("limit %d: %d items, %v", limit, len(items), err) + } + } + if _, err := s.Search(context.Background(), " ", KindTrack, 1); err == nil { + t.Error("empty query accepted") + } +} diff --git a/internal/playback/service.go b/internal/playback/service.go new file mode 100644 index 0000000..8f0490d --- /dev/null +++ b/internal/playback/service.go @@ -0,0 +1,196 @@ +package playback + +import ( + "context" + "errors" + "fmt" + "strings" +) + +// Service controls playback. Devices are chosen by a selector: a device ID, +// a name, a unique part of a name, or a device type ("smartphone"). An empty +// selector means the active device. +type Service struct { + spotify Spotify +} + +// NewService returns a Service using sp. +func NewService(sp Spotify) *Service { return &Service{spotify: sp} } + +// NoActiveDeviceError is returned when Spotify sees no active device. It lists +// the devices that could be passed instead. It matches ErrNoActiveDevice. +type NoActiveDeviceError struct { + Online []Device +} + +func (e *NoActiveDeviceError) Error() string { + msg := "No active Spotify device. Open the Spotify app on your phone, computer or speaker (playing anything once is enough), then try again" + if len(e.Online) > 0 { + msg += ", or pass one of these as device: " + quotedNames(e.Online, false) + } + return msg + "." +} + +func (e *NoActiveDeviceError) Unwrap() error { return ErrNoActiveDevice } + +// DeviceNotFoundError is returned when a selector matches no device or more +// than one. +type DeviceNotFoundError struct { + Selector string + Online []Device + // Ambiguous is set when the selector matched several devices. + Ambiguous bool +} + +func (e *DeviceNotFoundError) Error() string { + switch { + case len(e.Online) == 0: + return fmt.Sprintf("No Spotify devices are online. Open the Spotify app on the device %q first.", e.Selector) + case e.Ambiguous: + return fmt.Sprintf("%q matches more than one device: %s.", e.Selector, quotedNames(e.Online, true)) + default: + return fmt.Sprintf("No device called %q. Online devices: %s. If yours is missing, open the Spotify app on it.", e.Selector, quotedNames(e.Online, true)) + } +} + +func quotedNames(devs []Device, withType bool) string { + names := make([]string, len(devs)) + for i, d := range devs { + names[i] = fmt.Sprintf("%q", d.Name) + if withType { + names[i] += " (" + d.Type + ")" + } + } + return strings.Join(names, ", ") +} + +// Devices lists the devices Spotify currently sees. +func (s *Service) Devices(ctx context.Context) ([]Device, error) { + return s.spotify.Devices(ctx) +} + +// NowPlaying returns the playback state, or nil when nothing is playing. +func (s *Service) NowPlaying(ctx context.Context) (*State, error) { + return s.spotify.State(ctx) +} + +// Search returns up to limit items; limit 0 means a default of 5, and more +// than MaxSearchResults is capped. +func (s *Service) Search(ctx context.Context, query string, kind Kind, limit int) ([]Item, error) { + query = strings.TrimSpace(query) + if query == "" { + return nil, errors.New("search query is empty") + } + switch { + case limit <= 0: + limit = defaultSearchResults + case limit > MaxSearchResults: + limit = MaxSearchResults + } + return s.spotify.Search(ctx, query, kind, limit) +} + +// Play plays uri on the selected device and returns the device (nil for the +// active one). +func (s *Service) Play(ctx context.Context, selector string, uri URI) (*Device, error) { + if uri.IsZero() { + return nil, errors.New("no URI to play") + } + return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Play(ctx, id, uri) }) +} + +// PlayFirst plays the first search result for query. +func (s *Service) PlayFirst(ctx context.Context, selector, query string, kind Kind) (Item, *Device, error) { + items, err := s.Search(ctx, query, kind, 1) + if err != nil { + return Item{}, nil, err + } + if len(items) == 0 { + return Item{}, nil, fmt.Errorf("nothing found for %q", query) + } + dev, err := s.Play(ctx, selector, items[0].URI) + return items[0], dev, err +} + +// Resume continues playback. +func (s *Service) Resume(ctx context.Context, selector string) (*Device, error) { + return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Resume(ctx, id) }) +} + +// Pause pauses playback. +func (s *Service) Pause(ctx context.Context, selector string) (*Device, error) { + return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Pause(ctx, id) }) +} + +// Next skips to the next item. +func (s *Service) Next(ctx context.Context, selector string) (*Device, error) { + return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Next(ctx, id) }) +} + +// Previous goes back to the previous item. +func (s *Service) Previous(ctx context.Context, selector string) (*Device, error) { + return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Previous(ctx, id) }) +} + +// Transfer moves playback to the selected device, which is required here. +func (s *Service) Transfer(ctx context.Context, selector string, play bool) (Device, error) { + if strings.TrimSpace(selector) == "" { + return Device{}, errors.New("a device is required; call the devices tool to see the names") + } + dev, err := s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Transfer(ctx, id, play) }) + if err != nil { + return Device{}, err + } + return *dev, nil +} + +// control resolves the selector, runs cmd on the device and explains a +// missing active device. +func (s *Service) control(ctx context.Context, selector string, cmd func(DeviceID) error) (*Device, error) { + dev, err := s.resolve(ctx, selector) + if err != nil { + return nil, err + } + var id DeviceID + if dev != nil { + id = dev.ID + } + if err := cmd(id); err != nil { + if errors.Is(err, ErrNoActiveDevice) { + online, _ := s.spotify.Devices(ctx) // best effort, only for the message + return nil, &NoActiveDeviceError{Online: online} + } + return nil, err + } + return dev, nil +} + +// resolve finds the device a selector means: exact ID, then exact name +// (ignoring case), then a single device whose name contains the selector or +// whose type equals it. An empty selector returns nil, the active device. +func (s *Service) resolve(ctx context.Context, selector string) (*Device, error) { + selector = strings.TrimSpace(selector) + if selector == "" { + return nil, nil + } + devs, err := s.spotify.Devices(ctx) + if err != nil { + return nil, err + } + for _, d := range devs { + if string(d.ID) == selector || strings.EqualFold(d.Name, selector) { + return &d, nil + } + } + var matches []Device + lower := strings.ToLower(selector) + for _, d := range devs { + if strings.Contains(strings.ToLower(d.Name), lower) || strings.EqualFold(d.Type, selector) { + matches = append(matches, d) + } + } + if len(matches) == 1 { + return &matches[0], nil + } + return nil, &DeviceNotFoundError{Selector: selector, Online: devs, Ambiguous: len(matches) > 1} +} diff --git a/internal/spotify/api.go b/internal/spotify/api.go new file mode 100644 index 0000000..46b508f --- /dev/null +++ b/internal/spotify/api.go @@ -0,0 +1,145 @@ +// Package spotify adapts the Spotify Web API and Spotify's OAuth server to the +// ports of the account and playback packages. Spotify's JSON formats stay in +// this package. +package spotify + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/subpathdev/spotify-mcp/internal/playback" +) + +// DefaultAPIURL is the Web API's base URL. +const DefaultAPIURL = "https://api.spotify.com/v1" + +const maxBody = 4 << 20 + +// API sends requests to the Web API with a given access token. +type API struct { + base string + http *http.Client +} + +// NewAPI returns an API for baseURL (DefaultAPIURL in production). httpClient +// may be nil. +func NewAPI(baseURL string, httpClient *http.Client) *API { + if httpClient == nil { + httpClient = &http.Client{Timeout: 15 * time.Second} + } + return &API{base: strings.TrimRight(baseURL, "/"), http: httpClient} +} + +// Error is an error answer from the Web API that has no domain meaning. +type Error struct { + Status int + Message string + Reason string +} + +func (e *Error) Error() string { + msg := fmt.Sprintf("spotify API error %d", e.Status) + if e.Message != "" { + msg += ": " + e.Message + } + if e.Reason != "" { + msg += " (" + e.Reason + ")" + } + return msg +} + +// errUnauthorized marks a 401, which the Player answers by invalidating the +// access token. +var errUnauthorized = errors.New("spotify rejected the access token") + +// request describes one Web API call. +type request struct { + method string + path string + query url.Values + body any // JSON-encoded if not nil + out any // JSON-decoded from the answer if not nil +} + +// do sends req and returns the HTTP status. A 204 leaves req.out untouched. +func (a *API) do(ctx context.Context, token string, req request) (int, error) { + u := a.base + req.path + if len(req.query) > 0 { + u += "?" + req.query.Encode() + } + var body io.Reader = http.NoBody + if req.body != nil { + b, err := json.Marshal(req.body) + if err != nil { + return 0, err + } + body = bytes.NewReader(b) + } + hr, err := http.NewRequestWithContext(ctx, req.method, u, body) + if err != nil { + return 0, err + } + hr.Header.Set("Authorization", "Bearer "+token) + if req.body != nil { + hr.Header.Set("Content-Type", "application/json") + } + resp, err := a.http.Do(hr) + if err != nil { + return 0, err + } + defer func() { _ = resp.Body.Close() }() + data, err := io.ReadAll(io.LimitReader(resp.Body, maxBody)) + if err != nil { + return resp.StatusCode, err + } + if resp.StatusCode >= 300 { + return resp.StatusCode, apiError(resp, data) + } + if req.out != nil && resp.StatusCode != http.StatusNoContent && len(bytes.TrimSpace(data)) > 0 { + if err := json.Unmarshal(data, req.out); err != nil { + return resp.StatusCode, fmt.Errorf("decode Spotify answer: %w", err) + } + } + return resp.StatusCode, nil +} + +func apiError(resp *http.Response, data []byte) error { + var e struct { + Error struct { + Message string `json:"message"` + Reason string `json:"reason"` + } `json:"error"` + } + _ = json.Unmarshal(data, &e) // not every error answer is JSON + switch { + case e.Error.Reason == "NO_ACTIVE_DEVICE": + return playback.ErrNoActiveDevice + case e.Error.Reason == "PREMIUM_REQUIRED": + return playback.ErrPremiumRequired + case resp.StatusCode == http.StatusUnauthorized: + return errUnauthorized + case resp.StatusCode == http.StatusTooManyRequests: + msg := "rate limited by Spotify, try again shortly" + if s, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil { + msg = fmt.Sprintf("rate limited by Spotify, try again in %d s", s) + } + return &Error{Status: resp.StatusCode, Message: msg} + } + msg := e.Error.Message + if msg == "" { + msg = strings.TrimSpace(string(data)) + if len(msg) > 200 { + msg = msg[:200] + } + } + return &Error{Status: resp.StatusCode, Message: msg, Reason: e.Error.Reason} +} diff --git a/internal/spotify/auth.go b/internal/spotify/auth.go new file mode 100644 index 0000000..a6d05f2 --- /dev/null +++ b/internal/spotify/auth.go @@ -0,0 +1,129 @@ +package spotify + +import ( + "context" + "errors" + "net/http" + + "golang.org/x/oauth2" + + "github.com/subpathdev/spotify-mcp/internal/account" +) + +// Scopes the server asks for at login: read and control playback, nothing +// else. No library, playlist or e-mail access. +var Scopes = []string{ + "user-read-playback-state", + "user-modify-playback-state", + "user-read-currently-playing", +} + +// DefaultEndpoint is Spotify's OAuth endpoint. The client secret goes in the +// Authorization header, as Spotify documents. +var DefaultEndpoint = oauth2.Endpoint{ + AuthURL: "https://accounts.spotify.com/authorize", + TokenURL: "https://accounts.spotify.com/api/token", + AuthStyle: oauth2.AuthStyleInHeader, +} + +// OAuthConfig configures OAuth. +type OAuthConfig struct { + ClientID string + ClientSecret string + RedirectURL string + Endpoint oauth2.Endpoint // DefaultEndpoint if empty + HTTPClient *http.Client // may be nil +} + +// OAuth implements account.OAuth. +type OAuth struct { + cfg oauth2.Config + http *http.Client +} + +var _ account.OAuth = (*OAuth)(nil) + +// NewOAuth returns an OAuth for cfg. +func NewOAuth(cfg OAuthConfig) *OAuth { + ep := cfg.Endpoint + if ep.TokenURL == "" { + ep = DefaultEndpoint + } + return &OAuth{ + cfg: oauth2.Config{ + ClientID: cfg.ClientID, ClientSecret: cfg.ClientSecret, RedirectURL: cfg.RedirectURL, + Endpoint: ep, Scopes: Scopes, + }, + http: cfg.HTTPClient, + } +} + +func (o *OAuth) ctx(ctx context.Context) context.Context { + if o.http == nil { + return ctx + } + return context.WithValue(ctx, oauth2.HTTPClient, o.http) +} + +// AuthCodeURL implements account.OAuth. show_dialog makes Spotify always show +// its consent page, so someone on a shared browser sees which account they +// are about to connect. +func (o *OAuth) AuthCodeURL(state, verifier string) string { + return o.cfg.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier), oauth2.SetAuthURLParam("show_dialog", "true")) +} + +// Exchange implements account.OAuth. +func (o *OAuth) Exchange(ctx context.Context, code, verifier string) (account.Token, error) { + t, err := o.cfg.Exchange(o.ctx(ctx), code, oauth2.VerifierOption(verifier)) + if err != nil { + return account.Token{}, mapOAuthError(err) + } + return account.Token{AccessToken: t.AccessToken, RefreshToken: t.RefreshToken, Expiry: t.Expiry}, nil +} + +// Refresh implements account.OAuth. +func (o *OAuth) Refresh(ctx context.Context, refreshToken string) (account.Token, error) { + t, err := o.cfg.TokenSource(o.ctx(ctx), &oauth2.Token{RefreshToken: refreshToken}).Token() + if err != nil { + return account.Token{}, mapOAuthError(err) + } + // oauth2 copies the old refresh token when Spotify sends none; report the + // new one only if it changed. + rt := t.RefreshToken + if rt == refreshToken { + rt = "" + } + return account.Token{AccessToken: t.AccessToken, RefreshToken: rt, Expiry: t.Expiry}, nil +} + +func mapOAuthError(err error) error { + var re *oauth2.RetrieveError + if errors.As(err, &re) { + switch re.ErrorCode { + case "invalid_grant": + return account.ErrRevoked + case "invalid_client": + return account.ErrInvalidClient + } + } + return err +} + +// User implements account.Identity. Spotify answers 403 for accounts that +// aren't on a development-mode app's user list. +func (a *API) User(ctx context.Context, accessToken string) (account.User, error) { + var out struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + } + status, err := a.do(ctx, accessToken, request{method: http.MethodGet, path: "/me", out: &out}) + if status == http.StatusForbidden { + return account.User{}, account.ErrNotAllowlisted + } + if err != nil { + return account.User{}, err + } + return account.User{ID: out.ID, DisplayName: out.DisplayName}, nil +} + +var _ account.Identity = (*API)(nil) diff --git a/internal/spotify/client.go b/internal/spotify/client.go deleted file mode 100644 index b6bf018..0000000 --- a/internal/spotify/client.go +++ /dev/null @@ -1,459 +0,0 @@ -// Package spotify is a small client for the parts of the Spotify Web API this -// server needs: playback control, devices and search. It keeps the OAuth token -// of one profile in the store and writes it back whenever Spotify refreshes it. -package spotify - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/oauth2" - - "github.com/subpathdev/spotify-mcp/internal/store" -) - -// Scopes the server asks for at login: read and control playback, nothing else. -// No library, playlist or e-mail access. -var Scopes = []string{ - "user-read-playback-state", - "user-modify-playback-state", - "user-read-currently-playing", -} - -// Endpoint is Spotify's OAuth endpoint. The client secret goes in the -// Authorization header, as Spotify documents. -var Endpoint = oauth2.Endpoint{ - AuthURL: "https://accounts.spotify.com/authorize", - TokenURL: "https://accounts.spotify.com/api/token", - AuthStyle: oauth2.AuthStyleInHeader, -} - -// MaxSearchLimit is the most results Spotify returns per search for apps in -// development mode (February 2026 rules). -const MaxSearchLimit = 10 - -var ( - // ErrNotConnected means nobody has connected a Spotify account to the profile - // yet, or Spotify revoked the access. - ErrNotConnected = errors.New("no Spotify account is connected yet: create an invite link (spotify-mcp invite) and open it to connect one") - // ErrNoActiveDevice is Spotify's NO_ACTIVE_DEVICE. - ErrNoActiveDevice = errors.New("no active Spotify device") - // ErrPremiumRequired is Spotify's PREMIUM_REQUIRED. - ErrPremiumRequired = errors.New("playback control needs Spotify Premium (both for the app owner and the connected account)") -) - -// APIError is any other error answer from the Web API. -type APIError struct { - Status int - Message string - Reason string -} - -func (e *APIError) Error() string { - msg := fmt.Sprintf("Spotify API error %d", e.Status) - if e.Message != "" { - msg += ": " + e.Message - } - if e.Reason != "" { - msg += " (" + e.Reason + ")" - } - return msg -} - -// Client talks to the Web API for one profile. -type Client struct { - oauth *oauth2.Config - store *store.Store - profile string - http *http.Client // used for API and token calls - apiBase string - - mu sync.Mutex - tok *oauth2.Token -} - -// NewClient returns a client for profile. httpClient may be nil. -func NewClient(cfg *oauth2.Config, st *store.Store, profile string, httpClient *http.Client) *Client { - if httpClient == nil { - httpClient = &http.Client{Timeout: 15 * time.Second} - } - return &Client{oauth: cfg, store: st, profile: profile, http: httpClient, apiBase: "https://api.spotify.com/v1"} -} - -// SetAPIBase points the client at another server (tests). -func (c *Client) SetAPIBase(u string) { c.apiBase = strings.TrimRight(u, "/") } - -// Forget drops the cached token, e.g. after a new login or a disconnect. -func (c *Client) Forget() { - c.mu.Lock() - c.tok = nil - c.mu.Unlock() -} - -// token returns a valid access token, refreshing and persisting it if needed. -func (c *Client) token(ctx context.Context) (*oauth2.Token, error) { - c.mu.Lock() - defer c.mu.Unlock() - if c.tok == nil { - st, err := c.store.Token(c.profile) - if errors.Is(err, store.ErrNotFound) { - return nil, ErrNotConnected - } - if err != nil { - return nil, fmt.Errorf("load token: %w", err) - } - c.tok = &oauth2.Token{RefreshToken: st.RefreshToken, AccessToken: st.AccessToken, Expiry: st.Expiry, TokenType: "Bearer"} - } - if c.tok.Valid() { - return c.tok, nil - } - ctx = context.WithValue(ctx, oauth2.HTTPClient, c.http) - nt, err := c.oauth.TokenSource(ctx, c.tok).Token() - if err != nil { - var re *oauth2.RetrieveError - if errors.As(err, &re) && re.ErrorCode == "invalid_grant" { - // Revoked at Spotify or the app's secret changed: a new login is needed. - c.tok = nil - return nil, ErrNotConnected - } - return nil, fmt.Errorf("refresh Spotify token: %w", err) - } - // Spotify may or may not send a new refresh token; either way the current - // one goes to disk before it's used, so a pod restart keeps working. - st, err := c.store.Token(c.profile) - if err != nil && !errors.Is(err, store.ErrNotFound) { - return nil, err - } - st.RefreshToken = nt.RefreshToken - st.AccessToken = nt.AccessToken - st.Expiry = nt.Expiry - if err := c.store.SaveToken(c.profile, st); err != nil { - return nil, fmt.Errorf("save refreshed token: %w", err) - } - c.tok = nt - return nt, nil -} - -// do sends one API request. body is JSON-encoded if not nil; out is decoded -// from a JSON answer if not nil. A 204 leaves out untouched. -func (c *Client) do(ctx context.Context, method, path string, query url.Values, body, out any) (int, error) { - tok, err := c.token(ctx) - if err != nil { - return 0, err - } - u := c.apiBase + path - if len(query) > 0 { - u += "?" + query.Encode() - } - var rd io.Reader - if body != nil { - b, err := json.Marshal(body) - if err != nil { - return 0, err - } - rd = bytes.NewReader(b) - } - req, err := http.NewRequestWithContext(ctx, method, u, rd) - if err != nil { - return 0, err - } - req.Header.Set("Authorization", "Bearer "+tok.AccessToken) - if body != nil { - req.Header.Set("Content-Type", "application/json") - } else if method == http.MethodPut || method == http.MethodPost { - req.ContentLength = 0 - } - resp, err := c.http.Do(req) - if err != nil { - return 0, err - } - defer func() { _ = resp.Body.Close() }() - data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) - if err != nil { - return resp.StatusCode, err - } - if resp.StatusCode >= 300 { - return resp.StatusCode, c.apiError(resp, data) - } - if out != nil && resp.StatusCode != http.StatusNoContent && len(bytes.TrimSpace(data)) > 0 { - if err := json.Unmarshal(data, out); err != nil { - return resp.StatusCode, fmt.Errorf("decode Spotify answer: %w", err) - } - } - return resp.StatusCode, nil -} - -func (c *Client) apiError(resp *http.Response, data []byte) error { - var e struct { - Error struct { - Status int `json:"status"` - Message string `json:"message"` - Reason string `json:"reason"` - } `json:"error"` - } - _ = json.Unmarshal(data, &e) - switch { - case e.Error.Reason == "NO_ACTIVE_DEVICE": - return ErrNoActiveDevice - case e.Error.Reason == "PREMIUM_REQUIRED": - return ErrPremiumRequired - case resp.StatusCode == http.StatusUnauthorized: - // The access token was rejected although it looked valid: drop it so the - // next call refreshes. - c.mu.Lock() - if c.tok != nil { - c.tok.Expiry = time.Unix(1, 0) - } - c.mu.Unlock() - case resp.StatusCode == http.StatusTooManyRequests: - wait := resp.Header.Get("Retry-After") - if s, err := strconv.Atoi(wait); err == nil { - return &APIError{Status: 429, Message: fmt.Sprintf("rate limited by Spotify, try again in %d s", s)} - } - return &APIError{Status: 429, Message: "rate limited by Spotify, try again shortly"} - } - msg := e.Error.Message - if msg == "" { - msg = strings.TrimSpace(string(data)) - if len(msg) > 200 { - msg = msg[:200] - } - } - return &APIError{Status: resp.StatusCode, Message: msg, Reason: e.Error.Reason} -} - -// User is the connected account. -type User struct { - ID string `json:"id"` - DisplayName string `json:"display_name"` -} - -// Me returns the connected account. -func (c *Client) Me(ctx context.Context) (User, error) { - var u User - _, err := c.do(ctx, http.MethodGet, "/me", nil, nil, &u) - return u, err -} - -// Device is a Spotify Connect device. -type Device struct { - ID string `json:"id"` - Name string `json:"name"` - Type string `json:"type"` - IsActive bool `json:"is_active"` - IsRestricted bool `json:"is_restricted"` - VolumePercent *int `json:"volume_percent,omitempty"` -} - -// Devices lists the account's devices that Spotify currently sees. -func (c *Client) Devices(ctx context.Context) ([]Device, error) { - var out struct { - Devices []Device `json:"devices"` - } - _, err := c.do(ctx, http.MethodGet, "/me/player/devices", nil, nil, &out) - return out.Devices, err -} - -// Item is one search result or the playing item. -type Item struct { - Type string `json:"type"` - Name string `json:"name"` - URI string `json:"uri"` - Artists string `json:"artists,omitempty"` - Album string `json:"album,omitempty"` - Owner string `json:"owner,omitempty"` -} - -type apiArtist struct { - Name string `json:"name"` -} - -type apiItem struct { - Type string `json:"type"` - Name string `json:"name"` - URI string `json:"uri"` - Artists []apiArtist `json:"artists"` - Album *struct { - Name string `json:"name"` - } `json:"album"` - Owner *struct { - DisplayName string `json:"display_name"` - } `json:"owner"` - Show *struct { - Name string `json:"name"` - } `json:"show"` - DurationMS int `json:"duration_ms"` -} - -func (a apiItem) item() Item { - it := Item{Type: a.Type, Name: a.Name, URI: a.URI} - names := make([]string, 0, len(a.Artists)) - for _, ar := range a.Artists { - names = append(names, ar.Name) - } - it.Artists = strings.Join(names, ", ") - if a.Album != nil { - it.Album = a.Album.Name - } - if a.Owner != nil { - it.Owner = a.Owner.DisplayName - } - if a.Show != nil { - it.Album = a.Show.Name - } - return it -} - -// SearchTypes are the types Search accepts. -var SearchTypes = []string{"track", "album", "artist", "playlist", "show", "episode"} - -// Search returns up to limit results (1-10) of one type. -func (c *Client) Search(ctx context.Context, query, typ string, limit int) ([]Item, error) { - if strings.TrimSpace(query) == "" { - return nil, errors.New("search query is empty") - } - if typ == "" { - typ = "track" - } - valid := false - for _, t := range SearchTypes { - if t == typ { - valid = true - } - } - if !valid { - return nil, fmt.Errorf("unknown search type %q (use one of %s)", typ, strings.Join(SearchTypes, ", ")) - } - if limit <= 0 { - limit = 5 - } - if limit > MaxSearchLimit { - limit = MaxSearchLimit - } - q := url.Values{"q": {query}, "type": {typ}, "limit": {strconv.Itoa(limit)}} - var out map[string]struct { - Items []*apiItem `json:"items"` - } - if _, err := c.do(ctx, http.MethodGet, "/search", q, nil, &out); err != nil { - return nil, err - } - var items []Item - for _, it := range out[typ+"s"].Items { - if it == nil { // Spotify sometimes returns null entries for playlists - continue - } - items = append(items, it.item()) - } - return items, nil -} - -func deviceQuery(deviceID string) url.Values { - if deviceID == "" { - return nil - } - return url.Values{"device_id": {deviceID}} -} - -// Play starts playing uri on deviceID (empty: the active device). A track or -// episode URI plays on its own; an album, artist, playlist or show URI plays -// as a context. An empty uri resumes. -func (c *Client) Play(ctx context.Context, deviceID, uri string) error { - var body any - if uri != "" { - kind, err := URIType(uri) - if err != nil { - return err - } - switch kind { - case "track", "episode": - body = map[string]any{"uris": []string{uri}} - default: - body = map[string]any{"context_uri": uri} - } - } - _, err := c.do(ctx, http.MethodPut, "/me/player/play", deviceQuery(deviceID), body, nil) - return err -} - -// Pause pauses playback. -func (c *Client) Pause(ctx context.Context, deviceID string) error { - _, err := c.do(ctx, http.MethodPut, "/me/player/pause", deviceQuery(deviceID), nil, nil) - return err -} - -// Next skips to the next item. -func (c *Client) Next(ctx context.Context, deviceID string) error { - _, err := c.do(ctx, http.MethodPost, "/me/player/next", deviceQuery(deviceID), nil, nil) - return err -} - -// Previous goes back to the previous item. -func (c *Client) Previous(ctx context.Context, deviceID string) error { - _, err := c.do(ctx, http.MethodPost, "/me/player/previous", deviceQuery(deviceID), nil, nil) - return err -} - -// Transfer moves playback to deviceID; play starts it there even if it was paused. -func (c *Client) Transfer(ctx context.Context, deviceID string, play bool) error { - body := map[string]any{"device_ids": []string{deviceID}, "play": play} - _, err := c.do(ctx, http.MethodPut, "/me/player", nil, body, nil) - return err -} - -// Playback is the current playback state. -type Playback struct { - IsPlaying bool `json:"is_playing"` - Device *Device `json:"device,omitempty"` - Item *Item `json:"item,omitempty"` - // ProgressMS and DurationMS of the item. - ProgressMS int `json:"progress_ms"` - DurationMS int `json:"duration_ms"` -} - -// NowPlaying returns the playback state, or nil when nothing is playing anywhere. -func (c *Client) NowPlaying(ctx context.Context) (*Playback, error) { - var out struct { - IsPlaying bool `json:"is_playing"` - ProgressMS int `json:"progress_ms"` - Device *Device `json:"device"` - Item *apiItem `json:"item"` - } - status, err := c.do(ctx, http.MethodGet, "/me/player", url.Values{"additional_types": {"track,episode"}}, nil, &out) - if err != nil { - return nil, err - } - if status == http.StatusNoContent { - return nil, nil - } - p := &Playback{IsPlaying: out.IsPlaying, Device: out.Device, ProgressMS: out.ProgressMS} - if out.Item != nil { - it := out.Item.item() - p.Item = &it - p.DurationMS = out.Item.DurationMS - } - return p, nil -} - -// URIType checks a spotify:: URI (or an open.spotify.com link, -// which it doesn't convert) and returns its type. -func URIType(uri string) (string, error) { - parts := strings.Split(uri, ":") - if len(parts) != 3 || parts[0] != "spotify" || parts[2] == "" { - return "", fmt.Errorf("%q is not a Spotify URI like spotify:track:", uri) - } - switch parts[1] { - case "track", "episode", "album", "artist", "playlist", "show": - return parts[1], nil - } - return "", fmt.Errorf("unsupported Spotify URI type %q", parts[1]) -} diff --git a/internal/spotify/client_test.go b/internal/spotify/client_test.go deleted file mode 100644 index 097554a..0000000 --- a/internal/spotify/client_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package spotify - -import ( - "context" - "encoding/json" - "errors" - "io" - "net/http" - "net/http/httptest" - "strings" - "sync/atomic" - "testing" - "time" - - "golang.org/x/oauth2" - - "github.com/subpathdev/spotify-mcp/internal/store" -) - -type fakeSpotify struct { - *httptest.Server - refreshes atomic.Int32 - lastBody atomic.Value - lastPath atomic.Value -} - -func newFake(t *testing.T) *fakeSpotify { - f := &fakeSpotify{} - mux := http.NewServeMux() - mux.HandleFunc("POST /api/token", func(w http.ResponseWriter, r *http.Request) { - _ = r.ParseForm() - if r.PostForm.Get("grant_type") != "refresh_token" || r.PostForm.Get("refresh_token") != "r1" { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusBadRequest) - _, _ = io.WriteString(w, `{"error":"invalid_grant","error_description":"Refresh token revoked"}`) - return - } - f.refreshes.Add(1) - w.Header().Set("Content-Type", "application/json") - // Spotify rotates the refresh token here. - _, _ = io.WriteString(w, `{"access_token":"a2","token_type":"Bearer","expires_in":3600,"refresh_token":"r2"}`) - }) - api := func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Authorization") != "Bearer a2" { - w.WriteHeader(http.StatusUnauthorized) - return - } - b, _ := io.ReadAll(r.Body) - f.lastBody.Store(string(b)) - f.lastPath.Store(r.Method + " " + r.URL.Path + "?" + r.URL.RawQuery) - switch r.URL.Path { - case "/v1/me/player/devices": - _, _ = io.WriteString(w, `{"devices":[{"id":"d1","name":"Pixel","type":"Smartphone","is_active":false}]}`) - case "/v1/me/player/pause": - w.WriteHeader(http.StatusNotFound) - _, _ = io.WriteString(w, `{"error":{"status":404,"message":"Player command failed: No active device found","reason":"NO_ACTIVE_DEVICE"}}`) - case "/v1/me/player": - if r.Method == http.MethodGet { - w.WriteHeader(http.StatusNoContent) - return - } - w.WriteHeader(http.StatusNoContent) - case "/v1/search": - if r.URL.Query().Get("limit") != "10" { - t.Errorf("search limit %q, want clamped to 10", r.URL.Query().Get("limit")) - } - _, _ = io.WriteString(w, `{"tracks":{"items":[{"type":"track","name":"Song","uri":"spotify:track:1","artists":[{"name":"A"},{"name":"B"}],"album":{"name":"Al"}},null]}}`) - default: - w.WriteHeader(http.StatusNoContent) - } - } - mux.HandleFunc("/v1/", api) - f.Server = httptest.NewServer(mux) - t.Cleanup(f.Close) - return f -} - -func setup(t *testing.T) (*Client, *store.Store, *fakeSpotify) { - f := newFake(t) - st, err := store.Open(t.TempDir()) - if err != nil { - t.Fatal(err) - } - // An expired access token, so the first call has to refresh. - if err := st.SaveToken("default", store.Token{RefreshToken: "r1", AccessToken: "old", Expiry: time.Now().Add(-time.Hour), DisplayName: "Jan"}); err != nil { - t.Fatal(err) - } - cfg := &oauth2.Config{ClientID: "id", ClientSecret: "secret", Endpoint: oauth2.Endpoint{TokenURL: f.URL + "/api/token", AuthStyle: oauth2.AuthStyleInHeader}} - c := NewClient(cfg, st, "default", f.Client()) - c.SetAPIBase(f.URL + "/v1") - return c, st, f -} - -func TestRefreshIsPersisted(t *testing.T) { - c, st, f := setup(t) - ctx := context.Background() - devs, err := c.Devices(ctx) - if err != nil { - t.Fatal(err) - } - if len(devs) != 1 || devs[0].Name != "Pixel" { - t.Fatalf("devices: %+v", devs) - } - got, _ := st.Token("default") - if got.RefreshToken != "r2" || got.AccessToken != "a2" || got.DisplayName != "Jan" { - t.Fatalf("rotated token not saved (or profile info lost): %+v", got) - } - // Cached: no second refresh. - if _, err := c.Devices(ctx); err != nil { - t.Fatal(err) - } - if n := f.refreshes.Load(); n != 1 { - t.Fatalf("refreshes = %d, want 1", n) - } -} - -func TestRevokedTokenMeansNotConnected(t *testing.T) { - c, st, _ := setup(t) - _ = st.SaveToken("default", store.Token{RefreshToken: "revoked"}) - c.Forget() - if _, err := c.Devices(context.Background()); !errors.Is(err, ErrNotConnected) { - t.Fatalf("got %v, want ErrNotConnected", err) - } -} - -func TestNoToken(t *testing.T) { - c, st, _ := setup(t) - _ = st.DeleteToken("default") - c.Forget() - if err := c.Pause(context.Background(), ""); !errors.Is(err, ErrNotConnected) { - t.Fatalf("got %v", err) - } -} - -func TestNoActiveDevice(t *testing.T) { - c, _, _ := setup(t) - if err := c.Pause(context.Background(), ""); !errors.Is(err, ErrNoActiveDevice) { - t.Fatalf("got %v, want ErrNoActiveDevice", err) - } -} - -func TestPlayBodies(t *testing.T) { - c, _, f := setup(t) - ctx := context.Background() - cases := []struct{ uri, want string }{ - {"spotify:track:1", `{"uris":["spotify:track:1"]}`}, - {"spotify:album:2", `{"context_uri":"spotify:album:2"}`}, - {"", ``}, - } - for _, tc := range cases { - if err := c.Play(ctx, "d1", tc.uri); err != nil { - t.Fatal(err) - } - if got := f.lastBody.Load().(string); got != tc.want { - t.Errorf("play %q body %s, want %s", tc.uri, got, tc.want) - } - if got := f.lastPath.Load().(string); got != "PUT /v1/me/player/play?device_id=d1" { - t.Errorf("path %s", got) - } - } - if err := c.Play(ctx, "", "https://open.spotify.com/track/1"); err == nil { - t.Error("URL accepted as URI") - } -} - -func TestTransferAndSearch(t *testing.T) { - c, _, f := setup(t) - ctx := context.Background() - if err := c.Transfer(ctx, "d1", true); err != nil { - t.Fatal(err) - } - var body map[string]any - _ = json.Unmarshal([]byte(f.lastBody.Load().(string)), &body) - if body["play"] != true || body["device_ids"].([]any)[0] != "d1" { - t.Fatalf("transfer body %v", body) - } - items, err := c.Search(ctx, "song", "track", 50) - if err != nil { - t.Fatal(err) - } - if len(items) != 1 || items[0].Artists != "A, B" || items[0].Album != "Al" { - t.Fatalf("items %+v", items) - } - if _, err := c.Search(ctx, "x", "podcast", 1); err == nil || !strings.Contains(err.Error(), "unknown search type") { - t.Fatalf("bad type: %v", err) - } - pb, err := c.NowPlaying(ctx) - if err != nil || pb != nil { - t.Fatalf("now playing on 204: %+v %v", pb, err) - } -} diff --git a/internal/spotify/player.go b/internal/spotify/player.go new file mode 100644 index 0000000..11c96b1 --- /dev/null +++ b/internal/spotify/player.go @@ -0,0 +1,223 @@ +package spotify + +import ( + "context" + "errors" + "net/http" + "net/url" + "strconv" + "time" + + "github.com/subpathdev/spotify-mcp/internal/playback" +) + +// TokenSource provides the access token of the connected account. +type TokenSource interface { + AccessToken(ctx context.Context) (string, error) + // Invalidate is called after Spotify rejected accessToken. + Invalidate(ctx context.Context, accessToken string) error +} + +// Player implements playback.Spotify for one connected account. +type Player struct { + api *API + tokens TokenSource +} + +var _ playback.Spotify = (*Player)(nil) + +// NewPlayer returns a Player that authenticates with tokens. +func NewPlayer(api *API, tokens TokenSource) *Player { + return &Player{api: api, tokens: tokens} +} + +// do sends req with the account's token. After a 401 it invalidates the token +// and tries once more with a fresh one. +func (p *Player) do(ctx context.Context, req request) (int, error) { + for attempt := 0; ; attempt++ { + tok, err := p.tokens.AccessToken(ctx) + if err != nil { + return 0, err + } + status, err := p.api.do(ctx, tok, req) + if !errors.Is(err, errUnauthorized) || attempt > 0 { + return status, err + } + if err := p.tokens.Invalidate(ctx, tok); err != nil { + return status, err + } + } +} + +type wireDevice struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + IsActive bool `json:"is_active"` + IsRestricted bool `json:"is_restricted"` +} + +func (d wireDevice) device() playback.Device { + return playback.Device{ + ID: playback.DeviceID(d.ID), Name: d.Name, Type: d.Type, + Active: d.IsActive, Restricted: d.IsRestricted, + } +} + +type wireName struct { + Name string `json:"name"` +} + +type wireItem struct { + Type string `json:"type"` + Name string `json:"name"` + URI string `json:"uri"` + Artists []wireName `json:"artists"` + Album *wireName `json:"album"` + Show *wireName `json:"show"` + Owner *struct { + DisplayName string `json:"display_name"` + } `json:"owner"` + DurationMS int `json:"duration_ms"` +} + +// item maps a wire item; ok is false for items this server can't play. +func (w wireItem) item() (playback.Item, bool) { + uri, err := playback.ParseURI(w.URI) + if err != nil { + return playback.Item{}, false + } + it := playback.Item{ + Kind: uri.Kind(), Name: w.Name, URI: uri, + Duration: time.Duration(w.DurationMS) * time.Millisecond, + } + for _, a := range w.Artists { + it.Artists = append(it.Artists, a.Name) + } + switch { + case w.Album != nil: + it.Album = w.Album.Name + case w.Show != nil: + it.Album = w.Show.Name + } + if w.Owner != nil { + it.Owner = w.Owner.DisplayName + } + return it, true +} + +// Devices implements playback.Spotify. +func (p *Player) Devices(ctx context.Context) ([]playback.Device, error) { + var out struct { + Devices []wireDevice `json:"devices"` + } + if _, err := p.do(ctx, request{method: http.MethodGet, path: "/me/player/devices", out: &out}); err != nil { + return nil, err + } + devs := make([]playback.Device, len(out.Devices)) + for i, d := range out.Devices { + devs[i] = d.device() + } + return devs, nil +} + +// Search implements playback.Spotify. +func (p *Player) Search(ctx context.Context, query string, kind playback.Kind, limit int) ([]playback.Item, error) { + limit = min(max(limit, 1), playback.MaxSearchResults) + q := url.Values{"q": {query}, "type": {string(kind)}, "limit": {strconv.Itoa(limit)}} + var out map[string]struct { + Items []*wireItem `json:"items"` + } + if _, err := p.do(ctx, request{method: http.MethodGet, path: "/search", query: q, out: &out}); err != nil { + return nil, err + } + var items []playback.Item + for _, w := range out[string(kind)+"s"].Items { + if w == nil { // Spotify returns null entries for some playlists + continue + } + if it, ok := w.item(); ok { + items = append(items, it) + } + } + return items, nil +} + +func deviceQuery(id playback.DeviceID) url.Values { + if id == "" { + return nil + } + return url.Values{"device_id": {string(id)}} +} + +// Play implements playback.Spotify. A track or episode plays on its own; an +// album, artist, playlist or show plays as a context. +func (p *Player) Play(ctx context.Context, device playback.DeviceID, uri playback.URI) error { + var body any = map[string]any{"uris": []string{uri.String()}} + if uri.Kind().IsContext() { + body = map[string]any{"context_uri": uri.String()} + } + _, err := p.do(ctx, request{method: http.MethodPut, path: "/me/player/play", query: deviceQuery(device), body: body}) + return err +} + +func (p *Player) command(ctx context.Context, method, path string, device playback.DeviceID) error { + _, err := p.do(ctx, request{method: method, path: path, query: deviceQuery(device)}) + return err +} + +// Resume implements playback.Spotify. +func (p *Player) Resume(ctx context.Context, device playback.DeviceID) error { + return p.command(ctx, http.MethodPut, "/me/player/play", device) +} + +// Pause implements playback.Spotify. +func (p *Player) Pause(ctx context.Context, device playback.DeviceID) error { + return p.command(ctx, http.MethodPut, "/me/player/pause", device) +} + +// Next implements playback.Spotify. +func (p *Player) Next(ctx context.Context, device playback.DeviceID) error { + return p.command(ctx, http.MethodPost, "/me/player/next", device) +} + +// Previous implements playback.Spotify. +func (p *Player) Previous(ctx context.Context, device playback.DeviceID) error { + return p.command(ctx, http.MethodPost, "/me/player/previous", device) +} + +// Transfer implements playback.Spotify. +func (p *Player) Transfer(ctx context.Context, device playback.DeviceID, play bool) error { + body := map[string]any{"device_ids": []string{string(device)}, "play": play} + _, err := p.do(ctx, request{method: http.MethodPut, path: "/me/player", body: body}) + return err +} + +// State implements playback.Spotify. +func (p *Player) State(ctx context.Context) (*playback.State, error) { + var out struct { + IsPlaying bool `json:"is_playing"` + ProgressMS int `json:"progress_ms"` + Device *wireDevice `json:"device"` + Item *wireItem `json:"item"` + } + q := url.Values{"additional_types": {"track,episode"}} + status, err := p.do(ctx, request{method: http.MethodGet, path: "/me/player", query: q, out: &out}) + if err != nil { + return nil, err + } + if status == http.StatusNoContent { + return nil, nil + } + st := &playback.State{Playing: out.IsPlaying, Progress: time.Duration(out.ProgressMS) * time.Millisecond} + if out.Device != nil { + d := out.Device.device() + st.Device = &d + } + if out.Item != nil { + if it, ok := out.Item.item(); ok { + st.Item = &it + } + } + return st, nil +} diff --git a/internal/spotify/spotify_test.go b/internal/spotify/spotify_test.go new file mode 100644 index 0000000..4659ba1 --- /dev/null +++ b/internal/spotify/spotify_test.go @@ -0,0 +1,239 @@ +package spotify + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "golang.org/x/oauth2" + + "github.com/subpathdev/spotify-mcp/internal/account" + "github.com/subpathdev/spotify-mcp/internal/playback" +) + +type fakeTokens struct { + mu sync.Mutex + tok string + invalidated []string +} + +func (f *fakeTokens) AccessToken(context.Context) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.tok, nil +} + +func (f *fakeTokens) Invalidate(_ context.Context, tok string) error { + f.mu.Lock() + defer f.mu.Unlock() + f.invalidated = append(f.invalidated, tok) + f.tok = "fresh" + return nil +} + +type call struct{ method, path, query, body, auth string } + +// fakeAPI records calls and answers with the handler for "METHOD /path". +type fakeAPI struct { + mu sync.Mutex + calls []call + routes map[string]http.HandlerFunc +} + +func newPlayer(t *testing.T, routes map[string]http.HandlerFunc) (*Player, *fakeAPI, *fakeTokens) { + t.Helper() + f := &fakeAPI{routes: routes} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + f.mu.Lock() + f.calls = append(f.calls, call{r.Method, r.URL.Path, r.URL.RawQuery, string(b), r.Header.Get("Authorization")}) + f.mu.Unlock() + if h, ok := f.routes[r.Method+" "+r.URL.Path]; ok { + h(w, r) + return + } + w.WriteHeader(http.StatusNoContent) + })) + t.Cleanup(srv.Close) + tokens := &fakeTokens{tok: "t1"} + return NewPlayer(NewAPI(srv.URL, srv.Client()), tokens), f, tokens +} + +func (f *fakeAPI) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.calls) +} + +func (f *fakeAPI) last() call { + f.mu.Lock() + defer f.mu.Unlock() + return f.calls[len(f.calls)-1] +} + +func spotifyError(status int, reason string) http.HandlerFunc { + return func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{"status": status, "message": "nope", "reason": reason}}) + } +} + +func mustURI(t *testing.T, s string) playback.URI { + t.Helper() + u, err := playback.ParseURI(s) + if err != nil { + t.Fatal(err) + } + return u +} + +func TestPlayBodies(t *testing.T) { + ctx := context.Background() + p, api, _ := newPlayer(t, nil) + for uri, want := range map[string]string{ + "spotify:track:1": `{"uris":["spotify:track:1"]}`, + "spotify:episode:2": `{"uris":["spotify:episode:2"]}`, + "spotify:album:3": `{"context_uri":"spotify:album:3"}`, + "spotify:playlist:4": `{"context_uri":"spotify:playlist:4"}`, + } { + if err := p.Play(ctx, "dev1", mustURI(t, uri)); err != nil { + t.Fatal(err) + } + c := api.last() + if c.method != http.MethodPut || c.path != "/me/player/play" || c.query != "device_id=dev1" || c.body != want || c.auth != "Bearer t1" { + t.Errorf("%s: %+v", uri, c) + } + } + if err := p.Resume(ctx, ""); err != nil { + t.Fatal(err) + } + if c := api.last(); c.body != "" || c.query != "" { + t.Errorf("resume: %+v", c) + } + if err := p.Transfer(ctx, "ph1", true); err != nil { + t.Fatal(err) + } + if c := api.last(); c.path != "/me/player" || c.body != `{"device_ids":["ph1"],"play":true}` { + t.Errorf("transfer: %+v", c) + } +} + +func TestErrors(t *testing.T) { + ctx := context.Background() + p, _, _ := newPlayer(t, map[string]http.HandlerFunc{ + "PUT /me/player/pause": spotifyError(404, "NO_ACTIVE_DEVICE"), + "POST /me/player/next": spotifyError(403, "PREMIUM_REQUIRED"), + "POST /me/player/previous": func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Retry-After", "7") + w.WriteHeader(http.StatusTooManyRequests) + }, + }) + if err := p.Pause(ctx, ""); !errors.Is(err, playback.ErrNoActiveDevice) { + t.Errorf("pause: %v", err) + } + if err := p.Next(ctx, ""); !errors.Is(err, playback.ErrPremiumRequired) { + t.Errorf("next: %v", err) + } + var apiErr *Error + if err := p.Previous(ctx, ""); !errors.As(err, &apiErr) || apiErr.Status != 429 || !strings.Contains(err.Error(), "7 s") { + t.Errorf("previous: %v", err) + } +} + +func TestUnauthorizedRetriesOnceWithFreshToken(t *testing.T) { + ctx := context.Background() + p, api, tokens := newPlayer(t, map[string]http.HandlerFunc{ + "PUT /me/player/pause": func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer fresh" { + w.WriteHeader(http.StatusUnauthorized) + return + } + w.WriteHeader(http.StatusNoContent) + }, + }) + if err := p.Pause(ctx, ""); err != nil { + t.Fatal(err) + } + if len(tokens.invalidated) != 1 || tokens.invalidated[0] != "t1" || api.count() != 2 { + t.Fatalf("invalidated %v after %d calls", tokens.invalidated, api.count()) + } +} + +func TestSearchMapsItems(t *testing.T) { + p, api, _ := newPlayer(t, map[string]http.HandlerFunc{ + "GET /search": func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, `{"tracks":{"items":[null, + {"type":"track","name":"Song","uri":"spotify:track:1","duration_ms":61000, + "artists":[{"name":"A"},{"name":"B"}],"album":{"name":"LP"}}, + {"type":"track","name":"Local","uri":"spotify:local:x:y:z"}]}}`) + }, + }) + items, err := p.Search(context.Background(), "song", playback.KindTrack, 50) + if err != nil { + t.Fatal(err) + } + if q := api.last().query; !strings.Contains(q, "limit=10") || !strings.Contains(q, "type=track") { + t.Errorf("query %q", q) + } + if len(items) != 1 { + t.Fatalf("items %+v", items) + } + it := items[0] + if it.Name != "Song" || it.URI.String() != "spotify:track:1" || strings.Join(it.Artists, ",") != "A,B" || it.Album != "LP" || it.Duration.Seconds() != 61 { + t.Fatalf("item %+v", it) + } +} + +func TestStateNothingPlaying(t *testing.T) { + p, _, _ := newPlayer(t, nil) // every call answers 204 + st, err := p.State(context.Background()) + if err != nil || st != nil { + t.Fatalf("%+v %v", st, err) + } +} + +func TestUserNotAllowlisted(t *testing.T) { + srv := httptest.NewServer(spotifyError(http.StatusForbidden, "")) + defer srv.Close() + if _, err := NewAPI(srv.URL, srv.Client()).User(context.Background(), "t"); !errors.Is(err, account.ErrNotAllowlisted) { + t.Fatalf("got %v", err) + } +} + +func TestOAuthErrors(t *testing.T) { + ctx := context.Background() + var answer string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + if answer != "" { + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":"`+answer+`"}`) + return + } + _, _ = io.WriteString(w, `{"access_token":"a2","token_type":"Bearer","expires_in":3600,"refresh_token":"r1"}`) + })) + defer srv.Close() + o := NewOAuth(OAuthConfig{ + ClientID: "id", ClientSecret: "secret", HTTPClient: srv.Client(), + Endpoint: oauth2.Endpoint{TokenURL: srv.URL, AuthStyle: oauth2.AuthStyleInHeader}, + }) + + tok, err := o.Refresh(ctx, "r1") + if err != nil || tok.AccessToken != "a2" || tok.RefreshToken != "" { + t.Fatalf("unchanged refresh token must be reported as empty: %+v %v", tok, err) + } + answer = "invalid_grant" + if _, err := o.Refresh(ctx, "r1"); !errors.Is(err, account.ErrRevoked) { + t.Fatalf("invalid_grant: %v", err) + } + answer = "invalid_client" + if _, err := o.Exchange(ctx, "code", "verifier"); !errors.Is(err, account.ErrInvalidClient) { + t.Fatalf("invalid_client: %v", err) + } +} diff --git a/internal/store/store.go b/internal/store/store.go deleted file mode 100644 index e60a27a..0000000 --- a/internal/store/store.go +++ /dev/null @@ -1,238 +0,0 @@ -// Package store keeps the Spotify tokens and invite links in a data directory, -// usually a small persistent volume. Everything is written owner-only (0600) -// and replaced atomically, so a crash never leaves half a file behind. -package store - -import ( - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "os" - "path/filepath" - "regexp" - "sync" - "time" -) - -// ErrNotFound is returned when a profile has no token yet. -var ErrNotFound = errors.New("not found") - -// ErrInvalidInvite covers unknown, used and expired invites alike, so a caller -// can't tell which one it was. -var ErrInvalidInvite = errors.New("invite link is invalid or has expired") - -var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) - -// ValidProfile reports whether name can be used as a profile name. Profile -// names end up in file names, so they are restricted to a safe alphabet. -func ValidProfile(name string) bool { return profileRe.MatchString(name) } - -// Token is what is kept per profile. -type Token struct { - RefreshToken string `json:"refresh_token"` - AccessToken string `json:"access_token,omitempty"` - Expiry time.Time `json:"expiry,omitempty"` - // Who logged in, shown on the connect page. - SpotifyUserID string `json:"spotify_user_id,omitempty"` - DisplayName string `json:"display_name,omitempty"` - ConnectedAt time.Time `json:"connected_at,omitempty"` -} - -type invite struct { - Profile string `json:"profile"` - Expires time.Time `json:"expires"` -} - -// Store is safe for concurrent use within one process. The invite command runs -// as a second process (kubectl exec); it only adds invites, and the server -// re-reads the file on every check, so the two don't need a shared lock beyond -// the atomic rename. -type Store struct { - dir string - mu sync.Mutex - now func() time.Time -} - -// Open creates the data directory if needed. -func Open(dir string) (*Store, error) { - if err := os.MkdirAll(filepath.Join(dir, "tokens"), 0o700); err != nil { - return nil, fmt.Errorf("create data dir: %w", err) - } - return &Store{dir: dir, now: time.Now}, nil -} - -func (s *Store) tokenPath(profile string) string { - return filepath.Join(s.dir, "tokens", profile+".json") -} - -// Token returns the stored token of a profile, or ErrNotFound. -func (s *Store) Token(profile string) (Token, error) { - if !ValidProfile(profile) { - return Token{}, fmt.Errorf("invalid profile %q", profile) - } - s.mu.Lock() - defer s.mu.Unlock() - var t Token - if err := readJSON(s.tokenPath(profile), &t); err != nil { - return Token{}, err - } - return t, nil -} - -// SaveToken replaces the token of a profile. -func (s *Store) SaveToken(profile string, t Token) error { - if !ValidProfile(profile) { - return fmt.Errorf("invalid profile %q", profile) - } - s.mu.Lock() - defer s.mu.Unlock() - return writeJSON(s.tokenPath(profile), t) -} - -// DeleteToken forgets a profile's token. Deleting a missing token is not an error. -func (s *Store) DeleteToken(profile string) error { - if !ValidProfile(profile) { - return fmt.Errorf("invalid profile %q", profile) - } - s.mu.Lock() - defer s.mu.Unlock() - err := os.Remove(s.tokenPath(profile)) - if errors.Is(err, os.ErrNotExist) { - return nil - } - return err -} - -func (s *Store) invitePath() string { return filepath.Join(s.dir, "invites.json") } - -// hashInvite: only the SHA-256 of an invite is stored, so reading the volume -// doesn't give anyone a usable link. -func hashInvite(code string) string { - sum := sha256.Sum256([]byte(code)) - return hex.EncodeToString(sum[:]) -} - -func (s *Store) loadInvites() (map[string]invite, error) { - inv := map[string]invite{} - err := readJSON(s.invitePath(), &inv) - if errors.Is(err, ErrNotFound) { - return map[string]invite{}, nil - } - return inv, err -} - -// saveInvites drops expired entries on the way. -func (s *Store) saveInvites(inv map[string]invite) error { - now := s.now() - for k, v := range inv { - if now.After(v.Expires) { - delete(inv, k) - } - } - return writeJSON(s.invitePath(), inv) -} - -// CreateInvite returns a new one-time invite code for profile, valid for ttl. -func (s *Store) CreateInvite(profile string, ttl time.Duration) (string, error) { - if !ValidProfile(profile) { - return "", fmt.Errorf("invalid profile %q", profile) - } - b := make([]byte, 32) - if _, err := rand.Read(b); err != nil { - return "", err - } - code := base64.RawURLEncoding.EncodeToString(b) - s.mu.Lock() - defer s.mu.Unlock() - inv, err := s.loadInvites() - if err != nil { - return "", err - } - inv[hashInvite(code)] = invite{Profile: profile, Expires: s.now().Add(ttl)} - if err := s.saveInvites(inv); err != nil { - return "", err - } - return code, nil -} - -// CheckInvite returns the profile an invite belongs to without using it up. -func (s *Store) CheckInvite(code string) (string, error) { - s.mu.Lock() - defer s.mu.Unlock() - inv, err := s.loadInvites() - if err != nil { - return "", err - } - v, ok := inv[hashInvite(code)] - if !ok || s.now().After(v.Expires) { - return "", ErrInvalidInvite - } - return v.Profile, nil -} - -// UseInvite checks an invite and removes it, so it works only once. -func (s *Store) UseInvite(code string) (string, error) { - s.mu.Lock() - defer s.mu.Unlock() - inv, err := s.loadInvites() - if err != nil { - return "", err - } - h := hashInvite(code) - v, ok := inv[h] - if !ok || s.now().After(v.Expires) { - return "", ErrInvalidInvite - } - delete(inv, h) - if err := s.saveInvites(inv); err != nil { - return "", err - } - return v.Profile, nil -} - -func readJSON(path string, v any) error { - b, err := os.ReadFile(path) - if errors.Is(err, os.ErrNotExist) { - return ErrNotFound - } - if err != nil { - return err - } - if err := json.Unmarshal(b, v); err != nil { - return fmt.Errorf("read %s: %w", filepath.Base(path), err) - } - return nil -} - -func writeJSON(path string, v any) error { - b, err := json.MarshalIndent(v, "", " ") - if err != nil { - return err - } - f, err := os.CreateTemp(filepath.Dir(path), ".tmp-*") - if err != nil { - return err - } - tmp := f.Name() - defer func() { _ = os.Remove(tmp) }() // no-op after a successful rename - if err := f.Chmod(0o600); err != nil { - _ = f.Close() - return err - } - if _, err := f.Write(b); err != nil { - _ = f.Close() - return err - } - if err := f.Sync(); err != nil { - _ = f.Close() - return err - } - if err := f.Close(); err != nil { - return err - } - return os.Rename(tmp, path) -} diff --git a/internal/store/store_test.go b/internal/store/store_test.go deleted file mode 100644 index 672d23b..0000000 --- a/internal/store/store_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package store - -import ( - "errors" - "os" - "path/filepath" - "strings" - "testing" - "time" -) - -func TestTokenRoundTripAndPermissions(t *testing.T) { - dir := t.TempDir() - s, err := Open(dir) - if err != nil { - t.Fatal(err) - } - if _, err := s.Token("default"); !errors.Is(err, ErrNotFound) { - t.Fatalf("want ErrNotFound, got %v", err) - } - want := Token{RefreshToken: "r1", DisplayName: "Jan"} - if err := s.SaveToken("default", want); err != nil { - t.Fatal(err) - } - got, err := s.Token("default") - if err != nil || got.RefreshToken != "r1" || got.DisplayName != "Jan" { - t.Fatalf("got %+v, %v", got, err) - } - fi, err := os.Stat(filepath.Join(dir, "tokens", "default.json")) - if err != nil { - t.Fatal(err) - } - if fi.Mode().Perm() != 0o600 { - t.Fatalf("token file mode %v, want 0600", fi.Mode().Perm()) - } - // A second store on the same dir (e.g. after a pod restart) sees the token. - s2, _ := Open(dir) - if got, _ := s2.Token("default"); got.RefreshToken != "r1" { - t.Fatalf("reopened store lost the token: %+v", got) - } - if err := s.DeleteToken("default"); err != nil { - t.Fatal(err) - } - if err := s.DeleteToken("default"); err != nil { - t.Fatalf("second delete: %v", err) - } -} - -func TestProfileNames(t *testing.T) { - s, _ := Open(t.TempDir()) - for _, p := range []string{"../x", "", "A", "a/b", strings.Repeat("a", 64)} { - if err := s.SaveToken(p, Token{}); err == nil { - t.Errorf("profile %q accepted", p) - } - } -} - -func TestInvites(t *testing.T) { - dir := t.TempDir() - s, _ := Open(dir) - now := time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC) - s.now = func() time.Time { return now } - - code, err := s.CreateInvite("default", time.Hour) - if err != nil { - t.Fatal(err) - } - raw, _ := os.ReadFile(filepath.Join(dir, "invites.json")) - if strings.Contains(string(raw), code) { - t.Fatal("invite code stored in clear text") - } - if p, err := s.CheckInvite(code); err != nil || p != "default" { - t.Fatalf("check: %q %v", p, err) - } - if _, err := s.CheckInvite("wrong"); !errors.Is(err, ErrInvalidInvite) { - t.Fatalf("wrong code: %v", err) - } - if p, err := s.UseInvite(code); err != nil || p != "default" { - t.Fatalf("use: %q %v", p, err) - } - if _, err := s.UseInvite(code); !errors.Is(err, ErrInvalidInvite) { - t.Fatalf("second use: %v", err) - } - - old, _ := s.CreateInvite("default", time.Hour) - now = now.Add(2 * time.Hour) - if _, err := s.CheckInvite(old); !errors.Is(err, ErrInvalidInvite) { - t.Fatalf("expired invite accepted: %v", err) - } -} diff --git a/internal/tools/tools.go b/internal/tools/tools.go deleted file mode 100644 index 2b844cb..0000000 --- a/internal/tools/tools.go +++ /dev/null @@ -1,294 +0,0 @@ -// Package tools registers the MCP tools that control Spotify playback. -package tools - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/modelcontextprotocol/go-sdk/mcp" - - "github.com/subpathdev/spotify-mcp/internal/spotify" -) - -// Player is the part of the Spotify client the tools use. -type Player interface { - Devices(ctx context.Context) ([]spotify.Device, error) - Search(ctx context.Context, query, typ string, limit int) ([]spotify.Item, error) - Play(ctx context.Context, deviceID, uri string) error - Pause(ctx context.Context, deviceID string) error - Next(ctx context.Context, deviceID string) error - Previous(ctx context.Context, deviceID string) error - Transfer(ctx context.Context, deviceID string, play bool) error - NowPlaying(ctx context.Context) (*spotify.Playback, error) -} - -// DeviceArg is shared by every tool that can target a device. -type DeviceArg struct { - Device string `json:"device,omitempty" jsonschema:"Device name (e.g. 'Pixel 8') or ID from the devices tool. Empty: the active device."` -} - -// PlayArgs are the play tool's arguments. -type PlayArgs struct { - URI string `json:"uri,omitempty" jsonschema:"Spotify URI to play, e.g. spotify:track:..., spotify:album:..., spotify:playlist:... Takes precedence over query."` - Query string `json:"query,omitempty" jsonschema:"Search text; the first result of the given type is played, e.g. 'Bohemian Rhapsody Queen'."` - Type string `json:"type,omitempty" jsonschema:"What the query searches for: track (default), album, artist, playlist, show or episode."` - Device string `json:"device,omitempty" jsonschema:"Device name or ID. Empty: the active device."` -} - -// SearchArgs are the search tool's arguments. -type SearchArgs struct { - Query string `json:"query" jsonschema:"Search text, e.g. an artist, song or album name."` - Type string `json:"type,omitempty" jsonschema:"track (default), album, artist, playlist, show or episode."` - Limit int `json:"limit,omitempty" jsonschema:"Number of results, 1-10 (Spotify development mode allows at most 10). Default 5."` -} - -// TransferArgs are the transfer tool's arguments. -type TransferArgs struct { - Device string `json:"device" jsonschema:"Target device name (e.g. 'Pixel 8') or ID from the devices tool."` - Play *bool `json:"play,omitempty" jsonschema:"Start playing on the new device. Default true."` -} - -type empty struct{} - -func text(format string, a ...any) *mcp.CallToolResult { - return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf(format, a...)}}} -} - -func boolPtr(b bool) *bool { return &b } - -// Register adds the tools to s. -func Register(s *mcp.Server, p Player) { - t := &toolset{p: p} - - ro := &mcp.ToolAnnotations{ReadOnlyHint: true, OpenWorldHint: boolPtr(true)} - ctl := &mcp.ToolAnnotations{IdempotentHint: true, DestructiveHint: boolPtr(false), OpenWorldHint: boolPtr(true)} - step := &mcp.ToolAnnotations{DestructiveHint: boolPtr(false), OpenWorldHint: boolPtr(true)} - - mcp.AddTool(s, &mcp.Tool{Name: "devices", Description: "List the Spotify Connect devices (phone, computer, speakers) that Spotify currently sees, and which one is active.", Annotations: ro}, t.devices) - mcp.AddTool(s, &mcp.Tool{Name: "now_playing", Description: "Show what is playing on Spotify right now, on which device, and whether it is paused.", Annotations: ro}, t.nowPlaying) - mcp.AddTool(s, &mcp.Tool{Name: "search", Description: "Search Spotify. Returns up to 10 results with their URIs, which the play tool accepts.", Annotations: ro}, t.search) - mcp.AddTool(s, &mcp.Tool{Name: "play", Description: "Play a Spotify URI, or the first search result for a query, on a device (default: the active one). Without uri and query it resumes playback.", Annotations: step}, t.play) - mcp.AddTool(s, &mcp.Tool{Name: "pause", Description: "Pause Spotify playback.", Annotations: ctl}, t.pause) - mcp.AddTool(s, &mcp.Tool{Name: "resume", Description: "Resume Spotify playback where it was paused.", Annotations: ctl}, t.resume) - mcp.AddTool(s, &mcp.Tool{Name: "next", Description: "Skip to the next track.", Annotations: step}, t.next) - mcp.AddTool(s, &mcp.Tool{Name: "previous", Description: "Go back to the previous track.", Annotations: step}, t.previous) - mcp.AddTool(s, &mcp.Tool{Name: "transfer", Description: "Move playback to another device, e.g. from the computer to the phone.", Annotations: ctl}, t.transfer) -} - -type toolset struct{ p Player } - -// explain turns the common Spotify errors into something a person can act on. -func (t *toolset) explain(ctx context.Context, err error) error { - if !errors.Is(err, spotify.ErrNoActiveDevice) { - return err - } - msg := "No active Spotify device. Open the Spotify app on your phone, computer or speaker (playing anything once is enough), then try again" - if devs, derr := t.p.Devices(ctx); derr == nil && len(devs) > 0 { - names := make([]string, 0, len(devs)) - for _, d := range devs { - names = append(names, fmt.Sprintf("%q", d.Name)) - } - msg += ", or pass one of these as device: " + strings.Join(names, ", ") - } - return errors.New(msg + ".") -} - -// resolveDevice turns a name or ID into an ID. An empty name means the -// active device. -func (t *toolset) resolveDevice(ctx context.Context, name string) (string, string, error) { - name = strings.TrimSpace(name) - if name == "" { - return "", "", nil - } - devs, err := t.p.Devices(ctx) - if err != nil { - return "", "", err - } - for _, d := range devs { - if d.ID == name { - return d.ID, d.Name, nil - } - } - var matches []spotify.Device - for _, d := range devs { - if strings.EqualFold(d.Name, name) { - return d.ID, d.Name, nil - } - if strings.Contains(strings.ToLower(d.Name), strings.ToLower(name)) || - strings.EqualFold(d.Type, name) { - matches = append(matches, d) - } - } - if len(matches) == 1 { - return matches[0].ID, matches[0].Name, nil - } - names := make([]string, 0, len(devs)) - for _, d := range devs { - names = append(names, fmt.Sprintf("%q (%s)", d.Name, d.Type)) - } - if len(devs) == 0 { - return "", "", fmt.Errorf("no Spotify devices are online. Open the Spotify app on the device %q first", name) - } - if len(matches) > 1 { - return "", "", fmt.Errorf("%q matches more than one device: %s", name, strings.Join(names, ", ")) - } - return "", "", fmt.Errorf("no device called %q. Online devices: %s. If yours is missing, open the Spotify app on it", name, strings.Join(names, ", ")) -} - -func formatDevice(d spotify.Device) string { - s := fmt.Sprintf("%s (%s, id %s)", d.Name, d.Type, d.ID) - if d.IsActive { - s += " [active]" - } - if d.IsRestricted { - s += " [can't be controlled]" - } - return s -} - -func formatItem(it spotify.Item) string { - s := it.Name - if it.Artists != "" { - s += " by " + it.Artists - } - if it.Album != "" && it.Type != "album" { - s += " (" + it.Album + ")" - } - if it.Owner != "" { - s += " (by " + it.Owner + ")" - } - return s + " - " + it.URI -} - -func (t *toolset) devices(ctx context.Context, _ *mcp.CallToolRequest, _ empty) (*mcp.CallToolResult, any, error) { - devs, err := t.p.Devices(ctx) - if err != nil { - return nil, nil, err - } - if len(devs) == 0 { - return text("No Spotify devices are online. Open the Spotify app on a phone, computer or speaker; it then shows up here."), nil, nil - } - lines := make([]string, 0, len(devs)) - for _, d := range devs { - lines = append(lines, "- "+formatDevice(d)) - } - return text("Devices:\n%s", strings.Join(lines, "\n")), nil, nil -} - -func mmss(ms int) string { return fmt.Sprintf("%d:%02d", ms/60000, ms/1000%60) } - -func (t *toolset) nowPlaying(ctx context.Context, _ *mcp.CallToolRequest, _ empty) (*mcp.CallToolResult, any, error) { - pb, err := t.p.NowPlaying(ctx) - if err != nil { - return nil, nil, err - } - if pb == nil || pb.Item == nil { - return text("Nothing is playing on Spotify right now."), nil, nil - } - state := "Paused" - if pb.IsPlaying { - state = "Playing" - } - dev := "unknown device" - if pb.Device != nil { - dev = pb.Device.Name - } - return text("%s on %s: %s [%s / %s]", state, dev, formatItem(*pb.Item), mmss(pb.ProgressMS), mmss(pb.DurationMS)), nil, nil -} - -func (t *toolset) search(ctx context.Context, _ *mcp.CallToolRequest, in SearchArgs) (*mcp.CallToolResult, any, error) { - items, err := t.p.Search(ctx, in.Query, in.Type, in.Limit) - if err != nil { - return nil, nil, err - } - if len(items) == 0 { - return text("No results for %q.", in.Query), nil, nil - } - lines := make([]string, 0, len(items)) - for i, it := range items { - lines = append(lines, fmt.Sprintf("%d. %s", i+1, formatItem(it))) - } - return text("Results for %q:\n%s", in.Query, strings.Join(lines, "\n")), nil, nil -} - -func (t *toolset) play(ctx context.Context, _ *mcp.CallToolRequest, in PlayArgs) (*mcp.CallToolResult, any, error) { - devID, devName, err := t.resolveDevice(ctx, in.Device) - if err != nil { - return nil, nil, err - } - uri, what := strings.TrimSpace(in.URI), "" - if uri == "" && strings.TrimSpace(in.Query) != "" { - items, err := t.p.Search(ctx, in.Query, in.Type, 1) - if err != nil { - return nil, nil, err - } - if len(items) == 0 { - return nil, nil, fmt.Errorf("nothing found for %q", in.Query) - } - uri, what = items[0].URI, formatItem(items[0]) - } - if uri != "" { - if _, err := spotify.URIType(uri); err != nil { - return nil, nil, err - } - } - if err := t.p.Play(ctx, devID, uri); err != nil { - return nil, nil, t.explain(ctx, err) - } - where := "" - if devName != "" { - where = " on " + devName - } - switch { - case what != "": - return text("Playing %s%s.", what, where), nil, nil - case uri != "": - return text("Playing %s%s.", uri, where), nil, nil - default: - return text("Resumed playback%s.", where), nil, nil - } -} - -func (t *toolset) simple(ctx context.Context, device string, f func(context.Context, string) error, done string) (*mcp.CallToolResult, any, error) { - devID, _, err := t.resolveDevice(ctx, device) - if err != nil { - return nil, nil, err - } - if err := f(ctx, devID); err != nil { - return nil, nil, t.explain(ctx, err) - } - return text("%s", done), nil, nil -} - -func (t *toolset) pause(ctx context.Context, _ *mcp.CallToolRequest, in DeviceArg) (*mcp.CallToolResult, any, error) { - return t.simple(ctx, in.Device, t.p.Pause, "Paused.") -} - -func (t *toolset) resume(ctx context.Context, _ *mcp.CallToolRequest, in DeviceArg) (*mcp.CallToolResult, any, error) { - return t.simple(ctx, in.Device, func(ctx context.Context, id string) error { return t.p.Play(ctx, id, "") }, "Resumed.") -} - -func (t *toolset) next(ctx context.Context, _ *mcp.CallToolRequest, in DeviceArg) (*mcp.CallToolResult, any, error) { - return t.simple(ctx, in.Device, t.p.Next, "Skipped to the next track.") -} - -func (t *toolset) previous(ctx context.Context, _ *mcp.CallToolRequest, in DeviceArg) (*mcp.CallToolResult, any, error) { - return t.simple(ctx, in.Device, t.p.Previous, "Went back to the previous track.") -} - -func (t *toolset) transfer(ctx context.Context, _ *mcp.CallToolRequest, in TransferArgs) (*mcp.CallToolResult, any, error) { - if strings.TrimSpace(in.Device) == "" { - return nil, nil, errors.New("device is required; call the devices tool to see the names") - } - devID, devName, err := t.resolveDevice(ctx, in.Device) - if err != nil { - return nil, nil, err - } - play := in.Play == nil || *in.Play - if err := t.p.Transfer(ctx, devID, play); err != nil { - return nil, nil, t.explain(ctx, err) - } - return text("Moved playback to %s.", devName), nil, nil -} diff --git a/internal/tools/tools_test.go b/internal/tools/tools_test.go deleted file mode 100644 index 03ff4d4..0000000 --- a/internal/tools/tools_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package tools - -import ( - "context" - "sort" - "strings" - "testing" - - "github.com/modelcontextprotocol/go-sdk/mcp" - - "github.com/subpathdev/spotify-mcp/internal/spotify" -) - -type fakePlayer struct { - devices []spotify.Device - noActive bool - calls []string -} - -func (f *fakePlayer) Devices(context.Context) ([]spotify.Device, error) { return f.devices, nil } -func (f *fakePlayer) Search(_ context.Context, q, typ string, limit int) ([]spotify.Item, error) { - f.calls = append(f.calls, "search "+q+" "+typ) - return []spotify.Item{{Type: "track", Name: "Song", URI: "spotify:track:1", Artists: "Band"}}, nil -} -func (f *fakePlayer) Play(_ context.Context, dev, uri string) error { - f.calls = append(f.calls, "play "+dev+" "+uri) - if f.noActive && dev == "" { - return spotify.ErrNoActiveDevice - } - return nil -} -func (f *fakePlayer) Pause(_ context.Context, dev string) error { - f.calls = append(f.calls, "pause "+dev) - if f.noActive && dev == "" { - return spotify.ErrNoActiveDevice - } - return nil -} -func (f *fakePlayer) Next(_ context.Context, dev string) error { - f.calls = append(f.calls, "next "+dev) - return nil -} -func (f *fakePlayer) Previous(_ context.Context, dev string) error { - f.calls = append(f.calls, "previous "+dev) - return nil -} -func (f *fakePlayer) Transfer(_ context.Context, dev string, play bool) error { - f.calls = append(f.calls, "transfer "+dev) - return nil -} -func (f *fakePlayer) NowPlaying(context.Context) (*spotify.Playback, error) { - return &spotify.Playback{IsPlaying: true, Device: &f.devices[0], Item: &spotify.Item{Name: "Song", URI: "spotify:track:1"}, ProgressMS: 61000, DurationMS: 180000}, nil -} - -func session(t *testing.T, p Player) *mcp.ClientSession { - t.Helper() - ctx := context.Background() - s := mcp.NewServer(&mcp.Implementation{Name: "test"}, nil) - Register(s, p) - ct, st := mcp.NewInMemoryTransports() - if _, err := s.Connect(ctx, st, nil); err != nil { - t.Fatal(err) - } - cs, err := mcp.NewClient(&mcp.Implementation{Name: "c"}, nil).Connect(ctx, ct, nil) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = cs.Close() }) - return cs -} - -func call(t *testing.T, cs *mcp.ClientSession, name string, args map[string]any) (string, bool) { - t.Helper() - res, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: name, Arguments: args}) - if err != nil { - t.Fatalf("%s: %v", name, err) - } - var b strings.Builder - for _, c := range res.Content { - if tc, ok := c.(*mcp.TextContent); ok { - b.WriteString(tc.Text) - } - } - return b.String(), res.IsError -} - -func devices() []spotify.Device { - return []spotify.Device{ - {ID: "pc1", Name: "mobile", Type: "Computer"}, - {ID: "ph1", Name: "Jan's Pixel 8", Type: "Smartphone"}, - } -} - -func TestToolList(t *testing.T) { - cs := session(t, &fakePlayer{devices: devices()}) - res, err := cs.ListTools(context.Background(), nil) - if err != nil { - t.Fatal(err) - } - var names []string - for _, tl := range res.Tools { - names = append(names, tl.Name) - } - sort.Strings(names) - want := "devices,next,now_playing,pause,play,previous,resume,search,transfer" - if strings.Join(names, ",") != want { - t.Fatalf("tools %v", names) - } -} - -func TestPlayByQueryOnNamedDevice(t *testing.T) { - f := &fakePlayer{devices: devices()} - cs := session(t, f) - out, isErr := call(t, cs, "play", map[string]any{"query": "song", "device": "pixel"}) - if isErr || !strings.Contains(out, "Playing Song by Band") || !strings.Contains(out, "Pixel 8") { - t.Fatalf("%v %s", isErr, out) - } - if got := f.calls[len(f.calls)-1]; got != "play ph1 spotify:track:1" { - t.Fatalf("last call %q", got) - } -} - -func TestTransferByType(t *testing.T) { - f := &fakePlayer{devices: devices()} - cs := session(t, f) - out, isErr := call(t, cs, "transfer", map[string]any{"device": "smartphone"}) - if isErr || !strings.Contains(out, "Pixel 8") { - t.Fatalf("%v %s", isErr, out) - } - out, isErr = call(t, cs, "transfer", map[string]any{"device": "kitchen"}) - if !isErr || !strings.Contains(out, "no device called") || !strings.Contains(out, "mobile") { - t.Fatalf("unknown device: %v %s", isErr, out) - } -} - -func TestNoActiveDeviceMessage(t *testing.T) { - f := &fakePlayer{devices: devices(), noActive: true} - cs := session(t, f) - out, isErr := call(t, cs, "pause", nil) - if !isErr || !strings.Contains(out, "No active Spotify device") || !strings.Contains(out, `"Jan's Pixel 8"`) { - t.Fatalf("%v %s", isErr, out) - } - out, _ = call(t, cs, "resume", nil) - if !strings.Contains(out, "Open the Spotify app") { - t.Fatalf("resume: %s", out) - } -} - -func TestSimpleControls(t *testing.T) { - f := &fakePlayer{devices: devices()} - cs := session(t, f) - for name, want := range map[string]string{"next": "next", "previous": "previous", "pause": "Paused", "resume": "Resumed"} { - out, isErr := call(t, cs, name, nil) - if isErr || !strings.Contains(out, want) { - t.Errorf("%s: %v %s", name, isErr, out) - } - } - out, _ := call(t, cs, "now_playing", nil) - if !strings.Contains(out, "Playing on mobile: Song") || !strings.Contains(out, "1:01 / 3:00") { - t.Fatalf("now_playing: %s", out) - } - out, _ = call(t, cs, "devices", nil) - if !strings.Contains(out, "Jan's Pixel 8 (Smartphone, id ph1)") { - t.Fatalf("devices: %s", out) - } - if _, isErr := call(t, cs, "play", map[string]any{"uri": "spotify:bogus:1"}); !isErr { - t.Fatal("bogus URI accepted") - } -} diff --git a/internal/web/page.html b/internal/web/page.html new file mode 100644 index 0000000..23ffef5 --- /dev/null +++ b/internal/web/page.html @@ -0,0 +1,42 @@ + + + + + + +{{.Title}} + + + +
+

{{.Title}}

+{{if .Message}}{{.Message}}

{{end}} +{{if .ShowForm}} + {{if .Connected}} +
Connected as {{.Name}}{{if .Since}} since {{.Since}}{{end}}.
+ {{else}} +

Press the button and log in with your Spotify account. Afterwards Claude can play, pause and skip music for you. It can't see your playlists or e-mail address.

+ {{end}} +
+ + + {{if .Connected}}{{end}} +
+{{end}} +
+ + diff --git a/internal/web/web.go b/internal/web/web.go index c3604d3..537b15d 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -1,79 +1,59 @@ // Package web serves the "Connect Spotify" page: a person opens an invite // link, presses one button, logs in at Spotify, and the server keeps the -// resulting refresh token. No terminal, no copying tokens around. +// connection. No terminal, no copying tokens around. // -// Security notes: -// - Only someone with a valid one-time invite can connect or disconnect an -// account. Invites are stored hashed and used up when the login finishes. -// - The OAuth flow uses state (bound to the browser by a cookie) and PKCE, -// so a stolen callback URL or code can't be replayed. -// - Pages send no Referer, so the invite in the URL doesn't leak to Spotify. +// The rules (invites, state, PKCE) live in the account package. This package +// handles HTTP: forms, the cookie that binds a login to the browser, security +// headers and the pages. package web import ( "context" - "crypto/rand" - "crypto/subtle" - "encoding/base64" - "encoding/json" + _ "embed" "errors" - "fmt" "html/template" "log/slog" "net/http" - "sync" "time" - "golang.org/x/oauth2" - - "github.com/subpathdev/spotify-mcp/internal/store" + "github.com/subpathdev/spotify-mcp/internal/account" ) +// Connector is what the page needs; *account.Service implements it. +type Connector interface { + Status(ctx context.Context, code account.InviteCode) (account.Status, error) + StartLogin(ctx context.Context, code account.InviteCode) (account.Login, error) + FinishLogin(ctx context.Context, cb account.Callback) (account.User, error) + Disconnect(ctx context.Context, code account.InviteCode) (account.Profile, error) +} + const ( - cookieName = "spotify_mcp_login" - loginTTL = 10 * time.Minute - maxPending = 100 - callbackURL = "/callback" + cookieName = "spotify_mcp_login" + callbackPath = "/callback" + maxForm = 4 << 10 ) -// Handler serves /connect and /callback. -type Handler struct { - OAuth *oauth2.Config - Store *store.Store - Log *slog.Logger - // MeURL is where the display name of a new login comes from. - MeURL string - // HTTPClient is used for the token exchange and /me. May be nil. - HTTPClient *http.Client - // OnConnect is called after a profile's token changed (connect or disconnect). - OnConnect func(profile string) - // Now is replaceable in tests. - Now func() time.Time - - mu sync.Mutex - pending map[string]pendingLogin -} - -type pendingLogin struct { - profile string - invite string - verifier string - nonce string - expires time.Time +type handler struct { + c Connector + log *slog.Logger } -// Routes returns the HTTP handler with the page routes and /healthz. -func (h *Handler) Routes() http.Handler { +// NewHandler returns the page routes (/connect, /callback) and /healthz. +// +// Cross-site POSTs are rejected (Sec-Fetch-Site / Origin), so another page +// can't submit the form with a stolen invite in someone else's browser. +func NewHandler(c Connector, log *slog.Logger) http.Handler { + h := &handler{c: c, log: log} mux := http.NewServeMux() mux.HandleFunc("GET /connect", h.connectPage) mux.HandleFunc("POST /connect", h.connectPost) - mux.HandleFunc("GET "+callbackURL, h.callback) + mux.HandleFunc("GET "+callbackPath, h.callback) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok\n")) }) - // Rejects cross-site POSTs (Sec-Fetch-Site / Origin), so another page can't - // submit the form with a stolen invite in someone else's browser. return securityHeaders(http.NewCrossOriginProtection().Handler(mux)) } +// securityHeaders: no scripts, forms only to this page and Spotify, no +// framing, and no Referer, so the invite in the URL doesn't leak to Spotify. func securityHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hd := w.Header() @@ -85,127 +65,46 @@ func securityHeaders(next http.Handler) http.Handler { }) } -func (h *Handler) now() time.Time { - if h.Now != nil { - return h.Now() - } - return time.Now() -} - -func (h *Handler) httpCtx(ctx context.Context) context.Context { - if h.HTTPClient != nil { - return context.WithValue(ctx, oauth2.HTTPClient, h.HTTPClient) - } - return ctx -} - -func randomString() string { - b := make([]byte, 32) - _, _ = rand.Read(b) - return base64.RawURLEncoding.EncodeToString(b) -} - -type pageData struct { - Title string - Message string - Error bool - Invite string - Connected bool - Name string - Since string - ShowForm bool -} - -func (h *Handler) render(w http.ResponseWriter, status int, d pageData) { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.WriteHeader(status) - if err := page.Execute(w, d); err != nil { - h.Log.Error("render page", "err", err) - } -} - -func (h *Handler) invalidInvite(w http.ResponseWriter) { - h.render(w, http.StatusForbidden, pageData{ - Title: "Link not valid", - Message: "This link is invalid, was already used, or has expired. Ask for a new one.", - Error: true, - }) -} - -func (h *Handler) connectPage(w http.ResponseWriter, r *http.Request) { - code := r.URL.Query().Get("invite") - profile, err := h.Store.CheckInvite(code) +func (h *handler) connectPage(w http.ResponseWriter, r *http.Request) { + code := account.InviteCode(r.URL.Query().Get("invite")) + st, err := h.c.Status(r.Context(), code) if err != nil { - h.invalidInvite(w) + h.fail(w, err) return } - d := pageData{Title: "Connect Spotify", Invite: code, ShowForm: true} - if t, err := h.Store.Token(profile); err == nil { - d.Connected, d.Name = true, t.DisplayName - if d.Name == "" { - d.Name = t.SpotifyUserID - } - if !t.ConnectedAt.IsZero() { - d.Since = t.ConnectedAt.Format("2006-01-02") + d := pageData{Title: "Connect Spotify", Invite: string(code), ShowForm: true, Connected: st.Connected} + if st.Connected { + d.Name = st.User.Name() + if !st.ConnectedAt.IsZero() { + d.Since = st.ConnectedAt.Format(time.DateOnly) } } h.render(w, http.StatusOK, d) } -func (h *Handler) connectPost(w http.ResponseWriter, r *http.Request) { - r.Body = http.MaxBytesReader(w, r.Body, 4096) +func (h *handler) connectPost(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, maxForm) if err := r.ParseForm(); err != nil { http.Error(w, "bad request", http.StatusBadRequest) return } - code := r.PostForm.Get("invite") + code := account.InviteCode(r.PostForm.Get("invite")) switch r.PostForm.Get("action") { case "connect": - profile, err := h.Store.CheckInvite(code) + login, err := h.c.StartLogin(r.Context(), code) if err != nil { - h.invalidInvite(w) - return - } - state, nonce, verifier := randomString(), randomString(), oauth2.GenerateVerifier() - h.mu.Lock() - if h.pending == nil { - h.pending = map[string]pendingLogin{} - } - for k, p := range h.pending { - if h.now().After(p.expires) { - delete(h.pending, k) - } - } - if len(h.pending) >= maxPending { - h.mu.Unlock() - http.Error(w, "too many logins in progress, try again in a few minutes", http.StatusTooManyRequests) + h.fail(w, err) return } - h.pending[state] = pendingLogin{profile: profile, invite: code, verifier: verifier, nonce: nonce, expires: h.now().Add(loginTTL)} - h.mu.Unlock() - http.SetCookie(w, &http.Cookie{ - Name: cookieName, Value: nonce, Path: callbackURL, - MaxAge: int(loginTTL.Seconds()), HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, - }) - // show_dialog: always show Spotify's consent page, so a family member on - // a shared browser sees which account they're about to connect. - u := h.OAuth.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier), oauth2.SetAuthURLParam("show_dialog", "true")) - http.Redirect(w, r, u, http.StatusSeeOther) + http.SetCookie(w, loginCookie(login.Nonce, int(account.LoginTTL/time.Second))) + http.Redirect(w, r, login.URL, http.StatusSeeOther) case "disconnect": - profile, err := h.Store.UseInvite(code) + profile, err := h.c.Disconnect(r.Context(), code) if err != nil { - h.invalidInvite(w) + h.fail(w, err) return } - if err := h.Store.DeleteToken(profile); err != nil { - h.Log.Error("delete token", "profile", profile, "err", err) - http.Error(w, "could not disconnect", http.StatusInternalServerError) - return - } - h.Log.Info("spotify account disconnected", "profile", profile) - if h.OnConnect != nil { - h.OnConnect(profile) - } + h.log.Info("spotify account disconnected", "profile", profile) h.render(w, http.StatusOK, pageData{ Title: "Disconnected", Message: "The Spotify account is disconnected and its token deleted. To also remove the app on Spotify's side, open spotify.com → Account → Manage apps.", @@ -215,154 +114,94 @@ func (h *Handler) connectPost(w http.ResponseWriter, r *http.Request) { } } -func (h *Handler) callback(w http.ResponseWriter, r *http.Request) { +func (h *handler) callback(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() - state := q.Get("state") - h.mu.Lock() - p, ok := h.pending[state] - delete(h.pending, state) // one attempt per state - h.mu.Unlock() - c, cerr := r.Cookie(cookieName) - http.SetCookie(w, &http.Cookie{Name: cookieName, Path: callbackURL, MaxAge: -1, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode}) - if !ok || h.now().After(p.expires) || cerr != nil || subtle.ConstantTimeCompare([]byte(c.Value), []byte(p.nonce)) != 1 { - h.render(w, http.StatusBadRequest, pageData{ - Title: "Login expired", - Message: "This login can't be finished (it took too long, or was started in another browser). Open your invite link again and press the button once more.", - Error: true, - }) - return + cb := account.Callback{State: q.Get("state"), Code: q.Get("code"), Error: q.Get("error")} + if c, err := r.Cookie(cookieName); err == nil { + cb.Nonce = c.Value } - if e := q.Get("error"); e != "" { - msg := "Spotify didn't allow the connection (" + e + ")." - if e == "access_denied" { - msg = "You cancelled the login at Spotify. Nothing was connected. Your invite link still works." - } - h.render(w, http.StatusOK, pageData{Title: "Not connected", Message: msg, Error: true}) - return - } - ctx := h.httpCtx(r.Context()) - tok, err := h.OAuth.Exchange(ctx, q.Get("code"), oauth2.VerifierOption(p.verifier)) - if err != nil { - h.Log.Error("token exchange", "err", err) - msg := "Spotify didn't accept the login. Try again with your invite link." - var re *oauth2.RetrieveError - if errors.As(err, &re) && re.ErrorCode == "invalid_client" { - msg = "The server's Spotify app settings (client ID or secret) are wrong. Tell whoever runs it." - } - h.render(w, http.StatusBadGateway, pageData{Title: "Not connected", Message: msg, Error: true}) - return - } - if tok.RefreshToken == "" { - h.render(w, http.StatusBadGateway, pageData{Title: "Not connected", Message: "Spotify sent no refresh token. Try again.", Error: true}) - return - } - me, err := h.fetchMe(ctx, tok) + http.SetCookie(w, loginCookie("", -1)) + user, err := h.c.FinishLogin(r.Context(), cb) if err != nil { - h.Log.Warn("fetch profile after login", "err", err) - if errors.Is(err, errNotAllowlisted) { - h.render(w, http.StatusForbidden, pageData{ - Title: "Account not allowed yet", - Message: "This Spotify account isn't on the app's user list. The app owner has to add it under User Management in the Spotify developer dashboard (development mode allows up to 5 accounts). Then open the invite link again.", - Error: true, - }) - return - } - } - if _, err := h.Store.UseInvite(p.invite); err != nil { - h.invalidInvite(w) - return - } - st := store.Token{ - RefreshToken: tok.RefreshToken, AccessToken: tok.AccessToken, Expiry: tok.Expiry, - SpotifyUserID: me.ID, DisplayName: me.DisplayName, ConnectedAt: h.now(), - } - if err := h.Store.SaveToken(p.profile, st); err != nil { - h.Log.Error("save token", "profile", p.profile, "err", err) - http.Error(w, "could not save the login", http.StatusInternalServerError) + h.fail(w, err) return } - h.Log.Info("spotify account connected", "profile", p.profile, "spotify_user", me.ID) - if h.OnConnect != nil { - h.OnConnect(p.profile) - } - name := me.DisplayName - if name == "" { - name = me.ID - } + h.log.Info("spotify account connected", "spotify_user", user.ID) msg := "Spotify is connected. You can close this page." - if name != "" { + if name := user.Name(); name != "" { msg = "Spotify is connected as " + name + ". You can close this page." } h.render(w, http.StatusOK, pageData{Title: "Connected", Message: msg}) } -var errNotAllowlisted = errors.New("account not on the development-mode user list") +// loginCookie binds a login to the browser. Only the callback receives it. +func loginCookie(nonce string, maxAge int) *http.Cookie { + return &http.Cookie{ + Name: cookieName, Value: nonce, Path: callbackPath, MaxAge: maxAge, + HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, + } +} -type me struct { - ID string `json:"id"` - DisplayName string `json:"display_name"` +// failure is how an error is shown to a person. +type failure struct { + status int + title string + message string } -func (h *Handler) fetchMe(ctx context.Context, tok *oauth2.Token) (me, error) { - var m me - req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.MeURL, nil) - if err != nil { - return m, err - } - resp, err := h.OAuth.Client(ctx, tok).Do(req) - if err != nil { - return m, err - } - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode == http.StatusForbidden { - return m, errNotAllowlisted - } - if resp.StatusCode != http.StatusOK { - return m, fmt.Errorf("GET /me: %s", resp.Status) +var failures = []struct { + err error + failure +}{ + {account.ErrInvalidInvite, failure{http.StatusForbidden, "Link not valid", + "This link is invalid, was already used, or has expired. Ask for a new one."}}, + {account.ErrLoginExpired, failure{http.StatusBadRequest, "Login expired", + "This login can't be finished (it took too long, or was started in another browser). Open your invite link again and press the button once more."}}, + {account.ErrLoginCancelled, failure{http.StatusOK, "Not connected", + "You cancelled the login at Spotify. Nothing was connected. Your invite link still works."}}, + {account.ErrNotAllowlisted, failure{http.StatusForbidden, "Account not allowed yet", + "This Spotify account isn't on the app's user list. The app owner has to add it under User Management in the Spotify developer dashboard (development mode allows up to 5 accounts). Then open the invite link again."}}, + {account.ErrInvalidClient, failure{http.StatusBadGateway, "Not connected", + "The server's Spotify app settings (client ID or secret) are wrong. Tell whoever runs it."}}, + {account.ErrTooManyLogins, failure{http.StatusTooManyRequests, "Busy", + "Too many logins are in progress. Try again in a few minutes."}}, +} + +func (h *handler) fail(w http.ResponseWriter, err error) { + for _, f := range failures { + if errors.Is(err, f.err) { + h.render(w, f.status, pageData{Title: f.title, Message: f.message, Error: true}) + return + } } - return m, json.NewDecoder(http.MaxBytesReader(nil, resp.Body, 1<<20)).Decode(&m) + h.log.Error("connect page", "err", err) + h.render(w, http.StatusBadGateway, pageData{ + Title: "Not connected", + Message: "Something went wrong while connecting to Spotify. Try again with your invite link.", + Error: true, + }) } -var page = template.Must(template.New("page").Parse(` - - - - - -{{.Title}} - - - -
-

{{.Title}}

-{{if .Message}}{{.Message}}

{{end}} -{{if .ShowForm}} - {{if .Connected}} -
Connected as {{.Name}}{{if .Since}} since {{.Since}}{{end}}.
- {{else}} -

Press the button and log in with your Spotify account. Afterwards Claude can play, pause and skip music for you. It can't see your playlists or e-mail address.

- {{end}} -
- - - {{if .Connected}}{{end}} -
-{{end}} -
- - -`)) +type pageData struct { + Title string + Message string + Error bool + ShowForm bool + Invite string + Connected bool + Name string + Since string +} + +//go:embed page.html +var pageHTML string + +var page = template.Must(template.New("page").Parse(pageHTML)) + +func (h *handler) render(w http.ResponseWriter, status int, d pageData) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(status) + if err := page.Execute(w, d); err != nil { + h.log.Error("render page", "err", err) + } +} diff --git a/internal/web/web_test.go b/internal/web/web_test.go index 914e438..3b7e55e 100644 --- a/internal/web/web_test.go +++ b/internal/web/web_test.go @@ -1,8 +1,8 @@ -package web +package web_test import ( - "crypto/sha256" - "encoding/base64" + "context" + "errors" "io" "log/slog" "net/http" @@ -14,235 +14,212 @@ import ( "testing" "time" - "golang.org/x/oauth2" - - "github.com/subpathdev/spotify-mcp/internal/store" + "github.com/subpathdev/spotify-mcp/internal/account" + "github.com/subpathdev/spotify-mcp/internal/filestore" + "github.com/subpathdev/spotify-mcp/internal/web" ) -// fakeAccounts plays accounts.spotify.com and api.spotify.com/v1/me. -type fakeAccounts struct { - *httptest.Server +// fakeOAuth accepts the code "good" with the verifier of a started login. +type fakeOAuth struct { mu sync.Mutex - challenge string - meStatus int -} - -func newFakeAccounts(t *testing.T) *fakeAccounts { - f := &fakeAccounts{meStatus: http.StatusOK} - mux := http.NewServeMux() - mux.HandleFunc("POST /api/token", func(w http.ResponseWriter, r *http.Request) { - _ = r.ParseForm() - sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier"))) - f.mu.Lock() - ok := r.PostForm.Get("code") == "good-code" && base64.RawURLEncoding.EncodeToString(sum[:]) == f.challenge - f.mu.Unlock() - w.Header().Set("Content-Type", "application/json") - if !ok { - w.WriteHeader(http.StatusBadRequest) - _, _ = io.WriteString(w, `{"error":"invalid_grant"}`) - return + verifiers map[string]string +} + +func (f *fakeOAuth) AuthCodeURL(state, verifier string) string { + f.mu.Lock() + defer f.mu.Unlock() + f.verifiers[state] = verifier + return "https://accounts.test/authorize?" + url.Values{"state": {state}}.Encode() +} + +func (f *fakeOAuth) Exchange(_ context.Context, code, verifier string) (account.Token, error) { + f.mu.Lock() + defer f.mu.Unlock() + for _, v := range f.verifiers { + if v == verifier && code == "good" { + return account.Token{AccessToken: "a", RefreshToken: "r", Expiry: time.Now().Add(time.Hour)}, nil } - _, _ = io.WriteString(w, `{"access_token":"a1","token_type":"Bearer","expires_in":3600,"refresh_token":"r1"}`) - }) - mux.HandleFunc("GET /v1/me", func(w http.ResponseWriter, r *http.Request) { - f.mu.Lock() - st := f.meStatus - f.mu.Unlock() - w.WriteHeader(st) - _, _ = io.WriteString(w, `{"id":"jan","display_name":"Jan"}`) - }) - f.Server = httptest.NewServer(mux) - t.Cleanup(f.Close) - return f + } + return account.Token{}, errors.New("bad code") +} + +func (f *fakeOAuth) Refresh(context.Context, string) (account.Token, error) { + return account.Token{}, errors.New("unused") +} + +type fakeIdentity struct{ err error } + +func (f *fakeIdentity) User(context.Context, string) (account.User, error) { + return account.User{ID: "jan", DisplayName: "Jan"}, f.err } type env struct { - st *store.Store - acc *fakeAccounts - web *httptest.Server - browser *http.Client - changed []string + srv *httptest.Server + inviter *account.Inviter + store *filestore.Store + identity *fakeIdentity +} + +func newEnv(t *testing.T) *env { + t.Helper() + st, err := filestore.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + id := &fakeIdentity{} + svc := account.NewService(st, st, &fakeOAuth{verifiers: map[string]string{}}, id) + srv := httptest.NewTLSServer(web.NewHandler(svc, slog.New(slog.DiscardHandler))) + t.Cleanup(srv.Close) + return &env{srv: srv, inviter: account.NewInviter(st), store: st, identity: id} } -func setup(t *testing.T) *env { - e := &env{acc: newFakeAccounts(t)} - var err error - if e.st, err = store.Open(t.TempDir()); err != nil { +func (e *env) invite(t *testing.T) string { + t.Helper() + code, _, err := e.inviter.CreateInvite(context.Background(), "default", time.Hour) + if err != nil { t.Fatal(err) } - h := &Handler{ - OAuth: &oauth2.Config{ - ClientID: "id", ClientSecret: "secret", Scopes: []string{"user-modify-playback-state"}, - Endpoint: oauth2.Endpoint{AuthURL: "https://accounts.example/authorize", TokenURL: e.acc.URL + "/api/token", AuthStyle: oauth2.AuthStyleInHeader}, - }, - Store: e.st, - Log: slog.New(slog.NewTextHandler(io.Discard, nil)), - MeURL: e.acc.URL + "/v1/me", - HTTPClient: e.acc.Client(), - OnConnect: func(p string) { e.changed = append(e.changed, p) }, - } - e.web = httptest.NewTLSServer(h.Routes()) - t.Cleanup(e.web.Close) - h.OAuth.RedirectURL = e.web.URL + "/callback" + return string(code) +} + +// browser is a client with its own cookies that doesn't follow redirects. +func (e *env) browser(t *testing.T) *http.Client { + t.Helper() jar, _ := cookiejar.New(nil) - e.browser = e.web.Client() - e.browser.Jar = jar - // Stop at the redirect to Spotify instead of following it. - e.browser.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } - return e + return &http.Client{ + Transport: e.srv.Client().Transport, + Jar: jar, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } } func body(t *testing.T, resp *http.Response) string { t.Helper() defer func() { _ = resp.Body.Close() }() - b, _ := io.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } return string(b) } -// startLogin opens the invite page, presses Connect and returns the state -// from the redirect to Spotify. -func (e *env) startLogin(t *testing.T, code string) string { +func get(t *testing.T, c *http.Client, u string) (int, string) { t.Helper() - resp, err := e.browser.Get(e.web.URL + "/connect?invite=" + url.QueryEscape(code)) + resp, err := c.Get(u) if err != nil { t.Fatal(err) } - if b := body(t, resp); resp.StatusCode != 200 || !strings.Contains(b, "Connect Spotify") { - t.Fatalf("invite page: %d %s", resp.StatusCode, b) - } - if rp := resp.Header.Get("Referrer-Policy"); rp != "no-referrer" { - t.Fatalf("Referrer-Policy %q", rp) - } - resp, err = e.browser.PostForm(e.web.URL+"/connect", url.Values{"invite": {code}, "action": {"connect"}}) + return resp.StatusCode, body(t, resp) +} + +func post(t *testing.T, c *http.Client, u string, form url.Values) *http.Response { + t.Helper() + resp, err := c.PostForm(u, form) if err != nil { t.Fatal(err) } - _ = resp.Body.Close() + return resp +} + +// connect presses the button and returns the callback URL Spotify would +// redirect to. +func (e *env) connect(t *testing.T, c *http.Client, code string) string { + t.Helper() + resp := post(t, c, e.srv.URL+"/connect", url.Values{"invite": {code}, "action": {"connect"}}) + _ = body(t, resp) if resp.StatusCode != http.StatusSeeOther { t.Fatalf("connect: %d", resp.StatusCode) } loc, _ := url.Parse(resp.Header.Get("Location")) - q := loc.Query() - if q.Get("code_challenge_method") != "S256" || q.Get("show_dialog") != "true" || q.Get("state") == "" { - t.Fatalf("authorize URL %s", loc) - } - e.acc.mu.Lock() - e.acc.challenge = q.Get("code_challenge") - e.acc.mu.Unlock() - return q.Get("state") + return e.srv.URL + "/callback?" + url.Values{"state": {loc.Query().Get("state")}, "code": {"good"}}.Encode() } func TestConnectFlow(t *testing.T) { - e := setup(t) - code, _ := e.st.CreateInvite("default", time.Hour) - state := e.startLogin(t, code) + e := newEnv(t) + b := e.browser(t) + code := e.invite(t) - resp, err := e.browser.Get(e.web.URL + "/callback?code=good-code&state=" + state) - if err != nil { - t.Fatal(err) + status, page := get(t, b, e.srv.URL+"/connect?invite="+code) + if status != http.StatusOK || !strings.Contains(page, "Connect Spotify") { + t.Fatalf("page: %d %s", status, page) } - if b := body(t, resp); resp.StatusCode != 200 || !strings.Contains(b, "connected as Jan") { - t.Fatalf("callback: %d %s", resp.StatusCode, b) + callback := e.connect(t, b, code) + + // Another browser with the callback URL can't finish the login, and the + // attempt uses up the state. + if status, _ := get(t, e.browser(t), callback); status != http.StatusBadRequest { + t.Fatalf("foreign browser: %d", status) } - tok, err := e.st.Token("default") - if err != nil || tok.RefreshToken != "r1" || tok.DisplayName != "Jan" { - t.Fatalf("token %+v %v", tok, err) + callback = e.connect(t, b, code) + status, page = get(t, b, callback) + if status != http.StatusOK || !strings.Contains(page, "connected as Jan") { + t.Fatalf("callback: %d %s", status, page) } - if len(e.changed) != 1 { - t.Fatalf("OnConnect calls %v", e.changed) + if status, _ := get(t, b, callback); status != http.StatusBadRequest { + t.Fatalf("replay: %d", status) } - // The invite is used up, and the state can't be replayed. - if _, err := e.st.CheckInvite(code); err == nil { - t.Fatal("invite still valid after login") + if status, _ := get(t, b, e.srv.URL+"/connect?invite="+code); status != http.StatusForbidden { + t.Fatalf("used invite: %d", status) } - resp, _ = e.browser.Get(e.web.URL + "/callback?code=good-code&state=" + state) - if resp.StatusCode != http.StatusBadRequest { - t.Fatalf("replayed callback: %d", resp.StatusCode) + if _, err := e.store.Connection(context.Background(), "default"); err != nil { + t.Fatalf("not stored: %v", err) } - _ = resp.Body.Close() } -func TestCallbackNeedsSameBrowser(t *testing.T) { - e := setup(t) - code, _ := e.st.CreateInvite("default", time.Hour) - state := e.startLogin(t, code) - // An attacker's browser has no login cookie. - other := &http.Client{Transport: e.web.Client().Transport} - resp, err := other.Get(e.web.URL + "/callback?code=good-code&state=" + state) - if err != nil { - t.Fatal(err) - } - _ = resp.Body.Close() - if resp.StatusCode != http.StatusBadRequest { - t.Fatalf("callback from other browser: %d", resp.StatusCode) - } - if _, err := e.st.Token("default"); err == nil { - t.Fatal("token saved from foreign browser") +func TestNotAllowlistedPage(t *testing.T) { + e := newEnv(t) + e.identity.err = account.ErrNotAllowlisted + b := e.browser(t) + status, page := get(t, b, e.connect(t, b, e.invite(t))) + if status != http.StatusForbidden || !strings.Contains(page, "User Management") { + t.Fatalf("%d %s", status, page) } } -func TestNotOnAllowlist(t *testing.T) { - e := setup(t) - e.acc.meStatus = http.StatusForbidden - code, _ := e.st.CreateInvite("default", time.Hour) - state := e.startLogin(t, code) - resp, _ := e.browser.Get(e.web.URL + "/callback?code=good-code&state=" + state) - if b := body(t, resp); resp.StatusCode != http.StatusForbidden || !strings.Contains(b, "User Management") { - t.Fatalf("got %d %s", resp.StatusCode, b) +func TestDisconnect(t *testing.T) { + e := newEnv(t) + b := e.browser(t) + if status, _ := get(t, b, e.connect(t, b, e.invite(t))); status != http.StatusOK { + t.Fatal("connect failed") } - if _, err := e.st.CheckInvite(code); err != nil { - t.Fatal("invite used up although the login failed") + code := e.invite(t) + if _, page := get(t, b, e.srv.URL+"/connect?invite="+code); !strings.Contains(page, "Connected as Jan") { + t.Fatalf("status page: %s", page) } -} - -func TestCancelAtSpotify(t *testing.T) { - e := setup(t) - code, _ := e.st.CreateInvite("default", time.Hour) - state := e.startLogin(t, code) - resp, _ := e.browser.Get(e.web.URL + "/callback?error=access_denied&state=" + state) - if b := body(t, resp); !strings.Contains(b, "cancelled") { - t.Fatalf("cancel page: %s", b) + resp := post(t, b, e.srv.URL+"/connect", url.Values{"invite": {code}, "action": {"disconnect"}}) + if page := body(t, resp); resp.StatusCode != http.StatusOK || !strings.Contains(page, "Disconnected") { + t.Fatalf("disconnect: %d %s", resp.StatusCode, page) } - if _, err := e.st.CheckInvite(code); err != nil { - t.Fatal("invite used up by a cancelled login") + if _, err := e.store.Connection(context.Background(), "default"); !errors.Is(err, account.ErrNotFound) { + t.Fatalf("connection kept: %v", err) } } -func TestBadInviteAndCrossSite(t *testing.T) { - e := setup(t) - resp, _ := e.browser.Get(e.web.URL + "/connect?invite=nope") - if resp.StatusCode != http.StatusForbidden { - t.Fatalf("bad invite: %d", resp.StatusCode) - } - _ = resp.Body.Close() - - code, _ := e.st.CreateInvite("default", time.Hour) - req, _ := http.NewRequest(http.MethodPost, e.web.URL+"/connect", strings.NewReader(url.Values{"invite": {code}, "action": {"disconnect"}}.Encode())) +func TestCrossSitePostRejected(t *testing.T) { + e := newEnv(t) + req, _ := http.NewRequest(http.MethodPost, e.srv.URL+"/connect", strings.NewReader("action=connect&invite="+e.invite(t))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Sec-Fetch-Site", "cross-site") - resp, err := e.browser.Do(req) + resp, err := e.browser(t).Do(req) if err != nil { t.Fatal(err) } - _ = resp.Body.Close() + _ = body(t, resp) if resp.StatusCode != http.StatusForbidden { - t.Fatalf("cross-site POST: %d", resp.StatusCode) + t.Fatalf("status %d", resp.StatusCode) } } -func TestDisconnect(t *testing.T) { - e := setup(t) - _ = e.st.SaveToken("default", store.Token{RefreshToken: "r", DisplayName: "Jan"}) - code, _ := e.st.CreateInvite("default", time.Hour) - resp, _ := e.browser.Get(e.web.URL + "/connect?invite=" + code) - if b := body(t, resp); !strings.Contains(b, "Connected as Jan") { - t.Fatalf("status page: %s", b) - } - resp, _ = e.browser.PostForm(e.web.URL+"/connect", url.Values{"invite": {code}, "action": {"disconnect"}}) - if b := body(t, resp); resp.StatusCode != 200 || !strings.Contains(b, "Disconnected") { - t.Fatalf("disconnect: %d %s", resp.StatusCode, b) - } - if _, err := e.st.Token("default"); err == nil { - t.Fatal("token still there") +func TestSecurityHeaders(t *testing.T) { + e := newEnv(t) + resp, err := e.browser(t).Get(e.srv.URL + "/connect?invite=bad") + if err != nil { + t.Fatal(err) + } + _ = body(t, resp) + if resp.StatusCode != http.StatusForbidden || + resp.Header.Get("Referrer-Policy") != "no-referrer" || + !strings.Contains(resp.Header.Get("Content-Security-Policy"), "default-src 'none'") { + t.Fatalf("%d %v", resp.StatusCode, resp.Header) } } From 088039bc071c044bbae75d8d20cd93efcde0e2e2 Mon Sep 17 00:00:00 2001 From: Jan Unterbrink Date: Mon, 23 Nov 2026 11:15:09 +0100 Subject: [PATCH 2/7] refactor(account): make Profile an interface with an unexported profile Profile is now an exported interface (ID() string) backed by an unexported *profile built by ParseProfile, so more profile information can be added later without changing callers. Profiles are compared by ID; filestore rejects nil profiles, re-validates IDs and parses invite profiles from disk; CreateInvite rejects a nil profile. Co-Authored-By: Claude Opus 5.5 --- cmd/spotify-mcp/main.go | 6 ++--- internal/account/account.go | 37 +++++++++++++++++++++------- internal/account/account_test.go | 22 +++++++++++++---- internal/account/invite.go | 4 +++ internal/account/service.go | 4 +-- internal/config/config_test.go | 2 +- internal/filestore/filestore.go | 30 ++++++++++++++++------ internal/filestore/filestore_test.go | 24 +++++++++++++++--- internal/web/web.go | 2 +- internal/web/web_test.go | 14 ++++++++--- 10 files changed, 111 insertions(+), 34 deletions(-) diff --git a/cmd/spotify-mcp/main.go b/cmd/spotify-mcp/main.go index 9080f3f..3bcf783 100644 --- a/cmd/spotify-mcp/main.go +++ b/cmd/spotify-mcp/main.go @@ -71,7 +71,7 @@ func invite(args []string) error { return err } fmt.Println(cfg.InviteURL(code)) - fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", cfg.Profile, expires.Format("2006-01-02 15:04 MST")) + fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", cfg.Profile.ID(), expires.Format("2006-01-02 15:04 MST")) return nil } @@ -97,7 +97,7 @@ func serve(log *slog.Logger) error { accounts := account.NewService(store, store, oauth, api) if _, err := store.Connection(context.Background(), cfg.Profile); errors.Is(err, account.ErrNotFound) { - log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", cfg.Profile) + log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", cfg.Profile.ID()) } servers := []*http.Server{ @@ -114,7 +114,7 @@ func serve(log *slog.Logger) error { WriteTimeout: 30 * time.Second, }, } - log.Info("spotify-mcp started", "version", version, "profile", cfg.Profile, "connect_url", cfg.PublicURL.JoinPath("connect").String()) + log.Info("spotify-mcp started", "version", version, "profile", cfg.Profile.ID(), "connect_url", cfg.PublicURL.JoinPath("connect").String()) return run(log, servers) } diff --git a/internal/account/account.go b/internal/account/account.go index fa533d4..14d25fa 100644 --- a/internal/account/account.go +++ b/internal/account/account.go @@ -14,19 +14,38 @@ import ( "time" ) -// Profile names one connected account. Phase 1 uses a single profile; the -// type exists so a sign-in system can map people to profiles later. -type Profile string +// Profile is one connected account. Phase 1 uses a single profile; it is an +// interface so more about a profile (a display name, the person a sign-in +// system maps to it) can be added later without changing the code that only +// passes profiles around. +// +// Profiles are not comparable with ==; compare their IDs. +type Profile interface { + // ID is the validated identifier: 1-63 lower-case letters, digits and + // dashes. Adapters use it in file and key names. + ID() string +} + +// profile is the Profile built by ParseProfile. +type profile struct { + id string +} + +func (p *profile) ID() string { return p.id } + +// String makes a profile print as its ID in logs and messages. +func (p *profile) String() string { return p.id } var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) -// ParseProfile checks a profile name. Adapters may use it in file or key -// names, so it is restricted to lower-case letters, digits and dashes. -func ParseProfile(s string) (Profile, error) { - if !profileRe.MatchString(s) { - return "", fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) +// ParseProfile checks a profile ID and returns its Profile. Adapters may use +// the ID in file or key names, so it is restricted to lower-case letters, +// digits and dashes. +func ParseProfile(id string) (Profile, error) { + if !profileRe.MatchString(id) { + return nil, fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", id) } - return Profile(s), nil + return &profile{id: id}, nil } // User is the Spotify account behind a connection. diff --git a/internal/account/account_test.go b/internal/account/account_test.go index f964542..3faba86 100644 --- a/internal/account/account_test.go +++ b/internal/account/account_test.go @@ -12,7 +12,16 @@ import ( "github.com/subpathdev/spotify-mcp/internal/filestore" ) -const profile = account.Profile("default") +var profile = mustProfile("default") + +// mustProfile parses a profile ID that the test knows to be valid. +func mustProfile(id string) account.Profile { + p, err := account.ParseProfile(id) + if err != nil { + panic(err) + } + return p +} // fakeOAuth issues tokens for the code "good" and the verifier of the last // started login. @@ -103,7 +112,7 @@ func TestLoginConnectsAndUsesUpInvite(t *testing.T) { code := e.invite(t) st, err := e.svc.Status(ctx, code) - if err != nil || st.Connected || st.Profile != profile { + if err != nil || st.Connected || st.Profile.ID() != profile.ID() { t.Fatalf("status before: %+v %v", st, err) } user, err := e.svc.FinishLogin(ctx, e.start(t, code)) @@ -177,7 +186,7 @@ func TestDisconnect(t *testing.T) { if st, _ := e.svc.Status(ctx, code); !st.Connected || st.User.Name() != "Jan" { t.Fatalf("status: %+v", st) } - if p, err := e.svc.Disconnect(ctx, code); err != nil || p != profile { + if p, err := e.svc.Disconnect(ctx, code); err != nil || p.ID() != profile.ID() { t.Fatalf("disconnect: %q %v", p, err) } if _, err := e.store.Connection(ctx, profile); !errors.Is(err, account.ErrNotFound) { @@ -201,6 +210,9 @@ func TestInvites(t *testing.T) { if _, err := e.svc.StartLogin(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { t.Fatalf("expired invite accepted: %v", err) } + if _, _, err := e.inviter.CreateInvite(ctx, nil, time.Hour); err == nil { + t.Fatal("nil profile accepted") + } if _, _, err := e.inviter.CreateInvite(ctx, profile, 0); err == nil { t.Fatal("zero TTL accepted") } @@ -212,7 +224,7 @@ func TestParseProfile(t *testing.T) { t.Errorf("%q accepted", s) } } - if p, err := account.ParseProfile("jan-2"); err != nil || p != "jan-2" { - t.Fatalf("valid profile: %q %v", p, err) + if p, err := account.ParseProfile("jan-2"); err != nil || p.ID() != "jan-2" { + t.Fatalf("valid profile: %v %v", p, err) } } diff --git a/internal/account/invite.go b/internal/account/invite.go index 0a9316a..539506b 100644 --- a/internal/account/invite.go +++ b/internal/account/invite.go @@ -2,6 +2,7 @@ package account import ( "context" + "errors" "fmt" "time" ) @@ -20,6 +21,9 @@ func NewInviter(invites Invites, opts ...Option) *Inviter { // CreateInvite returns a new one-time code for p and when it expires. func (i *Inviter) CreateInvite(ctx context.Context, p Profile, ttl time.Duration) (InviteCode, time.Time, error) { + if p == nil { + return "", time.Time{}, errors.New("invite needs a profile") + } if ttl <= 0 { return "", time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) } diff --git a/internal/account/service.go b/internal/account/service.go index a46bac9..b2f8f2b 100644 --- a/internal/account/service.go +++ b/internal/account/service.go @@ -163,10 +163,10 @@ func (s *Service) FinishLogin(ctx context.Context, cb Callback) (User, error) { func (s *Service) Disconnect(ctx context.Context, code InviteCode) (Profile, error) { inv, err := s.takeInvite(ctx, hashInvite(code)) if err != nil { - return "", err + return nil, err } if err := s.tokens.DeleteConnection(ctx, inv.Profile); err != nil { - return "", fmt.Errorf("delete connection: %w", err) + return nil, fmt.Errorf("delete connection: %w", err) } return inv.Profile, nil } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 9e8d385..2c94fa0 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -14,7 +14,7 @@ func TestLoadDefaults(t *testing.T) { if err != nil { t.Fatal(err) } - if c.PublicURL.String() != "https://spotify.example.com" || c.Profile != "default" || c.DataDir != "/data" || c.MCPAddr != ":8000" { + if c.PublicURL.String() != "https://spotify.example.com" || c.Profile.ID() != "default" || c.DataDir != "/data" || c.MCPAddr != ":8000" { t.Fatalf("%+v", c) } if err := c.RequireCredentials(); err == nil || !strings.Contains(err.Error(), "SPOTIFY_CLIENT_SECRET") { diff --git a/internal/filestore/filestore.go b/internal/filestore/filestore.go index c96088f..591c9f9 100644 --- a/internal/filestore/filestore.go +++ b/internal/filestore/filestore.go @@ -72,6 +72,14 @@ type inviteRecord struct { Expires time.Time `json:"expires"` } +func (r inviteRecord) invite(h account.InviteHash) (account.Invite, error) { + p, err := account.ParseProfile(r.Profile) + if err != nil { + return account.Invite{}, fmt.Errorf("invite %s: %w", h, err) + } + return account.Invite{Hash: h, Profile: p, Expires: r.Expires}, nil +} + // lock takes the in-process and the cross-process lock. func (s *Store) lock() (unlock func(), err error) { s.mu.Lock() @@ -84,12 +92,16 @@ func (s *Store) lock() (unlock func(), err error) { } func (s *Store) connectionPath(p account.Profile) (string, error) { - // Profiles are validated when parsed; check again because the value ends - // up in a file name. - if _, err := account.ParseProfile(string(p)); err != nil { + if p == nil { + return "", errors.New("no profile given") + } + // ParseProfile validates IDs, but Profile is an interface that other + // code may implement; check again because the ID ends up in a file name. + id := p.ID() + if _, err := account.ParseProfile(id); err != nil { return "", err } - return filepath.Join(s.dir, "tokens", string(p)+".json"), nil + return filepath.Join(s.dir, "tokens", id+".json"), nil } // Connection implements account.Tokens. @@ -193,7 +205,7 @@ func (s *Store) changeInvites(fn func(map[account.InviteHash]inviteRecord) error // AddInvite implements account.Invites. func (s *Store) AddInvite(_ context.Context, i account.Invite) error { return s.changeInvites(func(inv map[account.InviteHash]inviteRecord) error { - inv[i.Hash] = inviteRecord{Profile: string(i.Profile), Expires: i.Expires} + inv[i.Hash] = inviteRecord{Profile: i.Profile.ID(), Expires: i.Expires} return nil }) } @@ -213,7 +225,7 @@ func (s *Store) Invite(_ context.Context, h account.InviteHash) (account.Invite, if !ok { return account.Invite{}, account.ErrNotFound } - return account.Invite{Hash: h, Profile: account.Profile(r.Profile), Expires: r.Expires}, nil + return r.invite(h) } // TakeInvite implements account.Invites. @@ -224,8 +236,12 @@ func (s *Store) TakeInvite(_ context.Context, h account.InviteHash) (account.Inv if !ok { return account.ErrNotFound } + i, err := r.invite(h) + if err != nil { + return err // nothing is written, so the invite stays until it expires + } delete(inv, h) - out = account.Invite{Hash: h, Profile: account.Profile(r.Profile), Expires: r.Expires} + out = i return nil }) return out, err diff --git a/internal/filestore/filestore_test.go b/internal/filestore/filestore_test.go index 9d67c0f..59f2723 100644 --- a/internal/filestore/filestore_test.go +++ b/internal/filestore/filestore_test.go @@ -13,7 +13,16 @@ import ( "github.com/subpathdev/spotify-mcp/internal/account" ) -const profile = account.Profile("default") +var profile = mustProfile("default") + +// mustProfile parses a profile ID that the test knows to be valid. +func mustProfile(id string) account.Profile { + p, err := account.ParseProfile(id) + if err != nil { + panic(err) + } + return p +} func open(t *testing.T, dir string) *Store { t.Helper() @@ -76,11 +85,20 @@ func TestUpdateConnection(t *testing.T) { } } +// badProfile is a Profile that skipped ParseProfile, as another +// implementation of the interface could. +type badProfile string + +func (b badProfile) ID() string { return string(b) } + func TestRejectsBadProfile(t *testing.T) { s := open(t, t.TempDir()) - if err := s.SaveConnection(context.Background(), "../x", account.Connection{}); err == nil { + if err := s.SaveConnection(context.Background(), badProfile("../x"), account.Connection{}); err == nil { t.Fatal("path traversal accepted") } + if err := s.SaveConnection(context.Background(), nil, account.Connection{}); err == nil { + t.Fatal("nil profile accepted") + } } func TestInviteTakenOnce(t *testing.T) { @@ -91,7 +109,7 @@ func TestInviteTakenOnce(t *testing.T) { if err := s.AddInvite(ctx, inv); err != nil { t.Fatal(err) } - if got, err := s.Invite(ctx, "h1"); err != nil || got.Profile != profile { + if got, err := s.Invite(ctx, "h1"); err != nil || got.Profile.ID() != profile.ID() { t.Fatalf("invite: %+v %v", got, err) } diff --git a/internal/web/web.go b/internal/web/web.go index 537b15d..be8e441 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -104,7 +104,7 @@ func (h *handler) connectPost(w http.ResponseWriter, r *http.Request) { h.fail(w, err) return } - h.log.Info("spotify account disconnected", "profile", profile) + h.log.Info("spotify account disconnected", "profile", profile.ID()) h.render(w, http.StatusOK, pageData{ Title: "Disconnected", Message: "The Spotify account is disconnected and its token deleted. To also remove the app on Spotify's side, open spotify.com → Account → Manage apps.", diff --git a/internal/web/web_test.go b/internal/web/web_test.go index 3b7e55e..d80f8f0 100644 --- a/internal/web/web_test.go +++ b/internal/web/web_test.go @@ -73,9 +73,17 @@ func newEnv(t *testing.T) *env { return &env{srv: srv, inviter: account.NewInviter(st), store: st, identity: id} } +var profile = func() account.Profile { + p, err := account.ParseProfile("default") + if err != nil { + panic(err) + } + return p +}() + func (e *env) invite(t *testing.T) string { t.Helper() - code, _, err := e.inviter.CreateInvite(context.Background(), "default", time.Hour) + code, _, err := e.inviter.CreateInvite(context.Background(), profile, time.Hour) if err != nil { t.Fatal(err) } @@ -161,7 +169,7 @@ func TestConnectFlow(t *testing.T) { if status, _ := get(t, b, e.srv.URL+"/connect?invite="+code); status != http.StatusForbidden { t.Fatalf("used invite: %d", status) } - if _, err := e.store.Connection(context.Background(), "default"); err != nil { + if _, err := e.store.Connection(context.Background(), profile); err != nil { t.Fatalf("not stored: %v", err) } } @@ -190,7 +198,7 @@ func TestDisconnect(t *testing.T) { if page := body(t, resp); resp.StatusCode != http.StatusOK || !strings.Contains(page, "Disconnected") { t.Fatalf("disconnect: %d %s", resp.StatusCode, page) } - if _, err := e.store.Connection(context.Background(), "default"); !errors.Is(err, account.ErrNotFound) { + if _, err := e.store.Connection(context.Background(), profile); !errors.Is(err, account.ErrNotFound) { t.Fatalf("connection kept: %v", err) } } From c0a4331009d06a4eba8fa224f2709dd37bfcb66c Mon Sep 17 00:00:00 2001 From: Jan Unterbrink Date: Mon, 23 Nov 2026 11:49:11 +0100 Subject: [PATCH 3/7] refactor(account): put the connected Spotify account on Profile Profile is now the profile as loaded: ID() plus Account(), the connected SpotifyAccount (renamed from User). A new Profiles loader (exported interface, unexported implementation) builds it from the Tokens port, so it is a fresh snapshot. The key used by config, invites, Tokens and the token source is the new ProfileID type. Status, FinishLogin and Disconnect return the Profile; Identity.User is now Identity.Account. The on-disk format is unchanged. Co-Authored-By: Claude Opus 5.5 --- cmd/spotify-mcp/main.go | 19 ++++-- internal/account/account.go | 97 ++++++++++++++++------------ internal/account/account_test.go | 83 ++++++++++++++++-------- internal/account/invite.go | 11 ++-- internal/account/profiles.go | 38 +++++++++++ internal/account/service.go | 56 ++++++++-------- internal/account/tokensource.go | 6 +- internal/account/tokensource_test.go | 12 ++-- internal/config/config.go | 4 +- internal/config/config_test.go | 2 +- internal/filestore/filestore.go | 40 ++++++------ internal/filestore/filestore_test.go | 39 ++++------- internal/spotify/auth.go | 10 +-- internal/spotify/spotify_test.go | 4 +- internal/web/web.go | 16 +++-- internal/web/web_test.go | 12 +--- 16 files changed, 254 insertions(+), 195 deletions(-) create mode 100644 internal/account/profiles.go diff --git a/cmd/spotify-mcp/main.go b/cmd/spotify-mcp/main.go index 3bcf783..e0edc46 100644 --- a/cmd/spotify-mcp/main.go +++ b/cmd/spotify-mcp/main.go @@ -66,12 +66,12 @@ func invite(args []string) error { if err != nil { return err } - code, expires, err := account.NewInviter(store).CreateInvite(context.Background(), cfg.Profile, *ttl) + code, expires, err := account.NewInviter(store).CreateInvite(context.Background(), cfg.ProfileID, *ttl) if err != nil { return err } fmt.Println(cfg.InviteURL(code)) - fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", cfg.Profile.ID(), expires.Format("2006-01-02 15:04 MST")) + fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", cfg.ProfileID, expires.Format("2006-01-02 15:04 MST")) return nil } @@ -92,12 +92,19 @@ func serve(log *slog.Logger) error { ClientID: cfg.ClientID, ClientSecret: cfg.ClientSecret, RedirectURL: cfg.RedirectURL.String(), }) api := spotify.NewAPI(spotify.DefaultAPIURL, nil) - tokens := account.NewTokenSource(store, oauth, cfg.Profile) + tokens := account.NewTokenSource(store, oauth, cfg.ProfileID) player := playback.NewService(spotify.NewPlayer(api, tokens)) accounts := account.NewService(store, store, oauth, api) - if _, err := store.Connection(context.Background(), cfg.Profile); errors.Is(err, account.ErrNotFound) { - log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", cfg.Profile.ID()) + // Only for the log: a broken token file shouldn't stop the server, the + // tools report it when they need the token. + prof, err := account.NewProfiles(store).Profile(context.Background(), cfg.ProfileID) + if err != nil { + log.Warn("can't read the connected account", "profile", cfg.ProfileID, "err", err) + } else if acc, ok := prof.Account(); ok { + log.Info("spotify account connected", "profile", prof.ID(), "spotify_user", acc.ID) + } else { + log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", prof.ID()) } servers := []*http.Server{ @@ -114,7 +121,7 @@ func serve(log *slog.Logger) error { WriteTimeout: 30 * time.Second, }, } - log.Info("spotify-mcp started", "version", version, "profile", cfg.Profile.ID(), "connect_url", cfg.PublicURL.JoinPath("connect").String()) + log.Info("spotify-mcp started", "version", version, "profile", cfg.ProfileID, "connect_url", cfg.PublicURL.JoinPath("connect").String()) return run(log, servers) } diff --git a/internal/account/account.go b/internal/account/account.go index 14d25fa..2b47415 100644 --- a/internal/account/account.go +++ b/internal/account/account.go @@ -14,52 +14,65 @@ import ( "time" ) -// Profile is one connected account. Phase 1 uses a single profile; it is an -// interface so more about a profile (a display name, the person a sign-in -// system maps to it) can be added later without changing the code that only -// passes profiles around. -// -// Profiles are not comparable with ==; compare their IDs. +// ProfileID identifies a profile: 1-63 lower-case letters, digits and +// dashes. Adapters use it in file and key names. Get one from ParseProfileID. +type ProfileID string + +var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) + +// ParseProfileID checks a profile ID. +func ParseProfileID(s string) (ProfileID, error) { + if !profileRe.MatchString(s) { + return "", fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) + } + return ProfileID(s), nil +} + +// Profile is one slot a Spotify account can be connected to, as it was when +// it was loaded (see Profiles). Phase 1 uses a single profile; more about a +// profile (a display name, the person a sign-in system maps to it) is added +// here later. type Profile interface { - // ID is the validated identifier: 1-63 lower-case letters, digits and - // dashes. Adapters use it in file and key names. - ID() string + ID() ProfileID + // Account is the connected Spotify account; false if none is connected. + Account() (SpotifyAccount, bool) } -// profile is the Profile built by ParseProfile. +// profile is the Profile this package builds. type profile struct { - id string + id ProfileID + account SpotifyAccount + connected bool + connectedAt time.Time // for Status; not part of Profile } -func (p *profile) ID() string { return p.id } - -// String makes a profile print as its ID in logs and messages. -func (p *profile) String() string { return p.id } - -var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) - -// ParseProfile checks a profile ID and returns its Profile. Adapters may use -// the ID in file or key names, so it is restricted to lower-case letters, -// digits and dashes. -func ParseProfile(id string) (Profile, error) { - if !profileRe.MatchString(id) { - return nil, fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", id) +// newProfile builds a profile from its connection; c is nil if it has none. +func newProfile(id ProfileID, c *Connection) *profile { + p := &profile{id: id} + if c != nil { + p.account, p.connected, p.connectedAt = c.Account, true, c.ConnectedAt } - return &profile{id: id}, nil + return p } -// User is the Spotify account behind a connection. -type User struct { +func (p *profile) ID() ProfileID { return p.id } +func (p *profile) Account() (SpotifyAccount, bool) { return p.account, p.connected } + +// String makes a profile print as its ID in logs and messages. +func (p *profile) String() string { return string(p.id) } + +// SpotifyAccount is the Spotify account connected to a profile. +type SpotifyAccount struct { ID string DisplayName string } // Name is what to show a person: the display name, else the account ID. -func (u User) Name() string { - if u.DisplayName != "" { - return u.DisplayName +func (a SpotifyAccount) Name() string { + if a.DisplayName != "" { + return a.DisplayName } - return u.ID + return a.ID } // Token is an OAuth token pair as Spotify issues it. @@ -75,7 +88,7 @@ const expiryDelta = 30 * time.Second // Connection is what is stored per profile. type Connection struct { Token Token - User User + Account SpotifyAccount ConnectedAt time.Time } @@ -92,9 +105,9 @@ type InviteHash string // Invite lets whoever holds its code connect or disconnect one profile. type Invite struct { - Hash InviteHash - Profile Profile - Expires time.Time + Hash InviteHash + ProfileID ProfileID + Expires time.Time } // Errors returned by this package and by the ports' implementations. @@ -127,15 +140,15 @@ var ( // Tokens stores one Connection per profile. type Tokens interface { // Connection returns ErrNotFound if the profile has none. - Connection(ctx context.Context, p Profile) (Connection, error) + Connection(ctx context.Context, id ProfileID) (Connection, error) // SaveConnection replaces the profile's connection. - SaveConnection(ctx context.Context, p Profile, c Connection) error + SaveConnection(ctx context.Context, id ProfileID, c Connection) error // UpdateConnection reads, changes and writes the connection as one step: // no other write to the profile may happen in between. It returns // ErrNotFound if the profile has none, and writes nothing if fn fails. - UpdateConnection(ctx context.Context, p Profile, fn func(*Connection) error) error + UpdateConnection(ctx context.Context, id ProfileID, fn func(*Connection) error) error // DeleteConnection forgets the profile's connection; a missing one is fine. - DeleteConnection(ctx context.Context, p Profile) error + DeleteConnection(ctx context.Context, id ProfileID) error } // Invites stores pending invites. @@ -161,8 +174,8 @@ type OAuth interface { Refresh(ctx context.Context, refreshToken string) (Token, error) } -// Identity tells who an access token belongs to. +// Identity tells which Spotify account an access token belongs to. type Identity interface { - // User returns ErrNotAllowlisted for accounts the app may not serve. - User(ctx context.Context, accessToken string) (User, error) + // Account returns ErrNotAllowlisted for accounts the app may not serve. + Account(ctx context.Context, accessToken string) (SpotifyAccount, error) } diff --git a/internal/account/account_test.go b/internal/account/account_test.go index 3faba86..f3a5eff 100644 --- a/internal/account/account_test.go +++ b/internal/account/account_test.go @@ -12,16 +12,7 @@ import ( "github.com/subpathdev/spotify-mcp/internal/filestore" ) -var profile = mustProfile("default") - -// mustProfile parses a profile ID that the test knows to be valid. -func mustProfile(id string) account.Profile { - p, err := account.ParseProfile(id) - if err != nil { - panic(err) - } - return p -} +const profile = account.ProfileID("default") // fakeOAuth issues tokens for the code "good" and the verifier of the last // started login. @@ -58,8 +49,8 @@ func (f *fakeOAuth) Refresh(ctx context.Context, rt string) (account.Token, erro type fakeIdentity struct{ err error } -func (f fakeIdentity) User(context.Context, string) (account.User, error) { - return account.User{ID: "jan", DisplayName: "Jan"}, f.err +func (f fakeIdentity) Account(context.Context, string) (account.SpotifyAccount, error) { + return account.SpotifyAccount{ID: "jan", DisplayName: "Jan"}, f.err } type env struct { @@ -112,15 +103,21 @@ func TestLoginConnectsAndUsesUpInvite(t *testing.T) { code := e.invite(t) st, err := e.svc.Status(ctx, code) - if err != nil || st.Connected || st.Profile.ID() != profile.ID() { + if err != nil || st.Profile.ID() != profile || !st.ConnectedAt.IsZero() { t.Fatalf("status before: %+v %v", st, err) } - user, err := e.svc.FinishLogin(ctx, e.start(t, code)) - if err != nil || user.Name() != "Jan" { - t.Fatalf("finish: %+v %v", user, err) + if _, connected := st.Profile.Account(); connected { + t.Fatal("connected before login") + } + p, err := e.svc.FinishLogin(ctx, e.start(t, code)) + if err != nil || p.ID() != profile { + t.Fatalf("finish: %v %v", p, err) + } + if acc, ok := p.Account(); !ok || acc.Name() != "Jan" { + t.Fatalf("finish account: %+v %v", acc, ok) } c, err := e.store.Connection(ctx, profile) - if err != nil || c.Token.RefreshToken != "r1" || c.User.ID != "jan" || !c.ConnectedAt.Equal(e.now) { + if err != nil || c.Token.RefreshToken != "r1" || c.Account.ID != "jan" || !c.ConnectedAt.Equal(e.now) { t.Fatalf("stored: %+v %v", c, err) } if _, err := e.svc.Status(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { @@ -183,11 +180,19 @@ func TestDisconnect(t *testing.T) { t.Fatal(err) } code := e.invite(t) - if st, _ := e.svc.Status(ctx, code); !st.Connected || st.User.Name() != "Jan" { - t.Fatalf("status: %+v", st) + st, err := e.svc.Status(ctx, code) + if err != nil || !st.ConnectedAt.Equal(e.now) { + t.Fatalf("status: %+v %v", st, err) + } + if acc, ok := st.Profile.Account(); !ok || acc.Name() != "Jan" { + t.Fatalf("status account: %+v %v", acc, ok) } - if p, err := e.svc.Disconnect(ctx, code); err != nil || p.ID() != profile.ID() { - t.Fatalf("disconnect: %q %v", p, err) + p, err := e.svc.Disconnect(ctx, code) + if err != nil || p.ID() != profile { + t.Fatalf("disconnect: %v %v", p, err) + } + if _, ok := p.Account(); ok { + t.Fatal("account kept after disconnect") } if _, err := e.store.Connection(ctx, profile); !errors.Is(err, account.ErrNotFound) { t.Fatalf("connection kept: %v", err) @@ -210,21 +215,45 @@ func TestInvites(t *testing.T) { if _, err := e.svc.StartLogin(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { t.Fatalf("expired invite accepted: %v", err) } - if _, _, err := e.inviter.CreateInvite(ctx, nil, time.Hour); err == nil { - t.Fatal("nil profile accepted") + if _, _, err := e.inviter.CreateInvite(ctx, "../x", time.Hour); err == nil { + t.Fatal("invalid profile accepted") } if _, _, err := e.inviter.CreateInvite(ctx, profile, 0); err == nil { t.Fatal("zero TTL accepted") } } -func TestParseProfile(t *testing.T) { +func TestParseProfileID(t *testing.T) { for _, s := range []string{"", "A", "../x", "a/b", "-a", string(make([]byte, 64))} { - if _, err := account.ParseProfile(s); err == nil { + if _, err := account.ParseProfileID(s); err == nil { t.Errorf("%q accepted", s) } } - if p, err := account.ParseProfile("jan-2"); err != nil || p.ID() != "jan-2" { - t.Fatalf("valid profile: %v %v", p, err) + if id, err := account.ParseProfileID("jan-2"); err != nil || id != "jan-2" { + t.Fatalf("valid profile: %q %v", id, err) + } +} + +func TestProfiles(t *testing.T) { + ctx := context.Background() + e := newEnv(t, nil) + profiles := account.NewProfiles(e.store) + p, err := profiles.Profile(ctx, profile) + if err != nil || p.ID() != profile { + t.Fatalf("profile: %v %v", p, err) + } + if _, ok := p.Account(); ok { + t.Fatal("account without a connection") + } + if _, err := e.svc.FinishLogin(ctx, e.start(t, e.invite(t))); err != nil { + t.Fatal(err) + } + // A loaded profile is a snapshot: p stays as it was, a new load sees the login. + if _, ok := p.Account(); ok { + t.Fatal("snapshot changed") + } + p, err = profiles.Profile(ctx, profile) + if acc, ok := p.Account(); err != nil || !ok || acc.ID != "jan" { + t.Fatalf("after login: %+v %v %v", acc, ok, err) } } diff --git a/internal/account/invite.go b/internal/account/invite.go index 539506b..61ce5e6 100644 --- a/internal/account/invite.go +++ b/internal/account/invite.go @@ -2,7 +2,6 @@ package account import ( "context" - "errors" "fmt" "time" ) @@ -19,17 +18,17 @@ func NewInviter(invites Invites, opts ...Option) *Inviter { return &Inviter{invites: invites, now: apply(opts).now} } -// CreateInvite returns a new one-time code for p and when it expires. -func (i *Inviter) CreateInvite(ctx context.Context, p Profile, ttl time.Duration) (InviteCode, time.Time, error) { - if p == nil { - return "", time.Time{}, errors.New("invite needs a profile") +// CreateInvite returns a new one-time code for the profile and when it expires. +func (i *Inviter) CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) { + if _, err := ParseProfileID(string(id)); err != nil { + return "", time.Time{}, err } if ttl <= 0 { return "", time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) } code := InviteCode(randomString()) now := i.now() - inv := Invite{Hash: hashInvite(code), Profile: p, Expires: now.Add(ttl)} + inv := Invite{Hash: hashInvite(code), ProfileID: id, Expires: now.Add(ttl)} if err := i.invites.PruneInvites(ctx, now); err != nil { return "", time.Time{}, fmt.Errorf("prune invites: %w", err) } diff --git a/internal/account/profiles.go b/internal/account/profiles.go new file mode 100644 index 0000000..745943e --- /dev/null +++ b/internal/account/profiles.go @@ -0,0 +1,38 @@ +package account + +import ( + "context" + "errors" + "fmt" +) + +// Profiles loads profiles with what is known about them right now. +type Profiles interface { + // Profile returns the profile with its connected Spotify account, if any. + // A profile without a connection is not an error. + Profile(ctx context.Context, id ProfileID) (Profile, error) +} + +// NewProfiles returns Profiles that reads connections from tokens. +func NewProfiles(tokens Tokens) Profiles { + return profiles{tokens: tokens} +} + +type profiles struct { + tokens Tokens +} + +func (p profiles) Profile(ctx context.Context, id ProfileID) (Profile, error) { + return loadProfile(ctx, p.tokens, id) +} + +func loadProfile(ctx context.Context, tokens Tokens, id ProfileID) (*profile, error) { + c, err := tokens.Connection(ctx, id) + switch { + case errors.Is(err, ErrNotFound): + return newProfile(id, nil), nil + case err != nil: + return nil, fmt.Errorf("load connection: %w", err) + } + return newProfile(id, &c), nil +} diff --git a/internal/account/service.go b/internal/account/service.go index b2f8f2b..a6ac767 100644 --- a/internal/account/service.go +++ b/internal/account/service.go @@ -33,7 +33,7 @@ type Service struct { type pendingLogin struct { invite InviteHash - profile Profile + profile ProfileID verifier string nonce string expires time.Time @@ -48,11 +48,10 @@ func NewService(tokens Tokens, invites Invites, oauth OAuth, identity Identity, } } -// Status is what an invite link's page shows. +// Status is what an invite link's page shows: the invite's profile with its +// connected account, and since when it is connected (zero if it isn't). type Status struct { Profile Profile - Connected bool - User User ConnectedAt time.Time } @@ -79,16 +78,11 @@ func (s *Service) Status(ctx context.Context, code InviteCode) (Status, error) { if err != nil { return Status{}, err } - st := Status{Profile: inv.Profile} - c, err := s.tokens.Connection(ctx, inv.Profile) - switch { - case errors.Is(err, ErrNotFound): - case err != nil: - return Status{}, fmt.Errorf("load connection: %w", err) - default: - st.Connected, st.User, st.ConnectedAt = true, c.User, c.ConnectedAt + p, err := loadProfile(ctx, s.tokens, inv.ProfileID) + if err != nil { + return Status{}, err } - return st, nil + return Status{Profile: p, ConnectedAt: p.connectedAt}, nil } // StartLogin begins the OAuth login (state + PKCE) for an invite. The invite @@ -112,7 +106,7 @@ func (s *Service) StartLogin(ctx context.Context, code InviteCode) (Login, error return Login{}, ErrTooManyLogins } s.pending[state] = pendingLogin{ - invite: inv.Hash, profile: inv.Profile, + invite: inv.Hash, profile: inv.ProfileID, verifier: verifier, nonce: nonce, expires: now.Add(LoginTTL), } return Login{URL: s.oauth.AuthCodeURL(state, verifier), Nonce: nonce}, nil @@ -120,55 +114,57 @@ func (s *Service) StartLogin(ctx context.Context, code InviteCode) (Login, error // FinishLogin completes a login: it exchanges the code, checks the account // may use the app, uses up the invite and stores the connection, replacing -// any previous one. Each state can be finished at most once. -func (s *Service) FinishLogin(ctx context.Context, cb Callback) (User, error) { +// any previous one. Each state can be finished at most once. It returns the +// profile with the newly connected account. +func (s *Service) FinishLogin(ctx context.Context, cb Callback) (Profile, error) { s.mu.Lock() p, ok := s.pending[cb.State] delete(s.pending, cb.State) s.mu.Unlock() if !ok || s.now().After(p.expires) || subtle.ConstantTimeCompare([]byte(cb.Nonce), []byte(p.nonce)) != 1 { - return User{}, ErrLoginExpired + return nil, ErrLoginExpired } if cb.Error == "access_denied" { - return User{}, ErrLoginCancelled + return nil, ErrLoginCancelled } if cb.Error != "" { - return User{}, fmt.Errorf("spotify refused the login: %s", cb.Error) + return nil, fmt.Errorf("spotify refused the login: %s", cb.Error) } tok, err := s.oauth.Exchange(ctx, cb.Code, p.verifier) if err != nil { - return User{}, fmt.Errorf("exchange code: %w", err) + return nil, fmt.Errorf("exchange code: %w", err) } if tok.RefreshToken == "" { - return User{}, errors.New("spotify sent no refresh token") + return nil, errors.New("spotify sent no refresh token") } // Before the invite is used up: an account that isn't allowlisted yet can // try again with the same link once the owner added it. - user, err := s.identity.User(ctx, tok.AccessToken) + acc, err := s.identity.Account(ctx, tok.AccessToken) if err != nil { - return User{}, fmt.Errorf("look up account: %w", err) + return nil, fmt.Errorf("look up account: %w", err) } if _, err := s.takeInvite(ctx, p.invite); err != nil { - return User{}, err + return nil, err } - c := Connection{Token: tok, User: user, ConnectedAt: s.now()} + c := Connection{Token: tok, Account: acc, ConnectedAt: s.now()} if err := s.tokens.SaveConnection(ctx, p.profile, c); err != nil { - return User{}, fmt.Errorf("save connection: %w", err) + return nil, fmt.Errorf("save connection: %w", err) } - return user, nil + return newProfile(p.profile, &c), nil } -// Disconnect uses up the invite and deletes its profile's connection. +// Disconnect uses up the invite and deletes its profile's connection. It +// returns the profile, now without an account. func (s *Service) Disconnect(ctx context.Context, code InviteCode) (Profile, error) { inv, err := s.takeInvite(ctx, hashInvite(code)) if err != nil { return nil, err } - if err := s.tokens.DeleteConnection(ctx, inv.Profile); err != nil { + if err := s.tokens.DeleteConnection(ctx, inv.ProfileID); err != nil { return nil, fmt.Errorf("delete connection: %w", err) } - return inv.Profile, nil + return newProfile(inv.ProfileID, nil), nil } func (s *Service) checkInvite(ctx context.Context, code InviteCode) (Invite, error) { diff --git a/internal/account/tokensource.go b/internal/account/tokensource.go index 44e0f78..79661ca 100644 --- a/internal/account/tokensource.go +++ b/internal/account/tokensource.go @@ -17,13 +17,13 @@ import ( type TokenSource struct { tokens Tokens oauth OAuth - profile Profile + profile ProfileID now func() time.Time } // NewTokenSource returns a TokenSource for p. -func NewTokenSource(tokens Tokens, oauth OAuth, p Profile, opts ...Option) *TokenSource { - return &TokenSource{tokens: tokens, oauth: oauth, profile: p, now: apply(opts).now} +func NewTokenSource(tokens Tokens, oauth OAuth, id ProfileID, opts ...Option) *TokenSource { + return &TokenSource{tokens: tokens, oauth: oauth, profile: id, now: apply(opts).now} } // AccessToken returns a valid access token, or ErrNotConnected. diff --git a/internal/account/tokensource_test.go b/internal/account/tokensource_test.go index ed04f5f..1043f39 100644 --- a/internal/account/tokensource_test.go +++ b/internal/account/tokensource_test.go @@ -22,8 +22,8 @@ func (e *env) tokens() *account.TokenSource { func expired(rt string) account.Connection { return account.Connection{ - Token: account.Token{AccessToken: "old", RefreshToken: rt}, - User: account.User{ID: "jan", DisplayName: "Jan"}, + Token: account.Token{AccessToken: "old", RefreshToken: rt}, + Account: account.SpotifyAccount{ID: "jan", DisplayName: "Jan"}, } } @@ -54,7 +54,7 @@ func TestAccessTokenRefreshesAndPersists(t *testing.T) { t.Fatalf("refreshed %d times, want once", calls) } c, _ := e.store.Connection(ctx, profile) - if c.Token.RefreshToken != tc.stored || c.User.DisplayName != "Jan" { + if c.Token.RefreshToken != tc.stored || c.Account.DisplayName != "Jan" { t.Fatalf("stored %+v", c) } }) @@ -119,8 +119,8 @@ func TestLoginDuringRefreshWins(t *testing.T) { <-refreshing login := account.Connection{ - Token: account.Token{AccessToken: "new-access", RefreshToken: "new-account", Expiry: e.now.Add(time.Hour)}, - User: account.User{ID: "someone-else"}, + Token: account.Token{AccessToken: "new-access", RefreshToken: "new-account", Expiry: e.now.Add(time.Hour)}, + Account: account.SpotifyAccount{ID: "someone-else"}, } saved := make(chan error, 1) go func() { saved <- e.store.SaveConnection(ctx, profile, login) }() @@ -137,7 +137,7 @@ func TestLoginDuringRefreshWins(t *testing.T) { t.Fatal(err) } c, err := e.store.Connection(ctx, profile) - if err != nil || c.Token.RefreshToken != "new-account" || c.User.ID != "someone-else" { + if err != nil || c.Token.RefreshToken != "new-account" || c.Account.ID != "someone-else" { t.Fatalf("stored %+v %v, want the new login", c, err) } } diff --git a/internal/config/config.go b/internal/config/config.go index 0d0344c..37fb41c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -21,7 +21,7 @@ type Config struct { // PublicURL is the base of invite links. PublicURL *url.URL DataDir string - Profile account.Profile + ProfileID account.ProfileID MCPAddr string WebAddr string } @@ -64,7 +64,7 @@ func Load(getenv func(string) string) (Config, error) { } } - if c.Profile, err = account.ParseProfile(get("PROFILE", "default")); err != nil { + if c.ProfileID, err = account.ParseProfileID(get("PROFILE", "default")); err != nil { return Config{}, fmt.Errorf("PROFILE: %w", err) } return c, nil diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 2c94fa0..d9568c2 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -14,7 +14,7 @@ func TestLoadDefaults(t *testing.T) { if err != nil { t.Fatal(err) } - if c.PublicURL.String() != "https://spotify.example.com" || c.Profile.ID() != "default" || c.DataDir != "/data" || c.MCPAddr != ":8000" { + if c.PublicURL.String() != "https://spotify.example.com" || c.ProfileID != "default" || c.DataDir != "/data" || c.MCPAddr != ":8000" { t.Fatalf("%+v", c) } if err := c.RequireCredentials(); err == nil || !strings.Contains(err.Error(), "SPOTIFY_CLIENT_SECRET") { diff --git a/internal/filestore/filestore.go b/internal/filestore/filestore.go index 591c9f9..fe02ff7 100644 --- a/internal/filestore/filestore.go +++ b/internal/filestore/filestore.go @@ -53,14 +53,14 @@ type connectionRecord struct { func toRecord(c account.Connection) connectionRecord { return connectionRecord{ RefreshToken: c.Token.RefreshToken, AccessToken: c.Token.AccessToken, Expiry: c.Token.Expiry, - SpotifyUserID: c.User.ID, DisplayName: c.User.DisplayName, ConnectedAt: c.ConnectedAt, + SpotifyUserID: c.Account.ID, DisplayName: c.Account.DisplayName, ConnectedAt: c.ConnectedAt, } } func (r connectionRecord) connection() account.Connection { return account.Connection{ Token: account.Token{AccessToken: r.AccessToken, RefreshToken: r.RefreshToken, Expiry: r.Expiry}, - User: account.User{ID: r.SpotifyUserID, DisplayName: r.DisplayName}, + Account: account.SpotifyAccount{ID: r.SpotifyUserID, DisplayName: r.DisplayName}, ConnectedAt: r.ConnectedAt, } } @@ -73,11 +73,11 @@ type inviteRecord struct { } func (r inviteRecord) invite(h account.InviteHash) (account.Invite, error) { - p, err := account.ParseProfile(r.Profile) + id, err := account.ParseProfileID(r.Profile) if err != nil { return account.Invite{}, fmt.Errorf("invite %s: %w", h, err) } - return account.Invite{Hash: h, Profile: p, Expires: r.Expires}, nil + return account.Invite{Hash: h, ProfileID: id, Expires: r.Expires}, nil } // lock takes the in-process and the cross-process lock. @@ -91,22 +91,18 @@ func (s *Store) lock() (unlock func(), err error) { return func() { release(); s.mu.Unlock() }, nil } -func (s *Store) connectionPath(p account.Profile) (string, error) { - if p == nil { - return "", errors.New("no profile given") - } - // ParseProfile validates IDs, but Profile is an interface that other - // code may implement; check again because the ID ends up in a file name. - id := p.ID() - if _, err := account.ParseProfile(id); err != nil { +func (s *Store) connectionPath(id account.ProfileID) (string, error) { + // IDs are validated when parsed; check again because a ProfileID can also + // be made by conversion, and it ends up in a file name. + if _, err := account.ParseProfileID(string(id)); err != nil { return "", err } - return filepath.Join(s.dir, "tokens", id+".json"), nil + return filepath.Join(s.dir, "tokens", string(id)+".json"), nil } // Connection implements account.Tokens. -func (s *Store) Connection(_ context.Context, p account.Profile) (account.Connection, error) { - path, err := s.connectionPath(p) +func (s *Store) Connection(_ context.Context, id account.ProfileID) (account.Connection, error) { + path, err := s.connectionPath(id) if err != nil { return account.Connection{}, err } @@ -123,8 +119,8 @@ func (s *Store) Connection(_ context.Context, p account.Profile) (account.Connec } // SaveConnection implements account.Tokens. -func (s *Store) SaveConnection(_ context.Context, p account.Profile, c account.Connection) error { - path, err := s.connectionPath(p) +func (s *Store) SaveConnection(_ context.Context, id account.ProfileID, c account.Connection) error { + path, err := s.connectionPath(id) if err != nil { return err } @@ -137,8 +133,8 @@ func (s *Store) SaveConnection(_ context.Context, p account.Profile, c account.C } // UpdateConnection implements account.Tokens. fn runs under the lock. -func (s *Store) UpdateConnection(_ context.Context, p account.Profile, fn func(*account.Connection) error) error { - path, err := s.connectionPath(p) +func (s *Store) UpdateConnection(_ context.Context, id account.ProfileID, fn func(*account.Connection) error) error { + path, err := s.connectionPath(id) if err != nil { return err } @@ -159,8 +155,8 @@ func (s *Store) UpdateConnection(_ context.Context, p account.Profile, fn func(* } // DeleteConnection implements account.Tokens. -func (s *Store) DeleteConnection(_ context.Context, p account.Profile) error { - path, err := s.connectionPath(p) +func (s *Store) DeleteConnection(_ context.Context, id account.ProfileID) error { + path, err := s.connectionPath(id) if err != nil { return err } @@ -205,7 +201,7 @@ func (s *Store) changeInvites(fn func(map[account.InviteHash]inviteRecord) error // AddInvite implements account.Invites. func (s *Store) AddInvite(_ context.Context, i account.Invite) error { return s.changeInvites(func(inv map[account.InviteHash]inviteRecord) error { - inv[i.Hash] = inviteRecord{Profile: i.Profile.ID(), Expires: i.Expires} + inv[i.Hash] = inviteRecord{Profile: string(i.ProfileID), Expires: i.Expires} return nil }) } diff --git a/internal/filestore/filestore_test.go b/internal/filestore/filestore_test.go index 59f2723..035a9cc 100644 --- a/internal/filestore/filestore_test.go +++ b/internal/filestore/filestore_test.go @@ -13,16 +13,7 @@ import ( "github.com/subpathdev/spotify-mcp/internal/account" ) -var profile = mustProfile("default") - -// mustProfile parses a profile ID that the test knows to be valid. -func mustProfile(id string) account.Profile { - p, err := account.ParseProfile(id) - if err != nil { - panic(err) - } - return p -} +const profile = account.ProfileID("default") func open(t *testing.T, dir string) *Store { t.Helper() @@ -42,7 +33,7 @@ func TestConnectionRoundTrip(t *testing.T) { } want := account.Connection{ Token: account.Token{AccessToken: "a", RefreshToken: "r", Expiry: time.Date(2026, 11, 22, 13, 0, 0, 0, time.UTC)}, - User: account.User{ID: "jan", DisplayName: "Jan"}, + Account: account.SpotifyAccount{ID: "jan", DisplayName: "Jan"}, ConnectedAt: time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC), } if err := s.SaveConnection(ctx, profile, want); err != nil { @@ -85,19 +76,13 @@ func TestUpdateConnection(t *testing.T) { } } -// badProfile is a Profile that skipped ParseProfile, as another -// implementation of the interface could. -type badProfile string - -func (b badProfile) ID() string { return string(b) } - func TestRejectsBadProfile(t *testing.T) { s := open(t, t.TempDir()) - if err := s.SaveConnection(context.Background(), badProfile("../x"), account.Connection{}); err == nil { - t.Fatal("path traversal accepted") - } - if err := s.SaveConnection(context.Background(), nil, account.Connection{}); err == nil { - t.Fatal("nil profile accepted") + // A ProfileID made by conversion skips ParseProfileID. + for _, id := range []account.ProfileID{"../x", ""} { + if err := s.SaveConnection(context.Background(), id, account.Connection{}); err == nil { + t.Fatalf("profile %q accepted", id) + } } } @@ -105,11 +90,11 @@ func TestInviteTakenOnce(t *testing.T) { ctx := context.Background() dir := t.TempDir() s := open(t, dir) - inv := account.Invite{Hash: "h1", Profile: profile, Expires: time.Now().Add(time.Hour)} + inv := account.Invite{Hash: "h1", ProfileID: profile, Expires: time.Now().Add(time.Hour)} if err := s.AddInvite(ctx, inv); err != nil { t.Fatal(err) } - if got, err := s.Invite(ctx, "h1"); err != nil || got.Profile.ID() != profile.ID() { + if got, err := s.Invite(ctx, "h1"); err != nil || got.ProfileID != profile { t.Fatalf("invite: %+v %v", got, err) } @@ -149,7 +134,7 @@ func TestConcurrentInvitesFromTwoStores(t *testing.T) { } wg.Go(func() { h := account.InviteHash(strings.Repeat("x", i+1)) - if err := st.AddInvite(ctx, account.Invite{Hash: h, Profile: profile, Expires: time.Now().Add(time.Hour)}); err != nil { + if err := st.AddInvite(ctx, account.Invite{Hash: h, ProfileID: profile, Expires: time.Now().Add(time.Hour)}); err != nil { t.Error(err) } }) @@ -166,8 +151,8 @@ func TestPruneInvites(t *testing.T) { ctx := context.Background() s := open(t, t.TempDir()) now := time.Now() - _ = s.AddInvite(ctx, account.Invite{Hash: "old", Profile: profile, Expires: now.Add(-time.Minute)}) - _ = s.AddInvite(ctx, account.Invite{Hash: "new", Profile: profile, Expires: now.Add(time.Minute)}) + _ = s.AddInvite(ctx, account.Invite{Hash: "old", ProfileID: profile, Expires: now.Add(-time.Minute)}) + _ = s.AddInvite(ctx, account.Invite{Hash: "new", ProfileID: profile, Expires: now.Add(time.Minute)}) if err := s.PruneInvites(ctx, now); err != nil { t.Fatal(err) } diff --git a/internal/spotify/auth.go b/internal/spotify/auth.go index a6d05f2..5d38112 100644 --- a/internal/spotify/auth.go +++ b/internal/spotify/auth.go @@ -109,21 +109,21 @@ func mapOAuthError(err error) error { return err } -// User implements account.Identity. Spotify answers 403 for accounts that +// Account implements account.Identity. Spotify answers 403 for accounts that // aren't on a development-mode app's user list. -func (a *API) User(ctx context.Context, accessToken string) (account.User, error) { +func (a *API) Account(ctx context.Context, accessToken string) (account.SpotifyAccount, error) { var out struct { ID string `json:"id"` DisplayName string `json:"display_name"` } status, err := a.do(ctx, accessToken, request{method: http.MethodGet, path: "/me", out: &out}) if status == http.StatusForbidden { - return account.User{}, account.ErrNotAllowlisted + return account.SpotifyAccount{}, account.ErrNotAllowlisted } if err != nil { - return account.User{}, err + return account.SpotifyAccount{}, err } - return account.User{ID: out.ID, DisplayName: out.DisplayName}, nil + return account.SpotifyAccount{ID: out.ID, DisplayName: out.DisplayName}, nil } var _ account.Identity = (*API)(nil) diff --git a/internal/spotify/spotify_test.go b/internal/spotify/spotify_test.go index 4659ba1..caae6df 100644 --- a/internal/spotify/spotify_test.go +++ b/internal/spotify/spotify_test.go @@ -198,10 +198,10 @@ func TestStateNothingPlaying(t *testing.T) { } } -func TestUserNotAllowlisted(t *testing.T) { +func TestAccountNotAllowlisted(t *testing.T) { srv := httptest.NewServer(spotifyError(http.StatusForbidden, "")) defer srv.Close() - if _, err := NewAPI(srv.URL, srv.Client()).User(context.Background(), "t"); !errors.Is(err, account.ErrNotAllowlisted) { + if _, err := NewAPI(srv.URL, srv.Client()).Account(context.Background(), "t"); !errors.Is(err, account.ErrNotAllowlisted) { t.Fatalf("got %v", err) } } diff --git a/internal/web/web.go b/internal/web/web.go index be8e441..0a6ae12 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -23,7 +23,7 @@ import ( type Connector interface { Status(ctx context.Context, code account.InviteCode) (account.Status, error) StartLogin(ctx context.Context, code account.InviteCode) (account.Login, error) - FinishLogin(ctx context.Context, cb account.Callback) (account.User, error) + FinishLogin(ctx context.Context, cb account.Callback) (account.Profile, error) Disconnect(ctx context.Context, code account.InviteCode) (account.Profile, error) } @@ -72,9 +72,10 @@ func (h *handler) connectPage(w http.ResponseWriter, r *http.Request) { h.fail(w, err) return } - d := pageData{Title: "Connect Spotify", Invite: string(code), ShowForm: true, Connected: st.Connected} - if st.Connected { - d.Name = st.User.Name() + acc, connected := st.Profile.Account() + d := pageData{Title: "Connect Spotify", Invite: string(code), ShowForm: true, Connected: connected} + if connected { + d.Name = acc.Name() if !st.ConnectedAt.IsZero() { d.Since = st.ConnectedAt.Format(time.DateOnly) } @@ -121,14 +122,15 @@ func (h *handler) callback(w http.ResponseWriter, r *http.Request) { cb.Nonce = c.Value } http.SetCookie(w, loginCookie("", -1)) - user, err := h.c.FinishLogin(r.Context(), cb) + profile, err := h.c.FinishLogin(r.Context(), cb) if err != nil { h.fail(w, err) return } - h.log.Info("spotify account connected", "spotify_user", user.ID) + acc, _ := profile.Account() + h.log.Info("spotify account connected", "profile", profile.ID(), "spotify_user", acc.ID) msg := "Spotify is connected. You can close this page." - if name := user.Name(); name != "" { + if name := acc.Name(); name != "" { msg = "Spotify is connected as " + name + ". You can close this page." } h.render(w, http.StatusOK, pageData{Title: "Connected", Message: msg}) diff --git a/internal/web/web_test.go b/internal/web/web_test.go index d80f8f0..d0f23d6 100644 --- a/internal/web/web_test.go +++ b/internal/web/web_test.go @@ -49,8 +49,8 @@ func (f *fakeOAuth) Refresh(context.Context, string) (account.Token, error) { type fakeIdentity struct{ err error } -func (f *fakeIdentity) User(context.Context, string) (account.User, error) { - return account.User{ID: "jan", DisplayName: "Jan"}, f.err +func (f *fakeIdentity) Account(context.Context, string) (account.SpotifyAccount, error) { + return account.SpotifyAccount{ID: "jan", DisplayName: "Jan"}, f.err } type env struct { @@ -73,13 +73,7 @@ func newEnv(t *testing.T) *env { return &env{srv: srv, inviter: account.NewInviter(st), store: st, identity: id} } -var profile = func() account.Profile { - p, err := account.ParseProfile("default") - if err != nil { - panic(err) - } - return p -}() +const profile = account.ProfileID("default") func (e *env) invite(t *testing.T) string { t.Helper() From dfdec1912f7ec46adbf7a90d380b1d10e24a490a Mon Sep 17 00:00:00 2001 From: Jan Unterbrink Date: Mon, 23 Nov 2026 12:03:56 +0100 Subject: [PATCH 4/7] refactor(account): make IDs, invite codes, hashes and invites interfaces ProfileID, InviteCode and InviteHash were named string types that any package could create by conversion, skipping validation. They are now sealed interfaces built only by ParseProfileID, ParseInviteCode and ParseInviteHash (or by the domain itself). Invite is an interface; adapters rebuild stored invites through RestoreInvite, which checks every part. InviteCode exposes the secret only via Secret() and prints as redacted. The on-disk format is unchanged. Co-Authored-By: Claude Opus 5.5 --- cmd/spotify-mcp/main.go | 8 +- internal/account/account.go | 32 +------ internal/account/account_test.go | 77 ++++++++++++++-- internal/account/ids.go | 129 +++++++++++++++++++++++++++ internal/account/invite.go | 17 ++-- internal/account/profiles.go | 3 + internal/account/service.go | 34 ++++--- internal/config/config.go | 2 +- internal/config/config_test.go | 15 +++- internal/filestore/filestore.go | 62 ++++++++----- internal/filestore/filestore_test.go | 50 +++++++---- internal/web/web.go | 18 ++-- internal/web/web_test.go | 13 ++- 13 files changed, 338 insertions(+), 122 deletions(-) create mode 100644 internal/account/ids.go diff --git a/cmd/spotify-mcp/main.go b/cmd/spotify-mcp/main.go index e0edc46..d3315c6 100644 --- a/cmd/spotify-mcp/main.go +++ b/cmd/spotify-mcp/main.go @@ -100,11 +100,11 @@ func serve(log *slog.Logger) error { // tools report it when they need the token. prof, err := account.NewProfiles(store).Profile(context.Background(), cfg.ProfileID) if err != nil { - log.Warn("can't read the connected account", "profile", cfg.ProfileID, "err", err) + log.Warn("can't read the connected account", "profile", cfg.ProfileID.String(), "err", err) } else if acc, ok := prof.Account(); ok { - log.Info("spotify account connected", "profile", prof.ID(), "spotify_user", acc.ID) + log.Info("spotify account connected", "profile", prof.ID().String(), "spotify_user", acc.ID) } else { - log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", prof.ID()) + log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", prof.ID().String()) } servers := []*http.Server{ @@ -121,7 +121,7 @@ func serve(log *slog.Logger) error { WriteTimeout: 30 * time.Second, }, } - log.Info("spotify-mcp started", "version", version, "profile", cfg.ProfileID, "connect_url", cfg.PublicURL.JoinPath("connect").String()) + log.Info("spotify-mcp started", "version", version, "profile", cfg.ProfileID.String(), "connect_url", cfg.PublicURL.JoinPath("connect").String()) return run(log, servers) } diff --git a/internal/account/account.go b/internal/account/account.go index 2b47415..7a914ce 100644 --- a/internal/account/account.go +++ b/internal/account/account.go @@ -9,25 +9,9 @@ package account import ( "context" "errors" - "fmt" - "regexp" "time" ) -// ProfileID identifies a profile: 1-63 lower-case letters, digits and -// dashes. Adapters use it in file and key names. Get one from ParseProfileID. -type ProfileID string - -var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) - -// ParseProfileID checks a profile ID. -func ParseProfileID(s string) (ProfileID, error) { - if !profileRe.MatchString(s) { - return "", fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) - } - return ProfileID(s), nil -} - // Profile is one slot a Spotify account can be connected to, as it was when // it was loaded (see Profiles). Phase 1 uses a single profile; more about a // profile (a display name, the person a sign-in system maps to it) is added @@ -59,7 +43,7 @@ func (p *profile) ID() ProfileID { return p.id } func (p *profile) Account() (SpotifyAccount, bool) { return p.account, p.connected } // String makes a profile print as its ID in logs and messages. -func (p *profile) String() string { return string(p.id) } +func (p *profile) String() string { return p.id.String() } // SpotifyAccount is the Spotify account connected to a profile. type SpotifyAccount struct { @@ -96,20 +80,6 @@ func (c Connection) accessValid(now time.Time) bool { return c.Token.AccessToken != "" && now.Add(expiryDelta).Before(c.Token.Expiry) } -// InviteCode is the secret part of an invite link. It is only ever shown -// once; repositories see its hash. -type InviteCode string - -// InviteHash identifies an invite in a repository. -type InviteHash string - -// Invite lets whoever holds its code connect or disconnect one profile. -type Invite struct { - Hash InviteHash - ProfileID ProfileID - Expires time.Time -} - // Errors returned by this package and by the ports' implementations. var ( // ErrNotFound is returned by repositories for a missing entry. diff --git a/internal/account/account_test.go b/internal/account/account_test.go index f3a5eff..4ced0a3 100644 --- a/internal/account/account_test.go +++ b/internal/account/account_test.go @@ -3,7 +3,9 @@ package account_test import ( "context" "errors" + "fmt" "net/url" + "strings" "sync" "testing" "time" @@ -12,7 +14,16 @@ import ( "github.com/subpathdev/spotify-mcp/internal/filestore" ) -const profile = account.ProfileID("default") +var profile = mustProfileID("default") + +// mustProfileID parses a profile ID that the test knows to be valid. +func mustProfileID(s string) account.ProfileID { + id, err := account.ParseProfileID(s) + if err != nil { + panic(err) + } + return id +} // fakeOAuth issues tokens for the code "good" and the verifier of the last // started login. @@ -205,18 +216,23 @@ func TestDisconnect(t *testing.T) { func TestInvites(t *testing.T) { ctx := context.Background() e := newEnv(t, nil) - for _, code := range []account.InviteCode{"", "unknown"} { - if _, err := e.svc.Status(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { - t.Fatalf("code %q: %v", code, err) - } + if _, err := e.svc.Status(ctx, nil); !errors.Is(err, account.ErrInvalidInvite) { + t.Fatalf("nil code: %v", err) + } + unknown, err := account.ParseInviteCode(strings.Repeat("a", 43)) + if err != nil { + t.Fatal(err) + } + if _, err := e.svc.Status(ctx, unknown); !errors.Is(err, account.ErrInvalidInvite) { + t.Fatalf("unknown code: %v", err) } code := e.invite(t) e.now = e.now.Add(2 * time.Hour) if _, err := e.svc.StartLogin(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { t.Fatalf("expired invite accepted: %v", err) } - if _, _, err := e.inviter.CreateInvite(ctx, "../x", time.Hour); err == nil { - t.Fatal("invalid profile accepted") + if _, _, err := e.inviter.CreateInvite(ctx, nil, time.Hour); err == nil { + t.Fatal("nil profile accepted") } if _, _, err := e.inviter.CreateInvite(ctx, profile, 0); err == nil { t.Fatal("zero TTL accepted") @@ -229,8 +245,51 @@ func TestParseProfileID(t *testing.T) { t.Errorf("%q accepted", s) } } - if id, err := account.ParseProfileID("jan-2"); err != nil || id != "jan-2" { - t.Fatalf("valid profile: %q %v", id, err) + a, err := account.ParseProfileID("jan-2") + if err != nil || a.String() != "jan-2" { + t.Fatalf("valid profile: %v %v", a, err) + } + if b := mustProfileID("jan-2"); a != b { + t.Fatal("equal IDs compare unequal") + } + if a == profile { + t.Fatal("different IDs compare equal") + } +} + +func TestParseInviteCode(t *testing.T) { + for _, s := range []string{"", "unknown", strings.Repeat("a", 42), strings.Repeat("a", 44), strings.Repeat("a", 42) + "="} { + if _, err := account.ParseInviteCode(s); !errors.Is(err, account.ErrInvalidInvite) { + t.Errorf("%q: %v", s, err) + } + } + code, err := account.ParseInviteCode(strings.Repeat("a", 42) + "_") + if err != nil { + t.Fatal(err) + } + if s := fmt.Sprint(code); strings.Contains(s, "aaaa") { + t.Fatalf("code printed: %s", s) + } +} + +func TestRestoreInvite(t *testing.T) { + hash, exp := strings.Repeat("0", 64), time.Now() + for name, tc := range map[string]struct { + hash, profile string + exp time.Time + }{ + "short hash": {"abc", "default", exp}, + "upper hash": {strings.Repeat("A", 64), "default", exp}, + "bad profile": {hash, "../x", exp}, + "no expiry": {hash, "default", time.Time{}}, + } { + if _, err := account.RestoreInvite(tc.hash, tc.profile, tc.exp); err == nil { + t.Errorf("%s: accepted", name) + } + } + inv, err := account.RestoreInvite(hash, "default", exp) + if err != nil || inv.Hash().String() != hash || inv.ProfileID() != profile || !inv.Expires().Equal(exp) { + t.Fatalf("restore: %v %v", inv, err) } } diff --git a/internal/account/ids.go b/internal/account/ids.go new file mode 100644 index 0000000..c209af4 --- /dev/null +++ b/internal/account/ids.go @@ -0,0 +1,129 @@ +package account + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "regexp" + "time" +) + +// The value types below are interfaces with an unexported marker method, so +// only this package implements them and every value went through one of its +// constructors. Their implementations are small comparable structs: two +// values are equal with == exactly when they hold the same text. + +// ProfileID identifies a profile: 1-63 lower-case letters, digits and dashes. +// Adapters may use String() in file and key names. Get one from +// ParseProfileID. +type ProfileID interface { + String() string + isProfileID() +} + +type profileID struct{ s string } + +func (p profileID) String() string { return p.s } +func (profileID) isProfileID() {} + +var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) + +// ParseProfileID checks a profile ID. +func ParseProfileID(s string) (ProfileID, error) { + if !profileRe.MatchString(s) { + return nil, fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) + } + return profileID{s: s}, nil +} + +// InviteCode is the secret part of an invite link. The Inviter creates new +// codes; ParseInviteCode reads one from a link. It is only ever shown once; +// repositories see its hash. +type InviteCode interface { + // Secret is the code itself, for building the link. Keep it out of logs. + Secret() string + isInviteCode() +} + +type inviteCode struct{ s string } + +func (c inviteCode) Secret() string { return c.s } +func (inviteCode) isInviteCode() {} + +// String keeps the code out of logs and error messages. +func (inviteCode) String() string { return "InviteCode(redacted)" } + +// A code is 32 random bytes, base64url-encoded without padding. +var inviteCodeRe = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) + +// ParseInviteCode checks a code taken from a link. Anything malformed is +// ErrInvalidInvite, like an unknown code. +func ParseInviteCode(s string) (InviteCode, error) { + if !inviteCodeRe.MatchString(s) { + return nil, ErrInvalidInvite + } + return inviteCode{s: s}, nil +} + +func newInviteCode() InviteCode { return inviteCode{s: randomString()} } + +// InviteHash identifies an invite in a repository: the hex SHA-256 of its +// code, so reading the storage doesn't give anyone a usable link. +type InviteHash interface { + String() string + isInviteHash() +} + +type inviteHash struct{ s string } + +func (h inviteHash) String() string { return h.s } +func (inviteHash) isInviteHash() {} + +var inviteHashRe = regexp.MustCompile(`^[0-9a-f]{64}$`) + +// ParseInviteHash checks a hash read back from a repository. +func ParseInviteHash(s string) (InviteHash, error) { + if !inviteHashRe.MatchString(s) { + return nil, fmt.Errorf("invalid invite hash %q", s) + } + return inviteHash{s: s}, nil +} + +func hashInvite(code InviteCode) InviteHash { + sum := sha256.Sum256([]byte(code.Secret())) + return inviteHash{s: hex.EncodeToString(sum[:])} +} + +// Invite lets whoever holds its code connect or disconnect one profile. +type Invite interface { + Hash() InviteHash + ProfileID() ProfileID + Expires() time.Time +} + +type invite struct { + hash InviteHash + profileID ProfileID + expires time.Time +} + +func (i *invite) Hash() InviteHash { return i.hash } +func (i *invite) ProfileID() ProfileID { return i.profileID } +func (i *invite) Expires() time.Time { return i.expires } + +// RestoreInvite rebuilds an invite a repository stored, checking each part. +func RestoreInvite(hash, profileID string, expires time.Time) (Invite, error) { + h, err := ParseInviteHash(hash) + if err != nil { + return nil, err + } + id, err := ParseProfileID(profileID) + if err != nil { + return nil, err + } + if expires.IsZero() { + return nil, errors.New("invite has no expiry") + } + return &invite{hash: h, profileID: id, expires: expires}, nil +} diff --git a/internal/account/invite.go b/internal/account/invite.go index 61ce5e6..02e7a63 100644 --- a/internal/account/invite.go +++ b/internal/account/invite.go @@ -2,6 +2,7 @@ package account import ( "context" + "errors" "fmt" "time" ) @@ -20,20 +21,20 @@ func NewInviter(invites Invites, opts ...Option) *Inviter { // CreateInvite returns a new one-time code for the profile and when it expires. func (i *Inviter) CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) { - if _, err := ParseProfileID(string(id)); err != nil { - return "", time.Time{}, err + if id == nil { + return nil, time.Time{}, errors.New("invite needs a profile") } if ttl <= 0 { - return "", time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) + return nil, time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) } - code := InviteCode(randomString()) + code := newInviteCode() now := i.now() - inv := Invite{Hash: hashInvite(code), ProfileID: id, Expires: now.Add(ttl)} + inv := &invite{hash: hashInvite(code), profileID: id, expires: now.Add(ttl)} if err := i.invites.PruneInvites(ctx, now); err != nil { - return "", time.Time{}, fmt.Errorf("prune invites: %w", err) + return nil, time.Time{}, fmt.Errorf("prune invites: %w", err) } if err := i.invites.AddInvite(ctx, inv); err != nil { - return "", time.Time{}, fmt.Errorf("save invite: %w", err) + return nil, time.Time{}, fmt.Errorf("save invite: %w", err) } - return code, inv.Expires, nil + return code, inv.expires, nil } diff --git a/internal/account/profiles.go b/internal/account/profiles.go index 745943e..36cdacc 100644 --- a/internal/account/profiles.go +++ b/internal/account/profiles.go @@ -27,6 +27,9 @@ func (p profiles) Profile(ctx context.Context, id ProfileID) (Profile, error) { } func loadProfile(ctx context.Context, tokens Tokens, id ProfileID) (*profile, error) { + if id == nil { + return nil, errors.New("no profile given") + } c, err := tokens.Connection(ctx, id) switch { case errors.Is(err, ErrNotFound): diff --git a/internal/account/service.go b/internal/account/service.go index a6ac767..a061437 100644 --- a/internal/account/service.go +++ b/internal/account/service.go @@ -3,10 +3,8 @@ package account import ( "context" "crypto/rand" - "crypto/sha256" "crypto/subtle" "encoding/base64" - "encoding/hex" "errors" "fmt" "sync" @@ -78,7 +76,7 @@ func (s *Service) Status(ctx context.Context, code InviteCode) (Status, error) { if err != nil { return Status{}, err } - p, err := loadProfile(ctx, s.tokens, inv.ProfileID) + p, err := loadProfile(ctx, s.tokens, inv.ProfileID()) if err != nil { return Status{}, err } @@ -106,7 +104,7 @@ func (s *Service) StartLogin(ctx context.Context, code InviteCode) (Login, error return Login{}, ErrTooManyLogins } s.pending[state] = pendingLogin{ - invite: inv.Hash, profile: inv.ProfileID, + invite: inv.Hash(), profile: inv.ProfileID(), verifier: verifier, nonce: nonce, expires: now.Add(LoginTTL), } return Login{URL: s.oauth.AuthCodeURL(state, verifier), Nonce: nonce}, nil @@ -157,19 +155,22 @@ func (s *Service) FinishLogin(ctx context.Context, cb Callback) (Profile, error) // Disconnect uses up the invite and deletes its profile's connection. It // returns the profile, now without an account. func (s *Service) Disconnect(ctx context.Context, code InviteCode) (Profile, error) { + if code == nil { + return nil, ErrInvalidInvite + } inv, err := s.takeInvite(ctx, hashInvite(code)) if err != nil { return nil, err } - if err := s.tokens.DeleteConnection(ctx, inv.ProfileID); err != nil { + if err := s.tokens.DeleteConnection(ctx, inv.ProfileID()); err != nil { return nil, fmt.Errorf("delete connection: %w", err) } - return newProfile(inv.ProfileID, nil), nil + return newProfile(inv.ProfileID(), nil), nil } func (s *Service) checkInvite(ctx context.Context, code InviteCode) (Invite, error) { - if code == "" { - return Invite{}, ErrInvalidInvite + if code == nil { + return nil, ErrInvalidInvite } inv, err := s.invites.Invite(ctx, hashInvite(code)) return s.validInvite(inv, err) @@ -183,22 +184,17 @@ func (s *Service) takeInvite(ctx context.Context, h InviteHash) (Invite, error) func (s *Service) validInvite(inv Invite, err error) (Invite, error) { switch { case errors.Is(err, ErrNotFound): - return Invite{}, ErrInvalidInvite + return nil, ErrInvalidInvite case err != nil: - return Invite{}, fmt.Errorf("load invite: %w", err) - case s.now().After(inv.Expires): - return Invite{}, ErrInvalidInvite + return nil, fmt.Errorf("load invite: %w", err) + case inv == nil || inv.ProfileID() == nil: + return nil, errors.New("load invite: repository returned an incomplete invite") + case s.now().After(inv.Expires()): + return nil, ErrInvalidInvite } return inv, nil } -// hashInvite: only the SHA-256 of a code is stored, so reading the storage -// doesn't give anyone a usable link. -func hashInvite(code InviteCode) InviteHash { - sum := sha256.Sum256([]byte(code)) - return InviteHash(hex.EncodeToString(sum[:])) -} - // randomString returns 256 random bits, base64url-encoded (43 characters, // which is also a valid PKCE verifier). func randomString() string { diff --git a/internal/config/config.go b/internal/config/config.go index 37fb41c..33bb9e9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -88,7 +88,7 @@ func (c Config) RequireCredentials() error { // InviteURL is the link that opens the connect page with code. func (c Config) InviteURL(code account.InviteCode) string { u := c.PublicURL.JoinPath("connect") - u.RawQuery = url.Values{"invite": {string(code)}}.Encode() + u.RawQuery = url.Values{"invite": {code.Secret()}}.Encode() return u.String() } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index d9568c2..3cb504c 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -3,6 +3,8 @@ package config import ( "strings" "testing" + + "github.com/subpathdev/spotify-mcp/internal/account" ) func envOf(m map[string]string) func(string) string { @@ -14,13 +16,13 @@ func TestLoadDefaults(t *testing.T) { if err != nil { t.Fatal(err) } - if c.PublicURL.String() != "https://spotify.example.com" || c.ProfileID != "default" || c.DataDir != "/data" || c.MCPAddr != ":8000" { + if c.PublicURL.String() != "https://spotify.example.com" || c.ProfileID.String() != "default" || c.DataDir != "/data" || c.MCPAddr != ":8000" { t.Fatalf("%+v", c) } if err := c.RequireCredentials(); err == nil || !strings.Contains(err.Error(), "SPOTIFY_CLIENT_SECRET") { t.Fatalf("credentials: %v", err) } - if got := c.InviteURL("a-b_c"); got != "https://spotify.example.com/connect?invite=a-b_c" { + if got := c.InviteURL(mustCode(t, "a-b_c"+strings.Repeat("x", 38))); got != "https://spotify.example.com/connect?invite=a-b_c"+strings.Repeat("x", 38) { t.Fatalf("invite URL %q", got) } } @@ -39,3 +41,12 @@ func TestLoadRejects(t *testing.T) { } } } + +func mustCode(t *testing.T, s string) account.InviteCode { + t.Helper() + code, err := account.ParseInviteCode(s) + if err != nil { + t.Fatal(err) + } + return code +} diff --git a/internal/filestore/filestore.go b/internal/filestore/filestore.go index fe02ff7..2a10435 100644 --- a/internal/filestore/filestore.go +++ b/internal/filestore/filestore.go @@ -66,18 +66,18 @@ func (r connectionRecord) connection() account.Connection { } // inviteRecord is the on-disk format of an invite; invites.json maps the -// invite hash to it. +// invite hash (hex) to it. type inviteRecord struct { Profile string `json:"profile"` Expires time.Time `json:"expires"` } -func (r inviteRecord) invite(h account.InviteHash) (account.Invite, error) { - id, err := account.ParseProfileID(r.Profile) +func (r inviteRecord) invite(hash string) (account.Invite, error) { + inv, err := account.RestoreInvite(hash, r.Profile, r.Expires) if err != nil { - return account.Invite{}, fmt.Errorf("invite %s: %w", h, err) + return nil, fmt.Errorf("invite %s: %w", hash, err) } - return account.Invite{Hash: h, ProfileID: id, Expires: r.Expires}, nil + return inv, nil } // lock takes the in-process and the cross-process lock. @@ -92,12 +92,16 @@ func (s *Store) lock() (unlock func(), err error) { } func (s *Store) connectionPath(id account.ProfileID) (string, error) { - // IDs are validated when parsed; check again because a ProfileID can also - // be made by conversion, and it ends up in a file name. - if _, err := account.ParseProfileID(string(id)); err != nil { + if id == nil { + return "", errors.New("no profile given") + } + // Only account.ParseProfileID creates IDs, but a type embedding one could + // still override String(); check again because it ends up in a file name. + name := id.String() + if _, err := account.ParseProfileID(name); err != nil { return "", err } - return filepath.Join(s.dir, "tokens", string(id)+".json"), nil + return filepath.Join(s.dir, "tokens", name+".json"), nil } // Connection implements account.Tokens. @@ -173,8 +177,8 @@ func (s *Store) DeleteConnection(_ context.Context, id account.ProfileID) error func (s *Store) invitePath() string { return filepath.Join(s.dir, "invites.json") } -func (s *Store) loadInvites() (map[account.InviteHash]inviteRecord, error) { - inv := map[account.InviteHash]inviteRecord{} +func (s *Store) loadInvites() (map[string]inviteRecord, error) { + inv := map[string]inviteRecord{} if err := readJSON(s.invitePath(), &inv); err != nil && !errors.Is(err, account.ErrNotFound) { return nil, err } @@ -182,7 +186,7 @@ func (s *Store) loadInvites() (map[account.InviteHash]inviteRecord, error) { } // changeInvites runs fn on the invites under the lock and writes them back. -func (s *Store) changeInvites(fn func(map[account.InviteHash]inviteRecord) error) error { +func (s *Store) changeInvites(fn func(map[string]inviteRecord) error) error { unlock, err := s.lock() if err != nil { return err @@ -200,43 +204,53 @@ func (s *Store) changeInvites(fn func(map[account.InviteHash]inviteRecord) error // AddInvite implements account.Invites. func (s *Store) AddInvite(_ context.Context, i account.Invite) error { - return s.changeInvites(func(inv map[account.InviteHash]inviteRecord) error { - inv[i.Hash] = inviteRecord{Profile: string(i.ProfileID), Expires: i.Expires} + if i == nil || i.Hash() == nil || i.ProfileID() == nil { + return errors.New("incomplete invite") + } + return s.changeInvites(func(inv map[string]inviteRecord) error { + inv[i.Hash().String()] = inviteRecord{Profile: i.ProfileID().String(), Expires: i.Expires()} return nil }) } // Invite implements account.Invites. func (s *Store) Invite(_ context.Context, h account.InviteHash) (account.Invite, error) { + if h == nil { + return nil, account.ErrNotFound + } unlock, err := s.lock() if err != nil { - return account.Invite{}, err + return nil, err } defer unlock() inv, err := s.loadInvites() if err != nil { - return account.Invite{}, err + return nil, err } - r, ok := inv[h] + r, ok := inv[h.String()] if !ok { - return account.Invite{}, account.ErrNotFound + return nil, account.ErrNotFound } - return r.invite(h) + return r.invite(h.String()) } // TakeInvite implements account.Invites. func (s *Store) TakeInvite(_ context.Context, h account.InviteHash) (account.Invite, error) { + if h == nil { + return nil, account.ErrNotFound + } + key := h.String() var out account.Invite - err := s.changeInvites(func(inv map[account.InviteHash]inviteRecord) error { - r, ok := inv[h] + err := s.changeInvites(func(inv map[string]inviteRecord) error { + r, ok := inv[key] if !ok { return account.ErrNotFound } - i, err := r.invite(h) + i, err := r.invite(key) if err != nil { return err // nothing is written, so the invite stays until it expires } - delete(inv, h) + delete(inv, key) out = i return nil }) @@ -245,7 +259,7 @@ func (s *Store) TakeInvite(_ context.Context, h account.InviteHash) (account.Inv // PruneInvites implements account.Invites. func (s *Store) PruneInvites(_ context.Context, t time.Time) error { - return s.changeInvites(func(inv map[account.InviteHash]inviteRecord) error { + return s.changeInvites(func(inv map[string]inviteRecord) error { for h, r := range inv { if r.Expires.Before(t) { delete(inv, h) diff --git a/internal/filestore/filestore_test.go b/internal/filestore/filestore_test.go index 035a9cc..df42099 100644 --- a/internal/filestore/filestore_test.go +++ b/internal/filestore/filestore_test.go @@ -3,9 +3,9 @@ package filestore import ( "context" "errors" + "fmt" "os" "path/filepath" - "strings" "sync" "testing" "time" @@ -13,7 +13,26 @@ import ( "github.com/subpathdev/spotify-mcp/internal/account" ) -const profile = account.ProfileID("default") +var profile = mustProfileID("default") + +// mustProfileID parses a profile ID that the test knows to be valid. +func mustProfileID(s string) account.ProfileID { + id, err := account.ParseProfileID(s) + if err != nil { + panic(err) + } + return id +} + +// testInvite is a valid invite whose hash is n in hex. +func testInvite(t *testing.T, n int, expires time.Time) account.Invite { + t.Helper() + inv, err := account.RestoreInvite(fmt.Sprintf("%064x", n), "default", expires) + if err != nil { + t.Fatal(err) + } + return inv +} func open(t *testing.T, dir string) *Store { t.Helper() @@ -78,11 +97,8 @@ func TestUpdateConnection(t *testing.T) { func TestRejectsBadProfile(t *testing.T) { s := open(t, t.TempDir()) - // A ProfileID made by conversion skips ParseProfileID. - for _, id := range []account.ProfileID{"../x", ""} { - if err := s.SaveConnection(context.Background(), id, account.Connection{}); err == nil { - t.Fatalf("profile %q accepted", id) - } + if err := s.SaveConnection(context.Background(), nil, account.Connection{}); err == nil { + t.Fatal("nil profile accepted") } } @@ -90,11 +106,11 @@ func TestInviteTakenOnce(t *testing.T) { ctx := context.Background() dir := t.TempDir() s := open(t, dir) - inv := account.Invite{Hash: "h1", ProfileID: profile, Expires: time.Now().Add(time.Hour)} + inv := testInvite(t, 1, time.Now().Add(time.Hour)) if err := s.AddInvite(ctx, inv); err != nil { t.Fatal(err) } - if got, err := s.Invite(ctx, "h1"); err != nil || got.ProfileID != profile { + if got, err := s.Invite(ctx, inv.Hash()); err != nil || got.ProfileID() != profile || got.Hash() != inv.Hash() { t.Fatalf("invite: %+v %v", got, err) } @@ -109,7 +125,7 @@ func TestInviteTakenOnce(t *testing.T) { st = other } wg.Go(func() { - if _, err := st.TakeInvite(ctx, "h1"); err == nil { + if _, err := st.TakeInvite(ctx, inv.Hash()); err == nil { mu.Lock() taken++ mu.Unlock() @@ -133,15 +149,14 @@ func TestConcurrentInvitesFromTwoStores(t *testing.T) { st = b } wg.Go(func() { - h := account.InviteHash(strings.Repeat("x", i+1)) - if err := st.AddInvite(ctx, account.Invite{Hash: h, ProfileID: profile, Expires: time.Now().Add(time.Hour)}); err != nil { + if err := st.AddInvite(ctx, testInvite(t, i, time.Now().Add(time.Hour))); err != nil { t.Error(err) } }) } wg.Wait() for i := range 20 { - if _, err := a.Invite(ctx, account.InviteHash(strings.Repeat("x", i+1))); err != nil { + if _, err := a.Invite(ctx, testInvite(t, i, time.Now()).Hash()); err != nil { t.Errorf("invite %d lost: %v", i, err) } } @@ -151,15 +166,16 @@ func TestPruneInvites(t *testing.T) { ctx := context.Background() s := open(t, t.TempDir()) now := time.Now() - _ = s.AddInvite(ctx, account.Invite{Hash: "old", ProfileID: profile, Expires: now.Add(-time.Minute)}) - _ = s.AddInvite(ctx, account.Invite{Hash: "new", ProfileID: profile, Expires: now.Add(time.Minute)}) + old, cur := testInvite(t, 1, now.Add(-time.Minute)), testInvite(t, 2, now.Add(time.Minute)) + _ = s.AddInvite(ctx, old) + _ = s.AddInvite(ctx, cur) if err := s.PruneInvites(ctx, now); err != nil { t.Fatal(err) } - if _, err := s.Invite(ctx, "old"); !errors.Is(err, account.ErrNotFound) { + if _, err := s.Invite(ctx, old.Hash()); !errors.Is(err, account.ErrNotFound) { t.Fatalf("expired invite kept: %v", err) } - if _, err := s.Invite(ctx, "new"); err != nil { + if _, err := s.Invite(ctx, cur.Hash()); err != nil { t.Fatalf("valid invite pruned: %v", err) } } diff --git a/internal/web/web.go b/internal/web/web.go index 0a6ae12..fd9cdcc 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -66,14 +66,18 @@ func securityHeaders(next http.Handler) http.Handler { } func (h *handler) connectPage(w http.ResponseWriter, r *http.Request) { - code := account.InviteCode(r.URL.Query().Get("invite")) + code, err := account.ParseInviteCode(r.URL.Query().Get("invite")) + if err != nil { + h.fail(w, err) + return + } st, err := h.c.Status(r.Context(), code) if err != nil { h.fail(w, err) return } acc, connected := st.Profile.Account() - d := pageData{Title: "Connect Spotify", Invite: string(code), ShowForm: true, Connected: connected} + d := pageData{Title: "Connect Spotify", Invite: code.Secret(), ShowForm: true, Connected: connected} if connected { d.Name = acc.Name() if !st.ConnectedAt.IsZero() { @@ -89,7 +93,11 @@ func (h *handler) connectPost(w http.ResponseWriter, r *http.Request) { http.Error(w, "bad request", http.StatusBadRequest) return } - code := account.InviteCode(r.PostForm.Get("invite")) + code, err := account.ParseInviteCode(r.PostForm.Get("invite")) + if err != nil { + h.fail(w, err) + return + } switch r.PostForm.Get("action") { case "connect": login, err := h.c.StartLogin(r.Context(), code) @@ -105,7 +113,7 @@ func (h *handler) connectPost(w http.ResponseWriter, r *http.Request) { h.fail(w, err) return } - h.log.Info("spotify account disconnected", "profile", profile.ID()) + h.log.Info("spotify account disconnected", "profile", profile.ID().String()) h.render(w, http.StatusOK, pageData{ Title: "Disconnected", Message: "The Spotify account is disconnected and its token deleted. To also remove the app on Spotify's side, open spotify.com → Account → Manage apps.", @@ -128,7 +136,7 @@ func (h *handler) callback(w http.ResponseWriter, r *http.Request) { return } acc, _ := profile.Account() - h.log.Info("spotify account connected", "profile", profile.ID(), "spotify_user", acc.ID) + h.log.Info("spotify account connected", "profile", profile.ID().String(), "spotify_user", acc.ID) msg := "Spotify is connected. You can close this page." if name := acc.Name(); name != "" { msg = "Spotify is connected as " + name + ". You can close this page." diff --git a/internal/web/web_test.go b/internal/web/web_test.go index d0f23d6..40db0d9 100644 --- a/internal/web/web_test.go +++ b/internal/web/web_test.go @@ -73,7 +73,16 @@ func newEnv(t *testing.T) *env { return &env{srv: srv, inviter: account.NewInviter(st), store: st, identity: id} } -const profile = account.ProfileID("default") +var profile = mustProfileID("default") + +// mustProfileID parses a profile ID that the test knows to be valid. +func mustProfileID(s string) account.ProfileID { + id, err := account.ParseProfileID(s) + if err != nil { + panic(err) + } + return id +} func (e *env) invite(t *testing.T) string { t.Helper() @@ -81,7 +90,7 @@ func (e *env) invite(t *testing.T) string { if err != nil { t.Fatal(err) } - return string(code) + return code.Secret() } // browser is a client with its own cookies that doesn't follow redirects. From 0f2ccad4d86d78931c98dd575e4869312d0ca47e Mon Sep 17 00:00:00 2001 From: Jan Unterbrink Date: Mon, 23 Nov 2026 12:11:52 +0100 Subject: [PATCH 5/7] refactor: interfaces with constructors for every domain value and entity Apply one rule across the repo: anything that carries a rule or a secret is an exported interface with an unexported implementation, created only through a constructor that validates. - account: Token (prints redacted), Connection, SpotifyAccount, Status, Login and Callback are interfaces with New* constructors; Service, Inviter and TokenSource are interfaces. Tokens.UpdateConnection takes fn(Connection) (Connection, error) instead of mutating a struct. - playback: Kind, URI and DeviceID are sealed value interfaces (Parse*, Kind* functions instead of mutable globals); Device, Item (functional options) and State are interfaces; Service is an interface. A nil DeviceID means the active device. - spotify: NewOAuth and NewPlayer return the ports they implement; API is a sealed interface; Scopes() and DefaultEndpoint() are functions, so the scope list can't be widened from outside. - filestore: Open returns a Store interface; stored connections are rebuilt through the account constructors. - config: Config is an interface built only by Load; it prints without the client secret. Kept on purpose: sentinel errors and error types (errors.Is/As), the functional option types, OAuthConfig and the MCP tool input structs. The on-disk format is unchanged. Co-Authored-By: Claude Opus 5.5 --- cmd/spotify-mcp/main.go | 24 +-- internal/account/account.go | 46 +---- internal/account/account_test.go | 87 ++++++++-- internal/account/entities.go | 107 ++++++++++++ internal/account/invite.go | 15 +- internal/account/profiles.go | 2 +- internal/account/service.go | 143 ++++++++++------ internal/account/tokensource.go | 67 +++++--- internal/account/tokensource_test.go | 28 ++- internal/config/config.go | 104 ++++++++---- internal/config/config_test.go | 22 ++- internal/filestore/filestore.go | 103 ++++++----- internal/filestore/filestore_test.go | 61 +++++-- internal/mcpserver/mcpserver.go | 65 ++++--- internal/mcpserver/mcpserver_test.go | 34 ++-- internal/playback/playback.go | 244 ++++++++++++++++++++------- internal/playback/playback_test.go | 93 +++++++--- internal/playback/service.go | 100 ++++++----- internal/spotify/api.go | 18 +- internal/spotify/auth.go | 68 ++++---- internal/spotify/player.go | 98 ++++++----- internal/spotify/spotify_test.go | 42 +++-- internal/web/web.go | 22 +-- internal/web/web_test.go | 15 +- 24 files changed, 1065 insertions(+), 543 deletions(-) create mode 100644 internal/account/entities.go diff --git a/cmd/spotify-mcp/main.go b/cmd/spotify-mcp/main.go index d3315c6..1003f69 100644 --- a/cmd/spotify-mcp/main.go +++ b/cmd/spotify-mcp/main.go @@ -62,16 +62,16 @@ func invite(args []string) error { if err != nil { return err } - store, err := filestore.Open(cfg.DataDir) + store, err := filestore.Open(cfg.DataDir()) if err != nil { return err } - code, expires, err := account.NewInviter(store).CreateInvite(context.Background(), cfg.ProfileID, *ttl) + code, expires, err := account.NewInviter(store).CreateInvite(context.Background(), cfg.ProfileID(), *ttl) if err != nil { return err } fmt.Println(cfg.InviteURL(code)) - fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", cfg.ProfileID, expires.Format("2006-01-02 15:04 MST")) + fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", cfg.ProfileID(), expires.Format("2006-01-02 15:04 MST")) return nil } @@ -83,45 +83,45 @@ func serve(log *slog.Logger) error { if err := cfg.RequireCredentials(); err != nil { return err } - store, err := filestore.Open(cfg.DataDir) + store, err := filestore.Open(cfg.DataDir()) if err != nil { return err } oauth := spotify.NewOAuth(spotify.OAuthConfig{ - ClientID: cfg.ClientID, ClientSecret: cfg.ClientSecret, RedirectURL: cfg.RedirectURL.String(), + ClientID: cfg.ClientID(), ClientSecret: cfg.ClientSecret(), RedirectURL: cfg.RedirectURL(), }) api := spotify.NewAPI(spotify.DefaultAPIURL, nil) - tokens := account.NewTokenSource(store, oauth, cfg.ProfileID) + tokens := account.NewTokenSource(store, oauth, cfg.ProfileID()) player := playback.NewService(spotify.NewPlayer(api, tokens)) accounts := account.NewService(store, store, oauth, api) // Only for the log: a broken token file shouldn't stop the server, the // tools report it when they need the token. - prof, err := account.NewProfiles(store).Profile(context.Background(), cfg.ProfileID) + prof, err := account.NewProfiles(store).Profile(context.Background(), cfg.ProfileID()) if err != nil { - log.Warn("can't read the connected account", "profile", cfg.ProfileID.String(), "err", err) + log.Warn("can't read the connected account", "profile", cfg.ProfileID().String(), "err", err) } else if acc, ok := prof.Account(); ok { - log.Info("spotify account connected", "profile", prof.ID().String(), "spotify_user", acc.ID) + log.Info("spotify account connected", "profile", prof.ID().String(), "spotify_user", acc.ID()) } else { log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", prof.ID().String()) } servers := []*http.Server{ { - Addr: cfg.MCPAddr, + Addr: cfg.MCPAddr(), Handler: mcpserver.Handler(mcpserver.NewServer(player, version), log), ReadHeaderTimeout: 10 * time.Second, }, { - Addr: cfg.WebAddr, + Addr: cfg.WebAddr(), Handler: web.NewHandler(accounts, log), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, }, } - log.Info("spotify-mcp started", "version", version, "profile", cfg.ProfileID.String(), "connect_url", cfg.PublicURL.JoinPath("connect").String()) + log.Info("spotify-mcp started", "version", version, "profile", cfg.ProfileID().String(), "connect_url", cfg.ConnectURL()) return run(log, servers) } diff --git a/internal/account/account.go b/internal/account/account.go index 7a914ce..2c576c6 100644 --- a/internal/account/account.go +++ b/internal/account/account.go @@ -31,10 +31,10 @@ type profile struct { } // newProfile builds a profile from its connection; c is nil if it has none. -func newProfile(id ProfileID, c *Connection) *profile { +func newProfile(id ProfileID, c Connection) *profile { p := &profile{id: id} if c != nil { - p.account, p.connected, p.connectedAt = c.Account, true, c.ConnectedAt + p.account, p.connected, p.connectedAt = c.Account(), true, c.ConnectedAt() } return p } @@ -45,41 +45,6 @@ func (p *profile) Account() (SpotifyAccount, bool) { return p.account, p.connect // String makes a profile print as its ID in logs and messages. func (p *profile) String() string { return p.id.String() } -// SpotifyAccount is the Spotify account connected to a profile. -type SpotifyAccount struct { - ID string - DisplayName string -} - -// Name is what to show a person: the display name, else the account ID. -func (a SpotifyAccount) Name() string { - if a.DisplayName != "" { - return a.DisplayName - } - return a.ID -} - -// Token is an OAuth token pair as Spotify issues it. -type Token struct { - AccessToken string - RefreshToken string // empty when Spotify keeps the old one - Expiry time.Time -} - -// expiryDelta refreshes a little early, so a token doesn't expire in flight. -const expiryDelta = 30 * time.Second - -// Connection is what is stored per profile. -type Connection struct { - Token Token - Account SpotifyAccount - ConnectedAt time.Time -} - -func (c Connection) accessValid(now time.Time) bool { - return c.Token.AccessToken != "" && now.Add(expiryDelta).Before(c.Token.Expiry) -} - // Errors returned by this package and by the ports' implementations. var ( // ErrNotFound is returned by repositories for a missing entry. @@ -114,9 +79,10 @@ type Tokens interface { // SaveConnection replaces the profile's connection. SaveConnection(ctx context.Context, id ProfileID, c Connection) error // UpdateConnection reads, changes and writes the connection as one step: - // no other write to the profile may happen in between. It returns - // ErrNotFound if the profile has none, and writes nothing if fn fails. - UpdateConnection(ctx context.Context, id ProfileID, fn func(*Connection) error) error + // no other write to the profile may happen in between. fn returns the + // connection to write. It returns ErrNotFound if the profile has none, + // and writes nothing if fn fails. + UpdateConnection(ctx context.Context, id ProfileID, fn func(Connection) (Connection, error)) error // DeleteConnection forgets the profile's connection; a missing one is fine. DeleteConnection(ctx context.Context, id ProfileID) error } diff --git a/internal/account/account_test.go b/internal/account/account_test.go index 4ced0a3..3936e88 100644 --- a/internal/account/account_test.go +++ b/internal/account/account_test.go @@ -25,6 +25,25 @@ func mustProfileID(s string) account.ProfileID { return id } +func must[T any](v T, err error) T { + if err != nil { + panic(err) + } + return v +} + +func token(access, refresh string, expiry time.Time) account.Token { + return must(account.NewToken(access, refresh, expiry)) +} + +func spotifyAccount(id, name string) account.SpotifyAccount { + return must(account.NewSpotifyAccount(id, name)) +} + +func connection(tok account.Token, acc account.SpotifyAccount, at time.Time) account.Connection { + return must(account.NewConnection(tok, acc, at)) +} + // fakeOAuth issues tokens for the code "good" and the verifier of the last // started login. type fakeOAuth struct { @@ -48,10 +67,10 @@ func (f *fakeOAuth) Exchange(_ context.Context, code, verifier string) (account. defer f.mu.Unlock() for _, v := range f.verifiers { if v == verifier && code == "good" { - return account.Token{AccessToken: "a1", RefreshToken: "r1", Expiry: time.Now().Add(time.Hour)}, nil + return token("a1", "r1", time.Now().Add(time.Hour)), nil } } - return account.Token{}, errors.New("bad code or verifier") + return nil, errors.New("bad code or verifier") } func (f *fakeOAuth) Refresh(ctx context.Context, rt string) (account.Token, error) { @@ -61,14 +80,17 @@ func (f *fakeOAuth) Refresh(ctx context.Context, rt string) (account.Token, erro type fakeIdentity struct{ err error } func (f fakeIdentity) Account(context.Context, string) (account.SpotifyAccount, error) { - return account.SpotifyAccount{ID: "jan", DisplayName: "Jan"}, f.err + if f.err != nil { + return nil, f.err + } + return spotifyAccount("jan", "Jan"), nil } type env struct { - store *filestore.Store + store filestore.Store oauth *fakeOAuth - inviter *account.Inviter - svc *account.Service + inviter account.Inviter + svc account.Service now time.Time } @@ -101,11 +123,11 @@ func (e *env) start(t *testing.T, code account.InviteCode) account.Callback { if err != nil { t.Fatal(err) } - u, err := url.Parse(login.URL) + u, err := url.Parse(login.URL()) if err != nil { t.Fatal(err) } - return account.Callback{State: u.Query().Get("state"), Nonce: login.Nonce, Code: "good"} + return account.NewCallback(u.Query().Get("state"), login.Nonce(), "good", "") } func TestLoginConnectsAndUsesUpInvite(t *testing.T) { @@ -114,10 +136,10 @@ func TestLoginConnectsAndUsesUpInvite(t *testing.T) { code := e.invite(t) st, err := e.svc.Status(ctx, code) - if err != nil || st.Profile.ID() != profile || !st.ConnectedAt.IsZero() { + if err != nil || st.Profile().ID() != profile || !st.ConnectedAt().IsZero() { t.Fatalf("status before: %+v %v", st, err) } - if _, connected := st.Profile.Account(); connected { + if _, connected := st.Profile().Account(); connected { t.Fatal("connected before login") } p, err := e.svc.FinishLogin(ctx, e.start(t, code)) @@ -128,7 +150,7 @@ func TestLoginConnectsAndUsesUpInvite(t *testing.T) { t.Fatalf("finish account: %+v %v", acc, ok) } c, err := e.store.Connection(ctx, profile) - if err != nil || c.Token.RefreshToken != "r1" || c.Account.ID != "jan" || !c.ConnectedAt.Equal(e.now) { + if err != nil || c.Token().RefreshToken() != "r1" || c.Account().ID() != "jan" || !c.ConnectedAt().Equal(e.now) { t.Fatalf("stored: %+v %v", c, err) } if _, err := e.svc.Status(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { @@ -142,8 +164,7 @@ func TestFinishLoginNeedsSameBrowserOnce(t *testing.T) { code := e.invite(t) cb := e.start(t, code) - foreign := cb - foreign.Nonce = "someone-else" + foreign := account.NewCallback(cb.State(), "someone-else", cb.Code(), "") if _, err := e.svc.FinishLogin(ctx, foreign); !errors.Is(err, account.ErrLoginExpired) { t.Fatalf("foreign browser: %v", err) } @@ -172,8 +193,8 @@ func TestFailedLoginsKeepInvite(t *testing.T) { t.Run(name, func(t *testing.T) { e := newEnv(t, tc.identityErr) code := e.invite(t) - cb := e.start(t, code) - cb.Error = tc.spotifyErr + started := e.start(t, code) + cb := account.NewCallback(started.State(), started.Nonce(), started.Code(), tc.spotifyErr) if _, err := e.svc.FinishLogin(ctx, cb); !errors.Is(err, tc.want) { t.Fatalf("got %v, want %v", err, tc.want) } @@ -192,10 +213,10 @@ func TestDisconnect(t *testing.T) { } code := e.invite(t) st, err := e.svc.Status(ctx, code) - if err != nil || !st.ConnectedAt.Equal(e.now) { + if err != nil || !st.ConnectedAt().Equal(e.now) { t.Fatalf("status: %+v %v", st, err) } - if acc, ok := st.Profile.Account(); !ok || acc.Name() != "Jan" { + if acc, ok := st.Profile().Account(); !ok || acc.Name() != "Jan" { t.Fatalf("status account: %+v %v", acc, ok) } p, err := e.svc.Disconnect(ctx, code) @@ -312,7 +333,37 @@ func TestProfiles(t *testing.T) { t.Fatal("snapshot changed") } p, err = profiles.Profile(ctx, profile) - if acc, ok := p.Account(); err != nil || !ok || acc.ID != "jan" { + if acc, ok := p.Account(); err != nil || !ok || acc.ID() != "jan" { t.Fatalf("after login: %+v %v %v", acc, ok, err) } } + +func TestEntityConstructors(t *testing.T) { + if _, err := account.NewToken("", "", time.Time{}); err == nil { + t.Error("empty token accepted") + } + if _, err := account.NewSpotifyAccount("", "Jan"); err == nil { + t.Error("account without ID accepted") + } + tok, acc := token("secret-access", "secret-refresh", time.Time{}), spotifyAccount("jan", "") + if acc.Name() != "jan" { + t.Errorf("name falls back to the ID: %q", acc.Name()) + } + for name, c := range map[string]struct { + tok account.Token + acc account.SpotifyAccount + }{ + "no token": {nil, acc}, + "no refresh token": {token("a", "", time.Time{}), acc}, + "no account": {tok, nil}, + } { + if _, err := account.NewConnection(c.tok, c.acc, time.Time{}); err == nil { + t.Errorf("%s: accepted", name) + } + } + for _, s := range []string{fmt.Sprint(tok), fmt.Sprintf("%v", tok), fmt.Sprintf("%+v", tok)} { + if strings.Contains(s, "secret") { + t.Errorf("token printed: %s", s) + } + } +} diff --git a/internal/account/entities.go b/internal/account/entities.go new file mode 100644 index 0000000..f67219d --- /dev/null +++ b/internal/account/entities.go @@ -0,0 +1,107 @@ +package account + +import ( + "errors" + "time" +) + +// SpotifyAccount is the Spotify account connected to a profile. Get one from +// NewSpotifyAccount. +type SpotifyAccount interface { + // ID is Spotify's user ID. + ID() string + DisplayName() string + // Name is what to show a person: the display name, else the ID. + Name() string +} + +type spotifyAccount struct { + id, displayName string +} + +// NewSpotifyAccount builds a SpotifyAccount; the ID is required. +func NewSpotifyAccount(id, displayName string) (SpotifyAccount, error) { + if id == "" { + return nil, errors.New("spotify account has no ID") + } + return &spotifyAccount{id: id, displayName: displayName}, nil +} + +func (a *spotifyAccount) ID() string { return a.id } +func (a *spotifyAccount) DisplayName() string { return a.displayName } + +func (a *spotifyAccount) Name() string { + if a.displayName != "" { + return a.displayName + } + return a.id +} + +// Token is an OAuth token pair as Spotify issues it. Get one from NewToken. +// It prints as redacted, so it can't leak into logs by accident. +type Token interface { + AccessToken() string + // RefreshToken is empty when Spotify keeps the old one. + RefreshToken() string + Expiry() time.Time +} + +type token struct { + access, refresh string + expiry time.Time +} + +// NewToken builds a Token. At least one of the two tokens is required. +func NewToken(accessToken, refreshToken string, expiry time.Time) (Token, error) { + if accessToken == "" && refreshToken == "" { + return nil, errors.New("token is empty") + } + return &token{access: accessToken, refresh: refreshToken, expiry: expiry}, nil +} + +func (t *token) AccessToken() string { return t.access } +func (t *token) RefreshToken() string { return t.refresh } +func (t *token) Expiry() time.Time { return t.expiry } +func (t *token) String() string { return "Token(redacted)" } + +// expiryDelta refreshes a little early, so a token doesn't expire in flight. +const expiryDelta = 30 * time.Second + +// Connection is what is stored per profile: the token and the account it +// belongs to. Get one from NewConnection. +type Connection interface { + Token() Token + Account() SpotifyAccount + ConnectedAt() time.Time +} + +type connection struct { + token Token + account SpotifyAccount + connectedAt time.Time +} + +// NewConnection builds a Connection; token and account are required. +func NewConnection(tok Token, acc SpotifyAccount, connectedAt time.Time) (Connection, error) { + if tok == nil || tok.RefreshToken() == "" { + return nil, errors.New("connection needs a refresh token") + } + if acc == nil { + return nil, errors.New("connection needs a Spotify account") + } + return &connection{token: tok, account: acc, connectedAt: connectedAt}, nil +} + +func (c *connection) Token() Token { return c.token } +func (c *connection) Account() SpotifyAccount { return c.account } +func (c *connection) ConnectedAt() time.Time { return c.connectedAt } + +// withToken returns a copy of c with another token. +func withToken(c Connection, tok Token) Connection { + return &connection{token: tok, account: c.Account(), connectedAt: c.ConnectedAt()} +} + +func accessValid(c Connection, now time.Time) bool { + t := c.Token() + return t != nil && t.AccessToken() != "" && now.Add(expiryDelta).Before(t.Expiry()) +} diff --git a/internal/account/invite.go b/internal/account/invite.go index 02e7a63..57a6a6a 100644 --- a/internal/account/invite.go +++ b/internal/account/invite.go @@ -9,18 +9,23 @@ import ( // Inviter creates one-time invite links. It needs no Spotify access, so the // invite command can run it on its own. -type Inviter struct { +type Inviter interface { + // CreateInvite returns a new one-time code for the profile and when it + // expires. + CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) +} + +type inviter struct { invites Invites now func() time.Time } // NewInviter returns an Inviter storing into invites. -func NewInviter(invites Invites, opts ...Option) *Inviter { - return &Inviter{invites: invites, now: apply(opts).now} +func NewInviter(invites Invites, opts ...Option) Inviter { + return &inviter{invites: invites, now: apply(opts).now} } -// CreateInvite returns a new one-time code for the profile and when it expires. -func (i *Inviter) CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) { +func (i *inviter) CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) { if id == nil { return nil, time.Time{}, errors.New("invite needs a profile") } diff --git a/internal/account/profiles.go b/internal/account/profiles.go index 36cdacc..5658636 100644 --- a/internal/account/profiles.go +++ b/internal/account/profiles.go @@ -37,5 +37,5 @@ func loadProfile(ctx context.Context, tokens Tokens, id ProfileID) (*profile, er case err != nil: return nil, fmt.Errorf("load connection: %w", err) } - return newProfile(id, &c), nil + return newProfile(id, c), nil } diff --git a/internal/account/service.go b/internal/account/service.go index a061437..68a47de 100644 --- a/internal/account/service.go +++ b/internal/account/service.go @@ -18,7 +18,24 @@ const ( ) // Service runs logins and disconnects for holders of an invite. -type Service struct { +type Service interface { + // Status reports the profile an invite belongs to and who is connected, + // without using the invite up. + Status(ctx context.Context, code InviteCode) (Status, error) + // StartLogin begins the OAuth login (state + PKCE) for an invite. The + // invite is only used up when the login succeeds. + StartLogin(ctx context.Context, code InviteCode) (Login, error) + // FinishLogin completes a login: it exchanges the code, checks the + // account may use the app, uses up the invite and stores the connection, + // replacing any previous one. Each state can be finished at most once. + // It returns the profile with the newly connected account. + FinishLogin(ctx context.Context, cb Callback) (Profile, error) + // Disconnect uses up the invite and deletes its profile's connection. It + // returns the profile, now without an account. + Disconnect(ctx context.Context, code InviteCode) (Profile, error) +} + +type service struct { tokens Tokens invites Invites oauth OAuth @@ -38,57 +55,79 @@ type pendingLogin struct { } // NewService returns a Service using the given ports. -func NewService(tokens Tokens, invites Invites, oauth OAuth, identity Identity, opts ...Option) *Service { - return &Service{ +func NewService(tokens Tokens, invites Invites, oauth OAuth, identity Identity, opts ...Option) Service { + return &service{ tokens: tokens, invites: invites, oauth: oauth, identity: identity, now: apply(opts).now, pending: map[string]pendingLogin{}, } } -// Status is what an invite link's page shows: the invite's profile with its -// connected account, and since when it is connected (zero if it isn't). -type Status struct { - Profile Profile - ConnectedAt time.Time +// Status is what an invite link's page shows. +type Status interface { + // Profile is the invite's profile with its connected account. + Profile() Profile + // ConnectedAt is when the account was connected; zero if none is. + ConnectedAt() time.Time } +type status struct{ p *profile } + +func (s status) Profile() Profile { return s.p } +func (s status) ConnectedAt() time.Time { return s.p.connectedAt } + // Login is a started login: send the browser to URL and bind it to the login // with Nonce (e.g. in a cookie that only the callback receives). -type Login struct { - URL string - Nonce string +type Login interface { + URL() string + Nonce() string } -// Callback is what Spotify sends back, plus the browser's nonce. -type Callback struct { - State string - Nonce string - Code string - // Error is Spotify's error parameter, e.g. "access_denied". - Error string +type login struct{ url, nonce string } + +func (l login) URL() string { return l.url } +func (l login) Nonce() string { return l.nonce } + +// Callback is what Spotify sends back, plus the browser's nonce. Get one +// from NewCallback. +type Callback interface { + State() string + Nonce() string + Code() string + // SpotifyError is Spotify's error parameter, e.g. "access_denied". + SpotifyError() string +} + +type callback struct{ state, nonce, code, spotifyError string } + +// NewCallback builds a Callback from the callback request. A state or nonce +// that doesn't belong to a started login makes FinishLogin fail with +// ErrLoginExpired. +func NewCallback(state, nonce, code, spotifyError string) Callback { + return callback{state: state, nonce: nonce, code: code, spotifyError: spotifyError} } -// Status reports the profile an invite belongs to and who is connected, -// without using the invite up. -func (s *Service) Status(ctx context.Context, code InviteCode) (Status, error) { +func (c callback) State() string { return c.state } +func (c callback) Nonce() string { return c.nonce } +func (c callback) Code() string { return c.code } +func (c callback) SpotifyError() string { return c.spotifyError } + +func (s *service) Status(ctx context.Context, code InviteCode) (Status, error) { inv, err := s.checkInvite(ctx, code) if err != nil { - return Status{}, err + return nil, err } p, err := loadProfile(ctx, s.tokens, inv.ProfileID()) if err != nil { - return Status{}, err + return nil, err } - return Status{Profile: p, ConnectedAt: p.connectedAt}, nil + return status{p: p}, nil } -// StartLogin begins the OAuth login (state + PKCE) for an invite. The invite -// is only used up when the login succeeds. -func (s *Service) StartLogin(ctx context.Context, code InviteCode) (Login, error) { +func (s *service) StartLogin(ctx context.Context, code InviteCode) (Login, error) { inv, err := s.checkInvite(ctx, code) if err != nil { - return Login{}, err + return nil, err } state, nonce, verifier := randomString(), randomString(), randomString() now := s.now() @@ -101,60 +140,60 @@ func (s *Service) StartLogin(ctx context.Context, code InviteCode) (Login, error } } if len(s.pending) >= maxPending { - return Login{}, ErrTooManyLogins + return nil, ErrTooManyLogins } s.pending[state] = pendingLogin{ invite: inv.Hash(), profile: inv.ProfileID(), verifier: verifier, nonce: nonce, expires: now.Add(LoginTTL), } - return Login{URL: s.oauth.AuthCodeURL(state, verifier), Nonce: nonce}, nil + return login{url: s.oauth.AuthCodeURL(state, verifier), nonce: nonce}, nil } -// FinishLogin completes a login: it exchanges the code, checks the account -// may use the app, uses up the invite and stores the connection, replacing -// any previous one. Each state can be finished at most once. It returns the -// profile with the newly connected account. -func (s *Service) FinishLogin(ctx context.Context, cb Callback) (Profile, error) { +func (s *service) FinishLogin(ctx context.Context, cb Callback) (Profile, error) { + if cb == nil { + return nil, ErrLoginExpired + } s.mu.Lock() - p, ok := s.pending[cb.State] - delete(s.pending, cb.State) + p, ok := s.pending[cb.State()] + delete(s.pending, cb.State()) s.mu.Unlock() - if !ok || s.now().After(p.expires) || subtle.ConstantTimeCompare([]byte(cb.Nonce), []byte(p.nonce)) != 1 { + if !ok || s.now().After(p.expires) || subtle.ConstantTimeCompare([]byte(cb.Nonce()), []byte(p.nonce)) != 1 { return nil, ErrLoginExpired } - if cb.Error == "access_denied" { + if cb.SpotifyError() == "access_denied" { return nil, ErrLoginCancelled } - if cb.Error != "" { - return nil, fmt.Errorf("spotify refused the login: %s", cb.Error) + if e := cb.SpotifyError(); e != "" { + return nil, fmt.Errorf("spotify refused the login: %s", e) } - tok, err := s.oauth.Exchange(ctx, cb.Code, p.verifier) + tok, err := s.oauth.Exchange(ctx, cb.Code(), p.verifier) if err != nil { return nil, fmt.Errorf("exchange code: %w", err) } - if tok.RefreshToken == "" { + if tok == nil || tok.RefreshToken() == "" { return nil, errors.New("spotify sent no refresh token") } // Before the invite is used up: an account that isn't allowlisted yet can // try again with the same link once the owner added it. - acc, err := s.identity.Account(ctx, tok.AccessToken) + acc, err := s.identity.Account(ctx, tok.AccessToken()) if err != nil { return nil, fmt.Errorf("look up account: %w", err) } + c, err := NewConnection(tok, acc, s.now()) + if err != nil { + return nil, err + } if _, err := s.takeInvite(ctx, p.invite); err != nil { return nil, err } - c := Connection{Token: tok, Account: acc, ConnectedAt: s.now()} if err := s.tokens.SaveConnection(ctx, p.profile, c); err != nil { return nil, fmt.Errorf("save connection: %w", err) } - return newProfile(p.profile, &c), nil + return newProfile(p.profile, c), nil } -// Disconnect uses up the invite and deletes its profile's connection. It -// returns the profile, now without an account. -func (s *Service) Disconnect(ctx context.Context, code InviteCode) (Profile, error) { +func (s *service) Disconnect(ctx context.Context, code InviteCode) (Profile, error) { if code == nil { return nil, ErrInvalidInvite } @@ -168,7 +207,7 @@ func (s *Service) Disconnect(ctx context.Context, code InviteCode) (Profile, err return newProfile(inv.ProfileID(), nil), nil } -func (s *Service) checkInvite(ctx context.Context, code InviteCode) (Invite, error) { +func (s *service) checkInvite(ctx context.Context, code InviteCode) (Invite, error) { if code == nil { return nil, ErrInvalidInvite } @@ -176,12 +215,12 @@ func (s *Service) checkInvite(ctx context.Context, code InviteCode) (Invite, err return s.validInvite(inv, err) } -func (s *Service) takeInvite(ctx context.Context, h InviteHash) (Invite, error) { +func (s *service) takeInvite(ctx context.Context, h InviteHash) (Invite, error) { inv, err := s.invites.TakeInvite(ctx, h) return s.validInvite(inv, err) } -func (s *Service) validInvite(inv Invite, err error) (Invite, error) { +func (s *service) validInvite(inv Invite, err error) (Invite, error) { switch { case errors.Is(err, ErrNotFound): return nil, ErrInvalidInvite diff --git a/internal/account/tokensource.go b/internal/account/tokensource.go index 79661ca..f493b92 100644 --- a/internal/account/tokensource.go +++ b/internal/account/tokensource.go @@ -14,20 +14,31 @@ import ( // writes the connection as one step. A login that lands meanwhile waits and // then replaces the result, instead of being overwritten by the old account's // refreshed token. It also means two callers never refresh the same token. -type TokenSource struct { +type TokenSource interface { + // AccessToken returns a valid access token, or ErrNotConnected. + AccessToken(ctx context.Context) (string, error) + // Invalidate marks accessToken as expired after Spotify rejected it, so + // the next call refreshes. It does nothing if the stored token has + // changed since. + Invalidate(ctx context.Context, accessToken string) error +} + +type tokenSource struct { tokens Tokens oauth OAuth profile ProfileID now func() time.Time } -// NewTokenSource returns a TokenSource for p. -func NewTokenSource(tokens Tokens, oauth OAuth, id ProfileID, opts ...Option) *TokenSource { - return &TokenSource{tokens: tokens, oauth: oauth, profile: id, now: apply(opts).now} +// NewTokenSource returns a TokenSource for the profile. +func NewTokenSource(tokens Tokens, oauth OAuth, id ProfileID, opts ...Option) TokenSource { + return &tokenSource{tokens: tokens, oauth: oauth, profile: id, now: apply(opts).now} } -// AccessToken returns a valid access token, or ErrNotConnected. -func (ts *TokenSource) AccessToken(ctx context.Context) (string, error) { +func (ts *tokenSource) AccessToken(ctx context.Context) (string, error) { + if ts.profile == nil { + return "", ErrNotConnected + } c, err := ts.tokens.Connection(ctx, ts.profile) if errors.Is(err, ErrNotFound) { return "", ErrNotConnected @@ -35,25 +46,28 @@ func (ts *TokenSource) AccessToken(ctx context.Context) (string, error) { if err != nil { return "", fmt.Errorf("load connection: %w", err) } - if c.accessValid(ts.now()) { - return c.Token.AccessToken, nil + if accessValid(c, ts.now()) { + return c.Token().AccessToken(), nil } var access string - err = ts.tokens.UpdateConnection(ctx, ts.profile, func(c *Connection) error { - if c.accessValid(ts.now()) { // refreshed by someone else meanwhile - access = c.Token.AccessToken - return nil + err = ts.tokens.UpdateConnection(ctx, ts.profile, func(c Connection) (Connection, error) { + if accessValid(c, ts.now()) { // refreshed by someone else meanwhile + access = c.Token().AccessToken() + return c, nil } - tok, err := ts.oauth.Refresh(ctx, c.Token.RefreshToken) + old := c.Token().RefreshToken() + tok, err := ts.oauth.Refresh(ctx, old) if err != nil { - return err + return nil, err } - if tok.RefreshToken == "" { // Spotify kept the old one - tok.RefreshToken = c.Token.RefreshToken + if tok.RefreshToken() == "" { // Spotify kept the old one + if tok, err = NewToken(tok.AccessToken(), old, tok.Expiry()); err != nil { + return nil, err + } } - c.Token, access = tok, tok.AccessToken - return nil + access = tok.AccessToken() + return withToken(c, tok), nil }) switch { case errors.Is(err, ErrNotFound), errors.Is(err, ErrRevoked): @@ -64,14 +78,17 @@ func (ts *TokenSource) AccessToken(ctx context.Context) (string, error) { return access, nil } -// Invalidate marks accessToken as expired after Spotify rejected it, so the -// next call refreshes. It does nothing if the stored token has changed since. -func (ts *TokenSource) Invalidate(ctx context.Context, accessToken string) error { - err := ts.tokens.UpdateConnection(ctx, ts.profile, func(c *Connection) error { - if c.Token.AccessToken == accessToken { - c.Token.Expiry = time.Time{} +func (ts *tokenSource) Invalidate(ctx context.Context, accessToken string) error { + err := ts.tokens.UpdateConnection(ctx, ts.profile, func(c Connection) (Connection, error) { + t := c.Token() + if t.AccessToken() != accessToken { + return c, nil } - return nil + expired, err := NewToken(t.AccessToken(), t.RefreshToken(), time.Time{}) + if err != nil { + return nil, err + } + return withToken(c, expired), nil }) if errors.Is(err, ErrNotFound) { return nil diff --git a/internal/account/tokensource_test.go b/internal/account/tokensource_test.go index 1043f39..60f3546 100644 --- a/internal/account/tokensource_test.go +++ b/internal/account/tokensource_test.go @@ -16,15 +16,12 @@ func (e *env) connect(t *testing.T, c account.Connection) { } } -func (e *env) tokens() *account.TokenSource { +func (e *env) tokens() account.TokenSource { return account.NewTokenSource(e.store, e.oauth, profile, account.WithClock(func() time.Time { return e.now })) } func expired(rt string) account.Connection { - return account.Connection{ - Token: account.Token{AccessToken: "old", RefreshToken: rt}, - Account: account.SpotifyAccount{ID: "jan", DisplayName: "Jan"}, - } + return connection(token("old", rt, time.Time{}), spotifyAccount("jan", "Jan"), time.Time{}) } func TestAccessTokenRefreshesAndPersists(t *testing.T) { @@ -42,7 +39,7 @@ func TestAccessTokenRefreshesAndPersists(t *testing.T) { if rt != "r1" { t.Errorf("refreshed with %q", rt) } - return account.Token{AccessToken: "new", RefreshToken: tc.sent, Expiry: e.now.Add(time.Hour)}, nil + return token("new", tc.sent, e.now.Add(time.Hour)), nil } ts := e.tokens() for range 2 { @@ -54,7 +51,7 @@ func TestAccessTokenRefreshesAndPersists(t *testing.T) { t.Fatalf("refreshed %d times, want once", calls) } c, _ := e.store.Connection(ctx, profile) - if c.Token.RefreshToken != tc.stored || c.Account.DisplayName != "Jan" { + if c.Token().RefreshToken() != tc.stored || c.Account().DisplayName() != "Jan" { t.Fatalf("stored %+v", c) } }) @@ -68,7 +65,7 @@ func TestAccessTokenNotConnected(t *testing.T) { t.Fatalf("no connection: %v", err) } e.connect(t, expired("r1")) - e.oauth.refresh = func(context.Context, string) (account.Token, error) { return account.Token{}, account.ErrRevoked } + e.oauth.refresh = func(context.Context, string) (account.Token, error) { return nil, account.ErrRevoked } if _, err := e.tokens().AccessToken(ctx); !errors.Is(err, account.ErrNotConnected) { t.Fatalf("revoked: %v", err) } @@ -77,11 +74,9 @@ func TestAccessTokenNotConnected(t *testing.T) { func TestInvalidateForcesRefresh(t *testing.T) { ctx := context.Background() e := newEnv(t, nil) - c := expired("r1") - c.Token.Expiry = e.now.Add(time.Hour) - e.connect(t, c) + e.connect(t, connection(token("old", "r1", e.now.Add(time.Hour)), spotifyAccount("jan", "Jan"), time.Time{})) e.oauth.refresh = func(context.Context, string) (account.Token, error) { - return account.Token{AccessToken: "new", Expiry: e.now.Add(time.Hour)}, nil + return token("new", "", e.now.Add(time.Hour)), nil } ts := e.tokens() if err := ts.Invalidate(ctx, "not-the-stored-one"); err != nil { @@ -109,7 +104,7 @@ func TestLoginDuringRefreshWins(t *testing.T) { e.oauth.refresh = func(context.Context, string) (account.Token, error) { close(refreshing) <-release - return account.Token{AccessToken: "old-account-access", Expiry: e.now.Add(time.Hour)}, nil + return token("old-account-access", "", e.now.Add(time.Hour)), nil } refreshed := make(chan error, 1) go func() { @@ -118,10 +113,7 @@ func TestLoginDuringRefreshWins(t *testing.T) { }() <-refreshing - login := account.Connection{ - Token: account.Token{AccessToken: "new-access", RefreshToken: "new-account", Expiry: e.now.Add(time.Hour)}, - Account: account.SpotifyAccount{ID: "someone-else"}, - } + login := connection(token("new-access", "new-account", e.now.Add(time.Hour)), spotifyAccount("someone-else", ""), time.Time{}) saved := make(chan error, 1) go func() { saved <- e.store.SaveConnection(ctx, profile, login) }() select { @@ -137,7 +129,7 @@ func TestLoginDuringRefreshWins(t *testing.T) { t.Fatal(err) } c, err := e.store.Connection(ctx, profile) - if err != nil || c.Token.RefreshToken != "new-account" || c.Account.ID != "someone-else" { + if err != nil || c.Token().RefreshToken() != "new-account" || c.Account().ID() != "someone-else" { t.Fatalf("stored %+v %v, want the new login", c, err) } } diff --git a/internal/config/config.go b/internal/config/config.go index 33bb9e9..7b9e963 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -11,72 +11,111 @@ import ( ) // Config holds every setting. Secrets come from a Kubernetes Secret (or a -// local .env) through the environment, never from files in the repo. -type Config struct { - ClientID string - ClientSecret string +// local .env) through the environment, never from files in the repo. Get one +// from Load. +type Config interface { + ClientID() string + // ClientSecret is the Spotify app's secret. Keep it out of logs. + ClientSecret() string // RedirectURL is the OAuth callback registered in the Spotify app; its // path is /callback. - RedirectURL *url.URL - // PublicURL is the base of invite links. - PublicURL *url.URL - DataDir string - ProfileID account.ProfileID - MCPAddr string - WebAddr string + RedirectURL() string + // ConnectURL is the connect page, the base of invite links. + ConnectURL() string + DataDir() string + ProfileID() account.ProfileID + MCPAddr() string + WebAddr() string + // RequireCredentials reports missing Spotify app credentials. + RequireCredentials() error + // InviteURL is the link that opens the connect page with code. + InviteURL(code account.InviteCode) string +} + +type config struct { + clientID string + clientSecret string + redirectURL *url.URL + publicURL *url.URL + dataDir string + profileID account.ProfileID + mcpAddr string + webAddr string +} + +func (c *config) ClientID() string { return c.clientID } +func (c *config) ClientSecret() string { return c.clientSecret } +func (c *config) RedirectURL() string { return c.redirectURL.String() } +func (c *config) ConnectURL() string { return c.publicURL.JoinPath("connect").String() } +func (c *config) DataDir() string { return c.dataDir } +func (c *config) ProfileID() account.ProfileID { return c.profileID } +func (c *config) MCPAddr() string { return c.mcpAddr } +func (c *config) WebAddr() string { return c.webAddr } + +// String keeps the client secret out of logs and error messages. +func (c *config) String() string { + return fmt.Sprintf("config{redirect %s, data %s, profile %s, mcp %s, web %s}", + c.redirectURL, c.dataDir, c.profileID, c.mcpAddr, c.webAddr) } // Load reads the settings through getenv (os.Getenv in production). It // doesn't require the client secret, which the invite command doesn't need; // call RequireCredentials before starting the server. func Load(getenv func(string) string) (Config, error) { + c, err := load(getenv) + if err != nil { + return nil, err + } + return c, nil +} + +func load(getenv func(string) string) (*config, error) { get := func(key, def string) string { if v := strings.TrimSpace(getenv(key)); v != "" { return v } return def } - c := Config{ - ClientID: get("SPOTIFY_CLIENT_ID", ""), - ClientSecret: get("SPOTIFY_CLIENT_SECRET", ""), - DataDir: get("DATA_DIR", "/data"), - MCPAddr: get("MCP_ADDR", ":8000"), - WebAddr: get("WEB_ADDR", ":8080"), + c := &config{ + clientID: get("SPOTIFY_CLIENT_ID", ""), + clientSecret: get("SPOTIFY_CLIENT_SECRET", ""), + dataDir: get("DATA_DIR", "/data"), + mcpAddr: get("MCP_ADDR", ":8000"), + webAddr: get("WEB_ADDR", ":8080"), } raw := get("SPOTIFY_REDIRECT_URI", "") if raw == "" { - return Config{}, errors.New("SPOTIFY_REDIRECT_URI is not set (see .env.example)") + return nil, errors.New("SPOTIFY_REDIRECT_URI is not set (see .env.example)") } redirect, err := parseHTTPURL(raw) if err != nil { - return Config{}, fmt.Errorf("SPOTIFY_REDIRECT_URI: %w", err) + return nil, fmt.Errorf("SPOTIFY_REDIRECT_URI: %w", err) } if redirect.Path != "/callback" { - return Config{}, errors.New("SPOTIFY_REDIRECT_URI must end in /callback, e.g. https://spotify.example.com/callback") + return nil, errors.New("SPOTIFY_REDIRECT_URI must end in /callback, e.g. https://spotify.example.com/callback") } - c.RedirectURL = redirect + c.redirectURL = redirect - c.PublicURL = &url.URL{Scheme: redirect.Scheme, Host: redirect.Host} + c.publicURL = &url.URL{Scheme: redirect.Scheme, Host: redirect.Host} if raw := get("PUBLIC_URL", ""); raw != "" { - if c.PublicURL, err = parseHTTPURL(strings.TrimRight(raw, "/")); err != nil { - return Config{}, fmt.Errorf("PUBLIC_URL: %w", err) + if c.publicURL, err = parseHTTPURL(strings.TrimRight(raw, "/")); err != nil { + return nil, fmt.Errorf("PUBLIC_URL: %w", err) } } - if c.ProfileID, err = account.ParseProfileID(get("PROFILE", "default")); err != nil { - return Config{}, fmt.Errorf("PROFILE: %w", err) + if c.profileID, err = account.ParseProfileID(get("PROFILE", "default")); err != nil { + return nil, fmt.Errorf("PROFILE: %w", err) } return c, nil } -// RequireCredentials reports missing Spotify app credentials. -func (c Config) RequireCredentials() error { +func (c *config) RequireCredentials() error { var missing []string - if c.ClientID == "" { + if c.clientID == "" { missing = append(missing, "SPOTIFY_CLIENT_ID") } - if c.ClientSecret == "" { + if c.clientSecret == "" { missing = append(missing, "SPOTIFY_CLIENT_SECRET") } if len(missing) > 0 { @@ -85,9 +124,8 @@ func (c Config) RequireCredentials() error { return nil } -// InviteURL is the link that opens the connect page with code. -func (c Config) InviteURL(code account.InviteCode) string { - u := c.PublicURL.JoinPath("connect") +func (c *config) InviteURL(code account.InviteCode) string { + u := c.publicURL.JoinPath("connect") u.RawQuery = url.Values{"invite": {code.Secret()}}.Encode() return u.String() } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 3cb504c..404add0 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -1,6 +1,7 @@ package config import ( + "fmt" "strings" "testing" @@ -16,8 +17,8 @@ func TestLoadDefaults(t *testing.T) { if err != nil { t.Fatal(err) } - if c.PublicURL.String() != "https://spotify.example.com" || c.ProfileID.String() != "default" || c.DataDir != "/data" || c.MCPAddr != ":8000" { - t.Fatalf("%+v", c) + if c.ConnectURL() != "https://spotify.example.com/connect" || c.ProfileID().String() != "default" || c.DataDir() != "/data" || c.MCPAddr() != ":8000" { + t.Fatalf("%v", c) } if err := c.RequireCredentials(); err == nil || !strings.Contains(err.Error(), "SPOTIFY_CLIENT_SECRET") { t.Fatalf("credentials: %v", err) @@ -27,6 +28,23 @@ func TestLoadDefaults(t *testing.T) { } } +func TestSecretStaysOutOfPrint(t *testing.T) { + c, err := Load(envOf(map[string]string{ + "SPOTIFY_REDIRECT_URI": "https://spotify.example.com/callback", "SPOTIFY_CLIENT_SECRET": "s3cret-value", + })) + if err != nil { + t.Fatal(err) + } + if c.ClientSecret() != "s3cret-value" { + t.Fatal("secret not loaded") + } + for _, s := range []string{fmt.Sprint(c), fmt.Sprintf("%v", c), fmt.Sprintf("%+v", c)} { + if strings.Contains(s, "s3cret") { + t.Fatalf("secret printed: %s", s) + } + } +} + func TestLoadRejects(t *testing.T) { for name, env := range map[string]map[string]string{ "no redirect": {}, diff --git a/internal/filestore/filestore.go b/internal/filestore/filestore.go index 2a10435..0100955 100644 --- a/internal/filestore/filestore.go +++ b/internal/filestore/filestore.go @@ -21,23 +21,24 @@ import ( "github.com/subpathdev/spotify-mcp/internal/account" ) -// Store is safe for concurrent use, also by several processes on one directory. -type Store struct { +// Store keeps connections and invites. It is safe for concurrent use, also +// by several processes on one directory. +type Store interface { + account.Tokens + account.Invites +} + +type store struct { dir string mu sync.Mutex } -var ( - _ account.Tokens = (*Store)(nil) - _ account.Invites = (*Store)(nil) -) - // Open creates the data directory if needed. -func Open(dir string) (*Store, error) { +func Open(dir string) (Store, error) { if err := os.MkdirAll(filepath.Join(dir, "tokens"), 0o700); err != nil { return nil, fmt.Errorf("create data dir: %w", err) } - return &Store{dir: dir}, nil + return &store{dir: dir}, nil } // connectionRecord is the on-disk format of a connection. @@ -50,19 +51,33 @@ type connectionRecord struct { ConnectedAt time.Time `json:"connected_at,omitzero"` } -func toRecord(c account.Connection) connectionRecord { - return connectionRecord{ - RefreshToken: c.Token.RefreshToken, AccessToken: c.Token.AccessToken, Expiry: c.Token.Expiry, - SpotifyUserID: c.Account.ID, DisplayName: c.Account.DisplayName, ConnectedAt: c.ConnectedAt, +func toRecord(c account.Connection) (connectionRecord, error) { + if c == nil || c.Token() == nil || c.Account() == nil { + return connectionRecord{}, errors.New("incomplete connection") } + t, a := c.Token(), c.Account() + return connectionRecord{ + RefreshToken: t.RefreshToken(), AccessToken: t.AccessToken(), Expiry: t.Expiry(), + SpotifyUserID: a.ID(), DisplayName: a.DisplayName(), ConnectedAt: c.ConnectedAt(), + }, nil } -func (r connectionRecord) connection() account.Connection { - return account.Connection{ - Token: account.Token{AccessToken: r.AccessToken, RefreshToken: r.RefreshToken, Expiry: r.Expiry}, - Account: account.SpotifyAccount{ID: r.SpotifyUserID, DisplayName: r.DisplayName}, - ConnectedAt: r.ConnectedAt, +// connection rebuilds a stored connection through the account constructors, +// so a damaged file is an error rather than a half-empty connection. +func (r connectionRecord) connection() (account.Connection, error) { + tok, err := account.NewToken(r.AccessToken, r.RefreshToken, r.Expiry) + if err != nil { + return nil, fmt.Errorf("stored connection: %w", err) + } + acc, err := account.NewSpotifyAccount(r.SpotifyUserID, r.DisplayName) + if err != nil { + return nil, fmt.Errorf("stored connection: %w", err) + } + c, err := account.NewConnection(tok, acc, r.ConnectedAt) + if err != nil { + return nil, fmt.Errorf("stored connection: %w", err) } + return c, nil } // inviteRecord is the on-disk format of an invite; invites.json maps the @@ -81,7 +96,7 @@ func (r inviteRecord) invite(hash string) (account.Invite, error) { } // lock takes the in-process and the cross-process lock. -func (s *Store) lock() (unlock func(), err error) { +func (s *store) lock() (unlock func(), err error) { s.mu.Lock() release, err := lockFile(filepath.Join(s.dir, ".lock")) if err != nil { @@ -91,7 +106,7 @@ func (s *Store) lock() (unlock func(), err error) { return func() { release(); s.mu.Unlock() }, nil } -func (s *Store) connectionPath(id account.ProfileID) (string, error) { +func (s *store) connectionPath(id account.ProfileID) (string, error) { if id == nil { return "", errors.New("no profile given") } @@ -105,25 +120,25 @@ func (s *Store) connectionPath(id account.ProfileID) (string, error) { } // Connection implements account.Tokens. -func (s *Store) Connection(_ context.Context, id account.ProfileID) (account.Connection, error) { +func (s *store) Connection(_ context.Context, id account.ProfileID) (account.Connection, error) { path, err := s.connectionPath(id) if err != nil { - return account.Connection{}, err + return nil, err } unlock, err := s.lock() if err != nil { - return account.Connection{}, err + return nil, err } defer unlock() var r connectionRecord if err := readJSON(path, &r); err != nil { - return account.Connection{}, err + return nil, err } - return r.connection(), nil + return r.connection() } // SaveConnection implements account.Tokens. -func (s *Store) SaveConnection(_ context.Context, id account.ProfileID, c account.Connection) error { +func (s *store) SaveConnection(_ context.Context, id account.ProfileID, c account.Connection) error { path, err := s.connectionPath(id) if err != nil { return err @@ -133,11 +148,15 @@ func (s *Store) SaveConnection(_ context.Context, id account.ProfileID, c accoun return err } defer unlock() - return writeJSON(path, toRecord(c)) + r, err := toRecord(c) + if err != nil { + return err + } + return writeJSON(path, r) } // UpdateConnection implements account.Tokens. fn runs under the lock. -func (s *Store) UpdateConnection(_ context.Context, id account.ProfileID, fn func(*account.Connection) error) error { +func (s *store) UpdateConnection(_ context.Context, id account.ProfileID, fn func(account.Connection) (account.Connection, error)) error { path, err := s.connectionPath(id) if err != nil { return err @@ -151,15 +170,21 @@ func (s *Store) UpdateConnection(_ context.Context, id account.ProfileID, fn fun if err := readJSON(path, &r); err != nil { return err } - c := r.connection() - if err := fn(&c); err != nil { + c, err := r.connection() + if err != nil { + return err + } + if c, err = fn(c); err != nil { + return err + } + if r, err = toRecord(c); err != nil { return err } - return writeJSON(path, toRecord(c)) + return writeJSON(path, r) } // DeleteConnection implements account.Tokens. -func (s *Store) DeleteConnection(_ context.Context, id account.ProfileID) error { +func (s *store) DeleteConnection(_ context.Context, id account.ProfileID) error { path, err := s.connectionPath(id) if err != nil { return err @@ -175,9 +200,9 @@ func (s *Store) DeleteConnection(_ context.Context, id account.ProfileID) error return nil } -func (s *Store) invitePath() string { return filepath.Join(s.dir, "invites.json") } +func (s *store) invitePath() string { return filepath.Join(s.dir, "invites.json") } -func (s *Store) loadInvites() (map[string]inviteRecord, error) { +func (s *store) loadInvites() (map[string]inviteRecord, error) { inv := map[string]inviteRecord{} if err := readJSON(s.invitePath(), &inv); err != nil && !errors.Is(err, account.ErrNotFound) { return nil, err @@ -186,7 +211,7 @@ func (s *Store) loadInvites() (map[string]inviteRecord, error) { } // changeInvites runs fn on the invites under the lock and writes them back. -func (s *Store) changeInvites(fn func(map[string]inviteRecord) error) error { +func (s *store) changeInvites(fn func(map[string]inviteRecord) error) error { unlock, err := s.lock() if err != nil { return err @@ -203,7 +228,7 @@ func (s *Store) changeInvites(fn func(map[string]inviteRecord) error) error { } // AddInvite implements account.Invites. -func (s *Store) AddInvite(_ context.Context, i account.Invite) error { +func (s *store) AddInvite(_ context.Context, i account.Invite) error { if i == nil || i.Hash() == nil || i.ProfileID() == nil { return errors.New("incomplete invite") } @@ -214,7 +239,7 @@ func (s *Store) AddInvite(_ context.Context, i account.Invite) error { } // Invite implements account.Invites. -func (s *Store) Invite(_ context.Context, h account.InviteHash) (account.Invite, error) { +func (s *store) Invite(_ context.Context, h account.InviteHash) (account.Invite, error) { if h == nil { return nil, account.ErrNotFound } @@ -235,7 +260,7 @@ func (s *Store) Invite(_ context.Context, h account.InviteHash) (account.Invite, } // TakeInvite implements account.Invites. -func (s *Store) TakeInvite(_ context.Context, h account.InviteHash) (account.Invite, error) { +func (s *store) TakeInvite(_ context.Context, h account.InviteHash) (account.Invite, error) { if h == nil { return nil, account.ErrNotFound } @@ -258,7 +283,7 @@ func (s *Store) TakeInvite(_ context.Context, h account.InviteHash) (account.Inv } // PruneInvites implements account.Invites. -func (s *Store) PruneInvites(_ context.Context, t time.Time) error { +func (s *store) PruneInvites(_ context.Context, t time.Time) error { return s.changeInvites(func(inv map[string]inviteRecord) error { for h, r := range inv { if r.Expires.Before(t) { diff --git a/internal/filestore/filestore_test.go b/internal/filestore/filestore_test.go index df42099..91996bb 100644 --- a/internal/filestore/filestore_test.go +++ b/internal/filestore/filestore_test.go @@ -34,7 +34,22 @@ func testInvite(t *testing.T, n int, expires time.Time) account.Invite { return inv } -func open(t *testing.T, dir string) *Store { +func must[T any](v T, err error) T { + if err != nil { + panic(err) + } + return v +} + +func testConnection(refresh string) account.Connection { + return must(account.NewConnection( + must(account.NewToken("a", refresh, time.Date(2026, 11, 22, 13, 0, 0, 0, time.UTC))), + must(account.NewSpotifyAccount("jan", "Jan")), + time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC), + )) +} + +func open(t *testing.T, dir string) Store { t.Helper() s, err := Open(dir) if err != nil { @@ -50,11 +65,7 @@ func TestConnectionRoundTrip(t *testing.T) { if _, err := s.Connection(ctx, profile); !errors.Is(err, account.ErrNotFound) { t.Fatalf("empty store: %v", err) } - want := account.Connection{ - Token: account.Token{AccessToken: "a", RefreshToken: "r", Expiry: time.Date(2026, 11, 22, 13, 0, 0, 0, time.UTC)}, - Account: account.SpotifyAccount{ID: "jan", DisplayName: "Jan"}, - ConnectedAt: time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC), - } + want := testConnection("r") if err := s.SaveConnection(ctx, profile, want); err != nil { t.Fatal(err) } @@ -64,8 +75,13 @@ func TestConnectionRoundTrip(t *testing.T) { } // A second store on the same dir, as after a pod restart, sees it. got, err := open(t, dir).Connection(ctx, profile) - if err != nil || got != want { - t.Fatalf("got %+v %v, want %+v", got, err, want) + if err != nil { + t.Fatal(err) + } + gt, wt := got.Token(), want.Token() + if gt.AccessToken() != wt.AccessToken() || gt.RefreshToken() != wt.RefreshToken() || !gt.Expiry().Equal(wt.Expiry()) || + got.Account().ID() != "jan" || got.Account().DisplayName() != "Jan" || !got.ConnectedAt().Equal(want.ConnectedAt()) { + t.Fatalf("round trip changed the connection: %v %v %v", gt.Expiry(), got.Account().Name(), got.ConnectedAt()) } for range 2 { if err := s.DeleteConnection(ctx, profile); err != nil { @@ -77,29 +93,40 @@ func TestConnectionRoundTrip(t *testing.T) { func TestUpdateConnection(t *testing.T) { ctx := context.Background() s := open(t, t.TempDir()) - noop := func(*account.Connection) error { return nil } + noop := func(c account.Connection) (account.Connection, error) { return c, nil } if err := s.UpdateConnection(ctx, profile, noop); !errors.Is(err, account.ErrNotFound) { t.Fatalf("missing: %v", err) } - _ = s.SaveConnection(ctx, profile, account.Connection{Token: account.Token{RefreshToken: "r1"}}) + _ = s.SaveConnection(ctx, profile, testConnection("r1")) boom := errors.New("boom") - err := s.UpdateConnection(ctx, profile, func(c *account.Connection) error { - c.Token.RefreshToken = "lost" - return boom + err := s.UpdateConnection(ctx, profile, func(account.Connection) (account.Connection, error) { + return testConnection("lost"), boom }) if !errors.Is(err, boom) { t.Fatalf("fn error: %v", err) } - if c, _ := s.Connection(ctx, profile); c.Token.RefreshToken != "r1" { + if c, _ := s.Connection(ctx, profile); c.Token().RefreshToken() != "r1" { t.Fatalf("failed update was written: %+v", c) } } -func TestRejectsBadProfile(t *testing.T) { - s := open(t, t.TempDir()) - if err := s.SaveConnection(context.Background(), nil, account.Connection{}); err == nil { +func TestRejectsBadInput(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + s := open(t, dir) + if err := s.SaveConnection(ctx, nil, testConnection("r")); err == nil { t.Fatal("nil profile accepted") } + if err := s.SaveConnection(ctx, profile, nil); err == nil { + t.Fatal("nil connection accepted") + } + // A damaged file is an error, not a half-empty connection. + if err := os.WriteFile(filepath.Join(dir, "tokens", "default.json"), []byte(`{"refresh_token":"r"}`), 0o600); err != nil { + t.Fatal(err) + } + if _, err := s.Connection(ctx, profile); err == nil || errors.Is(err, account.ErrNotFound) { + t.Fatalf("file without account: %v", err) + } } func TestInviteTakenOnce(t *testing.T) { diff --git a/internal/mcpserver/mcpserver.go b/internal/mcpserver/mcpserver.go index cc6c4b2..65b3b4e 100644 --- a/internal/mcpserver/mcpserver.go +++ b/internal/mcpserver/mcpserver.go @@ -15,17 +15,18 @@ import ( "github.com/subpathdev/spotify-mcp/internal/playback" ) -// Player is what the tools need; *playback.Service implements it. +// Player is what the tools need; playback.Service implements it. Methods +// return a nil Device when they acted on the active device. type Player interface { Devices(ctx context.Context) ([]playback.Device, error) - NowPlaying(ctx context.Context) (*playback.State, error) + NowPlaying(ctx context.Context) (playback.State, error) Search(ctx context.Context, query string, kind playback.Kind, limit int) ([]playback.Item, error) - Play(ctx context.Context, selector string, uri playback.URI) (*playback.Device, error) - PlayFirst(ctx context.Context, selector, query string, kind playback.Kind) (playback.Item, *playback.Device, error) - Resume(ctx context.Context, selector string) (*playback.Device, error) - Pause(ctx context.Context, selector string) (*playback.Device, error) - Next(ctx context.Context, selector string) (*playback.Device, error) - Previous(ctx context.Context, selector string) (*playback.Device, error) + Play(ctx context.Context, selector string, uri playback.URI) (playback.Device, error) + PlayFirst(ctx context.Context, selector, query string, kind playback.Kind) (playback.Item, playback.Device, error) + Resume(ctx context.Context, selector string) (playback.Device, error) + Pause(ctx context.Context, selector string) (playback.Device, error) + Next(ctx context.Context, selector string) (playback.Device, error) + Previous(ctx context.Context, selector string) (playback.Device, error) Transfer(ctx context.Context, selector string, play bool) (playback.Device, error) } @@ -123,18 +124,19 @@ func (t tools) nowPlaying(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) if err != nil { return nil, nil, err } - if st == nil || st.Item == nil { + if st == nil || st.Item() == nil { return text("Nothing is playing on Spotify right now."), nil, nil } state := "Paused" - if st.Playing { + if st.Playing() { state = "Playing" } dev := "unknown device" - if st.Device != nil { - dev = st.Device.Name + if st.Device() != nil { + dev = st.Device().Name() } - return text(fmt.Sprintf("%s on %s: %s [%s / %s]", state, dev, formatItem(*st.Item), mmss(st.Progress), mmss(st.Item.Duration))), nil, nil + it := st.Item() + return text(fmt.Sprintf("%s on %s: %s [%s / %s]", state, dev, formatItem(it), mmss(st.Progress()), mmss(it.Duration()))), nil, nil } func (t tools) search(ctx context.Context, _ *mcp.CallToolRequest, in searchArgs) (*mcp.CallToolResult, any, error) { @@ -208,22 +210,25 @@ func (t tools) transfer(ctx context.Context, _ *mcp.CallToolRequest, in transfer if err != nil { return nil, nil, err } - return text("Moved playback to " + dev.Name + "."), nil, nil + if dev == nil { + return text("Moved playback."), nil, nil + } + return text("Moved playback to " + dev.Name() + "."), nil, nil } // done turns the result of a simple command into a tool result. -func done(dev *playback.Device, err error, msg string) (*mcp.CallToolResult, any, error) { +func done(dev playback.Device, err error, msg string) (*mcp.CallToolResult, any, error) { if err != nil { return nil, nil, err } return text(msg + on(dev) + "."), nil, nil } -func on(dev *playback.Device) string { +func on(dev playback.Device) string { if dev == nil { return "" } - return " on " + dev.Name + return " on " + dev.Name() } func text(s string) *mcp.CallToolResult { @@ -231,28 +236,32 @@ func text(s string) *mcp.CallToolResult { } func formatDevice(d playback.Device) string { - s := fmt.Sprintf("%s (%s, id %s)", d.Name, d.Type, d.ID) - if d.Active { + id := "none" + if d.ID() != nil { + id = d.ID().String() + } + s := fmt.Sprintf("%s (%s, id %s)", d.Name(), d.Type(), id) + if d.Active() { s += " [active]" } - if d.Restricted { + if d.Restricted() || d.ID() == nil { s += " [can't be controlled]" } return s } func formatItem(it playback.Item) string { - s := it.Name - if len(it.Artists) > 0 { - s += " by " + strings.Join(it.Artists, ", ") + s := it.Name() + if artists := it.Artists(); len(artists) > 0 { + s += " by " + strings.Join(artists, ", ") } - if it.Album != "" && it.Kind != playback.KindAlbum { - s += " (" + it.Album + ")" + if it.Album() != "" && it.Kind() != playback.KindAlbum() { + s += " (" + it.Album() + ")" } - if it.Owner != "" { - s += " (by " + it.Owner + ")" + if it.Owner() != "" { + s += " (by " + it.Owner() + ")" } - return s + " - " + it.URI.String() + return s + " - " + it.URI().String() } func mmss(d time.Duration) string { diff --git a/internal/mcpserver/mcpserver_test.go b/internal/mcpserver/mcpserver_test.go index 9f1d452..818611d 100644 --- a/internal/mcpserver/mcpserver_test.go +++ b/internal/mcpserver/mcpserver_test.go @@ -19,9 +19,17 @@ type fakePlayer struct { err error } +func must[T any](v T, err error) T { + if err != nil { + panic(err) + } + return v +} + var ( - pixel = playback.Device{ID: "ph1", Name: "Jan's Pixel 8", Type: "Smartphone", Active: true} - song = playback.Item{Kind: playback.KindTrack, Name: "Song", Artists: []string{"Band"}, Album: "LP", Duration: 3 * time.Minute} + pixel = playback.NewDevice(must(playback.ParseDeviceID("ph1")), "Jan's Pixel 8", "Smartphone", true, false) + song = must(playback.NewItem(must(playback.ParseURI("spotify:track:s1")), "Song", + playback.WithArtists("Band"), playback.WithAlbum("LP"), playback.WithDuration(3*time.Minute))) ) func (f *fakePlayer) record(s string) { f.calls = append(f.calls, s) } @@ -29,34 +37,34 @@ func (f *fakePlayer) record(s string) { f.calls = append(f.calls, s) } func (f *fakePlayer) Devices(context.Context) ([]playback.Device, error) { return []playback.Device{pixel}, nil } -func (f *fakePlayer) NowPlaying(context.Context) (*playback.State, error) { - return &playback.State{Playing: true, Device: &pixel, Item: &song, Progress: 61 * time.Second}, nil +func (f *fakePlayer) NowPlaying(context.Context) (playback.State, error) { + return playback.NewState(true, 61*time.Second, pixel, song), nil } func (f *fakePlayer) Search(_ context.Context, q string, k playback.Kind, limit int) ([]playback.Item, error) { - f.record("search " + q + " " + string(k)) + f.record("search " + q + " " + k.String()) return []playback.Item{song}, nil } -func (f *fakePlayer) Play(_ context.Context, sel string, u playback.URI) (*playback.Device, error) { +func (f *fakePlayer) Play(_ context.Context, sel string, u playback.URI) (playback.Device, error) { f.record("play " + sel + " " + u.String()) - return &pixel, f.err + return pixel, f.err } -func (f *fakePlayer) PlayFirst(_ context.Context, sel, q string, k playback.Kind) (playback.Item, *playback.Device, error) { - f.record("playfirst " + sel + " " + q + " " + string(k)) +func (f *fakePlayer) PlayFirst(_ context.Context, sel, q string, k playback.Kind) (playback.Item, playback.Device, error) { + f.record("playfirst " + sel + " " + q + " " + k.String()) return song, nil, f.err } -func (f *fakePlayer) Resume(_ context.Context, sel string) (*playback.Device, error) { +func (f *fakePlayer) Resume(_ context.Context, sel string) (playback.Device, error) { f.record("resume " + sel) return nil, f.err } -func (f *fakePlayer) Pause(_ context.Context, sel string) (*playback.Device, error) { +func (f *fakePlayer) Pause(_ context.Context, sel string) (playback.Device, error) { f.record("pause " + sel) return nil, f.err } -func (f *fakePlayer) Next(_ context.Context, sel string) (*playback.Device, error) { +func (f *fakePlayer) Next(_ context.Context, sel string) (playback.Device, error) { f.record("next " + sel) return nil, f.err } -func (f *fakePlayer) Previous(_ context.Context, sel string) (*playback.Device, error) { +func (f *fakePlayer) Previous(_ context.Context, sel string) (playback.Device, error) { f.record("previous " + sel) return nil, f.err } diff --git a/internal/playback/playback.go b/internal/playback/playback.go index e81ca84..8ecf827 100644 --- a/internal/playback/playback.go +++ b/internal/playback/playback.go @@ -13,109 +13,227 @@ import ( "time" ) -// Kind is the type of a Spotify item. -type Kind string +// The value types below (Kind, URI, DeviceID) are interfaces with an +// unexported marker method, so only this package implements them and every +// value went through one of its constructors. Their implementations are small +// comparable structs: two values are equal with == exactly when they hold the +// same text. + +// Kind is the type of a Spotify item. Get one from ParseKind, Kinds or the +// Kind* functions. +type Kind interface { + String() string + // IsContext reports whether items of this kind play as a context (a list + // Spotify continues through) rather than on their own. + IsContext() bool + isKind() +} + +type kind struct{ s string } + +func (k kind) String() string { return k.s } +func (k kind) IsContext() bool { return k.s != "track" && k.s != "episode" } +func (kind) isKind() {} // The kinds this server can search for and play. -const ( - KindTrack Kind = "track" - KindAlbum Kind = "album" - KindArtist Kind = "artist" - KindPlaylist Kind = "playlist" - KindShow Kind = "show" - KindEpisode Kind = "episode" -) +func KindTrack() Kind { return kind{"track"} } +func KindAlbum() Kind { return kind{"album"} } +func KindArtist() Kind { return kind{"artist"} } +func KindPlaylist() Kind { return kind{"playlist"} } +func KindShow() Kind { return kind{"show"} } +func KindEpisode() Kind { return kind{"episode"} } // Kinds lists every Kind, in the order shown to people. -var Kinds = []Kind{KindTrack, KindAlbum, KindArtist, KindPlaylist, KindShow, KindEpisode} +func Kinds() []Kind { + return []Kind{KindTrack(), KindAlbum(), KindArtist(), KindPlaylist(), KindShow(), KindEpisode()} +} // ParseKind checks a kind name. An empty name means KindTrack. func ParseKind(s string) (Kind, error) { if s == "" { - return KindTrack, nil + return KindTrack(), nil } - for _, k := range Kinds { - if string(k) == s { + kinds := Kinds() + names := make([]string, len(kinds)) + for i, k := range kinds { + if k.String() == s { return k, nil } + names[i] = k.String() } - names := make([]string, len(Kinds)) - for i, k := range Kinds { - names[i] = string(k) - } - return "", fmt.Errorf("unknown type %q (use one of %s)", s, strings.Join(names, ", ")) + return nil, fmt.Errorf("unknown type %q (use one of %s)", s, strings.Join(names, ", ")) } -// IsContext reports whether items of this kind play as a context (a list -// Spotify continues through) rather than on their own. -func (k Kind) IsContext() bool { return k != KindTrack && k != KindEpisode } +// URI is a parsed spotify:: URI. Get one from ParseURI. +type URI interface { + // Kind of the URI's item. + Kind() Kind + String() string + isURI() +} -// URI is a parsed spotify:: URI. The zero URI is not valid. -type URI struct { +type uri struct { kind Kind id string } +func (u uri) Kind() Kind { return u.kind } +func (u uri) String() string { return "spotify:" + u.kind.String() + ":" + u.id } +func (uri) isURI() {} + // ParseURI parses a spotify:: URI. func ParseURI(s string) (URI, error) { parts := strings.Split(strings.TrimSpace(s), ":") if len(parts) != 3 || parts[0] != "spotify" || parts[2] == "" { - return URI{}, fmt.Errorf("%q is not a Spotify URI like spotify:track:", s) + return nil, fmt.Errorf("%q is not a Spotify URI like spotify:track:", s) + } + if parts[1] == "" { + return nil, fmt.Errorf("unsupported Spotify URI type %q", parts[1]) } k, err := ParseKind(parts[1]) - if err != nil || parts[1] == "" { - return URI{}, fmt.Errorf("unsupported Spotify URI type %q", parts[1]) + if err != nil { + return nil, fmt.Errorf("unsupported Spotify URI type %q", parts[1]) } - return URI{kind: k, id: parts[2]}, nil + return uri{kind: k, id: parts[2]}, nil } -// Kind of the URI's item. -func (u URI) Kind() Kind { return u.kind } +// DeviceID is Spotify's ID of a Connect device. Get one from ParseDeviceID. +// A nil DeviceID means the active device. +type DeviceID interface { + String() string + isDeviceID() +} + +type deviceID struct{ s string } -// IsZero reports whether u is the zero URI. -func (u URI) IsZero() bool { return u.id == "" } +func (d deviceID) String() string { return d.s } +func (deviceID) isDeviceID() {} -func (u URI) String() string { - if u.IsZero() { - return "" +// ParseDeviceID checks a device ID. +func ParseDeviceID(s string) (DeviceID, error) { + if strings.TrimSpace(s) == "" || strings.ContainsAny(s, " \t\r\n") { + return nil, fmt.Errorf("invalid device ID %q", s) } - return "spotify:" + string(u.kind) + ":" + u.id + return deviceID{s: s}, nil } -// DeviceID is Spotify's ID of a Connect device. -type DeviceID string - -// Device is a Spotify Connect device. -type Device struct { - ID DeviceID - Name string +// Device is a Spotify Connect device. Get one from NewDevice. +type Device interface { + // ID is nil for devices Spotify gives no ID; they can't be addressed. + ID() DeviceID + Name() string // Type is Spotify's device type, e.g. "Computer" or "Smartphone". - Type string - Active bool + Type() string + Active() bool // Restricted devices don't accept commands from the Web API. - Restricted bool + Restricted() bool +} + +type device struct { + id DeviceID + name, typ string + active, restricted bool } -// Item is a search result or the playing item. -type Item struct { - Kind Kind - Name string - URI URI - Artists []string +// NewDevice builds a Device; id may be nil. +func NewDevice(id DeviceID, name, typ string, active, restricted bool) Device { + return &device{id: id, name: name, typ: typ, active: active, restricted: restricted} +} + +func (d *device) ID() DeviceID { return d.id } +func (d *device) Name() string { return d.name } +func (d *device) Type() string { return d.typ } +func (d *device) Active() bool { return d.active } +func (d *device) Restricted() bool { return d.restricted } + +// Item is a search result or the playing item. Get one from NewItem. +type Item interface { + Kind() Kind + Name() string + URI() URI + Artists() []string // Album is the album of a track, or the show of an episode. - Album string - Owner string // of a playlist - Duration time.Duration + Album() string + // Owner is the owner of a playlist. + Owner() string + Duration() time.Duration } -// State is what is playing right now. -type State struct { - Playing bool - Device *Device // nil if Spotify doesn't say - Item *Item // nil between items or for unsupported types - Progress time.Duration +type item struct { + name string + uri URI + artists []string + album, owner string + duration time.Duration } +// ItemOption sets an optional part of an Item. +type ItemOption func(*item) + +// WithArtists sets the artists of a track or album. +func WithArtists(names ...string) ItemOption { + return func(it *item) { it.artists = append([]string(nil), names...) } +} + +// WithAlbum sets the album of a track, or the show of an episode. +func WithAlbum(name string) ItemOption { return func(it *item) { it.album = name } } + +// WithOwner sets the owner of a playlist. +func WithOwner(name string) ItemOption { return func(it *item) { it.owner = name } } + +// WithDuration sets the length of a track or episode. +func WithDuration(d time.Duration) ItemOption { return func(it *item) { it.duration = d } } + +// NewItem builds an Item; its kind comes from uri, which is required. +func NewItem(u URI, name string, opts ...ItemOption) (Item, error) { + if u == nil { + return nil, errors.New("item has no URI") + } + it := &item{name: name, uri: u} + for _, o := range opts { + o(it) + } + if it.duration < 0 { + return nil, fmt.Errorf("item %s has a negative duration", u) + } + return it, nil +} + +func (it *item) Kind() Kind { return it.uri.Kind() } +func (it *item) Name() string { return it.name } +func (it *item) URI() URI { return it.uri } +func (it *item) Artists() []string { return append([]string(nil), it.artists...) } +func (it *item) Album() string { return it.album } +func (it *item) Owner() string { return it.owner } +func (it *item) Duration() time.Duration { return it.duration } + +// State is what is playing right now. Get one from NewState. +type State interface { + Playing() bool + // Device is nil if Spotify doesn't say. + Device() Device + // Item is nil between items or for unsupported types. + Item() Item + Progress() time.Duration +} + +type state struct { + playing bool + device Device + item Item + progress time.Duration +} + +// NewState builds a State; dev and it may be nil. +func NewState(playing bool, progress time.Duration, dev Device, it Item) State { + return &state{playing: playing, progress: progress, device: dev, item: it} +} + +func (s *state) Playing() bool { return s.playing } +func (s *state) Device() Device { return s.device } +func (s *state) Item() Item { return s.item } +func (s *state) Progress() time.Duration { return s.progress } + // MaxSearchResults is the most results Spotify returns per search for apps in // development mode (February 2026 rules). const MaxSearchResults = 10 @@ -133,7 +251,7 @@ type Spotify interface { Devices(ctx context.Context) ([]Device, error) // Search returns up to limit (1..MaxSearchResults) items of one kind. Search(ctx context.Context, query string, kind Kind, limit int) ([]Item, error) - // Play plays uri; an empty device means the active one. + // Play plays uri; a nil device means the active one. Play(ctx context.Context, device DeviceID, uri URI) error Resume(ctx context.Context, device DeviceID) error Pause(ctx context.Context, device DeviceID) error @@ -141,5 +259,5 @@ type Spotify interface { Previous(ctx context.Context, device DeviceID) error Transfer(ctx context.Context, device DeviceID, play bool) error // State returns nil when nothing is playing on any device. - State(ctx context.Context) (*State, error) + State(ctx context.Context) (State, error) } diff --git a/internal/playback/playback_test.go b/internal/playback/playback_test.go index c4c0216..0a2f2ac 100644 --- a/internal/playback/playback_test.go +++ b/internal/playback/playback_test.go @@ -16,12 +16,16 @@ type fakeSpotify struct { func (f *fakeSpotify) Devices(context.Context) ([]Device, error) { return f.devices, nil } func (f *fakeSpotify) Search(_ context.Context, q string, k Kind, limit int) ([]Item, error) { - f.calls = append(f.calls, "search "+q+" "+string(k)) + f.calls = append(f.calls, "search "+q+" "+k.String()) return f.results[:min(limit, len(f.results))], nil } func (f *fakeSpotify) cmd(name string, id DeviceID) error { - f.calls = append(f.calls, name+" "+string(id)) - if f.noActive && id == "" { + s := "" + if id != nil { + s = id.String() + } + f.calls = append(f.calls, name+" "+s) + if f.noActive && id == nil { return ErrNoActiveDevice } return nil @@ -36,16 +40,27 @@ func (f *fakeSpotify) Previous(_ context.Context, id DeviceID) error { return f. func (f *fakeSpotify) Transfer(_ context.Context, id DeviceID, _ bool) error { return f.cmd("transfer", id) } -func (f *fakeSpotify) State(context.Context) (*State, error) { return nil, nil } +func (f *fakeSpotify) State(context.Context) (State, error) { return nil, nil } func (f *fakeSpotify) lastCall() string { return f.calls[len(f.calls)-1] } +func must[T any](v T, err error) T { + if err != nil { + panic(err) + } + return v +} + +func dev(id, name, typ string) Device { + return NewDevice(must(ParseDeviceID(id)), name, typ, false, false) +} + func devices() []Device { return []Device{ - {ID: "pc1", Name: "mobile", Type: "Computer"}, - {ID: "ph1", Name: "Jan's Pixel 8", Type: "Smartphone"}, - {ID: "sp1", Name: "Kitchen speaker", Type: "Speaker"}, - {ID: "sp2", Name: "Bath speaker", Type: "Speaker"}, + dev("pc1", "mobile", "Computer"), + dev("ph1", "Jan's Pixel 8", "Smartphone"), + dev("sp1", "Kitchen speaker", "Speaker"), + dev("sp2", "Bath speaker", "Speaker"), } } @@ -53,13 +68,13 @@ func TestResolveDevice(t *testing.T) { ctx := context.Background() f := &fakeSpotify{devices: devices()} s := NewService(f) - for selector, want := range map[string]DeviceID{ + for selector, want := range map[string]string{ "ph1": "ph1", "MOBILE": "pc1", "pixel": "ph1", "smartphone": "ph1", "kitchen": "sp1", "": "", } { if _, err := s.Pause(ctx, selector); err != nil { t.Fatalf("%q: %v", selector, err) } - if got := f.lastCall(); got != "pause "+string(want) { + if got := f.lastCall(); got != "pause "+want { t.Errorf("%q: called %q", selector, got) } } @@ -81,14 +96,14 @@ func TestNoActiveDeviceListsDevices(t *testing.T) { } func TestPlayFirst(t *testing.T) { - uri, _ := ParseURI("spotify:track:1") - f := &fakeSpotify{devices: devices(), results: []Item{{Kind: KindTrack, Name: "Song", URI: uri}}} - item, dev, err := NewService(f).PlayFirst(context.Background(), "pixel", "song", KindTrack) - if err != nil || item.Name != "Song" || dev.ID != "ph1" || f.lastCall() != "play spotify:track:1 ph1" { - t.Fatalf("%+v %+v %v %v", item, dev, err, f.calls) + song := must(NewItem(must(ParseURI("spotify:track:1")), "Song")) + f := &fakeSpotify{devices: devices(), results: []Item{song}} + item, d, err := NewService(f).PlayFirst(context.Background(), "pixel", "song", KindTrack()) + if err != nil || item.Name() != "Song" || item.Kind() != KindTrack() || d.ID().String() != "ph1" || f.lastCall() != "play spotify:track:1 ph1" { + t.Fatalf("%v %v %v %v", item, d, err, f.calls) } f.results = nil - if _, _, err := NewService(f).PlayFirst(context.Background(), "", "nothing", KindTrack); err == nil { + if _, _, err := NewService(f).PlayFirst(context.Background(), "", "nothing", KindTrack()); err == nil { t.Fatal("empty search played something") } } @@ -98,14 +113,14 @@ func TestTransferNeedsDevice(t *testing.T) { if _, err := s.Transfer(context.Background(), " ", true); err == nil { t.Fatal("transfer without device accepted") } - if d, err := s.Transfer(context.Background(), "pixel", true); err != nil || d.ID != "ph1" { + if d, err := s.Transfer(context.Background(), "pixel", true); err != nil || d.ID().String() != "ph1" { t.Fatalf("%+v %v", d, err) } } func TestParseURI(t *testing.T) { u, err := ParseURI(" spotify:album:abc ") - if err != nil || u.Kind() != KindAlbum || u.String() != "spotify:album:abc" || !u.Kind().IsContext() { + if err != nil || u.Kind() != KindAlbum() || u.String() != "spotify:album:abc" || !u.Kind().IsContext() { t.Fatalf("%v %v", u, err) } for _, s := range []string{"", "spotify:track:", "spotify::1", "spotify:local:1", "https://open.spotify.com/track/1", "spotify:track:1:2"} { @@ -119,12 +134,50 @@ func TestSearchLimits(t *testing.T) { f := &fakeSpotify{results: make([]Item, 20)} s := NewService(f) for limit, want := range map[int]int{0: 5, 3: 3, 50: MaxSearchResults} { - items, err := s.Search(context.Background(), "x", KindTrack, limit) + items, err := s.Search(context.Background(), "x", KindTrack(), limit) if err != nil || len(items) != want { t.Errorf("limit %d: %d items, %v", limit, len(items), err) } } - if _, err := s.Search(context.Background(), " ", KindTrack, 1); err == nil { + if _, err := s.Search(context.Background(), " ", KindTrack(), 1); err == nil { t.Error("empty query accepted") } } + +func TestValues(t *testing.T) { + if k, err := ParseKind(""); err != nil || k != KindTrack() { + t.Fatalf("default kind: %v %v", k, err) + } + if _, err := ParseKind("podcast"); err == nil { + t.Fatal("unknown kind accepted") + } + // Kinds returns a copy: changing it doesn't change the next call. + ks := Kinds() + ks[0] = KindShow() + if Kinds()[0] != KindTrack() { + t.Fatal("Kinds shared its slice") + } + if must(ParseURI("spotify:track:1")) != must(ParseURI("spotify:track:1")) { + t.Fatal("equal URIs compare unequal") + } + for _, s := range []string{"", " ", "a b"} { + if _, err := ParseDeviceID(s); err == nil { + t.Errorf("device ID %q accepted", s) + } + } + if _, err := NewItem(nil, "x"); err == nil { + t.Fatal("item without URI accepted") + } + it := must(NewItem(must(ParseURI("spotify:track:1")), "x", WithArtists("a", "b"))) + it.Artists()[0] = "changed" + if it.Artists()[0] != "a" { + t.Fatal("Artists shared its slice") + } +} + +func TestDeviceWithoutID(t *testing.T) { + f := &fakeSpotify{devices: []Device{NewDevice(nil, "Web Player", "Computer", false, false)}} + if _, err := NewService(f).Pause(context.Background(), "web player"); err == nil || !strings.Contains(err.Error(), "no ID") { + t.Fatalf("device without ID: %v", err) + } +} diff --git a/internal/playback/service.go b/internal/playback/service.go index 8f0490d..4fc84ad 100644 --- a/internal/playback/service.go +++ b/internal/playback/service.go @@ -9,13 +9,37 @@ import ( // Service controls playback. Devices are chosen by a selector: a device ID, // a name, a unique part of a name, or a device type ("smartphone"). An empty -// selector means the active device. -type Service struct { +// selector means the active device; methods then return a nil Device. +type Service interface { + // Devices lists the devices Spotify currently sees. + Devices(ctx context.Context) ([]Device, error) + // NowPlaying returns the playback state, or nil when nothing is playing. + NowPlaying(ctx context.Context) (State, error) + // Search returns up to limit items; limit 0 means a default of 5, and + // more than MaxSearchResults is capped. + Search(ctx context.Context, query string, kind Kind, limit int) ([]Item, error) + // Play plays uri on the selected device. + Play(ctx context.Context, selector string, uri URI) (Device, error) + // PlayFirst plays the first search result for query. + PlayFirst(ctx context.Context, selector, query string, kind Kind) (Item, Device, error) + // Resume continues playback. + Resume(ctx context.Context, selector string) (Device, error) + // Pause pauses playback. + Pause(ctx context.Context, selector string) (Device, error) + // Next skips to the next item. + Next(ctx context.Context, selector string) (Device, error) + // Previous goes back to the previous item. + Previous(ctx context.Context, selector string) (Device, error) + // Transfer moves playback to the selected device, which is required. + Transfer(ctx context.Context, selector string, play bool) (Device, error) +} + +type service struct { spotify Spotify } // NewService returns a Service using sp. -func NewService(sp Spotify) *Service { return &Service{spotify: sp} } +func NewService(sp Spotify) Service { return &service{spotify: sp} } // NoActiveDeviceError is returned when Spotify sees no active device. It lists // the devices that could be passed instead. It matches ErrNoActiveDevice. @@ -56,27 +80,23 @@ func (e *DeviceNotFoundError) Error() string { func quotedNames(devs []Device, withType bool) string { names := make([]string, len(devs)) for i, d := range devs { - names[i] = fmt.Sprintf("%q", d.Name) + names[i] = fmt.Sprintf("%q", d.Name()) if withType { - names[i] += " (" + d.Type + ")" + names[i] += " (" + d.Type() + ")" } } return strings.Join(names, ", ") } -// Devices lists the devices Spotify currently sees. -func (s *Service) Devices(ctx context.Context) ([]Device, error) { +func (s *service) Devices(ctx context.Context) ([]Device, error) { return s.spotify.Devices(ctx) } -// NowPlaying returns the playback state, or nil when nothing is playing. -func (s *Service) NowPlaying(ctx context.Context) (*State, error) { +func (s *service) NowPlaying(ctx context.Context) (State, error) { return s.spotify.State(ctx) } -// Search returns up to limit items; limit 0 means a default of 5, and more -// than MaxSearchResults is capped. -func (s *Service) Search(ctx context.Context, query string, kind Kind, limit int) ([]Item, error) { +func (s *service) Search(ctx context.Context, query string, kind Kind, limit int) ([]Item, error) { query = strings.TrimSpace(query) if query == "" { return nil, errors.New("search query is empty") @@ -90,70 +110,60 @@ func (s *Service) Search(ctx context.Context, query string, kind Kind, limit int return s.spotify.Search(ctx, query, kind, limit) } -// Play plays uri on the selected device and returns the device (nil for the -// active one). -func (s *Service) Play(ctx context.Context, selector string, uri URI) (*Device, error) { - if uri.IsZero() { +func (s *service) Play(ctx context.Context, selector string, uri URI) (Device, error) { + if uri == nil { return nil, errors.New("no URI to play") } return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Play(ctx, id, uri) }) } -// PlayFirst plays the first search result for query. -func (s *Service) PlayFirst(ctx context.Context, selector, query string, kind Kind) (Item, *Device, error) { +func (s *service) PlayFirst(ctx context.Context, selector, query string, kind Kind) (Item, Device, error) { items, err := s.Search(ctx, query, kind, 1) if err != nil { - return Item{}, nil, err + return nil, nil, err } if len(items) == 0 { - return Item{}, nil, fmt.Errorf("nothing found for %q", query) + return nil, nil, fmt.Errorf("nothing found for %q", query) } - dev, err := s.Play(ctx, selector, items[0].URI) + dev, err := s.Play(ctx, selector, items[0].URI()) return items[0], dev, err } -// Resume continues playback. -func (s *Service) Resume(ctx context.Context, selector string) (*Device, error) { +func (s *service) Resume(ctx context.Context, selector string) (Device, error) { return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Resume(ctx, id) }) } -// Pause pauses playback. -func (s *Service) Pause(ctx context.Context, selector string) (*Device, error) { +func (s *service) Pause(ctx context.Context, selector string) (Device, error) { return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Pause(ctx, id) }) } -// Next skips to the next item. -func (s *Service) Next(ctx context.Context, selector string) (*Device, error) { +func (s *service) Next(ctx context.Context, selector string) (Device, error) { return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Next(ctx, id) }) } -// Previous goes back to the previous item. -func (s *Service) Previous(ctx context.Context, selector string) (*Device, error) { +func (s *service) Previous(ctx context.Context, selector string) (Device, error) { return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Previous(ctx, id) }) } -// Transfer moves playback to the selected device, which is required here. -func (s *Service) Transfer(ctx context.Context, selector string, play bool) (Device, error) { +func (s *service) Transfer(ctx context.Context, selector string, play bool) (Device, error) { if strings.TrimSpace(selector) == "" { - return Device{}, errors.New("a device is required; call the devices tool to see the names") + return nil, errors.New("a device is required; call the devices tool to see the names") } - dev, err := s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Transfer(ctx, id, play) }) - if err != nil { - return Device{}, err - } - return *dev, nil + return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Transfer(ctx, id, play) }) } // control resolves the selector, runs cmd on the device and explains a // missing active device. -func (s *Service) control(ctx context.Context, selector string, cmd func(DeviceID) error) (*Device, error) { +func (s *service) control(ctx context.Context, selector string, cmd func(DeviceID) error) (Device, error) { dev, err := s.resolve(ctx, selector) if err != nil { return nil, err } - var id DeviceID + var id DeviceID // nil: the active device if dev != nil { - id = dev.ID + if id = dev.ID(); id == nil { + return nil, fmt.Errorf("the device %q has no ID and can't be controlled", dev.Name()) + } } if err := cmd(id); err != nil { if errors.Is(err, ErrNoActiveDevice) { @@ -168,7 +178,7 @@ func (s *Service) control(ctx context.Context, selector string, cmd func(DeviceI // resolve finds the device a selector means: exact ID, then exact name // (ignoring case), then a single device whose name contains the selector or // whose type equals it. An empty selector returns nil, the active device. -func (s *Service) resolve(ctx context.Context, selector string) (*Device, error) { +func (s *service) resolve(ctx context.Context, selector string) (Device, error) { selector = strings.TrimSpace(selector) if selector == "" { return nil, nil @@ -178,19 +188,19 @@ func (s *Service) resolve(ctx context.Context, selector string) (*Device, error) return nil, err } for _, d := range devs { - if string(d.ID) == selector || strings.EqualFold(d.Name, selector) { - return &d, nil + if (d.ID() != nil && d.ID().String() == selector) || strings.EqualFold(d.Name(), selector) { + return d, nil } } var matches []Device lower := strings.ToLower(selector) for _, d := range devs { - if strings.Contains(strings.ToLower(d.Name), lower) || strings.EqualFold(d.Type, selector) { + if strings.Contains(strings.ToLower(d.Name()), lower) || strings.EqualFold(d.Type(), selector) { matches = append(matches, d) } } if len(matches) == 1 { - return &matches[0], nil + return matches[0], nil } return nil, &DeviceNotFoundError{Selector: selector, Online: devs, Ambiguous: len(matches) > 1} } diff --git a/internal/spotify/api.go b/internal/spotify/api.go index 46b508f..fd6781e 100644 --- a/internal/spotify/api.go +++ b/internal/spotify/api.go @@ -16,6 +16,7 @@ import ( "strings" "time" + "github.com/subpathdev/spotify-mcp/internal/account" "github.com/subpathdev/spotify-mcp/internal/playback" ) @@ -24,19 +25,26 @@ const DefaultAPIURL = "https://api.spotify.com/v1" const maxBody = 4 << 20 -// API sends requests to the Web API with a given access token. -type API struct { +// API sends requests to the Web API with a given access token. It tells +// whose a token is (account.Identity); NewPlayer uses it for playback. Only +// this package implements it. +type API interface { + account.Identity + do(ctx context.Context, token string, req request) (int, error) +} + +type api struct { base string http *http.Client } // NewAPI returns an API for baseURL (DefaultAPIURL in production). httpClient // may be nil. -func NewAPI(baseURL string, httpClient *http.Client) *API { +func NewAPI(baseURL string, httpClient *http.Client) API { if httpClient == nil { httpClient = &http.Client{Timeout: 15 * time.Second} } - return &API{base: strings.TrimRight(baseURL, "/"), http: httpClient} + return &api{base: strings.TrimRight(baseURL, "/"), http: httpClient} } // Error is an error answer from the Web API that has no domain meaning. @@ -71,7 +79,7 @@ type request struct { } // do sends req and returns the HTTP status. A 204 leaves req.out untouched. -func (a *API) do(ctx context.Context, token string, req request) (int, error) { +func (a *api) do(ctx context.Context, token string, req request) (int, error) { u := a.base + req.path if len(req.query) > 0 { u += "?" + req.query.Encode() diff --git a/internal/spotify/auth.go b/internal/spotify/auth.go index 5d38112..4978e63 100644 --- a/internal/spotify/auth.go +++ b/internal/spotify/auth.go @@ -10,20 +10,25 @@ import ( "github.com/subpathdev/spotify-mcp/internal/account" ) -// Scopes the server asks for at login: read and control playback, nothing -// else. No library, playlist or e-mail access. -var Scopes = []string{ - "user-read-playback-state", - "user-modify-playback-state", - "user-read-currently-playing", +// Scopes are what the server asks for at login: read and control playback, +// nothing else. No library, playlist or e-mail access. It returns a new +// slice, so callers can't widen the list. +func Scopes() []string { + return []string{ + "user-read-playback-state", + "user-modify-playback-state", + "user-read-currently-playing", + } } // DefaultEndpoint is Spotify's OAuth endpoint. The client secret goes in the // Authorization header, as Spotify documents. -var DefaultEndpoint = oauth2.Endpoint{ - AuthURL: "https://accounts.spotify.com/authorize", - TokenURL: "https://accounts.spotify.com/api/token", - AuthStyle: oauth2.AuthStyleInHeader, +func DefaultEndpoint() oauth2.Endpoint { + return oauth2.Endpoint{ + AuthURL: "https://accounts.spotify.com/authorize", + TokenURL: "https://accounts.spotify.com/api/token", + AuthStyle: oauth2.AuthStyleInHeader, + } } // OAuthConfig configures OAuth. @@ -31,34 +36,31 @@ type OAuthConfig struct { ClientID string ClientSecret string RedirectURL string - Endpoint oauth2.Endpoint // DefaultEndpoint if empty + Endpoint oauth2.Endpoint // DefaultEndpoint() if empty HTTPClient *http.Client // may be nil } -// OAuth implements account.OAuth. -type OAuth struct { +type oauth struct { cfg oauth2.Config http *http.Client } -var _ account.OAuth = (*OAuth)(nil) - -// NewOAuth returns an OAuth for cfg. -func NewOAuth(cfg OAuthConfig) *OAuth { +// NewOAuth returns Spotify's authorization server as account.OAuth. +func NewOAuth(cfg OAuthConfig) account.OAuth { ep := cfg.Endpoint if ep.TokenURL == "" { - ep = DefaultEndpoint + ep = DefaultEndpoint() } - return &OAuth{ + return &oauth{ cfg: oauth2.Config{ ClientID: cfg.ClientID, ClientSecret: cfg.ClientSecret, RedirectURL: cfg.RedirectURL, - Endpoint: ep, Scopes: Scopes, + Endpoint: ep, Scopes: Scopes(), }, http: cfg.HTTPClient, } } -func (o *OAuth) ctx(ctx context.Context) context.Context { +func (o *oauth) ctx(ctx context.Context) context.Context { if o.http == nil { return ctx } @@ -68,24 +70,24 @@ func (o *OAuth) ctx(ctx context.Context) context.Context { // AuthCodeURL implements account.OAuth. show_dialog makes Spotify always show // its consent page, so someone on a shared browser sees which account they // are about to connect. -func (o *OAuth) AuthCodeURL(state, verifier string) string { +func (o *oauth) AuthCodeURL(state, verifier string) string { return o.cfg.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier), oauth2.SetAuthURLParam("show_dialog", "true")) } // Exchange implements account.OAuth. -func (o *OAuth) Exchange(ctx context.Context, code, verifier string) (account.Token, error) { +func (o *oauth) Exchange(ctx context.Context, code, verifier string) (account.Token, error) { t, err := o.cfg.Exchange(o.ctx(ctx), code, oauth2.VerifierOption(verifier)) if err != nil { - return account.Token{}, mapOAuthError(err) + return nil, mapOAuthError(err) } - return account.Token{AccessToken: t.AccessToken, RefreshToken: t.RefreshToken, Expiry: t.Expiry}, nil + return account.NewToken(t.AccessToken, t.RefreshToken, t.Expiry) } // Refresh implements account.OAuth. -func (o *OAuth) Refresh(ctx context.Context, refreshToken string) (account.Token, error) { +func (o *oauth) Refresh(ctx context.Context, refreshToken string) (account.Token, error) { t, err := o.cfg.TokenSource(o.ctx(ctx), &oauth2.Token{RefreshToken: refreshToken}).Token() if err != nil { - return account.Token{}, mapOAuthError(err) + return nil, mapOAuthError(err) } // oauth2 copies the old refresh token when Spotify sends none; report the // new one only if it changed. @@ -93,7 +95,7 @@ func (o *OAuth) Refresh(ctx context.Context, refreshToken string) (account.Token if rt == refreshToken { rt = "" } - return account.Token{AccessToken: t.AccessToken, RefreshToken: rt, Expiry: t.Expiry}, nil + return account.NewToken(t.AccessToken, rt, t.Expiry) } func mapOAuthError(err error) error { @@ -111,19 +113,17 @@ func mapOAuthError(err error) error { // Account implements account.Identity. Spotify answers 403 for accounts that // aren't on a development-mode app's user list. -func (a *API) Account(ctx context.Context, accessToken string) (account.SpotifyAccount, error) { +func (a *api) Account(ctx context.Context, accessToken string) (account.SpotifyAccount, error) { var out struct { ID string `json:"id"` DisplayName string `json:"display_name"` } status, err := a.do(ctx, accessToken, request{method: http.MethodGet, path: "/me", out: &out}) if status == http.StatusForbidden { - return account.SpotifyAccount{}, account.ErrNotAllowlisted + return nil, account.ErrNotAllowlisted } if err != nil { - return account.SpotifyAccount{}, err + return nil, err } - return account.SpotifyAccount{ID: out.ID, DisplayName: out.DisplayName}, nil + return account.NewSpotifyAccount(out.ID, out.DisplayName) } - -var _ account.Identity = (*API)(nil) diff --git a/internal/spotify/player.go b/internal/spotify/player.go index 11c96b1..40c1c93 100644 --- a/internal/spotify/player.go +++ b/internal/spotify/player.go @@ -18,22 +18,20 @@ type TokenSource interface { Invalidate(ctx context.Context, accessToken string) error } -// Player implements playback.Spotify for one connected account. -type Player struct { - api *API +type player struct { + api API tokens TokenSource } -var _ playback.Spotify = (*Player)(nil) - -// NewPlayer returns a Player that authenticates with tokens. -func NewPlayer(api *API, tokens TokenSource) *Player { - return &Player{api: api, tokens: tokens} +// NewPlayer returns playback.Spotify for one connected account, which +// authenticates with tokens. +func NewPlayer(api API, tokens TokenSource) playback.Spotify { + return &player{api: api, tokens: tokens} } // do sends req with the account's token. After a 401 it invalidates the token // and tries once more with a fresh one. -func (p *Player) do(ctx context.Context, req request) (int, error) { +func (p *player) do(ctx context.Context, req request) (int, error) { for attempt := 0; ; attempt++ { tok, err := p.tokens.AccessToken(ctx) if err != nil { @@ -58,10 +56,11 @@ type wireDevice struct { } func (d wireDevice) device() playback.Device { - return playback.Device{ - ID: playback.DeviceID(d.ID), Name: d.Name, Type: d.Type, - Active: d.IsActive, Restricted: d.IsRestricted, + id, err := playback.ParseDeviceID(d.ID) + if err != nil { + id = nil // Spotify sends no ID for some devices } + return playback.NewDevice(id, d.Name, d.Type, d.IsActive, d.IsRestricted) } type wireName struct { @@ -85,29 +84,31 @@ type wireItem struct { func (w wireItem) item() (playback.Item, bool) { uri, err := playback.ParseURI(w.URI) if err != nil { - return playback.Item{}, false + return nil, false } - it := playback.Item{ - Kind: uri.Kind(), Name: w.Name, URI: uri, - Duration: time.Duration(w.DurationMS) * time.Millisecond, - } - for _, a := range w.Artists { - it.Artists = append(it.Artists, a.Name) + opts := []playback.ItemOption{playback.WithDuration(time.Duration(w.DurationMS) * time.Millisecond)} + if len(w.Artists) > 0 { + names := make([]string, len(w.Artists)) + for i, a := range w.Artists { + names[i] = a.Name + } + opts = append(opts, playback.WithArtists(names...)) } switch { case w.Album != nil: - it.Album = w.Album.Name + opts = append(opts, playback.WithAlbum(w.Album.Name)) case w.Show != nil: - it.Album = w.Show.Name + opts = append(opts, playback.WithAlbum(w.Show.Name)) } if w.Owner != nil { - it.Owner = w.Owner.DisplayName + opts = append(opts, playback.WithOwner(w.Owner.DisplayName)) } - return it, true + it, err := playback.NewItem(uri, w.Name, opts...) + return it, err == nil } // Devices implements playback.Spotify. -func (p *Player) Devices(ctx context.Context) ([]playback.Device, error) { +func (p *player) Devices(ctx context.Context) ([]playback.Device, error) { var out struct { Devices []wireDevice `json:"devices"` } @@ -122,9 +123,12 @@ func (p *Player) Devices(ctx context.Context) ([]playback.Device, error) { } // Search implements playback.Spotify. -func (p *Player) Search(ctx context.Context, query string, kind playback.Kind, limit int) ([]playback.Item, error) { +func (p *player) Search(ctx context.Context, query string, kind playback.Kind, limit int) ([]playback.Item, error) { limit = min(max(limit, 1), playback.MaxSearchResults) - q := url.Values{"q": {query}, "type": {string(kind)}, "limit": {strconv.Itoa(limit)}} + if kind == nil { + return nil, errors.New("search needs a type") + } + q := url.Values{"q": {query}, "type": {kind.String()}, "limit": {strconv.Itoa(limit)}} var out map[string]struct { Items []*wireItem `json:"items"` } @@ -132,7 +136,7 @@ func (p *Player) Search(ctx context.Context, query string, kind playback.Kind, l return nil, err } var items []playback.Item - for _, w := range out[string(kind)+"s"].Items { + for _, w := range out[kind.String()+"s"].Items { if w == nil { // Spotify returns null entries for some playlists continue } @@ -144,15 +148,18 @@ func (p *Player) Search(ctx context.Context, query string, kind playback.Kind, l } func deviceQuery(id playback.DeviceID) url.Values { - if id == "" { + if id == nil { return nil } - return url.Values{"device_id": {string(id)}} + return url.Values{"device_id": {id.String()}} } // Play implements playback.Spotify. A track or episode plays on its own; an // album, artist, playlist or show plays as a context. -func (p *Player) Play(ctx context.Context, device playback.DeviceID, uri playback.URI) error { +func (p *player) Play(ctx context.Context, device playback.DeviceID, uri playback.URI) error { + if uri == nil { + return errors.New("no URI to play") + } var body any = map[string]any{"uris": []string{uri.String()}} if uri.Kind().IsContext() { body = map[string]any{"context_uri": uri.String()} @@ -161,40 +168,43 @@ func (p *Player) Play(ctx context.Context, device playback.DeviceID, uri playbac return err } -func (p *Player) command(ctx context.Context, method, path string, device playback.DeviceID) error { +func (p *player) command(ctx context.Context, method, path string, device playback.DeviceID) error { _, err := p.do(ctx, request{method: method, path: path, query: deviceQuery(device)}) return err } // Resume implements playback.Spotify. -func (p *Player) Resume(ctx context.Context, device playback.DeviceID) error { +func (p *player) Resume(ctx context.Context, device playback.DeviceID) error { return p.command(ctx, http.MethodPut, "/me/player/play", device) } // Pause implements playback.Spotify. -func (p *Player) Pause(ctx context.Context, device playback.DeviceID) error { +func (p *player) Pause(ctx context.Context, device playback.DeviceID) error { return p.command(ctx, http.MethodPut, "/me/player/pause", device) } // Next implements playback.Spotify. -func (p *Player) Next(ctx context.Context, device playback.DeviceID) error { +func (p *player) Next(ctx context.Context, device playback.DeviceID) error { return p.command(ctx, http.MethodPost, "/me/player/next", device) } // Previous implements playback.Spotify. -func (p *Player) Previous(ctx context.Context, device playback.DeviceID) error { +func (p *player) Previous(ctx context.Context, device playback.DeviceID) error { return p.command(ctx, http.MethodPost, "/me/player/previous", device) } // Transfer implements playback.Spotify. -func (p *Player) Transfer(ctx context.Context, device playback.DeviceID, play bool) error { - body := map[string]any{"device_ids": []string{string(device)}, "play": play} +func (p *player) Transfer(ctx context.Context, device playback.DeviceID, play bool) error { + if device == nil { + return errors.New("transfer needs a device") + } + body := map[string]any{"device_ids": []string{device.String()}, "play": play} _, err := p.do(ctx, request{method: http.MethodPut, path: "/me/player", body: body}) return err } // State implements playback.Spotify. -func (p *Player) State(ctx context.Context) (*playback.State, error) { +func (p *player) State(ctx context.Context) (playback.State, error) { var out struct { IsPlaying bool `json:"is_playing"` ProgressMS int `json:"progress_ms"` @@ -209,15 +219,15 @@ func (p *Player) State(ctx context.Context) (*playback.State, error) { if status == http.StatusNoContent { return nil, nil } - st := &playback.State{Playing: out.IsPlaying, Progress: time.Duration(out.ProgressMS) * time.Millisecond} + var dev playback.Device if out.Device != nil { - d := out.Device.device() - st.Device = &d + dev = out.Device.device() } + var it playback.Item if out.Item != nil { - if it, ok := out.Item.item(); ok { - st.Item = &it + if i, ok := out.Item.item(); ok { + it = i } } - return st, nil + return playback.NewState(out.IsPlaying, time.Duration(out.ProgressMS)*time.Millisecond, dev, it), nil } diff --git a/internal/spotify/spotify_test.go b/internal/spotify/spotify_test.go index caae6df..4afd729 100644 --- a/internal/spotify/spotify_test.go +++ b/internal/spotify/spotify_test.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "net/http/httptest" + "slices" "strings" "sync" "testing" @@ -46,7 +47,7 @@ type fakeAPI struct { routes map[string]http.HandlerFunc } -func newPlayer(t *testing.T, routes map[string]http.HandlerFunc) (*Player, *fakeAPI, *fakeTokens) { +func newPlayer(t *testing.T, routes map[string]http.HandlerFunc) (playback.Spotify, *fakeAPI, *fakeTokens) { t.Helper() f := &fakeAPI{routes: routes} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -84,6 +85,15 @@ func spotifyError(status int, reason string) http.HandlerFunc { } } +func mustDevice(t *testing.T, s string) playback.DeviceID { + t.Helper() + id, err := playback.ParseDeviceID(s) + if err != nil { + t.Fatal(err) + } + return id +} + func mustURI(t *testing.T, s string) playback.URI { t.Helper() u, err := playback.ParseURI(s) @@ -102,7 +112,7 @@ func TestPlayBodies(t *testing.T) { "spotify:album:3": `{"context_uri":"spotify:album:3"}`, "spotify:playlist:4": `{"context_uri":"spotify:playlist:4"}`, } { - if err := p.Play(ctx, "dev1", mustURI(t, uri)); err != nil { + if err := p.Play(ctx, mustDevice(t, "dev1"), mustURI(t, uri)); err != nil { t.Fatal(err) } c := api.last() @@ -110,13 +120,13 @@ func TestPlayBodies(t *testing.T) { t.Errorf("%s: %+v", uri, c) } } - if err := p.Resume(ctx, ""); err != nil { + if err := p.Resume(ctx, nil); err != nil { t.Fatal(err) } if c := api.last(); c.body != "" || c.query != "" { t.Errorf("resume: %+v", c) } - if err := p.Transfer(ctx, "ph1", true); err != nil { + if err := p.Transfer(ctx, mustDevice(t, "ph1"), true); err != nil { t.Fatal(err) } if c := api.last(); c.path != "/me/player" || c.body != `{"device_ids":["ph1"],"play":true}` { @@ -134,14 +144,14 @@ func TestErrors(t *testing.T) { w.WriteHeader(http.StatusTooManyRequests) }, }) - if err := p.Pause(ctx, ""); !errors.Is(err, playback.ErrNoActiveDevice) { + if err := p.Pause(ctx, nil); !errors.Is(err, playback.ErrNoActiveDevice) { t.Errorf("pause: %v", err) } - if err := p.Next(ctx, ""); !errors.Is(err, playback.ErrPremiumRequired) { + if err := p.Next(ctx, nil); !errors.Is(err, playback.ErrPremiumRequired) { t.Errorf("next: %v", err) } var apiErr *Error - if err := p.Previous(ctx, ""); !errors.As(err, &apiErr) || apiErr.Status != 429 || !strings.Contains(err.Error(), "7 s") { + if err := p.Previous(ctx, nil); !errors.As(err, &apiErr) || apiErr.Status != 429 || !strings.Contains(err.Error(), "7 s") { t.Errorf("previous: %v", err) } } @@ -157,7 +167,7 @@ func TestUnauthorizedRetriesOnceWithFreshToken(t *testing.T) { w.WriteHeader(http.StatusNoContent) }, }) - if err := p.Pause(ctx, ""); err != nil { + if err := p.Pause(ctx, nil); err != nil { t.Fatal(err) } if len(tokens.invalidated) != 1 || tokens.invalidated[0] != "t1" || api.count() != 2 { @@ -174,7 +184,7 @@ func TestSearchMapsItems(t *testing.T) { {"type":"track","name":"Local","uri":"spotify:local:x:y:z"}]}}`) }, }) - items, err := p.Search(context.Background(), "song", playback.KindTrack, 50) + items, err := p.Search(context.Background(), "song", playback.KindTrack(), 50) if err != nil { t.Fatal(err) } @@ -185,8 +195,8 @@ func TestSearchMapsItems(t *testing.T) { t.Fatalf("items %+v", items) } it := items[0] - if it.Name != "Song" || it.URI.String() != "spotify:track:1" || strings.Join(it.Artists, ",") != "A,B" || it.Album != "LP" || it.Duration.Seconds() != 61 { - t.Fatalf("item %+v", it) + if it.Name() != "Song" || it.URI().String() != "spotify:track:1" || strings.Join(it.Artists(), ",") != "A,B" || it.Album() != "LP" || it.Duration().Seconds() != 61 { + t.Fatalf("item %v %v", it.Name(), it.URI()) } } @@ -225,7 +235,7 @@ func TestOAuthErrors(t *testing.T) { }) tok, err := o.Refresh(ctx, "r1") - if err != nil || tok.AccessToken != "a2" || tok.RefreshToken != "" { + if err != nil || tok.AccessToken() != "a2" || tok.RefreshToken() != "" { t.Fatalf("unchanged refresh token must be reported as empty: %+v %v", tok, err) } answer = "invalid_grant" @@ -237,3 +247,11 @@ func TestOAuthErrors(t *testing.T) { t.Fatalf("invalid_client: %v", err) } } + +func TestScopesCannotBeWidened(t *testing.T) { + s := Scopes() + s[0] = "user-library-read" + if slices.Contains(Scopes(), "user-library-read") { + t.Fatal("Scopes shared its slice") + } +} diff --git a/internal/web/web.go b/internal/web/web.go index fd9cdcc..b34f679 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -76,12 +76,12 @@ func (h *handler) connectPage(w http.ResponseWriter, r *http.Request) { h.fail(w, err) return } - acc, connected := st.Profile.Account() + acc, connected := st.Profile().Account() d := pageData{Title: "Connect Spotify", Invite: code.Secret(), ShowForm: true, Connected: connected} if connected { d.Name = acc.Name() - if !st.ConnectedAt.IsZero() { - d.Since = st.ConnectedAt.Format(time.DateOnly) + if at := st.ConnectedAt(); !at.IsZero() { + d.Since = at.Format(time.DateOnly) } } h.render(w, http.StatusOK, d) @@ -105,8 +105,8 @@ func (h *handler) connectPost(w http.ResponseWriter, r *http.Request) { h.fail(w, err) return } - http.SetCookie(w, loginCookie(login.Nonce, int(account.LoginTTL/time.Second))) - http.Redirect(w, r, login.URL, http.StatusSeeOther) + http.SetCookie(w, loginCookie(login.Nonce(), int(account.LoginTTL/time.Second))) + http.Redirect(w, r, login.URL(), http.StatusSeeOther) case "disconnect": profile, err := h.c.Disconnect(r.Context(), code) if err != nil { @@ -125,21 +125,21 @@ func (h *handler) connectPost(w http.ResponseWriter, r *http.Request) { func (h *handler) callback(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() - cb := account.Callback{State: q.Get("state"), Code: q.Get("code"), Error: q.Get("error")} + var nonce string if c, err := r.Cookie(cookieName); err == nil { - cb.Nonce = c.Value + nonce = c.Value } + cb := account.NewCallback(q.Get("state"), nonce, q.Get("code"), q.Get("error")) http.SetCookie(w, loginCookie("", -1)) profile, err := h.c.FinishLogin(r.Context(), cb) if err != nil { h.fail(w, err) return } - acc, _ := profile.Account() - h.log.Info("spotify account connected", "profile", profile.ID().String(), "spotify_user", acc.ID) msg := "Spotify is connected. You can close this page." - if name := acc.Name(); name != "" { - msg = "Spotify is connected as " + name + ". You can close this page." + if acc, ok := profile.Account(); ok { + h.log.Info("spotify account connected", "profile", profile.ID().String(), "spotify_user", acc.ID()) + msg = "Spotify is connected as " + acc.Name() + ". You can close this page." } h.render(w, http.StatusOK, pageData{Title: "Connected", Message: msg}) } diff --git a/internal/web/web_test.go b/internal/web/web_test.go index 40db0d9..4ef70b2 100644 --- a/internal/web/web_test.go +++ b/internal/web/web_test.go @@ -37,26 +37,29 @@ func (f *fakeOAuth) Exchange(_ context.Context, code, verifier string) (account. defer f.mu.Unlock() for _, v := range f.verifiers { if v == verifier && code == "good" { - return account.Token{AccessToken: "a", RefreshToken: "r", Expiry: time.Now().Add(time.Hour)}, nil + return account.NewToken("a", "r", time.Now().Add(time.Hour)) } } - return account.Token{}, errors.New("bad code") + return nil, errors.New("bad code") } func (f *fakeOAuth) Refresh(context.Context, string) (account.Token, error) { - return account.Token{}, errors.New("unused") + return nil, errors.New("unused") } type fakeIdentity struct{ err error } func (f *fakeIdentity) Account(context.Context, string) (account.SpotifyAccount, error) { - return account.SpotifyAccount{ID: "jan", DisplayName: "Jan"}, f.err + if f.err != nil { + return nil, f.err + } + return account.NewSpotifyAccount("jan", "Jan") } type env struct { srv *httptest.Server - inviter *account.Inviter - store *filestore.Store + inviter account.Inviter + store filestore.Store identity *fakeIdentity } From 40e93cd5287503a9578eeb3c4c3b87ee56f8d537 Mon Sep 17 00:00:00 2001 From: Jan Unterbrink Date: Mon, 23 Nov 2026 20:14:23 +0100 Subject: [PATCH 6/7] refactor(account): inject a Clock and fold Inviter into Service Replace the functional options (Option, apply, WithClock) with an explicit Clock interface that NewService and NewTokenSource require; main wires SystemClock(), tests a fake. The domain no longer calls time.Now itself. Remove Inviter: CreateInvite is a use case of account.Service. The invite command builds the same Service; it never calls Spotify, so it still works without credentials. invite.go now holds only the invite types; ProfileID moves to profileid.go. README layout updated. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- cmd/spotify-mcp/main.go | 14 ++- internal/account/account_test.go | 23 ++--- internal/account/clock.go | 17 ++++ internal/account/ids.go | 129 --------------------------- internal/account/invite.go | 111 +++++++++++++++++------ internal/account/option.go | 21 ----- internal/account/profileid.go | 34 +++++++ internal/account/service.go | 42 +++++++-- internal/account/tokensource.go | 10 +-- internal/account/tokensource_test.go | 2 +- internal/web/web_test.go | 14 ++- 12 files changed, 210 insertions(+), 209 deletions(-) create mode 100644 internal/account/clock.go delete mode 100644 internal/account/ids.go delete mode 100644 internal/account/option.go create mode 100644 internal/account/profileid.go diff --git a/README.md b/README.md index 64db157..ab27c9b 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ flowchart LR account -- "OAuth / Identity ports" --> spotify ``` -- `internal/playback` and `internal/account` are the domain: typed values (`URI`, `DeviceID`, `Profile`, `InviteCode`), the rules, and the ports (interfaces) they need. +- `internal/playback` and `internal/account` are the domain: each has a `Service` with the use cases, the rules, and the ports (interfaces) it needs. Values and entities (`URI`, `DeviceID`, `ProfileID`, `InviteCode`, `Token`, …) are exported interfaces with unexported implementations, created only through constructors that validate (`ParseX`, `NewX`, `RestoreX` for stored data). The time comes from an injected `Clock`. - `internal/spotify` (Web API + OAuth) and `internal/filestore` (JSON files) implement the ports. Wire and file formats stay unexported in them. - `internal/mcpserver` and `internal/web` are the transports. Each depends on a small interface it defines itself. diff --git a/cmd/spotify-mcp/main.go b/cmd/spotify-mcp/main.go index 1003f69..952463f 100644 --- a/cmd/spotify-mcp/main.go +++ b/cmd/spotify-mcp/main.go @@ -66,7 +66,14 @@ func invite(args []string) error { if err != nil { return err } - code, expires, err := account.NewInviter(store).CreateInvite(context.Background(), cfg.ProfileID(), *ttl) + // Creating an invite never calls Spotify, so the credentials may be + // missing here; the OAuth and API adapters are only wired up. + oauth := spotify.NewOAuth(spotify.OAuthConfig{ + ClientID: cfg.ClientID(), ClientSecret: cfg.ClientSecret(), RedirectURL: cfg.RedirectURL(), + }) + api := spotify.NewAPI(spotify.DefaultAPIURL, nil) + accounts := account.NewService(store, store, oauth, api, account.SystemClock()) + code, expires, err := accounts.CreateInvite(context.Background(), cfg.ProfileID(), *ttl) if err != nil { return err } @@ -92,9 +99,10 @@ func serve(log *slog.Logger) error { ClientID: cfg.ClientID(), ClientSecret: cfg.ClientSecret(), RedirectURL: cfg.RedirectURL(), }) api := spotify.NewAPI(spotify.DefaultAPIURL, nil) - tokens := account.NewTokenSource(store, oauth, cfg.ProfileID()) + clock := account.SystemClock() + tokens := account.NewTokenSource(store, oauth, cfg.ProfileID(), clock) player := playback.NewService(spotify.NewPlayer(api, tokens)) - accounts := account.NewService(store, store, oauth, api) + accounts := account.NewService(store, store, oauth, api, clock) // Only for the log: a broken token file shouldn't stop the server, the // tools report it when they need the token. diff --git a/internal/account/account_test.go b/internal/account/account_test.go index 3936e88..9b8ef34 100644 --- a/internal/account/account_test.go +++ b/internal/account/account_test.go @@ -25,6 +25,11 @@ func mustProfileID(s string) account.ProfileID { return id } +// clockFunc is a test Clock. +type clockFunc func() time.Time + +func (f clockFunc) Now() time.Time { return f() } + func must[T any](v T, err error) T { if err != nil { panic(err) @@ -87,11 +92,10 @@ func (f fakeIdentity) Account(context.Context, string) (account.SpotifyAccount, } type env struct { - store filestore.Store - oauth *fakeOAuth - inviter account.Inviter - svc account.Service - now time.Time + store filestore.Store + oauth *fakeOAuth + svc account.Service + now time.Time } func newEnv(t *testing.T, identityErr error) *env { @@ -101,15 +105,14 @@ func newEnv(t *testing.T, identityErr error) *env { t.Fatal(err) } e := &env{store: st, oauth: &fakeOAuth{}, now: time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)} - clock := account.WithClock(func() time.Time { return e.now }) - e.inviter = account.NewInviter(st, clock) + clock := clockFunc(func() time.Time { return e.now }) e.svc = account.NewService(st, st, e.oauth, fakeIdentity{err: identityErr}, clock) return e } func (e *env) invite(t *testing.T) account.InviteCode { t.Helper() - code, _, err := e.inviter.CreateInvite(context.Background(), profile, time.Hour) + code, _, err := e.svc.CreateInvite(context.Background(), profile, time.Hour) if err != nil { t.Fatal(err) } @@ -252,10 +255,10 @@ func TestInvites(t *testing.T) { if _, err := e.svc.StartLogin(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { t.Fatalf("expired invite accepted: %v", err) } - if _, _, err := e.inviter.CreateInvite(ctx, nil, time.Hour); err == nil { + if _, _, err := e.svc.CreateInvite(ctx, nil, time.Hour); err == nil { t.Fatal("nil profile accepted") } - if _, _, err := e.inviter.CreateInvite(ctx, profile, 0); err == nil { + if _, _, err := e.svc.CreateInvite(ctx, profile, 0); err == nil { t.Fatal("zero TTL accepted") } } diff --git a/internal/account/clock.go b/internal/account/clock.go new file mode 100644 index 0000000..39fc7fc --- /dev/null +++ b/internal/account/clock.go @@ -0,0 +1,17 @@ +package account + +import "time" + +// Clock tells the time. The domain never calls time.Now itself, so tests can +// set the time and invite expiry, login timeouts and token refresh are +// checked without waiting. +type Clock interface { + Now() time.Time +} + +type systemClock struct{} + +func (systemClock) Now() time.Time { return time.Now() } + +// SystemClock is the real clock, for main. +func SystemClock() Clock { return systemClock{} } diff --git a/internal/account/ids.go b/internal/account/ids.go deleted file mode 100644 index c209af4..0000000 --- a/internal/account/ids.go +++ /dev/null @@ -1,129 +0,0 @@ -package account - -import ( - "crypto/sha256" - "encoding/hex" - "errors" - "fmt" - "regexp" - "time" -) - -// The value types below are interfaces with an unexported marker method, so -// only this package implements them and every value went through one of its -// constructors. Their implementations are small comparable structs: two -// values are equal with == exactly when they hold the same text. - -// ProfileID identifies a profile: 1-63 lower-case letters, digits and dashes. -// Adapters may use String() in file and key names. Get one from -// ParseProfileID. -type ProfileID interface { - String() string - isProfileID() -} - -type profileID struct{ s string } - -func (p profileID) String() string { return p.s } -func (profileID) isProfileID() {} - -var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) - -// ParseProfileID checks a profile ID. -func ParseProfileID(s string) (ProfileID, error) { - if !profileRe.MatchString(s) { - return nil, fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) - } - return profileID{s: s}, nil -} - -// InviteCode is the secret part of an invite link. The Inviter creates new -// codes; ParseInviteCode reads one from a link. It is only ever shown once; -// repositories see its hash. -type InviteCode interface { - // Secret is the code itself, for building the link. Keep it out of logs. - Secret() string - isInviteCode() -} - -type inviteCode struct{ s string } - -func (c inviteCode) Secret() string { return c.s } -func (inviteCode) isInviteCode() {} - -// String keeps the code out of logs and error messages. -func (inviteCode) String() string { return "InviteCode(redacted)" } - -// A code is 32 random bytes, base64url-encoded without padding. -var inviteCodeRe = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) - -// ParseInviteCode checks a code taken from a link. Anything malformed is -// ErrInvalidInvite, like an unknown code. -func ParseInviteCode(s string) (InviteCode, error) { - if !inviteCodeRe.MatchString(s) { - return nil, ErrInvalidInvite - } - return inviteCode{s: s}, nil -} - -func newInviteCode() InviteCode { return inviteCode{s: randomString()} } - -// InviteHash identifies an invite in a repository: the hex SHA-256 of its -// code, so reading the storage doesn't give anyone a usable link. -type InviteHash interface { - String() string - isInviteHash() -} - -type inviteHash struct{ s string } - -func (h inviteHash) String() string { return h.s } -func (inviteHash) isInviteHash() {} - -var inviteHashRe = regexp.MustCompile(`^[0-9a-f]{64}$`) - -// ParseInviteHash checks a hash read back from a repository. -func ParseInviteHash(s string) (InviteHash, error) { - if !inviteHashRe.MatchString(s) { - return nil, fmt.Errorf("invalid invite hash %q", s) - } - return inviteHash{s: s}, nil -} - -func hashInvite(code InviteCode) InviteHash { - sum := sha256.Sum256([]byte(code.Secret())) - return inviteHash{s: hex.EncodeToString(sum[:])} -} - -// Invite lets whoever holds its code connect or disconnect one profile. -type Invite interface { - Hash() InviteHash - ProfileID() ProfileID - Expires() time.Time -} - -type invite struct { - hash InviteHash - profileID ProfileID - expires time.Time -} - -func (i *invite) Hash() InviteHash { return i.hash } -func (i *invite) ProfileID() ProfileID { return i.profileID } -func (i *invite) Expires() time.Time { return i.expires } - -// RestoreInvite rebuilds an invite a repository stored, checking each part. -func RestoreInvite(hash, profileID string, expires time.Time) (Invite, error) { - h, err := ParseInviteHash(hash) - if err != nil { - return nil, err - } - id, err := ParseProfileID(profileID) - if err != nil { - return nil, err - } - if expires.IsZero() { - return nil, errors.New("invite has no expiry") - } - return &invite{hash: h, profileID: id, expires: expires}, nil -} diff --git a/internal/account/invite.go b/internal/account/invite.go index 57a6a6a..8af60b2 100644 --- a/internal/account/invite.go +++ b/internal/account/invite.go @@ -1,45 +1,104 @@ package account import ( - "context" + "crypto/sha256" + "encoding/hex" "errors" "fmt" + "regexp" "time" ) -// Inviter creates one-time invite links. It needs no Spotify access, so the -// invite command can run it on its own. -type Inviter interface { - // CreateInvite returns a new one-time code for the profile and when it - // expires. - CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) +// An invite lets whoever holds its code connect or disconnect one profile. +// InviteCode and InviteHash are sealed value interfaces like ProfileID. + +// InviteCode is the secret part of an invite link. Service.CreateInvite +// creates new codes; ParseInviteCode reads one from a link. It is only ever shown once; +// repositories see its hash. +type InviteCode interface { + // Secret is the code itself, for building the link. Keep it out of logs. + Secret() string + isInviteCode() } -type inviter struct { - invites Invites - now func() time.Time +type inviteCode struct{ s string } + +func (c inviteCode) Secret() string { return c.s } +func (inviteCode) isInviteCode() {} + +// String keeps the code out of logs and error messages. +func (inviteCode) String() string { return "InviteCode(redacted)" } + +// A code is 32 random bytes, base64url-encoded without padding. +var inviteCodeRe = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) + +// ParseInviteCode checks a code taken from a link. Anything malformed is +// ErrInvalidInvite, like an unknown code. +func ParseInviteCode(s string) (InviteCode, error) { + if !inviteCodeRe.MatchString(s) { + return nil, ErrInvalidInvite + } + return inviteCode{s: s}, nil } -// NewInviter returns an Inviter storing into invites. -func NewInviter(invites Invites, opts ...Option) Inviter { - return &inviter{invites: invites, now: apply(opts).now} +func newInviteCode() InviteCode { return inviteCode{s: randomString()} } + +// InviteHash identifies an invite in a repository: the hex SHA-256 of its +// code, so reading the storage doesn't give anyone a usable link. +type InviteHash interface { + String() string + isInviteHash() } -func (i *inviter) CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) { - if id == nil { - return nil, time.Time{}, errors.New("invite needs a profile") +type inviteHash struct{ s string } + +func (h inviteHash) String() string { return h.s } +func (inviteHash) isInviteHash() {} + +var inviteHashRe = regexp.MustCompile(`^[0-9a-f]{64}$`) + +// ParseInviteHash checks a hash read back from a repository. +func ParseInviteHash(s string) (InviteHash, error) { + if !inviteHashRe.MatchString(s) { + return nil, fmt.Errorf("invalid invite hash %q", s) } - if ttl <= 0 { - return nil, time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) + return inviteHash{s: s}, nil +} + +func hashInvite(code InviteCode) InviteHash { + sum := sha256.Sum256([]byte(code.Secret())) + return inviteHash{s: hex.EncodeToString(sum[:])} +} + +// Invite lets whoever holds its code connect or disconnect one profile. +type Invite interface { + Hash() InviteHash + ProfileID() ProfileID + Expires() time.Time +} + +type invite struct { + hash InviteHash + profileID ProfileID + expires time.Time +} + +func (i *invite) Hash() InviteHash { return i.hash } +func (i *invite) ProfileID() ProfileID { return i.profileID } +func (i *invite) Expires() time.Time { return i.expires } + +// RestoreInvite rebuilds an invite a repository stored, checking each part. +func RestoreInvite(hash, profileID string, expires time.Time) (Invite, error) { + h, err := ParseInviteHash(hash) + if err != nil { + return nil, err } - code := newInviteCode() - now := i.now() - inv := &invite{hash: hashInvite(code), profileID: id, expires: now.Add(ttl)} - if err := i.invites.PruneInvites(ctx, now); err != nil { - return nil, time.Time{}, fmt.Errorf("prune invites: %w", err) + id, err := ParseProfileID(profileID) + if err != nil { + return nil, err } - if err := i.invites.AddInvite(ctx, inv); err != nil { - return nil, time.Time{}, fmt.Errorf("save invite: %w", err) + if expires.IsZero() { + return nil, errors.New("invite has no expiry") } - return code, inv.expires, nil + return &invite{hash: h, profileID: id, expires: expires}, nil } diff --git a/internal/account/option.go b/internal/account/option.go deleted file mode 100644 index 474946f..0000000 --- a/internal/account/option.go +++ /dev/null @@ -1,21 +0,0 @@ -package account - -import "time" - -// Option configures a Service, Inviter or TokenSource. -type Option func(*settings) - -type settings struct { - now func() time.Time -} - -// WithClock replaces time.Now, e.g. in tests. -func WithClock(now func() time.Time) Option { return func(s *settings) { s.now = now } } - -func apply(opts []Option) settings { - s := settings{now: time.Now} - for _, o := range opts { - o(&s) - } - return s -} diff --git a/internal/account/profileid.go b/internal/account/profileid.go new file mode 100644 index 0000000..6b73be7 --- /dev/null +++ b/internal/account/profileid.go @@ -0,0 +1,34 @@ +package account + +import ( + "fmt" + "regexp" +) + +// Value types in this package are interfaces with an unexported marker method, so +// only this package implements them and every value went through one of its +// constructors. Their implementations are small comparable structs: two +// values are equal with == exactly when they hold the same text. + +// ProfileID identifies a profile: 1-63 lower-case letters, digits and dashes. +// Adapters may use String() in file and key names. Get one from +// ParseProfileID. +type ProfileID interface { + String() string + isProfileID() +} + +type profileID struct{ s string } + +func (p profileID) String() string { return p.s } +func (profileID) isProfileID() {} + +var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) + +// ParseProfileID checks a profile ID. +func ParseProfileID(s string) (ProfileID, error) { + if !profileRe.MatchString(s) { + return nil, fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) + } + return profileID{s: s}, nil +} diff --git a/internal/account/service.go b/internal/account/service.go index 68a47de..83bbcd7 100644 --- a/internal/account/service.go +++ b/internal/account/service.go @@ -17,8 +17,13 @@ const ( maxPending = 100 ) -// Service runs logins and disconnects for holders of an invite. +// Service is the account domain's use cases: it creates invite links and runs +// logins and disconnects for whoever holds one. type Service interface { + // CreateInvite returns a new one-time code for the profile and when it + // expires. It needs no Spotify access, so the invite command can call it + // without credentials. + CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) // Status reports the profile an invite belongs to and who is connected, // without using the invite up. Status(ctx context.Context, code InviteCode) (Status, error) @@ -40,7 +45,7 @@ type service struct { invites Invites oauth OAuth identity Identity - now func() time.Time + clock Clock mu sync.Mutex pending map[string]pendingLogin // by OAuth state @@ -55,10 +60,9 @@ type pendingLogin struct { } // NewService returns a Service using the given ports. -func NewService(tokens Tokens, invites Invites, oauth OAuth, identity Identity, opts ...Option) Service { +func NewService(tokens Tokens, invites Invites, oauth OAuth, identity Identity, clock Clock) Service { return &service{ - tokens: tokens, invites: invites, oauth: oauth, identity: identity, - now: apply(opts).now, + tokens: tokens, invites: invites, oauth: oauth, identity: identity, clock: clock, pending: map[string]pendingLogin{}, } } @@ -112,6 +116,26 @@ func (c callback) Nonce() string { return c.nonce } func (c callback) Code() string { return c.code } func (c callback) SpotifyError() string { return c.spotifyError } +func (s *service) CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) { + if id == nil { + return nil, time.Time{}, errors.New("invite needs a profile") + } + if ttl <= 0 { + return nil, time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) + } + code := newInviteCode() + now := s.clock.Now() + inv := &invite{hash: hashInvite(code), profileID: id, expires: now.Add(ttl)} + // Expired invites are removed here, so the store doesn't keep growing. + if err := s.invites.PruneInvites(ctx, now); err != nil { + return nil, time.Time{}, fmt.Errorf("prune invites: %w", err) + } + if err := s.invites.AddInvite(ctx, inv); err != nil { + return nil, time.Time{}, fmt.Errorf("save invite: %w", err) + } + return code, inv.expires, nil +} + func (s *service) Status(ctx context.Context, code InviteCode) (Status, error) { inv, err := s.checkInvite(ctx, code) if err != nil { @@ -130,7 +154,7 @@ func (s *service) StartLogin(ctx context.Context, code InviteCode) (Login, error return nil, err } state, nonce, verifier := randomString(), randomString(), randomString() - now := s.now() + now := s.clock.Now() s.mu.Lock() defer s.mu.Unlock() @@ -157,7 +181,7 @@ func (s *service) FinishLogin(ctx context.Context, cb Callback) (Profile, error) p, ok := s.pending[cb.State()] delete(s.pending, cb.State()) s.mu.Unlock() - if !ok || s.now().After(p.expires) || subtle.ConstantTimeCompare([]byte(cb.Nonce()), []byte(p.nonce)) != 1 { + if !ok || s.clock.Now().After(p.expires) || subtle.ConstantTimeCompare([]byte(cb.Nonce()), []byte(p.nonce)) != 1 { return nil, ErrLoginExpired } if cb.SpotifyError() == "access_denied" { @@ -180,7 +204,7 @@ func (s *service) FinishLogin(ctx context.Context, cb Callback) (Profile, error) if err != nil { return nil, fmt.Errorf("look up account: %w", err) } - c, err := NewConnection(tok, acc, s.now()) + c, err := NewConnection(tok, acc, s.clock.Now()) if err != nil { return nil, err } @@ -228,7 +252,7 @@ func (s *service) validInvite(inv Invite, err error) (Invite, error) { return nil, fmt.Errorf("load invite: %w", err) case inv == nil || inv.ProfileID() == nil: return nil, errors.New("load invite: repository returned an incomplete invite") - case s.now().After(inv.Expires()): + case s.clock.Now().After(inv.Expires()): return nil, ErrInvalidInvite } return inv, nil diff --git a/internal/account/tokensource.go b/internal/account/tokensource.go index f493b92..59832e2 100644 --- a/internal/account/tokensource.go +++ b/internal/account/tokensource.go @@ -27,12 +27,12 @@ type tokenSource struct { tokens Tokens oauth OAuth profile ProfileID - now func() time.Time + clock Clock } // NewTokenSource returns a TokenSource for the profile. -func NewTokenSource(tokens Tokens, oauth OAuth, id ProfileID, opts ...Option) TokenSource { - return &tokenSource{tokens: tokens, oauth: oauth, profile: id, now: apply(opts).now} +func NewTokenSource(tokens Tokens, oauth OAuth, id ProfileID, clock Clock) TokenSource { + return &tokenSource{tokens: tokens, oauth: oauth, profile: id, clock: clock} } func (ts *tokenSource) AccessToken(ctx context.Context) (string, error) { @@ -46,13 +46,13 @@ func (ts *tokenSource) AccessToken(ctx context.Context) (string, error) { if err != nil { return "", fmt.Errorf("load connection: %w", err) } - if accessValid(c, ts.now()) { + if accessValid(c, ts.clock.Now()) { return c.Token().AccessToken(), nil } var access string err = ts.tokens.UpdateConnection(ctx, ts.profile, func(c Connection) (Connection, error) { - if accessValid(c, ts.now()) { // refreshed by someone else meanwhile + if accessValid(c, ts.clock.Now()) { // refreshed by someone else meanwhile access = c.Token().AccessToken() return c, nil } diff --git a/internal/account/tokensource_test.go b/internal/account/tokensource_test.go index 60f3546..4a87089 100644 --- a/internal/account/tokensource_test.go +++ b/internal/account/tokensource_test.go @@ -17,7 +17,7 @@ func (e *env) connect(t *testing.T, c account.Connection) { } func (e *env) tokens() account.TokenSource { - return account.NewTokenSource(e.store, e.oauth, profile, account.WithClock(func() time.Time { return e.now })) + return account.NewTokenSource(e.store, e.oauth, profile, clockFunc(func() time.Time { return e.now })) } func expired(rt string) account.Connection { diff --git a/internal/web/web_test.go b/internal/web/web_test.go index 4ef70b2..a3eb707 100644 --- a/internal/web/web_test.go +++ b/internal/web/web_test.go @@ -57,12 +57,17 @@ func (f *fakeIdentity) Account(context.Context, string) (account.SpotifyAccount, } type env struct { + svc account.Service srv *httptest.Server - inviter account.Inviter store filestore.Store identity *fakeIdentity } +// fixedClock is a test Clock that always tells the same time. +type fixedClock time.Time + +func (c fixedClock) Now() time.Time { return time.Time(c) } + func newEnv(t *testing.T) *env { t.Helper() st, err := filestore.Open(t.TempDir()) @@ -70,10 +75,11 @@ func newEnv(t *testing.T) *env { t.Fatal(err) } id := &fakeIdentity{} - svc := account.NewService(st, st, &fakeOAuth{verifiers: map[string]string{}}, id) + clock := fixedClock(time.Date(2026, 11, 23, 9, 0, 0, 0, time.UTC)) + svc := account.NewService(st, st, &fakeOAuth{verifiers: map[string]string{}}, id, clock) srv := httptest.NewTLSServer(web.NewHandler(svc, slog.New(slog.DiscardHandler))) t.Cleanup(srv.Close) - return &env{srv: srv, inviter: account.NewInviter(st), store: st, identity: id} + return &env{svc: svc, srv: srv, store: st, identity: id} } var profile = mustProfileID("default") @@ -89,7 +95,7 @@ func mustProfileID(s string) account.ProfileID { func (e *env) invite(t *testing.T) string { t.Helper() - code, _, err := e.inviter.CreateInvite(context.Background(), profile, time.Hour) + code, _, err := e.svc.CreateInvite(context.Background(), profile, time.Hour) if err != nil { t.Fatal(err) } From 2552a485a744479c210a28aa207f81bc6b057067 Mon Sep 17 00:00:00 2001 From: Jan Unterbrink Date: Mon, 23 Nov 2026 21:06:43 +0100 Subject: [PATCH 7/7] refactor: opaque value structs, NewToken needs both tokens, locker interface Address the review on PR #2: - Value types (ProfileID, InviteCode, InviteHash, Kind, URI, DeviceID) are opaque structs with unexported fields, the netip.Addr pattern, instead of sealed interfaces with empty marker methods. Other packages can only make the zero value, which every function rejects (IsZero). The zero DeviceID means the active device. - InviteCode.Hash() replaces the free function hashInvite. - NewToken requires both the access and the refresh token. The OAuth adapter keeps the old refresh token when Spotify sends none, so the token source no longer patches it in. Token's String() (redacted) is part of the interface. - filestore: the cross-process lock is an unexported locker interface with one implementation per platform (flock, noLock). Co-Authored-By: Claude Opus 5.5 --- internal/account/account.go | 3 +- internal/account/account_test.go | 19 ++--- internal/account/entities.go | 16 ++-- internal/account/invite.go | 64 +++++++--------- internal/account/profileid.go | 28 ++++--- internal/account/profiles.go | 2 +- internal/account/service.go | 26 +++---- internal/account/tokensource.go | 10 +-- internal/account/tokensource_test.go | 8 +- internal/filestore/filestore.go | 30 ++++---- internal/filestore/filestore_test.go | 2 +- internal/filestore/lock_other.go | 10 ++- internal/filestore/lock_unix.go | 12 ++- internal/mcpserver/mcpserver.go | 4 +- internal/playback/playback.go | 108 +++++++++++++-------------- internal/playback/playback_test.go | 8 +- internal/playback/service.go | 8 +- internal/spotify/auth.go | 10 +-- internal/spotify/player.go | 14 ++-- internal/spotify/spotify_test.go | 16 ++-- 20 files changed, 195 insertions(+), 203 deletions(-) diff --git a/internal/account/account.go b/internal/account/account.go index 2c576c6..57ac663 100644 --- a/internal/account/account.go +++ b/internal/account/account.go @@ -106,7 +106,8 @@ type OAuth interface { AuthCodeURL(state, verifier string) string // Exchange trades a callback code for a token. Exchange(ctx context.Context, code, verifier string) (Token, error) - // Refresh returns a new access token, or ErrRevoked. + // Refresh returns a new token, or ErrRevoked. When Spotify keeps the + // refresh token, the returned token carries the old one. Refresh(ctx context.Context, refreshToken string) (Token, error) } diff --git a/internal/account/account_test.go b/internal/account/account_test.go index 9b8ef34..a706fa0 100644 --- a/internal/account/account_test.go +++ b/internal/account/account_test.go @@ -240,8 +240,8 @@ func TestDisconnect(t *testing.T) { func TestInvites(t *testing.T) { ctx := context.Background() e := newEnv(t, nil) - if _, err := e.svc.Status(ctx, nil); !errors.Is(err, account.ErrInvalidInvite) { - t.Fatalf("nil code: %v", err) + if _, err := e.svc.Status(ctx, account.InviteCode{}); !errors.Is(err, account.ErrInvalidInvite) { + t.Fatalf("zero code: %v", err) } unknown, err := account.ParseInviteCode(strings.Repeat("a", 43)) if err != nil { @@ -255,8 +255,8 @@ func TestInvites(t *testing.T) { if _, err := e.svc.StartLogin(ctx, code); !errors.Is(err, account.ErrInvalidInvite) { t.Fatalf("expired invite accepted: %v", err) } - if _, _, err := e.svc.CreateInvite(ctx, nil, time.Hour); err == nil { - t.Fatal("nil profile accepted") + if _, _, err := e.svc.CreateInvite(ctx, account.ProfileID{}, time.Hour); err == nil { + t.Fatal("zero profile accepted") } if _, _, err := e.svc.CreateInvite(ctx, profile, 0); err == nil { t.Fatal("zero TTL accepted") @@ -342,8 +342,10 @@ func TestProfiles(t *testing.T) { } func TestEntityConstructors(t *testing.T) { - if _, err := account.NewToken("", "", time.Time{}); err == nil { - t.Error("empty token accepted") + for _, tc := range [][2]string{{"", ""}, {"a", ""}, {"", "r"}} { + if _, err := account.NewToken(tc[0], tc[1], time.Time{}); err == nil { + t.Errorf("token %q accepted", tc) + } } if _, err := account.NewSpotifyAccount("", "Jan"); err == nil { t.Error("account without ID accepted") @@ -356,9 +358,8 @@ func TestEntityConstructors(t *testing.T) { tok account.Token acc account.SpotifyAccount }{ - "no token": {nil, acc}, - "no refresh token": {token("a", "", time.Time{}), acc}, - "no account": {tok, nil}, + "no token": {nil, acc}, + "no account": {tok, nil}, } { if _, err := account.NewConnection(c.tok, c.acc, time.Time{}); err == nil { t.Errorf("%s: accepted", name) diff --git a/internal/account/entities.go b/internal/account/entities.go index f67219d..1635717 100644 --- a/internal/account/entities.go +++ b/internal/account/entities.go @@ -38,12 +38,14 @@ func (a *spotifyAccount) Name() string { } // Token is an OAuth token pair as Spotify issues it. Get one from NewToken. -// It prints as redacted, so it can't leak into logs by accident. +// Spotify's tokens are opaque strings, not JWTs, so there is nothing to parse +// in them. type Token interface { AccessToken() string - // RefreshToken is empty when Spotify keeps the old one. RefreshToken() string Expiry() time.Time + // String is redacted, so a token can't leak into logs by accident. + String() string } type token struct { @@ -51,10 +53,10 @@ type token struct { expiry time.Time } -// NewToken builds a Token. At least one of the two tokens is required. +// NewToken builds a Token; both tokens are required. func NewToken(accessToken, refreshToken string, expiry time.Time) (Token, error) { - if accessToken == "" && refreshToken == "" { - return nil, errors.New("token is empty") + if accessToken == "" || refreshToken == "" { + return nil, errors.New("token needs an access and a refresh token") } return &token{access: accessToken, refresh: refreshToken, expiry: expiry}, nil } @@ -83,8 +85,8 @@ type connection struct { // NewConnection builds a Connection; token and account are required. func NewConnection(tok Token, acc SpotifyAccount, connectedAt time.Time) (Connection, error) { - if tok == nil || tok.RefreshToken() == "" { - return nil, errors.New("connection needs a refresh token") + if tok == nil { + return nil, errors.New("connection needs a token") } if acc == nil { return nil, errors.New("connection needs a Spotify account") diff --git a/internal/account/invite.go b/internal/account/invite.go index 8af60b2..1b5178f 100644 --- a/internal/account/invite.go +++ b/internal/account/invite.go @@ -9,25 +9,11 @@ import ( "time" ) -// An invite lets whoever holds its code connect or disconnect one profile. -// InviteCode and InviteHash are sealed value interfaces like ProfileID. - // InviteCode is the secret part of an invite link. Service.CreateInvite -// creates new codes; ParseInviteCode reads one from a link. It is only ever shown once; -// repositories see its hash. -type InviteCode interface { - // Secret is the code itself, for building the link. Keep it out of logs. - Secret() string - isInviteCode() -} - -type inviteCode struct{ s string } - -func (c inviteCode) Secret() string { return c.s } -func (inviteCode) isInviteCode() {} - -// String keeps the code out of logs and error messages. -func (inviteCode) String() string { return "InviteCode(redacted)" } +// creates new codes; ParseInviteCode reads one from a link. It is only ever +// shown once; repositories see its Hash. Like ProfileID it is an opaque +// value: the zero value is not a valid code. +type InviteCode struct{ s string } // A code is 32 random bytes, base64url-encoded without padding. var inviteCodeRe = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) @@ -36,39 +22,47 @@ var inviteCodeRe = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) // ErrInvalidInvite, like an unknown code. func ParseInviteCode(s string) (InviteCode, error) { if !inviteCodeRe.MatchString(s) { - return nil, ErrInvalidInvite + return InviteCode{}, ErrInvalidInvite } - return inviteCode{s: s}, nil + return InviteCode{s: s}, nil } -func newInviteCode() InviteCode { return inviteCode{s: randomString()} } +func newInviteCode() InviteCode { return InviteCode{s: randomString()} } -// InviteHash identifies an invite in a repository: the hex SHA-256 of its -// code, so reading the storage doesn't give anyone a usable link. -type InviteHash interface { - String() string - isInviteHash() +// Secret is the code itself, for building the link. Keep it out of logs. +func (c InviteCode) Secret() string { return c.s } + +// String keeps the code out of logs and error messages. +func (c InviteCode) String() string { return "InviteCode(redacted)" } + +// Hash is what repositories store instead of the code: its hex SHA-256, so +// reading the storage doesn't give anyone a usable link. +func (c InviteCode) Hash() InviteHash { + sum := sha256.Sum256([]byte(c.s)) + return InviteHash{s: hex.EncodeToString(sum[:])} } -type inviteHash struct{ s string } +// IsZero reports whether c is the zero value, which is not a valid code. +func (c InviteCode) IsZero() bool { return c.s == "" } -func (h inviteHash) String() string { return h.s } -func (inviteHash) isInviteHash() {} +// InviteHash identifies an invite in a repository. Get one from +// InviteCode.Hash or, for stored data, ParseInviteHash. +type InviteHash struct{ s string } var inviteHashRe = regexp.MustCompile(`^[0-9a-f]{64}$`) // ParseInviteHash checks a hash read back from a repository. func ParseInviteHash(s string) (InviteHash, error) { if !inviteHashRe.MatchString(s) { - return nil, fmt.Errorf("invalid invite hash %q", s) + return InviteHash{}, fmt.Errorf("invalid invite hash %q", s) } - return inviteHash{s: s}, nil + return InviteHash{s: s}, nil } -func hashInvite(code InviteCode) InviteHash { - sum := sha256.Sum256([]byte(code.Secret())) - return inviteHash{s: hex.EncodeToString(sum[:])} -} +func (h InviteHash) String() string { return h.s } + +// IsZero reports whether h is the zero value, which is not a valid hash. +func (h InviteHash) IsZero() bool { return h.s == "" } // Invite lets whoever holds its code connect or disconnect one profile. type Invite interface { diff --git a/internal/account/profileid.go b/internal/account/profileid.go index 6b73be7..c9d7850 100644 --- a/internal/account/profileid.go +++ b/internal/account/profileid.go @@ -5,30 +5,28 @@ import ( "regexp" ) -// Value types in this package are interfaces with an unexported marker method, so -// only this package implements them and every value went through one of its -// constructors. Their implementations are small comparable structs: two -// values are equal with == exactly when they hold the same text. +// Value types in this package (ProfileID, InviteCode, InviteHash) are opaque +// structs: their fields are unexported, so other packages get a valid value +// only from a Parse function. The only value they can make themselves is the +// zero value, which every function here rejects (see IsZero). Two values are +// equal with == exactly when they hold the same text. // ProfileID identifies a profile: 1-63 lower-case letters, digits and dashes. // Adapters may use String() in file and key names. Get one from // ParseProfileID. -type ProfileID interface { - String() string - isProfileID() -} - -type profileID struct{ s string } - -func (p profileID) String() string { return p.s } -func (profileID) isProfileID() {} +type ProfileID struct{ s string } var profileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) // ParseProfileID checks a profile ID. func ParseProfileID(s string) (ProfileID, error) { if !profileRe.MatchString(s) { - return nil, fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) + return ProfileID{}, fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) } - return profileID{s: s}, nil + return ProfileID{s: s}, nil } + +func (p ProfileID) String() string { return p.s } + +// IsZero reports whether p is the zero value, which is not a valid ID. +func (p ProfileID) IsZero() bool { return p.s == "" } diff --git a/internal/account/profiles.go b/internal/account/profiles.go index 5658636..ff8c1ee 100644 --- a/internal/account/profiles.go +++ b/internal/account/profiles.go @@ -27,7 +27,7 @@ func (p profiles) Profile(ctx context.Context, id ProfileID) (Profile, error) { } func loadProfile(ctx context.Context, tokens Tokens, id ProfileID) (*profile, error) { - if id == nil { + if id.IsZero() { return nil, errors.New("no profile given") } c, err := tokens.Connection(ctx, id) diff --git a/internal/account/service.go b/internal/account/service.go index 83bbcd7..17184b5 100644 --- a/internal/account/service.go +++ b/internal/account/service.go @@ -117,21 +117,21 @@ func (c callback) Code() string { return c.code } func (c callback) SpotifyError() string { return c.spotifyError } func (s *service) CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) { - if id == nil { - return nil, time.Time{}, errors.New("invite needs a profile") + if id.IsZero() { + return InviteCode{}, time.Time{}, errors.New("invite needs a profile") } if ttl <= 0 { - return nil, time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) + return InviteCode{}, time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) } code := newInviteCode() now := s.clock.Now() - inv := &invite{hash: hashInvite(code), profileID: id, expires: now.Add(ttl)} + inv := &invite{hash: code.Hash(), profileID: id, expires: now.Add(ttl)} // Expired invites are removed here, so the store doesn't keep growing. if err := s.invites.PruneInvites(ctx, now); err != nil { - return nil, time.Time{}, fmt.Errorf("prune invites: %w", err) + return InviteCode{}, time.Time{}, fmt.Errorf("prune invites: %w", err) } if err := s.invites.AddInvite(ctx, inv); err != nil { - return nil, time.Time{}, fmt.Errorf("save invite: %w", err) + return InviteCode{}, time.Time{}, fmt.Errorf("save invite: %w", err) } return code, inv.expires, nil } @@ -195,8 +195,8 @@ func (s *service) FinishLogin(ctx context.Context, cb Callback) (Profile, error) if err != nil { return nil, fmt.Errorf("exchange code: %w", err) } - if tok == nil || tok.RefreshToken() == "" { - return nil, errors.New("spotify sent no refresh token") + if tok == nil { + return nil, errors.New("spotify sent no token") } // Before the invite is used up: an account that isn't allowlisted yet can // try again with the same link once the owner added it. @@ -218,10 +218,10 @@ func (s *service) FinishLogin(ctx context.Context, cb Callback) (Profile, error) } func (s *service) Disconnect(ctx context.Context, code InviteCode) (Profile, error) { - if code == nil { + if code.IsZero() { return nil, ErrInvalidInvite } - inv, err := s.takeInvite(ctx, hashInvite(code)) + inv, err := s.takeInvite(ctx, code.Hash()) if err != nil { return nil, err } @@ -232,10 +232,10 @@ func (s *service) Disconnect(ctx context.Context, code InviteCode) (Profile, err } func (s *service) checkInvite(ctx context.Context, code InviteCode) (Invite, error) { - if code == nil { + if code.IsZero() { return nil, ErrInvalidInvite } - inv, err := s.invites.Invite(ctx, hashInvite(code)) + inv, err := s.invites.Invite(ctx, code.Hash()) return s.validInvite(inv, err) } @@ -250,7 +250,7 @@ func (s *service) validInvite(inv Invite, err error) (Invite, error) { return nil, ErrInvalidInvite case err != nil: return nil, fmt.Errorf("load invite: %w", err) - case inv == nil || inv.ProfileID() == nil: + case inv == nil || inv.ProfileID().IsZero(): return nil, errors.New("load invite: repository returned an incomplete invite") case s.clock.Now().After(inv.Expires()): return nil, ErrInvalidInvite diff --git a/internal/account/tokensource.go b/internal/account/tokensource.go index 59832e2..875cb64 100644 --- a/internal/account/tokensource.go +++ b/internal/account/tokensource.go @@ -36,7 +36,7 @@ func NewTokenSource(tokens Tokens, oauth OAuth, id ProfileID, clock Clock) Token } func (ts *tokenSource) AccessToken(ctx context.Context) (string, error) { - if ts.profile == nil { + if ts.profile.IsZero() { return "", ErrNotConnected } c, err := ts.tokens.Connection(ctx, ts.profile) @@ -56,16 +56,10 @@ func (ts *tokenSource) AccessToken(ctx context.Context) (string, error) { access = c.Token().AccessToken() return c, nil } - old := c.Token().RefreshToken() - tok, err := ts.oauth.Refresh(ctx, old) + tok, err := ts.oauth.Refresh(ctx, c.Token().RefreshToken()) if err != nil { return nil, err } - if tok.RefreshToken() == "" { // Spotify kept the old one - if tok, err = NewToken(tok.AccessToken(), old, tok.Expiry()); err != nil { - return nil, err - } - } access = tok.AccessToken() return withToken(c, tok), nil }) diff --git a/internal/account/tokensource_test.go b/internal/account/tokensource_test.go index 4a87089..f4190bd 100644 --- a/internal/account/tokensource_test.go +++ b/internal/account/tokensource_test.go @@ -27,8 +27,8 @@ func expired(rt string) account.Connection { func TestAccessTokenRefreshesAndPersists(t *testing.T) { ctx := context.Background() for name, tc := range map[string]struct{ sent, stored string }{ - "rotated": {sent: "r2", stored: "r2"}, - "not sent": {sent: "", stored: "r1"}, + "rotated": {sent: "r2", stored: "r2"}, + "kept": {sent: "r1", stored: "r1"}, } { t.Run(name, func(t *testing.T) { e := newEnv(t, nil) @@ -76,7 +76,7 @@ func TestInvalidateForcesRefresh(t *testing.T) { e := newEnv(t, nil) e.connect(t, connection(token("old", "r1", e.now.Add(time.Hour)), spotifyAccount("jan", "Jan"), time.Time{})) e.oauth.refresh = func(context.Context, string) (account.Token, error) { - return token("new", "", e.now.Add(time.Hour)), nil + return token("new", "r1", e.now.Add(time.Hour)), nil } ts := e.tokens() if err := ts.Invalidate(ctx, "not-the-stored-one"); err != nil { @@ -104,7 +104,7 @@ func TestLoginDuringRefreshWins(t *testing.T) { e.oauth.refresh = func(context.Context, string) (account.Token, error) { close(refreshing) <-release - return token("old-account-access", "", e.now.Add(time.Hour)), nil + return token("old-account-access", "old-account", e.now.Add(time.Hour)), nil } refreshed := make(chan error, 1) go func() { diff --git a/internal/filestore/filestore.go b/internal/filestore/filestore.go index 0100955..d7927ef 100644 --- a/internal/filestore/filestore.go +++ b/internal/filestore/filestore.go @@ -29,8 +29,15 @@ type Store interface { } type store struct { - dir string - mu sync.Mutex + dir string + mu sync.Mutex // goroutines of this process + files locker // other processes on the same directory +} + +// locker excludes other processes from the data directory while held. Each +// platform has its own implementation (lock_unix.go, lock_other.go). +type locker interface { + lock() (release func(), err error) } // Open creates the data directory if needed. @@ -38,7 +45,7 @@ func Open(dir string) (Store, error) { if err := os.MkdirAll(filepath.Join(dir, "tokens"), 0o700); err != nil { return nil, fmt.Errorf("create data dir: %w", err) } - return &store{dir: dir}, nil + return &store{dir: dir, files: newLocker(filepath.Join(dir, ".lock"))}, nil } // connectionRecord is the on-disk format of a connection. @@ -98,7 +105,7 @@ func (r inviteRecord) invite(hash string) (account.Invite, error) { // lock takes the in-process and the cross-process lock. func (s *store) lock() (unlock func(), err error) { s.mu.Lock() - release, err := lockFile(filepath.Join(s.dir, ".lock")) + release, err := s.files.lock() if err != nil { s.mu.Unlock() return nil, fmt.Errorf("lock data dir: %w", err) @@ -107,15 +114,12 @@ func (s *store) lock() (unlock func(), err error) { } func (s *store) connectionPath(id account.ProfileID) (string, error) { - if id == nil { + // Only account.ParseProfileID makes a non-zero ID, and its rules keep + // the name safe as a file name. + if id.IsZero() { return "", errors.New("no profile given") } - // Only account.ParseProfileID creates IDs, but a type embedding one could - // still override String(); check again because it ends up in a file name. name := id.String() - if _, err := account.ParseProfileID(name); err != nil { - return "", err - } return filepath.Join(s.dir, "tokens", name+".json"), nil } @@ -229,7 +233,7 @@ func (s *store) changeInvites(fn func(map[string]inviteRecord) error) error { // AddInvite implements account.Invites. func (s *store) AddInvite(_ context.Context, i account.Invite) error { - if i == nil || i.Hash() == nil || i.ProfileID() == nil { + if i == nil || i.Hash().IsZero() || i.ProfileID().IsZero() { return errors.New("incomplete invite") } return s.changeInvites(func(inv map[string]inviteRecord) error { @@ -240,7 +244,7 @@ func (s *store) AddInvite(_ context.Context, i account.Invite) error { // Invite implements account.Invites. func (s *store) Invite(_ context.Context, h account.InviteHash) (account.Invite, error) { - if h == nil { + if h.IsZero() { return nil, account.ErrNotFound } unlock, err := s.lock() @@ -261,7 +265,7 @@ func (s *store) Invite(_ context.Context, h account.InviteHash) (account.Invite, // TakeInvite implements account.Invites. func (s *store) TakeInvite(_ context.Context, h account.InviteHash) (account.Invite, error) { - if h == nil { + if h.IsZero() { return nil, account.ErrNotFound } key := h.String() diff --git a/internal/filestore/filestore_test.go b/internal/filestore/filestore_test.go index 91996bb..01a181c 100644 --- a/internal/filestore/filestore_test.go +++ b/internal/filestore/filestore_test.go @@ -114,7 +114,7 @@ func TestRejectsBadInput(t *testing.T) { ctx := context.Background() dir := t.TempDir() s := open(t, dir) - if err := s.SaveConnection(ctx, nil, testConnection("r")); err == nil { + if err := s.SaveConnection(ctx, account.ProfileID{}, testConnection("r")); err == nil { t.Fatal("nil profile accepted") } if err := s.SaveConnection(ctx, profile, nil); err == nil { diff --git a/internal/filestore/lock_other.go b/internal/filestore/lock_other.go index d03eac7..00d7dd6 100644 --- a/internal/filestore/lock_other.go +++ b/internal/filestore/lock_other.go @@ -2,6 +2,10 @@ package filestore -// lockFile has no cross-process lock on this platform; the Store's mutex -// still protects one process. -func lockFile(string) (release func(), err error) { return func() {}, nil } +// noLock is the locker on platforms without flock: there is no cross-process +// lock, and the store's mutex still protects one process. +type noLock struct{} + +func newLocker(string) locker { return noLock{} } + +func (noLock) lock() (release func(), err error) { return func() {}, nil } diff --git a/internal/filestore/lock_unix.go b/internal/filestore/lock_unix.go index b820dd8..13533dd 100644 --- a/internal/filestore/lock_unix.go +++ b/internal/filestore/lock_unix.go @@ -7,11 +7,15 @@ import ( "syscall" ) -// lockFile takes an exclusive flock on path, creating it if needed. The lock -// belongs to this open file, so it also excludes other goroutines and +// flock takes an exclusive flock on a lock file, creating it if needed. The +// lock belongs to the open file, so it also excludes other goroutines and // processes that open the same path. -func lockFile(path string) (release func(), err error) { - f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600) +type flock struct{ path string } + +func newLocker(path string) locker { return flock{path: path} } + +func (l flock) lock() (release func(), err error) { + f, err := os.OpenFile(l.path, os.O_RDWR|os.O_CREATE, 0o600) if err != nil { return nil, err } diff --git a/internal/mcpserver/mcpserver.go b/internal/mcpserver/mcpserver.go index 65b3b4e..e2e6929 100644 --- a/internal/mcpserver/mcpserver.go +++ b/internal/mcpserver/mcpserver.go @@ -237,14 +237,14 @@ func text(s string) *mcp.CallToolResult { func formatDevice(d playback.Device) string { id := "none" - if d.ID() != nil { + if !d.ID().IsZero() { id = d.ID().String() } s := fmt.Sprintf("%s (%s, id %s)", d.Name(), d.Type(), id) if d.Active() { s += " [active]" } - if d.Restricted() || d.ID() == nil { + if d.Restricted() || d.ID().IsZero() { s += " [can't be controlled]" } return s diff --git a/internal/playback/playback.go b/internal/playback/playback.go index 8ecf827..0fe7b6a 100644 --- a/internal/playback/playback.go +++ b/internal/playback/playback.go @@ -13,35 +13,23 @@ import ( "time" ) -// The value types below (Kind, URI, DeviceID) are interfaces with an -// unexported marker method, so only this package implements them and every -// value went through one of its constructors. Their implementations are small -// comparable structs: two values are equal with == exactly when they hold the +// The value types below (Kind, URI, DeviceID) are opaque structs: their +// fields are unexported, so other packages get a valid value only from this +// package's functions. The only value they can make themselves is the zero +// value (see IsZero). Two values are equal with == exactly when they hold the // same text. // Kind is the type of a Spotify item. Get one from ParseKind, Kinds or the // Kind* functions. -type Kind interface { - String() string - // IsContext reports whether items of this kind play as a context (a list - // Spotify continues through) rather than on their own. - IsContext() bool - isKind() -} - -type kind struct{ s string } - -func (k kind) String() string { return k.s } -func (k kind) IsContext() bool { return k.s != "track" && k.s != "episode" } -func (kind) isKind() {} +type Kind struct{ s string } // The kinds this server can search for and play. -func KindTrack() Kind { return kind{"track"} } -func KindAlbum() Kind { return kind{"album"} } -func KindArtist() Kind { return kind{"artist"} } -func KindPlaylist() Kind { return kind{"playlist"} } -func KindShow() Kind { return kind{"show"} } -func KindEpisode() Kind { return kind{"episode"} } +func KindTrack() Kind { return Kind{"track"} } +func KindAlbum() Kind { return Kind{"album"} } +func KindArtist() Kind { return Kind{"artist"} } +func KindPlaylist() Kind { return Kind{"playlist"} } +func KindShow() Kind { return Kind{"show"} } +func KindEpisode() Kind { return Kind{"episode"} } // Kinds lists every Kind, in the order shown to people. func Kinds() []Kind { @@ -56,70 +44,78 @@ func ParseKind(s string) (Kind, error) { kinds := Kinds() names := make([]string, len(kinds)) for i, k := range kinds { - if k.String() == s { + if k.s == s { return k, nil } - names[i] = k.String() + names[i] = k.s } - return nil, fmt.Errorf("unknown type %q (use one of %s)", s, strings.Join(names, ", ")) + return Kind{}, fmt.Errorf("unknown type %q (use one of %s)", s, strings.Join(names, ", ")) } -// URI is a parsed spotify:: URI. Get one from ParseURI. -type URI interface { - // Kind of the URI's item. - Kind() Kind - String() string - isURI() -} +func (k Kind) String() string { return k.s } + +// IsContext reports whether items of this kind play as a context (a list +// Spotify continues through) rather than on their own. +func (k Kind) IsContext() bool { return k != KindTrack() && k != KindEpisode() } + +// IsZero reports whether k is the zero value, which is not a valid kind. +func (k Kind) IsZero() bool { return k.s == "" } -type uri struct { +// URI is a parsed spotify:: URI. Get one from ParseURI. +type URI struct { kind Kind id string } -func (u uri) Kind() Kind { return u.kind } -func (u uri) String() string { return "spotify:" + u.kind.String() + ":" + u.id } -func (uri) isURI() {} - // ParseURI parses a spotify:: URI. func ParseURI(s string) (URI, error) { parts := strings.Split(strings.TrimSpace(s), ":") if len(parts) != 3 || parts[0] != "spotify" || parts[2] == "" { - return nil, fmt.Errorf("%q is not a Spotify URI like spotify:track:", s) + return URI{}, fmt.Errorf("%q is not a Spotify URI like spotify:track:", s) } if parts[1] == "" { - return nil, fmt.Errorf("unsupported Spotify URI type %q", parts[1]) + return URI{}, fmt.Errorf("unsupported Spotify URI type %q", parts[1]) } k, err := ParseKind(parts[1]) if err != nil { - return nil, fmt.Errorf("unsupported Spotify URI type %q", parts[1]) + return URI{}, fmt.Errorf("unsupported Spotify URI type %q", parts[1]) } - return uri{kind: k, id: parts[2]}, nil + return URI{kind: k, id: parts[2]}, nil } -// DeviceID is Spotify's ID of a Connect device. Get one from ParseDeviceID. -// A nil DeviceID means the active device. -type DeviceID interface { - String() string - isDeviceID() +// Kind of the URI's item. +func (u URI) Kind() Kind { return u.kind } + +func (u URI) String() string { + if u.IsZero() { + return "" + } + return "spotify:" + u.kind.s + ":" + u.id } -type deviceID struct{ s string } +// IsZero reports whether u is the zero value, which is not a valid URI. +func (u URI) IsZero() bool { return u.id == "" } -func (d deviceID) String() string { return d.s } -func (deviceID) isDeviceID() {} +// DeviceID is Spotify's ID of a Connect device. Get one from ParseDeviceID. +// The zero DeviceID means the active device. +type DeviceID struct{ s string } // ParseDeviceID checks a device ID. func ParseDeviceID(s string) (DeviceID, error) { if strings.TrimSpace(s) == "" || strings.ContainsAny(s, " \t\r\n") { - return nil, fmt.Errorf("invalid device ID %q", s) + return DeviceID{}, fmt.Errorf("invalid device ID %q", s) } - return deviceID{s: s}, nil + return DeviceID{s: s}, nil } +func (d DeviceID) String() string { return d.s } + +// IsZero reports whether d is the zero value: no device, or the active one. +func (d DeviceID) IsZero() bool { return d.s == "" } + // Device is a Spotify Connect device. Get one from NewDevice. type Device interface { - // ID is nil for devices Spotify gives no ID; they can't be addressed. + // ID is zero for devices Spotify gives no ID; they can't be addressed. ID() DeviceID Name() string // Type is Spotify's device type, e.g. "Computer" or "Smartphone". @@ -135,7 +131,7 @@ type device struct { active, restricted bool } -// NewDevice builds a Device; id may be nil. +// NewDevice builds a Device; id may be zero. func NewDevice(id DeviceID, name, typ string, active, restricted bool) Device { return &device{id: id, name: name, typ: typ, active: active, restricted: restricted} } @@ -186,7 +182,7 @@ func WithDuration(d time.Duration) ItemOption { return func(it *item) { it.durat // NewItem builds an Item; its kind comes from uri, which is required. func NewItem(u URI, name string, opts ...ItemOption) (Item, error) { - if u == nil { + if u.IsZero() { return nil, errors.New("item has no URI") } it := &item{name: name, uri: u} @@ -251,7 +247,7 @@ type Spotify interface { Devices(ctx context.Context) ([]Device, error) // Search returns up to limit (1..MaxSearchResults) items of one kind. Search(ctx context.Context, query string, kind Kind, limit int) ([]Item, error) - // Play plays uri; a nil device means the active one. + // Play plays uri; the zero device means the active one. Play(ctx context.Context, device DeviceID, uri URI) error Resume(ctx context.Context, device DeviceID) error Pause(ctx context.Context, device DeviceID) error diff --git a/internal/playback/playback_test.go b/internal/playback/playback_test.go index 0a2f2ac..22d41af 100644 --- a/internal/playback/playback_test.go +++ b/internal/playback/playback_test.go @@ -21,11 +21,11 @@ func (f *fakeSpotify) Search(_ context.Context, q string, k Kind, limit int) ([] } func (f *fakeSpotify) cmd(name string, id DeviceID) error { s := "" - if id != nil { + if !id.IsZero() { s = id.String() } f.calls = append(f.calls, name+" "+s) - if f.noActive && id == nil { + if f.noActive && id.IsZero() { return ErrNoActiveDevice } return nil @@ -165,7 +165,7 @@ func TestValues(t *testing.T) { t.Errorf("device ID %q accepted", s) } } - if _, err := NewItem(nil, "x"); err == nil { + if _, err := NewItem(URI{}, "x"); err == nil { t.Fatal("item without URI accepted") } it := must(NewItem(must(ParseURI("spotify:track:1")), "x", WithArtists("a", "b"))) @@ -176,7 +176,7 @@ func TestValues(t *testing.T) { } func TestDeviceWithoutID(t *testing.T) { - f := &fakeSpotify{devices: []Device{NewDevice(nil, "Web Player", "Computer", false, false)}} + f := &fakeSpotify{devices: []Device{NewDevice(DeviceID{}, "Web Player", "Computer", false, false)}} if _, err := NewService(f).Pause(context.Background(), "web player"); err == nil || !strings.Contains(err.Error(), "no ID") { t.Fatalf("device without ID: %v", err) } diff --git a/internal/playback/service.go b/internal/playback/service.go index 4fc84ad..31e0c46 100644 --- a/internal/playback/service.go +++ b/internal/playback/service.go @@ -111,7 +111,7 @@ func (s *service) Search(ctx context.Context, query string, kind Kind, limit int } func (s *service) Play(ctx context.Context, selector string, uri URI) (Device, error) { - if uri == nil { + if uri.IsZero() { return nil, errors.New("no URI to play") } return s.control(ctx, selector, func(id DeviceID) error { return s.spotify.Play(ctx, id, uri) }) @@ -159,9 +159,9 @@ func (s *service) control(ctx context.Context, selector string, cmd func(DeviceI if err != nil { return nil, err } - var id DeviceID // nil: the active device + var id DeviceID // zero: the active device if dev != nil { - if id = dev.ID(); id == nil { + if id = dev.ID(); id.IsZero() { return nil, fmt.Errorf("the device %q has no ID and can't be controlled", dev.Name()) } } @@ -188,7 +188,7 @@ func (s *service) resolve(ctx context.Context, selector string) (Device, error) return nil, err } for _, d := range devs { - if (d.ID() != nil && d.ID().String() == selector) || strings.EqualFold(d.Name(), selector) { + if (!d.ID().IsZero() && d.ID().String() == selector) || strings.EqualFold(d.Name(), selector) { return d, nil } } diff --git a/internal/spotify/auth.go b/internal/spotify/auth.go index 4978e63..5ba9686 100644 --- a/internal/spotify/auth.go +++ b/internal/spotify/auth.go @@ -89,13 +89,9 @@ func (o *oauth) Refresh(ctx context.Context, refreshToken string) (account.Token if err != nil { return nil, mapOAuthError(err) } - // oauth2 copies the old refresh token when Spotify sends none; report the - // new one only if it changed. - rt := t.RefreshToken - if rt == refreshToken { - rt = "" - } - return account.NewToken(t.AccessToken, rt, t.Expiry) + // Spotify doesn't always send a new refresh token; oauth2 then keeps the + // old one, so the token always has both. + return account.NewToken(t.AccessToken, t.RefreshToken, t.Expiry) } func mapOAuthError(err error) error { diff --git a/internal/spotify/player.go b/internal/spotify/player.go index 40c1c93..ade0c3c 100644 --- a/internal/spotify/player.go +++ b/internal/spotify/player.go @@ -56,10 +56,8 @@ type wireDevice struct { } func (d wireDevice) device() playback.Device { - id, err := playback.ParseDeviceID(d.ID) - if err != nil { - id = nil // Spotify sends no ID for some devices - } + // Spotify sends no ID for some devices; they keep the zero DeviceID. + id, _ := playback.ParseDeviceID(d.ID) return playback.NewDevice(id, d.Name, d.Type, d.IsActive, d.IsRestricted) } @@ -125,7 +123,7 @@ func (p *player) Devices(ctx context.Context) ([]playback.Device, error) { // Search implements playback.Spotify. func (p *player) Search(ctx context.Context, query string, kind playback.Kind, limit int) ([]playback.Item, error) { limit = min(max(limit, 1), playback.MaxSearchResults) - if kind == nil { + if kind.IsZero() { return nil, errors.New("search needs a type") } q := url.Values{"q": {query}, "type": {kind.String()}, "limit": {strconv.Itoa(limit)}} @@ -148,7 +146,7 @@ func (p *player) Search(ctx context.Context, query string, kind playback.Kind, l } func deviceQuery(id playback.DeviceID) url.Values { - if id == nil { + if id.IsZero() { return nil } return url.Values{"device_id": {id.String()}} @@ -157,7 +155,7 @@ func deviceQuery(id playback.DeviceID) url.Values { // Play implements playback.Spotify. A track or episode plays on its own; an // album, artist, playlist or show plays as a context. func (p *player) Play(ctx context.Context, device playback.DeviceID, uri playback.URI) error { - if uri == nil { + if uri.IsZero() { return errors.New("no URI to play") } var body any = map[string]any{"uris": []string{uri.String()}} @@ -195,7 +193,7 @@ func (p *player) Previous(ctx context.Context, device playback.DeviceID) error { // Transfer implements playback.Spotify. func (p *player) Transfer(ctx context.Context, device playback.DeviceID, play bool) error { - if device == nil { + if device.IsZero() { return errors.New("transfer needs a device") } body := map[string]any{"device_ids": []string{device.String()}, "play": play} diff --git a/internal/spotify/spotify_test.go b/internal/spotify/spotify_test.go index 4afd729..c52a0cf 100644 --- a/internal/spotify/spotify_test.go +++ b/internal/spotify/spotify_test.go @@ -120,7 +120,7 @@ func TestPlayBodies(t *testing.T) { t.Errorf("%s: %+v", uri, c) } } - if err := p.Resume(ctx, nil); err != nil { + if err := p.Resume(ctx, playback.DeviceID{}); err != nil { t.Fatal(err) } if c := api.last(); c.body != "" || c.query != "" { @@ -144,14 +144,14 @@ func TestErrors(t *testing.T) { w.WriteHeader(http.StatusTooManyRequests) }, }) - if err := p.Pause(ctx, nil); !errors.Is(err, playback.ErrNoActiveDevice) { + if err := p.Pause(ctx, playback.DeviceID{}); !errors.Is(err, playback.ErrNoActiveDevice) { t.Errorf("pause: %v", err) } - if err := p.Next(ctx, nil); !errors.Is(err, playback.ErrPremiumRequired) { + if err := p.Next(ctx, playback.DeviceID{}); !errors.Is(err, playback.ErrPremiumRequired) { t.Errorf("next: %v", err) } var apiErr *Error - if err := p.Previous(ctx, nil); !errors.As(err, &apiErr) || apiErr.Status != 429 || !strings.Contains(err.Error(), "7 s") { + if err := p.Previous(ctx, playback.DeviceID{}); !errors.As(err, &apiErr) || apiErr.Status != 429 || !strings.Contains(err.Error(), "7 s") { t.Errorf("previous: %v", err) } } @@ -167,7 +167,7 @@ func TestUnauthorizedRetriesOnceWithFreshToken(t *testing.T) { w.WriteHeader(http.StatusNoContent) }, }) - if err := p.Pause(ctx, nil); err != nil { + if err := p.Pause(ctx, playback.DeviceID{}); err != nil { t.Fatal(err) } if len(tokens.invalidated) != 1 || tokens.invalidated[0] != "t1" || api.count() != 2 { @@ -226,7 +226,7 @@ func TestOAuthErrors(t *testing.T) { _, _ = io.WriteString(w, `{"error":"`+answer+`"}`) return } - _, _ = io.WriteString(w, `{"access_token":"a2","token_type":"Bearer","expires_in":3600,"refresh_token":"r1"}`) + _, _ = io.WriteString(w, `{"access_token":"a2","token_type":"Bearer","expires_in":3600}`) })) defer srv.Close() o := NewOAuth(OAuthConfig{ @@ -235,8 +235,8 @@ func TestOAuthErrors(t *testing.T) { }) tok, err := o.Refresh(ctx, "r1") - if err != nil || tok.AccessToken() != "a2" || tok.RefreshToken() != "" { - t.Fatalf("unchanged refresh token must be reported as empty: %+v %v", tok, err) + if err != nil || tok.AccessToken() != "a2" || tok.RefreshToken() != "r1" { + t.Fatalf("Spotify sent no new refresh token, so the old one must be kept: %v %v", tok, err) } answer = "invalid_grant" if _, err := o.Refresh(ctx, "r1"); !errors.Is(err, account.ErrRevoked) {