@axiumine/koa-utils 9.3.0 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +31 -3
  2. package/dist/files/VirusScanError.d.mts +14 -0
  3. package/dist/files/VirusScanError.mjs +19 -0
  4. package/dist/files/reEncodePdf.d.mts +43 -0
  5. package/dist/files/reEncodePdf.mjs +39 -0
  6. package/dist/files/scanVirus.d.mts +18 -5
  7. package/dist/files/scanVirus.mjs +56 -22
  8. package/dist/files/storeUploadAsTemp.d.mts +13 -1
  9. package/dist/files/storeUploadAsTemp.mjs +21 -3
  10. package/dist/files/uploadTempImage.d.mts +19 -1
  11. package/dist/files/uploadTempImage.mjs +52 -17
  12. package/dist/files/uploadTempPdf.d.mts +14 -3
  13. package/dist/files/uploadTempPdf.mjs +52 -17
  14. package/dist/private/files/assertWholeNumber.d.mts +9 -0
  15. package/dist/private/files/assertWholeNumber.mjs +14 -0
  16. package/dist/private/files/reEncode.d.mts +10 -2
  17. package/dist/private/files/reEncode.mjs +28 -15
  18. package/dist/private/files/replaceExtension.d.mts +8 -0
  19. package/dist/private/files/replaceExtension.mjs +11 -0
  20. package/dist/private/glb/reEncodeImage.d.mts +2 -2
  21. package/dist/private/glb/reEncodeImage.mjs +2 -2
  22. package/dist/private/lib/createLimiter.d.mts +7 -0
  23. package/dist/private/lib/createLimiter.mjs +31 -0
  24. package/dist/private/lib/createSentryClient.mjs +1 -0
  25. package/dist/private/pdf/pdfDictionary.d.mts +9 -0
  26. package/dist/private/pdf/pdfDictionary.mjs +25 -0
  27. package/dist/private/pdf/pdfStripRules.d.mts +12 -0
  28. package/dist/private/pdf/pdfStripRules.mjs +56 -0
  29. package/dist/private/pdf/resolvePdfOptions.d.mts +15 -0
  30. package/dist/private/pdf/resolvePdfOptions.mjs +49 -0
  31. package/dist/private/pdf/rewritePdf.d.mts +11 -0
  32. package/dist/private/pdf/rewritePdf.mjs +29 -0
  33. package/dist/private/pdf/rewritePdfWorker.d.mts +1 -0
  34. package/dist/private/pdf/rewritePdfWorker.mjs +7 -0
  35. package/dist/private/pdf/runInWorker.d.mts +10 -0
  36. package/dist/private/pdf/runInWorker.mjs +45 -0
  37. package/dist/private/pdf/stripPdf.d.mts +7 -0
  38. package/dist/private/pdf/stripPdf.mjs +67 -0
  39. package/dist/s3/S3ObjectTooLargeError.d.mts +8 -0
  40. package/dist/s3/S3ObjectTooLargeError.mjs +13 -0
  41. package/dist/s3/createS3Client.d.mts +18 -0
  42. package/dist/s3/createS3Client.mjs +20 -0
  43. package/dist/s3/deleteObject.d.mts +9 -0
  44. package/dist/s3/deleteObject.mjs +9 -0
  45. package/dist/s3/getObjectToFile.d.mts +19 -0
  46. package/dist/s3/getObjectToFile.mjs +52 -0
  47. package/dist/s3/headObject.d.mts +17 -0
  48. package/dist/s3/headObject.mjs +23 -0
  49. package/dist/s3/presignPutUrl.d.mts +22 -0
  50. package/dist/s3/presignPutUrl.mjs +27 -0
  51. package/dist/s3/putObject.d.mts +15 -0
  52. package/dist/s3/putObject.mjs +10 -0
  53. package/package.json +56 -5
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Reject a limit that is not a whole number from 1 to `max`. A limit such as `NaN` (an unset environment variable
3
+ * passed through `Number`) or `0` (which sharp reads as "no limit") would otherwise switch the check off.
4
+ *
5
+ * @param value the caller-supplied value
6
+ * @param name option name, used in the error message
7
+ * @param max highest accepted value
8
+ */
9
+ export declare function assertWholeNumber(value: number, name: string, max?: number): void;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Reject a limit that is not a whole number from 1 to `max`. A limit such as `NaN` (an unset environment variable
3
+ * passed through `Number`) or `0` (which sharp reads as "no limit") would otherwise switch the check off.
4
+ *
5
+ * @param value the caller-supplied value
6
+ * @param name option name, used in the error message
7
+ * @param max highest accepted value
8
+ */
9
+ export function assertWholeNumber(value, name, max = Number.MAX_SAFE_INTEGER) {
10
+ if (!Number.isInteger(value) || value < 1 || value > max) {
11
+ throw new TypeError(`Invalid ${name}: expected a whole number from 1 to ${max}`);
12
+ }
13
+ }
14
+ //# sourceMappingURL=assertWholeNumber.mjs.map
@@ -1,10 +1,18 @@
1
1
  import { FormatEnum } from 'sharp';
