Files
wekan/models/changeHistory.js
T
Lauri Ojansivu 66dd9b0938 History: two changes at once no longer fork a board's History chain.
Admin Panel -> Problems showed HistoryIntegrity, critical, "history-fork",
89,062 times. Each History row names the row before it, and the legacy
append (every board not migrated to the coordinated chain) read "the
newest row" and inserted after it as two separate steps: two changes
saved at the same moment on one board - two members, or one action whose
hooks record twice at once - both named the same row. Nothing was
tampered with, but the audit called it tampering, and undo, redo and
restore were refused for both rows. The writer gate around the legacy
append counts its writers for a migration; it does not make them take
turns.

- models/lib/historyLegacyAppend.js: a board's appends take turns in
  this server, and each links after the chain's tip - the newest row,
  then its successors, as Sync History already did - so a createdAt tie
  does not fork either. The ordinary recorder, the Scrum restore writer
  and Sync's legacy append all use it. Several servers writing one board
  at the same moment can still race; the coordinated chain is the answer
  to that.
- The hourly audit reported every broken row again every hour, which is
  where 89,062 came from; each finding is now reported once
  (historyIntegrityReported). It reads the History board by board instead
  of all at once, and a fork of two intact rows saved within a minute of
  each other is reported as what it is - integrity.historyConcurrentFork,
  medium, "a History writer race, not tampering" - while anything else
  stays critical.

