From 085762ec174eae1c519ec14db632f5ba197ed3c7 Mon Sep 17 00:00:00 2001 From: winter Date: Tue, 17 Dec 2024 18:39:18 +0000 Subject: hopefully implement push! again i can't really test this yet because i don't have two https instances that can talk to each other. soon i will set that up and test all these recent commits --- Digitigrade/Job/ExpireInboundAuthToken.php | 2 +- Digitigrade/Job/RefreshOutboundAuthToken.php | 2 +- Digitigrade/Job/RequestOutboundAuthToken.php | 2 +- Digitigrade/Job/UpdateInstanceInfo.php | 2 +- Digitigrade/Model.php | 8 +++ Digitigrade/Model/Actor.php | 4 +- Digitigrade/Model/FetchableModel.php | 22 ++++---- Digitigrade/Model/Instance.php | 75 ++++++++++++++++++++++++++-- Digitigrade/Model/InstanceAuth.php | 2 + Digitigrade/Model/Note.php | 7 ++- Digitigrade/Model/PushableModel.php | 8 +++ 11 files changed, 113 insertions(+), 21 deletions(-) create mode 100644 Digitigrade/Model/PushableModel.php (limited to 'Digitigrade') diff --git a/Digitigrade/Job/ExpireInboundAuthToken.php b/Digitigrade/Job/ExpireInboundAuthToken.php index dfb5ae6..1ec3585 100644 --- a/Digitigrade/Job/ExpireInboundAuthToken.php +++ b/Digitigrade/Job/ExpireInboundAuthToken.php @@ -20,7 +20,7 @@ class ExpireInboundAuthToken extends Job { public function run() { Logger::getInstance()->info("expiring token for $this->domain"); - $instance = Instance::findByDomain($this->domain); + $instance = Instance::findByHostname($this->domain); if ($instance->auth->inboundToken != $this->token) { Logger::getInstance()->info("actually not expiring the token because it's been refreshed"); return; diff --git a/Digitigrade/Job/RefreshOutboundAuthToken.php b/Digitigrade/Job/RefreshOutboundAuthToken.php index 72dd466..6ba1f57 100644 --- a/Digitigrade/Job/RefreshOutboundAuthToken.php +++ b/Digitigrade/Job/RefreshOutboundAuthToken.php @@ -18,7 +18,7 @@ class RefreshOutboundAuthToken extends Job { public function run() { Logger::getInstance()->info("refreshing outbound token for $this->domain"); - $instance = Instance::findByDomain($this->domain); + $instance = Instance::findByHostname($this->domain); $instance->refreshOutboundAuthToken(); } diff --git a/Digitigrade/Job/RequestOutboundAuthToken.php b/Digitigrade/Job/RequestOutboundAuthToken.php index 1786e32..ef4de03 100644 --- a/Digitigrade/Job/RequestOutboundAuthToken.php +++ b/Digitigrade/Job/RequestOutboundAuthToken.php @@ -18,7 +18,7 @@ class RequestOutboundAuthToken extends Job { public function run() { Logger::getInstance()->info("requesting token from $this->domain in response to their dialback challenge"); - $instance = Instance::findByDomain($this->domain); + $instance = Instance::findByHostname($this->domain); $instance->requestOutboundAuthToken($this->secret); } diff --git a/Digitigrade/Job/UpdateInstanceInfo.php b/Digitigrade/Job/UpdateInstanceInfo.php index abcd182..4206aac 100644 --- a/Digitigrade/Job/UpdateInstanceInfo.php +++ b/Digitigrade/Job/UpdateInstanceInfo.php @@ -16,7 +16,7 @@ class UpdateInstanceInfo extends Job { public function run() { Logger::getInstance()->info("updating info for instance $this->domain"); - if (Instance::findByDomain($this->domain, forceRefetch: true) == null) { + if (Instance::findByHostname($this->domain, forceRefetch: true) == null) { throw new \RuntimeException("remote object doesn't seem to exist"); } } diff --git a/Digitigrade/Model.php b/Digitigrade/Model.php index a065154..40e85f4 100644 --- a/Digitigrade/Model.php +++ b/Digitigrade/Model.php @@ -128,6 +128,14 @@ abstract class Model { protected function hydrate() { } + /** + * Checks that all fields of the model are valid and allowed + * @return bool true if the model is valid, false otherwise + */ + protected function validate(): bool { + return true; + } + public static function findWhere(string $whereClause, array $parameters): ?static { $classNameParts = explode('\\', static::class); $className = $classNameParts[count($classNameParts) - 1]; diff --git a/Digitigrade/Model/Actor.php b/Digitigrade/Model/Actor.php index 3c416ee..8e8799d 100644 --- a/Digitigrade/Model/Actor.php +++ b/Digitigrade/Model/Actor.php @@ -1,9 +1,7 @@ bStrictObjectTypeChecking = false; } - protected static function fetchFromRemote(string $uri, bool $autoSave): ?static { - // fetch the object - // janky hack: if this is an Instance then avoid recursively fetching itself - $data = @get_remote_object_authenticated($uri, static::class == Instance::class); - if ($data === false) - return null; - $data = json_decode($data); - if ($data === null) - return null; + protected static function createFromJson(\stdClass $data, bool $autoSave): static { // default everything nullable to null $obj = new static(); $reflProps = (new \ReflectionClass(static::class))->getProperties(); @@ -67,6 +59,18 @@ abstract class FetchableModel extends Model implements RemoteFetchable { return $obj; } + protected static function fetchFromRemote(string $uri, bool $autoSave): ?static { + // fetch the object + // janky hack: if this is an Instance then avoid recursively fetching itself + $data = @get_remote_object_authenticated($uri, static::class == Instance::class); + if ($data === false) + return null; + $data = json_decode($data); + if ($data === null) + return null; + return static::createFromJson($data, $autoSave); + } + protected function finaliseAfterFetch(string $uri) { } diff --git a/Digitigrade/Model/Instance.php b/Digitigrade/Model/Instance.php index 7176fcd..9e54a5f 100644 --- a/Digitigrade/Model/Instance.php +++ b/Digitigrade/Model/Instance.php @@ -25,8 +25,8 @@ class Instance extends FetchableModel { return null; } - public static function findByDomain(string $domain, bool $autoSave = true, bool $forceRefetch = false): ?self { - return self::findByUri("https://$domain/.well-known/pawpub-instance", $autoSave, $forceRefetch); + public static function findByHostname(string $host, bool $autoSave = true, bool $forceRefetch = false): ?self { + return self::findByUri("https://$host/.well-known/pawpub-instance", $autoSave, $forceRefetch); } protected function hydrate() { @@ -40,7 +40,7 @@ class Instance extends FetchableModel { } protected function finaliseAfterFetch(string $uri) { - $this->domain = explode('/', $uri)[2]; + $this->domain = hostname_from_uri($uri); } protected function finaliseAfterSave() { @@ -50,7 +50,7 @@ class Instance extends FetchableModel { public static function findByUri(string $uri, bool $autoSave = true, bool $forceRefetch = false): ?static { if (!$forceRefetch) { - $domain = explode('/', $uri)[2]; + $domain = hostname_from_uri($uri); $obj = self::findWhere('domain = ?', [$domain]); if ($obj != null) return $obj; @@ -65,6 +65,14 @@ class Instance extends FetchableModel { return self::find($authRecord->instanceId); } + public static function findByRequestHeaders(): ?self { + if (!isset($_SERVER['HTTP_AUTHORIZATION']) || !str_starts_with($_SERVER['HTTP_AUTHORIZATION'], 'Bearer ')) + return null; + $header = $_SERVER['HTTP_AUTHORIZATION']; + $token = substr($header, 7); + return self::findByInboundAuthToken($token); + } + public static function findByDialbackSecret(string $secret): ?self { $authRecord = InstanceAuth::findWhere('secret = ?', [$secret]); if ($authRecord == null) @@ -126,4 +134,63 @@ class Instance extends FetchableModel { $refreshAt = (new \DateTimeImmutable($data->expires))->sub(new \DateInterval('PT1H')); (new RefreshOutboundAuthToken($this->domain, $refreshAt))->submit(); } + + private function subscribeOrUnsubscribe(bool $isUnsubscribe): bool { + if (!isset($this->endpoints->subscribe, $this->endpoints->unsubscribe)) { + throw new \RuntimeException("can't (un)subscribe to $this->domain because it doesn't have the right endpoints"); + } + if (!isset($this->auth->outboundToken)) { + throw new \RuntimeException("can't (un)subscribe to $this->domain because i don't have an outbound token for it"); + } + $context = stream_context_create(['http' => [ + 'header' => 'Authorization: Bearer ' . $this->auth->outboundToken + ]]); + file_get_contents($isUnsubscribe ? $this->endpoints->unsubscribe : $this->endpoints->subscribe, context: $context); + return str_contains($http_response_header[0], '200'); + } + + /** + * Tries to subscribe to the instance for receiving objects by push + * @return bool whether subscribing was successful + */ + public function subscribe(): bool { + if ($this->subscribeOrUnsubscribe(isUnsubscribe: false)) { + $this->auth->inboundPushEnabled = true; + $this->auth->save(); + return true; + } + return false; + } + + /** + * Tries to unsubscribe from the instance + * @return bool whether unsubscribing was successful + */ + public function unsubscribe() { + if ($this->subscribeOrUnsubscribe(isUnsubscribe: true)) { + $this->auth->inboundPushEnabled = false; + $this->auth->save(); + return true; + } + return false; + } + + public function pushObject(\JsonSerializable $obj) { + if (!isset($this->endpoints->push)) { + throw new \RuntimeException("can't push to $this->domain because it doesn't have a push endpoint"); + } + if (!isset($this->auth->outboundToken)) { + throw new \RuntimeException("can't push to $this->domain because i don't have an outbound token for it"); + } + if (!$this->auth->outboundPushEnabled) { + throw new \RuntimeException("won't push to $this->domain because it hasn't subscribed to us"); + } + $context = stream_context_create(['http' => [ + 'method' => 'POST', + 'header' => "Content-Type: application/json\nAuthorization: Bearer " . $this->auth->outboundToken, + 'content' => json_encode($obj) + ]]); + file_get_contents($this->endpoints->push, context: $context); + return str_contains($http_response_header[0], '200'); + } } \ No newline at end of file diff --git a/Digitigrade/Model/InstanceAuth.php b/Digitigrade/Model/InstanceAuth.php index 6f58298..6ebccb8 100644 --- a/Digitigrade/Model/InstanceAuth.php +++ b/Digitigrade/Model/InstanceAuth.php @@ -8,6 +8,8 @@ class InstanceAuth extends Model { public ?string $outboundToken; public ?string $inboundToken; public ?string $secret; + public bool $outboundPushEnabled = false; + public bool $inboundPushEnabled = false; protected function setOwnerId(int $id) { $this->instanceId = $id; diff --git a/Digitigrade/Model/Note.php b/Digitigrade/Model/Note.php index 3b7c362..1e867fa 100644 --- a/Digitigrade/Model/Note.php +++ b/Digitigrade/Model/Note.php @@ -3,7 +3,7 @@ namespace Digitigrade\Model; use Digitigrade\Db; -class Note extends FetchableModel implements \JsonSerializable { +class Note extends PushableModel { public ?int $id; public string $uri; public \DateTimeImmutable $created; @@ -44,6 +44,11 @@ class Note extends FetchableModel implements \JsonSerializable { $this->attachments = NoteAttachment::findAllWhere('note_id = ?', [$this->id]); } + protected function validate(): bool { + // author has to be from the same instance as the note itself + return hostname_from_uri($this->author->uri) == hostname_from_uri($this->uri); + } + private function findFormattedContents(): array { $pdo = Db::getInstance()->getPdo(); $stmt = $pdo->prepare('SELECT mimetype, body FROM note_formatted_content WHERE note_id = ?'); diff --git a/Digitigrade/Model/PushableModel.php b/Digitigrade/Model/PushableModel.php new file mode 100644 index 0000000..cfa68d3 --- /dev/null +++ b/Digitigrade/Model/PushableModel.php @@ -0,0 +1,8 @@ +