@preventive/archive 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/zip/unzip.js CHANGED
@@ -1,46 +1,26 @@
1
- // A zip archive in, its entries out, in the order of the central directory,
2
- // which is what a zip is read from. Strict throughout: the end record has to
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
5
- // to nothing, no two entries share any. Each local header has to agree with
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.
9
- // Given a limit, the sizes the entries declare may not add up to more than
10
- // it; since each has to come out at exactly its own, that bounds everything
11
- // unzip() puts out, and it is known from the central directory alone,
12
- // before a single byte is inflated.
13
- //
14
- // One reader serves both calls. It asks for the archive a range at a time:
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
17
- // over one holds no more of it than the entries' names and the entry it is
18
- // on. Everything about the layout is checked before the first entry is
19
- // handed over; what an entry's own data holds is checked as it is reached.
20
-
21
1
  import { crc32 } from '@exodus/bytes/crc.js'
22
2
  import { EMPTY, sameBytes } from '../bytes.js'
23
3
  import { DEFAULT_MODE } from '../entry.js'
24
4
  import { ArchiveError, located } from '../error.js'
25
- import { CENTRAL, END, LOCAL, TYPE_BITS, TYPE_MASK, fromDos, inflate, view } from './format.js'
26
- import { Names, cleanNames, levelsAbove } from '../names.js'
5
+ import { Names, cleanNames } from '../names.js'
27
6
  import { decodeUtf8, quote } from '../text.js'
7
+ import { CENTRAL, END, LOCAL, TYPE_BITS, TYPE_MASK, fromDos, inflate, view } from './format.js'
8
+
9
+ // Strict: the end record ends the archive, the central directory ends at it, and the entries tile
10
+ // everything before it from byte 0. Each local header agrees with the central directory, each entry
11
+ // inflates to exactly its declared size and CRC-32; zip64, encryption and other methods are refused.
28
12
 
29
13
  const DESCRIPTOR = 0x08074b50
30
14
  const ZIP64_LOCATOR = 0x07064b50
31
15
  const ZIP64_EXTRA = 0x0001
32
16
  const TIMESTAMP_EXTRA = 0x5455
33
- // Info-ZIP's Unicode Path field: a second, UTF-8 name that unzip takes over
34
- // the one in the header when its CRC-32 matches that header name.
35
- const UNICODE_PATH_EXTRA = 0x7075
17
+ const UNICODE_PATH_EXTRA = 0x7075 // a second name, which Info-ZIP's unzip takes over the header's
36
18
 
37
19
  const ENCRYPTED = 1
38
20
  const DESCRIBED = 8 // sizes and CRC follow the data, and may be 0 in the local header
39
21
  const DOS_DIRECTORY = 0x10
40
22
 
