@preventive/archive 1.4.0 → 1.4.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/compression.d.ts +50 -30
- package/compression.js +0 -5
- package/package.json +2 -1
- package/src/bytes.js +0 -2
- package/src/compression.js +36 -93
- package/src/entry.js +3 -9
- package/src/error.d.ts +10 -0
- package/src/error.js +4 -8
- package/src/names.js +29 -117
- package/src/tar/header.js +14 -39
- package/src/tar/pack.js +33 -48
- package/src/tar/pax.js +6 -11
- package/src/tar/unpack.js +67 -122
- package/src/text.js +6 -32
- package/src/zip/format.js +10 -29
- package/src/zip/unzip.js +40 -94
- package/src/zip/zip.js +24 -32
- package/tar.d.ts +166 -137
- package/tar.js +2 -18
- package/zip.d.ts +103 -98
- package/zip.js +1 -19
package/compression.d.ts
CHANGED
|
@@ -1,39 +1,59 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Bytes through the platform's `CompressionStream` and `DecompressionStream`, whole
|
|
3
|
+
*
|
|
4
|
+
* ```js
|
|
5
|
+
* import { compress, decompress, supports } from '@preventive/archive/compression.js'
|
|
6
|
+
* ```
|
|
7
|
+
*
|
|
8
|
+
* @module @preventive/archive/compression.js
|
|
9
|
+
*/
|
|
4
10
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
11
|
+
import { ArchiveError } from './src/error.js';
|
|
12
|
+
|
|
13
|
+
export { ArchiveError };
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Whether this runtime has a format both ways
|
|
17
|
+
*
|
|
18
|
+
* @param format - `'gzip'`, `'deflate'` and `'deflate-raw'` are everywhere, `'brotli'` only where added
|
|
19
|
+
*/
|
|
20
|
+
export function supports(format: string): boolean;
|
|
9
21
|
|
|
10
|
-
// `limit` bounds the output in bytes; past it the call rejects with
|
|
11
|
-
// `limited` set rather than going on.
|
|
12
22
|
export interface Options {
|
|
13
|
-
limit
|
|
23
|
+
/** Most bytes of output; past it, rejects with `limited` set (default: no limit) */
|
|
24
|
+
limit?: number;
|
|
14
25
|
}
|
|
15
26
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Compress bytes
|
|
29
|
+
*
|
|
30
|
+
* @param bytes - The input
|
|
31
|
+
* @param format - A `CompressionStream` format; one the runtime lacks rejects with the platform's error
|
|
32
|
+
* @param options - The output bound
|
|
33
|
+
* @returns The output
|
|
34
|
+
*/
|
|
35
|
+
export function compress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>;
|
|
22
36
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Decompress bytes
|
|
39
|
+
*
|
|
40
|
+
* gzip is read past zero bytes after its last member, as gzip(1) and zlib take them for padding and the
|
|
41
|
+
* platform does not; nothing else after the end is passed over.
|
|
42
|
+
*
|
|
43
|
+
* @param bytes - The input
|
|
44
|
+
* @param format - A `DecompressionStream` format; one the runtime lacks rejects with the platform's error
|
|
45
|
+
* @param options - The output bound
|
|
46
|
+
* @returns The output
|
|
47
|
+
*/
|
|
48
|
+
export function decompress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>;
|
|
30
49
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
50
|
+
/**
|
|
51
|
+
* What a stream refused
|
|
52
|
+
*/
|
|
34
53
|
export class CompressionError extends ArchiveError {
|
|
35
|
-
constructor(detail: string, options: { bytes: Uint8Array; limited?: boolean; cause?: unknown })
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
54
|
+
constructor(detail: string, options: { bytes: Uint8Array; limited?: boolean; cause?: unknown });
|
|
55
|
+
/** The output made before the failure, for a caller that keeps it as gzip(1) does */
|
|
56
|
+
bytes: Uint8Array;
|
|
57
|
+
/** The platform's error */
|
|
58
|
+
cause: unknown;
|
|
39
59
|
}
|
package/compression.js
CHANGED
|
@@ -1,7 +1,2 @@
|
|
|
1
|
-
// The compression front door of @preventive/archive, reached as
|
|
2
|
-
// `@preventive/archive/compression.js`: bytes through the platform's
|
|
3
|
-
// CompressionStream and DecompressionStream, whole, with an output bound,
|
|
4
|
-
// gzip's zero padding passed over, and with what came out before a failure
|
|
5
|
-
// kept on the error. The zip half deflates through the same code.
|
|
6
1
|
export { CompressionError, compress, decompress, supports } from './src/compression.js'
|
|
7
2
|
export { ArchiveError } from './src/error.js'
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@preventive/archive",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.1",
|
|
4
4
|
"description": "Strict in-memory tar and zip on browser APIs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
"src/bytes.js",
|
|
26
26
|
"src/compression.js",
|
|
27
27
|
"src/entry.js",
|
|
28
|
+
"src/error.d.ts",
|
|
28
29
|
"src/error.js",
|
|
29
30
|
"src/names.js",
|
|
30
31
|
"src/tar/header.js",
|
package/src/bytes.js
CHANGED
package/src/compression.js
CHANGED
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
// Bytes through the platform's compression streams, both ways: the zip
|
|
2
|
-
// half's deflate, and a front door of its own for anything else with bytes
|
|
3
|
-
// to compress. What came out before a stream failed travels with the
|
|
4
|
-
// error, for a caller that keeps it as gzip does.
|
|
5
|
-
|
|
6
1
|
import { concat } from './bytes.js'
|
|
7
2
|
import { ArchiveError } from './error.js'
|
|
8
3
|
|
|
@@ -15,137 +10,85 @@ export class CompressionError extends ArchiveError {
|
|
|
15
10
|
}
|
|
16
11
|
}
|
|
17
12
|
|
|
18
|
-
// Whether this runtime's streams know a format both ways: gzip is
|
|
19
|
-
// everywhere they are, brotli only where it was added.
|
|
20
13
|
export function supports(format) {
|
|
21
14
|
try {
|
|
22
|
-
return [
|
|
15
|
+
return [CompressionStream, DecompressionStream].every((Stream) => new Stream(format))
|
|
23
16
|
} catch {
|
|
24
17
|
return false
|
|
25
18
|
}
|
|
26
19
|
}
|
|
27
20
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
// reading it is left before its end.
|
|
31
|
-
async function* readerChunks(stream) {
|
|
32
|
-
const reader = stream.getReader()
|
|
33
|
-
try {
|
|
34
|
-
for (let next = await reader.read(); !next.done; next = await reader.read()) yield next.value
|
|
35
|
-
} finally {
|
|
36
|
-
reader.cancel().catch(() => {})
|
|
37
|
-
}
|
|
21
|
+
function checkBytes(bytes) {
|
|
22
|
+
if (!(bytes instanceof Uint8Array)) throw new ArchiveError('the data is not a Uint8Array')
|
|
38
23
|
}
|
|
39
|
-
const chunksOf = (stream) => (Symbol.asyncIterator in stream ? stream : readerChunks(stream))
|
|
40
24
|
|
|
41
|
-
//
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
// the stream makes and joined at the end, or, given `into`, copied into it
|
|
46
|
-
// as each piece comes and the piece let go: joining holds the output twice
|
|
47
|
-
// at the end, which a caller who knows how much is coming need not pay.
|
|
48
|
-
// Given `expected` bytes instead, the first that many are copied into one
|
|
49
|
-
// array of that size as they come, and any past it gathered in pieces.
|
|
50
|
-
// Output past `limit` is refused where it is, not after it has all been
|
|
51
|
-
// made: leaving the loop cancels the stream. A bound that is no number
|
|
52
|
-
// (NaN) refuses everything, not nothing.
|
|
53
|
-
async function through(bytes, Stream, format, limit, verb, into, expected = 0) {
|
|
54
|
-
if (!(bytes instanceof Uint8Array)) throw new ArchiveError('the data is not a Uint8Array')
|
|
55
|
-
const transform = new Stream(format)
|
|
56
|
-
const chunks = []
|
|
57
|
-
let length = 0
|
|
58
|
-
// Where the output is copied as it comes, and how much of it is filled.
|
|
59
|
-
let target = into ?? (expected > 0 ? new Uint8Array(expected) : undefined)
|
|
60
|
-
let filled = 0
|
|
61
|
-
// What has come out so far, as one array: handed back at the end, and
|
|
62
|
-
// with the error if the stream fails first.
|
|
63
|
-
const made = () => {
|
|
64
|
-
if (into !== undefined) return into.subarray(0, length)
|
|
65
|
-
if (target !== undefined) return filled === target.length ? target : target.subarray(0, filled)
|
|
66
|
-
return chunks.length === 1 ? chunks[0] : concat(chunks)
|
|
67
|
-
}
|
|
68
|
-
// The stream's own failure is read from its output; the writes fail with it.
|
|
25
|
+
// Output past `limit` is refused as it comes (NaN refuses all). Given `target`, output is written
|
|
26
|
+
// into it while it fits, rather than gathered in pieces and joined, which holds it twice.
|
|
27
|
+
async function through(bytes, Stream, format, limit, verb, target) {
|
|
28
|
+
const transform = new Stream(format) // a format the runtime lacks rejects with the platform's error
|
|
69
29
|
const writer = transform.writable.getWriter()
|
|
70
|
-
writer.write(bytes).catch(() => {})
|
|
30
|
+
writer.write(bytes).catch(() => {}) // the stream's failure is read from its output
|
|
71
31
|
writer.close().catch(() => {})
|
|
32
|
+
const reader = transform.readable.getReader() // not async iteration, which not every platform has
|
|
33
|
+
const chunks = []
|
|
34
|
+
let length = 0
|
|
35
|
+
const made = () => (target ? target.subarray(0, length) : chunks.length === 1 ? chunks[0] : concat(chunks))
|
|
72
36
|
try {
|
|
73
|
-
for await (
|
|
37
|
+
for (let next = await reader.read(); !next.done; next = await reader.read()) {
|
|
38
|
+
const chunk = next.value
|
|
74
39
|
if (!(length + chunk.length <= limit)) throw new RangeError(`output past ${limit} bytes`)
|
|
75
|
-
if (target
|
|
76
|
-
|
|
77
|
-
chunks.push(target.subarray(0, filled))
|
|
40
|
+
if (target && length + chunk.length > target.length) {
|
|
41
|
+
chunks.push(target.subarray(0, length))
|
|
78
42
|
target = undefined
|
|
79
43
|
}
|
|
80
|
-
if (target
|
|
81
|
-
|
|
82
|
-
} else {
|
|
83
|
-
target.set(chunk, filled)
|
|
84
|
-
filled += chunk.length
|
|
85
|
-
}
|
|
44
|
+
if (target) target.set(chunk, length)
|
|
45
|
+
else chunks.push(chunk)
|
|
86
46
|
length += chunk.length
|
|
87
47
|
}
|
|
88
48
|
} catch (cause) {
|
|
49
|
+
reader.cancel().catch(() => {})
|
|
89
50
|
const limited = cause instanceof RangeError
|
|
90
51
|
throw new CompressionError(limited ? `the data ${verb}es past ${limit} bytes` : `the data does not ${verb}`, { bytes: made(), limited, cause })
|
|
91
52
|
}
|
|
92
53
|
return made()
|
|
93
54
|
}
|
|
94
55
|
|
|
95
|
-
export
|
|
56
|
+
export async function compress(bytes, format, { limit = Infinity } = {}) {
|
|
57
|
+
checkBytes(bytes)
|
|
58
|
+
return await through(bytes, CompressionStream, format, limit, 'compress')
|
|
59
|
+
}
|
|
96
60
|
|
|
97
|
-
//
|
|
98
|
-
//
|
|
99
|
-
// is one member and no more than 4 GiB. It is the data's own word, so it is
|
|
100
|
-
// taken only where `limit` lets that much through and it is no more than
|
|
101
|
-
// RATIO times the data: tarballs come to 2 to 13 times theirs, so one that
|
|
102
|
-
// says more is gathered in pieces as before, and a trailer that lies costs
|
|
103
|
-
// no more than that. Else, as when the data ends in padding, none is
|
|
104
|
-
// expected. Where it says less than comes, the rest is gathered as any
|
|
105
|
-
// output is; where it says more, the stream fails on it, as zlib holds the
|
|
106
|
-
// trailer to what it made.
|
|
61
|
+
// gzip's last 4 bytes are its last member's size mod 2^32. Trusted only within `limit` and RATIO times
|
|
62
|
+
// the input (tarballs come to 2 to 13), so a lying trailer costs no more than that.
|
|
107
63
|
const RATIO = 16
|
|
108
|
-
function
|
|
64
|
+
function trailerSize(bytes, limit) {
|
|
109
65
|
if (bytes.length < 18) return 0
|
|
110
66
|
const said = new DataView(bytes.buffer, bytes.byteOffset + bytes.length - 4, 4).getUint32(0, true)
|
|
111
67
|
return said <= limit && said <= bytes.length * RATIO ? said : 0
|
|
112
68
|
}
|
|
113
69
|
|
|
114
|
-
|
|
115
|
-
// (expectedOf), which only the data as given has: a place that padding is
|
|
116
|
-
// tried ending at has the member's checksum or none where a trailer would be.
|
|
117
|
-
const inflate = (bytes, format, limit, sized) => through(bytes, DecompressionStream, format, limit, 'decompress', undefined, sized && format === 'gzip' ? expectedOf(bytes, limit) : 0)
|
|
70
|
+
const inflate = (bytes, format, limit, size = 0) => through(bytes, DecompressionStream, format, limit, 'decompress', size ? new Uint8Array(size) : undefined)
|
|
118
71
|
|
|
119
|
-
// gzip(1) and zlib take
|
|
120
|
-
//
|
|
121
|
-
// packed them through the system's tar; the platform's stream refuses
|
|
122
|
-
// anything there. So gzip that ends in a zero and does not decompress is
|
|
123
|
-
// tried again ending sooner, at the one place it decompresses whole: its
|
|
124
|
-
// last member's last four bytes are the length it inflates to, mod 2^32,
|
|
125
|
-
// so where that is not 0 it ends within three zeros past the last byte that
|
|
126
|
-
// is not; where the member is empty, as zlib writes one, `03 00` and eight
|
|
127
|
-
// zeros, within nine. Only zeros are passed over, where zlib passes over
|
|
128
|
-
// whatever follows one; and each place tried inflates it all again, which
|
|
129
|
-
// only padded data pays for.
|
|
72
|
+
// gzip(1) and zlib take zeros after the last member as padding, which the platform refuses. A member ends
|
|
73
|
+
// in its size, so within 3 zeros past the last nonzero byte, or 9 for an empty one: each end is tried.
|
|
130
74
|
export async function decompress(bytes, format, { limit = Infinity } = {}) {
|
|
75
|
+
checkBytes(bytes)
|
|
76
|
+
const gzip = format === 'gzip'
|
|
131
77
|
try {
|
|
132
|
-
return await inflate(bytes, format, limit,
|
|
78
|
+
return await inflate(bytes, format, limit, gzip ? trailerSize(bytes, limit) : 0)
|
|
133
79
|
} catch (error) {
|
|
134
|
-
if (
|
|
80
|
+
if (!gzip || !(error instanceof CompressionError) || error.limited || bytes.at(-1) !== 0) throw error
|
|
135
81
|
const last = bytes.findLastIndex((byte) => byte !== 0)
|
|
136
82
|
for (let end = last + 1; end <= Math.min(last + 10, bytes.length - 1); end++) {
|
|
137
83
|
try {
|
|
138
|
-
return await inflate(bytes.subarray(0, end), format, limit
|
|
84
|
+
return await inflate(bytes.subarray(0, end), format, limit)
|
|
139
85
|
} catch (retry) {
|
|
140
|
-
|
|
141
|
-
if (!(retry instanceof CompressionError) || retry.limited) throw retry
|
|
86
|
+
if (!(retry instanceof CompressionError) || retry.limited) throw retry // past the bound at any end
|
|
142
87
|
}
|
|
143
88
|
}
|
|
144
89
|
throw error
|
|
145
90
|
}
|
|
146
91
|
}
|
|
147
92
|
|
|
148
|
-
//
|
|
149
|
-
// was filled. Not in the front door: the zip half's, whose entries each
|
|
150
|
-
// declare their size.
|
|
93
|
+
// Bounded by and made into `into`, for zip's entries, which declare their size
|
|
151
94
|
export const decompressInto = (bytes, format, into) => through(bytes, DecompressionStream, format, into.length, 'decompress', into)
|
package/src/entry.js
CHANGED
|
@@ -1,25 +1,19 @@
|
|
|
1
|
-
// What an entry to write is in either format: checked here, and each
|
|
2
|
-
// format adds the fields it stores.
|
|
3
|
-
|
|
4
1
|
import { EMPTY } from './bytes.js'
|
|
5
2
|
import { ArchiveError } from './error.js'
|
|
6
3
|
import { checkString, quote } from './text.js'
|
|
7
4
|
|
|
8
5
|
export const DEFAULT_MODE = { file: 0o644, directory: 0o755, symlink: 0o777 }
|
|
9
6
|
|
|
10
|
-
// A contiguous file is a file for every purpose here.
|
|
11
7
|
export const isFile = (type) => type === 'file' || type === 'contiguous-file'
|
|
12
8
|
|
|
13
|
-
// The name as
|
|
9
|
+
// The name as stored: a directory's with its slash
|
|
14
10
|
export const wireName = (entry) => (entry.type === 'directory' ? `${entry.name}/` : entry.name)
|
|
15
11
|
|
|
16
|
-
//
|
|
17
|
-
// target for a link, whatever the format allows.
|
|
12
|
+
// The fields both formats share, checked; `types` has a key for each type the format writes
|
|
18
13
|
export function checkEntry(entry, types) {
|
|
19
14
|
if (entry === null || typeof entry !== 'object') throw new ArchiveError('an entry is not an object')
|
|
20
15
|
const type = entry.type ?? 'file'
|
|
21
|
-
//
|
|
22
|
-
// writes, and everything after compares `type` as the string it is not.
|
|
16
|
+
// Before Object.hasOwn, which would take anything that stringifies to a type
|
|
23
17
|
if (typeof type !== 'string') throw new ArchiveError('entry type is not a string')
|
|
24
18
|
if (!Object.hasOwn(types, type)) throw new ArchiveError(`entry type ${quote(type)} is not one this package writes`)
|
|
25
19
|
const { name } = entry
|
package/src/error.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown on anything refused, by a reader or a writer
|
|
3
|
+
*/
|
|
4
|
+
export class ArchiveError extends Error {
|
|
5
|
+
constructor(detail: string, offset?: number, options?: { limited?: boolean });
|
|
6
|
+
/** Byte offset in the archive where a reader gave up; unset from a writer */
|
|
7
|
+
offset: number | undefined;
|
|
8
|
+
/** Whether a bound the caller set stopped it, rather than anything wrong with the input */
|
|
9
|
+
limited: boolean;
|
|
10
|
+
}
|
package/src/error.js
CHANGED
|
@@ -1,18 +1,14 @@
|
|
|
1
|
-
// `offset` is where in the archive the reader gave up, in bytes; the
|
|
2
|
-
// writer leaves it unset. `limited` is true where a bound the caller set
|
|
3
|
-
// stopped it, rather than anything wrong with the archive.
|
|
4
1
|
export class ArchiveError extends Error {
|
|
5
2
|
constructor(detail, offset, { limited = false } = {}) {
|
|
6
3
|
super(offset === undefined ? detail : `${detail} at byte ${offset}`)
|
|
7
4
|
this.name = 'ArchiveError'
|
|
8
|
-
this.offset = offset
|
|
9
|
-
this.limited = limited
|
|
5
|
+
this.offset = offset // where a reader gave up, unset from a writer
|
|
6
|
+
this.limited = limited // a bound the caller set, not bad input
|
|
10
7
|
}
|
|
11
8
|
}
|
|
12
9
|
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
// goes on as it was, rather than dressed up as bad input.
|
|
10
|
+
// Places a refusal from a check that does not know where in the archive it runs.
|
|
11
|
+
// Anything else, a bug above all, is rethrown as is rather than dressed up as bad input.
|
|
16
12
|
export function located(fn, at) {
|
|
17
13
|
try {
|
|
18
14
|
return fn()
|
package/src/names.js
CHANGED
|
@@ -1,93 +1,51 @@
|
|
|
1
|
-
// Name safety, applied before writing an entry and before handing one out
|
|
2
|
-
// of an archive. A name is a relative path: `.` segments and a directory's
|
|
3
|
-
// trailing slash are dropped, and what is left has no empty or `..`
|
|
4
|
-
// segment, no control character and no backslash -- a separator on
|
|
5
|
-
// Windows, where `..\` would get past the check on `..` -- and does not
|
|
6
|
-
// start with a drive letter and colon, which Windows resolves from that
|
|
7
|
-
// drive rather than from the archive. A symlink target may use `..`, but
|
|
8
|
-
// is followed from where the link sits and refused if it climbs above the
|
|
9
|
-
// archive or passes through anything but a directory, which is how a
|
|
10
|
-
// chain of links would climb. A caller may let a relative target climb up
|
|
11
|
-
// to a number of levels above the archive's root, as a directory archived
|
|
12
|
-
// on its own links to the files of the tree it was cut from: past the root
|
|
13
|
-
// the archive cannot tell where a target leads -- not even back into
|
|
14
|
-
// itself, by the name it is extracted under -- so what it passes through
|
|
15
|
-
// there is the caller's to know. An absolute target is refused regardless.
|
|
16
|
-
// A hard link to a symlink, directly or down a chain of hard links, is a
|
|
17
|
-
// second name for it, and is held to the same walk from where that name
|
|
18
|
-
// sits, since a target safe under `a/b/` need not be safe at the root.
|
|
19
|
-
// Lengths are bounded by what a filesystem takes at all: PATH_MAX for the
|
|
20
|
-
// whole as the archive stores it, a directory's slash counted, and NAME_MAX
|
|
21
|
-
// for a segment, in bytes.
|
|
22
|
-
//
|
|
23
|
-
// A name may repeat only as the same entry again, field for field and byte
|
|
24
|
-
// for byte (some npm packagers write `d/f` and `d/./f` both): two different
|
|
25
|
-
// entries under one name would leave the winner to extraction order.
|
|
26
|
-
// Collisions a filesystem might add -- case, Unicode normalisation -- are
|
|
27
|
-
// the filesystem's, not the archive's, and are not looked for.
|
|
28
|
-
|
|
29
1
|
import { sameBytes } from './bytes.js'
|
|
30
2
|
import { ArchiveError } from './error.js'
|
|
31
3
|
import { checkString, hasUnsafe, quote, tooLong } from './text.js'
|
|
32
4
|
|
|
33
|
-
const PATH_MAX = 4096
|
|
34
|
-
const NAME_MAX = 255
|
|
5
|
+
const PATH_MAX = 4096 // bytes of the name as stored, a directory's slash counted
|
|
6
|
+
const NAME_MAX = 255 // bytes of a segment
|
|
35
7
|
|
|
36
|
-
// The rules
|
|
37
|
-
// segments, split the once.
|
|
8
|
+
// The rules for any path, a symlink target's too
|
|
38
9
|
function checkText(path, what) {
|
|
39
10
|
checkString(path, what)
|
|
40
11
|
if (path === '') throw new ArchiveError(`${what} is empty`)
|
|
12
|
+
// A backslash is a separator on Windows, where `..\` would pass the `..` check
|
|
41
13
|
if (hasUnsafe(path, true)) throw new ArchiveError(`${what} ${quote(path)} holds a control or formatting character, or a backslash`)
|
|
42
14
|
if (path.startsWith('/')) throw new ArchiveError(`${what} ${quote(path)} is absolute`)
|
|
43
15
|
const segments = path.split('/')
|
|
44
|
-
//
|
|
45
|
-
// that is not one is what a drive letter is looked for on.
|
|
16
|
+
// Windows resolves `C:x` from that drive, and `./C:x` is `C:x` once `.` is dropped
|
|
46
17
|
if (/^[a-zA-Z]:/u.test(segments.find((segment) => segment !== '.') ?? '')) throw new ArchiveError(`${what} ${quote(path)} starts with a drive letter`)
|
|
47
18
|
if (tooLong(path, PATH_MAX)) throw new ArchiveError(`${what} ${quote(path)} is longer than ${PATH_MAX} bytes`)
|
|
48
19
|
if (segments.some((segment) => tooLong(segment, NAME_MAX))) throw new ArchiveError(`${what} ${quote(path)} has a segment longer than ${NAME_MAX} bytes`)
|
|
49
20
|
return segments
|
|
50
21
|
}
|
|
51
22
|
|
|
52
|
-
//
|
|
53
|
-
// may name; it comes back as `.`. A path with nothing to drop comes back as
|
|
54
|
-
// the very string it came in as, so the name an archive stores and the one
|
|
55
|
-
// cleaned out of it are one string where they are one path.
|
|
23
|
+
// `.` segments and a directory's trailing slash dropped; only a directory may name the root, as `.`
|
|
56
24
|
export function cleanPath(path, what, directory = false) {
|
|
57
25
|
const segments = checkText(path, what)
|
|
58
|
-
|
|
59
|
-
if (slash) {
|
|
26
|
+
if (segments.at(-1) === '') {
|
|
60
27
|
if (!directory) throw new ArchiveError(`${what} ${quote(path)} ends in a slash but is not a directory`)
|
|
61
28
|
segments.pop()
|
|
62
29
|
}
|
|
63
30
|
const kept = segments.filter((segment) => segment !== '.')
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (segment === '..') throw new ArchiveError(`${what} ${quote(path)} has a .. segment`)
|
|
67
|
-
}
|
|
31
|
+
const bad = kept.find((segment) => segment === '' || segment === '..')
|
|
32
|
+
if (bad !== undefined) throw new ArchiveError(`${what} ${quote(path)} has ${bad ? 'a .. segment' : 'an empty segment'}`)
|
|
68
33
|
if (kept.length === 0) {
|
|
69
34
|
if (!directory) throw new ArchiveError(`${what} ${quote(path)} names the archive root but is not a directory`)
|
|
70
35
|
return '.'
|
|
71
36
|
}
|
|
72
|
-
const name =
|
|
73
|
-
// As the archive stores it, a directory's name carries its slash: what
|
|
74
|
-
// pack takes, unpack then reads.
|
|
37
|
+
const name = kept.join('/')
|
|
75
38
|
if (tooLong(name, PATH_MAX - (directory ? 1 : 0))) throw new ArchiveError(`${what} ${quote(path)} is longer than ${PATH_MAX} bytes`)
|
|
76
39
|
return name
|
|
77
40
|
}
|
|
78
41
|
|
|
79
|
-
// The levels above the archive's root a caller lets a symlink target climb
|
|
80
|
-
// (`symlinksAbove`): none unless given.
|
|
81
42
|
export function levelsAbove(above = 0) {
|
|
82
43
|
if (!(Number.isSafeInteger(above) && above >= 0)) throw new ArchiveError(`symlinksAbove ${String(above)} is not a whole number of levels`)
|
|
83
44
|
return above
|
|
84
45
|
}
|
|
85
46
|
|
|
86
|
-
//
|
|
87
|
-
// the
|
|
88
|
-
// steps: each segment it goes into, or `..` to come back out of one. The
|
|
89
|
-
// walk is counted rather than spelled out, since spelling out the path at
|
|
90
|
-
// every step of a deep one costs its depth squared.
|
|
47
|
+
// The target's steps from the link's directory, each a segment or `..`, climbing at most `above` levels
|
|
48
|
+
// above the root. Counted rather than spelled out, which would cost a deep walk its depth squared.
|
|
91
49
|
export function checkSymlinkTarget(name, target, above = 0) {
|
|
92
50
|
const steps = checkText(target, `symlink target of ${quote(name)}`).filter((segment) => segment !== '' && segment !== '.')
|
|
93
51
|
let depth = name.split('/').length - 1
|
|
@@ -101,86 +59,54 @@ export function checkSymlinkTarget(name, target, above = 0) {
|
|
|
101
59
|
return steps
|
|
102
60
|
}
|
|
103
61
|
|
|
104
|
-
//
|
|
62
|
+
// A symlink's target is checked, never rewritten; a hard link's is a name, cleaned as one
|
|
105
63
|
export function cleanNames(path, type, target, above = 0) {
|
|
106
64
|
const name = cleanPath(path, 'entry name', type === 'directory')
|
|
107
|
-
let linkname = target
|
|
108
65
|
if (type === 'symlink') checkSymlinkTarget(name, target, above)
|
|
109
|
-
|
|
110
|
-
return { name, linkname }
|
|
66
|
+
return { name, linkname: type === 'hardlink' ? cleanPath(target, `hard link target of ${quote(name)}`) : target }
|
|
111
67
|
}
|
|
112
68
|
|
|
113
69
|
const node = () => ({ kind: undefined, entry: undefined, symlink: undefined, first: undefined, firstNode: undefined, rest: undefined })
|
|
114
70
|
|
|
115
|
-
// A node's first child sits on the node
|
|
116
|
-
//
|
|
117
|
-
// one thing each, and a map at every link of it would cost more than the
|
|
118
|
-
// link. With `make` false, a missing child stays missing.
|
|
71
|
+
// A node's first child sits on the node and only a second brings a Map: a deep path is a chain of
|
|
72
|
+
// directories holding one thing each, where a Map at every link would cost more than the link.
|
|
119
73
|
function child(parent, segment, make = true) {
|
|
120
74
|
if (parent.first === segment) return parent.firstNode
|
|
121
75
|
let next = parent.rest?.get(segment)
|
|
122
76
|
if (next !== undefined || !make) return next
|
|
123
77
|
next = node()
|
|
124
|
-
if (parent.first === undefined) {
|
|
125
|
-
|
|
126
|
-
parent.firstNode = next
|
|
127
|
-
} else {
|
|
128
|
-
parent.rest ??= new Map()
|
|
129
|
-
parent.rest.set(segment, next)
|
|
130
|
-
}
|
|
78
|
+
if (parent.first === undefined) Object.assign(parent, { first: segment, firstNode: next })
|
|
79
|
+
else (parent.rest ??= new Map()).set(segment, next)
|
|
131
80
|
return next
|
|
132
81
|
}
|
|
133
82
|
|
|
134
83
|
const FIELDS = ['type', 'mode', 'uid', 'gid', 'mtime', 'uname', 'gname', 'linkname', 'devmajor', 'devminor']
|
|
135
84
|
|
|
136
|
-
// Each
|
|
137
|
-
//
|
|
138
|
-
//
|
|
139
|
-
// refused -- that is the shape of a path through a symlink -- and so is a
|
|
140
|
-
// symlink target that walks through one, in either order, so no chain of
|
|
141
|
-
// links leads out of the archive; where `above` lets a target climb out, a
|
|
142
|
-
// chain can only end at the link that does, so it climbs no further. Whether
|
|
143
|
-
// entries are kept with their data decides what a repeat can be compared
|
|
144
|
-
// with: the in-memory calls keep them, and a stream keeps the fields alone
|
|
145
|
-
// and refuses what it cannot compare.
|
|
146
|
-
//
|
|
147
|
-
// The names are a tree walked a segment at a time, so a lookup hashes one
|
|
148
|
-
// segment rather than a whole path, and a walk down a deep one costs its
|
|
149
|
-
// length rather than its depth squared; a path is spelled out only for a
|
|
150
|
-
// refusal. A node's `kind` is unset until its path is seen, which makes the
|
|
151
|
-
// tree hold exactly what a map from each path seen to its kind would.
|
|
85
|
+
// Each path seen is an 'entry', a 'directory', or a directory 'implied' by a path or symlink target through it.
|
|
86
|
+
// Nothing may sit or be walked through inside a non-directory, so no chain of links leads out of the archive.
|
|
87
|
+
// A name repeats only as the same entry; `keep` keeps data to compare a repeat with, else it is refused.
|
|
152
88
|
export class Names {
|
|
153
89
|
#root = node()
|
|
154
90
|
#keep
|
|
155
91
|
#above
|
|
156
92
|
|
|
157
|
-
|
|
158
|
-
constructor(keep = false, above = 0) {
|
|
93
|
+
constructor(keep = false, symlinksAbove = 0) {
|
|
159
94
|
this.#keep = keep
|
|
160
|
-
this.#above =
|
|
95
|
+
this.#above = levelsAbove(symlinksAbove)
|
|
161
96
|
}
|
|
162
97
|
|
|
163
|
-
// The levels a symlink target may climb above the root, for cleanNames.
|
|
164
98
|
get above() {
|
|
165
99
|
return this.#above
|
|
166
100
|
}
|
|
167
101
|
|
|
168
|
-
// `entry` is cleaned
|
|
102
|
+
// `entry` is cleaned
|
|
169
103
|
add(entry) {
|
|
170
104
|
const { name, type } = entry
|
|
171
|
-
// The target of the symlink this entry is, if it is one: a symlink's
|
|
172
|
-
// own, or, for a hard link, that of the entry it links to.
|
|
173
105
|
let symlink = type === 'symlink' ? entry.linkname : undefined
|
|
174
106
|
if (type === 'hardlink') {
|
|
175
107
|
const target = this.#find(entry.linkname)
|
|
176
108
|
if (target?.kind !== 'entry') throw new ArchiveError(`hard link ${quote(name)} targets ${quote(entry.linkname)}, which is not an earlier non-directory entry`)
|
|
177
|
-
// A hard link to a symlink is
|
|
178
|
-
// relative target is followed from wherever it is reached: `../x` under
|
|
179
|
-
// `a/b/` stays inside, the same link at the root does not. So the
|
|
180
|
-
// target is walked again from here, as if the symlink sat at this name.
|
|
181
|
-
// A hard link to such a hard link is the same symlink again, so the
|
|
182
|
-
// target travels down a chain of them, rather than the chain being
|
|
183
|
-
// followed back, which would cost each new link the chain's length.
|
|
109
|
+
// A hard link to a symlink is that symlink again at this name, where its target is walked again
|
|
184
110
|
symlink = target.symlink
|
|
185
111
|
if (symlink !== undefined) this.#symlink(name, symlink, `hard link ${quote(name)} to symlink ${quote(entry.linkname)}`)
|
|
186
112
|
}
|
|
@@ -196,8 +122,6 @@ export class Names {
|
|
|
196
122
|
}
|
|
197
123
|
const kind = type === 'directory' ? 'directory' : 'entry'
|
|
198
124
|
if (seen.kind !== undefined && kind !== 'directory') throw new ArchiveError(`${quote(name)} is already a directory, so it cannot be a ${type}`)
|
|
199
|
-
// Every parent, the outermost first; nodes[0] is the root, which no
|
|
200
|
-
// name has as a parent.
|
|
201
125
|
for (let i = 1; i < segments.length; i++) {
|
|
202
126
|
this.#directory(nodes[i], () => `${quote(name)} is inside ${quote(segments.slice(0, i).join('/'))}, which is not a directory`)
|
|
203
127
|
}
|
|
@@ -207,11 +131,8 @@ export class Names {
|
|
|
207
131
|
if (type === 'symlink') this.#symlink(name, entry.linkname, `symlink ${quote(name)}`)
|
|
208
132
|
}
|
|
209
133
|
|
|
210
|
-
//
|
|
211
|
-
//
|
|
212
|
-
// inside it has to be a directory -- each one it stands on short of the
|
|
213
|
-
// last step, the archive root aside. Out of it, nothing it passes is the
|
|
214
|
-
// archive's. `what` names it in a refusal.
|
|
134
|
+
// Every path the target stands on inside the archive short of its last step has to be a directory.
|
|
135
|
+
// Past the root nothing it passes is the archive's.
|
|
215
136
|
#symlink(at, target, what) {
|
|
216
137
|
const steps = checkSymlinkTarget(at, target, this.#above)
|
|
217
138
|
const path = at.split('/').slice(0, -1)
|
|
@@ -229,28 +150,19 @@ export class Names {
|
|
|
229
150
|
}
|
|
230
151
|
}
|
|
231
152
|
|
|
232
|
-
//
|
|
233
|
-
// `refusal` spells the path out, and only if it has to.
|
|
153
|
+
// `refusal` spells the path out only when it has to
|
|
234
154
|
#directory(at, refusal) {
|
|
235
155
|
if (at.kind === 'entry') throw new ArchiveError(refusal())
|
|
236
156
|
at.kind ??= 'implied'
|
|
237
157
|
}
|
|
238
158
|
|
|
239
|
-
// The root and the node of each segment in turn, made where missing: a
|
|
240
|
-
// node made here is unseen until something sets its kind.
|
|
241
159
|
#walk(segments) {
|
|
242
160
|
const nodes = [this.#root]
|
|
243
161
|
for (const segment of segments) nodes.push(child(nodes.at(-1), segment))
|
|
244
162
|
return nodes
|
|
245
163
|
}
|
|
246
164
|
|
|
247
|
-
// A path's node where it has one, without making any.
|
|
248
165
|
#find(path) {
|
|
249
|
-
|
|
250
|
-
for (const segment of path.split('/')) {
|
|
251
|
-
at = child(at, segment, false)
|
|
252
|
-
if (at === undefined) return undefined
|
|
253
|
-
}
|
|
254
|
-
return at
|
|
166
|
+
return path.split('/').reduce((at, segment) => at && child(at, segment, false), this.#root)
|
|
255
167
|
}
|
|
256
168
|
}
|