atp

package module
v0.0.0-...-fdb1591 Latest Latest
Warning

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

Go to latest
Published: May 23, 2026 License: MIT Imports: 25 Imported by: 0

README

atp

AT Protocol boilerplate for Go, extracted from arabica.social. Covers OAuth flows, PDS client operations, real-time event consumption, session storage, and HTTP middleware.

For integration testing against an ephemeral in-process PDS, see chrysalis.

Installation

go get tangled.org/pdewey.com/atp@latest

Packages

Root (atp)

Core types and clients for the AT Protocol.

  • Client -- authenticated PDS client for CRUD operations on a user's repository (CreateRecord, GetRecord, ListRecords, PutRecord, DeleteRecord, UploadBlob, GetBlob).
  • OAuthApp -- manages the OAuth flow: login (browser-based and CLI), callback handling, session resumption, and logout. Supports public and localhost (development) client modes.
  • PublicClient -- unauthenticated access to public atproto APIs (handle resolution, profiles, record reads) with SSRF protection.
  • Helpers for AT-URI parsing/building, scope construction, and error handling.
jetstream

WebSocket consumer for the Jetstream relay. Reconnects with exponential backoff, rotates endpoints, optionally decompresses zstd, and persists cursors for resuming after restarts.

middleware

Cookie-based AT Protocol auth middleware. Validates sessions against the OAuth store and injects the authenticated DID into the request context. Also serves the OAuth client metadata endpoint.

store/bolt and store/sqlite

Two oauth.ClientAuthStore implementations for persisting OAuth sessions and auth request state:

  • bolt: BoltDB-backed.
  • sqlite: SQLite-backed with automatic schema migration and expired request cleanup.
tracing

OpenTelemetry span helpers for AT Protocol operations (PDS calls, database operations, HTTP handlers). Sets up an OTLP HTTP exporter and returns no-op spans when there is no active trace context.

Documentation

Index

Constants

View Source
const MaxBlobSize = 1024 * 1024

Maximum PDS blob size (1 MB).

View Source
const MaxRKeyLength = 512

MaxRKeyLength is the maximum allowed length for a record key.

Variables

View Source
var ErrSSRFBlocked = errors.New("request blocked: potential SSRF detected")

ErrSSRFBlocked is returned when a request is blocked due to a private/internal destination.

View Source
var ErrSessionExpired = errors.New("oauth session expired")

ErrSessionExpired indicates the OAuth session can no longer be resumed. Callers should prompt the user to re-authenticate.

View Source
var PLCDirectory = "https://plc.directory"

PLCDirectory is used to resolve did:plc identifiers to DID documents. This is a variable so tests can override it.

View Source
var PublicAPIBase = "https://public.api.bsky.app"

PublicAPIBase is the Bluesky public API endpoint used for profile and handle lookups. This is a variable so tests can override it.

Functions

func BuildATURI

func BuildATURI(did, collection, rkey string) string

BuildATURI constructs an AT-URI string from its components.

func DisplayHandle

func DisplayHandle(handle string) string

DisplayHandle converts a handle to its Unicode form for display. If the input is already Unicode (or plain ASCII with no xn-- labels), it is returned unchanged. Falls back to the input on conversion error.

func NormalizeHandle

func NormalizeHandle(handle string) string

NormalizeHandle converts a handle to its ASCII (punycode) form for resolution and storage. Idempotent on plain ASCII input. Returns the lowercased input unchanged if IDN conversion fails.

func RKeyFromURI

func RKeyFromURI(uri string) string

RKeyFromURI extracts the record key from an AT-URI. Returns empty string on error.

func ResolveHandle

func ResolveHandle(ctx context.Context, handle string) (string, error)

ResolveHandle is a convenience that resolves an AT Protocol handle to a DID without needing to construct a PublicClient.

func ResolveRecord

func ResolveRecord[T any](
	ctx context.Context,
	fetcher RecordFetcher,
	atURI string,
	expectedCollection string,
	convert func(value map[string]any, uri string) (*T, error),
) (*T, error)

ResolveRecord parses an AT-URI, validates the collection matches the expected NSID, fetches the record from the PDS using the provided fetcher, and converts it to a typed struct via the caller-supplied convert function. Returns nil, nil if atURI is empty.

func ScopesForCollections

func ScopesForCollections(collections ...string) []string

ScopesForCollections builds an OAuth scope list from collection NSIDs. It always includes "atproto" as the first scope, then adds "repo:<collection>" for each collection provided.

