Files
outline/server/commands/documentRestorer.ts
T
Claude 597acedf0b fix: Complete customizable document retention
Follow-up fixes to the retention feature.

The superseded CleanupDeletedDocumentsTask was still registered and ran
hourly, hard deleting documents 30 days after `deletedAt` regardless of the
team's configured period. Any retention longer than 30 days — including
infinite — had no effect.

The `destroyedAt` column was declared with a bare `@Column`. Decorator
metadata is disabled in the server build, so sequelize-typescript could not
infer its type and threw while loading the Document model.

Documents pending permanent deletion stayed readable and restorable through
`documents.info`, `documents.restore` and the MCP restore tool. They are now
treated as if they no longer exist.

Also:

- Add trash and data retention controls to workspace security settings, the
  only way to configure either was to call the API directly.
- Derive the retention tranches to process from the periods teams actually
  use, so a team holding a period that is no longer offered is not skipped.
- Bound the trash expiry task by `limit`, it previously ran an unbounded
  UPDATE across the whole documents table every hour.
- Match team preferences on JSON text rather than casting to int, so one bad
  value cannot fail the query for every other team in the batch.
- Derive the API validation schema from the same presets the UI offers.
- Send `ASC` rather than `asc` from the trash list, the sort direction was
  silently coerced back to descending.
- Move the retention badge in with the other document badges, pluralize it,
  and never show a negative day count.
- Drop the unused `Template.destroyedAt` computed, which returned a future
  date under a name meaning the opposite on the sibling model.
- Rename the migration to match its position in the sequence and the column
  it adds.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U3kXbDxLMJesYLM5E4P6HQ
2026-08-16 14:36:32 -04:00

110 lines
3.6 KiB
TypeScript

import { traceFunction } from "@server/logging/tracing";
import { NotFoundError, ValidationError } from "@server/errors";
import { Collection, Revision } from "@server/models";
import type { Document } from "@server/models";
import { authorize } from "@server/policies";
import type { APIContext } from "@server/types";
import { assertPresent } from "@server/validation";
type Props = {
/** The document to restore. Must be loaded with `paranoid: false`. */
document: Document;
/** Destination collection to restore into. Defaults to the original collection. */
collectionId?: string | null;
/** Revision to restore the document's content from, when not archived or deleted. */
revisionId?: string | null;
};
/**
* Restores a previously archived or deleted document, or restores a document's
* content to a specific revision. Re-attaches the document to the destination
* collection's structure when applicable and authorizes the acting user.
*
* @param ctx - the API context, providing the acting user and transaction.
* @param props - the document and restore options.
* @returns the restored document.
* @throws NotFoundError if the document is pending permanent deletion.
* @throws ValidationError if the destination collection is not active.
* @throws NotFoundError if the given revision does not exist.
*/
async function documentRestorer(
ctx: APIContext,
{ document, collectionId, revisionId }: Props
): Promise<Document> {
const { user } = ctx.state.auth;
const { transaction } = ctx.state;
// Documents that have left the trash are pending permanent deletion, they are
// treated as if they no longer exist.
if (document.isDestroyed) {
throw NotFoundError();
}
const sourceCollectionId = document.collectionId;
const destCollectionId = collectionId ?? sourceCollectionId;
const srcCollection = sourceCollectionId
? await Collection.findByPk(sourceCollectionId, {
userId: user.id,
includeDocumentStructure: true,
paranoid: false,
transaction,
})
: undefined;
const destCollection = destCollectionId
? await Collection.findByPk(destCollectionId, {
userId: user.id,
includeDocumentStructure: true,
transaction,
})
: undefined;
if (!destCollection?.isActive) {
throw ValidationError(
"Unable to restore, the collection may have been deleted or archived"
);
}
if (sourceCollectionId && sourceCollectionId !== destCollection.id) {
authorize(user, "updateDocument", srcCollection);
await srcCollection?.removeDocumentInStructure(document, {
save: true,
transaction,
});
}
if (document.deletedAt) {
authorize(user, "restore", document);
authorize(user, "updateDocument", destCollection);
// restore a previously deleted document
await document.restoreTo(ctx, { collectionId: destCollection.id });
} else if (document.archivedAt) {
authorize(user, "unarchive", document);
authorize(user, "updateDocument", destCollection);
// restore a previously archived document
await document.restoreTo(ctx, { collectionId: destCollection.id });
} else if (revisionId) {
// restore a document to a specific revision
authorize(user, "update", document);
const revision = await Revision.findByPk(revisionId, {
transaction,
rejectOnEmpty: true,
});
authorize(document, "restore", revision);
await document.restoreFromRevision(revision);
await document.saveWithCtx(ctx, undefined, { name: "restore" });
} else {
assertPresent(revisionId, "revisionId is required");
}
return document;
}
export default traceFunction({
spanName: "documentRestorer",
})(documentRestorer);