-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbinary-content.test.ts
More file actions
351 lines (323 loc) · 10.1 KB
/
Copy pathbinary-content.test.ts
File metadata and controls
351 lines (323 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
extensionForMimeType,
formatByteSize,
isBinaryContentType,
looksLikeText,
persistBinaryContent,
sniffFileKind,
} from './binary-content.js';
describe('isBinaryContentType', () => {
it.each([
['text/html', false],
['text/plain; charset=utf-8', false],
['text/markdown', false],
['application/json', false],
['application/vnd.api+json', false],
['application/xml', false],
['image/svg+xml', false],
['application/javascript', false],
['application/x-www-form-urlencoded', false],
['application/yaml', false],
['application/x-yaml', false],
['application/x-ndjson', false],
['application/toml', false],
['application/json', false],
['', false],
['application/wasm', true],
['application/vnd.ms-powerpoint', true],
['application/x-tar', true],
['application/x-rar-compressed', true],
['application/vnd.rar', true],
['application/java-archive', true],
['font/woff2', true],
['application/pdf', true],
['application/zip', true],
['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', true],
['application/octet-stream', true],
['image/png', true],
['audio/mpeg', true],
['video/mp4', true],
['application/vnd.oasis.opendocument.text', true],
])('%s → %s', (contentType, expected) => {
expect(isBinaryContentType(contentType)).toBe(expected);
});
});
describe('looksLikeText', () => {
it('accepts printable UTF-8, rejects NUL bytes and invalid sequences', () => {
expect(looksLikeText(Buffer.from('plain text\nwith 中文 too\n'))).toBe(
true,
);
expect(looksLikeText(Buffer.from([0x68, 0x00, 0x69]))).toBe(false);
expect(looksLikeText(Buffer.alloc(64, 0x81))).toBe(false);
});
});
describe('extensionForMimeType', () => {
it.each([
['application/pdf', 'pdf'],
['application/pdf; charset=binary', 'pdf'],
[
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xlsx',
],
['image/jpeg', 'jpg'],
['application/vnd.ms-powerpoint', 'ppt'],
['application/x-gzip', 'gz'],
['application/x-tar', 'tar'],
['application/x-7z-compressed', '7z'],
['application/vnd.rar', 'rar'],
['application/wasm', 'wasm'],
['application/octet-stream', 'bin'],
['who/knows', 'bin'],
[undefined, 'bin'],
])('%s → %s', (mimeType, expected) => {
expect(extensionForMimeType(mimeType)).toBe(expected);
});
});
describe('persistBinaryContent', () => {
let dir: string;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'binary-content-test-'));
});
afterEach(() => {
fs.rmSync(dir, { recursive: true, force: true });
});
it('writes raw bytes with a mime-derived extension', async () => {
const bytes = Buffer.from([0x25, 0x50, 0x44, 0x46, 0x00, 0xff]);
const result = await persistBinaryContent(
bytes,
'pdf',
dir,
'webfetch-test-1',
);
expect(result).toEqual({
filepath: path.join(dir, 'webfetch-test-1.pdf'),
size: bytes.length,
ext: 'pdf',
});
expect(fs.readFileSync(path.join(dir, 'webfetch-test-1.pdf'))).toEqual(
bytes,
);
});
it.skipIf(process.platform === 'win32')(
'writes binary content mode 0600',
async () => {
await persistBinaryContent(
Buffer.from([0x25, 0x50, 0x44, 0x46, 0x00, 0xff]),
'pdf',
dir,
'webfetch-test-1',
);
expect(
fs.statSync(path.join(dir, 'webfetch-test-1.pdf')).mode & 0o777,
).toBe(0o600);
},
);
it('creates the target directory when missing', async () => {
const nested = path.join(dir, 'does', 'not', 'exist');
const result = await persistBinaryContent(
Buffer.from('x'),
'bin',
nested,
'id',
);
expect('filepath' in result && result.filepath).toBe(
path.join(nested, 'id.bin'),
);
});
it('returns an error instead of throwing on unwritable paths', async () => {
const filePath = path.join(dir, 'occupied');
fs.writeFileSync(filePath, 'a plain file, not a directory');
const result = await persistBinaryContent(
Buffer.from('x'),
'bin',
filePath, // dir path collides with an existing file
'id',
);
expect('error' in result).toBe(true);
});
});
describe('formatByteSize', () => {
it.each([
[0, '0 bytes'],
[512, '512 bytes'],
[1024, '1KB'],
[1536, '1.5KB'],
[10 * 1024 * 1024, '10MB'],
[3 * 1024 * 1024 * 1024, '3GB'],
])('%d → %s', (bytes, expected) => {
expect(formatByteSize(bytes)).toBe(expected);
});
});
describe('sniffFileKind', () => {
const PDF = Buffer.from('%PDF-1.4 junk');
const ZIP = Buffer.from([0x50, 0x4b, 0x03, 0x04, 0x00, 0x00]);
const GZ = Buffer.from([0x1f, 0x8b, 0x08]);
const TEXT = Buffer.from('plain old text');
const URL = 'https://example.com/files/download';
it('identifies PDFs by magic bytes regardless of content type', () => {
const kind = sniffFileKind(PDF, 'application/octet-stream', '', URL);
expect(kind).toEqual({
extension: 'pdf',
mimeType: 'application/pdf',
magicMatched: true,
extensionSource: 'magic',
});
});
it('refines ZIP magic to office extensions via Content-Disposition', () => {
const kind = sniffFileKind(
ZIP,
'application/octet-stream',
'attachment; filename="report.xlsx"',
URL,
);
expect(kind.extension).toBe('xlsx');
expect(kind.magicMatched).toBe(true);
});
it('refines ZIP magic to office extensions via URL path', () => {
const kind = sniffFileKind(
ZIP,
'application/octet-stream',
'',
'https://example.com/deck.pptx',
);
expect(kind.extension).toBe('pptx');
});
it('falls back to zip for unrefined ZIP containers', () => {
expect(sniffFileKind(ZIP, '', '', URL).extension).toBe('zip');
});
it('refines ZIP magic via the declared Content-Type when names are generic', () => {
const kind = sniffFileKind(
ZIP,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'',
URL, // generic /files/download — no useful extension
);
expect(kind.extension).toBe('xlsx');
});
it('reports how the extension was determined', () => {
expect(
sniffFileKind(TEXT, '', 'attachment; filename="fw.bin"', URL)
.extensionSource,
).toBe('name');
expect(
sniffFileKind(TEXT, 'application/pdf', '', URL).extensionSource,
).toBe('mime');
expect(sniffFileKind(TEXT, '', '', URL).extensionSource).toBe('fallback');
});
it('identifies gzip by magic bytes', () => {
expect(sniffFileKind(GZ, '', '', URL).extension).toBe('gz');
});
it.each([
// RAR4: Rar!\x1A\x07\x00
[Buffer.from([0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00, 0x33])],
// RAR5: Rar!\x1A\x07\x01\x00
[Buffer.from([0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x01, 0x00])],
])('identifies RAR archives by magic bytes', (bytes) => {
const kind = sniffFileKind(bytes, 'application/octet-stream', '', URL);
expect(kind).toEqual({
extension: 'rar',
mimeType: 'application/vnd.rar',
magicMatched: true,
extensionSource: 'magic',
});
});
it('refines ZIP magic to jar via filename or Content-Type', () => {
const byName = sniffFileKind(
ZIP,
'application/octet-stream',
'attachment; filename="library.jar"',
URL,
);
expect(byName.extension).toBe('jar');
expect(byName.magicMatched).toBe(true);
// Every real JAR carries ZIP magic, so the java-archive mime mapping
// must survive the ZIP refinement rather than degrade to .zip.
const byMime = sniffFileKind(ZIP, 'application/java-archive', '', URL);
expect(byMime.extension).toBe('jar');
});
it.each([
[
Buffer.concat([
Buffer.from([0x89]),
Buffer.from('PNG\r\n'),
Buffer.from([0x1a, 0x0a]),
]),
'png',
'image/png',
],
[Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00]), 'jpg', 'image/jpeg'],
[Buffer.from('GIF89a....'), 'gif', 'image/gif'],
[
Buffer.concat([
Buffer.from('RIFF'),
Buffer.from([0, 0, 0, 0]),
Buffer.from('WEBPVP8 '),
]),
'webp',
'image/webp',
],
])('identifies image magic bytes → %s', (bytes, ext, mime) => {
const kind = sniffFileKind(bytes as Buffer, '', '', URL);
expect(kind.extension).toBe(ext);
expect(kind.mimeType).toBe(mime);
expect(kind.magicMatched).toBe(true);
});
it('uses RFC 5987 filename* when present', () => {
const kind = sniffFileKind(
TEXT,
'application/octet-stream',
"attachment; filename*=UTF-8''r13031cp.pdf",
URL,
);
expect(kind.extension).toBe('pdf');
expect(kind.magicMatched).toBe(false);
// RFC 5987 allows a non-empty language tag between the quotes.
expect(
sniffFileKind(TEXT, '', "attachment; filename*=UTF-8'en'report.xlsx", URL)
.extension,
).toBe('xlsx');
});
it('recognizes archive extensions from headerless URLs', () => {
const kind = sniffFileKind(
TEXT,
'',
'',
'https://example.com/backup/archive.tar',
);
expect(kind.extension).toBe('tar');
expect(kind.extensionSource).toBe('name');
});
it('uses the URL extension when headers say nothing', () => {
const kind = sniffFileKind(
TEXT,
'application/octet-stream',
'',
'https://example.com/audio/track.mp3?sig=abc',
);
expect(kind.extension).toBe('mp3');
});
it('falls back to the content-type map, then bin', () => {
expect(sniffFileKind(TEXT, 'application/pdf', '', URL).extension).toBe(
'pdf',
);
expect(sniffFileKind(TEXT, 'who/knows', '', URL).extension).toBe('bin');
});
it('ignores unknown extensions in filenames', () => {
const kind = sniffFileKind(
TEXT,
'',
'attachment; filename="script.exe"',
URL,
);
expect(kind.extension).toBe('bin');
});
});