mirror of
https://github.com/wekan/wekan.git
synced 2026-11-25 17:45:18 -05:00
Every attachment gets its SHA-256 (contentHash: value, size, time) and its plain search text (with the time it was made) when it is added, and - for one added before this - the first time it is read whole. Text, Markdown, CSV, code, JSON, HTML and e-mail are read as text, PDF and Office through the document extractor, Outlook .msg and OpenDocument from their slideshow rows. A new attachment's "Added" card history row carries its hash, and so do the soft delete and restore rows. Each whole read hashes the bytes on their way out, with no second read: no stored hash - it is stored; the same - nothing; another hash that the card history knows - an earlier version an undo or restore brought back - a new hash and search text are made; anything else - a warning in Admin Panel / Problems (integrity), keeping the stored hash. A range is no evidence. Filter's text field, the board's Search and Search All Boards find a card by its attachments' text; each index row is checked against its live attachment on that card, and the text is never sent to the browser. tests/attachmentContent.test.cjs pins the decisions and the wiring; tests/playwright/specs/attachment-content-search.e2e.js adds a file, finds it three ways, changes it on disk (warned), reads a range (nothing) and brings back a known version (accepted, indexed again). Thanks to xet7 !
1140 lines
43 KiB
JavaScript
1140 lines
43 KiB
JavaScript
import { readAuthenticatedLegacyAvatar } from '/server/lib/legacyAvatarRead';
|
|
/**
|
|
* Universal File Server
|
|
* Ensures all attachments and avatars are always visible regardless of ROOT_URL and PORT settings
|
|
* Handles both new Meteor-Files and legacy CollectionFS file serving
|
|
*/
|
|
|
|
import { Meteor } from 'meteor/meteor';
|
|
import { check } from 'meteor/check';
|
|
import { WebApp } from 'meteor/webapp';
|
|
import { ReactiveCache } from '/imports/reactiveCache';
|
|
import Attachments from '/models/attachments';
|
|
import AttachmentStorageSettings from '/models/attachmentStorageSettings';
|
|
import { STORAGE_NAME_FILESYSTEM, STORAGE_NAME_GRIDFS } from '/models/lib/fileStoreConstants';
|
|
import { fileStoreStrategyFactory as attachmentStoreFactory } from '/models/attachments.server';
|
|
import Avatars from '/models/avatars';
|
|
import { fileStoreStrategyFactory as avatarStoreFactory } from '/models/avatars.server';
|
|
import { correctedNameForStoredFile } from '/models/lib/fileTypeCorrection';
|
|
import Boards from '/models/boards';
|
|
import Settings from '/models/settings';
|
|
const {isActiveSiteLogo} = require('/models/lib/siteLogo');
|
|
import { getAttachmentWithBackwardCompatibility, getOldAttachmentStream } from '/models/lib/attachmentBackwardCompatibility';
|
|
import { canReadBoard } from '/models/lib/boardVisibility';
|
|
import { assignedOnlyCardIds, mayReadBoardAttachment } from '/server/lib/assignedOnlyAttachments';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import { DocumentPreviews, indexDocumentText } from '/server/lib/documentGif';
|
|
import { boundedStreamBuffer, gifCacheKey } from '/server/lib/imageGif';
|
|
import { convertImageBufferToThumbnail, cachedThumbnail, rememberThumbnail } from '/server/lib/imageThumbnail';
|
|
const { isThumbnailPath, canThumbnail, THUMBNAIL_TYPE } = require('/models/lib/attachmentThumbnail');
|
|
const { previewPartOf } = require('/models/lib/attachmentPreviewPath');
|
|
// CacheBleed (GHSA-w3qg-pf27-g68r): files are served after an access check, so never shared-cacheable.
|
|
const { setPrivateFileCacheHeaders, privateFileCacheHeaders } = require('/models/lib/fileCacheHeaders');
|
|
const { parseRange, partialContentHeaders, ifRangeAllows } = require('/models/lib/httpRange');
|
|
import { sanitizeFilenameForHeader, buildContentDispositionHeader } from '/server/lib/contentDisposition';
|
|
// SVG is served sanitized, as an image (server/lib/svgResponse.js).
|
|
const svgResponse = require('/server/lib/svgResponse');
|
|
// The avatar types served inline; anything else is a download (AvatarMimeBleed).
|
|
const INLINE_AVATAR_TYPES = new Set(['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp', 'image/avif', 'image/bmp']);
|
|
const { readableWithoutMembership } = require('/models/lib/boardPermission');
|
|
|
|
async function normalizeStoredNameOnRead(collection, fileObj, factory) {
|
|
if (!fileObj) return fileObj;
|
|
const result = await correctedNameForStoredFile(fileObj, factory);
|
|
if (!result.changed) return fileObj;
|
|
const originalName = fileObj.name;
|
|
const dot = result.name.lastIndexOf('.');
|
|
const extension = dot > 0 ? result.name.slice(dot + 1).toLowerCase() : '';
|
|
await collection.updateAsync({ _id: fileObj._id }, { $set: {
|
|
name: result.name,
|
|
extension,
|
|
extensionWithDot: extension ? `.${extension}` : '',
|
|
} });
|
|
fileObj.name = result.name;
|
|
try {
|
|
await require('/server/lib/filenameSanitizeLog').logFilenameSanitized({
|
|
fileObj,
|
|
source: 'fileRead',
|
|
reasons: require('/models/lib/uploadFileName').sanitizationReasons(
|
|
originalName,
|
|
result.detectedMime || fileObj.type,
|
|
result.name,
|
|
),
|
|
from: originalName,
|
|
to: result.name,
|
|
});
|
|
} catch (e) { /* filename correction must not prevent the read */ }
|
|
return fileObj;
|
|
}
|
|
|
|
function parseNonNegativeInt(value, fallback = 0) {
|
|
const parsed = Number.parseInt(value, 10);
|
|
if (!Number.isFinite(parsed) || parsed < 0) {
|
|
return fallback;
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
async function getAttachmentDownloadLimitSettings() {
|
|
const fallbackMaxBytes = parseNonNegativeInt(process.env.ATTACHMENT_API_MAX_DOWNLOAD_BYTES, 0);
|
|
|
|
try {
|
|
const settings = await AttachmentStorageSettings.findOneAsync({});
|
|
const blocked = settings?.limitSettings?.attachmentsDownloadBlocked === true;
|
|
const configuredLimit = settings?.limitSettings?.attachmentsDownloadMaxBytes;
|
|
if (Number.isFinite(configuredLimit) && configuredLimit >= 0) {
|
|
return {
|
|
blocked,
|
|
maxBytes: configuredLimit,
|
|
};
|
|
}
|
|
|
|
// Backward compatibility: if no dedicated value exists, reuse API download limit when present.
|
|
const apiDownloadFallback = settings?.limitSettings?.apiDownloadMaxBytes;
|
|
if (Number.isFinite(apiDownloadFallback) && apiDownloadFallback >= 0) {
|
|
return {
|
|
blocked,
|
|
maxBytes: apiDownloadFallback,
|
|
};
|
|
}
|
|
|
|
return {
|
|
blocked,
|
|
maxBytes: fallbackMaxBytes,
|
|
};
|
|
} catch (error) {
|
|
if (process.env.DEBUG === 'true') {
|
|
console.warn('Could not load attachment download limit from settings:', error);
|
|
}
|
|
}
|
|
|
|
return {
|
|
blocked: false,
|
|
maxBytes: fallbackMaxBytes,
|
|
};
|
|
}
|
|
|
|
// Indexes an attachment's text for search only - no client-facing route.
|
|
// The viewer no longer reads this: DOCX/XLSX/PPTX render client-side via
|
|
// office-open-xml-viewer and PDF renders via the browser's native <embed>.
|
|
// Called from Attachments.onAfterUpload in the background, since nothing
|
|
// fetches a preview manifest to trigger indexing lazily any more.
|
|
export async function indexAttachmentDocumentText(attachment) {
|
|
const settings = await AttachmentStorageSettings.findOneAsync({});
|
|
const storage = settings?.getDefaultStorage?.() || STORAGE_NAME_FILESYSTEM;
|
|
if (settings?.isStorageWriteEnabled && !settings.isStorageWriteEnabled(storage)) {
|
|
throw new Error('Default attachment storage is not writable');
|
|
}
|
|
return indexDocumentText(attachment, {
|
|
factory: attachmentStoreFactory, collection: Attachments.collection,
|
|
getDefaultStorage: async () => storage,
|
|
});
|
|
}
|
|
|
|
if (Meteor.isServer) {
|
|
console.log('Universal file server initializing...');
|
|
|
|
Meteor.methods({
|
|
async searchAttachmentDocumentText(boardId, query) {
|
|
check(boardId, String);
|
|
check(query, String);
|
|
const needle = query.normalize('NFKC').replace(/\s+/g, ' ').trim().slice(0, 200);
|
|
if (needle.length < 2) return [];
|
|
const board = await ReactiveCache.getBoard(boardId);
|
|
if (!board || !(await canReadBoard(this.userId, board))) {
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
// An assigned-only member searches only their own cards' documents
|
|
// (AssignedBleed, GHSA-3cgr-47wm-9cc9): boardId alone matched the
|
|
// extracted text of every card. Ordinary use, so nothing is logged.
|
|
const assignedCardIds = await assignedOnlyCardIds(board, this.userId);
|
|
const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
const rows = await DocumentPreviews.find(
|
|
{ boardId, searchText: { $regex: escaped, $options: 'i' },
|
|
...(assignedCardIds ? { cardId: { $in: assignedCardIds } } : {}) },
|
|
{ fields: { attachmentId: 1, cardId: 1, searchText: 1 }, limit: 50 },
|
|
).fetchAsync();
|
|
return rows.map(row => {
|
|
const at = row.searchText.toLocaleLowerCase().indexOf(needle.toLocaleLowerCase());
|
|
return { attachmentId: row.attachmentId, cardId: row.cardId,
|
|
snippet: row.searchText.slice(Math.max(0, at - 80), Math.max(0, at - 80) + 240) };
|
|
});
|
|
},
|
|
});
|
|
|
|
/**
|
|
* Helper function to set appropriate headers for file serving
|
|
*/
|
|
function setFileHeaders(res, fileObj, isAttachment = false) {
|
|
// Decide safe serving strategy
|
|
const nameLower = (fileObj.name || '').toLowerCase();
|
|
const typeLower = (fileObj.type || '').toLowerCase();
|
|
const isPdfByExt = nameLower.endsWith('.pdf');
|
|
|
|
// Define dangerous types that must never be served inline
|
|
const dangerousTypes = new Set([
|
|
'text/html',
|
|
'application/xhtml+xml',
|
|
'image/svg+xml',
|
|
'text/xml',
|
|
'application/xml',
|
|
'application/javascript',
|
|
'text/javascript'
|
|
]);
|
|
|
|
// Define safe types that can be served inline for viewing
|
|
const safeInlineTypes = new Set([
|
|
'application/pdf',
|
|
'image/jpeg',
|
|
'image/jpg',
|
|
'image/png',
|
|
'image/gif',
|
|
'image/webp',
|
|
'image/avif',
|
|
'image/bmp',
|
|
'video/mp4',
|
|
'video/webm',
|
|
'video/ogg',
|
|
'audio/mpeg',
|
|
'audio/mp3',
|
|
'audio/ogg',
|
|
'audio/wav',
|
|
'audio/webm',
|
|
'text/plain',
|
|
'application/json'
|
|
]);
|
|
|
|
const isSvg = nameLower.endsWith('.svg') || typeLower === 'image/svg+xml';
|
|
const isDangerous = dangerousTypes.has(typeLower) || isSvg;
|
|
// Consider PDF safe inline by extension if type is missing/mis-set
|
|
const isSafeInline = safeInlineTypes.has(typeLower) || (isAttachment && isPdfByExt);
|
|
|
|
// Private, revalidated caching (CacheBleed) and integrity headers
|
|
setPrivateFileCacheHeaders(res);
|
|
res.setHeader('ETag', `"${fileObj._id}"`);
|
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
|
|
// Set content length when available
|
|
if (fileObj.size) {
|
|
res.setHeader('Content-Length', fileObj.size);
|
|
}
|
|
|
|
if (isAttachment) {
|
|
// Attachments: dangerous types forced to download, safe types can be inline
|
|
if (isDangerous) {
|
|
// SECURITY: Force download for dangerous types to prevent XSS
|
|
res.setHeader('Content-Type', 'application/octet-stream');
|
|
res.setHeader('Content-Disposition', buildContentDispositionHeader('attachment', sanitizeFilenameForHeader(fileObj.name)));
|
|
res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox;");
|
|
res.setHeader('X-Frame-Options', 'DENY');
|
|
} else if (isSafeInline) {
|
|
// Safe types: serve inline with proper type and restrictive CSP
|
|
// If the file is a PDF by extension but type is wrong/missing, correct it
|
|
const finalType = (isPdfByExt && typeLower !== 'application/pdf') ? 'application/pdf' : (typeLower || 'application/octet-stream');
|
|
res.setHeader('Content-Type', finalType);
|
|
res.setHeader('Content-Disposition', buildContentDispositionHeader('inline', sanitizeFilenameForHeader(fileObj.name)));
|
|
// Restrictive CSP for safe types - allow media/img/object for viewer embeds, no scripts
|
|
res.setHeader('Content-Security-Policy', "default-src 'none'; object-src 'self'; media-src 'self'; img-src 'self'; style-src 'unsafe-inline';");
|
|
} else {
|
|
// Unknown types: force download as fallback
|
|
res.setHeader('Content-Type', 'application/octet-stream');
|
|
res.setHeader('Content-Disposition', buildContentDispositionHeader('attachment', sanitizeFilenameForHeader(fileObj.name)));
|
|
res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox;");
|
|
}
|
|
} else {
|
|
// Avatars: allow inline images, but never serve SVG inline
|
|
if (isSvg || isDangerous) {
|
|
// Serve potentially dangerous avatar types as downloads instead
|
|
res.setHeader('Content-Type', 'application/octet-stream');
|
|
res.setHeader('Content-Disposition', buildContentDispositionHeader('attachment', sanitizeFilenameForHeader(fileObj.name)));
|
|
res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox;");
|
|
res.setHeader('X-Frame-Options', 'DENY');
|
|
} else if (INLINE_AVATAR_TYPES.has(typeLower.split(';')[0].trim())) {
|
|
// AvatarMimeBleed, prefix-route sibling (2026-10-02): only a known
|
|
// raster image type is served inline, under its exact canonical
|
|
// name and a restrictive CSP. This branch used to echo whatever type
|
|
// was stored - 'text/html; charset=utf-8' passed the exact-match
|
|
// dangerous list - and serve it inline with no CSP.
|
|
res.setHeader('Content-Type', typeLower.split(';')[0].trim());
|
|
res.setHeader('Content-Disposition', buildContentDispositionHeader('inline', sanitizeFilenameForHeader(fileObj.name)));
|
|
res.setHeader('Content-Security-Policy', "default-src 'none'; img-src 'self'; style-src 'unsafe-inline';");
|
|
} else {
|
|
res.setHeader('Content-Type', 'application/octet-stream');
|
|
res.setHeader('Content-Disposition', buildContentDispositionHeader('attachment', sanitizeFilenameForHeader(fileObj.name)));
|
|
res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox;");
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Helper function to handle conditional requests
|
|
*/
|
|
function handleConditionalRequest(req, res, fileObj) {
|
|
const ifNoneMatch = req.headers['if-none-match'];
|
|
if (ifNoneMatch && ifNoneMatch === `"${fileObj._id}"`) {
|
|
// A 304 repeats the caching rules of the 200 it stands for.
|
|
setPrivateFileCacheHeaders(res);
|
|
res.setHeader('ETag', `"${fileObj._id}"`);
|
|
res.writeHead(304);
|
|
res.end();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Extract first path segment (file id) from request URL.
|
|
* Works whether req.url is the full path or already trimmed by the mount path.
|
|
*/
|
|
function extractFirstIdFromUrl(req, mountPrefix) {
|
|
// Strip query string
|
|
let urlPath = (req.url || '').split('?')[0];
|
|
// If url still contains the mount prefix, remove it
|
|
if (mountPrefix && urlPath.startsWith(mountPrefix)) {
|
|
urlPath = urlPath.slice(mountPrefix.length);
|
|
}
|
|
// Ensure leading slash removed for splitting
|
|
if (urlPath.startsWith('/')) {
|
|
urlPath = urlPath.slice(1);
|
|
}
|
|
const parts = urlPath.split('/').filter(Boolean);
|
|
return parts[0] || null;
|
|
}
|
|
|
|
/**
|
|
* Check if the request explicitly asks to download the file
|
|
* Recognizes ?download=true or ?download=1 (case-insensitive for key)
|
|
*/
|
|
function isDownloadRequested(req) {
|
|
const q = (req.url || '').split('?')[1] || '';
|
|
if (!q) return false;
|
|
const pairs = q.split('&');
|
|
for (const p of pairs) {
|
|
const [rawK, rawV] = p.split('=');
|
|
const k = decodeURIComponent((rawK || '').trim()).toLowerCase();
|
|
const v = decodeURIComponent((rawV || '').trim());
|
|
if (k === 'download' && (v === '' || v === 'true' || v === '1')) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Determine if an avatar request is authorized
|
|
* Rules:
|
|
* - If a boardId query is provided and that board is public -> allow
|
|
* - Else if requester is authenticated (valid token) -> allow
|
|
* - Else if avatar's owner belongs to at least one public board -> allow
|
|
* - Otherwise -> deny
|
|
*/
|
|
async function isAuthorizedForAvatar(req, avatar) {
|
|
try {
|
|
if (!avatar) return false;
|
|
|
|
// Sandstorm already gated grain access; trust the platform (see isSandstormRequest).
|
|
if (isSandstormRequest(req)) return true;
|
|
|
|
// 1) Check explicit board context via query
|
|
const q = parseQuery(req);
|
|
const boardId = q.boardId || q.board || q.b;
|
|
if (boardId) {
|
|
const board = await ReactiveCache.getBoard(boardId);
|
|
if (board && board.isPublic && board.isPublic()) return true;
|
|
|
|
// Otherwise require a signed-in requester who may read the board: a
|
|
// member, or anybody signed in on an 'instance' board (#3249).
|
|
const token = extractLoginToken(req);
|
|
const user = process.env.NEXTCLOUD_EXAPP === 'true'
|
|
? await getNextcloudRequestUser(req) : token ? await getUserFromToken(token) : null;
|
|
if (user && board && board.hasMember && board.hasMember(user._id)) return true;
|
|
if (user && board && readableWithoutMembership(board.permission, true)) return true;
|
|
return false;
|
|
}
|
|
|
|
// 2) Authenticated request without explicit board context
|
|
const token = extractLoginToken(req);
|
|
const user = process.env.NEXTCLOUD_EXAPP === 'true'
|
|
? await getNextcloudRequestUser(req) : token ? await getUserFromToken(token) : null;
|
|
if (user) return true;
|
|
|
|
// 3) Allow if avatar owner is on any public board (so avatars are public only when on public boards)
|
|
// Use a lightweight query against Boards
|
|
const found =
|
|
Boards &&
|
|
(await Boards.findOneAsync(
|
|
{ permission: 'public', 'members.userId': avatar.userId },
|
|
{ fields: { _id: 1 } },
|
|
));
|
|
return !!found;
|
|
} catch (e) {
|
|
if (process.env.DEBUG === 'true') {
|
|
console.warn('Avatar authorization check failed:', e);
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Parse cookies from request headers into an object map
|
|
*/
|
|
function parseCookies(req) {
|
|
const header = req.headers && req.headers.cookie;
|
|
const out = {};
|
|
if (!header) return out;
|
|
const parts = header.split(';');
|
|
for (const part of parts) {
|
|
const idx = part.indexOf('=');
|
|
if (idx === -1) continue;
|
|
const k = decodeURIComponent(part.slice(0, idx).trim());
|
|
const v = decodeURIComponent(part.slice(idx + 1).trim());
|
|
out[k] = v;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Get query parameters as a simple object
|
|
*/
|
|
function parseQuery(req) {
|
|
const out = {};
|
|
const q = (req.url || '').split('?')[1] || '';
|
|
if (!q) return out;
|
|
const pairs = q.split('&');
|
|
for (const p of pairs) {
|
|
if (!p) continue;
|
|
const [rawK, rawV] = p.split('=');
|
|
const k = decodeURIComponent((rawK || '').trim());
|
|
const v = decodeURIComponent((rawV || '').trim());
|
|
if (k) out[k] = v;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Extract a login token from Authorization header, query param, or cookie
|
|
* Supported sources (priority order):
|
|
* - Authorization: Bearer <token>
|
|
* - X-Auth-Token header
|
|
* - authToken query parameter
|
|
* - meteor_login_token or wekan_login_token cookie
|
|
*/
|
|
function extractLoginToken(req) {
|
|
// Authorization: Bearer <token>
|
|
const authz = req.headers && (req.headers.authorization || req.headers.Authorization);
|
|
if (authz && typeof authz === 'string') {
|
|
const m = authz.match(/^Bearer\s+(.+)$/i);
|
|
if (m && m[1]) return m[1].trim();
|
|
}
|
|
|
|
// X-Auth-Token
|
|
const xAuth = req.headers && (req.headers['x-auth-token'] || req.headers['X-Auth-Token']);
|
|
if (xAuth && typeof xAuth === 'string') return xAuth.trim();
|
|
|
|
// Query parameter
|
|
const q = parseQuery(req);
|
|
if (q.authToken && typeof q.authToken === 'string') return q.authToken.trim();
|
|
|
|
// Cookies
|
|
const cookies = parseCookies(req);
|
|
if (cookies.meteor_login_token) return cookies.meteor_login_token.trim();
|
|
if (cookies.wekan_login_token) return cookies.wekan_login_token.trim();
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* On Sandstorm, grain access is already gated by the Sandstorm platform: every
|
|
* request that reaches WeKan has been authorized by Sandstorm and carries the
|
|
* bridge-injected X-Sandstorm-User-Id header. There is no Meteor login token or
|
|
* cookie in that model (auth is via connection.setUserId() + X-Sandstorm-*
|
|
* headers), so the token-based board/avatar authorization below would always
|
|
* fail with 403 and images (attachment thumbnails, minicard covers, slideshow)
|
|
* would break. Trust the platform: an X-Sandstorm-User-Id header means an
|
|
* authenticated grain user. Thanks to xet7.
|
|
*/
|
|
function isSandstormRequest(req) {
|
|
return !!(
|
|
Meteor.settings &&
|
|
Meteor.settings.public &&
|
|
Meteor.settings.public.sandstorm &&
|
|
req &&
|
|
req.headers &&
|
|
req.headers['x-sandstorm-user-id']
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Resolve the identity already verified by the Nextcloud gateway.
|
|
*/
|
|
async function getNextcloudRequestUser(req) {
|
|
const userId = await require('/server/lib/requestUser').getUserIdFromRequest(req);
|
|
return userId ? await Meteor.users.findOneAsync(userId) : null;
|
|
}
|
|
|
|
async function getUserFromToken(rawToken) {
|
|
try {
|
|
if (!rawToken || typeof rawToken !== 'string' || rawToken.length < 10) return null;
|
|
return await require('/server/lib/activeUser').activeUserByToken(rawToken, 'files');
|
|
} catch (e) {
|
|
// In case accounts-base is not available or any error occurs
|
|
if (process.env.DEBUG === 'true') {
|
|
console.warn('Token resolution error:', e);
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Authorization helper for attachment downloads (including Files Report)
|
|
* - Public boards: allow
|
|
* - Private boards: require an active member or an enabled site administrator
|
|
*/
|
|
// `attachment`: the file asked for. Membership is not enough for it: an
|
|
// assigned-only member reads only their own cards' files (AssignedBleed,
|
|
// GHSA-3cgr-47wm-9cc9); `source` names the route in Admin Panel -> Problems.
|
|
async function isAuthorizedForBoard(req, board, attachment, source) {
|
|
try {
|
|
if (!board) return false;
|
|
// Sandstorm already gated grain access; trust the platform (see isSandstormRequest).
|
|
if (isSandstormRequest(req)) return true;
|
|
const token = extractLoginToken(req);
|
|
const user = process.env.NEXTCLOUD_EXAPP === 'true'
|
|
? await getNextcloudRequestUser(req) : token ? await getUserFromToken(token) : null;
|
|
// Files Report already publishes every attachment to site administrators.
|
|
// Keep this exception local to attachment routes, not general board reads.
|
|
if (user?.isAdmin === true && user.loginDisabled !== true) return true;
|
|
if (!canReadBoard(user && user._id, board)) return false;
|
|
return await mayReadBoardAttachment(board, user && user._id, attachment, source);
|
|
} catch (e) {
|
|
if (process.env.DEBUG === 'true') {
|
|
console.warn('Authorization check failed:', e);
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Stream a file - or, for an SVG, send it sanitized: inline as an image, or
|
|
* as the download that was asked for (server/lib/svgResponse.js).
|
|
*/
|
|
function serveFile(req, res, readStream, fileObj) {
|
|
if (!svgResponse.isSvg(fileObj && fileObj.type, fileObj && fileObj.name)) {
|
|
streamFile(res, readStream, fileObj);
|
|
return;
|
|
}
|
|
svgResponse.sendInlineSvg(res, readStream, {
|
|
download: isDownloadRequested(req),
|
|
fileName: fileObj.name,
|
|
// Active markup removed on the way out: logged like the stream sanitizer's.
|
|
onSanitized: text => {
|
|
try {
|
|
const { classifyExploitKinds } = require('/imports/lib/fileNameDisplay');
|
|
require('/server/lib/filenameSanitizeLog').logContentSanitized({
|
|
fileObj, source: 'fileView', kinds: classifyExploitKinds(text),
|
|
});
|
|
} catch (e) { /* logging must never break serving */ }
|
|
},
|
|
}).catch(error => {
|
|
console.error('SVG serve error:', error);
|
|
if (!res.headersSent) { res.writeHead(500); res.end('Error reading file'); }
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Helper function to stream file with error handling
|
|
*/
|
|
function streamFile(res, readStream, fileObj) {
|
|
readStream.on('error', (error) => {
|
|
console.error('File stream error:', error);
|
|
if (!res.headersSent) {
|
|
res.writeHead(500);
|
|
res.end('Error reading file');
|
|
}
|
|
});
|
|
|
|
readStream.on('end', () => {
|
|
if (!res.headersSent) {
|
|
res.writeHead(200);
|
|
}
|
|
});
|
|
|
|
readStream.pipe(res);
|
|
}
|
|
|
|
// #3275: a thumbnail is a WebP of at most THUMBNAIL_EDGE pixels. Cached as
|
|
// the original is (CacheBleed): it is readable by the same people as the
|
|
// original, which is not everybody, and revalidated so a revocation holds.
|
|
// The parts of an attachment's converted preview, with HTTP Range: meta (how
|
|
// many rows), index (where each row starts) and rows. Made on the first
|
|
// request, a piece at a time, from the original's own storage.
|
|
async function serveAttachmentPreview(req, res, attachment, part) {
|
|
const { attachmentRichKind } = require('/models/lib/attachmentKind');
|
|
const { ensurePreview, PREVIEW_KINDS } = require('/server/lib/attachmentPreviewStore');
|
|
const kind = attachmentRichKind(attachment);
|
|
if (!PREVIEW_KINDS.has(kind) || attachment?.meta?.source === 'legacy') {
|
|
res.writeHead(404);
|
|
res.end('No preview for this attachment');
|
|
return;
|
|
}
|
|
let preview;
|
|
try {
|
|
preview = await ensurePreview(attachment, attachmentStoreFactory.getFileStrategy(attachment, 'original'), kind);
|
|
} catch (error) {
|
|
console.error('Attachment preview could not be made:', error && error.message);
|
|
res.writeHead(422);
|
|
res.end('The attachment could not be read for a preview');
|
|
return;
|
|
}
|
|
const headers = {
|
|
'Cache-Control': 'private, max-age=0, must-revalidate',
|
|
'X-Content-Type-Options': 'nosniff',
|
|
'Content-Security-Policy': "default-src 'none'; sandbox;",
|
|
};
|
|
if (part === 'meta') {
|
|
const body = JSON.stringify({ kind: preview.info.kind, count: preview.info.count, truncated: !!preview.info.truncated });
|
|
res.writeHead(200, { ...headers, 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(body) });
|
|
res.end(body);
|
|
return;
|
|
}
|
|
const file = part === 'index' ? preview.index : preview.rows;
|
|
const size = fs.statSync(file).size;
|
|
const range = parseRange(req.headers.range, size);
|
|
if (range === 'unsatisfiable') {
|
|
res.writeHead(416, { 'Content-Range': `bytes */${size}`, 'Accept-Ranges': 'bytes' });
|
|
res.end();
|
|
return;
|
|
}
|
|
const typed = { ...headers, 'Content-Type': 'application/octet-stream', 'Accept-Ranges': 'bytes' };
|
|
if (range) {
|
|
res.writeHead(206, { ...typed, ...partialContentHeaders(range, size) });
|
|
fs.createReadStream(file, { start: range.start, end: range.end }).pipe(res);
|
|
} else {
|
|
res.writeHead(200, { ...typed, 'Content-Length': String(size) });
|
|
fs.createReadStream(file).pipe(res);
|
|
}
|
|
}
|
|
|
|
function sendThumbnail(req, res, attachment, key, buffer) {
|
|
const etag = `"${attachment._id}-thumbnail-${key.slice(0, 16)}"`;
|
|
if (req.headers['if-none-match'] === etag) {
|
|
res.writeHead(304, { ETag: etag, ...privateFileCacheHeaders() });
|
|
res.end();
|
|
return;
|
|
}
|
|
res.writeHead(200, {
|
|
'Content-Type': THUMBNAIL_TYPE,
|
|
'Content-Length': buffer.length,
|
|
...privateFileCacheHeaders(),
|
|
ETag: etag,
|
|
'X-Content-Type-Options': 'nosniff',
|
|
'Content-Security-Policy': "default-src 'none'; sandbox;",
|
|
});
|
|
res.end(buffer);
|
|
}
|
|
|
|
// ============================================================================
|
|
// NEW METEOR-FILES ROUTES (URL-agnostic)
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Serve attachments from new Meteor-Files structure
|
|
* Route: /cdn/storage/attachments/{fileId} or /cdn/storage/attachments/{fileId}/original/{filename}
|
|
*/
|
|
WebApp.handlers.use('/cdn/storage/attachments', async (req, res, next) => {
|
|
if (req.method !== 'GET') {
|
|
return next();
|
|
}
|
|
|
|
try {
|
|
const fileId = extractFirstIdFromUrl(req, '/cdn/storage/attachments');
|
|
|
|
if (!fileId) {
|
|
res.writeHead(400);
|
|
res.end('Invalid attachment file ID');
|
|
return;
|
|
}
|
|
|
|
// Get attachment from database with backward compatibility
|
|
const attachment = await getAttachmentWithBackwardCompatibility(fileId);
|
|
if (!attachment) {
|
|
res.writeHead(404);
|
|
res.end('Attachment not found');
|
|
return;
|
|
}
|
|
|
|
// The currently configured site logo must be readable on the login
|
|
// page, before a user can authenticate. No other attachment is public
|
|
// through this exception, including an older replaced logo.
|
|
const siteLogo = attachment.meta?.source === 'site-logo';
|
|
if (siteLogo) {
|
|
const setting = await Settings.findOneAsync();
|
|
if (!isActiveSiteLogo(attachment, setting, fileId)) {
|
|
res.writeHead(404);
|
|
res.end('Logo not found');
|
|
return;
|
|
}
|
|
} else {
|
|
const board = await ReactiveCache.getBoard(attachment.meta.boardId);
|
|
if (!board) {
|
|
res.writeHead(404);
|
|
res.end('Board not found');
|
|
return;
|
|
}
|
|
const authorized = await isAuthorizedForBoard(req, board, attachment, 'file-server:cdn');
|
|
if (!authorized) {
|
|
res.writeHead(403);
|
|
res.end('Access denied');
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Lazy upgrade: only touch old metadata when an authorized request is
|
|
// actually reading the file. This also makes the download header use the
|
|
// detected extension on this very request.
|
|
await normalizeStoredNameOnRead(Attachments, attachment, attachmentStoreFactory);
|
|
|
|
// Handle conditional requests
|
|
if (handleConditionalRequest(req, res, attachment)) {
|
|
return;
|
|
}
|
|
|
|
const attachmentDownloadLimits = await getAttachmentDownloadLimitSettings();
|
|
if (attachmentDownloadLimits.blocked) {
|
|
res.writeHead(403);
|
|
res.end('Attachment downloads are disabled by administrator');
|
|
return;
|
|
}
|
|
|
|
if (Number.isFinite(attachmentDownloadLimits.maxBytes)
|
|
&& attachmentDownloadLimits.maxBytes > 0
|
|
&& Number.isFinite(attachment.size)
|
|
&& attachment.size > attachmentDownloadLimits.maxBytes) {
|
|
res.writeHead(413);
|
|
res.end('Attachment exceeds download limit');
|
|
return;
|
|
}
|
|
|
|
// Enforce the per-storage "Read" flag configured in
|
|
// Admin Panel / Attachments. The file is served only when reading from
|
|
// the storage backend it currently lives in is enabled.
|
|
const storageSettings = await AttachmentStorageSettings.findOneAsync({});
|
|
if (storageSettings) {
|
|
let storageName;
|
|
if (attachment?.meta?.source === 'legacy') {
|
|
// Legacy CollectionFS files live in MongoDB GridFS.
|
|
storageName = STORAGE_NAME_GRIDFS;
|
|
} else {
|
|
const probeStrategy = attachmentStoreFactory.getFileStrategy(attachment, 'original');
|
|
storageName = probeStrategy && probeStrategy.getStorageName
|
|
? probeStrategy.getStorageName()
|
|
: null;
|
|
}
|
|
if (storageName && !storageSettings.isStorageReadEnabled(storageName)) {
|
|
res.writeHead(403);
|
|
res.end('Reading from this storage backend is disabled by administrator');
|
|
return;
|
|
}
|
|
}
|
|
|
|
// /cdn/storage/attachments/<id>/preview-<meta|index|rows>: the slideshow's
|
|
// converted preview of a file whose content is scattered through it
|
|
// (server/lib/attachmentPreviewStore.js). Everything above has been
|
|
// applied, so the preview is readable exactly when the original is.
|
|
const previewPart = previewPartOf((req.url || '').replace(/^\/cdn\/storage\/attachments(?=\/)/, ''));
|
|
if (previewPart) {
|
|
await serveAttachmentPreview(req, res, attachment, previewPart);
|
|
return;
|
|
}
|
|
|
|
// #3275: /cdn/storage/attachments/<id>/thumbnail - everything above
|
|
// (board access, download block and limit, storage read flag) has
|
|
// already been applied, so a thumbnail is readable exactly when the
|
|
// original is.
|
|
const wantsThumbnail = isThumbnailPath((req.url || '').replace(/^\/cdn\/storage\/attachments(?=\/)/, ''));
|
|
if (wantsThumbnail && !canThumbnail(attachment)) {
|
|
res.writeHead(404);
|
|
res.end('No thumbnail for this attachment');
|
|
return;
|
|
}
|
|
const thumbnailKey = wantsThumbnail ? gifCacheKey(attachment) : null;
|
|
const cached = wantsThumbnail ? cachedThumbnail(thumbnailKey) : null;
|
|
if (cached) {
|
|
sendThumbnail(req, res, attachment, thumbnailKey, cached);
|
|
return;
|
|
}
|
|
|
|
// #6745: a Range request (a video seek, a resumed download) streams only
|
|
// the bytes asked for, from the storage backend itself. Legacy
|
|
// CollectionFS files and thumbnails are always sent whole.
|
|
const size = Number(attachment.size);
|
|
let range = null;
|
|
// An SVG is sent whole and sanitized (svgResponse.js): no range of it.
|
|
if (!wantsThumbnail && attachment?.meta?.source !== 'legacy' && !svgResponse.isSvg(attachment.type, attachment.name)
|
|
&& Number.isSafeInteger(size)
|
|
&& ifRangeAllows(req.headers['if-range'], `"${attachment._id}"`)) {
|
|
range = parseRange(req.headers.range, size);
|
|
}
|
|
if (range === 'unsatisfiable') {
|
|
res.writeHead(416, { 'Content-Range': `bytes */${size}`, 'Accept-Ranges': 'bytes' });
|
|
res.end();
|
|
return;
|
|
}
|
|
|
|
// Choose proper streaming based on source
|
|
let readStream;
|
|
if (attachment?.meta?.source === 'legacy') {
|
|
// Legacy CollectionFS GridFS stream
|
|
readStream = await getOldAttachmentStream(fileId);
|
|
} else {
|
|
// New Meteor-Files storage
|
|
const strategy = attachmentStoreFactory.getFileStrategy(attachment, 'original');
|
|
readStream = strategy.getReadStream(range || undefined);
|
|
}
|
|
|
|
if (!readStream) {
|
|
res.writeHead(404);
|
|
res.end('Attachment file not found in storage');
|
|
return;
|
|
}
|
|
|
|
if (wantsThumbnail) {
|
|
let thumbnail;
|
|
try {
|
|
thumbnail = await convertImageBufferToThumbnail(await boundedStreamBuffer(readStream));
|
|
} catch (error) {
|
|
// Too large, damaged or a format the converter cannot read: the
|
|
// original, which passed the same checks, still shows the image.
|
|
if (typeof readStream.destroy === 'function') readStream.destroy();
|
|
res.writeHead(302, { Location: Meteor.absoluteUrl(`cdn/storage/attachments/${fileId}`), 'Cache-Control': 'no-store' });
|
|
res.end();
|
|
return;
|
|
}
|
|
rememberThumbnail(thumbnailKey, thumbnail);
|
|
sendThumbnail(req, res, attachment, thumbnailKey, thumbnail);
|
|
return;
|
|
}
|
|
|
|
// Set headers and stream file
|
|
if (isDownloadRequested(req)) {
|
|
// Force download if requested via query param
|
|
setPrivateFileCacheHeaders(res);
|
|
res.setHeader('ETag', `"${attachment._id}"`);
|
|
if (attachment.size) res.setHeader('Content-Length', attachment.size);
|
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
res.setHeader('Content-Type', 'application/octet-stream');
|
|
res.setHeader('Content-Disposition', buildContentDispositionHeader('attachment', sanitizeFilenameForHeader(attachment.name)));
|
|
res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox;");
|
|
} else {
|
|
setFileHeaders(res, attachment, true);
|
|
}
|
|
if (attachment?.meta?.source !== 'legacy') res.setHeader('Accept-Ranges', 'bytes');
|
|
if (range) {
|
|
for (const [name, value] of Object.entries(partialContentHeaders(range, size))) {
|
|
res.setHeader(name, value);
|
|
}
|
|
res.statusCode = 206;
|
|
}
|
|
// A whole read is hashed on the way out and checked against the stored
|
|
// SHA-256; a missing hash or search text is made from it
|
|
// (server/lib/attachmentContentIndex.js). A range is part of the file.
|
|
if (!range && attachment?.meta?.source !== 'legacy') {
|
|
const { hashingTap, afterWholeRead } = require('/server/lib/attachmentContentIndex');
|
|
const tap = hashingTap();
|
|
readStream.on('error', error => tap.stream.destroy(error));
|
|
readStream.pipe(tap.stream);
|
|
tap.result.then(actual => afterWholeRead(attachment, actual)).catch(() => {});
|
|
readStream = tap.stream;
|
|
}
|
|
serveFile(req, res, readStream, attachment);
|
|
|
|
} catch (error) {
|
|
console.error('Attachment server error:', error);
|
|
if (!res.headersSent) {
|
|
res.writeHead(500);
|
|
res.end('Internal server error');
|
|
}
|
|
}
|
|
});
|
|
|
|
/**
|
|
* Serve avatars from new Meteor-Files structure
|
|
* Route: /cdn/storage/avatars/{fileId} or /cdn/storage/avatars/{fileId}/original/{filename}
|
|
*/
|
|
WebApp.handlers.use('/cdn/storage/avatars', async (req, res, next) => {
|
|
if (req.method !== 'GET') {
|
|
return next();
|
|
}
|
|
|
|
try {
|
|
const fileId = extractFirstIdFromUrl(req, '/cdn/storage/avatars');
|
|
|
|
if (!fileId) {
|
|
res.writeHead(400);
|
|
res.end('Invalid avatar file ID');
|
|
return;
|
|
}
|
|
|
|
// Get avatar from database
|
|
const avatar = await ReactiveCache.getAvatar(fileId);
|
|
if (!avatar) {
|
|
// This prefix route mounts before avatarServer's narrower route and
|
|
// also receives /<id>/original/<filename>. Read CollectionFS here
|
|
// rather than masking the authenticated legacy fallback with a 404.
|
|
const legacy = await readAuthenticatedLegacyAvatar(req, fileId);
|
|
if (legacy) {
|
|
if (handleConditionalRequest(req, res, legacy.avatar)) {
|
|
legacy.stream.destroy();
|
|
return;
|
|
}
|
|
setFileHeaders(res, legacy.avatar, false);
|
|
serveFile(req, res, legacy.stream, legacy.avatar);
|
|
return;
|
|
}
|
|
res.writeHead(404);
|
|
res.end('Avatar not found');
|
|
return;
|
|
}
|
|
|
|
// Enforce visibility: avatars are public only in the context of public boards
|
|
if (!(await isAuthorizedForAvatar(req, avatar))) {
|
|
res.writeHead(403);
|
|
res.end('Access denied');
|
|
return;
|
|
}
|
|
|
|
await normalizeStoredNameOnRead(Avatars, avatar, avatarStoreFactory);
|
|
|
|
// Handle conditional requests
|
|
if (handleConditionalRequest(req, res, avatar)) {
|
|
return;
|
|
}
|
|
|
|
// Get file strategy and stream
|
|
const strategy = avatarStoreFactory.getFileStrategy(avatar, 'original');
|
|
const readStream = strategy.getReadStream();
|
|
|
|
if (!readStream) {
|
|
res.writeHead(404);
|
|
res.end('Avatar file not found in storage');
|
|
return;
|
|
}
|
|
|
|
// Set headers and stream file
|
|
setFileHeaders(res, avatar, false);
|
|
serveFile(req, res, readStream, avatar);
|
|
|
|
} catch (error) {
|
|
console.error('Avatar server error:', error);
|
|
if (!res.headersSent) {
|
|
res.writeHead(500);
|
|
res.end('Internal server error');
|
|
}
|
|
}
|
|
});
|
|
|
|
// ============================================================================
|
|
// LEGACY COLLECTIONFS ROUTES (Backward compatibility)
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Serve legacy attachments from CollectionFS structure
|
|
* Route: /cfs/files/attachments/{attachmentId}
|
|
*/
|
|
WebApp.handlers.use('/cfs/files/attachments', async (req, res, next) => {
|
|
if (req.method !== 'GET') {
|
|
return next();
|
|
}
|
|
|
|
try {
|
|
const attachmentId = extractFirstIdFromUrl(req, '/cfs/files/attachments');
|
|
|
|
if (!attachmentId) {
|
|
res.writeHead(400);
|
|
res.end('Invalid attachment ID');
|
|
return;
|
|
}
|
|
|
|
// Try to get attachment with backward compatibility
|
|
const attachment = await getAttachmentWithBackwardCompatibility(attachmentId);
|
|
if (!attachment) {
|
|
res.writeHead(404);
|
|
res.end('Attachment not found');
|
|
return;
|
|
}
|
|
|
|
// Check permissions
|
|
const board = await ReactiveCache.getBoard(attachment.meta.boardId);
|
|
if (!board) {
|
|
res.writeHead(404);
|
|
res.end('Board not found');
|
|
return;
|
|
}
|
|
|
|
// Enforce cookie/header/query-based auth for private boards
|
|
if (!(await isAuthorizedForBoard(req, board, attachment, 'file-server:cfs'))) {
|
|
res.writeHead(403);
|
|
res.end('Access denied');
|
|
return;
|
|
}
|
|
|
|
// Handle conditional requests
|
|
if (handleConditionalRequest(req, res, attachment)) {
|
|
return;
|
|
}
|
|
|
|
// For legacy attachments, try to get GridFS stream
|
|
const fileStream = await getOldAttachmentStream(attachmentId);
|
|
if (fileStream) {
|
|
if (isDownloadRequested(req)) {
|
|
// Force download if requested
|
|
setPrivateFileCacheHeaders(res);
|
|
res.setHeader('ETag', `"${attachment._id}"`);
|
|
if (attachment.size) res.setHeader('Content-Length', attachment.size);
|
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
res.setHeader('Content-Type', 'application/octet-stream');
|
|
res.setHeader('Content-Disposition', buildContentDispositionHeader('attachment', sanitizeFilenameForHeader(attachment.name)));
|
|
res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox;");
|
|
} else {
|
|
setFileHeaders(res, attachment, true);
|
|
}
|
|
serveFile(req, res, fileStream, attachment);
|
|
} else {
|
|
res.writeHead(404);
|
|
res.end('Legacy attachment file not found in GridFS');
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('Legacy attachment server error:', error);
|
|
if (!res.headersSent) {
|
|
res.writeHead(500);
|
|
res.end('Internal server error');
|
|
}
|
|
}
|
|
});
|
|
|
|
/**
|
|
* Serve legacy avatars from CollectionFS structure
|
|
* Route: /cfs/files/avatars/{avatarId}
|
|
*/
|
|
WebApp.handlers.use('/cfs/files/avatars', async (req, res, next) => {
|
|
if (req.method !== 'GET') {
|
|
return next();
|
|
}
|
|
|
|
try {
|
|
const avatarId = extractFirstIdFromUrl(req, '/cfs/files/avatars');
|
|
|
|
if (!avatarId) {
|
|
res.writeHead(400);
|
|
res.end('Invalid avatar ID');
|
|
return;
|
|
}
|
|
|
|
// Try to get avatar from database (new structure first)
|
|
let avatar = await ReactiveCache.getAvatar(avatarId);
|
|
|
|
if (!avatar) {
|
|
// This prefix route mounts before avatarServer's narrower route and
|
|
// also receives /<id>/original/<filename>. Read CollectionFS here
|
|
// rather than masking the authenticated legacy fallback with a 404.
|
|
const legacy = await readAuthenticatedLegacyAvatar(req, avatarId);
|
|
if (legacy) {
|
|
if (handleConditionalRequest(req, res, legacy.avatar)) {
|
|
legacy.stream.destroy();
|
|
return;
|
|
}
|
|
setFileHeaders(res, legacy.avatar, false);
|
|
serveFile(req, res, legacy.stream, legacy.avatar);
|
|
return;
|
|
}
|
|
res.writeHead(404);
|
|
res.end('Avatar not found');
|
|
return;
|
|
}
|
|
|
|
// Enforce visibility for legacy avatars as well
|
|
if (!(await isAuthorizedForAvatar(req, avatar))) {
|
|
res.writeHead(403);
|
|
res.end('Access denied');
|
|
return;
|
|
}
|
|
|
|
// Handle conditional requests
|
|
if (handleConditionalRequest(req, res, avatar)) {
|
|
return;
|
|
}
|
|
|
|
// Get file strategy and stream
|
|
const strategy = avatarStoreFactory.getFileStrategy(avatar, 'original');
|
|
const readStream = strategy.getReadStream();
|
|
|
|
if (!readStream) {
|
|
res.writeHead(404);
|
|
res.end('Avatar file not found in storage');
|
|
return;
|
|
}
|
|
|
|
// Set headers and stream file
|
|
setFileHeaders(res, avatar, false);
|
|
serveFile(req, res, readStream, avatar);
|
|
|
|
} catch (error) {
|
|
console.error('Legacy avatar server error:', error);
|
|
if (!res.headersSent) {
|
|
res.writeHead(500);
|
|
res.end('Internal server error');
|
|
}
|
|
}
|
|
});
|
|
|
|
// ============================================================================
|
|
// ALTERNATIVE ROUTES (For different URL patterns)
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Alternative attachment route for different URL patterns
|
|
* Route: /attachments/{fileId}
|
|
*/
|
|
WebApp.handlers.use('/attachments', (req, res, next) => {
|
|
if (req.method !== 'GET') {
|
|
return next();
|
|
}
|
|
|
|
const fileId = extractFirstIdFromUrl(req, '/attachments');
|
|
if (!fileId) {
|
|
// No file ID — let Meteor serve the SPA (e.g. the admin /attachments settings page).
|
|
// Without this check a direct GET to /attachments redirected to /cdn/storage/attachments/null.
|
|
return next();
|
|
}
|
|
|
|
// Use absolute URL so the redirect is correct under sub-URL (ROOT_URL with path prefix) deployments
|
|
const newUrl = Meteor.absoluteUrl(`cdn/storage/attachments/${fileId}`);
|
|
res.writeHead(301, { 'Location': newUrl });
|
|
res.end();
|
|
});
|
|
|
|
/**
|
|
* Alternative avatar route for different URL patterns
|
|
* Route: /avatars/{fileId}
|
|
*/
|
|
WebApp.handlers.use('/avatars', (req, res, next) => {
|
|
if (req.method !== 'GET') {
|
|
return next();
|
|
}
|
|
|
|
const fileId = extractFirstIdFromUrl(req, '/avatars');
|
|
if (!fileId) {
|
|
return next();
|
|
}
|
|
|
|
// Use absolute URL so the redirect is correct under sub-URL deployments
|
|
const newUrl = Meteor.absoluteUrl(`cdn/storage/avatars/${fileId}`);
|
|
res.writeHead(301, { 'Location': newUrl });
|
|
res.end();
|
|
});
|
|
|
|
console.log('Universal file server initialized successfully');
|
|
}
|