mastodonapi

package
v0.8.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const DefaultMastodonRedirectURI = fixedMastodonRedirectURI

DefaultMastodonRedirectURI is the exact loopback callback registered for a Mastodon application. Interactive logins are serialized around this port.

Variables

View Source
var ErrMalformedStatus = errors.New("malformed Mastodon status")
View Source
var ErrSecretNotFound = errors.New("mastodon secret not found")
View Source
var ErrUnsupportedStatus = errors.New("unsupported Mastodon status")

Functions

func CanonicalOrigin

func CanonicalOrigin(raw string) (string, error)

CanonicalOrigin validates the user-facing Mastodon instance origin.

func MediaHTTPPolicy added in v0.8.13

func MediaHTTPPolicy(rawURL string, basePolicy *safehttp.Policy) (safehttp.Policy, error)

MediaHTTPPolicy reconstructs the exact origin authority for one Mastodon media URL. Callers may inject transport settings for tests, but cannot widen the origin or disable credential-query redirect rejection.

func ParseNextBookmarksCursor

func ParseNextBookmarksCursor(header, origin string) (string, error)

ParseNextBookmarksCursor extracts and validates only the server-provided rel=next URL. The URL is returned byte-for-byte after validation; callers must treat its query values as opaque.

func PersistOAuthSecrets

func PersistOAuthSecrets(ctx context.Context, store SecretStore, account AccountConfig, accessToken, clientID, clientSecret string) error

PersistOAuthSecrets commits token/client values as one logical operation. Any partial write restores existing values and removes new entries.

func ResolveTypedSecretRef

func ResolveTypedSecretRef(ctx context.Context, ref string) (string, error)

ResolveTypedSecretRef is the only Mastodon import resolver. It preserves the shared runtime resolver's env/op/keychain support while rejecting the legacy literal-value fallback for this new credential boundary.

func RevokeToken

func RevokeToken(ctx context.Context, client *http.Client, endpoints OAuthEndpoints, clientID, clientSecret, accessToken string) error

func ValidateCallback

func ValidateCallback(raw, expectedState, expectedCallback string) (string, error)

ValidateCallback accepts only the exact loopback callback registered for the OAuth client and the one-time state generated for that login.

func ValidateSecretRef

func ValidateSecretRef(ref string) error

ValidateSecretRef accepts only the reference syntaxes that the runtime resolver understands. The Mastodon config layer intentionally does not inherit runtimeenv's legacy behavior of treating bare strings as secrets.

Types

type Account

type Account struct {
	ID          string `json:"id"`
	Username    string `json:"username"`
	Acct        string `json:"acct,omitempty"`
	DisplayName string `json:"display_name,omitempty"`
	URL         string `json:"url,omitempty"`
}

type AccountConfig

type AccountConfig struct {
	Key             string
	Enabled         bool
	Origin          string
	AccessTokenRef  string
	ClientIDRef     string
	ClientSecretRef string
}

AccountConfig identifies one configured viewer account on one Mastodon origin. The remote account ID is learned from verify_credentials and is persisted separately in sync state.

func (AccountConfig) RedactedMetadata

func (a AccountConfig) RedactedMetadata() AccountMetadata

type AccountMetadata

type AccountMetadata struct {
	Key                    string `json:"key"`
	Enabled                bool   `json:"enabled"`
	Origin                 string `json:"origin"`
	AccessTokenRefPresent  bool   `json:"access_token_ref_present"`
	ClientIDRefPresent     bool   `json:"client_id_ref_present"`
	ClientSecretRefPresent bool   `json:"client_secret_ref_present"`
}

AccountMetadata is safe for status and diagnostics output. It contains presence bits instead of the configured secret references themselves.

type ApplicationCredentials

type ApplicationCredentials struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
}

func RegisterApplication

func RegisterApplication(ctx context.Context, client *http.Client, origin, redirectURI string) (ApplicationCredentials, error)

type AuthorizationRequest

type AuthorizationRequest struct {
	URL      string
	State    string
	Verifier string
}

AuthorizationRequest is the non-secret data needed to start a PKCE login. Verifier must remain in memory until the token exchange completes.

