Merge branch 'main' into feat/empty-trash

This commit is contained in:
CuriousCorrelation committed 2022-08-13 18:58:44 +05:30
commit 75d1329c2e
167 files changed
+3091 -2248

No files matched your search

+14 -1
View File
@@ -70,6 +70,15 @@ jobs:
- run:
name: test
command: yarn test:app
test-shared:
<<: *defaults
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: test
command: yarn test:shared
test-server:
<<: *defaults
steps:
@@ -81,7 +90,7 @@ jobs:
command: ./node_modules/.bin/sequelize db:migrate --url $DATABASE_URL_TEST
- run:
name: test
command: yarn test:server
command: yarn test:server --forceExit
bundle-size:
<<: *defaults
steps:
@@ -140,6 +149,9 @@ workflows:
- test-server:
requires:
- build
- test-shared:
requires:
- build
- test-app:
requires:
- build
@@ -149,6 +161,7 @@ workflows:
- bundle-size:
requires:
- test-app
- test-shared
- test-server
build-docker:
+9
View File
@@ -1,5 +1,7 @@
# –––––––––––––––– REQUIRED ––––––––––––––––
NODE_ENV=production
# Generate a hex-encoded 32-byte random key. You should use `openssl rand -hex 32`
# in your terminal to generate a random value.
SECRET_KEY=generate_a_new_key
@@ -168,3 +170,10 @@ SMTP_SECURE=true
# The default interface language. See translate.getoutline.com for a list of
# available language codes and their rough percentage translated.
DEFAULT_LANGUAGE=en_US
# Optionally enable rate limiter at application web server
RATE_LIMITER_ENABLED=true
# Configure default throttling paramaters for rate limiter
RATE_LIMITER_REQUESTS=5000
RATE_LIMITER_DURATION_WINDOW=60
+1
View File
@@ -25,6 +25,7 @@
"rules": {
"eqeqeq": 2,
"curly": 2,
"object-shorthand": "error",
"no-mixed-operators": "off",
"no-useless-escape": "off",
"es/no-regexp-lookbehind-assertions": "error",
+85
View File
@@ -0,0 +1,85 @@
{
"projects": [
{
"displayName": "server",
"verbose": false,
"roots": [
"<rootDir>/server"
],
"moduleNameMapper": {
"^@server/(.*)$": "<rootDir>/server/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1"
},
"setupFiles": [
"<rootDir>/__mocks__/console.js",
"<rootDir>/server/test/setup.ts"
],
"testEnvironment": "node",
"runner": "@getoutline/jest-runner-serial"
},
{
"displayName": "app",
"verbose": false,
"roots": [
"<rootDir>/app"
],
"moduleNameMapper": {
"^~/(.*)$": "<rootDir>/app/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1",
"^.*[.](gif|ttf|eot|svg)$": "<rootDir>/__test__/fileMock.js",
"^uuid$": "<rootDir>/node_modules/uuid/dist/index.js"
},
"modulePaths": [
"<rootDir>/app"
],
"setupFiles": [
"<rootDir>/__mocks__/window.js"
],
"setupFilesAfterEnv": [
"<rootDir>/app/test/setup.ts"
],
"testEnvironment": "jsdom",
"testEnvironmentOptions": {
"url": "http://localhost"
}
},
{
"displayName": "shared-node",
"verbose": false,
"roots": [
"<rootDir>/shared"
],
"moduleNameMapper": {
"^@server/(.*)$": "<rootDir>/server/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1"
},
"setupFiles": [
"<rootDir>/__mocks__/console.js"
],
"setupFilesAfterEnv": [
"<rootDir>/shared/test/setup.ts"
],
"testEnvironment": "node"
},
{
"displayName": "shared-jsdom",
"verbose": false,
"roots": [
"<rootDir>/shared"
],
"moduleNameMapper": {
"^~/(.*)$": "<rootDir>/app/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1",
"^.*[.](gif|ttf|eot|svg)$": "<rootDir>/__test__/fileMock.js",
"^uuid$": "<rootDir>/node_modules/uuid/dist/index.js"
},
"setupFiles": [
"<rootDir>/__mocks__/window.js"
],
"testEnvironment": "jsdom",
"testEnvironmentOptions": {
"url": "http://localhost"
}
}
]
}
-17
View File
@@ -1,17 +0,0 @@
export default class Queue {
name;
constructor(name) {
this.name = name;
}
process = (fn) => {
console.log(`Registered function ${this.name}`);
this.processFn = fn;
};
add = (data) => {
console.log(`Running ${this.name}`);
return this.processFn({ data });
};
}
-1
View File
@@ -1,2 +1 @@
// Mock for node-uuid
global.console.warn = () => {};
-27
View File
@@ -1,27 +0,0 @@
{
"testURL": "http://localhost",
"verbose": false,
"rootDir": "..",
"roots": [
"<rootDir>/app",
"<rootDir>/shared"
],
"moduleNameMapper": {
"^~/(.*)$": "<rootDir>/app/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1",
"^.*[.](gif|ttf|eot|svg)$": "<rootDir>/__test__/fileMock.js"
},
"moduleDirectories": [
"node_modules"
],
"modulePaths": [
"<rootDir>/app"
],
"setupFiles": [
"<rootDir>/__mocks__/window.js"
],
"setupFilesAfterEnv": [
"./app/test/setup.ts"
],
"testEnvironment": "jsdom"
}
+139 -2
View File
@@ -11,9 +11,16 @@ import {
ImportIcon,
PinIcon,
SearchIcon,
MoveIcon,
TrashIcon,
CrossIcon,
ArchiveIcon,
} from "outline-icons";
import * as React from "react";
import { getEventFiles } from "@shared/utils/files";
import DocumentDelete from "~/scenes/DocumentDelete";
import DocumentMove from "~/scenes/DocumentMove";
import DocumentPermanentDelete from "~/scenes/DocumentPermanentDelete";
import DocumentTemplatizeDialog from "~/components/DocumentTemplatizeDialog";
import { createAction } from "~/actions";
import { DocumentSection } from "~/actions/sections";
@@ -296,10 +303,11 @@ export const createTemplate = createAction({
return false;
}
const document = stores.documents.get(activeDocumentId);
return (
return !!(
!!activeCollectionId &&
stores.policies.abilities(activeCollectionId).update &&
!document?.isTemplate
!document?.isTemplate &&
!document?.isDeleted
);
},
perform: ({ activeDocumentId, stores, t, event }) => {
@@ -328,15 +336,144 @@ export const searchDocumentsForQuery = (searchQuery: string) =>
visible: ({ location }) => location.pathname !== searchPath(),
});
export const moveDocument = createAction({
name: ({ t }) => t("Move"),
section: DocumentSection,
icon: <MoveIcon />,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).move;
},
perform: ({ activeDocumentId, stores, t }) => {
if (activeDocumentId) {
const document = stores.documents.get(activeDocumentId);
if (!document) {
return;
}
stores.dialogs.openModal({
title: t("Move {{ documentName }}", {
documentName: document.noun,
}),
content: (
<DocumentMove
document={document}
onRequestClose={stores.dialogs.closeAllModals}
/>
),
});
}
},
});
export const archiveDocument = createAction({
name: ({ t }) => t("Archive"),
section: DocumentSection,
icon: <ArchiveIcon />,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).archive;
},
perform: async ({ activeDocumentId, stores, t }) => {
if (activeDocumentId) {
const document = stores.documents.get(activeDocumentId);
if (!document) {
return;
}
await document.archive();
stores.toasts.showToast(t("Document archived"), {
type: "success",
});
}
},
});
export const deleteDocument = createAction({
name: ({ t }) => t("Delete"),
section: DocumentSection,
icon: <TrashIcon />,
dangerous: true,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).delete;
},
perform: ({ activeDocumentId, stores, t }) => {
if (activeDocumentId) {
const document = stores.documents.get(activeDocumentId);
if (!document) {
return;
}
stores.dialogs.openModal({
title: t("Delete {{ documentName }}", {
documentName: document.noun,
}),
isCentered: true,
content: (
<DocumentDelete
document={document}
onSubmit={stores.dialogs.closeAllModals}
/>
),
});
}
},
});
export const permanentlyDeleteDocument = createAction({
name: ({ t }) => t("Permanently delete"),
section: DocumentSection,
icon: <CrossIcon />,
dangerous: true,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).permanentDelete;
},
perform: ({ activeDocumentId, stores, t }) => {
if (activeDocumentId) {
const document = stores.documents.get(activeDocumentId);
if (!document) {
return;
}
stores.dialogs.openModal({
title: t("Permanently delete {{ documentName }}", {
documentName: document.noun,
}),
isCentered: true,
content: (
<DocumentPermanentDelete
document={document}
onSubmit={stores.dialogs.closeAllModals}
/>
),
});
}
},
});
export const rootDocumentActions = [
openDocument,
archiveDocument,
createDocument,
createTemplate,
deleteDocument,
importDocument,
downloadDocument,
starDocument,
unstarDocument,
duplicateDocument,
moveDocument,
permanentlyDeleteDocument,
printDocument,
pinDocumentToCollection,
pinDocumentToHome,
+40
View File
@@ -0,0 +1,40 @@
import * as React from "react";
import styled from "styled-components";
import { createAction } from "~/actions";
import { loadSessionsFromCookie } from "~/hooks/useSessions";
export const changeTeam = createAction({
name: ({ t }) => t("Switch team"),
placeholder: ({ t }) => t("Select a team"),
keywords: "change workspace organization",
section: "Account",
visible: ({ currentTeamId }) => {
const sessions = loadSessionsFromCookie();
const otherSessions = sessions.filter(
(session) => session.teamId !== currentTeamId
);
return otherSessions.length > 0;
},
children: ({ currentTeamId }) => {
const sessions = loadSessionsFromCookie();
const otherSessions = sessions.filter(
(session) => session.teamId !== currentTeamId
);
return otherSessions.map((session) => ({
id: session.url,
name: session.name,
section: "Account",
icon: <Logo alt={session.name} src={session.logoUrl} />,
perform: () => (window.location.href = session.url),
}));
},
});
const Logo = styled("img")`
border-radius: 2px;
width: 24px;
height: 24px;
`;
export const rootTeamActions = [changeTeam];
+1
View File
@@ -56,6 +56,7 @@ export function actionToMenuItem(
title,
icon,
visible,
dangerous: action.dangerous,
onClick: () => action.perform && action.perform(context),
selected: action.selected ? action.selected(context) : undefined,
};
+2
View File
@@ -3,6 +3,7 @@ import { rootDeveloperActions } from "./definitions/developer";
import { rootDocumentActions } from "./definitions/documents";
import { rootNavigationActions } from "./definitions/navigation";
import { rootSettingsActions } from "./definitions/settings";
import { rootTeamActions } from "./definitions/teams";
import { rootUserActions } from "./definitions/users";
export default [
@@ -12,4 +13,5 @@ export default [
...rootNavigationActions,
...rootSettingsActions,
...rootDeveloperActions,
...rootTeamActions,
];
+1 -1
View File
@@ -3,7 +3,7 @@ import { deburr, sortBy } from "lodash";
import { DOMParser as ProsemirrorDOMParser } from "prosemirror-model";
import { TextSelection } from "prosemirror-state";
import * as React from "react";
import mergeRefs from "react-merge-refs";
import { mergeRefs } from "react-merge-refs";
import { Optional } from "utility-types";
import insertFiles from "@shared/editor/commands/insertFiles";
import embeds from "@shared/editor/embeds";
+3 -13
View File
@@ -40,6 +40,7 @@ import { useTranslation } from "react-i18next";
import { useMenuState, MenuButton, MenuItem } from "reakit/Menu";
import styled, { useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { colorPalette } from "@shared/utils/collections";
import ContextMenu from "~/components/ContextMenu";
import Flex from "~/components/Flex";
import { LabelText } from "~/components/Input";
@@ -200,18 +201,7 @@ export const icons = {
keywords: "warning alert error",
},
};
const colors = [
"#4E5C6E",
"#0366d6",
"#9E5CF7",
"#FF825C",
"#FF5C80",
"#FFBE0B",
"#42DED1",
"#00D084",
"#FF4DFA",
"#2F362F",
];
type Props = {
onOpen?: () => void;
onClose?: () => void;
@@ -272,7 +262,7 @@ function IconPicker({ onOpen, onClose, icon, color, onChange }: Props) {
<ColorPicker
color={color}
onChange={(color) => onChange(color.hex, icon)}
colors={colors}
colors={colorPalette}
triangle="hide"
styles={{
default: {
+3 -3
View File
@@ -11,7 +11,7 @@ import { setTextSelection } from "prosemirror-utils";
import { EditorView } from "prosemirror-view";
import * as React from "react";
import styled from "styled-components";
import { isInternalUrl, sanitizeHref } from "@shared/utils/urls";
import { isInternalUrl, sanitizeUrl } from "@shared/utils/urls";
import Flex from "~/components/Flex";
import { Dictionary } from "~/hooks/useDictionary";
import { ToastOptions } from "~/types";
@@ -70,7 +70,7 @@ class LinkEditor extends React.Component<Props, State> {
};
get href(): string {
return sanitizeHref(this.props.mark?.attrs.href) ?? "";
return sanitizeUrl(this.props.mark?.attrs.href) ?? "";
}
get suggestedLinkTitle(): string {
@@ -113,7 +113,7 @@ class LinkEditor extends React.Component<Props, State> {
this.discardInputValue = true;
const { from, to } = this.props;
href = sanitizeHref(href) ?? "";
href = sanitizeUrl(href) ?? "";
this.props.onSelectLink({ href, title, from, to });
};
+1 -1
View File
@@ -430,7 +430,7 @@ export class Editor extends React.PureComponent<
state: this.createState(this.props.value),
editable: () => !this.props.readOnly,
nodeViews: this.nodeViews,
dispatchTransaction: function (transaction) {
dispatchTransaction(transaction) {
// callback is bound to have the view instance as its this binding
const { state, transactions } = this.state.applyTransaction(
transaction
+1 -1
View File
@@ -8,7 +8,7 @@ type Session = {
teamId: string;
};
function loadSessionsFromCookie(): Session[] {
export function loadSessionsFromCookie(): Session[] {
const sessions = JSON.parse(getCookie("sessions") || "{}");
return Object.keys(sessions).map((teamId) => ({
teamId,
+23 -192
View File
@@ -1,20 +1,11 @@
import { observer } from "mobx-react";
import {
EditIcon,
StarredIcon,
UnstarredIcon,
DuplicateIcon,
ArchiveIcon,
TrashIcon,
MoveIcon,
HistoryIcon,
UnpublishIcon,
PrintIcon,
ImportIcon,
NewDocumentIcon,
DownloadIcon,
RestoreIcon,
CrossIcon,
} from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
@@ -25,19 +16,27 @@ import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { getEventFiles } from "@shared/utils/files";
import Document from "~/models/Document";
import DocumentDelete from "~/scenes/DocumentDelete";
import DocumentMove from "~/scenes/DocumentMove";
import DocumentPermanentDelete from "~/scenes/DocumentPermanentDelete";
import CollectionIcon from "~/components/CollectionIcon";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Separator from "~/components/ContextMenu/Separator";
import Template from "~/components/ContextMenu/Template";
import Flex from "~/components/Flex";
import Modal from "~/components/Modal";
import Switch from "~/components/Switch";
import { actionToMenuItem } from "~/actions";
import { pinDocument, createTemplate } from "~/actions/definitions/documents";
import {
pinDocument,
createTemplate,
moveDocument,
deleteDocument,
permanentlyDeleteDocument,
downloadDocument,
importDocument,
starDocument,
unstarDocument,
duplicateDocument,
archiveDocument,
} from "~/actions/definitions/documents";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useMobile from "~/hooks/useMobile";
@@ -94,39 +93,8 @@ function DocumentMenu({
});
const { t } = useTranslation();
const isMobile = useMobile();
const [renderModals, setRenderModals] = React.useState(false);
const [showDeleteModal, setShowDeleteModal] = React.useState(false);
const [
showPermanentDeleteModal,
setShowPermanentDeleteModal,
] = React.useState(false);
const [showMoveModal, setShowMoveModal] = React.useState(false);
const file = React.useRef<HTMLInputElement>(null);
const handleOpen = React.useCallback(() => {
setRenderModals(true);
if (onOpen) {
onOpen();
}
}, [onOpen]);
const handleDuplicate = React.useCallback(async () => {
const duped = await document.duplicate();
// when duplicating, go straight to the duplicated document content
history.push(duped.url);
showToast(t("Document duplicated"), {
type: "success",
});
}, [t, history, showToast, document]);
const handleArchive = React.useCallback(async () => {
await document.archive();
showToast(t("Document archived"), {
type: "success",
});
}, [showToast, t, document]);
const handleRestore = React.useCallback(
async (
ev: React.SyntheticEvent,
@@ -154,24 +122,6 @@ function DocumentMenu({
window.print();
}, [menu]);
const handleStar = React.useCallback(
(ev: React.SyntheticEvent) => {
ev.preventDefault();
ev.stopPropagation();
document.star();
},
[document]
);
const handleUnstar = React.useCallback(
(ev: React.SyntheticEvent) => {
ev.preventDefault();
ev.stopPropagation();
document.unstar();
},
[document]
);
const collection = collections.get(document.collectionId);
const can = usePolicy(document.id);
const canViewHistory = can.read && !can.restore;
@@ -205,19 +155,6 @@ function DocumentMenu({
ev.stopPropagation();
}, []);
const handleImportDocument = React.useCallback(
(ev: React.SyntheticEvent) => {
ev.preventDefault();
ev.stopPropagation();
// simulate a click on the file upload input element
if (file.current) {
file.current.click();
}
},
[file]
);
const handleFilePicked = React.useCallback(
async (ev: React.ChangeEvent<HTMLInputElement>) => {
const files = getEventFiles(ev);
@@ -280,7 +217,7 @@ function DocumentMenu({
<ContextMenu
{...menu}
aria-label={t("Document options")}
onOpen={handleOpen}
onOpen={onOpen}
onClose={onClose}
>
<Template
@@ -313,21 +250,8 @@ function DocumentMenu({
...restoreItems,
],
},
{
type: "button",
title: t("Unstar"),
onClick: handleUnstar,
visible: document.isStarred && !!can.unstar,
icon: <UnstarredIcon />,
},
{
type: "button",
title: t("Star"),
onClick: handleStar,
visible: !document.isStarred && !!can.star,
icon: <StarredIcon />,
},
// Pin document
actionToMenuItem(unstarDocument, context),
actionToMenuItem(starDocument, context),
actionToMenuItem(pinDocument, context),
{
type: "separator",
@@ -348,22 +272,9 @@ function DocumentMenu({
visible: !!can.createChildDocument,
icon: <NewDocumentIcon />,
},
{
type: "button",
title: t("Import document"),
visible: can.createChildDocument,
onClick: handleImportDocument,
icon: <ImportIcon />,
},
// Templatize document
actionToMenuItem(importDocument, context),
actionToMenuItem(createTemplate, context),
{
type: "button",
title: t("Duplicate"),
onClick: handleDuplicate,
visible: !!can.update,
icon: <DuplicateIcon />,
},
actionToMenuItem(duplicateDocument, context),
{
type: "button",
title: t("Unpublish"),
@@ -371,36 +282,10 @@ function DocumentMenu({
visible: !!can.unpublish,
icon: <UnpublishIcon />,
},
{
type: "button",
title: t("Archive"),
onClick: handleArchive,
visible: !!can.archive,
icon: <ArchiveIcon />,
},
{
type: "button",
title: `${t("Move")}…`,
onClick: () => setShowMoveModal(true),
visible: !!can.move,
icon: <MoveIcon />,
},
{
type: "button",
title: `${t("Delete")}…`,
dangerous: true,
onClick: () => setShowDeleteModal(true),
visible: !!can.delete,
icon: <TrashIcon />,
},
{
type: "button",
title: `${t("Permanently delete")}…`,
dangerous: true,
onClick: () => setShowPermanentDeleteModal(true),
visible: can.permanentDelete,
icon: <CrossIcon />,
},
actionToMenuItem(archiveDocument, context),
actionToMenuItem(moveDocument, context),
actionToMenuItem(deleteDocument, context),
actionToMenuItem(permanentlyDeleteDocument, context),
{
type: "separator",
},
@@ -413,13 +298,7 @@ function DocumentMenu({
visible: canViewHistory,
icon: <HistoryIcon />,
},
{
type: "button",
title: t("Download"),
onClick: document.download,
visible: !!can.download,
icon: <DownloadIcon />,
},
actionToMenuItem(downloadDocument, context),
{
type: "button",
title: t("Print"),
@@ -464,54 +343,6 @@ function DocumentMenu({
</>
)}
</ContextMenu>
{renderModals && (
<>
{can.move && (
<Modal
title={t("Move {{ documentName }}", {
documentName: document.noun,
})}
onRequestClose={() => setShowMoveModal(false)}
isOpen={showMoveModal}
>
<DocumentMove
document={document}
onRequestClose={() => setShowMoveModal(false)}
/>
</Modal>
)}
{can.delete && (
<Modal
title={t("Delete {{ documentName }}", {
documentName: document.noun,
})}
onRequestClose={() => setShowDeleteModal(false)}
isOpen={showDeleteModal}
isCentered
>
<DocumentDelete
document={document}
onSubmit={() => setShowDeleteModal(false)}
/>
</Modal>
)}
{can.permanentDelete && (
<Modal
title={t("Permanently delete {{ documentName }}", {
documentName: document.noun,
})}
onRequestClose={() => setShowPermanentDeleteModal(false)}
isOpen={showPermanentDeleteModal}
isCentered
>
<DocumentPermanentDelete
document={document}
onSubmit={() => setShowPermanentDeleteModal(false)}
/>
</Modal>
)}
</>
)}
</>
);
}
+5 -33
View File
@@ -2,11 +2,10 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { MenuButton, useMenuState } from "reakit/Menu";
import styled from "styled-components";
import ContextMenu from "~/components/ContextMenu";
import Template from "~/components/ContextMenu/Template";
import { createAction } from "~/actions";
import { navigateToSettings, logout } from "~/actions/definitions/navigation";
import { changeTeam } from "~/actions/definitions/teams";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import usePrevious from "~/hooks/usePrevious";
import useSessions from "~/hooks/useSessions";
@@ -32,32 +31,11 @@ const OrganizationMenu: React.FC = ({ children }) => {
}
}, [menu, theme, previousTheme]);
// NOTE: it's useful to memoize on the team id and session because the action
// menu is not cached at all.
const actions = React.useMemo(() => {
const otherSessions = sessions.filter(
(session) => session.teamId !== team.id && session.url !== team.url
);
return [
navigateToSettings,
separator(),
...(otherSessions.length
? [
createAction({
name: t("Switch team"),
section: "account",
children: otherSessions.map((session) => ({
id: session.url,
name: session.name,
section: "account",
icon: <Logo alt={session.name} src={session.logoUrl} />,
perform: () => (window.location.href = session.url),
})),
}),
]
: []),
logout,
];
}, [team.id, team.url, sessions, t]);
return [navigateToSettings, separator(), changeTeam, logout];
}, [team.id, sessions]);
return (
<>
@@ -69,10 +47,4 @@ const OrganizationMenu: React.FC = ({ children }) => {
);
};
const Logo = styled("img")`
border-radius: 2px;
width: 24px;
height: 24px;
`;
export default observer(OrganizationMenu);
+3 -1
View File
@@ -25,7 +25,9 @@ function CollectionExport({ collection, onSubmit }: Props) {
setIsLoading(false);
showToast(
t("Export started, you will receive an email when it’s complete.")
t(
"Export started. If you have notifications enabled, you will receive an email when it's complete."
)
);
onSubmit();
},
+3 -1
View File
@@ -3,6 +3,8 @@ import { observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
import { withTranslation, Trans, WithTranslation } from "react-i18next";
import { randomElement } from "@shared/random";
import { colorPalette } from "@shared/utils/collections";
import { CollectionValidation } from "@shared/validations";
import RootStore from "~/stores/RootStore";
import Collection from "~/models/Collection";
@@ -30,7 +32,7 @@ class CollectionNew extends React.Component<Props> {
icon = "";
@observable
color = "#4E5C6E";
color = randomElement(colorPalette);
@observable
sharing = true;
+1 -1
View File
@@ -25,7 +25,7 @@ function GroupEdit({ group, onSubmit }: Props) {
try {
await group.save({
name: name,
name,
});
onSubmit();
} catch (err) {
+1 -1
View File
@@ -29,7 +29,7 @@ function GroupNew({ onSubmit }: Props) {
const group = new Group(
{
name: name,
name,
},
groups
);
+4 -5
View File
@@ -5,6 +5,7 @@ import { useTranslation, Trans } from "react-i18next";
import { Link } from "react-router-dom";
import styled from "styled-components";
import { Role } from "@shared/types";
import { UserValidation } from "@shared/validations";
import Button from "~/components/Button";
import CopyToClipboard from "~/components/CopyToClipboard";
import Flex from "~/components/Flex";
@@ -19,8 +20,6 @@ import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
const MAX_INVITES = 20;
type Props = {
onSubmit: () => void;
};
@@ -97,10 +96,10 @@ function Invite({ onSubmit }: Props) {
}, []);
const handleAdd = React.useCallback(() => {
if (invites.length >= MAX_INVITES) {
if (invites.length >= UserValidation.maxInvitesPerRequest) {
showToast(
t("Sorry, you can only send {{MAX_INVITES}} invites at a time", {
MAX_INVITES,
MAX_INVITES: UserValidation.maxInvitesPerRequest,
}),
{
type: "warning",
@@ -241,7 +240,7 @@ function Invite({ onSubmit }: Props) {
))}
<Flex justify="space-between">
{invites.length <= MAX_INVITES ? (
{invites.length <= UserValidation.maxInvitesPerRequest ? (
<Button type="button" onClick={handleAdd} neutral>
<Trans>Add another</Trans>…
</Button>
+9 -5
View File
@@ -89,11 +89,15 @@ function AuthenticationProvider(props: Props) {
);
}
// If we're on a custom domain then the auth must point to the root
// app.getoutline.com for authentication so that the state cookie can be set
// and read.
const isCustomDomain = parseDomain(window.location.origin).custom;
const href = `${isCustomDomain ? env.URL : ""}${authUrl}`;
// 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 = needsRedirect
? `${env.URL}${authUrl}?host=${encodeURI(host)}`
: authUrl;
return (
<Wrapper>
+1 -1
View File
@@ -56,7 +56,7 @@ function Export() {
<Heading>{t("Export")}</Heading>
<Text type="secondary">
<Trans
defaults="A full export might take some time, consider exporting a single document or collection. The exported data is a zip of your documents in Markdown format. You may leave this page once the export has started – we will email a link to <em>{{ userEmail }}</em> when it’s complete."
defaults="A full export might take some time, consider exporting a single document or collection. The exported data is a zip of your documents in Markdown format. You may leave this page once the export has started – if you have notifications enabled, we will email a link to <em>{{ userEmail }}</em> when it’s complete."
values={{
userEmail: user.email,
}}
+7
View File
@@ -51,6 +51,13 @@ function Notifications() {
"Receive a notification when someone you invited creates an account"
),
},
{
event: "emails.export_completed",
title: t("Export completed"),
description: t(
"Receive a notification when an export you requested has been completed"
),
},
{
visible: isCloudHosted,
event: "emails.onboarding",
+1 -1
View File
@@ -532,7 +532,7 @@ export default class DocumentsStore extends BaseStore<Document> {
id: documentId,
collectionId,
parentDocumentId,
index: index,
index,
});
invariant(res?.data, "Data not available");
res.data.documents.forEach(this.add);
+1
View File
@@ -88,6 +88,7 @@ export type Action = {
section: ((context: ActionContext) => string) | string;
shortcut?: string[];
keywords?: string;
dangerous?: boolean;
iconInContextMenu?: boolean;
icon?: React.ReactElement | React.FC;
placeholder?: ((context: ActionContext) => string) | string;
+1 -1
View File
@@ -20,7 +20,7 @@ let supportsPassive = false;
try {
const opts = Object.defineProperty({}, "passive", {
get: function () {
get() {
supportsPassive = true;
},
});
+16 -13
View File
@@ -24,10 +24,10 @@
"db:rollback": "sequelize db:migrate:undo",
"db:reset": "sequelize db:drop && sequelize db:create && sequelize db:migrate",
"upgrade": "git fetch && git pull && yarn install && yarn heroku-postbuild",
"test": "yarn test:app && yarn test:server",
"test:app": "jest --config=app/.jestconfig.json --runInBand --forceExit",
"test:server": "jest --config=server/.jestconfig.json --runInBand --forceExit",
"test:watch": "jest --config=server/.jestconfig.json --runInBand --forceExit --watchAll"
"test": "jest --config=.jestconfig.json --forceExit",
"test:app": "jest --config=.jestconfig.json --selectProjects app",
"test:shared": "jest --config=.jestconfig.json --selectProjects shared-node shared-jsdom",
"test:server": "jest --config=.jestconfig.json --selectProjects server"
},
"funding": {
"type": "GitHub Sponsors ❤",
@@ -71,7 +71,7 @@
"@tommoor/remove-markdown": "^0.3.2",
"@types/mermaid": "^8.2.9",
"autotrack": "^2.4.1",
"aws-sdk": "^2.1044.0",
"aws-sdk": "^2.1189.0",
"babel-plugin-lodash": "^3.3.4",
"babel-plugin-styled-components": "^1.11.1",
"babel-plugin-transform-class-properties": "^6.24.1",
@@ -80,7 +80,7 @@
"cancan": "3.1.0",
"chalk": "^4.1.0",
"class-validator": "^0.13.2",
"compressorjs": "^1.0.7",
"compressorjs": "^1.1.1",
"copy-to-clipboard": "^3.3.1",
"core-js": "^3.10.2",
"crypto-js": "^4.1.1",
@@ -125,7 +125,7 @@
"koa-static": "^4.0.1",
"lodash": "^4.17.21",
"mammoth": "^1.4.19",
"markdown-it": "^12.3.2",
"markdown-it": "^13.0.1",
"markdown-it-container": "^3.0.0",
"markdown-it-emoji": "^2.0.0",
"mermaid": "9.1.3",
@@ -136,7 +136,7 @@
"node-fetch": "2.6.7",
"nodemailer": "^6.6.1",
"outline-icons": "^1.43.1",
"oy-vey": "^0.10.0",
"oy-vey": "^0.11.2",
"passport": "^0.6.0",
"passport-google-oauth2": "^0.2.0",
"passport-oauth2": "^1.6.1",
@@ -150,7 +150,7 @@
"prosemirror-history": "^1.2.0",
"prosemirror-inputrules": "^1.1.3",
"prosemirror-keymap": "^1.1.5",
"prosemirror-markdown": "^1.5.2",
"prosemirror-markdown": "^1.9.3",
"prosemirror-model": "1.16.1",
"prosemirror-schema-list": "1.1.4",
"prosemirror-state": "1.3.4",
@@ -161,6 +161,7 @@
"query-string": "^7.0.1",
"quoted-printable": "^1.0.1",
"randomstring": "1.1.5",
"rate-limiter-flexible": "^2.3.7",
"raw-loader": "^0.5.1",
"react": "^17.0.2",
"react-avatar-editor": "^11.1.0",
@@ -173,7 +174,7 @@
"react-hook-form": "^7.31.2",
"react-i18next": "^11.16.6",
"react-medium-image-zoom": "^3.1.3",
"react-merge-refs": "^1.1.0",
"react-merge-refs": "^2.0.1",
"react-portal": "^4.2.0",
"react-router-dom": "^5.2.0",
"react-table": "^7.7.0",
@@ -219,6 +220,7 @@
"devDependencies": {
"@babel/cli": "^7.10.5",
"@babel/preset-typescript": "^7.16.0",
"@getoutline/jest-runner-serial": "^2.0.0",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.4",
"@relative-ci/agent": "^3.0.0",
"@types/body-scroll-lock": "^3.1.0",
@@ -234,7 +236,7 @@
"@types/google.analytics": "^0.0.42",
"@types/invariant": "^2.2.35",
"@types/ioredis": "^4.28.1",
"@types/jest": "^27.0.2",
"@types/jest": "^28.1.6",
"@types/jsonwebtoken": "^8.5.8",
"@types/koa": "^2.13.4",
"@types/koa-compress": "^4.0.3",
@@ -291,7 +293,7 @@
"@typescript-eslint/eslint-plugin": "^5.3.1",
"@typescript-eslint/parser": "^5.3.1",
"babel-eslint": "^10.1.0",
"babel-jest": "^27.4.5",
"babel-jest": "^28.1.3",
"babel-loader": "^8.1.0",
"babel-plugin-transform-inline-environment-variables": "^0.4.3",
"babel-plugin-transform-typescript-metadata": "^0.3.2",
@@ -313,7 +315,8 @@
"html-webpack-plugin": "4.5.1",
"husky": "^7.0.4",
"i18next-parser": "^6.3.0",
"jest-cli": "^27.4.5",
"jest-cli": "^28.1.3",
"jest-environment-jsdom": "^28.1.3",
"jest-fetch-mock": "^3.0.3",
"koa-webpack-dev-middleware": "^1.4.5",
"koa-webpack-hot-middleware": "^1.0.3",
Binary file not shown.

After

Width:  |  Height:  |  Size: 533 B

-17
View File
@@ -1,17 +0,0 @@
{
"verbose": false,
"rootDir": "..",
"roots": [
"<rootDir>/server",
"<rootDir>/shared"
],
"moduleNameMapper": {
"^@server/(.*)$": "<rootDir>/server/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1"
},
"setupFiles": [
"<rootDir>/__mocks__/console.js",
"./server/test/setup.ts"
],
"testEnvironment": "node"
}
+33
View File
@@ -0,0 +1,33 @@
import { RateLimiterRedis } from "rate-limiter-flexible";
import env from "@server/env";
import Redis from "@server/redis";
import { RateLimiterConfig } from "@server/types";
export default class RateLimiter {
constructor() {
throw Error(`Cannot instantiate class!`);
}
static readonly RATE_LIMITER_REDIS_KEY_PREFIX = "rl";
static readonly rateLimiterMap = new Map<string, RateLimiterRedis>();
static readonly defaultRateLimiter = new RateLimiterRedis({
storeClient: Redis.defaultClient,
points: env.RATE_LIMITER_REQUESTS,
duration: env.RATE_LIMITER_DURATION_WINDOW,
keyPrefix: this.RATE_LIMITER_REDIS_KEY_PREFIX,
});
static getRateLimiter(path: string): RateLimiterRedis {
return this.rateLimiterMap.get(path) || this.defaultRateLimiter;
}
static setRateLimiter(path: string, config: RateLimiterConfig): void {
const rateLimiter = new RateLimiterRedis(config);
this.rateLimiterMap.set(path, rateLimiter);
}
static hasRateLimiter(path: string): boolean {
return this.rateLimiterMap.has(path);
}
}
+16
View File
@@ -0,0 +1,16 @@
export default class MockRateLimiter {
static getRateLimiter() {
return {
points: 100,
consume: jest.fn(),
};
}
static setRateLimiter() {
//
}
static hasRateLimiter() {
return false;
}
}
+41
View File
@@ -0,0 +1,41 @@
export default class Queue {
done() {
//
}
on() {
//
}
count() {
return 0;
}
getDelayedCount() {
return 0;
}
add = function (data: any) {
const job = this.createJob(data);
if (!this.handler) {
return;
}
this.handler(job, this.done);
};
process = function (handler: any) {
if (this.handler) {
throw Error("Cannot define a handler more than once per Queue instance");
}
this.handler = handler;
};
createJob = function (data: any) {
return {
data,
};
};
}
+6 -4
View File
@@ -4,12 +4,14 @@ import { TeamDomain } from "@server/models";
import Collection from "@server/models/Collection";
import UserAuthentication from "@server/models/UserAuthentication";
import { buildUser, buildTeam } from "@server/test/factories";
import { flushdb, seed } from "@server/test/support";
import { getTestDatabase, seed } from "@server/test/support";
import accountProvisioner from "./accountProvisioner";
beforeEach(() => {
return flushdb();
});
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("accountProvisioner", () => {
const ip = "127.0.0.1";
+7 -2
View File
@@ -2,11 +2,16 @@ import path from "path";
import fs from "fs-extra";
import Attachment from "@server/models/Attachment";
import { buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import documentImporter from "./documentImporter";
jest.mock("../utils/s3");
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("documentImporter", () => {
const ip = "127.0.0.1";
+6 -2
View File
@@ -5,10 +5,14 @@ import {
buildCollection,
buildUser,
} from "@server/test/factories";
import { flushdb, seed } from "@server/test/support";
import { getTestDatabase, seed } from "@server/test/support";
import documentMover from "./documentMover";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("documentMover", () => {
const ip = "127.0.0.1";
@@ -1,10 +1,14 @@
import { subDays } from "date-fns";
import { Attachment, Document } from "@server/models";
import { buildAttachment, buildDocument } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import documentPermanentDeleter from "./documentPermanentDeleter";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("documentPermanentDeleter", () => {
it("should destroy documents", async () => {
+6 -2
View File
@@ -1,10 +1,14 @@
import { sequelize } from "@server/database/sequelize";
import { Event } from "@server/models";
import { buildDocument, buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import documentUpdater from "./documentUpdater";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("documentUpdater", () => {
const ip = "127.0.0.1";
+6 -2
View File
@@ -1,9 +1,13 @@
import { FileOperation } from "@server/models";
import { buildAdmin, buildFileOperation } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import fileOperationDeleter from "./fileOperationDeleter";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("fileOperationDeleter", () => {
const ip = "127.0.0.1";
+7 -2
View File
@@ -1,9 +1,14 @@
import { Event } from "@server/models";
import { buildDocument, buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import pinCreator from "./pinCreator";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("pinCreator", () => {
const ip = "127.0.0.1";
+7 -2
View File
@@ -1,9 +1,14 @@
import { Pin, Event } from "@server/models";
import { buildDocument, buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import pinDestroyer from "./pinDestroyer";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("pinCreator", () => {
const ip = "127.0.0.1";
+6 -2
View File
@@ -1,9 +1,13 @@
import { Event } from "@server/models";
import { buildDocument, buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import revisionCreator from "./revisionCreator";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("revisionCreator", () => {
const ip = "127.0.0.1";
+7 -2
View File
@@ -1,10 +1,15 @@
import { sequelize } from "@server/database/sequelize";
import { Star, Event } from "@server/models";
import { buildDocument, buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import starCreator from "./starCreator";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("starCreator", () => {
const ip = "127.0.0.1";
+6 -2
View File
@@ -1,9 +1,13 @@
import { Star, Event } from "@server/models";
import { buildDocument, buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import starDestroyer from "./starDestroyer";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("starDestroyer", () => {
const ip = "127.0.0.1";
+6 -2
View File
@@ -1,9 +1,13 @@
import { Star, Event } from "@server/models";
import { buildDocument, buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import starUpdater from "./starUpdater";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("starUpdater", () => {
const ip = "127.0.0.1";
+6 -2
View File
@@ -6,10 +6,14 @@ import {
buildTeam,
buildDocument,
} from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import teamPermanentDeleter from "./teamPermanentDeleter";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("teamPermanentDeleter", () => {
it("should destroy related data", async () => {
+6 -2
View File
@@ -1,10 +1,14 @@
import env from "@server/env";
import TeamDomain from "@server/models/TeamDomain";
import { buildTeam, buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import teamProvisioner from "./teamProvisioner";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("teamProvisioner", () => {
const ip = "127.0.0.1";
+1 -1
View File
@@ -119,7 +119,7 @@ const teamUpdater = async ({ params, user, team, ip }: TeamUpdaterProps) => {
actorId: user.id,
teamId: user.teamId,
data,
ip: ip,
ip,
},
{
transaction,
+6 -2
View File
@@ -1,8 +1,12 @@
import { buildUser, buildAdmin } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import userDestroyer from "./userDestroyer";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("userDestroyer", () => {
const ip = "127.0.0.1";
+6 -2
View File
@@ -1,8 +1,12 @@
import { buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import userInviter from "./userInviter";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("userInviter", () => {
const ip = "127.0.0.1";
+6 -2
View File
@@ -1,10 +1,14 @@
import { v4 as uuidv4 } from "uuid";
import { TeamDomain } from "@server/models";
import { buildUser, buildTeam, buildInvite } from "@server/test/factories";
import { flushdb, seed } from "@server/test/support";
import { getTestDatabase, seed } from "@server/test/support";
import userProvisioner from "./userProvisioner";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("userProvisioner", () => {
const ip = "127.0.0.1";
+6 -2
View File
@@ -1,9 +1,13 @@
import GroupUser from "@server/models/GroupUser";
import { buildGroup, buildAdmin, buildUser } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import userSuspender from "./userSuspender";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("userSuspender", () => {
const ip = "127.0.0.1";
+2 -3
View File
@@ -1,6 +1,5 @@
import nodemailer, { Transporter } from "nodemailer";
import Oy from "oy-vey";
import * as React from "react";
import env from "@server/env";
import Logger from "@server/logging/Logger";
import { APM } from "@server/logging/tracing";
@@ -15,7 +14,7 @@ type SendMailOptions = {
subject: string;
previewText?: string;
text: string;
component: React.ReactNode;
component: JSX.Element;
headCSS?: string;
};
@@ -66,7 +65,7 @@ export class Mailer {
const html = Oy.renderTemplate(data.component, {
title: data.subject,
headCSS: [baseStyles, data.headCSS].join(" "),
previewText: data.previewText,
previewText: data.previewText ?? "",
});
try {
@@ -1,4 +1,5 @@
import * as React from "react";
import { NotificationSetting } from "@server/models";
import BaseEmail from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
@@ -10,13 +11,27 @@ import Heading from "./components/Heading";
type Props = {
to: string;
userId: string;
teamUrl: string;
teamId: string;
};
/**
* Email sent to a user when their data export has failed for some reason.
*/
export default class ExportFailureEmail extends BaseEmail<Props> {
protected async beforeSend({ userId, teamId }: Props) {
const notificationSetting = await NotificationSetting.findOne({
where: {
userId,
teamId,
event: "emails.export_completed",
},
});
return notificationSetting !== null;
}
protected subject() {
return "Your requested export";
}
@@ -1,4 +1,5 @@
import * as React from "react";
import { NotificationSetting } from "@server/models";
import BaseEmail from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
@@ -10,8 +11,10 @@ import Heading from "./components/Heading";
type Props = {
to: string;
userId: string;
id: string;
teamUrl: string;
teamId: string;
};
/**
@@ -19,6 +22,18 @@ type Props = {
* for download in the settings section.
*/
export default class ExportSuccessEmail extends BaseEmail<Props> {
protected async beforeSend({ userId, teamId }: Props) {
const notificationSetting = await NotificationSetting.findOne({
where: {
userId,
teamId,
event: "emails.export_completed",
},
});
return notificationSetting !== null;
}
protected subject() {
return "Your requested export";
}
@@ -3,7 +3,7 @@ import * as React from "react";
import theme from "@shared/styles/theme";
const EmailLayout: React.FC = ({ children }) => (
<Table width="550" padding="40">
<Table width="550">
<TBody>
<TR>
<TD align="left">{children}</TD>
+31
View File
@@ -495,6 +495,37 @@ export class Environment {
process.env.SOURCE_COMMIT || process.env.SOURCE_VERSION
);
/**
* A boolean switch to toggle the rate limiter
* at application web server.
*/
@IsOptional()
@IsBoolean()
public RATE_LIMITER_ENABLED = this.toBoolean(
process.env.RATE_LIMITER_ENABLED ?? "false"
);
/**
* Set max allowed requests in a given duration for
* default rate limiter to trigger throttling.
*/
@IsOptional()
@IsNumber()
@CannotUseWithout("RATE_LIMITER_ENABLED")
public RATE_LIMITER_REQUESTS =
this.toOptionalNumber(process.env.RATE_LIMITER_REQUESTS) ?? 5000;
/**
* Set fixed duration window(in secs) for
* default rate limiter, elapsing which the request
* quota is reset(the bucket is refilled with tokens).
*/
@IsOptional()
@IsNumber()
@CannotUseWithout("RATE_LIMITER_ENABLED")
public RATE_LIMITER_DURATION_WINDOW =
this.toOptionalNumber(process.env.RATE_LIMITER_DURATION_WINDOW) ?? 60;
private toOptionalString(value: string | undefined) {
return value ? value : undefined;
}
-10
View File
@@ -161,16 +161,6 @@ export function GmailAccountCreationError(
});
}
export function AuthRedirectError(
message = "Redirect to the correct domain after authentication",
redirectUrl: string
) {
return httpErrors(400, message, {
id: "auth_redirect",
redirectUrl,
});
}
export function OIDCMalformedUserInfoError(
message = "User profile information malformed"
) {
+1
View File
@@ -122,6 +122,7 @@ async function start(id: number, disconnect: () => void) {
}`
);
});
server.listen(normalizedPortFlag || env.PORT || "3000");
process.once("SIGTERM", shutdown);
process.once("SIGINT", shutdown);
+6 -2
View File
@@ -1,10 +1,14 @@
import randomstring from "randomstring";
import ApiKey from "@server/models/ApiKey";
import { buildUser, buildTeam } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import auth from "./authentication";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("Authentication middleware", () => {
describe("with JWT", () => {
+21 -4
View File
@@ -3,6 +3,7 @@ import { Context } from "koa";
import env from "@server/env";
import Logger from "@server/logging/Logger";
import { signIn } from "@server/utils/authentication";
import { parseState } from "@server/utils/passport";
import { AccountProvisionerResult } from "../commands/accountProvisioner";
export default function createMiddleware(providerName: string) {
@@ -18,12 +19,28 @@ export default function createMiddleware(providerName: string) {
if (err.id) {
const notice = err.id.replace(/_/g, "-");
const hasQueryString = err.redirectUrl?.includes("?");
const redirectUrl = err.redirectUrl ?? "/";
const hasQueryString = redirectUrl?.includes("?");
// Every authentication action is routed through the apex domain.
// But when there is an error, we want to redirect the user on the
// same domain or subdomain that they originated from (found in state).
// get original host
const state = ctx.cookies.get("state");
const host = state ? parseState(state).host : ctx.hostname;
// form a URL object with the err.redirectUrl and replace the host
const reqProtocol = ctx.protocol;
const requestHost = ctx.get("host");
const url = new URL(
`${reqProtocol}://${requestHost}${redirectUrl}`
);
url.host = host;
return ctx.redirect(
`${err.redirectUrl || "/"}${
hasQueryString ? "&" : "?"
}notice=${notice}`
`${url.toString()}${hasQueryString ? "&" : "?"}notice=${notice}`
);
}
+60
View File
@@ -0,0 +1,60 @@
import { Context, Next } from "koa";
import { defaults } from "lodash";
import RateLimiter from "@server/RateLimiter";
import env from "@server/env";
import { RateLimitExceededError } from "@server/errors";
import Redis from "@server/redis";
import { RateLimiterConfig } from "@server/types";
export function rateLimiter() {
return async function rateLimiterMiddleware(ctx: Context, next: Next) {
if (!env.RATE_LIMITER_ENABLED) {
return next();
}
const key = RateLimiter.hasRateLimiter(ctx.path)
? `${ctx.path}:${ctx.ip}`
: `${ctx.ip}`;
const limiter = RateLimiter.getRateLimiter(ctx.path);
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)}`
);
throw RateLimitExceededError();
}
return next();
};
}
export function registerRateLimiter(config: RateLimiterConfig) {
return async function registerRateLimiterMiddleware(
ctx: Context,
next: Next
) {
if (!env.RATE_LIMITER_ENABLED) {
return next();
}
if (!RateLimiter.hasRateLimiter(ctx.path)) {
RateLimiter.setRateLimiter(
ctx.path,
defaults(config, {
duration: env.RATE_LIMITER_DURATION_WINDOW,
keyPrefix: RateLimiter.RATE_LIMITER_REDIS_KEY_PREFIX,
storeClient: Redis.defaultClient,
})
);
}
return next();
};
}
+9 -3
View File
@@ -7,13 +7,19 @@ import {
buildTeam,
buildDocument,
} from "@server/test/factories";
import { flushdb, seed } from "@server/test/support";
import { getTestDatabase, seed } from "@server/test/support";
import slugify from "@server/utils/slugify";
import Collection from "./Collection";
import Document from "./Document";
beforeEach(() => flushdb());
beforeEach(jest.resetAllMocks);
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
describe("#url", () => {
test("should return correct url for the collection", () => {
+9 -3
View File
@@ -6,11 +6,17 @@ import {
buildUser,
buildShare,
} from "@server/test/factories";
import { flushdb, seed } from "@server/test/support";
import { getTestDatabase, seed } from "@server/test/support";
import slugify from "@server/utils/slugify";
beforeEach(() => flushdb());
beforeEach(jest.resetAllMocks);
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
describe("#getSummary", () => {
test("should strip markdown", async () => {
+9 -3
View File
@@ -1,10 +1,16 @@
import { buildUser, buildGroup, buildCollection } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import CollectionGroup from "./CollectionGroup";
import GroupUser from "./GroupUser";
beforeEach(() => flushdb());
beforeEach(jest.resetAllMocks);
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
describe("afterDestroy hook", () => {
test("should destroy associated group and collection join relations", async () => {
+1 -1
View File
@@ -31,7 +31,7 @@ import NotContainsUrl from "./validators/NotContainsUrl";
tableName: "groups",
modelName: "group",
validate: {
isUniqueNameInTeam: async function () {
async isUniqueNameInTeam() {
const foundItem = await Group.findOne({
where: {
teamId: this.teamId,
+1
View File
@@ -41,6 +41,7 @@ class NotificationSetting extends Model {
"emails.invite_accepted",
"emails.onboarding",
"emails.features",
"emails.export_completed",
],
])
@Column(DataType.STRING)
+9 -3
View File
@@ -1,9 +1,15 @@
import { buildDocument } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import Revision from "./Revision";
beforeEach(() => flushdb());
beforeEach(jest.resetAllMocks);
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
describe("#findLatest", () => {
test("should return latest revision", async () => {
+9 -2
View File
@@ -1,7 +1,14 @@
import { buildTeam, buildCollection } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
describe("collectionIds", () => {
it("should return non-private collection ids", async () => {
+9 -2
View File
@@ -1,8 +1,15 @@
import { buildAdmin, buildTeam } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import TeamDomain from "./TeamDomain";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
describe("team domain model", () => {
describe("create", () => {
+7 -2
View File
@@ -1,16 +1,21 @@
import { buildUser, buildTeam, buildCollection } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import CollectionUser from "./CollectionUser";
import UserAuthentication from "./UserAuthentication";
beforeEach(() => flushdb());
const db = getTestDatabase();
beforeAll(() => {
jest.useFakeTimers().setSystemTime(new Date("2018-01-02T00:00:00.000Z"));
});
afterAll(() => {
jest.useRealTimers();
db.disconnect();
});
beforeEach(db.flush);
describe("user model", () => {
describe("destroy", () => {
it("should delete user authentications", async () => {
+14 -1
View File
@@ -497,7 +497,9 @@ class User extends ParanoidModel {
};
// By default when a user signs up we subscribe them to email notifications
// when documents they created are edited by other team members and onboarding
// when documents they created are edited by other team members and onboarding.
// If the user is an admin, they will also be subscribed to export_completed
// notifications.
@AfterCreate
static subscribeToNotifications = async (
model: User,
@@ -537,6 +539,17 @@ class User extends ParanoidModel {
transaction: options.transaction,
}),
]);
if (model.isAdmin) {
await NotificationSetting.findOrCreate({
where: {
userId: model.id,
teamId: model.teamId,
event: "emails.export_completed",
},
transaction: options.transaction,
});
}
};
static getCounts = async function (teamId: string) {
+26
View File
@@ -7,8 +7,12 @@ import {
NotEmpty,
DataType,
IsUrl,
BeforeCreate,
DefaultScope,
} from "sequelize-typescript";
import { SaveOptions } from "sequelize/types";
import { WebhookSubscriptionValidation } from "@shared/validations";
import { ValidationError } from "@server/errors";
import { Event } from "@server/types";
import Team from "./Team";
import User from "./User";
@@ -16,6 +20,14 @@ import ParanoidModel from "./base/ParanoidModel";
import Fix from "./decorators/Fix";
import Length from "./validators/Length";
@DefaultScope(() => ({
include: [
{
association: "team",
required: true,
},
],
}))
@Table({
tableName: "webhook_subscriptions",
modelName: "webhook_subscription",
@@ -55,6 +67,20 @@ class WebhookSubscription extends ParanoidModel {
@Column
teamId: string;
// hooks
@BeforeCreate
static async checkLimit(model: WebhookSubscription) {
const count = await this.count({
where: { teamId: model.teamId },
});
if (count >= WebhookSubscriptionValidation.maxSubscriptions) {
throw ValidationError(
`You have reached the limit of ${WebhookSubscriptionValidation.maxSubscriptions} webhooks`
);
}
}
// methods
/**
+6 -2
View File
@@ -1,9 +1,13 @@
import { CollectionUser, Collection } from "@server/models";
import { buildUser, buildTeam, buildCollection } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import { serialize } from "./index";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("read_write permission", () => {
it("should allow read write permissions for team member", async () => {
+6 -2
View File
@@ -4,10 +4,14 @@ import {
buildDocument,
buildCollection,
} from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import { serialize } from "./index";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("read_write collection", () => {
it("should allow read write permissions for team member", async () => {
+6 -2
View File
@@ -1,8 +1,12 @@
import { buildUser, buildTeam } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import { serialize } from "./index";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
it("should serialize policy", async () => {
const user = await buildUser();
+7 -2
View File
@@ -1,8 +1,13 @@
import { buildUser, buildTeam, buildAdmin } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import { serialize } from "./index";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
it("should allow reading only", async () => {
const team = await buildTeam();
const user = await buildUser({
+1 -1
View File
@@ -33,6 +33,6 @@ export default function present({
webhookSubscriptionId: delivery.webhookSubscriptionId,
createdAt: delivery.createdAt,
event: event.name,
payload: payload,
payload,
};
}
@@ -1,12 +1,18 @@
import { Backlink } from "@server/models";
import { buildDocument } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import BacklinksProcessor from "./BacklinksProcessor";
const ip = "127.0.0.1";
beforeEach(() => flushdb());
beforeEach(jest.resetAllMocks);
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
describe("documents.publish", () => {
test("should create new backlink records", async () => {
@@ -161,7 +167,7 @@ describe("documents.update", () => {
ip,
});
document.text = `First link is gone
[this is a another link](${yetAnotherDocument.url})`;
await document.save();
@@ -5,14 +5,20 @@ import {
buildCollection,
buildUser,
} from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import NotificationsProcessor from "./NotificationsProcessor";
jest.mock("@server/emails/templates/DocumentNotificationEmail");
const ip = "127.0.0.1";
beforeEach(() => flushdb());
beforeEach(jest.resetAllMocks);
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
describe("documents.publish", () => {
test("should not send a notification to author", async () => {
@@ -1,12 +1,18 @@
import { Revision } from "@server/models";
import { buildDocument } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import RevisionsProcessor from "./RevisionsProcessor";
const ip = "127.0.0.1";
beforeEach(() => flushdb());
beforeEach(jest.resetAllMocks);
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
describe("documents.update.debounced", () => {
test("should create a revision", async () => {
@@ -1,18 +1,21 @@
import { buildUser, buildWebhookSubscription } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import { UserEvent } from "@server/types";
import DeliverWebhookTask from "../tasks/DeliverWebhookTask";
import WebhookProcessor from "./WebhookProcessor";
jest.mock("@server/queues/tasks/DeliverWebhookTask");
const ip = "127.0.0.1";
beforeEach(() => flushdb());
beforeEach(() => {
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
});
const ip = "127.0.0.1";
describe("WebhookProcessor", () => {
test("it schedules a delivery for the event", async () => {
const subscription = await buildWebhookSubscription({
@@ -1,10 +1,14 @@
import { subDays } from "date-fns";
import { Document } from "@server/models";
import { buildDocument } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import CleanupDeletedDocumentsTask from "./CleanupDeletedDocumentsTask";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("CleanupDeletedDocumentsTask", () => {
it("should not destroy documents not deleted", async () => {
@@ -6,10 +6,14 @@ import {
buildWebhookSubscription,
buildViewer,
} from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import CleanupDemotedUserTask from "./CleanupDemotedUserTask";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("CleanupDemotedUserTask", () => {
it("should delete api keys for suspended user", async () => {
@@ -5,10 +5,14 @@ import {
FileOperationType,
} from "@server/models/FileOperation";
import { buildFileOperation } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import CleanupExpiredFileOperationsTask from "./CleanupExpiredFileOperationsTask";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("CleanupExpiredFileOperationsTask", () => {
it("should expire exports older than 15 days ago", async () => {
@@ -1,10 +1,14 @@
import { subDays } from "date-fns";
import { WebhookDelivery } from "@server/models";
import { buildWebhookDelivery } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import CleanupWebhookDeliveriesTask from "./CleanupWebhookDeliveriesTask";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
const deliveryExists = async (delivery: WebhookDelivery) => {
const results = await WebhookDelivery.findOne({ where: { id: delivery.id } });
@@ -6,12 +6,16 @@ import {
buildWebhookDelivery,
buildWebhookSubscription,
} from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import { UserEvent } from "@server/types";
import DeliverWebhookTask from "./DeliverWebhookTask";
beforeEach(() => flushdb());
beforeEach(() => {
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(async () => {
await db.flush();
jest.resetAllMocks();
fetchMock.resetMocks();
fetchMock.doMock();
+12 -4
View File
@@ -79,10 +79,18 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
rejectOnEmpty: true,
});
Logger.info(
"task",
`DeliverWebhookTask: ${event.name} for ${subscription.name}`
);
if (!subscription.enabled) {
Logger.info("task", `WebhookSubscription was disabled before delivery`, {
event: event.name,
subscriptionId: subscription.id,
});
return;
}
Logger.info("task", `DeliverWebhookTask: ${event.name}`, {
event: event.name,
subscriptionId: subscription.id,
});
switch (event.name) {
case "api_keys.create":
@@ -72,8 +72,10 @@ export default class ExportMarkdownZipTask extends BaseTask<Props> {
await ExportSuccessEmail.schedule({
to: user.email,
userId: user.id,
id: fileOperation.id,
teamUrl: team.url,
teamId: team.id,
});
} catch (error) {
await this.updateFileOperation(fileOperation, {
@@ -82,7 +84,9 @@ export default class ExportMarkdownZipTask extends BaseTask<Props> {
});
await ExportFailureEmail.schedule({
to: user.email,
userId: user.id,
teamUrl: team.url,
teamId: team.id,
});
throw error;
}
@@ -2,10 +2,14 @@ import fs from "fs";
import path from "path";
import { FileOperation } from "@server/models";
import { buildFileOperation } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import ImportMarkdownZipTask from "./ImportMarkdownZipTask";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("ImportMarkdownZipTask", () => {
it("should import the documents, attachments", async () => {
+6 -2
View File
@@ -2,10 +2,14 @@ import fs from "fs";
import path from "path";
import { FileOperation } from "@server/models";
import { buildFileOperation } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import ImportNotionTask from "./ImportNotionTask";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("ImportNotionTask", () => {
it("should import successfully from a Markdown export", async () => {
@@ -1,10 +1,14 @@
import { subDays } from "date-fns";
import InviteReminderEmail from "@server/emails/templates/InviteReminderEmail";
import { buildInvite } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase } from "@server/test/support";
import InviteReminderTask from "./InviteReminderTask";
beforeEach(() => flushdb());
const db = getTestDatabase();
afterAll(db.disconnect);
beforeEach(db.flush);
describe("InviteReminderTask", () => {
it("should not destroy documents not deleted", async () => {
+7 -8
View File
@@ -1,6 +1,4 @@
import TestServer from "fetch-test-server";
import Attachment from "@server/models/Attachment";
import webService from "@server/services/web";
import {
buildUser,
buildAdmin,
@@ -8,15 +6,16 @@ import {
buildAttachment,
buildDocument,
} from "@server/test/factories";
import { flushdb } from "@server/test/support";
const app = webService();
const server = new TestServer(app.callback());
import { getTestDatabase, getTestServer } from "@server/test/support";
jest.mock("@server/utils/s3");
beforeEach(() => flushdb());
afterAll(() => server.close());
const db = getTestDatabase();
const server = getTestServer();
afterAll(server.disconnect);
beforeEach(db.flush);
describe("#attachments.create", () => {
it("should require authentication", async () => {
+7 -7
View File
@@ -1,14 +1,14 @@
import TestServer from "fetch-test-server";
import sharedEnv from "@shared/env";
import env from "@server/env";
import webService from "@server/services/web";
import { buildUser, buildTeam } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase, getTestServer } from "@server/test/support";
const app = webService();
const server = new TestServer(app.callback());
beforeEach(() => flushdb());
afterAll(() => server.close());
const db = getTestDatabase();
const server = getTestServer();
afterAll(server.disconnect);
beforeEach(db.flush);
describe("#auth.info", () => {
it("should return current authentication", async () => {
@@ -1,14 +1,13 @@
import TestServer from "fetch-test-server";
import { v4 as uuidv4 } from "uuid";
import webService from "@server/services/web";
import { buildUser, buildAdmin, buildTeam } from "@server/test/factories";
import { flushdb } from "@server/test/support";
import { getTestDatabase, getTestServer } from "@server/test/support";
const app = webService();
const server = new TestServer(app.callback());
const db = getTestDatabase();
const server = getTestServer();
beforeEach(() => flushdb());
afterAll(() => server.close());
afterAll(server.disconnect);
beforeEach(db.flush);
describe("#authenticationProviders.info", () => {
it("should return auth provider", async () => {
+9 -7
View File
@@ -1,6 +1,5 @@
import TestServer from "fetch-test-server";
import { colorPalette } from "@shared/utils/collections";
import { Document, CollectionUser, CollectionGroup } from "@server/models";
import webService from "@server/services/web";
import {
buildUser,
buildAdmin,
@@ -8,12 +7,14 @@ import {
buildCollection,
buildDocument,
} from "@server/test/factories";
import { flushdb, seed } from "@server/test/support";
import { seed, getTestDatabase, getTestServer } from "@server/test/support";
const app = webService();
const server = new TestServer(app.callback());
beforeEach(() => flushdb());
afterAll(() => server.close());
const db = getTestDatabase();
const server = getTestServer();
afterAll(server.disconnect);
beforeEach(db.flush);
describe("#collections.list", () => {
it("should require authentication", async () => {
@@ -1054,6 +1055,7 @@ describe("#collections.create", () => {
expect(body.data.name).toBe("Test");
expect(body.data.sort.field).toBe("index");
expect(body.data.sort.direction).toBe("asc");
expect(colorPalette.includes(body.data.color)).toBeTruthy();
expect(body.policies.length).toBe(1);
expect(body.policies[0].abilities.read).toBeTruthy();
});
+3 -1
View File
@@ -2,6 +2,8 @@ import fractionalIndex from "fractional-index";
import invariant from "invariant";
import Router from "koa-router";
import { Sequelize, Op, WhereOptions } from "sequelize";
import { randomElement } from "@shared/random";
import { colorPalette } from "@shared/utils/collections";
import collectionExporter from "@server/commands/collectionExporter";
import teamUpdater from "@server/commands/teamUpdater";
import { sequelize } from "@server/database/sequelize";
@@ -50,7 +52,7 @@ const router = new Router();
router.post("collections.create", auth(), async (ctx) => {
const {
name,
color,
color = randomElement(colorPalette),
description,
permission,
sharing,
+6 -7
View File
@@ -1,12 +1,11 @@
import TestServer from "fetch-test-server";
import webService from "@server/services/web";
import { flushdb } from "@server/test/support";
import { getTestDatabase, getTestServer } from "@server/test/support";
const app = webService();
const server = new TestServer(app.callback());
const db = getTestDatabase();
const server = getTestServer();
beforeEach(() => flushdb());
afterAll(() => server.close());
afterAll(server.disconnect);
beforeEach(db.flush);
describe("#cron.daily", () => {
it("should require authentication", async () => {
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff. Show more