Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ Download `connect-buttons-${VERSION}.pteroext` below, then upload it under **Adm
php artisan p:extension:install /path/to/connect-buttons-${VERSION}.pteroext --enable
```

### What's new in ${VERSION}

- Join and Copy show the server's domain from the Domains extension when it has one, without the port when an SRV record covers the game.
- The buttons now look like the panel's own buttons and line up with the other extensions above the console.

Requires Pterodactyl Panel 2.0 (2.0-develop or later) and PHP 8.3+. See the README for features and settings.

This is a community extension and is not affiliated with or endorsed by Pterodactyl.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## 1.1.0

- Works with the Domains extension. When the server's main allocation has a working domain, Join and Copy use it instead of the IP. If the domain has an SRV record for the game, the port is left off; otherwise it is shown as domain:port.
- Other ports on the same IP, such as RCON, show the domain too. Ports on another IP keep their IP.
- Without the Domains extension, or without a domain, nothing changes: the IP alias or IP is used as before.
- Join and Copy now look exactly like the panel's own buttons, so their height, corners and font match the rest of the console. Join is the main button and Copy the outlined one. Join is still a normal link, so it can be copied or opened in a new tab.
- The button row has the same 12px gap below it as the other extensions above the console.

## 1.0.0

- First release.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ One-click Join and Copy address buttons on every server's console page, set up a
- **Copy address button** for every game. Minecraft addresses leave off the default `:25565`.
- **Other ports listed with their notes**, such as "RCON: 1.2.3.4:28016". The notes are the ones you already set on the server's **Network** page, so there is nothing new to fill in.
- **Works out the game by itself** from the egg's name. To change it, open **Admin → Eggs → (egg)** and pick a join method under **Connect Buttons**: Steam, Minecraft, FiveM, TeamSpeak, Mumble, copy only, hidden, or your own link with `{ip}` and `{port}` (http, https, steam, fivem, ts3server and mumble links only).
- Uses the allocation's IP alias when one is set.
- **Works with the [Domains](https://github.com/Rustix-Development/pterodactyl-domains) extension.** When the server's main allocation has a working domain, Join and Copy use it instead of the IP: just the name when the domain has an SRV record for the game, otherwise `domain:port`. Other ports on the same IP, such as RCON, show the domain too. Without Domains, or without a domain, the allocation's IP alias (or IP) is used.
- **Matches the console.** Join and Copy look exactly like the panel's own buttons (Join stays a normal link), and the row lines up with Announcements, Custom Links and Next Wipe above the console.

## API

Expand Down
2 changes: 1 addition & 1 deletion extension.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"$schema": "./node_modules/@pterodactyl/sdk/manifest.schema.json",
"id": "connect-buttons",
"name": "Connect Buttons",
"version": "1.0.0",
"version": "1.1.0",
"description": "One-click Join and Copy address buttons on every server's console page, set up automatically for Minecraft, Rust, Source games, FiveM, TeamSpeak and Mumble.",
"author": "RustixDev",
"icon": "gamepad-2",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "connect-buttons",
"private": true,
"version": "1.0.0",
"version": "1.1.0",
"type": "module",
"scripts": {
"build": "vite build",
Expand Down
18 changes: 12 additions & 6 deletions src/Http/Controllers/ConnectController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Pterodactyl\Models\Server;
use Pterodactyl\Services\Extensions\ExtensionSettings;
use RustixDev\ConnectButtons\Support\ConnectPresets;
use RustixDev\ConnectButtons\Support\ServerDomains;

class ConnectController
{
Expand All @@ -23,18 +24,23 @@ public function show(Server $server): JsonResponse
}

$default = $server->allocation;
$host = $default ? ($default->ip_alias ?: $default->ip) : null;
$domains = ServerDomains::forServer($server);
$domain = $default ? ($domains[$default->id] ?? null) : null;

$host = $default ? ($domain['name'] ?? ServerDomains::ip($default)) : null;
// An SRV record for the game's port means players need only the name.
$withPort = ! ($domain !== null && $domain['srv'] && $domain['port'] === $default?->port);
$hidden = $type === 'none' || $default === null;

return new JsonResponse([
'type' => $type,
'url' => $type === 'none' || $default === null
? null
: ConnectPresets::url($type, $host, $default->port, $fields['template'] ?? null),
'address' => $type === 'none' || $default === null ? null : ConnectPresets::address($type, $host, $default->port),
'url' => $hidden ? null : ConnectPresets::url($type, $host, $default->port, $fields['template'] ?? null, $withPort),
'address' => $hidden ? null : ConnectPresets::address($type, $host, $default->port, $withPort),
'domain' => $domain['name'] ?? null,
'ports' => $server->allocations
->sortBy(fn (Allocation $a) => [$a->id !== $server->allocation_id, $a->port])
->map(fn (Allocation $a) => [
'address' => ($a->ip_alias ?: $a->ip).':'.$a->port,
'address' => ServerDomains::hostFor($a, $default, $domains).':'.$a->port,
'notes' => $a->notes,
'is_default' => $a->id === $server->allocation_id,
])
Expand Down
23 changes: 14 additions & 9 deletions src/Support/ConnectPresets.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,30 @@ public static function detect(string $eggName): string
return 'copy';
}

/** The join URL for a type, or null when players can only copy the address. */
public static function url(string $type, string $host, int $port, ?string $template): ?string
/**
* The join URL for a type, or null when players can only copy the address.
* Without the port (a domain with an SRV record) the game looks the port up itself;
* a custom template still gets {port}.
*/
public static function url(string $type, string $host, int $port, ?string $template, bool $withPort = true): ?string
{
$suffix = $withPort ? ":{$port}" : '';
$url = match ($type) {
'steam' => "steam://connect/{$host}:{$port}",
'fivem' => "fivem://connect/{$host}:{$port}",
'teamspeak' => "ts3server://{$host}?port={$port}",
'mumble' => "mumble://{$host}:{$port}",
'steam' => "steam://connect/{$host}{$suffix}",
'fivem' => "fivem://connect/{$host}{$suffix}",
'teamspeak' => $withPort ? "ts3server://{$host}?port={$port}" : "ts3server://{$host}",
'mumble' => "mumble://{$host}{$suffix}",
'custom' => $template === null ? null : strtr($template, ['{ip}' => rawurlencode($host), '{port}' => (string) $port]),
default => null,
};

return $url !== null && self::hasAllowedScheme($url) ? $url : null;
}

/** What players paste into the game. Minecraft leaves off its default port. */
public static function address(string $type, string $host, int $port): string
/** What players paste into the game. Minecraft leaves off its default port, and an SRV record any port. */
public static function address(string $type, string $host, int $port, bool $withPort = true): string
{
return $type === 'minecraft' && $port === 25565 ? $host : "{$host}:{$port}";
return ! $withPort || ($type === 'minecraft' && $port === 25565) ? $host : "{$host}:{$port}";
}

public static function hasAllowedScheme(string $url): bool
Expand Down
132 changes: 132 additions & 0 deletions src/Support/ServerDomains.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

namespace RustixDev\ConnectButtons\Support;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\Server;

/**
* Reads the server's domains from the Domains extension when it is installed.
* Nothing here depends on that extension's code: only its table is read, and
* when the table is missing the server simply has no domains.
*/
final class ServerDomains
{
public const string TABLE = 'ext_domains_domains';

/** DNS states in which the domain points at the server. */
public const array LIVE = ['active', 'verified'];

/**
* The server's working domains, one per allocation id.
*
* @return array<int, array{name: string, target: string|null, port: int|null, srv: bool}>
*/
public static function forServer(Server $server): array
{
try {
if (! Schema::hasTable(self::TABLE)) {
return [];
}

$rows = DB::table(self::TABLE)
->where('server_id', $server->id)
->whereIn('dns_status', self::LIVE)
->orderBy('id')
->get(['kind', 'name', 'allocation_id', 'target', 'port', 'srv_service', 'dns_records', 'dns_status', 'dns_error'])
->map(fn (object $row) => (array) $row)
->all();
} catch (\Throwable) {
return [];
}

return self::byAllocation($rows, $server->allocation_id);
}

/**
* Picks one domain per allocation. A domain without an allocation belongs to the
* primary one. When an allocation has several, one with a working SRV record wins,
* then the oldest.
*
* @param list<array<string, mixed>> $rows
*
* @return array<int, array{name: string, target: string|null, port: int|null, srv: bool}>
*/
public static function byAllocation(array $rows, ?int $primaryAllocationId): array
{
$domains = [];
foreach ($rows as $row) {
if (! in_array($row['dns_status'] ?? null, self::LIVE, true) || ! is_string($row['name'] ?? null) || $row['name'] === '') {
continue;
}

$allocation = isset($row['allocation_id']) ? (int) $row['allocation_id'] : $primaryAllocationId;
if ($allocation === null) {
continue;
}

$domain = [
'name' => $row['name'],
'target' => is_string($row['target'] ?? null) && $row['target'] !== '' ? $row['target'] : null,
'port' => isset($row['port']) ? (int) $row['port'] : null,
'srv' => self::hasSrv($row),
];
if (! isset($domains[$allocation]) || ($domain['srv'] && ! $domains[$allocation]['srv'])) {
$domains[$allocation] = $domain;
}
}

return $domains;
}

/**
* Whether players can join with the name alone: the domain has an SRV service
* and the record is in place. Subdomains keep the provider's record id; own
* domains report a missing SRV record in their DNS check.
*
* @param array<string, mixed> $row
*/
public static function hasSrv(array $row): bool
{
if (empty($row['srv_service']) || ! isset($row['port'])) {
return false;
}

if (($row['kind'] ?? 'subdomain') === 'own') {
return $row['dns_status'] === 'verified' && ! str_contains((string) ($row['dns_error'] ?? ''), 'SRV record');
}

$records = is_string($row['dns_records'] ?? null) ? json_decode($row['dns_records'], true) : ($row['dns_records'] ?? null);

return is_array($records) && isset($records['srv']);
}

/** The address players use for an allocation: its IP alias, else its IP. */
public static function ip(Allocation $allocation): string
{
return $allocation->ip_alias ?: $allocation->ip;
}

/**
* The host to show for an allocation: its own domain, else the primary
* allocation's domain when the domain points at this allocation's address too
* (such as RCON next to the game port), else its IP.
*
* @param array<int, array{name: string, target: string|null, port: int|null, srv: bool}> $domains
*/
public static function hostFor(Allocation $allocation, ?Allocation $primary, array $domains): string
{
if (isset($domains[$allocation->id])) {
return $domains[$allocation->id]['name'];
}

$domain = $primary !== null ? ($domains[$primary->id] ?? null) : null;
if ($domain !== null && self::ip($allocation) === ($domain['target'] ?? self::ip($primary))) {
return $domain['name'];
}

return self::ip($allocation);
}
}
2 changes: 2 additions & 0 deletions src/client/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export interface Connect {
type: string;
url: string | null;
address: string | null;
/** The Domains extension's name for the primary allocation, when there is one. */
domain?: string | null;
ports: Port[];
}

Expand Down
35 changes: 21 additions & 14 deletions src/client/components/ConnectBar.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Check, Copy, Gamepad2 } from 'lucide-react';
import { toast, type SdkServer as Server } from '@pterodactyl/sdk';
import { Button, toast, type SdkServer as Server } from '@pterodactyl/sdk';
import { connectQuery } from '../api';

const BUTTON =
'rxcb:inline-flex rxcb:min-h-9 rxcb:items-center rxcb:gap-2 rxcb:rounded-md rxcb:px-3 rxcb:py-1.5 rxcb:text-sm rxcb:font-medium rxcb:no-underline rxcb:transition-colors rxcb:focus-visible:outline-2 rxcb:focus-visible:outline-ring';
const LABEL = 'rxcb:inline-flex rxcb:items-center rxcb:gap-2';

/** The core primary Button's look, for the Join link (a real link, so it can be copied or opened elsewhere). */
const PRIMARY_LINK =
'rxcb:relative rxcb:inline-block rxcb:rounded-sm rxcb:border rxcb:px-4 rxcb:py-2 rxcb:text-sm rxcb:uppercase rxcb:tracking-wide rxcb:no-underline rxcb:transition-colors rxcb:duration-150 rxcb:border-primary rxcb:bg-primary rxcb:text-primary-foreground rxcb:[&:hover]:border-primary rxcb:[&:hover]:bg-primary/80 rxcb:[&:active]:border-primary/70 rxcb:[&:active]:bg-primary/70';

/** Join and Copy address buttons above the console, with the server's other ports and their notes. */
export default function ConnectBar({ data: server }: { data: Server }) {
Expand All @@ -29,23 +32,27 @@ export default function ConnectBar({ data: server }: { data: Server }) {
const others = data.ports.filter((port) => !port.is_default);

return (
<div className='rxcb:mb-4 rxcb:flex rxcb:flex-wrap rxcb:items-center rxcb:gap-2'>
<div className='rxcb:mt-0 rxcb:mb-3 rxcb:flex rxcb:flex-wrap rxcb:items-center rxcb:gap-2'>
{data.url && (
<a href={data.url} className={`${BUTTON} rxcb:bg-primary rxcb:text-primary-foreground rxcb:hover:opacity-90`}>
<Gamepad2 size={16} aria-hidden='true' />
Join server
<a href={data.url} className={PRIMARY_LINK}>
<span className={LABEL}>
<Gamepad2 size={16} aria-hidden='true' />
Join server
</span>
</a>
)}
{data.address && (
<button
type='button'
<Button
isSecondary
className='rxcb:max-w-full'
onClick={() => void copy()}
className={`${BUTTON} rxcb:border rxcb:border-border rxcb:bg-card rxcb:text-card-foreground rxcb:hover:bg-accent rxcb:hover:text-accent-foreground`}
aria-label={copied ? 'Copied' : `Copy address ${data.address}`}
>
{copied ? <Check size={16} aria-hidden='true' /> : <Copy size={16} aria-hidden='true' />}
<span className='rxcb:font-mono'>{data.address}</span>
<span className='rxcb:sr-only'>{copied ? 'Copied' : 'Copy address'}</span>
</button>
<span className={LABEL}>
{copied ? <Check size={16} aria-hidden='true' /> : <Copy size={16} aria-hidden='true' />}
<span className='rxcb:font-mono rxcb:break-all rxcb:normal-case rxcb:tracking-normal'>{data.address}</span>
</span>
</Button>
)}
{others.length > 0 && (
<ul className='rxcb:m-0 rxcb:flex rxcb:list-none rxcb:flex-wrap rxcb:gap-x-4 rxcb:gap-y-1 rxcb:p-0 rxcb:text-sm rxcb:text-muted-foreground'>
Expand Down
46 changes: 46 additions & 0 deletions src/client/connect.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,49 @@ test('nothing shows when the egg is set to no buttons', async () => {

await waitFor(() => expect(container.textContent).toBe(''));
});

test('Join is a link styled as the primary button and Copy a secondary core button', async () => {
host.queryClient.setQueryData(key, {
type: 'steam',
url: 'steam://connect/203.0.113.10:28015',
address: '203.0.113.10:28015',
ports: [],
});
const { container } = render(<ConnectBar data={server} />, { wrapper: host.Wrapper });

const join = (await screen.findByText('Join server')).closest('a')!;
const copy = screen.getByRole('button', { name: /Copy address/ });
expect(join.getAttribute('href')).toBe('steam://connect/203.0.113.10:28015');
expect(join.className.split(' ')).toEqual(expect.arrayContaining(['rxcb:bg-primary', 'rxcb:px-4', 'rxcb:py-2', 'rxcb:uppercase']));
expect(copy.className).toContain('bg-transparent');
expect(copy.className.split(' ')).not.toContain('bg-primary');
expect((container.firstElementChild as HTMLElement).className).toContain('rxcb:mb-3');
});

test('a domain with an SRV record is shown without the port', async () => {
host.queryClient.setQueryData(key, {
type: 'minecraft',
url: null,
address: 'mc.example.com',
domain: 'mc.example.com',
ports: [{ address: 'mc.example.com:25575', notes: 'RCON', is_default: false }],
});
render(<ConnectBar data={server} />, { wrapper: host.Wrapper });

expect(await screen.findByText('mc.example.com')).toBeTruthy();
expect(screen.getByText('mc.example.com:25575')).toBeTruthy();
});

test('a domain without an SRV record keeps the port in Join and Copy', async () => {
host.queryClient.setQueryData(key, {
type: 'steam',
url: 'steam://connect/rust.example.com:28015',
address: 'rust.example.com:28015',
domain: 'rust.example.com',
ports: [],
});
render(<ConnectBar data={server} />, { wrapper: host.Wrapper });

expect(await screen.findByText('rust.example.com:28015')).toBeTruthy();
expect(screen.getByText('Join server').closest('a')!.getAttribute('href')).toBe('steam://connect/rust.example.com:28015');
});
Loading