sonda/internal/mastodon/client.go
tgiachi 0dc7782028 feat: post what I listen to on Mastodon, if I connect an account
In Settings a person connects their Mastodon account: the address of their instance and an access token that can only write posts. Nothing is connected by default, and disconnecting forgets the token.

- When a track of this server counts as a listen, it is posted as an unlisted status: title, artists, album and #NowPlaying, with no link. Music of a friend is never reported as a listen, so it is never posted. At most one post a minute for each person, in the background, with a bounded queue.
- PUT, GET and DELETE /me/mastodon. The token is never sent back.
- The address of the instance is typed by a person, so it must be a domain name on https, and the client never connects to a private, loopback or link-local address (checked on the address it really dials, so a name that points inside is no way in), never follows a redirect, ignores proxy settings and reads at most a megabyte.
- New table mastodon_accounts (SQLite and PostgreSQL) that goes with the account.
- README: the feature, and the credit for butterchurn and its presets.
2026-11-13 21:59:03 +01:00

170 lines
5.3 KiB
Go

package mastodon
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"syscall"
"time"
)
const (
requestTimeout = 15 * time.Second
// maxAnswer is far more than any answer of Mastodon that is read.
maxAnswer = 1 << 20
// maxHandle is the longest handle that is believed.
maxHandle = 320
)
// HTTPRemote is the real Remote. The address of the instance is typed by a person, so the client is built to be sent
// nowhere it should not go: it never reaches a private, loopback or link-local address (checked on the address it
// really connects to, so a name that points inside is no way in either), never follows a redirect (the token would go
// along), keeps no cookies, ignores proxy settings and reads at most a megabyte.
type HTTPRemote struct {
client *http.Client
userAgent string
}
// NewRemote builds the client. userAgent says who is asking.
func NewRemote(userAgent string) *HTTPRemote {
dialer := &net.Dialer{
Timeout: 10 * time.Second,
Control: func(_, address string, _ syscall.RawConn) error {
host, _, err := net.SplitHostPort(address)
if err != nil {
return err
}
if !publicIP(net.ParseIP(host)) {
return errors.New("not a public address")
}
return nil
},
}
transport := &http.Transport{
Proxy: nil,
DialContext: dialer.DialContext,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: requestTimeout,
MaxIdleConns: 4,
IdleConnTimeout: 30 * time.Second,
DisableCompression: false,
}
return &HTTPRemote{
userAgent: userAgent,
client: &http.Client{
Transport: transport,
Timeout: requestTimeout,
CheckRedirect: refuseRedirect,
},
}
}
// refuseRedirect keeps the answer that says "go elsewhere" as the answer: the token must not follow it.
func refuseRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
// publicIP says whether an address is one on the open internet.
func publicIP(ip net.IP) bool {
addr, ok := netip.AddrFromSlice(ip)
if !ok {
return false
}
addr = addr.Unmap()
switch {
case !addr.IsValid(), addr.IsLoopback(), addr.IsPrivate(), addr.IsLinkLocalUnicast(), addr.IsLinkLocalMulticast(),
addr.IsMulticast(), addr.IsUnspecified(), addr.IsInterfaceLocalMulticast():
return false
}
// The shared address space of carriers (100.64.0.0/10), which is not public either.
if addr.Is4() {
if b := addr.As4(); b[0] == 100 && b[1]&0xC0 == 64 {
return false
}
if addr == netip.AddrFrom4([4]byte{255, 255, 255, 255}) {
return false
}
}
return true
}
func (r *HTTPRemote) do(ctx context.Context, method, base, path, token string, body io.Reader, headers map[string]string) ([]byte, int, error) {
req, err := http.NewRequestWithContext(ctx, method, base+path, body)
if err != nil {
return nil, 0, fmt.Errorf("%w: %v", ErrUnreachable, err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("User-Agent", r.userAgent)
req.Header.Set("Accept", "application/json")
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := r.client.Do(req)
if err != nil {
return nil, 0, fmt.Errorf("%w: %v", ErrUnreachable, unwrapURLError(err))
}
defer func() { _ = resp.Body.Close() }()
data, err := io.ReadAll(io.LimitReader(resp.Body, maxAnswer))
if err != nil {
return nil, resp.StatusCode, fmt.Errorf("%w: reading the answer", ErrUnreachable)
}
switch {
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
return nil, resp.StatusCode, ErrRefused
case resp.StatusCode < 200 || resp.StatusCode > 299:
return nil, resp.StatusCode, fmt.Errorf("%w: the instance answered %d", ErrUnreachable, resp.StatusCode)
}
return data, resp.StatusCode, nil
}
// unwrapURLError drops the address from a network error: it is typed by a person and goes into a log.
func unwrapURLError(err error) error {
var ue *url.Error
if errors.As(err, &ue) {
return ue.Err
}
return err
}
// plausibleAcct says whether an answer looks like name or name@domain: what the instance says about itself is not trusted.
func plausibleAcct(acct string) bool {
return acct != "" && len(acct) <= maxHandle && !strings.ContainsAny(acct, " \t\r\n/") && strings.Count(acct, "@") <= 1 && !strings.HasPrefix(acct, "@")
}
// Verify implements Remote.
func (r *HTTPRemote) Verify(ctx context.Context, instance, token string) (string, error) {
data, _, err := r.do(ctx, http.MethodGet, instance, "/api/v1/accounts/verify_credentials", token, nil, nil)
if err != nil {
return "", err
}
var account struct {
Acct string `json:"acct"`
}
if err := json.Unmarshal(data, &account); err != nil || !plausibleAcct(account.Acct) {
return "", fmt.Errorf("%w: not an account", ErrUnreachable)
}
acct := account.Acct
if !strings.Contains(acct, "@") {
u, err := url.Parse(instance)
if err != nil {
return "", fmt.Errorf("%w: %v", ErrUnreachable, err)
}
acct += "@" + u.Hostname()
}
return "@" + acct, nil
}
// Post implements Remote.
func (r *HTTPRemote) Post(ctx context.Context, instance, token, status, key string) error {
form := url.Values{"status": {status}, "visibility": {"unlisted"}}
_, _, err := r.do(ctx, http.MethodPost, instance, "/api/v1/statuses", token, strings.NewReader(form.Encode()), map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Idempotency-Key": key,
})
return err
}