Merge branch 'main' into feat/replace-webpack-with-vite

# Conflicts:
#	package.json
#	yarn.lock
This commit is contained in:
Hans Pagel committed 2023-01-23 17:49:03 +01:00
commit b008898aad
153 files changed
+4608 -5117

No files matched your search

+71 -2
View File
@@ -20,6 +20,8 @@ import {
ShuffleIcon,
HistoryIcon,
LightBulbIcon,
UnpublishIcon,
PublishIcon,
} from "outline-icons";
import * as React from "react";
import { ExportContentType } from "@shared/types";
@@ -128,6 +130,61 @@ export const unstarDocument = createAction({
},
});
export const publishDocument = createAction({
name: ({ t }) => t("Publish"),
section: DocumentSection,
icon: <PublishIcon />,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
const document = stores.documents.get(activeDocumentId);
return (
!!document?.isDraft && stores.policies.abilities(activeDocumentId).update
);
},
perform: ({ activeDocumentId, stores, t }) => {
if (!activeDocumentId) {
return;
}
const document = stores.documents.get(activeDocumentId);
document?.save({
publish: true,
});
stores.toasts.showToast(t("Document published"), {
type: "success",
});
},
});
export const unpublishDocument = createAction({
name: ({ t }) => t("Unpublish"),
section: DocumentSection,
icon: <UnpublishIcon />,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
return stores.policies.abilities(activeDocumentId).unpublish;
},
perform: ({ activeDocumentId, stores, t }) => {
if (!activeDocumentId) {
return;
}
const document = stores.documents.get(activeDocumentId);
document?.unpublish();
stores.toasts.showToast(t("Document unpublished"), {
type: "success",
});
},
});
export const subscribeDocument = createAction({
name: ({ t }) => t("Subscribe"),
section: DocumentSection,
@@ -295,7 +352,17 @@ export const duplicateDocument = createAction({
* of the collection for all collection members to see.
*/
export const pinDocumentToCollection = createAction({
name: ({ t }) => t("Pin to collection"),
name: ({ activeDocumentId = "", t, stores }) => {
const selectedDocument = stores.documents.get(activeDocumentId);
const collectionName = selectedDocument
? stores.documents.getCollectionForDocument(selectedDocument)?.name
: t("collection");
return t("Pin to {{collectionName}}", {
collectionName,
});
},
section: DocumentSection,
icon: <PinIcon />,
iconInContextMenu: false,
@@ -372,7 +439,7 @@ export const printDocument = createAction({
isContextMenu ? t("Print") : t("Print document"),
section: DocumentSection,
icon: <PrintIcon />,
visible: ({ activeDocumentId }) => !!activeDocumentId,
visible: ({ activeDocumentId }) => !!(activeDocumentId && window.print),
perform: async () => {
window.print();
},
@@ -662,6 +729,8 @@ export const rootDocumentActions = [
downloadDocument,
starDocument,
unstarDocument,
publishDocument,
unpublishDocument,
subscribeDocument,
unsubscribeDocument,
duplicateDocument,
+10 -2
View File
@@ -57,8 +57,16 @@ export function actionToMenuItem(
icon,
visible,
dangerous: action.dangerous,
onClick: () => action.perform && action.perform(context),
selected: action.selected ? action.selected(context) : undefined,
onClick: () => {
try {
action.perform?.(context);
} catch (err) {
context.stores.toasts.showToast(err.message, {
type: "error",
});
}
},
selected: action.selected?.(context),
};
}
+2 -3
View File
@@ -2,7 +2,6 @@ import * as React from "react";
import styled from "styled-components";
import useBoolean from "~/hooks/useBoolean";
import Initials from "./Initials";
import placeholder from "./placeholder.png";
export interface IAvatar {
avatarUrl: string | null;
@@ -29,10 +28,10 @@ function Avatar(props: Props) {
return (
<Relative>
{src ? (
{src && !error ? (
<CircleImg
onError={handleError}
src={error ? placeholder : src}
src={src}
$showBorder={showBorder}
{...rest}
/>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 564 B

+1 -1
View File
@@ -13,7 +13,7 @@ function Branding({ href = env.URL }: Props) {
return (
<Link href={href}>
<OutlineIcon size={20} />
&nbsp;Outline
&nbsp;{env.APP_NAME}
</Link>
);
}
+3 -2
View File
@@ -77,8 +77,9 @@ const DocumentBreadcrumb: React.FC<Props> = ({
}
const path = React.useMemo(
() => collection?.pathToDocument?.(document.id).slice(0, -1) || [],
[collection, document]
() => collection?.pathToDocument(document.id).slice(0, -1) || [],
// eslint-disable-next-line react-hooks/exhaustive-deps
[collection, document, document.collectionId, document.parentDocumentId]
);
const items = React.useMemo(() => {
+1 -1
View File
@@ -47,7 +47,7 @@ function GroupListItem({ group, showFacepile, renderActions }: Props) {
</Image>
}
title={<Title onClick={setMembersModalOpen}>{group.name}</Title>}
subtitle={t("{{ count }} members", { count: memberCount })}
subtitle={t("{{ count }} member", { count: memberCount })}
actions={
<Flex align="center" gap={8}>
{showFacepile && (
+24 -10
View File
@@ -51,6 +51,7 @@ const style = {
width: 30,
height: 30,
};
const TwitterPicker = React.lazy(
() =>
import(
@@ -241,7 +242,7 @@ function IconPicker({ onOpen, onClose, icon, color, onChange }: Props) {
aria-label={t("Choose icon")}
>
<Icons>
{Object.keys(icons).map((name) => {
{Object.keys(icons).map((name, index) => {
return (
<MenuItem
key={name}
@@ -249,7 +250,15 @@ function IconPicker({ onOpen, onClose, icon, color, onChange }: Props) {
{...menu}
>
{(props) => (
<IconButton style={style} {...props}>
<IconButton
style={
{
...style,
"--delay": `${index * 8}ms`,
} as React.CSSProperties
}
{...props}
>
<Icon as={icons[name].component} color={color} size={30} />
</IconButton>
)}
@@ -257,7 +266,7 @@ function IconPicker({ onOpen, onClose, icon, color, onChange }: Props) {
);
})}
</Icons>
<Flex>
<Colors>
<React.Suspense fallback={<Loading>{t("Loading")}…</Loading>}>
<ColorPicker
color={color}
@@ -266,6 +275,10 @@ function IconPicker({ onOpen, onClose, icon, color, onChange }: Props) {
triangle="hide"
styles={{
default: {
body: {
padding: 0,
marginRight: -8,
},
hash: {
color: theme.text,
background: theme.inputBorder,
@@ -279,7 +292,7 @@ function IconPicker({ onOpen, onClose, icon, color, onChange }: Props) {
}}
/>
</React.Suspense>
</Flex>
</Colors>
</ContextMenu>
</Wrapper>
);
@@ -287,6 +300,11 @@ function IconPicker({ onOpen, onClose, icon, color, onChange }: Props) {
const Icon = styled.svg`
transition: fill 150ms ease-in-out;
transition-delay: var(--delay);
`;
const Colors = styled(Flex)`
padding: 8px;
`;
const Label = styled.label`
@@ -294,7 +312,7 @@ const Label = styled.label`
`;
const Icons = styled.div`
padding: 16px 8px 0 16px;
padding: 8px;
${breakpoint("tablet")`
width: 276px;
@@ -321,11 +339,7 @@ const Loading = styled(Text)`
const ColorPicker = styled(TwitterPicker)`
box-shadow: none !important;
background: transparent !important;
width: auto !important;
${breakpoint("tablet")`
width: 276px;
`};
width: 100% !important;
`;
const Wrapper = styled("div")`
+3 -1
View File
@@ -6,6 +6,7 @@ import { languages, languageOptions } from "@shared/i18n";
import ButtonLink from "~/components/ButtonLink";
import Flex from "~/components/Flex";
import NoticeTip from "~/components/NoticeTip";
import env from "~/env";
import useCurrentUser from "~/hooks/useCurrentUser";
import useStores from "~/hooks/useStores";
import { detectLanguage } from "~/utils/language";
@@ -57,6 +58,7 @@ export default function LanguagePrompt() {
const option = find(languageOptions, (o) => o.value === language);
const optionLabel = option ? option.label : "";
const appName = env.APP_NAME;
return (
<NoticeTip>
@@ -64,7 +66,7 @@ export default function LanguagePrompt() {
<LanguageIcon />
<span>
<Trans>
Outline is available in your language{" "}
{{ appName }} is available in your language{" "}
{{
optionLabel,
}}
+2 -1
View File
@@ -7,6 +7,7 @@ import Flex from "~/components/Flex";
import { LoadingIndicatorBar } from "~/components/LoadingIndicator";
import SkipNavContent from "~/components/SkipNavContent";
import SkipNavLink from "~/components/SkipNavLink";
import env from "~/env";
import useKeyDown from "~/hooks/useKeyDown";
import { MenuProvider } from "~/hooks/useMenuContext";
import useStores from "~/hooks/useStores";
@@ -36,7 +37,7 @@ const Layout: React.FC<Props> = ({
return (
<Container column auto>
<Helmet>
<title>{title ? title : "Outline"}</title>
<title>{title ? title : env.APP_NAME}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</Helmet>
+4 -2
View File
@@ -2,6 +2,7 @@ import { observer } from "mobx-react";
import * as React from "react";
import { Helmet } from "react-helmet";
import { cdnPath } from "@shared/utils/urls";
import env from "~/env";
import useStores from "~/hooks/useStores";
type Props = {
@@ -16,14 +17,15 @@ const PageTitle = ({ title, favicon }: Props) => {
return (
<Helmet>
<title>
{team?.name ? `${title} - ${team.name}` : `${title} - Outline`}
{team?.name ? `${title} - ${team.name}` : `${title} - ${env.APP_NAME}`}
</title>
{favicon ? (
<link rel="shortcut icon" href={favicon} />
<link rel="shortcut icon" href={favicon} key={favicon} />
) : (
<link
rel="shortcut icon"
type="image/png"
key="favicon"
href={cdnPath("/images/favicon-32.png")}
sizes="32x32"
/>
@@ -27,7 +27,7 @@ import { useStarredContext } from "./StarredContext";
type Props = {
collection: Collection;
expanded?: boolean;
onDisclosureClick: (ev: React.MouseEvent<HTMLButtonElement>) => void;
onDisclosureClick: (ev?: React.MouseEvent<HTMLButtonElement>) => void;
activeDocument: Document | undefined;
isDraggingAnyCollection?: boolean;
};
@@ -62,7 +62,7 @@ const CollectionLink: React.FC<Props> = ({
// Drop to re-parent document
const [{ isOver, canDrop }, drop] = useDrop({
accept: "document",
drop: (item: DragObject, monitor) => {
drop: async (item: DragObject, monitor) => {
const { id, collectionId } = item;
if (monitor.didDrop()) {
return;
@@ -81,7 +81,8 @@ const CollectionLink: React.FC<Props> = ({
if (
prevCollection &&
prevCollection.permission === null &&
prevCollection.permission !== collection.permission
prevCollection.permission !== collection.permission &&
!document?.isDraft
) {
itemRef.current = item;
@@ -97,7 +98,11 @@ const CollectionLink: React.FC<Props> = ({
),
});
} else {
documents.move(id, collection.id);
await documents.move(id, collection.id);
if (!expanded) {
onDisclosureClick();
}
}
},
canDrop: () => canUpdate,
@@ -105,8 +105,7 @@ function InnerDocumentLink(
const handleDisclosureClick = React.useCallback(
(ev) => {
ev.preventDefault();
ev.stopPropagation();
ev?.preventDefault();
setExpanded(!expanded);
},
[expanded]
@@ -150,14 +149,10 @@ function InnerDocumentLink(
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
canDrag: () => {
return (
!isDraft &&
(policies.abilities(node.id).move ||
policies.abilities(node.id).archive ||
policies.abilities(node.id).delete)
);
},
canDrag: () =>
policies.abilities(node.id).move ||
policies.abilities(node.id).archive ||
policies.abilities(node.id).delete,
});
const hoverExpanding = React.useRef<ReturnType<typeof setTimeout>>();
@@ -174,14 +169,15 @@ function InnerDocumentLink(
// Drop to re-parent
const [{ isOverReparent, canDropToReparent }, dropToReparent] = useDrop({
accept: "document",
drop: (item: DragObject, monitor) => {
drop: async (item: DragObject, monitor) => {
if (monitor.didDrop()) {
return;
}
if (!collection) {
return;
}
documents.move(item.id, collection.id, node.id);
await documents.move(item.id, collection.id, node.id);
setExpanded(true);
},
canDrop: (_item, monitor) =>
!isDraft &&
@@ -91,7 +91,7 @@ function DraggableCollectionLink({
}, [collection.id, ui.activeCollectionId, locationStateStarred]);
const handleDisclosureClick = React.useCallback((ev) => {
ev.preventDefault();
ev?.preventDefault();
setExpanded((e) => !e);
}, []);
@@ -46,6 +46,15 @@ function EditableTitle({
[originalValue]
);
const stopPropagation = React.useCallback((event) => {
event.preventDefault();
event.stopPropagation();
}, []);
const handleFocus = React.useCallback((event) => {
event.target.select();
}, []);
const handleSave = React.useCallback(
async (ev) => {
ev.preventDefault();
@@ -85,9 +94,11 @@ function EditableTitle({
dir="auto"
type="text"
value={value}
onClick={stopPropagation}
onKeyDown={handleKeyDown}
onChange={handleChange}
onBlur={handleSave}
onFocus={handleFocus}
autoFocus
{...rest}
/>
@@ -102,11 +113,11 @@ function EditableTitle({
}
const Input = styled.input`
color: ${(props) => props.theme.sidebarText};
color: ${(props) => props.theme.text};
background: ${(props) => props.theme.background};
width: calc(100% + 12px);
border-radius: 3px;
border: 1px solid ${(props) => props.theme.inputBorderFocused};
border: 0;
padding: 5px 6px;
margin: -4px;
height: 32px;
@@ -194,8 +194,17 @@ const Link = styled(NavLink)<{
${(props) =>
props.$isDraft &&
css`
padding: 4px 14px;
border: 1px dashed ${props.theme.sidebarDraftBorder};
&:after {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
border-radius: 4px;
border: 1.5px dashed ${props.theme.sidebarDraftBorder};
}
`}
svg {
@@ -45,7 +45,7 @@ function Starred() {
React.useEffect(() => {
fetchResults();
}, [fetchResults]);
}, []);
const handleShowMore = async () => {
await fetchResults(displayedStarsCount);
+7 -8
View File
@@ -1,6 +1,5 @@
import { NodeSelection } from "prosemirror-state";
import { CellSelection } from "prosemirror-tables";
import { EditorView } from "prosemirror-view";
import * as React from "react";
import { Portal } from "react-portal";
import styled from "styled-components";
@@ -9,10 +8,10 @@ import useComponentSize from "~/hooks/useComponentSize";
import useEventListener from "~/hooks/useEventListener";
import useMediaQuery from "~/hooks/useMediaQuery";
import useViewportHeight from "~/hooks/useViewportHeight";
import { useEditor } from "./EditorContext";
type Props = {
active?: boolean;
view: EditorView;
children: React.ReactNode;
forwardedRef?: React.RefObject<HTMLDivElement> | null;
};
@@ -27,13 +26,13 @@ const defaultPosition = {
function usePosition({
menuRef,
isSelectingText,
props,
active,
}: {
menuRef: React.RefObject<HTMLDivElement>;
isSelectingText: boolean;
props: Props;
active?: boolean;
}) {
const { view, active } = props;
const { view } = useEditor();
const { selection } = view.state;
const { width: menuWidth, height: menuHeight } = useComponentSize(menuRef);
const viewportHeight = useViewportHeight();
@@ -155,14 +154,14 @@ function usePosition({
}
const FloatingToolbar = React.forwardRef(
(props: Props, forwardedRef: React.RefObject<HTMLDivElement>) => {
const menuRef = forwardedRef || React.createRef<HTMLDivElement>();
(props: Props, ref: React.RefObject<HTMLDivElement>) => {
const menuRef = ref || React.createRef<HTMLDivElement>();
const [isSelectingText, setSelectingText] = React.useState(false);
const position = usePosition({
menuRef,
isSelectingText,
props,
active: props.active,
});
useEventListener("mouseup", () => {
+104 -109
View File
@@ -2,152 +2,147 @@ import { EditorView } from "prosemirror-view";
import * as React from "react";
import createAndInsertLink from "@shared/editor/commands/createAndInsertLink";
import { creatingUrlPrefix } from "@shared/utils/urls";
import { Dictionary } from "~/hooks/useDictionary";
import useDictionary from "~/hooks/useDictionary";
import useEventListener from "~/hooks/useEventListener";
import useToasts from "~/hooks/useToasts";
import { useEditor } from "./EditorContext";
import FloatingToolbar from "./FloatingToolbar";
import LinkEditor, { SearchResult } from "./LinkEditor";
type Props = {
isActive: boolean;
view: EditorView;
dictionary: Dictionary;
onCreateLink?: (title: string) => Promise<string>;
onSearchLink?: (term: string) => Promise<SearchResult[]>;
onClickLink: (
href: string,
event: React.MouseEvent<HTMLButtonElement>
) => void;
onShowToast: (message: string) => void;
onClose: () => void;
};
function isActive(props: Props) {
const { view } = props;
const { selection } = view.state;
function isActive(view: EditorView, active: boolean): boolean {
try {
const { selection } = view.state;
const paragraph = view.domAtPos(selection.from);
return props.isActive && !!paragraph.node;
return active && !!paragraph.node;
} catch (err) {
return false;
}
}
export default class LinkToolbar extends React.Component<Props> {
menuRef = React.createRef<HTMLDivElement>();
export default function LinkToolbar({
onCreateLink,
onSearchLink,
onClickLink,
onClose,
...rest
}: Props) {
const dictionary = useDictionary();
const { view } = useEditor();
const { showToast } = useToasts();
const menuRef = React.useRef<HTMLDivElement>(null);
state = {
left: -1000,
top: undefined,
};
componentDidMount() {
window.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
window.removeEventListener("mousedown", this.handleClickOutside);
}
handleClickOutside = (event: Event) => {
useEventListener("mousedown", (event: Event) => {
if (
event.target instanceof HTMLElement &&
this.menuRef.current &&
this.menuRef.current.contains(event.target)
menuRef.current &&
menuRef.current.contains(event.target)
) {
return;
}
this.props.onClose();
};
handleOnCreateLink = async (title: string) => {
const { dictionary, onCreateLink, view, onClose, onShowToast } = this.props;
onClose();
this.props.view.focus();
});
if (!onCreateLink) {
return;
}
const handleOnCreateLink = React.useCallback(
async (title: string) => {
onClose();
view.focus();
const { dispatch, state } = view;
const { from, to } = state.selection;
if (from !== to) {
// selection must be collapsed
return;
}
if (!onCreateLink) {
return;
}
const href = `${creatingUrlPrefix}${title}…`;
const { dispatch, state } = view;
const { from, to } = state.selection;
if (from !== to) {
// selection must be collapsed
return;
}
// Insert a placeholder link
dispatch(
view.state.tr
.insertText(title, from, to)
.addMark(
from,
to + title.length,
state.schema.marks.link.create({ href })
)
);
const href = `${creatingUrlPrefix}#${title}…`;
createAndInsertLink(view, title, href, {
onCreateLink,
onShowToast,
dictionary,
});
};
// Insert a placeholder link
dispatch(
view.state.tr
.insertText(title, from, to)
.addMark(
from,
to + title.length,
state.schema.marks.link.create({ href })
)
);
handleOnSelectLink = ({
href,
title,
}: {
href: string;
title: string;
from: number;
to: number;
}) => {
const { view, onClose } = this.props;
createAndInsertLink(view, title, href, {
onCreateLink,
onShowToast: showToast,
dictionary,
});
},
[onCreateLink, onClose, view, dictionary, showToast]
);
onClose();
this.props.view.focus();
const handleOnSelectLink = React.useCallback(
({
href,
title,
}: {
href: string;
title: string;
from: number;
to: number;
}) => {
onClose();
view.focus();
const { dispatch, state } = view;
const { from, to } = state.selection;
if (from !== to) {
// selection must be collapsed
return;
}
const { dispatch, state } = view;
const { from, to } = state.selection;
if (from !== to) {
// selection must be collapsed
return;
}
dispatch(
view.state.tr
.insertText(title, from, to)
.addMark(
from,
to + title.length,
state.schema.marks.link.create({ href })
)
);
};
dispatch(
view.state.tr
.insertText(title, from, to)
.addMark(
from,
to + title.length,
state.schema.marks.link.create({ href })
)
);
},
[onClose, view]
);
render() {
const { onCreateLink, onClose, ...rest } = this.props;
const { selection } = this.props.view.state;
const active = isActive(this.props);
const { selection } = view.state;
const active = isActive(view, rest.isActive);
return (
<FloatingToolbar ref={this.menuRef} active={active} {...rest}>
{active && (
<LinkEditor
key={`${selection.from}-${selection.to}`}
from={selection.from}
to={selection.to}
onCreateLink={onCreateLink ? this.handleOnCreateLink : undefined}
onSelectLink={this.handleOnSelectLink}
onRemoveLink={onClose}
{...rest}
/>
)}
</FloatingToolbar>
);
}
return (
<FloatingToolbar ref={menuRef} active={active}>
{active && (
<LinkEditor
key={`${selection.from}-${selection.to}`}
from={selection.from}
to={selection.to}
onCreateLink={onCreateLink ? handleOnCreateLink : undefined}
onSelectLink={handleOnSelectLink}
onRemoveLink={onClose}
onShowToast={showToast}
onClickLink={onClickLink}
dictionary={dictionary}
view={view}
/>
)}
</FloatingToolbar>
);
}
+1 -5
View File
@@ -231,11 +231,7 @@ export default class SelectionToolbar extends React.Component<Props> {
}
return (
<FloatingToolbar
view={view}
active={isVisible(this.props)}
ref={this.menuRef}
>
<FloatingToolbar active={isVisible(this.props)} ref={this.menuRef}>
{link && range ? (
<LinkEditor
key={`${range.from}-${range.to}`}
-3
View File
@@ -685,13 +685,10 @@ export class Editor extends React.PureComponent<
onShowToast={this.props.onShowToast}
/>
<LinkToolbar
view={this.view}
dictionary={dictionary}
isActive={this.state.linkMenuOpen}
onCreateLink={this.props.onCreateLink}
onSearchLink={this.props.onSearchLink}
onClickLink={this.props.onClickLink}
onShowToast={this.props.onShowToast}
onClose={this.handleCloseLinkMenu}
/>
<EmojiMenu
+1 -1
View File
@@ -8,7 +8,6 @@ import { Provider } from "mobx-react";
import * as React from "react";
import { render } from "react-dom";
import { Router } from "react-router-dom";
import { initI18n } from "@shared/i18n";
import stores from "~/stores";
import Analytics from "~/components/Analytics";
import Dialogs from "~/components/Dialogs";
@@ -18,6 +17,7 @@ import ScrollToTop from "~/components/ScrollToTop";
import Theme from "~/components/Theme";
import Toasts from "~/components/Toasts";
import env from "~/env";
import { initI18n } from "~/utils/i18n";
import Desktop from "./components/DesktopEventHandler";
import LazyPolyfill from "./components/LazyPolyfills";
import Routes from "./routes";
+4 -15
View File
@@ -1,7 +1,6 @@
import { observer } from "mobx-react";
import {
EditIcon,
UnpublishIcon,
PrintIcon,
NewDocumentIcon,
RestoreIcon,
@@ -39,6 +38,8 @@ import {
archiveDocument,
openDocumentHistory,
openDocumentInsights,
publishDocument,
unpublishDocument,
} from "~/actions/definitions/documents";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
@@ -124,13 +125,6 @@ function DocumentMenu({
[showToast, t, document]
);
const handleUnpublish = React.useCallback(async () => {
await document.unpublish();
showToast(t("Document unpublished"), {
type: "success",
});
}, [showToast, t, document]);
const handlePrint = React.useCallback(() => {
menu.hide();
window.print();
@@ -289,13 +283,8 @@ function DocumentMenu({
actionToMenuItem(importDocument, context),
actionToMenuItem(createTemplate, context),
actionToMenuItem(duplicateDocument, context),
{
type: "button",
title: t("Unpublish"),
onClick: handleUnpublish,
visible: !!can.unpublish,
icon: <UnpublishIcon />,
},
actionToMenuItem(publishDocument, context),
actionToMenuItem(unpublishDocument, context),
actionToMenuItem(archiveDocument, context),
actionToMenuItem(moveDocument, context),
actionToMenuItem(pinDocument, context),
+6 -1
View File
@@ -1,4 +1,4 @@
import { observable } from "mobx";
import { computed, observable } from "mobx";
import BaseModel from "./BaseModel";
import Field from "./decorators/Field";
@@ -14,6 +14,11 @@ class AuthenticationProvider extends BaseModel {
@Field
@observable
isEnabled: boolean;
@computed
get isActive() {
return this.isEnabled && this.isConnected;
}
}
export default AuthenticationProvider;
+8 -5
View File
@@ -171,8 +171,11 @@ export default class Collection extends ParanoidModel {
}
pathToDocument(documentId: string) {
let path: NavigationNode[] | undefined;
let path: NavigationNode[] | undefined = [];
const document = this.store.rootStore.documents.get(documentId);
if (!document) {
return path;
}
const travelNodes = (
nodes: NavigationNode[],
@@ -187,8 +190,8 @@ export default class Collection extends ParanoidModel {
}
if (
document?.parentDocumentId &&
node?.id === document?.parentDocumentId
document.parentDocumentId &&
node.id === document.parentDocumentId
) {
path = [...newPath, document.asNavigationNode];
return;
@@ -199,10 +202,10 @@ export default class Collection extends ParanoidModel {
};
if (this.documents) {
travelNodes(this.documents, []);
travelNodes(this.documents, path);
}
return path || [];
return path;
}
@action
+3 -1
View File
@@ -13,6 +13,7 @@ import ErrorOffline from "~/scenes/ErrorOffline";
import Layout from "~/components/Layout";
import Sidebar from "~/components/Sidebar/Shared";
import Text from "~/components/Text";
import env from "~/env";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import { NavigationNode } from "~/types";
@@ -136,9 +137,10 @@ function SharedDocumentScene(props: Props) {
config?.name && isCloudHosted ? (
<Content>
{t(
"{{ teamName }} is using Outline to share documents, please login to continue.",
"{{ teamName }} is using {{ appName }} to share documents, please login to continue.",
{
teamName: config.name,
appName: env.APP_NAME,
}
)}
</Content>
@@ -102,6 +102,8 @@ const Sticky = styled.div`
max-height: calc(100vh - 80px);
background: ${(props) => props.theme.background};
transition: ${(props) => props.theme.backgroundTransition};
margin-top: 72px;
margin-right: 52px;
min-width: 204px;
-7
View File
@@ -63,13 +63,6 @@ function DocumentMove({ document, onRequestClose }: Props) {
if (onlyShowCollections) {
results = results.filter((result) => result.type === "collection");
} else {
// Exclude root from search results if document is already at the root
if (!document.parentDocumentId) {
results = results.filter(
(result) => result.id !== document.collectionId
);
}
// Exclude document if on the path to result, or the same result
results = results.filter(
(result) =>
+21 -12
View File
@@ -19,6 +19,25 @@ type Props = {
onEmailSuccess: (email: string) => void;
};
function useRedirectHref(authUrl: string) {
// If we're on a custom domain or a subdomain then the auth must point to the
// apex (env.URL) for authentication so that the state cookie can be set and read.
// We pass the host into the auth URL so that the server can redirect on error
// and keep the user on the same page.
const { custom, teamSubdomain, host } = parseDomain(window.location.origin);
const url = new URL(env.URL);
url.pathname = authUrl;
if (custom || teamSubdomain) {
url.searchParams.set("host", host);
}
if (Desktop.isElectron()) {
url.searchParams.set("client", Client.Desktop);
}
return url.toString();
}
function AuthenticationProvider(props: Props) {
const { t } = useTranslation();
const [showEmailSignin, setShowEmailSignin] = React.useState(false);
@@ -57,6 +76,8 @@ function AuthenticationProvider(props: Props) {
}
};
const href = useRedirectHref(authUrl);
if (id === "email") {
if (isCreate) {
return null;
@@ -92,18 +113,6 @@ function AuthenticationProvider(props: Props) {
);
}
// If we're on a custom domain or a subdomain then the auth must point to the
// apex (env.URL) for authentication so that the state cookie can be set and read.
// We pass the host into the auth URL so that the server can redirect on error
// and keep the user on the same page.
const { custom, teamSubdomain, host } = parseDomain(window.location.origin);
const needsRedirect = custom || teamSubdomain;
const href = Desktop.isElectron()
? `${env.URL}${authUrl}?client=${Client.Desktop}`
: needsRedirect
? `${env.URL}${authUrl}?host=${encodeURI(host)}`
: authUrl;
return (
<Wrapper>
<ButtonLarge
+2 -2
View File
@@ -74,8 +74,8 @@ export default function Notices() {
)}
{notice === "suspended" && (
<NoticeAlert>
Your Outline account has been suspended. To re-activate your account,
please contact a team admin.
Your account has been suspended. To re-activate your account, please
contact a team admin.
</NoticeAlert>
)}
{notice === "authentication-provider-disabled" && (
+1 -1
View File
@@ -215,7 +215,7 @@ function Login({ children }: Props) {
<>
<StyledHeading as="h2" centered>
{t("Login to {{ authProviderName }}", {
authProviderName: config.name || "Outline",
authProviderName: config.name || env.APP_NAME,
})}
</StyledHeading>
{children?.(config)}
+6 -3
View File
@@ -12,6 +12,7 @@ import Item from "~/components/List/Item";
import PaginatedList from "~/components/PaginatedList";
import Scene from "~/components/Scene";
import Text from "~/components/Text";
import env from "~/env";
import useStores from "~/hooks/useStores";
import FileOperationListItem from "./components/FileOperationListItem";
import ImportNotionDialog from "./components/ImportNotionDialog";
@@ -20,6 +21,7 @@ import ImportOutlineDialog from "./components/ImportOutlineDialog";
function Import() {
const { t } = useTranslation();
const { dialogs, fileOperations } = useStores();
const appName = env.APP_NAME;
return (
<Scene title={t("Import")} icon={<NewDocumentIcon color="currentColor" />}>
@@ -27,8 +29,9 @@ function Import() {
<Text type="secondary">
<Trans>
Quickly transfer your existing documents, pages, and files from other
tools and services into Outline. You can also drag and drop any HTML,
Markdown, and text documents directly into Collections in the app.
tools and services into {{ appName }}. You can also drag and drop any
HTML, Markdown, and text documents directly into Collections in the
app.
</Trans>
</Text>
@@ -38,7 +41,7 @@ function Import() {
image={<MarkdownIcon size={28} />}
title={t("Markdown")}
subtitle={t(
"Import a zip file of Markdown documents (exported from Outline 0.67.0 or earlier)"
"Import a zip file of Markdown documents (exported from version 0.67.0 or earlier)"
)}
actions={
<Button
+6 -3
View File
@@ -16,6 +16,7 @@ import InputSearch from "~/components/InputSearch";
import Modal from "~/components/Modal";
import Scene from "~/components/Scene";
import Text from "~/components/Text";
import env from "~/env";
import useBoolean from "~/hooks/useBoolean";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import usePolicy from "~/hooks/usePolicy";
@@ -142,6 +143,8 @@ function Members() {
[params, history, location.pathname]
);
const appName = env.APP_NAME;
return (
<Scene
title={t("Members")}
@@ -168,9 +171,9 @@ function Members() {
<Heading>{t("Members")}</Heading>
<Text type="secondary">
<Trans>
Everyone that has signed into Outline appears here. It’s possible that
there are other users who have access through {team.signinMethods} but
haven’t signed in yet.
Everyone that has signed into {{ appName }} is listed here. It’s
possible that there are other users who have access through{" "}
{team.signinMethods} but haven’t signed in yet.
</Trans>
</Text>
<Flex gap={8}>
+1 -3
View File
@@ -62,9 +62,7 @@ function Notifications() {
visible: isCloudHosted,
event: "emails.onboarding",
title: t("Getting started"),
description: t(
"Tips on getting started with Outline’s features and functionality"
),
description: t("Tips on getting started with features and functionality"),
},
{
visible: isCloudHosted,
+7 -2
View File
@@ -165,8 +165,13 @@ function Security() {
})}
>
<Flex align="center">
<CheckboxIcon color={theme.primary} checked />{" "}
<Text type="secondary">{t("Connected")}</Text>
<CheckboxIcon
color={provider.isActive ? theme.primary : undefined}
checked={provider.isActive}
/>{" "}
<Text type="secondary">
{provider.isActive ? t("Connected") : t("Disabled")}
</Text>
</Flex>
</SettingRow>
))}
+7 -4
View File
@@ -53,6 +53,8 @@ function Slack() {
})
.sort((a) => (a[1] ? -1 : 1));
const appName = env.APP_NAME;
return (
<Scene title="Slack" icon={<SlackIcon color="currentColor" />}>
<Heading>Slack</Heading>
@@ -61,7 +63,7 @@ function Slack() {
<Notice>
<Trans>
Whoops, you need to accept the permissions in Slack to connect
Outline to your team. Try again?
{{ appName }} to your team. Try again?
</Trans>
</Notice>
)}
@@ -75,9 +77,10 @@ function Slack() {
)}
<Text type="secondary">
<Trans
defaults="Get rich previews of Outline links shared in Slack and use the <em>{{ command }}</em> slash command to search for documents without leaving your chat."
defaults="Get rich previews of {{ appName }} links shared in Slack and use the <em>{{ command }}</em> slash command to search for documents without leaving your chat."
values={{
command: "/outline",
appName,
}}
components={{
em: <Code />,
@@ -112,8 +115,8 @@ function Slack() {
<h2>{t("Collections")}</h2>
<Text type="secondary">
<Trans>
Connect Outline collections to Slack channels and messages will be
automatically posted to Slack when documents are published or
Connect {{ appName }} collections to Slack channels. Messages will
be automatically posted to Slack when documents are published or
updated.
</Trans>
</Text>
+7 -1
View File
@@ -11,6 +11,7 @@ import PaginatedList from "~/components/PaginatedList";
import Scene from "~/components/Scene";
import Subheading from "~/components/Subheading";
import Text from "~/components/Text";
import env from "~/env";
import useBoolean from "~/hooks/useBoolean";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import usePolicy from "~/hooks/usePolicy";
@@ -24,6 +25,7 @@ function Webhooks() {
const { webhookSubscriptions } = useStores();
const [newModalOpen, handleNewModalOpen, handleNewModalClose] = useBoolean();
const can = usePolicy(team);
const appName = env.APP_NAME;
return (
<Scene
@@ -45,7 +47,11 @@ function Webhooks() {
>
<Heading>{t("Webhooks")}</Heading>
<Text type="secondary">
<Trans defaults="Webhooks can be used to notify your application when events happen in Outline. Events are sent as a https request with a JSON payload in near real-time." />
<Trans>
Webhooks can be used to notify your application when events happen in{" "}
{{ appName }}. Events are sent as a https request with a JSON payload
in near real-time.
</Trans>
</Text>
<PaginatedList
fetch={webhookSubscriptions.fetchPage}
+5 -3
View File
@@ -5,11 +5,13 @@ import Heading from "~/components/Heading";
import ZapierIcon from "~/components/Icons/ZapierIcon";
import Scene from "~/components/Scene";
import Text from "~/components/Text";
import env from "~/env";
import useStores from "~/hooks/useStores";
function Zapier() {
const { ui } = useStores();
const { resolvedTheme } = ui;
const appName = env.APP_NAME;
return (
<Scene title="Zapier" icon={<ZapierIcon color="currentColor" />}>
@@ -28,9 +30,9 @@ function Zapier() {
</Helmet>
<Text type="secondary">
<Trans>
Zapier is a platform that allows Outline to easily integrate with
thousands of other business tools. Automate your workflows, sync data,
and more.
Zapier is a platform that allows {{ appName }} to easily integrate
with thousands of other business tools. Automate your workflows, sync
data, and more.
</Trans>
</Text>
<br />
@@ -2,12 +2,14 @@ import * as React from "react";
import { Trans } from "react-i18next";
import Flex from "~/components/Flex";
import Text from "~/components/Text";
import env from "~/env";
import useStores from "~/hooks/useStores";
import DropToImport from "./DropToImport";
import HelpDisclosure from "./HelpDisclosure";
function ImportOutlineDialog() {
const { dialogs } = useStores();
const appName = env.APP_NAME;
return (
<Flex column>
@@ -17,8 +19,8 @@ function ImportOutlineDialog() {
format="outline-markdown"
>
<Trans>
Drag and drop the zip file from Outline's Markdown export option, or
click to upload
Drag and drop the zip file from the Markdown export option in{" "}
{{ appName }}, or click to upload
</Trans>
</DropToImport>
</Text>
+3 -2
View File
@@ -56,6 +56,7 @@ function UserDelete() {
const inputProps = register("code", {
required: true,
});
const appName = env.APP_NAME;
return (
<Flex column>
@@ -91,8 +92,8 @@ function UserDelete() {
<Trans>
Are you sure? Deleting your account will destroy identifying
data associated with your user and cannot be undone. You will be
immediately logged out of Outline and all your API tokens will
be revoked.
immediately logged out of {{ appName }} and all your API tokens
will be revoked.
</Trans>
</Text>
</>
+21 -12
View File
@@ -686,15 +686,24 @@ export default class DocumentsStore extends BaseStore<Document> {
lastRevision: number;
}
) {
const document = await super.update(params, options);
this.isSaving = true;
// Because the collection object contains the url and title
// we need to ensure they are updated there as well.
const collection = this.getCollectionForDocument(document);
if (collection) {
collection.updateDocument(document);
try {
const res = await client.post(`/${this.apiEndpoint}.update`, {
...params,
...options,
apiVersion: 2,
});
invariant(res?.data, "Data should be available");
this.addPolicies(res.policies);
const document = this.add(res.data.document);
const collection = this.getCollectionForDocument(document);
collection?.updateFromJson(res.data.collection);
return document;
} finally {
this.isSaving = false;
}
return document;
}
@action
@@ -763,16 +772,16 @@ export default class DocumentsStore extends BaseStore<Document> {
unpublish = async (document: Document) => {
const res = await client.post("/documents.unpublish", {
id: document.id,
apiVersion: 2,
});
runInAction("Document#unpublish", () => {
invariant(res?.data, "Data should be available");
document.updateFromJson(res.data);
document.updateFromJson(res.data.document);
const collection = this.getCollectionForDocument(document);
collection?.updateFromJson(res.data.collection);
this.addPolicies(res.policies);
});
const collection = this.getCollectionForDocument(document);
if (collection) {
collection.refresh();
}
};
star = (document: Document) => {
+1 -1
View File
@@ -3,7 +3,7 @@
import localStorage from "../../__mocks__/localStorage";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { initI18n } from "@shared/i18n";
import { initI18n } from "../utils/i18n";
initI18n();
@@ -1,8 +1,8 @@
import i18n from "i18next";
import de_DE from "./locales/de_DE/translation.json";
import en_US from "./locales/en_US/translation.json";
import pt_PT from "./locales/pt_PT/translation.json";
import { initI18n } from ".";
import de_DE from "../../shared/i18n/locales/de_DE/translation.json";
import en_US from "../../shared/i18n/locales/en_US/translation.json";
import pt_PT from "../../shared/i18n/locales/pt_PT/translation.json";
import { initI18n } from "./i18n";
describe("i18n env is unset", () => {
beforeEach(() => {
+49 -2
View File
@@ -17,6 +17,11 @@ import {
zhCN,
zhTW,
} from "date-fns/locale";
import i18n from "i18next";
import backend from "i18next-http-backend";
import { initReactI18next } from "react-i18next";
import { languages } from "@shared/i18n";
import { unicodeCLDRtoBCP47, unicodeBCP47toCLDR } from "@shared/utils/date";
const locales = {
de_DE: de,
@@ -38,8 +43,50 @@ const locales = {
zh_TW: zhTW,
};
export function dateLocale(userLocale: string | null | undefined) {
return userLocale ? locales[userLocale] : undefined;
/**
* Returns the date-fns locale object for the given user language preference.
*
* @param language The user language
* @returns The date-fns locale.
*/
export function dateLocale(language: string | null | undefined) {
return language ? locales[language] : undefined;
}
/**
* Initializes i18n library, loading all available translations from the
* API backend.
*
* @param defaultLanguage The default language to use if the user's language
* is not supported.
* @returns i18n instance
*/
export function initI18n(defaultLanguage = "en_US") {
const lng = unicodeCLDRtoBCP47(defaultLanguage);
i18n
.use(backend)
.use(initReactI18next)
.init({
compatibilityJSON: "v3",
backend: {
// this must match the path defined in routes. It's the path that the
// frontend UI code will hit to load missing translations.
loadPath: (languages: string[]) =>
`/locales/${unicodeBCP47toCLDR(languages[0])}.json`,
},
interpolation: {
escapeValue: false,
},
react: {
useSuspense: false,
},
lng,
fallbackLng: lng,
supportedLngs: languages.map(unicodeCLDRtoBCP47),
keySeparator: false,
returnNull: false,
});
return i18n;
}
export { locales };
+2 -2
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/bin/sh
yarn babel --extensions .ts,.tsx --quiet -d ./build/server ./server
yarn babel --extensions .ts,.tsx --quiet -d ./build/shared ./shared
@@ -10,4 +10,4 @@ cp ./server/static/error.dev.html ./build/server/error.dev.html
cp ./server/static/error.prod.html ./build/server/error.prod.html
# Link webpack config
ln -sf \"$(pwd)/webpack.config.dev.js\" ./build
ln -sf "$(pwd)/webpack.config.dev.js" ./build
+3 -14
View File
@@ -8,7 +8,9 @@ module.exports = {
defaultNamespace: "translation",
// Default namespace used in your i18next config
defaultValue: "",
defaultValue(locale, namespace, key) {
return key;
},
// Default value to give to empty keys
indentation: 2,
@@ -60,10 +62,6 @@ module.exports = {
skipDefaultValues: false,
// Whether to ignore default values.
useKeysAsDefaultValue: true,
// Whether to use the keys as the default value; ex. "Hello": "Hello", "World": "World"
// This option takes precedence over the `defaultValue` and `skipDefaultValues` options
verbose: false,
// Display info about the parsing including some stats
@@ -71,15 +69,6 @@ module.exports = {
// Exit with an exit code of 1 on warnings
customValueTemplate: null,
// If you wish to customize the value output the value as an object, you can set your own format.
// ${defaultValue} is the default value you set in your translation function.
// Any other custom property will be automatically extracted.
//
// Example:
// {
// message: "${defaultValue}",
// description: "${maxLength}", // t('my-key', {maxLength: 150})
// }
i18nextOptions: {
compatibilityJSON: "v3",
+10 -11
View File
@@ -8,16 +8,14 @@
"copy:i18n": "mkdir -p ./build/shared/i18n && cp -R ./shared/i18n/locales ./build/shared/i18n",
"build:i18n": "i18next --silent 'shared/**/*.tsx' 'shared/**/*.ts' 'app/**/*.tsx' 'app/**/*.ts' 'server/**/*.ts' 'server/**/*.tsx' && yarn copy:i18n",
"build:server": "./build.sh",
"build": "yarn vite:build && yarn build:i18n && yarn build:server",
"build": "yarn clean && yarn vite:build && yarn build:i18n && yarn build:server",
"start": "node ./build/server/index.js",
"dev": "NODE_ENV=development yarn concurrently -n api,frontend,collaboration -c \"blue,magenta\" \"node --inspect=0.0.0.0 build/server/index.js --services=collaboration,websockets,admin,web,worker\" \"yarn vite:dev\"",
"dev:watch": "nodemon --exec \"yarn build:server && yarn dev\" -e js,ts,tsx --ignore build/ --ignore app/ --ignore shared/editor",
"lint": "eslint app server shared",
"deploy": "git push heroku master",
"prepare": "husky install",
"postinstall": "rimraf node_modules/prosemirror-view/dist/index.d.ts && patch-package",
"heroku-postbuild": "yarn vite:build && yarn build:server && yarn copy:i18n && yarn db:migrate",
"sequelize:migrate": "sequelize db:migrate",
"db:create-migration": "sequelize migration:create",
"db:create": "sequelize db:create",
"db:migrate": "sequelize db:migrate",
@@ -62,7 +60,7 @@
"@getoutline/y-prosemirror": "^1.0.18",
"@hocuspocus/provider": "^1.0.0-beta.6",
"@hocuspocus/server": "^1.0.0-beta.6",
"@joplin/turndown-plugin-gfm": "^1.0.44",
"@joplin/turndown-plugin-gfm": "^1.0.45",
"@juggle/resize-observer": "^3.4.0",
"@outlinewiki/koa-passport": "^4.2.1",
"@outlinewiki/passport-azure-ad-oauth2": "^0.1.0",
@@ -75,7 +73,7 @@
"@types/mermaid": "^9.1.0",
"@vitejs/plugin-react": "^3.0.0",
"autotrack": "^2.4.1",
"aws-sdk": "^2.1189.0",
"aws-sdk": "^2.1290.0",
"babel-plugin-lodash": "^3.3.4",
"babel-plugin-styled-components": "^2.0.7",
"babel-plugin-transform-class-properties": "^6.24.1",
@@ -106,14 +104,15 @@
"fuzzy-search": "^3.2.1",
"gemoji": "6.x",
"http-errors": "2.0.0",
"i18next": "^22.4.6",
"i18next": "^22.4.8",
"i18next-fs-backend": "^2.1.1",
"i18next-http-backend": "^2.1.1",
"immutable": "^4.0.0",
"inline-css": "^4.0.1",
"invariant": "^2.2.4",
"ioredis": "^5.0.0",
"is-printable-key-event": "^1.0.0",
"jsdom": "^20.0.3",
"jsdom": "^21.0.0",
"json-loader": "0.5.7",
"jsonwebtoken": "^9.0.0",
"jszip": "^3.10.1",
@@ -181,7 +180,7 @@
"react-dom": "^17.0.2",
"react-dropzone": "^11.3.2",
"react-helmet": "^6.1.0",
"react-hook-form": "^7.37.0",
"react-hook-form": "^7.41.5",
"react-i18next": "^12.1.1",
"react-merge-refs": "^2.0.1",
"react-portal": "^4.2.0",
@@ -231,7 +230,7 @@
},
"devDependencies": {
"@babel/cli": "^7.10.5",
"@babel/preset-typescript": "^7.16.0",
"@babel/preset-typescript": "^7.18.6",
"@getoutline/jest-runner-serial": "^2.0.0",
"@relative-ci/agent": "^3.0.0",
"@types/body-scroll-lock": "^3.1.0",
@@ -304,7 +303,7 @@
"@types/utf8": "^3.0.1",
"@types/validator": "^13.7.10",
"@typescript-eslint/eslint-plugin": "^5.40.0",
"@typescript-eslint/parser": "^5.40.0",
"@typescript-eslint/parser": "^5.48.1",
"babel-eslint": "^10.1.0",
"babel-jest": "^29.3.1",
"babel-loader": "^8.1.0",
@@ -355,5 +354,5 @@
"jpeg-js": "0.4.4",
"qs": "6.9.7"
},
"version": "0.66.2"
"version": "0.67.2"
}
@@ -0,0 +1,64 @@
import {
Extension,
onConnectPayload,
onDisconnectPayload,
} from "@hocuspocus/server";
import env from "@server/env";
import Logger from "@server/logging/Logger";
import { trace } from "@server/logging/tracing";
@trace()
export class ConnectionLimitExtension implements Extension {
/**
* Map of documentId -> connection count
*/
connectionsByDocument: Map<string, number> = new Map();
/**
* onDisconnect hook
* @param data The disconnect payload
*/
onDisconnect(data: onDisconnectPayload) {
const { documentName } = data;
const currConnections = this.connectionsByDocument.get(documentName) || 0;
const newConnections = currConnections - 1;
this.connectionsByDocument.set(documentName, newConnections);
Logger.debug(
"multiplayer",
`${newConnections} connections to "${documentName}"`
);
return Promise.resolve();
}
/**
* onConnect hook
* @param data The connect payload
*/
onConnect(data: onConnectPayload) {
const { documentName } = data;
const currConnections = this.connectionsByDocument.get(documentName) || 0;
if (currConnections >= env.COLLABORATION_MAX_CLIENTS_PER_DOCUMENT) {
Logger.info(
"multiplayer",
`Rejected connection to "${documentName}" because it has reached the maximum number of connections`
);
// Rejecting the promise will cause the connection to be dropped.
return Promise.reject();
}
const newConnections = currConnections + 1;
this.connectionsByDocument.set(documentName, newConnections);
Logger.debug(
"multiplayer",
`${newConnections} connections to "${documentName}"`
);
return Promise.resolve();
}
}
+8 -4
View File
@@ -86,13 +86,17 @@ export default class PersistenceExtension implements Extension {
const [, documentId] = documentName.split(".");
// Find the collaborators that have modified the document since it was last
// persisted and clear the map.
// persisted and clear the map, if there's no collaborators then we don't
// need to persist the document.
const documentCollaboratorIds = this.documentCollaboratorIds.get(
documentName
);
const collaboratorIds = documentCollaboratorIds
? Array.from(documentCollaboratorIds.values())
: [context.user?.id];
if (!documentCollaboratorIds) {
Logger.debug("multiplayer", `No changes for ${documentName}`);
return;
}
const collaboratorIds = Array.from(documentCollaboratorIds.values());
this.documentCollaboratorIds.delete(documentName);
try {
+24 -25
View File
@@ -1,10 +1,6 @@
import { sequelize } from "@server/database/sequelize";
import Pin from "@server/models/Pin";
import {
buildDocument,
buildCollection,
buildUser,
} from "@server/test/factories";
import { buildDocument, buildCollection } from "@server/test/factories";
import { setupTestDatabase, seed } from "@server/test/support";
import documentMover from "./documentMover";
@@ -25,28 +21,31 @@ describe("documentMover", () => {
expect(response.documents.length).toEqual(1);
});
it("should error when not in source collection documentStructure", async () => {
const user = await buildUser();
const collection = await buildCollection({
teamId: user.teamId,
});
const document = await buildDocument({
it("should succeed when not in source collection documentStructure", async () => {
const { document, user, collection } = await seed();
const newDocument = await buildDocument({
parentDocumentId: document.id,
collectionId: collection.id,
teamId: collection.teamId,
userId: collection.createdById,
title: "Child document",
text: "content",
});
await document.archive(user.id);
let error;
try {
await documentMover({
user,
document,
collectionId: collection.id,
ip,
});
} catch (err) {
error = err;
}
expect(error).toBeTruthy();
const response = await documentMover({
user,
document,
collectionId: collection.id,
parentDocumentId: undefined,
index: 0,
ip,
});
expect(response.collections[0].documentStructure![0].children[0].id).toBe(
newDocument.id
);
expect(response.collections.length).toEqual(1);
expect(response.documents.length).toEqual(1);
expect(response.documents[0].collection?.id).toEqual(collection.id);
expect(response.documents[0].updatedBy.id).toEqual(user.id);
});
it("should move with children", async () => {
+42 -34
View File
@@ -1,6 +1,5 @@
import invariant from "invariant";
import { Transaction } from "sequelize";
import { ValidationError } from "@server/errors";
import { traceFunction } from "@server/logging/tracing";
import { User, Document, Collection, Pin, Event } from "@server/models";
import pinDestroyer from "./pinDestroyer";
@@ -67,43 +66,52 @@ async function documentMover({
invariant(newCollection, "collection should exist");
// Remove the document from the current collection
const response = await collection?.removeDocumentInStructure(document, {
transaction,
});
if (document.publishedAt) {
// Remove the document from the current collection
const response = await collection?.removeDocumentInStructure(document, {
transaction,
save: collectionChanged,
});
const documentJson = response?.[0];
const fromIndex = response?.[1] || 0;
let documentJson = response?.[0];
const fromIndex = response?.[1] || 0;
if (!documentJson) {
throw ValidationError("The document was not found in the collection");
if (!documentJson) {
documentJson = await document.toNavigationNode({ transaction });
}
// if we're reordering from within the same parent
// the original and destination collection are the same,
// so when the initial item is removed above, the list will reduce by 1.
// We need to compensate for this when reordering
const toIndex =
index !== undefined &&
document.parentDocumentId === parentDocumentId &&
document.collectionId === collectionId &&
fromIndex < index
? index - 1
: index;
// Update the properties on the document record, this must be done after
// the toIndex is calculated above
document.collectionId = collectionId;
document.parentDocumentId = parentDocumentId;
document.lastModifiedById = user.id;
document.updatedBy = user;
// Add the document and it's tree to the new collection
await newCollection.addDocumentToStructure(document, toIndex, {
documentJson,
transaction,
});
} else {
document.collectionId = collectionId;
document.parentDocumentId = parentDocumentId;
document.lastModifiedById = user.id;
document.updatedBy = user;
}
// if we're reordering from within the same parent
// the original and destination collection are the same,
// so when the initial item is removed above, the list will reduce by 1.
// We need to compensate for this when reordering
const toIndex =
index !== undefined &&
document.parentDocumentId === parentDocumentId &&
document.collectionId === collectionId &&
fromIndex < index
? index - 1
: index;
// Update the properties on the document record
document.collectionId = collectionId;
document.parentDocumentId = parentDocumentId;
document.lastModifiedById = user.id;
document.updatedBy = user;
// Add the document and it's tree to the new collection
await newCollection.addDocumentToStructure(document, toIndex, {
documentJson,
transaction,
});
if (collection) {
if (collection && document.publishedAt) {
result.collections.push(collection);
}
+6 -2
View File
@@ -1,4 +1,5 @@
import nodemailer, { Transporter } from "nodemailer";
import SMTPTransport from "nodemailer/lib/smtp-transport";
import Oy from "oy-vey";
import env from "@server/env";
import Logger from "@server/logging/Logger";
@@ -101,8 +102,9 @@ export class Mailer {
}
};
private getOptions() {
private getOptions(): SMTPTransport.Options {
return {
name: env.SMTP_NAME,
host: env.SMTP_HOST,
port: env.SMTP_PORT,
secure: env.SMTP_SECURE ?? env.ENVIRONMENT === "production",
@@ -124,7 +126,9 @@ export class Mailer {
};
}
private async getTestTransportOptions() {
private async getTestTransportOptions(): Promise<
SMTPTransport.Options | undefined
> {
try {
const testAccount = await nodemailer.createTestAccount();
return {
@@ -1,4 +1,5 @@
import * as React from "react";
import env from "@server/env";
import BaseEmail from "./BaseEmail";
import Body from "./components/Body";
import CopyableCode from "./components/CopyableCode";
@@ -27,7 +28,7 @@ export default class ConfirmUserDeleteEmail extends BaseEmail<Props> {
protected renderAsText({ deleteConfirmationCode }: Props): string {
return `
You requested to permanantly delete your Outline account. Please enter the code below to confirm your account deletion.
You requested to permanantly delete your ${env.APP_NAME} account. Please enter the code below to confirm your account deletion.
Code: ${deleteConfirmationCode}
`;
@@ -41,8 +42,8 @@ Code: ${deleteConfirmationCode}
<Body>
<Heading>Your account deletion request</Heading>
<p>
You requested to permanantly delete your Outline account. Please
enter the code below to confirm your account deletion.
You requested to permanantly delete your {env.APP_NAME} account.
Please enter the code below to confirm your account deletion.
</p>
<EmptySpace height={5} />
<p>
@@ -1,4 +1,5 @@
import * as React from "react";
import env from "@server/env";
import { NotificationSetting } from "@server/models";
import BaseEmail from "./BaseEmail";
import Body from "./components/Body";
@@ -39,7 +40,7 @@ export default class ExportSuccessEmail extends BaseEmail<Props> {
}
protected preview() {
return "Here's your request data export from Outline";
return `Here's your request data export from ${env.APP_NAME}`;
}
protected renderAsText() {
@@ -1,4 +1,5 @@
import * as React from "react";
import env from "@server/env";
import { NotificationSetting } from "@server/models";
import BaseEmail from "./BaseEmail";
import Body from "./components/Body";
@@ -39,7 +40,7 @@ export default class InviteAcceptedEmail extends BaseEmail<Props> {
}
protected subject({ invitedName }: Props) {
return `${invitedName} has joined your Outline team`;
return `${invitedName} has joined your ${env.APP_NAME} team`;
}
protected preview({ invitedName }: Props) {
@@ -50,7 +51,7 @@ export default class InviteAcceptedEmail extends BaseEmail<Props> {
return `
Great news, ${invitedName} just accepted your invitation and has created an account. You can now start collaborating on documents.
Open Outline: ${teamUrl}
Open ${env.APP_NAME}: ${teamUrl}
`;
}
@@ -71,7 +72,7 @@ Open Outline: ${teamUrl}
</p>
<EmptySpace height={10} />
<p>
<Button href={teamUrl}>Open Outline</Button>
<Button href={teamUrl}>Open {env.APP_NAME}</Button>
</p>
</Body>
+9 -6
View File
@@ -1,4 +1,5 @@
import * as React from "react";
import env from "@server/env";
import BaseEmail from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
@@ -26,7 +27,7 @@ export default class InviteEmail extends BaseEmail<Props> {
}
protected preview() {
return "Outline is a place for your team to build and share knowledge.";
return `${env.APP_NAME} is a place for your team to build and share knowledge.`;
}
protected renderAsText({
@@ -36,9 +37,9 @@ export default class InviteEmail extends BaseEmail<Props> {
teamUrl,
}: Props): string {
return `
Join ${teamName} on Outline
Join ${teamName} on ${env.APP_NAME}
${actorName} (${actorEmail}) has invited you to join Outline, a place for your team to build and share knowledge.
${actorName} (${actorEmail}) has invited you to join ${env.APP_NAME}, a place for your team to build and share knowledge.
Join now: ${teamUrl}
`;
@@ -50,10 +51,12 @@ Join now: ${teamUrl}
<Header />
<Body>
<Heading>Join {teamName} on Outline</Heading>
<Heading>
Join {teamName} on {env.APP_NAME}
</Heading>
<p>
{actorName} ({actorEmail}) has invited you to join Outline, a place
for your team to build and share knowledge.
{actorName} ({actorEmail}) has invited you to join {env.APP_NAME}, a
place for your team to build and share knowledge.
</p>
<EmptySpace height={10} />
<p>
@@ -1,4 +1,5 @@
import * as React from "react";
import env from "@server/env";
import BaseEmail from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
@@ -27,7 +28,7 @@ export default class InviteReminderEmail extends BaseEmail<Props> {
}
protected preview() {
return "Outline is a place for your team to build and share knowledge.";
return `${env.APP_NAME} is a place for your team to build and share knowledge.`;
}
protected renderAsText({
@@ -37,7 +38,7 @@ export default class InviteReminderEmail extends BaseEmail<Props> {
teamUrl,
}: Props): string {
return `
This is just a quick reminder that ${actorName} (${actorEmail}) invited you to join them in the ${teamName} team on Outline, a place for your team to build and share knowledge.
This is just a quick reminder that ${actorName} (${actorEmail}) invited you to join them in the ${teamName} team on ${env.APP_NAME}, a place for your team to build and share knowledge.
We only send a reminder once.
If you haven't signed up yet, you can do so here: ${teamUrl}
@@ -50,11 +51,13 @@ If you haven't signed up yet, you can do so here: ${teamUrl}
<Header />
<Body>
<Heading>Join {teamName} on Outline</Heading>
<Heading>
Join {teamName} on {env.APP_NAME}
</Heading>
<p>
This is just a quick reminder that {actorName} ({actorEmail})
invited you to join them in the {teamName} team on Outline, a place
for your team to build and share knowledge.
invited you to join them in the {teamName} team on {env.APP_NAME}, a
place for your team to build and share knowledge.
</p>
<p>If you haven't signed up yet, you can do so here:</p>
<EmptySpace height={10} />
+3 -3
View File
@@ -27,12 +27,12 @@ export default class SigninEmail extends BaseEmail<Props> {
}
protected preview(): string {
return "Here’s your link to signin to Outline.";
return `Here’s your link to signin to ${env.APP_NAME}.`;
}
protected renderAsText({ token, teamUrl, client }: Props): string {
return `
Use the link below to signin to Outline:
Use the link below to signin to ${env.APP_NAME}:
${this.signinLink(token, client)}
@@ -52,7 +52,7 @@ signin page at: ${teamUrl}
<Body>
<Heading>Magic Sign-in Link</Heading>
<p>Click the button below to sign in to Outline.</p>
<p>Click the button below to sign in to {env.APP_NAME}.</p>
<EmptySpace height={10} />
<p>
<Button href={this.signinLink(token, client)}>Sign In</Button>
+11 -7
View File
@@ -1,4 +1,5 @@
import * as React from "react";
import env from "@server/env";
import BaseEmail from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
@@ -19,18 +20,18 @@ type Props = {
*/
export default class WelcomeEmail extends BaseEmail<Props> {
protected subject() {
return "Welcome to Outline";
return `Welcome to ${env.APP_NAME}`;
}
protected preview() {
return "Outline is a place for your team to build and share knowledge.";
return `${env.APP_NAME} is a place for your team to build and share knowledge.`;
}
protected renderAsText({ teamUrl }: Props) {
return `
Welcome to Outline!
Welcome to ${env.APP_NAME}!
Outline is a place for your team to build and share knowledge.
${env.APP_NAME} is a place for your team to build and share knowledge.
To get started, head to the home screen and try creating a collection to help document your processes, create playbooks, or plan your teams work.
@@ -46,8 +47,11 @@ ${teamUrl}/home
<Header />
<Body>
<Heading>Welcome to Outline!</Heading>
<p>Outline is a place for your team to build and share knowledge.</p>
<Heading>Welcome to {env.APP_NAME}!</Heading>
<p>
{env.APP_NAME} is a place for your team to build and share
knowledge.
</p>
<p>
To get started, head to the home screen and try creating a
collection to help document your processes, create playbooks, or
@@ -60,7 +64,7 @@ ${teamUrl}/home
<EmptySpace height={10} />
<p>
<Button href={`${teamUrl}/home?ref=welcome-email`}>
Open Outline
Open {env.APP_NAME}
</Button>
</p>
</Body>
@@ -37,7 +37,7 @@ export default ({ unsubscribeUrl }: Props) => {
<TR>
<TD style={footerStyle}>
<a href={env.URL} style={linkStyle}>
Outline
{env.APP_NAME}
</a>
<a href={twitterUrl()} style={externalLinkStyle}>
Twitter
@@ -14,7 +14,7 @@ export default () => {
<TD>
<EmptySpace height={40} />
<img
alt="Outline"
alt={env.APP_NAME}
src={
isCloudHosted
? `${url}/email/header-logo.png`
+22
View File
@@ -147,6 +147,17 @@ export class Environment {
process.env.COLLABORATION_URL
);
/**
* The maximum number of network clients that can be connected to a single
* document at once. Defaults to 100.
*/
@IsOptional()
@IsNumber()
public COLLABORATION_MAX_CLIENTS_PER_DOCUMENT = parseInt(
process.env.COLLABORATION_MAX_CLIENTS_PER_DOCUMENT || "100",
10
);
/**
* The port that the server will listen on, defaults to 3000.
*/
@@ -264,6 +275,12 @@ export class Environment {
*/
public SMTP_HOST = process.env.SMTP_HOST;
/**
* Optional hostname of the client, used for identifying to the server
* defaults to hostname of the machine.
*/
public SMTP_NAME = process.env.SMTP_NAME;
/**
* The port of your SMTP server.
*/
@@ -553,6 +570,11 @@ export class Environment {
@IsOptional()
public AWS_S3_ACL = process.env.AWS_S3_ACL ?? "private";
/**
* The product name
*/
public APP_NAME = "Outline";
private toOptionalString(value: string | undefined) {
return value ? value : undefined;
}
+5 -5
View File
@@ -1,6 +1,6 @@
import * as Sentry from "@sentry/node";
import env from "@server/env";
import { ContextWithState } from "../types";
import { AppContext } from "@server/types";
if (env.SENTRY_DSN) {
Sentry.init({
@@ -29,7 +29,7 @@ if (env.SENTRY_DSN) {
});
}
export function requestErrorHandler(error: any, ctx: ContextWithState) {
export function requestErrorHandler(error: any, ctx: AppContext) {
// we don't need to report every time a request stops to the bug tracker
if (error.code === "EPIPE" || error.code === "ECONNRESET") {
console.warn("Connection error", {
@@ -46,17 +46,17 @@ export function requestErrorHandler(error: any, ctx: ContextWithState) {
scope.setTag("request_id", requestId as string);
}
const authType = ctx.state?.authType ?? undefined;
const authType = ctx.state?.auth?.type ?? undefined;
if (authType) {
scope.setTag("auth_type", authType);
}
const teamId = ctx.state?.user?.teamId ?? undefined;
const teamId = ctx.state?.auth?.user?.teamId ?? undefined;
if (teamId) {
scope.setTag("team_id", teamId);
}
const userId = ctx.state?.user?.id ?? undefined;
const userId = ctx.state?.auth?.user?.id ?? undefined;
if (userId) {
scope.setUser({
id: userId,
+4 -4
View File
@@ -24,7 +24,7 @@ describe("Authentication middleware", () => {
},
jest.fn()
);
expect(state.user.id).toEqual(user.id);
expect(state.auth.user.id).toEqual(user.id);
});
it("should return error with invalid token", async () => {
@@ -68,7 +68,7 @@ describe("Authentication middleware", () => {
},
jest.fn()
);
expect(state.user.id).toEqual(user.id);
expect(state.auth.user.id).toEqual(user.id);
});
it("should return error with invalid API key", async () => {
const state = {} as DefaultState;
@@ -133,7 +133,7 @@ describe("Authentication middleware", () => {
},
jest.fn()
);
expect(state.user.id).toEqual(user.id);
expect(state.auth.user.id).toEqual(user.id);
});
it("should allow passing auth token in body params", async () => {
@@ -154,7 +154,7 @@ describe("Authentication middleware", () => {
},
jest.fn()
);
expect(state.user.id).toEqual(user.id);
expect(state.auth.user.id).toEqual(user.id);
});
it("should return an error for suspended users", async () => {
+14 -8
View File
@@ -5,13 +5,13 @@ import tracer, {
getRootSpanFromRequestContext,
} from "@server/logging/tracer";
import { User, Team, ApiKey } from "@server/models";
import { AppContext, AuthenticationType } from "@server/types";
import { getUserForJWT } from "@server/utils/jwt";
import {
AuthenticationError,
AuthorizationError,
UserSuspendedError,
} from "../errors";
import { ContextWithState, AuthenticationType } from "../types";
type AuthenticationOptions = {
/* An admin user role is required to access the route */
@@ -26,7 +26,7 @@ type AuthenticationOptions = {
};
export default function auth(options: AuthenticationOptions = {}) {
return async function authMiddleware(ctx: ContextWithState, next: Next) {
return async function authMiddleware(ctx: AppContext, next: Next) {
let token;
const authorizationHeader = ctx.request.get("authorization");
@@ -61,11 +61,12 @@ export default function auth(options: AuthenticationOptions = {}) {
throw AuthenticationError("Authentication required");
}
let user: User | null | undefined;
let user: User | null;
let type: AuthenticationType;
if (token) {
if (ApiKey.match(String(token))) {
ctx.state.authType = AuthenticationType.API;
type = AuthenticationType.API;
let apiKey;
try {
@@ -96,7 +97,7 @@ export default function auth(options: AuthenticationOptions = {}) {
throw AuthenticationError("Invalid API key");
}
} else {
ctx.state.authType = AuthenticationType.APP;
type = AuthenticationType.APP;
user = await getUserForJWT(String(token));
}
@@ -129,19 +130,24 @@ export default function auth(options: AuthenticationOptions = {}) {
Logger.error("Failed to update user activeAt", err);
});
ctx.state.token = String(token);
ctx.state.user = user;
ctx.state.auth = {
user,
token: String(token),
type,
};
if (tracer) {
addTags(
{
"request.userId": user.id,
"request.teamId": user.teamId,
"request.authType": ctx.state.authType,
"request.authType": type,
},
getRootSpanFromRequestContext(ctx)
);
}
} else {
ctx.state.auth = {};
}
return next();
+16 -11
View File
@@ -2,6 +2,7 @@ import { Context, Next } from "koa";
import { defaults } from "lodash";
import env from "@server/env";
import { RateLimitExceededError } from "@server/errors";
import Logger from "@server/logging/Logger";
import Metrics from "@server/logging/Metrics";
import Redis from "@server/redis";
import RateLimiter from "@server/utils/RateLimiter";
@@ -27,19 +28,23 @@ export function defaultRateLimiter() {
try {
await limiter.consume(key);
} catch (rateLimiterRes) {
ctx.set("Retry-After", `${rateLimiterRes.msBeforeNext / 1000}`);
ctx.set("RateLimit-Limit", `${limiter.points}`);
ctx.set("RateLimit-Remaining", `${rateLimiterRes.remainingPoints}`);
ctx.set(
"RateLimit-Reset",
`${new Date(Date.now() + rateLimiterRes.msBeforeNext)}`
);
if (rateLimiterRes.msBeforeNext) {
ctx.set("Retry-After", `${rateLimiterRes.msBeforeNext / 1000}`);
ctx.set("RateLimit-Limit", `${limiter.points}`);
ctx.set("RateLimit-Remaining", `${rateLimiterRes.remainingPoints}`);
ctx.set(
"RateLimit-Reset",
`${new Date(Date.now() + rateLimiterRes.msBeforeNext)}`
);
Metrics.increment("rate_limit.exceeded", {
path: ctx.path,
});
Metrics.increment("rate_limit.exceeded", {
path: ctx.path,
});
throw RateLimitExceededError();
throw RateLimitExceededError();
} else {
Logger.error("Rate limiter error", rateLimiterRes);
}
}
return next();
+3 -8
View File
@@ -1,12 +1,7 @@
import { Context, Next } from "koa";
import { Next } from "koa";
import { Transaction } from "sequelize";
import { sequelize } from "@server/database/sequelize";
export type TransactionContext = Context & {
state: Context["state"] & {
transaction: Transaction;
};
};
import { AppContext } from "@server/types";
/**
* Middleware that wraps a route in a database transaction, useful for mutations
@@ -16,7 +11,7 @@ export type TransactionContext = Context & {
* @returns The middleware function.
*/
export function transaction() {
return async function transactionMiddleware(ctx: Context, next: Next) {
return async function transactionMiddleware(ctx: AppContext, next: Next) {
await sequelize.transaction(async (t: Transaction) => {
ctx.state.transaction = t;
return next();
+12 -8
View File
@@ -1,16 +1,20 @@
import { Next } from "koa";
import { z } from "zod";
import { z, ZodError } from "zod";
import { ValidationError } from "@server/errors";
import { APIContext } from "@server/types";
import { APIContext, BaseReq } from "@server/types";
export default function validate<T extends z.ZodTypeAny>(schema: T) {
return async function validateMiddleware(ctx: APIContext<T>, next: Next) {
export default function validate<T extends z.ZodType<BaseReq>>(schema: T) {
return async function validateMiddleware(ctx: APIContext, next: Next) {
try {
ctx.input = schema.parse(ctx.request.body);
ctx.input = schema.parse(ctx.request);
} catch (err) {
const { path, message } = err.issues[0];
const [prefix = "ValidationError"] = path;
throw ValidationError(`${prefix}: ${message}`);
if (err instanceof ZodError) {
const { path, message } = err.issues[0];
const errMessage =
path.length > 0 ? `${path[path.length - 1]}: ${message}` : message;
throw ValidationError(errMessage);
}
ctx.throw(err);
}
return next();
};
+33 -14
View File
@@ -33,7 +33,10 @@ describe("getDocumentParents", () => {
const document = await buildDocument();
const collection = await buildCollection({
documentStructure: [
{ ...parent.toJSON(), children: [document.toJSON()] },
{
...(await parent.toNavigationNode()),
children: [await document.toNavigationNode()],
},
],
});
const result = collection.getDocumentParents(document.id);
@@ -46,7 +49,10 @@ describe("getDocumentParents", () => {
const document = await buildDocument();
const collection = await buildCollection({
documentStructure: [
{ ...parent.toJSON(), children: [document.toJSON()] },
{
...(await parent.toNavigationNode()),
children: [await document.toNavigationNode()],
},
],
});
const result = collection.getDocumentParents(parent.id);
@@ -66,9 +72,11 @@ describe("getDocumentTree", () => {
test("should return document tree", async () => {
const document = await buildDocument();
const collection = await buildCollection({
documentStructure: [document.toJSON()],
documentStructure: [await document.toNavigationNode()],
});
expect(collection.getDocumentTree(document.id)).toEqual(document.toJSON());
expect(collection.getDocumentTree(document.id)).toEqual(
await document.toNavigationNode()
);
});
test("should return nested documents in tree", async () => {
@@ -76,15 +84,20 @@ describe("getDocumentTree", () => {
const document = await buildDocument();
const collection = await buildCollection({
documentStructure: [
{ ...parent.toJSON(), children: [document.toJSON()] },
{
...(await parent.toNavigationNode()),
children: [await document.toNavigationNode()],
},
],
});
expect(collection.getDocumentTree(parent.id)).toEqual({
...parent.toJSON(),
children: [document.toJSON()],
...(await parent.toNavigationNode()),
children: [await document.toNavigationNode()],
});
expect(collection.getDocumentTree(document.id)).toEqual(document.toJSON());
expect(collection.getDocumentTree(document.id)).toEqual(
await document.toNavigationNode()
);
});
});
@@ -92,10 +105,11 @@ describe("#addDocumentToStructure", () => {
test("should add as last element without index", async () => {
const { collection } = await seed();
const id = uuidv4();
const newDocument = new Document({
const newDocument = await buildDocument({
id,
title: "New end node",
parentDocumentId: null,
teamId: collection.teamId,
});
await collection.addDocumentToStructure(newDocument);
expect(collection.documentStructure!.length).toBe(2);
@@ -105,10 +119,11 @@ describe("#addDocumentToStructure", () => {
test("should add with an index", async () => {
const { collection } = await seed();
const id = uuidv4();
const newDocument = new Document({
const newDocument = await buildDocument({
id,
title: "New end node",
parentDocumentId: null,
teamId: collection.teamId,
});
await collection.addDocumentToStructure(newDocument, 1);
expect(collection.documentStructure!.length).toBe(2);
@@ -118,10 +133,11 @@ describe("#addDocumentToStructure", () => {
test("should add as a child if with parent", async () => {
const { collection, document } = await seed();
const id = uuidv4();
const newDocument = new Document({
const newDocument = await buildDocument({
id,
title: "New end node",
parentDocumentId: document.id,
teamId: collection.teamId,
});
await collection.addDocumentToStructure(newDocument, 1);
expect(collection.documentStructure!.length).toBe(1);
@@ -132,16 +148,18 @@ describe("#addDocumentToStructure", () => {
test("should add as a child if with parent with index", async () => {
const { collection, document } = await seed();
const newDocument = new Document({
const newDocument = await buildDocument({
id: uuidv4(),
title: "node",
parentDocumentId: document.id,
teamId: collection.teamId,
});
const id = uuidv4();
const secondDocument = new Document({
const secondDocument = await buildDocument({
id,
title: "New start node",
parentDocumentId: document.id,
teamId: collection.teamId,
});
await collection.addDocumentToStructure(newDocument);
await collection.addDocumentToStructure(secondDocument, 0);
@@ -154,10 +172,11 @@ describe("#addDocumentToStructure", () => {
test("should append supplied json over document's own", async () => {
const { collection } = await seed();
const id = uuidv4();
const newDocument = new Document({
const newDocument = await buildDocument({
id: uuidv4(),
title: "New end node",
parentDocumentId: null,
teamId: collection.teamId,
});
await collection.addDocumentToStructure(newDocument, undefined, {
documentJson: {
+19 -14
View File
@@ -554,7 +554,7 @@ class Collection extends ParanoidModel {
*/
updateDocument = async function (
updatedDocument: Document,
options?: { transaction?: Transaction | null }
options?: { transaction?: Transaction | null | undefined }
) {
if (!this.documentStructure) {
return;
@@ -563,21 +563,23 @@ class Collection extends ParanoidModel {
const { id } = updatedDocument;
const updateChildren = (documents: NavigationNode[]) => {
return documents.map((document) => {
if (document.id === id) {
document = {
...(updatedDocument.toJSON() as NavigationNode),
children: document.children,
};
} else {
document.children = updateChildren(document.children);
}
return Promise.all(
documents.map(async (document) => {
if (document.id === id) {
document = {
...(await updatedDocument.toNavigationNode(options)),
children: document.children,
};
} else {
document.children = await updateChildren(document.children);
}
return document;
});
return document;
})
);
};
this.documentStructure = updateChildren(this.documentStructure);
this.documentStructure = await updateChildren(this.documentStructure);
// Sequelize doesn't seem to set the value with splice on JSONB field
// https://github.com/sequelize/sequelize/blob/e1446837196c07b8ff0c23359b958d68af40fd6d/src/model.js#L3937
this.changed("documentStructure", true);
@@ -602,7 +604,10 @@ class Collection extends ParanoidModel {
}
// If moving existing document with children, use existing structure
const documentJson = { ...document.toJSON(), ...options.documentJson };
const documentJson = {
...(await document.toNavigationNode(options)),
...options.documentJson,
};
if (!document.parentDocumentId) {
// Note: Index is supported on DB level but it's being ignored
+32 -4
View File
@@ -36,6 +36,7 @@ import parseTitle from "@shared/utils/parseTitle";
import { SLUG_URL_REGEX } from "@shared/utils/urlHelpers";
import { DocumentValidation } from "@shared/validations";
import slugify from "@server/utils/slugify";
import type { NavigationNode } from "~/types";
import Backlink from "./Backlink";
import Collection from "./Collection";
import FileOperation from "./FileOperation";
@@ -750,14 +751,41 @@ class Document extends ParanoidModel {
return notEmpty ? lines[1] : "";
};
toJSON = () => {
// Warning: only use for new documents as order of children is
// handled in the collection's documentStructure
/**
* Returns a JSON representation of the document suitable for use in the
* collection documentStructure.
*
* @param options Optional transaction to use for the query
* @returns Promise resolving to a NavigationNode
*/
toNavigationNode = async (options?: {
transaction?: Transaction | null | undefined;
}): Promise<NavigationNode> => {
const childDocuments = await (this.constructor as typeof Document)
.unscoped()
.findAll({
where: {
teamId: this.teamId,
parentDocumentId: this.id,
archivedAt: {
[Op.is]: null,
},
publishedAt: {
[Op.ne]: null,
},
},
transaction: options?.transaction,
});
const children = await Promise.all(
childDocuments.map((child) => child.toNavigationNode(options))
);
return {
id: this.id,
title: this.title,
url: this.url,
children: [],
children,
};
};
}
+1 -2
View File
@@ -211,8 +211,7 @@ class Team extends ParanoidModel {
const collection = await Collection.create(
{
name: "Welcome",
description:
"This collection is a quick guide to what Outline is all about. Feel free to delete this collection once your team is up to speed with the basics!",
description: `This collection is a quick guide to what ${env.APP_NAME} is all about. Feel free to delete this collection once your team is up to speed with the basics!`,
teamId: this.id,
createdById: userId,
sort: Collection.DEFAULT_SORT,
+1 -1
View File
@@ -128,7 +128,7 @@ describe("no collection", () => {
expect(abilities.createChildDocument).toEqual(false);
expect(abilities.delete).toEqual(true);
expect(abilities.download).toEqual(true);
expect(abilities.move).toEqual(false);
expect(abilities.move).toEqual(true);
expect(abilities.permanentDelete).toEqual(false);
expect(abilities.pin).toEqual(false);
expect(abilities.pinToHome).toEqual(false);
+1 -8
View File
@@ -174,14 +174,7 @@ allow(User, "move", Document, (user, document) => {
if (document.deletedAt) {
return false;
}
if (!document.publishedAt) {
return false;
}
invariant(
document.collection,
"collection is missing, did you forget to include in the query scope?"
);
if (cannot(user, "update", document.collection)) {
if (document.collection && cannot(user, "update", document.collection)) {
return false;
}
return user.teamId === document.teamId;
+1
View File
@@ -30,6 +30,7 @@ export default function present(
GOOGLE_ANALYTICS_ID: env.GOOGLE_ANALYTICS_ID,
RELEASE:
process.env.SOURCE_COMMIT || process.env.SOURCE_VERSION || undefined,
APP_NAME: env.APP_NAME,
analytics: {
service: analytics?.service,
settings: analytics?.settings,
+6 -2
View File
@@ -1,3 +1,4 @@
import { compact } from "lodash";
import { traceFunction } from "@server/logging/tracing";
import { User } from "@server/models";
@@ -6,11 +7,14 @@ type Policy = {
abilities: Record<string, boolean>;
};
function presentPolicy(user: User, objects: Record<string, any>[]): Policy[] {
function presentPolicy(
user: User,
objects: (Record<string, any> | null)[]
): Policy[] {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { serialize } = require("../policies");
return objects.map((object) => ({
return compact(objects).map((object) => ({
id: object.id,
abilities: serialize(user, object),
}));
+1 -1
View File
@@ -62,7 +62,7 @@ export default class SlackProcessor extends BaseProcessor {
"Content-Type": "application/json",
},
body: JSON.stringify({
text: `👋 Hey there! When documents are published or updated in the *${collection.name}* collection on Outline they will be posted to this channel!`,
text: `👋 Hey there! When documents are published or updated in the *${collection.name}* collection on ${env.APP_NAME} they will be posted to this channel!`,
attachments: [
{
color: collection.color,
@@ -0,0 +1,195 @@
import path from "path";
import JSZip from "jszip";
import { FileOperationFormat } from "@shared/types";
import Logger from "@server/logging/Logger";
import { Collection } from "@server/models";
import Attachment from "@server/models/Attachment";
import Document from "@server/models/Document";
import DocumentHelper from "@server/models/helpers/DocumentHelper";
import ZipHelper from "@server/utils/ZipHelper";
import { serializeFilename } from "@server/utils/fs";
import parseAttachmentIds from "@server/utils/parseAttachmentIds";
import { getFileByKey } from "@server/utils/s3";
import { NavigationNode } from "~/types";
import ExportTask from "./ExportTask";
export default abstract class ExportDocumentTreeTask extends ExportTask {
/**
* Exports the document tree to the given zip instance.
*
* @param zip The JSZip instance to add files to
* @param documentId The document ID to export
* @param pathInZip The path in the zip to add the document to
* @param format The format to export in
*/
protected async addDocumentToArchive({
zip,
pathInZip,
documentId,
format = FileOperationFormat.MarkdownZip,
pathMap,
}: {
zip: JSZip;
pathInZip: string;
documentId: string;
format: FileOperationFormat;
pathMap: Map<string, string>;
}) {
const document = await Document.findByPk(documentId);
if (!document) {
return;
}
let text =
format === FileOperationFormat.HTMLZip
? await DocumentHelper.toHTML(document, { centered: true })
: await DocumentHelper.toMarkdown(document);
const attachments = await Attachment.findAll({
where: {
teamId: document.teamId,
id: parseAttachmentIds(document.text),
},
});
// Add any referenced attachments to the zip file and replace the
// reference in the document with the path to the attachment in the zip
await Promise.all(
attachments.map(async (attachment) => {
try {
const img = await getFileByKey(attachment.key);
const dir = path.dirname(pathInZip);
if (img) {
zip.file(path.join(dir, attachment.key), img as Blob, {
createFolders: true,
});
}
} catch (err) {
Logger.error(
`Failed to add attachment to archive: ${attachment.key}`,
err
);
}
text = text.replace(attachment.redirectUrl, encodeURI(attachment.key));
})
);
// Replace any internal links with relative paths to the document in the zip
const internalLinks = [
...text.matchAll(/\/doc\/(?:[0-9a-zA-Z-_~]*-)?([a-zA-Z0-9]{10,15})/g),
];
internalLinks.forEach((match) => {
const matchedLink = match[0];
const matchedDocPath = pathMap.get(matchedLink);
if (matchedDocPath) {
const relativePath = path.relative(pathInZip, matchedDocPath);
if (relativePath.startsWith(".")) {
text = text.replace(
matchedLink,
encodeURI(relativePath.substring(1))
);
}
}
});
// Finally, add the document to the zip file
zip.file(pathInZip, text, {
date: document.updatedAt,
createFolders: true,
comment: JSON.stringify({
createdAt: document.createdAt,
updatedAt: document.updatedAt,
}),
});
}
/**
* Exports the documents and attachments in the given collections to a zip file
* and returns the path to the zip file in tmp.
*
* @param zip The JSZip instance to add files to
* @param collections The collections to export
* @param format The format to export in
*
* @returns The path to the zip file in tmp.
*/
protected async addCollectionsToArchive(
zip: JSZip,
collections: Collection[],
format: FileOperationFormat
) {
const pathMap = this.createPathMap(collections, format);
for (const path of pathMap) {
const documentId = path[0].replace("/doc/", "");
const pathInZip = path[1];
await this.addDocumentToArchive({
zip,
pathInZip,
documentId,
format,
pathMap,
});
}
return ZipHelper.toTmpFile(zip);
}
/**
* Generates a map of document urls to their path in the zip file.
*
* @param collections
*/
private createPathMap(
collections: Collection[],
format: FileOperationFormat
) {
const map = new Map<string, string>();
for (const collection of collections) {
if (collection.documentStructure) {
this.addDocumentTreeToPathMap(
map,
collection.documentStructure,
serializeFilename(collection.name),
format
);
}
}
return map;
}
private addDocumentTreeToPathMap(
map: Map<string, string>,
nodes: NavigationNode[],
root: string,
format: FileOperationFormat
) {
for (const node of nodes) {
const title = serializeFilename(node.title) || "Untitled";
const extension = format === FileOperationFormat.HTMLZip ? "html" : "md";
// Ensure the document is given a unique path in zip, even if it has
// the same title as another document in the same collection.
let i = 0;
let filePath = path.join(root, `${title}.${extension}`);
while (Array.from(map.values()).includes(filePath)) {
filePath = path.join(root, `${title} (${++i}).${extension}`);
}
map.set(node.url, filePath);
if (node.children?.length) {
this.addDocumentTreeToPathMap(
map,
node.children,
path.join(root, title),
format
);
}
}
}
}
+10 -4
View File
@@ -1,10 +1,16 @@
import JSZip from "jszip";
import { FileOperationFormat } from "@shared/types";
import { Collection } from "@server/models";
import { archiveCollections } from "@server/utils/zip";
import ExportTask from "./ExportTask";
import ExportDocumentTreeTask from "./ExportDocumentTreeTask";
export default class ExportHTMLZipTask extends ExportTask {
export default class ExportHTMLZipTask extends ExportDocumentTreeTask {
public async export(collections: Collection[]) {
return await archiveCollections(collections, FileOperationFormat.HTMLZip);
const zip = new JSZip();
return await this.addCollectionsToArchive(
zip,
collections,
FileOperationFormat.HTMLZip
);
}
}
+7 -4
View File
@@ -1,11 +1,14 @@
import JSZip from "jszip";
import { FileOperationFormat } from "@shared/types";
import { Collection } from "@server/models";
import { archiveCollections } from "@server/utils/zip";
import ExportTask from "./ExportTask";
import ExportDocumentTreeTask from "./ExportDocumentTreeTask";
export default class ExportMarkdownZipTask extends ExportTask {
export default class ExportMarkdownZipTask extends ExportDocumentTreeTask {
public async export(collections: Collection[]) {
return await archiveCollections(
const zip = new JSZip();
return await this.addCollectionsToArchive(
zip,
collections,
FileOperationFormat.MarkdownZip
);
+7 -9
View File
@@ -5,7 +5,7 @@ import { v4 as uuidv4 } from "uuid";
import documentImporter from "@server/commands/documentImporter";
import Logger from "@server/logging/Logger";
import { FileOperation, User } from "@server/models";
import { zipAsFileTree, FileTreeNode } from "@server/utils/zip";
import ZipHelper, { FileTreeNode } from "@server/utils/ZipHelper";
import ImportTask, { StructuredImportData } from "./ImportTask";
export default class ImportMarkdownZipTask extends ImportTask {
@@ -14,7 +14,7 @@ export default class ImportMarkdownZipTask extends ImportTask {
fileOperation: FileOperation
): Promise<StructuredImportData> {
const zip = await JSZip.loadAsync(buffer);
const tree = zipAsFileTree(zip);
const tree = ZipHelper.toFileTree(zip);
return this.parseFileTree({ fileOperation, zip, tree });
}
@@ -152,22 +152,20 @@ export default class ImportMarkdownZipTask extends ImportTask {
// and replace them out with attachment redirect urls before continuing.
for (const document of output.documents) {
for (const attachment of output.attachments) {
const encodedPath = encodeURI(attachment.path);
// Pull the collection and subdirectory out of the path name, upload
// folders in an export are relative to the document itself
const normalizedAttachmentPath = attachment.path.replace(
const normalizedAttachmentPath = encodedPath.replace(
/(.*)uploads\//,
"uploads/"
);
const reference = `<<${attachment.id}>>`;
document.text = document.text
.replace(new RegExp(escapeRegExp(attachment.path), "g"), reference)
.replace(new RegExp(escapeRegExp(encodedPath), "g"), reference)
.replace(
new RegExp(escapeRegExp(normalizedAttachmentPath), "g"),
reference
)
.replace(
new RegExp(escapeRegExp(`/${normalizedAttachmentPath}`), "g"),
new RegExp(`/?${escapeRegExp(normalizedAttachmentPath)}`, "g"),
reference
);
}
+2 -2
View File
@@ -6,7 +6,7 @@ import { v4 as uuidv4 } from "uuid";
import documentImporter from "@server/commands/documentImporter";
import Logger from "@server/logging/Logger";
import { FileOperation, User } from "@server/models";
import { zipAsFileTree, FileTreeNode } from "@server/utils/zip";
import ZipHelper, { FileTreeNode } from "@server/utils/ZipHelper";
import ImportTask, { StructuredImportData } from "./ImportTask";
export default class ImportNotionTask extends ImportTask {
@@ -15,7 +15,7 @@ export default class ImportNotionTask extends ImportTask {
fileOperation: FileOperation
): Promise<StructuredImportData> {
const zip = await JSZip.loadAsync(buffer);
const tree = zipAsFileTree(zip);
const tree = ZipHelper.toFileTree(zip);
return this.parseFileTree({ fileOperation, zip, tree });
}
+8
View File
@@ -0,0 +1,8 @@
import { z } from "zod";
const BaseSchema = z.object({
body: z.unknown(),
query: z.unknown(),
});
export default BaseSchema;
+55 -46
View File
@@ -3,44 +3,49 @@ import auth from "@server/middlewares/authentication";
import { ApiKey, Event } from "@server/models";
import { authorize } from "@server/policies";
import { presentApiKey } from "@server/presenters";
import { APIContext } from "@server/types";
import { assertUuid, assertPresent } from "@server/validation";
import pagination from "./middlewares/pagination";
const router = new Router();
router.post("apiKeys.create", auth({ member: true }), async (ctx) => {
const { name } = ctx.request.body;
assertPresent(name, "name is required");
const { user } = ctx.state;
router.post(
"apiKeys.create",
auth({ member: true }),
async (ctx: APIContext) => {
const { name } = ctx.request.body;
assertPresent(name, "name is required");
const { user } = ctx.state.auth;
authorize(user, "createApiKey", user.team);
const key = await ApiKey.create({
name,
userId: user.id,
});
await Event.create({
name: "api_keys.create",
modelId: key.id,
teamId: user.teamId,
actorId: user.id,
data: {
authorize(user, "createApiKey", user.team);
const key = await ApiKey.create({
name,
},
ip: ctx.request.ip,
});
userId: user.id,
});
ctx.body = {
data: presentApiKey(key),
};
});
await Event.create({
name: "api_keys.create",
modelId: key.id,
teamId: user.teamId,
actorId: user.id,
data: {
name,
},
ip: ctx.request.ip,
});
ctx.body = {
data: presentApiKey(key),
};
}
);
router.post(
"apiKeys.list",
auth({ member: true }),
pagination(),
async (ctx) => {
const { user } = ctx.state;
async (ctx: APIContext) => {
const { user } = ctx.state.auth;
const keys = await ApiKey.findAll({
where: {
userId: user.id,
@@ -57,28 +62,32 @@ router.post(
}
);
router.post("apiKeys.delete", auth({ member: true }), async (ctx) => {
const { id } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state;
const key = await ApiKey.findByPk(id);
authorize(user, "delete", key);
router.post(
"apiKeys.delete",
auth({ member: true }),
async (ctx: APIContext) => {
const { id } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state.auth;
const key = await ApiKey.findByPk(id);
authorize(user, "delete", key);
await key.destroy();
await Event.create({
name: "api_keys.delete",
modelId: key.id,
teamId: user.teamId,
actorId: user.id,
data: {
name: key.name,
},
ip: ctx.request.ip,
});
await key.destroy();
await Event.create({
name: "api_keys.delete",
modelId: key.id,
teamId: user.teamId,
actorId: user.id,
data: {
name: key.name,
},
ip: ctx.request.ip,
});
ctx.body = {
success: true,
};
});
ctx.body = {
success: true,
};
}
);
export default router;
@@ -307,6 +307,24 @@ describe("#attachments.redirect", () => {
expect(res.status).toEqual(302);
});
it("should return a redirect for the attachment if id supplied via query params", async () => {
const user = await buildUser();
const attachment = await buildAttachment({
teamId: user.teamId,
userId: user.id,
});
const res = await server.post(
`/api/attachments.redirect?id=${attachment.id}`,
{
body: {
token: user.getJwtToken(),
},
redirect: "manual",
}
);
expect(res.status).toEqual(302);
});
it("should return a redirect for an attachment belonging to a trashed document user has access to", async () => {
const user = await buildUser();
const collection = await buildCollection({
@@ -385,4 +403,16 @@ describe("#attachments.redirect", () => {
});
expect(res.status).toEqual(403);
});
it("should fail in absence of id", async () => {
const user = await buildUser();
const res = await server.post("/api/attachments.redirect", {
body: {
token: user.getJwtToken(),
},
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toEqual("id is required");
});
});
+24 -12
View File
@@ -11,9 +11,9 @@ import { Attachment, Document, Event } from "@server/models";
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
import { authorize } from "@server/policies";
import { presentAttachment } from "@server/presenters";
import { APIContext, ContextWithState } from "@server/types";
import { APIContext } from "@server/types";
import { getPresignedPost, publicS3Endpoint } from "@server/utils/s3";
import { assertIn, assertUuid } from "@server/validation";
import { assertIn } from "@server/validation";
import * as T from "./schema";
const router = new Router();
@@ -24,8 +24,9 @@ router.post(
validate(T.AttachmentsCreateSchema),
transaction(),
async (ctx: APIContext<T.AttachmentCreateReq>) => {
const { name, documentId, contentType, size, preset } = ctx.input;
const { user, transaction } = ctx.state;
const { name, documentId, contentType, size, preset } = ctx.input.body;
const { auth, transaction } = ctx.state;
const { user } = auth;
// All user types can upload an avatar so no additional authorization is needed.
if (preset === AttachmentPreset.Avatar) {
@@ -112,8 +113,8 @@ router.post(
auth(),
validate(T.AttachmentDeleteSchema),
async (ctx: APIContext<T.AttachmentDeleteReq>) => {
const { id } = ctx.input;
const { user } = ctx.state;
const { id } = ctx.input.body;
const { user } = ctx.state.auth;
const attachment = await Attachment.findByPk(id, {
rejectOnEmpty: true,
});
@@ -140,11 +141,12 @@ router.post(
}
);
const handleAttachmentsRedirect = async (ctx: ContextWithState) => {
const id = ctx.request.body?.id ?? ctx.request.query?.id;
assertUuid(id, "id is required");
const handleAttachmentsRedirect = async (
ctx: APIContext<T.AttachmentsRedirectReq>
) => {
const id = (ctx.input.body.id ?? ctx.input.query.id) as string;
const { user } = ctx.state;
const { user } = ctx.state.auth;
const attachment = await Attachment.findByPk(id, {
rejectOnEmpty: true,
});
@@ -164,7 +166,17 @@ const handleAttachmentsRedirect = async (ctx: ContextWithState) => {
}
};
router.get("attachments.redirect", auth(), handleAttachmentsRedirect);
router.post("attachments.redirect", auth(), handleAttachmentsRedirect);
router.get(
"attachments.redirect",
auth(),
validate(T.AttachmentsRedirectSchema),
handleAttachmentsRedirect
);
router.post(
"attachments.redirect",
auth(),
validate(T.AttachmentsRedirectSchema),
handleAttachmentsRedirect
);
export default router;
+35 -14
View File
@@ -1,28 +1,49 @@
import { isEmpty } from "lodash";
import { z } from "zod";
import { AttachmentPreset } from "@shared/types";
import BaseSchema from "@server/routes/api/BaseSchema";
export const AttachmentsCreateSchema = z.object({
/** Attachment name */
name: z.string(),
export const AttachmentsCreateSchema = BaseSchema.extend({
body: z.object({
/** Attachment name */
name: z.string(),
/** Id of the document to which the Attachment belongs */
documentId: z.string().uuid().optional(),
/** Id of the document to which the Attachment belongs */
documentId: z.string().uuid().optional(),
/** File size of the Attachment */
size: z.number(),
/** File size of the Attachment */
size: z.number(),
/** Content-Type of the Attachment */
contentType: z.string().optional().default("application/octet-stream"),
/** Content-Type of the Attachment */
contentType: z.string().optional().default("application/octet-stream"),
/** Attachment type */
preset: z.nativeEnum(AttachmentPreset),
/** Attachment type */
preset: z.nativeEnum(AttachmentPreset),
}),
});
export type AttachmentCreateReq = z.infer<typeof AttachmentsCreateSchema>;
export const AttachmentDeleteSchema = z.object({
/** Id of the attachment to be deleted */
id: z.string().uuid(),
export const AttachmentDeleteSchema = BaseSchema.extend({
body: z.object({
/** Id of the attachment to be deleted */
id: z.string().uuid(),
}),
});
export type AttachmentDeleteReq = z.infer<typeof AttachmentDeleteSchema>;
export const AttachmentsRedirectSchema = BaseSchema.extend({
body: z.object({
/** Id of the attachment to be deleted */
id: z.string().uuid().optional(),
}),
query: z.object({
/** Id of the attachment to be deleted */
id: z.string().uuid().optional(),
}),
}).refine((req) => !(isEmpty(req.body.id) && isEmpty(req.query.id)), {
message: "id is required",
});
export type AttachmentsRedirectReq = z.infer<typeof AttachmentsRedirectSchema>;
+27 -33
View File
@@ -4,10 +4,7 @@ import { TeamPreference } from "@shared/types";
import { parseDomain } from "@shared/utils/domains";
import env from "@server/env";
import auth from "@server/middlewares/authentication";
import {
transaction,
TransactionContext,
} from "@server/middlewares/transaction";
import { transaction } from "@server/middlewares/transaction";
import { Event, Team } from "@server/models";
import {
presentUser,
@@ -16,6 +13,7 @@ import {
presentAvailableTeam,
} from "@server/presenters";
import ValidateSSOAccessTask from "@server/queues/tasks/ValidateSSOAccessTask";
import { APIContext } from "@server/types";
import { getSessionsInCookie } from "@server/utils/authentication";
import providers from "../auth/providers";
@@ -47,7 +45,7 @@ function filterProviders(team?: Team) {
}));
}
router.post("auth.config", async (ctx) => {
router.post("auth.config", async (ctx: APIContext) => {
// If self hosted AND there is only one team then that team becomes the
// brand for the knowledge base and it's guest signin option is used for the
// root login page.
@@ -124,8 +122,8 @@ router.post("auth.config", async (ctx) => {
};
});
router.post("auth.info", auth(), async (ctx) => {
const { user } = ctx.state;
router.post("auth.info", auth(), async (ctx: APIContext) => {
const { user } = ctx.state.auth;
const sessions = getSessionsInCookie(ctx);
const signedInTeamIds = Object.keys(sessions);
@@ -163,34 +161,30 @@ router.post("auth.info", auth(), async (ctx) => {
};
});
router.post(
"auth.delete",
auth(),
transaction(),
async (ctx: TransactionContext) => {
const { user, transaction } = ctx.state;
router.post("auth.delete", auth(), transaction(), async (ctx: APIContext) => {
const { auth, transaction } = ctx.state;
const { user } = auth;
await user.rotateJwtSecret({ transaction });
await Event.create(
{
name: "users.signout",
actorId: user.id,
userId: user.id,
teamId: user.teamId,
data: {
name: user.name,
},
ip: ctx.request.ip,
await user.rotateJwtSecret({ transaction });
await Event.create(
{
name: "users.signout",
actorId: user.id,
userId: user.id,
teamId: user.teamId,
data: {
name: user.name,
},
{
transaction,
}
);
ip: ctx.request.ip,
},
{
transaction,
}
);
ctx.body = {
success: true,
};
}
);
ctx.body = {
success: true,
};
});
export default router;
+7 -6
View File
@@ -7,6 +7,7 @@ import {
presentAuthenticationProvider,
presentPolicies,
} from "@server/presenters";
import { APIContext } from "@server/types";
import { assertUuid, assertPresent } from "@server/validation";
import allAuthenticationProviders from "../auth/providers";
@@ -15,11 +16,11 @@ const router = new Router();
router.post(
"authenticationProviders.info",
auth({ admin: true }),
async (ctx) => {
async (ctx: APIContext) => {
const { id } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const authenticationProvider = await AuthenticationProvider.findByPk(id);
authorize(user, "read", authenticationProvider);
@@ -33,11 +34,11 @@ router.post(
router.post(
"authenticationProviders.update",
auth({ admin: true }),
async (ctx) => {
async (ctx: APIContext) => {
const { id, isEnabled } = ctx.request.body;
assertUuid(id, "id is required");
assertPresent(isEnabled, "isEnabled is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const authenticationProvider = await sequelize.transaction(
async (transaction) => {
@@ -86,8 +87,8 @@ router.post(
router.post(
"authenticationProviders.list",
auth({ admin: true }),
async (ctx) => {
const { user } = ctx.state;
async (ctx: APIContext) => {
const { user } = ctx.state.auth;
authorize(user, "read", user.team);
const teamAuthenticationProviders = (await user.team.$get(
+144 -130
View File
@@ -16,10 +16,7 @@ import { sequelize } from "@server/database/sequelize";
import { AuthorizationError, ValidationError } from "@server/errors";
import auth from "@server/middlewares/authentication";
import { rateLimiter } from "@server/middlewares/rateLimiter";
import {
TransactionContext,
transaction,
} from "@server/middlewares/transaction";
import { transaction } from "@server/middlewares/transaction";
import {
Collection,
CollectionUser,
@@ -41,6 +38,7 @@ import {
presentCollectionGroupMembership,
presentFileOperation,
} from "@server/presenters";
import { APIContext } from "@server/types";
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
import { collectionIndexing } from "@server/utils/indexing";
import removeIndexCollision from "@server/utils/removeIndexCollision";
@@ -56,7 +54,7 @@ import pagination from "./middlewares/pagination";
const router = new Router();
router.post("collections.create", auth(), async (ctx) => {
router.post("collections.create", auth(), async (ctx: APIContext) => {
const {
name,
color = randomElement(colorPalette),
@@ -73,7 +71,7 @@ router.post("collections.create", auth(), async (ctx) => {
assertHexColor(color, "Invalid hex value (please use format #FFFFFF)");
}
const { user } = ctx.state;
const { user } = ctx.state.auth;
authorize(user, "createCollection", user.team);
if (index) {
@@ -134,10 +132,10 @@ router.post("collections.create", auth(), async (ctx) => {
};
});
router.post("collections.info", auth(), async (ctx) => {
router.post("collections.info", auth(), async (ctx: APIContext) => {
const { id } = ctx.request.body;
assertPresent(id, "id is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const collection = await Collection.scope({
method: ["withMembership", user.id],
}).findByPk(id);
@@ -154,14 +152,14 @@ router.post(
"collections.import",
auth(),
rateLimiter(RateLimiterStrategy.TenPerHour),
async (ctx) => {
async (ctx: APIContext) => {
const {
attachmentId,
format = FileOperationFormat.MarkdownZip,
} = ctx.request.body;
assertUuid(attachmentId, "attachmentId is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
authorize(user, "importCollection", user.team);
const attachment = await Attachment.findByPk(attachmentId);
@@ -207,7 +205,7 @@ router.post(
}
);
router.post("collections.add_group", auth(), async (ctx) => {
router.post("collections.add_group", auth(), async (ctx: APIContext) => {
const {
id,
groupId,
@@ -217,13 +215,15 @@ router.post("collections.add_group", auth(), async (ctx) => {
assertUuid(groupId, "groupId is required");
assertCollectionPermission(permission);
const { user } = ctx.state.auth;
const collection = await Collection.scope({
method: ["withMembership", ctx.state.user.id],
method: ["withMembership", user.id],
}).findByPk(id);
authorize(ctx.state.user, "update", collection);
authorize(user, "update", collection);
const group = await Group.findByPk(groupId);
authorize(ctx.state.user, "read", group);
authorize(user, "read", group);
let membership = await CollectionGroup.findOne({
where: {
@@ -237,7 +237,7 @@ router.post("collections.add_group", auth(), async (ctx) => {
collectionId: id,
groupId,
permission,
createdById: ctx.state.user.id,
createdById: user.id,
});
} else if (permission) {
membership.permission = permission;
@@ -248,7 +248,7 @@ router.post("collections.add_group", auth(), async (ctx) => {
name: "collections.add_group",
collectionId: collection.id,
teamId: collection.teamId,
actorId: ctx.state.user.id,
actorId: user.id,
modelId: groupId,
data: {
name: group.name,
@@ -265,25 +265,27 @@ router.post("collections.add_group", auth(), async (ctx) => {
};
});
router.post("collections.remove_group", auth(), async (ctx) => {
router.post("collections.remove_group", auth(), async (ctx: APIContext) => {
const { id, groupId } = ctx.request.body;
assertUuid(id, "id is required");
assertUuid(groupId, "groupId is required");
const { user } = ctx.state.auth;
const collection = await Collection.scope({
method: ["withMembership", ctx.state.user.id],
method: ["withMembership", user.id],
}).findByPk(id);
authorize(ctx.state.user, "update", collection);
authorize(user, "update", collection);
const group = await Group.findByPk(groupId);
authorize(ctx.state.user, "read", group);
authorize(user, "read", group);
await collection.$remove("group", group);
await Event.create({
name: "collections.remove_group",
collectionId: collection.id,
teamId: collection.teamId,
actorId: ctx.state.user.id,
actorId: user.id,
modelId: groupId,
data: {
name: group.name,
@@ -300,10 +302,10 @@ router.post(
"collections.group_memberships",
auth(),
pagination(),
async (ctx) => {
async (ctx: APIContext) => {
const { id, query, permission } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const collection = await Collection.scope({
method: ["withMembership", user.id],
@@ -365,19 +367,20 @@ router.post(
"collections.add_user",
auth(),
transaction(),
async (ctx: TransactionContext) => {
const { transaction } = ctx.state;
async (ctx: APIContext) => {
const { auth, transaction } = ctx.state;
const actor = auth.user;
const { id, userId, permission } = ctx.request.body;
assertUuid(id, "id is required");
assertUuid(userId, "userId is required");
const collection = await Collection.scope({
method: ["withMembership", ctx.state.user.id],
method: ["withMembership", actor.id],
}).findByPk(id);
authorize(ctx.state.user, "update", collection);
authorize(actor, "update", collection);
const user = await User.findByPk(userId);
authorize(ctx.state.user, "read", user);
authorize(actor, "read", user);
let membership = await CollectionUser.findOne({
where: {
@@ -388,7 +391,7 @@ router.post(
lock: transaction.LOCK.UPDATE,
});
if (userId === ctx.state.user.id) {
if (userId === actor.id) {
throw AuthorizationError("You cannot add yourself to a collection");
}
@@ -402,7 +405,7 @@ router.post(
collectionId: id,
userId,
permission: permission || user.defaultCollectionPermission,
createdById: ctx.state.user.id,
createdById: actor.id,
},
{
transaction,
@@ -419,7 +422,7 @@ router.post(
userId,
collectionId: collection.id,
teamId: collection.teamId,
actorId: ctx.state.user.id,
actorId: actor.id,
data: {
name: user.name,
},
@@ -443,19 +446,20 @@ router.post(
"collections.remove_user",
auth(),
transaction(),
async (ctx: TransactionContext) => {
const { transaction } = ctx.state;
async (ctx: APIContext) => {
const { auth, transaction } = ctx.state;
const actor = auth.user;
const { id, userId } = ctx.request.body;
assertUuid(id, "id is required");
assertUuid(userId, "userId is required");
const collection = await Collection.scope({
method: ["withMembership", ctx.state.user.id],
method: ["withMembership", actor.id],
}).findByPk(id);
authorize(ctx.state.user, "update", collection);
authorize(actor, "update", collection);
const user = await User.findByPk(userId);
authorize(ctx.state.user, "read", user);
authorize(actor, "read", user);
await collection.$remove("user", user, { transaction });
await Event.create(
@@ -464,7 +468,7 @@ router.post(
userId,
collectionId: collection.id,
teamId: collection.teamId,
actorId: ctx.state.user.id,
actorId: actor.id,
data: {
name: user.name,
},
@@ -479,77 +483,82 @@ router.post(
}
);
router.post("collections.memberships", auth(), pagination(), async (ctx) => {
const { id, query, permission } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state;
router.post(
"collections.memberships",
auth(),
pagination(),
async (ctx: APIContext) => {
const { id, query, permission } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state.auth;
const collection = await Collection.scope({
method: ["withMembership", user.id],
}).findByPk(id);
authorize(user, "read", collection);
const collection = await Collection.scope({
method: ["withMembership", user.id],
}).findByPk(id);
authorize(user, "read", collection);
let where: WhereOptions<CollectionUser> = {
collectionId: id,
};
let userWhere;
let where: WhereOptions<CollectionUser> = {
collectionId: id,
};
let userWhere;
if (query) {
userWhere = {
name: {
[Op.iLike]: `%${query}%`,
if (query) {
userWhere = {
name: {
[Op.iLike]: `%${query}%`,
},
};
}
if (permission) {
assertCollectionPermission(permission);
where = { ...where, permission };
}
const options = {
where,
include: [
{
model: User,
as: "user",
where: userWhere,
required: true,
},
],
};
const [total, memberships] = await Promise.all([
CollectionUser.count(options),
CollectionUser.findAll({
...options,
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
}),
]);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
data: {
memberships: memberships.map(presentMembership),
users: memberships.map((membership) => presentUser(membership.user)),
},
};
}
if (permission) {
assertCollectionPermission(permission);
where = { ...where, permission };
}
const options = {
where,
include: [
{
model: User,
as: "user",
where: userWhere,
required: true,
},
],
};
const [total, memberships] = await Promise.all([
CollectionUser.count(options),
CollectionUser.findAll({
...options,
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
}),
]);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
data: {
memberships: memberships.map(presentMembership),
users: memberships.map((membership) => presentUser(membership.user)),
},
};
});
);
router.post(
"collections.export",
auth(),
rateLimiter(RateLimiterStrategy.TenPerHour),
async (ctx) => {
async (ctx: APIContext) => {
const { id } = ctx.request.body;
const { format = FileOperationFormat.MarkdownZip } = ctx.request.body;
assertUuid(id, "id is required");
assertIn(format, Object.values(FileOperationFormat), "Invalid format");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const team = await Team.findByPk(user.teamId);
authorize(user, "createExport", team);
@@ -582,9 +591,9 @@ router.post(
"collections.export_all",
auth(),
rateLimiter(RateLimiterStrategy.FivePerHour),
async (ctx) => {
async (ctx: APIContext) => {
const { format = FileOperationFormat.MarkdownZip } = ctx.request.body;
const { user } = ctx.state;
const { user } = ctx.state.auth;
const team = await Team.findByPk(user.teamId);
authorize(user, "createExport", team);
@@ -609,7 +618,7 @@ router.post(
}
);
router.post("collections.update", auth(), async (ctx) => {
router.post("collections.update", auth(), async (ctx: APIContext) => {
const {
id,
name,
@@ -625,7 +634,7 @@ router.post("collections.update", auth(), async (ctx) => {
assertHexColor(color, "Invalid hex value (please use format #FFFFFF)");
}
const { user } = ctx.state;
const { user } = ctx.state.auth;
const collection = await Collection.scope({
method: ["withMembership", user.id],
}).findByPk(id);
@@ -736,43 +745,48 @@ router.post("collections.update", auth(), async (ctx) => {
};
});
router.post("collections.list", auth(), pagination(), async (ctx) => {
const { user } = ctx.state;
const collectionIds = await user.collectionIds();
const where: WhereOptions<Collection> = {
teamId: user.teamId,
id: collectionIds,
};
const collections = await Collection.scope({
method: ["withMembership", user.id],
}).findAll({
where,
order: [["updatedAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
});
const nullIndex = collections.findIndex(
(collection) => collection.index === null
);
if (nullIndex !== -1) {
const indexedCollections = await collectionIndexing(user.teamId);
collections.forEach((collection) => {
collection.index = indexedCollections[collection.id];
router.post(
"collections.list",
auth(),
pagination(),
async (ctx: APIContext) => {
const { user } = ctx.state.auth;
const collectionIds = await user.collectionIds();
const where: WhereOptions<Collection> = {
teamId: user.teamId,
id: collectionIds,
};
const collections = await Collection.scope({
method: ["withMembership", user.id],
}).findAll({
where,
order: [["updatedAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
});
const nullIndex = collections.findIndex(
(collection) => collection.index === null
);
if (nullIndex !== -1) {
const indexedCollections = await collectionIndexing(user.teamId);
collections.forEach((collection) => {
collection.index = indexedCollections[collection.id];
});
}
ctx.body = {
pagination: ctx.state.pagination,
data: collections.map(presentCollection),
policies: presentPolicies(user, collections),
};
}
);
ctx.body = {
pagination: ctx.state.pagination,
data: collections.map(presentCollection),
policies: presentPolicies(user, collections),
};
});
router.post("collections.delete", auth(), async (ctx) => {
router.post("collections.delete", auth(), async (ctx: APIContext) => {
const { id } = ctx.request.body;
const { user } = ctx.state;
const { user } = ctx.state.auth;
assertUuid(id, "id is required");
const collection = await Collection.scope({
@@ -814,13 +828,13 @@ router.post("collections.delete", auth(), async (ctx) => {
};
});
router.post("collections.move", auth(), async (ctx) => {
router.post("collections.move", auth(), async (ctx: APIContext) => {
const id = ctx.request.body.id;
let index = ctx.request.body.index;
assertPresent(index, "index is required");
assertIndexCharacters(index);
assertUuid(id, "id must be a uuid");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const collection = await Collection.findByPk(id);
authorize(user, "move", collection);
+37 -31
View File
@@ -6,6 +6,7 @@ import env from "@server/env";
import Logger from "@server/logging/Logger";
import auth from "@server/middlewares/authentication";
import { presentUser } from "@server/presenters";
import { APIContext } from "@server/types";
const router = new Router();
@@ -19,40 +20,45 @@ function dev() {
};
}
router.post("developer.create_test_users", dev(), auth(), async (ctx) => {
const { count = 10 } = ctx.request.body;
const { user } = ctx.state;
const invites = Array(Math.min(count, 100))
.fill(0)
.map(() => {
const rando = randomstring.generate(10);
router.post(
"developer.create_test_users",
dev(),
auth(),
async (ctx: APIContext) => {
const { count = 10 } = ctx.request.body;
const { user } = ctx.state.auth;
const invites = Array(Math.min(count, 100))
.fill(0)
.map(() => {
const rando = randomstring.generate(10);
return {
email: `${rando}@example.com`,
name: `${rando.slice(0, 5)} Tester`,
role: "member",
} as Invite;
return {
email: `${rando}@example.com`,
name: `${rando.slice(0, 5)} Tester`,
role: "member",
} as Invite;
});
Logger.info("utils", `Creating ${count} test users`, invites);
// Generate a bunch of invites
const response = await userInviter({
user,
invites,
ip: ctx.request.ip,
});
Logger.info("utils", `Creating ${count} test users`, invites);
// Convert from invites to active users by marking as active
await Promise.all(
response.users.map((user) => user.updateActiveAt(ctx, true))
);
// Generate a bunch of invites
const response = await userInviter({
user,
invites,
ip: ctx.request.ip,
});
// Convert from invites to active users by marking as active
await Promise.all(
response.users.map((user) => user.updateActiveAt(ctx, true))
);
ctx.body = {
data: {
users: response.users.map((user) => presentUser(user)),
},
};
});
ctx.body = {
data: {
users: response.users.map((user) => presentUser(user)),
},
};
}
);
export default router;
@@ -66,7 +66,7 @@ Object {
exports[`#documents.update should require text while appending 1`] = `
Object {
"error": "validation_error",
"message": "ValidationError: text is required while appending",
"message": "text is required while appending",
"ok": false,
"status": 400,
}
+60 -141
View File
@@ -30,9 +30,7 @@ describe("#documents.info", () => {
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toEqual(
"ValidationError: one of id or shareId is required"
);
expect(body.message).toEqual("one of id or shareId is required");
});
it("should return published document", async () => {
@@ -233,7 +231,7 @@ describe("#documents.info", () => {
expect(body.data.document.id).toEqual(document.id);
expect(body.data.document.createdBy).toEqual(undefined);
expect(body.data.document.updatedBy).toEqual(undefined);
expect(body.data.sharedTree).toEqual(document.toJSON());
expect(body.data.sharedTree).toEqual(await document.toNavigationNode());
});
it("should not return sharedTree if child documents not shared", async () => {
const { document, user } = await seed();
@@ -552,113 +550,6 @@ describe("#documents.export", () => {
expect(body.data).toEqual(DocumentHelper.toMarkdown(document));
});
it("should return document from shareId without token", async () => {
const { document, user } = await seed();
const share = await buildShare({
documentId: document.id,
teamId: document.teamId,
userId: user.id,
});
const res = await server.post("/api/documents.export", {
body: {
shareId: share.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data).toEqual(DocumentHelper.toMarkdown(document));
});
it("should not return document from revoked shareId", async () => {
const { document, user } = await seed();
const share = await buildShare({
documentId: document.id,
teamId: document.teamId,
userId: user.id,
});
await share.revoke(user.id);
const res = await server.post("/api/documents.export", {
body: {
shareId: share.id,
},
});
expect(res.status).toEqual(400);
});
it("should not return document from archived shareId", async () => {
const { document, user } = await seed();
const share = await buildShare({
documentId: document.id,
teamId: document.teamId,
userId: user.id,
});
await document.archive(user.id);
const res = await server.post("/api/documents.export", {
body: {
shareId: share.id,
},
});
expect(res.status).toEqual(400);
});
it("should return document from shareId with token", async () => {
const { user, document } = await seed();
const share = await buildShare({
documentId: document.id,
teamId: document.teamId,
userId: user.id,
});
const res = await server.post("/api/documents.export", {
body: {
token: user.getJwtToken(),
shareId: share.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data).toEqual(DocumentHelper.toMarkdown(document));
});
it("should return draft document from shareId with token", async () => {
const { user, document } = await seed();
document.publishedAt = null;
await document.save();
const share = await buildShare({
documentId: document.id,
teamId: document.teamId,
userId: user.id,
});
const res = await server.post("/api/documents.export", {
body: {
token: user.getJwtToken(),
shareId: share.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data).toEqual(DocumentHelper.toMarkdown(document));
});
it("should return document from shareId in collection not a member of", async () => {
const { user, document, collection } = await seed();
const share = await buildShare({
documentId: document.id,
teamId: document.teamId,
userId: user.id,
});
collection.permission = null;
await collection.save();
const res = await server.post("/api/documents.export", {
body: {
token: user.getJwtToken(),
shareId: share.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data).toEqual(DocumentHelper.toMarkdown(document));
});
it("should require authorization without token", async () => {
const { document } = await seed();
const res = await server.post("/api/documents.export", {
@@ -680,15 +571,6 @@ describe("#documents.export", () => {
});
expect(res.status).toEqual(403);
});
it("should require a valid shareId", async () => {
const res = await server.post("/api/documents.export", {
body: {
shareId: 123,
},
});
expect(res.status).toEqual(400);
});
});
describe("#documents.list", () => {
@@ -1163,20 +1045,6 @@ describe("#documents.search_titles", () => {
});
describe("#documents.search", () => {
it("should fail for invalid shareId", async () => {
const { user } = await seed();
const res = await server.post("/api/documents.search", {
body: {
token: user.getJwtToken(),
query: "much",
shareId: "invalid",
},
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toEqual("shareId: Invalid uuid");
});
it("should return results", async () => {
const { user } = await seed();
const res = await server.post("/api/documents.search", {
@@ -1954,10 +1822,30 @@ describe("#documents.move", () => {
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toEqual(
"ValidationError: infinite loop detected, cannot nest a document inside itself"
"infinite loop detected, cannot nest a document inside itself"
);
});
it("should fail if attempting to nest doc within a draft", async () => {
const { user, document, collection } = await seed();
const draft = await buildDraftDocument({
userId: user.id,
teamId: document.teamId,
collectionId: collection.id,
});
const res = await server.post("/api/documents.move", {
body: {
id: document.id,
collectionId: collection.id,
parentDocumentId: draft.id,
token: user.getJwtToken(),
},
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toEqual("Cannot move document inside a draft");
});
it("should require id", async () => {
const { user } = await seed();
const res = await server.post("/api/documents.move", {
@@ -2418,7 +2306,7 @@ describe("#documents.create", () => {
expect(res.status).toEqual(400);
expect(body.message).toBe(
"ValidationError: collectionId is required to create a template document"
"collectionId is required to create a template document"
);
});
@@ -2436,9 +2324,7 @@ describe("#documents.create", () => {
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toBe(
"ValidationError: collectionId is required to publish"
);
expect(body.message).toBe("collectionId is required to publish");
});
it("should not allow creating a nested doc without a collection", async () => {
@@ -2456,7 +2342,7 @@ describe("#documents.create", () => {
expect(res.status).toEqual(400);
expect(body.message).toBe(
"ValidationError: collectionId is required to create a nested document"
"collectionId is required to create a nested document"
);
});
@@ -2736,7 +2622,7 @@ describe("#documents.update", () => {
title: "Another doc",
children: [],
},
{ ...document.toJSON(), children: [] },
{ ...(await document.toNavigationNode()), children: [] },
],
},
];
@@ -2932,6 +2818,39 @@ describe("#documents.update", () => {
expect(res.status).toBe(400);
expect(body.message).toBe("id: Required");
});
describe("apiVersion=2", () => {
it("should successfully publish a draft", async () => {
const { user, team, collection } = await seed();
const document = await buildDraftDocument({
title: "title",
text: "text",
teamId: team.id,
});
const res = await server.post("/api/documents.update", {
body: {
apiVersion: 2,
token: user.getJwtToken(),
id: document.id,
title: "Updated title",
text: "Updated text",
lastRevision: document.revisionCount,
collectionId: collection.id,
publish: true,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.document.collectionId).toBe(collection.id);
expect(body.data.document.title).toBe("Updated title");
expect(body.data.document.text).toBe("Updated text");
expect(body.data.collection.icon).toBe(collection.icon);
expect(body.data.collection.documents.length).toBe(
collection.documentStructure!.length + 1
);
});
});
});
describe("#documents.archive", () => {
+73 -52
View File
@@ -59,7 +59,7 @@ router.post(
pagination(),
validate(T.DocumentsListSchema),
async (ctx: APIContext<T.DocumentsListReq>) => {
let { sort } = ctx.input;
let { sort } = ctx.input.body;
const {
direction,
template,
@@ -67,10 +67,10 @@ router.post(
backlinkDocumentId,
parentDocumentId,
userId: createdById,
} = ctx.input;
} = ctx.input.body;
// always filter by the current team
const { user } = ctx.state;
const { user } = ctx.state.auth;
let where: WhereOptions<Document> = {
teamId: user.teamId,
archivedAt: {
@@ -176,8 +176,8 @@ router.post(
pagination(),
validate(T.DocumentsArchivedSchema),
async (ctx: APIContext<T.DocumentsArchivedReq>) => {
const { sort, direction } = ctx.input;
const { user } = ctx.state;
const { sort, direction } = ctx.input.body;
const { user } = ctx.state.auth;
const collectionIds = await user.collectionIds();
const collectionScope: Readonly<ScopeOptions> = {
method: ["withCollectionPermissions", user.id],
@@ -220,8 +220,8 @@ router.post(
pagination(),
validate(T.DocumentsDeletedSchema),
async (ctx: APIContext<T.DocumentsDeletedReq>) => {
const { sort, direction } = ctx.input;
const { user } = ctx.state;
const { sort, direction } = ctx.input.body;
const { user } = ctx.state.auth;
const collectionIds = await user.collectionIds({
paranoid: false,
});
@@ -280,8 +280,8 @@ router.post(
pagination(),
validate(T.DocumentsViewedSchema),
async (ctx: APIContext<T.DocumentsViewedReq>) => {
const { sort, direction } = ctx.input;
const { user } = ctx.state;
const { sort, direction } = ctx.input.body;
const { user } = ctx.state.auth;
const collectionIds = await user.collectionIds();
const userId = user.id;
const views = await View.findAll({
@@ -333,8 +333,8 @@ router.post(
pagination(),
validate(T.DocumentsDraftsSchema),
async (ctx: APIContext<T.DocumentsDraftsReq>) => {
const { collectionId, dateFilter, direction, sort } = ctx.input;
const { user } = ctx.state;
const { collectionId, dateFilter, direction, sort } = ctx.input.body;
const { user } = ctx.state.auth;
if (collectionId) {
const collection = await Collection.scope({
@@ -396,8 +396,8 @@ router.post(
}),
validate(T.DocumentsInfoSchema),
async (ctx: APIContext<T.DocumentsInfoReq>) => {
const { id, shareId, apiVersion } = ctx.input;
const { user } = ctx.state;
const { id, shareId, apiVersion } = ctx.input.body;
const { user } = ctx.state.auth;
const teamFromCtx = await getTeamFromContext(ctx);
const { document, share, collection } = await documentLoader({
id,
@@ -442,13 +442,12 @@ router.post(
}),
validate(T.DocumentsExportSchema),
async (ctx: APIContext<T.DocumentsExportReq>) => {
const { id, shareId } = ctx.input;
const { user } = ctx.state;
const { id } = ctx.input.body;
const { user } = ctx.state.auth;
const accept = ctx.request.headers["accept"];
const { document } = await documentLoader({
id,
shareId,
user,
// We need the collaborative state to generate HTML.
includeState: !accept?.includes("text/markdown"),
@@ -495,8 +494,8 @@ router.post(
auth({ member: true }),
validate(T.DocumentsRestoreSchema),
async (ctx: APIContext<T.DocumentsRestoreReq>) => {
const { id, collectionId, revisionId } = ctx.input;
const { user } = ctx.state;
const { id, collectionId, revisionId } = ctx.input.body;
const { user } = ctx.state.auth;
const document = await Document.findByPk(id, {
userId: user.id,
paranoid: false,
@@ -605,9 +604,9 @@ router.post(
dateFilter,
collectionId,
userId,
} = ctx.input;
} = ctx.input.body;
const { offset, limit } = ctx.state.pagination;
const { user } = ctx.state;
const { user } = ctx.state.auth;
let collaboratorIds = undefined;
if (collectionId) {
@@ -661,18 +660,19 @@ router.post(
shareId,
snippetMinWords,
snippetMaxWords,
} = ctx.input;
} = ctx.input.body;
const { offset, limit } = ctx.state.pagination;
// this typing is a bit ugly, would be better to use a type like ContextWithState
// but that doesn't adequately handle cases when auth is optional
const { user }: { user: User | undefined } = ctx.state;
// Unfortunately, this still doesn't adequately handle cases when auth is optional
const { user } = ctx.state.auth;
let teamId;
let response;
if (shareId) {
const teamFromCtx = await getTeamFromContext(ctx);
const { share, document } = await documentLoader({
teamId: teamFromCtx?.id,
shareId,
user,
});
@@ -746,7 +746,7 @@ router.post(
userId: user?.id,
teamId,
shareId,
source: ctx.state.authType || "app", // we'll consider anything that isn't "api" to be "app"
source: ctx.state.auth.type || "app", // we'll consider anything that isn't "api" to be "app"
query,
results: totalCount,
});
@@ -765,8 +765,8 @@ router.post(
auth({ member: true }),
validate(T.DocumentsTemplatizeSchema),
async (ctx: APIContext<T.DocumentsTemplatizeReq>) => {
const { id } = ctx.input;
const { user } = ctx.state;
const { id } = ctx.input.body;
const { user } = ctx.state.auth;
const original = await Document.findByPk(id, {
userId: user.id,
@@ -826,9 +826,10 @@ router.post(
templateId,
collectionId,
append,
} = ctx.input;
apiVersion,
} = ctx.input.body;
const editorVersion = ctx.headers["x-editor-version"] as string | undefined;
const { user } = ctx.state;
const { user } = ctx.state.auth;
let collection: Collection | null | undefined;
const document = await Document.findByPk(id, {
@@ -845,8 +846,6 @@ router.post(
"collectionId is required to publish a draft without collection"
);
collection = await Collection.findByPk(collectionId as string);
} else {
collection = document.collection;
}
authorize(user, "publish", collection);
}
@@ -855,8 +854,8 @@ router.post(
throw InvalidRequestError("Document has changed since last revision");
}
const updatedDocument = await sequelize.transaction(async (transaction) => {
return documentUpdater({
collection = await sequelize.transaction(async (transaction) => {
await documentUpdater({
document,
user,
title,
@@ -870,14 +869,26 @@ router.post(
transaction,
ip: ctx.request.ip,
});
return await Collection.scope({
method: ["withMembership", user.id],
}).findByPk(document.collectionId, { transaction });
});
updatedDocument.updatedBy = user;
updatedDocument.collection = collection;
document.updatedBy = user;
document.collection = collection;
ctx.body = {
data: await presentDocument(updatedDocument),
policies: presentPolicies(user, [updatedDocument]),
data:
apiVersion === 2
? {
document: await presentDocument(document),
collection: collection
? presentCollection(collection)
: undefined,
}
: await presentDocument(document),
policies: presentPolicies(user, [document, collection]),
};
}
);
@@ -887,8 +898,8 @@ router.post(
auth(),
validate(T.DocumentsMoveSchema),
async (ctx: APIContext<T.DocumentsMoveReq>) => {
const { id, collectionId, parentDocumentId, index } = ctx.input;
const { user } = ctx.state;
const { id, collectionId, parentDocumentId, index } = ctx.input.body;
const { user } = ctx.state.auth;
const document = await Document.findByPk(id, {
userId: user.id,
});
@@ -904,6 +915,10 @@ router.post(
userId: user.id,
});
authorize(user, "update", parent);
if (!parent.publishedAt) {
throw InvalidRequestError("Cannot move document inside a draft");
}
}
const {
@@ -941,8 +956,8 @@ router.post(
auth(),
validate(T.DocumentsArchiveSchema),
async (ctx: APIContext<T.DocumentsArchiveReq>) => {
const { id } = ctx.input;
const { user } = ctx.state;
const { id } = ctx.input.body;
const { user } = ctx.state.auth;
const document = await Document.findByPk(id, {
userId: user.id,
@@ -974,8 +989,8 @@ router.post(
auth(),
validate(T.DocumentsDeleteSchema),
async (ctx: APIContext<T.DocumentsDeleteReq>) => {
const { id, permanent } = ctx.input;
const { user } = ctx.state;
const { id, permanent } = ctx.input.body;
const { user } = ctx.state.auth;
if (permanent) {
const document = await Document.findByPk(id, {
@@ -1039,8 +1054,8 @@ router.post(
auth(),
validate(T.DocumentsUnpublishSchema),
async (ctx: APIContext<T.DocumentsUnpublishReq>) => {
const { id } = ctx.input;
const { user } = ctx.state;
const { id, apiVersion } = ctx.input.body;
const { user } = ctx.state.auth;
const document = await Document.findByPk(id, {
userId: user.id,
@@ -1068,7 +1083,15 @@ router.post(
});
ctx.body = {
data: await presentDocument(document),
data:
apiVersion === 2
? {
document: await presentDocument(document),
collection: document.collection
? presentCollection(document.collection)
: undefined,
}
: await presentDocument(document),
policies: presentPolicies(user, [document]),
};
}
@@ -1083,9 +1106,7 @@ router.post(
throw InvalidRequestError("Request type must be multipart/form-data");
}
// String as this is always multipart/form-data
const publish = ctx.input.publish === "true";
const { collectionId, parentDocumentId } = ctx.input;
const { collectionId, parentDocumentId, publish } = ctx.input.body;
const file = ctx.request.files
? Object.values(ctx.request.files)[0]
@@ -1102,7 +1123,7 @@ router.post(
);
}
const { user } = ctx.state;
const { user } = ctx.state.auth;
const collection = await Collection.scope({
method: ["withMembership", user.id],
@@ -1173,10 +1194,10 @@ router.post(
parentDocumentId,
templateId,
template,
} = ctx.input;
} = ctx.input.body;
const editorVersion = ctx.headers["x-editor-version"] as string | undefined;
const { user } = ctx.state;
const { user } = ctx.state.auth;
let collection;
+142 -116
View File
@@ -2,12 +2,13 @@ import { isEmpty } from "lodash";
import isUUID from "validator/lib/isUUID";
import { z } from "zod";
import { SHARE_URL_SLUG_REGEX } from "@shared/utils/urlHelpers";
import BaseSchema from "@server/routes/api/BaseSchema";
const DocumentsSortParamsSchema = z.object({
/** Specifies the attributes by which documents will be sorted in the list */
sort: z
.string()
.refine((val) => ["createdAt", "updatedAt", "index"].includes(val))
.refine((val) => ["createdAt", "updatedAt", "index", "title"].includes(val))
.default("updatedAt"),
/** Specifies the sort order with respect to sort field */
@@ -39,63 +40,70 @@ const BaseIdSchema = z.object({
id: z.string(),
});
export const DocumentsListSchema = DocumentsSortParamsSchema.extend({
/** Id of the user who created the doc */
userId: z.string().uuid().optional(),
export const DocumentsListSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema.extend({
/** Id of the user who created the doc */
userId: z.string().uuid().optional(),
/** Alias for userId - kept for backwards compatibility */
user: z.string().uuid().optional(),
/** Alias for userId - kept for backwards compatibility */
user: z.string().uuid().optional(),
/** Id of the collection to which the document belongs */
collectionId: z.string().uuid().optional(),
/** Id of the collection to which the document belongs */
collectionId: z.string().uuid().optional(),
/** Alias for collectionId - kept for backwards compatibility */
collection: z.string().uuid().optional(),
/** Alias for collectionId - kept for backwards compatibility */
collection: z.string().uuid().optional(),
/** Id of the backlinked document */
backlinkDocumentId: z.string().uuid().optional(),
/** Id of the backlinked document */
backlinkDocumentId: z.string().uuid().optional(),
/** Id of the parent document to which the document belongs */
parentDocumentId: z.string().uuid().nullish(),
/** Id of the parent document to which the document belongs */
parentDocumentId: z.string().uuid().nullish(),
/** Boolean which denotes whether the document is a template */
template: z.boolean().optional(),
})
/** Boolean which denotes whether the document is a template */
template: z.boolean().optional(),
}),
// Maintains backwards compatibility
.transform((doc) => {
doc.collectionId = doc.collectionId || doc.collection;
doc.userId = doc.userId || doc.user;
delete doc.collection;
delete doc.user;
}).transform((req) => {
req.body.collectionId = req.body.collectionId || req.body.collection;
req.body.userId = req.body.userId || req.body.user;
delete req.body.collection;
delete req.body.user;
return doc;
});
return req;
});
export type DocumentsListReq = z.infer<typeof DocumentsListSchema>;
export const DocumentsArchivedSchema = DocumentsSortParamsSchema.extend({});
export const DocumentsArchivedSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema.extend({}),
});
export type DocumentsArchivedReq = z.infer<typeof DocumentsArchivedSchema>;
export const DocumentsDeletedSchema = DocumentsSortParamsSchema.extend({});
export const DocumentsDeletedSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema.extend({}),
});
export type DocumentsDeletedReq = z.infer<typeof DocumentsDeletedSchema>;
export const DocumentsViewedSchema = DocumentsSortParamsSchema.extend({});
export const DocumentsViewedSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema.extend({}),
});
export type DocumentsViewedReq = z.infer<typeof DocumentsViewedSchema>;
export const DocumentsDraftsSchema = DocumentsSortParamsSchema.merge(
DateFilterSchema
).extend({
/** Id of the collection to which the document belongs */
collectionId: z.string().uuid().optional(),
export const DocumentsDraftsSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema.merge(DateFilterSchema).extend({
/** Id of the collection to which the document belongs */
collectionId: z.string().uuid().optional(),
}),
});
export type DocumentsDraftsReq = z.infer<typeof DocumentsDraftsSchema>;
export const DocumentsInfoSchema = z
.object({
export const DocumentsInfoSchema = BaseSchema.extend({
body: z.object({
/** Id of the document to be retrieved */
id: z.string().optional(),
@@ -107,143 +115,160 @@ export const DocumentsInfoSchema = z
/** Version of the API to be used */
apiVersion: z.number().optional(),
})
.refine((obj) => !(isEmpty(obj.id) && isEmpty(obj.shareId)), {
message: "one of id or shareId is required",
});
}),
}).refine((req) => !(isEmpty(req.body.id) && isEmpty(req.body.shareId)), {
message: "one of id or shareId is required",
});
export type DocumentsInfoReq = z.infer<typeof DocumentsInfoSchema>;
export const DocumentsExportSchema = z
.object({
/** Id of the document to be exported */
id: z.string().uuid().optional(),
/** Share Id, if available */
shareId: z.string().uuid().optional(),
})
.refine((obj) => !(isEmpty(obj.id) && isEmpty(obj.shareId)), {
message: "one of id or shareId is required",
});
export const DocumentsExportSchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type DocumentsExportReq = z.infer<typeof DocumentsExportSchema>;
export const DocumentsRestoreSchema = BaseIdSchema.extend({
/** Id of the collection to which the document belongs */
collectionId: z.string().uuid().optional(),
export const DocumentsRestoreSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of the collection to which the document belongs */
collectionId: z.string().uuid().optional(),
/** Id of document revision */
revisionId: z.string().uuid().optional(),
/** Id of document revision */
revisionId: z.string().uuid().optional(),
}),
});
export type DocumentsRestoreReq = z.infer<typeof DocumentsRestoreSchema>;
export const DocumentsSearchSchema = SearchQuerySchema.merge(
DateFilterSchema
).extend({
/** Whether to include archived docs in results */
includeArchived: z.boolean().optional(),
export const DocumentsSearchSchema = BaseSchema.extend({
body: SearchQuerySchema.merge(DateFilterSchema).extend({
/** Whether to include archived docs in results */
includeArchived: z.boolean().optional(),
/** Whether to include drafts in results */
includeDrafts: z.boolean().optional(),
/** Whether to include drafts in results */
includeDrafts: z.boolean().optional(),
/** Filter results for team based on the collection */
collectionId: z.string().uuid().optional(),
/** Filter results for team based on the collection */
collectionId: z.string().uuid().optional(),
/** Filter results based on user */
userId: z.string().uuid().optional(),
/** Filter results based on user */
userId: z.string().uuid().optional(),
/** Filter results for the team derived from shareId */
shareId: z.string().uuid().optional(),
/** Filter results for the team derived from shareId */
shareId: z
.string()
.refine((val) => isUUID(val) || SHARE_URL_SLUG_REGEX.test(val))
.optional(),
/** Min words to be shown in the results snippets */
snippetMinWords: z.number().default(20),
/** Min words to be shown in the results snippets */
snippetMinWords: z.number().default(20),
/** Max words to be accomodated in the results snippets */
snippetMaxWords: z.number().default(30),
/** Max words to be accomodated in the results snippets */
snippetMaxWords: z.number().default(30),
}),
});
export type DocumentsSearchReq = z.infer<typeof DocumentsSearchSchema>;
export const DocumentsTemplatizeSchema = BaseIdSchema.extend({});
export const DocumentsTemplatizeSchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type DocumentsTemplatizeReq = z.infer<typeof DocumentsTemplatizeSchema>;
export const DocumentsUpdateSchema = BaseIdSchema.extend({
/** Doc title to be updated */
title: z.string().optional(),
export const DocumentsUpdateSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Doc title to be updated */
title: z.string().optional(),
/** Doc text to be updated */
text: z.string().optional(),
/** Doc text to be updated */
text: z.string().optional(),
/** Boolean to denote if the doc should occupy full width */
fullWidth: z.boolean().optional(),
/** Boolean to denote if the doc should occupy full width */
fullWidth: z.boolean().optional(),
/** Boolean to denote if the doc should be published */
publish: z.boolean().optional(),
/** Boolean to denote if the doc should be published */
publish: z.boolean().optional(),
/** Revision to compare against document revision count */
lastRevision: z.number().optional(),
/** Revision to compare against document revision count */
lastRevision: z.number().optional(),
/** Doc template Id */
templateId: z.string().uuid().nullish(),
/** Doc template Id */
templateId: z.string().uuid().nullish(),
/** Doc collection Id */
collectionId: z.string().uuid().optional(),
/** Doc collection Id */
collectionId: z.string().uuid().optional(),
/** Boolean to denote if text should be appended */
append: z.boolean().optional(),
}).refine((obj) => !(obj.append && !obj.text), {
/** Boolean to denote if text should be appended */
append: z.boolean().optional(),
/** Version of the API to be used */
apiVersion: z.number().optional(),
}),
}).refine((req) => !(req.body.append && !req.body.text), {
message: "text is required while appending",
});
export type DocumentsUpdateReq = z.infer<typeof DocumentsUpdateSchema>;
export const DocumentsMoveSchema = BaseIdSchema.extend({
/** Id of collection to which the doc is supposed to be moved */
collectionId: z.string().uuid(),
export const DocumentsMoveSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of collection to which the doc is supposed to be moved */
collectionId: z.string().uuid(),
/** Parent Id, in case if the doc is moved to a new parent */
parentDocumentId: z.string().uuid().nullish(),
/** Parent Id, in case if the doc is moved to a new parent */
parentDocumentId: z.string().uuid().nullish(),
/** Helps evaluate the new index in collection structure upon move */
index: z.number().gte(0).optional(),
}).refine((obj) => !(obj.parentDocumentId === obj.id), {
/** Helps evaluate the new index in collection structure upon move */
index: z.number().gte(0).optional(),
}),
}).refine((req) => !(req.body.parentDocumentId === req.body.id), {
message: "infinite loop detected, cannot nest a document inside itself",
});
export type DocumentsMoveReq = z.infer<typeof DocumentsMoveSchema>;
export const DocumentsArchiveSchema = BaseIdSchema.extend({});
export const DocumentsArchiveSchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type DocumentsArchiveReq = z.infer<typeof DocumentsArchiveSchema>;
export const DocumentsDeleteSchema = BaseIdSchema.extend({
/** Whether to permanently delete the doc as opposed to soft-delete */
permanent: z.boolean().optional(),
export const DocumentsDeleteSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Whether to permanently delete the doc as opposed to soft-delete */
permanent: z.boolean().optional(),
}),
});
export type DocumentsDeleteReq = z.infer<typeof DocumentsDeleteSchema>;
export const DocumentsUnpublishSchema = BaseIdSchema.extend({});
export const DocumentsUnpublishSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Version of the API to be used */
apiVersion: z.number().optional(),
}),
});
export type DocumentsUnpublishReq = z.infer<typeof DocumentsUnpublishSchema>;
export const DocumentsImportSchema = z.object({
/** Whether to publish the imported docs. String due to multi-part form upload */
publish: z.string().optional(),
export const DocumentsImportSchema = BaseSchema.extend({
body: z.object({
/** Whether to publish the imported docs. String as this is always multipart/form-data */
publish: z.preprocess((val) => val === "true", z.boolean()).optional(),
/** Import docs to this collection */
collectionId: z.string().uuid(),
/** Import docs to this collection */
collectionId: z.string().uuid(),
/** Import under this parent doc */
parentDocumentId: z.string().uuid().nullish(),
/** Import under this parent doc */
parentDocumentId: z.string().uuid().nullish(),
}),
});
export type DocumentsImportReq = z.infer<typeof DocumentsImportSchema>;
export const DocumentsCreateSchema = z
.object({
export const DocumentsCreateSchema = BaseSchema.extend({
body: z.object({
/** Doc title */
title: z.string().default(""),
@@ -264,14 +289,15 @@ export const DocumentsCreateSchema = z
/** Whether to create a template doc */
template: z.boolean().optional(),
})
.refine((obj) => !(obj.parentDocumentId && !obj.collectionId), {
}),
})
.refine((req) => !(req.body.parentDocumentId && !req.body.collectionId), {
message: "collectionId is required to create a nested document",
})
.refine((obj) => !(obj.template && !obj.collectionId), {
.refine((req) => !(req.body.template && !req.body.collectionId), {
message: "collectionId is required to create a template document",
})
.refine((obj) => !(obj.publish && !obj.collectionId), {
.refine((req) => !(req.body.publish && !req.body.collectionId), {
message: "collectionId is required to publish",
});
+2 -2
View File
@@ -17,7 +17,7 @@ router.post(
pagination(),
validate(T.EventsListSchema),
async (ctx: APIContext<T.EventsListReq>) => {
const { user } = ctx.state;
const { user } = ctx.state.auth;
const {
sort,
direction,
@@ -26,7 +26,7 @@ router.post(
collectionId,
name,
auditLog,
} = ctx.input;
} = ctx.input.body;
let where: WhereOptions<Event> = {
name: Event.ACTIVITY_EVENTS,
+24 -21
View File
@@ -1,32 +1,35 @@
import { z } from "zod";
import BaseSchema from "@server/routes/api/BaseSchema";
export const EventsListSchema = z.object({
/** Id of the user who performed the action */
actorId: z.string().uuid().optional(),
export const EventsListSchema = BaseSchema.extend({
body: z.object({
/** Id of the user who performed the action */
actorId: z.string().uuid().optional(),
/** Id of the document to filter the events for */
documentId: z.string().uuid().optional(),
/** Id of the document to filter the events for */
documentId: z.string().uuid().optional(),
/** Id of the collection to filter the events for */
collectionId: z.string().uuid().optional(),
/** Id of the collection to filter the events for */
collectionId: z.string().uuid().optional(),
/** Whether to include audit events */
auditLog: z.boolean().default(false),
/** Whether to include audit events */
auditLog: z.boolean().default(false),
/** Name of the event to retrieve */
name: z.string().optional(),
/** Name of the event to retrieve */
name: z.string().optional(),
/** The attribute to sort the events by */
sort: z
.string()
.refine((val) => ["name", "createdAt"].includes(val))
.default("createdAt"),
/** The attribute to sort the events by */
sort: z
.string()
.refine((val) => ["name", "createdAt"].includes(val))
.default("createdAt"),
/** The direction to sort the events */
direction: z
.string()
.optional()
.transform((val) => (val !== "ASC" ? "DESC" : val)),
/** The direction to sort the events */
direction: z
.string()
.optional()
.transform((val) => (val !== "ASC" ? "DESC" : val)),
}),
});
export type EventsListReq = z.infer<typeof EventsListSchema>;
+38 -30
View File
@@ -7,33 +7,37 @@ import auth from "@server/middlewares/authentication";
import { FileOperation, Team } from "@server/models";
import { authorize } from "@server/policies";
import { presentFileOperation } from "@server/presenters";
import { ContextWithState } from "@server/types";
import { APIContext } from "@server/types";
import { getSignedUrl } from "@server/utils/s3";
import { assertIn, assertSort, assertUuid } from "@server/validation";
import pagination from "./middlewares/pagination";
const router = new Router();
router.post("fileOperations.info", auth({ admin: true }), async (ctx) => {
const { id } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state;
const fileOperation = await FileOperation.findByPk(id, {
rejectOnEmpty: true,
});
router.post(
"fileOperations.info",
auth({ admin: true }),
async (ctx: APIContext) => {
const { id } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state.auth;
const fileOperation = await FileOperation.findByPk(id, {
rejectOnEmpty: true,
});
authorize(user, "read", fileOperation);
authorize(user, "read", fileOperation);
ctx.body = {
data: presentFileOperation(fileOperation),
};
});
ctx.body = {
data: presentFileOperation(fileOperation),
};
}
);
router.post(
"fileOperations.list",
auth({ admin: true }),
pagination(),
async (ctx) => {
async (ctx: APIContext) => {
let { direction } = ctx.request.body;
const { sort = "createdAt", type } = ctx.request.body;
assertIn(type, Object.values(FileOperationType));
@@ -42,7 +46,7 @@ router.post(
if (direction !== "ASC") {
direction = "DESC";
}
const { user } = ctx.state;
const { user } = ctx.state.auth;
const where: WhereOptions<FileOperation> = {
teamId: user.teamId,
type,
@@ -69,11 +73,11 @@ router.post(
}
);
const handleFileOperationsRedirect = async (ctx: ContextWithState) => {
const handleFileOperationsRedirect = async (ctx: APIContext) => {
const id = ctx.request.body?.id ?? ctx.request.query?.id;
assertUuid(id, "id is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const fileOperation = await FileOperation.unscoped().findByPk(id, {
rejectOnEmpty: true,
});
@@ -98,21 +102,25 @@ router.post(
handleFileOperationsRedirect
);
router.post("fileOperations.delete", auth({ admin: true }), async (ctx) => {
const { id } = ctx.request.body;
assertUuid(id, "id is required");
router.post(
"fileOperations.delete",
auth({ admin: true }),
async (ctx: APIContext) => {
const { id } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state;
const fileOperation = await FileOperation.unscoped().findByPk(id, {
rejectOnEmpty: true,
});
authorize(user, "delete", fileOperation);
const { user } = ctx.state.auth;
const fileOperation = await FileOperation.unscoped().findByPk(id, {
rejectOnEmpty: true,
});
authorize(user, "delete", fileOperation);
await fileOperationDeleter(fileOperation, user, ctx.request.ip);
await fileOperationDeleter(fileOperation, user, ctx.request.ip);
ctx.body = {
success: true,
};
});
ctx.body = {
success: true,
};
}
);
export default router;
+68 -58
View File
@@ -10,12 +10,13 @@ import {
presentUser,
presentGroupMembership,
} from "@server/presenters";
import { APIContext } from "@server/types";
import { assertPresent, assertUuid, assertSort } from "@server/validation";
import pagination from "./middlewares/pagination";
const router = new Router();
router.post("groups.list", auth(), pagination(), async (ctx) => {
router.post("groups.list", auth(), pagination(), async (ctx: APIContext) => {
let { direction } = ctx.request.body;
const { sort = "updatedAt" } = ctx.request.body;
if (direction !== "ASC") {
@@ -23,7 +24,7 @@ router.post("groups.list", auth(), pagination(), async (ctx) => {
}
assertSort(sort, Group);
const { user } = ctx.state;
const { user } = ctx.state.auth;
const groups = await Group.findAll({
where: {
teamId: user.teamId,
@@ -52,11 +53,11 @@ router.post("groups.list", auth(), pagination(), async (ctx) => {
};
});
router.post("groups.info", auth(), async (ctx) => {
router.post("groups.info", auth(), async (ctx: APIContext) => {
const { id } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const group = await Group.findByPk(id);
authorize(user, "read", group);
@@ -66,11 +67,11 @@ router.post("groups.info", auth(), async (ctx) => {
};
});
router.post("groups.create", auth(), async (ctx) => {
router.post("groups.create", auth(), async (ctx: APIContext) => {
const { name } = ctx.request.body;
assertPresent(name, "name is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
authorize(user, "createGroup", user.team);
const g = await Group.create({
name,
@@ -98,12 +99,12 @@ router.post("groups.create", auth(), async (ctx) => {
};
});
router.post("groups.update", auth(), async (ctx) => {
router.post("groups.update", auth(), async (ctx: APIContext) => {
const { id, name } = ctx.request.body;
assertPresent(name, "name is required");
assertUuid(id, "id is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const group = await Group.findByPk(id);
authorize(user, "update", group);
@@ -129,11 +130,11 @@ router.post("groups.update", auth(), async (ctx) => {
};
});
router.post("groups.delete", auth(), async (ctx) => {
router.post("groups.delete", auth(), async (ctx: APIContext) => {
const { id } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state;
const { user } = ctx.state.auth;
const group = await Group.findByPk(id);
authorize(user, "delete", group);
@@ -154,61 +155,68 @@ router.post("groups.delete", auth(), async (ctx) => {
};
});
router.post("groups.memberships", auth(), pagination(), async (ctx) => {
const { id, query } = ctx.request.body;
assertUuid(id, "id is required");
router.post(
"groups.memberships",
auth(),
pagination(),
async (ctx: APIContext) => {
const { id, query } = ctx.request.body;
assertUuid(id, "id is required");
const { user } = ctx.state;
const group = await Group.findByPk(id);
authorize(user, "read", group);
let userWhere;
const { user } = ctx.state.auth;
const group = await Group.findByPk(id);
authorize(user, "read", group);
let userWhere;
if (query) {
userWhere = {
name: {
[Op.iLike]: `%${query}%`,
if (query) {
userWhere = {
name: {
[Op.iLike]: `%${query}%`,
},
};
}
const memberships = await GroupUser.findAll({
where: {
groupId: id,
},
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
include: [
{
model: User,
as: "user",
where: userWhere,
required: true,
},
],
});
ctx.body = {
pagination: ctx.state.pagination,
data: {
groupMemberships: memberships.map((membership) =>
presentGroupMembership(membership, { includeUser: true })
),
users: memberships.map((membership) => presentUser(membership.user)),
},
};
}
);
const memberships = await GroupUser.findAll({
where: {
groupId: id,
},
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
include: [
{
model: User,
as: "user",
where: userWhere,
required: true,
},
],
});
ctx.body = {
pagination: ctx.state.pagination,
data: {
groupMemberships: memberships.map((membership) =>
presentGroupMembership(membership, { includeUser: true })
),
users: memberships.map((membership) => presentUser(membership.user)),
},
};
});
router.post("groups.add_user", auth(), async (ctx) => {
router.post("groups.add_user", auth(), async (ctx: APIContext) => {
const { id, userId } = ctx.request.body;
assertUuid(id, "id is required");
assertUuid(userId, "userId is required");
const actor = ctx.state.auth.user;
const user = await User.findByPk(userId);
authorize(ctx.state.user, "read", user);
authorize(actor, "read", user);
let group = await Group.findByPk(id);
authorize(ctx.state.user, "update", group);
authorize(actor, "update", group);
let membership = await GroupUser.findOne({
where: {
@@ -220,7 +228,7 @@ router.post("groups.add_user", auth(), async (ctx) => {
if (!membership) {
await group.$add("user", user, {
through: {
createdById: ctx.state.user.id,
createdById: actor.id,
},
});
// reload to get default scope
@@ -240,7 +248,7 @@ router.post("groups.add_user", auth(), async (ctx) => {
userId,
teamId: user.teamId,
modelId: group.id,
actorId: ctx.state.user.id,
actorId: actor.id,
data: {
name: user.name,
},
@@ -259,16 +267,18 @@ router.post("groups.add_user", auth(), async (ctx) => {
};
});
router.post("groups.remove_user", auth(), async (ctx) => {
router.post("groups.remove_user", auth(), async (ctx: APIContext) => {
const { id, userId } = ctx.request.body;
assertUuid(id, "id is required");
assertUuid(userId, "userId is required");
const actor = ctx.state.auth.user;
let group = await Group.findByPk(id);
authorize(ctx.state.user, "update", group);
authorize(actor, "update", group);
const user = await User.findByPk(userId);
authorize(ctx.state.user, "read", user);
authorize(actor, "read", user);
await group.$remove("user", user);
await Event.create({
@@ -276,7 +286,7 @@ router.post("groups.remove_user", auth(), async (ctx) => {
userId,
modelId: group.id,
teamId: user.teamId,
actorId: ctx.state.user.id,
actorId: actor.id,
data: {
name: user.name,
},
+62 -27
View File
@@ -1,4 +1,5 @@
import crypto from "crypto";
import { t } from "i18next";
import Router from "koa-router";
import { escapeRegExp } from "lodash";
import { IntegrationService } from "@shared/types";
@@ -17,6 +18,8 @@ import {
} from "@server/models";
import SearchHelper from "@server/models/helpers/SearchHelper";
import { presentSlackAttachment } from "@server/presenters";
import { APIContext } from "@server/types";
import { opts } from "@server/utils/i18n";
import * as Slack from "@server/utils/slack";
import { assertPresent } from "@server/validation";
@@ -41,10 +44,16 @@ function verifySlackToken(token: string) {
}
// triggered by a user posting a getoutline.com link in Slack
router.post("hooks.unfurl", async (ctx) => {
router.post("hooks.unfurl", async (ctx: APIContext) => {
const { challenge, token, event } = ctx.request.body;
// See URL verification handshake documentation on this page:
// https://api.slack.com/apis/connections/events-api
if (challenge) {
return (ctx.body = ctx.request.body.challenge);
ctx.body = {
challenge,
};
return;
}
assertPresent(token, "token is required");
@@ -104,7 +113,7 @@ router.post("hooks.unfurl", async (ctx) => {
});
// triggered by interactions with actions, dialogs, message buttons in Slack
router.post("hooks.interactive", async (ctx) => {
router.post("hooks.interactive", async (ctx: APIContext) => {
const { payload } = ctx.request.body;
assertPresent(payload, "payload is required");
@@ -142,28 +151,13 @@ router.post("hooks.interactive", async (ctx) => {
});
// triggered by the /outline command in Slack
router.post("hooks.slack", async (ctx) => {
router.post("hooks.slack", async (ctx: APIContext) => {
const { token, team_id, user_id, text = "" } = ctx.request.body;
assertPresent(token, "token is required");
assertPresent(team_id, "team_id is required");
assertPresent(user_id, "user_id is required");
verifySlackToken(token);
// Handle "help" command or no input
if (text.trim() === "help" || !text.trim()) {
ctx.body = {
response_type: "ephemeral",
text: "How to use /outline",
attachments: [
{
text:
"To search your knowledge base use `/outline keyword`. \nYou’ve already learned how to get help with `/outline help`.",
},
],
};
return;
}
let user, team;
// attempt to find the corresponding team for this request based on the team_id
team = await Team.findOne({
@@ -224,13 +218,39 @@ router.post("hooks.slack", async (ctx) => {
}
}
// Handle "help" command or no input
if (text.trim() === "help" || !text.trim()) {
ctx.body = {
response_type: "ephemeral",
text: "How to use /outline",
attachments: [
{
text: t(
"To search your knowledgebase use {{ command }}. \nYou’ve already learned how to get help with {{ command2 }}.",
{
command: `/outline keyword`,
command2: `/outline help`,
...opts(user),
}
),
},
],
};
return;
}
// This should be super rare, how does someone end up being able to make a valid
// request from Slack that connects to no teams in Outline.
if (!team) {
ctx.body = {
response_type: "ephemeral",
text:
"Sorry, we couldn’t find an integration for your team. Head to your Outline settings to set one up.",
text: t(
`Sorry, we couldn’t find an integration for your team. Head to your {{ appName }} settings to set one up.`,
{
...opts(user),
appName: env.APP_NAME,
}
),
};
return;
}
@@ -292,7 +312,13 @@ router.post("hooks.slack", async (ctx) => {
query: text,
results: totalCount,
});
const haventSignedIn = `(It looks like you haven’t signed in to Outline yet, so results may be limited)`;
const haventSignedIn = t(
`It looks like you haven’t signed in to {{ appName }} yet, so results may be limited`,
{
...opts(user),
appName: env.APP_NAME,
}
);
// Map search results to the format expected by the Slack API
if (results.length) {
@@ -312,7 +338,7 @@ router.post("hooks.slack", async (ctx) => {
? [
{
name: "post",
text: "Post to Channel",
text: t("Post to Channel", opts(user)),
type: "button",
value: result.document.id,
},
@@ -324,15 +350,24 @@ router.post("hooks.slack", async (ctx) => {
ctx.body = {
text: user
? `This is what we found for "${text}"…`
: `This is what we found for "${text}" ${haventSignedIn}…`,
? t(`This is what we found for "{{ term }}"`, {
...opts(user),
term: text,
})
: t(`This is what we found for "{{ term }}"`, {
term: text,
}) + ` (${haventSignedIn})…`,
attachments,
};
} else {
ctx.body = {
text: user
? `No results for "${text}"`
: `No results for "${text}" ${haventSignedIn}`,
? t(`No results for "{{ term }}"`, {
...opts(user),
term: text,
})
: t(`No results for "{{ term }}"`, { term: text }) +
` (${haventSignedIn})…`,
};
}
});
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff. Show more