mirror of
https://github.com/wekan/wekan.git
synced 2026-11-24 18:10:06 -05:00
Four Kanban and Scrum practices other tools have, kept on the card (card.flow, models/lib/cardFlow.js), offline and with no AI: - Blocked: ticked with a reason; who marked it and since when are the server's. A red Blocked badge on the minicard, the reason its tooltip. - Class of service: Standard, Fixed date, Expedite, Intangible. Expedite has a WIP limit of one open card per board; a second is refused. - MoSCoW priority: Must, Should, Could, Won't have. - WSJF score: business value, time criticality and risk reduction divided by job size, each on the 1-20 scale; shown once every part is set. Each is a row of Board Settings / Card in the Card section, off on the card and the minicard until a board turns it on, and an Admin Panel / Features / Card field that hides it on every board. Written only by the setCardFlow method, which checks the card edit right, an assigned-only member's own cards and the values; a client write of flow is denied. Translated in every language. Thanks to xet7 !
2953 lines
126 KiB
JavaScript
2953 lines
126 KiB
JavaScript
import { cardWithChecklists } from '/server/lib/checklistDeadlines';
|
|
import { canWriteSubtaskDeposit, recordSubtaskDepositDenial } from '/server/lib/subtaskDepositAccess';
|
|
import { recordLinkedWriteDenial } from '/models/lib/linkedWritePolicy';
|
|
const { isAssignedOnlyMember } = require('/models/lib/boardCardScope');
|
|
const { restCardListItem } = require('/models/lib/restCardListItem');
|
|
import { Meteor } from 'meteor/meteor';
|
|
import { WebApp } from 'meteor/webapp';
|
|
import { check, Match } from 'meteor/check';
|
|
import { Random } from 'meteor/random';
|
|
import { ReactiveCache } from '/imports/reactiveCache';
|
|
import { add, now } from '/imports/lib/dateUtils';
|
|
import { Authentication } from '/server/authentication';
|
|
import { sendJsonResult } from '/server/apiMiddleware';
|
|
import { allowIsBoardMember, allowIsBoardMemberWithWriteAccess, computeSortForIndex, mergeLabelIds, canAssignCardMember, isCardDateClear } from '/server/lib/utils';
|
|
import { computeTopSort, normalizeMoveParams, parseCardDate, parseCardScalarFields } from '/server/lib/restCardHelpers';
|
|
const { coerceRestArrayParam } = require('/server/lib/restArrayParam');
|
|
const { applyCardBoardConsistency } = require('/server/lib/cardBoardConsistency');
|
|
const { stampCardListEntry } = require('/models/lib/cardListEntry');
|
|
const { removeClaimedCard, cascadeIfRemoved } = require('/models/lib/claimedCardRemoval');
|
|
import { titleChanged } from '/server/lib/titleChangeActivity';
|
|
import { descriptionChanged } from '/server/lib/descriptionChangeActivity';
|
|
import { timingChange } from '/server/lib/timingChangeActivity';
|
|
const { collectionWriteSucceeded } = require('/server/lib/collectionWriteOutcome');
|
|
const { deferSyncRecording, deferSyncLabelActivities } = require('/server/lib/syncRecordingScope');
|
|
const { movedScrumMetadata } = require('/models/lib/scrumCopy');
|
|
import { scrumPlanningPair } from '/server/lib/scrumPlanningPair';
|
|
const { scrumRevisionSelector } = require('/models/lib/scrum');
|
|
import { buildDeleteCardActivity } from '/server/lib/deleteActivities';
|
|
import { assertParentCardIsVisible } from '/server/lib/visibleBoardIds';
|
|
import { computeSubtaskLabelIds } from '/models/lib/subtaskLabelInheritance';
|
|
import Activities from '/models/activities';
|
|
import Boards from '/models/boards';
|
|
import TableVisibilityModeSettings from '/models/tableVisibilityModeSettings';
|
|
import Cards, {
|
|
addCronJob,
|
|
cardAssignees,
|
|
cardCreation,
|
|
cardCustomFields,
|
|
cardLabels,
|
|
cardMembers,
|
|
cardMove,
|
|
cardRemover,
|
|
cardState,
|
|
updateActivities,
|
|
} from '/models/cards';
|
|
import Lists from '/models/lists';
|
|
import Swimlanes from '/models/swimlanes';
|
|
import CustomFields from '/models/customFields';
|
|
import { syncCardChildrenBoard } from '/server/lib/cardChildrenBoardSync';
|
|
import { subtaskCustomFields } from '/imports/lib/subtaskHelpers';
|
|
import { ensureIndex } from '/server/lib/mongoStartup';
|
|
import { canEditCardOrLinkedCard } from '/server/lib/linkedCardPermission';
|
|
import { assertListNotRefused, assertCardListsNotRefused, assertListsWritable, listException } from '/server/lib/listPermissionGate';
|
|
// #4693: setSubtaskDone - tick a subtask done from the parent's Subtasks list.
|
|
import '/server/lib/subtaskDoneMethod';
|
|
import '/server/lib/cardFlowMethod';
|
|
import getSlug from 'limax';
|
|
// ErrorBleed: refusals answer with their real status and a safe message.
|
|
const { publicErrorData } = require('/server/lib/apiResponseHelpers');
|
|
|
|
const getTAPi18n = () => require('/imports/i18n').TAPi18n;
|
|
const { isOpenPermission } = require('/models/lib/boardPermission');
|
|
const { parentFields } = require('/models/lib/cardParents');
|
|
|
|
function getTranslatedString(key, fallback, options) {
|
|
const i18n = getTAPi18n && getTAPi18n();
|
|
if (!i18n || !i18n.i18n) {
|
|
return fallback;
|
|
}
|
|
const translated = i18n.__(key, options);
|
|
return typeof translated === 'string' ? translated : fallback;
|
|
}
|
|
|
|
// #6613 / LinkedWriteBleed: the one rule for creating a linked card, used by
|
|
// the createLinkedCard method and the REST route (linkedId) alike. The REST
|
|
// route used to check only READ access on the source board and clone the whole
|
|
// source card, so a read-only or assigned-only member could link - and copy -
|
|
// cards the method refuses them.
|
|
// GHSA-6xqf-jh8x-4wxc: an assigned-only member's write on a card not assigned
|
|
// to them. No view shows them such a card, so it is an attempt: recorded in
|
|
// Admin Panel -> Problems as UnassignedArchiveBleed (medium: never disables).
|
|
function recordUnassignedCardWrite(userId, source) {
|
|
try {
|
|
require('/server/lib/securityLog').record({
|
|
key: 'authz.assigned-card-write', action: 'blocked', source, userId,
|
|
detail: 'Assigned-only member changed a card not assigned to them.',
|
|
});
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
}
|
|
|
|
async function createLinkedCardFor(userId, sourceCardId, boardId, swimlaneId, listId, sort, source) {
|
|
check(sourceCardId, String);
|
|
check(boardId, String);
|
|
check(swimlaneId, String);
|
|
check(listId, String);
|
|
check(sort, Number);
|
|
if (!userId) throw new Meteor.Error('not-authorized');
|
|
if (!Number.isFinite(sort)) throw new Meteor.Error('invalid-sort');
|
|
|
|
const [sourceCard, destinationBoard, destinationList, destinationSwimlane] =
|
|
await Promise.all([
|
|
Cards.findOneAsync(sourceCardId),
|
|
Boards.findOneAsync(boardId),
|
|
Lists.findOneAsync(listId),
|
|
Swimlanes.findOneAsync(swimlaneId),
|
|
]);
|
|
if (!sourceCard || !destinationBoard || !destinationList || !destinationSwimlane) {
|
|
throw new Meteor.Error('not-found');
|
|
}
|
|
const sourceBoard = await Boards.findOneAsync(sourceCard.boardId);
|
|
if (!sourceBoard || !allowIsBoardMemberWithWriteAccess(userId, sourceBoard)) {
|
|
recordLinkedWriteDenial(source);
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
// An assigned-only member links only cards assigned to them: the link shows
|
|
// the source card's content in a board they control.
|
|
if (isAssignedOnlyMember(sourceBoard, userId) && !(sourceCard.assignees || []).includes(userId)) {
|
|
recordLinkedWriteDenial(source);
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
if (!allowIsBoardMemberWithWriteAccess(userId, destinationBoard)) {
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
// GHSA-83w9-74mx-7v83: a list that refuses this role refuses a new linked
|
|
// card in it too; the insert below is server code, past the allow/deny rules.
|
|
await assertListsWritable(userId, destinationBoard, [listId]);
|
|
if (
|
|
sourceCard.linkedId ||
|
|
sourceCard.archived === true ||
|
|
destinationList.archived === true ||
|
|
destinationSwimlane.archived === true ||
|
|
destinationList.boardId !== boardId ||
|
|
destinationSwimlane.boardId !== boardId ||
|
|
sourceCard.type === 'template-card' ||
|
|
sourceCard.type === 'cardType-linkedCard' ||
|
|
sourceCard.type === 'cardType-linkedBoard'
|
|
) {
|
|
throw new Meteor.Error('invalid-linked-card');
|
|
}
|
|
|
|
return await Cards.insertAsync({
|
|
title: sourceCard.title || '',
|
|
listId,
|
|
swimlaneId,
|
|
boardId,
|
|
sort,
|
|
type: 'cardType-linkedCard',
|
|
linkedId: sourceCardId,
|
|
cardNumber: await destinationBoard.getNextCardNumber(),
|
|
userId: userId,
|
|
});
|
|
}
|
|
|
|
Meteor.methods({
|
|
// #4495: create a brand-new board from an EXISTING card, in one step, and
|
|
// link that same card to it — without leaving the card. This reuses the
|
|
// exact board-creation shape server/models/boards.js's own `/api/boards`
|
|
// endpoint uses (an admin member, a default swimlane), and then sets on the
|
|
// card the exact same fields the "Link to board" popup sets when linking to
|
|
// a whole board (client/components/lists/listBody.js `.js-link-board`):
|
|
// `type: 'cardType-linkedBoard'`, `linkedId: <boardId>`. Nothing else on the
|
|
// card is touched, so this is a conversion of the existing card, not a copy.
|
|
async createBoardFromCard(cardId, title) {
|
|
check(cardId, String);
|
|
check(title, Match.Optional(String));
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = await Cards.findOneAsync(cardId);
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
if (card.archived === true) throw new Meteor.Error('invalid-card');
|
|
if (
|
|
card.type === 'template-card' ||
|
|
card.type === 'cardType-linkedCard' ||
|
|
card.type === 'cardType-linkedBoard'
|
|
) {
|
|
// Already a link, or a template card: nothing sensible to convert.
|
|
throw new Meteor.Error('invalid-linked-card');
|
|
}
|
|
|
|
const sourceBoard = await Boards.findOneAsync(card.boardId);
|
|
if (!sourceBoard || !allowIsBoardMemberWithWriteAccess(this.userId, sourceBoard)) {
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
// GHSA-6xqf-jh8x-4wxc: the board's write capability is not enough. An
|
|
// assigned-only member converts only a card assigned to them, as copyCard
|
|
// allows them only theirs (models/lib/boardCardScope.js).
|
|
if (!require('/models/lib/boardCardScope').assignedOnlyAllowsCard(sourceBoard, this.userId, card)) {
|
|
recordUnassignedCardWrite(this.userId, 'method:createBoardFromCard');
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
// ListLockBulkBleed: converting the card is a write in its list.
|
|
await assertListsWritable(this.userId, sourceBoard, [card.listId]);
|
|
// CreateBleed: the card becomes a new working board.
|
|
const { assertMayCreateBoard } = require('/server/lib/boardCreationGuard');
|
|
await assertMayCreateBoard(this.userId, { source: 'method:createBoardFromCard', type: 'board' });
|
|
|
|
const boardTitle = (title && title.trim()) || card.title || '';
|
|
if (!boardTitle) throw new Meteor.Error('invalid-title');
|
|
|
|
const privateOnly = await TableVisibilityModeSettings.findOneAsync(
|
|
'tableVisibilityMode-allowPrivateOnly',
|
|
);
|
|
const requestedPermission = isOpenPermission(sourceBoard.permission) ? sourceBoard.permission : 'private';
|
|
const permission = privateOnly?.booleanValue ? 'private' : requestedPermission;
|
|
if (privateOnly?.booleanValue && isOpenPermission(requestedPermission)) {
|
|
try {
|
|
require('/server/lib/securityLog').record({
|
|
key: 'authz.board-visibility', action: 'blocked',
|
|
source: 'createBoardFromCard',
|
|
detail: 'Inherited public visibility overridden by private-only policy.',
|
|
});
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
}
|
|
|
|
const boardId = await Boards.insertAsync({
|
|
title: boardTitle,
|
|
slug: getSlug(boardTitle) || 'board',
|
|
members: [
|
|
{
|
|
userId: this.userId,
|
|
isAdmin: true,
|
|
isActive: true,
|
|
isNoComments: false,
|
|
isCommentOnly: false,
|
|
isWorker: false,
|
|
},
|
|
],
|
|
permission,
|
|
color: sourceBoard.color,
|
|
migrationVersion: 1,
|
|
});
|
|
await Swimlanes.insertAsync({
|
|
title: getTranslatedString('default', 'Default'),
|
|
boardId,
|
|
});
|
|
|
|
// The same two fields the existing "Link to board" flow sets — nothing
|
|
// else on the card changes.
|
|
await Cards.updateAsync(cardId, {
|
|
$set: {
|
|
type: 'cardType-linkedBoard',
|
|
linkedId: boardId,
|
|
},
|
|
});
|
|
|
|
return boardId;
|
|
},
|
|
// #6613: create cross-board card links as an acknowledged, authoritative
|
|
// operation. A direct client insert could be rejected after the optimistic
|
|
// write, leaving the Link popup open without creating anything.
|
|
async createLinkedCard(sourceCardId, boardId, swimlaneId, listId, sort) {
|
|
return createLinkedCardFor(this.userId, sourceCardId, boardId, swimlaneId, listId, sort, 'createLinkedCard');
|
|
},
|
|
|
|
// #6608: archive one card selection as one acknowledged server operation.
|
|
// The old sidebar loop issued direct client collection updates and closed
|
|
// immediately, so a rejected update looked exactly like a successful action
|
|
// while every selected card stayed put.
|
|
async archiveSelectedCards(boardId, cardIds) {
|
|
check(boardId, String);
|
|
check(cardIds, [String]);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const ids = [...new Set(cardIds)];
|
|
if (!ids.length || ids.length > 5000) {
|
|
throw new Meteor.Error('invalid-card-selection');
|
|
}
|
|
|
|
const board = await Boards.findOneAsync(boardId);
|
|
if (!board || !allowIsBoardMemberWithWriteAccess(this.userId, board)) {
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
|
|
const cards = await Cards.find({
|
|
_id: { $in: ids },
|
|
boardId,
|
|
archived: false,
|
|
}).fetchAsync();
|
|
if (cards.length !== ids.length) {
|
|
throw new Meteor.Error('invalid-card-selection');
|
|
}
|
|
|
|
// GHSA-6xqf-jh8x-4wxc: the board's write capability is not enough. An
|
|
// assigned-only member archives only cards assigned to them - every card
|
|
// of the selection is checked before the first is archived, so a refused
|
|
// selection changes nothing.
|
|
const { assignedOnlyAllowsCard } = require('/models/lib/boardCardScope');
|
|
if (!cards.every(card => assignedOnlyAllowsCard(board, this.userId, card))) {
|
|
recordUnassignedCardWrite(this.userId, 'method:archiveSelectedCards');
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
// GHSA-83w9-74mx-7v83: and every card's list - a list that refuses this
|
|
// role refuses the whole selection before the first card is archived.
|
|
await assertListsWritable(this.userId, board, cards.map(card => card.listId));
|
|
|
|
// Validate the complete selection before changing the first card. Preserve
|
|
// the board order used by Multi-Selection for deterministic activity order.
|
|
const byId = new Map(cards.map(card => [card._id, card]));
|
|
for (const id of ids) {
|
|
await byId.get(id).archive();
|
|
}
|
|
return { archived: ids.length };
|
|
},
|
|
|
|
// #6611: custom-field selection and checkbox values are acknowledged server
|
|
// writes. Direct client collection writes could be refused silently, making
|
|
// a removed field immediately reappear and a checkbox appear inert.
|
|
async setCardCustomFieldAssigned(cardId, customFieldId, assigned) {
|
|
check(cardId, String);
|
|
check(customFieldId, String);
|
|
check(assigned, Boolean);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = await Cards.findOneAsync(cardId);
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = await Boards.findOneAsync(card.boardId);
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) {
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
const definition = await CustomFields.findOneAsync({
|
|
_id: customFieldId,
|
|
boardIds: card.boardId,
|
|
});
|
|
if (!definition) throw new Meteor.Error('custom-field-not-found');
|
|
|
|
if (assigned) {
|
|
await Cards.updateAsync(cardId, {
|
|
$addToSet: { customFields: { _id: customFieldId, value: null } },
|
|
});
|
|
} else {
|
|
// #6611: MongoDB document conditions match fields within each array
|
|
// element. FerretDB must do the same here; exact document equality would
|
|
// not match an element that also contains its custom-field value.
|
|
await Cards.updateAsync(cardId, {
|
|
$pull: { customFields: { _id: customFieldId } },
|
|
});
|
|
}
|
|
return assigned;
|
|
},
|
|
|
|
async setCardCustomFieldCheckbox(cardId, customFieldId, value) {
|
|
check(cardId, String);
|
|
check(customFieldId, String);
|
|
check(value, Boolean);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = await Cards.findOneAsync(cardId);
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = await Boards.findOneAsync(card.boardId);
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) {
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
const definition = await CustomFields.findOneAsync({
|
|
_id: customFieldId,
|
|
boardIds: card.boardId,
|
|
type: 'checkbox',
|
|
});
|
|
if (!definition) throw new Meteor.Error('custom-field-not-found');
|
|
// #3141: a UI-only hide is not real access control - a direct method call
|
|
// is checked the same as the deny rule that covers text/number/dropdown/
|
|
// stringtemplate fields (server/permissions/cards.js).
|
|
if (definition.adminOnly && !board.hasAdmin(this.userId)) {
|
|
require('/server/lib/adminOnlyCustomFields').fieldWriteDenied(this.userId, 'method:setCardCustomFieldCheckbox');
|
|
}
|
|
|
|
const index = (card.customFields || []).findIndex(field =>
|
|
field && field._id === customFieldId);
|
|
if (index < 0) throw new Meteor.Error('custom-field-not-on-card');
|
|
await Cards.updateAsync(cardId, {
|
|
$set: { [`customFields.${index}.value`]: value },
|
|
});
|
|
return value;
|
|
},
|
|
|
|
async setCardCustomFieldCurrency(cardId, customFieldId, value) {
|
|
check(cardId, String);
|
|
check(customFieldId, String);
|
|
check(value, Number);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
if (!Number.isFinite(value)) {
|
|
throw new Meteor.Error('invalid-custom-field-value');
|
|
}
|
|
|
|
const card = await Cards.findOneAsync(cardId);
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = await Boards.findOneAsync(card.boardId);
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) {
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
const definition = await CustomFields.findOneAsync({
|
|
_id: customFieldId,
|
|
boardIds: card.boardId,
|
|
type: 'currency',
|
|
});
|
|
if (!definition) throw new Meteor.Error('custom-field-not-found');
|
|
// #3141: same server-side gate as setCardCustomFieldCheckbox above.
|
|
if (definition.adminOnly && !board.hasAdmin(this.userId)) {
|
|
require('/server/lib/adminOnlyCustomFields').fieldWriteDenied(this.userId, 'method:setCardCustomFieldCurrency');
|
|
}
|
|
|
|
const index = (card.customFields || []).findIndex(field =>
|
|
field && field._id === customFieldId);
|
|
if (index < 0) throw new Meteor.Error('custom-field-not-on-card');
|
|
await Cards.updateAsync(cardId, {
|
|
$set: { [`customFields.${index}.value`]: value },
|
|
});
|
|
return value;
|
|
},
|
|
|
|
// Server-authoritative subtask creation. Fixes:
|
|
// - #3868 / #5788 / #2256 "extra swimlane / column on subtask creation" and
|
|
// #4782 "can not create more than one subtask": the default subtasks
|
|
// board/list/swimlane are resolved (and lazily created ONCE) here on the
|
|
// server, so the client can no longer create duplicate helper boards.
|
|
// - #4037 / #3562 "custom fields not assigned to subtask cards": the
|
|
// destination board's automatic custom fields are applied to the subtask.
|
|
// - #2184: an optional `inheritLabels` flag copies the parent card's
|
|
// CURRENT labelIds onto the new subtask, once, at creation time. This is
|
|
// a one-time copy, not an ongoing sync: a later change to the parent's
|
|
// labels does not retroactively touch subtasks already created.
|
|
async addSubtaskCard(parentCardId, title, inheritLabels = false) {
|
|
check(parentCardId, String);
|
|
check(title, String);
|
|
check(inheritLabels, Boolean);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
const trimmed = title.trim();
|
|
if (!trimmed) return undefined;
|
|
|
|
const parentCard =
|
|
(await ReactiveCache.getCard(parentCardId)) ||
|
|
(await Cards.findOneAsync(parentCardId));
|
|
if (!parentCard) throw new Meteor.Error('not-found');
|
|
const parentBoard = await Boards.findOneAsync(parentCard.boardId);
|
|
if (!parentBoard) throw new Meteor.Error('not-found');
|
|
// The author must have write access to the parent card's board.
|
|
if (!(await canEditCardOrLinkedCard(this.userId, parentCard, parentBoard)))
|
|
throw new Meteor.Error('not-authorized');
|
|
|
|
// Resolve (and, on the server, lazily create ONCE) the default subtasks
|
|
// board + landing list. These getters never duplicate on the server.
|
|
const targetBoard = await parentBoard.getDefaultSubtasksBoardAsync();
|
|
if (!targetBoard) return undefined;
|
|
if (!(await canWriteSubtaskDeposit(this.userId, targetBoard._id))) {
|
|
recordSubtaskDepositDenial('addSubtaskCard');
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
// #1781: the landing list - the main board's own choice on a shared
|
|
// deposit board, else the deposit board's - and never a list of a third
|
|
// board (models/lib/subtaskLandingList.js).
|
|
const { chooseSubtaskLandingList } = require('/models/lib/subtaskLandingList');
|
|
const landing = chooseSubtaskLandingList({ parentBoard, targetBoard,
|
|
lists: await Lists.find({ boardId: targetBoard._id, archived: { $ne: true } }, { sort: { sort: 1 } }).fetchAsync() });
|
|
let targetList = null;
|
|
if (landing.listId) targetList = await Lists.findOneAsync(landing.listId);
|
|
else if (landing.create === 'store') targetList = await targetBoard.getDefaultSubtasksListAsync();
|
|
else {
|
|
const swimlane = await targetBoard.getDefaultSwimlineAsync();
|
|
const listId = await Lists.insertAsync({ title: getTranslatedString('queue', 'Queue'), boardId: targetBoard._id,
|
|
swimlaneId: swimlane ? swimlane._id : undefined });
|
|
targetList = await Lists.findOneAsync(listId);
|
|
}
|
|
if (!targetList) return undefined;
|
|
// ListLockBulkBleed: the landing list may refuse this role a new card.
|
|
await assertListsWritable(this.userId, targetBoard, [targetList._id]);
|
|
|
|
// #1953: the swimlane chosen in Board Settings / Subtasks (the main
|
|
// board's on a shared deposit board, else the deposit board's own), else
|
|
// as before: the destination swimlane with the parent's swimlane title,
|
|
// else the default swimlane (models/lib/subtaskLandingSwimlane.js).
|
|
const { chooseSubtaskSwimlane } = require('/models/lib/subtaskLandingSwimlane');
|
|
const parentSwimlane = parentCard.swimlaneId
|
|
? await Swimlanes.findOneAsync(parentCard.swimlaneId)
|
|
: null;
|
|
const landingSwimlane = chooseSubtaskSwimlane({ parentBoard, targetBoard,
|
|
swimlanes: await Swimlanes.find({ boardId: targetBoard._id, archived: { $ne: true } }).fetchAsync(),
|
|
parentSwimlaneTitle: parentSwimlane ? parentSwimlane.title : undefined });
|
|
let swimlaneId = landingSwimlane.swimlaneId;
|
|
if (!swimlaneId) {
|
|
const defaultSwimlane = await targetBoard.getDefaultSwimlineAsync();
|
|
swimlaneId = defaultSwimlane && defaultSwimlane._id;
|
|
}
|
|
if (!swimlaneId) return undefined;
|
|
|
|
// #4037 / #3562: apply the destination board's automatic custom fields.
|
|
const boardCustomFields = await CustomFields.find({
|
|
boardIds: targetBoard._id,
|
|
}).fetchAsync();
|
|
const customFields = subtaskCustomFields(boardCustomFields);
|
|
|
|
const cardNumber = await targetBoard.getNextCardNumber();
|
|
// #3826: a constant `sort: -1` made EVERY subtask card tie, so a list full
|
|
// of subtask cards could not be reordered by drag (no number lies strictly
|
|
// between two equal sorts; the computed index equalled the card's own sort
|
|
// and the move was discarded as a no-op). Append with a unique sort at the
|
|
// end of the target list instead — with the old all-ties data the cards
|
|
// effectively rendered in insertion order anyway, so the visible placement
|
|
// is unchanged while new subtasks no longer pile up duplicate sorts.
|
|
const lastCard = await Cards.findOneAsync(
|
|
{ listId: targetList._id, archived: false },
|
|
{ sort: { sort: -1 }, fields: { sort: 1 } },
|
|
);
|
|
const sort =
|
|
lastCard && Number.isFinite(lastCard.sort) ? lastCard.sort + 1 : 0;
|
|
// #2184: copy the parent's CURRENT labelIds when requested, otherwise
|
|
// keep the existing behavior of an empty labelIds array.
|
|
const labelIds = computeSubtaskLabelIds(parentCard, inheritLabels);
|
|
const _id = await Cards.insertAsync({
|
|
title: trimmed,
|
|
parentId: parentCardId,
|
|
members: [],
|
|
assignees: [],
|
|
labelIds,
|
|
customFields,
|
|
listId: targetList._id,
|
|
boardId: targetBoard._id,
|
|
sort,
|
|
swimlaneId,
|
|
type: 'cardType-card',
|
|
cardNumber,
|
|
userId: this.userId,
|
|
});
|
|
return _id;
|
|
},
|
|
|
|
async createCardWithDueDate(boardId, listId, title, dueDate, swimlaneId) {
|
|
check(boardId, String);
|
|
check(listId, String);
|
|
check(title, String);
|
|
check(dueDate, Date);
|
|
check(swimlaneId, String);
|
|
|
|
// AuthBleed (DueDateBleed): no WeKan client calls this method, so every
|
|
// refusal is an attempt and is recorded.
|
|
const refuse = detail => {
|
|
try {
|
|
require('/server/lib/securityLog').record({ key: 'authz.copy', action: 'blocked',
|
|
source: 'method:createCardWithDueDate', userId: this.userId || undefined, detail });
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
return new Meteor.Error('not-authorized');
|
|
};
|
|
if (!this.userId) throw refuse('Card insert refused: not signed in');
|
|
const destBoard = await Boards.findOneAsync(boardId);
|
|
if (!destBoard) throw new Meteor.Error('not-found');
|
|
if (!allowIsBoardMemberWithWriteAccess(this.userId, destBoard))
|
|
throw refuse('Card insert refused: no write access to the board');
|
|
// ListLockBulkBleed: the list must be this board's, and must not refuse
|
|
// this role a new card.
|
|
const destList = await Lists.findOneAsync({ _id: listId, boardId });
|
|
if (!destList) throw new Meteor.Error('not-found');
|
|
if ((await listException(this.userId, destBoard, listId, 'write')) === false)
|
|
throw refuse('Card insert refused: the list refuses this role');
|
|
|
|
const card = {
|
|
title,
|
|
listId,
|
|
boardId,
|
|
swimlaneId,
|
|
createdAt: new Date(),
|
|
dueAt: dueDate,
|
|
sort: 0,
|
|
userId: this.userId,
|
|
};
|
|
const cardId = await Cards.insertAsync(card);
|
|
return cardId;
|
|
},
|
|
|
|
async 'cards.pokerVote'(cardId, state) {
|
|
check(cardId, String);
|
|
if (state !== undefined && state !== null) check(state, String);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!board) throw new Meteor.Error('not-found');
|
|
|
|
const isMember = allowIsBoardMember(this.userId, board) ||
|
|
await canEditCardOrLinkedCard(this.userId, card, board);
|
|
const allowNBM = !!(card.poker && card.poker.allowNonBoardMembers);
|
|
if (!(isMember || allowNBM)) {
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
|
|
let mod = card.setPoker(this.userId, state);
|
|
if (!mod || typeof mod !== 'object') mod = {};
|
|
mod.$set = Object.assign({}, mod.$set, {
|
|
modifiedAt: new Date(),
|
|
dateLastActivity: new Date(),
|
|
});
|
|
return await Cards.updateAsync({ _id: cardId }, mod);
|
|
},
|
|
|
|
async 'cards.setPokerQuestion'(cardId, question, allowNonBoardMembers) {
|
|
check(cardId, String);
|
|
check(question, Boolean);
|
|
check(allowNonBoardMembers, Boolean);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
const modifier = {
|
|
$set: {
|
|
poker: {
|
|
question,
|
|
allowNonBoardMembers,
|
|
one: [],
|
|
two: [],
|
|
three: [],
|
|
five: [],
|
|
eight: [],
|
|
thirteen: [],
|
|
twenty: [],
|
|
forty: [],
|
|
oneHundred: [],
|
|
unsure: [],
|
|
},
|
|
modifiedAt: new Date(),
|
|
dateLastActivity: new Date(),
|
|
},
|
|
};
|
|
return await Cards.updateAsync({ _id: cardId }, modifier);
|
|
},
|
|
|
|
async 'cards.setPokerEnd'(cardId, end) {
|
|
check(cardId, String);
|
|
check(end, Date);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$set: {
|
|
'poker.end': end,
|
|
modifiedAt: new Date(),
|
|
dateLastActivity: new Date(),
|
|
},
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.unsetPokerEnd'(cardId) {
|
|
check(cardId, String);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$unset: { 'poker.end': '' },
|
|
$set: { modifiedAt: new Date(), dateLastActivity: new Date() },
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.unsetPoker'(cardId) {
|
|
check(cardId, String);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$unset: { poker: '' },
|
|
$set: { modifiedAt: new Date(), dateLastActivity: new Date() },
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.setPokerEstimation'(cardId, estimation) {
|
|
check(cardId, String);
|
|
check(estimation, Number);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$set: {
|
|
'poker.estimation': estimation,
|
|
modifiedAt: new Date(),
|
|
dateLastActivity: new Date(),
|
|
},
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.unsetPokerEstimation'(cardId) {
|
|
check(cardId, String);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$unset: { 'poker.estimation': '' },
|
|
$set: { modifiedAt: new Date(), dateLastActivity: new Date() },
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.replayPoker'(cardId) {
|
|
check(cardId, String);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$set: {
|
|
'poker.one': [],
|
|
'poker.two': [],
|
|
'poker.three': [],
|
|
'poker.five': [],
|
|
'poker.eight': [],
|
|
'poker.thirteen': [],
|
|
'poker.twenty': [],
|
|
'poker.forty': [],
|
|
'poker.oneHundred': [],
|
|
'poker.unsure': [],
|
|
modifiedAt: new Date(),
|
|
dateLastActivity: new Date(),
|
|
},
|
|
$unset: { 'poker.end': '' },
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.setVoteQuestion'(cardId, question, publicVote, allowNonBoardMembers) {
|
|
check(cardId, String);
|
|
check(question, String);
|
|
check(publicVote, Boolean);
|
|
check(allowNonBoardMembers, Boolean);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$set: {
|
|
vote: {
|
|
question,
|
|
public: publicVote,
|
|
allowNonBoardMembers,
|
|
positive: [],
|
|
negative: [],
|
|
},
|
|
modifiedAt: new Date(),
|
|
dateLastActivity: new Date(),
|
|
},
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.setVoteEnd'(cardId, end) {
|
|
check(cardId, String);
|
|
check(end, Date);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$set: {
|
|
'vote.end': end,
|
|
modifiedAt: new Date(),
|
|
dateLastActivity: new Date(),
|
|
},
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.unsetVoteEnd'(cardId) {
|
|
check(cardId, String);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$unset: { 'vote.end': '' },
|
|
$set: { modifiedAt: new Date(), dateLastActivity: new Date() },
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.unsetVote'(cardId) {
|
|
check(cardId, String);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!(await canEditCardOrLinkedCard(this.userId, card, board))) throw new Meteor.Error('not-authorized');
|
|
|
|
return await Cards.updateAsync(
|
|
{ _id: cardId },
|
|
{
|
|
$unset: { vote: '' },
|
|
$set: { modifiedAt: new Date(), dateLastActivity: new Date() },
|
|
},
|
|
);
|
|
},
|
|
|
|
async 'cards.vote'(cardId, forIt) {
|
|
check(cardId, String);
|
|
if (forIt !== undefined && forIt !== null) check(forIt, Boolean);
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
|
|
const card = (await ReactiveCache.getCard(cardId)) || (await Cards.findOneAsync(cardId));
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const board = (await ReactiveCache.getBoard(card.boardId)) || (await Boards.findOneAsync(card.boardId));
|
|
if (!board) throw new Meteor.Error('not-found');
|
|
|
|
const isMember = allowIsBoardMember(this.userId, board) ||
|
|
await canEditCardOrLinkedCard(this.userId, card, board);
|
|
const allowNBM = !!(card.vote && card.vote.allowNonBoardMembers);
|
|
if (!(isMember || allowNBM)) {
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
|
|
let modifier;
|
|
if (forIt === true) {
|
|
modifier = {
|
|
$pull: { 'vote.negative': this.userId },
|
|
$addToSet: { 'vote.positive': this.userId },
|
|
$set: { modifiedAt: new Date(), dateLastActivity: new Date() },
|
|
};
|
|
} else if (forIt === false) {
|
|
modifier = {
|
|
$pull: { 'vote.positive': this.userId },
|
|
$addToSet: { 'vote.negative': this.userId },
|
|
$set: { modifiedAt: new Date(), dateLastActivity: new Date() },
|
|
};
|
|
} else {
|
|
modifier = {
|
|
$pull: {
|
|
'vote.positive': this.userId,
|
|
'vote.negative': this.userId,
|
|
},
|
|
$set: { modifiedAt: new Date(), dateLastActivity: new Date() },
|
|
};
|
|
}
|
|
|
|
return await Cards.updateAsync({ _id: cardId }, modifier);
|
|
},
|
|
|
|
async copyCard(cardId, boardId, swimlaneId, listId, insertAtTop, mergeCardValues) {
|
|
check(cardId, String);
|
|
check(boardId, String);
|
|
check(swimlaneId, String);
|
|
check(listId, String);
|
|
check(insertAtTop, Boolean);
|
|
check(mergeCardValues, Object);
|
|
|
|
// AuthBleed: no signed-out client copies a card, so this is an attempt.
|
|
// The membership refusals below are not recorded: a stale Copy Card
|
|
// dialog reaches them in ordinary use.
|
|
if (!this.userId) {
|
|
try {
|
|
require('/server/lib/securityLog').record({ key: 'authz.copy', action: 'blocked',
|
|
source: 'method:copyCard', detail: 'Card copy refused: not signed in' });
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
throw new Meteor.Error('not-authorized');
|
|
}
|
|
const card = await ReactiveCache.getCard(cardId);
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const sourceBoard = await Boards.findOneAsync(card.boardId);
|
|
if (!allowIsBoardMember(this.userId, sourceBoard))
|
|
throw new Meteor.Error('not-authorized');
|
|
// AssignedBleed copy sibling (2026-10-02): an assigned-only member copies
|
|
// only a card assigned to them; a copy of any other showed them its content.
|
|
if (!require('/models/lib/boardCardScope').mayCopyFromBoard(sourceBoard, this.userId, card))
|
|
throw new Meteor.Error('not-authorized');
|
|
const destBoard = await Boards.findOneAsync(boardId);
|
|
if (!allowIsBoardMemberWithWriteAccess(this.userId, destBoard))
|
|
throw new Meteor.Error('not-authorized');
|
|
// GHSA-83w9-74mx-7v83: the destination list may refuse this role; the copy
|
|
// is inserted by server code, past the Cards allow/deny rules.
|
|
await assertListsWritable(this.userId, destBoard, [listId]);
|
|
// Reject a forged merge before copying children or emitting activities.
|
|
await require('/server/lib/adminOnlyCustomFields').assertFieldWrite(
|
|
this.userId, card, { ...card, ...mergeCardValues }, 'method:copyCard');
|
|
const { cardWithCopyOverrides } = require('/models/lib/cardCopyOverrides');
|
|
let copy;
|
|
try { copy = cardWithCopyOverrides(card, mergeCardValues); }
|
|
catch (error) {
|
|
try {
|
|
if (error.securityAttempt) require('/server/lib/securityLog').record({ key: 'authz.card-copy-overrides',
|
|
action: 'blocked', source: 'method:copyCard', userId: this.userId,
|
|
detail: 'Unsupported card-copy overrides refused' });
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
throw new Meteor.Error('bad-request', 'Invalid card copy overrides');
|
|
}
|
|
|
|
await require('/server/lib/cardCopyDestination').requireCardCopyDestination(boardId, swimlaneId, listId);
|
|
const sort = await copy.getSort(listId, swimlaneId, insertAtTop);
|
|
copy.sort = insertAtTop ? sort - 1 : sort + 1;
|
|
return await copy.copy(boardId, swimlaneId, listId);
|
|
},
|
|
|
|
// #2209: "Create template from element" — save an EXISTING card as a card
|
|
// template, the reverse direction of the existing "insert a card FROM a
|
|
// template" flow (Template.searchElementPopup, client/components/lists/
|
|
// listBody.js). Reuses the same lazy per-user Templates board that #4205's
|
|
// default-template application already relies on (ensureTemplatesBoardForUserId,
|
|
// extracted from the ensureTemplatesBoard Meteor method in
|
|
// /server/models/users.js) and the same card.copy() the copyCard method above
|
|
// uses, just targeting the user's "Card Templates" swimlane instead of an
|
|
// ordinary board/swimlane/list, and marking the copy `type: 'template-card'`
|
|
// (Cards.isTemplateCard()) so it behaves as a template rather than a normal
|
|
// card. A "Default" list is created on demand the first time, mirroring the
|
|
// client-side "create the first list if none exists" fallback already used
|
|
// for ad-hoc card creation (client/components/boards/boardBody.js).
|
|
async saveCardAsTemplate(cardId) {
|
|
check(cardId, String);
|
|
|
|
if (!this.userId) throw new Meteor.Error('not-authorized');
|
|
const card = await ReactiveCache.getCard(cardId);
|
|
if (!card) throw new Meteor.Error('not-found');
|
|
const sourceBoard = await Boards.findOneAsync(card.boardId);
|
|
if (!allowIsBoardMember(this.userId, sourceBoard))
|
|
throw new Meteor.Error('not-authorized');
|
|
// AssignedBleed copy sibling (2026-10-02): an assigned-only member copies
|
|
// only a card assigned to them; a copy of any other showed them its content.
|
|
if (!require('/models/lib/boardCardScope').mayCopyFromBoard(sourceBoard, this.userId, card))
|
|
throw new Meteor.Error('not-authorized');
|
|
|
|
const { ensureTemplatesBoardForUserId } = require('/server/models/users');
|
|
const templatesBoardId = await ensureTemplatesBoardForUserId(this.userId);
|
|
|
|
const user = await ReactiveCache.getUser(this.userId);
|
|
const swimlaneId = user && user.profile && user.profile.cardTemplatesSwimlaneId;
|
|
if (!swimlaneId) throw new Meteor.Error('not-found', 'card-templates-swimlane-missing');
|
|
|
|
let list = await Lists.findOneAsync({
|
|
boardId: templatesBoardId,
|
|
swimlaneId,
|
|
archived: false,
|
|
});
|
|
if (!list) {
|
|
const listId = await Lists.insertAsync({
|
|
title: 'Default',
|
|
boardId: templatesBoardId,
|
|
swimlaneId,
|
|
});
|
|
list = await Lists.findOneAsync(listId);
|
|
}
|
|
|
|
const sort = await card.getSort(list._id, swimlaneId, false);
|
|
card.sort = sort + 1;
|
|
card.type = 'template-card';
|
|
|
|
return await card.copy(templatesBoardId, swimlaneId, list._id);
|
|
},
|
|
});
|
|
|
|
Meteor.startup(async () => {
|
|
await ensureIndex(Cards, { modifiedAt: -1 });
|
|
await ensureIndex(Cards, { updatedAt: 1, deleted: 1 });
|
|
await ensureIndex(Cards, { boardId: 1, createdAt: -1 });
|
|
await ensureIndex(Cards, { boardId: 1, listId: 1 });
|
|
// The board publication's main card cursor filters { boardId, archived }; without
|
|
// archived in the index FerretDB/SQLite could only use the boardId prefix and then
|
|
// scanned archived, which on boards with years of archived+active cards burned CPU
|
|
// and caused SQLITE_BUSY (#6480). This compound index covers that filter.
|
|
await ensureIndex(Cards, { boardId: 1, archived: 1 });
|
|
// Linked-card and parent discovery add one predicate to that common prefix.
|
|
await ensureIndex(Cards, { boardId: 1, archived: 1, type: 1 });
|
|
await ensureIndex(Cards, { boardId: 1, archived: 1, parentId: 1 });
|
|
// Lazy card windows filter one board/list/swimlane, sort by the card order and
|
|
// use _id as a deterministic tie-breaker. MongoDB can answer the projected id
|
|
// window from this index alone (limit included) instead of reading and sorting
|
|
// every card in the list. FerretDB may use a shorter prefix until its SQLite
|
|
// compound-sort pushdown supports this shape, but retains identical semantics.
|
|
await ensureIndex(Cards, {
|
|
boardId: 1,
|
|
archived: 1,
|
|
listId: 1,
|
|
swimlaneId: 1,
|
|
sort: 1,
|
|
_id: 1,
|
|
});
|
|
// Due Cards narrows authorized boards and active ordinary cards, then orders
|
|
// them chronologically. The equality prefix avoids walking every card of each
|
|
// board before applying the due-date range.
|
|
await ensureIndex(Cards, { boardId: 1, archived: 1, type: 1, dueAt: 1 });
|
|
await ensureIndex(Cards, { parentId: 1 });
|
|
// Admin Panel / Problems / Broken cards asks for cards with NO board, swimlane
|
|
// or list, or an unknown type - an $or, which can only use an index if each of
|
|
// its branches has one. `boardId` is covered by { boardId, createdAt } above;
|
|
// these are the other three, so counting the report (and paging it) does not
|
|
// scan every card in the database.
|
|
await ensureIndex(Cards, { swimlaneId: 1 });
|
|
await ensureIndex(Cards, { listId: 1 });
|
|
await ensureIndex(Cards, { type: 1 });
|
|
// The hourly recurring-card job (server/cardRecurrenceSchedule.js) asks for
|
|
// cards with a recurrenceInterval. Without an index that read every card -
|
|
// 1.1 million on one instance, 1.1 s of a full collection scan every hour -
|
|
// to find the few that recur (#6825). Partial: only those cards are in it,
|
|
// the same way activities indexes commentId and attachmentId.
|
|
await ensureIndex(Cards, { recurrenceInterval: 1 },
|
|
{ partialFilterExpression: { recurrenceInterval: { $exists: true } } });
|
|
Meteor.defer(() => {
|
|
addCronJob();
|
|
});
|
|
});
|
|
|
|
// #6815: card numbers stay unique per board (models/lib/cardNumberAssign.js).
|
|
Cards.before.insert(async (userId, doc) => {
|
|
const { counterName, isCardNumber, needsNewCardNumber, counterFloor } = require('/models/lib/cardNumberAssign');
|
|
if (!doc || !doc.boardId || !isCardNumber(doc.cardNumber)) return;
|
|
const { Counters } = require('/models/counters');
|
|
const counters = Counters.rawCollection();
|
|
const counter = counterName(doc.boardId);
|
|
const topNumber = async () => {
|
|
const top = await Cards.findOneAsync(
|
|
{ boardId: doc.boardId },
|
|
{ sort: { cardNumber: -1 }, fields: { cardNumber: 1 } },
|
|
);
|
|
return top && top.cardNumber;
|
|
};
|
|
const taken = await Cards.findOneAsync(
|
|
{ boardId: doc.boardId, cardNumber: doc.cardNumber },
|
|
{ fields: { _id: 1 } },
|
|
);
|
|
if (needsNewCardNumber(doc.cardNumber, taken)) {
|
|
const board = await Boards.findOneAsync(doc.boardId);
|
|
if (!board) return;
|
|
// The counter may still be below numbers browsers wrote before this check
|
|
// existed: raise it to the board's highest number first.
|
|
const top = await topNumber();
|
|
if (isCardNumber(top)) {
|
|
await counters.updateOne({ _id: counter }, { $max: { next_val: top } }, { upsert: true });
|
|
}
|
|
doc.cardNumber = await board.getNextCardNumber();
|
|
} else {
|
|
// A free number the counter did not issue (from the browser or an import):
|
|
// never let the counter hand it out again. A board with no counter yet is
|
|
// seeded from its highest number too, as getNextCardNumber's lazy seed
|
|
// does - created here from a browser's number alone, the counter could
|
|
// start below numbers outside that browser's view, and the seed would
|
|
// never run again.
|
|
const exists = await counters.findOne({ _id: counter }, { projection: { _id: 1 } });
|
|
const floor = counterFloor(doc.cardNumber, exists ? null : await topNumber());
|
|
await counters.updateOne({ _id: counter }, { $max: { next_val: floor } }, { upsert: true });
|
|
}
|
|
});
|
|
|
|
// #6815 follow-up: the same check for a card that ENTERS a board's numbering by
|
|
// an update - moved from another board, restored from the archive, or given a
|
|
// number (models/lib/cardNumberAssign.js numberToCheckOnUpdate). A number
|
|
// another card on that board has is replaced by a fresh one from the counter;
|
|
// a free one is kept, and the counter is raised past it.
|
|
Cards.before.update(async (userId, doc, fieldNames, modifier) => {
|
|
const { counterName, isCardNumber, counterFloor, numberToCheckOnUpdate } = require('/models/lib/cardNumberAssign');
|
|
const set = modifier && modifier.$set;
|
|
const check = numberToCheckOnUpdate(doc, set);
|
|
if (!check) return;
|
|
const { boardId, cardNumber } = check;
|
|
const { Counters } = require('/models/counters');
|
|
const counters = Counters.rawCollection();
|
|
const counter = counterName(boardId);
|
|
const topNumber = async () => {
|
|
const top = await Cards.findOneAsync(
|
|
{ boardId, _id: { $ne: doc._id } },
|
|
{ sort: { cardNumber: -1 }, fields: { cardNumber: 1 } },
|
|
);
|
|
return top && top.cardNumber;
|
|
};
|
|
const taken = await Cards.findOneAsync(
|
|
{ boardId, cardNumber, _id: { $ne: doc._id } },
|
|
{ fields: { _id: 1 } },
|
|
);
|
|
if (taken) {
|
|
const board = await Boards.findOneAsync(boardId);
|
|
if (!board) return;
|
|
const top = await topNumber();
|
|
if (isCardNumber(top)) {
|
|
await counters.updateOne({ _id: counter }, { $max: { next_val: top } }, { upsert: true });
|
|
}
|
|
set.cardNumber = await board.getNextCardNumber();
|
|
} else {
|
|
const exists = await counters.findOne({ _id: counter }, { projection: { _id: 1 } });
|
|
const floor = counterFloor(cardNumber, exists ? null : await topNumber());
|
|
await counters.updateOne({ _id: counter }, { $max: { next_val: floor } }, { upsert: true });
|
|
}
|
|
});
|
|
|
|
Cards.after.insert(async (userId, doc) => {
|
|
// Outside a method (a REST route, a server job) the hook has no user: the
|
|
// card's own author is who created it (#6823).
|
|
if (!deferSyncRecording('create', doc)) await cardCreation(userId || doc.userId, doc);
|
|
|
|
Meteor.setTimeout(async () => {
|
|
const card = await Cards.findOneAsync(doc._id);
|
|
if (card) {
|
|
card.trackOriginalPosition();
|
|
}
|
|
}, 100);
|
|
});
|
|
|
|
Cards.after.update(async function(userId, doc, fieldNames) {
|
|
if (!collectionWriteSucceeded(this) || !!this.previous.archived === !!doc.archived) return;
|
|
if (!deferSyncRecording('archive', doc)) await cardState(userId, doc, fieldNames);
|
|
});
|
|
|
|
// When a card moves, re-sync the denormalized board id on everything that
|
|
// belongs to it - comments, comment reactions, text notes, checklists, checklist
|
|
// items and attachments (models/lib/cardChildrenBoard.js) - so the board
|
|
// publication, which finds those collections by board id, shows them on the
|
|
// destination board. #6793: only checklists and items used to follow the card,
|
|
// so a card moved to another board lost its comments there, and they reappeared
|
|
// when it was moved back. Attachments followed only when Card.move() ran on the
|
|
// server, never for a drag in the browser. Uses .direct to skip the children's
|
|
// own hooks (their content did not change).
|
|
Cards.after.update(async function(userId, doc, fieldNames) {
|
|
if (!fieldNames.some(field => field === 'boardId' || field === 'listId' || field === 'swimlaneId')) return;
|
|
await syncCardChildrenBoard(doc._id, doc, this.previous || {});
|
|
});
|
|
|
|
// #6572 / #3392: "Red Strings" only connect cards on the same board, so a card
|
|
// that moves away must also lose the INBOUND links pointing at it from the board
|
|
// it left, or those cards keep a dangling line to a card that is no longer there.
|
|
//
|
|
// The card's own dependencies are cleared by the move itself (cardDependencies:
|
|
// [] is part of the by-_id update). The inbound ones live on OTHER cards, so they
|
|
// need a multi-document update with a compound selector - and that used to sit in
|
|
// Cards.move() in models/cards.js, which the client calls directly. Meteor only
|
|
// lets untrusted code updateAsync BY ID, so the selector made every cross-board
|
|
// move fail with "Not permitted. Untrusted code may only updateAsync documents by
|
|
// ID" before the move ran at all, whether or not the card had any dependencies.
|
|
//
|
|
// Server-side the selector is allowed, and this covers every path that moves a
|
|
// card - the client helper, the REST API, and import - rather than only the one
|
|
// that happened to call the model helper. Dependency cleanup uses hooked writes so its before/after values also
|
|
// reach universal History and blocker reports.
|
|
//
|
|
// Two pulls, because an entry may be either shape: dependencies are stored as
|
|
// { cardId, type, color, icon } objects, and data written before #3392's rewrite
|
|
// can still hold bare card-id strings (normalizeDependencies upgrades those on
|
|
// read, so they are invisible until something has to delete one).
|
|
Cards.after.update(async function(userId, doc, fieldNames) {
|
|
if (!fieldNames.includes('boardId')) return;
|
|
const oldBoardId = (this.previous || {}).boardId;
|
|
if (!oldBoardId || oldBoardId === doc.boardId) return;
|
|
await Cards.updateAsync(
|
|
{ boardId: oldBoardId, 'cardDependencies.cardId': doc._id },
|
|
{ $pull: { cardDependencies: { cardId: doc._id } } },
|
|
{ multi: true },
|
|
);
|
|
await Cards.updateAsync(
|
|
{ boardId: oldBoardId, cardDependencies: doc._id },
|
|
{ $pull: { cardDependencies: doc._id } },
|
|
{ multi: true },
|
|
);
|
|
});
|
|
|
|
// A card that moved to another board takes the destination's sprint and
|
|
// release of the same name, when exactly one matches, and loses the rest of
|
|
// the board it left (models/lib/scrumCopy.js movedScrumMetadata), whoever moved
|
|
// it - the client, REST or a rule. Server-side, since Scrum fields are not the
|
|
// client's to write; compare-and-set on the Scrum revision. A writer that set
|
|
// the Scrum revision with the move (a durable rule move) has done it already.
|
|
Cards.after.update(async function(userId, doc, fieldNames) {
|
|
if (!fieldNames.includes('boardId') || fieldNames.includes('scrumRevision')) return;
|
|
const oldBoardId = (this.previous || {}).boardId;
|
|
if (!oldBoardId || oldBoardId === doc.boardId) return;
|
|
const planning = doc.scrum && (doc.scrum.sprintId || require('/models/lib/scrum').cardReleaseIds(doc.scrum).length)
|
|
? await scrumPlanningPair(oldBoardId, doc.boardId) : null;
|
|
const moved = movedScrumMetadata({ ...doc, boardId: oldBoardId }, doc.boardId, planning);
|
|
if (!moved.scrum) return;
|
|
await Cards.direct.updateAsync({ _id: doc._id, boardId: doc.boardId, ...scrumRevisionSelector(doc) }, { $set: moved });
|
|
});
|
|
|
|
Cards.after.update(async function(userId, doc, fieldNames) {
|
|
const previous = this.previous || {};
|
|
const oldListId = previous.listId || doc.listId;
|
|
const oldSwimlaneId = previous.swimlaneId || doc.swimlaneId;
|
|
const oldBoardId = previous.boardId || doc.boardId;
|
|
// A durable rule move writes its moveCard activity from its saved command.
|
|
if (deferSyncRecording('move', doc)) return;
|
|
await cardMove(userId, doc, fieldNames, oldListId, oldSwimlaneId, oldBoardId);
|
|
});
|
|
|
|
// #5874: a cross-board move must never leave the card pointing at the *source*
|
|
// board's swimlane/list. The move/copy dialog resolves its target board's
|
|
// swimlanes/lists from the client cache, which can still be empty when the user
|
|
// confirms, so it can send boardId=B while swimlaneId/listId still belong to
|
|
// board A — leaving the card invisible on both boards (data loss). This guard
|
|
// runs server-side (where the destination board's swimlanes/lists are always
|
|
// available) and rewrites the modifier so the card's swimlane/list always belong
|
|
// to the destination board, falling back to its default swimlane / first list.
|
|
// Corrective only: a move whose targets already belong to the destination board
|
|
// is left untouched. Server-only (uses the pure helper in server/lib).
|
|
async function enforceCardBoardConsistency(doc, fieldNames, modifier) {
|
|
await applyCardBoardConsistency(doc, fieldNames, modifier, {
|
|
swimlaneBelongs: async (swimlaneId, boardId) =>
|
|
!!(await ReactiveCache.getSwimlane({ _id: swimlaneId, boardId })),
|
|
listBelongs: async (listId, boardId) =>
|
|
!!(await ReactiveCache.getList({ _id: listId, boardId })),
|
|
getDefaultSwimlaneId: async boardId => {
|
|
const board = await ReactiveCache.getBoard(boardId);
|
|
if (!board) return undefined;
|
|
const swimlane = await board.getDefaultSwimlineAsync();
|
|
return swimlane && swimlane._id;
|
|
},
|
|
getFirstListId: async boardId => {
|
|
const list = await ReactiveCache.getList(
|
|
{ boardId, archived: false },
|
|
{ sort: { sort: 1 } },
|
|
);
|
|
return list && list._id;
|
|
},
|
|
});
|
|
}
|
|
|
|
// Registered first so the corrected modifier is what every later before/after
|
|
// hook (and the persisted update) sees.
|
|
Cards.before.update(async (userId, doc, fieldNames, modifier) => {
|
|
await enforceCardBoardConsistency(doc, fieldNames, modifier);
|
|
stampCardListEntry(doc, modifier);
|
|
});
|
|
|
|
Cards.before.update(async (userId, doc, fieldNames, modifier) => {
|
|
await cardMembers(userId, doc, fieldNames, modifier);
|
|
// Once per update. It used to run here AND in the assignees hook below: on a
|
|
// move to another board the first run re-pointed the card's addedLabel
|
|
// activities at the new board's labels, and the second, seeing label ids the
|
|
// card did not have before the move, deleted every one of them.
|
|
// A durable rule move to another board writes the same changes itself.
|
|
if (!deferSyncLabelActivities(doc)) await updateActivities(doc, fieldNames, modifier);
|
|
});
|
|
|
|
Cards.before.update(async (userId, doc, fieldNames, modifier) => {
|
|
await cardAssignees(userId, doc, fieldNames, modifier);
|
|
});
|
|
|
|
Cards.before.update((userId, doc, fieldNames, modifier) => {
|
|
cardLabels(userId, doc, fieldNames, modifier);
|
|
});
|
|
|
|
// Custom-field rules must observe the saved card, including whole-array Sync writes.
|
|
Cards.after.update(async function(userId, doc, fieldNames) {
|
|
if (!collectionWriteSucceeded(this)) return;
|
|
if (fieldNames.includes('customFields') && deferSyncRecording('customFields', doc)) return;
|
|
await cardCustomFields(userId, doc, fieldNames, this.previous);
|
|
});
|
|
|
|
Cards.before.update(async (userId, doc, fieldNames, modifier) => {
|
|
// A date set carries timeValue, a date cleared ($unset) timeOldValue alone;
|
|
// neither reads a $set that is not there (server/lib/timingChangeActivity.js).
|
|
const change = timingChange(fieldNames, modifier);
|
|
if (change) {
|
|
// A durable rule date action writes this activity from its saved plan.
|
|
if (deferSyncRecording('timing', doc)) return;
|
|
const action = change.field;
|
|
// Clearing a date the card does not have changes nothing.
|
|
if (!change.set && !doc[action]) return;
|
|
const oldvalue = doc[action] || '';
|
|
const activityType = `a-${action}`;
|
|
const card = await ReactiveCache.getCard(doc._id);
|
|
if (!card) {
|
|
console.warn('[Cards.before.update] Card not found for cardId:', doc._id, '— skipping timing activity.');
|
|
return;
|
|
}
|
|
const list = await card.list();
|
|
if (list) {
|
|
const modifiedAt = add(now(), -1, 'year').toISOString();
|
|
const boardId = list.boardId;
|
|
await Lists.direct.updateAsync(
|
|
{ _id: list._id },
|
|
{ $set: { modifiedAt, boardId } },
|
|
);
|
|
}
|
|
const user = await ReactiveCache.getUser(userId);
|
|
await Activities.insertAsync({
|
|
userId,
|
|
username: user && user.username,
|
|
activityType,
|
|
boardId: doc.boardId,
|
|
cardId: doc._id,
|
|
cardTitle: doc.title,
|
|
timeKey: action,
|
|
...(change.set ? { timeValue: change.value } : {}),
|
|
timeOldValue: oldvalue,
|
|
listId: card.listId,
|
|
swimlaneId: card.swimlaneId,
|
|
});
|
|
}
|
|
});
|
|
|
|
// Issue #3619: emit title activity only after a successful card write, so
|
|
// outgoing webhooks/rules cannot act on a rejected conditional update.
|
|
Cards.after.update(async function(userId, doc, fieldNames, modifier) {
|
|
if (!collectionWriteSucceeded(this) || !titleChanged(this.previous, modifier)) return;
|
|
if (deferSyncRecording('title', doc)) return;
|
|
const oldValue = this.previous.title || '';
|
|
const newValue = modifier.$set.title;
|
|
const user = await ReactiveCache.getUser(userId);
|
|
await Activities.insertAsync({
|
|
userId,
|
|
username: user && user.username,
|
|
activityType: 'a-changedTitle',
|
|
boardId: doc.boardId,
|
|
cardId: doc._id,
|
|
cardTitle: newValue,
|
|
oldValue,
|
|
value: newValue,
|
|
listId: doc.listId,
|
|
swimlaneId: doc.swimlaneId,
|
|
});
|
|
});
|
|
|
|
// Issue #5482: clearing prose may be cleaned into $unset by SimpleSchema.
|
|
// Treat that as an empty description, while retaining no-op suppression.
|
|
Cards.after.update(async function(userId, doc, fieldNames, modifier) {
|
|
if (!collectionWriteSucceeded(this)) return;
|
|
const change = modifier?.$unset && Object.hasOwn(modifier.$unset, 'description')
|
|
? { $set: { description: '' } } : modifier;
|
|
if (!descriptionChanged(this.previous, change)) return;
|
|
if (deferSyncRecording('description', doc)) return;
|
|
const oldValue = this.previous.description || '';
|
|
const newValue = change.$set.description || '';
|
|
const user = await ReactiveCache.getUser(userId);
|
|
await Activities.insertAsync({
|
|
userId,
|
|
username: user && user.username,
|
|
activityType: 'a-changedDescription',
|
|
boardId: doc.boardId,
|
|
cardId: doc._id,
|
|
cardTitle: doc.title,
|
|
oldValue,
|
|
value: newValue,
|
|
listId: doc.listId,
|
|
swimlaneId: doc.swimlaneId,
|
|
});
|
|
});
|
|
|
|
// Clear stale move reasons on every entry path, including REST and rules.
|
|
Cards.before.update((userId, doc, fieldNames, modifier) => {
|
|
const set = modifier.$set;
|
|
if (set && ((set.listId && set.listId !== doc.listId) || (set.boardId && set.boardId !== doc.boardId))) {
|
|
const reason = typeof set.lastMoveReason === 'string' ? set.lastMoveReason.trim().slice(0, 1000) : '';
|
|
// SimpleSchema cleans an empty string into $unset before this hook.
|
|
// Never send both operators for the same path when undo clears a reason.
|
|
if (reason) {
|
|
set.lastMoveReason = reason;
|
|
if (modifier.$unset) delete modifier.$unset.lastMoveReason;
|
|
} else {
|
|
delete set.lastMoveReason;
|
|
modifier.$unset = { ...modifier.$unset, lastMoveReason: '' };
|
|
}
|
|
}
|
|
});
|
|
|
|
Cards.before.remove(async (userId, doc) => {
|
|
// Issue #1587: permanently deleting a card must log an activity so the
|
|
// Activities.after.insert outgoing-webhook hook fires (archiving already logs
|
|
// an archivedCard activity, but a real delete previously logged nothing). The
|
|
// card document still exists here (it is removed after this before.remove
|
|
// hook), so the notify hook can resolve the card title, members and watchers.
|
|
await Activities.insertAsync(
|
|
buildDeleteCardActivity({
|
|
userId,
|
|
cardId: doc._id,
|
|
boardId: doc.boardId,
|
|
listId: doc.listId,
|
|
swimlaneId: doc.swimlaneId,
|
|
cardTitle: doc.title,
|
|
}),
|
|
);
|
|
});
|
|
|
|
// RaceBleed (GHSA-3vjg-3p4q-8fwh): the card's checklists, checklist items,
|
|
// comments, attachments and subcards are destroyed AFTER the card, and only when
|
|
// it is really gone. collection-hooks runs before.remove on the documents it
|
|
// fetched and then removes by the caller's ORIGINAL selector - by swimlane, by
|
|
// delete batch, by parent - so a card moved to another board in between no
|
|
// longer matched, stayed, and had lost all its children in before.remove. Here
|
|
// a card that is still stored was not removed, and keeps them. Must be awaited,
|
|
// so the cascade has finished when the removal returns; the children's own
|
|
// before.remove hooks already take a missing parent card (they skip their
|
|
// activity), and cardRemover removes the rest directly.
|
|
Cards.after.remove(async (userId, doc) => {
|
|
await cascadeIfRemoved({
|
|
doc,
|
|
exists: async id => !!(await Cards.findOneAsync({ _id: id }, { fields: { _id: 1 } })),
|
|
cascade: card => cardRemover(userId, card),
|
|
});
|
|
});
|
|
|
|
/**
|
|
* @operation get_board_swimlane_cards
|
|
* @tag Cards
|
|
*
|
|
* @summary Get the active cards of a swimlane
|
|
*
|
|
* @description Each card's listId, dates, assignees and sort, and also its
|
|
* modifiedAt, dateLastActivity, labelIds, members and customFields
|
|
* ([{_id, value}]), so a client can sync without a GET per card (#6928).
|
|
* Admin-only custom field values are null unless the caller is a board admin.
|
|
*
|
|
* @param {string} boardId the board ID
|
|
* @param {string} swimlaneId the swimlane ID
|
|
* @return_type [{_id: string, boardId: string, title: string, description: string, listId: string, receivedAt: string, startAt: string, dueAt: string, endAt: string, assignees: [string], sort: number, modifiedAt: string, dateLastActivity: string, labelIds: [string], members: [string], customFields: [{_id: string, value: string}]}]
|
|
*/
|
|
WebApp.handlers.get(
|
|
'/api/boards/:boardId/swimlanes/:swimlaneId/cards',
|
|
async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramSwimlaneId = req.params.swimlaneId;
|
|
await Authentication.checkBoardAccess(req.userId, paramBoardId);
|
|
const cards = await ReactiveCache.getCards(
|
|
{
|
|
boardId: paramBoardId,
|
|
swimlaneId: paramSwimlaneId,
|
|
archived: false,
|
|
},
|
|
{ sort: ['sort'] },
|
|
);
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: cards.map(doc => restCardListItem(doc, 'swimlane')),
|
|
});
|
|
},
|
|
);
|
|
|
|
/**
|
|
* @operation get_board_list_cards
|
|
* @tag Cards
|
|
*
|
|
* @summary Get the active cards of a list
|
|
*
|
|
* @description Each card's swimlaneId, dates, assignees and sort, and also its
|
|
* modifiedAt, dateLastActivity, labelIds, members and customFields
|
|
* ([{_id, value}]), so a client can sync without a GET per card (#6928).
|
|
* Admin-only custom field values are null unless the caller is a board admin.
|
|
*
|
|
* @param {string} boardId the board ID
|
|
* @param {string} listId the list ID
|
|
* @return_type [{_id: string, boardId: string, title: string, description: string, swimlaneId: string, receivedAt: string, startAt: string, dueAt: string, endAt: string, assignees: [string], sort: number, modifiedAt: string, dateLastActivity: string, labelIds: [string], members: [string], customFields: [{_id: string, value: string}]}]
|
|
*/
|
|
WebApp.handlers.get('/api/boards/:boardId/lists/:listId/cards', async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramListId = req.params.listId;
|
|
await Authentication.checkBoardAccess(req.userId, paramBoardId);
|
|
const cards = await ReactiveCache.getCards(
|
|
{
|
|
boardId: paramBoardId,
|
|
listId: paramListId,
|
|
archived: false,
|
|
},
|
|
{ sort: ['sort'] },
|
|
);
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: cards.map(doc => restCardListItem(doc, 'list')),
|
|
});
|
|
});
|
|
|
|
// Issue #5546: this single-card GET looks up by id ONLY (no archived filter),
|
|
// so it returns archived cards too — letting a caller inspect an archived card
|
|
// (e.g. to read its listId) and then de-archive it via PUT archive=false.
|
|
WebApp.handlers.get('/api/cards/:cardId', async function(req, res) {
|
|
const paramCardId = req.params.cardId;
|
|
const card = await ReactiveCache.getCard(paramCardId);
|
|
if (!card) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
await Authentication.checkBoardAccess(req.userId, card.boardId);
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: await cardWithChecklists(card, ReactiveCache),
|
|
});
|
|
});
|
|
|
|
WebApp.handlers.get(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId',
|
|
async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramListId = req.params.listId;
|
|
const paramCardId = req.params.cardId;
|
|
await Authentication.checkBoardAccess(req.userId, paramBoardId);
|
|
// No active card of this board and list with that id: 404, as the global
|
|
// GET answers. It used to answer 200 with an empty body (#6862). The board
|
|
// check stays first, so a stranger learns nothing about which ids exist.
|
|
const card = await ReactiveCache.getCard({
|
|
_id: paramCardId,
|
|
listId: paramListId,
|
|
boardId: paramBoardId,
|
|
archived: false,
|
|
});
|
|
if (!card) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: await cardWithChecklists(card, ReactiveCache),
|
|
});
|
|
},
|
|
);
|
|
|
|
// A card created over REST is placed on the board in the URL, so its list and
|
|
// its swimlane must be that board's. Neither was checked: a list or swimlane id
|
|
// of ANOTHER board was written onto the new card, which then pointed at a list
|
|
// and a swimlane its own board does not have - the #6572 shape, a card that
|
|
// shows on neither board. The PUT route has refused this since #6572; these
|
|
// are its create siblings. Returns the error to answer with, or null.
|
|
async function restPlacementError(boardId, listId, swimlaneId) {
|
|
if (typeof listId !== 'string' || !(await ReactiveCache.getList({ _id: listId, boardId }))) {
|
|
return 'listId does not belong to this board.';
|
|
}
|
|
if (swimlaneId === undefined || swimlaneId === null || swimlaneId === '') return null;
|
|
if (typeof swimlaneId !== 'string' || !(await ReactiveCache.getSwimlane({ _id: swimlaneId, boardId }))) {
|
|
return 'swimlaneId does not belong to this board.';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
WebApp.handlers.post('/api/boards/:boardId/lists/:listId/cards', async function(req, res) {
|
|
Authentication.checkLoggedIn(req.userId);
|
|
const paramBoardId = req.params.boardId;
|
|
const board = await ReactiveCache.getBoard(paramBoardId);
|
|
const addPermission = allowIsBoardMemberWithWriteAccess(req.userId, board);
|
|
// Must be awaited: checkAdminOrCondition is async, so without await a denied
|
|
// (non board member) caller's rejection never blocks and the card was created
|
|
// anyway — an auth bypass (CWE-862). Awaiting enforces the membership check.
|
|
await Authentication.checkAdminOrCondition(req.userId, addPermission);
|
|
await assertListNotRefused(req.userId, board, req.params.listId); // #4527
|
|
const paramListId = req.params.listId;
|
|
const paramParentId = req.body.parentId;
|
|
|
|
// Issue #5897: create a Linked Card. When linkedId is provided, the new card
|
|
// references an existing card (type cardType-linkedCard) instead of holding
|
|
// its own content. Linking across boards is allowed under the same rule as
|
|
// the in-app Link popup (createLinkedCardFor - LinkedWriteBleed): write
|
|
// access to the source board, the source card visible to an assigned-only
|
|
// member, and a list and swimlane that belong to the destination board.
|
|
if (req.body.linkedId) {
|
|
const siblingCards = await ReactiveCache.getCards(
|
|
{ listId: paramListId, archived: false },
|
|
{ sort: ['sort'] },
|
|
);
|
|
let linkedNewId;
|
|
try {
|
|
linkedNewId = await createLinkedCardFor(req.userId, String(req.body.linkedId), paramBoardId,
|
|
String(req.body.swimlaneId || ''), paramListId, siblingCards.length, 'rest:card-link');
|
|
} catch (error) {
|
|
const code = { 'not-found': 404, 'not-authorized': 403 }[error && error.error] || 400;
|
|
sendJsonResult(res, { code, data: { error: (error && error.error) || 'invalid-linked-card' } });
|
|
return;
|
|
}
|
|
sendJsonResult(res, { code: 200, data: { _id: linkedNewId } });
|
|
// GHSA-6jr3-42jf-vhm5: attribution comes from the session, not the body.
|
|
noteAuthorSpoof(req, 'POST cards (linked)');
|
|
// createLinkedCardFor inserts through the collection, so Cards.after.insert
|
|
// has already recorded the "created" activity; a second one here gave every
|
|
// linked card created over REST two, and its watchers two notifications
|
|
// (#6823).
|
|
return;
|
|
}
|
|
|
|
if (paramParentId !== undefined && paramParentId !== null && typeof paramParentId !== 'string') {
|
|
sendJsonResult(res, { code: 400, data: { error: 'Invalid parentId' } });
|
|
return;
|
|
}
|
|
|
|
// GHSA-jvv9-498p-hxrg: the same read check the linked-card branch above makes
|
|
// for `linkedId`, for the parent card. A parent on another board is only
|
|
// allowed when the caller may see that board; otherwise creating one card
|
|
// would publish that board's ancestor cards to everyone subscribed here.
|
|
await assertParentCardIsVisible(req.userId, paramParentId);
|
|
|
|
const placementError = await restPlacementError(paramBoardId, paramListId, req.body.swimlaneId);
|
|
if (placementError) {
|
|
sendJsonResult(res, { code: 400, data: { error: placementError } });
|
|
return;
|
|
}
|
|
|
|
const nextCardNumber = await board.getNextCardNumber();
|
|
|
|
const customFields = await ReactiveCache.getCustomFields({ boardIds: paramBoardId });
|
|
const customFieldsArr = [];
|
|
(customFields || []).forEach(field => {
|
|
if (field.automaticallyOnCard || field.alwaysOnCard) {
|
|
customFieldsArr.push({ _id: field._id, value: null });
|
|
}
|
|
});
|
|
|
|
const currentCards = await ReactiveCache.getCards(
|
|
{ listId: paramListId, archived: false },
|
|
{ sort: ['sort'] },
|
|
);
|
|
// GHSA-6jr3-42jf-vhm5: attribution comes from the SESSION, not from the
|
|
// request body. `authorId` was taken as given after checking only that such a
|
|
// user exists, so any board member could record a card creation, a card
|
|
// deletion or a custom field as somebody else's - the board's own history,
|
|
// written by whoever called the endpoint. The same spoofing was fixed for
|
|
// comments in 8.19 and for the card PUT handler, and these paths were missed.
|
|
const checkUser = await ReactiveCache.getUser(req.userId);
|
|
// #2875: normalize members/assignees so a card can be created with none, and so
|
|
// a `null`/`""` payload never persists as null (which breaks UI editing — see
|
|
// #3697). Omit the field entirely when not provided so the schema default ([])
|
|
// applies. Same coercion the card PUT handler uses.
|
|
// GHSA-whxm-pxgj-7wqv: only ACTIVE members of this board may be named, the
|
|
// same rule the merge endpoint has enforced since #5998.
|
|
const postBoard = await ReactiveCache.getBoard(paramBoardId);
|
|
const members = req.body.members !== undefined
|
|
? await assignableOnBoard(postBoard, coerceRestArrayParam(req.body.members))
|
|
: undefined;
|
|
const assignees = req.body.assignees !== undefined
|
|
? await assignableOnBoard(postBoard, coerceRestArrayParam(req.body.assignees))
|
|
: undefined;
|
|
if (typeof checkUser !== 'undefined') {
|
|
// Issue #5537: accept card dates on create. These schema fields are typed
|
|
// as Date, so a raw request string is stripped by schema cleaning and the
|
|
// date never persists. Parse each into a real Date and only include the
|
|
// ones that parsed, so an invalid/absent date simply leaves the field unset.
|
|
const dateFieldsOnCreate = {};
|
|
['receivedAt', 'startAt', 'dueAt', 'endAt'].forEach(dateField => {
|
|
if (Object.prototype.hasOwnProperty.call(req.body, dateField)) {
|
|
const parsed = parseCardDate(req.body[dateField]);
|
|
if (parsed) {
|
|
dateFieldsOnCreate[dateField] = parsed;
|
|
}
|
|
}
|
|
});
|
|
const id = await Cards.direct.insertAsync({
|
|
title: req.body.title,
|
|
boardId: paramBoardId,
|
|
listId: paramListId,
|
|
parentId: paramParentId,
|
|
description: req.body.description,
|
|
userId: req.userId,
|
|
swimlaneId: req.body.swimlaneId,
|
|
sort: currentCards.length,
|
|
cardNumber: nextCardNumber,
|
|
customFields: customFieldsArr,
|
|
members,
|
|
assignees,
|
|
...dateFieldsOnCreate,
|
|
});
|
|
sendJsonResult(res, { code: 200, data: { _id: id } });
|
|
|
|
const card = await ReactiveCache.getCard(id);
|
|
noteAuthorSpoof(req, 'POST cards');
|
|
await cardCreation(req.userId, card);
|
|
} else {
|
|
sendJsonResult(res, { code: 401 });
|
|
}
|
|
});
|
|
|
|
// Issue #4743: deleting and recreating hundreds of cards via one HTTP request
|
|
// per card pegs the CPU and makes WeKan unreachable. This bulk endpoint creates
|
|
// many cards in a single request, so a sync job no longer has to fan out
|
|
// hundreds of POST calls. Card numbers come from the atomic per-board counter
|
|
// (see Board.getNextCardNumber, Issue #5813), so they stay unique even here.
|
|
//
|
|
// Body: { authorId, swimlaneId, cards: [ { title, description, swimlaneId?,
|
|
// authorId?, members?, assignees? }, ... ] }
|
|
// authorId/swimlaneId at the top level are defaults; each card may override them.
|
|
const BULK_CARDS_MAX = 500;
|
|
WebApp.handlers.post(
|
|
'/api/boards/:boardId/lists/:listId/cards/bulk',
|
|
async function(req, res) {
|
|
Authentication.checkLoggedIn(req.userId);
|
|
const paramBoardId = req.params.boardId;
|
|
const board = await ReactiveCache.getBoard(paramBoardId);
|
|
const addPermission = allowIsBoardMemberWithWriteAccess(req.userId, board);
|
|
await Authentication.checkAdminOrCondition(req.userId, addPermission);
|
|
await assertListNotRefused(req.userId, board, req.params.listId); // #4527
|
|
const paramListId = req.params.listId;
|
|
|
|
const listError = await restPlacementError(paramBoardId, paramListId);
|
|
if (listError) {
|
|
sendJsonResult(res, { code: 400, data: { error: listError } });
|
|
return;
|
|
}
|
|
|
|
const cardsInput = req.body.cards;
|
|
if (!Array.isArray(cardsInput) || cardsInput.length === 0) {
|
|
sendJsonResult(res, { code: 400, data: { error: 'cards must be a non-empty array' } });
|
|
return;
|
|
}
|
|
if (cardsInput.length > BULK_CARDS_MAX) {
|
|
sendJsonResult(res, {
|
|
code: 400,
|
|
data: { error: `cards array too large (max ${BULK_CARDS_MAX} per request)` },
|
|
});
|
|
return;
|
|
}
|
|
|
|
const customFields = await ReactiveCache.getCustomFields({ boardIds: paramBoardId });
|
|
const customFieldsArr = [];
|
|
(customFields || []).forEach(field => {
|
|
if (field.automaticallyOnCard || field.alwaysOnCard) {
|
|
customFieldsArr.push({ _id: field._id, value: null });
|
|
}
|
|
});
|
|
|
|
const currentCards = await ReactiveCache.getCards(
|
|
{ listId: paramListId, archived: false },
|
|
{ sort: ['sort'] },
|
|
);
|
|
const baseSort = currentCards.length;
|
|
|
|
const results = [];
|
|
for (let i = 0; i < cardsInput.length; i++) {
|
|
const input = cardsInput[i] || {};
|
|
// GHSA-6jr3-42jf-vhm5: the session identity, not the body's - per card,
|
|
// because the bulk form let each entry name its own author too.
|
|
noteAuthorSpoof(req, 'POST cards/bulk');
|
|
const authorId = req.userId;
|
|
const swimlaneId = input.swimlaneId || req.body.swimlaneId;
|
|
const swimlaneError = await restPlacementError(paramBoardId, paramListId, swimlaneId);
|
|
if (swimlaneError) {
|
|
results.push({ index: i, error: swimlaneError });
|
|
continue;
|
|
}
|
|
const checkUser = await ReactiveCache.getUser(authorId);
|
|
if (typeof checkUser === 'undefined') {
|
|
results.push({ index: i, error: 'authorId not found' });
|
|
continue;
|
|
}
|
|
// ParentBleed, bulk sibling: the parent check the single create makes.
|
|
// Cards.direct skips the DDP deny rule, so this is the only guard here.
|
|
try {
|
|
await assertParentCardIsVisible(req.userId, input.parentId);
|
|
} catch (error) {
|
|
results.push({ index: i, error: (error && error.error) || 'Forbidden' });
|
|
continue;
|
|
}
|
|
// getNextCardNumber() is an atomic per-board counter, so calling it once
|
|
// per card in this loop still yields unique, sequential numbers.
|
|
const nextCardNumber = await board.getNextCardNumber();
|
|
const id = await Cards.direct.insertAsync({
|
|
title: input.title,
|
|
boardId: paramBoardId,
|
|
listId: paramListId,
|
|
parentId: input.parentId,
|
|
description: input.description,
|
|
userId: authorId,
|
|
swimlaneId,
|
|
sort: baseSort + i,
|
|
cardNumber: nextCardNumber,
|
|
customFields: customFieldsArr,
|
|
// #2875: same normalization as the single-card create above.
|
|
// GHSA-whxm-pxgj-7wqv: and the same board-membership rule.
|
|
members: input.members !== undefined
|
|
? await assignableOnBoard(board, coerceRestArrayParam(input.members))
|
|
: undefined,
|
|
assignees: input.assignees !== undefined
|
|
? await assignableOnBoard(board, coerceRestArrayParam(input.assignees))
|
|
: undefined,
|
|
});
|
|
const card = await ReactiveCache.getCard(id);
|
|
await cardCreation(authorId, card);
|
|
results.push({ index: i, _id: id });
|
|
}
|
|
|
|
sendJsonResult(res, { code: 200, data: results });
|
|
},
|
|
);
|
|
|
|
WebApp.handlers.get('/api/boards/:boardId/cards_count', async function(req, res) {
|
|
try {
|
|
const paramBoardId = req.params.boardId;
|
|
await Authentication.checkBoardAccess(req.userId, paramBoardId);
|
|
const cards = await ReactiveCache.getCards({
|
|
boardId: paramBoardId,
|
|
archived: false,
|
|
});
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: { board_cards_count: cards.length },
|
|
});
|
|
} catch (error) {
|
|
sendJsonResult(res, publicErrorData(error));
|
|
}
|
|
});
|
|
|
|
WebApp.handlers.get('/api/boards/:boardId/lists/:listId/cards_count', async function(req, res) {
|
|
try {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramListId = req.params.listId;
|
|
await Authentication.checkBoardAccess(req.userId, paramBoardId);
|
|
const cards = await ReactiveCache.getCards({
|
|
boardId: paramBoardId,
|
|
listId: paramListId,
|
|
archived: false,
|
|
});
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: { list_cards_count: cards.length },
|
|
});
|
|
} catch (error) {
|
|
sendJsonResult(res, publicErrorData(error));
|
|
}
|
|
});
|
|
|
|
WebApp.handlers.put(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId',
|
|
async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramCardId = req.params.cardId;
|
|
const paramListId = req.params.listId;
|
|
// Issue #5398: consolidate the board-move parameters into one consistent set
|
|
// instead of re-reading them under several inconsistent names. The external
|
|
// API contract is unchanged: full move uses newBoardId/newSwimlaneId/
|
|
// newListId, a same-board move uses listId/swimlaneId.
|
|
const moveParams = normalizeMoveParams(req.body);
|
|
const moveReason = typeof req.body.moveReason === 'string' ? req.body.moveReason.trim().slice(0, 1000) : '';
|
|
const { newBoardId, newSwimlaneId, newListId } = moveParams;
|
|
let updated = false;
|
|
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
|
|
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), paramListId); // #4527
|
|
// #4527: a move INTO a list that refuses this role is refused too.
|
|
if (typeof newListId === 'string' && newListId && newListId !== paramListId) {
|
|
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(newBoardId || paramBoardId), newListId, 'moveCard');
|
|
}
|
|
const beforeEdit = await Cards.findOneAsync({ _id: paramCardId, boardId: paramBoardId, listId: paramListId });
|
|
// A card that is not on this board and list is not edited here: the move
|
|
// branches below would otherwise act on the card id alone, on any board.
|
|
if (!beforeEdit) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
// Validate supplied scalars before the first write, including empty strings.
|
|
const scalars = parseCardScalarFields(req.body);
|
|
if (scalars.error) {
|
|
sendJsonResult(res, { code: 400, data: { error: scalars.error } });
|
|
return;
|
|
}
|
|
|
|
if ('title' in scalars.set) {
|
|
const newTitle = scalars.set.title;
|
|
if (process.env.DEBUG === 'true' && newTitle !== req.body.title) {
|
|
console.warn('Sanitized card title input:', req.body.title, '->', newTitle);
|
|
}
|
|
const matchedCount = await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { title: newTitle } },
|
|
// Always: '' is a value here, and a title of only spaces is trimmed to
|
|
// '' by the default clean, which would then remove it and leave an
|
|
// empty modifier (a 500).
|
|
{ removeEmptyStrings: false },
|
|
);
|
|
updated = matchedCount > 0;
|
|
}
|
|
if ('sort' in scalars.set) {
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { sort: scalars.set.sort } },
|
|
);
|
|
updated = true;
|
|
}
|
|
if (req.body.parentId) {
|
|
// GHSA-jvv9-498p-hxrg: a parent card may live on another board, and write
|
|
// access HERE says nothing about read access THERE. Without this check a
|
|
// board member could name a card on a private board as the parent and the
|
|
// board publication would then hand that private card to everyone
|
|
// subscribed to this board.
|
|
// Only a CHANGED parent is checked: a client that writes a card back
|
|
// unchanged must not be refused (or recorded) for a parent it already had.
|
|
if (req.body.parentId !== beforeEdit.parentId) {
|
|
await assertParentCardIsVisible(req.userId, req.body.parentId);
|
|
}
|
|
// #3626: over REST, parentId makes that card the ONE parent, as it did
|
|
// before cards could have several - parentIds follows it.
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: parentFields([req.body.parentId]) },
|
|
);
|
|
updated = true;
|
|
}
|
|
if ('description' in scalars.set) {
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { description: scalars.set.description } },
|
|
// #6877: '' clears the description; the default clean would remove it.
|
|
{ removeEmptyStrings: false },
|
|
);
|
|
updated = true;
|
|
}
|
|
if (req.body.color) {
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { color: req.body.color } },
|
|
);
|
|
updated = true;
|
|
}
|
|
if (req.body.vote) {
|
|
const newVote = req.body.vote;
|
|
newVote.positive = [];
|
|
newVote.negative = [];
|
|
if (!Object.prototype.hasOwnProperty.call(newVote, 'public')) newVote.public = false;
|
|
if (!Object.prototype.hasOwnProperty.call(newVote, 'allowNonBoardMembers')) {
|
|
newVote.allowNonBoardMembers = false;
|
|
}
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { vote: newVote } },
|
|
);
|
|
updated = true;
|
|
}
|
|
if (req.body.poker) {
|
|
const newPoker = req.body.poker;
|
|
newPoker.one = [];
|
|
newPoker.two = [];
|
|
newPoker.three = [];
|
|
newPoker.five = [];
|
|
newPoker.eight = [];
|
|
newPoker.thirteen = [];
|
|
newPoker.twenty = [];
|
|
newPoker.forty = [];
|
|
newPoker.oneHundred = [];
|
|
newPoker.unsure = [];
|
|
if (!Object.prototype.hasOwnProperty.call(newPoker, 'allowNonBoardMembers')) {
|
|
newPoker.allowNonBoardMembers = false;
|
|
}
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { poker: newPoker } },
|
|
);
|
|
updated = true;
|
|
}
|
|
if (req.body.labelIds) {
|
|
let newlabelIds = req.body.labelIds;
|
|
if (typeof newlabelIds === 'string') {
|
|
newlabelIds = newlabelIds === '' ? null : [newlabelIds];
|
|
}
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { labelIds: newlabelIds } },
|
|
);
|
|
updated = true;
|
|
}
|
|
if (req.body.requestedBy) {
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { requestedBy: req.body.requestedBy } },
|
|
);
|
|
updated = true;
|
|
}
|
|
if (req.body.assignedBy) {
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { assignedBy: req.body.assignedBy } },
|
|
);
|
|
updated = true;
|
|
}
|
|
// Issue #5846: add/remove card dates. Previously each date was only written
|
|
// when the body value was truthy (if (req.body.receivedAt)), so an empty
|
|
// string / null could not CLEAR a date via the API. Now, whenever the field
|
|
// is present in the request body, an empty string or null unsets the date
|
|
// ($unset) and any other value sets it ($set).
|
|
const dateFields = ['receivedAt', 'startAt', 'dueAt', 'endAt'];
|
|
for (const dateField of dateFields) {
|
|
if (Object.prototype.hasOwnProperty.call(req.body, dateField)) {
|
|
const value = req.body[dateField];
|
|
const isClear = isCardDateClear(value);
|
|
// Issue #5537: these schema fields are typed as Date, so a raw request
|
|
// string is stripped by schema cleaning and the date reverts. Parse a
|
|
// non-clear value into a real Date so it persists. An unparseable value
|
|
// is skipped rather than written (which would have silently dropped it).
|
|
let modifier;
|
|
if (isClear) {
|
|
modifier = { $unset: { [dateField]: '' } };
|
|
} else {
|
|
const parsed = parseCardDate(value);
|
|
if (!parsed) {
|
|
continue;
|
|
}
|
|
modifier = { $set: { [dateField]: parsed } };
|
|
}
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
modifier,
|
|
);
|
|
updated = true;
|
|
}
|
|
}
|
|
if (req.body.spentTime !== undefined) {
|
|
const hours = Number(req.body.spentTime);
|
|
if (!Number.isFinite(hours) || hours < 0) {
|
|
sendJsonResult(res, { code: 400, data: { error: 'Invalid spentTime' } });
|
|
return;
|
|
}
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { spentTime: hours } },
|
|
);
|
|
updated = true;
|
|
}
|
|
if ('isOverTime' in scalars.set) {
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
// Keep the REST parameter spelling; the schema and UI use isOvertime.
|
|
{ $set: { isOvertime: scalars.set.isOverTime } },
|
|
);
|
|
updated = true;
|
|
}
|
|
if (req.body.customFields) {
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { customFields: req.body.customFields } },
|
|
);
|
|
updated = true;
|
|
// #5681: `.direct` skips the hook that carries linked custom fields.
|
|
const { propagateLinkedCustomFields } = require('/server/models/customFieldLinks');
|
|
await propagateLinkedCustomFields(await Cards.findOneAsync(paramCardId), beforeEdit.customFields);
|
|
}
|
|
// #3697: accept any "clear" payload (null / "" / [] / a single id) and always
|
|
// store a String[] — never null — so removing the last member/assignee over
|
|
// REST works and never leaves a value the UI cannot edit. Use `!== undefined`
|
|
// so an explicit null/"" clears instead of being skipped by a truthiness guard.
|
|
if (req.body.members !== undefined) {
|
|
// GHSA-whxm-pxgj-7wqv: only active members of this board may be named.
|
|
const putBoard = await ReactiveCache.getBoard(paramBoardId);
|
|
const newmembers = await assignableOnBoard(
|
|
putBoard,
|
|
coerceRestArrayParam(req.body.members),
|
|
);
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { members: newmembers } },
|
|
);
|
|
updated = true;
|
|
}
|
|
if (req.body.assignees !== undefined) {
|
|
// GHSA-whxm-pxgj-7wqv: same rule for assignees.
|
|
const putAssignBoard = await ReactiveCache.getBoard(paramBoardId);
|
|
const newassignees = await assignableOnBoard(
|
|
putAssignBoard,
|
|
coerceRestArrayParam(req.body.assignees),
|
|
);
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { assignees: newassignees } },
|
|
);
|
|
updated = true;
|
|
}
|
|
// #6572: a body that names a swimlane or list belonging to ANOTHER board is
|
|
// refused, and a cross-board move is only ever done by the isBoardMove
|
|
// branch below.
|
|
//
|
|
// The reporter of #6572 tried to work around the client-side move by sending
|
|
// boardId/listId/swimlaneId of the DESTINATION board to this route. Those are
|
|
// not the board-move parameters - isBoardMove needs newBoardId, newSwimlaneId
|
|
// and newListId - so the board move never ran, while these two branches did:
|
|
// the card kept its old boardId and got the destination board's listId and
|
|
// swimlaneId written onto it, which points it at a list and a swimlane that
|
|
// belong to a different board than the card does. It shows on neither board,
|
|
// and it took a hand-written database update to undo.
|
|
//
|
|
// These two branches are for moving WITHIN the board in the URL, so that is
|
|
// what they now enforce; anything else says which parameters to use instead.
|
|
// They are also skipped entirely during a board move: they would rewrite
|
|
// listId before the isBoardMove update runs, and that update's selector pins
|
|
// the card's original listId, so it would then match nothing and silently do
|
|
// nothing - the same inconsistent card, by a different route.
|
|
if (moveParams.swimlaneId && !moveParams.isBoardMove) {
|
|
const sameBoardSwimlane = await ReactiveCache.getSwimlane({
|
|
_id: moveParams.swimlaneId,
|
|
boardId: paramBoardId,
|
|
});
|
|
if (!sameBoardSwimlane) {
|
|
sendJsonResult(res, {
|
|
code: 400,
|
|
data: {
|
|
error: 'swimlaneId does not belong to this board. To move a card to '
|
|
+ 'another board, send newBoardId, newSwimlaneId and newListId.',
|
|
},
|
|
});
|
|
return;
|
|
}
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { swimlaneId: moveParams.swimlaneId } },
|
|
);
|
|
updated = true;
|
|
// The attachments' swimlane meta, as the hook skipped by `.direct` would (#6793).
|
|
await syncCardChildrenBoard(paramCardId,
|
|
{ boardId: paramBoardId, swimlaneId: moveParams.swimlaneId }, beforeEdit);
|
|
}
|
|
if (moveParams.listId && !moveParams.isBoardMove) {
|
|
const sameBoardList = await ReactiveCache.getList({
|
|
_id: moveParams.listId,
|
|
boardId: paramBoardId,
|
|
});
|
|
if (!sameBoardList) {
|
|
sendJsonResult(res, {
|
|
code: 400,
|
|
data: {
|
|
error: 'listId does not belong to this board. To move a card to '
|
|
+ 'another board, send newBoardId, newSwimlaneId and newListId.',
|
|
},
|
|
});
|
|
return;
|
|
}
|
|
// Issue #5399: a same-board list move must land the card on TOP of the
|
|
// destination list (like the Move Card dialog: getMinSort then
|
|
// minSort - 1), otherwise it only $set listId and the card landed at a
|
|
// random position. Issue #5398: use the consolidated moveParams.listId and
|
|
// req.userId consistently (it previously read req.body.authorId here).
|
|
const destListId = moveParams.listId;
|
|
const destSiblings = await ReactiveCache.getCards(
|
|
{ boardId: paramBoardId, listId: destListId, archived: false },
|
|
{ sort: ['sort'] },
|
|
);
|
|
const topSort = computeTopSort((destSiblings || []).map(c => c.sort));
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { listId: destListId, sort: topSort, lastMoveReason: moveReason } },
|
|
);
|
|
updated = true;
|
|
// The attachments' list meta, as the hook skipped by `.direct` would (#6793).
|
|
await syncCardChildrenBoard(paramCardId, { boardId: paramBoardId, listId: destListId }, beforeEdit);
|
|
|
|
const card = await ReactiveCache.getCard(paramCardId);
|
|
// cardMove() does fieldNames.includes(...), so this MUST be an array of
|
|
// changed field names — not an object. Passing { fieldName: 'listId' }
|
|
// threw "fieldNames.includes is not a function" (HTTP 500). See #6423.
|
|
await cardMove(req.userId, card, ['listId'], paramListId);
|
|
}
|
|
if (moveParams.isBoardMove) {
|
|
await Authentication.checkBoardWriteAccess(req.userId, newBoardId);
|
|
const destList = await ReactiveCache.getList({
|
|
_id: newListId,
|
|
boardId: newBoardId,
|
|
archived: false,
|
|
});
|
|
if (!destList) {
|
|
sendJsonResult(res, {
|
|
code: 404,
|
|
data: { error: 'Destination list not found or does not belong to destination board' },
|
|
});
|
|
return;
|
|
}
|
|
const destSwimlane = await ReactiveCache.getSwimlane({
|
|
_id: newSwimlaneId,
|
|
boardId: newBoardId,
|
|
archived: false,
|
|
});
|
|
if (!destSwimlane) {
|
|
sendJsonResult(res, {
|
|
code: 404,
|
|
data: { error: 'Destination swimlane not found or does not belong to destination board' },
|
|
});
|
|
return;
|
|
}
|
|
// Issue #5399: land the moved card on TOP of the destination list (like
|
|
// the Move Card dialog) instead of leaving sort unchanged at a random
|
|
// position.
|
|
const destSiblings = await ReactiveCache.getCards(
|
|
{ boardId: newBoardId, listId: newListId, archived: false },
|
|
{ sort: ['sort'] },
|
|
);
|
|
const topSort = computeTopSort((destSiblings || []).map(c => c.sort));
|
|
const movedCount = await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { boardId: newBoardId, swimlaneId: newSwimlaneId, listId: newListId, sort: topSort, lastMoveReason: moveReason } },
|
|
);
|
|
// RaceBleed (GHSA-3vjg-3p4q-8fwh): a card deleted (or moved) by another
|
|
// request since it was looked up is no longer where this selector says,
|
|
// so the move matched nothing. That is a 404, not a 500 from cardMove
|
|
// dereferencing a card that is gone - and nothing below may run for it.
|
|
if (!movedCount) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
updated = true;
|
|
|
|
const card = await ReactiveCache.getCard(paramCardId);
|
|
// #6793: `.direct` skips the Cards.after.update hook that re-homes the
|
|
// card's comments, reactions, text notes, checklists, items and
|
|
// attachments, so a card moved by REST arrived on the new board without
|
|
// them. Do here what the hook does on every other path - from the card as
|
|
// it now is, so a write that matched nothing moves nothing.
|
|
await syncCardChildrenBoard(paramCardId, (await Cards.findOneAsync(paramCardId)) || {}, beforeEdit);
|
|
await cardMove(req.userId, card, ['boardId', 'swimlaneId', 'listId'], paramListId, beforeEdit?.swimlaneId, paramBoardId);
|
|
}
|
|
// Issue #5546: archive / de-archive a card. The selector intentionally does
|
|
// NOT pin listId: a caller who only wants to set archived=false cannot
|
|
// reliably supply the archived card's listId (the list-scoped GET hides
|
|
// archived cards), so matching on board + card id is enough. `archived:
|
|
// !archive` still guards against a redundant no-op write.
|
|
if ('archive' in req.body) {
|
|
const archive = String(req.body.archive).toLowerCase() === 'true';
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, boardId: paramBoardId, archived: !archive },
|
|
{ $set: { archived: archive } },
|
|
);
|
|
updated = true;
|
|
}
|
|
// Trello-style "complete" checkbox (independent of the due date).
|
|
if ('dueComplete' in req.body) {
|
|
const dueComplete = String(req.body.dueComplete).toLowerCase() === 'true';
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId },
|
|
{ $set: { dueComplete } },
|
|
);
|
|
updated = true;
|
|
}
|
|
// Stickers: an array of { icon, highlight } (JSON, or a JSON string when
|
|
// sent form-encoded).
|
|
if (req.body.stickers) {
|
|
let stickers = req.body.stickers;
|
|
if (typeof stickers === 'string') stickers = JSON.parse(stickers);
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId },
|
|
{ $set: { stickers } },
|
|
);
|
|
updated = true;
|
|
}
|
|
// Locations: an array of { name, address, latitude, longitude } (JSON, or a
|
|
// JSON string when sent form-encoded).
|
|
if (req.body.locations) {
|
|
let locations = req.body.locations;
|
|
if (typeof locations === 'string') locations = JSON.parse(locations);
|
|
// Each location entry requires an `_id` (schema), and coordinates must be
|
|
// numbers (form-encoded values arrive as strings).
|
|
locations = locations.map(loc => {
|
|
const out = {
|
|
_id: loc._id || Random.id(),
|
|
name: loc.name || '',
|
|
address: loc.address || '',
|
|
};
|
|
if (loc.latitude !== undefined && loc.latitude !== '')
|
|
out.latitude = Number(loc.latitude);
|
|
if (loc.longitude !== undefined && loc.longitude !== '')
|
|
out.longitude = Number(loc.longitude);
|
|
return out;
|
|
});
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId },
|
|
{ $set: { locations } },
|
|
);
|
|
updated = true;
|
|
}
|
|
|
|
if (!updated) {
|
|
sendJsonResult(res, { code: 404, data: { message: 'Error' } });
|
|
return;
|
|
}
|
|
|
|
// These legacy REST writes use .direct and bypass collection hooks.
|
|
// Record their authenticated before/after diff in the same History store.
|
|
if (beforeEdit) {
|
|
const afterEdit = await Cards.findOneAsync(paramCardId);
|
|
if (afterEdit) {
|
|
const { recordUpdate } = require('/server/models/changeHistoryHooks');
|
|
await recordUpdate('card', req.userId, afterEdit, [...new Set([...Object.keys(beforeEdit), ...Object.keys(afterEdit)])], beforeEdit);
|
|
}
|
|
}
|
|
|
|
sendJsonResult(res, { code: 200, data: { _id: paramCardId } });
|
|
},
|
|
);
|
|
|
|
WebApp.handlers.delete(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId',
|
|
async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramListId = req.params.listId;
|
|
const paramCardId = req.params.cardId;
|
|
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
|
|
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), paramListId); // #4527
|
|
|
|
// GHSA-8cqr-x6m5-v4w6: the card is fetched with the BOARD the caller was
|
|
// authorised on, not by its id alone. A bare primary-key lookup answered
|
|
// with any board's card, and cardRemover below then destroyed that card's
|
|
// checklists, comments, activities and subcard tree - irreversibly, on a
|
|
// board the caller could not even read - while the triple-key removal that
|
|
// follows quietly matched nothing and the endpoint still answered 200. The
|
|
// bulk endpoint has always constrained its lookup this way; this one did
|
|
// not. A card that is not on this board is now simply not found.
|
|
const card = await ReactiveCache.getCard({
|
|
_id: paramCardId,
|
|
boardId: paramBoardId,
|
|
});
|
|
// An id that names a card, but not one on the board the caller was
|
|
// authorised for, is the attempt this fix refuses - so it is recorded and
|
|
// shows in Admin Panel / Problems. A card id that names nothing at all is
|
|
// an ordinary 404 and is not logged.
|
|
if (!card) {
|
|
const elsewhere = await ReactiveCache.getCard(paramCardId);
|
|
if (elsewhere) {
|
|
// RaceBleed (GHSA-3vjg-3p4q-8fwh): a card that was MOVED away from this
|
|
// board is a delete that arrived after the move - a stale view, or one
|
|
// that lost the race. It is refused all the same, but it is not
|
|
// PurgeBleed: that names a card that was never here, and its critical
|
|
// record disables the account, which a member deleting a card somebody
|
|
// had just moved must not lose.
|
|
const movedFromHere = await Activities.findOneAsync(
|
|
{ activityType: 'moveCardBoard', cardId: paramCardId, oldBoardId: paramBoardId },
|
|
{ fields: { _id: 1 } },
|
|
);
|
|
try {
|
|
require('/server/lib/securityLog').record({
|
|
key: movedFromHere ? 'authz.card-delete-race' : 'authz.card-delete',
|
|
action: 'blocked', source: 'DELETE /api/boards/:boardId/lists/:listId/cards/:cardId',
|
|
userId: req.userId,
|
|
detail: movedFromHere
|
|
? `card ${paramCardId} was moved from board ${paramBoardId} to board ${elsewhere.boardId} before this delete; nothing removed`
|
|
: `refused delete of card ${paramCardId} on board ${elsewhere.boardId} via board ${paramBoardId}`,
|
|
});
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
}
|
|
}
|
|
// The card has to be in the list the URL names: the removal below is keyed
|
|
// on that list, and cardRemover used to run on a card found by board alone,
|
|
// so a card id with the wrong list id lost its checklists, comments and
|
|
// attachments while the card stayed and the reply was 200. That also let a
|
|
// member who may write the named list strip the children of a card in a
|
|
// list that refuses them (ListLockBleed, GHSA-4734-8vrg-8j3w), so the
|
|
// card's own list is asked first, which records that attempt.
|
|
if (card && card.listId !== paramListId) {
|
|
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), card.listId, 'write', 'rest:card-delete-other-list');
|
|
}
|
|
if (!card || card.listId !== paramListId) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
// RaceBleed (GHSA-3vjg-3p4q-8fwh): the card is removed FIRST, keyed on the
|
|
// board and list the caller was authorised for, and its checklists,
|
|
// checklist items, comments, attachments and subcards only when that
|
|
// removal matched. They used to go first, and a move to another board that
|
|
// landed between the lookup above and the removal left the card alive on a
|
|
// board the caller cannot read, stripped of all its children. Now exactly
|
|
// one of the two wins. `Cards.direct.removeAsync` bypasses the hooks, so
|
|
// cardRemover runs once, here.
|
|
noteAuthorSpoof(req, 'DELETE card');
|
|
const removed = await removeClaimedCard({
|
|
card,
|
|
selector: { listId: paramListId, boardId: paramBoardId },
|
|
removeCard: selector => Cards.direct.removeAsync(selector),
|
|
cascade: claimed => cardRemover(req.userId, claimed),
|
|
});
|
|
if (!removed) {
|
|
// The card left this board or list after it was looked up: the delete
|
|
// lost the race, so it touched nothing. Recorded like the refusal above
|
|
// when the card now lives elsewhere.
|
|
const moved = await ReactiveCache.getCard(paramCardId);
|
|
if (moved) {
|
|
try {
|
|
require('/server/lib/securityLog').record({
|
|
key: 'authz.card-delete-race', action: 'blocked', source: 'DELETE /api/boards/:boardId/lists/:listId/cards/:cardId',
|
|
userId: req.userId,
|
|
detail: `card ${paramCardId} moved to board ${moved.boardId} while it was being deleted via board ${paramBoardId}; nothing removed`,
|
|
});
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
}
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
// Issue #1587: Cards.direct.removeAsync bypasses Cards.before.remove, so log
|
|
// the deleteCard activity here too (outgoing-webhook fires on delete).
|
|
await Activities.insertAsync(
|
|
buildDeleteCardActivity({
|
|
userId: req.userId,
|
|
cardId: card._id,
|
|
boardId: card.boardId,
|
|
listId: card.listId,
|
|
swimlaneId: card.swimlaneId,
|
|
cardTitle: card.title,
|
|
}),
|
|
);
|
|
sendJsonResult(res, { code: 200, data: { _id: paramCardId } });
|
|
},
|
|
);
|
|
|
|
// Issue #4743: bulk delete cards in one request instead of one DELETE per card.
|
|
// Body: { cardIds: [ ... ], authorId? }
|
|
// Only cards that belong to :boardId are removed; unknown/foreign ids are
|
|
// reported back in notFound so the caller can reconcile.
|
|
WebApp.handlers.delete('/api/boards/:boardId/cards/bulk', async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
|
|
|
|
const cardIds = req.body.cardIds;
|
|
if (!Array.isArray(cardIds) || cardIds.length === 0) {
|
|
sendJsonResult(res, { code: 400, data: { error: 'cardIds must be a non-empty array' } });
|
|
return;
|
|
}
|
|
if (cardIds.length > BULK_CARDS_MAX) {
|
|
sendJsonResult(res, {
|
|
code: 400,
|
|
data: { error: `cardIds array too large (max ${BULK_CARDS_MAX} per request)` },
|
|
});
|
|
return;
|
|
}
|
|
|
|
// GHSA-83w9-74mx-7v83: the cards come from the body, so no URL names their
|
|
// lists. Every card is read, and every list it is in asked, before the first
|
|
// removal: a list that refuses the caller's role refuses the whole request.
|
|
const found = new Map();
|
|
for (const cardId of cardIds) {
|
|
const card = await ReactiveCache.getCard({ _id: cardId, boardId: paramBoardId });
|
|
if (card) found.set(cardId, card);
|
|
}
|
|
await assertCardListsNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId),
|
|
[...found.values()], 'write', 'rest:cards/bulk-delete');
|
|
|
|
const deleted = [];
|
|
const notFound = [];
|
|
for (const cardId of cardIds) {
|
|
const card = found.get(cardId);
|
|
if (!card) {
|
|
notFound.push(cardId);
|
|
continue;
|
|
}
|
|
// RaceBleed (GHSA-3vjg-3p4q-8fwh): the card first, keyed on this board,
|
|
// and its checklists, items, comments, attachments and subcards only when
|
|
// that removal matched - a card moved away meanwhile keeps them all.
|
|
// Keyed on the list that was checked, too: a card moved into a refusing
|
|
// list since is not removed.
|
|
noteAuthorSpoof(req, 'DELETE cards/bulk');
|
|
const removed = await removeClaimedCard({
|
|
card,
|
|
selector: { boardId: paramBoardId, listId: card.listId },
|
|
removeCard: selector => Cards.direct.removeAsync(selector),
|
|
cascade: claimed => cardRemover(req.userId, claimed),
|
|
});
|
|
if (!removed) {
|
|
notFound.push(cardId);
|
|
continue;
|
|
}
|
|
// Issue #1587: Cards.direct.removeAsync bypasses Cards.before.remove, so log
|
|
// the deleteCard activity here too (outgoing-webhook fires on delete).
|
|
await Activities.insertAsync(
|
|
buildDeleteCardActivity({
|
|
userId: req.userId,
|
|
cardId: card._id,
|
|
boardId: card.boardId,
|
|
listId: card.listId,
|
|
swimlaneId: card.swimlaneId,
|
|
cardTitle: card.title,
|
|
}),
|
|
);
|
|
deleted.push(cardId);
|
|
}
|
|
|
|
sendJsonResult(res, { code: 200, data: { deleted, notFound } });
|
|
});
|
|
|
|
// Issue #5819: bulk add/remove labels across many cards in one request, MERGING
|
|
// (add labels without dropping existing ones, remove specific labels) instead
|
|
// of the replace-the-whole-array behavior of PUT card labelIds.
|
|
// Body: { cardIds: [ ... ], addLabelIds: [ ... ], removeLabelIds: [ ... ] }
|
|
WebApp.handlers.post('/api/boards/:boardId/cards/labels', async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
|
|
|
|
const cardIds = req.body.cardIds;
|
|
if (!Array.isArray(cardIds) || cardIds.length === 0) {
|
|
sendJsonResult(res, { code: 400, data: { error: 'cardIds must be a non-empty array' } });
|
|
return;
|
|
}
|
|
if (cardIds.length > BULK_CARDS_MAX) {
|
|
sendJsonResult(res, {
|
|
code: 400,
|
|
data: { error: `cardIds array too large (max ${BULK_CARDS_MAX} per request)` },
|
|
});
|
|
return;
|
|
}
|
|
const addLabelIds = Array.isArray(req.body.addLabelIds) ? req.body.addLabelIds : [];
|
|
const removeLabelIds = Array.isArray(req.body.removeLabelIds) ? req.body.removeLabelIds : [];
|
|
if (addLabelIds.length === 0 && removeLabelIds.length === 0) {
|
|
sendJsonResult(res, {
|
|
code: 400,
|
|
data: { error: 'provide at least one of addLabelIds or removeLabelIds' },
|
|
});
|
|
return;
|
|
}
|
|
|
|
// Validate that every label being added actually exists on this board.
|
|
const board = await ReactiveCache.getBoard(paramBoardId);
|
|
const boardLabelIds = new Set((board.labels || []).map(label => label._id));
|
|
const invalidLabelIds = addLabelIds.filter(labelId => !boardLabelIds.has(labelId));
|
|
if (invalidLabelIds.length > 0) {
|
|
sendJsonResult(res, {
|
|
code: 400,
|
|
data: { error: 'addLabelIds contains labels not on this board', invalidLabelIds },
|
|
});
|
|
return;
|
|
}
|
|
|
|
// ONE read for every card, not one per card.
|
|
//
|
|
// This used to await a getCard per id and then an update per id - at the
|
|
// BULK_CARDS_MAX of 500 that is a thousand round-trips, issued one at a time,
|
|
// for a single request. The reads are all the same question, so they are one
|
|
// `$in` query; the writes genuinely differ (each card merges its own labels),
|
|
// so they stay individual, but they are issued TOGETHER instead of each
|
|
// waiting for the last.
|
|
const cards = await ReactiveCache.getCards(
|
|
{ _id: { $in: cardIds }, boardId: paramBoardId, archived: false },
|
|
{ fields: { _id: 1, labelIds: 1, listId: 1 } },
|
|
);
|
|
const cardById = new Map((cards || []).map(card => [card._id, card]));
|
|
// GHSA-83w9-74mx-7v83: every card's list, before the first write.
|
|
await assertCardListsNotRefused(req.userId, board, cards || [], 'write', 'rest:cards/labels');
|
|
|
|
const updated = [];
|
|
const notFound = [];
|
|
const writes = [];
|
|
// Iterate cardIds, not the query result: the response has to preserve the
|
|
// caller's order and report the ids that matched nothing.
|
|
for (const cardId of cardIds) {
|
|
const card = cardById.get(cardId);
|
|
if (!card) {
|
|
notFound.push(cardId);
|
|
continue;
|
|
}
|
|
// Merge: keep existing minus removed, then add new ones, de-duplicated.
|
|
const merged = mergeLabelIds(card.labelIds, addLabelIds, removeLabelIds);
|
|
writes.push(
|
|
Cards.direct.updateAsync(
|
|
// The list that was checked: a card moved since is not relabelled.
|
|
{ _id: cardId, boardId: paramBoardId, listId: card.listId, archived: false },
|
|
{ $set: { labelIds: merged } },
|
|
),
|
|
);
|
|
updated.push({ _id: cardId, labelIds: merged });
|
|
}
|
|
|
|
// Every write must land before the 200 says they did.
|
|
await Promise.all(writes);
|
|
|
|
sendJsonResult(res, { code: 200, data: { updated, notFound } });
|
|
});
|
|
|
|
WebApp.handlers.get(
|
|
'/api/boards/:boardId/cardsByCustomField/:customFieldId/:customFieldValue',
|
|
async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramCustomFieldId = req.params.customFieldId;
|
|
const paramCustomFieldValue = req.params.customFieldValue;
|
|
const { fieldPolicy } = require('/server/lib/adminOnlyCustomFields');
|
|
const { mayReadField } = require('/models/lib/adminOnlyCustomFields');
|
|
const policy = await fieldPolicy(req.userId);
|
|
if (!mayReadField(policy.definitions.get(paramCustomFieldId), paramBoardId, policy.adminBoards)) {
|
|
sendJsonResult(res, { code: 403, data: { error: 'Forbidden' } });
|
|
return;
|
|
}
|
|
await Authentication.checkBoardAccess(req.userId, paramBoardId);
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: await ReactiveCache.getCards({
|
|
boardId: paramBoardId,
|
|
customFields: {
|
|
$elemMatch: { _id: paramCustomFieldId, value: paramCustomFieldValue },
|
|
},
|
|
archived: false,
|
|
}),
|
|
});
|
|
},
|
|
);
|
|
|
|
WebApp.handlers.post(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId/customFields/:customFieldId',
|
|
async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramCardId = req.params.cardId;
|
|
const paramListId = req.params.listId;
|
|
const paramCustomFieldId = req.params.customFieldId;
|
|
const paramCustomFieldValue = req.body.value;
|
|
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
|
|
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), paramListId); // #4527
|
|
const card = await ReactiveCache.getCard({
|
|
_id: paramCardId,
|
|
listId: paramListId,
|
|
boardId: paramBoardId,
|
|
archived: false,
|
|
});
|
|
if (!card) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
const updatedCustomFields = (card.customFields || []).map(cf =>
|
|
cf._id === paramCustomFieldId ? { _id: cf._id, value: paramCustomFieldValue } : cf,
|
|
);
|
|
await Cards.direct.updateAsync(
|
|
{ _id: paramCardId, listId: paramListId, boardId: paramBoardId, archived: false },
|
|
{ $set: { customFields: updatedCustomFields } },
|
|
);
|
|
// #5681: `.direct` skips the hook that carries linked custom fields.
|
|
const { propagateLinkedCustomFields } = require('/server/models/customFieldLinks');
|
|
await propagateLinkedCustomFields(await Cards.findOneAsync(paramCardId), card.customFields);
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: { _id: paramCardId, customFields: updatedCustomFields },
|
|
});
|
|
},
|
|
);
|
|
|
|
WebApp.handlers.post(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId/archive',
|
|
async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramCardId = req.params.cardId;
|
|
const paramListId = req.params.listId;
|
|
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
|
|
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), paramListId); // #4527
|
|
const card = await ReactiveCache.getCard({
|
|
_id: paramCardId,
|
|
listId: paramListId,
|
|
boardId: paramBoardId,
|
|
archived: false,
|
|
});
|
|
if (!card) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
await card.archive();
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: { _id: paramCardId, archived: true, archivedAt: new Date() },
|
|
});
|
|
},
|
|
);
|
|
|
|
WebApp.handlers.post(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId/unarchive',
|
|
async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramCardId = req.params.cardId;
|
|
const paramListId = req.params.listId;
|
|
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
|
|
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), paramListId); // #4527
|
|
const card = await ReactiveCache.getCard({
|
|
_id: paramCardId,
|
|
listId: paramListId,
|
|
boardId: paramBoardId,
|
|
archived: true,
|
|
});
|
|
if (!card) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
await card.restore();
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: { _id: paramCardId, archived: false },
|
|
});
|
|
},
|
|
);
|
|
|
|
// Issue #5998: add/remove a single board member to/from a card as a card member
|
|
// or assignee, MERGE-style ($addToSet/$pull via Card.assignMember etc.), so
|
|
// callers don't have to read-modify-write the whole members/assignees array.
|
|
// The userId must be an active member of the card's board, otherwise 400.
|
|
async function cardMemberFieldHandler(req, res, field, paramUserKey, addNotRemove) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramListId = req.params.listId;
|
|
const paramCardId = req.params.cardId;
|
|
const targetUserId = req.params[paramUserKey];
|
|
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
|
|
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), paramListId); // #4527
|
|
|
|
const card = await ReactiveCache.getCard({
|
|
_id: paramCardId,
|
|
listId: paramListId,
|
|
boardId: paramBoardId,
|
|
archived: false,
|
|
});
|
|
if (!card) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
|
|
if (addNotRemove) {
|
|
// Only validate board membership when ADDING; removing a stale id is allowed.
|
|
const board = await ReactiveCache.getBoard(paramBoardId);
|
|
if (!canAssignCardMember(board, targetUserId)) {
|
|
sendJsonResult(res, {
|
|
code: 400,
|
|
data: { error: 'userId is not an active member of this board' },
|
|
});
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (field === 'members') {
|
|
await (addNotRemove ? card.assignMember(targetUserId) : card.unassignMember(targetUserId));
|
|
} else {
|
|
await (addNotRemove ? card.assignAssignee(targetUserId) : card.unassignAssignee(targetUserId));
|
|
}
|
|
|
|
const updated = await ReactiveCache.getCard(paramCardId);
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: { _id: paramCardId, members: updated.members || [], assignees: updated.assignees || [] },
|
|
});
|
|
}
|
|
|
|
WebApp.handlers.post(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId/members/:memberId',
|
|
async function(req, res) {
|
|
await cardMemberFieldHandler(req, res, 'members', 'memberId', true);
|
|
},
|
|
);
|
|
WebApp.handlers.delete(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId/members/:memberId',
|
|
async function(req, res) {
|
|
await cardMemberFieldHandler(req, res, 'members', 'memberId', false);
|
|
},
|
|
);
|
|
WebApp.handlers.post(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId/assignees/:assigneeId',
|
|
async function(req, res) {
|
|
await cardMemberFieldHandler(req, res, 'assignees', 'assigneeId', true);
|
|
},
|
|
);
|
|
WebApp.handlers.delete(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId/assignees/:assigneeId',
|
|
async function(req, res) {
|
|
await cardMemberFieldHandler(req, res, 'assignees', 'assigneeId', false);
|
|
},
|
|
);
|
|
|
|
// Copy a card to the same or a different board/swimlane/list, at a 0-based
|
|
// `position` counted from the top of the destination list. Deep copy is handled
|
|
// by Card.copy (comments, checklists, attachments, custom field values).
|
|
// Body: { toBoardId?, toSwimlaneId?, toListId?, position? }
|
|
WebApp.handlers.post(
|
|
'/api/boards/:boardId/lists/:listId/cards/:cardId/copy',
|
|
async function(req, res) {
|
|
const paramBoardId = req.params.boardId;
|
|
const paramListId = req.params.listId;
|
|
const paramCardId = req.params.cardId;
|
|
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
|
|
|
|
const toBoardId = req.body.toBoardId || paramBoardId;
|
|
const toSwimlaneId = req.body.toSwimlaneId;
|
|
const toListId = req.body.toListId || paramListId;
|
|
if (!toSwimlaneId) {
|
|
sendJsonResult(res, { code: 400, data: { error: 'toSwimlaneId is required' } });
|
|
return;
|
|
}
|
|
// Require write access on the destination board too (may differ from source).
|
|
await Authentication.checkBoardWriteAccess(req.userId, toBoardId);
|
|
// #4527: copying INTO a list is adding a card to it; copying out is reading.
|
|
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(toBoardId), toListId);
|
|
|
|
const card = await ReactiveCache.getCard({
|
|
_id: paramCardId,
|
|
listId: paramListId,
|
|
boardId: paramBoardId,
|
|
});
|
|
if (!card) {
|
|
sendJsonResult(res, { code: 404, data: { error: 'Card not found' } });
|
|
return;
|
|
}
|
|
|
|
let newId;
|
|
try { newId = await card.copy(toBoardId, toSwimlaneId, toListId); }
|
|
catch (error) {
|
|
if (error.error !== 'invalid-copy-destination') throw error;
|
|
sendJsonResult(res, { code: 400, data: { error: error.reason } });
|
|
return;
|
|
}
|
|
|
|
if (Object.prototype.hasOwnProperty.call(req.body, 'position')) {
|
|
const siblings = await ReactiveCache.getCards(
|
|
{ listId: toListId, archived: false, _id: { $ne: newId } },
|
|
{ sort: ['sort'] },
|
|
);
|
|
const newSort = computeSortForIndex(siblings, Number(req.body.position));
|
|
await Cards.direct.updateAsync({ _id: newId }, { $set: { sort: newSort } });
|
|
}
|
|
|
|
sendJsonResult(res, { code: 200, data: { _id: newId } });
|
|
},
|
|
);
|
|
|
|
// GHSA-6jr3-42jf-vhm5: a request body that still carries `authorId` naming
|
|
// somebody OTHER than the session is the attempt this fix refuses - the value is
|
|
// ignored either way now, and naming yourself is what an old client does, so only
|
|
// the mismatch is recorded. Shows in Admin Panel / Problems.
|
|
function noteAuthorSpoof(req, source) {
|
|
try {
|
|
const claimed = req.body && req.body.authorId;
|
|
if (!claimed || String(claimed) === String(req.userId)) return;
|
|
require('/server/lib/securityLog').record({
|
|
key: 'spoofing.author', action: 'ignored', source,
|
|
userId: req.userId,
|
|
detail: `ignored authorId "${claimed}" from the body; recorded the session instead`,
|
|
});
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
}
|
|
|
|
// GHSA-whxm-pxgj-7wqv: who may be put on a card, in the ARRAY form.
|
|
//
|
|
// `POST .../cards` and `PUT .../cards/{cardId}` take `members` and `assignees`
|
|
// as arrays and stored them exactly as given. The merge endpoint
|
|
// `POST .../cards/{cardId}/members/{memberId}` has enforced since #5998 that the
|
|
// user must be an ACTIVE member of the card's board; the array form bypassed
|
|
// that, so a member of a private board could put any user id on a card - and
|
|
// `GET /api/user/cards`, which lists by card membership, then handed that
|
|
// outsider the private board's card titles, ids and dates, while their direct
|
|
// read of the board stayed Forbidden.
|
|
//
|
|
// One rule for every shape. An id that may not be assigned is dropped rather
|
|
// than refused, so a bulk edit does not fail over one stale id, and the caller
|
|
// sees what was kept in the answer.
|
|
async function assignableOnBoard(board, ids, source) {
|
|
const out = [];
|
|
const refused = [];
|
|
for (const id of Array.isArray(ids) ? ids : []) {
|
|
if (canAssignCardMember(board, id)) out.push(id);
|
|
else if (id) refused.push(id);
|
|
}
|
|
// Naming somebody who was NEVER on this board is the attempt, so it is
|
|
// recorded and shows in Admin Panel / Problems. A FORMER member is not: a
|
|
// removed member stays in old cards' assignees, and a client that reads a
|
|
// card and writes its assignees back sends them innocently - recording that
|
|
// (high, blocked) disabled the client's own account.
|
|
const strangers = refused.filter(id => !(board && Array.isArray(board.members) &&
|
|
board.members.some(member => member && member.userId === id)));
|
|
if (strangers.length) {
|
|
try {
|
|
require('/server/lib/securityLog').record({
|
|
key: 'authz.card-member', action: 'blocked', source: source || 'card members/assignees',
|
|
detail: `refused ${strangers.length} id(s) never on board ${board && board._id}: ${strangers.join(' ')}`,
|
|
});
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// Issue #4815: get the current user's cards (cards where they are a member or
|
|
// assignee). ?due=true returns only cards that have a due date; ?from= and ?to=
|
|
// (ISO 8601) restrict due cards to a date range. Returns a compact field set.
|
|
WebApp.handlers.get('/api/user/cards', async function(req, res) {
|
|
// Return a clean 401 rather than letting checkLoggedIn throw (which under
|
|
// Express 4 would leave the request hanging instead of responding).
|
|
if (!req.userId) {
|
|
sendJsonResult(res, { code: 401, data: { error: 'Unauthorized' } });
|
|
return;
|
|
}
|
|
const userId = req.userId;
|
|
|
|
const selector = {
|
|
archived: false,
|
|
$or: [
|
|
{ members: userId }, { assignees: userId },
|
|
{ requesters: userId }, { assigners: userId },
|
|
],
|
|
};
|
|
|
|
const url = new URL(req.url, 'http://localhost');
|
|
const dueOnly = ['true', '1', 'yes'].includes(
|
|
String(url.searchParams.get('due') || '').toLowerCase(),
|
|
);
|
|
const from = url.searchParams.get('from');
|
|
const to = url.searchParams.get('to');
|
|
if (dueOnly || from || to) {
|
|
selector.dueAt = { $exists: true, $ne: null };
|
|
if (from) {
|
|
selector.dueAt.$gte = new Date(from);
|
|
}
|
|
if (to) {
|
|
selector.dueAt.$lte = new Date(to);
|
|
}
|
|
}
|
|
|
|
const cards = await ReactiveCache.getCards(selector, { sort: { dueAt: 1 } });
|
|
|
|
// GHSA-whxm-pxgj-7wqv: card membership is not board access. This listed every
|
|
// card naming the caller, so being placed on a card of a board they cannot
|
|
// read - which the array form above used to allow - disclosed that private
|
|
// board's card titles, ids and dates. Both halves are fixed: nobody outside a
|
|
// board can be put on its cards any more, and the answer is filtered here as
|
|
// well, so a card placed before this release stops leaking too.
|
|
const boardIds = [...new Set((cards || []).map(card => card.boardId).filter(Boolean))];
|
|
const visible = boardIds.length
|
|
? await ReactiveCache.getBoards(
|
|
{
|
|
_id: { $in: boardIds },
|
|
members: { $elemMatch: { userId, isActive: true } },
|
|
},
|
|
{ fields: { _id: 1, members: 1 } },
|
|
)
|
|
: [];
|
|
const visibleBoards = new Map((visible || []).map(board => [board._id, board]));
|
|
// ...and on each board by the caller's role: being a card's member,
|
|
// requester or assigner does not show an assigned-only member a card that
|
|
// is not assigned to them (GHSA-r4gm-mjj9-g3x8).
|
|
const { assignedOnlyAllowsCard } = require('/models/lib/boardCardScope');
|
|
const readable = (cards || []).filter(card => visibleBoards.has(card.boardId) &&
|
|
assignedOnlyAllowsCard(visibleBoards.get(card.boardId), userId, card));
|
|
|
|
sendJsonResult(res, {
|
|
code: 200,
|
|
data: readable.map(card => ({
|
|
_id: card._id,
|
|
title: card.title,
|
|
boardId: card.boardId,
|
|
swimlaneId: card.swimlaneId,
|
|
listId: card.listId,
|
|
dueAt: card.dueAt,
|
|
startAt: card.startAt,
|
|
endAt: card.endAt,
|
|
members: card.members || [],
|
|
assignees: card.assignees || [],
|
|
})),
|
|
});
|
|
});
|