@agy-daddy/plugin-pet 0.0.0-stage → 1.1.1
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/LICENSE +21 -0
- package/README.md +10 -2
- package/agy-plugin.json +57 -0
- package/locales/en.json +10 -0
- package/locales/zh-CN.json +10 -0
- package/package.json +28 -4
- package/settings.schema.json +136 -0
- package/src/node.js +620 -0
- package/src/renderer.js +231 -0
- package/src/session-watch-aggregator.js +271 -0
- package/src/shared/pet-canvas-stage.d.ts +36 -0
- package/src/shared/pet-canvas-stage.js +218 -0
- package/src/shared/pet-rig-evaluator.js +172 -0
- package/src/shared/themes.d.ts +20 -0
- package/src/shared/themes.js +456 -0
- package/src/theme-pack-sandbox.js +501 -0
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const zlib = require('node:zlib');
|
|
6
|
+
|
|
7
|
+
const MAX_ARCHIVE_BYTES = 5 * 1024 * 1024; // 5 MB
|
|
8
|
+
const MAX_UNPACKED_BYTES = 12 * 1024 * 1024; // 12 MB
|
|
9
|
+
const MAX_ENTRY_COUNT = 32;
|
|
10
|
+
const MAX_CUSTOM_THEMES = 20;
|
|
11
|
+
const MAX_THEME_JSON_BYTES = 128 * 1024;
|
|
12
|
+
const MAX_RASTER_BYTES = 1024 * 1024;
|
|
13
|
+
const MAX_RASTER_DIM = 512;
|
|
14
|
+
|
|
15
|
+
const FORBIDDEN_EXTENSIONS = new Set([
|
|
16
|
+
'.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.jsx', '.tsx',
|
|
17
|
+
'.wasm', '.html', '.htm', '.xhtml', '.sh', '.bash', '.zsh',
|
|
18
|
+
'.ps1', '.psm1', '.bat', '.cmd', '.vbs', '.exe', '.dll', '.dylib', '.so'
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
const ALLOWED_EXTENSIONS = new Set(['.json', '.png', '.webp', '.gif', '.svg']);
|
|
22
|
+
|
|
23
|
+
function loadTarParser() {
|
|
24
|
+
try {
|
|
25
|
+
const hostTarPath = path.resolve(__dirname, '..', '..', 'agy-daddy-host', 'src', 'core', 'tar.js');
|
|
26
|
+
if (fs.existsSync(hostTarPath)) {
|
|
27
|
+
return require(hostTarPath).parseTarBuffer;
|
|
28
|
+
}
|
|
29
|
+
} catch {}
|
|
30
|
+
return function parseTarBufferFallback(buf) {
|
|
31
|
+
const entries = [];
|
|
32
|
+
let offset = 0;
|
|
33
|
+
while (offset + 512 <= buf.length) {
|
|
34
|
+
const header = buf.subarray(offset, offset + 512);
|
|
35
|
+
let isZero = true;
|
|
36
|
+
for (let i = 0; i < 512; i++) {
|
|
37
|
+
if (header[i] !== 0) { isZero = false; break; }
|
|
38
|
+
}
|
|
39
|
+
if (isZero) break;
|
|
40
|
+
const nameRaw = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
|
|
41
|
+
const prefixRaw = header.subarray(345, 500).toString('utf8').replace(/\0.*$/, '');
|
|
42
|
+
const sizeOctal = header.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim();
|
|
43
|
+
const typeFlag = String.fromCharCode(header[156] || 48);
|
|
44
|
+
const size = sizeOctal ? parseInt(sizeOctal, 8) : 0;
|
|
45
|
+
const fullName = prefixRaw ? `${prefixRaw}/${nameRaw}` : nameRaw;
|
|
46
|
+
offset += 512;
|
|
47
|
+
const data = buf.subarray(offset, offset + size);
|
|
48
|
+
offset += Math.ceil(size / 512) * 512;
|
|
49
|
+
if (typeFlag === 'g' || typeFlag === 'x') continue;
|
|
50
|
+
entries.push({ name: fullName, type: typeFlag, data });
|
|
51
|
+
}
|
|
52
|
+
return entries;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const parseTarBuffer = loadTarParser();
|
|
57
|
+
|
|
58
|
+
function inspectRasterHeader(buf) {
|
|
59
|
+
if (!Buffer.isBuffer(buf) || buf.length < 10) return null;
|
|
60
|
+
if (
|
|
61
|
+
buf.length >= 24 &&
|
|
62
|
+
buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
|
|
63
|
+
buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a
|
|
64
|
+
) {
|
|
65
|
+
return { format: 'png', width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
66
|
+
}
|
|
67
|
+
if (
|
|
68
|
+
buf.length >= 10 &&
|
|
69
|
+
buf.subarray(0, 4).toString('ascii') === 'GIF8' &&
|
|
70
|
+
(buf[4] === 0x37 || buf[4] === 0x39) &&
|
|
71
|
+
buf[5] === 0x61
|
|
72
|
+
) {
|
|
73
|
+
return { format: 'gif', width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
|
|
74
|
+
}
|
|
75
|
+
if (
|
|
76
|
+
buf.length >= 30 &&
|
|
77
|
+
buf.subarray(0, 4).toString('ascii') === 'RIFF' &&
|
|
78
|
+
buf.subarray(8, 12).toString('ascii') === 'WEBP'
|
|
79
|
+
) {
|
|
80
|
+
const chunk = buf.subarray(12, 16).toString('ascii');
|
|
81
|
+
if (chunk === 'VP8X' && buf.length >= 30) {
|
|
82
|
+
return {
|
|
83
|
+
format: 'webp',
|
|
84
|
+
width: 1 + (buf[24] | (buf[25] << 8) | (buf[26] << 16)),
|
|
85
|
+
height: 1 + (buf[27] | (buf[28] << 8) | (buf[29] << 16))
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
if (chunk === 'VP8 ' && buf.length >= 30 && buf[23] === 0x9d && buf[24] === 0x01 && buf[25] === 0x2a) {
|
|
89
|
+
return {
|
|
90
|
+
format: 'webp',
|
|
91
|
+
width: buf.readUInt16LE(26) & 0x3fff,
|
|
92
|
+
height: buf.readUInt16LE(28) & 0x3fff
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
if (chunk === 'VP8L' && buf.length >= 25 && buf[20] === 0x2f) {
|
|
96
|
+
const b1 = buf[21];
|
|
97
|
+
const b2 = buf[22];
|
|
98
|
+
const b3 = buf[23];
|
|
99
|
+
const b4 = buf[24];
|
|
100
|
+
return {
|
|
101
|
+
format: 'webp',
|
|
102
|
+
width: 1 + (((b2 & 0x3f) << 8) | b1),
|
|
103
|
+
height: 1 + (((b4 & 0x0f) << 10) | (b3 << 2) | ((b2 & 0xc0) >> 6))
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function packError(code, msg) {
|
|
111
|
+
return Object.assign(new Error(`${code}: ${msg}`), { code });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function sanitizeSvgToLayers(svgText) {
|
|
115
|
+
const raw = String(svgText || '');
|
|
116
|
+
if (!raw.trim()) {
|
|
117
|
+
throw packError('UNSAFE_SVG_CONTENT', 'Empty SVG file');
|
|
118
|
+
}
|
|
119
|
+
const forbiddenPatterns = [
|
|
120
|
+
/<\s*script\b/i,
|
|
121
|
+
/<\s*foreignObject\b/i,
|
|
122
|
+
/on[a-z]+\s*=/i,
|
|
123
|
+
/javascript\s*:/i,
|
|
124
|
+
/data\s*:\s*text\/html/i,
|
|
125
|
+
/https?:\/\//i,
|
|
126
|
+
/@import\b/i
|
|
127
|
+
];
|
|
128
|
+
for (const re of forbiddenPatterns) {
|
|
129
|
+
if (re.test(raw)) {
|
|
130
|
+
throw packError('UNSAFE_SVG_CONTENT', `SVG contains forbidden active/external content (${re})`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const layers = [];
|
|
135
|
+
const pathRe = /<path\b([^>]*)>/gi;
|
|
136
|
+
let m;
|
|
137
|
+
while ((m = pathRe.exec(raw)) !== null && layers.length < 48) {
|
|
138
|
+
const attrs = m[1] || '';
|
|
139
|
+
const dMatch = /\bd\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
140
|
+
if (!dMatch) continue;
|
|
141
|
+
const d = dMatch[1].trim();
|
|
142
|
+
if (!/^[MLHVCSQTAZmlhvcsqtaz0-9.,\s+-]+$/.test(d)) {
|
|
143
|
+
throw packError('UNSAFE_SVG_CONTENT', 'SVG path data contains invalid tokens');
|
|
144
|
+
}
|
|
145
|
+
const fillMatch = /\bfill\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
146
|
+
const strokeMatch = /\bstroke\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
147
|
+
const swMatch = /\bstroke-width\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
148
|
+
layers.push({
|
|
149
|
+
id: `svg-path-${layers.length}`,
|
|
150
|
+
kind: 'path',
|
|
151
|
+
d,
|
|
152
|
+
fill: fillMatch ? fillMatch[1].trim() : '#a78bfa',
|
|
153
|
+
...(strokeMatch ? { stroke: strokeMatch[1].trim() } : {}),
|
|
154
|
+
...(swMatch && Number.isFinite(Number(swMatch[1])) ? { strokeWidth: Number(swMatch[1]) } : {})
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const circleRe = /<circle\b([^>]*)>/gi;
|
|
159
|
+
while ((m = circleRe.exec(raw)) !== null && layers.length < 64) {
|
|
160
|
+
const attrs = m[1] || '';
|
|
161
|
+
const cx = Number((/\bcx\s*=\s*["']([^"']+)["']/i.exec(attrs) || [])[1] || 0);
|
|
162
|
+
const cy = Number((/\bcy\s*=\s*["']([^"']+)["']/i.exec(attrs) || [])[1] || 0);
|
|
163
|
+
const r = Number((/\br\s*=\s*["']([^"']+)["']/i.exec(attrs) || [])[1] || 0);
|
|
164
|
+
if (!Number.isFinite(r) || r <= 0) continue;
|
|
165
|
+
const fillMatch = /\bfill\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
166
|
+
layers.push({
|
|
167
|
+
id: `svg-circle-${layers.length}`,
|
|
168
|
+
kind: 'circle',
|
|
169
|
+
cx,
|
|
170
|
+
cy,
|
|
171
|
+
r,
|
|
172
|
+
fill: fillMatch ? fillMatch[1].trim() : '#a78bfa'
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (layers.length === 0) {
|
|
177
|
+
throw Object.assign(new Error('SVG yielded no valid geometric path/circle layers'), {
|
|
178
|
+
code: 'UNSAFE_SVG_CONTENT'
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
return layers;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function slugifyThemeId(rawId) {
|
|
185
|
+
const clean = String(rawId || '')
|
|
186
|
+
.toLowerCase()
|
|
187
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
188
|
+
.replace(/^-+|-+$/g, '')
|
|
189
|
+
.slice(0, 40);
|
|
190
|
+
return clean || `custom-${Date.now()}`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function validateSafeArchiveEntryName(rawName) {
|
|
194
|
+
const name = String(rawName || '');
|
|
195
|
+
if (!name || name.includes('\0') || name.startsWith('/') || name.startsWith('\\') || /^[a-zA-Z]:/.test(name)) {
|
|
196
|
+
throw packError('UNSAFE_PACK_PATH', `Unsafe archive path: ${name}`);
|
|
197
|
+
}
|
|
198
|
+
const normalized = name.replace(/\\/g, '/');
|
|
199
|
+
const parts = normalized.split('/').filter(Boolean);
|
|
200
|
+
if (parts.some((p) => p === '..')) {
|
|
201
|
+
throw packError('UNSAFE_PACK_PATH', `Path traversal in archive entry: ${name}`);
|
|
202
|
+
}
|
|
203
|
+
return parts.join('/');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function normalizeAndValidateManifest(rawManifest, customSlug, assetPathMap = new Map()) {
|
|
207
|
+
if (!rawManifest || typeof rawManifest !== 'object' || Array.isArray(rawManifest)) {
|
|
208
|
+
throw Object.assign(new Error('Invalid pet-theme.json manifest'), { code: 'INVALID_THEME_MANIFEST' });
|
|
209
|
+
}
|
|
210
|
+
const sceneInput = rawManifest.scene && typeof rawManifest.scene === 'object' ? rawManifest.scene : rawManifest;
|
|
211
|
+
const vbW = Math.min(512, Math.max(32, Number(sceneInput.viewBox?.width || 160)));
|
|
212
|
+
const vbH = Math.min(512, Math.max(32, Number(sceneInput.viewBox?.height || 160)));
|
|
213
|
+
const hitBox = {
|
|
214
|
+
x: Number(sceneInput.hitBox?.x ?? 20),
|
|
215
|
+
y: Number(sceneInput.hitBox?.y ?? 20),
|
|
216
|
+
width: Math.min(vbW, Math.max(16, Number(sceneInput.hitBox?.width || vbW - 40))),
|
|
217
|
+
height: Math.min(vbH, Math.max(16, Number(sceneInput.hitBox?.height || vbH - 40)))
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
const rawLayers = Array.isArray(sceneInput.layers) ? sceneInput.layers.slice(0, 64) : [];
|
|
221
|
+
const layers = [];
|
|
222
|
+
for (const item of rawLayers) {
|
|
223
|
+
if (!item || typeof item !== 'object') continue;
|
|
224
|
+
const kind = ['path', 'circle', 'rect', 'ellipse', 'sprite'].includes(item.kind) ? item.kind : 'path';
|
|
225
|
+
const layer = { id: String(item.id || `layer-${layers.length}`), kind };
|
|
226
|
+
if (kind === 'path') {
|
|
227
|
+
const d = String(item.d || '').trim();
|
|
228
|
+
if (!d || !/^[MLHVCSQTAZmlhvcsqtaz0-9.,\s+-]+$/.test(d)) {
|
|
229
|
+
throw Object.assign(new Error(`Invalid SVG path data in custom theme layer ${layer.id}`), {
|
|
230
|
+
code: 'UNSAFE_SVG_CONTENT'
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
layer.d = d;
|
|
234
|
+
} else if (kind === 'circle') {
|
|
235
|
+
layer.cx = Number(item.cx || 0);
|
|
236
|
+
layer.cy = Number(item.cy || 0);
|
|
237
|
+
layer.r = Math.max(0.5, Number(item.r || 10));
|
|
238
|
+
} else if (kind === 'ellipse') {
|
|
239
|
+
layer.cx = Number(item.cx || 0);
|
|
240
|
+
layer.cy = Number(item.cy || 0);
|
|
241
|
+
layer.rx = Math.max(0.5, Number(item.rx || 10));
|
|
242
|
+
layer.ry = Math.max(0.5, Number(item.ry || 10));
|
|
243
|
+
} else if (kind === 'rect') {
|
|
244
|
+
layer.x = Number(item.x || 0);
|
|
245
|
+
layer.y = Number(item.y || 0);
|
|
246
|
+
layer.width = Math.max(1, Number(item.width || 10));
|
|
247
|
+
layer.height = Math.max(1, Number(item.height || 10));
|
|
248
|
+
if (item.cornerRadius !== undefined) layer.cornerRadius = Math.max(0, Number(item.cornerRadius));
|
|
249
|
+
} else if (kind === 'sprite') {
|
|
250
|
+
const spRaw = String(item.spritePath || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
251
|
+
const resolved = assetPathMap.get(spRaw);
|
|
252
|
+
if (!resolved) {
|
|
253
|
+
throw Object.assign(new Error(`Sprite missing or blocked by sandbox: ${item.spritePath}`), {
|
|
254
|
+
code: 'UNSAFE_SPRITE_REF'
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
layer.spritePath = resolved;
|
|
258
|
+
layer.x = Number(item.x || 0);
|
|
259
|
+
layer.y = Number(item.y || 0);
|
|
260
|
+
layer.width = Math.max(8, Number(item.width || vbW));
|
|
261
|
+
layer.height = Math.max(8, Number(item.height || vbH));
|
|
262
|
+
}
|
|
263
|
+
if (typeof item.fill === 'string') layer.fill = item.fill.trim();
|
|
264
|
+
if (typeof item.stroke === 'string') layer.stroke = item.stroke.trim();
|
|
265
|
+
if (item.strokeWidth !== undefined) layer.strokeWidth = Number(item.strokeWidth);
|
|
266
|
+
if (item.opacity !== undefined) layer.opacity = Number(item.opacity);
|
|
267
|
+
if (item.motion && typeof item.motion === 'object') layer.motion = item.motion;
|
|
268
|
+
layers.push(layer);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (layers.length === 0) {
|
|
272
|
+
throw Object.assign(new Error('Custom theme must contain at least one valid layer'), {
|
|
273
|
+
code: 'INVALID_THEME_MANIFEST'
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const nameRaw = rawManifest.name;
|
|
278
|
+
const name = typeof nameRaw === 'string' && nameRaw.trim()
|
|
279
|
+
? { 'zh-CN': nameRaw.trim().slice(0, 40), en: nameRaw.trim().slice(0, 40) }
|
|
280
|
+
: (nameRaw && typeof nameRaw === 'object' ? nameRaw : { 'zh-CN': customSlug, en: customSlug });
|
|
281
|
+
|
|
282
|
+
return {
|
|
283
|
+
id: `custom:${customSlug}`,
|
|
284
|
+
slug: customSlug,
|
|
285
|
+
name,
|
|
286
|
+
description: rawManifest.description || { 'zh-CN': '本地导入自定义形象', en: 'Locally imported custom pet pack' },
|
|
287
|
+
accentHex: typeof rawManifest.accentHex === 'string' && /^#[0-9a-fA-F]{6}$/.test(rawManifest.accentHex)
|
|
288
|
+
? rawManifest.accentHex
|
|
289
|
+
: '#a78bfa',
|
|
290
|
+
builtin: false,
|
|
291
|
+
scene: {
|
|
292
|
+
sceneId: `custom:${customSlug}`,
|
|
293
|
+
viewBox: { width: vbW, height: vbH },
|
|
294
|
+
fps: { active: 30, idle: 12, sleep: 4 },
|
|
295
|
+
hitBox,
|
|
296
|
+
particles: sceneInput.particles && typeof sceneInput.particles === 'object'
|
|
297
|
+
? sceneInput.particles
|
|
298
|
+
: { preset: 'sparks', color: '#a78bfa' },
|
|
299
|
+
layers
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function listCustomThemes(customThemesDir) {
|
|
305
|
+
if (!customThemesDir || !fs.existsSync(customThemesDir)) return [];
|
|
306
|
+
const out = [];
|
|
307
|
+
for (const ent of fs.readdirSync(customThemesDir, { withFileTypes: true })) {
|
|
308
|
+
if (!ent.isDirectory()) continue;
|
|
309
|
+
const mfPath = path.join(customThemesDir, ent.name, 'theme.resolved.json');
|
|
310
|
+
if (!fs.existsSync(mfPath)) continue;
|
|
311
|
+
try {
|
|
312
|
+
const data = JSON.parse(fs.readFileSync(mfPath, 'utf8'));
|
|
313
|
+
if (data && data.id && data.scene) out.push(data);
|
|
314
|
+
} catch {}
|
|
315
|
+
}
|
|
316
|
+
return out.sort((a, b) => String(a.id).localeCompare(String(b.id)));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function deleteCustomTheme(customThemesDir, themeId) {
|
|
320
|
+
const slug = String(themeId || '').replace(/^custom:/, '').trim();
|
|
321
|
+
if (!slug || slug.includes('..') || slug.includes('/') || slug.includes('\\')) {
|
|
322
|
+
return { ok: false, error: 'INVALID_THEME_ID' };
|
|
323
|
+
}
|
|
324
|
+
if (!fs.existsSync(customThemesDir)) return { ok: false, error: 'NOT_FOUND' };
|
|
325
|
+
const realRoot = fs.realpathSync(customThemesDir);
|
|
326
|
+
const targetDir = path.join(realRoot, slug);
|
|
327
|
+
if (!fs.existsSync(targetDir)) return { ok: false, error: 'NOT_FOUND' };
|
|
328
|
+
const realTarget = fs.realpathSync(targetDir);
|
|
329
|
+
if (!realTarget.startsWith(realRoot + path.sep)) {
|
|
330
|
+
return { ok: false, error: 'UNSAFE_PATH' };
|
|
331
|
+
}
|
|
332
|
+
fs.rmSync(realTarget, { recursive: true, force: true });
|
|
333
|
+
return { ok: true, id: `custom:${slug}` };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function importThemePack({ customThemesDir, archiveBase64, jsonText, svgText, fileName = 'custom-pet.agypet' }) {
|
|
337
|
+
if (!customThemesDir) throw new Error('customThemesDir is required');
|
|
338
|
+
fs.mkdirSync(customThemesDir, { recursive: true });
|
|
339
|
+
const realRoot = fs.realpathSync(customThemesDir);
|
|
340
|
+
|
|
341
|
+
const existingCount = listCustomThemes(realRoot).length;
|
|
342
|
+
if (existingCount >= MAX_CUSTOM_THEMES) {
|
|
343
|
+
throw Object.assign(new Error(`Custom theme limit (${MAX_CUSTOM_THEMES}) reached`), {
|
|
344
|
+
code: 'CUSTOM_THEME_LIMIT_EXCEEDED'
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const cleanFileName = String(fileName || '').toLowerCase();
|
|
349
|
+
|
|
350
|
+
// Direct JSON manifest import
|
|
351
|
+
if (jsonText !== undefined || cleanFileName.endsWith('.json')) {
|
|
352
|
+
const rawStr = jsonText !== undefined
|
|
353
|
+
? String(jsonText)
|
|
354
|
+
: Buffer.from(String(archiveBase64 || ''), 'base64').toString('utf8');
|
|
355
|
+
if (Buffer.byteLength(rawStr, 'utf8') > MAX_THEME_JSON_BYTES) {
|
|
356
|
+
throw Object.assign(new Error('JSON manifest exceeds 128 KB'), { code: 'UNSAFE_PACK_SIZE' });
|
|
357
|
+
}
|
|
358
|
+
const parsed = JSON.parse(rawStr);
|
|
359
|
+
const slug = slugifyThemeId(parsed.id || path.basename(cleanFileName, '.json'));
|
|
360
|
+
const themeDir = path.join(realRoot, slug);
|
|
361
|
+
fs.mkdirSync(themeDir, { recursive: true });
|
|
362
|
+
const resolved = normalizeAndValidateManifest(parsed, slug);
|
|
363
|
+
fs.writeFileSync(path.join(themeDir, 'theme.resolved.json'), JSON.stringify(resolved, null, 2), 'utf8');
|
|
364
|
+
return resolved;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// Direct single SVG import (Zero-Script SVG Sanitizer)
|
|
368
|
+
if (svgText !== undefined || cleanFileName.endsWith('.svg')) {
|
|
369
|
+
const rawSvg = svgText !== undefined
|
|
370
|
+
? String(svgText)
|
|
371
|
+
: Buffer.from(String(archiveBase64 || ''), 'base64').toString('utf8');
|
|
372
|
+
if (Buffer.byteLength(rawSvg, 'utf8') > MAX_RASTER_BYTES) {
|
|
373
|
+
throw Object.assign(new Error('SVG exceeds 1 MB'), { code: 'UNSAFE_PACK_SIZE' });
|
|
374
|
+
}
|
|
375
|
+
const layers = sanitizeSvgToLayers(rawSvg);
|
|
376
|
+
const slug = slugifyThemeId(path.basename(cleanFileName, '.svg'));
|
|
377
|
+
const themeDir = path.join(realRoot, slug);
|
|
378
|
+
fs.mkdirSync(themeDir, { recursive: true });
|
|
379
|
+
const resolved = normalizeAndValidateManifest({ id: slug, name: slug, layers }, slug);
|
|
380
|
+
fs.writeFileSync(path.join(themeDir, 'theme.resolved.json'), JSON.stringify(resolved, null, 2), 'utf8');
|
|
381
|
+
return resolved;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// .agypet / .tar / .tar.gz archive import
|
|
385
|
+
const rawBuf = Buffer.from(String(archiveBase64 || ''), 'base64');
|
|
386
|
+
if (rawBuf.length === 0 || rawBuf.length > MAX_ARCHIVE_BYTES) {
|
|
387
|
+
throw Object.assign(new Error(`Archive size invalid (${rawBuf.length} bytes, max 5 MB)`), {
|
|
388
|
+
code: 'UNSAFE_PACK_SIZE'
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
let tarBuf = rawBuf;
|
|
393
|
+
if (rawBuf.length >= 2 && rawBuf[0] === 0x1f && rawBuf[1] === 0x8b) {
|
|
394
|
+
tarBuf = zlib.gunzipSync(rawBuf, { maxOutputLength: MAX_UNPACKED_BYTES + 4096 });
|
|
395
|
+
}
|
|
396
|
+
if (tarBuf.length > MAX_UNPACKED_BYTES) {
|
|
397
|
+
throw Object.assign(new Error('Unpacked archive exceeds 12 MB limit'), { code: 'UNSAFE_PACK_SIZE' });
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const entries = parseTarBuffer(tarBuf);
|
|
401
|
+
if (entries.length === 0 || entries.length > MAX_ENTRY_COUNT) {
|
|
402
|
+
throw Object.assign(new Error(`Archive entry count invalid (${entries.length}, max ${MAX_ENTRY_COUNT})`), {
|
|
403
|
+
code: 'UNSAFE_PACK_ENTRIES'
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
let totalUnpacked = 0;
|
|
408
|
+
let manifestJson = null;
|
|
409
|
+
const safeFiles = [];
|
|
410
|
+
|
|
411
|
+
for (const ent of entries) {
|
|
412
|
+
if (ent.type === '1' || ent.type === '2' || ent.type === '3' || ent.type === '4' || ent.type === '6') {
|
|
413
|
+
throw packError('UNSAFE_PACK_LINK', `Links/devices forbidden in .agypet archive: ${ent.name}`);
|
|
414
|
+
}
|
|
415
|
+
const safeRel = validateSafeArchiveEntryName(ent.name);
|
|
416
|
+
if (!safeRel || ent.type === '5') continue;
|
|
417
|
+
|
|
418
|
+
const ext = path.extname(safeRel).toLowerCase();
|
|
419
|
+
if (FORBIDDEN_EXTENSIONS.has(ext) || !ALLOWED_EXTENSIONS.has(ext)) {
|
|
420
|
+
throw packError('UNSAFE_PACK_FILE_TYPE', `Forbidden file type in .agypet archive: ${safeRel}`);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
totalUnpacked += ent.data.length;
|
|
424
|
+
if (totalUnpacked > MAX_UNPACKED_BYTES) {
|
|
425
|
+
throw packError('UNSAFE_PACK_SIZE', 'Archive unpacked total exceeds 12 MB');
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
if (ext === '.json') {
|
|
429
|
+
if (ent.data.length > MAX_THEME_JSON_BYTES) {
|
|
430
|
+
throw packError('UNSAFE_PACK_SIZE', 'pet-theme.json exceeds 128 KB');
|
|
431
|
+
}
|
|
432
|
+
if (path.basename(safeRel) === 'pet-theme.json') {
|
|
433
|
+
manifestJson = JSON.parse(ent.data.toString('utf8'));
|
|
434
|
+
}
|
|
435
|
+
} else if (ext === '.svg') {
|
|
436
|
+
if (ent.data.length > MAX_RASTER_BYTES) {
|
|
437
|
+
throw packError('UNSAFE_PACK_SIZE', `SVG exceeds 1 MB: ${safeRel}`);
|
|
438
|
+
}
|
|
439
|
+
const layers = sanitizeSvgToLayers(ent.data.toString('utf8'));
|
|
440
|
+
safeFiles.push({ rel: safeRel, kind: 'svg-layers', layers });
|
|
441
|
+
} else {
|
|
442
|
+
if (ent.data.length > MAX_RASTER_BYTES) {
|
|
443
|
+
throw packError('UNSAFE_PACK_SIZE', `Sprite exceeds 1 MB: ${safeRel}`);
|
|
444
|
+
}
|
|
445
|
+
const info = inspectRasterHeader(ent.data);
|
|
446
|
+
if (!info) {
|
|
447
|
+
throw packError('UNSAFE_SPRITE_FORMAT', `Invalid raster magic bytes: ${safeRel}`);
|
|
448
|
+
}
|
|
449
|
+
if (info.width <= 0 || info.height <= 0 || info.width > MAX_RASTER_DIM || info.height > MAX_RASTER_DIM) {
|
|
450
|
+
throw packError('UNSAFE_SPRITE_DIMENSIONS', `Sprite dimensions exceed 512x512: ${safeRel}`);
|
|
451
|
+
}
|
|
452
|
+
safeFiles.push({ rel: safeRel, kind: 'raster', data: ent.data });
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if (!manifestJson) {
|
|
457
|
+
throw Object.assign(new Error('Missing pet-theme.json in archive'), { code: 'INVALID_THEME_MANIFEST' });
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const slug = slugifyThemeId(manifestJson.id || path.basename(cleanFileName, path.extname(cleanFileName)));
|
|
461
|
+
const themeDir = path.join(realRoot, slug);
|
|
462
|
+
fs.mkdirSync(themeDir, { recursive: true });
|
|
463
|
+
const realThemeDir = fs.realpathSync(themeDir);
|
|
464
|
+
if (!realThemeDir.startsWith(realRoot + path.sep)) {
|
|
465
|
+
throw Object.assign(new Error('Theme directory escaped sandbox root'), { code: 'UNSAFE_PACK_PATH' });
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const assetPathMap = new Map();
|
|
469
|
+
for (const item of safeFiles) {
|
|
470
|
+
if (item.kind === 'raster') {
|
|
471
|
+
const dest = path.resolve(realThemeDir, item.rel);
|
|
472
|
+
if (!dest.startsWith(realThemeDir + path.sep)) {
|
|
473
|
+
throw Object.assign(new Error('Resolved sprite path escaped theme directory'), { code: 'UNSAFE_PACK_PATH' });
|
|
474
|
+
}
|
|
475
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
476
|
+
fs.writeFileSync(dest, item.data);
|
|
477
|
+
const realDest = fs.realpathSync(dest);
|
|
478
|
+
if (!realDest.startsWith(realRoot + path.sep)) {
|
|
479
|
+
throw Object.assign(new Error('Symlink escape detected after write'), { code: 'UNSAFE_PACK_PATH' });
|
|
480
|
+
}
|
|
481
|
+
assetPathMap.set(item.rel, realDest);
|
|
482
|
+
assetPathMap.set(path.basename(item.rel), realDest);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const resolved = normalizeAndValidateManifest(manifestJson, slug, assetPathMap);
|
|
487
|
+
fs.writeFileSync(path.join(realThemeDir, 'theme.resolved.json'), JSON.stringify(resolved, null, 2), 'utf8');
|
|
488
|
+
return resolved;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
module.exports = {
|
|
492
|
+
MAX_ARCHIVE_BYTES,
|
|
493
|
+
MAX_UNPACKED_BYTES,
|
|
494
|
+
MAX_ENTRY_COUNT,
|
|
495
|
+
MAX_CUSTOM_THEMES,
|
|
496
|
+
inspectRasterHeader,
|
|
497
|
+
sanitizeSvgToLayers,
|
|
498
|
+
importThemePack,
|
|
499
|
+
listCustomThemes,
|
|
500
|
+
deleteCustomTheme
|
|
501
|
+
};
|