Files
wekan/models/importZip.js
T
Lauri Ojansivu a7cd22f94c Import: a .zip that becomes a new board, and a Trello API import, run as the importing user.
POST /api/import/zip?newBoard=1 - All Boards / Import of a WeKan .zip, and
"Import many boards" - answered 500 for every archive that named people:
"Meteor.userId can only be invoked inside a method, publication, or WebApp
endpoint". trackImport() runs the import at once, and only the await of its
promise was wrapped in the importer's method context, so the creator had
already asked Meteor.userId() for the file's people (membersMode=me) and for
rows with no author. The Trello API import job started TrelloCreator with no
context at all. Both now start the import inside the context.

tests/importZipUserContext.test.cjs requires every trackImport() outside a
Meteor method to be started inside withValue or runAsUser, and finds the old
shape nowhere. tests/playwright/specs/gitea-backup-wekan-import.e2e.js
imports a Gitea backup's WeKan .zip as a new board through the route, with
its cards, comments, labels and files.

Thanks to xet7 !
2026-11-22 16:39:48 +02:00

242 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');
// The import STARTS inside the importer's method context, not merely is
// awaited in it: trackImport runs execute() at once, and everything it
// reaches - the people the file names becoming the importer
// (membersMode=me), the author of a row with none - asks Meteor.userId(),
// which outside a context threw, so every .zip that became a new board
// answered 500 (tests/importZipUserContext.test.cjs).
const newBoardId = await DDP._CurrentMethodInvocation.withValue(
{ userId: user._id, isSimulation: false, connection: null },
() => require('/server/importRuns').trackImport({ userId: user._id, source: 'wekan-zip', creator,
execute: () => creator.create(doc, null) }).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(() => {});
}
}));
});