@axiumine/koa-utils 9.2.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 +33 -6
- package/dist/email/ISocketLabsClient.d.mts +4 -3
- package/dist/email/ISocketLabsMessage.d.mts +1 -1
- package/dist/email/ISocketLabsSendResult.d.mts +3 -3
- package/dist/email/ISocketLabsSenderOptions.d.mts +9 -8
- package/dist/email/SocketLabsLib.d.mts +2 -15
- package/dist/email/SocketLabsLib.mjs +4 -19
- package/dist/email/createSocketLabsSender.d.mts +9 -8
- package/dist/email/createSocketLabsSender.mjs +16 -22
- 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/email/ISocketLabsBasicMessage.d.mts +22 -0
- package/dist/private/email/ISocketLabsBasicMessage.mjs +2 -0
- package/dist/private/email/ISocketLabsOutcome.d.mts +10 -0
- package/dist/private/email/ISocketLabsOutcome.mjs +2 -0
- package/dist/private/email/SocketLabsSendError.d.mts +17 -0
- package/dist/private/email/SocketLabsSendError.mjs +21 -0
- package/dist/private/email/socketLabsClient.d.mts +26 -0
- package/dist/private/email/socketLabsClient.mjs +80 -0
- package/dist/private/email/socketLabsMessage.d.mts +9 -0
- package/dist/private/email/socketLabsMessage.mjs +36 -0
- package/dist/private/email/socketLabsRequest.d.mts +19 -0
- package/dist/private/email/socketLabsRequest.mjs +86 -0
- package/dist/private/email/socketLabsResponse.d.mts +10 -0
- package/dist/private/email/socketLabsResponse.mjs +49 -0
- package/dist/private/email/withDefined.d.mts +4 -0
- package/dist/private/email/withDefined.mjs +5 -0
- 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 +62 -19
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,11 +30,13 @@ 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
|
-
| `@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
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` |
|
|
39
41
|
| `clamscan` | `files/scanVirus`, `files/uploadTempImage`, `files/uploadTempPdf` |
|
|
40
42
|
| `file-type` | `files/validateMimeType`, `files/validateMimeTypeImages`, `files/validateJpgPngMimeType`, `files/validateMimeTypeGlb`, `files/uploadTempImage`, `files/uploadTempPdf` — loaded lazily, at first call |
|
|
@@ -50,7 +52,7 @@ yarn add @node-rs/bcrypt graphql mongoose redis
|
|
|
50
52
|
|
|
51
53
|
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.
|
|
52
54
|
|
|
53
|
-
`email/createSocketLabsSender` needs
|
|
55
|
+
`email/createSocketLabsSender` needs nothing installed: it builds a function that sends one mail you composed, with your own `serverId` and `apiKey`, and returns `{ ok: true }` or `{ ok: false, code }` instead of throwing on a rejected send. It posts to the SocketLabs Injection API with Node's built-in `fetch` (a timeout, and retries on a timeout or a 429, 500, 502, 503 or 504 answer), reads no environment variable and loads no Sentry, no dotenv and no `graphql`; its four type files (`email/ISocketLabsSenderOptions`, `ISocketLabsMessage`, `ISocketLabsSendResult`, `ISocketLabsClient`) need nothing installed either. `email/SocketLabsLib` sends through it and adds the copy, the HTML template, the environment variables and the Sentry report. `@socketlabs/email` is not a peer of this package any more and nothing here imports it: remove it from your project if this package was the only reason you installed it (it depends on `axios` 0.21, which has published advisories). Node's `fetch` does not read `HTTP_PROXY` / `HTTPS_PROXY` on its own: behind a proxy, start Node with `NODE_USE_ENV_PROXY=1`.
|
|
54
56
|
|
|
55
57
|
The PostgreSQL kit under `lib/PostgreSQL/{error,parse,pool,url,counter,tx,guard,role,clock,lock}/` reaches no peer either, `pg` included: `lib/PostgreSQL/pool/createPool` takes the `pg` module you imported as its `driver` argument and talks to it through structural types, so you install `pg` yourself for your own code and the kit never imports it. It holds the pool factory (URL allow-list, `SHOW timezone` must answer `UTC`, one connect deadline, a listener for idle-client errors), `lib/PostgreSQL/tx/withTx` (one transaction wrapper: closed `BEGIN`, `SET LOCAL lock_timeout`, a bounded retry on deadlocks and serialisation failures, and an error factory you pass in), string parsers for `date`, `time`, `timestamptz`, `int8`, `uuid` and arrays of them that never build a `Date`, closed-reason `DbParseError`, `DbConnectError` and `DbTxError`, SQLSTATE readers, `lib/PostgreSQL/error/mapDbError` (turns any driver failure into an error of your own family through a constraint table you pass in, and logs a closed reason, never the driver text), `lib/PostgreSQL/guard/assertAffected` and `guardVersion` (say why an update matched no row), `lib/PostgreSQL/role/assertRole` (a boot check that the connected database role has no dangerous attribute, owns nothing, has no unlisted membership and holds the grants you list, with a closed-reason `RoleAssertionError`), `lib/PostgreSQL/clock/createDbClock` (the server time read once per transaction, which a write transaction may read only after a lock), `lib/PostgreSQL/lock/createLockOrderTracker` (the order of the locks of a transaction from a spec you give, checked before each statement) with the small parts for writing your own lock helpers (the kit exports no lock clause), and `databaseUrlReason`, a strict check for a database URL. See [docs/code/lib-postgres.md](https://github.com/Axiumine/koa-utils/blob/main/docs/code/lib-postgres.md).
|
|
56
58
|
|
|
@@ -209,11 +211,36 @@ import { initClamScan } from '@axiumine/koa-utils/files/scanVirus'
|
|
|
209
211
|
import { uploadTempImage } from '@axiumine/koa-utils/files/uploadTempImage'
|
|
210
212
|
import { uploadTempPdf } from '@axiumine/koa-utils/files/uploadTempPdf'
|
|
211
213
|
|
|
212
|
-
await initClamScan() // once at boot
|
|
214
|
+
await initClamScan() // once at boot; TCP daemon: initClamScan({ clamdscan: { host, port } })
|
|
213
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 })
|
|
214
241
|
```
|
|
215
242
|
|
|
216
|
-
|
|
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).
|
|
217
244
|
|
|
218
245
|
### Email
|
|
219
246
|
|
|
@@ -326,7 +353,7 @@ yarn check:static # every static gate: caps, lint, typecheck (src, scripts, spec
|
|
|
326
353
|
yarn clean
|
|
327
354
|
```
|
|
328
355
|
|
|
329
|
-
Source files are `.mts`. Imports use `.mjs` extension explicitly (NodeNext). Path aliases (`@lib/*`, `@throw/*`, `@models/*`, `@context/*`, `@stypes/*`, `@private/*`, `@email/*`, `@dataSources/*`) are rewritten to relative paths in emitted
|
|
356
|
+
Source files are `.mts`. Imports use `.mjs` extension explicitly (NodeNext). Path aliases (`@lib/*`, `@throw/*`, `@models/*`, `@context/*`, `@stypes/*`, `@private/*`, `@email/*`, `@dataSources/*`) are rewritten to relative paths in the emitted `.mjs` / `.d.mts` right after `tsc`, by `scripts/rewrite-path-aliases.mts`, which reads the alias map from the tsconfig `paths`. The build is a plain `tsc` plus that step: it does not patch the compiler or need a transformer plugin.
|
|
330
357
|
|
|
331
358
|
Adding a new public symbol requires both:
|
|
332
359
|
1. Creating `src/<area>/<Name>.mts`
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The part of a SocketLabs client that {@link createSocketLabsSender} calls.
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* The part of a SocketLabs client that {@link createSocketLabsSender} calls. The client the sender builds fits it, so does
|
|
3
|
+
* the `SocketLabsClient` of the SocketLabs Node SDK if you still use it, and so does a test double such as
|
|
4
|
+
* `{ send: async () => ({}) }`. A client resolves when the mail was accepted and rejects when it was not; the sender turns
|
|
5
|
+
* the rejection into `{ ok: false, code }`. It is declared here so `.d.mts` files that name this interface need no package.
|
|
5
6
|
*/
|
|
6
7
|
export interface ISocketLabsClient {
|
|
7
8
|
send(message: unknown): Promise<unknown>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* One mail handed to the function that {@link createSocketLabsSender} returns. A single recipient, no attachments,
|
|
3
|
-
* no copies. `text` and `html` are both optional here, but
|
|
3
|
+
* no copies. `text` and `html` are both optional here, but a message with neither is not sent: the send fails with the code `MessageValidationEmptyMessage`.
|
|
4
4
|
*/
|
|
5
5
|
export interface ISocketLabsMessage {
|
|
6
6
|
/** Sender address. */
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* What the function from {@link createSocketLabsSender} resolves to. A failed send does not reject: it resolves to
|
|
3
|
-
* `{ ok: false, code }`, where `code` is
|
|
4
|
-
* `'Warning'`, ...) or `'UnknownError'` when the rejection carries none. The code is all that is exposed: never
|
|
5
|
-
*
|
|
3
|
+
* `{ ok: false, code }`, where `code` is a SocketLabs result name (`'Timeout'`, `'InvalidAuthentication'`,
|
|
4
|
+
* `'Warning'`, ...) or `'UnknownError'` when the rejection carries none. The code is all that is exposed: never a
|
|
5
|
+
* response message, the per-recipient results or the raw rejection, which can hold recipients and a receipt.
|
|
6
6
|
*/
|
|
7
7
|
export type ISocketLabsSendResult = {
|
|
8
8
|
ok: true;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ISocketLabsClient } from './ISocketLabsClient.mjs';
|
|
2
2
|
/**
|
|
3
3
|
* Options of {@link createSocketLabsSender}. Nothing is read from the environment: you pass the credentials.
|
|
4
|
-
* There is no `endpointUrl` and no proxy option on purpose, so the sender can only talk to the
|
|
4
|
+
* There is no `endpointUrl` and no proxy option on purpose, so the sender can only talk to the SocketLabs Injection API.
|
|
5
5
|
*/
|
|
6
6
|
export interface ISocketLabsSenderOptions {
|
|
7
7
|
/** SocketLabs server id. Not validated here. Ignored when `client` is given. */
|
|
@@ -9,21 +9,22 @@ export interface ISocketLabsSenderOptions {
|
|
|
9
9
|
/** SocketLabs injection API key. Not validated here, never put in an error text. Ignored when `client` is given. */
|
|
10
10
|
apiKey: string;
|
|
11
11
|
/**
|
|
12
|
-
* Timeout of one HTTP request, in seconds
|
|
13
|
-
* sender is created. Unused when `client` is given.
|
|
12
|
+
* Timeout of one HTTP request, in seconds, counted from the start of the request to the last byte of the answer. Default 120.
|
|
13
|
+
* Must be finite and above 0, else `RangeError` when the sender is created. Unused when `client` is given.
|
|
14
14
|
*/
|
|
15
15
|
requestTimeout?: number | undefined;
|
|
16
16
|
/**
|
|
17
|
-
* How many times the
|
|
18
|
-
* the sender is created. Unused when `client` is given. Retries add to the time
|
|
19
|
-
* (up to `requestTimeout` x (1 + `numberOfRetries`) plus
|
|
17
|
+
* How many times the client retries a failed request: a timeout, or a 429, 500, 502, 503 or 504 answer (`Retry-After` is not read). Default 3. Must be an
|
|
18
|
+
* integer from 0 to 5, else `RangeError` when the sender is created. Unused when `client` is given. Retries add to the time
|
|
19
|
+
* one send can take (up to `requestTimeout` x (1 + `numberOfRetries`) plus a back-off of 1 to 10 s before each retry), and a
|
|
20
|
+
* retry after a timeout can deliver the mail twice.
|
|
20
21
|
*/
|
|
21
22
|
numberOfRetries?: number | undefined;
|
|
22
|
-
/** Use this client instead of
|
|
23
|
+
/** Use this client instead of the built-in one. For tests and for a client you configure yourself. */
|
|
23
24
|
client?: ISocketLabsClient | undefined;
|
|
24
25
|
/**
|
|
25
26
|
* Called with the raw rejection of a failed send, before the sender resolves to `{ ok: false, code }`. Default: nothing.
|
|
26
|
-
* The value is whatever the client rejected with (a `
|
|
27
|
+
* The value is whatever the client rejected with (the built-in client rejects with an `Error` that carries a `result`; another client may reject with a `SendResponse`, a `TypeError`, a string, `null`) and can
|
|
27
28
|
* hold recipients and a transaction receipt: do not log or serialise it as is. A throw from here rejects the sender's promise.
|
|
28
29
|
*/
|
|
29
30
|
onError?: ((rejection: unknown) => void) | undefined;
|
|
@@ -42,21 +42,8 @@ export declare class SocketLabsLib {
|
|
|
42
42
|
*/
|
|
43
43
|
sendEmailVerify(emailTo: string, hash: string, name?: string, linkBase?: string, linkPath?: string): Promise<boolean>;
|
|
44
44
|
/**
|
|
45
|
-
* A timed-out send is
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
statusCode: ECONNABORTED
|
|
49
|
-
Error in sending the email
|
|
50
|
-
SendResponse {
|
|
51
|
-
transactionReceipt: null,
|
|
52
|
-
addressResults: null,
|
|
53
|
-
result: {
|
|
54
|
-
name: 'Timeout',
|
|
55
|
-
value: 1,
|
|
56
|
-
message: 'A timeout occurred sending the message'
|
|
57
|
-
},
|
|
58
|
-
responseMessage: 'A timeout occurred sending the message'
|
|
59
|
-
}
|
|
45
|
+
* A timed-out send is retried by the client (`numberOfRetries: 3`, with a back-off of 1 to 10 s between tries). When the
|
|
46
|
+
* last try times out as well, the send is reported as failed and the template methods return `false`. This class adds no retry of its own.
|
|
60
47
|
*/
|
|
61
48
|
sendEmailChangeVerify(emailTo: string, hash: string, name?: string): Promise<boolean>;
|
|
62
49
|
sendWelcome(emailTo: string): Promise<boolean>;
|
|
@@ -5,9 +5,9 @@ import { confirmationLink, httpLinkBase } from "../private/email/messageParts.mj
|
|
|
5
5
|
import * as notice from "../private/email/noticeMessages.mjs";
|
|
6
6
|
import { orFalse } from "../private/email/orFalse.mjs";
|
|
7
7
|
import * as reset from "../private/email/resetMessages.mjs";
|
|
8
|
+
import { createSocketLabsClient } from "../private/email/socketLabsClient.mjs";
|
|
8
9
|
import { loadEnv } from "../private/lib/loadEnv.mjs";
|
|
9
10
|
import * as Sentry from "../private/lib/sentry.mjs";
|
|
10
|
-
import { SocketLabsClient } from '@socketlabs/email';
|
|
11
11
|
import { createSocketLabsSender } from './createSocketLabsSender.mjs';
|
|
12
12
|
loadEnv();
|
|
13
13
|
export class SocketLabsLib {
|
|
@@ -24,9 +24,7 @@ export class SocketLabsLib {
|
|
|
24
24
|
/* c8 ignore next -- env fallback '0' covered only when SOCKETLABS_SERVER_ID is unset */
|
|
25
25
|
const serverId = parseInt(process.env['SOCKETLABS_SERVER_ID'] || '0');
|
|
26
26
|
const apiKey = `${process.env['SOCKETLABS_SERVER_APIKEY']}`;
|
|
27
|
-
|
|
28
|
-
const Client = SocketLabsClient;
|
|
29
|
-
this.client = new Client(serverId, apiKey, { requestTimeout: 120, numberOfRetries: 3 });
|
|
27
|
+
this.client = createSocketLabsClient({ serverId, apiKey, requestTimeout: 120, numberOfRetries: 3 });
|
|
30
28
|
this.credentials = { serverId, apiKey };
|
|
31
29
|
this.platformName = `${process.env['PLATFORM_NAME']}`;
|
|
32
30
|
this.linkBase = `${process.env['APP_DOMAIN']}`;
|
|
@@ -105,21 +103,8 @@ export class SocketLabsLib {
|
|
|
105
103
|
}
|
|
106
104
|
*/
|
|
107
105
|
/**
|
|
108
|
-
* A timed-out send is
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
statusCode: ECONNABORTED
|
|
112
|
-
Error in sending the email
|
|
113
|
-
SendResponse {
|
|
114
|
-
transactionReceipt: null,
|
|
115
|
-
addressResults: null,
|
|
116
|
-
result: {
|
|
117
|
-
name: 'Timeout',
|
|
118
|
-
value: 1,
|
|
119
|
-
message: 'A timeout occurred sending the message'
|
|
120
|
-
},
|
|
121
|
-
responseMessage: 'A timeout occurred sending the message'
|
|
122
|
-
}
|
|
106
|
+
* A timed-out send is retried by the client (`numberOfRetries: 3`, with a back-off of 1 to 10 s between tries). When the
|
|
107
|
+
* last try times out as well, the send is reported as failed and the template methods return `false`. This class adds no retry of its own.
|
|
123
108
|
*/
|
|
124
109
|
async sendEmailChangeVerify(emailTo, hash, name = '') {
|
|
125
110
|
const link = `${httpLinkBase(this.linkBase)}/check/verify-change-email/${encodeURI(emailTo)}/${hash}`;
|
|
@@ -4,16 +4,17 @@ import type { ISocketLabsSendResult } from './ISocketLabsSendResult.mjs';
|
|
|
4
4
|
/**
|
|
5
5
|
* Builds a function that sends one mail through SocketLabs and reports the outcome as a value.
|
|
6
6
|
*
|
|
7
|
-
* The returned function builds
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* `
|
|
7
|
+
* The returned function builds the message (`buildBasicMessage`: the fields of the SocketLabs SDK's `BasicMessage`) and passes
|
|
8
|
+
* it to the client. On success it resolves to `{ ok: true }`. When the client rejects it calls `onError` with the raw
|
|
9
|
+
* rejection and resolves to `{ ok: false, code }`, where `code` is `rejection.result.name` if that is a string and
|
|
10
|
+
* `'UnknownError'` otherwise.
|
|
11
11
|
*
|
|
12
|
-
* There is no `try`/`catch`: a throw from a
|
|
13
|
-
* returned promise, and when
|
|
12
|
+
* There is no `try`/`catch`: a throw from the message builder (a field that is not a string), from `client.send` itself,
|
|
13
|
+
* and from `onError`, reject the returned promise, and when the builder throws `client.send` is never called.
|
|
14
14
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
15
|
+
* The built-in client posts with `fetch` to the SocketLabs Injection API and nothing else; it needs no package. The sender reads no
|
|
16
|
+
* environment variable and checks nothing about `serverId` and `apiKey` when it is created: a bad pair is rejected at
|
|
17
|
+
* send time and comes back as a code. Importing it loads no peer: no Sentry, no dotenv.
|
|
17
18
|
*
|
|
18
19
|
* @throws RangeError `requestTimeout` is not a finite number above 0, or `numberOfRetries` is not an integer from 0 to 5. The text never holds the API key.
|
|
19
20
|
*/
|
|
@@ -1,15 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createSocketLabsClient } from "../private/email/socketLabsClient.mjs";
|
|
2
|
+
import { buildBasicMessage } from "../private/email/socketLabsMessage.mjs";
|
|
2
3
|
/** Seconds, what `SocketLabsLib` has always passed. */
|
|
3
4
|
const DEFAULT_REQUEST_TIMEOUT = 120;
|
|
4
5
|
/** What `SocketLabsLib` has always passed. */
|
|
5
6
|
const DEFAULT_NUMBER_OF_RETRIES = 3;
|
|
6
7
|
/** Upper bound of `numberOfRetries`: every retry can run a full timeout, so a larger value outlives any sane job lease. */
|
|
7
8
|
const MAX_NUMBER_OF_RETRIES = 5;
|
|
8
|
-
/** The
|
|
9
|
+
/** The name a failure gets when nothing classifies it: the name the SocketLabs SDK's result enum gave it. */
|
|
9
10
|
const UNKNOWN_ERROR = 'UnknownError';
|
|
10
|
-
// The import is `any` (src/types/socketlabs-email.d.ts): one assertion each gives the two classes the shapes above
|
|
11
|
-
const Message = BasicMessage;
|
|
12
|
-
const Client = SocketLabsClient;
|
|
13
11
|
// Messages name the constraint, never the value: the options object also holds the API key
|
|
14
12
|
function assertRequestTimeout(requestTimeout) {
|
|
15
13
|
if (!Number.isFinite(requestTimeout) || requestTimeout <= 0) {
|
|
@@ -21,7 +19,7 @@ function assertNumberOfRetries(numberOfRetries) {
|
|
|
21
19
|
throw new RangeError(`numberOfRetries must be an integer from 0 to ${MAX_NUMBER_OF_RETRIES}`);
|
|
22
20
|
}
|
|
23
21
|
}
|
|
24
|
-
/** `rejection.result.name` when it is a string, else `'UnknownError'`. The
|
|
22
|
+
/** `rejection.result.name` when it is a string, else `'UnknownError'`. The built-in client rejects with an error whose `result` holds the name. */
|
|
25
23
|
const codeOf = (rejection) => {
|
|
26
24
|
const name = rejection?.result?.name;
|
|
27
25
|
return typeof name === 'string' ? name : UNKNOWN_ERROR;
|
|
@@ -29,16 +27,17 @@ const codeOf = (rejection) => {
|
|
|
29
27
|
/**
|
|
30
28
|
* Builds a function that sends one mail through SocketLabs and reports the outcome as a value.
|
|
31
29
|
*
|
|
32
|
-
* The returned function builds
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
* `
|
|
30
|
+
* The returned function builds the message (`buildBasicMessage`: the fields of the SocketLabs SDK's `BasicMessage`) and passes
|
|
31
|
+
* it to the client. On success it resolves to `{ ok: true }`. When the client rejects it calls `onError` with the raw
|
|
32
|
+
* rejection and resolves to `{ ok: false, code }`, where `code` is `rejection.result.name` if that is a string and
|
|
33
|
+
* `'UnknownError'` otherwise.
|
|
36
34
|
*
|
|
37
|
-
* There is no `try`/`catch`: a throw from a
|
|
38
|
-
* returned promise, and when
|
|
35
|
+
* There is no `try`/`catch`: a throw from the message builder (a field that is not a string), from `client.send` itself,
|
|
36
|
+
* and from `onError`, reject the returned promise, and when the builder throws `client.send` is never called.
|
|
39
37
|
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
38
|
+
* The built-in client posts with `fetch` to the SocketLabs Injection API and nothing else; it needs no package. The sender reads no
|
|
39
|
+
* environment variable and checks nothing about `serverId` and `apiKey` when it is created: a bad pair is rejected at
|
|
40
|
+
* send time and comes back as a code. Importing it loads no peer: no Sentry, no dotenv.
|
|
42
41
|
*
|
|
43
42
|
* @throws RangeError `requestTimeout` is not a finite number above 0, or `numberOfRetries` is not an integer from 0 to 5. The text never holds the API key.
|
|
44
43
|
*/
|
|
@@ -47,16 +46,11 @@ export function createSocketLabsSender(options) {
|
|
|
47
46
|
const numberOfRetries = options.numberOfRetries ?? DEFAULT_NUMBER_OF_RETRIES;
|
|
48
47
|
assertRequestTimeout(requestTimeout);
|
|
49
48
|
assertNumberOfRetries(numberOfRetries);
|
|
50
|
-
const client = options.client ??
|
|
49
|
+
const client = options.client ??
|
|
50
|
+
createSocketLabsClient({ serverId: options.serverId, apiKey: options.apiKey, requestTimeout, numberOfRetries });
|
|
51
51
|
const { onError } = options;
|
|
52
52
|
return async function sendSocketLabsMessage(message) {
|
|
53
|
-
const basicMessage =
|
|
54
|
-
basicMessage.setFromAddress(message.from, message.fromName);
|
|
55
|
-
basicMessage.setSubject(message.subject);
|
|
56
|
-
basicMessage.setTextBody(message.text);
|
|
57
|
-
basicMessage.setHtmlBody(message.html);
|
|
58
|
-
basicMessage.setTo(message.to);
|
|
59
|
-
basicMessage.setMessageId(message.messageId);
|
|
53
|
+
const basicMessage = buildBasicMessage(message);
|
|
60
54
|
return client.send(basicMessage).then(() => ({ ok: true }), (rejection) => {
|
|
61
55
|
onError?.(rejection);
|
|
62
56
|
return { ok: false, code: codeOf(rejection) };
|
|
@@ -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
|