func BuildAuthorizationRequest

func BuildAuthorizationRequest(endpoints OAuthEndpoints, clientID, redirectURI string, random io.Reader) (AuthorizationRequest, error)

BuildAuthorizationRequest creates a read-only Authorization Code + PKCE request. The caller supplies the exact registered loopback redirect URI.

type BookmarkOptions

type BookmarkOptions struct {
	AccountKey string
	Limit      int
	Timeout    time.Duration
	MaxPages   int
	// MediaRetryLimit bounds the post-import sweep that retries historical
	// Mastodon media failures. Zero uses the package default.
	MediaRetryLimit int
	Force           bool
	MediaHTTPPolicy *safehttp.Policy
	Now             func() time.Time
	// contains filtered or unexported fields
}

type BookmarkStats

type BookmarkStats struct {
	AccountKey         string `json:"account_key"`
	Origin             string `json:"origin"`
	VerifiedAccountID  string `json:"verified_account_id"`
	Handle             string `json:"handle"`
	PagesFetched       int    `json:"pages_fetched"`
	Seen               int    `json:"seen"`
	Processed          int    `json:"processed"`
	Skipped            int    `json:"skipped"`
	SkippedUnsupported int    `json:"skipped_unsupported"`
	SkippedMalformed   int    `json:"skipped_malformed"`
	Created            int    `json:"created"`
	Updated            int    `json:"updated"`
	Unchanged          int    `json:"unchanged"`
	Rendered           int    `json:"rendered"`
	MediaDiscovered    int    `json:"media_discovered"`
	MediaLinked        int    `json:"media_linked"`
	MediaUnavailable   int    `json:"media_unavailable"`
	MediaDownloaded    int    `json:"media_downloaded"`
	MediaGone          int    `json:"media_gone"`
	MediaErrors        int    `json:"media_errors"`
	MediaBlocked       int    `json:"media_blocked"`
	APIErrors          int    `json:"api_errors"`
	RateLimits         int    `json:"rate_limits"`
	Retries            int    `json:"retries"`
	StoppedReason      string `json:"stopped_reason"`
}

func RunBookmarksWithClient

func RunBookmarksWithClient(ctx context.Context, cfg config.Config, st *store.Store, client *Client, opts BookmarkOptions) (BookmarkStats, error)

RunBookmarksWithClient imports one configured account. The caller resolves credentials and constructs the origin-scoped API client; this keeps token lookup out of the protocol package's persistence and test fixtures.

type BookmarksPage

type BookmarksPage struct {
	URL        string
	Statuses   []StatusRecord
	NextURL    string
	PageDigest string
}

type Card

