@mizius/minecraft 0.0.0-stage → 1.5.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.
- package/README.md +159 -3
- package/artifacts/minecraft-control-1.21.10.jar +0 -0
- package/artifacts/minecraft-control-1.21.11.jar +0 -0
- package/artifacts/minecraft-control-1.21.4.jar +0 -0
- package/artifacts/minecraft-control-1.21.5.jar +0 -0
- package/artifacts/minecraft-control-1.21.6.jar +0 -0
- package/artifacts/minecraft-control-1.21.7.jar +0 -0
- package/artifacts/minecraft-control-1.21.8.jar +0 -0
- package/artifacts/minecraft-control-1.21.9.jar +0 -0
- package/artifacts/minecraft-control-26.1.1.jar +0 -0
- package/artifacts/minecraft-control-26.1.2.jar +0 -0
- package/artifacts/minecraft-control-26.1.jar +0 -0
- package/artifacts/minecraft-control-26.2.jar +0 -0
- package/artifacts/minecraft-control-26.3.jar +0 -0
- package/compatibility.json +109 -0
- package/dist/core.js +70 -0
- package/dist/download.js +99 -0
- package/dist/index.js +302 -0
- package/dist/install.js +360 -0
- package/dist/launch.js +165 -0
- package/dist/process.js +149 -0
- package/dist/update.js +376 -0
- package/package.json +40 -4
- package/skills/minecraft/SKILL.md +64 -0
package/dist/launch.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { open, readFile, mkdir, rm } from 'node:fs/promises';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { createServer } from 'node:net';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
7
|
+
import { initializeOptions, offlineUuid, readManifest, resolveVersion, writeJson } from './core.js';
|
|
8
|
+
import { atomicWrite } from './download.js';
|
|
9
|
+
import { install } from './install.js';
|
|
10
|
+
import { acquireLock, identity, running, stopClient } from './process.js';
|
|
11
|
+
export const CONTROL_URL = 'http://127.0.0.1:8765/control';
|
|
12
|
+
export const controlUrl = (port = 8765) => `http://127.0.0.1:${port}/control`;
|
|
13
|
+
export async function command(name, arguments_ = {}, url = CONTROL_URL, timeoutMs = 35_000) {
|
|
14
|
+
const response = await fetch(url, {
|
|
15
|
+
method: 'POST', signal: AbortSignal.timeout(timeoutMs),
|
|
16
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json',
|
|
17
|
+
...(process.env.MINECRAFT_CONTROL_TOKEN ? { Authorization: `Bearer ${process.env.MINECRAFT_CONTROL_TOKEN}` } : {}) },
|
|
18
|
+
body: JSON.stringify({ command: name, arguments: arguments_ }),
|
|
19
|
+
});
|
|
20
|
+
let result;
|
|
21
|
+
try {
|
|
22
|
+
result = await response.json();
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw new Error(`Control endpoint returned HTTP ${response.status}.`);
|
|
26
|
+
}
|
|
27
|
+
if (!result || typeof result !== 'object')
|
|
28
|
+
throw new Error('Control endpoint returned an invalid response.');
|
|
29
|
+
if (!response.ok || result.error)
|
|
30
|
+
throw new Error(typeof result.error === 'string' ? result.error : `Control endpoint returned HTTP ${response.status}.`);
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
export async function controlReady(url = CONTROL_URL) {
|
|
34
|
+
const healthUrl = new URL(url);
|
|
35
|
+
healthUrl.pathname = '/health';
|
|
36
|
+
const response = await fetch(healthUrl, {
|
|
37
|
+
signal: AbortSignal.timeout(5000),
|
|
38
|
+
headers: process.env.MINECRAFT_CONTROL_TOKEN ? { Authorization: `Bearer ${process.env.MINECRAFT_CONTROL_TOKEN}` } : {},
|
|
39
|
+
});
|
|
40
|
+
if (!response.ok)
|
|
41
|
+
throw new Error(`Minecraft command endpoint returned HTTP ${response.status}.`);
|
|
42
|
+
const result = await response.json();
|
|
43
|
+
if (result.ready !== true)
|
|
44
|
+
throw new Error('Minecraft command endpoint is not ready.');
|
|
45
|
+
}
|
|
46
|
+
export async function requireFreePort(port = 8765) {
|
|
47
|
+
await new Promise((resolve, reject) => {
|
|
48
|
+
const socket = createServer();
|
|
49
|
+
socket.once('error', () => reject(new Error(`Control port ${port} is occupied. Choose another free port with --port.`)));
|
|
50
|
+
socket.listen(port, '127.0.0.1', () => socket.close(error => error ? reject(error) : resolve()));
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
export function validateControlPort(port) {
|
|
54
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535 || port === 18765) {
|
|
55
|
+
throw new Error('Port must be an integer from 1024 to 65535, excluding mutex port 18765.');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export async function launch(root, packageRoot, requested, username, progress, port = 8765, background = true) {
|
|
59
|
+
validateControlPort(port);
|
|
60
|
+
const url = controlUrl(port);
|
|
61
|
+
const manifest = await readManifest(packageRoot);
|
|
62
|
+
const { version, compatibility } = resolveVersion(manifest, requested);
|
|
63
|
+
const uuid = offlineUuid(username);
|
|
64
|
+
const release = await acquireLock(root);
|
|
65
|
+
let record;
|
|
66
|
+
let child;
|
|
67
|
+
let childError;
|
|
68
|
+
try {
|
|
69
|
+
const active = await running(root);
|
|
70
|
+
if (active)
|
|
71
|
+
throw new Error(`Minecraft ${active.version} is already running. Run minecraft status or minecraft stop.`);
|
|
72
|
+
await requireFreePort(port);
|
|
73
|
+
const mod = await readFile(path.resolve(packageRoot, compatibility.mod.file));
|
|
74
|
+
if (createHash('sha256').update(mod).digest('hex') !== compatibility.mod.sha256)
|
|
75
|
+
throw new Error('Bundled mod checksum does not match the compatibility manifest.');
|
|
76
|
+
const installation = await install(root, version, compatibility, progress);
|
|
77
|
+
await initializeOptions(installation.instance, version, installation.optionsDataVersion);
|
|
78
|
+
await atomicWrite(path.join(installation.instance, 'mods', 'minecraft-control.jar'), mod);
|
|
79
|
+
await rm(path.join(installation.instance, 'mods', 'minecraft-mcp.jar'), { force: true });
|
|
80
|
+
// Downloads can take time. Check again immediately before creating the process.
|
|
81
|
+
await requireFreePort(port);
|
|
82
|
+
const log = path.join(installation.instance, 'launcher.log');
|
|
83
|
+
await mkdir(path.dirname(log), { recursive: true });
|
|
84
|
+
const output = await open(log, 'w');
|
|
85
|
+
try {
|
|
86
|
+
child = spawn(installation.java, installation.launch(username, uuid, port, background), {
|
|
87
|
+
cwd: installation.instance, detached: true, windowsHide: false, stdio: ['ignore', output.fd, output.fd],
|
|
88
|
+
});
|
|
89
|
+
child.on('error', error => { childError = error; });
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
await output.close();
|
|
93
|
+
}
|
|
94
|
+
if (!child.pid)
|
|
95
|
+
throw new Error(`Could not start Minecraft. See ${log}`);
|
|
96
|
+
const processIdentity = await identity(child.pid);
|
|
97
|
+
if (!processIdentity)
|
|
98
|
+
throw new Error(`Minecraft exited during startup. See ${log}`);
|
|
99
|
+
record = { identity: processIdentity, version, instance: installation.instance, log, port };
|
|
100
|
+
await writeJson(path.join(root, 'client.json'), record);
|
|
101
|
+
progress(`Waiting for Minecraft command endpoint. Startup log ${log}`);
|
|
102
|
+
const deadline = Date.now() + 180_000;
|
|
103
|
+
while (Date.now() < deadline) {
|
|
104
|
+
if (childError || child.exitCode !== null || child.signalCode !== null)
|
|
105
|
+
throw new Error(`Minecraft exited during startup. See ${log}`, { cause: childError });
|
|
106
|
+
try {
|
|
107
|
+
await controlReady(url);
|
|
108
|
+
child.unref();
|
|
109
|
+
return record;
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
await delay(1000);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
throw new Error(`Minecraft command endpoint did not become ready within 180 seconds. See ${log}`);
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
if (record) {
|
|
119
|
+
await stopClient(record);
|
|
120
|
+
await rm(path.join(root, 'client.json'), { force: true });
|
|
121
|
+
}
|
|
122
|
+
else if (child && child.exitCode === null && child.signalCode === null)
|
|
123
|
+
child.kill();
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
await release();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
export async function stop(root) {
|
|
131
|
+
const release = await acquireLock(root);
|
|
132
|
+
try {
|
|
133
|
+
const record = await running(root);
|
|
134
|
+
if (!record)
|
|
135
|
+
return { stopped: false };
|
|
136
|
+
const url = controlUrl(record.port);
|
|
137
|
+
let ready = false;
|
|
138
|
+
try {
|
|
139
|
+
await controlReady(url);
|
|
140
|
+
ready = true;
|
|
141
|
+
}
|
|
142
|
+
catch { /* The process may be starting or exiting. */ }
|
|
143
|
+
if (ready) {
|
|
144
|
+
let recording = false;
|
|
145
|
+
try {
|
|
146
|
+
recording = (await command('state', {}, url)).recording === true;
|
|
147
|
+
}
|
|
148
|
+
catch { /* Fall back to the normal window close. */ }
|
|
149
|
+
if (recording)
|
|
150
|
+
await command('record', { action: 'stop' }, url, 125_000);
|
|
151
|
+
}
|
|
152
|
+
await stopClient(record);
|
|
153
|
+
for (let count = 0; count < 30; count++) {
|
|
154
|
+
if (!(await running(root))) {
|
|
155
|
+
await rm(path.join(root, 'client.json'), { force: true });
|
|
156
|
+
return { stopped: true };
|
|
157
|
+
}
|
|
158
|
+
await delay(100);
|
|
159
|
+
}
|
|
160
|
+
throw new Error('The managed Minecraft process did not stop.');
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
await release();
|
|
164
|
+
}
|
|
165
|
+
}
|
package/dist/process.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
import { mkdir, readFile, readlink } from 'node:fs/promises';
|
|
5
|
+
import { createServer } from 'node:net';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
const exec = promisify(execFile);
|
|
8
|
+
async function powershell(script) {
|
|
9
|
+
const encoded = Buffer.from(`$ErrorActionPreference='Stop'; ${script}`, 'utf16le').toString('base64');
|
|
10
|
+
const { stdout } = await exec('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], {
|
|
11
|
+
windowsHide: true, timeout: 30000, maxBuffer: 1024 * 1024,
|
|
12
|
+
});
|
|
13
|
+
return stdout.trim();
|
|
14
|
+
}
|
|
15
|
+
export async function identity(pid) {
|
|
16
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
17
|
+
throw new Error('Invalid process identifier.');
|
|
18
|
+
if (process.platform === 'linux') {
|
|
19
|
+
try {
|
|
20
|
+
const readStat = () => readFile(`/proc/${pid}/stat`, 'utf8');
|
|
21
|
+
const before = await readStat();
|
|
22
|
+
if (['Z', 'X'].includes(before.slice(before.lastIndexOf(')') + 2).split(' ')[0]))
|
|
23
|
+
return null;
|
|
24
|
+
const [executable, commandLine, boot] = await Promise.all([
|
|
25
|
+
readlink(`/proc/${pid}/exe`), readFile(`/proc/${pid}/cmdline`, 'utf8'),
|
|
26
|
+
readFile('/proc/sys/kernel/random/boot_id', 'utf8'),
|
|
27
|
+
]);
|
|
28
|
+
const after = await readStat();
|
|
29
|
+
const start = (stat) => stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19];
|
|
30
|
+
if (start(before) !== start(after) || !commandLine)
|
|
31
|
+
return null;
|
|
32
|
+
return { pid, started: `${boot.trim()}:${start(after)}`, executable, commandLine };
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (error.code === 'EACCES') {
|
|
36
|
+
try {
|
|
37
|
+
const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
|
|
38
|
+
if (['Z', 'X'].includes(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[0]))
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
catch (statError) {
|
|
42
|
+
if (['ENOENT', 'ESRCH'].includes(statError.code ?? ''))
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (['ENOENT', 'ESRCH'].includes(error.code ?? ''))
|
|
47
|
+
return null;
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const json = await powershell(`$p=Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}'; if($p){ @{pid=[int]$p.ProcessId;started=$p.CreationDate.ToUniversalTime().ToString('o');executable=$p.ExecutablePath;commandLine=$p.CommandLine} | ConvertTo-Json -Compress }`);
|
|
52
|
+
return json ? JSON.parse(json) : null;
|
|
53
|
+
}
|
|
54
|
+
export function matchesProcess(actual, expected, instance) {
|
|
55
|
+
const escaped = instance.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
56
|
+
const gameDirectory = new RegExp(`(?:^|\\s)--gameDir\\s+(?:"${escaped}"|${escaped}(?=\\s|$))`);
|
|
57
|
+
const args = actual?.commandLine.split('\0') ?? [];
|
|
58
|
+
const directoryMatches = process.platform === 'linux' && args.length > 1
|
|
59
|
+
? args.some((arg, index) => arg === '--gameDir' && args[index + 1] === instance)
|
|
60
|
+
: gameDirectory.test(actual?.commandLine ?? '');
|
|
61
|
+
return !!actual && actual.pid === expected.pid && actual.started === expected.started &&
|
|
62
|
+
!!actual.executable && (process.platform === 'win32' ? actual.executable.toLowerCase() === expected.executable.toLowerCase() : actual.executable === expected.executable) &&
|
|
63
|
+
!!actual.commandLine && actual.commandLine === expected.commandLine && directoryMatches;
|
|
64
|
+
}
|
|
65
|
+
export async function running(root) {
|
|
66
|
+
let record;
|
|
67
|
+
try {
|
|
68
|
+
record = JSON.parse(await readFile(path.join(root, 'client.json'), 'utf8'));
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
if (error.code === 'ENOENT')
|
|
72
|
+
return null;
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
const legacyPort = (() => {
|
|
76
|
+
try {
|
|
77
|
+
const url = new URL(record.url ?? '');
|
|
78
|
+
const port = Number(url.port || 8765);
|
|
79
|
+
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && validControlPort(port) ? port : undefined;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
})();
|
|
85
|
+
const port = validControlPort(record.port) ? record.port : legacyPort ?? 8765;
|
|
86
|
+
const normalized = { ...record, port };
|
|
87
|
+
return matchesProcess(await identity(record.identity.pid), record.identity, record.instance) ? normalized : null;
|
|
88
|
+
}
|
|
89
|
+
function validControlPort(port) {
|
|
90
|
+
return Number.isInteger(port) && port >= 1024 && port <= 65535 && port !== 18765;
|
|
91
|
+
}
|
|
92
|
+
export async function stopClient(record) {
|
|
93
|
+
if (process.platform === 'linux') {
|
|
94
|
+
const signal = async (value) => {
|
|
95
|
+
if (matchesProcess(await identity(record.identity.pid), record.identity, record.instance)) {
|
|
96
|
+
try {
|
|
97
|
+
process.kill(record.identity.pid, value);
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error.code !== 'ESRCH')
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
await signal('SIGTERM');
|
|
106
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
107
|
+
if (!matchesProcess(await identity(record.identity.pid), record.identity, record.instance))
|
|
108
|
+
return;
|
|
109
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
110
|
+
}
|
|
111
|
+
await signal('SIGKILL');
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
// Keep the PowerShell command short even when Minecraft has a long Java classpath.
|
|
115
|
+
const data = Buffer.from(JSON.stringify({ identity: {
|
|
116
|
+
pid: record.identity.pid, started: record.identity.started, executable: record.identity.executable,
|
|
117
|
+
commandHash: createHash('sha256').update(record.identity.commandLine).digest('base64'),
|
|
118
|
+
} }), 'utf8').toString('base64');
|
|
119
|
+
// Verify and terminate within the same PowerShell invocation. Never kill a PID based only on a stale file.
|
|
120
|
+
if (!matchesProcess(record.identity, record.identity, record.instance))
|
|
121
|
+
throw new Error('Invalid managed process record.');
|
|
122
|
+
await powershell(`
|
|
123
|
+
$r=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${data}')) | ConvertFrom-Json
|
|
124
|
+
function Matches($p) {
|
|
125
|
+
return ($p -and $p.CreationDate.ToUniversalTime().ToString('o') -eq $r.identity.started -and
|
|
126
|
+
$p.ExecutablePath -eq $r.identity.executable -and
|
|
127
|
+
[Convert]::ToBase64String([Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes($p.CommandLine))) -ceq $r.identity.commandHash)
|
|
128
|
+
}
|
|
129
|
+
$p=Get-CimInstance Win32_Process -Filter ('ProcessId='+$r.identity.pid)
|
|
130
|
+
if(Matches $p) {
|
|
131
|
+
$process=Get-Process -Id $p.ProcessId -ErrorAction SilentlyContinue
|
|
132
|
+
if($process -and $process.CloseMainWindow()) {
|
|
133
|
+
try { $process.WaitForExit(10000) | Out-Null } catch {}
|
|
134
|
+
}
|
|
135
|
+
$p=Get-CimInstance Win32_Process -Filter ('ProcessId='+$r.identity.pid)
|
|
136
|
+
if(Matches $p) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue }
|
|
137
|
+
}
|
|
138
|
+
`);
|
|
139
|
+
}
|
|
140
|
+
export async function acquireLock(root) {
|
|
141
|
+
await mkdir(root, { recursive: true });
|
|
142
|
+
// The OS releases this mutex on crashes. It also serializes different managed roots.
|
|
143
|
+
const socket = createServer();
|
|
144
|
+
await new Promise((resolve, reject) => {
|
|
145
|
+
socket.once('error', () => reject(new Error('Another CLI operation is running, or mutex port 18765 is occupied.')));
|
|
146
|
+
socket.listen({ host: '127.0.0.1', port: 18765, exclusive: true }, resolve);
|
|
147
|
+
});
|
|
148
|
+
return () => new Promise((resolve, reject) => socket.close(error => error ? reject(error) : resolve()));
|
|
149
|
+
}
|