@preventive/archive 1.0.0 → 1.2.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
@@ -21,9 +21,11 @@ export function compress(bytes: Uint8Array, format: string, options?: Options):
21
21
  export function decompress(bytes: Uint8Array, format: string, options?: Options): Promise<Uint8Array>
22
22
 
23
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.
24
25
  export class ArchiveError extends Error {
25
- constructor(detail: string, offset?: number)
26
+ constructor(detail: string, offset?: number, options?: { limited?: boolean })
26
27
  offset: number | undefined
28
+ limited: boolean
27
29
  }
28
30
 
29
31
  // What a stream refused: `bytes` is what it had put out by then, kept for a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/archive",
3
- "version": "1.0.0",
3
+ "version": "1.2.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
  }
package/src/error.js CHANGED
@@ -1,10 +1,12 @@
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
 
@@ -16,6 +18,6 @@ export function located(fn, at) {
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
@@ -7,12 +7,18 @@
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
@@ -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
  }
@@ -123,10 +140,11 @@ const FIELDS = ['type', 'mode', 'uid', 'gid', 'mtime', 'uname', 'gname', 'linkna
123
140
  // directory may still be named as one. An entry inside a non-directory is
124
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
@@ -135,6 +135,10 @@ export function encodeHeader(f) {
135
135
  return block
136
136
  }
137
137
 
138
+ // Whether a numeric field holds octal digits, as POSIX writes it, rather
139
+ // than nothing or GNU's base 256, both of which readNumber reads.
140
+ const isOctal = (block, offset, size) => /^ *[0-7]+ *$/u.test(ascii(untilNul(block.subarray(offset, offset + size))))
141
+
138
142
  export function decodeHeader(block, at) {
139
143
  if (checksum(block) !== readNumber(block, CHKSUM, 8, 'checksum', at)) throw new ArchiveError('header checksum does not match', at)
140
144
  const magic = ascii(block.subarray(MAGIC, MAGIC + 8))
@@ -155,5 +159,7 @@ export function decodeHeader(block, at) {
155
159
  ...Object.fromEntries(NUMBERS.map(([key, offset, size]) => [key, readNumber(block, offset, size, key, at, key === 'mtime')])),
156
160
  devmajor: device ? readNumber(block, DEVMAJOR, 8, 'devmajor', at) : 0,
157
161
  devminor: device ? readNumber(block, DEVMINOR, 8, 'devminor', at) : 0,
162
+ octal: [['checksum', CHKSUM, 8], ...NUMBERS, ...device ? [['devmajor', DEVMAJOR, 8], ['devminor', DEVMINOR, 8]] : []]
163
+ .every(([, offset, size]) => isOctal(block, offset, size)),
158
164
  }
159
165
  }
package/src/tar/pack.js CHANGED
@@ -7,7 +7,7 @@ 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,7 +8,7 @@ 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
 
@@ -57,6 +57,10 @@ const nonePending = () => ({ pax: null, longname: null, longlink: null })
57
57
  // global one.
58
58
  const NO_RECORDS = new Records()
59
59
 
60
+ // The extended headers of every entry with none ahead of it.
61
+ const NO_EXTENDED = Object.freeze([])
62
+ const magicOf = (header) => (header.gnu ? 'gnu' : 'ustar')
63
+
60
64
  class Unpacker {
61
65
  #chunks = []
62
66
  #offset = 0
@@ -64,24 +68,33 @@ class Unpacker {
64
68
  #position = 0
65
69
  #names
66
70
  #pending = nonePending()
71
+ // The extended headers read since the last entry, in order: each its
72
+ // kind and its magic.
73
+ #extended = []
67
74
  #global = null
68
75
  // The header whose body is due: { extended, size, at, entry }.
69
76
  #awaiting = null
70
77
  #zeros = 0
71
78
  #done = false
79
+ #count = 0
80
+ #maxEntries
72
81
 
73
82
  // `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)
83
+ // in-memory call can afford; the options are unpack's.
84
+ constructor(keep, { symlinksAbove, maxEntries = Infinity } = {}) {
85
+ if (maxEntries !== Infinity && !(Number.isSafeInteger(maxEntries) && maxEntries >= 0)) throw new ArchiveError(`maxEntries ${String(maxEntries)} is not a whole number of entries`)
86
+ this.#names = new Names(keep, levelsAbove(symlinksAbove))
87
+ this.#maxEntries = maxEntries
77
88
  }
78
89
 
79
- push(chunk) {
90
+ // The entries a chunk completes, each as it is read, so that a chunk
91
+ // holding many has no more of them held than the one being read.
92
+ *push(chunk) {
80
93
  if (!(chunk instanceof Uint8Array)) throw new ArchiveError('a chunk is not a Uint8Array')
81
94
  if (this.#done) {
82
95
  this.#trailing(chunk, this.#position)
83
96
  this.#position += chunk.length
84
- return []
97
+ return
85
98
  }
86
99
  if (chunk.length) {
87
100
  this.#chunks.push(chunk)
@@ -89,8 +102,10 @@ class Unpacker {
89
102
  }
90
103
  const out = []
91
104
  let more = true
92
- while (more && !this.#done) more = this.#awaiting === null ? this.#header() : this.#body(out)
93
- return out
105
+ while (more && !this.#done) {
106
+ more = this.#awaiting === null ? this.#header() : this.#body(out)
107
+ yield* out.splice(0)
108
+ }
94
109
  }
95
110
 
96
111
  end() {
@@ -140,7 +155,8 @@ class Unpacker {
140
155
  if (block === null) return false
141
156
  const at = this.#position - BLOCK
142
157
  if (isZeroBlock(block)) {
143
- if (Object.values(this.#pending).some((value) => value !== null)) throw new ArchiveError('an extended header is not followed by an entry', at)
158
+ // A global header too: one with no entry after it stands for nothing.
159
+ if (this.#extended.length > 0) throw new ArchiveError('an extended header is not followed by an entry', at)
144
160
  if (++this.#zeros === 2) {
145
161
  this.#done = true
146
162
  const after = this.#position
@@ -152,16 +168,18 @@ class Unpacker {
152
168
  const header = decodeHeader(block, at)
153
169
  const extended = EXTENDED.get(header.typeflag)
154
170
  if (extended === undefined) {
171
+ // Counted at its header, before anything is made of it or its data read.
172
+ if (++this.#count > this.#maxEntries) throw new ArchiveError(`the archive holds more than ${this.#maxEntries} entries`, at, { limited: true })
155
173
  this.#awaiting = { extended: null, at, ...this.#resolve(header, at) }
156
174
  } else {
157
175
  if (header.size > MAX_EXTENDED) throw new ArchiveError(`a ${extended} header of ${header.size} bytes is longer than any tar writes`, at)
158
- this.#awaiting = { extended, size: header.size, at, entry: null }
176
+ this.#awaiting = { extended, size: header.size, at, entry: null, magic: magicOf(header), octal: header.octal }
159
177
  }
160
178
  return true
161
179
  }
162
180
 
163
181
  #body(out) {
164
- const { extended, size, at, entry } = this.#awaiting
182
+ const { extended, size, at, entry, magic, octal } = this.#awaiting
165
183
  const whole = Math.ceil(size / BLOCK) * BLOCK
166
184
  const body = this.#take(whole)
167
185
  if (body === null) return false
@@ -180,9 +198,11 @@ class Unpacker {
180
198
  // Once, here: a global header stands until another replaces it, and
181
199
  // re-reading its keys under every entry is work an archive can ask for.
182
200
  sparse(this.#global.keys(), at)
201
+ this.#extended.push(Object.freeze({ kind: extended, magic, octal }))
183
202
  } else {
184
203
  if (this.#pending[extended] !== null) throw new ArchiveError(`two ${extended} headers ahead of one entry`, at)
185
204
  this.#pending[extended] = extended === 'pax' ? decodePax(raw, at) : decodeUtf8(untilNul(raw), `a ${extended} header`, at)
205
+ this.#extended.push(Object.freeze({ kind: extended, magic, octal }))
186
206
  }
187
207
  return true
188
208
  }
@@ -200,7 +220,7 @@ class Unpacker {
200
220
  if (longlink !== null && record('linkpath') !== undefined) throw new ArchiveError('both a long link header and a pax linkpath name one entry', at)
201
221
  const rawName = longname ?? record('path') ?? this.#headerName(header, at)
202
222
  const rawTarget = longlink ?? record('linkpath') ?? decodeUtf8(header.linkname, 'link target', at)
203
- const { name, linkname } = located(() => cleanNames(rawName, type, rawTarget), at)
223
+ const { name, linkname } = located(() => cleanNames(rawName, type, rawTarget, this.#names.above), at)
204
224
  const number = (key, parse = paxNumber) => {
205
225
  const value = record(key)
206
226
  return value === undefined ? header[key] : parse(value, key, at)
@@ -230,7 +250,13 @@ class Unpacker {
230
250
  storedLinkname: rawTarget,
231
251
  pax: pax ?? NO_RECORDS,
232
252
  globalPax: this.#global ?? NO_RECORDS,
253
+ extended: this.#extended.length ? Object.freeze(this.#extended) : NO_EXTENDED,
254
+ magic: magicOf(header),
255
+ typeflag: String.fromCodePoint(header.typeflag),
256
+ storedMode: header.mode,
257
+ octal: header.octal,
233
258
  }
259
+ this.#extended = []
234
260
  return { entry, size }
235
261
  }
236
262
 
@@ -240,15 +266,15 @@ class Unpacker {
240
266
  }
241
267
  }
242
268
 
243
- export function unpack(bytes) {
244
- const unpacker = new Unpacker(true)
245
- const entries = unpacker.push(bytes)
269
+ export function unpack(bytes, options) {
270
+ const unpacker = new Unpacker(true, options)
271
+ const entries = [...unpacker.push(bytes)]
246
272
  unpacker.end()
247
273
  return entries
248
274
  }
249
275
 
250
- export async function* unpackStream(chunks) {
251
- const unpacker = new Unpacker()
276
+ export async function* unpackStream(chunks, options) {
277
+ const unpacker = new Unpacker(false, options)
252
278
  for await (const chunk of chunks) yield* unpacker.push(chunk)
253
279
  unpacker.end()
254
280
  }
package/src/zip/unzip.js CHANGED
@@ -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
@@ -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
@@ -33,6 +33,18 @@ export type EntryType =
33
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
+ // `extended` is the extended headers read since the entry before it, in
37
+ // the order stored, each its kind -- its own pax header, a global one,
38
+ // GNU's long name and long link -- and its magic; the one empty list where
39
+ // none was, and frozen, as a Map is. An extended header, a global one too,
40
+ // with no entry after it is refused. `magic` is the entry's own header's:
41
+ // POSIX's 'ustar', or 'gnu', under which the bytes ustar holds a name's
42
+ // prefix in are GNU's own and not read as one. `typeflag` and `storedMode`
43
+ // are its header's type flag and mode as stored: '\0' where `type` is a
44
+ // 'file' as '0' is, and the file type bits among the permission bits
45
+ // `mode` keeps. `octal` is whether every numeric field of its header -- an
46
+ // extended one's too -- holds octal digits, as POSIX writes them, rather
47
+ // than nothing or GNU's base 256, both of which are read too.
36
48
  export interface Entry {
37
49
  name: string
38
50
  type: EntryType
@@ -50,6 +62,18 @@ export interface Entry {
50
62
  storedLinkname: string
51
63
  pax: ReadonlyMap<string, string>
52
64
  globalPax: ReadonlyMap<string, string>
65
+ extended: readonly ExtendedHeader[]
66
+ magic: 'ustar' | 'gnu'
67
+ typeflag: string
68
+ storedMode: number
69
+ octal: boolean
70
+ }
71
+
72
+ // An extended header, as `extended` lists them.
73
+ export interface ExtendedHeader {
74
+ kind: 'pax' | 'global' | 'longname' | 'longlink'
75
+ magic: 'ustar' | 'gnu'
76
+ octal: boolean
53
77
  }
54
78
 
55
79
  // An entry to write. `name` is cleaned as above, so `./a`, `a/./b` and
@@ -77,34 +101,61 @@ export interface EntryInput {
77
101
  // 'ustar' refuses what it cannot hold, 'pax' holds everything.
78
102
  export type Format = 'gnu' | 'ustar' | 'pax'
79
103
 
104
+ // `symlinksAbove` lets a relative symlink target climb up to that many
105
+ // levels above the archive's root, none by default: for a directory
106
+ // archived on its own, as GitHub archives a tree, that links to the files
107
+ // of the tree it was cut from -- `LICENSE -> ../../LICENSE` in a tree's
108
+ // `packages/a/`, archived under one top directory, climbs one. Past the root
109
+ // the archive cannot tell where a target leads, not even back into itself
110
+ // by the name it is extracted under, so what it passes through there is
111
+ // the caller's to know. An absolute target is refused regardless, and what
112
+ // one call reads with it, another writes with it.
113
+ export interface SymlinkOptions {
114
+ symlinksAbove?: number
115
+ }
116
+
80
117
  // `blocking` is tar's -b: zero padding to a multiple of that many 512-byte
81
118
  // blocks, 20 by default; 1 pads nothing past the two zero end blocks.
82
- export interface PackOptions {
119
+ export interface PackOptions extends SymlinkOptions {
83
120
  format?: Format
84
121
  blocking?: number
85
122
  }
86
123
 
124
+ // `maxEntries` bounds how many entries the archive may hold, every kind
125
+ // counted and a repeat again, its extended headers not: past it the call
126
+ // throws with `limited` set, at the header that crosses it, before that
127
+ // entry is read. No bound by default.
128
+ export interface UnpackOptions extends SymlinkOptions {
129
+ maxEntries?: number
130
+ }
131
+
87
132
  // Both refuse a name that repeats as a different entry -- anything but the
88
133
  // same fields and the same bytes again, however either was stored -- an
89
134
  // 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.
135
+ // climbs out of the archive, further than `symlinksAbove` lets it, or
136
+ // passes through anything in it but a directory, and a hard link to no
137
+ // earlier entry. A hard link to a symlink, directly or down a chain of hard
138
+ // links, is a second name for it, and its target is walked again from that
139
+ // name, which a target safe where the symlink sits need not survive.
95
140
  export function pack(entries: Iterable<EntryInput>, options?: PackOptions): Uint8Array
96
- export function unpack(bytes: Uint8Array): Entry[]
141
+ export function unpack(bytes: Uint8Array, options?: UnpackOptions): Entry[]
97
142
 
98
143
  // The same a piece at a time, as async generators over a plain or an
99
- // async iterable. A stream keeps no entry's data, so a name that repeats
100
- // with the same fields is refused there, and such an archive is for the
101
- // in-memory call. packStream yields each entry's `data` as the very array
102
- // it was given.
144
+ // async iterable. unpackStream yields each entry as it is read, however
145
+ // many a chunk holds, its `data` a view of the chunk wherever one holds it
146
+ // whole: an archive whole in memory, given as one chunk, is read an entry
147
+ // at a time and nothing of it copied. A stream keeps no entry's data, so a
148
+ // name that repeats with the same fields is refused there, and such an
149
+ // archive is for the in-memory call. packStream yields each entry's `data`
150
+ // as the very array it was given.
103
151
  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>
152
+ export function unpackStream(chunks: Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: UnpackOptions): AsyncGenerator<Entry, void, undefined>
105
153
 
106
154
  // `offset` is where in the archive the reader gave up; unset from the writer.
155
+ // `limited` is true where a bound the caller set stopped it, rather than
156
+ // anything wrong with the archive.
107
157
  export class ArchiveError extends Error {
108
- constructor(detail: string, offset?: number)
158
+ constructor(detail: string, offset?: number, options?: { limited?: boolean })
109
159
  offset: number | undefined
160
+ limited: boolean
110
161
  }
package/zip.d.ts CHANGED
@@ -44,9 +44,18 @@ 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
 
@@ -54,19 +63,19 @@ export interface ZipOptions {
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
71
  // Both refuse a name that repeats as a different entry -- anything but the
63
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
 
@@ -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
  }