Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Client;
use Psr\Http\Client\ClientExceptionInterface;use Psr\Http\Message\RequestFactoryInterface;use Psr\Http\Message\RequestInterface;use Psr\Http\Message\ResponseInterface;use Psr\Http\Message\StreamFactoryInterface;use Psr\Http\Message\StreamInterface;use Wotnak\Atproto\Exception\XrpcDecodeException;use Wotnak\Atproto\Exception\XrpcException;use Wotnak\Atproto\Exception\XrpcHttpException;use Wotnak\Atproto\Exception\XrpcProtocolException;use Wotnak\Atproto\Exception\XrpcResponseException;use Wotnak\Atproto\Http\BoundedResponseBody;use Wotnak\Atproto\Identifier\NsidParser;use Wotnak\Atproto\Security\OutboundUrlPolicy;use Wotnak\Atproto\Security\OutboundUrlPolicyInterface;
/** * Generic XRPC client for AT Protocol services. * * @api */final class XrpcClient {
public function __construct( private readonly XrpcRequestSenderInterface $requestSender, private readonly RequestFactoryInterface $requestFactory, private readonly StreamFactoryInterface $streamFactory, private readonly ?string $defaultServiceUrl = NULL, private readonly OutboundUrlPolicyInterface $urlPolicy = new OutboundUrlPolicy(), private readonly NsidParser $nsidParser = new NsidParser(), ) {}
/** * Sends a GET XRPC request and returns decoded data. * * @param array<string, mixed> $query * Query parameters. * * @return array<string, mixed> * The decoded XRPC response. */ public function get(string $method, array $query = [], ?XrpcOptions $options = NULL): array { return $this->request('GET', $method, $query, $options)->data; }
/** * Sends a POST XRPC request and returns decoded data. * * @param array<string, mixed> $payload * Request payload. * * @return array<string, mixed> * The decoded XRPC response. */ public function post(string $method, array $payload = [], ?XrpcOptions $options = NULL): array { return $this->request('POST', $method, $payload, $options)->data; }
/** * Sends a POST XRPC procedure that declares no input body. * * @return array<string, mixed> */ public function postWithoutBody(string $method, ?XrpcOptions $options = NULL): array { return $this->requestWithoutBody('POST', $method, [], $options)->data; }
/** * Executes the request without body operation. * * @param array<string, mixed> $query */ public function requestWithoutBody( string $httpMethod, string $method, array $query = [], ?XrpcOptions $options = NULL, ): XrpcResponse { [$serviceUrl, $response, $options] = $this->sendWithoutBody($httpMethod, $method, $query, $options); return $this->decodeResponse($method, $serviceUrl, $response, $options); }
/** * Executes the request raw without body operation. * * @param array<string, mixed> $query */ public function requestRawWithoutBody( string $httpMethod, string $method, array $query = [], ?XrpcOptions $options = NULL, ): RawXrpcResponse { [$serviceUrl, $response, $options] = $this->sendWithoutBody($httpMethod, $method, $query, $options); return $this->decodeRawResponse($method, $serviceUrl, $response, $options); }
/** * Sends a request whose Lexicon does not declare an output encoding. * * @param array<string, mixed> $query */ public function requestUnknownWithoutBody( string $httpMethod, string $method, array $query = [], ?XrpcOptions $options = NULL, ): XrpcResponse|RawXrpcResponse { [$serviceUrl, $response, $options] = $this->sendWithoutBody($httpMethod, $method, $query, $options); return $this->decodeUnknownResponse($method, $serviceUrl, $response, $options); }
/** * Sends a POST XRPC request with a caller-provided raw body. * * @return array<string, mixed> */ public function postRaw( string $method, string|StreamInterface $body, string $contentType = 'application/octet-stream', ?XrpcOptions $options = NULL, ): array { return $this->requestWithBody('POST', $method, $body, $contentType, [], $options)->data; }
/** * Sends an XRPC request and returns decoded data with response metadata. * * @param array<string, mixed> $data */ public function request( string $httpMethod, string $method, array $data = [], ?XrpcOptions $options = NULL, ): XrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createRequest($httpMethod, $method, $serviceUrl, $data, $options);
try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); }
return $this->decodeResponse($method, $serviceUrl, $response, $options); }
/** * Sends an XRPC request with a caller-provided raw body. * * @param array<string, mixed> $query * Query parameters. */ public function requestWithBody( string $httpMethod, string $method, string|StreamInterface $body, string $contentType = 'application/octet-stream', array $query = [], ?XrpcOptions $options = NULL, ): XrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createBodyRequest($httpMethod, $method, $serviceUrl, $query, $body, $contentType, $options);
try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); }
return $this->decodeResponse($method, $serviceUrl, $response, $options); }
/** * Sends an XRPC request and returns the raw response body. * * @param array<string, mixed> $data */ public function requestRaw( string $httpMethod, string $method, array $data = [], ?XrpcOptions $options = NULL, ): RawXrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createRequest($httpMethod, $method, $serviceUrl, $data, $options);
try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); }
$body = $this->readBoundedBody($method, $serviceUrl, $response, $options->maxResponseBytes); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw $this->httpException($method, $serviceUrl, $response, $body); }
return new RawXrpcResponse($body, $response->getStatusCode(), $this->responseHeaders($response)); }
/** * Sends an XRPC request with a raw body and returns the raw response body. * * @param array<string, mixed> $query * Query parameters. */ public function requestRawWithBody( string $httpMethod, string $method, string|StreamInterface $body, string $contentType = 'application/octet-stream', array $query = [], ?XrpcOptions $options = NULL, ): RawXrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createBodyRequest($httpMethod, $method, $serviceUrl, $query, $body, $contentType, $options);
try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); }
return $this->decodeRawResponse($method, $serviceUrl, $response, $options); }
/** * Sends a body for a method whose Lexicon does not declare output. * * @param array<string, mixed> $query */ public function requestUnknownWithBody( string $httpMethod, string $method, string|StreamInterface $body, string $contentType = 'application/octet-stream', array $query = [], ?XrpcOptions $options = NULL, ): XrpcResponse|RawXrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createBodyRequest($httpMethod, $method, $serviceUrl, $query, $body, $contentType, $options);
try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); }
return $this->decodeUnknownResponse($method, $serviceUrl, $response, $options); }
private function decodeUnknownResponse( string $method, string $serviceUrl, ResponseInterface $response, XrpcOptions $options, ): XrpcResponse|RawXrpcResponse { $body = $this->readBoundedBody($method, $serviceUrl, $response, $options->maxResponseBytes); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw $this->httpException($method, $serviceUrl, $response, $body); }
$headers = $this->responseHeaders($response); if ($body === '') { return new XrpcResponse([], $response->getStatusCode(), $headers, FALSE); } if (self::responseContentType($response) !== 'application/json') { return new RawXrpcResponse($body, $response->getStatusCode(), $headers); }
try { $decoded = \json_decode( $body, FALSE, \max(1, \min(512, $options->maxJsonDepth)), JSON_THROW_ON_ERROR, ); } catch (\JsonException $e) { throw new XrpcDecodeException($method, $serviceUrl, $response->getStatusCode(), $body, $e); } if (!$decoded instanceof \stdClass) { return new RawXrpcResponse($body, $response->getStatusCode(), $headers); } return new XrpcResponse(self::normalizeDecodedObject($decoded), $response->getStatusCode(), $headers); }
private function decodeRawResponse( string $method, string $serviceUrl, ResponseInterface $response, XrpcOptions $options, ): RawXrpcResponse { $body = $this->readBoundedBody($method, $serviceUrl, $response, $options->maxResponseBytes); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw $this->httpException($method, $serviceUrl, $response, $body); }
return new RawXrpcResponse($body, $response->getStatusCode(), $this->responseHeaders($response)); }
/** * @param array<string, mixed> $query * @return array{string, \Psr\Http\Message\ResponseInterface, \Wotnak\Atproto\Client\XrpcOptions} */ private function sendWithoutBody( string $httpMethod, string $method, array $query, ?XrpcOptions $options, ): array { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->requestFactory ->createRequest(\strtoupper($httpMethod), $this->buildUrl($method, $serviceUrl, $query)) ->withHeader('Accept', 'application/json'); foreach ($options->headers as $name => $value) { $request = $request->withHeader($name, $value); } try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); } return [$serviceUrl, $response, $options]; }
/** * Returns the default service url. */ public function getDefaultServiceUrl(): ?string { return $this->defaultServiceUrl !== NULL ? \rtrim($this->defaultServiceUrl, '/') : NULL; }
/** * @param array<string, mixed> $data */ private function createRequest( string $httpMethod, string $method, string $serviceUrl, array $data, XrpcOptions $options, ): RequestInterface { $httpMethod = \strtoupper($httpMethod); $request = $this->requestFactory ->createRequest($httpMethod, $this->buildUrl($method, $serviceUrl, $httpMethod === 'GET' ? $data : [])) ->withHeader('Accept', 'application/json');
foreach ($options->headers as $name => $value) { $request = $request->withHeader($name, $value); }
if ($httpMethod !== 'GET') { $request = $request ->withHeader('Content-Type', 'application/json') ->withBody($this->streamFactory->createStream(\json_encode((object) $data, JSON_THROW_ON_ERROR))); }
return $request; }
/** * @param array<string, mixed> $query * Query parameters. */ private function createBodyRequest( string $httpMethod, string $method, string $serviceUrl, array $query, string|StreamInterface $body, string $contentType, XrpcOptions $options, ): RequestInterface { $httpMethod = \strtoupper($httpMethod); if ($httpMethod === 'GET') { throw new \InvalidArgumentException('GET XRPC requests cannot include a raw body.'); }
$request = $this->requestFactory ->createRequest($httpMethod, $this->buildUrl($method, $serviceUrl, $query)) ->withHeader('Accept', 'application/json');
foreach ($options->headers as $name => $value) { $request = $request->withHeader($name, $value); }
return $request ->withHeader('Content-Type', $contentType) ->withBody(\is_string($body) ? $this->streamFactory->createStream($body) : $body); }
private function decodeResponse( string $method, string $serviceUrl, ResponseInterface $response, XrpcOptions $options, ): XrpcResponse { $body = $this->readBoundedBody($method, $serviceUrl, $response, $options->maxResponseBytes); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw $this->httpException($method, $serviceUrl, $response, $body); } if ($body === '') { return new XrpcResponse([], $response->getStatusCode(), $this->responseHeaders($response), FALSE); } $contentType = self::responseContentType($response); if ($contentType !== NULL && $contentType !== 'application/json') { throw new XrpcProtocolException( \sprintf('XRPC %s returned Content-Type "%s", expected "application/json".', $method, $contentType), $method, $serviceUrl, $response->getStatusCode(), $body, ); }
try { $decoded = \json_decode( $body, FALSE, \max(1, \min(512, $options->maxJsonDepth)), JSON_THROW_ON_ERROR, ); } catch (\JsonException $e) { throw new XrpcDecodeException($method, $serviceUrl, $response->getStatusCode(), $body, $e); }
if (!$decoded instanceof \stdClass) { throw new XrpcResponseException($method, $serviceUrl, $response->getStatusCode(), $decoded); } return new XrpcResponse( self::normalizeDecodedObject($decoded), $response->getStatusCode(), $this->responseHeaders($response), ); }
/** * Keeps JSON arrays and empty objects distinct while retaining associative * arrays for ordinary object-shaped response data. * * @return array<string, mixed> */ private static function normalizeDecodedObject(\stdClass $value): array { // JSON object member names are strings even though PHP exposes object vars // with the wider array-key type. // @mago-expect analysis:less-specific-return-statement return \array_map(self::normalizeDecodedValue(...), \get_object_vars($value)); }
private static function normalizeDecodedValue(mixed $value): mixed { if ($value instanceof \stdClass) { $properties = self::normalizeDecodedObject($value); return $properties === [] ? (object) $properties : $properties; } if (\is_array($value)) { return \array_map(self::normalizeDecodedValue(...), $value); } return $value; }
/** * Reads a response without allowing an unbounded body allocation. */ private static function readBoundedBody( string $method, string $serviceUrl, ResponseInterface $response, int $maxBytes, ): string { $maxBytes = \max(1, $maxBytes); try { return BoundedResponseBody::read($response, $maxBytes); } catch (\LengthException) { throw new XrpcException( \sprintf('XRPC response for %s exceeds the %d-byte limit.', $method, $maxBytes), $method, $serviceUrl, ); } }
private function httpException( string $method, string $serviceUrl, ResponseInterface $response, string $body, ): XrpcHttpException { $decoded = self::decodeErrorBody($body); return new XrpcHttpException( $method, $serviceUrl, $response->getStatusCode(), $body, $decoded, \is_string($decoded['error'] ?? NULL) ? $decoded['error'] : NULL, \is_string($decoded['message'] ?? NULL) ? $decoded['message'] : NULL, $this->responseHeaders($response), ); }
/** * @return array<string, mixed>|null */ private static function decodeErrorBody(string $body): ?array { if ($body === '') { return NULL; }
try { $decoded = \json_decode($body, TRUE, flags: JSON_THROW_ON_ERROR); } catch (\JsonException) { return NULL; } if (!\is_array($decoded)) { return NULL; } /** @var array<string, mixed> $decoded */ return $decoded; }
private static function responseContentType(ResponseInterface $response): ?string { $contentType = \trim($response->getHeaderLine('Content-Type')); return $contentType !== '' ? \strtolower(\trim(\explode(';', $contentType, 2)[0])) : NULL; }
/** * @return array<string, list<string>> */ private static function responseHeaders(ResponseInterface $response): array { // This assignment refines PSR-7's arrays to the lists guaranteed here. // @mago-expect lint:inline-variable-return /** @var array<string, list<string>> $headers */ $headers = $response->getHeaders(); return $headers; }
/** * @param array<string, mixed> $query * Query parameters. */ private function buildUrl(string $method, string $serviceUrl, array $query = []): string { $method = $this->nsidParser->normalize($method); $url = $serviceUrl . '/xrpc/' . $method; if ($query !== []) { $queryString = $this->buildQueryString($query); if ($queryString !== '') { $url .= '?' . $queryString; } } return $url; }
/** * @param array<string, mixed> $query * Query parameters. */ private function buildQueryString(array $query): string { $pairs = []; foreach ($query as $name => $value) { if ($value === NULL) { continue; } if (\is_array($value)) { foreach ($value as $item) { if ($item === NULL) { continue; }
$pairs[] = \rawurlencode($name) . '=' . \rawurlencode($this->encodeQueryValue($item)); } continue; } $pairs[] = \rawurlencode($name) . '=' . \rawurlencode($this->encodeQueryValue($value)); } return \implode('&', $pairs); }
private static function encodeQueryValue(mixed $value): string { if (\is_bool($value)) { return $value ? 'true' : 'false'; } if (\is_scalar($value) || $value instanceof \Stringable) { return (string) $value; } throw new \InvalidArgumentException('XRPC query parameters must be scalar values or scalar arrays.'); }
private function resolveServiceUrl(XrpcOptions $options): string { $serviceUrl = \rtrim((string) ($options->serviceUrl ?? $this->defaultServiceUrl), '/'); if ($serviceUrl === '') { throw new \InvalidArgumentException('An AT Protocol service URL is required.'); } $this->urlPolicy->assertAllowedServiceUrl($serviceUrl); $this->assertServiceOrigin($serviceUrl); return $serviceUrl; }
private static function assertServiceOrigin(string $url): void { try { $parts = \parse_url($url); } // ValueError is an expected invalid-input result at this API boundary. // @mago-expect analysis:avoid-catching-error catch (\ValueError) { $parts = FALSE; } if ( !\is_array($parts) || isset($parts['user']) || isset($parts['pass']) || isset($parts['path']) || isset($parts['query']) || isset($parts['fragment']) ) { throw new \InvalidArgumentException( 'An AT Protocol service URL must be an origin without a path, query, or fragment.', ); } }
private function sendRequest(RequestInterface $request): ResponseInterface { return $this->requestSender->send($request); }
}