README.md

CoreATProtocol #

A Swift package providing the foundational networking layer for interacting with the AT Protocol (Authenticated Transfer Protocol). This library handles the core HTTP communication, authentication token management, and request/response encoding required to build AT Protocol clients.

Overview #

CoreATProtocol is designed to be protocol-agnostic within the AT Protocol ecosystem. It provides the networking infrastructure that higher-level packages (like bskyKit for Bluesky) can build upon to implement specific lexicons.

Key Features #

  • Modern Swift Concurrency - Built with Swift 6.2 using async/await and actors for thread-safe operations
  • Global Actor Isolation - Uses @APActor for consistent thread safety across all AT Protocol operations
  • Flexible Network Routing - Generic NetworkRouter that works with any endpoint conforming to EndpointType
  • ATProto OAuth - First-party OAuth client with DPoP, PAR, issuer validation, and identity resolution (handle or DID)
  • Automatic Token Management - Built-in support for JWT access/refresh token handling with automatic retry on expiration
  • Multiple Parameter Encodings - URL, JSON, and combined encoding strategies for request parameters
  • AT Protocol Error Handling - Typed error responses matching AT Protocol error specifications
  • Testable Architecture - Protocol-based design allows easy mocking for unit tests
  • Jetstream - The JetstreamKit product reads the event stream with reconnects, host failover and both wire formats

Requirements #

  • Swift 6.2+
  • iOS 17.0+ / macOS 14.0+ / watchOS 11.0+ / tvOS 17.0+ / Mac Catalyst 17.0+

Installation #

Swift Package Manager #

Add CoreATProtocol to your Package.swift dependencies:

dependencies: [
    .package(url: "https://tangled.org/@sparrowtek.com/CoreATProtocol", branch: "main"),
]

Then add it to your target dependencies:

.target(
    name: "YourTarget",
    dependencies: ["CoreATProtocol"]
),

Or in Xcode: File > Add Package Dependencies and enter:

https://tangled.org/@sparrowtek.com/CoreATProtocol

Usage #

Initial Setup #

Configure the environment with your host URL and authentication tokens:

import CoreATProtocol

// Setup with host and tokens
await setup(
    hostURL: "https://bsky.social",
    accessJWT: "your-access-token",
    refreshJWT: "your-refresh-token"
)

// Or update tokens later
await updateTokens(access: newAccessToken, refresh: newRefreshToken)

// Change host
await update(hostURL: "https://different-pds.example")

OAuth Authentication #

Use ATProtoOAuth for OAuth login flows:

import CoreATProtocol

let oauth = await ATProtoOAuth(
    config: .init(
        clientMetadataURL: "https://example.com/client-metadata.json",
        redirectURI: "com.example.app:/oauth/callback"
    ),
    storage: .init(
        retrieveLogin: { nil },
        storeLogin: { _ in },
        retrievePrivateKey: { nil },
        storePrivateKey: { _ in }
    )
)

let result = try await oauth.authenticate(identifier: "alice.bsky.social") { authURL, _ in
    // Present authURL to the user and return callback URL.
    fatalError("Implement user-auth callback handling")
}

await setup(hostURL: result.pdsEndpoint, accessJWT: result.accessToken, refreshJWT: result.refreshToken)

authenticate always takes the user through their account host's sign-in page. A login already in storage is only replaced once new tokens arrive, so a cancelled or failed attempt leaves an existing session as it was.

What it throws:

  • whatever your callback throws (a cancelled web session, for one), unchanged
  • URLError when the network fails
  • ATProtoOAuthError for everything else. A refusal from the token endpoint is .tokenRequestFailed, and its text starts with the server's OAuth error code (invalid_grant: …)

The flow follows the AT Protocol OAuth profile: PKCE, pushed authorization requests, DPoP with per-server nonces, and a check that the tokens are for the account that was asked for. A confidential client sets authProxyBaseURL and clientAuthMethod: .privateKeyJWT; its requests then go through atproto-auth-proxy, which holds the client's signing key.

Refreshing the session #

refreshLoginIfNeeded(accountIdentifier:force:) trades the stored refresh token for new tokens and stores them. Give the session a handler that calls it, and a request the server refuses for its access token (a 401) is refreshed and sent again:

await setTokenRefreshHandler {
    let oauth = await ATProtoOAuth(config: config, storage: storage)
    do {
        guard let login = try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: true) else { return false }
        await updateTokens(access: login.accessToken.value, refresh: login.refreshToken?.value)
        return true
    } catch let error as ATProtoOAuthError where error.endsSession {
        // The server refused the refresh token itself. Sign the user out.
        return false
    } catch {
        // No verdict on the session: offline, a proxy outage, a server that could not check the client just then.
        return false
    }
}

A refresh token works once, and a server that is shown one twice ends the whole session. So the answer to a refresh is the only copy of the next token, and the library does what it can to not lose it:

  • Callers that refresh the same session at the same time share one exchange, and a caller whose turn comes after someone else's refresh takes what that one stored.
  • An exchange that has started is finished: cancelling the caller does not cancel it, and on iOS the system is asked not to suspend the app until the new tokens are stored.
  • A request that gets no answer is sent again with the same token, twice at most. Through the auth proxy that recovers the tokens of a refresh whose answer was lost on the way, because the proxy keeps it for ten minutes.
  • A request is only refreshed for when that can help: not for a 403, not when another request already replaced the token it was sent with, and not for a token that is seconds old.

Sign the user out only when ATProtoOAuthError.endsSession is true: the server answered invalid_grant, or the stored session lacks a part that refreshing needs. Every other failure leaves the session as it was. In particular invalid_client and invalid_client_metadata are about the client, not the grant, and pass. tokenEndpointErrorCode gives the server's code when you need it; don't search the error's text for one.

