@axiumine/koa-utils 9.1.0 → 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.
Files changed (66) hide show
  1. package/README.md +10 -10
  2. package/dist/files/GLB_POLICY_DEFAULTS.d.mts +49 -0
  3. package/dist/files/GLB_POLICY_DEFAULTS.mjs +45 -0
  4. package/dist/files/GLB_REJECT_CODES.d.mts +29 -0
  5. package/dist/files/GLB_REJECT_CODES.mjs +51 -0
  6. package/dist/files/IGlbContainer.d.mts +12 -0
  7. package/dist/files/IGlbContainer.mjs +2 -0
  8. package/dist/files/IGlbSanitiseResult.d.mts +56 -0
  9. package/dist/files/IGlbSanitiseResult.mjs +2 -0
  10. package/dist/files/checkGlbContainer.d.mts +11 -0
  11. package/dist/files/checkGlbContainer.mjs +68 -0
  12. package/dist/files/sanitiseGlb.d.mts +22 -0
  13. package/dist/files/sanitiseGlb.mjs +66 -0
  14. package/dist/files/sanitiseGlbFile.d.mts +16 -0
  15. package/dist/files/sanitiseGlbFile.mjs +36 -0
  16. package/dist/files/validateGlbExtension.d.mts +1 -0
  17. package/dist/files/validateGlbExtension.mjs +9 -0
  18. package/dist/files/validateMimeTypeGlb.d.mts +5 -0
  19. package/dist/files/validateMimeTypeGlb.mjs +9 -0
  20. package/dist/private/glb/IImageSize.d.mts +5 -0
  21. package/dist/private/glb/IImageSize.mjs +2 -0
  22. package/dist/private/glb/checkGlbCounts.d.mts +15 -0
  23. package/dist/private/glb/checkGlbCounts.mjs +53 -0
  24. package/dist/private/glb/checkGlbExtensions.d.mts +7 -0
  25. package/dist/private/glb/checkGlbExtensions.mjs +26 -0
  26. package/dist/private/glb/checkGlbGeometry.d.mts +9 -0
  27. package/dist/private/glb/checkGlbGeometry.mjs +56 -0
  28. package/dist/private/glb/checkGlbImages.d.mts +10 -0
  29. package/dist/private/glb/checkGlbImages.mjs +60 -0
  30. package/dist/private/glb/checkGlbUris.d.mts +7 -0
  31. package/dist/private/glb/checkGlbUris.mjs +25 -0
  32. package/dist/private/glb/glbExtensions.d.mts +7 -0
  33. package/dist/private/glb/glbExtensions.mjs +13 -0
  34. package/dist/private/glb/glbIo.d.mts +7 -0
  35. package/dist/private/glb/glbIo.mjs +16 -0
  36. package/dist/private/glb/glbReason.d.mts +7 -0
  37. package/dist/private/glb/glbReason.mjs +14 -0
  38. package/dist/private/glb/glbStats.d.mts +5 -0
  39. package/dist/private/glb/glbStats.mjs +24 -0
  40. package/dist/private/glb/inspectGlbJson.d.mts +8 -0
  41. package/dist/private/glb/inspectGlbJson.mjs +21 -0
  42. package/dist/private/glb/jsonAccess.d.mts +17 -0
  43. package/dist/private/glb/jsonAccess.mjs +24 -0
  44. package/dist/private/glb/parseGlbJson.d.mts +11 -0
  45. package/dist/private/glb/parseGlbJson.mjs +14 -0
  46. package/dist/private/glb/reEncodeImage.d.mts +13 -0
  47. package/dist/private/glb/reEncodeImage.mjs +24 -0
  48. package/dist/private/glb/readImageHeader.d.mts +25 -0
  49. package/dist/private/glb/readImageHeader.mjs +68 -0
  50. package/dist/private/glb/readJpegSize.d.mts +3 -0
  51. package/dist/private/glb/readJpegSize.mjs +27 -0
  52. package/dist/private/glb/readKtx2Size.d.mts +3 -0
  53. package/dist/private/glb/readKtx2Size.mjs +23 -0
  54. package/dist/private/glb/reencodeTextures.d.mts +9 -0
  55. package/dist/private/glb/reencodeTextures.mjs +34 -0
  56. package/dist/private/glb/resolveGlbPolicy.d.mts +6 -0
  57. package/dist/private/glb/resolveGlbPolicy.mjs +48 -0
  58. package/dist/private/glb/rewriteGlb.d.mts +16 -0
  59. package/dist/private/glb/rewriteGlb.mjs +49 -0
  60. package/dist/private/glb/stripExtras.d.mts +8 -0
  61. package/dist/private/glb/stripExtras.mjs +16 -0
  62. package/dist/private/glb/validateKhronos.d.mts +12 -0
  63. package/dist/private/glb/validateKhronos.mjs +32 -0
  64. package/dist/private/glb/verifyGlbOutput.d.mts +8 -0
  65. package/dist/private/glb/verifyGlbOutput.mjs +20 -0
  66. package/package.json +77 -20
package/README.md CHANGED
@@ -35,9 +35,10 @@ yarn add @node-rs/bcrypt graphql mongoose redis
35
35
  | `mongoose` | `dataSources/MongoDB`, the models (`graphQL/models/MongoDB/*`), the mutations other than `logout` and `refresh`, `lib/db/*`, `lib/OBJECTID_0_OBJ`, `lib/access/create*Flow`, `koa/router/verifyEmail`, `koa/middleware/authenticatedAuthorizationHandler`, `koa/middleware/authenticatedResourceHandler` (its types are also named by a few `.d.mts` files) |
