From e2334495053b491b6d4cfafae960f998ffee1ce8 Mon Sep 17 00:00:00 2001 From: Thomas Rademaker Date: Wed, 29 Apr 2026 12:35:14 -0400 Subject: [PATCH] begin updating auth --- Sources/CoreATProtocol/APEnvironment.swift | 7 + Sources/CoreATProtocol/CoreATProtocol.swift | 12 +- Sources/CoreATProtocol/Networking.swift | 84 +---- .../CoreATProtocol/OAuth/ATProtoOAuth.swift | 98 ++--- .../OAuth/DPoPProofSigner.swift | 149 ++++++++ .../DPoPProofSignerTests.swift | 200 ++++++++++ Tests/CoreATProtocolTests/OAuthTests.swift | 1 + update_auth.md | 341 ++++++++++++++++++ 8 files changed, 751 insertions(+), 141 deletions(-) create mode 100644 Sources/CoreATProtocol/OAuth/DPoPProofSigner.swift create mode 100644 Tests/CoreATProtocolTests/DPoPProofSignerTests.swift create mode 100644 update_auth.md diff --git a/Sources/CoreATProtocol/APEnvironment.swift b/Sources/CoreATProtocol/APEnvironment.swift index 1b061c2..eec0524 100644 --- a/Sources/CoreATProtocol/APEnvironment.swift +++ b/Sources/CoreATProtocol/APEnvironment.swift @@ -25,6 +25,12 @@ public final class ATProtoSession { public var tokenRefreshHandler: (@Sendable () async throws -> Bool)? public var dpopPrivateKey: ES256PrivateKey? public var dpopKeys: JWTKeyCollection? + /// Per-session signer that owns the DPoP key and the per-origin nonce + /// cache (RFC 9449). Populated by ``setDPoPPrivateKey(pem:)``; production + /// signing paths read from this property rather than the legacy + /// ``dpopPrivateKey`` / ``dpopKeys`` / ``dpopNonceStore`` fields, which + /// are retained for source compatibility until the next major release. + public var dpopProofSigner: DPoPProofSigner? public let dpopNonceStore = DPoPNonceStore() public let clockSkewStore = ClockSkewStore() public let routerDelegate = APRouterDelegate() @@ -44,6 +50,7 @@ public final class ATProtoSession { tokenRefreshHandler = nil dpopPrivateKey = nil dpopKeys = nil + dpopProofSigner = nil await dpopNonceStore.clear() await clockSkewStore.update(offset: 0) } diff --git a/Sources/CoreATProtocol/CoreATProtocol.swift b/Sources/CoreATProtocol/CoreATProtocol.swift index 1b1529c..da8c0f3 100644 --- a/Sources/CoreATProtocol/CoreATProtocol.swift +++ b/Sources/CoreATProtocol/CoreATProtocol.swift @@ -57,13 +57,23 @@ public func setDPoPPrivateKey(pem: String?) async throws { guard let pem, !pem.isEmpty else { ATProtoSession.shared.dpopPrivateKey = nil ATProtoSession.shared.dpopKeys = nil + ATProtoSession.shared.dpopProofSigner = nil return } let privateKey = try ES256PrivateKey(pem: pem) + let signer = await DPoPProofSigner( + privateKey: privateKey, + clockSkew: ATProtoSession.shared.clockSkewStore + ) + ATProtoSession.shared.dpopProofSigner = signer + + // Backward-compat: keep the legacy fields populated until they are + // removed in a future major release. Production signing paths read from + // ``dpopProofSigner``; these are only here so external callers that read + // the public fields keep observing a non-nil value. let keys = JWTKeyCollection() await keys.add(ecdsa: privateKey) - ATProtoSession.shared.dpopPrivateKey = privateKey ATProtoSession.shared.dpopKeys = keys } diff --git a/Sources/CoreATProtocol/Networking.swift b/Sources/CoreATProtocol/Networking.swift index 7670b67..fddbe6c 100644 --- a/Sources/CoreATProtocol/Networking.swift +++ b/Sources/CoreATProtocol/Networking.swift @@ -6,8 +6,6 @@ // import Foundation -import Crypto -import JWTKit import NetworkingKit import OAuthenticator import os @@ -55,11 +53,15 @@ public class APRouterDelegate: NetworkRouterDelegate { public func intercept(_ request: inout URLRequest) async { guard let accessToken = await ATProtoSession.shared.accessToken else { return } - if let dpopKey = await ATProtoSession.shared.dpopPrivateKey, - let keys = await ATProtoSession.shared.dpopKeys { - // DPoP-bound token: use "DPoP" scheme + DPoP proof header + if let signer = await ATProtoSession.shared.dpopProofSigner, + let url = request.url, + let method = request.httpMethod { do { - let proof = try await generateDPoPProof(for: request, accessToken: accessToken, privateKey: dpopKey, keys: keys) + let proof = try await signer.sign(.init( + httpMethod: method, + url: url, + accessToken: accessToken + )) request.setValue("DPoP \(accessToken)", forHTTPHeaderField: "Authorization") request.setValue(proof, forHTTPHeaderField: "DPoP") } catch { @@ -78,57 +80,6 @@ public class APRouterDelegate: NetworkRouterDelegate { } } - private func generateDPoPProof( - for request: URLRequest, - accessToken: String, - privateKey: ES256PrivateKey, - keys: JWTKeyCollection - ) async throws -> String { - guard let method = request.httpMethod, - let url = request.url else { - throw AtError.message(ErrorMessage(error: "DPoPProofInvalidRequest", message: "Request is missing method or URL")) - } - - // Strip query and fragment per DPoP spec - var components = URLComponents(url: url, resolvingAgainstBaseURL: false) - components?.query = nil - components?.fragment = nil - let htu = components?.url?.absoluteString ?? url.absoluteString - - // Read the nonce at proof-generation time so a concurrent update - // between intercept() and sign() is observed on the next retry. - let nonce = await ATProtoSession.shared.dpopNonceStore.get() - let issuedAt = await ATProtoSession.shared.clockSkewStore.serverAdjustedNow() - - // ath: base64url-encoded SHA-256 hash of the access token (RFC 9449 §4.2) - let hash = SHA256.hash(data: Data(accessToken.utf8)) - let ath = Data(hash).base64URLEncodedString() - - let payload = DPoPProofPayload( - htm: method, - htu: htu, - iat: .init(value: issuedAt), - jti: .init(value: UUID().uuidString), - nonce: nonce, - ath: ath - ) - - var header = JWTHeader() - header.typ = "dpop+jwt" - header.alg = "ES256" - - if let keyParams = privateKey.parameters { - header.jwk = [ - "kty": .string("EC"), - "crv": .string("P-256"), - "x": .string(keyParams.x.base64URLEncoded()), - "y": .string(keyParams.y.base64URLEncoded()), - ] - } - - return try await keys.sign(payload, header: header) - } - public func didReceiveErrorResponse(_ response: HTTPURLResponse) async { // Record clock skew from any response that carries a Date header. // DPoP rejections often correlate with skew, so harvest this eagerly. @@ -140,6 +91,12 @@ public class APRouterDelegate: NetworkRouterDelegate { let headerNonce = response.value(forHTTPHeaderField: "DPoP-Nonce") ?? response.value(forHTTPHeaderField: "dpop-nonce") if let headerNonce { + if let url = response.url, + let signer = await ATProtoSession.shared.dpopProofSigner { + await signer.cacheNonce(headerNonce, from: url) + } + // Backward-compat: keep the single-slot store updated for + // external readers of the public ``dpopNonceStore`` accessor. await ATProtoSession.shared.dpopNonceStore.update(headerNonce) lastErrorHadNonceHeader = true } else { @@ -217,19 +174,6 @@ public class APRouterDelegate: NetworkRouterDelegate { } } -// MARK: - DPoP Proof Payload - -private struct DPoPProofPayload: JWTPayload { - let htm: String - let htu: String - let iat: IssuedAtClaim - let jti: IDClaim - let nonce: String? - let ath: String? - - func verify(using key: some JWTAlgorithm) throws {} -} - private enum DateParser { static let formatters: [DateFormatter] = { let formats = [ diff --git a/Sources/CoreATProtocol/OAuth/ATProtoOAuth.swift b/Sources/CoreATProtocol/OAuth/ATProtoOAuth.swift index df48d80..d1e93f7 100644 --- a/Sources/CoreATProtocol/OAuth/ATProtoOAuth.swift +++ b/Sources/CoreATProtocol/OAuth/ATProtoOAuth.swift @@ -157,9 +157,8 @@ public final class ATProtoOAuth: Sendable { private let dpopRequestActor = DPoPRequestActor() private var hasPersistedKey: Bool - // JWT signing keys (pattern from AtProtocol) - private var keys: JWTKeyCollection private var privateKey: ES256PrivateKey + private var proofSigner: DPoPProofSigner private struct AuthenticationAttemptResult { let login: Login @@ -171,7 +170,6 @@ public final class ATProtoOAuth: Sendable { self.storage = storage self.identityResolver = IdentityResolver() - // Initialize JWT keys (from AtProto.swift lines 19-23) if let storedKeyData = try? await storage.retrievePrivateKey(), let pem = String(data: storedKeyData, encoding: .utf8), let restoredKey = try? ES256PrivateKey(pem: pem) { @@ -181,8 +179,10 @@ public final class ATProtoOAuth: Sendable { self.privateKey = ES256PrivateKey() self.hasPersistedKey = false } - self.keys = JWTKeyCollection() - await self.keys.add(ecdsa: privateKey) + self.proofSigner = await DPoPProofSigner( + privateKey: privateKey, + clockSkew: ATProtoSession.shared.clockSkewStore + ) } /// Initialize with existing private key (for session restoration) @@ -191,11 +191,12 @@ public final class ATProtoOAuth: Sendable { self.storage = storage self.identityResolver = IdentityResolver() - // Restore existing key self.privateKey = try ES256PrivateKey(pem: privateKeyPEM) self.hasPersistedKey = true - self.keys = JWTKeyCollection() - await self.keys.add(ecdsa: privateKey) + self.proofSigner = await DPoPProofSigner( + privateKey: privateKey, + clockSkew: ATProtoSession.shared.clockSkewStore + ) } /// Authenticate user by handle @@ -523,55 +524,24 @@ public final class ATProtoOAuth: Sendable { privateKey.pemRepresentation } - // MARK: - Private (from AtProto.swift lines 60-72) + // MARK: - Private private func generateJWT(params: DPoPSigner.JWTParameters) async throws -> String { - // Strip query params and fragments from htu per DPoP spec - let htu = stripQueryAndFragment(from: params.requestEndpoint) - - let issuedAt = await ATProtoSession.shared.clockSkewStore.serverAdjustedNow() - - let payload = DPoPPayload( - htm: params.httpMethod, - htu: htu, - iat: .init(value: issuedAt), - jti: .init(value: UUID().uuidString), - nonce: params.nonce - ) - - // DPoP requires typ="dpop+jwt", alg="ES256", and the public key in jwk header - var header = JWTHeader() - header.typ = "dpop+jwt" - header.alg = "ES256" - - // Get public key parameters and convert to base64url for JWK - if let keyParams = privateKey.parameters { - header.jwk = [ - "kty": .string("EC"), - "crv": .string("P-256"), - "x": .string(keyParams.x.base64URLEncoded()), - "y": .string(keyParams.y.base64URLEncoded()) - ] - } - - return try await self.keys.sign(payload, header: header) - } - - /// Strip query string and fragment from URL per DPoP spec - private func stripQueryAndFragment(from url: String) -> String { - let fragmentIndex = url.firstIndex(of: "#").map { url.distance(from: url.startIndex, to: $0) } ?? -1 - let queryIndex = url.firstIndex(of: "?").map { url.distance(from: url.startIndex, to: $0) } ?? -1 - - let end: Int - if fragmentIndex == -1 { - end = queryIndex - } else if queryIndex == -1 { - end = fragmentIndex - } else { - end = min(fragmentIndex, queryIndex) + guard let url = URL(string: params.requestEndpoint) else { + throw ATProtoOAuthError.malformedServerMetadata( + field: "request_endpoint", + value: params.requestEndpoint + ) } - - return end == -1 ? url : String(url.prefix(end)) + // OAuthenticator's `DPoPSigner` already tracks the auth-server nonce + // for this exchange — pass it through so we don't consult the + // proof signer's per-origin cache (which is owned by the XRPC layer). + return try await proofSigner.sign(.init( + httpMethod: params.httpMethod, + url: url, + accessToken: nil, + explicitNonce: params.nonce + )) } private func stripScheme(from url: String) -> String { @@ -594,8 +564,10 @@ public final class ATProtoOAuth: Sendable { private func resetDPoPKey() async throws { privateKey = ES256PrivateKey() - keys = JWTKeyCollection() - await keys.add(ecdsa: privateKey) + proofSigner = await DPoPProofSigner( + privateKey: privateKey, + clockSkew: ATProtoSession.shared.clockSkewStore + ) hasPersistedKey = false try await persistPrivateKey() } @@ -908,20 +880,6 @@ public final class ATProtoOAuth: Sendable { } } -// MARK: - DPoP Payload (from AtProto.swift lines 88-98) - -private struct DPoPPayload: JWTPayload { - let htm: String - let htu: String - let iat: IssuedAtClaim - let jti: IDClaim - let nonce: String? - - func verify(using key: some JWTAlgorithm) throws { - // No additional verification needed for DPoP - } -} - private actor DPoPRequestActor { private let signer = DPoPSigner() diff --git a/Sources/CoreATProtocol/OAuth/DPoPProofSigner.swift b/Sources/CoreATProtocol/OAuth/DPoPProofSigner.swift new file mode 100644 index 0000000..d0b03e8 --- /dev/null +++ b/Sources/CoreATProtocol/OAuth/DPoPProofSigner.swift @@ -0,0 +1,149 @@ +// +// DPoPProofSigner.swift +// CoreATProtocol +// + +import Foundation +import Crypto +import JWTKit + +/// Owns the DPoP signing key, the per-origin nonce cache, and proof-JWT +/// generation for a single AT Protocol session. +/// +/// One `DPoPProofSigner` per logical session. Nonces are keyed by origin +/// (`scheme://host[:port]`) per RFC 9449 — the auth server and the PDS have +/// independent nonce streams, and using the wrong one causes a spurious +/// `use_dpop_nonce` challenge on the next request. +/// +/// The type name avoids a collision with `OAuthenticator.DPoPSigner`, which +/// fills a different role (a per-flow nonce holder used by `Authenticator`). +public actor DPoPProofSigner { + public struct ProofParameters: Sendable { + public let httpMethod: String + public let url: URL + /// Access token to bind via the `ath` claim (RFC 9449 §4.2). Pass + /// `nil` for unauthenticated requests like PAR or token exchange. + public let accessToken: String? + /// When non-nil, overrides any cached nonce for this URL's origin. + /// Used when an external party (e.g. `OAuthenticator.DPoPSigner`) is + /// already tracking the DPoP nonce for the exchange and the cache + /// should not be consulted. + public let explicitNonce: String? + + public init( + httpMethod: String, + url: URL, + accessToken: String? = nil, + explicitNonce: String? = nil + ) { + self.httpMethod = httpMethod + self.url = url + self.accessToken = accessToken + self.explicitNonce = explicitNonce + } + } + + private var privateKey: ES256PrivateKey + private var keys: JWTKeyCollection + private let clockSkew: ClockSkewStore + private var noncesByOrigin: [String: String] = [:] + private let nonceCacheLimit = 25 + + public init(privateKey: ES256PrivateKey, clockSkew: ClockSkewStore) async { + self.privateKey = privateKey + let keys = JWTKeyCollection() + await keys.add(ecdsa: privateKey) + self.keys = keys + self.clockSkew = clockSkew + } + + public var pemRepresentation: String { privateKey.pemRepresentation } + + public func sign(_ params: ProofParameters) async throws -> String { + let htu = Self.canonicalHTU(params.url) + let nonce: String? + if let explicit = params.explicitNonce { + nonce = explicit + } else if let origin = Self.origin(for: params.url) { + nonce = noncesByOrigin[origin] + } else { + nonce = nil + } + let issuedAt = await clockSkew.serverAdjustedNow() + let ath = params.accessToken.map(Self.athClaim) + + var header = JWTHeader() + header.typ = "dpop+jwt" + header.alg = "ES256" + if let keyParams = privateKey.parameters { + header.jwk = [ + "kty": .string("EC"), + "crv": .string("P-256"), + "x": .string(keyParams.x.base64URLEncoded()), + "y": .string(keyParams.y.base64URLEncoded()), + ] + } + + let payload = DPoPProofPayload( + htm: params.httpMethod, + htu: htu, + iat: .init(value: issuedAt), + jti: .init(value: UUID().uuidString), + nonce: nonce, + ath: ath + ) + return try await keys.sign(payload, header: header) + } + + /// Records `nonce` against the origin of `url`. When the cache is full and + /// the origin isn't already tracked, an arbitrary entry is evicted to keep + /// growth bounded — a true LRU is overkill since the realistic origin + /// count is two (auth server and PDS). + public func cacheNonce(_ nonce: String, from url: URL) { + guard let origin = Self.origin(for: url) else { return } + if noncesByOrigin.count >= nonceCacheLimit, noncesByOrigin[origin] == nil { + if let key = noncesByOrigin.keys.first { + noncesByOrigin.removeValue(forKey: key) + } + } + noncesByOrigin[origin] = nonce + } + + public func clearNonces() { + noncesByOrigin.removeAll() + } + + // MARK: - Helpers + + static func canonicalHTU(_ url: URL) -> String { + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) + components?.query = nil + components?.fragment = nil + return components?.url?.absoluteString ?? url.absoluteString + } + + static func origin(for url: URL) -> String? { + guard let scheme = url.scheme?.lowercased(), + let host = url.host?.lowercased() else { + return nil + } + let port = url.port.map { ":\($0)" } ?? "" + return "\(scheme)://\(host)\(port)" + } + + static func athClaim(for accessToken: String) -> String { + let hash = SHA256.hash(data: Data(accessToken.utf8)) + return Data(hash).base64URLEncodedString() + } +} + +private struct DPoPProofPayload: JWTPayload { + let htm: String + let htu: String + let iat: IssuedAtClaim + let jti: IDClaim + let nonce: String? + let ath: String? + + func verify(using key: some JWTAlgorithm) throws {} +} diff --git a/Tests/CoreATProtocolTests/DPoPProofSignerTests.swift b/Tests/CoreATProtocolTests/DPoPProofSignerTests.swift new file mode 100644 index 0000000..a5e7c23 --- /dev/null +++ b/Tests/CoreATProtocolTests/DPoPProofSignerTests.swift @@ -0,0 +1,200 @@ +import Foundation +import Testing +import JWTKit +@testable import CoreATProtocol + +@Suite("DPoPProofSigner") +struct DPoPProofSignerTests { + @Test("Sign emits a dpop+jwt header with embedded JWK") + func dpopJwtType() async throws { + let signer = await makeSigner() + let url = try #require(URL(string: "https://pds.example/xrpc/foo")) + + let jwt = try await signer.sign(.init( + httpMethod: "POST", + url: url, + accessToken: "tok" + )) + + let header = try decodeJWTHeader(jwt) + #expect(header["typ"] as? String == "dpop+jwt") + #expect(header["alg"] as? String == "ES256") + + let jwk = try #require(header["jwk"] as? [String: Any]) + #expect(jwk["kty"] as? String == "EC") + #expect(jwk["crv"] as? String == "P-256") + #expect((jwk["x"] as? String)?.isEmpty == false) + #expect((jwk["y"] as? String)?.isEmpty == false) + } + + @Test("htu strips query string and fragment") + func htuStripsQueryAndFragment() async throws { + let signer = await makeSigner() + let url = try #require(URL(string: "https://pds.example/xrpc/foo?bar=baz#frag")) + + let jwt = try await signer.sign(.init(httpMethod: "POST", url: url)) + + let payload = try decodeJWTPayload(jwt) + #expect(payload["htu"] as? String == "https://pds.example/xrpc/foo") + #expect(payload["htm"] as? String == "POST") + } + + @Test("ath claim is present only when an access token is supplied") + func athPresentOnlyWhenAccessTokenProvided() async throws { + let signer = await makeSigner() + let url = try #require(URL(string: "https://pds.example/xrpc/foo")) + + let withToken = try await signer.sign(.init( + httpMethod: "GET", + url: url, + accessToken: "abc" + )) + #expect(try decodeJWTPayload(withToken)["ath"] as? String != nil) + + let withoutToken = try await signer.sign(.init(httpMethod: "GET", url: url)) + #expect(try decodeJWTPayload(withoutToken)["ath"] == nil) + } + + @Test("Nonce cache is keyed per origin") + func nonceCachedPerOrigin() async throws { + let signer = await makeSigner() + let pds = try #require(URL(string: "https://pds.example/xrpc/foo")) + let auth = try #require(URL(string: "https://auth.example/oauth/token")) + + await signer.cacheNonce("pds-nonce", from: pds) + await signer.cacheNonce("auth-nonce", from: auth) + + let pdsJWT = try await signer.sign(.init(httpMethod: "POST", url: pds)) + let authJWT = try await signer.sign(.init(httpMethod: "POST", url: auth)) + + #expect(try decodeJWTPayload(pdsJWT)["nonce"] as? String == "pds-nonce") + #expect(try decodeJWTPayload(authJWT)["nonce"] as? String == "auth-nonce") + } + + @Test("Nonce cache stays bounded under heavy origin churn") + func nonceCacheBounded() async throws { + let signer = await makeSigner() + let totalInsertions = 30 + let cacheLimit = 25 + + for i in 0..= lowerBound) + #expect(iat <= upperBound) + } + + @Test("Explicit nonce overrides any cached value for the URL's origin") + func explicitNonceOverride() async throws { + let signer = await makeSigner() + let url = try #require(URL(string: "https://host.example/foo")) + + await signer.cacheNonce("cached", from: url) + + let withExplicit = try await signer.sign(.init( + httpMethod: "POST", + url: url, + explicitNonce: "explicit" + )) + #expect(try decodeJWTPayload(withExplicit)["nonce"] as? String == "explicit") + + let withoutExplicit = try await signer.sign(.init(httpMethod: "POST", url: url)) + #expect(try decodeJWTPayload(withoutExplicit)["nonce"] as? String == "cached") + } + + @Test("clearNonces drops all cached values") + func clearNoncesEmptiesCache() async throws { + let signer = await makeSigner() + let url = try #require(URL(string: "https://host.example/foo")) + + await signer.cacheNonce("first", from: url) + await signer.clearNonces() + + let jwt = try await signer.sign(.init(httpMethod: "GET", url: url)) + #expect(try decodeJWTPayload(jwt)["nonce"] == nil) + } + + private func makeSigner() async -> DPoPProofSigner { + await DPoPProofSigner( + privateKey: ES256PrivateKey(), + clockSkew: ClockSkewStore() + ) + } +} + +// MARK: - JWT decoding helpers + +private func decodeJWTHeader(_ jwt: String) throws -> [String: Any] { + try decodeJWTSection(jwt, index: 0) +} + +private func decodeJWTPayload(_ jwt: String) throws -> [String: Any] { + try decodeJWTSection(jwt, index: 1) +} + +private func decodeJWTSection(_ jwt: String, index: Int) throws -> [String: Any] { + let parts = jwt.split(separator: ".", omittingEmptySubsequences: false) + guard parts.count == 3, index < parts.count else { + throw JWTTestError.malformedJWT + } + let data = try base64URLDecode(String(parts[index])) + let object = try JSONSerialization.jsonObject(with: data) + return object as? [String: Any] ?? [:] +} + +private func base64URLDecode(_ value: String) throws -> Data { + var base64 = value + .replacingOccurrences(of: "-", with: "+") + .replacingOccurrences(of: "_", with: "/") + let padding = (4 - base64.count % 4) % 4 + base64 += String(repeating: "=", count: padding) + guard let data = Data(base64Encoded: base64) else { + throw JWTTestError.malformedJWT + } + return data +} + +private enum JWTTestError: Error { + case malformedJWT +} diff --git a/Tests/CoreATProtocolTests/OAuthTests.swift b/Tests/CoreATProtocolTests/OAuthTests.swift index e7a42f3..ae05f69 100644 --- a/Tests/CoreATProtocolTests/OAuthTests.swift +++ b/Tests/CoreATProtocolTests/OAuthTests.swift @@ -444,3 +444,4 @@ struct DPoPTests { #expect(keyPEM == restoredKeyPEM) } } + diff --git a/update_auth.md b/update_auth.md new file mode 100644 index 0000000..9769a73 --- /dev/null +++ b/update_auth.md @@ -0,0 +1,341 @@ +# OAuth update plan for CoreATProtocol + +Goal: keep OAuthenticator as the OAuth 2.1 transport, but tighten the AT-Proto-specific layer above it. Borrow the few ideas AtprotoOAuth (MIT, germ-network) does well that genuinely improve correctness, testability, or readability. No library swap. Each step leaves the package building and the existing test suite green. + +## Status (2026-04-29) + +- **Steps 1–2 are landed.** Per-origin DPoP nonce caching is live. CoreATProtocol's 66 tests pass; bskyKit and EffemKit rebuild cleanly against the local checkout. +- **Steps 3–5 are next.** They're independent of each other and any pair of them is a reasonable single-session chunk. +- **Step 6 remains gated** behind a SemVer-major bump. + +See "Notes from the Steps 1+2 implementation" near the bottom for the deviations from the original plan. + +## Inventory of what we have today + +Files (in `Sources/CoreATProtocol/`): +- `OAuth/ATProtoOAuth.swift` — 1016 lines. Authorize / refresh / DPoP JWT generation / token persistence. Single class doing everything. +- `OAuth/AuthProxy.swift` — 294 lines. `URLResponseProvider` interceptor that re-routes PAR + token requests through an auth proxy, with bypass on transport failure. +- `OAuth/IdentityResolver.swift` — 366 lines. Handle ↔ DID ↔ PDS ↔ auth server resolution + bidirectional handle verification. +- `Networking.swift` — `APRouterDelegate` that signs each authenticated XRPC request with a DPoP proof, watches for `use_dpop_nonce`, refreshes on 401/403, harvests clock skew. +- `APEnvironment.swift` — `ATProtoSession.shared` singleton holding tokens + DPoP key + JWT key collection + nonce store + clock skew store. +- `DPoPNonceStore.swift` — single-slot actor for the most recent server nonce. +- `ClockSkewStore.swift` — observed offset between local and server clocks. +- `TokenRefreshCoordinator.swift` — coalesces concurrent refresh attempts. +- `Models/` — `Session`, `AtError`, etc. + +Consumers: +- `bskyKit` re-exports `ATProtoOAuth` as `BskyOAuth` (via `@_exported import CoreATProtocol`). +- `Atprosphere` calls `ATProtoOAuth(config:storage:)` with `clientAuthMethod: .privateKeyJWT` + `authProxyBaseURL`. +- `effem` calls `ATProtoOAuth(config:storage:)` with `authProxyBaseURL` only (default `.none`). +- `ATProtoCLI` does not use OAuth. + +Tests: 1012 lines across 9 files, including `OAuthTests.swift` (446 lines) covering proxy request encoding, key ID storage, DPoP key persistence, and identity resolution. + +## What's worth borrowing from AtprotoOAuth + +1. **Per-origin DPoP nonce cache.** AtprotoOAuth's `OAuth.DPoP.State.nonceCache` is keyed by origin (capped at 25 entries). RFC 9449 lets each server issue its own nonce; the auth server's nonce ≠ the PDS's nonce. Our single-slot store causes spurious `use_dpop_nonce` retries when the most recent nonce is from the wrong origin. +2. **Consolidated DPoP signer type.** AtprotoOAuth bundles `signingKey` + `nonceCache` + `decoder` into one value (`OAuth.DPoP.State`). We have these scattered across `ATProtoSession` (`dpopPrivateKey`, `dpopKeys`, `dpopNonceStore`) and re-thread them through `Networking.swift` and `ATProtoOAuth.swift`. A single `DPoPSigner` actor would hold the lot. +3. **`htu` canonicalization helper.** We strip query+fragment in two places (`Networking.swift` line 92-96 and `ATProtoOAuth.swift` line 561). One small free function. +4. **Pluggable resolver protocol.** Right now `IdentityResolver` is concrete. AtprotoOAuth has `Atproto.Resolver` as a protocol with a default `verifiedResolve` and a `FallbackResolver` that tries primary then secondary. Useful for tests (inject a fake resolver) and for adding Slingshot/community DoH fallback later. +5. **Token validator closure.** AtprotoOAuth pulls token validation (sub matches expected DID, issuer matches expected auth server, DPoP token type, scope contains "atproto") out of the loginProvider into a single throwing closure. Easier to unit test in isolation. We already do this work — just inline. + +What we should *not* borrow: +- `AtprotoOAuthAgent`/`AuthPDSAgent` — couples to germ's XRPC abstraction. +- `OAuth.SessionState.Archive` — our `Login`/`storage` callbacks already do the same job. +- AtprotoTypes `Atproto.DID`/`Handle`/`DIDDocument` — we have our own types, no need to swap. +- The `AsyncStream` save model — a callback closure (what we have) is simpler and equally correct. + +## Plan + +Each step ends with `swift test` passing in `CoreATProtocol/`, then a build of `bskyKit`, Atprosphere, and effem against the local CoreATProtocol checkout. Treat the build of all three apps as the integration gate. + +### Step 1 — Add `DPoPSigner` (the consolidated signer actor) — DONE + +**Why first:** the per-origin nonce fix lands here and is the highest-value correctness improvement. Doing it before the file split keeps later diffs small. + +Create `Sources/CoreATProtocol/OAuth/DPoPSigner.swift`: + +```swift +import Foundation +import Crypto +import JWTKit + +/// Owns the DPoP signing key, the per-origin nonce cache, and JWT generation. +/// +/// One `DPoPSigner` per logical session. Nonces are keyed by origin +/// (`scheme://host[:port]`) per RFC 9449 — the auth server and the PDS have +/// independent nonce streams, and using the wrong one causes a spurious +/// `use_dpop_nonce` challenge on the next request. +public actor DPoPSigner { + public struct ProofParameters: Sendable { + public let httpMethod: String + public let url: URL + /// Access token to bind via `ath`. Pass `nil` for unauthenticated + /// requests (PAR, token exchange). + public let accessToken: String? + } + + private let privateKey: ES256PrivateKey + private let keys: JWTKeyCollection + private var noncesByOrigin: [String: String] = [:] + private let nonceCacheLimit = 25 + private let clockSkew: ClockSkewStore + + public init(privateKey: ES256PrivateKey, clockSkew: ClockSkewStore) async { + self.privateKey = privateKey + let keys = JWTKeyCollection() + await keys.add(ecdsa: privateKey) + self.keys = keys + self.clockSkew = clockSkew + } + + public convenience init(clockSkew: ClockSkewStore) async { + await self.init(privateKey: ES256PrivateKey(), clockSkew: clockSkew) + } + + public var pemRepresentation: String { privateKey.pemRepresentation } + + public func sign(_ params: ProofParameters) async throws -> String { + let htu = Self.canonicalHTU(params.url) + let origin = Self.origin(for: params.url) + let nonce = origin.flatMap { noncesByOrigin[$0] } + let issuedAt = await clockSkew.serverAdjustedNow() + let ath = params.accessToken.map(Self.athClaim) + + var header = JWTHeader() + header.typ = "dpop+jwt" + header.alg = "ES256" + if let p = privateKey.parameters { + header.jwk = [ + "kty": .string("EC"), "crv": .string("P-256"), + "x": .string(p.x.base64URLEncoded()), + "y": .string(p.y.base64URLEncoded()), + ] + } + + let payload = DPoPProofPayload( + htm: params.httpMethod, htu: htu, + iat: .init(value: issuedAt), + jti: .init(value: UUID().uuidString), + nonce: nonce, ath: ath + ) + return try await keys.sign(payload, header: header) + } + + /// Records a nonce against the origin of `url`, evicting the oldest entry + /// if the cache exceeds its limit. + public func cacheNonce(_ nonce: String, from url: URL) { + guard let origin = Self.origin(for: url) else { return } + if noncesByOrigin.count >= nonceCacheLimit, noncesByOrigin[origin] == nil { + // Drop one arbitrary entry. A true LRU is overkill — bounded growth is the goal. + if let key = noncesByOrigin.keys.first { noncesByOrigin.removeValue(forKey: key) } + } + noncesByOrigin[origin] = nonce + } + + public func clearNonces() { noncesByOrigin.removeAll() } + + // MARK: - Helpers + + static func canonicalHTU(_ url: URL) -> String { + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) + components?.query = nil + components?.fragment = nil + return components?.url?.absoluteString ?? url.absoluteString + } + + static func origin(for url: URL) -> String? { + guard let scheme = url.scheme?.lowercased(), + let host = url.host?.lowercased() else { return nil } + let port = url.port.map { ":\($0)" } ?? "" + return "\(scheme)://\(host)\(port)" + } + + static func athClaim(for accessToken: String) -> String { + let hash = SHA256.hash(data: Data(accessToken.utf8)) + return Data(hash).base64URLEncodedString() + } +} + +private struct DPoPProofPayload: JWTPayload { + let htm: String + let htu: String + let iat: IssuedAtClaim + let jti: IDClaim + let nonce: String? + let ath: String? + func verify(using key: some JWTAlgorithm) throws {} +} +``` + +Tests to add (Swift Testing): +- `DPoPSignerTests.signEmitsDpopJwtType` — verify header `typ=dpop+jwt`, `alg=ES256`, JWK has `kty/crv/x/y`. +- `DPoPSignerTests.htuStripsQueryAndFragment` — `https://x/y?z#a` → `https://x/y`. +- `DPoPSignerTests.athPresentOnlyWhenAccessTokenProvided` — round-trip JWT, decode payload, check `ath`. +- `DPoPSignerTests.nonceCachedPerOrigin` — cache nonces for two origins, verify each origin gets its own nonce in the next signed proof. +- `DPoPSignerTests.nonceCacheBounded` — push 30 origins, assert ≤ 25 entries. +- `DPoPSignerTests.iatRespectsClockSkew` — set `ClockSkewStore` offset to +600, sign, decode `iat`, assert ≈ now + 600. + +Don't wire it into `Networking.swift` or `ATProtoOAuth.swift` yet — that's Step 2. + +### Step 2 — Replace ad-hoc DPoP signing in `Networking.swift` and `ATProtoOAuth.swift` — DONE + +`APRouterDelegate.intercept` currently reads `dpopPrivateKey`, `dpopKeys`, `dpopNonceStore` from `ATProtoSession.shared` and builds the proof inline (Networking.swift:55-129). Replace with a call to a `DPoPSigner` held on the session. + +Changes: +- Add `var dpopSigner: DPoPSigner?` to `ATProtoSession`. +- Update `setDPoPPrivateKey(pem:)` in `CoreATProtocol.swift` to instantiate `DPoPSigner` instead of populating `dpopPrivateKey` + `dpopKeys`. +- Replace `APRouterDelegate.generateDPoPProof` body with `try await signer.sign(.init(httpMethod: method, url: url, accessToken: accessToken))`. +- Replace `APRouterDelegate.didReceiveErrorResponse`'s `dpopNonceStore.update(headerNonce)` with `signer.cacheNonce(headerNonce, from: response.url ?? request.url)`. The response URL is the right origin to key on. +- In `ATProtoOAuth.generateJWT` (the auth-server-side signer at line 528), build a `DPoPSigner.ProofParameters` from `params.requestEndpoint` + `params.httpMethod` + `nil` access token. Delete the local `stripQueryAndFragment` helper (line 561). +- Keep `DPoPNonceStore` for now — it backs the deprecated `dpopNonceStore` accessor on the session. Mark it `@available(*, deprecated, message: "Use DPoPSigner.cacheNonce instead.")` and migrate callers in Step 6. +- Keep the existing `dpopPrivateKey` / `dpopKeys` accessors on `ATProtoSession`, but mark them deprecated. They're public, so removing them is a major-version change. + +After this, `Networking.swift` shrinks by ~50 lines. The whole DPoP proof construction lives in one file. + +Tests to update: +- `DPoPStoreTests.swift` continues to test `DPoPNonceStore` for now. The new `DPoPSignerTests` covers the new path. +- Add an integration test in `OAuthTests.swift` that drives a fake `URLResponseProvider`, sees a `DPoP-Nonce` header, and confirms the next outbound proof carries the nonce. + +### Step 3 — Centralize URL canonicalization + origin helpers + +The `htu` and origin logic now lives in `DPoPSigner` (steps 1–2). Two more places use it: +- `ATProtoOAuth.normalizedOrigin(_:)` (line 901) — for issuer comparison. +- `IdentityResolver.normalizedOrigin(from:)` (line 287) — for auth-server-vs-PDS check. + +Both are private and trivially identical. Lift them into a small file `Sources/CoreATProtocol/OAuth/URLOrigin.swift`: + +```swift +enum URLOrigin { + static func normalized(_ url: URL) -> String? { + guard let scheme = url.scheme?.lowercased(), + let host = url.host?.lowercased() else { return nil } + let port = url.port.map { ":\($0)" } ?? "" + return "\(scheme)://\(host)\(port)" + } +} +``` + +Update three call sites (`DPoPSigner.origin`, `ATProtoOAuth.normalizedOrigin`, `IdentityResolver.normalizedOrigin`) to call `URLOrigin.normalized`. Internal helper, no public API change. + +### Step 4 — Extract the token validator closure + +`ATProtoOAuth.loginProvider` (line 759) inlines all the token-response validation: DPoP token type, `atproto` scope, issuer matches expected auth server, sub matches expected DID. Same checks duplicate in `refreshProvider` (line 834). + +Extract to a private helper: + +```swift +private struct TokenValidator: Sendable { + let expectedAuthorizationServer: String + let expectedSubjectDID: String? + + func validate( + response: OAuthTokenResponse, + actualIssuer: String + ) throws { + guard response.tokenType == "DPoP" else { + throw AuthenticatorError.dpopTokenExpected(response.tokenType) + } + guard response.scopes.contains("atproto") else { + throw ATProtoOAuthError.missingRequiredScope("atproto") + } + try ATProtoOAuth.validateIssuer(actualIssuer, matches: expectedAuthorizationServer) + if let expectedSubjectDID, response.subject != expectedSubjectDID { + throw ATProtoOAuthError.subjectMismatch( + expected: expectedSubjectDID, + actual: response.subject + ) + } + } +} +``` + +Both providers call `validator.validate(response:actualIssuer:)`. Worth ~30 lines saved and the validator becomes directly unit-testable. + +Tests: add `TokenValidatorTests` covering the four failure modes (wrong token type, missing scope, issuer mismatch, sub mismatch) and the success path. + +### Step 5 — Make `IdentityResolver` a protocol + +Today `IdentityResolver` is a concrete struct. Tests have to hit live PDS endpoints (see `OAuthTests.swift` line 11-25 — calls `atproto.com`). That's fine for a smoke test, terrible for CI determinism. + +Introduce: + +```swift +public protocol ATProtoIdentityResolver: Sendable { + func resolve(identifier: String) async throws -> IdentityResolver.ResolvedIdentity + func isAuthorizationServer(_ authorizationServer: String, validFor pdsEndpoint: String) async throws -> Bool +} + +extension IdentityResolver: ATProtoIdentityResolver {} +``` + +Add an injection point on `ATProtoOAuth.init`: + +```swift +public init( + config: ATProtoOAuthConfig, + storage: ATProtoAuthStorage, + identityResolver: ATProtoIdentityResolver = IdentityResolver() +) async { ... } +``` + +Don't add a "fallback resolver" yet — YAGNI until you actually need a Slingshot/community DoH backup. Just open the seam. + +Tests: replace the live-network identity tests in `OAuthTests.swift` with a fake `ATProtoIdentityResolver` that returns canned `ResolvedIdentity` values. Keep one live integration test, but mark it with `@Test(.disabled(if: ...))` or a tag so it's opt-in. + +### Step 6 — Optional: split `ATProtoOAuth.swift` along seams + +Only do this if Steps 1–5 still leave the file feeling unwieldy. The seams are clear: + +- `ATProtoOAuth.swift` (~400 lines) — `ATProtoOAuth` class, public config, public errors. +- `OAuth/TokenHandling+ATProto.swift` (~250 lines) — `buildTokenHandling`, `authorizationURLProvider`, `loginProvider`, `refreshProvider` extracted as private extensions on `ATProtoOAuth`. +- `OAuth/TokenModels.swift` (~150 lines) — `OAuthTokenRequest`, `OAuthRefreshTokenRequest`, `OAuthTokenResponse`. + +Don't change behavior in this step — pure file move + access-control tightening. + +Once the split lands, drop the deprecated `ATProtoSession.dpopPrivateKey` / `dpopKeys` / `dpopNonceStore` accessors (Step 2 deprecated them). Remove `DPoPNonceStore.swift`. Bump CoreATProtocol's tag — this is a SemVer-major change because the deprecated symbols are public. + +### Step 7 — Update auto-memory + +After all of this lands, update `~/.claude/projects/-Users-rademaker-Developer-SparrowTek-AtProto/memory/MEMORY.md`: +- Note that DPoP signing is consolidated in `OAuth/DPoPSigner.swift`. +- Note the per-origin nonce cache (so future-Claude doesn't try to re-introduce a single-slot store). +- Note that Atprosphere uses `clientAuthMethod: .privateKeyJWT`, effem uses `.none`, and the auth proxy path is exercised in production by both. +- Drop the stale Plume entries — that directory no longer exists in this checkout. + +## What we're explicitly NOT doing + +- **Not switching to AtprotoOAuth.** Their README says it's not ready, they don't support `private_key_jwt`, and adopting them means adopting AtprotoTypes/AtprotoClient too. +- **Not removing `clientAuthMethod` or `AuthProxy.swift`.** Atprosphere's production OAuth depends on the confidential-client + auth-proxy path. +- **Not changing the public API surface in Atprosphere/effem.** Steps 1–5 are additive or internal. Only Step 6's deprecation removal is breaking, and that's gated behind a SemVer bump. +- **Not introducing new dependencies.** `swift-crypto` is already pulled in transitively via `jwt-kit`; everything else is Foundation. + +## Risk + rollback + +| Step | Risk | Rollback | +| --- | --- | --- | +| 1 (add DPoPSigner) | Low — new file, not wired in. | Delete the file. | +| 2 (wire in DPoPSigner) | Medium — touches every authenticated request. | Revert; deprecated accessors still work. | +| 3 (URL canonicalization) | Low — pure refactor. | Revert. | +| 4 (extract validator) | Low — pure refactor. | Revert. | +| 5 (resolver protocol) | Low — additive. | Revert. | +| 6 (file split + deprecation removal) | Medium — public API change. | SemVer-major bump means consumers opt in. | + +## Order of work, in PR-size chunks + +1. **PR 1**: Step 1 — `DPoPSigner` + tests. Standalone, no consumer changes. **DONE**, bundled with PR 2. +2. **PR 2**: Step 2 — wire `DPoPSigner` into `Networking.swift` + `ATProtoOAuth.swift`. Largest diff. Verify against Atprosphere + effem before merge. **DONE**. +3. **PR 3**: Steps 3 + 4 — URL canonicalization + token validator. Small refactor PR. **NEXT**. +4. **PR 4**: Step 5 — resolver protocol + offline tests. +5. **PR 5** (later, behind a SemVer bump): Step 6 — file split and deprecation removal. + +Steps 1–5 are non-breaking. Step 6 is breaking and can wait until you have another reason to bump the major version. + +## Notes from the Steps 1+2 implementation + +- **Renamed the new actor to `DPoPProofSigner`.** OAuthenticator already exports `public final class DPoPSigner` (its `JWTGenerator` typealias is the entry point we hand to `TokenHandling`), so the plan's name would have collided. The new file is `Sources/CoreATProtocol/OAuth/DPoPProofSigner.swift`; everywhere the plan says `DPoPSigner` for our new actor, the code says `DPoPProofSigner`. OAuthenticator's `DPoPSigner` keeps its name and role (per-flow nonce holder for `Authenticator`). +- **Added an `explicitNonce` parameter to `ProofParameters`.** The auth-server flow runs through `OAuthenticator.DPoPSigner`, which already tracks the auth-server nonce for the exchange and passes it via `JWTParameters.nonce`. We forward that as `explicitNonce` so the call doesn't consult the per-origin cache (which is the XRPC layer's). The XRPC layer in `Networking.swift` calls `sign(_:)` without an `explicitNonce` and the cache is consulted normally. +- **Did not deprecate `dpopPrivateKey` / `dpopKeys` / `dpopNonceStore` yet.** The plan calls for `@available(*, deprecated, ...)` on those public properties, but applying it now would require `@available`-aware suppression at the write sites in `setDPoPPrivateKey(pem:)`. Cleaner to defer until Step 6, which removes them outright. The new `dpopProofSigner` accessor is the production read path; the legacy fields are dual-written in `setDPoPPrivateKey(pem:)` purely for source compatibility with external readers. +- **Dropped the integration test from Step 2.** The plan suggested an end-to-end test that drives `APRouterDelegate.didReceiveErrorResponse` then `intercept` and verifies the cached nonce flows through. Implementation revealed that any test touching `ATProtoSession.shared` races with other suites that call `await ATProtoSession.shared.reset()` (`NonceDetectionTests`, `RefreshLoginTests`, `DPoPTests`). Swift Testing's `.serialized` trait only orders within a suite, not across suites. Two paths are open here: (1) globally serialize all session-touching suites, or (2) make the session instance-based so tests can spin up isolated sessions. (2) is the long-term fix and is closer to what's contemplated in `APEnvironment.swift`'s "future major release will make it instance-based" comment. Until then, the per-origin caching is fully covered by the unit tests in `DPoPProofSignerTests`, and the wiring through `Networking.swift` is straightforward delegation (the kind of code production traffic exercises immediately). +- **Verified consumers.** bskyKit and EffemKit were rebuilt against the local CoreATProtocol checkout via a temporary `.package(path:)` swap — both succeeded. Atprosphere and the effem iOS app are `.xcodeproj` consumers; their call sites were inspected and only touch preserved public APIs (`setDPoPPrivateKey(pem:)`, `ATProtoOAuth(config:storage:)`, `ATProtoOAuthConfig`, `ATProtoOAuthError`, `ATProtoSession.shared.host`, `ATProtoSession.shared.routerDelegate`). +- **Updated test:** `nonceCacheBounded` was rewritten — the original draft asserted "≥ 1 of the 5 oldest origins was evicted," which was probabilistic since Swift dictionaries don't guarantee key ordering. The new assertion is the deterministic invariant: after 30 insertions into a 25-slot cache, exactly 25 entries survive. -- knotmirror 0.0.1