Defining Endpoints #

Create endpoints by conforming to EndpointType:

import CoreATProtocol

enum MyEndpoint: EndpointType {
    case getProfile(actor: String)
    case createPost(text: String)

    var baseURL: URL {
        get async {
            URL(string: APEnvironment.current.host ?? "https://bsky.social")!
        }
    }

    var path: String {
        switch self {
        case .getProfile:
            return "/xrpc/app.bsky.actor.getProfile"
        case .createPost:
            return "/xrpc/com.atproto.repo.createRecord"
        }
    }

    var httpMethod: HTTPMethod {
        switch self {
        case .getProfile: return .get
        case .createPost: return .post
        }
    }

    var task: HTTPTask {
        get async {
            switch self {
            case .getProfile(let actor):
                return .requestParameters(encoding: .urlEncoding(parameters: ["actor": actor]))
            case .createPost(let text):
                let body: [String: Any] = ["text": text]
                return .requestParameters(encoding: .jsonEncoding(parameters: body))
            }
        }
    }

    var headers: HTTPHeaders? {
        get async { nil }
    }
}

Making Requests #

Use NetworkRouter to execute requests:

@APActor
class MyATClient {
    private let router = NetworkRouter<MyEndpoint>()

    init() {
        router.delegate = APEnvironment.current.routerDelegate
    }

    func getProfile(actor: String) async throws -> ProfileResponse {
        try await router.execute(.getProfile(actor: actor))
    }
}

Custom JSON Decoding #

Use the pre-configured AT Protocol decoder for proper date handling:

let router = NetworkRouter<MyEndpoint>(decoder: .atDecoder)

Error Handling #

Handle AT Protocol specific errors:

do {
    let profile: Profile = try await router.execute(.getProfile(actor: "did:plc:example"))
} catch let error as AtError {
    switch error {
    case .message(let errorMessage):
        print("AT Error: \(errorMessage.error) - \(errorMessage.message ?? "")")
    case .network(let networkError):
        switch networkError {
        case .statusCode(let code, let data):
            print("HTTP \(code?.rawValue ?? 0)")
        case .encodingFailed:
            print("Failed to encode request")
        default:
            print("Network error: \(networkError)")
        }
    }
}

Reading Jetstream #

The JetstreamKit product reads the Jetstream event stream and re-exports CoreATProtocol. A JetstreamClient connects, backs off, moves between hosts and works out where to resume on its own, until the task iterating it is cancelled:

.product(name: "JetstreamKit", package: "CoreATProtocol")
import JetstreamKit

let client = JetstreamClient(
    hosts: [
        .v2("wss://jetstream.us-east.bsky.network"),
        .v2("wss://jetstream.us-west.bsky.network"),
        .v1("wss://index.tangled.network"),
    ],
    filter: JetstreamFilter(collections: ["org.tangled.*"], kinds: [.commit])
)

for try await delivery in client.deliveries(resumingFrom: savedPosition) {
    switch delivery {
    case .event(.commit(let commit), let position, let isLive):
        try await handle(commit, isLive: isLive)
        savedPosition = position
    case .info(let info) where info.name == JetstreamInfo.outdatedCursor:
        savedPosition = nil // The host no longer has it; the client is now on the live tail.
    default:
        break
    }
}

v2 hosts use sequence-number cursors and v1 hosts (the original /subscribe wire) use timestamps; a commit decodes to the same JetstreamCommit from either, minus the seq. A position resumes by seq only on the host that issued it and by its time, rewound five seconds, anywhere else, so delivery is at least once and handlers must tolerate seeing an event twice. Frames are read only as the consumer asks for them, so a slow consumer slows the socket rather than filling a buffer.

URLSessionJetstreamTransport is the default transport. URLSession has no WebSockets on Linux with Ubuntu's libcurl, so a server supplies its own JetstreamTransport, for example on a NIO WebSocket client, and tests can use ScriptedJetstreamTransport. The tests that read the public hosts are opt-in, and scripts/capture-frames.sh refreshes the captured frames the others use:

CORE_ATPROTOCOL_LIVE_TESTS=1 swift test --filter LiveJetstreamTests

Architecture #

Core Components #

Component Description
APActor Global actor ensuring thread-safe access to AT Protocol state
APEnvironment Singleton holding host URL, tokens, and delegates
NetworkRouter Generic router executing typed endpoint requests
EndpointType Protocol defining API endpoint requirements
ParameterEncoding Enum supporting URL, JSON, and hybrid encoding
AtError AT Protocol error types with message parsing

Thread Safety #

All AT Protocol operations are isolated to @APActor ensuring thread-safe access:

@APActor
public func myFunction() async {
    // Safe access to APEnvironment.current
}

Parameter Encoding Options #

// URL query parameters
.urlEncoding(parameters: ["key": "value"])

// JSON body
.jsonEncoding(parameters: ["key": "value"])

// Pre-encoded JSON data
.jsonDataEncoding(data: jsonData)

// Encodable objects
.jsonEncodableEncoding(encodable: myStruct)

// Combined URL + JSON body
.urlAndJsonEncoding(urlParameters: ["q": "search"], bodyParameters: ["data": "value"])
  • bskyKit - Bluesky-specific lexicon implementations built on CoreATProtocol

License #

This project is licensed under an MIT license.

Contributing #

It is always a good idea to discuss before taking on a significant task. That said, I have a strong bias towards enthusiasm. If you are excited about doing something, I'll do my best to get out of your way.

By participating in this project you agree to abide by the Contributor Code of Conduct.