@preventive/archive 1.2.2 → 1.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/archive",
3
- "version": "1.2.2",
3
+ "version": "1.4.0",
4
4
  "description": "Strict in-memory tar and zip on browser APIs",
5
5
  "type": "module",
6
6
  "exports": {
package/src/names.js CHANGED
@@ -45,9 +45,7 @@ function checkText(path, what) {
45
45
  // that is not one is what a drive letter is looked for on.
46
46
  if (/^[a-zA-Z]:/u.test(segments.find((segment) => segment !== '.') ?? '')) throw new ArchiveError(`${what} ${quote(path)} starts with a drive letter`)
47
47
  if (tooLong(path, PATH_MAX)) throw new ArchiveError(`${what} ${quote(path)} is longer than ${PATH_MAX} bytes`)
48
- for (const segment of segments) {
49
- if (tooLong(segment, NAME_MAX)) throw new ArchiveError(`${what} ${quote(path)} has a segment longer than ${NAME_MAX} bytes`)
50
- }
48
+ if (segments.some((segment) => tooLong(segment, NAME_MAX))) throw new ArchiveError(`${what} ${quote(path)} has a segment longer than ${NAME_MAX} bytes`)
51
49
  return segments
52
50
  }
53
51
 
package/src/tar/header.js CHANGED
@@ -56,6 +56,7 @@ const latin1 = (text) => Uint8Array.from(text, (c) => c.codePointAt(0))
56
56
  const ascii = (raw) => String.fromCodePoint(...raw)
57
57
  // Throws (RangeError) rather than overwriting the next field.
58
58
  const put = (block, offset, size, bytes) => block.subarray(offset, offset + size).set(bytes)
59
+ const field = (block, offset, size) => untilNul(block.subarray(offset, offset + size))
59
60
 
60
61
  export const octalMax = (size) => 8 ** (size - 1) - 1
61
62
  export const fitsOctal = (value, size) => value >= 0 && value <= octalMax(size)
@@ -93,7 +94,7 @@ export function readNumber(block, offset, size, what, at, signed = false) {
93
94
  if (v > BigInt(Number.MAX_SAFE_INTEGER) || v < -BigInt(Number.MAX_SAFE_INTEGER)) throw new ArchiveError(`the ${what} field is too large`, at)
94
95
  return Number(v)
95
96
  }
96
- const match = /^ *([0-7]*) *$/u.exec(ascii(untilNul(block.subarray(offset, offset + size))))
97
+ const match = /^ *([0-7]*) *$/u.exec(ascii(field(block, offset, size)))
97
98
  if (!match) throw new ArchiveError(`the ${what} field is not an octal number`, at)
98
99
  return match[1] === '' ? 0 : Number.parseInt(match[1], 8)
99
100
  }
@@ -103,8 +104,6 @@ export function untilNul(raw) {
103
104
  return end === -1 ? raw : raw.subarray(0, end)
104
105
  }
105
106
 
106
- const field = (block, offset, size) => untilNul(block.subarray(offset, offset + size))
107
-
108
107
  // Every byte, with the checksum field itself counted as spaces.
