Loheide-eu-mitarbeiterplatt.../app/Push/WebPush.php
Friederich Loheide f11a3e24b3
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 3m54s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 4m0s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 4m54s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 4m50s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 7m48s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 7m38s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 6m56s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 7m5s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m17s
Phase 8 Mobil: REST-API, Web-Push, installierbare App (0.25.0)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 08:20:07 +00:00

187 lines
7.2 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Push;
use App\Support\Settings;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use OpenSSLAsymmetricKey;
use RuntimeException;
use Throwable;
/**
* Web-Push ohne zusätzliche Pakete – nur mit OpenSSL:
* Verschlüsselung nach RFC 8291 (aes128gcm) und Absender-Kennung nach RFC 8292 (VAPID).
*
* Die Schlüssel entstehen beim ersten Gebrauch und liegen verschlüsselt in den Einstellungen.
*/
class WebPush
{
public const KEYS = 'push.vapid';
/** Präfix einer DER-kodierten P-256-Public-Key-Struktur (SubjectPublicKeyInfo) vor dem 65-Byte-Punkt */
private const P256_SPKI_PREFIX = '3059301306072a8648ce3d020106082a8648ce3d030107034200';
public function __construct(private readonly Settings $settings) {}
public static function supported(): bool
{
return extension_loaded('openssl') && function_exists('openssl_pkey_derive') && in_array('aes-128-gcm', openssl_get_cipher_methods(), true);
}
/** Öffentlicher Schlüssel für den Browser (applicationServerKey, base64url) */
public function publicKey(): ?string
{
return self::supported() ? $this->keys()['public'] : null;
}
/**
* Nachricht an ein Abonnement senden. Liefert false, wenn das Abonnement ungültig ist (abgelaufen, abgemeldet).
*
* @param array<string, mixed> $payload
*/
public function send(PushSubscription $subscription, array $payload): bool
{
$body = $this->encrypt((string) json_encode($payload, JSON_UNESCAPED_UNICODE), $subscription->public_key, $subscription->auth_token);
$keys = $this->keys();
$response = Http::timeout(10)->withHeaders([
'Authorization' => 'vapid t='.$this->jwt($subscription->endpoint, $keys['private']).', k='.$keys['public'],
'Content-Encoding' => 'aes128gcm',
'Content-Type' => 'application/octet-stream',
'TTL' => '86400',
'Urgency' => 'normal',
])->withBody($body, 'application/octet-stream')->post($subscription->endpoint);
if (in_array($response->status(), [404, 410], true)) {
return false;
}
if (! $response->successful()) {
Log::warning('Web-Push abgelehnt: HTTP '.$response->status().' '.mb_substr($response->body(), 0, 200));
}
return true;
}
/**
* Inhalt verschlüsseln (RFC 8291). Ergebnis: Kopf (Salt, Satzgröße, Absenderschlüssel) + Chiffrat.
*/
public function encrypt(string $plaintext, string $userPublicKey, string $userAuth): string
{
$uaPublic = self::base64UrlDecode($userPublicKey);
$authSecret = self::base64UrlDecode($userAuth);
if (strlen($uaPublic) !== 65 || $uaPublic[0] !== "\x04" || strlen($authSecret) < 16) {
throw new RuntimeException('Ungültiges Push-Abonnement.');
}
// Einmal-Schlüsselpaar des Servers für diese Nachricht
$ephemeral = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]);
$asPublic = self::rawPublicKey($ephemeral);
$shared = openssl_pkey_derive(self::publicKeyFromRaw($uaPublic), $ephemeral, 32);
if ($shared === false) {
throw new RuntimeException('Schlüsselaustausch fehlgeschlagen.');
}
$ikm = hash_hkdf('sha256', $shared, 32, "WebPush: info\0".$uaPublic.$asPublic, $authSecret);
$salt = random_bytes(16);
$cek = hash_hkdf('sha256', $ikm, 16, "Content-Encoding: aes128gcm\0", $salt);
$nonce = hash_hkdf('sha256', $ikm, 12, "Content-Encoding: nonce\0", $salt);
$tag = '';
$cipher = openssl_encrypt($plaintext."\x02", 'aes-128-gcm', $cek, OPENSSL_RAW_DATA, $nonce, $tag);
return $salt.pack('N', 4096).chr(65).$asPublic.$cipher.$tag;
}
/**
* VAPID-Kennung: signiertes JWT (ES256) für den Push-Dienst des Abonnements.
*/
private function jwt(string $endpoint, OpenSSLAsymmetricKey $private): string
{
$parts = parse_url($endpoint);
$header = self::base64UrlEncode('{"typ":"JWT","alg":"ES256"}');
$claims = self::base64UrlEncode((string) json_encode([
'aud' => $parts['scheme'].'://'.$parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : ''),
'exp' => time() + 12 * 3600,
'sub' => rtrim((string) config('app.url'), '/') ?: 'mailto:admin@example.org',
]));
openssl_sign($header.'.'.$claims, $der, $private, OPENSSL_ALGO_SHA256);
return $header.'.'.$claims.'.'.self::base64UrlEncode(self::derToRaw($der));
}
/**
* @return array{public: string, private: OpenSSLAsymmetricKey}
*/
private function keys(): array
{
$stored = $this->settings->get(self::KEYS);
try {
if (is_array($stored) && isset($stored['private'], $stored['public'])) {
$private = openssl_pkey_get_private(Crypt::decryptString($stored['private']));
if ($private) {
return ['public' => $stored['public'], 'private' => $private];
}
}
} catch (Throwable) {
// z. B. neuer APP_KEY – dann neue Schlüssel (bestehende Abonnements werden ungültig)
}
$private = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]);
openssl_pkey_export($private, $pem);
$public = self::base64UrlEncode(self::rawPublicKey($private));
$this->settings->set(self::KEYS, ['public' => $public, 'private' => Crypt::encryptString($pem)]);
PushSubscription::query()->delete();
return ['public' => $public, 'private' => $private];
}
public static function rawPublicKey(OpenSSLAsymmetricKey $key): string
{
$ec = openssl_pkey_get_details($key)['ec'];
return "\x04".str_pad($ec['x'], 32, "\0", STR_PAD_LEFT).str_pad($ec['y'], 32, "\0", STR_PAD_LEFT);
}
public static function publicKeyFromRaw(string $raw): OpenSSLAsymmetricKey
{
$pem = "-----BEGIN PUBLIC KEY-----\n".chunk_split(base64_encode(hex2bin(self::P256_SPKI_PREFIX).$raw), 64, "\n")."-----END PUBLIC KEY-----\n";
$key = openssl_pkey_get_public($pem);
if (! $key) {
throw new RuntimeException('Ungültiger öffentlicher Schlüssel.');
}
return $key;
}
/** ECDSA-Signatur von DER (SEQUENCE r, s) in 64 Byte r||s umwandeln */
private static function derToRaw(string $der): string
{
$offset = 3 + (ord($der[1]) & 0x80 ? ord($der[1]) & 0x7F : 0);
$rLength = ord($der[$offset]);
$r = substr($der, $offset + 1, $rLength);
$offset += 1 + $rLength + 1;
$sLength = ord($der[$offset]);
$s = substr($der, $offset + 1, $sLength);
return str_pad(ltrim($r, "\0"), 32, "\0", STR_PAD_LEFT).str_pad(ltrim($s, "\0"), 32, "\0", STR_PAD_LEFT);
}
public static function base64UrlEncode(string $value): string
{
return rtrim(strtr(base64_encode($value), '+/', '-_'), '=');
}
public static function base64UrlDecode(string $value): string
{
return (string) base64_decode(strtr($value, '-_', '+/').str_repeat('=', (4 - strlen($value) % 4) % 4));
}
}