1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace WyriHaximus\React\ChildProcess\Messenger\Messages; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
|
9
|
|
|
use function base64_encode; |
10
|
|
|
use function hash_equals; |
11
|
|
|
use function hash_hmac; |
12
|
|
|
use function Safe\base64_decode; |
13
|
|
|
use function Safe\json_encode; |
14
|
|
|
|
15
|
|
|
final class SecureLine implements LineInterface |
16
|
|
|
{ |
17
|
|
|
protected ActionableMessageInterface $line; |
18
|
|
|
|
19
|
|
|
protected string $key; |
20
|
|
|
|
21
|
2 |
|
/** |
22
|
|
|
* @param array<mixed> $options |
23
|
2 |
|
*/ |
24
|
2 |
|
public function __construct(ActionableMessageInterface $line, array $options) |
25
|
2 |
|
{ |
26
|
|
|
$this->line = $line; |
27
|
|
|
$this->key = $options['key']; |
28
|
|
|
} |
29
|
|
|
|
30
|
2 |
|
public function __toString(): string |
31
|
|
|
{ |
32
|
2 |
|
$line = json_encode($this->line); |
33
|
|
|
|
34
|
2 |
|
return json_encode([ |
35
|
2 |
|
'type' => 'secure', |
36
|
2 |
|
'line' => $line, |
37
|
2 |
|
'signature' => base64_encode(static::sign($line, $this->key)), |
38
|
2 |
|
]) . LineInterface::EOL; |
39
|
|
|
} |
40
|
|
|
|
41
|
4 |
|
/** |
42
|
|
|
* @param array<mixed> $line |
43
|
4 |
|
* @param array<mixed> $lineOptions |
44
|
3 |
|
* |
45
|
|
|
* @throws Exception |
46
|
|
|
*/ |
47
|
1 |
|
public static function fromLine(array $line, array $lineOptions): ActionableMessageInterface |
48
|
|
|
{ |
49
|
|
|
if (static::validate(base64_decode($line['signature'], true), $line['line'], $lineOptions['key'])) { |
50
|
4 |
|
return Factory::fromLine($line['line'], $lineOptions); |
51
|
|
|
} |
52
|
4 |
|
|
53
|
|
|
/** @phpstan-ignore-next-line */ |
54
|
|
|
throw new Exception('Signature mismatch!'); |
55
|
4 |
|
} |
56
|
|
|
|
57
|
4 |
|
private static function sign(string $line, string $key): string |
58
|
|
|
{ |
59
|
|
|
return hash_hmac('sha256', $line, $key, true); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
private static function validate(string $signature, string $line, string $key): bool |
63
|
|
|
{ |
64
|
|
|
return hash_equals($signature, static::sign($line, $key)); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|