36
36
  | `redis` | `dataSources/Redis`, the `login*` / `logout` / `refresh` mutations, `koa/middleware/authenticatedAuthorizationHandler`, `koa/middleware/authenticatedLogoutHandler`, `koa/middleware/authenticatedResourceHandler` |
37
37
  | `@socketlabs/email` | `email/SocketLabsLib`, `email/createSocketLabsSender`, `lib/access/createResetPwdFlow`, `lib/access/createVerifyEmailFlow`, `lib/access/resetPwdMailer`, `lib/access/verifyEmailMailer`, `koa/router/verifyEmail`, and the `signUp` / `login*` / `resetPwd` / `updatePassword` / `emailChangeHashVerify` mutations |
38
+ | `@gltf-transform/core`, `@gltf-transform/extensions`, `@gltf-transform/functions`, `gltf-validator`, `meshoptimizer` | `files/sanitiseGlb`, `files/sanitiseGlbFile` only (the GLB sanitiser; `sharp` is needed there too). `gltf-validator` is published only as `2.0.0-dev.*` prereleases, so its peer range is `>=2.0.0-0 <3` |
38
39
  | `clamscan` | `files/scanVirus`, `files/uploadTempImage`, `files/uploadTempPdf` |
39
- | `file-type` | `files/validateMimeType`, `files/validateMimeTypeImages`, `files/validateJpgPngMimeType`, `files/uploadTempImage`, `files/uploadTempPdf` — loaded lazily, at first call |
40
- | `fs-extra` | the `files/move*` and `files/validate*` helpers, `files/uploadTempImage`, `files/uploadTempPdf` |
40
+ | `file-type` | `files/validateMimeType`, `files/validateMimeTypeImages`, `files/validateJpgPngMimeType`, `files/validateMimeTypeGlb`, `files/uploadTempImage`, `files/uploadTempPdf` — loaded lazily, at first call |
41
+ | `fs-extra` | the `files/move*` and `files/validate*` helpers (the GLB ones included), `files/uploadTempImage`, `files/uploadTempPdf` |
41
42
  | `keygrip` | `koa/middleware/authenticatedAuthorizationHandler`, `.../verifySignedRefreshToken`, `koa/middleware/authenticatedLogoutHandler` — types only; the `Keygrip` instance is yours to construct and pass in |
42
43
  | `koa` | the `koa/middleware/*` handlers, `koa/tdwKoaErrorHandler`, `koa/logRequestToDb` — types only (`Next`) |
43
44
  | `mariadb` | `dataSources/MariaDB` — Sequelize connects with `dialect: 'mariadb'` and loads the driver itself |
@@ -45,7 +46,7 @@ yarn add @node-rs/bcrypt graphql mongoose redis
45
46
  | `reflect-metadata` | `dataSources/MariaDB` — required by `sequelize-typescript`, never imported by this package |
46
47
  | `sequelize` | `dataSources/MariaDB` — peer of `sequelize-typescript` |
47
48
  | `sequelize-typescript` | `dataSources/MariaDB` |
48
- | `sharp` | `files/reEncodeToJpeg`, `files/reEncodeToPng`, `files/reEncodeToWebp`, `files/uploadTempImage` |
49
+ | `sharp` | `files/reEncodeToJpeg`, `files/reEncodeToPng`, `files/reEncodeToWebp`, `files/uploadTempImage`, `files/sanitiseGlb`, `files/sanitiseGlbFile` |
49
50
 
50
51
  A subpath that reaches no peer needs nothing installed, not even `koa` (it appears there only as a type you pass in): `koa/createKoaErrorHandler`, a Koa error middleware you configure with `statusOf`, `bodyOf`, `report` and `noBodyStatuses`, and its two type files `koa/IKoaErrorHandlerOptions` and `koa/IKoaErrorHandlerContext`. `koa/tdwKoaErrorHandler` is the same middleware preconfigured for GraphQL errors, Sentry and dotenv, which is why it needs the peers above.
51
52
 
@@ -312,7 +313,9 @@ For the cluster path the `rediss://` scheme on `rootNodes` is not enough on its
312
313
  ## Build (contributors only)
313
314
 
314
315
  ```bash
316
+ corepack enable # once: Yarn 4 comes from the packageManager field
315
317
  yarn install
318
+ yarn hooks:install # maintainers: points git at .githooks (Yarn 4 does not run the prepare script)
316
319
  yarn build # ESM only — production output
317
320
  yarn build:all # not usable today: the CJS half emits nothing, the package is ESM-only (use yarn build)
318
321
  yarn test # build + build:tests + mocha, no coverage gate
@@ -333,19 +336,16 @@ There is no barrel and no `main` / `module` field.
333
336
 
334
337
  ### Registry
335
338
 
336
- `yarn.lock` always resolves against `https://registry.npmjs.org/`, so a plain clone installs with no extra setup.
339
+ `yarn.lock` is in the Yarn 4 format, which records no registry host, so a plain clone installs with no extra setup (`corepack enable`, then `yarn install`). `.yarnrc.yml` points Yarn at `https://registry.npmjs.org`.
337
340
 
338
- If you install through a private npm mirror, do not commit its host. Yarn 1 downloads tarballs from the absolute `resolved` URL in the lockfile and ignores the configured registry for them, so a lockfile written through a mirror breaks every clone that cannot reach it. Nothing is rewritten unless you ask for it:
341
+ If you install through a private npm mirror, set an environment variable instead of editing any file. It overrides `.yarnrc.yml` for your shell only:
339
342
 
340
343
  ```sh
341
- export REGISTRY_MIRROR=http://host:4873
342
- yarn registry:mirror # public registry -> mirror, before install
344
+ export YARN_NPM_REGISTRY_SERVER=http://host:4873
343
345
  yarn install
344
- yarn registry:canonical # mirror -> public registry, before commit
345
- yarn registry:check # exit 1 if yarn.lock names any other host
346
346
  ```
