# Sculk Backend Plugin Format v1

Format v1 is **stable** (`"x-stability": "stable"` in `packages/plugins/schema/plugin-v1.schema.json`, locked by `packages/plugins/schema/v1.sha256`). A later change to format 1 may only add optional fields; anything else is format 2.

---

## Top-Level Fields

A plugin document is a strict JSON object (`PluginV1`) with ten top-level fields:

### `format`

Literal integer `1`. Identifies the plugin schema revision.

### `id`

Plugin identifier matching `^[a-z0-9][a-z0-9-]{0,63}$` (for example, `"pufferpanel"` or `"pterodactyl"`).

### `kind`

Literal string `"backend"`.

### `name`

Human-readable plugin display name (`1..100` characters).

### `connection`

Map of connection fields (`Record<name, { type: "url" | "text" | "secret" }>`) supplied by the caller when connecting to a panel instance. Must include `"baseUrl": { "type": "url" }`. Fields marked `"secret"` may only be referenced inside the `request` and `apply` blocks of their own credential in `auth`.

### `vars`

Map of input variable definitions (`Record<name, VarShape>`). Defaults to `{}`. Every variable referenced in an action's steps must be declared in `vars`.

### `auth`

Optional map of named credentials (`Record<name, Credential>`). Each entry defines either a `"token"` credential or a `"static"` credential.

### `fetch`

Optional outbound allowlist `{ "allowHosts": ["..."] }` (defaults to `{ "allowHosts": [] }`).

### `capabilities`

Array of capability identifiers declared by the plugin:

