@axiumine/koa-utils 9.1.1 → 9.2.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/README.md +4 -3
- package/dist/files/GLB_POLICY_DEFAULTS.d.mts +49 -0
- package/dist/files/GLB_POLICY_DEFAULTS.mjs +45 -0
- package/dist/files/GLB_REJECT_CODES.d.mts +29 -0
- package/dist/files/GLB_REJECT_CODES.mjs +51 -0
- package/dist/files/IGlbContainer.d.mts +12 -0
- package/dist/files/IGlbContainer.mjs +2 -0
- package/dist/files/IGlbSanitiseResult.d.mts +56 -0
- package/dist/files/IGlbSanitiseResult.mjs +2 -0
- package/dist/files/checkGlbContainer.d.mts +11 -0
- package/dist/files/checkGlbContainer.mjs +68 -0
- package/dist/files/sanitiseGlb.d.mts +22 -0
- package/dist/files/sanitiseGlb.mjs +66 -0
- package/dist/files/sanitiseGlbFile.d.mts +16 -0
- package/dist/files/sanitiseGlbFile.mjs +36 -0
- package/dist/files/validateGlbExtension.d.mts +1 -0
- package/dist/files/validateGlbExtension.mjs +9 -0
- package/dist/files/validateMimeTypeGlb.d.mts +5 -0
- package/dist/files/validateMimeTypeGlb.mjs +9 -0
- package/dist/private/glb/IImageSize.d.mts +5 -0
- package/dist/private/glb/IImageSize.mjs +2 -0
- package/dist/private/glb/checkGlbCounts.d.mts +15 -0
- package/dist/private/glb/checkGlbCounts.mjs +53 -0
- package/dist/private/glb/checkGlbExtensions.d.mts +7 -0
- package/dist/private/glb/checkGlbExtensions.mjs +26 -0
- package/dist/private/glb/checkGlbGeometry.d.mts +9 -0
- package/dist/private/glb/checkGlbGeometry.mjs +56 -0
- package/dist/private/glb/checkGlbImages.d.mts +10 -0
- package/dist/private/glb/checkGlbImages.mjs +60 -0
- package/dist/private/glb/checkGlbUris.d.mts +7 -0
- package/dist/private/glb/checkGlbUris.mjs +25 -0
- package/dist/private/glb/glbExtensions.d.mts +7 -0
- package/dist/private/glb/glbExtensions.mjs +13 -0
- package/dist/private/glb/glbIo.d.mts +7 -0
- package/dist/private/glb/glbIo.mjs +16 -0
- package/dist/private/glb/glbReason.d.mts +7 -0
- package/dist/private/glb/glbReason.mjs +14 -0
- package/dist/private/glb/glbStats.d.mts +5 -0
- package/dist/private/glb/glbStats.mjs +24 -0
- package/dist/private/glb/inspectGlbJson.d.mts +8 -0
- package/dist/private/glb/inspectGlbJson.mjs +21 -0
- package/dist/private/glb/jsonAccess.d.mts +17 -0
- package/dist/private/glb/jsonAccess.mjs +24 -0
- package/dist/private/glb/parseGlbJson.d.mts +11 -0
- package/dist/private/glb/parseGlbJson.mjs +14 -0
- package/dist/private/glb/reEncodeImage.d.mts +13 -0
- package/dist/private/glb/reEncodeImage.mjs +24 -0
- package/dist/private/glb/readImageHeader.d.mts +25 -0
- package/dist/private/glb/readImageHeader.mjs +68 -0
- package/dist/private/glb/readJpegSize.d.mts +3 -0
- package/dist/private/glb/readJpegSize.mjs +27 -0
- package/dist/private/glb/readKtx2Size.d.mts +3 -0
- package/dist/private/glb/readKtx2Size.mjs +23 -0
- package/dist/private/glb/reencodeTextures.d.mts +9 -0
- package/dist/private/glb/reencodeTextures.mjs +34 -0
- package/dist/private/glb/resolveGlbPolicy.d.mts +6 -0
- package/dist/private/glb/resolveGlbPolicy.mjs +48 -0
- package/dist/private/glb/rewriteGlb.d.mts +16 -0
- package/dist/private/glb/rewriteGlb.mjs +49 -0
- package/dist/private/glb/stripExtras.d.mts +8 -0
- package/dist/private/glb/stripExtras.mjs +16 -0
- package/dist/private/glb/validateKhronos.d.mts +12 -0
- package/dist/private/glb/validateKhronos.mjs +32 -0
- package/dist/private/glb/verifyGlbOutput.d.mts +8 -0
- package/dist/private/glb/verifyGlbOutput.mjs +20 -0
- package/package.json +62 -1
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { GLB_FORBIDDEN_EXTENSIONS } from './glbExtensions.mjs';
|
|
2
|
+
import { childOf, field, listOf } from './jsonAccess.mjs';
|
|
3
|
+
/** Every extension name the file declares, in `extensionsUsed`, in `extensionsRequired` or as a key of the root `extensions`. Each name once. */
|
|
4
|
+
function declaredNames(json) {
|
|
5
|
+
const raw = [
|
|
6
|
+
...listOf(field(json, 'extensionsUsed')),
|
|
7
|
+
...listOf(field(json, 'extensionsRequired')),
|
|
8
|
+
...Object.keys(childOf(json, 'extensions'))
|
|
9
|
+
];
|
|
10
|
+
return [...new Set(raw.map(String))];
|
|
11
|
+
}
|
|
12
|
+
function reasonFor(name, allowed) {
|
|
13
|
+
if (GLB_FORBIDDEN_EXTENSIONS.includes(name)) {
|
|
14
|
+
return [{ code: 'EXTENSION_FORBIDDEN', message: `${name} is never allowed` }];
|
|
15
|
+
}
|
|
16
|
+
return allowed.has(name) ? [] : [{ code: 'EXTENSION_NOT_ALLOWED', message: `${name} is not in allowedExtensions` }];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Every declared extension must be in the allow list. `KHR_interactivity` has its own code. Undeclared use of an
|
|
20
|
+
* extension deeper in the JSON is an error of the Khronos validator (`UNDECLARED_EXTENSION`), which runs next.
|
|
21
|
+
*/
|
|
22
|
+
export function checkGlbExtensions(json, allowedExtensions) {
|
|
23
|
+
const allowed = new Set(allowedExtensions);
|
|
24
|
+
return declaredNames(json).flatMap((name) => reasonFor(name, allowed));
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=checkGlbExtensions.mjs.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { IGlbPolicy } from '../../files/GLB_POLICY_DEFAULTS.mjs';
|
|
2
|
+
import type { IGlbReason, IGlbStats } from '../../files/IGlbSanitiseResult.mjs';
|
|
3
|
+
import { type IJsonObject } from './jsonAccess.mjs';
|
|
4
|
+
/**
|
|
5
|
+
* Triangles and vertices of the scene, read from the accessor `count` fields and never from the data. A mesh is counted
|
|
6
|
+
* once for every node that instances it, because that is what the renderer draws, and 10 000 nodes on one big mesh is a
|
|
7
|
+
* bomb. Fills `stats.triangles` and `stats.vertices`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function checkGlbGeometry(json: IJsonObject, policy: IGlbPolicy, stats: IGlbStats): IGlbReason[];
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { limitReasons } from './glbReason.mjs';
|
|
2
|
+
import { childOf, countOf, field, isObject, itemOf, listOf } from './jsonAccess.mjs';
|
|
3
|
+
const MODE_TRIANGLES = 4;
|
|
4
|
+
const MODE_STRIP = 5;
|
|
5
|
+
const MODE_FAN = 6;
|
|
6
|
+
function trianglesOf(mode, elements) {
|
|
7
|
+
const value = typeof mode === 'number' ? mode : MODE_TRIANGLES;
|
|
8
|
+
if (value === MODE_TRIANGLES) {
|
|
9
|
+
return Math.floor(elements / 3);
|
|
10
|
+
}
|
|
11
|
+
return value === MODE_STRIP || value === MODE_FAN ? Math.max(0, elements - 2) : 0;
|
|
12
|
+
}
|
|
13
|
+
function primitiveCounts(primitive, accessors) {
|
|
14
|
+
const vertices = countOf(field(itemOf(accessors, field(childOf(primitive, 'attributes'), 'POSITION')), 'count'));
|
|
15
|
+
const indices = field(primitive, 'indices');
|
|
16
|
+
const elements = indices === undefined ? vertices : countOf(field(itemOf(accessors, indices), 'count'));
|
|
17
|
+
return { triangles: trianglesOf(field(primitive, 'mode'), elements), vertices };
|
|
18
|
+
}
|
|
19
|
+
function meshCounts(mesh, accessors) {
|
|
20
|
+
const counts = { triangles: 0, vertices: 0 };
|
|
21
|
+
for (const primitive of listOf(field(mesh, 'primitives')).filter(isObject)) {
|
|
22
|
+
const one = primitiveCounts(primitive, accessors);
|
|
23
|
+
counts.triangles += one.triangles;
|
|
24
|
+
counts.vertices += one.vertices;
|
|
25
|
+
}
|
|
26
|
+
return counts;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Triangles and vertices of the scene, read from the accessor `count` fields and never from the data. A mesh is counted
|
|
30
|
+
* once for every node that instances it, because that is what the renderer draws, and 10 000 nodes on one big mesh is a
|
|
31
|
+
* bomb. Fills `stats.triangles` and `stats.vertices`.
|
|
32
|
+
*/
|
|
33
|
+
export function checkGlbGeometry(json, policy, stats) {
|
|
34
|
+
const accessors = listOf(field(json, 'accessors'));
|
|
35
|
+
const meshes = listOf(field(json, 'meshes'));
|
|
36
|
+
const perMesh = new Map();
|
|
37
|
+
let triangles = 0;
|
|
38
|
+
let vertices = 0;
|
|
39
|
+
for (const node of listOf(field(json, 'nodes')).filter(isObject)) {
|
|
40
|
+
const mesh = field(node, 'mesh');
|
|
41
|
+
let counts = perMesh.get(mesh);
|
|
42
|
+
if (!counts) {
|
|
43
|
+
counts = meshCounts(itemOf(meshes, mesh), accessors);
|
|
44
|
+
perMesh.set(mesh, counts);
|
|
45
|
+
}
|
|
46
|
+
triangles += counts.triangles;
|
|
47
|
+
vertices += counts.vertices;
|
|
48
|
+
}
|
|
49
|
+
stats.triangles = triangles;
|
|
50
|
+
stats.vertices = vertices;
|
|
51
|
+
return [
|
|
52
|
+
...limitReasons('maxTriangles', 'the triangles', triangles, policy.maxTriangles),
|
|
53
|
+
...limitReasons('maxVertices', 'the vertices', vertices, policy.maxVertices)
|
|
54
|
+
];
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=checkGlbGeometry.mjs.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { IGlbPolicy } from '../../files/GLB_POLICY_DEFAULTS.mjs';
|
|
2
|
+
import type { IGlbReason, IGlbStats } from '../../files/IGlbSanitiseResult.mjs';
|
|
3
|
+
import { type IJsonObject } from './jsonAccess.mjs';
|
|
4
|
+
/**
|
|
5
|
+
* Read the size of every embedded image from its header, before anything decodes it, and check it against
|
|
6
|
+
* `maxTextureSide` and `maxTexturePixels`. A header can claim 100 000 by 100 000 pixels in a few dozen bytes: that is the
|
|
7
|
+
* texture bomb. The format comes from the magic number, not from the `mimeType` the file claims. Images that carry a `uri`
|
|
8
|
+
* are left to the URI check. Fills `stats.maxTextureSide`.
|
|
9
|
+
*/
|
|
10
|
+
export declare function checkGlbImages(json: IJsonObject, bin: Uint8Array | null, policy: IGlbPolicy, stats: IGlbStats): IGlbReason[];
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { limitReasons } from './glbReason.mjs';
|
|
2
|
+
import { countOf, field, itemOf, listOf } from './jsonAccess.mjs';
|
|
3
|
+
import { detectImageFormat, readImageSize } from './readImageHeader.mjs';
|
|
4
|
+
const problem = (code, index, message) => ({
|
|
5
|
+
size: null,
|
|
6
|
+
reasons: [{ code, pointer: `/images/${index}`, message: `images[${index}] ${message}` }]
|
|
7
|
+
});
|
|
8
|
+
/** The bytes of an image inside the BIN chunk, or `null` when the buffer view is missing, empty or outside the chunk. */
|
|
9
|
+
function imageBytes(image, views, bin) {
|
|
10
|
+
if (bin === null) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
const view = itemOf(views, field(image, 'bufferView'));
|
|
14
|
+
const start = countOf(field(view, 'byteOffset'));
|
|
15
|
+
const end = start + countOf(field(view, 'byteLength'));
|
|
16
|
+
return countOf(field(view, 'buffer')) === 0 && end > start && end <= bin.length ? bin.subarray(start, end) : null;
|
|
17
|
+
}
|
|
18
|
+
function inspectImage(image, index, views, bin) {
|
|
19
|
+
const bytes = imageBytes(image, views, bin);
|
|
20
|
+
if (bytes === null) {
|
|
21
|
+
return problem('IMAGE_UNREADABLE', index, 'has no bytes inside the BIN chunk');
|
|
22
|
+
}
|
|
23
|
+
const format = detectImageFormat(bytes);
|
|
24
|
+
if (format === null) {
|
|
25
|
+
return problem('IMAGE_UNSUPPORTED', index, 'is not PNG, JPEG, WebP or KTX2');
|
|
26
|
+
}
|
|
27
|
+
if (typeof field(image, 'mimeType') === 'string' && field(image, 'mimeType') !== format.mime) {
|
|
28
|
+
return problem('IMAGE_FORMAT_MISMATCH', index, `says ${String(field(image, 'mimeType'))} but the bytes are ${format.mime}`);
|
|
29
|
+
}
|
|
30
|
+
const size = readImageSize(format, bytes);
|
|
31
|
+
return size === null ? problem('IMAGE_UNREADABLE', index, 'has a header that cannot be read') : { size, reasons: [] };
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Read the size of every embedded image from its header, before anything decodes it, and check it against
|
|
35
|
+
* `maxTextureSide` and `maxTexturePixels`. A header can claim 100 000 by 100 000 pixels in a few dozen bytes: that is the
|
|
36
|
+
* texture bomb. The format comes from the magic number, not from the `mimeType` the file claims. Images that carry a `uri`
|
|
37
|
+
* are left to the URI check. Fills `stats.maxTextureSide`.
|
|
38
|
+
*/
|
|
39
|
+
export function checkGlbImages(json, bin, policy, stats) {
|
|
40
|
+
const views = listOf(field(json, 'bufferViews'));
|
|
41
|
+
const reasons = [];
|
|
42
|
+
let pixels = 0;
|
|
43
|
+
const images = listOf(field(json, 'images'));
|
|
44
|
+
images.forEach((_item, index) => {
|
|
45
|
+
const image = itemOf(images, index);
|
|
46
|
+
if (field(image, 'uri') !== undefined) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const { size, reasons: own } = inspectImage(image, index, views, bin);
|
|
50
|
+
reasons.push(...own);
|
|
51
|
+
if (size !== null) {
|
|
52
|
+
const side = Math.max(size.width, size.height);
|
|
53
|
+
stats.maxTextureSide = Math.max(stats.maxTextureSide, side);
|
|
54
|
+
pixels += size.width * size.height;
|
|
55
|
+
reasons.push(...limitReasons('maxTextureSide', `images[${index}]`, side, policy.maxTextureSide));
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
return [...reasons, ...limitReasons('maxTexturePixels', 'the images together', pixels, policy.maxTexturePixels)];
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=checkGlbImages.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { IGlbReason } from '../../files/IGlbSanitiseResult.mjs';
|
|
2
|
+
import { type IJsonObject } from './jsonAccess.mjs';
|
|
3
|
+
/**
|
|
4
|
+
* Every buffer and image must live inside the GLB: no `uri` at all. A `data:` URI gets its own code. Anything else (a
|
|
5
|
+
* relative path with `../`, an absolute path, `http:`, `file:`, even a non-string value) is `URI_EXTERNAL`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function checkGlbUris(json: IJsonObject): IGlbReason[];
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { field, isObject, listOf } from './jsonAccess.mjs';
|
|
2
|
+
const COLLECTIONS = ['buffers', 'images'];
|
|
3
|
+
function reasonFor(collection, index, uri) {
|
|
4
|
+
const pointer = `/${collection}/${index}/uri`;
|
|
5
|
+
if (typeof uri === 'string' && /^data:/i.test(uri)) {
|
|
6
|
+
return {
|
|
7
|
+
code: 'URI_DATA',
|
|
8
|
+
pointer,
|
|
9
|
+
message: `${collection}[${index}] carries a data: URI, only the embedded GLB buffer is allowed`
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
return {
|
|
13
|
+
code: 'URI_EXTERNAL',
|
|
14
|
+
pointer,
|
|
15
|
+
message: `${collection}[${index}] points at an external resource, only the embedded GLB buffer is allowed`
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Every buffer and image must live inside the GLB: no `uri` at all. A `data:` URI gets its own code. Anything else (a
|
|
20
|
+
* relative path with `../`, an absolute path, `http:`, `file:`, even a non-string value) is `URI_EXTERNAL`.
|
|
21
|
+
*/
|
|
22
|
+
export function checkGlbUris(json) {
|
|
23
|
+
return COLLECTIONS.flatMap((collection) => listOf(field(json, collection)).flatMap((item, index) => isObject(item) && field(item, 'uri') !== undefined ? [reasonFor(collection, index, field(item, 'uri'))] : []));
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=checkGlbUris.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Extensions that are refused whatever `allowedExtensions` says. */
|
|
2
|
+
export declare const GLB_FORBIDDEN_EXTENSIONS: readonly string[];
|
|
3
|
+
/**
|
|
4
|
+
* Extensions the sanitiser can read and write again: the defaults plus two that are safe but not on by default. A caller
|
|
5
|
+
* may put only a name from this list into `allowedExtensions`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const GLB_SUPPORTED_EXTENSIONS: readonly string[];
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { GLB_POLICY_DEFAULTS } from '../../files/GLB_POLICY_DEFAULTS.mjs';
|
|
2
|
+
/** Extensions that are refused whatever `allowedExtensions` says. */
|
|
3
|
+
export const GLB_FORBIDDEN_EXTENSIONS = ['KHR_interactivity'];
|
|
4
|
+
/**
|
|
5
|
+
* Extensions the sanitiser can read and write again: the defaults plus two that are safe but not on by default. A caller
|
|
6
|
+
* may put only a name from this list into `allowedExtensions`.
|
|
7
|
+
*/
|
|
8
|
+
export const GLB_SUPPORTED_EXTENSIONS = [
|
|
9
|
+
...GLB_POLICY_DEFAULTS.allowedExtensions,
|
|
10
|
+
'KHR_lights_punctual',
|
|
11
|
+
'KHR_materials_variants'
|
|
12
|
+
];
|
|
13
|
+
//# sourceMappingURL=glbExtensions.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { WebIO } from '@gltf-transform/core';
|
|
2
|
+
/**
|
|
3
|
+
* A glTF Transform reader and writer that knows exactly the allowed extensions and nothing else, plus the meshopt
|
|
4
|
+
* decoder and encoder. `WebIO` is used, not `NodeIO`: it has no file access, and the sanitiser never lets a GLB point
|
|
5
|
+
* at a file anyway. The logger is silent so a hostile file cannot flood the process log.
|
|
6
|
+
*/
|
|
7
|
+
export declare function createGlbIo(allowedExtensions: readonly string[]): Promise<WebIO>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Logger, WebIO } from '@gltf-transform/core';
|
|
2
|
+
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
|
|
3
|
+
import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
|
|
4
|
+
/**
|
|
5
|
+
* A glTF Transform reader and writer that knows exactly the allowed extensions and nothing else, plus the meshopt
|
|
6
|
+
* decoder and encoder. `WebIO` is used, not `NodeIO`: it has no file access, and the sanitiser never lets a GLB point
|
|
7
|
+
* at a file anyway. The logger is silent so a hostile file cannot flood the process log.
|
|
8
|
+
*/
|
|
9
|
+
export async function createGlbIo(allowedExtensions) {
|
|
10
|
+
await Promise.all([MeshoptDecoder.ready, MeshoptEncoder.ready]);
|
|
11
|
+
return new WebIO()
|
|
12
|
+
.setLogger(new Logger(Logger.Verbosity.SILENT))
|
|
13
|
+
.registerExtensions(ALL_EXTENSIONS.filter((extension) => allowedExtensions.includes(extension.EXTENSION_NAME)))
|
|
14
|
+
.registerDependencies({ 'meshopt.decoder': MeshoptDecoder, 'meshopt.encoder': MeshoptEncoder });
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=glbIo.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { IGlbLimitName, IGlbReason } from '../../files/IGlbSanitiseResult.mjs';
|
|
2
|
+
/** One `LIMIT_EXCEEDED` reason when `value` is over `max`, otherwise no reason. A value equal to `max` passes. */
|
|
3
|
+
export declare function limitReasons(limit: IGlbLimitName, label: string, value: number, max: number): IGlbReason[];
|
|
4
|
+
/** The most reasons one result carries. A hostile file can trigger thousands of validator errors. */
|
|
5
|
+
export declare const MAX_REASONS = 20;
|
|
6
|
+
/** The `GLB_TOO_LARGE` reason, shared by the container check and by the file reader that refuses before it reads. */
|
|
7
|
+
export declare const tooLargeReason: (size: number, max: number) => IGlbReason;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** One `LIMIT_EXCEEDED` reason when `value` is over `max`, otherwise no reason. A value equal to `max` passes. */
|
|
2
|
+
export function limitReasons(limit, label, value, max) {
|
|
3
|
+
return value > max
|
|
4
|
+
? [{ code: 'LIMIT_EXCEEDED', limit, message: `${label}: ${value} is over the limit ${limit} = ${max}` }]
|
|
5
|
+
: [];
|
|
6
|
+
}
|
|
7
|
+
/** The most reasons one result carries. A hostile file can trigger thousands of validator errors. */
|
|
8
|
+
export const MAX_REASONS = 20;
|
|
9
|
+
/** The `GLB_TOO_LARGE` reason, shared by the container check and by the file reader that refuses before it reads. */
|
|
10
|
+
export const tooLargeReason = (size, max) => ({
|
|
11
|
+
code: 'GLB_TOO_LARGE',
|
|
12
|
+
message: `the file has ${size} bytes, the limit is ${max}`
|
|
13
|
+
});
|
|
14
|
+
//# sourceMappingURL=glbReason.mjs.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { IGlbReason, IGlbRejected, IGlbStats } from '../../files/IGlbSanitiseResult.mjs';
|
|
2
|
+
/** A stats object for a file of `inputBytes`, everything else `0` until a stage measures it. */
|
|
3
|
+
export declare const emptyStats: (inputBytes: number) => IGlbStats;
|
|
4
|
+
/** The rejected result: at most `MAX_REASONS` reasons, so a hostile file cannot make the result as big as itself. */
|
|
5
|
+
export declare const rejected: (reasons: IGlbReason[], stats: IGlbStats) => IGlbRejected;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { MAX_REASONS } from './glbReason.mjs';
|
|
2
|
+
/** A stats object for a file of `inputBytes`, everything else `0` until a stage measures it. */
|
|
3
|
+
export const emptyStats = (inputBytes) => ({
|
|
4
|
+
inputBytes,
|
|
5
|
+
outputBytes: 0,
|
|
6
|
+
nodes: 0,
|
|
7
|
+
meshes: 0,
|
|
8
|
+
materials: 0,
|
|
9
|
+
textures: 0,
|
|
10
|
+
animations: 0,
|
|
11
|
+
accessors: 0,
|
|
12
|
+
triangles: 0,
|
|
13
|
+
vertices: 0,
|
|
14
|
+
bufferBytes: 0,
|
|
15
|
+
maxTextureSide: 0,
|
|
16
|
+
texturesReencoded: 0
|
|
17
|
+
});
|
|
18
|
+
/** The rejected result: at most `MAX_REASONS` reasons, so a hostile file cannot make the result as big as itself. */
|
|
19
|
+
export const rejected = (reasons, stats) => ({
|
|
20
|
+
accepted: false,
|
|
21
|
+
reasons: reasons.slice(0, MAX_REASONS),
|
|
22
|
+
stats
|
|
23
|
+
});
|
|
24
|
+
//# sourceMappingURL=glbStats.mjs.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { IGlbPolicy } from '../../files/GLB_POLICY_DEFAULTS.mjs';
|
|
2
|
+
import type { IGlbReason, IGlbStats } from '../../files/IGlbSanitiseResult.mjs';
|
|
3
|
+
import type { IJsonObject } from './jsonAccess.mjs';
|
|
4
|
+
/**
|
|
5
|
+
* Every policy check that needs only the parsed JSON and the BIN chunk, run together so the caller sees all the
|
|
6
|
+
* reasons at once. None of them allocates in proportion to a number the file declares. Fills the counts in `stats`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function inspectGlbJson(json: IJsonObject, bin: Uint8Array | null, policy: IGlbPolicy, stats: IGlbStats): IGlbReason[];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { checkGlbAccessors, checkGlbBuffers, checkGlbCounts } from './checkGlbCounts.mjs';
|
|
2
|
+
import { checkGlbExtensions } from './checkGlbExtensions.mjs';
|
|
3
|
+
import { checkGlbGeometry } from './checkGlbGeometry.mjs';
|
|
4
|
+
import { checkGlbImages } from './checkGlbImages.mjs';
|
|
5
|
+
import { checkGlbUris } from './checkGlbUris.mjs';
|
|
6
|
+
/**
|
|
7
|
+
* Every policy check that needs only the parsed JSON and the BIN chunk, run together so the caller sees all the
|
|
8
|
+
* reasons at once. None of them allocates in proportion to a number the file declares. Fills the counts in `stats`.
|
|
9
|
+
*/
|
|
10
|
+
export function inspectGlbJson(json, bin, policy, stats) {
|
|
11
|
+
return [
|
|
12
|
+
...checkGlbUris(json),
|
|
13
|
+
...checkGlbExtensions(json, policy.allowedExtensions),
|
|
14
|
+
...checkGlbCounts(json, policy, stats),
|
|
15
|
+
...checkGlbAccessors(json, policy),
|
|
16
|
+
...checkGlbBuffers(json, policy, stats),
|
|
17
|
+
...checkGlbGeometry(json, policy, stats),
|
|
18
|
+
...checkGlbImages(json, bin, policy, stats)
|
|
19
|
+
];
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=inspectGlbJson.mjs.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** A parsed glTF JSON object whose shape nobody has checked yet. */
|
|
2
|
+
export type IJsonObject = Record<string, unknown>;
|
|
3
|
+
/** True for a plain JSON object: not `null`, not an array. */
|
|
4
|
+
export declare const isObject: (value: unknown) => value is IJsonObject;
|
|
5
|
+
/** The elements of a JSON array, or an empty list for anything else. */
|
|
6
|
+
export declare const listOf: (value: unknown) => unknown[];
|
|
7
|
+
/** A non-negative integer, or `0` for anything else. Hostile JSON can put any value in any field. */
|
|
8
|
+
export declare const countOf: (value: unknown) => number;
|
|
9
|
+
/**
|
|
10
|
+
* `object[key]` for an own property only, so a key such as `constructor` or `__proto__` reads nothing from the prototype.
|
|
11
|
+
* Every key passed here is a literal of this package, never a name from the file.
|
|
12
|
+
*/
|
|
13
|
+
export declare const field: (object: IJsonObject, key: string) => unknown;
|
|
14
|
+
/** The object at `list[index]`, or an empty object when the index is not a valid position or the element is not an object. */
|
|
15
|
+
export declare const itemOf: (list: unknown[], index: unknown) => IJsonObject;
|
|
16
|
+
/** `object[key]` as an object, or an empty object. */
|
|
17
|
+
export declare const childOf: (object: IJsonObject, key: string) => IJsonObject;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** True for a plain JSON object: not `null`, not an array. */
|
|
2
|
+
export const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
3
|
+
/** The elements of a JSON array, or an empty list for anything else. */
|
|
4
|
+
export const listOf = (value) => (Array.isArray(value) ? value : []);
|
|
5
|
+
/** A non-negative integer, or `0` for anything else. Hostile JSON can put any value in any field. */
|
|
6
|
+
export const countOf = (value) => typeof value === 'number' && Number.isSafeInteger(value) ? Math.max(0, value) : 0;
|
|
7
|
+
/**
|
|
8
|
+
* `object[key]` for an own property only, so a key such as `constructor` or `__proto__` reads nothing from the prototype.
|
|
9
|
+
* Every key passed here is a literal of this package, never a name from the file.
|
|
10
|
+
*/
|
|
11
|
+
export const field = (object, key) =>
|
|
12
|
+
// eslint-disable-next-line security/detect-object-injection -- `key` is a literal of this package and the read is limited to own properties
|
|
13
|
+
Object.hasOwn(object, key) ? object[key] : undefined;
|
|
14
|
+
/** The object at `list[index]`, or an empty object when the index is not a valid position or the element is not an object. */
|
|
15
|
+
export const itemOf = (list, index) => {
|
|
16
|
+
const item = typeof index === 'number' && index >= 0 ? list.at(index) : undefined;
|
|
17
|
+
return isObject(item) ? item : {};
|
|
18
|
+
};
|
|
19
|
+
/** `object[key]` as an object, or an empty object. */
|
|
20
|
+
export const childOf = (object, key) => {
|
|
21
|
+
const child = field(object, key);
|
|
22
|
+
return isObject(child) ? child : {};
|
|
23
|
+
};
|
|
24
|
+
//# sourceMappingURL=jsonAccess.mjs.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { IGlbReason } from '../../files/IGlbSanitiseResult.mjs';
|
|
2
|
+
import { type IJsonObject } from './jsonAccess.mjs';
|
|
3
|
+
export type IGlbJsonResult = {
|
|
4
|
+
json: IJsonObject;
|
|
5
|
+
reasons: [];
|
|
6
|
+
} | {
|
|
7
|
+
json: null;
|
|
8
|
+
reasons: IGlbReason[];
|
|
9
|
+
};
|
|
10
|
+
/** Decode the JSON chunk as strict UTF-8 and parse it. The result must be one JSON object. */
|
|
11
|
+
export declare function parseGlbJson(chunk: Uint8Array): IGlbJsonResult;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { isObject } from './jsonAccess.mjs';
|
|
2
|
+
const invalid = (message) => ({ json: null, reasons: [{ code: 'JSON_INVALID', message }] });
|
|
3
|
+
/** Decode the JSON chunk as strict UTF-8 and parse it. The result must be one JSON object. */
|
|
4
|
+
export function parseGlbJson(chunk) {
|
|
5
|
+
let parsed;
|
|
6
|
+
try {
|
|
7
|
+
parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(chunk));
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return invalid('the JSON chunk is not valid UTF-8 JSON');
|
|
11
|
+
}
|
|
12
|
+
return isObject(parsed) ? { json: parsed, reasons: [] } : invalid('the JSON chunk does not hold one JSON object');
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=parseGlbJson.mjs.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { IReencodableFormat } from './readImageHeader.mjs';
|
|
2
|
+
/**
|
|
3
|
+
* Decode an image with `sharp` and encode it again in the same format. The new file is built from the decoded pixels, so
|
|
4
|
+
* whatever hid in the container (trailing bytes, extra chunks, polyglot payloads) is gone, and `sharp` drops every
|
|
5
|
+
* metadata block (EXIF, XMP, ICC) because nothing asks it to keep one.
|
|
6
|
+
*
|
|
7
|
+
* `reEncode` in `reEncode.mts` is not reused on purpose: it reads and writes files and keeps XMP and ICC (limit L13 in
|
|
8
|
+
* `docs/security.md`), while a GLB texture is a buffer in memory that must come out clean.
|
|
9
|
+
*
|
|
10
|
+
* `limitInputPixels` makes `sharp` refuse an image bigger than `maxSide` squared before it allocates the pixels, a
|
|
11
|
+
* second line behind the header check. `failOn: 'warning'` refuses a truncated or damaged file instead of repairing it.
|
|
12
|
+
*/
|
|
13
|
+
export declare function reEncodeImage(bytes: Uint8Array, format: IReencodableFormat, quality: number, maxSide: number): Promise<Uint8Array>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import sharp from 'sharp';
|
|
2
|
+
/**
|
|
3
|
+
* Decode an image with `sharp` and encode it again in the same format. The new file is built from the decoded pixels, so
|
|
4
|
+
* whatever hid in the container (trailing bytes, extra chunks, polyglot payloads) is gone, and `sharp` drops every
|
|
5
|
+
* metadata block (EXIF, XMP, ICC) because nothing asks it to keep one.
|
|
6
|
+
*
|
|
7
|
+
* `reEncode` in `reEncode.mts` is not reused on purpose: it reads and writes files and keeps XMP and ICC (limit L13 in
|
|
8
|
+
* `docs/security.md`), while a GLB texture is a buffer in memory that must come out clean.
|
|
9
|
+
*
|
|
10
|
+
* `limitInputPixels` makes `sharp` refuse an image bigger than `maxSide` squared before it allocates the pixels, a
|
|
11
|
+
* second line behind the header check. `failOn: 'warning'` refuses a truncated or damaged file instead of repairing it.
|
|
12
|
+
*/
|
|
13
|
+
export async function reEncodeImage(bytes, format, quality, maxSide) {
|
|
14
|
+
const image = sharp(bytes, { limitInputPixels: maxSide * maxSide, failOn: 'warning' });
|
|
15
|
+
// PNG needs no call: `sharp` writes the format it read, and PNG is lossless.
|
|
16
|
+
if (format.name === 'jpeg') {
|
|
17
|
+
image.jpeg({ quality, progressive: true });
|
|
18
|
+
}
|
|
19
|
+
else if (format.name === 'webp') {
|
|
20
|
+
image.webp({ quality });
|
|
21
|
+
}
|
|
22
|
+
return new Uint8Array(await image.toBuffer());
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=reEncodeImage.mjs.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { IImageSize } from './IImageSize.mjs';
|
|
2
|
+
interface IImageFormatBase {
|
|
3
|
+
/** The MIME type glTF uses for the format. */
|
|
4
|
+
mime: string;
|
|
5
|
+
/** True when the bytes start like this format. */
|
|
6
|
+
matches: (bytes: Uint8Array) => boolean;
|
|
7
|
+
/** Width and height from the header. Throws when the header is cut short. */
|
|
8
|
+
read: (view: DataView) => IImageSize | null;
|
|
9
|
+
}
|
|
10
|
+
/** PNG, JPEG and WebP: `sharp` can decode and re-encode them. */
|
|
11
|
+
export type IReencodableFormat = IImageFormatBase & {
|
|
12
|
+
name: 'png' | 'jpeg' | 'webp';
|
|
13
|
+
};
|
|
14
|
+
/** KTX2 (`KHR_texture_basisu`): GPU-compressed, only its header and level index can be checked. */
|
|
15
|
+
export type IImageFormat = IReencodableFormat | (IImageFormatBase & {
|
|
16
|
+
name: 'ktx2';
|
|
17
|
+
});
|
|
18
|
+
/** The format of the bytes, by magic number. The `mimeType` the file claims is not used. */
|
|
19
|
+
export declare function detectImageFormat(bytes: Uint8Array): IImageFormat | null;
|
|
20
|
+
/**
|
|
21
|
+
* Width and height from the header only, nothing is decoded. `null` when the header is cut short, malformed, or
|
|
22
|
+
* reports a side of `0`. Nothing here throws on hostile bytes: reads past the end become `null`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function readImageSize(format: IImageFormat, bytes: Uint8Array): IImageSize | null;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { readJpeg } from './readJpegSize.mjs';
|
|
2
|
+
import { readKtx2 } from './readKtx2Size.mjs';
|
|
3
|
+
const KTX2_IDENTIFIER = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
|
|
4
|
+
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
|
5
|
+
const RIFF = [0x52, 0x49, 0x46, 0x46];
|
|
6
|
+
const WEBP = [0x57, 0x45, 0x42, 0x50];
|
|
7
|
+
const JPEG_START = [0xff, 0xd8, 0xff];
|
|
8
|
+
const startsWith = (bytes, prefix, at = 0) => prefix.every((byte, index) => bytes[at + index] === byte);
|
|
9
|
+
const MAX_SIDE = 0x7f_ff_ff_ff;
|
|
10
|
+
function readPng(view) {
|
|
11
|
+
// the first chunk must be IHDR, 13 bytes: this also turns away the "fried" iPhone variant that starts with CgBI
|
|
12
|
+
if (view.getUint32(8) !== 13 || view.getUint32(12) !== 0x49_48_44_52) {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
return { width: view.getUint32(16), height: view.getUint32(20) };
|
|
16
|
+
}
|
|
17
|
+
function readWebp(view) {
|
|
18
|
+
const chunk = view.getUint32(12);
|
|
19
|
+
if (chunk === 0x56_50_38_20) {
|
|
20
|
+
// 'VP8 ': lossy, 14 bit sizes behind the 3 byte start code
|
|
21
|
+
return view.getUint32(23) >>> 8 === 0x9d_01_2a
|
|
22
|
+
? { width: view.getUint16(26, true) & 0x3f_ff, height: view.getUint16(28, true) & 0x3f_ff }
|
|
23
|
+
: null;
|
|
24
|
+
}
|
|
25
|
+
if (chunk === 0x56_50_38_4c) {
|
|
26
|
+
// 'VP8L': lossless, two 14 bit sizes minus one in one 28 bit field
|
|
27
|
+
const bits = view.getUint32(21, true);
|
|
28
|
+
return view.getUint8(20) === 0x2f ? { width: (bits & 0x3f_ff) + 1, height: ((bits >>> 14) & 0x3f_ff) + 1 } : null;
|
|
29
|
+
}
|
|
30
|
+
if (chunk === 0x56_50_38_58) {
|
|
31
|
+
// 'VP8X': extended, two 24 bit sizes minus one
|
|
32
|
+
return {
|
|
33
|
+
width: (view.getUint16(24, true) | (view.getUint8(26) << 16)) + 1,
|
|
34
|
+
height: (view.getUint16(27, true) | (view.getUint8(29) << 16)) + 1
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
const FORMATS = [
|
|
40
|
+
{ name: 'png', mime: 'image/png', matches: (bytes) => startsWith(bytes, PNG_SIGNATURE), read: readPng },
|
|
41
|
+
{ name: 'jpeg', mime: 'image/jpeg', matches: (bytes) => startsWith(bytes, JPEG_START), read: readJpeg },
|
|
42
|
+
{
|
|
43
|
+
name: 'webp',
|
|
44
|
+
mime: 'image/webp',
|
|
45
|
+
matches: (bytes) => startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8),
|
|
46
|
+
read: readWebp
|
|
47
|
+
},
|
|
48
|
+
{ name: 'ktx2', mime: 'image/ktx2', matches: (bytes) => startsWith(bytes, KTX2_IDENTIFIER), read: readKtx2 }
|
|
49
|
+
];
|
|
50
|
+
/** The format of the bytes, by magic number. The `mimeType` the file claims is not used. */
|
|
51
|
+
export function detectImageFormat(bytes) {
|
|
52
|
+
return FORMATS.find((format) => format.matches(bytes)) ?? null;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Width and height from the header only, nothing is decoded. `null` when the header is cut short, malformed, or
|
|
56
|
+
* reports a side of `0`. Nothing here throws on hostile bytes: reads past the end become `null`.
|
|
57
|
+
*/
|
|
58
|
+
export function readImageSize(format, bytes) {
|
|
59
|
+
let size;
|
|
60
|
+
try {
|
|
61
|
+
size = format.read(new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
return size !== null && size.width > 0 && size.height > 0 && size.width <= MAX_SIDE && size.height <= MAX_SIDE ? size : null;
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=readImageHeader.mjs.map
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const isStartOfFrame = (marker) => marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
|
|
2
|
+
const hasNoLength = (marker) => marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8);
|
|
3
|
+
/** Width and height from the first start-of-frame segment. Throws when the file is cut short. */
|
|
4
|
+
export function readJpeg(view) {
|
|
5
|
+
let offset = 2;
|
|
6
|
+
while (offset < view.byteLength) {
|
|
7
|
+
const marker = view.getUint8(offset + 1);
|
|
8
|
+
if (view.getUint8(offset) !== 0xff || marker === 0xd9) {
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
if (marker === 0xff) {
|
|
12
|
+
offset += 1;
|
|
13
|
+
}
|
|
14
|
+
else if (hasNoLength(marker)) {
|
|
15
|
+
offset += 2;
|
|
16
|
+
}
|
|
17
|
+
else if (isStartOfFrame(marker)) {
|
|
18
|
+
return { width: view.getUint16(offset + 7), height: view.getUint16(offset + 5) };
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
// a length under 2 lands inside the length field itself, which is never 0xff, so the next pass ends the walk
|
|
22
|
+
offset += 2 + view.getUint16(offset + 2);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=readJpegSize.mjs.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const KTX2_LEVEL_INDEX = 80;
|
|
2
|
+
const KTX2_LEVEL_BYTES = 24;
|
|
3
|
+
const KTX2_MAX_LEVELS = 32;
|
|
4
|
+
/** Every level of the index (64 bit byte offset, then 64 bit byte length) must end inside the file. */
|
|
5
|
+
function ktx2LevelsFit(view, levels) {
|
|
6
|
+
const size = BigInt(view.byteLength);
|
|
7
|
+
for (let level = 0; level < levels; level++) {
|
|
8
|
+
const at = KTX2_LEVEL_INDEX + level * KTX2_LEVEL_BYTES;
|
|
9
|
+
if (view.getBigUint64(at, true) + view.getBigUint64(at + 8, true) > size) {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
/** Width and height from the KTX2 header, once the level index checks out. Throws when the header is cut short. */
|
|
16
|
+
export function readKtx2(view) {
|
|
17
|
+
const levels = view.getUint32(40, true);
|
|
18
|
+
if (levels < 1 || levels > KTX2_MAX_LEVELS || !ktx2LevelsFit(view, levels)) {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
return { width: view.getUint32(20, true), height: view.getUint32(24, true) };
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=readKtx2Size.mjs.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Document } from '@gltf-transform/core';
|
|
2
|
+
import type { IGlbPolicy } from '../../files/GLB_POLICY_DEFAULTS.mjs';
|
|
3
|
+
import type { IGlbReason, IGlbStats } from '../../files/IGlbSanitiseResult.mjs';
|
|
4
|
+
/**
|
|
5
|
+
* Decode and re-encode every PNG, JPEG and WebP texture with `sharp`, and put the new bytes in the document. A texture
|
|
6
|
+
* that does not decode is a reason, never a throw. KTX2 textures (`KHR_texture_basisu`) cannot be decoded here: their
|
|
7
|
+
* header and level index were checked before, and the bytes go through untouched. Counts into `stats.texturesReencoded`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function reencodeTextures(document: Document, policy: IGlbPolicy, stats: IGlbStats): Promise<IGlbReason[]>;
|