@preventive/archive 1.4.1 → 1.6.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/compression.d.ts CHANGED
@@ -12,48 +12,40 @@ import { ArchiveError } from './src/error.js';
12
12
 
13
13
  export { ArchiveError };
14
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;
21
-
15
+ /** Options for `compress()` and `decompress()` */
22
16
  export interface Options {
23
17
  /** Most bytes of output; past it, rejects with `limited` set (default: no limit) */
24
18
  limit?: number;
25
19
  }
26
20
 
21
+ /**
22
+ * Whether this runtime can both compress and decompress a format
23
+ *
24
+ * @param format - `'gzip'`, `'deflate'` and `'deflate-raw'` are everywhere, `'brotli'` on some runtimes
25
+ */
26
+ export function supports(format: string): boolean;
27
+
27
28
  /**
28
29
  * Compress bytes
29
30
  *
30
- * @param bytes - The input
31
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
32
  */
35
33
  export function compress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>;
36
34
 
37
35
  /**
38
36
  * Decompress bytes
39
37
  *
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.
38
+ * Zeros after gzip's last member are passed over as padding, as gzip(1) does; nothing else after the end is.
42
39
  *
43
- * @param bytes - The input
44
40
  * @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
41
  */
48
42
  export function decompress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>;
49
43
 
