diff --git a/README.md b/README.md index 387ff60..ab27c9b 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: 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. + ```bash go test -race ./... go vet ./... diff --git a/cmd/spotify-mcp/main.go b/cmd/spotify-mcp/main.go index 7241af2..952463f 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,83 @@ 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) + // 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 } - 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.ProfileID(), 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(), }) - 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) + 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, clock) - wh := &web.Handler{ - OAuth: oc, - Store: st, - Log: log, - MeURL: "https://api.spotify.com/v1/me", - OnConnect: func(string) { client.Forget() }, + // 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().String(), "err", err) + } else if acc, ok := prof.Account(); ok { + 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: 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.ProfileID().String(), "connect_url", cfg.ConnectURL()) + 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 +142,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 +154,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..57ac663 --- /dev/null +++ b/internal/account/account.go @@ -0,0 +1,118 @@ +// 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" + "time" +) + +// 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() ProfileID + // Account is the connected Spotify account; false if none is connected. + Account() (SpotifyAccount, bool) +} + +// profile is the Profile this package builds. +type profile struct { + id ProfileID + account SpotifyAccount + connected bool + connectedAt time.Time // for Status; not part of Profile +} + +// 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 p +} + +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 p.id.String() } + +// 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, id ProfileID) (Connection, error) + // 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. 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 +} + +// 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 token, or ErrRevoked. When Spotify keeps the + // refresh token, the returned token carries the old one. + Refresh(ctx context.Context, refreshToken string) (Token, error) +} + +// Identity tells which Spotify account an access token belongs to. +type Identity interface { + // 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 new file mode 100644 index 0000000..a706fa0 --- /dev/null +++ b/internal/account/account_test.go @@ -0,0 +1,373 @@ +package account_test + +import ( + "context" + "errors" + "fmt" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/subpathdev/spotify-mcp/internal/account" + "github.com/subpathdev/spotify-mcp/internal/filestore" +) + +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 +} + +// 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) + } + 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 { + 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 token("a1", "r1", time.Now().Add(time.Hour)), nil + } + } + return nil, 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) Account(context.Context, string) (account.SpotifyAccount, error) { + if f.err != nil { + return nil, f.err + } + return spotifyAccount("jan", "Jan"), nil +} + +type env struct { + store filestore.Store + oauth *fakeOAuth + 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 := 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.svc.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.NewCallback(u.Query().Get("state"), login.Nonce(), "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.Profile().ID() != profile || !st.ConnectedAt().IsZero() { + t.Fatalf("status before: %+v %v", st, 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.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) { + 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 := 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) + } + // 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) + 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) + } + 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) + 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) + } + 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) + } + 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) + 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 { + 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.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") + } +} + +func TestParseProfileID(t *testing.T) { + for _, s := range []string{"", "A", "../x", "a/b", "-a", string(make([]byte, 64))} { + if _, err := account.ParseProfileID(s); err == nil { + t.Errorf("%q accepted", s) + } + } + 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) + } +} + +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) + } +} + +func TestEntityConstructors(t *testing.T) { + 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") + } + 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 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/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/entities.go b/internal/account/entities.go new file mode 100644 index 0000000..1635717 --- /dev/null +++ b/internal/account/entities.go @@ -0,0 +1,109 @@ +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. +// Spotify's tokens are opaque strings, not JWTs, so there is nothing to parse +// in them. +type Token interface { + AccessToken() string + RefreshToken() string + Expiry() time.Time + // String is redacted, so a token can't leak into logs by accident. + String() string +} + +type token struct { + access, refresh string + expiry time.Time +} + +// 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 needs an access and a refresh token") + } + 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 { + return nil, errors.New("connection needs a 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 new file mode 100644 index 0000000..1b5178f --- /dev/null +++ b/internal/account/invite.go @@ -0,0 +1,98 @@ +package account + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "regexp" + "time" +) + +// 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. 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}$`) + +// 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 InviteCode{}, ErrInvalidInvite + } + return InviteCode{s: s}, nil +} + +func newInviteCode() InviteCode { return InviteCode{s: randomString()} } + +// 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[:])} +} + +// IsZero reports whether c is the zero value, which is not a valid code. +func (c InviteCode) IsZero() bool { return c.s == "" } + +// 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 InviteHash{}, fmt.Errorf("invalid invite hash %q", s) + } + return InviteHash{s: s}, nil +} + +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 { + 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/profileid.go b/internal/account/profileid.go new file mode 100644 index 0000000..c9d7850 --- /dev/null +++ b/internal/account/profileid.go @@ -0,0 +1,32 @@ +package account + +import ( + "fmt" + "regexp" +) + +// 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 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 ProfileID{}, fmt.Errorf("invalid profile %q: use 1-63 lower-case letters, digits and dashes", s) + } + 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 new file mode 100644 index 0000000..ff8c1ee --- /dev/null +++ b/internal/account/profiles.go @@ -0,0 +1,41 @@ +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) { + if id.IsZero() { + return nil, errors.New("no profile given") + } + 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 new file mode 100644 index 0000000..17184b5 --- /dev/null +++ b/internal/account/service.go @@ -0,0 +1,271 @@ +package account + +import ( + "context" + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "sync" + "time" +) + +const ( + // LoginTTL is how long a started login waits for Spotify's callback. + LoginTTL = 10 * time.Minute + maxPending = 100 +) + +// 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) + // 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 + identity Identity + clock Clock + + mu sync.Mutex + pending map[string]pendingLogin // by OAuth state +} + +type pendingLogin struct { + invite InviteHash + profile ProfileID + 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, clock Clock) Service { + return &service{ + tokens: tokens, invites: invites, oauth: oauth, identity: identity, clock: clock, + pending: map[string]pendingLogin{}, + } +} + +// 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 interface { + URL() string + Nonce() 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} +} + +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) CreateInvite(ctx context.Context, id ProfileID, ttl time.Duration) (InviteCode, time.Time, error) { + if id.IsZero() { + return InviteCode{}, time.Time{}, errors.New("invite needs a profile") + } + if ttl <= 0 { + return InviteCode{}, time.Time{}, fmt.Errorf("invite TTL must be positive, got %s", ttl) + } + code := newInviteCode() + now := s.clock.Now() + 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 InviteCode{}, time.Time{}, fmt.Errorf("prune invites: %w", err) + } + if err := s.invites.AddInvite(ctx, inv); err != nil { + return InviteCode{}, 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 { + return nil, err + } + p, err := loadProfile(ctx, s.tokens, inv.ProfileID()) + if err != nil { + return nil, err + } + return status{p: p}, nil +} + +func (s *service) StartLogin(ctx context.Context, code InviteCode) (Login, error) { + inv, err := s.checkInvite(ctx, code) + if err != nil { + return nil, err + } + state, nonce, verifier := randomString(), randomString(), randomString() + now := s.clock.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 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 +} + +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()) + s.mu.Unlock() + 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" { + return nil, ErrLoginCancelled + } + 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) + if err != nil { + return nil, fmt.Errorf("exchange code: %w", err) + } + 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. + 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.clock.Now()) + if err != nil { + return nil, err + } + if _, err := s.takeInvite(ctx, p.invite); err != nil { + return nil, err + } + 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 +} + +func (s *service) Disconnect(ctx context.Context, code InviteCode) (Profile, error) { + if code.IsZero() { + return nil, ErrInvalidInvite + } + inv, err := s.takeInvite(ctx, code.Hash()) + if err != nil { + return nil, err + } + if err := s.tokens.DeleteConnection(ctx, inv.ProfileID()); err != nil { + return nil, fmt.Errorf("delete connection: %w", err) + } + return newProfile(inv.ProfileID(), nil), nil +} + +func (s *service) checkInvite(ctx context.Context, code InviteCode) (Invite, error) { + if code.IsZero() { + return nil, ErrInvalidInvite + } + inv, err := s.invites.Invite(ctx, code.Hash()) + 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 nil, ErrInvalidInvite + case err != nil: + return nil, fmt.Errorf("load invite: %w", err) + 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 + } + return inv, nil +} + +// 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..875cb64 --- /dev/null +++ b/internal/account/tokensource.go @@ -0,0 +1,91 @@ +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 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 + clock Clock +} + +// NewTokenSource returns a TokenSource for the profile. +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) { + if ts.profile.IsZero() { + return "", ErrNotConnected + } + 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 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.clock.Now()) { // refreshed by someone else meanwhile + access = c.Token().AccessToken() + return c, nil + } + tok, err := ts.oauth.Refresh(ctx, c.Token().RefreshToken()) + if err != nil { + return nil, err + } + access = tok.AccessToken() + return withToken(c, tok), 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 +} + +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 + } + 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 + } + return err +} diff --git a/internal/account/tokensource_test.go b/internal/account/tokensource_test.go new file mode 100644 index 0000000..f4190bd --- /dev/null +++ b/internal/account/tokensource_test.go @@ -0,0 +1,135 @@ +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, clockFunc(func() time.Time { return e.now })) +} + +func expired(rt string) account.Connection { + return connection(token("old", rt, time.Time{}), spotifyAccount("jan", "Jan"), time.Time{}) +} + +func TestAccessTokenRefreshesAndPersists(t *testing.T) { + ctx := context.Background() + for name, tc := range map[string]struct{ sent, stored string }{ + "rotated": {sent: "r2", stored: "r2"}, + "kept": {sent: "r1", 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 token("new", tc.sent, 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.Account().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 nil, 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) + 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", "r1", 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 token("old-account-access", "old-account", e.now.Add(time.Hour)), nil + } + refreshed := make(chan error, 1) + go func() { + _, err := e.tokens().AccessToken(ctx) + refreshed <- err + }() + <-refreshing + + 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 { + 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.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 new file mode 100644 index 0000000..7b9e963 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,142 @@ +// 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. 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() 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"), + } + + raw := get("SPOTIFY_REDIRECT_URI", "") + if raw == "" { + return nil, errors.New("SPOTIFY_REDIRECT_URI is not set (see .env.example)") + } + redirect, err := parseHTTPURL(raw) + if err != nil { + return nil, fmt.Errorf("SPOTIFY_REDIRECT_URI: %w", err) + } + if redirect.Path != "/callback" { + return nil, 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 nil, fmt.Errorf("PUBLIC_URL: %w", err) + } + } + + if c.profileID, err = account.ParseProfileID(get("PROFILE", "default")); err != nil { + return nil, fmt.Errorf("PROFILE: %w", err) + } + return c, nil +} + +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 +} + +func (c *config) InviteURL(code account.InviteCode) string { + u := c.publicURL.JoinPath("connect") + u.RawQuery = url.Values{"invite": {code.Secret()}}.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..404add0 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,70 @@ +package config + +import ( + "fmt" + "strings" + "testing" + + "github.com/subpathdev/spotify-mcp/internal/account" +) + +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.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) + } + 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) + } +} + +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": {}, + "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) + } + } +} + +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 new file mode 100644 index 0000000..d7927ef --- /dev/null +++ b/internal/filestore/filestore.go @@ -0,0 +1,344 @@ +// 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 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 // 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. +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, files: newLocker(filepath.Join(dir, ".lock"))}, 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, 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 +} + +// 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 +// invite hash (hex) to it. +type inviteRecord struct { + Profile string `json:"profile"` + Expires time.Time `json:"expires"` +} + +func (r inviteRecord) invite(hash string) (account.Invite, error) { + inv, err := account.RestoreInvite(hash, r.Profile, r.Expires) + if err != nil { + return nil, fmt.Errorf("invite %s: %w", hash, err) + } + return inv, nil +} + +// lock takes the in-process and the cross-process lock. +func (s *store) lock() (unlock func(), err error) { + s.mu.Lock() + release, err := s.files.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(id account.ProfileID) (string, error) { + // 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") + } + name := id.String() + return filepath.Join(s.dir, "tokens", name+".json"), nil +} + +// Connection implements account.Tokens. +func (s *store) Connection(_ context.Context, id account.ProfileID) (account.Connection, error) { + path, err := s.connectionPath(id) + if err != nil { + return nil, err + } + unlock, err := s.lock() + if err != nil { + return nil, err + } + defer unlock() + var r connectionRecord + if err := readJSON(path, &r); err != nil { + return nil, err + } + return r.connection() +} + +// SaveConnection implements account.Tokens. +func (s *store) SaveConnection(_ context.Context, id account.ProfileID, c account.Connection) error { + path, err := s.connectionPath(id) + if err != nil { + return err + } + unlock, err := s.lock() + if err != nil { + return err + } + defer unlock() + 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) (account.Connection, error)) error { + path, err := s.connectionPath(id) + 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, 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, r) +} + +// DeleteConnection implements account.Tokens. +func (s *store) DeleteConnection(_ context.Context, id account.ProfileID) error { + path, err := s.connectionPath(id) + 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[string]inviteRecord, error) { + inv := map[string]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[string]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 { + if i == nil || i.Hash().IsZero() || i.ProfileID().IsZero() { + 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.IsZero() { + return nil, account.ErrNotFound + } + unlock, err := s.lock() + if err != nil { + return nil, err + } + defer unlock() + inv, err := s.loadInvites() + if err != nil { + return nil, err + } + r, ok := inv[h.String()] + if !ok { + return nil, account.ErrNotFound + } + return r.invite(h.String()) +} + +// TakeInvite implements account.Invites. +func (s *store) TakeInvite(_ context.Context, h account.InviteHash) (account.Invite, error) { + if h.IsZero() { + return nil, account.ErrNotFound + } + key := h.String() + var out account.Invite + err := s.changeInvites(func(inv map[string]inviteRecord) error { + r, ok := inv[key] + if !ok { + return account.ErrNotFound + } + i, err := r.invite(key) + if err != nil { + return err // nothing is written, so the invite stays until it expires + } + delete(inv, key) + out = i + 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[string]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..01a181c --- /dev/null +++ b/internal/filestore/filestore_test.go @@ -0,0 +1,208 @@ +package filestore + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/subpathdev/spotify-mcp/internal/account" +) + +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 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 { + 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 := testConnection("r") + 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 { + 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 { + t.Fatal(err) + } + } +} + +func TestUpdateConnection(t *testing.T) { + ctx := context.Background() + s := open(t, t.TempDir()) + 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, testConnection("r1")) + boom := errors.New("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" { + t.Fatalf("failed update was written: %+v", c) + } +} + +func TestRejectsBadInput(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + s := open(t, dir) + 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 { + 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) { + ctx := context.Background() + dir := t.TempDir() + s := open(t, dir) + 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, inv.Hash()); err != nil || got.ProfileID() != profile || got.Hash() != inv.Hash() { + 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, inv.Hash()); 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() { + 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, testInvite(t, i, time.Now()).Hash()); 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() + 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.Hash()); !errors.Is(err, account.ErrNotFound) { + t.Fatalf("expired invite kept: %v", err) + } + if _, err := s.Invite(ctx, cur.Hash()); 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..00d7dd6 --- /dev/null +++ b/internal/filestore/lock_other.go @@ -0,0 +1,11 @@ +//go:build !unix + +package filestore + +// 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 new file mode 100644 index 0000000..13533dd --- /dev/null +++ b/internal/filestore/lock_unix.go @@ -0,0 +1,27 @@ +//go:build unix + +package filestore + +import ( + "os" + "syscall" +) + +// 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. +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 + } + 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..e2e6929 --- /dev/null +++ b/internal/mcpserver/mcpserver.go @@ -0,0 +1,272 @@ +// 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. 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) + 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() + } + 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) { + 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 + } + 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) { + 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 { + id := "none" + 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().IsZero() { + s += " [can't be controlled]" + } + return s +} + +func formatItem(it playback.Item) string { + 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.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..818611d --- /dev/null +++ b/internal/mcpserver/mcpserver_test.go @@ -0,0 +1,164 @@ +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 +} + +func must[T any](v T, err error) T { + if err != nil { + panic(err) + } + return v +} + +var ( + 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) } + +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.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 + " " + k.String()) + 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 + " " + k.String()) + 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..0fe7b6a --- /dev/null +++ b/internal/playback/playback.go @@ -0,0 +1,259 @@ +// 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" +) + +// 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 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"} } + +// Kinds lists every Kind, in the order shown to people. +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 + } + kinds := Kinds() + names := make([]string, len(kinds)) + for i, k := range kinds { + if k.s == s { + return k, nil + } + names[i] = k.s + } + return Kind{}, fmt.Errorf("unknown type %q (use one of %s)", s, strings.Join(names, ", ")) +} + +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 == "" } + +// URI is a parsed spotify:: URI. Get one from ParseURI. +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) + } + if parts[1] == "" { + return URI{}, fmt.Errorf("unsupported Spotify URI type %q", parts[1]) + } + k, err := ParseKind(parts[1]) + if err != nil { + 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 } + +func (u URI) String() string { + if u.IsZero() { + return "" + } + return "spotify:" + u.kind.s + ":" + u.id +} + +// IsZero reports whether u is the zero value, which is not a valid URI. +func (u URI) IsZero() bool { return u.id == "" } + +// 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 DeviceID{}, fmt.Errorf("invalid device ID %q", s) + } + 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 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". + Type() string + Active() bool + // Restricted devices don't accept commands from the Web API. + Restricted() bool +} + +type device struct { + id DeviceID + name, typ string + active, restricted bool +} + +// 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} +} + +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 is the owner of a playlist. + Owner() string + Duration() 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.IsZero() { + 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 + +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; 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 + 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..22d41af --- /dev/null +++ b/internal/playback/playback_test.go @@ -0,0 +1,183 @@ +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+" "+k.String()) + return f.results[:min(limit, len(f.results))], nil +} +func (f *fakeSpotify) cmd(name string, id DeviceID) error { + s := "" + if !id.IsZero() { + s = id.String() + } + f.calls = append(f.calls, name+" "+s) + if f.noActive && id.IsZero() { + 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 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{ + dev("pc1", "mobile", "Computer"), + dev("ph1", "Jan's Pixel 8", "Smartphone"), + dev("sp1", "Kitchen speaker", "Speaker"), + dev("sp2", "Bath speaker", "Speaker"), + } +} + +func TestResolveDevice(t *testing.T) { + ctx := context.Background() + f := &fakeSpotify{devices: devices()} + s := NewService(f) + 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 "+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) { + 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 { + 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().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() { + 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") + } +} + +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(URI{}, "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(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 new file mode 100644 index 0000000..31e0c46 --- /dev/null +++ b/internal/playback/service.go @@ -0,0 +1,206 @@ +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; 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} } + +// 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, ", ") +} + +func (s *service) Devices(ctx context.Context) ([]Device, error) { + return s.spotify.Devices(ctx) +} + +func (s *service) NowPlaying(ctx context.Context) (State, error) { + return s.spotify.State(ctx) +} + +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) +} + +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) }) +} + +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 nil, nil, err + } + if len(items) == 0 { + return nil, nil, fmt.Errorf("nothing found for %q", query) + } + dev, err := s.Play(ctx, selector, items[0].URI()) + return items[0], dev, err +} + +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) }) +} + +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) }) +} + +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) }) +} + +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) }) +} + +func (s *service) Transfer(ctx context.Context, selector string, play bool) (Device, error) { + if strings.TrimSpace(selector) == "" { + return nil, errors.New("a device is required; call the devices tool to see the names") + } + 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) { + dev, err := s.resolve(ctx, selector) + if err != nil { + return nil, err + } + var id DeviceID // zero: the active device + if dev != nil { + if id = dev.ID(); id.IsZero() { + 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) { + 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 (!d.ID().IsZero() && 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) { + 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..fd6781e --- /dev/null +++ b/internal/spotify/api.go @@ -0,0 +1,153 @@ +// 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/account" + "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. 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 { + 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..5ba9686 --- /dev/null +++ b/internal/spotify/auth.go @@ -0,0 +1,125 @@ +package spotify + +import ( + "context" + "errors" + "net/http" + + "golang.org/x/oauth2" + + "github.com/subpathdev/spotify-mcp/internal/account" +) + +// 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. +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. +type OAuthConfig struct { + ClientID string + ClientSecret string + RedirectURL string + Endpoint oauth2.Endpoint // DefaultEndpoint() if empty + HTTPClient *http.Client // may be nil +} + +type oauth struct { + cfg oauth2.Config + http *http.Client +} + +// NewOAuth returns Spotify's authorization server as account.OAuth. +func NewOAuth(cfg OAuthConfig) account.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 nil, mapOAuthError(err) + } + 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) { + t, err := o.cfg.TokenSource(o.ctx(ctx), &oauth2.Token{RefreshToken: refreshToken}).Token() + if err != nil { + return nil, mapOAuthError(err) + } + // 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 { + 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 +} + +// 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) { + 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 nil, account.ErrNotAllowlisted + } + if err != nil { + return nil, err + } + return account.NewSpotifyAccount(out.ID, out.DisplayName) +} 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..ade0c3c --- /dev/null +++ b/internal/spotify/player.go @@ -0,0 +1,231 @@ +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 +} + +type player struct { + api API + tokens TokenSource +} + +// 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) { + 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 { + // 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) +} + +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 nil, false + } + 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: + opts = append(opts, playback.WithAlbum(w.Album.Name)) + case w.Show != nil: + opts = append(opts, playback.WithAlbum(w.Show.Name)) + } + if w.Owner != nil { + opts = append(opts, playback.WithOwner(w.Owner.DisplayName)) + } + 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) { + 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) + if kind.IsZero() { + 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"` + } + 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[kind.String()+"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.IsZero() { + return nil + } + 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 { + if uri.IsZero() { + 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()} + } + _, 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 { + if device.IsZero() { + 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) { + 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 + } + var dev playback.Device + if out.Device != nil { + dev = out.Device.device() + } + var it playback.Item + if out.Item != nil { + if i, ok := out.Item.item(); ok { + it = i + } + } + 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 new file mode 100644 index 0000000..c52a0cf --- /dev/null +++ b/internal/spotify/spotify_test.go @@ -0,0 +1,257 @@ +package spotify + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "slices" + "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) (playback.Spotify, *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 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) + 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, mustDevice(t, "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, playback.DeviceID{}); err != nil { + t.Fatal(err) + } + if c := api.last(); c.body != "" || c.query != "" { + t.Errorf("resume: %+v", c) + } + 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}` { + 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, playback.DeviceID{}); !errors.Is(err, playback.ErrNoActiveDevice) { + t.Errorf("pause: %v", err) + } + 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, playback.DeviceID{}); !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, playback.DeviceID{}); 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 %v", it.Name(), it.URI()) + } +} + +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 TestAccountNotAllowlisted(t *testing.T) { + srv := httptest.NewServer(spotifyError(http.StatusForbidden, "")) + defer srv.Close() + if _, err := NewAPI(srv.URL, srv.Client()).Account(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}`) + })) + 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() != "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) { + 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) + } +} + +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/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..b34f679 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.Profile, 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 handler struct { + c Connector + log *slog.Logger } -type pendingLogin struct { - profile string - invite string - verifier string - nonce string - expires time.Time -} - -// 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,55 @@ 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) connectPage(w http.ResponseWriter, r *http.Request) { + code, err := account.ParseInviteCode(r.URL.Query().Get("invite")) + if err != nil { + h.fail(w, err) + return } -} - -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) + 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") + acc, connected := st.Profile().Account() + d := pageData{Title: "Connect Spotify", Invite: code.Secret(), ShowForm: true, Connected: connected} + if connected { + d.Name = acc.Name() + if at := st.ConnectedAt(); !at.IsZero() { + d.Since = at.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, err := account.ParseInviteCode(r.PostForm.Get("invite")) + if err != nil { + h.fail(w, err) + return + } 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) - 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) + h.fail(w, err) return } - h.Log.Info("spotify account disconnected", "profile", profile) - if h.OnConnect != nil { - h.OnConnect(profile) - } + 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.", @@ -215,154 +123,95 @@ 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 - } - 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 + var nonce string + if c, err := r.Cookie(cookieName); err == nil { + nonce = c.Value } - ctx := h.httpCtx(r.Context()) - tok, err := h.OAuth.Exchange(ctx, q.Get("code"), oauth2.VerifierOption(p.verifier)) + 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.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) - 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) + h.fail(w, err) 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) - 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 - } msg := "Spotify is connected. You can close this page." - if 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}) } -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, + }) +} + +type pageData struct { + Title string + Message string + Error bool + ShowForm bool + Invite string + Connected bool + Name string + Since string } -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}} -
- - -`)) +//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..a3eb707 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,232 @@ 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.NewToken("a", "r", time.Now().Add(time.Hour)) } - _, _ = 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 nil, errors.New("bad code") +} + +func (f *fakeOAuth) Refresh(context.Context, string) (account.Token, error) { + return nil, errors.New("unused") +} + +type fakeIdentity struct{ err error } + +func (f *fakeIdentity) Account(context.Context, string) (account.SpotifyAccount, error) { + if f.err != nil { + return nil, f.err + } + return account.NewSpotifyAccount("jan", "Jan") } type env struct { - st *store.Store - acc *fakeAccounts - web *httptest.Server - browser *http.Client - changed []string + svc account.Service + srv *httptest.Server + 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()) + if err != nil { + t.Fatal(err) + } + id := &fakeIdentity{} + 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{svc: svc, srv: srv, 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 { +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() + code, _, err := e.svc.CreateInvite(context.Background(), profile, 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 code.Secret() +} + +// 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(), profile); 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(), profile); !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) } }