Files
wekan/models/importZip.js
T
Lauri Ojansivu 3b1c7ce7bb WeKan and Trello .zip imports use the shared upload, limit and disk check; .mbox and .enex export a page at a time.
The WeKan .zip route and the Trello package route wrote their uploads
with caps of their own (5 GB and 200 MB, 1 GB unpacked). They now go
through the same receiver as every Import page upload: the Admin Panel's
largest import (else WEKAN_IMPORT_ZIP_MAX_BYTES for the WeKan zip), or
with none the free disk space, checked before and while the file is
written, and a Trello package may unpack to as much as that.

The .mbox and .enex exports are written to the response 500 cards at a
time, waiting for the socket when it is full, instead of being built
whole in memory; the pages together are the same file. TODO.md keeps
what is left: streamed reading of large JSON and text, and the other
formats' exports.

Thanks to xet7 !
2026-11-20 06:10:37 +02:00

237 lines
11 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { ReactiveCache } from '/imports/reactiveCache';
import { runOnServer } from './runOnServer';
import {
BOARD_EXPORT_FIELD_KEYS,
parseExportFields,
parseExportScope,
} from './lib/exportFields';
import { pruneImportDocument } from './lib/importParts';
import { validateImportSourceShape } from './lib/importSourceShape';
const { safeEntryPath } = require('./lib/backupPaths');
// The wekan.json of an import zip inflates to at most this (ZipBombBleed).
const MAX_IMPORT_DOCUMENT_BYTES = 256 * 1024 * 1024;
runOnServer(function () {
const fs = Npm.require('fs');
const path = Npm.require('path');
const { WebApp } = require('meteor/webapp');
const { safeRoute } = require('/server/apiMiddleware');
const { Authentication } = require('/server/authentication');
const { assertImportEnabled } = require('./lib/importExportSecurity');
// A .zip import that does not hold the archive in memory (#1173).
//
// The browser used to unpack an archive and send its attachments as base64
// over DDP, which is fine for a card and wrong for a board: a 2 GB archive
// became 2.7 GB of base64 in one message. This route takes the file itself.
//
// Nothing is ever whole in memory on the way in:
// * the request body is streamed to a temp file as it arrives;
// * `unzipper.Open.file` reads the archive's central directory, so entries
// are opened on demand rather than inflated together - the same thing the
// backup restore does (server/methods/backup.js);
// * each attachment is piped from the archive into the attachments
// collection by `addAttachmentFromStream`, which writes it to a temp file
// and hands the PATH to Meteor-Files rather than a Buffer.
//
// Where the files END UP is not decided here: `addFile` fires the collection's
// onAfterUpload, which validates the file and moves it to the default storage
// configured in the Admin Panel, exactly as an ordinary upload does.
//
// ZipBleed: an entry's name is data, so `attachments/` is matched literally
// and the name is never used as a path - a temp name is generated instead, so
// an entry called `../../etc/cron.d/x` can only ever be an attachment called
// that.
// The upload is streamed to WRITABLE_PATH/import-uploads by the same receiver
// as every Import page upload (server/lib/importUpload.js): the free space is
// checked before and while it is written, and the largest import is the
// Admin Panel's (Settings / Security), else WEKAN_IMPORT_ZIP_MAX_BYTES when
// set, else none - as large as the free disk space lets it finish. Its name
// is generated, never the archive's, and the entries below are matched by
// name, never used as paths.
const receiveToTempFile = async req => {
const { receiveUpload } = require('/server/lib/importUpload');
const { importLimitBytes } = require('/server/lib/importDiskSpace');
const Settings = require('/models/settings').default;
const configured = parseInt(process.env.WEKAN_IMPORT_ZIP_MAX_BYTES, 10);
const limit = importLimitBytes(await Settings.findOneAsync({}, { fields: { importMaxMegabytes: 1 } }))
|| (Number.isFinite(configured) && configured > 0 ? configured : 0);
try {
const { file, size } = await receiveUpload(req, { userId: 'import-zip', source: 'wekan', limit });
// The generated name is still proven to be beneath the upload directory
// (ZipBleed: tests/fixedVulnerabilityClasses.test.cjs).
const tempPath = safeEntryPath(require('path').dirname(file), [require('path').basename(file)]);
if (!tempPath) throw new Error('import-temp-path');
return { tempPath, received: size };
} catch (error) {
if (error && error.code === 'import-too-large') throw new Error('import-zip-too-large');
if (error && error.code === 'import-disk-full') throw new Error('import-disk-full');
throw error;
}
};
/**
* @operation importZip
* @tag Boards
* @summary Import a .zip export - the document and its attachment files.
* @description POST the .zip as the request body. Takes the same `fields`,
* `swimlaneId`, `listId`, `cardId` and `checklistId` parameters as the
* exports: with one of those ids it imports beside that thing, without one it
* imports the whole document into the board named by `boardId`.
* @param {string} boardId the board to import into
* @param {string} authToken the loginToken
*/
WebApp.handlers.post('/api/import/zip', safeRoute(async function (req, res) {
const answer = (code, data) => {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(data));
};
let user = null;
const loginToken = req.query && req.query.authToken;
if (loginToken) {
if (String(loginToken).length > 10000) {
answer(400, { error: 'Bad request' });
return;
}
user = await require('/server/lib/activeUser').activeUserByToken(loginToken, 'importZip', req);
if (!user) {
answer(401, { error: 'Invalid token' });
return;
}
} else {
try {
Authentication.checkLoggedIn(req.userId);
} catch (error) {
answer(error.statusCode || 403, { error: 'Unauthorized' });
return;
}
user = await ReactiveCache.getUser({ _id: req.userId });
}
// newBoard=1 (All Boards > Import, and "Import many boards"): the .zip
// becomes a NEW board through the full-board importer, as its .json would,
// with the attachment files put back on their rows as the .json carries
// them. Without it, the document is imported into the board named here.
const newBoard = req.query && req.query.newBoard === '1';
const boardId = req.query && req.query.boardId;
const board = boardId ? await ReactiveCache.getBoard(boardId) : null;
if (!board && !newBoard) {
answer(404, { error: 'Not found' });
return;
}
// Importing WRITES, so this is "may you change it", not "may you see it" -
// the same check the DDP import method makes: write access, not mere
// active membership (MutationBleed sibling, 2026-10-02 - read-only,
// comment-only and worker members could import into a board).
const { memberCan } = require('/models/lib/boardRoleCapabilities');
if (board && (!board.isVisibleBy(user) || !memberCan(board.members || [], user._id, 'write'))) {
answer(403, { error: 'Forbidden' });
return;
}
try {
await assertImportEnabled();
} catch (error) {
answer(403, { error: 'Import is disabled' });
return;
}
let tempPath = null;
try {
const received = await receiveToTempFile(req);
tempPath = received.tempPath;
const unzipper = require('unzipper');
const directory = await unzipper.Open.file(tempPath);
const documentEntry = directory.files.find(entry =>
entry.type === 'File' && /(^|\/)wekan\.json$/.test(entry.path));
if (!documentEntry) {
answer(400, { error: 'import-not-wekan-export' });
return;
}
// ZipBombBleed: the document inflates under a byte limit, counted.
const { readZipEntryBounded } = require('/server/lib/boundedZipEntry');
const parsedDoc = JSON.parse((await readZipEntryBounded(documentEntry, MAX_IMPORT_DOCUMENT_BYTES)).toString('utf8'));
const doc = require('/server/lib/secureTransfer').secureTransfer(parsedDoc, {
direction: 'import', source: 'import:zip', userId: user._id,
ip: req.connection && req.connection.remoteAddress,
});
if (doc._format && doc._format !== 'wekan-board-1.0.0') {
answer(400, { error: 'invalid-format' });
return;
}
const fields = parseExportFields(req.query && req.query.fields, BOARD_EXPORT_FIELD_KEYS);
pruneImportDocument(doc, fields);
// attachmentId -> the entry holding its bytes. The name is
// `attachments/<id>-<name>`, and only the id before the first dash is
// read: the rest is a filename from another machine and is not used as
// one here.
const entriesById = new Map();
for (const entry of directory.files) {
if (entry.type !== 'File') continue;
const match = /(?:^|\/)attachments\/([^/]+)$/.exec(entry.path);
if (!match) continue;
const base = match[1];
const dash = base.indexOf('-');
entriesById.set(dash === -1 ? base : base.slice(0, dash), entry);
}
// Each attachment as a fresh read stream, opened only when the importer
// asks for it - which is what keeps one attachment in flight at a time.
const attachmentStream = attachment => {
const entry = entriesById.get(attachment && attachment._id);
return entry ? entry.stream() : null;
};
if (newBoard) {
// A new board from the whole document, by the full-board importer,
// with each attachment file streamed from the archive into storage as
// the importer reaches it - never held in memory, whatever its size,
// within only the Admin Panel's upload limit.
validateImportSourceShape('wekan', doc);
const { WekanCreator } = require('./wekanCreator');
const creator = new WekanCreator({ membersMode: req.query && req.query.membersMode, importFields: fields });
creator.attachmentStream = attachmentStream;
const { DDP } = require('meteor/ddp');
const tracked = require('/server/importRuns').trackImport({ userId: user._id, source: 'wekan-zip', creator,
execute: () => creator.create(doc, null) });
const newBoardId = await DDP._CurrentMethodInvocation.withValue(
{ userId: user._id, isSimulation: false, connection: null },
() => tracked.promise,
);
answer(200, { ok: true, boardId: newBoardId });
return;
}
const scope = parseExportScope(req.query);
const { ScopedImporter } = require('./server/scopedImporter');
const importer = new ScopedImporter(
{ boardId, ...scope },
doc,
{ userId: user._id, fields, attachmentStream, source: 'import:zip' },
);
const counts = await importer.run();
answer(200, { ok: true, counts });
} catch (error) {
// ImportPlacementBleed: a list, swimlane or card of another board is a
// bad request, answered as the REST card create answers it.
if (error && error.error === 'error-import-placement') {
answer(400, { error: error.reason });
return;
}
const message = error && ['import-zip-too-large', 'import-disk-full'].includes(error.message)
? error.message
: 'import-failed';
console.error('importZip failed', error);
answer(message === 'import-zip-too-large' ? 413 : message === 'import-disk-full' ? 507 : 500, { error: message });
} finally {
if (tempPath) fs.promises.unlink(tempPath).catch(() => {});
}
}));
});