<?phpnamespace App\Cloud;use JumPHP\Net\NetSession;/** * The account's devices talking through the relay (php-wasm-network): every device of the account enters the same * private room (GET /cloud/link: {relay, room, key}, for the week), every message is sealed with AES-256-GCM and the * account's key (a fresh 12-byte nonce each): the relay only moves ciphertext and keeps nothing. * * Messages (type 40, JSON once opened): hi {device, kind, ask} (who is who in the room), want {entry, sha256, offset}, * offer {entry, size, lan: [urls], exp}, relay {entry, offset}, done {entry}, nack {entry, reason: missing | busy}, * got {entry, bytes} (the receiver's progress), push {entries: [ids]} (new entries: copy them); the synced playback * (App\Cloud\PlaySync): play {seq, leader, why, song, state, pos, vol, sent}, playAsk {}, sync {on}. * Type 41: a chunk of a file, sealed: n(entry length) entry N(offset) bytes (48 KB of the file at most). * `to` is a device id; the room's peer ids stay inside this class. */final class CloudLink{ public const JSON = 40; public const CHUNK = 41; public const CHUNK_BYTES = 49152; private const AAD = 'winzik-cloud-1'; private ?NetSession $net = null; private string $key = ''; /** @var array<int, array{device: string, kind: string}> the other peers of the room */ private array $peers = []; /** off | connecting | in | error */ public string $state = 'off'; public string $error = ''; /** @var array<string, mixed> the last /cloud/link answer */ public array $link = []; /** @var (\Closure(string, array<string, mixed>): void)|null a message from a device of the account */ public ?\Closure $onMessage = null; /** @var (\Closure(string, string, int, string): void)|null from, entry, offset, bytes */ public ?\Closure $onChunk = null; /** @var (\Closure(): void)|null a device came or went */ public ?\Closure $onPresence = null; /** @param \Closure(): NetSession $netFactory a NetSession (tests attach a fake connection to it) */ public function __construct(private \Closure $netFactory, private string $deviceId, private string $kind) { } public function setDevice(string $deviceId): void { $this->deviceId = $deviceId; } /** @param array<string, mixed> $link {relay, room, key} */ public function join(array $link): void { $this->close(); $key = self::b64decode((string)($link['key'] ?? '')); $room = (string)($link['room'] ?? ''); if (strlen($key) !== 32 || !NetSession::isRoomId($room)) { $this->state = 'error'; $this->error = 'lien du compte invalide'; return; } $this->link = $link; $this->key = $key; try { $net = ($this->netFactory)(); } catch (\Throwable $e) { $this->state = 'error'; $this->error = 'relais indisponible : ' . $e->getMessage(); return; } $this->net = $net; $this->state = 'connecting'; $net->on('room', function (): void { $this->state = 'in'; $this->peers = []; $this->sendRaw(self::JSON, json_encode(['t' => 'hi', 'device' => $this->deviceId, 'kind' => $this->kind, 'ask' => true]) ?: '', null); }); $net->on('peerLeave', function (int $peer): void { unset($this->peers[$peer]); $this->presence(); }); $net->on('close', function (): void { $this->state = 'off'; $this->peers = []; $this->presence(); }); $net->on('error', function (string $code, string $message): void { if ($code === 'quota') { $this->error = 'quota du relais atteint pour aujourd\'hui'; return; } $this->state = 'error'; $this->error = $code === 'room-id' ? 'relais trop ancien (salle privée impossible)' : $message; }); $net->on('message', fn (int $from, int $type, string $payload) => $this->received($from, $type, $payload)); try { if (!$net->isConnected()) { // JUMPHP_CLOUD_RELAY: another relay (a local playground's server answers with an address of its own domain) $relay = getenv('JUMPHP_CLOUD_RELAY'); $net->connect(is_string($relay) && $relay !== '' ? $relay : (string)($link['relay'] ?? '')); } $net->enter($room, 4, ['app' => 'winzik-cloud']); } catch (\Throwable $e) { $this->state = 'error'; $this->error = 'relais injoignable : ' . $e->getMessage(); } } public function poll(): void { try { $this->net?->poll(); } catch (\Throwable $e) { $this->state = 'error'; $this->error = $e->getMessage(); } } public function inRoom(): bool { return $this->state === 'in'; } /** @return array<string, string> the devices of the account in the room now: device id => kind */ public function devices(): array { $out = []; foreach ($this->peers as $p) { $out[$p['device']] = $p['kind']; } return $out; } public function has(string $device): bool { return isset($this->devices()[$device]); } /** @param array<string, mixed> $message $to: a device id, null = every device of the room */ public function send(array $message, ?string $to = null): bool { $json = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); return $json !== false && $this->sendRaw(self::JSON, $json, $to); } public function sendChunk(string $entry, int $offset, string $bytes, string $to): bool { return $this->sendRaw(self::CHUNK, pack('n', strlen($entry)) . $entry . pack('N', $offset) . $bytes, $to); } private function sendRaw(int $type, string $plain, ?string $to): bool { if ($this->net === null || $this->state !== 'in') { return false; } $peer = null; if ($to !== null) { $peer = $this->peerOf($to); if ($peer === null) { return false; } } return $this->net->send($type, self::seal($this->key, $plain), $peer); } private function peerOf(string $device): ?int { foreach ($this->peers as $peer => $p) { if ($p['device'] === $device) { return $peer; } } return null; } private function received(int $from, int $type, string $payload): void { $plain = self::open($this->key, $payload); if ($plain === null) { return; // not sealed with the account's key: not one of its devices } if ($type === self::CHUNK) { $device = $this->peers[$from]['device'] ?? null; if ($device === null || strlen($plain) < 6) { return; } $n = (int)unpack('n', $plain)[1]; $entry = substr($plain, 2, $n); $offset = (int)unpack('N', substr($plain, 2 + $n, 4))[1]; if ($this->onChunk !== null) { ($this->onChunk)($device, $entry, $offset, (string)substr($plain, 6 + $n)); } return; } if ($type !== self::JSON) { return; } $message = json_decode($plain, true); if (!is_array($message)) { return; } if (($message['t'] ?? '') === 'hi') { $device = (string)($message['device'] ?? ''); if ($device === '' || $device === $this->deviceId) { return; } $this->peers[$from] = ['device' => $device, 'kind' => (string)($message['kind'] ?? '')]; if (!empty($message['ask'])) { $this->sendRaw(self::JSON, json_encode(['t' => 'hi', 'device' => $this->deviceId, 'kind' => $this->kind, 'ask' => false]) ?: '', $device); } $this->presence(); return; } $device = $this->peers[$from]['device'] ?? null; if ($device !== null && $this->onMessage !== null) { ($this->onMessage)($device, $message); } } private function presence(): void { if ($this->onPresence !== null) { ($this->onPresence)(); } } public function close(): void { $this->net?->removeAllListeners(); $this->net?->close(); $this->net = null; $this->peers = []; $this->state = 'off'; } // --- AES-256-GCM ----------------------------------------------------------------------------------------------- /** nonce (12) + tag (16) + ciphertext */ public static function seal(string $key, string $plain): string { $nonce = random_bytes(12); $tag = ''; $cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag, self::AAD, 16); if ($cipher === false) { throw new \RuntimeException('chiffrement impossible'); } return $nonce . $tag . $cipher; } /** null: not sealed with this key (or changed on the way) */ public static function open(string $key, string $sealed): ?string { if (strlen($sealed) < 28 || strlen($key) !== 32) { return null; } $plain = openssl_decrypt(substr($sealed, 28), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, substr($sealed, 0, 12), substr($sealed, 12, 16), self::AAD); return $plain === false ? null : $plain; } public static function b64decode(string $text): string { return (string)base64_decode(strtr($text, '-_', '+/') . str_repeat('=', (4 - strlen($text) % 4) % 4), true); }}