feat: Document verification and freshness tracking

Adds a verification lifecycle to documents. A user with admin-level access
to a document (document admin membership or team admin) can mark it as
verified, vouching that its content is accurate. Verification carries an
optional expiry deadline derived from a re-verification interval resolved
through a document → collection → team preference inheritance chain.

- documents.verify / documents.unverify API endpoints, gated by new
  verify/unverify abilities
- verificationInterval override on documents.update and a collection
  default on collections.update (team admin only), plus a team-wide
  default via the verificationInterval team preference
- verificationStatus filter (verified/unverified/expired/expiring) on
  documents.list
- daily VerificationExpirySweepTask emits idempotent
  documents.verification_expired events without mutating documents;
  expiry is derived from the materialized verificationExpiresAt deadline
- notification and email to the verifier when their verification lapses;
  suppressed when the verifier is deleted, suspended, or lost access
- verification state excluded from duplicates and public shares;
  presenter exposes verifiedAt/verifiedById/verificationExpiresAt/
  verificationInterval and a derived editedSinceVerification flag

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Mb5McXaNbEDyyCZXPAdGAY
This commit is contained in:
Claude committed 2026-07-05 15:50:13 +00:00
1 parent 1b268ee26d
commit 4717c029aa
29 files changed
+1585 -1

No files matched your search

