Files
wekan/models/exporter.js
T
Lauri Ojansivu d56bb34490 Make large boards fast on 8 GB: load only what is visible, stop re-running every minicard, and stream big attachments.
On a seeded board of 4,000 cards, 12,000 comments, 20,000 checklist items
and 32,000 activities, served from FerretDB with SQLite as the Snap is:
closing a card took about 4 s and now takes 0.1 s, the board finished
loading in 17.6 s and now in 6.2 s, a card open re-ran about 7,700
computations and now about 1,000, and FerretDB used 13 s of CPU and 724 MB
while the board opened, now 3 s and 280 MB.

- The client data cache queued one more stop callback each time a helper
  re-ran, and every check asked Tracker for dependents, which on close was
  710 walks of 3 ms; there is now one callback per computation and key and
  one timer per key (imports/lib/dataCache.js).
- Opening a card writes the user's last-viewed card, and avatars, @mentions,
  list and swimlane headers read the whole user, so everything re-ran; they
  read only the fields they show. The comment, checklist and subtask indexes
  were one object every minicard depended on and are now per card
  (imports/lib/keyedGroupIndex.js).
- The lazy card window kept a full copy of every card of a list per window;
  it keeps the id and the sort keys, runs its id query once instead of five
  times, and sends comment text only when minicards show comments
  (server/publications/cardsWindow.js, models/lib/cardWindowFields.js).
  Comment reactions and legacy attachment lookups come with the opened card
  only.
- Attachment downloads honour Range for filesystem, GridFS and cloud
  storage (206, 416, If-Range); uploads to cloud storage are spooled to a
  temporary file and streamed instead of gathered into one Buffer; the API
  copy checks the size limit before reading; the legacy attachment
  migration streams, and no longer stores "[object Promise]" as a file; the
  board export no longer concatenates buffers quadratically.

The FerretDB fork pushes dotted-path filters such as meta.cardId down to
SQLite (they were each a full scan) and decodes only the fields a count
filters on. docs/Features/Admin-Panel/Problems/Large-Boards.md describes how
a large board loads and how to size a server with 8 GB of RAM.

Thanks to markusst1982 and xet7 !

Fixes #6745.
2026-10-09 13:28:08 +03:00

930 lines
42 KiB
JavaScript

