diff --git a/.env.sample b/.env.sample index 58e8188cae..73e3628ccf 100644 --- a/.env.sample +++ b/.env.sample @@ -36,7 +36,7 @@ COLLABORATION_URL= CDN_URL= # How many processes should be spawned. As a reasonable rule divide your servers -# available memory by 512 for a rough estimate +# available memory in megabytes by 512 for a rough estimate WEB_CONCURRENCY=1 # Generate a hex-encoded 32-byte random key. Use `openssl rand -hex 32` in your diff --git a/.oxlintrc.json b/.oxlintrc.json index 207b36d758..2a75b9875b 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -144,6 +144,11 @@ "addColumnAfter" ], "message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell." + }, + { + "name": "koa", + "importNames": ["Context", "DefaultContext"], + "message": "Use AppContext or Context from @server/types, which do not allow arbitrary properties." } ], "patterns": [ diff --git a/AGENTS.md b/AGENTS.md index 26308d61f2..bd8cde3822 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,7 +131,9 @@ yarn sequelize migration:create --name=add-field-to-table - Schedule optional background work that depends on a transaction from `afterCommit`, and use non-fatal scheduling so a queue failure does not fail the committed operation. - When changing persisted task input fields, keep readers compatible with queued inputs or migrate them before removing old fields. - For row locks used only for non-key updates or soft deletes, use `LOCK.NO_KEY_UPDATE` and set `lock.of` to the target model when includes or scopes add joins. Verify with separate transactions that foreign-key inserts and locks on unrelated joined rows do not block the operation, while competing writers to the target still wait for commit. +- When serializing migrations, poll `LockHelper.tryAcquire` in short transactions and roll back unsuccessful attempts before waiting. A blocking advisory-lock statement holds a snapshot that can stall `CREATE INDEX CONCURRENTLY` in the lock holder. Verify simultaneous startup checks let concurrent index migrations finish. - In import task completion and failure handlers, reload the import under a row lock in the transaction before changing its state. Preserve `Processed` and `Import.terminalStates` outcomes, and never mark a completed task errored. Test cancellation committed while a task runs and late failure callbacks, then reload the import and task to verify their states. +- When parallelizing requests inside a retryable import task, await all started operations with `Promise.allSettled` before propagating a failure, or cancel and drain them. Test one failed request alongside an unfinished request; the task must not reject while work from that attempt can overlap its retry. ## API Design @@ -141,6 +143,7 @@ yarn sequelize migration:create --name=add-field-to-table - Validate request data using the validation middleware and schemas - Use presenters to format API responses. - Keep API routes thin, use model methods for business logic, or commands if logic spans multiple models. +- MCP tools that call commands directly must preserve REST cross-field validation before any mutation. For document edits, reject nonempty `findText` in default or explicit replace mode, require nonempty text for append/prepend, and require nonempty `findText` plus defined text for patch while allowing empty replacement text for deletion. Test invalid combinations leave title, content, and revision unchanged. ## Authentication & Authorization @@ -212,6 +215,7 @@ yarn test:shared # All shared code tests - Log errors with appropriate context. - Return user-friendly error messages. - Never expose sensitive information in errors. +- For subscription-controlled emails, reload the recipient and check the subscription in the template's `beforeSend`, returning false when unsubscribed or missing. Caller-only checks can miss other senders such as SSO. Test the template's send path directly and assert the mailer is not called for an unsubscribed recipient. ## Performance @@ -231,5 +235,7 @@ yarn test:shared # All shared code tests - Use rateLimiter middleware for sensitive endpoints. - Follow OWASP guidelines. - Never store sensitive data in plain text. +- When changing log sanitization, sanitize error-report extras as a whole object so top-level credential keys are filtered too, matching sensitive names regardless of case, underscores, or hyphens. Sanitize each value's `toJSON` result without calling that result's root `toJSON` again. Test nested credentials and serializers returning themselves or shallow copies for filtering without recursion failures. - Use environment variables for secrets. - When reading untrusted response bodies or import archives, enforce limits while consuming data rather than truncating after buffering. For ZIP imports, set `ZipHelper` entry-count and aggregate read-byte limits as well as per-entry limits. Verify oversized responses and archives whose individually valid entries exceed the aggregate limit stop reading. +- For API import attachments, do not treat `isExternalUrl` as proof a URL is downloadable; it also accepts unresolved relative paths. Require an absolute URL with a hostname or supported base64 data before creating an attachment or queuing a download. Test missing archive-relative paths remain unchanged while remote and base64 attachments are queued. diff --git a/app/components/Header.tsx b/app/components/Header.tsx index 830364e668..3cc13751c3 100644 --- a/app/components/Header.tsx +++ b/app/components/Header.tsx @@ -177,8 +177,6 @@ const fadeStops = (height: number) => ) .join(", "); -const headerFadeStops = fadeStops(HeaderFadeHeight); - /** Raised capsule that holds header buttons on mobile, like an iOS toolbar. */ const mobilePill = css` background: ${s("menuBackground")}; @@ -344,38 +342,30 @@ const Wrapper = styled(Flex)` ${(props: WrapperProps & { theme: DefaultTheme }) => !props.$passThrough && ` - background: transparent; + /* iOS reads this color for the status bar. The clip leaves the visible background to the fade. */ + background: ${props.theme.background}; + -webkit-background-clip: text; + background-clip: text; backdrop-filter: none; - /* The blurred background extends past the header and fades out, so content blends under it. */ + /* The background extends past the header and fades out, so content blends under it. */ &::before { content: ""; position: absolute; inset: 0 0 -${HeaderFadeHeight / 2}px; z-index: -1; pointer-events: none; - background: ${transparentize(0.2, props.theme.background)}; + background: ${props.theme.background}; backdrop-filter: blur(20px); - mask-image: linear-gradient(to bottom, ${headerFadeStops}); + mask-image: linear-gradient(to bottom, ${fadeStops(HeaderFadeHeight)}); } /* A stuck tab bar or table header continues the header, so the header is solid above it. */ body:has([data-stuck]) &::before { inset: 0; - background: ${props.theme.background}; backdrop-filter: none; mask-image: none; } - - /* iOS blurs the top of an installed web app unless the sticky header has a solid background. */ - @media (display-mode: standalone) { - background: ${props.theme.background}; - - &::before { - background: ${props.theme.background}; - mask-image: linear-gradient(to bottom, ${fadeStops(HeaderFadeHeight / 2)}); - } - } `} `}; diff --git a/app/components/Icons/UnlockedPadlockIcon.tsx b/app/components/Icons/UnlockedPadlockIcon.tsx new file mode 100644 index 0000000000..18a90ca384 --- /dev/null +++ b/app/components/Icons/UnlockedPadlockIcon.tsx @@ -0,0 +1,41 @@ +type Props = { + /** The size of the icon, 24px is default to match standard icons */ + size?: number; + /** The color of the icon, defaults to the current text color */ + color?: string; +}; + +/** + * A padlock with an open shackle, the unlocked variant of PadlockIcon. + * + * @param props the icon props. + * @returns the icon element. + */ +export function UnlockedPadlockIcon({ + size = 24, + color = "currentColor", + ...rest +}: Props) { + return ( + + + + + ); +} diff --git a/app/components/Menu/MenuFilter.tsx b/app/components/Menu/MenuFilter.tsx index 6fae2db542..b5a01b43d7 100644 --- a/app/components/Menu/MenuFilter.tsx +++ b/app/components/Menu/MenuFilter.tsx @@ -200,7 +200,10 @@ export function MenuFilter({ query, onChange }: Props) { ); return ( - + !!element ); } @@ -47,4 +47,33 @@ describe("toMenuItems", () => { it("returns null when nothing matches", () => { expect(toMenuItems(items, "zzz")).toBeNull(); }); + + it("removes a separator above a group", () => { + const keys = render(undefined, [ + { type: "button", title: "Team", onClick: noop }, + { type: "separator" }, + { + type: "group", + title: "Group", + items: [{ type: "button", title: "Design", onClick: noop }], + }, + ]).map((element) => element.key); + expect(keys).toEqual(["button-0", "group-1"]); + }); + + it("keeps a separator above a group that has no visible items", () => { + const keys = render(undefined, [ + { type: "button", title: "Team", onClick: noop }, + { type: "separator" }, + { + type: "group", + title: "Group", + items: [ + { type: "button", title: "Design", visible: false, onClick: noop }, + ], + }, + { type: "button", title: "Due date", onClick: noop }, + ]).map((element) => element.key); + expect(keys).toEqual(["button-0", "separator-1", "button-2"]); + }); }); diff --git a/app/components/Menu/transformer.tsx b/app/components/Menu/transformer.tsx index 2dadb495ae..852b95cc31 100644 --- a/app/components/Menu/transformer.tsx +++ b/app/components/Menu/transformer.tsx @@ -290,7 +290,7 @@ export function toMobileMenuItems( } return ( -
+
{item.title} {groupItems}
@@ -340,7 +340,11 @@ function matchesQuery(item: MenuItem, query: string): boolean { function filterMenuItems(items: MenuItem[]): MenuItem[] { return items - .filter((item) => item.visible !== false) + .filter( + (item) => + item.visible !== false && + (item.type !== "group" || filterMenuItems(item.items).length > 0) + ) .reduce((acc, item) => { // trim separator when the previous item is also a separator. if ( @@ -352,10 +356,12 @@ function filterMenuItems(items: MenuItem[]): MenuItem[] { return [...acc, item]; }, [] as MenuItem[]) .filter((item, index, arr) => { - // trim when first or last item is a separator. + // trim when first or last item is a separator, or above a group header. if ( item.type === "separator" && - (index === 0 || index === arr.length - 1) + (index === 0 || + index === arr.length - 1 || + arr[index + 1]?.type === "group") ) { return false; } diff --git a/app/components/MouseSafeArea.tsx b/app/components/MouseSafeArea.tsx index 5efe84f25e..bcce555bb2 100644 --- a/app/components/MouseSafeArea.tsx +++ b/app/components/MouseSafeArea.tsx @@ -55,6 +55,7 @@ export const MouseSafeArea = observer(function MouseSafeArea_(props: { return (
*), + [data-menu-hidden]:first-child + &, + [role="group"]:first-child > &:first-child, + [data-menu-hidden]:first-child + [role="group"] > &:first-child { + margin-top: 0; + } + `} `; export const MenuDisclosure = styled(ExpandedIcon)` diff --git a/app/editor/components/AspectRatioLockButton.tsx b/app/editor/components/AspectRatioLockButton.tsx new file mode 100644 index 0000000000..fde8f96223 --- /dev/null +++ b/app/editor/components/AspectRatioLockButton.tsx @@ -0,0 +1,46 @@ +import { PadlockIcon } from "outline-icons"; +import type * as React from "react"; +import { useTranslation } from "react-i18next"; +import styled, { useTheme } from "styled-components"; +import { UnlockedPadlockIcon } from "~/components/Icons/UnlockedPadlockIcon"; +import ToolbarButton from "./ToolbarButton"; + +interface Props extends React.ComponentProps { + /** Whether the aspect ratio is locked. */ + isLocked: boolean; +} + +/** + * A toolbar button that shows and toggles whether media keeps its aspect ratio. + * + * @param props - the component props. + * @returns the button. + */ +export function AspectRatioLockButton({ isLocked, ...rest }: Props) { + const { t } = useTranslation(); + const theme = useTheme(); + + return ( + + {isLocked ? ( + + ) : ( + + )} + + ); +} + +const LockButton = styled(ToolbarButton)` + justify-content: center; + margin-left: -6px; + + /* The padlock glyph sits above its box center, so align it with the digits. */ + svg { + transform: translateY(1px); + } +`; diff --git a/app/editor/components/MediaDimension.tsx b/app/editor/components/MediaDimension.tsx index e216a723dd..4201326d60 100644 --- a/app/editor/components/MediaDimension.tsx +++ b/app/editor/components/MediaDimension.tsx @@ -1,13 +1,23 @@ import type { NodeSelection } from "prosemirror-state"; -import { useCallback, useEffect, useRef, useState } from "react"; +import * as Toolbar from "@radix-ui/react-toolbar"; +import { clamp } from "es-toolkit"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import styled from "styled-components"; import Flex from "@shared/components/Flex"; import Text from "@shared/components/Text"; +import { embedDefaultHeight } from "@shared/editor/components/Embed"; import { contentWidth } from "@shared/editor/lib/contentWidth"; -import { resolvePDFDimensions } from "@shared/editor/lib/pdf"; +import { isAspectRatioLocked } from "@shared/editor/queries/isAspectRatioLocked"; +import { + pdfNaturalHeight, + pdfNaturalWidth, + resolvePDFDimensions, +} from "@shared/editor/lib/pdf"; import { extraArea } from "@shared/styles"; import Input, { NativeInput, Outline } from "~/components/Input"; import { useEditor } from "./EditorContext"; +import { AspectRatioLockButton } from "./AspectRatioLockButton"; +import Tooltip from "./Tooltip"; import { useTranslation } from "react-i18next"; type Dimension = { @@ -16,15 +26,20 @@ type Dimension = { changed: "width" | "height" | "none"; }; -export function MediaDimension() { +interface Props { + /** Tooltip shown when the dimension inputs are hovered. */ + tooltip?: string; +} + +/** + * Toolbar inputs to change the width and height of the selected media node. + * + * @param props - the component props. + * @returns the dimension inputs. + */ +export function MediaDimension({ tooltip }: Props) { const isDraggingRef = useRef(false); - const boundsRef = useRef< - | { - width: { min: number; max: number }; - height: { min: number; max: number }; - } - | undefined - >(undefined); + const isSteppingRef = useRef(false); const { t } = useTranslation(); const { view, commands } = useEditor(); const { state } = view; @@ -35,10 +50,26 @@ export function MediaDimension() { const nodeType = node.type.name; const nodeWidth = node.attrs.width as number | null | undefined; const nodeHeight = node.attrs.height as number | null | undefined; + const [maxWidth] = useState(() => contentWidth(view.dom)); + + // Embeds without a stored size fill the editor width at their default height. const { width, height } = nodeType === "attachment" ? resolvePDFDimensions(nodeWidth, nodeHeight) - : { width: nodeWidth ?? 0, height: nodeHeight ?? 0 }; + : nodeType === "embed" + ? { + width: nodeWidth || maxWidth, + height: nodeHeight ?? embedDefaultHeight, + } + : { width: nodeWidth ?? 0, height: nodeHeight ?? 0 }; + + // Only PDFs and embeds can be unlocked, images and videos keep their natural aspect ratio. + const canUnlock = nodeType === "attachment" || nodeType === "embed"; + const isLocked = !canUnlock || isAspectRatioLocked(node); + + // Full-width images store their natural width, so the editor width gives their + // aspect ratio. PDFs and embeds always store dimensions with a matching ratio. + const ratioWidth = canUnlock ? width : Math.min(width, maxWidth); const [localDimension, setLocalDimension] = useState(() => ({ width: width ? String(width) : "", @@ -50,17 +81,17 @@ export function MediaDimension() { height: false, }); - if (!boundsRef.current) { - const maxWidth = contentWidth(view.dom); - const constrainedWidth = Math.min(width, maxWidth); // Ensure media width does not exceed the max width of the editor. - const aspectRatio = height / constrainedWidth; + const bounds = useMemo(() => { + // Unlocked height does not change the width, so limit it to a full-width page. + const aspectRatio = isLocked + ? height / ratioWidth + : pdfNaturalHeight / pdfNaturalWidth; - const maxHeight = Math.round(maxWidth * aspectRatio); - boundsRef.current = { + return { width: { min: 50, max: maxWidth }, - height: { min: 50, max: maxHeight }, + height: { min: 50, max: Math.round(maxWidth * aspectRatio) }, }; - } + }, [height, ratioWidth, maxWidth, isLocked]); const reset = useCallback(() => { setLocalDimension({ @@ -72,14 +103,9 @@ export function MediaDimension() { }, [width, height]); const isOutsideBounds = useCallback( - (type: "width" | "height", value: number) => { - const bounds = boundsRef.current; - if (!bounds) { - return false; - } - return value < bounds[type].min || value > bounds[type].max; - }, - [] + (type: "width" | "height", value: number) => + value < bounds[type].min || value > bounds[type].max, + [bounds] ); const handleChange = useCallback( @@ -116,86 +142,139 @@ export function MediaDimension() { [] ); - const handleBlur = useCallback(() => { - const localWidthAsNumber = localDimension.width - ? parseInt(localDimension.width, 10) - : undefined, - localHeightAsNumber = localDimension.height - ? parseInt(localDimension.height, 10) - : undefined; + const commit = useCallback( + (dimension: Dimension, hasError: boolean) => { + const localWidthAsNumber = dimension.width + ? parseInt(dimension.width, 10) + : undefined, + localHeightAsNumber = dimension.height + ? parseInt(dimension.height, 10) + : undefined; - const isUnchanged = - !localWidthAsNumber || - !localHeightAsNumber || - (localWidthAsNumber === width && localHeightAsNumber === height); + const isUnchanged = + !localWidthAsNumber || + !localHeightAsNumber || + (localWidthAsNumber === width && localHeightAsNumber === height); - const isError = - error.width || - error.height || - (localDimension.changed === "width" && - localWidthAsNumber && - isOutsideBounds("width", localWidthAsNumber)); // check width bounds here since 'onChange' error checker is debounced. + // Check bounds here since the 'onChange' error checker is debounced. + const isError = + hasError || + (dimension.changed === "width" && + localWidthAsNumber && + isOutsideBounds("width", localWidthAsNumber)) || + (dimension.changed === "height" && + localHeightAsNumber && + isOutsideBounds("height", localHeightAsNumber)); - if (isUnchanged || isError || !boundsRef.current) { - reset(); - return; - } - - const maxWidth = boundsRef.current.width.max; - // For images resized to the full width of the editor, natural width will be shown in the toolbar. - // So, we constrain it here for computing aspect ratio. - const constrainedWidth = Math.min(width, maxWidth); - - const aspectRatio = - localDimension.changed === "width" - ? height / constrainedWidth - : constrainedWidth / height; - - const finalWidth = - localDimension.changed === "width" - ? localWidthAsNumber - : Math.round(aspectRatio * localHeightAsNumber); - const finalHeight = - localDimension.changed === "height" - ? localHeightAsNumber - : Math.round(aspectRatio * localWidthAsNumber); - - if (nodeType === "image") { - commands["resizeImage"]({ - width: finalWidth, - height: finalHeight, - }); - } else if (nodeType === "attachment") { - commands["resizeAttachment"]({ - width: finalWidth, - height: finalHeight, - }); - } else if (nodeType === "video") { - commands["resizeVideo"]({ - width: finalWidth, - height: finalHeight, - }); - } - }, [ - commands, - width, - height, - localDimension, - nodeType, - error, - reset, - isOutsideBounds, - ]); - - const handleKeyDown = useCallback( - (e: React.KeyboardEvent) => { - if (e.key === "Enter") { - handleBlur(); - } else if (e.key === "Escape") { + if (isUnchanged || isError) { reset(); + return; + } + + const aspectRatio = + dimension.changed === "width" + ? height / ratioWidth + : ratioWidth / height; + + const isIndependent = canUnlock && !isLocked; + const finalWidth = + isIndependent || dimension.changed === "width" + ? localWidthAsNumber + : Math.round(aspectRatio * localHeightAsNumber); + const finalHeight = + isIndependent || dimension.changed === "height" + ? localHeightAsNumber + : Math.round(aspectRatio * localWidthAsNumber); + + if (nodeType === "image") { + commands["resizeImage"]({ + width: finalWidth, + height: finalHeight, + }); + } else if (nodeType === "attachment") { + commands["resizeAttachment"]({ + width: finalWidth, + height: finalHeight, + }); + } else if (nodeType === "video") { + commands["resizeVideo"]({ + width: finalWidth, + height: finalHeight, + }); + } else if (nodeType === "embed") { + commands["resizeEmbed"]({ + width: finalWidth, + height: finalHeight, + }); } }, - [handleBlur, reset] + [ + commands, + width, + height, + nodeType, + reset, + isOutsideBounds, + ratioWidth, + canUnlock, + isLocked, + ] + ); + + const handleBlur = useCallback(() => { + if (isSteppingRef.current) { + return; + } + commit(localDimension, error.width || error.height); + }, [commit, localDimension, error]); + + const handleToggleLock = useCallback(() => { + commands[ + nodeType === "embed" + ? "toggleEmbedAspectRatioLock" + : "toggleAttachmentAspectRatioLock" + ](); + setError({ width: false, height: false }); + }, [commands, nodeType]); + + const handleKeyDown = useCallback( + (type: "width" | "height") => + (e: React.KeyboardEvent) => { + if (e.key === "Enter") { + handleBlur(); + } else if (e.key === "Escape") { + reset(); + } else if (e.key === "ArrowUp" || e.key === "ArrowDown") { + e.preventDefault(); + + // Shift steps by 10, like number inputs in design tools. + const step = (e.shiftKey ? 10 : 1) * (e.key === "ArrowUp" ? 1 : -1); + const current = + parseInt(localDimension[type], 10) || + (type === "width" ? width : height); + const next = clamp( + current + step, + bounds[type].min, + bounds[type].max + ); + const dimension: Dimension = { + ...localDimension, + [type]: String(next), + changed: type, + }; + + setError({ width: false, height: false }); + setLocalDimension(dimension); + + // Editor commands focus the editor, so return focus to keep stepping. + const input = e.currentTarget; + isSteppingRef.current = true; + commit(dimension, false); + input.focus(); + isSteppingRef.current = false; + } + }, + [handleBlur, reset, commit, localDimension, width, height, bounds] ); // Sync dimension changes from outside, without clobbering in-progress edits @@ -233,7 +312,7 @@ export function MediaDimension() { const dimensions = nodeType === "attachment" - ? resolvePDFDimensions(newWidth) + ? resolvePDFDimensions(newWidth, newHeight) : { width: newWidth, height: newHeight }; setLocalDimension({ @@ -274,29 +353,47 @@ export function MediaDimension() { return ( - - - × - - + + + + + × + + + + + {canUnlock && ( + + + + + + )} ); } diff --git a/app/editor/components/MediaLinkEditor.tsx b/app/editor/components/MediaLinkEditor.tsx index 76ae8c1965..1908eab9e2 100644 --- a/app/editor/components/MediaLinkEditor.tsx +++ b/app/editor/components/MediaLinkEditor.tsx @@ -7,7 +7,10 @@ import { useTranslation } from "react-i18next"; import styled from "styled-components"; import Flex from "~/components/Flex"; import Tooltip from "~/components/Tooltip"; +import * as Toolbar from "@radix-ui/react-toolbar"; import Input from "~/editor/components/Input"; +import { MediaDimension } from "./MediaDimension"; +import ToolbarSeparator from "./ToolbarSeparator"; import ToolbarButton from "./ToolbarButton"; import useOnClickOutside from "~/hooks/useOnClickOutside"; @@ -115,6 +118,17 @@ export function MediaLinkEditor({ onKeyDown={handleKeyDown} readOnly={!view.editable} /> + {view.editable && node.type.name === "embed" && ( + <> + + + + + + + + + )} @@ -139,6 +153,11 @@ export function MediaLinkEditor({ ); } +const DimensionGroup = styled.div` + display: flex; + align-items: center; +`; + const Wrapper = styled(Flex)` pointer-events: all; gap: 6px; diff --git a/app/editor/components/ToolbarMenu.tsx b/app/editor/components/ToolbarMenu.tsx index fa67f235d0..70def9b64b 100644 --- a/app/editor/components/ToolbarMenu.tsx +++ b/app/editor/components/ToolbarMenu.tsx @@ -198,28 +198,28 @@ function ToolbarMenu(props: Props) { ); } + if (item.name === "dimensions") { + return ; + } + return ( - {item.name === "dimensions" ? ( - - ) : ( - - - {item.label && } - {item.icon} - - - )} + + + {item.label && } + {item.icon} + + ); })} diff --git a/app/editor/extensions/DragHandle.ts b/app/editor/extensions/DragHandle.ts index 62ba35274a..cd1a45293c 100644 --- a/app/editor/extensions/DragHandle.ts +++ b/app/editor/extensions/DragHandle.ts @@ -1,4 +1,5 @@ import { t } from "i18next"; +import type { Node as ProsemirrorNode } from "prosemirror-model"; import { NodeSelection, Plugin, PluginKey, Selection } from "prosemirror-state"; import type { EditorView } from "prosemirror-view"; import { Decoration, DecorationSet } from "prosemirror-view"; @@ -48,6 +49,9 @@ export default class DragHandle extends Extension { } get plugins() { + // The document when the mouse was last pressed in the editor. + let mouseDownDoc: ProsemirrorNode | null = null; + return [ // Marks the heading that owns the handle, so its level label in the // gutter can be hidden. @@ -145,7 +149,20 @@ export default class DragHandle extends Extension { ]); }, handleDOMEvents: { - dragstart: (view) => { + mousedown: (view) => { + mouseDownDoc = view.state.doc; + return false; + }, + dragstart: (view, event) => { + const startDoc = mouseDownDoc; + mouseDownDoc = null; + + // ProseMirror drags the node at the position from mousedown, + // so cancel the drag if the document changed since then. + if (startDoc && startDoc !== view.state.doc) { + event.preventDefault(); + return true; + } view.dom.classList.add("dragging"); return false; }, diff --git a/app/hooks/useTemplateMenuActions.tsx b/app/hooks/useTemplateMenuActions.tsx index ad1545b387..fd55b6a349 100644 --- a/app/hooks/useTemplateMenuActions.tsx +++ b/app/hooks/useTemplateMenuActions.tsx @@ -24,7 +24,8 @@ type Props = { * they are published and organizes them into appropriate sections. * * Collection-specific templates are displayed first, followed by workspace templates - * with a separator in between (if both types exist). + * in a group with a separator in between. Workspace templates are not grouped + * when there are no collection-specific templates. * * @returns An array of Action objects representing templates that can be applied * to the current document. Returns an empty array if no callback is provided. @@ -90,6 +91,10 @@ export function useTemplateMenuActions({ return []; } + if (!collectionTemplatesActions.length) { + return workspaceTemplatesActions; + } + return [ ...collectionTemplatesActions, ActionSeparator, diff --git a/plugins/azure/server/auth/azure.ts b/plugins/azure/server/auth/azure.ts index 50c89c26ea..5ac7074d2a 100644 --- a/plugins/azure/server/auth/azure.ts +++ b/plugins/azure/server/auth/azure.ts @@ -10,7 +10,7 @@ import { parseEmail } from "@shared/utils/email"; import accountProvisioner from "@server/commands/accountProvisioner"; import passportMiddleware from "@server/middlewares/passport"; import type { User } from "@server/models"; -import type { AuthenticationResult } from "@server/types"; +import type { AuthenticationResult, AppContext } from "@server/types"; import { StateStore, request, @@ -22,7 +22,7 @@ import { } from "@server/utils/passport"; import config from "../../plugin.json"; import env from "../env"; -import { createContext } from "@server/context"; +import { withUser } from "@server/context"; import UploadUserAvatarTask from "@server/queues/tasks/UploadUserAvatarTask"; import { UserFlag } from "@server/models/User"; import { getEmailVerified } from "./getEmailVerified"; @@ -57,7 +57,7 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) { result?: AuthenticationResult ) => void ) { - const context = req.ctx; + const context: AppContext = req.ctx; try { // see docs for what the fields in profile represent here: // https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens @@ -106,7 +106,7 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) { const team = await getTeamFromContext(context); const client = getClientFromOAuthState(context); const user = - context.state?.auth?.user ?? (await getUserFromOAuthState(context)); + context.auth?.user ?? (await getUserFromOAuthState(context)); const emailVerified = getEmailVerified( email, @@ -122,11 +122,7 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) { const subdomain = slugifyDomain(domain); const teamName = organization.displayName; - const ctx = createContext({ - ip: context.ip, - user, - authType: context.state?.auth?.type, - }); + const ctx = withUser(context, user); const result = await accountProvisioner(ctx, { team: { teamId: team?.id, diff --git a/plugins/discord/server/auth/discord.ts b/plugins/discord/server/auth/discord.ts index ad7cfe208d..c8fafa41e3 100644 --- a/plugins/discord/server/auth/discord.ts +++ b/plugins/discord/server/auth/discord.ts @@ -18,7 +18,7 @@ import accountProvisioner from "@server/commands/accountProvisioner"; import { InvalidRequestError, TeamDomainRequiredError } from "@server/errors"; import passportMiddleware from "@server/middlewares/passport"; import type { User } from "@server/models"; -import type { AuthenticationResult } from "@server/types"; +import type { AuthenticationResult, AppContext } from "@server/types"; import { StateStore, getTeamFromContext, @@ -31,7 +31,7 @@ import { import config from "../../plugin.json"; import env from "../env"; import { DiscordGuildError, DiscordGuildRoleError } from "../errors"; -import { createContext } from "@server/context"; +import { withUser } from "@server/context"; const router = new Router(); @@ -72,7 +72,7 @@ if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) { result?: AuthenticationResult ) => void ) { - const context = req.ctx; + const context: AppContext = req.ctx; try { const team = await getTeamFromContext(context); const client = getClientFromOAuthState(context); @@ -185,17 +185,12 @@ if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) { } } const user = - context.state?.auth?.user ?? - (await getUserFromOAuthState(context)); + context.auth?.user ?? (await getUserFromOAuthState(context)); // if a team can be inferred, we assume the user is only interested in signing into // that team in particular; otherwise, we will do a best effort at finding their account // or provisioning a new one (within AccountProvisioner) - const ctx = createContext({ - ip: context.ip, - user, - authType: context.state?.auth?.type, - }); + const ctx = withUser(context, user); const result = await accountProvisioner(ctx, { team: { teamId: team?.id, diff --git a/plugins/email/server/auth/email.ts b/plugins/email/server/auth/email.ts index e9dc65c1ea..3496196a2d 100644 --- a/plugins/email/server/auth/email.ts +++ b/plugins/email/server/auth/email.ts @@ -10,7 +10,7 @@ import Logger from "@server/logging/Logger"; import { rateLimiter } from "@server/middlewares/rateLimiter"; import validate from "@server/middlewares/validate"; import { Event, User, Team } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { VerificationCode } from "@server/utils/VerificationCode"; import { signIn } from "@server/utils/authentication"; @@ -26,7 +26,7 @@ router.post( "email", rateLimiter(RateLimiterStrategy.TenPerHour), validate(T.EmailSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { email, client, preferOTP } = ctx.input.body; const domain = parseDomain(ctx.request.hostname); @@ -99,7 +99,7 @@ router.post( } ); -const emailCallback = async (ctx: APIContext) => { +const emailCallback = async (ctx: Context) => { const { query, body } = ctx.input; const token = query?.token || body?.token; const client = query?.client || body?.client || Client.Web; diff --git a/plugins/figma/server/api/figma.ts b/plugins/figma/server/api/figma.ts index 4cbb73be0f..bd71c121bb 100644 --- a/plugins/figma/server/api/figma.ts +++ b/plugins/figma/server/api/figma.ts @@ -3,7 +3,7 @@ import auth from "@server/middlewares/authentication"; import Router from "@koa/router"; import * as T from "./schema"; import apexAuthRedirect from "@server/middlewares/apexAuthRedirect"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import validate from "@server/middlewares/validate"; import { FigmaOAuthNonceCookie, @@ -36,7 +36,7 @@ router.get( getErrorPath: () => FigmaUtils.errorUrl("unauthenticated"), }), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { code, error, state } = ctx.input.query; // Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain. @@ -52,8 +52,8 @@ router.get( verifyOAuthStateNonce(ctx, FigmaOAuthNonceCookie, parsedState.nonce); - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; try { // validation middleware ensures that code is non-null at this point. diff --git a/plugins/gitea/server/api/gitea.ts b/plugins/gitea/server/api/gitea.ts index 31ef41ddfb..86c9bac9a9 100644 --- a/plugins/gitea/server/api/gitea.ts +++ b/plugins/gitea/server/api/gitea.ts @@ -11,7 +11,7 @@ import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; import { IntegrationAuthentication, Integration } from "@server/models"; import { authorize } from "@server/policies"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { generateOAuthStateNonce, verifyOAuthStateNonce, @@ -28,12 +28,12 @@ router.post( auth(), validate(T.GiteaConnectSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { clientId, clientSecret } = ctx.input.body; const parsedUrl = new URL(ctx.input.body.url); const url = `${parsedUrl.origin}${parsedUrl.pathname}`.replace(/\/+$/, ""); - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; authorize(user, "createIntegration", user.team); await validateUrlNotPrivate(url); @@ -119,10 +119,10 @@ router.get( getErrorPath: () => GiteaUtils.errorUrl("unauthenticated"), }), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { code, error, state } = ctx.input.query; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; if (error) { ctx.redirect(GiteaUtils.errorUrl(error)); diff --git a/plugins/github/server/api/github.ts b/plugins/github/server/api/github.ts index 34402faa53..c33025a3ea 100644 --- a/plugins/github/server/api/github.ts +++ b/plugins/github/server/api/github.ts @@ -10,7 +10,7 @@ import validate from "@server/middlewares/validate"; import validateWebhook from "@server/middlewares/validateWebhook"; import { IntegrationAuthentication, Integration } from "@server/models"; import { authorize } from "@server/policies"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { verifyOAuthStateNonce } from "@server/utils/oauth"; import { RequestHelper } from "@server/utils/RequestHelper"; import { GitHubOAuthNonceCookie, GitHubUtils } from "../../shared/GitHubUtils"; @@ -35,7 +35,7 @@ router.get( getErrorPath: () => GitHubUtils.errorUrl("unauthenticated"), }), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { code, state, @@ -43,8 +43,8 @@ router.get( installation_id: installationId, setup_action: setupAction, } = ctx.input.query; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; if (error) { ctx.redirect(GitHubUtils.errorUrl(error)); @@ -129,7 +129,7 @@ router.post( return signature?.split("=")[1]; }, }), - async (ctx: APIContext) => { + async (ctx: Context) => { const { headers } = ctx.request; const body = RequestHelper.getBodyObject(ctx.request); diff --git a/plugins/gitlab/server/api/gitlab.ts b/plugins/gitlab/server/api/gitlab.ts index bb36262043..6586902096 100644 --- a/plugins/gitlab/server/api/gitlab.ts +++ b/plugins/gitlab/server/api/gitlab.ts @@ -11,7 +11,7 @@ import validate from "@server/middlewares/validate"; import validateWebhook from "@server/middlewares/validateWebhook"; import { IntegrationAuthentication, Integration } from "@server/models"; import { authorize } from "@server/policies"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { safeEqual } from "@server/utils/crypto"; import { RequestHelper } from "@server/utils/RequestHelper"; import { @@ -29,7 +29,7 @@ import * as T from "./schema"; const router = new Router(); -function getGitLabWebhookToken(ctx: APIContext): string | undefined { +function getGitLabWebhookToken(ctx: Context): string | undefined { const signatureHeader = ctx.request.headers["x-gitlab-token"]; return Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader; } @@ -39,11 +39,11 @@ router.post( auth(), validate(T.GitLabConnectSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { url: rawUrl, clientId, clientSecret } = ctx.input.body; const url = rawUrl?.replace(/\/+$/, ""); - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; authorize(user, "createIntegration", user.team); @@ -150,10 +150,10 @@ router.get( getErrorPath: () => GitLabUtils.errorUrl("unauthenticated"), }), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { code, error, state } = ctx.input.query; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; if (error) { ctx.redirect(GitLabUtils.errorUrl(error)); @@ -355,7 +355,7 @@ router.post( }, getSignatureFromHeader: getGitLabWebhookToken, }), - async (ctx: APIContext) => { + async (ctx: Context) => { const { headers } = ctx.request; const body = RequestHelper.getBodyObject(ctx.request); const teamIds: Array = ctx.state.webhookTeamIds ?? [null]; diff --git a/plugins/google/server/auth/google.ts b/plugins/google/server/auth/google.ts index a03b2d0929..c32e30ef03 100644 --- a/plugins/google/server/auth/google.ts +++ b/plugins/google/server/auth/google.ts @@ -11,7 +11,7 @@ import accountProvisioner from "@server/commands/accountProvisioner"; import { TeamDomainRequiredError } from "@server/errors"; import passportMiddleware from "@server/middlewares/passport"; import { AuthenticationProvider, User } from "@server/models"; -import type { AuthenticationResult } from "@server/types"; +import type { AuthenticationResult, AppContext } from "@server/types"; import { StateStore, getTeamFromContext, @@ -22,7 +22,7 @@ import { } from "@server/utils/passport"; import config from "../../plugin.json"; import env from "../env"; -import { createContext } from "@server/context"; +import { withUser } from "@server/context"; import { GmailAccountCreationError } from "../errors"; const router = new Router(); @@ -65,14 +65,14 @@ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) { result?: AuthenticationResult ) => void ) { - const context = req.ctx; + const context: AppContext = req.ctx; try { // "domain" is the Google Workspaces domain const domain = profile._json.hd; let team = await getTeamFromContext(context); const client = getClientFromOAuthState(context); const user = - context.state?.auth?.user ?? (await getUserFromOAuthState(context)); + context.auth?.user ?? (await getUserFromOAuthState(context)); // No profile domain means a personal gmail account, and no team means // the request came from the apex domain rather than a workspace @@ -125,11 +125,7 @@ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) { // if a team can be inferred, we assume the user is only interested in signing into // that team in particular; otherwise, we will do a best effort at finding their account // or provisioning a new one (within AccountProvisioner) - const ctx = createContext({ - ip: context.ip, - user, - authType: context.state?.auth?.type, - }); + const ctx = withUser(context, user); const result = await accountProvisioner(ctx, { team: { teamId: team?.id, diff --git a/plugins/linear/server/api/linear.ts b/plugins/linear/server/api/linear.ts index 27ac66a89d..5dd35af74f 100644 --- a/plugins/linear/server/api/linear.ts +++ b/plugins/linear/server/api/linear.ts @@ -10,7 +10,7 @@ import validate from "@server/middlewares/validate"; import { IntegrationAuthentication, Integration } from "@server/models"; import { authorize } from "@server/policies"; import { afterCommit } from "@server/storage/transaction"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { verifyOAuthStateNonce } from "@server/utils/oauth"; import { Linear } from "../linear"; import UploadIntegrationLogoTask from "@server/queues/tasks/UploadIntegrationLogoTask"; @@ -39,10 +39,10 @@ router.get( getErrorPath: () => LinearUtils.errorUrl("unauthenticated"), }), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { code, error, state } = ctx.input.query; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; // Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain. if (error) { diff --git a/plugins/notion/server/api/notion.ts b/plugins/notion/server/api/notion.ts index 9d4e0ee18a..c685a3694b 100644 --- a/plugins/notion/server/api/notion.ts +++ b/plugins/notion/server/api/notion.ts @@ -7,7 +7,7 @@ import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; import { Integration, IntegrationAuthentication } from "@server/models"; import { authorize } from "@server/policies"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { verifyOAuthStateNonce } from "@server/utils/oauth"; import { NotionClient } from "../notion"; import * as T from "./schema"; @@ -32,10 +32,10 @@ router.get( getErrorPath: () => NotionUtils.errorUrl("unauthenticated"), }), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { code, error, state } = ctx.input.query; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; // Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain. if (error) { diff --git a/plugins/oidc/server/auth/oidcRouter.ts b/plugins/oidc/server/auth/oidcRouter.ts index 9eed7a9c85..5fdfdbd59c 100644 --- a/plugins/oidc/server/auth/oidcRouter.ts +++ b/plugins/oidc/server/auth/oidcRouter.ts @@ -1,6 +1,6 @@ import passport from "@outlinewiki/koa-passport"; import JWT from "jsonwebtoken"; -import type { Context, Request } from "koa"; +import type { Request } from "koa"; import type Router from "@koa/router"; import { get } from "es-toolkit/compat"; import { toError } from "@shared/utils/error"; @@ -13,7 +13,7 @@ import { AuthenticationError } from "@server/errors"; import Logger from "@server/logging/Logger"; import passportMiddleware from "@server/middlewares/passport"; import type { User } from "@server/models"; -import type { AuthenticationResult } from "@server/types"; +import type { AuthenticationResult, AppContext } from "@server/types"; import { LogoutTokenStore } from "@server/utils/LogoutTokenStore"; import { StateStore, @@ -28,7 +28,7 @@ import config from "../../plugin.json"; import env from "../env"; import { OIDCStrategy } from "./OIDCStrategy"; import { resolveProviderId } from "./resolveProviderId"; -import { createContext } from "@server/context"; +import { withUser } from "@server/context"; import { OIDCMalformedUserInfoError } from "../errors"; export interface OIDCEndpoints { @@ -84,7 +84,7 @@ export function createOIDCRouter( result?: AuthenticationResult ) => void ) { - const context = req.ctx; + const context: AppContext = req.ctx; try { // Some providers require a POST request to the userinfo endpoint, add them as exceptions here. const usePostMethod = [ @@ -142,8 +142,7 @@ export function createOIDCRouter( const team = await getTeamFromContext(context); const client = getClientFromOAuthState(context); const user = - context.state?.auth?.user ?? - (await getUserFromOAuthState(context)); + context.auth?.user ?? (await getUserFromOAuthState(context)); const { domain } = parseEmail(email); const providerId = await resolveProviderId( @@ -193,11 +192,7 @@ export function createOIDCRouter( avatarUrl = null; } - const ctx = createContext({ - ip: context.ip, - user, - authType: context.state?.auth?.type, - }); + const ctx = withUser(context, user); const result = await accountProvisioner(ctx, { team: { teamId: team?.id, @@ -252,7 +247,7 @@ export function createOIDCRouter( // ended so the provider can scope the logout and skip a confirmation prompt, // while `post_logout_redirect_uri` returns the user to Outline afterwards. // https://openid.net/specs/openid-connect-rpinitiated-1_0.html - router.get(`${config.id}.logout`, async (ctx: Context) => { + router.get(`${config.id}.logout`, async (ctx: AppContext) => { const idToken = await logoutTokens.consume(ctx); if (!endpoints.logoutURL) { diff --git a/plugins/passkeys/server/api/passkeys.ts b/plugins/passkeys/server/api/passkeys.ts index afb32630e1..1801282434 100644 --- a/plugins/passkeys/server/api/passkeys.ts +++ b/plugins/passkeys/server/api/passkeys.ts @@ -1,7 +1,7 @@ import auth from "@server/middlewares/authentication"; import validate from "@server/middlewares/validate"; import { UserPasskey } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { AuthenticationType } from "@server/types"; import Router from "@koa/router"; import * as T from "./schema"; @@ -17,8 +17,8 @@ router.post( auth({ type: AuthenticationType.APP }), pagination(), validate(T.PasskeysListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { pagination } = ctx.state; const passkeys = await UserPasskey.findAll({ @@ -40,10 +40,10 @@ router.post( auth({ type: AuthenticationType.APP }), validate(T.PasskeysUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, name } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const passkey = await UserPasskey.findByPk(id, { rejectOnEmpty: true, @@ -64,10 +64,10 @@ router.post( auth({ type: AuthenticationType.APP }), validate(T.PasskeysDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const passkey = await UserPasskey.findByPk(id, { rejectOnEmpty: true, diff --git a/plugins/passkeys/server/auth/passkeys.test.ts b/plugins/passkeys/server/auth/passkeys.test.ts index 5bf0fc249a..0c9326bcb7 100644 --- a/plugins/passkeys/server/auth/passkeys.test.ts +++ b/plugins/passkeys/server/auth/passkeys.test.ts @@ -9,7 +9,7 @@ import { buildUser, } from "@server/test/factories"; import { getTestServer } from "@server/test/support"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { PasskeyBrand } from "@shared/utils/passkeys"; import { getExpectedOrigin, @@ -82,13 +82,13 @@ function buildNoneAttestationResponse(challenge: string, rpId: string) { } describe("getExpectedOrigin", () => { - // Helper to mock APIContext for testing + // Helper to mock Context for testing const createMockContext = (options: { protocol: string; hostname: string; host: string; forwardedPort?: string; - }): APIContext => + }): Context => ({ protocol: options.protocol, request: { @@ -101,7 +101,7 @@ describe("getExpectedOrigin", () => { return undefined; }, } as unknown, - }) as unknown as APIContext; + }) as unknown as Context; it("should construct origin with non-standard HTTPS port from X-Forwarded-Port", () => { const ctx = createMockContext({ diff --git a/plugins/passkeys/server/auth/passkeys.ts b/plugins/passkeys/server/auth/passkeys.ts index e2717cf2d7..57a627ced7 100644 --- a/plugins/passkeys/server/auth/passkeys.ts +++ b/plugins/passkeys/server/auth/passkeys.ts @@ -10,13 +10,12 @@ import Router from "@koa/router"; import { randomBytes } from "node:crypto"; import { toError } from "@shared/utils/error"; import { User, UserPasskey, Team } from "@server/models"; -import { apiContext } from "@server/middlewares/apiContext"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; import env from "@server/env"; import { AuthorizationError, ValidationError } from "@server/errors"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { AuthenticationType } from "@server/types"; import Logger from "@server/logging/Logger"; import Redis from "@server/storage/redis"; @@ -32,16 +31,16 @@ const rpName = env.APP_NAME; const CHALLENGE_EXPIRY_MS = Minute.ms * 5; // Helper to get RP ID (domain) - for simplicity, we can use the hostname but strip port. -const getRpID = (ctx: APIContext) => ctx.request.hostname; +const getRpID = (ctx: Context) => ctx.request.hostname; /** * Helper to get the expected origin for WebAuthn. * Properly handles non-standard ports by checking X-Forwarded-Port header. * - * @param ctx - the API context. + * @param ctx - the context. * @returns the expected origin (protocol://host:port). */ -export const getExpectedOrigin = (ctx: APIContext): string => { +export const getExpectedOrigin = (ctx: Context): string => { const protocol = ctx.protocol; const hostname = ctx.request.hostname; @@ -108,8 +107,8 @@ export const isUniqueAuthenticator = (aaguid: string | undefined): boolean => router.post( "passkeys.generateRegistrationOptions", auth({ type: AuthenticationType.APP }), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; authorize(user, "createUserPasskey", user.team); // Fetch existing passkeys to exclude them from registration @@ -148,12 +147,9 @@ router.post( "passkeys.verifyRegistration", auth({ type: AuthenticationType.APP }), validate(T.PasskeysVerifyRegistrationSchema), - // Auth routes have no API context by default, without it the resulting event - // has no actor or team and cannot appear in the audit log. - apiContext(), transaction(), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const body = ctx.input.body; authorize(user, "createUserPasskey", user.team); @@ -266,14 +262,14 @@ export const getPasskeyLoginRedirect = ( * ceremony and returns the authenticated session via the outline:// deep link, * mirroring the existing SSO desktop flow. */ -router.get("passkey", (ctx: APIContext) => { +router.get("passkey", (ctx: Context) => { ctx.redirect(getPasskeyLoginRedirect(ctx.query.client)); }); router.post( "passkeys.generateAuthenticationOptions", validate(T.PasskeysGenerateAuthenticationOptionsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const options = await generateAuthenticationOptions({ rpID: getRpID(ctx), userVerification: "preferred", @@ -295,7 +291,7 @@ router.post( router.post( "passkeys.verifyAuthentication", validate(T.PasskeysVerifyAuthenticationSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const body = ctx.input.body; const { challengeId, client = Client.Web } = body; diff --git a/plugins/slack/server/api/hooks.ts b/plugins/slack/server/api/hooks.ts index 7a5b8c6dda..1ad6e88d7c 100644 --- a/plugins/slack/server/api/hooks.ts +++ b/plugins/slack/server/api/hooks.ts @@ -23,7 +23,7 @@ import { import { SearchQuerySource } from "@server/models/SearchQuery"; import SearchProviderManager from "@server/utils/SearchProviderManager"; import { can } from "@server/policies"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { safeEqual } from "@server/utils/crypto"; import { opts } from "@server/utils/i18n"; import env from "../env"; @@ -38,7 +38,7 @@ const router = new Router(); router.post( "hooks.unfurl", validate(T.HooksUnfurlSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { // See URL verification handshake documentation on this page: // https://api.slack.com/apis/connections/events-api if ("challenge" in ctx.input.body) { @@ -133,7 +133,7 @@ router.post( router.post( "hooks.interactive", validate(T.HooksInteractiveSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { payload } = ctx.input.body; let parsed; @@ -208,7 +208,7 @@ router.post( router.post( "hooks.slack", validate(T.HooksSlackCommandSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { token, team_id, user_id, text } = ctx.input.body; verifySlackToken(token); diff --git a/plugins/slack/server/auth/slack.ts b/plugins/slack/server/auth/slack.ts index ed54c275b9..e1709ca342 100644 --- a/plugins/slack/server/auth/slack.ts +++ b/plugins/slack/server/auth/slack.ts @@ -19,7 +19,7 @@ import { } from "@server/models"; import { authorize } from "@server/policies"; import { sequelize } from "@server/storage/database"; -import type { APIContext, AuthenticationResult } from "@server/types"; +import type { Context, AuthenticationResult, AppContext } from "@server/types"; import { verifyOAuthStateNonce } from "@server/utils/oauth"; import { getClientFromOAuthState, @@ -37,7 +37,7 @@ import { SlackUtils, SlackOAuthNonceCookie, } from "plugins/slack/shared/SlackUtils"; -import { createContext } from "@server/context"; +import { withUser } from "@server/context"; type SlackProfile = Profile & { team: { @@ -88,20 +88,16 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) { result?: AuthenticationResult ) => void ) { - const context = req.ctx; + const context: AppContext = req.ctx; try { const team = await getTeamFromContext(context); const client = getClientFromOAuthState(context); const user = - context.state?.auth?.user ?? (await getUserFromOAuthState(context)); + context.auth?.user ?? (await getUserFromOAuthState(context)); const { domain } = parseEmail(profile.user.email); - const ctx = createContext({ - ip: context.ip, - user, - authType: context.state?.auth?.type, - }); + const ctx = withUser(context, user); const result = await accountProvisioner(ctx, { team: { teamId: team?.id, @@ -156,9 +152,9 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) { }), getErrorPath: () => SlackUtils.errorUrl("unauthenticated"), }), - async (ctx: APIContext) => { + async (ctx: Context) => { const { code, error, state } = ctx.input.query; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (error) { ctx.redirect(SlackUtils.errorUrl(error)); diff --git a/plugins/slack/server/processors/SlackProcessor.ts b/plugins/slack/server/processors/SlackProcessor.ts index 26d771994d..f1fceb465b 100644 --- a/plugins/slack/server/processors/SlackProcessor.ts +++ b/plugins/slack/server/processors/SlackProcessor.ts @@ -1,7 +1,7 @@ import { differenceInMilliseconds } from "date-fns"; import { Op } from "sequelize"; import { IntegrationService, IntegrationType } from "@shared/types"; -import { Minute } from "@shared/utils/time"; +import { Minute, Second } from "@shared/utils/time"; import { Document, Integration, Collection, Team } from "@server/models"; import BaseProcessor from "@server/queues/processors/BaseProcessor"; import type { @@ -16,6 +16,9 @@ import env from "../env"; import { presentMessageAttachment } from "../presenters/messageAttachment"; export default class SlackProcessor extends BaseProcessor { + /** Time limit in milliseconds for posts to the Slack webhook. */ + static fetchTimeout = 10 * Second.ms; + static applicableEvents: Event["name"][] = [ "documents.publish", "revisions.create", @@ -90,6 +93,7 @@ export default class SlackProcessor extends BaseProcessor { headers: { "Content-Type": "application/json", }, + timeout: SlackProcessor.fetchTimeout, body: JSON.stringify({ text: `👋 Hey there! When documents are published or updated in the *${collection.name}* collection on ${env.APP_NAME} they will be posted to this channel!`, attachments: [ @@ -169,6 +173,7 @@ export default class SlackProcessor extends BaseProcessor { headers: { "Content-Type": "application/json", }, + timeout: SlackProcessor.fetchTimeout, body: JSON.stringify({ text, attachments: [ diff --git a/plugins/storage/server/api/files.ts b/plugins/storage/server/api/files.ts index 810da4ca08..e5bc1cbb64 100644 --- a/plugins/storage/server/api/files.ts +++ b/plugins/storage/server/api/files.ts @@ -20,7 +20,7 @@ import AttachmentHelper from "@server/models/helpers/AttachmentHelper"; import { authorize } from "@server/policies"; import FileStorage from "@server/storage/files"; import type LocalStorage from "@server/storage/files/LocalStorage"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { getJWTPayload } from "@server/utils/jwt"; import { ByteRangeHelper } from "../utils/ByteRangeHelper"; @@ -40,8 +40,8 @@ router.post( env.FILE_STORAGE_IMPORT_MAX_SIZE ), }), - async (ctx: APIContext) => { - const actor = ctx.state.auth.user; + async (ctx: Context) => { + const actor = ctx.auth.user; const { key, sig } = ctx.input.body; const file = ctx.input.file; @@ -104,8 +104,8 @@ router.get( // Signed requests are authorized by their signature alone. auth({ optional: true, skip: (ctx) => !!ctx.query.sig }), validate(T.FilesGetSchema), - async (ctx: APIContext) => { - const actor = ctx.state.auth.user; + async (ctx: Context) => { + const actor = ctx.auth.user; const key = getKeyFromContext(ctx); const forceDownload = !!ctx.input.query.download; const isSignedRequest = !!ctx.input.query.sig; @@ -206,7 +206,7 @@ function verifyUploadSignature(sig: string, key: string) { } } -function getKeyFromContext(ctx: APIContext): string { +function getKeyFromContext(ctx: Context): string { const { key, sig } = ctx.input.query; if (sig) { const payload = getJWTPayload(sig); diff --git a/plugins/webhooks/server/api/webhookSubscriptions.ts b/plugins/webhooks/server/api/webhookSubscriptions.ts index 9b8024fee9..e6a28ceefa 100644 --- a/plugins/webhooks/server/api/webhookSubscriptions.ts +++ b/plugins/webhooks/server/api/webhookSubscriptions.ts @@ -10,7 +10,7 @@ import { authorize } from "@server/policies"; import pagination, { paginateQuery, } from "@server/routes/api/middlewares/pagination"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { AuthenticationType } from "@server/types"; import { QueryHelper } from "@server/storage/QueryHelper"; import presentWebhookSubscription from "../presenters/webhookSubscription"; @@ -23,9 +23,9 @@ router.post( auth({ role: UserRole.Admin }), pagination(), validate(T.WebhookSubscriptionsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, query } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "listWebhookSubscription", user.team); @@ -84,9 +84,9 @@ router.post( }), validate(T.WebhookSubscriptionsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { name, url, secret, events } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createWebhookSubscription", user.team); @@ -114,10 +114,10 @@ router.post( }), validate(T.WebhookSubscriptionsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const webhookSubscription = await WebhookSubscription.findByPk(id, { rejectOnEmpty: true, @@ -145,10 +145,10 @@ router.post( }), validate(T.WebhookSubscriptionsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, name, url, secret, events } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const webhookSubscription = await WebhookSubscription.findByPk(id, { rejectOnEmpty: true, diff --git a/server/commands/accountProvisioner.ts b/server/commands/accountProvisioner.ts index 0161bdf2f8..9801785af5 100644 --- a/server/commands/accountProvisioner.ts +++ b/server/commands/accountProvisioner.ts @@ -23,9 +23,9 @@ import { sequelize } from "@server/storage/database"; import SyncUserGroupsTask from "@server/queues/tasks/SyncUserGroupsTask"; import teamProvisioner from "./teamProvisioner"; import userProvisioner from "./userProvisioner"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { addSeconds } from "date-fns"; -import { createContext } from "@server/context"; +import { withTransaction, withUser } from "@server/context"; type Props = { /** Details of the user logging in from SSO provider */ @@ -89,7 +89,7 @@ export type AccountProvisionerResult = { }; async function accountProvisioner( - ctx: APIContext, + ctx: Context, { user: userParams, team: teamParams, @@ -100,7 +100,7 @@ async function accountProvisioner( let result; let emailMatchOnly; - const actor = ctx.state.auth?.user; + const actor = ctx.auth?.user; // If the user is already logged in and is an admin of the team then we // allow them to connect or reconnect an authentication provider. @@ -120,15 +120,9 @@ async function accountProvisioner( if (!isConnected && providers.length === 1) { // Update in place so that existing user authentications stay linked. await sequelize.transaction((transaction) => - providers[0].updateWithCtx( - createContext({ - user: actor, - authType: ctx.context.auth?.type, - ip: ctx.context.ip, - transaction, - }), - { providerId: authenticationProviderParams.providerId } - ) + providers[0].updateWithCtx(withTransaction(ctx, transaction), { + providerId: authenticationProviderParams.providerId, + }) ); } else if (!isConnected) { await team.$create( @@ -230,9 +224,9 @@ async function accountProvisioner( userId: user.id, actorId: user.id, teamId: user.teamId, - ip: ctx.context.ip, + ip: ctx.ip, }, - { transaction: ctx.state.transaction } + { transaction: ctx.transaction } ); } @@ -287,17 +281,12 @@ async function accountProvisioner( * @returns a promise that resolves when the collection has been created. */ export async function provisionFirstCollection( - ctx: APIContext, + ctx: Context, team: Team, user: User ) { await sequelize.transaction(async (transaction) => { - const context = createContext({ - user, - authType: ctx.context.auth?.type, - ip: ctx.context.ip, - transaction, - }); + const context = withTransaction(withUser(ctx, user), transaction); const collection = await Collection.createWithCtx(context, { name: "Welcome", diff --git a/server/commands/attachmentCreator.ts b/server/commands/attachmentCreator.ts index deb02968b6..979cea908f 100644 --- a/server/commands/attachmentCreator.ts +++ b/server/commands/attachmentCreator.ts @@ -4,7 +4,7 @@ import type { User } from "@server/models"; import { Attachment } from "@server/models"; import AttachmentHelper from "@server/models/helpers/AttachmentHelper"; import FileStorage from "@server/storage/files"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import type { RequestInit } from "@server/utils/fetch"; type BaseProps = { @@ -19,7 +19,7 @@ type BaseProps = { /** The preset to use for the attachment */ preset: AttachmentPreset; /** The request context */ - ctx: APIContext; + ctx: Context; /** Options to pass to fetch when downloading the attachment */ fetchOptions?: RequestInit; }; @@ -51,7 +51,7 @@ export default async function attachmentCreator({ if (id) { const existing = await Attachment.findOne({ where: { id, teamId: user.teamId }, - transaction: ctx.context.transaction, + transaction: ctx.transaction, }); if (existing) { diff --git a/server/commands/collectionDuplicator.ts b/server/commands/collectionDuplicator.ts index 6fbf9e7939..f6fb147577 100644 --- a/server/commands/collectionDuplicator.ts +++ b/server/commands/collectionDuplicator.ts @@ -3,7 +3,7 @@ import Logger from "@server/logging/Logger"; import { Collection } from "@server/models"; import DuplicateCollectionDocumentsTask from "@server/queues/tasks/DuplicateCollectionDocumentsTask"; import { afterCommit } from "@server/storage/transaction"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; type Props = { /** The collection to duplicate */ @@ -17,16 +17,16 @@ type Props = { * published documents within the collection are duplicated asynchronously by a * background task once the new collection is committed. * - * @param ctx the API context containing the acting user and transaction. + * @param ctx the context containing the acting user and transaction. * @param props the collection to duplicate and optional overrides. * @returns the duplicated collection. */ export default async function collectionDuplicator( - ctx: APIContext, + ctx: Context, { collection, name }: Props ): Promise { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const duplicated = Collection.build({ name: name ?? collection.name, @@ -54,7 +54,7 @@ export default async function collectionDuplicator( collectionId: duplicated.id, originalCollectionId: collection.id, actorId: user.id, - ip: ctx.context.ip ?? null, + ip: ctx.ip ?? null, }); if (transaction) { diff --git a/server/commands/documentCreator.test.ts b/server/commands/documentCreator.test.ts index d1013d6dfd..fd152de55a 100644 --- a/server/commands/documentCreator.test.ts +++ b/server/commands/documentCreator.test.ts @@ -7,14 +7,14 @@ import { buildFileOperation, buildTemplate, } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import documentCreator from "./documentCreator"; describe("documentCreator", () => { it("should attribute Markdown mentions to the authenticated writer", async () => { const user = await buildUser(); const mentioned = await buildUser({ teamId: user.teamId }); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Mentions", text: `@[${mentioned.name}](mention://user/${mentioned.id})`, @@ -40,7 +40,7 @@ describe("documentCreator", () => { "This is rich content" ).toJSON(); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Test Document", text: testText, @@ -63,7 +63,7 @@ describe("documentCreator", () => { const testText = "This is plain text"; - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Test Document", text: testText, @@ -81,7 +81,7 @@ describe("documentCreator", () => { teamId: user.teamId, }); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Empty Document", collectionId: collection.id, @@ -101,7 +101,7 @@ describe("documentCreator", () => { teamId: user.teamId, }); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Test Document", text: "This is a test document", @@ -124,7 +124,7 @@ describe("documentCreator", () => { teamId: user.teamId, }); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Custom Document", text: "Custom content", @@ -147,7 +147,7 @@ describe("documentCreator", () => { teamId: user.teamId, }); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Draft Document", text: "Draft content", @@ -166,7 +166,7 @@ describe("documentCreator", () => { teamId: user.teamId, }); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Published Document", text: "Published content", @@ -182,7 +182,7 @@ describe("documentCreator", () => { const user = await buildUser(); await expect( - withAPIContext(user, (ctx) => + withContext(user, (ctx) => documentCreator(ctx, { title: "Invalid Document", text: "Content", @@ -212,7 +212,7 @@ describe("documentCreator", () => { collectionId: collection.id, }); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "From Template", template, @@ -241,7 +241,7 @@ describe("documentCreator", () => { collectionId: collection.id, }); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { template, collectionId: collection.id, @@ -267,7 +267,7 @@ describe("documentCreator", () => { }); await expect( - withAPIContext(user, (ctx) => + withContext(user, (ctx) => documentCreator(ctx, { template, state: Buffer.from("some state"), @@ -296,7 +296,7 @@ describe("documentCreator", () => { collectionId: collection.id, }); - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Child Document", text: "Child content", @@ -323,7 +323,7 @@ describe("documentCreator", () => { const sourceMetadata = { fileName: "test" }; - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "fileOperation Document", text: "fileOperation content", @@ -349,7 +349,7 @@ describe("documentCreator", () => { const customEmojiId = "550e8400-e29b-41d4-a716-446655440000"; const text = `Check this :${customEmojiId}: custom emoji`; - const document = await withAPIContext(user, (ctx) => + const document = await withContext(user, (ctx) => documentCreator(ctx, { title: "Custom Emoji Test", text, diff --git a/server/commands/documentCreator.ts b/server/commands/documentCreator.ts index 9e6f8a9a58..e836bf7dae 100644 --- a/server/commands/documentCreator.ts +++ b/server/commands/documentCreator.ts @@ -6,8 +6,9 @@ import { Collection, Document, type Template } from "@server/models"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import { validateOwnerIds } from "@server/models/helpers/owners"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; +import { toHookContext } from "@server/context"; import { authorize } from "@server/policies"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { assertPresent } from "@server/validation"; import personalCollectionLoader from "./personalCollectionLoader"; @@ -59,20 +60,20 @@ type CreateLocation = { * "personal" refers to the personal collection of the user, which is created * when it does not exist yet. * - * @param ctx the API context containing the acting user. + * @param ctx the context containing the acting user. * @param location the requested collection and/or parent document. * @returns the resolved collection and parent document, when applicable. * @throws AuthorizationError when the user may not create the document. */ export async function authorizeDocumentCreate( - ctx: APIContext, + ctx: Context, { collectionId, parentDocumentId }: CreateLocation ): Promise<{ collection?: Collection | null; parentDocument?: Document | null; }> { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; if (parentDocumentId) { const parentDocument = await Document.findByPk(parentDocumentId, { @@ -112,19 +113,19 @@ export async function authorizeDocumentCreate( * requires create permission on the destination — separate from the update * permission that governs editing a draft's content. * - * @param ctx the API context containing the acting user. + * @param ctx the context containing the acting user. * @param document the document being published. * @param collectionId the destination collection, required when publishing a draft that has none. * @returns the resolved destination collection. * @throws AuthorizationError when the user may not publish into the collection. */ export async function authorizeDocumentPublish( - ctx: APIContext, + ctx: Context, document: Document, collectionId?: string | null ): Promise { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; let collection = document.collection; if (document.isDraft) { @@ -160,7 +161,7 @@ export async function authorizeDocumentPublish( } export default async function documentCreator( - ctx: APIContext, + ctx: Context, { title, text, @@ -190,8 +191,8 @@ export default async function documentCreator( ownerIds, }: Props ): Promise { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const templateId = template ? template.id : undefined; const eventData = importId || apiImportId ? { source: "import" } : undefined; @@ -302,7 +303,7 @@ export default async function documentCreator( if (validatedOwnerIds.length > 0) { authorize(user, "manageOwners", reloaded); reloaded.ownerIds = validatedOwnerIds; - await reloaded.save({ ...ctx.context, silent: true }); + await reloaded.save({ ...toHookContext(ctx), silent: true }); await reloaded.grantOwnerAccess(ctx, validatedOwnerIds); } diff --git a/server/commands/documentDuplicator.test.ts b/server/commands/documentDuplicator.test.ts index f04698a070..4996e19671 100644 --- a/server/commands/documentDuplicator.test.ts +++ b/server/commands/documentDuplicator.test.ts @@ -8,7 +8,7 @@ import { buildDocument, buildUser, } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import { generateUrlId } from "@server/utils/url"; import documentDuplicator from "./documentDuplicator"; @@ -20,7 +20,7 @@ describe("documentDuplicator", () => { teamId: user.teamId, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentDuplicator(ctx, { document: original, collection: original.collection, @@ -43,7 +43,7 @@ describe("documentDuplicator", () => { icon: "👋", }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentDuplicator(ctx, { document: original, collection: original.collection, @@ -100,7 +100,7 @@ describe("documentDuplicator", () => { await collection.addDocumentToStructure(child2); await collection.addDocumentToStructure(child3); - await withAPIContext(user, (ctx) => + await withContext(user, (ctx) => documentDuplicator(ctx, { title: "duplicate", document: original, @@ -127,7 +127,7 @@ describe("documentDuplicator", () => { teamId: user.teamId, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentDuplicator(ctx, { document: original, collection: original.collection, @@ -233,7 +233,7 @@ describe("documentDuplicator", () => { text: `See [child 2](${child2.path}) and the [parent](/doc/${original.id}).`, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentDuplicator(ctx, { document: original, collection, @@ -304,7 +304,7 @@ describe("documentDuplicator", () => { }, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentDuplicator(ctx, { document: original, collection, @@ -343,7 +343,7 @@ describe("documentDuplicator", () => { text: `See [other](${other.path}) and [elsewhere](https://example.com/doc/${other.urlId}).`, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentDuplicator(ctx, { document: original, collection, @@ -377,7 +377,7 @@ describe("documentDuplicator", () => { ].join("\n\n"), }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentDuplicator(ctx, { document: original, collection, @@ -399,7 +399,7 @@ describe("documentDuplicator", () => { fullWidth: true, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentDuplicator(ctx, { document: original, collection: original.collection, @@ -432,7 +432,7 @@ describe("documentDuplicator", () => { collectionId: collection.id, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentDuplicator(ctx, { document: original, collection: original.collection, diff --git a/server/commands/documentDuplicator.ts b/server/commands/documentDuplicator.ts index 8543878970..35387c725a 100644 --- a/server/commands/documentDuplicator.ts +++ b/server/commands/documentDuplicator.ts @@ -4,7 +4,7 @@ import { Collection, Document } from "@server/models"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import type { DocumentReference } from "@server/models/helpers/ProsemirrorHelper"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { generateUrlId } from "@server/utils/url"; import documentCreator from "./documentCreator"; @@ -62,12 +62,12 @@ type DuplicateItem = { * Duplicates a document, optionally including its child documents. Links * between the duplicated documents are remapped to point at the copies. * - * @param ctx the API context containing the acting user and transaction. + * @param ctx the context containing the acting user and transaction. * @param props the document to duplicate and optional overrides. * @returns the duplicated documents. */ export default async function documentDuplicator( - ctx: APIContext, + ctx: Context, { document, collection, parentDocumentId, title, publish, recursive }: Props ): Promise { return duplicateRoots(ctx, { @@ -82,12 +82,12 @@ export default async function documentDuplicator( * Duplicates several documents as one unit, so that links between them are * remapped to the copies no matter which of the documents they cross between. * - * @param ctx the API context containing the acting user and transaction. + * @param ctx the context containing the acting user and transaction. * @param props the documents to duplicate and optional overrides. * @returns the duplicated documents. */ export async function documentsDuplicator( - ctx: APIContext, + ctx: Context, { documents, collection, publish, recursive }: ManyProps ): Promise { return duplicateRoots(ctx, { @@ -99,7 +99,7 @@ export async function documentsDuplicator( } async function duplicateRoots( - ctx: APIContext, + ctx: Context, { roots, collection, @@ -203,7 +203,7 @@ async function duplicateRoots( item.original.dataValues.content !== undefined ? item.original : await Document.findByPk(item.original.id, { - transaction: ctx.state.transaction, + transaction: ctx.transaction, rejectOnEmpty: true, }); diff --git a/server/commands/documentImporter.ts b/server/commands/documentImporter.ts index 2661395a26..fa6b4a22c5 100644 --- a/server/commands/documentImporter.ts +++ b/server/commands/documentImporter.ts @@ -6,7 +6,7 @@ import { serializer } from "@server/editor"; import { traceFunction } from "@server/logging/tracing"; import type { User } from "@server/models"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { DocumentConverter } from "@server/converters/DocumentConverter"; import { InvalidRequestError } from "../errors"; @@ -15,7 +15,7 @@ type Props = { mimeType: string; fileName: string; content: Buffer | string; - ctx: APIContext; + ctx: Context; }; type ImportResult = { diff --git a/server/commands/documentMover.test.ts b/server/commands/documentMover.test.ts index 67b7c06538..f78d952c91 100644 --- a/server/commands/documentMover.test.ts +++ b/server/commands/documentMover.test.ts @@ -9,7 +9,7 @@ import { buildUser, } from "@server/test/factories"; import documentMover from "./documentMover"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; describe("documentMover", () => { it("should move within a collection", async () => { @@ -24,7 +24,7 @@ describe("documentMover", () => { collectionId: collection.id, teamId: team.id, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: collection.id, @@ -54,7 +54,7 @@ describe("documentMover", () => { title: "Child document", text: "content", }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: collection.id, @@ -92,7 +92,7 @@ describe("documentMover", () => { text: "content", }); await collection.addDocumentToStructure(newDocument); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: collection.id, @@ -133,7 +133,7 @@ describe("documentMover", () => { text: "content", }); await collection.addDocumentToStructure(newDocument); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: newCollection.id, @@ -182,7 +182,7 @@ describe("documentMover", () => { teamId: collection.teamId, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: newCollection.id, @@ -242,7 +242,7 @@ describe("documentMover", () => { teamId: team.id, }); - await withAPIContext(user, (ctx) => + await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: newCollection.id, @@ -283,7 +283,7 @@ describe("documentMover", () => { }); } - await withAPIContext(user, (ctx) => + await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: personal.id, @@ -314,7 +314,7 @@ describe("documentMover", () => { teamId: team.id, }); - await withAPIContext(user, (ctx) => + await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: personal.id, @@ -347,7 +347,7 @@ describe("documentMover", () => { teamId: team.id, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: null, diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index 0e5602f183..126386f1e7 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -1,7 +1,7 @@ import { Transaction } from "sequelize"; import { traceFunction } from "@server/logging/tracing"; import { Document, Collection, Pin } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; type Props = { /** Document which is being moved */ @@ -21,7 +21,7 @@ type Result = { }; async function documentMover( - ctx: APIContext, + ctx: Context, { document, collectionId, @@ -30,8 +30,8 @@ async function documentMover( index, }: Props ): Promise { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const collectionChanged = collectionId !== document.collectionId; const previousCollectionId = document.collectionId; diff --git a/server/commands/documentRestorer.ts b/server/commands/documentRestorer.ts index d8379d7d2d..ee9f832462 100644 --- a/server/commands/documentRestorer.ts +++ b/server/commands/documentRestorer.ts @@ -3,7 +3,7 @@ import { ParamRequiredError, ValidationError } from "@server/errors"; import { Collection, Revision } from "@server/models"; import type { Document } from "@server/models"; import { authorize } from "@server/policies"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; type Props = { /** The document to restore. Must be loaded with `paranoid: false`. */ @@ -20,7 +20,7 @@ type Props = { * are re-attached to the destination collection's structure. Authorizes the * acting user against the document before any other check. * - * @param ctx - the API context, providing the acting user and transaction. + * @param ctx - the context, providing the acting user and transaction. * @param props - the document and restore options. * @returns the restored document. * @throws AuthorizationError if the user cannot restore the document. @@ -28,11 +28,11 @@ type Props = { * @throws NotFoundError if the given revision does not exist. */ async function documentRestorer( - ctx: APIContext, + ctx: Context, { document, collectionId, revisionId }: Props ): Promise { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; if (!document.deletedAt && !document.archivedAt) { // restore an active document to a specific revision diff --git a/server/commands/documentUpdater.test.ts b/server/commands/documentUpdater.test.ts index b87175a6b9..bf4df5b336 100644 --- a/server/commands/documentUpdater.test.ts +++ b/server/commands/documentUpdater.test.ts @@ -17,7 +17,7 @@ import { buildDocument, buildUser, } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import documentUpdater from "./documentUpdater"; describe("documentUpdater", () => { @@ -41,7 +41,7 @@ describe("documentUpdater", () => { }); const newMention = `@[Writer](mention://user/${user.id})`; - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { document, text: @@ -83,7 +83,7 @@ describe("documentUpdater", () => { }); const originalMentions = DocumentHelper.parseMentions(document); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { document, text: `${mention} updated` }) ); @@ -97,7 +97,7 @@ describe("documentUpdater", () => { teamId: user.teamId, }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Changed", document, @@ -120,7 +120,7 @@ describe("documentUpdater", () => { userId: creator.id, }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Changed", publish: true, @@ -138,7 +138,7 @@ describe("documentUpdater", () => { teamId: user.teamId, }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { title: document.title, document, @@ -164,7 +164,7 @@ describe("documentUpdater", () => { document.state = Buffer.from(Y.encodeStateAsUpdate(ydoc)); await document.save(); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Changed content", document, @@ -185,7 +185,7 @@ describe("documentUpdater", () => { teamId: user.teamId, }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { title: "New Title", document, @@ -213,7 +213,7 @@ describe("documentUpdater", () => { }); const loadedCollection = document.collection; - const result = await withAPIContext(user, (ctx) => + const result = await withContext(user, (ctx) => documentUpdater(ctx, { title: "New Title", document, @@ -234,7 +234,7 @@ describe("documentUpdater", () => { teamId: user.teamId, }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Changed", document, @@ -267,7 +267,7 @@ describe("documentUpdater", () => { text: "Initial", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Appended", document, @@ -294,7 +294,7 @@ describe("documentUpdater", () => { text: "**Bold**", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Appended", document, @@ -346,7 +346,7 @@ describe("documentUpdater", () => { }; await document.save(); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Appended", document, @@ -382,7 +382,7 @@ describe("documentUpdater", () => { text: "Initial", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "\n\nAppended", document, @@ -415,7 +415,7 @@ describe("documentUpdater", () => { text: "Existing", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Prepended", document, @@ -442,7 +442,7 @@ describe("documentUpdater", () => { text: "**Bold**", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Prepended", document, @@ -478,7 +478,7 @@ describe("documentUpdater", () => { text: "Existing", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Prepended\n\n", document, @@ -588,7 +588,7 @@ describe("documentUpdater", () => { }); await expect( - withAPIContext(user, (ctx) => + withContext(user, (ctx) => documentUpdater(ctx, { text: "replacement", findText: "nonexistent text", @@ -718,7 +718,7 @@ describe("documentUpdater", () => { text: "- First item\n- Second item\n- Third item", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "* Updated item", findText: "* Second item", @@ -750,7 +750,7 @@ describe("documentUpdater", () => { text: "1. Alpha one.\n2. Bravo two:\n\n :::info\n A note inside item two.\n :::\n3. Charlie three.", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "Amber", findText: "Alpha", @@ -803,7 +803,7 @@ describe("documentUpdater", () => { const lastRow = await lineContaining(document, "gamma"); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: `${lastRow}\n\n## New\n\nbody text`, findText: lastRow, @@ -834,7 +834,7 @@ describe("documentUpdater", () => { const middleRow = await lineContaining(document, "beta"); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: `${middleRow}\n\n## New`, findText: middleRow, @@ -855,7 +855,7 @@ describe("documentUpdater", () => { text: "* alpha\n* beta\n* gamma", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "- beta EDITED", findText: "* beta", @@ -887,7 +887,7 @@ describe("documentUpdater", () => { text: "> alpha\n>\n> beta\n>\n> gamma\n\n## Notes", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "beta EDITED", findText: "> beta", @@ -924,7 +924,7 @@ describe("documentUpdater", () => { const lastRow = await lineContaining(document, "two"); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: `${lastRow}\n${lastRow.replace("two", "three").replace("2", "3")}`, findText: lastRow, @@ -968,7 +968,7 @@ describe("documentUpdater", () => { }, }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "* beta EDITED\n* delta", findText: "* beta", @@ -1018,7 +1018,7 @@ describe("documentUpdater", () => { }, }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "", findText: "* alpha\n", @@ -1046,7 +1046,7 @@ describe("documentUpdater", () => { text: "# Title\n\n* only item\n\nafter", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "plain text now", findText: "* only item", @@ -1073,7 +1073,7 @@ describe("documentUpdater", () => { text: "* alpha\n* beta\n* gamma", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "1. beta EDITED", findText: "* beta", @@ -1101,7 +1101,7 @@ describe("documentUpdater", () => { text: "1. one\n2. two\n3. three", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "2) two EDITED", findText: "2. two", @@ -1134,7 +1134,7 @@ describe("documentUpdater", () => { text: "a. alpha", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "a. alpha\n1) numeric", findText: "a. alpha", @@ -1168,7 +1168,7 @@ describe("documentUpdater", () => { text: "* alpha\n * one\n * two\n * three\n* beta", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: " - two EDITED", findText: " * two", @@ -1212,7 +1212,7 @@ describe("documentUpdater", () => { text: "> alpha\n>\n> beta", }); - document = await withAPIContext(user, (ctx) => + document = await withContext(user, (ctx) => documentUpdater(ctx, { text: "> beta\n\n## New\n\nbody", findText: "> beta", @@ -2426,7 +2426,7 @@ describe("documentUpdater", () => { const user = await buildUser(); const document = await buildDocument({ teamId: user.teamId }); - const result = await withAPIContext(user, (ctx) => + const result = await withContext(user, (ctx) => documentUpdater(ctx, { document, text: "- [ ] one\n\n+++ Title\nBody\n+++", @@ -2450,7 +2450,7 @@ describe("documentUpdater", () => { content, }); - const result = await withAPIContext(user, (ctx) => + const result = await withContext(user, (ctx) => documentUpdater(ctx, { document, text: replacement, diff --git a/server/commands/documentUpdater.ts b/server/commands/documentUpdater.ts index 2eadc0bc98..579168786d 100644 --- a/server/commands/documentUpdater.ts +++ b/server/commands/documentUpdater.ts @@ -4,7 +4,7 @@ import { DocumentConflictError, ValidationError } from "@server/errors"; import { Document } from "@server/models"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import { TextHelper } from "@server/models/helpers/TextHelper"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; type Props = { /** The existing document */ @@ -51,7 +51,7 @@ type Props = { * @returns Document The updated document */ export default async function documentUpdater( - ctx: APIContext, + ctx: Context, { document, title, @@ -72,8 +72,8 @@ export default async function documentUpdater( ownerIds, }: Props ): Promise { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const cId = collectionId || document.collectionId; const previousOwnerIds = document.ownerIds ?? []; diff --git a/server/commands/groupsSyncer.ts b/server/commands/groupsSyncer.ts index b40014fd62..f876fcae66 100644 --- a/server/commands/groupsSyncer.ts +++ b/server/commands/groupsSyncer.ts @@ -4,7 +4,7 @@ import Logger from "@server/logging/Logger"; import type { AuthenticationProvider } from "@server/models"; import { ExternalGroup, Group, GroupUser } from "@server/models"; import type { User, Team } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import type { ExternalGroupData } from "@server/utils/GroupSyncProvider"; interface Props { @@ -32,15 +32,15 @@ interface GroupSyncResult { * groups. Upserts ExternalGroup records, auto-creates Group records when * needed, and manages GroupUser memberships. * - * @param ctx - API context with transaction. + * @param ctx - context with transaction. * @param props - sync parameters. * @returns result summary. */ async function groupsSyncer( - ctx: APIContext, + ctx: Context, { user, team, authenticationProvider, externalGroups }: Props ): Promise { - const { transaction } = ctx.state; + const { transaction } = ctx; const result: GroupSyncResult = { groupsCreated: 0, membershipsAdded: 0, diff --git a/server/commands/personalCollectionLoader.ts b/server/commands/personalCollectionLoader.ts index 692d7b9f40..daba742c3a 100644 --- a/server/commands/personalCollectionLoader.ts +++ b/server/commands/personalCollectionLoader.ts @@ -1,24 +1,24 @@ import { PersonalCollectionId } from "@shared/constants"; -import { createContext } from "@server/context"; +import { withTransaction } from "@server/context"; import { Collection } from "@server/models"; import { authorize } from "@server/policies"; import { sequelize } from "@server/storage/database"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; /** * Loads the personal collection of the acting user, and creates it when the * user does not have one yet. * - * @param ctx the API context containing the acting user. + * @param ctx the context containing the acting user. * @returns the personal collection, with the memberships of the user loaded. * @throws AuthorizationError when the collection does not exist and the user * may not create it. */ export default async function personalCollectionLoader( - ctx: APIContext + ctx: Context ): Promise { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const existing = await Collection.findPersonal(user, { transaction }); if (existing) { @@ -33,14 +33,7 @@ export default async function personalCollectionLoader( // The creation lock is only held inside a transaction. return sequelize.transaction((innerTransaction) => - Collection.findOrCreatePersonal( - createContext({ - user, - authType: ctx.state.auth.type, - ip: ctx.context.ip, - transaction: innerTransaction, - }) - ) + Collection.findOrCreatePersonal(withTransaction(ctx, innerTransaction)) ); } @@ -49,7 +42,7 @@ export default async function personalCollectionLoader( * the acting user, which is created when it does not exist yet. Other values * are returned unchanged. * - * @param ctx the API context containing the acting user. + * @param ctx the context containing the acting user. * @param collectionId the requested collectionId. * @returns the resolved collectionId. * @throws AuthorizationError when the collection does not exist and the user @@ -57,7 +50,7 @@ export default async function personalCollectionLoader( */ export async function resolvePersonalCollectionId< T extends string | null | undefined, ->(ctx: APIContext, collectionId: T): Promise { +>(ctx: Context, collectionId: T): Promise { return collectionId === PersonalCollectionId ? (await personalCollectionLoader(ctx)).id : collectionId; diff --git a/server/commands/pinCreator.test.ts b/server/commands/pinCreator.test.ts index 79f8d0e46c..7a2d0bbf05 100644 --- a/server/commands/pinCreator.test.ts +++ b/server/commands/pinCreator.test.ts @@ -1,6 +1,6 @@ import { Event } from "@server/models"; import { buildDocument, buildUser } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import pinCreator from "./pinCreator"; describe("pinCreator", () => { @@ -11,7 +11,7 @@ describe("pinCreator", () => { teamId: user.teamId, }); - const pin = await withAPIContext(user, (ctx) => + const pin = await withContext(user, (ctx) => pinCreator({ ctx, user, @@ -37,7 +37,7 @@ describe("pinCreator", () => { teamId: user.teamId, }); - const pin = await withAPIContext(user, (ctx) => + const pin = await withContext(user, (ctx) => pinCreator({ ctx, user, diff --git a/server/commands/pinCreator.ts b/server/commands/pinCreator.ts index e0ed518cf7..02b26e9e9e 100644 --- a/server/commands/pinCreator.ts +++ b/server/commands/pinCreator.ts @@ -3,11 +3,11 @@ import type { WhereOptions } from "sequelize"; import { Sequelize, Op } from "sequelize"; import type { User } from "@server/models"; import { Pin } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; type Props = { /** The request context */ - ctx: APIContext; + ctx: Context; /** The user creating the pin */ user: User; /** The document to pin */ @@ -33,7 +33,7 @@ export default async function pinCreator({ ...rest }: Props): Promise { let { index } = rest; - const { transaction } = ctx.context; + const { transaction } = ctx; const where: WhereOptions = { teamId: user.teamId, ...(collectionId ? { collectionId } : { collectionId: { [Op.is]: null } }), diff --git a/server/commands/starCreator.test.ts b/server/commands/starCreator.test.ts index 31b34f8fdc..e371bd4293 100644 --- a/server/commands/starCreator.test.ts +++ b/server/commands/starCreator.test.ts @@ -1,6 +1,6 @@ import { Star, Event } from "@server/models"; import { buildDocument, buildUser } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import starCreator from "./starCreator"; describe("starCreator", () => { @@ -11,7 +11,7 @@ describe("starCreator", () => { teamId: user.teamId, }); - const star = await withAPIContext(user, (ctx) => + const star = await withContext(user, (ctx) => starCreator({ ctx, documentId: document.id, @@ -42,7 +42,7 @@ describe("starCreator", () => { index: "P", }); - const star = await withAPIContext(user, (ctx) => + const star = await withContext(user, (ctx) => starCreator({ ctx, documentId: document.id, diff --git a/server/commands/starCreator.ts b/server/commands/starCreator.ts index a969282a1b..7553fe8238 100644 --- a/server/commands/starCreator.ts +++ b/server/commands/starCreator.ts @@ -3,7 +3,7 @@ import type { WhereOptions } from "sequelize"; import { Sequelize } from "sequelize"; import type { User } from "@server/models"; import { Star } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; type Props = { /** The user creating the star */ @@ -15,7 +15,7 @@ type Props = { /** The sorted index for the star in the sidebar If no index is provided then it will be at the end */ index?: string; /** The request context */ - ctx: APIContext; + ctx: Context; }; /** @@ -48,7 +48,7 @@ export default async function starCreator({ Sequelize.literal('"star"."index" collate "C"'), ["updatedAt", "DESC"], ], - transaction: ctx.state.transaction, + transaction: ctx.transaction, }); // create a star at the beginning of the list diff --git a/server/commands/subscriptionCreator.ts b/server/commands/subscriptionCreator.ts index 8b279d710b..445eb598de 100644 --- a/server/commands/subscriptionCreator.ts +++ b/server/commands/subscriptionCreator.ts @@ -5,15 +5,15 @@ import type { Collection, Document, User } from "@server/models"; import { Subscription, Event } from "@server/models"; import { sequelize } from "@server/storage/database"; import type { - APIContext, CollectionOwnerEvent, + Context, DocumentEvent, RevisionEvent, } from "@server/types"; type Props = { /** The request context, which also contains the user creating the subscription */ - ctx: APIContext; + ctx: Context; /** The document to subscribe to */ documentId?: string; /** The collection to subscribe to */ @@ -39,7 +39,7 @@ export default async function subscriptionCreator({ event, resubscribe = true, }: Props): Promise { - const { user } = ctx.state.auth; + const { user } = ctx.auth; let rows: SubscriptionRow[]; const now = new Date(); @@ -58,7 +58,7 @@ export default async function subscriptionCreator({ now, }, type: QueryTypes.SELECT, - transaction: ctx.state.transaction, + transaction: ctx.transaction, } ); } else if (collectionId) { @@ -76,7 +76,7 @@ export default async function subscriptionCreator({ now, }, type: QueryTypes.SELECT, - transaction: ctx.state.transaction, + transaction: ctx.transaction, } ); } else { diff --git a/server/commands/teamCreator.ts b/server/commands/teamCreator.ts index 0b16cd201a..8c62db9cea 100644 --- a/server/commands/teamCreator.ts +++ b/server/commands/teamCreator.ts @@ -1,7 +1,7 @@ import type { InferCreationAttributes } from "sequelize"; import { traceFunction } from "@server/logging/tracing"; import { Team } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; type Props = { /** The displayed name of the team */ @@ -22,7 +22,7 @@ type Props = { }; async function teamCreator( - ctx: APIContext, + ctx: Context, { name, subdomain, avatarUrl, authenticationProviders }: Props ): Promise { if (!avatarUrl?.startsWith("http")) { @@ -30,7 +30,7 @@ async function teamCreator( } const availableSubdomain = await Team.findAvailableSubdomain(subdomain, { - transaction: ctx.state.transaction, + transaction: ctx.transaction, }); return await Team.createWithCtx( ctx, diff --git a/server/commands/teamProvisioner.ts b/server/commands/teamProvisioner.ts index 44d3bbb568..4a0019c6f9 100644 --- a/server/commands/teamProvisioner.ts +++ b/server/commands/teamProvisioner.ts @@ -13,7 +13,7 @@ import { retryOnUniqueConstraintError, sequelize, } from "@server/storage/database"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; type TeamProvisionerResult = { team: Team; @@ -45,7 +45,7 @@ type Props = { }; async function teamProvisioner( - ctx: APIContext, + ctx: Context, { teamId, name, domain, subdomain, avatarUrl, authenticationProvider }: Props ): Promise { const where = teamId diff --git a/server/commands/teamUpdater.test.ts b/server/commands/teamUpdater.test.ts index 4274ff087c..aca609d3b6 100644 --- a/server/commands/teamUpdater.test.ts +++ b/server/commands/teamUpdater.test.ts @@ -5,7 +5,7 @@ import { randomString } from "@shared/random"; import { CommentingAccess, Plan, TeamPreference } from "@shared/types"; import { Team } from "@server/models"; import { buildAdmin, buildTeam, buildUser } from "@server/test/factories"; -import { setCloudHosted, withAPIContext } from "@server/test/support"; +import { setCloudHosted, withContext } from "@server/test/support"; import teamUpdater from "./teamUpdater"; describe("teamUpdater", () => { @@ -27,7 +27,7 @@ describe("teamUpdater", () => { team, user, run: () => - withAPIContext(user, (ctx) => + withContext(user, (ctx) => teamUpdater(ctx, { params: { preferences: { [TeamPreference.DefaultShareExpiryDays]: days }, @@ -78,7 +78,7 @@ describe("teamUpdater", () => { const newValue = CommentingAccess.None; - const updatedTeam = await withAPIContext(user, (ctx) => + const updatedTeam = await withContext(user, (ctx) => teamUpdater(ctx, { params: { preferences: { @@ -104,7 +104,7 @@ describe("teamUpdater", () => { await team.save(); // Try to set the same value again - const updatedTeam = await withAPIContext(user, (ctx) => + const updatedTeam = await withContext(user, (ctx) => teamUpdater(ctx, { params: { preferences: { @@ -134,7 +134,7 @@ describe("teamUpdater", () => { await team.save(); // Pass an object with the same values (but different reference) - const updatedTeam = await withAPIContext(user, (ctx) => + const updatedTeam = await withContext(user, (ctx) => teamUpdater(ctx, { params: { preferences: { @@ -166,7 +166,7 @@ describe("teamUpdater", () => { team.setPreference(TeamPreference.ViewersCanExport, true); await team.save(); - const updatedTeam = await withAPIContext(user, (ctx) => + const updatedTeam = await withContext(user, (ctx) => teamUpdater(ctx, { params: { preferences: { @@ -194,7 +194,7 @@ describe("teamUpdater", () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); - const updatedTeam = await withAPIContext(user, (ctx) => + const updatedTeam = await withContext(user, (ctx) => teamUpdater(ctx, { params: { name: "Updated Team Name" }, user, @@ -214,7 +214,7 @@ describe("teamUpdater", () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); - const updatedTeam = await withAPIContext(user, (ctx) => + const updatedTeam = await withContext(user, (ctx) => teamUpdater(ctx, { params: { subdomain }, user, @@ -232,7 +232,7 @@ describe("teamUpdater", () => { const user = await buildUser({ teamId: team.id }); await expect( - withAPIContext(user, (ctx) => + withContext(user, (ctx) => teamUpdater(ctx, { params: { subdomain }, user, diff --git a/server/commands/teamUpdater.ts b/server/commands/teamUpdater.ts index 155ed890ed..83e64e143e 100644 --- a/server/commands/teamUpdater.ts +++ b/server/commands/teamUpdater.ts @@ -5,7 +5,7 @@ import { ValidationError } from "@server/errors"; import type { User } from "@server/models"; import { Collection, Team, TeamDomain } from "@server/models"; import { authorize } from "@server/policies"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; type Props = { params: Partial> & { allowedDomains?: string[] }; @@ -13,7 +13,7 @@ type Props = { team: Team; }; -const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => { +const teamUpdater = async (ctx: Context, { params, user, team }: Props) => { const { allowedDomains, preferences, subdomain, ...attributes } = params; team.fill(attributes); @@ -25,7 +25,7 @@ const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => { teamId: team.id, ownerId: null, }, - transaction: ctx.state.transaction, + transaction: ctx.transaction, }); if (!collection) { @@ -40,7 +40,7 @@ const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => { const existing = await Team.findOne({ where: { subdomain: newSubdomain }, paranoid: false, - transaction: ctx.state.transaction, + transaction: ctx.transaction, }); if (existing) { @@ -54,7 +54,7 @@ const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => { if (allowedDomains !== undefined) { const existingAllowedDomains = await TeamDomain.findAll({ where: { teamId: team.id }, - transaction: ctx.state.transaction, + transaction: ctx.transaction, }); // Only keep existing domains if they are still in the list of allowed domains diff --git a/server/commands/userInviter.test.ts b/server/commands/userInviter.test.ts index 25f75af5e4..a00ce409a2 100644 --- a/server/commands/userInviter.test.ts +++ b/server/commands/userInviter.test.ts @@ -2,13 +2,13 @@ import { faker } from "@faker-js/faker"; import { UserRole } from "@shared/types"; import { buildTeam, buildUser } from "@server/test/factories"; import userInviter from "./userInviter"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import { TeamDomain } from "@server/models"; describe("userInviter", () => { it("should return sent invites", async () => { const user = await buildUser(); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => userInviter(ctx, { invites: [ { @@ -24,7 +24,7 @@ describe("userInviter", () => { it("should filter empty invites", async () => { const user = await buildUser(); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => userInviter(ctx, { invites: [ { @@ -48,7 +48,7 @@ describe("userInviter", () => { createdById: user.id, }); - await withAPIContext(user, (ctx) => + await withContext(user, (ctx) => expect( userInviter(ctx, { invites: [ @@ -74,7 +74,7 @@ describe("userInviter", () => { createdById: user.id, }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => userInviter(ctx, { invites: [ { @@ -92,7 +92,7 @@ describe("userInviter", () => { it("should filter obviously bunk emails", async () => { const user = await buildUser(); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => userInviter(ctx, { invites: [ { @@ -108,7 +108,7 @@ describe("userInviter", () => { it("should not send duplicates", async () => { const user = await buildUser(); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => userInviter(ctx, { invites: [ { @@ -130,7 +130,7 @@ describe("userInviter", () => { it("should not send invites to existing team members", async () => { const email = faker.internet.email().toLowerCase(); const user = await buildUser({ email }); - const response = await withAPIContext(user, (ctx) => + const response = await withContext(user, (ctx) => userInviter(ctx, { invites: [ { diff --git a/server/commands/userInviter.ts b/server/commands/userInviter.ts index a14c404b63..908c25dee6 100644 --- a/server/commands/userInviter.ts +++ b/server/commands/userInviter.ts @@ -5,7 +5,7 @@ import env from "@server/env"; import Logger from "@server/logging/Logger"; import { User, Team } from "@server/models"; import { UserFlag } from "@server/models/User"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { DomainNotAllowedError } from "@server/errors"; import { authorize, can } from "@server/policies"; @@ -21,14 +21,14 @@ type Props = { }; export default async function userInviter( - ctx: APIContext, + ctx: Context, { invites, suppressEmail }: Props ): Promise<{ sent: Invite[]; unsent: Invite[]; users: User[]; }> { - const { user } = ctx.state.auth; + const { user } = ctx.auth; const team = await Team.findByPk(user.teamId, { rejectOnEmpty: true }); if (invites.some((invite) => invite.role === UserRole.Guest)) { diff --git a/server/commands/userProvisioner.ts b/server/commands/userProvisioner.ts index dc85d013ae..8f7683aab8 100644 --- a/server/commands/userProvisioner.ts +++ b/server/commands/userProvisioner.ts @@ -15,7 +15,7 @@ import { UserAuthentication, } from "@server/models"; import { sequelize } from "@server/storage/database"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { UserFlag } from "@server/models/User"; import UploadUserAvatarTask from "@server/queues/tasks/UploadUserAvatarTask"; @@ -67,7 +67,7 @@ type Props = { }; export default async function userProvisioner( - ctx: APIContext, + ctx: Context, { name, email, diff --git a/server/context.test.ts b/server/context.test.ts new file mode 100644 index 0000000000..692401c485 --- /dev/null +++ b/server/context.test.ts @@ -0,0 +1,37 @@ +import { sequelize } from "@server/storage/database"; +import { buildUser } from "@server/test/factories"; +import { AuthenticationType } from "@server/types"; +import { createContext, withTransaction, withUser } from "./context"; + +describe("withUser", () => { + it("should act as the given user and keep the other fields", async () => { + const original = await buildUser(); + const user = await buildUser(); + const ctx = createContext({ + user: original, + authType: AuthenticationType.API, + ip: "127.0.0.1", + }); + + const derived = withUser(ctx, user); + expect(derived.auth.user).toBe(user); + expect(derived.auth.type).toEqual(AuthenticationType.API); + expect(derived.ip).toEqual("127.0.0.1"); + expect(ctx.auth.user).toBe(original); + }); +}); + +describe("withTransaction", () => { + it("should run in the given transaction and keep the other fields", async () => { + const user = await buildUser(); + const ctx = createContext({ user, ip: "127.0.0.1" }); + + await sequelize.transaction(async (transaction) => { + const derived = withTransaction(ctx, transaction); + expect(derived.transaction).toBe(transaction); + expect(derived.auth).toBe(ctx.auth); + expect(derived.ip).toEqual("127.0.0.1"); + expect(ctx.transaction).toBeUndefined(); + }); + }); +}); diff --git a/server/context.ts b/server/context.ts index 910465e9e5..e0f48358da 100644 --- a/server/context.ts +++ b/server/context.ts @@ -1,10 +1,26 @@ import type { Transaction } from "sequelize"; import type { User } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { AppContext, Authentication, Context } from "@server/types"; import { AuthenticationType } from "@server/types"; +/** The fields of a context that model hooks read from query options. */ +export interface HookContextFields { + /** The authentication for the actor performing the mutation. */ + auth: Authentication; + /** The transaction the mutation runs in. */ + transaction?: Transaction; + /** The IP address of the actor. */ + ip?: string; +} + /** - * Factory to create a new API context. + * Factory to create a new context. + * + * @param options.user the actor for the context. + * @param options.authType the type of authentication used by the actor. + * @param options.ip the IP address of the actor, defaults to the last active IP. + * @param options.transaction the transaction for database mutations. + * @returns the context. */ export function createContext({ user, @@ -17,16 +33,50 @@ export function createContext({ ip?: string | null; transaction?: Transaction; }) { - const auth = { user, type: authType }; return { - state: { - auth, - transaction, - }, - context: { - auth, - ip: ip ?? user?.lastActiveIp, - transaction, - }, - } as APIContext; + auth: { user, type: authType }, + ip: ip ?? user?.lastActiveIp, + transaction, + } as Context; +} + +/** + * Derives a context from an existing one that acts as the given user. + * + * @param ctx the context to derive from. + * @param user the actor for the new context. + * @returns the derived context. + */ +export function withUser(ctx: AppContext | Context, user?: User) { + return createContext({ + user, + authType: ctx.auth?.type, + ip: ctx.ip, + transaction: ctx.transaction, + }); +} + +/** + * Derives a context from an existing one that runs in the given transaction. + * + * @param ctx the context to derive from. + * @param transaction the transaction for the new context. + * @returns the derived context. + */ +export function withTransaction(ctx: Context, transaction: Transaction) { + return { auth: ctx.auth, ip: ctx.ip, transaction } as Context; +} + +/** + * Extracts the fields that model hooks read from a context, for use as query options. + * + * @param ctx the context to read from. + * @returns the hook context fields. + */ +export function toHookContext(ctx: Context): HookContextFields { + return { + auth: ctx.auth, + transaction: ctx.transaction, + ip: ctx.ip, + }; } diff --git a/server/logging/sentry.ts b/server/logging/sentry.ts index ec5f3e85bd..0d6e65b326 100644 --- a/server/logging/sentry.ts +++ b/server/logging/sentry.ts @@ -23,17 +23,17 @@ export function requestErrorHandler(error: any, ctx: AppContext) { scope.setTag("request_id", requestId as string); } - const authType = ctx.state?.auth?.type ?? undefined; + const authType = ctx.auth?.type ?? undefined; if (authType) { scope.setTag("auth_type", authType); } - const teamId = ctx.state?.auth?.user?.teamId ?? undefined; + const teamId = ctx.auth?.user?.teamId ?? undefined; if (teamId) { scope.setTag("team_id", teamId); } - const userId = ctx.state?.auth?.user?.id ?? undefined; + const userId = ctx.auth?.user?.id ?? undefined; if (userId) { scope.setUser({ id: userId, diff --git a/server/mcp/tools/attachments.ts b/server/mcp/tools/attachments.ts index 5925563bb0..5e0a83d54c 100644 --- a/server/mcp/tools/attachments.ts +++ b/server/mcp/tools/attachments.ts @@ -60,7 +60,7 @@ export function attachmentTools(server: McpServer, scopes: string[]) { async ({ contentType, name, size }, extra) => { try { const ctx = buildAPIContext(extra); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const team = await Team.findByPk(user.teamId, { rejectOnEmpty: true, }); diff --git a/server/mcp/tools/collections.ts b/server/mcp/tools/collections.ts index 0c8c94af4b..56d08e2fd7 100644 --- a/server/mcp/tools/collections.ts +++ b/server/mcp/tools/collections.ts @@ -212,7 +212,7 @@ export function collectionTools(server: McpServer, scopes: string[]) { withTracing("create_collection", async (input, context) => { try { const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const team = await Team.findByPk(user.teamId, { rejectOnEmpty: true, }); @@ -220,8 +220,7 @@ export function collectionTools(server: McpServer, scopes: string[]) { const collection = await sequelize.transaction( async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + ctx.transaction = transaction; const created = Collection.build({ name: input.name, @@ -313,11 +312,10 @@ export function collectionTools(server: McpServer, scopes: string[]) { withTracing("update_collection", async (input, context) => { try { const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; return await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + ctx.transaction = transaction; const collection = await Collection.findByPk(input.id, { userId: user.id, @@ -418,11 +416,11 @@ export function collectionTools(server: McpServer, scopes: string[]) { async ({ id, archive, reason }, context) => { try { const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + ctx.transaction = transaction; + ctx.transaction = transaction; const collection = await Collection.findByPk(id, { userId: user.id, diff --git a/server/mcp/tools/comments.ts b/server/mcp/tools/comments.ts index 0dea86d6d4..808879e546 100644 --- a/server/mcp/tools/comments.ts +++ b/server/mcp/tools/comments.ts @@ -196,14 +196,14 @@ export function commentTools(server: McpServer, scopes: string[]) { ) => { try { const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const data = commentParser.parse(text).toJSON(); const commentId = uuidv4(); const comment = await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + ctx.transaction = transaction; + ctx.transaction = transaction; let document = await Document.findByPk(documentId, { userId: user.id, @@ -305,7 +305,7 @@ export function commentTools(server: McpServer, scopes: string[]) { withTracing("update_comment", async ({ id, text, status }, context) => { try { const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const comment = await Comment.findByPk(id, { rejectOnEmpty: true, @@ -381,7 +381,7 @@ export function commentTools(server: McpServer, scopes: string[]) { withTracing("delete_comment", async ({ id }, context) => { try { const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const comment = await Comment.findByPk(id, { rejectOnEmpty: true, diff --git a/server/mcp/tools/documents.test.ts b/server/mcp/tools/documents.test.ts index 54a856b491..db972e0fbe 100644 --- a/server/mcp/tools/documents.test.ts +++ b/server/mcp/tools/documents.test.ts @@ -760,6 +760,120 @@ describe("create_document", () => { }); describe("update_document", () => { + it.each([ + { input: { findText: "original", text: "replacement" }, field: "findText" }, + { + input: { editMode: "replace", findText: "original", text: "replacement" }, + field: "findText", + }, + { + input: { editMode: "replace", findText: " ", text: "replacement" }, + field: "findText", + }, + { input: { editMode: "patch", findText: "original" }, field: "text" }, + { input: { editMode: "patch", text: "replacement" }, field: "findText" }, + { + input: { editMode: "patch", findText: "", text: "replacement" }, + field: "findText", + }, + { input: { editMode: "append" }, field: "text" }, + { input: { editMode: "append", text: "" }, field: "text" }, + { input: { editMode: "prepend" }, field: "text" }, + { input: { editMode: "prepend", text: "" }, field: "text" }, + ])("rejects invalid edit parameters: $input", async ({ input, field }) => { + const { user, accessToken } = await buildOAuthUser(); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + text: "original content", + }); + const { title, text, revisionCount } = document; + + const res = await callMcpTool(server, accessToken, "update_document", { + id: document.id, + title: "Must not change", + ...input, + }); + + expect(res?.result?.isError).toBe(true); + expect(res?.result?.content?.[0]?.text).toContain(field); + expect(res?.result?.content?.[0]?.text).toContain("editMode"); + + await document.reload(); + expect(document.title).toEqual(title); + expect(document.text).toEqual(text); + expect(document.revisionCount).toEqual(revisionCount); + }); + + it.each([undefined, "replace"])( + "allows an empty findText with editMode %s", + async (editMode) => { + const { user, accessToken } = await buildOAuthUser(); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + text: "original content", + }); + + const res = await callMcpTool(server, accessToken, "update_document", { + id: document.id, + editMode, + findText: "", + text: "replacement content", + }); + + expect(res?.result?.isError).toBeFalsy(); + await document.reload(); + expect(document.text).toEqual("replacement content"); + } + ); + + it.each([ + { editMode: "append", expected: "original contentadded content" }, + { editMode: "prepend", expected: "added contentoriginal content" }, + ])( + "allows findText with $editMode for REST parity", + async ({ editMode, expected }) => { + const { user, accessToken } = await buildOAuthUser(); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + text: "original content", + }); + + const res = await callMcpTool(server, accessToken, "update_document", { + id: document.id, + editMode, + findText: "original", + text: "added content", + }); + + expect(res?.result?.isError).toBeFalsy(); + await document.reload(); + expect(document.text).toEqual(expected); + } + ); + + it("allows empty patch text to delete the matched content", async () => { + const { user, accessToken } = await buildOAuthUser(); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + text: "the original sentence", + }); + + const res = await callMcpTool(server, accessToken, "update_document", { + id: document.id, + editMode: "patch", + findText: "original ", + text: "", + }); + + expect(res?.result?.isError).toBeFalsy(); + await document.reload(); + expect(document.text).toEqual("the sentence"); + }); + it("attributes Markdown mentions to the authenticated editor", async () => { const { user, accessToken } = await buildOAuthUser(); const author = await buildUser({ teamId: user.teamId }); diff --git a/server/mcp/tools/documents.ts b/server/mcp/tools/documents.ts index 6fef4fd5cc..e1905f3922 100644 --- a/server/mcp/tools/documents.ts +++ b/server/mcp/tools/documents.ts @@ -460,7 +460,7 @@ export function documentTools(server: McpServer, scopes: string[]) { try { const { collectionId, parentDocumentId, templateId } = input; const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const { collection, parentDocument } = await authorizeDocumentCreate( ctx, @@ -496,12 +496,12 @@ export function documentTools(server: McpServer, scopes: string[]) { publish: input.publish !== false, collectionId: collection?.id, parentDocumentId: parentDocument?.id, - authType: ctx.state.auth.type, - ip: ctx.context.ip, + authType: ctx.auth.type, + ip: ctx.ip, }) : await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + ctx.transaction = transaction; + ctx.transaction = transaction; return documentCreator(ctx, { title: input.title, @@ -576,11 +576,11 @@ export function documentTools(server: McpServer, scopes: string[]) { withTracing("move_document", async (input, context) => { try { const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + ctx.transaction = transaction; + ctx.transaction = transaction; const document = await Document.findByPk(input.id, { userId: user.id, @@ -732,13 +732,47 @@ export function documentTools(server: McpServer, scopes: string[]) { }, withTracing("update_document", async (input, context) => { try { + if ( + (input.editMode === undefined || + input.editMode === TextEditMode.Replace) && + input.findText + ) { + throw ValidationError( + 'findText cannot be used with replace editMode. Use editMode "patch" instead.' + ); + } + + if ( + (input.editMode === TextEditMode.Append || + input.editMode === TextEditMode.Prepend) && + !input.text + ) { + throw ValidationError( + "text is required when using append, prepend, or editMode" + ); + } + + if (input.editMode === TextEditMode.Patch) { + if (input.text === undefined) { + throw ValidationError( + "text is required when using patch editMode" + ); + } + + if (!input.findText) { + throw ValidationError( + "findText is required when using patch editMode" + ); + } + } + const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; // Returns null when the update persisted nothing. const updated = await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + ctx.transaction = transaction; + ctx.transaction = transaction; const document = await Document.findByPk(input.id, { userId: user.id, @@ -888,11 +922,11 @@ export function documentTools(server: McpServer, scopes: string[]) { async ({ id, archive, reason }, context) => { try { const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + ctx.transaction = transaction; + ctx.transaction = transaction; const document = await Document.findByPk(id, { userId: user.id, @@ -947,11 +981,11 @@ export function documentTools(server: McpServer, scopes: string[]) { withTracing("restore_document", async ({ id, collectionId }, context) => { try { const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + ctx.transaction = transaction; + ctx.transaction = transaction; const document = await Document.findByPk(id, { userId: user.id, diff --git a/server/mcp/util.ts b/server/mcp/util.ts index 9645fd23a3..ea6e3ce882 100644 --- a/server/mcp/util.ts +++ b/server/mcp/util.ts @@ -6,7 +6,7 @@ import { Collection, Share, type Team, type User } from "@server/models"; import { addTags } from "@server/logging/tracer"; import { traceFunction } from "@server/logging/tracing"; import { can } from "@server/policies"; -import { type APIContext, AuthenticationType } from "@server/types"; +import { type Context, AuthenticationType } from "@server/types"; import type { NavigationNode } from "@shared/types"; interface McpContext { @@ -24,11 +24,11 @@ export function getActorFromContext(context: McpContext) { } /** - * Constructs a minimal APIContext from the MCP request context for use with + * Constructs a minimal Context from the MCP request context for use with * server commands that require a Koa-style context. * * @param context - the MCP request context. - * @returns a partial APIContext suitable for command functions. + * @returns a partial Context suitable for command functions. */ export function buildAPIContext(context: McpContext) { const user = context.http?.authInfo?.extra?.user as User; @@ -42,11 +42,11 @@ export function buildAPIContext(context: McpContext) { }; return { - state: { auth }, - context: { auth, ip }, + auth, + ip, request: { secure: env.URL.startsWith("https://") }, cookies: { get: () => undefined, set: () => undefined }, - } as unknown as APIContext; + } as unknown as Context; } /** diff --git a/server/middlewares/apexAuthRedirect.ts b/server/middlewares/apexAuthRedirect.ts index 466a9963f6..5409b2d69e 100644 --- a/server/middlewares/apexAuthRedirect.ts +++ b/server/middlewares/apexAuthRedirect.ts @@ -3,7 +3,7 @@ import { toError } from "@shared/utils/error"; import { parseDomain } from "@shared/utils/domains"; import Logger from "@server/logging/Logger"; import { Team } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; /** * An authentication middleware that should be used on routes that return from external auth flows @@ -19,17 +19,17 @@ export default function apexAuthRedirect({ getErrorPath, }: { /** Get the team ID for the current request */ - getTeamId: (ctx: APIContext) => string | null | undefined; + getTeamId: (ctx: Context) => string | null | undefined; /** Get the redirect URL for the given team ID */ - getRedirectPath: (ctx: APIContext, team: Team) => string; + getRedirectPath: (ctx: Context, team: Team) => string; /** Get the error URL for the current request */ - getErrorPath: (ctx: APIContext) => string; + getErrorPath: (ctx: Context) => string; }) { return async function apexAuthRedirectMiddleware( - ctx: APIContext, + ctx: Context, next: Next ) { - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (user) { return next(); } diff --git a/server/middlewares/apexRedirect.ts b/server/middlewares/apexRedirect.ts index 589588e172..1499af2aed 100644 --- a/server/middlewares/apexRedirect.ts +++ b/server/middlewares/apexRedirect.ts @@ -1,7 +1,8 @@ -import type { Context, Next } from "koa"; +import type { Next } from "koa"; +import type { AppContext } from "@server/types"; export default function apexRedirect() { - return async function apexRedirectMiddleware(ctx: Context, next: Next) { + return async function apexRedirectMiddleware(ctx: AppContext, next: Next) { if (ctx.headers.host === "getoutline.com") { ctx.redirect(`https://www.${ctx.headers.host}${ctx.path}`); } else { diff --git a/server/middlewares/apiContext.ts b/server/middlewares/apiContext.ts deleted file mode 100644 index 5da5547442..0000000000 --- a/server/middlewares/apiContext.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { Next } from "koa"; -import type { AppContext } from "@server/types"; - -/** - * Middleware that defines the `ctx.context` getter, which provides the current - * request's auth, transaction, and IP to database mutation helpers like - * `saveWithCtx` and `destroyWithCtx`. - * - * @returns The middleware function. - */ -export function apiContext() { - return async function apiContextMiddleware(ctx: AppContext, next: Next) { - Object.defineProperty(ctx, "context", { - configurable: true, - get() { - return { - auth: ctx.state.auth, - transaction: ctx.state.transaction, - ip: ctx.request.ip, - }; - }, - }); - - return next(); - }; -} diff --git a/server/middlewares/appHeaders.ts b/server/middlewares/appHeaders.ts index 4095359882..3bd2b612ee 100644 --- a/server/middlewares/appHeaders.ts +++ b/server/middlewares/appHeaders.ts @@ -1,5 +1,6 @@ -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import env from "@server/env"; +import type { AppContext } from "@server/types"; /** * Middleware that sets the response headers that are needed when serving the @@ -18,7 +19,7 @@ export default function appHeaders() { const timingAllowOrigin = timingOrigins.join(", "); - return async function appHeadersMiddleware(ctx: Context, next: Next) { + return async function appHeadersMiddleware(ctx: AppContext, next: Next) { ctx.set("Timing-Allow-Origin", timingAllowOrigin); // Allow the JS Self-Profiling API to be used for local performance work. diff --git a/server/middlewares/authentication.test.ts b/server/middlewares/authentication.test.ts index c52c1f3ff1..49d56599a2 100644 --- a/server/middlewares/authentication.test.ts +++ b/server/middlewares/authentication.test.ts @@ -1,4 +1,3 @@ -import type { DefaultState } from "koa"; import { errToString } from "@shared/utils/error"; import { randomString } from "@shared/random"; import { Scope } from "@shared/types"; @@ -16,61 +15,49 @@ import auth from "./authentication"; describe("Authentication middleware", () => { describe("with session JWT", () => { it("should authenticate with correct session token", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => `Bearer ${user.getSessionToken()}`), - }, - state, - cache: {}, - }), - vi.fn() - ); - expect(state.auth.user.id).toEqual(user.id); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => `Bearer ${user.getSessionToken()}`), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); + expect(ctx.auth?.user.id).toEqual(user.id); }); it("should return error with invalid session token", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); try { - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => `Bearer ${user.getSessionToken()}error`), - }, - state, - cache: {}, - }), - vi.fn() - ); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => `Bearer ${user.getSessionToken()}error`), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); } catch (e) { expect(errToString(e)).toBe("Invalid token"); } }); it("should return error if AuthenticationType mismatches", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth({ type: AuthenticationType.API, }); try { - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => `Bearer ${user.getSessionToken()}`), - }, - state, - cache: {}, - }), - vi.fn() - ); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => `Bearer ${user.getSessionToken()}`), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); } catch (e) { expect(errToString(e)).toBe("Invalid authentication type"); } @@ -79,24 +66,19 @@ describe("Authentication middleware", () => { describe("with API key", () => { it("should authenticate user with valid API key", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); const key = await buildApiKey({ userId: user.id }); - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => `Bearer ${key.value}`), - }, - state, - cache: {}, - }), - vi.fn() - ); - expect(state.auth.user.id).toEqual(user.id); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => `Bearer ${key.value}`), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); + expect(ctx.auth?.user.id).toEqual(user.id); }); it("should authenticate with global read scope on read endpoints", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); const key = await buildApiKey({ @@ -104,23 +86,20 @@ describe("Authentication middleware", () => { scope: [Scope.Read], }); - await authMiddleware( - buildMockContext({ - originalUrl: "/api/auth.info", - request: { - url: "/auth.info", - get: vi.fn(() => `Bearer ${key.value}`), - }, - state, - cache: {}, - }), - vi.fn() - ); - expect(state.auth.user.id).toEqual(user.id); + const ctx = buildMockContext({ + originalUrl: "/api/auth.info", + request: { + url: "/auth.info", + get: vi.fn(() => `Bearer ${key.value}`), + }, + cache: {}, + }); + + await authMiddleware(ctx, vi.fn()); + expect(ctx.auth?.user.id).toEqual(user.id); }); it("should return 403 authorization error when scope does not match", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); const key = await buildApiKey({ @@ -129,18 +108,15 @@ describe("Authentication middleware", () => { }); try { - await authMiddleware( - buildMockContext({ - originalUrl: "/api/documents.create", - request: { - url: "/documents.create", - get: vi.fn(() => `Bearer ${key.value}`), - }, - state, - cache: {}, - }), - vi.fn() - ); + const ctx = buildMockContext({ + originalUrl: "/api/documents.create", + request: { + url: "/documents.create", + get: vi.fn(() => `Bearer ${key.value}`), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); throw new Error("Expected error to be thrown"); } catch (e) { expect(e).toHaveProperty("status", 403); @@ -152,20 +128,16 @@ describe("Authentication middleware", () => { }); it("should return error with invalid API key", async () => { - const state = {} as DefaultState; const authMiddleware = auth(); try { - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => `Bearer ${randomString(38)}`), - }, - state, - cache: {}, - }), - vi.fn() - ); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => `Bearer ${randomString(38)}`), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); } catch (e) { expect(errToString(e)).toBe("Invalid API key"); } @@ -174,7 +146,6 @@ describe("Authentication middleware", () => { describe("with OAuth access token", () => { it("should authenticate user with valid OAuth access token", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); const authentication = await buildOAuthAuthentication({ @@ -182,23 +153,20 @@ describe("Authentication middleware", () => { scope: [Scope.Read], }); - await authMiddleware( - buildMockContext({ - originalUrl: "/api/users.info", - request: { - url: "/users.info", - get: vi.fn(() => `Bearer ${authentication.accessToken}`), - }, - state, - cache: {}, - }), - vi.fn() - ); - expect(state.auth.user.id).toEqual(user.id); + const ctx = buildMockContext({ + originalUrl: "/api/users.info", + request: { + url: "/users.info", + get: vi.fn(() => `Bearer ${authentication.accessToken}`), + }, + cache: {}, + }); + + await authMiddleware(ctx, vi.fn()); + expect(ctx.auth?.user.id).toEqual(user.id); }); it("should return error with invalid scope", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); const authentication = await buildOAuthAuthentication({ @@ -207,18 +175,15 @@ describe("Authentication middleware", () => { }); try { - await authMiddleware( - buildMockContext({ - originalUrl: "/api/documents.create", - request: { - url: "/documents.create", - get: vi.fn(() => `Bearer ${authentication.accessToken}`), - }, - state, - cache: {}, - }), - vi.fn() - ); + const ctx = buildMockContext({ + originalUrl: "/api/documents.create", + request: { + url: "/documents.create", + get: vi.fn(() => `Bearer ${authentication.accessToken}`), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); } catch (e) { expect(errToString(e)).toContain( "does not have access to this resource" @@ -227,7 +192,6 @@ describe("Authentication middleware", () => { }); it("should return error with OAuth access token in body", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); const authentication = await buildOAuthAuthentication({ @@ -235,21 +199,18 @@ describe("Authentication middleware", () => { scope: [Scope.Read], }); try { - await authMiddleware( - buildMockContext({ - originalUrl: "/api/users.info", - request: { - url: "/users.info", - get: vi.fn(() => null), - body: { - token: authentication.accessToken, - }, + const ctx = buildMockContext({ + originalUrl: "/api/users.info", + request: { + url: "/users.info", + get: vi.fn(() => null), + body: { + token: authentication.accessToken, }, - state, - cache: {}, - }), - vi.fn() - ); + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); } catch (e) { expect(errToString(e)).toContain( "must be passed in the Authorization header" @@ -259,20 +220,16 @@ describe("Authentication middleware", () => { }); it("should return error message if no auth token is available", async () => { - const state = {} as DefaultState; const authMiddleware = auth(); try { - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => "error"), - }, - state, - cache: {}, - }), - vi.fn() - ); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => "error"), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); } catch (e) { expect(errToString(e)).toBe( 'Bad Authorization header format. Format is "Authorization: Bearer "' @@ -281,27 +238,22 @@ describe("Authentication middleware", () => { }); it("should allow passing session token in a cookie", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => null), - }, - cookies: { - get: vi.fn(() => user.getSessionToken()), - }, - state, - cache: {}, - }), - vi.fn() - ); - expect(state.auth.user.id).toEqual(user.id); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => null), + }, + cookies: { + get: vi.fn(() => user.getSessionToken()), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); + expect(ctx.auth?.user.id).toEqual(user.id); }); it("should return error with session token as a GET param", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); @@ -314,7 +266,6 @@ describe("Authentication middleware", () => { token: user.getSessionToken(), }, }, - state, cache: {}, }), vi.fn() @@ -325,7 +276,6 @@ describe("Authentication middleware", () => { }); it("should return error with session token in body params", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); @@ -338,7 +288,6 @@ describe("Authentication middleware", () => { token: user.getSessionToken(), }, }, - state, cache: {}, }), vi.fn() @@ -349,7 +298,6 @@ describe("Authentication middleware", () => { }); it("should not accept transfer token as a GET param", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); @@ -362,7 +310,6 @@ describe("Authentication middleware", () => { token: user.getTransferToken(), }, }, - state, cache: {}, }), vi.fn() @@ -373,7 +320,6 @@ describe("Authentication middleware", () => { }); it("should not accept transfer token in the Authorization header", async () => { - const state = {} as DefaultState; const user = await buildUser(); const authMiddleware = auth(); @@ -383,7 +329,6 @@ describe("Authentication middleware", () => { request: { get: vi.fn(() => `Bearer ${user.getTransferToken()}`), }, - state, cache: {}, }), vi.fn() @@ -392,7 +337,6 @@ describe("Authentication middleware", () => { }); it("should return an error for suspended users", async () => { - const state = {} as DefaultState; const admin = await buildAdmin(); const user = await buildUser({ suspendedAt: new Date(), @@ -402,16 +346,13 @@ describe("Authentication middleware", () => { let error; try { - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => `Bearer ${user.getSessionToken()}`), - }, - state, - cache: {}, - }), - vi.fn() - ); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => `Bearer ${user.getSessionToken()}`), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); } catch (err) { error = err; } @@ -423,7 +364,6 @@ describe("Authentication middleware", () => { }); it("should return an error for deleted team", async () => { - const state = {} as DefaultState; const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); await team.destroy(); @@ -431,16 +371,13 @@ describe("Authentication middleware", () => { let error; try { - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => `Bearer ${user.getSessionToken()}`), - }, - state, - cache: {}, - }), - vi.fn() - ); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => `Bearer ${user.getSessionToken()}`), + }, + cache: {}, + }); + await authMiddleware(ctx, vi.fn()); } catch (err) { error = err; } @@ -449,7 +386,6 @@ describe("Authentication middleware", () => { }); describe("with skip", () => { it("should ignore credentials when skip returns true", async () => { - const state = {} as DefaultState; const user = await buildUser(); const apiKey = await buildApiKey({ userId: user.id, @@ -460,43 +396,36 @@ describe("Authentication middleware", () => { optional: true, skip: (ctx) => !!ctx.query.sig, }); - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => `Bearer ${apiKey.value}`), - }, - query: { sig: "signature" }, - originalUrl: "/api/files.get?sig=signature", - state, - cache: {}, - }), - next - ); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => `Bearer ${apiKey.value}`), + }, + query: { sig: "signature" }, + originalUrl: "/api/files.get?sig=signature", + cache: {}, + }); + await authMiddleware(ctx, next); expect(next).toHaveBeenCalled(); - expect(state.auth).toEqual({}); + expect(ctx.auth).toEqual({}); }); it("should authenticate when skip returns false", async () => { - const state = {} as DefaultState; const user = await buildUser(); const next = vi.fn(); const authMiddleware = auth({ optional: true, skip: (ctx) => !!ctx.query.sig, }); - await authMiddleware( - buildMockContext({ - request: { - get: vi.fn(() => `Bearer ${user.getSessionToken()}`), - }, - query: {}, - state, - cache: {}, - }), - next - ); + const ctx = buildMockContext({ + request: { + get: vi.fn(() => `Bearer ${user.getSessionToken()}`), + }, + query: {}, + cache: {}, + }); + await authMiddleware(ctx, next); expect(next).toHaveBeenCalled(); - expect(state.auth.user.id).toEqual(user.id); + expect(ctx.auth?.user.id).toEqual(user.id); }); }); }); diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index 89f0ad2643..e99f971ed2 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -55,7 +55,7 @@ type AuthInput = { export default function auth(options: AuthenticationOptions = {}) { return async function authMiddleware(ctx: AppContext, next: Next) { if (options.skip?.(ctx)) { - ctx.state.auth = {}; + ctx.auth = {}; return next(); } @@ -67,7 +67,7 @@ export default function auth(options: AuthenticationOptions = {}) { Promise.all([user.updateActiveAt(ctx), user.team?.updateActiveAt()]) ); - ctx.state.auth = { + ctx.auth = { user, token, type, @@ -89,7 +89,7 @@ export default function auth(options: AuthenticationOptions = {}) { // Credentials that are valid but insufficient are always surfaced, // otherwise the request would be silently downgraded to anonymous. if (options.optional && !(err instanceof httpErrors.Forbidden)) { - ctx.state.auth = {}; + ctx.auth = {}; } else { throw err; } diff --git a/server/middlewares/csp.ts b/server/middlewares/csp.ts index a00d757aba..edc23c426f 100644 --- a/server/middlewares/csp.ts +++ b/server/middlewares/csp.ts @@ -1,9 +1,10 @@ import crypto from "node:crypto"; -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import helmet from "koa-helmet"; import { asyncNoop } from "es-toolkit"; import { uniq } from "es-toolkit/compat"; import env from "@server/env"; +import type { AppContext } from "@server/types"; const getBucketOrigins = (): string[] => { if (env.AWS_S3_ACCELERATE_URL) { @@ -59,7 +60,7 @@ interface CSPOptions { * @param ctx The Koa context of the current request. * @param sources The origins to allow. */ -export function allowScriptSrc(ctx: Context, sources: string[]) { +export function allowScriptSrc(ctx: AppContext, sources: string[]) { ctx.state.cspScriptSrc = [...(ctx.state.cspScriptSrc ?? []), ...sources]; } @@ -70,7 +71,7 @@ export function allowScriptSrc(ctx: Context, sources: string[]) { * @param ctx The Koa context of the current request. * @param sources The origins to allow. */ -export function allowStyleSrc(ctx: Context, sources: string[]) { +export function allowStyleSrc(ctx: AppContext, sources: string[]) { ctx.state.cspStyleSrc = [...(ctx.state.cspStyleSrc ?? []), ...sources]; } @@ -80,7 +81,7 @@ export function allowStyleSrc(ctx: Context, sources: string[]) { * * @param ctx The Koa context of the current request. */ -export function allowFraming(ctx: Context) { +export function allowFraming(ctx: AppContext) { ctx.state.cspAllowFraming = true; ctx.remove("X-Frame-Options"); } @@ -130,7 +131,7 @@ export default function createCSPMiddleware(options?: CSPOptions) { objectSrc.push(cloudFrontOrigin); } - return async function cspMiddleware(ctx: Context, next: Next) { + return async function cspMiddleware(ctx: AppContext, next: Next) { ctx.state.cspNonce = crypto.randomBytes(16).toString("hex"); ctx.state.cspScriptSrc = []; ctx.state.cspStyleSrc = []; diff --git a/server/middlewares/feature.ts b/server/middlewares/feature.ts index 120db72421..0efdcca619 100644 --- a/server/middlewares/feature.ts +++ b/server/middlewares/feature.ts @@ -1,7 +1,7 @@ import type { Next } from "koa"; import { CommentingAccess, TeamPreference } from "@shared/types"; import { ValidationError } from "@server/errors"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; /** * Middleware to check if a feature is enabled for the team. @@ -10,8 +10,8 @@ import type { APIContext } from "@server/types"; * @returns The middleware function */ export function feature(preference: TeamPreference) { - return async function featureEnabledMiddleware(ctx: APIContext, next: Next) { - if (!ctx.state.auth.user.team.getPreference(preference)) { + return async function featureEnabledMiddleware(ctx: Context, next: Next) { + if (!ctx.auth.user.team.getPreference(preference)) { throw ValidationError(`${preference} is currently disabled`); } return next(); @@ -24,11 +24,8 @@ export function feature(preference: TeamPreference) { * @returns The middleware function */ export function commentingEnabled() { - return async function commentingEnabledMiddleware( - ctx: APIContext, - next: Next - ) { - const commenting = ctx.state.auth.user.team.getPreference( + return async function commentingEnabledMiddleware(ctx: Context, next: Next) { + const commenting = ctx.auth.user.team.getPreference( TeamPreference.Commenting ); // A legacy boolean `false` (team not yet migrated) means disabled. diff --git a/server/middlewares/multipart.ts b/server/middlewares/multipart.ts index e2228211a8..fa6d0614e4 100644 --- a/server/middlewares/multipart.ts +++ b/server/middlewares/multipart.ts @@ -1,7 +1,7 @@ import type { Next } from "koa"; import { bytesToHumanReadable } from "@shared/utils/files"; import { InvalidRequestError } from "@server/errors"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { getFileFromRequest } from "@server/utils/koa"; export default function multipart({ @@ -12,7 +12,7 @@ export default function multipart({ /** When true, non-multipart requests pass through with file set to undefined. */ optional?: boolean; }) { - return async function multipartMiddleware(ctx: APIContext, next: Next) { + return async function multipartMiddleware(ctx: Context, next: Next) { if (!ctx.is("multipart/form-data")) { if (optional) { return next(); diff --git a/server/middlewares/passport.ts b/server/middlewares/passport.ts index db09f391aa..faee69588f 100644 --- a/server/middlewares/passport.ts +++ b/server/middlewares/passport.ts @@ -1,5 +1,4 @@ import passport from "@outlinewiki/koa-passport"; -import type { Context } from "koa"; import { AuthorizationError, InternalOAuthError, @@ -11,7 +10,7 @@ import env from "@server/env"; import { AuthenticationError } from "@server/errors"; import Logger from "@server/logging/Logger"; import { Team } from "@server/models"; -import type { AuthenticationResult } from "@server/types"; +import type { AuthenticationResult, AppContext } from "@server/types"; import { signIn } from "@server/utils/authentication"; import { parseState } from "@server/utils/passport"; @@ -52,7 +51,7 @@ async function getValidatedHost(host: string): Promise { } export default function createMiddleware(providerName: string) { - return function passportMiddleware(ctx: Context) { + return function passportMiddleware(ctx: AppContext) { return passport.authorize( providerName, { diff --git a/server/middlewares/rateLimiter.test.ts b/server/middlewares/rateLimiter.test.ts index 770f6af3bc..def75ae532 100644 --- a/server/middlewares/rateLimiter.test.ts +++ b/server/middlewares/rateLimiter.test.ts @@ -1,10 +1,10 @@ -import type { Context } from "koa"; import { RateLimiterRes } from "rate-limiter-flexible"; import env from "@server/env"; import { ApiKey } from "@server/models"; import * as jwtUtils from "@server/utils/jwt"; import RateLimiter from "@server/utils/RateLimiter"; import { defaultRateLimiter, rateLimiter } from "./rateLimiter"; +import type { AppContext } from "@server/types"; interface MockContextOptions { path?: string; @@ -35,7 +35,7 @@ const createContext = ({ query: {}, }, cookies: { get: () => undefined }, - }) as unknown as Context; + }) as unknown as AppContext; describe("rateLimiter middleware", () => { const originalRateLimiterEnabled = env.RATE_LIMITER_ENABLED; diff --git a/server/middlewares/requestTracer.ts b/server/middlewares/requestTracer.ts index 81cf757e99..4ce6e3bbc1 100644 --- a/server/middlewares/requestTracer.ts +++ b/server/middlewares/requestTracer.ts @@ -1,9 +1,10 @@ -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import { addTags, getRootSpanFromRequestContext } from "@server/logging/tracer"; import { RequestHelper } from "@server/utils/RequestHelper"; +import type { AppContext } from "@server/types"; export default function requestTracer() { - return async function requestTracerMiddleware(ctx: Context, next: Next) { + return async function requestTracerMiddleware(ctx: AppContext, next: Next) { const params = ctx.request.body ? RequestHelper.getBodyObject(ctx.request) : ctx.request.query; diff --git a/server/middlewares/shareDomains.test.ts b/server/middlewares/shareDomains.test.ts index fe083e4883..ab60ffbea5 100644 --- a/server/middlewares/shareDomains.test.ts +++ b/server/middlewares/shareDomains.test.ts @@ -1,9 +1,9 @@ import { subDays } from "date-fns"; -import type { Context } from "koa"; import { randomString } from "@shared/random"; import env from "@server/env"; import { buildShare, buildTeam } from "@server/test/factories"; import shareDomains from "./shareDomains"; +import type { AppContext } from "@server/types"; describe("shareDomains middleware", () => { const buildContext = (hostname: string) => @@ -11,7 +11,7 @@ describe("shareDomains middleware", () => { host: hostname, hostname, state: {}, - }) as Context; + }) as AppContext; beforeEach(() => { vi.spyOn(env, "isCloudHosted", "get").mockReturnValue(true); diff --git a/server/middlewares/shareDomains.ts b/server/middlewares/shareDomains.ts index 469ca78fab..b4acf9c9c1 100644 --- a/server/middlewares/shareDomains.ts +++ b/server/middlewares/shareDomains.ts @@ -1,11 +1,12 @@ -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import { Op } from "sequelize"; import { parseDomain } from "@shared/utils/domains"; import env from "@server/env"; import { Share } from "@server/models"; +import type { AppContext } from "@server/types"; export default function shareDomains() { - return async function shareDomainsMiddleware(ctx: Context, next: Next) { + return async function shareDomainsMiddleware(ctx: AppContext, next: Next) { const isCustomDomain = parseDomain(ctx.host).custom; if (env.isDevelopment || (isCustomDomain && env.isCloudHosted)) { diff --git a/server/middlewares/transaction.ts b/server/middlewares/transaction.ts index eaf6f196e8..664b002488 100644 --- a/server/middlewares/transaction.ts +++ b/server/middlewares/transaction.ts @@ -5,7 +5,7 @@ import type { AppContext } from "@server/types"; /** * Middleware that wraps a route in a database transaction, useful for mutations - * The transaction is available on the context as `ctx.state.transaction` and + * The transaction is available on the context as `ctx.transaction` and * should be passed to all database calls within the route. * * @returns The middleware function. @@ -13,7 +13,7 @@ import type { AppContext } from "@server/types"; export function transaction() { return async function transactionMiddleware(ctx: AppContext, next: Next) { await sequelize.transaction(async (t: Transaction) => { - ctx.state.transaction = t; + ctx.transaction = t; return next(); }); }; diff --git a/server/middlewares/userAgent.test.ts b/server/middlewares/userAgent.test.ts index 83603d8bde..8a1e48bfcd 100644 --- a/server/middlewares/userAgent.test.ts +++ b/server/middlewares/userAgent.test.ts @@ -13,9 +13,9 @@ describe("userAgent middleware", () => { await userAgent()(ctx, next); - expect(ctx.userAgent.source).toEqual(chromeOnMac); - expect(ctx.userAgent.isDesktop).toBe(true); - expect(ctx.userAgent.isMobile).toBe(false); + expect(ctx.userAgent?.source).toEqual(chromeOnMac); + expect(ctx.userAgent?.isDesktop).toBe(true); + expect(ctx.userAgent?.isMobile).toBe(false); expect(next).toHaveBeenCalled(); }); @@ -24,8 +24,8 @@ describe("userAgent middleware", () => { await userAgent()(ctx, vi.fn()); - expect(ctx.userAgent.isMobile).toBe(true); - expect(ctx.userAgent.isDesktop).toBe(false); + expect(ctx.userAgent?.isMobile).toBe(true); + expect(ctx.userAgent?.isDesktop).toBe(false); }); it("should use a placeholder when the header is missing", async () => { @@ -33,6 +33,6 @@ describe("userAgent middleware", () => { await userAgent()(ctx, vi.fn()); - expect(ctx.userAgent.source).toEqual("unknown"); + expect(ctx.userAgent?.source).toEqual("unknown"); }); }); diff --git a/server/middlewares/validate.ts b/server/middlewares/validate.ts index 9d7f1c1f29..7cf8926382 100644 --- a/server/middlewares/validate.ts +++ b/server/middlewares/validate.ts @@ -3,12 +3,12 @@ import type { z } from "zod"; import { ZodError } from "zod"; import { toError } from "@shared/utils/error"; import { ValidationError } from "@server/errors"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; export default function validate>>( schema: T ) { - return async function validateMiddleware(ctx: APIContext, next: Next) { + return async function validateMiddleware(ctx: Context, next: Next) { try { ctx.input = { ...ctx.input, diff --git a/server/middlewares/validateWebhook.ts b/server/middlewares/validateWebhook.ts index b16d983e1b..f0c09577af 100644 --- a/server/middlewares/validateWebhook.ts +++ b/server/middlewares/validateWebhook.ts @@ -1,6 +1,6 @@ import crypto from "node:crypto"; import type { Next } from "koa"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { safeEqual } from "@server/utils/crypto"; export default function validateWebhook({ @@ -8,11 +8,11 @@ export default function validateWebhook({ getSignatureFromHeader, hmacSign = true, }: { - secretKey: string | ((ctx: APIContext) => Promise); - getSignatureFromHeader: (ctx: APIContext) => string | undefined; + secretKey: string | ((ctx: Context) => Promise); + getSignatureFromHeader: (ctx: Context) => string | undefined; hmacSign?: boolean; }) { - return async function validateWebhookMiddleware(ctx: APIContext, next: Next) { + return async function validateWebhookMiddleware(ctx: Context, next: Next) { const { body } = ctx.request; const signatureFromHeader = getSignatureFromHeader(ctx); diff --git a/server/migrations/20261123070000-add-subscriptions-document-id-index.js b/server/migrations/20261123070000-add-subscriptions-document-id-index.js new file mode 100644 index 0000000000..19ab6779fd --- /dev/null +++ b/server/migrations/20261123070000-add-subscriptions-document-id-index.js @@ -0,0 +1,17 @@ +"use strict"; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface) { + // Covers the foreign key cascade when a document is permanently deleted. + await queryInterface.sequelize.query( + 'CREATE INDEX CONCURRENTLY IF NOT EXISTS "subscriptions_document_id" ON "subscriptions" ("documentId");' + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + 'DROP INDEX CONCURRENTLY IF EXISTS "subscriptions_document_id";' + ); + }, +}; diff --git a/server/models/AccessRequest.ts b/server/models/AccessRequest.ts index 4137ab10b1..27c8d7d8ff 100644 --- a/server/models/AccessRequest.ts +++ b/server/models/AccessRequest.ts @@ -20,7 +20,7 @@ import Team from "./Team"; import User from "./User"; import IdModel from "./base/IdModel"; import { ValidationError } from "@server/errors"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; export enum AccessRequestStatus { Pending = "pending", @@ -113,11 +113,11 @@ class AccessRequest extends IdModel< /** * Approve this access request, setting the status and responder, and persist. * - * @param ctx the API context; the authenticated user is recorded as responder. + * @param ctx the context; the authenticated user is recorded as responder. */ - public approve(ctx: APIContext) { + public approve(ctx: Context) { this.status = AccessRequestStatus.Approved; - this.responderId = ctx.state.auth.user.id; + this.responderId = ctx.auth.user.id; this.respondedAt = new Date(); return this.saveWithCtx(ctx); } @@ -125,11 +125,11 @@ class AccessRequest extends IdModel< /** * Dismiss this access request, setting the status and responder, and persist. * - * @param ctx the API context; the authenticated user is recorded as responder. + * @param ctx the context; the authenticated user is recorded as responder. */ - public dismiss(ctx: APIContext) { + public dismiss(ctx: Context) { this.status = AccessRequestStatus.Dismissed; - this.responderId = ctx.state.auth.user.id; + this.responderId = ctx.auth.user.id; this.respondedAt = new Date(); return this.saveWithCtx(ctx); } diff --git a/server/models/AuthenticationProvider.ts b/server/models/AuthenticationProvider.ts index 3f0425748a..c5c95478e1 100644 --- a/server/models/AuthenticationProvider.ts +++ b/server/models/AuthenticationProvider.ts @@ -26,7 +26,7 @@ import Team from "./Team"; import UserAuthentication from "./UserAuthentication"; import Length from "./validators/Length"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import type { DestroyOptions } from "sequelize"; @Scopes(() => ({ @@ -171,14 +171,12 @@ class AuthenticationProvider extends Model< /** * Disable this authentication provider after ensuring it's allowed. * - * @param ctx - API context containing the transaction. + * @param ctx - context containing the transaction. * @returns The updated AuthenticationProvider instance. * @throws ValidationError if disabling is not allowed. */ - disable: (ctx: APIContext) => Promise = async ( - ctx - ) => { - const { transaction } = ctx.state; + disable: (ctx: Context) => Promise = async (ctx) => { + const { transaction } = ctx; await this.checkCanBeDisabled(transaction); return this.updateWithCtx(ctx, { @@ -189,10 +187,10 @@ class AuthenticationProvider extends Model< /** * Enable this authentication provider. * - * @param ctx - API context containing the transaction. + * @param ctx - context containing the transaction. * @returns The updated AuthenticationProvider instance. */ - enable: (ctx: APIContext) => Promise = async (ctx) => + enable: (ctx: Context) => Promise = async (ctx) => this.updateWithCtx(ctx, { enabled: true, }); diff --git a/server/models/Collection.test.ts b/server/models/Collection.test.ts index 9335e55658..f15613bcb5 100644 --- a/server/models/Collection.test.ts +++ b/server/models/Collection.test.ts @@ -11,7 +11,7 @@ import { buildTeam, buildDocument, } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import Collection from "./Collection"; import Document from "./Document"; import Event from "./Event"; @@ -35,7 +35,7 @@ describe("#updateDeprecatedReason", () => { ); await expect( - withAPIContext(user, (ctx) => + withContext(user, (ctx) => collection.updateDeprecatedReason(ctx, "Outdated") ) ).rejects.toThrow("The collection must be archived"); @@ -688,7 +688,7 @@ describe("#archiveWithCtx", () => { archivedAt: new Date("2024-01-01"), }); - await withAPIContext(user, (ctx) => collection.archiveWithCtx(ctx)); + await withContext(user, (ctx) => collection.archiveWithCtx(ctx)); await Promise.all([ collection.reload(), @@ -720,7 +720,7 @@ describe("#archiveWithCtx", () => { publishedAt: new Date(), }); - await withAPIContext(user, (ctx) => collection.archiveWithCtx(ctx)); + await withContext(user, (ctx) => collection.archiveWithCtx(ctx)); await otherDocument.reload(); expect(otherDocument.archivedAt).toBeNull(); @@ -742,7 +742,7 @@ describe("#owners", () => { const owner = await buildUser({ teamId: user.teamId }); const collection = await buildCollection({ teamId: user.teamId }); - await withAPIContext(user, (ctx) => collection.addOwner(ctx, owner.id)); + await withContext(user, (ctx) => collection.addOwner(ctx, owner.id)); await collection.reload(); expect(collection.ownerIds).toEqual([owner.id]); @@ -760,9 +760,9 @@ describe("#owners", () => { const user = await buildUser(); const owner = await buildUser({ teamId: user.teamId }); const collection = await buildCollection({ teamId: user.teamId }); - await withAPIContext(user, (ctx) => collection.addOwner(ctx, owner.id)); + await withContext(user, (ctx) => collection.addOwner(ctx, owner.id)); - await withAPIContext(user, (ctx) => collection.removeOwner(ctx, owner.id)); + await withContext(user, (ctx) => collection.removeOwner(ctx, owner.id)); await collection.reload(); expect(collection.ownerIds).toEqual([]); @@ -786,8 +786,8 @@ describe("#owners", () => { rejectOnEmpty: true, }); - await withAPIContext(user, (ctx) => collection.addOwner(ctx, first.id)); - await withAPIContext(user, (ctx) => stale.addOwner(ctx, second.id)); + await withContext(user, (ctx) => collection.addOwner(ctx, first.id)); + await withContext(user, (ctx) => stale.addOwner(ctx, second.id)); await collection.reload(); expect(collection.ownerIds).toEqual([first.id, second.id]); diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 9a6eb49d45..395bc6ce4f 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -61,7 +61,8 @@ import { } from "@shared/validations"; import { parser } from "@server/editor"; import { ValidationError } from "@server/errors"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; +import { toHookContext, type HookContextFields } from "@server/context"; import { LockHelper } from "@server/storage/LockHelper"; import { afterCommit } from "@server/storage/transaction"; import { CacheHelper } from "@server/utils/CacheHelper"; @@ -434,7 +435,7 @@ class Collection extends ParanoidModel< } @BeforeDestroy - static async deleteDocuments(model: Collection, ctx: APIContext["context"]) { + static async deleteDocuments(model: Collection, ctx: HookContextFields) { // A bulk update rather than a destroy per document, so `deletedById` is // written here instead of by the hook on ParanoidModel. await Document.update( @@ -542,7 +543,7 @@ class Collection extends ParanoidModel< @BeforeUpdate static async publishPermissionChangedEvent( model: Collection, - ctx: APIContext["context"] + ctx: HookContextFields ) { const privacyChanged = model.previous("permission") !== model.permission; const sharingChanged = model.previous("sharing") !== model.sharing; @@ -556,10 +557,7 @@ class Collection extends ParanoidModel< } @AfterUpdate - static async publishOwnerEvents( - model: Collection, - ctx: APIContext["context"] - ) { + static async publishOwnerEvents(model: Collection, ctx: HookContextFields) { if (!model.changed("ownerIds")) { return; } @@ -846,9 +844,9 @@ class Collection extends ParanoidModel< * @param ctx The request context with the acting user and a transaction. * @returns the personal collection of the user. */ - static async findOrCreatePersonal(ctx: APIContext): Promise { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + static async findOrCreatePersonal(ctx: Context): Promise { + const { user } = ctx.auth; + const { transaction } = ctx; const existing = await this.findPersonal(user, { transaction }); if (existing) { @@ -980,7 +978,7 @@ class Collection extends ParanoidModel< * @returns a promise that resolves once the owners are assigned. * @throws ValidationError when any of the owners are not valid. */ - setOwnerIds = async (ctx: APIContext, ownerIds: string[]): Promise => { + setOwnerIds = async (ctx: Context, ownerIds: string[]): Promise => { const nextOwnerIds = await resolveRequestedOwnerIds( ctx, this.ownerIds ?? [], @@ -1001,7 +999,7 @@ class Collection extends ParanoidModel< * @returns a promise that resolves once the owner is saved. * @throws ValidationError when the user cannot be an owner. */ - addOwner = async (ctx: APIContext, userId: string): Promise => { + addOwner = async (ctx: Context, userId: string): Promise => { const ownerIds = await this.lockOwnerIds(ctx); if (!ownerIds.includes(userId)) { @@ -1025,7 +1023,7 @@ class Collection extends ParanoidModel< * @param userId the ID of the user to remove. * @returns a promise that resolves once the owner is removed. */ - removeOwner = async (ctx: APIContext, userId: string): Promise => { + removeOwner = async (ctx: Context, userId: string): Promise => { if (!this.ownerIds?.includes(userId)) { return; } @@ -1047,12 +1045,9 @@ class Collection extends ParanoidModel< * @param userIds the IDs of the owners. * @returns a promise that resolves once the memberships are saved. */ - grantOwnerAccess = async ( - ctx: APIContext, - userIds: string[] - ): Promise => { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + grantOwnerAccess = async (ctx: Context, userIds: string[]): Promise => { + const { user } = ctx.auth; + const { transaction } = ctx; for (const userId of userIds) { const membership = await UserMembership.findOneForUpdate( @@ -1072,7 +1067,7 @@ class Collection extends ParanoidModel< membership.permission = CollectionPermission.Admin; if (membership.changed()) { - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } }; @@ -1082,12 +1077,12 @@ class Collection extends ParanoidModel< * collection's `archivedAt` and `archivedBy` are set to now and the acting * user respectively, and child documents inherit the same `archivedAt`. * - * @param ctx - the API context, including the acting user and optional transaction. + * @param ctx - the context, including the acting user and optional transaction. * @returns the updated collection. */ - archiveWithCtx = async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + archiveWithCtx = async (ctx: Context) => { + const { transaction } = ctx; + const { user } = ctx.auth; this.archivedAt = new Date(); this.archivedById = user.id; @@ -1116,13 +1111,13 @@ class Collection extends ParanoidModel< /** * Updates the reason for archiving the collection. * - * @param ctx the API context, including the acting user and transaction. + * @param ctx the context, including the acting user and transaction. * @param reason the reason to save, or null to clear it. * @returns the updated collection. * @throws ValidationError if the collection is no longer archived. */ - updateDeprecatedReason = async (ctx: APIContext, reason: string | null) => { - const { transaction } = ctx.state; + updateDeprecatedReason = async (ctx: Context, reason: string | null) => { + const { transaction } = ctx; if (transaction) { await Collection.unscoped().findOne({ @@ -1150,11 +1145,11 @@ class Collection extends ParanoidModel< * Removes a document from this collection's structure and soft deletes it * along with all of its descendants. * - * @param ctx the API context, which attributes the deletion to the acting user. + * @param ctx the context, which attributes the deletion to the acting user. * @param document the document to delete. */ - deleteDocument = async (ctx: APIContext, document: Document) => { - const { transaction } = ctx.context; + deleteDocument = async (ctx: Context, document: Document) => { + const { transaction } = ctx; await this.removeDocumentInStructure(document, { transaction }); @@ -1175,11 +1170,11 @@ class Collection extends ParanoidModel< // Destroyed one at a time to ensure model hooks run for each document. for (const childDocumentId of childDocumentIds) { - await childDocumentsById[childDocumentId]?.destroy(ctx.context); + await childDocumentsById[childDocumentId]?.destroy(toHookContext(ctx)); } } - await document.destroy(ctx.context); + await document.destroy(toHookContext(ctx)); }; removeDocumentInStructure = async ( @@ -1427,8 +1422,8 @@ class Collection extends ParanoidModel< * @param ctx the API context containing the transaction. * @returns the current owner IDs. */ - private async lockOwnerIds(ctx: APIContext): Promise { - const { transaction } = ctx.state; + private async lockOwnerIds(ctx: Context): Promise { + const { transaction } = ctx; const locked = await Collection.unscoped().findOne({ where: { id: this.id }, attributes: ["id", "ownerIds"], diff --git a/server/models/Document.test.ts b/server/models/Document.test.ts index b361ae2980..0e3b4871f5 100644 --- a/server/models/Document.test.ts +++ b/server/models/Document.test.ts @@ -15,7 +15,7 @@ import { buildUser, buildGuestUser, } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import { sequelize } from "@server/storage/database"; import GroupMembership from "./GroupMembership"; import GroupUser from "./GroupUser"; @@ -48,7 +48,7 @@ describe("#restoreTo", () => { { deprecatedReason: "Outdated" }, { where: { id: document.id }, paranoid: false } ); - await withAPIContext(user, (ctx) => + await withContext(user, (ctx) => document.restoreTo(ctx, { collectionId: collection.id }) ); await document.reload(); @@ -84,7 +84,7 @@ describe("#destroyWithCtx", () => { it("should soft delete and set last modified", async () => { const document = await buildDocument(); const user = await buildUser(); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const newDocument = await Document.findByPk(document.id, { paranoid: false, @@ -98,7 +98,7 @@ describe("#destroyWithCtx", () => { archivedAt: new Date(), }); const user = await buildUser(); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const newDocument = await Document.findByPk(document.id, { paranoid: false, }); @@ -121,7 +121,7 @@ describe("#destroyWithCtx", () => { }); await collection.addDocumentToStructure(document, 0); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const [newDocument, newCollection] = await Promise.all([ document.reload({ paranoid: false }), collection.reload(), @@ -135,7 +135,7 @@ describe("#destroyWithCtx", () => { it("should delete draft without collection", async () => { const user = await buildUser(); const document = await buildDraftDocument(); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const deletedDocument = await Document.findByPk(document.id, { paranoid: false, }); @@ -1189,7 +1189,7 @@ describe("#owners", () => { const owner = await buildUser({ teamId: user.teamId }); const document = await buildDocument({ teamId: user.teamId }); - await withAPIContext(user, (ctx) => document.addOwner(ctx, owner.id)); + await withContext(user, (ctx) => document.addOwner(ctx, owner.id)); await document.reload(); expect(document.ownerIds).toEqual([owner.id]); @@ -1207,9 +1207,9 @@ describe("#owners", () => { const user = await buildUser(); const owner = await buildUser({ teamId: user.teamId }); const document = await buildDocument({ teamId: user.teamId }); - await withAPIContext(user, (ctx) => document.addOwner(ctx, owner.id)); + await withContext(user, (ctx) => document.addOwner(ctx, owner.id)); - await withAPIContext(user, (ctx) => document.removeOwner(ctx, owner.id)); + await withContext(user, (ctx) => document.removeOwner(ctx, owner.id)); await document.reload(); expect(document.ownerIds).toEqual([]); @@ -1233,8 +1233,8 @@ describe("#owners", () => { rejectOnEmpty: true, }); - await withAPIContext(user, (ctx) => document.addOwner(ctx, first.id)); - await withAPIContext(user, (ctx) => stale.addOwner(ctx, second.id)); + await withContext(user, (ctx) => document.addOwner(ctx, first.id)); + await withContext(user, (ctx) => stale.addOwner(ctx, second.id)); await document.reload(); expect(document.ownerIds).toEqual([first.id, second.id]); diff --git a/server/models/Document.ts b/server/models/Document.ts index 8c56bcda7a..77d4302edc 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -86,7 +86,8 @@ import { } from "./helpers/owners"; import IsHexColor from "./validators/IsHexColor"; import Length from "./validators/Length"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; +import { toHookContext, type HookContextFields } from "@server/context"; import { APIUpdateExtension } from "@server/collaboration/APIUpdateExtension"; import { SkipChangeset } from "./decorators/Changeset"; import type { EventOverrideOptions, HookContext } from "./base/Model"; @@ -659,7 +660,7 @@ class Document extends ArchivableModel< @AfterUpdate static async publishTitleChangeEvent( model: Document, - ctx: APIContext["context"] + ctx: HookContextFields ) { if (model.changed("title")) { const hookContext = { @@ -671,7 +672,7 @@ class Document extends ArchivableModel< } @AfterUpdate - static async publishOwnerEvents(model: Document, ctx: APIContext["context"]) { + static async publishOwnerEvents(model: Document, ctx: HookContextFields) { if (!model.changed("ownerIds")) { return; } @@ -1323,7 +1324,7 @@ class Document extends ArchivableModel< * @returns a promise that resolves once the owners are assigned. * @throws ValidationError when any of the owners are not valid. */ - setOwnerIds = async (ctx: APIContext, ownerIds: string[]): Promise => { + setOwnerIds = async (ctx: Context, ownerIds: string[]): Promise => { const nextOwnerIds = await resolveRequestedOwnerIds( ctx, this.ownerIds ?? [], @@ -1344,7 +1345,7 @@ class Document extends ArchivableModel< * @returns a promise that resolves once the owner is saved. * @throws ValidationError when the user cannot be an owner. */ - addOwner = async (ctx: APIContext, userId: string): Promise => { + addOwner = async (ctx: Context, userId: string): Promise => { const ownerIds = await this.lockOwnerIds(ctx); if (!ownerIds.includes(userId)) { @@ -1368,7 +1369,7 @@ class Document extends ArchivableModel< * @param userId the ID of the user to remove. * @returns a promise that resolves once the owner is removed. */ - removeOwner = async (ctx: APIContext, userId: string): Promise => { + removeOwner = async (ctx: Context, userId: string): Promise => { if (!this.ownerIds?.includes(userId)) { return; } @@ -1390,12 +1391,9 @@ class Document extends ArchivableModel< * @param userIds the IDs of the owners. * @returns a promise that resolves once the memberships are saved. */ - grantOwnerAccess = async ( - ctx: APIContext, - userIds: string[] - ): Promise => { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + grantOwnerAccess = async (ctx: Context, userIds: string[]): Promise => { + const { user } = ctx.auth; + const { transaction } = ctx; for (const userId of userIds) { const membership = await UserMembership.findOneForUpdate( @@ -1416,13 +1414,13 @@ class Document extends ArchivableModel< membership.permission = DocumentPermission.Admin; membership.sourceId = null; if (membership.changed()) { - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } }; publish = async ( - ctx: APIContext, + ctx: Context, { index = 0, collectionId, @@ -1437,8 +1435,8 @@ class Document extends ArchivableModel< data?: Record; } ): Promise => { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; this.lastModifiedById = user.id; this.updatedBy = user; @@ -1529,19 +1527,19 @@ class Document extends ArchivableModel< /** * Unpublishes a published document, converting it back to a draft. * - * @param ctx the API context. + * @param ctx the context. * @param options.detach whether to detach the document from the containing collection. * @returns updated document. * @throws if the document has child documents. */ - unpublishWithCtx = async (ctx: APIContext, options: { detach: boolean }) => { + unpublishWithCtx = async (ctx: Context, options: { detach: boolean }) => { // If the document is already a draft then calling unpublish should act like save if (!this.publishedAt) { return this.save(); } - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const childDocumentIds = await this.findAllChildDocumentIds( { archivedAt: { [Op.eq]: null } }, @@ -1604,8 +1602,8 @@ class Document extends ArchivableModel< // 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) => { - const { transaction } = ctx.state; + archiveWithCtx = async (ctx: Context) => { + const { transaction } = ctx; const collection = this.collectionId ? await Collection.findByPk(this.collectionId, { includeDocumentStructure: true, @@ -1627,10 +1625,10 @@ class Document extends ArchivableModel< // Restore an archived document back to being visible to the team restoreTo = async ( - ctx: APIContext, + ctx: Context, { collectionId }: { collectionId: string } ) => { - const { transaction } = ctx.state; + const { transaction } = ctx; const collection = collectionId ? await Collection.findByPk(collectionId, { includeDocumentStructure: true, @@ -1681,11 +1679,11 @@ class Document extends ArchivableModel< // Delete a document, archived or otherwise. destroyWithCtx = async ( - ctx: APIContext, + ctx: Context, eventOpts?: EventOverrideOptions ): Promise => { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; let deleted = false; if (this.collectionId) { @@ -1703,7 +1701,7 @@ class Document extends ArchivableModel< } if (!deleted) { - await this.destroy(ctx.context); + await this.destroy(toHookContext(ctx)); } this.lastModifiedById = user.id; @@ -1823,11 +1821,11 @@ class Document extends ArchivableModel< }); private restoreArchivedWithChildren = async ( - ctx: APIContext, + ctx: Context, { collectionId }: { collectionId: string } ) => { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const restoreChildren = async (parentDocumentId: string) => { const childDocuments = await ( @@ -1860,9 +1858,9 @@ class Document extends ArchivableModel< return this.saveWithCtx(ctx, undefined, { name: "unarchive" }); }; - private archiveWithChildren = async (ctx: APIContext) => { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + private archiveWithChildren = async (ctx: Context) => { + const { user } = ctx.auth; + const { transaction } = ctx; const archivedAt = new Date(); // Helper to archive all child documents for a document @@ -1898,8 +1896,8 @@ class Document extends ArchivableModel< * @param ctx the API context containing the transaction. * @returns the current owner IDs. */ - private async lockOwnerIds(ctx: APIContext): Promise { - const { transaction } = ctx.state; + private async lockOwnerIds(ctx: Context): Promise { + const { transaction } = ctx; const locked = await Document.unscoped().findOne({ where: { id: this.id }, attributes: ["id", "ownerIds"], diff --git a/server/models/Event.ts b/server/models/Event.ts index e6d70df41a..7dcf29a74b 100644 --- a/server/models/Event.ts +++ b/server/models/Event.ts @@ -19,7 +19,7 @@ import { } from "sequelize-typescript"; import { globalEventQueue } from "../queues"; import { afterCommit } from "../storage/transaction"; -import type { APIContext } from "../types"; +import type { Context } from "../types"; import { AuthenticationType } from "../types"; import { normalizeIp } from "../utils/ip"; import Collection from "./Collection"; @@ -27,7 +27,7 @@ import Document from "./Document"; import Team from "./Team"; import User from "./User"; import IdModel from "./base/IdModel"; -import type { Context } from "koa"; +import type { AppContext } from "@server/types"; @Table({ tableName: "events", modelName: "event", updatedAt: false }) class Event extends IdModel< @@ -161,13 +161,13 @@ class Event extends IdModel< * @returns A promise resolving to the new event */ static createFromContext( - ctx: Context | APIContext, + ctx: AppContext | Context, attributes: Omit, "ip" | "teamId" | "actorId"> = {}, defaultAttributes: Pick, "ip" | "teamId" | "actorId"> = {}, options?: CreateOptions> ) { - const user = ctx.state.auth?.user; - const authType = ctx.state.auth?.type; + const user = ctx.auth?.user; + const authType = ctx.auth?.type; return this.create( { @@ -178,7 +178,7 @@ class Event extends IdModel< authType, }, { - transaction: ctx.state.transaction, + transaction: ctx.transaction, ...options, } ); diff --git a/server/models/FileOperation.ts b/server/models/FileOperation.ts index b062ab614e..b31d9d8ec9 100644 --- a/server/models/FileOperation.ts +++ b/server/models/FileOperation.ts @@ -26,7 +26,7 @@ import { FileOperationType, } from "@shared/types"; import FileStorage from "@server/storage/files"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { ValidateKey } from "@server/validation"; import Collection from "./Collection"; import Document from "./Document"; @@ -155,10 +155,10 @@ class FileOperation extends ParanoidModel< * @returns the new file operation with its source associations set. */ static async createExport( - ctx: APIContext, + ctx: Context, options: CreateExportOptions ): Promise { - const { user } = ctx.state.auth; + const { user } = ctx.auth; const format = options.format ?? FileOperationFormat.MarkdownZip; // The owner is stored on the export, as a document can move out of the @@ -171,7 +171,7 @@ class FileOperation extends ParanoidModel< ? await Collection.unscoped().findOne({ attributes: ["ownerId"], where: { id: sourceCollectionId }, - transaction: ctx.state.transaction, + transaction: ctx.transaction, }) : null; const personalOwnerId = sourceCollection?.ownerId ?? undefined; diff --git a/server/models/GroupMembership.ts b/server/models/GroupMembership.ts index df0d176bda..6fdd4b6745 100644 --- a/server/models/GroupMembership.ts +++ b/server/models/GroupMembership.ts @@ -26,7 +26,7 @@ import type { DocumentPermission } from "@shared/types"; import { CollectionPermission } from "@shared/types"; import { ValidationError } from "@server/errors"; import { LockHelper } from "@server/storage/LockHelper"; -import type { APIContext } from "@server/types"; +import type { HookContextFields } from "@server/context"; import Collection from "./Collection"; import Document from "./Document"; import Group from "./Group"; @@ -252,7 +252,7 @@ class GroupMembership extends ParanoidModel< @AfterCreate static async publishAddGroupEventAfterCreate( model: GroupMembership, - context: APIContext["context"] + context: HookContextFields ) { await model.insertEvent(context, "add_group", { membershipId: model.id, @@ -295,7 +295,7 @@ class GroupMembership extends ParanoidModel< @BeforeUpdate static async checkLastAdminBeforeUpdate( model: GroupMembership, - ctx: APIContext["context"] + ctx: HookContextFields ) { if ( model.permission === CollectionPermission.Admin || @@ -310,7 +310,7 @@ class GroupMembership extends ParanoidModel< @BeforeDestroy static async checkLastAdminBeforeDestroy( model: GroupMembership, - ctx: APIContext["context"] + ctx: HookContextFields ) { // Only check for last admin permission if this permission is admin if ( @@ -325,7 +325,7 @@ class GroupMembership extends ParanoidModel< @AfterUpdate static async publishAddGroupEventAfterUpdate( model: GroupMembership, - context: APIContext["context"] + context: HookContextFields ) { await model.insertEvent(context, "add_group", { membershipId: model.id, @@ -355,7 +355,7 @@ class GroupMembership extends ParanoidModel< @AfterDestroy static async publishRemoveGroupEvent( model: GroupMembership, - context: APIContext["context"] + context: HookContextFields ) { await model.insertEvent(context, "remove_group", { membershipId: model.id, @@ -469,7 +469,7 @@ class GroupMembership extends ParanoidModel< } private async insertEvent( - ctx: APIContext["context"], + ctx: HookContextFields, name: string, data: Record ) { @@ -487,7 +487,7 @@ class GroupMembership extends ParanoidModel< private static async validateLastAdminPermission( model: GroupMembership, - { transaction }: APIContext["context"] + { transaction }: HookContextFields ) { // Both models guard the same invariant, so they share one lock name, // otherwise the last user manager and the last group manager can be diff --git a/server/models/Reaction.ts b/server/models/Reaction.ts index f3ede25206..b9ff1bd961 100644 --- a/server/models/Reaction.ts +++ b/server/models/Reaction.ts @@ -17,7 +17,7 @@ import { Table, } from "sequelize-typescript"; import { createContext } from "@server/context"; -import type { APIContext } from "@server/types"; +import type { HookContextFields } from "@server/context"; import Comment from "./Comment"; import User from "./User"; import IdModel from "./base/IdModel"; @@ -54,7 +54,7 @@ class Reaction extends IdModel< @AfterCreate public static async addReactionToCommentCache( model: Reaction, - ctx: APIContext["context"] & + ctx: HookContextFields & FindOrCreateOptions, CreationAttributes> ) { const { transaction } = ctx; @@ -86,7 +86,7 @@ class Reaction extends IdModel< comment.reactions = reactions; - // Pass only the fields needed in APIContext; otherwise sequelize props will be overwritten. + // Pass only the fields needed in Context; otherwise sequelize props will be overwritten. const context = createContext({ user: ctx.auth.user, authType: ctx.auth.type, @@ -106,7 +106,7 @@ class Reaction extends IdModel< @AfterDestroy public static async removeReactionFromCommentCache( model: Reaction, - ctx: APIContext["context"] & InstanceDestroyOptions + ctx: HookContextFields & InstanceDestroyOptions ) { const { transaction } = ctx; @@ -139,7 +139,7 @@ class Reaction extends IdModel< comment.reactions = reactions; - // Pass only the fields needed in APIContext; otherwise sequelize props will be overwritten. + // Pass only the fields needed in Context; otherwise sequelize props will be overwritten. const context = createContext({ user: ctx.auth.user, authType: ctx.auth.type, diff --git a/server/models/Revision.ts b/server/models/Revision.ts index 395a47975c..cee2354ea7 100644 --- a/server/models/Revision.ts +++ b/server/models/Revision.ts @@ -16,7 +16,7 @@ import { } from "sequelize-typescript"; import type { ProsemirrorData, SourceMetadata } from "@shared/types"; import { DocumentValidation, RevisionValidation } from "@shared/validations"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import Document from "./Document"; import User from "./User"; import ParanoidModel from "./base/ParanoidModel"; @@ -266,12 +266,12 @@ class Revision extends ParanoidModel< * @returns A Promise that resolves when saved */ static createFromDocument( - ctx: APIContext, + ctx: Context, document: Document, collaboratorIds?: string[] ) { const revision = this.buildFromDocument(document); - const authType = ctx.context.auth?.type; + const authType = ctx.auth?.type; revision.sourceMetadata = authType ? { authType } : null; if (collaboratorIds) { diff --git a/server/models/Share.ts b/server/models/Share.ts index cc6e45c87f..af9e28890b 100644 --- a/server/models/Share.ts +++ b/server/models/Share.ts @@ -18,7 +18,7 @@ import { UrlHelper } from "@shared/utils/UrlHelper"; import { ShareValidation } from "@shared/validations"; import env from "@server/env"; import { ValidationError } from "@server/errors"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import Collection from "./Collection"; import Document from "./Document"; import Team from "./Team"; @@ -323,8 +323,8 @@ class Share extends IdModel< @Column(DataType.UUID) documentId: string | null; - revoke(ctx: APIContext) { - const { user } = ctx.state.auth; + revoke(ctx: Context) { + const { user } = ctx.auth; this.revokedAt = new Date(); this.revokedById = user.id; return this.saveWithCtx(ctx, undefined, { name: "revoke" }); diff --git a/server/models/User.ts b/server/models/User.ts index fb3f78c0e1..6a98df6511 100644 --- a/server/models/User.ts +++ b/server/models/User.ts @@ -1,7 +1,6 @@ import crypto from "node:crypto"; import { addHours, addMinutes, subMinutes } from "date-fns"; import JWT from "jsonwebtoken"; -import type { Context } from "koa"; import type { Transaction, SaveOptions, @@ -52,7 +51,8 @@ import env from "@server/env"; import DeleteAttachmentTask from "@server/queues/tasks/DeleteAttachmentTask"; import { LockHelper } from "@server/storage/LockHelper"; import { afterCommit } from "@server/storage/transaction"; -import type { APIContext } from "@server/types"; +import type { Context, AppContext } from "@server/types"; +import { toHookContext } from "@server/context"; import { VerificationCode } from "@server/utils/VerificationCode"; import parseAttachmentIds from "@server/utils/parseAttachmentIds"; import { CacheHelper } from "@server/utils/CacheHelper"; @@ -582,7 +582,7 @@ class User extends ParanoidModel< * @param force whether to update even if the last update was recent. * @returns a promise that resolves with the updated user. */ - updateActiveAt = async (ctx?: Context, force = false) => { + updateActiveAt = async (ctx?: AppContext, force = false) => { const fiveMinutesAgo = subMinutes(new Date(), 5); // ensure this is updated only every few minutes otherwise @@ -609,13 +609,13 @@ class User extends ParanoidModel< }); }; - updateSignedIn = (ctx: Context | APIContext) => { + updateSignedIn = (ctx: AppContext | Context) => { const now = new Date(); this.lastActiveAt = now; this.lastActiveIp = ctx.request.ip; this.lastSignedInAt = now; this.lastSignedInIp = ctx.request.ip; - return this.save({ hooks: false, transaction: ctx.state.transaction }); + return this.save({ hooks: false, transaction: ctx.transaction }); }; /** @@ -693,7 +693,7 @@ class User extends ParanoidModel< * @param ctx The request context, used to get the IP address of the request * @returns The email signin token */ - getEmailSigninToken = (ctx: Context) => + getEmailSigninToken = (ctx: AppContext) => JWT.sign( { id: this.id, @@ -990,15 +990,15 @@ class User extends ParanoidModel< static findByEmail = async function ( this: typeof User, - ctx: APIContext, + ctx: Context, email: string ) { return this.findOne({ where: { - teamId: ctx.state.auth.user.teamId, + teamId: ctx.auth.user.teamId, email: email.trim().toLowerCase(), }, - ...ctx.context, + ...toHookContext(ctx), }); }; diff --git a/server/models/UserMembership.test.ts b/server/models/UserMembership.test.ts index b3c5c3e50e..0c3457dccf 100644 --- a/server/models/UserMembership.test.ts +++ b/server/models/UserMembership.test.ts @@ -7,7 +7,7 @@ import { buildUser, } from "@server/test/factories"; import { sequelize } from "@server/storage/database"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import Event from "./Event"; import GroupMembership from "./GroupMembership"; import UserMembership from "./UserMembership"; @@ -87,14 +87,14 @@ describe("UserMembership", () => { }); // The user membership goes first, leaving the group as the only manager. - const one = withAPIContext(user, async (ctx) => { + const one = withContext(user, async (ctx) => { await userMembership.destroyWithCtx(ctx); removed(); await held; }); await first; - const two = withAPIContext(user, (ctx) => + const two = withContext(user, (ctx) => groupMembership.destroyWithCtx(ctx) ); await sleep(250); diff --git a/server/models/UserMembership.ts b/server/models/UserMembership.ts index bde81a2beb..9c5fdc1cf0 100644 --- a/server/models/UserMembership.ts +++ b/server/models/UserMembership.ts @@ -29,7 +29,7 @@ import { CollectionPermission } from "@shared/types"; import { ValidationError } from "@server/errors"; import { LockHelper } from "@server/storage/LockHelper"; import { afterCommit } from "@server/storage/transaction"; -import type { APIContext } from "@server/types"; +import type { HookContextFields } from "@server/context"; import { CacheHelper } from "@server/utils/CacheHelper"; import { RedisPrefixHelper } from "@server/utils/RedisPrefixHelper"; import Collection from "./Collection"; @@ -259,7 +259,7 @@ class UserMembership extends IdModel< @AfterCreate static async publishAddUserEventAfterCreate( model: UserMembership, - context: APIContext["context"] + context: HookContextFields ) { await model.insertEvent(context, "add_user", { isNew: true, @@ -311,7 +311,7 @@ class UserMembership extends IdModel< @BeforeUpdate static async checkLastAdminBeforeUpdate( model: UserMembership, - ctx: APIContext["context"] + ctx: HookContextFields ) { if ( model.permission === CollectionPermission.Admin || @@ -326,7 +326,7 @@ class UserMembership extends IdModel< @BeforeDestroy static async checkLastAdminBeforeDestroy( model: UserMembership, - ctx: APIContext["context"] + ctx: HookContextFields ) { // Only check for last admin permission if this permission is admin if ( @@ -341,7 +341,7 @@ class UserMembership extends IdModel< @AfterUpdate static async publishAddUserEventAfterUpdate( model: UserMembership, - context: APIContext["context"] + context: HookContextFields ) { await model.insertEvent(context, "add_user", { isNew: false, @@ -351,7 +351,7 @@ class UserMembership extends IdModel< @AfterDestroy static async publishRemoveUserEvent( model: UserMembership, - context: APIContext["context"] + context: HookContextFields ) { await model.insertEvent(context, "remove_user"); } @@ -454,7 +454,7 @@ class UserMembership extends IdModel< } private async insertEvent( - ctx: APIContext["context"], + ctx: HookContextFields, name: string, data?: Record ) { @@ -487,7 +487,7 @@ class UserMembership extends IdModel< private static async validateLastAdminPermission( model: UserMembership, - { transaction }: APIContext["context"] + { transaction }: HookContextFields ) { // Both models guard the same invariant, so they share one lock name, // otherwise the last user manager and the last group manager can be diff --git a/server/models/View.ts b/server/models/View.ts index d465106284..810dad5117 100644 --- a/server/models/View.ts +++ b/server/models/View.ts @@ -13,7 +13,7 @@ import { DataType, Scopes, } from "sequelize-typescript"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import Document from "./Document"; import Event from "./Event"; import User from "./User"; @@ -61,7 +61,7 @@ class View extends IdModel< documentId: string; static async incrementOrCreate( - ctx: APIContext, + ctx: Context, where: { userId: string; documentId: string; diff --git a/server/models/base/Model.ts b/server/models/base/Model.ts index 3e9cb6eaa5..a81522ccc5 100644 --- a/server/models/base/Model.ts +++ b/server/models/base/Model.ts @@ -23,7 +23,8 @@ import { Model as SequelizeModel, } from "sequelize-typescript"; import Logger from "@server/logging/Logger"; -import type { Replace, APIContext } from "@server/types"; +import type { Replace, Context } from "@server/types"; +import { toHookContext, type HookContextFields } from "@server/context"; import { getChangesetSkipped } from "../decorators/Changeset"; import { InternalError } from "@server/errors"; import { afterCommit } from "@server/storage/transaction"; @@ -48,7 +49,7 @@ type EventOptions = EventOverrideOptions & { publish: boolean; }; -export type HookContext = APIContext["context"] & { event?: EventOptions }; +export type HookContext = HookContextFields & { event?: EventOptions }; class Model< // oxlint-disable-next-line @typescript-eslint/no-explicit-any -- Sequelize's Attributes resolves to never under object default; load-bearing for static helpers like saveWithCtx. @@ -71,12 +72,12 @@ class Model< * Validates this instance, and if the validation passes, persists it to the database. */ public saveWithCtx( - ctx: APIContext, + ctx: Context, options?: SaveOptions>, eventOpts?: EventOverrideOptions ) { const hookContext: HookContext = { - ...ctx.context, + ...toHookContext(ctx), event: { ...eventOpts, publish: true, @@ -89,12 +90,12 @@ class Model< * This is the same as calling `fill` and then calling `save`. */ public updateWithCtx( - ctx: APIContext, + ctx: Context, keys: Partial, eventOpts?: EventOverrideOptions ) { const hookContext: HookContext = { - ...ctx.context, + ...toHookContext(ctx), event: { ...eventOpts, publish: true, @@ -119,9 +120,9 @@ class Model< * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will * either be completely deleted, or have its deletedAt timestamp set to the current time. */ - public destroyWithCtx(ctx: APIContext, eventOpts?: EventOverrideOptions) { + public destroyWithCtx(ctx: Context, eventOpts?: EventOverrideOptions) { const hookContext: HookContext = { - ...ctx.context, + ...toHookContext(ctx), event: { ...eventOpts, publish: true, @@ -133,9 +134,9 @@ class Model< /** * Restore the row corresponding to this instance. Only available for paranoid models. */ - public restoreWithCtx(ctx: APIContext, eventOpts?: EventOverrideOptions) { + public restoreWithCtx(ctx: Context, eventOpts?: EventOverrideOptions) { const hookContext: HookContext = { - ...ctx.context, + ...toHookContext(ctx), event: { ...eventOpts, publish: true, @@ -148,25 +149,25 @@ class Model< * Find a row that matches the query, or build and save the row if none is found. * The successful result of the promise will be (instance, created) - Make sure to use `.then(([...]))` * - * @param ctx The API context. + * @param ctx The context. * @param options The find or create options. * @param eventOpts Optional event override options. * @returns a tuple of the instance and a boolean indicating if it was created. */ public static async findOrCreateWithCtx( this: ModelStatic, - ctx: APIContext, + ctx: Context, options: FindOrCreateOptions, CreationAttributes>, eventOpts?: EventOverrideOptions ): Promise<[M, boolean]> { const hookContext: HookContext = { - ...ctx.context, + ...toHookContext(ctx), event: { ...eventOpts, publish: true, }, }; - const transaction = ctx.context.transaction; + const transaction = ctx.transaction; // First, try to find an existing record const existing = await this.findOne({ @@ -208,19 +209,19 @@ class Model< * each. Rows are matched when the destroy runs, so rows written after the * options were prepared are destroyed too. * - * @param ctx The API context. + * @param ctx The context. * @param options The destroy options. * @param eventOpts Optional event override options. * @returns the number of destroyed rows. */ public static destroyWithCtx( this: ModelStatic, - ctx: APIContext, + ctx: Context, options: DestroyOptions>, eventOpts?: EventOverrideOptions ) { const hookContext = { - ...ctx.context, + ...toHookContext(ctx), ...options, individualHooks: true, event: { @@ -236,13 +237,13 @@ class Model< */ public static createWithCtx( this: ModelStatic, - ctx: APIContext, + ctx: Context, values?: CreationAttributes, eventOpts?: EventOverrideOptions, createOpts?: CreateOptions ) { const hookContext = { - ...ctx.context, + ...toHookContext(ctx), ...createOpts, event: { ...eventOpts, @@ -302,7 +303,7 @@ class Model< * * @param name The name of the event. * @param model The model that was mutated. - * @param context The API context. + * @param context The context. */ protected static async insertEvent( name: string, diff --git a/server/models/base/ParanoidModel.test.ts b/server/models/base/ParanoidModel.test.ts index 0d5c40ea24..abb28a8ec4 100644 --- a/server/models/base/ParanoidModel.test.ts +++ b/server/models/base/ParanoidModel.test.ts @@ -1,4 +1,4 @@ -import { createContext } from "@server/context"; +import { createContext, toHookContext } from "@server/context"; import { buildCollection, buildDocument, @@ -12,7 +12,7 @@ describe("ParanoidModel", () => { const user = await buildUser(); const document = await buildDocument({ teamId: user.teamId }); - await document.destroy(createContext({ user }).context); + await document.destroy(toHookContext(createContext({ user }))); await document.reload({ paranoid: false }); expect(document.deletedAt).toBeTruthy(); @@ -23,7 +23,7 @@ describe("ParanoidModel", () => { const user = await buildUser(); const document = await buildDocument({ teamId: user.teamId }); - await document.destroy(createContext({ user }).context); + await document.destroy(toHookContext(createContext({ user }))); await document.restore(); await document.reload(); @@ -51,7 +51,7 @@ describe("ParanoidModel", () => { userId: user.id, }); - await collection.destroy(createContext({ user }).context); + await collection.destroy(toHookContext(createContext({ user }))); expect(collection.deletedAt).toBeTruthy(); }); diff --git a/server/models/helpers/ProsemirrorHelper.tsx b/server/models/helpers/ProsemirrorHelper.tsx index 739cfae56a..2ecc1ed4be 100644 --- a/server/models/helpers/ProsemirrorHelper.tsx +++ b/server/models/helpers/ProsemirrorHelper.tsx @@ -55,7 +55,7 @@ import { trace } from "@server/logging/tracing"; import Attachment from "@server/models/Attachment"; import User from "@server/models/User"; import FileStorage from "@server/storage/files"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; export type HTMLOptions = { /** A title, if it should be included */ @@ -1242,13 +1242,13 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper { * images — a PDF bundled alongside a document, for example — do not remain * embedded in the document as base64. * - * @param ctx The API context. + * @param ctx The context. * @param doc The Prosemirror node to process. * @param user The user context. * @returns A new Prosemirror node with images and embedded files replaced. */ static async replaceImagesWithAttachments( - ctx: APIContext, + ctx: Context, doc: Node, user: User ): Promise { diff --git a/server/models/helpers/TextHelper.ts b/server/models/helpers/TextHelper.ts index e1cea6ea76..1f736550af 100644 --- a/server/models/helpers/TextHelper.ts +++ b/server/models/helpers/TextHelper.ts @@ -9,7 +9,7 @@ import { trace } from "@server/logging/tracing"; import type { User } from "@server/models"; import { Attachment } from "@server/models"; import FileStorage from "@server/storage/files"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import parseAttachmentIds from "@server/utils/parseAttachmentIds"; import parseImages from "@server/utils/parseImages"; @@ -61,13 +61,13 @@ export class TextHelper { * Replaces remote and base64 encoded images in the given text with attachment * urls and uploads the images to the storage provider. * - * @param ctx The API context + * @param ctx The context * @param markdown The text to replace the images in * @param user The user context * @returns The text with the images replaced */ static async replaceImagesWithAttachments( - ctx: APIContext, + ctx: Context, markdown: string, user: User, options: { diff --git a/server/models/helpers/owners.ts b/server/models/helpers/owners.ts index 49bc7af9fd..5c0ee1e077 100644 --- a/server/models/helpers/owners.ts +++ b/server/models/helpers/owners.ts @@ -3,7 +3,7 @@ import { Op } from "sequelize"; import { UserRole } from "@shared/types"; import { ValidationError } from "@server/errors"; import User from "@server/models/User"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; /** * Validates the requested owners of a document or collection, added owners @@ -19,13 +19,13 @@ import type { APIContext } from "@server/types"; * users cannot be an owner. */ export async function validateOwnerIds( - ctx: APIContext, + ctx: Context, ownerIds: string[], previousOwnerIds: string[], maxOwners: number ): Promise { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const ids = uniq(ownerIds); const addedIds = difference(ids, previousOwnerIds); @@ -69,7 +69,7 @@ export async function validateOwnerIds( * @throws ValidationError when any of the owners are not valid. */ export async function resolveOwnerIds( - ctx: APIContext, + ctx: Context, currentOwnerIds: string[], ownerIds: string[], maxOwners: number diff --git a/server/presenters/collection.ts b/server/presenters/collection.ts index 333a4099c0..9f6e19bf94 100644 --- a/server/presenters/collection.ts +++ b/server/presenters/collection.ts @@ -1,7 +1,7 @@ import { Hour } from "@shared/utils/time"; import type Collection from "@server/models/Collection"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import presentUser from "./user"; type Options = { @@ -18,7 +18,7 @@ type Options = { }; export default async function presentCollection( - ctx: APIContext | undefined, + ctx: Context | undefined, collection: Collection, options: Options = {} ) { diff --git a/server/presenters/document.test.ts b/server/presenters/document.test.ts index 562984cea9..04f4790aec 100644 --- a/server/presenters/document.test.ts +++ b/server/presenters/document.test.ts @@ -5,7 +5,7 @@ import { buildDocument, buildUser, } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import { sequelize } from "@server/storage/database"; describe("presentDocuments", () => { @@ -19,7 +19,7 @@ describe("presentDocuments", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); } const documents = await Document.scope("withDrafts").findAll({ @@ -65,8 +65,8 @@ describe("presentDocuments", () => { teamId: userA.teamId, collectionId: collection.id, }); - await withAPIContext(userA, (ctx) => documentA.destroyWithCtx(ctx)); - await withAPIContext(userB, (ctx) => documentB.destroyWithCtx(ctx)); + await withContext(userA, (ctx) => documentA.destroyWithCtx(ctx)); + await withContext(userB, (ctx) => documentB.destroyWithCtx(ctx)); // One document arrives with the association loaded, the other without. const loaded = await Document.scope("withDrafts").findOne({ diff --git a/server/presenters/document.ts b/server/presenters/document.ts index d6ee205387..1148423e68 100644 --- a/server/presenters/document.ts +++ b/server/presenters/document.ts @@ -5,7 +5,7 @@ import type { Document } from "@server/models"; import FileOperation from "@server/models/FileOperation"; import User from "@server/models/User"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import presentUser from "./user"; type Options = { @@ -27,7 +27,7 @@ type Options = { }; async function presentDocument( - ctx: APIContext | undefined, + ctx: Context | undefined, document: Document, options: Options | null | undefined = {} ) { @@ -161,13 +161,13 @@ export default traceFunction({ * Batch-present multiple documents, fetching all related FileOperation and * deleting User records in a single query instead of one per document. * - * @param ctx the API context. + * @param ctx the context. * @param documents the documents to present. * @param options presentation options forwarded to presentDocument. * @returns array of presented document objects. */ export async function presentDocuments( - ctx: APIContext | undefined, + ctx: Context | undefined, documents: Document[], options?: Options | null ) { diff --git a/server/presenters/integration.ts b/server/presenters/integration.ts index 523fb40c07..05cf5a812d 100644 --- a/server/presenters/integration.ts +++ b/server/presenters/integration.ts @@ -1,15 +1,15 @@ import type { Integration } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; /** * Presents an integration for API responses. * - * @param ctx the API context, used to find the user the integration is presented to. + * @param ctx the context, used to find the user the integration is presented to. * @param integration the integration to present. * @returns the presented integration. */ export default function presentIntegration( - ctx: APIContext | undefined, + ctx: Context | undefined, integration: Integration ) { return { @@ -20,7 +20,7 @@ export default function presentIntegration( authenticationId: integration.authenticationId, service: integration.service, events: integration.events, - settings: integration.presentSettings(ctx?.state.auth.user), + settings: integration.presentSettings(ctx?.auth.user), createdAt: integration.createdAt, updatedAt: integration.updatedAt, }; diff --git a/server/presenters/notification.ts b/server/presenters/notification.ts index 79004b0f3d..ca4970e1e8 100644 --- a/server/presenters/notification.ts +++ b/server/presenters/notification.ts @@ -1,12 +1,12 @@ import type { Notification } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import presentFileOperation from "./fileOperation"; import presentGroup from "./group"; import presentUser from "./user"; import { presentComment, presentDocument } from "."; export default async function presentNotification( - ctx: APIContext | undefined, + ctx: Context | undefined, notification: Notification ) { return { diff --git a/server/queues/tasks/MarkdownAPIImportTask.test.ts b/server/queues/tasks/MarkdownAPIImportTask.test.ts index 92fba4e30b..7c5fa4dffb 100644 --- a/server/queues/tasks/MarkdownAPIImportTask.test.ts +++ b/server/queues/tasks/MarkdownAPIImportTask.test.ts @@ -17,7 +17,7 @@ import { buildDocument, buildImport, } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import MarkdownImportsProcessor from "../processors/MarkdownImportsProcessor"; import UploadAttachmentsForImportTask from "./UploadAttachmentsForImportTask"; import MarkdownAPIImportTask, { @@ -529,7 +529,7 @@ describe("MarkdownAPIImportTask document export archives", () => { userId: admin.id, rejectOnEmpty: true, }); - await withAPIContext(admin, (ctx) => archivable.archiveWithCtx(ctx)); + await withContext(admin, (ctx) => archivable.archiveWithCtx(ctx)); await new MarkdownImportsProcessor().perform({ name: "imports.delete", diff --git a/server/queues/tasks/ShareSubscriptionNotificationsTask.test.ts b/server/queues/tasks/ShareSubscriptionNotificationsTask.test.ts index f696dd6a5d..754af44d74 100644 --- a/server/queues/tasks/ShareSubscriptionNotificationsTask.test.ts +++ b/server/queues/tasks/ShareSubscriptionNotificationsTask.test.ts @@ -11,7 +11,7 @@ import { buildTeam, buildUser, } from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; +import { withContext } from "@server/test/support"; import ShareSubscriptionNotificationsTask from "./ShareSubscriptionNotificationsTask"; const ip = "127.0.0.1"; @@ -431,7 +431,7 @@ describe("ShareSubscriptionNotificationsTask", () => { confirmedAt: new Date(), }); - await withAPIContext(user, (ctx) => + await withContext(user, (ctx) => documentMover(ctx, { document, collectionId: other.id }) ); diff --git a/server/routes/api/accessRequests/accessRequests.ts b/server/routes/api/accessRequests/accessRequests.ts index 3ab19d5d6b..6c43fd1962 100644 --- a/server/routes/api/accessRequests/accessRequests.ts +++ b/server/routes/api/accessRequests/accessRequests.ts @@ -7,7 +7,7 @@ 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 type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import * as T from "./schema"; import { InvalidRequestError, NotFoundError } from "@server/errors"; @@ -20,10 +20,10 @@ router.post( auth(), validate(T.AccessRequestsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { documentId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const document = await Document.findByPk(documentId, { userId: user.id, @@ -57,8 +57,8 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), auth(), validate(T.AccessRequestsInfoSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { id, documentId } = ctx.input.body; let accessRequest: AccessRequest | null = null; @@ -91,10 +91,10 @@ router.post( auth(), validate(T.AccessRequestsApproveSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, permission } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const accessRequest = await AccessRequest.findByPk(id, { rejectOnEmpty: true, @@ -143,10 +143,10 @@ router.post( auth(), validate(T.AccessRequestsDismissSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const accessRequest = await AccessRequest.findByPk(id, { rejectOnEmpty: true, diff --git a/server/routes/api/apiKeys/apiKeys.ts b/server/routes/api/apiKeys/apiKeys.ts index 3bbbaff7d5..5b8391516a 100644 --- a/server/routes/api/apiKeys/apiKeys.ts +++ b/server/routes/api/apiKeys/apiKeys.ts @@ -7,7 +7,7 @@ import validate from "@server/middlewares/validate"; import { ApiKey, User } from "@server/models"; import { authorize, cannot } from "@server/policies"; import { presentApiKey } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { AuthenticationType } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { QueryHelper } from "@server/storage/QueryHelper"; @@ -24,9 +24,9 @@ router.post( }), validate(T.APIKeysCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { name, scope, expiresAt } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createApiKey", user.team); @@ -50,10 +50,10 @@ router.post( auth(), pagination(), validate(T.APIKeysListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { userId, query, sort, direction } = ctx.input.body; const { pagination } = ctx.state; - const actor = ctx.state.auth.user; + const actor = ctx.auth.user; let userWhere: WhereOptions = { teamId: actor.teamId, @@ -120,10 +120,10 @@ router.post( }), validate(T.APIKeysDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const key = await ApiKey.scope("withUser").findByPk(id, { lock: { diff --git a/server/routes/api/attachments/attachments.ts b/server/routes/api/attachments/attachments.ts index 18f203f77e..f9a6d9befb 100644 --- a/server/routes/api/attachments/attachments.ts +++ b/server/routes/api/attachments/attachments.ts @@ -5,7 +5,7 @@ import { AttachmentPreset } from "@shared/types"; import { bytesToHumanReadable, getFileNameFromUrl } from "@shared/utils/files"; import env from "@server/env"; import { AttachmentValidation } from "@shared/validations"; -import { createContext } from "@server/context"; +import { withTransaction } from "@server/context"; import { AuthorizationError, InvalidRequestError, @@ -25,7 +25,7 @@ import pagination from "@server/routes/api/middlewares/pagination"; import { sequelize } from "@server/storage/database"; import FileStorage from "@server/storage/files"; import BaseStorage from "@server/storage/files/BaseStorage"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { assertIn } from "@server/validation"; import * as T from "./schema"; @@ -68,9 +68,9 @@ router.post( auth(), pagination(), validate(T.AttachmentsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { documentId, userId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const where: WhereOptions = { teamId: user.teamId, @@ -115,9 +115,9 @@ router.post( auth(), validate(T.AttachmentsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, name, documentId, contentType, size, preset } = ctx.input.body; - const { auth, transaction } = ctx.state; + const { auth, transaction } = ctx; const { user } = auth; if (documentId) { @@ -228,9 +228,9 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), auth(), validate(T.AttachmentsCreateFromUrlSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, url, documentId, preset } = ctx.input.body; - const { user, type } = ctx.state.auth; + const { user } = ctx.auth; if (preset !== AttachmentPreset.DocumentAttachment || !documentId) { throw ValidationError( @@ -252,25 +252,17 @@ router.post( // Does not use transaction middleware, as attachment must be persisted // before the job is scheduled. const attachment = await sequelize.transaction(async (transaction) => - Attachment.createWithCtx( - createContext({ - authType: type, - user, - ip: ctx.ip, - transaction, - }), - { - id: modelId, - key, - acl, - size: 0, - expiresAt: AttachmentHelper.presetToExpiry(preset), - contentType: "application/octet-stream", - documentId, - teamId: user.teamId, - userId: user.id, - } - ) + Attachment.createWithCtx(withTransaction(ctx, transaction), { + id: modelId, + key, + acl, + size: 0, + expiresAt: AttachmentHelper.presetToExpiry(preset), + contentType: "application/octet-stream", + documentId, + teamId: user.teamId, + userId: user.id, + }) ); const job = await new UploadAttachmentFromUrlTask().schedule({ @@ -296,10 +288,10 @@ router.post( auth(), validate(T.AttachmentDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const attachment = await Attachment.findByPk(id, { rejectOnEmpty: true, lock: transaction.LOCK.UPDATE, @@ -320,11 +312,11 @@ router.post( ); const handleAttachmentsRedirect = async ( - ctx: APIContext + ctx: Context ) => { const id = (ctx.input.body.id ?? ctx.input.query.id) as string; - const user = ctx.state.auth?.user; + const user = ctx.auth?.user; const attachment = await Attachment.findByPk(id, { rejectOnEmpty: true, }); diff --git a/server/routes/api/auth/auth.ts b/server/routes/api/auth/auth.ts index 16bc88f02e..3a45d527d1 100644 --- a/server/routes/api/auth/auth.ts +++ b/server/routes/api/auth/auth.ts @@ -19,7 +19,7 @@ import { presentGroupUser, } from "@server/presenters"; import ValidateSSOAccessTask from "@server/queues/tasks/ValidateSSOAccessTask"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { AuthenticationType } from "@server/types"; import { clearCSRFCookie } from "@server/utils/csrf"; import { getJWTPayload } from "@server/utils/jwt"; @@ -29,7 +29,7 @@ import type * as T from "./schema"; const router = new Router(); -router.post("auth.config", async (ctx: APIContext) => { +router.post("auth.config", async (ctx: Context) => { // If self hosted AND there is only one team then that team becomes the // brand for the knowledge base and its guest sign-in option is used for the // root login page. @@ -122,8 +122,8 @@ router.post("auth.config", async (ctx: APIContext) => { /** Authentication services that don't require SSO validation. */ const NON_SSO_SERVICES = ["email", "passkeys"]; -router.post("auth.info", auth(), async (ctx: APIContext) => { - const { user, service, type, token } = ctx.state.auth; +router.post("auth.info", auth(), async (ctx: Context) => { + const { user, service, type, token } = ctx.auth; const [team, groups, availableTeams] = await Promise.all([ Team.scope("withDomains").findByPk(user.teamId, { rejectOnEmpty: true, @@ -194,8 +194,8 @@ router.post( "auth.delete", auth(), transaction(), - async (ctx: APIContext) => { - const { auth, transaction } = ctx.state; + async (ctx: Context) => { + const { auth, transaction } = ctx; const { user, token } = auth; await user.rotateJwtSecret({ transaction }); diff --git a/server/routes/api/authenticationProviders/authenticationProviders.ts b/server/routes/api/authenticationProviders/authenticationProviders.ts index 34580ecff0..03d6876d66 100644 --- a/server/routes/api/authenticationProviders/authenticationProviders.ts +++ b/server/routes/api/authenticationProviders/authenticationProviders.ts @@ -13,7 +13,7 @@ import { presentAuthenticationProvider, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import * as T from "./schema"; const router = new Router(); @@ -22,9 +22,9 @@ router.post( "authenticationProviders.info", auth({ role: UserRole.Admin }), validate(T.AuthenticationProvidersInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const authenticationProvider = await AuthenticationProvider.findByPk(id); authorize(user, "read", authenticationProvider); @@ -41,10 +41,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.AuthenticationProvidersUpdateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, isEnabled, settings } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const authenticationProvider = await AuthenticationProvider.findByPk(id, { transaction, @@ -102,8 +102,8 @@ router.post( "authenticationProviders.startGroupSync", auth({ role: UserRole.Admin }), validate(T.AuthenticationProvidersStartGroupSyncSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const authenticationProvider = await AuthenticationProvider.findByPk( ctx.input.body.id ); @@ -140,10 +140,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.AuthenticationProvidersDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const authenticationProvider = await AuthenticationProvider.findByPk(id, { transaction, @@ -173,8 +173,8 @@ router.post( router.post( "authenticationProviders.list", auth({ role: UserRole.Admin }), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; authorize(user, "read", user.team); const teamAuthenticationProviders = (await user.team.$get( diff --git a/server/routes/api/batch/batch.ts b/server/routes/api/batch/batch.ts index 555f145cba..95ecb1a386 100644 --- a/server/routes/api/batch/batch.ts +++ b/server/routes/api/batch/batch.ts @@ -14,7 +14,7 @@ import { rateLimiter, } from "@server/middlewares/rateLimiter"; import validate from "@server/middlewares/validate"; -import type { APIContext, AppContext } from "@server/types"; +import type { Context, AppContext } from "@server/types"; import { AuthenticationType } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { BatchableApiMethods } from "@shared/constants"; @@ -115,9 +115,11 @@ function createSubContext( body: T.BatchRequestBody ) { const sub: AppContext = Object.create(ctx); - // A shallow copy so middleware writes (auth, transaction) don't leak between - // concurrent sub-requests or back to the parent. + // Own copies so middleware writes don't leak between concurrent sub-requests + // or back to the parent. sub.state = { ...ctx.state }; + sub.auth = ctx.auth; + sub.transaction = ctx.transaction; sub.request = Object.create(ctx.request); // The parent's credential is the actor for every sub-request, so a token in // the sub-request body must not re-authenticate it as a different one. @@ -153,16 +155,6 @@ function createSubContext( captured.status = value; }, }); - // Re-bind ctx.context to this child so mutations use the child's transaction - // rather than the parent's (the getter from apiContext closes over its ctx). - Object.defineProperty(sub, "context", { - configurable: true, - get: () => ({ - auth: sub.state.auth, - transaction: sub.state.transaction, - ip: sub.request.ip, - }), - }); return { sub, captured }; } @@ -275,7 +267,7 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), auth({ type: AuthenticationType.APP }), validate(T.BatchSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { requests } = ctx.input.body; // Sub-request routes would otherwise be appended to the APM route name. diff --git a/server/routes/api/collections/collections.ts b/server/routes/api/collections/collections.ts index 1d502b6de7..4df0397fc3 100644 --- a/server/routes/api/collections/collections.ts +++ b/server/routes/api/collections/collections.ts @@ -47,7 +47,8 @@ import { presentGroupMembership, presentFileOperation, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; +import { toHookContext } from "@server/context"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { collectionIndexing } from "@server/utils/indexing"; import { QueryHelper } from "@server/storage/QueryHelper"; @@ -63,8 +64,8 @@ router.post( auth(), validate(T.CollectionsCreateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { name, color, @@ -80,7 +81,7 @@ router.post( ownerIds, } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createCollection", user.team); const collection = Collection.build({ @@ -129,10 +130,10 @@ router.post( auth(), validate(T.CollectionsDuplicateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, name } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -157,9 +158,9 @@ router.post( "collections.info", auth(), validate(T.CollectionsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, includeArchivedBy: true, @@ -179,9 +180,9 @@ router.post( "collections.documents", auth(), validate(T.CollectionsDocumentsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, }); @@ -202,10 +203,10 @@ router.post( auth(), validate(T.CollectionsImportSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { attachmentId, permission, format } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "importCollection", user.team); const attachment = await Attachment.findByPk(attachmentId, { @@ -247,10 +248,10 @@ router.post( auth(), validate(T.CollectionsAddGroupSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, groupId, permission } = ctx.input.body; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; const [collection, group] = await Promise.all([ Collection.findByPk(id, { userId: user.id, transaction }), @@ -267,7 +268,7 @@ router.post( if (membership) { if (permission !== undefined) { membership.permission = permission; - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } else { membership = await GroupMembership.create( @@ -277,7 +278,7 @@ router.post( permission: permission ?? CollectionPermission.ReadWrite, createdById: user.id, }, - ctx.context + toHookContext(ctx) ); } @@ -296,10 +297,10 @@ router.post( auth(), validate(T.CollectionsRemoveGroupSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, groupId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const [collection, group] = await Promise.all([ Collection.findByPk(id, { @@ -324,7 +325,7 @@ router.post( ); } - await membership.destroy(ctx.context); + await membership.destroy(toHookContext(ctx)); ctx.body = { success: true, @@ -337,9 +338,9 @@ router.post( auth(), pagination(), validate(T.CollectionsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -403,9 +404,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), validate(T.CollectionsAddUserSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user: actor } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user: actor } = ctx.auth; const { id, userId, permission, owner } = ctx.input.body; const [collection, user] = await Promise.all([ @@ -445,7 +446,7 @@ router.post( if (membership) { if (permission !== undefined) { membership.permission = permission; - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } else { membership = await UserMembership.create( @@ -455,7 +456,7 @@ router.post( permission: permission || user.defaultCollectionPermission, createdById: actor.id, }, - ctx.context + toHookContext(ctx) ); } @@ -486,9 +487,9 @@ router.post( auth(), validate(T.CollectionsRemoveUserSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user: actor } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user: actor } = ctx.auth; const { id, userId } = ctx.input.body; const [collection, user] = await Promise.all([ @@ -506,7 +507,7 @@ router.post( ctx.throw(InvalidRequestError("User is not a collection member")); } - await membership.destroy(ctx.context); + await membership.destroy(toHookContext(ctx)); await collection.removeOwner(ctx, userId); ctx.body = { @@ -520,9 +521,9 @@ router.post( auth(), pagination(), validate(T.CollectionsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -582,10 +583,10 @@ router.post( auth({ role: UserRole.Member }), validate(T.CollectionsExportSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, format, includeAttachments } = ctx.input.body; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; const { team } = user; const collection = await Collection.findByPk(id, { @@ -616,10 +617,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.CollectionsExportAllSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { format, includeAttachments, includePrivate } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const team = await Team.findByPk(user.teamId, { transaction }); authorize(user, "createExport", team); @@ -644,8 +645,8 @@ router.post( auth(), validate(T.CollectionsUpdateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, name, @@ -668,7 +669,7 @@ router.post( (key) => key === "id" || key === "deprecatedReason" ); - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, includeArchivedBy: updatingDeprecatedReason, @@ -783,15 +784,15 @@ router.post( validate(T.CollectionsListSchema), pagination(), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { includeListOnly, query, statusFilter, filters: rawFilters, } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const collectionIds = await user.collectionIds({ transaction }); const where: WhereOptions & { @@ -893,10 +894,10 @@ router.post( auth(), validate(T.CollectionsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, reason } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -922,10 +923,10 @@ router.post( auth(), validate(T.CollectionsArchiveSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, reason } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collection = await Collection.findByPk(id, { userId: user.id, @@ -953,10 +954,10 @@ router.post( auth(), validate(T.CollectionsRestoreSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let collection = await Collection.findByPk(id, { userId: user.id, @@ -1003,10 +1004,10 @@ router.post( auth(), validate(T.CollectionsMoveSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, index } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let collection = await Collection.findByPk(id, { transaction, diff --git a/server/routes/api/comments/comments.ts b/server/routes/api/comments/comments.ts index 84041db547..2cd446f0b0 100644 --- a/server/routes/api/comments/comments.ts +++ b/server/routes/api/comments/comments.ts @@ -16,7 +16,8 @@ import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import { TextHelper } from "@server/models/helpers/TextHelper"; import { authorize } from "@server/policies"; import { presentComment, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; +import { toHookContext } from "@server/context"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -30,7 +31,7 @@ router.post( commentingEnabled(), validate(T.CommentsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, documentId, @@ -40,8 +41,8 @@ router.post( anchorSuffix, anchorNodeId, } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const anchored = !!(anchorText || anchorNodeId); if (anchored) { @@ -109,7 +110,7 @@ router.post( // as updated by adding a comment. await document.update( { state: updated.state, content: updated.content }, - { ...ctx.context, transaction, silent: true } + { ...toHookContext(ctx), transaction, silent: true } ); } @@ -135,9 +136,9 @@ router.post( auth(), commentingEnabled(), validate(T.CommentsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, includeAnchorText } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const comment = await Comment.findByPk(id, { rejectOnEmpty: true, @@ -165,7 +166,7 @@ router.post( pagination(), commentingEnabled(), validate(T.CommentsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, @@ -175,7 +176,7 @@ router.post( collectionId, includeAnchorText, } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "listComments", user.team); let document: Document | null = null; @@ -221,10 +222,10 @@ router.post( commentingEnabled(), validate(T.CommentsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -297,10 +298,10 @@ router.post( commentingEnabled(), validate(T.CommentsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -331,10 +332,10 @@ router.post( commentingEnabled(), validate(T.CommentsResolveSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -367,10 +368,10 @@ router.post( commentingEnabled(), validate(T.CommentsUnresolveSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -404,10 +405,10 @@ router.post( commentingEnabled(), validate(T.CommentsReactionSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, emoji } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -460,10 +461,10 @@ router.post( commentingEnabled(), validate(T.CommentsReactionSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, emoji } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const comment = await Comment.findByPk(id, { transaction, @@ -488,7 +489,7 @@ router.post( }); authorize(user, "delete", reaction); - await reaction.destroy(ctx.context); + await reaction.destroy(toHookContext(ctx)); ctx.body = { success: true, diff --git a/server/routes/api/cron/cron.ts b/server/routes/api/cron/cron.ts index a4d56b1d91..09dc88652b 100644 --- a/server/routes/api/cron/cron.ts +++ b/server/routes/api/cron/cron.ts @@ -5,7 +5,7 @@ import Logger from "@server/logging/Logger"; import validate from "@server/middlewares/validate"; import tasks from "@server/queues/tasks"; import { CronTask, TaskInterval } from "@server/queues/tasks/base/CronTask"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { safeEqual } from "@server/utils/crypto"; import * as T from "./schema"; import { Minute } from "@shared/utils/time"; @@ -13,7 +13,7 @@ import { Minute } from "@shared/utils/time"; const router = new Router(); const receivedPeriods = new Set(); -const cronHandler = async (ctx: APIContext) => { +const cronHandler = async (ctx: Context) => { const period = Object.values(TaskInterval).includes( ctx.params.period as TaskInterval ) diff --git a/server/routes/api/developer/developer.ts b/server/routes/api/developer/developer.ts index dfa7166dce..655bc28589 100644 --- a/server/routes/api/developer/developer.ts +++ b/server/routes/api/developer/developer.ts @@ -1,4 +1,4 @@ -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import Router from "@koa/router"; import { Op } from "sequelize"; import { randomString, randomElement } from "@shared/random"; @@ -12,13 +12,16 @@ import validate from "@server/middlewares/validate"; import { Document, Notification, User } from "@server/models"; import presentNotification from "@server/presenters/notification"; import { presentUser } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context, AppContext } from "@server/types"; import * as T from "./schema"; const router = new Router(); function dev() { - return async function checkDevelopmentMiddleware(ctx: Context, next: Next) { + return async function checkDevelopmentMiddleware( + ctx: AppContext, + next: Next + ) { if (env.ENVIRONMENT !== "development") { throw new Error("Attempted to access development route in production"); } @@ -32,7 +35,7 @@ router.post( dev(), auth(), validate(T.CreateTestUsersSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { count } = ctx.input.body; const invites = Array(Math.min(count, 100)) .fill(0) @@ -69,9 +72,9 @@ router.post( dev(), auth(), validate(T.CreateTestNotificationsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { count } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const events = [ NotificationEventType.UpdateDocument, diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index c13c233cfa..1624d2bbf3 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -53,7 +53,7 @@ import { import { getTestServer, readZipResponse, - withAPIContext, + withContext, } from "@server/test/support"; const server = getTestServer(); @@ -210,7 +210,7 @@ describe("#documents.info", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.info", user, { body: { id: document.id, @@ -491,7 +491,7 @@ describe("#documents.info", () => { teamId: document.teamId, userId: user.id, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.info", { body: { shareId: share.id, @@ -690,7 +690,7 @@ describe("#documents.export", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.export", user, { body: { id: document.id, @@ -1044,7 +1044,7 @@ describe("#documents.list", () => { collectionId: collection.id, }), ]); - await withAPIContext(user, (ctx) => docs[0].archiveWithCtx(ctx)); + await withContext(user, (ctx) => docs[0].archiveWithCtx(ctx)); const res = await server.post("/api/documents.list", user, { body: { statusFilter: [StatusFilter.Archived], @@ -1085,8 +1085,8 @@ describe("#documents.list", () => { }), ]); await Promise.all([ - withAPIContext(user, (ctx) => docs[0].archiveWithCtx(ctx)), - withAPIContext(user, (ctx) => docs[1].archiveWithCtx(ctx)), + withContext(user, (ctx) => docs[0].archiveWithCtx(ctx)), + withContext(user, (ctx) => docs[1].archiveWithCtx(ctx)), ]); const res = await server.post("/api/documents.list", user, { body: { @@ -3519,7 +3519,7 @@ describe("#documents.search", () => { text: "search term", teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.search", user, { body: { query: "search term", @@ -3538,7 +3538,7 @@ describe("#documents.search", () => { text: "search term", teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.search", user, { body: { query: "search term", @@ -4652,10 +4652,8 @@ describe("#documents.archived", () => { ]); await Promise.all([ - withAPIContext(user, (ctx) => - documentInFirstCollection.archiveWithCtx(ctx) - ), - withAPIContext(user, (ctx) => + withContext(user, (ctx) => documentInFirstCollection.archiveWithCtx(ctx)), + withContext(user, (ctx) => documentInSecondCollection.archiveWithCtx(ctx) ), ]); @@ -4694,10 +4692,8 @@ describe("#documents.archived", () => { ]); await Promise.all([ - withAPIContext(user, (ctx) => - documentInFirstCollection.archiveWithCtx(ctx) - ), - withAPIContext(user, (ctx) => + withContext(user, (ctx) => documentInFirstCollection.archiveWithCtx(ctx)), + withContext(user, (ctx) => documentInSecondCollection.archiveWithCtx(ctx) ), ]); @@ -4714,7 +4710,7 @@ describe("#documents.archived", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.archived", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4727,7 +4723,7 @@ describe("#documents.archived", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.archived", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4743,7 +4739,7 @@ describe("#documents.archived", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.archived", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4769,7 +4765,7 @@ describe("#documents.deleted", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4797,9 +4793,9 @@ describe("#documents.deleted", () => { collectionId: null, }); await Promise.all([ - withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)), - withAPIContext(user, (ctx) => draftDocument.destroyWithCtx(ctx)), - withAPIContext(user2, (ctx) => otherUserDraft.destroyWithCtx(ctx)), + withContext(user, (ctx) => document.destroyWithCtx(ctx)), + withContext(user, (ctx) => draftDocument.destroyWithCtx(ctx)), + withContext(user2, (ctx) => otherUserDraft.destroyWithCtx(ctx)), ]); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); @@ -4816,7 +4812,7 @@ describe("#documents.deleted", () => { userId: admin.id, teamId: admin.teamId, }); - await withAPIContext(admin, (ctx) => document.destroyWithCtx(ctx)); + await withContext(admin, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", admin); const body = await res.json(); expect(res.status).toEqual(200); @@ -4835,7 +4831,7 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -4856,8 +4852,8 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); - await withAPIContext(other, (ctx) => otherDocument.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(other, (ctx) => otherDocument.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user, { body: { @@ -4896,7 +4892,7 @@ describe("#documents.deleted", () => { collectionId: collection.id, parentDocumentId: document.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); await childDocument.reload({ paranoid: false }); expect(childDocument.deletedById).toEqual(user.id); @@ -4921,7 +4917,7 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.info", user, { body: { id: document.id }, @@ -4965,7 +4961,7 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); await Document.update( { deletedAt: subDays(new Date(), 10) }, { @@ -5014,9 +5010,9 @@ describe("#documents.deleted", () => { teamId: user.teamId, collectionId: collection.id, }); - await withAPIContext(user, (ctx) => ownDraft.destroyWithCtx(ctx)); - await withAPIContext(other, (ctx) => otherDraft.destroyWithCtx(ctx)); - await withAPIContext(other, (ctx) => otherDocument.destroyWithCtx(ctx)); + await withContext(user, (ctx) => ownDraft.destroyWithCtx(ctx)); + await withContext(other, (ctx) => otherDraft.destroyWithCtx(ctx)); + await withContext(other, (ctx) => otherDocument.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); @@ -5043,7 +5039,7 @@ describe("#documents.deleted", () => { userId: user.id, permission: DocumentPermission.ReadWrite, }); - await withAPIContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx)); + await withContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); @@ -5071,7 +5067,7 @@ describe("#documents.deleted", () => { permission: DocumentPermission.ReadWrite, createdById: other.id, }); - await withAPIContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx)); + await withContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx)); const res = await server.post("/api/documents.deleted", user); const body = await res.json(); @@ -5897,7 +5893,7 @@ describe("#documents.restore", () => { collectionId: collection.id, teamId: team.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); await collection.destroy({ hooks: false }); const res = await server.post("/api/documents.restore", user, { @@ -5926,7 +5922,7 @@ describe("#documents.restore", () => { collectionId: collection.id, teamId: team.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); await collection.destroy({ hooks: false }); const res = await server.post("/api/documents.restore", user, { @@ -5996,7 +5992,7 @@ describe("#documents.restore", () => { teamId: user.teamId, deprecatedReason: "Outdated", }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.restore", user, { body: { id: document.id, @@ -6030,7 +6026,7 @@ describe("#documents.restore", () => { parentDocumentId: child.id, deprecatedReason: "Grandchild is outdated", }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.restore", user, { body: { id: document.id }, }); @@ -6054,8 +6050,8 @@ describe("#documents.restore", () => { collectionId: document.collectionId, parentDocumentId: document.id, }); - await withAPIContext(user, (ctx) => childDocument.archiveWithCtx(ctx)); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => childDocument.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.restore", user, { body: { id: childDocument.id, @@ -7509,7 +7505,7 @@ describe("#documents.update", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.update", user, { body: { id: document.id, @@ -8195,7 +8191,7 @@ describe("#documents.unpublish", () => { teamId: user.teamId, parentDocumentId: document.id, }); - await withAPIContext(user, (ctx) => child.archiveWithCtx(ctx)); + await withContext(user, (ctx) => child.archiveWithCtx(ctx)); const res = await server.post("/api/documents.unpublish", user, { body: { id: document.id, @@ -8254,7 +8250,7 @@ describe("#documents.unpublish", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/documents.unpublish", user, { body: { id: document.id, @@ -8269,7 +8265,7 @@ describe("#documents.unpublish", () => { userId: user.id, teamId: user.teamId, }); - await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + await withContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.unpublish", user, { body: { id: document.id, diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index ed7327f126..b19852e018 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -97,7 +97,8 @@ import { import DocumentImportTask from "@server/queues/tasks/DocumentImportTask"; import EmptyTrashTask from "@server/queues/tasks/EmptyTrashTask"; import FileStorage from "@server/storage/files"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; +import { toHookContext } from "@server/context"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { convertBareUrlsToEmbedMarkdown } from "@server/utils/embeds"; import { streamZipResponse } from "@server/utils/koa"; @@ -184,7 +185,7 @@ router.post( auth(), pagination(), validate(T.DocumentsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, @@ -198,7 +199,7 @@ router.post( const { offset, limit } = ctx.state.pagination; // always filter by the current team - const { user } = ctx.state.auth; + const { user } = ctx.auth; const where: WhereOptions & { [Op.and]: WhereOptions[]; } = { @@ -459,9 +460,9 @@ router.post( auth({ role: UserRole.Member }), pagination(), validate(T.DocumentsArchivedSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, collectionId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (sort === "index") { throw ValidationError( @@ -516,9 +517,9 @@ router.post( auth({ role: UserRole.Member }), pagination(), validate(T.DocumentsDeletedSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, filters: rawFilters } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const collectionIds = await user.collectionIds({ paranoid: false, }); @@ -594,9 +595,9 @@ router.post( auth(), pagination(), validate(T.DocumentsViewedSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const viewIds = await View.findAccessibleIds(user, { sort, direction, @@ -642,9 +643,9 @@ router.post( auth(), pagination(), validate(T.DocumentsDraftsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { collectionId, dateFilter, direction, sort } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (collectionId) { const collection = await Collection.findByPk(collectionId, { @@ -698,9 +699,9 @@ router.post( "documents.info", auth({ optional: true }), validate(T.DocumentsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, shareId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const apiVersion = getAPIVersion(ctx); let document: Document | null; @@ -781,9 +782,9 @@ router.post( "documents.insights", auth(), validate(T.DocumentsInsightsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, startDate, endDate } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -820,9 +821,9 @@ router.post( auth(), pagination(), validate(T.DocumentsUsersSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, userId, query } = ctx.input.body; - const actor = ctx.state.auth.user; + const actor = ctx.auth.user; const document = await Document.findByPk(id, { userId: actor.id, includeContent: false, @@ -905,9 +906,9 @@ router.post( "documents.documents", auth(), validate(T.DocumentsChildrenSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, includeContent: false, @@ -935,9 +936,9 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), auth(), validate(T.DocumentsExportSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, signedUrls, includeChildDocuments } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const accept = ctx.request.headers["accept"]; const document = await documentLoader({ @@ -1141,10 +1142,10 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsRestoreSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, collectionId, revisionId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const document = await Document.findByPk(id, { userId: user.id, paranoid: false, @@ -1167,12 +1168,12 @@ router.post( pagination(), rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsSearchTitlesSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { query, sort, direction, filters: rawFilters } = ctx.input.body; const { collectionId, userId, documentId, statusFilter, dateFilter } = ctx.input.body; const { offset, limit } = ctx.state.pagination; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const filter = combineFilters(rawFilters) ?? legacyParamsToFilter({ @@ -1217,7 +1218,7 @@ router.post( pagination(), rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsSearchSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { query, shareId, @@ -1239,7 +1240,7 @@ router.post( dateFilter, }); const { offset, limit } = ctx.state.pagination; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let teamId; let response; @@ -1360,7 +1361,7 @@ router.post( shareId: share?.id, // auth.type values are a subset of search sources; unauthenticated share searches default to "app" source: - (ctx.state.auth.type as unknown as SearchQuerySource) || + (ctx.auth.type as unknown as SearchQuerySource) || SearchQuerySource.App, query, results: total, @@ -1383,10 +1384,10 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), validate(T.DocumentsTemplatizeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, collectionId, publish } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const original = await Document.findByPk(id, { userId: user.id, @@ -1438,8 +1439,8 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsUpdateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, insightsEnabled, publish, collectionId, ...input } = ctx.input.body; const updatingDeprecatedReason = @@ -1449,7 +1450,7 @@ router.post( ); const editorVersion = ctx.headers["x-editor-version"] as string | undefined; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let collection: Collection | null | undefined; let document = await Document.findByPk(id, { @@ -1511,11 +1512,11 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), validate(T.DocumentsDuplicateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, title, publish, recursive, collectionId, parentDocumentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -1589,11 +1590,11 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsMoveSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, parentDocumentId, index } = ctx.input.body; let collectionId = ctx.input.body.collectionId; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, transaction, @@ -1645,10 +1646,10 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsArchiveSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, reason } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const document = await Document.findByPk(id, { userId: user.id, @@ -1676,10 +1677,10 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { id, permanent, reason } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (permanent) { const document = await Document.findByPk(id, { @@ -1725,9 +1726,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsUnpublishSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, detach } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -1752,10 +1753,10 @@ router.post( optional: true, }), validate(T.DocumentsImportSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { collectionId, parentDocumentId, publish, attachmentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (!attachmentId && !ctx.input.file) { throw ValidationError("one of attachmentId or file is required"); @@ -1808,7 +1809,7 @@ router.post( collectionId: collection?.id, parentDocumentId, publish, - authType: ctx.state.auth.type, + authType: ctx.auth.type, ip: ctx.request.ip, }); @@ -1825,7 +1826,7 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), validate(T.DocumentsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, title, @@ -1844,8 +1845,8 @@ router.post( } = ctx.input.body; const editorVersion = ctx.headers["x-editor-version"] as string | undefined; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; const { collection } = await authorizeDocumentCreate(ctx, { collectionId, @@ -1906,9 +1907,9 @@ router.post( validate(T.DocumentsAddUserSchema), rateLimiter(RateLimiterStrategy.OneHundredPerHour), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user: actor } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user: actor } = ctx.auth; const { id, userId, permission, owner } = ctx.input.body; // Users can only change their own ownership, not their own access. @@ -2004,7 +2005,7 @@ router.post( membership.permission = permission; // disconnect from the source if the permission is manually updated membership.sourceId = null; - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } else { membership = await UserMembership.create( @@ -2015,7 +2016,7 @@ router.post( permission: permission || user.defaultDocumentPermission, createdById: actor.id, }, - ctx.context + toHookContext(ctx) ); } @@ -2044,9 +2045,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), validate(T.DocumentsRemoveUserSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user: actor } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user: actor } = ctx.auth; const { id, userId } = ctx.input.body; const [document, user] = await Promise.all([ @@ -2082,7 +2083,7 @@ router.post( ); } - await membership.destroy(ctx.context); + await membership.destroy(toHookContext(ctx)); await document.removeOwner(ctx, userId); ctx.body = { @@ -2097,10 +2098,10 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), validate(T.DocumentsAddGroupSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, groupId, permission } = ctx.input.body; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; const [document, group] = await Promise.all([ Document.findByPk(id, { @@ -2126,7 +2127,7 @@ router.post( membership.permission = permission; // disconnect from the source if the permission is manually updated membership.sourceId = null; - await membership.save(ctx.context); + await membership.save(toHookContext(ctx)); } } else { membership = await GroupMembership.create( @@ -2136,7 +2137,7 @@ router.post( permission: permission ?? DocumentPermission.ReadWrite, createdById: user.id, }, - ctx.context + toHookContext(ctx) ); } @@ -2154,9 +2155,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), validate(T.DocumentsRemoveGroupSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user } = ctx.auth; const { id, groupId } = ctx.input.body; const [document, group] = await Promise.all([ @@ -2183,7 +2184,7 @@ router.post( rejectOnEmpty: true, }); - await membership.destroy(ctx.context); + await membership.destroy(toHookContext(ctx)); ctx.body = { success: true, @@ -2196,9 +2197,9 @@ router.post( auth(), pagination(), validate(T.DocumentsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user: actor } = ctx.state.auth; + const { user: actor } = ctx.auth; const document = await Document.findByPk(id, { userId: actor.id }); authorize(actor, "update", document); @@ -2256,9 +2257,9 @@ router.post( auth(), pagination(), validate(T.DocumentsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(id, { userId: user.id }); authorize(user, "update", document); @@ -2319,8 +2320,8 @@ router.post( "documents.empty_trash", auth({ role: UserRole.Admin }), rateLimiter(RateLimiterStrategy.TenPerHour), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const collectionIds = await user.collectionIds({ paranoid: false, @@ -2365,7 +2366,7 @@ router.post( ); // Remove this helper once apiVersion is removed (#6175) -function getAPIVersion(ctx: APIContext) { +function getAPIVersion(ctx: Context) { return Number( ctx.headers["x-api-version"] ?? (typeof ctx.input.body === "object" && diff --git a/server/routes/api/emojis/emojis.ts b/server/routes/api/emojis/emojis.ts index a91539472f..4e850ba1d8 100644 --- a/server/routes/api/emojis/emojis.ts +++ b/server/routes/api/emojis/emojis.ts @@ -9,7 +9,7 @@ import { Emoji, User, Attachment } from "@server/models"; import BaseStorage from "@server/storage/files/BaseStorage"; import { authorize } from "@server/policies"; import { presentEmoji, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -24,9 +24,9 @@ router.post( "emojis.info", auth(), validate(T.EmojisInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, name } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const include = [ { @@ -71,9 +71,9 @@ router.get( "emojis.redirect", auth({ optional: true }), validate(T.EmojisRedirectSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, shareId } = ctx.input.query; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const emoji = await Emoji.unscoped().findByPk(id, { rejectOnEmpty: true, @@ -116,8 +116,8 @@ router.post( auth(), pagination(), validate(T.EmojisListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { query } = ctx.input.body; let where: WhereOptions = { @@ -169,10 +169,10 @@ router.post( auth(), validate(T.EmojisCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { name, attachmentId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; authorize(user, "createEmoji", user.team); const attachment = await Attachment.findByPk(attachmentId, { @@ -207,10 +207,10 @@ router.post( auth(), validate(T.EmojisUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, attachmentId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const emoji = await Emoji.findByPk(id, { transaction, @@ -261,13 +261,13 @@ router.post( auth(), validate(T.EmojisDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const emoji = await Emoji.findByPk(id, { - transaction: ctx.state.transaction, + transaction: ctx.transaction, rejectOnEmpty: true, lock: transaction.LOCK.UPDATE, }); diff --git a/server/routes/api/events/events.ts b/server/routes/api/events/events.ts index 24c611fec3..d8cc1e45af 100644 --- a/server/routes/api/events/events.ts +++ b/server/routes/api/events/events.ts @@ -8,7 +8,7 @@ import validate from "@server/middlewares/validate"; import { Event, User, Collection, Document } from "@server/models"; import { authorize } from "@server/policies"; import { presentEvent } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -19,8 +19,8 @@ router.post( auth(), pagination(), validate(T.EventsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { name, events, diff --git a/server/routes/api/fileOperations/fileOperations.ts b/server/routes/api/fileOperations/fileOperations.ts index a710c609c6..8299780fcd 100644 --- a/server/routes/api/fileOperations/fileOperations.ts +++ b/server/routes/api/fileOperations/fileOperations.ts @@ -9,7 +9,7 @@ import { FileOperation, Team } from "@server/models"; import { authorize } from "@server/policies"; import { presentFileOperation, presentPolicies } from "@server/presenters"; import FileStorage from "@server/storage/files"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -19,9 +19,9 @@ router.post( "fileOperations.info", auth(), validate(T.FileOperationsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const fileOperation = await FileOperation.findByPk(id, { userId: user.id, @@ -41,9 +41,9 @@ router.post( auth({ role: UserRole.Admin }), pagination(), validate(T.FileOperationsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { direction, sort, type } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const where: WhereOptions = { teamId: user.teamId, @@ -94,10 +94,10 @@ router.post( ); const handleFileOperationsRedirect = async ( - ctx: APIContext + ctx: Context ) => { const id = (ctx.input.body.id ?? ctx.input.query.id) as string; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const fileOperation = await FileOperation.findByPk(id, { userId: user.id, @@ -128,10 +128,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.FileOperationsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const fileOperation = await FileOperation.unscoped().findByPk(id, { rejectOnEmpty: true, diff --git a/server/routes/api/groupMemberships/groupMemberships.ts b/server/routes/api/groupMemberships/groupMemberships.ts index 4af2d90180..1834979ba5 100644 --- a/server/routes/api/groupMemberships/groupMemberships.ts +++ b/server/routes/api/groupMemberships/groupMemberships.ts @@ -10,7 +10,7 @@ import { presentGroupMembership, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -21,9 +21,9 @@ router.post( auth(), pagination(), validate(T.GroupMembershipsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { groupId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const userId = user.id; // Filtering on the user's groups up front lets the query use the groupId diff --git a/server/routes/api/groups/groups.ts b/server/routes/api/groups/groups.ts index de64b47e1b..8a24e1a0f4 100644 --- a/server/routes/api/groups/groups.ts +++ b/server/routes/api/groups/groups.ts @@ -22,7 +22,7 @@ import { presentPolicies, presentUser, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { QueryHelper } from "@server/storage/QueryHelper"; import pagination from "../middlewares/pagination"; @@ -49,10 +49,10 @@ router.post( auth(), pagination(), validate(T.GroupsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, query, userId, externalId, name, source } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "listGroups", user.team); let where: WhereOptions = { @@ -195,9 +195,9 @@ router.post( "groups.info", auth(), validate(T.GroupsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, externalId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const include = [ { @@ -235,10 +235,10 @@ router.post( auth(), validate(T.GroupsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { name, description, icon, color, externalId, disableMentions } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createGroup", user.team); const group = await Group.createWithCtx(ctx, { @@ -267,10 +267,10 @@ router.post( auth(), validate(T.GroupsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const group = await Group.findByPk(id, { transaction, @@ -325,10 +325,10 @@ router.post( auth(), validate(T.GroupsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const group = await Group.findByPk(id, { transaction, @@ -353,10 +353,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.GroupsDeleteAllSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { authenticationProviderId } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const authenticationProvider = await AuthenticationProvider.findByPk( authenticationProviderId, @@ -401,9 +401,9 @@ router.post( auth(), pagination(), validate(T.GroupsMembershipsSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query, permission } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const group = await Group.findByPk(id); authorize(user, "read", group); @@ -470,10 +470,10 @@ router.post( auth(), validate(T.GroupsAddUserSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, userId, permission } = ctx.input.body; - const actor = ctx.state.auth.user; - const { transaction } = ctx.state; + const actor = ctx.auth.user; + const { transaction } = ctx; const user = await User.findByPk(userId, { transaction, @@ -549,10 +549,10 @@ router.post( auth(), validate(T.GroupsRemoveUserSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, userId } = ctx.input.body; - const actor = ctx.state.auth.user; - const { transaction } = ctx.state; + const actor = ctx.auth.user; + const { transaction } = ctx; const group = await Group.findByPk(id, { transaction, @@ -606,10 +606,10 @@ router.post( auth(), validate(T.GroupsUpdateUserSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, userId, permission } = ctx.input.body; - const actor = ctx.state.auth.user; - const { transaction } = ctx.state; + const actor = ctx.auth.user; + const { transaction } = ctx; // Load group with group users for authorization const group = await Group.findByPk(id, { diff --git a/server/routes/api/imports/imports.ts b/server/routes/api/imports/imports.ts index 0d674f6481..80fecfdae0 100644 --- a/server/routes/api/imports/imports.ts +++ b/server/routes/api/imports/imports.ts @@ -13,7 +13,7 @@ import { Attachment, Collection, Document, Integration } from "@server/models"; import Import from "@server/models/Import"; import { authorize } from "@server/policies"; import { presentImport, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -25,14 +25,14 @@ const router = new Router(); * is chosen the user must be able to create documents in it; when a document * is chosen the user must be able to add children to it. * - * @param ctx The API context for the create request. + * @param ctx The context for the create request. * @returns The resolved destination ids (both null when no destination set). */ async function resolveImportDestination( - ctx: APIContext + ctx: Context ): Promise<{ collectionId: string | null; documentId: string | null }> { - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const { collectionId, documentId } = ctx.input.body; if (collectionId) { @@ -65,9 +65,9 @@ router.post( auth({ role: UserRole.Admin }), validate(T.ImportsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const body = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createImport", user.team); @@ -141,9 +141,9 @@ router.post( auth({ role: UserRole.Admin }), pagination(), validate(T.ImportsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { service, sort, direction } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "listImports", user.team); @@ -180,9 +180,9 @@ router.post( "imports.info", auth({ role: UserRole.Admin }), validate(T.ImportsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const importModel = await Import.findByPk(id, { rejectOnEmpty: true, @@ -201,10 +201,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.ImportsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const importModel = await Import.findByPk(id, { rejectOnEmpty: true, @@ -226,10 +226,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.ImportsCancelSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; let importModel = await Import.findByPk(id, { rejectOnEmpty: true, diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index 7ab2c17b25..04edb3e2f0 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -3,7 +3,6 @@ import bodyParser from "koa-body"; import Router from "@koa/router"; import env from "@server/env"; import { NotFoundError } from "@server/errors"; -import { apiContext } from "@server/middlewares/apiContext"; import cleanupMultipartFiles from "@server/middlewares/cleanupMultipartFiles"; import coalesceBody from "@server/middlewares/coaleseBody"; import requestContextMiddleware from "@server/middlewares/requestContext"; @@ -78,7 +77,6 @@ api.use(requestTracer()); api.use(apiResponse()); api.use(apiErrorHandler()); api.use(editor()); -api.use(apiContext()); api.use(verifyCSRFToken()); // Register plugin API routes before others to allow for overrides diff --git a/server/routes/api/installation/installation.ts b/server/routes/api/installation/installation.ts index e6c3bcaa38..9d23a64277 100644 --- a/server/routes/api/installation/installation.ts +++ b/server/routes/api/installation/installation.ts @@ -6,7 +6,7 @@ import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; import { Team, User } from "@server/models"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { signIn } from "@server/utils/authentication"; import { getVersion, getVersionInfo } from "@server/utils/getInstallationInfo"; import * as T from "./schema"; @@ -18,9 +18,9 @@ router.post( "installation.create", validate(T.InstallationCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { teamName, userName, userEmail } = ctx.input.body; - const { transaction } = ctx.state; + const { transaction } = ctx; // Check that this can only be called when there are no existing teams const existingTeamCount = await Team.count({ transaction }); @@ -51,7 +51,7 @@ router.post( } ); -router.post("installation.info", auth(), async (ctx: APIContext) => { +router.post("installation.info", auth(), async (ctx: Context) => { const currentVersion = getVersion(); const { latestVersion, versionsBehind } = await getVersionInfo(currentVersion); diff --git a/server/routes/api/integrations/integrations.ts b/server/routes/api/integrations/integrations.ts index b31b0038a7..6a4642ef81 100644 --- a/server/routes/api/integrations/integrations.ts +++ b/server/routes/api/integrations/integrations.ts @@ -9,7 +9,7 @@ import validate from "@server/middlewares/validate"; import Integration from "@server/models/Integration"; import { authorize } from "@server/policies"; import { presentIntegration, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -21,9 +21,9 @@ router.post( auth(), pagination(), validate(T.IntegrationsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { direction, service, type, sort } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let where: WhereOptions = { teamId: user.teamId, @@ -77,9 +77,9 @@ router.post( auth({ role: UserRole.Admin }), validate(T.IntegrationsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { type, service, settings } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createIntegration", user.team); @@ -102,9 +102,9 @@ router.post( "integrations.info", auth(), validate(T.IntegrationsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const integration = await Integration.findByPk(id, { rejectOnEmpty: true, @@ -123,10 +123,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.IntegrationsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, events, settings } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const integration = await Integration.findByPk(id, { transaction, @@ -158,10 +158,10 @@ router.post( auth(), validate(T.IntegrationsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const integration = await Integration.findByPk(id, { rejectOnEmpty: true, diff --git a/server/routes/api/middlewares/apiErrorHandler.test.ts b/server/routes/api/middlewares/apiErrorHandler.test.ts index e1df1d7b16..687a4a2bf7 100644 --- a/server/routes/api/middlewares/apiErrorHandler.test.ts +++ b/server/routes/api/middlewares/apiErrorHandler.test.ts @@ -1,7 +1,7 @@ import httpErrors from "http-errors"; -import type { Context } from "koa"; import { AuthenticationError } from "@server/errors"; import apiErrorHandler from "./apiErrorHandler"; +import type { AppContext } from "@server/types"; const createContext = (challenge?: string) => { const headers: Record = {}; @@ -12,10 +12,10 @@ const createContext = (challenge?: string) => { response: { get: (field: string) => headers[field.toLowerCase()] ?? "", }, - } as unknown as Context; + } as unknown as AppContext; }; -const runWithError = async (ctx: Context) => { +const runWithError = async (ctx: AppContext) => { try { await apiErrorHandler()(ctx, () => Promise.reject(AuthenticationError())); } catch (err) { diff --git a/server/routes/api/middlewares/apiErrorHandler.ts b/server/routes/api/middlewares/apiErrorHandler.ts index 0b99206c49..1d78477dfa 100644 --- a/server/routes/api/middlewares/apiErrorHandler.ts +++ b/server/routes/api/middlewares/apiErrorHandler.ts @@ -1,5 +1,5 @@ import httpErrors from "http-errors"; -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import { ValidationError as SequelizeValidationError, EmptyResultError as SequelizeEmptyResultError, @@ -19,6 +19,7 @@ import { isDatabaseUnavailableError, isQueryCanceledError, } from "@server/storage/database"; +import type { AppContext } from "@server/types"; /** Postgres codes for a requested date the database cannot represent. */ const DATE_RANGE_ERROR_CODES = new Set(["22008", "22015"]); @@ -38,7 +39,7 @@ function sqlStateOf(err: SequelizeDatabaseError): string | undefined { } export default function apiErrorHandler() { - return async function apiErrorHandlerMiddleware(ctx: Context, next: Next) { + return async function apiErrorHandlerMiddleware(ctx: AppContext, next: Next) { try { await next(); } catch (err) { diff --git a/server/routes/api/middlewares/apiResponse.ts b/server/routes/api/middlewares/apiResponse.ts index afcc0a0c07..7d54cf4e8d 100644 --- a/server/routes/api/middlewares/apiResponse.ts +++ b/server/routes/api/middlewares/apiResponse.ts @@ -1,9 +1,10 @@ import stream from "node:stream"; -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import { Readable } from "readable-stream"; +import type { AppContext } from "@server/types"; export default function apiResponse() { - return async function apiResponseMiddleware(ctx: Context, next: Next) { + return async function apiResponseMiddleware(ctx: AppContext, next: Next) { await next(); const ok = ctx.status < 400; diff --git a/server/routes/api/middlewares/editor.ts b/server/routes/api/middlewares/editor.ts index 389817b0be..f4c07a1511 100644 --- a/server/routes/api/middlewares/editor.ts +++ b/server/routes/api/middlewares/editor.ts @@ -1,7 +1,8 @@ -import type { Context, Next } from "koa"; +import type { Next } from "koa"; import semver from "semver"; import EDITOR_VERSION from "@shared/editor/version"; import { EditorUpdateError } from "@server/errors"; +import type { AppContext } from "@server/types"; export default function editor() { /** @@ -9,7 +10,7 @@ export default function editor() { * version. See the equivalent logic for collab server in: * /server/collaboration/EditorVersionExtension.ts */ - return async function editorMiddleware(ctx: Context, next: Next) { + return async function editorMiddleware(ctx: AppContext, next: Next) { const clientVersion = ctx.headers["x-editor-version"]; if (clientVersion) { diff --git a/server/routes/api/notifications/notifications.ts b/server/routes/api/notifications/notifications.ts index af56d48591..7ca72e5a8b 100644 --- a/server/routes/api/notifications/notifications.ts +++ b/server/routes/api/notifications/notifications.ts @@ -14,7 +14,7 @@ import NotificationSettingsHelper from "@server/models/helpers/NotificationSetti import { authorize } from "@server/policies"; import { presentPolicies } from "@server/presenters"; import presentNotification from "@server/presenters/notification"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { safeEqual } from "@server/utils/crypto"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -31,8 +31,8 @@ const pixel = Buffer.from( * @param ctx The request context. * @returns The updated user, or undefined if the token is not valid. */ -const unsubscribe = async (ctx: APIContext) => { - const { transaction } = ctx.state; +const unsubscribe = async (ctx: Context) => { + const { transaction } = ctx; const eventType = (ctx.input.body.eventType ?? ctx.input.query.eventType) as NotificationEventType; const userId = (ctx.input.body.userId ?? ctx.input.query.userId) as string; @@ -62,7 +62,7 @@ router.get( "notifications.unsubscribe", validate(T.NotificationsUnsubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { follow } = ctx.input.query; // The link in the email does not include the follow query param, this @@ -86,7 +86,7 @@ router.post( "notifications.unsubscribe", validate(T.NotificationsUnsubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const user = await unsubscribe(ctx); if (!user) { throw AuthenticationError("Invalid unsubscribe token"); @@ -103,9 +103,9 @@ router.post( auth(), pagination(), validate(T.NotificationsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { eventType, archived } = ctx.input.body; - const user = ctx.state.auth.user; + const user = ctx.auth.user; let where: WhereOptions = { teamId: user.teamId, userId: user.id, @@ -163,9 +163,9 @@ router.get( "notifications.pixel", validate(T.NotificationsPixelSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, token } = ctx.input.query; - const { transaction } = ctx.state; + const { transaction } = ctx; const notification = await Notification.unscoped().findByPk(id, { lock: transaction.LOCK.UPDATE, @@ -203,10 +203,10 @@ router.post( auth(), validate(T.NotificationsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, viewedAt, archivedAt } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const notification = await Notification.findByPk(id, { lock: { @@ -233,10 +233,10 @@ router.post( auth(), validate(T.NotificationsUpdateAllSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { viewedAt, archivedAt } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const values: Partial = {}; let where: WhereOptions = { diff --git a/server/routes/api/oauthAuthentications/oauthAuthentications.ts b/server/routes/api/oauthAuthentications/oauthAuthentications.ts index 56a5dfb263..f54f04ba27 100644 --- a/server/routes/api/oauthAuthentications/oauthAuthentications.ts +++ b/server/routes/api/oauthAuthentications/oauthAuthentications.ts @@ -9,7 +9,7 @@ import { authorize } from "@server/policies"; import { presentPolicies } from "@server/presenters"; import presentOAuthAuthentication from "@server/presenters/oauthAuthentication"; import { sequelize } from "@server/storage/database"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -21,8 +21,8 @@ router.post( auth(), pagination(), validate(T.OAuthAuthenticationsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const oauthAuthentications = await sequelize.query( ` @@ -64,8 +64,8 @@ router.post( auth(), validate(T.OAuthAuthenticationsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { oauthClientId, scope } = ctx.input.body; const where = { userId: user.id, @@ -75,7 +75,7 @@ router.post( const oauthAuthentications = await OAuthAuthentication.findAll({ where, - transaction: ctx.state.transaction, + transaction: ctx.transaction, }); for (const oauthAuthentication of oauthAuthentications) { diff --git a/server/routes/api/oauthClients/oauthClients.ts b/server/routes/api/oauthClients/oauthClients.ts index 1e78cf8aac..9d38f0dd48 100644 --- a/server/routes/api/oauthClients/oauthClients.ts +++ b/server/routes/api/oauthClients/oauthClients.ts @@ -14,7 +14,7 @@ import { presentOAuthClient, presentPublishedOAuthClient, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { ClientMetadataHelper } from "@server/utils/oauth/ClientMetadataHelper"; import { OAuthHelper } from "@server/utils/oauth/OAuthHelper"; @@ -31,10 +31,10 @@ const router = new Router(); * @param ctx The request context. * @returns true if the credential's scope covers managing clients. */ -function hasManageScope(ctx: APIContext) { +function hasManageScope(ctx: Context) { return AuthenticationHelper.canAccess( "/api/oauthClients.update", - ctx.state.auth.scope ?? ["*"] + ctx.auth.scope ?? ["*"] ); } @@ -43,8 +43,8 @@ router.post( auth({ role: UserRole.Admin }), pagination(), validate(T.OAuthClientsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const where = { teamId: user.teamId, createdById: { @@ -81,9 +81,9 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerHour), auth(), validate(T.OAuthClientsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, clientId, redirectUri } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const oauthClient = clientId ? await ClientMetadataHelper.findOrFetchByClientId(clientId, user.team) @@ -123,9 +123,9 @@ router.post( auth({ role: UserRole.Admin }), validate(T.OAuthClientsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const input = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createOAuthClient", user.team); @@ -147,10 +147,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.OAuthClientsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, ...input } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const oauthClient = await OAuthClient.findByPk(id, { transaction, @@ -176,10 +176,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.OAuthClientsRotateSecretSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const oauthClient = await OAuthClient.findByPk(id, { transaction, @@ -205,10 +205,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.OAuthClientsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body as { id: string }; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const oauthClient = await OAuthClient.findByPk(id, { transaction, diff --git a/server/routes/api/pins/pins.ts b/server/routes/api/pins/pins.ts index 283397539c..cf8cdb02ee 100644 --- a/server/routes/api/pins/pins.ts +++ b/server/routes/api/pins/pins.ts @@ -12,7 +12,7 @@ import { presentDocuments, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -25,10 +25,10 @@ router.post( auth(), validate(T.PinsCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { documentId, collectionId, index } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const document = await Document.findByPk(documentId, { userId: user.id, transaction, @@ -65,8 +65,8 @@ router.post( "pins.info", auth(), validate(T.PinsInfoSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { documentId, collectionId } = ctx.input.body; const document = await Document.findByPk(documentId, { @@ -102,9 +102,9 @@ router.post( auth(), validate(T.PinsListSchema), pagination(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { collectionId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (collectionId) { const collection = await Collection.findByPk(collectionId, { @@ -161,10 +161,10 @@ router.post( auth(), validate(T.PinsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, index } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const pin = await Pin.findByPk(id, { transaction, lock: Transaction.LOCK.UPDATE, @@ -196,11 +196,11 @@ router.post( auth(), validate(T.PinsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { transaction } = ctx.state; + const { transaction } = ctx; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const pin = await Pin.findByPk(id, { transaction, lock: Transaction.LOCK.UPDATE, diff --git a/server/routes/api/reactions/reactions.ts b/server/routes/api/reactions/reactions.ts index 755cf08da7..891f420ccc 100644 --- a/server/routes/api/reactions/reactions.ts +++ b/server/routes/api/reactions/reactions.ts @@ -5,7 +5,7 @@ import validate from "@server/middlewares/validate"; import { Comment, Document, Reaction, User } from "@server/models"; import { authorize } from "@server/policies"; import { presentReaction } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -16,9 +16,9 @@ router.post( auth(), pagination(), validate(T.ReactionsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { commentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const comment = await Comment.findByPk(commentId, { rejectOnEmpty: true, diff --git a/server/routes/api/relationships/relationships.ts b/server/routes/api/relationships/relationships.ts index 121bb7b9f4..b1d82fd0e2 100644 --- a/server/routes/api/relationships/relationships.ts +++ b/server/routes/api/relationships/relationships.ts @@ -9,7 +9,7 @@ import { presentDocuments, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -19,9 +19,9 @@ router.post( "relationships.info", auth(), validate(T.RelationshipsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const relationship = await Relationship.findByPk(id, { rejectOnEmpty: true, @@ -58,9 +58,9 @@ router.post( auth(), pagination(), validate(T.RelationshipsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { type, documentId, reverseDocumentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; // Results are anchored to a single document, which the user must be able to // read. Documents on the opposite side of each relationship are filtered by diff --git a/server/routes/api/revisions/revisions.ts b/server/routes/api/revisions/revisions.ts index 86b6912bb6..4795ff284f 100644 --- a/server/routes/api/revisions/revisions.ts +++ b/server/routes/api/revisions/revisions.ts @@ -18,7 +18,7 @@ import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import TextBundleHelper from "@server/models/helpers/TextBundleHelper"; import { authorize } from "@server/policies"; import { presentPolicies, presentRevision } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { streamZipResponse } from "@server/utils/koa"; import pagination from "../middlewares/pagination"; @@ -30,9 +30,9 @@ router.post( "revisions.info", auth(), validate(T.RevisionsInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, documentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; let revision: Revision; if (id) { @@ -71,9 +71,9 @@ router.post( "revisions.update", auth(), validate(T.RevisionsUpdateSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, name } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const revision = await Revision.findByPk(id, { rejectOnEmpty: true, @@ -101,10 +101,10 @@ router.post( auth({ role: UserRole.Admin }), validate(T.RevisionsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const revision = await Revision.findByPk(id, { rejectOnEmpty: true, @@ -135,9 +135,9 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), auth(), validate(T.RevisionsExportSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const accept = ctx.request.headers["accept"]; const revision = await Revision.findByPk(id, { @@ -280,9 +280,9 @@ router.post( auth(), pagination(), validate(T.RevisionsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { direction, documentId, sort } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const document = await Document.findByPk(documentId, { userId: user.id, diff --git a/server/routes/api/searches/searches.ts b/server/routes/api/searches/searches.ts index 35200caa54..dd4a2f7c0a 100644 --- a/server/routes/api/searches/searches.ts +++ b/server/routes/api/searches/searches.ts @@ -4,7 +4,7 @@ import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; import { SearchQuery } from "@server/models"; import { presentSearchQuery } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -15,8 +15,8 @@ router.post( auth(), validate(T.SearchesListSchema), pagination(), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const source = ctx.input.body?.source; const searches = await SearchQuery.findAll({ @@ -42,10 +42,10 @@ router.post( auth(), validate(T.SearchesUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, score } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const search = await SearchQuery.findOne({ where: { @@ -70,9 +70,9 @@ router.post( "searches.delete", auth(), validate(T.SearchesDeleteSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, query } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; await SearchQuery.destroy({ where: { diff --git a/server/routes/api/shares/shares.test.ts b/server/routes/api/shares/shares.test.ts index a223e655aa..6b6051bbea 100644 --- a/server/routes/api/shares/shares.test.ts +++ b/server/routes/api/shares/shares.test.ts @@ -17,7 +17,7 @@ import { buildTeam, } from "@server/test/factories"; -import { getTestServer, withAPIContext } from "@server/test/support"; +import { getTestServer, withContext } from "@server/test/support"; const server = getTestServer(); @@ -174,7 +174,7 @@ describe("#shares.list", () => { teamId: user.teamId, userId: user.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/shares.list", user); const body = await res.json(); expect(res.status).toEqual(200); @@ -1546,7 +1546,7 @@ describe("#shares.revoke", () => { teamId: user.teamId, userId: user.id, }); - await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx)); + await withContext(user, (ctx) => document.destroyWithCtx(ctx)); const res = await server.post("/api/shares.revoke", user, { body: { id: share.id, diff --git a/server/routes/api/shares/shares.ts b/server/routes/api/shares/shares.ts index ccb3bd8da3..4b5cfc43ad 100644 --- a/server/routes/api/shares/shares.ts +++ b/server/routes/api/shares/shares.ts @@ -31,7 +31,7 @@ import { presentCollection, presentDocument, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { getTeamFromContext } from "@server/utils/passport"; import { QueryHelper } from "@server/storage/QueryHelper"; @@ -52,9 +52,9 @@ router.post( "shares.info", auth({ optional: true }), validate(T.SharesInfoSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, collectionId, documentId } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; // only public link loads will send "id". if (id) { @@ -160,9 +160,9 @@ router.post( auth(), pagination(), validate(T.SharesListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, query } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "listShares", user.team); const collectionIds = await user.collectionIds(); @@ -261,7 +261,7 @@ router.post( auth(), validate(T.SharesCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { collectionId, documentId, @@ -274,7 +274,7 @@ router.post( showTOC, expiresAt, } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "createShare", user.team); const collection = collectionId @@ -350,7 +350,7 @@ router.post( auth(), validate(T.SharesUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, includeChildDocuments, @@ -365,7 +365,7 @@ router.post( iconUrl, } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; authorize(user, "share", user.team); // fetch the share with document and collection. @@ -407,9 +407,9 @@ router.post( auth(), validate(T.SharesRevokeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const share = await Share.scope({ method: ["withCollectionPermissions", user.id], }).findByPk(id); @@ -433,7 +433,7 @@ router.get( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), shareDomains(), validate(T.SharesSitemapSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.query; const team = await getTeamFromContext(ctx, { includeOAuthState: false }); @@ -461,13 +461,13 @@ router.post( rateLimiter(RateLimiterStrategy.TenPerHour), validate(T.SharesSubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { if (!env.EMAIL_ENABLED) { throw InvalidRequestError("Email is not configured"); } const { shareId, documentId, email } = ctx.input.body; - const { transaction } = ctx.state; + const { transaction } = ctx; const team = await getTeamFromContext(ctx, { includeOAuthState: false }); // Validate the share exists and is published @@ -551,9 +551,9 @@ router.get( rateLimiter(RateLimiterStrategy.TenPerMinute), validate(T.SharesConfirmSubscriptionSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, token, follow } = ctx.input.query; - const { transaction } = ctx.state; + const { transaction } = ctx; // Anti-prefetch: prevent email clients from pre-fetching the link if (!follow) { @@ -615,9 +615,9 @@ router.get( * @param ctx The request context. * @returns The updated subscription, or undefined if the token is not valid. */ -const unsubscribeShare = async (ctx: APIContext) => { +const unsubscribeShare = async (ctx: Context) => { const { id, token } = ctx.input.query; - const { transaction } = ctx.state; + const { transaction } = ctx; const subscription = await ShareSubscription.findByPk(id, { transaction, @@ -644,7 +644,7 @@ router.get( "shares.unsubscribe", validate(T.SharesUnsubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { follow } = ctx.input.query; // Anti-prefetch: prevent email clients from pre-fetching the link @@ -669,7 +669,7 @@ router.post( "shares.unsubscribe", validate(T.SharesUnsubscribeSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const subscription = await unsubscribeShare(ctx); if (!subscription) { throw AuthenticationError("Invalid unsubscribe token"); diff --git a/server/routes/api/stars/stars.ts b/server/routes/api/stars/stars.ts index 5b9dfcb378..96874aecf7 100644 --- a/server/routes/api/stars/stars.ts +++ b/server/routes/api/stars/stars.ts @@ -12,7 +12,7 @@ import { presentDocuments, presentPolicies, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { starIndexing } from "@server/utils/indexing"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import pagination from "../middlewares/pagination"; @@ -26,10 +26,10 @@ router.post( auth(), validate(T.StarsCreateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { documentId, collectionId, index } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; if (documentId) { const document = await Document.findByPk(documentId, { @@ -67,8 +67,8 @@ router.post( auth(), pagination(), validate(T.StarsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const [stars, collectionIds] = await Promise.all([ Star.findAll({ @@ -124,10 +124,10 @@ router.post( auth(), validate(T.StarsUpdateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, index } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const star = await Star.findByPk(id, { transaction, @@ -149,10 +149,10 @@ router.post( auth(), validate(T.StarsDeleteSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id } = ctx.input.body; - const { user } = ctx.state.auth; - const { transaction } = ctx.state; + const { user } = ctx.auth; + const { transaction } = ctx; const star = await Star.findByPk(id, { transaction, diff --git a/server/routes/api/subscriptions/subscriptions.ts b/server/routes/api/subscriptions/subscriptions.ts index 012191adee..2c9497b96b 100644 --- a/server/routes/api/subscriptions/subscriptions.ts +++ b/server/routes/api/subscriptions/subscriptions.ts @@ -13,7 +13,7 @@ import { Subscription, Document, User, Collection } from "@server/models"; import SubscriptionHelper from "@server/models/helpers/SubscriptionHelper"; import { authorize } from "@server/policies"; import { presentSubscription } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { safeEqual } from "@server/utils/crypto"; import pagination from "../middlewares/pagination"; @@ -26,8 +26,8 @@ router.post( auth(), pagination(), validate(T.SubscriptionsListSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { event, collectionId, documentId } = ctx.input.body; const where: WhereOptions = { @@ -38,7 +38,7 @@ router.post( if (collectionId) { const collection = await Collection.findByPk(collectionId, { userId: user.id, - transaction: ctx.state.transaction, + transaction: ctx.transaction, }); authorize(user, "read", collection); @@ -72,8 +72,8 @@ router.post( "subscriptions.info", auth(), validate(T.SubscriptionsInfoSchema), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { event, collectionId, documentId } = ctx.input.body; const where: WhereOptions = { @@ -121,8 +121,8 @@ router.post( auth(), validate(T.SubscriptionsCreateSchema), transaction(), - async (ctx: APIContext) => { - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { user } = ctx.auth; const { event, collectionId, documentId } = ctx.input.body; if (documentId) { @@ -159,8 +159,8 @@ router.get( validate(T.SubscriptionsDeleteTokenSchema), rateLimiter(RateLimiterStrategy.FivePerMinute), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; + async (ctx: Context) => { + const { transaction } = ctx; const { follow, userId, documentId, token } = ctx.input.query; // The link in the email does not include the follow query param, this @@ -237,9 +237,9 @@ router.post( auth(), validate(T.SubscriptionsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user } = ctx.auth; const { id } = ctx.input.body; const subscription = await Subscription.findByPk(id, { diff --git a/server/routes/api/suggestions/suggestions.ts b/server/routes/api/suggestions/suggestions.ts index ed674ee9ed..8d57b947da 100644 --- a/server/routes/api/suggestions/suggestions.ts +++ b/server/routes/api/suggestions/suggestions.ts @@ -19,7 +19,7 @@ import { presentGroup, presentUser, } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; @@ -33,10 +33,10 @@ router.post( auth(), pagination(), validate(T.SuggestionsListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { query } = ctx.input.body; const { offset, limit } = ctx.state.pagination; - const actor = ctx.state.auth.user; + const actor = ctx.auth.user; const suggestUsers = async (): Promise<{ users: User[]; diff --git a/server/routes/api/teams/teams.ts b/server/routes/api/teams/teams.ts index 6746a617ff..e4de6424c3 100644 --- a/server/routes/api/teams/teams.ts +++ b/server/routes/api/teams/teams.ts @@ -12,16 +12,16 @@ import validate from "@server/middlewares/validate"; import { Team, TeamDomain, User } from "@server/models"; import { authorize } from "@server/policies"; import { presentTeam, presentPolicies } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { safeEqual } from "@server/utils/crypto"; import * as T from "./schema"; const router = new Router(); -const handleTeamUpdate = async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user } = ctx.state.auth; +const handleTeamUpdate = async (ctx: Context) => { + const { transaction } = ctx; + const { user } = ctx.auth; const team = await Team.findByPk(user.teamId, { include: [{ model: TeamDomain, separate: true }], lock: transaction.LOCK.NO_KEY_UPDATE, @@ -63,12 +63,12 @@ router.post( "teams.requestDelete", rateLimiter(RateLimiterStrategy.FivePerHour), auth(), - async (ctx: APIContext) => { + async (ctx: Context) => { if (!env.EMAIL_ENABLED) { throw ValidationError("Email support is not set up for this instance"); } - const { user } = ctx.state.auth; + const { user } = ctx.auth; const { team } = user; authorize(user, "delete", team); @@ -90,8 +90,8 @@ router.post( auth(), validate(T.TeamsDeleteSchema), transaction(), - async (ctx: APIContext) => { - const { auth } = ctx.state; + async (ctx: Context) => { + const { auth } = ctx; const { code } = ctx.input.body; const { user } = auth; const { team } = user; @@ -120,9 +120,9 @@ router.post( auth(), validate(T.TeamsCreateSchema), transaction(), - async (ctx: APIContext) => { - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + async (ctx: Context) => { + const { transaction } = ctx; + const { user } = ctx.auth; const { name } = ctx.input.body; const existingTeam = await Team.scope( diff --git a/server/routes/api/templates/templates.ts b/server/routes/api/templates/templates.ts index 47c5619cea..dfbd191e0c 100644 --- a/server/routes/api/templates/templates.ts +++ b/server/routes/api/templates/templates.ts @@ -10,7 +10,7 @@ import validate from "@server/middlewares/validate"; import { Collection, Template } from "@server/models"; import { authorize } from "@server/policies"; import { presentPolicies, presentTemplate } from "@server/presenters"; -import type { APIContext } from "@server/types"; +import type { Context } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { QueryHelper } from "@server/storage/QueryHelper"; import pagination from "../middlewares/pagination"; @@ -24,13 +24,13 @@ router.post( rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), validate(T.TemplatesCreateSchema), transaction(), - async (ctx: APIContext) => { + async (ctx: Context) => { const { id, title, data, icon, color, collectionId, publish } = ctx.input.body; const editorVersion = ctx.headers["x-editor-version"] as string | undefined; - const { transaction } = ctx.state; - const { user } = ctx.state.auth; + const { transaction } = ctx; + const { user } = ctx.auth; if (publish && (!data || ProsemirrorDataHelper.isEmpty(data))) { throw ValidationError("A published template must have content"); @@ -79,9 +79,9 @@ router.post( auth(), pagination(), validate(T.TemplatesListSchema), - async (ctx: APIContext) => { + async (ctx: Context) => { const { sort, direction, collectionId, query } = ctx.input.body; - const { user } = ctx.state.auth; + const { user } = ctx.auth; const where: WhereOptions