diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx index d5d831fa0f..cbf69a373d 100644 --- a/app/components/Editor.tsx +++ b/app/components/Editor.tsx @@ -8,12 +8,10 @@ import { Optional } from "utility-types"; import insertFiles from "@shared/editor/commands/insertFiles"; import embeds from "@shared/editor/embeds"; import { Heading } from "@shared/editor/lib/getHeadings"; -import { - getDataTransferFiles, - supportedImageMimeTypes, -} from "@shared/utils/files"; +import { getDataTransferFiles } from "@shared/utils/files"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; import { isInternalUrl } from "@shared/utils/urls"; +import { AttachmentValidation } from "@shared/validations"; import Document from "~/models/Document"; import ClickablePadding from "~/components/ClickablePadding"; import ErrorBoundary from "~/components/ErrorBoundary"; @@ -212,7 +210,7 @@ function Editor(props: Props, ref: React.RefObject | null) { // Insert all files as attachments if any of the files are not images. const isAttachment = files.some( - (file) => !supportedImageMimeTypes.includes(file.type) + (file) => !AttachmentValidation.imageContentTypes.includes(file.type) ); insertFiles(view, event, pos, files, { diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 8a7aac0df3..c0519f293e 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -6,8 +6,8 @@ import { useDrag, useDrop } from "react-dnd"; import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; import styled from "styled-components"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import { sortNavigationNodes } from "@shared/utils/collections"; +import { DocumentValidation } from "@shared/validations"; import Collection from "~/models/Collection"; import Document from "~/models/Document"; import Fade from "~/components/Fade"; @@ -319,7 +319,7 @@ function InnerDocumentLink( onSubmit={handleTitleChange} onEditing={handleTitleEditing} canUpdate={canUpdate} - maxLength={MAX_TITLE_LENGTH} + maxLength={DocumentValidation.maxTitleLength} /> } isActive={(match, location: Location<{ starred?: boolean }>) => diff --git a/app/editor/components/CommandMenu.tsx b/app/editor/components/CommandMenu.tsx index f6554fc3da..cf172db1e7 100644 --- a/app/editor/components/CommandMenu.tsx +++ b/app/editor/components/CommandMenu.tsx @@ -11,7 +11,8 @@ import { CommandFactory } from "@shared/editor/lib/Extension"; import filterExcessSeparators from "@shared/editor/lib/filterExcessSeparators"; import { EmbedDescriptor, MenuItem } from "@shared/editor/types"; import { depths } from "@shared/styles"; -import { supportedImageMimeTypes, getEventFiles } from "@shared/utils/files"; +import { getEventFiles } from "@shared/utils/files"; +import { AttachmentValidation } from "@shared/validations"; import Scrollable from "~/components/Scrollable"; import { Dictionary } from "~/hooks/useDictionary"; import Input from "./Input"; @@ -35,7 +36,7 @@ export type Props = { onFileUploadStop?: () => void; onShowToast: (message: string) => void; onLinkToolbarOpen?: () => void; - onClose: () => void; + onClose: (insertNewLine?: boolean) => void; onClearSearch: () => void; embeds?: EmbedDescriptor[]; renderMenuItem: ( @@ -122,7 +123,7 @@ class CommandMenu extends React.Component, State> { if (item) { this.insertItem(item); } else { - this.props.onClose(); + this.props.onClose(true); } } @@ -181,7 +182,9 @@ class CommandMenu extends React.Component, State> { insertItem = (item: any) => { switch (item.name) { case "image": - return this.triggerFilePick(supportedImageMimeTypes.join(", ")); + return this.triggerFilePick( + AttachmentValidation.imageContentTypes.join(", ") + ); case "attachment": return this.triggerFilePick("*"); case "embed": diff --git a/app/editor/index.tsx b/app/editor/index.tsx index a17c6d8e1e..0de98128f5 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -554,7 +554,14 @@ export class Editor extends React.PureComponent< this.setState({ blockMenuOpen: true, blockMenuSearch: search }); }; - private handleCloseBlockMenu = () => { + private handleCloseBlockMenu = (insertNewLine?: boolean) => { + if (insertNewLine) { + const transaction = this.view.state.tr.split( + this.view.state.selection.to + ); + this.view.dispatch(transaction); + this.view.focus(); + } if (!this.state.blockMenuOpen) { return; } diff --git a/app/menus/CollectionMenu.tsx b/app/menus/CollectionMenu.tsx index 0fbc5fc9fc..8591c033e1 100644 --- a/app/menus/CollectionMenu.tsx +++ b/app/menus/CollectionMenu.tsx @@ -266,7 +266,7 @@ function CollectionMenu({ { type: "button", title: `${t("Export")}…`, - visible: !!(collection && canUserInTeam.export), + visible: !!(collection && canUserInTeam.createExport), onClick: handleExport, icon: , }, @@ -296,7 +296,7 @@ function CollectionMenu({ alphabeticalSort, handleEdit, handlePermissions, - canUserInTeam.export, + canUserInTeam.createExport, handleExport, handleDelete, handleChangeSort, diff --git a/app/models/User.ts b/app/models/User.ts index d920aec554..c1753d722f 100644 --- a/app/models/User.ts +++ b/app/models/User.ts @@ -1,5 +1,5 @@ import { computed, observable } from "mobx"; -import { Role } from "@shared/types"; +import type { Role } from "@shared/types"; import ParanoidModel from "./ParanoidModel"; import Field from "./decorators/Field"; diff --git a/app/scenes/CollectionEdit.tsx b/app/scenes/CollectionEdit.tsx index 3ddbdadcb6..31a235ec72 100644 --- a/app/scenes/CollectionEdit.tsx +++ b/app/scenes/CollectionEdit.tsx @@ -3,7 +3,7 @@ import { observer } from "mobx-react"; import { useState } from "react"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; +import { CollectionValidation } from "@shared/validations"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; import IconPicker from "~/components/IconPicker"; @@ -94,7 +94,7 @@ const CollectionEdit = ({ collectionId, onSubmit }: Props) => { type="text" label={t("Name")} onChange={handleNameChange} - maxLength={MAX_TITLE_LENGTH} + maxLength={CollectionValidation.maxNameLength} value={name} required autoFocus diff --git a/app/scenes/CollectionNew.tsx b/app/scenes/CollectionNew.tsx index ce20cbbf10..5ea45a0957 100644 --- a/app/scenes/CollectionNew.tsx +++ b/app/scenes/CollectionNew.tsx @@ -3,7 +3,7 @@ import { observable } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; import { withTranslation, Trans, WithTranslation } from "react-i18next"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; +import { CollectionValidation } from "@shared/validations"; import RootStore from "~/stores/RootStore"; import Collection from "~/models/Collection"; import Button from "~/components/Button"; @@ -128,7 +128,7 @@ class CollectionNew extends React.Component { type="text" label={t("Name")} onChange={this.handleNameChange} - maxLength={MAX_TITLE_LENGTH} + maxLength={CollectionValidation.maxNameLength} value={this.name} required autoFocus diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index 50f2d65736..3924274bd3 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -45,7 +45,12 @@ function DataLoader({ match, children }: Props) { const { team } = auth; const [error, setError] = React.useState(null); const { revisionId, shareId, documentSlug } = match.params; - const document = documents.getByUrl(match.params.documentSlug); + + // Allows loading by /doc/slug- or /doc/ + const document = + documents.getByUrl(match.params.documentSlug) ?? + documents.get(match.params.documentSlug); + const revision = revisionId ? revisions.get(revisionId) : undefined; const sharedTree = document ? documents.getSharedTree(document.id) diff --git a/app/scenes/Document/components/EditableTitle.tsx b/app/scenes/Document/components/EditableTitle.tsx index d1cffeafcb..e708293648 100644 --- a/app/scenes/Document/components/EditableTitle.tsx +++ b/app/scenes/Document/components/EditableTitle.tsx @@ -2,13 +2,13 @@ import { observer } from "mobx-react"; import * as React from "react"; import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import { light } from "@shared/styles/theme"; import { getCurrentDateAsString, getCurrentDateTimeAsString, getCurrentTimeAsString, } from "@shared/utils/date"; +import { DocumentValidation } from "@shared/validations"; import Document from "~/models/Document"; import ContentEditable, { RefHandle } from "~/components/ContentEditable"; import Star, { AnimatedStar } from "~/components/Star"; @@ -132,7 +132,7 @@ const EditableTitle = React.forwardRef( $emojiWidth={emojiWidth} $isStarred={document.isStarred} autoFocus={!value} - maxLength={MAX_TITLE_LENGTH} + maxLength={DocumentValidation.maxTitleLength} readOnly={readOnly} dir="auto" ref={ref} diff --git a/app/scenes/DocumentDelete.tsx b/app/scenes/DocumentDelete.tsx index 774a4fa1d2..82537a6f5d 100644 --- a/app/scenes/DocumentDelete.tsx +++ b/app/scenes/DocumentDelete.tsx @@ -24,6 +24,9 @@ function DocumentDelete({ document, onSubmit }: Props) { const { showToast } = useToasts(); const canArchive = !document.isDraft && !document.isArchived; const collection = collections.get(document.collectionId); + const nestedDocumentsCount = collection + ? collection.getDocumentChildren(document.id).length + : 0; const handleSubmit = React.useCallback( async (ev: React.SyntheticEvent) => { ev.preventDefault(); @@ -94,9 +97,9 @@ function DocumentDelete({ document, onSubmit }: Props) { em: , }} /> - ) : ( + ) : nestedDocumentsCount < 1 ? ( , }} /> + ) : ( + , + }} + /> )} {canArchive && ( diff --git a/app/scenes/Settings/components/ImageUpload.tsx b/app/scenes/Settings/components/ImageUpload.tsx index 2b33ef4bb1..696149b327 100644 --- a/app/scenes/Settings/components/ImageUpload.tsx +++ b/app/scenes/Settings/components/ImageUpload.tsx @@ -5,6 +5,7 @@ import * as React from "react"; import AvatarEditor from "react-avatar-editor"; import Dropzone from "react-dropzone"; import styled from "styled-components"; +import { AttachmentValidation } from "@shared/validations"; import RootStore from "~/stores/RootStore"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; @@ -134,7 +135,7 @@ class ImageUpload extends React.Component { return ( {({ getRootProps, getInputProps }) => ( diff --git a/app/scenes/UserDelete.tsx b/app/scenes/UserDelete.tsx index 48186b1022..116b27b7e0 100644 --- a/app/scenes/UserDelete.tsx +++ b/app/scenes/UserDelete.tsx @@ -1,65 +1,120 @@ import { observer } from "mobx-react"; import * as React from "react"; +import { useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; +import { ReactHookWrappedInput as Input } from "~/components/Input"; import Modal from "~/components/Modal"; import Text from "~/components/Text"; +import env from "~/env"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; +type FormData = { + code: string; +}; + type Props = { onRequestClose: () => void; }; function UserDelete({ onRequestClose }: Props) { - const [isDeleting, setIsDeleting] = React.useState(false); + const [isWaitingCode, setWaitingCode] = React.useState(false); const { auth } = useStores(); const { showToast } = useToasts(); const { t } = useTranslation(); + const { register, handleSubmit: formHandleSubmit, formState } = useForm< + FormData + >(); - const handleSubmit = React.useCallback( + const handleRequestDelete = React.useCallback( async (ev: React.SyntheticEvent) => { ev.preventDefault(); - setIsDeleting(true); try { - await auth.deleteUser(); - auth.logout(); + await auth.requestDelete(); + setWaitingCode(true); } catch (error) { showToast(error.message, { type: "error", }); - } finally { - setIsDeleting(false); } }, [auth, showToast] ); + const handleSubmit = React.useCallback( + async (data: FormData) => { + try { + await auth.deleteUser(data); + auth.logout(); + } catch (error) { + showToast(error.message, { + type: "error", + }); + } + }, + [auth, showToast] + ); + + const inputProps = register("code", { + required: true, + }); + return ( -
- - - 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. - - - - , - }} - /> - - + + {isWaitingCode ? ( + <> + + + A confirmation code has been sent to your email address, + please enter the code below to permanantly destroy your + account. + + + + , + }} + /> + + + + ) : ( + <> + + + 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. + + + + )} + {env.EMAIL_ENABLED && !isWaitingCode ? ( + + ) : ( + + )}
diff --git a/app/stores/AuthStore.ts b/app/stores/AuthStore.ts index 0c4322f248..55d908a0e6 100644 --- a/app/stores/AuthStore.ts +++ b/app/stores/AuthStore.ts @@ -199,8 +199,13 @@ export default class AuthStore { }; @action - deleteUser = async () => { - await client.post(`/users.delete`); + requestDelete = () => { + return client.post(`/users.requestDelete`); + }; + + @action + deleteUser = async (data: { code: string }) => { + await client.post(`/users.delete`, data); runInAction("AuthStore#updateUser", () => { this.user = null; this.team = null; diff --git a/app/stores/DocumentsStore.ts b/app/stores/DocumentsStore.ts index 75bf6846ef..efd4c74b13 100644 --- a/app/stores/DocumentsStore.ts +++ b/app/stores/DocumentsStore.ts @@ -2,10 +2,10 @@ import path from "path"; import invariant from "invariant"; import { find, orderBy, filter, compact, omitBy } from "lodash"; import { observable, action, computed, runInAction } from "mobx"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import { DateFilter } from "@shared/types"; import { subtractDate } from "@shared/utils/date"; import naturalSort from "@shared/utils/naturalSort"; +import { DocumentValidation } from "@shared/validations"; import BaseStore from "~/stores/BaseStore"; import RootStore from "~/stores/RootStore"; import Document from "~/models/Document"; @@ -553,7 +553,7 @@ export default class DocumentsStore extends BaseStore { template: document.template, title: `${document.title.slice( 0, - MAX_TITLE_LENGTH - append.length + DocumentValidation.maxTitleLength - append.length )}${append}`, text: document.text, }); diff --git a/app/stores/UiStore.ts b/app/stores/UiStore.ts index 8186dd8034..1c7abc6769 100644 --- a/app/stores/UiStore.ts +++ b/app/stores/UiStore.ts @@ -1,7 +1,7 @@ import { action, autorun, computed, observable } from "mobx"; import { light as defaultTheme } from "@shared/styles/theme"; import Document from "~/models/Document"; -import { ConnectionStatus } from "~/scenes/Document/components/MultiplayerEditor"; +import type { ConnectionStatus } from "~/scenes/Document/components/MultiplayerEditor"; import Storage from "~/utils/Storage"; const UI_STORE = "UI_STORE"; diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 57d1704870..9ff4d5575d 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -4,7 +4,7 @@ The Outline team takes security bugs seriously. We appreciate your efforts to responsibly disclose your findings, and will make every effort to acknowledge your contributions. -If you discover a security vulnerability in outline, please disclose it via [our huntr page](https://huntr.dev/repos/${owner}/${repo}/). Bounty eligibility, CVE assignment, response times and past reports are all there. +If you discover a security vulnerability in outline, please disclose it via [our huntr page](https://huntr.dev/repos/outline/outline/). Bounty eligibility, CVE assignment, response times and past reports are all there. The Outline team will send a response indicating the next steps in handling your report. After the initial reply to your report you will be kept informed of the progress towards a fix and full announcement. diff --git a/package.json b/package.json index d35e2be66e..cb7d500ccf 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "db:create-migration": "sequelize migration:create", "db:migrate": "sequelize db:migrate", "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", @@ -108,7 +109,7 @@ "is-printable-key-event": "^1.0.0", "json-loader": "0.5.4", "jsonwebtoken": "^8.5.0", - "jszip": "^3.7.1", + "jszip": "^3.10.0", "kbar": "0.1.0-beta.28", "koa": "^2.13.4", "koa-body": "^4.2.0", @@ -178,7 +179,7 @@ "react-table": "^7.7.0", "react-virtualized-auto-sizer": "^1.0.5", "react-waypoint": "^10.1.0", - "react-window": "^1.8.6", + "react-window": "^1.8.7", "reakit": "^1.3.10", "reflect-metadata": "^0.1.13", "refractor": "^3.5.0", @@ -234,7 +235,7 @@ "@types/invariant": "^2.2.35", "@types/ioredis": "^4.28.1", "@types/jest": "^27.0.2", - "@types/jsonwebtoken": "^8.5.5", + "@types/jsonwebtoken": "^8.5.8", "@types/koa": "^2.13.4", "@types/koa-compress": "^4.0.3", "@types/koa-helmet": "^6.0.4", @@ -295,11 +296,11 @@ "babel-plugin-transform-inline-environment-variables": "^0.4.3", "babel-plugin-transform-typescript-metadata": "^0.3.2", "babel-plugin-tsconfig-paths-module-resolver": "^1.0.3", - "concurrently": "^6.2.1", + "concurrently": "^7.3.0", "enzyme": "^3.11.0", "enzyme-adapter-react-16": "^1.15.6", "eslint": "^7.6.0", - "eslint-config-prettier": "^8.3.0", + "eslint-config-prettier": "^8.5.0", "eslint-import-resolver-typescript": "^2.5.0", "eslint-plugin-es": "^4.1.0", "eslint-plugin-import": "^2.25.3", @@ -322,7 +323,7 @@ "react-refresh": "^0.9.0", "rimraf": "^2.5.4", "terser-webpack-plugin": "^4.1.0", - "typescript": "^4.4.4", + "typescript": "^4.7.4", "url-loader": "^0.6.2", "webpack": "4.44.1", "webpack-cli": "^3.3.12", @@ -339,5 +340,5 @@ "js-yaml": "^3.14.1", "jpeg-js": "0.4.4" }, - "version": "0.65.1" + "version": "0.65.2" } diff --git a/server/commands/accountProvisioner.test.ts b/server/commands/accountProvisioner.test.ts index 7a65280de3..33b96048bb 100644 --- a/server/commands/accountProvisioner.test.ts +++ b/server/commands/accountProvisioner.test.ts @@ -108,6 +108,44 @@ describe("accountProvisioner", () => { spy.mockRestore(); }); + it("should allow authentication by email matching", async () => { + const existingTeam = await buildTeam(); + const providers = await existingTeam.$get("authenticationProviders"); + const authenticationProvider = providers[0]; + const userWithoutAuth = await buildUser({ + email: "email@example.com", + teamId: existingTeam.id, + authentications: [], + }); + + const { user, isNewUser, isNewTeam } = await accountProvisioner({ + ip, + user: { + name: userWithoutAuth.name, + email: "email@example.com", + avatarUrl: userWithoutAuth.avatarUrl, + }, + team: { + name: existingTeam.name, + avatarUrl: existingTeam.avatarUrl, + subdomain: "example", + }, + authenticationProvider: { + name: authenticationProvider.name, + providerId: authenticationProvider.providerId, + }, + authentication: { + providerId: "anything", + accessToken: "123", + scopes: ["read"], + }, + }); + expect(user.id).toEqual(userWithoutAuth.id); + expect(isNewTeam).toEqual(false); + expect(isNewUser).toEqual(false); + expect(user.authentications.length).toEqual(0); + }); + it("should throw an error when authentication provider is disabled", async () => { const existingTeam = await buildTeam(); const providers = await existingTeam.$get("authenticationProviders"); diff --git a/server/commands/accountProvisioner.ts b/server/commands/accountProvisioner.ts index 27dabc5a6d..ff4d0d017e 100644 --- a/server/commands/accountProvisioner.ts +++ b/server/commands/accountProvisioner.ts @@ -8,34 +8,58 @@ import { AuthenticationProviderDisabledError, } from "@server/errors"; import { APM } from "@server/logging/tracing"; -import { Collection, Team, User } from "@server/models"; -import teamCreator from "./teamCreator"; -import userCreator from "./userCreator"; +import { AuthenticationProvider, Collection, Team, User } from "@server/models"; +import teamProvisioner from "./teamProvisioner"; +import userProvisioner from "./userProvisioner"; type Props = { + /** The IP address of the incoming request */ ip: string; + /** Details of the user logging in from SSO provider */ user: { + /** The displayed name of the user */ name: string; + /** The email address of the user */ email: string; + /** The public url of an image representing the user */ avatarUrl?: string | null; + /** The username of the user */ username?: string; }; + /** Details of the team the user is logging into */ team: { - id?: string; + /** + * The internal ID of the team that is being logged into based on the + * subdomain that the request came from, if any. + */ + teamId?: string; + /** The displayed name of the team */ name: string; + /** The domain name from the email of the user logging in */ domain?: string; + /** The preferred subdomain to provision for the team if not yet created */ subdomain: string; + /** The public url of an image representing the team */ avatarUrl?: string | null; }; + /** Details of the authentication provider being used */ authenticationProvider: { + /** The name of the authentication provider, eg "google" */ name: string; + /** External identifier of the authentication provider */ providerId: string; }; + /** Details of the authentication from SSO provider */ authentication: { + /** External identifier of the user in the authentication provider */ providerId: string; + /** The scopes granted by the access token */ scopes: string[]; + /** The token provided by the authentication provider */ accessToken?: string; + /** The refresh token provided by the authentication provider */ refreshToken?: string; + /** A number of seconds that the given access token expires in */ expiresIn?: number; }; }; @@ -55,15 +79,45 @@ async function accountProvisioner({ authentication: authenticationParams, }: Props): Promise { let result; + let emailMatchOnly; try { - result = await teamCreator({ + result = await teamProvisioner({ ...teamParams, authenticationProvider: authenticationProviderParams, ip, }); } catch (err) { - throw InvalidAuthenticationError(err.message); + // The account could not be provisioned for the provided teamId + // check to see if we can try authentication using email matching only + if (err.id === "invalid_authentication") { + const authenticationProvider = await AuthenticationProvider.findOne({ + where: { + name: authenticationProviderParams.name, // example: "google" + teamId: teamParams.teamId, + }, + include: [ + { + model: Team, + as: "team", + required: true, + }, + ], + }); + + if (authenticationProvider) { + emailMatchOnly = true; + result = { + authenticationProvider, + team: authenticationProvider.team, + isNewTeam: false, + }; + } + } + + if (!result) { + throw InvalidAuthenticationError(err.message); + } } invariant(result, "Team creator result must exist"); @@ -74,20 +128,21 @@ async function accountProvisioner({ } try { - const result = await userCreator({ + const result = await userProvisioner({ name: userParams.name, email: userParams.email, username: userParams.username, isAdmin: isNewTeam || undefined, avatarUrl: userParams.avatarUrl, teamId: team.id, + emailMatchOnly, ip, authentication: { + authenticationProviderId: authenticationProvider.id, ...authenticationParams, expiresAt: authenticationParams.expiresIn ? new Date(Date.now() + authenticationParams.expiresIn * 1000) : undefined, - authenticationProviderId: authenticationProvider.id, }, }); const { isNewUser, user } = result; diff --git a/server/commands/documentImporter.test.ts b/server/commands/documentImporter.test.ts index c4139bbad3..889c234e10 100644 --- a/server/commands/documentImporter.test.ts +++ b/server/commands/documentImporter.test.ts @@ -148,6 +148,21 @@ describe("documentImporter", () => { expect(response.title).toEqual("Heading 1"); }); + it("should handle only title", async () => { + const user = await buildUser(); + const fileName = "markdown.md"; + const content = `# Title`; + const response = await documentImporter({ + user, + mimeType: "text/plain", + fileName, + content, + ip, + }); + expect(response.text).toEqual(""); + expect(response.title).toEqual("Title"); + }); + it("should fallback to extension if mimetype unknown", async () => { const user = await buildUser(); const fileName = "markdown.md"; diff --git a/server/commands/documentImporter.ts b/server/commands/documentImporter.ts index 5e761d0d8a..974fc0ca86 100644 --- a/server/commands/documentImporter.ts +++ b/server/commands/documentImporter.ts @@ -5,8 +5,8 @@ import mammoth from "mammoth"; import quotedPrintable from "quoted-printable"; import { Transaction } from "sequelize"; import utf8 from "utf8"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import parseTitle from "@shared/utils/parseTitle"; +import { DocumentValidation } from "@shared/validations"; import { APM } from "@server/logging/tracing"; import { User } from "@server/models"; import dataURItoBuffer from "@server/utils/dataURItoBuffer"; @@ -190,7 +190,7 @@ async function documentImporter({ if (text.startsWith("# ")) { const result = parseTitle(text); title = result.title; - text = text.replace(`# ${title}\n`, ""); + text = text.replace(`# ${title}`, "").trimStart(); } // If we parsed an emoji from _above_ the title then add it back at prefixing @@ -221,7 +221,7 @@ async function documentImporter({ } // It's better to truncate particularly long titles than fail the import - title = truncate(title, { length: MAX_TITLE_LENGTH }); + title = truncate(title, { length: DocumentValidation.maxTitleLength }); return { text, diff --git a/server/commands/pinCreator.ts b/server/commands/pinCreator.ts index 7ce38427b4..12b957ea17 100644 --- a/server/commands/pinCreator.ts +++ b/server/commands/pinCreator.ts @@ -1,11 +1,10 @@ import fractionalIndex from "fractional-index"; import { Sequelize, Op, WhereOptions } from "sequelize"; +import { PinValidation } from "@shared/validations"; import { sequelize } from "@server/database/sequelize"; import { ValidationError } from "@server/errors"; import { Pin, User, Event } from "@server/models"; -const MAX_PINS = 8; - type Props = { /** The user creating the pin */ user: User; @@ -40,8 +39,10 @@ export default async function pinCreator({ }; const count = await Pin.count({ where }); - if (count >= MAX_PINS) { - throw ValidationError(`You cannot pin more than ${MAX_PINS} documents`); + if (count >= PinValidation.max) { + throw ValidationError( + `You cannot pin more than ${PinValidation.max} documents` + ); } if (!index) { diff --git a/server/commands/starCreator.ts b/server/commands/starCreator.ts index 02a55bae97..cdf960b614 100644 --- a/server/commands/starCreator.ts +++ b/server/commands/starCreator.ts @@ -54,7 +54,7 @@ export default async function starCreator({ index = fractionalIndex(null, stars.length ? stars[0].index : null); } - const response = await Star.findOrCreate({ + const [star, isCreated] = await Star.findOrCreate({ where: documentId ? { userId: user.id, @@ -69,12 +69,12 @@ export default async function starCreator({ }, transaction, }); - const star = response[0]; - if (response[1]) { + if (isCreated) { await Event.create( { name: "stars.create", + teamId: user.teamId, modelId: star.id, userId: user.id, actorId: user.id, diff --git a/server/commands/teamCreator.test.ts b/server/commands/teamProvisioner.test.ts similarity index 73% rename from server/commands/teamCreator.test.ts rename to server/commands/teamProvisioner.test.ts index a6aba15f2a..c6e5f3b436 100644 --- a/server/commands/teamCreator.test.ts +++ b/server/commands/teamProvisioner.test.ts @@ -2,16 +2,16 @@ 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 teamCreator from "./teamCreator"; +import teamProvisioner from "./teamProvisioner"; beforeEach(() => flushdb()); -describe("teamCreator", () => { +describe("teamProvisioner", () => { const ip = "127.0.0.1"; it("should create team and authentication provider", async () => { env.DEPLOYMENT = "hosted"; - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Test team", subdomain: "example", avatarUrl: "http://example.com/logo.png", @@ -35,7 +35,7 @@ describe("teamCreator", () => { await buildTeam({ subdomain: "myteam", }); - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Test team", subdomain: "myteam", avatarUrl: "http://example.com/logo.png", @@ -58,7 +58,7 @@ describe("teamCreator", () => { await buildTeam({ subdomain: "myteam1", }); - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Test team", subdomain: "myteam", avatarUrl: "http://example.com/logo.png", @@ -72,10 +72,63 @@ describe("teamCreator", () => { expect(result.team.subdomain).toEqual("myteam2"); }); + it("should return existing team", async () => { + env.DEPLOYMENT = "hosted"; + const authenticationProvider = { + name: "google", + providerId: "example.com", + }; + const existing = await buildTeam({ + subdomain: "example", + authenticationProviders: [authenticationProvider], + }); + const result = await teamProvisioner({ + name: "Updated name", + subdomain: "example", + authenticationProvider, + ip, + }); + const { team, isNewTeam } = result; + expect(team.id).toEqual(existing.id); + expect(team.name).toEqual(existing.name); + expect(team.subdomain).toEqual("example"); + expect(isNewTeam).toEqual(false); + }); + + it("should error on mismatched team and authentication provider", async () => { + env.DEPLOYMENT = "hosted"; + const exampleTeam = await buildTeam({ + subdomain: "example", + authenticationProviders: [ + { + name: "google", + providerId: "example.com", + }, + ], + }); + + let error; + try { + await teamProvisioner({ + teamId: exampleTeam.id, + name: "name", + subdomain: "other", + authenticationProvider: { + name: "google", + providerId: "other.com", + }, + ip, + }); + } catch (e) { + error = e; + } + expect(error.id).toEqual("invalid_authentication"); + }); + describe("self hosted", () => { it("should allow creating first team", async () => { env.DEPLOYMENT = undefined; - const { team, isNewTeam } = await teamCreator({ + const { team, isNewTeam } = await teamProvisioner({ name: "Test team", subdomain: "example", avatarUrl: "http://example.com/logo.png", @@ -96,7 +149,7 @@ describe("teamCreator", () => { let error; try { - await teamCreator({ + await teamProvisioner({ name: "Test team", subdomain: "example", avatarUrl: "http://example.com/logo.png", @@ -124,7 +177,7 @@ describe("teamCreator", () => { name: "allowed-domain.com", createdById: user.id, }); - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Updated name", subdomain: "example", domain: "allowed-domain.com", @@ -158,7 +211,7 @@ describe("teamCreator", () => { let error; try { - await teamCreator({ + await teamProvisioner({ name: "Updated name", subdomain: "example", domain: "other-domain.com", @@ -175,7 +228,7 @@ describe("teamCreator", () => { expect(error).toBeTruthy(); }); - it("should return exising team", async () => { + it("should return existing team", async () => { env.DEPLOYMENT = undefined; const authenticationProvider = { name: "google", @@ -185,7 +238,7 @@ describe("teamCreator", () => { subdomain: "example", authenticationProviders: [authenticationProvider], }); - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Updated name", subdomain: "example", authenticationProvider, diff --git a/server/commands/teamCreator.ts b/server/commands/teamProvisioner.ts similarity index 79% rename from server/commands/teamCreator.ts rename to server/commands/teamProvisioner.ts index 210a09a264..8c93cc49f2 100644 --- a/server/commands/teamCreator.ts +++ b/server/commands/teamProvisioner.ts @@ -1,8 +1,8 @@ import { sequelize } from "@server/database/sequelize"; import env from "@server/env"; import { - InvalidAuthenticationError, DomainNotAllowedError, + InvalidAuthenticationError, MaximumTeamsError, } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -10,37 +10,49 @@ import { APM } from "@server/logging/tracing"; import { Team, AuthenticationProvider, Event } from "@server/models"; import { generateAvatarUrl } from "@server/utils/avatars"; -type TeamCreatorResult = { +type TeamProvisionerResult = { team: Team; authenticationProvider: AuthenticationProvider; isNewTeam: boolean; }; type Props = { - id?: string; + /** + * The internal ID of the team that is being logged into based on the + * subdomain that the request came from, if any. + */ + teamId?: string; + /** The displayed name of the team */ name: string; + /** The domain name from the email of the user logging in */ domain?: string; + /** The preferred subdomain to provision for the team if not yet created */ subdomain: string; + /** The public url of an image representing the team */ avatarUrl?: string | null; + /** Details of the authentication provider being used */ authenticationProvider: { + /** The name of the authentication provider, eg "google" */ name: string; + /** External identifier of the authentication provider */ providerId: string; }; + /** The IP address of the incoming request */ ip: string; }; -async function teamCreator({ - id, +async function teamProvisioner({ + teamId, name, domain, subdomain, avatarUrl, authenticationProvider, ip, -}: Props): Promise { +}: Props): Promise { let authP = await AuthenticationProvider.findOne({ - where: id - ? { ...authenticationProvider, teamId: id } + where: teamId + ? { ...authenticationProvider, teamId } : authenticationProvider, include: [ { @@ -59,11 +71,9 @@ async function teamCreator({ team: authP.team, isNewTeam: false, }; - } - // A team id was provided but no auth provider was found matching those credentials - // The user is attempting to log into a team with an incorrect SSO - fail the login - else if (id) { - throw InvalidAuthenticationError("incorrect authentication credentials"); + } else if (teamId) { + // The user is attempting to log into a team with an unfamiliar SSO provider + throw InvalidAuthenticationError(); } // This team has never been seen before, if self hosted the logic is different @@ -176,5 +186,5 @@ async function provisionSubdomain(team: Team, requestedSubdomain: string) { export default APM.traceFunction({ serviceName: "command", - spanName: "teamCreator", -})(teamCreator); + spanName: "teamProvisioner", +})(teamProvisioner); diff --git a/server/commands/userCreator.test.ts b/server/commands/userProvisioner.test.ts similarity index 76% rename from server/commands/userCreator.test.ts rename to server/commands/userProvisioner.test.ts index 6969ba7f61..31aa473759 100644 --- a/server/commands/userCreator.test.ts +++ b/server/commands/userProvisioner.test.ts @@ -2,20 +2,20 @@ 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 userCreator from "./userCreator"; +import userProvisioner from "./userProvisioner"; beforeEach(() => flushdb()); -describe("userCreator", () => { +describe("userProvisioner", () => { const ip = "127.0.0.1"; - it("should update exising user and authentication", async () => { + it("should update existing user and authentication", async () => { const existing = await buildUser(); const authentications = await existing.$get("authentications"); const existingAuth = authentications[0]; const newEmail = "test@example.com"; const newUsername = "tname"; - const result = await userCreator({ + const result = await userProvisioner({ name: existing.name, email: newEmail, username: newUsername, @@ -30,9 +30,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual(newEmail); expect(user.username).toEqual(newUsername); expect(isNewUser).toEqual(false); @@ -50,7 +51,7 @@ describe("userCreator", () => { authentications: [], }); - const result = await userCreator({ + const result = await userProvisioner({ name: existing.name, email, username: "new-username", @@ -65,9 +66,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); const authentications = await user.$get("authentications"); expect(authentications.length).toEqual(1); @@ -85,7 +87,7 @@ describe("userCreator", () => { teamId: team.id, }); - const result = await userCreator({ + const result = await userProvisioner({ name: existing.name, email, username: "new-username", @@ -100,9 +102,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); const authentications = await user.$get("authentications"); expect(authentications.length).toEqual(1); @@ -115,7 +118,7 @@ describe("userCreator", () => { const existingAuth = authentications[0]; const newEmail = "test@example.com"; await existing.destroy(); - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "test@example.com", teamId: existing.teamId, @@ -128,9 +131,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual(newEmail); expect(isNewUser).toEqual(true); }); @@ -142,13 +146,13 @@ describe("userCreator", () => { let error; try { - await userCreator({ + await userProvisioner({ name: "Test Name", email: "test@example.com", teamId: existing.teamId, ip, authentication: { - authenticationProviderId: "example.org", + authenticationProviderId: uuidv4(), providerId: existingAuth.providerId, accessToken: "123", scopes: ["read"], @@ -165,7 +169,7 @@ describe("userCreator", () => { const team = await buildTeam(); const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "test@example.com", username: "tname", @@ -179,9 +183,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual("test@example.com"); expect(user.username).toEqual("tname"); expect(user.isAdmin).toEqual(false); @@ -195,7 +200,7 @@ describe("userCreator", () => { }); const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "test@example.com", username: "tname", @@ -219,7 +224,7 @@ describe("userCreator", () => { }); const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "test@example.com", username: "tname", @@ -236,7 +241,7 @@ describe("userCreator", () => { expect(tname.username).toEqual("tname"); expect(tname.isAdmin).toEqual(false); expect(tname.isViewer).toEqual(true); - const tname2Result = await userCreator({ + const tname2Result = await userProvisioner({ name: "Test2 Name", email: "tes2@example.com", username: "tname2", @@ -264,7 +269,7 @@ describe("userCreator", () => { }); const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: invite.name, email: "invite@ExamPle.com", teamId: invite.teamId, @@ -277,13 +282,46 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual(invite.email); expect(isNewUser).toEqual(true); }); + it("should create a user from an invited user using email match", async () => { + const externalUser = await buildUser({ + email: "external@example.com", + }); + + const team = await buildTeam({ inviteRequired: true }); + const invite = await buildInvite({ + teamId: team.id, + email: externalUser.email, + }); + + const authenticationProviders = await team.$get("authenticationProviders"); + const authenticationProvider = authenticationProviders[0]; + const result = await userProvisioner({ + name: invite.name, + email: "external@ExamPle.com", // ensure that email is case insensistive + teamId: invite.teamId, + emailMatchOnly: true, + ip, + authentication: { + authenticationProviderId: authenticationProvider.id, + providerId: "whatever", + accessToken: "123", + scopes: ["read"], + }, + }); + const { user, authentication, isNewUser } = result; + expect(authentication).toEqual(null); + expect(user.id).toEqual(invite.id); + expect(isNewUser).toEqual(true); + }); + it("should reject an uninvited user when invites are required", async () => { const team = await buildTeam({ inviteRequired: true }); @@ -292,7 +330,7 @@ describe("userCreator", () => { let error; try { - await userCreator({ + await userProvisioner({ name: "Uninvited User", email: "invite@ExamPle.com", teamId: team.id, @@ -323,7 +361,7 @@ describe("userCreator", () => { const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "user@example-company.com", teamId: team.id, @@ -336,9 +374,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual("user@example-company.com"); expect(isNewUser).toEqual(true); }); @@ -356,7 +395,7 @@ describe("userCreator", () => { let error; try { - await userCreator({ + await userProvisioner({ name: "Bad Domain User", email: "user@example.com", teamId: team.id, diff --git a/server/commands/userCreator.ts b/server/commands/userProvisioner.ts similarity index 74% rename from server/commands/userCreator.ts rename to server/commands/userProvisioner.ts index f9c6a9bfb0..280a8a4af3 100644 --- a/server/commands/userCreator.ts +++ b/server/commands/userProvisioner.ts @@ -1,43 +1,65 @@ import { sequelize } from "@server/database/sequelize"; import InviteAcceptedEmail from "@server/emails/templates/InviteAcceptedEmail"; -import { DomainNotAllowedError, InviteRequiredError } from "@server/errors"; +import { + DomainNotAllowedError, + InvalidAuthenticationError, + InviteRequiredError, +} from "@server/errors"; import { Event, Team, User, UserAuthentication } from "@server/models"; -type UserCreatorResult = { +type UserProvisionerResult = { user: User; isNewUser: boolean; - authentication: UserAuthentication; + authentication: UserAuthentication | null; }; type Props = { + /** The displayed name of the user */ name: string; + /** The email address of the user */ email: string; + /** The username of the user */ username?: string; + /** Provision the new user as an administrator */ isAdmin?: boolean; + /** The public url of an image representing the user */ avatarUrl?: string | null; + /** + * The internal ID of the team that is being logged into based on the + * subdomain that the request came from, if any. + */ teamId: string; + /** Only match against existing user accounts using email, do not create a new account */ + emailMatchOnly?: boolean; + /** The IP address of the incoming request */ ip: string; authentication: { authenticationProviderId: string; + /** External identifier of the user in the authentication provider */ providerId: string; + /** The scopes granted by the access token */ scopes: string[]; + /** The token provided by the authentication provider */ accessToken?: string; + /** The refresh token provided by the authentication provider */ refreshToken?: string; + /** The timestamp when the access token expires */ expiresAt?: Date; }; }; -export default async function userCreator({ +export default async function userProvisioner({ name, email, username, isAdmin, + emailMatchOnly, avatarUrl, teamId, authentication, ip, -}: Props): Promise { - const { authenticationProviderId, providerId, ...rest } = authentication; +}: Props): Promise { + const { providerId, authenticationProviderId, ...rest } = authentication; const auth = await UserAuthentication.findOne({ where: { @@ -87,9 +109,8 @@ export default async function userCreator({ await auth.destroy(); } - // A `user` record might exist in the form of an invite even if there is no - // existing authentication record that matches. In Outline an invite is a - // shell user record. + // A `user` record may exist even if there is no existing authentication record. + // This is either an invite or a user that's external to the team const existingUser = await User.scope([ "withAuthentications", "withTeam", @@ -102,12 +123,11 @@ export default async function userCreator({ }, }); - // We have an existing invite for his user, so we need to update it with our - // new details, link up the authentication method, and count this as a new - // user creation. + // We have an existing user, so we need to update it with our + // new details and count this as a new user creation. if (existingUser) { // A `user` record might exist in the form of an invite. - // In Outline an invite is a shell user record with no authentication method + // An invite is a shell user record with no authentication method // that's never been active before. const isInvite = existingUser.isInvited; @@ -145,6 +165,12 @@ export default async function userCreator({ } ); + // We don't want to associate a user auth with the auth provider + // if we're doing a simple email match, so early return here + if (emailMatchOnly) { + return null; + } + return await existingUser.$create( "authentication", authentication, @@ -171,9 +197,16 @@ export default async function userCreator({ authentication: auth, isNewUser: isInvite, }; + } else if (emailMatchOnly) { + // There's no existing invite or user that matches the external auth email + // This is simply unauthorized + throw InvalidAuthenticationError(); } + // // No auth, no user – this is an entirely new sign in. + // + const transaction = await User.sequelize!.transaction(); try { diff --git a/server/emails/mailer.tsx b/server/emails/mailer.tsx index f366391a98..bd58d278b4 100644 --- a/server/emails/mailer.tsx +++ b/server/emails/mailer.tsx @@ -103,11 +103,15 @@ export class Mailer { pass: env.SMTP_PASSWORD, } : undefined, - tls: env.SMTP_TLS_CIPHERS - ? { - ciphers: env.SMTP_TLS_CIPHERS, - } - : undefined, + tls: env.SMTP_SECURE + ? env.SMTP_TLS_CIPHERS + ? { + ciphers: env.SMTP_TLS_CIPHERS, + } + : undefined + : { + rejectUnauthorized: false, + }, }; } diff --git a/server/emails/templates/ConfirmUserDeleteEmail.tsx b/server/emails/templates/ConfirmUserDeleteEmail.tsx new file mode 100644 index 0000000000..0364aadc78 --- /dev/null +++ b/server/emails/templates/ConfirmUserDeleteEmail.tsx @@ -0,0 +1,57 @@ +import * as React from "react"; +import BaseEmail from "./BaseEmail"; +import Body from "./components/Body"; +import CopyableCode from "./components/CopyableCode"; +import EmailTemplate from "./components/EmailLayout"; +import EmptySpace from "./components/EmptySpace"; +import Footer from "./components/Footer"; +import Header from "./components/Header"; +import Heading from "./components/Heading"; + +type Props = { + to: string; + deleteConfirmationCode: string; +}; + +/** + * Email sent to a user when they request to delete their account. + */ +export default class ConfirmUserDeleteEmail extends BaseEmail { + protected subject() { + return `Your account deletion request`; + } + + protected preview() { + return `Your requested account deletion code`; + } + + protected renderAsText({ deleteConfirmationCode }: Props): string { + return ` +You requested to permanantly delete your Outline account. Please enter the code below to confirm your account deletion. + +Code: ${deleteConfirmationCode} +`; + } + + protected render({ deleteConfirmationCode }: Props) { + return ( + +
+ + + Your account deletion request +

+ You requested to permanantly delete your Outline account. Please + enter the code below to confirm your account deletion. +

+ +

+ {deleteConfirmationCode} +

+ + +