@openartifactsai/server-sdk 0.0.0-stage → 0.23.0-rc.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.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +47 -0
- package/package.json +124 -4
- package/src/child.d.ts +37 -0
- package/src/child.js +64 -0
- package/src/connectors/connectors.d.ts +101 -0
- package/src/connectors/connectors.js +256 -0
- package/src/connectors/daemon-connectors.d.ts +34 -0
- package/src/connectors/daemon-connectors.js +73 -0
- package/src/connectors/index.d.ts +7 -0
- package/src/connectors/index.js +7 -0
- package/src/connectors/mcp-client.d.ts +157 -0
- package/src/connectors/mcp-client.js +483 -0
- package/src/daemon.d.ts +119 -0
- package/src/daemon.js +301 -0
- package/src/frame/access.d.ts +69 -0
- package/src/frame/access.js +168 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +58 -0
- package/src/frame/client/imports.d.ts +6 -0
- package/src/frame/client/imports.js +112 -0
- package/src/frame/client/mcp-shell.js +345 -0
- package/src/frame/client/mcp.js +253 -0
- package/src/frame/client/runtime.js +1363 -0
- package/src/frame/client/sample.js +762 -0
- package/src/frame/client/shell.css +51 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +1417 -0
- package/src/frame/comments.d.ts +102 -0
- package/src/frame/comments.js +379 -0
- package/src/frame/core.d.ts +313 -0
- package/src/frame/core.js +1757 -0
- package/src/frame/db.d.ts +162 -0
- package/src/frame/db.js +604 -0
- package/src/frame/declaration.d.ts +30 -0
- package/src/frame/declaration.js +60 -0
- package/src/frame/env.d.ts +262 -0
- package/src/frame/env.js +13 -0
- package/src/frame/files.d.ts +130 -0
- package/src/frame/files.js +472 -0
- package/src/frame/index.d.ts +35 -0
- package/src/frame/index.js +33 -0
- package/src/frame/local.d.ts +126 -0
- package/src/frame/local.js +612 -0
- package/src/frame/mcp-relay.d.ts +79 -0
- package/src/frame/mcp-relay.js +191 -0
- package/src/frame/page-api.d.ts +48 -0
- package/src/frame/page-api.js +1 -0
- package/src/frame/page-comments.d.ts +109 -0
- package/src/frame/page-comments.js +1 -0
- package/src/frame/page-db.d.ts +88 -0
- package/src/frame/page-db.js +1 -0
- package/src/frame/page-imports.d.ts +2 -0
- package/src/frame/page-imports.js +2 -0
- package/src/frame/page-services.d.ts +124 -0
- package/src/frame/page-services.js +1 -0
- package/src/frame/page-values.d.ts +90 -0
- package/src/frame/page-values.js +1 -0
- package/src/frame/sample-relay.d.ts +42 -0
- package/src/frame/sample-relay.js +186 -0
- package/src/frame/snapshot-action.d.ts +18 -0
- package/src/frame/snapshot-action.js +82 -0
- package/src/frame/wire.d.ts +198 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +17 -0
- package/src/index.js +17 -0
- package/src/lan.d.ts +75 -0
- package/src/lan.js +200 -0
- package/src/legacy-env.d.ts +7 -0
- package/src/legacy-env.js +14 -0
- package/src/serve.d.ts +375 -0
- package/src/serve.js +811 -0
- package/src/snapshot.d.ts +41 -0
- package/src/snapshot.js +224 -0
- package/src/type-package.d.ts +48 -0
- package/src/type-package.js +114 -0
- package/src/ws.d.ts +50 -0
- package/src/ws.js +203 -0
- package/src/zip.d.ts +197 -0
- package/src/zip.js +662 -0
package/src/zip.js
ADDED
|
@@ -0,0 +1,662 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zip files, the plain kind (no Zip64), with Node built-ins only: reading one (the central directory, an entry's
|
|
3
|
+
* bytes), writing one (an artifact folder's archive, a type package), and unpacking one that may come from anyone
|
|
4
|
+
* into a folder, with every rule checked before a byte is written. Shared by the type server (`archive`, imports),
|
|
5
|
+
* frame-host (`/__open-artifacts/archive`) and the daemon (`types pack`, `types install`, `import`, the archives of
|
|
6
|
+
* static types), so one archive shape and one set of path rules hold everywhere.
|
|
7
|
+
*
|
|
8
|
+
* The archive of an artifact folder holds one folder, named as the artifact folder is, with what makes the artifact:
|
|
9
|
+
* `project/` (or `db/`), `_blobs/`, `comments.json`, `history/` and `.artifact.json`. Left out is what belongs to this
|
|
10
|
+
* computer or to nobody: the agent channel (`_agent/`: inbox, waiting, view context), dot files (a server's state and
|
|
11
|
+
* log, share links, temp files of atomic writes), `node_modules`, `.git` and the OS's `.DS_Store` / `Thumbs.db`.
|
|
12
|
+
* Symbolic links are not followed. At most 65 535 files and 4 GiB, checked before the first byte goes out. Names are
|
|
13
|
+
* UTF-8 (flag bit 11), Unix permissions ride in the external attributes, and each file is deflated unless it is a
|
|
14
|
+
* format that is compressed already or deflate would not shrink it.
|
|
15
|
+
*/
|
|
16
|
+
import { randomBytes } from 'node:crypto';
|
|
17
|
+
import { constants } from 'node:fs';
|
|
18
|
+
import { lstat, mkdir, open, readdir, readFile, rename, rm, stat } from 'node:fs/promises';
|
|
19
|
+
import { basename, dirname, extname, join, resolve, sep } from 'node:path';
|
|
20
|
+
import { promisify } from 'node:util';
|
|
21
|
+
import { deflateRaw as deflateRawCallback, inflateRaw as inflateRawCallback, inflateRawSync } from 'node:zlib';
|
|
22
|
+
/* -------------------------------------------------------------------------- */
|
|
23
|
+
/* Reading */
|
|
24
|
+
/* -------------------------------------------------------------------------- */
|
|
25
|
+
/** A file that is not a zip (`not_zip`), or a zip whose parts do not hold together (`damaged`). */
|
|
26
|
+
export class ZipError extends Error {
|
|
27
|
+
code;
|
|
28
|
+
constructor(code, message) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.code = code;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const END_SIGNATURE = 0x06054b50;
|
|
34
|
+
const CENTRAL_SIGNATURE = 0x02014b50;
|
|
35
|
+
const LOCAL_SIGNATURE = 0x04034b50;
|
|
36
|
+
function view(bytes) {
|
|
37
|
+
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Where the end of central directory record starts, or -1. It is looked for where it can be: in the last 22 bytes
|
|
41
|
+
* plus the longest comment (64 KiB). The record whose comment runs exactly to the end of the file is the one, so the
|
|
42
|
+
* signature's four bytes inside a comment are passed over. A file with bytes after its zip (a newline a transfer
|
|
43
|
+
* added, padding) has no such record: there the last record whose comment fits in what follows it is taken, as the
|
|
44
|
+
* common unzip tools do.
|
|
45
|
+
*/
|
|
46
|
+
function endRecordAt(zip) {
|
|
47
|
+
const first = Math.max(0, zip.length - 22 - 0xffff);
|
|
48
|
+
let loose = -1;
|
|
49
|
+
for (let at = zip.length - 22; at >= first; at--) {
|
|
50
|
+
if (zip.readUInt32LE(at) !== END_SIGNATURE)
|
|
51
|
+
continue;
|
|
52
|
+
const after = zip.length - at - 22;
|
|
53
|
+
const comment = zip.readUInt16LE(at + 20);
|
|
54
|
+
if (comment === after)
|
|
55
|
+
return at;
|
|
56
|
+
if (comment < after && loose < 0)
|
|
57
|
+
loose = at;
|
|
58
|
+
}
|
|
59
|
+
return loose;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The central directory. Reading stops at the first record that is not one (the end record's count is in
|
|
63
|
+
* `declared`, so a strict caller can see a short directory). Throws `not_zip` when there is no end record.
|
|
64
|
+
*/
|
|
65
|
+
export function zipEntries(bytes) {
|
|
66
|
+
const zip = view(bytes);
|
|
67
|
+
const end = endRecordAt(zip);
|
|
68
|
+
if (end < 0)
|
|
69
|
+
throw new ZipError('not_zip', 'This file is not a zip: it has no end of central directory record.');
|
|
70
|
+
const declared = zip.readUInt16LE(end + 10);
|
|
71
|
+
const directoryOffset = zip.readUInt32LE(end + 16);
|
|
72
|
+
const entries = [];
|
|
73
|
+
let at = directoryOffset;
|
|
74
|
+
for (let index = 0; index < declared && at + 46 <= zip.length && zip.readUInt32LE(at) === CENTRAL_SIGNATURE; index++) {
|
|
75
|
+
const nameLength = zip.readUInt16LE(at + 28);
|
|
76
|
+
entries.push({
|
|
77
|
+
name: zip.toString('utf8', at + 46, at + 46 + nameLength),
|
|
78
|
+
madeBy: zip.readUInt16LE(at + 4),
|
|
79
|
+
flags: zip.readUInt16LE(at + 8),
|
|
80
|
+
method: zip.readUInt16LE(at + 10),
|
|
81
|
+
crc: zip.readUInt32LE(at + 16),
|
|
82
|
+
packedSize: zip.readUInt32LE(at + 20),
|
|
83
|
+
size: zip.readUInt32LE(at + 24),
|
|
84
|
+
externalAttributes: zip.readUInt32LE(at + 38),
|
|
85
|
+
localOffset: zip.readUInt32LE(at + 42),
|
|
86
|
+
});
|
|
87
|
+
at += 46 + nameLength + zip.readUInt16LE(at + 30) + zip.readUInt16LE(at + 32);
|
|
88
|
+
}
|
|
89
|
+
return { entries, declared, directoryOffset };
|
|
90
|
+
}
|
|
91
|
+
/** Where an entry's packed data sits, read from its local header: the data and the name the local header gives. Throws `damaged` when the local header is missing. */
|
|
92
|
+
export function entryBytes(bytes, entry) {
|
|
93
|
+
const zip = view(bytes);
|
|
94
|
+
const local = entry.localOffset;
|
|
95
|
+
if (local + 30 > zip.length || zip.readUInt32LE(local) !== LOCAL_SIGNATURE)
|
|
96
|
+
throw new ZipError('damaged', `The zip is damaged: the data of ${entry.name} is missing.`);
|
|
97
|
+
const nameLength = zip.readUInt16LE(local + 26);
|
|
98
|
+
const start = local + 30 + nameLength + zip.readUInt16LE(local + 28);
|
|
99
|
+
if (start + entry.packedSize > zip.length)
|
|
100
|
+
throw new ZipError('damaged', `The zip is damaged: the data of ${entry.name} runs past its end.`);
|
|
101
|
+
return {
|
|
102
|
+
data: zip.subarray(start, start + entry.packedSize),
|
|
103
|
+
start,
|
|
104
|
+
localName: zip.toString('utf8', local + 30, local + 30 + nameLength),
|
|
105
|
+
localMethod: zip.readUInt16LE(local + 8),
|
|
106
|
+
localFlags: zip.readUInt16LE(local + 6),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const inflateRaw = promisify(inflateRawCallback);
|
|
110
|
+
/**
|
|
111
|
+
* An entry's bytes, unpacked: stored data is copied, anything else is inflated, never past `maxBytes`
|
|
112
|
+
* (throws a `RangeError` when stored or inflated data would grow past it).
|
|
113
|
+
*/
|
|
114
|
+
export async function unpackEntry(bytes, entry, maxBytes) {
|
|
115
|
+
const { data } = entryBytes(bytes, entry);
|
|
116
|
+
if (entry.method === 0) {
|
|
117
|
+
if (data.length > maxBytes)
|
|
118
|
+
throw new RangeError(`Stored entry ${entry.name} is ${data.length} bytes, more than ${maxBytes}.`);
|
|
119
|
+
return Buffer.from(data);
|
|
120
|
+
}
|
|
121
|
+
return inflateRaw(data, { maxOutputLength: Math.max(1, maxBytes) });
|
|
122
|
+
}
|
|
123
|
+
/** {@link unpackEntry}, synchronously. */
|
|
124
|
+
export function unpackEntrySync(bytes, entry, maxBytes) {
|
|
125
|
+
const { data } = entryBytes(bytes, entry);
|
|
126
|
+
if (entry.method === 0) {
|
|
127
|
+
if (data.length > maxBytes)
|
|
128
|
+
throw new RangeError(`Stored entry ${entry.name} is ${data.length} bytes, more than ${maxBytes}.`);
|
|
129
|
+
return Buffer.from(data);
|
|
130
|
+
}
|
|
131
|
+
return inflateRawSync(data, { maxOutputLength: Math.max(1, maxBytes) });
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Every name of the zip with a reader of its bytes, unpacked on demand and never past `maxEntryBytes`. A name given
|
|
135
|
+
* twice keeps its last entry. Throws `not_zip`; a reader throws `damaged` when its entry's data is missing.
|
|
136
|
+
*/
|
|
137
|
+
export function readZip(bytes, maxEntryBytes) {
|
|
138
|
+
const entries = new Map();
|
|
139
|
+
for (const entry of zipEntries(bytes).entries)
|
|
140
|
+
entries.set(entry.name, () => unpackEntrySync(bytes, entry, maxEntryBytes));
|
|
141
|
+
return entries;
|
|
142
|
+
}
|
|
143
|
+
/* -------------------------------------------------------------------------- */
|
|
144
|
+
/* An artifact folder's archive */
|
|
145
|
+
/* -------------------------------------------------------------------------- */
|
|
146
|
+
/** Hidden paths carrying portable artifact data, relative to the archive root. */
|
|
147
|
+
const KEPT_DOT_FILES = new Set(['.artifact.json', '.gitignore', 'doc/.sessions.json', 'doc/.people.json', 'doc/tabs/.deleted']);
|
|
148
|
+
/** Never in the zip, at any depth. */
|
|
149
|
+
const JUNK = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini', '.git', 'node_modules']);
|
|
150
|
+
/** Never in the zip, at the folder's top. */
|
|
151
|
+
const LOCAL_DIRS = new Set(['_agent']);
|
|
152
|
+
/** An atomic write's temp file. */
|
|
153
|
+
const isTemp = (name) => name.endsWith('.tmp') || name.startsWith('.tmp-');
|
|
154
|
+
/**
|
|
155
|
+
* Whether the archive carries `name`, found at `path` (its path under the artifact folder, forward slashes) in the
|
|
156
|
+
* folder `parent` (`''` at the top). A path is in the archive when every step down to it is.
|
|
157
|
+
*/
|
|
158
|
+
function keepsStep(parent, name, path) {
|
|
159
|
+
if (JUNK.has(name) || isTemp(name))
|
|
160
|
+
return false;
|
|
161
|
+
if (name.startsWith('.') && !KEPT_DOT_FILES.has(path))
|
|
162
|
+
return false;
|
|
163
|
+
return !(parent === '' && LOCAL_DIRS.has(name));
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Whether a path under the artifact folder (forward slashes, no leading slash) is one {@link archiveEntries} would
|
|
167
|
+
* put in the zip, by name alone. The export and the import share it, so what one leaves out the other refuses.
|
|
168
|
+
*/
|
|
169
|
+
export function archiveKeeps(path) {
|
|
170
|
+
const steps = path.split('/');
|
|
171
|
+
let parent = '';
|
|
172
|
+
for (const name of steps) {
|
|
173
|
+
const inner = parent ? `${parent}/${name}` : name;
|
|
174
|
+
if (!keepsStep(parent, name, inner))
|
|
175
|
+
return false;
|
|
176
|
+
parent = inner;
|
|
177
|
+
}
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
/** Formats that are compressed already: stored as they are. */
|
|
181
|
+
const STORED = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.heic', '.mp4', '.m4v', '.mov', '.webm', '.mp3', '.m4a', '.aac', '.ogg', '.opus', '.flac', '.woff', '.woff2', '.zip', '.gz', '.br', '.zst', '.7z']);
|
|
182
|
+
const MAX_ENTRIES = 0xffff;
|
|
183
|
+
const MAX_BYTES = 0xffffffff;
|
|
184
|
+
/** A folder over plain zip's limits. */
|
|
185
|
+
export class ArchiveTooLarge extends Error {
|
|
186
|
+
code = 'TOO_LARGE';
|
|
187
|
+
}
|
|
188
|
+
/** The files to zip, sorted by path. `skip`: absolute paths to leave out too (the zip itself, written inside the folder). */
|
|
189
|
+
export async function archiveEntries(root, skip = []) {
|
|
190
|
+
const top = resolve(root);
|
|
191
|
+
const folder = basename(top) || 'artifact';
|
|
192
|
+
const skipped = new Set(skip.map((file) => resolve(file)));
|
|
193
|
+
const entries = [];
|
|
194
|
+
const walk = async (dir, rel) => {
|
|
195
|
+
let names;
|
|
196
|
+
try {
|
|
197
|
+
names = await readdir(dir, { withFileTypes: true });
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (rel && error.code === 'ENOENT')
|
|
201
|
+
return; // removed meanwhile
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
for (const dirent of names.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
|
|
205
|
+
const name = dirent.name;
|
|
206
|
+
const inner = rel ? `${rel}/${name}` : name;
|
|
207
|
+
if (!keepsStep(rel, name, inner))
|
|
208
|
+
continue;
|
|
209
|
+
const file = join(dir, name);
|
|
210
|
+
if (skipped.has(file))
|
|
211
|
+
continue;
|
|
212
|
+
if (dirent.isDirectory())
|
|
213
|
+
await walk(file, inner);
|
|
214
|
+
else if (dirent.isFile()) {
|
|
215
|
+
const info = await stat(file).catch(() => null);
|
|
216
|
+
if (info?.isFile())
|
|
217
|
+
entries.push({ name: `${folder}/${inner}`, file, size: info.size, mode: info.mode & 0o777, mtime: info.mtime });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
await walk(top, '');
|
|
222
|
+
if (entries.length > MAX_ENTRIES)
|
|
223
|
+
throw new ArchiveTooLarge(`The folder holds ${entries.length} files, more than a zip holds (${MAX_ENTRIES}); copy the folder itself instead.`);
|
|
224
|
+
const bound = entries.reduce((sum, entry) => sum + entry.size + 2 * (46 + Buffer.byteLength(entry.name)), 22);
|
|
225
|
+
if (bound > MAX_BYTES)
|
|
226
|
+
throw new ArchiveTooLarge(`The folder holds ${(bound / 2 ** 30).toFixed(1)} GiB, more than a zip holds (4 GiB); copy the folder itself instead.`);
|
|
227
|
+
return entries;
|
|
228
|
+
}
|
|
229
|
+
/* -------------------------------------------------------------------------- */
|
|
230
|
+
/* The zip format */
|
|
231
|
+
/* -------------------------------------------------------------------------- */
|
|
232
|
+
const CRC_TABLE = (() => {
|
|
233
|
+
const table = new Uint32Array(256);
|
|
234
|
+
for (let n = 0; n < 256; n++) {
|
|
235
|
+
let c = n;
|
|
236
|
+
for (let k = 0; k < 8; k++)
|
|
237
|
+
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
238
|
+
table[n] = c >>> 0;
|
|
239
|
+
}
|
|
240
|
+
return table;
|
|
241
|
+
})();
|
|
242
|
+
/** CRC-32 of bytes. */
|
|
243
|
+
export function crc32(bytes) {
|
|
244
|
+
let crc = 0xffffffff;
|
|
245
|
+
for (let i = 0; i < bytes.length; i++)
|
|
246
|
+
crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
|
|
247
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
248
|
+
}
|
|
249
|
+
/** MS-DOS time and date, local time; the format starts in 1980 and ends in 2107. */
|
|
250
|
+
function dosTime(date) {
|
|
251
|
+
const year = date.getFullYear();
|
|
252
|
+
if (year < 1980)
|
|
253
|
+
return { time: 0, date: (1 << 5) | 1 };
|
|
254
|
+
if (year > 2107)
|
|
255
|
+
return { time: (23 << 11) | (59 << 5) | 29, date: (127 << 9) | (12 << 5) | 31 };
|
|
256
|
+
return {
|
|
257
|
+
time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1),
|
|
258
|
+
date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
const deflateRaw = promisify(deflateRawCallback);
|
|
262
|
+
const UTF8 = 1 << 11;
|
|
263
|
+
/**
|
|
264
|
+
* Writes the zip of `entries` through `write`, one file at a time: its local
|
|
265
|
+
* header and data, then the central directory. A file gone since the listing
|
|
266
|
+
* is left out. Resolves with the number of bytes written.
|
|
267
|
+
*/
|
|
268
|
+
export async function writeZip(entries, write) {
|
|
269
|
+
const central = [];
|
|
270
|
+
let offset = 0;
|
|
271
|
+
let files = 0;
|
|
272
|
+
const put = async (chunk) => {
|
|
273
|
+
await write(chunk);
|
|
274
|
+
offset += chunk.length;
|
|
275
|
+
};
|
|
276
|
+
for (const entry of entries) {
|
|
277
|
+
let data;
|
|
278
|
+
try {
|
|
279
|
+
data = await readFile(entry.file);
|
|
280
|
+
}
|
|
281
|
+
catch (error) {
|
|
282
|
+
if (error.code === 'ENOENT')
|
|
283
|
+
continue;
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
const crc = crc32(data);
|
|
287
|
+
let method = 0;
|
|
288
|
+
let body = data;
|
|
289
|
+
if (data.length > 0 && !STORED.has(extname(entry.name).toLowerCase())) {
|
|
290
|
+
const deflated = await deflateRaw(data);
|
|
291
|
+
if (deflated.length < data.length) {
|
|
292
|
+
method = 8;
|
|
293
|
+
body = deflated;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (offset + body.length > MAX_BYTES)
|
|
297
|
+
throw new ArchiveTooLarge('The folder grew past what a zip holds (4 GiB) while it was being zipped.');
|
|
298
|
+
const name = Buffer.from(entry.name, 'utf8');
|
|
299
|
+
const { time, date } = dosTime(entry.mtime);
|
|
300
|
+
const local = Buffer.alloc(30);
|
|
301
|
+
local.writeUInt32LE(0x04034b50, 0);
|
|
302
|
+
local.writeUInt16LE(20, 4); // version needed: 2.0
|
|
303
|
+
local.writeUInt16LE(UTF8, 6);
|
|
304
|
+
local.writeUInt16LE(method, 8);
|
|
305
|
+
local.writeUInt16LE(time, 10);
|
|
306
|
+
local.writeUInt16LE(date, 12);
|
|
307
|
+
local.writeUInt32LE(crc, 14);
|
|
308
|
+
local.writeUInt32LE(body.length, 18);
|
|
309
|
+
local.writeUInt32LE(data.length, 22);
|
|
310
|
+
local.writeUInt16LE(name.length, 26);
|
|
311
|
+
local.writeUInt16LE(0, 28);
|
|
312
|
+
const header = Buffer.alloc(46);
|
|
313
|
+
header.writeUInt32LE(0x02014b50, 0);
|
|
314
|
+
header.writeUInt16LE((3 << 8) | 20, 4); // made by: Unix, 2.0
|
|
315
|
+
header.writeUInt16LE(20, 6);
|
|
316
|
+
header.writeUInt16LE(UTF8, 8);
|
|
317
|
+
header.writeUInt16LE(method, 10);
|
|
318
|
+
header.writeUInt16LE(time, 12);
|
|
319
|
+
header.writeUInt16LE(date, 14);
|
|
320
|
+
header.writeUInt32LE(crc, 16);
|
|
321
|
+
header.writeUInt32LE(body.length, 20);
|
|
322
|
+
header.writeUInt32LE(data.length, 24);
|
|
323
|
+
header.writeUInt16LE(name.length, 28);
|
|
324
|
+
// extra, comment, disk, internal attributes: 0
|
|
325
|
+
header.writeUInt32LE(((0o100000 | (entry.mode || 0o644) | 0o600) << 16) >>> 0, 38); // a regular file, its permissions
|
|
326
|
+
header.writeUInt32LE(offset, 42);
|
|
327
|
+
central.push(header, name);
|
|
328
|
+
await put(Buffer.concat([local, name]));
|
|
329
|
+
await put(body);
|
|
330
|
+
files++;
|
|
331
|
+
}
|
|
332
|
+
const start = offset;
|
|
333
|
+
const directory = Buffer.concat(central);
|
|
334
|
+
await put(directory);
|
|
335
|
+
const end = Buffer.alloc(22);
|
|
336
|
+
end.writeUInt32LE(0x06054b50, 0);
|
|
337
|
+
end.writeUInt16LE(files, 8);
|
|
338
|
+
end.writeUInt16LE(files, 10);
|
|
339
|
+
end.writeUInt32LE(directory.length, 12);
|
|
340
|
+
end.writeUInt32LE(start, 16);
|
|
341
|
+
await put(end);
|
|
342
|
+
return { bytes: offset, files };
|
|
343
|
+
}
|
|
344
|
+
/* -------------------------------------------------------------------------- */
|
|
345
|
+
/* Where it goes */
|
|
346
|
+
/* -------------------------------------------------------------------------- */
|
|
347
|
+
/** `<folder>-<yyyy-mm-dd>.zip`: a day's backup beside the last one, not over it. */
|
|
348
|
+
export function archiveFileName(root, now = new Date()) {
|
|
349
|
+
const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
|
|
350
|
+
return `${basename(resolve(root)) || 'artifact'}-${day}.zip`;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Writes the folder's zip to `out` (through a temp file beside it, so a
|
|
354
|
+
* failure leaves no half zip). `out` may be inside the folder: it is never
|
|
355
|
+
* zipped into itself.
|
|
356
|
+
*/
|
|
357
|
+
export async function writeArchive(root, out) {
|
|
358
|
+
const file = resolve(out);
|
|
359
|
+
const entries = await archiveEntries(root, [file]);
|
|
360
|
+
const temp = join(dirname(file), `.${basename(file)}.${process.pid}.tmp`);
|
|
361
|
+
const handle = await open(temp, 'w');
|
|
362
|
+
let result;
|
|
363
|
+
try {
|
|
364
|
+
result = await writeZip(entries, async (chunk) => {
|
|
365
|
+
await handle.write(chunk);
|
|
366
|
+
});
|
|
367
|
+
await handle.close();
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
await handle.close().catch(() => undefined);
|
|
371
|
+
await rm(temp, { force: true });
|
|
372
|
+
throw error;
|
|
373
|
+
}
|
|
374
|
+
await rename(temp, file);
|
|
375
|
+
return { file, ...result };
|
|
376
|
+
}
|
|
377
|
+
/** `attachment` with the file's name: plain ASCII in `filename`, the real name in `filename*`. */
|
|
378
|
+
export function attachmentHeader(name) {
|
|
379
|
+
const ascii = name.replace(/[^\x20-\x7e]|["\\]/g, '_');
|
|
380
|
+
return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Answers `GET|HEAD /__open-artifacts/archive`: the folder's zip, streamed as
|
|
384
|
+
* it is written (no length: each file is deflated on the way). `HEAD` lists
|
|
385
|
+
* the files only, so a folder over plain zip's limits answers 413 before
|
|
386
|
+
* anything is zipped. A connection that closes stops the zipping.
|
|
387
|
+
*/
|
|
388
|
+
export async function sendArchive(req, res, root) {
|
|
389
|
+
const method = req.method ?? 'GET';
|
|
390
|
+
req.resume();
|
|
391
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
392
|
+
res.writeHead(405, { allow: 'GET, HEAD' }).end();
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
let entries;
|
|
396
|
+
try {
|
|
397
|
+
entries = await archiveEntries(root);
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
if (error instanceof ArchiveTooLarge) {
|
|
401
|
+
const body = JSON.stringify({ code: 'too_large', message: error.message });
|
|
402
|
+
res.writeHead(413, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(method === 'HEAD' ? undefined : body);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
throw error;
|
|
406
|
+
}
|
|
407
|
+
res.writeHead(200, { 'content-type': 'application/zip', 'content-disposition': attachmentHeader(archiveFileName(root)), 'cache-control': 'no-store' });
|
|
408
|
+
if (method === 'HEAD') {
|
|
409
|
+
res.end();
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
let closed = false;
|
|
413
|
+
res.on('close', () => (closed = true));
|
|
414
|
+
try {
|
|
415
|
+
await writeZip(entries, (chunk) => {
|
|
416
|
+
if (closed || res.destroyed)
|
|
417
|
+
return Promise.reject(new Error('The connection closed.'));
|
|
418
|
+
if (res.write(chunk))
|
|
419
|
+
return Promise.resolve();
|
|
420
|
+
return new Promise((done, fail) => {
|
|
421
|
+
const onDrain = () => {
|
|
422
|
+
res.off('close', onClose);
|
|
423
|
+
done();
|
|
424
|
+
};
|
|
425
|
+
const onClose = () => {
|
|
426
|
+
res.off('drain', onDrain);
|
|
427
|
+
fail(new Error('The connection closed.'));
|
|
428
|
+
};
|
|
429
|
+
res.once('drain', onDrain);
|
|
430
|
+
res.once('close', onClose);
|
|
431
|
+
});
|
|
432
|
+
});
|
|
433
|
+
res.end();
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
// Headers are out: the only way to say it failed is to cut the download short.
|
|
437
|
+
res.destroy();
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/* -------------------------------------------------------------------------- */
|
|
441
|
+
/* Unpacking a zip from anyone */
|
|
442
|
+
/* -------------------------------------------------------------------------- */
|
|
443
|
+
/** Why a zip is refused: `invalid` (its shape or a name, 400) or `too_large` (a limit, 413). */
|
|
444
|
+
export class ZipRefusal extends Error {
|
|
445
|
+
code;
|
|
446
|
+
status;
|
|
447
|
+
constructor(code, message) {
|
|
448
|
+
super(message);
|
|
449
|
+
this.code = code;
|
|
450
|
+
this.status = code === 'too_large' ? 413 : 400;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
const UNIX_HOST = 3;
|
|
454
|
+
const S_IFMT = 0o170000;
|
|
455
|
+
const S_IFREG = 0o100000;
|
|
456
|
+
const S_IFDIR = 0o040000;
|
|
457
|
+
const DOS_DIRECTORY = 0x10;
|
|
458
|
+
/** Flag bits of an encrypted entry: encrypted, strong encryption, masked local header. */
|
|
459
|
+
const ENCRYPTED = (1 << 0) | (1 << 6) | (1 << 13);
|
|
460
|
+
/** `wx`, and never through a symbolic link. */
|
|
461
|
+
const WRITE_NEW = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);
|
|
462
|
+
/** Whether an entry was made on a Unix host and its mode says a regular file (not a folder, link, device or no kind at all). */
|
|
463
|
+
export function isUnixRegularFile(entry) {
|
|
464
|
+
return entry.madeBy >>> 8 === UNIX_HOST && ((entry.externalAttributes >>> 16) & S_IFMT) === S_IFREG;
|
|
465
|
+
}
|
|
466
|
+
/** How a name compares on a disk that ignores case and Unicode normalization. */
|
|
467
|
+
export const foldedName = (path) => path.normalize('NFC').toLowerCase();
|
|
468
|
+
/**
|
|
469
|
+
* Every entry of a zip checked, before a byte is unpacked: no encryption, stored or deflated only; plain files (and,
|
|
470
|
+
* with `folders`, folder entries) only, so no symbolic link or device (by the Unix mode in the external attributes);
|
|
471
|
+
* no NUL, backslash, absolute path, `..`, empty or `.` step; all under one top folder; no name twice once case and
|
|
472
|
+
* Unicode normalization are ignored, and no name both a file and a folder; local headers that match the directory;
|
|
473
|
+
* and the declared sizes within `rules` (which {@link unpackZip} holds them to while inflating), each file's against
|
|
474
|
+
* `rules.fileLimit` of its path when given, else `rules.maxFileBytes`. A file whose name passes the built-in checks is
|
|
475
|
+
* then put to `rules.accept`, when given, before the duplicate and size checks; a string it returns is thrown as an
|
|
476
|
+
* `invalid` refusal. Throws {@link ZipRefusal}.
|
|
477
|
+
*/
|
|
478
|
+
export function checkZip(bytes, rules) {
|
|
479
|
+
const refuse = (message) => new ZipRefusal('invalid', message);
|
|
480
|
+
const tooLarge = (message) => new ZipRefusal('too_large', message);
|
|
481
|
+
let directory;
|
|
482
|
+
try {
|
|
483
|
+
directory = zipEntries(bytes);
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
if (error instanceof ZipError)
|
|
487
|
+
throw refuse('This file is not a zip.');
|
|
488
|
+
throw error;
|
|
489
|
+
}
|
|
490
|
+
if (directory.declared > rules.maxFiles * 2 + 1000)
|
|
491
|
+
throw tooLarge(`${rules.noun} holds ${directory.declared} entries, more than it may (${rules.maxFiles} files).`);
|
|
492
|
+
if (directory.entries.length !== directory.declared)
|
|
493
|
+
throw refuse('The zip is damaged: its central directory is short.');
|
|
494
|
+
if (directory.declared === 0)
|
|
495
|
+
throw refuse(`${rules.noun} is empty.`);
|
|
496
|
+
const files = [];
|
|
497
|
+
const seen = new Set();
|
|
498
|
+
const folders = new Set();
|
|
499
|
+
let top;
|
|
500
|
+
let declared = 0;
|
|
501
|
+
for (const entry of directory.entries) {
|
|
502
|
+
const name = entry.name;
|
|
503
|
+
const shown = JSON.stringify(name);
|
|
504
|
+
if (entry.flags & ENCRYPTED)
|
|
505
|
+
throw refuse(`${shown} is encrypted; ${rules.noun} never is.`);
|
|
506
|
+
if (entry.method !== 0 && entry.method !== 8)
|
|
507
|
+
throw refuse(`${shown} is packed with method ${entry.method}; only stored and deflated files are read.`);
|
|
508
|
+
if (name.includes('\0') || name.includes('\\'))
|
|
509
|
+
throw refuse(`${shown} has a backslash or a NUL in its name.`);
|
|
510
|
+
if (name.startsWith('/') || /^[A-Za-z]:/.test(name))
|
|
511
|
+
throw refuse(`${shown} is an absolute path.`);
|
|
512
|
+
const mode = entry.externalAttributes >>> 16;
|
|
513
|
+
const unix = entry.madeBy >>> 8 === UNIX_HOST;
|
|
514
|
+
const kind = unix ? mode & S_IFMT : 0;
|
|
515
|
+
const folder = name.endsWith('/') || (entry.externalAttributes & DOS_DIRECTORY) !== 0 || kind === S_IFDIR;
|
|
516
|
+
if (kind !== 0 && kind !== S_IFREG && kind !== S_IFDIR)
|
|
517
|
+
throw refuse(`${shown} is a symbolic link or a device; ${rules.noun} holds plain files only.`);
|
|
518
|
+
if (folder && !rules.folders)
|
|
519
|
+
throw refuse(`${shown} is a folder entry; ${rules.noun} holds files only.`);
|
|
520
|
+
const steps = name.replace(/\/$/, '').split('/');
|
|
521
|
+
if (steps.some((step) => step === '..'))
|
|
522
|
+
throw refuse(`${shown} climbs out of its folder (..).`);
|
|
523
|
+
if (steps.some((step) => step === '' || step === '.'))
|
|
524
|
+
throw refuse(`${shown} has an empty or "." step in its path.`);
|
|
525
|
+
// Said before the folders are compared: a file beside the folder is that mistake, not a second folder.
|
|
526
|
+
if (!folder && steps.length < 2)
|
|
527
|
+
throw refuse(`${shown} is at the top of the zip; ${rules.noun} holds one folder.`);
|
|
528
|
+
if (top === undefined)
|
|
529
|
+
top = steps[0];
|
|
530
|
+
else if (steps[0] !== top)
|
|
531
|
+
throw refuse(`${rules.noun} holds more than one top folder (${JSON.stringify(top)} and ${JSON.stringify(steps[0])}); it holds one.`);
|
|
532
|
+
if (folder) {
|
|
533
|
+
if (entry.size !== 0)
|
|
534
|
+
throw refuse(`The zip is damaged: the folder ${shown} has data.`);
|
|
535
|
+
const key = foldedName(steps.slice(1).join('/'));
|
|
536
|
+
if (key)
|
|
537
|
+
folders.add(key);
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
const path = steps.slice(1).join('/');
|
|
541
|
+
const demand = rules.accept?.(entry, path) ?? null;
|
|
542
|
+
if (demand !== null)
|
|
543
|
+
throw refuse(demand);
|
|
544
|
+
const key = foldedName(path);
|
|
545
|
+
if (seen.has(key))
|
|
546
|
+
throw refuse(`${shown} is in ${rules.noun} twice (names that differ only in case or Unicode form count as the same).`);
|
|
547
|
+
seen.add(key);
|
|
548
|
+
const parts = key.split('/');
|
|
549
|
+
for (let index = 1; index < parts.length; index++)
|
|
550
|
+
folders.add(parts.slice(0, index).join('/'));
|
|
551
|
+
if (seen.size > rules.maxFiles)
|
|
552
|
+
throw tooLarge(`${rules.noun} holds more than ${rules.maxFiles} files.`);
|
|
553
|
+
const cap = rules.fileLimit ? rules.fileLimit(path) : rules.maxFileBytes;
|
|
554
|
+
if (entry.size > cap)
|
|
555
|
+
throw tooLarge(`${path} unpacks to ${entry.size} bytes, more than ${cap}.`);
|
|
556
|
+
declared += entry.size;
|
|
557
|
+
if (declared > rules.maxBytes)
|
|
558
|
+
throw tooLarge(`${rules.noun} unpacks to more than ${rules.maxBytes} bytes.`);
|
|
559
|
+
let local;
|
|
560
|
+
try {
|
|
561
|
+
local = entryBytes(bytes, entry);
|
|
562
|
+
}
|
|
563
|
+
catch (error) {
|
|
564
|
+
if (error instanceof ZipError)
|
|
565
|
+
throw refuse(error.message);
|
|
566
|
+
throw error;
|
|
567
|
+
}
|
|
568
|
+
if (local.start + entry.packedSize > directory.directoryOffset || directory.directoryOffset > bytes.byteLength)
|
|
569
|
+
throw refuse(`The zip is damaged: the data of ${path} runs past its end.`);
|
|
570
|
+
if (local.localName !== entry.name || local.localMethod !== entry.method || local.localFlags & ENCRYPTED)
|
|
571
|
+
throw refuse(`The zip is damaged: the local header of ${path} does not match its directory entry.`);
|
|
572
|
+
if (entry.method === 0 && entry.packedSize !== entry.size)
|
|
573
|
+
throw refuse(`The zip is damaged: ${path} is stored but its sizes differ.`);
|
|
574
|
+
files.push({ entry, path, mode: ((unix ? mode : 0o644) & 0o755) | 0o600 });
|
|
575
|
+
}
|
|
576
|
+
for (const key of seen)
|
|
577
|
+
if (folders.has(key))
|
|
578
|
+
throw refuse(`${key} is in ${rules.noun} both as a file and as a folder.`);
|
|
579
|
+
if (top === undefined)
|
|
580
|
+
throw refuse(`${rules.noun} is empty.`);
|
|
581
|
+
return { top, files };
|
|
582
|
+
}
|
|
583
|
+
/** One checked file's bytes: inflated never past its declared size, which must be its real size, with its CRC holding. */
|
|
584
|
+
export async function unpackZipFile(bytes, item) {
|
|
585
|
+
let data;
|
|
586
|
+
try {
|
|
587
|
+
data = await unpackEntry(bytes, item.entry, item.entry.size);
|
|
588
|
+
}
|
|
589
|
+
catch (error) {
|
|
590
|
+
if (error instanceof RangeError)
|
|
591
|
+
throw new ZipRefusal('too_large', `${item.path} unpacks to more than the ${item.entry.size} bytes it declares.`);
|
|
592
|
+
if (error instanceof ZipError)
|
|
593
|
+
throw new ZipRefusal('invalid', error.message);
|
|
594
|
+
throw new ZipRefusal('invalid', `The zip is damaged: ${item.path} cannot be unpacked.`);
|
|
595
|
+
}
|
|
596
|
+
if (data.length !== item.entry.size)
|
|
597
|
+
throw new ZipRefusal('invalid', `The zip is damaged: ${item.path} unpacks to ${data.length} bytes, not the ${item.entry.size} it declares.`);
|
|
598
|
+
if (crc32(data) !== item.entry.crc)
|
|
599
|
+
throw new ZipRefusal('invalid', `The zip is damaged: ${item.path} fails its CRC check.`);
|
|
600
|
+
return data;
|
|
601
|
+
}
|
|
602
|
+
/** Writes a new file, refusing one that exists and never following a symbolic link. */
|
|
603
|
+
export async function writeNewFile(file, data, mode = 0o644) {
|
|
604
|
+
const handle = await open(file, WRITE_NEW, mode);
|
|
605
|
+
try {
|
|
606
|
+
await handle.writeFile(data);
|
|
607
|
+
}
|
|
608
|
+
finally {
|
|
609
|
+
await handle.close();
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Unpacks a checked zip into a new temporary folder beside `dest` (named `.<dest>.<random>.unpack`, so a type root's
|
|
614
|
+
* scan skips it), counting the bytes actually inflated against `maxBytes`, and returns that folder. The caller checks
|
|
615
|
+
* what was unpacked and renames it into place; on a failure here the temporary folder is removed.
|
|
616
|
+
*/
|
|
617
|
+
export async function unpackZip(bytes, files, dest, maxBytes) {
|
|
618
|
+
const target = resolve(dest);
|
|
619
|
+
await mkdir(dirname(target), { recursive: true });
|
|
620
|
+
const temp = join(dirname(target), `.${basename(target)}.${randomBytes(6).toString('hex')}.unpack`);
|
|
621
|
+
await mkdir(temp);
|
|
622
|
+
try {
|
|
623
|
+
let total = 0;
|
|
624
|
+
for (const item of files) {
|
|
625
|
+
const data = await unpackZipFile(bytes, item);
|
|
626
|
+
total += data.length;
|
|
627
|
+
if (total > maxBytes)
|
|
628
|
+
throw new ZipRefusal('too_large', `It unpacks to more than ${maxBytes} bytes.`);
|
|
629
|
+
const file = resolve(temp, ...item.path.split('/'));
|
|
630
|
+
if (!file.startsWith(temp + sep))
|
|
631
|
+
throw new ZipRefusal('invalid', `${item.path} would land outside its folder.`);
|
|
632
|
+
await mkdir(dirname(file), { recursive: true });
|
|
633
|
+
await writeNewFile(file, data, item.mode);
|
|
634
|
+
}
|
|
635
|
+
return { temp, files: files.length, bytes: total };
|
|
636
|
+
}
|
|
637
|
+
catch (error) {
|
|
638
|
+
await rm(temp, { recursive: true, force: true });
|
|
639
|
+
const code = error.code;
|
|
640
|
+
if (code === 'EEXIST' || code === 'ENOTDIR')
|
|
641
|
+
throw new ZipRefusal('invalid', "The zip's paths collide with one another.");
|
|
642
|
+
throw error;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
/** Moves a checked, unpacked folder into place; refuses when `dest` exists by then. */
|
|
646
|
+
export async function moveIntoPlace(temp, dest) {
|
|
647
|
+
if (await lstat(dest).then(() => true, () => false)) {
|
|
648
|
+
await rm(temp, { recursive: true, force: true });
|
|
649
|
+
throw Object.assign(new Error(`${dest} exists already.`), { code: 'EEXIST' });
|
|
650
|
+
}
|
|
651
|
+
await rename(temp, dest);
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* The zip of a folder's files as bytes (`types pack`): `entries` named `<folder>/<path>`, already chosen by the caller.
|
|
655
|
+
*/
|
|
656
|
+
export async function zipBytes(entries) {
|
|
657
|
+
const chunks = [];
|
|
658
|
+
await writeZip(entries, async (chunk) => {
|
|
659
|
+
chunks.push(chunk);
|
|
660
|
+
});
|
|
661
|
+
return Buffer.concat(chunks);
|
|
662
|
+
}
|