-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathASQueue.php
More file actions
246 lines (231 loc) · 7.56 KB
/
Copy pathASQueue.php
File metadata and controls
246 lines (231 loc) · 7.56 KB
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<?php
declare(strict_types=1);
namespace FediE2EE\PKDServer\Scheduled;
use FediE2EE\PKDServer\ActivityPub\{
ActivityStream,
WebFinger
};
use FediE2EE\PKD\Crypto\Exceptions\{
CryptoException,
HttpSignatureException,
NetworkException
};
use FediE2EE\PKD\Crypto\HttpSignature;
use FediE2EE\PKDServer\Exceptions\{
CacheException,
DependencyException,
ProtocolException
};
use JsonException;
use ParagonIE\PQCrypto\Exception\MLDSAInternalException;
use ParagonIE\PQCrypto\Exception\PQCryptoCompatException;
use FediE2EE\PKDServer\{
Protocol,
ServerConfig
};
use FediE2EE\PKDServer\Traits\ConfigTrait;
use GuzzleHttp\{
Client,
Exception\GuzzleException,
Psr7\Request
};
use ParagonIE\Certainty\Exception\CertaintyException;
use ParagonIE\ConstantTime\Base64;
use ParagonIE\EasyDB\EasyDB;
use Psr\Http\Message\RequestInterface;
use Psr\SimpleCache\InvalidArgumentException;
use Random\RandomException;
use SodiumException;
use Throwable;
use TypeError;
use function defined, hash, is_null;
class ASQueue
{
use ConfigTrait;
private EasyDB $db;
private Client $http;
protected ?WebFinger $webFinger = null;
/**
* @throws CertaintyException
* @throws DependencyException
* @throws SodiumException
*/
public function __construct(?ServerConfig $config = null)
{
if (is_null($config)) {
$config = $GLOBALS['pkdConfig'];
}
$this->config = $config;
$this->db = $config->getDB();
$this->http = $config->getGuzzle();
$this->webFinger = new WebFinger($config, $this->http, $config->getCaCertFetch());
}
/**
* ASQueue::run() is a very dumb method.
*
* All this method does is grab the unprocessed messages, order them, decode them, and then pass them onto
* Protocol::process().
*
* The logic is entirely contained to Protocol and the Table classes.
*
* @throws DependencyException
*/
public function run(): void
{
$workload = $this->db->run(
"SELECT * FROM pkd_activitystream_queue
WHERE NOT processed
ORDER BY queueid ASC"
);
$protocol = new Protocol($this->config);
foreach ($workload as $queue) {
$success = false;
try {
$decoded = self::jsonDecodeObject($queue['message']);
$enqueued = ActivityStream::fromDecoded($decoded);
try {
$results = $protocol->process($enqueued);
$success = true;
$this->replySuccess($enqueued, $results);
} catch (ProtocolException $ex) {
$this->replyFailure($enqueued, $ex);
}
} catch (Throwable $ex) {
$this->config()->getLogger()->error($ex->getMessage());
echo $ex->getMessage(), PHP_EOL;
}
// Update the database to mark this field as processed and whether it was successful.
$this->db->update(
'pkd_activitystream_queue',
[
'processed' => true,
'successful' => $success,
],
['queueid' => $queue['queueid']]
);
}
}
/**
* @param array<string, mixed> $results
*
* @throws CacheException
* @throws GuzzleException
* @throws InvalidArgumentException
* @throws JsonException
* @throws NetworkException
* @throws SodiumException
*/
protected function replySuccess(ActivityStream $enqueued, array $results): void
{
// TODO: Let this be customized.
$message = match ($results['action']) {
'AddKey' => 'Key added successfully.',
'AddAuxData' => 'Auxiliary data added successfully.',
'Checkpoint' => 'Checkpoint acknowledged.',
'Fireproof' => 'You are now immune from BurnDown.',
'RevokeKey' => 'Key revoked successfully.',
'RevokeAuxData' => 'Auxiliary data revoked successfully.',
'UndoFireproof' => 'You are no longer immune from BurnDown.',
default => '',
};
if (empty($message)) {
return;
}
// Append latest Merkle root
$message .= "\nLatest Merkle Root: {$results['latest-root']}";
$this->sendDM($enqueued->actor, $enqueued->id, [
'content' => $message
]);
}
/**
* @throws CacheException
* @throws GuzzleException
* @throws InvalidArgumentException
* @throws JsonException
* @throws NetworkException
* @throws SodiumException
*/
protected function replyFailure(ActivityStream $enqueued, Throwable $ex): void
{
$this->sendDM($enqueued->actor, $enqueued->id, [
'content' => defined('PKD_SERVER_DEBUG')
? $ex->getMessage()
: 'An unexpected error has occurred.',
]);
}
/**
* @param string $actor
* @param string $inReplyTo
* @param array<string, mixed> $object
*
* @throws CacheException
* @throws CryptoException
* @throws DependencyException
* @throws GuzzleException
* @throws HttpSignatureException
* @throws InvalidArgumentException
* @throws JsonException
* @throws MLDSAInternalException
* @throws NetworkException
* @throws PQCryptoCompatException
* @throws RandomException
* @throws SodiumException
*/
protected function sendDM(string $actor, string $inReplyTo, array $object): void
{
$params = $this->config()->getParams();
// Format the object:
$data = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'type' => 'Create',
'actor' => 'https://' . $params->hostname . '/users/' . $params->actorUsername,
'inReplyTo' => $inReplyTo,
'to' => [$actor],
'object' => $object,
];
$data['object']['type'] = 'Note';
$encoded = self::jsonEncode($data);
// Get the actor's inbox URL:
if (is_null($this->webFinger)) {
throw new NetworkException('WebFinger not initialized');
}
$actorInbox = $this->webFinger->getInboxUrl($actor);
$request = $this->buildSignedPost($actorInbox, $encoded);
$this->http->send($request);
}
/**
* @throws CryptoException
* @throws DependencyException
* @throws HttpSignatureException
* @throws MLDSAInternalException
* @throws PQCryptoCompatException
* @throws RandomException
* @throws SodiumException
*/
protected function buildSignedPost(string $inboxUrl, string $body): RequestInterface
{
$params = $this->config()->getParams();
$keyId = 'https://' . $params->hostname . '/users/' . $params->actorUsername . '#main-key';
$digest = 'sha-512=:' . Base64::encode(hash('sha512', $body, true)) . ':';
$request = new Request(
'POST',
$inboxUrl,
[
'Accept' => 'application/activity+json',
'Content-Type' => 'application/activity+json',
'Content-Digest' => $digest,
],
$body
);
$signed = (new HttpSignature())->sign(
$this->config()->getSigningKeys()->secretKey,
$request,
['@method', '@path', 'content-type', 'content-digest'],
$keyId
);
if (!($signed instanceof RequestInterface)) {
throw new TypeError('incorrect return type');
}
return $signed;
}
}