@preventive/archive 1.0.0-beta.4 → 1.1.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
@@ -13,14 +13,19 @@ export interface Options {
13
13
  limit?: number
14
14
  }
15
15
 
16
- // The whole input through one stream, the whole output back.
16
+ // The whole input through one stream, the whole output back. gzip is
17
+ // decompressed past zero bytes after its last member, as gzip(1) and zlib
18
+ // take them for padding, where the platform's stream refuses them; nothing
19
+ // else after the end is passed over.
17
20
  export function compress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>
18
21
  export function decompress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>
19
22
 
20
23
  // `offset` is where in the archive the reader gave up; unset here.
24
+ // `limited` is true where a bound the caller set stopped it.
21
25
  export class ArchiveError extends Error {
22
- constructor(detail: string, offset?: number)
26
+ constructor(detail: string, offset?: number, options?: { limited?: boolean })
23
27
  offset: number | undefined
28
+ limited: boolean
24
29
  }
25
30
 
26
31
  // What a stream refused: `bytes` is what it had put out by then, kept for a
package/compression.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // The compression front door of @preventive/archive, reached as
2
2
  // `@preventive/archive/compression.js`: bytes through the platform's
3
3
  // CompressionStream and DecompressionStream, whole, with an output bound,
4
- // and with what came out before a failure kept on the error. The zip half
5
- // deflates through the same code.
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
6
  export { CompressionError, compress, decompress, supports } from './src/compression.js'
7
7
  export { ArchiveError } from './src/error.js'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/archive",
3
- "version": "1.0.0-beta.4",
3
+ "version": "1.1.0",
4
4
  "description": "Strict in-memory tar and zip on browser APIs",
5
5
  "type": "module",
