Files

519 lines
20 KiB
Go
Raw Permalink Normal View History

package api
import (
2026-08-06 22:33:56 +12:00
"context"
"encoding/json"
2026-08-25 11:39:55 +12:00
"errors"
2026-08-14 09:40:03 +12:00
"fmt"
"net/http"
2026-08-14 09:40:03 +12:00
"net/url"
"strings"
2026-08-02 22:10:19 +12:00
"time"
2026-08-25 11:39:55 +12:00
"golang.org/x/crypto/bcrypt"
2026-08-14 09:40:03 +12:00
"github.com/ponzischeme89/memby/server/internal/adminevents"
"github.com/ponzischeme89/memby/server/internal/cache"
2026-07-27 21:06:51 +12:00
"github.com/ponzischeme89/memby/server/internal/emby"
"github.com/ponzischeme89/memby/server/internal/store"
)
type loginRequest struct {
2026-07-27 21:06:51 +12:00
Username string `json:"username"`
Password string `json:"password"`
DeviceID string `json:"deviceId"`
DeviceName string `json:"deviceName"`
}
type loginResponse struct {
2026-08-02 22:10:19 +12:00
Token string `json:"token"`
UserID string `json:"userId"`
Username string `json:"username"`
ServerID string `json:"serverId"`
2026-07-27 21:06:51 +12:00
}
2026-08-02 22:10:19 +12:00
type deviceSessionResponse struct {
DeviceID string `json:"deviceId"`
DeviceName string `json:"deviceName"`
ClientVersion string `json:"clientVersion,omitempty"`
LastSeenAt time.Time `json:"lastSeenAt"`
Current bool `json:"current"`
2026-07-27 21:06:51 +12:00
}
2026-08-02 22:10:19 +12:00
type renameDeviceRequest struct {
DeviceName string `json:"deviceName"`
}
2026-08-25 11:39:55 +12:00
type recoveryRequest struct {
DeviceID string `json:"deviceId"`
ViewerID string `json:"viewerId"`
PIN string `json:"pin"`
}
type recoveryProfileResponse struct {
DeviceID string `json:"deviceId"`
DeviceName string `json:"deviceName"`
UserID string `json:"userId"`
Username string `json:"username"`
Viewer store.Viewer `json:"viewer"`
}
// handleLogin exchanges Emby credentials for a gateway token.
//
// The Emby access token stays here: the TV only ever holds the gateway token, so
// revoking a device is a DELETE in Postgres rather than an Emby-side cleanup.
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
var req loginRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<10)).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "malformed request body")
return
}
req.Username = strings.TrimSpace(req.Username)
if req.Username == "" {
writeError(w, http.StatusBadRequest, "username is required")
return
}
if req.DeviceID == "" {
req.DeviceID = "memby-tv"
}
2026-07-27 21:06:51 +12:00
req.DeviceName = strings.TrimSpace(req.DeviceName)
if req.DeviceName == "" {
// Compatibility for APKs released before device naming. New clients require an
// editable name in their UI, but an older TV must still be able to sign in while
// the household rollout is in progress.
2026-08-06 22:33:56 +12:00
req.DeviceName = store.DefaultDeviceName
2026-07-27 21:06:51 +12:00
}
if len([]rune(req.DeviceName)) > 80 {
writeError(w, http.StatusBadRequest, "device name is too long")
return
}
2026-08-27 07:31:57 +12:00
log := s.loggerFor(r.Context()).With(
"emby_client", s.cfg.ClientName,
"device", req.DeviceName,
"device_id", req.DeviceID,
"client_version", clientVersion(r),
)
log.Info("Emby client registration starting")
2026-07-27 21:06:51 +12:00
auth, err := s.emby.Authenticate(
2026-08-12 13:08:53 +12:00
r.Context(), req.Username, req.Password,
emby.Credentials{
DeviceID: req.DeviceID, DeviceName: req.DeviceName,
ClientVersion: clientVersion(r),
},
2026-07-27 21:06:51 +12:00
)
if err != nil {
// Never echo Emby's body here: a failed sign-in is the one place a wrong
// password could be reflected back.
2026-08-27 07:31:57 +12:00
log.Warn("sign-in rejected",
2026-08-06 22:33:56 +12:00
"username", req.Username, "device", req.DeviceName, "device_id", req.DeviceID,
"reason", "emby refused the credentials",
)
2026-08-14 09:40:03 +12:00
// A refused attempt has no verified identity, so it carries the name that was
// typed and no user id. It is recorded precisely because a run of these against
// one name is the thing worth noticing, and nothing else in the gateway keeps it.
s.recordLogin(r, store.LoginEvent{
Username: req.Username,
DeviceID: req.DeviceID,
DeviceName: req.DeviceName,
Success: false,
Method: store.LoginMethodPassword,
// Emby's reason is deliberately not carried through: it distinguishes
// "no such user" from "wrong password", which is more than an operator's
// console should restate about somebody else's failed attempt.
FailureReason: "credentials refused",
})
s.publishAdmin(r.Context(), adminevents.Event{
Type: adminevents.TypeLoginFailed,
Severity: adminevents.SeverityWarning,
Title: "Sign-in refused",
Summary: fmt.Sprintf("%s was refused on %s",
displayName(req.Username), displayName(req.DeviceName)),
Actor: req.Username, Target: req.DeviceName,
Link: "/admin/logins",
Metadata: adminevents.Meta(map[string]any{
2026-08-28 23:00:02 +12:00
"deviceId": req.DeviceID, "ip": s.resolveClientIP(r).String(),
2026-08-14 09:40:03 +12:00
}),
})
writeError(w, http.StatusUnauthorized, "sign-in failed")
return
}
2026-08-14 09:40:03 +12:00
// Asked before the attempt is recorded, so this sign-in cannot answer for itself:
// "new device registered" is only distinguishable from every later sign-in by the
// same set if the history is consulted while it still predates this one.
knownDevice, lookupErr := s.store.DeviceHasLoggedIn(r.Context(), auth.User.ID, req.DeviceID)
if lookupErr != nil {
s.loggerFor(r.Context()).Warn("device history lookup failed", "error", lookupErr)
// Assume known. Announcing a device as new because a query failed is a claim; not
// announcing one is a missed line.
knownDevice = true
}
token, err := newToken()
if err != nil {
s.log.Error("token generation failed", "error", err)
writeError(w, http.StatusInternalServerError, "could not issue a token")
return
}
sess := store.Session{
2026-08-02 22:10:19 +12:00
TokenHash: hashToken(token),
EmbyUserID: auth.User.ID,
EmbyToken: auth.AccessToken,
Username: auth.User.Name,
ServerID: auth.ServerID,
DeviceID: req.DeviceID,
DeviceName: req.DeviceName,
ClientVersion: clientVersion(r),
ClientProtocol: clientProtocol(r),
ClientCapabilities: clientCapabilities(r),
}
if sess.Username == "" {
sess.Username = req.Username
}
2026-08-06 22:33:56 +12:00
created, err := s.store.CreateSession(r.Context(), sess)
2026-07-27 21:06:51 +12:00
if err != nil {
_ = s.emby.Logout(r.Context(), emby.Credentials{
UserID: auth.User.ID, Token: auth.AccessToken,
DeviceID: req.DeviceID, DeviceName: req.DeviceName,
2026-08-06 22:33:56 +12:00
ClientVersion: sess.ClientVersion,
2026-07-27 21:06:51 +12:00
})
s.log.Error("session persist failed", "error", err)
writeError(w, http.StatusInternalServerError, "could not start a session")
return
}
2026-08-06 22:33:56 +12:00
if len(created.ReplacedHash) > 0 {
_ = s.cache.Delete(r.Context(), cache.SessionKey(hexHash(created.ReplacedHash)))
}
2026-08-27 07:31:57 +12:00
log.Info("Emby client registration succeeded",
"user", sess.Username,
"user_id", sess.EmbyUserID,
"replaced", len(created.ReplacedHash) > 0,
)
2026-08-06 22:33:56 +12:00
s.retireSupersededDevices(r.Context(), created.Superseded)
// Recorded after the session exists, so a build history can only describe a
// television that got as far as signing in.
if err := s.store.RecordDeviceVersion(r.Context(), sess.DeviceID, sess.ClientVersion); err != nil {
s.loggerFor(r.Context()).Warn("device version record failed",
"device_id", sess.DeviceID, "error", err)
2026-07-27 21:06:51 +12:00
}
2026-07-29 15:26:27 +12:00
if s.forYou != nil {
s.forYou.MarkDirty(r.Context(), sess)
s.forYou.RefreshAsync(sess, false)
}
2026-08-06 22:33:56 +12:00
// Now that the session exists, the request line this call ends with can name it too.
identify(r.Context(), sess)
2026-08-28 23:00:02 +12:00
origin := s.resolveClientIP(r)
2026-08-06 22:33:56 +12:00
s.loggerFor(r.Context()).Info("signed in",
"emby_user", sess.EmbyUserID,
"device_id", sess.DeviceID,
"protocol", clientLogValue(sess.ClientProtocol),
"replaced_session", len(created.ReplacedHash) > 0,
2026-08-28 23:00:02 +12:00
"client_ip", origin.String(),
"client_ip_via", origin.Via,
2026-08-06 22:33:56 +12:00
)
2026-08-28 23:00:02 +12:00
address := origin.String()
2026-08-14 09:40:03 +12:00
s.recordLogin(r, store.LoginEvent{
EmbyUserID: sess.EmbyUserID, Username: sess.Username,
DeviceID: sess.DeviceID, DeviceName: sess.DeviceName,
ClientVersion: sess.ClientVersion, ClientProtocol: sess.ClientProtocol,
Success: true, Method: store.LoginMethodPassword, NewDevice: !knownDevice,
})
// A television arriving for the first time and one signing in again are the same
// request and different news, which is why they are different event types rather than
// one type with a flag: an operator subscribing a Discord channel to new devices is
// asking for the rare one, and would not want the other.
if knownDevice {
s.publishAdmin(r.Context(), adminevents.Event{
Type: adminevents.TypeLogin,
Title: "Signed in",
Summary: fmt.Sprintf("%s signed in on %s",
displayName(sess.Username), displayName(sess.DeviceName)),
Actor: sess.Username, Target: sess.DeviceName,
Link: "/admin/devices/" + url.PathEscape(sess.DeviceID),
Metadata: adminevents.Meta(map[string]any{
"deviceId": sess.DeviceID, "userId": sess.EmbyUserID,
"ip": address, "version": sess.ClientVersion,
}),
})
} else {
s.publishAdmin(r.Context(), adminevents.Event{
Type: adminevents.TypeDeviceRegistered,
Title: "New device registered",
Summary: fmt.Sprintf("%s signed in on %s for the first time",
displayName(sess.Username), displayName(sess.DeviceName)),
Actor: sess.Username, Target: sess.DeviceName,
Link: "/admin/devices/" + url.PathEscape(sess.DeviceID),
Metadata: adminevents.Meta(map[string]any{
"deviceId": sess.DeviceID, "userId": sess.EmbyUserID,
"ip": address, "version": sess.ClientVersion,
}),
})
}
writeJSON(w, http.StatusOK, loginResponse{
2026-08-02 22:10:19 +12:00
Token: token, UserID: sess.EmbyUserID, Username: sess.Username, ServerID: sess.ServerID,
})
}
2026-08-25 11:39:55 +12:00
// handleRecoveryProfiles is intentionally unauthenticated: its only credential is the
// derived device id. It returns no upstream token or PIN material.
func (s *Server) handleRecoveryProfiles(w http.ResponseWriter, r *http.Request) {
deviceID := strings.TrimSpace(r.URL.Query().Get("deviceId"))
if deviceID == "" {
writeError(w, http.StatusBadRequest, "device id is required")
return
}
profiles, err := s.store.DeviceRecoveryProfiles(r.Context(), deviceID)
if err != nil {
s.log.Error("device recovery lookup failed", "error", err)
writeError(w, http.StatusInternalServerError, "could not check this device")
return
}
out := make([]recoveryProfileResponse, 0, len(profiles))
for _, p := range profiles {
out = append(out, recoveryProfileResponse{p.DeviceID, p.DeviceName, p.UserID, p.Username, p.Viewer})
}
writeJSON(w, http.StatusOK, map[string]any{"profiles": out})
}
// handleRecovery turns a valid profile PIN into a fresh ordinary gateway session. The
// upstream Emby token remains server-side, exactly like a password sign-in.
func (s *Server) handleRecovery(w http.ResponseWriter, r *http.Request) {
var req recoveryRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "malformed request body")
return
}
profiles, err := s.store.DeviceRecoveryProfiles(r.Context(), strings.TrimSpace(req.DeviceID))
if err != nil {
writeError(w, http.StatusInternalServerError, "could not check this device")
return
}
var chosen *store.DeviceRecoveryProfile
for i := range profiles {
if profiles[i].Viewer.ID == strings.TrimSpace(req.ViewerID) {
chosen = &profiles[i]
break
}
}
if chosen == nil {
writeError(w, http.StatusUnauthorized, "profile recovery failed")
return
}
valid, pinErr := s.store.CheckViewerPIN(r.Context(), chosen.UserID, chosen.Viewer.ID, func(hash []byte) bool {
return bcrypt.CompareHashAndPassword(hash, []byte(req.PIN)) == nil
})
if pinErr != nil || !valid {
s.loggerFor(r.Context()).Warn("profile PIN rejected", "device_id", req.DeviceID, "viewer_id", req.ViewerID, "reason", pinReason(pinErr))
writeError(w, http.StatusUnauthorized, "incorrect PIN")
return
}
token, err := newToken()
if err != nil {
writeError(w, http.StatusInternalServerError, "could not issue a token")
return
}
sess := store.Session{TokenHash: hashToken(token), EmbyUserID: chosen.UserID, EmbyToken: chosen.EmbyToken, Username: chosen.Username, ServerID: chosen.ServerID, DeviceID: chosen.DeviceID, DeviceName: chosen.DeviceName, ClientVersion: clientVersion(r), ClientProtocol: clientProtocol(r), ClientCapabilities: clientCapabilities(r)}
created, err := s.store.CreateSession(r.Context(), sess)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not start a session")
return
}
if len(created.ReplacedHash) > 0 {
_ = s.cache.Delete(r.Context(), cache.SessionKey(hexHash(created.ReplacedHash)))
}
s.cacheSession(r.Context(), sess)
s.recordLogin(r, store.LoginEvent{EmbyUserID: sess.EmbyUserID, Username: sess.Username, DeviceID: sess.DeviceID, DeviceName: sess.DeviceName, ClientVersion: sess.ClientVersion, Success: true, Method: store.LoginMethodPIN})
writeJSON(w, http.StatusOK, loginResponse{Token: token, UserID: sess.EmbyUserID, Username: sess.Username, ServerID: sess.ServerID})
}
func pinReason(err error) string {
if errors.Is(err, store.ErrPINLocked) {
return "temporarily locked"
}
return "invalid"
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request, sess store.Session) {
if err := s.store.DeleteSession(r.Context(), sess.TokenHash); err != nil {
s.log.Error("session delete failed", "error", err)
}
_ = s.cache.Delete(r.Context(), cache.SessionKey(hexHash(sess.TokenHash)))
2026-08-20 15:06:00 +12:00
s.invalidateAccountViews(r.Context(), sess)
2026-08-06 22:33:56 +12:00
s.loggerFor(r.Context()).Info("signed out", "device_id", sess.DeviceID)
2026-08-14 09:40:03 +12:00
s.publishAdmin(r.Context(), adminevents.Event{
Type: adminevents.TypeLogout,
Title: "Signed out",
Summary: fmt.Sprintf("%s signed out on %s",
displayName(sess.Username), displayName(sess.DeviceName)),
Actor: sess.Username, Target: sess.DeviceName,
Link: "/admin/devices/" + url.PathEscape(sess.DeviceID),
Metadata: adminevents.Meta(map[string]any{"deviceId": sess.DeviceID}),
})
w.WriteHeader(http.StatusNoContent)
}
// handleSession lets the TV confirm a stored token is still good before rendering.
func (s *Server) handleSession(w http.ResponseWriter, _ *http.Request, sess store.Session) {
writeJSON(w, http.StatusOK, loginResponse{
2026-08-02 22:10:19 +12:00
UserID: sess.EmbyUserID, Username: sess.Username, ServerID: sess.ServerID,
})
}
2026-08-02 22:10:19 +12:00
func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request, current store.Session) {
sessions, err := s.store.SessionsForUser(r.Context(), current.EmbyUserID)
if err != nil {
s.log.Error("device list failed", "error", err)
writeError(w, http.StatusInternalServerError, "could not list devices")
return
}
devices := make([]deviceSessionResponse, 0, len(sessions))
for _, sess := range sessions {
devices = append(devices, deviceSessionResponse{
DeviceID: sess.DeviceID, DeviceName: sess.DeviceName,
ClientVersion: sess.ClientVersion, LastSeenAt: sess.LastSeenAt,
Current: string(sess.TokenHash) == string(current.TokenHash),
})
}
writeJSON(w, http.StatusOK, map[string]any{"devices": devices})
}
func (s *Server) handleDeleteDevice(w http.ResponseWriter, r *http.Request, current store.Session) {
deviceID := strings.TrimSpace(r.PathValue("deviceID"))
if deviceID == "" {
writeError(w, http.StatusBadRequest, "device id is required")
return
}
if deviceID == current.DeviceID {
writeError(w, http.StatusBadRequest, "sign out to remove the current device")
return
}
tokenHash, err := s.store.DeleteUserDevice(r.Context(), current.EmbyUserID, deviceID)
if err == store.ErrNotFound {
writeError(w, http.StatusNotFound, "device not found")
return
}
if err != nil {
s.log.Error("device revoke failed", "error", err)
writeError(w, http.StatusInternalServerError, "could not remove device")
return
}
_ = s.cache.Delete(r.Context(), cache.SessionKey(hexHash(tokenHash)))
2026-08-06 22:33:56 +12:00
s.retireEmbyDevice(r.Context(), deviceID)
if err := s.store.DeleteDeviceVersions(r.Context(), deviceID); err != nil {
s.loggerFor(r.Context()).Warn("device version cleanup failed",
"removed_device_id", deviceID, "error", err)
}
2026-08-17 19:09:17 +12:00
if err := s.store.DeleteDeviceActivityDays(r.Context(), deviceID); err != nil {
s.loggerFor(r.Context()).Warn("device activity cleanup failed",
"removed_device_id", deviceID, "error", err)
}
2026-08-06 22:33:56 +12:00
// A device disappearing from a household is worth a line: the next thing that TV
// reports is a sign-in, and the two together explain each other.
s.loggerFor(r.Context()).Info("device signed out remotely", "removed_device_id", deviceID)
2026-08-14 09:40:03 +12:00
s.publishAdmin(r.Context(), adminevents.Event{
Type: adminevents.TypeDeviceRemoved,
Severity: adminevents.SeverityWarning,
Title: "Device removed",
Summary: fmt.Sprintf("%s removed a device from their account",
displayName(current.Username)),
Actor: current.Username, Target: deviceID,
Link: "/admin/devices",
Metadata: adminevents.Meta(map[string]any{"deviceId": deviceID}),
})
2026-08-02 22:10:19 +12:00
w.WriteHeader(http.StatusNoContent)
}
2026-08-06 22:33:56 +12:00
// retireSupersededDevices finishes what CreateSession started: the rows for a television
// under a device id it no longer uses are already gone from Postgres, and this takes the
// rest of that identity with them — the cached session, the build history and the record
// Emby is still holding in its own devices list.
//
// Best-effort throughout, and deliberately after the sign-in has succeeded: tidying up a
// set's previous life must never be what stops it getting in.
func (s *Server) retireSupersededDevices(ctx context.Context, devices []store.SupersededDevice) {
if len(devices) == 0 {
return
}
ids := make([]string, 0, len(devices))
for _, device := range devices {
ids = append(ids, device.DeviceID)
if s.cache != nil && len(device.TokenHash) > 0 {
_ = s.cache.Delete(ctx, cache.SessionKey(hexHash(device.TokenHash)))
}
s.retireEmbyDevice(ctx, device.DeviceID)
}
if err := s.store.DeleteDeviceVersions(ctx, ids...); err != nil {
s.loggerFor(ctx).Warn("device version cleanup failed", "error", err)
}
2026-08-17 19:09:17 +12:00
if err := s.store.DeleteDeviceActivityDays(ctx, ids...); err != nil {
s.loggerFor(ctx).Warn("device activity cleanup failed", "error", err)
}
2026-08-06 22:33:56 +12:00
s.loggerFor(ctx).Info("device identity superseded", "retired_device_ids", ids)
}
// retireEmbyDevice deletes the Emby device record a removed television left behind.
//
// Revoking the gateway session only takes the TV out of Settings → Devices; Emby keeps
// its own record until the record itself is deleted, so without this a set removed from
// one list stays visible in the other. Deliberately best-effort: the session is already
// gone, which is what actually ends that TV's access, and a lingering Emby row is not
// worth failing the request the operator made. It needs the sync credentials because a
// device record belongs to Emby's server, not to the viewer whose session was removed.
func (s *Server) retireEmbyDevice(ctx context.Context, deviceID string) {
if s.emby == nil || s.cfg.SyncAPIKey == "" || deviceID == "" {
return
}
if err := s.emby.DeleteDevice(ctx, emby.Credentials{
UserID: s.cfg.SyncUserID, Token: s.cfg.SyncAPIKey,
2026-08-12 13:08:53 +12:00
DeviceID: "memby-gateway", DeviceName: s.gatewayDeviceName(),
Gateway: true,
2026-08-06 22:33:56 +12:00
}, deviceID); err != nil {
s.loggerFor(ctx).Warn("emby device cleanup failed",
"removed_device_id", deviceID, "error", err)
}
}
2026-08-02 22:10:19 +12:00
func (s *Server) handleRenameDevice(w http.ResponseWriter, r *http.Request, current store.Session) {
deviceID := strings.TrimSpace(r.PathValue("deviceID"))
var req renameDeviceRequest
if deviceID == "" || json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<10)).Decode(&req) != nil {
writeError(w, http.StatusBadRequest, "device id and name are required")
return
}
req.DeviceName = strings.TrimSpace(req.DeviceName)
if req.DeviceName == "" {
writeError(w, http.StatusBadRequest, "device name is required")
return
}
if len([]rune(req.DeviceName)) > 80 {
writeError(w, http.StatusBadRequest, "device name is too long")
return
}
if err := s.store.RenameUserDevice(r.Context(), current.EmbyUserID, deviceID, req.DeviceName); err == store.ErrNotFound {
writeError(w, http.StatusNotFound, "device not found")
return
} else if err != nil {
s.log.Error("device rename failed", "error", err)
writeError(w, http.StatusInternalServerError, "could not rename device")
return
}
2026-08-06 22:33:56 +12:00
s.loggerFor(r.Context()).Info("device renamed",
"renamed_device_id", deviceID, "new_name", req.DeviceName,
)
2026-08-14 09:40:03 +12:00
s.publishAdmin(r.Context(), adminevents.Event{
Type: adminevents.TypeDeviceRenamed,
Title: "Device renamed",
Summary: fmt.Sprintf("%s renamed a device to %s",
displayName(current.Username), req.DeviceName),
Actor: current.Username, Target: req.DeviceName,
Link: "/admin/devices/" + url.PathEscape(deviceID),
Metadata: adminevents.Meta(map[string]any{"deviceId": deviceID}),
})
2026-08-02 22:10:19 +12:00
w.WriteHeader(http.StatusNoContent)
}