50
- /**
51
- * What a stream refused
52
- */
44
+ /** What `compress()` and `decompress()` reject with where the stream fails or the output passes `limit` */
53
45
  export class CompressionError extends ArchiveError {
54
46
  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 */
47
+ /** The output made before the failure */
56
48
  bytes: Uint8Array;
57
- /** The platform's error */
49
+ /** The platform's error, unless `limited` */
58
50
  cause: unknown;
59
51
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/archive",
3
- "version": "1.4.1",
3
+ "version": "1.6.0",
4
4
  "description": "Strict in-memory tar and zip on browser APIs",
5
5
  "type": "module",
6
6
  "exports": {
@@ -22,8 +22,8 @@ function checkBytes(bytes) {
22
22
  if (!(bytes instanceof Uint8Array)) throw new ArchiveError('the data is not a Uint8Array')
23
23
  }
24
24
 
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.
25
+ // A NaN `limit` refuses all. Given `target`, output is written into it while it fits, rather than
26
+ // gathered in pieces and joined, which holds it twice.
27
27
  async function through(bytes, Stream, format, limit, verb, target) {
28
28
  const transform = new Stream(format) // a format the runtime lacks rejects with the platform's error
29
29
  const writer = transform.writable.getWriter()
@@ -90,5 +90,4 @@ export async function decompress(bytes, format, { limit = Infinity } = {}) {
90
90
  }
91
91
  }
92
92
 
93
- // Bounded by and made into `into`, for zip's entries, which declare their size
94
93
  export const decompressInto = (bytes, format, into) => through(bytes, DecompressionStream, format, into.length, 'decompress', into)
package/src/entry.js CHANGED
@@ -6,10 +6,9 @@ export const DEFAULT_MODE = { file: 0o644, directory: 0o755, symlink: 0o777 }
6
6
 
7
7
  export const isFile = (type) => type === 'file' || type === 'contiguous-file'
8
8
 
9
- // The name as stored: a directory's with its slash
10
9
  export const wireName = (entry) => (entry.type === 'directory' ? `${entry.name}/` : entry.name)
11
10
 
12
- // The fields both formats share, checked; `types` has a key for each type the format writes
11
+ // `types` has a key for each type the format writes
13
12
  export function checkEntry(entry, types) {
14
13
  if (entry === null || typeof entry !== 'object') throw new ArchiveError('an entry is not an object')
15
14
  const type = entry.type ?? 'file'
package/src/error.d.ts CHANGED
@@ -1,9 +1,7 @@
1
- /**
2
- * Thrown on anything refused, by a reader or a writer
3
- */
1
+ /** Thrown on anything refused, by a reader or a writer */
4
2
  export class ArchiveError extends Error {
5
3
  constructor(detail: string, offset?: number, options?: { limited?: boolean });
6
- /** Byte offset in the archive where a reader gave up; unset from a writer */
4
+ /** Byte offset in the archive where a reader gave up, if it gave up at one; unset from a writer */
7
5
  offset: number | undefined;
8
6
  /** Whether a bound the caller set stopped it, rather than anything wrong with the input */
9
7
  limited: boolean;
package/src/error.js CHANGED
@@ -2,13 +2,12 @@ export class ArchiveError extends Error {
2
2
  constructor(detail, offset, { limited = false } = {}) {
3
3
  super(offset === undefined ? detail : `${detail} at byte ${offset}`)
4
4
  this.name = 'ArchiveError'
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
5
+ this.offset = offset
6
+ this.limited = limited
7
7
  }
8
8
  }
9
9
 
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.
10
+ // Anything but an unplaced refusal, a bug above all, is rethrown as is rather than dressed up as bad input
12
11
  export function located(fn, at) {
13
12
  try {
14
13
  return fn()
package/src/names.js CHANGED
@@ -5,7 +5,6 @@ import { checkString, hasUnsafe, quote, tooLong } from './text.js'
5
5
  const PATH_MAX = 4096 // bytes of the name as stored, a directory's slash counted
6
6
  const NAME_MAX = 255 // bytes of a segment
7
7
 
8
- // The rules for any path, a symlink target's too
9
8
  function checkText(path, what) {
10
9
  checkString(path, what)
11
10
  if (path === '') throw new ArchiveError(`${what} is empty`)
@@ -13,21 +12,22 @@ function checkText(path, what) {
13
12
  if (hasUnsafe(path, true)) throw new ArchiveError(`${what} ${quote(path)} holds a control or formatting character, or a backslash`)
14
13
  if (path.startsWith('/')) throw new ArchiveError(`${what} ${quote(path)} is absolute`)
15
14
  const segments = path.split('/')
16
- // Windows resolves `C:x` from that drive, and `./C:x` is `C:x` once `.` is dropped
17
- if (/^[a-zA-Z]:/u.test(segments.find((segment) => segment !== '.') ?? '')) throw new ArchiveError(`${what} ${quote(path)} starts with a drive letter`)
15
+ // Windows resolves `C:x` from that drive, and `./C:x` or `.//C:x` is `C:x` once `.` and empty segments are dropped
16
+ if (/^[a-zA-Z]:/u.test(segments.find((segment) => segment !== '.' && segment !== '') ?? '')) throw new ArchiveError(`${what} ${quote(path)} starts with a drive letter`)
18
17
  if (tooLong(path, PATH_MAX)) throw new ArchiveError(`${what} ${quote(path)} is longer than ${PATH_MAX} bytes`)
19
18
  if (segments.some((segment) => tooLong(segment, NAME_MAX))) throw new ArchiveError(`${what} ${quote(path)} has a segment longer than ${NAME_MAX} bytes`)
20
19
  return segments
21
20
  }
22
21
 
23
- // `.` segments and a directory's trailing slash dropped; only a directory may name the root, as `.`
24
- export function cleanPath(path, what, directory = false) {
22
+ // With `empty`, an empty segment, as in `a//b`, is dropped as a `.` one is: extracting resolves it away, but
23
+ // stripping a leading directory off the name as stored does not, so it is for a caller to ask for
24
+ export function cleanPath(path, what, directory = false, empty = false) {
25
25
  const segments = checkText(path, what)
26
26
  if (segments.at(-1) === '') {
27
27
  if (!directory) throw new ArchiveError(`${what} ${quote(path)} ends in a slash but is not a directory`)
28
28
  segments.pop()
29
29
  }
30
- const kept = segments.filter((segment) => segment !== '.')
30
+ const kept = segments.filter((segment) => segment !== '.' && !(empty && segment === ''))
31
31
  const bad = kept.find((segment) => segment === '' || segment === '..')
32
32
  if (bad !== undefined) throw new ArchiveError(`${what} ${quote(path)} has ${bad ? 'a .. segment' : 'an empty segment'}`)
33
33
  if (kept.length === 0) {
@@ -44,26 +44,24 @@ export function levelsAbove(above = 0) {
44
44
  return above
45
45
  }
46
46
 
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.
47
+ const isStep = (segment) => segment !== '' && segment !== '.'
48
+ const beyond = (above) => above === 0 ? 'outside the archive' : `more than ${above} level${above === 1 ? '' : 's'} above the archive`
49
+
50
+ // The depth is counted rather than the path spelled out, which would cost a deep walk its depth squared
49
51
  export function checkSymlinkTarget(name, target, above = 0) {
50
- const steps = checkText(target, `symlink target of ${quote(name)}`).filter((segment) => segment !== '' && segment !== '.')
52
+ const steps = checkText(target, `symlink target of ${quote(name)}`).filter(isStep)
51
53
  let depth = name.split('/').length - 1
52
54
  for (const step of steps) {
53
55
  depth += step === '..' ? -1 : 1
54
- if (depth < -above) {
55
- const how = above === 0 ? 'outside the archive' : `more than ${above} level${above === 1 ? '' : 's'} above the archive`
56
- throw new ArchiveError(`symlink ${quote(name)} points ${how}, to ${quote(target)}`)
57
- }
56
+ if (depth < -above) throw new ArchiveError(`symlink ${quote(name)} points ${beyond(above)}, to ${quote(target)}`)
58
57
  }
59
58
  return steps
60
59
  }
61
60
 
62
- // A symlink's target is checked, never rewritten; a hard link's is a name, cleaned as one
63
- export function cleanNames(path, type, target, above = 0) {
64
- const name = cleanPath(path, 'entry name', type === 'directory')
61
+ export function cleanNames(path, type, target, above = 0, empty = false) {
62
+ const name = cleanPath(path, 'entry name', type === 'directory', empty)
65
63
  if (type === 'symlink') checkSymlinkTarget(name, target, above)
66
- return { name, linkname: type === 'hardlink' ? cleanPath(target, `hard link target of ${quote(name)}`) : target }
64
+ return { name, linkname: type === 'hardlink' ? cleanPath(target, `hard link target of ${quote(name)}`, false, empty) : target }
67
65
  }
68
66
 
69
67
  const node = () => ({ kind: undefined, entry: undefined, symlink: undefined, first: undefined, firstNode: undefined, rest: undefined })
@@ -82,17 +80,40 @@ function child(parent, segment, make = true) {
82
80
 
83
81
  const FIELDS = ['type', 'mode', 'uid', 'gid', 'mtime', 'uname', 'gname', 'linkname', 'devmajor', 'devminor']
84
82
 
83
+ // Linux's ELOOP bound
84
+ const MAX_HOPS = 40
85
+ const RESOLVING = Symbol('resolving')
86
+
87
+ // Never changed, so a link's memoized end serves every walk through it
88
+ const place = (here, name, up) => ({ node: here, name, up, depth: up === undefined ? 0 : up.depth + 1 })
89
+
90
+ function pathOf(at) {
91
+ const names = []
92
+ for (let p = at; p.up !== undefined; p = p.up) names.push(p.name)
93
+ return names.toReversed().join('/')
94
+ }
95
+
96
+ // `through` is a non-directory, or a symlink that leads `to` one
97
+ function notDirectory(what, through, to) {
98
+ const which = to === undefined ? 'is' : `leads to ${quote(pathOf(to))},`
99
+ return new ArchiveError(`the target of ${what} passes through ${quote(pathOf(through))}, which ${which} not a directory`)
100
+ }
101
+
85
102
  // 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.
103
+ // Nothing may sit or be walked through inside a non-directory, so no chain of links leads out of the archive. With
104
+ // `chains` a target may pass through symlinks, as a macOS framework's do, and implies nothing: settle() follows it.
88
105
  export class Names {
89
106
  #root = node()
90
107
  #keep
91
108
  #above
109
+ #links
110
+ #resolved = new Map()
111
+ #resolving = 0
92
112
 
93
- constructor(keep = false, symlinksAbove = 0) {
113
+ constructor(keep = false, symlinksAbove = 0, chains = false) {
94
114
  this.#keep = keep
95
115
  this.#above = levelsAbove(symlinksAbove)
116
+ this.#links = chains ? [] : null
96
117
  }
97
118
 
98
119
  get above() {
@@ -113,6 +134,7 @@ export class Names {
113
134
  const segments = name.split('/')
114
135
  const nodes = this.#walk(segments)
115
136
  const seen = nodes.at(-1)
137
+ // A name repeats only as the same entry; `keep` keeps data to compare a repeat with
116
138
  if (seen.kind !== undefined && seen.kind !== 'implied') {
117
139
  const differs = FIELDS.find((field) => seen.entry[field] !== entry[field])
118
140
  if (differs !== undefined) throw new ArchiveError(`duplicate entry ${quote(name)} differs in ${differs}`)
@@ -131,10 +153,13 @@ export class Names {
131
153
  if (type === 'symlink') this.#symlink(name, entry.linkname, `symlink ${quote(name)}`)
132
154
  }
133
155
 
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.
156
+ // Past the root nothing the target passes is the archive's
136
157
  #symlink(at, target, what) {
137
158
  const steps = checkSymlinkTarget(at, target, this.#above)
159
+ if (this.#links !== null) {
160
+ this.#links.push({ at, what })
161
+ return
162
+ }
138
163
  const path = at.split('/').slice(0, -1)
139
164
  const nodes = this.#walk(path)
140
165
  for (const [i, step] of steps.entries()) {
@@ -150,6 +175,63 @@ export class Names {
150
175
  }
151
176
  }
152
177
 
178
+ settle() {
179
+ for (const { at, what } of this.#links ?? []) {
180
+ let link = place(this.#root)
181
+ for (const name of at.split('/')) link = place(child(link.node, name), name, link)
182
+ this.#resolve(link, what)
183
+ }
184
+ }
185
+
186
+ // Memoized by link: no name passes through one, so each sits at one place
187
+ #resolve(link, what) {
188
+ const known = this.#resolved.get(link.node)
189
+ if (known === RESOLVING) throw new ArchiveError(`${what} leads through a loop of symlinks`)
190
+ if (known !== undefined) return known
191
+ // Each nested resolve is a link the outermost passes: refused before the stack is spent
192
+ if (this.#resolving > MAX_HOPS) throw new ArchiveError(`${what} leads through more than ${MAX_HOPS} symlinks`)
193
+ this.#resolved.set(link.node, RESOLVING)
194
+ this.#resolving++
195
+ try {
196
+ const end = this.#follow(link.up, link.node.symlink.split('/').filter(isStep), what)
197
+ this.#resolved.set(link.node, end)
198
+ return end
199
+ } finally {
200
+ this.#resolving--
201
+ }
202
+ }
203
+
204
+ // Levels counted as checkSymlinkTarget counts them; past the root nothing is the archive's, and `at` is undefined
205
+ #follow(from, steps, what) {
206
+ let at = from
207
+ let depth = from.depth
208
+ let hops = 0
209
+ for (const [i, step] of steps.entries()) {
210
+ if (step === '..') {
211
+ depth -= 1
212
+ if (depth < -this.#above) throw new ArchiveError(`${what} leads ${beyond(this.#above)} through the symlinks it passes`)
213
+ at = at?.up
214
+ continue
215
+ }
216
+ depth += 1
217
+ if (at === undefined) continue
218
+ const next = place(child(at.node, step, false) ?? node(), step, at)
219
+ if (next.node.symlink === undefined) {
220
+ if (next.node.kind === 'entry' && i < steps.length - 1) throw notDirectory(what, next)
221
+ at = next
222
+ continue
223
+ }
224
+ const end = this.#resolve(next, what)
225
+ hops += end.hops + 1
226
+ if (hops > MAX_HOPS) throw new ArchiveError(`${what} leads through more than ${MAX_HOPS} symlinks`)
227
+ // A link may end at a file, but no step, `..` included, goes on from one
228
+ if (end.at?.node.kind === 'entry' && i < steps.length - 1) throw notDirectory(what, next, end.at)
229
+ at = end.at
230
+ depth = end.depth
231
+ }
232
+ return { at, depth, hops }
233
+ }
234
+
153
235
  // `refusal` spells the path out only when it has to
154
236
  #directory(at, refusal) {
155
237
  if (at.kind === 'entry') throw new ArchiveError(refusal())
package/src/tar/pack.js CHANGED
@@ -46,7 +46,7 @@ function normalize(entry, above) {
46
46
  }
47
47
  }
48
48
 
49
- // A copy in whole blocks; `length` may reach past `raw` to count a NUL
49
+ // `length` may reach past `raw` to count a NUL
50
50
  function padded(raw, length = raw.length) {
51
51
  const out = new Uint8Array(Math.ceil(length / BLOCK) * BLOCK)
52
52
  out.set(raw)
@@ -80,7 +80,6 @@ function splitName(raw, display) {
80
80
  return { prefix: raw.subarray(0, i), name: raw.subarray(i + 1) }
81
81
  }
82
82
 
83
- // Long-name blocks or a pax header, the header, the data and its padding.
84
83
  // Pax records go in GNU's order: linkpath, path, uid, gid, size, mtime, devmajor, devminor, uname, gname.
85
84
  function encodeEntry(e, format) {
86
85
  const gnu = format === 'gnu'
package/src/tar/unpack.js CHANGED
@@ -42,14 +42,13 @@ function headerName(header, at) {
42
42
  return header.prefix.length ? `${decodeUtf8(header.prefix, 'name prefix', at)}/${name}` : name
43
43
  }
44
44
 
45
- // Chunks in, entries out as each completes; the in-memory call and the stream share it
46
45
  class Unpacker {
47
46
  #chunks = [] // unread input, from #offset in the first
48
47
  #offset = 0
49
48
  #buffered = 0
50
49
  #position = 0 // in the archive, of the first byte unread
51
50
  #names
52
- #pending = { pax: null, longname: null, longlink: null } // extended headers awaiting their entry
51
+ #pending = { pax: null, longname: null, longlink: null }
53
52
  #extended = [] // each extended header since the last entry, as entries list them
54
53
  #global = null
55
54
  #awaiting = null // the header whose body is next: { at, size, entry } or { at, size, extended }
@@ -58,13 +57,16 @@ class Unpacker {
58
57
  #count = 0
59
58
  #maxEntries
60
59
  #trailingGlobal
60
+ #emptySegments
61
61
 
62
- constructor(keep, { symlinksAbove, maxEntries = Infinity, trailingGlobal = false } = {}) {
62
+ constructor(keep, { symlinksAbove, maxEntries = Infinity, trailingGlobal = false, emptySegments = false } = {}) {
63
63
  if (maxEntries !== Infinity && !(Number.isSafeInteger(maxEntries) && maxEntries >= 0)) throw new ArchiveError(`maxEntries ${String(maxEntries)} is not a whole number of entries`)
64
64
  if (typeof trailingGlobal !== 'boolean') throw new ArchiveError(`trailingGlobal ${String(trailingGlobal)} is not a boolean`)
65
+ if (typeof emptySegments !== 'boolean') throw new ArchiveError(`emptySegments ${String(emptySegments)} is not a boolean`)
65
66
  this.#names = new Names(keep, symlinksAbove)
66
67
  this.#maxEntries = maxEntries
67
68
  this.#trailingGlobal = trailingGlobal
69
+ this.#emptySegments = emptySegments
68
70
  }
69
71
 
70
72
  // Each entry as it is read, so a chunk holding many holds no more of them than the one being read
@@ -91,7 +93,7 @@ class Unpacker {
91
93
  throw new ArchiveError('the archive is truncated', this.#position)
92
94
  }
93
95
 
94
- // The next `size` bytes once all have arrived: a view where one chunk holds them, else a copy
96
+ // A view where one chunk holds all `size` bytes, else a copy
95
97
  #take(size) {
96
98
  if (this.#buffered < size) return null
97
99
  if (size === 0) return EMPTY
@@ -136,7 +138,6 @@ class Unpacker {
136
138
  }
137
139
  }
138
140
 
139
- // An entry's data, returning the entry, or an extended header's records
140
141
  #body(bytes) {
141
142
  const { at, size, entry, extended } = this.#awaiting
142
143
  this.#awaiting = null
@@ -160,7 +161,6 @@ class Unpacker {
160
161
  this.#extended.push(extended)
161
162
  }
162
163
 
163
- // The entry a header stands for, a pax record winning over the field it stands in for
164
164
  #resolve(header, at) {
165
165
  const type = TYPES.get(header.typeflag)
166
166
  if (type === undefined) throw new ArchiveError(`entry type ${quote(String.fromCodePoint(header.typeflag))} is not one this package reads`, at)
@@ -172,7 +172,7 @@ class Unpacker {
172
172
  if (longlink !== null && record('linkpath') !== undefined) throw new ArchiveError('both a long link header and a pax linkpath name one entry', at)
173
173
  const rawName = longname ?? record('path') ?? headerName(header, at)
174
174
  const rawTarget = longlink ?? record('linkpath') ?? decodeUtf8(header.linkname, 'link target', at)
175
- const { name, linkname } = located(() => cleanNames(rawName, type, rawTarget, this.#names.above), at)
175
+ const { name, linkname } = located(() => cleanNames(rawName, type, rawTarget, this.#names.above, this.#emptySegments), at)
176
176
  const number = (key, parse = paxNumber) => {
177
177
  const value = record(key)
178
178
  return value === undefined ? header[key] : parse(value, key, at)
package/src/zip/unzip.js CHANGED
@@ -33,7 +33,6 @@ function reader(bytes, base = 0) {
33
33
  }
34
34
  }
35
35
 
36
- // The archive a range at a time: views of it in memory, reads of just that range from a Blob
37
36
  function sourceOf(archive) {
38
37
  if (archive instanceof Uint8Array) {
39
38
  const whole = reader(archive)
@@ -200,9 +199,11 @@ async function entryOf(source, entry, names) {
200
199
  }
201
200
 
202
201
  // The layout is checked whole before the first entry is read
203
- async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep = false) {
202
+ async function* entries(source, { limit = Infinity, symlinksAbove, symlinkChains = false } = {}, keep = false) {
204
203
  if (limit !== Infinity && !(Number.isSafeInteger(limit) && limit >= 0)) throw new ArchiveError(`limit ${String(limit)} is not a whole number of bytes`)
205
- const names = new Names(keep, symlinksAbove)
204
+ if (typeof symlinkChains !== 'boolean') throw new ArchiveError(`symlinkChains ${String(symlinkChains)} is not a boolean`)
205
+ if (symlinkChains && !keep) throw new ArchiveError('symlinkChains is taken by unzip() alone, which answers no entry before every one is read')
206
+ const names = new Names(keep, symlinksAbove, symlinkChains)
206
207
  const { end, r } = await findEnd(source)
207
208
  const count = r.u16(end + 8)
208
209
  if (r.u16(end + 4) !== 0 || r.u16(end + 6) !== 0 || count !== r.u16(end + 10)) throw new ArchiveError('the archive spans several disks', end)
@@ -239,6 +240,7 @@ async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep =
239
240
  }
240
241
  if (expected !== start) throw new ArchiveError('bytes belong to no entry', expected)
241
242
  for (const entry of list) yield await entryOf(source, entry, names)
243
+ names.settle()
242
244
  }
243
245
 
244
246
  export async function unzip(bytes, options) {
package/tar.d.ts CHANGED
@@ -2,28 +2,19 @@
2
2
  * Strict in-memory tar, as GNU tar 1.35 writes it
3
3
  *
4
4
  * ```js
5
- * import { pack, unpack } from '@preventive/archive/tar.js'
6
- * import { packStream, unpackStream } from '@preventive/archive/tar.js'
5
+ * import { pack, packStream, unpack, unpackStream } from '@preventive/archive/tar.js'
7
6
  * ```
8
7
  *
9
- * Writing and reading refuse alike:
10
- * - a name that is not a clean relative path: absolute, with an empty or `..` segment, a drive letter,
11
- * a backslash, a control or bidi character, or over 4096 bytes (255 a segment)
12
- * - a name that repeats as anything but the same fields and data again
13
- * - an entry inside a non-directory
14
- * - a symlink whose target climbs above the root, past `symlinksAbove`, or passes through a non-directory
15
- * - a hard link to no earlier entry; a hard link to a symlink is held to that symlink's rules at its own name
8
+ * Writing and reading alike refuse, with an `ArchiveError`, anything unsafe to extract: a name that is not
9
+ * a clean relative path or repeats as a different entry, an entry inside a non-directory, a symlink that
10
+ * leads out of the archive, or a hard link to no earlier entry.
16
11
  *
17
12
  * @module @preventive/archive/tar.js
18
13
  */
19
14
 
20
15
  export { ArchiveError } from './src/error.js';
21
16
 
22
- /**
23
- * An entry's type, under tar-stream's names but for `'hardlink'` (its `'link'`)
24
- *
25
- * A `'contiguous-file'` is a file for every purpose here.
26
- */
17
+ /** An entry's type; a `'contiguous-file'` counts as a `'file'` */
27
18
  export type EntryType =
28
19
  | 'file'
29
20
  | 'directory'
@@ -35,61 +26,7 @@ export type EntryType =
35
26
  | 'contiguous-file';
36
27
 
37
28
  /**
38
- * An entry read from an archive: the fields of `EntryInput`, then what the archive stored
39
- */
40
- export interface Entry {
41
- /** Relative path with `.` segments and a trailing slash dropped, or `.` for the root directory */
42
- name: string;
43
- type: EntryType;
44
- /** Permission bits */
45
- mode: number;
46
- uid: number;
47
- gid: number;
48
- /** Whole seconds since the epoch */
49
- mtime: number;
50
- uname: string;
51
- gname: string;
52
- /** The target of a symlink, as stored, or of a hard link, cleaned as `name` is; else `''` */
53
- linkname: string;
54
- /** A device's numbers, else 0 */
55
- devmajor: number;
56
- devminor: number;
57
- /** A file's contents, else empty; a view of the input where one chunk held it whole */
58
- data: Uint8Array;
59
- /** `name` before cleaning, with any ustar prefix joined on */
60
- storedName: string;
61
- /** `linkname` before cleaning */
62
- storedLinkname: string;
63
- /**
64
- * The entry's own pax records, in stored order, read-only and shared by every entry without any.
65
- * A value no field is read from is unchecked and may hold any character.
66
- */
67
- pax: ReadonlyMap<string, string>;
68
- /** The global pax records in effect, shared by every entry under them; `pax` wins over these */
69
- globalPax: ReadonlyMap<string, string>;
70
- /** The extended headers since the previous entry, in stored order; frozen */
71
- extended: readonly ExtendedHeader[];
72
- /** The header's magic; under `'gnu'` there is no ustar name prefix */
73
- magic: 'ustar' | 'gnu';
74
- /** The header's type flag, such as `'\0'` or `'0'` for a `'file'` */
75
- typeflag: string;
76
- /** The header's mode, file type bits included */
77
- storedMode: number;
78
- /** Whether every number in the header is octal digits, as POSIX writes, rather than blank or GNU's base 256 */
79
- octal: boolean;
80
- }
81
-
82
- /**
83
- * A pax header of an entry's own, a global one, or GNU's long name or long link
84
- */
85
- export interface ExtendedHeader {
86
- kind: 'pax' | 'global' | 'longname' | 'longlink';
87
- magic: 'ustar' | 'gnu';
88
- octal: boolean;
89
- }
90
-
91
- /**
92
- * An entry to write; an `Entry` read is one to write as is, what it stored aside
29
+ * An entry to write; an `Entry` read is one, its other fields ignored
93
30
  *
94
31
  * `mode` defaults to 0o644 (0o755 for a directory, 0o777 for a symlink), owners to 0 with no names,
95
32
  * `mtime` to 0.
@@ -112,68 +49,117 @@ export interface EntryInput {
112
49
  devminor?: number;
113
50
  }
114
51
 
52
+ /** What writing and reading both take */
115
53
  export interface SymlinkOptions {
116
54
  /**
117
- * How many levels above the root a relative symlink target may climb (default: 0)
55
+ * How many levels above the root a symlink target may climb (default: 0)
118
56
  *
119
- * 1 lets `LICENSE -> ../../LICENSE` out of `packages/a/` archived under one top directory, as GitHub
120
- * archives a subtree. What a target passes through past the root is for the caller to trust.
57
+ * What a target passes through above the root is not checked: that is for the caller to trust.
121
58
  */
122
59
  symlinksAbove?: number;
123
60
  }
124
61
 
125
- /**
126
- * GNU tar's formats: `'gnu'`, as plain `tar` writes; `'ustar'`, refusing what it cannot hold; `'pax'`
127
- */
62
+ /** GNU tar's formats: `'gnu'`, as plain `tar` writes; `'ustar'`, refusing what it cannot hold; `'pax'` */
128
63
  export type Format = 'gnu' | 'ustar' | 'pax';
129
64
 
65
+ /** Options for `pack()` and `packStream()` */
130
66
  export interface PackOptions extends SymlinkOptions {
131
67
  /** Default: `'gnu'` */
132
68
  format?: Format;
133
- /** tar's `-b`: zeros to a multiple of this many 512-byte blocks (default: 20) */
69
+ /** tar's `-b`: the archive is padded to a multiple of this many 512-byte blocks (default: 20) */
134
70
  blocking?: number;
135
71
  }
136
72
 
73
+ /** Options for `unpack()` and `unpackStream()` */
137
74
  export interface UnpackOptions extends SymlinkOptions {
138
- /**
139
- * How many entries to read, each kind and repeat counted, extended headers not (default: no limit)
140
- *
141
- * Past it, throws with `limited` set at that entry's header.
142
- */
75
+ /** Most entries to read (default: no limit); past it, throws with `limited` set */
143
76
  maxEntries?: number;
144
77
  /** Take a global header with no entry after it as nothing, as GNU tar does (default: refused) */
145
78
  trailingGlobal?: boolean;
79
+ /**
80
+ * Take an empty segment in a name or a hard link's target, as in `a//b`, as none, as extracting resolves
81
+ * it (default: refused)
82
+ *
83
+ * Two names that differ in nothing else are then one name, held to repeat only as the same entry.
84
+ *
85
+ * Strip leading directories from `storedName`, not `name`: tar's `strip`, as npm and yarn extract a package
86
+ * with, splits the name as stored, so `a//b` is `/b` once `a` is stripped, which some extractors drop, and
87
+ * `a/b//c` is `/c` once two are.
88
+ */
89
+ emptySegments?: boolean;
90
+ }
91
+
92
+ /** A pax header of an entry's own, a global one, or GNU's long name or long link */
93
+ export interface ExtendedHeader {
94
+ kind: 'pax' | 'global' | 'longname' | 'longlink';
95
+ magic: 'ustar' | 'gnu';
96
+ octal: boolean;
97
+ }
98
+
99
+ /** An entry read: the fields of `EntryInput`, then what the archive stored */
100
+ export interface Entry {
101
+ /**
102
+ * Relative path with `.` segments, empty ones with `emptySegments`, and a trailing slash dropped, or `.`
103
+ * for the root directory
104
+ */
105
+ name: string;
106
+ type: EntryType;
107
+ /** Permission bits */
108
+ mode: number;
109
+ uid: number;
110
+ gid: number;
111
+ /** Whole seconds since the epoch */
112
+ mtime: number;
113
+ uname: string;
114
+ gname: string;
115
+ /** A symlink's target as stored, or a hard link's cleaned as `name` is; else `''` */
116
+ linkname: string;
117
+ /** A device's numbers, else 0 */
118
+ devmajor: number;
119
+ devminor: number;
120
+ /** A file's contents, else empty; a view of the input where one chunk held it whole */
121
+ data: Uint8Array;
122
+ /** `name` before cleaning, any ustar prefix joined on */
123
+ storedName: string;
124
+ /** `linkname` before cleaning */
125
+ storedLinkname: string;
126
+ /** The entry's own pax records, in stored order and read-only; a value no field is read from is unchecked */
127
+ pax: ReadonlyMap<string, string>;
128
+ /** The global pax records in effect, read-only; `pax` wins over these */
129
+ globalPax: ReadonlyMap<string, string>;
130
+ /** The extended headers since the previous entry, in stored order; frozen */
131
+ extended: readonly ExtendedHeader[];
132
+ /** `'ustar'` for a ustar or pax header */
133
+ magic: 'ustar' | 'gnu';
134
+ /** The header's type flag, such as `'\0'` or `'0'` for a `'file'` */
135
+ typeflag: string;
136
+ /** The header's mode, file type bits included */
137
+ storedMode: number;
138
+ /** Whether every number in the header is octal digits, rather than blank or base 256 */
139
+ octal: boolean;
146
140
  }
147
141
 
148
142
  /**
149
143
  * Write a tar archive
150
144
  *
151
- * Byte for byte what GNU tar writes with `--owner=0 --group=0 --numeric-owner` and, for pax,
152
- * `--pax-option=delete=atime,delete=ctime`; where it would cut or substitute, this refuses.
153
- *
154
- * @param entries - The entries, in order
155
- * @param options - Packing options
156
- * @returns The archive
145
+ * Byte for byte what GNU tar writes with `--owner=0 --group=0 --numeric-owner` (for pax, with no atime or
146
+ * ctime records), but refusing what tar would cut or substitute.
157
147
  */
158
148
  export function pack(entries: Iterable<EntryInput>, options?: PackOptions): Uint8Array;
159
149
 
160
150
  /**
161
151
  * Read a tar archive
162
152
  *
163
- * Takes the extended headers GNU tar writes and refuses sparse entries.
153
+ * Takes the extended headers GNU tar writes; refuses sparse entries.
164
154
  *
165
- * @param bytes - The archive
166
- * @param options - Unpacking options
167
- * @returns The entries, in order
155
+ * @returns The entries, in archive order
168
156
  */
169
157
  export function unpack(bytes: Uint8Array, options?: UnpackOptions): Entry[];
170
158
 
171
159
  /**
172
- * `pack()` a chunk at a time, each entry's `data` yielded as the same array
160
+ * `pack()` a chunk at a time
173
161
  *
174
- * @param entries - The entries, in order
175
- * @param options - Packing options
176
- * @returns The archive's chunks
162
+ * Each entry's `data` is yielded as the same array. A name may not repeat, even as the same entry.
177
163
  */
178
164
  export function packStream(
179
165
  entries: Iterable<EntryInput> | AsyncIterable<EntryInput>,
@@ -183,12 +169,7 @@ export function packStream(
183
169
  /**
184
170
  * `unpack()` an entry at a time, each yielded as it is read
185
171
  *
186
- * `data` is a view of a chunk wherever one holds it whole, so an archive in one chunk is not copied.
187
- * No entry's data is kept, so a name that repeats is refused: such an archive is for `unpack()`.
188
- *
189
- * @param chunks - The archive's chunks
190
- * @param options - Unpacking options
191
- * @returns The entries, in order
172
+ * A name may not repeat, even as the same entry.
192
173
  */
193
174
  export function unpackStream(
194
175
  chunks: Iterable<Uint8Array> | AsyncIterable<Uint8Array>,
package/zip.d.ts CHANGED
@@ -5,57 +5,18 @@
5
5
  * import { unzip, unzipStream, zip } from '@preventive/archive/zip.js'
6
6
  * ```
7
7
  *
8
- * Names and symlinks are held to the rules of `@preventive/archive/tar.js`. Neither writing nor reading
9
- * takes zip64, so an archive holds at most 65534 entries and stays under 4 GiB.
8
+ * Unsafe names and symlinks are refused with an `ArchiveError`, as in `@preventive/archive/tar.js`.
9
+ * No zip64: an archive holds at most 65534 entries and stays under 4 GiB.
10
10
  *
11
11
  * @module @preventive/archive/zip.js
12
12
  */
13
13
 
14
14
  export { ArchiveError } from './src/error.js';
15
15
 
16
- /**
17
- * A `'symlink'` is stored as Info-ZIP stores one: its target as data, its type in the Unix mode
18
- */
16
+ /** An entry's type; a `'symlink'` is stored as Info-ZIP stores one */
19
17
  export type EntryType = 'file' | 'directory' | 'symlink';
20
18
 
21
- /**
22
- * An entry read from an archive: the fields of `EntryInput`, then what the central directory stored
23
- */
24
- export interface Entry {
25
- /** Relative path with `.` segments and a trailing slash dropped, or `.` for the root directory */
26
- name: string;
27
- type: EntryType;
28
- /** Permission bits, or the default where the maker recorded none */
29
- mode: number;
30
- /** Whole seconds since the epoch: exact from an extended timestamp, else DOS time read as UTC */
31
- mtime: number;
32
- /** A symlink's target, as stored, else `''` */
33
- linkname: string;
34
- /** A file's contents, else empty; a view of the archive where stored and given as a `Uint8Array` */
35
- data: Uint8Array;
36
- /** `name` before cleaning */
37
- storedName: string;
38
- /** The maker's system, the upper byte of "version made by": 3 for Unix, whose alone `mode` is read */
39
- system: number;
40
- /** The version needed to extract */
41
- version: number;
42
- /** The general purpose bits */
43
- flags: number;
44
- internalAttributes: number;
45
- /** The external attributes */
46
- attributes: number;
47
- /** The extra fields, in stored order */
48
- extra: ExtraField[];
49
- }
50
-
51
- export interface ExtraField {
52
- id: number;
53
- data: Uint8Array;
54
- }
55
-
56
- /**
57
- * An entry to write; an `Entry` read is one to write as is, what it stored aside
58
- */
19
+ /** An entry to write; an `Entry` read is one, its other fields ignored */
59
20
  export interface EntryInput {
60
21
  /** Cleaned as `Entry.name`, so `./a` and `dir/` are taken; only a directory may end in a slash or be `.` */
61
22
  name: string;
@@ -64,62 +25,94 @@ export interface EntryInput {
64
25
  data?: Uint8Array;
65
26
  /** Default: 0o644, or 0o755 for a directory and 0o777 for a symlink */
66
27
  mode?: number;
67
- /** From 1980-01-01, the earliest DOS time and the default, to 2038-01-19, the latest extended timestamp */
28
+ /** Whole seconds since the epoch, from 1980-01-01 (the default) to 2038-01-19 */
68
29
  mtime?: number;
69
30
  /** A symlink's target */
70
31
  linkname?: string;
71
32
  }
72
33
 
34
+ /** What writing and reading both take */
73
35
  export interface SymlinkOptions {
74
- /** How many levels above the root a relative symlink target may climb, as in `tar.js` (default: 0) */
36
+ /** How many levels above the root a symlink target may climb, as in `tar.js` (default: 0) */
75
37
  symlinksAbove?: number;
76
38
  }
77
39
 
40
+ /** Options for `zip()` */
78
41
  export interface ZipOptions extends SymlinkOptions {
79
- /** `'deflate'` keeps a file deflated only where that is smaller, as Info-ZIP does (default); `'store'` does not */
42
+ /** `'deflate'` deflates a file where that makes it smaller, as Info-ZIP does (default); `'store'` never does */
80
43
  method?: 'deflate' | 'store';
81
44
  }
82
45
 
46
+ /** Options for `unzip()` and `unzipStream()` */
83
47
  export interface UnzipOptions extends SymlinkOptions {
84
48
  /**
85
- * How many bytes the entries may come to together, a symlink's target counted (default: no limit)
49
+ * Most bytes the entries may come to together, uncompressed (default: no limit)
86
50
  *
87
- * Each has to inflate to exactly its declared size, so this is checked before anything is inflated;
88
- * past it, rejects with `limited` set.
51
+ * Checked before anything is inflated; past it, rejects with `limited` set.
89
52
  */
90
53
  limit?: number;
54
+ /**
55
+ * Whether a symlink's target may pass through other symlinks, as a macOS framework's do (default: false)
56
+ *
57
+ * Each chain is followed once every entry is read, and held to the same rules. `unzipStream()` refuses this.
58
+ */
59
+ symlinkChains?: boolean;
60
+ }
61
+
62
+ /** An extra field of an entry's central directory record */
63
+ export interface ExtraField {
64
+ id: number;
65
+ data: Uint8Array;
66
+ }
67
+
68
+ /** An entry read: the fields of `EntryInput`, then what the central directory stored */
69
+ export interface Entry {
70
+ /** Relative path with `.` segments and a trailing slash dropped, or `.` for the root directory */
71
+ name: string;
72
+ type: EntryType;
73
+ /** Permission bits, or the default where the maker recorded none */
74
+ mode: number;
75
+ /** Whole seconds since the epoch: exact from an extended timestamp, else DOS time read as UTC */
76
+ mtime: number;
77
+ /** A symlink's target, as stored, else `''` */
78
+ linkname: string;
79
+ /** A file's contents, else empty; a view of the archive where stored and given as a `Uint8Array` */
80
+ data: Uint8Array;
81
+ /** `name` before cleaning */
82
+ storedName: string;
83
+ /** The maker's system: 3 for Unix, the only one whose `mode` is read */
84
+ system: number;
85
+ /** The version needed to extract */
86
+ version: number;
87
+ /** The general purpose bits */
88
+ flags: number;
89
+ internalAttributes: number;
90
+ /** The external attributes */
91
+ attributes: number;
92
+ /** In stored order */
93
+ extra: ExtraField[];
91
94
  }
92
95
 
93
96
  /**
94
97
  * Write a zip archive
95
- *
96
- * @param entries - The entries, in order
97
- * @param options - Zip options
98
- * @returns The archive
99
98
  */
100
99
  export function zip(entries: Iterable<EntryInput>, options?: ZipOptions): Promise<Uint8Array>;
101
100
 
102
101
  /**
103
102
  * Read a zip archive
104
103
  *
105
- * Every header, size and checksum is checked against every other, and the entries have to tile the archive.
106
- * An entry with a Unicode path extra field, a second name other readers take over its own, is refused.
104
+ * Takes unencrypted stored or deflated entries alone, and refuses an archive whose headers, sizes or CRCs
105
+ * disagree, or with bytes outside its entries.
107
106
  *
108
- * @param bytes - The archive
109
- * @param options - Unzip options
110
107
  * @returns The entries, in central directory order
111
108
  */
112
109
  export function unzip(bytes: Uint8Array, options?: UnzipOptions): Promise<Entry[]>;
113
110
 
114
111
  /**
115
- * `unzip()` an entry at a time, over the archive in memory or a `Blob` read a range at a time
112
+ * `unzip()` an entry at a time, from bytes or a `Blob` read a range at a time
116
113
  *
117
- * From a `Blob`, such as a `File` or `fs.openAsBlob()`, no more is held than the names and the entry at hand.
118
- * The layout is checked before the first entry, each entry's contents as it is reached. No entry's data is
119
- * kept, so a name that repeats is refused: such an archive is for `unzip()`.
120
- *
121
- * @param archive - The archive
122
- * @param options - Unzip options
123
- * @returns The entries, in central directory order
114
+ * From a `Blob`, such as a `File`, no more is held than the central directory and the entry at hand. The
115
+ * layout is checked before the first entry, each entry's data as it is reached. A name may not repeat,
116
+ * even as the same entry.
124
117
  */
125
118
  export function unzipStream(archive: Uint8Array | Blob, options?: UnzipOptions): AsyncGenerator<Entry, void, undefined>;