Existing forks stay as they are (a row's hash cannot be changed), and
undo of their two rows is still refused.

tests/historyLegacyAppend.test.cjs: the old append forks under
concurrency (negative control), twenty appends at once on two boards
make two straight chains, a createdAt tie follows the chain, a failed
append does not stop the next, the audit tells a race from a changed or
late row, and no append in models/ or server/ links by "newest" without
taking turns.

Thanks to xet7 !
2026-10-14 22:39:36 +03:00

210 lines
7.5 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
const { SimpleSchema } = require('/imports/simpleSchema');
/**
* The universal change history — one append-only row per change a user makes.
* docs/Features/Reports/History/History.md §4 is the specification; this is
* phase 1 of §10 (the store, the write helper, and the undo/redo stack that the
* shipped position history moves onto).
*
* THIS FILE IMPORTS NO OTHER MODEL, DELIBERATELY. Its predecessor,
* models/userPositionHistory.js, imports Cards, Lists, Swimlanes, Checklists and
* ChecklistItems so that its undo() can write to them — which makes it
* unimportable from those same files. models/cards.js therefore could not import
* it, guarded on `typeof UserPositionHistory !== 'undefined'` instead, and
* recorded nothing at all for years (#6478, and the card half of it survived
* that fix). Keeping this file dependency-free means every mutation path can
* import it normally. Applying a change back to a document is the server's job
* and lives in server/models/changeHistory.js, which may import whatever it
* likes because nothing imports IT.
*/
const ChangeHistory = new Mongo.Collection('changeHistory');
/* The entity kinds a row can describe (History.md §4). */
export const ENTITY_TYPES = [
'card', 'list', 'swimlane', 'board',
'checklist', 'checklistItem', 'comment', 'attachment', 'customField', 'rule', 'scrum',
];
/* The logical groups of the card details view (History.md §3). */
export const GROUPS = [
'title', 'description', 'labels', 'members', 'assignees', 'dates',
'checklists', 'subtasks', 'attachments', 'comments', 'customFields',
'position', 'lifecycle', 'dependencies', 'rules', 'scrum',
];
/* A small closed set, each with an i18n key `history-change-<type>`. */
export const CHANGE_TYPES = ['added', 'removed', 'edited', 'moved', 'restored'];
ChangeHistory.attachSchema(
new SimpleSchema({
boardId: {
/** the board this change belongs to — permission scoping and the board view */
type: String,
optional: true,
defaultValue: null,
},
// The id columns below are what makes a container scope a plain equality
// instead of a join: a row carries every container it sits inside, so a
// swimlane's history is `{ swimlaneId }` and includes its lists' and cards'
// rows without walking the tree (History.md §6).
swimlaneId: { type: String, optional: true, defaultValue: null },
listId: { type: String, optional: true, defaultValue: null },
cardId: { type: String, optional: true, defaultValue: null },
entityType: {
/** what kind of thing changed */
type: String,
allowedValues: ENTITY_TYPES,
},
entityId: {
/** the changed entity's _id */
type: String,
},
group: {
/** which group of the card details view this belongs to */
type: String,
optional: true,
defaultValue: null,
},
changeType: {
/** added | removed | edited | moved | restored */
type: String,
allowedValues: CHANGE_TYPES,
},
previousContent: {
/** what it was — null for 'added'. Blackbox: each group stores its own shape. */
type: Object,
optional: true,
blackbox: true,
defaultValue: null,
},
newContent: {
/** what it became — null for 'removed' */
type: Object,
optional: true,
blackbox: true,
defaultValue: null,
},
userId: {
/** who made the change — the axis the Member-settings view filters on */
type: String,
},
createdAt: {
type: Date,
// eslint-disable-next-line consistent-return
autoValue() {
if (this.isInsert && !this.isSet) return new Date();
if (this.isUpsert) return { $setOnInsert: new Date() };
if (!this.isInsert) this.unset();
},
},
// The undo/redo stack, folded in from userPositionHistory (History.md §7c).
undone: { type: Boolean, defaultValue: false },
undoneAt: { type: Date, optional: true, defaultValue: null },
isCheckpoint: { type: Boolean, defaultValue: false },
batchId: {
/** groups one logical multi-entity change so it undoes as a unit */
type: String,
optional: true,
defaultValue: null,
},
// Restore provenance, set only when changeType === 'restored' (§8.3).
restoredFromId: { type: String, optional: true, defaultValue: null },
restoredByUserId: { type: String, optional: true, defaultValue: null },
previousHash: { type: String, optional: true, defaultValue: null },
integrityHash: { type: String, optional: true, defaultValue: null },
superseded: { type: Boolean, optional: true, defaultValue: false },
}),
);
/**
* Append one change. Best-effort by contract: a history failure must never fail
* the mutation it describes, so this resolves rather than throws (History.md §5).
*
* Returns the new row's _id, or null when nothing was recorded.
*/
ChangeHistory.record = async function record(options) {
const {
boardId = null,
swimlaneId = null,
listId = null,
cardId = null,
entityType,
entityId,
group = null,
changeType,
previousContent = null,
newContent = null,
userId,
batchId = null,
restoredFromId = null,
restoredByUserId = null,
isCheckpoint = false,
} = options || {};
// A row nobody can attribute or locate is not history, it is noise.
if (!userId || !entityType || !entityId || !changeType) return null;
if (!ENTITY_TYPES.includes(entityType)) return null;
if (!CHANGE_TYPES.includes(changeType)) return null;
try {
const createdAt = new Date();
const row = {
boardId,
swimlaneId,
listId,
cardId,
entityType,
entityId,
group,
changeType,
previousContent,
newContent,
userId,
undone: false,
undoneAt: null,
isCheckpoint,
batchId,
restoredFromId,
restoredByUserId,
createdAt,
superseded: false,
};
// One append at a time per board, after the chain's tip
// (models/lib/historyLegacyAppend.js): two at once used to fork it.
const legacy = document => {
const { hashHistoryRow } = require('/models/lib/changeHistoryIntegrity');
const { appendLegacyHistoryRow } = require('/models/lib/historyLegacyAppend');
return appendLegacyHistoryRow({ history: ChangeHistory, boardId, document, hash: hashHistoryRow,
prepare: doc => ({ ...doc, createdAt: new Date() }) });
};
const write = async append => {
// A NEW change clears this user's redo stack on this board (History.md §7c):
// an undone change that has since been superseded must never be redoable
// back over the newer work. Retain and flag the rows so the integrity chain
// remains auditable without allowing redo to resurrect stale content.
if (changeType !== 'restored' && !isCheckpoint) {
await ChangeHistory.updateAsync(
{ userId, boardId, undone: true },
{ $set: { superseded: true } },
{ multi: true },
);
}
return append(row);
};
return await (Meteor.isServer && typeof ChangeHistory.withHistoryWriter === 'function'
? ChangeHistory.withHistoryWriter({ boardId, row, write, legacy }) : write(legacy));
} catch (error) {
// Deliberately swallowed. The alternative is that a schema slip in a history
// row stops a user moving a card.
if (Meteor.isServer) {
console.warn('changeHistory: failed to record a change:', error && error.message);
}
return null;
}
};
export default ChangeHistory;