2
2
  type AvailableFormatInf = 'jpeg' | 'png' | 'webp' | 'avif';
3
+ export interface IReEncodeOptions {
4
+ /** WebP output only. Default `true` */
5
+ webpLossless?: boolean | undefined;
6
+ /** limit of width × height of the input (sharp `limitInputPixels`). Default: the limit of sharp */
7
+ maxPixels?: number | undefined;
8
+ }
3
9
  /**
4
- * Re-encode the image to a specific format and remove all metadata (EXIF, etc.)
10
+ * Re-encode the image to a specific format and remove all metadata (EXIF, XMP, IPTC, ICC profile). The pixels are
11
+ * turned the way the EXIF orientation says and converted to sRGB.
5
12
  * @param filePath
6
13
  * @param ext
7
14
  * @param quality
15
+ * @param options
8
16
  */
9
- export declare function reEncode(filePath: string, ext: keyof FormatEnum | AvailableFormatInf, quality?: number): Promise<string>;
17
+ export declare function reEncode(filePath: string, ext: keyof FormatEnum | AvailableFormatInf, quality?: number, options?: IReEncodeOptions): Promise<string>;
10
18
  export {};
@@ -1,32 +1,45 @@
1
+ import { replaceExtension } from "./replaceExtension.mjs";
1
2
  import * as Sentry from "../lib/sentry.mjs";
2
3
  import { throwInternalError } from "../../graphQL/throw/throwInternalError.mjs";
3
4
  import { promises as fs } from 'fs';
4
5
  import sharp from 'sharp';
6
+ /* eslint-enable sonarjs/no-redundant-optional -- end of the exactOptionalPropertyTypes block above */
7
+ // sharp writes no metadata unless it is asked to, so no call below asks for it
8
+ async function writeAs(image, ext, finalFilepath, encoder) {
9
+ const { quality, webpLossless } = encoder;
10
+ if (ext === 'jpeg') {
11
+ await image.jpeg({ quality, progressive: true }).toFile(finalFilepath);
12
+ }
13
+ else if (ext === 'png') {
14
+ await image.png({ quality, progressive: true }).toFile(finalFilepath);
15
+ }
16
+ else if (ext === 'webp') {
17
+ await image.webp({ quality, lossless: webpLossless }).toFile(finalFilepath);
18
+ }
19
+ else if (ext === 'avif') {
20
+ await image.avif({ quality, lossless: true }).toFile(finalFilepath);
21
+ }
22
+ }
5
23
  /**
6
- * Re-encode the image to a specific format and remove all metadata (EXIF, etc.)
24
+ * Re-encode the image to a specific format and remove all metadata (EXIF, XMP, IPTC, ICC profile). The pixels are
25
+ * turned the way the EXIF orientation says and converted to sRGB.
7
26
  * @param filePath
8
27
  * @param ext
9
28
  * @param quality
29
+ * @param options
10
30
  */
