odant-work 1.0.20 → 1.0.22
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/#system/package-manifest.json +37 -24
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +21 -2
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +58 -0
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/readme.md +2 -2
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +2 -11
- package/$server/$folder/lib/chat-item/chat-item.js +17 -1
- package/$server/$folder/lib/local-models-transfer/local-models-transfer.js +972 -0
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +408 -111
- package/MODELS/Local/$provider/handlers/methods/transfer/$handler/class.js +41 -0
- package/logo.png +0 -0
- package/package.json +1 -1
- package/rules/threats.md +117 -116
- package/sources/client.js +1 -0
- package/sources/data/progress.md +15 -0
- package/sources/host/auto-updater.js +6 -2
- package/sources/host/http-server.js +23 -0
- package/sources/host/websocket.js +127 -120
- package/sources/modules/agent/index.js +6 -1
- package/sources/modules/agent/readme.md +217 -216
- package/sources/modules/agent/session.js +43 -8
- package/sources/modules/agent/tools/chrome.js +263 -0
- package/sources/modules/bridge/chrome.js +673 -0
- package/sources/modules/bridge/hub.js +395 -361
- package/sources/modules/chrome-extension/background.js +299 -0
- package/sources/modules/chrome-extension/manifest.json +25 -0
- package/sources/modules/chrome-extension/options.html +48 -0
- package/sources/modules/chrome-extension/options.js +104 -0
- package/sources/modules/chrome-extension/popup.html +25 -0
- package/sources/modules/chrome-extension/popup.js +32 -0
- package/sources/modules/trainer/huggingface.js +412 -65
- package/sources/modules/trainer/index.js +288 -1
- package/sources/modules/trainer/tar-stream.js +458 -0
- package/sources/modules/trainer/transfer.js +1570 -0
- package/sources/modules/user-profile/user-profile.js +34 -10
- package/sources/modules/user-profile/user-token.js +168 -0
- package/sw.js +85 -9
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Потоковый POSIX.1-2001 (USTAR + PAX) генератор и парсер `.tar` без сжатия.
|
|
3
|
+
*
|
|
4
|
+
* Особенности:
|
|
5
|
+
* - Нулевая буферизация файлов в памяти: файлы читаются и пишутся чанками напрямую с диска и на диск.
|
|
6
|
+
* - Полная поддержка UTF-8 путей (включая кириллицу и пути длиннее 100 байт) и файлов > 8 ГБ через PAX extended headers.
|
|
7
|
+
* - Защита от path traversal (`..`, абсолютные пути, симлинки/хардлинки отклоняются).
|
|
8
|
+
*/
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import fsp from 'node:fs/promises';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
import { PassThrough } from 'node:stream';
|
|
14
|
+
|
|
15
|
+
const BLOCK_SIZE = 512;
|
|
16
|
+
const MAX_USTAR_SIZE = 0o77777777777; // 8 GiB - 1
|
|
17
|
+
const ZERO_BLOCK = Buffer.alloc(BLOCK_SIZE);
|
|
18
|
+
|
|
19
|
+
function formatOctal(num, width) {
|
|
20
|
+
const str = Math.max(0, Math.floor(Number(num) || 0)).toString(8);
|
|
21
|
+
return str.padStart(width - 1, '0').slice(-(width - 1)) + '\0';
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function buildPaxRecord(key, value) {
|
|
25
|
+
const body = ` ${key}=${value}\n`;
|
|
26
|
+
let totalLen = Buffer.byteLength(body, 'utf8') + 1;
|
|
27
|
+
while (true) {
|
|
28
|
+
const line = `${totalLen}${body}`;
|
|
29
|
+
const actual = Buffer.byteLength(line, 'utf8');
|
|
30
|
+
if (actual === totalLen)
|
|
31
|
+
return Buffer.from(line, 'utf8');
|
|
32
|
+
totalLen = actual;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function parsePaxBuffer(buf) {
|
|
37
|
+
const out = {};
|
|
38
|
+
let offset = 0;
|
|
39
|
+
while (offset < buf.length) {
|
|
40
|
+
const sp = buf.indexOf(0x20, offset);
|
|
41
|
+
if (sp <= offset)
|
|
42
|
+
break;
|
|
43
|
+
const len = Number(buf.subarray(offset, sp).toString('ascii'));
|
|
44
|
+
if (!Number.isFinite(len) || len <= 0 || offset + len > buf.length)
|
|
45
|
+
break;
|
|
46
|
+
const rec = buf.subarray(sp + 1, offset + len).toString('utf8').replace(/\n$/, '');
|
|
47
|
+
const eq = rec.indexOf('=');
|
|
48
|
+
if (eq > 0)
|
|
49
|
+
out[rec.slice(0, eq)] = rec.slice(eq + 1);
|
|
50
|
+
offset += len;
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function encodeTarHeader({ name, size = 0, mtime = Date.now(), type = '0', mode = 0o644 }) {
|
|
56
|
+
const header = Buffer.alloc(BLOCK_SIZE);
|
|
57
|
+
const nameBuf = Buffer.from(String(name || ''), 'utf8');
|
|
58
|
+
nameBuf.copy(header, 0, 0, Math.min(nameBuf.length, 100));
|
|
59
|
+
header.write(formatOctal(mode, 8), 100, 8, 'ascii');
|
|
60
|
+
header.write(formatOctal(0, 8), 108, 8, 'ascii');
|
|
61
|
+
header.write(formatOctal(0, 8), 116, 8, 'ascii');
|
|
62
|
+
header.write(formatOctal(size > MAX_USTAR_SIZE ? 0 : size, 12), 124, 12, 'ascii');
|
|
63
|
+
header.write(formatOctal(Math.floor(mtime / 1000), 12), 136, 12, 'ascii');
|
|
64
|
+
header.fill(0x20, 148, 156); // placeholder for checksum
|
|
65
|
+
header.write(type, 156, 1, 'ascii');
|
|
66
|
+
header.write('ustar\0', 257, 6, 'ascii');
|
|
67
|
+
header.write('00', 263, 2, 'ascii');
|
|
68
|
+
|
|
69
|
+
let sum = 0;
|
|
70
|
+
for (let i = 0; i < BLOCK_SIZE; i++)
|
|
71
|
+
sum += header[i];
|
|
72
|
+
const chk = sum.toString(8).padStart(6, '0') + '\0 ';
|
|
73
|
+
header.write(chk, 148, 8, 'ascii');
|
|
74
|
+
return header;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function buildEntryHeaders(relPath, size, mtimeMs) {
|
|
78
|
+
const norm = String(relPath).replace(/\\/g, '/').replace(/^\/+/, '');
|
|
79
|
+
const nameBytes = Buffer.byteLength(norm, 'utf8');
|
|
80
|
+
const isAscii = /^[\x20-\x7e]+$/.test(norm);
|
|
81
|
+
const needPax = !isAscii || nameBytes > 99 || size > MAX_USTAR_SIZE;
|
|
82
|
+
|
|
83
|
+
const blocks = [];
|
|
84
|
+
if (needPax) {
|
|
85
|
+
const paxChunks = [];
|
|
86
|
+
if (!isAscii || nameBytes > 99)
|
|
87
|
+
paxChunks.push(buildPaxRecord('path', norm));
|
|
88
|
+
if (size > MAX_USTAR_SIZE)
|
|
89
|
+
paxChunks.push(buildPaxRecord('size', String(size)));
|
|
90
|
+
const paxData = Buffer.concat(paxChunks);
|
|
91
|
+
const paxHeader = encodeTarHeader({
|
|
92
|
+
name: `PaxHeaders.0/${norm}`.slice(0, 99),
|
|
93
|
+
size: paxData.length,
|
|
94
|
+
mtime: mtimeMs,
|
|
95
|
+
type: 'x',
|
|
96
|
+
mode: 0o644,
|
|
97
|
+
});
|
|
98
|
+
blocks.push(paxHeader, paxData);
|
|
99
|
+
const pad = (BLOCK_SIZE - (paxData.length % BLOCK_SIZE)) % BLOCK_SIZE;
|
|
100
|
+
if (pad)
|
|
101
|
+
blocks.push(ZERO_BLOCK.subarray(0, pad));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const fallbackName = isAscii ? norm.slice(0, 99) : Buffer.from(norm, 'utf8').toString('latin1').slice(0, 99);
|
|
105
|
+
blocks.push(encodeTarHeader({
|
|
106
|
+
name: fallbackName,
|
|
107
|
+
size,
|
|
108
|
+
mtime: mtimeMs,
|
|
109
|
+
type: '0',
|
|
110
|
+
mode: 0o644,
|
|
111
|
+
}));
|
|
112
|
+
return Buffer.concat(blocks);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Вычислить точный размер `.tar` потока в байтах (для `Content-Length`).
|
|
117
|
+
*/
|
|
118
|
+
export function calculateTarSize(entries = []) {
|
|
119
|
+
let total = 0;
|
|
120
|
+
for (const entry of entries) {
|
|
121
|
+
const size = entry.buffer ? entry.buffer.length : (Number(entry.size) || 0);
|
|
122
|
+
const hdr = buildEntryHeaders(entry.relPath, size, entry.mtimeMs || Date.now());
|
|
123
|
+
total += hdr.length + size + ((BLOCK_SIZE - (size % BLOCK_SIZE)) % BLOCK_SIZE);
|
|
124
|
+
}
|
|
125
|
+
total += BLOCK_SIZE * 2; // EOF
|
|
126
|
+
return total;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function writeChunkWithBackpressure(stream, chunk, signal) {
|
|
130
|
+
if (signal?.aborted)
|
|
131
|
+
throw new Error('Операция отменена');
|
|
132
|
+
if (!stream.write(chunk)) {
|
|
133
|
+
await new Promise((resolve, reject) => {
|
|
134
|
+
const onDrain = () => {
|
|
135
|
+
cleanup();
|
|
136
|
+
resolve();
|
|
137
|
+
};
|
|
138
|
+
const onErr = (err) => {
|
|
139
|
+
cleanup();
|
|
140
|
+
reject(err);
|
|
141
|
+
};
|
|
142
|
+
const onAbort = () => {
|
|
143
|
+
cleanup();
|
|
144
|
+
reject(new Error('Операция отменена'));
|
|
145
|
+
};
|
|
146
|
+
const cleanup = () => {
|
|
147
|
+
stream.off('drain', onDrain);
|
|
148
|
+
stream.off('error', onErr);
|
|
149
|
+
stream.off('close', onErr);
|
|
150
|
+
signal?.removeEventListener('abort', onAbort);
|
|
151
|
+
};
|
|
152
|
+
stream.once('drain', onDrain);
|
|
153
|
+
stream.once('error', onErr);
|
|
154
|
+
stream.once('close', onErr);
|
|
155
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Создать потоковый `Readable` (`.tar` без сжатия) для списка `{ relPath, fullPath?, buffer?, size?, mtimeMs? }`.
|
|
162
|
+
*/
|
|
163
|
+
export function createTarExportStream(entries = [], { onProgress, signal } = {}) {
|
|
164
|
+
const out = new PassThrough({ highWaterMark: 1024 * 1024 });
|
|
165
|
+
out.contentLength = calculateTarSize(entries);
|
|
166
|
+
|
|
167
|
+
(async () => {
|
|
168
|
+
try {
|
|
169
|
+
let writtenDataBytes = 0;
|
|
170
|
+
for (const entry of entries) {
|
|
171
|
+
if (signal?.aborted)
|
|
172
|
+
throw new Error('Операция отменена');
|
|
173
|
+
const size = entry.buffer ? entry.buffer.length : (Number(entry.size) || 0);
|
|
174
|
+
const hdr = buildEntryHeaders(entry.relPath, size, entry.mtimeMs || Date.now());
|
|
175
|
+
await writeChunkWithBackpressure(out, hdr, signal);
|
|
176
|
+
|
|
177
|
+
if (entry.buffer) {
|
|
178
|
+
await writeChunkWithBackpressure(out, entry.buffer, signal);
|
|
179
|
+
writtenDataBytes += entry.buffer.length;
|
|
180
|
+
onProgress?.({ file: entry.relPath, bytesDelta: entry.buffer.length, totalWritten: writtenDataBytes });
|
|
181
|
+
}
|
|
182
|
+
else if (size > 0) {
|
|
183
|
+
const rs = fs.createReadStream(entry.fullPath, { highWaterMark: 1024 * 1024 });
|
|
184
|
+
let fileBytes = 0;
|
|
185
|
+
try {
|
|
186
|
+
for await (const chunk of rs) {
|
|
187
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
188
|
+
fileBytes += buf.length;
|
|
189
|
+
await writeChunkWithBackpressure(out, buf, signal);
|
|
190
|
+
writtenDataBytes += buf.length;
|
|
191
|
+
onProgress?.({ file: entry.relPath, bytesDelta: buf.length, totalWritten: writtenDataBytes });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
finally {
|
|
195
|
+
rs.destroy();
|
|
196
|
+
}
|
|
197
|
+
if (fileBytes !== size)
|
|
198
|
+
throw new Error(`Размер файла «${entry.relPath}» изменился во время упаковки`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const pad = (BLOCK_SIZE - (size % BLOCK_SIZE)) % BLOCK_SIZE;
|
|
202
|
+
if (pad)
|
|
203
|
+
await writeChunkWithBackpressure(out, ZERO_BLOCK.subarray(0, pad), signal);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
await writeChunkWithBackpressure(out, ZERO_BLOCK, signal);
|
|
207
|
+
await writeChunkWithBackpressure(out, ZERO_BLOCK, signal);
|
|
208
|
+
out.end();
|
|
209
|
+
}
|
|
210
|
+
catch (err) {
|
|
211
|
+
out.destroy(err);
|
|
212
|
+
}
|
|
213
|
+
})();
|
|
214
|
+
|
|
215
|
+
return out;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function sanitizeTarRelPath(rawPath) {
|
|
219
|
+
const cleaned = String(rawPath || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
220
|
+
if (!cleaned || cleaned.startsWith('/') || /^[A-Za-z]:/.test(cleaned) || cleaned.includes('\0'))
|
|
221
|
+
return '';
|
|
222
|
+
const parts = cleaned.split('/').filter(Boolean);
|
|
223
|
+
if (!parts.length || parts.some(p => p === '.' || p === '..'))
|
|
224
|
+
return '';
|
|
225
|
+
return parts.join('/');
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function parseOctalField(buf, start, end) {
|
|
229
|
+
const raw = buf.subarray(start, end).toString('ascii').replace(/\0.*$/, '').trim();
|
|
230
|
+
if (!raw)
|
|
231
|
+
return 0;
|
|
232
|
+
const val = parseInt(raw, 8);
|
|
233
|
+
return Number.isFinite(val) ? val : 0;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function isAllZeroBlock(buf) {
|
|
237
|
+
for (let i = 0; i < buf.length; i++) {
|
|
238
|
+
if (buf[i] !== 0)
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function parseUstarHeader(block) {
|
|
245
|
+
const rawName = block.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
|
|
246
|
+
const prefix = block.subarray(345, 500).toString('utf8').replace(/\0.*$/, '');
|
|
247
|
+
const typeFlag = String.fromCharCode(block[156] || 48);
|
|
248
|
+
const size = parseOctalField(block, 124, 136);
|
|
249
|
+
const name = prefix ? `${prefix}/${rawName}` : rawName;
|
|
250
|
+
return { name, typeFlag, size };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Потоково распаковать `.tar` из `Readable` в `destDir` с подсчётом SHA-256 и без удержания файлов в памяти.
|
|
255
|
+
*/
|
|
256
|
+
export async function extractTarStream(readable, destDir, { onProgress, signal } = {}) {
|
|
257
|
+
await fsp.mkdir(destDir, { recursive: true });
|
|
258
|
+
const extractedFiles = [];
|
|
259
|
+
|
|
260
|
+
let state = 'header'; // 'header' | 'meta' | 'file' | 'pad'
|
|
261
|
+
let headerChunks = [];
|
|
262
|
+
let headerLen = 0;
|
|
263
|
+
|
|
264
|
+
let metaBufs = [];
|
|
265
|
+
let metaRemaining = 0;
|
|
266
|
+
let metaType = '';
|
|
267
|
+
let paxNext = {};
|
|
268
|
+
let paxGlobal = {};
|
|
269
|
+
let gnuLongName = '';
|
|
270
|
+
|
|
271
|
+
let currentFile = null;
|
|
272
|
+
let padRemaining = 0;
|
|
273
|
+
let totalReadBytes = 0;
|
|
274
|
+
let zeroBlocks = 0;
|
|
275
|
+
let eof = false;
|
|
276
|
+
|
|
277
|
+
const closeCurrentFile = async () => {
|
|
278
|
+
if (!currentFile)
|
|
279
|
+
return;
|
|
280
|
+
const f = currentFile;
|
|
281
|
+
currentFile = null;
|
|
282
|
+
await new Promise((resolve, reject) => {
|
|
283
|
+
f.stream.end();
|
|
284
|
+
f.stream.once('finish', resolve);
|
|
285
|
+
f.stream.once('error', reject);
|
|
286
|
+
});
|
|
287
|
+
extractedFiles.push({
|
|
288
|
+
relPath: f.relPath,
|
|
289
|
+
size: f.size,
|
|
290
|
+
sha256: f.hash.digest('hex'),
|
|
291
|
+
});
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
const cleanupOnError = async () => {
|
|
295
|
+
if (currentFile?.stream) {
|
|
296
|
+
try { currentFile.stream.destroy(); } catch { /* ignore */ }
|
|
297
|
+
currentFile = null;
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
try {
|
|
302
|
+
for await (const rawChunk of readable) {
|
|
303
|
+
if (signal?.aborted)
|
|
304
|
+
throw new Error('Операция отменена пользователем');
|
|
305
|
+
const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
|
|
306
|
+
totalReadBytes += chunk.length;
|
|
307
|
+
if (eof)
|
|
308
|
+
continue;
|
|
309
|
+
let offset = 0;
|
|
310
|
+
|
|
311
|
+
while (offset < chunk.length) {
|
|
312
|
+
if (signal?.aborted)
|
|
313
|
+
throw new Error('Операция отменена пользователем');
|
|
314
|
+
|
|
315
|
+
if (state === 'header') {
|
|
316
|
+
const need = BLOCK_SIZE - headerLen;
|
|
317
|
+
const take = Math.min(need, chunk.length - offset);
|
|
318
|
+
headerChunks.push(chunk.subarray(offset, offset + take));
|
|
319
|
+
headerLen += take;
|
|
320
|
+
offset += take;
|
|
321
|
+
if (headerLen < BLOCK_SIZE)
|
|
322
|
+
continue;
|
|
323
|
+
|
|
324
|
+
const block = headerChunks.length === 1 ? headerChunks[0] : Buffer.concat(headerChunks);
|
|
325
|
+
headerChunks = [];
|
|
326
|
+
headerLen = 0;
|
|
327
|
+
|
|
328
|
+
if (isAllZeroBlock(block)) {
|
|
329
|
+
zeroBlocks++;
|
|
330
|
+
if (zeroBlocks >= 2) {
|
|
331
|
+
eof = true;
|
|
332
|
+
break;
|
|
333
|
+
}
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
zeroBlocks = 0;
|
|
337
|
+
|
|
338
|
+
const hdr = parseUstarHeader(block);
|
|
339
|
+
if (hdr.typeFlag === 'x' || hdr.typeFlag === 'g' || hdr.typeFlag === 'L') {
|
|
340
|
+
metaType = hdr.typeFlag;
|
|
341
|
+
metaRemaining = hdr.size;
|
|
342
|
+
metaBufs = [];
|
|
343
|
+
padRemaining = (BLOCK_SIZE - (hdr.size % BLOCK_SIZE)) % BLOCK_SIZE;
|
|
344
|
+
if (metaRemaining === 0) {
|
|
345
|
+
state = padRemaining ? 'pad' : 'header';
|
|
346
|
+
}
|
|
347
|
+
else {
|
|
348
|
+
state = 'meta';
|
|
349
|
+
}
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const mergedPax = { ...paxGlobal, ...paxNext };
|
|
354
|
+
const resolvedName = mergedPax.path || gnuLongName || hdr.name;
|
|
355
|
+
const resolvedSize = mergedPax.size !== undefined ? Number(mergedPax.size) : hdr.size;
|
|
356
|
+
paxNext = {};
|
|
357
|
+
gnuLongName = '';
|
|
358
|
+
|
|
359
|
+
if (hdr.typeFlag === '5') {
|
|
360
|
+
const relDir = sanitizeTarRelPath(resolvedName.replace(/\/+$/, ''));
|
|
361
|
+
if (relDir) {
|
|
362
|
+
const absDir = path.resolve(destDir, relDir);
|
|
363
|
+
if (absDir.startsWith(path.resolve(destDir) + path.sep))
|
|
364
|
+
await fsp.mkdir(absDir, { recursive: true });
|
|
365
|
+
}
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (hdr.typeFlag !== '0' && hdr.typeFlag !== '\0') {
|
|
370
|
+
// Неизвестный или ссылочный тип: безопасно пропускаем данные, файлы не создаём
|
|
371
|
+
const skipPad = (BLOCK_SIZE - (resolvedSize % BLOCK_SIZE)) % BLOCK_SIZE;
|
|
372
|
+
padRemaining = resolvedSize + skipPad;
|
|
373
|
+
state = padRemaining > 0 ? 'pad' : 'header';
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const relPath = sanitizeTarRelPath(resolvedName);
|
|
378
|
+
if (!relPath)
|
|
379
|
+
throw new Error(`Недопустимый путь в архиве: ${resolvedName}`);
|
|
380
|
+
|
|
381
|
+
const absDest = path.resolve(destDir, relPath);
|
|
382
|
+
const absRoot = path.resolve(destDir);
|
|
383
|
+
if (absDest !== absRoot && !absDest.startsWith(absRoot + path.sep))
|
|
384
|
+
throw new Error(`Запрещённый путь вне каталога распаковки: ${relPath}`);
|
|
385
|
+
|
|
386
|
+
await fsp.mkdir(path.dirname(absDest), { recursive: true });
|
|
387
|
+
const ws = fs.createWriteStream(absDest, { highWaterMark: 1024 * 1024 });
|
|
388
|
+
currentFile = {
|
|
389
|
+
relPath,
|
|
390
|
+
size: resolvedSize,
|
|
391
|
+
remaining: resolvedSize,
|
|
392
|
+
stream: ws,
|
|
393
|
+
hash: crypto.createHash('sha256'),
|
|
394
|
+
};
|
|
395
|
+
padRemaining = (BLOCK_SIZE - (resolvedSize % BLOCK_SIZE)) % BLOCK_SIZE;
|
|
396
|
+
|
|
397
|
+
if (resolvedSize === 0) {
|
|
398
|
+
await closeCurrentFile();
|
|
399
|
+
state = padRemaining ? 'pad' : 'header';
|
|
400
|
+
}
|
|
401
|
+
else {
|
|
402
|
+
state = 'file';
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
else if (state === 'meta') {
|
|
406
|
+
const take = Math.min(metaRemaining, chunk.length - offset);
|
|
407
|
+
metaBufs.push(chunk.subarray(offset, offset + take));
|
|
408
|
+
metaRemaining -= take;
|
|
409
|
+
offset += take;
|
|
410
|
+
if (metaRemaining === 0) {
|
|
411
|
+
const fullMeta = Buffer.concat(metaBufs);
|
|
412
|
+
metaBufs = [];
|
|
413
|
+
if (metaType === 'x')
|
|
414
|
+
paxNext = { ...paxNext, ...parsePaxBuffer(fullMeta) };
|
|
415
|
+
else if (metaType === 'g')
|
|
416
|
+
paxGlobal = { ...paxGlobal, ...parsePaxBuffer(fullMeta) };
|
|
417
|
+
else if (metaType === 'L')
|
|
418
|
+
gnuLongName = fullMeta.toString('utf8').replace(/\0.*$/, '');
|
|
419
|
+
state = padRemaining ? 'pad' : 'header';
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
else if (state === 'file') {
|
|
423
|
+
const take = Math.min(currentFile.remaining, chunk.length - offset);
|
|
424
|
+
const slice = chunk.subarray(offset, offset + take);
|
|
425
|
+
offset += take;
|
|
426
|
+
currentFile.remaining -= take;
|
|
427
|
+
currentFile.hash.update(slice);
|
|
428
|
+
if (!currentFile.stream.write(slice)) {
|
|
429
|
+
await new Promise((resolve, reject) => {
|
|
430
|
+
currentFile.stream.once('drain', resolve);
|
|
431
|
+
currentFile.stream.once('error', reject);
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
onProgress?.({ file: currentFile.relPath, totalReadBytes });
|
|
435
|
+
if (currentFile.remaining === 0) {
|
|
436
|
+
await closeCurrentFile();
|
|
437
|
+
state = padRemaining ? 'pad' : 'header';
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
else if (state === 'pad') {
|
|
441
|
+
const take = Math.min(padRemaining, chunk.length - offset);
|
|
442
|
+
padRemaining -= take;
|
|
443
|
+
offset += take;
|
|
444
|
+
if (padRemaining === 0)
|
|
445
|
+
state = 'header';
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (currentFile)
|
|
451
|
+
throw new Error(`Архив .tar оборван на файле «${currentFile.relPath}»`);
|
|
452
|
+
return { files: extractedFiles, totalReadBytes };
|
|
453
|
+
}
|
|
454
|
+
catch (err) {
|
|
455
|
+
await cleanupOnError();
|
|
456
|
+
throw err;
|
|
457
|
+
}
|
|
458
|
+
}
|