import { ReactiveCache } from '/imports/reactiveCache';
import { liveAttachments } from '/models/lib/attachmentSoftDelete';
const Papa = require('papaparse');
const { buildCsvCardRow } = require('./lib/exporterCsvRow');
const { csvColumnMask, applyMask } = require('./lib/exportFields');
const { encodeAligned, encodeFinal } = require('./lib/base64Chunk');
const {
getImportExportSecuritySettings,
assertExportEnabled,
anonymizedUserWord,
buildUserAnonymizationMap,
anonymizeUserDoc,
anonymizeBoardTextInPlace,
} = require('./lib/importExportSecurity');
import { TAPi18n } from '/imports/i18n';
import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import {
formatDateTime,
formatDate,
formatTime,
getISOWeek,
isValidDate,
isBefore,
isAfter,
isSame,
add,
subtract,
startOf,
endOf,
format,
parseDate,
now,
createDate,
fromNow,
calendar
} from '/imports/lib/dateUtils';
//const stringify = require('csv-stringify');
//const stringify = require('csv-stringify');
// Write a chunk to the HTTP response, pausing on backpressure. #6480: the naive
// `res.once('drain', resolve); res.once('error', reject)` leaks one 'error'
// listener on the ServerResponse per backpressured write (the 'drain' listener
// self-removes when it fires, but the paired 'error' listener never does), which
// on a large export raised Node's "MaxListenersExceededWarning: 11 error
// listeners added to [ServerResponse]" and left listeners accumulating for the
// life of the socket. Always remove BOTH listeners once either settles.
export function writeWithBackpressure(res, str) {
return new Promise((resolve, reject) => {
if (res.write(str)) {
resolve();
return;
}
const cleanup = () => {
res.removeListener('drain', onDrain);
res.removeListener('error', onError);
};
const onDrain = () => { cleanup(); resolve(); };
const onError = err => { cleanup(); reject(err); };
res.once('drain', onDrain);
res.once('error', onError);
});
}
// GHSA-4mxf-m8pq-xc9p: an avatar's `versions.original.path` comes out of the
// DATABASE, and the export below reads it off disk and embeds the bytes as
// base64. The avatar allow rule now refuses to let a client write that field
// (server/permissions/avatars.js), and this is the second lock: a path is only
// read when it resolves to somewhere inside WeKan's own storage, so a path
// poisoned any other way - an old document written before the fix, a restored
// backup, a bad migration - still cannot turn an export into a file read.
//
// The roots are computed the same way models/avatars.js and models/attachments.js
// compute their storagePath, via the shared helper both of them are kept in sync
// with.
export function avatarStorageRoots() {
const { computeStoragePaths } = require('./lib/attachmentStoragePath');
const paths = computeStoragePaths(process.env.WRITABLE_PATH);
return [paths.avatars, paths.attachments];
}
// True when `storedPath` may be read. Exported so the guard itself is testable.
export function isReadableStoredFilePath(storedPath, roots) {
const { isPathInsideAny } = require('./lib/storagePathContainment');
return isPathInsideAny(storedPath, roots || avatarStorageRoots());
}
// exporter maybe is broken since Gridfs introduced, add fs and path
export class Exporter {
constructor(boardId, attachmentId, options = {}) {
this._boardId = boardId;
this._attachmentId = attachmentId;
// #5870: when true, board export omits the base64-encoded attachment file
// data (metadata is still exported). This lets very large boards export
// without overflowing V8's max string length in JSON.stringify or loading
// every attachment buffer into memory at once. Default false (full export).
this._excludeAttachments = options.excludeAttachments === true;
// Language used for the anonymized user placeholder word ("user" -> user1,
// "käyttäjä" -> käyttäjä1). Defaults to English when the caller cannot supply
// the exporting user's language.
this._userLanguage = options.userLanguage || 'en';
// #1173: WHAT of the board, and WHICH PARTS of it.
//
// `scope` narrows the export to one swimlane, one list, one card or one
// checklist, for the menus that offer it there. The FORMAT does not change -
// it is still `wekan-board-1.0.0`, still the board's own fields with the
// arrays under them - because the file has to import back, and an importer
// that had to understand four shapes would be four times the code and four
// times the bugs. A scoped export is the same document with fewer rows in
// it, plus the lists and swimlanes its cards refer to, so what comes back in
// still has somewhere to land.
//
// `fields` is the selection popup's `?fields=`, the same keys the PDF and
// Excel exports gate on. An unselected section is emitted as an EMPTY ARRAY
// rather than left out: a missing key is a format change, an empty one is an
// export with nothing of that kind in it.
this._scope = options.scope || {};
this._fields = options.fields && options.fields.length > 0
? new Set(options.fields)
: null;
}
// No selection means everything, the same rule every other exporter follows.
hasField(key) { return this._fields === null || this._fields.has(key); }
// The cards this export is about. A card scope is one card; a checklist scope
// is the card that checklist is on, because a checklist without its card
// cannot be imported anywhere.
async _scopedCardSelector(boardId) {
const selector = { boardId, linkedId: { $in: ['', null] } };
if (this._scope.cardId) {
selector._id = this._scope.cardId;
} else if (this._scope.checklistId) {
const checklist = await ReactiveCache.getChecklist(this._scope.checklistId);
selector._id = checklist ? checklist.cardId : '__no_such_card__';
} else {
if (this._scope.swimlaneId) selector.swimlaneId = this._scope.swimlaneId;
if (this._scope.listId) selector.listId = this._scope.listId;
}
return selector;
}
hasScope() {
return Boolean(this._scope.swimlaneId || this._scope.listId
|| this._scope.cardId || this._scope.checklistId);
}
async build() {
await require('/server/lib/adminOnlyCustomFields').assertFieldExport(this._boardId, this._customFieldViewerId);
await assertExportEnabled();
const fs = Npm.require('fs');
const os = Npm.require('os');
const path = Npm.require('path');
const byBoard = { boardId: this._boardId };
// Attachments store the board id under `meta.boardId`, unlike lists,
// swimlanes, cards and rules which keep a flat `boardId`.
const byBoardAttachment = { 'meta.boardId': this._boardId };
const byBoardNoLinked = {
boardId: this._boardId,
linkedId: { $in: ['', null] },
};
// we do not want to retrieve boardId in related elements
const noBoardId = {
fields: {
boardId: 0,
},
};
const result = {
_format: 'wekan-board-1.0.0',
};
Object.assign(
result,
await ReactiveCache.getBoard(this._boardId, {
fields: {
stars: 0,
},
}),
);
// [Old] for attachments we only export IDs and absolute url to original doc
// [New] Encode attachment to base64
const getBase64Data = function (doc, callback) {
// #6745: the chunks are joined ONCE at the end. Appending each chunk with
// Buffer.concat([buffer, chunk]) copied everything read so far on every
// chunk - quadratic in the file size - and the copy was also piped to a
// temporary file that was then deleted unread.
const chunks = [];
// callback has the form function (err, res) {}
// GHSA-4mxf-m8pq-xc9p: this is the ONE place the export turns a stored
// path into bytes, for attachments and avatars alike, so the containment
// check belongs here as well as at the call sites. A path that does not
// resolve inside WeKan's storage is not a file this export may read.
const storedPath = doc?.versions?.original?.path;
if (!isReadableStoredFilePath(storedPath)) {
if (process.env.DEBUG === 'true') {
console.warn('Refused to export a file stored outside the storage root:', storedPath);
}
// A canary, not a guess: every path WeKan writes is inside the storage
// root, so one that is not was put there by something that should not
// have. The export continues without the file, exactly as before.
try {
const { tripCanary } = require('/server/lib/canary');
tripCanary('export.path-outside-storage', { detail: 'during board export' });
} catch (e) { /* never break an export to report on it */ }
callback(null, null);
return;
}
const readStream = fs.createReadStream(storedPath);
readStream.on('data', function (chunk) {
chunks.push(chunk);
});
readStream.on('error', function () {
callback(null, null);
});
readStream.on('end', function () {
callback(null, Buffer.concat(chunks).toString('base64'));
});
};
const getBase64DataAsync = (doc) => new Promise((resolve, reject) => {
getBase64Data(doc, (err, res) => err ? reject(err) : resolve(res));
});
const byBoardAndAttachment = this._attachmentId
? { 'meta.boardId': this._boardId, _id: this._attachmentId }
: byBoardAttachment;
const attachmentDocs = await ReactiveCache.getAttachments(liveAttachments(byBoardAndAttachment));
result.attachments = [];
for (const attachment of attachmentDocs) {
const attachmentExport = {
_id: attachment._id,
cardId: attachment.meta.cardId,
// `source` distinguishes board-level backgrounds ('board-background')
// from card attachments on import.
source: attachment.meta.source,
//url: FlowRouter.url(attachment.url()),
name: attachment.name,
type: attachment.type,
};
// #5870: only base64-encode the file when not excluding attachments. The
// single-attachment path below always includes the file (used to export
// one attachment), so it is unaffected by this board-level option.
if (!this._excludeAttachments || this._attachmentId) {
attachmentExport.file = await getBase64DataAsync(attachment);
}
result.attachments.push(attachmentExport);
}
//When has a especific valid attachment return the single element
if (this._attachmentId) {
return result.attachments.length > 0 ? result.attachments[0] : {};
}
result.lists = await ReactiveCache.getLists(byBoard, noBoardId);
result.cards = await ReactiveCache.getCards(byBoardNoLinked, noBoardId);
result.swimlanes = await ReactiveCache.getSwimlanes(byBoard, noBoardId);
result.customFields = await ReactiveCache.getCustomFields(
{ boardIds: this._boardId },
{ fields: { boardIds: 0 } },
);
const { exportScrumTransfer, scrumTransferUserIds } = require('/server/lib/scrumTransferExport');
if (this.hasField('scrum')) {
const scrum = await exportScrumTransfer(this._boardId, result.cards.map(c => c._id), result.lists.map(l => l._id), result.swimlanes.map(s => s._id), this.hasScope());
if (scrum) { result.scrumTransfer = scrum.transfer; result.scrumTransferLosses = scrum.losses; }
} else {
for (const row of [result, ...result.cards, ...result.lists, ...result.swimlanes]) { delete row.scrum; delete row.scrumRevision; }
}
const cardIds = result.cards.map(card => card._id);
result.comments = await ReactiveCache.getCardComments(
{ cardId: { $in: cardIds } },
noBoardId,
);
result.activities = await ReactiveCache.getActivities(
{
$or: [{ boardId: this._boardId }, { cardId: { $in: cardIds } }],
},
noBoardId,
);
result.rules = await ReactiveCache.getRules(byBoard, noBoardId);
result.checklists = [];
result.checklistItems = [];
result.subtaskItems = [];
result.triggers = [];
result.actions = [];
for (const card of result.cards) {
result.checklists.push(
...await ReactiveCache.getChecklists({
cardId: card._id,
}),
);
result.checklistItems.push(
...await ReactiveCache.getChecklistItems({
cardId: card._id,
}),
);
result.subtaskItems.push(
...await ReactiveCache.getCards({
boardId: card.boardId,
parentId: card._id,
}),
);
}
const { ruleTriggerIds: partTriggerIds, ruleActionIds: partActionIds } = require('/models/lib/ruleParts');
for (const rule of result.rules) {
// #4294: every trigger and action of the rule, not only the first ones.
result.triggers.push(
...await ReactiveCache.getTriggers(
{
_id: { $in: partTriggerIds(rule) },
},
noBoardId,
),
);
result.actions.push(
...await ReactiveCache.getActions(
{
_id: { $in: partActionIds(rule) },
},
noBoardId,
),
);
}
// we also have to export some user data - as the other elements only
// include id but we have to be careful:
// 1- only exports users that are linked somehow to that board
// 2- do not export any sensitive information
const users = {};
scrumTransferUserIds(result.scrumTransfer).forEach(id => { users[id] = true; });
result.members.forEach((member) => {
users[member.userId] = true;
});
result.lists.forEach((list) => {
users[list.userId] = true;
});
result.cards.forEach((card) => {
users[card.userId] = true;
if (card.members) {
card.members.forEach((memberId) => {
users[memberId] = true;
});
}
(card.requesters || []).forEach(userId => { users[userId] = true; });
(card.assigners || []).forEach(userId => { users[userId] = true; });
});
result.comments.forEach((comment) => {
users[comment.userId] = true;
});
result.activities.forEach((activity) => {
users[activity.userId] = true;
});
result.checklists.forEach((checklist) => {
users[checklist.userId] = true;
});
const byUserIds = {
_id: {
$in: Object.getOwnPropertyNames(users),
},
};
// we use whitelist to be sure we do not expose inadvertently
// some secret fields that gets added to User later.
const userFields = {
fields: {
_id: 1,
username: 1,
'profile.fullname': 1,
'profile.initials': 1,
'profile.avatarUrl': 1,
},
};
// Export the original members with their username + fullname + initials + avatar,
// but NEVER any secret (the whitelist above already excludes passwords, emails and
// services). For each member whose avatar is a LOCAL WeKan file, embed the file
// itself as base64 so the original picture round-trips through export/import without
// the identity provider — this reads a local file (no outbound fetch), so it works
// inside a Sandstorm grain too, letting a board with many already-stored avatars be
// exported and re-imported with every member's picture intact.
const security = await getImportExportSecuritySettings();
const usersRaw = await ReactiveCache.getUsers(byUserIds, userFields);
result.users = [];
for (const user of usersRaw) {
if (security.disableExportAvatars) {
// Admin Panel / Features / Security: never carry avatars out of WeKan.
if (user.profile) delete user.profile.avatarUrl;
} else {
const localUrl = ((user.profile || {}).avatarUrl) || '';
const m = localUrl.match(/\/(?:cdn\/storage\/avatars|cfs\/files\/avatars)\/([^/?#]+)/);
if (m && m[1]) {
const avatar = await ReactiveCache.getAvatar(m[1]);
const avatarPath = avatar?.versions?.original?.path;
// GHSA-4mxf-m8pq-xc9p: only read it when it is really inside WeKan's
// own storage. A path pointing anywhere else is not an avatar.
if (avatarPath && isReadableStoredFilePath(avatarPath)) {
const file = await getBase64DataAsync(avatar);
if (file) {
user.profile = user.profile || {};
user.profile.avatarFile = file;
user.profile.avatarFileName = avatar.name;
user.profile.avatarFileType = avatar.type;
}
}
}
// user avatar is stored as a relative url, we export absolute (kept as a fallback
// reference; the embedded avatarFile above is the authoritative copy on import).
if ((user.profile || {}).avatarUrl) {
user.profile.avatarUrl = FlowRouter.url(user.profile.avatarUrl);
}
}
result.users.push(user);
}
if (security.anonymizeExportUsers) {
// Replace every exported user's identity (username/fullname/initials, and any
// avatar) with counter placeholders, and rewrite @username mentions + the
// requestedBy/assignedBy free-text fields in card and comment content.
const word = anonymizedUserWord(this._userLanguage);
const map = buildUserAnonymizationMap(result.users, word);
result.users.forEach(u => anonymizeUserDoc(u, map));
anonymizeBoardTextInPlace(result, map.byUsername);
}
return require('/server/lib/secureTransfer').secureTransfer(result, {
direction: 'export', source: 'export:wekan-json',
});
}
// ───────────────────────────────────────────────────────────────────────────
// Streaming board export.
//
// build() assembles the ENTIRE board — every card, comment, activity,
// checklist, and base64-encoded attachment — into one object and then
// JSON.stringify's it. For a board with thousands of cards or a multi-GB
// attachment that peaks at gigabytes of RAM and can blow V8's max string
// length. buildStream() instead writes the same JSON document straight to the
// HTTP response, a document at a time from raw Mongo cursors, and encodes each
// attachment file to base64 in 3-byte-aligned chunks — so peak memory stays
// flat regardless of board size. The output is byte-for-byte the same shape
// build() produces (same `_format`, same keys), so import round-trips.
//
// Only used for the full board export (no single-attachment id); the
// single-attachment path stays on build() since it returns one small object.
// ───────────────────────────────────────────────────────────────────────────
async buildStream(res) {
await require('/server/lib/adminOnlyCustomFields').assertFieldExport(this._boardId, this._customFieldViewerId);
await assertExportEnabled();
const fs = Npm.require('fs');
const { secureTransfer } = require('/server/lib/secureTransfer');
const secureExportDoc = (value, source) => secureTransfer(value, {
direction: 'export', source,
});
// Static requires only — Meteor's bundler cannot resolve a dynamic
// require(`/models/${name}`) path.
const cardsRaw = require('/models/cards').default.rawCollection();
const listsRaw = require('/models/lists').default.rawCollection();
const swimlanesRaw = require('/models/swimlanes').default.rawCollection();
const customFieldsRaw = require('/models/customFields').default.rawCollection();
const cardCommentsRaw = require('/models/cardComments').default.rawCollection();
const activitiesRaw = require('/models/activities').default.rawCollection();
const checklistsRaw = require('/models/checklists').default.rawCollection();
const checklistItemsRaw = require('/models/checklistItems').default.rawCollection();
const rulesRaw = require('/models/rules').default.rawCollection();
const triggersRaw = require('/models/triggers').default.rawCollection();
const actionsRaw = require('/models/actions').default.rawCollection();
const usersRaw = require('/models/users').default.rawCollection();
const attachmentsRaw = require('/models/attachments').default.collection.rawCollection();
// write-with-backpressure: pause when the socket buffer is full.
const w = str => writeWithBackpressure(res, str);
const noBoardId = { projection: { boardId: 0 } };
const boardId = this._boardId;
const userIds = new Set();
const cardIds = [];
const security = await getImportExportSecuritySettings();
// Anonymization pre-scan: card/comment text is streamed BEFORE the users[]
// array, so to rewrite @username mentions we must know the anonymized labels
// up front. Collect every referenced userId (small projections only, so peak
// memory stays bounded — attachments are never loaded here), then build the
// same deterministic map the users[] emission uses at the end.
const { exportScrumTransfer, scrumTransferUserIds } = require('/server/lib/scrumTransferExport');
let scrumExport = null;
if (this.hasField('scrum')) {
const selectedCards = await cardsRaw.find(await this._scopedCardSelector(boardId), { projection: { _id: 1, listId: 1, swimlaneId: 1 } }).toArray();
const selectContainers = (ids, scopeId) => this.hasScope() ? { boardId, _id: { $in: [...new Set([...ids, scopeId].filter(Boolean))] } } : { boardId };
const [selectedLists, selectedLanes] = await Promise.all([
listsRaw.find(selectContainers(selectedCards.map(c => c.listId), this._scope.listId), { projection: { _id: 1 } }).toArray(),
swimlanesRaw.find(selectContainers(selectedCards.map(c => c.swimlaneId), this._scope.swimlaneId), { projection: { _id: 1 } }).toArray(),
]);
scrumExport = await exportScrumTransfer(boardId, selectedCards.map(c => c._id), selectedLists.map(l => l._id), selectedLanes.map(s => s._id), this.hasScope(), this.hasField('custom-fields'));
scrumTransferUserIds(scrumExport?.transfer).forEach(id => userIds.add(id));
}
let anonMap = null;
if (security.anonymizeExportUsers) {
const preUserIds = new Set();
scrumTransferUserIds(scrumExport?.transfer).forEach(id => preUserIds.add(id));
const board0 = await ReactiveCache.getBoard(boardId, { fields: { members: 1 } });
(board0.members || []).forEach(m => preUserIds.add(m.userId));
const preCardIds = [];
for await (const d of cardsRaw.find({ boardId, linkedId: { $in: ['', null] } }, {
projection: {
_id: 1, userId: 1, members: 1, requesters: 1, assigners: 1,
},
})) {
preCardIds.push(d._id);
if (d.userId) preUserIds.add(d.userId);
(d.members || []).forEach(id => preUserIds.add(id));
(d.requesters || []).forEach(id => preUserIds.add(id));
(d.assigners || []).forEach(id => preUserIds.add(id));
}
for await (const d of listsRaw.find({ boardId }, { projection: { userId: 1 } })) { if (d.userId) preUserIds.add(d.userId); }
for await (const d of cardCommentsRaw.find({ cardId: { $in: preCardIds } }, { projection: { userId: 1 } })) { if (d.userId) preUserIds.add(d.userId); }
for await (const d of activitiesRaw.find({ $or: [{ boardId }, { cardId: { $in: preCardIds } }] }, { projection: { userId: 1, memberId: 1 } })) { if (d.userId) preUserIds.add(d.userId); if (d.memberId) preUserIds.add(d.memberId); }
for await (const d of checklistsRaw.find({ cardId: { $in: preCardIds } }, { projection: { userId: 1 } })) { if (d.userId) preUserIds.add(d.userId); }
const preUsers = await usersRaw
.find({ _id: { $in: Array.from(preUserIds).filter(Boolean) } }, { projection: { _id: 1, username: 1 } })
.toArray();
anonMap = buildUserAnonymizationMap(preUsers, anonymizedUserWord(this._userLanguage));
}
// Stream one collection's docs out as a JSON array value `"key":[ … ]`.
const streamArray = async (key, rawColl, selector, options = noBoardId, onDoc) => {
await w(`,${JSON.stringify(key)}:[`);
const cursor = rawColl.find(selector, options);
let i = 0;
for await (const doc of cursor) {
if (onDoc) onDoc(doc);
await w((i++ ? ',' : '') + JSON.stringify(
secureExportDoc(doc, `export:wekan-stream:${key}`),
));
}
await w(']');
return i;
};
// #1173: which cards this export is about, resolved BEFORE anything keyed off
// them is written - the attachments array is emitted first and has to be the
// scope's attachments, not the whole board's.
const cardSelector = await this._scopedCardSelector(boardId);
const scoped = this.hasScope();
let scopedCardIds = null;
if (scoped) {
scopedCardIds = [];
for await (const d of cardsRaw.find(cardSelector, { projection: { _id: 1 } })) {
scopedCardIds.push(d._id);
}
}
// Open the object with the board's own fields + _format (board data is small).
const board = await ReactiveCache.getBoard(boardId, { fields: { stars: 0 } });
if (!this.hasField('scrum')) { delete board.scrum; delete board.scrumRevision; }
if (scrumExport) { board.scrumTransfer = scrumExport.transfer; board.scrumTransferLosses = scrumExport.losses; }
(board.members || []).forEach(m => userIds.add(m.userId));
if (anonMap) anonymizeBoardTextInPlace(board, anonMap.byUsername);
const boardJson = JSON.stringify(secureExportDoc(
{ _format: 'wekan-board-1.0.0', ...board }, 'export:wekan-stream:board',
));
await w(boardJson.slice(0, -1)); // drop the trailing '}' to keep the object open
// Attachments — file bytes streamed as base64 in aligned chunks.
await w(`,"attachments":[`);
{
// An unselected section is an EMPTY array, not a missing key: the file
// still imports, it just has no attachments in it.
const attachmentSelector = !this.hasField('attachments')
? { _id: '__none__' }
: (scoped
? { 'meta.cardId': { $in: scopedCardIds } }
: { 'meta.boardId': boardId });
const cursor = attachmentsRaw.find(attachmentSelector);
let i = 0;
for await (const att of cursor) {
const head = {
_id: att._id,
cardId: att.meta && att.meta.cardId,
source: att.meta && att.meta.source,
name: att.name,
type: att.type,
};
// Open this attachment object; append "file" streamed if included.
const headJson = JSON.stringify(
secureExportDoc(head, 'export:wekan-stream:attachment'),
);
await w((i++ ? ',' : '') + (this._excludeAttachments ? headJson : headJson.slice(0, -1)));
if (!this._excludeAttachments) {
await w(',"file":"');
const filePath = att.versions && att.versions.original && att.versions.original.path;
// GHSA-4mxf-m8pq-xc9p class: the ATTACHMENT half of the same read. The
// attachment allow rule refuses a client-supplied path, so this is not
// the reported hole - but a path is only as trustworthy as every way it
// could have been written, and this streaming export is the one
// remaining place that read a stored path with nothing but an
// existsSync. Same containment check as the avatars above.
if (filePath && isReadableStoredFilePath(filePath) && fs.existsSync(filePath)) {
await new Promise((resolve, reject) => {
const rs = fs.createReadStream(filePath);
let leftover = Buffer.alloc(0);
rs.on('data', chunk => {
rs.pause();
// Emit the 3-byte-aligned base64 prefix; carry 0-2 bytes over.
const r = encodeAligned(leftover, chunk);
leftover = r.leftover;
(r.piece ? w(r.piece) : Promise.resolve()).then(() => rs.resume(), reject);
});
rs.on('end', () => {
const tail = encodeFinal(leftover);
(tail ? w(tail) : Promise.resolve()).then(resolve, reject);
});
rs.on('error', reject);
});
}
await w('"}');
}
}
}
await w(']');
// Lists / swimlanes / custom fields (bounded, but streamed uniformly).
// A scoped export carries the lists and swimlanes ITS cards refer to - the
// whole board's would be rows that import into empty columns, and none at
// all would leave the cards with nowhere to land.
let listSelector = { boardId };
let swimlaneSelector = { boardId };
if (scoped) {
const referenced = await cardsRaw
.find({ _id: { $in: scopedCardIds } }, { projection: { listId: 1, swimlaneId: 1 } })
.toArray();
const listIds = [...new Set(referenced.map(c => c.listId).filter(Boolean))];
const swimlaneIds = [...new Set(referenced.map(c => c.swimlaneId).filter(Boolean))];
if (this._scope.listId) listIds.push(this._scope.listId);
if (this._scope.swimlaneId) swimlaneIds.push(this._scope.swimlaneId);
listSelector = { boardId, _id: { $in: [...new Set(listIds)] } };
swimlaneSelector = { boardId, _id: { $in: [...new Set(swimlaneIds)] } };
}
await streamArray('lists', listsRaw, listSelector, noBoardId, d => {
userIds.add(d.userId);
if (!this.hasField('scrum')) { delete d.scrum; delete d.scrumRevision; }
});
await streamArray('swimlanes', swimlanesRaw, swimlaneSelector, {}, d => {
if (!this.hasField('scrum')) { delete d.scrum; delete d.scrumRevision; }
if (anonMap) anonymizeBoardTextInPlace({ swimlanes: [d] }, anonMap.byUsername);
});
await streamArray('customFields', customFieldsRaw,
this.hasField('custom-fields') ? { boardIds: boardId } : { _id: '__none__' },
{ projection: { boardIds: 0 } });
// Cards (non-linked, like build()) — collect ids + userIds as we go, and
// (when anonymizing) rewrite @mentions + requestedBy/assignedBy in each card.
await streamArray('cards', cardsRaw, cardSelector, noBoardId, d => {
if (!this.hasField('scrum')) { delete d.scrum; delete d.scrumRevision; }
cardIds.push(d._id);
userIds.add(d.userId);
(d.members || []).forEach(id => userIds.add(id));
if (anonMap) anonymizeBoardTextInPlace({ cards: [d] }, anonMap.byUsername);
});
// Everything keyed by the card ids we just streamed.
await streamArray('comments', cardCommentsRaw,
this.hasField('comments') ? { cardId: { $in: cardIds } } : { _id: '__none__' },
noBoardId, d => {
userIds.add(d.userId);
if (anonMap) anonymizeBoardTextInPlace({ comments: [d] }, anonMap.byUsername);
});
// A scoped export's activities are its cards', not the board's - a swimlane
// export carrying every board-level activity would be mostly other people's
// swimlanes.
const activitySelector = !this.hasField('activities')
? { _id: '__none__' }
: (scoped
? { cardId: { $in: cardIds } }
: { $or: [{ boardId }, { cardId: { $in: cardIds } }] });
await streamArray('activities', activitiesRaw, activitySelector, noBoardId, d => userIds.add(d.userId));
// A checklist scope exports THAT checklist, on the card that holds it.
const checklistSelector = !this.hasField('checklists')
? { _id: '__none__' }
: (this._scope.checklistId
? { _id: this._scope.checklistId }
: { cardId: { $in: cardIds } });
const checklistItemSelector = !this.hasField('checklists')
? { _id: '__none__' }
: (this._scope.checklistId
? { checklistId: this._scope.checklistId }
: { cardId: { $in: cardIds } });
await streamArray('checklists', checklistsRaw, checklistSelector, {}, d => userIds.add(d.userId));
await streamArray('checklistItems', checklistItemsRaw, checklistItemSelector, {});
await streamArray('subtaskItems', cardsRaw,
// #3626: a subtask under any of its parents.
this.hasField('subtasks') ? { boardId, $or: [{ parentId: { $in: cardIds } }, { parentIds: { $in: cardIds } }] } : { _id: '__none__' }, {});
// Rules + their triggers/actions.
const ruleTriggerIds = [];
const ruleActionIds = [];
await streamArray('rules', rulesRaw, scoped ? { _id: '__none__' } : { boardId }, noBoardId, d => {
// #4294: extra triggers/actions travel with their rule.
const parts = require('/models/lib/ruleParts');
ruleTriggerIds.push(...parts.ruleTriggerIds(d)); ruleActionIds.push(...parts.ruleActionIds(d));
});
await streamArray('triggers', triggersRaw, { _id: { $in: ruleTriggerIds } }, noBoardId);
await streamArray('actions', actionsRaw, { _id: { $in: ruleActionIds } }, noBoardId);
// Users last, once every referenced id has been collected. Only safe fields
// (username, fullname, initials, avatarUrl) — never passwords, emails or services.
// Each member whose avatar is a LOCAL WeKan file also carries the file itself as
// base64, so the original picture round-trips through export/import (and, since it
// reads a local file with no outbound fetch, works inside a Sandstorm grain).
await w(`,"users":[`);
{
const avatarsRaw = require('/models/avatars').default.collection.rawCollection();
const cursor = usersRaw.find(
{ _id: { $in: Array.from(userIds).filter(Boolean) } },
{ projection: { _id: 1, username: 1, 'profile.fullname': 1, 'profile.initials': 1, 'profile.avatarUrl': 1 } },
);
let i = 0;
for await (const user of cursor) {
if (security.disableExportAvatars) {
// Admin Panel / Features / Security: never carry avatars out of WeKan.
if (user.profile) delete user.profile.avatarUrl;
} else {
const localUrl = (user.profile && user.profile.avatarUrl) || '';
const m = localUrl.match(/\/(?:cdn\/storage\/avatars|cfs\/files\/avatars)\/([^/?#]+)/);
if (m && m[1]) {
const avatar = await avatarsRaw.findOne({ _id: m[1] });
const p = avatar && avatar.versions && avatar.versions.original && avatar.versions.original.path;
// GHSA-4mxf-m8pq-xc9p: same containment check as the non-streaming
// export above - never read a stored path from outside the storage.
if (p && isReadableStoredFilePath(p)) {
try {
const buf = fs.readFileSync(p);
user.profile = user.profile || {};
user.profile.avatarFile = buf.toString('base64');
user.profile.avatarFileName = avatar.name;
user.profile.avatarFileType = avatar.type;
} catch (e) { /* unreadable avatar file — export URL only */ }
}
}
if (user.profile && user.profile.avatarUrl) {
user.profile.avatarUrl = FlowRouter.url(user.profile.avatarUrl);
}
}
// Anonymize identity (and drop any avatar) using the pre-scan map.
if (anonMap) anonymizeUserDoc(user, anonMap);
await w((i++ ? ',' : '') + JSON.stringify(
secureExportDoc(user, 'export:wekan-stream:user'),
));
}
}
await w(']');
await w('}'); // close the board object
}
async buildCsv(userDelimiter = ',', userLanguage='en') {
await require('/server/lib/adminOnlyCustomFields').assertFieldExport(this._boardId, this._customFieldViewerId);
const result = await this.build();
const columnHeaders = [];
const cardRows = [];
const papaconfig = {
quotes: true,
quoteChar: '"',
escapeChar: '"',
delimiter: userDelimiter,
header: true,
newline: "\r\n",
skipEmptyLines: false,
escapeFormulae: true,
};
columnHeaders.push(
TAPi18n.__('title','',userLanguage),
TAPi18n.__('description','',userLanguage),
TAPi18n.__('list','',userLanguage),
TAPi18n.__('swimlane','',userLanguage),
TAPi18n.__('owner','',userLanguage),
TAPi18n.__('requested-by','',userLanguage),
TAPi18n.__('assigned-by','',userLanguage),
TAPi18n.__('members','',userLanguage),
TAPi18n.__('assignee','',userLanguage),
TAPi18n.__('labels','',userLanguage),
TAPi18n.__('card-start','',userLanguage),
TAPi18n.__('card-due','',userLanguage),
TAPi18n.__('card-end','',userLanguage),
TAPi18n.__('overtime-hours','',userLanguage),
TAPi18n.__('spent-time-hours','',userLanguage),
TAPi18n.__('createdAt','',userLanguage),
TAPi18n.__('last-modified-at','',userLanguage),
TAPi18n.__('last-activity','',userLanguage),
TAPi18n.__('voting','',userLanguage),
TAPi18n.__('archived','',userLanguage),
);
const customFieldMap = {};
let i = 0;
result.customFields.forEach((customField) => {
customFieldMap[customField._id] = {
position: i,
type: customField.type,
};
if (customField.type === 'dropdown' || customField.type === 'dropdownMultiSelect') {
let options = '';
customField.settings.dropdownItems.forEach((item) => {
options = options === '' ? item.name : `${`${options}/${item.name}`}`;
});
columnHeaders.push(
`CustomField-${customField.name}-${customField.type}-${options}`,
);
} else if (customField.type === 'currency') {
columnHeaders.push(
`CustomField-${customField.name}-${customField.type}-${customField.settings.currencyCode}`,
);
} else {
columnHeaders.push(
`CustomField-${customField.name}-${customField.type}`,
);
}
i++;
});
//cardRows.push([[columnHeaders]]);
cardRows.push(columnHeaders);
result.cards.forEach((card) => {
// #5604: build the row via a null-safe helper so a card that references a
// deleted list/swimlane/owner/member/assignee/label/customField exports a
// blank cell instead of crashing the whole export with
// "Cannot read property 'title' of undefined".
const currentRow = buildCsvCardRow(card, result, customFieldMap);
//cardRows.push([[currentRow]]);
cardRows.push(currentRow);
});
return Papa.unparse(cardRows, papaconfig);
}
// Streaming CSV/TSV export. buildCsv() calls build(), which loads the ENTIRE
// board — including every base64 attachment — into memory just to emit card
// rows. buildCsvStream() instead keeps only the small lookup tables (lists,
// swimlanes, custom fields, labels, referenced users) in memory and streams
// the cards from a raw cursor, writing one CSV row at a time to `res`. Two
// cheap passes over the card cursor: pass 1 collects referenced user ids
// (strings only), pass 2 writes rows. Output matches buildCsv() exactly.
async buildCsvStream(res, userDelimiter = ',', userLanguage = 'en') {
await require('/server/lib/adminOnlyCustomFields').assertFieldExport(this._boardId, this._customFieldViewerId);
const cardsRaw = require('/models/cards').default.rawCollection();
const cardSelector = { boardId: this._boardId, linkedId: { $in: ['', null] } };
const board = await ReactiveCache.getBoard(this._boardId);
const lookup = {
lists: await ReactiveCache.getLists({ boardId: this._boardId }),
swimlanes: await ReactiveCache.getSwimlanes({ boardId: this._boardId }),
customFields: await ReactiveCache.getCustomFields({ boardIds: this._boardId }),
labels: (board && board.labels) || [],
users: [],
};
const papaconfig = {
quotes: true, quoteChar: '"', escapeChar: '"', delimiter: userDelimiter,
header: false, newline: '\r\n', skipEmptyLines: false, escapeFormulae: true,
};
const w = str => writeWithBackpressure(res, str);
const writeRow = row => w(Papa.unparse([row], papaconfig) + papaconfig.newline);
// Header row + custom-field columns (same order as buildCsv).
//
// #1173: the export selection lands on COLUMNS here. The keys are kept
// UNTRANSLATED first so the mask can be built from them - a translated
// header is a label, not an identity - and the same mask then filters the
// header and every row, so the two cannot drift apart.
const columnKeys = [
'title','description','list','swimlane','owner','requested-by','assigned-by',
'members','assignee','labels','card-start','card-due','card-end','overtime-hours',
'spent-time-hours','createdAt','last-modified-at','last-activity','voting','archived',
];
const columnHeaders = columnKeys.map(k => TAPi18n.__(k, '', userLanguage));
const customFieldMap = {};
lookup.customFields.forEach((cf, i) => {
customFieldMap[cf._id] = { position: i, type: cf.type };
if (cf.type === 'dropdown' || cf.type === 'dropdownMultiSelect') {
let options = '';
cf.settings.dropdownItems.forEach(item => { options = options === '' ? item.name : `${options}/${item.name}`; });
columnHeaders.push(`CustomField-${cf.name}-${cf.type}-${options}`);
} else if (cf.type === 'currency') {
columnHeaders.push(`CustomField-${cf.name}-${cf.type}-${cf.settings.currencyCode}`);
} else {
columnHeaders.push(`CustomField-${cf.name}-${cf.type}`);
}
});
const columnMask = csvColumnMask(columnKeys, lookup.customFields.length,
this._fields ? [...this._fields] : null);
await writeRow(applyMask(columnHeaders, columnMask));
// Pass 1 — collect referenced user ids (ids only, cheap).
const userIds = new Set();
{
const cursor = cardsRaw.find(cardSelector, { projection: {
userId: 1, members: 1, assignees: 1, requesters: 1, assigners: 1, vote: 1,
} });
for await (const c of cursor) {
if (c.userId) userIds.add(c.userId);
(c.members || []).forEach(id => userIds.add(id));
(c.assignees || []).forEach(id => userIds.add(id));
(c.requesters || []).forEach(id => userIds.add(id));
(c.assigners || []).forEach(id => userIds.add(id));
if (c.vote) { (c.vote.positive || []).forEach(id => userIds.add(id)); (c.vote.negative || []).forEach(id => userIds.add(id)); }
}
}
lookup.users = await ReactiveCache.getUsers(
{ _id: { $in: Array.from(userIds).filter(Boolean) } },
{ fields: { _id: 1, username: 1 } },
);
// Pass 2 — stream one row per card.
{
const cursor = cardsRaw.find(cardSelector);
for await (const card of cursor) {
await writeRow(applyMask(buildCsvCardRow(card, lookup, customFieldMap), columnMask));
}
}
}
async canExport(user) {
this._customFieldViewerId = user?._id;
await require('/server/lib/adminOnlyCustomFields').assertFieldExport(this._boardId, this._customFieldViewerId);
const board = await ReactiveCache.getBoard(this._boardId);
const { canExportBoardData } = require('/models/lib/exportAccess');
return canExportBoardData(board, user);
}
}