# Write a panel plugin

sculk.network talks to a game panel only through a plugin: one JSON file that declares every request the panel may receive. In this tutorial we write a small plugin for a fake panel that runs on your machine, run it from the command line, and watch it refuse bad input before any request leaves.

You need Git, Node.js 22.18 or later and pnpm 11. [Format v1](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md) explains every field we use.

## Get the code

We clone the repository and install its dependencies.

```sh
git clone https://github.com/YellowUmbrellaDev/sculk.network.git
cd sculk.network
pnpm install
```

The install ends with:

```text
Done in <n>s using pnpm v11.<x>.<y>
```

## Start the fake panel

`dev/fake-panel/` is a small server that answers like PufferPanel. It accepts the client ID `fake-id` with the secret `fake-secret`, it already holds a server called `s1`, and it writes every request it gets to a log file.

Open a second terminal in the `sculk.network` folder and start it on port 47123:

```sh
node dev/fake-panel/server.mjs --port 47123 --log /tmp/toy-panel.log
```

```text
FAKE-PANEL url=http://127.0.0.1:47123 log=/tmp/toy-panel.log
```

Leave it running. Go back to the first terminal for the rest of the tutorial.

## Make a folder for the plugin

We keep our plugin outside the repository, in a folder next to it. A link named `toy` inside the repository points to it, so every command below runs from the `sculk.network` folder:

```sh
mkdir ../toy
ln -s ../toy toy
```

This prints nothing. `git status` lists the link as a new file. Don't commit it.

## Write the connection file

A connection holds the panel address and its credentials. sculk.network stores it encrypted. For the command line we write it to a file, `toy/conn.json`:

```json
{
  "baseUrl": "http://127.0.0.1:47123",
  "clientId": "fake-id",
  "clientSecret": "fake-secret"
}
```

## Write the plugin

Create `toy/plugin.json`:

```json
{
  "format": 1,
  "id": "toy",
  "kind": "backend",
  "name": "Toy Panel",
  "connection": {
    "baseUrl": { "type": "url" },
    "clientId": { "type": "text" },
    "clientSecret": { "type": "secret" }
  },
  "vars": {
    "serverId": { "type": "pattern", "pattern": "^[a-z0-9]{1,32}$" }
  },
  "auth": {
    "panel": {
      "kind": "token",
      "request": {
        "method": "POST",
        "path": "/oauth2/token",
        "body": {
          "form": {
            "grant_type": "client_credentials",
            "client_id": "{{clientId}}",
            "client_secret": "{{clientSecret}}"
          }
        },
        "accept": [200]
      },
      "extract": { "token": "access_token", "ttl": "expires_in" },
      "apply": { "headers": { "Authorization": "Bearer {{token}}" } }
    }
  },
  "fetch": { "allowHosts": [] },
  "capabilities": ["status"],
  "actions": {
    "listServers": {
      "steps": [
        { "request": { "method": "GET", "path": "/api/servers", "accept": [200], "extract": { "servers": "servers" } } }
      ]
    },
    "status": {
      "steps": [
        {
          "request": {
            "method": "GET",
            "path": "/api/servers/{{serverId}}/status",
            "accept": [200],
            "extract": { "running": { "path": "running", "equals": true } }
          }
        }
      ]
    }
  }
}
```

Here is what each part does:

