Giter VIP home page Giter VIP logo

pterojs's Introduction

PteroJS

A verbose API library for Pterodactyl

About

PteroJS is a verbose API library for the Pterodactyl Game Panel designed to give developers full access and control over the API without having to compromise on code quality or efficiency.

Installing

If you are using Node.js (v14.x and above):

npm install @devnote-dev/pterojs
yarn add @devnote-dev/pterojs

or if you are using Deno:

import pterojs from 'https://cdn.skypack.dev/@devnote-dev/pterojs';

Please join the support server if you experience any issues with installing the package.

Compatibility

Note that you can use older versions of PteroJS with newer versions of Pterodactyl and Wings, but they will not be up-to-date with the latest features and fixes.

PteroJS Panel Wings
โŒ <= 0.7 <= 1.5
1.3.0 1.6.5 >= 1.7.0 ~1.6.0
1.4.2 1.7.0 >= 1.8.1 ~1.6.0
2.0.1 ^1.9.0 ^1.7.0
2.1.0 ^1.10.0 ^1.7.0

Setting Up

PteroJS uses separate classes for the client and application sides of the Pterodactyl API.

Using the application API

const { PteroApp } = require('@devnote-dev/pterojs');

// Initialising the application
const app = new PteroApp('your.domain.name', 'pterodactyl_api_key');

// Accessing information
app.servers.fetch(4).then(console.log);

Using the client API

const { PteroClient } = require('@devnote-dev/pterojs');

// Initialising the client
const client = new PteroClient('your.domain.name', 'pterodactyl_api_key');

// Adding the server to listen for
const shard = client.addSocketServer('f7eca02e');

// Listening to events
shard.on('statusUpdate', (status) => {
    console.log(`server ${shard.id} status: ${status}`);
});

// Connecting to the server
shard.connect();

Migrations

Checkout the new migrations guide to PteroJS v2!

Contributing

Please see the issues section for contributing ideas. New ideas/features are also welcome.

  1. Fork this repo!
  2. Make a branch from main (git branch -b <new-feature>)
  3. Commit your changes (git commit -am "...")
  4. Open a PR here (git push origin <new-feature>)

Contributors

This repository is managed under the MIT license.

ยฉ 2021-present PteroPackages

pterojs's People

Contributors

blackdemonfire avatar cainthebest avatar chelog avatar devnote-dev avatar enxg avatar linux123123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

pterojs's Issues

bug: emitters not working

For some strange reason, the emit functions in RestRequestManager throw an internal Node error, they've been commented out currently for functionality.

TypeError: domain.enter is not a function
    at RestRequestManager.emit (node:domain:536:10)
    at RestRequestManager.debug (C:\...\PteroJS\src\http\RestRequestManager.ts:41:15)
    at RestRequestManager._make (C:\...\PteroJS\src\http\RestRequestManager.ts:65:14)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

//super.emit('debug', message);

Permissions: 4x Flags

Currently the Permission flags go up to 43, with permissions between 35 and 40 being unknown or undocumented permissions, and 40+ being administrative permissions. Permission 40 is currently parsed as a non-administrative permission, however it should be changed to:

  • Represent all permissions; or
  • Represent all administrative permissions.

Please let me know what you think of this change. ๐Ÿ‘

Ratelimit system

Currently there is no proper ratelimit system for HTTP requests, all 4xx responses are treated as PteroAPIErrors and are subsequently thrown. Ratelimit responses should be a special case which suspends all requests until the ratelimit is over, this can be tracked via the X-Ratelimit-Limit and X-Ratelimit-Remaining headers.

ESM Support

Currently this package does not support ESM. It would be great if this functionality is added. gen-esm-wrapper can be used to generate ESM bindings.

Error Abstraction

Abstracting errors to their own classes is a popular and common error structure in a lot of libraries and is a standard in certain programming languages like Java. Currently, PteroJS groups all API errors under PteroAPIError, following this structure we would abstract PteroAPIError and have AuthorizationError for 401/403 responses, ValidationError will extend this for 422 responses, and a series of other error classes for various parts of the API.

Thoughts?

WS authentication failure should throw an error

Currently when a websocket authentication fails, there is no indication of this to the end-user, and the websocket connection will stay alive despite not receiving anything from the server. Instead, the websocket should throw an error when authentication fails. This would mean that Shard#launch() would now be error-prone, I'm not sure if that should be considered a breaking change.

Fetching server causes a "maximum call stack size exceeded" error

When used in NextJS's API Handlers

