redirectUris, TRUE)) { throw new \InvalidArgumentException('OAuth redirect URI is not declared in client metadata.'); } $resolved = $this->resolveIdentifier($identifier); $metadata = $this->discoverAuthorizationServer($resolved['pdsUrl'], $resolved['authorizationServer']); $stateValue = $this->randomToken(); $codeVerifier = $this->randomToken(64); $dpopKey = DpopPrivateKey::generate('ES256'); $state = new AuthorizationState( state: $stateValue, codeVerifier: $codeVerifier, redirectUri: $redirectUri, authorizationServer: $metadata->issuer, clientId: $config->clientId, scopes: $config->scopes, did: $resolved['did'], handle: $resolved['handle'], pdsUrl: $resolved['pdsUrl'], dpopPrivateJwk: $dpopKey->privateJwk(), dpopAlgorithm: $dpopKey->algorithm, createdAt: \time(), ); $par = $this->sendPushedAuthorizationRequest($metadata, $config, $state, $dpopKey, $resolved['loginHint']); $state = $state->withAuthorizationServerNonce($par['nonce']); $authorizationUrl = $this->appendQuery($metadata->authorizationEndpoint, [ 'client_id' => $config->clientId, 'request_uri' => $par['data']['request_uri'], ]); return new OAuthAuthorizationRequest($authorizationUrl, $state); } /** * Exchanges the authorization code. */ public function exchangeAuthorizationCode( AuthorizationState $state, #[\SensitiveParameter] string $code, string $issuer, ): OAuthSession { if ($issuer !== $state->authorizationServer) { throw new \InvalidArgumentException('OAuth callback issuer does not match the authorization request.'); } if ($state->dpopPrivateJwk === NULL) { throw new \InvalidArgumentException('OAuth authorization state is missing DPoP key material.'); } $metadata = $this->fetchAuthorizationServerMetadata($state->authorizationServer); $dpopKey = DpopPrivateKey::fromJwk($state->dpopPrivateJwk, $state->dpopAlgorithm); $response = $this->sendTokenRequest( $metadata, [ 'grant_type' => 'authorization_code', 'client_id' => $state->clientId, 'redirect_uri' => $state->redirectUri, 'code' => $code, 'code_verifier' => $state->codeVerifier, ], $dpopKey, $state->authorizationServerNonce, ); $did = $this->validatedSubjectDid($response['data'], $state); $document = $this->resolveAndVerifySubjectDocument($did, $state, $metadata); $pdsUrl = $document->getPdsEndpoint() ?? $state->pdsUrl; $handle = $state->handle; if ($handle !== NULL && !$document->hasAlsoKnownAsHandle($handle)) { $handle = NULL; } return new OAuthSession( did: $did, handle: $handle, pdsUrl: $pdsUrl, authorizationServer: $metadata->issuer, tokens: TokenSet::fromResponse($response['data']), dpopPrivateJwk: $dpopKey->privateJwk(), dpopAlgorithm: $dpopKey->algorithm, authorizationServerNonce: $response['nonce'] ?? $state->authorizationServerNonce, ); } /** * Refreshes an OAuth session and returns its rotated credentials. */ public function refreshSession(OAuthConfig $config, OAuthSession $session): OAuthSession { if ($session->tokens->refreshToken === NULL || $session->tokens->refreshToken === '') { throw new \InvalidArgumentException('OAuth session has no refresh token.'); } if ($session->dpopPrivateJwk === NULL) { throw new \InvalidArgumentException('OAuth session is missing DPoP key material.'); } $metadata = $this->fetchAuthorizationServerMetadata($session->authorizationServer); $dpopKey = DpopPrivateKey::fromJwk($session->dpopPrivateJwk, $session->dpopAlgorithm); $response = $this->sendTokenRequest( $metadata, [ 'grant_type' => 'refresh_token', 'client_id' => $config->clientId, 'refresh_token' => $session->tokens->refreshToken, ], $dpopKey, $session->authorizationServerNonce, ); $data = $response['data']; $did = \is_string($data['sub'] ?? NULL) && $data['sub'] !== '' ? $data['sub'] : $session->did; if ($did !== $session->did) { throw new OAuthException('OAuth refresh returned a different subject DID.'); } if (!\array_key_exists('refresh_token', $data)) { $data['refresh_token'] = $session->tokens->refreshToken; } return new OAuthSession( did: $session->did, handle: $session->handle, pdsUrl: $session->pdsUrl, authorizationServer: $metadata->issuer, tokens: TokenSet::fromResponse($data), dpopPrivateJwk: $dpopKey->privateJwk(), dpopAlgorithm: $dpopKey->algorithm, authorizationServerNonce: $response['nonce'] ?? $session->authorizationServerNonce, resourceServerNonce: $session->resourceServerNonce, ); } /** * @return array{did: ?string, handle: ?string, pdsUrl: ?string, authorizationServer: ?string, loginHint: ?string} */ private function resolveIdentifier(?string $identifier): array { $identifier = \trim((string) $identifier); if ($identifier === '') { return ['did' => NULL, 'handle' => NULL, 'pdsUrl' => NULL, 'authorizationServer' => NULL, 'loginHint' => NULL]; } if (\str_starts_with($identifier, 'did:')) { $document = $this->didResolver->resolveDocumentOrFail($identifier); return [ 'did' => $document->id, 'handle' => NULL, 'pdsUrl' => $document->getPdsEndpoint(), 'authorizationServer' => NULL, 'loginHint' => $identifier, ]; } if (\str_starts_with($identifier, 'http://') || \str_starts_with($identifier, 'https://')) { return [ 'did' => NULL, 'handle' => NULL, 'pdsUrl' => \rtrim($identifier, '/'), 'authorizationServer' => NULL, 'loginHint' => NULL, ]; } $identifier = \ltrim($identifier, '@'); if (\str_contains($identifier, '.') && !\str_contains($identifier, '/')) { $did = $this->handleResolver->resolveDidOrFail($identifier); $document = $this->didResolver->resolveDocumentOrFail($did); if (!$document->hasAlsoKnownAsHandle($identifier)) { throw new OAuthException('Resolved DID document does not verify the requested handle.'); } return [ 'did' => $document->id, 'handle' => $identifier, 'pdsUrl' => $document->getPdsEndpoint(), 'authorizationServer' => NULL, 'loginHint' => $identifier, ]; } return [ 'did' => NULL, 'handle' => NULL, 'pdsUrl' => 'https://' . $identifier, 'authorizationServer' => NULL, 'loginHint' => NULL, ]; } private function discoverAuthorizationServer( ?string $pdsUrl, ?string $authorizationServer, ): AuthorizationServerMetadata { if ($authorizationServer !== NULL) { return $this->fetchAuthorizationServerMetadata($authorizationServer); } if ($pdsUrl === NULL || $pdsUrl === '') { throw new \InvalidArgumentException('An ATProto account identifier or server URL is required.'); } $this->assertHttpsOrigin($pdsUrl, 'ATProto resource server'); $resourceMetadata = $this->fetchOptionalJson($pdsUrl . '/.well-known/oauth-protected-resource'); if ($resourceMetadata === NULL) { return $this->fetchAuthorizationServerMetadata($pdsUrl); } if (($resourceMetadata['resource'] ?? NULL) !== $pdsUrl) { throw new OAuthException('OAuth resource metadata does not match the resource server origin.'); } $servers = $resourceMetadata['authorization_servers'] ?? NULL; if (!\is_array($servers) || \count($servers) !== 1 || !\is_string($servers[0]) || $servers[0] === '') { throw new OAuthException('OAuth resource metadata must declare exactly one authorization server.'); } $this->assertHttpsOrigin($servers[0], 'OAuth authorization server'); $metadata = $this->fetchAuthorizationServerMetadata($servers[0]); $protectedResources = $metadata->raw['protected_resources'] ?? NULL; if ( $protectedResources !== NULL && (!\is_array($protectedResources) || !\in_array($pdsUrl, $protectedResources, TRUE)) ) { throw new OAuthException(\sprintf( 'PDS "%s" is not protected by issuer "%s".', $pdsUrl, $metadata->issuer, )); } return $metadata; } private function fetchAuthorizationServerMetadata(string $authorizationServer): AuthorizationServerMetadata { $this->assertHttpsOrigin($authorizationServer, 'OAuth authorization server'); $metadata = $this->fetchJson($authorizationServer . '/.well-known/oauth-authorization-server'); return AuthorizationServerMetadata::fromArray( $metadata, $authorizationServer, $this->urlPolicy, ); } /** * @return array */ private function fetchJson(string $url): array { $this->urlPolicy->assertAllowedHttpsUrl($url); $request = $this->requestFactory->createRequest('GET', $url)->withHeader('Accept', 'application/json'); try { $response = $this->httpClient->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new OAuthException(\sprintf('OAuth metadata request failed: %s', $e->getMessage()), previous: $e); } if ($response->getStatusCode() !== 200) { throw new OAuthException(\sprintf('OAuth metadata request failed with HTTP %d.', $response->getStatusCode())); } return $this->decodeMetadataResponse($response); } /** * @return array|null */ private function fetchOptionalJson(string $url): ?array { $this->urlPolicy->assertAllowedHttpsUrl($url); $request = $this->requestFactory->createRequest('GET', $url)->withHeader('Accept', 'application/json'); try { $response = $this->httpClient->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new OAuthException(\sprintf('OAuth metadata request failed: %s', $e->getMessage()), previous: $e); } if ($response->getStatusCode() === 404) { return NULL; } if ($response->getStatusCode() !== 200) { throw new OAuthException(\sprintf('OAuth metadata request failed with HTTP %d.', $response->getStatusCode())); } return $this->decodeMetadataResponse($response); } /** * @return array */ private function decodeMetadataResponse(ResponseInterface $response): array { $this->assertJsonContentType($response, 'OAuth metadata'); try { $data = \json_decode( BoundedResponseBody::read($response, self::MAX_RESPONSE_BYTES), TRUE, self::MAX_JSON_DEPTH, JSON_THROW_ON_ERROR, ); } catch (\JsonException|\LengthException $exception) { throw new OAuthException('OAuth metadata response could not be decoded.', previous: $exception); } if (!\is_array($data) || \array_is_list($data) && $data !== []) { throw new OAuthException('OAuth metadata response is not a JSON object.'); } /** @var array $data */ return $data; } /** * @return array{data: array, nonce: ?string, status: int} */ private function sendPushedAuthorizationRequest( AuthorizationServerMetadata $metadata, OAuthConfig $config, AuthorizationState $state, DpopPrivateKey $dpopKey, ?string $loginHint, ): array { $params = [ 'response_type' => 'code', 'client_id' => $config->clientId, 'redirect_uri' => $state->redirectUri, 'scope' => \implode(' ', $state->scopes), 'state' => $state->state, 'code_challenge' => Base64Url::encode(\hash('sha256', $state->codeVerifier, TRUE)), 'code_challenge_method' => 'S256', ]; if ($loginHint !== NULL && \trim($loginHint) !== '') { $params['login_hint'] = \trim($loginHint); } $response = $this->sendFormRequest($metadata->pushedAuthorizationRequestEndpoint, $params, $dpopKey, NULL, NULL); if (($response['data']['error'] ?? NULL) === 'use_dpop_nonce' && \is_string($response['nonce'])) { $challengeNonce = $response['nonce']; $response = $this->sendFormRequest( $metadata->pushedAuthorizationRequestEndpoint, $params, $dpopKey, NULL, $challengeNonce, ); $response['nonce'] ??= $challengeNonce; } if ($response['status'] < 200 || $response['status'] >= 300) { throw self::httpException('PAR', $response); } if (!\is_string($response['data']['request_uri'] ?? NULL) || $response['data']['request_uri'] === '') { throw new OAuthException('OAuth PAR response is missing request_uri.'); } return $response; } /** * @param array $params * @return array{data: array, nonce: ?string, status: int} */ private function sendTokenRequest( AuthorizationServerMetadata $metadata, #[\SensitiveParameter] array $params, DpopPrivateKey $dpopKey, ?string $nonce, ): array { $response = $this->sendFormRequest($metadata->tokenEndpoint, $params, $dpopKey, NULL, $nonce); if (($response['data']['error'] ?? NULL) === 'use_dpop_nonce' && \is_string($response['nonce'])) { $challengeNonce = $response['nonce']; $response = $this->sendFormRequest($metadata->tokenEndpoint, $params, $dpopKey, NULL, $challengeNonce); $response['nonce'] ??= $challengeNonce; } if ($response['status'] < 200 || $response['status'] >= 300) { throw self::httpException('token', $response, $params['grant_type'] ?? NULL); } return $response; } /** * @param array $params * @return array{data: array, nonce: ?string, status: int} */ private function sendFormRequest( string $url, #[\SensitiveParameter] array $params, DpopPrivateKey $dpopKey, #[\SensitiveParameter] ?string $accessToken, ?string $nonce, ): array { $this->urlPolicy->assertAllowedHttpsUrl($url); $body = \http_build_query($params, '', '&', PHP_QUERY_RFC3986); $request = $this->requestFactory ->createRequest('POST', $url) ->withHeader('Accept', 'application/json') ->withHeader('Content-Type', 'application/x-www-form-urlencoded') ->withBody($this->streamFactory->createStream($body)); $request = new DpopRequestSigner(new DpopProofFactory($dpopKey), NULL, $nonce)->sign($request); if ($accessToken !== NULL && $accessToken !== '') { $request = $request->withHeader('Authorization', 'DPoP ' . $accessToken); } try { $response = $this->httpClient->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new OAuthException(\sprintf('OAuth request failed: %s', $e->getMessage()), previous: $e); } return $this->decodeFormResponse($response); } /** * @return array{data: array, nonce: ?string, status: int} */ private function decodeFormResponse(ResponseInterface $response): array { $this->assertJsonContentType($response, 'OAuth'); try { $body = BoundedResponseBody::read($response, self::MAX_RESPONSE_BYTES); $data = $body !== '' ? \json_decode($body, TRUE, self::MAX_JSON_DEPTH, JSON_THROW_ON_ERROR) : []; } catch (\JsonException|\LengthException $exception) { throw new OAuthException('OAuth response could not be decoded.', previous: $exception); } if (!\is_array($data) || \array_is_list($data) && $data !== []) { throw new OAuthException('OAuth response is not a JSON object.'); } /** @var array $data */ $nonce = \trim($response->getHeaderLine('DPoP-Nonce')); return ['data' => $data, 'nonce' => $nonce !== '' ? $nonce : NULL, 'status' => $response->getStatusCode()]; } /** * @param array $tokenResponse */ private static function validatedSubjectDid(array $tokenResponse, AuthorizationState $state): string { if (!\is_string($tokenResponse['sub'] ?? NULL) || $tokenResponse['sub'] === '') { throw new OAuthException('OAuth token response is missing subject DID.'); } $did = $tokenResponse['sub']; if ($state->did !== NULL && $state->did !== $did) { throw new OAuthException('OAuth token subject does not match the requested account.'); } if ( !\is_string($tokenResponse['scope'] ?? NULL) || !\in_array('atproto', \explode(' ', $tokenResponse['scope']), TRUE) ) { throw new OAuthException('OAuth token response did not grant the required atproto scope.'); } return $did; } /** * @param array{data: array, nonce: ?string, status: int} $response */ private static function httpException( string $endpoint, array $response, ?string $grantType = NULL, ): OAuthHttpException { $error = $response['data']['error'] ?? NULL; $description = $response['data']['error_description'] ?? NULL; return new OAuthHttpException( $endpoint, $response['status'], \is_string($error) ? $error : NULL, \is_string($description) ? $description : NULL, $response['data'], $grantType, ); } private function resolveAndVerifySubjectDocument( string $did, AuthorizationState $state, AuthorizationServerMetadata $metadata, ): \Wotnak\Atproto\Identity\DidDocument { $document = $this->didResolver->resolveDocumentOrFail($did); $pdsUrl = $document->getPdsEndpoint(); if ($pdsUrl === NULL || $pdsUrl === '') { throw new OAuthException('OAuth subject DID document does not declare an ATProto PDS endpoint.'); } if ($state->did === NULL) { $subjectAuthorizationServer = $this->discoverAuthorizationServer($pdsUrl, NULL); if (\rtrim($subjectAuthorizationServer->issuer, '/') !== \rtrim($metadata->issuer, '/')) { throw new OAuthException('OAuth token subject is not authoritative for the callback issuer.'); } } return $document; } private static function randomToken(int $bytes = 32): string { if ($bytes < 1) { throw new \InvalidArgumentException('Token length must be at least one byte.'); } return Base64Url::encode(\random_bytes($bytes)); } /** * @param array $parameters */ private static function appendQuery(string $url, array $parameters): string { $query = \http_build_query($parameters, '', '&', PHP_QUERY_RFC3986); $separator = match (TRUE) { !\str_contains($url, '?') => '?', \str_ends_with($url, '?') || \str_ends_with($url, '&') => '', default => '&', }; return $url . $separator . $query; } private function assertHttpsOrigin(string $url, string $description): 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) || \strtolower($parts['scheme'] ?? '') !== 'https' || ($parts['host'] ?? '') === '' || ($parts['port'] ?? NULL) === 443 || isset($parts['user']) || isset($parts['pass']) || isset($parts['path']) || isset($parts['query']) || isset($parts['fragment']) ) { throw new \InvalidArgumentException(\sprintf('%s URL must be an HTTPS origin.', $description)); } $this->urlPolicy->assertAllowedHttpsUrl($url); } private static function assertJsonContentType(ResponseInterface $response, string $description): void { $contentType = \strtolower(\trim(\explode(';', $response->getHeaderLine('Content-Type'), 2)[0])); if ($contentType !== 'application/json') { throw new OAuthException(\sprintf('%s response must use the application/json content type.', $description)); } } }