aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Model/Instance.php
blob: e4b1ef13cf48280f9077feeb7472820d03454d36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<?php
namespace Digitigrade\Model;

use Digitigrade\Job\RefreshOutboundAuthToken;

class Instance extends FetchableModel {
    public ?int $id;
    public string $domain;
    public string $name;
    public ?string $description;
    public ?string $icon; // uri
    public string $softwareName;
    public ?string $softwareDescription;
    public ?string $softwareVersion;
    public ?string $softwareHomepage;

    public InstanceEndpoints $endpoints;
    public InstanceAuth $auth;

    protected function getUpdateWhereClause(\PDO $db): ?string {
        if (self::findWhere('domain = ?', [$this->domain]) != null)
            return 'domain = ' . $db->quote($this->domain);
        if (self::findWhere('id = ?', [$this->id]) != null)
            return "id = $this->id";
        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);
    }

    protected function hydrate() {
        $this->endpoints = InstanceEndpoints::findWhere('instance_id = ?', [$this->id]);
        $auth = InstanceAuth::findWhere('instance_id = ?', [$this->id]);
        if ($auth == null) {
            $auth = new InstanceAuth();
            $auth->setOwnerId($this->id);
        }
        $this->auth = $auth;
    }

    protected function finaliseAfterFetch(string $uri) {
        $this->domain = explode('/', $uri)[2];
    }

    protected function finaliseAfterSave() {
        // this has to be done after saving because we didn't have an id before
        $this->auth = InstanceAuth::findWhere('instance_id = ?', [$this->id]) ?? new InstanceAuth();
    }

    public static function findByUri(string $uri, bool $autoSave = true, bool $forceRefetch = false): ?static {
        if (!$forceRefetch) {
            $domain = explode('/', $uri)[2];
            $obj = self::findWhere('domain = ?', [$domain]);
            if ($obj != null)
                return $obj;
        }
        return self::fetchFromRemote($uri, $autoSave);
    }

    public static function findByInboundAuthToken(string $token): ?self {
        $authRecord = InstanceAuth::findWhere('inbound_token = ?', [$token]);
        if ($authRecord == null)
            return null;
        return self::find($authRecord->instanceId);
    }

    public static function findByDialbackSecret(string $secret): ?self {
        $authRecord = InstanceAuth::findWhere('secret = ?', [$secret]);
        if ($authRecord == null)
            return null;
        return self::find($authRecord->instanceId);
    }

    public function beginOutboundAuth() {
        $authEndpoint = $this->endpoints->auth;
        if (!isset($authEndpoint)) {
            throw new \RuntimeException("can't authenticate with $this->domain because it doesn't have an auth endpoint");
        }
        file_get_contents($authEndpoint . '?phase=dialback&target=' . urlencode(path_to_uri('/auth/dialback')));
    }

    public function requestOutboundAuthToken(string $secret) {
        $authEndpoint = $this->endpoints->auth;
        if (!isset($authEndpoint)) {
            throw new \RuntimeException("can't authenticate with $this->domain because it doesn't have an auth endpoint");
        }
        $response = file_get_contents($authEndpoint . '?phase=token&secret=' . urlencode($secret));
        if ($response === false) {
            throw new \RuntimeException("requesting a token from $this->domain failed");
        }
        $data = json_decode($response);
        if ($data === false || !isset($data->token, $data->expires)) {
            throw new \RuntimeException("$this->domain sent bogus json in response to token request");
        }

        $this->auth->outboundToken = $data->token;
        $this->save();

        (new RefreshOutboundAuthToken($this->domain, new \DateTimeImmutable($data->expires)))->submit();
    }

    public function refreshOutboundAuthToken() {
        $authEndpoint = $this->endpoints->auth;
        if (!isset($authEndpoint)) {
            throw new \RuntimeException("can't authenticate with $this->domain because it doesn't have an auth endpoint");
        }
        if (!isset($this->auth->outboundToken)) {
            throw new \RuntimeException("can't refresh outbound token for $this->domain because i don't already have one");
        }
        $response = file_get_contents($authEndpoint . '?phase=refresh&token=' . urlencode($this->auth->outboundToken));
        if ($response === false) {
            throw new \RuntimeException("requesting a new token from $this->domain failed");
        }
        $data = json_decode($response);
        if ($data === false || !isset($data->token, $data->expires)) {
            throw new \RuntimeException("$this->domain sent bogus json in response to token refresh request");
        }

        $this->auth->outboundToken = $data->token;
        $this->save();

        (new RefreshOutboundAuthToken($this->domain, new \DateTimeImmutable($data->expires)))->submit();
    }
}