-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3392 lines (3008 loc) · 110 KB
/
Copy pathserver.js
File metadata and controls
3392 lines (3008 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from "express";
import path from "path";
import fs from "fs/promises";
import { existsSync, watch } from "fs";
import crypto from "crypto";
import nbt from "prismarine-nbt";
import { createRequire } from "module";
const app = express();
app.disable("x-powered-by");
app.use(express.json({ limit: "64kb" }));
const ROOT_DIR = path.resolve(process.cwd());
const PUBLIC_DIR = path.join(ROOT_DIR, "public");
const DEBUG_DIR = path.join(ROOT_DIR, ".dbg");
const UPLOADS_DIR = path.join(PUBLIC_DIR, "uploads");
const MODS_DIR = path.join(UPLOADS_DIR, "mods");
const GALLERY_DIR = path.join(UPLOADS_DIR, "gallery");
const DEVELOPER_COVERS_DIR = path.join(UPLOADS_DIR, "developers");
const USER_AVATARS_DIR = path.join(UPLOADS_DIR, "users");
const FEEDBACK_UPLOADS_DIR = path.join(UPLOADS_DIR, "feedback");
const WORKSHOP_UPLOADS_DIR = path.join(UPLOADS_DIR, "workshop");
const DEVELOPER_SHELL_HTML = path.join(PUBLIC_DIR, "developer-shell.html");
const CONFIG_DIR = path.join(PUBLIC_DIR, "config");
const ANNOUNCEMENTS_TXT = path.join(CONFIG_DIR, "announcements.txt");
const EXTERNAL_MODS_JSON = path.join(CONFIG_DIR, "external_mods.json");
const DEVELOPERS_JSON = path.join(CONFIG_DIR, "developers.json");
const CHANGELOG_JSON = path.join(CONFIG_DIR, "changelog.json");
const ASSETS_DIR = path.join(PUBLIC_DIR, "assets");
const DEFAULT_AVATAR_URL = "/assets/logo.png";
// 用户主页默认背景:清晰的站点大图(而不是被拉伸糊掉的 logo)。
const DEFAULT_USER_COVER = "/assets/hero-bottom.png";
const USER_INTRO_MAX_LENGTH = 80;
const WORKSHOP_TITLE_MAX_LENGTH = 60;
const WORKSHOP_DESCRIPTION_MAX_LENGTH = 1200;
const WORKSHOP_REVIEW_REASON_MAX_LENGTH = 200;
const WORKSHOP_RENDER_BLOCK_LIMIT = 25_000;
const WORKSHOP_FILE_KINDS = ["nbt"];
const MINECRAFT_ASSETS_VERSION = "1.21.8";
const WORKSHOP_CATEGORY_META = {
other: { key: "other", label: "其他" },
residence: { key: "residence", label: "住宅" },
commercial: { key: "commercial", label: "商业" },
industrial: { key: "industrial", label: "工业" },
public: { key: "public", label: "公共" },
};
const THREE_BUILD_DIR = path.join(ROOT_DIR, "node_modules", "three", "build");
const MINECRAFT_ASSETS_DIR = path.join(
ROOT_DIR,
"node_modules",
"minecraft-assets",
"minecraft-assets",
"data",
MINECRAFT_ASSETS_VERSION,
);
const AIR_BLOCK_NAMES = new Set([
"minecraft:air",
"minecraft:cave_air",
"minecraft:void_air",
"minecraft:structure_void",
]);
const PREVIEW_BRANCH_PATTERN = /(beta|preview|alpha|test|internal|sponsor|内测|尝鲜)/i;
const FIXED_BRANCHES = ["main", "neoforge", "sponsor"];
const SPONSOR_BRANCHES = new Set(["sponsor", "beta", "preview", "internal"]);
const BRANCH_DIRECTORY_ALIASES = {
main: ["forge", "", "main"],
neoforge: ["neoforge"],
sponsor: ["内测版(赞助)", "内测版", "sponsor", "preview", "beta", "internal"],
};
const ROLE_PRESETS = {
admin: {
key: "admin",
label: "管理员",
permissionLevel: 3,
},
service: {
key: "service",
label: "客服",
permissionLevel: 3,
},
sponsor: {
key: "sponsor",
label: "赞助者",
permissionLevel: 2,
},
guest: {
key: "guest",
label: "游客",
permissionLevel: 1,
},
};
const ROLE_BADGE_META = {
admin: { label: "管理员", className: "is-admin", accentA: "#22c55e", accentB: "#16a34a" },
service: { label: "客服", className: "is-service", accentA: "#facc15", accentB: "#eab308" },
sponsor: { label: "赞助者", className: "is-sponsor", accentA: "#fb923c", accentB: "#ea580c" },
guest: { label: "游客", className: "is-guest", accentA: "#9ca3af", accentB: "#6b7280" },
};
const ONE_MINUTE_MS = 60_000;
const APP_NAME = "nsimu-like-site";
const ADMIN_TOKEN = process.env.ADMIN_TOKEN ?? "";
const ADMIN_DEFAULT_PASSWORD = process.env.ADMIN_DEFAULT_PASSWORD ?? "";
const SESSION_SECRET = process.env.SESSION_SECRET ?? "";
const COOKIE_SECURE =
process.env.COOKIE_SECURE === "1" ||
process.env.COOKIE_SECURE === "true" ||
process.env.COOKIE_SECURE === "yes";
const FORCE_PORT =
process.env.FORCE_PORT === "1" ||
process.env.FORCE_PORT === "true" ||
process.env.FORCE_PORT === "yes";
const require = createRequire(import.meta.url);
const minecraftAssets = require("minecraft-assets")("1.21.8");
const workshopTextureCache = new Map();
function getDebugLogFilePath(sessionId) {
const safeSessionId = typeof sessionId === "string" ? sessionId.trim() : "";
if (!/^[a-z0-9-]{2,80}$/.test(safeSessionId)) return null;
return path.join(DEBUG_DIR, `trae-debug-log-${safeSessionId}.ndjson`);
}
async function appendDebugEvent(event) {
const sessionId = typeof event?.sessionId === "string" ? event.sessionId : "";
const filePath = getDebugLogFilePath(sessionId);
if (!filePath) return false;
const payload = {
sessionId,
runId: typeof event?.runId === "string" ? event.runId : "pre-fix",
hypothesisId: typeof event?.hypothesisId === "string" ? event.hypothesisId : "",
ts: Number.isFinite(Number(event?.ts)) ? Number(event.ts) : Date.now(),
location: typeof event?.location === "string" ? event.location : "",
msg: typeof event?.msg === "string" ? event.msg : "[DEBUG] event",
href: typeof event?.href === "string" ? event.href : "",
name: typeof event?.name === "string" ? event.name : "",
data: event?.data ?? null,
};
await fs.mkdir(DEBUG_DIR, { recursive: true });
await fs.appendFile(filePath, `${JSON.stringify(payload)}\n`, "utf-8");
return true;
}
function isLoopbackRequest(req) {
const ip = req.socket?.remoteAddress ?? "";
return ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1";
}
function safeJoin(baseDir, ...parts) {
const fullPath = path.resolve(baseDir, ...parts);
const rel = path.relative(baseDir, fullPath);
if (rel.startsWith("..") || path.isAbsolute(rel)) {
return null;
}
return fullPath;
}
function formatVersionGuess(fileName) {
const base = fileName.replace(/\.(zip|jar)$/i, "");
const match = base.match(/(\d+\.\d+\.\d+[^-_ ]*)/);
return match?.[1] ?? base;
}
function randomId() {
return `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
}
function randomTokenBase64Url(byteCount) {
return crypto
.randomBytes(byteCount)
.toString("base64")
.replaceAll("+", "-")
.replaceAll("/", "_")
.replaceAll("=", "");
}
function parseCookies(req) {
const header = req.headers.cookie ?? "";
const out = {};
for (const part of header.split(";")) {
const trimmed = part.trim();
if (!trimmed) continue;
const eq = trimmed.indexOf("=");
if (eq <= 0) continue;
const k = trimmed.slice(0, eq).trim();
const v = trimmed.slice(eq + 1).trim();
out[k] = decodeURIComponent(v);
}
return out;
}
function getCookie(req, name) {
const cookies = parseCookies(req);
return cookies[name] ?? "";
}
function setCookie(res, name, value, options) {
const attrs = [];
attrs.push(`${name}=${encodeURIComponent(value)}`);
if (options?.maxAgeSec != null) attrs.push(`Max-Age=${options.maxAgeSec}`);
if (options?.path) attrs.push(`Path=${options.path}`);
if (options?.httpOnly) attrs.push("HttpOnly");
if (options?.sameSite) attrs.push(`SameSite=${options.sameSite}`);
if (options?.secure) attrs.push("Secure");
res.append("Set-Cookie", attrs.join("; "));
}
function hashSessionToken(token) {
const secret = SESSION_SECRET || "dev_secret";
return crypto.createHmac("sha256", secret).update(token).digest("base64url");
}
async function scryptHash(password, saltBase64) {
const salt = Buffer.from(saltBase64, "base64");
const key = await new Promise((resolve, reject) => {
crypto.scrypt(password, salt, 64, (err, derivedKey) => {
if (err) reject(err);
else resolve(derivedKey);
});
});
return Buffer.from(key).toString("base64");
}
async function makePasswordRecord(password) {
const salt = crypto.randomBytes(16).toString("base64");
const hash = await scryptHash(password, salt);
return { salt, hash };
}
async function verifyPassword(password, record) {
if (!record || typeof record.salt !== "string" || typeof record.hash !== "string") {
return false;
}
const calc = await scryptHash(password, record.salt);
const a = Buffer.from(record.hash, "base64");
const b = Buffer.from(calc, "base64");
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
}
class ExpiringCache {
#store = new Map();
get(key) {
const entry = this.#store.get(key);
if (!entry) return null;
if (entry.expiresAtMs <= Date.now()) {
this.#store.delete(key);
return null;
}
return entry.value;
}
set(key, value, ttlMs) {
this.#store.set(key, { value, expiresAtMs: Date.now() + ttlMs });
}
delete(key) {
this.#store.delete(key);
}
deleteByPrefix(prefix) {
for (const key of this.#store.keys()) {
if (key.startsWith(prefix)) this.#store.delete(key);
}
}
}
const cache = new ExpiringCache();
function setupDirWatch(dirPath, cacheKeysToInvalidate) {
try {
if (!existsSync(dirPath)) return;
watch(
dirPath,
{ recursive: true },
() => {
for (const key of cacheKeysToInvalidate) {
if (key.endsWith("*")) {
cache.deleteByPrefix(key.slice(0, -1));
} else {
cache.delete(key);
}
}
},
);
} catch {
}
}
setupDirWatch(MODS_DIR, ["branches", "mods:*"]);
setupDirWatch(GALLERY_DIR, ["gallery:categories"]);
setupDirWatch(CONFIG_DIR, ["announcements", "external_mods", "developers", "changelog"]);
async function fileExists(filePath) {
try {
const st = await fs.stat(filePath);
return st.isFile();
} catch {
return false;
}
}
async function bootstrapAssets() {
const logoSource =
process.env.LOGO_SOURCE ??
"C:\\Users\\nqwer\\Desktop\\千恋万花穗织还原\\素材\\MC_XiaoLiangdd_vzge face.png";
const devSources = [
{
src:
process.env.DEV_XIAOLIANG_SOURCE ??
"C:\\Users\\nqwer\\Desktop\\千恋万花穗织还原\\素材\\MC_XiaoLiangdd_vzge face.png",
dest: path.join(ASSETS_DIR, "devs", "xiaoliang.png"),
},
{
src:
process.env.DEV_KAFEI_SOURCE ??
"C:\\Users\\nqwer\\Desktop\\千恋万花穗织还原\\素材\\mckafei_CN_vzge face.png",
dest: path.join(ASSETS_DIR, "devs", "kafei.png"),
},
{
src:
process.env.DEV_MENGLAN_SOURCE ??
"C:\\Users\\nqwer\\Desktop\\千恋万花穗织还原\\素材\\menglannnn_vzge face.png",
dest: path.join(ASSETS_DIR, "devs", "menglannnn.png"),
},
];
try {
await fs.mkdir(path.join(ASSETS_DIR, "devs"), { recursive: true });
await fs.mkdir(ASSETS_DIR, { recursive: true });
const logoDest = path.join(ASSETS_DIR, "logo.png");
if (!(await fileExists(logoDest)) && (await fileExists(logoSource))) {
await fs.copyFile(logoSource, logoDest);
}
for (const item of devSources) {
if (!(await fileExists(item.dest)) && (await fileExists(item.src))) {
await fs.copyFile(item.src, item.dest);
}
}
} catch {
}
}
async function listBranches() {
const cached = cache.get("branches");
if (cached) return cached;
const branches = [...FIXED_BRANCHES];
cache.set("branches", branches, ONE_MINUTE_MS);
return branches;
}
function parseFileNameFromUrl(url) {
try {
const u = new URL(url);
const fileName = u.searchParams.get("fileName") || "";
if (fileName) return fileName;
const pathPart = u.pathname.split("/").filter(Boolean).pop() || "";
return decodeURIComponent(pathPart);
} catch {
return "";
}
}
function sanitizeExternalModKey(value) {
const raw = typeof value === "string" ? value.trim() : "";
if (!raw || raw.length > 80) return "";
if (/[\\/\x00-\x1f]/.test(raw)) return "";
return raw;
}
function sanitizeExternalModTitle(value, fallback) {
const raw = typeof value === "string" ? value.trim() : "";
const safeFallback = typeof fallback === "string" && fallback.trim() ? fallback.trim() : "未命名版本";
return (raw || safeFallback).slice(0, 80);
}
function sanitizeExternalModDescription(value) {
return typeof value === "string" ? value.trim().slice(0, 120) : "";
}
function normalizeExternalModTimestamp(value) {
const raw = typeof value === "string" ? value.trim() : "";
const ms = raw ? Date.parse(raw) : NaN;
return Number.isFinite(ms) ? new Date(ms).toISOString() : new Date().toISOString();
}
function normalizeExternalLink(link, index) {
if (!link || typeof link !== "object") return null;
const url = typeof link.url === "string" ? link.url.trim() : "";
if (!url) return null;
try {
const parsed = new URL(url);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
} catch {
return null;
}
const rawLabel = typeof link.label === "string" ? link.label.trim() : "";
const label = rawLabel || `站外下载 ${index + 1}`;
return { label: label.slice(0, 40), url };
}
function parseExternalConfigEntry(entry) {
const branch = normalizeBranchInput(
typeof entry?.branch === "string" && entry.branch.trim() ? entry.branch.trim() : "main",
);
const linksRaw = Array.isArray(entry?.links)
? entry.links
: [
{
label: typeof entry?.label === "string" ? entry.label : "",
url:
(typeof entry?.externalUrl === "string" ? entry.externalUrl : "") ||
(typeof entry?.url === "string" ? entry.url : ""),
},
];
const links = linksRaw
.map((link, index) => normalizeExternalLink(link, index))
.filter(Boolean);
const fileName = sanitizeExternalModKey(
(typeof entry?.fileName === "string" ? entry.fileName.trim() : "") ||
(typeof entry?.id === "string" ? entry.id.trim() : "") ||
(links[0]?.url ? parseFileNameFromUrl(links[0].url) : "") ||
(typeof entry?.title === "string" ? entry.title.trim() : ""),
);
if (!fileName) return null;
if (links.length === 0) return null;
const title = sanitizeExternalModTitle(entry?.title, formatVersionGuess(fileName));
const description = sanitizeExternalModDescription(entry?.description);
const updatedAt = normalizeExternalModTimestamp(entry?.updatedAt);
return { branch, fileName, title, description, links, updatedAt };
}
async function readExternalModsConfig() {
const cached = cache.get("external_mods");
if (cached) return cached;
const list = await readExternalModsConfigUncached();
cache.set("external_mods", list, 10_000);
return list;
}
async function readExternalModsConfigUncached() {
let data = null;
try {
const raw = await fs.readFile(EXTERNAL_MODS_JSON, "utf-8");
data = JSON.parse(raw);
} catch {
data = null;
}
const items = Array.isArray(data?.mods) ? data.mods : [];
return items.map(parseExternalConfigEntry).filter(Boolean);
}
let externalModsWriteChain = Promise.resolve();
function enqueueExternalModsWrite(task) {
externalModsWriteChain = externalModsWriteChain.then(() => task()).catch(() => {});
return externalModsWriteChain;
}
async function writeExternalModsConfig(items) {
await fs.mkdir(CONFIG_DIR, { recursive: true });
await fs.writeFile(
EXTERNAL_MODS_JSON,
JSON.stringify({ version: 2, mods: items }, null, 2),
"utf-8",
);
cache.delete("external_mods");
cache.delete("branches");
cache.deleteByPrefix("mods:");
}
function normalizeBranchInput(branch) {
const raw = typeof branch === "string" ? branch.trim().toLowerCase() : "";
if (!raw || raw === "main" || raw === "forge") return "main";
if (raw === "neoforge") return "neoforge";
if (SPONSOR_BRANCHES.has(raw) || PREVIEW_BRANCH_PATTERN.test(raw)) return "sponsor";
return raw;
}
function getBranchDirectoryCandidates(branch) {
const normalizedBranch = normalizeBranchInput(branch);
const aliases = BRANCH_DIRECTORY_ALIASES[normalizedBranch] ?? [normalizedBranch];
const seen = new Set();
const dirs = [];
for (const alias of aliases) {
const dirPath = alias ? safeJoin(MODS_DIR, alias) : MODS_DIR;
if (!dirPath || seen.has(dirPath)) continue;
seen.add(dirPath);
dirs.push(dirPath);
}
return dirs;
}
function getPrimaryBranchDirectory(branch) {
return getBranchDirectoryCandidates(branch)[0] ?? null;
}
async function resolveBranchFilePath(branch, fileName) {
for (const dirPath of getBranchDirectoryCandidates(branch)) {
const filePath = safeJoin(dirPath, fileName);
if (!filePath) continue;
try {
const st = await fs.stat(filePath);
if (st.isFile()) return filePath;
} catch {
}
}
return null;
}
function isValidBranchName(branch) {
return /^[a-zA-Z0-9._-]+$/.test(branch);
}
function isManagedBranch(branch) {
return FIXED_BRANCHES.includes(normalizeBranchInput(branch));
}
function isValidModFileName(fileName) {
return (
typeof fileName === "string" &&
fileName.length > 0 &&
fileName.length <= 200 &&
!fileName.includes("/") &&
!fileName.includes("\\") &&
/\.(zip|jar)$/i.test(fileName)
);
}
function isValidExternalModKey(value) {
return Boolean(sanitizeExternalModKey(value));
}
function isValidImageFileName(fileName) {
return (
typeof fileName === "string" &&
fileName.length > 0 &&
fileName.length <= 120 &&
!fileName.includes("/") &&
!fileName.includes("\\") &&
/\.(png|jpe?g|webp|gif)$/i.test(fileName)
);
}
function isValidFeedbackDraftId(draftId) {
return typeof draftId === "string" && /^[a-zA-Z0-9_-]{8,80}$/.test(draftId);
}
function isValidFeedbackFileName(fileName) {
return (
typeof fileName === "string" &&
fileName.length > 0 &&
fileName.length <= 180 &&
!/[<>:"/\\|?*\x00-\x1f]/.test(fileName)
);
}
function normalizeFeedbackType(type) {
return type === "bug" ? "bug" : "suggestion";
}
function normalizeIsoTimestamp(value, fallback = new Date()) {
const raw = typeof value === "string" ? value.trim() : "";
const ms = raw ? Date.parse(raw) : NaN;
if (Number.isFinite(ms)) return new Date(ms).toISOString();
const safeFallback = fallback instanceof Date && !Number.isNaN(fallback.getTime())
? fallback
: new Date();
return safeFallback.toISOString();
}
function normalizeWorkshopCategory(value) {
const raw = typeof value === "string" ? value.trim().toLowerCase() : "";
if (!raw) return "";
if (raw === "other" || raw === "其他") return "other";
if (raw === "residence" || raw === "housing" || raw === "住宅") return "residence";
if (raw === "commercial" || raw === "商业") return "commercial";
if (raw === "industrial" || raw === "工业") return "industrial";
if (raw === "public" || raw === "公共") return "public";
return "";
}
function getWorkshopCategoryMeta(value) {
const key = normalizeWorkshopCategory(value);
return WORKSHOP_CATEGORY_META[key] ?? null;
}
function listWorkshopCategories() {
return Object.values(WORKSHOP_CATEGORY_META).map((item) => ({
key: item.key,
label: item.label,
}));
}
function getWorkshopRequiredKinds(category) {
const meta = getWorkshopCategoryMeta(category);
if (!meta) return [];
return ["nbt"];
}
function isValidWorkshopFileName(kind, fileName) {
if (!isValidFeedbackFileName(fileName)) return false;
if (kind === "nbt") return /\.nbt$/i.test(fileName);
return false;
}
function sanitizeWorkshopText(value, maxLength) {
return typeof value === "string" ? value.trim().slice(0, maxLength) : "";
}
function sanitizeWorkshopAttachment(item, kind, draftId) {
if (!item || typeof item !== "object" || !isValidFeedbackDraftId(draftId)) return null;
const name = typeof item.name === "string" ? item.name.trim() : "";
const url = typeof item.url === "string" ? item.url.trim() : "";
const size = Number(item.size ?? 0);
const expectedPrefix = `/uploads/workshop/${encodeURIComponent(draftId)}/${kind}/`;
if (!isValidWorkshopFileName(kind, name) || !url.startsWith(expectedPrefix)) return null;
return {
kind,
name,
url,
size: Number.isFinite(size) && size > 0 ? size : 0,
};
}
function sanitizeWorkshopFiles(files, category, draftId) {
if (!files || typeof files !== "object") return null;
const result = {};
for (const kind of WORKSHOP_FILE_KINDS) {
const attachment = sanitizeWorkshopAttachment(files[kind], kind, draftId);
if (attachment) result[kind] = attachment;
}
const requiredKinds = getWorkshopRequiredKinds(category);
if (requiredKinds.length === 0 || requiredKinds.some((kind) => !result[kind])) return null;
return result;
}
function sanitizeWorkshopExternalLinks(items) {
if (!Array.isArray(items)) return [];
return items
.map((item, index) => normalizeExternalLink(item, index))
.filter(Boolean)
.slice(0, 8);
}
function normalizeWorkshopStatus(value) {
if (value === "approved" || value === "rejected") return value;
return "pending";
}
function sanitizeWorkshopEntry(entry) {
if (!entry || typeof entry !== "object") return null;
const categoryKey = normalizeWorkshopCategory(entry.category) || "other";
const categoryMeta = getWorkshopCategoryMeta(categoryKey);
if (!categoryMeta) return null;
const draftId = typeof entry.draftId === "string" ? entry.draftId.trim() : "";
const title = sanitizeWorkshopText(entry.title, WORKSHOP_TITLE_MAX_LENGTH);
const description = sanitizeWorkshopText(entry.description, WORKSHOP_DESCRIPTION_MAX_LENGTH);
const externalLinks = sanitizeWorkshopExternalLinks(entry.externalLinks);
const authorUsername = normalizeUsername(entry.authorUsername);
const authorDisplayName = sanitizeWorkshopText(
entry.authorDisplayName || entry.authorUsername,
40,
);
if (!draftId || !isValidFeedbackDraftId(draftId) || !title || !description || !authorUsername) {
return null;
}
const files = sanitizeWorkshopFiles(entry.files, categoryKey, draftId);
if (!files) return null;
const createdAt = normalizeIsoTimestamp(entry.createdAt);
const updatedAt = normalizeIsoTimestamp(entry.updatedAt, new Date(createdAt));
const status = normalizeWorkshopStatus(entry.status);
const reviewedAt = status === "pending" ? null : normalizeIsoTimestamp(entry.reviewedAt, new Date(updatedAt));
const publishedAt = status === "approved"
? normalizeIsoTimestamp(entry.publishedAt || reviewedAt || updatedAt, new Date(updatedAt))
: null;
return {
id: typeof entry.id === "string" && entry.id.trim() ? entry.id.trim() : randomId(),
draftId,
title,
category: categoryMeta.key,
description,
files,
externalLinks,
authorUsername,
authorDisplayName: authorDisplayName || authorUsername,
status,
reviewReason:
status === "rejected"
? sanitizeWorkshopText(entry.reviewReason, WORKSHOP_REVIEW_REASON_MAX_LENGTH)
: "",
reviewedBy: status === "pending" ? "" : sanitizeWorkshopText(entry.reviewedBy, 40),
createdAt,
updatedAt,
reviewedAt,
publishedAt,
};
}
function fileUrlToLocalPath(fileUrl) {
const raw = typeof fileUrl === "string" ? fileUrl.trim() : "";
if (!raw.startsWith("/uploads/workshop/")) return null;
const relative = raw
.replace(/^\/+/, "")
.split("/")
.map((part) => decodeURIComponent(part))
.join(path.sep);
return safeJoin(PUBLIC_DIR, relative);
}
function sanitizeNbtPreviewValue(value, depth = 0) {
if (depth > 32) return "[Depth limit]";
if (typeof value === "bigint") return `${value}n`;
if (Array.isArray(value)) {
return value.slice(0, 512).map((item) => sanitizeNbtPreviewValue(item, depth + 1));
}
if (value && typeof value === "object") {
const output = {};
let count = 0;
for (const [key, nested] of Object.entries(value)) {
output[key] = sanitizeNbtPreviewValue(nested, depth + 1);
count += 1;
if (count >= 512) break;
}
return output;
}
return value;
}
function normalizeMinecraftAssetKey(value) {
const raw = typeof value === "string" ? value.trim() : "";
if (!raw) return "";
return raw
.replace(/^minecraft:/, "")
.replace(/^blocks?\//, "")
.replace(/^textures\/blocks?\//, "")
.replace(/\.png$/i, "");
}
function normalizeMinecraftModelKey(value) {
const raw = typeof value === "string" ? value.trim() : "";
if (!raw) return "";
return raw
.replace(/^minecraft:/, "")
.replace(/^models\//, "")
.replace(/^blocks?\//, "")
.replace(/\.json$/i, "");
}
function resolveMinecraftModelTextures(modelKey, seen = new Set()) {
const normalizedKey = normalizeMinecraftModelKey(modelKey);
if (!normalizedKey || seen.has(normalizedKey)) return {};
seen.add(normalizedKey);
const model = minecraftAssets?.blocksModels?.[normalizedKey];
if (!model || typeof model !== "object") return {};
const parentTextures = resolveMinecraftModelTextures(model.parent, seen);
return {
...parentTextures,
...(model.textures && typeof model.textures === "object" ? model.textures : {}),
};
}
function resolveMinecraftTextureRef(textureMap, key, depth = 0) {
if (!textureMap || typeof textureMap !== "object" || !key || depth > 12) return "";
const rawValue = textureMap[key];
if (typeof rawValue !== "string" || !rawValue.trim()) return "";
const value = rawValue.trim();
if (value.startsWith("#")) {
return resolveMinecraftTextureRef(textureMap, value.slice(1), depth + 1);
}
return normalizeMinecraftAssetKey(value);
}
function getTextureContentByKey(textureKey) {
const normalizedKey = normalizeMinecraftAssetKey(textureKey);
const pngPath = safeJoin(MINECRAFT_ASSETS_DIR, "blocks", `${normalizedKey}.png`);
if (pngPath && existsSync(pngPath)) {
const urlPath = normalizedKey
.split("/")
.map((part) => encodeURIComponent(part))
.join("/");
return `/vendor/minecraft-assets/${MINECRAFT_ASSETS_VERSION}/blocks/${urlPath}.png`;
}
const entry = minecraftAssets?.textureContent?.[normalizedKey];
return typeof entry?.texture === "string" ? entry.texture : "";
}
function buildWorkshopTextureSet(blockName) {
const normalizedBlockName = normalizeMinecraftAssetKey(blockName);
if (!normalizedBlockName) return null;
const cached = workshopTextureCache.get(normalizedBlockName);
if (cached) return cached;
const blockEntry = minecraftAssets?.blocks?.[normalizedBlockName] ?? null;
const textureMap = resolveMinecraftModelTextures(blockEntry?.model || normalizedBlockName);
const directTexture = normalizeMinecraftAssetKey(blockEntry?.texture);
const pick = (...candidates) => {
for (const candidate of candidates) {
const fromMap = resolveMinecraftTextureRef(textureMap, candidate);
if (fromMap) return fromMap;
}
return directTexture;
};
const sideKey = pick("side", "north", "south", "west", "east", "all", "texture", "particle", "end", "top", "bottom");
const topKey = pick("top", "up", "end", "all", "texture", "side", "particle", "bottom");
const bottomKey = pick("bottom", "down", "end", "all", "texture", "side", "particle", "top");
const frontKey = pick("front", "north", "side", "all", "texture", "particle", "top");
const textureSet = {
top: getTextureContentByKey(topKey || sideKey || directTexture),
bottom: getTextureContentByKey(bottomKey || sideKey || directTexture),
side: getTextureContentByKey(sideKey || directTexture),
front: getTextureContentByKey(frontKey || sideKey || directTexture),
back: getTextureContentByKey(sideKey || directTexture),
left: getTextureContentByKey(sideKey || directTexture),
right: getTextureContentByKey(sideKey || directTexture),
transparent: /(glass|ice|leaves|slime|honey|water|barrier|chain|lantern|door|trapdoor|pane|vine|sculk_sensor)/i.test(normalizedBlockName),
};
workshopTextureCache.set(normalizedBlockName, textureSet);
return textureSet;
}
function normalizeStructureNumberList(value) {
if (!Array.isArray(value) || value.length < 3) return null;
const nums = value.slice(0, 3).map((item) => Number(item));
if (nums.some((item) => !Number.isFinite(item))) return null;
return nums.map((item) => Math.max(0, Math.trunc(item)));
}
function readStructurePaletteEntries(value) {
if (Array.isArray(value?.palette)) return value.palette;
if (Array.isArray(value?.palettes?.[0])) return value.palettes[0];
return [];
}
function extractWorkshopRenderModel(preview) {
if (!preview || typeof preview !== "object") return null;
const size = normalizeStructureNumberList(preview.size);
const blocksRaw = Array.isArray(preview.blocks) ? preview.blocks : [];
const paletteRaw = readStructurePaletteEntries(preview);
if (!size || blocksRaw.length === 0 || paletteRaw.length === 0) return null;
const palette = paletteRaw.map((entry, index) => {
const name =
typeof entry?.Name === "string"
? entry.Name.trim()
: typeof entry?.name === "string"
? entry.name.trim()
: "";
return {
index,
name: name || `palette:${index}`,
textures: buildWorkshopTextureSet(name),
};
});
let solidBlockCount = 0;
const blocks = [];
for (const rawBlock of blocksRaw) {
const stateIndex = Math.trunc(Number(rawBlock?.state));
const pos = normalizeStructureNumberList(rawBlock?.pos);
if (!Number.isFinite(stateIndex) || !pos) continue;
const paletteEntry = palette[stateIndex];
if (!paletteEntry || AIR_BLOCK_NAMES.has(paletteEntry.name)) continue;
solidBlockCount += 1;
if (blocks.length >= WORKSHOP_RENDER_BLOCK_LIMIT) continue;
blocks.push({
x: pos[0],
y: pos[1],
z: pos[2],
state: stateIndex,
name: paletteEntry.name,
});
}
return {
size,
palette,
paletteSize: palette.length,
totalBlockCount: blocksRaw.length,
solidBlockCount,
renderedBlockCount: blocks.length,
omittedBlockCount: Math.max(0, solidBlockCount - blocks.length),
entityCount: Array.isArray(preview.entities) ? preview.entities.length : 0,
blocks,
};
}
function sanitizeFeedbackAttachments(items, kind, draftId) {
if (!Array.isArray(items) || !isValidFeedbackDraftId(draftId)) return [];
const subDir = kind === "image" ? "images" : "files";
const expectedPrefix = `/uploads/feedback/${encodeURIComponent(draftId)}/${subDir}/`;
const maxCount = kind === "image" ? 8 : 8;
return items
.map((item) => {
const name = typeof item?.name === "string" ? item.name.trim() : "";
const url = typeof item?.url === "string" ? item.url.trim() : "";
const size = Number(item?.size ?? 0);
const validName = kind === "image" ? isValidImageFileName(name) : isValidFeedbackFileName(name);
if (!validName || !url.startsWith(expectedPrefix)) return null;
return {
kind,
name,
url,
size: Number.isFinite(size) && size > 0 ? size : 0,
};
})
.filter(Boolean)
.slice(0, maxCount);
}
async function listMods(branch) {
const normalizedBranch = normalizeBranchInput(branch);
const key = `mods:${normalizedBranch}`;
const cached = cache.get(key);
if (cached) return cached;
if (!isManagedBranch(normalizedBranch)) return [];
let mods = [];
try {
const ext = await readExternalModsConfig();
mods = ext
.filter((item) => item.branch === normalizedBranch)
.map((item) => ({
branch: normalizedBranch,
fileName: item.fileName,
sizeBytes: null,
mtimeMs: Date.parse(item.updatedAt || "") || 0,
versionGuess: item.title || formatVersionGuess(item.fileName),
externalOnly: true,
externalLinks: item.links,
description: item.description || "",
}));
} catch {
mods = [];
}
mods.sort((a, b) => {
const am = Number.isFinite(a?.mtimeMs) ? a.mtimeMs : 0;
const bm = Number.isFinite(b?.mtimeMs) ? b.mtimeMs : 0;
return bm - am;
});
cache.set(key, mods, ONE_MINUTE_MS);
return mods;
}
async function readAnnouncements() {
const cached = cache.get("announcements");
if (cached) return cached;
let announcements = [];
try {
const raw = await fs.readFile(ANNOUNCEMENTS_TXT, "utf-8");
announcements = raw
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
} catch {
announcements = [];
}
cache.set("announcements", announcements, 10_000);
return announcements;
}
function sanitizeChangelogDate(value) {
const raw = typeof value === "string" ? value.trim() : "";
if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) return raw;
const date = raw ? new Date(raw) : new Date();
const safe = Number.isNaN(date.getTime()) ? new Date() : date;
const y = safe.getFullYear();
const m = String(safe.getMonth() + 1).padStart(2, "0");
const d = String(safe.getDate()).padStart(2, "0");
return `${y}-${m}-${d}`;
}
function sanitizeChangelogEntry(entry) {
if (!entry || typeof entry !== "object") return null;
const title = typeof entry.title === "string" ? entry.title.trim().slice(0, 60) : "";
const summary = typeof entry.summary === "string" ? entry.summary.trim().slice(0, 240) : "";
if (!title || !summary) return null;
const version = typeof entry.version === "string" ? entry.version.trim().slice(0, 40) : "";
const createdAtRaw = typeof entry.createdAt === "string" ? entry.createdAt.trim() : "";
const createdAt = !createdAtRaw || Number.isNaN(new Date(createdAtRaw).getTime())
? new Date().toISOString()
: new Date(createdAtRaw).toISOString();
return {
id: typeof entry.id === "string" && entry.id.trim() ? entry.id.trim() : randomId(),
version,