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

# Conflicts:
#	server/commands/documentUpdater.ts
#	server/mcp/tools/documents.ts
#	server/routes/api/documents/schema.ts
This commit is contained in:
Tom Moor committed 2026-11-12 23:09:00 -05:00
commit 67fbbc6fcc
120 files changed
+4258 -2035

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ ARG APP_PATH
WORKDIR $APP_PATH
# ---
FROM node:26.13.0-slim AS runner
FROM node:26.13.1-slim AS runner
LABEL org.opencontainers.image.source="https://github.com/outline/outline"
+1 -1
View File
@@ -1,5 +1,5 @@
ARG APP_PATH=/opt/outline
FROM node:26.13.0 AS deps
FROM node:26.13.1 AS deps
ARG APP_PATH
WORKDIR $APP_PATH
+15 -3
View File
@@ -4,6 +4,7 @@ import useActionContext from "~/hooks/useActionContext";
import useMobile from "~/hooks/useMobile";
import type { ActionFactory, ActionVariant, ActionWithChildren } from "~/types";
import { preventDefault } from "~/utils/events";
import { MenuFilter, MenuFilterEmpty, useMenuFilter } from "./MenuFilter";
import { toMenuItems } from "./transformer";
import { observer } from "mobx-react";
import { useComputed } from "~/hooks/useComputed";
@@ -31,6 +32,13 @@ export const ContextMenu = observer(
const actionContext = useActionContext({
isMenu: true,
});
const {
query,
setQuery,
handleKeyDownCapture,
handleEscapeKeyDown,
reset: resetFilter,
} = useMenuFilter();
// Menu items are only built while the menu is open.
const menuItems = useComputed(() => {
@@ -54,12 +62,13 @@ export const ContextMenu = observer(
(open: boolean) => {
setOpen(open);
if (open) {
resetFilter();
onOpen?.();
} else {
onClose?.();
}
},
[onOpen, onClose]
[onOpen, onClose, resetFilter]
);
const enablePointerEvents = React.useCallback(() => {
@@ -86,7 +95,7 @@ export const ContextMenu = observer(
return <>{children}</>;
}
const content = open ? toMenuItems(menuItems) : null;
const content = open ? toMenuItems(menuItems, query) : null;
return (
<MenuProvider variant="context">
@@ -97,8 +106,11 @@ export const ContextMenu = observer(
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
onEscapeKeyDown={handleEscapeKeyDown}
onKeyDownCapture={handleKeyDownCapture}
>
{content}
<MenuFilter query={query} onChange={setQuery} />
{content ?? (query ? <MenuFilterEmpty /> : null)}
</MenuContent>
</Menu>
</MenuProvider>
+16 -4
View File
@@ -20,6 +20,7 @@ import type {
MenuItem,
MenuItemWithChildren,
} from "~/types";
import { MenuFilter, MenuFilterEmpty, useMenuFilter } from "./MenuFilter";
import { toMenuItems, toMobileMenuItems } from "./transformer";
import { observer } from "mobx-react";
import { useComputed } from "~/hooks/useComputed";
@@ -65,6 +66,13 @@ export const DropdownMenu = observer(function DropdownMenu({
const actionContext = useActionContext({
isMenu: true,
});
const {
query,
setQuery,
handleKeyDownCapture,
handleEscapeKeyDown,
reset: resetFilter,
} = useMenuFilter();
const menuItems = useComputed(() => {
if (!open) {
@@ -93,12 +101,13 @@ export const DropdownMenu = observer(function DropdownMenu({
(open: boolean) => {
setOpen(open);
if (open) {
resetFilter();
onOpen?.();
} else {
onClose?.();
}
},
[onOpen, onClose]
[onOpen, onClose, resetFilter]
);
const enablePointerEvents = React.useCallback(() => {
@@ -130,7 +139,7 @@ export const DropdownMenu = observer(function DropdownMenu({
);
}
const content = toMenuItems(menuItems);
const content = toMenuItems(menuItems, query);
return (
<MenuProvider variant="dropdown">
@@ -144,9 +153,12 @@ export const DropdownMenu = observer(function DropdownMenu({
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
onEscapeKeyDown={handleEscapeKeyDown}
onKeyDownCapture={handleKeyDownCapture}
>
{content}
{append}
<MenuFilter query={query} onChange={setQuery} />
{content ?? (query ? <MenuFilterEmpty /> : null)}
{query ? null : append}
</MenuContent>
</Menu>
</MenuProvider>
+330
View File
@@ -0,0 +1,330 @@
import { VISUALLY_HIDDEN_STYLES } from "@radix-ui/react-visually-hidden";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { s } from "@shared/styles";
import { breakpoint } from "@shared/styles/breakpoint";
import isTextInput from "~/utils/isTextInput";
interface MenuFilterState {
/** The current filter query, or undefined when the filter is hidden. */
query: string | undefined;
/** Sets the filter query. */
setQuery: (query: string) => void;
/** Capture-phase keydown handler to attach to the menu content. */
handleKeyDownCapture: (event: React.KeyboardEvent<HTMLElement>) => void;
/** Escape handler to attach to the menu content. */
handleEscapeKeyDown: (event: KeyboardEvent) => void;
/** Hides the filter and clears the query. */
reset: () => void;
}
/**
* Lets the user filter a menu by typing. When a key that types text is pressed
* on a menu item, focus moves to the filter input, which then receives the
* text.
*
* @returns the filter query and the handlers to attach to the menu content.
*/
export function useMenuFilter(): MenuFilterState {
const [query, setQuery] = React.useState<string>();
const contentRef = React.useRef<HTMLElement | null>(null);
const highlightRef = React.useRef<HTMLElement | null>(null);
const reset = React.useCallback(() => {
contentRef.current = null;
highlightRef.current = null;
setQuery(undefined);
}, []);
const handleKeyDownCapture = React.useCallback(
(event: React.KeyboardEvent<HTMLElement>) => {
const { target, currentTarget } = event;
if (
!(target instanceof HTMLElement) ||
target.closest("[data-radix-menu-content]") !== currentTarget ||
(isTextInput(target) && !target.matches('[role^="menuitem"]')) ||
target.isContentEditable
) {
return;
}
const input = currentTarget.querySelector<HTMLInputElement>(
`[${INPUT_ATTRIBUTE}]`
);
// AltGr is reported as Ctrl+Alt on Windows, but it types a character.
const isShortcut =
(event.ctrlKey || event.metaKey || event.altKey) &&
!event.getModifierState("AltGraph");
if (!input || isShortcut) {
return;
}
// Move up from the first item to the input while the filter is visible.
if (
event.key === "ArrowUp" &&
query !== undefined &&
target === currentTarget.querySelector(ITEM_SELECTOR)
) {
event.preventDefault();
event.stopPropagation();
highlightRef.current = highlightItem(currentTarget, target);
input.focus();
return;
}
const isText =
Array.from(event.key).length === 1 ||
(event.key === "Backspace" && !!query);
if (!isText) {
return;
}
// Space selects the focused item until there is a query to add it to.
if (event.key === " " && !query) {
return;
}
// The default action is kept, so the browser types into the input. Radix
// typeahead, item selection and global shortcuts must not handle the key.
event.stopPropagation();
contentRef.current = currentTarget;
if (target.matches(ITEM_SELECTOR)) {
highlightRef.current = target;
}
if (query === undefined) {
lockLayout(currentTarget);
}
input.focus();
},
[query]
);
const handleEscapeKeyDown = React.useCallback(
(event: KeyboardEvent) => {
if (query === undefined) {
return;
}
event.preventDefault();
setQuery(undefined);
},
[query]
);
// While the input has focus, highlight the item that had focus before, or
// the first match if it was filtered out. Otherwise move focus to the first
// item if the focused item was filtered out, or if the filter was hidden
// while it had focus. A passive effect runs after Radix removes unmounted
// items from its collection.
React.useEffect(() => {
const content = contentRef.current;
if (!content) {
return;
}
const active = document.activeElement;
if (query !== undefined && active?.hasAttribute(INPUT_ATTRIBUTE)) {
highlightRef.current = highlightItem(content, highlightRef.current);
return;
}
if (
active &&
content.contains(active) &&
active.getAttribute("role")?.startsWith("menuitem")
) {
return;
}
const first = content.querySelector<HTMLElement>(ITEM_SELECTOR);
(first ?? content).focus();
}, [query]);
return { query, setQuery, handleKeyDownCapture, handleEscapeKeyDown, reset };
}
interface Props {
/** The current filter query, or undefined when the filter is hidden. */
query: string | undefined;
/** Called when the user changes the query. */
onChange: (query: string) => void;
}
/**
* Displays the filter input at the top of a menu. The input is always
* rendered, so that it can receive focus before the first character is typed,
* but it is only visible while there is a query.
*/
export function MenuFilter({ query, onChange }: Props) {
const { t } = useTranslation();
const isActive = query !== undefined;
const handleChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
onChange(event.target.value);
},
[onChange]
);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
// Radix typeahead must not handle keys typed into the input, but Tab
// must reach the menu so that focus stays in it.
if (event.key !== "Tab") {
event.stopPropagation();
}
if (event.nativeEvent.isComposing) {
return;
}
const content = event.currentTarget.closest("[data-radix-menu-content]");
const items = content
? Array.from(content.querySelectorAll<HTMLElement>(ITEM_SELECTOR))
: [];
const highlighted =
content?.querySelector<HTMLElement>(`[${HIGHLIGHT_ATTRIBUTE}]`) ??
items[0];
if (event.key === "ArrowDown") {
event.preventDefault();
highlighted?.focus();
} else if (event.key === "ArrowUp") {
event.preventDefault();
items[items.length - 1]?.focus();
} else if (event.key === "Enter") {
event.preventDefault();
highlighted?.click();
}
},
[]
);
return (
<Wrapper style={isActive ? undefined : VISUALLY_HIDDEN_STYLES}>
<Input
value={query ?? ""}
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder={`${t("Filter")}…`}
aria-label={t("Filter")}
tabIndex={-1}
autoComplete="off"
spellCheck={false}
{...{ [INPUT_ATTRIBUTE]: "" }}
/>
</Wrapper>
);
}
/**
* Displays a message when no menu items match the filter query.
*/
export function MenuFilterEmpty() {
const { t } = useTranslation();
return <Empty>{t("No results")}</Empty>;
}
/**
* Records the current width and position of the menu. The filter row applies
* them, so that the menu does not move while the items are filtered.
*/
function lockLayout(content: HTMLElement) {
// The computed width is not changed by the scale of the open animation.
content.style.setProperty(
"--menu-filter-width",
getComputedStyle(content).width
);
content.setAttribute(LOCKED_ATTRIBUTE, "");
const wrapper = content.closest<HTMLElement>(
"[data-radix-popper-content-wrapper]"
);
if (wrapper?.style.transform) {
wrapper.style.setProperty(
"--menu-filter-transform",
wrapper.style.transform
);
wrapper.setAttribute(LOCKED_ATTRIBUTE, "");
}
}
/**
* Marks the item that Enter selects while the filter input has focus.
*
* @param content the menu content.
* @param preferred the item to mark if it is still in the menu.
* @returns the marked item, or null if the menu has no items.
*/
function highlightItem(content: HTMLElement, preferred: HTMLElement | null) {
const item =
preferred?.isConnected &&
content.contains(preferred) &&
preferred.matches(ITEM_SELECTOR)
? preferred
: content.querySelector<HTMLElement>(ITEM_SELECTOR);
content
.querySelectorAll(`[${HIGHLIGHT_ATTRIBUTE}]`)
.forEach((element) => element.removeAttribute(HIGHLIGHT_ATTRIBUTE));
item?.setAttribute(HIGHLIGHT_ATTRIBUTE, "");
return item;
}
const ITEM_SELECTOR = '[role^="menuitem"]:not([data-disabled])';
const HIGHLIGHT_ATTRIBUTE = "data-menu-filter-highlighted";
const LOCKED_ATTRIBUTE = "data-menu-filter-locked";
const INPUT_ATTRIBUTE = "data-menu-filter-input";
const Wrapper = styled.label`
position: sticky;
top: 0;
z-index: 1;
display: flex;
align-items: center;
min-height: 40px;
margin: -6px -6px 6px;
padding: 8px 18px;
cursor: text;
background: ${s("menuBackground")};
border-bottom: 1px solid ${s("divider")};
// Keep the size and position that the menu had before filtering. This rule
// overrides the inline transform that Radix changes when the menu resizes.
[data-radix-menu-content][${LOCKED_ATTRIBUTE}]:has(&) {
width: var(--menu-filter-width);
}
[data-radix-popper-content-wrapper][${LOCKED_ATTRIBUTE}]:has(&) {
transform: var(--menu-filter-transform) !important;
}
`;
const Input = styled.input`
flex: 1;
min-width: 0;
margin: 0;
padding: 0;
border: 0;
outline: none;
background: none;
font: inherit;
font-size: 16px;
color: ${s("text")};
&::placeholder {
color: ${s("placeholder")};
}
${breakpoint("tablet")`
font-size: 14px;
`}
`;
const Empty = styled.div`
padding: 4px 12px;
font-size: 14px;
color: ${s("textTertiary")};
`;
+50
View File
@@ -0,0 +1,50 @@
import type { ReactElement } from "react";
import type { MenuItem } from "~/types";
import { toMenuItems } from "./transformer";
const noop = () => undefined;
const items: MenuItem[] = [
{ type: "button", title: "Team", onClick: noop },
{ type: "button", title: "Due date", onClick: noop },
{ type: "separator" },
{
type: "submenu",
title: "Move to",
items: [
{ type: "button", title: "Engineering", onClick: noop },
{ type: "button", title: "Design", onClick: noop },
],
},
{ type: "button", title: "Hidden date", visible: false, onClick: noop },
];
function render(query?: string) {
return (toMenuItems(items, query) ?? []).filter(
(element): element is ReactElement => !!element
);
}
describe("toMenuItems", () => {
it("returns all visible items without a query", () => {
expect(render().map((element) => element.key)).toEqual([
"button-0",
"button-1",
"separator-2",
"submenu-3",
]);
});
it("returns only matching items and keeps their keys", () => {
expect(render("DATE").map((element) => element.key)).toEqual(["button-1"]);
});
it("keeps a submenu when one of its items matches", () => {
const [submenu] = render("design");
expect(submenu.key).toEqual("submenu-3");
});
it("returns null when nothing matches", () => {
expect(toMenuItems(items, "zzz")).toBeNull();
});
});
+56 -5
View File
@@ -14,11 +14,27 @@ import type { MenuItem } from "~/types";
import { MouseSafeArea } from "~/components/MouseSafeArea";
import { createRef } from "react";
export function toMenuItems(items: MenuItem[]) {
/**
* Converts menu items to menu elements.
*
* @param items the menu items to convert.
* @param query an optional filter query, only matching items are returned.
* @returns the menu elements, or null if there are none.
*/
export function toMenuItems(items: MenuItem[], query?: string) {
const filteredItems = filterMenuItems(items);
const parentRef = createRef<HTMLDivElement>();
const normalizedQuery = query?.toLocaleLowerCase();
if (!filteredItems.length) {
// Keys use the index before the query is applied, so that the focused item
// keeps its element while the query changes.
const entries = filteredItems
.map((item, index) => ({ item, index }))
.filter(
({ item }) => !normalizedQuery || matchesQuery(item, normalizedQuery)
);
if (!entries.length) {
return null;
}
@@ -31,13 +47,19 @@ export function toMenuItems(items: MenuItem[]) {
!!item.icon
);
return filteredItems.map((item, index) => {
return entries.map(({ item, index }) => {
const icon = showIcon ? (
<Components.MenuIconWrapper aria-hidden>
{"icon" in item ? item.icon : null}
</Components.MenuIconWrapper>
) : undefined;
// Children are filtered too, unless the parent title itself matches.
const childQuery =
normalizedQuery && !titleMatches(item, normalizedQuery)
? normalizedQuery
: undefined;
switch (item.type) {
case "button":
return (
@@ -85,7 +107,7 @@ export function toMenuItems(items: MenuItem[]) {
);
case "submenu": {
const submenuItems = toMenuItems(item.items);
const submenuItems = toMenuItems(item.items, childQuery);
if (!submenuItems?.length) {
return null;
@@ -116,7 +138,7 @@ export function toMenuItems(items: MenuItem[]) {
}
case "group": {
const groupItems = toMenuItems(item.items);
const groupItems = toMenuItems(item.items, childQuery);
if (!groupItems?.length) {
return null;
@@ -287,6 +309,35 @@ export function toMobileMenuItems(
});
}
function titleMatches(item: MenuItem, query: string): boolean {
return (
"title" in item &&
typeof item.title === "string" &&
item.title.toLocaleLowerCase().includes(query)
);
}
function matchesQuery(item: MenuItem, query: string): boolean {
if (item.visible === false) {
return false;
}
switch (item.type) {
case "button":
case "route":
case "link":
return titleMatches(item, query);
case "submenu":
case "group":
return (
titleMatches(item, query) ||
item.items.some((child) => matchesQuery(child, query))
);
default:
return false;
}
}
function filterMenuItems(items: MenuItem[]): MenuItem[] {
return items
.filter((item) => item.visible !== false)
@@ -2,7 +2,7 @@ import { CollapsedIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { extraArea, s } from "@shared/styles";
import { extraArea, hover, s } from "@shared/styles";
import NudeButton from "~/components/NudeButton";
type Props = React.ComponentProps<typeof Button> & {
@@ -34,7 +34,7 @@ const Button = styled(NudeButton)`
margin: 2px;
${extraArea(4)}
&:hover {
&:${hover} {
color: ${s("text")};
background: ${s("sidebarControlHoverBackground")};
}
@@ -15,7 +15,7 @@ import useBoolean from "~/hooks/useBoolean";
import { ActionContextProvider } from "~/hooks/useActionContext";
import DropToImport from "./DropToImport";
import Relative from "./Relative";
import SidebarLink from "./SidebarLink";
import SidebarLink, { childDepthFor } from "./SidebarLink";
import { StaticLink } from "./StaticLink";
import type { SidebarContextType } from "./SidebarContext";
import { useSidebarContext } from "./SidebarContext";
@@ -94,8 +94,6 @@ export type DocumentRowProps = {
canCreateChild?: boolean;
/** Submit handler for the inline new-child title input. */
onCreateChild?: (title: string) => Promise<void>;
/** Depth of the inline new-child SidebarLink. Defaults to `depth + 1`. */
newChildDepth?: number;
/** Context menu action for the row. */
contextAction?: ActionWithChildren | ActionFactory;
@@ -145,7 +143,6 @@ function DocumentRow({
menuOpen,
canCreateChild,
onCreateChild,
newChildDepth,
contextAction,
isActiveOverride,
children,
@@ -306,7 +303,7 @@ function DocumentRow({
{isAddingNewChild && onCreateChild && (
<SidebarLink
isActive={() => true}
depth={newChildDepth ?? depth + 1}
depth={childDepthFor(depth)}
ellipsis={false}
label={
<EditableTitle
@@ -3,16 +3,21 @@ import type { Location } from "history";
import { observer } from "mobx-react";
import * as React from "react";
import type { match } from "react-router";
import { IconType, NotificationEventType } from "@shared/types";
import { useHistory } from "react-router-dom";
import { IconType, NotificationEventType, UserPreference } from "@shared/types";
import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
import { determineIconType } from "@shared/utils/icon";
import type GroupMembership from "~/models/GroupMembership";
import UserMembership from "~/models/UserMembership";
import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext";
import useBoolean from "~/hooks/useBoolean";
import { useComputed } from "~/hooks/useComputed";
import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import DocumentMenu from "~/menus/DocumentMenu";
import * as Scenes from "~/routes/scenes";
import { documentEditPath } from "~/utils/routeHelpers";
import {
useDragMembership,
useDropToReorderUserMembership,
@@ -31,6 +36,7 @@ import SidebarDisclosureContext, {
useSidebarDisclosureState,
} from "./SidebarDisclosureContext";
import { useSidebarContext, type SidebarContextType } from "./SidebarContext";
import { childDepthFor } from "./SidebarLink";
import { useSidebarNavigation } from "./SidebarNavigation";
type Props = {
@@ -50,6 +56,9 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
const activeSidebarContext = useActiveSidebarContext();
const sidebarContext = useSidebarContext();
const document = documentId ? documents.get(documentId) : undefined;
const can = usePolicy(document);
const history = useHistory();
const user = useCurrentUser();
const membershipDocuments = membership.documents;
const expansion = useSidebarExpansionState(membershipDocuments);
@@ -122,6 +131,45 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
]
);
const handleNewDoc = React.useCallback(
async (input: string) => {
if (!document) {
return;
}
const newDocument = await documents.create(
{
collectionId: document.collectionId ?? undefined,
parentDocumentId: document.id,
fullWidth:
document.fullWidth ??
user.getPreference(UserPreference.FullWidthDocuments),
title: input,
data: ProsemirrorDataHelper.getEmpty(),
},
{ publish: true }
);
if (newDocument.collectionId) {
collections
.get(newDocument.collectionId)
?.addDocument(newDocument, document.id);
}
membership.addDocument(newDocument, document.id);
history.push({
pathname: documentEditPath(newDocument),
state: { sidebarContext },
});
},
[
documents,
collections,
document,
membership,
sidebarContext,
user,
history,
]
);
const parentRef = React.useRef<HTMLDivElement>(null);
const reparentableNode = React.useMemo(
() => document?.asNavigationNode,
@@ -236,6 +284,8 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
}
menu={menu}
menuOpen={menuOpen}
canCreateChild={can.createChildDocument}
onCreateChild={handleNewDoc}
isActiveOverride={isActive}
>
<SidebarDisclosureContext.Provider value={disclosureEvent}>
@@ -243,7 +293,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
<Folder expanded={displayChildDocuments}>
<DocumentTree
nodes={childDocuments}
depth={depth + 1}
depth={childDepthFor(depth)}
parentId={document.id}
collection={collection}
membership={membership}
@@ -1,14 +1,15 @@
import styled, { css } from "styled-components";
import EventBoundary from "@shared/components/EventBoundary";
import { s } from "@shared/styles";
import { hover, s } from "@shared/styles";
import NudeButton from "~/components/NudeButton";
/**
* Selector list matching a sidebar row that is hovered, pressed, or has one
* of its menus open. Radix marks the open trigger with `data-state="open"`:
* the row itself for a context menu, a descendant button for a dropdown.
* the row itself for a context menu, a descendant button for a dropdown. On
* touch devices `:hover` sticks after a tap, so only `:active` is matched.
*/
export const hoveredOrMenuOpen = `&:hover, &:active, &[data-state="open"], &:has([data-state="open"])`;
export const hoveredOrMenuOpen = `&:${hover}, &:active, &[data-state="open"], &:has([data-state="open"])`;
/**
* Trailing action buttons for a sidebar row. Hidden until the row reveals
@@ -235,7 +235,6 @@ const StarredDocumentLink = observer(function StarredDocumentLink({
menuOpen={menuOpen}
canCreateChild={can.createChildDocument}
onCreateChild={handleNewDoc}
newChildDepth={2}
contextAction={contextMenuAction}
isActiveOverride={isActive}
onClickIntent={handlePrefetch}
+18 -6
View File
@@ -13,6 +13,7 @@ import Input from "~/components/Input";
import useCurrentUser from "~/hooks/useCurrentUser";
import useStores from "~/hooks/useStores";
import ImageInput from "~/scenes/Settings/components/ImageInput";
import type { ImageUploadHandle } from "~/scenes/Settings/components/ImageUpload";
import { performBatch } from "~/actions/definitions/common";
import { client } from "~/utils/ApiClient";
import Text from "./Text";
@@ -183,6 +184,11 @@ export const UserChangeAvatarDialog = observer(function UserChangeAvatarDialog({
onSubmit,
}: Props) {
const { t } = useTranslation();
const imageRef = React.useRef<ImageUploadHandle>(null);
const handleReplace = () => {
imageRef.current?.open();
};
const handleAvatarChange = async (avatarUrl: string | null) => {
try {
@@ -205,15 +211,21 @@ export const UserChangeAvatarDialog = observer(function UserChangeAvatarDialog({
onSuccess={handleAvatarChange}
onError={handleAvatarError}
model={user}
showRemoveOption={false}
showActions={false}
ref={imageRef}
/>
</Flex>
<Flex justify="flex-end" gap={8}>
{user.avatarUrl && (
<Button onClick={() => handleAvatarChange(null)} neutral>
{t("Remove")}
<Flex justify="space-between" gap={8}>
<Flex gap={8}>
<Button onClick={handleReplace} neutral>
{user.avatarUrl ? t("Replace") : t("Upload")}…
</Button>
)}
{user.avatarUrl && (
<Button onClick={() => handleAvatarChange(null)} neutral>
{t("Delete")}
</Button>
)}
</Flex>
<Button onClick={onSubmit}>{t("Done")}</Button>
</Flex>
</Flex>
@@ -68,7 +68,9 @@ const BaseMenuItemCSS = css<BaseMenuItemProps>`
`
&[data-highlighted],
&[data-state="open"],
&:focus-visible {
&:focus-visible,
[data-radix-menu-content]:has([data-menu-filter-input]:focus)
&[data-menu-filter-highlighted] {
color: ${props.theme.accentText};
background: ${props.$dangerous ? props.theme.danger : props.theme.accent};
outline-color: ${
+28 -4
View File
@@ -16,6 +16,11 @@ import ToolbarButton from "./ToolbarButton";
import ToolbarSeparator from "./ToolbarSeparator";
import Tooltip from "./Tooltip";
import { toMenuItems } from "~/components/Menu/transformer";
import {
MenuFilter,
MenuFilterEmpty,
useMenuFilter,
} from "~/components/Menu/MenuFilter";
import { MenuContent } from "~/components/primitives/Menu";
import { MenuProvider } from "~/components/primitives/Menu/MenuContext";
import { Menu, MenuTrigger } from "~/components/primitives/Menu";
@@ -44,10 +49,23 @@ function ToolbarDropdown(props: ToolbarDropdownProps) {
const { item, shortcut, tooltip } = props;
const { state } = view;
const [isOpen, setIsOpen] = useState<boolean>(false);
const {
query,
setQuery,
handleKeyDownCapture,
handleEscapeKeyDown,
reset: resetFilter,
} = useMenuFilter();
const handleOpenChange = useCallback((open: boolean) => {
setIsOpen(open);
}, []);
const handleOpenChange = useCallback(
(open: boolean) => {
setIsOpen(open);
if (open) {
resetFilter();
}
},
[resetFilter]
);
const items: TMenuItem[] = useMemo(() => {
if (!isOpen) {
@@ -86,8 +104,14 @@ function ToolbarDropdown(props: ToolbarDropdownProps) {
align="end"
aria-label={item.tooltip || t("More options")}
onCloseAutoFocus={handleCloseAutoFocus}
onEscapeKeyDown={handleEscapeKeyDown}
onKeyDownCapture={handleKeyDownCapture}
>
<EventBoundary>{toMenuItems(items)}</EventBoundary>
<MenuFilter query={query} onChange={setQuery} />
<EventBoundary>
{toMenuItems(items, query) ??
(query ? <MenuFilterEmpty /> : null)}
</EventBoundary>
</MenuContent>
</Menu>
</MenuProvider>
+1 -1
View File
@@ -37,7 +37,7 @@ const hoverPluginKey = new PluginKey<number | null>(HOVER_META_KEY);
/**
* Renders a floating drag handle to the left of block-level nodes when the
* user hovers within the editor, and lets the user drag the block to reorder
* user hovers near the side of the editor, and lets the user drag the block to reorder
* it. The handle is a real, always-draggable DOM element rather than a CSS
* pseudo on the block, which keeps drag-and-drop working uniformly across
* node types regardless of whether the schema declares `draggable: true`.
+48 -30
View File
@@ -18,12 +18,13 @@ export interface ResolvedDragTarget {
const LIST_TYPES = ["bullet_list", "ordered_list", "checkbox_list"];
// Distance outside the content column in which the cursor still finds a block.
const GUTTER_HIT_WIDTH = 60;
// Inset from the content edges, so that posAtCoords lands inside the block.
const CONTENT_INSET = 1;
// Fraction of the content width, from the handle side, in which hover shows
// the handle.
const HOVER_ZONE_RATIO = 0.25;
/**
* A block in the editor that the drag handle can attach to. Holds the
* position of the block in the document and the DOM element that the handle
@@ -46,8 +47,9 @@ export class DragTarget {
}
/**
* Finds the block under the cursor, also when the cursor is in the gutter
* to the side of the content.
* Finds the block at the cursor's height when the cursor is on the side
* where the handle renders, either outside the content or in the first 25%
* of the content width.
*
* @param view - the editor view.
* @param event - the mouse event.
@@ -61,17 +63,20 @@ export class DragTarget {
if (event.clientY < rect.top || event.clientY > rect.bottom) {
return null;
}
// Ignore the cursor over other regions, such as the sidebar or a modal.
const region = view.dom.closest("[role='main']");
if (
region &&
!(event.target instanceof Node && region.contains(event.target))
) {
return null;
}
const style = window.getComputedStyle(view.dom);
const paddingLeft = parseFloat(style.paddingLeft) || 0;
const paddingRight = parseFloat(style.paddingRight) || 0;
const contentLeft = rect.left + paddingLeft + CONTENT_INSET;
const contentRight = rect.right - paddingRight - CONTENT_INSET;
if (
event.clientX < contentLeft - GUTTER_HIT_WIDTH ||
event.clientX > contentRight + GUTTER_HIT_WIDTH
) {
return null;
}
const projectedX = Math.max(
contentLeft,
Math.min(contentRight, event.clientX)
@@ -80,27 +85,20 @@ export class DragTarget {
// Mermaid diagrams hide their source code block and render an SVG widget
// next to it — target the underlying code block but anchor the handle to
// the visible diagram element.
const mermaid = this.mermaidFromEvent(view, event, projectedX);
if (mermaid) {
return mermaid;
const target =
this.mermaidFromEvent(view, event, projectedX) ??
this.blockFromCoords(view, projectedX, event.clientY);
if (!target) {
return null;
}
const coords = view.posAtCoords({
left: projectedX,
top: event.clientY,
});
if (!coords) {
return null;
}
const resolved = this.resolvePos(view.state, coords.pos);
if (!resolved) {
return null;
}
const dom = view.nodeDOM(resolved.pos);
if (!(dom instanceof HTMLElement)) {
return null;
}
return new DragTarget(resolved.pos, dom, resolved.kind);
// Only show the handle when the cursor is on the side it renders on.
const zoneWidth = (contentRight - contentLeft) * HOVER_ZONE_RATIO;
const isRTL = window.getComputedStyle(target.element).direction === "rtl";
const inZone = isRTL
? event.clientX >= contentRight - zoneWidth
: event.clientX <= contentLeft + zoneWidth;
return inZone ? target : null;
}
/**
@@ -258,6 +256,26 @@ export class DragTarget {
return found;
}
private static blockFromCoords(
view: EditorView,
left: number,
top: number
): DragTarget | null {
const coords = view.posAtCoords({ left, top });
if (!coords) {
return null;
}
const resolved = this.resolvePos(view.state, coords.pos);
if (!resolved) {
return null;
}
const dom = view.nodeDOM(resolved.pos);
if (!(dom instanceof HTMLElement)) {
return null;
}
return new DragTarget(resolved.pos, dom, resolved.kind);
}
private static mermaidFromEvent(
view: EditorView,
event: MouseEvent,
-1
View File
@@ -42,7 +42,6 @@ import type { Searchable } from "./interfaces/Searchable";
type SaveOptions = JSONObject & {
publish?: boolean;
done?: boolean;
autosave?: boolean;
};
+5 -1
View File
@@ -1,6 +1,7 @@
import { computed, observable } from "mobx";
import type GroupMembership from "./GroupMembership";
import Model from "./base/Model";
import NavigableModel from "./base/NavigableModel";
import Field from "./decorators/Field";
import { GroupPermission } from "@shared/types";
import type { Searchable } from "./interfaces/Searchable";
@@ -110,6 +111,7 @@ class Group extends Model implements Searchable {
/**
* Returns the direct memberships that this group has to documents. Documents that the current
* user already has access to through a collection, archived, and trashed documents are not included.
* Documents nested under another shared document in the list are also not included.
*
* @returns A list of group memberships
*/
@@ -118,7 +120,7 @@ class Group extends Model implements Searchable {
const { groupMemberships, groupUsers, documents, policies, auth } =
this.store.rootStore;
return groupMemberships.orderedData
const memberships = groupMemberships.orderedData
.filter((groupMembership) =>
groupUsers.orderedData.some(
(groupUser) =>
@@ -136,6 +138,8 @@ class Group extends Model implements Searchable {
: undefined;
return !policy?.abilities?.readDocument && !!document?.isActive;
});
return NavigableModel.filterRoots(memberships, documents);
}
}
+72
View File
@@ -194,4 +194,76 @@ describe("User model", () => {
expect(user.initials).toBe("JG");
});
});
describe("documentMemberships", () => {
const user = new User({ id: "300", name: "Member" }, users);
beforeEach(() => {
stores.documents.clear();
stores.userMemberships.clear();
});
const addDocument = (id: string, parentDocumentId?: string) =>
stores.documents.add({
id,
title: id,
parentDocumentId,
collectionId: "collection",
});
const addMembership = (id: string, documentId: string) =>
stores.userMemberships.add({
id,
userId: user.id,
documentId,
sourceId: null,
index: id,
});
it("should only include the highest shared document of a tree", () => {
addDocument("parent");
addDocument("child", "parent");
addDocument("grandchild", "child");
addMembership("m1", "grandchild");
addMembership("m2", "child");
addMembership("m3", "parent");
expect(user.documentMemberships.map((m) => m.documentId)).toEqual([
"parent",
]);
});
it("should include a moved document that is still in a cached tree", () => {
addDocument("parent");
addDocument("child");
addMembership("m1", "child");
const parent = addMembership("m2", "parent");
parent.node = {
id: "parent",
title: "parent",
url: "/doc/parent",
children: [
{ id: "child", title: "child", url: "/doc/child", children: [] },
],
};
expect(user.documentMemberships.map((m) => m.documentId)).toEqual([
"child",
"parent",
]);
});
it("should include a document whose parent is not shared", () => {
addDocument("parent");
addDocument("child", "parent");
addDocument("other");
addMembership("m1", "child");
addMembership("m2", "other");
expect(user.documentMemberships.map((m) => m.documentId)).toEqual([
"child",
"other",
]);
});
});
});
+5 -1
View File
@@ -17,6 +17,7 @@ import { client } from "~/utils/ApiClient";
import type Document from "./Document";
import type Group from "./Group";
import type UserMembership from "./UserMembership";
import NavigableModel from "./base/NavigableModel";
import ParanoidModel from "./base/ParanoidModel";
import Field from "./decorators/Field";
import Relation from "./decorators/Relation";
@@ -211,13 +212,14 @@ class User extends ParanoidModel implements Searchable {
/**
* Returns the direct memberships that this user has to documents. Documents that the
* user already has access to through a collection, archived, and trashed documents are not included.
* Documents nested under another shared document in the list are also not included.
*
* @returns A list of user memberships
*/
@computed
get documentMemberships(): UserMembership[] {
const { userMemberships, documents, policies } = this.store.rootStore;
return userMemberships.orderedData
const memberships = userMemberships.orderedData
.filter(
(m) => m.userId === this.id && m.sourceId === null && m.documentId
)
@@ -228,6 +230,8 @@ class User extends ParanoidModel implements Searchable {
: undefined;
return !policy?.abilities?.readDocument && !!document?.isActive;
});
return NavigableModel.filterRoots(memberships, documents);
}
@computed
+1 -1
View File
@@ -29,7 +29,7 @@ class UserMembership extends NavigableModel {
document?: Document;
/** The source ID points to the root membership from which this inherits */
sourceId?: string;
sourceId?: string | null;
/** The source points to the root membership from which this inherits */
@Relation(() => UserMembership, { onDelete: "cascade" })
+54
View File
@@ -3,8 +3,62 @@ import type { JSONObject, NavigationNode } from "@shared/types";
import { client } from "~/utils/ApiClient";
import Model from "./Model";
import type Document from "../Document";
import type DocumentsStore from "~/stores/DocumentsStore";
export default abstract class NavigableModel extends Model {
/**
* Filters memberships to those whose document is not nested under the
* document of another membership in the list, so that each shared tree is
* shown once from its highest shared document.
*
* @param memberships the memberships to filter.
* @param documents the documents store used to find parent documents.
* @returns the memberships that are roots of a shared tree.
*/
static filterRoots<T extends NavigableModel>(
memberships: T[],
documents: DocumentsStore
): T[] {
if (memberships.length < 2) {
return memberships;
}
const rootIds = new Set(memberships.map((m) => m.documentId));
return memberships.filter((membership) => {
const { documentId } = membership;
if (!documentId) {
return true;
}
const visited = new Set([documentId]);
let document = documents.get(documentId);
while (document?.parentDocumentId) {
const { parentDocumentId } = document;
if (rootIds.has(parentDocumentId)) {
return false;
}
if (visited.has(parentDocumentId)) {
return true;
}
visited.add(parentDocumentId);
document = documents.get(parentDocumentId);
}
// The parent chain is complete, so the loaded trees are not needed.
if (document) {
return true;
}
// Parent documents may not be loaded, so also check the loaded trees.
return !memberships.some(
(other) =>
other.documentId !== documentId &&
other.childrenByDocumentId.has(documentId)
);
});
}
private isFetching = false;
/** The document ID associated with this model. */
+4 -1
View File
@@ -165,7 +165,10 @@ export function useDocumentSave({
setIsPublishing(!!options.publish);
try {
const savedDocument = await document.save(undefined, options);
const savedDocument = await document.save(undefined, {
publish: options.publish,
autosave: options.autosave,
});
isEditorDirtyRef.current = false;
setIsEditorDirty(false);
+88 -87
View File
@@ -11,6 +11,7 @@ import Switch from "~/components/Switch";
import Text from "~/components/Text";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import SettingRow from "./components/SettingRow";
import { SettingsSection } from "./components/SettingsSection";
import Input from "~/components/Input";
import Tooltip from "~/components/Tooltip";
import CopyToClipboard from "~/components/CopyToClipboard";
@@ -56,102 +57,102 @@ function AI() {
<Trans>Control how AI features are used in the workspace.</Trans>
</Text>
<Heading as="h2">{t("MCP server")}</Heading>
<SettingRow
name={TeamPreference.MCP}
label={t("Enabled")}
description={
<>
<Text type="secondary" as="p">
{t(
"Let members connect AI assistants and other apps to this workspace. Connected apps can read and edit content with the same permissions as the member who connects them."
)}
</Text>
{team.getPreference(TeamPreference.MCP) && (
<>
<Text
type="secondary"
as="p"
style={{ marginTop: 8, marginBottom: 4 }}
>
<Trans
defaults="Use this URL in your MCP client. See <a>the setup guide</a> for more details."
components={{
a: (
<Text
as="a"
weight="bold"
href="https://docs.getoutline.com/s/guide/doc/mcp-6j9jtENNKL"
target="_blank"
rel="noopener noreferrer"
/>
),
}}
/>
</Text>
<Input readOnly value={mcpEndpoint}>
<Tooltip content={t("Copy URL")}>
<CopyToClipboard text={mcpEndpoint} onCopy={handleCopied}>
<NudeButton type="button" style={{ marginRight: 3 }}>
<CopyIcon color={theme.placeholder} size={18} />
</NudeButton>
</CopyToClipboard>
</Tooltip>
</Input>
</>
)}
</>
}
>
<Switch
id={TeamPreference.MCP}
name={TeamPreference.MCP}
aria-label={t("MCP server")}
checked={team.getPreference(TeamPreference.MCP)}
onChange={handleMCPChange}
/>
</SettingRow>
{team.getPreference(TeamPreference.MCP) && (
<SettingsSection title={t("MCP server")}>
<SettingRow
name="guidanceMCP"
label={t("Custom instructions")}
border={false}
name={TeamPreference.MCP}
label={t("Enabled")}
description={
<>
<div style={{ marginBottom: 8 }}>
<Text type="secondary" as="p">
{t(
"Optional instructions that are sent to connected AI apps, for example how your workspace is organized or where to find important information."
"Let members connect AI assistants and other apps to this workspace. Connected apps can read and edit content with the same permissions as the member who connects them."
)}
</div>
<Input
id="guidanceMCP"
type="textarea"
autoSize
minHeight="6lh"
maxHeight="20lh"
value={team.guidanceMCP ?? ""}
maxLength={TeamValidation.maxGuidanceMCPLength}
warningLimit={TeamValidation.warnGuidanceMCPLength}
onChange={handleGuidanceMCPChange}
onBlur={handleGuidanceMCPBlur}
/>
</Text>
{team.getPreference(TeamPreference.MCP) && (
<>
<Text
type="secondary"
as="p"
style={{ marginTop: 8, marginBottom: 4 }}
>
<Trans
defaults="Use this URL in your MCP client. See <a>the setup guide</a> for more details."
components={{
a: (
<Text
as="a"
weight="bold"
href="https://docs.getoutline.com/s/guide/doc/mcp-6j9jtENNKL"
target="_blank"
rel="noopener noreferrer"
/>
),
}}
/>
</Text>
<Input readOnly value={mcpEndpoint}>
<Tooltip content={t("Copy URL")}>
<CopyToClipboard text={mcpEndpoint} onCopy={handleCopied}>
<NudeButton type="button" style={{ marginRight: 3 }}>
<CopyIcon color={theme.placeholder} size={18} />
</NudeButton>
</CopyToClipboard>
</Tooltip>
</Input>
</>
)}
</>
}
/>
)}
>
<Switch
id={TeamPreference.MCP}
name={TeamPreference.MCP}
aria-label={t("MCP server")}
checked={team.getPreference(TeamPreference.MCP)}
onChange={handleMCPChange}
/>
</SettingRow>
<Heading as="h2">{t("AI answers")}</Heading>
<SettingRow
name="answers"
label={t("Enabled")}
description={t(
"Show AI-generated answers to questions in search, based on content in your workspace. Requires a paid license."
{team.getPreference(TeamPreference.MCP) && (
<SettingRow
name="guidanceMCP"
label={t("Custom instructions")}
description={
<>
<div style={{ marginBottom: 8 }}>
{t(
"Optional instructions that are sent to connected AI apps, for example how your workspace is organized or where to find important information."
)}
</div>
<Input
id="guidanceMCP"
type="textarea"
autoSize
minHeight="6lh"
maxHeight="20lh"
value={team.guidanceMCP ?? ""}
maxLength={TeamValidation.maxGuidanceMCPLength}
warningLimit={TeamValidation.warnGuidanceMCPLength}
onChange={handleGuidanceMCPChange}
onBlur={handleGuidanceMCPBlur}
/>
</>
}
/>
)}
border={false}
>
<Switch disabled />
</SettingRow>
</SettingsSection>
<SettingsSection title={t("AI answers")}>
<SettingRow
name="answers"
label={t("Enabled")}
description={t(
"Show AI-generated answers to questions in search, based on content in your workspace. Requires a paid license."
)}
>
<Switch disabled />
</SettingRow>
</SettingsSection>
</Scene>
);
}
+170 -169
View File
@@ -21,6 +21,7 @@ import usePolicy from "~/hooks/usePolicy";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import SettingRow from "./components/SettingRow";
import { SettingsSection } from "./components/SettingsSection";
import { setPostLoginPath } from "~/hooks/useLastVisitedPath";
import { getRedirectUrl, toRelative } from "~/utils/urls";
import { settingsPath } from "~/utils/routeHelpers";
@@ -193,188 +194,188 @@ function Authentication() {
</Trans>
</Text>
<Heading as="h2">{t("Sign in")}</Heading>
<SettingsSection title={t("Sign in")}>
{authenticationProviders.orderedData.map((provider) => {
// Group sync can still be disabled after losing the entitlement.
const showGroupSync =
provider.isActive &&
provider.groupSyncSupported &&
(!!can.externalGroupSync || !!provider.settings?.groupSyncEnabled);
{authenticationProviders.orderedData.map((provider) => {
// Group sync can still be disabled after losing the entitlement.
const showGroupSync =
provider.isActive &&
provider.groupSyncSupported &&
(!!can.externalGroupSync || !!provider.settings?.groupSyncEnabled);
return (
<React.Fragment key={provider.name}>
<SettingRow
label={
<Flex gap={8} align="center">
<PluginIcon id={provider.name} /> {provider.displayName}
</Flex>
}
name={provider.name}
description={
provider.isConnected
? t("Allow members to sign in with {{ authProvider }}", {
authProvider: provider.displayName,
})
: t(
"Connect {{ authProvider }} to allow members to sign in",
{
return (
<React.Fragment key={provider.name}>
<SettingRow
label={
<Flex gap={8} align="center">
<PluginIcon id={provider.name} /> {provider.displayName}
</Flex>
}
name={provider.name}
description={
provider.isConnected
? t("Allow members to sign in with {{ authProvider }}", {
authProvider: provider.displayName,
}
)
}
border={!showGroupSync}
>
<Flex align="center" gap={12}>
{provider.isConnected ? (
<VStack align="start">
})
: t(
"Connect {{ authProvider }} to allow members to sign in",
{
authProvider: provider.displayName,
}
)
}
border={!showGroupSync}
>
<Flex align="center" gap={12}>
{provider.isConnected ? (
<VStack align="start">
<Button
icon={
provider.isEnabled ? (
<ConnectedIcon />
) : (
<ConnectedIcon color={theme.textSecondary} />
)
}
onClick={() =>
!provider.isEnabled
? handleToggleProvider(provider, true)
: handleRemoveProvider(provider)
}
neutral
>
{provider.isEnabled ? t("Connected") : t("Disabled")}
</Button>
<Text type="tertiary" size="small">
{provider.providerId}
</Text>
</VStack>
) : (
<Button
icon={
provider.isEnabled ? (
<ConnectedIcon />
) : (
<ConnectedIcon color={theme.textSecondary} />
)
}
onClick={() =>
!provider.isEnabled
? handleToggleProvider(provider, true)
: handleRemoveProvider(provider)
}
onClick={() => handleConnectProvider(provider.name)}
neutral
>
{provider.isEnabled ? t("Connected") : t("Disabled")}
{t("Connect")}
</Button>
<Text type="tertiary" size="small">
{provider.providerId}
</Text>
</VStack>
) : (
<Button
onClick={() => handleConnectProvider(provider.name)}
neutral
>
{t("Connect")}
</Button>
)}
</Flex>
</SettingRow>
{showGroupSync && (
<SettingRow
label={t("Group sync")}
name={`groupSync-${provider.name}`}
description={
provider.groupSyncRequiresSetup &&
!provider.settings?.groupSyncEnabled
? t(
"An administrator of {{ authProvider }} must approve group access for this workspace",
{ authProvider: provider.displayName }
)
: t(
"Sync group memberships from {{ authProvider }} on each sign-in",
{ authProvider: provider.displayName }
)
}
border={
!(
provider.settings?.groupSyncEnabled &&
provider.groupSyncUsesClaim
)
}
>
{provider.groupSyncRequiresSetup &&
!provider.settings?.groupSyncEnabled ? (
<Button
onClick={() => handleToggleGroupSync(provider, true)}
neutral
>
{t("Set up group sync")}
</Button>
) : (
<Switch
id={`groupSync-${provider.name}`}
checked={provider.settings?.groupSyncEnabled ?? false}
onChange={(checked) =>
handleToggleGroupSync(provider, checked)
}
/>
)}
</SettingRow>
)}
{showGroupSync &&
provider.groupSyncUsesClaim &&
provider.settings?.groupSyncEnabled && (
<SettingRow
label={t("Group claim")}
name={`groupClaim-${provider.name}`}
description={t(
"The claim in the provider response that contains group names (e.g. groups, roles)"
)}
border={false}
</Flex>
</SettingRow>
{showGroupSync && (
<SettingRow
label={t("Group sync")}
name={`groupSync-${provider.name}`}
description={
provider.groupSyncRequiresSetup &&
!provider.settings?.groupSyncEnabled
? t(
"An administrator of {{ authProvider }} must approve group access for this workspace",
{ authProvider: provider.displayName }
)
: t(
"Sync group memberships from {{ authProvider }} on each sign-in",
{ authProvider: provider.displayName }
)
}
border={
!(
provider.settings?.groupSyncEnabled &&
provider.groupSyncUsesClaim
)
}
>
<Input
id={`groupClaim-${provider.name}`}
defaultValue={provider.settings?.groupClaim ?? "groups"}
placeholder="groups"
onBlur={(ev: React.FocusEvent<HTMLInputElement>) => {
const value = ev.target.value.trim();
if (value !== (provider.settings?.groupClaim ?? "")) {
void handleGroupClaimChange(provider, value);
{provider.groupSyncRequiresSetup &&
!provider.settings?.groupSyncEnabled ? (
<Button
onClick={() => handleToggleGroupSync(provider, true)}
neutral
>
{t("Set up group sync")}
</Button>
) : (
<Switch
id={`groupSync-${provider.name}`}
checked={provider.settings?.groupSyncEnabled ?? false}
onChange={(checked) =>
handleToggleGroupSync(provider, checked)
}
}}
/>
/>
)}
</SettingRow>
)}
</React.Fragment>
);
})}
<SettingRow
label={
<Flex gap={8} align="center">
<EmailIcon /> {t("Email")}
</Flex>
}
name="guestSignin"
description={
env.EMAIL_ENABLED
? t("Allow members to sign in using their email address")
: t("The server must have SMTP configured to enable this setting")
}
border={false}
>
<Switch
id="guestSignin"
checked={team.guestSignin}
onChange={handleGuestSigninChange}
disabled={!env.EMAIL_ENABLED}
/>
</SettingRow>
{showGroupSync &&
provider.groupSyncUsesClaim &&
provider.settings?.groupSyncEnabled && (
<SettingRow
label={t("Group claim")}
name={`groupClaim-${provider.name}`}
description={t(
"The claim in the provider response that contains group names (e.g. groups, roles)"
)}
border={false}
>
<Input
id={`groupClaim-${provider.name}`}
defaultValue={provider.settings?.groupClaim ?? "groups"}
placeholder="groups"
onBlur={(ev: React.FocusEvent<HTMLInputElement>) => {
const value = ev.target.value.trim();
if (value !== (provider.settings?.groupClaim ?? "")) {
void handleGroupClaimChange(provider, value);
}
}}
/>
</SettingRow>
)}
</React.Fragment>
);
})}
<SettingRow
label={
<Flex gap={8} align="center">
<EmailIcon /> {t("Email")}
</Flex>
}
name="guestSignin"
description={
env.EMAIL_ENABLED
? t("Allow members to sign in using their email address")
: t("The server must have SMTP configured to enable this setting")
}
>
<Switch
id="guestSignin"
checked={team.guestSignin}
onChange={handleGuestSigninChange}
disabled={!env.EMAIL_ENABLED}
/>
</SettingRow>
<SettingRow
label={
<Flex gap={8} align="center">
<PadlockIcon /> {t("Passkeys")}
</Flex>
}
name="passkeysEnabled"
description={t("Allow members to sign in with a WebAuthn passkey")}
>
<Switch
id="passkeysEnabled"
checked={team.passkeysEnabled}
onChange={async (checked) => {
try {
await team.save({ passkeysEnabled: checked });
toast.success(t("Settings saved"));
} catch (err) {
toast.error(errToString(err));
}
}}
/>
</SettingRow>
<SettingRow
label={
<Flex gap={8} align="center">
<PadlockIcon /> {t("Passkeys")}
</Flex>
}
name="passkeysEnabled"
description={t("Allow members to sign in with a WebAuthn passkey")}
>
<Switch
id="passkeysEnabled"
checked={team.passkeysEnabled}
onChange={async (checked) => {
try {
await team.save({ passkeysEnabled: checked });
toast.success(t("Settings saved"));
} catch (err) {
toast.error(errToString(err));
}
}}
/>
</SettingRow>
</SettingsSection>
<Heading as="h2">{t("Restrictions")}</Heading>
<DomainManagement onSuccess={showSuccessMessage} />
<SettingsSection title={t("Restrictions")}>
<DomainManagement onSuccess={showSuccessMessage} />
</SettingsSection>
</Scene>
);
}
+337 -251
View File
@@ -1,18 +1,19 @@
import { isHexColor } from "class-validator";
import { pickBy } from "es-toolkit/compat";
import { debounce, pickBy } from "es-toolkit/compat";
import { observer } from "mobx-react";
import { TeamIcon } from "outline-icons";
import { useRef, useState } from "react";
import { useState } from "react";
import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import { toast } from "sonner";
import { ThemeProvider } from "styled-components";
import { errToString } from "@shared/utils/error";
import { buildDarkTheme, buildLightTheme } from "@shared/styles/theme";
import type { CustomTheme } from "@shared/types";
import type { CustomTheme, TeamPreferences } from "@shared/types";
import { TOCPosition, TeamPreference, UserPreference } from "@shared/types";
import { getBaseDomain } from "@shared/utils/domains";
import { TeamValidation } from "@shared/validations";
import { AvatarVariant } from "~/components/Avatar/Avatar";
import Button from "~/components/Button";
import ButtonLink from "~/components/ButtonLink";
import DefaultCollectionInputSelect from "~/components/DefaultCollectionInputSelect";
@@ -27,13 +28,18 @@ import useCurrentTeam from "~/hooks/useCurrentTeam";
import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import type Team from "~/models/Team";
import isCloudHosted from "~/utils/isCloudHosted";
import TeamDelete from "../TeamDelete";
import { ActionRow } from "./components/ActionRow";
import ImageInput from "./components/ImageInput";
import SettingRow from "./components/SettingRow";
import { SettingsSection } from "./components/SettingsSection";
import { ThemeColorInputs } from "./components/ThemeColorInputs";
type TeamUpdate = Partial<
Pick<Team, "name" | "description" | "subdomain" | "defaultCollectionId">
> & { preferences?: TeamPreferences };
function Details() {
const { dialogs, ui } = useStores();
const { t } = useTranslation();
@@ -41,7 +47,6 @@ function Details() {
const user = useCurrentUser();
const can = usePolicy(team);
const form = useRef<HTMLFormElement>(null);
const [accent, setAccent] = useState<null | undefined | string>(
team.preferences?.customTheme?.accent
);
@@ -51,12 +56,6 @@ function Details() {
const [name, setName] = useState(team.name);
const [description, setDescription] = useState(team.description || "");
const [subdomain, setSubdomain] = useState(team.subdomain);
const [publicBranding, setPublicBranding] = useState(
team.preferences?.publicBranding
);
const [defaultCollectionId, setDefaultCollectionId] = useState<string | null>(
team.defaultCollectionId
);
const customTheme: Partial<CustomTheme> = React.useMemo(
() =>
@@ -70,10 +69,6 @@ function Details() {
[accent, accentText]
);
const [tocPosition, setTocPosition] = useState(
team.getPreference(TeamPreference.TocPosition) as TOCPosition
);
const tocPositionOptions: Option[] = React.useMemo(
() =>
[
@@ -91,47 +86,103 @@ function Details() {
[t]
);
const handleTocPositionChange = React.useCallback((position: string) => {
setTocPosition(position as TOCPosition);
}, []);
const handleSubmit = React.useCallback(
async (event?: React.SyntheticEvent) => {
if (event) {
event.preventDefault();
}
try {
await team.save({
name,
description,
subdomain,
defaultCollectionId,
preferences: {
...team.preferences,
publicBranding,
customTheme,
tocPosition,
},
});
const showSuccessMessage = React.useMemo(
() =>
debounce(() => {
toast.success(t("Settings saved"));
}, 250),
[t]
);
const saveData = React.useCallback(
async (data: TeamUpdate) => {
try {
await team.save(data);
showSuccessMessage();
return true;
} catch (err) {
toast.error(errToString(err));
return false;
}
},
[
tocPosition,
team,
name,
description,
subdomain,
defaultCollectionId,
publicBranding,
customTheme,
t,
]
[team, showSuccessMessage]
);
const savePreference = React.useCallback(
<T extends TeamPreference>(key: T, value: TeamPreferences[T]) =>
saveData({ preferences: { [key]: value } }),
[saveData]
);
const saveTheme = React.useMemo(
() =>
debounce((theme: Partial<CustomTheme>) => {
void savePreference(TeamPreference.CustomTheme, theme);
}, 500),
[savePreference]
);
// Save a pending theme change when the user leaves the page.
React.useEffect(() => () => saveTheme.flush(), [saveTheme]);
const handleThemeChange = React.useCallback(
(
nextAccent: string | null | undefined,
nextText: string | null | undefined
) => {
// Wait until every entered color is complete or empty before saving.
const isReady = (value: string | null | undefined) =>
!value || value === "#" || isHexColor(value);
if (!isReady(nextAccent) || !isReady(nextText)) {
return;
}
saveTheme(
pickBy({ accent: nextAccent, accentText: nextText }, isHexColor)
);
},
[saveTheme]
);
const handleAccentChange = React.useCallback(
(value: string) => {
setAccent(value);
handleThemeChange(value, accentText);
},
[accentText, handleThemeChange]
);
const handleAccentTextChange = React.useCallback(
(value: string) => {
setAccentText(value);
handleThemeChange(accent, value);
},
[accent, handleThemeChange]
);
const handleResetTheme = React.useCallback(() => {
setAccent(null);
setAccentText(null);
saveTheme.cancel();
void savePreference(TeamPreference.CustomTheme, {});
}, [saveTheme, savePreference]);
const handleSubmit = React.useCallback((ev: React.FormEvent) => {
ev.preventDefault();
}, []);
const handleKeyDown = React.useCallback((ev: React.KeyboardEvent) => {
// Text fields save on blur, so Enter saves the focused field.
if (
ev.key === "Enter" &&
!ev.nativeEvent.isComposing &&
ev.target instanceof HTMLInputElement &&
ev.currentTarget.contains(ev.target)
) {
ev.preventDefault();
ev.target.blur();
}
}, []);
const handleNameChange = React.useCallback(
(ev: React.ChangeEvent<HTMLInputElement>) => {
setName(ev.target.value);
@@ -139,6 +190,31 @@ function Details() {
[]
);
const handleNameBlur = React.useCallback(async () => {
if (name === team.name) {
return;
}
if (!name.trim() || !(await saveData({ name }))) {
setName(team.name);
}
}, [name, team, saveData]);
const handleDescriptionChange = React.useCallback(
(ev: React.ChangeEvent<HTMLInputElement>) => {
setDescription(ev.target.value);
},
[]
);
const handleDescriptionBlur = React.useCallback(async () => {
if (description === (team.description || "")) {
return;
}
if (!(await saveData({ description }))) {
setDescription(team.description || "");
}
}, [description, team, saveData]);
const handleSubdomainChange = React.useCallback(
(ev: React.ChangeEvent<HTMLInputElement>) => {
setSubdomain(ev.target.value.toLowerCase());
@@ -146,6 +222,33 @@ function Details() {
[]
);
const handleSubdomainBlur = React.useCallback(async () => {
if (subdomain === team.subdomain) {
return;
}
if (!(await saveData({ subdomain }))) {
setSubdomain(team.subdomain);
}
}, [subdomain, team, saveData]);
const handlePublicBrandingChange = React.useCallback(
(checked: boolean) =>
savePreference(TeamPreference.PublicBranding, checked),
[savePreference]
);
const handleTocPositionChange = React.useCallback(
(position: string) =>
savePreference(TeamPreference.TocPosition, position as TOCPosition),
[savePreference]
);
const handleSelectCollection = React.useCallback(
(value: string) =>
saveData({ defaultCollectionId: value === "home" ? null : value }),
[saveData]
);
const handleAvatarChange = async (avatarUrl: string | null) => {
await team.save({ avatarUrl });
toast.success(t("Logo updated"));
@@ -165,28 +268,25 @@ function Details() {
});
};
const onSelectCollection = React.useCallback((value: string) => {
const selectedValue = value === "home" ? null : value;
setDefaultCollectionId(selectedValue);
}, []);
const handleSeamlessEditChange = React.useCallback(
async (checked: boolean) => {
team.setPreference(TeamPreference.SeamlessEdit, !checked);
await team.save();
if (!(await savePreference(TeamPreference.SeamlessEdit, !checked))) {
return;
}
// Enabling separate editing also applies it to the current user.
if (checked) {
user.setPreference(UserPreference.SeamlessEdit, false);
await user.save();
try {
user.setPreference(UserPreference.SeamlessEdit, false);
await user.save();
} catch (err) {
toast.error(errToString(err));
}
}
toast.success(t("Settings saved"));
},
[team, user, t]
[savePreference, user]
);
const isValid = form.current?.checkValidity();
const newTheme = React.useMemo(
() =>
ui.resolvedTheme === "light"
@@ -206,206 +306,192 @@ function Details() {
</Trans>
</Text>
<form onSubmit={handleSubmit} ref={form}>
<Heading as="h2">{t("Appearance")}</Heading>
<SettingRow
label={t("Logo")}
name="avatarUrl"
description={t(
"The logo is displayed at the top left of the application."
)}
>
<ImageInput
alt={t("Workspace logo")}
onSuccess={handleAvatarChange}
onError={handleAvatarError}
model={team}
borderRadius={0}
/>
</SettingRow>
<SettingRow
label={t("Name")}
name="name"
description={t(
"The workspace name, usually the same as your company name."
)}
>
<Input
id="name"
autoComplete="organization"
value={name}
onChange={handleNameChange}
maxLength={TeamValidation.maxNameLength}
showCharacterCount
required
/>
</SettingRow>
<SettingRow
label={t("Description")}
name="description"
description={t("A short description of your workspace.")}
>
<Input
id="description"
value={description}
onChange={(ev: React.ChangeEvent<HTMLInputElement>) => {
setDescription(ev.target.value);
}}
maxLength={TeamValidation.maxDescriptionLength}
showCharacterCount
/>
</SettingRow>
<SettingRow
label={t("Theme")}
name="accent"
description={
<>
{t("Customize the interface look and feel.")}{" "}
{accent && (
<>
<ButtonLink
onClick={() => {
setAccent(null);
setAccentText(null);
}}
>
<form onSubmit={handleSubmit} onKeyDown={handleKeyDown}>
<SettingsSection title={t("Appearance")}>
<SettingRow
label={t("Logo")}
name="avatarUrl"
description={t(
"The logo is displayed at the top left of the application."
)}
>
<ImageInput
alt={t("Workspace logo")}
onSuccess={handleAvatarChange}
onError={handleAvatarError}
model={team}
borderRadius={0}
variant={AvatarVariant.Square}
/>
</SettingRow>
<SettingRow
label={t("Name")}
name="name"
description={t(
"The workspace name, usually the same as your company name."
)}
>
<Input
id="name"
autoComplete="organization"
value={name}
onChange={handleNameChange}
onBlur={handleNameBlur}
maxLength={TeamValidation.maxNameLength}
showCharacterCount
required
/>
</SettingRow>
<SettingRow
label={t("Description")}
name="description"
description={t("A short description of your workspace.")}
>
<Input
id="description"
value={description}
onChange={handleDescriptionChange}
onBlur={handleDescriptionBlur}
maxLength={TeamValidation.maxDescriptionLength}
showCharacterCount
/>
</SettingRow>
<SettingRow
label={t("Theme")}
name="accent"
description={
<>
{t("Customize the interface look and feel.")}{" "}
{accent && (
<ButtonLink onClick={handleResetTheme}>
{t("Reset theme")}
</ButtonLink>
</>
)}
</>
}
>
<ThemeColorInputs
accent={accent}
accentText={accentText}
onAccentChange={handleAccentChange}
onAccentTextChange={handleAccentTextChange}
/>
</SettingRow>
{(team.avatarUrl || team.description) && (
<SettingRow
name={TeamPreference.PublicBranding}
label={t("Public branding")}
description={t(
"Show your workspace logo, description, and branding on publicly shared pages."
)}
</>
}
>
<ThemeColorInputs
accent={accent}
accentText={accentText}
onAccentChange={setAccent}
onAccentTextChange={setAccentText}
/>
</SettingRow>
{(team.avatarUrl || team.description) && (
>
<Switch
id={TeamPreference.PublicBranding}
name={TeamPreference.PublicBranding}
checked={!!team.getPreference(TeamPreference.PublicBranding)}
onChange={handlePublicBrandingChange}
/>
</SettingRow>
)}
<SettingRow
name={TeamPreference.PublicBranding}
label={t("Public branding")}
label={t("Table of contents position")}
name="tocPosition"
description={t(
"Show your workspace logo, description, and branding on publicly shared pages."
"The side to display the table of contents in relation to the main content."
)}
>
<InputSelect
options={tocPositionOptions}
value={
team.getPreference(TeamPreference.TocPosition) || undefined
}
onChange={handleTocPositionChange}
label={t("Table of contents position")}
labelHidden
/>
</SettingRow>
</SettingsSection>
<SettingsSection title={t("Behavior")}>
<SettingRow
visible={isCloudHosted}
label={t("Subdomain")}
name="subdomain"
description={
subdomain ? (
<>
<Trans>Your workspace will be accessible at</Trans>{" "}
<strong>
{subdomain}.{getBaseDomain()}
</strong>
</>
) : (
t(
"Choose a subdomain to enable a login page just for your team."
)
)
}
>
<Input
id="subdomain"
value={subdomain || ""}
onChange={handleSubdomainChange}
onBlur={handleSubdomainBlur}
autoComplete="off"
minLength={TeamValidation.minSubdomainLength}
maxLength={
isCloudHosted
? TeamValidation.maxSubdomainLength
: TeamValidation.maxSubdomainSelfHostedLength
}
/>
</SettingRow>
<SettingRow
label={t("Start view")}
name="defaultCollectionId"
description={t(
"This is the screen that workspace members will first see when they sign in."
)}
>
<DefaultCollectionInputSelect
onSelectCollection={handleSelectCollection}
defaultCollectionId={team.defaultCollectionId}
/>
</SettingRow>
<SettingRow
name={TeamPreference.SeamlessEdit}
label={t("Separate editing")}
description={t(
"When enabled, documents have a separate editing mode by default instead of being always editable. This setting can be overridden by user preferences."
)}
>
<Switch
id={TeamPreference.PublicBranding}
name={TeamPreference.PublicBranding}
checked={publicBranding}
onChange={(checked: boolean) => setPublicBranding(checked)}
id={TeamPreference.SeamlessEdit}
name={TeamPreference.SeamlessEdit}
checked={!team.getPreference(TeamPreference.SeamlessEdit)}
onChange={handleSeamlessEditChange}
/>
</SettingRow>
)}
<SettingRow
border={false}
label={t("Table of contents position")}
name="tocPosition"
description={t(
"The side to display the table of contents in relation to the main content."
)}
>
<InputSelect
options={tocPositionOptions}
value={tocPosition}
onChange={handleTocPositionChange}
label={t("Table of contents position")}
labelHidden
/>
</SettingRow>
<Heading as="h2">{t("Behavior")}</Heading>
<SettingRow
visible={isCloudHosted}
label={t("Subdomain")}
name="subdomain"
description={
subdomain ? (
<>
<Trans>Your workspace will be accessible at</Trans>{" "}
<strong>
{subdomain}.{getBaseDomain()}
</strong>
</>
) : (
t(
"Choose a subdomain to enable a login page just for your team."
)
)
}
>
<Input
id="subdomain"
value={subdomain || ""}
onChange={handleSubdomainChange}
autoComplete="off"
minLength={TeamValidation.minSubdomainLength}
maxLength={
isCloudHosted
? TeamValidation.maxSubdomainLength
: TeamValidation.maxSubdomainSelfHostedLength
}
/>
</SettingRow>
<SettingRow
label={t("Start view")}
name="defaultCollectionId"
description={t(
"This is the screen that workspace members will first see when they sign in."
)}
>
<DefaultCollectionInputSelect
onSelectCollection={onSelectCollection}
defaultCollectionId={defaultCollectionId}
/>
</SettingRow>
<SettingRow
border={false}
name={TeamPreference.SeamlessEdit}
label={t("Separate editing")}
description={t(
"When enabled, documents have a separate editing mode by default instead of being always editable. This setting can be overridden by user preferences."
)}
>
<Switch
id={TeamPreference.SeamlessEdit}
name={TeamPreference.SeamlessEdit}
checked={!team.getPreference(TeamPreference.SeamlessEdit)}
onChange={handleSeamlessEditChange}
/>
</SettingRow>
<ActionRow>
<Button type="submit" disabled={team.isSaving || !isValid}>
{team.isSaving ? `${t("Saving")}…` : t("Save")}
</Button>
</ActionRow>
{can.delete && (
<>
<p>&nbsp;</p>
<Heading as="h2">{t("Danger")}</Heading>
<SettingRow
name="delete"
border={false}
label={t("Delete workspace")}
description={t(
"You can delete this entire workspace including collections, documents, and users."
)}
>
<span>
<Button onClick={showDeleteWorkspace} neutral>
{t("Delete workspace")}…
</Button>
</span>
</SettingRow>
</>
)}
</SettingsSection>
</form>
{can.delete && (
<SettingsSection title={t("Danger")} danger>
<SettingRow
name="delete"
label={t("Delete workspace")}
description={t(
"You can delete this entire workspace including collections, documents, and users."
)}
>
<span>
<Button onClick={showDeleteWorkspace} neutral>
{t("Delete workspace")}…
</Button>
</span>
</SettingRow>
</SettingsSection>
)}
</Scene>
</ThemeProvider>
);
+7 -5
View File
@@ -12,6 +12,7 @@ import Text from "~/components/Text";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import { IntegrationScene } from "./components/IntegrationScene";
import SettingRow from "./components/SettingRow";
import { SettingsSection } from "./components/SettingsSection";
import { HStack } from "~/components/primitives/HStack";
/** List of embed providers available for configuration. */
@@ -99,15 +100,16 @@ function Embeds() {
</SettingRow>
{team.documentEmbeds && (
<>
<Heading as="h2">{t("Providers")}</Heading>
<Text as="p" type="secondary">
<SettingsSection
title={t("Providers")}
description={
<Trans>
Enabled providers will appear in the editor slash menu and embed
automatically when a compatible link is pasted. Existing embeds in
documents will continue to display regardless of these settings.
</Trans>
</Text>
}
>
<SettingRow
name="allEmbeds"
label={t("All providers")}
@@ -148,7 +150,7 @@ function Embeds() {
</SettingRow>
);
})}
</>
</SettingsSection>
)}
</IntegrationScene>
);
+161 -161
View File
@@ -24,6 +24,7 @@ import useStores from "~/hooks/useStores";
import UserDelete from "../UserDelete";
import { AutoLaunchSetting } from "./components/AutoLaunchSetting";
import SettingRow from "./components/SettingRow";
import { SettingsSection } from "./components/SettingsSection";
function Preferences() {
const { t } = useTranslation();
@@ -181,173 +182,172 @@ function Preferences() {
<Trans>Manage settings that affect your personal experience.</Trans>
</Text>
<Heading as="h2">{t("Appearance")}</Heading>
<SettingRow
label={t("Language")}
name="language"
description={
<>
<Trans>
Choose the interface language. Community translations are accepted
through our{" "}
<a
href="https://translate.getoutline.com"
target="_blank"
rel="noreferrer"
>
translation portal
</a>
.
</Trans>
</>
}
>
<InputSelect
options={languageOptions}
value={user.language}
onChange={handleLanguageChange}
<SettingsSection title={t("Appearance")}>
<SettingRow
label={t("Language")}
labelHidden
/>
</SettingRow>
<SettingRow
name="theme"
label={t("Theme")}
description={t("Choose your preferred interface color scheme.")}
>
<InputSelect
options={themeOptions}
value={ui.theme}
onChange={handleThemeChange}
label={t("Theme")}
labelHidden
/>
</SettingRow>
<SettingRow
name={UserPreference.UseCursorPointer}
label={t("Use pointer cursor")}
description={t(
"Show a hand cursor when hovering over interactive elements."
)}
>
<Switch
id={UserPreference.UseCursorPointer}
name={UserPreference.UseCursorPointer}
checked={user.getPreference(UserPreference.UseCursorPointer)}
onChange={handleUseCursorPointerChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.CodeBlockLineNumers}
label={t("Show line numbers")}
description={t("Show line numbers on code blocks in documents.")}
>
<Switch
id={UserPreference.CodeBlockLineNumers}
name={UserPreference.CodeBlockLineNumers}
checked={user.getPreference(UserPreference.CodeBlockLineNumers)}
onChange={handleCodeBlockLineNumbersChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.CommentsInGutter}
label={t("Show comment marker")}
description={t(
"Display a marker beside lines in the editor that contain comments."
)}
>
<Switch
id={UserPreference.CommentsInGutter}
name={UserPreference.CommentsInGutter}
checked={user.getPreference(UserPreference.CommentsInGutter)}
onChange={handleCommentsInGutterChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.ShowDocumentStats}
label={t("Show editing stats")}
description={t(
"Display live word, character, and paragraph counts while editing."
)}
border={false}
>
<Switch
id={UserPreference.ShowDocumentStats}
name={UserPreference.ShowDocumentStats}
checked={user.getPreference(UserPreference.ShowDocumentStats)}
onChange={handleShowDocumentStatsChange}
/>
</SettingRow>
<Heading as="h2">{t("Behavior")}</Heading>
<SettingRow
name={UserPreference.SeamlessEdit}
label={t("Separate editing")}
description={t(
`When enabled, documents have a separate editing mode. When disabled, documents are always editable when you have permission.`
)}
>
<Switch
id={UserPreference.SeamlessEdit}
name={UserPreference.SeamlessEdit}
checked={
!user.getPreference(
UserPreference.SeamlessEdit,
team.getPreference(TeamPreference.SeamlessEdit)
)
name="language"
description={
<>
<Trans>
Choose the interface language. Community translations are
accepted through our{" "}
<a
href="https://translate.getoutline.com"
target="_blank"
rel="noreferrer"
>
translation portal
</a>
.
</Trans>
</>
}
onChange={handleSeamlessEditChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.RememberLastPath}
label={t("Remember previous location")}
description={t(
"Automatically return to the document you were last viewing when the app is reopened."
)}
>
<Switch
id={UserPreference.RememberLastPath}
>
<InputSelect
options={languageOptions}
value={user.language}
onChange={handleLanguageChange}
label={t("Language")}
labelHidden
/>
</SettingRow>
<SettingRow
name="theme"
label={t("Theme")}
description={t("Choose your preferred interface color scheme.")}
>
<InputSelect
options={themeOptions}
value={ui.theme}
onChange={handleThemeChange}
label={t("Theme")}
labelHidden
/>
</SettingRow>
<SettingRow
name={UserPreference.UseCursorPointer}
label={t("Use pointer cursor")}
description={t(
"Show a hand cursor when hovering over interactive elements."
)}
>
<Switch
id={UserPreference.UseCursorPointer}
name={UserPreference.UseCursorPointer}
checked={user.getPreference(UserPreference.UseCursorPointer)}
onChange={handleUseCursorPointerChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.CodeBlockLineNumers}
label={t("Show line numbers")}
description={t("Show line numbers on code blocks in documents.")}
>
<Switch
id={UserPreference.CodeBlockLineNumers}
name={UserPreference.CodeBlockLineNumers}
checked={user.getPreference(UserPreference.CodeBlockLineNumers)}
onChange={handleCodeBlockLineNumbersChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.CommentsInGutter}
label={t("Show comment marker")}
description={t(
"Display a marker beside lines in the editor that contain comments."
)}
>
<Switch
id={UserPreference.CommentsInGutter}
name={UserPreference.CommentsInGutter}
checked={user.getPreference(UserPreference.CommentsInGutter)}
onChange={handleCommentsInGutterChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.ShowDocumentStats}
label={t("Show editing stats")}
description={t(
"Display live word, character, and paragraph counts while editing."
)}
>
<Switch
id={UserPreference.ShowDocumentStats}
name={UserPreference.ShowDocumentStats}
checked={user.getPreference(UserPreference.ShowDocumentStats)}
onChange={handleShowDocumentStatsChange}
/>
</SettingRow>
</SettingsSection>
<SettingsSection title={t("Behavior")}>
<SettingRow
name={UserPreference.SeamlessEdit}
label={t("Separate editing")}
description={t(
`When enabled, documents have a separate editing mode. When disabled, documents are always editable when you have permission.`
)}
>
<Switch
id={UserPreference.SeamlessEdit}
name={UserPreference.SeamlessEdit}
checked={
!user.getPreference(
UserPreference.SeamlessEdit,
team.getPreference(TeamPreference.SeamlessEdit)
)
}
onChange={handleSeamlessEditChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.RememberLastPath}
checked={!!user.getPreference(UserPreference.RememberLastPath)}
onChange={handleRememberLastPathChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.EnableSmartText}
label={t("Smart text replacements")}
description={t(
"Auto-format text by replacing shortcuts with symbols, dashes, smart quotes, and other typographical elements."
)}
>
<Switch
id={UserPreference.EnableSmartText}
label={t("Remember previous location")}
description={t(
"Automatically return to the document you were last viewing when the app is reopened."
)}
>
<Switch
id={UserPreference.RememberLastPath}
name={UserPreference.RememberLastPath}
checked={!!user.getPreference(UserPreference.RememberLastPath)}
onChange={handleRememberLastPathChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.EnableSmartText}
checked={!!user.getPreference(UserPreference.EnableSmartText)}
onChange={handleEnableSmartTextChange}
/>
</SettingRow>
<AutoLaunchSetting />
<SettingRow
border={false}
name={UserPreference.NotificationBadge}
label={t("Notification badge")}
description={t(
"Choose how unread notifications are indicated on the app icon."
)}
>
<InputSelect
options={notificationBadgeOptions}
value={user.getPreference(UserPreference.NotificationBadge)}
onChange={handleNotificationBadgeChange}
label={t("Smart text replacements")}
description={t(
"Auto-format text by replacing shortcuts with symbols, dashes, smart quotes, and other typographical elements."
)}
>
<Switch
id={UserPreference.EnableSmartText}
name={UserPreference.EnableSmartText}
checked={!!user.getPreference(UserPreference.EnableSmartText)}
onChange={handleEnableSmartTextChange}
/>
</SettingRow>
<AutoLaunchSetting />
<SettingRow
name={UserPreference.NotificationBadge}
label={t("Notification badge")}
labelHidden
/>
</SettingRow>
description={t(
"Choose how unread notifications are indicated on the app icon."
)}
>
<InputSelect
options={notificationBadgeOptions}
value={user.getPreference(UserPreference.NotificationBadge)}
onChange={handleNotificationBadgeChange}
label={t("Notification badge")}
labelHidden
/>
</SettingRow>
</SettingsSection>
{can.delete && (
<>
<Heading as="h2">{t("Danger")}</Heading>
<SettingsSection title={t("Danger")} danger>
<SettingRow
name="delete"
label={t("Delete account")}
@@ -361,7 +361,7 @@ function Preferences() {
</Button>
</span>
</SettingRow>
</>
</SettingsSection>
)}
</Scene>
);
+27 -11
View File
@@ -4,7 +4,6 @@ import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import { toast } from "sonner";
import { errToString } from "@shared/utils/error";
import Button from "~/components/Button";
import Heading from "~/components/Heading";
import Input from "~/components/Input";
import Scene from "~/components/Scene";
@@ -20,17 +19,40 @@ import SettingRow from "./components/SettingRow";
const Profile = () => {
const user = useCurrentUser();
const { dialogs } = useStores();
const form = React.useRef<HTMLFormElement>(null);
const [name, setName] = React.useState<string>(user.name);
const { t } = useTranslation();
const handleSubmit = async (ev: React.SyntheticEvent) => {
const handleSubmit = (ev: React.FormEvent) => {
ev.preventDefault();
};
const handleKeyDown = (ev: React.KeyboardEvent) => {
// The name saves on blur, so Enter saves it.
if (
ev.key === "Enter" &&
!ev.nativeEvent.isComposing &&
ev.target instanceof HTMLInputElement &&
ev.currentTarget.contains(ev.target)
) {
ev.preventDefault();
ev.target.blur();
}
};
const handleNameBlur = async () => {
if (name === user.name) {
return;
}
if (!name.trim()) {
setName(user.name);
return;
}
try {
await user.save({ name });
toast.success(t("Profile saved"));
} catch (err) {
setName(user.name);
toast.error(errToString(err));
}
};
@@ -57,9 +79,6 @@ const Profile = () => {
toast.error(error || t("Unable to upload new profile picture"));
};
const isValid = form.current?.checkValidity();
const { isSaving } = user;
return (
<Scene title={t("Profile")} icon={<ProfileIcon />}>
<Heading>{t("Profile")}</Heading>
@@ -67,7 +86,7 @@ const Profile = () => {
<Trans>Manage how you appear to other members of the workspace.</Trans>
</Text>
<form onSubmit={handleSubmit} ref={form}>
<form onSubmit={handleSubmit} onKeyDown={handleKeyDown}>
<SettingRow
label={t("Photo")}
name="avatarUrl"
@@ -93,6 +112,7 @@ const Profile = () => {
autoComplete="name"
value={name}
onChange={handleNameChange}
onBlur={handleNameBlur}
maxLength={UserValidation.maxNameLength}
showCharacterCount
required
@@ -109,10 +129,6 @@ const Profile = () => {
/>
</SettingRow>
)}
<Button type="submit" disabled={isSaving || !isValid}>
{isSaving ? `${t("Saving")}…` : t("Save")}
</Button>
</form>
</Scene>
);
+167 -163
View File
@@ -21,6 +21,7 @@ import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import isCloudHosted from "~/utils/isCloudHosted";
import SettingRow from "./components/SettingRow";
import { SettingsSection } from "./components/SettingsSection";
function Security() {
const { dialogs } = useStores();
@@ -280,186 +281,189 @@ function Security() {
</Trans>
</Text>
<Heading as="h2">{t("Invites")}</Heading>
<SettingRow
label={t("Allow users to send invites")}
name={TeamPreference.MembersCanInvite}
description={t("Allow editors to invite other people to the workspace")}
>
<Switch
id={TeamPreference.MembersCanInvite}
checked={team.getPreference(TeamPreference.MembersCanInvite)}
onChange={handleMembersCanInviteChange}
/>
</SettingRow>
{isCloudHosted && (
<SettingsSection title={t("Invites")}>
<SettingRow
label={t("Require invites")}
name="inviteRequired"
label={t("Allow users to send invites")}
name={TeamPreference.MembersCanInvite}
description={t(
"Require members to be invited to the workspace before they can create an account using SSO."
"Allow editors to invite other people to the workspace"
)}
>
<Switch
id="inviteRequired"
checked={data.inviteRequired}
onChange={handleInviteRequiredChange}
id={TeamPreference.MembersCanInvite}
checked={team.getPreference(TeamPreference.MembersCanInvite)}
onChange={handleMembersCanInviteChange}
/>
</SettingRow>
)}
{!data.inviteRequired && (
<SettingRow
label={t("Default role")}
name="defaultUserRole"
description={t(
"The default user role for new accounts. Changing this setting does not affect existing user accounts."
)}
border={false}
>
<InputSelect
value={data.defaultUserRole}
options={userRoleOptions}
onChange={handleDefaultRoleChange}
label={t("Default role")}
labelHidden
short
/>
</SettingRow>
)}
<Heading as="h2">{t("Behavior")}</Heading>
<SettingRow
label={t("Public document sharing")}
name="sharing"
description={t(
"When enabled, documents can be shared publicly on the internet by any member of the workspace"
)}
>
<Switch
id="sharing"
checked={data.sharing}
onChange={handleSharingChange}
/>
</SettingRow>
{can.setDefaultShareExpiry && (
<SettingRow
label={t("Default link expiration")}
name={TeamPreference.DefaultShareExpiryDays}
description={t(
"New public links will expire after this period. Existing links are not affected."
)}
>
<InputSelect
value={String(
team.getPreference(TeamPreference.DefaultShareExpiryDays)
{isCloudHosted && (
<SettingRow
label={t("Require invites")}
name="inviteRequired"
description={t(
"Require members to be invited to the workspace before they can create an account using SSO."
)}
options={defaultShareExpiryOptions}
onChange={handleDefaultShareExpiryChange}
>
<Switch
id="inviteRequired"
checked={data.inviteRequired}
onChange={handleInviteRequiredChange}
/>
</SettingRow>
)}
{!data.inviteRequired && (
<SettingRow
label={t("Default role")}
name="defaultUserRole"
description={t(
"The default user role for new accounts. Changing this setting does not affect existing user accounts."
)}
>
<InputSelect
value={data.defaultUserRole}
options={userRoleOptions}
onChange={handleDefaultRoleChange}
label={t("Default role")}
labelHidden
short
/>
</SettingRow>
)}
</SettingsSection>
<SettingsSection title={t("Behavior")}>
<SettingRow
label={t("Public document sharing")}
name="sharing"
description={t(
"When enabled, documents can be shared publicly on the internet by any member of the workspace"
)}
>
<Switch
id="sharing"
checked={data.sharing}
onChange={handleSharingChange}
/>
</SettingRow>
{can.setDefaultShareExpiry && (
<SettingRow
label={t("Default link expiration")}
name={TeamPreference.DefaultShareExpiryDays}
description={t(
"New public links will expire after this period. Existing links are not affected."
)}
>
<InputSelect
value={String(
team.getPreference(TeamPreference.DefaultShareExpiryDays)
)}
options={defaultShareExpiryOptions}
onChange={handleDefaultShareExpiryChange}
label={t("Default link expiration")}
labelHidden
short
/>
</SettingRow>
)}
<SettingRow
label={t("Viewer document exports")}
name={TeamPreference.ViewersCanExport}
description={t(
"When enabled, viewers can see download options for documents"
)}
>
<Switch
id={TeamPreference.ViewersCanExport}
checked={team.getPreference(TeamPreference.ViewersCanExport)}
onChange={handleViewersCanExportChange}
/>
</SettingRow>
<SettingRow
label={t("Users can delete account")}
name={TeamPreference.MembersCanDeleteAccount}
description={t(
"When enabled, users can delete their own account from the workspace"
)}
>
<Switch
id={TeamPreference.MembersCanDeleteAccount}
checked={team.getPreference(TeamPreference.MembersCanDeleteAccount)}
onChange={handleMembersCanDeleteAccountChange}
/>
</SettingRow>
<SettingRow
label={t("Email address visibility")}
name={TeamPreference.EmailDisplay}
description={t(
"Controls who can see user email addresses in the workspace"
)}
>
<InputSelect
value={team.getPreference(TeamPreference.EmailDisplay) as string}
options={emailDisplayOptions}
onChange={handleEmailDisplayChange}
label={t("Email address visibility")}
labelHidden
short
/>
</SettingRow>
)}
<SettingRow
label={t("Viewer document exports")}
name={TeamPreference.ViewersCanExport}
description={t(
"When enabled, viewers can see download options for documents"
)}
>
<Switch
id={TeamPreference.ViewersCanExport}
checked={team.getPreference(TeamPreference.ViewersCanExport)}
onChange={handleViewersCanExportChange}
/>
</SettingRow>
<SettingRow
label={t("Users can delete account")}
name={TeamPreference.MembersCanDeleteAccount}
description={t(
"When enabled, users can delete their own account from the workspace"
)}
>
<Switch
id={TeamPreference.MembersCanDeleteAccount}
checked={team.getPreference(TeamPreference.MembersCanDeleteAccount)}
onChange={handleMembersCanDeleteAccountChange}
/>
</SettingRow>
<SettingRow
label={t("Email address visibility")}
name={TeamPreference.EmailDisplay}
description={t(
"Controls who can see user email addresses in the workspace"
)}
>
<InputSelect
value={team.getPreference(TeamPreference.EmailDisplay) as string}
options={emailDisplayOptions}
onChange={handleEmailDisplayChange}
label={t("Email address visibility")}
labelHidden
short
/>
</SettingRow>
<SettingRow
label={t("Commenting")}
name={TeamPreference.Commenting}
description={t("Controls who can add comments to documents")}
>
<InputSelect
value={
team.getPreference(TeamPreference.Commenting) ||
CommentingAccess.Members
}
options={commentingOptions}
onChange={handleCommentingChange}
label={t("Commenting")}
labelHidden
short
/>
</SettingRow>
<SettingRow
label={t("Personal documents")}
name={TeamPreference.PersonalDocs}
description={t(
"Allow editors to create personal documents that are only visible to themselves and the people they share them with"
)}
>
<Switch
id={TeamPreference.PersonalDocs}
checked={team.getPreference(TeamPreference.PersonalDocs)}
onChange={handlePersonalDocsChange}
/>
</SettingRow>
<SettingRow
label={t("Collection creation")}
name="memberCollectionCreate"
description={t(
"Allow editors to create new collections within the workspace"
)}
>
<Switch
id="memberCollectionCreate"
checked={data.memberCollectionCreate}
onChange={handleMemberCollectionCreateChange}
/>
</SettingRow>
{isCloudHosted && (
<SettingRow
label={t("Workspace creation")}
name="memberTeamCreate"
description={t("Allow editors to create new workspaces")}
label={t("Commenting")}
name={TeamPreference.Commenting}
description={t("Controls who can add comments to documents")}
>
<Switch
id="memberTeamCreate"
checked={data.memberTeamCreate}
onChange={handleMemberTeamCreateChange}
<InputSelect
value={
team.getPreference(TeamPreference.Commenting) ||
CommentingAccess.Members
}
options={commentingOptions}
onChange={handleCommentingChange}
label={t("Commenting")}
labelHidden
short
/>
</SettingRow>
)}
<SettingRow
label={t("Personal documents")}
name={TeamPreference.PersonalDocs}
description={t(
"Allow editors to create personal documents that are only visible to themselves and the people they share them with"
)}
>
<Switch
id={TeamPreference.PersonalDocs}
checked={team.getPreference(TeamPreference.PersonalDocs)}
onChange={handlePersonalDocsChange}
/>
</SettingRow>
<SettingRow
label={t("Collection creation")}
name="memberCollectionCreate"
description={t(
"Allow editors to create new collections within the workspace"
)}
>
<Switch
id="memberCollectionCreate"
checked={data.memberCollectionCreate}
onChange={handleMemberCollectionCreateChange}
/>
</SettingRow>
{isCloudHosted && (
<SettingRow
label={t("Workspace creation")}
name="memberTeamCreate"
description={t("Allow editors to create new workspaces")}
>
<Switch
id="memberTeamCreate"
checked={data.memberTeamCreate}
onChange={handleMemberTeamCreateChange}
/>
</SettingRow>
)}
</SettingsSection>
</Scene>
);
}
+76 -19
View File
@@ -1,13 +1,19 @@
import { EditIcon } from "outline-icons";
import { observer } from "mobx-react";
import { EditIcon, ExportIcon, TrashIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { s } from "@shared/styles";
import type { IAvatar } from "~/components/Avatar";
import { Avatar, AvatarSize } from "~/components/Avatar";
import { AvatarVariant } from "~/components/Avatar/Avatar";
import Button from "~/components/Button";
import Flex from "~/components/Flex";
import type { Props as ImageUploadProps } from "./ImageUpload";
import NudeButton from "~/components/NudeButton";
import Tooltip from "~/components/Tooltip";
import type {
ImageUploadHandle,
Props as ImageUploadProps,
} from "./ImageUpload";
import ImageUpload from "./ImageUpload";
type Props = ImageUploadProps & {
@@ -15,26 +21,48 @@ type Props = ImageUploadProps & {
model: IAvatar;
/** Alt text for the avatar image. */
alt: string;
/** The shape of the avatar preview. Defaults to round. */
variant?: AvatarVariant;
/**
* Whether to render the inline "Remove" button when the model has an
* existing avatar. Defaults to true.
* Whether to render the change and remove buttons below the image. Hide
* them when the parent provides its own controls. Defaults to true.
*/
showRemoveOption?: boolean;
showActions?: boolean;
/** Handle to open the file picker from the parent. */
ref?: React.Ref<ImageUploadHandle>;
};
export default function ImageInput({
function ImageInput({
model,
onSuccess,
alt,
showRemoveOption = true,
variant = AvatarVariant.Round,
showActions = true,
ref,
...rest
}: Props) {
const { t } = useTranslation();
const uploadRef = React.useRef<ImageUploadHandle>(null);
React.useImperativeHandle(
ref,
() => ({ open: () => uploadRef.current?.open() }),
[]
);
const handleChange = React.useCallback(() => {
uploadRef.current?.open();
}, []);
const handleRemove = React.useCallback(() => {
void onSuccess(null);
}, [onSuccess]);
return (
<Flex gap={8} justify="space-between">
<ImageBox>
<Wrapper column align="center" gap={4}>
<ImageBox $variant={variant}>
<ImageUpload
ref={uploadRef}
onSuccess={onSuccess}
submitText={t("Crop image")}
{...rest}
@@ -42,33 +70,62 @@ export default function ImageInput({
<Avatar
model={model}
size={AvatarSize.Upload}
variant={AvatarVariant.Round}
variant={variant}
alt={alt}
/>
<Flex auto align="center" justify="center" className="upload">
<EditIcon />
<ExportIcon />
</Flex>
</ImageUpload>
</ImageBox>
{model.avatarUrl && showRemoveOption && (
<Button onClick={() => onSuccess(null)} neutral>
{t("Remove")}
</Button>
{showActions && (
<Actions gap={4} justify="center">
<Tooltip content={t("Change image")}>
<NudeButton aria-label={t("Change image")} onClick={handleChange}>
<EditIcon />
</NudeButton>
</Tooltip>
{model.avatarUrl && (
<Tooltip content={t("Remove image")}>
<NudeButton aria-label={t("Remove image")} onClick={handleRemove}>
<TrashIcon />
</NudeButton>
</Tooltip>
)}
</Actions>
)}
</Flex>
</Wrapper>
);
}
export default observer(ImageInput);
const Wrapper = styled(Flex)`
width: fit-content;
`;
const Actions = styled(Flex)`
color: ${s("textSecondary")};
button:hover,
button:focus-visible {
color: ${s("text")};
}
`;
const avatarStyles = `
width: ${AvatarSize.Upload}px;
height: ${AvatarSize.Upload}px;
`;
const ImageBox = styled(Flex)`
const ImageBox = styled(Flex)<{ $variant: AvatarVariant }>`
${avatarStyles};
position: relative;
font-size: 14px;
border-radius: 50%;
border-radius: ${(props) =>
props.$variant === AvatarVariant.Round
? "50%"
: `${AvatarSize.Upload / 8}px`};
box-shadow: 0 0 0 1px ${s("backgroundSecondary")};
background: ${s("background")};
overflow: hidden;
+12 -3
View File
@@ -26,13 +26,20 @@ export type Props = {
children?: React.ReactNode;
};
const ImageUpload: React.FC<Props> = ({
/** Imperative handle exposed by ImageUpload. */
export interface ImageUploadHandle {
/** Opens the file picker. */
open: () => void;
}
const ImageUpload = ({
onSuccess,
onError,
submitText,
borderRadius,
children,
}) => {
ref,
}: Props & { ref?: React.Ref<ImageUploadHandle> }) => {
const { dialogs } = useStores();
const { t } = useTranslation();
@@ -110,11 +117,13 @@ const ImageUpload: React.FC<Props> = ({
[t, dialogs, handleUpload, handleClose, onError, borderRadius, submitText]
);
const { getRootProps, getInputProps } = useDropzone({
const { getRootProps, getInputProps, open } = useDropzone({
accept: avatarAccept,
onDropAccepted,
});
React.useImperativeHandle(ref, () => ({ open }), [open]);
if (isCropping) {
return null; // onDropAccepted would have opened a modal for cropping the image.
}
+16 -5
View File
@@ -28,6 +28,18 @@ const Row = styled(Flex)<{ $border?: boolean; $compact?: boolean }>`
border-bottom: 0;
}
/* Center switches, unless the text column also holds a field. */
&:has(> :last-child > [role="switch"]):not(
:has(> :first-child :is(input, textarea))
) {
align-items: center;
}
/* A switch column is only as wide as the switch. */
&:has(> :last-child > [role="switch"]) > :last-child {
flex: 0 0 auto;
}
${breakpoint("mobile", "tablet")`
&:has([role="switch"]) {
gap: 16px;
@@ -73,11 +85,10 @@ const Column = styled.div`
align-self: flex-end;
}
${breakpoint("tablet")`
> * {
align-self: initial;
}
`}
/* Text fields and selects fill the column. */
> :has(input:not([type="file"]), textarea, [role="combobox"]) {
align-self: stretch;
}
}
${breakpoint("tablet")`
@@ -0,0 +1,74 @@
import { transparentize } from "polished";
import * as React from "react";
import styled, { css } from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import Text from "~/components/Text";
interface Props {
/** The section heading. */
title: React.ReactNode;
/** Optional text shown below the heading. */
description?: React.ReactNode;
/** Whether the section holds destructive actions. */
danger?: boolean;
/** The rows in the section, usually SettingRow components. */
children: React.ReactNode;
}
/**
* A titled group of setting rows on a settings screen.
*
* @param props the section props.
* @returns the section element.
*/
export function SettingsSection({
title,
description,
danger,
children,
}: Props) {
const titleId = React.useId();
return (
<Section aria-labelledby={titleId}>
<Title id={titleId}>{title}</Title>
{description && (
<Description as="p" type="secondary">
{description}
</Description>
)}
<Rows $danger={danger}>{children}</Rows>
</Section>
);
}
const Section = styled.section`
margin-top: 32px;
${breakpoint("tablet")`
margin-top: 48px;
`}
`;
const Title = styled.h2`
font-size: 20px;
font-weight: 600;
margin: 0;
`;
const Description = styled(Text)`
margin: 4px 0 8px;
`;
const Rows = styled.div<{ $danger?: boolean }>`
${(props) =>
props.$danger &&
css`
/* Inset by the shadow width so the shadow aligns with the content. */
margin: 24px 8px 8px;
padding: 0 16px;
border: 1px solid ${transparentize(0.6, props.theme.danger)};
border-radius: 8px;
box-shadow: 0 0 0 8px ${transparentize(0.9, props.theme.danger)};
`}
`;
+18 -19
View File
@@ -42,7 +42,7 @@
"url": "https://github.com/sponsors/outline"
},
"engines": {
"node": ">=22.23.4 <23 || >=24.22.1 <25 || >=26.12.1 <27"
"node": ">=22.23.5 <23 || >=24.22.3 <25 || >=26.13.1 <27"
},
"repository": {
"type": "git",
@@ -52,12 +52,12 @@
"> 0.25%, not dead"
],
"dependencies": {
"@aws-sdk/client-s3": "^3.1159.0",
"@aws-sdk/cloudfront-signer": "^3.1157.0",
"@aws-sdk/lib-storage": "^3.1159.0",
"@aws-sdk/s3-presigned-post": "^3.1159.0",
"@aws-sdk/s3-request-presigner": "^3.1159.0",
"@aws-sdk/signature-v4-crt": "^3.1159.0",
"@aws-sdk/client-s3": "^3.1162.0",
"@aws-sdk/cloudfront-signer": "^3.1161.0",
"@aws-sdk/lib-storage": "^3.1162.0",
"@aws-sdk/s3-presigned-post": "^3.1162.0",
"@aws-sdk/s3-request-presigner": "^3.1162.0",
"@aws-sdk/signature-v4-crt": "^3.1162.0",
"@benrbray/prosemirror-math": "^0.2.2",
"@bull-board/api": "^6.21.3",
"@bull-board/koa": "^6.21.3",
@@ -76,7 +76,6 @@
"@fortawesome/free-solid-svg-icons": "^7.3.1",
"@fortawesome/react-fontawesome": "^3.5.0",
"@getoutline/react-roving-tabindex": "^3.2.4",
"@gitbeaker/rest": "^43.8.0",
"@hocuspocus/extension-redis": "1.1.3",
"@hocuspocus/extension-throttle": "1.1.3",
"@hocuspocus/provider": "1.1.3",
@@ -113,7 +112,7 @@
"@simplewebauthn/server": "^13.3.3",
"@socket.io/redis-adapter": "^8.3.0",
"@tanstack/react-table": "^8.21.3",
"@tanstack/react-virtual": "^3.14.23",
"@tanstack/react-virtual": "^3.14.26",
"@types/mailparser": "^3.9.0",
"@vitejs/plugin-react": "^6.1.2",
"async-sema": "^3.1.1",
@@ -151,8 +150,8 @@
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"i18next": "^22.5.1",
"i18next-fs-backend": "^2.6.9",
"i18next-http-backend": "^4.0.9",
"i18next-fs-backend": "^2.6.10",
"i18next-http-backend": "^4.0.10",
"invariant": "^2.2.4",
"ioredis": "^5.11.1",
"ipaddr.js": "^2.5.0",
@@ -183,7 +182,7 @@
"mobx-utils": "^6.1.1",
"natural-sort": "^1.0.0",
"node-fetch": "2.7.0",
"nodemailer": "^10.0.9",
"nodemailer": "^10.3.1",
"octokit": "^5.0.5",
"outline-icons": "^4.6.0",
"pako": "^3.0.2",
@@ -217,11 +216,11 @@
"proxy-from-env": "^1.1.0",
"query-string": "^9.5.0",
"rate-limiter-flexible": "^11.2.3",
"react": "^19.3.0",
"react": "^19.3.1",
"react-avatar-editor": "^15.1.0",
"react-colorful": "^5.8.0",
"react-colorful": "^5.8.1",
"react-day-picker": "^8.10.2",
"react-dom": "^19.3.0",
"react-dom": "^19.3.1",
"react-dropzone": "^20.1.4",
"react-hook-form": "^7.85.0",
"react-i18next": "^12.3.1",
@@ -230,7 +229,7 @@
"react-remove-scroll": "^2.7.2",
"react-router-dom": "^5.3.4",
"react-use-measure": "^2.1.7",
"react-window": "^2.3.4",
"react-window": "^2.5.3",
"react-zoom-pan-pinch": "^3.7.0",
"reflect-metadata": "^0.2.2",
"refractor": "^5.0.0",
@@ -272,7 +271,7 @@
"@faker-js/faker": "^10.6.0",
"@relative-ci/agent": "^4.3.1",
"@swc/cli": "^0.8.2",
"@swc/core": "^1.16.20",
"@swc/core": "^1.16.22",
"@types/cookie": "0.6.0",
"@types/diff": "^5.0.9",
"@types/escape-html": "^1.0.4",
@@ -321,7 +320,7 @@
"browserslist-to-esbuild": "^1.2.0",
"concurrently": "^8.2.2",
"discord-api-types": "^0.38.48",
"fake-indexeddb": "^6.2.6",
"fake-indexeddb": "^6.2.8",
"husky": "^9.1.7",
"i18next-parser": "^9.4.0",
"ioredis-mock": "^8.13.1",
@@ -329,7 +328,7 @@
"msw": "^2.15.0",
"oxfmt": "0.73.0",
"oxlint": "1.90.0",
"oxlint-tsgolint": "7.0.2005",
"oxlint-tsgolint": "7.0.2006",
"react-refresh": "^0.19.0",
"rimraf": "^6.1.3",
"rollup-plugin-webpack-stats": "^3.1.3",
+3 -3
View File
@@ -131,7 +131,7 @@ export class GitHubIssueProvider extends BaseIssueProvider {
required: true,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: Integration },
});
const authentication = integration.authentication;
@@ -172,7 +172,7 @@ export class GitHubIssueProvider extends BaseIssueProvider {
"settings.github.installation.id": installationId,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
if (!integration) {
@@ -241,7 +241,7 @@ export class GitHubIssueProvider extends BaseIssueProvider {
"settings.github.installation.id": installationId,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
if (!integration) {
+5 -5
View File
@@ -142,7 +142,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
const integration = (await Integration.findOne({
where,
replacements: { jsonCondition },
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
})) as Integration<IntegrationType.Embed>;
@@ -213,7 +213,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
const integrations = (await Integration.findAll({
where: whereCondition,
replacements,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
})) as Integration<IntegrationType.Embed>[];
@@ -257,7 +257,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
replacements: {
projectJson: JSON.stringify([{ id: String(payload.project_id) }]),
},
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
});
@@ -303,7 +303,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
...(teamId ? { teamId } : {}),
"settings.gitlab.installation.account.id": payload.user_id,
},
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
})) as Integration<IntegrationType.Embed>;
@@ -354,7 +354,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
replacements: {
projectJson: JSON.stringify([{ id: String(payload.project_id) }]),
},
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
});
+1 -1
View File
@@ -269,7 +269,7 @@ router.get(
account: {
id: userInfo.id,
name: userInfo.username,
avatarUrl: userInfo.avatar_url,
avatarUrl: userInfo.avatar_url ?? "",
},
},
},
+238
View File
@@ -0,0 +1,238 @@
import { randomUUID } from "node:crypto";
import { addHours, subHours } from "date-fns";
import { http, HttpResponse } from "msw";
import { IntegrationService, IntegrationType } from "@shared/types";
import { Integration, IntegrationAuthentication } from "@server/models";
import { buildUser } from "@server/test/factories";
import { server } from "@server/test/msw";
import { GitLab } from "./gitlab";
const author = { id: 7, username: "octo", avatar_url: "https://a.test/a.png" };
const buildBaseUrl = () => `https://${randomUUID()}.example.com`;
async function buildGitLabIntegration({
teamId,
userId,
url,
expiresAt = addHours(new Date(), 1),
}: {
teamId: string;
userId: string;
url: string;
expiresAt?: Date;
}) {
const authentication = await IntegrationAuthentication.create({
service: IntegrationService.GitLab,
userId,
teamId,
clientId: "client-id",
clientSecret: "client-secret",
token: "token",
refreshToken: "refresh",
expiresAt,
});
const integration = await Integration.create({
service: IntegrationService.GitLab,
type: IntegrationType.Embed,
userId,
teamId,
authenticationId: authentication.id,
settings: { gitlab: { url } },
});
return { integration, authentication };
}
describe("GitLab", () => {
describe("getIssue", () => {
it("should request the issue with an encoded project path", async () => {
const customUrl = buildBaseUrl();
let requestUrl: URL | undefined;
let authorization: string | null = null;
server.use(
http.get(
`${customUrl}/api/v4/projects/:project/issues`,
({ request }) => {
requestUrl = new URL(request.url);
authorization = request.headers.get("authorization");
return HttpResponse.json([
{
iid: 12,
title: "Fix it",
description: "Details",
web_url: `${customUrl}/group/repo/-/issues/12`,
state: "opened",
author,
labels: [{ name: "bug", color: "#ff0000" }],
created_at: "2026-01-01T00:00:00Z",
},
]);
}
)
);
const issue = await GitLab.getIssue({
accessToken: "token",
customUrl,
path: "group/repo",
id: 12,
});
expect(issue.title).toEqual("Fix it");
expect(requestUrl?.pathname).toEqual(
"/api/v4/projects/group%2Frepo/issues"
);
expect(requestUrl?.searchParams.get("iids[]")).toEqual("12");
expect(authorization).toEqual("Bearer token");
});
});
describe("getProjects", () => {
it("should follow pagination", async () => {
const user = await buildUser();
const pages: (string | null)[] = [];
server.use(
http.get("https://gitlab.com/api/v4/projects", ({ request }) => {
const page = new URL(request.url).searchParams.get("page");
pages.push(page);
return HttpResponse.json(
[
{
id: Number(page),
name: `project-${page}`,
namespace: { id: 1, full_path: "group" },
},
],
{ headers: { "x-next-page": page === "1" ? "2" : "" } }
);
})
);
const projects = await GitLab.getProjects({
accessToken: "token",
teamId: user.teamId,
});
expect(pages).toEqual(["1", "2"]);
expect(projects.map((project) => project.name)).toEqual([
"project-1",
"project-2",
]);
});
});
describe("unfurl", () => {
it("should refresh an expired token and use the new token", async () => {
const user = await buildUser();
const customUrl = buildBaseUrl();
const { authentication } = await buildGitLabIntegration({
teamId: user.teamId,
userId: user.id,
url: customUrl,
expiresAt: subHours(new Date(), 1),
});
let tokenRequest: Record<string, string> | undefined;
let authorization: string | null = null;
server.use(
http.post(`${customUrl}/oauth/token`, async ({ request }) => {
tokenRequest = (await request.json()) as Record<string, string>;
return HttpResponse.json({
access_token: "new-token",
token_type: "Bearer",
expires_in: 7200,
refresh_token: "new-refresh",
scope: "read_api read_user",
created_at: 0,
});
}),
http.get(
`${customUrl}/api/v4/projects/:project/merge_requests/5`,
({ request }) => {
authorization = request.headers.get("authorization");
return HttpResponse.json({
iid: 5,
title: "Change",
web_url: `${customUrl}/group/repo/-/merge_requests/5`,
state: "opened",
author,
created_at: "2026-01-01T00:00:00Z",
});
}
)
);
const result = await GitLab.unfurl(
`${customUrl}/group/repo/-/merge_requests/5`,
user
);
expect(result).toMatchObject({ title: "Change" });
expect(tokenRequest).toMatchObject({
grant_type: "refresh_token",
refresh_token: "refresh",
client_id: "client-id",
client_secret: "client-secret",
});
expect(authorization).toEqual("Bearer new-token");
await authentication.reload();
expect(authentication.token).toEqual("new-token");
expect(authentication.refreshToken).toEqual("new-refresh");
});
it("should unfurl a project without progress when statistics fail", async () => {
const user = await buildUser();
const customUrl = buildBaseUrl();
await buildGitLabIntegration({
teamId: user.teamId,
userId: user.id,
url: customUrl,
});
server.use(
http.get(`${customUrl}/api/v4/projects/:project`, () =>
HttpResponse.json({
id: 1,
name: "repo",
web_url: `${customUrl}/group/repo`,
visibility: "public",
created_at: "2026-01-01T00:00:00Z",
})
),
http.get(
`${customUrl}/api/v4/projects/:project/issues_statistics`,
() => HttpResponse.json({}, { status: 500 })
)
);
const result = await GitLab.unfurl(`${customUrl}/group/repo`, user);
expect(result).toMatchObject({ name: "repo", progress: undefined });
});
it("should not return the response body of a failed request", async () => {
const user = await buildUser();
const customUrl = buildBaseUrl();
await buildGitLabIntegration({
teamId: user.teamId,
userId: user.id,
url: customUrl,
});
server.use(
http.get(`${customUrl}/api/v4/projects/:project/merge_requests/5`, () =>
HttpResponse.json({ message: "secret" }, { status: 500 })
)
);
const result = await GitLab.unfurl(
`${customUrl}/group/repo/-/merge_requests/5`,
user
);
expect(result).toEqual({
error:
"Error while requesting /projects/group%2Frepo/merge_requests/5 from GitLab; status: 500",
});
});
});
});
+291 -177
View File
@@ -1,12 +1,3 @@
import { Gitlab } from "@gitbeaker/rest";
import type {
EpicSchema,
IssueSchemaWithExpandedLabels,
MergeRequestSchema,
ProjectSchema,
SimpleLabelSchema,
StatisticsSchema,
} from "@gitbeaker/rest";
import z from "zod";
import {
type IntegrationType,
@@ -14,6 +5,7 @@ import {
UnfurlResourceType,
} from "@shared/types";
import { toError, errToString } from "@shared/utils/error";
import { Second } from "@shared/utils/time";
import Logger from "@server/logging/Logger";
import type { User } from "@server/models";
import { Integration, IntegrationAuthentication } from "@server/models";
@@ -22,8 +14,7 @@ import type {
UnfurlProject,
UnfurlSignature,
} from "@server/types";
import fetch from "@server/utils/fetch";
import { validateUrlNotPrivate } from "@server/utils/url";
import fetch, { type Headers } from "@server/utils/fetch";
import { GitLabUtils } from "../shared/GitLabUtils";
import env from "./env";
@@ -36,10 +27,97 @@ const AccessTokenResponseSchema = z.object({
created_at: z.number(),
});
export class GitLab {
private static clientSecret = env.GITLAB_CLIENT_SECRET;
private static clientId = env.GITLAB_CLIENT_ID;
const UserSchema = z.object({
id: z.number(),
username: z.string(),
avatar_url: z.string().nullish(),
});
const LabelSchema = z.object({
name: z.string(),
color: z.string(),
});
const IssueSchema = z.object({
iid: z.number(),
title: z.string(),
description: z.string().nullish(),
web_url: z.string(),
state: z.string(),
author: UserSchema.nullish(),
labels: z.array(LabelSchema),
created_at: z.string(),
});
// Epics are returned without label color details.
const EpicSchema = IssueSchema.extend({
labels: z.array(z.string()),
});
const MergeRequestSchema = z.object({
iid: z.number(),
title: z.string(),
description: z.string().nullish(),
web_url: z.string(),
state: z.string(),
author: UserSchema,
draft: z.boolean().nullish(),
merged_at: z.string().nullish(),
created_at: z.string(),
});
const NamespaceSchema = z.object({
id: z.number(),
full_path: z.string(),
});
const SimpleProjectSchema = z.object({
id: z.number(),
name: z.string(),
namespace: NamespaceSchema,
});
const ProjectSchema = z.object({
id: z.number(),
name: z.string(),
description: z.string().nullish(),
web_url: z.string(),
avatar_url: z.string().nullish(),
visibility: z.string().nullish(),
owner: z
.object({ name: z.string(), avatar_url: z.string().nullish() })
.nullish(),
topics: z.array(z.string()).nullish(),
created_at: z.string(),
});
const IssueStatisticsSchema = z.object({
statistics: z.object({
counts: z.object({
opened: z.number(),
closed: z.number(),
}),
}),
});
type Issue = z.infer<typeof IssueSchema>;
type Epic = z.infer<typeof EpicSchema>;
type MergeRequest = z.infer<typeof MergeRequestSchema>;
type SimpleProject = z.infer<typeof SimpleProjectSchema>;
type Project = z.infer<typeof ProjectSchema>;
type IssueStatistics = z.infer<typeof IssueStatisticsSchema>;
interface RequestParams {
accessToken: string;
customUrl?: string;
}
interface ResourceParams extends RequestParams {
path: string;
id: number;
}
export class GitLab {
/**
* Fetches the custom GitLab URL for a team from the first matching
* integration, falling back to the default.
@@ -58,93 +136,90 @@ export class GitLab {
return url || GitLabUtils.defaultGitlabUrl;
}
/**
* Creates a Gitbeaker client instance.
*
* @param accessToken - The access token for authentication.
* @param customUrl - Optional custom GitLab URL from integration settings.
* @returns A configured Gitbeaker client.
*/
public static async createClient(accessToken: string, customUrl?: string) {
const host = customUrl || GitLabUtils.defaultGitlabUrl;
// Validate the URL to prevent SSRF as GitLab instance does not use our
// fetch wrapper which has built-in SSRF protection.
await validateUrlNotPrivate(host);
return new Gitlab({
host,
oauthToken: accessToken,
});
}
/**
* Fetches an issue from a GitLab project.
*
* @param accessToken - The access token for authentication.
* @param projectPath - The project path (owner/repo).
* @param issueIid - The issue IID (internal ID within the project).
* @param customUrl - Optional custom GitLab URL from integration settings.
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The project path (owner/repo).
* @param params.id - The issue IID (internal ID within the project).
* @returns The issue data.
* @throws If the issue does not exist.
*/
public static async getIssue(
accessToken: string,
projectPath: string,
issueIid: number,
customUrl?: string
) {
const client = await this.createClient(accessToken, customUrl);
const issues = await client.Issues.all({
projectId: projectPath,
iids: [issueIid],
withLabelsDetails: true,
public static async getIssue({ path, id, ...params }: ResourceParams) {
const { data } = await this.request({
...params,
path: `/projects/${encodeURIComponent(path)}/issues?iids[]=${id}&with_labels_details=true`,
schema: z.array(IssueSchema),
});
if (!issues || issues.length === 0) {
throw new Error(`Issue ${issueIid} not found in project ${projectPath}`);
if (data.length === 0) {
throw new Error(`Issue ${id} not found in project ${path}`);
}
return issues[0];
return data[0];
}
/**
* Fetches an epic from a GitLab group.
*
* @param accessToken - The access token for authentication.
* @param groupPath - The full path of the group.
* @param epicIid - The epic IID (internal ID within the group).
* @param customUrl - Optional custom GitLab URL from integration settings.
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The full path of the group.
* @param params.id - The epic IID (internal ID within the group).
* @returns The epic data.
*/
public static async getEpic(
accessToken: string,
groupPath: string,
epicIid: number,
customUrl?: string
) {
const client = await this.createClient(accessToken, customUrl);
return client.Epics.show(groupPath, epicIid);
public static async getEpic({ path, id, ...params }: ResourceParams) {
const { data } = await this.request({
...params,
path: `/groups/${encodeURIComponent(path)}/epics/${id}`,
schema: EpicSchema,
});
return data;
}
/**
* Fetches a merge request from a GitLab project.
*
* @param accessToken - The access token for authentication.
* @param projectPath - The project path (owner/repo).
* @param mrIid - The merge request IID (internal ID within the project).
* @param customUrl - Optional custom GitLab URL from integration settings.
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The project path (owner/repo).
* @param params.id - The merge request IID (internal ID within the project).
* @returns The merge request data.
*/
public static async getMergeRequest(
accessToken: string,
projectPath: string,
mrIid: number,
customUrl?: string
) {
const client = await this.createClient(accessToken, customUrl);
const mr = await client.MergeRequests.show(projectPath, mrIid);
return mr;
public static async getMergeRequest({ path, id, ...params }: ResourceParams) {
const { data } = await this.request({
...params,
path: `/projects/${encodeURIComponent(path)}/merge_requests/${id}`,
schema: MergeRequestSchema,
});
return data;
}
/**
* Fetches a GitLab project and its issue statistics.
*
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The project path (owner/repo).
* @returns The project data and its issue statistics, if available.
*/
public static async getProject({
path,
...params
}: RequestParams & { path: string }) {
const projectPath = `/projects/${encodeURIComponent(path)}`;
const [project, issueStats] = await Promise.all([
this.request({ ...params, path: projectPath, schema: ProjectSchema }),
// Statistics can be slow for projects with many issues, so they are optional.
this.request({
...params,
path: `${projectPath}/issues_statistics`,
schema: IssueStatisticsSchema,
}).catch(() => undefined),
]);
return { project: project.data, issueStats: issueStats?.data };
}
/**
@@ -154,26 +229,21 @@ export class GitLab {
* @param params.customUrl - Optional custom GitLab URL. Falls back to default.
* @returns User information including the resolved URL.
*/
public static async getCurrentUser({
accessToken,
customUrl,
}: {
accessToken: string;
customUrl?: string;
}) {
const url = customUrl || GitLabUtils.defaultGitlabUrl;
const client = await this.createClient(accessToken, url);
const userData = await client.Users.showCurrentUser({
showExpanded: false,
public static async getCurrentUser(params: RequestParams) {
const url = params.customUrl || GitLabUtils.defaultGitlabUrl;
const { data } = await this.request({
...params,
path: "/user",
schema: UserSchema,
});
return { ...userData, url };
return { ...data, url };
}
/**
* Fetches projects accessible to the user.
* Fetches projects that the user can maintain.
*
* @param accessToken - Access token for authentication.
* @param params.accessToken - Access token for authentication.
* @param params.teamId - The team ID used to find the GitLab URL.
* @returns Array of projects.
*/
public static async getProjects({
@@ -184,13 +254,22 @@ export class GitLab {
teamId: string;
}) {
const customUrl = await this.getGitLabUrl(teamId);
const client = await this.createClient(accessToken, customUrl);
const projects: SimpleProject[] = [];
let page: string | null = "1";
for (let i = 0; i < this.maxPages && page; i++) {
const res: { data: SimpleProject[]; headers: Headers } =
await this.request({
accessToken,
customUrl,
// At least Maintainer access to reduce the sheer volume of projects.
path: `/projects?simple=true&min_access_level=40&per_page=100&page=${page}`,
schema: z.array(SimpleProjectSchema),
});
projects.push(...res.data);
page = res.headers.get("x-next-page");
}
const projects = await client.Projects.all({
simple: true,
perPage: 100,
minAccessLevel: 40, // At least Maintainer access to reduce the sheer volume of projects
});
return projects;
}
@@ -250,7 +329,7 @@ export class GitLab {
try {
const customUrl = matchedIntegration.settings?.gitlab?.url;
const { authentication } = matchedIntegration;
const token = await authentication.refreshTokenIfNeeded(
const accessToken = await authentication.refreshTokenIfNeeded(
async (refreshToken: string) =>
GitLab.refreshToken({
refreshToken,
@@ -265,41 +344,41 @@ export class GitLab {
resource.type === UnfurlResourceType.Issue &&
resource.scope === "group"
) {
const epic = await this.getEpic(
token,
resource.owner,
resource.id,
customUrl
);
const epic = await this.getEpic({
accessToken,
customUrl,
path: resource.owner,
id: resource.id,
});
return this.transformIssue(epic);
}
const projectPath = `${resource.owner}/${resource.repo}`;
const path = `${resource.owner}/${resource.repo}`;
if (resource.type === UnfurlResourceType.Issue) {
const issue = await this.getIssue(
token,
projectPath,
resource.id,
customUrl
);
const issue = await this.getIssue({
accessToken,
customUrl,
path,
id: resource.id,
});
return this.transformIssue(issue);
} else if (resource.type === UnfurlResourceType.PR) {
const mr = await this.getMergeRequest(
token,
projectPath,
resource.id,
customUrl
);
const mr = await this.getMergeRequest({
accessToken,
customUrl,
path,
id: resource.id,
});
return this.transformMR(mr);
} else if (resource.type === UnfurlResourceType.Project) {
const client = await this.createClient(token, customUrl);
const [project, issueStats] = await Promise.all([
client.Projects.show(projectPath),
client.IssuesStatistics.all({ projectId: projectPath }),
]);
const { project, issueStats } = await this.getProject({
accessToken,
customUrl,
path,
});
return this.transformProject(project, issueStats);
}
@@ -321,7 +400,7 @@ export class GitLab {
* @param params.clientSecret - Optional custom client secret (falls back to env var).
* @returns The parsed access token response.
*/
public static oauthAccess = async ({
public static async oauthAccess({
code,
customUrl,
clientId,
@@ -331,30 +410,61 @@ export class GitLab {
customUrl?: string;
clientId?: string;
clientSecret?: string;
}) => {
const url = customUrl || GitLabUtils.defaultGitlabUrl;
const res = await fetch(GitLabUtils.getOauthUrl(url) + "/token", {
method: "POST",
}) {
return this.requestToken(customUrl, {
code: code ?? "",
client_id: clientId || this.clientId || "",
client_secret: clientSecret || this.clientSecret || "",
grant_type: "authorization_code",
redirect_uri: GitLabUtils.callbackUrl(),
});
}
/** The time to wait for a response from a GitLab instance. */
private static timeout = 10 * Second.ms;
/** The maximum number of pages to fetch from a paginated endpoint. */
private static maxPages = 10;
private static clientSecret = env.GITLAB_CLIENT_SECRET;
private static clientId = env.GITLAB_CLIENT_ID;
/**
* Makes an authenticated GET request to the GitLab API.
*
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The API path, starting with a slash.
* @param params.schema - The schema to parse the response body with.
* @returns The parsed body and the response headers.
* @throws If the response status is not successful.
*/
private static async request<T extends z.ZodType>({
accessToken,
customUrl,
path,
schema,
}: RequestParams & { path: string; schema: T }) {
const baseUrl = customUrl || GitLabUtils.defaultGitlabUrl;
const res = await fetch(`${baseUrl}/api/v4${path}`, {
timeout: this.timeout,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
code,
client_id: clientId || this.clientId,
client_secret: clientSecret || this.clientSecret,
grant_type: "authorization_code",
redirect_uri: GitLabUtils.callbackUrl(),
}),
});
if (res.status !== 200) {
if (!res.ok) {
throw new Error(
`Error while validating oauth code from GitLab; status: ${res.status}`
`Error while requesting ${path} from GitLab; status: ${res.status}`
);
}
return AccessTokenResponseSchema.parse(await res.json());
};
// Read the body at once, a body left unread while awaiting other requests
// can be closed early.
return { data: schema.parse(await res.json()), headers: res.headers };
}
private static async refreshToken({
refreshToken,
@@ -367,39 +477,40 @@ export class GitLab {
clientId?: string;
clientSecret?: string;
}) {
const queryParams = new URLSearchParams({
client_id: clientId || this.clientId!,
client_secret: clientSecret || this.clientSecret!,
grant_type: "refresh_token",
return this.requestToken(customUrl, {
refresh_token: refreshToken,
client_id: clientId || this.clientId || "",
client_secret: clientSecret || this.clientSecret || "",
grant_type: "refresh_token",
redirect_uri: GitLabUtils.callbackUrl(),
});
}
private static async requestToken(
customUrl: string | undefined,
body: Record<string, string>
) {
const res = await fetch(`${GitLabUtils.getOauthUrl(customUrl)}/token`, {
method: "POST",
timeout: this.timeout,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(body),
});
const res = await fetch(
`${GitLabUtils.getOauthUrl(customUrl)}/token?${queryParams.toString()}`,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
}
);
const resJson = await res.json();
if (res.status !== 200) {
Logger.error("failed to refresh access token from GitLab", resJson);
throw new Error(
`Error while refreshing access token from GitLab; status: ${res.status}`
`Error while requesting access token from GitLab; status: ${res.status}`
);
}
return AccessTokenResponseSchema.parse(resJson);
return AccessTokenResponseSchema.parse(await res.json());
}
private static transformIssue(
issue: IssueSchemaWithExpandedLabels | EpicSchema
) {
const labels: (string | SimpleLabelSchema)[] = issue.labels;
private static transformIssue(issue: Issue | Epic) {
const labels: (string | z.infer<typeof LabelSchema>)[] = issue.labels;
return {
type: UnfurlResourceType.Issue,
@@ -411,7 +522,6 @@ export class GitLab {
name: issue.author?.username ?? "",
avatarUrl: issue.author?.avatar_url ?? "",
},
// Epics are returned without label color details.
labels: labels.map((label) =>
typeof label === "string"
? { name: label, color: GitLabUtils.defaultLabelColor }
@@ -425,8 +535,10 @@ export class GitLab {
} satisfies UnfurlIssueOrPR;
}
private static transformMR(mr: MergeRequestSchema) {
private static transformMR(mr: MergeRequest) {
const mrState = mr.merged_at ? "merged" : mr.state;
const draft = !!mr.draft;
return {
type: UnfurlResourceType.PR,
url: mr.web_url,
@@ -435,28 +547,30 @@ export class GitLab {
description: GitLabUtils.sanitizeGitLabMarkdown(mr.description) ?? "",
author: {
name: mr.author.username,
avatarUrl: mr.author.avatar_url,
avatarUrl: mr.author.avatar_url ?? "",
},
state: {
name: mrState,
color: GitLabUtils.getColorForStatus(mrState, !!mr.draft),
draft: mr.draft,
color: GitLabUtils.getColorForStatus(mrState, draft),
draft,
},
createdAt: mr.created_at,
} satisfies UnfurlIssueOrPR;
}
private static transformProject(
project: ProjectSchema,
issueStats: StatisticsSchema
project: Project,
issueStats?: IssueStatistics
) {
const visibility = project.visibility ?? "private";
const owner = project.owner as
| { name: string; avatar_url?: string }
| undefined;
const { opened, closed } = issueStats.statistics.counts;
const total = opened + closed;
const progress = total > 0 ? closed / total : 0;
const { owner } = project;
const counts = issueStats?.statistics.counts;
let progress: number | undefined;
if (counts) {
const total = counts.opened + counts.closed;
progress = total > 0 ? counts.closed / total : 0;
}
return {
type: UnfurlResourceType.Project,
@@ -477,7 +591,7 @@ export class GitLab {
name: visibility.charAt(0).toUpperCase() + visibility.slice(1),
color: GitLabUtils.getColorForVisibility(visibility),
},
labels: (project.topics ?? []).map((topic: string) => ({
labels: (project.topics ?? []).map((topic) => ({
name: topic,
color: GitLabUtils.defaultLabelColor,
})),
@@ -259,6 +259,38 @@ describe("#passkeys.verifyRegistration", () => {
expect(body.message).toEqual("Invalid authentication type");
});
it("should consume the challenge on a failed attempt", async () => {
const team = await buildTeam({ passkeysEnabled: true });
const user = await buildUser({ teamId: team.id });
const options = await server.post(
"/auth/passkeys.generateRegistrationOptions",
user
);
const { data } = await options.json();
const failed = await server.post(
"/auth/passkeys.verifyRegistration",
user,
{
body: buildNoneAttestationResponse(
isoBase64URL.fromBuffer(randomBytes(32)),
data.rp.id
),
}
);
expect(failed.status).toEqual(400);
const res = await server.post("/auth/passkeys.verifyRegistration", user, {
body: buildNoneAttestationResponse(data.challenge, data.rp.id),
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toEqual(
"No registration challenge found or challenge expired"
);
});
it("should record the registration in the audit log", async () => {
const planSpy = vi
.spyOn(Team.prototype, "plan", "get")
@@ -290,3 +322,40 @@ describe("#passkeys.verifyRegistration", () => {
planSpy.mockRestore();
});
});
describe("#passkeys.verifyAuthentication", () => {
it("should consume the challenge on a failed attempt", async () => {
const options = await server.post(
"/auth/passkeys.generateAuthenticationOptions",
{ body: {} }
);
const { data } = await options.json();
const body = {
challengeId: data.challengeId,
id: "unknown",
rawId: "unknown",
response: {
authenticatorData: "",
clientDataJSON: "",
signature: "",
},
type: "public-key",
};
const failed = await server.post("/auth/passkeys.verifyAuthentication", {
body,
});
const failedBody = await failed.json();
expect(failed.status).toEqual(400);
expect(failedBody.message).toContain("Passkey not found");
const res = await server.post("/auth/passkeys.verifyAuthentication", {
body,
});
const resBody = await res.json();
expect(res.status).toEqual(400);
expect(resBody.message).toEqual(
"No authentication challenge found or challenge expired"
);
});
});
+4 -9
View File
@@ -157,8 +157,8 @@ router.post(
const body = ctx.input.body;
authorize(user, "createUserPasskey", user.team);
// Retrieve challenge from Redis
const expectedChallenge = await Redis.defaultClient.get(
// Consume the challenge atomically so it can only be used once
const expectedChallenge = await Redis.defaultClient.getdel(
getRegistrationChallengeKey(user.id)
);
@@ -238,8 +238,6 @@ router.post(
});
}
// Delete challenge from Redis
await Redis.defaultClient.del(getRegistrationChallengeKey(user.id));
ctx.body = { data: { verified: true } };
} else {
throw ValidationError("Verification failed");
@@ -301,8 +299,8 @@ router.post(
const body = ctx.input.body;
const { challengeId, client = Client.Web } = body;
// Retrieve challenge from Redis
const expectedChallenge = await Redis.defaultClient.get(
// Consume the challenge atomically so it can only be used once
const expectedChallenge = await Redis.defaultClient.getdel(
getAuthenticationChallengeKey(challengeId)
);
@@ -371,9 +369,6 @@ router.post(
passkey.lastActiveAt = new Date();
await passkey.save({ silent: true });
// Delete challenge from Redis
await Redis.defaultClient.del(getAuthenticationChallengeKey(challengeId));
// Use the signIn utility which handles all sign-in logic
await signIn(ctx, "passkeys", {
user,
+1 -1
View File
@@ -83,7 +83,7 @@ router.post(
await attachment.destroy();
if (err instanceof Error && err.message.includes("permission denied")) {
throw Error(
`Permission denied writing to "${key}". Check the host machine file system permissions.`
`Permission denied writing to "${key}". Check that uid ${process.getuid?.() ?? "unknown"} can write to the storage directory on the host machine.`
);
}
throw err;
+37 -1
View File
@@ -1,4 +1,10 @@
import { existsSync, mkdirSync } from "node:fs";
import {
accessSync,
constants,
existsSync,
mkdirSync,
statSync,
} from "node:fs";
import { toError } from "@shared/utils/error";
import env from "@server/env";
import Logger from "@server/logging/Logger";
@@ -16,6 +22,7 @@ if (env.FILE_STORAGE === "local") {
mkdirSync(rootDir, { recursive: true });
Logger.debug("utils", `Created ${rootDir} for local storage`);
}
checkWritable(rootDir);
} catch (err) {
Logger.fatal(
`Failed to create directory for local file storage at ${env.FILE_STORAGE_LOCAL_ROOT_DIR}`,
@@ -41,3 +48,32 @@ if (enabled) {
},
]);
}
/**
* Logs an error that explains how to fix the permissions when the process
* cannot write to or enter the local file storage directory.
*
* @param rootDir the local file storage directory.
*/
function checkWritable(rootDir: string) {
try {
accessSync(rootDir, constants.W_OK | constants.X_OK);
} catch (err) {
if (process.getuid === undefined || process.getgid === undefined) {
Logger.error(
`Local file storage directory ${rootDir} is not writable`,
toError(err)
);
return;
}
const uid = process.getuid();
const gid = process.getgid();
const owner = statSync(rootDir);
Logger.error(
`Local file storage directory ${rootDir} is not writable. Outline runs as uid ${uid} and gid ${gid}, but the directory is owned by uid ${owner.uid} and gid ${owner.gid}. Run "chown -R ${uid}:${gid}" on the directory on the host, or run the container as the directory owner with user: "${owner.uid}:${owner.gid}".`,
toError(err)
);
}
}
@@ -121,7 +121,7 @@ router.post(
const webhookSubscription = await WebhookSubscription.findByPk(id, {
rejectOnEmpty: true,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: WebhookSubscription },
transaction,
});
@@ -152,7 +152,7 @@ router.post(
const webhookSubscription = await WebhookSubscription.findByPk(id, {
rejectOnEmpty: true,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: WebhookSubscription },
transaction,
});
@@ -137,6 +137,67 @@ describe("DeliverWebhookTask", () => {
expect(delivery.responseBody).toEqual("SUCCESS");
});
it("should truncate stored response bodies", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
events: ["*"],
});
const signedInUser = await buildUser({ teamId: subscription.teamId });
captureWebhook(
"http://example.com",
() => new HttpResponse("a".repeat(5000), { status: 200 })
);
await new DeliverWebhookTask().perform({
subscriptionId: subscription.id,
event: {
name: "users.signin",
userId: signedInUser.id,
teamId: subscription.teamId,
actorId: signedInUser.id,
ip,
},
});
const delivery = await WebhookDelivery.findOne({
where: { webhookSubscriptionId: subscription.id },
rejectOnEmpty: true,
});
expect(delivery.status).toBe("success");
expect(delivery.responseBody).toEqual("a".repeat(1024));
});
it("should not read response bodies over the size limit", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
events: ["*"],
});
const signedInUser = await buildUser({ teamId: subscription.teamId });
captureWebhook(
"http://example.com",
() => new HttpResponse("a".repeat(128 * 1024), { status: 200 })
);
await new DeliverWebhookTask().perform({
subscriptionId: subscription.id,
event: {
name: "users.signin",
userId: signedInUser.id,
teamId: subscription.teamId,
actorId: signedInUser.id,
ip,
},
});
const delivery = await WebhookDelivery.findOne({
where: { webhookSubscriptionId: subscription.id },
rejectOnEmpty: true,
});
expect(delivery.status).toBe("success");
expect(delivery.statusCode).toBe(200);
expect(delivery.responseBody).toEqual("");
});
it("should hit the subscription url with signature header", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
@@ -799,9 +799,12 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
});
}
/** Maximum number of bytes to read from webhook response bodies. */
/** Maximum number of bytes to store from webhook response bodies. */
private static readonly MAX_RESPONSE_BODY_SIZE = 1024;
/** Maximum number of bytes to read from webhook response bodies. */
private static readonly MAX_RESPONSE_READ_SIZE = 64 * 1024;
private async sendWebhook({
event,
subscription,
@@ -842,6 +845,7 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
body: JSON.stringify(requestBody),
redirect: "error",
timeout: 5000,
size: DeliverWebhookTask.MAX_RESPONSE_READ_SIZE,
});
status = response.ok ? "success" : "failed";
} catch (err) {
@@ -862,7 +866,6 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
if (response) {
try {
// TODO: Use stream to avoid buffering large responses in memory.
const text = await response.text();
responseBody = text.slice(0, DeliverWebhookTask.MAX_RESPONSE_BODY_SIZE);
} catch (err) {
+1 -1
View File
@@ -66,7 +66,7 @@ export default class PersistenceExtension implements Extension {
const document = await Document.unscoped().findOne({
attributes: ["id", "state", "content", "text"],
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
rejectOnEmpty: true,
where: {
id: documentId,
@@ -3,6 +3,7 @@ import { prosemirrorToYDoc } from "y-prosemirror";
import { schema } from "@server/editor";
import { createContext } from "@server/context";
import { Document, Event, Revision } from "@server/models";
import { sequelize } from "@server/storage/database";
import { buildDocument, buildUser } from "@server/test/factories";
import documentCollaborativeUpdater from "./documentCollaborativeUpdater";
@@ -231,4 +232,48 @@ describe("documentCollaborativeUpdater", () => {
);
ydoc.destroy();
});
it("does not wait for a concurrent foreign key insert on the document", async () => {
const user = await buildUser();
const document = await buildDocument({
teamId: user.teamId,
userId: user.id,
});
const ydoc = buildYDoc([
{
type: "paragraph",
content: [{ type: "text", text: "Saved while referenced" }],
},
]);
// A foreign key check on insert takes FOR KEY SHARE on the parent row.
const other = await sequelize.transaction();
try {
await sequelize.query(
`SELECT id FROM documents WHERE id = :id FOR KEY SHARE`,
{ replacements: { id: document.id }, transaction: other }
);
const save = documentCollaborativeUpdater({
documentId: document.id,
ydoc,
collaborators: { ids: [user.id] },
isLastConnection: true,
clientVersion: null,
}).then(() => "saved");
const timeout = new Promise((resolve) =>
setTimeout(() => resolve("blocked"), 2000)
);
await expect(Promise.race([save, timeout])).resolves.toBe("saved");
} finally {
await other.rollback();
}
await document.reload();
expect(document.content?.content?.[0]?.content?.[0]?.text).toBe(
"Saved while referenced"
);
ydoc.destroy();
});
});
@@ -89,7 +89,7 @@ export default async function documentCollaborativeUpdater({
transaction,
lock: {
of: Document,
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
},
rejectOnEmpty: true,
paranoid: false,
+51
View File
@@ -743,6 +743,57 @@ describe("documentUpdater", () => {
});
});
it("should keep a notice nested in its list item when patching another item", async () => {
const user = await buildUser();
let document = await buildDocument({
teamId: user.teamId,
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) =>
documentUpdater(ctx, {
text: "Amber",
findText: "Alpha",
document,
editMode: TextEditMode.Patch,
})
);
expect(document.content).toMatchObject({
type: "doc",
content: [
{
type: "ordered_list",
content: [
listItem("Amber one."),
{
type: "list_item",
content: [
{
type: "paragraph",
content: [{ type: "text", text: "Bravo two:" }],
},
{
type: "container_notice",
content: [
{
type: "paragraph",
content: [
{ type: "text", text: "A note inside item two." },
],
},
],
},
],
},
listItem("Charlie three."),
],
},
{ type: "paragraph" },
],
});
});
it("should append new blocks after a table when patching the last row", async () => {
const user = await buildUser();
let document = await buildDocument({
+5 -22
View File
@@ -1,7 +1,7 @@
import { difference } from "es-toolkit";
import type { DocumentPreferences, TextEditMode } from "@shared/types";
import { DocumentConflictError, ValidationError } from "@server/errors";
import { Event, Document } from "@server/models";
import { Document } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import { TextHelper } from "@server/models/helpers/TextHelper";
import { authorize } from "@server/policies";
@@ -23,8 +23,6 @@ type Props = {
color?: string | null;
/** The new text content */
text?: string;
/** Whether the editing session is complete */
done?: boolean;
/** The version of the client editor that was used */
editorVersion?: string;
/** The ID of the template that was used */
@@ -77,7 +75,6 @@ export default async function documentUpdater(
publish,
collectionId,
deprecatedReason,
done,
ownerIds,
}: Props
): Promise<Document> {
@@ -131,7 +128,7 @@ export default async function documentUpdater(
// Serialize concurrent updates to the same document by taking a row-level
// lock before writing. The wait is already bounded by the transaction's
// statement_timeout. When lastRevision is provided it becomes part of the
// lock_timeout. When lastRevision is provided it becomes part of the
// predicate, so a document modified since that revision matches no row.
if (transaction) {
const locked = await Document.unscoped().findOne({
@@ -141,7 +138,7 @@ export default async function documentUpdater(
...(lastRevision !== undefined && { revisionCount: lastRevision }),
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
paranoid: false,
});
@@ -165,31 +162,17 @@ export default async function documentUpdater(
}
const changed = document.changed();
const eventData = done !== undefined ? { done } : undefined;
const { collection } = document;
const event = {
name: "documents.update",
documentId: document.id,
collectionId: cId,
data: eventData,
};
if (publish && cId) {
if (!document.collectionId) {
document.collectionId = cId;
}
await document.publish(ctx, { collectionId: cId, data: eventData });
await document.publish(ctx, { collectionId: cId });
} else if (changed) {
document.lastModifiedById = user.id;
document.updatedBy = user;
await document.saveWithCtx(ctx, undefined, { data: eventData });
} else if (done) {
await Event.schedule({
...event,
actorId: user.id,
teamId: document.teamId,
});
await document.saveWithCtx(ctx);
}
if (document.ownerIds !== previousOwnerIds) {
+32
View File
@@ -59,6 +59,10 @@ function loadSentry(dsn: string): typeof SentryNode {
environment: env.ENVIRONMENT,
release: env.RELEASE,
maxBreadcrumbs: 0,
integrations: [
// Request bodies can contain document content and credentials.
sentry.httpIntegration({ maxIncomingRequestBodySize: "none" }),
],
ignoreErrors: [
// These errors are expected in normal running of the application and
// don't need to be reported.
@@ -80,6 +84,8 @@ function loadSentry(dsn: string): typeof SentryNode {
"Premature close",
],
beforeSend(event) {
scrubRequest(event);
try {
switch (event.level) {
case "warning":
@@ -97,3 +103,29 @@ function loadSentry(dsn: string): typeof SentryNode {
});
return sentry;
}
const SensitiveHeaderPattern =
/auth|cookie|token|secret|key|session|signature/i;
/**
* Removes the request body, cookies, and sensitive headers from an event.
*
* @param event the event to scrub in place.
*/
function scrubRequest(event: SentryNode.ErrorEvent) {
const { request } = event;
if (!request) {
return;
}
delete request.data;
delete request.cookies;
if (request.headers) {
request.headers = Object.fromEntries(
Object.entries(request.headers).filter(
([name]) => !SensitiveHeaderPattern.test(name)
)
);
}
}
+1 -1
View File
@@ -219,7 +219,7 @@ export function commentTools(server: McpServer, scopes: string[]) {
where: { id: document.id },
attributes: ["id"],
transaction,
lock: Transaction.LOCK.UPDATE,
lock: Transaction.LOCK.NO_KEY_UPDATE,
});
// Reload under the lock, with the state needed for the mark.
+29 -27
View File
@@ -735,21 +735,26 @@ export function documentTools(server: McpServer, scopes: string[]) {
const ctx = buildAPIContext(context);
const { user } = ctx.state.auth;
const document = await Document.findByPk(input.id, {
userId: user.id,
includeState: true,
rejectOnEmpty: true,
});
// Returns null when the update persisted nothing.
const updated = await sequelize.transaction(async (transaction) => {
ctx.state.transaction = transaction;
ctx.context.transaction = transaction;
let updated;
if (input.publish === false) {
authorize(user, "unpublish", document);
updated = await document.unpublishWithCtx(ctx, {
detach: false,
const document = await Document.findByPk(input.id, {
userId: user.id,
includeState: true,
rejectOnEmpty: true,
transaction,
});
} else {
if (input.publish === false) {
authorize(user, "unpublish", document);
return document.unpublishWithCtx(ctx, {
detach: false,
});
}
authorize(user, "update", document);
// The collection is only used when publishing a draft that has
@@ -773,15 +778,10 @@ export function documentTools(server: McpServer, scopes: string[]) {
const { revisionCount } = document;
updated = await sequelize.transaction(async (transaction) => {
ctx.state.transaction = transaction;
ctx.context.transaction = transaction;
return documentUpdater(ctx, {
document,
...input,
collectionId,
});
const result = await documentUpdater(ctx, {
document,
...input,
collectionId,
});
// Every save increments revisionCount, so an unchanged count means
@@ -789,11 +789,13 @@ export function documentTools(server: McpServer, scopes: string[]) {
// the caller would read as a completed write — the request either
// carried no recognized fields or values identical to the current
// document.
if (updated.revisionCount === revisionCount) {
return error(
"The update resulted in no changes to the document. Ensure at least one field is provided and differs from the current document."
);
}
return result.revisionCount === revisionCount ? null : result;
});
if (!updated) {
return error(
"The update resulted in no changes to the document. Ensure at least one field is provided and differs from the current document."
);
}
// A patch only rewrites part of the document, so the resulting
+31
View File
@@ -0,0 +1,31 @@
import type { Context, Next } from "koa";
import env from "@server/env";
/**
* Middleware that sets the response headers that are needed when serving the
* web application.
*
* @returns the middleware function.
*/
export default function appHeaders() {
// Sentry needs this header to report all performance metrics, see:
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin
const timingOrigins = [env.URL];
if (env.SENTRY_DSN) {
timingOrigins.push("https://sentry.io");
}
const timingAllowOrigin = timingOrigins.join(", ");
return async function appHeadersMiddleware(ctx: Context, next: Next) {
ctx.set("Timing-Allow-Origin", timingAllowOrigin);
// Allow the JS Self-Profiling API to be used for local performance work.
if (env.isDevelopment) {
ctx.set("Document-Policy", "js-profiling");
}
await next();
};
}
+36 -13
View File
@@ -348,24 +348,47 @@ describe("Authentication middleware", () => {
);
});
it("should allow passing transfer token as a GET param", async () => {
it("should not accept transfer token as a GET param", async () => {
const state = {} as DefaultState;
const user = await buildUser();
const authMiddleware = auth();
await authMiddleware(
buildMockContext({
request: {
get: vi.fn(() => null),
query: {
token: user.getTransferToken(),
await expect(
authMiddleware(
buildMockContext({
request: {
get: vi.fn(() => null),
query: {
token: user.getTransferToken(),
},
},
},
state,
cache: {},
}),
vi.fn()
state,
cache: {},
}),
vi.fn()
)
).rejects.toThrow(
"Session token must be passed in the cookie or Authorization header"
);
expect(state.auth.user.id).toEqual(user.id);
});
it("should not accept transfer token in the Authorization header", async () => {
const state = {} as DefaultState;
const user = await buildUser();
const authMiddleware = auth();
await expect(
authMiddleware(
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getTransferToken()}`),
},
state,
cache: {},
}),
vi.fn()
)
).rejects.toThrow("Invalid token");
});
it("should return an error for suspended users", async () => {
+5 -10
View File
@@ -10,7 +10,7 @@ import tracer, {
import { User, Team, ApiKey, OAuthAuthentication } from "@server/models";
import type { AppContext } from "@server/types";
import { AuthenticationType } from "@server/types";
import { getJWTPayload, getUserForJWT } from "@server/utils/jwt";
import { getUserForJWT } from "@server/utils/jwt";
import {
AuthenticationError,
AuthorizationError,
@@ -274,16 +274,11 @@ async function validateAuthentication(
await apiKey.updateActiveAt();
} else {
// Session tokens are long-lived, so keep them out of transports that end up
// in browser history, referrers, and request logs. Short-lived single-use
// tokens such as transfer are still accepted from anywhere.
// in browser history, referrers, and request logs.
if (transport !== "cookie" && transport !== "header") {
const payload = getJWTPayload(token);
if (payload.type === "session") {
throw AuthenticationError(
"Session token must be passed in the cookie or Authorization header"
);
}
throw AuthenticationError(
"Session token must be passed in the cookie or Authorization header"
);
}
type = AuthenticationType.APP;
@@ -0,0 +1,17 @@
"use strict";
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface) {
// Covers the scan for stuck import tasks, which pages by createdAt.
await queryInterface.sequelize.query(
`CREATE INDEX CONCURRENTLY IF NOT EXISTS "import_tasks_pending_created_at" ON "import_tasks" ("createdAt", "id") WHERE "state" IN ('created', 'in_progress');`
);
},
async down(queryInterface) {
await queryInterface.sequelize.query(
'DROP INDEX CONCURRENTLY IF EXISTS "import_tasks_pending_created_at";'
);
},
};
@@ -0,0 +1,18 @@
"use strict";
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface) {
// Covers lookups of inherited group permissions by document and group.
// Partial so it only indexes rows that are sourced from a parent.
await queryInterface.sequelize.query(
'CREATE INDEX CONCURRENTLY IF NOT EXISTS "group_permissions_document_id_group_id_sourced" ON "group_permissions" ("documentId", "groupId") WHERE "sourceId" IS NOT NULL AND "deletedAt" IS NULL;'
);
},
async down(queryInterface) {
await queryInterface.sequelize.query(
'DROP INDEX CONCURRENTLY IF EXISTS "group_permissions_document_id_group_id_sourced";'
);
},
};
+1 -1
View File
@@ -993,7 +993,7 @@ class Collection extends ParanoidModel<
attributes: ["id"],
where: { id: this.id },
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
rejectOnEmpty: true,
});
}
+1 -1
View File
@@ -293,7 +293,7 @@ class Comment extends ParanoidModel<
},
transaction: options.transaction,
lock: options.transaction
? { level: options.transaction.LOCK.UPDATE, of: this }
? { level: options.transaction.LOCK.NO_KEY_UPDATE, of: this }
: undefined,
});
if (!parent) {
+7 -1
View File
@@ -1576,7 +1576,13 @@ class Document extends ArchivableModel<
this.lastModifiedById = user.id;
this.updatedBy = user;
await this.saveWithCtx(ctx, undefined, { name: "delete", ...eventOpts });
// Deleted documents are excluded from the default scope, so the title
// cannot be read from the document association when listing this event.
await this.saveWithCtx(ctx, undefined, {
name: "delete",
data: { title: this.title },
...eventOpts,
});
};
getTimestamp = () => Math.round(new Date(this.updatedAt).getTime() / 1000);
+1 -1
View File
@@ -164,7 +164,7 @@ class GroupMembership extends ParanoidModel<
return this.findOne({
...options,
where: collectionId ? { groupId, collectionId } : { groupId, documentId },
lock: options.transaction.LOCK.UPDATE,
lock: options.transaction.LOCK.NO_KEY_UPDATE,
});
}
+1 -1
View File
@@ -117,7 +117,7 @@ class IntegrationAuthentication extends IdModel<
this.constructor as typeof IntegrationAuthentication
).findByPk(this.id, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
rejectOnEmpty: true,
});
+2 -2
View File
@@ -61,7 +61,7 @@ class Reaction extends IdModel<
const lock = transaction
? {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
}
: undefined;
@@ -112,7 +112,7 @@ class Reaction extends IdModel<
const lock = transaction
? {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
}
: undefined;
+1 -1
View File
@@ -171,7 +171,7 @@ class UserMembership extends IdModel<
return this.findOne({
...options,
where: collectionId ? { userId, collectionId } : { userId, documentId },
lock: options.transaction.LOCK.UPDATE,
lock: options.transaction.LOCK.NO_KEY_UPDATE,
});
}
@@ -22,7 +22,7 @@ export default class CollectionsProcessor extends BaseProcessor {
await sequelize.transaction(async (transaction) => {
const team = await Team.findByPk(event.teamId, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
if (team?.defaultCollectionId === event.collectionId) {
+13 -4
View File
@@ -88,7 +88,7 @@ export default abstract class ImportsProcessor<
rejectOnEmpty: true,
paranoid: false,
transaction,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: Import },
});
if (
@@ -606,9 +606,10 @@ export default abstract class ImportsProcessor<
const rootNode = rootNodesByExternalId[externalId];
// documentId is set for root pages too.
const attachments = await Attachment.findAll({
attributes: ["id", "size"],
where: { documentId: externalId }, // This will be set for root pages too
where: { documentId: externalId, teamId: importModel.teamId },
transaction,
});
@@ -690,7 +691,11 @@ export default abstract class ImportsProcessor<
// Unset documentId for attachments in collection overview.
await Attachment.update(
{ documentId: null },
{ where: { documentId: externalId }, silent: true, transaction }
{
where: { documentId: externalId, teamId: importModel.teamId },
silent: true,
transaction,
}
);
continue;
@@ -832,7 +837,11 @@ export default abstract class ImportsProcessor<
// Update document id for attachments in document content.
await Attachment.update(
{ documentId: internalId },
{ where: { documentId: externalId }, silent: true, transaction }
{
where: { documentId: externalId, teamId: importModel.teamId },
silent: true,
transaction,
}
);
}
}
+1 -1
View File
@@ -150,7 +150,7 @@ export default abstract class APIImportTask<
},
],
transaction,
lock: Transaction.LOCK.UPDATE,
lock: { level: Transaction.LOCK.NO_KEY_UPDATE, of: ImportTask },
}
);
+4 -1
View File
@@ -27,7 +27,10 @@ export default class CacheIssueSourcesTask extends BaseTask<Props> {
const sources = await plugin.value.fetchSources(integration);
await sequelize.transaction(async (transaction) => {
await integration.reload({ transaction, lock: transaction.LOCK.UPDATE });
await integration.reload({
transaction,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
integration.issueSources = sources;
await integration.save({ transaction });
});
@@ -32,7 +32,10 @@ export default class CleanupDemotedUserTask extends BaseTask<Props> {
enabled: true,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: {
level: transaction.LOCK.NO_KEY_UPDATE,
of: WebhookSubscription,
},
});
await Promise.all(
subscriptions.map((subscription) =>
+1 -1
View File
@@ -24,7 +24,7 @@ export default class InviteReminderTask extends CronTask {
await sequelize.transaction(async (transaction) => {
const user = await User.scope("withTeam").findByPk(userId, {
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: User,
},
transaction,
@@ -347,4 +347,34 @@ describe("UpdateDocumentsPopularityScoreTask", () => {
expect(Number(updatedDraft?.popularityScore)).toEqual(0);
expect(Number(updatedDeleted?.popularityScore)).toEqual(0);
});
it("should update documents that hold a key share lock", async () => {
const team = await buildTeam();
const document = await buildDocument({
teamId: team.id,
publishedAt: new Date(),
});
await DocumentInsight.create({
documentId: document.id,
teamId: team.id,
date: dayStr(new Date()),
revisionCount: 1,
});
// Inserts into tables that reference documents take this lock.
const transaction = await sequelize.transaction();
try {
await sequelize.query(
`SELECT id FROM documents WHERE id = :id FOR KEY SHARE`,
{ replacements: { id: document.id }, transaction }
);
await task.perform(props);
} finally {
await transaction.rollback();
}
const updated = await Document.findByPk(document.id);
expect(Number(updated?.popularityScore)).toBeGreaterThan(0);
});
});
@@ -418,10 +418,11 @@ export default class UpdateDocumentsPopularityScoreTask extends CronTask {
// Update documents in a single batch to improve performance and reduce round-trips.
// We use unnest with multiple arrays to ensure the IDs and scores stay aligned.
// We also use SKIP LOCKED to avoid waiting on locked rows from other concurrent tasks.
// NO KEY UPDATE does not block the KEY SHARE locks taken by inserts that reference documents.
await sequelize.query(
`
WITH lockable AS (
SELECT id FROM documents WHERE id = ANY(ARRAY[:ids]::uuid[]) FOR UPDATE SKIP LOCKED
SELECT id FROM documents WHERE id = ANY(ARRAY[:ids]::uuid[]) FOR NO KEY UPDATE SKIP LOCKED
)
UPDATE documents AS d
SET "popularityScore" = s.score
@@ -99,7 +99,7 @@ router.post(
const accessRequest = await AccessRequest.findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: { level: transaction.LOCK.UPDATE, of: AccessRequest },
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: AccessRequest },
});
const document = await Document.findByPk(accessRequest.documentId, {
@@ -151,7 +151,7 @@ router.post(
const accessRequest = await AccessRequest.findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: { level: transaction.LOCK.UPDATE, of: AccessRequest },
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: AccessRequest },
});
const document = await Document.findByPk(accessRequest.documentId, {
@@ -48,7 +48,7 @@ router.post(
const authenticationProvider = await AuthenticationProvider.findByPk(id, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
authorize(user, "update", authenticationProvider);
+30 -1
View File
@@ -1,6 +1,7 @@
import { RateLimiterRes } from "rate-limiter-flexible";
import { DatabaseError } from "sequelize";
import env from "@server/env";
import { Collection } from "@server/models";
import { Collection, Document as DocumentModel } from "@server/models";
import type { Document, User } from "@server/models";
import {
buildAdmin,
@@ -270,6 +271,34 @@ describe("#batch", () => {
expect(body.data[0].error).toEqual("not_found");
});
it("should return a request timeout when a sub-request waits too long for a lock", async () => {
const parent = Object.assign(
new Error("canceling statement due to lock timeout"),
{ code: "55P03", sql: "" }
);
vi.spyOn(DocumentModel, "findByPk").mockRejectedValueOnce(
new DatabaseError(parent)
);
const res = await server.post("/api/batch", user, {
body: {
requests: [
{
method: "documents.update",
body: { id: documentOne.id, title: "Updated" },
},
],
},
});
const body = await res.json();
vi.restoreAllMocks();
expect(res.status).toEqual(200);
expect(body.data[0].ok).toBe(false);
expect(body.data[0].status).toEqual(503);
expect(body.data[0].error).toEqual("request_timeout");
});
it("should surface per-request validation errors", async () => {
const res = await server.post("/api/batch", user, {
body: {
+7 -7
View File
@@ -51,7 +51,7 @@ router.post(
where: { id: documentId },
attributes: ["id"],
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
}
@@ -230,7 +230,7 @@ router.post(
transaction,
rejectOnEmpty: true,
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
},
});
@@ -306,7 +306,7 @@ router.post(
transaction,
rejectOnEmpty: true,
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
},
});
@@ -340,7 +340,7 @@ router.post(
transaction,
rejectOnEmpty: true,
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
},
});
@@ -376,7 +376,7 @@ router.post(
transaction,
rejectOnEmpty: true,
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
},
});
@@ -413,7 +413,7 @@ router.post(
transaction,
rejectOnEmpty: true,
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
},
});
@@ -469,7 +469,7 @@ router.post(
transaction,
rejectOnEmpty: true,
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Comment,
},
});
@@ -4995,6 +4995,91 @@ describe("#documents.deleted", () => {
expect(monthBody.data.length).toEqual(1);
});
it("should not return deleted drafts created by other collection members", async () => {
const user = await buildUser();
const other = await buildUser({ teamId: user.teamId });
const collection = await buildCollection({ teamId: user.teamId });
const ownDraft = await buildDraftDocument({
userId: user.id,
teamId: user.teamId,
collectionId: collection.id,
});
const otherDraft = await buildDraftDocument({
userId: other.id,
teamId: user.teamId,
collectionId: collection.id,
});
const otherDocument = await buildDocument({
userId: other.id,
teamId: user.teamId,
collectionId: collection.id,
});
await withAPIContext(user, (ctx) => ownDraft.destroyWithCtx(ctx));
await withAPIContext(other, (ctx) => otherDraft.destroyWithCtx(ctx));
await withAPIContext(other, (ctx) => otherDocument.destroyWithCtx(ctx));
const res = await server.post("/api/documents.deleted", user);
const body = await res.json();
const ids = body.data.map((d: { id: string }) => d.id);
expect(res.status).toEqual(200);
expect(ids).toHaveLength(2);
expect(ids).toContain(ownDraft.id);
expect(ids).toContain(otherDocument.id);
expect(ids).not.toContain(otherDraft.id);
});
it("should return deleted drafts the user has a direct membership on", async () => {
const user = await buildUser();
const other = await buildUser({ teamId: user.teamId });
const collection = await buildCollection({ teamId: user.teamId });
const sharedDraft = await buildDraftDocument({
userId: other.id,
teamId: user.teamId,
collectionId: collection.id,
});
await UserMembership.create({
createdById: other.id,
documentId: sharedDraft.id,
userId: user.id,
permission: DocumentPermission.ReadWrite,
});
await withAPIContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx));
const res = await server.post("/api/documents.deleted", user);
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.length).toEqual(1);
expect(body.data[0].id).toEqual(sharedDraft.id);
});
it("should return deleted drafts shared with a group of the user", async () => {
const user = await buildUser();
const other = await buildUser({ teamId: user.teamId });
const group = await buildGroup({ teamId: user.teamId });
await group.$add("user", user, {
through: { createdById: other.id },
});
const collection = await buildCollection({ teamId: user.teamId });
const sharedDraft = await buildDraftDocument({
userId: other.id,
teamId: user.teamId,
collectionId: collection.id,
});
await GroupMembership.create({
groupId: group.id,
documentId: sharedDraft.id,
permission: DocumentPermission.ReadWrite,
createdById: other.id,
});
await withAPIContext(other, (ctx) => sharedDraft.destroyWithCtx(ctx));
const res = await server.post("/api/documents.deleted", user);
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.length).toEqual(1);
expect(body.data[0].id).toEqual(sharedDraft.id);
});
it("should require member", async () => {
const viewer = await buildViewer();
const res = await server.post("/api/documents.deleted", viewer);
+10 -24
View File
@@ -167,30 +167,10 @@ async function expandDocumentIdLeaves(
return expandDocumentIdInFilter(filter, expandedIds);
}
/**
* Fetch the ids of documents the user has a direct membership on. Used to
* express draft visibility without referencing the (separately-loaded)
* memberships association, which would otherwise break the COUNT query.
*
* @param user the user to fetch membership document ids for.
* @returns the list of document ids.
*/
async function directMembershipDocumentIds(user: User): Promise<string[]> {
const memberships = await UserMembership.findAll({
attributes: ["documentId"],
where: {
userId: user.id,
documentId: { [Op.ne]: null },
},
});
return memberships.map((m) => m.documentId as string);
}
/**
* Build the visibility clauses for drafts: a draft is only ever visible to its
* creator or to a user with a direct membership on it. Both the filter-derived
* and legacy statusFilter draft paths route through this so the invariant lives
* in one place.
* creator or to a user with a user or group membership on it. List endpoints
* that can return drafts route through this so the invariant lives in one place.
*
* @param user the user the drafts must be visible to.
* @returns an array of OR-able Sequelize conditions.
@@ -198,7 +178,7 @@ async function directMembershipDocumentIds(user: User): Promise<string[]> {
async function draftVisibilityClauses(user: User): Promise<WhereOptions[]> {
return [
{ createdById: user.id },
{ id: await directMembershipDocumentIds(user) },
{ id: await Document.membershipDocumentIds(user.id) },
];
}
@@ -576,6 +556,12 @@ router.post(
},
],
},
{
[Op.or]: [
{ publishedAt: { [Op.ne]: null } },
...(await draftVisibilityClauses(user)),
],
},
],
};
@@ -2206,7 +2192,7 @@ router.post(
groupId,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
rejectOnEmpty: true,
});
-3
View File
@@ -454,9 +454,6 @@ export const DocumentsUpdateSchema = BaseSchema.extend({
/** @deprecated Version of the API to be used, remove in a few releases */
apiVersion: z.number().optional(),
/** Whether the editing session is complete */
done: z.boolean().optional(),
/** IDs of the users that own the doc */
ownerIds: z.array(z.uuid()).max(DocumentValidation.maxOwners).optional(),
}),
@@ -136,7 +136,7 @@ router.post(
const fileOperation = await FileOperation.unscoped().findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
authorize(user, "delete", fileOperation);
@@ -63,6 +63,53 @@ describe("groupMemberships.list", () => {
expect(body.policies).not.toBeFalsy();
});
it("should not return documents nested under another shared document", async () => {
const user = await buildUser();
const collection = await buildCollection({
teamId: user.teamId,
createdById: user.id,
permission: null,
});
const group = await buildGroup({
teamId: user.teamId,
});
const member = await buildUser({
teamId: user.teamId,
});
await GroupUser.create({
groupId: group.id,
userId: member.id,
createdById: user.id,
});
const parent = await buildDocument({
collectionId: collection.id,
createdById: user.id,
teamId: user.teamId,
});
const child = await buildDocument({
collectionId: collection.id,
parentDocumentId: parent.id,
createdById: user.id,
teamId: user.teamId,
});
for (const document of [child, parent]) {
await server.post("/api/documents.add_group", user, {
body: {
id: document.id,
groupId: group.id,
},
});
}
const res = await server.post("/api/groupMemberships.list", member);
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.pagination.total).toEqual(1);
expect(body.data.groupMemberships).toHaveLength(1);
expect(body.data.groupMemberships[0].documentId).toEqual(parent.id);
});
it("should return total count in pagination", async () => {
const user = await buildUser();
const collection = await buildCollection({
@@ -1,6 +1,6 @@
import Router from "@koa/router";
import { uniqBy } from "es-toolkit/compat";
import { Op } from "sequelize";
import { Op, Sequelize } from "sequelize";
import auth from "@server/middlewares/authentication";
import validate from "@server/middlewares/validate";
import { Document, GroupMembership, GroupUser } from "@server/models";
@@ -44,6 +44,16 @@ router.post(
sourceId: {
[Op.eq]: null,
},
// Documents that inherit access from a shared ancestor are shown
// nested under that ancestor rather than as separate roots.
[Op.and]: Sequelize.literal(`NOT EXISTS (
SELECT 1 FROM group_permissions AS sourced
WHERE sourced."documentId" = "group_permission"."documentId"
AND sourced."groupId" = "group_permission"."groupId"
AND sourced."sourceId" IS NOT NULL
AND sourced."deletedAt" IS NULL
)`),
},
include: [
{
+3 -3
View File
@@ -286,7 +286,7 @@ router.post(
externalGroupInclude,
],
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Group,
},
});
@@ -334,7 +334,7 @@ router.post(
transaction,
include: [externalGroupInclude],
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: Group,
},
});
@@ -380,7 +380,7 @@ router.post(
const groups = await Group.findAll({
where: { id: groupIds, teamId: user.teamId },
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
// Each group is destroyed individually so that a delete event is
+2 -2
View File
@@ -209,7 +209,7 @@ router.post(
const importModel = await Import.findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: Import },
});
authorize(user, "delete", importModel);
@@ -234,7 +234,7 @@ router.post(
let importModel = await Import.findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: Import },
});
authorize(user, "cancel", importModel);
@@ -130,7 +130,7 @@ router.post(
const integration = await Integration.findByPk(id, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
authorize(user, "update", integration);
@@ -166,7 +166,7 @@ router.post(
const integration = await Integration.findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
authorize(user, "delete", integration);
@@ -8,8 +8,10 @@ import {
import {
AuthorizationError,
NotFoundError,
RequestTimeoutError,
ValidationError,
} from "@server/errors";
import { isQueryCanceledError } from "@server/storage/database";
/** Postgres codes for a requested date the database cannot represent. */
const DATE_RANGE_ERROR_CODES = new Set(["22008", "22015"]);
@@ -62,6 +64,10 @@ export default function apiErrorHandler() {
);
}
if (isQueryCanceledError(err)) {
transformedErr = RequestTimeoutError();
}
if (
(err instanceof Error && "code" in err && err.code === "ENOENT") ||
err instanceof SequelizeEmptyResultError ||
@@ -49,7 +49,7 @@ const unsubscribe = async (ctx: APIContext<T.NotificationsUnsubscribeReq>) => {
const user = await User.scope("withTeam").findByPk(userId, {
rejectOnEmpty: true,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: User },
transaction,
});
@@ -154,7 +154,7 @@ router.post(
const oauthClient = await OAuthClient.findByPk(id, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
rejectOnEmpty: true,
});
authorize(user, "update", oauthClient);
@@ -183,7 +183,7 @@ router.post(
const oauthClient = await OAuthClient.findByPk(id, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
rejectOnEmpty: true,
});
authorize(user, "update", oauthClient);
@@ -212,7 +212,7 @@ router.post(
const oauthClient = await OAuthClient.findByPk(id, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
rejectOnEmpty: true,
});
authorize(user, "delete", oauthClient);
+1 -1
View File
@@ -111,7 +111,7 @@ router.post(
transaction,
lock: {
of: Revision,
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
},
});
const document = await Document.findByPk(revision.documentId, {
+1 -1
View File
@@ -24,7 +24,7 @@ const handleTeamUpdate = async (ctx: APIContext<T.TeamsUpdateSchemaReq>) => {
const { user } = ctx.state.auth;
const team = await Team.findByPk(user.teamId, {
include: [{ model: TeamDomain, separate: true }],
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
});
authorize(user, "update", team);
@@ -102,6 +102,86 @@ describe("#userMemberships.list", () => {
expect(body.data.documents).toHaveLength(1);
expect(body.data.documents[0].id).toEqual(documents[2].id);
});
it("should not return documents nested under another shared document", async () => {
const user = await buildUser();
const collection = await buildCollection({
teamId: user.teamId,
createdById: user.id,
permission: null,
});
const member = await buildUser({
teamId: user.teamId,
});
const parent = await buildDocument({
collectionId: collection.id,
createdById: user.id,
teamId: user.teamId,
});
const child = await buildDocument({
collectionId: collection.id,
parentDocumentId: parent.id,
createdById: user.id,
teamId: user.teamId,
});
const grandchild = await buildDocument({
collectionId: collection.id,
parentDocumentId: child.id,
createdById: user.id,
teamId: user.teamId,
});
for (const document of [grandchild, child, parent]) {
await server.post("/api/documents.add_user", user, {
body: {
id: document.id,
userId: member.id,
},
});
}
const res = await server.post("/api/userMemberships.list", member);
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.memberships).toHaveLength(1);
expect(body.data.memberships[0].documentId).toEqual(parent.id);
});
it("should return a nested document when its parent is not shared", async () => {
const user = await buildUser();
const collection = await buildCollection({
teamId: user.teamId,
createdById: user.id,
permission: null,
});
const member = await buildUser({
teamId: user.teamId,
});
const parent = await buildDocument({
collectionId: collection.id,
createdById: user.id,
teamId: user.teamId,
});
const child = await buildDocument({
collectionId: collection.id,
parentDocumentId: parent.id,
createdById: user.id,
teamId: user.teamId,
});
await server.post("/api/documents.add_user", user, {
body: {
id: child.id,
userId: member.id,
},
});
const res = await server.post("/api/userMemberships.list", member);
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.memberships).toHaveLength(1);
expect(body.data.memberships[0].documentId).toEqual(child.id);
});
});
describe("#userMemberships.update", () => {
@@ -33,6 +33,15 @@ router.post(
sourceId: {
[Op.eq]: null,
},
// Documents that inherit access from a shared ancestor are shown
// nested under that ancestor rather than as separate roots.
[Op.and]: Sequelize.literal(`NOT EXISTS (
SELECT 1 FROM user_permissions AS sourced
WHERE sourced."documentId" = "user_permission"."documentId"
AND sourced."userId" = "user_permission"."userId"
AND sourced."sourceId" IS NOT NULL
)`),
},
include: [
{
@@ -88,7 +97,7 @@ router.post(
const membership = await UserMembership.scope("withUser").findByPk(id, {
transaction,
lock: {
level: transaction.LOCK.UPDATE,
level: transaction.LOCK.NO_KEY_UPDATE,
of: UserMembership,
},
rejectOnEmpty: true,
+8 -8
View File
@@ -237,7 +237,7 @@ router.get(
try {
const res = await getDetailsForEmailUpdateToken(code as string, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
user = res.user;
email = res.email;
@@ -281,7 +281,7 @@ router.post(
user = await User.findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
}
authorize(actor, "update", user);
@@ -382,13 +382,13 @@ async function updateRole(ctx: APIContext<T.UsersChangeRoleReq>) {
const user = await User.findByPk(userId, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
authorize(actor, "update", user);
await Team.findByPk(user.teamId, {
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
let name;
@@ -435,7 +435,7 @@ router.post(
const user = await User.findByPk(userId, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
authorize(actor, "suspend", user);
@@ -472,7 +472,7 @@ router.post(
const user = await User.findByPk(userId, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
authorize(actor, "activate", user);
@@ -539,7 +539,7 @@ router.post(
const actor = auth.user;
const user = await User.findByPk(id, {
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
});
authorize(actor, "resendInvite", user);
@@ -618,7 +618,7 @@ router.post(
user = await User.findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
} else {
user = actor;
+43 -14
View File
@@ -1,6 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import util from "node:util";
import Router from "@koa/router";
import type { Context, Next } from "koa";
import { escape } from "es-toolkit/compat";
import { isbot } from "isbot";
@@ -26,7 +27,28 @@ import { getTeamFromContext } from "@server/utils/passport";
import prefetchTags from "@server/utils/prefetchTags";
import readManifestFile from "@server/utils/readManifestFile";
import { RedisPrefixHelper } from "@server/utils/RedisPrefixHelper";
import { isInvalidAppPath } from "@server/utils/url";
import { loadPublicShare } from "@server/commands/shareLoader";
import {
getWorkspaceRedirectUrl,
getWorkspaceRenderOptions,
} from "./workspace";
/** Options used to render the app shell. */
export interface AppRenderOptions {
title?: string;
description?: string;
content?: string;
canonical?: string;
shortcutIcon?: string;
image?: string;
siteName?: string;
rootShareId?: string;
isShare?: boolean;
markdownUrl?: string;
analytics?: Integration<IntegrationType.Analytics>[];
allowIndexing?: boolean;
}
const readFile = util.promisify(fs.readFile);
const entry = "app/index.tsx";
@@ -139,20 +161,7 @@ const readIndexFile = async (): Promise<Buffer> => {
export const renderApp = async (
ctx: Context,
next: Next,
options: {
title?: string;
description?: string;
content?: string;
canonical?: string;
shortcutIcon?: string;
image?: string;
siteName?: string;
rootShareId?: string;
isShare?: boolean;
markdownUrl?: string;
analytics?: Integration<IntegrationType.Analytics>[];
allowIndexing?: boolean;
} = {}
options: AppRenderOptions = {}
) => {
const {
title = env.APP_NAME,
@@ -444,3 +453,23 @@ export const renderShare = async (ctx: Context, next: Next) => {
markdownUrl: document || collection ? markdownUrl : undefined,
});
};
const router = new Router();
router.get("{/*path}", async (ctx, next) => {
if (isInvalidAppPath(ctx.path)) {
ctx.status = 404;
return;
}
const team = await getTeamFromContext(ctx);
const redirectUrl = await getWorkspaceRedirectUrl(ctx, team);
if (redirectUrl) {
ctx.redirect(redirectUrl);
return;
}
return renderApp(ctx, next, await getWorkspaceRenderOptions(team));
});
export default router;
+103
View File
@@ -0,0 +1,103 @@
import crypto from "node:crypto";
import path from "node:path";
import { formatRFC7231 } from "date-fns";
import Router from "@koa/router";
import { send } from "@koa/send";
import { languages } from "@shared/i18n";
import { Day } from "@shared/utils/time";
import env from "@server/env";
import { NotFoundError } from "@server/errors";
const router = new Router();
router.get(
["/images/{*path}", "/email/{*path}", "/fonts/{*path}"],
async (ctx, next) => {
let sent;
try {
sent = await send(ctx, ctx.path, {
root: path.resolve(__dirname, "../../../public"),
// 7 day expiry, these assets are mostly static but do not contain a hash
maxAge: Day.ms * 7,
setHeaders: (res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
},
});
} catch (err) {
if (!isNotFound(err)) {
throw err;
}
}
if (!sent) {
await next();
}
}
);
if (env.isProduction) {
router.get("/static/{*path}", async (ctx) => {
try {
const pathname = ctx.path.substring(8);
if (!pathname) {
throw NotFoundError();
}
await send(ctx, pathname, {
root: path.join(__dirname, "../../app/"),
// Hashed static assets get 1 year expiry plus immutable flag
maxAge: Day.ms * 365,
immutable: true,
setHeaders: (res, filePath) => {
res.setHeader("Service-Worker-Allowed", "/");
res.setHeader("Access-Control-Allow-Origin", "*");
// The service worker is not hashed and must always be revalidated
// so that browsers detect and install new versions.
if (path.basename(filePath) === "sw.js") {
res.setHeader("Cache-Control", "no-cache");
}
},
});
} catch (err) {
// Serve a bad request instead of not found if the file doesn't exist,
// this prevents CDNs from caching the response and allows them to
// continue serving old file versions.
if (isNotFound(err)) {
ctx.status = 400;
return;
}
throw err;
}
});
}
router.get("/locales/:lng.json", async (ctx) => {
const { lng } = ctx.params;
if (!languages.includes(lng as (typeof languages)[number])) {
ctx.status = 404;
return;
}
await send(ctx, path.join(lng, "translation.json"), {
setHeaders: (res, _, stats) => {
res.setHeader("Last-Modified", formatRFC7231(stats.mtime));
res.setHeader("Cache-Control", `public, max-age=${7 * Day.seconds}`);
res.setHeader(
"ETag",
crypto.createHash("md5").update(stats.mtime.toISOString()).digest("hex")
);
res.setHeader("Access-Control-Allow-Origin", "*");
},
root: path.join(__dirname, "../../shared/i18n/locales"),
});
});
function isNotFound(err: unknown): boolean {
return err instanceof Error && "status" in err && err.status === 404;
}
export default router;
+25
View File
@@ -82,6 +82,31 @@ describe("auth/redirect", () => {
expect(res.status).toEqual(401);
});
it("should not accept a transfer token twice", async () => {
const user = await buildUser();
const token = user.getTransferToken();
const first = await server.get(`/auth/redirect?token=${token}`, {
redirect: "manual",
});
expect(first.status).toEqual(302);
const second = await server.get(`/auth/redirect?token=${token}`, {
redirect: "manual",
});
expect(second.status).toEqual(401);
});
it("should not accept a transfer token on the API", async () => {
const user = await buildUser();
const res = await server.post("/api/auth.info", {
headers: {
Authorization: `Bearer ${user.getTransferToken()}`,
},
});
expect(res.status).toEqual(401);
});
});
describe("auth provider routes", () => {
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more