ql-agent 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +69 -0
  2. package/package.json +15 -0
package/index.js ADDED
@@ -0,0 +1,69 @@
1
+ import axios from "axios";
2
+ import os from "os";
3
+ import fs from "fs";
4
+ import path from "path";
5
+
6
+ export function initAgent(config) {
7
+ const { relay, token, baseDir } = config;
8
+
9
+ let agentId = null;
10
+
11
+ async function register() {
12
+ const payload = {
13
+ hostname: os.hostname(),
14
+ platform: os.platform()
15
+ };
16
+
17
+ const res = await axios.post(relay + "/register", { payload }, {
18
+ headers: { "x-relay-token": token }
19
+ });
20
+
21
+ agentId = res.data.id;
22
+ }
23
+
24
+ async function heartbeat() {
25
+ if (!agentId) return;
26
+ await axios.post(relay + "/heartbeat", { id: agentId }, {
27
+ headers: { "x-relay-token": token }
28
+ });
29
+ }
30
+
31
+ function safePath(p) {
32
+ const full = path.resolve(baseDir, p);
33
+ if (!full.startsWith(baseDir)) throw new Error();
34
+ return full;
35
+ }
36
+
37
+ function execCommand(cmd) {
38
+ if (cmd.type === "read") {
39
+ return fs.readFileSync(safePath(cmd.path), "utf-8");
40
+ }
41
+
42
+ if (cmd.type === "write") {
43
+ fs.writeFileSync(safePath(cmd.path), cmd.content);
44
+ return "ok";
45
+ }
46
+
47
+ if (cmd.type === "delete") {
48
+ const f = safePath(cmd.path);
49
+ if (fs.existsSync(f)) fs.unlinkSync(f);
50
+ return "ok";
51
+ }
52
+ }
53
+
54
+ async function poll() {
55
+ if (!agentId) return;
56
+
57
+ const res = await axios.post(relay + "/fetch-commands", { id: agentId }, {
58
+ headers: { "x-relay-token": token }
59
+ });
60
+
61
+ for (const cmd of res.data) {
62
+ try { execCommand(cmd); } catch {}
63
+ }
64
+ }
65
+
66
+ setInterval(register, 15000);
67
+ setInterval(heartbeat, 10000);
68
+ setInterval(poll, 5000);
69
+ }
package/package.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "ql-agent",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [],
10
+ "author": "",
11
+ "license": "ISC",
12
+ "dependencies": {
13
+ "axios": "^1.14.0"
14
+ }
15
+ }