ScopesForCollections("x.y.bean", "x.y.brew")
// => ["atproto", "repo:x.y.bean", "repo:x.y.brew"]

TODO: add support for collections and more granular control than just full rw

func ValidateRKey

func ValidateRKey(rkey string) bool

ValidateRKey checks if an rkey is valid according to AT Protocol spec. Returns true if valid, false otherwise.

func WrapPDSError

func WrapPDSError(err error) error

WrapPDSError inspects an XRPC error for signals that the OAuth grant is no longer valid and, if so, wraps it with ErrSessionExpired. TODO: handle other common error types

Types

type BlobRef

type BlobRef struct {
	Type     string  `json:"$type"`
	Ref      CIDLink `json:"ref"`
	MimeType string  `json:"mimeType"`
	Size     int     `json:"size"`
}

BlobRef represents a reference to an uploaded blob.

type CIDLink struct {
	Link string `json:"$link"`
}

CIDLink is the ref field inside a BlobRef.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client wraps an authenticated atclient.APIClient for PDS CRUD operations. Create one per-user session via `ResumeSession` or NewClient.

func NewClient

func NewClient(api *atclient.APIClient, did syntax.DID) *Client

NewClient wraps an existing indigo APIClient. Use this when you manage OAuth sessions yourself (e.g. CLI apps that call ResumeSession directly).

func (*Client) APIClient

func (c *Client) APIClient() *atclient.APIClient

APIClient returns the underlying indigo APIClient for advanced usage (custom XRPC calls, service proxying, etc.).

func (*Client) CreateRecord

func (c *Client) CreateRecord(ctx context.Context, collection string, record any) (uri, cid string, err error)

func (*Client) CreateRecordWithRKey

func (c *Client) CreateRecordWithRKey(ctx context.Context, collection, rkey string, record any) (uri, cid string, err error)

func (*Client) DID

func (c *Client) DID() syntax.DID

func (*Client) DeleteRecord

func (c *Client) DeleteRecord(ctx context.Context, collection, rkey string) error

func (*Client) GetBlob

func (c *Client) GetBlob(ctx context.Context, cid string) ([]byte, error)

func (*Client) GetRecord

func (c *Client) GetRecord(ctx context.Context, collection, rkey string) (*Record, error)

GetRecord retrieves a single record by collection and record key.

func (*Client) ListAllRecords

func (c *Client) ListAllRecords(ctx context.Context, collection string) ([]Record, error)

func (*Client) ListRecords

func (c *Client) ListRecords(ctx context.Context, collection string, limit int, cursor string) (*ListResult, error)

Pass limit <= 0 for the server default (usually 50). Pass empty cursor for the first page.

func (*Client) PutRecord

func (c *Client) PutRecord(ctx context.Context, collection, rkey string, record any) (uri, cid string, err error)

func (*Client) UploadBlob

func (c *Client) UploadBlob(ctx context.Context, data []byte, mimeType string) (*BlobRef, error)

Data must be at most 1 MB (MaxBlobSize). The mimeType should match the blob content.

type ListPublicRecordsOpts

type ListPublicRecordsOpts struct {
	Limit   int    // 0 means server default
	Cursor  string // empty for first page
	Reverse bool   // true returns newest-first
}

ListPublicRecordsOpts configures a ListPublicRecords call. All fields are optional; the zero value yields the lexicon defaults.

type ListResult

type ListResult struct {
	Records []Record
	Cursor  string // empty when there are no more pages
}

ListResult holds a page of records and an optional cursor for the next page.

type OAuthApp

type OAuthApp struct {
	// contains filtered or unexported fields
}

OAuthApp manages AT Protocol OAuth flows.

func NewOAuthApp

func NewOAuthApp(cfg OAuthConfig) (*OAuthApp, error)

NewOAuthApp creates a new OAuth application from the given config.

func (*OAuthApp) ClientMetadata

func (a *OAuthApp) ClientMetadata() oauth.ClientMetadata

ClientMetadata returns the OAuth client metadata document. Serve this at your client_id URL and at /.well-known/oauth-client-metadata.

func (*OAuthApp) DeleteSession

func (a *OAuthApp) DeleteSession(ctx context.Context, did syntax.DID, sessionID string) error

DeleteSession removes an OAuth session (for logout).

func (*OAuthApp) HandleCallback

func (a *OAuthApp) HandleCallback(ctx context.Context, params url.Values) (*SessionInfo, error)

