commitall

This commit is contained in:
Sampanna Rimal
2024-07-10 18:28:19 +05:45
parent 140abda4e6
commit 9cd05ef3cb
15723 changed files with 4818733 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
<?php
namespace Pusher;
/**
* HTTP error responses.
* getCode() will return the response HTTP status code,
* and getMessage() will return the response body.
*/
class ApiErrorException extends PusherException
{
/**
* Returns the string representation of the exception.
*
* @return string
*/
public function __toString(): string
{
return "(Status {$this->getCode()}) {$this->getMessage()}";
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,230 @@
<?php
namespace Pusher;
class PusherCrypto
{
private $encryption_master_key;
// The prefix any e2e channel must have
public const ENCRYPTED_PREFIX = 'private-encrypted-';
/**
* Checks if a given channel is an encrypted channel.
*
* @param string $channel the name of the channel
*
* @return bool true if channel is an encrypted channel
*/
public static function is_encrypted_channel(string $channel): bool
{
return strpos($channel, self::ENCRYPTED_PREFIX) === 0;
}
/**
* Checks if channels are a mix of encrypted and non-encrypted types.
*
* @param array $channels
* @return bool true when mixed channel types are discovered
*/
public static function has_mixed_channels(array $channels): bool
{
$unencrypted_seen = false;
$encrypted_seen = false;
foreach ($channels as $channel) {
if(self::is_encrypted_channel($channel)) {
if ($unencrypted_seen) {
return true;
} else {
$encrypted_seen = true;
}
} else {
if ($encrypted_seen) {
return true;
} else {
$unencrypted_seen = true;
}
}
}
return false;
}
/**
* @param $encryption_master_key_base64
* @return string
* @throws PusherException
*/
public static function parse_master_key($encryption_master_key_base64): string
{
if (!function_exists('sodium_crypto_secretbox')) {
throw new PusherException('To use end to end encryption, you must either be using PHP 7.2 or greater or have installed the libsodium-php extension for php < 7.2.');
}
if ($encryption_master_key_base64 !== '') {
$decoded_key = base64_decode($encryption_master_key_base64, true);
if ($decoded_key === false) {
throw new PusherException('encryption_master_key_base64 must be a valid base64 string');
}
if (strlen($decoded_key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
throw new PusherException('encryption_master_key_base64 must encode a key which is 32 bytes long');
}
return $decoded_key;
}
return '';
}
/**
* Initialises a PusherCrypto instance.
*
* @param string $encryption_master_key the SECRET_KEY_LENGTH key that will be used for key derivation.
*/
public function __construct(string $encryption_master_key)
{
$this->encryption_master_key = $encryption_master_key;
}
/**
* Decrypts a given event.
*
* @param object $event an object that has an encrypted data property and a channel property.
*
* @return object the event with a decrypted payload, or false if decryption was unsuccessful.
* @throws PusherException
*/
public function decrypt_event(object $event): object
{
$parsed_payload = $this->parse_encrypted_message($event->data);
$shared_secret = $this->generate_shared_secret($event->channel);
$decrypted_payload = $this->decrypt_payload($parsed_payload->ciphertext, $parsed_payload->nonce, $shared_secret);
if (!$decrypted_payload) {
throw new PusherException('Decryption of the payload failed. Wrong key?');
}
$event->data = $decrypted_payload;
return $event;
}
/**
* Derives a shared secret from the secret key and the channel to broadcast to.
*
* @param string $channel the name of the channel
*
* @return string a SHA256 hash (encoded as base64) of the channel name appended to the encryption key
* @throws PusherException
*/
public function generate_shared_secret(string $channel): string
{
if (!self::is_encrypted_channel($channel)) {
throw new PusherException('You must specify a channel of the form private-encrypted-* for E2E encryption. Got ' . $channel);
}
return hash('sha256', $channel . $this->encryption_master_key, true);
}
/**
* Encrypts a given plaintext for broadcast on a particular channel.
*
* @param string $channel the name of the channel the payloads event will be broadcast on
* @param string $plaintext the data to encrypt
*
* @return string a string ready to be sent as the data of an event.
* @throws PusherException
* @throws \SodiumException
*/
public function encrypt_payload(string $channel, string $plaintext): string
{
if (!self::is_encrypted_channel($channel)) {
throw new PusherException('Cannot encrypt plaintext for a channel that is not of the form private-encrypted-*. Got ' . $channel);
}
$nonce = $this->generate_nonce();
$shared_secret = $this->generate_shared_secret($channel);
$cipher_text = sodium_crypto_secretbox($plaintext, $nonce, $shared_secret);
try {
return $this->format_encrypted_message($nonce, $cipher_text);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
}
/**
* Decrypts a given payload using the nonce and shared secret.
*
* @param string $payload the ciphertext
* @param string $nonce the nonce used in the encryption
* @param string $shared_secret the shared_secret used in the encryption
*
* @return string plaintext
* @throws \SodiumException
*/
public function decrypt_payload(string $payload, string $nonce, string $shared_secret)
{
$plaintext = sodium_crypto_secretbox_open($payload, $nonce, $shared_secret);
if (empty($plaintext)) {
return false;
}
return $plaintext;
}
/**
* Formats an encrypted message ready for broadcast.
*
* @param string $nonce the nonce used in the encryption process (bytes)
* @param string $ciphertext the ciphertext (bytes)
*
* @return string JSON with base64 encoded nonce and ciphertext`
* @throws \JsonException
*/
private function format_encrypted_message(string $nonce, string $ciphertext): string
{
$encrypted_message = new \stdClass();
$encrypted_message->nonce = base64_encode($nonce);
$encrypted_message->ciphertext = base64_encode($ciphertext);
return json_encode($encrypted_message, JSON_THROW_ON_ERROR);
}
/**
* Parses an encrypted message into its nonce and ciphertext components.
*
*
* @param string $payload the encrypted message payload
*
* @return object php object with decoded nonce and ciphertext
* @throws PusherException
*/
private function parse_encrypted_message(string $payload): object
{
try {
$decoded_payload = json_decode($payload, false, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new PusherException('Data decoding error.');
}
$decoded_payload->nonce = base64_decode($decoded_payload->nonce);
$decoded_payload->ciphertext = base64_decode($decoded_payload->ciphertext);
if ($decoded_payload->ciphertext === '' || strlen($decoded_payload->nonce) !== SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
throw new PusherException('Received a payload that cannot be parsed.');
}
return $decoded_payload;
}
/**
* Generates a nonce that is SODIUM_CRYPTO_SECRETBOX_NONCEBYTES long.
* @return string
* @throws \Exception
*/
private function generate_nonce(): string
{
return random_bytes(
SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
);
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Pusher;
use Exception;
class PusherException extends Exception
{
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Pusher;
class PusherInstance
{
private static $instance = null;
private static $app_id = '';
private static $secret = '';
private static $api_key = '';
/**
* Get the pusher singleton instance.
*
* @return Pusher
* @throws PusherException
*/
public static function get_pusher()
{
if (self::$instance !== null) {
return self::$instance;
}
self::$instance = new Pusher(
self::$api_key,
self::$secret,
self::$app_id
);
return self::$instance;
}
}

View File

@@ -0,0 +1,257 @@
<?php
namespace Pusher;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
interface PusherInterface
{
/**
* Fetch the settings.
*
* @return array
*/
public function getSettings();
/**
* Trigger an event by providing event name and payload.
* Optionally provide a socket ID to exclude a client (most likely the sender).
*
* @param array|string $channels A channel name or an array of channel names to publish the event on.
* @param string $event
* @param mixed $data Event data
* @param array $params [optional]
* @param bool $already_encoded [optional]
*
* @throws PusherException Throws exception if $channels is an array of size 101 or above or $socket_id is invalid
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function trigger($channels, string $event, $data, array $params = [], bool $already_encoded = false): object;
/**
* Asynchronously trigger an event by providing event name and payload.
* Optionally provide a socket ID to exclude a client (most likely the sender).
*
* @param array|string $channels A channel name or an array of channel names to publish the event on.
* @param mixed $data Event data
* @param array $params [optional]
* @param bool $already_encoded [optional]
*
*/
public function triggerAsync($channels, string $event, $data, array $params = [], bool $already_encoded = false): PromiseInterface;
/**
* Trigger multiple events at the same time.
*
* @param array $batch [optional] An array of events to send
* @param bool $already_encoded [optional]
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function triggerBatch(array $batch = [], bool $already_encoded = false): object;
/**
* Asynchronously trigger multiple events at the same time.
*
* @param array $batch [optional] An array of events to send
* @param bool $already_encoded [optional]
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
*
*/
public function triggerBatchAsync(array $batch = [], bool $already_encoded = false): PromiseInterface;
/**
* Get information, such as subscriber and user count, for a channel.
*
* @param string $channel The name of the channel
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws PusherException If $channel is invalid or if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function getChannelInfo(string $channel, array $params = []): object;
/**
* Fetch a list containing all channels.
*
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function getChannels(array $params = []): object;
/**
* Fetch user ids currently subscribed to a presence channel.
*
* @param string $channel The name of the channel
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function getPresenceUsers(string $channel): object;
/**
* GET arbitrary REST API resource using a synchronous http client.
* All request signing is handled automatically.
*
* @param string $path Path excluding /apps/APP_ID
* @param array $params API params (see http://pusher.com/docs/rest_api)
* @param bool $associative When true, return the response body as an associative array, else return as an object
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
* @return mixed See Pusher API docs
*/
public function get(string $path, array $params = [], bool $associative = false);
/**
* Creates a socket signature.
*
* @param string $channel
* @param string $socket_id
* @param string|null $custom_data
* @return string Json encoded authentication string.
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*/
public function socketAuth(string $channel, string $socket_id, string $custom_data = null): string;
/**
* Creates a presence signature (an extension of socket signing).
*
* @param mixed $user_info
*
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*
*/
public function presenceAuth(string $channel, string $socket_id, string $user_id, $user_info = null): string;
/**
* Verify that a webhook actually came from Pusher, decrypts any
* encrypted events, and marshals them into a PHP object.
*
* @param array $headers a array of headers from the request (for example, from getallheaders())
* @param string $body the body of the request (for example, from file_get_contents('php://input'))
*
* @throws PusherException
*
* @return Webhook marshalled object with the properties time_ms (an int) and events (an array of event objects)
*/
public function webhook(array $headers, string $body): object;
/**
* Verify that a given Pusher Signature is valid.
*
* @param array $headers an array of headers from the request (for example, from getallheaders())
* @param string $body the body of the request (for example, from file_get_contents('php://input'))
*
* @throws PusherException if signature is incorrect.
*/
public function verifySignature(array $headers, string $body);
/*******************************************************************
*
* DEPRECATION WARNING:
*
* all the functions below have been deprecated in favour of their
* camelCased variants. They will be removed in the next major
* update.
*/
/**
* Get information, such as subscriber and user count, for a channel.
*
* @deprecated in favour of getChannelInfo
*
* @param string $channel The name of the channel
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws PusherException If $channel is invalid or if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function get_channel_info(string $channel, array $params = []): object;
/**
* Fetch a list containing all channels.
*
* @deprecated in favour of getChannels
*
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function get_channels(array $params = []): object;
/**
* Fetch user ids currently subscribed to a presence channel.
*
* @deprecated in favour of getPresenceUsers
*
* @param string $channel The name of the channel
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function get_users_info(string $channel): object;
/**
* Creates a socket signature.
*
* @deprecated in favour of socketAuth
*
* @param string $channel
* @param string $socket_id
* @param string|null $custom_data
* @return string Json encoded authentication string.
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*/
public function socket_auth(string $channel, string $socket_id, string $custom_data = null): string;
/**
* Creates a presence signature (an extension of socket signing).
*
* @deprecated in favour of presenceAuth
*
* @param mixed $user_info
*
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*
*/
public function presence_auth(string $channel, string $socket_id, string $user_id, $user_info = null): string;
/**
* Verify that a given Pusher Signature is valid.
*
* @deprecated in favour of verifySignature
*
* @param array $headers an array of headers from the request (for example, from getallheaders())
* @param string $body the body of the request (for example, from file_get_contents('php://input'))
*
* @throws PusherException if signature is incorrect.
*/
public function ensure_valid_signature(array $headers, string $body);
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Pusher;
class Webhook
{
/** @var int $time_ms */
private $time_ms;
/** @var array $events */
private $events;
public function __construct($time_ms, $events)
{
$this->time_ms = $time_ms;
$this->events = $events;
}
public function get_events(): array
{
return $this->events;
}
public function get_time_ms(): int
{
return $this->time_ms;
}
}