feat: Document verification and freshness tracking

Adds a verification lifecycle to documents, rebuilt on top of the new
main history. 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
- the feature requires the new DocumentVerification plan entitlement,
  included in the Business and Enterprise plans, and remains limited to
  cloud hosting
- 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
- 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; the
  interval override is carried over when duplicating

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-11-21 17:34:44 +00:00
1 parent ee3c88bc14
commit f5acd9c72b
31 files changed
+1527 -1

No files matched your search

+4
View File
@@ -56,6 +56,7 @@ class Notification extends Model {
NotificationEventType.CreateRevision,
NotificationEventType.AddUserToDocument,
NotificationEventType.RequestDocumentAccess,
NotificationEventType.VerificationExpired,
],
collections: [
NotificationEventType.CreateCollection,
@@ -349,6 +350,9 @@ class Notification extends Model {
? settingsPath("groups", this.groupId, "members")
: "";
}
case NotificationEventType.VerificationExpired: {
return this.document?.path;
}
default:
this.event satisfies never;
return;
@@ -208,6 +208,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
@@ -25,6 +25,7 @@ type Props = Optional<
| "apiImportId"
| "fullWidth"
| "preferences"
| "verificationInterval"
| "sourceMetadata"
| "editorVersion"
| "publishedAt"
@@ -174,6 +175,7 @@ export default async function documentCreator(
template,
fullWidth,
preferences,
verificationInterval,
importId,
apiImportId,
createdAt,
@@ -248,6 +250,7 @@ export default async function documentCreator(
sourceMetadata,
fullWidth: fullWidth ?? template?.fullWidth,
preferences,
verificationInterval,
icon: icon ?? template?.icon,
color: color ?? template?.color,
title: titleWithReplacements,
@@ -35,6 +35,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({
+1
View File
@@ -217,6 +217,7 @@ async function duplicateRoots(
color: original.color,
fullWidth: original.fullWidth,
preferences: original.preferences,
verificationInterval: original.verificationInterval,
title: item.title,
content: ProsemirrorHelper.replaceDocumentReferences(
ProsemirrorHelper.removeMarks(DocumentHelper.toProsemirror(original), [
+29
View File
@@ -1,4 +1,5 @@
import type { DocumentPreferences, TextEditMode } from "@shared/types";
import { Day } from "@shared/utils/time";
import { DocumentConflictError, ValidationError } from "@server/errors";
import { Document } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
@@ -26,6 +27,8 @@ type Props = {
preferences?: DocumentPreferences | null;
/** 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 document revision the changes are based on, the update is rejected if it no longer matches */
@@ -60,6 +63,7 @@ export default async function documentUpdater(
fullWidth,
preferences,
insightsEnabled,
verificationInterval,
editMode,
findText,
lastRevision,
@@ -87,6 +91,21 @@ export default async function documentUpdater(
...preferences,
};
}
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,
@@ -135,6 +154,12 @@ export default async function documentUpdater(
}
const changed = document.changed();
const verificationOnly =
!!changed &&
changed.every(
(attr) =>
attr === "verificationInterval" || attr === "verificationExpiresAt"
);
const { collection } = document;
if (publish && cId) {
@@ -142,6 +167,10 @@ export default async function documentUpdater(
document.collectionId = cId;
}
await document.publish(ctx, { collectionId: cId });
} 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 });
} 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.displayTitle,
});
}
protected preview({ document }: Props): string {
return this.t("“{{ documentTitle }}” is due to be reviewed again", {
documentTitle: document.displayTitle,
});
}
protected renderAsText({ teamUrl, document }: Props): string {
return `
${this.t("Your verification of “{{ documentTitle }}” has expired", { documentTitle: document.displayTitle })}
${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.displayTitle,
})}
</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
@@ -322,6 +322,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
@@ -1172,3 +1172,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("#verify", () => {
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.verify(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.verify(ctx));
expect(document.verifiedAt).toBeTruthy();
expect(document.verificationExpiresAt).toEqual(null);
});
});
describe("#unverify", () => {
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.verify(ctx));
await withAPIContext(user, (ctx) => document.unverify(ctx));
expect(document.verifiedAt).toEqual(null);
expect(document.verifiedById).toEqual(null);
expect(document.verificationExpiresAt).toEqual(null);
expect(document.verificationInterval).toEqual(90);
});
});
});
+167
View File
@@ -51,7 +51,9 @@ import type {
ProsemirrorData,
SourceMetadata,
} from "@shared/types";
import { TeamPreference } from "@shared/types";
import { DocumentPreferenceDefaults } from "@shared/constants";
import { Day } from "@shared/utils/time";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import { UrlHelper } from "@shared/utils/UrlHelper";
import slugify from "@server/utils/slugify";
@@ -460,6 +462,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[];
@@ -713,6 +733,15 @@ class Document extends ArchivableModel<
@Column(DataType.UUID)
createdById: string;
@BelongsTo(() => User, "verifiedById")
verifiedBy: User | null;
/** The user that last verified this document as accurate, if any. */
@AllowNull
@ForeignKey(() => User)
@Column(DataType.UUID)
verifiedById: string | null;
@BelongsTo(() => User, "deletedById")
deletedBy: User | null;
@@ -1073,6 +1102,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
/**
@@ -1465,6 +1543,95 @@ class Document extends ArchivableModel<
});
};
/**
* 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.
*/
verify = 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.
*/
unverify = 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) => {
+19
View File
@@ -2,12 +2,14 @@ import invariant from "invariant";
import {
CommentingAccess,
DocumentPermission,
PlanFeature,
TeamPreference,
} from "@shared/types";
import { Document, Revision, User, Team } from "@server/models";
import { allow, cannot, can } from "./cancan";
import {
and,
isCloudHosted,
isCollectionOwner,
isCollectionWritable,
isCommentingEnabled,
@@ -15,6 +17,7 @@ import {
isTeamModel,
isTeamMutable,
or,
teamHasEntitlement,
} from "./utils";
allow(User, "createDocument", Team, (actor, document) =>
@@ -118,6 +121,22 @@ allow(User, "publish", Document, (actor, document) =>
)
);
allow(User, ["verify", "unverify"], Document, (actor, document) =>
and(
isCloudHosted(),
teamHasEntitlement(actor.team, PlanFeature.DocumentVerification),
isTeamMutable(actor),
can(actor, "read", document),
!!document?.publishedAt,
!document?.template,
!!document?.isActive,
or(
includesMembership(document, [DocumentPermission.Admin]),
and(!document?.collection?.isPersonal, isTeamAdmin(actor, document))
)
)
);
allow(User, "manageUsers", Document, (actor, document) =>
and(
isTeamMutable(actor),
+1
View File
@@ -63,6 +63,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.ownerId = collection.ownerId;
res.deletedAt = collection.deletedAt;
+4
View File
@@ -125,6 +125,10 @@ 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;
if (document.deletedById) {
const deletedBy =
document.deletedBy ??
@@ -6,6 +6,7 @@ import CommentCreatedEmail from "@server/emails/templates/CommentCreatedEmail";
import CommentMentionedEmail from "@server/emails/templates/CommentMentionedEmail";
import CommentResolvedEmail from "@server/emails/templates/CommentResolvedEmail";
import DocumentAccessRequestEmail from "@server/emails/templates/DocumentAccessRequestEmail";
import DocumentVerificationExpiredEmail from "@server/emails/templates/DocumentVerificationExpiredEmail";
import DocumentMentionedEmail from "@server/emails/templates/DocumentMentionedEmail";
import DocumentPublishedOrUpdatedEmail from "@server/emails/templates/DocumentPublishedOrUpdatedEmail";
import DocumentSharedEmail from "@server/emails/templates/DocumentSharedEmail";
@@ -269,6 +270,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;
}
}
}
}
@@ -21,6 +21,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 GroupUserNotificationsTask from "../tasks/GroupUserNotificationsTask";
import RevisionCreatedNotificationsTask from "../tasks/RevisionCreatedNotificationsTask";
import ShareSubscriptionNotificationsTask from "../tasks/ShareSubscriptionNotificationsTask";
@@ -31,6 +32,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",
@@ -51,6 +53,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":
@@ -101,6 +105,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 Promise.all([
new RevisionCreatedNotificationsTask().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,
};
}
}
@@ -3060,3 +3060,50 @@ describe("personal collection lists", () => {
expect(body.data.ownerId).toBeNull();
});
});
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);
});
});
+9 -1
View File
@@ -52,7 +52,7 @@ import { collectionIndexing } from "@server/utils/indexing";
import { QueryHelper } from "@server/storage/QueryHelper";
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();
@@ -612,6 +612,7 @@ router.post(
sharing,
commenting,
templateManagement,
verificationInterval,
deprecatedReason,
} = ctx.input.body;
@@ -633,6 +634,12 @@ router.post(
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();
}
if (deprecatedReason !== undefined) {
authorize(user, "updateDeprecatedReason", collection);
await collection.updateDeprecatedReason(ctx, deprecatedReason);
@@ -682,6 +689,7 @@ router.post(
sort,
commenting,
templateManagement,
verificationInterval,
});
const privacyChanged = collection.changed("permission");
+2
View File
@@ -216,6 +216,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),
});
@@ -9,6 +9,7 @@ import {
ExportContentType,
FileOperationFormat,
HeadingPrefixStyle,
Plan,
StatusFilter,
TeamPreference,
UserRole,
@@ -30,6 +31,7 @@ import {
GroupMembership,
Relationship,
Share,
Team,
} from "@server/models";
import { RelationshipType } from "@server/models/Relationship";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
@@ -53,6 +55,7 @@ import {
import {
getTestServer,
readZipResponse,
setSelfHosted,
withAPIContext,
} from "@server/test/support";
@@ -9880,3 +9883,364 @@ describe("#documents.documents", () => {
expect(body).toMatchSnapshot();
});
});
describe("#documents.verify", () => {
beforeEach(() => {
vi.spyOn(Team.prototype, "plan", "get").mockReturnValue(Plan.Business);
});
afterEach(() => {
vi.restoreAllMocks();
});
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 require a plan entitled to document verification", async () => {
vi.restoreAllMocks();
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,
},
});
expect(res.status).toEqual(403);
});
it("should not allow verifying on self-hosted installations", async () => {
setSelfHosted();
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,
},
});
expect(res.status).toEqual(403);
});
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.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", () => {
beforeEach(() => {
vi.spyOn(Team.prototype, "plan", "get").mockReturnValue(Plan.Business);
});
afterEach(() => {
vi.restoreAllMocks();
});
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", () => {
beforeEach(() => {
vi.spyOn(Team.prototype, "plan", "get").mockReturnValue(Plan.Business);
});
afterEach(() => {
vi.restoreAllMocks();
});
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)
);
});
});
+58
View File
@@ -1473,6 +1473,10 @@ router.post(
authorize(user, "updateInsights", document);
}
if (input.verificationInterval !== undefined) {
authorize(user, "verify", document);
}
if (publish) {
await authorizeDocumentPublish(ctx, document, collectionId);
}
@@ -1666,6 +1670,60 @@ router.post(
}
);
router.post(
"documents.verify",
auth(),
rateLimiter(RateLimiterStrategy.OneHundredPerMinute),
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.verify(ctx);
ctx.body = {
data: await presentDocument(ctx, document),
policies: presentPolicies(user, [document]),
};
}
);
router.post(
"documents.unverify",
auth(),
rateLimiter(RateLimiterStrategy.OneHundredPerMinute),
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.unverify(ctx);
ctx.body = {
data: await presentDocument(ctx, document),
policies: presentPolicies(user, [document]),
};
}
);
router.post(
"documents.delete",
auth(),
+15
View File
@@ -427,6 +427,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(),
@@ -535,6 +538,18 @@ export const DocumentsDeleteSchema = BaseSchema.extend({
export type DocumentsDeleteReq = z.infer<typeof DocumentsDeleteSchema>;
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 DocumentsUnpublishSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Whether to detach the document from the collection */
+7
View File
@@ -89,6 +89,13 @@ export const TeamsUpdateSchema = BaseSchema.extend({
error: "must be one of the available expiry periods",
}
),
/** Default re-verification cadence for documents, in days; null clears it. */
[TeamPreference.VerificationInterval]: z
.number()
.int()
.min(1)
.max(3650)
.nullable(),
})
.partial()
.optional(),
+16
View File
@@ -243,6 +243,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"
+2
View File
@@ -25,6 +25,7 @@ export enum NotificationEventType {
Features = "emails.features",
ExportCompleted = "emails.export_completed",
RequestDocumentAccess = "access_requests.create",
VerificationExpired = "documents.verification_expired",
}
/** Channels that a notification can be delivered through. */
@@ -71,6 +72,7 @@ export const NotificationEventDefaults: Record<NotificationEventType, boolean> =
[NotificationEventType.AddUserToGroup]: true,
[NotificationEventType.RemoveUserFromGroup]: true,
[NotificationEventType.RequestDocumentAccess]: true,
[NotificationEventType.VerificationExpired]: true,
};
/** Notices shown to the user from the `notice` query parameter. */
+2
View File
@@ -34,4 +34,6 @@ export enum PlanFeature {
SAML = "saml",
/** Structured data attributes on documents. */
DataAttributes = "dataAttributes",
/** Verification of document accuracy with re-verification cadences. */
DocumentVerification = "documentVerification",
}
+3
View File
@@ -69,6 +69,8 @@ export enum TeamPreference {
PersonalDocs = "personalDocs",
/** The number of days until new public share links expire, 0 for no expiry. */
DefaultShareExpiryDays = "defaultShareExpiryDays",
/** Default re-verification cadence for documents, in days. */
VerificationInterval = "verificationInterval",
}
/** Workspace preference values, keyed by preference. */
@@ -89,4 +91,5 @@ export type TeamPreferences = {
[TeamPreference.DisabledEmbeds]?: string[];
[TeamPreference.PersonalDocs]?: boolean;
[TeamPreference.DefaultShareExpiryDays]?: number;
[TeamPreference.VerificationInterval]?: number | null;
};