Files
wekan/server/models/lists.js
T
Lauri Ojansivu 3202a1d7ac A list's role exception also refuses deleting, archiving or moving it, and its swimlane.
Decided by the maintainer on 2026-11-18 (TODO.md). Deleting, archiving,
restoring or moving a list, and deleting, archiving or moving a
swimlane, does the same to the cards in it, so a list that refuses a
role write access (#4527) now refuses those too:

- lists.softRemove, lists.restore and moveList answer not-authorized;
- the REST list DELETE, archive, unarchive and move, and the REST
  swimlane DELETE, answer 403, recorded as ListLockBleed;
- moveSwimlane is refused when a list holding its cards, or bound to
  it, refuses the role (swimlaneRefusingListIds);
- client writes meet new Lists and Swimlanes deny rules, and the list
  menu no longer offers Archive list or Archive all cards in such a list.

Renaming, recolouring and reordering are not refused, and board admins
are never restricted.

tests/listLockStructure.test.cjs runs the swimlane gate and pins every
path; list-lock-bulk.e2e.js replays the REST cases. Sandboxed route
tests get a pass-through gate.

Thanks to xet7 !
2026-11-18 23:08:06 +02:00

1117 lines
41 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { check, Match } from 'meteor/check';
import { Authentication } from '/server/authentication';
import { sendJsonResult } from '/server/apiMiddleware';
import { ReactiveCache } from '/imports/reactiveCache';
import Activities from '/models/activities';
import Boards from '/models/boards';
import Cards from '/models/cards';
import Lists, { normalizeListColor } from '/models/lists';
import UserPositionHistory from '/models/userPositionHistory';
import { ensureIndex } from '/server/lib/mongoStartup';
import { computeSortForIndex } from '/server/lib/utils';
import { buildListPutUpdate } from '/models/lib/listApiUpdate';
import { Random } from 'meteor/random';
import { getFeatureFlags } from '/models/lib/featureFlags';
import { softDeleteSet, restoreModifier, canPurge } from '/models/lib/softDelete';
import { listsToUnbind } from '/models/lib/listUnbindRepair';
import ChangeHistory from '/models/changeHistory';
import { allowIsBoardMemberWithWriteAccess } from '/server/lib/utils';
import { requireBoardMutation } from '/models/lib/boardMutationGuard';
import { assertListNotRefused, assertListsWritable } from '/server/lib/listPermissionGate';
// ErrorBleed: refusals answer with their real status and a safe message.
const { publicErrorData } = require('/server/lib/apiResponseHelpers');
const hasBoardWriteAccess = allowIsBoardMemberWithWriteAccess;
// Soft delete (docs/Features/Undo/Undo.md): mark a list — and cascade-mark its live
// cards with the SAME deleteBatchId — instead of destroying them, and record a
// reversible 'delete' in position history. Restore/undo is all-or-nothing per batch.
// Shared by the `lists.softRemove` method and the REST DELETE endpoint. Returns the
// batchId. Best-effort history: a recording failure never fails the delete.
async function softRemoveList({ userId, list }) {
const at = new Date();
const batchId = Random.id();
await Cards.updateAsync(
{ listId: list._id, boardId: list.boardId, deletedAt: null },
{ $set: softDeleteSet(userId, batchId, at) },
{ multi: true },
);
await Lists.updateAsync(list._id, { $set: softDeleteSet(userId, batchId, at) });
try {
await UserPositionHistory.trackChange({
userId,
boardId: list.boardId,
entityType: 'list',
entityId: list._id,
actionType: 'delete',
previousState: { swimlaneId: list.swimlaneId, sort: list.sort, boardId: list.boardId },
newState: { deletedAt: at },
batchId,
});
} catch (e) {
// best-effort: never fail the delete because history recording failed
}
// The same change in the universal store (History.md §10.1). A lifecycle row
// is read in both directions: undoing it clears the delete mark, redoing it
// sets it again, which is what makes #1023 "undo a deleted list" work.
await ChangeHistory.record({
boardId: list.boardId,
swimlaneId: list.swimlaneId,
listId: list._id,
entityType: 'list',
entityId: list._id,
group: 'lifecycle',
changeType: 'removed',
previousContent: { deleted: false, deleteBatchId: batchId },
newContent: { deleted: true, deletedAt: at, deleteBatchId: batchId },
userId,
batchId,
});
return batchId;
}
Meteor.methods({
// Soft-delete a list (the ordinary "Delete list" action). Marks it + its cards
// deleted; restorable from the Recycle Bin / undo. Idempotent.
async 'lists.softRemove'(listId) {
check(listId, String);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'Must be logged in');
}
const list = await Lists.findOneAsync(listId);
if (!list) {
throw new Meteor.Error('not-found', 'List not found');
}
const board = await ReactiveCache.getBoard(list.boardId);
if (!hasBoardWriteAccess(this.userId, board)) {
throw new Meteor.Error('not-authorized', 'You cannot modify this board.');
}
// Decided 2026-11-18 (TODO.md): a list that refuses this role a write
// refuses deleting or restoring it, with its cards (#4527).
await assertListsWritable(this.userId, board, [list._id]);
if (list.deletedAt) {
return { deleted: true, batchId: list.deleteBatchId }; // already soft-deleted
}
const batchId = await softRemoveList({ userId: this.userId, list });
return { deleted: true, batchId };
},
// Restore a soft-deleted list and every card deleted alongside it (same batch).
async 'lists.restore'(listId) {
check(listId, String);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'Must be logged in');
}
const list = await Lists.findOneAsync(listId);
if (!list) {
throw new Meteor.Error('not-found', 'List not found');
}
const board = await ReactiveCache.getBoard(list.boardId);
if (!hasBoardWriteAccess(this.userId, board)) {
throw new Meteor.Error('not-authorized', 'You cannot modify this board.');
}
// Decided 2026-11-18 (TODO.md): a list that refuses this role a write
// refuses deleting or restoring it, with its cards (#4527).
await assertListsWritable(this.userId, board, [list._id]);
const batchId = list.deleteBatchId;
await Lists.updateAsync(list._id, restoreModifier());
if (batchId) {
await Cards.updateAsync({ deleteBatchId: batchId }, restoreModifier(), { multi: true });
}
try {
await UserPositionHistory.trackChange({
userId: this.userId,
boardId: list.boardId,
entityType: 'list',
entityId: list._id,
actionType: 'restore',
previousState: { deletedAt: list.deletedAt },
newState: { deletedAt: null },
batchId,
});
} catch (e) {
// best-effort
}
await ChangeHistory.record({
boardId: list.boardId,
swimlaneId: list.swimlaneId,
listId: list._id,
entityType: 'list',
entityId: list._id,
group: 'lifecycle',
changeType: 'added',
previousContent: { deleted: true, deletedAt: list.deletedAt, deleteBatchId: batchId },
newContent: { deleted: false, deleteBatchId: batchId },
userId: this.userId,
batchId,
});
return { restored: true };
},
// PERMANENTLY delete a soft-deleted list + its batch cards. The ONLY physical
// list delete in ordinary use — gated on Global Admin AND the Admin Panel /
// Features / Delete "Enable permanent delete" flag (models/lib/softDelete canPurge).
async 'lists.purge'(listId) {
check(listId, String);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'Must be logged in');
}
const user = await Meteor.users.findOneAsync(this.userId);
const flags = getFeatureFlags();
if (!canPurge(user, flags.enablePermanentDelete)) {
throw new Meteor.Error('not-authorized', 'Permanent delete is disabled.');
}
const list = await Lists.findOneAsync(listId);
if (!list) {
throw new Meteor.Error('not-found', 'List not found');
}
if (!list.deletedAt) {
throw new Meteor.Error('not-deleted', 'Only soft-deleted lists can be permanently deleted.');
}
const batchId = list.deleteBatchId;
if (batchId) {
await Cards.removeAsync({ deleteBatchId: batchId });
}
await Lists.removeAsync({ _id: list._id });
return { purged: true };
},
async createListAfter(params) {
// Match.Optional (not a bare Match.OneOf) so a caller may OMIT these keys — a
// missing object key throws "Match failed" for any non-Optional sub-pattern.
// The #6465 inline composer sends no nextListId, which previously 400'd here.
check(params, {
title: String,
boardId: String,
swimlaneId: Match.Optional(Match.OneOf(String, null)),
afterListId: Match.Optional(Match.OneOf(String, null)),
nextListId: Match.Optional(Match.OneOf(String, null)),
type: Match.Optional(String),
});
const {
title,
boardId,
swimlaneId = null,
afterListId = null,
nextListId = null,
type = 'list',
} = params;
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const board = await ReactiveCache.getBoard(boardId);
if (!board) {
throw new Meteor.Error('board-not-found', 'Board not found');
}
try {
if (Authentication?.checkBoardWriteAccess) {
await Authentication.checkBoardWriteAccess(this.userId, boardId);
} else if (!hasBoardWriteAccess(this.userId, board)) {
throw new Meteor.Error('not-authorized', 'Access denied');
}
} catch (error) {
throw new Meteor.Error('not-authorized', 'Access denied');
}
const normalizeSwimlaneId = value => value || '';
const getResolvedSwimlaneId = (list, fallback = '') => {
if (!list) return normalizeSwimlaneId(fallback);
if (typeof list.getEffectiveSwimlaneId === 'function') {
return normalizeSwimlaneId(list.getEffectiveSwimlaneId() || fallback);
}
return normalizeSwimlaneId(list.swimlaneId || fallback);
};
const defaultSwimlane = board.getDefaultSwimlineAsync
? await board.getDefaultSwimlineAsync()
: board.getDefaultSwimline
? board.getDefaultSwimline()
: null;
let targetSwimlaneId = normalizeSwimlaneId(swimlaneId || (defaultSwimlane && defaultSwimlane._id));
let sort = 0;
if (afterListId) {
const selectedList = await ReactiveCache.getList({
_id: afterListId,
boardId,
archived: false,
});
if (!selectedList) {
throw new Meteor.Error('list-not-found', 'Selected list not found');
}
targetSwimlaneId = getResolvedSwimlaneId(selectedList, targetSwimlaneId);
const swimlaneLists = (await ReactiveCache.getLists({
boardId,
archived: false,
}))
.filter(list => getResolvedSwimlaneId(list, targetSwimlaneId) === targetSwimlaneId)
.sort((a, b) => a.sort - b.sort);
let nextList = null;
if (nextListId) {
nextList = await ReactiveCache.getList({
_id: nextListId,
boardId,
archived: false,
});
if (nextList) {
const nextSwimlaneId = getResolvedSwimlaneId(nextList, targetSwimlaneId);
if (nextSwimlaneId !== targetSwimlaneId) {
nextList = null;
}
}
}
if (!nextList) {
const selectedIndex = swimlaneLists.findIndex(list => list._id === selectedList._id);
nextList = selectedIndex >= 0 ? swimlaneLists[selectedIndex + 1] : null;
}
if (
nextList &&
Number.isFinite(selectedList.sort) &&
nextList.sort > selectedList.sort
) {
sort = selectedList.sort + (nextList.sort - selectedList.sort) / 2;
} else if (Number.isFinite(selectedList.sort)) {
sort = selectedList.sort + 1;
} else {
const last = swimlaneLists[swimlaneLists.length - 1];
sort = Number.isFinite(last?.sort) ? last.sort + 1 : 0;
}
} else {
const swimlaneLists = (await ReactiveCache.getLists({
boardId,
archived: false,
}))
.filter(list => getResolvedSwimlaneId(list, targetSwimlaneId) === targetSwimlaneId)
.sort((a, b) => a.sort - b.sort);
const last = swimlaneLists[swimlaneLists.length - 1];
sort = Number.isFinite(last?.sort) ? last.sort + 1 : 0;
}
return await Lists.insertAsync({
title,
boardId,
sort,
type,
swimlaneId: targetSwimlaneId,
});
},
async copyList(listId, boardId, swimlaneId, title, neighborListId, position) {
check(listId, String);
check(boardId, String);
check(swimlaneId, String);
check(title, String);
check(neighborListId, Match.OneOf(String, null, undefined));
check(position, Match.OneOf(String, null, undefined));
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const list = await ReactiveCache.getList(listId);
if (!list) {
throw new Meteor.Error('list-not-found', 'List not found');
}
const sourceBoard = await Boards.findOneAsync(list.boardId);
requireBoardMutation(this.userId, sourceBoard, 'moveList:source', Meteor);
// AssignedBleed copy sibling (2026-10-02): a list holds cards an
// assigned-only member cannot see; copying or moving it would show them.
if (!require('/models/lib/boardCardScope').mayCopyFromBoard(sourceBoard, this.userId)) {
throw new Meteor.Error('not-authorized', 'You cannot copy or move this list.');
}
const targetBoard = await ReactiveCache.getBoard(boardId);
if (!targetBoard) {
throw new Meteor.Error('board-not-found', 'Target board not found');
}
requireBoardMutation(this.userId, targetBoard, 'moveList:destination', Meteor);
let sort = (await ReactiveCache.getLists({ boardId, archived: false })).length;
if (neighborListId) {
const neighborList = await ReactiveCache.getList({ _id: neighborListId, boardId, archived: false });
if (neighborList && Number.isFinite(neighborList.sort)) {
const allLists = (await ReactiveCache.getLists({ boardId, swimlaneId, archived: false }))
.sort((a, b) => a.sort - b.sort);
const neighborIndex = allLists.findIndex(l => l._id === neighborListId);
if (position === 'left') {
const prev = allLists[neighborIndex - 1];
sort = prev && Number.isFinite(prev.sort)
? (prev.sort + neighborList.sort) / 2
: neighborList.sort - 1;
} else {
const next = allLists[neighborIndex + 1];
sort = next && Number.isFinite(next.sort)
? (neighborList.sort + next.sort) / 2
: neighborList.sort + 1;
}
}
}
const { copiedScrumMetadata } = require('/models/lib/scrumCopy');
const newListId = await Lists.insertAsync({
title: title || list.title,
...copiedScrumMetadata(list, boardId),
boardId,
swimlaneId,
type: list.type,
archived: false,
wipLimit: list.wipLimit,
sort,
});
const cards = await ReactiveCache.getCards({ listId: list._id, archived: false });
for (const card of cards) {
await card.copy(boardId, swimlaneId, newListId);
}
return newListId;
},
async moveList(listId, boardId, swimlaneId, neighborListId, position, title) {
check(listId, String);
check(boardId, String);
check(swimlaneId, String);
check(neighborListId, Match.OneOf(String, null, undefined));
check(position, Match.OneOf(String, null, undefined));
check(title, Match.OneOf(String, null, undefined));
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const list = await ReactiveCache.getList(listId);
if (!list) {
throw new Meteor.Error('list-not-found', 'List not found');
}
const sourceBoard = await Boards.findOneAsync(list.boardId);
requireBoardMutation(this.userId, sourceBoard, 'moveList:source', Meteor);
// AssignedBleed copy sibling (2026-10-02): a list holds cards an
// assigned-only member cannot see; copying or moving it would show them.
if (!require('/models/lib/boardCardScope').mayCopyFromBoard(sourceBoard, this.userId)) {
throw new Meteor.Error('not-authorized', 'You cannot copy or move this list.');
}
// Decided 2026-11-18 (TODO.md): a list that refuses this role a write
// refuses moving it, with its cards (#4527).
await assertListsWritable(this.userId, sourceBoard, [list._id]);
const desiredTitle = typeof title === 'string' && title.trim().length > 0
? title.trim()
: list.title;
const targetBoard = await ReactiveCache.getBoard(boardId);
if (!targetBoard) {
throw new Meteor.Error('board-not-found', 'Target board not found');
}
requireBoardMutation(this.userId, targetBoard, 'moveList:destination', Meteor);
// #6670: a move within the same board now BINDS the list to the chosen
// swimlane, so that swimlane has to be one of the target board's - binding a
// list to a swimlane on another board would hide it everywhere. An empty
// swimlaneId is the deliberate "make it board-wide again" case.
if (swimlaneId) {
const targetSwimlane = await ReactiveCache.getSwimlane(swimlaneId);
if (!targetSwimlane || targetSwimlane.boardId !== boardId) {
throw new Meteor.Error(
'swimlane-not-found',
'That swimlane is not on the board the list is being moved to.',
);
}
}
list.title = desiredTitle;
await list.move(boardId, swimlaneId);
if (neighborListId) {
const movedList = await ReactiveCache.getList({ boardId, title: desiredTitle, archived: false });
const neighborList = await ReactiveCache.getList({ _id: neighborListId, boardId, archived: false });
if (movedList && neighborList && Number.isFinite(neighborList.sort)) {
const allLists = (await ReactiveCache.getLists({ boardId, swimlaneId, archived: false }))
.filter(l => l._id !== movedList._id)
.sort((a, b) => a.sort - b.sort);
const neighborIndex = allLists.findIndex(l => l._id === neighborListId);
let newSort;
if (position === 'left') {
const prev = allLists[neighborIndex - 1];
newSort = prev && Number.isFinite(prev.sort)
? (prev.sort + neighborList.sort) / 2
: neighborList.sort - 1;
} else {
const next = allLists[neighborIndex + 1];
newSort = next && Number.isFinite(next.sort)
? (neighborList.sort + next.sort) / 2
: neighborList.sort + 1;
}
await Lists.updateAsync(movedList._id, { $set: { sort: newSort } });
}
}
await list.archive();
},
async applyWipLimit(listId, limit) {
check(listId, String);
check(limit, Number);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const list = await ReactiveCache.getList(listId);
if (!list) {
throw new Meteor.Error('list-not-found', 'List not found');
}
const board = await ReactiveCache.getBoard(list.boardId);
if (!board || !board.hasAdmin(this.userId)) {
throw new Meteor.Error('not-authorized', 'You must be a board admin to modify WIP limits.');
}
// The client sends what the user typed. A NaN passes `check(limit, Number)` -
// it IS a number - and would reach the document, where the schema refuses it
// with nothing to show the user; 0 and negatives are meaningless as a limit.
if (!Number.isFinite(limit) || limit < 1) {
limit = 1;
}
await list.setWipLimit(limit);
},
async enableWipLimit(listId) {
check(listId, String);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const list = await ReactiveCache.getList(listId);
if (!list) {
throw new Meteor.Error('list-not-found', 'List not found');
}
const board = await ReactiveCache.getBoard(list.boardId);
if (!board || !board.hasAdmin(this.userId)) {
throw new Meteor.Error('not-authorized', 'You must be a board admin to modify WIP limits.');
}
if ((await list.getWipLimit('value')) === 0) {
await list.setWipLimit(1);
}
await list.toggleWipLimit(!(await list.getWipLimit('enabled')));
},
async enableSoftLimit(listId) {
check(listId, String);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const list = await ReactiveCache.getList(listId);
if (!list) {
throw new Meteor.Error('list-not-found', 'List not found');
}
const board = await ReactiveCache.getBoard(list.boardId);
if (!board || !board.hasAdmin(this.userId)) {
throw new Meteor.Error('not-authorized', 'You must be a board admin to modify WIP limits.');
}
await list.toggleSoftLimit(!(await list.getWipLimit('soft')));
},
// #6484 detection: does this board have lists wrongly bound to a swimlane (so
// they "disappeared" from other swimlanes)? Called cheaply when a board opens.
// Returns { needsRepair: <count of bound lists>, canRepair: <viewer is a board
// admin> } so the client can auto-run repairBoardWideLists (below) with a
// progress modal only when there is something to fix and the user may fix it.
async boardListRepairNeeded(boardId) {
check(boardId, String);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const board = await ReactiveCache.getBoard(boardId);
if (!board || !board.hasMember(this.userId)) {
throw new Meteor.Error('not-authorized', 'You must be a board member.');
}
const lists = await ReactiveCache.getLists({ boardId });
return {
needsRepair: listsToUnbind(lists).length,
canRepair: board.hasAdmin(this.userId) === true,
};
},
// #6484 repair: restore board-wide lists that were wrongly bound to a single
// swimlane (so they "disappeared" from the other swimlanes) by clearing their
// swimlaneId back to null. Run by a board admin (deliberately, or auto on board
// open when boardListRepairNeeded reports needsRepair). Idempotent: lists
// already board-wide are left untouched. Returns the number of lists un-bound.
// Note this repairs the LIST binding only; cards the same bug moved into one
// swimlane are not restored (recover those from a backup) since their intended
// swimlane cannot be known.
async repairBoardWideLists(boardId) {
check(boardId, String);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const board = await ReactiveCache.getBoard(boardId);
if (!board || !board.hasAdmin(this.userId)) {
throw new Meteor.Error('not-authorized', 'You must be a board admin to repair this board.');
}
// Include swimlane-scoped lists regardless of archived state; only the
// swimlaneId is being cleared.
const lists = await ReactiveCache.getLists({ boardId });
const ids = listsToUnbind(lists);
if (ids.length > 0) {
await Lists.direct.updateAsync(
{ _id: { $in: ids }, boardId },
{ $set: { swimlaneId: null } },
{ multi: true },
);
}
return { repaired: ids.length };
},
async myLists() {
const lists = await ReactiveCache.getLists(
{
boardId: { $in: await Boards.userBoardIds(this.userId) },
archived: false,
},
{ fields: { title: 1 } },
);
return [...new Set(lists.map(list => list.title))].sort();
},
async updateListSort(listId, boardId, updateData) {
check(listId, String);
check(boardId, String);
check(updateData, Object);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in.');
}
const board = await ReactiveCache.getBoard(boardId);
if (!board) {
throw new Meteor.Error('board-not-found', 'Board not found');
}
// Reordering / re-assigning lists is a write operation, so require board
// write access. (The previous guard referenced an unimported
// `allowIsBoardMember`, so `typeof ... === 'function'` was always false and
// the check never ran — any caller could mutate any board's lists by ID.)
if (!hasBoardWriteAccess(this.userId, board)) {
throw new Meteor.Error('permission-denied', 'User does not have permission to modify this board');
}
const list = await ReactiveCache.getList(listId);
if (!list) {
throw new Meteor.Error('list-not-found', 'List not found');
}
if (list.boardId !== boardId) {
throw new Meteor.Error('permission-denied', 'List does not belong to this board');
}
const validUpdateFields = ['sort', 'swimlaneId', 'updatedAt', 'modifiedAt'];
Object.keys(updateData).forEach(field => {
if (!validUpdateFields.includes(field)) {
throw new Meteor.Error('invalid-field', `Field ${field} is not allowed`);
}
});
if (updateData.swimlaneId) {
const swimlane = await ReactiveCache.getSwimlane(updateData.swimlaneId);
if (!swimlane || swimlane.boardId !== boardId) {
throw new Meteor.Error('invalid-swimlane', 'Invalid swimlane for this board');
}
}
// #6478: capture the pre-move position so the change is UNDOABLE. A list
// dragged to another swimlane (especially an accidental one on mobile) can be
// reverted from the position history, like card moves already are.
const previousState = {
sort: list.sort,
swimlaneId: list.swimlaneId,
boardId: list.boardId,
};
await Lists.updateAsync(
listId,
{
$set: {
...updateData,
modifiedAt: new Date(),
},
},
);
// #6478: record the list move in the undo/redo position history (best-effort;
// never fail the reorder if history recording throws).
//
// No `typeof UserPositionHistory !== 'undefined'` guard here. It is imported
// at the top of this file, so the guard was always true and did nothing -
// but it is the shape that made undo inert in the first place, and copying
// this block into a file that does NOT import the collection silently turns
// the recording off again. That is exactly how the card path stayed dead
// after #6478 was declared fixed.
{
try {
await UserPositionHistory.trackChange({
userId: this.userId,
boardId,
entityType: 'list',
entityId: listId,
actionType: 'move',
previousState,
newState: {
boardId,
swimlaneId: updateData.swimlaneId !== undefined ? updateData.swimlaneId : list.swimlaneId,
sort: updateData.sort !== undefined ? updateData.sort : list.sort,
},
});
await ChangeHistory.record({
boardId,
swimlaneId: updateData.swimlaneId !== undefined ? updateData.swimlaneId : list.swimlaneId,
listId,
entityType: 'list',
entityId: listId,
group: 'position',
changeType: 'moved',
previousContent: previousState,
newContent: {
sort: updateData.sort !== undefined ? updateData.sort : list.sort,
swimlaneId: updateData.swimlaneId !== undefined ? updateData.swimlaneId : list.swimlaneId,
},
userId: this.userId,
});
} catch (e) {
console.warn('Failed to track list move in history:', e);
}
}
return {
success: true,
listId,
updatedFields: Object.keys(updateData),
timestamp: new Date().toISOString(),
};
},
});
Meteor.startup(async () => {
await ensureIndex(Lists, { modifiedAt: -1 });
await ensureIndex(Lists, { updatedAt: 1, deleted: 1 });
await ensureIndex(Lists, { boardId: 1 });
await ensureIndex(Lists, { archivedAt: -1 });
});
Lists.after.insert(async (userId, doc) => {
await Activities.insertAsync({
userId,
type: 'list',
activityType: 'createList',
boardId: doc.boardId,
listId: doc._id,
title: doc.title,
});
Meteor.setTimeout(() => {
Lists.findOneAsync(doc._id).then(list => {
if (list) {
Promise.resolve(list.trackOriginalPosition()).catch(error => {
console.error('Failed to track original list position:', error);
});
}
}).catch(error => {
console.error('Failed to load list for original position tracking:', error);
});
}, 100);
});
Lists.before.remove(async (userId, doc) => {
const cards = await ReactiveCache.getCards({ listId: doc._id });
if (cards) {
for (const card of cards) {
if (!doc.archived) {
await Cards.removeAsync({ _id: card._id, listId: doc._id }); // RaceBleed: only while it is still in this list
continue;
}
const listArchivedAt = doc.archivedAt;
const cardArchivedAt = card.archivedAt;
const shouldDeleteCard =
!listArchivedAt ||
!card.archived ||
!cardArchivedAt ||
cardArchivedAt >= listArchivedAt;
if (shouldDeleteCard) {
await Cards.removeAsync({ _id: card._id, listId: doc._id }); // RaceBleed: only while it is still in this list
}
}
}
await Activities.insertAsync({
userId,
type: 'list',
activityType: 'removeList',
boardId: doc.boardId,
listId: doc._id,
title: doc.title,
});
});
Lists.hookOptions.after.update = { fetchPrevious: false };
Lists.after.update(async (userId, doc, fieldNames) => {
if (fieldNames.includes('title')) {
await Activities.insertAsync({
userId,
type: 'list',
activityType: 'changedListTitle',
listId: doc._id,
boardId: doc.boardId,
title: doc.title,
});
} else if (doc.archived) {
await Activities.insertAsync({
userId,
type: 'list',
activityType: 'archivedList',
listId: doc._id,
boardId: doc.boardId,
title: doc.title,
});
} else if (fieldNames.includes('archived')) {
await Activities.insertAsync({
userId,
type: 'list',
activityType: 'restoredList',
listId: doc._id,
boardId: doc.boardId,
title: doc.title,
});
}
if (fieldNames.includes('sort') || fieldNames.includes('swimlaneId')) {
await Lists.direct.updateAsync(
{ _id: doc._id },
{ $set: { _updatedAt: new Date() } },
);
}
});
// #6765: archiving a list archives its cards, and restoring it restores the
// cards archived WITH it - the rule #2292 gave swimlanes
// (models/lib/swimlaneArchive.js). Done here, on the server, because every way
// a list is archived ends in this update: the list menu, the Archive sidebar,
// the REST API and the methods. A client cascade would only reach the
// archived cards the browser was sent, which is a capped page of them.
//
// Cards already archived on their own keep their own archivedAt and stay
// archived on restore. The cards archived with the list are given the LIST's
// archivedAt, which is how restore tells the two apart - the list's time may
// come from the browser's clock, so the server's own clock is not compared
// with it.
Lists.after.update(async (userId, doc, fieldNames) => {
if (!fieldNames.includes('archived')) return;
const { cardsToArchiveWithSwimlane: toArchive, cardsToRestoreWithSwimlane: toRestore } =
require('/models/lib/swimlaneArchive');
const cards = await ReactiveCache.getCards({ listId: doc._id, boardId: doc.boardId });
if (doc.archived) {
let archivedAt = doc.archivedAt;
if (!archivedAt) {
archivedAt = new Date();
await Lists.direct.updateAsync(doc._id, { $set: { archivedAt } });
}
const archived = toArchive(cards);
for (const card of archived) await card.archive();
if (archived.length) {
await Cards.direct.updateAsync({ _id: { $in: archived.map(card => card._id) } },
{ $set: { archivedAt } }, { multi: true });
}
} else {
for (const card of toRestore(cards, doc.archivedAt)) await card.restore();
}
});
WebApp.handlers.get('/api/boards/:boardId/lists', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
// #5251: two dates per list, so a client can tell whether anything changed
// without fetching every card and diffing it.
//
// modifiedAt - the LIST document: title, sort, archived.
// cardsModifiedAt - the newest change among the cards IN it: a card added,
// edited or archived. The list's own modifiedAt does not
// move for those, which is what made this unanswerable.
//
// One query for the board's cards and a reduction in memory, rather than a
// query per list. Archived cards are included on purpose: archiving a card is
// one of the changes the client is asking about.
const { newestCardChangeByList } = require('/models/lib/listActivityDates');
const lists = await ReactiveCache.getLists({ boardId: paramBoardId, archived: false });
const cards = await ReactiveCache.getCards(
{ boardId: paramBoardId },
{ fields: { listId: 1, modifiedAt: 1, dateLastActivity: 1 } },
);
const newestByList = newestCardChangeByList(cards);
sendJsonResult(res, {
code: 200,
data: lists.map(doc => ({
_id: doc._id,
title: doc.title,
modifiedAt: doc.modifiedAt || null,
cardsModifiedAt: newestByList.get(doc._id) || null,
})),
});
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
});
WebApp.handlers.get('/api/boards/:boardId/lists/:listId', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
const paramListId = req.params.listId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
const list = await ReactiveCache.getList({
_id: paramListId,
boardId: paramBoardId,
archived: false,
});
// 404, not a 200 with an empty body (#6862).
if (!list) {
sendJsonResult(res, { code: 404, data: { error: 'List not found' } });
return;
}
sendJsonResult(res, { code: 200, data: list });
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
});
WebApp.handlers.post('/api/boards/:boardId/lists', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const board = await ReactiveCache.getBoard(paramBoardId);
const defaultSwimlane = board.getDefaultSwimlineAsync
? await board.getDefaultSwimlineAsync()
: board.getDefaultSwimline();
const id = await Lists.insertAsync({
title: req.body.title,
boardId: paramBoardId,
sort: board.lists().length,
swimlaneId: req.body.swimlaneId || defaultSwimlane?._id,
});
sendJsonResult(res, { code: 200, data: { _id: id } });
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
});
WebApp.handlers.put('/api/boards/:boardId/lists/:listId', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
const paramListId = req.params.listId;
let updated = false;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const list = await ReactiveCache.getList({
_id: paramListId,
boardId: paramBoardId,
archived: false,
});
if (!list) {
sendJsonResult(res, { code: 404, data: { error: 'List not found' } });
return;
}
// #5396: edit a list's title/color (and starred/wipLimit) via the REST API,
// like cards can be edited. The color is validated with normalizeListColor
// (named palette color OR custom '#rrggbb' hex); a bad color is rejected
// with a clear 4xx rather than being silently stored as None. The pure
// field/validation logic lives in models/lib/listApiUpdate.js so it is unit
// testable without Meteor.
const { set, error } = buildListPutUpdate(req.body, normalizeListColor);
if (error) {
sendJsonResult(res, { code: 400, data: { error } });
return;
}
// The WIP limit is set by a board admin, as the applyWipLimit /
// enableWipLimit methods require; write access edits the rest.
if (set.wipLimit !== undefined) {
await Authentication.checkBoardAdmin(req.userId, paramBoardId);
}
if (Object.keys(set).length > 0) {
await Lists.direct.updateAsync(
{ _id: paramListId, boardId: paramBoardId, archived: false },
{ $set: set },
);
updated = true;
}
if (!updated) {
sendJsonResult(res, { code: 404, data: { message: 'Error' } });
return;
}
sendJsonResult(res, { code: 200, data: { _id: paramListId } });
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
});
WebApp.handlers.delete('/api/boards/:boardId/lists/:listId', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
const paramListId = req.params.listId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
// Soft delete (docs/Features/Undo/Undo.md): mark deleted + cascade, don't destroy.
const list = await Lists.findOneAsync({ _id: paramListId, boardId: paramBoardId });
// A list that is not on this board, or is already deleted, is 404 - not a
// 200 for a deletion that did nothing.
if (!list || list.deletedAt) {
sendJsonResult(res, { code: 404, data: { error: 'List not found' } });
return;
}
// A list refusing this role refuses deleting it (decided 2026-11-18, #4527).
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), list._id, 'write', 'rest:list-delete');
await softRemoveList({ userId: req.userId, list });
sendJsonResult(res, { code: 200, data: { _id: paramListId } });
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
});
// #2906: archive and restore a list by script, as the board does (models/lists.js
// archive/restore). The PUT above edits only live lists and cannot archive.
WebApp.handlers.post('/api/boards/:boardId/lists/:listId/archive', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
const paramListId = req.params.listId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const list = await ReactiveCache.getList({ _id: paramListId, boardId: paramBoardId, archived: false });
if (!list) {
sendJsonResult(res, { code: 404, data: { error: 'List not found' } });
return;
}
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), list._id, 'write', 'rest:list-archive');
await list.archive();
sendJsonResult(res, { code: 200, data: { _id: paramListId, archived: true } });
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
});
WebApp.handlers.post('/api/boards/:boardId/lists/:listId/unarchive', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
const paramListId = req.params.listId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const list = await ReactiveCache.getList({ _id: paramListId, boardId: paramBoardId, archived: true });
if (!list) {
sendJsonResult(res, { code: 404, data: { error: 'List not found' } });
return;
}
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), list._id, 'write', 'rest:list-unarchive');
await list.restore();
sendJsonResult(res, { code: 200, data: { _id: paramListId, archived: false } });
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
});
// Reposition a list at a 0-based `position` counted from the left of the
// destination board, by setting its sort between siblings.
async function repositionList(listId, toBoardId, position) {
if (position === undefined || position === null) {
return;
}
const siblings = await ReactiveCache.getLists(
{ boardId: toBoardId, archived: false, _id: { $ne: listId } },
{ sort: { sort: 1 } },
);
const newSort = computeSortForIndex(siblings, Number(position));
await Lists.direct.updateAsync({ _id: listId }, { $set: { sort: newSort } });
}
// Copy a list (deep copy: its cards) to the same or a different board, at a
// 0-based `position` from the left. Body: { toBoardId?, toSwimlaneId?, position? }
WebApp.handlers.post(
'/api/boards/:boardId/lists/:listId/copy',
async function(req, res) {
const paramBoardId = req.params.boardId;
const paramListId = req.params.listId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const toBoardId = req.body.toBoardId || paramBoardId;
await Authentication.checkBoardWriteAccess(req.userId, toBoardId);
const list = await ReactiveCache.getList({ _id: paramListId, boardId: paramBoardId });
if (!list) {
sendJsonResult(res, { code: 404, data: { error: 'List not found' } });
return;
}
const newId = await list.copy(toBoardId, req.body.toSwimlaneId);
await repositionList(newId, toBoardId, req.body.position);
sendJsonResult(res, { code: 200, data: { _id: newId } });
},
);
// Move a list (with its cards) to the same or a different board, at a 0-based
// `position` from the left. Body: { toBoardId?, toSwimlaneId?, position? }
// NOTE: List.move merges into an existing same-titled list on the destination
// board when one exists; otherwise it recreates the list there.
WebApp.handlers.post(
'/api/boards/:boardId/lists/:listId/move',
async function(req, res) {
const paramBoardId = req.params.boardId;
const paramListId = req.params.listId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const toBoardId = req.body.toBoardId || paramBoardId;
await Authentication.checkBoardWriteAccess(req.userId, toBoardId);
const list = await ReactiveCache.getList({ _id: paramListId, boardId: paramBoardId });
if (!list) {
sendJsonResult(res, { code: 404, data: { error: 'List not found' } });
return;
}
await assertListNotRefused(req.userId, await ReactiveCache.getBoard(paramBoardId), list._id, 'write', 'rest:list-move');
if (toBoardId === paramBoardId) {
// Same-board move is purely a reposition (and optional swimlane change).
if (req.body.toSwimlaneId) {
await Lists.direct.updateAsync(
{ _id: paramListId },
{ $set: { swimlaneId: req.body.toSwimlaneId } },
);
}
await repositionList(paramListId, toBoardId, req.body.position);
sendJsonResult(res, { code: 200, data: { _id: paramListId } });
return;
}
await list.move(toBoardId, req.body.toSwimlaneId);
sendJsonResult(res, { code: 200, data: { _id: paramListId } });
},
);