@lumesync/studio 0.0.0-stage → 1.0.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.
@@ -0,0 +1,251 @@
1
+ // 无第三方依赖的 ZIP 读写:只支持 store / deflate,拒绝 zip64、加密、符号链接与越界路径。
2
+ // 打包输出固定时间戳与排序,保证同一 revision 生成字节稳定。
3
+
4
+ import zlib from 'node:zlib';
5
+ import { ERROR_CODES, StudioError } from './errors.js';
6
+
7
+ const LOCAL_SIGNATURE = 0x04034b50;
8
+ const CENTRAL_SIGNATURE = 0x02014b50;
9
+ const EOCD_SIGNATURE = 0x06054b50;
10
+ const FLAG_UTF8 = 0x0800;
11
+ const METHOD_STORE = 0;
12
+ const METHOD_DEFLATE = 8;
13
+ // 1980-01-01 00:00:00,固定时间戳保证可复现。
14
+ const DOS_TIME = 0;
15
+ const DOS_DATE = ((1980 - 1980) << 9) | (1 << 5) | 1;
16
+
17
+ export const ZIP_LIMITS = {
18
+ maxEntries: 5000,
19
+ maxEntryBytes: 64 * 1024 * 1024,
20
+ maxTotalBytes: 256 * 1024 * 1024,
21
+ };
22
+
23
+ let crcTable = null;
24
+
25
+ function table() {
26
+ if (crcTable) return crcTable;
27
+ crcTable = new Uint32Array(256);
28
+ for (let index = 0; index < 256; index += 1) {
29
+ let value = index;
30
+ for (let bit = 0; bit < 8; bit += 1) {
31
+ value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
32
+ }
33
+ crcTable[index] = value >>> 0;
34
+ }
35
+ return crcTable;
36
+ }
37
+
38
+ export function crc32(buffer) {
39
+ const lookup = table();
40
+ let crc = 0xffffffff;
41
+ for (const byte of buffer) {
42
+ crc = lookup[(crc ^ byte) & 0xff] ^ (crc >>> 8);
43
+ }
44
+ return (crc ^ 0xffffffff) >>> 0;
45
+ }
46
+
47
+ function zipError(message, details, status = 422) {
48
+ return new StudioError(ERROR_CODES.COURSEWARE_INVALID, message, details, status);
49
+ }
50
+
51
+ export function assertSafeEntryPath(name) {
52
+ if (typeof name !== 'string' || name.length === 0) throw zipError('压缩包条目路径为空');
53
+ if (name.includes('\0')) throw zipError('压缩包条目路径包含非法字符', { name });
54
+ if (name.includes('\\')) throw zipError('压缩包条目路径不能包含反斜杠', { name });
55
+ if (name.startsWith('/') || /^[a-zA-Z]:/.test(name)) throw zipError('压缩包条目不能使用绝对路径', { name });
56
+ const parts = name.split('/');
57
+ for (const part of parts) {
58
+ if (part === '' || part === '.' || part === '..') {
59
+ throw zipError('压缩包条目路径越界', { name });
60
+ }
61
+ if (part.startsWith('.')) {
62
+ throw zipError('压缩包不能包含隐藏文件或 .studio 目录', { name });
63
+ }
64
+ }
65
+ return parts.join('/');
66
+ }
67
+
68
+ function normalizeEntries(entries) {
69
+ if (!Array.isArray(entries) || entries.length === 0) throw zipError('没有可打包的文件');
70
+ if (entries.length > ZIP_LIMITS.maxEntries) throw zipError('压缩包条目过多', { limit: ZIP_LIMITS.maxEntries });
71
+ const seen = new Set();
72
+ let total = 0;
73
+ const normalized = entries.map((entry) => {
74
+ const name = assertSafeEntryPath(entry.path);
75
+ if (seen.has(name)) throw zipError('压缩包条目路径重复', { name });
76
+ seen.add(name);
77
+ const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data ?? '');
78
+ if (data.length > ZIP_LIMITS.maxEntryBytes) throw zipError('单个文件超过打包上限', { name, limit: ZIP_LIMITS.maxEntryBytes });
79
+ total += data.length;
80
+ if (total > ZIP_LIMITS.maxTotalBytes) throw zipError('压缩包总大小超过上限', { limit: ZIP_LIMITS.maxTotalBytes });
81
+ return { name, data };
82
+ });
83
+ normalized.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
84
+ return normalized;
85
+ }
86
+
87
+ export function createZip(entries) {
88
+ const files = normalizeEntries(entries);
89
+ const locals = [];
90
+ const centrals = [];
91
+ let offset = 0;
92
+ for (const file of files) {
93
+ const compressed = zlib.deflateRawSync(file.data, { level: 9 });
94
+ const useDeflate = compressed.length < file.data.length;
95
+ const payload = useDeflate ? compressed : file.data;
96
+ const method = useDeflate ? METHOD_DEFLATE : METHOD_STORE;
97
+ const name = Buffer.from(file.name, 'utf8');
98
+ const checksum = crc32(file.data);
99
+
100
+ const local = Buffer.alloc(30);
101
+ local.writeUInt32LE(LOCAL_SIGNATURE, 0);
102
+ local.writeUInt16LE(20, 4);
103
+ local.writeUInt16LE(FLAG_UTF8, 6);
104
+ local.writeUInt16LE(method, 8);
105
+ local.writeUInt16LE(DOS_TIME, 10);
106
+ local.writeUInt16LE(DOS_DATE, 12);
107
+ local.writeUInt32LE(checksum, 14);
108
+ local.writeUInt32LE(payload.length, 18);
109
+ local.writeUInt32LE(file.data.length, 22);
110
+ local.writeUInt16LE(name.length, 26);
111
+ local.writeUInt16LE(0, 28);
112
+ locals.push(local, name, payload);
113
+
114
+ const central = Buffer.alloc(46);
115
+ central.writeUInt32LE(CENTRAL_SIGNATURE, 0);
116
+ central.writeUInt16LE(20, 4);
117
+ central.writeUInt16LE(20, 6);
118
+ central.writeUInt16LE(FLAG_UTF8, 8);
119
+ central.writeUInt16LE(method, 10);
120
+ central.writeUInt16LE(DOS_TIME, 12);
121
+ central.writeUInt16LE(DOS_DATE, 14);
122
+ central.writeUInt32LE(checksum, 16);
123
+ central.writeUInt32LE(payload.length, 20);
124
+ central.writeUInt32LE(file.data.length, 24);
125
+ central.writeUInt16LE(name.length, 28);
126
+ central.writeUInt16LE(0, 30);
127
+ central.writeUInt16LE(0, 32);
128
+ central.writeUInt16LE(0, 34);
129
+ central.writeUInt16LE(0, 36);
130
+ central.writeUInt32LE((0o100644 * 0x10000) >>> 0, 38);
131
+ central.writeUInt32LE(offset, 42);
132
+ centrals.push(central, name);
133
+
134
+ offset += local.length + name.length + payload.length;
135
+ }
136
+
137
+ const centralOffset = offset;
138
+ const centralSize = centrals.reduce((sum, part) => sum + part.length, 0);
139
+ const eocd = Buffer.alloc(22);
140
+ eocd.writeUInt32LE(EOCD_SIGNATURE, 0);
141
+ eocd.writeUInt16LE(0, 4);
142
+ eocd.writeUInt16LE(0, 6);
143
+ eocd.writeUInt16LE(files.length, 8);
144
+ eocd.writeUInt16LE(files.length, 10);
145
+ eocd.writeUInt32LE(centralSize, 12);
146
+ eocd.writeUInt32LE(centralOffset, 16);
147
+ eocd.writeUInt16LE(0, 20);
148
+
149
+ return Buffer.concat([...locals, ...centrals, eocd]);
150
+ }
151
+
152
+ export function readZip(buffer) {
153
+ if (!Buffer.isBuffer(buffer) || buffer.length < 22) throw zipError('不是合法的 ZIP 文件');
154
+ let eocd = -1;
155
+ const minimum = Math.max(0, buffer.length - 22 - 0xffff);
156
+ for (let index = buffer.length - 22; index >= minimum; index -= 1) {
157
+ if (buffer.readUInt32LE(index) === EOCD_SIGNATURE) {
158
+ eocd = index;
159
+ break;
160
+ }
161
+ }
162
+ if (eocd < 0) throw zipError('ZIP 缺少中央目录结束标记');
163
+
164
+ const count = buffer.readUInt16LE(eocd + 10);
165
+ const centralSize = buffer.readUInt32LE(eocd + 12);
166
+ const centralOffset = buffer.readUInt32LE(eocd + 16);
167
+ if (count === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff) {
168
+ throw zipError('不支持 ZIP64 包');
169
+ }
170
+ if (count > ZIP_LIMITS.maxEntries) throw zipError('压缩包条目过多', { limit: ZIP_LIMITS.maxEntries });
171
+ if (centralOffset + centralSize > buffer.length) throw zipError('ZIP 中央目录越界');
172
+
173
+ const entries = [];
174
+ const seen = new Set();
175
+ let total = 0;
176
+ let cursor = centralOffset;
177
+ for (let index = 0; index < count; index += 1) {
178
+ if (cursor + 46 > buffer.length || buffer.readUInt32LE(cursor) !== CENTRAL_SIGNATURE) {
179
+ throw zipError('ZIP 中央目录损坏');
180
+ }
181
+ const flags = buffer.readUInt16LE(cursor + 8);
182
+ if (flags & 0x1) throw zipError('不支持加密 ZIP 条目');
183
+ const method = buffer.readUInt16LE(cursor + 10);
184
+ const compressedSize = buffer.readUInt32LE(cursor + 20);
185
+ const uncompressedSize = buffer.readUInt32LE(cursor + 24);
186
+ const nameLength = buffer.readUInt16LE(cursor + 28);
187
+ const extraLength = buffer.readUInt16LE(cursor + 30);
188
+ const commentLength = buffer.readUInt16LE(cursor + 32);
189
+ const externalAttributes = buffer.readUInt32LE(cursor + 38);
190
+ const localOffset = buffer.readUInt32LE(cursor + 42);
191
+ const nameEnd = cursor + 46 + nameLength;
192
+ if (nameEnd > buffer.length) throw zipError('ZIP 条目名称越界');
193
+ const rawName = buffer.subarray(cursor + 46, nameEnd).toString('utf8');
194
+ const directory = rawName.endsWith('/');
195
+ const base = rawName.split('/').pop() ?? '';
196
+ const ignored = rawName.startsWith('__MACOSX/') || base === '.DS_Store' || base.startsWith('._');
197
+ const mode = (externalAttributes >>> 16) & 0xffff;
198
+ if (!directory && !ignored && (mode & 0o170000) === 0o120000) {
199
+ throw zipError('压缩包不能包含符号链接', { name: rawName });
200
+ }
201
+
202
+ if (!directory && !ignored) {
203
+ const name = assertSafeEntryPath(rawName);
204
+ if (seen.has(name)) throw zipError('压缩包条目路径重复', { name });
205
+ seen.add(name);
206
+ if (uncompressedSize > ZIP_LIMITS.maxEntryBytes) throw zipError('单个文件超过解包上限', { name, limit: ZIP_LIMITS.maxEntryBytes });
207
+ total += uncompressedSize;
208
+ if (total > ZIP_LIMITS.maxTotalBytes) throw zipError('压缩包总解包大小超过上限', { limit: ZIP_LIMITS.maxTotalBytes });
209
+ if (localOffset + 30 > buffer.length || buffer.readUInt32LE(localOffset) !== LOCAL_SIGNATURE) {
210
+ throw zipError('ZIP 本地文件头损坏', { name });
211
+ }
212
+ if (buffer.readUInt16LE(localOffset + 8) !== method) throw zipError('ZIP 条目压缩方式不一致', { name });
213
+ const localNameLength = buffer.readUInt16LE(localOffset + 26);
214
+ const localExtraLength = buffer.readUInt16LE(localOffset + 28);
215
+ const dataStart = localOffset + 30 + localNameLength + localExtraLength;
216
+ const dataEnd = dataStart + compressedSize;
217
+ if (dataEnd > buffer.length) throw zipError('ZIP 条目数据越界', { name });
218
+ const payload = buffer.subarray(dataStart, dataEnd);
219
+ let data;
220
+ if (method === METHOD_STORE) data = Buffer.from(payload);
221
+ else if (method === METHOD_DEFLATE) {
222
+ try {
223
+ data = zlib.inflateRawSync(payload);
224
+ } catch {
225
+ throw zipError('ZIP 条目解压失败', { name });
226
+ }
227
+ } else {
228
+ throw zipError('不支持的 ZIP 压缩方式', { name, method });
229
+ }
230
+ if (data.length !== uncompressedSize) throw zipError('ZIP 条目大小不一致', { name });
231
+ const checksum = buffer.readUInt32LE(cursor + 16);
232
+ if (crc32(data) !== checksum) throw zipError('ZIP 条目校验失败', { name });
233
+ entries.push({ path: name, data });
234
+ }
235
+
236
+ cursor = nameEnd + extraLength + commentLength;
237
+ }
238
+ if (entries.length === 0) throw zipError('压缩包中没有文件');
239
+ return entries;
240
+ }
241
+
242
+ // 兼容“整包放在单一顶层目录”的压缩工具输出。
243
+ export function stripSingleRoot(entries) {
244
+ const hasRootManifest = entries.some((entry) => entry.path === 'manifest.json');
245
+ if (hasRootManifest) return entries;
246
+ const manifests = entries.filter((entry) => entry.path.endsWith('/manifest.json'));
247
+ if (manifests.length !== 1) return entries;
248
+ const root = manifests[0].path.slice(0, -'manifest.json'.length);
249
+ if (!entries.every((entry) => entry.path.startsWith(root))) return entries;
250
+ return entries.map((entry) => ({ ...entry, path: entry.path.slice(root.length) }));
251
+ }