11
- export async function reEncode(filePath, ext, quality = 100) {
12
- const finalFilepath = filePath.replace(/\.[^.]+$/, `.${ext}`);
31
+ export async function reEncode(filePath, ext, quality = 100, options = {}) {
32
+ const finalFilepath = replaceExtension(filePath, ext);
33
+ const { webpLossless = true, maxPixels } = options;
13
34
  try {
14
35
  // Read the bytes up front: sharp refuses to use one file as both input and output, which is
15
36
  // exactly what happens when the source already carries the target extension.
16
37
  // eslint-disable-next-line security/detect-non-literal-fs-filename -- the path is this helper's input by design: the caller names a file it stored itself, nothing here builds it from request data
17
38
  const input = await fs.readFile(filePath);
18
- if (ext === 'jpeg') {
19
- await sharp(input).jpeg({ quality, progressive: true }).withMetadata({}).withExif({}).toFile(finalFilepath);
20
- }
21
- else if (ext === 'png') {
22
- await sharp(input).png({ quality, progressive: true }).withMetadata({}).withExif({}).toFile(finalFilepath);
23
- }
24
- else if (ext === 'webp') {
25
- await sharp(input).webp({ quality, lossless: true }).withMetadata({}).withExif({}).toFile(finalFilepath);
26
- }
27
- else if (ext === 'avif') {
28
- await sharp(input).avif({ quality, lossless: true }).withMetadata({}).withExif({}).toFile(finalFilepath);
29
- }
39
+ // `rotate()` without an angle applies the EXIF orientation, whose tag is not written out. It is the same call as
40
+ // `autoOrient()` and, unlike it, also exists in sharp releases older than 0.34.
41
+ const image = sharp(input, { limitInputPixels: maxPixels }).rotate();
42
+ await writeAs(image, ext, finalFilepath, { quality, webpLossless });
30
43
  }
31
44
  catch (err) {
32
45
  Sentry.captureException(err);
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Swap the last extension of the file name in a path. A path whose file name has no dot is returned unchanged: a dot in
3
+ * a folder name is not an extension.
4
+ *
5
+ * @param filePath
6
+ * @param ext new extension, without the dot
7
+ */
8
+ export declare function replaceExtension(filePath: string, ext: string): string;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Swap the last extension of the file name in a path. A path whose file name has no dot is returned unchanged: a dot in
3
+ * a folder name is not an extension.
4
+ *
5
+ * @param filePath
6
+ * @param ext new extension, without the dot
7
+ */
8
+ export function replaceExtension(filePath, ext) {
9
+ return filePath.replace(/\.[^./]+$/, `.${ext}`);
10
+ }
11
+ //# sourceMappingURL=replaceExtension.mjs.map
@@ -4,8 +4,8 @@ import type { IReencodableFormat } from './readImageHeader.mjs';
4
4
  * whatever hid in the container (trailing bytes, extra chunks, polyglot payloads) is gone, and `sharp` drops every
5
5
  * metadata block (EXIF, XMP, ICC) because nothing asks it to keep one.
6
6
  *
7
- * `reEncode` in `reEncode.mts` is not reused on purpose: it reads and writes files and keeps XMP and ICC (limit L13 in
8
- * `docs/security.md`), while a GLB texture is a buffer in memory that must come out clean.
7
+ * `reEncode` in `reEncode.mts` is not reused on purpose: it reads and writes files, while a GLB texture is a buffer in
8
+ * memory.
9
9
  *
10
10
  * `limitInputPixels` makes `sharp` refuse an image bigger than `maxSide` squared before it allocates the pixels, a
11
11
  * second line behind the header check. `failOn: 'warning'` refuses a truncated or damaged file instead of repairing it.
@@ -4,8 +4,8 @@ import sharp from 'sharp';
4
4
  * whatever hid in the container (trailing bytes, extra chunks, polyglot payloads) is gone, and `sharp` drops every
5
5
  * metadata block (EXIF, XMP, ICC) because nothing asks it to keep one.
6
6
  *
7
- * `reEncode` in `reEncode.mts` is not reused on purpose: it reads and writes files and keeps XMP and ICC (limit L13 in
8
- * `docs/security.md`), while a GLB texture is a buffer in memory that must come out clean.
7
+ * `reEncode` in `reEncode.mts` is not reused on purpose: it reads and writes files, while a GLB texture is a buffer in
8
+ * memory.
9
9
  *
10
10
  * `limitInputPixels` makes `sharp` refuse an image bigger than `maxSide` squared before it allocates the pixels, a
11
11
  * second line behind the header check. `failOn: 'warning'` refuses a truncated or damaged file instead of repairing it.
@@ -0,0 +1,7 @@
1
+ /**
2
+ * A gate that lets at most `size` tasks run at once. The others wait, first come first served.
3
+ *
4
+ * @param size
5
+ * @returns runs a task when a place is free and resolves what the task resolves
6
+ */
7
+ export declare function createLimiter(size: number): <T>(task: () => Promise<T>) => Promise<T>;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A gate that lets at most `size` tasks run at once. The others wait, first come first served.
3
+ *
4
+ * @param size
5
+ * @returns runs a task when a place is free and resolves what the task resolves
6
+ */
7
+ export function createLimiter(size) {
8
+ let free = size;
9
+ const waiting = [];
10
+ return async function inTurn(task) {
11
+ if (free > 0)
12
+ free--;
13
+ else {
14
+ await new Promise((resolve) => {
15
+ waiting.push(resolve);
16
+ });
17
+ }
18
+ try {
19
+ return await task();
20
+ }
21
+ finally {
22
+ // the place goes to the next in line, or back to the free ones
23
+ const next = waiting.shift();
24
+ if (next === undefined)
25
+ free++;
26
+ else
27
+ next();
28
+ }
29
+ };
30
+ }
31
+ //# sourceMappingURL=createLimiter.mjs.map
@@ -2,6 +2,7 @@
2
2
  // `then` is left undefined: a callback that returns the scope from an async function would otherwise treat it as a
3
3
  // thenable and wait forever.
4
4
  const noopSetter = () => NOOP_SCOPE;
5
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-class-instance-assignment -- a Proxy stand-in on purpose: no Sentry `Scope` exists when the peer is absent
5
6
  const NOOP_SCOPE = new Proxy({}, { get: (_target, property) => (property === 'then' ? undefined : noopSetter) });
6
7
  // What the package reports to when `@sentry/node` is not installed: nothing. The event id is '' as no event exists.
7
8
  const NOOP_CLIENT = {
@@ -0,0 +1,9 @@
1
+ import type { PDFObject } from 'mupdf';
2
+ /** Remove every entry of a dictionary, so that nothing it held stays reachable through it. */
3
+ export declare function clearDictionary(dictionary: PDFObject): void;
4
+ /**
5
+ * Call `visit` on `root`, when it is a dictionary, and on every dictionary written inside it. References are not
6
+ * followed: each referenced object is an entry of the cross-reference table, which the caller walks. A list instead of
7
+ * recursion, so that the nesting of a hostile file cannot exhaust the stack.
8
+ */
9
+ export declare function visitDictionaries(root: PDFObject, visit: (dictionary: PDFObject) => void): void;
@@ -0,0 +1,25 @@
1
+ /** Remove every entry of a dictionary, so that nothing it held stays reachable through it. */
2
+ export function clearDictionary(dictionary) {
3
+ // listed first: deleting while MuPDF walks the entries would skip some
4
+ const keys = new Set();
5
+ dictionary.forEach((_value, key) => keys.add(String(key)));
6
+ for (const key of keys)
7
+ dictionary.delete(key);
8
+ }
9
+ /**
10
+ * Call `visit` on `root`, when it is a dictionary, and on every dictionary written inside it. References are not
11
+ * followed: each referenced object is an entry of the cross-reference table, which the caller walks. A list instead of
12
+ * recursion, so that the nesting of a hostile file cannot exhaust the stack.
13
+ */
14
+ export function visitDictionaries(root, visit) {
15
+ const pending = [root];
16
+ for (let object = pending.pop(); object !== undefined; object = pending.pop()) {
17
+ if (object.isDictionary())
18
+ visit(object);
19
+ object.forEach((child) => {
20
+ if (!child.isIndirect())
21
+ pending.push(child);
22
+ });
23
+ }
24
+ }
25
+ //# sourceMappingURL=pdfDictionary.mjs.map
@@ -0,0 +1,12 @@
1
+ import type { TPdfCategory } from './resolvePdfOptions.mjs';
2
+ /** type of an action (`/S`) → the category that removes it. `GoTo`, a jump inside the document, is never removed */
3
+ export declare const ACTION_CATEGORY: Map<string, keyof import("../../files/reEncodePdf.mjs").IPdfStripOptions>;
4
+ /** `/Subtype` of an annotation → the category that removes it. Any other subtype but `Link` counts as `annotations` */
5
+ export declare const ANNOTATION_CATEGORY: Map<string, keyof import("../../files/reEncodePdf.mjs").IPdfStripOptions>;
6
+ /** keys removed from any dictionary of the file */
7
+ export declare const ANY_KEYS: [TPdfCategory, string[]][];
8
+ /** keys removed from the document catalog */
9
+ export declare const CATALOG_KEYS: [TPdfCategory, string[]][];
10
+ /** name trees removed from the `/Names` dictionary of the catalog */
11
+ export declare const NAME_TREE_KEYS: [TPdfCategory, string[]][];
12
+ export declare const TRAILER_KEYS: [TPdfCategory, string[]][];
@@ -0,0 +1,56 @@
1
+ const OTHER_ACTIONS = [
2
+ 'GoToR',
3
+ 'GoToE',
4
+ 'GoToDp',
5
+ 'Launch',
6
+ 'Thread',
7
+ 'Sound',
8
+ 'Movie',
9
+ 'Hide',
10
+ 'Named',
11
+ 'SubmitForm',
12
+ 'ResetForm',
13
+ 'ImportData',
14
+ 'SetOCGState',
15
+ 'SetState',
16
+ 'NOP',
17
+ 'Rendition',
18
+ 'Trans',
19
+ 'GoTo3DView',
20
+ 'RichMediaExecute'
21
+ ];
22
+ /** type of an action (`/S`) → the category that removes it. `GoTo`, a jump inside the document, is never removed */
23
+ export const ACTION_CATEGORY = new Map([
24
+ ['JavaScript', 'javaScript'],
25
+ ['URI', 'links'],
26
+ ...OTHER_ACTIONS.map((type) => [type, 'actions'])
27
+ ]);
28
+ /** `/Subtype` of an annotation → the category that removes it. Any other subtype but `Link` counts as `annotations` */
29
+ export const ANNOTATION_CATEGORY = new Map([
30
+ ['Widget', 'forms'],
31
+ ['FileAttachment', 'embeddedFiles'],
32
+ ['RichMedia', 'multimedia'],
33
+ ['Screen', 'multimedia'],
34
+ ['Movie', 'multimedia'],
35
+ ['Sound', 'multimedia'],
36
+ ['3D', 'multimedia']
37
+ ]);
38
+ /** keys removed from any dictionary of the file */
39
+ export const ANY_KEYS = [
40
+ ['javaScript', ['JS', 'XFA']],
41
+ ['embeddedFiles', ['EF', 'RF', 'AF']],
42
+ ['metadata', ['Metadata', 'PieceInfo', 'LastModified', 'Thumb']]
43
+ ];
44
+ /** keys removed from the document catalog */
45
+ export const CATALOG_KEYS = [
46
+ ['forms', ['AcroForm']],
47
+ ['embeddedFiles', ['Collection']]
48
+ ];
49
+ /** name trees removed from the `/Names` dictionary of the catalog */
50
+ export const NAME_TREE_KEYS = [
51
+ ['javaScript', ['JavaScript']],
52
+ ['embeddedFiles', ['EmbeddedFiles']],
53
+ ['multimedia', ['Renditions']]
54
+ ];
55
+ export const TRAILER_KEYS = [['metadata', ['Info']]];
56
+ //# sourceMappingURL=pdfStripRules.mjs.map
@@ -0,0 +1,15 @@
1
+ import type { IPdfStripOptions, IReEncodePdfOptions } from '../../files/reEncodePdf.mjs';
2
+ export type TPdfCategory = keyof IPdfStripOptions;
3
+ /** the categories a call removes */
4
+ export type TPdfStrip = ReadonlySet<TPdfCategory>;
5
+ export declare function assertKnownKeys(value: unknown, known: string[], name: string): void;
6
+ /**
7
+ * Check the options of a PDF re-encode and fill in the defaults.
8
+ *
9
+ * @throws TypeError for an unknown key, a `strip` value that is not a boolean or a `timeout` that is not a whole number of
10
+ * milliseconds
11
+ */
12
+ export declare function resolvePdfOptions(options: IReEncodePdfOptions): {
13
+ strip: TPdfStrip;
14
+ timeout: number;
15
+ };
@@ -0,0 +1,49 @@
1
+ import { assertWholeNumber } from "../files/assertWholeNumber.mjs";
2
+ // Active content and hidden data go by default, content a reader sees stays
3
+ const DEFAULTS = {
4
+ javaScript: true,
5
+ actions: true,
6
+ embeddedFiles: true,
7
+ multimedia: true,
8
+ metadata: true,
9
+ links: false,
10
+ forms: false,
11
+ annotations: false
12
+ };
13
+ const DEFAULT_TIMEOUT = 30_000;
14
+ // the longest delay a timer of Node takes
15
+ const MAX_TIMEOUT = 2_147_483_647;
16
+ // A misspelt key must not pass in silence: the caller would believe something is removed
17
+ export function assertKnownKeys(value, known, name) {
18
+ if (typeof value !== 'object' || value === null) {
19
+ throw new TypeError(`Invalid ${name}: expected an object`);
20
+ }
21
+ const unknownKey = Object.keys(value).find((key) => !known.includes(key));
22
+ if (unknownKey !== undefined) {
23
+ throw new TypeError(`Unknown key in ${name}: ${unknownKey}`);
24
+ }
25
+ }
26
+ function resolveStrip(strip) {
27
+ assertKnownKeys(strip, Object.keys(DEFAULTS), 'strip');
28
+ const wanted = Object.entries(strip).filter(([, value]) => value !== undefined);
29
+ for (const [name, value] of wanted) {
30
+ if (typeof value !== 'boolean') {
31
+ throw new TypeError(`Invalid strip.${name}: expected a boolean`);
32
+ }
33
+ }
34
+ const resolved = Object.entries({ ...DEFAULTS, ...Object.fromEntries(wanted) });
35
+ return new Set(resolved.filter(([, removed]) => removed).map(([name]) => name));
36
+ }
37
+ /**
38
+ * Check the options of a PDF re-encode and fill in the defaults.
39
+ *
40
+ * @throws TypeError for an unknown key, a `strip` value that is not a boolean or a `timeout` that is not a whole number of
41
+ * milliseconds
42
+ */
43
+ export function resolvePdfOptions(options) {
44
+ assertKnownKeys(options, ['strip', 'timeout'], 'reEncode');
45
+ const { strip = {}, timeout = DEFAULT_TIMEOUT } = options;
46
+ assertWholeNumber(timeout, 'reEncode.timeout', MAX_TIMEOUT);
47
+ return { strip: resolveStrip(strip), timeout };
48
+ }
49
+ //# sourceMappingURL=resolvePdfOptions.mjs.map
@@ -0,0 +1,11 @@
1
+ import type { TPdfStrip } from './resolvePdfOptions.mjs';
2
+ /**
3
+ * Parse a PDF, remove what `strip` says and write it as a new file.
4
+ *
5
+ * Meant for a worker thread that ends afterwards (`rewritePdfWorker`), so nothing is released here. Releasing would not
6
+ * be enough: `mupdf` 1.28.6 takes two references for every object it hands to JavaScript and gives back one, so each
7
+ * file would leave its objects in the memory of the WebAssembly module for the life of the thread.
8
+ *
9
+ * @throws `Error` for a password protected file, a file without pages or one MuPDF cannot read
10
+ */
11
+ export declare function rewritePdf(bytes: Uint8Array, strip: TPdfStrip): Promise<Uint8Array>;
@@ -0,0 +1,29 @@
1
+ import { stripPdf } from './stripPdf.mjs';
2
+ // `garbage=yes` leaves out the objects nothing references any more, the removed ones included, and keeps the number of
3
+ // every other object. `compact` is left out on purpose: it renumbers, and while it does so MuPDF copies every object that
4
+ // has more than one reference and whose dictionary holds a reference, and the copy loses its stream. `mupdf` 1.28.6 leaves
5
+ // one reference too many on each object handed to JavaScript (see `rewritePdf`), so images left the file. `deduplicate`
6
+ // renumbers too, and it, `clean` and `sanitize` each changed how pages of real files render
7
+ const SAVE_OPTIONS = 'garbage=yes,compress,encrypt=none';
8
+ /**
9
+ * Parse a PDF, remove what `strip` says and write it as a new file.
10
+ *
11
+ * Meant for a worker thread that ends afterwards (`rewritePdfWorker`), so nothing is released here. Releasing would not
12
+ * be enough: `mupdf` 1.28.6 takes two references for every object it hands to JavaScript and gives back one, so each
13
+ * file would leave its objects in the memory of the WebAssembly module for the life of the thread.
14
+ *
15
+ * @throws `Error` for a password protected file, a file without pages or one MuPDF cannot read
16
+ */
17
+ export async function rewritePdf(bytes, strip) {
18
+ // loaded at first use: only a caller that re-encodes a PDF needs the optional peer
19
+ const mupdf = await import('mupdf');
20
+ const document = new mupdf.PDFDocument(bytes);
21
+ if (document.needsPassword())
22
+ throw new Error('The PDF is password protected');
23
+ if (document.countPages() < 1)
24
+ throw new Error('The PDF has no pages');
25
+ stripPdf(document, strip);
26
+ // copied out: the buffer is a view of the memory of the WebAssembly module
27
+ return document.saveToBuffer(SAVE_OPTIONS).asUint8Array().slice();
28
+ }
29
+ //# sourceMappingURL=rewritePdf.mjs.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ // Entry of the worker thread `reEncodePdf` starts for each file
2
+ import { parentPort, workerData } from 'node:worker_threads';
3
+ import { rewritePdf } from './rewritePdf.mjs';
4
+ const { bytes, strip } = workerData;
5
+ const port = parentPort;
6
+ port.postMessage(await rewritePdf(bytes, strip));
7
+ //# sourceMappingURL=rewritePdfWorker.mjs.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Run a script once in a worker thread of its own and resolve the one message it posts. The thread is ended after that
3
+ * message, and everything it allocated, WebAssembly memory included, is gone when the promise settles.
4
+ *
5
+ * @param script
6
+ * @param workerData handed to the script, copied
7
+ * @param timeout milliseconds the thread may take to post its message, counted from its start
8
+ * @throws the error the script throws, or `Error` when it ends without posting anything or takes longer than `timeout`
9
+ */
10
+ export declare function runInWorker(script: URL, workerData: unknown, timeout: number): Promise<unknown>;
@@ -0,0 +1,45 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ /**
3
+ * Run a script once in a worker thread of its own and resolve the one message it posts. The thread is ended after that
4
+ * message, and everything it allocated, WebAssembly memory included, is gone when the promise settles.
5
+ *
6
+ * @param script
7
+ * @param workerData handed to the script, copied
8
+ * @param timeout milliseconds the thread may take to post its message, counted from its start
9
+ * @throws the error the script throws, or `Error` when it ends without posting anything or takes longer than `timeout`
10
+ */
11
+ export async function runInWorker(script, workerData, timeout) {
12
+ return await new Promise((resolve, reject) => {
13
+ const worker = new Worker(script, { workerData });
14
+ // what the promise will do once the thread is gone, set by whatever happens first
15
+ let outcome;
16
+ const end = () => {
17
+ worker.terminate().catch(reject);
18
+ };
19
+ const timer = setTimeout(() => {
20
+ outcome ??= () => {
21
+ reject(new Error(`The worker gave no result in ${timeout} ms`));
22
+ };
23
+ end();
24
+ }, timeout);
25
+ worker.once('message', (value) => {
26
+ outcome = () => {
27
+ resolve(value);
28
+ };
29
+ end();
30
+ });
31
+ worker.once('error', (error) => {
32
+ outcome = () => {
33
+ reject(error);
34
+ };
35
+ });
36
+ worker.once('exit', (code) => {
37
+ clearTimeout(timer);
38
+ if (outcome)
39
+ outcome();
40
+ else
41
+ reject(new Error(`The worker stopped without a result (exit code ${code})`));
42
+ });
43
+ });
44
+ }
45
+ //# sourceMappingURL=runInWorker.mjs.map
@@ -0,0 +1,7 @@
1
+ import type { PDFDocument } from 'mupdf';
2
+ import type { TPdfStrip } from './resolvePdfOptions.mjs';
3
+ /**
4
+ * Remove from an open document what `strip` asks for. The removed objects are only unreachable afterwards: the document
5
+ * must be saved with garbage collection for them to leave the file.
6
+ */
7
+ export declare function stripPdf(pdf: PDFDocument, strip: TPdfStrip): void;
@@ -0,0 +1,67 @@
1
+ import { clearDictionary, visitDictionaries } from './pdfDictionary.mjs';
2
+ import { ACTION_CATEGORY, ANNOTATION_CATEGORY, ANY_KEYS, CATALOG_KEYS, NAME_TREE_KEYS, TRAILER_KEYS } from './pdfStripRules.mjs';
3
+ function removeKeys(dictionary, rules, strip) {
4
+ for (const [category, keys] of rules) {
5
+ if (strip.has(category)) {
6
+ for (const key of keys)
7
+ dictionary.delete(key);
8
+ }
9
+ }
10
+ }
11
+ function isStrippedAnnotation(annotation, strip) {
12
+ const subtype = annotation.get('Subtype').asName();
13
+ // a link goes with its action, `links` or `actions`: what is left of it does nothing
14
+ if (subtype === 'Link')
15
+ return false;
16
+ return strip.has(ANNOTATION_CATEGORY.get(subtype) ?? 'annotations');
17
+ }
18
+ function stripAnnotationList(annotations, strip) {
19
+ for (let at = annotations.length - 1; at >= 0; at--) {
20
+ const annotation = annotations.get(at);
21
+ if (!annotation.isDictionary() || isStrippedAnnotation(annotation, strip)) {
22
+ // emptied as well as unlisted: a structure tree can still reference it
23
+ if (annotation.isDictionary())
24
+ clearDictionary(annotation);
25
+ annotations.delete(at);
26
+ }
27
+ }
28
+ }
29
+ function stripAnnotations(pdf, strip) {
30
+ for (let page = 0; page < pdf.countPages(); page++) {
31
+ // no list on the page, or something that is not one, has length 0
32
+ stripAnnotationList(pdf.findPage(page).get('Annots'), strip);
33
+ }
34
+ }
35
+ function cleanDictionary(dictionary, strip) {
36
+ const category = ACTION_CATEGORY.get(dictionary.get('S').asName());
37
+ if (category !== undefined && strip.has(category)) {
38
+ clearDictionary(dictionary);
39
+ return;
40
+ }
41
+ removeKeys(dictionary, ANY_KEYS, strip);
42
+ }
43
+ function stripCatalog(pdf, strip) {
44
+ const catalog = pdf.getTrailer().get('Root');
45
+ removeKeys(catalog, CATALOG_KEYS, strip);
46
+ const names = catalog.get('Names');
47
+ if (names.isDictionary())
48
+ removeKeys(names, NAME_TREE_KEYS, strip);
49
+ }
50
+ /**
51
+ * Remove from an open document what `strip` asks for. The removed objects are only unreachable afterwards: the document
52
+ * must be saved with garbage collection for them to leave the file.
53
+ */
54
+ export function stripPdf(pdf, strip) {
55
+ stripAnnotations(pdf, strip);
56
+ stripCatalog(pdf, strip);
57
+ removeKeys(pdf.getTrailer(), TRAILER_KEYS, strip);
58
+ const clean = (dictionary) => {
59
+ cleanDictionary(dictionary, strip);
60
+ };
61
+ visitDictionaries(pdf.getTrailer(), clean);
62
+ // Stryker disable next-line EqualityOperator: only the <= replacement is equivalent (the number one past the last entry resolves to null, which holds no dictionary to visit). The >= replacement visits no object and is not equivalent: Stryker cannot disable one replacement only, so it was applied by hand and the rewritePdf specs that expect content to leave the file fail on it.
63
+ for (let number = 1; number < pdf.countObjects(); number++) {
64
+ visitDictionaries(pdf.newIndirect(number).resolve(), clean);
65
+ }
66
+ }
67
+ //# sourceMappingURL=stripPdf.mjs.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * An object bigger than the limit given to `getObjectToFile`.
3
+ */
4
+ export declare class S3ObjectTooLargeError extends Error {
5
+ /** the limit in bytes */
6
+ readonly maxBytes: number;
7
+ constructor(maxBytes: number);
8
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * An object bigger than the limit given to `getObjectToFile`.
3
+ */
4
+ export class S3ObjectTooLargeError extends Error {
5
+ /** the limit in bytes */
6
+ maxBytes;
7
+ constructor(maxBytes) {
8
+ super(`Object size exceeds the limit of ${maxBytes} bytes`);
9
+ this.name = 'S3ObjectTooLargeError';
10
+ this.maxBytes = maxBytes;
11
+ }
12
+ }
13
+ //# sourceMappingURL=S3ObjectTooLargeError.mjs.map
@@ -0,0 +1,18 @@
1
+ import { S3Client } from '@aws-sdk/client-s3';
2
+ export interface IS3ClientOptions {
3
+ /** URL of the service. Cloudflare R2: `https://<account>.r2.cloudflarestorage.com`, EU: `https://<account>.eu.r2.cloudflarestorage.com` */
4
+ endpoint: string;
5
+ /** Cloudflare R2: `auto` */
6
+ region: string;
7
+ accessKeyId: string;
8
+ secretAccessKey: string;
9
+ /** `true` (default): `https://host/bucket/key`. `false`: `https://bucket.host/key` */
10
+ forcePathStyle?: boolean | undefined;
11
+ }
12
+ /**
13
+ * Client for S3-compatible storage with static credentials.
14
+ *
15
+ * Checksums are sent and checked only where an operation requires them: not every S3-compatible service takes the ones
16
+ * the SDK adds by default, and a presigned PUT URL would carry the checksum of an empty body.
17
+ */
18
+ export declare function createS3Client(options: IS3ClientOptions): S3Client;
@@ -0,0 +1,20 @@
1
+ import { S3Client } from '@aws-sdk/client-s3';
2
+ /* eslint-enable sonarjs/no-redundant-optional -- end of the exactOptionalPropertyTypes block above */
3
+ /**
4
+ * Client for S3-compatible storage with static credentials.
5
+ *
6
+ * Checksums are sent and checked only where an operation requires them: not every S3-compatible service takes the ones
7
+ * the SDK adds by default, and a presigned PUT URL would carry the checksum of an empty body.
8
+ */
9
+ export function createS3Client(options) {
10
+ const { endpoint, region, accessKeyId, secretAccessKey, forcePathStyle = true } = options;
11
+ return new S3Client({
12
+ endpoint,
13
+ region,
14
+ credentials: { accessKeyId, secretAccessKey },
15
+ forcePathStyle,
16
+ requestChecksumCalculation: 'WHEN_REQUIRED',
17
+ responseChecksumValidation: 'WHEN_REQUIRED'
18
+ });
19
+ }
20
+ //# sourceMappingURL=createS3Client.mjs.map
@@ -0,0 +1,9 @@
1
+ import { S3Client } from '@aws-sdk/client-s3';
2
+ export interface IDeleteObjectInput {
3
+ bucket: string;
4
+ key: string;
5
+ }
6
+ /**
7
+ * Delete an object. A key that holds no object is not an error.
8
+ */
9
+ export declare function deleteObject(client: S3Client, input: IDeleteObjectInput): Promise<void>;