@axiumine/koa-utils 9.1.1 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +6 -6
  2. package/dist/email/ISocketLabsClient.d.mts +4 -3
  3. package/dist/email/ISocketLabsMessage.d.mts +1 -1
  4. package/dist/email/ISocketLabsSendResult.d.mts +3 -3
  5. package/dist/email/ISocketLabsSenderOptions.d.mts +9 -8
  6. package/dist/email/SocketLabsLib.d.mts +2 -15
  7. package/dist/email/SocketLabsLib.mjs +4 -19
  8. package/dist/email/createSocketLabsSender.d.mts +9 -8
  9. package/dist/email/createSocketLabsSender.mjs +16 -22
  10. package/dist/files/GLB_POLICY_DEFAULTS.d.mts +49 -0
  11. package/dist/files/GLB_POLICY_DEFAULTS.mjs +45 -0
  12. package/dist/files/GLB_REJECT_CODES.d.mts +29 -0
  13. package/dist/files/GLB_REJECT_CODES.mjs +51 -0
  14. package/dist/files/IGlbContainer.d.mts +12 -0
  15. package/dist/files/IGlbContainer.mjs +2 -0
  16. package/dist/files/IGlbSanitiseResult.d.mts +56 -0
  17. package/dist/files/IGlbSanitiseResult.mjs +2 -0
  18. package/dist/files/checkGlbContainer.d.mts +11 -0
  19. package/dist/files/checkGlbContainer.mjs +68 -0
  20. package/dist/files/sanitiseGlb.d.mts +22 -0
  21. package/dist/files/sanitiseGlb.mjs +66 -0
  22. package/dist/files/sanitiseGlbFile.d.mts +16 -0
  23. package/dist/files/sanitiseGlbFile.mjs +36 -0
  24. package/dist/files/validateGlbExtension.d.mts +1 -0
  25. package/dist/files/validateGlbExtension.mjs +9 -0
  26. package/dist/files/validateMimeTypeGlb.d.mts +5 -0
  27. package/dist/files/validateMimeTypeGlb.mjs +9 -0
  28. package/dist/private/email/ISocketLabsBasicMessage.d.mts +22 -0
  29. package/dist/private/email/ISocketLabsBasicMessage.mjs +2 -0
  30. package/dist/private/email/ISocketLabsOutcome.d.mts +10 -0
  31. package/dist/private/email/ISocketLabsOutcome.mjs +2 -0
  32. package/dist/private/email/SocketLabsSendError.d.mts +17 -0
  33. package/dist/private/email/SocketLabsSendError.mjs +21 -0
  34. package/dist/private/email/socketLabsClient.d.mts +26 -0
  35. package/dist/private/email/socketLabsClient.mjs +80 -0
  36. package/dist/private/email/socketLabsMessage.d.mts +9 -0
  37. package/dist/private/email/socketLabsMessage.mjs +36 -0
  38. package/dist/private/email/socketLabsRequest.d.mts +19 -0
  39. package/dist/private/email/socketLabsRequest.mjs +86 -0
  40. package/dist/private/email/socketLabsResponse.d.mts +10 -0
  41. package/dist/private/email/socketLabsResponse.mjs +49 -0
  42. package/dist/private/email/withDefined.d.mts +4 -0
  43. package/dist/private/email/withDefined.mjs +5 -0
  44. package/dist/private/glb/IImageSize.d.mts +5 -0
  45. package/dist/private/glb/IImageSize.mjs +2 -0
  46. package/dist/private/glb/checkGlbCounts.d.mts +15 -0
  47. package/dist/private/glb/checkGlbCounts.mjs +53 -0
  48. package/dist/private/glb/checkGlbExtensions.d.mts +7 -0
  49. package/dist/private/glb/checkGlbExtensions.mjs +26 -0
  50. package/dist/private/glb/checkGlbGeometry.d.mts +9 -0
  51. package/dist/private/glb/checkGlbGeometry.mjs +56 -0
  52. package/dist/private/glb/checkGlbImages.d.mts +10 -0
  53. package/dist/private/glb/checkGlbImages.mjs +60 -0
  54. package/dist/private/glb/checkGlbUris.d.mts +7 -0
  55. package/dist/private/glb/checkGlbUris.mjs +25 -0
  56. package/dist/private/glb/glbExtensions.d.mts +7 -0
  57. package/dist/private/glb/glbExtensions.mjs +13 -0
  58. package/dist/private/glb/glbIo.d.mts +7 -0
  59. package/dist/private/glb/glbIo.mjs +16 -0
  60. package/dist/private/glb/glbReason.d.mts +7 -0
  61. package/dist/private/glb/glbReason.mjs +14 -0
  62. package/dist/private/glb/glbStats.d.mts +5 -0
  63. package/dist/private/glb/glbStats.mjs +24 -0
  64. package/dist/private/glb/inspectGlbJson.d.mts +8 -0
  65. package/dist/private/glb/inspectGlbJson.mjs +21 -0
  66. package/dist/private/glb/jsonAccess.d.mts +17 -0
  67. package/dist/private/glb/jsonAccess.mjs +24 -0
  68. package/dist/private/glb/parseGlbJson.d.mts +11 -0
  69. package/dist/private/glb/parseGlbJson.mjs +14 -0
  70. package/dist/private/glb/reEncodeImage.d.mts +13 -0
  71. package/dist/private/glb/reEncodeImage.mjs +24 -0
  72. package/dist/private/glb/readImageHeader.d.mts +25 -0
  73. package/dist/private/glb/readImageHeader.mjs +68 -0
  74. package/dist/private/glb/readJpegSize.d.mts +3 -0
  75. package/dist/private/glb/readJpegSize.mjs +27 -0
  76. package/dist/private/glb/readKtx2Size.d.mts +3 -0
  77. package/dist/private/glb/readKtx2Size.mjs +23 -0
  78. package/dist/private/glb/reencodeTextures.d.mts +9 -0
  79. package/dist/private/glb/reencodeTextures.mjs +34 -0
  80. package/dist/private/glb/resolveGlbPolicy.d.mts +6 -0
  81. package/dist/private/glb/resolveGlbPolicy.mjs +48 -0
  82. package/dist/private/glb/rewriteGlb.d.mts +16 -0
  83. package/dist/private/glb/rewriteGlb.mjs +49 -0
  84. package/dist/private/glb/stripExtras.d.mts +8 -0
  85. package/dist/private/glb/stripExtras.mjs +16 -0
  86. package/dist/private/glb/validateKhronos.d.mts +12 -0
  87. package/dist/private/glb/validateKhronos.mjs +32 -0
  88. package/dist/private/glb/verifyGlbOutput.d.mts +8 -0
  89. package/dist/private/glb/verifyGlbOutput.mjs +20 -0
  90. package/package.json +69 -16
