Merge remote-tracking branch 'origin/main' into claude/document-owners

# Conflicts:
#	server/commands/subscriptionCreator.ts
#	server/routes/api/collections/collections.ts
#	server/routes/api/documents/documents.ts
This commit is contained in:
Tom Moor committed 2026-11-24 15:16:22 -05:00
commit bbc3e5724c
229 files changed
+5112 -2776

No files matched your search

+1 -1
View File
@@ -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
+5
View File
@@ -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": [
+6
View File
@@ -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.
+7 -17
View File
@@ -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)<WrapperProps>`
${(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)});
}
}
`}
`};
@@ -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 (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...rest}
>
<path
fill={color}
fillRule="evenodd"
d="M7,9 L17,9 C18.1045695,9 19,9.8954305 19,11 L19,17 C19,18.1045695 18.1045695,19 17,19 L7,19 C5.8954305,19 5,18.1045695 5,17 L5,11 C5,9.8954305 5.8954305,9 7,9 Z M13,14.7324356 C13.5978014,14.3866262 14,13.7402824 14,13 C14,11.8954305 13.1045695,11 12,11 C10.8954305,11 10,11.8954305 10,13 C10,13.7402824 10.4021986,14.3866262 11,14.7324356 L11,16.5 C11,17.0522847 11.4477153,17.5 12,17.5 C12.5522847,17.5 13,17.0522847 13,16.5 L13,14.7324356 Z"
/>
<path
stroke={color}
strokeWidth="2"
strokeLinecap="round"
d="M8,10 L8,9 A4,4 0 0 1 14.83,6.17"
/>
</svg>
);
}
+4 -1
View File
@@ -200,7 +200,10 @@ export function MenuFilter({ query, onChange }: Props) {
);
return (
<Wrapper style={isActive ? undefined : VISUALLY_HIDDEN_STYLES}>
<Wrapper
style={isActive ? undefined : VISUALLY_HIDDEN_STYLES}
data-menu-hidden={isActive ? undefined : ""}
>
<Input
value={query ?? ""}
onChange={handleChange}
+31 -2
View File
@@ -19,8 +19,8 @@ const items: MenuItem[] = [
{ type: "button", title: "Hidden date", visible: false, onClick: noop },
];
function render(query?: string) {
return (toMenuItems(items, query) ?? []).filter(
function render(query?: string, menuItems = items) {
return (toMenuItems(menuItems, query) ?? []).filter(
(element): element is ReactElement => !!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"]);
});
});
+10 -4
View File
@@ -290,7 +290,7 @@ export function toMobileMenuItems(
}
return (
<div key={`${item.type}-${index}`}>
<div key={`${item.type}-${index}`} role="group">
<Components.MenuHeader>{item.title}</Components.MenuHeader>
{groupItems}
</div>
@@ -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;
}
+1
View File
@@ -55,6 +55,7 @@ export const MouseSafeArea = observer(function MouseSafeArea_(props: {
return (
<div
data-menu-hidden=""
style={{
position: "absolute",
top: 0,
+13 -4
View File
@@ -128,13 +128,22 @@ export const MenuLabel = styled.div`
`;
export const MenuHeader = styled.h3`
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
font-size: 13px;
font-weight: 500;
color: ${s("sidebarText")};
letter-spacing: 0.04em;
margin: 1em 12px 0.5em;
user-select: none;
// Remove the top margin when nothing visible is above the header, except in
// the mobile drawer, which has less padding.
${breakpoint("tablet")`
&:first-child:not([role="group"] > *),
[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)`
@@ -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<typeof ToolbarButton> {
/** 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 (
<LockButton
aria-label={t("Lock aspect ratio")}
aria-pressed={isLocked}
{...rest}
>
{isLocked ? (
<PadlockIcon size={18} />
) : (
<UnlockedPadlockIcon size={18} color={theme.textTertiary} />
)}
</LockButton>
);
}
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);
}
`;
+222 -125
View File
@@ -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<Dimension>(() => ({
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<HTMLInputElement>) => {
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<HTMLInputElement>) => {
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 (
<StyledFlex align="center">
<StyledInput
label={t("Image width")}
labelHidden
placeholder={t("Width")}
value={localDimension.width}
onChange={handleChange("width")}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
$error={error.width}
/>
<Text size="xsmall" type="tertiary">
×
</Text>
<StyledInput
label={t("Image height")}
labelHidden
placeholder={t("Height")}
value={localDimension.height}
onChange={handleChange("height")}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
$error={error.height}
/>
<Tooltip content={tooltip}>
<Flex align="center">
<StyledInput
label={t("Image width")}
labelHidden
placeholder={t("Width")}
value={localDimension.width}
onChange={handleChange("width")}
onBlur={handleBlur}
onKeyDown={handleKeyDown("width")}
$error={error.width}
/>
<Text size="xsmall" type="tertiary">
×
</Text>
<StyledInput
label={t("Image height")}
labelHidden
placeholder={t("Height")}
value={localDimension.height}
onChange={handleChange("height")}
onBlur={handleBlur}
onKeyDown={handleKeyDown("height")}
$error={error.height}
/>
</Flex>
</Tooltip>
{canUnlock && (
<Tooltip
content={
isLocked ? t("Aspect ratio locked") : t("Aspect ratio unlocked")
}
>
<Toolbar.Button asChild>
<AspectRatioLockButton
isLocked={isLocked}
onClick={handleToggleLock}
/>
</Toolbar.Button>
</Tooltip>
)}
</StyledFlex>
);
}
+19
View File
@@ -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" && (
<>
<ToolbarSeparator />
<Toolbar.Root asChild>
<DimensionGroup>
<MediaDimension tooltip={`${t("Width")} × ${t("Height")}`} />
</DimensionGroup>
</Toolbar.Root>
<ToolbarSeparator />
</>
)}
<Tooltip content={t("Open link")}>
<ToolbarButton onClick={openLink} disabled={!localUrl}>
<OpenIcon />
@@ -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;
+16 -16
View File
@@ -198,28 +198,28 @@ function ToolbarMenu(props: Props) {
);
}
if (item.name === "dimensions") {
return <MediaDimension key={index} tooltip={item.tooltip} />;
}
return (
<Tooltip
key={index}
shortcut={item.shortcut}
content={item.label === item.tooltip ? undefined : item.tooltip}
>
{item.name === "dimensions" ? (
<MediaDimension key={index} />
) : (
<Toolbar.Button asChild>
<ToolbarButton
data-group={item.group}
onClick={handleClick(item)}
active={isActive && !item.label}
aria-label={item.label ? undefined : item.tooltip}
disabled={item.disabled}
>
{item.label && <Label>{item.label}</Label>}
{item.icon}
</ToolbarButton>
</Toolbar.Button>
)}
<Toolbar.Button asChild>
<ToolbarButton
data-group={item.group}
onClick={handleClick(item)}
active={isActive && !item.label}
aria-label={item.label ? undefined : item.tooltip}
disabled={item.disabled}
>
{item.label && <Label>{item.label}</Label>}
{item.icon}
</ToolbarButton>
</Toolbar.Button>
</Tooltip>
);
})}
+18 -1
View File
@@ -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;
},
+6 -1
View File
@@ -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,
+5 -9
View File
@@ -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,
+5 -10
View File
@@ -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,
+3 -3
View File
@@ -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<T.EmailReq>) => {
async (ctx: Context<T.EmailReq>) => {
const { email, client, preferOTP } = ctx.input.body;
const domain = parseDomain(ctx.request.hostname);
@@ -99,7 +99,7 @@ router.post(
}
);
const emailCallback = async (ctx: APIContext<T.EmailCallbackReq>) => {
const emailCallback = async (ctx: Context<T.EmailCallbackReq>) => {
const { query, body } = ctx.input;
const token = query?.token || body?.token;
const client = query?.client || body?.client || Client.Web;
+4 -4
View File
@@ -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<T.FigmaCallbackReq>) => {
async (ctx: Context<T.FigmaCallbackReq>) => {
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.
+7 -7
View File
@@ -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<T.GiteaConnectReq>) => {
async (ctx: Context<T.GiteaConnectReq>) => {
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<T.GiteaCallbackReq>) => {
async (ctx: Context<T.GiteaCallbackReq>) => {
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));
+5 -5
View File
@@ -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<T.GitHubCallbackReq>) => {
async (ctx: Context<T.GitHubCallbackReq>) => {
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);
+9 -9
View File
@@ -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<T.GitLabConnectReq>) => {
async (ctx: Context<T.GitLabConnectReq>) => {
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<T.GitLabCallbackReq>) => {
async (ctx: Context<T.GitLabCallbackReq>) => {
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<string | null> = ctx.state.webhookTeamIds ?? [null];
+5 -9
View File
@@ -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,
+4 -4
View File
@@ -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<T.LinearCallbackReq>) => {
async (ctx: Context<T.LinearCallbackReq>) => {
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) {
+4 -4
View File
@@ -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<T.NotionCallbackReq>) => {
async (ctx: Context<T.NotionCallbackReq>) => {
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) {
+7 -12
View File
@@ -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) {
+9 -9
View File
@@ -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<T.PasskeysListReq>) => {
const { user } = ctx.state.auth;
async (ctx: Context<T.PasskeysListReq>) => {
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<T.PasskeysUpdateReq>) => {
async (ctx: Context<T.PasskeysUpdateReq>) => {
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<T.PasskeysDeleteReq>) => {
async (ctx: Context<T.PasskeysDeleteReq>) => {
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,
@@ -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({
+11 -15
View File
@@ -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<T.PasskeysVerifyRegistrationReq>) => {
const { user } = ctx.state.auth;
async (ctx: Context<T.PasskeysVerifyRegistrationReq>) => {
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<T.PasskeysGenerateAuthenticationOptionsReq>) => {
async (ctx: Context<T.PasskeysGenerateAuthenticationOptionsReq>) => {
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<T.PasskeysVerifyAuthenticationReq>) => {
async (ctx: Context<T.PasskeysVerifyAuthenticationReq>) => {
const body = ctx.input.body;
const { challengeId, client = Client.Web } = body;
+4 -4
View File
@@ -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<T.HooksUnfurlReq>) => {
async (ctx: Context<T.HooksUnfurlReq>) => {
// 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<T.HooksInteractiveReq>) => {
async (ctx: Context<T.HooksInteractiveReq>) => {
const { payload } = ctx.input.body;
let parsed;
@@ -208,7 +208,7 @@ router.post(
router.post(
"hooks.slack",
validate(T.HooksSlackCommandSchema),
async (ctx: APIContext<T.HooksSlackCommandReq>) => {
async (ctx: Context<T.HooksSlackCommandReq>) => {
const { token, team_id, user_id, text } = ctx.input.body;
verifySlackToken(token);
+7 -11
View File
@@ -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<T.SlackPostReq>) => {
async (ctx: Context<T.SlackPostReq>) => {
const { code, error, state } = ctx.input.query;
const { user } = ctx.state.auth;
const { user } = ctx.auth;
if (error) {
ctx.redirect(SlackUtils.errorUrl(error));
@@ -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: [
+6 -6
View File
@@ -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<T.FilesCreateReq>) => {
const actor = ctx.state.auth.user;
async (ctx: Context<T.FilesCreateReq>) => {
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<T.FilesGetReq>) => {
const actor = ctx.state.auth.user;
async (ctx: Context<T.FilesGetReq>) => {
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<T.FilesGetReq>): string {
function getKeyFromContext(ctx: Context<T.FilesGetReq>): string {
const { key, sig } = ctx.input.query;
if (sig) {
const payload = getJWTPayload(sig);
@@ -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<T.WebhookSubscriptionsListReq>) => {
async (ctx: Context<T.WebhookSubscriptionsListReq>) => {
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<T.WebhookSubscriptionsCreateReq>) => {
async (ctx: Context<T.WebhookSubscriptionsCreateReq>) => {
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<T.WebhookSubscriptionsDeleteReq>) => {
async (ctx: Context<T.WebhookSubscriptionsDeleteReq>) => {
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<T.WebhookSubscriptionsUpdateReq>) => {
async (ctx: Context<T.WebhookSubscriptionsUpdateReq>) => {
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,
+11 -22
View File
@@ -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<AuthenticationProvider>(
@@ -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",
+3 -3
View File
@@ -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) {
+6 -6
View File
@@ -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<Collection> {
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) {
+16 -16
View File
@@ -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,
+14 -13
View File
@@ -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<Collection | null | undefined> {
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<Document> {
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);
}
+11 -11
View File
@@ -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,
+7 -7
View File
@@ -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<Document[]> {
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<Document[]> {
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,
});
+2 -2
View File
@@ -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 = {
+10 -10
View File
@@ -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,
+4 -4
View File
@@ -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<Result> {
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;
+5 -5
View File
@@ -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<Document> {
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
+35 -35
View File
@@ -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,
+4 -4
View File
@@ -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<Document> {
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 ?? [];
+4 -4
View File
@@ -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<GroupSyncResult> {
const { transaction } = ctx.state;
const { transaction } = ctx;
const result: GroupSyncResult = {
groupsCreated: 0,
membershipsAdded: 0,
+9 -16
View File
@@ -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<Collection> {
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<T | string> {
>(ctx: Context, collectionId: T): Promise<T | string> {
return collectionId === PersonalCollectionId
? (await personalCollectionLoader(ctx)).id
: collectionId;
+3 -3
View File
@@ -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,
+3 -3
View File
@@ -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<Pin> {
let { index } = rest;
const { transaction } = ctx.context;
const { transaction } = ctx;
const where: WhereOptions<Pin> = {
teamId: user.teamId,
...(collectionId ? { collectionId } : { collectionId: { [Op.is]: null } }),
+3 -3
View File
@@ -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,
+3 -3
View File
@@ -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
+5 -5
View File
@@ -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<Subscription> {
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 {
+3 -3
View File
@@ -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<Team> {
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,
+2 -2
View File
@@ -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<TeamProvisionerResult> {
const where = teamId
+9 -9
View File
@@ -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,
+5 -5
View File
@@ -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<Omit<Team, "allowedDomains">> & { 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
+8 -8
View File
@@ -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: [
{
+3 -3
View File
@@ -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)) {
+2 -2
View File
@@ -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,
+37
View File
@@ -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();
});
});
});
+63 -13
View File
@@ -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,
};
}
+3 -3
View File
@@ -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,
+1 -1
View File
@@ -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,
});
+7 -9
View File
@@ -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,
+5 -5
View File
@@ -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,
+114
View File
@@ -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 });
+51 -17
View File
@@ -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,
+6 -6
View File
@@ -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;
}
/**
+6 -6
View File
@@ -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<T>({
getErrorPath,
}: {
/** Get the team ID for the current request */
getTeamId: (ctx: APIContext<T>) => string | null | undefined;
getTeamId: (ctx: Context<T>) => string | null | undefined;
/** Get the redirect URL for the given team ID */
getRedirectPath: (ctx: APIContext<T>, team: Team) => string;
getRedirectPath: (ctx: Context<T>, team: Team) => string;
/** Get the error URL for the current request */
getErrorPath: (ctx: APIContext<T>) => string;
getErrorPath: (ctx: Context<T>) => string;
}) {
return async function apexAuthRedirectMiddleware(
ctx: APIContext<T>,
ctx: Context<T>,
next: Next
) {
const { user } = ctx.state.auth;
const { user } = ctx.auth;
if (user) {
return next();
}
+3 -2
View File
@@ -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 {
-26
View File
@@ -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();
};
}
+3 -2
View File
@@ -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.
+139 -210
View File
@@ -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 <token>"'
@@ -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);
});
});
});
+3 -3
View File
@@ -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;
}
+6 -5
View File
@@ -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 = [];
+5 -8
View File
@@ -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.
+2 -2
View File
@@ -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();
+2 -3
View File
@@ -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<string> {
}
export default function createMiddleware(providerName: string) {
return function passportMiddleware(ctx: Context) {
return function passportMiddleware(ctx: AppContext) {
return passport.authorize(
providerName,
{
+2 -2
View File
@@ -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;
+3 -2
View File
@@ -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;
+2 -2
View File
@@ -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);
+3 -2
View File
@@ -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)) {
+2 -2
View File
@@ -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();
});
};
+6 -6
View File
@@ -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");
});
});
+2 -2
View File
@@ -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<T extends z.ZodType<Record<string, unknown>>>(
schema: T
) {
return async function validateMiddleware(ctx: APIContext, next: Next) {
return async function validateMiddleware(ctx: Context, next: Next) {
try {
ctx.input = {
...ctx.input,
+4 -4
View File
@@ -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<string | undefined>);
getSignatureFromHeader: (ctx: APIContext) => string | undefined;
secretKey: string | ((ctx: Context) => Promise<string | undefined>);
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);
@@ -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";'
);
},
};
+7 -7
View File
@@ -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);
}
+6 -8
View File
@@ -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<AuthenticationProvider> = async (
ctx
) => {
const { transaction } = ctx.state;
disable: (ctx: Context) => Promise<AuthenticationProvider> = 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<AuthenticationProvider> = async (ctx) =>
enable: (ctx: Context) => Promise<AuthenticationProvider> = async (ctx) =>
this.updateWithCtx(ctx, {
enabled: true,
});
+9 -9
View File
@@ -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]);
+29 -34
View File
@@ -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<Collection> {
const { user } = ctx.state.auth;
const { transaction } = ctx.state;
static async findOrCreatePersonal(ctx: Context): Promise<Collection> {
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<void> => {
setOwnerIds = async (ctx: Context, ownerIds: string[]): Promise<void> => {
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<void> => {
addOwner = async (ctx: Context, userId: string): Promise<void> => {
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<void> => {
removeOwner = async (ctx: Context, userId: string): Promise<void> => {
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<void> => {
const { user } = ctx.state.auth;
const { transaction } = ctx.state;
grantOwnerAccess = async (ctx: Context, userIds: string[]): Promise<void> => {
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<string[]> {
const { transaction } = ctx.state;
private async lockOwnerIds(ctx: Context): Promise<string[]> {
const { transaction } = ctx;
const locked = await Collection.unscoped().findOne({
where: { id: this.id },
attributes: ["id", "ownerIds"],
+11 -11
View File
@@ -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]);
+34 -36
View File
@@ -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<void> => {
setOwnerIds = async (ctx: Context, ownerIds: string[]): Promise<void> => {
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<void> => {
addOwner = async (ctx: Context, userId: string): Promise<void> => {
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<void> => {
removeOwner = async (ctx: Context, userId: string): Promise<void> => {
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<void> => {
const { user } = ctx.state.auth;
const { transaction } = ctx.state;
grantOwnerAccess = async (ctx: Context, userIds: string[]): Promise<void> => {
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<string, unknown>;
}
): Promise<this> => {
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<void> => {
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<string[]> {
const { transaction } = ctx.state;
private async lockOwnerIds(ctx: Context): Promise<string[]> {
const { transaction } = ctx;
const locked = await Document.unscoped().findOne({
where: { id: this.id },
attributes: ["id", "ownerIds"],
+6 -6
View File
@@ -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<Partial<Event>, "ip" | "teamId" | "actorId"> = {},
defaultAttributes: Pick<Partial<Event>, "ip" | "teamId" | "actorId"> = {},
options?: CreateOptions<InferAttributes<Event>>
) {
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,
}
);
+4 -4
View File
@@ -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<FileOperation> {
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;
+8 -8
View File
@@ -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<string, unknown>
) {
@@ -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
+5 -5
View File
@@ -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<Attributes<Reaction>, CreationAttributes<Reaction>>
) {
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,
Loaded 100 of 229 files, more files were not shown because too many files have changed in this diff. Show more