6
6
  "exports": {
@@ -8,10 +8,9 @@ import { ArchiveError } from './error.js'
8
8
 
9
9
  export class CompressionError extends ArchiveError {
10
10
  constructor(detail, { bytes, limited = false, cause }) {
11
- super(detail)
11
+ super(detail, undefined, { limited })
12
12
  this.name = 'CompressionError'
13
13
  this.bytes = bytes
14
- this.limited = limited
15
14
  this.cause = cause
16
15
  }
17
16
  }
@@ -79,7 +78,37 @@ async function through(bytes, Stream, format, limit, verb, into) {
79
78
  }
80
79
 
81
80
  export const compress = (bytes, format, { limit = Infinity } = {}) => through(bytes, CompressionStream, format, limit, 'compress')
82
- export const decompress = (bytes, format, { limit = Infinity } = {}) => through(bytes, DecompressionStream, format, limit, 'decompress')
81
+
82
+ const inflate = (bytes, format, limit) => through(bytes, DecompressionStream, format, limit, 'decompress')
83
+
84
+ // gzip(1) and zlib take zero bytes after the last member as padding, as old
85
+ // tarballs run on in zeros to a whole 10240-byte record, the way npm 1.0
86
+ // packed them through the system's tar; the platform's stream refuses
87
+ // anything there. So gzip that ends in a zero and does not decompress is
88
+ // tried again ending sooner, at the one place it decompresses whole: its
89
+ // last member's last four bytes are the length it inflates to, mod 2^32,
90
+ // so where that is not 0 it ends within three zeros past the last byte that
91
+ // is not; where the member is empty, as zlib writes one, `03 00` and eight
92
+ // zeros, within nine. Only zeros are passed over, where zlib passes over
93
+ // whatever follows one; and each place tried inflates it all again, which
94
+ // only padded data pays for.
95
+ export async function decompress(bytes, format, { limit = Infinity } = {}) {
96
+ try {
97
+ return await inflate(bytes, format, limit)
98
+ } catch (error) {
99
+ if (format !== 'gzip' || !(error instanceof CompressionError) || error.limited || bytes.at(-1) !== 0) throw error
100
+ const last = bytes.findLastIndex((byte) => byte !== 0)
101
+ for (let end = last + 1; end <= Math.min(last + 10, bytes.length - 1); end++) {
102
+ try {
103
+ return await inflate(bytes.subarray(0, end), format, limit)
104
+ } catch (retry) {
105
+ // Output past the bound before the end is past it wherever the end is.
106
+ if (!(retry instanceof CompressionError) || retry.limited) throw retry
107
+ }
108
+ }
109
+ throw error
110
+ }
111
+ }
83
112
 
84
113
  // Into `into`, which bounds the output, and handed back as much of it as
85
114
  // was filled. Not in the front door: the zip half's, whose entries each
package/src/error.js CHANGED
@@ -1,21 +1,23 @@
1
1
  // `offset` is where in the archive the reader gave up, in bytes; the
2
- // writer leaves it unset.
2
+ // writer leaves it unset. `limited` is true where a bound the caller set
3
+ // stopped it, rather than anything wrong with the archive.
3
4
  export class ArchiveError extends Error {
4
- constructor(detail, offset) {
5
+ constructor(detail, offset, { limited = false } = {}) {
5
6
  super(offset === undefined ? detail : `${detail} at byte ${offset}`)
6
7
  this.name = 'ArchiveError'
7
8
  this.offset = offset
9
+ this.limited = limited
8
10
  }
9
11
  }
10
12
 
11
13
  // The same error, placed: for a check that does not know where in the
12
- // archive it is running. Anything but such a refusal — a bug above all —
14
+ // archive it is running. Anything but such a refusal -- a bug above all --
13
15
  // goes on as it was, rather than dressed up as bad input.
14
16
  export function located(fn, at) {
15
17
  try {
16
18
  return fn()
17
19
  } catch (error) {
18
20
  if (!(error instanceof ArchiveError) || error.offset !== undefined) throw error
19
- throw new ArchiveError(error.message, at)
21
+ throw new ArchiveError(error.message, at, { limited: error.limited })
20
22
  }
21
23
  }
package/src/names.js CHANGED
@@ -1,23 +1,29 @@
1
1
  // Name safety, applied before writing an entry and before handing one out
2
2
  // of an archive. A name is a relative path: `.` segments and a directory's
3
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
4
+ // segment, no control character and no backslash -- a separator on
5
+ // Windows, where `..\` would get past the check on `..` -- and does not
6
6
  // start with a drive letter and colon, which Windows resolves from that
7
7
  // drive rather than from the archive. A symlink target may use `..`, but
8
8
  // is followed from where the link sits and refused if it climbs above the
9
9
  // archive or passes through anything but a directory, which is how a
10
- // chain of links would climb. A hard link to a symlink, directly or down a
11
- // chain of hard links, is a second name for it, and is held to the same walk
12
- // from where that name sits, since a target safe under `a/b/` need not be
13
- // safe at the root. Lengths are bounded by what a filesystem takes at all:
14
- // PATH_MAX for the whole as the archive stores it, a directory's slash
15
- // counted, and NAME_MAX for a segment, in bytes.
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.
16
22
  //
17
23
  // A name may repeat only as the same entry again, field for field and byte
18
24
  // for byte (some npm packagers write `d/f` and `d/./f` both): two different
19
25
  // entries under one name would leave the winner to extraction order.
20
- // Collisions a filesystem might add — case, Unicode normalisation — are
26
+ // Collisions a filesystem might add -- case, Unicode normalisation -- are
21
27
  // the filesystem's, not the archive's, and are not looked for.
22
28
 
23
29
  import { sameBytes } from './bytes.js'
@@ -72,25 +78,36 @@ export function cleanPath(path, what, directory = false) {
72
78
  return name
73
79
  }
74
80
 
81
+ // The levels above the archive's root a caller lets a symlink target climb
82
+ // (`symlinksAbove`): none unless given.
83
+ export function levelsAbove(above = 0) {
84
+ if (!(Number.isSafeInteger(above) && above >= 0)) throw new ArchiveError(`symlinksAbove ${String(above)} is not a whole number of levels`)
85
+ return above
86
+ }
87
+
75
88
  // Checks the target, walked from the link's directory, never climbs above
76
- // the archive, and returns its steps: each segment it goes into, or `..` to
77
- // come back out of one. The walk is counted rather than spelled out, since
78
- // spelling out the path at every step of a deep one costs its depth squared.
79
- export function checkSymlinkTarget(name, target) {
89
+ // the archive, or no more than `above` levels above it, and returns its
90
+ // steps: each segment it goes into, or `..` to come back out of one. The
91
+ // walk is counted rather than spelled out, since spelling out the path at
92
+ // every step of a deep one costs its depth squared.
93
+ export function checkSymlinkTarget(name, target, above = 0) {
80
94
  const steps = checkText(target, `symlink target of ${quote(name)}`).filter((segment) => segment !== '' && segment !== '.')
81
95
  let depth = name.split('/').length - 1
82
96
  for (const step of steps) {
83
97
  depth += step === '..' ? -1 : 1
84
- if (depth < 0) throw new ArchiveError(`symlink ${quote(name)} points outside the archive, to ${quote(target)}`)
98
+ if (depth < -above) {
99
+ const how = above === 0 ? 'outside the archive' : `more than ${above} level${above === 1 ? '' : 's'} above the archive`
100
+ throw new ArchiveError(`symlink ${quote(name)} points ${how}, to ${quote(target)}`)
101
+ }
85
102
  }
86
103
  return steps
87
104
  }
88
105
 
89
106
  // The name and link target of an entry, cleaned and checked.
90
- export function cleanNames(path, type, target) {
107
+ export function cleanNames(path, type, target, above = 0) {
91
108
  const name = cleanPath(path, 'entry name', type === 'directory')
92
109
  let linkname = target
93
- if (type === 'symlink') checkSymlinkTarget(name, target)
110
+ if (type === 'symlink') checkSymlinkTarget(name, target, above)
94
111
  else if (type === 'hardlink') linkname = cleanPath(target, `hard link target of ${quote(name)}`)
95
112
  return { name, linkname }
96
113
  }
@@ -121,12 +138,13 @@ const FIELDS = ['type', 'mode', 'uid', 'gid', 'mtime', 'uname', 'gname', 'linkna
121
138
  // Each name seen is an entry, a directory entry, or a directory implied by
122
139
  // an entry inside it or by a symlink target walking through it; an implied
123
140
  // directory may still be named as one. An entry inside a non-directory is
124
- // refused — that is the shape of a path through a symlink — and so is a
141
+ // refused -- that is the shape of a path through a symlink -- and so is a
125
142
  // symlink target that walks through one, in either order, so no chain of
126
- // links leads out of the archive. Whether entries are kept with their data
127
- // decides what a repeat can be compared with: the in-memory calls keep
128
- // them, and a stream keeps the fields alone and refuses what it cannot
129
- // compare.
143
+ // links leads out of the archive; where `above` lets a target climb out, a
144
+ // chain can only end at the link that does, so it climbs no further. Whether
145
+ // entries are kept with their data decides what a repeat can be compared
146
+ // with: the in-memory calls keep them, and a stream keeps the fields alone
147
+ // and refuses what it cannot compare.
130
148
  //
131
149
  // The names are a tree walked a segment at a time, so a lookup hashes one
132
150
  // segment rather than a whole path, and a walk down a deep one costs its
@@ -136,9 +154,17 @@ const FIELDS = ['type', 'mode', 'uid', 'gid', 'mtime', 'uname', 'gname', 'linkna
136
154
  export class Names {
137
155
  #root = node()
138
156
  #keep
157
+ #above
139
158
 
140
- constructor(keep = false) {
159
+ // `above` is levelsAbove's, checked.
160
+ constructor(keep = false, above = 0) {
141
161
  this.#keep = keep
162
+ this.#above = above
163
+ }
164
+
165
+ // The levels a symlink target may climb above the root, for cleanNames.
166
+ get above() {
167
+ return this.#above
142
168
  }
143
169
 
144
170
  // `entry` is cleaned, with its data.
@@ -183,15 +209,18 @@ export class Names {
183
209
  if (type === 'symlink') this.#symlink(name, entry.linkname, `symlink ${quote(name)}`)
184
210
  }
185
211
 
186
- // A target followed from `at`: it has to stay inside the archive, and every
187
- // path it walks through has to be a directory — each one it stands on short
188
- // of the last step, the archive root aside. `what` names it in a refusal.
212
+ // A target followed from `at`: it has to stay inside the archive, or climb
213
+ // out of it no further than `above` allows, and every path it walks through
214
+ // inside it has to be a directory -- each one it stands on short of the
215
+ // last step, the archive root aside. Out of it, nothing it passes is the
216
+ // archive's. `what` names it in a refusal.
189
217
  #symlink(at, target, what) {
190
- const steps = checkSymlinkTarget(at, target)
218
+ const steps = checkSymlinkTarget(at, target, this.#above)
191
219
  const path = at.split('/').slice(0, -1)
192
220
  const nodes = this.#walk(path)
193
221
  for (const [i, step] of steps.entries()) {
194
222
  if (step === '..') {
223
+ if (path.length === 0) return
195
224
  path.pop()
196
225
  nodes.pop()
197
226
  } else {
package/src/tar/header.js CHANGED
@@ -42,9 +42,9 @@ const DEVMAJOR = 329
42
42
  const DEVMINOR = 337
43
43
  const PREFIX = 345
44
44
  // Under the gnu magic: the old GNU sparse map, its isextended flag and the
45
- // file's real size. libarchive reads them whatever the type flag says —
45
+ // file's real size. libarchive reads them whatever the type flag says --
46
46
  // taking the real size as the file's, and the map and any extension blocks
47
- // after the header as its layout — where GNU tar and the rest read them for
47
+ // after the header as its layout -- where GNU tar and the rest read them for
48
48
  // a sparse entry alone.
49
49
  const OLD_SPARSE = 386
50
50
  const OLD_SPARSE_END = 495
@@ -80,7 +80,7 @@ export function writeNumber(block, offset, size, value, gnu) {
80
80
  // Older tars wrote leading spaces, and either spaces or NULs after; a field
81
81
  // left blank (npm's packer wrote uid and gid so for years) is 0, as GNU tar,
82
82
  // libarchive and the rest read it. A NUL ends the number wherever it sits, so
83
- // a field that opens with one is 0 however it goes on — GNU stops there, and
83
+ // a field that opens with one is 0 however it goes on -- GNU stops there, and
84
84
  // reading the digits past it instead would give a size, and so an archive,
85
85
  // that only this package sees. Only a time may be negative.
86
86
  export function readNumber(block, offset, size, what, at, signed = false) {
package/src/tar/pack.js CHANGED
@@ -1,13 +1,13 @@
1
1
  // Writes what GNU tar 1.35 writes for the same entries under `--owner=0
2
2
  // --group=0 --numeric-owner` and, for pax, `--pax-option=delete=atime,
3
- // delete=ctime`. Where GNU would cut or substitute — a name too long for
4
- // ustar, a number out of range — this refuses instead.
3
+ // delete=ctime`. Where GNU would cut or substitute -- a name too long for
4
+ // ustar, a number out of range -- this refuses instead.
5
5
 
6
6
  import { EMPTY, concat, isAscii } from '../bytes.js'
7
7
  import { DEFAULT_MODE, checkEntry, wireName } from '../entry.js'
8
8
  import { ArchiveError } from '../error.js'
9
9
  import { BLOCK, EXTENDED_TYPEFLAGS, NAME_SIZE, OWNER_SIZE, PREFIX_SIZE, TYPEFLAGS, encodeHeader, fitsOctal, isDevice, octalMax } from './header.js'
10
- import { Names, cleanNames } from '../names.js'
10
+ import { Names, cleanNames, levelsAbove } from '../names.js'
11
11
  import { encodePax } from './pax.js'
12
12
  import { checkString, encodeUtf8, hasUnsafe, quote } from '../text.js'
13
13
 
@@ -148,15 +148,15 @@ function encodeEntry(e, format) {
148
148
 
149
149
  // `keep` holds entries for a repeat to be compared with, which only the
150
150
  // in-memory call can afford.
151
- function packer({ format = 'gnu', blocking = 20 } = {}, keep = false) {
151
+ function packer({ format = 'gnu', blocking = 20, symlinksAbove } = {}, keep = false) {
152
152
  if (!FORMATS.has(format)) throw new ArchiveError(`format ${quote(String(format))} is not gnu, ustar or pax`)
153
153
  if (!Number.isSafeInteger(blocking) || blocking < 1) throw new ArchiveError('blocking is not a positive integer')
154
- const names = new Names(keep)
154
+ const names = new Names(keep, levelsAbove(symlinksAbove))
155
155
  let total = 0
156
156
  return {
157
157
  add(entry) {
158
158
  const e = normalize(entry)
159
- const cleaned = { ...e, ...cleanNames(e.name, e.type, e.linkname) }
159
+ const cleaned = { ...e, ...cleanNames(e.name, e.type, e.linkname, names.above) }
160
160
  names.add(cleaned)
161
161
  const chunks = encodeEntry(cleaned, format)
162
162
  for (const chunk of chunks) total += chunk.length
package/src/tar/unpack.js CHANGED
@@ -8,11 +8,11 @@ import { EMPTY } from '../bytes.js'
8
8
  import { isFile } from '../entry.js'
9
9
  import { ArchiveError, located } from '../error.js'
10
10
  import { BLOCK, EXTENDED_TYPEFLAGS, TYPEFLAGS, decodeHeader, isDevice, isZeroBlock, untilNul } from './header.js'
11
- import { Names, cleanNames } from '../names.js'
11
+ import { Names, cleanNames, levelsAbove } from '../names.js'
12
12
  import { Records, decodePax } from './pax.js'
13
13
  import { decodeUtf8, hasUnsafe, quote } from '../text.js'
14
14
 
15
- // Type flag → name. NUL is the pre-POSIX regular file.
15
+ // Type flag -> name. NUL is the pre-POSIX regular file.
16
16
  const byFlag = (flags) => Object.entries(flags).map(([name, flag]) => [flag, name])
17
17
  const TYPES = new Map([...byFlag(TYPEFLAGS), [0, 'file']])
18
18
  const EXTENDED = new Map(byFlag(EXTENDED_TYPEFLAGS))
@@ -69,11 +69,15 @@ class Unpacker {
69
69
  #awaiting = null
70
70
  #zeros = 0
71
71
  #done = false
72
+ #count = 0
73
+ #maxEntries
72
74
 
73
75
  // `keep` holds entries for a repeat to be compared with, which only the
74
- // in-memory call can afford.
75
- constructor(keep = false) {
76
- this.#names = new Names(keep)
76
+ // in-memory call can afford; the options are unpack's.
77
+ constructor(keep, { symlinksAbove, maxEntries = Infinity } = {}) {
78
+ if (maxEntries !== Infinity && !(Number.isSafeInteger(maxEntries) && maxEntries >= 0)) throw new ArchiveError(`maxEntries ${String(maxEntries)} is not a whole number of entries`)
79
+ this.#names = new Names(keep, levelsAbove(symlinksAbove))
80
+ this.#maxEntries = maxEntries
77
81
  }
78
82
 
79
83
  push(chunk) {
@@ -152,6 +156,8 @@ class Unpacker {
152
156
  const header = decodeHeader(block, at)
153
157
  const extended = EXTENDED.get(header.typeflag)
154
158
  if (extended === undefined) {
159
+ // Counted at its header, before anything is made of it or its data read.
160
+ if (++this.#count > this.#maxEntries) throw new ArchiveError(`the archive holds more than ${this.#maxEntries} entries`, at, { limited: true })
155
161
  this.#awaiting = { extended: null, at, ...this.#resolve(header, at) }
156
162
  } else {
157
163
  if (header.size > MAX_EXTENDED) throw new ArchiveError(`a ${extended} header of ${header.size} bytes is longer than any tar writes`, at)
@@ -200,7 +206,7 @@ class Unpacker {
200
206
  if (longlink !== null && record('linkpath') !== undefined) throw new ArchiveError('both a long link header and a pax linkpath name one entry', at)
201
207
  const rawName = longname ?? record('path') ?? this.#headerName(header, at)
202
208
  const rawTarget = longlink ?? record('linkpath') ?? decodeUtf8(header.linkname, 'link target', at)
203
- const { name, linkname } = located(() => cleanNames(rawName, type, rawTarget), at)
209
+ const { name, linkname } = located(() => cleanNames(rawName, type, rawTarget, this.#names.above), at)
204
210
  const number = (key, parse = paxNumber) => {
205
211
  const value = record(key)
206
212
  return value === undefined ? header[key] : parse(value, key, at)
@@ -240,15 +246,15 @@ class Unpacker {
240
246
  }
241
247
  }
242
248
 
243
- export function unpack(bytes) {
244
- const unpacker = new Unpacker(true)
249
+ export function unpack(bytes, options) {
250
+ const unpacker = new Unpacker(true, options)
245
251
  const entries = unpacker.push(bytes)
246
252
  unpacker.end()
247
253
  return entries
248
254
  }
249
255
 
250
- export async function* unpackStream(chunks) {
251
- const unpacker = new Unpacker()
256
+ export async function* unpackStream(chunks, options) {
257
+ const unpacker = new Unpacker(false, options)
252
258
  for await (const chunk of chunks) yield* unpacker.push(chunk)
253
259
  unpacker.end()
254
260
  }
package/src/text.js CHANGED
@@ -5,13 +5,13 @@ import { ArchiveError } from './error.js'
5
5
  // short of a surrogate pair, so a long one cannot flood it.
6
6
  export function quote(text) {
7
7
  if (text.length <= 200) return JSON.stringify(text)
8
- return JSON.stringify(`${text.slice(0, text.codePointAt(199) > 0xffff ? 199 : 200)}…`)
8
+ return JSON.stringify(`${text.slice(0, text.codePointAt(199) > 0xffff ? 199 : 200)}\u2026`)
9
9
  }
10
10
 
11
11
  // A C0, DEL or C1 control (Cc is those three and nothing else); a line or
12
12
  // paragraph separator (Zl, Zp: one each); and every bidirectional control
13
- // Unicode names — embeddings, overrides and isolates, and the three marks
14
- // that shift neutral characters about them unseen — since each breaks or
13
+ // Unicode names -- embeddings, overrides and isolates, and the three marks
14
+ // that shift neutral characters about them unseen -- since each breaks or
15
15
  // reorders a name as shown. A backslash too, if asked.
16
16
  const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u
17
17
  const UNSAFE_OR_BACKSLASH = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\\]/u
package/src/zip/format.js CHANGED
@@ -53,7 +53,7 @@ export async function inflate(bytes, size, at) {
53
53
  return out
54
54
  }
55
55
 
56
- // DOS time is two seconds and a year from 1980, in the maker's local time —
56
+ // DOS time is two seconds and a year from 1980, in the maker's local time --
57
57
  // read and written here as UTC.
58
58
  function dos(seconds) {
59
59
  const date = new Date(seconds * 1000)
package/src/zip/unzip.js CHANGED
@@ -1,11 +1,11 @@
1
1
  // A zip archive in, its entries out, in the order of the central directory,
2
2
  // which is what a zip is read from. Strict throughout: the end record has to
3
3
  // sit at the very end, the central directory right before it, and the
4
- // entries have to tile everything before that from byte 0 — no bytes belong
4
+ // entries have to tile everything before that from byte 0 -- no bytes belong
5
5
  // to nothing, no two entries share any. Each local header has to agree with
6
6
  // the central directory, the data has to inflate to exactly the declared
7
- // size and match its CRC-32, and what this package does not model — zip64,
8
- // encryption, any method but stored and deflate, several disks — is refused.
7
+ // size and match its CRC-32, and what this package does not model -- zip64,
8
+ // encryption, any method but stored and deflate, several disks -- is refused.
9
9
  // Given a limit, the sizes the entries declare may not add up to more than
10
10
  // it; since each has to come out at exactly its own, that bounds everything
11
11
  // unzip() puts out, and it is known from the central directory alone,
@@ -13,7 +13,7 @@
13
13
  //
14
14
  // One reader serves both calls. It asks for the archive a range at a time:
15
15
  // views of it when it is in memory, and reads of just those bytes when it
16
- // is a Blob — a File, or a file opened with fs.openAsBlob — so a stream
16
+ // is a Blob -- a File, or a file opened with fs.openAsBlob -- so a stream
17
17
  // over one holds no more of it than the entries' names and the entry it is
18
18
  // on. Everything about the layout is checked before the first entry is
19
19
  // handed over; what an entry's own data holds is checked as it is reached.
@@ -23,7 +23,7 @@ import { EMPTY, sameBytes } from '../bytes.js'
23
23
  import { DEFAULT_MODE } from '../entry.js'
24
24
  import { ArchiveError, located } from '../error.js'
25
25
  import { CENTRAL, END, LOCAL, TYPE_BITS, TYPE_MASK, fromDos, inflate, view } from './format.js'
26
- import { Names, cleanNames } from '../names.js'
26
+ import { Names, cleanNames, levelsAbove } from '../names.js'
27
27
  import { decodeUtf8, quote } from '../text.js'
28
28
 
29
29
  const DESCRIPTOR = 0x08074b50
@@ -71,7 +71,7 @@ function sourceOf(archive) {
71
71
 
72
72
  // A walk forward through records too small to be worth a read each: a
73
73
  // window over [at, at + width), cut short only where the archive ends,
74
- // and over what else the read it came from holds — up to CHUNK bytes past
74
+ // and over what else the read it came from holds -- up to CHUNK bytes past
75
75
  // `at`, and short of `stop`, so that the records after it come in the same
76
76
  // read and nothing past them is read to no purpose.
77
77
  const CHUNK = 1 << 16
@@ -116,7 +116,7 @@ function extras(raw, at) {
116
116
  if (pos + 4 + size > raw.length) throw new ArchiveError('an extra field runs past its room', at)
117
117
  if (id === ZIP64_EXTRA) throw new ArchiveError('zip64 is not supported', at)
118
118
  // Every name here is UTF-8 already, so this field can only disagree with
119
- // the name checked above — and unzip would extract the name it carries.
119
+ // the name checked above -- and unzip would extract the name it carries.
120
120
  if (id === UNICODE_PATH_EXTRA) throw new ArchiveError('an entry carries a second name in a Unicode path extra field', at)
121
121
  if (!fields.has(id)) fields.set(id, raw.subarray(pos + 4, pos + 4 + size))
122
122
  pos += 4 + size
@@ -165,8 +165,8 @@ async function readCentral(read, at) {
165
165
  // The local header checked against the central entry; returns where the
166
166
  // entry's bytes end, which has to be `boundary`, the next record's start,
167
167
  // and notes where its data starts. The two records have to agree on
168
- // everything both carry — flags included, since a descriptor bit set in
169
- // one and not the other is read two ways by two readers — and the local
168
+ // everything both carry -- flags included, since a descriptor bit set in
169
+ // one and not the other is read two ways by two readers -- and the local
170
170
  // sizes and CRC may be 0 only where a descriptor carries them. `stop` is
171
171
  // as far as the header is read ahead of itself.
172
172
  async function readLocal(read, entry, boundary, stop) {
@@ -201,7 +201,7 @@ async function readLocal(read, entry, boundary, stop) {
201
201
  return end
202
202
  }
203
203
 
204
- // A directory marker anywhere — the Unix type bits, the DOS bit — needs
204
+ // A directory marker anywhere -- the Unix type bits, the DOS bit -- needs
205
205
  // the slash; the slash needs no marker, since Java writes no attributes at
206
206
  // all and every JAR has directories.
207
207
  function typeOf(entry, rawName, mode) {
@@ -232,7 +232,7 @@ async function entryOf(source, entry, names) {
232
232
  const body = method === 8 ? await inflate(raw, usize, at) : raw
233
233
  if (crc32(body) !== entry.crc) throw new ArchiveError('the data does not match its CRC-32', at)
234
234
  const target = type === 'symlink' ? decodeUtf8(body, 'symlink target', at) : ''
235
- const named = located(() => cleanNames(rawName, type, target), at)
235
+ const named = located(() => cleanNames(rawName, type, target, names.above), at)
236
236
  const out = { ...named, type, mode: mode === 0 ? DEFAULT_MODE[type] : mode & 0o7777, mtime: entry.mtime, data: type === 'file' ? body : EMPTY, storedName: rawName }
237
237
  located(() => names.add(out), at)
238
238
  return out
@@ -241,8 +241,9 @@ async function entryOf(source, entry, names) {
241
241
  // The entries one at a time, the layout all checked before the first.
242
242
  // `keep` holds entries for a repeat to be compared with, which only the
243
243
  // in-memory call can afford.
244
- async function* entries(source, { limit = Infinity } = {}, keep = false) {
244
+ async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep = false) {
245
245
  if (limit !== Infinity && !(Number.isSafeInteger(limit) && limit >= 0)) throw new ArchiveError(`limit ${String(limit)} is not a whole number of bytes`)
246
+ const above = levelsAbove(symlinksAbove)
246
247
  const { end, r } = await findEnd(source)
247
248
  const count = r.u16(end + 8)
248
249
  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)
@@ -260,7 +261,7 @@ async function* entries(source, { limit = Infinity } = {}, keep = false) {
260
261
  for (let i = 0; i < count; i++) {
261
262
  const entry = await readCentral(directory, pos)
262
263
  total += entry.usize
263
- if (total > limit) throw new ArchiveError(`the entries come to more than ${limit} bytes`, pos)
264
+ if (total > limit) throw new ArchiveError(`the entries come to more than ${limit} bytes`, pos, { limited: true })
264
265
  list.push(entry)
265
266
  pos = entry.next
266
267
  }
@@ -282,7 +283,7 @@ async function* entries(source, { limit = Infinity } = {}, keep = false) {
282
283
  expected = await readLocal(locals, entry, boundaries[i], stops[i])
283
284
  }
284
285
  if (expected !== start) throw new ArchiveError('bytes belong to no entry', expected)
285
- const names = new Names(keep)
286
+ const names = new Names(keep, above)
286
287
  for (const entry of list) yield await entryOf(source, entry, names)
287
288
  }
288
289
 
package/src/zip/zip.js CHANGED
@@ -8,7 +8,7 @@ import { concat, isAscii } from '../bytes.js'
8
8
  import { DEFAULT_MODE, checkEntry, wireName } from '../entry.js'
9
9
  import { ArchiveError } from '../error.js'
10
10
  import { CENTRAL, END, LOCAL, TYPE_BITS, deflate, record, toDos } from './format.js'
11
- import { Names, cleanNames } from '../names.js'
11
+ import { Names, cleanNames, levelsAbove } from '../names.js'
12
12
  import { encodeUtf8, quote } from '../text.js'
13
13
 
14
14
  const METHODS = new Set(['deflate', 'store'])
@@ -39,16 +39,16 @@ function normalize(entry) {
39
39
  // 0x5455: flag bit 0 and the mtime, as Info-ZIP writes in the central copy.
40
40
  const timestamp = (mtime) => record([[2, 0x5455], [2, 5], [1, 1], [4, mtime]])
41
41
 
42
- export async function zip(entries, { method = 'deflate' } = {}) {
42
+ export async function zip(entries, { method = 'deflate', symlinksAbove } = {}) {
43
43
  if (!METHODS.has(method)) throw new ArchiveError(`method ${quote(String(method))} is not deflate or store`)
44
- const names = new Names(true)
44
+ const names = new Names(true, levelsAbove(symlinksAbove))
45
45
  const locals = []
46
46
  const centrals = []
47
47
  let offset = 0
48
48
  let count = 0
49
49
  for (const given of entries) {
50
50
  const entry = normalize(given)
51
- const e = { ...entry, ...cleanNames(entry.name, entry.type, entry.linkname) }
51
+ const e = { ...entry, ...cleanNames(entry.name, entry.type, entry.linkname, names.above) }
52
52
  names.add(e)
53
53
  if (++count > MAX_ENTRIES) throw new ArchiveError(`more than ${MAX_ENTRIES} entries would need zip64`)
54
54
  const name = encodeUtf8(wireName(e), 'entry name')
package/tar.d.ts CHANGED
@@ -23,14 +23,14 @@ export type EntryType =
23
23
  //
24
24
  // Beside those, what the archive itself says. `storedName` and
25
25
  // `storedLinkname` are the name and link target as stored, before any
26
- // cleaning — `./a` where `name` is `a`, `dir/` where it is `dir`, a ustar
27
- // prefix joined on — and passed every check the cleaned ones did; only a
26
+ // cleaning -- `./a` where `name` is `a`, `dir/` where it is `dir`, a ustar
27
+ // prefix joined on -- and passed every check the cleaned ones did; only a
28
28
  // hard link's target is ever cleaned, so a symlink's is its `linkname`.
29
29
  // `pax` is the records of the entry's own pax header and `globalPax` those
30
30
  // of the global header it is under, each in the order stored, those read
31
31
  // into the fields above among them; the fields take an entry's own record
32
- // over the global one. A Map is shared — every entry under one global
33
- // header has its, every entry without a header the one empty Map — so it
32
+ // over the global one. A Map is shared -- every entry under one global
33
+ // header has its, every entry without a header the one empty Map -- so it
34
34
  // cannot be changed. A value this package does not read is as stored,
35
35
  // unchecked, and may hold any character, a control one included.
36
36
  export interface Entry {
@@ -77,23 +77,44 @@ export interface EntryInput {
77
77
  // 'ustar' refuses what it cannot hold, 'pax' holds everything.
78
78
  export type Format = 'gnu' | 'ustar' | 'pax'
79
79
 
80
+ // `symlinksAbove` lets a relative symlink target climb up to that many
81
+ // levels above the archive's root, none by default: for a directory
82
+ // archived on its own, as GitHub archives a tree, that links to the files
83
+ // of the tree it was cut from -- `LICENSE -> ../../LICENSE` in a tree's
84
+ // `packages/a/`, archived under one top directory, climbs one. Past the root
85
+ // the archive cannot tell where a target leads, not even back into itself
86
+ // by the name it is extracted under, so what it passes through there is
87
+ // the caller's to know. An absolute target is refused regardless, and what
88
+ // one call reads with it, another writes with it.
89
+ export interface SymlinkOptions {
90
+ symlinksAbove?: number
91
+ }
92
+
80
93
  // `blocking` is tar's -b: zero padding to a multiple of that many 512-byte
81
94
  // blocks, 20 by default; 1 pads nothing past the two zero end blocks.
82
- export interface PackOptions {
95
+ export interface PackOptions extends SymlinkOptions {
83
96
  format?: Format
84
97
  blocking?: number
85
98
  }
86
99
 
87
- // Both refuse a name that repeats as a different entry — anything but the
88
- // same fields and the same bytes again, however either was stored — an
100
+ // `maxEntries` bounds how many entries the archive may hold, every kind
101
+ // counted and a repeat again, its extended headers not: past it the call
102
+ // throws with `limited` set, at the header that crosses it, before that
103
+ // entry is read. No bound by default.
104
+ export interface UnpackOptions extends SymlinkOptions {
105
+ maxEntries?: number
106
+ }
107
+
108
+ // Both refuse a name that repeats as a different entry -- anything but the
109
+ // same fields and the same bytes again, however either was stored -- an
89
110
  // entry inside something that is not a directory, a symlink whose target
90
- // climbs out of the archive or passes through anything but a directory, and
91
- // a hard link to no earlier entry. A hard link to a symlink, directly or
92
- // down a chain of hard links, is a second name for it, and its target is
93
- // walked again from that name, which a target safe where the symlink sits
94
- // need not survive.
111
+ // climbs out of the archive, further than `symlinksAbove` lets it, or
112
+ // passes through anything in it but a directory, and a hard link to no
113
+ // earlier entry. A hard link to a symlink, directly or down a chain of hard
114
+ // links, is a second name for it, and its target is walked again from that
115
+ // name, which a target safe where the symlink sits need not survive.
95
116
  export function pack(entries: Iterable<EntryInput>, options?: PackOptions): Uint8Array
96
- export function unpack(bytes: Uint8Array): Entry[]
117
+ export function unpack(bytes: Uint8Array, options?: UnpackOptions): Entry[]
97
118
 
98
119
  // The same a piece at a time, as async generators over a plain or an
99
120
  // async iterable. A stream keeps no entry's data, so a name that repeats
@@ -101,10 +122,13 @@ export function unpack(bytes: Uint8Array): Entry[]
101
122
  // in-memory call. packStream yields each entry's `data` as the very array
102
123
  // it was given.
103
124
  export function packStream(entries: Iterable<EntryInput> | AsyncIterable<EntryInput>, options?: PackOptions): AsyncGenerator<Uint8Array, void, undefined>
104
- export function unpackStream(chunks: Iterable<Uint8Array> | AsyncIterable<Uint8Array>): AsyncGenerator<Entry, void, undefined>
125
+ export function unpackStream(chunks: Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: UnpackOptions): AsyncGenerator<Entry, void, undefined>
105
126
 
106
127
  // `offset` is where in the archive the reader gave up; unset from the writer.
128
+ // `limited` is true where a bound the caller set stopped it, rather than
129
+ // anything wrong with the archive.
107
130
  export class ArchiveError extends Error {
108
- constructor(detail: string, offset?: number)
131
+ constructor(detail: string, offset?: number, options?: { limited?: boolean })
109
132
  offset: number | undefined
133
+ limited: boolean
110
134
  }
package/zip.d.ts CHANGED
@@ -14,8 +14,8 @@ export type EntryType = 'file' | 'directory' | 'symlink'
14
14
  // `linkname` is '' for anything but a symlink; `data` is empty for
15
15
  // anything but a file, and a view over the archive bytes where the entry
16
16
  // was stored and the archive is in memory rather than a Blob.
17
- // `storedName` is the name as the archive stores it, before any cleaning —
18
- // `./a` where `name` is `a`, `dir/` where it is `dir` — and passed every
17
+ // `storedName` is the name as the archive stores it, before any cleaning --
18
+ // `./a` where `name` is `a`, `dir/` where it is `dir` -- and passed every
19
19
  // check the cleaned one did. A symlink's target is never rewritten, only
20
20
  // checked, so `linkname` is as stored.
21
21
  export interface Entry {
@@ -44,34 +44,43 @@ export interface EntryInput {
44
44
  linkname?: string
45
45
  }
46
46
 
47
+ // `symlinksAbove` lets a relative symlink target climb up to that many
48
+ // levels above the archive's root, none by default, as tar.d.ts tells: past
49
+ // the root, what a target passes through is the caller's to know. An
50
+ // absolute target is refused regardless, and what one call reads with it,
51
+ // another writes with it.
52
+ export interface SymlinkOptions {
53
+ symlinksAbove?: number
54
+ }
55
+
47
56
  // 'deflate' (the default) deflates each file and keeps the result only
48
57
  // where it is smaller, as Info-ZIP does; 'store' compresses nothing.
49
- export interface ZipOptions {
58
+ export interface ZipOptions extends SymlinkOptions {
50
59
  method?: 'deflate' | 'store'
51
60
  }
52
61
 
53
- // `limit` bounds the entries' sizes, all of them together, in bytes —
62
+ // `limit` bounds the entries' sizes, all of them together, in bytes --
54
63
  // stored and deflated alike, a symlink's target included. Each entry has to
55
64
  // come out at exactly the size it declares, so the sum is checked against
56
65
  // the central directory before anything is inflated, and past the limit
57
- // the call rejects. No limit by default.
58
- export interface UnzipOptions {
66
+ // the call rejects, with `limited` set. No limit by default.
67
+ export interface UnzipOptions extends SymlinkOptions {
59
68
  limit?: number
60
69
  }
61
70
 
62
- // Both refuse a name that repeats as a different entry — anything but the
63
- // same fields and the same bytes again, however either was stored — an
71
+ // Both refuse a name that repeats as a different entry -- anything but the
72
+ // same fields and the same bytes again, however either was stored -- an
64
73
  // entry inside something that is not a directory, and a symlink whose
65
- // target climbs out of the archive or passes through anything but a
66
- // directory. unzip() also refuses an entry carrying a Unicode path extra
67
- // field, a second name that other readers take over the one in the header.
68
- // Neither takes or makes zip64, so an archive holds at most 65534 entries
69
- // and stays under 4 GiB.
74
+ // target climbs out of the archive, further than `symlinksAbove` lets it,
75
+ // or passes through anything in it but a directory. unzip() also refuses
76
+ // an entry carrying a Unicode path extra field, a second name that other
77
+ // readers take over the one in the header. Neither takes or makes zip64,
78
+ // so an archive holds at most 65534 entries and stays under 4 GiB.
70
79
  export function zip(entries: Iterable<EntryInput>, options?: ZipOptions): Promise<Uint8Array>
71
80
  export function unzip(bytes: Uint8Array, options?: UnzipOptions): Promise<Entry[]>
72
81
 
73
82
  // The same one entry at a time, as an async generator: over the archive in
74
- // memory, or over a Blob — a File, or a file opened with fs.openAsBlob —
83
+ // memory, or over a Blob -- a File, or a file opened with fs.openAsBlob --
75
84
  // read a range at a time, so that no more of it is held than the entries'
76
85
  // names and the entry it is on, whose data is then its own rather than a
77
86
  // view of the archive.
@@ -83,7 +92,10 @@ export function unzip(bytes: Uint8Array, options?: UnzipOptions): Promise<Entry[
83
92
  export function unzipStream(archive: Uint8Array | Blob, options?: UnzipOptions): AsyncGenerator<Entry, void, undefined>
84
93
 
85
94
  // `offset` is where in the archive the reader gave up; unset from the writer.
95
+ // `limited` is true where a bound the caller set stopped it, rather than
96
+ // anything wrong with the archive.
86
97
  export class ArchiveError extends Error {
87
- constructor(detail: string, offset?: number)
98
+ constructor(detail: string, offset?: number, options?: { limited?: boolean })
88
99
  offset: number | undefined
100
+ limited: boolean
89
101
  }
package/zip.js CHANGED
@@ -8,13 +8,13 @@
8
8
  // refused rather than written down wrong.
9
9
  export { zip } from './src/zip/zip.js'
10
10
 
11
- // An archive in, its entries out, under the same rules — and with every
11
+ // An archive in, its entries out, under the same rules -- and with every
12
12
  // header, size and checksum in it checked against every other, and the
13
13
  // sizes all together held to a limit where one is given.
14
14
  export { unzip } from './src/zip/unzip.js'
15
15
 
16
16
  // The same an entry at a time, as an async generator over the archive in
17
- // memory or over a Blob — a File, or a file opened with fs.openAsBlob —
17
+ // memory or over a Blob -- a File, or a file opened with fs.openAsBlob --
18
18
  // read a range at a time, so no more of it is held than the entry it is on.
19
19
  export { unzipStream } from './src/zip/unzip.js'
20
20