109
108
  function checksum(block) {
110
109
  let sum = 8 * 0x20
@@ -137,7 +136,7 @@ export function encodeHeader(f) {
137
136
 
138
137
  // Whether a numeric field holds octal digits, as POSIX writes it, rather
139
138
  // 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))))
139
+ const isOctal = (block, offset, size) => /^ *[0-7]+ *$/u.test(ascii(field(block, offset, size)))
141
140
 
142
141
  export function decodeHeader(block, at) {
143
142
  if (checksum(block) !== readNumber(block, CHKSUM, 8, 'checksum', at)) throw new ArchiveError('header checksum does not match', at)
package/src/tar/unpack.js CHANGED
@@ -25,9 +25,7 @@ const MAX_EXTENDED = 1 << 20
25
25
  const SPARSE_KEYS = new Set(['SCHILY.realsize', 'SUN.holesdata'])
26
26
 
27
27
  function sparse(keys, at) {
28
- for (const key of keys) {
29
- if (key.startsWith('GNU.sparse.') || SPARSE_KEYS.has(key)) throw new ArchiveError('sparse entries are not supported', at)
30
- }
28
+ if (keys.some((key) => key.startsWith('GNU.sparse.') || SPARSE_KEYS.has(key))) throw new ArchiveError('sparse entries are not supported', at)
31
29
  }
32
30
 
33
31
  function paxNumber(value, what, at) {
@@ -78,13 +76,16 @@ class Unpacker {
78
76
  #done = false
79
77
  #count = 0
80
78
  #maxEntries
79
+ #trailingGlobal
81
80
 
82
81
  // `keep` holds entries for a repeat to be compared with, which only the
83
82
  // in-memory call can afford; the options are unpack's.
84
- constructor(keep, { symlinksAbove, maxEntries = Infinity } = {}) {
83
+ constructor(keep, { symlinksAbove, maxEntries = Infinity, trailingGlobal = false } = {}) {
85
84
  if (maxEntries !== Infinity && !(Number.isSafeInteger(maxEntries) && maxEntries >= 0)) throw new ArchiveError(`maxEntries ${String(maxEntries)} is not a whole number of entries`)
85
+ if (typeof trailingGlobal !== 'boolean') throw new ArchiveError(`trailingGlobal ${String(trailingGlobal)} is not a boolean`)
86
86
  this.#names = new Names(keep, levelsAbove(symlinksAbove))
87
87
  this.#maxEntries = maxEntries
88
+ this.#trailingGlobal = trailingGlobal
88
89
  }
89
90
 
90
91
  // The entries a chunk completes, each as it is read, so that a chunk
@@ -155,8 +156,9 @@ class Unpacker {
155
156
  if (block === null) return false
156
157
  const at = this.#position - BLOCK
157
158
  if (isZeroBlock(block)) {
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)
159
+ // A global header too: one with no entry after it stands for nothing,
160
+ // unless the caller takes it as GNU tar does (trailingGlobal).
161
+ if (this.#extended.some(({ kind }) => kind !== 'global' || !this.#trailingGlobal)) throw new ArchiveError('an extended header is not followed by an entry', at)
160
162
  if (++this.#zeros === 2) {
161
163
  this.#done = true
162
164
  const after = this.#position
@@ -190,20 +192,20 @@ class Unpacker {
190
192
  entry.data = raw
191
193
  located(() => this.#names.add(entry), at)
192
194
  out.push(entry)
193
- } else if (extended === 'global') {
195
+ return true
196
+ }
197
+ if (extended === 'global') {
194
198
  this.#global = decodePax(raw, at)
195
- for (const key of ['path', 'linkpath', 'size']) {
196
- if (this.#global.has(key)) throw new ArchiveError(`a global header sets ${key}`, at)
197
- }
199
+ const set = ['path', 'linkpath', 'size'].find((key) => this.#global.has(key))
200
+ if (set !== undefined) throw new ArchiveError(`a global header sets ${set}`, at)
198
201
  // Once, here: a global header stands until another replaces it, and
199
202
  // re-reading its keys under every entry is work an archive can ask for.
200
203
  sparse(this.#global.keys(), at)
201
- this.#extended.push(Object.freeze({ kind: extended, magic, octal }))
202
204
  } else {
203
205
  if (this.#pending[extended] !== null) throw new ArchiveError(`two ${extended} headers ahead of one entry`, at)
204
206
  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 }))
206
207
  }
208
+ this.#extended.push(Object.freeze({ kind: extended, magic, octal }))
207
209
  return true
208
210
  }
209
211
 
@@ -233,6 +235,7 @@ class Unpacker {
233
235
  if (hasUnsafe(value, false)) throw new ArchiveError(`${key} ${quote(value)} holds a control or formatting character`, at)
234
236
  return value
235
237
  }
238
+ const device = isDevice(type)
236
239
  const entry = {
237
240
  name,
238
241
  type,
@@ -243,8 +246,8 @@ class Unpacker {
243
246
  uname: owner('uname'),
244
247
  gname: owner('gname'),
245
248
  linkname,
246
- devmajor: isDevice(type) ? number('devmajor') : 0,
247
- devminor: isDevice(type) ? number('devminor') : 0,
249
+ devmajor: device ? number('devmajor') : 0,
250
+ devminor: device ? number('devminor') : 0,
248
251
  data: EMPTY,
249
252
  storedName: rawName,
250
253
  storedLinkname: rawTarget,
package/src/zip/unzip.js CHANGED
@@ -106,9 +106,10 @@ async function findEnd(source) {
106
106
  throw new ArchiveError('no end of central directory record')
107
107
  }
108
108
 
109
- // Extra fields, each an id, a length and that many bytes, tiling the room.
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.
110
111
  function extras(raw, at) {
111
- const fields = new Map()
112
+ const fields = []
112
113
  const r = reader(raw)
113
114
  for (let pos = 0; pos < raw.length;) {
114
115
  const id = r.u16(pos)
@@ -118,7 +119,7 @@ function extras(raw, at) {
118
119
  // Every name here is UTF-8 already, so this field can only disagree with
119
120
  // the name checked above -- and unzip would extract the name it carries.
120
121
  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))
122
+ fields.push({ id, data: raw.slice(pos + 4, pos + 4 + size) })
122
123
  pos += 4 + size
123
124
  }
124
125
  return fields
@@ -141,6 +142,7 @@ async function readCentral(read, at) {
141
142
  crc: r.u32(at + 16),
142
143
  csize: r.u32(at + 20),
143
144
  usize: r.u32(at + 24),
145
+ internal: r.u16(at + 36),
144
146
  attributes: r.u32(at + 38),
145
147
  offset: r.u32(at + 42),
146
148
  // A copy, so that no entry holds on to the chunk it was read from.
@@ -154,7 +156,8 @@ async function readCentral(read, at) {
154
156
  // The DOS fields have to be a time even where the extended timestamp,
155
157
  // an exact one, is the time kept.
156
158
  entry.mtime = fromDos(entry.date, entry.time, at)
157
- const stamp = extras(r.slice(at + 46 + nameLength, extraLength), at).get(TIMESTAMP_EXTRA)
159
+ entry.extra = extras(r.slice(at + 46 + nameLength, extraLength), at)
160
+ const stamp = entry.extra.find((field) => field.id === TIMESTAMP_EXTRA)?.data
158
161
  if (stamp !== undefined && stamp[0] & 1) {
159
162
  if (stamp.length < 5) throw new ArchiveError('an extended timestamp is cut short', at)
160
163
  entry.mtime = view(stamp).getInt32(1, true)
@@ -233,7 +236,10 @@ async function entryOf(source, entry, names) {
233
236
  if (crc32(body) !== entry.crc) throw new ArchiveError('the data does not match its CRC-32', at)
234
237
  const target = type === 'symlink' ? decodeUtf8(body, 'symlink target', at) : ''
235
238
  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 }
239
+ const out = {
240
+ ...named, type, mode: mode === 0 ? DEFAULT_MODE[type] : mode & 0o7777, mtime: entry.mtime, data: type === 'file' ? body : EMPTY, storedName: rawName,
241
+ system: entry.madeBy >> 8, version: entry.version, flags: entry.flags, internalAttributes: entry.internal, attributes: entry.attributes, extra: entry.extra,
242
+ }
237
243
  located(() => names.add(out), at)
238
244
  return out
239
245
  }
@@ -268,13 +274,15 @@ async function* entries(source, { limit = Infinity, symlinksAbove } = {}, keep =
268
274
  if (pos !== end) throw new ArchiveError('the central directory does not hold what the end record counts', pos)
269
275
  let expected = 0
270
276
  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.
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 = []
276
283
  const stops = []
277
284
  for (let i = sorted.length - 1; i >= 0; i--) {
285
+ boundaries[i] = sorted[i + 1]?.offset ?? start
278
286
  stops[i] = sorted[i].csize === 0 && i + 1 < sorted.length ? stops[i + 1] : boundaries[i] - sorted[i].csize
279
287
  }
280
288
  const locals = walk(source)
package/tar.d.ts CHANGED
@@ -36,15 +36,16 @@ export type EntryType =
36
36
  // `extended` is the extended headers read since the entry before it, in
37
37
  // the order stored, each its kind -- its own pax header, a global one,
38
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.
39
+ // none was, and frozen, as a Map is. An extended header with no entry after
40
+ // it is refused, a global one too unless `trailingGlobal` takes it. `magic`
41
+ // is the entry's own header's: POSIX's 'ustar', or 'gnu', under which the
42
+ // bytes ustar holds a name's prefix in are GNU's own and not read as one.
43
+ // `typeflag` and `storedMode` are its header's type flag and mode as
44
+ // stored: '\0' where `type` is a 'file' as '0' is, and the file type bits
45
+ // among the permission bits `mode` keeps. `octal` is whether every numeric
46
+ // field of its header -- an extended one's too -- holds octal digits, as
47
+ // POSIX writes them, rather than nothing or GNU's base 256, both of which
48
+ // are read too.
48
49
  export interface Entry {
49
50
  name: string
50
51
  type: EntryType
@@ -125,8 +126,13 @@ export interface PackOptions extends SymlinkOptions {
125
126
  // counted and a repeat again, its extended headers not: past it the call
126
127
  // throws with `limited` set, at the header that crosses it, before that
127
128
  // entry is read. No bound by default.
129
+ // `trailingGlobal` takes a global header with no entry after it, as GNU tar
130
+ // lists one: as nothing, carried in no entry's `extended`. By default it is
131
+ // refused, as any extended header with no entry to describe is. A pax or
132
+ // long name header with nothing after it is refused either way.
128
133
  export interface UnpackOptions extends SymlinkOptions {
129
134
  maxEntries?: number
135
+ trailingGlobal?: boolean
130
136
  }
131
137
 
132
138
  // Both refuse a name that repeats as a different entry -- anything but the
package/zip.d.ts CHANGED
@@ -18,6 +18,14 @@ export type EntryType = 'file' | 'directory' | 'symlink'
18
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
+ //
22
+ // Beside those, what the central directory stores of the entry, for a
23
+ // reader that follows another program's reading of it: `system` is the
24
+ // maker's, the upper byte of the version made by, 3 for Unix, whose
25
+ // attributes alone `mode` is read from; `version` the one needed to
26
+ // extract, `flags` the general purpose bits, `internalAttributes` and
27
+ // `attributes` the internal and external ones, each as stored; `extra` the
28
+ // extra fields, each its id and data, in the order stored.
21
29
  export interface Entry {
22
30
  name: string
23
31
  type: EntryType
@@ -26,6 +34,17 @@ export interface Entry {
26
34
  linkname: string
27
35
  data: Uint8Array
28
36
  storedName: string
37
+ system: number
38
+ version: number
39
+ flags: number
40
+ internalAttributes: number
41
+ attributes: number
42
+ extra: ExtraField[]
43
+ }
44
+
45
+ export interface ExtraField {
46
+ id: number
47
+ data: Uint8Array
29
48
  }
30
49
 
31
50
  // An entry to write. `name` is cleaned as above, so `./a`, `a/./b` and