Files

4884 lines
183 KiB
PHP

<?php
namespace Paymenter\Extensions\Servers\PterodactylSSO;
use App\Classes\Extension\Server;
use App\Mail\SystemMail;
use App\Models\ConfigOption as ConfigOptionModel;
use App\Models\DebugLog;
use App\Models\EmailLog;
use App\Models\Product;
use App\Models\Property;
use App\Models\Service;
use Carbon\Carbon;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Pool;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\Response;
use Illuminate\Http\RedirectResponse;
use Illuminate\Mail\Events\MessageSent;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\View;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
// Only edit if you know what you are doing
// Made by Cloee
// Version v2.4
/**
* Class PterodactylSSO
* Enhanced Pterodactyl extension with Single Sign-On functionality
*/
class PterodactylSSO extends Server
{
private const RATE_LIMIT_DEFAULT_MAX_ATTEMPTS = 240;
private const RATE_LIMIT_DECAY_SECONDS = 60;
private const RATE_LIMIT_DEFAULT_RETRY_AFTER = 60;
private const RATE_LIMIT_INLINE_WAIT_SECONDS = 5;
private const SERVER_LOOKUP_MAX_ATTEMPTS = 3;
private const SERVER_LOOKUP_RETRY_DELAY_MS = 500;
private const CARD_SERVER_CACHE_SECONDS = 300;
private const CARD_RESOURCES_CACHE_SECONDS = 20;
private const CARD_POOL_CONCURRENCY = 10;
private const CLIENT_API_USER_AGENT = 'Paymenter-PterodactylSSO/2.0';
private static bool $serverNameGuardRegistered = false;
private static bool $navigationRegistered = false;
private static bool $viewNamespaceRegistered = false;
private static bool $langNamespaceRegistered = false;
private static bool $emailStatusListenersRegistered = false;
protected string $viewDirectory = __DIR__ . '/resources/views';
protected string $langDirectory = __DIR__ . '/resources/lang';
public function __construct($config = [])
{
parent::__construct($config);
if (!self::$serverNameGuardRegistered) {
Property::saving(function (Property $property): void {
if ($property->key !== 'server_name') {
return;
}
$rawValue = $property->value;
if ($rawValue !== null && trim((string) $rawValue) !== '') {
return;
}
$model = $property->model;
if (!$model instanceof Service) {
return;
}
$server = $model->product?->server;
if (!$server || $server->extension !== class_basename(static::class)) {
return;
}
$property->name = $property->name ?? 'Server Name';
$property->value = ($model->product?->name ?? 'Server') . ' #' . $model->id;
});
self::$serverNameGuardRegistered = true;
}
if (!self::$viewNamespaceRegistered) {
View::addNamespace('pterodactyl-sso', $this->viewDirectory);
self::$viewNamespaceRegistered = true;
}
if (!self::$langNamespaceRegistered) {
Lang::addNamespace('pterodactyl-sso', $this->langDirectory);
self::$langNamespaceRegistered = true;
}
}
public function boot(): void
{
// Listeners first: boot() runs with mayFail=true on some code
// paths, so a failure below (e.g. routes) must never silently
// disable mail status tracking and strand logs on pending.
$this->registerEmailStatusListeners();
if (file_exists(__DIR__ . '/routes.php')) {
require_once __DIR__ . '/routes.php';
}
$this->registerClientNavigation();
}
/**
* Surface the "My Servers" overview in the client dashboard sidebar.
*
* The link is only added when the signed-in user actually owns a
* service backed by this extension, so unrelated accounts never see a
* dead entry.
*/
private function registerClientNavigation(): void
{
if (self::$navigationRegistered) {
return;
}
self::$navigationRegistered = true;
Event::listen('navigation.dashboard', function () {
$user = Auth::user();
if (!$user) {
return [];
}
$hasServers = Service::query()
->where('user_id', $user->id)
->whereHas('product.server', fn ($query) => $query->where('extension', class_basename(static::class)))
->exists();
if (!$hasServers) {
return [];
}
return [[
'name' => $this->trans('servers.nav'),
'route' => 'services.pterodactyl.servers',
'icon' => 'ri-server',
'priority' => 15,
]];
});
}
public function installed(): void
{
$this->restartQueueWorkers();
}
public function enabled($extension = null): void
{
$this->restartQueueWorkers();
}
public function upgraded($oldVersion = null): void
{
$this->restartQueueWorkers();
}
/**
* Signal long-running queue workers to restart.
*
* Workers boot the extension (and its SystemMail queue listeners) only
* once at startup. Without a restart after install/enable/upgrade, stale
* workers keep processing our mails without the listeners, leaving
* EmailLog rows stuck on pending/failed-unresolved.
*/
private function restartQueueWorkers(): void
{
try {
Artisan::call('queue:restart');
} catch (\Throwable $e) {
$this->logMessage('warning', 'PterodactylSSO failed to restart queue workers', [
'error' => $e->getMessage(),
], true);
}
}
/**
* Resolve the EmailLog id for a queued SystemMail job.
*
* Paymenter's core queue listeners (AppServiceProvider) only track
* `App\Mail\Mail` jobs, so queued `App\Mail\SystemMail` jobs would stay
* `pending` in the email logs forever. These listeners fill that gap for
* mails dispatched by this extension (user_id is set on our logs).
*
* Two independent signals are used so no single framework behavior can
* strand a log: MessageSent fires in whichever process actually hands
* the message to the mail transport (any queue driver, any Laravel
* version, no payload parsing), while Queue::after/failing cover the
* job lifecycle as a backup. All updates are idempotent.
*/
private function registerEmailStatusListeners(): void
{
if (self::$emailStatusListenersRegistered) {
return;
}
self::$emailStatusListenersRegistered = true;
Event::listen(MessageSent::class, function (MessageSent $event) {
$emailLogId = $event->data['email_log_id'] ?? null;
if (!is_numeric($emailLogId)) {
return;
}
EmailLog::where('id', (int) $emailLogId)->update([
'sent_at' => now(),
'status' => 'sent',
]);
});
Queue::after(function (JobProcessed $event) {
$emailLogId = self::resolveQueuedSystemMailLogId($event->job);
if ($emailLogId === null) {
return;
}
EmailLog::where('id', $emailLogId)->update([
'sent_at' => now(),
'status' => 'sent',
]);
});
Queue::failing(function (JobFailed $event) {
$emailLogId = self::resolveQueuedSystemMailLogId($event->job);
if ($emailLogId === null) {
return;
}
EmailLog::where('id', $emailLogId)->update([
'status' => 'failed',
'error' => $event->exception->getMessage(),
'job_uuid' => $event->job->uuid(),
]);
});
}
private static function resolveQueuedSystemMailLogId(mixed $job): ?int
{
try {
if (!is_object($job) || !method_exists($job, 'resolveName') || !method_exists($job, 'getRawBody')) {
return null;
}
if ($job->resolveName() !== SystemMail::class) {
return null;
}
$payload = json_decode((string) $job->getRawBody());
if (!isset($payload->data->command)) {
return null;
}
$command = unserialize($payload->data->command);
if (!is_object($command)) {
return null;
}
// Canonical shape: SendQueuedMailable wrapping the mailable.
$emailLogId = $command->mailable->email_log_id ?? null;
// Fallback: the command itself carrying the id (unconventional
// dispatch or a future framework payload layout).
if ($emailLogId === null) {
$emailLogId = $command->email_log_id ?? null;
}
return is_numeric($emailLogId) ? (int) $emailLogId : null;
} catch (\Throwable) {
return null;
}
}
private function renderView(string $template, array $data = []): string
{
$view = 'pterodactyl-sso::' . str_replace(['/', '\\'], '.', $template);
return View::make($view, $data)->render();
}
private function trans(string $key, array $replace = []): string
{
return (string) __("pterodactyl-sso::messages.{$key}", $replace);
}
private function logMessage(string $level, string $message, array $context = [], bool $force = false): void
{
$level = strtolower($level);
$alwaysLog = ['emergency', 'alert', 'critical', 'error'];
if (isset($context['service_id'])) {
$message = "[Service: {$context['service_id']}] " . $message;
}
if ($force || in_array($level, $alwaysLog, true)) {
Log::log($level, $message, $context);
return;
}
if ($this->shouldLogVerbose()) {
Log::log($level, $message, $context);
}
}
private function shouldLogVerbose(): bool
{
return (bool) $this->config('verbose_logging');
}
private function configBool(string $key, bool $default = false): bool
{
$value = $this->config($key);
if ($value === null) {
return $default;
}
if (is_bool($value)) {
return $value;
}
if (is_numeric($value)) {
return (bool) $value;
}
return filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? $default;
}
private function purgeStoredPassword(Service $service): void
{
$service->properties()->where('key', 'current_password')->delete();
}
private function decryptStoredPassword(Service $service): ?string
{
$passwordProperty = $service->properties()->where('key', 'current_password')->first();
if (!$passwordProperty || !$passwordProperty->value) {
return null;
}
// Return the stored value as-is. Reading must never destroy it:
// purging here (and previously returning null unconditionally) made
// the reveal-password flow always show "missing" and silently wiped
// any legacy stored value on first view.
return (string) $passwordProperty->value;
}
private function passwordPreview(string $password): string
{
$length = strlen($password);
if ($length <= 1) {
return str_repeat('•', $length);
}
$start = substr($password, 0, 1);
return $start . str_repeat('•', max($length - 1, 0));
}
private function resolveServerMetadata(Service $service): array
{
$serviceProperties = $service->properties()->pluck('value', 'key')->toArray();
$serverName = $serviceProperties['server_name'] ?? null;
$serverIdentifier = $this->normalizeServerIdentifier($serviceProperties['server_identifier'] ?? null);
if (!$serverName || !$serverIdentifier) {
try {
$server = $this->getServer($service->id, raw: true);
if ($server && isset($server['attributes'])) {
$serverName = $serverName ?? $server['attributes']['name'];
$serverIdentifier = $serverIdentifier ?? $this->normalizeServerIdentifier($server['attributes']['identifier'] ?? null);
}
} catch (\Exception $e) {
// Display-only fallback for the name. The identifier MUST stay
// null here: it is used to build panel API URLs, and a
// placeholder like 'Unknown' would be sent to the panel as a
// real server identifier (404 spam in HTTP logs).
$serverName = $serverName ?? 'Unknown Server';
}
}
return [
'serverName' => $serverName,
'serverIdentifier' => $serverIdentifier,
'panelUrl' => $this->config('host'),
];
}
/**
* Normalize a panel server identifier.
*
* Older runs could persist the literal display placeholder 'Unknown' as
* the stored server_identifier property (or it arrives from a failed
* lookup). That value is truthy, so without this guard it sails through
* every `if (!$identifier)` check and gets used in API URLs verbatim.
*/
private function normalizeServerIdentifier(mixed $identifier): ?string
{
if (!is_string($identifier)) {
return null;
}
$identifier = trim($identifier);
if ($identifier === '' || strcasecmp($identifier, 'unknown') === 0) {
return null;
}
return $identifier;
}
/**
* Whether a panel error means the stored server is gone.
*
* When the panel 404s a stored identifier (deleted/recreated server),
* callers surface the same recoverable "not linked" state as a missing
* identifier instead of leaking panel 404 text to the UI.
*/
private function isPanelServerMissing(\Exception $e): bool
{
return (int) $e->getCode() === 404 || $this->isServerNotFoundException($e);
}
private function sendSecurityMail(Service $service, string $type, array $meta = []): void
{
if (!$this->shouldSendSecurityMail($type)) {
return;
}
$userEmail = $service->properties()->where('key', 'user_email')->value('value')
?? $service->user?->email
?? null;
if (!$userEmail) {
return;
}
$ip = request()?->ip() ?? 'Unknown';
$timestamp = now()->toDayDateTimeString();
$metadata = $this->resolveServerMetadata($service);
$typeKey = in_array($type, ['sso', 'reveal', 'generated'], true) ? $type : 'default';
$subject = $this->trans("security_mail.types.{$typeKey}.subject");
$title = $this->trans("security_mail.types.{$typeKey}.title");
$intro = $this->trans("security_mail.types.{$typeKey}.intro");
$unknown = $this->trans('common.unknown');
$notAvailable = $this->trans('common.not_available');
$labels = [
'server_name' => $this->trans('security_mail.labels.server_name'),
'server_identifier' => $this->trans('security_mail.labels.server_identifier'),
'user_id' => $this->trans('security_mail.labels.user_id'),
'password_preview' => $this->trans('security_mail.labels.password_preview'),
'ip_address' => $this->trans('security_mail.labels.ip_address'),
'time' => $this->trans('security_mail.labels.time'),
'panel_url' => $this->trans('security_mail.labels.panel_url'),
];
$details = [
$labels['server_identifier'] => $metadata['serverIdentifier'] ?? $unknown,
$labels['ip_address'] => $ip,
$labels['time'] => $timestamp,
];
if ($typeKey === 'sso') {
$details = [
$labels['server_identifier'] => $metadata['serverIdentifier'] ?? $unknown,
$labels['user_id'] => $meta['user_id'] ?? $unknown,
$labels['ip_address'] => $ip,
$labels['time'] => $timestamp,
];
}
if (in_array($typeKey, ['reveal', 'generated'], true)) {
$details = [
$labels['server_identifier'] => $metadata['serverIdentifier'] ?? $unknown,
$labels['password_preview'] => $meta['password_preview'] ?? $notAvailable,
$labels['ip_address'] => $ip,
$labels['time'] => $timestamp,
];
}
$details[$labels['panel_url']] = $metadata['panelUrl'] ?? $this->config('host');
if ($this->configBool('security_email_include_server_name', true) && !empty($metadata['serverName'])) {
$details = [$labels['server_name'] => $metadata['serverName']] + $details;
}
$details = collect($details)
->filter(fn ($value) => $value !== null && $value !== '')
->mapWithKeys(fn ($value, $label) => [
$this->escapeMarkdownTableCell($label) => $this->escapeMarkdownTableCell($value),
])
->all();
$body = $this->renderView($this->securityMailView($typeKey), [
'title' => $title,
'intro' => $intro,
'details' => $details,
]);
$emailLog = null;
try {
$mail = new SystemMail([
'subject' => $subject,
'body' => $body,
]);
$emailLog = EmailLog::create([
'user_id' => $service->user_id,
'subject' => $subject,
'to' => $userEmail,
'body' => $mail->render(),
]);
$mail->email_log_id = $emailLog->id;
// Queue the mail like App\Helpers\NotificationHelper does. The
// pending -> sent/failed transition is handled by the
// Queue::after / Queue::failing listeners registered in boot().
// Core only tracks App\Mail\Mail jobs, which is why SystemMail
// needs its own listeners — without them these logs stay
// `pending` forever. Queuing also keeps slow SMTP servers from
// blocking (or killing) the web request, which likewise left
// pending rows behind when the process died mid-send.
Mail::to($userEmail)->queue($mail);
} catch (\Throwable $e) {
// Dispatching to the queue failed (e.g. queue backend down), so
// no worker will ever resolve this log. Mark it failed right
// away instead of leaving it stuck on pending.
try {
$emailLog?->update([
'status' => 'failed',
'error' => $e->getMessage(),
]);
} catch (\Throwable) {
// Best effort: the original error is logged below.
}
$this->logMessage('error', 'PterodactylSSO security mail failed', [
'service_id' => $service->id,
'email' => $userEmail,
'type' => $type,
'error' => $e->getMessage(),
], true);
}
}
private function escapeMarkdownTableCell(mixed $value): string
{
$value = trim((string) $value);
return str_replace(['\\', '|', "\r", "\n"], ['\\\\', '\|', ' ', ' '], $value);
}
private function securityMailView(string $type): string
{
return match ($type) {
'sso' => 'mail.security.auto-login',
'reveal' => 'mail.security.password-revealed',
'generated' => 'mail.security.password-generated',
default => 'mail.security-alert',
};
}
private function shouldSendSecurityMail(string $type): bool
{
if (config('settings.mail_disable')) {
return false;
}
if (!$this->configBool('security_email_enable', true)) {
return false;
}
$map = [
'sso' => 'security_email_auto_login',
'reveal' => 'security_email_reveal_password',
'generated' => 'security_email_generate_password',
];
$key = $map[$type] ?? null;
if ($key === null) {
return true;
}
return $this->configBool($key, true);
}
public function getConfig($values = []): array
{
return [
[
'name' => 'host',
'label' => $this->trans('config.host_label'),
'type' => 'text',
'description' => $this->trans('config.host_description'),
'required' => true,
'validation' => 'url',
], // e1ef11cd010cb5c2e5418e68a0407571
[
'name' => 'api_key',
'label' => $this->trans('config.api_key_label'),
'type' => 'text',
'description' => $this->trans('config.api_key_description'),
'required' => true,
'encrypted' => true,
],
[
'name' => 'client_api_key',
'label' => $this->trans('config.client_api_key_label'),
'type' => 'text',
'description' => $this->trans('config.client_api_key_description'),
'required' => false,
'encrypted' => true,
],
[
'name' => 'overview_refresh_seconds',
'label' => $this->trans('config.overview_refresh_seconds_label'),
'type' => 'number',
'description' => $this->trans('config.overview_refresh_seconds_description'),
'required' => false,
'default' => 30,
'min_value' => 5,
],
[
'name' => 'sso_secret',
'label' => $this->trans('config.sso_secret_label'),
'type' => 'text',
'description' => $this->trans('config.sso_secret_description'),
'required' => false,
'encrypted' => true,
],
[
'name' => 'sso_endpoint',
'label' => $this->trans('config.sso_endpoint_label'),
'type' => 'text',
'description' => $this->trans('config.sso_endpoint_description'),
'required' => false,
'default' => '/sso-wemx',
],
[
'name' => 'verbose_logging',
'label' => $this->trans('config.verbose_logging_label'),
'type' => 'checkbox',
'description' => $this->trans('config.verbose_logging_description'),
'required' => false,
'default' => false,
],
[
'name' => 'allow_custom_server_name',
'label' => $this->trans('config.allow_custom_server_name_label'),
'type' => 'checkbox',
'description' => $this->trans('config.allow_custom_server_name_description'),
'required' => false,
'default' => true,
],
[
'name' => 'security_email_enable',
'label' => $this->trans('config.security_email_enable_label'),
'type' => 'checkbox',
'description' => $this->trans('config.security_email_enable_description'),
'required' => false,
'default' => true,
],
[
'name' => 'security_email_auto_login',
'label' => $this->trans('config.security_email_auto_login_label'),
'type' => 'checkbox',
'description' => $this->trans('config.security_email_auto_login_description'),
'required' => false,
'default' => true,
],
[
'name' => 'security_email_reveal_password',
'label' => $this->trans('config.security_email_reveal_password_label'),
'type' => 'checkbox',
'description' => $this->trans('config.security_email_reveal_password_description'),
'required' => false,
'default' => true,
],
[
'name' => 'security_email_generate_password',
'label' => $this->trans('config.security_email_generate_password_label'),
'type' => 'checkbox',
'description' => $this->trans('config.security_email_generate_password_description'),
'required' => false,
'default' => true,
],
[
'name' => 'security_email_include_server_name',
'label' => $this->trans('config.security_email_include_server_name_label'),
'type' => 'checkbox',
'description' => $this->trans('config.security_email_include_server_name_description'),
'required' => false,
'default' => true,
],
[
'name' => 'global_server_name_template',
'label' => $this->trans('config.global_server_name_template_label'),
'type' => 'text',
'description' => $this->trans('config.global_server_name_template_description'),
'required' => false,
'default' => '{product_name} #{id}',
],
[
'name' => 'global_server_description_template',
'label' => $this->trans('config.global_server_description_template_label'),
'type' => 'text',
'description' => $this->trans('config.global_server_description_template_description'),
'required' => false,
],
];
}
public function testConfig(): bool|string
{
try {
$this->request('/api/application/servers', 'GET');
} catch (\Exception $e) {
return $e->getMessage();
}
return true;
}
/**
* Get the checkout configuration for the product.
*
* @param Product $product The product that is being checked out.
* @param array $values The values that are provided by the user.
* @param array $settings The settings that are provided on the product from `getProductConfig`.
*/
public function getCheckoutConfig($product = null, $values = [], $settings = []): array
{
if (!$this->configBool('allow_custom_server_name', true)) {
return [];
}
$existing = data_get($values, 'server_name');
$option = tap(new ConfigOptionModel, function (ConfigOptionModel $option) use ($existing) {
$option->forceFill([
'id' => 'server_name',
'name' => 'server_name',
'type' => 'text',
'env_variable' => 'server_name',
]);
$option->label = $this->trans('checkout.server_name_label');
$option->required = false;
$option->description = $this->trans('checkout.server_name_description');
$option->placeholder = $this->trans('checkout.server_name_placeholder');
$option->default = is_string($existing) ? $existing : '';
$option->validation = [
'nullable',
'max:255',
function (string $attribute, $value, \Closure $fail): void {
if ($value === null) {
return;
}
if (!is_string($value)) {
$fail($this->trans('checkout.server_name_type_error', [
'attribute' => $this->trans('checkout.server_name_label'),
]));
return;
}
if (trim($value) === '') {
return;
}
},
];
$option->setRelation('children', collect());
});
return [$option];
}
/**
* Check and respect the rate limit for a specific API Key.
*
* @throws \Exception
*/
private function respectRateLimit(string $apiKey, string $bucket): void
{
$localKey = $this->rateLimitKey($apiKey, $bucket, 'local');
$delay = $this->currentRateLimitDelay($apiKey, $bucket);
if ($delay !== null && $delay > 0) {
if ($delay <= self::RATE_LIMIT_INLINE_WAIT_SECONDS) {
sleep($delay);
} else {
throw new \Exception("Rate limit cooldown active for {$bucket} key. Retry in {$delay} seconds.", 429);
}
}
if (RateLimiter::tooManyAttempts($localKey, self::RATE_LIMIT_DEFAULT_MAX_ATTEMPTS)) {
$seconds = max(1, RateLimiter::availableIn($localKey));
$this->markRateLimited($apiKey, $bucket, $seconds);
if ($seconds <= self::RATE_LIMIT_INLINE_WAIT_SECONDS) {
sleep($seconds);
} else {
throw new \Exception("Local rate limit exceeded for {$bucket} key. Retry in {$seconds} seconds.", 429);
}
}
RateLimiter::hit($localKey, self::RATE_LIMIT_DECAY_SECONDS);
}
private function syncRateLimitHeaders(string $apiKey, string $bucket, Response $response, string $requestId, int $keyIndex): ?int
{
$limit = $this->nullableIntHeader($response, 'X-RateLimit-Limit');
$remaining = $this->nullableIntHeader($response, 'X-RateLimit-Remaining');
$resetHeader = $response->header('X-RateLimit-Reset');
$retryAfterHeader = $response->header('Retry-After');
$retryAfter = null;
if ($response->status() === 429) {
$retryAfter = $this->rateLimitDelayFromHeaders($retryAfterHeader, $resetHeader);
$this->markRateLimited($apiKey, $bucket, $retryAfter);
} elseif ($remaining !== null && $remaining <= 0 && $resetHeader) {
$retryAfter = $this->rateLimitDelayFromHeaders(null, $resetHeader);
$this->markRateLimited($apiKey, $bucket, $retryAfter);
}
if ($this->shouldLogVerbose() && ($limit !== null || $remaining !== null || $resetHeader !== null)) {
$this->logMessage('debug', 'PterodactylSSO rate limit headers received', [
'request_id' => $requestId,
'bucket' => $bucket,
'key_index' => $keyIndex,
'limit' => $limit,
'remaining' => $remaining,
'reset' => $resetHeader,
'retry_after' => $retryAfter,
]);
}
return $retryAfter;
}
private function nullableIntHeader(Response $response, string $header): ?int
{
$value = $response->header($header);
if ($value === null || $value === '') {
return null;
}
return is_numeric($value) ? (int) $value : null;
}
private function rateLimitDelayFromHeaders(?string $retryAfter, ?string $reset): int
{
$delay = $this->rateLimitDelayFromHeader($retryAfter, true)
?? $this->rateLimitDelayFromHeader($reset, false)
?? self::RATE_LIMIT_DEFAULT_RETRY_AFTER;
return max(1, min(3600, $delay));
}
private function rateLimitDelayFromHeader(?string $value, bool $isRetryAfter): ?int
{
if ($value === null || trim($value) === '') {
return null;
}
$value = trim($value);
if (is_numeric($value)) {
$numeric = (int) $value;
if (!$isRetryAfter || $numeric > 1000000000) {
return max(1, $numeric - time());
}
return max(1, $numeric);
}
$timestamp = strtotime($value);
return $timestamp ? max(1, $timestamp - time()) : null;
}
private function rateLimitInlineWaitSeconds(): int
{
return self::RATE_LIMIT_INLINE_WAIT_SECONDS;
}
private function markRateLimited(string $apiKey, string $bucket, int $seconds): void
{
$seconds = max(1, $seconds);
Cache::put(
$this->rateLimitKey($apiKey, $bucket, 'blocked_until'),
time() + $seconds,
now()->addSeconds($seconds + 5)
);
}
private function currentRateLimitDelay(string $apiKey, string $bucket): ?int
{
$blockedUntil = Cache::get($this->rateLimitKey($apiKey, $bucket, 'blocked_until'));
if (!$blockedUntil) {
return null;
}
$delay = (int) $blockedUntil - time();
if ($delay <= 0) {
Cache::forget($this->rateLimitKey($apiKey, $bucket, 'blocked_until'));
return null;
}
return $delay;
}
private function shortestCurrentRateLimitDelay(array $apiKeys, string $bucket): ?int
{
$delays = [];
foreach ($apiKeys as $apiKey) {
$delay = $this->currentRateLimitDelay($apiKey, $bucket);
if ($delay !== null) {
$delays[] = $delay;
}
}
return $delays ? min($delays) : null;
}
private function isRateLimitException(\Exception $exception): bool
{
$message = strtolower($exception->getMessage());
return (int) $exception->getCode() === 429
|| str_contains($message, 'rate limit')
|| str_contains($message, '429');
}
private function rateLimitKey(string $apiKey, string $bucket, string $suffix): string
{
$host = (string) $this->config('host');
return 'pterodactyl_sso_rate_' . $suffix . '_' . md5($bucket . '|' . $host . '|' . $apiKey);
}
/**
* Make a request to the Pterodactyl API
*
* @param string $url The API endpoint URL
* @param string $method The HTTP method (get, post, patch, delete)
* @param array $data The data to send with the request
* @return array The response data
*
* @throws \Exception When the request fails
*/
public function request($url, $method = 'get', $data = [], int $rateLimitRetries = 0): array
{
$reqUrl = rtrim($this->config('host'), '/') . $url;
$requestId = (string) Str::uuid();
$method = strtolower((string) $method);
$methodName = strtoupper($method);
$rawKeys = (string) $this->config('api_key');
$apiKeys = array_filter(array_map('trim', explode(',', $rawKeys)));
if (empty($apiKeys)) {
throw new \Exception('No API Key configured.');
}
$lastException = null;
$attempts = 0;
foreach ($apiKeys as $index => $apiKey) {
$attempts++;
$keyMasked = substr($apiKey, 0, 5) . '...';
$this->logMessage('debug', "PterodactylSSO API request initiated (Key #{$index}: {$keyMasked})", [
'request_id' => $requestId,
'method' => $methodName,
'url' => $reqUrl,
'key_index' => $index,
]);
try {
$this->respectRateLimit($apiKey, 'application');
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $apiKey,
'Accept' => 'application/json',
'User-Agent' => self::CLIENT_API_USER_AGENT,
])->connectTimeout(5)
->timeout(15)
->retry(2, 250)
->$method($reqUrl, $data);
$retryAfter = $this->syncRateLimitHeaders($apiKey, 'application', $response, $requestId, $index);
if ($response->status() === 429) {
throw new \Exception("Application API rate limit exceeded. Retry in {$retryAfter} seconds.", 429);
}
// e1ef11cd010cb5c2e5418e68a0407571
if (!$response->successful()) {
$body = $response->json();
$errorMessage = data_get($body, 'errors.0.detail')
?? data_get($body, 'errors.0.code')
?? $response->reason();
$this->logMessage('warning', "PterodactylSSO API request error (Key #{$index})", [
'request_id' => $requestId,
'status' => $response->status(),
'error' => $errorMessage,
]);
if (in_array($response->status(), [401, 403])) {
throw new \Exception("Auth error {$response->status()}: " . $errorMessage, $response->status());
}
throw new \Exception($errorMessage ?: 'Pterodactyl API responded with an error.', $response->status());
}
$this->logMessage('debug', "PterodactylSSO API request success (Key #{$index})", [
'request_id' => $requestId,
'response_status' => $response->status(),
]);
return $response->json() ?? [];
} catch (\Exception $e) {
$isRateLimit = $this->isRateLimitException($e);
$isAuthError = in_array((int) $e->getCode(), [401, 403], true)
|| strpos($e->getMessage(), 'Auth error') !== false;
$shouldRotate = $isRateLimit || $isAuthError;
if (!$shouldRotate) {
$this->logMessage('error', 'PterodactylSSO API request failed (non-rotatable): ' . $e->getMessage(), [
'request_id' => $requestId,
'key_index' => $index,
]);
throw $e;
}
$this->logMessage('warning', "PterodactylSSO Key #{$index} rate limited/auth failed, rotating: " . $e->getMessage(), [
'request_id' => $requestId,
'try_next' => ($attempts < count($apiKeys)),
]);
$lastException = $e;
if ($attempts >= count($apiKeys)) {
break;
}
continue;
}
}
$delay = $this->shortestCurrentRateLimitDelay($apiKeys, 'application');
if ($lastException && $this->isRateLimitException($lastException) && $delay !== null && $delay <= $this->rateLimitInlineWaitSeconds() && $rateLimitRetries < 2) {
$this->logMessage('info', 'PterodactylSSO all application keys are briefly rate limited; waiting before retry', [
'request_id' => $requestId,
'retry_after' => $delay,
'retry_attempt' => $rateLimitRetries + 1,
]);
sleep($delay);
return $this->request($url, $method, $data, $rateLimitRetries + 1);
}
$this->logMessage('error', 'PterodactylSSO API request failed on ALL keys', [
'request_id' => $requestId,
'total_attempts' => $attempts,
]);
throw $lastException ?? new \Exception('Unknown error during API request.');
}
private function requestClient(string $path, string $method = 'get', array $data = [], array $ignoredCodes = [], int $rateLimitRetries = 0): array
{
$rawKeys = (string) $this->config('client_api_key');
$apiKeys = array_filter(array_map('trim', explode(',', $rawKeys)));
if (empty($apiKeys)) {
throw new \Exception('Client API key is not configured.');
}
$normalizedPath = '/' . ltrim($path, '/');
$url = rtrim($this->config('host'), '/') . '/api/client' . $normalizedPath;
$requestId = (string) Str::uuid();
$method = strtolower($method);
$methodName = strtoupper($method);
$lastException = null;
$attempts = 0;
foreach ($apiKeys as $index => $apiKey) {
$attempts++;
$this->logMessage('debug', "PterodactylSSO client API request initiated (Key #{$index})", [
'request_id' => $requestId,
'method' => $methodName,
'url' => $url,
]);
try {
$this->respectRateLimit($apiKey, 'client');
$http = Http::withHeaders([
'Authorization' => 'Bearer ' . $apiKey,
'Accept' => 'Application/vnd.pterodactyl.v1+json',
'Content-Type' => 'application/json',
'User-Agent' => self::CLIENT_API_USER_AGENT,
])->connectTimeout(5)
->timeout(15)
->retry(2, 250);
$response = $method === 'get'
? $http->get($url, $data)
: $http->{$method}($url, $data);
$retryAfter = $this->syncRateLimitHeaders($apiKey, 'client', $response, $requestId, $index);
if ($response->status() === 429) {
throw new \Exception("Client API rate limit exceeded. Retry in {$retryAfter} seconds.", 429);
}
if (!$response->successful() && $response->status() !== 204) {
if (in_array($response->status(), $ignoredCodes)) {
return ['status_code' => $response->status(), '_ignored_error' => true];
}
$body = $response->json();
$errorMessage = data_get($body, 'errors.0.detail')
?? data_get($body, 'errors.0.code')
?? $response->reason();
if (in_array($response->status(), [401, 403])) {
throw new \Exception("Auth error {$response->status()}: " . $errorMessage, $response->status());
}
$this->logMessage('warning', 'PterodactylSSO client API returned error response', [
'request_id' => $requestId,
'method' => $methodName,
'url' => $url,
'status' => $response->status(),
'error' => $errorMessage,
]);
throw new \Exception($errorMessage ?: 'Client API responded with an error.', $response->status());
}
if ($response->status() === 204) {
return [];
}
return $response->json() ?? [];
} catch (\Exception $e) {
if ($e instanceof RequestException
&& $e->response
&& in_array($e->response->status(), $ignoredCodes)) {
return ['status_code' => $e->response->status(), '_ignored_error' => true];
}
$isRateLimit = $this->isRateLimitException($e);
$isAuthError = strpos($e->getMessage(), 'Auth error') !== false;
$shouldRotate = $isRateLimit || $isAuthError;
if (!$shouldRotate) {
$this->logMessage('error', 'PterodactylSSO Client API request failed (non-rotatable): ' . $e->getMessage(), [
'request_id' => $requestId,
'key_index' => $index,
]);
throw $e;
}
$this->logMessage('warning', "PterodactylSSO Client Key #{$index} rate limited/auth failed, rotating: " . $e->getMessage(), [
'request_id' => $requestId,
'try_next' => ($attempts < count($apiKeys)),
]);
$lastException = $e;
if ($attempts >= count($apiKeys)) {
break;
}
continue;
}
}
$delay = $this->shortestCurrentRateLimitDelay($apiKeys, 'client');
if ($lastException && $this->isRateLimitException($lastException) && $delay !== null && $delay <= $this->rateLimitInlineWaitSeconds() && $rateLimitRetries < 2) {
$this->logMessage('info', 'PterodactylSSO all client keys are briefly rate limited; waiting before retry', [
'request_id' => $requestId,
'retry_after' => $delay,
'retry_attempt' => $rateLimitRetries + 1,
]);
sleep($delay);
return $this->requestClient($path, $method, $data, $ignoredCodes, $rateLimitRetries + 1);
}
throw $lastException ?? new \Exception('Unknown error during Client API request.');
}
/**
* Pelican compatibility helpers.
*
* Pelican's application API returns flat resource objects (no
* "attributes" wrapper) while Pterodactyl wraps them. These helpers
* accept either shape and always return the Pterodactyl shape the
* rest of this extension already handles, so a response that already
* has "attributes" passes through untouched.
*/
private function pelicanItem(array $item): array
{
if (isset($item['attributes']) && is_array($item['attributes'])) {
return $item['attributes'];
}
return $item;
}
private function pelicanList(array $response): array
{
$data = $response['data'] ?? $response;
return is_array($data) ? array_values($data) : [];
}
private function pelicanId($item): ?int
{
if (!is_array($item)) {
return null;
}
if (isset($item['attributes']['id'])) {
return (int) $item['attributes']['id'];
}
if (isset($item['data']) && is_array($item['data'])) {
return $this->pelicanId($item['data']);
}
if (isset($item['id'])) {
return (int) $item['id'];
}
return null;
}
private function pelicanEggVariables(array $egg): array
{
$variables = $egg['variables'] ?? null;
if (is_array($variables) && isset($variables['data']) && is_array($variables['data'])) {
$variables = $variables['data'];
}
if (!is_array($variables)) {
$variables = $egg['relationships']['variables']['data'] ?? [];
}
$normalized = [];
foreach ((array) $variables as $variable) {
$attrs = $this->pelicanItem(is_array($variable) ? $variable : []);
if (isset($attrs['env_variable'])) {
$normalized[] = ['attributes' => $attrs];
}
}
return $normalized;
}
private function normalizePelicanEgg(array $response): array
{
$flat = $response['data'] ?? $response;
if (!is_array($flat) || isset($flat['attributes'])) {
return $response;
}
$dockerImage = $flat['docker_image'] ?? null;
if (is_array($dockerImage)) {
$dockerImage = $dockerImage[0] ?? null;
}
if (!is_string($dockerImage) && isset($flat['docker_images']) && is_array($flat['docker_images'])) {
$dockerImage = $flat['docker_images'][0] ?? null;
}
$startup = $flat['startup'] ?? null;
if (is_array($startup)) {
$startup = $startup[0] ?? null;
}
if (!is_string($startup) && isset($flat['startup_commands']) && is_array($flat['startup_commands'])) {
$startup = $flat['startup_commands'][0] ?? null;
}
$flat['docker_image'] = is_string($dockerImage) ? $dockerImage : '';
$flat['startup'] = is_string($startup) ? $startup : '';
$flat['relationships'] = ['variables' => ['data' => $this->pelicanEggVariables($flat)]];
return ['attributes' => $flat];
}
private function normalizePelicanServer(array $response): array
{
if (isset($response['attributes']['id'])) {
return $response;
}
$flat = $response['data'] ?? $response;
if (!is_array($flat) || !isset($flat['id'])) {
return $response;
}
$flat['identifier'] = $flat['identifier'] ?? $flat['uuid'] ?? null;
return ['attributes' => $flat];
}
private function pelicanDeploymentData(array $settings, array $environment): array
{
$nodeId = $settings['node'] ?? null;
if ($nodeId === null || $nodeId === '') {
return [
'auto_deploy' => true,
'environment' => $environment,
'allocations_needed' => 1,
];
}
$node = $this->request('/api/application/nodes/' . $nodeId, data: ['include' => 'allocations']);
$nodeData = $node['data'] ?? $node;
$flatNode = $this->pelicanItem(is_array($nodeData) ? $nodeData : []);
$allocations = $flatNode['allocations'] ?? [];
if (is_array($allocations) && isset($allocations['data']) && is_array($allocations['data'])) {
$allocations = $allocations['data'];
}
$chosen = null;
$fallback = null;
foreach ((array) $allocations as $allocation) {
$flatAlloc = $this->pelicanItem(is_array($allocation) ? $allocation : []);
if (!isset($flatAlloc['id'])) {
continue;
}
if (($flatAlloc['assigned'] ?? null) === false) {
$chosen = $flatAlloc;
break;
}
if ($fallback === null && !array_key_exists('assigned', $flatAlloc)) {
$fallback = $flatAlloc;
}
}
$chosen = $chosen ?? $fallback;
if ($chosen === null) {
// The node view allocations include can come back null when the
// admin ACL for the allocation resource does not cover the
// caller, even when free allocations exist. Fall back to the
// dedicated node-allocations endpoint, which lists the same items.
try {
$allocResponse = $this->request('/api/application/nodes/' . $nodeId . '/allocations', data: ['per_page' => 100]);
$allocList = $this->pelicanList(is_array($allocResponse) ? $allocResponse : []);
foreach ($allocList as $allocation) {
$flatAlloc = $this->pelicanItem(is_array($allocation) ? $allocation : []);
if (!isset($flatAlloc['id'])) {
continue;
}
if (($flatAlloc['assigned'] ?? null) === false) {
$chosen = $flatAlloc;
break;
}
if ($fallback === null && !array_key_exists('assigned', $flatAlloc)) {
$fallback = $flatAlloc;
}
}
$chosen = $chosen ?? $fallback;
} catch (\Throwable $e) {
// Keep the original no-free-allocations error below.
}
}
if ($chosen === null) {
throw new \Exception('No free allocations available on the selected node.');
}
$environment['SERVER_PORT'] = (string) $chosen['port'];
return [
'auto_deploy' => false,
'environment' => $environment,
'allocations_needed' => 1,
'allocation' => [
'default' => $chosen['id'],
'additional' => [],
],
];
}
public function getProductConfig($values = []): array
{
// Include the panel host so cached option lists can never leak across
// different panels/credentials (or go stale right after a host/key
// change) when several PterodactylSSO servers exist.
$cacheKey = 'pterodactyl_sso_config_' . md5((string) $this->config('host') . '|' . serialize($values));
$cached = cache()->get($cacheKey);
if ($cached) {
return $cached;
}
try {
$nodes = $this->request('/api/application/nodes');
$nodeList = [];
foreach ($nodes['data'] as $node) {
$nodeAttrs = $node['attributes'] ?? $node;
$nodeList[$nodeAttrs['id']] = $nodeAttrs['name'];
}
$isPelican = false;
$pelicanEggList = [];
try {
$location = $this->request('/api/application/locations');
$locationList = [];
foreach ($location['data'] as $location) {
$locationList[$location['attributes']['id']] = $location['attributes']['short'];
}
$nests = $this->request('/api/application/nests');
$nestList = [];
foreach ($nests['data'] as $nest) {
$nestList[$nest['attributes']['id']] = $nest['attributes']['name'];
}
} catch (\Exception $e) {
// Pelican has no locations or nests endpoints (both 404).
// Fall back to Pelican's flat egg list instead of letting
// the outer catch collapse the form to empty selects.
$isPelican = true;
$locationList = [];
$nestList = [];
$pelicanEggs = $this->request('/api/application/eggs');
foreach ($this->pelicanList($pelicanEggs) as $pelicanEgg) {
$pelicanEggAttrs = $this->pelicanItem($pelicanEgg);
$pelicanEggList[$pelicanEggAttrs['id']] = $pelicanEggAttrs['name'];
}
}
$eggList = $pelicanEggList;
if (!$isPelican && isset($values['nest_id']) && $values['nest_id'] !== '') {
$eggs = $this->request('/api/application/nests/' . $values['nest_id'] . '/eggs');
foreach ($eggs['data'] as $egg) {
$eggList[$egg['attributes']['id']] = $egg['attributes']['name'];
}
}
$using_port_array = isset($values['port_array']) && $values['port_array'] !== '';
$config = [
[
'name' => 'location_ids',
'label' => 'Location(s)',
'type' => 'select',
'description' => 'Location(s) where the server will be installed',
'options' => $locationList,
'multiple' => true,
'database_type' => 'array',
'required' => false,
],
[
'name' => 'node',
'label' => 'Node',
'type' => 'select',
'description' => 'Fill in to install the server on a specific node',
'options' => $nodeList,
],
[
'name' => 'nest_id',
'label' => 'Nest ID',
'type' => 'select',
'options' => $nestList,
'description' => 'Nest ID to fetch the eggs from',
'required' => true,
'live' => true,
],
[
'name' => 'egg_id',
'label' => 'Egg ID',
'type' => 'select',
'options' => $eggList,
'required' => true,
],
[
'name' => 'memory',
'label' => 'Memory',
'type' => 'number',
'suffix' => 'MiB',
'required' => true,
'validation' => 'numeric',
'min_value' => 0,
'description' => 'Set to 0 for unlimited',
],
[
'name' => 'swap',
'label' => 'Swap',
'type' => 'number',
'min_value' => -1,
'suffix' => 'MiB',
'required' => true,
'description' => 'Set to -1 for unlimited, or to 0 to disable swap',
],
[
'name' => 'disk',
'label' => 'Disk',
'type' => 'number',
'suffix' => 'MiB',
'required' => true,
'min_value' => 0,
'description' => 'Set to 0 for unlimited',
],
[
'name' => 'io',
'label' => 'IO Weight',
'type' => 'number',
'required' => true,
'default' => 500,
'min_value' => 10,
'max_value' => 1000,
'description' => 'The IO Weight is the priority given to this server for disk access.',
'hint' => new HtmlString('<a href="https://docs.docker.com/engine/reference/run/#block-io-bandwidth-blkio-constraint" target="_blank">Documentation</a>'),
],
[
'name' => 'cpu',
'label' => 'CPU Limit',
'type' => 'number',
'required' => true,
'min_value' => 0,
'suffix' => '%',
'description' => 'Set to 0 for unlimited',
],
[
'name' => 'cpu_pinning',
'label' => 'CPU Pinning',
'type' => 'text',
'description' => 'Leave empty for no pinning. Used to specify what threads should be used. Example: 0,2-4,5,6',
'validation' => 'regex:/^[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*$/',
],
[
'name' => 'databases',
'label' => 'Databases',
'type' => 'number',
'required' => true,
'min_value' => 0,
],
[
'name' => 'backups',
'label' => 'Backups',
'type' => 'number',
'required' => true,
'min_value' => 0,
],
[
'name' => 'reverse_proxies',
'label' => 'Reverse Proxies',
'type' => 'number',
'description' => 'Number of reverse proxies allowed (requires reverse proxy support on Pterodactyl).',
'required' => false,
'default' => 0,
'min_value' => 0,
],
[
'name' => 'splits',
'label' => 'Splits',
'type' => 'number',
'description' => 'Number of server splits allowed (requires ServerSplitter addon on Pterodactyl)',
'required' => false,
'default' => 0,
'min_value' => 0,
],
[
'name' => 'additional_allocations',
'label' => 'Additional Allocations',
'type' => 'number',
'required' => true,
'min_value' => 0,
],
[
'name' => 'port_array',
'label' => 'Port Array',
'type' => 'text',
'description' => 'Used to assign ports to egg variables.',
'hint' => new HtmlString('<a href="https://paymenter.org/docs/extensions/pterodactyl#port-array" target="_blank">Documentation</a>'),
'live' => true,
'validation' => 'json',
],
[
'name' => 'port_range',
'label' => 'Port ranges',
'type' => 'tags',
'description' => '',
'database_type' => 'array',
'required' => false,
'disabled' => $using_port_array,
],
[
'name' => 'skip_scripts',
'label' => 'Skip Egg Install Script',
'description' => 'If the selected Egg has an install script attached to it, the script will run during the install. If you would like to skip this step, check this box.',
'type' => 'checkbox',
],
[
'name' => 'dedicated_ip',
'label' => 'Dedicated IP',
'description' => 'Assigns the server an allocation whose IP is not being used by any other server.',
'type' => 'checkbox',
'disabled' => $using_port_array,
],
[
'name' => 'start_on_completion',
'label' => 'Start on completion',
'description' => 'Start server automatically after installation.',
'type' => 'checkbox',
],
[
'name' => 'oom_killer',
'label' => 'Enable OOM Killer',
'description' => 'Terminates the server if it breaches the memory limits. Enabling OOM killer may cause server processes to exit unexpectedly.',
'type' => 'checkbox',
],
[
'name' => 'product_server_name_template',
'label' => 'Server Name Template',
'type' => 'text',
'description' => 'Override global name template. Leave empty to use global default.',
'required' => false,
],
[
'name' => 'product_server_description_template',
'label' => 'Server Description Template',
'type' => 'text',
'description' => 'Override global description template. Leave empty to use global default.',
'required' => false,
],
];
if ($isPelican) {
// Pelican has no locations or nests: drop those fields so
// the product form only offers node + flat egg.
$config = array_values(array_filter($config, function ($field) {
return !isset($field['name']) || ($field['name'] !== 'location_ids' && $field['name'] !== 'nest_id');
}));
}
cache()->put($cacheKey, $config, now()->addMinutes(30));
return $config;
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to fetch product config', [
'error' => $e->getMessage(),
]);
return [
[
'name' => 'nest_id',
'label' => 'Nest ID',
'type' => 'select',
'options' => [],
'description' => 'Nest ID to fetch the eggs from',
'required' => true,
],
[
'name' => 'egg_id',
'label' => 'Egg ID',
'type' => 'select',
'options' => [],
'required' => true,
],
[
'name' => 'memory',
'label' => 'Memory',
'type' => 'number',
'suffix' => 'MiB',
'required' => true,
'validation' => 'numeric',
'min_value' => 0,
'description' => 'Set to 0 for unlimited',
],
];
}
}
public function getServer($id, $failIfNotFound = true, $raw = false, bool $forceRefresh = false)
{
$cacheKey = 'pterodactyl_server_id_' . $id;
if (!$forceRefresh) {
$cached = Cache::get($cacheKey);
if ($cached && is_array($cached)) {
if ($raw) {
return $cached;
}
return $cached['attributes']['id'] ?? false;
}
}
try {
$attempt = 0;
while (true) {
try {
$server = $this->normalizePelicanServer($this->request('/api/application/servers/external/' . $id));
if (!$server || !isset($server['attributes'])) {
throw new \Exception('Server not found');
}
Cache::put($cacheKey, $server, 3600);
if ($raw) {
return $server;
}
return $server['attributes']['id'];
} catch (\Exception $e) {
// Permanent failures fail fast: unknown servers (404),
// rate limits (already rotated/waited in request()) and
// auth errors must never be retried here.
if (!$this->isTransientLookupException($e) || ++$attempt >= self::SERVER_LOOKUP_MAX_ATTEMPTS) {
throw $e;
}
usleep(self::SERVER_LOOKUP_RETRY_DELAY_MS * 1000);
}
}
} catch (\Exception $e) {
$isNotFound = $this->isServerNotFoundException($e);
if (!$isNotFound) {
throw $e;
}
Cache::forget($cacheKey);
if ($failIfNotFound) {
throw new \Exception('Server not found');
}
return false;
}
}
private function isServerNotFoundException(\Exception $exception): bool
{
if ((int) $exception->getCode() === 404) {
return true;
}
$message = strtolower($exception->getMessage());
return str_contains($message, 'not found')
|| str_contains($message, 'could not be found');
}
/**
* Whether a failed server lookup is worth retrying.
*
* Only genuinely transient failures (network/timeouts/5xx) are retried.
* Unknown servers, rate limits (already handled in request()) and auth
* errors are permanent from this layer's perspective.
*/
private function isTransientLookupException(\Exception $exception): bool
{
if ($this->isServerNotFoundException($exception) || $this->isRateLimitException($exception)) {
return false;
}
return !in_array((int) $exception->getCode(), [400, 401, 403, 422], true);
}
/**
* Create a new server in Pterodactyl
*
* @param Service $service The service instance
* @param array $settings Server settings from the product configuration
* @param array $properties Additional properties from the service
* @return array Server creation data including ID and link
*
* @throws \Exception When server creation fails
*/
public function createServer(Service $service, $settings, $properties)
{
$this->logMessage('info', 'PterodactylSSO creating server', [
'service_id' => $service->id,
'settings_keys' => array_keys($settings),
'properties_keys' => array_keys($properties),
]);
if ($this->getServer($service->id, failIfNotFound: false, forceRefresh: true)) {
$this->logMessage('warning', 'PterodactylSSO server already exists', [
'service_id' => $service->id,
]);
throw new \Exception('Server already exists');
}
$settings = array_merge($settings, $properties);
$settings = $this->normalizeLocationSettings($settings);
// Pelican has no nests: a Pelican product carries an egg but no
// nest. Only that combination lifts the nest requirement; every
// other missing value keeps the original error below.
$isPelican = (!isset($settings['nest_id']) || $settings['nest_id'] === '')
&& isset($settings['egg_id']) && $settings['egg_id'] !== '';
if (!$isPelican && (!isset($settings['nest_id']) || $settings['nest_id'] === '')) {
$this->logMessage('error', 'PterodactylSSO missing nest ID', [
'service_id' => $service->id,
]);
throw new \Exception('Nest ID is missing. Please select a nest.');
}
if ($isPelican) {
$settings['nest_id'] = '';
}
if (!isset($settings['egg_id']) || $settings['egg_id'] === '') {
$this->logMessage('error', 'PterodactylSSO missing egg ID', [
'service_id' => $service->id,
]);
throw new \Exception('Egg ID is missing. Please select an egg.');
}
try {
if ($isPelican) {
$eggData = $this->normalizePelicanEgg($this->request('/api/application/eggs/' . $settings['egg_id'], data: ['include' => 'variables']));
} else {
$eggData = $this->request('/api/application/nests/' . $settings['nest_id'] . '/eggs/' . $settings['egg_id'], data: ['include' => 'variables']);
}
if (!isset($eggData['attributes'])) {
$this->logMessage('error', 'PterodactylSSO invalid egg data response', [
'service_id' => $service->id,
'nest_id' => $settings['nest_id'],
'egg_id' => $settings['egg_id'],
]);
throw new \Exception('Could not fetch egg data');
}
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to fetch egg data', [
'service_id' => $service->id,
'nest_id' => $settings['nest_id'],
'egg_id' => $settings['egg_id'],
'error' => $e->getMessage(),
]);
throw new \Exception('Failed to fetch egg data: ' . $e->getMessage());
}
$environment = [];
foreach ($eggData['attributes']['relationships']['variables']['data'] as $variable) {
$environment[$variable['attributes']['env_variable']] = $settings[$variable['attributes']['env_variable']] ?? $variable['attributes']['default_value'];
}
if ($isPelican) {
// Pelican validates required egg variables on server creation, and
// some eggs (Paper) ship a required variable with an empty default
// (USER_AGENT). An empty value fails that validation, so give such
// variables a non-empty placeholder; the value is only the
// download User-Agent header used by the install script.
foreach ($eggData['attributes']['relationships']['variables']['data'] as $variable) {
$attrs = $variable['attributes'] ?? [];
$envVariable = $attrs['env_variable'] ?? null;
if ($envVariable === null) {
continue;
}
$rules = $attrs['rules'] ?? [];
if (!is_array($rules)) {
$rules = explode('|', (string) $rules);
}
if (in_array('required', $rules, true) && ($environment[$envVariable] ?? '') === '') {
$environment[$envVariable] = 'Pelican';
}
}
}
$orderUser = $service->user;
if (!$orderUser) {
$this->logMessage('error', 'PterodactylSSO service has no associated user', [
'service_id' => $service->id,
]);
throw new \Exception('Service has no associated user');
}
try {
$userResponse = $this->request('/api/application/users', 'get', ['filter' => ['email' => $orderUser->email]]);
$user = $userResponse['data'][0]['attributes']['id'] ?? null;
if ($isPelican) {
// Pelican returns flat user items: match by email so a
// list that ignores the filter cannot pick the wrong owner.
$user = null;
foreach ($this->pelicanList($userResponse) as $existingUser) {
$existingAttrs = $this->pelicanItem($existingUser);
if (isset($existingAttrs['email']) && strtolower((string) $existingAttrs['email']) === strtolower((string) $orderUser->email)) {
$user = $existingAttrs['id'] ?? null;
break;
}
}
}
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to check existing user', [
'service_id' => $service->id,
'email' => $orderUser->email,
'error' => $e->getMessage(),
]);
throw new \Exception('Failed to check if user already exists: ' . $e->getMessage());
}
if (!$user) {
try {
$username = (preg_replace('/[^a-zA-Z0-9]/', '', strtolower(Str::transliterate($orderUser->name))) ?? Str::random(8)) . '_' . Str::random(4);
$userData = [
'email' => $orderUser->email,
'username' => $username,
'first_name' => $orderUser->first_name ?? '',
'last_name' => $orderUser->last_name ?? '',
];
$this->logMessage('info', 'PterodactylSSO creating new user', [
'service_id' => $service->id,
'email' => $orderUser->email,
'username' => $username,
]);
$userResponse = $this->request('/api/application/users', 'post', $userData);
$user = $userResponse['attributes']['id'] ?? $this->pelicanId($userResponse);
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to create user', [
'service_id' => $service->id,
'email' => $orderUser->email,
'error' => $e->getMessage(),
]);
throw new \Exception('Failed to create user: ' . $e->getMessage());
}
}
try {
$deploymentData = $this->generateDeploymentData($settings, $environment, $isPelican);
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to generate deployment data', [
'service_id' => $service->id,
'error' => $e->getMessage(),
]);
throw new \Exception('Failed to generate deployment data: ' . $e->getMessage());
}
$rawServerName = $properties['server_name'] ?? null;
if (is_string($rawServerName)) {
$rawServerName = trim($rawServerName);
if ($rawServerName === '') {
$rawServerName = null;
}
} else {
$rawServerName = null;
}
$configuredServerName = $settings['servername'] ?? null;
if (is_string($configuredServerName)) {
$configuredServerName = trim($configuredServerName);
if ($configuredServerName === '') {
$configuredServerName = null;
}
} else {
$configuredServerName = null;
}
$serverName = $rawServerName ?? $configuredServerName;
if (!$serverName) {
$nameTemplate = $settings['product_server_name_template'] ?? $this->config('global_server_name_template');
if ($nameTemplate && trim($nameTemplate) !== '') {
$serverName = $this->parsePlaceholderTemplate($nameTemplate, $service, $service->product?->name);
} else {
$serverName = ($service->product?->name ?? 'Server') . ' #' . $service->id;
}
}
$descriptionTemplate = $settings['product_server_description_template'] ?? $this->config('global_server_description_template');
$serverDescription = null;
if ($descriptionTemplate && trim($descriptionTemplate) !== '') {
$serverDescription = $this->parsePlaceholderTemplate($descriptionTemplate, $service, $service->product?->name);
}
$this->logMessage('debug', 'PterodactylSSO resolved naming', [
'service_id' => $service->id,
'final_name' => $serverName,
'final_description' => $serverDescription,
'name_template_used' => $nameTemplate ?? 'none',
]);
if ($rawServerName === null) {
$service->properties()->updateOrCreate([
'key' => 'server_name',
], [
'name' => 'Server Name',
'value' => $serverName,
]);
}
$cpuPinning = null;
if (isset($settings['cpu_pinning']) && $settings['cpu_pinning'] !== '') {
if (!preg_match('/^[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*$/', $settings['cpu_pinning'])) {
$this->logMessage('error', 'PterodactylSSO invalid CPU pinning format', [
'service_id' => $service->id,
'cpu_pinning' => $settings['cpu_pinning'],
]);
throw new \Exception('Invalid CPU pinning format. Use format like "0,2-4,5,6"');
}
$cpuPinning = $settings['cpu_pinning'];
}
$featureLimits = [
'databases' => (int) $settings['databases'],
'allocations' => $deploymentData['allocations_needed'] + (int) $settings['additional_allocations'],
'backups' => (int) $settings['backups'],
'splits' => isset($settings['splits']) ? (int) $settings['splits'] : 0,
];
$reverseProxies = $settings['reverse_proxies'] ?? null;
if ($reverseProxies !== null && trim((string) $reverseProxies) !== '') {
$featureLimits['reverse_proxies'] = (int) $reverseProxies;
}
$serverCreationData = [
'external_id' => (string) $service->id,
'name' => $serverName,
'description' => $serverDescription,
'user' => (int) $user,
'egg' => $settings['egg_id'],
'docker_image' => $eggData['attributes']['docker_image'],
'startup' => $eggData['attributes']['startup'],
'environment' => $deploymentData['environment'],
'skip_scripts' => $this->normalizeBoolean($settings['skip_scripts'] ?? false),
'oom_disabled' => !$this->normalizeBoolean($settings['oom_killer'] ?? false),
'limits' => [
'memory' => (int) $settings['memory'],
'swap' => (int) $settings['swap'],
'disk' => (int) $settings['disk'],
'io' => (int) $settings['io'],
'threads' => $cpuPinning,
'cpu' => (int) $settings['cpu'],
],
'feature_limits' => $featureLimits,
'start_on_completion' => $this->normalizeBoolean($settings['start_on_completion'] ?? false),
];
if ($deploymentData['auto_deploy']) {
$serverCreationData['deploy'] = [
'locations' => $settings['location_ids'],
'dedicated_ip' => $this->normalizeBoolean($settings['dedicated_ip'] ?? false),
'port_range' => $settings['port_range'] ?? [],
];
} else {
$serverCreationData['allocation'] = $deploymentData['allocation'];
}
try {
$this->logMessage('info', 'PterodactylSSO creating server', [
'service_id' => $service->id,
'server_name' => $serverName,
'user_id' => $user,
'external_id' => (string) $service->id,
]);
$server = $this->normalizePelicanServer($this->request('/api/application/servers', 'post', $serverCreationData));
if (!isset($server['attributes']['id']) || !isset($server['attributes']['identifier'])) {
$this->logMessage('error', 'PterodactylSSO invalid server creation response', [
'service_id' => $service->id,
'response' => $server,
]);
throw new \Exception('Invalid server creation response from Pterodactyl API');
}
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to create server', [
'service_id' => $service->id,
'server_name' => $serverName,
'error' => $e->getMessage(),
]);
throw new \Exception('Failed to create server: ' . $e->getMessage());
}
try {
$service->properties()->updateOrCreate([
'key' => 'user_id',
], [
'name' => 'Pterodactyl User ID',
'value' => $user,
]);
$service->properties()->updateOrCreate([
'key' => 'server_id',
], [
'name' => 'Pterodactyl Server ID',
'value' => $server['attributes']['id'],
]);
$service->properties()->updateOrCreate([
'key' => 'server_identifier',
], [
'name' => 'Pterodactyl Server Identifier',
'value' => $server['attributes']['identifier'],
]);
$service->properties()->updateOrCreate([
'key' => 'server_name',
], [
'name' => 'Server Name',
'value' => $serverName,
]);
$userEmail = $orderUser->email;
$service->properties()->updateOrCreate([
'key' => 'user_email',
], [
'name' => 'User Email',
'value' => $userEmail,
]);
$this->logMessage('info', 'PterodactylSSO server created successfully', [
'service_id' => $service->id,
'server_id' => $server['attributes']['id'],
'server_identifier' => $server['attributes']['identifier'],
]);
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to store server properties', [
'service_id' => $service->id,
'server_id' => $server['attributes']['id'] ?? 'unknown',
'error' => $e->getMessage(),
]);
}
return [
'server' => $server['attributes']['id'],
'link' => $this->config('host') . '/server/' . $server['attributes']['identifier'],
];
}
private function generateDeploymentData($settings, $environment, bool $isPelican = false)
{
if ($isPelican) {
return $this->pelicanDeploymentData($settings, $environment);
}
$settings = $this->normalizeLocationSettings($settings);
if (!isset($settings['port_array']) || $settings['port_array'] === '') {
if (!empty($settings['node'])) {
$nodes = $this->request('/api/application/nodes/deployable', 'get', [
'memory' => $settings['memory'],
'disk' => $settings['disk'],
'location_ids' => $settings['location_ids'] ?? [],
'include' => ['allocations'],
]);
$nodes = collect($nodes['data']);
$nodes_by_id = $nodes->mapWithKeys(fn ($node) => [$node['attributes']['id'] => $node['attributes']]);
if (!$nodes_by_id->has($settings['node'])) {
throw new \Exception('Node is not suitable for deployment.');
}
$node = $nodes_by_id->get($settings['node']);
$availablePorts = collect($node['relationships']['allocations']['data']);
$availablePorts = $availablePorts
->filter(fn ($port) => !$port['attributes']['assigned'])
->map(
fn ($port) => [
'port' => $port['attributes']['port'],
'id' => $port['attributes']['id'],
]
);
if ($availablePorts->isEmpty()) {
throw new \Exception('No available allocations found on the selected node.');
}
$allocation = $availablePorts->first();
$environment['SERVER_PORT'] = $allocation['port'];
return [
'auto_deploy' => false,
'environment' => $environment,
'allocations_needed' => 1,
'allocation' => [
'default' => $allocation['id'],
'additional' => [],
],
];
}
return [
'auto_deploy' => true,
'environment' => $environment,
'allocations_needed' => 1,
];
}
try {
$port_array = json_decode($settings['port_array'], true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception('JSON decode error: ' . json_last_error_msg());
}
} catch (\Exception $e) {
throw new \Exception('Invalid JSON in port array');
}
if (!is_array($port_array)) {
throw new \Exception('Port array must be an array');
}
foreach ($port_array as $key => $value) {
if (!preg_match('/^[A-Z0-9_]+$/', $key)) {
throw new \Exception('Invalid port array key format: ' . $key);
}
if (is_array($value)) {
foreach ($value as $port) {
if (!is_numeric($port) || $port < 1 || $port > 65535) {
throw new \Exception('Invalid port value in array: ' . $port);
}
}
} elseif (is_numeric($value)) {
if ($value < 1 || $value > 65535) {
throw new \Exception('Invalid port value: ' . $value);
}
} else {
throw new \Exception('Port array values must be numeric or array of numerics');
}
}
if (!array_key_exists('SERVER_PORT', $port_array)) {
throw new \Exception('Port array must include SERVER_PORT');
}
// Without SERVER_PORT, deployment starts arguing with itself.
if (is_array($port_array['SERVER_PORT']) || !is_numeric($port_array['SERVER_PORT'])) {
throw new \Exception('SERVER_PORT must be a single numeric port value');
}
$nodes = $this->request('/api/application/nodes/deployable', 'get', [
'memory' => $settings['memory'],
'disk' => $settings['disk'],
'location_ids' => $settings['location_ids'] ?? [],
'include' => ['allocations'],
]);
$nodes = collect($nodes['data']);
if ($nodes->isEmpty()) {
throw new \Exception('No deployable nodes found for deployment.');
}
$nodes_by_id = $nodes->mapWithKeys(fn ($node) => [$node['attributes']['id'] => $node['attributes']]);
if (!empty($settings['node'])) {
if (!$nodes_by_id->has($settings['node'])) {
throw new \Exception('Node is not suitable for deployment.');
}
$node = $nodes_by_id->get($settings['node']);
$availablePorts = collect($node['relationships']['allocations']['data']);
$availablePorts = $availablePorts
->filter(fn ($port) => !$port['attributes']['assigned'])
->map(
fn ($port) => [
'port' => $port['attributes']['port'],
'id' => $port['attributes']['id'],
]
);
$free_allocations_needed = 0;
foreach ($port_array as $key => $value) {
$free_allocations_needed += is_array($value) ? count($value) : 1;
}
if (count($availablePorts) < $free_allocations_needed) {
throw new \Exception("Not enough allocations found for deployment. Found: {$availablePorts->count()}, Required: {$free_allocations_needed}");
}
} else {
foreach ($nodes as $index => $node) {
$availablePorts = collect($node['attributes']['relationships']['allocations']['data']);
$availablePorts = $availablePorts
->filter(fn ($port) => !$port['attributes']['assigned'])
->map(
fn ($port) => [
'port' => $port['attributes']['port'],
'id' => $port['attributes']['id'],
]
);
$free_allocations_needed = 0;
foreach ($port_array as $key => $value) {
$free_allocations_needed += is_array($value) ? count($value) : 1;
}
if (count($availablePorts) < $free_allocations_needed) {
if ($index == $nodes->count() - 1) {
throw new \Exception('No nodes with suitable allocations found for deployment');
}
continue;
}
break;
}
}
$allocations = [];
foreach ($port_array as $key => $value) {
if (is_array($value)) {
foreach ($value as $port) {
$allocation = $availablePorts->where('port', $port)->first();
if (!$allocation) {
$allocation = $availablePorts->where('port', '>', $port)->first();
if (!$allocation) {
$allocation = $availablePorts->random();
}
if (!$allocation) {
throw new \Exception('Could not find a port to assign');
}
}
$allocations[$key][] = $allocation;
$availablePorts = $availablePorts->reject(function ($port) use ($allocation) {
return $port['id'] == $allocation['id'];
});
}
} else {
$allocation = $availablePorts->where('port', $value)->first();
if (!$allocation) {
$allocation = $availablePorts->where('port', '>', $value)->first();
if (!$allocation) {
$allocation = $availablePorts->random();
}
if (!$allocation) {
throw new \Exception('Could not find a port to assign');
}
}
$allocations[$key] = $allocation;
$availablePorts = $availablePorts->reject(function ($port) use ($allocation) {
return $port['id'] == $allocation['id'];
});
}
}
$allocationIds = [];
foreach ($allocations as $key => $value) {
if ($key !== 'NONE') {
if (isset($environment[$key])) {
if (is_array($value) && isset($value['port'])) {
$environment[$key] = $value['port'];
} elseif (is_array($value) && isset($value[0]['port'])) {
$environment[$key] = $value[0]['port'];
}
}
}
if ($key !== 'SERVER_PORT') {
if (is_array($value) && isset($value[0])) {
foreach ($value as $v) {
$allocationIds[] = $v['id'];
}
} else {
$allocationIds[] = $value['id'];
}
}
}
return [
'auto_deploy' => false,
'allocations_needed' => $free_allocations_needed,
'environment' => $environment,
'allocation' => [
'default' => $allocations['SERVER_PORT']['id'],
'additional' => $allocationIds,
],
];
}
private function normalizeLocationSettings(array $settings): array
{
if (isset($settings['location']) && !isset($settings['location_ids'])) {
$settings['location_ids'] = [$settings['location']];
}
$locationIds = $settings['location_ids'] ?? [];
if (is_string($locationIds)) {
$locationIds = array_filter(array_map('intval', explode(',', $locationIds)));
} elseif (is_numeric($locationIds)) {
$locationIds = [(int) $locationIds];
} elseif (!is_array($locationIds)) {
$locationIds = [];
} else {
$locationIds = array_map('intval', $locationIds);
}
$settings['location_ids'] = array_values($locationIds);
return $settings;
}
private function normalizeBoolean($value): bool
{
$normalized = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
return $normalized ?? false;
}
private function calculateAllocationLimit(array $settings): int
{
$requiredAllocations = 1;
$rawPortArray = $settings['port_array'] ?? null;
if (is_array($rawPortArray) && !empty($rawPortArray)) {
$requiredAllocations = 0;
foreach ($rawPortArray as $value) {
$requiredAllocations += is_array($value) ? count($value) : 1;
}
} elseif (is_string($rawPortArray) && trim($rawPortArray) !== '') {
$decoded = json_decode($rawPortArray, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded) && !empty($decoded)) {
$requiredAllocations = 0;
foreach ($decoded as $value) {
$requiredAllocations += is_array($value) ? count($value) : 1;
}
}
}
$requiredAllocations = max(1, $requiredAllocations);
$additionalAllocations = max(0, (int) ($settings['additional_allocations'] ?? 0));
return $requiredAllocations + $additionalAllocations;
}
private function buildOverviewContext(Service $service): array
{
$metadata = $this->resolveServerMetadata($service);
$panelUrl = $metadata['panelUrl'] ?? $this->config('host');
[$serverIdentifier, $rawServerAttributes] = $this->resolveServerIdentifier($service, $metadata, true);
if (!$serverIdentifier) {
$usage = $this->prepareUsageMetrics([], null);
return $this->buildOverviewFallbackPayload(
$service,
$metadata,
$panelUrl,
$usage,
'Server identifier is missing. Please sync the service with its panel server.'
);
}
try {
$serverResponse = $this->requestClient('/servers/' . $serverIdentifier);
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO overview failed to fetch client server details', [
'service_id' => $service->id,
'server_identifier' => $serverIdentifier,
'error' => $e->getMessage(),
], true);
$usage = $this->prepareUsageMetrics([], null);
// Panel-side deletion surfaces as the same recoverable state as
// a missing linkage, with its clearer message.
$errorMessage = $this->isPanelServerMissing($e)
? 'Server identifier is missing. Please sync the service with its panel server.'
: 'Unable to load server details right now. Please try again shortly.';
return $this->buildOverviewFallbackPayload(
$service,
$metadata,
$panelUrl,
$usage,
$errorMessage
);
}
$serverAttributes = $serverResponse['attributes'] ?? [];
$relationships = $serverAttributes['relationships'] ?? [];
if (!$relationships && isset($rawServerAttributes['relationships'])) {
$relationships = $rawServerAttributes['relationships'];
}
$limits = $serverAttributes['limits'] ?? [];
$featureLimits = $serverAttributes['feature_limits'] ?? [];
$createdAt = $serverAttributes['created_at'] ?? ($rawServerAttributes['created_at'] ?? null);
$createdAtHuman = $this->formatDateTime($createdAt);
$node = $this->extractNodeDetails($relationships);
$egg = $this->extractEggDetails($relationships);
$allocations = $this->extractAllocations($relationships, $serverAttributes['allocation'] ?? ($rawServerAttributes['allocation'] ?? null));
$usageAttributes = null;
$warnings = [];
try {
$usageResponse = $this->requestClient('/servers/' . $serverIdentifier . '/resources', 'get', [], [409]);
if (isset($usageResponse['_ignored_error']) && $usageResponse['status_code'] === 409) {
$appServer = $this->getServer($service->id, raw: true, forceRefresh: true);
$status = $appServer['attributes']['status'] ?? null;
if (!$status && !($appServer['attributes']['container']['installed'] ?? false)) {
$status = 'installing';
}
// 409 means panel is busy installing/transferring; keep UI calm with minimal fallback data.
$usageAttributes = [
'current_state' => $status ?? 'installing',
'is_suspended' => (bool) ($appServer['attributes']['suspended'] ?? false),
'resources' => [],
];
$this->logMessage('debug', 'PterodactylSSO 409 fallback used', [
'service_id' => $service->id,
'status' => $status,
]);
} else {
$usageAttributes = $usageResponse['attributes'] ?? null;
}
} catch (\Exception $e) {
$warnings[] = 'Live resource usage is currently unavailable. ' . $e->getMessage();
$this->logMessage('warning', 'PterodactylSSO overview resources lookup failed', [
'service_id' => $service->id,
'server_identifier' => $serverIdentifier,
'error' => $e->getMessage(),
]);
}
$usage = $this->prepareUsageMetrics($limits, $usageAttributes);
$statusMeta = $this->buildStatusMeta($usage);
if ($this->shouldLogVerbose()) {
$this->logMessage('debug', 'PterodactylSSO processing allocations for display', [
'service_id' => $service->id,
'primary_allocation' => $allocations['primary'] ?? null,
'additional_count' => count($allocations['additional'] ?? []),
]);
}
$primaryAllocationDisplay = $this->formatAllocationDisplay($allocations['primary'] ?? null);
$additionalAllocationsFormatted = $this->formatAdditionalAllocations($allocations['additional'] ?? []);
$uptimeLabel = $this->formatUptime($usage['uptime'] ?? null);
$featureLimitsFormatted = $this->formatFeatureLimits($featureLimits);
$usageBars = $this->buildUsageBars($usage);
$networkStats = $this->buildNetworkStats($usage);
$panelServerUrl = $this->buildPanelServerUrl($panelUrl, $metadata['serverIdentifier'] ?? null);
$consoleLinks = $this->buildConsoleLinks($panelServerUrl);
return [
'error' => null,
'warnings' => $warnings,
'panelUrl' => $panelUrl,
'metadata' => $metadata,
'statusMeta' => $statusMeta,
'server' => [
'id' => $serverAttributes['id'] ?? ($rawServerAttributes['id'] ?? null),
'name' => $metadata['serverName'] ?? $serverAttributes['name'] ?? ($service->product?->name . ' #' . $service->id),
'identifier' => $metadata['serverIdentifier'] ?? $serverIdentifier,
'uuid' => $serverAttributes['uuid'] ?? ($rawServerAttributes['uuid'] ?? null),
'description' => $serverAttributes['description'] ?? ($rawServerAttributes['description'] ?? null),
'created_at' => $createdAt,
'created_at_human' => $createdAtHuman,
'status' => $usage['state'] ?? null,
'is_suspended' => $usage['is_suspended'] ?? false,
'product' => $service->product?->name,
'service_id' => $service->id,
'uptime_label' => $uptimeLabel,
],
'node' => $node,
'egg' => $egg,
'allocations' => $allocations,
'primaryAllocationDisplay' => $primaryAllocationDisplay,
'additionalAllocationsDisplay' => $additionalAllocationsFormatted,
'limits' => $this->formatLimitSummaries($limits),
'featureLimits' => $featureLimits,
'featureLimitsFormatted' => $featureLimitsFormatted,
'usage' => $usage,
'usageBars' => $usageBars,
'networkStats' => $networkStats,
'consoleLinks' => $consoleLinks,
'generated_at' => now()->toDayDateTimeString(),
'panelServerUrl' => $panelServerUrl,
'refreshInterval' => $this->getOverviewRefreshInterval(),
];
}
private function buildOverviewFallbackPayload(Service $service, array $metadata, ?string $panelUrl, array $usage, string $errorMessage): array
{
$statusMeta = $this->buildStatusMeta($usage);
$panelServerUrl = $this->buildPanelServerUrl($panelUrl, $metadata['serverIdentifier'] ?? null);
return [
'error' => $errorMessage,
'warnings' => [],
'panelUrl' => $panelUrl,
'metadata' => $metadata,
'statusMeta' => $statusMeta,
'server' => [
'id' => null,
'name' => $metadata['serverName'] ?? ($service->product?->name . ' #' . $service->id),
'identifier' => $metadata['serverIdentifier'] ?? null,
'uuid' => null,
'description' => null,
'created_at' => null,
'created_at_human' => null,
'status' => $usage['state'] ?? null,
'is_suspended' => $usage['is_suspended'] ?? false,
'product' => $service->product?->name,
'service_id' => $service->id,
'uptime_label' => null,
],
'node' => null,
'egg' => null,
'allocations' => [
'primary' => null,
'additional' => [],
],
'primaryAllocationDisplay' => null,
'additionalAllocationsDisplay' => [],
'limits' => $this->formatLimitSummaries([]),
'featureLimits' => [],
'featureLimitsFormatted' => $this->formatFeatureLimits([]),
'usage' => $usage,
'usageBars' => $this->buildUsageBars($usage),
'networkStats' => $this->buildNetworkStats($usage),
'consoleLinks' => $this->buildConsoleLinks($panelServerUrl),
'generated_at' => now()->toDayDateTimeString(),
'panelServerUrl' => $panelServerUrl,
'refreshInterval' => $this->getOverviewRefreshInterval(),
];
}
private function resolveServerIdentifier(Service $service, array &$metadata, bool $fetchAttributes = false): array
{
$rawAttributes = null;
$identifier = $this->normalizeServerIdentifier($metadata['serverIdentifier'] ?? null);
$metadata['serverIdentifier'] = $identifier;
if (!$identifier) {
$identifier = $this->normalizeServerIdentifier(
$service->properties()->where('key', 'server_identifier')->value('value')
);
if ($identifier) {
$metadata['serverIdentifier'] = $identifier;
}
}
$shouldFetch = $fetchAttributes || !$identifier || empty($metadata['serverName']);
if ($shouldFetch) {
try {
$rawServer = $this->getServer($service->id, raw: true, forceRefresh: $fetchAttributes);
$rawAttributes = $rawServer['attributes'] ?? [];
$fetchedIdentifier = $this->normalizeServerIdentifier($rawAttributes['identifier'] ?? null);
if ($fetchedIdentifier && $fetchedIdentifier !== $identifier) {
// The panel links this service to a different server than
// we have stored (e.g. recreated after deletion). Adopt
// the fresh linkage so reads and controls recover
// automatically on the next poll.
$identifier = $fetchedIdentifier;
$metadata['serverIdentifier'] = $identifier;
$service->properties()->updateOrCreate([
'key' => 'server_identifier',
], [
'name' => 'Pterodactyl Server Identifier',
'value' => $identifier,
]);
// The cached application-API response may still describe
// the previously linked server; drop it so the next read
// fetches attributes for the newly linked one.
Cache::forget('pterodactyl_server_id_' . $service->id);
} elseif ($identifier) {
$service->properties()->updateOrCreate([
'key' => 'server_identifier',
], [
'name' => 'Pterodactyl Server Identifier',
'value' => $identifier,
]);
}
if (empty($metadata['serverName']) && isset($rawAttributes['name'])) {
$metadata['serverName'] = $rawAttributes['name'];
}
} catch (\Exception $e) {
$this->logMessage('warning', 'PterodactylSSO failed to resolve server identifier', [
'service_id' => $service->id,
'error' => $e->getMessage(),
]);
}
}
return [$identifier, $rawAttributes];
}
private function parsePlaceholderTemplate(string $template, Service $service, ?string $productName = null): string
{
$user = $service->user;
$product = $productName ?? $service->product?->name ?? 'Unknown Product';
$placeholders = [
'{id}' => $service->id,
'{service_id}' => $service->id,
'{user_id}' => $user?->id ?? '0',
'{username}' => $user?->name ?? 'Unknown',
'{email}' => $user?->email ?? '',
'{firstname}' => $user?->first_name ?? '',
'{lastname}' => $user?->last_name ?? '',
'{product_name}' => $product,
'{date}' => now()->format('Y-m-d'),
'{time}' => now()->format('H:i:s'),
'{random_id}' => Str::random(6),
];
return str_replace(array_keys($placeholders), array_values($placeholders), $template);
}
private function formatDateTime(?string $timestamp): ?string
{
if (!$timestamp) {
return null;
}
try {
return Carbon::parse($timestamp)->toDayDateTimeString();
} catch (\Exception $e) {
return $timestamp;
}
}
private function extractNodeDetails(array $relationships): ?array
{
$nodeAttrs = $relationships['node']['attributes']
?? $relationships['node']['data']['attributes']
?? null;
if (!is_array($nodeAttrs)) {
return null;
}
return [
'id' => $nodeAttrs['id'] ?? null,
'name' => $nodeAttrs['name'] ?? null,
'fqdn' => $nodeAttrs['fqdn'] ?? null,
'location' => $nodeAttrs['location_id'] ?? null,
];
}
private function extractEggDetails(array $relationships): ?array
{
$eggAttrs = $relationships['egg']['attributes']
?? $relationships['egg']['data']['attributes']
?? null;
if (!is_array($eggAttrs)) {
return null;
}
return [
'id' => $eggAttrs['id'] ?? null,
'name' => $eggAttrs['name'] ?? null,
'nest' => $eggAttrs['nest'] ?? null,
'author' => $eggAttrs['author'] ?? null,
];
}
private function extractAllocations(array $relationships, $primaryAllocationId): array
{
$allocations = [
'primary' => null,
'additional' => [],
];
foreach ($relationships['allocations']['data'] ?? [] as $allocation) {
$attributes = $allocation['attributes'] ?? [];
$rawAlias = $attributes['ip_alias'] ?? $attributes['alias'] ?? null;
$normalizedAlias = null;
if ($rawAlias !== null && is_string($rawAlias)) {
$trimmed = trim($rawAlias);
$normalizedAlias = ($trimmed !== '') ? $trimmed : null;
}
$isPrimary = (string) ($attributes['id'] ?? '') === (string) ($primaryAllocationId ?? '')
|| ($attributes['is_default'] ?? false) === true;
$item = [
'id' => $attributes['id'] ?? null,
'ip' => $attributes['ip'] ?? null,
'alias' => $normalizedAlias,
'port' => $attributes['port'] ?? null,
'notes' => $attributes['notes'] ?? null,
'is_primary' => $isPrimary,
];
if ($isPrimary && !$allocations['primary']) {
$allocations['primary'] = $item;
} else {
$allocations['additional'][] = $item;
}
}
return $allocations;
}
private function buildStatusMeta(array $usage): array
{
$state = $usage['state'] ?? null;
return [
'state' => $state,
'label' => $this->formatStatusLabel($state),
'classes' => $this->statusBadgeClasses($state),
'is_suspended' => (bool) ($usage['is_suspended'] ?? false),
];
}
private function formatAllocationDisplay(?array $allocation): ?array
{
if (!$allocation) {
return null;
}
$alias = $allocation['alias'] ?? null;
$ip = $allocation['ip'] ?? null;
$port = $allocation['port'] ?? null;
if ($alias !== null && is_string($alias)) {
$alias = trim($alias);
$alias = ($alias !== '') ? $alias : null;
}
$host = $alias ?? $ip;
if ($this->shouldLogVerbose() && $allocation) {
$this->logMessage('debug', 'PterodactylSSO formatting allocation display', [
'allocation_id' => $allocation['id'] ?? 'unknown',
'has_alias' => $alias !== null,
'alias_value' => $alias,
'ip_value' => $ip,
'using' => $alias ? 'alias' : 'ip',
'port' => $port,
]);
}
if (!$host || !$port) {
return null;
}
return [
'host' => $host,
'port' => $port,
'display' => $host . ':' . $port,
];
}
private function formatAdditionalAllocations(array $allocations): array
{
$formatted = [];
foreach ($allocations as $allocation) {
$item = $this->formatAllocationDisplay($allocation);
if ($item) {
$formatted[] = $item;
}
}
return $formatted;
}
private function formatUptime(?int $seconds): ?string
{
if ($seconds === null) {
return null;
}
$hours = intdiv($seconds, 3600);
$minutes = intdiv($seconds % 3600, 60);
$remainingSeconds = $seconds % 60;
return sprintf('%02dh %02dm %02ds', $hours, $minutes, $remainingSeconds);
}
private function formatFeatureLimits(?array $featureLimits): array
{
$featureLimits = $featureLimits ?? [];
$formatted = [
'Databases' => $featureLimits['databases'] ?? 0,
'Allocations' => $featureLimits['allocations'] ?? 0,
'Backups' => $featureLimits['backups'] ?? 0,
'Reverse Proxies' => $featureLimits['reverse_proxies'] ?? 0,
];
if (isset($featureLimits['splits']) && $featureLimits['splits'] > 0) {
$formatted['Splits'] = $featureLimits['splits'];
}
return $formatted;
}
private function buildUsageBars(array $usage): array
{
return [
'cpu' => [
'percentage' => $this->sanitizePercentage($usage['cpu']['percent'] ?? null),
'usage_label' => $usage['cpu']['display'] ?? '—',
'limit_label' => $usage['cpu']['limit_label'] ?? 'Unknown',
'bar_class' => 'bg-primary',
'limit_value' => $usage['cpu']['limit'] ?? null,
],
'memory' => [
'percentage' => $this->sanitizePercentage($usage['memory']['percent'] ?? null),
'usage_label' => $usage['memory']['used_label'] ?? '—',
'limit_label' => $usage['memory']['limit_label'] ?? 'Unknown',
'bar_class' => 'bg-secondary',
'limit_bytes' => isset($usage['memory']['limit_mb']) && $usage['memory']['limit_mb'] > 0
? $usage['memory']['limit_mb'] * 1024 * 1024
: null,
],
'disk' => [
'percentage' => $this->sanitizePercentage($usage['disk']['percent'] ?? null),
'usage_label' => $usage['disk']['used_label'] ?? '—',
'limit_label' => $usage['disk']['limit_label'] ?? 'Unknown',
'bar_class' => 'bg-accent',
'limit_bytes' => isset($usage['disk']['limit_mb']) && $usage['disk']['limit_mb'] > 0
? $usage['disk']['limit_mb'] * 1024 * 1024
: null,
],
];
}
private function buildNetworkStats(array $usage): array
{
return [
'rx_label' => $usage['network']['rx_label'] ?? '—',
'tx_label' => $usage['network']['tx_label'] ?? '—',
'retrieved_at' => $usage['retrieved_at'] ?? null,
];
}
private function buildPanelServerUrl(?string $panelUrl, ?string $identifier): ?string
{
if (!$panelUrl || !$identifier) {
return null;
}
return rtrim((string) $panelUrl, '/') . '/server/' . $identifier;
}
private function buildConsoleLinks(?string $panelServerUrl): array
{
return [
'panel' => $panelServerUrl,
'auto_login' => '?tab=auto_login',
];
}
private function formatStatusLabel(?string $state): string
{
if (!$state) {
return 'Unknown';
}
return ucfirst(str_replace('_', ' ', $state));
}
private function statusBadgeClasses(?string $state): string
{
return match ($state) {
'running' => 'bg-success/15 text-success border-success/20',
'starting' => 'bg-primary/15 text-primary border-primary/20',
'stopping', 'offline' => 'bg-danger/15 text-danger border-danger/20',
default => 'bg-muted/15 text-muted border-muted/30',
};
}
private function sanitizePercentage($value): float
{
if ($value === null) {
return 0.0;
}
return max(0.0, min(100.0, (float) $value));
}
public function sendPowerSignal(Service $service, $settings, $properties, string $signal): array
{
$signal = strtolower(trim($signal));
$allowed = ['start', 'stop', 'restart', 'kill'];
if (!in_array($signal, $allowed, true)) {
throw new \InvalidArgumentException('Invalid power signal.');
}
$metadata = $this->resolveServerMetadata($service);
[$serverIdentifier] = $this->resolveServerIdentifier($service, $metadata, true);
if (!$serverIdentifier) {
throw new \Exception('Server identifier could not be resolved.');
}
try {
$this->requestClient('/servers/' . $serverIdentifier . '/power', 'post', [
'signal' => $signal,
]);
} catch (\Exception $e) {
if ($this->isPanelServerMissing($e)) {
throw new \Exception('Server identifier could not be resolved.');
}
throw $e;
}
$this->logMessage('info', 'PterodactylSSO power signal dispatched', [
'service_id' => $service->id,
'server_identifier' => $serverIdentifier,
'signal' => $signal,
]);
return [
'message' => ucfirst($signal) . ' signal sent.',
];
}
public function getLiveMetrics(Service $service, $settings, $properties): array
{
$metadata = $this->resolveServerMetadata($service);
[$serverIdentifier, $rawAttributes] = $this->resolveServerIdentifier($service, $metadata, true);
if (!$serverIdentifier) {
throw new \Exception('Server identifier could not be resolved.');
}
if (!$rawAttributes) {
try {
$clientServer = $this->requestClient('/servers/' . $serverIdentifier);
$rawAttributes = $clientServer['attributes'] ?? [];
} catch (\Exception $e) {
$this->logMessage('debug', 'PterodactylSSO live metrics client lookup failed', [
'service_id' => $service->id,
'server_identifier' => $serverIdentifier,
'error' => $e->getMessage(),
]);
if ($this->isPanelServerMissing($e)) {
throw new \Exception('Server identifier could not be resolved.');
}
}
}
try {
$response = $this->requestClient('/servers/' . $serverIdentifier . '/resources');
} catch (\Exception $e) {
if ($this->isPanelServerMissing($e)) {
throw new \Exception('Server identifier could not be resolved.');
}
if ($this->isServerStateConflict($e)) {
// Suspended servers have no live wings state; the panel
// answers 409 instead. Report zeroed usage flagged as
// suspended so polls keep rendering instead of failing.
$this->logMessage('debug', 'PterodactylSSO live metrics unavailable for suspended server', [
'service_id' => $service->id,
'server_identifier' => $serverIdentifier,
]);
return $this->buildMetricsPayload($rawAttributes['limits'] ?? [], ['is_suspended' => true]);
}
throw $e;
}
return $this->buildMetricsPayload($rawAttributes['limits'] ?? [], $response['attributes'] ?? []);
}
/**
* Whether a panel error means the server refuses live state.
*
* Wings answers 409 ServerStateConflict for servers without a live
* state (e.g. suspended). That is a normal production state, not a
* failure, so callers degrade instead of throwing.
*/
private function isServerStateConflict(\Exception $e): bool
{
return (int) $e->getCode() === 409 || stripos($e->getMessage(), 'ServerStateConflict') !== false;
}
/**
* Shape live usage into the metrics payload consumed by the route/JS.
*/
private function buildMetricsPayload(array $limits, ?array $resourceAttributes): array
{
$usage = $this->prepareUsageMetrics($limits, $resourceAttributes);
$statusMeta = $this->buildStatusMeta($usage);
return [
'status' => $statusMeta,
'usage' => [
'cpu' => [
'percent' => $usage['cpu']['percent'],
'display' => $usage['cpu']['display'],
'limit_label' => $usage['cpu']['limit_label'] ?? $this->formatCpuLimit($usage['cpu']['limit'] ?? null),
],
'memory' => [
'percent' => $usage['memory']['percent'],
'used_label' => $usage['memory']['used_label'],
'used_bytes' => $usage['memory']['used_bytes'],
'limit_label' => $usage['memory']['limit_label'],
],
'disk' => [
'percent' => $usage['disk']['percent'],
'used_label' => $usage['disk']['used_label'],
'used_bytes' => $usage['disk']['used_bytes'],
'limit_label' => $usage['disk']['limit_label'],
],
],
'network' => [
'rx_label' => $usage['network']['rx_label'],
'tx_label' => $usage['network']['tx_label'],
],
'uptime' => [
'seconds' => $usage['uptime'],
'label' => $this->formatUptime($usage['uptime'] ?? null),
],
];
}
private function getOverviewRefreshInterval(): int
{
$value = (int) ($this->config('overview_refresh_seconds') ?? 30);
if ($value < 5) {
return 5;
}
return min($value, 600);
}
private function prepareUsageMetrics(array $limits, ?array $usageAttributes): array
{
$resources = $usageAttributes['resources'] ?? [];
$memoryLimitMb = isset($limits['memory']) ? (int) $limits['memory'] : null;
$diskLimitMb = isset($limits['disk']) ? (int) $limits['disk'] : null;
$memoryLimitBytes = ($memoryLimitMb && $memoryLimitMb > 0) ? $memoryLimitMb * 1024 * 1024 : null;
$diskLimitBytes = ($diskLimitMb && $diskLimitMb > 0) ? $diskLimitMb * 1024 * 1024 : null;
$memoryUsedBytes = isset($resources['memory_bytes']) ? (int) $resources['memory_bytes'] : null;
$diskUsedBytes = isset($resources['disk_bytes']) ? (int) $resources['disk_bytes'] : null;
$memoryPercent = ($memoryLimitBytes && $memoryLimitBytes > 0 && $memoryUsedBytes !== null)
? min(100, round(($memoryUsedBytes / $memoryLimitBytes) * 100, 2))
: null;
$diskPercent = ($diskLimitBytes && $diskLimitBytes > 0 && $diskUsedBytes !== null)
? min(100, round(($diskUsedBytes / $diskLimitBytes) * 100, 2))
: null;
$cpuUsage = isset($resources['cpu_absolute']) ? round((float) $resources['cpu_absolute'], 2) : null;
$cpuLimit = isset($limits['cpu']) ? (int) $limits['cpu'] : null;
$retrievedAt = $usageAttributes ? now()->toDayDateTimeString() : null;
$uptimeMillis = isset($resources['uptime']) ? (int) $resources['uptime'] : null;
$uptimeSeconds = $uptimeMillis !== null ? (int) floor($uptimeMillis / 1000) : null;
return [
'state' => $usageAttributes['current_state'] ?? null,
'is_suspended' => (bool) ($usageAttributes['is_suspended'] ?? false),
'retrieved_at' => $retrievedAt,
'cpu' => [
'usage' => $cpuUsage,
'limit' => $cpuLimit,
'display' => $cpuUsage !== null ? $cpuUsage . '%' : null,
'limit_label' => $this->formatCpuLimit($cpuLimit),
'percent' => $cpuUsage !== null ? min(100, max(0, $cpuUsage)) : null,
],
'memory' => [
'used_bytes' => $memoryUsedBytes,
'used_label' => $this->formatBytes($memoryUsedBytes),
'limit_mb' => $memoryLimitMb,
'limit_label' => $this->formatCapacityLimit($memoryLimitMb),
'percent' => $memoryPercent,
],
'disk' => [
'used_bytes' => $diskUsedBytes,
'used_label' => $this->formatBytes($diskUsedBytes),
'limit_mb' => $diskLimitMb,
'limit_label' => $this->formatCapacityLimit($diskLimitMb),
'percent' => $diskPercent,
],
'network' => [
'rx_bytes' => isset($resources['network_rx_bytes']) ? (int) $resources['network_rx_bytes'] : null,
'tx_bytes' => isset($resources['network_tx_bytes']) ? (int) $resources['network_tx_bytes'] : null,
'rx_label' => $this->formatBytes(isset($resources['network_rx_bytes']) ? (int) $resources['network_rx_bytes'] : null),
'tx_label' => $this->formatBytes(isset($resources['network_tx_bytes']) ? (int) $resources['network_tx_bytes'] : null),
],
'uptime' => $uptimeSeconds,
];
}
private function formatLimitSummaries(array $limits): array
{
return [
'memory' => [
'raw' => $limits['memory'] ?? null,
'label' => $this->formatCapacityLimit($limits['memory'] ?? null),
],
'swap' => [
'raw' => $limits['swap'] ?? null,
'label' => $this->formatSwapLimit($limits['swap'] ?? null),
],
'disk' => [
'raw' => $limits['disk'] ?? null,
'label' => $this->formatCapacityLimit($limits['disk'] ?? null),
],
'io' => [
'raw' => $limits['io'] ?? null,
'label' => isset($limits['io']) ? (string) $limits['io'] : 'Default',
],
'cpu' => [
'raw' => $limits['cpu'] ?? null,
'label' => $this->formatCpuLimit($limits['cpu'] ?? null),
],
];
}
private function formatCapacityLimit(?int $megabytes): string
{
if ($megabytes === null) {
return 'Unknown';
}
if ($megabytes <= 0) {
return 'Unlimited';
}
return $this->formatBytes($megabytes * 1024 * 1024);
}
private function formatSwapLimit(?int $swap): string
{
if ($swap === null) {
return 'Unknown';
}
if ($swap === -1) {
return 'Unlimited';
}
if ($swap === 0) {
return 'Disabled';
}
return $this->formatBytes($swap * 1024 * 1024);
}
private function formatCpuLimit(?int $cpu): string
{
if ($cpu === null) {
return 'Unknown';
}
if ($cpu <= 0) {
return 'Unlimited';
}
return $cpu . '%';
}
private function formatBytes(?int $bytes, int $precision = 2): string
{
if ($bytes === null) {
return '—';
}
if ($bytes === 0) {
return '0 B';
}
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
$power = (int) floor(log($bytes, 1024));
$power = max(0, min($power, count($units) - 1));
$value = $bytes / (1024 ** $power);
return round($value, $precision) . ' ' . $units[$power];
}
/**
* Build client-area list metrics for many services in one pass.
*
* Identifiers come from the already loaded service properties and only
* fall back to the application API when they are missing. Live panel
* data is fetched concurrently over the client API using a single HTTP
* pool: the mostly-static server object (limits, allocation, node,
* suspension) is cached briefly while live resources use a very short
* cache so rapid page interactions do not hammer the panel. When the
* client key is unavailable or rejected the cached application API
* data is used instead of failing the whole list.
*
* @param array<int, Service> $services
* @return array<int, array<string, mixed>> Keyed by service id.
*/
public function getServerCardMetrics(array $services): array
{
$entries = [];
foreach ($services as $service) {
if (!$service instanceof Service) {
continue;
}
$entries[$service->id] = $this->resolveCardEntry($service);
}
if ($entries === []) {
return [];
}
$serverObjects = [];
$resources = [];
$requests = [];
foreach ($entries as $entry) {
$identifier = $entry['identifier'];
if (!$identifier) {
continue;
}
$cachedServer = Cache::get($this->cardCacheKey('server', $identifier));
if (is_array($cachedServer)) {
$serverObjects[$identifier] = $cachedServer;
} else {
$requests['server|' . $identifier] = '/servers/' . $identifier;
}
$cachedResources = Cache::get($this->cardCacheKey('resources', $identifier));
if (is_array($cachedResources)) {
$resources[$identifier] = $cachedResources;
} else {
$requests['resources|' . $identifier] = '/servers/' . $identifier . '/resources';
}
}
if ($requests !== []) {
[$serverObjects, $resources] = $this->fetchClientCards($requests, $serverObjects, $resources);
}
$metrics = [];
foreach ($entries as $serviceId => $entry) {
$identifier = $entry['identifier'];
$applicationAttributes = $entry['application_attributes'];
// Without a client-side server object or live resource (missing
// key, 404/409 on the panel, private server), the application API
// still carries the limits, node and lifecycle state needed to
// render a useful card.
if (!$applicationAttributes && (
!$identifier
|| !isset($serverObjects[$identifier])
|| !isset($resources[$identifier])
)) {
$applicationAttributes = $this->fetchApplicationAttributes($serviceId);
}
$serverAttributes = $identifier ? ($serverObjects[$identifier] ?? null) : null;
$resourceAttributes = $identifier ? ($resources[$identifier] ?? null) : null;
$limits = $serverAttributes['limits'] ?? $applicationAttributes['limits'] ?? [];
$usage = $this->prepareUsageMetrics($limits, $resourceAttributes);
$state = $usage['state'];
$suspended = $usage['is_suspended'] || (bool) ($serverAttributes['is_suspended'] ?? false);
if (!$resourceAttributes) {
// No live wings state (409) and no client key both land
// here; static panel data is the best available source.
$suspended = $suspended
|| (bool) ($applicationAttributes['suspended'] ?? false)
|| (bool) ($applicationAttributes['is_suspended'] ?? false);
if ($state === null) {
$state = $serverAttributes['status']
?? $applicationAttributes['status']
?? ($suspended ? 'suspended' : null);
}
}
if ($state === null) {
$state = $serverAttributes['status'] ?? $applicationAttributes['status'] ?? null;
}
if (
$state === null
&& $applicationAttributes !== null
&& array_key_exists('installed', $applicationAttributes['container'] ?? [])
&& !$applicationAttributes['container']['installed']
) {
$state = 'installing';
}
$allocations = $this->extractAllocations(
$serverAttributes['relationships'] ?? ($applicationAttributes['relationships'] ?? []),
$serverAttributes['allocation'] ?? ($applicationAttributes['allocation'] ?? null)
);
// The client API does not expose the primary allocation id on
// older panels; the first allocation is the next best source.
$primaryAllocation = $this->formatAllocationDisplay(
$allocations['primary'] ?? ($allocations['additional'][0] ?? null)
);
$nodeName = $serverAttributes['node']
?? ($applicationAttributes['relationships']['node']['attributes']['name'] ?? null)
?? ($applicationAttributes['relationships']['node']['data']['attributes']['name'] ?? null);
$metrics[$serviceId] = [
'identifier' => $identifier,
'state' => $state,
'is_suspended' => $suspended,
'address' => $primaryAllocation['display'] ?? null,
'location' => is_string($nodeName) && trim($nodeName) !== '' ? $nodeName : null,
'limits' => [
'cpu' => isset($limits['cpu']) ? (int) $limits['cpu'] : null,
'memory_mb' => isset($limits['memory']) ? (int) $limits['memory'] : null,
'disk_mb' => isset($limits['disk']) ? (int) $limits['disk'] : null,
],
'usage' => [
'cpu_percent' => $usage['cpu']['percent'] ?? null,
'memory_percent' => $usage['memory']['percent'] ?? null,
'memory_used_bytes' => $usage['memory']['used_bytes'] ?? null,
'disk_percent' => $usage['disk']['percent'] ?? null,
'disk_used_bytes' => $usage['disk']['used_bytes'] ?? null,
],
'panel_url' => $this->buildPanelServerUrl($this->config('host'), $identifier),
];
}
return $metrics;
}
/**
* Resolve the panel linkage for a service without extra API calls when
* the identifier is already stored on the service properties.
*
* @return array{identifier: ?string, application_attributes: ?array}
*/
private function resolveCardEntry(Service $service): array
{
$properties = $service->relationLoaded('properties')
? $service->properties->pluck('value', 'key')->all()
: $service->properties()->pluck('value', 'key')->all();
$entry = [
'identifier' => $this->normalizeServerIdentifier($properties['server_identifier'] ?? null),
'application_attributes' => null,
];
if (!$entry['identifier']) {
$entry['application_attributes'] = $this->fetchApplicationAttributes($service->id);
$entry['identifier'] = $this->normalizeServerIdentifier(
$entry['application_attributes']['identifier'] ?? null
);
}
return $entry;
}
private function fetchApplicationAttributes(int $serviceId): ?array
{
try {
$server = $this->getServer($serviceId, raw: true, failIfNotFound: false);
return is_array($server) ? ($server['attributes'] ?? null) : null;
} catch (\Throwable $e) {
$this->logMessage('debug', 'PterodactylSSO card metrics application lookup failed', [
'service_id' => $serviceId,
'error' => $e->getMessage(),
]);
return null;
}
}
/**
* Fetch the queued client API paths concurrently and fill the cached
* server object / live resource maps.
*
* @param array<string, string> $requests keyed as "<kind>|<identifier>"
* @return array{0: array<string, array>, 1: array<string, array>}
*/
private function fetchClientCards(array $requests, array $serverObjects, array $resources): array
{
$apiKeys = $this->clientApiKeys();
if ($apiKeys === []) {
return [$serverObjects, $resources];
}
$poolResponses = $this->poolClientRequests($apiKeys[0], $requests);
$rateLimited = $poolResponses === [];
foreach ($poolResponses as $key => $response) {
[$kind, $identifier] = array_pad(explode('|', (string) $key, 2), 2, null);
if (!$identifier || !$response instanceof Response) {
// Connection failures surface as Throwable entries; the
// sequential fallback below retries them with key rotation.
$rateLimited = true;
continue;
}
$this->syncRateLimitHeaders($apiKeys[0], 'client', $response, (string) Str::uuid(), 0);
if (in_array($response->status(), [401, 403, 429], true)) {
$rateLimited = true;
continue;
}
// 404 means the panel no longer knows the server; 409 means it
// has no live wings state (suspended/installing). Both are
// resolved from application data when the card is assembled.
if (in_array($response->status(), [404, 409], true)) {
continue;
}
if (!$response->successful()) {
$this->logMessage('warning', 'PterodactylSSO card metrics request failed', [
'identifier' => $identifier,
'kind' => $kind,
'status' => $response->status(),
]);
continue;
}
$attributes = $response->json()['attributes'] ?? [];
if ($kind === 'server') {
$serverObjects[$identifier] = $attributes;
Cache::put($this->cardCacheKey('server', $identifier), $attributes, self::CARD_SERVER_CACHE_SECONDS);
} else {
$resources[$identifier] = $attributes;
Cache::put($this->cardCacheKey('resources', $identifier), $attributes, self::CARD_RESOURCES_CACHE_SECONDS);
}
}
if (!$rateLimited) {
return [$serverObjects, $resources];
}
return $this->fetchClientCardsSequentially($requests, $serverObjects, $resources);
}
/**
* Sequential fallback used when the pooled request bounced so the
* existing per-key rotation and cooldown handling can take over.
*
* @param array<string, string> $requests
* @return array{0: array<string, array>, 1: array<string, array>}
*/
private function fetchClientCardsSequentially(array $requests, array $serverObjects, array $resources): array
{
foreach ($requests as $key => $path) {
[$kind, $identifier] = array_pad(explode('|', (string) $key, 2), 2, null);
if (
!$identifier
|| ($kind === 'server' && isset($serverObjects[$identifier]))
|| ($kind === 'resources' && isset($resources[$identifier]))
) {
continue;
}
try {
$json = $this->requestClient($path, 'get', [], [404, 409]);
if (!empty($json['_ignored_error'])) {
continue;
}
$attributes = $json['attributes'] ?? [];
if ($kind === 'server') {
$serverObjects[$identifier] = $attributes;
Cache::put($this->cardCacheKey('server', $identifier), $attributes, self::CARD_SERVER_CACHE_SECONDS);
} else {
$resources[$identifier] = $attributes;
Cache::put($this->cardCacheKey('resources', $identifier), $attributes, self::CARD_RESOURCES_CACHE_SECONDS);
}
} catch (\Throwable $e) {
$this->logMessage('warning', 'PterodactylSSO card metrics fallback request failed', [
'identifier' => $identifier,
'kind' => $kind,
'error' => $e->getMessage(),
]);
}
}
return [$serverObjects, $resources];
}
/**
* Send many client API GETs concurrently with the first configured key.
*
* @param array<string, string> $requests
* @return array<string, Response|\Throwable>
*/
private function poolClientRequests(string $apiKey, array $requests): array
{
$base = rtrim((string) $this->config('host'), '/');
try {
$this->respectRateLimit($apiKey, 'client');
} catch (\Exception $e) {
$this->logMessage('warning', 'PterodactylSSO card metrics rate limit guard failed', [
'error' => $e->getMessage(),
]);
return [];
}
try {
return Http::pool(function (Pool $pool) use ($apiKey, $base, $requests) {
foreach ($requests as $key => $path) {
$pool->as($key)
->withHeaders([
'Authorization' => 'Bearer ' . $apiKey,
'Accept' => 'Application/vnd.pterodactyl.v1+json',
'Content-Type' => 'application/json',
'User-Agent' => self::CLIENT_API_USER_AGENT,
])
->connectTimeout(5)
->timeout(10)
->get($base . '/api/client' . $path);
}
}, self::CARD_POOL_CONCURRENCY);
} catch (\Throwable $e) {
$this->logMessage('warning', 'PterodactylSSO card metrics pool failed', [
'error' => $e->getMessage(),
]);
return [];
}
}
/**
* @return array<int, string>
*/
private function clientApiKeys(): array
{
$raw = (string) $this->config('client_api_key');
return array_values(array_filter(array_map('trim', explode(',', $raw))));
}
private function cardCacheKey(string $kind, string $identifier): string
{
return 'pterodactyl_sso_card_' . $kind . '_' . md5((string) $this->config('host') . '|' . $identifier);
}
public function getOverviewView(Service $service, $settings, $properties, $view): string
{
$context = $this->buildOverviewContext($service);
return $this->renderView('overview.index', $context);
}
public function suspendServer(Service $service, $settings, $properties)
{
$server = $this->getServer($service->id, forceRefresh: true);
$this->request('/api/application/servers/' . $server . '/suspend', 'post');
return true;
}
public function unsuspendServer(Service $service, $settings, $properties)
{
$server = $this->getServer($service->id, forceRefresh: true);
$this->request('/api/application/servers/' . $server . '/unsuspend', 'post');
return true;
}
public function terminateServer(Service $service, $settings, $properties)
{
$server = $this->getServer($service->id, failIfNotFound: false, forceRefresh: true);
if (!$server) {
Cache::forget('pterodactyl_server_id_' . $service->id);
return true;
}
$this->request('/api/application/servers/' . $server, 'delete');
Cache::forget('pterodactyl_server_id_' . $service->id);
return true;
}
/**
* Upgrade server resources
*
* @param Service $service The service instance
* @param array $settings Server settings from the product configuration
* @param array $properties Additional properties from the service
* @return bool True on success
*
* @throws \Exception When upgrade fails
*/
public function upgradeServer(Service $service, $settings, $properties)
{
$this->logMessage('info', 'PterodactylSSO upgrading server', [
'service_id' => $service->id,
'settings_keys' => array_keys($settings),
'properties_keys' => array_keys($properties),
]);
try {
$server = $this->getServer($service->id, raw: true, forceRefresh: true);
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to get server for upgrade', [
'service_id' => $service->id,
'error' => $e->getMessage(),
]);
throw new \Exception('Failed to retrieve server information: ' . $e->getMessage());
}
$settings = array_merge($settings, $properties);
// Products created before newer fields existed may not have every
// setting stored. Fall back to the live server values instead of
// crashing on missing keys (or worse, resetting limits to 0).
$existingLimits = $server['attributes']['limits'] ?? [];
$existingFeatureLimits = $server['attributes']['feature_limits'] ?? [];
foreach (['memory', 'swap', 'disk', 'io', 'cpu'] as $limitKey) {
$settings[$limitKey] = $settings[$limitKey] ?? ($existingLimits[$limitKey] ?? 0);
}
foreach (['databases', 'backups'] as $featureKey) {
$settings[$featureKey] = $settings[$featureKey] ?? ($existingFeatureLimits[$featureKey] ?? 0);
}
$settings['splits'] = $settings['splits'] ?? ($existingFeatureLimits['splits'] ?? 0);
$settings['cpu_pinning'] = $settings['cpu_pinning'] ?? ($existingLimits['threads'] ?? null);
if (isset($settings['additional_allocations']) || isset($settings['port_array'])) {
$targetAllocations = $this->calculateAllocationLimit($settings);
} else {
$targetAllocations = (int) ($existingFeatureLimits['allocations'] ?? 0);
}
$cpuPinning = null;
if (isset($settings['cpu_pinning']) && $settings['cpu_pinning'] !== '' && $settings['cpu_pinning'] !== null) {
if (!preg_match('/^[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*$/', $settings['cpu_pinning'])) {
$this->logMessage('error', 'PterodactylSSO invalid CPU pinning format in upgrade', [
'service_id' => $service->id,
'cpu_pinning' => $settings['cpu_pinning'],
]);
throw new \Exception('Invalid CPU pinning format. Use format like "0,2-4,5,6"');
}
$cpuPinning = $settings['cpu_pinning'];
}
$featureLimits = [
'databases' => (int) $settings['databases'],
'allocations' => $targetAllocations,
'backups' => (int) $settings['backups'],
'splits' => (int) $settings['splits'],
];
$reverseProxies = $settings['reverse_proxies'] ?? null;
if ($reverseProxies !== null && trim((string) $reverseProxies) !== '') {
$featureLimits['reverse_proxies'] = (int) $reverseProxies;
}
$updateServerData = [
'allocation' => $server['attributes']['allocation'],
'memory' => (int) $settings['memory'],
'swap' => (int) $settings['swap'],
'disk' => (int) $settings['disk'],
'io' => (int) $settings['io'],
'cpu' => (int) $settings['cpu'],
'threads' => $cpuPinning,
'feature_limits' => $featureLimits,
];
try {
$this->logMessage('info', 'PterodactylSSO updating server resources', [
'service_id' => $service->id,
'server_id' => $server['attributes']['id'],
]);
$this->request('/api/application/servers/' . $server['attributes']['id'] . '/build', 'patch', $updateServerData);
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to update server resources', [
'service_id' => $service->id,
'server_id' => $server['attributes']['id'],
'error' => $e->getMessage(),
]);
throw new \Exception('Failed to update server resources: ' . $e->getMessage());
}
// The egg cannot be resolved without both ids (older products may not
// store them). Skip only the startup section then — the build limits
// above have already been applied.
if (empty($settings['nest_id']) || empty($settings['egg_id'])) {
$this->logMessage('warning', 'PterodactylSSO skipping startup update: nest/egg not configured', [
'service_id' => $service->id,
'server_id' => $server['attributes']['id'],
]);
$this->logMessage('info', 'PterodactylSSO server upgrade completed successfully', [
'service_id' => $service->id,
'server_id' => $server['attributes']['id'],
]);
return true;
}
try {
$eggData = $this->request('/api/application/nests/' . $settings['nest_id'] . '/eggs/' . $settings['egg_id'], data: ['include' => 'variables']);
if (!isset($eggData['attributes'])) {
throw new \Exception('Could not fetch egg data');
}
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to fetch egg data for upgrade', [
'service_id' => $service->id,
'nest_id' => $settings['nest_id'],
'egg_id' => $settings['egg_id'],
'error' => $e->getMessage(),
]);
throw new \Exception('Failed to fetch egg data: ' . $e->getMessage());
}
$environment = [];
foreach ($eggData['attributes']['relationships']['variables']['data'] as $variable) {
if (isset($server['attributes']['container']['environment'][$variable['attributes']['env_variable']])) {
$environment[$variable['attributes']['env_variable']] = $server['attributes']['container']['environment'][$variable['attributes']['env_variable']];
} else {
$environment[$variable['attributes']['env_variable']] = $settings[$variable['attributes']['env_variable']] ?? $variable['attributes']['default_value'];
}
}
$updateServerData = [
'environment' => $environment,
'skip_scripts' => $this->normalizeBoolean($settings['skip_scripts'] ?? false),
'oom_disabled' => !$this->normalizeBoolean($settings['oom_killer'] ?? false),
'egg' => $settings['egg_id'],
'image' => $server['attributes']['container']['image'] ?? $eggData['attributes']['docker_image'],
'startup' => $server['attributes']['container']['startup_command'] ?? $settings['startup'] ?? $eggData['attributes']['startup'],
];
try {
$this->logMessage('info', 'PterodactylSSO updating server startup configuration', [
'service_id' => $service->id,
'server_id' => $server['attributes']['id'],
]);
$this->request('/api/application/servers/' . $server['attributes']['id'] . '/startup', 'patch', $updateServerData);
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO failed to update server startup configuration', [
'service_id' => $service->id,
'server_id' => $server['attributes']['id'],
'error' => $e->getMessage(),
]);
throw new \Exception('Failed to update server startup configuration: ' . $e->getMessage());
}
$this->logMessage('info', 'PterodactylSSO server upgrade completed successfully', [
'service_id' => $service->id,
'server_id' => $server['attributes']['id'],
]);
return true;
}
/**
* Sync server status and details
*
* @param Service $service The service instance
* @param array $settings Server settings from the product configuration
* @param array $properties Additional properties from the service
* @return bool True on success
*/
public function sync(Service $service, $settings, $properties)
{
$this->logMessage('info', 'PterodactylSSO syncing server', [
'service_id' => $service->id,
]);
try {
$metadata = $this->resolveServerMetadata($service);
[$serverIdentifier, $serverAttributes] = $this->resolveServerIdentifier($service, $metadata, true);
if (!$serverIdentifier) {
$this->logMessage('warning', 'PterodactylSSO sync failed: server identifier not found', [
'service_id' => $service->id,
]);
return false;
}
if (!$serverAttributes) {
$server = $this->getServer($service->id, raw: true, forceRefresh: true);
$serverAttributes = $server['attributes'] ?? [];
}
if (empty($serverAttributes)) {
$this->logMessage('error', 'PterodactylSSO sync failed: could not retrieve server attributes', [
'service_id' => $service->id,
'identifier' => $serverIdentifier,
]);
return false;
}
$changes = [];
if (isset($serverAttributes['identifier']) && $serverAttributes['identifier'] !== $serverIdentifier) { $service->properties()->updateOrCreate(
['key' => 'server_identifier'],
['name' => 'Pterodactyl Server Identifier', 'value' => $serverAttributes['identifier']]
);
$changes['identifier'] = $serverAttributes['identifier'];
}
$userIdProp = $service->properties()->where('key', 'user_id')->first();
if (!$userIdProp && isset($serverAttributes['user'])) {
$service->properties()->create([
'key' => 'user_id',
'name' => 'Pterodactyl User ID',
'value' => $serverAttributes['user'],
]);
$changes['user_id'] = $serverAttributes['user'];
}
$this->logMessage('info', 'PterodactylSSO sync successful', [
'service_id' => $service->id,
'changes' => $changes,
]);
return true;
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO sync failed with exception', [
'service_id' => $service->id,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Get available actions for the service
*
* @param Service $service The service instance
* @return array Array of available actions
*/
public function getActions(Service $service): array
{
$serverIdentifier = $this->normalizeServerIdentifier($service->properties()->where('key', 'server_identifier')->value('value'));
try {
$server = $this->getServer($service->id, raw: true, forceRefresh: true);
$serverIdentifier = $this->normalizeServerIdentifier($server['attributes']['identifier'] ?? null) ?? $serverIdentifier;
} catch (\Throwable $e) {
$this->logMessage('warning', 'PterodactylSSO getActions fallback: server lookup failed', [
'service_id' => $service->id,
'error' => $e->getMessage(),
]);
}
$actions = [
[
'name' => 'overview',
'type' => 'view',
'label' => 'Overview',
'function' => 'getOverviewView',
],
];
$panelUrl = rtrim((string) $this->config('host'), '/');
if ($panelUrl !== '') {
$actions[] = [
'name' => 'access_panel',
'type' => 'button',
'label' => 'Access Panel',
'url' => $serverIdentifier
? $panelUrl . '/server/' . $serverIdentifier
: $panelUrl,
];
}
$userIdProperty = $service->properties()->where('key', 'user_id')->first();
if ($this->config('sso_secret') && $userIdProperty) {
$actions[] = [
'name' => 'auto_login',
'type' => 'button',
'label' => 'Auto Login to Panel',
'function' => 'ssoLink',
];
}
$actions[] = [
'name' => 'show_credentials',
'type' => 'view',
'label' => 'Show Credentials',
'function' => 'getCredentialsView',
];
if ($service->properties()->where('key', 'current_password')->exists()) {
$actions[] = [
'name' => 'reveal_password',
'type' => 'view',
'label' => 'Reveal Password',
'function' => 'getRevealPasswordView',
];
}
$actions[] = [
'name' => 'generate_password',
'type' => 'view',
'label' => 'Generate New Password',
'function' => 'getNewPasswordView',
];
if ($this->isAdminContext()) {
$actions[] = [
'name' => 'edit_server_properties',
'type' => 'view',
'label' => 'Edit Server Properties',
'function' => 'getEditServerPropertiesView',
];
}
return $actions;
}
/**
* Generate SSO login link for the Pterodactyl panel
*
* @param Service $service The service instance
* @return RedirectResponse|string Redirect response or fallback URL
*/
public function ssoLink(Service $service)
{
$panelBaseUrl = trim((string) $this->config('host'));
if ($panelBaseUrl === '') {
return '/';
}
$panelBaseUrl = rtrim($panelBaseUrl, '/');
$fallbackUrl = $panelBaseUrl;
$serverIdentifier = $this->normalizeServerIdentifier($service->properties()->where('key', 'server_identifier')->value('value'));
if ($serverIdentifier) {
$fallbackUrl = $panelBaseUrl . '/server/' . $serverIdentifier;
}
try {
$userIdProperty = $service->properties()->where('key', 'user_id')->first();
$secret = trim((string) $this->config('sso_secret'));
if ($secret === '') {
$this->logMessage('warning', 'PterodactylSSO: SSO secret not configured', [
'service_id' => $service->id,
]);
return $fallbackUrl;
}
if (!$userIdProperty || !$userIdProperty->value) {
$this->logMessage('warning', 'PterodactylSSO: User ID not found for SSO', [
'service_id' => $service->id,
]);
return $fallbackUrl;
}
} catch (\Throwable $e) {
$this->logMessage('error', 'PterodactylSSO: Initial SSO validation failed', [
'service_id' => $service->id,
'message' => $e->getMessage(),
]);
return $fallbackUrl;
}
try {
$endpoint = trim((string) $this->config('sso_endpoint'));
if ($endpoint === '') {
$endpoint = '/sso-wemx';
}
$endpoint = '/' . ltrim($endpoint, '/');
$ssoUrl = $panelBaseUrl . $endpoint;
$response = Http::acceptJson()
->connectTimeout(5)
->timeout(10)
->retry(1, 200)
->get($ssoUrl, [
'sso_secret' => $secret,
'user_id' => $userIdProperty->value,
]);
if (!$response->successful()) {
$responseMessage = null;
if (str_contains((string) $response->header('Content-Type'), 'application/json')) {
$responseMessage = data_get($response->json(), 'message');
}
$this->logMessage('warning', 'PterodactylSSO: SSO endpoint returned error response', [
'service_id' => $service->id,
'status' => $response->status(),
'message' => $responseMessage,
]);
return $fallbackUrl;
}
$data = $response->json();
if (!is_array($data)) {
$this->logMessage('warning', 'PterodactylSSO: Invalid SSO response payload', [
'service_id' => $service->id,
'response_type' => gettype($data),
]);
return $fallbackUrl;
}
if (!filter_var($data['success'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
$this->logMessage('warning', 'PterodactylSSO: SSO endpoint reported failure', [
'service_id' => $service->id,
'response' => $data,
]);
return $fallbackUrl;
}
$redirect = $this->resolveWemxRedirectUrl($data, $panelBaseUrl, $endpoint);
if ($redirect && !$this->isSafeRedirect($redirect)) {
$this->logMessage('warning', 'PterodactylSSO: Unsafe redirect blocked', [
'service_id' => $service->id,
'redirect' => $redirect,
]);
$redirect = null;
}
if (!$redirect) {
$this->logMessage('warning', 'PterodactylSSO: SSO response missing redirect', [
'service_id' => $service->id,
'response' => $data,
]);
return $fallbackUrl;
}
$this->sendSecurityMail($service, 'sso', [
'user_id' => $userIdProperty->value ?? null,
'server_identifier' => $serverIdentifier,
]);
return redirect()->away($redirect);
} catch (ConnectionException $e) {
$this->logMessage('warning', 'PterodactylSSO: SSO endpoint unreachable', [
'service_id' => $service->id,
'message' => $e->getMessage(),
]);
return $fallbackUrl;
} catch (\Throwable $e) {
$this->logMessage('error', 'PterodactylSSO: SSO handling failed', [
'service_id' => $service->id,
'message' => $e->getMessage(),
]);
return $fallbackUrl;
}
}
private function resolveWemxRedirectUrl(array $payload, string $panelBaseUrl, string $endpoint): ?string
{
$redirect = $payload['redirect'] ?? $payload['redirect_url'] ?? null;
if (!is_string($redirect) || trim($redirect) === '') {
return null;
}
$redirect = trim($redirect);
if (!preg_match('#^https?://#i', $redirect)) {
return $panelBaseUrl . '/' . ltrim($redirect, '/');
}
$parsed = parse_url($redirect);
if ($parsed === false) {
return null;
}
$path = $parsed['path'] ?? '';
$query = isset($parsed['query']) && $parsed['query'] !== '' ? '?' . $parsed['query'] : '';
$fragment = isset($parsed['fragment']) && $parsed['fragment'] !== '' ? '#' . $parsed['fragment'] : '';
$panelHost = parse_url($panelBaseUrl, PHP_URL_HOST);
$redirectHost = $parsed['host'] ?? null;
$normalizedEndpoint = rtrim($endpoint, '/');
$looksLikeWemxTokenRedirect = $path !== '' && str_starts_with($path, $normalizedEndpoint . '/');
if ($panelHost && $redirectHost && strcasecmp($panelHost, $redirectHost) !== 0 && $looksLikeWemxTokenRedirect) {
return $panelBaseUrl . $path . $query . $fragment;
}
return $redirect;
}
private function isSafeRedirect(string $url): bool
{
$url = trim($url);
if ($url === '') {
return false;
}
if (preg_match('#^\s*(javascript:|data:|vbscript:)#i', $url)) {
return false;
}
$panelHost = parse_url(trim((string) $this->config('host')), PHP_URL_HOST);
if (!$panelHost) {
return false;
}
$parsed = parse_url($url);
if ($parsed === false) {
return false;
}
if (isset($parsed['scheme']) && !in_array(strtolower($parsed['scheme']), ['http', 'https'], true)) {
return false;
}
if (!isset($parsed['host'])) {
$path = $parsed['path'] ?? '';
if (preg_match('#[<>"\']#', $path)) {
return false;
}
return $path === '' || str_starts_with($path, '/');
}
return strcasecmp($parsed['host'], $panelHost) === 0;
}
/**
* Get credentials view for the service
*
* @param array $settings
* @param array $properties
* @param string $view
*/
public function getCredentialsView(Service $service, $settings, $properties, $view): string
{
$serviceProperties = $service->properties()->pluck('value', 'key')->toArray();
$userEmail = $serviceProperties['user_email'] ?? $service->user?->email;
$metadata = $this->resolveServerMetadata($service);
return $this->renderView('credentials', [
'serverName' => $metadata['serverName'],
'serverIdentifier' => $metadata['serverIdentifier'],
'userEmail' => $userEmail,
'panelUrl' => $metadata['panelUrl'],
'revealAction' => null,
]);
}
/**
* Get new password generation view
*
* @param array $settings
* @param array $properties
* @param string $view
*/
public function getRevealPasswordView(Service $service, $settings, $properties, $view): string
{
$metadata = $this->resolveServerMetadata($service);
$userEmail = $service->properties()->where('key', 'user_email')->value('value') ?? $service->user?->email;
$password = $this->decryptStoredPassword($service);
if (!$password) {
return $this->renderView('password-reveal-missing', [
'serverName' => $metadata['serverName'],
'serverIdentifier' => $metadata['serverIdentifier'],
'panelUrl' => $metadata['panelUrl'],
]);
}
$this->sendSecurityMail($service, 'reveal', [
'password_preview' => $this->passwordPreview($password),
'server_identifier' => $metadata['serverIdentifier'],
]);
return $this->renderView('password-reveal', [
'serverName' => $metadata['serverName'],
'serverIdentifier' => $metadata['serverIdentifier'],
'userEmail' => $userEmail,
'panelUrl' => $metadata['panelUrl'],
'password' => $password,
'autoHideMilliseconds' => 15000,
]);
}
public function getNewPasswordView(Service $service, $settings, $properties, $view): string
{
$sessionResult = request()?->session()?->get('pterodactyl_password_result');
if (is_array($sessionResult)) {
if (($sessionResult['success'] ?? false) && !empty($sessionResult['password'])) {
$metadata = $this->resolveServerMetadata($service);
$userEmail = $service->properties()->where('key', 'user_email')->value('value') ?? $service->user?->email;
return $this->renderView('password-generated', [
'serverName' => $metadata['serverName'],
'serverIdentifier' => $metadata['serverIdentifier'],
'userEmail' => $userEmail,
'panelUrl' => $metadata['panelUrl'],
'password' => $sessionResult['password'],
'autoHideMilliseconds' => 20000,
]);
}
if (!($sessionResult['success'] ?? true)) {
return $this->renderView('password-error', [
'heading' => 'Password Generation Failed',
'message' => $sessionResult['message'] ?? 'Failed to generate a new password.',
]);
}
}
return $this->renderView('password-confirm', [
'confirmUrl' => route('services.pterodactyl.password.generate', ['service' => $service]),
'cancelUrl' => '?tab=show_credentials',
]);
}
public function generateNewPasswordAction(Service $service, $settings, $properties): array
{
try {
$result = $this->generateNewPasswordInternal($service);
return [
'success' => true,
'password' => $result['password'] ?? null,
'message' => $result['message'] ?? 'Password updated successfully!',
];
} catch (\Throwable $e) {
$this->logMessage('error', 'PterodactylSSO password generation action failed', [
'service_id' => $service->id,
'error' => $e->getMessage(),
], true);
return [
'success' => false,
'message' => $e->getMessage(),
];
}
}
/**
* Internal method to generate a new password for the user
*
* @throws \Exception
*/
public function generateNewPasswordInternal(Service $service): array
{
try {
$userIdProperty = $service->properties()->where('key', 'user_id')->first();
$userEmailProperty = $service->properties()->where('key', 'user_email')->first();
if (!$userIdProperty || !$userIdProperty->value) {
throw new \Exception('User ID not found. Cannot generate new password.');
}
if ($this->isPaymenterAdmin($service)) {
throw new \Exception('Password rotation is disabled for administrator accounts.');
}
$userEmail = $userEmailProperty?->value ?? $service->user?->email;
if (!$userEmail) {
throw new \Exception('User email not found. Cannot generate new password.');
}
$currentUser = $this->request('/api/application/users/' . $userIdProperty->value, 'get');
if ($this->isPterodactylAdmin($currentUser)) {
throw new \Exception('Password rotation is disabled for administrator accounts.');
}
$newPassword = $this->generateSecurePassword();
// Pelican's user view is flat (id/username/email/root_admin) with no
// first_name/last_name, and its user update accepts only email,
// username and password; use a Pelican-shaped payload instead.
if (str_contains(strtolower((string) $this->config('host')), 'pelican')) {
$updateData = [
'email' => $userEmail,
'username' => $currentUser['attributes']['username'],
'password' => $newPassword,
];
} else {
$updateData = [
'email' => $userEmail,
'username' => $currentUser['attributes']['username'],
'first_name' => $currentUser['attributes']['first_name'],
'last_name' => $currentUser['attributes']['last_name'],
'password' => $newPassword,
];
}
$this->logMessage('info', 'PterodactylSSO updating user password', [
'service_id' => $service->id,
'user_id' => $userIdProperty->value,
'email' => $userEmail,
'update_data' => array_merge($updateData, ['password' => '[REDACTED]']),
]);
$this->request('/api/application/users/' . $userIdProperty->value, 'patch', $updateData);
$this->purgeStoredPassword($service);
$this->logMessage('info', 'PterodactylSSO password generated successfully', [
'service_id' => $service->id,
'user_id' => $userIdProperty->value,
]);
$this->sendSecurityMail($service, 'generated', [
'password_preview' => $this->passwordPreview($newPassword),
'server_identifier' => $service->properties()->where('key', 'server_identifier')->value('value'),
]);
$this->recordPasswordResetLog($service, $currentUser, [
'password_preview' => $this->passwordPreview($newPassword),
'pterodactyl_user_id' => $userIdProperty->value,
'pterodactyl_email' => $userEmail,
]);
return [
'password' => $newPassword,
'message' => 'Password updated successfully!',
];
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO password generation failed', [
'service_id' => $service->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw new \Exception('Failed to generate new password: ' . $e->getMessage());
}
}
/**
* Generate a secure password
*/
/**
* Generate a secure random password
*
* @return string The generated password
*/
private function generateSecurePassword(): string
{
$length = 16;
$lowercase = 'abcdefghijklmnopqrstuvwxyz';
$uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$numbers = '0123456789';
$special = '!@#$%^&*';
// Start with one of each class so support never has to explain "why no symbols?".
$password = [
$lowercase[random_int(0, strlen($lowercase) - 1)],
$uppercase[random_int(0, strlen($uppercase) - 1)],
$numbers[random_int(0, strlen($numbers) - 1)],
$special[random_int(0, strlen($special) - 1)],
];
$allChars = $lowercase . $uppercase . $numbers . $special;
for ($i = 4; $i < $length; $i++) {
$password[] = $allChars[random_int(0, strlen($allChars) - 1)];
}
shuffle($password);
return implode('', $password);
}
/**
* Check if the current request is from admin context
*/
private function isAdminContext(): bool
{
$request = request();
if ($request) {
$routeName = $request->route()?->getName() ?? '';
if (str_starts_with($routeName, 'filament.admin.')) {
return true;
}
}
return $this->currentUserCanManageServers();
}
/**
* Whether the currently authenticated user is allowed to manage services.
*
* This must be permission-based: any staff role (e.g. support) has a
* non-null role_id, so a role presence check would grant this to staff
* without service-management rights. The request Referer/URL must not be
* trusted either since both are client-controlled.
*/
private function currentUserCanManageServers(): bool
{
$user = auth()->user();
if (!$user || !method_exists($user, 'hasPermission')) {
return false;
}
try {
return $user->hasPermission('admin.services.update');
} catch (\Throwable $e) {
$this->logMessage('debug', 'PterodactylSSO admin permission lookup failed', [
'message' => $e->getMessage(),
]);
return false;
}
}
private function isPaymenterAdmin(Service $service): bool
{
return $this->userHasAdminRole($service->user);
}
private function userHasAdminRole($user): bool
{
if (!$user) {
return false;
}
try {
if (!is_null($user->role_id ?? null)) {
return true;
}
if (($user->role ?? null) !== null) {
return true;
}
if (method_exists($user, 'hasPermission') && $user->hasPermission('*')) {
return true;
}
} catch (\Throwable $e) {
$this->logMessage('debug', 'PterodactylSSO admin detection lookup failed', [
'message' => $e->getMessage(),
]);
}
return false;
}
private function isPterodactylAdmin(array $userData): bool
{
return (bool) data_get($userData, 'attributes.root_admin', false);
}
private function recordPasswordResetLog(Service $service, array $pterodactylUser, array $meta = []): void
{
try {
$triggeredBy = auth()->user();
$serverIdentifier = $service->properties()->where('key', 'server_identifier')->value('value');
$pteroAttributes = $pterodactylUser['attributes'] ?? [];
$context = [
'event' => 'password_rotated',
'service_id' => $service->id,
'service_label' => trim(($service->product?->name ?? 'Service') . ' #' . $service->id),
'product' => $service->product?->name,
'user' => [
'id' => $service->user?->id,
'email' => $service->user?->email,
],
'triggered_by' => [
'id' => $triggeredBy?->id,
'email' => $triggeredBy?->email,
],
'pterodactyl' => [
'user_id' => $meta['pterodactyl_user_id'] ?? $pteroAttributes['id'] ?? null,
'email' => $meta['pterodactyl_email'] ?? $pteroAttributes['email'] ?? null,
'username' => $pteroAttributes['username'] ?? null,
],
'server_identifier' => $serverIdentifier,
'password_preview' => $meta['password_preview'] ?? null,
'panel_url' => $this->config('host'),
'ip_address' => request()?->ip(),
'occurred_at' => now()->toIso8601String(),
];
DebugLog::create([
'type' => 'pterodactyl_sso_password',
'context' => $context,
]);
} catch (\Throwable $e) {
$this->logMessage('warning', 'PterodactylSSO failed to write password log', [
'service_id' => $service->id,
'error' => $e->getMessage(),
], true);
}
}
/**
* Get edit server properties view for admin
*
* @param array $settings
* @param array $properties
* @param string $view
*/
public function getEditServerPropertiesView(Service $service, $settings, $properties, $view): string
{
if (!$this->currentUserCanManageServers()) {
return $this->renderView('admin/update-error', [
'title' => 'Unauthorized',
'messages' => ['Only administrators can update server properties.'],
]);
}
$result = request()?->session()?->get('pterodactyl_edit_properties_result');
if (is_array($result)) {
if (($result['success'] ?? false) === true) {
return $this->renderView('admin/update-success', [
'serverId' => $result['serverId'] ?? '',
'serverName' => $result['serverName'] ?? '',
'serverIdentifier' => $result['serverIdentifier'] ?? '',
'userId' => $result['userId'] ?? '',
'userEmail' => $result['userEmail'] ?? '',
]);
}
return $this->renderView('admin/update-error', [
'title' => $result['title'] ?? 'Update Failed',
'messages' => $result['messages'] ?? ['Unable to update server properties right now.'],
]);
}
$serviceProperties = $service->properties()->pluck('value', 'key')->toArray();
return $this->renderView('admin/edit-properties', [
'serviceId' => $service->id,
'updateAction' => route('services.pterodactyl.admin.update-properties', ['service' => $service]),
'serverId' => $serviceProperties['server_id'] ?? '',
'serverName' => $serviceProperties['server_name'] ?? '',
'serverIdentifier' => $serviceProperties['server_identifier'] ?? '',
'userId' => $serviceProperties['user_id'] ?? '',
'userEmail' => $serviceProperties['user_email'] ?? $service->user?->email ?? '',
]);
}
public function updateServerPropertiesPayload(Service $service, $settings, $properties, array $payload): array
{
if (!$this->currentUserCanManageServers()) {
return [
'success' => false,
'title' => 'Unauthorized',
'messages' => ['Only administrators can update server properties.'],
];
}
return $this->handleUpdateServerProperties($service, $payload);
}
/**
* Handle updating server properties
*/
private function handleUpdateServerProperties(Service $service, array $payload): array
{
try {
$serverId = trim($payload['server_id'] ?? '');
$serverName = trim($payload['server_name'] ?? '');
$serverIdentifier = trim($payload['server_identifier'] ?? '');
$userId = trim($payload['user_id'] ?? '');
$userEmail = trim($payload['user_email'] ?? '');
$errors = [];
if ($serverId === '') {
$errors[] = 'Server ID is required';
} elseif (!ctype_digit($serverId)) {
$errors[] = 'Server ID must be a numeric value';
}
if ($serverName === '') {
$errors[] = 'Server Name is required';
} elseif (strlen($serverName) > 255) {
$errors[] = 'Server Name must be less than 255 characters';
}
if ($serverIdentifier === '') {
$errors[] = 'Server Identifier is required';
} elseif (!preg_match('/^[a-zA-Z0-9_-]+$/', $serverIdentifier)) {
$errors[] = 'Server Identifier can only contain letters, numbers, underscores, and hyphens';
}
if ($userId === '') {
$errors[] = 'User ID is required';
} elseif (!ctype_digit($userId)) {
$errors[] = 'User ID must be a numeric value';
}
if ($userEmail === '') {
$errors[] = 'User Email is required';
} elseif (!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'User Email must be a valid address';
}
if ($errors) {
return [
'success' => false,
'title' => 'Validation Error',
'messages' => $errors,
];
}
$propertiesToUpdate = [
'server_id' => ['name' => 'Pterodactyl Server ID', 'value' => $serverId],
'server_name' => ['name' => 'Server Name', 'value' => $serverName],
'server_identifier' => ['name' => 'Pterodactyl Server Identifier', 'value' => $serverIdentifier],
'user_id' => ['name' => 'Pterodactyl User ID', 'value' => $userId],
'user_email' => ['name' => 'User Email', 'value' => $userEmail],
];
foreach ($propertiesToUpdate as $key => $data) {
$service->properties()->updateOrCreate([
'key' => $key,
], [
'name' => $data['name'],
'value' => $data['value'],
]);
}
// Linkage changed: drop the cached panel response so subsequent
// reads resolve against the newly stored identifiers immediately.
Cache::forget('pterodactyl_server_id_' . $service->id);
$this->logMessage('info', 'PterodactylSSO v2 server properties updated', [
'service_id' => $service->id,
'updated_properties' => array_keys($propertiesToUpdate),
'admin_action' => true,
'version' => 'v2',
]);
return [
'success' => true,
'serverId' => $serverId,
'serverName' => $serverName,
'serverIdentifier' => $serverIdentifier,
'userId' => $userId,
'userEmail' => $userEmail,
];
} catch (\Exception $e) {
$this->logMessage('error', 'PterodactylSSO v2 failed to update server properties', [
'service_id' => $service->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
'version' => 'v2',
]);
return [
'success' => false,
'title' => 'Update Failed (v2)',
'messages' => [$e->getMessage()],
];
}
}
public function migrateOption(string $key, ?string $value)
{
return match ($key) {
'egg' => ['key' => 'egg_id', 'value' => $value],
'nest' => ['key' => 'nest_id', 'value' => $value],
'allocation' => ['key' => 'additional_allocations', 'value' => $value],
'location' => ['key' => 'location_ids', 'value' => json_encode([$value]), 'type' => 'array'],
default => ['key' => $key, 'value' => $value]
};
}
}