Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Sync proxy #10

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/Controller/Kobo/KoboAuthDeviceController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace App\Controller\Kobo;

use App\Kobo\Proxy\KoboProxyConfiguration;
use App\Kobo\Proxy\KoboStoreProxy;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/kobo/{accessKey}', name: 'kobo')]
class KoboAuthDeviceController extends AbstractController
{
public function __construct(
protected KoboProxyConfiguration $koboProxyConfiguration,
protected KoboStoreProxy $koboStoreProxy,
protected LoggerInterface $logger)
{
}

/**
* @throws GuzzleException
*/
#[Route('/v1/auth/device', methods: ['GET', 'POST'])]
#[Route('/v1/auth/refresh', methods: ['GET', 'POST'])]
public function authDevice(Request $request): Response
{
if ($this->koboProxyConfiguration->useProxy()) {
return $this->koboStoreProxy->proxy(
$request, ['stream' => true]
);
}

$response = new Response();
$response->headers->set('Content-Type', 'application/json');

return $response;
}
}
3 changes: 0 additions & 3 deletions src/Controller/Kobo/KoboController.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ public function index(): Response
#[Route('/v1/products/{uuid}/prices', requirements: ['uuid' => '^[a-zA-Z0-9\-]+$'], methods: ['GET', 'POST'])]
#[Route('/v1/products/{uuid}/recommendations', requirements: ['uuid' => '^[a-zA-Z0-9\-]+$'], methods: ['GET', 'POST'])]
#[Route('/v1/products/{uuid}/reviews', requirements: ['uuid' => '^[a-zA-Z0-9\-]+$'], methods: ['GET', 'POST'])]
#[Route('/v1/user/profile')]
#[Route('/v1/configuration')]
#[Route('/v1/auth/device')]
#[Route('/v1/auth/refresh')]
#[Route('/v1/library/borrow')]
#[Route('/v1/auth/exchange')]
#[Route('/v1/library/{uuid}', methods: ['DELETE'])]
Expand Down
4 changes: 4 additions & 0 deletions src/Controller/Kobo/KoboSyncController.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ public function __construct(
#[Route('/v1/library/sync', name: 'api_endpoint_v1_library_sync')]
public function apiEndpoint(KoboDevice $kobo, SyncToken $syncToken, Request $request): Response
{
// if (true) {
// return $this->koboStoreProxy->proxy($request);
// }

$forced = $kobo->isForceSync() || $request->query->has('force');
$count = $this->koboSyncedBookRepository->countByKoboDevice($kobo);
if ($forced || $count === 0) {
Expand Down
47 changes: 47 additions & 0 deletions src/Controller/Kobo/KoboUserProfileController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace App\Controller\Kobo;

use App\Kobo\Proxy\KoboProxyConfiguration;
use App\Kobo\Proxy\KoboStoreProxy;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/kobo/{accessKey}', name: 'kobo')]
class KoboUserProfileController extends AbstractController
{
public function __construct(
protected KoboProxyConfiguration $koboProxyConfiguration,
protected KoboStoreProxy $koboStoreProxy,
) {
}

#[Route('/v1/user/profile')]
public function userProfile(Request $request): Response
{
if ($this->koboProxyConfiguration->useProxy()) {
return $this->koboStoreProxy->proxy($request);
}

$tokenParts = [];
$tokenParts[] = base64_encode((string) json_encode([
'typ' => 1,
'ver' => 'v1',
'ptyp' => 'ApiUserToken',
]));
$tokenParts[] = base64_encode((string) json_encode([
'LoyaltyMembershipVersion' => 2147483647,
'LastModifiedTime' => -62135596800,
'BuildVersion' => '1.0.0',
'LifetimeTagsHash' => -790277027,
]));

$response = new Response();
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('X-Kobo-Apitoken', base64_encode((string) json_encode(['x-kobo-profile-token' => implode('.', $tokenParts)])));

return $response;
}
}
4 changes: 4 additions & 0 deletions src/Kobo/Proxy/KoboProxyLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,14 @@ protected function onFailure(RequestInterface $request): \Closure

private function log(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): void
{
$body = $response?->getBody()->__toString();
$response?->getBody()->rewind();

$this->logger->info(sprintf('Proxied: %s', (string) $request->getUri()), [
'method' => $request->getMethod(),
'status' => $response?->getStatusCode(),
'token_hash' => md5($this->accessToken),
'body' => $body,
]);

if ($error instanceof \Throwable) {
Expand Down
56 changes: 50 additions & 6 deletions src/Kobo/Proxy/KoboStoreProxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Security\KoboTokenExtractor;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Nyholm\Psr7\Factory\Psr17Factory;
Expand Down Expand Up @@ -90,9 +91,14 @@ private function _proxy(Request $request, string $hostname, array $config = []):
$psrRequest = $this->convertRequest($request, $hostname);

$accessToken = $this->tokenExtractor->extractAccessToken($request) ?? 'unknown';
$jar = new CookieJar();
if ($psrRequest instanceof ServerRequestInterface) {
$jar = CookieJar::fromArray($psrRequest->getCookieParams(), $psrRequest->getUri()->getHost());
}

$client = new Client();
$psrResponse = $client->send($psrRequest, [
'cookies' => $jar,
'base_uri' => $hostname,
'handler' => $this->koboProxyLoggerFactory->createStack($accessToken),
'http_errors' => false,
Expand All @@ -108,25 +114,59 @@ protected function getTransformedUrl(Request $request): UriInterface
$psrRequest = $this->toPsrRequest($request);
$hostname = $this->configuration->isImageHostUrl($psrRequest) ? $this->configuration->getImageApiUrl() : $this->configuration->getStoreApiUrl();

return $this->transformUrl($psrRequest, $hostname);
return $this->transformUrl($psrRequest, $hostname, $request->getScheme());
}

private function transformUrl(ServerRequestInterface $psrRequest, string $hostname): UriInterface
private function transformUrl(ServerRequestInterface $psrRequest, string $hostname, string $scheme): UriInterface
{
$host = parse_url($hostname, PHP_URL_HOST);
$host = $host === false ? $hostname : $host;
$host = $host ?? $hostname;
$path = $this->tokenExtractor->getOriginalPath($psrRequest, $psrRequest->getUri()->getPath());

return $psrRequest->getUri()->withHost($host)->withPath($path);
return $psrRequest->getUri()
->withHost($host)
->withPath($path)
->withScheme($scheme)
;
}

private function toPsrRequest(Request $request): ServerRequestInterface
{
$psr17Factory = new Psr17Factory();
$psrHttpFactory = new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);

return $psrHttpFactory->createRequest($request);
$request = clone $request;

// Remove server attributes
foreach ($request->server->all() as $key => $value) {
if ($key !== 'HTTPS' && $key !== 'X-Forwarded-Proto') {
$request->server->remove($key);
}
}

// Remove route attributes
foreach ($request->attributes->all() as $key => $value) {
$request->attributes->remove($key);
}

// Remove cookies
foreach ($request->cookies->all() as $key => $value) {
if (in_array($key, ['PHPSESSID', 'XDEBUG_SESSION'], true)) {
$request->cookies->remove($key);
}
}

// Remove headers
foreach ($request->headers->all() as $key => $value) {
if (str_starts_with($key, 'x-forwarded-') || $key === 'x-real-ip' || $key === 'cookie') {
$request->headers->remove($key);
}
}

return $psrHttpFactory->createRequest($request)
->withCookieParams($request->cookies->all())
;
}

public function proxyAsync(Request $request, bool $streamAllowed): PromiseInterface
Expand All @@ -137,8 +177,13 @@ public function proxyAsync(Request $request, bool $streamAllowed): PromiseInterf
$accessToken = $this->tokenExtractor->extractAccessToken($request) ?? 'unknown';

$client = new Client();
$jar = new CookieJar();
if ($psrRequest instanceof ServerRequestInterface) {
$jar = CookieJar::fromArray($psrRequest->getCookieParams(), $psrRequest->getUri()->getHost());
}

return $client->sendAsync($psrRequest, [
'cookies' => $jar,
'base_uri' => $hostname,
'handler' => $this->koboProxyLoggerFactory->createStack($accessToken),
'http_errors' => false,
Expand All @@ -154,11 +199,10 @@ private function convertRequest(Request $request, string $hostname): RequestInte
$host = parse_url($hostname, PHP_URL_HOST);
$host = $host === false ? $hostname : $host;
$request->headers->set('Host', $host);
$request->server->set('HTTPS', 'on'); // Force HTTPS (for cli)
$psrRequest = $this->toPsrRequest($request);
$psrRequest = $this->cleanup($psrRequest);

$url = $this->transformUrl($psrRequest, $hostname);
$url = $this->transformUrl($psrRequest, $hostname, $request->getScheme());

return $psrRequest->withUri($url);
}
Expand Down
Loading