Repository navigation
Expand file tree
/
Copy pathtest.mjs
More file actions
285 lines (251 loc) · 11.4 KB
/
Copy pathtest.mjs
File metadata and controls
285 lines (251 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// SELink + Torch Remote API integration tests
// Run: node --test --test-reporter=spec test.js
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
const { config } = await import('dotenv');
config();
const BASE = 'http://localhost:6690';
const TORCH = process.env.TORCHREMOTE_ADDRESS || 'http://100.116.101.91:9080';
const TORCH_TOKEN = process.env.TORCHREMOTE_TOKEN || '';
const LOGIN_USER = process.env.TEST_USER || 'root';
const LOGIN_PASS = process.env.TEST_PASS || 'admin123';
// ── helpers ──────────────────────────────────────────────────────────────────
const SELINK_TIMEOUT = 12000; // 12s — covers the 8s Torch request timeout + overhead
const TORCH_TIMEOUT = 10000; // 10s — direct Torch calls should be fast
function withTimeout(ms) {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), ms);
return { signal: ctrl.signal, clear: () => clearTimeout(t) };
}
async function timedFetch(url, opts, ms) {
const { signal, clear } = withTimeout(ms);
try {
return await fetch(url, { ...opts, signal });
} finally {
clear();
}
}
async function login(user = LOGIN_USER, pass = LOGIN_PASS) {
const r = await timedFetch(`${BASE}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `username=${encodeURIComponent(user)}&password=${encodeURIComponent(pass)}`,
redirect: 'manual',
}, SELINK_TIMEOUT);
const setCookie = r.headers.get('set-cookie') || '';
const match = setCookie.match(/connect\.sid=[^;]+/);
return { status: r.status, cookie: match ? match[0] : '' };
}
// Shared auth cookie — set via top-level await before any describe blocks
let sessionCookie = '';
async function authedGet(path) {
return timedFetch(`${BASE}${path}`, { headers: { Cookie: sessionCookie } }, SELINK_TIMEOUT);
}
async function authedPost(path, body, ajax = false) {
const headers = { 'Content-Type': 'application/x-www-form-urlencoded', Cookie: sessionCookie };
if (ajax) headers['X-Requested-With'] = 'XMLHttpRequest';
return timedFetch(`${BASE}${path}`, { method: 'POST', headers, body }, SELINK_TIMEOUT);
}
async function torchGet(path) {
return timedFetch(`${TORCH}${path}`, { headers: { Authorization: `Bearer ${TORCH_TOKEN}` } }, TORCH_TIMEOUT);
}
async function torchPost(path, payload) {
return timedFetch(`${TORCH}${path}`, {
method: 'POST',
headers: { Authorization: `Bearer ${TORCH_TOKEN}`, 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
}, TORCH_TIMEOUT);
}
// ── global setup: login once before describe blocks are evaluated ─────────────
{
const { status, cookie } = await login();
sessionCookie = cookie;
if (!cookie) {
console.error(`FATAL: Login failed (status ${status}) — check TEST_USER/TEST_PASS or that selink is running`);
process.exit(1);
}
console.log('Login OK — session acquired');
}
// ── suites ───────────────────────────────────────────────────────────────────
describe('Auth', () => {
test('valid login returns session cookie', async () => {
const { status, cookie } = await login();
assert.ok([200, 302].includes(status), `Expected 200/302, got ${status}`);
assert.ok(cookie.length > 0, 'No session cookie in Set-Cookie');
});
test('invalid credentials return login page with error', async () => {
const { status } = await login('nobody', 'badpass');
assert.equal(status, 200, `Expected 200, got ${status}`);
// Session will be created (saveUninitialized) but userId will NOT be set
// Verify the empty session can't access protected routes
const r2 = await fetch(`${BASE}/api/status`);
assert.equal(r2.status, 401, 'Bad-login session should not grant /api/status access');
});
test('unauthenticated /api/status returns 401', async () => {
const r = await fetch(`${BASE}/api/status`);
assert.equal(r.status, 401);
const j = await r.json();
assert.equal(j.error, 'unauthorized');
});
test('unauthenticated /console/logs returns inline session error', async () => {
const r = await fetch(`${BASE}/console/logs`);
assert.equal(r.status, 200);
const body = await r.text();
assert.ok(body.includes('Invalid session'), `Expected session error, got: ${body.slice(0, 200)}`);
});
});
describe('/api/status', () => {
test('returns JSON with correct shape', async () => {
const r = await authedGet('/api/status');
assert.equal(r.status, 200, `Got ${r.status}`);
const j = await r.json();
assert.ok('online' in j, 'Missing "online"');
if (j.online) {
assert.ok('status' in j, 'Missing "status"');
assert.ok('memberCount' in j, 'Missing "memberCount"');
assert.ok('simSpeed' in j, 'Missing "simSpeed"');
assert.ok('uptime' in j, 'Missing "uptime"');
assert.ok(Number.isFinite(j.status), '"status" should be a number');
}
console.log(` Server online=${j.online}` + (j.online ? ` status=${j.status} players=${j.memberCount}` : ''));
});
});
describe('/invokeCommand (AJAX)', () => {
test('returns JSON {ok, status} for a valid command (save)', async () => {
// Torch console commands don't use ! prefix. "save" = save the world.
const r = await authedPost('/invokeCommand', 'command=save', true);
assert.equal(r.status, 200, `Got ${r.status}`);
const j = await r.json();
assert.ok('ok' in j, `Missing "ok": ${JSON.stringify(j)}`);
assert.ok('status' in j, `Missing "status": ${JSON.stringify(j)}`);
// 503 = SE game not yet fully loaded; accept it alongside 200
assert.ok(j.ok || j.status === 503, `save failed unexpectedly, torchStatus=${j.status}`);
console.log(` save → ok=${j.ok} torchStatus=${j.status}`);
});
test('empty command returns JSON without crashing', async () => {
const r = await authedPost('/invokeCommand', 'command=', true);
assert.equal(r.status, 200);
const j = await r.json();
assert.ok('ok' in j);
});
test('non-AJAX command still renders console.hbs HTML', async () => {
const r = await authedPost('/invokeCommand', 'command=!save', false);
assert.equal(r.status, 200);
const body = await r.text();
assert.ok(body.includes('Console') || body.includes('console'), 'Expected console page HTML');
});
});
describe('/postMessage (AJAX)', () => {
test('returns JSON {ok, status}', async () => {
const r = await authedPost('/postMessage', 'command=SELink+test', true);
assert.equal(r.status, 200);
const j = await r.json();
assert.ok('ok' in j, `Missing "ok": ${JSON.stringify(j)}`);
console.log(` chat send → ok=${j.ok}`);
});
test('HTML-like content is rejected before hitting Torch', async () => {
const r = await authedPost('/postMessage', 'command=<script>alert(1)</script>', true);
assert.equal(r.status, 200);
// The app renders chatplayers.hbs with errormsg — with AJAX header it may still return HTML
// Key check: server did not crash
});
});
describe('/players/list', () => {
test('returns table HTML or offline message', async () => {
let r;
try {
r = await authedGet('/players/list');
} catch (e) {
if (e.name === 'AbortError') { console.log(' players list: timeout (SE still loading)'); return; }
throw e;
}
assert.equal(r.status, 200);
const body = await r.text();
const isTable = body.includes('<table');
const isOffline = body.includes('offline') || body.includes('Server is offline');
assert.ok(isTable || isOffline, `Unexpected body: ${body.slice(0, 200)}`);
console.log(` players list: ${isTable ? 'table returned' : 'server offline'}`);
});
});
describe('/console/logs', () => {
test('returns log content when logged in', async () => {
const r = await authedGet('/console/logs');
assert.equal(r.status, 200);
const body = await r.text();
assert.ok(body.length > 0, 'Log body is empty');
});
});
describe('/panel/players/heal/:name', () => {
test('endpoint exists and responds without crashing', async () => {
const r = await authedPost('/panel/players/heal/TestPlayer', '', true);
assert.ok([200, 302].includes(r.status), `Got ${r.status}`);
if (r.status === 200) {
const j = await r.json();
assert.ok('ok' in j);
console.log(` heal TestPlayer → ok=${j.ok}`);
}
});
});
describe('Torch Remote API — direct', () => {
test('GET /api/v1/server/status returns 200 or 503', async () => {
const r = await torchGet('/api/v1/server/status');
assert.ok([200, 503].includes(r.status), `Got ${r.status}`);
if (r.status === 200) {
const j = await r.json();
assert.ok('status' in j || 'Status' in j, `Unexpected shape: ${JSON.stringify(j).slice(0, 100)}`);
console.log(` Torch status: ${JSON.stringify(j).slice(0, 80)}`);
}
});
test('GET /api/v1/players/ returns array or 503', async () => {
let r;
try {
r = await torchGet('/api/v1/players/');
} catch (e) {
// Torch's /players/ hangs during SE startup; AbortError here is acceptable
if (e.name === 'AbortError') { console.log(' players: timeout (SE still loading)'); return; }
throw e;
}
assert.ok([200, 503].includes(r.status), `Got ${r.status}`);
if (r.status === 200) {
const body = await r.text();
assert.ok(body.startsWith('[') || body.startsWith('{'), `Not JSON: ${body.slice(0, 100)}`);
}
});
test('POST /api/v1/chat/command with Torch console command returns 200', async () => {
// streamed:false — never use streamed:true in tests; it keeps the TCP connection open
// and the request module has no timeout, which destroyed TorchRemote's HTTP listener.
const r = await torchPost('/api/v1/chat/command', {
command: 'save',
streamed: false,
});
assert.ok([200, 503].includes(r.status), `Got ${r.status}`);
console.log(` save via Torch API → ${r.status}`);
});
test('POST /api/v1/chat/command with int streamingDuration returns 400', async () => {
const r = await torchPost('/api/v1/chat/command', {
command: '!save',
streamed: false,
streamingDuration: 3, // wrong type — should be a "hh:mm:ss" string if used
});
assert.ok([400, 500, 503].includes(r.status), `Expected 400/500/503 for bad duration, got ${r.status}`);
console.log(` bad duration → ${r.status} (expected 400)`);
});
test('POST /api/v1/chat/message — known SE API incompatibility (500)', async () => {
// TorchRemote uses ChatMsg.CustomAuthorName which was removed in a newer SE update.
// This endpoint returns 500 until TorchRemote is updated for the current SE version.
const r = await torchPost('/api/v1/chat/message', {
message: 'SELink test',
author: 'SELink',
channel: 1,
});
// Accept 500 (known broken) or 503 (SE offline) — not 200
assert.ok([500, 503].includes(r.status), `Got ${r.status} — if 200, the SE/Torch compat may be fixed`);
console.log(` chat/message → ${r.status} (expected 500: known SE compat issue)`);
});
test('wrong Bearer token returns 401', async () => {
const r = await fetch(`${TORCH}/api/v1/server/status`, {
headers: { Authorization: 'Bearer wrongtoken' },
});
assert.equal(r.status, 401, `Expected 401, got ${r.status}`);
});
});