diff --git a/app/components/Notifications/AccessRequestActions.tsx b/app/components/Notifications/AccessRequestActions.tsx new file mode 100644 index 0000000000..cb694cb39d --- /dev/null +++ b/app/components/Notifications/AccessRequestActions.tsx @@ -0,0 +1,121 @@ +import { observer } from "mobx-react"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import styled from "styled-components"; +import { DocumentPermission } from "@shared/types"; +import type Notification from "~/models/Notification"; +import { client } from "~/utils/ApiClient"; +import Button from "../Button"; +import Flex from "../Flex"; +import { SplitButton } from "../primitives/SplitButton"; + +type Props = { + notification: Notification; +}; + +function AccessRequestActions({ notification }: Props) { + const { t } = useTranslation(); + const [processing, setProcessing] = React.useState(false); + const [selectedPermission, setSelectedPermission] = + React.useState(DocumentPermission.Read); + + const permissionOptions = React.useMemo( + () => [ + { + label: t("View only"), + value: DocumentPermission.Read, + description: t("Can view the document"), + }, + { + label: t("Can edit"), + value: DocumentPermission.ReadWrite, + description: t("Can view and edit the document"), + }, + { + label: t("Manage"), + value: DocumentPermission.Admin, + description: t("Full access including sharing"), + }, + ], + [t] + ); + + const selectedLabel = permissionOptions.find( + (o) => o.value === selectedPermission + )?.label; + + const handleApprove = React.useCallback(async () => { + if (!notification.actor || processing) { + return; + } + + setProcessing(true); + try { + await client.post("/accessRequests.approve", { + id: notification.accessRequestId, + permission: selectedPermission, + }); + notification.accessRequestStatus = "approved"; + toast.success( + t(`Permissions for {{ userName }} updated`, { + userName: notification.actor?.name, + }) + ); + void notification.markAsRead(); + } catch { + toast.error(t("Failed to approve access request")); + } finally { + setProcessing(false); + } + }, [notification, processing, selectedPermission, t]); + + const handleDismiss = React.useCallback(async () => { + if (processing) { + return; + } + + setProcessing(true); + try { + await client.post("/accessRequests.dismiss", { + id: notification.accessRequestId, + }); + notification.accessRequestStatus = "dismissed"; + toast.success(t("Access request dismissed")); + void notification.markAsRead(); + } catch { + toast.error(t("Failed to dismiss access request")); + } finally { + setProcessing(false); + } + }, [notification, processing, t]); + + const handleContainerClick = React.useCallback((e: React.MouseEvent) => { + e.preventDefault(); + e.stopPropagation(); + }, []); + + return ( + + + setSelectedPermission(value as DocumentPermission)} + onClick={handleApprove} + disabled={processing} + > + {t("Approve")} · {selectedLabel} + + + ); +} + +const Container = styled(Flex)` + margin-top: 8px; + flex-wrap: wrap; +`; + +export default observer(AccessRequestActions); diff --git a/app/components/Notifications/NotificationListItem.tsx b/app/components/Notifications/NotificationListItem.tsx index 2fcf91affe..0aea0a5034 100644 --- a/app/components/Notifications/NotificationListItem.tsx +++ b/app/components/Notifications/NotificationListItem.tsx @@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; import styled from "styled-components"; import { s, hover, truncateMultiline } from "@shared/styles"; +import { NotificationEventType } from "@shared/types"; import type Notification from "~/models/Notification"; import useStores from "~/hooks/useStores"; import { Avatar, AvatarSize, AvatarVariant } from "../Avatar"; @@ -21,6 +22,7 @@ import { notificationArchive, } from "~/actions/definitions/notifications"; import { NotificationSection } from "~/actions/sections"; +import AccessRequestActions from "./AccessRequestActions"; const CommentEditor = lazyWithRetry( () => import("~/scenes/Document/components/Comments/CommentEditor") @@ -37,6 +39,10 @@ function NotificationListItem({ notification, onNavigate }: Props) { const collectionId = notification.document?.collectionId; const collection = collectionId ? collections.get(collectionId) : undefined; + const isAccessRequestPending = + notification.event === NotificationEventType.RequestDocumentAccess && + notification.accessRequestStatus === "pending"; + const handleClick: React.MouseEventHandler = (event) => { if (event.altKey) { event.preventDefault(); @@ -86,6 +92,9 @@ function NotificationListItem({ notification, onNavigate }: Props) { defaultValue={toJS(notification.comment.data)} /> )} + {isAccessRequestPending && ( + + )} {notification.viewedAt ? null : } @@ -122,6 +131,7 @@ const Container = styled(Flex)<{ $unread: boolean }>` border-radius: 4px; ${StyledLink}[data-state=open] &, + &:has([data-state="open"]), &:${hover}, &:active { background: ${s("listItemHoverBackground")}; diff --git a/app/components/Notifications/NotificationsPopover.tsx b/app/components/Notifications/NotificationsPopover.tsx index da0ea18a9f..a322e5b570 100644 --- a/app/components/Notifications/NotificationsPopover.tsx +++ b/app/components/Notifications/NotificationsPopover.tsx @@ -12,6 +12,7 @@ import { PopoverTrigger, PopoverContent, } from "~/components/primitives/Popover"; +import useConsumeQueryParam from "~/hooks/useConsumeQueryParam"; import useMobile from "~/hooks/useMobile"; import useStores from "~/hooks/useStores"; import Notifications from "./Notifications"; @@ -23,7 +24,8 @@ type Props = { const NotificationsPopover: React.FC = ({ children }: Props) => { const { t } = useTranslation(); const { notifications } = useStores(); - const [open, setOpen] = useState(false); + const shouldOpen = useConsumeQueryParam("notifications") === "true"; + const [open, setOpen] = useState(shouldOpen); const isMobile = useMobile(); const scrollableRef = useRef(null); const drawerContentRef = useRef>(null); diff --git a/app/components/primitives/SplitButton.tsx b/app/components/primitives/SplitButton.tsx new file mode 100644 index 0000000000..e515f4fbca --- /dev/null +++ b/app/components/primitives/SplitButton.tsx @@ -0,0 +1,288 @@ +import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; +import { CheckmarkIcon, ExpandedIcon } from "outline-icons"; +import { darken, transparentize } from "polished"; +import * as React from "react"; +import styled, { css } from "styled-components"; +import { s } from "@shared/styles"; +import { fadeAndScaleIn } from "~/styles/animations"; +import { undraggableOnDesktop } from "~/styles"; + +interface Option { + /** Display label for the option. */ + label: string; + /** Value for the option. */ + value: string; + /** Optional description shown below the label. */ + description?: string; +} + +interface SplitButtonProps { + /** The options available in the dropdown. */ + options: Option[]; + /** The currently selected option value. */ + selectedValue: string; + /** Called when a dropdown option is selected. */ + onSelect: (value: string) => void; + /** Called when the main button area is clicked. */ + onClick: (event: React.MouseEvent) => void; + /** Whether the button is disabled. */ + disabled?: boolean; + /** Use the neutral color variant instead of accent. */ + neutral?: boolean; + children: React.ReactNode; +} + +/** + * A split button with a main action and a dropdown disclosure for selecting + * from a set of options. Built on Radix UI DropdownMenu. + */ +export function SplitButton({ + options, + selectedValue, + onSelect, + onClick, + disabled, + neutral, + children, +}: SplitButtonProps) { + const selectedOption = options.find((o) => o.value === selectedValue); + const containerRef = React.useRef(null); + const triggerRef = React.useRef(null); + const [alignOffset, setAlignOffset] = React.useState(0); + + const handleOpenChange = React.useCallback((open: boolean) => { + if (!open || !containerRef.current || !triggerRef.current) { + return; + } + const containerLeft = containerRef.current.getBoundingClientRect().left; + const triggerLeft = triggerRef.current.getBoundingClientRect().left; + setAlignOffset(containerLeft - triggerLeft); + }, []); + + return ( + + + + {children} + + + + + + + + + + + + e.stopPropagation()}> + {options.map((option) => ( + onSelect(option.value)} + > + + + {option.label} + {option.description && ( + + {option.description} + + )} + + + {option.value === selectedValue && ( + + )} + + + + ))} + + + + + ); +} + +const accentStyles = css` + background: ${s("accent")}; + color: ${s("accentText")}; + box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 2px; +`; + +const neutralStyles = css` + background: inherit; + color: ${(props) => props.theme.buttonNeutralText}; + box-shadow: + rgba(0, 0, 0, 0.07) 0px 1px 2px, + ${(props) => props.theme.buttonNeutralBorder} 0 0 0 1px inset; +`; + +const Container = styled.span<{ $neutral?: boolean; $disabled?: boolean }>` + display: inline-flex; + align-items: stretch; + border-radius: 6px; + height: 32px; + font-size: 14px; + font-weight: 500; + flex-shrink: 0; + ${undraggableOnDesktop()} + ${(props) => (props.$neutral ? neutralStyles : accentStyles)} + + ${(props) => + props.$disabled && + ` + cursor: default; + pointer-events: none; + opacity: 0.7; + `} +`; + +const buttonReset = css` + margin: 0; + padding: 0; + border: 0; + background: none; + color: inherit; + font: inherit; + cursor: var(--pointer); + appearance: none; + + &:disabled { + cursor: default; + pointer-events: none; + } +`; + +const MainButton = styled.button<{ $neutral?: boolean }>` + ${buttonReset} + display: flex; + align-items: center; + padding: 0 8px; + border-radius: 6px 0 0 6px; + white-space: nowrap; + transition: background 200ms ease-out; + + &:hover:not(:disabled) { + background: ${(props) => + props.$neutral + ? darken(0.05, props.theme.buttonNeutralBackground) + : "rgba(0, 0, 0, 0.1)"}; + transition: background 0s; + } +`; + +const DisclosureButton = styled.button<{ $neutral?: boolean }>` + ${buttonReset} + display: flex; + align-items: center; + justify-content: center; + padding: 0 4px; + border-radius: 0 6px 6px 0; + transition: background 200ms ease-out; + + &:hover:not(:disabled), + &[data-state="open"] { + background: ${(props) => + props.$neutral + ? darken(0.05, props.theme.buttonNeutralBackground) + : "rgba(0, 0, 0, 0.1)"}; + transition: background 0s; + } +`; + +const Divider = styled.span<{ $neutral?: boolean }>` + width: 1px; + align-self: stretch; + margin: 6px 0; + background: ${(props) => + props.$neutral + ? transparentize(0.7, props.theme.buttonNeutralText) + : "rgba(255, 255, 255, 0.3)"}; +`; + +const StyledExpandedIcon = styled(ExpandedIcon)` + opacity: 0.8; +`; + +const MenuContent = styled.div` + z-index: 4000; + min-width: 180px; + max-width: 276px; + background: ${s("menuBackground")}; + box-shadow: ${s("menuShadow")}; + border-radius: 6px; + padding: 6px; + outline: none; + + transform-origin: var(--radix-dropdown-menu-content-transform-origin); + &[data-state="open"] { + animation: ${fadeAndScaleIn} 150ms ease-out; + } +`; + +const MenuItem = styled.button` + ${buttonReset} + position: relative; + display: flex; + align-items: center; + width: 100%; + min-height: 32px; + font-size: 14px; + color: ${s("textSecondary")}; + border-radius: 4px; + padding: 4px 12px; + gap: 8px; + user-select: none; + + &[data-highlighted] { + color: ${s("accentText")}; + background: ${s("accent")}; + outline: none; + } +`; + +const MenuItemContent = styled.div` + display: flex; + flex-direction: column; + flex-grow: 1; + text-align: left; +`; + +const MenuItemLabel = styled.span` + font-weight: 500; +`; + +const MenuItemDescription = styled.span` + font-size: 12px; + opacity: 0.75; + margin-top: 1px; +`; + +const CheckmarkWrapper = styled.span` + width: 18px; + height: 18px; + flex-shrink: 0; + display: flex; + align-items: center; + justify-content: center; +`; diff --git a/app/hooks/useConsumeQueryParam.ts b/app/hooks/useConsumeQueryParam.ts new file mode 100644 index 0000000000..21397dffda --- /dev/null +++ b/app/hooks/useConsumeQueryParam.ts @@ -0,0 +1,34 @@ +import { useEffect, useRef } from "react"; +import { useHistory } from "react-router-dom"; +import useQuery from "./useQuery"; + +/** + * Hook that reads a query parameter from the URL and removes it after the first + * render. Returns the value that was present when the component mounted, or + * null if the parameter was absent. + * + * @param name - the query parameter name to consume. + * @returns the consumed value, or null. + */ +export default function useConsumeQueryParam(name: string): string | null { + const query = useQuery(); + const history = useHistory(); + const value = query.get(name); + const consumedRef = useRef(false); + + useEffect(() => { + if (value && !consumedRef.current) { + consumedRef.current = true; + + const params = new URLSearchParams(window.location.search); + params.delete(name); + const search = params.toString(); + history.replace({ + pathname: window.location.pathname, + search: search ? `?${search}` : "", + }); + } + }, [value, name, history]); + + return consumedRef.current ? null : value; +} diff --git a/app/hooks/useQueryNotices.ts b/app/hooks/useQueryNotices.ts index 8a3379f5ec..3dee76439d 100644 --- a/app/hooks/useQueryNotices.ts +++ b/app/hooks/useQueryNotices.ts @@ -1,9 +1,8 @@ import { useEffect } from "react"; import { useTranslation } from "react-i18next"; -import { useHistory } from "react-router-dom"; import { toast } from "sonner"; import { QueryNotices } from "@shared/types"; -import useQuery from "./useQuery"; +import useConsumeQueryParam from "./useConsumeQueryParam"; /** * Display a toast message based on a notice in the query string. This is usually @@ -11,10 +10,8 @@ import useQuery from "./useQuery"; * or emails. */ export default function useQueryNotices() { - const query = useQuery(); - const history = useHistory(); const { t } = useTranslation(); - const notice = query.get("notice") as QueryNotices; + const notice = useConsumeQueryParam("notice") as QueryNotices; useEffect(() => { let message: string | undefined; @@ -40,16 +37,7 @@ export default function useQueryNotices() { } if (message) { - // Remove the notice param from the URL to prevent duplicate toasts - const params = new URLSearchParams(window.location.search); - params.delete("notice"); - const search = params.toString(); - history.replace({ - pathname: window.location.pathname, - search: search ? `?${search}` : "", - }); - setTimeout(() => toast.success(message), 0); } - }, [t, notice, history]); + }, [t, notice]); } diff --git a/app/models/Notification.ts b/app/models/Notification.ts index 37f14a2e70..a09b9ab1f1 100644 --- a/app/models/Notification.ts +++ b/app/models/Notification.ts @@ -48,6 +48,7 @@ class Notification extends Model { NotificationEventType.UpdateDocument, NotificationEventType.CreateRevision, NotificationEventType.AddUserToDocument, + NotificationEventType.RequestDocumentAccess, ], collections: [ NotificationEventType.CreateCollection, @@ -75,6 +76,20 @@ class Notification extends Model { @observable archivedAt: Date | null; + /** + * Request ID on notifications for access requests. + */ + @Field + @observable + accessRequestId?: string; + + /** + * Status of the associated access request. + */ + @Field + @observable + accessRequestStatus?: string; + /** * The user that triggered the notification. */ @@ -195,6 +210,14 @@ class Notification extends Model { return t("shared"); case NotificationEventType.AddUserToCollection: return t("invited you to"); + case NotificationEventType.RequestDocumentAccess: + if (this.accessRequestStatus === "approved") { + return t("was granted access to"); + } + if (this.accessRequestStatus === "dismissed") { + return t("requested access to"); + } + return t("is requesting access to"); default: return this.event; } @@ -237,6 +260,7 @@ class Notification extends Model { : undefined; return collection ? collectionPath(collection) : ""; } + case NotificationEventType.RequestDocumentAccess: case NotificationEventType.AddUserToDocument: case NotificationEventType.GroupMentionedInDocument: case NotificationEventType.MentionedInDocument: { diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index a2a33960e5..c5fae17713 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -238,7 +238,7 @@ function DataLoader({ match, children }: Props) { ) : error instanceof PaymentRequiredError ? ( ) : error instanceof AuthorizationError ? ( - + ) : error instanceof NotFoundError ? ( ) : ( diff --git a/app/scenes/Errors/Error403.tsx b/app/scenes/Errors/Error403.tsx index 5c0c51d213..3143bdde9e 100644 --- a/app/scenes/Errors/Error403.tsx +++ b/app/scenes/Errors/Error403.tsx @@ -1,6 +1,7 @@ -import { useCallback } from "react"; +import { useCallback, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; -import { useHistory } from "react-router-dom"; +import { useHistory, useLocation } from "react-router-dom"; +import { toast } from "sonner"; import Button from "~/components/Button"; import Empty from "~/components/Empty"; import Heading from "~/components/Heading"; @@ -8,24 +9,98 @@ import Scene from "~/components/Scene"; import { navigateToHome } from "~/actions/definitions/navigation"; import { HStack } from "~/components/primitives/HStack"; import { VStack } from "~/components/primitives/VStack"; +import Loading from "~/scenes/Document/components/Loading"; +import { client } from "~/utils/ApiClient"; -const Error403 = () => { +type Props = { + /** The document ID to request access to. */ + documentId?: string; +}; + +const Error403 = ({ documentId }: Props) => { const { t } = useTranslation(); + const location = useLocation<{ title?: string }>(); const history = useHistory(); + const [requesting, setRequesting] = useState(false); + const [requested, setRequested] = useState(false); + const [loading, setLoading] = useState(!!documentId); + + useEffect(() => { + if (!documentId) { + return; + } + + const checkRequested = async () => { + try { + const request = await client.post("/accessRequests.info", { + documentId, + }); + setRequested(request?.data?.status === "pending"); + } catch { + // No pending request or error — leave as not requested + } finally { + setLoading(false); + } + }; + + void checkRequested(); + }, [documentId]); + + const handleRequestAccess = useCallback(async () => { + if (!documentId || requesting || requested) { + return; + } + + setRequesting(true); + try { + await client.post("/accessRequests.create", { documentId }); + setRequested(true); + toast.success(t("Access request sent")); + } catch (err) { + toast.error(err.message); + } finally { + setRequesting(false); + } + }, [documentId, t, requested, requesting]); + const handleGoBack = useCallback(() => history.goBack(), [history]); + if (loading) { + return ; + } + return ( {t("No access to this doc")} - - {t( - "It doesn’t look like you have permission to access this document." - )}{" "} - {t("Please request access from the document owner.")} - - - + )} + +

+ + + ); + } +} diff --git a/server/migrations/20260107213946-create-access-requests.js b/server/migrations/20260107213946-create-access-requests.js new file mode 100644 index 0000000000..faef287791 --- /dev/null +++ b/server/migrations/20260107213946-create-access-requests.js @@ -0,0 +1,86 @@ +"use strict"; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable("access_requests", { + id: { + type: Sequelize.UUID, + primaryKey: true, + defaultValue: Sequelize.UUIDV4, + allowNull: false, + }, + status: { + type: Sequelize.STRING, + allowNull: false, + defaultValue: "pending", + }, + respondedAt: { + type: Sequelize.DATE, + allowNull: true, + }, + createdAt: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.NOW, + }, + updatedAt: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.NOW, + }, + documentId: { + type: Sequelize.UUID, + allowNull: false, + references: { + model: "documents", + key: "id", + }, + onDelete: "CASCADE", + onUpdate: "CASCADE", + }, + userId: { + type: Sequelize.UUID, + allowNull: false, + references: { + model: "users", + key: "id", + }, + onDelete: "CASCADE", + onUpdate: "CASCADE", + }, + teamId: { + type: Sequelize.UUID, + allowNull: false, + references: { + model: "teams", + key: "id", + }, + onDelete: "CASCADE", + onUpdate: "CASCADE", + }, + responderId: { + type: Sequelize.UUID, + allowNull: true, + references: { + model: "users", + key: "id", + }, + onDelete: "SET NULL", + onUpdate: "CASCADE", + }, + }); + + await queryInterface.addIndex("access_requests", ["documentId", "userId"], { + unique: true, + where: { status: "pending" }, + name: "access_requests_document_id_user_id_pending", + }); + await queryInterface.addIndex("access_requests", ["userId"]); + await queryInterface.addIndex("access_requests", ["teamId"]); + }, + + async down(queryInterface) { + await queryInterface.dropTable("access_requests"); + }, +}; diff --git a/server/migrations/20260107220000-add-access-request-to-notifications.js b/server/migrations/20260107220000-add-access-request-to-notifications.js new file mode 100644 index 0000000000..edf24d887a --- /dev/null +++ b/server/migrations/20260107220000-add-access-request-to-notifications.js @@ -0,0 +1,24 @@ +"use strict"; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn("notifications", "accessRequestId", { + type: Sequelize.UUID, + allowNull: true, + references: { + model: "access_requests", + key: "id", + }, + onDelete: "SET NULL", + onUpdate: "CASCADE", + }); + + await queryInterface.addIndex("notifications", ["accessRequestId"]); + }, + + async down(queryInterface) { + await queryInterface.removeIndex("notifications", ["accessRequestId"]); + await queryInterface.removeColumn("notifications", "accessRequestId"); + }, +}; diff --git a/server/models/AccessRequest.ts b/server/models/AccessRequest.ts new file mode 100644 index 0000000000..909f98c76a --- /dev/null +++ b/server/models/AccessRequest.ts @@ -0,0 +1,168 @@ +import type { + InferAttributes, + InferCreationAttributes, + SaveOptions, +} from "sequelize"; +import { + Table, + ForeignKey, + Column, + BelongsTo, + DataType, + Default, + AllowNull, + DefaultScope, + BeforeCreate, +} from "sequelize-typescript"; +import Document from "./Document"; +import Team from "./Team"; +import User from "./User"; +import Fix from "./decorators/Fix"; +import IdModel from "./base/IdModel"; +import { IsIn } from "class-validator"; +import { ValidationError } from "@server/errors"; +import type { APIContext } from "@server/types"; + +export enum AccessRequestStatus { + Pending = "pending", + Approved = "approved", + Dismissed = "dismissed", +} + +@DefaultScope(() => ({ + include: [ + { + association: "user", + required: true, + }, + { + association: "responder", + required: false, + }, + ], +})) +@Table({ + tableName: "access_requests", + modelName: "access_request", +}) +@Fix +class AccessRequest extends IdModel< + InferAttributes, + Partial> +> { + @Default(AccessRequestStatus.Pending) + @IsIn([Object.values(AccessRequestStatus)]) + @Column(DataType.STRING) + status: AccessRequestStatus; + + @AllowNull + @Column + respondedAt: Date | null; + + // associations + @BelongsTo(() => Document, "documentId") + document: Document; + + @ForeignKey(() => Document) + @Column(DataType.UUID) + documentId: string; + + @BelongsTo(() => User, "userId") + user: User; + + @ForeignKey(() => User) + @Column(DataType.UUID) + userId: string; + + @BelongsTo(() => Team, "teamId") + team: Team; + + @ForeignKey(() => Team) + @Column(DataType.UUID) + teamId: string; + + @BelongsTo(() => User, "responderId") + responder: User | null; + + @AllowNull + @ForeignKey(() => User) + @Column(DataType.UUID) + responderId: string | null; + + @BeforeCreate + static async validateNoDuplicatePendingRequest( + instance: AccessRequest, + options: SaveOptions + ) { + const { documentId, userId } = instance; + + const existingRequest = await this.findOne({ + where: { + documentId, + userId, + status: AccessRequestStatus.Pending, + }, + transaction: options.transaction, + }); + + if (existingRequest) { + throw ValidationError( + "A pending access request already exists for this document and user." + ); + } + } + + /** + * Approve this access request, setting the status and responder, and persist. + * + * @param ctx the API context; the authenticated user is recorded as responder. + */ + public approve(ctx: APIContext) { + this.status = AccessRequestStatus.Approved; + this.responderId = ctx.state.auth.user.id; + this.respondedAt = new Date(); + return this.saveWithCtx(ctx); + } + + /** + * Dismiss this access request, setting the status and responder, and persist. + * + * @param ctx the API context; the authenticated user is recorded as responder. + */ + public dismiss(ctx: APIContext) { + this.status = AccessRequestStatus.Dismissed; + this.responderId = ctx.state.auth.user.id; + this.respondedAt = new Date(); + return this.saveWithCtx(ctx); + } + + /** + * get the user's pending request. + * + * @param documentId The document ID or slug. + * @param userId The user ID. + * + * @returns the pending request or null. + */ + public static async findPendingForUser({ + documentId, + userId, + }: { + documentId?: string; + userId?: string; + }): Promise { + if (!documentId || !userId) { + return null; + } + + return this.findOne({ + where: { + documentId, + userId, + status: AccessRequestStatus.Pending, + }, + }); + } +} + +export default AccessRequest; diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 7e51f28062..4af1dc579f 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -563,12 +563,32 @@ class Collection extends ParanoidModel< * either via group or direct membership. * * @param collectionId + * @param permission optional permission filter + * * @returns userIds */ - static async membershipUserIds(collectionId: string) { + static async membershipUserIds( + collectionId: string, + permission?: CollectionPermission + ) { const collection = await this.scope("withAllMemberships").findOne({ where: { id: collectionId }, + include: [ + { + association: "memberships", + required: false, + ...(permission ? { where: { permission } } : {}), + separate: true, + }, + { + association: "groupMemberships", + required: false, + ...(permission ? { where: { permission } } : {}), + separate: true, + }, + ], }); + if (!collection) { return []; } diff --git a/server/models/Document.ts b/server/models/Document.ts index 924588b541..2b4c8d995a 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -38,6 +38,7 @@ import { import { MaxLength } from "class-validator"; import isUUID from "validator/lib/isUUID"; import type { + DocumentPermission, ImportableIntegrationService, NavigationNode, ProsemirrorData, @@ -682,11 +683,30 @@ class Document extends ArchivableModel< * either via group or direct membership. * * @param documentId + * @param permission optional permission filter + * * @returns userIds */ - static async membershipUserIds(documentId: string) { + static async membershipUserIds( + documentId: string, + permission?: DocumentPermission + ) { const document = await this.scope("withAllMemberships").findOne({ where: { id: documentId }, + include: [ + { + association: "memberships", + required: false, + ...(permission ? { where: { permission } } : {}), + separate: true, + }, + { + association: "groupMemberships", + required: false, + ...(permission ? { where: { permission } } : {}), + separate: true, + }, + ], }); if (!document) { return []; diff --git a/server/models/Notification.ts b/server/models/Notification.ts index 658794f1b6..c48105b234 100644 --- a/server/models/Notification.ts +++ b/server/models/Notification.ts @@ -33,6 +33,7 @@ import Team from "./Team"; import User from "./User"; import Group from "./Group"; import Fix from "./decorators/Fix"; +import AccessRequest from "./AccessRequest"; let baseDomain; @@ -90,6 +91,10 @@ let baseDomain; association: "actor", required: false, }, + { + association: "accessRequest", + required: false, + }, ], })) @Table({ @@ -196,6 +201,14 @@ class Notification extends Model< @Column(DataType.UUID) membershipId: string; + @BelongsTo(() => AccessRequest, "accessRequestId") + accessRequest: AccessRequest; + + @AllowNull + @ForeignKey(() => AccessRequest) + @Column(DataType.UUID) + accessRequestId: string; + @AfterCreate static async createEvent( model: Notification, diff --git a/server/models/index.ts b/server/models/index.ts index 4be4a88e16..c4ac58fd14 100644 --- a/server/models/index.ts +++ b/server/models/index.ts @@ -78,3 +78,5 @@ export { default as Subscription } from "./Subscription"; export { default as Emoji } from "./Emoji"; export { default as UserPasskey } from "./UserPasskey"; + +export { default as AccessRequest } from "./AccessRequest"; diff --git a/server/policies/accessRequest.ts b/server/policies/accessRequest.ts new file mode 100644 index 0000000000..0fed8e6f83 --- /dev/null +++ b/server/policies/accessRequest.ts @@ -0,0 +1,14 @@ +import { AccessRequest, User } from "@server/models"; +import { allow } from "./cancan"; +import { isOwner, isTeamModel, or, and } from "./utils"; + +allow( + User, + ["read", "update", "delete"], + AccessRequest, + (actor, accessRequest) => + and( + isTeamModel(actor, accessRequest), + or(actor.isAdmin, isOwner(actor, accessRequest)) + ) +); diff --git a/server/policies/index.ts b/server/policies/index.ts index 83aae1a724..2d92beef76 100644 --- a/server/policies/index.ts +++ b/server/policies/index.ts @@ -30,3 +30,4 @@ import "./webhookSubscription"; import "./userMembership"; import "./userPasskey"; import "./emoji"; +import "./accessRequest"; diff --git a/server/presenters/accessRequest.ts b/server/presenters/accessRequest.ts new file mode 100644 index 0000000000..99f1ff6bf9 --- /dev/null +++ b/server/presenters/accessRequest.ts @@ -0,0 +1,20 @@ +import type { AccessRequest } from "@server/models"; +import presentUser from "./user"; + +export default function present(accessRequest: AccessRequest) { + return { + id: accessRequest.id, + documentId: accessRequest.documentId, + userId: accessRequest.userId, + user: accessRequest.user ? presentUser(accessRequest.user) : undefined, + teamId: accessRequest.teamId, + status: accessRequest.status, + responderId: accessRequest.responderId, + responder: accessRequest.responder + ? presentUser(accessRequest.responder) + : undefined, + respondedAt: accessRequest.respondedAt, + createdAt: accessRequest.createdAt, + updatedAt: accessRequest.updatedAt, + }; +} diff --git a/server/presenters/index.ts b/server/presenters/index.ts index 60249226a2..7162e259fd 100644 --- a/server/presenters/index.ts +++ b/server/presenters/index.ts @@ -33,6 +33,7 @@ import presentTemplate from "./template"; import presentUser from "./user"; import presentView from "./view"; import presentEmoji from "./emoji"; +import presentAccessRequest from "./accessRequest"; export { presentApiKey, @@ -72,4 +73,5 @@ export { presentUser, presentView, presentEmoji, + presentAccessRequest, }; diff --git a/server/presenters/notification.ts b/server/presenters/notification.ts index d29c664bfe..69d6e4e2d8 100644 --- a/server/presenters/notification.ts +++ b/server/presenters/notification.ts @@ -10,6 +10,8 @@ export default async function presentNotification( return { id: notification.id, viewedAt: notification.viewedAt, + accessRequestId: notification.accessRequestId, + accessRequestStatus: notification.accessRequest?.status, archivedAt: notification.archivedAt, createdAt: notification.createdAt, event: notification.event, diff --git a/server/queues/processors/EmailsProcessor.ts b/server/queues/processors/EmailsProcessor.ts index 65dd721932..ec3e39642a 100644 --- a/server/queues/processors/EmailsProcessor.ts +++ b/server/queues/processors/EmailsProcessor.ts @@ -5,6 +5,7 @@ import CollectionSharedEmail from "@server/emails/templates/CollectionSharedEmai 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 DocumentMentionedEmail from "@server/emails/templates/DocumentMentionedEmail"; import DocumentPublishedOrUpdatedEmail from "@server/emails/templates/DocumentPublishedOrUpdatedEmail"; import DocumentSharedEmail from "@server/emails/templates/DocumentSharedEmail"; @@ -207,6 +208,22 @@ export default class EmailsProcessor extends BaseProcessor { ).schedule({ delay: Minute.ms, }); + return; + } + + case NotificationEventType.RequestDocumentAccess: { + await new DocumentAccessRequestEmail( + { + to: notification.user.email, + documentId: notification.documentId, + actorId: notification.actorId, + teamUrl: notification.team.url, + }, + { notificationId: notification.id } + ).schedule({ + delay: Minute.ms, + }); + return; } } } diff --git a/server/queues/processors/NotificationsProcessor.ts b/server/queues/processors/NotificationsProcessor.ts index 16ea25d9bf..4d223d4381 100644 --- a/server/queues/processors/NotificationsProcessor.ts +++ b/server/queues/processors/NotificationsProcessor.ts @@ -1,4 +1,5 @@ import type { + AccessRequestEvent, CollectionEvent, RevisionEvent, Event, @@ -15,6 +16,7 @@ import CommentCreatedNotificationsTask from "../tasks/CommentCreatedNotification import CommentUpdatedNotificationsTask from "../tasks/CommentUpdatedNotificationsTask"; import ReactionCreatedNotificationsTask from "../tasks/ReactionCreatedNotificationsTask"; import ReactionRemovedNotificationsTask from "../tasks/ReactionRemovedNotificationsTask"; +import DocumentAccessRequestNotificationsTask from "../tasks/DocumentAccessRequestNotificationsTask"; import DocumentAddGroupNotificationsTask from "../tasks/DocumentAddGroupNotificationsTask"; import DocumentAddUserNotificationsTask from "../tasks/DocumentAddUserNotificationsTask"; import DocumentPublishedNotificationsTask from "../tasks/DocumentPublishedNotificationsTask"; @@ -27,6 +29,7 @@ export default class NotificationsProcessor extends BaseProcessor { "documents.publish", "documents.add_user", "documents.add_group", + "access_requests.create", "revisions.create", "collections.create", "collections.add_user", @@ -44,6 +47,8 @@ export default class NotificationsProcessor extends BaseProcessor { return this.documentAddUser(event); case "documents.add_group": return this.documentAddGroup(event); + case "access_requests.create": + return this.documentAccessRequest(event); case "revisions.create": return this.revisionCreated(event); case "collections.create": @@ -85,6 +90,10 @@ export default class NotificationsProcessor extends BaseProcessor { await new DocumentAddGroupNotificationsTask().schedule(event); } + async documentAccessRequest(event: AccessRequestEvent) { + await new DocumentAccessRequestNotificationsTask().schedule(event); + } + async revisionCreated(event: RevisionEvent) { await new RevisionCreatedNotificationsTask().schedule(event); await new ShareSubscriptionNotificationsTask().schedule(event); diff --git a/server/queues/tasks/DocumentAccessRequestNotificationTask.test.ts b/server/queues/tasks/DocumentAccessRequestNotificationTask.test.ts new file mode 100644 index 0000000000..f657049ef3 --- /dev/null +++ b/server/queues/tasks/DocumentAccessRequestNotificationTask.test.ts @@ -0,0 +1,336 @@ +import { + NotificationEventType, + DocumentPermission, + CollectionPermission, +} from "@shared/types"; +import Logger from "@server/logging/Logger"; +import { AccessRequest, Notification, UserMembership } from "@server/models"; +import DocumentAccessRequestNotificationsTask from "./DocumentAccessRequestNotificationsTask"; +import { + buildAdmin, + buildCollection, + buildDocument, + buildTeam, + buildUser, +} from "@server/test/factories"; + +const ip = "127.0.0.1"; + +describe("DocumentAccessRequestNotificationsTask", () => { + let task: DocumentAccessRequestNotificationsTask; + + beforeEach(() => { + task = new DocumentAccessRequestNotificationsTask(); + vi.clearAllMocks(); + }); + + describe("perform", () => { + it("should fail with the correct error if the document is not found", async () => { + const loggerSpy = vi.spyOn(Logger, "debug"); + + await task.perform({ + name: "access_requests.create", + modelId: "ar1", + documentId: "doc1", + teamId: "team1", + actorId: "actor1", + ip, + }); + + expect(loggerSpy).toHaveBeenCalledWith( + "task", + "Document not found for access request notification", + { documentId: "doc1" } + ); + }); + + it("should send notifications to document managers", async () => { + const spy = vi.spyOn(Notification, "create"); + const team = await buildTeam(); + const manager1 = await buildUser({ teamId: team.id }); + const manager2 = await buildUser({ teamId: team.id }); + + const actor = await buildUser({ teamId: team.id }); + const document = await buildDocument({ teamId: team.id }); + + await UserMembership.create({ + userId: manager1.id, + documentId: document.id, + createdById: manager1.id, + permission: DocumentPermission.Admin, + }); + await UserMembership.create({ + userId: manager2.id, + documentId: document.id, + createdById: manager2.id, + permission: DocumentPermission.Admin, + }); + + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: actor.id, + teamId: team.id, + }); + + const task = new DocumentAccessRequestNotificationsTask(); + await task.perform({ + name: "access_requests.create", + modelId: accessRequest.id, + documentId: document.id, + teamId: team.id, + actorId: actor.id, + ip, + }); + + expect(spy).toHaveBeenCalledTimes(2); + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + event: NotificationEventType.RequestDocumentAccess, + userId: manager1.id, + actorId: actor.id, + documentId: document.id, + teamId: team.id, + }) + ); + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + event: NotificationEventType.RequestDocumentAccess, + userId: manager2.id, + actorId: actor.id, + documentId: document.id, + teamId: team.id, + }) + ); + }); + + it("should send notifications to collection managers", async () => { + const spy = vi.spyOn(Notification, "create"); + const team = await buildTeam(); + const manager1 = await buildAdmin({ teamId: team.id }); + const manager2 = await buildUser({ teamId: team.id }); + + const actor = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + createdById: manager1.id, + }); + const document = await buildDocument({ + teamId: team.id, + collectionId: collection.id, + }); + + await UserMembership.create({ + userId: manager2.id, + collectionId: collection.id, + createdById: manager2.id, + permission: CollectionPermission.Admin, + }); + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: actor.id, + teamId: team.id, + }); + + const task = new DocumentAccessRequestNotificationsTask(); + await task.perform({ + name: "access_requests.create", + modelId: accessRequest.id, + documentId: document.id, + teamId: team.id, + actorId: actor.id, + ip, + }); + + expect(spy).toHaveBeenCalledTimes(2); + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + event: NotificationEventType.RequestDocumentAccess, + userId: manager1.id, + actorId: actor.id, + documentId: document.id, + teamId: team.id, + }) + ); + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + event: NotificationEventType.RequestDocumentAccess, + userId: manager2.id, + actorId: actor.id, + documentId: document.id, + teamId: team.id, + }) + ); + }); + + it("should not send notifications to suspended users", async () => { + const spy = vi.spyOn(Notification, "create"); + const team = await buildTeam(); + const manager = await buildUser({ + teamId: team.id, + suspendedAt: new Date(), + }); + const actor = await buildUser({ teamId: team.id }); + const document = await buildDocument({ + teamId: team.id, + createdById: manager.id, + }); + + await UserMembership.create({ + userId: manager.id, + documentId: document.id, + permission: DocumentPermission.Admin, + createdById: manager.id, + }); + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: actor.id, + teamId: team.id, + }); + + const task = new DocumentAccessRequestNotificationsTask(); + await task.perform({ + name: "access_requests.create", + modelId: accessRequest.id, + documentId: document.id, + teamId: team.id, + actorId: actor.id, + ip, + }); + + expect(spy).not.toHaveBeenCalled(); + }); + + it("should not send notification if user has disabled this notification type", async () => { + const spy = vi.spyOn(Notification, "create"); + const team = await buildTeam(); + const admin = await buildAdmin({ teamId: team.id }); + const actor = await buildUser({ teamId: team.id }); + + const document = await buildDocument({ + teamId: team.id, + createdById: admin.id, + }); + + await UserMembership.create({ + userId: admin.id, + documentId: document.id, + permission: DocumentPermission.Admin, + createdById: admin.id, + }); + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: actor.id, + teamId: team.id, + }); + + // disable notifications for this event type + admin.setNotificationEventType( + NotificationEventType.RequestDocumentAccess, + false + ); + await admin.save(); + + const task = new DocumentAccessRequestNotificationsTask(); + await task.perform({ + name: "access_requests.create", + modelId: accessRequest.id, + documentId: document.id, + teamId: team.id, + actorId: actor.id, + ip, + }); + + expect(spy).not.toHaveBeenCalled(); + }); + + it("should fall back to workspace admins when no document or collection admin is set", async () => { + const spy = vi.spyOn(Notification, "create"); + const team = await buildTeam(); + const workspaceAdmin = await buildAdmin({ teamId: team.id }); + const actor = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ teamId: team.id }); + const document = await buildDocument({ + teamId: team.id, + collectionId: collection.id, + }); + + // Remove the auto-created collection admin membership so workspace admin + // is the only fallback target. + await UserMembership.destroy({ where: { collectionId: collection.id } }); + + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: actor.id, + teamId: team.id, + }); + + const task = new DocumentAccessRequestNotificationsTask(); + await task.perform({ + name: "access_requests.create", + modelId: accessRequest.id, + documentId: document.id, + teamId: team.id, + actorId: actor.id, + ip, + }); + + expect(spy).toHaveBeenCalledTimes(1); + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + event: NotificationEventType.RequestDocumentAccess, + userId: workspaceAdmin.id, + actorId: actor.id, + documentId: document.id, + teamId: team.id, + }) + ); + }); + + it("should not fall back to workspace admins when document admins exist", async () => { + const spy = vi.spyOn(Notification, "create"); + const team = await buildTeam(); + const workspaceAdmin = await buildAdmin({ teamId: team.id }); + const documentAdmin = await buildUser({ teamId: team.id }); + const actor = await buildUser({ teamId: team.id }); + const document = await buildDocument({ + teamId: team.id, + createdById: documentAdmin.id, + }); + + await UserMembership.create({ + userId: documentAdmin.id, + documentId: document.id, + permission: DocumentPermission.Admin, + createdById: documentAdmin.id, + }); + + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: actor.id, + teamId: team.id, + }); + + const task = new DocumentAccessRequestNotificationsTask(); + await task.perform({ + name: "access_requests.create", + modelId: accessRequest.id, + documentId: document.id, + teamId: team.id, + actorId: actor.id, + ip, + }); + + expect(spy).toHaveBeenCalledTimes(1); + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + userId: documentAdmin.id, + }) + ); + expect(spy).not.toHaveBeenCalledWith( + expect.objectContaining({ + userId: workspaceAdmin.id, + }) + ); + }); + }); +}); diff --git a/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts b/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts new file mode 100644 index 0000000000..c984a2a185 --- /dev/null +++ b/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts @@ -0,0 +1,146 @@ +import { Op } from "sequelize"; +import { uniq } from "es-toolkit/compat"; +import { + NotificationEventType, + DocumentPermission, + CollectionPermission, + UserRole, +} from "@shared/types"; +import Logger from "@server/logging/Logger"; +import { + Document, + Notification, + User, + Collection, + AccessRequest, +} from "@server/models"; +import { AccessRequestStatus } from "@server/models/AccessRequest"; +import type { AccessRequestEvent } from "@server/types"; +import { BaseTask, TaskPriority } from "./base/BaseTask"; + +/** + * Notification task that sends notifications to users who can manage a document + * when someone requests access to it. + */ +export default class DocumentAccessRequestNotificationsTask extends BaseTask { + public async perform(event: AccessRequestEvent) { + const document = await Document.findByPk(event.documentId); + if (!document) { + Logger.debug( + "task", + `Document not found for access request notification`, + { + documentId: event.documentId, + } + ); + return; + } + + const accessRequest = await AccessRequest.findByPk(event.modelId); + if ( + !accessRequest || + accessRequest.status !== AccessRequestStatus.Pending + ) { + Logger.debug("task", `Access request not pending for notification`, { + documentId: event.documentId, + accessRequestId: event.modelId, + }); + return; + } + + const recipients = await this.findDocumentAdmins(document); + Logger.debug("task", "Access request notification recipients", { + documentId: event.documentId, + accessRequestId: event.modelId, + recipientIds: recipients.map((r) => r.id), + }); + + for (const recipient of recipients) { + if (recipient.id === event.actorId) { + Logger.debug("task", "Skipping recipient: is the actor", { + documentId: event.documentId, + recipientId: recipient.id, + }); + continue; + } + if ( + !recipient.subscribedToEventType( + NotificationEventType.RequestDocumentAccess + ) + ) { + Logger.debug("task", "Skipping recipient: not subscribed", { + documentId: event.documentId, + recipientId: recipient.id, + }); + continue; + } + + await Notification.create({ + event: NotificationEventType.RequestDocumentAccess, + userId: recipient.id, + actorId: event.actorId, + teamId: event.teamId, + documentId: event.documentId, + accessRequestId: accessRequest.id, + }); + } + } + + /** + * Find users who can manage the document, with tiered fallback: + * document admins → collection admins → workspace admins. The first tier + * with any users is used. + * + * @param document - the document to find managers for. + * @returns list of users who can manage the document. + */ + private async findDocumentAdmins(document: Document): Promise { + const documentManagerIds = await Document.membershipUserIds( + document.id, + DocumentPermission.Admin + ); + + if (documentManagerIds.length > 0) { + return this.loadUsers(documentManagerIds, document.teamId); + } + + if (document.collectionId) { + const collectionManagerIds = await Collection.membershipUserIds( + document.collectionId, + CollectionPermission.Admin + ); + if (collectionManagerIds.length > 0) { + return this.loadUsers(collectionManagerIds, document.teamId); + } + } + + Logger.debug("task", "Falling back to workspace admins", { + documentId: document.id, + collectionId: document.collectionId, + }); + + return User.findAll({ + where: { + teamId: document.teamId, + role: UserRole.Admin, + suspendedAt: null, + }, + }); + } + + private async loadUsers(ids: string[], teamId: string): Promise { + return User.findAll({ + where: { + id: { [Op.in]: uniq(ids) }, + teamId, + suspendedAt: null, + }, + }); + } + + public get options() { + return { + priority: TaskPriority.Background, + }; + } +} diff --git a/server/routes/api/accessRequests/accessRequests.test.ts b/server/routes/api/accessRequests/accessRequests.test.ts new file mode 100644 index 0000000000..62adf9a5f9 --- /dev/null +++ b/server/routes/api/accessRequests/accessRequests.test.ts @@ -0,0 +1,554 @@ +import { DocumentPermission } from "@shared/types"; +import { AccessRequest, UserMembership } from "@server/models"; +import { AccessRequestStatus } from "@server/models/AccessRequest"; +import { + buildAdmin, + buildCollection, + buildDocument, + buildTeam, + buildUser, +} from "@server/test/factories"; +import { getTestServer } from "@server/test/support"; + +const server = getTestServer(); + +describe("#accessRequests.create", () => { + it("should require id", async () => { + const user = await buildUser(); + const res = await server.post("/api/accessRequests.create", { + body: { + token: user.getJwtToken(), + }, + }); + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("documentId: Must be a valid UUID or slug"); + }); + + it("should require authentication", async () => { + const document = await buildDocument(); + const res = await server.post("/api/accessRequests.create", { + body: { + documentId: document.id, + }, + }); + expect(res.status).toEqual(401); + }); + + it("should return 404 for non-existent document", async () => { + const user = await buildUser(); + const res = await server.post("/api/accessRequests.create", { + body: { + token: user.getJwtToken(), + documentId: "a8f22c38-f4eb-4909-8c30-b927af36c5f3", + }, + }); + const body = await res.json(); + expect(res.status).toEqual(404); + expect(body.message).toEqual("Resource not found"); + }); + + it("should create access request for a document", async () => { + const team = await buildTeam(); + const owner = await buildUser({ teamId: team.id }); + const requester = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: owner.id, + permission: null, + }); + const document = await buildDocument({ + teamId: team.id, + createdById: owner.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/accessRequests.create", { + body: { + token: requester.getJwtToken(), + documentId: document.id, + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.documentId).toEqual(document.id); + expect(body.data.userId).toEqual(requester.id); + }); + + it("should reject if user already has access", async () => { + const team = await buildTeam(); + const owner = await buildUser({ teamId: team.id }); + const requester = await buildUser({ teamId: team.id }); + const document = await buildDocument({ + teamId: team.id, + createdById: owner.id, + }); + + const res = await server.post("/api/accessRequests.create", { + body: { + token: requester.getJwtToken(), + documentId: document.id, + }, + }); + + expect(res.status).toEqual(400); + }); + + it("should work with document urlId", async () => { + const team = await buildTeam(); + const owner = await buildUser({ teamId: team.id }); + const requester = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: owner.id, + permission: null, + }); + const document = await buildDocument({ + teamId: team.id, + createdById: owner.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/accessRequests.create", { + body: { + token: requester.getJwtToken(), + documentId: document.urlId, + }, + }); + expect(res.status).toEqual(200); + }); + + it("should not allow new request if pending exists", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: admin.id, + permission: null, + }); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + collectionId: collection.id, + }); + + // Create first access request + const res1 = await server.post("/api/accessRequests.create", { + body: { + token: requester.getJwtToken(), + documentId: document.id, + }, + }); + + // Try to create another + const res2 = await server.post("/api/accessRequests.create", { + body: { + token: requester.getJwtToken(), + documentId: document.id, + }, + }); + + expect(res1.status).toEqual(200); + expect(res2.status).toEqual(400); + + // Verify only one access request exists + const count = await AccessRequest.count({ + where: { + documentId: document.id, + userId: requester.id, + }, + }); + expect(count).toEqual(1); + }); + + it("should allow creating new request after previous was dismissed", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: admin.id, + permission: null, + }); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + collectionId: collection.id, + }); + + // Create and dismiss first request + const res1 = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + status: AccessRequestStatus.Dismissed, + responderId: admin.id, + respondedAt: new Date(), + }); + + // Create new request + const res2 = await server.post("/api/accessRequests.create", { + body: { + token: requester.getJwtToken(), + documentId: document.id, + }, + }); + const body = await res2.json(); + + expect(res2.status).toEqual(200); + expect(body.data.id).not.toEqual(res1.id); + expect(body.data.status).toEqual(AccessRequestStatus.Pending); + }); +}); + +describe("#accessRequests.info", () => { + it("should require authentication", async () => { + const res = await server.post("/api/accessRequests.info"); + expect(res.status).toEqual(401); + }); + + it("should fail if both id and documentId are missing", async () => { + const user = await buildUser(); + const res = await server.post("/api/accessRequests.info", { + body: { + token: user.getJwtToken(), + }, + }); + expect(res.status).toEqual(400); + }); + + it("should return access request correctly by id", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + }); + + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + }); + + const res = await server.post("/api/accessRequests.info", { + body: { + token: requester.getJwtToken(), + id: accessRequest.id, + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.id).toEqual(accessRequest.id); + expect(body.data.status).toEqual(AccessRequestStatus.Pending); + }); + + it("should return access request correctly by documentId", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + }); + + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + }); + + const res = await server.post("/api/accessRequests.info", { + body: { + token: requester.getJwtToken(), + documentId: document.urlId, + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.id).toEqual(accessRequest.id); + expect(body.data.status).toEqual(AccessRequestStatus.Pending); + }); + + it("should return 404 if access request not found", async () => { + const user = await buildUser(); + const res = await server.post("/api/accessRequests.info", { + body: { + token: user.getJwtToken(), + id: "00000000-0000-0000-0000-000000000000", + }, + }); + expect(res.status).toEqual(404); + }); +}); + +describe("#accessRequests.approve", () => { + it("should require authentication", async () => { + const res = await server.post("/api/accessRequests.approve"); + expect(res.status).toEqual(401); + }); + + it("should approve an access request and grant access", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + }); + + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + status: AccessRequestStatus.Pending, + }); + + const res = await server.post("/api/accessRequests.approve", { + body: { + token: admin.getJwtToken(), + id: accessRequest.id, + permission: DocumentPermission.ReadWrite, + }, + }); + const body = await res.json(); + + expect(body.data.status).toEqual(AccessRequestStatus.Approved); + expect(body.data.responderId).toEqual(admin.id); + + // // Verify that the user now has access + const membership = await UserMembership.findOne({ + where: { + userId: requester.id, + documentId: document.id, + }, + }); + expect(membership).toBeTruthy(); + expect(membership?.permission).toEqual(DocumentPermission.ReadWrite); + }); + + it("should not allow non-managers to approve requests", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const nonManager = await buildUser(); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + }); + + await UserMembership.create({ + userId: admin.id, + documentId: document.id, + createdById: admin.id, + permission: DocumentPermission.ReadWrite, + }); + + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + }); + + const res = await server.post("/api/accessRequests.approve", { + body: { + token: nonManager.getJwtToken(), + id: accessRequest.id, + permission: DocumentPermission.ReadWrite, + }, + }); + + expect(res.status).toEqual(403); + }); + + it("should be a no-op when user already has membership", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + }); + + await UserMembership.create({ + userId: requester.id, + documentId: document.id, + createdById: admin.id, + permission: DocumentPermission.Read, + }); + + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + status: AccessRequestStatus.Pending, + }); + + const res = await server.post("/api/accessRequests.approve", { + body: { + token: admin.getJwtToken(), + id: accessRequest.id, + permission: DocumentPermission.ReadWrite, + }, + }); + + expect(res.status).toEqual(200); + + // Existing membership is unchanged. + const memberships = await UserMembership.findAll({ + where: { + userId: requester.id, + documentId: document.id, + }, + }); + expect(memberships).toHaveLength(1); + expect(memberships[0].permission).toEqual(DocumentPermission.Read); + }); + + it("should not allow approving requests that have been responded to", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + }); + + // Create access request that's already approved + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + status: AccessRequestStatus.Approved, + responderId: admin.id, + respondedAt: new Date(), + }); + + const res = await server.post("/api/accessRequests.approve", { + body: { + token: admin.getJwtToken(), + id: accessRequest.id, + permission: DocumentPermission.ReadWrite, + }, + }); + + expect(res.status).toEqual(400); + }); +}); + +describe("#accessRequests.dismiss", () => { + it("should require authentication", async () => { + const res = await server.post("/api/accessRequests.dismiss"); + expect(res.status).toEqual(401); + }); + + it("should dismiss an access request", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + }); + + // Create access request + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + }); + + const res = await server.post("/api/accessRequests.dismiss", { + body: { + token: admin.getJwtToken(), + id: accessRequest.id, + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.status).toEqual(AccessRequestStatus.Dismissed); + expect(body.data.responderId).toEqual(admin.id); + + const membership = await UserMembership.findOne({ + where: { + userId: requester.id, + documentId: document.id, + }, + }); + expect(membership).toBeNull(); + }); + + it("should not allow non-managers to dismiss requests", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const nonManager = await buildUser(); + const document = await buildDocument({ + userId: admin.id, + teamId: team.id, + }); + + // add non-manager to the document with editor access + await UserMembership.create({ + userId: admin.id, + documentId: document.id, + createdById: admin.id, + permission: DocumentPermission.ReadWrite, + }); + + // Create access request + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + }); + + const res = await server.post("/api/accessRequests.dismiss", { + body: { + token: nonManager.getJwtToken(), + id: accessRequest.id, + }, + }); + + expect(res.status).toEqual(403); + }); + + it("should be a no-op when request has already been responded to", async () => { + const team = await buildTeam(); + const requester = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const responder = await buildAdmin({ teamId: team.id }); + const document = await buildDocument({ + createdById: admin.id, + teamId: team.id, + }); + + const respondedAt = new Date(); + const accessRequest = await AccessRequest.create({ + documentId: document.id, + userId: requester.id, + teamId: team.id, + status: AccessRequestStatus.Dismissed, + responderId: responder.id, + respondedAt, + }); + + const res = await server.post("/api/accessRequests.dismiss", { + body: { + token: admin.getJwtToken(), + id: accessRequest.id, + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.status).toEqual(AccessRequestStatus.Dismissed); + expect(body.data.responderId).toEqual(responder.id); + }); +}); diff --git a/server/routes/api/accessRequests/accessRequests.ts b/server/routes/api/accessRequests/accessRequests.ts new file mode 100644 index 0000000000..ffc8af0cac --- /dev/null +++ b/server/routes/api/accessRequests/accessRequests.ts @@ -0,0 +1,180 @@ +import Router from "koa-router"; +import auth from "@server/middlewares/authentication"; +import { rateLimiter } from "@server/middlewares/rateLimiter"; +import { transaction } from "@server/middlewares/transaction"; +import validate from "@server/middlewares/validate"; +import { Document, AccessRequest, UserMembership } from "@server/models"; +import { AccessRequestStatus } from "@server/models/AccessRequest"; +import { authorize, can } from "@server/policies"; +import { presentAccessRequest, presentPolicies } from "@server/presenters"; +import type { APIContext } from "@server/types"; +import { RateLimiterStrategy } from "@server/utils/RateLimiter"; +import * as T from "./schema"; +import { InvalidRequestError, NotFoundError } from "@server/errors"; + +const router = new Router(); + +router.post( + "accessRequests.create", + rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), + auth(), + validate(T.AccessRequestsCreateSchema), + transaction(), + async (ctx: APIContext) => { + const { documentId } = ctx.input.body; + const { user } = ctx.state.auth; + const { transaction } = ctx.state; + + const document = await Document.findByPk(documentId, { + userId: user.id, + transaction, + rejectOnEmpty: true, + }); + + if (can(user, "read", document)) { + throw InvalidRequestError("User already has document access"); + } + if (user.teamId !== document.teamId) { + throw NotFoundError(); + } + + const accessRequest = await AccessRequest.createWithCtx(ctx, { + documentId: document.id, + teamId: user.teamId, + userId: user.id, + status: AccessRequestStatus.Pending, + }); + + ctx.body = { + data: presentAccessRequest(accessRequest), + policies: presentPolicies(user, [accessRequest]), + }; + } +); + +router.post( + "accessRequests.info", + rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), + auth(), + validate(T.AccessRequestsInfoSchema), + async (ctx: APIContext) => { + const { user } = ctx.state.auth; + const { id, documentId } = ctx.input.body; + let accessRequest: AccessRequest | null = null; + + if (id) { + accessRequest = await AccessRequest.findByPk(id); + } else if (documentId) { + const document = await Document.findByPk(documentId); + accessRequest = document + ? await AccessRequest.findPendingForUser({ + documentId: document.id, + userId: user.id, + }) + : null; + } + if (!accessRequest) { + throw NotFoundError("Access request not found"); + } + authorize(user, "read", accessRequest); + + ctx.body = { + data: presentAccessRequest(accessRequest), + policies: presentPolicies(user, [accessRequest]), + }; + } +); + +router.post( + "accessRequests.approve", + rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), + auth(), + validate(T.AccessRequestsApproveSchema), + transaction(), + async (ctx: APIContext) => { + const { id, permission } = ctx.input.body; + const { user } = ctx.state.auth; + const { transaction } = ctx.state; + + const accessRequest = await AccessRequest.findByPk(id, { + rejectOnEmpty: true, + transaction, + lock: { level: transaction.LOCK.UPDATE, of: AccessRequest }, + }); + authorize(user, "update", accessRequest); + authorize(user, "read", accessRequest.user); + + if (accessRequest.status !== AccessRequestStatus.Pending) { + throw InvalidRequestError("Access request has already been responded to"); + } + + const document = await Document.findByPk(accessRequest.documentId, { + userId: user.id, + transaction, + }); + authorize(user, "share", document); + + const membership = await UserMembership.findOne({ + where: { + userId: accessRequest.userId, + documentId: accessRequest.documentId, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!membership) { + await UserMembership.createWithCtx(ctx, { + userId: accessRequest.userId, + documentId: accessRequest.documentId, + permission: permission, + createdById: user.id, + }); + } + + await accessRequest.approve(ctx); + + ctx.body = { + data: presentAccessRequest(accessRequest), + policies: presentPolicies(user, [accessRequest]), + }; + } +); + +router.post( + "accessRequests.dismiss", + rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), + auth(), + validate(T.AccessRequestsDismissSchema), + transaction(), + async (ctx: APIContext) => { + const { id } = ctx.input.body; + const { user } = ctx.state.auth; + const { transaction } = ctx.state; + + const accessRequest = await AccessRequest.findByPk(id, { + rejectOnEmpty: true, + transaction, + lock: { level: transaction.LOCK.UPDATE, of: AccessRequest }, + }); + authorize(user, "update", accessRequest); + authorize(user, "read", accessRequest.user); + + const document = await Document.findByPk(accessRequest.documentId, { + userId: user.id, + transaction, + }); + authorize(user, "share", document); + + if (accessRequest.status === AccessRequestStatus.Pending) { + await accessRequest.dismiss(ctx); + } + + ctx.body = { + data: presentAccessRequest(accessRequest), + policies: presentPolicies(user, [accessRequest]), + }; + } +); + +export default router; diff --git a/server/routes/api/accessRequests/index.ts b/server/routes/api/accessRequests/index.ts new file mode 100644 index 0000000000..f45a0444ab --- /dev/null +++ b/server/routes/api/accessRequests/index.ts @@ -0,0 +1 @@ +export { default } from "./accessRequests"; diff --git a/server/routes/api/accessRequests/schema.ts b/server/routes/api/accessRequests/schema.ts new file mode 100644 index 0000000000..9385ae40fd --- /dev/null +++ b/server/routes/api/accessRequests/schema.ts @@ -0,0 +1,52 @@ +import { z } from "zod"; +import { DocumentPermission } from "@shared/types"; +import { BaseSchema } from "@server/routes/api/schema"; +import { zodIdType } from "@server/utils/zod"; + +const BaseIdSchema = z.object({ + id: z.string().uuid(), +}); + +export const AccessRequestsCreateSchema = BaseSchema.extend({ + body: z.object({ + documentId: zodIdType(), + }), +}); + +export type AccessRequestsCreateReq = z.infer< + typeof AccessRequestsCreateSchema +>; + +export const AccessRequestsInfoSchema = BaseSchema.extend({ + body: z + .object({ + id: z.string().uuid().optional(), + documentId: zodIdType().optional(), + }) + .refine((data) => data.id || data.documentId, { + message: "Either 'id' or 'documentId' must be provided", + path: ["body"], + }), +}); + +export type AccessRequestsInfoReq = z.infer; + +export const AccessRequestsApproveSchema = BaseSchema.extend({ + body: BaseIdSchema.extend({ + permission: z + .nativeEnum(DocumentPermission) + .default(DocumentPermission.Read), + }), +}); + +export type AccessRequestsApproveReq = z.infer< + typeof AccessRequestsApproveSchema +>; + +export const AccessRequestsDismissSchema = BaseSchema.extend({ + body: BaseIdSchema, +}); + +export type AccessRequestsDismissReq = z.infer< + typeof AccessRequestsDismissSchema +>; diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index f9235858a0..3b6b7569ed 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -51,6 +51,7 @@ import urls from "./urls"; import userMemberships from "./userMemberships"; import users from "./users"; import views from "./views"; +import accessRequests from "./accessRequests"; const api = new Koa(); const router = new Router(); @@ -92,6 +93,7 @@ router.use("/", users.routes()); router.use("/", collections.routes()); router.use("/", comments.routes()); router.use("/", documents.routes()); +router.use("/", accessRequests.routes()); router.use("/", emojis.routes()); router.use("/", pins.routes()); router.use("/", revisions.routes()); diff --git a/server/types.ts b/server/types.ts index f5d6f77fae..5d419dc290 100644 --- a/server/types.ts +++ b/server/types.ts @@ -15,6 +15,7 @@ import type { import type { BaseSchema } from "@server/routes/api/schema"; import type { AccountProvisionerResult } from "./commands/accountProvisioner"; import type { + AccessRequest, ApiKey, Attachment, AuthenticationProvider, @@ -248,6 +249,7 @@ export type DocumentEvent = BaseEvent & createdAt: string; } | DocumentMovedEvent + | AccessRequestEvent ); export type TemplateEvent = BaseEvent & { @@ -308,6 +310,12 @@ export type DocumentUserEvent = BaseEvent & { }; }; +export type AccessRequestEvent = BaseEvent & { + name: "access_requests.create"; + modelId: string; + documentId: string; +}; + export type DocumentGroupEvent = BaseEvent & { name: "documents.add_group" | "documents.remove_group"; documentId: string; @@ -483,6 +491,7 @@ export type Event = | AuthenticationProviderEvent | DocumentEvent | DocumentUserEvent + | AccessRequestEvent | DocumentMovedEvent | DocumentGroupEvent | PinEvent diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 8d810c0fa6..4d37aa16d2 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -385,6 +385,15 @@ "Sorry, an error occurred.": "Sorry, an error occurred.", "Click to retry": "Click to retry", "Back": "Back", + "Can view the document": "Can view the document", + "Can view and edit the document": "Can view and edit the document", + "Manage": "Manage", + "Full access including sharing": "Full access including sharing", + "Permissions for {{ userName }} updated": "Permissions for {{ userName }} updated", + "Failed to approve access request": "Failed to approve access request", + "Access request dismissed": "Access request dismissed", + "Failed to dismiss access request": "Failed to dismiss access request", + "Approve": "Approve", "Notification options": "Notification options", "Unknown": "Unknown", "Mentions": "Mentions", @@ -417,7 +426,6 @@ "{{ hours }}h {{ minutes }}m read": "{{ hours }}h {{ minutes }}m read", "{{ hours }}h read": "{{ hours }}h read", "{{ minutes }}m read": "{{ minutes }}m read", - "Manage": "Manage", "All members": "All members", "Everyone in the workspace": "Everyone in the workspace", "{{ count }} member": "{{ count }} member", @@ -474,7 +482,6 @@ "Access inherited from collection": "Access inherited from collection", "{{ userName }} was removed from the document": "{{ userName }} was removed from the document", "Could not remove user": "Could not remove user", - "Permissions for {{ userName }} updated": "Permissions for {{ userName }} updated", "Could not update user": "Could not update user", "Has access through <2>parent": "Has access through <2>parent", "Suspended": "Suspended", @@ -719,6 +726,9 @@ "reacted {{ emoji }} to your comment on": "reacted {{ emoji }} to your comment on", "shared": "shared", "invited you to": "invited you to", + "was granted access to": "was granted access to", + "requested access to": "requested access to", + "is requesting access to": "is requesting access to", "Choose a date": "Choose a date", "API key created. Please copy the value now as it will not be shown again.": "API key created. Please copy the value now as it will not be shown again.", "Scopes": "Scopes", @@ -874,9 +884,13 @@ "No documents found for your filters.": "No documents found for your filters.", "You’ve not got any drafts at the moment.": "You’ve not got any drafts at the moment.", "Payment Required": "Payment Required", + "Access request sent": "Access request sent", "No access to this doc": "No access to this doc", - "It doesn’t look like you have permission to access this document.": "It doesn’t look like you have permission to access this document.", - "Please request access from the document owner.": "Please request access from the document owner.", + "Your request to access this document has been sent. You will be notified once access is granted.": "Your request to access this document has been sent. You will be notified once access is granted.", + "It doesn't look like you have permission to access this document. You can request access.": "It doesn't look like you have permission to access this document. You can request access.", + "Access requested": "Access requested", + "Requesting…": "Requesting…", + "Request access": "Request access", "Not found": "Not found", "The page you’re looking for cannot be found. It might have been deleted or the link is incorrect.": "The page you’re looking for cannot be found. It might have been deleted or the link is incorrect.", "We were unable to load the document while offline.": "We were unable to load the document while offline.", @@ -1312,6 +1326,8 @@ "Receive a notification when you are given access to a collection": "Receive a notification when you are given access to a collection", "Export completed": "Export completed", "Receive a notification when an export you requested has been completed": "Receive a notification when an export you requested has been completed", + "Document access requested": "Document access requested", + "Receive a notification when a user requests access to a document you manage": "Receive a notification when a user requests access to a document you manage", "Getting started": "Getting started", "Tips on getting started with features and functionality": "Tips on getting started with features and functionality", "New features": "New features", diff --git a/shared/types.ts b/shared/types.ts index 6bf0f4313a..39860c05dd 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -480,6 +480,7 @@ export enum NotificationEventType { Onboarding = "emails.onboarding", Features = "emails.features", ExportCompleted = "emails.export_completed", + RequestDocumentAccess = "access_requests.create", } export enum NotificationChannelType { @@ -519,6 +520,7 @@ export const NotificationEventDefaults: Record = [NotificationEventType.ExportCompleted]: true, [NotificationEventType.AddUserToDocument]: true, [NotificationEventType.AddUserToCollection]: true, + [NotificationEventType.RequestDocumentAccess]: true, }; export enum UnfurlResourceType {