- `"power"` — requires actions `start`, `stop`, `kill`
- `"status"` — requires action `status`
- `"players"` — requires action `players`
- `"files"` — requires actions `listDir`, `mkdir`, `readFile`, `writeFile`, `uploadFile`, `deleteFile` (and optional `moveFile`, `backupFile` and `restoreFile`, which take root names `^\.sculk-…` for `from`, `backup` and `scratch`; a contract variable with a fixed pattern must declare exactly that pattern, and optional `sftpDetails`, which reads the host and port the panel's SFTP service listens on and extracts `sftp` as `{ "host": ..., "port": ... }`; the Files tab shows SFTP details only for a plugin that has it)
- `"console"` — requires action `sendCommand`
- `"logs"` — requires action `readLog`, which reads the server's console output without sending anything. It takes `serverId` and an integer `since` (`0` for the whole log, or the `cursor` of the last read) and extracts `cursor`, the value to pass as `since` next time, and `text`, the output since `since`. A plugin whose panel cannot read the console over HTTP leaves `logs` out: Pterodactyl does, because its console is a websocket. This capability is optional, and sculk.network shows no console for a plugin without it.
- `"stats"` — requires action `stats`, which reads the resources the server uses right now. It takes `serverId` and extracts `cpuPercent`, a number where `100` is one full core, and `memoryBytes`, the memory in use in bytes. sculk.network samples every bound server every 30 seconds, and every 5 seconds while someone watches it, and draws the history, so the action must be one cheap `GET`. A panel that reports zeros for a stopped server is fine: sculk.network does not call `stats` for a server it knows is stopped. This capability is optional, and sculk.network shows no resource graphs for a plugin without it.
- `"create"` — requires actions `createServer`, `deleteServer` (and optional `listNodes`, `listEggs`, `listAllocations`)
- `"downloadUrl"` — requires action `downloadFromUrl`

Every contract action present in `actions` requires its declared capability to be listed in `capabilities` (except `listServers`, which is always required and has no capability) and must match the exact variable types and extracted outputs required by `ACTIONS`.

### `actions`

Map of action definitions (`Record<name, { auth?: string, steps: Step[] }>`). Each action declares:

- `auth` (optional when `auth` has one entry; required on the action or per step when `auth` has multiple entries): default credential name for `path` steps in this action.
- `steps`: non-empty array of step objects (`request`, `poll`, or `merge`).

---

## Variable Shapes (`vars`)

Every variable declared in `vars` uses one of the eight shapes in `VarShape`. Variable values are validated by `parseVar` before any network request is made and are **never re-templated**.

| Shape | Schema Fields | Validation Rules | Allowed Template Slots |
| :--- | :--- | :--- | :--- |
| `pattern` | `{ type?: "pattern", pattern: string }` | String matching `^(?:<pattern>)$`, no `\r`, `\n`, or `\0`. | URL path segment, query value, header value, JSON whole value or substring, multipart `filename`. |
| `enum` | `{ type: "enum", values: [string, ...] }` | String equal to one of `values`, no `\r`, `\n`, or `\0`. | URL path segment, query value, header value, JSON whole value or substring. |
| `integer` | `{ type: "integer", min?: number, max?: number }` | Safe integer `n` (`min <= n <= max`), no `\r`, `\n`, or `\0`. | URL path segment, query value, header value, JSON whole value (substituted as a JSON number) or substring. |
| `relpath` | `{ type: "relpath" }` | Relative POSIX path, no leading `/`, no `\`, no drive letter, no `\r`, `\n`, `\0`, no empty or `.` / `..` segment (including after percent-decoding). Supports `{{dirname x}}` and `{{basename x}}`. | URL path segment, query value, header value, JSON whole value or substring, multipart `filename` (via `{{basename x}}`). `{{dirname x}}` and `{{basename x}}` are allowed in `path`, `url`, `query`, and `body`. |
| `url` | `{ type: "url", allowHosts: [string, ...] }` | Valid `https://` URL with no credentials (`username`/`password`), no explicit port, no `\r`, `\n`, `\0`, and host matching `allowHosts`. Supports `{{basename x}}` in `body`. | Query value, header value, `body` (JSON whole value or substring, `body.text`, `body.form`), `auth`. |
| `text` | `{ type: "text", maxLength?: number }` | UTF-8 string with length (`string.length`) `<= maxLength`, no `\0`. CR and LF pass through unchanged. | `body` (`body.text`, `body.json`, `body.form`). |
| `bytes` | `{ type: "bytes", maxBytes?: number }` | `Uint8Array` (or UTF-8 string) with `byteLength <= maxBytes`. | `body.bytes` (`"bytes": "{{var}}"`) or `body.multipart.bytes` (`"bytes": "{{var}}"`). |
| `map` | `{ type: "map", keyPattern: string, valuePattern: string, maxEntries: number }` | Plain JSON object with `<= maxEntries` entries, string keys matching `keyPattern`, string values matching `valuePattern`, and no `\r`, `\n`, or `\0` anywhere. | Whole JSON value in `body.json` only (`"environment": "{{environment}}"`). Values are never templated again. |

### Patterns that load

Patterns use **RE2 syntax** and run on RE2 (the `re2js` port), whose matching time is linear in the value. Each `pattern`, `keyPattern` and `valuePattern` is compiled as `^(?:<pattern>)$` when the plugin loads, in every plugin. A pattern that fails fails with `plugin_invalid` at `/vars/<name>`:

- Longer than 200 characters: `has a pattern longer than 200 characters`.
- Not valid RE2: `has a pattern RE2 cannot compile (<reason>)`. RE2 has **no backreferences** (`\1`, `\k<name>`) and **no lookarounds** (`(?=`, `(?!`, `(?<=`, `(?<!`), and a repeat count is at most 1000, so write `^[^\r\n]{1,1000}[^\r\n]{0,24}$` instead of `^[^\r\n]{1,1024}$`.

Where RE2 differs from JavaScript:

- **Patterns count code points, not UTF-16 units.** `.`, `[^…]`, `\S`, `\W` and `\PL` match one whole character, so a bounded repeat counts characters outside the Basic Multilingual Plane, such as emoji, once each. `^[^\r\n]{1,64}$` accepts 64 emoji, which are 128 UTF-16 units; JavaScript would refuse them. The 256-character value cap for user plugins counts UTF-16 units, as before.
- `\s` is ASCII whitespace only (`[\t\n\f\r ]`) and does not match U+00A0 or U+2028.
- `.` matches U+2028 and U+2029; JavaScript's `.` does not. Like JavaScript, it does not match `\n`.
- `\w` and `\d` match the same ASCII sets as in JavaScript.

A plugin a user installed has more limits. Each bounds how long the service spends compiling the plugin's patterns and checking a value against them. With all of them, on the 16-CPU machine the limits were measured on, the worst plugin found loads in about 16 ms, refusing a pattern takes about 1 ms, and the worst single check of a value takes about 10 ms (9.4 ms at the 99th percentile). A smaller machine takes proportionally longer.

- A pattern must follow the user grammar below. sculk.network parses it before RE2 sees it, and the first construct outside the grammar fails with `has a pattern outside the user grammar: <construct> at character <n> is not allowed in a user pattern`. An inline flag or a named group fails with `has a pattern with a `(?` group other than `(?:`; a user plugin may not set inline flags such as (?i), (?s), (?m) or (?U), or use named groups`, and `\p` or `\P` with `has a pattern with a Unicode property class; a user plugin may not use \p or \P`.
- Each pattern may compile to at most 1024 RE2 instructions. RE2 stays linear above that, but its work per character grows with the program. While parsing, sculk.network estimates the size, counting each atom times every repeat around it and never less than RE2 builds; an estimate over 4096 fails at once with `has a pattern that would compile to more than 1024 RE2 instructions`, so a pattern such as `(?:()()…){1000}` costs nothing to refuse. A pattern under that estimate is compiled, and one that still compiles to more than 1024 fails with `has a pattern that compiles to <n> RE2 instructions, more than 1024`. The estimate overcounts, so a pattern that repeats a large group many times may be refused even though it would fit; split it or use a smaller repeat. The bundled plugins' patterns other than Pterodactyl's `startup` compile to between 14 and 518 instructions.
- All its patterns together (`pattern`, `keyPattern` and `valuePattern`) may compile to at most 4096 instructions. They compile in the order the variables are declared, and the first variable that takes the total past 4096 fails with `brings the plugin's patterns to <n> RE2 instructions, more than 4096`. A user's own copy of PufferPanel fits, and so does one of Pterodactyl once its `startup` pattern is `^[^\r\n]{1,256}$`, the most a user value can hold anyway.
- At most 64 variables may carry a pattern. The 65th fails with `is pattern variable 65, more than 64`.
- Each string value of a `pattern` or `map` variable may be at most 256 characters. A longer value fails with `var_invalid` and rule `pattern: longer than 256 characters` before the pattern runs.

Bundled plugins and the plugins in `SCULK_PLUGIN_DIR` keep the bounds their own patterns set, and are not held to the user grammar.

#### The user grammar

A pattern in a plugin a user installed is made only of these:

- **Literals:** any character other than the metacharacters `\ . ^ $ | ( ) [ ] { } * + ?`. Other characters, such as `-`, `/`, `:` and non-ASCII letters, are literals as they are.
- **Escapes, from a fixed set:** `\d \D \w \W \s \S`; `\n \r \t`; and an escaped metacharacter, `\-` or `\/`, such as `\.` or `\(`. Every other escape is refused, including `\Q`, `\E`, `\x`, `\p`, `\P`, `\b`, `\B`, `\A`, `\z`, octal and `\C`.
- **`.`, `^` and `$`.**
- **Classes `[…]` and `[^…]`** with at least one member. A member is a single character, an escape from the set above, or a range `a-z` between two single characters with the start not after the end. `-` is a member only first, last or escaped; `]` and `[` only escaped, so POSIX classes such as `[[:alpha:]]` are refused.
- **Groups** `(…)` and `(?:…)`. Every other `(?`, including named groups, is refused.
- **Alternation** `|`.
- **Repeats** after an atom: `*`, `+`, `?`, `{n}`, `{n,}` and `{n,m}`, optionally followed by `?` for a non-greedy repeat. Counts are plain decimal numbers with no leading zero and no spaces, at most 1000, with `n` not above `m`. A repeat may not directly follow another repeat (`a**`, `a{2}{3}`), and nested counts may not multiply past 1000, as in RE2.

Every bundled pattern follows this grammar, so a user's own copy of a bundled plugin loads.

---

## Credential Kinds (`auth`)

`auth` maps credential names (`^[A-Za-z][A-Za-z0-9_]*$`) to one of two credential kinds:

1. **`token`** (`kind: "token"`):
   - `request`: `BareRequest` (`method`, `path`, optional `query`, `headers`, `body` (`text` or `form`), `accept`, `timeoutMs`, `response`; `url`, `body.json`, and `body.multipart` are not allowed in `auth`)
   - `extract`: `{ token: string, ttl: string }` (JSONPath expressions against the token response)
   - `apply`: `{ headers: Record<string, string> }` referencing `{{token}}`
   - Cached per `(plugin, credentialName, connection)` (keyed via HMAC-SHA256) and refreshed 60 seconds before expiry. A `401` on a step drops and refreshes only that step's credential token, then retries once.
2. **`static`** (`kind: "static"`):
   - `apply`: `{ headers: Record<string, string> }` referencing connection secrets owned by that credential (for example, `"Authorization": "Bearer {{applicationKey}}"`).
   - Each credential owns the `secret` connection fields referenced in its own `request` and `apply` blocks (collected on a first pass over `auth`, with no field-name heuristics). A secret field may be owned by at most one credential and may only appear inside that credential's `request` and `apply` blocks; referencing it in another credential or in an action step (or referencing an unowned secret in a step) fails at load with `plugin_invalid`.

---

## Step Kinds (`steps`)

Every step in an action's `steps` array has optional `auth?: string` and exactly one of `request`, `poll`, or `merge`:

### 1. `request`

Executes a single HTTP request (`{ auth?: string, request: Request }`):

- `method`: `"GET" | "POST" | "PUT" | "PATCH" | "DELETE"`.
- `path` or `url` (mutually exclusive):
  - `path`: relative path starting with `/` resolved against `connection.baseUrl`. Sends the step's resolved credential headers.
  - `url`: template starting with `"{{urlVar}}"` where `urlVar` was extracted earlier in the action with `as: "url"`. Sends **no** panel `auth` headers.
- `query` (optional): `Record<string, string>`.
- `headers` (optional): `Record<HeaderName, string>`.
- `body` (optional): strict object with exactly one of:
  - `json`: arbitrary JSON value.
  - `text`: `"{{textVar}}"` from a `text` variable.
  - `bytes`: `"{{bytesVar}}"` from a `bytes` variable.
  - `form`: `Record<string, string>` (`application/x-www-form-urlencoded`).
  - `multipart`: `{ field: string, filename: string, bytes: "{{bytesVar}}" }` (`multipart/form-data` upload where `filename` takes a `pattern` variable or `{{basename x}}` of a `relpath` variable, and `bytes` takes a `bytes` variable).
- `accept`: non-empty array of HTTP status codes (`100..599`).
- `timeoutMs` (optional): request timeout in milliseconds (`1..3600000`).
- `response` (optional): `"json" | "text" | "bytes"`.
- `extract` (optional): `Record<Name, Extract>` storing values into the action scope and outputs.
- `optional` (optional): boolean; when `true` and the response status is `204`, extraction is skipped instead of failing on an empty body.

### 2. `poll`

Repeatedly runs a request until `until` matches or `failWhen` / `timeoutMs` triggers (`{ auth?: string, poll: Poll }`):

- `request`: `Request` executed on each poll attempt.
- `until`: `{ status: number[] }`, `{ json: string, equals: Json }`, or `{ json: string, contains: string }`. `contains` is a template; the condition holds when the value at `json` equals it or, for an array (such as `$[*].name` of a folder listing), includes it.
- `failWhen` (optional): `{ status: number[], request?: BareRequest }` or `{ json: string, equals: Json, request?: BareRequest }`. When matched (or when its optional `request` matches), aborts polling with `poll_failed`.
- `intervalMs`: delay between attempts in milliseconds (`1..3600000`).
- `timeoutMs`: maximum total poll time in milliseconds (`1..3600000`).

### 3. `merge`

Fetches a JSON document and merges keys into it before storing the result in a step variable (`{ auth?: string, merge: Merge }`):

- `request`: `BareRequest` that fetches the source JSON object.
- `set`: `Record<string, Json>` mapping dot-separated paths (`a.b.c`, rejecting empty segments and `__proto__`, `constructor`, and `prototype`) to templated JSON values.
- `into`: step variable name (`Name`) that receives the merged JSON object for use in a subsequent `request` step's `body.json`.

---

## Extract Paths and `as` Tags

Each entry in `extract` is one of:

- A JSONPath string (`"attributes.id"`, `"data[*].attributes"`, `"$"`).
  - Dot-separated segments (`a.b.c`), integer indices (`items[0].id`), and the `[*]` wildcard (`data[*].attributes.fqdn`) are supported.
  - When `[*]` appears in a path, extraction maps across the array and produces an array of extracted values.
  - `"$"` extracts the entire response payload (including raw `Uint8Array` when `response: "bytes"`).
- `{ path: string, equals: Json }` — extracts a boolean (`true` when the value at `path` equals `equals`, `false` otherwise).
- `{ path: string, as: "url" | "nodeHost" | "base64" }`:
  - `as: "url"`: marks the variable as a signed URL for a later `url` step (validated as a URL when that step builds its request) and redacts its query string in `trace` as `?<redacted>`.
  - `as: "nodeHost"`: extracts a host string or (with `[*]`) an array of host strings and adds every host in it to the run's allowed node hosts.
  - `as: "base64"`: decodes the extracted base64 string to UTF-8 text. A value that is not a base64 string fails the run with `response_invalid`. PufferPanel returns its console this way, so `readLog` reads `{ "path": "logs", "as": "base64" }`.
- `{ path: string, fields: Record<Name, string> }` — renames values to the names an action contract expects. Each `fields` entry maps an output field to a JSONPath read relative to the value at `path`. When that value is an array (such as `data[*].attributes`), each item becomes an object holding only the named fields; otherwise the value itself does. A missing field fails the run with `response_invalid`. Pterodactyl's `listServers` uses `{ "path": "data[*].attributes", "fields": { "id": "identifier", "name": "name" } }`, because the client API names the server id `identifier`.

---

## Template Rules

1. **Typed whole-value substitution**: In `body.json` and `merge.set`, a string consisting of a single `"{{var}}"` placeholder evaluates to the variable's typed value (`integer` becomes a JSON number, `map` becomes a JSON object, `into` / extracted values keep their structure).
2. **Per-segment path encoding**: In `path`, each `{{var}}` is URL-encoded per path segment (`encodeURIComponent` for scalar variables; per-segment encoding joined by `/` for `relpath`, with `{{dirname x}}` and `{{basename x}}` helpers).
3. **No re-templating of values**: Variable values are substituted once and never templated again. A Pterodactyl startup line such as `java -Xmx{{SERVER_MEMORY}}M` passes through as literal text.

---

## Fetch Boundary Rules

All HTTP requests go through `packages/plugins/src/boundary.ts`:

- A `path` request may only contact `connection.baseUrl`. A `url` request may only contact `connection.baseUrl`, `fetch.allowHosts`, or a host extracted during the same run with `as: "nodeHost"`. Any other host fails with `host_blocked` before sending a request.
- Resolved IP addresses are checked against the address guard (`unspecified`, `private`, `cgnat`, `loopback`, `link-local`, `site-local`, `benchmarking`, `multicast`, `broadcast`, `nat64-local`), failing with `address_blocked` when disallowed.
- Redirects are followed up to 3 hops only when the target host is allowed and the scheme does not downgrade from `https:` to `http:`; otherwise the request fails with `redirect_blocked` (`host not allowed`, `scheme downgrade`, or `too many redirects`). Cross-origin redirects strip `Authorization` and credential headers.
- Signed URLs (`as: "url"`) never carry panel `auth` headers, and their query strings are replaced with `?<redacted>` in `trace`.

---

## Run Error Codes

Every load or run failure returns `{ ok: false, error: RunError }` with one of these 12 `code` values:

- `plugin_invalid` — schema validation, capability contract, credential isolation, or template slot check failed (`{ code: "plugin_invalid", pointer, message }`).
- `var_invalid` — input variable failed `parseVar` (`{ code: "var_invalid", var, rule }`).
- `host_blocked` — target host is outside the allowlist and run node hosts (`{ code: "host_blocked", host }`).
- `address_blocked` — resolved IP address is blocked by the address guard (`{ code: "address_blocked", host, address, reason }`).
- `redirect_blocked` — redirect was rejected (`{ code: "redirect_blocked", host, reason }`).
- `auth_failed` — token request returned a non-accepted status, returned a token with control characters, or a step still returned `401` after refreshing the token (`{ code: "auth_failed", status?, reason? }`).
- `status_unexpected` — step returned an HTTP status outside `accept` (`{ code: "status_unexpected", step, status?, body }`).
- `timeout` — single HTTP request timed out (`{ code: "timeout", step }`).
- `poll_timeout` — `poll` step exceeded `timeoutMs` (`{ code: "poll_timeout", step, attempts }`).
- `poll_failed` — `poll` step matched `failWhen` (`{ code: "poll_failed", step, failWhen }`).
- `response_invalid` — response body was invalid JSON or missed a required `extract` path (`{ code: "response_invalid", step, reason }`).
- `aborted` — the caller's `beforeRequest` hook refused the next request, so the action stopped before sending it (`{ code: "aborted", reason }`).

---

## Complete Example

```json plugin
{
  "format": 1,
  "id": "example-panel",
  "kind": "backend",
  "name": "Example Panel",
  "connection": {
    "baseUrl": { "type": "url" },
    "apiKey": { "type": "secret" }
  },
  "vars": {
    "serverId": { "type": "pattern", "pattern": "^[0-9a-f]{8}$" },
    "command": { "type": "pattern", "pattern": "^[^\\r\\n]{1,256}$" }
  },
  "auth": {
    "panel": {
      "kind": "static",
      "apply": {
        "headers": {
          "Authorization": "Bearer {{apiKey}}"
        }
      }
    }
  },
  "capabilities": ["status", "console"],
  "actions": {
    "listServers": {
      "auth": "panel",
      "steps": [
        {
          "request": {
            "method": "GET",
            "path": "/api/client",
            "accept": [200],
            "extract": {
              "servers": "data[*].attributes"
            }
          }
        }
      ]
    },
    "status": {
      "auth": "panel",
      "steps": [
        {
          "request": {
            "method": "GET",
            "path": "/api/client/servers/{{serverId}}/resources",
            "accept": [200],
            "extract": {
              "running": {
                "path": "attributes.current_state",
                "equals": "running"
              }
            }
          }
        }
      ]
    },
    "sendCommand": {
      "auth": "panel",
      "steps": [
        {
          "request": {
            "method": "POST",
            "path": "/api/client/servers/{{serverId}}/command",
            "body": {
              "json": {
                "command": "{{command}}"
              }
            },
            "accept": [204]
          }
        }
      ]
    }
  }
}
```