347
347
 
348
- `registry:check` needs no `REGISTRY_MIRROR`. A pre-commit check also rejects any staged lockfile that names a non-public host.
348
+ Credentials belong in `~/.yarnrc.yml`, never in the repository. A pre-commit check rejects a Yarn 1 lockfile, a lockfile that resolves a package from a URL or git source, and a tracked `.yarnrc.yml` that sets credentials or another registry.
349
349
 
350
350
  ## Feedback, contributing and security
351
351
 
@@ -0,0 +1,49 @@
1
+ /**
2
+ * What `sanitiseGlb` accepts. Every field has a safe default in {@link GLB_POLICY_DEFAULTS}; the caller passes only the
3
+ * fields it wants to change. Every limit is a positive integer: a `0`, a negative number, a float or a `NaN` is a
4
+ * programming error and throws.
5
+ */
6
+ export interface IGlbPolicy {
7
+ /** Bytes of the whole GLB file. */
8
+ maxBytes: number;
9
+ /** Bytes of the JSON chunk. */
10
+ maxJsonBytes: number;
11
+ /** Bytes of all buffers as declared in the JSON, plus the decoded size of every `EXT_meshopt_compression` view. */
12
+ maxBufferBytes: number;
13
+ /** Triangles, counted once for every node that instances the mesh. */
14
+ maxTriangles: number;
15
+ /** Vertices, counted once for every node that instances the mesh. */
16
+ maxVertices: number;
17
+ /** Number of accessors. */
18
+ maxAccessors: number;
19
+ /** `count` of the biggest single accessor, sparse or not. */
20
+ maxAccessorElements: number;
21
+ /** Sum of the `sparse.count` of every accessor. */
22
+ maxSparseElements: number;
23
+ /** Number of meshes. */
24
+ maxMeshes: number;
25
+ /** Number of nodes. */
26
+ maxNodes: number;
27
+ /** Number of materials. */
28
+ maxMaterials: number;
29
+ /** Number of textures, and of images. */
30
+ maxTextures: number;
31
+ /** Number of animations. */
32
+ maxAnimations: number;
33
+ /** Width or height of one image in pixels, read from its header. */
34
+ maxTextureSide: number;
35
+ /** Sum of width times height over every image, read from the headers. */
36
+ maxTexturePixels: number;
37
+ /** JPEG and WebP quality (1 to 100) used when the textures are re-encoded. PNG is always lossless. */
38
+ textureQuality: number;
39
+ /** Extension names the file may declare. Every name must be one the sanitiser can rewrite. */
40
+ allowedExtensions: readonly string[];
41
+ }
42
+ /**
43
+ * The safe defaults of {@link IGlbPolicy}. A caller that wants one more extension spreads the list:
44
+ * `{ allowedExtensions: [...GLB_POLICY_DEFAULTS.allowedExtensions, 'KHR_lights_punctual'] }`.
45
+ *
46
+ * `KHR_draco_mesh_compression` is not in the list: the sanitiser has no Draco decoder, so it could not check the data.
47
+ * `KHR_interactivity` is refused whatever the list says.
48
+ */
49
+ export declare const GLB_POLICY_DEFAULTS: Readonly<IGlbPolicy>;
@@ -0,0 +1,45 @@
1
+ const MIB = 1024 * 1024;
2
+ /**
3
+ * The safe defaults of {@link IGlbPolicy}. A caller that wants one more extension spreads the list:
4
+ * `{ allowedExtensions: [...GLB_POLICY_DEFAULTS.allowedExtensions, 'KHR_lights_punctual'] }`.
5
+ *
6
+ * `KHR_draco_mesh_compression` is not in the list: the sanitiser has no Draco decoder, so it could not check the data.
7
+ * `KHR_interactivity` is refused whatever the list says.
8
+ */
9
+ export const GLB_POLICY_DEFAULTS = {
10
+ maxBytes: 32 * MIB,
11
+ maxJsonBytes: 4 * MIB,
12
+ maxBufferBytes: 128 * MIB,
13
+ maxTriangles: 500_000,
14
+ maxVertices: 1_000_000,
15
+ maxAccessors: 5000,
16
+ maxAccessorElements: 2_000_000,
17
+ maxSparseElements: 100_000,
18
+ maxMeshes: 1000,
19
+ maxNodes: 10_000,
20
+ maxMaterials: 500,
21
+ maxTextures: 100,
22
+ maxAnimations: 100,
23
+ maxTextureSide: 2048,
24
+ maxTexturePixels: 64 * MIB,
25
+ textureQuality: 90,
26
+ allowedExtensions: [
27
+ 'KHR_materials_anisotropy',
28
+ 'KHR_materials_clearcoat',
29
+ 'KHR_materials_dispersion',
30
+ 'KHR_materials_emissive_strength',
31
+ 'KHR_materials_ior',
32
+ 'KHR_materials_iridescence',
33
+ 'KHR_materials_sheen',
34
+ 'KHR_materials_specular',
35
+ 'KHR_materials_transmission',
36
+ 'KHR_materials_unlit',
37
+ 'KHR_materials_volume',
38
+ 'KHR_texture_transform',
39
+ 'KHR_mesh_quantization',
40
+ 'EXT_meshopt_compression',
41
+ 'KHR_texture_basisu',
42
+ 'EXT_texture_webp'
43
+ ]
44
+ };
45
+ //# sourceMappingURL=GLB_POLICY_DEFAULTS.mjs.map
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The closed reasons a GLB upload is rejected for (see `IGlbReason` in `IGlbSanitiseResult`):
3
+ *
4
+ * - `GLB_TOO_LARGE`: the file is bigger than `maxBytes`.
5
+ * - `GLB_TRUNCATED`: the file is shorter than the 12 byte header plus one chunk header.
6
+ * - `GLB_BAD_MAGIC`: the first four bytes are not `glTF`.
7
+ * - `GLB_BAD_VERSION`: the container version is not 2.
8
+ * - `GLB_LENGTH_MISMATCH`: the length in the header differs from the real size of the file.
9
+ * - `GLB_BAD_CHUNKS`: the chunks are not exactly one JSON chunk followed by at most one BIN chunk, or one of them overruns the file.
10
+ * - `GLB_JSON_TOO_LARGE`: the JSON chunk is bigger than `maxJsonBytes`.
11
+ * - `JSON_INVALID`: the JSON chunk is not UTF-8 text holding one JSON object.
12
+ * - `URI_EXTERNAL`: a buffer or image points at a file or a URL. Only the embedded GLB buffer is allowed.
13
+ * - `URI_DATA`: a buffer or image carries a `data:` URI. Only the embedded GLB buffer is allowed.
14
+ * - `EXTENSION_FORBIDDEN`: the file uses an extension that is always refused (`KHR_interactivity`).
15
+ * - `EXTENSION_NOT_ALLOWED`: the file uses an extension that is not in `allowedExtensions`.
16
+ * - `LIMIT_EXCEEDED`: a count or a size is over the limit named in `limit` (see `IGlbPolicy`).
17
+ * - `IMAGE_UNREADABLE`: an image has no bytes inside the BIN chunk, or its header cannot be read.
18
+ * - `IMAGE_UNSUPPORTED`: the bytes of an image are not PNG, JPEG, WebP or KTX2.
19
+ * - `IMAGE_FORMAT_MISMATCH`: the `mimeType` of an image names another format than its bytes.
20
+ * - `IMAGE_DECODE_FAILED`: the image passed the header check but could not be decoded and re-encoded.
21
+ * - `VALIDATOR_ERROR`: the Khronos glTF Validator reported an error.
22
+ * - `VALIDATOR_FAILED`: the Khronos glTF Validator crashed on the file.
23
+ * - `MESHOPT_DECODE_FAILED`: the `EXT_meshopt_compression` data does not decode.
24
+ * - `READ_FAILED`: the glTF Transform reader could not read the file.
25
+ * - `OUTPUT_INVALID`: the rewritten file failed its own check (validator or decode). Never expected: the input is rejected instead.
26
+ */
27
+ export declare const GLB_REJECT_CODES: readonly ["GLB_TOO_LARGE", "GLB_TRUNCATED", "GLB_BAD_MAGIC", "GLB_BAD_VERSION", "GLB_LENGTH_MISMATCH", "GLB_BAD_CHUNKS", "GLB_JSON_TOO_LARGE", "JSON_INVALID", "URI_EXTERNAL", "URI_DATA", "EXTENSION_FORBIDDEN", "EXTENSION_NOT_ALLOWED", "LIMIT_EXCEEDED", "IMAGE_UNREADABLE", "IMAGE_UNSUPPORTED", "IMAGE_FORMAT_MISMATCH", "IMAGE_DECODE_FAILED", "VALIDATOR_ERROR", "VALIDATOR_FAILED", "MESHOPT_DECODE_FAILED", "READ_FAILED", "OUTPUT_INVALID"];
28
+ /** One of {@link GLB_REJECT_CODES}. */
29
+ export type IGlbRejectCode = (typeof GLB_REJECT_CODES)[number];
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The closed reasons a GLB upload is rejected for (see `IGlbReason` in `IGlbSanitiseResult`):
3
+ *
4
+ * - `GLB_TOO_LARGE`: the file is bigger than `maxBytes`.
5
+ * - `GLB_TRUNCATED`: the file is shorter than the 12 byte header plus one chunk header.
6
+ * - `GLB_BAD_MAGIC`: the first four bytes are not `glTF`.
7
+ * - `GLB_BAD_VERSION`: the container version is not 2.
8
+ * - `GLB_LENGTH_MISMATCH`: the length in the header differs from the real size of the file.
9
+ * - `GLB_BAD_CHUNKS`: the chunks are not exactly one JSON chunk followed by at most one BIN chunk, or one of them overruns the file.
10
+ * - `GLB_JSON_TOO_LARGE`: the JSON chunk is bigger than `maxJsonBytes`.
11
+ * - `JSON_INVALID`: the JSON chunk is not UTF-8 text holding one JSON object.
12
+ * - `URI_EXTERNAL`: a buffer or image points at a file or a URL. Only the embedded GLB buffer is allowed.
13
+ * - `URI_DATA`: a buffer or image carries a `data:` URI. Only the embedded GLB buffer is allowed.
14
+ * - `EXTENSION_FORBIDDEN`: the file uses an extension that is always refused (`KHR_interactivity`).
15
+ * - `EXTENSION_NOT_ALLOWED`: the file uses an extension that is not in `allowedExtensions`.
16
+ * - `LIMIT_EXCEEDED`: a count or a size is over the limit named in `limit` (see `IGlbPolicy`).
17
+ * - `IMAGE_UNREADABLE`: an image has no bytes inside the BIN chunk, or its header cannot be read.
18
+ * - `IMAGE_UNSUPPORTED`: the bytes of an image are not PNG, JPEG, WebP or KTX2.
19
+ * - `IMAGE_FORMAT_MISMATCH`: the `mimeType` of an image names another format than its bytes.
20
+ * - `IMAGE_DECODE_FAILED`: the image passed the header check but could not be decoded and re-encoded.
21
+ * - `VALIDATOR_ERROR`: the Khronos glTF Validator reported an error.
22
+ * - `VALIDATOR_FAILED`: the Khronos glTF Validator crashed on the file.
23
+ * - `MESHOPT_DECODE_FAILED`: the `EXT_meshopt_compression` data does not decode.
24
+ * - `READ_FAILED`: the glTF Transform reader could not read the file.
25
+ * - `OUTPUT_INVALID`: the rewritten file failed its own check (validator or decode). Never expected: the input is rejected instead.
26
+ */
27
+ export const GLB_REJECT_CODES = [
28
+ 'GLB_TOO_LARGE',
29
+ 'GLB_TRUNCATED',
30
+ 'GLB_BAD_MAGIC',
31
+ 'GLB_BAD_VERSION',
32
+ 'GLB_LENGTH_MISMATCH',
33
+ 'GLB_BAD_CHUNKS',
34
+ 'GLB_JSON_TOO_LARGE',
35
+ 'JSON_INVALID',
36
+ 'URI_EXTERNAL',
37
+ 'URI_DATA',
38
+ 'EXTENSION_FORBIDDEN',
39
+ 'EXTENSION_NOT_ALLOWED',
40
+ 'LIMIT_EXCEEDED',
41
+ 'IMAGE_UNREADABLE',
42
+ 'IMAGE_UNSUPPORTED',
43
+ 'IMAGE_FORMAT_MISMATCH',
44
+ 'IMAGE_DECODE_FAILED',
45
+ 'VALIDATOR_ERROR',
46
+ 'VALIDATOR_FAILED',
47
+ 'MESHOPT_DECODE_FAILED',
48
+ 'READ_FAILED',
49
+ 'OUTPUT_INVALID'
50
+ ];
51
+ //# sourceMappingURL=GLB_REJECT_CODES.mjs.map
@@ -0,0 +1,12 @@
1
+ import type { IGlbReason } from './IGlbSanitiseResult.mjs';
2
+ /** Result of `checkGlbContainer`. The byte arrays are views into the input, not copies. */
3
+ export type IGlbContainerResult = {
4
+ ok: true;
5
+ /** The JSON chunk. */
6
+ json: Uint8Array;
7
+ /** The BIN chunk, `null` when the file has none. */
8
+ bin: Uint8Array | null;
9
+ } | {
10
+ ok: false;
11
+ reason: IGlbReason;
12
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IGlbContainer.mjs.map
@@ -0,0 +1,56 @@
1
+ import type { IGlbPolicy } from './GLB_POLICY_DEFAULTS.mjs';
2
+ import type { IGlbRejectCode } from './GLB_REJECT_CODES.mjs';
3
+ /** A name in {@link IGlbPolicy} that holds a limit (every field but the quality and the extension list). */
4
+ export type IGlbLimitName = Exclude<keyof IGlbPolicy, 'allowedExtensions' | 'textureQuality'>;
5
+ /** One reason a file was rejected. */
6
+ export interface IGlbReason {
7
+ /** Machine code, one of `GLB_REJECT_CODES`. */
8
+ code: IGlbRejectCode;
9
+ /** English text for a log. The wording can change in a patch release, so do not match on it. */
10
+ message: string;
11
+ /** JSON pointer into the glTF JSON when the reason points at one object, for example `/images/0`. */
12
+ pointer?: string;
13
+ /** Set for `LIMIT_EXCEEDED`: the name of the limit that was hit. */
14
+ limit?: IGlbLimitName;
15
+ }
16
+ /**
17
+ * What was measured. A number is `0` for a stage the file never reached, so a file rejected in the container check has
18
+ * only `inputBytes` set.
19
+ */
20
+ export interface IGlbStats {
21
+ /** Size of the uploaded file. */
22
+ inputBytes: number;
23
+ /** Size of the sanitised file, `0` when the file was rejected. */
24
+ outputBytes: number;
25
+ nodes: number;
26
+ meshes: number;
27
+ materials: number;
28
+ textures: number;
29
+ animations: number;
30
+ accessors: number;
31
+ /** Triangles, counted once for every node that instances the mesh. */
32
+ triangles: number;
33
+ /** Vertices, counted once for every node that instances the mesh. */
34
+ vertices: number;
35
+ /** Declared buffer bytes plus the decoded size of the `EXT_meshopt_compression` views. */
36
+ bufferBytes: number;
37
+ /** Longest side in pixels over all images, read from the headers. */
38
+ maxTextureSide: number;
39
+ /** Textures that were decoded and re-encoded by `sharp`. */
40
+ texturesReencoded: number;
41
+ }
42
+ /** The file passed every check and `glb` is the freshly written file. `reasons` is empty. */
43
+ export interface IGlbAccepted {
44
+ accepted: true;
45
+ glb: Uint8Array;
46
+ reasons: [];
47
+ stats: IGlbStats;
48
+ }
49
+ /** The file failed at least one check. `reasons` is never empty. */
50
+ export interface IGlbRejected {
51
+ accepted: false;
52
+ reasons: IGlbReason[];
53
+ stats: IGlbStats;
54
+ }
55
+ /** Result of `sanitiseGlb`. A hostile file gives `accepted: false`, never a thrown error. */
56
+ export type IGlbSanitiseResult = IGlbAccepted | IGlbRejected;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IGlbSanitiseResult.mjs.map
@@ -0,0 +1,11 @@
1
+ import { type IGlbPolicy } from './GLB_POLICY_DEFAULTS.mjs';
2
+ import type { IGlbContainerResult } from './IGlbContainer.mjs';
3
+ /**
4
+ * Check the container of a GLB without parsing its JSON: magic `glTF`, version 2, the length in the header against the
5
+ * real size, and the chunk layout (one JSON chunk, then at most one BIN chunk, nothing else). Cheap, so a caller can use
6
+ * it to turn a file away before any heavy work. Never throws on a hostile file.
7
+ *
8
+ * @param bytes the whole file
9
+ * @param limits `maxBytes` and `maxJsonBytes` of {@link IGlbPolicy}; the defaults apply to a field that is left out
10
+ */
11
+ export declare function checkGlbContainer(bytes: Uint8Array, limits?: Partial<Pick<IGlbPolicy, 'maxBytes' | 'maxJsonBytes'>>): IGlbContainerResult;
@@ -0,0 +1,68 @@
1
+ import { tooLargeReason } from "../private/glb/glbReason.mjs";
2
+ import { GLB_POLICY_DEFAULTS } from './GLB_POLICY_DEFAULTS.mjs';
3
+ const MAGIC = 0x46_54_6c_67; // 'glTF' read as a little-endian uint32
4
+ const VERSION = 2;
5
+ const CHUNK_JSON = 0x4e_4f_53_4a; // 'JSON'
6
+ const CHUNK_BIN = 0x00_4e_49_42; // 'BIN\0'
7
+ const HEADER_BYTES = 12;
8
+ const CHUNK_HEADER_BYTES = 8;
9
+ const JSON_START = HEADER_BYTES + CHUNK_HEADER_BYTES;
10
+ const fail = (code, message) => ({ ok: false, reason: { code, message } });
11
+ function readBin(view, bytes, json, offset) {
12
+ if (offset + CHUNK_HEADER_BYTES > bytes.length) {
13
+ return fail('GLB_BAD_CHUNKS', 'bytes after the JSON chunk are too few for a BIN chunk');
14
+ }
15
+ if (view.getUint32(offset + 4, true) !== CHUNK_BIN) {
16
+ return fail('GLB_BAD_CHUNKS', 'the chunk after the JSON chunk is not a BIN chunk');
17
+ }
18
+ const start = offset + CHUNK_HEADER_BYTES;
19
+ const end = start + view.getUint32(offset, true);
20
+ if (end !== bytes.length) {
21
+ return fail('GLB_BAD_CHUNKS', 'the BIN chunk does not end where the file ends');
22
+ }
23
+ return { ok: true, json, bin: bytes.subarray(start, end) };
24
+ }
25
+ function readChunks(view, bytes, maxJsonBytes) {
26
+ if (view.getUint32(HEADER_BYTES + 4, true) !== CHUNK_JSON) {
27
+ return fail('GLB_BAD_CHUNKS', 'the first chunk is not a JSON chunk');
28
+ }
29
+ const jsonLength = view.getUint32(HEADER_BYTES, true);
30
+ if (jsonLength > maxJsonBytes) {
31
+ return fail('GLB_JSON_TOO_LARGE', `the JSON chunk has ${jsonLength} bytes, the limit is ${maxJsonBytes}`);
32
+ }
33
+ const jsonEnd = JSON_START + jsonLength;
34
+ if (jsonEnd > bytes.length) {
35
+ return fail('GLB_BAD_CHUNKS', 'the JSON chunk runs past the end of the file');
36
+ }
37
+ const json = bytes.subarray(JSON_START, jsonEnd);
38
+ return jsonEnd === bytes.length ? { ok: true, json, bin: null } : readBin(view, bytes, json, jsonEnd);
39
+ }
40
+ /**
41
+ * Check the container of a GLB without parsing its JSON: magic `glTF`, version 2, the length in the header against the
42
+ * real size, and the chunk layout (one JSON chunk, then at most one BIN chunk, nothing else). Cheap, so a caller can use
43
+ * it to turn a file away before any heavy work. Never throws on a hostile file.
44
+ *
45
+ * @param bytes the whole file
46
+ * @param limits `maxBytes` and `maxJsonBytes` of {@link IGlbPolicy}; the defaults apply to a field that is left out
47
+ */
48
+ export function checkGlbContainer(bytes, limits = {}) {
49
+ const maxBytes = limits.maxBytes ?? GLB_POLICY_DEFAULTS.maxBytes;
50
+ if (bytes.length > maxBytes) {
51
+ return { ok: false, reason: tooLargeReason(bytes.length, maxBytes) };
52
+ }
53
+ if (bytes.length < JSON_START) {
54
+ return fail('GLB_TRUNCATED', 'the file is too short to hold a header and a chunk');
55
+ }
56
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
57
+ if (view.getUint32(0, true) !== MAGIC) {
58
+ return fail('GLB_BAD_MAGIC', 'the file does not start with glTF');
59
+ }
60
+ if (view.getUint32(4, true) !== VERSION) {
61
+ return fail('GLB_BAD_VERSION', 'the GLB container version is not 2');
62
+ }
63
+ if (view.getUint32(8, true) !== bytes.length) {
64
+ return fail('GLB_LENGTH_MISMATCH', `the header says ${view.getUint32(8, true)} bytes, the file has ${bytes.length}`);
65
+ }
66
+ return readChunks(view, bytes, limits.maxJsonBytes ?? GLB_POLICY_DEFAULTS.maxJsonBytes);
67
+ }
68
+ //# sourceMappingURL=checkGlbContainer.mjs.map
@@ -0,0 +1,22 @@
1
+ import type { IGlbPolicy } from './GLB_POLICY_DEFAULTS.mjs';
2
+ import type { IGlbSanitiseResult } from './IGlbSanitiseResult.mjs';
3
+ /**
4
+ * Check a GLB for hostile content and write a clean copy. In this order, and the first stage that finds a problem ends it:
5
+ *
6
+ * 1. the container: `glTF` magic, version 2, declared length, chunk layout, size ({@link checkGlbContainer});
7
+ * 2. the JSON chunk parses as one JSON object;
8
+ * 3. the policy: no external or `data:` URI, only allowed extensions, counts, triangles, vertices, accessors (sparse
9
+ * ones too), buffer bytes, and the size of every texture read from its header before anything decodes it;
10
+ * 4. the Khronos glTF Validator: any error rejects;
11
+ * 5. the rewrite through glTF Transform: meshopt data is decoded (bad data rejects), `extras`, unknown extensions and
12
+ * unused data are dropped, PNG, JPEG and WebP textures are re-encoded with `sharp`, one embedded buffer is written;
13
+ * 6. the new file goes through the validator and the decoder once more.
14
+ *
15
+ * A hostile file never throws: it gives `{ accepted: false, reasons, stats }`. Only misuse throws (`TypeError` for
16
+ * input that is not a `Uint8Array` or for an invalid option, `RangeError` for an extension the sanitiser cannot rewrite).
17
+ * This function does not scan for viruses: call `scanVirus` on the stored file as well.
18
+ *
19
+ * @param input the whole GLB file
20
+ * @param options the limits and the extension list; see {@link IGlbPolicy}. Every field has a safe default.
21
+ */
22
+ export declare function sanitiseGlb(input: Uint8Array, options?: Partial<IGlbPolicy>): Promise<IGlbSanitiseResult>;
@@ -0,0 +1,66 @@
1
+ import { createGlbIo } from "../private/glb/glbIo.mjs";
2
+ import { emptyStats, rejected } from "../private/glb/glbStats.mjs";
3
+ import { inspectGlbJson } from "../private/glb/inspectGlbJson.mjs";
4
+ import { parseGlbJson } from "../private/glb/parseGlbJson.mjs";
5
+ import { resolveGlbPolicy } from "../private/glb/resolveGlbPolicy.mjs";
6
+ import { rewriteGlb } from "../private/glb/rewriteGlb.mjs";
7
+ import { validateKhronos } from "../private/glb/validateKhronos.mjs";
8
+ import { verifyGlbOutput } from "../private/glb/verifyGlbOutput.mjs";
9
+ import { checkGlbContainer } from './checkGlbContainer.mjs';
10
+ /**
11
+ * Check a GLB for hostile content and write a clean copy. In this order, and the first stage that finds a problem ends it:
12
+ *
13
+ * 1. the container: `glTF` magic, version 2, declared length, chunk layout, size ({@link checkGlbContainer});
14
+ * 2. the JSON chunk parses as one JSON object;
15
+ * 3. the policy: no external or `data:` URI, only allowed extensions, counts, triangles, vertices, accessors (sparse
16
+ * ones too), buffer bytes, and the size of every texture read from its header before anything decodes it;
17
+ * 4. the Khronos glTF Validator: any error rejects;
18
+ * 5. the rewrite through glTF Transform: meshopt data is decoded (bad data rejects), `extras`, unknown extensions and
19
+ * unused data are dropped, PNG, JPEG and WebP textures are re-encoded with `sharp`, one embedded buffer is written;
20
+ * 6. the new file goes through the validator and the decoder once more.
21
+ *
22
+ * A hostile file never throws: it gives `{ accepted: false, reasons, stats }`. Only misuse throws (`TypeError` for
23
+ * input that is not a `Uint8Array` or for an invalid option, `RangeError` for an extension the sanitiser cannot rewrite).
24
+ * This function does not scan for viruses: call `scanVirus` on the stored file as well.
25
+ *
26
+ * @param input the whole GLB file
27
+ * @param options the limits and the extension list; see {@link IGlbPolicy}. Every field has a safe default.
28
+ */
29
+ export async function sanitiseGlb(input, options = {}) {
30
+ const policy = resolveGlbPolicy(options);
31
+ if (!(input instanceof Uint8Array)) {
32
+ throw new TypeError('sanitiseGlb: input must be a Uint8Array or a Buffer');
33
+ }
34
+ // One private copy: glTF Transform reads from offset 0 of the underlying buffer, so a view or a pooled Buffer would
35
+ // fail to read. It also freezes what every stage sees if the caller changes its array while this call awaits.
36
+ const bytes = new Uint8Array(input);
37
+ const stats = emptyStats(bytes.length);
38
+ const container = checkGlbContainer(bytes, policy);
39
+ if (!container.ok) {
40
+ return rejected([container.reason], stats);
41
+ }
42
+ const parsed = parseGlbJson(container.json);
43
+ if (parsed.json === null) {
44
+ return rejected(parsed.reasons, stats);
45
+ }
46
+ const violations = inspectGlbJson(parsed.json, container.bin, policy, stats);
47
+ if (violations.length > 0) {
48
+ return rejected(violations, stats);
49
+ }
50
+ const invalid = await validateKhronos(bytes);
51
+ if (invalid.length > 0) {
52
+ return rejected(invalid, stats);
53
+ }
54
+ const io = await createGlbIo(policy.allowedExtensions);
55
+ const rewritten = await rewriteGlb(io, bytes, policy, stats);
56
+ if (rewritten.glb === null) {
57
+ return rejected(rewritten.reasons, stats);
58
+ }
59
+ const problems = await verifyGlbOutput(io, rewritten.glb);
60
+ if (problems.length > 0) {
61
+ return rejected(problems, stats);
62
+ }
63
+ stats.outputBytes = rewritten.glb.length;
64
+ return { accepted: true, glb: rewritten.glb, reasons: [], stats };
65
+ }
66
+ //# sourceMappingURL=sanitiseGlb.mjs.map
@@ -0,0 +1,16 @@
1
+ import type { IGlbPolicy } from './GLB_POLICY_DEFAULTS.mjs';
2
+ import type { IGlbSanitiseResult } from './IGlbSanitiseResult.mjs';
3
+ /**
4
+ * `sanitiseGlb` on a stored upload, for the temp file `storeUploadAsTemp` wrote. A file bigger than `maxBytes` is
5
+ * refused from its size, before one byte is read.
6
+ *
7
+ * - accepted: the sanitised bytes replace the file at `filePath`, so the path stays valid for the mover.
8
+ * - rejected: the file is deleted, like the extension and MIME validators do, so a hostile upload never stays on disk.
9
+ *
10
+ * Throws only on misuse (an invalid option) or when the file cannot be read, as `fs` does. A hostile file gives a
11
+ * rejected result. Run `scanVirus` on the file before this call: the sanitiser looks at structure, not at signatures.
12
+ *
13
+ * @param filePath the temp file
14
+ * @param options the limits and the extension list; see {@link IGlbPolicy}
15
+ */
16
+ export declare function sanitiseGlbFile(filePath: string, options?: Partial<IGlbPolicy>): Promise<IGlbSanitiseResult>;
@@ -0,0 +1,36 @@
1
+ import { readFile, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { tooLargeReason } from "../private/glb/glbReason.mjs";
3
+ import { emptyStats, rejected } from "../private/glb/glbStats.mjs";
4
+ import { resolveGlbPolicy } from "../private/glb/resolveGlbPolicy.mjs";
5
+ import { sanitiseGlb } from './sanitiseGlb.mjs';
6
+ /**
7
+ * `sanitiseGlb` on a stored upload, for the temp file `storeUploadAsTemp` wrote. A file bigger than `maxBytes` is
8
+ * refused from its size, before one byte is read.
9
+ *
10
+ * - accepted: the sanitised bytes replace the file at `filePath`, so the path stays valid for the mover.
11
+ * - rejected: the file is deleted, like the extension and MIME validators do, so a hostile upload never stays on disk.
12
+ *
13
+ * Throws only on misuse (an invalid option) or when the file cannot be read, as `fs` does. A hostile file gives a
14
+ * rejected result. Run `scanVirus` on the file before this call: the sanitiser looks at structure, not at signatures.
15
+ *
16
+ * @param filePath the temp file
17
+ * @param options the limits and the extension list; see {@link IGlbPolicy}
18
+ */
19
+ export async function sanitiseGlbFile(filePath, options = {}) {
20
+ const policy = resolveGlbPolicy(options);
21
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the caller names a temp file it stored itself, nothing here builds the path from request data
22
+ const { size } = await stat(filePath);
23
+ const result = size > policy.maxBytes
24
+ ? rejected([tooLargeReason(size, policy.maxBytes)], emptyStats(size))
25
+ : // eslint-disable-next-line security/detect-non-literal-fs-filename -- same caller-owned path as the stat above
26
+ await sanitiseGlb(await readFile(filePath), policy);
27
+ if (result.accepted) {
28
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- same caller-owned path as the stat above
29
+ await writeFile(filePath, result.glb);
30
+ }
31
+ else {
32
+ await rm(filePath, { force: true });
33
+ }
34
+ return result;
35
+ }
36
+ //# sourceMappingURL=sanitiseGlbFile.mjs.map
@@ -0,0 +1 @@
1
+ export declare function validateGlbExtension(filename: string, filePath: string): Promise<void>;
@@ -0,0 +1,9 @@
1
+ import fs from 'fs-extra';
2
+ import { validateExtension } from './validateExtension.mjs';
3
+ export async function validateGlbExtension(filename, filePath) {
4
+ if (!validateExtension(filename, ['.glb'])) {
5
+ await fs.remove(filePath); // Clean up the file
6
+ throw new Error('Invalid file extension');
7
+ }
8
+ }
9
+ //# sourceMappingURL=validateGlbExtension.mjs.map
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Validate MIME type based on file content (magic number validation)
3
+ * @param filePath
4
+ */
5
+ export declare function validateMimeTypeGlb(filePath: string): Promise<string>;
@@ -0,0 +1,9 @@
1
+ import { validateMimeType } from './validateMimeType.mjs';
2
+ /**
3
+ * Validate MIME type based on file content (magic number validation)
4
+ * @param filePath
5
+ */
6
+ export async function validateMimeTypeGlb(filePath) {
7
+ return await validateMimeType(filePath, ['model/gltf-binary']);
8
+ }
9
+ //# sourceMappingURL=validateMimeTypeGlb.mjs.map
@@ -0,0 +1,5 @@
1
+ /** Width and height of an image in pixels, as its header states them. */
2
+ export interface IImageSize {
3
+ width: number;
4
+ height: number;
5
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IImageSize.mjs.map
@@ -0,0 +1,15 @@
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
+ * How many objects each top-level collection holds, against its limit. Images count against `maxTextures` too, since
6
+ * every image is a texture payload. Fills `nodes`, `meshes`, `materials`, `textures`, `animations` and `accessors` in `stats`.
7
+ */
8
+ export declare function checkGlbCounts(json: IJsonObject, policy: IGlbPolicy, stats: IGlbStats): IGlbReason[];
9
+ /** The biggest accessor `count`, and the sum of every `sparse.count`, against their limits. Reads the JSON only, never the data. */
10
+ export declare function checkGlbAccessors(json: IJsonObject, policy: IGlbPolicy): IGlbReason[];
11
+ /**
12
+ * The declared size of every buffer plus the decoded size of every meshopt buffer view, against `maxBufferBytes`. The
13
+ * decoder allocates `count * byteStride` before it reads one byte, so a tiny file can ask for gigabytes.
14
+ */
15
+ export declare function checkGlbBuffers(json: IJsonObject, policy: IGlbPolicy, stats: IGlbStats): IGlbReason[];