forked from Fei-Away/Codex-Dream-Skin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstage-theme.mjs
More file actions
126 lines (113 loc) · 4.83 KB
/
Copy pathstage-theme.mjs
File metadata and controls
126 lines (113 loc) · 4.83 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
import fs from "node:fs/promises";
import { constants as fsConstants } from "node:fs";
import path from "node:path";
const [sourceDirArg, stageDirArg] = process.argv.slice(2);
if (!sourceDirArg || !stageDirArg) {
throw new Error("Usage: stage-theme.mjs <source-theme-dir> <stage-dir>");
}
const MAX_CONFIG_BYTES = 1024 * 1024;
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
const OPEN_FLAGS = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0);
const PORTABLE_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".webp"]);
const PORTABLE_RESERVED_IMAGE_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])\./iu;
function assertContained(rootPath, candidatePath, label) {
const relative = path.relative(rootPath, candidatePath);
if (
relative === ""
|| (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))
) return;
throw new Error(`${label} must stay inside its theme directory`);
}
function sameStat(left, right) {
return left.isFile() && right.isFile()
&& left.dev === right.dev
&& left.ino === right.ino
&& left.size === right.size
&& left.mtimeMs === right.mtimeMs
&& left.ctimeMs === right.ctimeMs;
}
async function readStableFile(filePath, label, maxBytes) {
let handle;
try {
handle = await fs.open(filePath, OPEN_FLAGS);
} catch (error) {
if (error.code === "ELOOP") throw new Error(`${label} must not be a symbolic link`);
throw error;
}
try {
const before = await handle.stat();
if (!before.isFile()) throw new Error(`${label} must be a regular file`);
if (before.size > maxBytes) throw new Error(`${label} is larger than ${maxBytes} bytes`);
const bytes = await handle.readFile();
const after = await handle.stat();
if (!sameStat(before, after)) {
throw new Error(`${label} changed while it was being staged`);
}
if (bytes.length > maxBytes) throw new Error(`${label} is larger than ${maxBytes} bytes`);
return { bytes, stat: after };
} finally {
await handle.close();
}
}
function decodeJson(bytes, label) {
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
if (text.includes("\0")) throw new Error(`${label} contains NUL characters`);
try {
return JSON.parse(text);
} catch {
throw new Error(`${label} is not valid JSON`);
}
}
async function writeExclusive(filePath, bytes) {
const temporary = `${filePath}.${process.pid}.tmp`;
try {
await fs.writeFile(temporary, bytes, { flag: "wx", mode: 0o600 });
await fs.rename(temporary, filePath);
} finally {
await fs.rm(temporary, { force: true }).catch(() => {});
}
}
async function main() {
const sourceRoot = await fs.realpath(sourceDirArg);
const sourceStat = await fs.stat(sourceRoot);
if (!sourceStat.isDirectory()) throw new Error("Theme source must be a directory");
const configPath = path.join(sourceRoot, "theme.json");
const config = await readStableFile(configPath, "Theme config", MAX_CONFIG_BYTES);
const theme = decodeJson(config.bytes, "Theme config");
if (!theme || typeof theme !== "object" || Array.isArray(theme)) {
throw new Error("Theme config root must be an object");
}
const schemaVersion = Object.hasOwn(theme, "schemaVersion") ? theme.schemaVersion : 1;
if (schemaVersion !== 1) {
throw new Error("Theme config has an unsupported schemaVersion field");
}
if (
typeof theme.image !== "string"
|| !theme.image
|| Array.from(theme.image).length > 240
|| /[<>:"/\\|?*\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(theme.image)
|| PORTABLE_RESERVED_IMAGE_NAME.test(theme.image)
|| !PORTABLE_IMAGE_EXTENSIONS.has(path.extname(theme.image).toLowerCase())
) {
throw new Error("Theme image must stay inside its theme directory");
}
if (theme.image === "theme.json") {
throw new Error("Theme image must not replace theme.json");
}
const imagePath = path.resolve(sourceRoot, theme.image);
assertContained(sourceRoot, imagePath, "Theme image");
const image = await readStableFile(imagePath, "Theme image", MAX_IMAGE_BYTES);
if (image.bytes.length < 1) throw new Error("Theme image is empty");
const stageRoot = await fs.realpath(stageDirArg);
const stageStat = await fs.stat(stageRoot);
if (!stageStat.isDirectory()) throw new Error("Theme stage must be a directory");
assertContained(stageRoot, path.join(stageRoot, "theme.json"), "Staged theme config");
assertContained(stageRoot, path.join(stageRoot, theme.image), "Staged theme image");
// Write both files from the already-open, stable descriptors. The caller
// publishes the image first and theme.json last, so the watcher only ever
// observes a complete pair; subsequent source edits cannot race the copy.
await writeExclusive(path.join(stageRoot, theme.image), image.bytes);
await writeExclusive(path.join(stageRoot, "theme.json"), config.bytes);
process.stdout.write(theme.image);
}
await main();