- [`connection`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#connection) lists the fields of `conn.json`. A `secret` field can only appear in the `request` and `apply` blocks of its own credential in `auth`, so a plugin cannot leak it into a step URL or a log.
- [`vars`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#vars) declares `serverId` as a `pattern` variable. A value that does not match `^[a-z0-9]{1,32}$` stops the run before any request.
- [`auth`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#auth) trades the client ID and secret for a token at `/oauth2/token` and adds it to every later request.
- [`capabilities`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#capabilities) says what the plugin can do. `status` needs the `status` capability.
- [`actions`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#actions) holds one entry per thing sculk.network asks a panel. Every plugin has `listServers`. `status` reads `running` from the panel's answer and reports whether it equals `true`.

Check that the file is valid:

```sh
node dev/scripts/plugin.mjs validate toy/plugin.json
```

```text
valid (format 1, stable)
```

## Run the status action

```sh
node dev/scripts/plugin.mjs run toy/plugin.json status --conn toy/conn.json --var serverId=s1
```

```json
{"ok":true,"outputs":{"running":false}}
```

The fake panel's `s1` server is stopped, so `running` is `false`.

Look at what the panel received:

```sh
grep -o '"method":"[A-Z]*","rawUrl":"[^"]*"' /tmp/toy-panel.log
```

```text
"method":"POST","rawUrl":"/oauth2/token"
"method":"GET","rawUrl":"/api/servers/s1/status"
```

Exactly the two requests the plugin declares: one for the token, one for the status.

## Send a console command

A console command is one line of text. If the line could hold a newline, a caller could slip a second command after the first. We declare a `command` variable that refuses carriage returns and line feeds.

In `toy/plugin.json`, add `command` to `vars`:

```json
"vars": {
  "serverId": { "type": "pattern", "pattern": "^[a-z0-9]{1,32}$" },
  "command": { "type": "pattern", "pattern": "^[^\\r\\n]{1,256}$" }
},
```

add `console` to `capabilities`:

```json
"capabilities": ["status", "console"],
```

and add a `sendCommand` action next to `status` in `actions`:

```json
"sendCommand": {
  "steps": [
    {
      "request": {
        "method": "POST",
        "path": "/api/servers/{{serverId}}/console",
        "body": { "text": "{{command}}" },
        "accept": [204]
      }
    }
  ]
},
```

```sh
node dev/scripts/plugin.mjs validate toy/plugin.json
```

```text
valid (format 1, stable)
```

Send a command. Like PufferPanel, the fake panel refuses console commands while the server is stopped, so `s1` answers `500 ErrServerOffline` until it is started:

```sh
node dev/scripts/plugin.mjs run toy/plugin.json sendCommand --conn toy/conn.json --var serverId=s1 --var "command=say hi"
```

```json
{"ok":false,"error":{"code":"status_unexpected","step":"/actions/sendCommand/steps/0/request","status":500,"body":"{\"error\":\"ErrServerOffline\"}"}}
```

If you also add a `start` action (with capability `power`, `POST /api/servers/{{serverId}}/start?wait=true`, `accept: [204]`) and start `s1` first, `sendCommand` returns `{"ok":true,"outputs":{}}`.

Now try a command with a newline in it:

```sh
node dev/scripts/plugin.mjs run toy/plugin.json sendCommand --conn toy/conn.json --var serverId=s1 --var "command=$(printf 'say hi\nop Mallory')"
echo "exit $?"
```

```text
{"ok":false,"error":{"code":"var_invalid","var":"command","rule":"pattern: CR, LF or NUL"}}
exit 1
```

The run stops at the variable and names it. Nothing reaches the panel:

```sh
grep -c 'op Mallory' /tmp/toy-panel.log
```

```text
0
```

## Read the console

The `logs` capability reads what the server prints, so the creation page can show the install and the first start. It is optional: declare it only when the panel gives you the console over HTTP.

Add an integer `since` to `vars`, the capability `logs`, and a `readLog` action. PufferPanel answers `GET /api/servers/{id}/console?time=<since>` with `{ "epoch": <number>, "logs": "<base64>" }`, where `epoch` is the time of the read:

```json
"readLog": {
  "steps": [
    {
      "request": {
        "method": "GET",
        "path": "/api/servers/{{serverId}}/console",
        "query": { "time": "{{since}}" },
        "accept": [200],
        "extract": { "cursor": "epoch", "text": { "path": "logs", "as": "base64" } }
      }
    }
  ]
},
```

`cursor` is what the caller passes as `since` on its next read, so it receives only the new lines. A first read passes `0`.


## Read the resource use

The `stats` capability reads the CPU and memory the server uses, so the server page can draw their history. It is optional. Add the capability `stats` and a `stats` action. PufferPanel answers `GET /api/servers/{id}/stats` with `{ "cpu": <percent of one core>, "memory": <bytes>, ... }`:

```json
"stats": {
  "steps": [
    {
      "request": {
        "method": "GET",
        "path": "/api/servers/{{serverId}}/stats",
        "accept": [200],
        "extract": { "cpuPercent": "cpu", "memoryBytes": "memory" }
      }
    }
  ]
},
```

`cpuPercent` is `100` for one full core, so a server that uses three cores reads `300`. Pterodactyl reports the same unit as `cpu_absolute` under `attributes.resources` of `GET /api/client/servers/{id}/resources`.


## Read a file

A file path must stay inside the server's folder. The `relpath` shape refuses absolute paths and any `..` segment.

Add `path` to `vars`:

```json
"path": { "type": "relpath" }
```

add `files` to `capabilities`:

```json
"capabilities": ["status", "console", "files"],
```

and add a `readFile` action:

```json
"readFile": {
  "steps": [
    {
      "request": {
        "method": "GET",
        "path": "/api/servers/{{serverId}}/file/{{path}}",
        "accept": [200],
        "response": "bytes",
        "extract": { "content": "$" }
      }
    }
  ]
}
```

```sh
node dev/scripts/plugin.mjs validate toy/plugin.json
```

```text
valid (format 1, stable)
```

Ask for a file outside the server's folder:

```sh
node dev/scripts/plugin.mjs run toy/plugin.json readFile --conn toy/conn.json --var serverId=s1 --var path=../x
echo "exit $?"
```

```text
{"ok":false,"error":{"code":"var_invalid","var":"path","rule":"relpath: segment \"..\""}}
exit 1
```

Again the run stops before any request:

```sh
grep -c '/file/' /tmp/toy-panel.log
```

```text
0
```

## Clean up

Stop the fake panel with Ctrl+C in its terminal. Remove the log and the link. Keep `../toy` if you want your plugin:

```sh
rm /tmp/toy-panel.log toy
```

## Next steps

- [Format v1](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md) lists every field, every variable shape and every error code.
- [`plugins/pufferpanel/plugin.json`](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/plugins/pufferpanel/plugin.json) is a full plugin for a real panel. Compare it with yours.
- [Run Error Codes](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#run-error-codes) explains each `code` a failed run prints.

## Install your plugin and connect a server

So far we ran the plugin from the command line. Now we install it in sculk.network and connect a server through it. We use a development instance with the fake panel next to it, so this part needs Docker.

We start with the finished plugin of this tutorial, which also sends console commands:

```sh
mkdir -p toy
cp dev/fake-panel/toy.plugin.json toy/plugin.json
```

We start a lane with the fake panel:

```sh
pnpm lane up --with fakepanel
```

The last line names the lane number `<k>` and the address of the app:

```text
LANE k=<k> app=http://127.0.0.1:<port>
```

A plugin a user installs is never trusted to reach a private address, on any instance: its hosts, the panel address and every request it sends are checked, and a private, loopback or link-local address gets "This panel address isn't allowed". The fake panel runs on the lane's private network, so the `fakepanel` profile sets `SCULK_DEV_PLUGIN_HOSTS=fake-panel:8080` on the app, which lets user plugins reach exactly that `host:port` and nothing else. Never set it on an instance people use. A plugin for a panel on your own network goes in `SCULK_PLUGIN_DIR` instead, where the operator reviews it; see the self-hosting guide.

We open that address and press **Sign in**. The Sign in page lists the providers. We press **Continue with Google**, which opens the development sign-in page, and press `owner`. The account page opens.

We press **Plugins** on the account page. The Plugins page opens and says "You have not installed a plugin yet." We press **Upload file** and choose `toy/plugin.json`. The review shows:

- the name "Toy panel" and the id `toy`,
- under "Capabilities", `console` and `status`,
- under "Connection fields", `baseUrl`, `clientId` and `clientSecret`,
- under "Hosts this plugin may call", one line, "The panel URL you enter". Our plugin lists no other host.

We press **Install**. The list shows "Toy panel" with the id `toy`, "Uploaded file", the first 12 characters of its SHA-256, and "0 connections".

We ask the lane for the fake panel's values:

```sh
pnpm lane creds <k> fakepanel
```

```text
{"baseUrl":"http://fake-panel:8080","clientId":"lane","clientSecret":"lanesecret"}
```

We open `/new` and press "Add a connection" if the form is not open yet. The plugins are grouped by where they come from: "Included" for the ones sculk.network ships, "This instance" when the operator added some, and "Yours" for the ones we installed. We pick "Toy panel" under "Yours", which shows "Installed by you" and the same 12 characters. We enter the three values in **Panel URL**, **Client ID** and **Client secret** and press **Test**. It shows "Connected, 1 server". We press **Save**.

The list "Choose a panel server" shows `sculkmc`. We pick it, keep or change the name in **Server name**, and press **Connect server**. The server's connection settings open and name "Toy panel" as the plugin.

The connection is pinned to the exact file we installed. An update of the plugin moves the pin only after we review it and press **Update**, and an update that removes actions a connection needs to deploy is refused.

When we are done, we stop the lane:

```sh
pnpm lane down <k>
```