import { type NextApiRequest, type NextApiResponse } from "next";
import { pteroAdmin } from "~/server/pterodactyl";

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  return res.status(200).json(await pteroAdmin.servers.fetch("test"));
};

export default handler;

Issue is specific to NextJS, same does not occur when Node alone is used.

const { PteroApp } = require("@devnote-dev/pterojs");

const pteroAdmin = new PteroApp(
  "https://panel.",
  ""
);

pteroAdmin.servers
  .fetch("test")
  .then((servers) => {
    console.log(servers);
  })
  .catch((error) => {
    console.error(error);
  });

The issue seems to stem from the function "toSnakeCase"

error - Error [RangeError]: Maximum call stack size exceeded
    at toSnakeCase (file:///home/.../node_modules/@devnote-dev/pterojs/dist/index.mjs:300:21)
    at toSnakeCase (file:///home/.../node_modules/@devnote-dev/pterojs/dist/index.mjs:323:11)
    at toSnakeCase (file:///home/.../node_modules/@devnote-dev/pterojs/dist/index.mjs:323:11)
    ...
    digest: undefined
}

`app.allocations.fetchAvailable(1, true);` gives me "404: The requested resource could not be found on the server." - Uncaught PteroAPIError Error

ERROR:

(node:20352) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
(Use `node --trace-warnings ...` to show where the warning was created)
index.js:279
Uncaught PteroAPIError Error: 
- 404: The requested resource could not be found on the server.
    at handleError (file:///C:/Users/Admin/node_modules/@devnote-dev/pterojs/dist/index.js:1568:11)
    at <anonymous> (file:///C:/Users/Admin/node_modules/@devnote-dev/pterojs/dist/index.js:1517:62)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
Process exited with code 1

CODE (pretty much the code in the example):

const { PteroApp } = require('@devnote-dev/pterojs');

const app = new PteroApp(
    'https://mc.abysl.dev/', // <-- this is the panel, the node is at http://mc.abysl.dev:8080/
    'REDACTED'
);

(async () => {
    const alloc = await app.allocations.fetchAvailable(1, true);
    const server = await app.servers.create({
        name: 'Welcome',
        user: 1,
        egg: 5,
        dockerImage: 'ghcr.io/pterodactyl/yolks:java_18',
        startup:
            'java -Xms128M -XX:MaxRAMPercentage=95.0 -Dterminal.jline=false -Dterminal.ansi=true -jar {{SERVER_JARFILE}}',
        environment: {
            MINECRAFT_VERSION: 'latest',
            SERVER_JARFILE: 'server.jar',
            DL_PATH: '',
            BUILD_NUMBER: 'latest'
        },
        limits: {
            cpu: 1000,
            memory: 8192,
            swap: 0,
            disk: 4096,
            io: 200
        },
        featureLimits: {
            allocations: 0,
            backups: 1,
            databases: 0,
        },
        allocation: {
            default: alloc.id,
        },
    });

    console.log(server);
})();

Anything obvious I'm missing? I'm not sure why it's not working, is there something I need to install on the server? When I try the wing/node, it says unauthorized, with use and application keys. When I try the panel, it says not found, for user and application keys.

EDIT: If I type a port directly instead of using allocation, I do get "422: The selected allocation.default is invalid.". If I understand correctly (although I am a little sleep deprived), this means it's a problem with getting the ports. Since the server can respond with that, but when I try to get an allocation, it says 404 - another edit: confirmed, this. I can't get the allocations. It returns 404. Is there another way to choose one maybe? Works perfecty if I use an id from 3000 to 3999 and add 1 to it

Websocket connection attempt results in 403

Given code:

import { ClientServer, PteroClient } from '@devnote-dev/pterojs';

async function run() {
	const client = new PteroClient('https://mydomain.com', '-snip-', {
		ws: true,
	})

	client.on('debug', console.log)

	// I created PR to fix client.addSocketServer() thus using the hack
	client.ws.servers.push('d7d01832')
	client.on('serverOutput', (id, output) => {
		console.log({ id, output });
	})

	await client.connect()
}

run()

results in:

Error: Unexpected server response: 403
    at ClientRequest.<anonymous> (/path/to/myproject/node_modules/.pnpm/[email protected]/node_modules/ws/lib/websocket.js:852:7)
    at ClientRequest.emit (node:events:526:28)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:618:27)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
    at TLSSocket.socketOnData (node:_http_client:482:22)
    at TLSSocket.emit (node:events:526:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:228:10)
    at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23)
[ERROR] 19:11:15 Error: Unexpected server response: 403

Pterodactyl: 1.7.0 (latest)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.