HandleCallback processes the OAuth callback after user authorization. Pass r.URL.Query() from the callback request.

func (*OAuthApp) LoginCLI

func (a *OAuthApp) LoginCLI(ctx context.Context, handle string) (*SessionInfo, error)

LoginCLI runs a complete loopback OAuth flow for CLI applications. It opens the user's browser, starts a temporary HTTP server to receive the callback, and blocks until authentication completes. TODO: should this be part of the library? probably not? (removeds `browser` dep)

func (*OAuthApp) Logout

func (a *OAuthApp) Logout(ctx context.Context, did syntax.DID, sessionID string) error

Logout revokes the OAuth tokens and deletes the session.

func (*OAuthApp) ResumeSession

func (a *OAuthApp) ResumeSession(ctx context.Context, did syntax.DID, sessionID string) (*Client, error)

ResumeSession restores an existing OAuth session and returns a Client ready for PDS CRUD operations.

func (*OAuthApp) SessionScopes

func (a *OAuthApp) SessionScopes(ctx context.Context, did syntax.DID, sessionID string) ([]string, error)

SessionScopes returns the scopes granted to the given session, or an error if the session cannot be loaded. Useful for gating UI on whether a session has elevated permissions without resuming a full client.

func (*OAuthApp) StartLogin

func (a *OAuthApp) StartLogin(ctx context.Context, handle string) (string, error)

StartLogin begins the web OAuth flow. Returns the authorization URL to redirect the user to. Use [HandleCallback] when the user returns.

func (*OAuthApp) StartLoginWithScopes

func (a *OAuthApp) StartLoginWithScopes(ctx context.Context, handle string, scopes []string) (string, error)

StartLoginWithScopes is like [StartLogin] but requests the given scopes instead of the default OAuthConfig.Scopes. Use this for incremental scope upgrades: configure OAuthConfig.Scopes with the full superset that is declared in client metadata, then call this with a subset for the default login and the superset when the user opts in to elevated permissions.

The requested scopes must all be a subset of the scopes declared in client metadata, or the auth server will reject the request. TODO: maybe just make this the default behavior for oauth, seems like a good pattern to encourage. (e.g. incrementally add scopes where they are needed)

func (*OAuthApp) StartSignup

func (a *OAuthApp) StartSignup(ctx context.Context, pdsURL string) (string, error)

StartSignup starts an OAuth flow with prompt=create for account registration. pdsURL is the PDS host URL (e.g. "https://arabica.systems"). Returns the authorization URL to redirect the user to.

func (*OAuthApp) Store

func (a *OAuthApp) Store() oauth.ClientAuthStore

type OAuthConfig

type OAuthConfig struct {
	// ClientID is the OAuth client ID (a URL). Empty string or a localhost/127.0.0.1
	// prefix triggers development mode (localhost OAuth with automatic PKCE).
	ClientID string

	// RedirectURI is the fully-qualified OAuth callback URL.
	RedirectURI string

	// Scopes for the OAuth grant. Use [ScopesForCollections] to build these
	// from collection NSIDs. Must include "atproto".
	Scopes []string

	// Store persists OAuth sessions and auth request state. If nil, an
	// in-memory store is used (sessions lost on restart).
	Store oauth.ClientAuthStore

	// AppName is an optional human-readable name included in client metadata.
	AppName string

	// Directory overrides the identity directory used to resolve handles and
	// DIDs during the OAuth flow. If nil, indigo's default directory is used
	// (which queries plc.directory and the public DNS). Set this to point at
	// a test PLC (e.g. for integration tests against an ephemeral PDS).
	Directory identity.Directory
}

OAuthConfig configures an OAuthApp.

type PublicClient

type PublicClient struct {
	// contains filtered or unexported fields
}

PublicClient provides unauthenticated read access to public AT Protocol APIs. Use this to resolve handles, look up profiles, and read public records without requiring an OAuth session.

Handle→DID and DID→PDS lookups are cached with a 1-hour TTL. Call InvalidateHandle or InvalidateDID when identity changes are detected.

func NewPublicClient

func NewPublicClient() *PublicClient

NewPublicClient creates a PublicClient with a 30-second timeout. To add OTel instrumentation, use NewPublicClientWithHTTP and pass an otelhttp-wrapped transport.

func NewPublicClientWithHTTP

func NewPublicClientWithHTTP(hc *http.Client) *PublicClient

NewPublicClientWithHTTP creates a PublicClient using the provided http.Client. This lets callers inject custom transports (e.g. with OTel or rate limiting).

func (*PublicClient) GetPDSEndpoint

func (c *PublicClient) GetPDSEndpoint(ctx context.Context, did string) (string, error)

GetPDSEndpoint resolves a DID to the user's PDS base URL. Results are cached with a 1-hour TTL.

func (*PublicClient) GetProfile

func (c *PublicClient) GetProfile(ctx context.Context, actor string) (*PublicProfile, error)

GetProfile fetches a user's public profile by DID or handle.

func (*PublicClient) GetPublicRecord

func (c *PublicClient) GetPublicRecord(ctx context.Context, did, collection, rkey string) (*Record, error)

GetPublicRecord fetches a single public record from a user's PDS.

func (*PublicClient) InvalidateDID

func (c *PublicClient) InvalidateDID(did string)

InvalidateDID drops any cached entries pointing at this DID — both the PDS endpoint cache and any handle→DID mappings whose resolved DID is the given one. Used when a DID's repo is gone (account deleted/takendown) or when a handle has been reassigned away from this DID.

func (*PublicClient) InvalidateHandle

func (c *PublicClient) InvalidateHandle(handle string)

InvalidateHandle removes a handle from the resolver cache so the next ResolveHandle call refetches from the directory. Call when a firehose identity event signals that a handle's DID mapping has changed.

func (*PublicClient) ListAllRecords

func (c *PublicClient) ListAllRecords(ctx context.Context, did, collection string) ([]Record, error)

ListAllRecords paginates through every record in a collection on the user's PDS and returns them all, newest-first. Cap of 10k records (100 pages × 100 records).

func (*PublicClient) ListPublicRecords

func (c *PublicClient) ListPublicRecords(ctx context.Context, did, collection string, opts ListPublicRecordsOpts) ([]Record, string, error)

ListPublicRecords fetches records from a public collection. Queries the user's PDS directly, so it works with any collection NSID.

func (*PublicClient) ResolveHandle

func (c *PublicClient) ResolveHandle(ctx context.Context, handle string) (string, error)

ResolveHandle resolves an AT Protocol handle to a DID string. Accepts both Unicode and ASCII (punycode) IDN forms; input is normalized to ASCII before lookup so cache hits are independent of the form supplied.

type PublicProfile

type PublicProfile struct {
	DID         string  `json:"did"`
	Handle      string  `json:"handle"`
	DisplayName *string `json:"displayName,omitempty"`
	Avatar      *string `json:"avatar,omitempty"`
}

PublicProfile is a user's public profile as returned by the Bluesky public API.

type Record

type Record struct {
	URI   string
	CID   string
	Value map[string]any
}

Record represents a single record from a PDS.

type RecordFetcher

type RecordFetcher interface {
	GetRecord(ctx context.Context, collection string, rkey string) (*Record, error)
}

RecordFetcher can fetch a record by collection and record key. atp.Client satisfies this interface.

type SessionInfo

type SessionInfo struct {
	DID       syntax.DID
	SessionID string
	Scopes    []string
}

SessionInfo is returned after a successful OAuth callback.

type URI

type URI struct {
	DID        string
	Collection string
	RKey       string
}

URI holds the parsed components of an AT Protocol URI (at://did/collection/rkey).

func ParseATURI

func ParseATURI(uri string) (*URI, error)

ParseATURI parses an AT-URI and returns its components.

func (*URI) String

func (u *URI) String() string

String reconstructs the AT-URI from its components.

Source Files

  • client.go
  • errors.go
  • oauth.go
  • public.go
  • record.go
  • scopes.go
  • uri.go

Directories

Path Synopsis
Package jetstream consumes real-time AT Protocol events from a Jetstream relay.
Package jetstream consumes real-time AT Protocol events from a Jetstream relay.
Package middleware provides HTTP middleware for AT Protocol authentication.
Package middleware provides HTTP middleware for AT Protocol authentication.
store
bolt
Package bolt provides an oauth.ClientAuthStore backed by BoltDB.
Package bolt provides an oauth.ClientAuthStore backed by BoltDB.
sqlite
Package sqlite provides an oauth.ClientAuthStore backed by SQLite.
Package sqlite provides an oauth.ClientAuthStore backed by SQLite.
Package tracing provides OpenTelemetry span helpers for AT Protocol operations.
Package tracing provides OpenTelemetry span helpers for AT Protocol operations.

Jump to

Keyboard shortcuts

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