@axiumine/koa-utils 9.3.0 → 10.0.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 +31 -3
- package/dist/files/VirusScanError.d.mts +14 -0
- package/dist/files/VirusScanError.mjs +19 -0
- package/dist/files/reEncodePdf.d.mts +43 -0
- package/dist/files/reEncodePdf.mjs +39 -0
- package/dist/files/scanVirus.d.mts +18 -5
- package/dist/files/scanVirus.mjs +56 -22
- package/dist/files/storeUploadAsTemp.d.mts +13 -1
- package/dist/files/storeUploadAsTemp.mjs +21 -3
- package/dist/files/uploadTempImage.d.mts +19 -1
- package/dist/files/uploadTempImage.mjs +52 -17
- package/dist/files/uploadTempPdf.d.mts +14 -3
- package/dist/files/uploadTempPdf.mjs +52 -17
- package/dist/private/files/assertWholeNumber.d.mts +9 -0
- package/dist/private/files/assertWholeNumber.mjs +14 -0
- package/dist/private/files/reEncode.d.mts +10 -2
- package/dist/private/files/reEncode.mjs +28 -15
- package/dist/private/files/replaceExtension.d.mts +8 -0
- package/dist/private/files/replaceExtension.mjs +11 -0
- package/dist/private/glb/reEncodeImage.d.mts +2 -2
- package/dist/private/glb/reEncodeImage.mjs +2 -2
- package/dist/private/lib/createLimiter.d.mts +7 -0
- package/dist/private/lib/createLimiter.mjs +31 -0
- package/dist/private/lib/createSentryClient.mjs +1 -0
- package/dist/private/pdf/pdfDictionary.d.mts +9 -0
- package/dist/private/pdf/pdfDictionary.mjs +25 -0
- package/dist/private/pdf/pdfStripRules.d.mts +12 -0
- package/dist/private/pdf/pdfStripRules.mjs +56 -0
- package/dist/private/pdf/resolvePdfOptions.d.mts +15 -0
- package/dist/private/pdf/resolvePdfOptions.mjs +49 -0
- package/dist/private/pdf/rewritePdf.d.mts +11 -0
- package/dist/private/pdf/rewritePdf.mjs +29 -0
- package/dist/private/pdf/rewritePdfWorker.d.mts +1 -0
- package/dist/private/pdf/rewritePdfWorker.mjs +7 -0
- package/dist/private/pdf/runInWorker.d.mts +10 -0
- package/dist/private/pdf/runInWorker.mjs +45 -0
- package/dist/private/pdf/stripPdf.d.mts +7 -0
- package/dist/private/pdf/stripPdf.mjs +67 -0
- package/dist/s3/S3ObjectTooLargeError.d.mts +8 -0
- package/dist/s3/S3ObjectTooLargeError.mjs +13 -0
- package/dist/s3/createS3Client.d.mts +18 -0
- package/dist/s3/createS3Client.mjs +20 -0
- package/dist/s3/deleteObject.d.mts +9 -0
- package/dist/s3/deleteObject.mjs +9 -0
- package/dist/s3/getObjectToFile.d.mts +19 -0
- package/dist/s3/getObjectToFile.mjs +52 -0
- package/dist/s3/headObject.d.mts +17 -0
- package/dist/s3/headObject.mjs +23 -0
- package/dist/s3/presignPutUrl.d.mts +22 -0
- package/dist/s3/presignPutUrl.mjs +27 -0
- package/dist/s3/putObject.d.mts +15 -0
- package/dist/s3/putObject.mjs +10 -0
- package/package.json +56 -5
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
[](https://scorecard.dev/viewer/?uri=github.com/Axiumine/koa-utils)
|
|
4
4
|
[](https://www.bestpractices.dev/projects/16094)
|
|
5
5
|
|
|
6
|
-
TypeScript utility library for Koa + GraphQL backends. Ships authentication middleware, GraphQL error helpers, data-source connectors (MongoDB, MariaDB, PostgreSQL, Redis), file upload pipeline (ClamAV + sharp re-encode), and transactional email via SocketLabs.
|
|
6
|
+
TypeScript utility library for Koa + GraphQL backends. Ships authentication middleware, GraphQL error helpers, data-source connectors (MongoDB, MariaDB, PostgreSQL, Redis), file upload pipeline (ClamAV + sharp re-encode), S3-compatible object storage (Cloudflare R2), and transactional email via SocketLabs.
|
|
7
7
|
|
|
8
8
|
- **Module format:** ESM only (`.mjs` + `.d.mts`)
|
|
9
9
|
- **Node:** `^24.14.0 || ^26.13.0` (24 and 26 are the LTS lines; the suite runs on both)
|
|
@@ -30,9 +30,12 @@ yarn add @node-rs/bcrypt graphql mongoose redis
|
|
|
30
30
|
|
|
31
31
|
| Peer | Needed by (fails at import with `ERR_MODULE_NOT_FOUND` if missing) |
|
|
32
32
|
|---|---|
|
|
33
|
+
| `@aws-sdk/client-s3` | `s3/createS3Client`, `s3/putObject`, `s3/headObject`, `s3/getObjectToFile`, `s3/deleteObject`, `s3/presignPutUrl` |
|
|
34
|
+
| `@aws-sdk/s3-request-presigner` | `s3/presignPutUrl` only |
|
|
33
35
|
| `@node-rs/bcrypt` | the password flows: `lib/encryptPassword`, `lib/hash`, `lib/db/registerNewUser`, `lib/access/createResetPwdFlow`, and the `signUp` / `login*` / `updatePassword` mutations |
|
|
34
36
|
| `graphql` | `graphQL/throw/*`, `graphQL/schema/types/*`, `graphQL/schema/GraphQLInput/*`, the mutations, and every subpath that raises a `GraphQLError` through a `throw*` helper: `lib/checkEmailLen`, `lib/checkPwdLen`, `lib/tryCatchRethrow`, `lib/MongoDB/*`, `lib/MariaDB/throwSqlErrors`, `lib/throwIfNotValidEnumValue`, `lib/access/create*Flow`, `lib/access/*Mailer`, `koa/customFormatErrorFn`, `koa/tdwKoaErrorHandler`, the `koa/middleware/*` handlers, `koa/router/verifyEmail`, `email/SocketLabsLib`, `files/uploadTempImage` and `files/reEncodeTo*` |
|
|
35
37
|
| `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) |
|
|
38
|
+
| `mupdf` | `files/reEncodePdf`, and `files/uploadTempPdf` when called with `reEncode` — loaded lazily, in a worker thread, at each re-encode |
|
|
36
39
|
| `redis` | `dataSources/Redis`, the `login*` / `logout` / `refresh` mutations, `koa/middleware/authenticatedAuthorizationHandler`, `koa/middleware/authenticatedLogoutHandler`, `koa/middleware/authenticatedResourceHandler` |
|
|
37
40
|
| `@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
41
|
| `clamscan` | `files/scanVirus`, `files/uploadTempImage`, `files/uploadTempPdf` |
|
|
@@ -208,11 +211,36 @@ import { initClamScan } from '@axiumine/koa-utils/files/scanVirus'
|
|
|
208
211
|
import { uploadTempImage } from '@axiumine/koa-utils/files/uploadTempImage'
|
|
209
212
|
import { uploadTempPdf } from '@axiumine/koa-utils/files/uploadTempPdf'
|
|
210
213
|
|
|
211
|
-
await initClamScan() // once at boot
|
|
214
|
+
await initClamScan() // once at boot; TCP daemon: initClamScan({ clamdscan: { host, port } })
|
|
212
215
|
const { tempFile, ext } = await uploadTempImage(filePromise) // jpg/png → webp
|
|
216
|
+
const photo = await uploadTempImage(filePromise, {
|
|
217
|
+
maxFileSize: 2 * 1024 * 1024,
|
|
218
|
+
maxPixels: 4096 * 4096,
|
|
219
|
+
webp: { lossless: false, quality: 85 }
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
const pdf = await uploadTempPdf(filePromise) // kept as uploaded
|
|
223
|
+
const clean = await uploadTempPdf(filePromise, { reEncode: true }) // written again without active content
|
|
224
|
+
await uploadTempPdf(filePromise, { reEncode: { strip: { links: true, forms: true } } })
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Pipeline: stream to `/tmp` (5 MB cap) → extension + magic-number MIME check → ClamAV → sharp re-encode. `tempDir`, `maxFileSize`, `maxPixels` and the WebP encoder are options of `uploadTempImage`.
|
|
228
|
+
|
|
229
|
+
- **Uploads fail closed.** For images and PDFs alike, an infected file, and a scan that gave no verdict, throw `VirusScanError` (`files/VirusScanError`); a refused upload leaves no temp file. `clamd` must be able to read the temp folder.
|
|
230
|
+
- **No metadata is kept.** The re-encoded image has no EXIF, XMP, IPTC or ICC profile, and is turned the way its EXIF orientation said.
|
|
231
|
+
- **PDFs are re-encoded only on request.** Without `reEncode` the file holds the uploaded bytes, active content included. With it (optional peer `mupdf`), scripts, actions, embedded files, multimedia and metadata are removed by default; `strip` also takes `links`, `forms` and `annotations`. Images and fonts inside the PDF are not rebuilt.
|
|
232
|
+
|
|
233
|
+
### S3-compatible storage
|
|
234
|
+
|
|
235
|
+
```ts
|
|
236
|
+
import { createS3Client } from '@axiumine/koa-utils/s3/createS3Client'
|
|
237
|
+
import { presignPutUrl } from '@axiumine/koa-utils/s3/presignPutUrl'
|
|
238
|
+
|
|
239
|
+
const client = createS3Client({ endpoint, region: 'auto', accessKeyId, secretAccessKey }) // Cloudflare R2
|
|
240
|
+
const url = await presignPutUrl(client, { bucket, key, contentType: 'model/gltf-binary', contentLength, expiresIn: 600 })
|
|
213
241
|
```
|
|
214
242
|
|
|
215
|
-
|
|
243
|
+
Also `s3/putObject`, `s3/headObject`, `s3/getObjectToFile` (stops past `maxBytes`) and `s3/deleteObject`. Peers: `@aws-sdk/client-s3`, plus `@aws-sdk/s3-request-presigner` for presigned URLs. Reference and security notes: [docs/code/s3.md](https://github.com/Axiumine/koa-utils/blob/main/docs/code/s3.md).
|
|
216
244
|
|
|
217
245
|
### Email
|
|
218
246
|
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type TVirusScanErrorCode = 'VIRUS_FOUND' | 'SCAN_FAILED';
|
|
2
|
+
/**
|
|
3
|
+
* A file refused by the virus check: ClamAV reported it as infected (`VIRUS_FOUND`), or the scan gave no verdict
|
|
4
|
+
* (`SCAN_FAILED`). Thrown by `scanVirus` with `failClosed: true` and by `uploadTempImage`.
|
|
5
|
+
*
|
|
6
|
+
* The message is fixed and names neither the file path nor the signature. The detail is in `code`, `viruses` and,
|
|
7
|
+
* for a failed scan, `cause`.
|
|
8
|
+
*/
|
|
9
|
+
export declare class VirusScanError extends Error {
|
|
10
|
+
readonly code: TVirusScanErrorCode;
|
|
11
|
+
/** virus names reported by ClamAV; empty for `SCAN_FAILED` */
|
|
12
|
+
readonly viruses: string[];
|
|
13
|
+
constructor(code: TVirusScanErrorCode, viruses?: string[], options?: ErrorOptions);
|
|
14
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A file refused by the virus check: ClamAV reported it as infected (`VIRUS_FOUND`), or the scan gave no verdict
|
|
3
|
+
* (`SCAN_FAILED`). Thrown by `scanVirus` with `failClosed: true` and by `uploadTempImage`.
|
|
4
|
+
*
|
|
5
|
+
* The message is fixed and names neither the file path nor the signature. The detail is in `code`, `viruses` and,
|
|
6
|
+
* for a failed scan, `cause`.
|
|
7
|
+
*/
|
|
8
|
+
export class VirusScanError extends Error {
|
|
9
|
+
code;
|
|
10
|
+
/** virus names reported by ClamAV; empty for `SCAN_FAILED` */
|
|
11
|
+
viruses;
|
|
12
|
+
constructor(code, viruses = [], options) {
|
|
13
|
+
super(code === 'VIRUS_FOUND' ? 'Infected file refused' : 'Virus scan did not complete', options);
|
|
14
|
+
this.name = 'VirusScanError';
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.viruses = viruses;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=VirusScanError.mjs.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export interface IPdfStripOptions {
|
|
2
|
+
/** JavaScript actions, document scripts and XFA forms. Default `true` */
|
|
3
|
+
javaScript?: boolean | undefined;
|
|
4
|
+
/** the other actions: launch a program, send or import form data, open another file, play media. Default `true` */
|
|
5
|
+
actions?: boolean | undefined;
|
|
6
|
+
/** attached and associated files, file attachment annotations, portfolios. Default `true` */
|
|
7
|
+
embeddedFiles?: boolean | undefined;
|
|
8
|
+
/** screen, movie, sound, 3D and rich media annotations. Default `true` */
|
|
9
|
+
multimedia?: boolean | undefined;
|
|
10
|
+
/** document information, XMP, private application data, thumbnails. Default `true` */
|
|
11
|
+
metadata?: boolean | undefined;
|
|
12
|
+
/** actions that open a web address. Default `false` */
|
|
13
|
+
links?: boolean | undefined;
|
|
14
|
+
/** form fields, with the values they show. Default `false` */
|
|
15
|
+
forms?: boolean | undefined;
|
|
16
|
+
/** comments, highlights, stamps and the other markup annotations. Default `false` */
|
|
17
|
+
annotations?: boolean | undefined;
|
|
18
|
+
}
|
|
19
|
+
export interface IReEncodePdfOptions {
|
|
20
|
+
/** what to remove */
|
|
21
|
+
strip?: IPdfStripOptions | undefined;
|
|
22
|
+
/** milliseconds the work on one file may take, waiting for a turn not counted. Default 30 000 */
|
|
23
|
+
timeout?: number | undefined;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Write a PDF again, in place, from its parsed objects, and remove what `options.strip` asks for. Text stays text: the
|
|
27
|
+
* pages are not turned into images. The new file holds no earlier version, no unused object and no encryption.
|
|
28
|
+
*
|
|
29
|
+
* Each call runs in a worker thread of its own, so the event loop is not blocked and the memory MuPDF takes is released
|
|
30
|
+
* with the thread. A thread costs some tens of milliseconds and megabytes: at most four run at once in a process (one per
|
|
31
|
+
* core on a smaller machine), further calls wait. A thread that takes longer than `timeout` is ended.
|
|
32
|
+
*
|
|
33
|
+
* Needs the optional peer `mupdf`, loaded in the worker.
|
|
34
|
+
*
|
|
35
|
+
* @param filePath
|
|
36
|
+
* @param options without `strip`, scripts, actions, embedded files, multimedia and metadata are removed; `timeout` is
|
|
37
|
+
* 30 000 ms
|
|
38
|
+
* @returns `filePath`
|
|
39
|
+
* @throws TypeError for an invalid option, before the file is read. `Error` for a password protected file, a file without
|
|
40
|
+
* pages, one MuPDF cannot read or one that takes too long; the file is then left as it was. A write that fails (a full
|
|
41
|
+
* disk) can leave it partly written
|
|
42
|
+
*/
|
|
43
|
+
export declare function reEncodePdf(filePath: string, options?: IReEncodePdfOptions): Promise<string>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createLimiter } from "../private/lib/createLimiter.mjs";
|
|
2
|
+
import { resolvePdfOptions } from "../private/pdf/resolvePdfOptions.mjs";
|
|
3
|
+
import { runInWorker } from "../private/pdf/runInWorker.mjs";
|
|
4
|
+
import { promises as fs } from 'fs';
|
|
5
|
+
import { availableParallelism } from 'os';
|
|
6
|
+
/* eslint-enable sonarjs/no-redundant-optional -- end of the exactOptionalPropertyTypes block above */
|
|
7
|
+
// a thread running MuPDF takes tens of megabytes: further calls wait for their turn
|
|
8
|
+
const inTurn = createLimiter(Math.min(4, availableParallelism()));
|
|
9
|
+
/**
|
|
10
|
+
* Write a PDF again, in place, from its parsed objects, and remove what `options.strip` asks for. Text stays text: the
|
|
11
|
+
* pages are not turned into images. The new file holds no earlier version, no unused object and no encryption.
|
|
12
|
+
*
|
|
13
|
+
* Each call runs in a worker thread of its own, so the event loop is not blocked and the memory MuPDF takes is released
|
|
14
|
+
* with the thread. A thread costs some tens of milliseconds and megabytes: at most four run at once in a process (one per
|
|
15
|
+
* core on a smaller machine), further calls wait. A thread that takes longer than `timeout` is ended.
|
|
16
|
+
*
|
|
17
|
+
* Needs the optional peer `mupdf`, loaded in the worker.
|
|
18
|
+
*
|
|
19
|
+
* @param filePath
|
|
20
|
+
* @param options without `strip`, scripts, actions, embedded files, multimedia and metadata are removed; `timeout` is
|
|
21
|
+
* 30 000 ms
|
|
22
|
+
* @returns `filePath`
|
|
23
|
+
* @throws TypeError for an invalid option, before the file is read. `Error` for a password protected file, a file without
|
|
24
|
+
* pages, one MuPDF cannot read or one that takes too long; the file is then left as it was. A write that fails (a full
|
|
25
|
+
* disk) can leave it partly written
|
|
26
|
+
*/
|
|
27
|
+
export async function reEncodePdf(filePath, options = {}) {
|
|
28
|
+
const { strip, timeout } = resolvePdfOptions(options);
|
|
29
|
+
return await inTurn(async () => {
|
|
30
|
+
// eslint-disable-next-line security/detect-non-literal-fs-filename -- the path is the caller's own, nothing here builds it from request data
|
|
31
|
+
const bytes = await fs.readFile(filePath);
|
|
32
|
+
const script = new URL('../private/pdf/rewritePdfWorker.mjs', import.meta.url);
|
|
33
|
+
const rewritten = (await runInWorker(script, { bytes, strip }, timeout));
|
|
34
|
+
// eslint-disable-next-line security/detect-non-literal-fs-filename -- same path as the read above
|
|
35
|
+
await fs.writeFile(filePath, rewritten);
|
|
36
|
+
return filePath;
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=reEncodePdf.mjs.map
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import NodeClam from 'clamscan';
|
|
2
2
|
/**********
|
|
3
3
|
* Call inside koa initialization
|
|
4
|
+
*
|
|
5
|
+
* `options` override the defaults key by key, `clamdscan` included. With `clamdscan.host` or `clamdscan.port` and no
|
|
6
|
+
* `clamdscan.socket`, the default unix socket is dropped.
|
|
4
7
|
*/
|
|
5
8
|
export declare function initClamScan(options?: Partial<NodeClam.Options>): Promise<NodeClam>;
|
|
6
9
|
/**
|
|
@@ -12,9 +15,9 @@ export declare function initClamScan(options?: Partial<NodeClam.Options>): Promi
|
|
|
12
15
|
* and is never initialised in the suite, making captureMessage a silent no-op there).
|
|
13
16
|
* `alerted` is set inside the branch precisely so the branch itself is observable.
|
|
14
17
|
*
|
|
15
|
-
* scanVirus
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
+
* Without `failClosed`, scanVirus does not throw on detection or on a failed scan —
|
|
19
|
+
* blocking is then the caller's decision. Note `scanned: false` means the scan did
|
|
20
|
+
* not complete: treat it as unknown, not as clean.
|
|
18
21
|
*/
|
|
19
22
|
export interface IScanVirusResult {
|
|
20
23
|
/** true when ClamAV reported the file as infected */
|
|
@@ -23,7 +26,17 @@ export interface IScanVirusResult {
|
|
|
23
26
|
viruses: string[];
|
|
24
27
|
/** true when the infected-file alert was raised */
|
|
25
28
|
alerted: boolean;
|
|
26
|
-
/** false when the scan
|
|
29
|
+
/** false when the scan errored or gave no verdict — the result is unknown, NOT clean */
|
|
27
30
|
scanned: boolean;
|
|
28
31
|
}
|
|
29
|
-
export
|
|
32
|
+
export interface IScanVirusOptions {
|
|
33
|
+
/** throw a `VirusScanError` for an infected file and for a scan that did not complete */
|
|
34
|
+
failClosed?: boolean | undefined;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Scan a file with ClamAV. The file is left where it is: removing a refused file is the caller's job.
|
|
38
|
+
*
|
|
39
|
+
* @param filePath
|
|
40
|
+
* @param options `failClosed: true` rejects with a `VirusScanError` unless ClamAV said the file is clean
|
|
41
|
+
*/
|
|
42
|
+
export declare function scanVirus(filePath: string, options?: IScanVirusOptions): Promise<IScanVirusResult>;
|
package/dist/files/scanVirus.mjs
CHANGED
|
@@ -1,25 +1,33 @@
|
|
|
1
1
|
import * as Sentry from "../private/lib/sentry.mjs";
|
|
2
2
|
import NodeClam from 'clamscan';
|
|
3
|
+
import { VirusScanError } from './VirusScanError.mjs';
|
|
3
4
|
let clamScanInstance = null;
|
|
5
|
+
// A new object on every call: NodeClam deletes the nested keys from the options it is given.
|
|
6
|
+
function mergeClamOptions(options = {}) {
|
|
7
|
+
const { clamdscan: overrides, ...rest } = options;
|
|
8
|
+
const clamdscan = {
|
|
9
|
+
socket: '/var/run/clamav/clamd.ctl',
|
|
10
|
+
timeout: 60000,
|
|
11
|
+
multiscan: true,
|
|
12
|
+
localFallback: false,
|
|
13
|
+
...overrides
|
|
14
|
+
};
|
|
15
|
+
// NodeClam prefers the socket to host and port: a caller that names a TCP daemon must not keep the default socket
|
|
16
|
+
if ((overrides?.host || overrides?.port) && overrides.socket === undefined) {
|
|
17
|
+
clamdscan.socket = false;
|
|
18
|
+
}
|
|
19
|
+
return { removeInfected: true, quarantineInfected: false, debugMode: false, ...rest, clamdscan };
|
|
20
|
+
}
|
|
4
21
|
/**********
|
|
5
22
|
* Call inside koa initialization
|
|
23
|
+
*
|
|
24
|
+
* `options` override the defaults key by key, `clamdscan` included. With `clamdscan.host` or `clamdscan.port` and no
|
|
25
|
+
* `clamdscan.socket`, the default unix socket is dropped.
|
|
6
26
|
*/
|
|
7
27
|
export async function initClamScan(options) {
|
|
8
|
-
const defaultOptions = {
|
|
9
|
-
removeInfected: true,
|
|
10
|
-
quarantineInfected: false,
|
|
11
|
-
clamdscan: {
|
|
12
|
-
socket: '/var/run/clamav/clamd.ctl',
|
|
13
|
-
timeout: 60000,
|
|
14
|
-
multiscan: true,
|
|
15
|
-
localFallback: false
|
|
16
|
-
},
|
|
17
|
-
debugMode: false
|
|
18
|
-
};
|
|
19
28
|
console.info('[ClamScan] init...');
|
|
20
29
|
try {
|
|
21
|
-
|
|
22
|
-
clamScanInstance = await new NodeClam().init(mergedOptions);
|
|
30
|
+
clamScanInstance = await new NodeClam().init(mergeClamOptions(options));
|
|
23
31
|
console.info('[ClamScan] OK: ClamScan has been initialized successfully');
|
|
24
32
|
return clamScanInstance;
|
|
25
33
|
}
|
|
@@ -29,29 +37,55 @@ export async function initClamScan(options) {
|
|
|
29
37
|
throw e;
|
|
30
38
|
}
|
|
31
39
|
}
|
|
32
|
-
|
|
40
|
+
/* eslint-enable sonarjs/no-redundant-optional -- end of the exactOptionalPropertyTypes block above */
|
|
41
|
+
// NodeClam resolves with `isInfected: null` after a timeout or an unreadable reply: that is not a verdict
|
|
42
|
+
async function readVerdict(scanner, filePath) {
|
|
43
|
+
const { isInfected, viruses } = await scanner.scanFile(filePath);
|
|
44
|
+
if (typeof isInfected !== 'boolean') {
|
|
45
|
+
throw new Error('ClamAV returned no verdict');
|
|
46
|
+
}
|
|
47
|
+
return { isInfected, viruses };
|
|
48
|
+
}
|
|
49
|
+
function alertInfected(filePath, viruses) {
|
|
50
|
+
Sentry.withScope((scope) => {
|
|
51
|
+
scope.setTag('file', filePath);
|
|
52
|
+
scope.setContext('viruses', { list: viruses, count: viruses.length });
|
|
53
|
+
scope.setLevel('warning');
|
|
54
|
+
Sentry.captureMessage(`Infected file detected: ${filePath}`);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Scan a file with ClamAV. The file is left where it is: removing a refused file is the caller's job.
|
|
59
|
+
*
|
|
60
|
+
* @param filePath
|
|
61
|
+
* @param options `failClosed: true` rejects with a `VirusScanError` unless ClamAV said the file is clean
|
|
62
|
+
*/
|
|
63
|
+
export async function scanVirus(filePath, options = {}) {
|
|
33
64
|
if (!clamScanInstance) {
|
|
34
65
|
throw new Error('ClamScan has not been initialized. Call initClamScan first.');
|
|
35
66
|
}
|
|
67
|
+
let result;
|
|
36
68
|
try {
|
|
37
|
-
const { isInfected, viruses } = await clamScanInstance
|
|
69
|
+
const { isInfected, viruses } = await readVerdict(clamScanInstance, filePath);
|
|
38
70
|
let alerted = false;
|
|
39
71
|
if (isInfected) {
|
|
40
72
|
alerted = true;
|
|
41
|
-
|
|
42
|
-
scope.setTag('file', filePath);
|
|
43
|
-
scope.setContext('viruses', { list: viruses, count: viruses.length });
|
|
44
|
-
scope.setLevel('warning');
|
|
45
|
-
Sentry.captureMessage(`Infected file detected: ${filePath}`);
|
|
46
|
-
});
|
|
73
|
+
alertInfected(filePath, viruses);
|
|
47
74
|
}
|
|
48
|
-
|
|
75
|
+
result = { isInfected, viruses, alerted, scanned: true };
|
|
49
76
|
}
|
|
50
77
|
catch (e) {
|
|
51
78
|
Sentry.captureException(e, {
|
|
52
79
|
extra: { detail: `Error while scanning the file ${filePath}` }
|
|
53
80
|
});
|
|
81
|
+
if (options.failClosed) {
|
|
82
|
+
throw new VirusScanError('SCAN_FAILED', [], { cause: e });
|
|
83
|
+
}
|
|
54
84
|
return { isInfected: false, viruses: [], alerted: false, scanned: false };
|
|
55
85
|
}
|
|
86
|
+
if (options.failClosed && result.isInfected) {
|
|
87
|
+
throw new VirusScanError('VIRUS_FOUND', result.viruses);
|
|
88
|
+
}
|
|
89
|
+
return result;
|
|
56
90
|
}
|
|
57
91
|
//# sourceMappingURL=scanVirus.mjs.map
|
|
@@ -1,3 +1,15 @@
|
|
|
1
1
|
import { IFileUpload } from '../koa/IFileUpload.mjs';
|
|
2
2
|
import { IStoreFile } from './fileConst.mjs';
|
|
3
|
-
export
|
|
3
|
+
export interface IStoreUploadOptions {
|
|
4
|
+
/** folder the file is written to; it must exist. Default `/tmp` */
|
|
5
|
+
dir?: string | undefined;
|
|
6
|
+
/** limit of the upload in bytes. Default 5 MiB */
|
|
7
|
+
maxFileSize?: number | undefined;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Write an upload to a temp file with a random name. An upload over the size limit, or one that fails, is removed.
|
|
11
|
+
*
|
|
12
|
+
* @param upload
|
|
13
|
+
* @param options the folder and the byte limit, or the byte limit alone
|
|
14
|
+
*/
|
|
15
|
+
export declare function storeUploadAsTemp(upload: Promise<IFileUpload>, options?: number | IStoreUploadOptions): Promise<IStoreFile>;
|
|
@@ -1,22 +1,40 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { createWriteStream, unlink } from 'node:fs';
|
|
3
|
+
import { assertWholeNumber } from "../private/files/assertWholeNumber.mjs";
|
|
3
4
|
import path from 'path';
|
|
4
5
|
import { UPLOAD_TEMP_DIRECTORY_URL } from './fileConst.mjs';
|
|
5
6
|
// Simulating __dirname using process.cwd()
|
|
6
7
|
// const __dirname = process.cwd()
|
|
7
8
|
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB size limit
|
|
8
|
-
|
|
9
|
+
/* eslint-enable sonarjs/no-redundant-optional -- end of the exactOptionalPropertyTypes block above */
|
|
10
|
+
// A number is the older form of the second argument, the byte limit: it is used as it is, as before
|
|
11
|
+
function resolveStoreOptions(options) {
|
|
12
|
+
if (typeof options === 'number') {
|
|
13
|
+
return { dir: UPLOAD_TEMP_DIRECTORY_URL, maxFileSize: options };
|
|
14
|
+
}
|
|
15
|
+
const { dir = UPLOAD_TEMP_DIRECTORY_URL, maxFileSize = MAX_FILE_SIZE } = options;
|
|
16
|
+
assertWholeNumber(maxFileSize, 'maxFileSize');
|
|
17
|
+
return { dir, maxFileSize };
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Write an upload to a temp file with a random name. An upload over the size limit, or one that fails, is removed.
|
|
21
|
+
*
|
|
22
|
+
* @param upload
|
|
23
|
+
* @param options the folder and the byte limit, or the byte limit alone
|
|
24
|
+
*/
|
|
25
|
+
export async function storeUploadAsTemp(upload, options = {}) {
|
|
26
|
+
const { dir, maxFileSize } = resolveStoreOptions(options);
|
|
9
27
|
const { createReadStream, filename } = await upload;
|
|
10
28
|
const stream = createReadStream();
|
|
11
29
|
const storedFileName = randomUUID() + path.extname(filename).toLowerCase();
|
|
12
|
-
const storedFileUrl =
|
|
30
|
+
const storedFileUrl = path.join(dir, storedFileName);
|
|
13
31
|
let fileSize = 0; // Variable to track file size
|
|
14
32
|
let sizeExceeded = false; // Set once the limit is passed; read by the 'close' handler
|
|
15
33
|
let writeFailure = null; // Set on a write/stream error; read by the 'close' handler
|
|
16
34
|
// Store the file in the filesystem.
|
|
17
35
|
await new Promise((resolve, reject) => {
|
|
18
36
|
// Create a stream to which the upload will be written.
|
|
19
|
-
// eslint-disable-next-line security/detect-non-literal-fs-filename -- the name is a server-side UUID
|
|
37
|
+
// eslint-disable-next-line security/detect-non-literal-fs-filename -- the folder is the caller's own, the name is a server-side UUID; only the extension comes from the client, and path.extname never returns a path separator
|
|
20
38
|
const writeStream = createWriteStream(storedFileUrl);
|
|
21
39
|
// Check file size during streaming.
|
|
22
40
|
// Only flags and stops the stream — the rejection is issued from the 'close'
|
|
@@ -1,8 +1,26 @@
|
|
|
1
1
|
import { IFileUpload } from '../koa/IFileUpload.mjs';
|
|
2
2
|
import { IUploadTemp } from './IUploadTemp.mjs';
|
|
3
|
+
export interface IUploadTempImageOptions {
|
|
4
|
+
/** folder of the temp files. It must exist and ClamAV must be able to read it. Default `/tmp` */
|
|
5
|
+
tempDir?: string | undefined;
|
|
6
|
+
/** limit of the upload in bytes. Default 5 MiB */
|
|
7
|
+
maxFileSize?: number | undefined;
|
|
8
|
+
/** limit of width × height of the image (sharp `limitInputPixels`). Default: the limit of sharp */
|
|
9
|
+
maxPixels?: number | undefined;
|
|
10
|
+
/** WebP encoder of the result. Default `{ lossless: true, quality: 100 }` */
|
|
11
|
+
webp?: {
|
|
12
|
+
lossless?: boolean | undefined;
|
|
13
|
+
quality?: number | undefined;
|
|
14
|
+
} | undefined;
|
|
15
|
+
}
|
|
3
16
|
/**
|
|
4
17
|
* Validate file extension, Mime Type, scan with ClamAV, re encode to webp, rename final file
|
|
18
|
+
*
|
|
19
|
+
* Fails closed: the upload is refused unless ClamAV said it is clean. A refused upload leaves no file behind.
|
|
5
20
|
* @todo log uploaded file
|
|
6
21
|
* @param img
|
|
22
|
+
* @param options
|
|
23
|
+
* @throws VirusScanError when the file is infected or the scan did not complete, `Error('Error storing image')` for
|
|
24
|
+
* any other refusal, `TypeError` for an invalid option
|
|
7
25
|
*/
|
|
8
|
-
export declare function uploadTempImage(img: Promise<IFileUpload
|
|
26
|
+
export declare function uploadTempImage(img: Promise<IFileUpload>, options?: IUploadTempImageOptions): Promise<IUploadTemp>;
|
|
@@ -1,25 +1,38 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { assertWholeNumber } from "../private/files/assertWholeNumber.mjs";
|
|
2
|
+
import { reEncode } from "../private/files/reEncode.mjs";
|
|
3
|
+
import { replaceExtension } from "../private/files/replaceExtension.mjs";
|
|
4
|
+
import * as Sentry from "../private/lib/sentry.mjs";
|
|
5
|
+
import { promises as fs } from 'fs';
|
|
2
6
|
import { scanVirus } from './scanVirus.mjs';
|
|
3
7
|
import { storeUploadAsTemp } from './storeUploadAsTemp.mjs';
|
|
4
8
|
import { validateJpgPngExtension } from './validateJpgPngExtension.mjs';
|
|
5
9
|
import { validateJpgPngMimeType } from './validateMimeTypeImages.mjs';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
import { VirusScanError } from './VirusScanError.mjs';
|
|
11
|
+
/* eslint-enable sonarjs/no-redundant-optional -- end of the exactOptionalPropertyTypes block above */
|
|
12
|
+
// A wrong option is a programming error: it is thrown as it is, before the upload is read
|
|
13
|
+
function assertOptions({ maxFileSize, maxPixels, webp }) {
|
|
14
|
+
if (maxFileSize !== undefined)
|
|
15
|
+
assertWholeNumber(maxFileSize, 'maxFileSize');
|
|
16
|
+
if (maxPixels !== undefined)
|
|
17
|
+
assertWholeNumber(maxPixels, 'maxPixels');
|
|
18
|
+
if (webp?.quality !== undefined)
|
|
19
|
+
assertWholeNumber(webp.quality, 'webp.quality', 100);
|
|
20
|
+
}
|
|
21
|
+
// The upload and the WebP written beside it. Best effort: a failed clean-up must not hide why the upload was refused
|
|
22
|
+
async function removeTempFiles(filePath) {
|
|
23
|
+
for (const file of [filePath, replaceExtension(filePath, 'webp')]) {
|
|
24
|
+
await fs.rm(file, { force: true }).catch((e) => Sentry.captureException(e));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
// Everything done to the stored upload (steps as in Readme.md). Whatever refuses it, no temp file stays behind
|
|
28
|
+
async function checkAndReEncode({ fileName, filePath }, { maxPixels, webp }) {
|
|
14
29
|
try {
|
|
15
|
-
// Step 1 - Readme.md
|
|
16
|
-
const { fileName, filePath } = await storeUploadAsTemp(img);
|
|
17
30
|
await validateJpgPngExtension(fileName, filePath);
|
|
18
31
|
await validateJpgPngMimeType(filePath);
|
|
19
32
|
// step 2
|
|
20
|
-
await scanVirus(filePath);
|
|
33
|
+
await scanVirus(filePath, { failClosed: true });
|
|
21
34
|
// step 3
|
|
22
|
-
|
|
35
|
+
return await reEncode(filePath, 'webp', webp?.quality, { webpLossless: webp?.lossless, maxPixels });
|
|
23
36
|
// await checkForNSFW(filePath)
|
|
24
37
|
// step 4 - safe file name (ok)
|
|
25
38
|
// step 5 - rate limit (ok)
|
|
@@ -29,14 +42,36 @@ export async function uploadTempImage(img) {
|
|
|
29
42
|
// user's IP address, filename, and timestamp,
|
|
30
43
|
// @todo await logUpload('team', uId, originalFilename, fileName)
|
|
31
44
|
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
await removeTempFiles(filePath);
|
|
47
|
+
throw e;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Validate file extension, Mime Type, scan with ClamAV, re encode to webp, rename final file
|
|
52
|
+
*
|
|
53
|
+
* Fails closed: the upload is refused unless ClamAV said it is clean. A refused upload leaves no file behind.
|
|
54
|
+
* @todo log uploaded file
|
|
55
|
+
* @param img
|
|
56
|
+
* @param options
|
|
57
|
+
* @throws VirusScanError when the file is infected or the scan did not complete, `Error('Error storing image')` for
|
|
58
|
+
* any other refusal, `TypeError` for an invalid option
|
|
59
|
+
*/
|
|
60
|
+
export async function uploadTempImage(img, options = {}) {
|
|
61
|
+
assertOptions(options);
|
|
62
|
+
const { tempDir, maxFileSize } = options;
|
|
63
|
+
try {
|
|
64
|
+
// Step 1 - Readme.md
|
|
65
|
+
const stored = await storeUploadAsTemp(img, { dir: tempDir, maxFileSize });
|
|
66
|
+
const tempFile = await checkAndReEncode(stored, options);
|
|
67
|
+
return { ext: 'webp', tempFile };
|
|
68
|
+
}
|
|
32
69
|
catch (e) {
|
|
33
70
|
// error for file handling
|
|
34
71
|
console.error('Error storing image:', e);
|
|
72
|
+
if (e instanceof VirusScanError)
|
|
73
|
+
throw e;
|
|
35
74
|
throw new Error('Error storing image');
|
|
36
75
|
}
|
|
37
|
-
return {
|
|
38
|
-
ext: 'webp',
|
|
39
|
-
tempFile: storedTempFile
|
|
40
|
-
};
|
|
41
76
|
}
|
|
42
77
|
//# sourceMappingURL=uploadTempImage.mjs.map
|
|
@@ -1,8 +1,19 @@
|
|
|
1
1
|
import { IFileUpload } from '../koa/IFileUpload.mjs';
|
|
2
2
|
import { IUploadTemp } from './IUploadTemp.mjs';
|
|
3
|
+
import { type IReEncodePdfOptions } from './reEncodePdf.mjs';
|
|
4
|
+
export interface IUploadTempPdfOptions {
|
|
5
|
+
/** write the PDF again without its active content: `true`, or the options of `reEncodePdf`. Default `false` */
|
|
6
|
+
reEncode?: boolean | IReEncodePdfOptions | undefined;
|
|
7
|
+
}
|
|
3
8
|
/**
|
|
4
|
-
* Validate file extension, Mime Type, scan with ClamAV, re encode to
|
|
5
|
-
*
|
|
9
|
+
* Validate file extension, Mime Type, scan with ClamAV, and re encode when asked to. Without `reEncode` the file returned
|
|
10
|
+
* holds the bytes that were uploaded
|
|
11
|
+
*
|
|
12
|
+
* Fails closed: the upload is refused unless ClamAV said it is clean. A refused upload leaves no file behind.
|
|
13
|
+
* @todo log uploaded file
|
|
6
14
|
* @param pdf
|
|
15
|
+
* @param options
|
|
16
|
+
* @throws VirusScanError when the file is infected or the scan did not complete, `Error('Error storing pdf')` for any
|
|
17
|
+
* other refusal, `TypeError` for an invalid option
|
|
7
18
|
*/
|
|
8
|
-
export declare function uploadTempPdf(pdf: Promise<IFileUpload
|
|
19
|
+
export declare function uploadTempPdf(pdf: Promise<IFileUpload>, options?: IUploadTempPdfOptions): Promise<IUploadTemp>;
|
|
@@ -1,25 +1,37 @@
|
|
|
1
|
+
import * as Sentry from "../private/lib/sentry.mjs";
|
|
2
|
+
import { assertKnownKeys, resolvePdfOptions } from "../private/pdf/resolvePdfOptions.mjs";
|
|
3
|
+
import { promises as fs } from 'fs';
|
|
4
|
+
import { reEncodePdf } from './reEncodePdf.mjs';
|
|
1
5
|
import { scanVirus } from './scanVirus.mjs';
|
|
2
6
|
import { storeUploadAsTemp } from './storeUploadAsTemp.mjs';
|
|
3
7
|
import { validateMimeTypePdf } from './validateMimeTypePdf.mjs';
|
|
4
8
|
import { validatePdfExtension } from './validatePdfExtension.mjs';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
import { VirusScanError } from './VirusScanError.mjs';
|
|
10
|
+
/* eslint-enable sonarjs/no-redundant-optional -- end of the exactOptionalPropertyTypes block above */
|
|
11
|
+
// The options of the re-encode, undefined when none is asked for. A wrong one is thrown before the upload is read
|
|
12
|
+
function resolveReEncode(options) {
|
|
13
|
+
assertKnownKeys(options, ['reEncode'], 'options');
|
|
14
|
+
const { reEncode = false } = options;
|
|
15
|
+
if (reEncode === false)
|
|
16
|
+
return undefined;
|
|
17
|
+
const wanted = reEncode === true ? {} : reEncode;
|
|
18
|
+
resolvePdfOptions(wanted);
|
|
19
|
+
return wanted;
|
|
20
|
+
}
|
|
21
|
+
// Everything done to the stored upload (steps as in Readme.md). Whatever refuses it, the temp file does not stay behind
|
|
22
|
+
async function checkStoredPdf({ fileName, filePath }, reEncode) {
|
|
13
23
|
try {
|
|
14
|
-
// Step 1 - Readme.md
|
|
15
|
-
const { fileName, filePath } = await storeUploadAsTemp(pdf);
|
|
16
24
|
await validatePdfExtension(fileName, filePath);
|
|
17
25
|
await validateMimeTypePdf(filePath);
|
|
18
26
|
// step 2
|
|
19
|
-
await scanVirus(filePath);
|
|
27
|
+
await scanVirus(filePath, { failClosed: true });
|
|
20
28
|
// step 3
|
|
21
|
-
|
|
22
|
-
|
|
29
|
+
if (reEncode !== undefined) {
|
|
30
|
+
await reEncodePdf(filePath, reEncode);
|
|
31
|
+
// the scanner may not see inside an encrypted file: what the re-encode opened is scanned too
|
|
32
|
+
await scanVirus(filePath, { failClosed: true });
|
|
33
|
+
}
|
|
34
|
+
return filePath;
|
|
23
35
|
// await checkForNSFW(filePath)
|
|
24
36
|
// step 4 - safe file name (ok)
|
|
25
37
|
// step 5 - rate limit (ok)
|
|
@@ -29,14 +41,37 @@ export async function uploadTempPdf(pdf) {
|
|
|
29
41
|
// user's IP address, filename, and timestamp,
|
|
30
42
|
// @todo await logUpload('team', uId, originalFilename, fileName)
|
|
31
43
|
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
// best effort: a failed clean-up must not hide why the upload was refused
|
|
46
|
+
await fs.rm(filePath, { force: true }).catch((error) => Sentry.captureException(error));
|
|
47
|
+
throw e;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Validate file extension, Mime Type, scan with ClamAV, and re encode when asked to. Without `reEncode` the file returned
|
|
52
|
+
* holds the bytes that were uploaded
|
|
53
|
+
*
|
|
54
|
+
* Fails closed: the upload is refused unless ClamAV said it is clean. A refused upload leaves no file behind.
|
|
55
|
+
* @todo log uploaded file
|
|
56
|
+
* @param pdf
|
|
57
|
+
* @param options
|
|
58
|
+
* @throws VirusScanError when the file is infected or the scan did not complete, `Error('Error storing pdf')` for any
|
|
59
|
+
* other refusal, `TypeError` for an invalid option
|
|
60
|
+
*/
|
|
61
|
+
export async function uploadTempPdf(pdf, options = {}) {
|
|
62
|
+
const reEncode = resolveReEncode(options);
|
|
63
|
+
try {
|
|
64
|
+
// Step 1 - Readme.md
|
|
65
|
+
const stored = await storeUploadAsTemp(pdf);
|
|
66
|
+
const tempFile = await checkStoredPdf(stored, reEncode);
|
|
67
|
+
return { ext: 'pdf', tempFile };
|
|
68
|
+
}
|
|
32
69
|
catch (e) {
|
|
33
70
|
// error for file handling
|
|
34
71
|
console.error('Error storing pdf:', e);
|
|
72
|
+
if (e instanceof VirusScanError)
|
|
73
|
+
throw e;
|
|
35
74
|
throw new Error('Error storing pdf');
|
|
36
75
|
}
|
|
37
|
-
return {
|
|
38
|
-
ext: 'pdf',
|
|
39
|
-
tempFile: storedTempFile
|
|
40
|
-
};
|
|
41
76
|
}
|
|
42
77
|
//# sourceMappingURL=uploadTempPdf.mjs.map
|