type Card struct {
	URL         string `json:"url,omitempty"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
}

type Client

type Client struct {
	Origin      string
	AccessToken string
	HTTPClient  *http.Client
}

Client is an origin-scoped authenticated Mastodon API client. The bearer token is held only in memory and is never part of a status projection.

func NewClient

func NewClient(origin, accessToken string, httpClient *http.Client) (*Client, error)

func (*Client) FetchBookmarksPage

func (c *Client) FetchBookmarksPage(ctx context.Context, cursor string, limit int) (BookmarksPage, error)

func (*Client) VerifyCredentials

func (c *Client) VerifyCredentials(ctx context.Context) (VerifiedAccount, error)

type Config

type Config struct {
	Enabled  bool
	Accounts []AccountConfig
}

Config is the parsed Mastodon runtime configuration. Secret values are intentionally never part of this type; only typed references are retained.

func ParseConfig

func ParseConfig(raw map[string]any) (Config, error)

ParseConfig validates the mastodon section returned by runtimeenv.ConfigMap. It rejects bare secret values because ResolveSecretRef deliberately retains literal values for legacy integrations.

type KeychainSecretStore

type KeychainSecretStore struct{}

KeychainSecretStore is the production writer for keychain:// refs.

func (KeychainSecretStore) Delete

func (KeychainSecretStore) Get

func (KeychainSecretStore) Put

func (KeychainSecretStore) Put(_ context.Context, ref, value string) error

type LoginOptions

type LoginOptions struct {
	HTTPClient         *http.Client
	SecretStore        SecretStore
	Listen             func(network, address string) (net.Listener, error)
	OpenBrowser        func(string) error
	OnAuthorizationURL func(string)
	Random             io.Reader
	// CallbackCode is a deterministic test seam. Production callers leave it
	// nil and receive the code through the fixed loopback listener.
	CallbackCode func(context.Context, AuthorizationRequest) (string, error)
}

type LoginResult

type LoginResult struct {
	Origin           string   `json:"origin"`
	AccountID        string   `json:"account_id"`
	AccountHandle    string   `json:"account_handle"`
	EffectiveScopes  []string `json:"effective_scopes"`
	TokenFingerprint string   `json:"token_fingerprint"`
}

func Login

func Login(ctx context.Context, account AccountConfig, opts LoginOptions) (LoginResult, error)

type LogoutOptions

type LogoutOptions struct {
	HTTPClient   *http.Client
	SecretStore  SecretStore
	ForgetClient bool
	LocalOnly    bool
}

type LogoutResult

type LogoutResult struct {
	Revoked            bool `json:"revoked"`
	AccessTokenCleared bool `json:"access_token_cleared"`
	ClientCleared      bool `json:"client_cleared"`
}

func Logout

func Logout(ctx context.Context, account AccountConfig, opts LogoutOptions) (LogoutResult, error)

type MediaAttachment

type MediaAttachment struct {
	ID          string         `json:"id"`
	Type        string         `json:"type"`
	URL         string         `json:"url,omitempty"`
	RemoteURL   string         `json:"remote_url,omitempty"`
	PreviewURL  string         `json:"preview_url,omitempty"`
	Description string         `json:"description,omitempty"`
	Meta        map[string]any `json:"meta,omitempty"`
}

type OAuthEndpoints

type OAuthEndpoints struct {
	AuthorizationURL string
	TokenURL         string
	RevocationURL    string
	Version          string
	SupportsPKCE     bool
}

OAuthEndpoints contains the same-origin authorization endpoint discovered from a Mastodon instance or its OAuth metadata.

func DiscoverOAuthEndpoints

func DiscoverOAuthEndpoints(ctx context.Context, origin string, client *http.Client) (OAuthEndpoints, error)

DiscoverOAuthEndpoints learns optional OAuth metadata while retaining Mastodon's same-origin defaults when metadata is absent.

type Poll

type Poll struct {
	Question string       `json:"question,omitempty"`
	Options  []PollOption `json:"options,omitempty"`
}

type PollOption

type PollOption struct {
	Title string `json:"title,omitempty"`
}

type RetryableError

type RetryableError struct {
	StatusCode int
	RetryAfter time.Duration
	Message    string
}

func (*RetryableError) Error

func (e *RetryableError) Error() string

type SecretStore

type SecretStore interface {
	Get(ctx context.Context, ref string) (string, error)
	Put(ctx context.Context, ref string, value string) error
	Delete(ctx context.Context, ref string) error
}

SecretStore is deliberately reference-oriented so OAuth can write only deterministic Keychain refs while tests can use an in-memory implementation.

type StaleCursorError

type StaleCursorError struct {
	StatusCode int
	Reason     string
}

StaleCursorError means that a previously persisted Link cursor is no longer accepted by the instance. The importer restarts from the endpoint head and keeps local items append-only.

func (*StaleCursorError) Error

func (e *StaleCursorError) Error() string

type StatusOptions

type StatusOptions struct {
	HTTPClient    *http.Client
	ResolveSecret func(context.Context, string) (string, error)
}

StatusOptions contains the injectable boundaries needed to verify an already-configured account without exposing its token in the result.

type StatusProjection

type StatusProjection struct {
	Item             model.Item
	MediaCandidates  []model.MediaCandidate
	MediaUnavailable bool
	MediaComplete    bool
}

func NormalizeStatus

func NormalizeStatus(status StatusRecord, origin string, now time.Time) (StatusProjection, error)

NormalizeStatus turns one Mastodon status into the existing item/media pipeline. Direct bookmarks use mastodon_bookmark; PR B can use NormalizeStatusAs for quote/reblog children without duplicating parsing.

func NormalizeStatusAs

func NormalizeStatusAs(status StatusRecord, origin, sourceType string, now time.Time) (StatusProjection, error)

func NormalizeStatusAsForAccount

func NormalizeStatusAsForAccount(status StatusRecord, origin, sourceType, accountID string, now time.Time) (StatusProjection, error)

func NormalizeStatusForAccount

func NormalizeStatusForAccount(status StatusRecord, origin, accountID string, now time.Time) (StatusProjection, error)

type StatusRecord

type StatusRecord struct {
	ID               string            `json:"id"`
	URI              string            `json:"uri"`
	URL              string            `json:"url"`
	Content          string            `json:"content"`
	CreatedAt        string            `json:"created_at"`
	EditedAt         string            `json:"edited_at,omitempty"`
	SpoilerText      string            `json:"spoiler_text,omitempty"`
	Sensitive        bool              `json:"sensitive,omitempty"`
	Visibility       string            `json:"visibility,omitempty"`
	Language         string            `json:"language,omitempty"`
	Account          Account           `json:"account"`
	Card             *Card             `json:"card,omitempty"`
	MediaAttachments []MediaAttachment `json:"media_attachments,omitempty"`
	Poll             *Poll             `json:"poll,omitempty"`
	FavouritesCount  int               `json:"favourites_count,omitempty"`
	ReblogsCount     int               `json:"reblogs_count,omitempty"`
	RepliesCount     int               `json:"replies_count,omitempty"`
	BookmarksCount   int               `json:"bookmarks_count,omitempty"`
	Reblog           *StatusRecord     `json:"reblog,omitempty"`
	Quote            json.RawMessage   `json:"quote,omitempty"`
	QuotedStatusID   string            `json:"quoted_status_id,omitempty"`
	Application      json.RawMessage   `json:"application,omitempty"`
	RawExtra         map[string]any    `json:"-"`
	// contains filtered or unexported fields
}

StatusRecord is the bounded, source-neutral subset of a Mastodon status needed by the importer. Keeping the API shape typed also prevents bearer credentials or callback state from being copied into raw item evidence.

func (StatusRecord) MarshalJSON

func (s StatusRecord) MarshalJSON() ([]byte, error)

func (*StatusRecord) UnmarshalJSON

func (s *StatusRecord) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps unknown Mastodon extension fields as bounded raw evidence. Mastodon-compatible servers add fields at different cadences; dropping them would make reprojection and repair impossible.

type StatusResult

type StatusResult struct {
	Key              string   `json:"key"`
	Origin           string   `json:"origin"`
	AccountID        string   `json:"account_id"`
	AccountHandle    string   `json:"account_handle"`
	EffectiveScopes  []string `json:"effective_scopes"`
	TokenFingerprint string   `json:"token_fingerprint"`
}

StatusResult is the non-secret account identity and capability view shown by auth status. Mastodon does not expose a portable token introspection endpoint, so the read-only scope set is the scope contract requested by dbrain and accepted during login; verify_credentials proves the token is still valid for the configured origin.

func Status

func Status(ctx context.Context, account AccountConfig, opts StatusOptions) (StatusResult, error)

Status resolves the configured access-token reference and verifies it against the configured origin. The token itself is never returned.

type TokenResponse

type TokenResponse struct {
	AccessToken string `json:"access_token"`
	Scope       string `json:"scope"`
	TokenType   string `json:"token_type"`
}

func ExchangeAuthorizationCode

func ExchangeAuthorizationCode(ctx context.Context, client *http.Client, endpoints OAuthEndpoints, clientID, clientSecret, code, verifier, redirectURI string) (TokenResponse, error)

ExchangeAuthorizationCode performs the same-origin token exchange without sending a bearer token. The verifier is memory-only and never persisted.

type VerifiedAccount

type VerifiedAccount struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	Acct     string `json:"acct"`
	URL      string `json:"url"`
}

func VerifyCredentials

func VerifyCredentials(ctx context.Context, client *http.Client, origin, accessToken string) (VerifiedAccount, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL