Documentation
¶
Index ¶
- Constants
- Variables
- func BuildATURI(did, collection, rkey string) string
- func DisplayHandle(handle string) string
- func NormalizeHandle(handle string) string
- func RKeyFromURI(uri string) string
- func ResolveHandle(ctx context.Context, handle string) (string, error)
- func ResolveRecord[T any](ctx context.Context, fetcher RecordFetcher, atURI string, ...) (*T, error)
- func ScopesForCollections(collections ...string) []string
- func ValidateRKey(rkey string) bool
- func WrapPDSError(err error) error
- type BlobRef
- type CIDLink
- type Client
- func (c *Client) APIClient() *atclient.APIClient
- func (c *Client) CreateRecord(ctx context.Context, collection string, record any) (uri, cid string, err error)
- func (c *Client) CreateRecordWithRKey(ctx context.Context, collection, rkey string, record any) (uri, cid string, err error)
- func (c *Client) DID() syntax.DID
- func (c *Client) DeleteRecord(ctx context.Context, collection, rkey string) error
- func (c *Client) GetBlob(ctx context.Context, cid string) ([]byte, error)
- func (c *Client) GetRecord(ctx context.Context, collection, rkey string) (*Record, error)
- func (c *Client) ListAllRecords(ctx context.Context, collection string) ([]Record, error)
- func (c *Client) ListRecords(ctx context.Context, collection string, limit int, cursor string) (*ListResult, error)
- func (c *Client) PutRecord(ctx context.Context, collection, rkey string, record any) (uri, cid string, err error)
- func (c *Client) UploadBlob(ctx context.Context, data []byte, mimeType string) (*BlobRef, error)
- type ListPublicRecordsOpts
- type ListResult
- type OAuthApp
- func (a *OAuthApp) ClientMetadata() oauth.ClientMetadata
- func (a *OAuthApp) DeleteSession(ctx context.Context, did syntax.DID, sessionID string) error
- func (a *OAuthApp) HandleCallback(ctx context.Context, params url.Values) (*SessionInfo, error)
- func (a *OAuthApp) LoginCLI(ctx context.Context, handle string) (*SessionInfo, error)
- func (a *OAuthApp) Logout(ctx context.Context, did syntax.DID, sessionID string) error
- func (a *OAuthApp) ResumeSession(ctx context.Context, did syntax.DID, sessionID string) (*Client, error)
- func (a *OAuthApp) SessionScopes(ctx context.Context, did syntax.DID, sessionID string) ([]string, error)
- func (a *OAuthApp) StartLogin(ctx context.Context, handle string) (string, error)
- func (a *OAuthApp) StartLoginWithScopes(ctx context.Context, handle string, scopes []string) (string, error)
- func (a *OAuthApp) StartSignup(ctx context.Context, pdsURL string) (string, error)
- func (a *OAuthApp) Store() oauth.ClientAuthStore
- type OAuthConfig
- type PublicClient
- func (c *PublicClient) GetPDSEndpoint(ctx context.Context, did string) (string, error)
- func (c *PublicClient) GetProfile(ctx context.Context, actor string) (*PublicProfile, error)
- func (c *PublicClient) GetPublicRecord(ctx context.Context, did, collection, rkey string) (*Record, error)
- func (c *PublicClient) InvalidateDID(did string)
- func (c *PublicClient) InvalidateHandle(handle string)
- func (c *PublicClient) ListAllRecords(ctx context.Context, did, collection string) ([]Record, error)
- func (c *PublicClient) ListPublicRecords(ctx context.Context, did, collection string, opts ListPublicRecordsOpts) ([]Record, string, error)
- func (c *PublicClient) ResolveHandle(ctx context.Context, handle string) (string, error)
- type PublicProfile
- type Record
- type RecordFetcher
- type SessionInfo
- type URI
Constants ¶
const MaxBlobSize = 1024 * 1024
Maximum PDS blob size (1 MB).
const MaxRKeyLength = 512
MaxRKeyLength is the maximum allowed length for a record key.
Variables ¶
ErrSSRFBlocked is returned when a request is blocked due to a private/internal destination.
ErrSessionExpired indicates the OAuth session can no longer be resumed. Callers should prompt the user to re-authenticate.
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.
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 ¶
BuildATURI constructs an AT-URI string from its components.
func DisplayHandle ¶
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 ¶
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 ¶
RKeyFromURI extracts the record key from an AT-URI. Returns empty string on error.
func ResolveHandle ¶
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 ¶
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 ¶
ValidateRKey checks if an rkey is valid according to AT Protocol spec. Returns true if valid, false otherwise.
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 ¶
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 ¶
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 ¶
APIClient returns the underlying indigo APIClient for advanced usage (custom XRPC calls, service proxying, etc.).
func (*Client) CreateRecord ¶
func (*Client) CreateRecordWithRKey ¶
func (*Client) DeleteRecord ¶
func (*Client) GetRecord ¶
GetRecord retrieves a single record by collection and record key.
func (*Client) ListAllRecords ¶
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 ¶
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 ¶
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 ¶
DeleteSession removes an OAuth session (for logout).
func (*OAuthApp) HandleCallback ¶
HandleCallback processes the OAuth callback after user authorization. Pass r.URL.Query() from the callback request.
func (*OAuthApp) LoginCLI ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SessionInfo is returned after a successful OAuth callback.
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. |