@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
|
@@ -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
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One address of a message. A key with no value is absent, never `undefined`: that is how the SocketLabs SDK's
|
|
3
|
+
* `EmailAddress` held it, and a client double that checks `'friendlyName' in from` keeps working.
|
|
4
|
+
*/
|
|
5
|
+
export interface ISocketLabsAddress {
|
|
6
|
+
emailAddress?: string;
|
|
7
|
+
friendlyName?: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The message `createSocketLabsSender` hands to `client.send`: the data fields of the SDK's `BasicMessage`, with the
|
|
11
|
+
* same names, so a double written against the SDK reads it unchanged and an SDK `SocketLabsClient` can still send it.
|
|
12
|
+
* A field with no value is absent.
|
|
13
|
+
*/
|
|
14
|
+
export interface ISocketLabsBasicMessage {
|
|
15
|
+
messageType: 'basic';
|
|
16
|
+
from: ISocketLabsAddress;
|
|
17
|
+
to: ISocketLabsAddress[];
|
|
18
|
+
subject?: string;
|
|
19
|
+
textBody?: string;
|
|
20
|
+
htmlBody?: string;
|
|
21
|
+
messageId?: string;
|
|
22
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a send came to, before it is turned into a resolution or a rejection. `name` is the SocketLabs result name
|
|
3
|
+
* (`'Success'`, `'Timeout'`, `'InvalidAuthentication'`, ...); it is absent when the outcome could not be classified,
|
|
4
|
+
* which the sender reports as `'UnknownError'`.
|
|
5
|
+
*/
|
|
6
|
+
export interface ISocketLabsOutcome {
|
|
7
|
+
name?: string;
|
|
8
|
+
transactionReceipt?: string;
|
|
9
|
+
addressResults?: Record<string, unknown>[];
|
|
10
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ISocketLabsOutcome } from './ISocketLabsOutcome.mjs';
|
|
2
|
+
/**
|
|
3
|
+
* What the built-in client rejects with when a send fails. It has the fields the SocketLabs SDK's `SendResponse` had
|
|
4
|
+
* (`result.name`, `transactionReceipt`, `addressResults`) and is an `Error`, so a report made from it has a stack and a
|
|
5
|
+
* title. The text holds the result name and nothing else: no key, no recipient, no body. `addressResults` can hold
|
|
6
|
+
* recipients and `transactionReceipt` is the server's receipt, so the object is not for logging as it is.
|
|
7
|
+
*/
|
|
8
|
+
export declare class SocketLabsSendError extends Error {
|
|
9
|
+
readonly name = "SocketLabsSendError";
|
|
10
|
+
/** Absent, as a key, when the failure could not be classified. `declare` so no empty field is emitted. */
|
|
11
|
+
readonly result?: {
|
|
12
|
+
name: string;
|
|
13
|
+
};
|
|
14
|
+
readonly transactionReceipt: string | null;
|
|
15
|
+
readonly addressResults: Record<string, unknown>[] | null;
|
|
16
|
+
constructor(outcome: ISocketLabsOutcome);
|
|
17
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const UNKNOWN_ERROR = 'UnknownError';
|
|
2
|
+
/**
|
|
3
|
+
* What the built-in client rejects with when a send fails. It has the fields the SocketLabs SDK's `SendResponse` had
|
|
4
|
+
* (`result.name`, `transactionReceipt`, `addressResults`) and is an `Error`, so a report made from it has a stack and a
|
|
5
|
+
* title. The text holds the result name and nothing else: no key, no recipient, no body. `addressResults` can hold
|
|
6
|
+
* recipients and `transactionReceipt` is the server's receipt, so the object is not for logging as it is.
|
|
7
|
+
*/
|
|
8
|
+
export class SocketLabsSendError extends Error {
|
|
9
|
+
name = 'SocketLabsSendError';
|
|
10
|
+
transactionReceipt;
|
|
11
|
+
addressResults;
|
|
12
|
+
constructor(outcome) {
|
|
13
|
+
super(`SocketLabs send failed: ${outcome.name ?? UNKNOWN_ERROR}`);
|
|
14
|
+
if (outcome.name !== undefined) {
|
|
15
|
+
this.result = { name: outcome.name };
|
|
16
|
+
}
|
|
17
|
+
this.transactionReceipt = outcome.transactionReceipt ?? null;
|
|
18
|
+
this.addressResults = outcome.addressResults ?? null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=SocketLabsSendError.mjs.map
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ISocketLabsClient } from "../../email/ISocketLabsClient.mjs";
|
|
2
|
+
export interface ISocketLabsClientOptions {
|
|
3
|
+
serverId: number;
|
|
4
|
+
apiKey: string;
|
|
5
|
+
/** Seconds one request may take, from the start of the call to the last byte of the answer. Finite and above 0. */
|
|
6
|
+
requestTimeout: number;
|
|
7
|
+
/** Retries after the first attempt, from 0 to 5. */
|
|
8
|
+
numberOfRetries: number;
|
|
9
|
+
/** Tests only: where to post. The sender never passes it, so the endpoint cannot be changed from outside. */
|
|
10
|
+
endpointUrl?: string;
|
|
11
|
+
/** Tests only: the wait between attempts. */
|
|
12
|
+
sleep?: (ms: number) => Promise<unknown>;
|
|
13
|
+
/** Tests only: the randomness of the back-off, a function returning a number from 0 up to 1. */
|
|
14
|
+
random?: () => number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The wait before retry number `retry` (0 for the first), the SDK's `promise-retry` setting: `minTimeout` 1000, factor 2,
|
|
18
|
+
* randomised by a factor from 1 up to 2, `maxTimeout` 10000. So 1-2 s, 2-4 s, 4-8 s, 8-10 s, then 10 s.
|
|
19
|
+
*/
|
|
20
|
+
export declare function backoffMs(retry: number, random: () => number): number;
|
|
21
|
+
/**
|
|
22
|
+
* A client for the SocketLabs Injection API built on `fetch`, replacing the `@socketlabs/email` SDK. `send` takes the message
|
|
23
|
+
* `buildBasicMessage` makes and resolves with the outcome when SocketLabs accepted it. Every failure rejects with a
|
|
24
|
+
* `SocketLabsSendError` whose `result.name` is the code `createSocketLabsSender` reports; a failure that cannot be classified has no `result`.
|
|
25
|
+
*/
|
|
26
|
+
export declare function createSocketLabsClient(options: ISocketLabsClientOptions): ISocketLabsClient;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { sleepMs } from "../../lib/sleepMs.mjs";
|
|
2
|
+
import { buildInjectionRequest, credentialsOutcome, messageOutcome } from './socketLabsRequest.mjs';
|
|
3
|
+
import { parseInjectionResponse } from './socketLabsResponse.mjs';
|
|
4
|
+
import { SocketLabsSendError } from './SocketLabsSendError.mjs';
|
|
5
|
+
/** The SocketLabs Injection API, the only host the client talks to. Fixed: nothing a caller passes can change it. */
|
|
6
|
+
const INJECTION_ENDPOINT = 'https://inject.socketlabs.com/api/v1/email';
|
|
7
|
+
/**
|
|
8
|
+
* The statuses retried, besides a timeout: the four the SDK retried (500, 502, 503, 504) and 429, which is retried on purpose, a deviation
|
|
9
|
+
* from the SDK. A 429 means the request was rejected, so a retry cannot deliver the mail twice. No other 4xx is retried, and no network
|
|
10
|
+
* error either: that request may have reached SocketLabs, so a retry could send the mail twice. `Retry-After` is not read.
|
|
11
|
+
*/
|
|
12
|
+
const RETRY_STATUSES = new Set([429, 500, 502, 503, 504]);
|
|
13
|
+
const BACKOFF_MIN_MS = 1000;
|
|
14
|
+
const BACKOFF_MAX_MS = 10_000;
|
|
15
|
+
/** Longest delay a Node timer can hold: a larger one makes it fire after 1 ms. */
|
|
16
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
17
|
+
/**
|
|
18
|
+
* The wait before retry number `retry` (0 for the first), the SDK's `promise-retry` setting: `minTimeout` 1000, factor 2,
|
|
19
|
+
* randomised by a factor from 1 up to 2, `maxTimeout` 10000. So 1-2 s, 2-4 s, 4-8 s, 8-10 s, then 10 s.
|
|
20
|
+
*/
|
|
21
|
+
export function backoffMs(retry, random) {
|
|
22
|
+
return Math.min((random() + 1) * BACKOFF_MIN_MS * 2 ** retry, BACKOFF_MAX_MS);
|
|
23
|
+
}
|
|
24
|
+
async function post(url, request, timeoutMs) {
|
|
25
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
26
|
+
try {
|
|
27
|
+
// redirect 'error': the key and the mail go to the endpoint above and nowhere else
|
|
28
|
+
const response = await fetch(url, {
|
|
29
|
+
method: 'POST',
|
|
30
|
+
headers: request.headers,
|
|
31
|
+
body: request.body,
|
|
32
|
+
signal,
|
|
33
|
+
redirect: 'error'
|
|
34
|
+
});
|
|
35
|
+
return { kind: 'http', status: response.status, text: await response.text() };
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// The error itself is dropped on purpose: it comes from the HTTP stack and nothing in it is worth the risk of carrying a header value
|
|
39
|
+
return signal.aborted ? { kind: 'timeout' } : { kind: 'network' };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const isRetryable = (attempt) => attempt.kind === 'timeout' || (attempt.kind === 'http' && RETRY_STATUSES.has(attempt.status));
|
|
43
|
+
function outcomeOf(attempt) {
|
|
44
|
+
if (attempt.kind === 'timeout') {
|
|
45
|
+
return { name: 'Timeout' };
|
|
46
|
+
}
|
|
47
|
+
return attempt.kind === 'network' ? {} : parseInjectionResponse(attempt.status, attempt.text);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A client for the SocketLabs Injection API built on `fetch`, replacing the `@socketlabs/email` SDK. `send` takes the message
|
|
51
|
+
* `buildBasicMessage` makes and resolves with the outcome when SocketLabs accepted it. Every failure rejects with a
|
|
52
|
+
* `SocketLabsSendError` whose `result.name` is the code `createSocketLabsSender` reports; a failure that cannot be classified has no `result`.
|
|
53
|
+
*/
|
|
54
|
+
export function createSocketLabsClient(options) {
|
|
55
|
+
const { serverId, apiKey, numberOfRetries } = options;
|
|
56
|
+
const url = options.endpointUrl ?? INJECTION_ENDPOINT;
|
|
57
|
+
const sleep = options.sleep ?? sleepMs;
|
|
58
|
+
const random = options.random ?? Math.random;
|
|
59
|
+
const timeoutMs = Math.min(Math.ceil(options.requestTimeout * 1000), MAX_TIMEOUT_MS);
|
|
60
|
+
return {
|
|
61
|
+
async send(message) {
|
|
62
|
+
const invalid = credentialsOutcome(serverId, apiKey) ?? messageOutcome(message);
|
|
63
|
+
if (invalid) {
|
|
64
|
+
throw new SocketLabsSendError(invalid);
|
|
65
|
+
}
|
|
66
|
+
const request = buildInjectionRequest(serverId, apiKey, message);
|
|
67
|
+
let attempt = await post(url, request, timeoutMs);
|
|
68
|
+
for (let retry = 0; retry < numberOfRetries && isRetryable(attempt); retry++) {
|
|
69
|
+
await sleep(backoffMs(retry, random));
|
|
70
|
+
attempt = await post(url, request, timeoutMs);
|
|
71
|
+
}
|
|
72
|
+
const outcome = outcomeOf(attempt);
|
|
73
|
+
if (outcome.name === 'Success') {
|
|
74
|
+
return outcome;
|
|
75
|
+
}
|
|
76
|
+
throw new SocketLabsSendError(outcome);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=socketLabsClient.mjs.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ISocketLabsMessage } from "../../email/ISocketLabsMessage.mjs";
|
|
2
|
+
import type { ISocketLabsBasicMessage } from './ISocketLabsBasicMessage.mjs';
|
|
3
|
+
/**
|
|
4
|
+
* Turns what the caller of `createSocketLabsSender` passes into the message `client.send` receives. Fields are read in the
|
|
5
|
+
* order from, from name, subject, text, html, to, message id, so when two are wrong the first of them is the one reported.
|
|
6
|
+
*
|
|
7
|
+
* @throws TypeError a field that is set but is not a string.
|
|
8
|
+
*/
|
|
9
|
+
export declare function buildBasicMessage(message: ISocketLabsMessage): ISocketLabsBasicMessage;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { withDefined } from './withDefined.mjs';
|
|
2
|
+
/**
|
|
3
|
+
* An absent value (`undefined`, `null`, `''`, `0`, `false`) gives `undefined`, a string gives itself and anything else
|
|
4
|
+
* throws. The text names the field, never the value.
|
|
5
|
+
*/
|
|
6
|
+
function asText(value, label) {
|
|
7
|
+
if (!value) {
|
|
8
|
+
return undefined;
|
|
9
|
+
}
|
|
10
|
+
if (typeof value !== 'string') {
|
|
11
|
+
throw new TypeError(`Invalid ${label}, type of 'string' was expected.`);
|
|
12
|
+
}
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Turns what the caller of `createSocketLabsSender` passes into the message `client.send` receives. Fields are read in the
|
|
17
|
+
* order from, from name, subject, text, html, to, message id, so when two are wrong the first of them is the one reported.
|
|
18
|
+
*
|
|
19
|
+
* @throws TypeError a field that is set but is not a string.
|
|
20
|
+
*/
|
|
21
|
+
export function buildBasicMessage(message) {
|
|
22
|
+
const emailAddress = asText(message.from, 'from address');
|
|
23
|
+
const friendlyName = asText(message.fromName, 'from name');
|
|
24
|
+
const subject = asText(message.subject, 'subject');
|
|
25
|
+
const textBody = asText(message.text, 'text body');
|
|
26
|
+
const htmlBody = asText(message.html, 'html body');
|
|
27
|
+
const recipient = asText(message.to, 'to address');
|
|
28
|
+
const messageId = asText(message.messageId, 'message id');
|
|
29
|
+
return {
|
|
30
|
+
messageType: 'basic',
|
|
31
|
+
from: withDefined({ emailAddress, friendlyName }),
|
|
32
|
+
to: recipient === undefined ? [] : [{ emailAddress: recipient }],
|
|
33
|
+
...withDefined({ subject, textBody, htmlBody, messageId })
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=socketLabsMessage.mjs.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ISocketLabsBasicMessage } from './ISocketLabsBasicMessage.mjs';
|
|
2
|
+
import type { ISocketLabsOutcome } from './ISocketLabsOutcome.mjs';
|
|
3
|
+
/** `undefined` when `serverId` is a positive integer and `apiKey` a non-empty string, else the SDK's `AuthenticationValidationFailed`. */
|
|
4
|
+
export declare function credentialsOutcome(serverId: unknown, apiKey: unknown): ISocketLabsOutcome | undefined;
|
|
5
|
+
/**
|
|
6
|
+
* `undefined` when the message can be sent, else the outcome the SDK's validator gave, checked in its order: subject, from
|
|
7
|
+
* address, body, recipients. Nothing is sent for a message that fails here.
|
|
8
|
+
*/
|
|
9
|
+
export declare function messageOutcome(message: ISocketLabsBasicMessage): ISocketLabsOutcome | undefined;
|
|
10
|
+
export interface IInjectionRequest {
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
body: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* What the SDK's `createRequest` sends. A key of the form `<20>.<40>` travels as `Authorization: Bearer <key>` and stays out of
|
|
16
|
+
* the body; any other key travels as `apiKey` in the body and there is no `Authorization` header. The body is
|
|
17
|
+
* `{ serverId, messages: [message] }`. The key is never put anywhere else.
|
|
18
|
+
*/
|
|
19
|
+
export declare function buildInjectionRequest(serverId: number, apiKey: string, message: ISocketLabsBasicMessage): IInjectionRequest;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** Longest address the SDK accepts, in characters. */
|
|
2
|
+
const MAX_ADDRESS_LENGTH = 320;
|
|
3
|
+
/** A key of the form `<20 characters>.<40 characters>` is sent as a bearer token; any other key goes in the body. */
|
|
4
|
+
const STRUCTURED_KEY_LENGTH = 61;
|
|
5
|
+
const STRUCTURED_KEY_SEPARATOR_AT = 20;
|
|
6
|
+
const USER_AGENT = `@axiumine/koa-utils (nodejs ${process.version})`;
|
|
7
|
+
/** The same checks as the SDK's `EmailAddress.isValid`: one `@` with something on both sides, none of `,` `;` or a space. */
|
|
8
|
+
function isValidAddress(address) {
|
|
9
|
+
if (address === undefined || address.length > MAX_ADDRESS_LENGTH) {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
const parts = address.split('@');
|
|
13
|
+
return parts.length === 2 && parts.every((part) => part.trim().length > 0) && !/[ ,;]/.test(address);
|
|
14
|
+
}
|
|
15
|
+
/** `undefined` when `serverId` is a positive integer and `apiKey` a non-empty string, else the SDK's `AuthenticationValidationFailed`. */
|
|
16
|
+
export function credentialsOutcome(serverId, apiKey) {
|
|
17
|
+
const valid = typeof apiKey === 'string' && apiKey !== '' && typeof serverId === 'number' && Number.isInteger(serverId) && serverId > 0;
|
|
18
|
+
return valid ? undefined : { name: 'AuthenticationValidationFailed' };
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* `undefined` when the message can be sent, else the outcome the SDK's validator gave, checked in its order: subject, from
|
|
22
|
+
* address, body, recipients. Nothing is sent for a message that fails here.
|
|
23
|
+
*/
|
|
24
|
+
export function messageOutcome(message) {
|
|
25
|
+
const { from, to } = message;
|
|
26
|
+
if (!message.subject) {
|
|
27
|
+
return { name: 'MessageValidationEmptySubject' };
|
|
28
|
+
}
|
|
29
|
+
if (!from.emailAddress) {
|
|
30
|
+
return { name: 'EmailAddressValidationMissingFrom' };
|
|
31
|
+
}
|
|
32
|
+
if (!isValidAddress(from.emailAddress)) {
|
|
33
|
+
return { name: 'EmailAddressValidationInvalidFrom' };
|
|
34
|
+
}
|
|
35
|
+
if (!message.htmlBody && !message.textBody) {
|
|
36
|
+
return { name: 'MessageValidationEmptyMessage' };
|
|
37
|
+
}
|
|
38
|
+
if (to.length === 0) {
|
|
39
|
+
return { name: 'RecipientValidationNoneInMessage' };
|
|
40
|
+
}
|
|
41
|
+
const invalid = to.filter((address) => !isValidAddress(address.emailAddress));
|
|
42
|
+
if (invalid.length > 0) {
|
|
43
|
+
return {
|
|
44
|
+
name: 'RecipientValidationInvalidRecipients',
|
|
45
|
+
addressResults: invalid.map((address) => ({
|
|
46
|
+
emailAddress: address.emailAddress,
|
|
47
|
+
accepted: false,
|
|
48
|
+
errorCode: 'InvalidAddress'
|
|
49
|
+
}))
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
// `undefined` values drop out of JSON.stringify, which leaves the keys of the SDK's `BasicMessage.toJSON`, in its order
|
|
55
|
+
const addressJson = ({ emailAddress, friendlyName }) => ({ emailAddress, friendlyName });
|
|
56
|
+
/** One message as the Injection API takes it. */
|
|
57
|
+
function messageJson(message) {
|
|
58
|
+
return {
|
|
59
|
+
subject: message.subject,
|
|
60
|
+
htmlBody: message.htmlBody,
|
|
61
|
+
textBody: message.textBody,
|
|
62
|
+
messageId: message.messageId,
|
|
63
|
+
from: addressJson(message.from),
|
|
64
|
+
to: message.to.map(addressJson)
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
const isStructuredApiKey = (apiKey) => apiKey.length === STRUCTURED_KEY_LENGTH && apiKey.indexOf('.') === STRUCTURED_KEY_SEPARATOR_AT;
|
|
68
|
+
/**
|
|
69
|
+
* What the SDK's `createRequest` sends. A key of the form `<20>.<40>` travels as `Authorization: Bearer <key>` and stays out of
|
|
70
|
+
* the body; any other key travels as `apiKey` in the body and there is no `Authorization` header. The body is
|
|
71
|
+
* `{ serverId, messages: [message] }`. The key is never put anywhere else.
|
|
72
|
+
*/
|
|
73
|
+
export function buildInjectionRequest(serverId, apiKey, message) {
|
|
74
|
+
const bearer = isStructuredApiKey(apiKey);
|
|
75
|
+
const headers = {
|
|
76
|
+
'Content-Type': 'application/json;charset=utf-8',
|
|
77
|
+
Accept: 'application/json',
|
|
78
|
+
'User-Agent': USER_AGENT
|
|
79
|
+
};
|
|
80
|
+
if (bearer) {
|
|
81
|
+
headers['Authorization'] = `Bearer ${apiKey}`;
|
|
82
|
+
}
|
|
83
|
+
const messages = [messageJson(message)];
|
|
84
|
+
return { headers, body: JSON.stringify(bearer ? { serverId, messages } : { apiKey, serverId, messages }) };
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=socketLabsRequest.mjs.map
|