From dd28d778ca5b0bcee46950f5f64aa0d5a1915696 Mon Sep 17 00:00:00 2001 From: Ali Amori Kadhim Date: Wed, 4 Jun 2025 09:42:46 +0200 Subject: [PATCH] feat: create strapi-provider-media-upload plugin --- .changeset/old-parrots-judge.md | 5 + .changeset/popular-countries-collect.md | 5 + .eslintrc.js | 1 + apps/pdc-dashboard/config/plugins.ts | 2 + apps/pdc-dashboard/package.json | 1 + .../strapi-provider-media-upload/LICENSE.md | 288 ++++++++++++++++++ .../strapi-provider-media-upload/README.md | 99 ++++++ .../strapi-provider-media-upload/custom.d.ts | 6 + .../strapi-provider-media-upload/package.json | 51 ++++ .../rollup.config.ts | 37 +++ .../strapi-provider-media-upload/src/index.ts | 147 +++++++++ .../tsconfig.json | 27 ++ yarn.lock | 51 +++- 13 files changed, 719 insertions(+), 1 deletion(-) create mode 100644 .changeset/old-parrots-judge.md create mode 100644 .changeset/popular-countries-collect.md create mode 100644 packages/strapi-provider-media-upload/LICENSE.md create mode 100644 packages/strapi-provider-media-upload/README.md create mode 100644 packages/strapi-provider-media-upload/custom.d.ts create mode 100644 packages/strapi-provider-media-upload/package.json create mode 100644 packages/strapi-provider-media-upload/rollup.config.ts create mode 100644 packages/strapi-provider-media-upload/src/index.ts create mode 100644 packages/strapi-provider-media-upload/tsconfig.json diff --git a/.changeset/old-parrots-judge.md b/.changeset/old-parrots-judge.md new file mode 100644 index 000000000..708426c63 --- /dev/null +++ b/.changeset/old-parrots-judge.md @@ -0,0 +1,5 @@ +--- +"@frameless/strapi-provider-media-upload": major +--- + +Ondersteuning toegevoegd voor filtering op veilige bestandstypen bij uploads ([GitHub Issue Frameless/strapi#1167](https://github.com/frameless/strapi/issues/1167)). diff --git a/.changeset/popular-countries-collect.md b/.changeset/popular-countries-collect.md new file mode 100644 index 000000000..906a2c1e4 --- /dev/null +++ b/.changeset/popular-countries-collect.md @@ -0,0 +1,5 @@ +--- +"@frameless/pdc-dashboard": minor +--- + +Ondersteuning toegevoegd voor filtering op veilige bestandstypen bij uploads ([GitHub Issue Frameless/strapi#1167](https://github.com/frameless/strapi/issues/1167)). diff --git a/.eslintrc.js b/.eslintrc.js index 0cf70ffe3..41593103d 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -86,6 +86,7 @@ module.exports = { './packages/strapi-plugin-uniform-product-name/tsconfig.server.json', './packages/strapi-plugin-uuid-field/tsconfig.json', './packages/strapi-plugin-uuid-field/tsconfig.server.json', + './packages/strapi-provider-media-upload/tsconfig.json', './packages/strapi-tiptap-editor/tsconfig.json', './packages/strapi-tiptap-editor/tsconfig.server.json', './packages/strapi-tiptap-editor/tsconfig.test.json', diff --git a/apps/pdc-dashboard/config/plugins.ts b/apps/pdc-dashboard/config/plugins.ts index 3634e5f7d..49b04d0d2 100644 --- a/apps/pdc-dashboard/config/plugins.ts +++ b/apps/pdc-dashboard/config/plugins.ts @@ -108,10 +108,12 @@ export default ({ env }) => ({ }, upload: { config: { + provider: '@frameless/strapi-provider-media-upload', providerOptions: { localServer: { maxage: 300000, }, + allowedMimeTypes: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'], }, }, }, diff --git a/apps/pdc-dashboard/package.json b/apps/pdc-dashboard/package.json index 2de95b1df..ca50b6b3a 100644 --- a/apps/pdc-dashboard/package.json +++ b/apps/pdc-dashboard/package.json @@ -30,6 +30,7 @@ "@frameless/strapi-plugin-uuid-field": "0.0.0", "@frameless/strapi-tiptap-editor": "0.3.2", "@frameless/strapi-plugin-old-slugs": "1.0.0", + "@frameless/strapi-provider-media-upload": "0.0.0", "@strapi/plugin-graphql": "4.25.8", "@strapi/plugin-i18n": "4.25.8", "@strapi/plugin-users-permissions": "4.25.8", diff --git a/packages/strapi-provider-media-upload/LICENSE.md b/packages/strapi-provider-media-upload/LICENSE.md new file mode 100644 index 000000000..ed38ebab5 --- /dev/null +++ b/packages/strapi-provider-media-upload/LICENSE.md @@ -0,0 +1,288 @@ +# EUROPEAN UNION PUBLIC LICENCE v. 1.2 + +EUPL © the European Union 2007, 2016 + +This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined +below) which is provided under the terms of this Licence. Any use of the Work, +other than as authorised under this Licence is prohibited (to the extent such +use is covered by a right of the copyright holder of the Work). + +The Work is provided under the terms of this Licence when the Licensor (as +defined below) has placed the following notice immediately following the +copyright notice for the Work: + + Licensed under the EUPL + +or has expressed by any other means his willingness to license under the EUPL. + +## 1. Definitions + +In this Licence, the following terms have the following meaning: + +- ‘The Licence’: this Licence. + +- ‘The Original Work’: the work or software distributed or communicated by the + Licensor under this Licence, available as Source Code and also as Executable + Code as the case may be. + +- ‘Derivative Works’: the works or software that could be created by the + Licensee, based upon the Original Work or modifications thereof. This Licence + does not define the extent of modification or dependence on the Original Work + required in order to classify a work as a Derivative Work; this extent is + determined by copyright law applicable in the country mentioned in Article 15. + +- ‘The Work’: the Original Work or its Derivative Works. + +- ‘The Source Code’: the human-readable form of the Work which is the most + convenient for people to study and modify. + +- ‘The Executable Code’: any code which has generally been compiled and which is + meant to be interpreted by a computer as a program. + +- ‘The Licensor’: the natural or legal person that distributes or communicates + the Work under the Licence. + +- ‘Contributor(s)’: any natural or legal person who modifies the Work under the + Licence, or otherwise contributes to the creation of a Derivative Work. + +- ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of + the Work under the terms of the Licence. + +- ‘Distribution’ or ‘Communication’: any act of selling, giving, lending, + renting, distributing, communicating, transmitting, or otherwise making + available, online or offline, copies of the Work or providing access to its + essential functionalities at the disposal of any other natural or legal + person. + +## 2. Scope of the rights granted by the Licence + +The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, +sublicensable licence to do the following, for the duration of copyright vested +in the Original Work: + +- use the Work in any circumstance and for all usage, +- reproduce the Work, +- modify the Work, and make Derivative Works based upon the Work, +- communicate to the public, including the right to make available or display + the Work or copies thereof to the public and perform publicly, as the case may + be, the Work, +- distribute the Work or copies thereof, +- lend and rent the Work or copies thereof, +- sublicense rights in the Work or copies thereof. + +Those rights can be exercised on any media, supports and formats, whether now +known or later invented, as far as the applicable law permits so. + +In the countries where moral rights apply, the Licensor waives his right to +exercise his moral right to the extent allowed by law in order to make effective +the licence of the economic rights here above listed. + +The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to +any patents held by the Licensor, to the extent necessary to make use of the +rights granted on the Work under this Licence. + +## 3. Communication of the Source Code + +The Licensor may provide the Work either in its Source Code form, or as +Executable Code. If the Work is provided as Executable Code, the Licensor +provides in addition a machine-readable copy of the Source Code of the Work +along with each copy of the Work that the Licensor distributes or indicates, in +a notice following the copyright notice attached to the Work, a repository where +the Source Code is easily and freely accessible for as long as the Licensor +continues to distribute or communicate the Work. + +## 4. Limitations on copyright + +Nothing in this Licence is intended to deprive the Licensee of the benefits from +any exception or limitation to the exclusive rights of the rights owners in the +Work, of the exhaustion of those rights or of other applicable limitations +thereto. + +## 5. Obligations of the Licensee + +The grant of the rights mentioned above is subject to some restrictions and +obligations imposed on the Licensee. Those obligations are the following: + +Attribution right: The Licensee shall keep intact all copyright, patent or +trademarks notices and all notices that refer to the Licence and to the +disclaimer of warranties. The Licensee must include a copy of such notices and a +copy of the Licence with every copy of the Work he/she distributes or +communicates. The Licensee must cause any Derivative Work to carry prominent +notices stating that the Work has been modified and the date of modification. + +Copyleft clause: If the Licensee distributes or communicates copies of the +Original Works or Derivative Works, this Distribution or Communication will be +done under the terms of this Licence or of a later version of this Licence +unless the Original Work is expressly distributed only under this version of the +Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee +(becoming Licensor) cannot offer or impose any additional terms or conditions on +the Work or Derivative Work that alter or restrict the terms of the Licence. + +Compatibility clause: If the Licensee Distributes or Communicates Derivative +Works or copies thereof based upon both the Work and another work licensed under +a Compatible Licence, this Distribution or Communication can be done under the +terms of this Compatible Licence. For the sake of this clause, ‘Compatible +Licence’ refers to the licences listed in the appendix attached to this Licence. +Should the Licensee's obligations under the Compatible Licence conflict with +his/her obligations under this Licence, the obligations of the Compatible +Licence shall prevail. + +Provision of Source Code: When distributing or communicating copies of the Work, +the Licensee will provide a machine-readable copy of the Source Code or indicate +a repository where this Source will be easily and freely available for as long +as the Licensee continues to distribute or communicate the Work. + +Legal Protection: This Licence does not grant permission to use the trade names, +trademarks, service marks, or names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the copyright notice. + +## 6. Chain of Authorship + +The original Licensor warrants that the copyright in the Original Work granted +hereunder is owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each Contributor warrants that the copyright in the modifications he/she brings +to the Work are owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each time You accept the Licence, the original Licensor and subsequent +Contributors grant You a licence to their contributions to the Work, under the +terms of this Licence. + +## 7. Disclaimer of Warranty + +The Work is a work in progress, which is continuously improved by numerous +Contributors. It is not a finished work and may therefore contain defects or +‘bugs’ inherent to this type of development. + +For the above reason, the Work is provided under the Licence on an ‘as is’ basis +and without warranties of any kind concerning the Work, including without +limitation merchantability, fitness for a particular purpose, absence of defects +or errors, accuracy, non-infringement of intellectual property rights other than +copyright as stated in Article 6 of this Licence. + +This disclaimer of warranty is an essential part of the Licence and a condition +for the grant of any rights to the Work. + +## 8. Disclaimer of Liability + +Except in the cases of wilful misconduct or damages directly caused to natural +persons, the Licensor will in no event be liable for any direct or indirect, +material or moral, damages of any kind, arising out of the Licence or of the use +of the Work, including without limitation, damages for loss of goodwill, work +stoppage, computer failure or malfunction, loss of data or any commercial +damage, even if the Licensor has been advised of the possibility of such damage. +However, the Licensor will be liable under statutory product liability laws as +far such laws apply to the Work. + +## 9. Additional agreements + +While distributing the Work, You may choose to conclude an additional agreement, +defining obligations or services consistent with this Licence. However, if +accepting obligations, You may act only on your own behalf and on your sole +responsibility, not on behalf of the original Licensor or any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor harmless +for any liability incurred by, or claims asserted against such Contributor by +the fact You have accepted any warranty or additional liability. + +## 10. Acceptance of the Licence + +The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ +placed under the bottom of a window displaying the text of this Licence or by +affirming consent in any other similar way, in accordance with the rules of +applicable law. Clicking on that icon indicates your clear and irrevocable +acceptance of this Licence and all of its terms and conditions. + +Similarly, you irrevocably accept this Licence and all of its terms and +conditions by exercising any rights granted to You by Article 2 of this Licence, +such as the use of the Work, the creation by You of a Derivative Work or the +Distribution or Communication by You of the Work or copies thereof. + +## 11. Information to the public + +In case of any Distribution or Communication of the Work by means of electronic +communication by You (for example, by offering to download the Work from a +remote location) the distribution channel or media (for example, a website) must +at least provide to the public the information requested by the applicable law +regarding the Licensor, the Licence and the way it may be accessible, concluded, +stored and reproduced by the Licensee. + +## 12. Termination of the Licence + +The Licence and the rights granted hereunder will terminate automatically upon +any breach by the Licensee of the terms of the Licence. + +Such a termination will not terminate the licences of any person who has +received the Work from the Licensee under the Licence, provided such persons +remain in full compliance with the Licence. + +## 13. Miscellaneous + +Without prejudice of Article 9 above, the Licence represents the complete +agreement between the Parties as to the Work. + +If any provision of the Licence is invalid or unenforceable under applicable +law, this will not affect the validity or enforceability of the Licence as a +whole. Such provision will be construed or reformed so as necessary to make it +valid and enforceable. + +The European Commission may publish other linguistic versions or new versions of +this Licence or updated versions of the Appendix, so far this is required and +reasonable, without reducing the scope of the rights granted by the Licence. New +versions of the Licence will be published with a unique version number. + +All linguistic versions of this Licence, approved by the European Commission, +have identical value. Parties can take advantage of the linguistic version of +their choice. + +## 14. Jurisdiction + +Without prejudice to specific agreement between parties, + +- any litigation resulting from the interpretation of this License, arising + between the European Union institutions, bodies, offices or agencies, as a + Licensor, and any Licensee, will be subject to the jurisdiction of the Court + of Justice of the European Union, as laid down in article 272 of the Treaty on + the Functioning of the European Union, + +- any litigation arising between other parties and resulting from the + interpretation of this License, will be subject to the exclusive jurisdiction + of the competent court where the Licensor resides or conducts its primary + business. + +## 15. Applicable Law + +Without prejudice to specific agreement between parties, + +- this Licence shall be governed by the law of the European Union Member State + where the Licensor has his seat, resides or has his registered office, + +- this licence shall be governed by Belgian law if the Licensor has no seat, + residence or registered office inside a European Union Member State. + +## Appendix + +‘Compatible Licences’ according to Article 5 EUPL are: + +- GNU General Public License (GPL) v. 2, v. 3 +- GNU Affero General Public License (AGPL) v. 3 +- Open Software License (OSL) v. 2.1, v. 3.0 +- Eclipse Public License (EPL) v. 1.0 +- CeCILL v. 2.0, v. 2.1 +- Mozilla Public Licence (MPL) v. 2 +- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 +- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for + works other than software +- European Union Public Licence (EUPL) v. 1.1, v. 1.2 +- Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong + Reciprocity (LiLiQ-R+). + +The European Commission may update this Appendix to later versions of the above +licences without producing a new version of the EUPL, as long as they provide +the rights granted in Article 2 of this Licence and protect the covered Source +Code from exclusive appropriation. + +All other changes or additions to this Appendix require the production of a new +EUPL version. diff --git a/packages/strapi-provider-media-upload/README.md b/packages/strapi-provider-media-upload/README.md new file mode 100644 index 000000000..6958fa3a4 --- /dev/null +++ b/packages/strapi-provider-media-upload/README.md @@ -0,0 +1,99 @@ +# @frameless/strapi-provider-media-upload + +## Description + +A custom Strapi provider plugin for handling local media uploads with support for MIME type filtering via the `allowedMimeTypes` option. + +This plugin is **based on Strapi's official [upload-local provider](https://github.com/strapi/strapi/tree/develop/packages/providers/upload-local)** and extends it with additional validation through the `allowedMimeTypes` option. + +## Features + +- Upload files to the local filesystem (public/uploads) +- Validate MIME types before uploading +- Reject unsupported file types with proper error messages +- Compatible with Strapi v4 + +## Installation + +To install this Strapi plugin, you can use npm or yarn: + +```bash +yarn add @frameless/strapi-provider-media-upload +# or +npm install @frameless/strapi-provider-media-upload +``` + +## Configuration + +### Strapi Configuration + +To configure this plugin in your Strapi server, follow these steps: + +1. Navigate to your Strapi project directory. + +2. Locate the `/config/plugins.ts` file. + +3. Open the `plugins.ts` file for editing. + +4. Add the following configuration to set up the Vercel provider: + + ```ts + export default ({ env }) => ({ + upload: { + config: { + provider: "@frameless/strapi-provider-media-upload", + providerOptions: { + allowedMimeTypes: ["image/jpeg", "image/png", "image/webp", "application/pdf"], // Adjust as needed + sizeLimit: 1000000, // in bytes (optional) + // uploadPath: 'uploads', // defaults to 'uploads' inside public dir (optional, if supported) + }, + }, + }, + // ... other plugins and configurations + }); + ``` + +5. Build the dashboard before you run the server by following the commands below + +```bash + yarn build && yarn dev +``` + +## Available Options + +| Option | Type | Required | Default | Description | +| ------------------ | ---------- | -------- | ----------- | ------------------------------------------------------------------------------ | +| `allowedMimeTypes` | `string[]` | No | `undefined` | List of allowed MIME types. If not set, all types are allowed. | +| `sizeLimit` | `number` | No | `undefined` | Maximum allowed file size in **bytes**. Files exceeding this will be rejected. | +| `uploadPath` | `string` | No | `uploads` | Folder name inside `public/` where files are stored (if configurable). | + +> ⚠️ Ensure the public/uploads directory exists and is writable by the server. + +## MIME Type Filtering + +When `allowedMimeTypes` is defined, any file that does not match will be rejected with a 400 error: + +```bash +somefile.exe has unsupported file type: application/x-msdownload. Only JPEG, PNG, PDF are allowed. + +``` + +## Based On + +This plugin is adapted from the official [`upload-local`](https://github.com/strapi/strapi/tree/develop/packages/providers/upload-local) provider, with minor enhancements to support file type filtering. + +## License + +This plugin is released under the [EUPL-1.2 License](./LICENSE). + +## Author + +Created by [Frameless](https://github.com/frameless). + +## Development + +If you want to contribute to this plugin or build it locally, you can follow these development instructions: + +1. Clone the repository from GitHub. +2. Install the necessary development dependencies using `yarn install`. +3. Build the plugin using `yarn build`. diff --git a/packages/strapi-provider-media-upload/custom.d.ts b/packages/strapi-provider-media-upload/custom.d.ts new file mode 100644 index 000000000..ce7570326 --- /dev/null +++ b/packages/strapi-provider-media-upload/custom.d.ts @@ -0,0 +1,6 @@ +declare module '@strapi/design-system/*'; +declare module '@strapi/design-system'; +declare module '@strapi/icons'; +declare module '@strapi/icons/*'; +declare module '@strapi/helper-plugin'; +declare module 'rollup-plugin-peer-deps-external'; diff --git a/packages/strapi-provider-media-upload/package.json b/packages/strapi-provider-media-upload/package.json new file mode 100644 index 000000000..a6712fa7a --- /dev/null +++ b/packages/strapi-provider-media-upload/package.json @@ -0,0 +1,51 @@ +{ + "name": "@frameless/strapi-provider-media-upload", + "version": "0.0.0", + "description": "Local provider for strapi upload", + "private": true, + "keywords": [ + "blob", + "upload", + "strapi", + "provider" + ], + "main": "./dist/index.cjs.js", + "module": "./dist/index.esm.js", + "types": "./dist/src/index.d.ts", + "license": "EUPL-1.2", + "files": [ + "dist/" + ], + "repository": { + "type": "git+ssh", + "url": "git@github.com:frameless/strapi.git", + "directory": "packages/strapi-provider-media-upload" + }, + "author": "Frameless", + "scripts": { + "prebuild": "yarn clean", + "build": "rollup --config rollup.config.ts --configPlugin typescript", + "watch": "rollup --config rollup.config.ts --configPlugin typescript -w", + "clean": "rimraf dist .rollup.cache", + "lint-build": "tsc --noEmit --project tsconfig.json" + }, + "dependencies": { + "@strapi/utils": "5.14.0", + "fs-extra": "11.3.0" + }, + "devDependencies": { + "@types/fs-extra": "11.0.4", + "rollup-plugin-typescript2": "0.35.0", + "@rollup/plugin-typescript": "11.1.6", + "rollup": "3.29.4", + "@rollup/plugin-terser": "0.4.4", + "@rollup/plugin-commonjs": "25.0.7", + "@rollup/plugin-json": "6.0.1", + "@rollup/plugin-node-resolve": "15.2.3", + "rollup-plugin-peer-deps-external": "2.2.4", + "rollup-plugin-terser": "7.0.2" + }, + "engines": { + "node": "20.x.x" + } +} diff --git a/packages/strapi-provider-media-upload/rollup.config.ts b/packages/strapi-provider-media-upload/rollup.config.ts new file mode 100644 index 000000000..658661a0b --- /dev/null +++ b/packages/strapi-provider-media-upload/rollup.config.ts @@ -0,0 +1,37 @@ +import commonjs from '@rollup/plugin-commonjs'; +import json from '@rollup/plugin-json'; +import { nodeResolve } from '@rollup/plugin-node-resolve'; +import { readFileSync } from 'fs'; +import { RollupOptions } from 'rollup'; +import peerDepsExternal from 'rollup-plugin-peer-deps-external'; +import { terser } from 'rollup-plugin-terser'; +import typescript from 'rollup-plugin-typescript2'; + +const packageJson = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')); + +const config: RollupOptions = { + input: 'src/index.ts', + output: [ + { + file: packageJson.main, + format: 'cjs', + exports: 'auto', + }, + { + file: packageJson.module, + format: 'esm', + }, + ], + plugins: [ + typescript({ + tsconfig: 'tsconfig.json', + }), + nodeResolve(), + commonjs(), + terser(), + peerDepsExternal(), + json(), + ], +}; + +export default config; diff --git a/packages/strapi-provider-media-upload/src/index.ts b/packages/strapi-provider-media-upload/src/index.ts new file mode 100644 index 000000000..2ac4581c7 --- /dev/null +++ b/packages/strapi-provider-media-upload/src/index.ts @@ -0,0 +1,147 @@ +import type { Strapi } from '@strapi/strapi'; +import * as utils from '@strapi/utils'; +import fs, { ReadStream } from 'fs'; +import fse from 'fs-extra'; +import path from 'path'; +import { pipeline } from 'stream'; + +interface File { + name: string; + alternativeText?: string; + caption?: string; + width?: number; + height?: number; + formats?: Record; + hash: string; + ext?: string; + mime: string; + size: number; + sizeInBytes: number; + url: string; + previewUrl?: string; + path?: string; + provider?: string; + provider_metadata?: Record; + stream?: ReadStream; + buffer?: Buffer; +} + +const { PayloadTooLargeError, ValidationError } = utils.errors; +const { kbytesToBytes, bytesToHumanReadable } = utils.file; + +const UPLOADS_FOLDER_NAME = 'uploads'; + +interface InitOptions { + allowedMimeTypes?: string[]; +} + +interface CheckFileOptions { + sizeLimit?: number; + allowedMimeTypes?: string[]; +} + +export default { + init({ allowedMimeTypes }: InitOptions = {}) { + const strapiGlobal = global.strapi as Strapi; + // Ensure uploads folder exists + if (!strapiGlobal || !strapiGlobal.dirs?.static?.public) { + throw new Error('Strapi global object with dirs.static.public is not available.'); + } + + const uploadPath = path.resolve(strapiGlobal.dirs.static.public, UPLOADS_FOLDER_NAME); + if (!fse.pathExistsSync(uploadPath)) { + throw new Error( + `The upload folder (${uploadPath}) doesn't exist or is not accessible. Please make sure it exists.`, + ); + } + + // Helper to check size and mime type + const checkFile = (file: File, options: CheckFileOptions) => { + const { sizeLimit, allowedMimeTypes } = options; + + // Size check + const limit = sizeLimit; + if (limit && kbytesToBytes(file.size) > limit) { + throw new PayloadTooLargeError(`${file.name} exceeds size limit of ${bytesToHumanReadable(limit)}.`); + } + + // Mime type check + if (allowedMimeTypes && !allowedMimeTypes.includes(file.mime)) { + const allowedTypes = allowedMimeTypes.map((type) => type.split('/')[1].toUpperCase()).join(', '); + const message = `${file.name} has unsupported file type: ${file.mime}. Only ${allowedTypes} are allowed.`; + + const error = new ValidationError(message); + (error as any).status = 400; + + throw error; + } + }; + + return { + checkFileSize(file: File, options: CheckFileOptions) { + checkFile(file, options); + }, + + uploadStream(file: File): Promise { + checkFile(file, { allowedMimeTypes }); + + if (!file.stream) { + return Promise.reject(new Error('Missing file stream')); + } + + const { stream } = file; + + return new Promise((resolve, reject) => { + pipeline(stream, fs.createWriteStream(path.join(uploadPath, `${file.hash}${file.ext}`)), (err) => { + if (err) { + return reject(err); + } + + file.url = `/${UPLOADS_FOLDER_NAME}/${file.hash}${file.ext}`; + resolve(); + }); + }); + }, + + upload(file: File): Promise { + checkFile(file, { allowedMimeTypes }); + + if (!file.buffer) { + return Promise.reject(new Error('Missing file buffer')); + } + + const { buffer } = file; + + return new Promise((resolve, reject) => { + fs.writeFile(path.join(uploadPath, `${file.hash}${file.ext}`), buffer, (err) => { + if (err) { + return reject(err); + } + + file.url = `/${UPLOADS_FOLDER_NAME}/${file.hash}${file.ext}`; + resolve(); + }); + }); + }, + + delete(file: File): Promise { + return new Promise((resolve, reject) => { + const filePath = path.join(uploadPath, `${file.hash}${file.ext}`); + + if (!fs.existsSync(filePath)) { + resolve("File doesn't exist"); + return; + } + + fs.unlink(filePath, (err) => { + if (err) { + return reject(err); + } + + resolve(); + }); + }); + }, + }; + }, +}; diff --git a/packages/strapi-provider-media-upload/tsconfig.json b/packages/strapi-provider-media-upload/tsconfig.json new file mode 100644 index 000000000..34c9a7c75 --- /dev/null +++ b/packages/strapi-provider-media-upload/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "es5", + "allowJs": true, + "allowSyntheticDefaultImports": true, + "allowUnreachableCode": false, + "composite": true, + "declaration": true, + "esModuleInterop": true, + "experimentalDecorators": true, + "forceConsistentCasingInFileNames": true, + "incremental": true, + "isolatedModules": true, + "lib": ["es2020"], + "module": "es2020", + "moduleResolution": "node", + "noUnusedLocals": true, + "noUnusedParameters": true, + "outDir": "dist", + "resolveJsonModule": true, + "rootDir": ".", + "skipLibCheck": true, + "strict": true + }, + "include": ["src/**/*", "rollup.config.ts", "custom.d.ts"], + "exclude": ["node_modules", "**/*.test.ts"] +} diff --git a/yarn.lock b/yarn.lock index 1aee974bd..3eaa12ce9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6785,6 +6785,23 @@ p-map "4.0.0" yup "0.32.9" +"@strapi/utils@5.14.0": + version "5.14.0" + resolved "https://registry.yarnpkg.com/@strapi/utils/-/utils-5.14.0.tgz#c1b6865bbd145e62e9bf25a3c7f1b2133cc55b4a" + integrity sha512-PAcTr9A2tInXXvY8IjtEqDxxOOMrCAxeLDr7wB3I7OTu5Nhxk2sTvp2o3l2/E/kj6BAAam3u1QofDD0ViQYJMg== + dependencies: + "@sindresorhus/slugify" "1.1.0" + date-fns "2.30.0" + execa "5.1.1" + http-errors "2.0.0" + json-logic-js "2.0.5" + lodash "4.17.21" + node-machine-id "1.1.12" + p-map "4.0.0" + preferred-pm "3.1.2" + yup "0.32.9" + zod "3.24.2" + "@svgr/babel-plugin-add-jsx-attribute@8.0.0": version "8.0.0" resolved "https://registry.yarnpkg.com/@svgr/babel-plugin-add-jsx-attribute/-/babel-plugin-add-jsx-attribute-8.0.0.tgz#4001f5d5dd87fa13303e36ee106e3ff3a7eb8b22" @@ -15624,6 +15641,15 @@ fs-extra@10.0.0: jsonfile "^6.0.1" universalify "^2.0.0" +fs-extra@11.3.0: + version "11.3.0" + resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-11.3.0.tgz#0daced136bbaf65a555a326719af931adc7a314d" + integrity sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew== + dependencies: + graceful-fs "^4.2.0" + jsonfile "^6.0.1" + universalify "^2.0.0" + fs-extra@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-10.1.0.tgz#02873cfbc4084dde127eaa5f9905eef2325d1abf" @@ -18834,7 +18860,7 @@ json-buffer@3.0.1: resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.1.tgz#9338802a30d3b6605fbe0613e094008ca8c05a13" integrity sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ== -json-logic-js@^2.0.0, json-logic-js@^2.0.2: +json-logic-js@2.0.5, json-logic-js@^2.0.0, json-logic-js@^2.0.2: version "2.0.5" resolved "https://registry.yarnpkg.com/json-logic-js/-/json-logic-js-2.0.5.tgz#55f0c687dd6f56b02ccdcfdd64171ed998ab5499" integrity sha512-rTT2+lqcuUmj4DgWfmzupZqQDA64AdmYqizzMPWj3DxGdfFNsxPpcNVSaTj4l8W2tG/+hg7/mQhxjU3aPacO6g== @@ -24038,6 +24064,16 @@ prebuild-install@^7.1.0, prebuild-install@^7.1.1: tar-fs "^2.0.0" tunnel-agent "^0.6.0" +preferred-pm@3.1.2: + version "3.1.2" + resolved "https://registry.yarnpkg.com/preferred-pm/-/preferred-pm-3.1.2.tgz#aedb70550734a574dffcbf2ce82642bd1753bdd6" + integrity sha512-nk7dKrcW8hfCZ4H6klWcdRknBOXWzNQByJ0oJyX97BOupsYD+FzLS4hflgEu/uPUEHZCuRfMxzCBsuWd7OzT8Q== + dependencies: + find-up "^5.0.0" + find-yarn-workspace-root2 "1.2.16" + path-exists "^4.0.0" + which-pm "2.0.0" + preferred-pm@^3.0.0: version "3.1.4" resolved "https://registry.yarnpkg.com/preferred-pm/-/preferred-pm-3.1.4.tgz#b99cf3da129cdb63555649b226b7530e82769769" @@ -29705,6 +29741,14 @@ which-module@^2.0.0: resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.1.tgz#776b1fe35d90aebe99e8ac15eb24093389a4a409" integrity sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ== +which-pm@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/which-pm/-/which-pm-2.0.0.tgz#8245609ecfe64bf751d0eef2f376d83bf1ddb7ae" + integrity sha512-Lhs9Pmyph0p5n5Z3mVnN0yWcbQYUAD7rbQUiMsQxOJ3T57k7RFe35SUwWMf7dsbDZks1uOmw4AecB/JMDj3v/w== + dependencies: + load-yaml-file "^0.2.0" + path-exists "^4.0.0" + which-pm@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/which-pm/-/which-pm-2.2.0.tgz#6b5d8efd7b5089b97cd51a36c60dd8e4ec7eca59" @@ -30134,6 +30178,11 @@ zod-formik-adapter@^1.2.0: resolved "https://registry.yarnpkg.com/zod-formik-adapter/-/zod-formik-adapter-1.3.0.tgz#02c1c07791f315032499063eab29355098a2e9fc" integrity sha512-qWsVwRYqpRod5BL35pRXHD6UOugiyaEyLPO04rCN/uKTCFCR+VElPEG26+3wNrxGP7y5XmJM+4/0MrABnRYZrw== +zod@3.24.2: + version "3.24.2" + resolved "https://registry.yarnpkg.com/zod/-/zod-3.24.2.tgz#8efa74126287c675e92f46871cfc8d15c34372b3" + integrity sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ== + zod@^3.21.4: version "3.23.8" resolved "https://registry.yarnpkg.com/zod/-/zod-3.23.8.tgz#e37b957b5d52079769fb8097099b592f0ef4067d"