allow vendord
All checks were successful
Build, Push and Deploy / build-and-push (push) Successful in 3m3s
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 16s
Build, Push and Deploy / deploy-staging (push) Successful in 32s
Build, Push and Deploy / deploy-production (push) Has been skipped
Build, Push and Deploy / cleanup (push) Successful in 1s

This commit is contained in:
2026-03-30 14:54:57 +07:00
parent 66aed7c4e8
commit b5e3a778ce
21316 changed files with 2777892 additions and 13 deletions

View File

@@ -0,0 +1,169 @@
<?php
namespace Twilio\Jwt;
use Twilio\Jwt\Grants\Grant;
class AccessToken {
private $signingKeySid;
private $accountSid;
private $secret;
private $ttl;
private $identity;
private $nbf;
private $region;
/** @var Grant[] $grants */
private $grants;
/** @var string[] $customClaims */
private $customClaims;
public function __construct(string $accountSid, string $signingKeySid, string $secret, int $ttl = 3600, ?string $identity = null, ?string $region = null) {
$this->signingKeySid = $signingKeySid;
$this->accountSid = $accountSid;
$this->secret = $secret;
$this->ttl = $ttl;
$this->region = $region;
if ($identity !== null) {
$this->identity = $identity;
}
$this->grants = [];
$this->customClaims = [];
}
/**
* Set the identity of this access token
*
* @param string $identity identity of the grant
*
* @return $this updated access token
*/
public function setIdentity(string $identity): self {
$this->identity = $identity;
return $this;
}
/**
* Returns the identity of the grant
*
* @return string the identity
*/
public function getIdentity(): string {
return $this->identity;
}
/**
* Set the nbf of this access token
*
* @param int $nbf nbf in epoch seconds of the grant
*
* @return $this updated access token
*/
public function setNbf(int $nbf): self {
$this->nbf = $nbf;
return $this;
}
/**
* Returns the nbf of the grant
*
* @return int the nbf in epoch seconds
*/
public function getNbf(): int {
return $this->nbf;
}
/**
* Set the region of this access token
*
* @param string $region Home region of the account sid in this access token
*
* @return $this updated access token
*/
public function setRegion(string $region): self {
$this->region = $region;
return $this;
}
/**
* Returns the region of this access token
*
* @return string Home region of the account sid in this access token
*/
public function getRegion(): string {
return $this->region;
}
/**
* Add a grant to the access token
*
* @param Grant $grant to be added
*
* @return $this the updated access token
*/
public function addGrant(Grant $grant): self {
$this->grants[] = $grant;
return $this;
}
/**
* Allows to set custom claims, which then will be encoded into JWT payload.
*
* @param string $name
* @param string $value
*/
public function addClaim(string $name, string $value): void {
$this->customClaims[$name] = $value;
}
public function toJWT(string $algorithm = 'HS256'): string {
$header = [
'cty' => 'twilio-fpa;v=1',
'typ' => 'JWT'
];
if ($this->region) {
$header['twr'] = $this->region;
}
$now = \time();
$grants = [];
if ($this->identity) {
$grants['identity'] = $this->identity;
}
foreach ($this->grants as $grant) {
$payload = $grant->getPayload();
if (empty($payload)) {
$payload = \json_decode('{}');
}
$grants[$grant->getGrantKey()] = $payload;
}
if (empty($grants)) {
$grants = \json_decode('{}');
}
$payload = \array_merge($this->customClaims, [
'jti' => $this->signingKeySid . '-' . $now,
'iss' => $this->signingKeySid,
'sub' => $this->accountSid,
'exp' => $now + $this->ttl,
'grants' => $grants
]);
if ($this->nbf !== null) {
$payload['nbf'] = $this->nbf;
}
return JWT::encode($payload, $this->secret, $algorithm, $header);
}
public function __toString(): string {
return $this->toJWT();
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Twilio\Jwt\Client;
/**
* Scope URI implementation
*
* Simple way to represent configurable privileges in an OAuth
* friendly way. For our case, they look like this:
*
* scope:<service>:<privilege>?<params>
*
* For example:
* scope:client:incoming?name=jonas
*/
class ScopeURI {
public $service;
public $privilege;
public $params;
public function __construct(string $service, string $privilege, array $params = []) {
$this->service = $service;
$this->privilege = $privilege;
$this->params = $params;
}
public function toString(): string {
$uri = "scope:{$this->service}:{$this->privilege}";
if (\count($this->params)) {
$uri .= '?' . \http_build_query($this->params, '', '&');
}
return $uri;
}
/**
* Parse a scope URI into a ScopeURI object
*
* @param string $uri The scope URI
* @return ScopeURI The parsed scope uri
* @throws \UnexpectedValueException
*/
public static function parse(string $uri): ScopeURI {
if (\strpos($uri, 'scope:') !== 0) {
throw new \UnexpectedValueException(
'Not a scope URI according to scheme');
}
$parts = \explode('?', $uri, 1);
$params = null;
if (\count($parts) > 1) {
\parse_str($parts[1], $params);
}
$parts = \explode(':', $parts[0], 2);
if (\count($parts) !== 3) {
throw new \UnexpectedValueException(
'Not enough parts for scope URI');
}
[$scheme, $service, $privilege] = $parts;
return new ScopeURI($service, $privilege, $params);
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace Twilio\Jwt;
use Twilio\Jwt\Client\ScopeURI;
/**
* Twilio Capability Token generator
*/
class ClientToken {
public $accountSid;
public $authToken;
/** @var ScopeURI[] $scopes */
public $scopes;
public $clientName;
/** @var string[] $customClaims */
private $customClaims;
/**
* Create a new TwilioCapability with zero permissions. Next steps are to
* grant access to resources by configuring this token through the
* functions allowXXXX.
*
* @param string $accountSid the account sid to which this token is granted
* access
* @param string $authToken the secret key used to sign the token. Note,
* this auth token is not visible to the user of the token.
*/
public function __construct(string $accountSid, string $authToken) {
$this->accountSid = $accountSid;
$this->authToken = $authToken;
$this->scopes = [];
$this->clientName = false;
$this->customClaims = [];
}
/**
* If the user of this token should be allowed to accept incoming
* connections then configure the TwilioCapability through this method and
* specify the client name.
*
* @param string $clientName
* @throws \InvalidArgumentException
*/
public function allowClientIncoming(string $clientName): void {
// clientName must be a non-zero length alphanumeric string
if (\preg_match('/\W/', $clientName)) {
throw new \InvalidArgumentException(
'Only alphanumeric characters allowed in client name.');
}
if ($clientName === '') {
throw new \InvalidArgumentException(
'Client name must not be a zero length string.');
}
$this->clientName = $clientName;
$this->allow('client', 'incoming', ['clientName' => $clientName]);
}
/**
* Allow the user of this token to make outgoing connections.
*
* @param string $appSid the application to which this token grants access
* @param mixed[] $appParams signed parameters that the user of this token
* cannot overwrite.
*/
public function allowClientOutgoing(string $appSid, array $appParams = []): void {
$this->allow('client', 'outgoing', [
'appSid' => $appSid,
'appParams' => \http_build_query($appParams, '', '&')
]);
}
/**
* Allow the user of this token to access their event stream.
*
* @param mixed[] $filters key/value filters to apply to the event stream
*/
public function allowEventStream(array $filters = []): void {
$this->allow('stream', 'subscribe', [
'path' => '/2010-04-01/Events',
'params' => \http_build_query($filters, '', '&'),
]);
}
/**
* Allows to set custom claims, which then will be encoded into JWT payload.
*
* @param string $name
* @param string $value
*/
public function addClaim(string $name, string $value): void {
$this->customClaims[$name] = $value;
}
/**
* Generates a new token based on the credentials and permissions that
* previously has been granted to this token.
*
* @param int $ttl the expiration time of the token (in seconds). Default
* value is 3600 (1hr)
* @return string the newly generated token that is valid for $ttl seconds
*/
public function generateToken(int $ttl = 3600): string {
$payload = \array_merge($this->customClaims, [
'scope' => [],
'iss' => $this->accountSid,
'exp' => \time() + $ttl,
]);
$scopeStrings = [];
foreach ($this->scopes as $scope) {
if ($scope->privilege === 'outgoing' && $this->clientName) {
$scope->params['clientName'] = $this->clientName;
}
$scopeStrings[] = $scope->toString();
}
$payload['scope'] = \implode(' ', $scopeStrings);
return JWT::encode($payload, $this->authToken, 'HS256');
}
protected function allow(string $service, string $privilege, array $params): void {
$this->scopes[] = new ScopeURI($service, $privilege, $params);
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace Twilio\Jwt\Grants;
class ChatGrant implements Grant {
private $serviceSid;
private $endpointId;
private $deploymentRoleSid;
private $pushCredentialSid;
/**
* Returns the service sid
*
* @return string the service sid
*/
public function getServiceSid(): string {
return $this->serviceSid;
}
/**
* Set the service sid of this grant
*
* @param string $serviceSid service sid of the grant
*
* @return $this updated grant
*/
public function setServiceSid(string $serviceSid): self {
$this->serviceSid = $serviceSid;
return $this;
}
/**
* Returns the endpoint id of the grant
*
* @return string the endpoint id
*/
public function getEndpointId(): string {
return $this->endpointId;
}
/**
* Set the endpoint id of the grant
*
* @param string $endpointId endpoint id of the grant
*
* @return $this updated grant
*/
public function setEndpointId(string $endpointId): self {
$this->endpointId = $endpointId;
return $this;
}
/**
* Returns the deployment role sid of the grant
*
* @return string the deployment role sid
*/
public function getDeploymentRoleSid(): string {
return $this->deploymentRoleSid;
}
/**
* Set the role sid of the grant
*
* @param string $deploymentRoleSid role sid of the grant
*
* @return $this updated grant
*/
public function setDeploymentRoleSid(string $deploymentRoleSid): self {
$this->deploymentRoleSid = $deploymentRoleSid;
return $this;
}
/**
* Returns the push credential sid of the grant
*
* @return string the push credential sid
*/
public function getPushCredentialSid(): string {
return $this->pushCredentialSid;
}
/**
* Set the credential sid of the grant
*
* @param string $pushCredentialSid push credential sid of the grant
*
* @return $this updated grant
*/
public function setPushCredentialSid(string $pushCredentialSid): self {
$this->pushCredentialSid = $pushCredentialSid;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'chat';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->serviceSid) {
$payload['service_sid'] = $this->serviceSid;
}
if ($this->endpointId) {
$payload['endpoint_id'] = $this->endpointId;
}
if ($this->deploymentRoleSid) {
$payload['deployment_role_sid'] = $this->deploymentRoleSid;
}
if ($this->pushCredentialSid) {
$payload['push_credential_sid'] = $this->pushCredentialSid;
}
return $payload;
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace Twilio\Jwt\Grants;
interface Grant {
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string;
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array;
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Twilio\Jwt\Grants;
class PlaybackGrant implements Grant {
private $grant;
/**
* Returns the grant
*
* @return array playback grant from the Twilio API
*/
public function getGrant(): array {
return $this->grant;
}
/**
* Set the playback grant that will allow access to a stream
*
* @param array $grant playback grant from Twilio API
* @return $this updated grant
*/
public function setGrant(array $grant): self {
$this->grant = $grant;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'player';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->grant) {
$payload = $this->grant;
}
return $payload;
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace Twilio\Jwt\Grants;
class SyncGrant implements Grant {
private $serviceSid;
private $endpointId;
private $deploymentRoleSid;
private $pushCredentialSid;
/**
* Returns the service sid
*
* @return string the service sid
*/
public function getServiceSid(): string {
return $this->serviceSid;
}
/**
* Set the service sid of this grant
*
* @param string $serviceSid service sid of the grant
*
* @return $this updated grant
*/
public function setServiceSid(string $serviceSid): self {
$this->serviceSid = $serviceSid;
return $this;
}
/**
* Returns the endpoint id of the grant
*
* @return string the endpoint id
*/
public function getEndpointId(): string {
return $this->endpointId;
}
/**
* Set the endpoint id of the grant
*
* @param string $endpointId endpoint id of the grant
*
* @return $this updated grant
*/
public function setEndpointId(string $endpointId): self {
$this->endpointId = $endpointId;
return $this;
}
/**
* Returns the deployment role sid of the grant
*
* @return string the deployment role sid
*/
public function getDeploymentRoleSid(): string {
return $this->deploymentRoleSid;
}
/**
* Set the role sid of the grant
*
* @param string $deploymentRoleSid role sid of the grant
*
* @return $this updated grant
*/
public function setDeploymentRoleSid(string $deploymentRoleSid): self {
$this->deploymentRoleSid = $deploymentRoleSid;
return $this;
}
/**
* Returns the push credential sid of the grant
*
* @return string the push credential sid
*/
public function getPushCredentialSid(): string {
return $this->pushCredentialSid;
}
/**
* Set the credential sid of the grant
*
* @param string $pushCredentialSid push credential sid of the grant
*
* @return $this updated grant
*/
public function setPushCredentialSid(string $pushCredentialSid): self {
$this->pushCredentialSid = $pushCredentialSid;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'data_sync';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->serviceSid) {
$payload['service_sid'] = $this->serviceSid;
}
if ($this->endpointId) {
$payload['endpoint_id'] = $this->endpointId;
}
if ($this->deploymentRoleSid) {
$payload['deployment_role_sid'] = $this->deploymentRoleSid;
}
if ($this->pushCredentialSid) {
$payload['push_credential_sid'] = $this->pushCredentialSid;
}
return $payload;
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace Twilio\Jwt\Grants;
class TaskRouterGrant implements Grant {
private $workspaceSid;
private $workerSid;
private $role;
/**
* Returns the workspace sid
*
* @return string the workspace sid
*/
public function getWorkspaceSid(): string {
return $this->workspaceSid;
}
/**
* Set the workspace sid of this grant
*
* @param string $workspaceSid workspace sid of the grant
*
* @return $this updated grant
*/
public function setWorkspaceSid(string $workspaceSid): self {
$this->workspaceSid = $workspaceSid;
return $this;
}
/**
* Returns the worker sid
*
* @return string the worker sid
*/
public function getWorkerSid(): string {
return $this->workerSid;
}
/**
* Set the worker sid of this grant
*
* @param string $workerSid worker sid of the grant
*
* @return $this updated grant
*/
public function setWorkerSid(string $workerSid): self {
$this->workerSid = $workerSid;
return $this;
}
/**
* Returns the role
*
* @return string the role
*/
public function getRole(): string {
return $this->role;
}
/**
* Set the role of this grant
*
* @param string $role role of the grant
*
* @return $this updated grant
*/
public function setRole(string $role): self {
$this->role = $role;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'task_router';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->workspaceSid) {
$payload['workspace_sid'] = $this->workspaceSid;
}
if ($this->workerSid) {
$payload['worker_sid'] = $this->workerSid;
}
if ($this->role) {
$payload['role'] = $this->role;
}
return $payload;
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Twilio\Jwt\Grants;
class VideoGrant implements Grant {
private $room;
/**
* Returns the room
*
* @return string room name or sid set in this grant
*/
public function getRoom(): string {
return $this->room;
}
/**
* Set the room to allow access to in the grant
*
* @param string $roomSidOrName room sid or name
* @return $this updated grant
*/
public function setRoom(string $roomSidOrName): self {
$this->room = $roomSidOrName;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'video';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->room) {
$payload['room'] = $this->room;
}
return $payload;
}
}

View File

@@ -0,0 +1,165 @@
<?php
namespace Twilio\Jwt\Grants;
class VoiceGrant implements Grant {
private $incomingAllow;
private $outgoingApplicationSid;
private $outgoingApplicationParams;
private $pushCredentialSid;
private $endpointId;
/**
* Returns whether incoming is allowed
*
* @return bool whether incoming is allowed
*/
public function getIncomingAllow(): bool {
return $this->incomingAllow;
}
/**
* Set whether incoming is allowed
*
* @param bool $incomingAllow whether incoming is allowed
*
* @return $this updated grant
*/
public function setIncomingAllow(bool $incomingAllow): self {
$this->incomingAllow = $incomingAllow;
return $this;
}
/**
* Returns the outgoing application sid
*
* @return string the outgoing application sid
*/
public function getOutgoingApplicationSid(): string {
return $this->outgoingApplicationSid;
}
/**
* Set the outgoing application sid of the grant
*
* @param string $outgoingApplicationSid outgoing application sid of grant
*
* @return $this updated grant
*/
public function setOutgoingApplicationSid(string $outgoingApplicationSid): self {
$this->outgoingApplicationSid = $outgoingApplicationSid;
return $this;
}
/**
* Returns the outgoing application params
*
* @return array the outgoing application params
*/
public function getOutgoingApplicationParams(): array {
return $this->outgoingApplicationParams;
}
/**
* Set the outgoing application of the the grant
*
* @param string $sid outgoing application sid of the grant
* @param array $params params to pass the the application
*
* @return $this updated grant
*/
public function setOutgoingApplication(string $sid, array $params): self {
$this->outgoingApplicationSid = $sid;
$this->outgoingApplicationParams = $params;
return $this;
}
/**
* Returns the push credential sid
*
* @return string the push credential sid
*/
public function getPushCredentialSid(): string {
return $this->pushCredentialSid;
}
/**
* Set the push credential sid
*
* @param string $pushCredentialSid
*
* @return $this updated grant
*/
public function setPushCredentialSid(string $pushCredentialSid): self {
$this->pushCredentialSid = $pushCredentialSid;
return $this;
}
/**
* Returns the endpoint id
*
* @return string the endpoint id
*/
public function getEndpointId(): string {
return $this->endpointId;
}
/**
* Set the endpoint id
*
* @param string $endpointId endpoint id
*
* @return $this updated grant
*/
public function setEndpointId(string $endpointId): self {
$this->endpointId = $endpointId;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'voice';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->incomingAllow === true) {
$incoming = [];
$incoming['allow'] = true;
$payload['incoming'] = $incoming;
}
if ($this->outgoingApplicationSid) {
$outgoing = [];
$outgoing['application_sid'] = $this->outgoingApplicationSid;
if ($this->outgoingApplicationParams) {
$outgoing['params'] = $this->outgoingApplicationParams;
}
$payload['outgoing'] = $outgoing;
}
if ($this->pushCredentialSid) {
$payload['push_credential_sid'] = $this->pushCredentialSid;
}
if ($this->endpointId) {
$payload['endpoint_id'] = $this->endpointId;
}
return $payload;
}
}

172
vendor/twilio/sdk/src/Twilio/Jwt/JWT.php vendored Normal file
View File

@@ -0,0 +1,172 @@
<?php
namespace Twilio\Jwt;
/**
* JSON Web Token implementation
*
* Minimum implementation used by Realtime auth, based on this spec:
* http://self-issued.info/docs/draft-jones-json-web-token-01.html.
*
* @author Neuman Vong <neuman@twilio.com>
*/
class JWT {
/**
* @param string $jwt The JWT
* @param string|null $key The secret key
* @param bool $verify Don't skip verification process
* @return object The JWT's payload as a PHP object
* @throws \DomainException
* @throws \UnexpectedValueException
*/
public static function decode(string $jwt, ?string $key = null, bool $verify = true) {
$tks = \explode('.', $jwt);
if (\count($tks) !== 3) {
throw new \UnexpectedValueException('Wrong number of segments');
}
list($headb64, $payloadb64, $cryptob64) = $tks;
if (null === ($header = self::jsonDecode(self::urlsafeB64Decode($headb64)))
) {
throw new \UnexpectedValueException('Invalid segment encoding');
}
if (null === $payload = self::jsonDecode(self::urlsafeB64Decode($payloadb64))
) {
throw new \UnexpectedValueException('Invalid segment encoding');
}
$sig = self::urlsafeB64Decode($cryptob64);
if ($verify) {
if (empty($header->alg)) {
throw new \DomainException('Empty algorithm');
}
if (!hash_equals($sig, self::sign("$headb64.$payloadb64", $key, $header->alg))) {
throw new \UnexpectedValueException('Signature verification failed');
}
}
return $payload;
}
/**
* @param string $jwt The JWT
* @return object The JWT's header as a PHP object
* @throws \UnexpectedValueException
*/
public static function getHeader(string $jwt) {
$tks = \explode('.', $jwt);
if (\count($tks) !== 3) {
throw new \UnexpectedValueException('Wrong number of segments');
}
list($headb64) = $tks;
if (null === ($header = self::jsonDecode(self::urlsafeB64Decode($headb64)))
) {
throw new \UnexpectedValueException('Invalid segment encoding');
}
return $header;
}
/**
* @param object|array $payload PHP object or array
* @param string $key The secret key
* @param string $algo The signing algorithm
* @param array $additionalHeaders Additional keys/values to add to the header
*
* @return string A JWT
*/
public static function encode($payload, string $key, string $algo = 'HS256', array $additionalHeaders = []): string {
$header = ['typ' => 'JWT', 'alg' => $algo];
$header += $additionalHeaders;
$segments = [];
$segments[] = self::urlsafeB64Encode(self::jsonEncode($header));
$segments[] = self::urlsafeB64Encode(self::jsonEncode($payload));
$signing_input = \implode('.', $segments);
$signature = self::sign($signing_input, $key, $algo);
$segments[] = self::urlsafeB64Encode($signature);
return \implode('.', $segments);
}
/**
* @param string $msg The message to sign
* @param string $key The secret key
* @param string $method The signing algorithm
* @return string An encrypted message
* @throws \DomainException
*/
public static function sign(string $msg, string $key, string $method = 'HS256'): string {
$methods = [
'HS256' => 'sha256',
'HS384' => 'sha384',
'HS512' => 'sha512',
];
if (empty($methods[$method])) {
throw new \DomainException('Algorithm not supported');
}
return \hash_hmac($methods[$method], $msg, $key, true);
}
/**
* @param string $input JSON string
* @return object Object representation of JSON string
* @throws \DomainException
*/
public static function jsonDecode(string $input) {
$obj = \json_decode($input);
if (\function_exists('json_last_error') && $errno = \json_last_error()) {
self::handleJsonError($errno);
} else if ($obj === null && $input !== 'null') {
throw new \DomainException('Null result with non-null input');
}
return $obj;
}
/**
* @param object|array $input A PHP object or array
* @return string JSON representation of the PHP object or array
* @throws \DomainException
*/
public static function jsonEncode($input): string {
$json = \json_encode($input);
if (\function_exists('json_last_error') && $errno = \json_last_error()) {
self::handleJsonError($errno);
} else if ($json === 'null' && $input !== null) {
throw new \DomainException('Null result with non-null input');
}
return $json;
}
/**
* @param string $input A base64 encoded string
*
* @return string A decoded string
*/
public static function urlsafeB64Decode(string $input): string {
$padLen = 4 - \strlen($input) % 4;
$input .= \str_repeat('=', $padLen);
return \base64_decode(\strtr($input, '-_', '+/'));
}
/**
* @param string $input Anything really
*
* @return string The base64 encode of what you passed in
*/
public static function urlsafeB64Encode(string $input): string {
return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
}
/**
* @param int $errno An error number from json_last_error()
*
* @throws \DomainException
*/
private static function handleJsonError(int $errno): void {
$messages = [
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
];
throw new \DomainException($messages[$errno] ?? 'Unknown JSON error: ' . $errno);
}
}

View File

@@ -0,0 +1,161 @@
<?php
namespace Twilio\Jwt\TaskRouter;
use Twilio\Jwt\JWT;
/**
* Twilio TaskRouter Capability assigner
*
* @author Justin Witz <justin.witz@twilio.com>
* @license http://creativecommons.org/licenses/MIT/ MIT
*/
class CapabilityToken {
protected $accountSid;
protected $authToken;
private $friendlyName;
/** @var Policy[] $policies */
private $policies;
protected $baseUrl = 'https://taskrouter.twilio.com/v1';
protected $baseWsUrl = 'https://event-bridge.twilio.com/v1/wschannels';
protected $version = 'v1';
protected $workspaceSid;
protected $channelId;
protected $resourceUrl;
protected $required = ['required' => true];
protected $optional = ['required' => false];
public function __construct(string $accountSid, string $authToken, string $workspaceSid, string $channelId,
?string $resourceUrl = null, ?string $overrideBaseUrl = null, ?string $overrideBaseWSUrl = null) {
$this->accountSid = $accountSid;
$this->authToken = $authToken;
$this->friendlyName = $channelId;
$this->policies = [];
$this->workspaceSid = $workspaceSid;
$this->channelId = $channelId;
if (isset($overrideBaseUrl)) {
$this->baseUrl = $overrideBaseUrl;
}
if (isset($overrideBaseWSUrl)) {
$this->baseWsUrl = $overrideBaseWSUrl;
}
$this->baseUrl .= '/Workspaces/' . $workspaceSid;
$this->validateJWT();
if (!isset($resourceUrl)) {
$this->setupResource();
}
//add permissions to GET and POST to the event-bridge channel
$this->allow($this->baseWsUrl . '/' . $this->accountSid . '/' . $this->channelId, 'GET', null, null);
$this->allow($this->baseWsUrl . '/' . $this->accountSid . '/' . $this->channelId, 'POST', null, null);
//add permissions to fetch the instance resource
$this->allow($this->resourceUrl, 'GET', null, null);
}
protected function setupResource(): void {
}
public function addPolicyDeconstructed(string $url, string $method, ?array $queryFilter = [], ?array $postFilter = [], bool $allow = true): Policy {
$policy = new Policy($url, $method, $queryFilter, $postFilter, $allow);
$this->policies[] = $policy;
return $policy;
}
public function allow(string $url, string $method, ?array $queryFilter = [], ?array $postFilter = []): void {
$this->addPolicyDeconstructed($url, $method, $queryFilter, $postFilter, true);
}
public function deny(string $url, string $method, array $queryFilter = [], array $postFilter = []): void {
$this->addPolicyDeconstructed($url, $method, $queryFilter, $postFilter, false);
}
private function validateJWT(): void {
if (!isset($this->accountSid) || \strpos($this->accountSid, 'AC') !== 0) {
throw new \Exception('Invalid AccountSid provided: ' . $this->accountSid);
}
if (!isset($this->workspaceSid) || \strpos($this->workspaceSid, 'WS') !== 0) {
throw new \Exception('Invalid WorkspaceSid provided: ' . $this->workspaceSid);
}
if (!isset($this->channelId)) {
throw new \Exception('ChannelId not provided');
}
$prefix = \substr($this->channelId, 0, 2);
if ($prefix !== 'WS' && $prefix !== 'WK' && $prefix !== 'WQ') {
throw new \Exception("Invalid ChannelId provided: " . $this->channelId);
}
}
public function allowFetchSubresources(): void {
$method = 'GET';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl . '/**', $method, $queryFilter, $postFilter);
}
public function allowUpdates(): void {
$method = 'POST';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl, $method, $queryFilter, $postFilter);
}
public function allowUpdatesSubresources(): void {
$method = 'POST';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl . '/**', $method, $queryFilter, $postFilter);
}
public function allowDelete(): void {
$method = 'DELETE';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl, $method, $queryFilter, $postFilter);
}
public function allowDeleteSubresources(): void {
$method = 'DELETE';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl . '/**', $method, $queryFilter, $postFilter);
}
public function generateToken(int $ttl = 3600, array $extraAttributes = []): string {
$payload = [
'version' => $this->version,
'friendly_name' => $this->friendlyName,
'iss' => $this->accountSid,
'exp' => \time() + $ttl,
'account_sid' => $this->accountSid,
'channel' => $this->channelId,
'workspace_sid' => $this->workspaceSid
];
if (\strpos($this->channelId, 'WK') === 0) {
$payload['worker_sid'] = $this->channelId;
} else if (\strpos($this->channelId, 'WQ') === 0) {
$payload['taskqueue_sid'] = $this->channelId;
}
foreach ($extraAttributes as $key => $value) {
$payload[$key] = $value;
}
$policyStrings = [];
foreach ($this->policies as $policy) {
$policyStrings[] = $policy->toArray();
}
$payload['policies'] = $policyStrings;
return JWT::encode($payload, $this->authToken, 'HS256');
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Twilio\Jwt\TaskRouter;
/**
* Twilio API Policy constructor
*
* @author Justin Witz <justin.witz@twilio.com>
* @license http://creativecommons.org/licenses/MIT/ MIT
*/
class Policy {
private $url;
private $method;
private $queryFilter;
private $postFilter;
private $allow;
public function __construct(string $url, string $method, ?array $queryFilter = [], ?array $postFilter = [], bool $allow = true) {
$this->url = $url;
$this->method = $method;
$this->queryFilter = $queryFilter;
$this->postFilter = $postFilter;
$this->allow = $allow;
}
public function addQueryFilter($queryFilter): void {
$this->queryFilter[] = $queryFilter;
}
public function addPostFilter($postFilter): void {
$this->postFilter[] = $postFilter;
}
public function toArray(): array {
$policy_array = ['url' => $this->url, 'method' => $this->method, 'allow' => $this->allow];
if ($this->queryFilter !== null) {
if (\count($this->queryFilter) > 0) {
$policy_array['query_filter'] = $this->queryFilter;
} else {
$policy_array['query_filter'] = new \stdClass();
}
}
if ($this->postFilter !== null) {
if (\count($this->postFilter) > 0) {
$policy_array['post_filter'] = $this->postFilter;
} else {
$policy_array['post_filter'] = new \stdClass();
}
}
return $policy_array;
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace Twilio\Jwt\TaskRouter;
/**
* Twilio TaskRouter TaskQueue Capability assigner
*
* @author Justin Witz <justin.witz@twilio.com>
* @license http://creativecommons.org/licenses/MIT/ MIT
*/
class TaskQueueCapability extends CapabilityToken {
public function __construct(string $accountSid, string $authToken, string $workspaceSid, string $taskQueueSid,
?string $overrideBaseUrl = null, ?string $overrideBaseWSUrl = null) {
parent::__construct($accountSid, $authToken, $workspaceSid, $taskQueueSid, null, $overrideBaseUrl, $overrideBaseWSUrl);
}
protected function setupResource(): void {
$this->resourceUrl = $this->baseUrl . '/TaskQueues/' . $this->channelId;
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace Twilio\Jwt\TaskRouter;
/**
* Twilio TaskRouter Worker Capability assigner
*
* @author Justin Witz <justin.witz@twilio.com>
* @license http://creativecommons.org/licenses/MIT/ MIT
*/
class WorkerCapability extends CapabilityToken {
private $tasksUrl;
private $workerReservationsUrl;
private $activityUrl;
public function __construct(string $accountSid, string $authToken, string $workspaceSid, string $workerSid,
?string $overrideBaseUrl = null, ?string $overrideBaseWSUrl = null) {
parent::__construct($accountSid, $authToken, $workspaceSid, $workerSid, null, $overrideBaseUrl, $overrideBaseWSUrl);
$this->tasksUrl = $this->baseUrl . '/Tasks/**';
$this->activityUrl = $this->baseUrl . '/Activities';
$this->workerReservationsUrl = $this->resourceUrl . '/Reservations/**';
//add permissions to fetch the list of activities, tasks, and worker reservations
$this->allow($this->activityUrl, 'GET', null, null);
$this->allow($this->tasksUrl, 'GET', null, null);
$this->allow($this->workerReservationsUrl, 'GET', null, null);
}
protected function setupResource(): void {
$this->resourceUrl = $this->baseUrl . '/Workers/' . $this->channelId;
}
public function allowActivityUpdates(): void {
$method = 'POST';
$queryFilter = [];
$postFilter = ['ActivitySid' => $this->required];
$this->allow($this->resourceUrl, $method, $queryFilter, $postFilter);
}
public function allowReservationUpdates(): void {
$method = 'POST';
$queryFilter = [];
$postFilter = [];
$this->allow($this->tasksUrl, $method, $queryFilter, $postFilter);
$this->allow($this->workerReservationsUrl, $method, $queryFilter, $postFilter);
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Twilio\Jwt\TaskRouter;
class WorkspaceCapability extends CapabilityToken {
public function __construct(string $accountSid, string $authToken, string $workspaceSid,
?string $overrideBaseUrl = null, ?string $overrideBaseWSUrl = null) {
parent::__construct($accountSid, $authToken, $workspaceSid, $workspaceSid, null, $overrideBaseUrl, $overrideBaseWSUrl);
}
protected function setupResource(): void {
$this->resourceUrl = $this->baseUrl;
}
}