+3
View File
@@ -285,6 +285,9 @@ class Notification extends Model {
case NotificationEventType.ExportCompleted: {
return settingsPath("export");
}
case NotificationEventType.VerificationExpired: {
return this.document?.path;
}
default:
this.event satisfies never;
return;
@@ -196,6 +196,9 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
case "documents.move":
case "documents.update":
case "documents.title_change":
case "documents.verify":
case "documents.unverify":
case "documents.verification_expired":
await this.handleDocumentEvent(subscription, event);
return;
case "documents.add_user":
+3
View File
@@ -22,6 +22,7 @@ type Props = Optional<
| "importId"
| "apiImportId"
| "fullWidth"
| "verificationInterval"
| "sourceMetadata"
| "editorVersion"
| "publishedAt"
@@ -161,6 +162,7 @@ export default async function documentCreator(
content,
template,
fullWidth,
verificationInterval,
importId,
apiImportId,
createdAt,
@@ -229,6 +231,7 @@ export default async function documentCreator(
apiImportId,
sourceMetadata,
fullWidth: fullWidth ?? template?.fullWidth,
verificationInterval,
icon: icon ?? template?.icon,
color: color ?? template?.color,
title: titleWithReplacements,
@@ -31,6 +31,31 @@ describe("documentDuplicator", () => {
expect(response[0].publishedAt).toBeInstanceOf(Date);
});
it("should not copy verification state, but keep the interval override", async () => {
const user = await buildUser();
const original = await buildDocument({
userId: user.id,
teamId: user.teamId,
verifiedAt: new Date(),
verifiedById: user.id,
verificationExpiresAt: new Date(),
verificationInterval: 90,
});
const response = await withAPIContext(user, (ctx) =>
documentDuplicator(ctx, {
document: original,
collection: original.collection,
})
);
expect(response).toHaveLength(1);
expect(response[0].verifiedAt).toEqual(null);
expect(response[0].verifiedById).toEqual(null);
expect(response[0].verificationExpiresAt).toEqual(null);
expect(response[0].verificationInterval).toEqual(90);
});
it("should duplicate document with title override", async () => {
const user = await buildUser();
const original = await buildDocument({
+2
View File
@@ -36,6 +36,7 @@ export default async function documentDuplicator(
icon: document.icon,
color: document.color,
fullWidth: document.fullWidth,
verificationInterval: document.verificationInterval,
title: title ?? document.title,
content: ProsemirrorHelper.removeMarks(
DocumentHelper.toProsemirror(document),
@@ -87,6 +88,7 @@ export default async function documentDuplicator(
icon: childDocument.icon,
color: childDocument.color,
fullWidth: childDocument.fullWidth,
verificationInterval: childDocument.verificationInterval,
title: childDocument.title,
content: ProsemirrorHelper.removeMarks(
DocumentHelper.toProsemirror(childDocument),
+29
View File
@@ -1,4 +1,5 @@
import type { TextEditMode } from "@shared/types";
import { Day } from "@shared/utils/time";
import { Event, Document } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import { TextHelper } from "@server/models/helpers/TextHelper";
@@ -25,6 +26,8 @@ type Props = {
fullWidth?: boolean;
/** Whether insights should be visible on the document */
insightsEnabled?: boolean;
/** Re-verification cadence override in days, null clears the override */
verificationInterval?: number | null;
/** The edit mode: "replace", "append", "prepend", or "patch" */
editMode?: TextEditMode;
/** The markdown text to find when using "patch" edit mode */
@@ -54,6 +57,7 @@ export default async function documentUpdater(
templateId,
fullWidth,
insightsEnabled,
verificationInterval,
editMode,
findText,
publish,
@@ -86,6 +90,21 @@ export default async function documentUpdater(
if (insightsEnabled !== undefined) {
document.insightsEnabled = insightsEnabled;
}
if (verificationInterval !== undefined) {
document.verificationInterval = verificationInterval;
// recompute the materialized deadline when currently verified, as the
// effective interval may have changed, including falling back through
// the collection and team inheritance chain when the override is cleared.
if (document.verifiedAt) {
const interval = await document.resolveVerificationInterval({
transaction,
});
document.verificationExpiresAt = interval
? new Date(document.verifiedAt.getTime() + interval * Day.ms)
: null;
}
}
if (text !== undefined) {
document = DocumentHelper.applyMarkdownToDocument(
document,
@@ -98,6 +117,12 @@ export default async function documentUpdater(
}
const changed = document.changed();
const verificationOnly =
!!changed &&
changed.every(
(attr) =>
attr === "verificationInterval" || attr === "verificationExpiresAt"
);
const eventData = done !== undefined ? { done } : undefined;
const event = {
@@ -112,6 +137,10 @@ export default async function documentUpdater(
document.collectionId = cId;
}
await document.publish(ctx, { collectionId: cId, data: eventData });
} else if (verificationOnly) {
// changing the verification cadence is a policy change, not a content
// edit, so it must not update the edit timestamps or the last editor
await document.saveWithCtx(ctx, { silent: true }, { data: eventData });
} else if (changed) {
document.lastModifiedById = user.id;
document.updatedBy = user;
@@ -0,0 +1,118 @@
import * as React from "react";
import { NotificationEventType } from "@shared/types";
import { Document } from "@server/models";
import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper";
import type { EmailProps } from "./BaseEmail";
import BaseEmail, { EmailMessageCategory } from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
import EmailTemplate from "./components/EmailLayout";
import EmptySpace from "./components/EmptySpace";
import Footer from "./components/Footer";
import Header from "./components/Header";
import Heading from "./components/Heading";
type InputProps = EmailProps & {
userId: string;
documentId: string;
teamUrl: string;
};
type BeforeSend = {
document: Document;
unsubscribeUrl: string;
};
type Props = InputProps & BeforeSend;
/**
* Email sent to the verifier of a document when their verification has
* expired and the document is due to be reviewed again.
*/
export default class DocumentVerificationExpiredEmail extends BaseEmail<
InputProps,
BeforeSend
> {
protected get category() {
return EmailMessageCategory.Notification;
}
protected async beforeSend(props: InputProps) {
const document = await Document.unscoped().findByPk(props.documentId);
if (!document) {
return false;
}
return {
document,
unsubscribeUrl: this.unsubscribeUrl(props),
};
}
protected unsubscribeUrl({ userId }: InputProps) {
return NotificationSettingsHelper.unsubscribeUrl(
userId,
NotificationEventType.VerificationExpired
);
}
protected subject({ document }: Props) {
return this.t("Your verification of “{{ documentTitle }}” has expired", {
documentTitle: document.titleWithDefault,
});
}
protected preview({ document }: Props): string {
return this.t("“{{ documentTitle }}” is due to be reviewed again", {
documentTitle: document.titleWithDefault,
});
}
protected renderAsText({ teamUrl, document }: Props): string {
return `
${this.t("Your verification of “{{ documentTitle }}” has expired", { documentTitle: document.titleWithDefault })}
${this.t(
"You previously verified this document as accurate. That verification has now lapsed – please review the content and verify it again if it is still correct."
)}
${this.t("Open Document")}: ${teamUrl}${document.url}
`;
}
protected render(props: Props) {
const { document, teamUrl, unsubscribeUrl } = props;
const documentLink = `${teamUrl}${document.url}?ref=notification-email`;
return (
<EmailTemplate
previewText={this.preview(props)}
goToAction={{ url: documentLink, name: this.t("View Document") }}
>
<Header />
<Body>
<Heading>
{this.t("Your verification of “{{ documentTitle }}” has expired", {
documentTitle: document.titleWithDefault,
})}
</Heading>
<p>
{this.t(
"You previously verified the document as accurate. That verification has now lapsed – please review the content and verify it again if it is still correct."
)}
</p>
<EmptySpace height={10} />
<p>
<Button href={documentLink}>{this.t("Open Document")}</Button>
</p>
</Body>
<Footer
unsubscribeUrl={unsubscribeUrl}
unsubscribeText={this.t("Unsubscribe from these emails")}
/>
</EmailTemplate>
);
}
}
@@ -0,0 +1,96 @@
"use strict";
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.sequelize.transaction(async (transaction) => {
await queryInterface.addColumn(
"documents",
"verifiedAt",
{
type: Sequelize.DATE,
allowNull: true,
},
{ transaction }
);
await queryInterface.addColumn(
"documents",
"verifiedById",
{
type: Sequelize.UUID,
allowNull: true,
references: {
model: "users",
},
onDelete: "SET NULL",
},
{ transaction }
);
await queryInterface.addColumn(
"documents",
"verificationExpiresAt",
{
type: Sequelize.DATE,
allowNull: true,
},
{ transaction }
);
await queryInterface.addColumn(
"documents",
"verificationInterval",
{
type: Sequelize.INTEGER,
allowNull: true,
},
{ transaction }
);
await queryInterface.addColumn(
"collections",
"verificationInterval",
{
type: Sequelize.INTEGER,
allowNull: true,
},
{ transaction }
);
await queryInterface.addIndex(
"documents",
["teamId", "verificationExpiresAt"],
{
name: "documents_team_id_verification_expires_at",
where: {
verificationExpiresAt: {
[Sequelize.Op.ne]: null,
},
},
transaction,
}
);
});
},
async down(queryInterface) {
await queryInterface.sequelize.transaction(async (transaction) => {
await queryInterface.removeIndex(
"documents",
"documents_team_id_verification_expires_at",
{ transaction }
);
await queryInterface.removeColumn("documents", "verificationInterval", {
transaction,
});
await queryInterface.removeColumn("documents", "verificationExpiresAt", {
transaction,
});
await queryInterface.removeColumn("documents", "verifiedById", {
transaction,
});
await queryInterface.removeColumn("documents", "verifiedAt", {
transaction,
});
await queryInterface.removeColumn("collections", "verificationInterval", {
transaction,
});
});
},
};
+5
View File
@@ -314,6 +314,11 @@ class Collection extends ParanoidModel<
@Column(DataType.BOOLEAN)
commenting: boolean | null;
/** Default re-verification cadence for documents in this collection, in days. Null means inherit the team preference. */
@AllowNull
@Column(DataType.INTEGER)
verificationInterval: number | null;
@AllowNull
@Column(DataType.JSONB)
sourceMetadata: SourceMetadata | null;
+113
View File
@@ -451,3 +451,116 @@ describe("commentCount", () => {
expect(await document.commentCount).toEqual(1);
});
});
describe("verification", () => {
describe("#resolveVerificationInterval", () => {
it("should prefer the document override over all other sources", async () => {
const team = await buildTeam({
preferences: { verificationInterval: 365 },
});
const collection = await buildCollection({
teamId: team.id,
verificationInterval: 180,
});
const document = await buildDocument({
teamId: team.id,
collectionId: collection.id,
verificationInterval: 30,
});
expect(await document.resolveVerificationInterval()).toEqual(30);
});
it("should fall back to the collection default", async () => {
const team = await buildTeam({
preferences: { verificationInterval: 365 },
});
const collection = await buildCollection({
teamId: team.id,
verificationInterval: 180,
});
const document = await buildDocument({
teamId: team.id,
collectionId: collection.id,
});
expect(await document.resolveVerificationInterval()).toEqual(180);
});
it("should fall back to the team preference", async () => {
const team = await buildTeam({
preferences: { verificationInterval: 365 },
});
const collection = await buildCollection({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
collectionId: collection.id,
});
expect(await document.resolveVerificationInterval()).toEqual(365);
});
it("should return null when no interval is configured anywhere", async () => {
const document = await buildDocument();
expect(await document.resolveVerificationInterval()).toEqual(null);
});
});
describe("#verifyWithCtx", () => {
it("should set the verification fields and compute the deadline", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
userId: user.id,
verificationInterval: 90,
});
const updatedAt = document.updatedAt;
await withAPIContext(user, (ctx) => document.verifyWithCtx(ctx));
expect(document.verifiedAt).toBeTruthy();
expect(document.verifiedById).toEqual(user.id);
expect(document.verificationExpiresAt).toEqual(
new Date(document.verifiedAt!.getTime() + 90 * 24 * 60 * 60 * 1000)
);
// verifying must not count as an edit of the document
expect(document.updatedAt).toEqual(updatedAt);
});
it("should leave the deadline empty when no interval is configured", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
userId: user.id,
});
await withAPIContext(user, (ctx) => document.verifyWithCtx(ctx));
expect(document.verifiedAt).toBeTruthy();
expect(document.verificationExpiresAt).toEqual(null);
});
});
describe("#unverifyWithCtx", () => {
it("should clear verification state but keep the interval override", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
userId: user.id,
verificationInterval: 90,
});
await withAPIContext(user, (ctx) => document.verifyWithCtx(ctx));
await withAPIContext(user, (ctx) => document.unverifyWithCtx(ctx));
expect(document.verifiedAt).toEqual(null);
expect(document.verifiedById).toEqual(null);
expect(document.verificationExpiresAt).toEqual(null);
expect(document.verificationInterval).toEqual(90);
});
});
});
+166
View File
@@ -44,6 +44,8 @@ import type {
ProsemirrorData,
SourceMetadata,
} from "@shared/types";
import { TeamPreference } from "@shared/types";
import { Day } from "@shared/utils/time";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import { UrlHelper } from "@shared/utils/UrlHelper";
import slugify from "@shared/utils/slugify";
@@ -389,6 +391,24 @@ class Document extends ArchivableModel<
@Column(DataType.DATE)
publishedAt: Date | null;
/** When the document content was last verified as accurate, if ever. */
@IsDate
@AllowNull
@Column(DataType.DATE)
verifiedAt: Date | null;
/** When the current verification lapses. Null means it never expires. */
@IsDate
@AllowNull
@Column(DataType.DATE)
verificationExpiresAt: Date | null;
/** Per-document override of the re-verification cadence, in days. Null means inherit. */
@IsNumeric
@AllowNull
@Column(DataType.INTEGER)
verificationInterval: number | null;
/** An array of user IDs that have edited this document. */
@Column(DataType.ARRAY(DataType.UUID))
collaboratorIds: string[];
@@ -641,6 +661,14 @@ class Document extends ArchivableModel<
@Column(DataType.UUID)
createdById: string;
@BelongsTo(() => User, "verifiedById")
verifiedBy: User | null;
@AllowNull
@ForeignKey(() => User)
@Column(DataType.UUID)
verifiedById: string | null;
@ForeignKey(() => Template)
@Column(DataType.UUID)
templateId: string;
@@ -883,6 +911,55 @@ class Document extends ArchivableModel<
);
}
/**
* Finds documents whose verification expired within the given time window,
* scoped to a UUID partition of the documents table. Archived and deleted
* documents are excluded.
*
* @param options.windowStart inclusive lower bound for the expiry time.
* @param options.windowEnd exclusive upper bound for the expiry time.
* @param options.startUuid inclusive lower bound of the document id partition.
* @param options.endUuid inclusive upper bound of the document id partition.
* @returns the matching documents with the verifier association loaded.
*/
static findExpiredVerifications({
windowStart,
windowEnd,
startUuid,
endUuid,
}: {
windowStart: Date;
windowEnd: Date;
startUuid: string;
endUuid: string;
}): Promise<Document[]> {
return this.scope(["withDrafts", "withoutState"]).findAll({
where: {
verifiedAt: {
[Op.ne]: null,
},
verificationExpiresAt: {
[Op.gte]: windowStart,
[Op.lt]: windowEnd,
},
archivedAt: {
[Op.eq]: null,
},
id: {
[Op.gte]: startUuid,
[Op.lte]: endUuid,
},
},
include: [
{
model: User,
as: "verifiedBy",
required: false,
},
],
});
}
// instance methods
/**
@@ -1165,6 +1242,95 @@ class Document extends ArchivableModel<
return this.saveWithCtx(ctx, undefined, { name: "unpublish" });
};
/**
* Resolves the effective re-verification interval for this document by
* walking the inheritance chain: document override, then collection default,
* then team preference.
*
* @param options.transaction optional transaction to load associations with.
* @returns the interval in days, or null when verification never expires.
*/
resolveVerificationInterval = async (options?: {
transaction?: Transaction | null;
}): Promise<number | null> => {
if (this.verificationInterval) {
return this.verificationInterval;
}
const collection = this.collectionId
? (this.collection ??
(await this.$get("collection", {
transaction: options?.transaction,
})))
: null;
if (collection?.verificationInterval) {
return collection.verificationInterval;
}
const team =
this.team ??
(await this.$get("team", { transaction: options?.transaction }));
const preference = team?.getPreference(TeamPreference.VerificationInterval);
return typeof preference === "number" ? preference : null;
};
/**
* Marks the document as verified by the acting user, computing the expiry
* deadline from the re-verification interval resolved at the time of the
* call. Emits a "documents.verify" event. Calling this on an already
* verified document re-verifies it, overwriting the previous verification.
*
* @param ctx the API context of the request.
* @returns the updated document.
*/
verifyWithCtx = async (ctx: APIContext) => {
const { user } = ctx.state.auth;
const { transaction } = ctx.state;
const interval = await this.resolveVerificationInterval({ transaction });
this.verifiedAt = new Date();
this.verifiedById = user.id;
this.verifiedBy = user;
this.verificationExpiresAt = interval
? new Date(this.verifiedAt.getTime() + interval * Day.ms)
: null;
// silent so that verifying does not count as an edit of the document
return this.saveWithCtx(
ctx,
{ silent: true },
{
name: "verify",
data: {
expiresAt: this.verificationExpiresAt?.toISOString() ?? null,
},
}
);
};
/**
* Removes the current verification from the document and emits a
* "documents.unverify" event. The per-document interval override is
* intentionally preserved. Calling this on an unverified document is a
* no-op.
*
* @param ctx the API context of the request.
* @returns the updated document.
*/
unverifyWithCtx = async (ctx: APIContext) => {
if (!this.verifiedAt) {
return this;
}
this.verifiedAt = null;
this.verifiedById = null;
this.verifiedBy = null;
this.verificationExpiresAt = null;
// silent so that unverifying does not count as an edit of the document
return this.saveWithCtx(ctx, { silent: true }, { name: "unverify" });
};
// Moves a document from being visible to the team within a collection
// to the archived area, where it can be subsequently restored.
archiveWithCtx = async (ctx: APIContext) => {
+14
View File
@@ -109,6 +109,20 @@ allow(User, "publish", Document, (actor, document) =>
)
);
allow(User, ["verify", "unverify"], Document, (actor, document) =>
and(
isTeamMutable(actor),
can(actor, "read", document),
!!document?.publishedAt,
!document?.template,
!!document?.isActive,
or(
includesMembership(document, [DocumentPermission.Admin]),
isTeamAdmin(actor, document)
)
)
);
allow(User, "manageUsers", Document, (actor, document) =>
and(
isTeamMutable(actor),
+1
View File
@@ -55,6 +55,7 @@ export default async function presentCollection(
res.sharing = collection.sharing;
res.commenting = collection.commenting;
res.templateManagement = collection.templateManagement;
res.verificationInterval = collection.verificationInterval;
res.permission = collection.permission;
res.deletedAt = collection.deletedAt;
res.archivedAt = collection.archivedAt;
+6
View File
@@ -113,6 +113,12 @@ async function presentDocument(
res.templateId = document.templateId;
res.insightsEnabled = document.insightsEnabled;
res.popularityScore = document.popularityScore;
res.verifiedAt = document.verifiedAt;
res.verifiedById = document.verifiedById;
res.verificationExpiresAt = document.verificationExpiresAt;
res.verificationInterval = document.verificationInterval;
res.editedSinceVerification =
!!document.verifiedAt && document.updatedAt > document.verifiedAt;
if (options.includeCommentCount) {
res.commentCount = await document.commentCount;
}
@@ -9,6 +9,7 @@ import DocumentAccessRequestEmail from "@server/emails/templates/DocumentAccessR
import DocumentMentionedEmail from "@server/emails/templates/DocumentMentionedEmail";
import DocumentPublishedOrUpdatedEmail from "@server/emails/templates/DocumentPublishedOrUpdatedEmail";
import DocumentSharedEmail from "@server/emails/templates/DocumentSharedEmail";
import DocumentVerificationExpiredEmail from "@server/emails/templates/DocumentVerificationExpiredEmail";
import { Notification } from "@server/models";
import type { Event, NotificationEvent } from "@server/types";
import BaseProcessor from "./BaseProcessor";
@@ -211,6 +212,20 @@ export default class EmailsProcessor extends BaseProcessor {
return;
}
case NotificationEventType.VerificationExpired: {
await new DocumentVerificationExpiredEmail(
{
to: notification.user.email,
language: notification.user.language,
userId: notification.userId,
documentId: notification.documentId,
teamUrl: notification.team.url,
},
{ notificationId }
).schedule();
return;
}
case NotificationEventType.RequestDocumentAccess: {
await new DocumentAccessRequestEmail(
{
@@ -20,6 +20,7 @@ import DocumentAccessRequestNotificationsTask from "../tasks/DocumentAccessReque
import DocumentAddGroupNotificationsTask from "../tasks/DocumentAddGroupNotificationsTask";
import DocumentAddUserNotificationsTask from "../tasks/DocumentAddUserNotificationsTask";
import DocumentPublishedNotificationsTask from "../tasks/DocumentPublishedNotificationsTask";
import DocumentVerificationExpiredNotificationsTask from "../tasks/DocumentVerificationExpiredNotificationsTask";
import RevisionCreatedNotificationsTask from "../tasks/RevisionCreatedNotificationsTask";
import ShareSubscriptionNotificationsTask from "../tasks/ShareSubscriptionNotificationsTask";
import BaseProcessor from "./BaseProcessor";
@@ -29,6 +30,7 @@ export default class NotificationsProcessor extends BaseProcessor {
"documents.publish",
"documents.add_user",
"documents.add_group",
"documents.verification_expired",
"access_requests.create",
"revisions.create",
"collections.create",
@@ -47,6 +49,8 @@ export default class NotificationsProcessor extends BaseProcessor {
return this.documentAddUser(event);
case "documents.add_group":
return this.documentAddGroup(event);
case "documents.verification_expired":
return this.documentVerificationExpired(event);
case "access_requests.create":
return this.documentAccessRequest(event);
case "revisions.create":
@@ -94,6 +98,10 @@ export default class NotificationsProcessor extends BaseProcessor {
await new DocumentAccessRequestNotificationsTask().schedule(event);
}
async documentVerificationExpired(event: DocumentEvent) {
await new DocumentVerificationExpiredNotificationsTask().schedule(event);
}
async revisionCreated(event: RevisionEvent) {
await new RevisionCreatedNotificationsTask().schedule(event);
await new ShareSubscriptionNotificationsTask().schedule(event);
@@ -0,0 +1,108 @@
import { subDays, subHours } from "date-fns";
import { NotificationEventType } from "@shared/types";
import { Notification } from "@server/models";
import type { DocumentEvent } from "@server/types";
import { buildDocument, buildTeam, buildUser } from "@server/test/factories";
import DocumentVerificationExpiredNotificationsTask from "./DocumentVerificationExpiredNotificationsTask";
vi.setConfig({ testTimeout: 30000 });
describe("DocumentVerificationExpiredNotificationsTask", () => {
let task: DocumentVerificationExpiredNotificationsTask;
beforeEach(() => {
task = new DocumentVerificationExpiredNotificationsTask();
});
const buildExpiredDocument = async () => {
const team = await buildTeam();
const verifier = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
userId: verifier.id,
verifiedAt: subDays(new Date(), 30),
verifiedById: verifier.id,
verificationExpiresAt: subHours(new Date(), 12),
});
const event = {
name: "documents.verification_expired",
documentId: document.id,
collectionId: document.collectionId,
teamId: team.id,
data: {
expiresAt: document.verificationExpiresAt!.toISOString(),
},
} as DocumentEvent;
return { team, verifier, document, event };
};
const countNotifications = (userId: string) =>
Notification.count({
where: {
event: NotificationEventType.VerificationExpired,
userId,
},
});
it("creates a notification for an active verifier", async () => {
const { verifier, document, event } = await buildExpiredDocument();
await task.perform(event);
expect(await countNotifications(verifier.id)).toBe(1);
const notification = await Notification.findOne({
where: {
event: NotificationEventType.VerificationExpired,
userId: verifier.id,
},
});
expect(notification?.documentId).toEqual(document.id);
});
it("creates no notification when the verifier is suspended", async () => {
const { verifier, event } = await buildExpiredDocument();
await verifier.update({ suspendedAt: new Date() });
await task.perform(event);
expect(await countNotifications(verifier.id)).toBe(0);
});
it("creates no notification when the verifier was deleted", async () => {
const { team, verifier, document, event } = await buildExpiredDocument();
await buildUser({ teamId: team.id });
// deleting a user nulls the verifier reference via the FK
await document.update({ verifiedById: null });
await verifier.destroy();
await task.perform(event);
expect(await countNotifications(verifier.id)).toBe(0);
});
it("creates no notification when the document was re-verified since", async () => {
const { verifier, document, event } = await buildExpiredDocument();
await document.update({
verifiedAt: new Date(),
verificationExpiresAt: subDays(new Date(), -30),
});
await task.perform(event);
expect(await countNotifications(verifier.id)).toBe(0);
});
it("creates no notification when the verifier unsubscribed from the event", async () => {
const { verifier, event } = await buildExpiredDocument();
await verifier.update({
notificationSettings: {
[NotificationEventType.VerificationExpired]: false,
},
});
await task.perform(event);
expect(await countNotifications(verifier.id)).toBe(0);
});
});
@@ -0,0 +1,54 @@
import { NotificationEventType } from "@shared/types";
import { Document, Notification, User } from "@server/models";
import type { DocumentEvent } from "@server/types";
import { canUserAccessDocument } from "@server/utils/permissions";
import { BaseTask, TaskPriority } from "./base/BaseTask";
/**
* Notifies the verifier of a document that their verification has expired.
* The verifier is the only candidate recipient – when they have been removed,
* suspended, or have lost access to the document no notification is sent at
* all, the audit event alone records the expiry.
*/
export default class DocumentVerificationExpiredNotificationsTask extends BaseTask<DocumentEvent> {
public async perform(event: DocumentEvent) {
const document = await Document.findByPk(event.documentId);
if (!document || !document.verifiedAt || !document.verifiedById) {
return;
}
// ignore stale events – the document was re-verified with a new deadline
// after this event was emitted.
if (
event.name === "documents.verification_expired" &&
document.verificationExpiresAt?.toISOString() !== event.data.expiresAt
) {
return;
}
const recipient = await User.findByPk(document.verifiedById);
if (
!recipient ||
recipient.isSuspended ||
!recipient.subscribedToEventType(
NotificationEventType.VerificationExpired
) ||
!(await canUserAccessDocument(recipient, document.id))
) {
return;
}
await Notification.create({
event: NotificationEventType.VerificationExpired,
userId: recipient.id,
teamId: document.teamId,
documentId: document.id,
});
}
public get options() {
return {
priority: TaskPriority.Background,
};
}
}
@@ -0,0 +1,147 @@
import { subDays, subHours } from "date-fns";
import { Event } from "@server/models";
import { buildDocument, buildTeam, buildUser } from "@server/test/factories";
import VerificationExpirySweepTask from "./VerificationExpirySweepTask";
const props = {
limit: 10000,
partition: {
partitionIndex: 0,
partitionCount: 1,
},
};
vi.setConfig({ testTimeout: 30000 });
describe("VerificationExpirySweepTask", () => {
let task: VerificationExpirySweepTask;
beforeEach(() => {
task = new VerificationExpirySweepTask();
});
const countEvents = (documentId: string) =>
Event.count({
where: {
name: "documents.verification_expired",
documentId,
},
});
it("emits an event for a document whose verification expired in the window", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
userId: user.id,
verifiedAt: subDays(new Date(), 30),
verifiedById: user.id,
verificationExpiresAt: subHours(new Date(), 12),
});
await task.perform(props);
expect(await countEvents(document.id)).toBe(1);
const event = await Event.findOne({
where: {
name: "documents.verification_expired",
documentId: document.id,
},
});
expect(event?.data?.expiresAt).toEqual(
document.verificationExpiresAt?.toISOString()
);
expect(event?.teamId).toEqual(team.id);
});
it("does not emit for documents outside the window", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const longExpired = await buildDocument({
teamId: team.id,
userId: user.id,
verifiedAt: subDays(new Date(), 60),
verifiedById: user.id,
verificationExpiresAt: subDays(new Date(), 10),
});
const notYetExpired = await buildDocument({
teamId: team.id,
userId: user.id,
verifiedAt: new Date(),
verifiedById: user.id,
verificationExpiresAt: subDays(new Date(), -10),
});
await task.perform(props);
expect(await countEvents(longExpired.id)).toBe(0);
expect(await countEvents(notYetExpired.id)).toBe(0);
});
it("does not emit for archived or deleted documents", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const archived = await buildDocument({
teamId: team.id,
userId: user.id,
verifiedAt: subDays(new Date(), 30),
verifiedById: user.id,
verificationExpiresAt: subHours(new Date(), 12),
archivedAt: new Date(),
});
const deleted = await buildDocument({
teamId: team.id,
userId: user.id,
verifiedAt: subDays(new Date(), 30),
verifiedById: user.id,
verificationExpiresAt: subHours(new Date(), 12),
deletedAt: new Date(),
});
await task.perform(props);
expect(await countEvents(archived.id)).toBe(0);
expect(await countEvents(deleted.id)).toBe(0);
});
it("is idempotent across repeated runs", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
userId: user.id,
verifiedAt: subDays(new Date(), 30),
verifiedById: user.id,
verificationExpiresAt: subHours(new Date(), 12),
});
await task.perform(props);
await task.perform(props);
expect(await countEvents(document.id)).toBe(1);
});
it("emits again when a re-verification produced a new deadline", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
userId: user.id,
verifiedAt: subDays(new Date(), 30),
verifiedById: user.id,
verificationExpiresAt: subHours(new Date(), 30),
});
await task.perform(props);
expect(await countEvents(document.id)).toBe(1);
// simulate a re-verification whose new deadline has also lapsed
await document.update({
verifiedAt: subHours(new Date(), 20),
verificationExpiresAt: subHours(new Date(), 2),
});
await task.perform(props);
expect(await countEvents(document.id)).toBe(2);
});
});
@@ -0,0 +1,82 @@
import { Day, Minute } from "@shared/utils/time";
import Logger from "@server/logging/Logger";
import { Document, Event } from "@server/models";
import { TaskPriority } from "./base/BaseTask";
import type { Props } from "./base/CronTask";
import { CronTask, TaskInterval } from "./base/CronTask";
/**
* Number of recent days to (re)scan on each run. Overlapping the previous
* run's window lets documents whose expiry was missed (worker downtime,
* skipped runs) still be picked up. Emission is idempotent per deadline.
*/
const RESCAN_DAYS = 2;
/**
* Finds documents whose verification deadline passed recently and emits a
* "documents.verification_expired" event for each. The task never mutates
* document rows – expiry is derived state, computed from the stored
* verificationExpiresAt deadline.
*/
export default class VerificationExpirySweepTask extends CronTask {
public async perform({ partition }: Props) {
const [startUuid, endUuid] = this.getPartitionBounds(partition);
const windowEnd = new Date();
const windowStart = new Date(windowEnd.getTime() - RESCAN_DAYS * Day.ms);
const documents = await Document.findExpiredVerifications({
windowStart,
windowEnd,
startUuid,
endUuid,
});
let emitted = 0;
for (const document of documents) {
if (!document.verificationExpiresAt) {
continue;
}
const expiresAt = document.verificationExpiresAt.toISOString();
// idempotency: re-verification produces a new deadline, so a latest
// event with a matching deadline means this expiry was already handled.
const existing = await Event.findLatest({
name: "documents.verification_expired",
documentId: document.id,
});
if (existing?.data?.expiresAt === expiresAt) {
continue;
}
await Event.create({
name: "documents.verification_expired",
documentId: document.id,
collectionId: document.collectionId,
teamId: document.teamId,
data: { expiresAt },
});
emitted++;
}
Logger.info("task", `Verification expiry sweep complete`, {
scanned: documents.length,
emitted,
});
}
public get cron() {
return {
interval: TaskInterval.Day,
partitionWindow: 30 * Minute.ms,
};
}
public get options() {
return {
attempts: 1,
priority: TaskPriority.Background,
};
}
}
@@ -1944,3 +1944,50 @@ describe("#collections.restore", () => {
expect(body.data.index).not.toBe("P");
});
});
describe("#collections.update verificationInterval", () => {
it("should not allow a non-admin to change the collection cadence", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({
teamId: team.id,
userId: user.id,
});
const res = await server.post("/api/collections.update", user, {
body: {
id: collection.id,
verificationInterval: 90,
},
});
expect(res.status).toEqual(403);
});
it("should allow an admin to set and clear the collection cadence", async () => {
const team = await buildTeam();
const admin = await buildAdmin({ teamId: team.id });
const collection = await buildCollection({
teamId: team.id,
userId: admin.id,
});
const res = await server.post("/api/collections.update", admin, {
body: {
id: collection.id,
verificationInterval: 90,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.verificationInterval).toEqual(90);
const cleared = await server.post("/api/collections.update", admin, {
body: {
id: collection.id,
verificationInterval: null,
},
});
const clearedBody = await cleared.json();
expect(cleared.status).toEqual(200);
expect(clearedBody.data.verificationInterval).toEqual(null);
});
});
+12 -1
View File
@@ -44,7 +44,7 @@ import { RateLimiterStrategy } from "@server/utils/RateLimiter";
import { collectionIndexing } from "@server/utils/indexing";
import pagination from "../middlewares/pagination";
import * as T from "./schema";
import { InvalidRequestError } from "@server/errors";
import { AuthorizationError, InvalidRequestError } from "@server/errors";
const router = new Router();
@@ -586,6 +586,7 @@ router.post(
sharing,
commenting,
templateManagement,
verificationInterval,
} = ctx.input.body;
const { user } = ctx.state.auth;
@@ -595,6 +596,12 @@ router.post(
});
authorize(user, "update", collection);
// the verification cadence is policy for every document in the
// collection, so changing it additionally requires team admin access.
if (verificationInterval !== undefined && !user.isAdmin) {
throw AuthorizationError();
}
// we're making this collection have no default access, ensure that the
// current user has an admin membership so that at least they can manage it.
if (
@@ -670,6 +677,10 @@ router.post(
collection.templateManagement = templateManagement;
}
if (verificationInterval !== undefined) {
collection.verificationInterval = verificationInterval;
}
await collection.saveWithCtx(ctx);
// must reload to update collection membership for correct policy calculation
+2
View File
@@ -199,6 +199,8 @@ export const CollectionsUpdateSchema = BaseSchema.extend({
templateManagement: z
.enum([CollectionPermission.Admin, CollectionPermission.ReadWrite])
.optional(),
/** Default re-verification cadence for documents in the collection, in days; null clears it */
verificationInterval: z.number().int().min(1).max(3650).nullish(),
}).refine(refineBodyContent, bodyContentError),
});
@@ -5911,3 +5911,392 @@ describe("#documents.documents", () => {
expect(body).toMatchSnapshot();
});
});
describe("#documents.verify", () => {
it("should require authentication", async () => {
const document = await buildDocument();
const res = await server.post("/api/documents.verify", {
body: {
id: document.id,
},
});
expect(res.status).toEqual(401);
});
it("should not allow a member with write access to verify", async () => {
const user = await buildUser();
const collection = await buildCollection({
teamId: user.teamId,
});
const document = await buildDocument({
teamId: user.teamId,
collectionId: collection.id,
});
const res = await server.post("/api/documents.verify", user, {
body: {
id: document.id,
},
});
expect(res.status).toEqual(403);
});
it("should allow a team admin to verify", async () => {
const admin = await buildAdmin();
const collection = await buildCollection({
teamId: admin.teamId,
});
const document = await buildDocument({
teamId: admin.teamId,
collectionId: collection.id,
});
const res = await server.post("/api/documents.verify", admin, {
body: {
id: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.verifiedAt).toBeTruthy();
expect(body.data.verifiedById).toEqual(admin.id);
expect(body.data.verificationExpiresAt).toEqual(null);
expect(body.data.editedSinceVerification).toEqual(false);
expect(body.policies[0].abilities.unverify).toEqual(true);
const event = await Event.findLatest({
name: "documents.verify",
documentId: document.id,
});
expect(event).toBeTruthy();
expect(event!.actorId).toEqual(admin.id);
});
it("should allow a member with document admin membership to verify", async () => {
const admin = await buildAdmin();
const user = await buildUser({ teamId: admin.teamId });
const collection = await buildCollection({
teamId: admin.teamId,
});
const document = await buildDocument({
teamId: admin.teamId,
collectionId: collection.id,
});
await UserMembership.create({
documentId: document.id,
userId: user.id,
permission: DocumentPermission.Admin,
createdById: admin.id,
});
const res = await server.post("/api/documents.verify", user, {
body: {
id: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.verifiedById).toEqual(user.id);
});
it("should compute the deadline from the collection default", async () => {
const admin = await buildAdmin();
const collection = await buildCollection({
teamId: admin.teamId,
verificationInterval: 90,
});
const document = await buildDocument({
teamId: admin.teamId,
collectionId: collection.id,
});
const res = await server.post("/api/documents.verify", admin, {
body: {
id: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.verificationExpiresAt).toBeTruthy();
expect(
new Date(body.data.verificationExpiresAt).getTime() -
new Date(body.data.verifiedAt).getTime()
).toEqual(90 * 24 * 60 * 60 * 1000);
});
it("should not allow verifying a draft", async () => {
const admin = await buildAdmin();
const document = await buildDraftDocument({
teamId: admin.teamId,
userId: admin.id,
});
const res = await server.post("/api/documents.verify", admin, {
body: {
id: document.id,
},
});
expect(res.status).toEqual(403);
});
it("should not allow verifying an archived document", async () => {
const admin = await buildAdmin();
const collection = await buildCollection({
teamId: admin.teamId,
});
const document = await buildDocument({
teamId: admin.teamId,
collectionId: collection.id,
archivedAt: new Date(),
});
const res = await server.post("/api/documents.verify", admin, {
body: {
id: document.id,
},
});
expect(res.status).toEqual(403);
});
});
describe("#documents.unverify", () => {
it("should clear the verification state", async () => {
const admin = await buildAdmin();
const collection = await buildCollection({
teamId: admin.teamId,
});
const document = await buildDocument({
teamId: admin.teamId,
collectionId: collection.id,
verifiedAt: new Date(),
verifiedById: admin.id,
verificationExpiresAt: subDays(new Date(), -30),
});
const res = await server.post("/api/documents.unverify", admin, {
body: {
id: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.verifiedAt).toEqual(null);
expect(body.data.verifiedById).toEqual(null);
expect(body.data.verificationExpiresAt).toEqual(null);
const event = await Event.findLatest({
name: "documents.unverify",
documentId: document.id,
});
expect(event).toBeTruthy();
});
it("should be a no-op for an unverified document", async () => {
const admin = await buildAdmin();
const collection = await buildCollection({
teamId: admin.teamId,
});
const document = await buildDocument({
teamId: admin.teamId,
collectionId: collection.id,
});
const res = await server.post("/api/documents.unverify", admin, {
body: {
id: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.verifiedAt).toEqual(null);
});
it("should not allow a member with write access to unverify", async () => {
const admin = await buildAdmin();
const user = await buildUser({ teamId: admin.teamId });
const collection = await buildCollection({
teamId: admin.teamId,
});
const document = await buildDocument({
teamId: admin.teamId,
collectionId: collection.id,
verifiedAt: new Date(),
verifiedById: admin.id,
});
const res = await server.post("/api/documents.unverify", user, {
body: {
id: document.id,
},
});
expect(res.status).toEqual(403);
});
});
describe("#documents.update verificationInterval", () => {
it("should not allow a member with write access to change the interval", async () => {
const user = await buildUser();
const collection = await buildCollection({
teamId: user.teamId,
});
const document = await buildDocument({
teamId: user.teamId,
collectionId: collection.id,
});
const res = await server.post("/api/documents.update", user, {
body: {
id: document.id,
verificationInterval: 30,
},
});
expect(res.status).toEqual(403);
// the same request without the field is permitted
const allowed = await server.post("/api/documents.update", user, {
body: {
id: document.id,
title: "Updated",
},
});
expect(allowed.status).toEqual(200);
});
it("should recompute the deadline of a verified document", async () => {
const admin = await buildAdmin();
const collection = await buildCollection({
teamId: admin.teamId,
});
const verifiedAt = subDays(new Date(), 10);
const document = await buildDocument({
teamId: admin.teamId,
collectionId: collection.id,
verifiedAt,
verifiedById: admin.id,
});
const res = await server.post("/api/documents.update", admin, {
body: {
id: document.id,
verificationInterval: 30,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.verificationInterval).toEqual(30);
expect(new Date(body.data.verificationExpiresAt)).toEqual(
new Date(verifiedAt.getTime() + 30 * 24 * 60 * 60 * 1000)
);
// a cadence change is not a content edit
expect(body.data.updatedAt).toEqual(document.updatedAt.toISOString());
});
it("should fall back through the chain when the override is cleared", async () => {
const admin = await buildAdmin();
const collection = await buildCollection({
teamId: admin.teamId,
verificationInterval: 90,
});
const verifiedAt = subDays(new Date(), 10);
const document = await buildDocument({
teamId: admin.teamId,
collectionId: collection.id,
verifiedAt,
verifiedById: admin.id,
verificationInterval: 30,
verificationExpiresAt: new Date(
verifiedAt.getTime() + 30 * 24 * 60 * 60 * 1000
),
});
const res = await server.post("/api/documents.update", admin, {
body: {
id: document.id,
verificationInterval: null,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.verificationInterval).toEqual(null);
expect(new Date(body.data.verificationExpiresAt)).toEqual(
new Date(verifiedAt.getTime() + 90 * 24 * 60 * 60 * 1000)
);
});
});
describe("#documents.list verificationStatus", () => {
const buildVerificationFixtures = async () => {
const user = await buildUser();
const collection = await buildCollection({
teamId: user.teamId,
userId: user.id,
});
const unverified = await buildDocument({
teamId: user.teamId,
userId: user.id,
collectionId: collection.id,
});
const verified = await buildDocument({
teamId: user.teamId,
userId: user.id,
collectionId: collection.id,
verifiedAt: new Date(),
verifiedById: user.id,
});
const expired = await buildDocument({
teamId: user.teamId,
userId: user.id,
collectionId: collection.id,
verifiedAt: subDays(new Date(), 30),
verifiedById: user.id,
verificationExpiresAt: subDays(new Date(), 1),
});
const expiring = await buildDocument({
teamId: user.teamId,
userId: user.id,
collectionId: collection.id,
verifiedAt: new Date(),
verifiedById: user.id,
verificationExpiresAt: subDays(new Date(), -7),
});
return { user, unverified, verified, expired, expiring };
};
it("should filter to verified documents", async () => {
const { user, verified, expiring } = await buildVerificationFixtures();
const res = await server.post("/api/documents.list", user, {
body: {
verificationStatus: "verified",
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.map((d: { id: string }) => d.id).sort()).toEqual(
[verified.id, expiring.id].sort()
);
});
it("should filter to unverified documents", async () => {
const { user, unverified } = await buildVerificationFixtures();
const res = await server.post("/api/documents.list", user, {
body: {
verificationStatus: "unverified",
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.map((d: { id: string }) => d.id)).toEqual([unverified.id]);
});
it("should filter to expired documents", async () => {
const { user, expired } = await buildVerificationFixtures();
const res = await server.post("/api/documents.list", user, {
body: {
verificationStatus: "expired",
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.map((d: { id: string }) => d.id)).toEqual([expired.id]);
});
it("should filter to documents expiring soon", async () => {
const { user, expiring } = await buildVerificationFixtures();
const res = await server.post("/api/documents.list", user, {
body: {
verificationStatus: "expiring",
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.map((d: { id: string }) => d.id)).toEqual([expiring.id]);
});
});
+88
View File
@@ -18,6 +18,7 @@ import {
FileOperationType,
StatusFilter,
UserRole,
VerificationStatusFilter,
} from "@shared/types";
import { subtractDate } from "@shared/utils/date";
import slugify from "@shared/utils/slugify";
@@ -113,6 +114,7 @@ router.post(
parentDocumentId,
userId: createdById,
statusFilter,
verificationStatus,
} = ctx.input.body;
const { offset, limit } = ctx.state.pagination;
@@ -292,6 +294,36 @@ router.post(
});
}
if (verificationStatus) {
const now = new Date();
switch (verificationStatus) {
case VerificationStatusFilter.Verified:
where[Op.and].push({
verifiedAt: { [Op.ne]: null },
[Op.or]: [
{ verificationExpiresAt: { [Op.is]: null } },
{ verificationExpiresAt: { [Op.gte]: now } },
],
});
break;
case VerificationStatusFilter.Unverified:
where[Op.and].push({ verifiedAt: { [Op.is]: null } });
break;
case VerificationStatusFilter.Expired:
where[Op.and].push({ verificationExpiresAt: { [Op.lt]: now } });
break;
case VerificationStatusFilter.Expiring:
where[Op.and].push({
verificationExpiresAt: {
[Op.gte]: now,
[Op.lt]: new Date(now.getTime() + 14 * Day.ms),
},
});
break;
}
}
// When sorting by index, use array_position to sort by the document order
// in the collection structure directly in SQL, enabling correct pagination
const orderClause =
@@ -1273,6 +1305,10 @@ router.post(
authorize(user, "updateInsights", document);
}
if (input.verificationInterval !== undefined) {
authorize(user, "verify", document);
}
if (publish) {
await authorizeDocumentPublish(ctx, document, collectionId);
}
@@ -1432,6 +1468,58 @@ router.post(
}
);
router.post(
"documents.verify",
auth(),
validate(T.DocumentsVerifySchema),
transaction(),
async (ctx: APIContext<T.DocumentsVerifyReq>) => {
const { id } = ctx.input.body;
const { user } = ctx.state.auth;
const { transaction } = ctx.state;
const document = await Document.findByPk(id, {
userId: user.id,
rejectOnEmpty: true,
transaction,
});
authorize(user, "verify", document);
await document.verifyWithCtx(ctx);
ctx.body = {
data: await presentDocument(ctx, document),
policies: presentPolicies(user, [document]),
};
}
);
router.post(
"documents.unverify",
auth(),
validate(T.DocumentsUnverifySchema),
transaction(),
async (ctx: APIContext<T.DocumentsUnverifyReq>) => {
const { id } = ctx.input.body;
const { user } = ctx.state.auth;
const { transaction } = ctx.state;
const document = await Document.findByPk(id, {
userId: user.id,
rejectOnEmpty: true,
transaction,
});
authorize(user, "unverify", document);
await document.unverifyWithCtx(ctx);
ctx.body = {
data: await presentDocument(ctx, document),
policies: presentPolicies(user, [document]),
};
}
);
router.post(
"documents.delete",
auth(),
+19
View File
@@ -7,6 +7,7 @@ import {
StatusFilter,
TextEditMode,
SortFilter,
VerificationStatusFilter,
} from "@shared/types";
import { BaseSchema } from "@server/routes/api/schema";
import { zodIconType, zodIdType, zodShareIdType } from "@server/utils/zod";
@@ -97,6 +98,9 @@ export const DocumentsListSchema = BaseSchema.extend({
/** Document statuses to include in results */
statusFilter: z.enum(StatusFilter).array().optional(),
/** Verification state to filter results by */
verificationStatus: z.enum(VerificationStatusFilter).optional(),
}),
// Maintains backwards compatibility
}).transform((req) => {
@@ -281,6 +285,9 @@ export const DocumentsUpdateSchema = BaseSchema.extend({
/** Boolean to denote if insights should be visible on the doc */
insightsEnabled: z.boolean().optional(),
/** Re-verification cadence override in days; null clears the override */
verificationInterval: z.number().int().min(1).max(3650).nullish(),
/** Boolean to denote if the doc should be published */
publish: z.boolean().optional(),
@@ -388,6 +395,18 @@ export const DocumentsUnpublishSchema = BaseSchema.extend({
export type DocumentsUnpublishReq = z.infer<typeof DocumentsUnpublishSchema>;
export const DocumentsVerifySchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type DocumentsVerifyReq = z.infer<typeof DocumentsVerifySchema>;
export const DocumentsUnverifySchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type DocumentsUnverifyReq = z.infer<typeof DocumentsUnverifySchema>;
export const DocumentsImportSchema = BaseSchema.extend({
body: z
.object({
+2
View File
@@ -75,6 +75,8 @@ export const TeamsUpdateSchema = BaseSchema.extend({
mcp: z.boolean().optional(),
/** List of disabled embed provider titles. */
disabledEmbeds: z.array(z.string()).optional(),
/** Default re-verification cadence for documents, in days; null clears it. */
verificationInterval: z.number().int().min(1).max(3650).nullish(),
})
.optional(),
}),
+16
View File
@@ -233,6 +233,22 @@ export type DocumentEvent = BaseEvent<Document> &
documentId: string;
collectionId: string;
}
| {
name: "documents.verify" | "documents.unverify";
documentId: string;
collectionId?: string;
data?: {
expiresAt: string | null;
};
}
| {
name: "documents.verification_expired";
documentId: string;
collectionId?: string;
data: {
expiresAt: string;
};
}
| {
name:
| "documents.update"
+12
View File
@@ -21,6 +21,13 @@ export enum StatusFilter {
Draft = "draft",
}
export enum VerificationStatusFilter {
Verified = "verified",
Unverified = "unverified",
Expired = "expired",
Expiring = "expiring",
}
export enum SortFilter {
CreatedAt = "createdAt",
UpdatedAt = "updatedAt",
@@ -443,6 +450,8 @@ export enum TeamPreference {
MCP = "mcp",
/** List of disabled embed provider titles. */
DisabledEmbeds = "disabledEmbeds",
/** Default re-verification cadence for documents, in days. */
VerificationInterval = "verificationInterval",
}
export type TeamPreferences = {
@@ -460,6 +469,7 @@ export type TeamPreferences = {
[TeamPreference.EmailDisplay]?: EmailDisplay;
[TeamPreference.MCP]?: boolean;
[TeamPreference.DisabledEmbeds]?: string[];
[TeamPreference.VerificationInterval]?: number | null;
};
export enum NavigationNodeType {
@@ -512,6 +522,7 @@ export enum NotificationEventType {
Features = "emails.features",
ExportCompleted = "emails.export_completed",
RequestDocumentAccess = "access_requests.create",
VerificationExpired = "documents.verification_expired",
}
export enum NotificationChannelType {
@@ -552,6 +563,7 @@ export const NotificationEventDefaults: Record<NotificationEventType, boolean> =
[NotificationEventType.AddUserToDocument]: true,
[NotificationEventType.AddUserToCollection]: true,
[NotificationEventType.RequestDocumentAccess]: true,
[NotificationEventType.VerificationExpired]: true,
};
export enum UnfurlResourceType {