import CoreATProtocol import Foundation import Hummingbird import HummingbirdAuth import HummingbirdWebSocket import NIOCore /// Codable configuration shared by every context: responses are written in /// snake_case, which is what EffemKit decodes, and request bodies are read /// the same way. enum WireCoding { static let encoder: JSONEncoder = { let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToSnakeCase encoder.outputFormatting = [.withoutEscapingSlashes] return encoder }() /// For AT Protocol records, whose canonical keys are camelCase. static let canonicalEncoder: JSONEncoder = { let encoder = JSONEncoder() encoder.outputFormatting = [.withoutEscapingSlashes] return encoder }() static let decoder: JSONDecoder = { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase return decoder }() } /// The context every request starts with: the socket peer, the client /// address once the proxy chain has been unwound, and the principal once the /// token has been checked. struct AppRequestContext: AuthRequestContext, RequestContext { typealias Identity = Principal var coreContext: CoreRequestContextStorage var identity: Principal? let peerAddress: IPAddress? var clientAddress: IPAddress? init(source: ApplicationRequestContextSource) { self.coreContext = .init(source: source) self.identity = nil self.peerAddress = source.channel.remoteAddress?.ipAddress.flatMap(IPAddress.init) self.clientAddress = nil } var requestDecoder: JSONDecoder { WireCoding.decoder } var responseEncoder: JSONEncoder { WireCoding.encoder } } /// The context under `/xrpc`: a principal is guaranteed to exist, so handlers /// never check for one. struct AuthenticatedRequestContext: ChildRequestContext { typealias ParentContext = AppRequestContext var coreContext: CoreRequestContextStorage let principal: Principal let clientAddress: IPAddress? init(context: AppRequestContext) throws { guard let principal = context.identity else { throw AppError.authRequired("missing bearer token or x-api-key") } guard principal.hasScope(.read) else { throw AppError.forbidden() } self.coreContext = context.coreContext self.principal = principal self.clientAddress = context.clientAddress } /// Every body the app sends is a small JSON object. var maxUploadSize: Int { 64 * 1024 } var requestDecoder: JSONDecoder { WireCoding.decoder } var responseEncoder: JSONEncoder { WireCoding.encoder } /// The DID the caller acts as, or nil for service tokens. var callerDID: String? { principal.did } /// Who is looking, for the parts of a read that depend on the reader. /// See ``Viewer``. func viewerDID(in request: Request) -> String? { Viewer.did(of: principal, in: request) } /// The key the Podcast Index budget charges a cache miss to. var budgetKey: String? { clientAddress?.description ?? (principal.isService ? nil : principal.subject) } } /// Who is looking, for the parts of a read that depend on the reader: which /// comments they liked and whose content they blocked. /// /// A user token is its own viewer, and nothing in the request can change /// that. The app's shared token has no user behind it, so the app names the /// viewer in the `viewer` parameter. Like every DID that token passes, it is /// taken as given until the service can authenticate individual users. What /// it unlocks is public already: likes and blocks are public records. /// /// The read routes and the comment stream both ask here, so a comment the /// list leaves out for a viewer cannot reach the same viewer live. enum Viewer { static func did(of principal: Principal?, in request: Request) -> String? { if let own = principal?.did { return own } guard let claimed = QueryValues.trimmed(request.uri.queryParameters["viewer"].map(String.init)), DID.isValid(claimed) else { return nil } return claimed } } /// The context under `/xrpc/xyz.effem.admin.*`: admin scope is required and /// request bodies are capped at 64 KB. struct AdminRequestContext: ChildRequestContext { typealias ParentContext = AuthenticatedRequestContext var coreContext: CoreRequestContextStorage let principal: Principal init(context: AuthenticatedRequestContext) throws { guard context.principal.isAdmin else { throw AppError.forbidden() } self.coreContext = context.coreContext self.principal = context.principal } var maxUploadSize: Int { 64 * 1024 } var requestDecoder: JSONDecoder { WireCoding.decoder } var responseEncoder: JSONEncoder { WireCoding.encoder } } /// The context for the WebSocket router, which runs the same token /// authenticator before upgrading. struct WebSocketAppRequestContext: WebSocketRequestContext, AuthRequestContext, RequestContext { typealias Identity = Principal var coreContext: CoreRequestContextStorage let webSocket: WebSocketHandlerReference var identity: Principal? init(source: ApplicationRequestContextSource) { self.coreContext = .init(source: source) self.webSocket = .init() self.identity = nil } }