Skip to content

Commit 95ee8c7

Browse files
committed
check buffers and dates by their brand, and say when a buffer is detached
1 parent 6a8956b commit 95ee8c7

3 files changed

Lines changed: 54 additions & 8 deletions

File tree

‎src/metadata.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@ import { encode as utf8 } from './util/utf8.ts';
22
import { shown } from './util/options.ts';
33
import * as exif from './codecs/exif.ts';
44

5+
/** whether a value is a Date, also one of another realm (an iframe's or Jest's isn't an instance here) */
6+
function isDate(value: unknown): value is Date {
7+
if (typeof value !== 'object' || value === null) return false;
8+
try {
9+
// (getTime() checks it is a Date: the tag, which any object can claim, doesn't)
10+
Date.prototype.getTime.call(value);
11+
return true;
12+
} catch {
13+
return false;
14+
}
15+
}
16+
517
/**
618
* Metadata written by the encoders. Each format stores the fields it has a place for:
719
*
@@ -26,6 +38,7 @@ import * as exif from './codecs/exif.ts';
2638
* Empty fields (and `null` ones) are left out. Without metadata, the files only say which software made them (`software`), so the same
2739
* image always encodes to the same bytes
2840
*/
41+
2942
export interface Metadata {
3043
/** The image's title */
3144
title?: string;
@@ -86,8 +99,7 @@ export function resolveMetadata(metadata: Metadata = {}): ResolvedMetadata {
8699
const resolved: ResolvedMetadata = {};
87100
if (creationTime !== undefined && creationTime !== null) {
88101
// (other types than these were turned into a date anyway: true was 1970)
89-
// (a Date by its tag, not instanceof: one of another realm, an iframe's or Jest's, isn't an instance here)
90-
if (Object.prototype.toString.call(creationTime) !== '[object Date]' && typeof creationTime !== 'number' && typeof creationTime !== 'string') {
102+
if (!isDate(creationTime) && typeof creationTime !== 'number' && typeof creationTime !== 'string') {
91103
// eslint-disable-next-line no-restricted-syntax -- the one date in the options
92104
throw new TypeError(`creationTime must be a Date, a number or a string, not ${typeof creationTime === 'object' ? shown(creationTime) : typeof creationTime}`);
93105
}

‎src/util/mem.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,43 @@ import { shown } from './options.ts';
22
/** Data accepted wherever binary input is expected */
33
export type BinaryData = ArrayBuffer | ArrayBufferView;
44

5+
// eslint-disable-next-line @typescript-eslint/unbound-method -- called on the value, as a check
6+
const byteLengthOf = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength')!.get!;
7+
// eslint-disable-next-line @typescript-eslint/unbound-method -- called on the value, as a check
8+
const sharedByteLengthOf = typeof SharedArrayBuffer === 'undefined' ? null : Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength')!.get!;
9+
10+
/** Whether a value is a buffer (an ArrayBuffer or a SharedArrayBuffer), also one of another realm */
11+
function isBuffer(value: unknown): value is ArrayBuffer {
12+
// (by the byteLength getter's own check, not instanceof: a buffer of another realm, an iframe's or a vm context's,
13+
// isn't an instance here; nor by the tag, which any object can claim)
14+
if (typeof value !== 'object' || value === null) return false;
15+
for (const getter of [byteLengthOf, sharedByteLengthOf]) {
16+
try {
17+
getter?.call(value);
18+
if (getter) return true;
19+
} catch { /* another kind */ }
20+
}
21+
return false;
22+
}
23+
524
/** Whether a value is binary data (an ArrayBuffer, a SharedArrayBuffer or a view), also one of another realm */
625
export function isBinaryData(value: unknown): value is BinaryData {
7-
if (ArrayBuffer.isView(value)) return true;
8-
const tag = Object.prototype.toString.call(value);
9-
return tag === '[object ArrayBuffer]' || tag === '[object SharedArrayBuffer]';
26+
return ArrayBuffer.isView(value) || isBuffer(value);
1027
}
1128

1229
/**
1330
* Returns a Uint8Array view of the given buffer without copying
1431
*/
1532
export function view(buffer: BinaryData): Uint8Array {
33+
// (a buffer transferred away, to a worker for one, has no data: said so instead of the engine's construct error, or
34+
// the "unsupported type" of 0 bytes)
35+
const data = ArrayBuffer.isView(buffer) ? buffer.buffer : buffer;
36+
if (isBuffer(data) && (data as { detached?: boolean }).detached === true)
37+
throw new TypeError('Binary data has to be readable, not of a detached ArrayBuffer (one transferred, to a worker for one)');
1638
// subclasses like node's Buffer are unwrapped, their slice() doesn't copy
1739
if (buffer instanceof Uint8Array && buffer.constructor === Uint8Array) return buffer;
1840
if (ArrayBuffer.isView(buffer)) return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
19-
// (by its tag, not instanceof: a buffer of another realm, an iframe's or a vm context's, isn't an instance here)
20-
const tag = Object.prototype.toString.call(buffer);
21-
if (tag === '[object ArrayBuffer]' || tag === '[object SharedArrayBuffer]') return new Uint8Array(buffer);
41+
if (isBuffer(buffer)) return new Uint8Array(buffer);
2242

2343
throw new TypeError(`Binary data has to be an ArrayBuffer or a typed array like Uint8Array, not ${shown(buffer)}`);
2444
}

‎tests/other-realms.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,20 @@ const panic = message => {
1919
if (!(image instanceof Image) || image.getPixelAt(0, 0) !== 0xff0000ff) panic(`${name} of another realm: ${image}`);
2020
if (ImageType.getType(data) !== 'png') panic(`ImageType.getType(${name} of another realm)`);
2121
}
22+
// objects that only claim to be one by their tag are not
23+
for (const [name, fake] of [['ArrayBuffer', {[Symbol.toStringTag]: 'ArrayBuffer', byteLength: 8}], ['SharedArrayBuffer', {[Symbol.toStringTag]: 'SharedArrayBuffer', byteLength: 8}], ['proxied ArrayBuffer', new Proxy(new ArrayBuffer(8), {})]]) {
24+
const err = await Image.decode(fake).then(() => null, err => err);
25+
if (!(err instanceof TypeError) || !/^Binary data has to be/.test(err.message)) panic(`a fake ${name}: ${err}`);
26+
}
27+
const fakeDate = await new Image(1, 1).encodePNG({metadata: {creationTime: {[Symbol.toStringTag]: 'Date'}}}).then(() => null, err => err);
28+
if (!(fakeDate instanceof TypeError) || !/^creationTime must be a Date/.test(fakeDate.message)) panic(`a fake Date: ${fakeDate}`);
29+
// a detached buffer (transferred to a worker) is said to be one
30+
const detached = png.buffer.slice(0), detachedView = new Uint8Array(detached);
31+
structuredClone(detached, {transfer: [detached]});
32+
for (const data of [detached, detachedView]) {
33+
const err = await Image.decode(data).then(() => null, err => err);
34+
if (!(err instanceof TypeError) || !/detached/.test(err.message) || !/^Binary data/.test(err.message)) panic(`a detached buffer: ${err}`);
35+
}
2236
const date = vm.runInContext('new Date(Date.UTC(2020, 1, 1))', context);
2337
const file = await new Image(1, 1).encodePNG({metadata: {creationTime: date}}).catch(err => err);
2438
if (!(file instanceof Uint8Array) || !Buffer.from(file).toString('latin1').includes('2020')) panic(`a Date of another realm: ${file}`);

0 commit comments

Comments
 (0)