UNPKG

@nocobase/plugin-file-manager

Version:

Provides files storage services with files collection template and attachment field.

220 lines (218 loc) • 8.24 kB
/** * This file is part of the NocoBase (R) project. * Copyright (c) 2020-2024 NocoBase Co., Ltd. * Authors: NocoBase Team. * * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. * For more information, please refer to: https://www.nocobase.com/agreement. */ var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var utils_exports = {}; __export(utils_exports, { cloudFilenameGetter: () => cloudFilenameGetter, diskFilenameGetter: () => diskFilenameGetter, encodeURL: () => encodeURL, ensureUrlEncoded: () => ensureUrlEncoded, getFileKey: () => getFileKey, getFilename: () => getFilename, normalizeDocumentRoot: () => normalizeDocumentRoot, normalizeStorageSubPath: () => normalizeStorageSubPath, resolveStoragePath: () => resolveStoragePath }); module.exports = __toCommonJS(utils_exports); var import_utils = require("@nocobase/utils"); var import_crypto = __toESM(require("crypto")); var import_path = __toESM(require("path")); var import_url_join = __toESM(require("url-join")); const INVALID_FILENAME_CHARS = /* @__PURE__ */ new Set(["<", ">", "?", "*", "|", ":", '"', "\\", "/"]); function sanitizeFilename(value) { return Array.from(value).map((char) => { const code = char.charCodeAt(0); return code < 32 || code === 127 || INVALID_FILENAME_CHARS.has(char) ? "-" : char; }).join(""); } function normalizeOriginalname(file) { const originalname = file == null ? void 0 : file.originalname; if (!originalname) { return ""; } if (Buffer.isBuffer(originalname)) { return originalname.toString("utf8"); } if (Array.from(originalname).some((char) => char.charCodeAt(0) > 255)) { return originalname; } const decoded = Buffer.from(originalname, "binary").toString("utf8"); if (decoded.includes("\uFFFD")) { return originalname; } return decoded; } function getFilename(req, file, cb) { const originalname = normalizeOriginalname(file); const baseName = import_path.default.basename(sanitizeFilename(originalname), import_path.default.extname(originalname)); cb(null, `${baseName}-${(0, import_utils.uid)(6)}${import_path.default.extname(originalname)}`); } function getOriginalFilename(file) { const originalname = normalizeOriginalname(file); const extname = import_path.default.extname(originalname); const baseName = import_path.default.basename(sanitizeFilename(originalname), extname); return `${baseName}${extname}`; } const cloudFilenameGetter = (storage) => (req, file, cb) => { const renameMode = storage.renameMode; if (renameMode === "random") { import_crypto.default.randomBytes(16, function(err, raw) { if (err) { return cb(err); } const filename = `${raw.toString("hex")}${import_path.default.extname(normalizeOriginalname(file))}`; cb(null, `${storage.path ? `${storage.path.replace(/\/+$/, "")}/` : ""}${filename}`); }); return; } if (renameMode === "none") { const filename = getOriginalFilename(file); cb(null, `${storage.path ? `${storage.path.replace(/\/+$/, "")}/` : ""}${filename}`); return; } getFilename(req, file, (err, filename) => { if (err) { return cb(err); } cb(null, `${storage.path ? `${storage.path.replace(/\/+$/, "")}/` : ""}${filename}`); }); }; const diskFilenameGetter = (storage) => (req, file, cb) => { const renameMode = storage.renameMode; if (renameMode === "random") { import_crypto.default.randomBytes(16, function(err, raw) { if (err) { return cb(err); } const filename = `${raw.toString("hex")}${import_path.default.extname(normalizeOriginalname(file))}`; cb(null, filename); }); return; } if (renameMode === "none") { cb(null, getOriginalFilename(file)); return; } getFilename(req, file, cb); }; function getFileKey(record) { return (0, import_url_join.default)(record.path || "", record.filename).replace(/^\//, ""); } function pathError(message) { const error = new Error(message); error.code = "PATH_TRAVERSAL"; return error; } function normalizeStoragePathForJoin(value, message, { allowLeadingSlash = false } = {}) { if (value == null || value === "") { return ""; } if (typeof value !== "string" || value.includes("\0")) { throw pathError(message); } const normalized = value.replace(/\\/g, "/"); if (!allowLeadingSlash && normalized.startsWith("/")) { throw pathError(message); } const segments = normalized.replace(/^\/+|\/+$/g, "").split("/").filter((segment) => segment && segment !== "."); if (segments.some((segment) => segment === "..")) { throw pathError("Access denied"); } return segments.join("/"); } function normalizeStorageSubPath(subPath) { return normalizeStoragePathForJoin(subPath, "Invalid storage sub path"); } function resolveStoragePath(storagePath, subPath) { const normalizedSubPath = normalizeStorageSubPath(subPath); if (!normalizedSubPath) { return typeof storagePath === "string" ? storagePath : ""; } const normalizedStoragePath = normalizeStoragePathForJoin(storagePath, "Invalid storage path", { allowLeadingSlash: true }); return normalizedStoragePath ? `${normalizedStoragePath}/${normalizedSubPath}` : normalizedSubPath; } function ensureUrlEncoded(value) { try { if (decodeURIComponent(value) !== value) { return value; } } catch (e) { return encodeURIComponent(value); } return encodeURIComponent(value); } function encodePathKeepSlash(path2) { return path2.split("/").map((segment) => ensureUrlEncoded(segment)).join("/"); } function encodeURL(url) { try { const parsedUrl = new URL(url); parsedUrl.pathname = encodePathKeepSlash(parsedUrl.pathname); return parsedUrl.toString(); } catch (error) { return url; } } function isStorageRelativeDocumentRoot(documentRoot) { return documentRoot === "storage" || documentRoot.startsWith("storage/") || documentRoot === "./storage" || documentRoot.startsWith("./storage/"); } function normalizeDocumentRoot(documentRoot) { if (!documentRoot) { return (0, import_utils.storagePathJoin)("uploads"); } if (import_path.default.isAbsolute(documentRoot)) { return documentRoot; } const normalizedDocumentRoot = documentRoot.replace(/\\/g, "/"); if (isStorageRelativeDocumentRoot(normalizedDocumentRoot)) { const relativePath = normalizedDocumentRoot.replace(/^\.?\/?storage(?:\/|$)/, "").replace(/^[/\\]+/, ""); return relativePath ? (0, import_utils.storagePathJoin)(relativePath) : (0, import_utils.storagePathJoin)(); } return import_path.default.resolve(process.cwd(), documentRoot); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { cloudFilenameGetter, diskFilenameGetter, encodeURL, ensureUrlEncoded, getFileKey, getFilename, normalizeDocumentRoot, normalizeStorageSubPath, resolveStoragePath });