@preventive/archive 1.3.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,19 +78,17 @@ 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.
81
+ // Each a copy, holding on to no chunk
110
82
  function extras(raw, at) {
111
- const fields = new Map()
83
+ const fields = []
112
84
  const r = reader(raw)
113
85
  for (let pos = 0; pos < raw.length;) {
114
86
  const id = r.u16(pos)
115
87
  const size = r.u16(pos + 2)
116
88
  if (pos + 4 + size > raw.length) throw new ArchiveError('an extra field runs past its room', at)
117
89
  if (id === ZIP64_EXTRA) throw new ArchiveError('zip64 is not supported', at)
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.
120
90
  if (id === UNICODE_PATH_EXTRA) throw new ArchiveError('an entry carries a second name in a Unicode path extra field', at)
121
- if (!fields.has(id)) fields.set(id, raw.subarray(pos + 4, pos + 4 + size))
91
+ fields.push({ id, data: raw.slice(pos + 4, pos + 4 + size) })
122
92
  pos += 4 + size
123
93
  }
124
94
  return fields
@@ -141,20 +111,19 @@ async function readCentral(read, at) {
141
111
  crc: r.u32(at + 16),
142
112
  csize: r.u32(at + 20),
143
113
  usize: r.u32(at + 24),
114
+ internal: r.u16(at + 36),
144
115
  attributes: r.u32(at + 38),
145
116
  offset: r.u32(at + 42),
146
- // A copy, so that no entry holds on to the chunk it was read from.
147
- name: r.slice(at + 46, nameLength).slice(),
117
+ name: r.range(at + 46, nameLength).slice(), // a copy, holding on to no chunk
148
118
  next: at + 46 + nameLength + extraLength + r.u16(at + 32),
149
119
  }
150
120
  if (r.u16(at + 34) !== 0) throw new ArchiveError('the archive spans several disks', at)
151
121
  if (entry.flags & ENCRYPTED) throw new ArchiveError('an entry is encrypted', at)
152
122
  if (entry.method !== 0 && entry.method !== 8) throw new ArchiveError(`compression method ${entry.method} is not stored or deflate`, at)
153
123
  if (entry.csize === 0xffffffff || entry.usize === 0xffffffff || entry.offset === 0xffffffff) throw new ArchiveError('zip64 is not supported', at)
154
- // The DOS fields have to be a time even where the extended timestamp,
155
- // an exact one, is the time kept.
156
- entry.mtime = fromDos(entry.date, entry.time, at)
157
- const stamp = extras(r.slice(at + 46 + nameLength, extraLength), at).get(TIMESTAMP_EXTRA)
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)
126
+ const stamp = entry.extra.find((field) => field.id === TIMESTAMP_EXTRA)?.data
158
127
  if (stamp !== undefined && stamp[0] & 1) {
159
128
  if (stamp.length < 5) throw new ArchiveError('an extended timestamp is cut short', at)
160
129
  entry.mtime = view(stamp).getInt32(1, true)
@@ -162,35 +131,28 @@ async function readCentral(read, at) {
162
131
  return entry
163
132
  }
164
133
 
165
- // The local header checked against the central entry; returns where the
166
- // entry's bytes end, which has to be `boundary`, the next record's start,
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
170
- // sizes and CRC may be 0 only where a descriptor carries them. `stop` is
171
- // as far as the header is read ahead of itself.
172
- async function readLocal(read, entry, boundary, stop) {
173
- 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
174
138
  let r = await read(at, 30, stop)
175
139
  if (r.u32(at) !== LOCAL) throw new ArchiveError('no local header where the central directory points', at)
176
140
  const nameLength = r.u16(at + 26)
177
141
  const extraLength = r.u16(at + 28)
178
142
  r = await read(at, 30 + nameLength + extraLength, stop)
179
- 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)
180
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']]
181
145
  for (const [field, key, what] of shared) {
182
146
  if (r.u16(at + field) !== entry[key]) throw new ArchiveError(`the local header has ${what}`, at)
183
147
  }
184
- extras(r.slice(at + 30 + nameLength, extraLength), at)
148
+ extras(r.range(at + 30 + nameLength, extraLength), at)
185
149
  const described = entry.flags & DESCRIBED
186
150
  const agrees = (field, value) => r.u32(at + field) === value || (described && r.u32(at + field) === 0)
187
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)
188
152
  entry.dataAt = at + 30 + nameLength + extraLength
189
153
  let end = entry.dataAt + entry.csize
