narrarium-server 0.0.0-stage → 0.1.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 +189 -2
- package/dist/cli.mjs +1305 -0
- package/dist/cli.mjs.map +6 -0
- package/dist/server.mjs +16414 -0
- package/dist/server.mjs.map +6 -0
- package/package.json +53 -4
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,1305 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __narrariumCreateRequire } from "node:module"; const require = __narrariumCreateRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// src/cli-main.ts
|
|
5
|
+
import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
|
|
6
|
+
import { accessSync, constants as constants4, existsSync as existsSync2 } from "node:fs";
|
|
7
|
+
import path6 from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
|
|
10
|
+
// ../engine/dist/server/protocol.js
|
|
11
|
+
var DEFAULT_SERVER_PORT = 24242;
|
|
12
|
+
var DEFAULT_ADMIN_PORT = 24243;
|
|
13
|
+
var SERVER_PACKAGE_NAME = "narrarium-server";
|
|
14
|
+
var SERVER_SCOPES = ["read", "write", "run", "update"];
|
|
15
|
+
|
|
16
|
+
// src/admin-client.ts
|
|
17
|
+
import { constants as constants2 } from "node:fs";
|
|
18
|
+
import * as fs2 from "node:fs/promises";
|
|
19
|
+
import path2 from "node:path";
|
|
20
|
+
|
|
21
|
+
// src/errors.ts
|
|
22
|
+
var HttpError = class extends Error {
|
|
23
|
+
constructor(status, code, message) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.status = status;
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.name = "HttpError";
|
|
28
|
+
}
|
|
29
|
+
status;
|
|
30
|
+
code;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// src/files.ts
|
|
34
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
35
|
+
import { constants } from "node:fs";
|
|
36
|
+
import * as fs from "node:fs/promises";
|
|
37
|
+
import path from "node:path";
|
|
38
|
+
var MAX_DATA_FILE_BYTES = 64 * 1024 * 1024;
|
|
39
|
+
function unsafeKeys(value, depth = 0) {
|
|
40
|
+
if (depth > 64) return true;
|
|
41
|
+
if (value === null || typeof value !== "object") return false;
|
|
42
|
+
return Object.entries(value).some(([key, entry]) => key === "__proto__" || key === "constructor" || key === "prototype" || unsafeKeys(entry, depth + 1));
|
|
43
|
+
}
|
|
44
|
+
async function readJson(file, max = MAX_DATA_FILE_BYTES) {
|
|
45
|
+
let handle;
|
|
46
|
+
try {
|
|
47
|
+
const info = await fs.lstat(file);
|
|
48
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size > max) throw new Error(`${path.basename(file)} is not a regular file or is too large.`);
|
|
49
|
+
handle = await fs.open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
50
|
+
const opened = await handle.stat();
|
|
51
|
+
if (opened.dev !== info.dev || opened.ino !== info.ino) {
|
|
52
|
+
await handle.close();
|
|
53
|
+
throw new Error(`${path.basename(file)} changed while it was read.`);
|
|
54
|
+
}
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error.code === "ENOENT") return void 0;
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
const bytes = await handle.readFile();
|
|
61
|
+
if (bytes.byteLength > max) throw new Error(`${path.basename(file)} is too large.`);
|
|
62
|
+
const data = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
63
|
+
if (unsafeKeys(data)) throw new Error(`${path.basename(file)} contains keys that are not allowed.`);
|
|
64
|
+
return data;
|
|
65
|
+
} finally {
|
|
66
|
+
await handle.close();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function renameReplacing(from, to) {
|
|
70
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
71
|
+
try {
|
|
72
|
+
await fs.rename(from, to);
|
|
73
|
+
return;
|
|
74
|
+
} catch (error) {
|
|
75
|
+
const code = error.code;
|
|
76
|
+
if (attempt >= 12 || process.platform !== "win32" || code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw error;
|
|
77
|
+
await new Promise((done) => setTimeout(done, 15 * (attempt + 1)));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function syncDirectory(directory) {
|
|
82
|
+
if (process.platform === "win32") return;
|
|
83
|
+
const handle = await fs.open(directory, "r");
|
|
84
|
+
try {
|
|
85
|
+
await handle.sync();
|
|
86
|
+
} finally {
|
|
87
|
+
await handle.close();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async function atomicWrite(file, data, mode = 384) {
|
|
91
|
+
const bytes = typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data);
|
|
92
|
+
if (bytes.byteLength > MAX_DATA_FILE_BYTES) throw new Error(`${path.basename(file)} would be larger than the safety limit; nothing was written.`);
|
|
93
|
+
const parent = path.dirname(file);
|
|
94
|
+
await fs.mkdir(parent, { recursive: true, mode: 448 });
|
|
95
|
+
const parentStat = await fs.lstat(parent);
|
|
96
|
+
if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) throw new Error(`${parent} is not a safe directory.`);
|
|
97
|
+
try {
|
|
98
|
+
const existing = await fs.lstat(file);
|
|
99
|
+
if (!existing.isFile() || existing.isSymbolicLink() || existing.nlink !== 1) throw new Error(`${path.basename(file)} is not a regular file.`);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (error.code !== "ENOENT") throw error;
|
|
102
|
+
}
|
|
103
|
+
const temporary = `${file}.new-${randomUUID()}`;
|
|
104
|
+
const handle = await fs.open(temporary, "wx", mode);
|
|
105
|
+
try {
|
|
106
|
+
await handle.writeFile(bytes);
|
|
107
|
+
await handle.sync();
|
|
108
|
+
await handle.close();
|
|
109
|
+
await renameReplacing(temporary, file);
|
|
110
|
+
await syncDirectory(parent);
|
|
111
|
+
} finally {
|
|
112
|
+
await handle.close().catch(() => void 0);
|
|
113
|
+
await fs.unlink(temporary).catch(() => void 0);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function atomicJson(file, value, mode = 384) {
|
|
117
|
+
await atomicWrite(file, `${JSON.stringify(value, null, 2)}
|
|
118
|
+
`, mode);
|
|
119
|
+
}
|
|
120
|
+
async function ensurePrivateDirectory(directory) {
|
|
121
|
+
const resolved = path.resolve(directory);
|
|
122
|
+
await fs.mkdir(resolved, { recursive: true, mode: 448 });
|
|
123
|
+
const stat2 = await fs.lstat(resolved);
|
|
124
|
+
if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw new Error(`${resolved} must be a directory, not a link.`);
|
|
125
|
+
if (process.platform !== "win32" && (stat2.mode & 63) !== 0) await fs.chmod(resolved, 448);
|
|
126
|
+
return resolved;
|
|
127
|
+
}
|
|
128
|
+
async function readPrivateText(file, max = 4096) {
|
|
129
|
+
let info;
|
|
130
|
+
try {
|
|
131
|
+
info = await fs.lstat(file);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (error.code === "ENOENT") return void 0;
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size > max || process.platform !== "win32" && (info.mode & 63) !== 0) {
|
|
137
|
+
throw new Error(`${path.basename(file)} must be a private regular file (mode 0600).`);
|
|
138
|
+
}
|
|
139
|
+
const handle = await fs.open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
140
|
+
try {
|
|
141
|
+
const opened = await handle.stat();
|
|
142
|
+
if (opened.dev !== info.dev || opened.ino !== info.ino) throw new Error(`${path.basename(file)} changed while it was read.`);
|
|
143
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(await handle.readFile());
|
|
144
|
+
} finally {
|
|
145
|
+
await handle.close();
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/vault.ts
|
|
150
|
+
var AAD = Buffer.from("narrarium-server-v1");
|
|
151
|
+
|
|
152
|
+
// src/auth.ts
|
|
153
|
+
var ADMIN_SESSION_MS = 30 * 6e4;
|
|
154
|
+
var PAIRING_MS = 5 * 6e4;
|
|
155
|
+
var ATTEMPT_WINDOW_MS = 5 * 6e4;
|
|
156
|
+
var ADMIN_CODE_FILE = "admin-code.txt";
|
|
157
|
+
function isScope(value) {
|
|
158
|
+
return typeof value === "string" && SERVER_SCOPES.includes(value);
|
|
159
|
+
}
|
|
160
|
+
function parseScopes(value) {
|
|
161
|
+
const scopes = Array.isArray(value) ? value : [];
|
|
162
|
+
if (!scopes.length || scopes.length > SERVER_SCOPES.length || !scopes.every(isScope) || new Set(scopes).size !== scopes.length) {
|
|
163
|
+
throw new HttpError(422, "scopes", "Choose permissions among read, write, run and update, without repetitions.");
|
|
164
|
+
}
|
|
165
|
+
return scopes;
|
|
166
|
+
}
|
|
167
|
+
function assertAdminCode(value) {
|
|
168
|
+
if (value.length < 32 || value.length > 200 || value !== value.trim() || /[\u0000-\u001f\u007f]/u.test(value)) {
|
|
169
|
+
throw new HttpError(422, "admin_code", "The admin code must have 32-200 visible characters, without line breaks or leading/trailing spaces.");
|
|
170
|
+
}
|
|
171
|
+
return value;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// src/admin-client.ts
|
|
175
|
+
async function readAdminCode(dataRoot) {
|
|
176
|
+
const text = await readPrivateText(path2.join(path2.resolve(dataRoot), "private", ADMIN_CODE_FILE), 202);
|
|
177
|
+
if (text === void 0) throw new Error("The admin code does not exist yet: start the server once with `npx narrarium-server start`.");
|
|
178
|
+
const code = text.trim();
|
|
179
|
+
if (!code || /[\r\n\0]/.test(code)) throw new Error("The admin code file is not valid.");
|
|
180
|
+
return code;
|
|
181
|
+
}
|
|
182
|
+
async function readAdminCodeFile(file) {
|
|
183
|
+
const info = await fs2.lstat(file);
|
|
184
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size < 32 || info.size > 201 || process.platform !== "win32" && (info.mode & 63) !== 0) {
|
|
185
|
+
throw new Error("The code file must be a private (0600) regular file with 32-200 characters.");
|
|
186
|
+
}
|
|
187
|
+
const handle = await fs2.open(file, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
|
|
188
|
+
try {
|
|
189
|
+
const opened = await handle.stat();
|
|
190
|
+
if (opened.dev !== info.dev || opened.ino !== info.ino) throw new Error("The code file changed while it was read.");
|
|
191
|
+
const text = await handle.readFile("utf8");
|
|
192
|
+
return assertAdminCode(text.endsWith("\n") ? text.slice(0, -1) : text);
|
|
193
|
+
} finally {
|
|
194
|
+
await handle.close();
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async function localAdminSession(options) {
|
|
198
|
+
const code = await readAdminCode(options.dataRoot);
|
|
199
|
+
const origin = `http://127.0.0.1:${options.adminPort ?? DEFAULT_ADMIN_PORT}`;
|
|
200
|
+
const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
201
|
+
let login;
|
|
202
|
+
try {
|
|
203
|
+
login = await fetchImpl(`${origin}/admin/api/login`, { method: "POST", redirect: "error", credentials: "omit", headers: { origin, "content-type": "application/json" }, body: JSON.stringify({ code }) });
|
|
204
|
+
} catch {
|
|
205
|
+
throw new Error(`The server is not running on ${origin}: start it with \`npx narrarium-server start\`.`);
|
|
206
|
+
}
|
|
207
|
+
if (!login.ok) throw new Error("Admin sign-in failed: check that the server of this data folder is running.");
|
|
208
|
+
const session = await login.json();
|
|
209
|
+
const cookie = login.headers.get("set-cookie")?.split(";", 1)[0];
|
|
210
|
+
if (typeof session.csrf !== "string" || !cookie) throw new Error("The admin session is not valid.");
|
|
211
|
+
return { origin, csrf: session.csrf, cookie, fetchImpl };
|
|
212
|
+
}
|
|
213
|
+
async function adminPost(session, route, body) {
|
|
214
|
+
const response = await session.fetchImpl(`${session.origin}${route}`, {
|
|
215
|
+
method: "POST",
|
|
216
|
+
redirect: "error",
|
|
217
|
+
credentials: "omit",
|
|
218
|
+
headers: { origin: session.origin, "content-type": "application/json", cookie: session.cookie, "x-csrf-token": session.csrf },
|
|
219
|
+
body: JSON.stringify(body)
|
|
220
|
+
});
|
|
221
|
+
const payload = await response.json().catch(() => ({}));
|
|
222
|
+
if (!response.ok) throw new Error(payload.message || `The admin request failed (HTTP ${response.status}).`);
|
|
223
|
+
return payload;
|
|
224
|
+
}
|
|
225
|
+
async function requestLocalClientToken(options) {
|
|
226
|
+
const label = options.label.trim();
|
|
227
|
+
if (!label || label.length > 80) throw new Error("The client name must have 1-80 characters.");
|
|
228
|
+
const scopes = parseScopes(options.scopes.map((scope) => scope.trim()));
|
|
229
|
+
const session = await localAdminSession(options);
|
|
230
|
+
return adminPost(session, "/admin/api/token", { label, scopes });
|
|
231
|
+
}
|
|
232
|
+
async function rotateLocalAdminCode(options) {
|
|
233
|
+
const session = await localAdminSession(options);
|
|
234
|
+
const result = await adminPost(session, "/admin/api/admin-code/rotate", {});
|
|
235
|
+
if (typeof result.code !== "string") throw new Error("The new admin code is not valid.");
|
|
236
|
+
return result.code;
|
|
237
|
+
}
|
|
238
|
+
async function setLocalAdminCode(options) {
|
|
239
|
+
const code = assertAdminCode(options.code);
|
|
240
|
+
const session = await localAdminSession(options);
|
|
241
|
+
await adminPost(session, "/admin/api/admin-code/set", { code });
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// src/autostart.ts
|
|
245
|
+
import { spawnSync } from "node:child_process";
|
|
246
|
+
import * as fs3 from "node:fs/promises";
|
|
247
|
+
import { homedir } from "node:os";
|
|
248
|
+
import path3 from "node:path";
|
|
249
|
+
var SYSTEMD_UNIT = "narrarium-server.service";
|
|
250
|
+
var LAUNCHD_LABEL = "net.narrarium.server";
|
|
251
|
+
function systemdQuote(value) {
|
|
252
|
+
return `"${value.replace(/([%\\"])/g, (char) => char === "%" ? "%%" : `\\${char}`)}"`;
|
|
253
|
+
}
|
|
254
|
+
function renderUserService(active, dataRoot, nodeBinary = process.execPath) {
|
|
255
|
+
const exec = [systemdQuote(path3.resolve(nodeBinary)), systemdQuote(path3.resolve(active.packageRoot, "dist", "cli.mjs")), "start", "--data-root", systemdQuote(path3.resolve(dataRoot))].join(" ");
|
|
256
|
+
return `[Unit]
|
|
257
|
+
Description=Narrarium personal server
|
|
258
|
+
After=network-online.target
|
|
259
|
+
Wants=network-online.target
|
|
260
|
+
|
|
261
|
+
[Service]
|
|
262
|
+
Type=simple
|
|
263
|
+
ExecStart=${exec}
|
|
264
|
+
Restart=on-failure
|
|
265
|
+
RestartSec=5
|
|
266
|
+
NoNewPrivileges=true
|
|
267
|
+
|
|
268
|
+
[Install]
|
|
269
|
+
WantedBy=default.target
|
|
270
|
+
`;
|
|
271
|
+
}
|
|
272
|
+
function xmlEscape(value) {
|
|
273
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
274
|
+
}
|
|
275
|
+
function renderLaunchAgent(active, dataRoot, nodeBinary = process.execPath) {
|
|
276
|
+
const args = [path3.resolve(nodeBinary), path3.resolve(active.packageRoot, "dist", "cli.mjs"), "start", "--data-root", path3.resolve(dataRoot)];
|
|
277
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
278
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
279
|
+
<plist version="1.0">
|
|
280
|
+
<dict>
|
|
281
|
+
<key>Label</key>
|
|
282
|
+
<string>${LAUNCHD_LABEL}</string>
|
|
283
|
+
<key>ProgramArguments</key>
|
|
284
|
+
<array>
|
|
285
|
+
${args.map((arg) => ` <string>${xmlEscape(arg)}</string>`).join("\n")}
|
|
286
|
+
</array>
|
|
287
|
+
<key>RunAtLoad</key>
|
|
288
|
+
<true/>
|
|
289
|
+
<key>KeepAlive</key>
|
|
290
|
+
<dict>
|
|
291
|
+
<key>SuccessfulExit</key>
|
|
292
|
+
<false/>
|
|
293
|
+
</dict>
|
|
294
|
+
<key>StandardOutPath</key>
|
|
295
|
+
<string>${xmlEscape(path3.join(path3.resolve(dataRoot), "server.log"))}</string>
|
|
296
|
+
<key>StandardErrorPath</key>
|
|
297
|
+
<string>${xmlEscape(path3.join(path3.resolve(dataRoot), "server.log"))}</string>
|
|
298
|
+
</dict>
|
|
299
|
+
</plist>
|
|
300
|
+
`;
|
|
301
|
+
}
|
|
302
|
+
function run(command, args, env) {
|
|
303
|
+
const result = spawnSync(command, args, { shell: false, windowsHide: true, encoding: "utf8", env, timeout: 3e4, stdio: ["ignore", "pipe", "pipe"] });
|
|
304
|
+
return { ok: result.status === 0, output: `${result.stdout ?? ""}${result.stderr ?? ""}` };
|
|
305
|
+
}
|
|
306
|
+
async function configureAutostart(active, dataRoot, environment = process.env) {
|
|
307
|
+
const uid = process.getuid?.();
|
|
308
|
+
if (uid === 0) throw new Error("Do not install autostart as root: run the command as the user who owns the server and its data.");
|
|
309
|
+
const home = environment.HOME ?? homedir();
|
|
310
|
+
if (process.platform === "linux") {
|
|
311
|
+
const runtimeDir = environment.XDG_RUNTIME_DIR || (uid !== void 0 ? `/run/user/${uid}` : "");
|
|
312
|
+
const env = { ...environment, HOME: home, XDG_RUNTIME_DIR: runtimeDir, DBUS_SESSION_BUS_ADDRESS: environment.DBUS_SESSION_BUS_ADDRESS ?? (runtimeDir ? `unix:path=${path3.join(runtimeDir, "bus")}` : "") };
|
|
313
|
+
const systemctl = environment.NARRARIUM_SYSTEMCTL || "systemctl";
|
|
314
|
+
const configDir = path3.join(home, ".config", "systemd", "user");
|
|
315
|
+
await fs3.mkdir(configDir, { recursive: true, mode: 448 });
|
|
316
|
+
const servicePath = path3.join(configDir, SYSTEMD_UNIT);
|
|
317
|
+
await fs3.writeFile(servicePath, renderUserService(active, dataRoot), { mode: 384 });
|
|
318
|
+
if (!run(systemctl, ["--user", "daemon-reload"], env).ok) throw new Error("The service was written, but systemd --user does not answer. Run the command from a real user session or set XDG_RUNTIME_DIR.");
|
|
319
|
+
if (!run(systemctl, ["--user", "enable", "--now", SYSTEMD_UNIT], env).ok) throw new Error(`The service was written but could not be enabled. Check: systemctl --user status ${SYSTEMD_UNIT}`);
|
|
320
|
+
const user = environment.USER ?? String(uid);
|
|
321
|
+
const linger = spawnSync("loginctl", ["show-user", user, "-p", "Linger", "--value"], { shell: false, encoding: "utf8", env }).stdout?.trim();
|
|
322
|
+
return {
|
|
323
|
+
kind: "systemd-user",
|
|
324
|
+
servicePath,
|
|
325
|
+
activeVersion: active.version,
|
|
326
|
+
message: linger === "yes" ? "User service enabled and started; it also starts after a reboot." : `User service started. To start it after a reboot without logging in, an administrator must run: sudo loginctl enable-linger ${user}`
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
if (process.platform === "darwin") {
|
|
330
|
+
const agents = path3.join(home, "Library", "LaunchAgents");
|
|
331
|
+
await fs3.mkdir(agents, { recursive: true });
|
|
332
|
+
const servicePath = path3.join(agents, `${LAUNCHD_LABEL}.plist`);
|
|
333
|
+
await fs3.writeFile(servicePath, renderLaunchAgent(active, dataRoot), { mode: 420 });
|
|
334
|
+
const launchctl = environment.NARRARIUM_LAUNCHCTL || "launchctl";
|
|
335
|
+
const domain = `gui/${uid ?? ""}`;
|
|
336
|
+
run(launchctl, ["bootout", `${domain}/${LAUNCHD_LABEL}`], environment);
|
|
337
|
+
if (!run(launchctl, ["bootstrap", domain, servicePath], environment).ok) throw new Error(`The launch agent was written but could not be loaded. Try: launchctl bootstrap ${domain} "${servicePath}"`);
|
|
338
|
+
return { kind: "launchd", servicePath, activeVersion: active.version, message: "Launch agent loaded: the server starts at every login." };
|
|
339
|
+
}
|
|
340
|
+
throw new Error("Automatic start is available on Linux (systemd) and macOS (launchd). On Windows, add `npx narrarium-server start` to Task Scheduler at logon.");
|
|
341
|
+
}
|
|
342
|
+
async function autostartStatus(home = homedir(), platform = process.platform) {
|
|
343
|
+
const file = platform === "darwin" ? path3.join(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`) : path3.join(home, ".config", "systemd", "user", SYSTEMD_UNIT);
|
|
344
|
+
try {
|
|
345
|
+
await fs3.stat(file);
|
|
346
|
+
return file;
|
|
347
|
+
} catch {
|
|
348
|
+
return void 0;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// src/config.ts
|
|
353
|
+
import { createHash as createHash2, createPrivateKey, generateKeyPairSync, randomUUID as randomUUID2, sign } from "node:crypto";
|
|
354
|
+
import os from "node:os";
|
|
355
|
+
import path4 from "node:path";
|
|
356
|
+
function validPort(value, fallback) {
|
|
357
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 65535 ? value : fallback;
|
|
358
|
+
}
|
|
359
|
+
function stringList(value, max) {
|
|
360
|
+
return Array.isArray(value) ? [...new Set(value.filter((entry) => typeof entry === "string" && entry.length <= 500))].slice(0, max) : [];
|
|
361
|
+
}
|
|
362
|
+
function normalizeOrigin(value, allowLoopbackHttp = true) {
|
|
363
|
+
let url;
|
|
364
|
+
try {
|
|
365
|
+
url = new URL(value.trim());
|
|
366
|
+
} catch {
|
|
367
|
+
throw new HttpError(422, "invalid_url", `Not a valid address: ${value}`);
|
|
368
|
+
}
|
|
369
|
+
const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]";
|
|
370
|
+
if (url.username || url.password || url.protocol !== "https:" && !(url.protocol === "http:" && loopback && allowLoopbackHttp)) {
|
|
371
|
+
throw new HttpError(422, "invalid_url", `Use an https:// address (plain http only for this computer): ${value}`);
|
|
372
|
+
}
|
|
373
|
+
return url.origin;
|
|
374
|
+
}
|
|
375
|
+
function configPath(root) {
|
|
376
|
+
return path4.join(root, "config.json");
|
|
377
|
+
}
|
|
378
|
+
function parseConfig(stored) {
|
|
379
|
+
const value = stored && typeof stored === "object" ? stored : {};
|
|
380
|
+
return {
|
|
381
|
+
version: 2,
|
|
382
|
+
serverId: typeof value.serverId === "string" && /^[0-9a-f-]{36}$/i.test(value.serverId) ? value.serverId : randomUUID2(),
|
|
383
|
+
label: typeof value.label === "string" && value.label.trim() ? value.label.trim().slice(0, 80) : `narrarium-server@${os.hostname()}`,
|
|
384
|
+
apiPort: validPort(value.apiPort ?? value.port, DEFAULT_SERVER_PORT),
|
|
385
|
+
adminPort: validPort(value.adminPort, DEFAULT_ADMIN_PORT),
|
|
386
|
+
origins: stringList(value.origins, 20),
|
|
387
|
+
allowedAiBases: stringList(value.allowedAiBases, 50),
|
|
388
|
+
pendingAiBases: stringList(value.pendingAiBases, 50),
|
|
389
|
+
...typeof value.publicUrl === "string" && value.publicUrl ? { publicUrl: value.publicUrl } : {},
|
|
390
|
+
...typeof value.adminPublicUrl === "string" && value.adminPublicUrl ? { adminPublicUrl: value.adminPublicUrl } : {},
|
|
391
|
+
allowRemoteAdmin: value.allowRemoteAdmin !== false,
|
|
392
|
+
maxConcurrentRuns: typeof value.maxConcurrentRuns === "number" && value.maxConcurrentRuns >= 1 && value.maxConcurrentRuns <= 8 ? Math.round(value.maxConcurrentRuns) : 2,
|
|
393
|
+
createdAt: typeof value.createdAt === "string" ? value.createdAt : (/* @__PURE__ */ new Date()).toISOString()
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
async function loadServerConfig(root, overrides = {}) {
|
|
397
|
+
await ensurePrivateDirectory(root);
|
|
398
|
+
const stored = await readJson(configPath(root), 1024 * 1024);
|
|
399
|
+
const config = parseConfig(stored);
|
|
400
|
+
if (overrides.label?.trim()) config.label = overrides.label.trim().slice(0, 80);
|
|
401
|
+
if (overrides.apiPort !== void 0) config.apiPort = validPort(overrides.apiPort, config.apiPort);
|
|
402
|
+
if (overrides.adminPort !== void 0) config.adminPort = validPort(overrides.adminPort, config.adminPort);
|
|
403
|
+
if (overrides.origins?.length) config.origins = [.../* @__PURE__ */ new Set([...config.origins, ...overrides.origins.map((origin) => normalizeOrigin(origin))])].slice(0, 20);
|
|
404
|
+
if (!stored || JSON.stringify(stored) !== JSON.stringify(config)) await atomicJson(configPath(root), config, 384);
|
|
405
|
+
return config;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// src/npm-release.ts
|
|
409
|
+
var NPM_SERVER_PACKAGE = SERVER_PACKAGE_NAME;
|
|
410
|
+
var NPM_LATEST = `https://registry.npmjs.org/${NPM_SERVER_PACKAGE}/latest`;
|
|
411
|
+
var MAX_PACKUMENT_BYTES = 256 * 1024;
|
|
412
|
+
var REPOSITORY_URLS = /* @__PURE__ */ new Set([
|
|
413
|
+
"git+https://github.com/KeyserDSoze/GhostWriterFramework.git",
|
|
414
|
+
"https://github.com/KeyserDSoze/GhostWriterFramework.git",
|
|
415
|
+
"git+https://github.com/KeyserDSoze/GhostWriterFramework",
|
|
416
|
+
"https://github.com/KeyserDSoze/GhostWriterFramework"
|
|
417
|
+
]);
|
|
418
|
+
var REPOSITORY_DIRECTORY = "packages/server";
|
|
419
|
+
var BOOTSTRAP_VERSIONS = /* @__PURE__ */ new Set(["0.1.0"]);
|
|
420
|
+
var SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
|
|
421
|
+
function isExactSemver(value) {
|
|
422
|
+
if (typeof value !== "string" || value.length > 100) return false;
|
|
423
|
+
const match = SEMVER.exec(value);
|
|
424
|
+
if (!match) return false;
|
|
425
|
+
return !match[4]?.split(".").some((part) => /^\d+$/.test(part) && part.length > 1 && part.startsWith("0"));
|
|
426
|
+
}
|
|
427
|
+
function compareSemver(a, b) {
|
|
428
|
+
const parse = (value) => {
|
|
429
|
+
const core = value.split("+", 1)[0];
|
|
430
|
+
const dash = core.indexOf("-");
|
|
431
|
+
return { numbers: (dash < 0 ? core : core.slice(0, dash)).split("."), prerelease: dash < 0 ? "" : core.slice(dash + 1) };
|
|
432
|
+
};
|
|
433
|
+
const left = parse(a);
|
|
434
|
+
const right = parse(b);
|
|
435
|
+
for (let index = 0; index < 3; index += 1) {
|
|
436
|
+
const l2 = left.numbers[index];
|
|
437
|
+
const r2 = right.numbers[index];
|
|
438
|
+
if (l2 !== r2) return l2.length !== r2.length ? l2.length - r2.length : l2 < r2 ? -1 : 1;
|
|
439
|
+
}
|
|
440
|
+
if (!left.prerelease && right.prerelease) return 1;
|
|
441
|
+
if (left.prerelease && !right.prerelease) return -1;
|
|
442
|
+
if (!left.prerelease && !right.prerelease) return 0;
|
|
443
|
+
const l = left.prerelease.split(".");
|
|
444
|
+
const r = right.prerelease.split(".");
|
|
445
|
+
for (let index = 0; index < Math.max(l.length, r.length); index += 1) {
|
|
446
|
+
if (l[index] === void 0) return -1;
|
|
447
|
+
if (r[index] === void 0) return 1;
|
|
448
|
+
if (l[index] === r[index]) continue;
|
|
449
|
+
const ln = /^\d+$/.test(l[index]);
|
|
450
|
+
const rn = /^\d+$/.test(r[index]);
|
|
451
|
+
if (ln && rn) {
|
|
452
|
+
const lv = l[index].replace(/^0+/, "") || "0";
|
|
453
|
+
const rv = r[index].replace(/^0+/, "") || "0";
|
|
454
|
+
return lv.length !== rv.length ? lv.length - rv.length : lv === rv ? 0 : lv < rv ? -1 : 1;
|
|
455
|
+
}
|
|
456
|
+
if (ln !== rn) return ln ? -1 : 1;
|
|
457
|
+
return l[index] < r[index] ? -1 : 1;
|
|
458
|
+
}
|
|
459
|
+
return 0;
|
|
460
|
+
}
|
|
461
|
+
function trustedNpmReleaseMetadata(value, expectedVersion, allowRegistryBootstrap = false) {
|
|
462
|
+
const candidate = Array.isArray(value) && value.length === 1 ? value[0] : value;
|
|
463
|
+
const manifest = candidate;
|
|
464
|
+
if (!manifest || typeof manifest !== "object" || manifest.name !== NPM_SERVER_PACKAGE || !isExactSemver(manifest.version) || !manifest.repository || !REPOSITORY_URLS.has(String(manifest.repository.url)) || manifest.repository.directory !== REPOSITORY_DIRECTORY || !manifest.dist || typeof manifest.dist.integrity !== "string" || manifest.dist.integrity.length < 20 || manifest.dist.integrity.length > 500) {
|
|
465
|
+
throw new Error("The npm metadata is not valid or does not come from the Narrarium repository.");
|
|
466
|
+
}
|
|
467
|
+
const version = manifest.version;
|
|
468
|
+
if (expectedVersion && version !== expectedVersion) throw new Error("The npm version differs from the requested one.");
|
|
469
|
+
const signatures = Array.isArray(manifest.dist.signatures) ? manifest.dist.signatures : [];
|
|
470
|
+
const signed = signatures.length > 0 && signatures.every((entry) => entry && typeof entry === "object" && typeof entry.keyid === "string" && typeof entry.sig === "string" && String(entry.sig).length >= 20);
|
|
471
|
+
const predicateType = manifest.dist.attestations?.provenance?.predicateType;
|
|
472
|
+
const attested = signed && (predicateType === "https://slsa.dev/provenance/v1" || predicateType === "https://slsa.dev/provenance/v0.2") && manifest.dist.attestations?.url === `https://registry.npmjs.org/-/npm/v1/attestations/${NPM_SERVER_PACKAGE}@${version}`;
|
|
473
|
+
if (!attested && !(allowRegistryBootstrap && signed && BOOTSTRAP_VERSIONS.has(version) && version === expectedVersion)) {
|
|
474
|
+
throw new Error("The npm release lacks the registry signature and the provenance attestation that are required.");
|
|
475
|
+
}
|
|
476
|
+
return { version };
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// src/runtime-install.ts
|
|
480
|
+
import { spawn } from "node:child_process";
|
|
481
|
+
import { constants as constants3, existsSync } from "node:fs";
|
|
482
|
+
import * as fs4 from "node:fs/promises";
|
|
483
|
+
import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
|
|
484
|
+
import { homedir as homedir2 } from "node:os";
|
|
485
|
+
import path5 from "node:path";
|
|
486
|
+
var PACKAGE_NAME = NPM_SERVER_PACKAGE;
|
|
487
|
+
var MINIMUM_NODE = [22, 14, 0];
|
|
488
|
+
var SUPERVISED_ENV = "NARRARIUM_SUPERVISED";
|
|
489
|
+
var MAX_CONTROL_FILE_BYTES = 16 * 1024;
|
|
490
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
491
|
+
var UPDATE_MESSAGES = {
|
|
492
|
+
completed: "Update completed.",
|
|
493
|
+
failed: "The update did not succeed. The previous version is still active.",
|
|
494
|
+
limited: "Limit of three supervised updates per hour reached. The active version stays; restart the supervisor when you can.",
|
|
495
|
+
stopping: "The server did not stop cleanly. The active version was not replaced."
|
|
496
|
+
};
|
|
497
|
+
function isPlainObject(value) {
|
|
498
|
+
return Boolean(value) && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype;
|
|
499
|
+
}
|
|
500
|
+
function exactKeys(value, keys) {
|
|
501
|
+
const actual = Object.keys(value).sort();
|
|
502
|
+
const expected = [...keys].sort();
|
|
503
|
+
return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
|
|
504
|
+
}
|
|
505
|
+
function validIso(value) {
|
|
506
|
+
if (typeof value !== "string" || value.length > 40) return false;
|
|
507
|
+
const date = new Date(value);
|
|
508
|
+
return !Number.isNaN(date.valueOf()) && date.toISOString() === value;
|
|
509
|
+
}
|
|
510
|
+
function assertExactSemver(value) {
|
|
511
|
+
if (!isExactSemver(value)) throw new Error("Not a valid version: an exact semver version is required.");
|
|
512
|
+
}
|
|
513
|
+
function assertSupportedNode(version = process.versions.node) {
|
|
514
|
+
const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
|
|
515
|
+
const parsed = match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
|
|
516
|
+
let ok = Boolean(parsed);
|
|
517
|
+
if (parsed) {
|
|
518
|
+
for (let index = 0; index < 3; index += 1) {
|
|
519
|
+
if (parsed[index] !== MINIMUM_NODE[index]) {
|
|
520
|
+
ok = parsed[index] > MINIMUM_NODE[index];
|
|
521
|
+
break;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
if (!ok) throw new Error(`Node.js ${MINIMUM_NODE.join(".")} or newer is required (this is ${version}).`);
|
|
526
|
+
}
|
|
527
|
+
function defaultDataRoot(env = process.env, platform = process.platform) {
|
|
528
|
+
const paths = platform === "win32" ? path5.win32 : path5.posix;
|
|
529
|
+
if (env.NARRARIUM_SERVER_HOME?.trim()) return paths.resolve(env.NARRARIUM_SERVER_HOME.trim());
|
|
530
|
+
if (platform === "win32") return paths.resolve(env.APPDATA ?? paths.join(homedir2(), "AppData", "Roaming"), "Narrarium", "server");
|
|
531
|
+
if (platform === "darwin") return paths.resolve(env.HOME ?? homedir2(), "Library", "Application Support", "Narrarium Server");
|
|
532
|
+
const xdg = env.XDG_DATA_HOME;
|
|
533
|
+
return paths.resolve(xdg && xdg.startsWith("/") ? xdg : paths.join(env.HOME ?? homedir2(), ".local", "share"), "narrarium-server");
|
|
534
|
+
}
|
|
535
|
+
var NETWORK_AND_SYSTEM_VARIABLES = [
|
|
536
|
+
"PATH",
|
|
537
|
+
"HOME",
|
|
538
|
+
"USERPROFILE",
|
|
539
|
+
"HOMEDRIVE",
|
|
540
|
+
"HOMEPATH",
|
|
541
|
+
"APPDATA",
|
|
542
|
+
"LOCALAPPDATA",
|
|
543
|
+
"SystemRoot",
|
|
544
|
+
"WINDIR",
|
|
545
|
+
"ComSpec",
|
|
546
|
+
"PATHEXT",
|
|
547
|
+
"TEMP",
|
|
548
|
+
"TMP",
|
|
549
|
+
"XDG_CACHE_HOME",
|
|
550
|
+
"XDG_CONFIG_HOME",
|
|
551
|
+
"HTTPS_PROXY",
|
|
552
|
+
"https_proxy",
|
|
553
|
+
"HTTP_PROXY",
|
|
554
|
+
"http_proxy",
|
|
555
|
+
"ALL_PROXY",
|
|
556
|
+
"all_proxy",
|
|
557
|
+
"NO_PROXY",
|
|
558
|
+
"no_proxy",
|
|
559
|
+
"SSL_CERT_FILE",
|
|
560
|
+
"SSL_CERT_DIR",
|
|
561
|
+
"NODE_EXTRA_CA_CERTS"
|
|
562
|
+
];
|
|
563
|
+
function sanitizedNpmEnvironment(source = process.env) {
|
|
564
|
+
const env = { NPM_CONFIG_IGNORE_SCRIPTS: "true", NPM_CONFIG_UPDATE_NOTIFIER: "false" };
|
|
565
|
+
for (const name of NETWORK_AND_SYSTEM_VARIABLES) if (source[name] !== void 0) env[name] = source[name];
|
|
566
|
+
return env;
|
|
567
|
+
}
|
|
568
|
+
function parseUpdateRequest(value) {
|
|
569
|
+
if (!isPlainObject(value) || !exactKeys(value, ["schemaVersion", "packageName", "version", "requestedAt", "requestId", "source"])) throw new Error("Not a valid update request.");
|
|
570
|
+
assertExactSemver(value.version);
|
|
571
|
+
if (value.schemaVersion !== 1 || value.packageName !== PACKAGE_NAME || value.source !== "client" && value.source !== "admin" || !validIso(value.requestedAt) || typeof value.requestId !== "string" || !UUID.test(value.requestId)) {
|
|
572
|
+
throw new Error("Not a valid update request.");
|
|
573
|
+
}
|
|
574
|
+
return value;
|
|
575
|
+
}
|
|
576
|
+
function parseUpdateResult(value) {
|
|
577
|
+
if (!isPlainObject(value) || !exactKeys(value, ["schemaVersion", "requestId", "state", "outcome", "version", "fromVersion", "at", "message"])) throw new Error("Not a valid update result.");
|
|
578
|
+
assertExactSemver(value.version);
|
|
579
|
+
assertExactSemver(value.fromVersion);
|
|
580
|
+
const outcome = value.outcome;
|
|
581
|
+
const consistent = value.state === "completed" ? outcome === "completed" : value.state === "failed" && (outcome === "failed" || outcome === "limited" || outcome === "stopping");
|
|
582
|
+
if (value.schemaVersion !== 1 || typeof value.requestId !== "string" || !UUID.test(value.requestId) || !consistent || !validIso(value.at) || value.message !== UPDATE_MESSAGES[outcome]) {
|
|
583
|
+
throw new Error("Not a valid update result.");
|
|
584
|
+
}
|
|
585
|
+
return value;
|
|
586
|
+
}
|
|
587
|
+
var UPDATE_REQUEST_FILE = path5.join("private", "update-request.json");
|
|
588
|
+
var UPDATE_RESULT_FILE = path5.join("private", "update-result.json");
|
|
589
|
+
async function readBoundedJson(file, maxBytes = MAX_CONTROL_FILE_BYTES) {
|
|
590
|
+
let handle;
|
|
591
|
+
try {
|
|
592
|
+
const info = await fs4.lstat(file);
|
|
593
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size > maxBytes) throw new Error("Control file is not regular or too large.");
|
|
594
|
+
handle = await fs4.open(file, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
|
|
595
|
+
const opened = await handle.stat();
|
|
596
|
+
if (opened.dev !== info.dev || opened.ino !== info.ino || opened.size > maxBytes) throw new Error("Control file changed while it was read.");
|
|
597
|
+
} catch (error) {
|
|
598
|
+
if (error.code === "ENOENT") return void 0;
|
|
599
|
+
throw error;
|
|
600
|
+
}
|
|
601
|
+
try {
|
|
602
|
+
const bytes = await handle.readFile();
|
|
603
|
+
if (bytes.byteLength > maxBytes) throw new Error("Control file over the limit.");
|
|
604
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
605
|
+
} finally {
|
|
606
|
+
await handle.close();
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
async function renameWithRetry(from, to) {
|
|
610
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
611
|
+
try {
|
|
612
|
+
await fs4.rename(from, to);
|
|
613
|
+
return;
|
|
614
|
+
} catch (error) {
|
|
615
|
+
const code = error.code;
|
|
616
|
+
if (attempt >= 12 || process.platform !== "win32" || !["EPERM", "EACCES", "EBUSY"].includes(code ?? "")) throw error;
|
|
617
|
+
await new Promise((done) => setTimeout(done, 15 * (attempt + 1)));
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
async function writeControlJson(file, value) {
|
|
622
|
+
const parent = path5.dirname(file);
|
|
623
|
+
await fs4.mkdir(parent, { recursive: true, mode: 448 });
|
|
624
|
+
if (process.platform !== "win32") await fs4.chmod(parent, 448);
|
|
625
|
+
const data = Buffer.from(`${JSON.stringify(value)}
|
|
626
|
+
`);
|
|
627
|
+
if (data.byteLength > MAX_CONTROL_FILE_BYTES) throw new Error("Control file over the limit.");
|
|
628
|
+
const temporary = `${file}.new-${randomUUID3()}`;
|
|
629
|
+
const handle = await fs4.open(temporary, "wx", 384);
|
|
630
|
+
try {
|
|
631
|
+
await handle.writeFile(data);
|
|
632
|
+
await handle.sync();
|
|
633
|
+
await handle.close();
|
|
634
|
+
await renameWithRetry(temporary, file);
|
|
635
|
+
} finally {
|
|
636
|
+
await handle.close().catch(() => void 0);
|
|
637
|
+
await fs4.unlink(temporary).catch(() => void 0);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
async function regularFile(file) {
|
|
641
|
+
try {
|
|
642
|
+
const stat2 = await fs4.lstat(file);
|
|
643
|
+
return stat2.isFile() && !stat2.isSymbolicLink() && stat2.nlink === 1;
|
|
644
|
+
} catch (error) {
|
|
645
|
+
if (error.code === "ENOENT") return false;
|
|
646
|
+
throw error;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
async function ensureDataRoot(dataRoot) {
|
|
650
|
+
const root = path5.resolve(dataRoot);
|
|
651
|
+
await fs4.mkdir(root, { recursive: true, mode: 448 });
|
|
652
|
+
const stat2 = await fs4.lstat(root);
|
|
653
|
+
if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw new Error("The data folder must be a regular directory.");
|
|
654
|
+
if (process.platform !== "win32") await fs4.chmod(root, 448);
|
|
655
|
+
const privateDir = path5.join(root, "private");
|
|
656
|
+
await fs4.mkdir(privateDir, { recursive: true, mode: 448 });
|
|
657
|
+
const privateStat = await fs4.lstat(privateDir);
|
|
658
|
+
if (!privateStat.isDirectory() || privateStat.isSymbolicLink()) throw new Error("The private folder of the server is not safe.");
|
|
659
|
+
if (process.platform !== "win32") await fs4.chmod(privateDir, 448);
|
|
660
|
+
return root;
|
|
661
|
+
}
|
|
662
|
+
function cmdQuote(value) {
|
|
663
|
+
return /^[A-Za-z0-9_@=:.,/\\+-]+$/.test(value) ? value : `"${value.replace(/"/g, '""')}"`;
|
|
664
|
+
}
|
|
665
|
+
function spawnCommand(command, args, options) {
|
|
666
|
+
return new Promise((accept, reject) => {
|
|
667
|
+
const limits = { stdout: 1024 * 1024, stderr: 64 * 1024 };
|
|
668
|
+
let stdout = "";
|
|
669
|
+
let stderr = "";
|
|
670
|
+
let settled = false;
|
|
671
|
+
const viaShell = process.platform === "win32" && /\.cmd$/i.test(command);
|
|
672
|
+
const child = viaShell ? spawn([command, ...args].map(cmdQuote).join(" "), { cwd: options.cwd, env: options.env, shell: true, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }) : spawn(command, [...args], { cwd: options.cwd, env: options.env, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
673
|
+
const timer = options.timeoutMs ? setTimeout(() => child.kill("SIGKILL"), options.timeoutMs) : void 0;
|
|
674
|
+
const finish = (action) => {
|
|
675
|
+
if (settled) return;
|
|
676
|
+
settled = true;
|
|
677
|
+
if (timer) clearTimeout(timer);
|
|
678
|
+
action();
|
|
679
|
+
};
|
|
680
|
+
child.once("error", () => finish(() => reject(new Error(`Could not run ${command}.`))));
|
|
681
|
+
child.stdout?.on("data", (chunk) => {
|
|
682
|
+
if (Buffer.byteLength(stdout) + chunk.byteLength > limits.stdout) {
|
|
683
|
+
child.kill("SIGKILL");
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
stdout += chunk.toString("utf8");
|
|
687
|
+
});
|
|
688
|
+
child.stderr?.on("data", (chunk) => {
|
|
689
|
+
if (Buffer.byteLength(stderr) + chunk.byteLength > limits.stderr) return;
|
|
690
|
+
stderr += chunk.toString("utf8");
|
|
691
|
+
});
|
|
692
|
+
child.once("close", (code) => finish(() => accept({ code: code ?? 1, stdout, stderr })));
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
function npmInvocation(platform = process.platform, execPath = process.execPath) {
|
|
696
|
+
if (platform !== "win32") return { command: "npm", prefix: [] };
|
|
697
|
+
const cli = path5.join(path5.dirname(execPath), "node_modules", "npm", "bin", "npm-cli.js");
|
|
698
|
+
return existsSync(cli) ? { command: execPath, prefix: [cli] } : { command: "npm.cmd", prefix: [] };
|
|
699
|
+
}
|
|
700
|
+
var RuntimeInstaller = class {
|
|
701
|
+
dataRoot;
|
|
702
|
+
runtimeRoot;
|
|
703
|
+
runner;
|
|
704
|
+
npm;
|
|
705
|
+
npmPrefix;
|
|
706
|
+
now;
|
|
707
|
+
uuid;
|
|
708
|
+
constructor(options) {
|
|
709
|
+
this.dataRoot = path5.resolve(options.dataRoot);
|
|
710
|
+
this.runtimeRoot = path5.join(this.dataRoot, "private", "npm-runtime");
|
|
711
|
+
this.runner = options.runner ?? spawnCommand;
|
|
712
|
+
const npm = options.npmBinary ? { command: options.npmBinary, prefix: [] } : npmInvocation();
|
|
713
|
+
this.npm = npm.command;
|
|
714
|
+
this.npmPrefix = npm.prefix;
|
|
715
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
716
|
+
this.uuid = options.uuid ?? randomUUID3;
|
|
717
|
+
}
|
|
718
|
+
async runNpm(args) {
|
|
719
|
+
const result = await this.runner(this.npm, [...this.npmPrefix, ...args, "--registry=https://registry.npmjs.org"], { cwd: this.dataRoot, env: sanitizedNpmEnvironment(), timeoutMs: 10 * 6e4 });
|
|
720
|
+
if (result.code !== 0) throw new Error(`npm ${args[0]} did not succeed.`);
|
|
721
|
+
return result;
|
|
722
|
+
}
|
|
723
|
+
async latestVersion() {
|
|
724
|
+
await ensureDataRoot(this.dataRoot);
|
|
725
|
+
const result = await this.runNpm(["view", PACKAGE_NAME, "version", "--json"]);
|
|
726
|
+
let version;
|
|
727
|
+
try {
|
|
728
|
+
version = JSON.parse(result.stdout.trim());
|
|
729
|
+
} catch {
|
|
730
|
+
throw new Error("npm returned an invalid version list.");
|
|
731
|
+
}
|
|
732
|
+
if (Array.isArray(version) && version.length === 1) version = version[0];
|
|
733
|
+
assertExactSemver(version);
|
|
734
|
+
return version;
|
|
735
|
+
}
|
|
736
|
+
async assertTrustedRelease(version, allowRegistryBootstrap = false) {
|
|
737
|
+
const result = await this.runNpm(["view", `${PACKAGE_NAME}@${version}`, "--json"]);
|
|
738
|
+
let metadata;
|
|
739
|
+
try {
|
|
740
|
+
metadata = JSON.parse(result.stdout);
|
|
741
|
+
} catch {
|
|
742
|
+
throw new Error("npm returned invalid package metadata.");
|
|
743
|
+
}
|
|
744
|
+
trustedNpmReleaseMetadata(metadata, version, allowRegistryBootstrap);
|
|
745
|
+
}
|
|
746
|
+
async installVersion(requested = "latest", options = {}) {
|
|
747
|
+
assertSupportedNode();
|
|
748
|
+
await ensureDataRoot(this.dataRoot);
|
|
749
|
+
const version = requested === "latest" ? await this.latestVersion() : requested;
|
|
750
|
+
assertExactSemver(version);
|
|
751
|
+
await this.assertTrustedRelease(version, options.bootstrapRegistryRelease === true);
|
|
752
|
+
await fs4.mkdir(path5.join(this.runtimeRoot, "versions"), { recursive: true, mode: 448 });
|
|
753
|
+
const staging = path5.join(this.runtimeRoot, `staging-${this.uuid()}`);
|
|
754
|
+
const destination = path5.join(this.runtimeRoot, "versions", version);
|
|
755
|
+
await fs4.mkdir(staging, { recursive: true, mode: 448 });
|
|
756
|
+
try {
|
|
757
|
+
await this.runNpm(["install", "--prefix", staging, "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact", "--package-lock=true", `${PACKAGE_NAME}@${version}`]);
|
|
758
|
+
await this.runNpm(["audit", "signatures", "--prefix", staging]);
|
|
759
|
+
const stagedPackage = path5.join(staging, "node_modules", PACKAGE_NAME);
|
|
760
|
+
await this.validateInstalledPackage(stagedPackage, version);
|
|
761
|
+
if (await regularFile(path5.join(destination, "package.json"))) {
|
|
762
|
+
await this.validateInstalledPackage(destination, version);
|
|
763
|
+
if (await this.packageDigest(destination) !== await this.packageDigest(stagedPackage)) throw new Error("A different copy of this version is already installed: it was not replaced.");
|
|
764
|
+
} else {
|
|
765
|
+
await renameWithRetry(stagedPackage, destination);
|
|
766
|
+
}
|
|
767
|
+
await this.activate(version);
|
|
768
|
+
const active = await this.activeRuntime();
|
|
769
|
+
if (!active) throw new Error("The activated runtime cannot be read.");
|
|
770
|
+
return active;
|
|
771
|
+
} finally {
|
|
772
|
+
await fs4.rm(staging, { recursive: true, force: true });
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
async packageDigest(root) {
|
|
776
|
+
const hash = createHash3("sha256");
|
|
777
|
+
let files = 0;
|
|
778
|
+
let bytes = 0;
|
|
779
|
+
const walk = async (directory, relative = "") => {
|
|
780
|
+
const entries = await fs4.readdir(directory, { withFileTypes: true });
|
|
781
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
782
|
+
for (const entry of entries) {
|
|
783
|
+
const name = relative ? `${relative}/${entry.name}` : entry.name;
|
|
784
|
+
const file = path5.join(directory, entry.name);
|
|
785
|
+
if (entry.isSymbolicLink()) throw new Error("npm package with links: refused.");
|
|
786
|
+
if (entry.isDirectory()) {
|
|
787
|
+
await walk(file, name);
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
if (!entry.isFile()) throw new Error("npm package with irregular files: refused.");
|
|
791
|
+
const stat2 = await fs4.lstat(file);
|
|
792
|
+
files += 1;
|
|
793
|
+
bytes += stat2.size;
|
|
794
|
+
if (stat2.size > 20 * 1024 * 1024 || files > 5e3 || bytes > 80 * 1024 * 1024) throw new Error("npm package over the safety limits.");
|
|
795
|
+
hash.update(JSON.stringify(name));
|
|
796
|
+
hash.update("\0");
|
|
797
|
+
hash.update(await fs4.readFile(file));
|
|
798
|
+
hash.update("\0");
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
await walk(root);
|
|
802
|
+
return hash.digest("hex");
|
|
803
|
+
}
|
|
804
|
+
async validateInstalledPackage(root, expectedVersion) {
|
|
805
|
+
const value = await readBoundedJson(path5.join(root, "package.json"));
|
|
806
|
+
if (!isPlainObject(value) || value.name !== PACKAGE_NAME || value.version !== expectedVersion) throw new Error("The installed npm package does not match.");
|
|
807
|
+
if (!await regularFile(path5.join(root, "dist", "cli.mjs")) || !await regularFile(path5.join(root, "dist", "server.mjs"))) throw new Error("The installed npm package is incomplete.");
|
|
808
|
+
}
|
|
809
|
+
async activate(version) {
|
|
810
|
+
const at = this.now().toISOString();
|
|
811
|
+
await this.validateInstalledPackage(path5.join(this.runtimeRoot, "versions", version), version);
|
|
812
|
+
await writeControlJson(path5.join(this.runtimeRoot, "active.json"), { schemaVersion: 1, packageName: PACKAGE_NAME, version, activatedAt: at });
|
|
813
|
+
const state = { schemaVersion: 1, packageName: PACKAGE_NAME, channel: "latest", activeVersion: version, installedAt: at };
|
|
814
|
+
await writeControlJson(path5.join(this.dataRoot, "private", "npm-install.json"), state);
|
|
815
|
+
}
|
|
816
|
+
async activeRuntime() {
|
|
817
|
+
const value = await readBoundedJson(path5.join(this.runtimeRoot, "active.json"));
|
|
818
|
+
if (value === void 0) return void 0;
|
|
819
|
+
if (!isPlainObject(value) || !exactKeys(value, ["schemaVersion", "packageName", "version", "activatedAt"]) || value.schemaVersion !== 1 || value.packageName !== PACKAGE_NAME || !validIso(value.activatedAt)) {
|
|
820
|
+
throw new Error("The runtime state is not valid.");
|
|
821
|
+
}
|
|
822
|
+
assertExactSemver(value.version);
|
|
823
|
+
const packageRoot = path5.join(this.runtimeRoot, "versions", value.version);
|
|
824
|
+
await this.validateInstalledPackage(packageRoot, value.version);
|
|
825
|
+
return { ...value, packageRoot, serverPath: path5.join(packageRoot, "dist", "server.mjs") };
|
|
826
|
+
}
|
|
827
|
+
async installerState() {
|
|
828
|
+
const value = await readBoundedJson(path5.join(this.dataRoot, "private", "npm-install.json"));
|
|
829
|
+
if (value === void 0) return void 0;
|
|
830
|
+
if (!isPlainObject(value) || !exactKeys(value, ["schemaVersion", "packageName", "channel", "activeVersion", "installedAt"]) || value.schemaVersion !== 1 || value.packageName !== PACKAGE_NAME || value.channel !== "latest" || !validIso(value.installedAt)) {
|
|
831
|
+
throw new Error("The installation state is not valid.");
|
|
832
|
+
}
|
|
833
|
+
assertExactSemver(value.activeVersion);
|
|
834
|
+
return value;
|
|
835
|
+
}
|
|
836
|
+
async writeUpdateRequest(request) {
|
|
837
|
+
await writeControlJson(path5.join(this.dataRoot, UPDATE_REQUEST_FILE), parseUpdateRequest(request));
|
|
838
|
+
}
|
|
839
|
+
async writeUpdateResult(result) {
|
|
840
|
+
await writeControlJson(path5.join(this.dataRoot, UPDATE_RESULT_FILE), parseUpdateResult(result));
|
|
841
|
+
}
|
|
842
|
+
async readUpdateRequest() {
|
|
843
|
+
const value = await readBoundedJson(path5.join(this.dataRoot, UPDATE_REQUEST_FILE));
|
|
844
|
+
return value === void 0 ? void 0 : parseUpdateRequest(value);
|
|
845
|
+
}
|
|
846
|
+
async readUpdateResult() {
|
|
847
|
+
const value = await readBoundedJson(path5.join(this.dataRoot, UPDATE_RESULT_FILE));
|
|
848
|
+
return value === void 0 ? void 0 : parseUpdateResult(value);
|
|
849
|
+
}
|
|
850
|
+
async deleteMatchingUpdateRequest(expected) {
|
|
851
|
+
const current = await this.readUpdateRequest();
|
|
852
|
+
if (!current || JSON.stringify(current) !== JSON.stringify(expected)) return false;
|
|
853
|
+
await fs4.unlink(path5.join(this.dataRoot, UPDATE_REQUEST_FILE));
|
|
854
|
+
return true;
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
function childHandle(child) {
|
|
858
|
+
return {
|
|
859
|
+
kill: (signal) => child.kill(signal),
|
|
860
|
+
exited: new Promise((accept) => {
|
|
861
|
+
let finished = false;
|
|
862
|
+
const done = (code, signal) => {
|
|
863
|
+
if (finished) return;
|
|
864
|
+
finished = true;
|
|
865
|
+
accept({ code, signal });
|
|
866
|
+
};
|
|
867
|
+
child.once("error", () => done(1, null));
|
|
868
|
+
child.once("exit", done);
|
|
869
|
+
})
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
function supervisedChildEnvironment(environment = process.env) {
|
|
873
|
+
const clean = { [SUPERVISED_ENV]: "1", NPM_CONFIG_UPDATE_NOTIFIER: "false" };
|
|
874
|
+
for (const name of [...NETWORK_AND_SYSTEM_VARIABLES, "XDG_DATA_HOME", "NARRARIUM_SERVER_HOME"]) if (environment[name] !== void 0) clean[name] = environment[name];
|
|
875
|
+
return clean;
|
|
876
|
+
}
|
|
877
|
+
async function withTimeout(promise, ms) {
|
|
878
|
+
let timer;
|
|
879
|
+
try {
|
|
880
|
+
return await Promise.race([promise, new Promise((resolve) => {
|
|
881
|
+
timer = setTimeout(() => resolve(void 0), ms);
|
|
882
|
+
})]);
|
|
883
|
+
} finally {
|
|
884
|
+
if (timer) clearTimeout(timer);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
function defaultChild(childArgs) {
|
|
888
|
+
return (serverPath, dataRoot) => childHandle(spawn(process.execPath, [serverPath, "--data-root", dataRoot, ...childArgs], {
|
|
889
|
+
shell: false,
|
|
890
|
+
windowsHide: false,
|
|
891
|
+
stdio: "inherit",
|
|
892
|
+
env: supervisedChildEnvironment()
|
|
893
|
+
}));
|
|
894
|
+
}
|
|
895
|
+
async function writeUpdateFailure(installer, request, fromVersion, outcome) {
|
|
896
|
+
await installer.writeUpdateResult({ schemaVersion: 1, requestId: request.requestId, state: "failed", outcome, version: request.version, fromVersion, at: (/* @__PURE__ */ new Date()).toISOString(), message: UPDATE_MESSAGES[outcome] });
|
|
897
|
+
}
|
|
898
|
+
async function superviseServer(options) {
|
|
899
|
+
assertSupportedNode();
|
|
900
|
+
const installer = options.installer;
|
|
901
|
+
const pollMs = options.pollMs ?? 500;
|
|
902
|
+
const stopTimeoutMs = options.stopTimeoutMs ?? 3e4;
|
|
903
|
+
const hourMs = options.hourMs ?? 60 * 6e4;
|
|
904
|
+
const spawnChild = options.spawnChild ?? defaultChild(options.childArgs ?? []);
|
|
905
|
+
const log = options.log ?? (() => void 0);
|
|
906
|
+
const updateRestarts = [];
|
|
907
|
+
const ignoredRequests = /* @__PURE__ */ new Set();
|
|
908
|
+
let stopping = false;
|
|
909
|
+
let currentChild;
|
|
910
|
+
const onSigint = () => {
|
|
911
|
+
stopping = true;
|
|
912
|
+
currentChild?.kill("SIGINT");
|
|
913
|
+
};
|
|
914
|
+
const onSigterm = () => {
|
|
915
|
+
stopping = true;
|
|
916
|
+
currentChild?.kill("SIGTERM");
|
|
917
|
+
};
|
|
918
|
+
if (options.forwardSignals !== false) {
|
|
919
|
+
process.once("SIGINT", onSigint);
|
|
920
|
+
process.once("SIGTERM", onSigterm);
|
|
921
|
+
}
|
|
922
|
+
const prune = () => {
|
|
923
|
+
const cutoff = Date.now() - hourMs;
|
|
924
|
+
while (updateRestarts[0] !== void 0 && updateRestarts[0] < cutoff) updateRestarts.shift();
|
|
925
|
+
};
|
|
926
|
+
try {
|
|
927
|
+
if (!await installer.activeRuntime()) await installer.installVersion(options.currentVersion, { bootstrapRegistryRelease: true });
|
|
928
|
+
for (; ; ) {
|
|
929
|
+
const active = await installer.activeRuntime();
|
|
930
|
+
if (!active) throw new Error("No active runtime is available.");
|
|
931
|
+
currentChild = spawnChild(active.serverPath, installer.dataRoot);
|
|
932
|
+
let updateRequest;
|
|
933
|
+
for (; ; ) {
|
|
934
|
+
const exited = await withTimeout(currentChild.exited, pollMs);
|
|
935
|
+
if (exited !== void 0) {
|
|
936
|
+
try {
|
|
937
|
+
updateRequest = await installer.readUpdateRequest();
|
|
938
|
+
} catch {
|
|
939
|
+
updateRequest = void 0;
|
|
940
|
+
}
|
|
941
|
+
if (stopping || !updateRequest || ignoredRequests.has(updateRequest.requestId)) return exited;
|
|
942
|
+
break;
|
|
943
|
+
}
|
|
944
|
+
try {
|
|
945
|
+
const request = await installer.readUpdateRequest();
|
|
946
|
+
if (!request || ignoredRequests.has(request.requestId)) continue;
|
|
947
|
+
updateRequest = request;
|
|
948
|
+
prune();
|
|
949
|
+
if (updateRestarts.length >= 3) {
|
|
950
|
+
await writeUpdateFailure(installer, request, active.version, "limited");
|
|
951
|
+
ignoredRequests.add(request.requestId);
|
|
952
|
+
continue;
|
|
953
|
+
}
|
|
954
|
+
log(`Update to ${request.version} requested: stopping the server.`);
|
|
955
|
+
currentChild.kill("SIGTERM");
|
|
956
|
+
const childExit = await withTimeout(currentChild.exited, stopTimeoutMs);
|
|
957
|
+
if (!childExit) {
|
|
958
|
+
ignoredRequests.add(request.requestId);
|
|
959
|
+
await writeUpdateFailure(installer, request, active.version, "stopping");
|
|
960
|
+
continue;
|
|
961
|
+
}
|
|
962
|
+
break;
|
|
963
|
+
} catch {
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
if (!updateRequest || stopping) return await currentChild.exited;
|
|
967
|
+
prune();
|
|
968
|
+
if (updateRestarts.length >= 3) {
|
|
969
|
+
await writeUpdateFailure(installer, updateRequest, active.version, "limited");
|
|
970
|
+
ignoredRequests.add(updateRequest.requestId);
|
|
971
|
+
return await spawnChild(active.serverPath, installer.dataRoot).exited;
|
|
972
|
+
}
|
|
973
|
+
let installed;
|
|
974
|
+
try {
|
|
975
|
+
installed = await installer.installVersion(updateRequest.version);
|
|
976
|
+
} catch (error) {
|
|
977
|
+
log(`Update to ${updateRequest.version} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
978
|
+
await writeUpdateFailure(installer, updateRequest, active.version, "failed").catch(() => void 0);
|
|
979
|
+
ignoredRequests.add(updateRequest.requestId);
|
|
980
|
+
}
|
|
981
|
+
if (installed) {
|
|
982
|
+
log(`Updated from ${active.version} to ${installed.version}.`);
|
|
983
|
+
await installer.writeUpdateResult({ schemaVersion: 1, requestId: updateRequest.requestId, state: "completed", outcome: "completed", version: updateRequest.version, fromVersion: active.version, at: (/* @__PURE__ */ new Date()).toISOString(), message: UPDATE_MESSAGES.completed }).catch(() => void 0);
|
|
984
|
+
await installer.deleteMatchingUpdateRequest(updateRequest).catch(() => false);
|
|
985
|
+
updateRestarts.push(Date.now());
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
} finally {
|
|
989
|
+
if (options.forwardSignals !== false) {
|
|
990
|
+
process.off("SIGINT", onSigint);
|
|
991
|
+
process.off("SIGTERM", onSigterm);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// src/tunnel.ts
|
|
997
|
+
var MAX_CAPTURE_BYTES = 64 * 1024;
|
|
998
|
+
function parseCloudflaredVersion(text) {
|
|
999
|
+
const match = /(?:^|\s)cloudflared version\s+(\d+)\.(\d+)\.(\d+)(?:\s|$)/i.exec(text);
|
|
1000
|
+
if (!match) return void 0;
|
|
1001
|
+
const parsed = match.slice(1).map(Number);
|
|
1002
|
+
return parsed.every(Number.isSafeInteger) ? parsed : void 0;
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// src/version.ts
|
|
1006
|
+
var SERVER_VERSION = "0.1.0";
|
|
1007
|
+
|
|
1008
|
+
// src/cli-main.ts
|
|
1009
|
+
var HELP = `Narrarium personal server ${SERVER_VERSION}
|
|
1010
|
+
|
|
1011
|
+
Usage:
|
|
1012
|
+
npx ${PACKAGE_NAME} [start] [--data-root DIR] [--port N] [--admin-port N] [--label NAME] [--origin URL] [--direct] [--verbose]
|
|
1013
|
+
npx ${PACKAGE_NAME} setup [--data-root DIR] [--autostart] [--port N] [--admin-port N] [--label NAME]
|
|
1014
|
+
npx ${PACKAGE_NAME} status [--data-root DIR]
|
|
1015
|
+
npx ${PACKAGE_NAME} doctor [--data-root DIR]
|
|
1016
|
+
npx ${PACKAGE_NAME} admin-code [--data-root DIR]
|
|
1017
|
+
npx ${PACKAGE_NAME} rotate-admin-code [--data-root DIR]
|
|
1018
|
+
npx ${PACKAGE_NAME} set-admin-code [--data-root DIR] [--code-file FILE-0600]
|
|
1019
|
+
npx ${PACKAGE_NAME} client-token [--data-root DIR] [--label NAME] [--scope read,write,run[,update]]
|
|
1020
|
+
npx ${PACKAGE_NAME} update [--data-root DIR] [--to VERSION]
|
|
1021
|
+
npx ${PACKAGE_NAME} --version
|
|
1022
|
+
|
|
1023
|
+
start Run the server under the update supervisor (default). --direct runs it without the supervisor.
|
|
1024
|
+
setup Install the verified runtime in the data folder; --autostart also starts it at login (Linux, macOS).
|
|
1025
|
+
admin-code Show the code that opens the admin panel (${"http://127.0.0.1:" + DEFAULT_ADMIN_PORT}).
|
|
1026
|
+
client-token Create a client token to paste in Narrarium \u2192 Settings \u2192 Personal server.
|
|
1027
|
+
update Install the latest verified version (or --to VERSION); a running server keeps its version until restarted.
|
|
1028
|
+
|
|
1029
|
+
The data folder is ${defaultDataRoot()} unless --data-root or NARRARIUM_SERVER_HOME says otherwise.
|
|
1030
|
+
`;
|
|
1031
|
+
var COMMANDS = ["start", "setup", "status", "doctor", "admin-code", "rotate-admin-code", "set-admin-code", "client-token", "update"];
|
|
1032
|
+
function port(value, flag) {
|
|
1033
|
+
const parsed = Number(value);
|
|
1034
|
+
if (!value || !Number.isInteger(parsed) || parsed < 1 || parsed > 65535) throw new Error(`${flag} needs a port between 1 and 65535.`);
|
|
1035
|
+
return parsed;
|
|
1036
|
+
}
|
|
1037
|
+
function parseCommand(argv) {
|
|
1038
|
+
const first = argv[0];
|
|
1039
|
+
if (first === "--help" || first === "-h" || first === "help") return { command: "help", origins: [] };
|
|
1040
|
+
if (first === "--version" || first === "-v" || first === "version") return { command: "version", origins: [] };
|
|
1041
|
+
const explicit = first !== void 0 && !first.startsWith("--");
|
|
1042
|
+
if (explicit && !COMMANDS.includes(first)) throw new Error(`Unknown command: ${first}
|
|
1043
|
+
|
|
1044
|
+
${HELP}`);
|
|
1045
|
+
const parsed = { command: explicit ? first : "start", origins: [] };
|
|
1046
|
+
const value = (index, flag) => {
|
|
1047
|
+
const next = argv[index];
|
|
1048
|
+
if (!next || next.startsWith("--")) throw new Error(`${flag} needs a value.`);
|
|
1049
|
+
return next;
|
|
1050
|
+
};
|
|
1051
|
+
for (let index = explicit ? 1 : 0; index < argv.length; index += 1) {
|
|
1052
|
+
const flag = argv[index];
|
|
1053
|
+
const allowed = (commands) => commands.includes(parsed.command);
|
|
1054
|
+
if ((flag === "--data-root" || flag === "--data") && allowed(COMMANDS)) parsed.dataRoot = value(++index, flag);
|
|
1055
|
+
else if (flag === "--port" && allowed(["start", "setup"])) parsed.apiPort = port(argv[++index], flag);
|
|
1056
|
+
else if (flag === "--admin-port" && allowed(["start", "setup"])) parsed.adminPort = port(argv[++index], flag);
|
|
1057
|
+
else if (flag === "--label" && allowed(["start", "setup", "client-token"])) {
|
|
1058
|
+
const label = value(++index, flag);
|
|
1059
|
+
if (label.length > 80) throw new Error("--label must have at most 80 characters.");
|
|
1060
|
+
parsed.label = label;
|
|
1061
|
+
} else if (flag === "--origin" && allowed(["start"])) parsed.origins.push(value(++index, flag));
|
|
1062
|
+
else if (flag === "--direct" && allowed(["start"])) parsed.direct = true;
|
|
1063
|
+
else if (flag === "--verbose" && allowed(["start"])) parsed.verbose = true;
|
|
1064
|
+
else if (flag === "--autostart" && allowed(["setup"])) parsed.autostart = true;
|
|
1065
|
+
else if (flag === "--code-file" && allowed(["set-admin-code"])) parsed.codeFile = value(++index, flag);
|
|
1066
|
+
else if (flag === "--scope" && allowed(["client-token"])) parsed.scopes = value(++index, flag).split(",").map((scope) => scope.trim());
|
|
1067
|
+
else if (flag === "--to" && allowed(["update"])) {
|
|
1068
|
+
const version = value(++index, flag);
|
|
1069
|
+
assertExactSemver(version);
|
|
1070
|
+
parsed.requestedVersion = version;
|
|
1071
|
+
} else throw new Error(`Option not allowed for ${parsed.command}: ${flag}`);
|
|
1072
|
+
}
|
|
1073
|
+
return parsed;
|
|
1074
|
+
}
|
|
1075
|
+
function output(line = "") {
|
|
1076
|
+
process.stdout.write(`${line}
|
|
1077
|
+
`);
|
|
1078
|
+
}
|
|
1079
|
+
function probe(command, args) {
|
|
1080
|
+
const result = spawnSync2(command, [...args], { shell: process.platform === "win32" && /\.cmd$/i.test(command), windowsHide: true, encoding: "utf8", env: sanitizedNpmEnvironment(), timeout: 15e3 });
|
|
1081
|
+
return { ok: result.status === 0, output: `${result.stdout ?? ""}
|
|
1082
|
+
${result.stderr ?? ""}`.trim() };
|
|
1083
|
+
}
|
|
1084
|
+
function doctorChecks(dataRoot, platform = process.platform, run2 = probe) {
|
|
1085
|
+
const checks = [];
|
|
1086
|
+
try {
|
|
1087
|
+
assertSupportedNode();
|
|
1088
|
+
checks.push({ name: "Node.js", ok: true, required: true, detail: process.versions.node });
|
|
1089
|
+
} catch (error) {
|
|
1090
|
+
checks.push({ name: "Node.js", ok: false, required: true, detail: error instanceof Error ? error.message : "not supported" });
|
|
1091
|
+
}
|
|
1092
|
+
const npm = run2(platform === "win32" ? "npm.cmd" : "npm", ["--version"]);
|
|
1093
|
+
checks.push({ name: "npm (supervised updates)", ok: npm.ok, required: false, detail: npm.ok ? npm.output.split("\n")[0] : "npm is not available: updates cannot be installed" });
|
|
1094
|
+
const git = run2("git", ["--version"]);
|
|
1095
|
+
checks.push({ name: "git (GitHub books)", ok: git.ok, required: false, detail: git.ok ? git.output.split("\n")[0] : "git is not available: only local books" });
|
|
1096
|
+
if (platform === "linux") {
|
|
1097
|
+
const flock = run2("flock", ["--version"]);
|
|
1098
|
+
checks.push({ name: "flock (data folder lock)", ok: flock.ok, required: true, detail: flock.ok ? flock.output.split("\n")[0] : "install util-linux (flock)" });
|
|
1099
|
+
} else if (platform === "win32") {
|
|
1100
|
+
const powershell = run2("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "$PSVersionTable.PSVersion.ToString()"]);
|
|
1101
|
+
checks.push({ name: "PowerShell (lock and vault)", ok: powershell.ok, required: true, detail: powershell.ok ? powershell.output.split("\n")[0] : "PowerShell is not available" });
|
|
1102
|
+
}
|
|
1103
|
+
const cloudflared = run2(platform === "win32" ? "cloudflared.exe" : "cloudflared", ["--version"]);
|
|
1104
|
+
const version = cloudflared.ok ? parseCloudflaredVersion(cloudflared.output) : void 0;
|
|
1105
|
+
checks.push({ name: "cloudflared (optional remote access)", ok: Boolean(version), required: false, detail: version ? version.join(".") : "not installed (needed only for a Cloudflare tunnel)" });
|
|
1106
|
+
let writable = false;
|
|
1107
|
+
try {
|
|
1108
|
+
if (existsSync2(dataRoot)) accessSync(dataRoot, constants4.W_OK);
|
|
1109
|
+
else accessSync(path6.dirname(dataRoot), constants4.W_OK);
|
|
1110
|
+
writable = true;
|
|
1111
|
+
} catch {
|
|
1112
|
+
writable = false;
|
|
1113
|
+
}
|
|
1114
|
+
checks.push({ name: "Data folder", ok: writable, required: true, detail: `${dataRoot}${writable ? "" : " is not writable"}` });
|
|
1115
|
+
return checks;
|
|
1116
|
+
}
|
|
1117
|
+
async function serverRunning(apiPort) {
|
|
1118
|
+
try {
|
|
1119
|
+
const response = await fetch(`http://127.0.0.1:${apiPort}/api/v1/info`, { signal: AbortSignal.timeout(2e3) });
|
|
1120
|
+
if (!response.ok) return void 0;
|
|
1121
|
+
const info = await response.json();
|
|
1122
|
+
return info.name === PACKAGE_NAME && typeof info.serverVersion === "string" ? info.serverVersion : void 0;
|
|
1123
|
+
} catch {
|
|
1124
|
+
return void 0;
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
function runDirect(dataRoot, verbose) {
|
|
1128
|
+
const serverPath = fileURLToPath(new URL("./server.mjs", import.meta.url));
|
|
1129
|
+
return new Promise((resolve) => {
|
|
1130
|
+
const env = { ...process.env };
|
|
1131
|
+
delete env.NARRARIUM_SUPERVISED;
|
|
1132
|
+
const child = spawn2(process.execPath, [serverPath, "--data-root", dataRoot, ...verbose ? ["--verbose"] : []], { stdio: "inherit", env, windowsHide: false });
|
|
1133
|
+
const forward = (signal) => () => child.kill(signal);
|
|
1134
|
+
const onInt = forward("SIGINT");
|
|
1135
|
+
const onTerm = forward("SIGTERM");
|
|
1136
|
+
process.once("SIGINT", onInt);
|
|
1137
|
+
process.once("SIGTERM", onTerm);
|
|
1138
|
+
child.once("exit", (code, signal) => {
|
|
1139
|
+
process.off("SIGINT", onInt);
|
|
1140
|
+
process.off("SIGTERM", onTerm);
|
|
1141
|
+
resolve(code ?? (signal ? 1 : 0));
|
|
1142
|
+
});
|
|
1143
|
+
child.once("error", () => resolve(1));
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
async function main(argv = process.argv.slice(2), environment = process.env) {
|
|
1147
|
+
let parsed;
|
|
1148
|
+
try {
|
|
1149
|
+
parsed = parseCommand(argv);
|
|
1150
|
+
} catch (error) {
|
|
1151
|
+
process.stderr.write(`${error instanceof Error ? error.message : "Invalid command."}
|
|
1152
|
+
`);
|
|
1153
|
+
return 2;
|
|
1154
|
+
}
|
|
1155
|
+
if (parsed.command === "help") {
|
|
1156
|
+
output(HELP.trimEnd());
|
|
1157
|
+
return 0;
|
|
1158
|
+
}
|
|
1159
|
+
if (parsed.command === "version") {
|
|
1160
|
+
output(SERVER_VERSION);
|
|
1161
|
+
return 0;
|
|
1162
|
+
}
|
|
1163
|
+
const dataRoot = path6.resolve(parsed.dataRoot ?? defaultDataRoot(environment));
|
|
1164
|
+
const installer = new RuntimeInstaller({ dataRoot });
|
|
1165
|
+
try {
|
|
1166
|
+
if (parsed.command === "start") {
|
|
1167
|
+
const required = doctorChecks(dataRoot).filter((check) => check.required && !check.ok);
|
|
1168
|
+
if (required.length) throw new Error(required.map((check) => `${check.name}: ${check.detail}`).join("; "));
|
|
1169
|
+
const config = await loadServerConfig(dataRoot, { label: parsed.label, apiPort: parsed.apiPort, adminPort: parsed.adminPort, origins: parsed.origins });
|
|
1170
|
+
const running = await serverRunning(config.apiPort);
|
|
1171
|
+
if (running) throw new Error(`A narrarium-server ${running} already answers on port ${config.apiPort}. Stop it first or use --port.`);
|
|
1172
|
+
if (parsed.direct) return await runDirect(dataRoot, Boolean(parsed.verbose));
|
|
1173
|
+
try {
|
|
1174
|
+
const active = await installer.activeRuntime().catch(() => void 0);
|
|
1175
|
+
if (!active || compareSemver(SERVER_VERSION, active.version) > 0) {
|
|
1176
|
+
output(active ? `Installing the verified runtime ${SERVER_VERSION} (was ${active.version})\u2026` : `Preparing the verified runtime ${SERVER_VERSION} in ${dataRoot}\u2026`);
|
|
1177
|
+
await installer.installVersion(SERVER_VERSION, { bootstrapRegistryRelease: true });
|
|
1178
|
+
}
|
|
1179
|
+
} catch (error) {
|
|
1180
|
+
if (!await installer.activeRuntime().catch(() => void 0)) {
|
|
1181
|
+
output(`The verified runtime could not be prepared (${error instanceof Error ? error.message : String(error)}).`);
|
|
1182
|
+
output("Starting directly instead: everything works, but the server cannot be updated remotely.");
|
|
1183
|
+
return await runDirect(dataRoot, Boolean(parsed.verbose));
|
|
1184
|
+
}
|
|
1185
|
+
output(`Keeping the installed runtime: ${error instanceof Error ? error.message : String(error)}`);
|
|
1186
|
+
}
|
|
1187
|
+
const exit = await superviseServer({ installer, currentVersion: SERVER_VERSION, childArgs: parsed.verbose ? ["--verbose"] : [], forwardSignals: true, log: (line) => output(`[supervisor] ${line}`) });
|
|
1188
|
+
if (exit.code !== null) return exit.code;
|
|
1189
|
+
return exit.signal ? 1 : 0;
|
|
1190
|
+
}
|
|
1191
|
+
if (parsed.command === "setup") {
|
|
1192
|
+
assertSupportedNode();
|
|
1193
|
+
const config = await loadServerConfig(dataRoot, { label: parsed.label, apiPort: parsed.apiPort, adminPort: parsed.adminPort });
|
|
1194
|
+
const active = await installer.installVersion(SERVER_VERSION, { bootstrapRegistryRelease: true });
|
|
1195
|
+
output(`Narrarium personal server ${active.version} installed in ${dataRoot}.`);
|
|
1196
|
+
if (parsed.autostart) {
|
|
1197
|
+
const configured = await configureAutostart(active, dataRoot, environment);
|
|
1198
|
+
output(configured.message);
|
|
1199
|
+
output(`Service file: ${configured.servicePath}`);
|
|
1200
|
+
} else {
|
|
1201
|
+
output(`Start it with: npx ${PACKAGE_NAME} start${parsed.dataRoot ? ` --data-root "${dataRoot}"` : ""}`);
|
|
1202
|
+
}
|
|
1203
|
+
output(`API: http://127.0.0.1:${config.apiPort} \xB7 admin panel: http://127.0.0.1:${config.adminPort} (open it on this computer).`);
|
|
1204
|
+
output(`Admin code: npx ${PACKAGE_NAME} admin-code${parsed.dataRoot ? ` --data-root "${dataRoot}"` : ""}`);
|
|
1205
|
+
return 0;
|
|
1206
|
+
}
|
|
1207
|
+
if (parsed.command === "status") {
|
|
1208
|
+
const config = await loadServerConfig(dataRoot);
|
|
1209
|
+
const state = await installer.installerState().catch(() => void 0);
|
|
1210
|
+
const active = await installer.activeRuntime().catch(() => void 0);
|
|
1211
|
+
const running = await serverRunning(config.apiPort);
|
|
1212
|
+
output(`Package: ${PACKAGE_NAME} ${SERVER_VERSION}`);
|
|
1213
|
+
output(`Data folder: ${dataRoot}`);
|
|
1214
|
+
output(`Active runtime: ${active?.version ?? state?.activeVersion ?? "not installed (run setup or start)"}`);
|
|
1215
|
+
output(`Running: ${running ? `yes, version ${running} on port ${config.apiPort}` : "no"}`);
|
|
1216
|
+
output(`API: http://127.0.0.1:${config.apiPort}`);
|
|
1217
|
+
output(`Admin panel: http://127.0.0.1:${config.adminPort}`);
|
|
1218
|
+
output(`Autostart: ${await autostartStatus(environment.HOME) ?? "not configured"}`);
|
|
1219
|
+
return 0;
|
|
1220
|
+
}
|
|
1221
|
+
if (parsed.command === "doctor") {
|
|
1222
|
+
const checks = doctorChecks(dataRoot);
|
|
1223
|
+
for (const check of checks) output(`${check.ok ? "OK " : check.required ? "FAIL" : "WARN"} ${check.name}: ${check.detail}`);
|
|
1224
|
+
const active = await installer.activeRuntime().catch(() => void 0);
|
|
1225
|
+
output(`${active ? "OK " : "WARN"} Runtime: ${active?.version ?? "not installed yet (start installs it)"}`);
|
|
1226
|
+
return checks.every((check) => check.ok || !check.required) ? 0 : 1;
|
|
1227
|
+
}
|
|
1228
|
+
if (parsed.command === "admin-code") {
|
|
1229
|
+
const config = await loadServerConfig(dataRoot);
|
|
1230
|
+
output(`Admin code (local secret): ${await readAdminCode(dataRoot)}`);
|
|
1231
|
+
output(`Open http://127.0.0.1:${config.adminPort} on this computer and sign in with it. Never paste it in public places.`);
|
|
1232
|
+
return 0;
|
|
1233
|
+
}
|
|
1234
|
+
if (parsed.command === "rotate-admin-code") {
|
|
1235
|
+
const config = await loadServerConfig(dataRoot);
|
|
1236
|
+
const code = await rotateLocalAdminCode({ dataRoot, adminPort: config.adminPort });
|
|
1237
|
+
output("The previous admin code no longer works.");
|
|
1238
|
+
output(`New admin code: ${code}`);
|
|
1239
|
+
return 0;
|
|
1240
|
+
}
|
|
1241
|
+
if (parsed.command === "set-admin-code") {
|
|
1242
|
+
const config = await loadServerConfig(dataRoot);
|
|
1243
|
+
const code = parsed.codeFile ? await readAdminCodeFile(path6.resolve(parsed.codeFile)) : await readSecretFromTerminal("New admin code (32-200 characters): ");
|
|
1244
|
+
await setLocalAdminCode({ dataRoot, adminPort: config.adminPort, code });
|
|
1245
|
+
output("The new admin code is active; previous admin sessions ended.");
|
|
1246
|
+
return 0;
|
|
1247
|
+
}
|
|
1248
|
+
if (parsed.command === "client-token") {
|
|
1249
|
+
const config = await loadServerConfig(dataRoot);
|
|
1250
|
+
const result = await requestLocalClientToken({ dataRoot, adminPort: config.adminPort, label: parsed.label ?? "Narrarium", scopes: parsed.scopes ?? ["read", "write", "run"] });
|
|
1251
|
+
output(`Client token (shown once): ${result.token}`);
|
|
1252
|
+
output(`Paste it in Narrarium \u2192 Settings \u2192 Personal server with the address http://127.0.0.1:${config.apiPort}. Never share it.`);
|
|
1253
|
+
return 0;
|
|
1254
|
+
}
|
|
1255
|
+
if (parsed.command === "update") {
|
|
1256
|
+
assertSupportedNode();
|
|
1257
|
+
const previous = await installer.activeRuntime().catch(() => void 0);
|
|
1258
|
+
const active = await installer.installVersion(parsed.requestedVersion ?? "latest");
|
|
1259
|
+
output(`Runtime ${previous?.version ?? "(none)"} \u2192 ${active.version}. A running server keeps its version until it restarts; under the supervisor, update from Narrarium or the admin panel instead.`);
|
|
1260
|
+
return 0;
|
|
1261
|
+
}
|
|
1262
|
+
return 2;
|
|
1263
|
+
} catch (error) {
|
|
1264
|
+
process.stderr.write(`${error instanceof Error ? error.message : "Unexpected error."}
|
|
1265
|
+
`);
|
|
1266
|
+
return 1;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
async function readSecretFromTerminal(prompt) {
|
|
1270
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY || !process.stdin.setRawMode) throw new Error("An interactive terminal is needed; otherwise use --code-file with a private (0600) file.");
|
|
1271
|
+
const chunks = [];
|
|
1272
|
+
process.stdout.write(prompt);
|
|
1273
|
+
process.stdin.setRawMode(true);
|
|
1274
|
+
process.stdin.resume();
|
|
1275
|
+
try {
|
|
1276
|
+
for await (const chunk of process.stdin) {
|
|
1277
|
+
for (const byte of Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))) {
|
|
1278
|
+
if (byte === 3) throw new Error("Cancelled.");
|
|
1279
|
+
if (byte === 10 || byte === 13) {
|
|
1280
|
+
process.stdout.write("\n");
|
|
1281
|
+
return Buffer.from(chunks).toString("utf8");
|
|
1282
|
+
}
|
|
1283
|
+
if (byte === 8 || byte === 127) {
|
|
1284
|
+
if (chunks.length) {
|
|
1285
|
+
chunks.pop();
|
|
1286
|
+
process.stdout.write("\b \b");
|
|
1287
|
+
}
|
|
1288
|
+
continue;
|
|
1289
|
+
}
|
|
1290
|
+
if (byte < 32) continue;
|
|
1291
|
+
chunks.push(byte);
|
|
1292
|
+
process.stdout.write("*");
|
|
1293
|
+
if (chunks.length > 200) throw new Error("The code is longer than 200 characters.");
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
throw new Error("The input ended before Enter.");
|
|
1297
|
+
} finally {
|
|
1298
|
+
process.stdin.setRawMode(false);
|
|
1299
|
+
process.stdin.pause();
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
// src/cli.ts
|
|
1304
|
+
process.exitCode = await main();
|
|
1305
|
+
//# sourceMappingURL=cli.mjs.map
|