41
- // Bounds-checked little-endian reads over `bytes`, which sit at `base` in
42
- // the archive: offsets are the archive's own, and one past what was read,
43
- // which stops short only at the archive's end, is past its end.
23
+ // Bounds-checked reads of `bytes`, which sit at `base` in the archive, by the archive's own offsets
44
24
  function reader(bytes, base = 0) {
45
25
  const data = view(bytes)
46
26
  const check = (at, width) => {
@@ -49,14 +29,11 @@ function reader(bytes, base = 0) {
49
29
  return {
50
30
  u16: (at) => (check(at, 2), data.getUint16(at - base, true)),
51
31
  u32: (at) => (check(at, 4), data.getUint32(at - base, true)),
52
- slice: (at, width) => (check(at, width), bytes.subarray(at - base, at - base + width)),
32
+ range: (at, width) => (check(at, width), bytes.subarray(at - base, at - base + width)),
53
33
  }
54
34
  }
55
35
 
56
- // Where the archive's bytes come from, a range at a time: `read` for the
57
- // bytes themselves, `window` for a reader over them, cut short where the
58
- // archive ends. In memory, a range is a view and every window is the one
59
- // reader over the whole; a Blob reads each range as it is asked for.
36
+ // The archive a range at a time: views of it in memory, reads of just that range from a Blob
60
37
  function sourceOf(archive) {
61
38
  if (archive instanceof Uint8Array) {
62
39
  const whole = reader(archive)
@@ -69,11 +46,8 @@ function sourceOf(archive) {
69
46
  throw new ArchiveError('the archive is not a Uint8Array or a Blob')
70
47
  }
71
48
 
72
- // A walk forward through records too small to be worth a read each: a
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
75
- // `at`, and short of `stop`, so that the records after it come in the same
76
- // read and nothing past them is read to no purpose.
49
+ // Reads for a walk forward through small records: each window reads ahead up to CHUNK bytes,
50
+ // short of `stop`, so the records after come in the same read and data past them is not read
77
51
  const CHUNK = 1 << 16
78
52
 
79
53
  function walk(source) {
@@ -91,9 +65,7 @@ function walk(source) {
91
65
  }
92
66
  }
93
67
 
94
- // The end record is the last 22 bytes plus its comment, and nothing after.
95
- // Read with the 20 bytes ahead of the furthest back it can start, where a
96
- // zip64 locator would sit.
68
+ // The last 22 bytes and the comment they count, read with the 20 before, where a zip64 locator would be
97
69
  async function findEnd(source) {
98
70
  const { size } = source
99
71
  const r = await source.window(Math.max(0, size - 22 - 0xffff - 20), size)
@@ -106,8 +78,7 @@ async function findEnd(source) {
106
78
  throw new ArchiveError('no end of central directory record')
107
79
  }
108
80
 
109
- // Extra fields, each an id, a length and that many bytes, tiling the room,
110
- // in the order stored; copies, so that none holds on to the chunk read.
81
+ // Each a copy, holding on to no chunk
111
82
  function extras(raw, at) {
112
83
  const fields = []
113
84
  const r = reader(raw)
@@ -116,8 +87,6 @@ function extras(raw, at) {
116
87
  const size = r.u16(pos + 2)
117
88
  if (pos + 4 + size > raw.length) throw new ArchiveError('an extra field runs past its room', at)
118
89
  if (id === ZIP64_EXTRA) throw new ArchiveError('zip64 is not supported', at)
119
- // Every name here is UTF-8 already, so this field can only disagree with
120
- // the name checked above -- and unzip would extract the name it carries.
121
90
  if (id === UNICODE_PATH_EXTRA) throw new ArchiveError('an entry carries a second name in a Unicode path extra field', at)
122
91
  fields.push({ id, data: raw.slice(pos + 4, pos + 4 + size) })
123
92
  pos += 4 + size
@@ -145,18 +114,15 @@ async function readCentral(read, at) {
145
114
  internal: r.u16(at + 36),
146
115
  attributes: r.u32(at + 38),
147
116
  offset: r.u32(at + 42),
148
- // A copy, so that no entry holds on to the chunk it was read from.
149
- name: r.slice(at + 46, nameLength).slice(),
117
+ name: r.range(at + 46, nameLength).slice(), // a copy, holding on to no chunk
150
118
  next: at + 46 + nameLength + extraLength + r.u16(at + 32),
151
119
  }
152
120
  if (r.u16(at + 34) !== 0) throw new ArchiveError('the archive spans several disks', at)
153
121
  if (entry.flags & ENCRYPTED) throw new ArchiveError('an entry is encrypted', at)
154
122
  if (entry.method !== 0 && entry.method !== 8) throw new ArchiveError(`compression method ${entry.method} is not stored or deflate`, at)
155
123
  if (entry.csize === 0xffffffff || entry.usize === 0xffffffff || entry.offset === 0xffffffff) throw new ArchiveError('zip64 is not supported', at)
156
- // The DOS fields have to be a time even where the extended timestamp,
157
- // an exact one, is the time kept.
158
- entry.mtime = fromDos(entry.date, entry.time, at)
159
- entry.extra = extras(r.slice(at + 46 + nameLength, extraLength), at)
124
+ entry.mtime = fromDos(entry.date, entry.time, at) // a valid DOS time even where the extended one is kept
125
+ entry.extra = extras(r.range(at + 46 + nameLength, extraLength), at)
160
126
  const stamp = entry.extra.find((field) => field.id === TIMESTAMP_EXTRA)?.data
161
127
  if (stamp !== undefined && stamp[0] & 1) {
162
128
  if (stamp.length < 5) throw new ArchiveError('an extended timestamp is cut short', at)
@@ -165,35 +131,28 @@ async function readCentral(read, at) {
165
131
  return entry
166
132
  }
167
133
 
168
- // The local header checked against the central entry; returns where the
169
- // entry's bytes end, which has to be `boundary`, the next record's start,
170
- // and notes where its data starts. The two records have to agree on
171
- // everything both carry -- flags included, since a descriptor bit set in
172
- // one and not the other is read two ways by two readers -- and the local
173
- // sizes and CRC may be 0 only where a descriptor carries them. `stop` is
174
- // as far as the header is read ahead of itself.
175
- async function readLocal(read, entry, boundary, stop) {
176
- const at = entry.offset
134
+ // Checks the local header against the central one, flags included, as readers differ on a descriptor bit
135
+ // set in one alone. Returns where the entry ends, which must be `boundary`; `stop` bounds the read-ahead.
136
+ async function readLocal(read, entry) {
137
+ const { offset: at, boundary, stop } = entry
177
138
  let r = await read(at, 30, stop)
178
139
  if (r.u32(at) !== LOCAL) throw new ArchiveError('no local header where the central directory points', at)
179
140
  const nameLength = r.u16(at + 26)
180
141
  const extraLength = r.u16(at + 28)
181
142
  r = await read(at, 30 + nameLength + extraLength, stop)
182
- if (!sameBytes(r.slice(at + 30, nameLength), entry.name)) throw new ArchiveError('the local header names a different entry', at)
143
+ if (!sameBytes(r.range(at + 30, nameLength), entry.name)) throw new ArchiveError('the local header names a different entry', at)
183
144
  const shared = [[4, 'version', 'a different version'], [6, 'flags', 'different flags'], [8, 'method', 'a different compression method'], [10, 'time', 'a different time'], [12, 'date', 'a different date']]
184
145
  for (const [field, key, what] of shared) {
185
146
  if (r.u16(at + field) !== entry[key]) throw new ArchiveError(`the local header has ${what}`, at)
186
147
  }
187
- extras(r.slice(at + 30 + nameLength, extraLength), at)
148
+ extras(r.range(at + 30 + nameLength, extraLength), at)
188
149
  const described = entry.flags & DESCRIBED
189
150
  const agrees = (field, value) => r.u32(at + field) === value || (described && r.u32(at + field) === 0)
190
151
  if (!agrees(14, entry.crc) || !agrees(18, entry.csize) || !agrees(22, entry.usize)) throw new ArchiveError('the local header disagrees with the central directory', at)
191
152
  entry.dataAt = at + 30 + nameLength + extraLength
192
153
  let end = entry.dataAt + entry.csize
193
154
  if (described) {
194
- // The descriptor may start with its signature or not, and a CRC can be
195
- // that very value, so both layouts are tried against the record; where
196
- // both fit (every word the signature), the one reaching the boundary is it.
155
+ // With or without its signature, which a CRC can equal: where both fit, the one reaching `boundary`
197
156
  const d = await read(end, 16, boundary)
198
157
  const matches = (from) => d.u32(from) === entry.crc && d.u32(from + 4) === entry.csize && d.u32(from + 8) === entry.usize
199
158
  const signed = d.u32(end) === DESCRIPTOR && matches(end + 4)
@@ -204,9 +163,7 @@ async function readLocal(read, entry, boundary, stop) {
204
163
  return end
205
164
  }
206
165
 
207
- // A directory marker anywhere -- the Unix type bits, the DOS bit -- needs
208
- // the slash; the slash needs no marker, since Java writes no attributes at
209
- // all and every JAR has directories.
166
+ // A directory marker needs the slash; the slash needs no marker, as Java writes no attributes
210
167
  function typeOf(entry, rawName, mode) {
211
168
  const format = mode & TYPE_MASK
212
169
  if (rawName.endsWith('/')) {
@@ -223,33 +180,29 @@ function typeOf(entry, rawName, mode) {
223
180
  async function entryOf(source, entry, names) {
224
181
  const { at, method, csize, usize } = entry
225
182
  const rawName = decodeUtf8(entry.name, 'entry name', at)
226
- // Only a Unix maker's attributes carry a mode.
227
- const mode = entry.madeBy >> 8 === 3 ? entry.attributes >>> 16 : 0
183
+ const mode = entry.madeBy >> 8 === 3 ? entry.attributes >>> 16 : 0 // only a Unix maker's carry one
228
184
  const type = typeOf(entry, rawName, mode)
229
185
  if (type === 'directory' && usize !== 0) throw new ArchiveError(`directory ${quote(rawName)} has data`, at)
230
186
  if (method === 0 && csize !== usize) throw new ArchiveError('a stored entry has two sizes', at)
231
- // A Blob can come back short if what is behind it changed since the
232
- // layout was checked; the bytes checked are the bytes read, or nothing.
187
+ // A Blob changed since the layout was checked can come back short
233
188
  const raw = await source.read(entry.dataAt, entry.dataAt + csize)
234
189
  if (raw.length !== csize) throw new ArchiveError('the archive is truncated', entry.dataAt)
235
190
  const body = method === 8 ? await inflate(raw, usize, at) : raw
236
191
  if (crc32(body) !== entry.crc) throw new ArchiveError('the data does not match its CRC-32', at)
237
192
  const target = type === 'symlink' ? decodeUtf8(body, 'symlink target', at) : ''
238
- const named = located(() => cleanNames(rawName, type, target, names.above), at)
239
193
  const out = {
240
- ...named, type, mode: mode === 0 ? DEFAULT_MODE[type] : mode & 0o7777, mtime: entry.mtime, data: type === 'file' ? body : EMPTY, storedName: rawName,
194
+ ...located(() => cleanNames(rawName, type, target, names.above), at),
195
+ type, mode: mode === 0 ? DEFAULT_MODE[type] : mode & 0o7777, mtime: entry.mtime, data: type === 'file' ? body : EMPTY, storedName: rawName,
241
196
  system: entry.madeBy >> 8, version: entry.version, flags: entry.flags, internalAttributes: entry.internal, attributes: entry.attributes, extra: entry.extra,
242
197
  }
243
198
  located(() => names.add(out), at)
244
199
  return out
245
200
  }
246
201
 
247
- // The entries one at a time, the layout all checked before the first.
248
- // `keep` holds entries for a repeat to be compared with, which only the
249
- // in-memory call can afford.
202
+ // The layout is checked whole before the first entry is read
250
203
  async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep = false) {
251
204
  if (limit !== Infinity && !(Number.isSafeInteger(limit) && limit >= 0)) throw new ArchiveError(`limit ${String(limit)} is not a whole number of bytes`)
252
- const above = levelsAbove(symlinksAbove)
205
+ const names = new Names(keep, symlinksAbove)
253
206
  const { end, r } = await findEnd(source)
254
207
  const count = r.u16(end + 8)
255
208
  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)
@@ -257,9 +210,7 @@ async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep =
257
210
  const start = r.u32(end + 16)
258
211
  if (count === 0xffff || size === 0xffffffff || start === 0xffffffff) throw new ArchiveError('zip64 is not supported', end)
259
212
  if (start + size !== end) throw new ArchiveError('the central directory does not end at the end record', end)
260
- // A chunk at a time, not the whole of a directory that can near 4 GiB,
261
- // and cut only at the archive's end, so a record counted past the
262
- // directory meets the end record, as it would in the archive.
213
+ // A window at a time, cut only at the archive's end, so a record counted past the directory meets the end record
263
214
  const directory = walk(source)
264
215
  const list = []
265
216
  let pos = start
@@ -272,26 +223,21 @@ async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep =
272
223
  pos = entry.next
273
224
  }
274
225
  if (pos !== end) throw new ArchiveError('the central directory does not hold what the end record counts', pos)
275
- let expected = 0
226
+ // Each entry ends where the next starts, the last at the directory. Headers are read ahead through,
227
+ // but not the data between: each `stop` is the next data's start, or past it while it is empty.
276
228
  const sorted = list.toSorted((a, b) => a.offset - b.offset)
277
- // Each entry ends where the next starts, the last at the directory. The
278
- // headers are read ahead through, but never the data between them, which
279
- // is read again when its entry is reached: from each header to its own
280
- // data, give or take a descriptor, by the directory's sizes, or on through
281
- // the next header where it has none.
282
- const boundaries = []
283
- const stops = []
284
229
  for (let i = sorted.length - 1; i >= 0; i--) {
285
- boundaries[i] = sorted[i + 1]?.offset ?? start
286
- stops[i] = sorted[i].csize === 0 && i + 1 < sorted.length ? stops[i + 1] : boundaries[i] - sorted[i].csize
230
+ const [entry, next] = [sorted[i], sorted[i + 1]]
231
+ entry.boundary = next?.offset ?? start
232
+ entry.stop = entry.csize === 0 && next ? next.stop : entry.boundary - entry.csize
287
233
  }
288
234
  const locals = walk(source)
289
- for (const [i, entry] of sorted.entries()) {
235
+ let expected = 0
236
+ for (const entry of sorted) {
290
237
  if (entry.offset !== expected) throw new ArchiveError(entry.offset > expected ? 'bytes belong to no entry' : 'two entries overlap', expected)
291
- expected = await readLocal(locals, entry, boundaries[i], stops[i])
238
+ expected = await readLocal(locals, entry)
292
239
  }
293
240
  if (expected !== start) throw new ArchiveError('bytes belong to no entry', expected)
294
- const names = new Names(keep, above)
295
241
  for (const entry of list) yield await entryOf(source, entry, names)
296
242
  }
297
243
 
package/src/zip/zip.js CHANGED
@@ -1,24 +1,22 @@
1
- // Entries in, a zip archive out, laid out the way Info-ZIP lays one out: a
2
- // Unix maker, the mode in the external attributes, a symlink as a stored
3
- // entry whose data is its target, an extended-timestamp extra field for an
4
- // exact UTC mtime, and each file deflated only where that made it smaller.
5
-
6
1
  import { crc32 } from '@exodus/bytes/crc.js'
2
+ import { utf8fromString } from '@exodus/bytes/utf8.js'
7
3
  import { concat, isAscii } from '../bytes.js'
8
4
  import { DEFAULT_MODE, checkEntry, wireName } from '../entry.js'
9
5
  import { ArchiveError } from '../error.js'
6
+ import { Names, cleanNames } from '../names.js'
7
+ import { quote } from '../text.js'
10
8
  import { CENTRAL, END, LOCAL, TYPE_BITS, deflate, record, toDos } from './format.js'
11
- import { Names, cleanNames, levelsAbove } from '../names.js'
12
- import { encodeUtf8, quote } from '../text.js'
9
+
10
+ // Laid out as Info-ZIP does: a Unix maker with the mode in the external attributes, a symlink stored
11
+ // with its target as data, an extended timestamp, and each file deflated only where that is smaller
13
12
 
14
13
  const METHODS = new Set(['deflate', 'store'])
15
14
 
16
15
  const MADE_BY = (3 << 8) | 20 // Unix, spec 2.0
17
16
  const UTF8_NAME = 0x800
18
- const DOS_EPOCH = 315532800 // 1980-01-01T00:00:00Z, the earliest DOS time
19
- const LAST_STAMP = 0x7fffffff // the extended timestamp is a signed 32-bit time
20
- // A count of 0xffff or a size or offset of 0xffffffff sends a reader to
21
- // zip64, so the last value short of each is the most this writes.
17
+ const DOS_EPOCH = 315532800 // 1980-01-01T00:00:00Z
18
+ const LAST_STAMP = 0x7fffffff // the extended timestamp is signed 32-bit
19
+ // 0xffff entries or 0xffffffff bytes send a reader to zip64
22
20
  const MAX_ENTRIES = 0xfffe
23
21
  const MAX_SIZE = 0xfffffffe
24
22
 
@@ -27,45 +25,39 @@ function integer(value, what, min, max) {
27
25
  return value
28
26
  }
29
27
 
30
- function normalize(entry) {
28
+ function normalize(entry, above) {
31
29
  const checked = checkEntry(entry, TYPE_BITS)
30
+ const { name, type, linkname } = checked
32
31
  return {
33
32
  ...checked,
34
- mode: integer(entry.mode ?? DEFAULT_MODE[checked.type], 'mode', 0, 0o7777),
33
+ mode: integer(entry.mode ?? DEFAULT_MODE[type], 'mode', 0, 0o7777),
35
34
  mtime: integer(entry.mtime ?? DOS_EPOCH, 'mtime', DOS_EPOCH, LAST_STAMP),
35
+ ...cleanNames(name, type, linkname, above),
36
36
  }
37
37
  }
38
38
 
39
- // 0x5455: flag bit 0 and the mtime, as Info-ZIP writes in the central copy.
39
+ // 0x5455 with flag bit 0 and the mtime, as Info-ZIP writes it in the central directory
40
40
  const timestamp = (mtime) => record([[2, 0x5455], [2, 5], [1, 1], [4, mtime]])
41
41
 
42
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, levelsAbove(symlinksAbove))
44
+ const names = new Names(true, symlinksAbove)
45
45
  const locals = []
46
46
  const centrals = []
47
47
  let offset = 0
48
48
  let count = 0
49
- for (const given of entries) {
50
- const entry = normalize(given)
51
- const e = { ...entry, ...cleanNames(entry.name, entry.type, entry.linkname, names.above) }
49
+ for (const entry of entries) {
50
+ const e = normalize(entry, names.above)
52
51
  names.add(e)
53
52
  if (++count > MAX_ENTRIES) throw new ArchiveError(`more than ${MAX_ENTRIES} entries would need zip64`)
54
- const name = encodeUtf8(wireName(e), 'entry name')
55
- const body = e.type === 'symlink' ? encodeUtf8(e.linkname, 'symlink target') : e.data
56
- // Before deflating, which is all the work an entry takes, and is only
57
- // ever kept where it made the entry smaller.
53
+ const name = utf8fromString(wireName(e))
54
+ const body = e.type === 'symlink' ? utf8fromString(e.linkname) : e.data
55
+ // Before deflating, which may not make it smaller
58
56
  if (body.length > MAX_SIZE || offset > MAX_SIZE) throw new ArchiveError(`${quote(e.name)} would need zip64`)
59
- let stored = body
60
- let compression = 0
61
- if (method === 'deflate' && e.type === 'file' && body.length) {
62
- const packed = await deflate(body)
63
- if (packed.length < body.length) {
64
- stored = packed
65
- compression = 8
66
- }
67
- }
68
- const { time, date } = toDos(e.mtime)
57
+ const packed = method === 'deflate' && e.type === 'file' && body.length ? await deflate(body) : body
58
+ const stored = packed.length < body.length ? packed : body
59
+ const compression = stored === body ? 0 : 8
60
+ const { time, date } = toDos(e.mtime) // within DOS time, as normalize holds mtime to 1980-2038
69
61
  const extra = timestamp(e.mtime)
70
62
  const common = [
71
63
  [2, compression === 8 ? 20 : 10], [2, isAscii(name) ? 0 : UTF8_NAME], [2, compression], [2, time], [2, date],