190
154
  if (described) {
191
- // The descriptor may start with its signature or not, and a CRC can be
192
- // that very value, so both layouts are tried against the record; where
193
- // 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`
194
156
  const d = await read(end, 16, boundary)
195
157
  const matches = (from) => d.u32(from) === entry.crc && d.u32(from + 4) === entry.csize && d.u32(from + 8) === entry.usize
196
158
  const signed = d.u32(end) === DESCRIPTOR && matches(end + 4)
@@ -201,9 +163,7 @@ async function readLocal(read, entry, boundary, stop) {
201
163
  return end
202
164
  }
203
165
 
204
- // A directory marker anywhere -- the Unix type bits, the DOS bit -- needs
205
- // the slash; the slash needs no marker, since Java writes no attributes at
206
- // all and every JAR has directories.
166
+ // A directory marker needs the slash; the slash needs no marker, as Java writes no attributes
207
167
  function typeOf(entry, rawName, mode) {
208
168
  const format = mode & TYPE_MASK
209
169
  if (rawName.endsWith('/')) {
@@ -220,30 +180,29 @@ function typeOf(entry, rawName, mode) {
220
180
  async function entryOf(source, entry, names) {
221
181
  const { at, method, csize, usize } = entry
222
182
  const rawName = decodeUtf8(entry.name, 'entry name', at)
223
- // Only a Unix maker's attributes carry a mode.
224
- 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
225
184
  const type = typeOf(entry, rawName, mode)
226
185
  if (type === 'directory' && usize !== 0) throw new ArchiveError(`directory ${quote(rawName)} has data`, at)
227
186
  if (method === 0 && csize !== usize) throw new ArchiveError('a stored entry has two sizes', at)
228
- // A Blob can come back short if what is behind it changed since the
229
- // 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
230
188
  const raw = await source.read(entry.dataAt, entry.dataAt + csize)
231
189
  if (raw.length !== csize) throw new ArchiveError('the archive is truncated', entry.dataAt)
232
190
  const body = method === 8 ? await inflate(raw, usize, at) : raw
233
191
  if (crc32(body) !== entry.crc) throw new ArchiveError('the data does not match its CRC-32', at)
234
192
  const target = type === 'symlink' ? decodeUtf8(body, 'symlink target', at) : ''
235
- const named = located(() => cleanNames(rawName, type, target, names.above), at)
236
- const out = { ...named, type, mode: mode === 0 ? DEFAULT_MODE[type] : mode & 0o7777, mtime: entry.mtime, data: type === 'file' ? body : EMPTY, storedName: rawName }
193
+ const out = {
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,
196
+ system: entry.madeBy >> 8, version: entry.version, flags: entry.flags, internalAttributes: entry.internal, attributes: entry.attributes, extra: entry.extra,
197
+ }
237
198
  located(() => names.add(out), at)
238
199
  return out
239
200
  }
240
201
 
241
- // The entries one at a time, the layout all checked before the first.
242
- // `keep` holds entries for a repeat to be compared with, which only the
243
- // in-memory call can afford.
202
+ // The layout is checked whole before the first entry is read
244
203
  async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep = false) {
245
204
  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)
205
+ const names = new Names(keep, symlinksAbove)
247
206
  const { end, r } = await findEnd(source)
248
207
  const count = r.u16(end + 8)
249
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)
@@ -251,9 +210,7 @@ async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep =
251
210
  const start = r.u32(end + 16)
252
211
  if (count === 0xffff || size === 0xffffffff || start === 0xffffffff) throw new ArchiveError('zip64 is not supported', end)
253
212
  if (start + size !== end) throw new ArchiveError('the central directory does not end at the end record', end)
254
- // A chunk at a time, not the whole of a directory that can near 4 GiB,
255
- // and cut only at the archive's end, so a record counted past the
256
- // 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
257
214
  const directory = walk(source)
258
215
  const list = []
259
216
  let pos = start
@@ -266,24 +223,21 @@ async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep =
266
223
  pos = entry.next
267
224
  }
268
225
  if (pos !== end) throw new ArchiveError('the central directory does not hold what the end record counts', pos)
269
- 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.
270
228
  const sorted = list.toSorted((a, b) => a.offset - b.offset)
271
- const boundaries = sorted.map((_, i) => sorted[i + 1]?.offset ?? start)
272
- // The headers are read ahead through, but never the data between them,
273
- // which is read again when its entry is reached: from each header to its
274
- // own data, give or take a descriptor, by the directory's sizes, or on
275
- // through the next header where it has none.
276
- const stops = []
277
229
  for (let i = sorted.length - 1; i >= 0; i--) {
278
- 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
279
233
  }
280
234
  const locals = walk(source)
281
- for (const [i, entry] of sorted.entries()) {
235
+ let expected = 0
236
+ for (const entry of sorted) {
282
237
  if (entry.offset !== expected) throw new ArchiveError(entry.offset > expected ? 'bytes belong to no entry' : 'two entries overlap', expected)
283
- expected = await readLocal(locals, entry, boundaries[i], stops[i])
238
+ expected = await readLocal(locals, entry)
284
239
  }
285
240
  if (expected !== start) throw new ArchiveError('bytes belong to no entry', expected)
286
- const names = new Names(keep, above)
287
241
  for (const entry of list) yield await entryOf(source, entry, names)
288
242
  }
289
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],