@@ -0,0 +1,68 @@
1
+ import { tooLargeReason } from "../private/glb/glbReason.mjs";
2
+ import { GLB_POLICY_DEFAULTS } from './GLB_POLICY_DEFAULTS.mjs';
3
+ const MAGIC = 0x46_54_6c_67; // 'glTF' read as a little-endian uint32
4
+ const VERSION = 2;
5
+ const CHUNK_JSON = 0x4e_4f_53_4a; // 'JSON'
6
+ const CHUNK_BIN = 0x00_4e_49_42; // 'BIN\0'
7
+ const HEADER_BYTES = 12;
8
+ const CHUNK_HEADER_BYTES = 8;
9
+ const JSON_START = HEADER_BYTES + CHUNK_HEADER_BYTES;
10
+ const fail = (code, message) => ({ ok: false, reason: { code, message } });
11
+ function readBin(view, bytes, json, offset) {
12
+ if (offset + CHUNK_HEADER_BYTES > bytes.length) {
13
+ return fail('GLB_BAD_CHUNKS', 'bytes after the JSON chunk are too few for a BIN chunk');
14
+ }
15
+ if (view.getUint32(offset + 4, true) !== CHUNK_BIN) {
16
+ return fail('GLB_BAD_CHUNKS', 'the chunk after the JSON chunk is not a BIN chunk');
17
+ }
18
+ const start = offset + CHUNK_HEADER_BYTES;
19
+ const end = start + view.getUint32(offset, true);
20
+ if (end !== bytes.length) {
21
+ return fail('GLB_BAD_CHUNKS', 'the BIN chunk does not end where the file ends');
22
+ }
23
+ return { ok: true, json, bin: bytes.subarray(start, end) };
24
+ }
25
+ function readChunks(view, bytes, maxJsonBytes) {
26
+ if (view.getUint32(HEADER_BYTES + 4, true) !== CHUNK_JSON) {
27
+ return fail('GLB_BAD_CHUNKS', 'the first chunk is not a JSON chunk');
28
+ }
29
+ const jsonLength = view.getUint32(HEADER_BYTES, true);
30
+ if (jsonLength > maxJsonBytes) {
31
+ return fail('GLB_JSON_TOO_LARGE', `the JSON chunk has ${jsonLength} bytes, the limit is ${maxJsonBytes}`);
32
+ }
33
+ const jsonEnd = JSON_START + jsonLength;
34
+ if (jsonEnd > bytes.length) {
35
+ return fail('GLB_BAD_CHUNKS', 'the JSON chunk runs past the end of the file');
36
+ }
37
+ const json = bytes.subarray(JSON_START, jsonEnd);
38
+ return jsonEnd === bytes.length ? { ok: true, json, bin: null } : readBin(view, bytes, json, jsonEnd);
39
+ }
40
+ /**
41
+ * Check the container of a GLB without parsing its JSON: magic `glTF`, version 2, the length in the header against the
42
+ * real size, and the chunk layout (one JSON chunk, then at most one BIN chunk, nothing else). Cheap, so a caller can use
43
+ * it to turn a file away before any heavy work. Never throws on a hostile file.
44
+ *
45
+ * @param bytes the whole file
46
+ * @param limits `maxBytes` and `maxJsonBytes` of {@link IGlbPolicy}; the defaults apply to a field that is left out
47
+ */
48
+ export function checkGlbContainer(bytes, limits = {}) {
49
+ const maxBytes = limits.maxBytes ?? GLB_POLICY_DEFAULTS.maxBytes;
50
+ if (bytes.length > maxBytes) {
51
+ return { ok: false, reason: tooLargeReason(bytes.length, maxBytes) };
52
+ }
53
+ if (bytes.length < JSON_START) {
54
+ return fail('GLB_TRUNCATED', 'the file is too short to hold a header and a chunk');
55
+ }
56
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
57
+ if (view.getUint32(0, true) !== MAGIC) {
58
+ return fail('GLB_BAD_MAGIC', 'the file does not start with glTF');
59
+ }
60
+ if (view.getUint32(4, true) !== VERSION) {
61
+ return fail('GLB_BAD_VERSION', 'the GLB container version is not 2');
62
+ }
63
+ if (view.getUint32(8, true) !== bytes.length) {
64
+ return fail('GLB_LENGTH_MISMATCH', `the header says ${view.getUint32(8, true)} bytes, the file has ${bytes.length}`);
65
+ }
66
+ return readChunks(view, bytes, limits.maxJsonBytes ?? GLB_POLICY_DEFAULTS.maxJsonBytes);
67
+ }
68
+ //# sourceMappingURL=checkGlbContainer.mjs.map
@@ -0,0 +1,22 @@
1
+ import type { IGlbPolicy } from './GLB_POLICY_DEFAULTS.mjs';
2
+ import type { IGlbSanitiseResult } from './IGlbSanitiseResult.mjs';
3
+ /**
4
+ * Check a GLB for hostile content and write a clean copy. In this order, and the first stage that finds a problem ends it:
5
+ *
6
+ * 1. the container: `glTF` magic, version 2, declared length, chunk layout, size ({@link checkGlbContainer});
7
+ * 2. the JSON chunk parses as one JSON object;
8
+ * 3. the policy: no external or `data:` URI, only allowed extensions, counts, triangles, vertices, accessors (sparse
9
+ * ones too), buffer bytes, and the size of every texture read from its header before anything decodes it;
10
+ * 4. the Khronos glTF Validator: any error rejects;
11
+ * 5. the rewrite through glTF Transform: meshopt data is decoded (bad data rejects), `extras`, unknown extensions and
12
+ * unused data are dropped, PNG, JPEG and WebP textures are re-encoded with `sharp`, one embedded buffer is written;
13
+ * 6. the new file goes through the validator and the decoder once more.
14
+ *
15
+ * A hostile file never throws: it gives `{ accepted: false, reasons, stats }`. Only misuse throws (`TypeError` for
16
+ * input that is not a `Uint8Array` or for an invalid option, `RangeError` for an extension the sanitiser cannot rewrite).
17
+ * This function does not scan for viruses: call `scanVirus` on the stored file as well.
18
+ *
19
+ * @param input the whole GLB file
20
+ * @param options the limits and the extension list; see {@link IGlbPolicy}. Every field has a safe default.
21
+ */
22
+ export declare function sanitiseGlb(input: Uint8Array, options?: Partial<IGlbPolicy>): Promise<IGlbSanitiseResult>;
@@ -0,0 +1,66 @@
1
+ import { createGlbIo } from "../private/glb/glbIo.mjs";
2
+ import { emptyStats, rejected } from "../private/glb/glbStats.mjs";
3
+ import { inspectGlbJson } from "../private/glb/inspectGlbJson.mjs";
4
+ import { parseGlbJson } from "../private/glb/parseGlbJson.mjs";
5
+ import { resolveGlbPolicy } from "../private/glb/resolveGlbPolicy.mjs";
6
+ import { rewriteGlb } from "../private/glb/rewriteGlb.mjs";
7
+ import { validateKhronos } from "../private/glb/validateKhronos.mjs";
8
+ import { verifyGlbOutput } from "../private/glb/verifyGlbOutput.mjs";
9
+ import { checkGlbContainer } from './checkGlbContainer.mjs';
10
+ /**
11
+ * Check a GLB for hostile content and write a clean copy. In this order, and the first stage that finds a problem ends it:
12
+ *
13
+ * 1. the container: `glTF` magic, version 2, declared length, chunk layout, size ({@link checkGlbContainer});
14
+ * 2. the JSON chunk parses as one JSON object;
15
+ * 3. the policy: no external or `data:` URI, only allowed extensions, counts, triangles, vertices, accessors (sparse
16
+ * ones too), buffer bytes, and the size of every texture read from its header before anything decodes it;
17
+ * 4. the Khronos glTF Validator: any error rejects;
18
+ * 5. the rewrite through glTF Transform: meshopt data is decoded (bad data rejects), `extras`, unknown extensions and
19
+ * unused data are dropped, PNG, JPEG and WebP textures are re-encoded with `sharp`, one embedded buffer is written;
20
+ * 6. the new file goes through the validator and the decoder once more.
21
+ *
22
+ * A hostile file never throws: it gives `{ accepted: false, reasons, stats }`. Only misuse throws (`TypeError` for
23
+ * input that is not a `Uint8Array` or for an invalid option, `RangeError` for an extension the sanitiser cannot rewrite).
24
+ * This function does not scan for viruses: call `scanVirus` on the stored file as well.
25
+ *
26
+ * @param input the whole GLB file
27
+ * @param options the limits and the extension list; see {@link IGlbPolicy}. Every field has a safe default.
28
+ */
29
+ export async function sanitiseGlb(input, options = {}) {
30
+ const policy = resolveGlbPolicy(options);
31
+ if (!(input instanceof Uint8Array)) {
32
+ throw new TypeError('sanitiseGlb: input must be a Uint8Array or a Buffer');
33
+ }
34
+ // One private copy: glTF Transform reads from offset 0 of the underlying buffer, so a view or a pooled Buffer would
35
+ // fail to read. It also freezes what every stage sees if the caller changes its array while this call awaits.
36
+ const bytes = new Uint8Array(input);
37
+ const stats = emptyStats(bytes.length);
38
+ const container = checkGlbContainer(bytes, policy);
39
+ if (!container.ok) {
40
+ return rejected([container.reason], stats);
41
+ }
42
+ const parsed = parseGlbJson(container.json);
43
+ if (parsed.json === null) {
44
+ return rejected(parsed.reasons, stats);
45
+ }
46
+ const violations = inspectGlbJson(parsed.json, container.bin, policy, stats);
47
+ if (violations.length > 0) {
48
+ return rejected(violations, stats);
49
+ }
50
+ const invalid = await validateKhronos(bytes);
51
+ if (invalid.length > 0) {
52
+ return rejected(invalid, stats);
53
+ }
54
+ const io = await createGlbIo(policy.allowedExtensions);
55
+ const rewritten = await rewriteGlb(io, bytes, policy, stats);
56
+ if (rewritten.glb === null) {
57
+ return rejected(rewritten.reasons, stats);
58
+ }
59
+ const problems = await verifyGlbOutput(io, rewritten.glb);
60
+ if (problems.length > 0) {
61
+ return rejected(problems, stats);
62
+ }
63
+ stats.outputBytes = rewritten.glb.length;
64
+ return { accepted: true, glb: rewritten.glb, reasons: [], stats };
65
+ }
66
+ //# sourceMappingURL=sanitiseGlb.mjs.map
@@ -0,0 +1,16 @@
1
+ import type { IGlbPolicy } from './GLB_POLICY_DEFAULTS.mjs';
2
+ import type { IGlbSanitiseResult } from './IGlbSanitiseResult.mjs';
3
+ /**
4
+ * `sanitiseGlb` on a stored upload, for the temp file `storeUploadAsTemp` wrote. A file bigger than `maxBytes` is
5
+ * refused from its size, before one byte is read.
6
+ *
7
+ * - accepted: the sanitised bytes replace the file at `filePath`, so the path stays valid for the mover.
8
+ * - rejected: the file is deleted, like the extension and MIME validators do, so a hostile upload never stays on disk.
9
+ *
10
+ * Throws only on misuse (an invalid option) or when the file cannot be read, as `fs` does. A hostile file gives a
11
+ * rejected result. Run `scanVirus` on the file before this call: the sanitiser looks at structure, not at signatures.
12
+ *
13
+ * @param filePath the temp file
14
+ * @param options the limits and the extension list; see {@link IGlbPolicy}
15
+ */
16
+ export declare function sanitiseGlbFile(filePath: string, options?: Partial<IGlbPolicy>): Promise<IGlbSanitiseResult>;
@@ -0,0 +1,36 @@
1
+ import { readFile, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { tooLargeReason } from "../private/glb/glbReason.mjs";
3
+ import { emptyStats, rejected } from "../private/glb/glbStats.mjs";
4
+ import { resolveGlbPolicy } from "../private/glb/resolveGlbPolicy.mjs";
5
+ import { sanitiseGlb } from './sanitiseGlb.mjs';
6
+ /**
7
+ * `sanitiseGlb` on a stored upload, for the temp file `storeUploadAsTemp` wrote. A file bigger than `maxBytes` is
8
+ * refused from its size, before one byte is read.
9
+ *
10
+ * - accepted: the sanitised bytes replace the file at `filePath`, so the path stays valid for the mover.
11
+ * - rejected: the file is deleted, like the extension and MIME validators do, so a hostile upload never stays on disk.
12
+ *
13
+ * Throws only on misuse (an invalid option) or when the file cannot be read, as `fs` does. A hostile file gives a
14
+ * rejected result. Run `scanVirus` on the file before this call: the sanitiser looks at structure, not at signatures.
15
+ *
16
+ * @param filePath the temp file
17
+ * @param options the limits and the extension list; see {@link IGlbPolicy}
18
+ */
19
+ export async function sanitiseGlbFile(filePath, options = {}) {
20
+ const policy = resolveGlbPolicy(options);
21
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the caller names a temp file it stored itself, nothing here builds the path from request data
22
+ const { size } = await stat(filePath);
23
+ const result = size > policy.maxBytes
24
+ ? rejected([tooLargeReason(size, policy.maxBytes)], emptyStats(size))
25
+ : // eslint-disable-next-line security/detect-non-literal-fs-filename -- same caller-owned path as the stat above
26
+ await sanitiseGlb(await readFile(filePath), policy);
27
+ if (result.accepted) {
28
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- same caller-owned path as the stat above
29
+ await writeFile(filePath, result.glb);
30
+ }
31
+ else {
32
+ await rm(filePath, { force: true });
33
+ }
34
+ return result;
35
+ }
36
+ //# sourceMappingURL=sanitiseGlbFile.mjs.map
@@ -0,0 +1 @@
1
+ export declare function validateGlbExtension(filename: string, filePath: string): Promise<void>;
@@ -0,0 +1,9 @@
1
+ import fs from 'fs-extra';
2
+ import { validateExtension } from './validateExtension.mjs';
3
+ export async function validateGlbExtension(filename, filePath) {
4
+ if (!validateExtension(filename, ['.glb'])) {
5
+ await fs.remove(filePath); // Clean up the file
6
+ throw new Error('Invalid file extension');
7
+ }
8
+ }
9
+ //# sourceMappingURL=validateGlbExtension.mjs.map
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Validate MIME type based on file content (magic number validation)
3
+ * @param filePath
4
+ */
5
+ export declare function validateMimeTypeGlb(filePath: string): Promise<string>;
@@ -0,0 +1,9 @@
1
+ import { validateMimeType } from './validateMimeType.mjs';
2
+ /**
3
+ * Validate MIME type based on file content (magic number validation)
4
+ * @param filePath
5
+ */
6
+ export async function validateMimeTypeGlb(filePath) {
7
+ return await validateMimeType(filePath, ['model/gltf-binary']);
8
+ }
9
+ //# sourceMappingURL=validateMimeTypeGlb.mjs.map
@@ -0,0 +1,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,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ISocketLabsBasicMessage.mjs.map
@@ -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,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ISocketLabsOutcome.mjs.map
@@ -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
@@ -0,0 +1,10 @@
1
+ import type { ISocketLabsOutcome } from './ISocketLabsOutcome.mjs';
2
+ /**
3
+ * Reads the answer of the Injection API, the way the SDK's `SendResponse.parse` does for a response axios let through.
4
+ *
5
+ * Only a `200` is read. Any other status gives an outcome with no name: the SDK looked the status up in a result enum
6
+ * that has no numeric keys, so a `401`, a `500` and a `408` all arrived unclassified. On a `200` the `ErrorCode` of the
7
+ * body names the result; a `Warning` takes the `ErrorCode` of the first message result when that one is known, which
8
+ * is how a rejected recipient shows up. The transaction receipt and the address results ride along for `onError`.
9
+ */
10
+ export declare function parseInjectionResponse(status: number, text: string): ISocketLabsOutcome;