From 1c9eee2134e8bacd96d5b6200d07a53c11b5b1c7 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 3 Jan 2023 19:28:04 -0500 Subject: [PATCH 01/61] fix: Search on shared documents with custom slug not working fix: Should not be able to export a document with shareId --- server/routes/api/documents/documents.ts | 5 +++-- server/routes/api/documents/schema.ts | 17 +++++------------ 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 23c8a0eeef..d3cd1e745d 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -442,13 +442,12 @@ router.post( }), validate(T.DocumentsExportSchema), async (ctx: APIContext) => { - const { id, shareId } = ctx.input; + const { id } = ctx.input; const { user } = ctx.state; const accept = ctx.request.headers["accept"]; const { document } = await documentLoader({ id, - shareId, user, // We need the collaborative state to generate HTML. includeState: !accept?.includes("text/markdown"), @@ -672,7 +671,9 @@ router.post( let response; if (shareId) { + const teamFromCtx = await getTeamFromContext(ctx); const { share, document } = await documentLoader({ + teamId: teamFromCtx?.id, shareId, user, }); diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index 192542697a..9d01d3a6d4 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -114,17 +114,7 @@ export const DocumentsInfoSchema = z export type DocumentsInfoReq = z.infer; -export const DocumentsExportSchema = z - .object({ - /** Id of the document to be exported */ - id: z.string().uuid().optional(), - - /** Share Id, if available */ - shareId: z.string().uuid().optional(), - }) - .refine((obj) => !(isEmpty(obj.id) && isEmpty(obj.shareId)), { - message: "one of id or shareId is required", - }); +export const DocumentsExportSchema = BaseIdSchema.extend({}); export type DocumentsExportReq = z.infer; @@ -154,7 +144,10 @@ export const DocumentsSearchSchema = SearchQuerySchema.merge( userId: z.string().uuid().optional(), /** Filter results for the team derived from shareId */ - shareId: z.string().uuid().optional(), + shareId: z + .string() + .refine((val) => isUUID(val) || SHARE_URL_SLUG_REGEX.test(val)) + .optional(), /** Min words to be shown in the results snippets */ snippetMinWords: z.number().default(20), From a2e183627c8b62997bbb68f15ecf89c953762fbe Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 3 Jan 2023 19:32:16 -0500 Subject: [PATCH 02/61] fix: Disabled authentication providers show as enabled in settings --- app/models/AuthenticationProvider.ts | 7 ++++++- app/scenes/Settings/Security.tsx | 9 +++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/app/models/AuthenticationProvider.ts b/app/models/AuthenticationProvider.ts index e144eb94e2..f292651a83 100644 --- a/app/models/AuthenticationProvider.ts +++ b/app/models/AuthenticationProvider.ts @@ -1,4 +1,4 @@ -import { observable } from "mobx"; +import { computed, observable } from "mobx"; import BaseModel from "./BaseModel"; import Field from "./decorators/Field"; @@ -14,6 +14,11 @@ class AuthenticationProvider extends BaseModel { @Field @observable isEnabled: boolean; + + @computed + get isActive() { + return this.isEnabled && this.isConnected; + } } export default AuthenticationProvider; diff --git a/app/scenes/Settings/Security.tsx b/app/scenes/Settings/Security.tsx index 840822f22f..57a870ff20 100644 --- a/app/scenes/Settings/Security.tsx +++ b/app/scenes/Settings/Security.tsx @@ -165,8 +165,13 @@ function Security() { })} > - {" "} - {t("Connected")} + {" "} + + {provider.isActive ? t("Connected") : t("Disabled")} + ))} From eb50c9e1f1c823b82635a9a79ccdb1188a7ff84b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 3 Jan 2023 22:49:02 -0500 Subject: [PATCH 03/61] test: Remove tests associated with exporting documents from shareId --- server/routes/api/documents/documents.test.ts | 130 ------------------ 1 file changed, 130 deletions(-) diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index bde267871c..166c74d2ac 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -552,113 +552,6 @@ describe("#documents.export", () => { expect(body.data).toEqual(DocumentHelper.toMarkdown(document)); }); - it("should return document from shareId without token", async () => { - const { document, user } = await seed(); - const share = await buildShare({ - documentId: document.id, - teamId: document.teamId, - userId: user.id, - }); - const res = await server.post("/api/documents.export", { - body: { - shareId: share.id, - }, - }); - const body = await res.json(); - expect(res.status).toEqual(200); - expect(body.data).toEqual(DocumentHelper.toMarkdown(document)); - }); - - it("should not return document from revoked shareId", async () => { - const { document, user } = await seed(); - const share = await buildShare({ - documentId: document.id, - teamId: document.teamId, - userId: user.id, - }); - await share.revoke(user.id); - const res = await server.post("/api/documents.export", { - body: { - shareId: share.id, - }, - }); - expect(res.status).toEqual(400); - }); - - it("should not return document from archived shareId", async () => { - const { document, user } = await seed(); - const share = await buildShare({ - documentId: document.id, - teamId: document.teamId, - userId: user.id, - }); - await document.archive(user.id); - const res = await server.post("/api/documents.export", { - body: { - shareId: share.id, - }, - }); - expect(res.status).toEqual(400); - }); - - it("should return document from shareId with token", async () => { - const { user, document } = await seed(); - const share = await buildShare({ - documentId: document.id, - teamId: document.teamId, - userId: user.id, - }); - const res = await server.post("/api/documents.export", { - body: { - token: user.getJwtToken(), - shareId: share.id, - }, - }); - const body = await res.json(); - expect(res.status).toEqual(200); - expect(body.data).toEqual(DocumentHelper.toMarkdown(document)); - }); - - it("should return draft document from shareId with token", async () => { - const { user, document } = await seed(); - document.publishedAt = null; - await document.save(); - const share = await buildShare({ - documentId: document.id, - teamId: document.teamId, - userId: user.id, - }); - const res = await server.post("/api/documents.export", { - body: { - token: user.getJwtToken(), - shareId: share.id, - }, - }); - const body = await res.json(); - expect(res.status).toEqual(200); - expect(body.data).toEqual(DocumentHelper.toMarkdown(document)); - }); - - it("should return document from shareId in collection not a member of", async () => { - const { user, document, collection } = await seed(); - const share = await buildShare({ - documentId: document.id, - teamId: document.teamId, - userId: user.id, - }); - collection.permission = null; - await collection.save(); - const res = await server.post("/api/documents.export", { - body: { - token: user.getJwtToken(), - shareId: share.id, - }, - }); - const body = await res.json(); - expect(res.status).toEqual(200); - expect(body.data).toEqual(DocumentHelper.toMarkdown(document)); - }); - it("should require authorization without token", async () => { const { document } = await seed(); const res = await server.post("/api/documents.export", { @@ -680,15 +573,6 @@ describe("#documents.export", () => { }); expect(res.status).toEqual(403); }); - - it("should require a valid shareId", async () => { - const res = await server.post("/api/documents.export", { - body: { - shareId: 123, - }, - }); - expect(res.status).toEqual(400); - }); }); describe("#documents.list", () => { @@ -1163,20 +1047,6 @@ describe("#documents.search_titles", () => { }); describe("#documents.search", () => { - it("should fail for invalid shareId", async () => { - const { user } = await seed(); - const res = await server.post("/api/documents.search", { - body: { - token: user.getJwtToken(), - query: "much", - shareId: "invalid", - }, - }); - const body = await res.json(); - expect(res.status).toEqual(400); - expect(body.message).toEqual("shareId: Invalid uuid"); - }); - it("should return results", async () => { const { user } = await seed(); const res = await server.post("/api/documents.search", { From bb568d2e62bc1dbb2ccb971c0b553eaedaf2937b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 4 Jan 2023 12:18:59 +0000 Subject: [PATCH 04/61] fix: Exports generate invalid internal links (#4639) * refactoring * Refactoring continues * Refactor export, fix internal links in exported docs * fix: Dupe document name detection * sigh --- server/queues/tasks/ExportDocumentTreeTask.ts | 195 +++++++++++++ server/queues/tasks/ExportHTMLZipTask.ts | 14 +- server/queues/tasks/ExportMarkdownZipTask.ts | 11 +- server/queues/tasks/ImportMarkdownZipTask.ts | 4 +- server/queues/tasks/ImportNotionTask.ts | 4 +- server/utils/ZipHelper.ts | 115 ++++++++ server/utils/zip.ts | 266 ------------------ 7 files changed, 331 insertions(+), 278 deletions(-) create mode 100644 server/queues/tasks/ExportDocumentTreeTask.ts create mode 100644 server/utils/ZipHelper.ts delete mode 100644 server/utils/zip.ts diff --git a/server/queues/tasks/ExportDocumentTreeTask.ts b/server/queues/tasks/ExportDocumentTreeTask.ts new file mode 100644 index 0000000000..edaa0ed90f --- /dev/null +++ b/server/queues/tasks/ExportDocumentTreeTask.ts @@ -0,0 +1,195 @@ +import path from "path"; +import JSZip from "jszip"; +import { FileOperationFormat } from "@shared/types"; +import Logger from "@server/logging/Logger"; +import { Collection } from "@server/models"; +import Attachment from "@server/models/Attachment"; +import Document from "@server/models/Document"; +import DocumentHelper from "@server/models/helpers/DocumentHelper"; +import ZipHelper from "@server/utils/ZipHelper"; +import { serializeFilename } from "@server/utils/fs"; +import parseAttachmentIds from "@server/utils/parseAttachmentIds"; +import { getFileByKey } from "@server/utils/s3"; +import { NavigationNode } from "~/types"; +import ExportTask from "./ExportTask"; + +export default abstract class ExportDocumentTreeTask extends ExportTask { + /** + * Exports the document tree to the given zip instance. + * + * @param zip The JSZip instance to add files to + * @param documentId The document ID to export + * @param pathInZip The path in the zip to add the document to + * @param format The format to export in + */ + protected async addDocumentToArchive({ + zip, + pathInZip, + documentId, + format = FileOperationFormat.MarkdownZip, + pathMap, + }: { + zip: JSZip; + pathInZip: string; + documentId: string; + format: FileOperationFormat; + pathMap: Map; + }) { + const document = await Document.findByPk(documentId); + if (!document) { + return; + } + + let text = + format === FileOperationFormat.HTMLZip + ? await DocumentHelper.toHTML(document, { centered: true }) + : await DocumentHelper.toMarkdown(document); + const attachments = await Attachment.findAll({ + where: { + teamId: document.teamId, + id: parseAttachmentIds(document.text), + }, + }); + + // Add any referenced attachments to the zip file and replace the + // reference in the document with the path to the attachment in the zip + await Promise.all( + attachments.map(async (attachment) => { + try { + const img = await getFileByKey(attachment.key); + const dir = path.dirname(pathInZip); + if (img) { + zip.file(path.join(dir, attachment.key), img as Blob, { + createFolders: true, + }); + } + } catch (err) { + Logger.error( + `Failed to add attachment to archive: ${attachment.key}`, + err + ); + } + + text = text.replace(attachment.redirectUrl, encodeURI(attachment.key)); + }) + ); + + // Replace any internal links with relative paths to the document in the zip + const internalLinks = [ + ...text.matchAll(/\/doc\/(?:[0-9a-zA-Z-_~]*-)?([a-zA-Z0-9]{10,15})/g), + ]; + internalLinks.forEach((match) => { + const matchedLink = match[0]; + const matchedDocPath = pathMap.get(matchedLink); + + if (matchedDocPath) { + const relativePath = path.relative(pathInZip, matchedDocPath); + if (relativePath.startsWith(".")) { + text = text.replace( + matchedLink, + encodeURI(relativePath.substring(1)) + ); + } + } + }); + + // Finally, add the document to the zip file + zip.file(pathInZip, text, { + date: document.updatedAt, + createFolders: true, + comment: JSON.stringify({ + createdAt: document.createdAt, + updatedAt: document.updatedAt, + }), + }); + } + + /** + * Exports the documents and attachments in the given collections to a zip file + * and returns the path to the zip file in tmp. + * + * @param zip The JSZip instance to add files to + * @param collections The collections to export + * @param format The format to export in + * + * @returns The path to the zip file in tmp. + */ + protected async addCollectionsToArchive( + zip: JSZip, + collections: Collection[], + format: FileOperationFormat + ) { + const pathMap = this.createPathMap(collections, format); + + for (const path of pathMap) { + const documentId = path[0].replace("/doc/", ""); + const pathInZip = path[1]; + + await this.addDocumentToArchive({ + zip, + pathInZip, + documentId, + format, + pathMap, + }); + } + + return ZipHelper.toTmpFile(zip); + } + + /** + * Generates a map of document urls to their path in the zip file. + * + * @param collections + */ + private createPathMap( + collections: Collection[], + format: FileOperationFormat + ) { + const map = new Map(); + + for (const collection of collections) { + if (collection.documentStructure) { + this.addDocumentTreeToPathMap( + map, + collection.documentStructure, + serializeFilename(collection.name), + format + ); + } + } + + return map; + } + + private addDocumentTreeToPathMap( + map: Map, + nodes: NavigationNode[], + root: string, + format: FileOperationFormat + ) { + for (const node of nodes) { + const title = serializeFilename(node.title) || "Untitled"; + const extension = format === FileOperationFormat.HTMLZip ? "html" : "md"; + + // Ensure the document is given a unique path in zip, even if it has + // the same title as another document in the same collection. + let i = 0; + let filePath = path.join(root, `${title}.${extension}`); + while (Array.from(map.values()).includes(filePath)) { + filePath = path.join(root, `${title} (${++i}).${extension}`); + } + + map.set(node.url, filePath); + + if (node.children?.length) { + this.addDocumentTreeToPathMap( + map, + node.children, + path.join(root, title), + format + ); + } + } + } +} diff --git a/server/queues/tasks/ExportHTMLZipTask.ts b/server/queues/tasks/ExportHTMLZipTask.ts index aabdfafa66..fc6a84ef92 100644 --- a/server/queues/tasks/ExportHTMLZipTask.ts +++ b/server/queues/tasks/ExportHTMLZipTask.ts @@ -1,10 +1,16 @@ +import JSZip from "jszip"; import { FileOperationFormat } from "@shared/types"; import { Collection } from "@server/models"; -import { archiveCollections } from "@server/utils/zip"; -import ExportTask from "./ExportTask"; +import ExportDocumentTreeTask from "./ExportDocumentTreeTask"; -export default class ExportHTMLZipTask extends ExportTask { +export default class ExportHTMLZipTask extends ExportDocumentTreeTask { public async export(collections: Collection[]) { - return await archiveCollections(collections, FileOperationFormat.HTMLZip); + const zip = new JSZip(); + + return await this.addCollectionsToArchive( + zip, + collections, + FileOperationFormat.HTMLZip + ); } } diff --git a/server/queues/tasks/ExportMarkdownZipTask.ts b/server/queues/tasks/ExportMarkdownZipTask.ts index a84a93cb63..6ea69eefe5 100644 --- a/server/queues/tasks/ExportMarkdownZipTask.ts +++ b/server/queues/tasks/ExportMarkdownZipTask.ts @@ -1,11 +1,14 @@ +import JSZip from "jszip"; import { FileOperationFormat } from "@shared/types"; import { Collection } from "@server/models"; -import { archiveCollections } from "@server/utils/zip"; -import ExportTask from "./ExportTask"; +import ExportDocumentTreeTask from "./ExportDocumentTreeTask"; -export default class ExportMarkdownZipTask extends ExportTask { +export default class ExportMarkdownZipTask extends ExportDocumentTreeTask { public async export(collections: Collection[]) { - return await archiveCollections( + const zip = new JSZip(); + + return await this.addCollectionsToArchive( + zip, collections, FileOperationFormat.MarkdownZip ); diff --git a/server/queues/tasks/ImportMarkdownZipTask.ts b/server/queues/tasks/ImportMarkdownZipTask.ts index 4053619fd2..966f8240ed 100644 --- a/server/queues/tasks/ImportMarkdownZipTask.ts +++ b/server/queues/tasks/ImportMarkdownZipTask.ts @@ -5,7 +5,7 @@ import { v4 as uuidv4 } from "uuid"; import documentImporter from "@server/commands/documentImporter"; import Logger from "@server/logging/Logger"; import { FileOperation, User } from "@server/models"; -import { zipAsFileTree, FileTreeNode } from "@server/utils/zip"; +import ZipHelper, { FileTreeNode } from "@server/utils/ZipHelper"; import ImportTask, { StructuredImportData } from "./ImportTask"; export default class ImportMarkdownZipTask extends ImportTask { @@ -14,7 +14,7 @@ export default class ImportMarkdownZipTask extends ImportTask { fileOperation: FileOperation ): Promise { const zip = await JSZip.loadAsync(buffer); - const tree = zipAsFileTree(zip); + const tree = ZipHelper.toFileTree(zip); return this.parseFileTree({ fileOperation, zip, tree }); } diff --git a/server/queues/tasks/ImportNotionTask.ts b/server/queues/tasks/ImportNotionTask.ts index bcbaa8c253..7b67523e2b 100644 --- a/server/queues/tasks/ImportNotionTask.ts +++ b/server/queues/tasks/ImportNotionTask.ts @@ -6,7 +6,7 @@ import { v4 as uuidv4 } from "uuid"; import documentImporter from "@server/commands/documentImporter"; import Logger from "@server/logging/Logger"; import { FileOperation, User } from "@server/models"; -import { zipAsFileTree, FileTreeNode } from "@server/utils/zip"; +import ZipHelper, { FileTreeNode } from "@server/utils/ZipHelper"; import ImportTask, { StructuredImportData } from "./ImportTask"; export default class ImportNotionTask extends ImportTask { @@ -15,7 +15,7 @@ export default class ImportNotionTask extends ImportTask { fileOperation: FileOperation ): Promise { const zip = await JSZip.loadAsync(buffer); - const tree = zipAsFileTree(zip); + const tree = ZipHelper.toFileTree(zip); return this.parseFileTree({ fileOperation, zip, tree }); } diff --git a/server/utils/ZipHelper.ts b/server/utils/ZipHelper.ts new file mode 100644 index 0000000000..bc15f267d1 --- /dev/null +++ b/server/utils/ZipHelper.ts @@ -0,0 +1,115 @@ +import fs from "fs"; +import path from "path"; +import JSZip from "jszip"; +import { find } from "lodash"; +import tmp from "tmp"; +import { ValidationError } from "@server/errors"; +import { trace } from "@server/logging/tracing"; +import { deserializeFilename } from "./fs"; + +export type FileTreeNode = { + /** The title, extracted from the file name */ + title: string; + /** The file name including extension */ + name: string; + /** Full path to the file within the zip file */ + path: string; + /** Any nested children */ + children: FileTreeNode[]; +}; + +@trace() +export default class ZipHelper { + /** + * Converts the flat structure returned by JSZIP into a nested file structure + * for easier processing. + * + * @param zip The JSZip instance + * @param maxFiles The maximum number of files to unzip (Prevent zip bombs) + */ + public static toFileTree( + zip: JSZip, + /** The maximum number of files to unzip */ + maxFiles = 10000 + ) { + let fileCount = 0; + const paths = Object.keys(zip.files).map((filePath) => { + if (++fileCount > maxFiles) { + throw ValidationError("Too many files in zip"); + } + + return `/${filePath}`; + }); + const tree: FileTreeNode[] = []; + + paths.forEach(function (filePath) { + if (filePath.startsWith("/__MACOSX")) { + return; + } + + const pathParts = filePath.split("/"); + + // Remove first blank element from the parts array. + pathParts.shift(); + + let currentLevel = tree; // initialize currentLevel to root + + pathParts.forEach(function (name) { + // check to see if the path already exists. + const existingPath = find(currentLevel, { + name, + }); + + if (existingPath) { + // The path to this item was already in the tree, so don't add again. + // Set the current level to this path's children + currentLevel = existingPath.children; + } else if (name.endsWith(".DS_Store") || !name) { + return; + } else { + const newPart = { + name, + path: filePath.replace(/^\//, ""), + title: deserializeFilename(path.parse(path.basename(name)).name), + children: [], + }; + + currentLevel.push(newPart); + currentLevel = newPart.children; + } + }); + }); + + return tree; + } + + /** + * Write a zip file to a temporary disk location + * + * @param zip JSZip object + * @returns pathname of the temporary file where the zip was written to disk + */ + public static async toTmpFile(zip: JSZip): Promise { + return new Promise((resolve, reject) => { + tmp.file( + { + prefix: "export-", + postfix: ".zip", + }, + (err, path) => { + if (err) { + return reject(err); + } + zip + .generateNodeStream({ + type: "nodebuffer", + streamFiles: true, + }) + .pipe(fs.createWriteStream(path)) + .on("finish", () => resolve(path)) + .on("error", reject); + } + ); + }); + } +} diff --git a/server/utils/zip.ts b/server/utils/zip.ts deleted file mode 100644 index 8882b216c7..0000000000 --- a/server/utils/zip.ts +++ /dev/null @@ -1,266 +0,0 @@ -import fs from "fs"; -import path from "path"; -import JSZip, { JSZipObject } from "jszip"; -import { find } from "lodash"; -import tmp from "tmp"; -import { FileOperationFormat } from "@shared/types"; -import { ValidationError } from "@server/errors"; -import Logger from "@server/logging/Logger"; -import Attachment from "@server/models/Attachment"; -import Collection from "@server/models/Collection"; -import Document from "@server/models/Document"; -import DocumentHelper from "@server/models/helpers/DocumentHelper"; -import { NavigationNode } from "~/types"; -import { deserializeFilename, serializeFilename } from "./fs"; -import parseAttachmentIds from "./parseAttachmentIds"; -import { getFileByKey } from "./s3"; - -type ItemType = "collection" | "document" | "attachment"; - -export type Item = { - path: string; - dir: string; - name: string; - depth: number; - metadata: Record; - type: ItemType; - item: JSZipObject; -}; - -export type FileTreeNode = { - /** The title, extracted from the file name */ - title: string; - /** The file name including extension */ - name: string; - /** The full path to within the zip file */ - path: string; - /** The nested children */ - children: FileTreeNode[]; -}; - -async function addDocumentTreeToArchive( - zip: JSZip, - documents: NavigationNode[], - format = FileOperationFormat.MarkdownZip -) { - for (const doc of documents) { - const document = await Document.findByPk(doc.id); - - if (!document) { - continue; - } - - let text = - format === FileOperationFormat.HTMLZip - ? await DocumentHelper.toHTML(document, { centered: true }) - : await DocumentHelper.toMarkdown(document); - const attachments = await Attachment.findAll({ - where: { - teamId: document.teamId, - id: parseAttachmentIds(document.text), - }, - }); - - for (const attachment of attachments) { - await addImageToArchive(zip, attachment.key); - text = text.replace(attachment.redirectUrl, encodeURI(attachment.key)); - } - - let title = serializeFilename(document.title) || "Untitled"; - - const extension = format === FileOperationFormat.HTMLZip ? "html" : "md"; - - title = safeAddFileToArchive(zip, `${title}.${extension}`, text, { - date: document.updatedAt, - comment: JSON.stringify({ - createdAt: document.createdAt, - updatedAt: document.updatedAt, - }), - }); - - if (doc.children && doc.children.length) { - const folder = zip.folder(path.parse(title).name); - - if (folder) { - await addDocumentTreeToArchive(folder, doc.children, format); - } - } - } -} - -/** - * Adds the content of a file in remote storage to the given zip file. - * - * @param zip JSZip object to add to - * @param key path to file in S3 storage - */ -async function addImageToArchive(zip: JSZip, key: string) { - try { - const img = await getFileByKey(key); - - // @ts-expect-error Blob - zip.file(key, img, { - createFolders: true, - }); - } catch (err) { - Logger.error("Error loading image attachment from S3", err, { - key, - }); - } -} - -/** - * Adds content to a zip file, if the given filename already exists in the zip - * then it will automatically increment numbers at the end of the filename. - * - * @param zip JSZip object to add to - * @param key filename with extension - * @param content the content to add - * @param options options for added content - * @returns The new title - */ -function safeAddFileToArchive( - zip: JSZip, - key: string, - content: string | Uint8Array | ArrayBuffer | Blob, - options: JSZip.JSZipFileOptions -) { - // @ts-expect-error root exists - const root = zip.root; - - // Filenames in the directory already - const keysInDirectory = Object.keys(zip.files) - .filter((k) => k.includes(root)) - .filter((k) => !k.endsWith("/")) - .map((k) => path.basename(k).replace(/\s\((\d+)\)\./, ".")); - - // The number of duplicate filenames - const existingKeysCount = keysInDirectory.filter((t) => t === key).length; - const filename = path.parse(key).name; - const extension = path.extname(key); - - // Construct the new de-duplicated filename (if any) - const safeKey = - existingKeysCount > 0 - ? `${filename} (${existingKeysCount})${extension}` - : key; - - zip.file(safeKey, content, options); - return safeKey; -} - -/** - * Write a zip file to a temporary disk location - * - * @param zip JSZip object - * @returns pathname of the temporary file where the zip was written to disk - */ -async function archiveToPath(zip: JSZip): Promise { - return new Promise((resolve, reject) => { - tmp.file( - { - prefix: "export-", - postfix: ".zip", - }, - (err, path) => { - if (err) { - return reject(err); - } - zip - .generateNodeStream({ - type: "nodebuffer", - streamFiles: true, - }) - .pipe(fs.createWriteStream(path)) - .on("finish", () => resolve(path)) - .on("error", reject); - } - ); - }); -} - -export async function archiveCollections( - collections: Collection[], - format: FileOperationFormat -) { - const zip = new JSZip(); - - for (const collection of collections) { - if (collection.documentStructure) { - const folder = zip.folder(serializeFilename(collection.name)); - - if (folder) { - await addDocumentTreeToArchive( - folder, - collection.documentStructure, - format - ); - } - } - } - - return archiveToPath(zip); -} - -/** - * Converts the flat structure returned by JSZIP into a nested file structure - * for easier processing. - * - * @param paths An array of paths to files in the zip - * @returns - */ -export function zipAsFileTree( - zip: JSZip, - /** The maximum number of files to unzip */ - maxFiles = 10000 -) { - let fileCount = 0; - const paths = Object.keys(zip.files).map((filePath) => { - if (++fileCount > maxFiles) { - throw ValidationError("Too many files in zip"); - } - - return `/${filePath}`; - }); - const tree: FileTreeNode[] = []; - - paths.forEach(function (filePath) { - if (filePath.startsWith("/__MACOSX")) { - return; - } - - const pathParts = filePath.split("/"); - - // Remove first blank element from the parts array. - pathParts.shift(); - - let currentLevel = tree; // initialize currentLevel to root - - pathParts.forEach(function (name) { - // check to see if the path already exists. - const existingPath = find(currentLevel, { - name, - }); - - if (existingPath) { - // The path to this item was already in the tree, so don't add again. - // Set the current level to this path's children - currentLevel = existingPath.children; - } else if (name.endsWith(".DS_Store") || !name) { - return; - } else { - const newPart = { - name, - path: filePath.replace(/^\//, ""), - title: deserializeFilename(path.parse(path.basename(name)).name), - children: [], - }; - - currentLevel.push(newPart); - currentLevel = newPart.children; - } - }); - }); - - return tree; -} From f4461573ded7539d29de35edd6b1477fb451bac3 Mon Sep 17 00:00:00 2001 From: Apoorv Mishra Date: Wed, 4 Jan 2023 23:51:44 +0530 Subject: [PATCH 05/61] Refactor to accommodate authentication, transaction and pagination states together (#4636) * fix: refactor to accommodate authentication, transaction and pagination together into ctx.state * feat: allow passing response type to APIContext --- server/logging/sentry.ts | 10 +- server/middlewares/authentication.test.ts | 8 +- server/middlewares/authentication.ts | 22 +- server/middlewares/transaction.ts | 11 +- server/routes/api/apiKeys.ts | 101 +++---- server/routes/api/attachments/attachments.ts | 11 +- server/routes/api/auth.ts | 60 ++-- server/routes/api/authenticationProviders.ts | 13 +- server/routes/api/collections.ts | 274 ++++++++++--------- server/routes/api/developer.ts | 68 ++--- server/routes/api/documents/documents.ts | 41 ++- server/routes/api/events/events.ts | 2 +- server/routes/api/fileOperations.ts | 68 +++-- server/routes/api/groups.ts | 126 +++++---- server/routes/api/hooks.ts | 7 +- server/routes/api/index.ts | 9 +- server/routes/api/integrations.ts | 198 ++++++++------ server/routes/api/middlewares/pagination.ts | 19 +- server/routes/api/notificationSettings.ts | 16 +- server/routes/api/pins.ts | 17 +- server/routes/api/revisions.ts | 13 +- server/routes/api/searches.ts | 9 +- server/routes/api/shares.ts | 21 +- server/routes/api/stars.ts | 17 +- server/routes/api/subscriptions.ts | 81 +++--- server/routes/api/team.ts | 9 +- server/routes/api/users.ts | 132 +++++---- server/routes/api/views.ts | 9 +- server/routes/api/webhookSubscriptions.ts | 18 +- server/routes/auth/index.ts | 7 +- server/types.ts | 31 ++- 31 files changed, 753 insertions(+), 675 deletions(-) diff --git a/server/logging/sentry.ts b/server/logging/sentry.ts index 9e2745a02f..a89221d0dc 100644 --- a/server/logging/sentry.ts +++ b/server/logging/sentry.ts @@ -1,6 +1,6 @@ import * as Sentry from "@sentry/node"; import env from "@server/env"; -import { ContextWithState } from "../types"; +import { AppContext } from "@server/types"; if (env.SENTRY_DSN) { Sentry.init({ @@ -29,7 +29,7 @@ if (env.SENTRY_DSN) { }); } -export function requestErrorHandler(error: any, ctx: ContextWithState) { +export function requestErrorHandler(error: any, ctx: AppContext) { // we don't need to report every time a request stops to the bug tracker if (error.code === "EPIPE" || error.code === "ECONNRESET") { console.warn("Connection error", { @@ -46,17 +46,17 @@ export function requestErrorHandler(error: any, ctx: ContextWithState) { scope.setTag("request_id", requestId as string); } - const authType = ctx.state?.authType ?? undefined; + const authType = ctx.state?.auth?.type ?? undefined; if (authType) { scope.setTag("auth_type", authType); } - const teamId = ctx.state?.user?.teamId ?? undefined; + const teamId = ctx.state?.auth?.user?.teamId ?? undefined; if (teamId) { scope.setTag("team_id", teamId); } - const userId = ctx.state?.user?.id ?? undefined; + const userId = ctx.state?.auth?.user?.id ?? undefined; if (userId) { scope.setUser({ id: userId, diff --git a/server/middlewares/authentication.test.ts b/server/middlewares/authentication.test.ts index 7a29c10bd8..2ade227d1a 100644 --- a/server/middlewares/authentication.test.ts +++ b/server/middlewares/authentication.test.ts @@ -24,7 +24,7 @@ describe("Authentication middleware", () => { }, jest.fn() ); - expect(state.user.id).toEqual(user.id); + expect(state.auth.user.id).toEqual(user.id); }); it("should return error with invalid token", async () => { @@ -68,7 +68,7 @@ describe("Authentication middleware", () => { }, jest.fn() ); - expect(state.user.id).toEqual(user.id); + expect(state.auth.user.id).toEqual(user.id); }); it("should return error with invalid API key", async () => { const state = {} as DefaultState; @@ -133,7 +133,7 @@ describe("Authentication middleware", () => { }, jest.fn() ); - expect(state.user.id).toEqual(user.id); + expect(state.auth.user.id).toEqual(user.id); }); it("should allow passing auth token in body params", async () => { @@ -154,7 +154,7 @@ describe("Authentication middleware", () => { }, jest.fn() ); - expect(state.user.id).toEqual(user.id); + expect(state.auth.user.id).toEqual(user.id); }); it("should return an error for suspended users", async () => { diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index b0d5778533..278d89008a 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -5,13 +5,13 @@ import tracer, { getRootSpanFromRequestContext, } from "@server/logging/tracer"; import { User, Team, ApiKey } from "@server/models"; +import { AppContext, AuthenticationType } from "@server/types"; import { getUserForJWT } from "@server/utils/jwt"; import { AuthenticationError, AuthorizationError, UserSuspendedError, } from "../errors"; -import { ContextWithState, AuthenticationType } from "../types"; type AuthenticationOptions = { /* An admin user role is required to access the route */ @@ -26,7 +26,7 @@ type AuthenticationOptions = { }; export default function auth(options: AuthenticationOptions = {}) { - return async function authMiddleware(ctx: ContextWithState, next: Next) { + return async function authMiddleware(ctx: AppContext, next: Next) { let token; const authorizationHeader = ctx.request.get("authorization"); @@ -61,11 +61,12 @@ export default function auth(options: AuthenticationOptions = {}) { throw AuthenticationError("Authentication required"); } - let user: User | null | undefined; + let user: User | null; + let type: AuthenticationType; if (token) { if (ApiKey.match(String(token))) { - ctx.state.authType = AuthenticationType.API; + type = AuthenticationType.API; let apiKey; try { @@ -96,7 +97,7 @@ export default function auth(options: AuthenticationOptions = {}) { throw AuthenticationError("Invalid API key"); } } else { - ctx.state.authType = AuthenticationType.APP; + type = AuthenticationType.APP; user = await getUserForJWT(String(token)); } @@ -129,19 +130,24 @@ export default function auth(options: AuthenticationOptions = {}) { Logger.error("Failed to update user activeAt", err); }); - ctx.state.token = String(token); - ctx.state.user = user; + ctx.state.auth = { + user, + token: String(token), + type, + }; if (tracer) { addTags( { "request.userId": user.id, "request.teamId": user.teamId, - "request.authType": ctx.state.authType, + "request.authType": type, }, getRootSpanFromRequestContext(ctx) ); } + } else { + ctx.state.auth = {}; } return next(); diff --git a/server/middlewares/transaction.ts b/server/middlewares/transaction.ts index 9291b3e9dd..58ca1b434f 100644 --- a/server/middlewares/transaction.ts +++ b/server/middlewares/transaction.ts @@ -1,12 +1,7 @@ -import { Context, Next } from "koa"; +import { Next } from "koa"; import { Transaction } from "sequelize"; import { sequelize } from "@server/database/sequelize"; - -export type TransactionContext = Context & { - state: Context["state"] & { - transaction: Transaction; - }; -}; +import { AppContext } from "@server/types"; /** * Middleware that wraps a route in a database transaction, useful for mutations @@ -16,7 +11,7 @@ export type TransactionContext = Context & { * @returns The middleware function. */ export function transaction() { - return async function transactionMiddleware(ctx: Context, next: Next) { + return async function transactionMiddleware(ctx: AppContext, next: Next) { await sequelize.transaction(async (t: Transaction) => { ctx.state.transaction = t; return next(); diff --git a/server/routes/api/apiKeys.ts b/server/routes/api/apiKeys.ts index 31f4ffa5ff..7b96dea0d9 100644 --- a/server/routes/api/apiKeys.ts +++ b/server/routes/api/apiKeys.ts @@ -3,44 +3,49 @@ import auth from "@server/middlewares/authentication"; import { ApiKey, Event } from "@server/models"; import { authorize } from "@server/policies"; import { presentApiKey } from "@server/presenters"; +import { APIContext } from "@server/types"; import { assertUuid, assertPresent } from "@server/validation"; import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("apiKeys.create", auth({ member: true }), async (ctx) => { - const { name } = ctx.request.body; - assertPresent(name, "name is required"); - const { user } = ctx.state; +router.post( + "apiKeys.create", + auth({ member: true }), + async (ctx: APIContext) => { + const { name } = ctx.request.body; + assertPresent(name, "name is required"); + const { user } = ctx.state.auth; - authorize(user, "createApiKey", user.team); - const key = await ApiKey.create({ - name, - userId: user.id, - }); - - await Event.create({ - name: "api_keys.create", - modelId: key.id, - teamId: user.teamId, - actorId: user.id, - data: { + authorize(user, "createApiKey", user.team); + const key = await ApiKey.create({ name, - }, - ip: ctx.request.ip, - }); + userId: user.id, + }); - ctx.body = { - data: presentApiKey(key), - }; -}); + await Event.create({ + name: "api_keys.create", + modelId: key.id, + teamId: user.teamId, + actorId: user.id, + data: { + name, + }, + ip: ctx.request.ip, + }); + + ctx.body = { + data: presentApiKey(key), + }; + } +); router.post( "apiKeys.list", auth({ member: true }), pagination(), - async (ctx) => { - const { user } = ctx.state; + async (ctx: APIContext) => { + const { user } = ctx.state.auth; const keys = await ApiKey.findAll({ where: { userId: user.id, @@ -57,28 +62,32 @@ router.post( } ); -router.post("apiKeys.delete", auth({ member: true }), async (ctx) => { - const { id } = ctx.request.body; - assertUuid(id, "id is required"); - const { user } = ctx.state; - const key = await ApiKey.findByPk(id); - authorize(user, "delete", key); +router.post( + "apiKeys.delete", + auth({ member: true }), + async (ctx: APIContext) => { + const { id } = ctx.request.body; + assertUuid(id, "id is required"); + const { user } = ctx.state.auth; + const key = await ApiKey.findByPk(id); + authorize(user, "delete", key); - await key.destroy(); - await Event.create({ - name: "api_keys.delete", - modelId: key.id, - teamId: user.teamId, - actorId: user.id, - data: { - name: key.name, - }, - ip: ctx.request.ip, - }); + await key.destroy(); + await Event.create({ + name: "api_keys.delete", + modelId: key.id, + teamId: user.teamId, + actorId: user.id, + data: { + name: key.name, + }, + ip: ctx.request.ip, + }); - ctx.body = { - success: true, - }; -}); + ctx.body = { + success: true, + }; + } +); export default router; diff --git a/server/routes/api/attachments/attachments.ts b/server/routes/api/attachments/attachments.ts index d74e083d3c..9a4281abb7 100644 --- a/server/routes/api/attachments/attachments.ts +++ b/server/routes/api/attachments/attachments.ts @@ -11,7 +11,7 @@ import { Attachment, Document, Event } from "@server/models"; import AttachmentHelper from "@server/models/helpers/AttachmentHelper"; import { authorize } from "@server/policies"; import { presentAttachment } from "@server/presenters"; -import { APIContext, ContextWithState } from "@server/types"; +import { APIContext } from "@server/types"; import { getPresignedPost, publicS3Endpoint } from "@server/utils/s3"; import { assertIn, assertUuid } from "@server/validation"; import * as T from "./schema"; @@ -25,7 +25,8 @@ router.post( transaction(), async (ctx: APIContext) => { const { name, documentId, contentType, size, preset } = ctx.input; - const { user, transaction } = ctx.state; + const { auth, transaction } = ctx.state; + const { user } = auth; // All user types can upload an avatar so no additional authorization is needed. if (preset === AttachmentPreset.Avatar) { @@ -113,7 +114,7 @@ router.post( validate(T.AttachmentDeleteSchema), async (ctx: APIContext) => { const { id } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const attachment = await Attachment.findByPk(id, { rejectOnEmpty: true, }); @@ -140,11 +141,11 @@ router.post( } ); -const handleAttachmentsRedirect = async (ctx: ContextWithState) => { +const handleAttachmentsRedirect = async (ctx: APIContext) => { const id = ctx.request.body?.id ?? ctx.request.query?.id; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const attachment = await Attachment.findByPk(id, { rejectOnEmpty: true, }); diff --git a/server/routes/api/auth.ts b/server/routes/api/auth.ts index c6c9f2bdc3..72e7ec0e4d 100644 --- a/server/routes/api/auth.ts +++ b/server/routes/api/auth.ts @@ -4,10 +4,7 @@ import { TeamPreference } from "@shared/types"; import { parseDomain } from "@shared/utils/domains"; import env from "@server/env"; import auth from "@server/middlewares/authentication"; -import { - transaction, - TransactionContext, -} from "@server/middlewares/transaction"; +import { transaction } from "@server/middlewares/transaction"; import { Event, Team } from "@server/models"; import { presentUser, @@ -16,6 +13,7 @@ import { presentAvailableTeam, } from "@server/presenters"; import ValidateSSOAccessTask from "@server/queues/tasks/ValidateSSOAccessTask"; +import { APIContext } from "@server/types"; import { getSessionsInCookie } from "@server/utils/authentication"; import providers from "../auth/providers"; @@ -47,7 +45,7 @@ function filterProviders(team?: Team) { })); } -router.post("auth.config", async (ctx) => { +router.post("auth.config", async (ctx: APIContext) => { // If self hosted AND there is only one team then that team becomes the // brand for the knowledge base and it's guest signin option is used for the // root login page. @@ -124,8 +122,8 @@ router.post("auth.config", async (ctx) => { }; }); -router.post("auth.info", auth(), async (ctx) => { - const { user } = ctx.state; +router.post("auth.info", auth(), async (ctx: APIContext) => { + const { user } = ctx.state.auth; const sessions = getSessionsInCookie(ctx); const signedInTeamIds = Object.keys(sessions); @@ -163,34 +161,30 @@ router.post("auth.info", auth(), async (ctx) => { }; }); -router.post( - "auth.delete", - auth(), - transaction(), - async (ctx: TransactionContext) => { - const { user, transaction } = ctx.state; +router.post("auth.delete", auth(), transaction(), async (ctx: APIContext) => { + const { auth, transaction } = ctx.state; + const { user } = auth; - await user.rotateJwtSecret({ transaction }); - await Event.create( - { - name: "users.signout", - actorId: user.id, - userId: user.id, - teamId: user.teamId, - data: { - name: user.name, - }, - ip: ctx.request.ip, + await user.rotateJwtSecret({ transaction }); + await Event.create( + { + name: "users.signout", + actorId: user.id, + userId: user.id, + teamId: user.teamId, + data: { + name: user.name, }, - { - transaction, - } - ); + ip: ctx.request.ip, + }, + { + transaction, + } + ); - ctx.body = { - success: true, - }; - } -); + ctx.body = { + success: true, + }; +}); export default router; diff --git a/server/routes/api/authenticationProviders.ts b/server/routes/api/authenticationProviders.ts index ae3548e965..62b51d9e5f 100644 --- a/server/routes/api/authenticationProviders.ts +++ b/server/routes/api/authenticationProviders.ts @@ -7,6 +7,7 @@ import { presentAuthenticationProvider, presentPolicies, } from "@server/presenters"; +import { APIContext } from "@server/types"; import { assertUuid, assertPresent } from "@server/validation"; import allAuthenticationProviders from "../auth/providers"; @@ -15,11 +16,11 @@ const router = new Router(); router.post( "authenticationProviders.info", auth({ admin: true }), - async (ctx) => { + async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const authenticationProvider = await AuthenticationProvider.findByPk(id); authorize(user, "read", authenticationProvider); @@ -33,11 +34,11 @@ router.post( router.post( "authenticationProviders.update", auth({ admin: true }), - async (ctx) => { + async (ctx: APIContext) => { const { id, isEnabled } = ctx.request.body; assertUuid(id, "id is required"); assertPresent(isEnabled, "isEnabled is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const authenticationProvider = await sequelize.transaction( async (transaction) => { @@ -86,8 +87,8 @@ router.post( router.post( "authenticationProviders.list", auth({ admin: true }), - async (ctx) => { - const { user } = ctx.state; + async (ctx: APIContext) => { + const { user } = ctx.state.auth; authorize(user, "read", user.team); const teamAuthenticationProviders = (await user.team.$get( diff --git a/server/routes/api/collections.ts b/server/routes/api/collections.ts index 4299db2548..006da0b513 100644 --- a/server/routes/api/collections.ts +++ b/server/routes/api/collections.ts @@ -16,10 +16,7 @@ import { sequelize } from "@server/database/sequelize"; import { AuthorizationError, ValidationError } from "@server/errors"; import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; -import { - TransactionContext, - transaction, -} from "@server/middlewares/transaction"; +import { transaction } from "@server/middlewares/transaction"; import { Collection, CollectionUser, @@ -41,6 +38,7 @@ import { presentCollectionGroupMembership, presentFileOperation, } from "@server/presenters"; +import { APIContext } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { collectionIndexing } from "@server/utils/indexing"; import removeIndexCollision from "@server/utils/removeIndexCollision"; @@ -56,7 +54,7 @@ import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("collections.create", auth(), async (ctx) => { +router.post("collections.create", auth(), async (ctx: APIContext) => { const { name, color = randomElement(colorPalette), @@ -73,7 +71,7 @@ router.post("collections.create", auth(), async (ctx) => { assertHexColor(color, "Invalid hex value (please use format #FFFFFF)"); } - const { user } = ctx.state; + const { user } = ctx.state.auth; authorize(user, "createCollection", user.team); if (index) { @@ -134,10 +132,10 @@ router.post("collections.create", auth(), async (ctx) => { }; }); -router.post("collections.info", auth(), async (ctx) => { +router.post("collections.info", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; assertPresent(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const collection = await Collection.scope({ method: ["withMembership", user.id], }).findByPk(id); @@ -154,14 +152,14 @@ router.post( "collections.import", auth(), rateLimiter(RateLimiterStrategy.TenPerHour), - async (ctx) => { + async (ctx: APIContext) => { const { attachmentId, format = FileOperationFormat.MarkdownZip, } = ctx.request.body; assertUuid(attachmentId, "attachmentId is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; authorize(user, "importCollection", user.team); const attachment = await Attachment.findByPk(attachmentId); @@ -207,7 +205,7 @@ router.post( } ); -router.post("collections.add_group", auth(), async (ctx) => { +router.post("collections.add_group", auth(), async (ctx: APIContext) => { const { id, groupId, @@ -217,13 +215,15 @@ router.post("collections.add_group", auth(), async (ctx) => { assertUuid(groupId, "groupId is required"); assertCollectionPermission(permission); + const { user } = ctx.state.auth; + const collection = await Collection.scope({ - method: ["withMembership", ctx.state.user.id], + method: ["withMembership", user.id], }).findByPk(id); - authorize(ctx.state.user, "update", collection); + authorize(user, "update", collection); const group = await Group.findByPk(groupId); - authorize(ctx.state.user, "read", group); + authorize(user, "read", group); let membership = await CollectionGroup.findOne({ where: { @@ -237,7 +237,7 @@ router.post("collections.add_group", auth(), async (ctx) => { collectionId: id, groupId, permission, - createdById: ctx.state.user.id, + createdById: user.id, }); } else if (permission) { membership.permission = permission; @@ -248,7 +248,7 @@ router.post("collections.add_group", auth(), async (ctx) => { name: "collections.add_group", collectionId: collection.id, teamId: collection.teamId, - actorId: ctx.state.user.id, + actorId: user.id, modelId: groupId, data: { name: group.name, @@ -265,25 +265,27 @@ router.post("collections.add_group", auth(), async (ctx) => { }; }); -router.post("collections.remove_group", auth(), async (ctx) => { +router.post("collections.remove_group", auth(), async (ctx: APIContext) => { const { id, groupId } = ctx.request.body; assertUuid(id, "id is required"); assertUuid(groupId, "groupId is required"); + const { user } = ctx.state.auth; + const collection = await Collection.scope({ - method: ["withMembership", ctx.state.user.id], + method: ["withMembership", user.id], }).findByPk(id); - authorize(ctx.state.user, "update", collection); + authorize(user, "update", collection); const group = await Group.findByPk(groupId); - authorize(ctx.state.user, "read", group); + authorize(user, "read", group); await collection.$remove("group", group); await Event.create({ name: "collections.remove_group", collectionId: collection.id, teamId: collection.teamId, - actorId: ctx.state.user.id, + actorId: user.id, modelId: groupId, data: { name: group.name, @@ -300,10 +302,10 @@ router.post( "collections.group_memberships", auth(), pagination(), - async (ctx) => { + async (ctx: APIContext) => { const { id, query, permission } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const collection = await Collection.scope({ method: ["withMembership", user.id], @@ -365,19 +367,20 @@ router.post( "collections.add_user", auth(), transaction(), - async (ctx: TransactionContext) => { - const { transaction } = ctx.state; + async (ctx: APIContext) => { + const { auth, transaction } = ctx.state; + const actor = auth.user; const { id, userId, permission } = ctx.request.body; assertUuid(id, "id is required"); assertUuid(userId, "userId is required"); const collection = await Collection.scope({ - method: ["withMembership", ctx.state.user.id], + method: ["withMembership", actor.id], }).findByPk(id); - authorize(ctx.state.user, "update", collection); + authorize(actor, "update", collection); const user = await User.findByPk(userId); - authorize(ctx.state.user, "read", user); + authorize(actor, "read", user); let membership = await CollectionUser.findOne({ where: { @@ -388,7 +391,7 @@ router.post( lock: transaction.LOCK.UPDATE, }); - if (userId === ctx.state.user.id) { + if (userId === actor.id) { throw AuthorizationError("You cannot add yourself to a collection"); } @@ -402,7 +405,7 @@ router.post( collectionId: id, userId, permission: permission || user.defaultCollectionPermission, - createdById: ctx.state.user.id, + createdById: actor.id, }, { transaction, @@ -419,7 +422,7 @@ router.post( userId, collectionId: collection.id, teamId: collection.teamId, - actorId: ctx.state.user.id, + actorId: actor.id, data: { name: user.name, }, @@ -443,19 +446,20 @@ router.post( "collections.remove_user", auth(), transaction(), - async (ctx: TransactionContext) => { - const { transaction } = ctx.state; + async (ctx: APIContext) => { + const { auth, transaction } = ctx.state; + const actor = auth.user; const { id, userId } = ctx.request.body; assertUuid(id, "id is required"); assertUuid(userId, "userId is required"); const collection = await Collection.scope({ - method: ["withMembership", ctx.state.user.id], + method: ["withMembership", actor.id], }).findByPk(id); - authorize(ctx.state.user, "update", collection); + authorize(actor, "update", collection); const user = await User.findByPk(userId); - authorize(ctx.state.user, "read", user); + authorize(actor, "read", user); await collection.$remove("user", user, { transaction }); await Event.create( @@ -464,7 +468,7 @@ router.post( userId, collectionId: collection.id, teamId: collection.teamId, - actorId: ctx.state.user.id, + actorId: actor.id, data: { name: user.name, }, @@ -479,77 +483,82 @@ router.post( } ); -router.post("collections.memberships", auth(), pagination(), async (ctx) => { - const { id, query, permission } = ctx.request.body; - assertUuid(id, "id is required"); - const { user } = ctx.state; +router.post( + "collections.memberships", + auth(), + pagination(), + async (ctx: APIContext) => { + const { id, query, permission } = ctx.request.body; + assertUuid(id, "id is required"); + const { user } = ctx.state.auth; - const collection = await Collection.scope({ - method: ["withMembership", user.id], - }).findByPk(id); - authorize(user, "read", collection); + const collection = await Collection.scope({ + method: ["withMembership", user.id], + }).findByPk(id); + authorize(user, "read", collection); - let where: WhereOptions = { - collectionId: id, - }; - let userWhere; + let where: WhereOptions = { + collectionId: id, + }; + let userWhere; - if (query) { - userWhere = { - name: { - [Op.iLike]: `%${query}%`, + if (query) { + userWhere = { + name: { + [Op.iLike]: `%${query}%`, + }, + }; + } + + if (permission) { + assertCollectionPermission(permission); + where = { ...where, permission }; + } + + const options = { + where, + include: [ + { + model: User, + as: "user", + where: userWhere, + required: true, + }, + ], + }; + + const [total, memberships] = await Promise.all([ + CollectionUser.count(options), + CollectionUser.findAll({ + ...options, + order: [["createdAt", "DESC"]], + offset: ctx.state.pagination.offset, + limit: ctx.state.pagination.limit, + }), + ]); + + ctx.body = { + pagination: { ...ctx.state.pagination, total }, + data: { + memberships: memberships.map(presentMembership), + users: memberships.map((membership) => presentUser(membership.user)), }, }; } - - if (permission) { - assertCollectionPermission(permission); - where = { ...where, permission }; - } - - const options = { - where, - include: [ - { - model: User, - as: "user", - where: userWhere, - required: true, - }, - ], - }; - - const [total, memberships] = await Promise.all([ - CollectionUser.count(options), - CollectionUser.findAll({ - ...options, - order: [["createdAt", "DESC"]], - offset: ctx.state.pagination.offset, - limit: ctx.state.pagination.limit, - }), - ]); - - ctx.body = { - pagination: { ...ctx.state.pagination, total }, - data: { - memberships: memberships.map(presentMembership), - users: memberships.map((membership) => presentUser(membership.user)), - }, - }; -}); +); router.post( "collections.export", auth(), rateLimiter(RateLimiterStrategy.TenPerHour), - async (ctx) => { + async (ctx: APIContext) => { const { id } = ctx.request.body; const { format = FileOperationFormat.MarkdownZip } = ctx.request.body; assertUuid(id, "id is required"); assertIn(format, Object.values(FileOperationFormat), "Invalid format"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const team = await Team.findByPk(user.teamId); authorize(user, "createExport", team); @@ -582,9 +591,9 @@ router.post( "collections.export_all", auth(), rateLimiter(RateLimiterStrategy.FivePerHour), - async (ctx) => { + async (ctx: APIContext) => { const { format = FileOperationFormat.MarkdownZip } = ctx.request.body; - const { user } = ctx.state; + const { user } = ctx.state.auth; const team = await Team.findByPk(user.teamId); authorize(user, "createExport", team); @@ -609,7 +618,7 @@ router.post( } ); -router.post("collections.update", auth(), async (ctx) => { +router.post("collections.update", auth(), async (ctx: APIContext) => { const { id, name, @@ -625,7 +634,7 @@ router.post("collections.update", auth(), async (ctx) => { assertHexColor(color, "Invalid hex value (please use format #FFFFFF)"); } - const { user } = ctx.state; + const { user } = ctx.state.auth; const collection = await Collection.scope({ method: ["withMembership", user.id], }).findByPk(id); @@ -736,43 +745,48 @@ router.post("collections.update", auth(), async (ctx) => { }; }); -router.post("collections.list", auth(), pagination(), async (ctx) => { - const { user } = ctx.state; - const collectionIds = await user.collectionIds(); - const where: WhereOptions = { - teamId: user.teamId, - id: collectionIds, - }; - const collections = await Collection.scope({ - method: ["withMembership", user.id], - }).findAll({ - where, - order: [["updatedAt", "DESC"]], - offset: ctx.state.pagination.offset, - limit: ctx.state.pagination.limit, - }); - - const nullIndex = collections.findIndex( - (collection) => collection.index === null - ); - - if (nullIndex !== -1) { - const indexedCollections = await collectionIndexing(user.teamId); - collections.forEach((collection) => { - collection.index = indexedCollections[collection.id]; +router.post( + "collections.list", + auth(), + pagination(), + async (ctx: APIContext) => { + const { user } = ctx.state.auth; + const collectionIds = await user.collectionIds(); + const where: WhereOptions = { + teamId: user.teamId, + id: collectionIds, + }; + const collections = await Collection.scope({ + method: ["withMembership", user.id], + }).findAll({ + where, + order: [["updatedAt", "DESC"]], + offset: ctx.state.pagination.offset, + limit: ctx.state.pagination.limit, }); + + const nullIndex = collections.findIndex( + (collection) => collection.index === null + ); + + if (nullIndex !== -1) { + const indexedCollections = await collectionIndexing(user.teamId); + collections.forEach((collection) => { + collection.index = indexedCollections[collection.id]; + }); + } + + ctx.body = { + pagination: ctx.state.pagination, + data: collections.map(presentCollection), + policies: presentPolicies(user, collections), + }; } +); - ctx.body = { - pagination: ctx.state.pagination, - data: collections.map(presentCollection), - policies: presentPolicies(user, collections), - }; -}); - -router.post("collections.delete", auth(), async (ctx) => { +router.post("collections.delete", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; - const { user } = ctx.state; + const { user } = ctx.state.auth; assertUuid(id, "id is required"); const collection = await Collection.scope({ @@ -814,13 +828,13 @@ router.post("collections.delete", auth(), async (ctx) => { }; }); -router.post("collections.move", auth(), async (ctx) => { +router.post("collections.move", auth(), async (ctx: APIContext) => { const id = ctx.request.body.id; let index = ctx.request.body.index; assertPresent(index, "index is required"); assertIndexCharacters(index); assertUuid(id, "id must be a uuid"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const collection = await Collection.findByPk(id); authorize(user, "move", collection); diff --git a/server/routes/api/developer.ts b/server/routes/api/developer.ts index ebd5bfa0c0..4c1ea0b5cc 100644 --- a/server/routes/api/developer.ts +++ b/server/routes/api/developer.ts @@ -6,6 +6,7 @@ import env from "@server/env"; import Logger from "@server/logging/Logger"; import auth from "@server/middlewares/authentication"; import { presentUser } from "@server/presenters"; +import { APIContext } from "@server/types"; const router = new Router(); @@ -19,40 +20,45 @@ function dev() { }; } -router.post("developer.create_test_users", dev(), auth(), async (ctx) => { - const { count = 10 } = ctx.request.body; - const { user } = ctx.state; - const invites = Array(Math.min(count, 100)) - .fill(0) - .map(() => { - const rando = randomstring.generate(10); +router.post( + "developer.create_test_users", + dev(), + auth(), + async (ctx: APIContext) => { + const { count = 10 } = ctx.request.body; + const { user } = ctx.state.auth; + const invites = Array(Math.min(count, 100)) + .fill(0) + .map(() => { + const rando = randomstring.generate(10); - return { - email: `${rando}@example.com`, - name: `${rando.slice(0, 5)} Tester`, - role: "member", - } as Invite; + return { + email: `${rando}@example.com`, + name: `${rando.slice(0, 5)} Tester`, + role: "member", + } as Invite; + }); + + Logger.info("utils", `Creating ${count} test users`, invites); + + // Generate a bunch of invites + const response = await userInviter({ + user, + invites, + ip: ctx.request.ip, }); - Logger.info("utils", `Creating ${count} test users`, invites); + // Convert from invites to active users by marking as active + await Promise.all( + response.users.map((user) => user.updateActiveAt(ctx, true)) + ); - // Generate a bunch of invites - const response = await userInviter({ - user, - invites, - ip: ctx.request.ip, - }); - - // Convert from invites to active users by marking as active - await Promise.all( - response.users.map((user) => user.updateActiveAt(ctx, true)) - ); - - ctx.body = { - data: { - users: response.users.map((user) => presentUser(user)), - }, - }; -}); + ctx.body = { + data: { + users: response.users.map((user) => presentUser(user)), + }, + }; + } +); export default router; diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index d3cd1e745d..75e8da8e0b 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -70,7 +70,7 @@ router.post( } = ctx.input; // always filter by the current team - const { user } = ctx.state; + const { user } = ctx.state.auth; let where: WhereOptions = { teamId: user.teamId, archivedAt: { @@ -177,7 +177,7 @@ router.post( validate(T.DocumentsArchivedSchema), async (ctx: APIContext) => { const { sort, direction } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const collectionIds = await user.collectionIds(); const collectionScope: Readonly = { method: ["withCollectionPermissions", user.id], @@ -221,7 +221,7 @@ router.post( validate(T.DocumentsDeletedSchema), async (ctx: APIContext) => { const { sort, direction } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const collectionIds = await user.collectionIds({ paranoid: false, }); @@ -281,7 +281,7 @@ router.post( validate(T.DocumentsViewedSchema), async (ctx: APIContext) => { const { sort, direction } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const collectionIds = await user.collectionIds(); const userId = user.id; const views = await View.findAll({ @@ -334,7 +334,7 @@ router.post( validate(T.DocumentsDraftsSchema), async (ctx: APIContext) => { const { collectionId, dateFilter, direction, sort } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; if (collectionId) { const collection = await Collection.scope({ @@ -397,7 +397,7 @@ router.post( validate(T.DocumentsInfoSchema), async (ctx: APIContext) => { const { id, shareId, apiVersion } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const teamFromCtx = await getTeamFromContext(ctx); const { document, share, collection } = await documentLoader({ id, @@ -443,7 +443,7 @@ router.post( validate(T.DocumentsExportSchema), async (ctx: APIContext) => { const { id } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const accept = ctx.request.headers["accept"]; const { document } = await documentLoader({ @@ -495,7 +495,7 @@ router.post( validate(T.DocumentsRestoreSchema), async (ctx: APIContext) => { const { id, collectionId, revisionId } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const document = await Document.findByPk(id, { userId: user.id, paranoid: false, @@ -606,7 +606,7 @@ router.post( userId, } = ctx.input; const { offset, limit } = ctx.state.pagination; - const { user } = ctx.state; + const { user } = ctx.state.auth; let collaboratorIds = undefined; if (collectionId) { @@ -663,9 +663,8 @@ router.post( } = ctx.input; const { offset, limit } = ctx.state.pagination; - // this typing is a bit ugly, would be better to use a type like ContextWithState - // but that doesn't adequately handle cases when auth is optional - const { user }: { user: User | undefined } = ctx.state; + // Unfortunately, this still doesn't adequately handle cases when auth is optional + const { user } = ctx.state.auth; let teamId; let response; @@ -747,7 +746,7 @@ router.post( userId: user?.id, teamId, shareId, - source: ctx.state.authType || "app", // we'll consider anything that isn't "api" to be "app" + source: ctx.state.auth.type || "app", // we'll consider anything that isn't "api" to be "app" query, results: totalCount, }); @@ -767,7 +766,7 @@ router.post( validate(T.DocumentsTemplatizeSchema), async (ctx: APIContext) => { const { id } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const original = await Document.findByPk(id, { userId: user.id, @@ -829,7 +828,7 @@ router.post( append, } = ctx.input; const editorVersion = ctx.headers["x-editor-version"] as string | undefined; - const { user } = ctx.state; + const { user } = ctx.state.auth; let collection: Collection | null | undefined; const document = await Document.findByPk(id, { @@ -889,7 +888,7 @@ router.post( validate(T.DocumentsMoveSchema), async (ctx: APIContext) => { const { id, collectionId, parentDocumentId, index } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const document = await Document.findByPk(id, { userId: user.id, }); @@ -943,7 +942,7 @@ router.post( validate(T.DocumentsArchiveSchema), async (ctx: APIContext) => { const { id } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -976,7 +975,7 @@ router.post( validate(T.DocumentsDeleteSchema), async (ctx: APIContext) => { const { id, permanent } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; if (permanent) { const document = await Document.findByPk(id, { @@ -1041,7 +1040,7 @@ router.post( validate(T.DocumentsUnpublishSchema), async (ctx: APIContext) => { const { id } = ctx.input; - const { user } = ctx.state; + const { user } = ctx.state.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -1103,7 +1102,7 @@ router.post( ); } - const { user } = ctx.state; + const { user } = ctx.state.auth; const collection = await Collection.scope({ method: ["withMembership", user.id], @@ -1177,7 +1176,7 @@ router.post( } = ctx.input; const editorVersion = ctx.headers["x-editor-version"] as string | undefined; - const { user } = ctx.state; + const { user } = ctx.state.auth; let collection; diff --git a/server/routes/api/events/events.ts b/server/routes/api/events/events.ts index 089c89f9b3..e66af05281 100644 --- a/server/routes/api/events/events.ts +++ b/server/routes/api/events/events.ts @@ -17,7 +17,7 @@ router.post( pagination(), validate(T.EventsListSchema), async (ctx: APIContext) => { - const { user } = ctx.state; + const { user } = ctx.state.auth; const { sort, direction, diff --git a/server/routes/api/fileOperations.ts b/server/routes/api/fileOperations.ts index e522e683d6..3143d84bcb 100644 --- a/server/routes/api/fileOperations.ts +++ b/server/routes/api/fileOperations.ts @@ -7,33 +7,37 @@ import auth from "@server/middlewares/authentication"; import { FileOperation, Team } from "@server/models"; import { authorize } from "@server/policies"; import { presentFileOperation } from "@server/presenters"; -import { ContextWithState } from "@server/types"; +import { APIContext } from "@server/types"; import { getSignedUrl } from "@server/utils/s3"; import { assertIn, assertSort, assertUuid } from "@server/validation"; import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("fileOperations.info", auth({ admin: true }), async (ctx) => { - const { id } = ctx.request.body; - assertUuid(id, "id is required"); - const { user } = ctx.state; - const fileOperation = await FileOperation.findByPk(id, { - rejectOnEmpty: true, - }); +router.post( + "fileOperations.info", + auth({ admin: true }), + async (ctx: APIContext) => { + const { id } = ctx.request.body; + assertUuid(id, "id is required"); + const { user } = ctx.state.auth; + const fileOperation = await FileOperation.findByPk(id, { + rejectOnEmpty: true, + }); - authorize(user, "read", fileOperation); + authorize(user, "read", fileOperation); - ctx.body = { - data: presentFileOperation(fileOperation), - }; -}); + ctx.body = { + data: presentFileOperation(fileOperation), + }; + } +); router.post( "fileOperations.list", auth({ admin: true }), pagination(), - async (ctx) => { + async (ctx: APIContext) => { let { direction } = ctx.request.body; const { sort = "createdAt", type } = ctx.request.body; assertIn(type, Object.values(FileOperationType)); @@ -42,7 +46,7 @@ router.post( if (direction !== "ASC") { direction = "DESC"; } - const { user } = ctx.state; + const { user } = ctx.state.auth; const where: WhereOptions = { teamId: user.teamId, type, @@ -69,11 +73,11 @@ router.post( } ); -const handleFileOperationsRedirect = async (ctx: ContextWithState) => { +const handleFileOperationsRedirect = async (ctx: APIContext) => { const id = ctx.request.body?.id ?? ctx.request.query?.id; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const fileOperation = await FileOperation.unscoped().findByPk(id, { rejectOnEmpty: true, }); @@ -98,21 +102,25 @@ router.post( handleFileOperationsRedirect ); -router.post("fileOperations.delete", auth({ admin: true }), async (ctx) => { - const { id } = ctx.request.body; - assertUuid(id, "id is required"); +router.post( + "fileOperations.delete", + auth({ admin: true }), + async (ctx: APIContext) => { + const { id } = ctx.request.body; + assertUuid(id, "id is required"); - const { user } = ctx.state; - const fileOperation = await FileOperation.unscoped().findByPk(id, { - rejectOnEmpty: true, - }); - authorize(user, "delete", fileOperation); + const { user } = ctx.state.auth; + const fileOperation = await FileOperation.unscoped().findByPk(id, { + rejectOnEmpty: true, + }); + authorize(user, "delete", fileOperation); - await fileOperationDeleter(fileOperation, user, ctx.request.ip); + await fileOperationDeleter(fileOperation, user, ctx.request.ip); - ctx.body = { - success: true, - }; -}); + ctx.body = { + success: true, + }; + } +); export default router; diff --git a/server/routes/api/groups.ts b/server/routes/api/groups.ts index 1fdbdc6fca..3ec9236736 100644 --- a/server/routes/api/groups.ts +++ b/server/routes/api/groups.ts @@ -10,12 +10,13 @@ import { presentUser, presentGroupMembership, } from "@server/presenters"; +import { APIContext } from "@server/types"; import { assertPresent, assertUuid, assertSort } from "@server/validation"; import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("groups.list", auth(), pagination(), async (ctx) => { +router.post("groups.list", auth(), pagination(), async (ctx: APIContext) => { let { direction } = ctx.request.body; const { sort = "updatedAt" } = ctx.request.body; if (direction !== "ASC") { @@ -23,7 +24,7 @@ router.post("groups.list", auth(), pagination(), async (ctx) => { } assertSort(sort, Group); - const { user } = ctx.state; + const { user } = ctx.state.auth; const groups = await Group.findAll({ where: { teamId: user.teamId, @@ -52,11 +53,11 @@ router.post("groups.list", auth(), pagination(), async (ctx) => { }; }); -router.post("groups.info", auth(), async (ctx) => { +router.post("groups.info", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const group = await Group.findByPk(id); authorize(user, "read", group); @@ -66,11 +67,11 @@ router.post("groups.info", auth(), async (ctx) => { }; }); -router.post("groups.create", auth(), async (ctx) => { +router.post("groups.create", auth(), async (ctx: APIContext) => { const { name } = ctx.request.body; assertPresent(name, "name is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; authorize(user, "createGroup", user.team); const g = await Group.create({ name, @@ -98,12 +99,12 @@ router.post("groups.create", auth(), async (ctx) => { }; }); -router.post("groups.update", auth(), async (ctx) => { +router.post("groups.update", auth(), async (ctx: APIContext) => { const { id, name } = ctx.request.body; assertPresent(name, "name is required"); assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const group = await Group.findByPk(id); authorize(user, "update", group); @@ -129,11 +130,11 @@ router.post("groups.update", auth(), async (ctx) => { }; }); -router.post("groups.delete", auth(), async (ctx) => { +router.post("groups.delete", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const group = await Group.findByPk(id); authorize(user, "delete", group); @@ -154,61 +155,68 @@ router.post("groups.delete", auth(), async (ctx) => { }; }); -router.post("groups.memberships", auth(), pagination(), async (ctx) => { - const { id, query } = ctx.request.body; - assertUuid(id, "id is required"); +router.post( + "groups.memberships", + auth(), + pagination(), + async (ctx: APIContext) => { + const { id, query } = ctx.request.body; + assertUuid(id, "id is required"); - const { user } = ctx.state; - const group = await Group.findByPk(id); - authorize(user, "read", group); - let userWhere; + const { user } = ctx.state.auth; + const group = await Group.findByPk(id); + authorize(user, "read", group); + let userWhere; - if (query) { - userWhere = { - name: { - [Op.iLike]: `%${query}%`, + if (query) { + userWhere = { + name: { + [Op.iLike]: `%${query}%`, + }, + }; + } + + const memberships = await GroupUser.findAll({ + where: { + groupId: id, + }, + order: [["createdAt", "DESC"]], + offset: ctx.state.pagination.offset, + limit: ctx.state.pagination.limit, + include: [ + { + model: User, + as: "user", + where: userWhere, + required: true, + }, + ], + }); + + ctx.body = { + pagination: ctx.state.pagination, + data: { + groupMemberships: memberships.map((membership) => + presentGroupMembership(membership, { includeUser: true }) + ), + users: memberships.map((membership) => presentUser(membership.user)), }, }; } +); - const memberships = await GroupUser.findAll({ - where: { - groupId: id, - }, - order: [["createdAt", "DESC"]], - offset: ctx.state.pagination.offset, - limit: ctx.state.pagination.limit, - include: [ - { - model: User, - as: "user", - where: userWhere, - required: true, - }, - ], - }); - - ctx.body = { - pagination: ctx.state.pagination, - data: { - groupMemberships: memberships.map((membership) => - presentGroupMembership(membership, { includeUser: true }) - ), - users: memberships.map((membership) => presentUser(membership.user)), - }, - }; -}); - -router.post("groups.add_user", auth(), async (ctx) => { +router.post("groups.add_user", auth(), async (ctx: APIContext) => { const { id, userId } = ctx.request.body; assertUuid(id, "id is required"); assertUuid(userId, "userId is required"); + const actor = ctx.state.auth.user; + const user = await User.findByPk(userId); - authorize(ctx.state.user, "read", user); + authorize(actor, "read", user); let group = await Group.findByPk(id); - authorize(ctx.state.user, "update", group); + authorize(actor, "update", group); let membership = await GroupUser.findOne({ where: { @@ -220,7 +228,7 @@ router.post("groups.add_user", auth(), async (ctx) => { if (!membership) { await group.$add("user", user, { through: { - createdById: ctx.state.user.id, + createdById: actor.id, }, }); // reload to get default scope @@ -240,7 +248,7 @@ router.post("groups.add_user", auth(), async (ctx) => { userId, teamId: user.teamId, modelId: group.id, - actorId: ctx.state.user.id, + actorId: actor.id, data: { name: user.name, }, @@ -259,16 +267,18 @@ router.post("groups.add_user", auth(), async (ctx) => { }; }); -router.post("groups.remove_user", auth(), async (ctx) => { +router.post("groups.remove_user", auth(), async (ctx: APIContext) => { const { id, userId } = ctx.request.body; assertUuid(id, "id is required"); assertUuid(userId, "userId is required"); + const actor = ctx.state.auth.user; + let group = await Group.findByPk(id); - authorize(ctx.state.user, "update", group); + authorize(actor, "update", group); const user = await User.findByPk(userId); - authorize(ctx.state.user, "read", user); + authorize(actor, "read", user); await group.$remove("user", user); await Event.create({ @@ -276,7 +286,7 @@ router.post("groups.remove_user", auth(), async (ctx) => { userId, modelId: group.id, teamId: user.teamId, - actorId: ctx.state.user.id, + actorId: actor.id, data: { name: user.name, }, diff --git a/server/routes/api/hooks.ts b/server/routes/api/hooks.ts index d74900c775..6945d41978 100644 --- a/server/routes/api/hooks.ts +++ b/server/routes/api/hooks.ts @@ -17,6 +17,7 @@ import { } from "@server/models"; import SearchHelper from "@server/models/helpers/SearchHelper"; import { presentSlackAttachment } from "@server/presenters"; +import { APIContext } from "@server/types"; import * as Slack from "@server/utils/slack"; import { assertPresent } from "@server/validation"; @@ -41,7 +42,7 @@ function verifySlackToken(token: string) { } // triggered by a user posting a getoutline.com link in Slack -router.post("hooks.unfurl", async (ctx) => { +router.post("hooks.unfurl", async (ctx: APIContext) => { const { challenge, token, event } = ctx.request.body; if (challenge) { return (ctx.body = ctx.request.body.challenge); @@ -104,7 +105,7 @@ router.post("hooks.unfurl", async (ctx) => { }); // triggered by interactions with actions, dialogs, message buttons in Slack -router.post("hooks.interactive", async (ctx) => { +router.post("hooks.interactive", async (ctx: APIContext) => { const { payload } = ctx.request.body; assertPresent(payload, "payload is required"); @@ -142,7 +143,7 @@ router.post("hooks.interactive", async (ctx) => { }); // triggered by the /outline command in Slack -router.post("hooks.slack", async (ctx) => { +router.post("hooks.slack", async (ctx: APIContext) => { const { token, team_id, user_id, text = "" } = ctx.request.body; assertPresent(token, "token is required"); assertPresent(team_id, "team_id is required"); diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index 69eabb8bb5..ab53c7426d 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -1,10 +1,10 @@ -import Koa, { BaseContext, DefaultContext, DefaultState } from "koa"; +import Koa, { BaseContext } from "koa"; import bodyParser from "koa-body"; import Router from "koa-router"; import userAgent, { UserAgentContext } from "koa-useragent"; import env from "@server/env"; import { NotFoundError } from "@server/errors"; -import { AuthenticatedState } from "@server/types"; +import { AppState, AppContext } from "@server/types"; import apiKeys from "./apiKeys"; import attachments from "./attachments"; import auth from "./auth"; @@ -32,10 +32,7 @@ import users from "./users"; import views from "./views"; import webhookSubscriptions from "./webhookSubscriptions"; -const api = new Koa< - DefaultState & AuthenticatedState, - DefaultContext & { body: Record } ->(); +const api = new Koa(); const router = new Router(); // middlewares diff --git a/server/routes/api/integrations.ts b/server/routes/api/integrations.ts index bfa521abd1..b3c3314077 100644 --- a/server/routes/api/integrations.ts +++ b/server/routes/api/integrations.ts @@ -9,6 +9,7 @@ import Integration, { } from "@server/models/Integration"; import { authorize } from "@server/policies"; import { presentIntegration } from "@server/presenters"; +import { APIContext } from "@server/types"; import { assertSort, assertUuid, @@ -20,116 +21,133 @@ import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("integrations.list", auth(), pagination(), async (ctx) => { - let { direction } = ctx.request.body; - const { user } = ctx.state; - const { type, sort = "updatedAt" } = ctx.request.body; - if (direction !== "ASC") { - direction = "DESC"; - } - assertSort(sort, Integration); +router.post( + "integrations.list", + auth(), + pagination(), + async (ctx: APIContext) => { + let { direction } = ctx.request.body; + const { user } = ctx.state.auth; + const { type, sort = "updatedAt" } = ctx.request.body; + if (direction !== "ASC") { + direction = "DESC"; + } + assertSort(sort, Integration); - let where: WhereOptions = { - teamId: user.teamId, - }; + let where: WhereOptions = { + teamId: user.teamId, + }; - if (type) { - assertIn(type, Object.values(IntegrationType)); - where = { - ...where, - type, + if (type) { + assertIn(type, Object.values(IntegrationType)); + where = { + ...where, + type, + }; + } + + const integrations = await Integration.findAll({ + where, + order: [[sort, direction]], + offset: ctx.state.pagination.offset, + limit: ctx.state.pagination.limit, + }); + + ctx.body = { + pagination: ctx.state.pagination, + data: integrations.map(presentIntegration), }; } +); - const integrations = await Integration.findAll({ - where, - order: [[sort, direction]], - offset: ctx.state.pagination.offset, - limit: ctx.state.pagination.limit, - }); +router.post( + "integrations.create", + auth({ admin: true }), + async (ctx: APIContext) => { + const { type, service, settings } = ctx.request.body; - ctx.body = { - pagination: ctx.state.pagination, - data: integrations.map(presentIntegration), - }; -}); + assertIn(type, Object.values(IntegrationType)); -router.post("integrations.create", auth({ admin: true }), async (ctx) => { - const { type, service, settings } = ctx.request.body; + const { user } = ctx.state.auth; + authorize(user, "createIntegration", user.team); - assertIn(type, Object.values(IntegrationType)); + assertIn(service, Object.values(UserCreatableIntegrationService)); - const { user } = ctx.state; - authorize(user, "createIntegration", user.team); + if (has(settings, "url")) { + assertUrl(settings.url); + } - assertIn(service, Object.values(UserCreatableIntegrationService)); + const integration = await Integration.create({ + userId: user.id, + teamId: user.teamId, + service, + settings, + type, + }); - if (has(settings, "url")) { - assertUrl(settings.url); + ctx.body = { + data: presentIntegration(integration), + }; } +); - const integration = await Integration.create({ - userId: user.id, - teamId: user.teamId, - service, - settings, - type, - }); +router.post( + "integrations.update", + auth({ admin: true }), + async (ctx: APIContext) => { + const { id, events = [], settings } = ctx.request.body; + assertUuid(id, "id is required"); - ctx.body = { - data: presentIntegration(integration), - }; -}); + const { user } = ctx.state.auth; + const integration = await Integration.findByPk(id); + authorize(user, "update", integration); -router.post("integrations.update", auth({ admin: true }), async (ctx) => { - const { id, events = [], settings } = ctx.request.body; - assertUuid(id, "id is required"); + assertArray(events, "events must be an array"); - const { user } = ctx.state; - const integration = await Integration.findByPk(id); - authorize(user, "update", integration); + if (has(settings, "url")) { + assertUrl(settings.url); + } - assertArray(events, "events must be an array"); + if (integration.type === IntegrationType.Post) { + integration.events = events.filter((event: string) => + ["documents.update", "documents.publish"].includes(event) + ); + } - if (has(settings, "url")) { - assertUrl(settings.url); + integration.settings = settings; + + await integration.save(); + + ctx.body = { + data: presentIntegration(integration), + }; } +); - if (integration.type === IntegrationType.Post) { - integration.events = events.filter((event: string) => - ["documents.update", "documents.publish"].includes(event) - ); +router.post( + "integrations.delete", + auth({ admin: true }), + async (ctx: APIContext) => { + const { id } = ctx.request.body; + assertUuid(id, "id is required"); + + const { user } = ctx.state.auth; + const integration = await Integration.findByPk(id); + authorize(user, "delete", integration); + + await integration.destroy(); + await Event.create({ + name: "integrations.delete", + modelId: integration.id, + teamId: integration.teamId, + actorId: user.id, + ip: ctx.request.ip, + }); + + ctx.body = { + success: true, + }; } - - integration.settings = settings; - - await integration.save(); - - ctx.body = { - data: presentIntegration(integration), - }; -}); - -router.post("integrations.delete", auth({ admin: true }), async (ctx) => { - const { id } = ctx.request.body; - assertUuid(id, "id is required"); - - const { user } = ctx.state; - const integration = await Integration.findByPk(id); - authorize(user, "delete", integration); - - await integration.destroy(); - await Event.create({ - name: "integrations.delete", - modelId: integration.id, - teamId: integration.teamId, - actorId: user.id, - ip: ctx.request.ip, - }); - - ctx.body = { - success: true, - }; -}); +); export default router; diff --git a/server/routes/api/middlewares/pagination.ts b/server/routes/api/middlewares/pagination.ts index 201b95d4ce..b2dba45608 100644 --- a/server/routes/api/middlewares/pagination.ts +++ b/server/routes/api/middlewares/pagination.ts @@ -1,14 +1,14 @@ import querystring from "querystring"; -import { Context, Next } from "koa"; +import { Next } from "koa"; import { InvalidRequestError } from "@server/errors"; +import { AppContext } from "@server/types"; -export default function pagination(options?: Record) { - return async function paginationMiddleware(ctx: Context, next: Next) { +export default function pagination() { + return async function paginationMiddleware(ctx: AppContext, next: Next) { const opts = { defaultLimit: 15, defaultOffset: 0, maxLimit: 100, - ...options, }; const query = ctx.request.query; const body = ctx.request.body; @@ -42,18 +42,15 @@ export default function pagination(options?: Record) { ); } + query.limit = String(limit); + query.offset = String(limit + offset); + ctx.state.pagination = { limit, offset, + nextPath: `/api${ctx.request.path}?${querystring.stringify(query)}`, }; - query.limit = ctx.state.pagination.limit; - query.offset = ctx.state.pagination.offset + query.limit; - - ctx.state.pagination.nextPath = `/api${ - ctx.request.path - }?${querystring.stringify(query)}`; - return next(); }; } diff --git a/server/routes/api/notificationSettings.ts b/server/routes/api/notificationSettings.ts index 5b0c5726fa..f176a88ac7 100644 --- a/server/routes/api/notificationSettings.ts +++ b/server/routes/api/notificationSettings.ts @@ -4,16 +4,16 @@ import auth from "@server/middlewares/authentication"; import { Team, NotificationSetting } from "@server/models"; import { authorize } from "@server/policies"; import { presentNotificationSetting } from "@server/presenters"; -import { ContextWithState } from "@server/types"; +import { APIContext } from "@server/types"; import { assertPresent, assertUuid } from "@server/validation"; const router = new Router(); -router.post("notificationSettings.create", auth(), async (ctx) => { +router.post("notificationSettings.create", auth(), async (ctx: APIContext) => { const { event } = ctx.request.body; assertPresent(event, "event is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; authorize(user, "createNotificationSetting", user.team); const [setting] = await NotificationSetting.findOrCreate({ where: { @@ -28,8 +28,8 @@ router.post("notificationSettings.create", auth(), async (ctx) => { }; }); -router.post("notificationSettings.list", auth(), async (ctx) => { - const { user } = ctx.state; +router.post("notificationSettings.list", auth(), async (ctx: APIContext) => { + const { user } = ctx.state.auth; const settings = await NotificationSetting.findAll({ where: { userId: user.id, @@ -41,11 +41,11 @@ router.post("notificationSettings.list", auth(), async (ctx) => { }; }); -router.post("notificationSettings.delete", auth(), async (ctx) => { +router.post("notificationSettings.delete", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const setting = await NotificationSetting.findByPk(id); authorize(user, "delete", setting); @@ -56,7 +56,7 @@ router.post("notificationSettings.delete", auth(), async (ctx) => { }; }); -const handleUnsubscribe = async (ctx: ContextWithState) => { +const handleUnsubscribe = async (ctx: APIContext) => { const { id, token } = (ctx.method === "POST" ? ctx.request.body : ctx.request.query) as { diff --git a/server/routes/api/pins.ts b/server/routes/api/pins.ts index d19e1d58da..7cc452b7b4 100644 --- a/server/routes/api/pins.ts +++ b/server/routes/api/pins.ts @@ -11,17 +11,18 @@ import { presentDocument, presentPolicies, } from "@server/presenters"; +import { APIContext } from "@server/types"; import { assertUuid, assertIndexCharacters } from "@server/validation"; import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("pins.create", auth(), async (ctx) => { +router.post("pins.create", auth(), async (ctx: APIContext) => { const { documentId, collectionId } = ctx.request.body; const { index } = ctx.request.body; assertUuid(documentId, "documentId is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const document = await Document.findByPk(documentId, { userId: user.id, }); @@ -55,9 +56,9 @@ router.post("pins.create", auth(), async (ctx) => { }; }); -router.post("pins.list", auth(), pagination(), async (ctx) => { +router.post("pins.list", auth(), pagination(), async (ctx: APIContext) => { const { collectionId } = ctx.request.body; - const { user } = ctx.state; + const { user } = ctx.state.auth; const [pins, collectionIds] = await Promise.all([ Pin.findAll({ @@ -98,13 +99,13 @@ router.post("pins.list", auth(), pagination(), async (ctx) => { }; }); -router.post("pins.update", auth(), async (ctx) => { +router.post("pins.update", auth(), async (ctx: APIContext) => { const { id, index } = ctx.request.body; assertUuid(id, "id is required"); assertIndexCharacters(index); - const { user } = ctx.state; + const { user } = ctx.state.auth; let pin = await Pin.findByPk(id, { rejectOnEmpty: true }); const document = await Document.findByPk(pin.documentId, { @@ -130,11 +131,11 @@ router.post("pins.update", auth(), async (ctx) => { }; }); -router.post("pins.delete", auth(), async (ctx) => { +router.post("pins.delete", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const pin = await Pin.findByPk(id, { rejectOnEmpty: true }); const document = await Document.findByPk(pin.documentId, { diff --git a/server/routes/api/revisions.ts b/server/routes/api/revisions.ts index fff1acabc8..6ddd6dab7d 100644 --- a/server/routes/api/revisions.ts +++ b/server/routes/api/revisions.ts @@ -6,16 +6,17 @@ import { Document, Revision } from "@server/models"; import DocumentHelper from "@server/models/helpers/DocumentHelper"; import { authorize } from "@server/policies"; import { presentRevision } from "@server/presenters"; +import { APIContext } from "@server/types"; import slugify from "@server/utils/slugify"; import { assertPresent, assertSort, assertUuid } from "@server/validation"; import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("revisions.info", auth(), async (ctx) => { +router.post("revisions.info", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const revision = await Revision.findByPk(id, { rejectOnEmpty: true, }); @@ -38,11 +39,11 @@ router.post("revisions.info", auth(), async (ctx) => { }; }); -router.post("revisions.diff", auth(), async (ctx) => { +router.post("revisions.diff", auth(), async (ctx: APIContext) => { const { id, compareToId } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const revision = await Revision.findByPk(id, { rejectOnEmpty: true, }); @@ -92,7 +93,7 @@ router.post("revisions.diff", auth(), async (ctx) => { }; }); -router.post("revisions.list", auth(), pagination(), async (ctx) => { +router.post("revisions.list", auth(), pagination(), async (ctx: APIContext) => { let { direction } = ctx.request.body; const { documentId, sort = "updatedAt" } = ctx.request.body; if (direction !== "ASC") { @@ -101,7 +102,7 @@ router.post("revisions.list", auth(), pagination(), async (ctx) => { assertSort(sort, Revision); assertPresent(documentId, "documentId is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const document = await Document.findByPk(documentId, { userId: user.id, }); diff --git a/server/routes/api/searches.ts b/server/routes/api/searches.ts index f9a3578af0..5caf588cc6 100644 --- a/server/routes/api/searches.ts +++ b/server/routes/api/searches.ts @@ -2,13 +2,14 @@ import Router from "koa-router"; import auth from "@server/middlewares/authentication"; import { SearchQuery } from "@server/models"; import { presentSearchQuery } from "@server/presenters"; +import { APIContext } from "@server/types"; import { assertPresent, assertUuid } from "@server/validation"; import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("searches.list", auth(), pagination(), async (ctx) => { - const { user } = ctx.state; +router.post("searches.list", auth(), pagination(), async (ctx: APIContext) => { + const { user } = ctx.state.auth; const searches = await SearchQuery.findAll({ where: { @@ -25,14 +26,14 @@ router.post("searches.list", auth(), pagination(), async (ctx) => { }; }); -router.post("searches.delete", auth(), async (ctx) => { +router.post("searches.delete", auth(), async (ctx: APIContext) => { const { id, query } = ctx.request.body; assertPresent(id || query, "id or query is required"); if (id) { assertUuid(id, "id is must be a uuid"); } - const { user } = ctx.state; + const { user } = ctx.state.auth; await SearchQuery.destroy({ where: { ...(id ? { id } : { query }), diff --git a/server/routes/api/shares.ts b/server/routes/api/shares.ts index 73b17537a5..c2e4b6495b 100644 --- a/server/routes/api/shares.ts +++ b/server/routes/api/shares.ts @@ -6,12 +6,13 @@ import auth from "@server/middlewares/authentication"; import { Document, User, Event, Share, Team, Collection } from "@server/models"; import { authorize } from "@server/policies"; import { presentShare, presentPolicies } from "@server/presenters"; +import { APIContext } from "@server/types"; import { assertUuid, assertSort, assertPresent } from "@server/validation"; import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("shares.info", auth(), async (ctx) => { +router.post("shares.info", auth(), async (ctx: APIContext) => { const { id, documentId } = ctx.request.body; assertPresent(id || documentId, "id or documentId is required"); if (id) { @@ -21,7 +22,7 @@ router.post("shares.info", auth(), async (ctx) => { assertUuid(documentId, "documentId is must be a uuid"); } - const { user } = ctx.state; + const { user } = ctx.state.auth; const shares = []; const share = await Share.scope({ method: ["withCollectionPermissions", user.id], @@ -92,7 +93,7 @@ router.post("shares.info", auth(), async (ctx) => { }; }); -router.post("shares.list", auth(), pagination(), async (ctx) => { +router.post("shares.list", auth(), pagination(), async (ctx: APIContext) => { let { direction } = ctx.request.body; const { sort = "updatedAt" } = ctx.request.body; if (direction !== "ASC") { @@ -100,7 +101,7 @@ router.post("shares.list", auth(), pagination(), async (ctx) => { } assertSort(sort, Share); - const { user } = ctx.state; + const { user } = ctx.state.auth; const where: WhereOptions = { teamId: user.teamId, userId: user.id, @@ -162,11 +163,11 @@ router.post("shares.list", auth(), pagination(), async (ctx) => { }; }); -router.post("shares.update", auth(), async (ctx) => { +router.post("shares.update", auth(), async (ctx: APIContext) => { const { id, includeChildDocuments, published, urlId } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const team = await Team.findByPk(user.teamId); authorize(user, "share", team); @@ -215,11 +216,11 @@ router.post("shares.update", auth(), async (ctx) => { }; }); -router.post("shares.create", auth(), async (ctx) => { +router.post("shares.create", auth(), async (ctx: APIContext) => { const { documentId } = ctx.request.body; assertPresent(documentId, "documentId is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const document = await Document.findByPk(documentId, { userId: user.id, }); @@ -267,11 +268,11 @@ router.post("shares.create", auth(), async (ctx) => { }; }); -router.post("shares.revoke", auth(), async (ctx) => { +router.post("shares.revoke", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const share = await Share.findByPk(id); if (!share?.document) { diff --git a/server/routes/api/stars.ts b/server/routes/api/stars.ts index e3361cd101..bf72a252c4 100644 --- a/server/routes/api/stars.ts +++ b/server/routes/api/stars.ts @@ -12,16 +12,17 @@ import { presentDocument, presentPolicies, } from "@server/presenters"; +import { APIContext } from "@server/types"; import { starIndexing } from "@server/utils/indexing"; import { assertUuid, assertIndexCharacters } from "@server/validation"; import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("stars.create", auth(), async (ctx) => { +router.post("stars.create", auth(), async (ctx: APIContext) => { const { documentId, collectionId } = ctx.request.body; const { index } = ctx.request.body; - const { user } = ctx.state; + const { user } = ctx.state.auth; assertUuid( documentId || collectionId, @@ -62,8 +63,8 @@ router.post("stars.create", auth(), async (ctx) => { }; }); -router.post("stars.list", auth(), pagination(), async (ctx) => { - const { user } = ctx.state; +router.post("stars.list", auth(), pagination(), async (ctx: APIContext) => { + const { user } = ctx.state.auth; const [stars, collectionIds] = await Promise.all([ Star.findAll({ @@ -115,13 +116,13 @@ router.post("stars.list", auth(), pagination(), async (ctx) => { }; }); -router.post("stars.update", auth(), async (ctx) => { +router.post("stars.update", auth(), async (ctx: APIContext) => { const { id, index } = ctx.request.body; assertUuid(id, "id is required"); assertIndexCharacters(index); - const { user } = ctx.state; + const { user } = ctx.state.auth; let star = await Star.findByPk(id); authorize(user, "update", star); @@ -138,11 +139,11 @@ router.post("stars.update", auth(), async (ctx) => { }; }); -router.post("stars.delete", auth(), async (ctx) => { +router.post("stars.delete", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const star = await Star.findByPk(id); authorize(user, "delete", star); diff --git a/server/routes/api/subscriptions.ts b/server/routes/api/subscriptions.ts index 80a4ef871d..d8bfc00f8e 100644 --- a/server/routes/api/subscriptions.ts +++ b/server/routes/api/subscriptions.ts @@ -2,53 +2,56 @@ import Router from "koa-router"; import subscriptionCreator from "@server/commands/subscriptionCreator"; import subscriptionDestroyer from "@server/commands/subscriptionDestroyer"; import auth from "@server/middlewares/authentication"; -import { - transaction, - TransactionContext, -} from "@server/middlewares/transaction"; +import { transaction } from "@server/middlewares/transaction"; import { Subscription, Document } from "@server/models"; import { authorize } from "@server/policies"; import { presentSubscription } from "@server/presenters"; +import { APIContext } from "@server/types"; import { assertIn, assertUuid } from "@server/validation"; import pagination from "./middlewares/pagination"; const router = new Router(); -router.post("subscriptions.list", auth(), pagination(), async (ctx) => { - const { user } = ctx.state; - const { documentId, event } = ctx.request.body; +router.post( + "subscriptions.list", + auth(), + pagination(), + async (ctx: APIContext) => { + const { user } = ctx.state.auth; + const { documentId, event } = ctx.request.body; - assertUuid(documentId, "documentId is required"); + assertUuid(documentId, "documentId is required"); - assertIn( - event, - ["documents.update"], - `Not a valid subscription event for documents` - ); - - const document = await Document.findByPk(documentId, { userId: user.id }); - - authorize(user, "read", document); - - const subscriptions = await Subscription.findAll({ - where: { - documentId: document.id, - userId: user.id, + assertIn( event, - }, - order: [["createdAt", "DESC"]], - offset: ctx.state.pagination.offset, - limit: ctx.state.pagination.limit, - }); + ["documents.update"], + `Not a valid subscription event for documents` + ); - ctx.body = { - pagination: ctx.state.pagination, - data: subscriptions.map(presentSubscription), - }; -}); + const document = await Document.findByPk(documentId, { userId: user.id }); -router.post("subscriptions.info", auth(), async (ctx) => { - const { user } = ctx.state; + authorize(user, "read", document); + + const subscriptions = await Subscription.findAll({ + where: { + documentId: document.id, + userId: user.id, + event, + }, + order: [["createdAt", "DESC"]], + offset: ctx.state.pagination.offset, + limit: ctx.state.pagination.limit, + }); + + ctx.body = { + pagination: ctx.state.pagination, + data: subscriptions.map(presentSubscription), + }; + } +); + +router.post("subscriptions.info", auth(), async (ctx: APIContext) => { + const { user } = ctx.state.auth; const { documentId, event } = ctx.request.body; assertUuid(documentId, "documentId is required"); @@ -82,8 +85,9 @@ router.post( "subscriptions.create", auth(), transaction(), - async (ctx: TransactionContext) => { - const { user, transaction } = ctx.state; + async (ctx: APIContext) => { + const { auth, transaction } = ctx.state; + const { user } = auth; const { documentId, event } = ctx.request.body; assertUuid(documentId, "documentId is required"); @@ -119,8 +123,9 @@ router.post( "subscriptions.delete", auth(), transaction(), - async (ctx: TransactionContext) => { - const { user, transaction } = ctx.state; + async (ctx: APIContext) => { + const { auth, transaction } = ctx.state; + const { user } = auth; const { id } = ctx.request.body; assertUuid(id, "id is required"); diff --git a/server/routes/api/team.ts b/server/routes/api/team.ts index 73f8cac7b0..f6e3a38ec0 100644 --- a/server/routes/api/team.ts +++ b/server/routes/api/team.ts @@ -8,6 +8,7 @@ import { rateLimiter } from "@server/middlewares/rateLimiter"; import { Event, Team, TeamDomain, User } from "@server/models"; import { authorize } from "@server/policies"; import { presentTeam, presentPolicies } from "@server/presenters"; +import { APIContext } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { assertUuid } from "@server/validation"; @@ -17,7 +18,7 @@ router.post( "team.update", auth(), rateLimiter(RateLimiterStrategy.TenPerHour), - async (ctx) => { + async (ctx: APIContext) => { const { name, avatarUrl, @@ -34,7 +35,7 @@ router.post( preferences, } = ctx.request.body; - const { user } = ctx.state; + const { user } = ctx.state.auth; const team = await Team.findByPk(user.teamId, { include: [{ model: TeamDomain }], }); @@ -76,8 +77,8 @@ router.post( "teams.create", auth(), rateLimiter(RateLimiterStrategy.FivePerHour), - async (ctx) => { - const { user } = ctx.state; + async (ctx: APIContext) => { + const { user } = ctx.state.auth; const { name } = ctx.request.body; const existingTeam = await Team.scope( diff --git a/server/routes/api/users.ts b/server/routes/api/users.ts index 08b6decad0..1c58065e16 100644 --- a/server/routes/api/users.ts +++ b/server/routes/api/users.ts @@ -16,14 +16,12 @@ import { ValidationError } from "@server/errors"; import logger from "@server/logging/Logger"; import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; -import { - transaction, - TransactionContext, -} from "@server/middlewares/transaction"; +import { transaction } from "@server/middlewares/transaction"; import { Event, User, Team } from "@server/models"; import { UserFlag, UserRole } from "@server/models/User"; import { can, authorize } from "@server/policies"; import { presentUser, presentPolicies } from "@server/presenters"; +import { APIContext } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { assertIn, @@ -39,7 +37,7 @@ import pagination from "./middlewares/pagination"; const router = new Router(); const emailEnabled = !!(env.SMTP_HOST || env.ENVIRONMENT === "development"); -router.post("users.list", auth(), pagination(), async (ctx) => { +router.post("users.list", auth(), pagination(), async (ctx: APIContext) => { let { direction } = ctx.request.body; const { sort = "createdAt", query, filter, ids } = ctx.request.body; if (direction !== "ASC") { @@ -55,7 +53,7 @@ router.post("users.list", auth(), pagination(), async (ctx) => { ); } - const actor = ctx.state.user; + const actor = ctx.state.auth.user; let where: WhereOptions = { teamId: actor.teamId, }; @@ -158,8 +156,8 @@ router.post("users.list", auth(), pagination(), async (ctx) => { }; }); -router.post("users.count", auth(), async (ctx) => { - const { user } = ctx.state; +router.post("users.count", auth(), async (ctx: APIContext) => { + const { user } = ctx.state.auth; const counts = await User.getCounts(user.teamId); ctx.body = { @@ -169,9 +167,9 @@ router.post("users.count", auth(), async (ctx) => { }; }); -router.post("users.info", auth(), async (ctx) => { +router.post("users.info", auth(), async (ctx: APIContext) => { const { id } = ctx.request.body; - const actor = ctx.state.user; + const actor = ctx.state.auth.user; const user = id ? await User.findByPk(id) : actor; authorize(actor, "read", user); const includeDetails = can(actor, "readDetails", user); @@ -184,57 +182,53 @@ router.post("users.info", auth(), async (ctx) => { }; }); -router.post( - "users.update", - auth(), - transaction(), - async (ctx: TransactionContext) => { - const { user, transaction } = ctx.state; - const { name, avatarUrl, language, preferences } = ctx.request.body; - if (name) { - user.name = name; - } - if (avatarUrl) { - user.avatarUrl = avatarUrl; - } - if (language) { - user.language = language; - } - if (preferences) { - assertKeysIn(preferences, UserPreference); +router.post("users.update", auth(), transaction(), async (ctx: APIContext) => { + const { auth, transaction } = ctx.state; + const { user } = auth; + const { name, avatarUrl, language, preferences } = ctx.request.body; + if (name) { + user.name = name; + } + if (avatarUrl) { + user.avatarUrl = avatarUrl; + } + if (language) { + user.language = language; + } + if (preferences) { + assertKeysIn(preferences, UserPreference); - for (const value of Object.values(UserPreference)) { - if (has(preferences, value)) { - assertBoolean(preferences[value]); - user.setPreference(value, preferences[value]); - } + for (const value of Object.values(UserPreference)) { + if (has(preferences, value)) { + assertBoolean(preferences[value]); + user.setPreference(value, preferences[value]); } } - await user.save({ transaction }); - await Event.create( - { - name: "users.update", - actorId: user.id, - userId: user.id, - teamId: user.teamId, - ip: ctx.request.ip, - }, - { transaction } - ); - - ctx.body = { - data: presentUser(user, { - includeDetails: true, - }), - }; } -); + await user.save({ transaction }); + await Event.create( + { + name: "users.update", + actorId: user.id, + userId: user.id, + teamId: user.teamId, + ip: ctx.request.ip, + }, + { transaction } + ); + + ctx.body = { + data: presentUser(user, { + includeDetails: true, + }), + }; +}); // Admin specific -router.post("users.promote", auth(), async (ctx) => { +router.post("users.promote", auth(), async (ctx: APIContext) => { const userId = ctx.request.body.id; - const teamId = ctx.state.user.teamId; - const actor = ctx.state.user; + const actor = ctx.state.auth.user; + const teamId = actor.teamId; assertPresent(userId, "id is required"); const user = await User.findByPk(userId); authorize(actor, "promote", user); @@ -260,10 +254,10 @@ router.post("users.promote", auth(), async (ctx) => { }; }); -router.post("users.demote", auth(), async (ctx) => { +router.post("users.demote", auth(), async (ctx: APIContext) => { const userId = ctx.request.body.id; let { to } = ctx.request.body; - const actor = ctx.state.user as User; + const actor = ctx.state.auth.user; assertPresent(userId, "id is required"); to = (to === "viewer" ? "viewer" : "member") as UserRole; @@ -289,9 +283,9 @@ router.post("users.demote", auth(), async (ctx) => { }; }); -router.post("users.suspend", auth(), async (ctx) => { +router.post("users.suspend", auth(), async (ctx: APIContext) => { const userId = ctx.request.body.id; - const actor = ctx.state.user; + const actor = ctx.state.auth.user; assertPresent(userId, "id is required"); const user = await User.findByPk(userId, { rejectOnEmpty: true, @@ -313,9 +307,9 @@ router.post("users.suspend", auth(), async (ctx) => { }; }); -router.post("users.activate", auth(), async (ctx) => { +router.post("users.activate", auth(), async (ctx: APIContext) => { const userId = ctx.request.body.id; - const actor = ctx.state.user; + const actor = ctx.state.auth.user; assertPresent(userId, "id is required"); const user = await User.findByPk(userId, { rejectOnEmpty: true, @@ -341,10 +335,10 @@ router.post( "users.invite", auth(), rateLimiter(RateLimiterStrategy.TenPerHour), - async (ctx) => { + async (ctx: APIContext) => { const { invites } = ctx.request.body; assertArray(invites, "invites must be an array"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const team = await Team.findByPk(user.teamId); authorize(user, "inviteUser", team); @@ -367,10 +361,10 @@ router.post( "users.resendInvite", auth(), transaction(), - async (ctx: TransactionContext) => { + async (ctx: APIContext) => { const { id } = ctx.request.body; - const actor = ctx.state.user; - const { transaction } = ctx.state; + const { auth, transaction } = ctx.state; + const actor = auth.user; const user = await User.findByPk(id, { lock: transaction.LOCK.UPDATE, @@ -413,8 +407,8 @@ router.post( "users.requestDelete", auth(), rateLimiter(RateLimiterStrategy.FivePerHour), - async (ctx) => { - const { user } = ctx.state; + async (ctx: APIContext) => { + const { user } = ctx.state.auth; authorize(user, "delete", user); if (emailEnabled) { @@ -434,9 +428,9 @@ router.post( "users.delete", auth(), rateLimiter(RateLimiterStrategy.TenPerHour), - async (ctx) => { + async (ctx: APIContext) => { const { id, code = "" } = ctx.request.body; - const actor = ctx.state.user; + const actor = ctx.state.auth.user; let user: User; if (id) { diff --git a/server/routes/api/views.ts b/server/routes/api/views.ts index 1937d90e79..613f2bb46d 100644 --- a/server/routes/api/views.ts +++ b/server/routes/api/views.ts @@ -4,16 +4,17 @@ import { rateLimiter } from "@server/middlewares/rateLimiter"; import { View, Document, Event } from "@server/models"; import { authorize } from "@server/policies"; import { presentView } from "@server/presenters"; +import { APIContext } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { assertUuid } from "@server/validation"; const router = new Router(); -router.post("views.list", auth(), async (ctx) => { +router.post("views.list", auth(), async (ctx: APIContext) => { const { documentId, includeSuspended = false } = ctx.request.body; assertUuid(documentId, "documentId is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const document = await Document.findByPk(documentId, { userId: user.id, }); @@ -29,11 +30,11 @@ router.post( "views.create", auth(), rateLimiter(RateLimiterStrategy.OneThousandPerHour), - async (ctx) => { + async (ctx: APIContext) => { const { documentId } = ctx.request.body; assertUuid(documentId, "documentId is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const document = await Document.findByPk(documentId, { userId: user.id, }); diff --git a/server/routes/api/webhookSubscriptions.ts b/server/routes/api/webhookSubscriptions.ts index e60bf04fbd..aa4cb34679 100644 --- a/server/routes/api/webhookSubscriptions.ts +++ b/server/routes/api/webhookSubscriptions.ts @@ -5,7 +5,7 @@ import auth from "@server/middlewares/authentication"; import { WebhookSubscription, Event } from "@server/models"; import { authorize } from "@server/policies"; import { presentWebhookSubscription } from "@server/presenters"; -import { WebhookSubscriptionEvent } from "@server/types"; +import { WebhookSubscriptionEvent, APIContext } from "@server/types"; import { assertArray, assertPresent, assertUuid } from "@server/validation"; import pagination from "./middlewares/pagination"; @@ -15,8 +15,8 @@ router.post( "webhookSubscriptions.list", auth({ admin: true }), pagination(), - async (ctx) => { - const { user } = ctx.state; + async (ctx: APIContext) => { + const { user } = ctx.state.auth; authorize(user, "listWebhookSubscription", user.team); const webhooks = await WebhookSubscription.findAll({ where: { @@ -37,8 +37,8 @@ router.post( router.post( "webhookSubscriptions.create", auth({ admin: true }), - async (ctx) => { - const { user } = ctx.state; + async (ctx: APIContext) => { + const { user } = ctx.state.auth; authorize(user, "createWebhookSubscription", user.team); const { name, url, secret } = ctx.request.body; @@ -83,10 +83,10 @@ router.post( router.post( "webhookSubscriptions.delete", auth({ admin: true }), - async (ctx) => { + async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const webhookSubscription = await WebhookSubscription.findByPk(id); authorize(user, "delete", webhookSubscription); @@ -112,10 +112,10 @@ router.post( router.post( "webhookSubscriptions.update", auth({ admin: true }), - async (ctx) => { + async (ctx: APIContext) => { const { id } = ctx.request.body; assertUuid(id, "id is required"); - const { user } = ctx.state; + const { user } = ctx.state.auth; const { name, url, secret } = ctx.request.body; const events: string[] = compact(ctx.request.body.events); diff --git a/server/routes/auth/index.ts b/server/routes/auth/index.ts index b12392d6c1..8a2a0be551 100644 --- a/server/routes/auth/index.ts +++ b/server/routes/auth/index.ts @@ -6,9 +6,10 @@ import Router from "koa-router"; import { AuthenticationError } from "@server/errors"; import auth from "@server/middlewares/authentication"; import { Collection, Team, View } from "@server/models"; +import { AppState, AppContext, APIContext } from "@server/types"; import providers from "./providers"; -const app = new Koa(); +const app = new Koa(); const router = new Router(); router.use(passport.initialize()); @@ -20,8 +21,8 @@ providers.forEach((provider) => { } }); -router.get("/redirect", auth(), async (ctx) => { - const { user } = ctx.state; +router.get("/redirect", auth(), async (ctx: APIContext) => { + const { user } = ctx.state.auth; const jwtToken = user.getJwtToken(); if (jwtToken === ctx.params.token) { diff --git a/server/types.ts b/server/types.ts index bb5c7d937d..7f81465d43 100644 --- a/server/types.ts +++ b/server/types.ts @@ -1,5 +1,6 @@ -import { Context } from "koa"; -import { RouterContext } from "koa-router"; +import { ParameterizedContext, DefaultContext } from "koa"; +import { IRouterParamContext } from "koa-router"; +import { Transaction } from "sequelize/types"; import { Client } from "@shared/types"; import { AccountProvisionerResult } from "./commands/accountProvisioner"; import { FileOperation, Team, User } from "./models"; @@ -13,18 +14,32 @@ export type AuthenticationResult = AccountProvisionerResult & { client: Client; }; -export type AuthenticatedState = { +export type Authentication = { user: User; token: string; - authType: AuthenticationType; + type: AuthenticationType; }; -export type ContextWithState = Context & { - state: AuthenticatedState; +export type Pagination = { + limit: number; + offset: number; + nextPath: string; }; -export interface APIContext> - extends RouterContext { +export type AppState = { + auth: Authentication | Record; + transaction: Transaction; + pagination: Pagination; +}; + +export type AppContext = ParameterizedContext; + +export interface APIContext, ResT = unknown> + extends ParameterizedContext< + AppState, + DefaultContext & IRouterParamContext, + ResT + > { input: ReqT; } From fc6bb3caef8b4de46fd3296ec9789a3f0ee51cf5 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 4 Jan 2023 20:42:48 -0500 Subject: [PATCH 06/61] fix: Unstable t method causing stars.list to fetch run multiple times. Seems this behavior changed in the recent dep bump --- app/components/Sidebar/components/Starred.tsx | 2 +- package.json | 2 +- yarn.lock | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/components/Sidebar/components/Starred.tsx b/app/components/Sidebar/components/Starred.tsx index 1b4b6ceadf..4ee247968f 100644 --- a/app/components/Sidebar/components/Starred.tsx +++ b/app/components/Sidebar/components/Starred.tsx @@ -45,7 +45,7 @@ function Starred() { React.useEffect(() => { fetchResults(); - }, [fetchResults]); + }, []); const handleShowMore = async () => { await fetchResults(displayedStarsCount); diff --git a/package.json b/package.json index 7acc1bd67d..396ccb565b 100644 --- a/package.json +++ b/package.json @@ -103,7 +103,7 @@ "fuzzy-search": "^3.2.1", "gemoji": "6.x", "http-errors": "2.0.0", - "i18next": "^22.4.6", + "i18next": "^22.4.8", "i18next-http-backend": "^2.1.1", "immutable": "^4.0.0", "inline-css": "^4.0.1", diff --git a/yarn.lock b/yarn.lock index 426e5ea606..8d03e6319b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8831,10 +8831,10 @@ i18next-parser@^7.1.0: vinyl-fs "^3.0.2" vue-template-compiler "^2.6.11" -i18next@^22.0.4, i18next@^22.4.6: - version "22.4.6" - resolved "https://registry.yarnpkg.com/i18next/-/i18next-22.4.6.tgz#876352c3ba81bdfedc38eeda124e2bbd05f46988" - integrity sha512-9Tm1ezxWyzV+306CIDMBbYBitC1jedQyYuuLtIv7oxjp2ohh8eyxP9xytIf+2bbQfhH784IQKPSYp+Zq9+YSbw== +i18next@^22.0.4, i18next@^22.4.8: + version "22.4.8" + resolved "https://registry.yarnpkg.com/i18next/-/i18next-22.4.8.tgz#7a3c5d26a93e8e5f32eee07b58484e2f721fb45b" + integrity sha512-XSOy17ZWqflOiJRYE/dzv6vDle2Se32dnHREHb93UnZzZ1+UnvQ8yKtt1fpNL3zvXz5AwCqqixrtTVZmRetaiQ== dependencies: "@babel/runtime" "^7.20.6" From f655288f67f1146dd83885e1bdc4b051437027f8 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 4 Jan 2023 21:13:13 -0500 Subject: [PATCH 07/61] fix: Issue where possibly logged into the wrong workspace when signing in via desktop app with multiple workspaces --- app/scenes/Login/AuthenticationProvider.tsx | 33 +++++++++++++-------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/app/scenes/Login/AuthenticationProvider.tsx b/app/scenes/Login/AuthenticationProvider.tsx index 9456011ff9..7e124c1247 100644 --- a/app/scenes/Login/AuthenticationProvider.tsx +++ b/app/scenes/Login/AuthenticationProvider.tsx @@ -19,6 +19,25 @@ type Props = { onEmailSuccess: (email: string) => void; }; +function useRedirectHref(authUrl: string) { + // If we're on a custom domain or a subdomain then the auth must point to the + // apex (env.URL) for authentication so that the state cookie can be set and read. + // We pass the host into the auth URL so that the server can redirect on error + // and keep the user on the same page. + const { custom, teamSubdomain, host } = parseDomain(window.location.origin); + const url = new URL(env.URL); + url.pathname = authUrl; + + if (custom || teamSubdomain) { + url.searchParams.set("host", host); + } + if (Desktop.isElectron()) { + url.searchParams.set("client", Client.Desktop); + } + + return url.toString(); +} + function AuthenticationProvider(props: Props) { const { t } = useTranslation(); const [showEmailSignin, setShowEmailSignin] = React.useState(false); @@ -57,6 +76,8 @@ function AuthenticationProvider(props: Props) { } }; + const href = useRedirectHref(authUrl); + if (id === "email") { if (isCreate) { return null; @@ -92,18 +113,6 @@ function AuthenticationProvider(props: Props) { ); } - // If we're on a custom domain or a subdomain then the auth must point to the - // apex (env.URL) for authentication so that the state cookie can be set and read. - // We pass the host into the auth URL so that the server can redirect on error - // and keep the user on the same page. - const { custom, teamSubdomain, host } = parseDomain(window.location.origin); - const needsRedirect = custom || teamSubdomain; - const href = Desktop.isElectron() - ? `${env.URL}${authUrl}?client=${Client.Desktop}` - : needsRedirect - ? `${env.URL}${authUrl}?host=${encodeURI(host)}` - : authUrl; - return ( Date: Wed, 4 Jan 2023 19:00:57 -0800 Subject: [PATCH 08/61] chore: Extract product name from translation strings (#4646) --- app/components/Branding.tsx | 2 +- app/components/LanguagePrompt.tsx | 4 ++- app/components/Layout.tsx | 3 ++- app/components/PageTitle.tsx | 6 +++-- app/scenes/Document/Shared.tsx | 4 ++- app/scenes/Login/Notices.tsx | 4 +-- app/scenes/Login/index.tsx | 2 +- app/scenes/Settings/Import.tsx | 9 ++++--- app/scenes/Settings/Members.tsx | 9 ++++--- app/scenes/Settings/Notifications.tsx | 4 +-- app/scenes/Settings/Slack.tsx | 11 +++++--- app/scenes/Settings/Webhooks.tsx | 8 +++++- app/scenes/Settings/Zapier.tsx | 8 +++--- .../components/ImportOutlineDialog.tsx | 6 +++-- app/scenes/UserDelete.tsx | 5 ++-- .../templates/ConfirmUserDeleteEmail.tsx | 7 ++--- .../emails/templates/ExportSuccessEmail.tsx | 3 ++- .../emails/templates/InviteAcceptedEmail.tsx | 7 ++--- server/emails/templates/InviteEmail.tsx | 15 ++++++----- .../emails/templates/InviteReminderEmail.tsx | 13 ++++++---- server/emails/templates/SigninEmail.tsx | 6 ++--- server/emails/templates/WelcomeEmail.tsx | 18 ++++++++----- server/emails/templates/components/Footer.tsx | 2 +- server/emails/templates/components/Header.tsx | 2 +- server/env.ts | 5 ++++ server/models/Team.ts | 3 +-- server/presenters/env.ts | 1 + server/queues/processors/SlackProcessor.ts | 2 +- server/routes/api/hooks.ts | 5 ++-- server/routes/app.ts | 2 +- shared/i18n/locales/en_US/translation.json | 26 +++++++++---------- shared/types.ts | 1 + 32 files changed, 123 insertions(+), 80 deletions(-) diff --git a/app/components/Branding.tsx b/app/components/Branding.tsx index 934a2ae48a..bea13a7b29 100644 --- a/app/components/Branding.tsx +++ b/app/components/Branding.tsx @@ -13,7 +13,7 @@ function Branding({ href = env.URL }: Props) { return ( -  Outline +  {env.APP_NAME} ); } diff --git a/app/components/LanguagePrompt.tsx b/app/components/LanguagePrompt.tsx index 3dcde2b386..8c057abc7f 100644 --- a/app/components/LanguagePrompt.tsx +++ b/app/components/LanguagePrompt.tsx @@ -6,6 +6,7 @@ import { languages, languageOptions } from "@shared/i18n"; import ButtonLink from "~/components/ButtonLink"; import Flex from "~/components/Flex"; import NoticeTip from "~/components/NoticeTip"; +import env from "~/env"; import useCurrentUser from "~/hooks/useCurrentUser"; import useStores from "~/hooks/useStores"; import { detectLanguage } from "~/utils/language"; @@ -57,6 +58,7 @@ export default function LanguagePrompt() { const option = find(languageOptions, (o) => o.value === language); const optionLabel = option ? option.label : ""; + const appName = env.APP_NAME; return ( @@ -64,7 +66,7 @@ export default function LanguagePrompt() { - Outline is available in your language{" "} + {{ appName }} is available in your language{" "} {{ optionLabel, }} diff --git a/app/components/Layout.tsx b/app/components/Layout.tsx index fa86483890..23b4402d23 100644 --- a/app/components/Layout.tsx +++ b/app/components/Layout.tsx @@ -7,6 +7,7 @@ import Flex from "~/components/Flex"; import { LoadingIndicatorBar } from "~/components/LoadingIndicator"; import SkipNavContent from "~/components/SkipNavContent"; import SkipNavLink from "~/components/SkipNavLink"; +import env from "~/env"; import useKeyDown from "~/hooks/useKeyDown"; import { MenuProvider } from "~/hooks/useMenuContext"; import useStores from "~/hooks/useStores"; @@ -36,7 +37,7 @@ const Layout: React.FC = ({ return ( - {title ? title : "Outline"} + {title ? title : env.APP_NAME} diff --git a/app/components/PageTitle.tsx b/app/components/PageTitle.tsx index 076f9fbf75..1ffacf4e39 100644 --- a/app/components/PageTitle.tsx +++ b/app/components/PageTitle.tsx @@ -2,6 +2,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { Helmet } from "react-helmet"; import { cdnPath } from "@shared/utils/urls"; +import env from "~/env"; import useStores from "~/hooks/useStores"; type Props = { @@ -16,14 +17,15 @@ const PageTitle = ({ title, favicon }: Props) => { return ( - {team?.name ? `${title} - ${team.name}` : `${title} - Outline`} + {team?.name ? `${title} - ${team.name}` : `${title} - ${env.APP_NAME}}`} {favicon ? ( - + ) : ( diff --git a/app/scenes/Document/Shared.tsx b/app/scenes/Document/Shared.tsx index e07d813860..d061dc51c4 100644 --- a/app/scenes/Document/Shared.tsx +++ b/app/scenes/Document/Shared.tsx @@ -13,6 +13,7 @@ import ErrorOffline from "~/scenes/ErrorOffline"; import Layout from "~/components/Layout"; import Sidebar from "~/components/Sidebar/Shared"; import Text from "~/components/Text"; +import env from "~/env"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import { NavigationNode } from "~/types"; @@ -136,9 +137,10 @@ function SharedDocumentScene(props: Props) { config?.name && isCloudHosted ? ( {t( - "{{ teamName }} is using Outline to share documents, please login to continue.", + "{{ teamName }} is using {{ appName }} to share documents, please login to continue.", { teamName: config.name, + appName: env.APP_NAME, } )} diff --git a/app/scenes/Login/Notices.tsx b/app/scenes/Login/Notices.tsx index c43816dee1..d38e32bc22 100644 --- a/app/scenes/Login/Notices.tsx +++ b/app/scenes/Login/Notices.tsx @@ -74,8 +74,8 @@ export default function Notices() { )} {notice === "suspended" && ( - Your Outline account has been suspended. To re-activate your account, - please contact a team admin. + Your account has been suspended. To re-activate your account, please + contact a team admin. )} {notice === "authentication-provider-disabled" && ( diff --git a/app/scenes/Login/index.tsx b/app/scenes/Login/index.tsx index c0ddc1120f..168165b08f 100644 --- a/app/scenes/Login/index.tsx +++ b/app/scenes/Login/index.tsx @@ -215,7 +215,7 @@ function Login({ children }: Props) { <> {t("Login to {{ authProviderName }}", { - authProviderName: config.name || "Outline", + authProviderName: config.name || env.APP_NAME, })} {children?.(config)} diff --git a/app/scenes/Settings/Import.tsx b/app/scenes/Settings/Import.tsx index c7af91c1aa..12a18e4b53 100644 --- a/app/scenes/Settings/Import.tsx +++ b/app/scenes/Settings/Import.tsx @@ -12,6 +12,7 @@ import Item from "~/components/List/Item"; import PaginatedList from "~/components/PaginatedList"; import Scene from "~/components/Scene"; import Text from "~/components/Text"; +import env from "~/env"; import useStores from "~/hooks/useStores"; import FileOperationListItem from "./components/FileOperationListItem"; import ImportNotionDialog from "./components/ImportNotionDialog"; @@ -20,6 +21,7 @@ import ImportOutlineDialog from "./components/ImportOutlineDialog"; function Import() { const { t } = useTranslation(); const { dialogs, fileOperations } = useStores(); + const appName = env.APP_NAME; return ( }> @@ -27,8 +29,9 @@ function Import() { Quickly transfer your existing documents, pages, and files from other - tools and services into Outline. You can also drag and drop any HTML, - Markdown, and text documents directly into Collections in the app. + tools and services into {{ appName }}. You can also drag and drop any + HTML, Markdown, and text documents directly into Collections in the + app. @@ -38,7 +41,7 @@ function Import() { image={} title={t("Markdown")} subtitle={t( - "Import a zip file of Markdown documents (exported from Outline 0.67.0 or earlier)" + "Import a zip file of Markdown documents (exported from version 0.67.0 or earlier)" )} actions={ +

diff --git a/server/emails/templates/InviteEmail.tsx b/server/emails/templates/InviteEmail.tsx index a80f0fffee..8b2aeebfab 100644 --- a/server/emails/templates/InviteEmail.tsx +++ b/server/emails/templates/InviteEmail.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import env from "@server/env"; import BaseEmail from "./BaseEmail"; import Body from "./components/Body"; import Button from "./components/Button"; @@ -26,7 +27,7 @@ export default class InviteEmail extends BaseEmail { } protected preview() { - return "Outline is a place for your team to build and share knowledge."; + return `${env.APP_NAME} is a place for your team to build and share knowledge.`; } protected renderAsText({ @@ -36,9 +37,9 @@ export default class InviteEmail extends BaseEmail { teamUrl, }: Props): string { return ` -Join ${teamName} on Outline +Join ${teamName} on ${env.APP_NAME} -${actorName} (${actorEmail}) has invited you to join Outline, a place for your team to build and share knowledge. +${actorName} (${actorEmail}) has invited you to join ${env.APP_NAME}, a place for your team to build and share knowledge. Join now: ${teamUrl} `; @@ -50,10 +51,12 @@ Join now: ${teamUrl}
- Join {teamName} on Outline + + Join {teamName} on {env.APP_NAME} +

- {actorName} ({actorEmail}) has invited you to join Outline, a place - for your team to build and share knowledge. + {actorName} ({actorEmail}) has invited you to join {env.APP_NAME}, a + place for your team to build and share knowledge.

diff --git a/server/emails/templates/InviteReminderEmail.tsx b/server/emails/templates/InviteReminderEmail.tsx index b06f83ecbf..9ff6274c0f 100644 --- a/server/emails/templates/InviteReminderEmail.tsx +++ b/server/emails/templates/InviteReminderEmail.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import env from "@server/env"; import BaseEmail from "./BaseEmail"; import Body from "./components/Body"; import Button from "./components/Button"; @@ -27,7 +28,7 @@ export default class InviteReminderEmail extends BaseEmail { } protected preview() { - return "Outline is a place for your team to build and share knowledge."; + return `${env.APP_NAME} is a place for your team to build and share knowledge.`; } protected renderAsText({ @@ -37,7 +38,7 @@ export default class InviteReminderEmail extends BaseEmail { teamUrl, }: Props): string { return ` -This is just a quick reminder that ${actorName} (${actorEmail}) invited you to join them in the ${teamName} team on Outline, a place for your team to build and share knowledge. +This is just a quick reminder that ${actorName} (${actorEmail}) invited you to join them in the ${teamName} team on ${env.APP_NAME}, a place for your team to build and share knowledge. We only send a reminder once. If you haven't signed up yet, you can do so here: ${teamUrl} @@ -50,11 +51,13 @@ If you haven't signed up yet, you can do so here: ${teamUrl}

- Join {teamName} on Outline + + Join {teamName} on {env.APP_NAME} +

This is just a quick reminder that {actorName} ({actorEmail}) - invited you to join them in the {teamName} team on Outline, a place - for your team to build and share knowledge. + invited you to join them in the {teamName} team on {env.APP_NAME}, a + place for your team to build and share knowledge.

If you haven't signed up yet, you can do so here:

diff --git a/server/emails/templates/SigninEmail.tsx b/server/emails/templates/SigninEmail.tsx index 4cfb921788..300f63a7a0 100644 --- a/server/emails/templates/SigninEmail.tsx +++ b/server/emails/templates/SigninEmail.tsx @@ -27,12 +27,12 @@ export default class SigninEmail extends BaseEmail { } protected preview(): string { - return "Here’s your link to signin to Outline."; + return `Here’s your link to signin to ${env.APP_NAME}.`; } protected renderAsText({ token, teamUrl, client }: Props): string { return ` -Use the link below to signin to Outline: +Use the link below to signin to ${env.APP_NAME}: ${this.signinLink(token, client)} @@ -52,7 +52,7 @@ signin page at: ${teamUrl} Magic Sign-in Link -

Click the button below to sign in to Outline.

+

Click the button below to sign in to {env.APP_NAME}.

diff --git a/server/emails/templates/WelcomeEmail.tsx b/server/emails/templates/WelcomeEmail.tsx index d8fe13fbaa..3fb1cd3e42 100644 --- a/server/emails/templates/WelcomeEmail.tsx +++ b/server/emails/templates/WelcomeEmail.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import env from "@server/env"; import BaseEmail from "./BaseEmail"; import Body from "./components/Body"; import Button from "./components/Button"; @@ -19,18 +20,18 @@ type Props = { */ export default class WelcomeEmail extends BaseEmail { protected subject() { - return "Welcome to Outline"; + return `Welcome to ${env.APP_NAME}`; } protected preview() { - return "Outline is a place for your team to build and share knowledge."; + return `${env.APP_NAME} is a place for your team to build and share knowledge.`; } protected renderAsText({ teamUrl }: Props) { return ` -Welcome to Outline! +Welcome to ${env.APP_NAME}! -Outline is a place for your team to build and share knowledge. +${env.APP_NAME} is a place for your team to build and share knowledge. To get started, head to the home screen and try creating a collection to help document your processes, create playbooks, or plan your teams work. @@ -46,8 +47,11 @@ ${teamUrl}/home

- Welcome to Outline! -

Outline is a place for your team to build and share knowledge.

+ Welcome to {env.APP_NAME}! +

+ {env.APP_NAME} is a place for your team to build and share + knowledge. +

To get started, head to the home screen and try creating a collection to help document your processes, create playbooks, or @@ -60,7 +64,7 @@ ${teamUrl}/home

diff --git a/server/emails/templates/components/Footer.tsx b/server/emails/templates/components/Footer.tsx index 12aa48e758..035b0bdefc 100644 --- a/server/emails/templates/components/Footer.tsx +++ b/server/emails/templates/components/Footer.tsx @@ -37,7 +37,7 @@ export default ({ unsubscribeUrl }: Props) => { - Outline + {env.APP_NAME} Twitter diff --git a/server/emails/templates/components/Header.tsx b/server/emails/templates/components/Header.tsx index 671b1ed009..f0848abb92 100644 --- a/server/emails/templates/components/Header.tsx +++ b/server/emails/templates/components/Header.tsx @@ -14,7 +14,7 @@ export default () => { Outline { if (!team) { ctx.body = { response_type: "ephemeral", - text: - "Sorry, we couldn’t find an integration for your team. Head to your Outline settings to set one up.", + text: `Sorry, we couldn’t find an integration for your team. Head to your ${env.APP_NAME} settings to set one up.`, }; return; } @@ -293,7 +292,7 @@ router.post("hooks.slack", async (ctx: APIContext) => { query: text, results: totalCount, }); - const haventSignedIn = `(It looks like you haven’t signed in to Outline yet, so results may be limited)`; + const haventSignedIn = `(It looks like you haven’t signed in to ${env.APP_NAME} yet, so results may be limited)`; // Map search results to the format expected by the Slack API if (results.length) { diff --git a/server/routes/app.ts b/server/routes/app.ts index d42870045c..5336250f8f 100644 --- a/server/routes/app.ts +++ b/server/routes/app.ts @@ -64,7 +64,7 @@ export const renderApp = async ( } = {} ) => { const { - title = "Outline", + title = env.APP_NAME, description = "A modern team knowledge base for your internal documentation, product specs, support answers, meeting notes, onboarding, & more…", canonical = "", } = options; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 5abc7d896d..9fd47e6c02 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -185,7 +185,7 @@ "Member": "Member", "Viewer": "Viewer", "Admin": "Admin", - "Outline is available in your language {{optionLabel}}, would you like to change?": "Outline is available in your language {{optionLabel}}, would you like to change?", + "{{appName}} is available in your language {{optionLabel}}, would you like to change?": "{{appName}} is available in your language {{optionLabel}}, would you like to change?", "Change Language": "Change Language", "Dismiss": "Dismiss", "You’re offline.": "You’re offline.", @@ -497,7 +497,7 @@ "The document will be accessible at <2>{{url}}": "The document will be accessible at <2>{{url}}", "More options": "More options", "Close": "Close", - "{{ teamName }} is using Outline to share documents, please login to continue.": "{{ teamName }} is using Outline to share documents, please login to continue.", + "{{ teamName }} is using {{ appName }} to share documents, please login to continue.": "", "Are you sure you want to delete the {{ documentTitle }} template?": "Are you sure you want to delete the {{ documentTitle }} template?", "Are you sure about that? Deleting the {{ documentTitle }} document will delete all of its history.": "Are you sure about that? Deleting the {{ documentTitle }} document will delete all of its history.", "Are you sure about that? Deleting the {{ documentTitle }} document will delete all of its history and {{ any }} nested document.": "Are you sure about that? Deleting the {{ documentTitle }} document will delete all of its history and one nested document.", @@ -643,7 +643,7 @@ "Drag and drop the zip file from Notion's HTML export option, or click to upload": "Drag and drop the zip file from Notion's HTML export option, or click to upload", "Where do I find the file?": "Where do I find the file?", "In Notion, click Settings & Members in the left sidebar and open Settings. Look for the Export section, and click Export all workspace content. Choose HTML as the format for the best data compatability.": "In Notion, click Settings & Members in the left sidebar and open Settings. Look for the Export section, and click Export all workspace content. Choose HTML as the format for the best data compatability.", - "Drag and drop the zip file from Outline's Markdown export option, or click to upload": "Drag and drop the zip file from Outline's Markdown export option, or click to upload", + "Drag and drop the zip file from the Markdown export option in {{appName}}, or click to upload": "Drag and drop the zip file from the Markdown export option in {{appName}}, or click to upload", "How does this work?": "How does this work?", "You can import a zip file that was previously exported from an Outline installation – collections, documents, and images will be imported. In Outline, open Export in the Settings sidebar and click on Export Data.": "You can import a zip file that was previously exported from an Outline installation – collections, documents, and images will be imported. In Outline, open Export in the Settings sidebar and click on Export Data.", "Last active": "Last active", @@ -713,14 +713,14 @@ "Groups can be used to organize and manage the people on your team.": "Groups can be used to organize and manage the people on your team.", "All groups": "All groups", "No groups have been created yet": "No groups have been created yet", - "Quickly transfer your existing documents, pages, and files from other tools and services into Outline. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.": "Quickly transfer your existing documents, pages, and files from other tools and services into Outline. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.", - "Import a zip file of Markdown documents (exported from Outline 0.67.0 or earlier)": "Import a zip file of Markdown documents (exported from Outline 0.67.0 or earlier)", + "Quickly transfer your existing documents, pages, and files from other tools and services into {{appName}}. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.": "Quickly transfer your existing documents, pages, and files from other tools and services into {{appName}}. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.", + "Import a zip file of Markdown documents (exported from version 0.67.0 or earlier)": "", "Import data": "Import data", "Import pages exported from Notion": "Import pages exported from Notion", "Import pages from a Confluence instance": "Import pages from a Confluence instance", "Enterprise": "Enterprise", "Recent imports": "Recent imports", - "Everyone that has signed into Outline appears here. It’s possible that there are other users who have access through {team.signinMethods} but haven’t signed in yet.": "Everyone that has signed into Outline appears here. It’s possible that there are other users who have access through {team.signinMethods} but haven’t signed in yet.", + "Everyone that has signed into {{appName}} is listed here. It’s possible that there are other users who have access through {team.signinMethods} but haven’t signed in yet.": "Everyone that has signed into {{appName}} is listed here. It’s possible that there are other users who have access through {team.signinMethods} but haven’t signed in yet.", "Filter": "Filter", "Receive a notification whenever a new document is published": "Receive a notification whenever a new document is published", "Receive a notification when a document you created is edited": "Receive a notification when a document you created is edited", @@ -731,7 +731,7 @@ "Export completed": "Export completed", "Receive a notification when an export you requested has been completed": "Receive a notification when an export you requested has been completed", "Getting started": "Getting started", - "Tips on getting started with Outline’s features and functionality": "Tips on getting started with Outline’s features and functionality", + "Tips on getting started with features and functionality": "", "New features": "New features", "Receive an email when new features of note are added": "Receive an email when new features of note are added", "Notifications saved": "Notifications saved", @@ -786,10 +786,10 @@ "Sharing is currently disabled.": "Sharing is currently disabled.", "You can globally enable and disable public document sharing in the security settings.": "You can globally enable and disable public document sharing in the security settings.", "Documents that have been shared are listed below. Anyone that has the public link can access a read-only version of the document until the link has been revoked.": "Documents that have been shared are listed below. Anyone that has the public link can access a read-only version of the document until the link has been revoked.", - "Whoops, you need to accept the permissions in Slack to connect Outline to your team. Try again?": "Whoops, you need to accept the permissions in Slack to connect Outline to your team. Try again?", + "Whoops, you need to accept the permissions in Slack to connect{{appName}} to your team. Try again?": "Whoops, you need to accept the permissions in Slack to connect{{appName}} to your team. Try again?", "Something went wrong while authenticating your request. Please try logging in again?": "Something went wrong while authenticating your request. Please try logging in again?", - "Get rich previews of Outline links shared in Slack and use the {{ command }} slash command to search for documents without leaving your chat.": "Get rich previews of Outline links shared in Slack and use the {{ command }} slash command to search for documents without leaving your chat.", - "Connect Outline collections to Slack channels and messages will be automatically posted to Slack when documents are published or updated.": "Connect Outline collections to Slack channels and messages will be automatically posted to Slack when documents are published or updated.", + "Get rich previews of {{ appName }} links shared in Slack and use the {{ command }} slash command to search for documents without leaving your chat.": "Get rich previews of {{ appName }} links shared in Slack and use the {{ command }} slash command to search for documents without leaving your chat.", + "Connect {{appName}} collections to Slack channels. Messages will be automatically posted to Slack when documents are published or updated.": "Connect {{appName}} collections to Slack channels. Messages will be automatically posted to Slack when documents are published or updated.", "Connect": "Connect", "The Slack integration is currently disabled. Please set the associated environment variables and restart the server to enable the integration.": "The Slack integration is currently disabled. Please set the associated environment variables and restart the server to enable the integration.", "New token": "New token", @@ -797,9 +797,9 @@ "Tokens": "Tokens", "Create a token": "Create a token", "New webhook": "New webhook", - "Webhooks can be used to notify your application when events happen in Outline. Events are sent as a https request with a JSON payload in near real-time.": "Webhooks can be used to notify your application when events happen in Outline. Events are sent as a https request with a JSON payload in near real-time.", + "Webhooks can be used to notify your application when events happen in {{appName}}. Events are sent as a https request with a JSON payload in near real-time.": "Webhooks can be used to notify your application when events happen in {{appName}}. Events are sent as a https request with a JSON payload in near real-time.", "Create a webhook": "Create a webhook", - "Zapier is a platform that allows Outline to easily integrate with thousands of other business tools. Automate your workflows, sync data, and more.": "Zapier is a platform that allows Outline to easily integrate with thousands of other business tools. Automate your workflows, sync data, and more.", + "Zapier is a platform that allows {{appName}} to easily integrate with thousands of other business tools. Automate your workflows, sync data, and more.": "Zapier is a platform that allows {{appName}} to easily integrate with thousands of other business tools. Automate your workflows, sync data, and more.", "Your are creating a new workspace using your current account — {{email}}": "Your are creating a new workspace using your current account — {{email}}", "Workspace name": "Workspace name", "When your new workspace is created, you will be the admin, meaning you will have the highest level of permissions and the ability to invite others.": "When your new workspace is created, you will be the admin, meaning you will have the highest level of permissions and the ability to invite others.", @@ -809,7 +809,7 @@ "Trash is empty at the moment.": "Trash is empty at the moment.", "A confirmation code has been sent to your email address, please enter the code below to permanantly destroy your account.": "A confirmation code has been sent to your email address, please enter the code below to permanantly destroy your account.", "Note: Signing back in will cause a new account to be automatically reprovisioned.": "Note: Signing back in will cause a new account to be automatically reprovisioned.", - "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.": "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.", + "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 {{appName}} and all your API tokens will be revoked.": "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 {{appName}} and all your API tokens will be revoked.", "Delete My Account": "Delete My Account", "Profile picture": "Profile picture", "You joined": "You joined", diff --git a/shared/types.ts b/shared/types.ts index e7b286df26..d6bd537507 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -52,6 +52,7 @@ export type PublicEnv = { DEFAULT_LANGUAGE: string; GOOGLE_ANALYTICS_ID: string | undefined; RELEASE: string | undefined; + APP_NAME: string; analytics: { service?: IntegrationService; settings?: IntegrationSettings; From b6141442b7e110d69f6f4de2ac7a7c9db72a1b61 Mon Sep 17 00:00:00 2001 From: Apoorv Mishra Date: Thu, 5 Jan 2023 20:24:03 +0530 Subject: [PATCH 09/61] Validate API request query (#4642) * fix: refactor to accommodate authentication, transaction and pagination together into ctx.state * feat: allow passing response type to APIContext * feat: preliminary work for initial review * fix: use unknown for base types * fix: api/attachments * fix: api/documents * fix: jsdoc comment for input * fix: replace at() with index access for compatibility * fix: validation err message * fix: error handling * fix: remove unnecessary extend --- server/middlewares/validate.ts | 20 +- server/routes/api/BaseSchema.ts | 8 + .../api/attachments/attachments.test.ts | 30 +++ server/routes/api/attachments/attachments.ts | 27 +- server/routes/api/attachments/schema.ts | 49 +++- .../__snapshots__/documents.test.ts.snap | 2 +- server/routes/api/documents/documents.test.ts | 14 +- server/routes/api/documents/documents.ts | 40 ++- server/routes/api/documents/schema.ts | 243 ++++++++++-------- server/routes/api/events/events.ts | 2 +- server/routes/api/events/schema.ts | 45 ++-- server/types.ts | 9 +- 12 files changed, 297 insertions(+), 192 deletions(-) create mode 100644 server/routes/api/BaseSchema.ts diff --git a/server/middlewares/validate.ts b/server/middlewares/validate.ts index 2c0684352b..24f7e55ef0 100644 --- a/server/middlewares/validate.ts +++ b/server/middlewares/validate.ts @@ -1,16 +1,20 @@ import { Next } from "koa"; -import { z } from "zod"; +import { z, ZodError } from "zod"; import { ValidationError } from "@server/errors"; -import { APIContext } from "@server/types"; +import { APIContext, BaseReq } from "@server/types"; -export default function validate(schema: T) { - return async function validateMiddleware(ctx: APIContext, next: Next) { +export default function validate>(schema: T) { + return async function validateMiddleware(ctx: APIContext, next: Next) { try { - ctx.input = schema.parse(ctx.request.body); + ctx.input = schema.parse(ctx.request); } catch (err) { - const { path, message } = err.issues[0]; - const [prefix = "ValidationError"] = path; - throw ValidationError(`${prefix}: ${message}`); + if (err instanceof ZodError) { + const { path, message } = err.issues[0]; + const errMessage = + path.length > 0 ? `${path[path.length - 1]}: ${message}` : message; + throw ValidationError(errMessage); + } + ctx.throw(err); } return next(); }; diff --git a/server/routes/api/BaseSchema.ts b/server/routes/api/BaseSchema.ts new file mode 100644 index 0000000000..04d7dba434 --- /dev/null +++ b/server/routes/api/BaseSchema.ts @@ -0,0 +1,8 @@ +import { z } from "zod"; + +const BaseSchema = z.object({ + body: z.unknown(), + query: z.unknown(), +}); + +export default BaseSchema; diff --git a/server/routes/api/attachments/attachments.test.ts b/server/routes/api/attachments/attachments.test.ts index a71c37479d..2cd0879b95 100644 --- a/server/routes/api/attachments/attachments.test.ts +++ b/server/routes/api/attachments/attachments.test.ts @@ -307,6 +307,24 @@ describe("#attachments.redirect", () => { expect(res.status).toEqual(302); }); + it("should return a redirect for the attachment if id supplied via query params", async () => { + const user = await buildUser(); + const attachment = await buildAttachment({ + teamId: user.teamId, + userId: user.id, + }); + const res = await server.post( + `/api/attachments.redirect?id=${attachment.id}`, + { + body: { + token: user.getJwtToken(), + }, + redirect: "manual", + } + ); + expect(res.status).toEqual(302); + }); + it("should return a redirect for an attachment belonging to a trashed document user has access to", async () => { const user = await buildUser(); const collection = await buildCollection({ @@ -385,4 +403,16 @@ describe("#attachments.redirect", () => { }); expect(res.status).toEqual(403); }); + + it("should fail in absence of id", async () => { + const user = await buildUser(); + const res = await server.post("/api/attachments.redirect", { + body: { + token: user.getJwtToken(), + }, + }); + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("id is required"); + }); }); diff --git a/server/routes/api/attachments/attachments.ts b/server/routes/api/attachments/attachments.ts index 9a4281abb7..9a8d485f91 100644 --- a/server/routes/api/attachments/attachments.ts +++ b/server/routes/api/attachments/attachments.ts @@ -13,7 +13,7 @@ import { authorize } from "@server/policies"; import { presentAttachment } from "@server/presenters"; import { APIContext } from "@server/types"; import { getPresignedPost, publicS3Endpoint } from "@server/utils/s3"; -import { assertIn, assertUuid } from "@server/validation"; +import { assertIn } from "@server/validation"; import * as T from "./schema"; const router = new Router(); @@ -24,7 +24,7 @@ router.post( validate(T.AttachmentsCreateSchema), transaction(), async (ctx: APIContext) => { - const { name, documentId, contentType, size, preset } = ctx.input; + const { name, documentId, contentType, size, preset } = ctx.input.body; const { auth, transaction } = ctx.state; const { user } = auth; @@ -113,7 +113,7 @@ router.post( auth(), validate(T.AttachmentDeleteSchema), async (ctx: APIContext) => { - const { id } = ctx.input; + const { id } = ctx.input.body; const { user } = ctx.state.auth; const attachment = await Attachment.findByPk(id, { rejectOnEmpty: true, @@ -141,9 +141,10 @@ router.post( } ); -const handleAttachmentsRedirect = async (ctx: APIContext) => { - const id = ctx.request.body?.id ?? ctx.request.query?.id; - assertUuid(id, "id is required"); +const handleAttachmentsRedirect = async ( + ctx: APIContext +) => { + const id = (ctx.input.body.id ?? ctx.input.query.id) as string; const { user } = ctx.state.auth; const attachment = await Attachment.findByPk(id, { @@ -165,7 +166,17 @@ const handleAttachmentsRedirect = async (ctx: APIContext) => { } }; -router.get("attachments.redirect", auth(), handleAttachmentsRedirect); -router.post("attachments.redirect", auth(), handleAttachmentsRedirect); +router.get( + "attachments.redirect", + auth(), + validate(T.AttachmentsRedirectSchema), + handleAttachmentsRedirect +); +router.post( + "attachments.redirect", + auth(), + validate(T.AttachmentsRedirectSchema), + handleAttachmentsRedirect +); export default router; diff --git a/server/routes/api/attachments/schema.ts b/server/routes/api/attachments/schema.ts index 7639608775..8604f0ad20 100644 --- a/server/routes/api/attachments/schema.ts +++ b/server/routes/api/attachments/schema.ts @@ -1,28 +1,49 @@ +import { isEmpty } from "lodash"; import { z } from "zod"; import { AttachmentPreset } from "@shared/types"; +import BaseSchema from "@server/routes/api/BaseSchema"; -export const AttachmentsCreateSchema = z.object({ - /** Attachment name */ - name: z.string(), +export const AttachmentsCreateSchema = BaseSchema.extend({ + body: z.object({ + /** Attachment name */ + name: z.string(), - /** Id of the document to which the Attachment belongs */ - documentId: z.string().uuid().optional(), + /** Id of the document to which the Attachment belongs */ + documentId: z.string().uuid().optional(), - /** File size of the Attachment */ - size: z.number(), + /** File size of the Attachment */ + size: z.number(), - /** Content-Type of the Attachment */ - contentType: z.string().optional().default("application/octet-stream"), + /** Content-Type of the Attachment */ + contentType: z.string().optional().default("application/octet-stream"), - /** Attachment type */ - preset: z.nativeEnum(AttachmentPreset), + /** Attachment type */ + preset: z.nativeEnum(AttachmentPreset), + }), }); export type AttachmentCreateReq = z.infer; -export const AttachmentDeleteSchema = z.object({ - /** Id of the attachment to be deleted */ - id: z.string().uuid(), +export const AttachmentDeleteSchema = BaseSchema.extend({ + body: z.object({ + /** Id of the attachment to be deleted */ + id: z.string().uuid(), + }), }); export type AttachmentDeleteReq = z.infer; + +export const AttachmentsRedirectSchema = BaseSchema.extend({ + body: z.object({ + /** Id of the attachment to be deleted */ + id: z.string().uuid().optional(), + }), + query: z.object({ + /** Id of the attachment to be deleted */ + id: z.string().uuid().optional(), + }), +}).refine((req) => !(isEmpty(req.body.id) && isEmpty(req.query.id)), { + message: "id is required", +}); + +export type AttachmentsRedirectReq = z.infer; diff --git a/server/routes/api/documents/__snapshots__/documents.test.ts.snap b/server/routes/api/documents/__snapshots__/documents.test.ts.snap index a045cdb845..2115718d91 100644 --- a/server/routes/api/documents/__snapshots__/documents.test.ts.snap +++ b/server/routes/api/documents/__snapshots__/documents.test.ts.snap @@ -66,7 +66,7 @@ Object { exports[`#documents.update should require text while appending 1`] = ` Object { "error": "validation_error", - "message": "ValidationError: text is required while appending", + "message": "text is required while appending", "ok": false, "status": 400, } diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 166c74d2ac..2a35bf62e5 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -30,9 +30,7 @@ describe("#documents.info", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual( - "ValidationError: one of id or shareId is required" - ); + expect(body.message).toEqual("one of id or shareId is required"); }); it("should return published document", async () => { @@ -1824,7 +1822,7 @@ describe("#documents.move", () => { const body = await res.json(); expect(res.status).toEqual(400); expect(body.message).toEqual( - "ValidationError: infinite loop detected, cannot nest a document inside itself" + "infinite loop detected, cannot nest a document inside itself" ); }); @@ -2288,7 +2286,7 @@ describe("#documents.create", () => { expect(res.status).toEqual(400); expect(body.message).toBe( - "ValidationError: collectionId is required to create a template document" + "collectionId is required to create a template document" ); }); @@ -2306,9 +2304,7 @@ describe("#documents.create", () => { const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toBe( - "ValidationError: collectionId is required to publish" - ); + expect(body.message).toBe("collectionId is required to publish"); }); it("should not allow creating a nested doc without a collection", async () => { @@ -2326,7 +2322,7 @@ describe("#documents.create", () => { expect(res.status).toEqual(400); expect(body.message).toBe( - "ValidationError: collectionId is required to create a nested document" + "collectionId is required to create a nested document" ); }); diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 75e8da8e0b..f73b19b86d 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -59,7 +59,7 @@ router.post( pagination(), validate(T.DocumentsListSchema), async (ctx: APIContext) => { - let { sort } = ctx.input; + let { sort } = ctx.input.body; const { direction, template, @@ -67,7 +67,7 @@ router.post( backlinkDocumentId, parentDocumentId, userId: createdById, - } = ctx.input; + } = ctx.input.body; // always filter by the current team const { user } = ctx.state.auth; @@ -176,7 +176,7 @@ router.post( pagination(), validate(T.DocumentsArchivedSchema), async (ctx: APIContext) => { - const { sort, direction } = ctx.input; + const { sort, direction } = ctx.input.body; const { user } = ctx.state.auth; const collectionIds = await user.collectionIds(); const collectionScope: Readonly = { @@ -220,7 +220,7 @@ router.post( pagination(), validate(T.DocumentsDeletedSchema), async (ctx: APIContext) => { - const { sort, direction } = ctx.input; + const { sort, direction } = ctx.input.body; const { user } = ctx.state.auth; const collectionIds = await user.collectionIds({ paranoid: false, @@ -280,7 +280,7 @@ router.post( pagination(), validate(T.DocumentsViewedSchema), async (ctx: APIContext) => { - const { sort, direction } = ctx.input; + const { sort, direction } = ctx.input.body; const { user } = ctx.state.auth; const collectionIds = await user.collectionIds(); const userId = user.id; @@ -333,7 +333,7 @@ router.post( pagination(), validate(T.DocumentsDraftsSchema), async (ctx: APIContext) => { - const { collectionId, dateFilter, direction, sort } = ctx.input; + const { collectionId, dateFilter, direction, sort } = ctx.input.body; const { user } = ctx.state.auth; if (collectionId) { @@ -396,7 +396,7 @@ router.post( }), validate(T.DocumentsInfoSchema), async (ctx: APIContext) => { - const { id, shareId, apiVersion } = ctx.input; + const { id, shareId, apiVersion } = ctx.input.body; const { user } = ctx.state.auth; const teamFromCtx = await getTeamFromContext(ctx); const { document, share, collection } = await documentLoader({ @@ -442,7 +442,7 @@ router.post( }), validate(T.DocumentsExportSchema), async (ctx: APIContext) => { - const { id } = ctx.input; + const { id } = ctx.input.body; const { user } = ctx.state.auth; const accept = ctx.request.headers["accept"]; @@ -494,7 +494,7 @@ router.post( auth({ member: true }), validate(T.DocumentsRestoreSchema), async (ctx: APIContext) => { - const { id, collectionId, revisionId } = ctx.input; + const { id, collectionId, revisionId } = ctx.input.body; const { user } = ctx.state.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -604,7 +604,7 @@ router.post( dateFilter, collectionId, userId, - } = ctx.input; + } = ctx.input.body; const { offset, limit } = ctx.state.pagination; const { user } = ctx.state.auth; let collaboratorIds = undefined; @@ -660,7 +660,7 @@ router.post( shareId, snippetMinWords, snippetMaxWords, - } = ctx.input; + } = ctx.input.body; const { offset, limit } = ctx.state.pagination; // Unfortunately, this still doesn't adequately handle cases when auth is optional @@ -765,7 +765,7 @@ router.post( auth({ member: true }), validate(T.DocumentsTemplatizeSchema), async (ctx: APIContext) => { - const { id } = ctx.input; + const { id } = ctx.input.body; const { user } = ctx.state.auth; const original = await Document.findByPk(id, { @@ -826,7 +826,7 @@ router.post( templateId, collectionId, append, - } = ctx.input; + } = ctx.input.body; const editorVersion = ctx.headers["x-editor-version"] as string | undefined; const { user } = ctx.state.auth; let collection: Collection | null | undefined; @@ -887,7 +887,7 @@ router.post( auth(), validate(T.DocumentsMoveSchema), async (ctx: APIContext) => { - const { id, collectionId, parentDocumentId, index } = ctx.input; + const { id, collectionId, parentDocumentId, index } = ctx.input.body; const { user } = ctx.state.auth; const document = await Document.findByPk(id, { userId: user.id, @@ -941,7 +941,7 @@ router.post( auth(), validate(T.DocumentsArchiveSchema), async (ctx: APIContext) => { - const { id } = ctx.input; + const { id } = ctx.input.body; const { user } = ctx.state.auth; const document = await Document.findByPk(id, { @@ -974,7 +974,7 @@ router.post( auth(), validate(T.DocumentsDeleteSchema), async (ctx: APIContext) => { - const { id, permanent } = ctx.input; + const { id, permanent } = ctx.input.body; const { user } = ctx.state.auth; if (permanent) { @@ -1039,7 +1039,7 @@ router.post( auth(), validate(T.DocumentsUnpublishSchema), async (ctx: APIContext) => { - const { id } = ctx.input; + const { id } = ctx.input.body; const { user } = ctx.state.auth; const document = await Document.findByPk(id, { @@ -1083,9 +1083,7 @@ router.post( throw InvalidRequestError("Request type must be multipart/form-data"); } - // String as this is always multipart/form-data - const publish = ctx.input.publish === "true"; - const { collectionId, parentDocumentId } = ctx.input; + const { collectionId, parentDocumentId, publish } = ctx.input.body; const file = ctx.request.files ? Object.values(ctx.request.files)[0] @@ -1173,7 +1171,7 @@ router.post( parentDocumentId, templateId, template, - } = ctx.input; + } = ctx.input.body; const editorVersion = ctx.headers["x-editor-version"] as string | undefined; const { user } = ctx.state.auth; diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index 9d01d3a6d4..78fb92339b 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -2,6 +2,7 @@ import { isEmpty } from "lodash"; import isUUID from "validator/lib/isUUID"; import { z } from "zod"; import { SHARE_URL_SLUG_REGEX } from "@shared/utils/urlHelpers"; +import BaseSchema from "@server/routes/api/BaseSchema"; const DocumentsSortParamsSchema = z.object({ /** Specifies the attributes by which documents will be sorted in the list */ @@ -39,63 +40,70 @@ const BaseIdSchema = z.object({ id: z.string(), }); -export const DocumentsListSchema = DocumentsSortParamsSchema.extend({ - /** Id of the user who created the doc */ - userId: z.string().uuid().optional(), +export const DocumentsListSchema = BaseSchema.extend({ + body: DocumentsSortParamsSchema.extend({ + /** Id of the user who created the doc */ + userId: z.string().uuid().optional(), - /** Alias for userId - kept for backwards compatibility */ - user: z.string().uuid().optional(), + /** Alias for userId - kept for backwards compatibility */ + user: z.string().uuid().optional(), - /** Id of the collection to which the document belongs */ - collectionId: z.string().uuid().optional(), + /** Id of the collection to which the document belongs */ + collectionId: z.string().uuid().optional(), - /** Alias for collectionId - kept for backwards compatibility */ - collection: z.string().uuid().optional(), + /** Alias for collectionId - kept for backwards compatibility */ + collection: z.string().uuid().optional(), - /** Id of the backlinked document */ - backlinkDocumentId: z.string().uuid().optional(), + /** Id of the backlinked document */ + backlinkDocumentId: z.string().uuid().optional(), - /** Id of the parent document to which the document belongs */ - parentDocumentId: z.string().uuid().nullish(), + /** Id of the parent document to which the document belongs */ + parentDocumentId: z.string().uuid().nullish(), - /** Boolean which denotes whether the document is a template */ - template: z.boolean().optional(), -}) + /** Boolean which denotes whether the document is a template */ + template: z.boolean().optional(), + }), // Maintains backwards compatibility - .transform((doc) => { - doc.collectionId = doc.collectionId || doc.collection; - doc.userId = doc.userId || doc.user; - delete doc.collection; - delete doc.user; +}).transform((req) => { + req.body.collectionId = req.body.collectionId || req.body.collection; + req.body.userId = req.body.userId || req.body.user; + delete req.body.collection; + delete req.body.user; - return doc; - }); + return req; +}); export type DocumentsListReq = z.infer; -export const DocumentsArchivedSchema = DocumentsSortParamsSchema.extend({}); +export const DocumentsArchivedSchema = BaseSchema.extend({ + body: DocumentsSortParamsSchema.extend({}), +}); export type DocumentsArchivedReq = z.infer; -export const DocumentsDeletedSchema = DocumentsSortParamsSchema.extend({}); +export const DocumentsDeletedSchema = BaseSchema.extend({ + body: DocumentsSortParamsSchema.extend({}), +}); export type DocumentsDeletedReq = z.infer; -export const DocumentsViewedSchema = DocumentsSortParamsSchema.extend({}); +export const DocumentsViewedSchema = BaseSchema.extend({ + body: DocumentsSortParamsSchema.extend({}), +}); export type DocumentsViewedReq = z.infer; -export const DocumentsDraftsSchema = DocumentsSortParamsSchema.merge( - DateFilterSchema -).extend({ - /** Id of the collection to which the document belongs */ - collectionId: z.string().uuid().optional(), +export const DocumentsDraftsSchema = BaseSchema.extend({ + body: DocumentsSortParamsSchema.merge(DateFilterSchema).extend({ + /** Id of the collection to which the document belongs */ + collectionId: z.string().uuid().optional(), + }), }); export type DocumentsDraftsReq = z.infer; -export const DocumentsInfoSchema = z - .object({ +export const DocumentsInfoSchema = BaseSchema.extend({ + body: z.object({ /** Id of the document to be retrieved */ id: z.string().optional(), @@ -107,136 +115,154 @@ export const DocumentsInfoSchema = z /** Version of the API to be used */ apiVersion: z.number().optional(), - }) - .refine((obj) => !(isEmpty(obj.id) && isEmpty(obj.shareId)), { - message: "one of id or shareId is required", - }); + }), +}).refine((req) => !(isEmpty(req.body.id) && isEmpty(req.body.shareId)), { + message: "one of id or shareId is required", +}); export type DocumentsInfoReq = z.infer; -export const DocumentsExportSchema = BaseIdSchema.extend({}); +export const DocumentsExportSchema = BaseSchema.extend({ + body: BaseIdSchema, +}); export type DocumentsExportReq = z.infer; -export const DocumentsRestoreSchema = BaseIdSchema.extend({ - /** Id of the collection to which the document belongs */ - collectionId: z.string().uuid().optional(), +export const DocumentsRestoreSchema = BaseSchema.extend({ + body: BaseIdSchema.extend({ + /** Id of the collection to which the document belongs */ + collectionId: z.string().uuid().optional(), - /** Id of document revision */ - revisionId: z.string().uuid().optional(), + /** Id of document revision */ + revisionId: z.string().uuid().optional(), + }), }); export type DocumentsRestoreReq = z.infer; -export const DocumentsSearchSchema = SearchQuerySchema.merge( - DateFilterSchema -).extend({ - /** Whether to include archived docs in results */ - includeArchived: z.boolean().optional(), +export const DocumentsSearchSchema = BaseSchema.extend({ + body: SearchQuerySchema.merge(DateFilterSchema).extend({ + /** Whether to include archived docs in results */ + includeArchived: z.boolean().optional(), - /** Whether to include drafts in results */ - includeDrafts: z.boolean().optional(), + /** Whether to include drafts in results */ + includeDrafts: z.boolean().optional(), - /** Filter results for team based on the collection */ - collectionId: z.string().uuid().optional(), + /** Filter results for team based on the collection */ + collectionId: z.string().uuid().optional(), - /** Filter results based on user */ - userId: z.string().uuid().optional(), + /** Filter results based on user */ + userId: z.string().uuid().optional(), - /** Filter results for the team derived from shareId */ - shareId: z - .string() - .refine((val) => isUUID(val) || SHARE_URL_SLUG_REGEX.test(val)) - .optional(), + /** Filter results for the team derived from shareId */ + shareId: z + .string() + .refine((val) => isUUID(val) || SHARE_URL_SLUG_REGEX.test(val)) + .optional(), - /** Min words to be shown in the results snippets */ - snippetMinWords: z.number().default(20), + /** Min words to be shown in the results snippets */ + snippetMinWords: z.number().default(20), - /** Max words to be accomodated in the results snippets */ - snippetMaxWords: z.number().default(30), + /** Max words to be accomodated in the results snippets */ + snippetMaxWords: z.number().default(30), + }), }); export type DocumentsSearchReq = z.infer; -export const DocumentsTemplatizeSchema = BaseIdSchema.extend({}); +export const DocumentsTemplatizeSchema = BaseSchema.extend({ + body: BaseIdSchema, +}); export type DocumentsTemplatizeReq = z.infer; -export const DocumentsUpdateSchema = BaseIdSchema.extend({ - /** Doc title to be updated */ - title: z.string().optional(), +export const DocumentsUpdateSchema = BaseSchema.extend({ + body: BaseIdSchema.extend({ + /** Doc title to be updated */ + title: z.string().optional(), - /** Doc text to be updated */ - text: z.string().optional(), + /** Doc text to be updated */ + text: z.string().optional(), - /** Boolean to denote if the doc should occupy full width */ - fullWidth: z.boolean().optional(), + /** Boolean to denote if the doc should occupy full width */ + fullWidth: z.boolean().optional(), - /** Boolean to denote if the doc should be published */ - publish: z.boolean().optional(), + /** Boolean to denote if the doc should be published */ + publish: z.boolean().optional(), - /** Revision to compare against document revision count */ - lastRevision: z.number().optional(), + /** Revision to compare against document revision count */ + lastRevision: z.number().optional(), - /** Doc template Id */ - templateId: z.string().uuid().nullish(), + /** Doc template Id */ + templateId: z.string().uuid().nullish(), - /** Doc collection Id */ - collectionId: z.string().uuid().optional(), + /** Doc collection Id */ + collectionId: z.string().uuid().optional(), - /** Boolean to denote if text should be appended */ - append: z.boolean().optional(), -}).refine((obj) => !(obj.append && !obj.text), { + /** Boolean to denote if text should be appended */ + append: z.boolean().optional(), + }), +}).refine((req) => !(req.body.append && !req.body.text), { message: "text is required while appending", }); export type DocumentsUpdateReq = z.infer; -export const DocumentsMoveSchema = BaseIdSchema.extend({ - /** Id of collection to which the doc is supposed to be moved */ - collectionId: z.string().uuid(), +export const DocumentsMoveSchema = BaseSchema.extend({ + body: BaseIdSchema.extend({ + /** Id of collection to which the doc is supposed to be moved */ + collectionId: z.string().uuid(), - /** Parent Id, in case if the doc is moved to a new parent */ - parentDocumentId: z.string().uuid().nullish(), + /** Parent Id, in case if the doc is moved to a new parent */ + parentDocumentId: z.string().uuid().nullish(), - /** Helps evaluate the new index in collection structure upon move */ - index: z.number().gte(0).optional(), -}).refine((obj) => !(obj.parentDocumentId === obj.id), { + /** Helps evaluate the new index in collection structure upon move */ + index: z.number().gte(0).optional(), + }), +}).refine((req) => !(req.body.parentDocumentId === req.body.id), { message: "infinite loop detected, cannot nest a document inside itself", }); export type DocumentsMoveReq = z.infer; -export const DocumentsArchiveSchema = BaseIdSchema.extend({}); +export const DocumentsArchiveSchema = BaseSchema.extend({ + body: BaseIdSchema, +}); export type DocumentsArchiveReq = z.infer; -export const DocumentsDeleteSchema = BaseIdSchema.extend({ - /** Whether to permanently delete the doc as opposed to soft-delete */ - permanent: z.boolean().optional(), +export const DocumentsDeleteSchema = BaseSchema.extend({ + body: BaseIdSchema.extend({ + /** Whether to permanently delete the doc as opposed to soft-delete */ + permanent: z.boolean().optional(), + }), }); export type DocumentsDeleteReq = z.infer; -export const DocumentsUnpublishSchema = BaseIdSchema.extend({}); +export const DocumentsUnpublishSchema = BaseSchema.extend({ + body: BaseIdSchema, +}); export type DocumentsUnpublishReq = z.infer; -export const DocumentsImportSchema = z.object({ - /** Whether to publish the imported docs. String due to multi-part form upload */ - publish: z.string().optional(), +export const DocumentsImportSchema = BaseSchema.extend({ + body: z.object({ + /** Whether to publish the imported docs. String as this is always multipart/form-data */ + publish: z.preprocess((val) => val === "true", z.boolean()).optional(), - /** Import docs to this collection */ - collectionId: z.string().uuid(), + /** Import docs to this collection */ + collectionId: z.string().uuid(), - /** Import under this parent doc */ - parentDocumentId: z.string().uuid().nullish(), + /** Import under this parent doc */ + parentDocumentId: z.string().uuid().nullish(), + }), }); export type DocumentsImportReq = z.infer; -export const DocumentsCreateSchema = z - .object({ +export const DocumentsCreateSchema = BaseSchema.extend({ + body: z.object({ /** Doc title */ title: z.string().default(""), @@ -257,14 +283,15 @@ export const DocumentsCreateSchema = z /** Whether to create a template doc */ template: z.boolean().optional(), - }) - .refine((obj) => !(obj.parentDocumentId && !obj.collectionId), { + }), +}) + .refine((req) => !(req.body.parentDocumentId && !req.body.collectionId), { message: "collectionId is required to create a nested document", }) - .refine((obj) => !(obj.template && !obj.collectionId), { + .refine((req) => !(req.body.template && !req.body.collectionId), { message: "collectionId is required to create a template document", }) - .refine((obj) => !(obj.publish && !obj.collectionId), { + .refine((req) => !(req.body.publish && !req.body.collectionId), { message: "collectionId is required to publish", }); diff --git a/server/routes/api/events/events.ts b/server/routes/api/events/events.ts index e66af05281..bbb6184b33 100644 --- a/server/routes/api/events/events.ts +++ b/server/routes/api/events/events.ts @@ -26,7 +26,7 @@ router.post( collectionId, name, auditLog, - } = ctx.input; + } = ctx.input.body; let where: WhereOptions = { name: Event.ACTIVITY_EVENTS, diff --git a/server/routes/api/events/schema.ts b/server/routes/api/events/schema.ts index 9462a7061f..66b39248a8 100644 --- a/server/routes/api/events/schema.ts +++ b/server/routes/api/events/schema.ts @@ -1,32 +1,35 @@ import { z } from "zod"; +import BaseSchema from "@server/routes/api/BaseSchema"; -export const EventsListSchema = z.object({ - /** Id of the user who performed the action */ - actorId: z.string().uuid().optional(), +export const EventsListSchema = BaseSchema.extend({ + body: z.object({ + /** Id of the user who performed the action */ + actorId: z.string().uuid().optional(), - /** Id of the document to filter the events for */ - documentId: z.string().uuid().optional(), + /** Id of the document to filter the events for */ + documentId: z.string().uuid().optional(), - /** Id of the collection to filter the events for */ - collectionId: z.string().uuid().optional(), + /** Id of the collection to filter the events for */ + collectionId: z.string().uuid().optional(), - /** Whether to include audit events */ - auditLog: z.boolean().default(false), + /** Whether to include audit events */ + auditLog: z.boolean().default(false), - /** Name of the event to retrieve */ - name: z.string().optional(), + /** Name of the event to retrieve */ + name: z.string().optional(), - /** The attribute to sort the events by */ - sort: z - .string() - .refine((val) => ["name", "createdAt"].includes(val)) - .default("createdAt"), + /** The attribute to sort the events by */ + sort: z + .string() + .refine((val) => ["name", "createdAt"].includes(val)) + .default("createdAt"), - /** The direction to sort the events */ - direction: z - .string() - .optional() - .transform((val) => (val !== "ASC" ? "DESC" : val)), + /** The direction to sort the events */ + direction: z + .string() + .optional() + .transform((val) => (val !== "ASC" ? "DESC" : val)), + }), }); export type EventsListReq = z.infer; diff --git a/server/types.ts b/server/types.ts index 7f81465d43..ec680a943d 100644 --- a/server/types.ts +++ b/server/types.ts @@ -1,7 +1,9 @@ import { ParameterizedContext, DefaultContext } from "koa"; import { IRouterParamContext } from "koa-router"; import { Transaction } from "sequelize/types"; +import { z } from "zod"; import { Client } from "@shared/types"; +import BaseSchema from "@server/routes/api/BaseSchema"; import { AccountProvisionerResult } from "./commands/accountProvisioner"; import { FileOperation, Team, User } from "./models"; @@ -34,12 +36,17 @@ export type AppState = { export type AppContext = ParameterizedContext; -export interface APIContext, ResT = unknown> +export type BaseReq = z.infer; + +export type BaseRes = unknown; + +export interface APIContext extends ParameterizedContext< AppState, DefaultContext & IRouterParamContext, ResT > { + /** Typed and validated version of request, consisting of validated body, query, etc */ input: ReqT; } From a065a8426f9c81c89d353116e4dc45cb21ec1783 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 5 Jan 2023 17:18:07 -0800 Subject: [PATCH 10/61] fix: OL/UL inside of checkbox list is not styled correctly (#4648) closes #4635 --- shared/editor/components/Styles.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index 73124c4dcb..22e548af88 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -721,7 +721,6 @@ ol ol ol { } ul.checkbox_list { - list-style: none; padding: 0; margin-left: ${props.rtl ? "0" : "-24px"}; margin-right: ${props.rtl ? "-24px" : "0"}; @@ -741,12 +740,13 @@ ol li { } } -ul.checkbox_list li { +ul.checkbox_list > li { display: flex; + list-style: none; padding-${props.rtl ? "right" : "left"}: 24px; } -ul.checkbox_list li.checked > div > p { +ul.checkbox_list > li.checked > div > p { color: ${props.theme.textTertiary}; } @@ -785,7 +785,7 @@ ol li.ProseMirror-selectednode::after { display: none; } -ul.checkbox_list li::before { +ul.checkbox_list > li::before { ${props.rtl ? "right" : "left"}: 0; } From ec2da746dcbf4d731f2e712a6f7161b33466126e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 5 Jan 2023 21:11:28 -0500 Subject: [PATCH 11/61] chore: Convert LinkToolbar to functional component MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ítalo Sousa --- app/editor/components/FloatingToolbar.tsx | 15 +- app/editor/components/LinkToolbar.tsx | 213 +++++++++++----------- app/editor/index.tsx | 3 - 3 files changed, 111 insertions(+), 120 deletions(-) diff --git a/app/editor/components/FloatingToolbar.tsx b/app/editor/components/FloatingToolbar.tsx index c72407e90d..c288d5b9ab 100644 --- a/app/editor/components/FloatingToolbar.tsx +++ b/app/editor/components/FloatingToolbar.tsx @@ -1,6 +1,5 @@ import { NodeSelection } from "prosemirror-state"; import { CellSelection } from "prosemirror-tables"; -import { EditorView } from "prosemirror-view"; import * as React from "react"; import { Portal } from "react-portal"; import styled from "styled-components"; @@ -9,10 +8,10 @@ import useComponentSize from "~/hooks/useComponentSize"; import useEventListener from "~/hooks/useEventListener"; import useMediaQuery from "~/hooks/useMediaQuery"; import useViewportHeight from "~/hooks/useViewportHeight"; +import { useEditor } from "./EditorContext"; type Props = { active?: boolean; - view: EditorView; children: React.ReactNode; forwardedRef?: React.RefObject | null; }; @@ -27,13 +26,13 @@ const defaultPosition = { function usePosition({ menuRef, isSelectingText, - props, + active, }: { menuRef: React.RefObject; isSelectingText: boolean; - props: Props; + active?: boolean; }) { - const { view, active } = props; + const { view } = useEditor(); const { selection } = view.state; const { width: menuWidth, height: menuHeight } = useComponentSize(menuRef); const viewportHeight = useViewportHeight(); @@ -155,14 +154,14 @@ function usePosition({ } const FloatingToolbar = React.forwardRef( - (props: Props, forwardedRef: React.RefObject) => { - const menuRef = forwardedRef || React.createRef(); + (props: Props, ref: React.RefObject) => { + const menuRef = ref || React.createRef(); const [isSelectingText, setSelectingText] = React.useState(false); const position = usePosition({ menuRef, isSelectingText, - props, + active: props.active, }); useEventListener("mouseup", () => { diff --git a/app/editor/components/LinkToolbar.tsx b/app/editor/components/LinkToolbar.tsx index 499a0a8220..0f3d3568aa 100644 --- a/app/editor/components/LinkToolbar.tsx +++ b/app/editor/components/LinkToolbar.tsx @@ -2,152 +2,147 @@ import { EditorView } from "prosemirror-view"; import * as React from "react"; import createAndInsertLink from "@shared/editor/commands/createAndInsertLink"; import { creatingUrlPrefix } from "@shared/utils/urls"; -import { Dictionary } from "~/hooks/useDictionary"; +import useDictionary from "~/hooks/useDictionary"; +import useEventListener from "~/hooks/useEventListener"; +import useToasts from "~/hooks/useToasts"; +import { useEditor } from "./EditorContext"; import FloatingToolbar from "./FloatingToolbar"; import LinkEditor, { SearchResult } from "./LinkEditor"; type Props = { isActive: boolean; - view: EditorView; - dictionary: Dictionary; onCreateLink?: (title: string) => Promise; onSearchLink?: (term: string) => Promise; onClickLink: ( href: string, event: React.MouseEvent ) => void; - onShowToast: (message: string) => void; onClose: () => void; }; -function isActive(props: Props) { - const { view } = props; - const { selection } = view.state; - +function isActive(view: EditorView, active: boolean): boolean { try { + const { selection } = view.state; const paragraph = view.domAtPos(selection.from); - return props.isActive && !!paragraph.node; + return active && !!paragraph.node; } catch (err) { return false; } } -export default class LinkToolbar extends React.Component { - menuRef = React.createRef(); +export default function LinkToolbar({ + onCreateLink, + onSearchLink, + onClickLink, + onClose, + ...rest +}: Props) { + const dictionary = useDictionary(); + const { view } = useEditor(); + const { showToast } = useToasts(); + const menuRef = React.useRef(null); - state = { - left: -1000, - top: undefined, - }; - - componentDidMount() { - window.addEventListener("mousedown", this.handleClickOutside); - } - - componentWillUnmount() { - window.removeEventListener("mousedown", this.handleClickOutside); - } - - handleClickOutside = (event: Event) => { + useEventListener("mousedown", (event: Event) => { if ( event.target instanceof HTMLElement && - this.menuRef.current && - this.menuRef.current.contains(event.target) + menuRef.current && + menuRef.current.contains(event.target) ) { return; } - - this.props.onClose(); - }; - - handleOnCreateLink = async (title: string) => { - const { dictionary, onCreateLink, view, onClose, onShowToast } = this.props; - onClose(); - this.props.view.focus(); + }); - if (!onCreateLink) { - return; - } + const handleOnCreateLink = React.useCallback( + async (title: string) => { + onClose(); + view.focus(); - const { dispatch, state } = view; - const { from, to } = state.selection; - if (from !== to) { - // selection must be collapsed - return; - } + if (!onCreateLink) { + return; + } - const href = `${creatingUrlPrefix}${title}…`; + const { dispatch, state } = view; + const { from, to } = state.selection; + if (from !== to) { + // selection must be collapsed + return; + } - // Insert a placeholder link - dispatch( - view.state.tr - .insertText(title, from, to) - .addMark( - from, - to + title.length, - state.schema.marks.link.create({ href }) - ) - ); + const href = `${creatingUrlPrefix}#${title}…`; - createAndInsertLink(view, title, href, { - onCreateLink, - onShowToast, - dictionary, - }); - }; + // Insert a placeholder link + dispatch( + view.state.tr + .insertText(title, from, to) + .addMark( + from, + to + title.length, + state.schema.marks.link.create({ href }) + ) + ); - handleOnSelectLink = ({ - href, - title, - }: { - href: string; - title: string; - from: number; - to: number; - }) => { - const { view, onClose } = this.props; + createAndInsertLink(view, title, href, { + onCreateLink, + onShowToast: showToast, + dictionary, + }); + }, + [onCreateLink, onClose, view, dictionary, showToast] + ); - onClose(); - this.props.view.focus(); + const handleOnSelectLink = React.useCallback( + ({ + href, + title, + }: { + href: string; + title: string; + from: number; + to: number; + }) => { + onClose(); + view.focus(); - const { dispatch, state } = view; - const { from, to } = state.selection; - if (from !== to) { - // selection must be collapsed - return; - } + const { dispatch, state } = view; + const { from, to } = state.selection; + if (from !== to) { + // selection must be collapsed + return; + } - dispatch( - view.state.tr - .insertText(title, from, to) - .addMark( - from, - to + title.length, - state.schema.marks.link.create({ href }) - ) - ); - }; + dispatch( + view.state.tr + .insertText(title, from, to) + .addMark( + from, + to + title.length, + state.schema.marks.link.create({ href }) + ) + ); + }, + [onClose, view] + ); - render() { - const { onCreateLink, onClose, ...rest } = this.props; - const { selection } = this.props.view.state; - const active = isActive(this.props); + const { selection } = view.state; + const active = isActive(view, rest.isActive); - return ( - - {active && ( - - )} - - ); - } + return ( + + {active && ( + + )} + + ); } diff --git a/app/editor/index.tsx b/app/editor/index.tsx index 8e97809e44..60064b8d5a 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -685,13 +685,10 @@ export class Editor extends React.PureComponent< onShowToast={this.props.onShowToast} /> Date: Thu, 5 Jan 2023 21:25:17 -0500 Subject: [PATCH 12/61] tsc --- app/editor/components/SelectionToolbar.tsx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/app/editor/components/SelectionToolbar.tsx b/app/editor/components/SelectionToolbar.tsx index bfe41deb3d..9d8855e43b 100644 --- a/app/editor/components/SelectionToolbar.tsx +++ b/app/editor/components/SelectionToolbar.tsx @@ -231,11 +231,7 @@ export default class SelectionToolbar extends React.Component { } return ( - + {link && range ? ( Date: Fri, 6 Jan 2023 05:26:13 -0800 Subject: [PATCH 13/61] fix: build.sh copies dev webpack incorrectly --- build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sh b/build.sh index 69d2eb5d34..1b8fe88cc8 100755 --- a/build.sh +++ b/build.sh @@ -10,4 +10,4 @@ cp ./server/static/error.dev.html ./build/server/error.dev.html cp ./server/static/error.prod.html ./build/server/error.prod.html # Link webpack config -ln -sf \"$(pwd)/webpack.config.dev.js\" ./build +ln -sf "$(pwd)/webpack.config.dev.js" ./build From cbd9971bc7d425db1d4c73cf69d12c5701118dda Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 6 Jan 2023 08:32:55 -0500 Subject: [PATCH 14/61] fix: Missing translation on Import screen --- shared/i18n/locales/en_US/translation.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 9fd47e6c02..c4af6ff79f 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -714,7 +714,7 @@ "All groups": "All groups", "No groups have been created yet": "No groups have been created yet", "Quickly transfer your existing documents, pages, and files from other tools and services into {{appName}}. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.": "Quickly transfer your existing documents, pages, and files from other tools and services into {{appName}}. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.", - "Import a zip file of Markdown documents (exported from version 0.67.0 or earlier)": "", + "Import a zip file of Markdown documents (exported from version 0.67.0 or earlier)": "Import a zip file of Markdown documents (exported from version 0.67.0 or earlier)", "Import data": "Import data", "Import pages exported from Notion": "Import pages exported from Notion", "Import pages from a Confluence instance": "Import pages from a Confluence instance", From 4b47bffcf512faad0fdb9d88959715dacbd7e02b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 6 Jan 2023 06:02:15 -0800 Subject: [PATCH 15/61] fix: images and files with cyrillic names don't import (#4654) closes #4559 --- server/queues/tasks/ImportMarkdownZipTask.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/server/queues/tasks/ImportMarkdownZipTask.ts b/server/queues/tasks/ImportMarkdownZipTask.ts index 966f8240ed..0f549fb017 100644 --- a/server/queues/tasks/ImportMarkdownZipTask.ts +++ b/server/queues/tasks/ImportMarkdownZipTask.ts @@ -152,22 +152,20 @@ export default class ImportMarkdownZipTask extends ImportTask { // and replace them out with attachment redirect urls before continuing. for (const document of output.documents) { for (const attachment of output.attachments) { + const encodedPath = encodeURI(attachment.path); + // Pull the collection and subdirectory out of the path name, upload // folders in an export are relative to the document itself - const normalizedAttachmentPath = attachment.path.replace( + const normalizedAttachmentPath = encodedPath.replace( /(.*)uploads\//, "uploads/" ); const reference = `<<${attachment.id}>>`; document.text = document.text - .replace(new RegExp(escapeRegExp(attachment.path), "g"), reference) + .replace(new RegExp(escapeRegExp(encodedPath), "g"), reference) .replace( - new RegExp(escapeRegExp(normalizedAttachmentPath), "g"), - reference - ) - .replace( - new RegExp(escapeRegExp(`/${normalizedAttachmentPath}`), "g"), + new RegExp(`/?${escapeRegExp(normalizedAttachmentPath)}`, "g"), reference ); } From 9f825b9adf67529fe4c2972b92d4405d2ae89477 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 6 Jan 2023 16:58:39 -0500 Subject: [PATCH 16/61] fix: Allow sort by title in documents.list --- server/routes/api/documents/schema.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index 78fb92339b..286ed977c6 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -8,7 +8,7 @@ const DocumentsSortParamsSchema = z.object({ /** Specifies the attributes by which documents will be sorted in the list */ sort: z .string() - .refine((val) => ["createdAt", "updatedAt", "index"].includes(val)) + .refine((val) => ["createdAt", "updatedAt", "index", "title"].includes(val)) .default("updatedAt"), /** Specifies the sort order with respect to sort field */ From e67ac1215a98fd10ba70022c77cd65fc1033005e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 6 Jan 2023 19:31:06 -0800 Subject: [PATCH 17/61] feat: Allow moving draft documents (#4652) * feat: Allow moving draft documents * Allow drag-n-drop move of draft documents * fix: Allow moving draft without a collection * fix: Allow moving draft without a collection --- app/components/DocumentBreadcrumb.tsx | 5 +- .../Sidebar/components/CollectionLink.tsx | 13 +++-- .../Sidebar/components/DocumentLink.tsx | 24 +++----- .../components/DraggableCollectionLink.tsx | 2 +- app/models/Collection.ts | 13 +++-- server/commands/documentMover.ts | 56 ++++++++++--------- server/policies/document.test.ts | 2 +- server/policies/document.ts | 9 +-- 8 files changed, 61 insertions(+), 63 deletions(-) diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx index 78e6399d9b..3a8b928927 100644 --- a/app/components/DocumentBreadcrumb.tsx +++ b/app/components/DocumentBreadcrumb.tsx @@ -77,8 +77,9 @@ const DocumentBreadcrumb: React.FC = ({ } const path = React.useMemo( - () => collection?.pathToDocument?.(document.id).slice(0, -1) || [], - [collection, document] + () => collection?.pathToDocument(document.id).slice(0, -1) || [], + // eslint-disable-next-line react-hooks/exhaustive-deps + [collection, document, document.collectionId, document.parentDocumentId] ); const items = React.useMemo(() => { diff --git a/app/components/Sidebar/components/CollectionLink.tsx b/app/components/Sidebar/components/CollectionLink.tsx index 83460d27d5..09a189b7a7 100644 --- a/app/components/Sidebar/components/CollectionLink.tsx +++ b/app/components/Sidebar/components/CollectionLink.tsx @@ -27,7 +27,7 @@ import { useStarredContext } from "./StarredContext"; type Props = { collection: Collection; expanded?: boolean; - onDisclosureClick: (ev: React.MouseEvent) => void; + onDisclosureClick: (ev?: React.MouseEvent) => void; activeDocument: Document | undefined; isDraggingAnyCollection?: boolean; }; @@ -62,7 +62,7 @@ const CollectionLink: React.FC = ({ // Drop to re-parent document const [{ isOver, canDrop }, drop] = useDrop({ accept: "document", - drop: (item: DragObject, monitor) => { + drop: async (item: DragObject, monitor) => { const { id, collectionId } = item; if (monitor.didDrop()) { return; @@ -81,7 +81,8 @@ const CollectionLink: React.FC = ({ if ( prevCollection && prevCollection.permission === null && - prevCollection.permission !== collection.permission + prevCollection.permission !== collection.permission && + !document?.isDraft ) { itemRef.current = item; @@ -97,7 +98,11 @@ const CollectionLink: React.FC = ({ ), }); } else { - documents.move(id, collection.id); + await documents.move(id, collection.id); + + if (!expanded) { + onDisclosureClick(); + } } }, canDrop: () => canUpdate, diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 62bc8887ff..bc7ce632a8 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -105,8 +105,7 @@ function InnerDocumentLink( const handleDisclosureClick = React.useCallback( (ev) => { - ev.preventDefault(); - ev.stopPropagation(); + ev?.preventDefault(); setExpanded(!expanded); }, [expanded] @@ -150,14 +149,10 @@ function InnerDocumentLink( collect: (monitor) => ({ isDragging: monitor.isDragging(), }), - canDrag: () => { - return ( - !isDraft && - (policies.abilities(node.id).move || - policies.abilities(node.id).archive || - policies.abilities(node.id).delete) - ); - }, + canDrag: () => + policies.abilities(node.id).move || + policies.abilities(node.id).archive || + policies.abilities(node.id).delete, }); const hoverExpanding = React.useRef>(); @@ -174,19 +169,18 @@ function InnerDocumentLink( // Drop to re-parent const [{ isOverReparent, canDropToReparent }, dropToReparent] = useDrop({ accept: "document", - drop: (item: DragObject, monitor) => { + drop: async (item: DragObject, monitor) => { if (monitor.didDrop()) { return; } if (!collection) { return; } - documents.move(item.id, collection.id, node.id); + await documents.move(item.id, collection.id, node.id); + setExpanded(true); }, canDrop: (_item, monitor) => - !isDraft && - !!pathToNode && - !pathToNode.includes(monitor.getItem().id), + !!pathToNode && !pathToNode.includes(monitor.getItem().id), hover: (_item, monitor) => { // Enables expansion of document children when hovering over the document // for more than half a second. diff --git a/app/components/Sidebar/components/DraggableCollectionLink.tsx b/app/components/Sidebar/components/DraggableCollectionLink.tsx index b2f17ab4c4..00c1fd47e6 100644 --- a/app/components/Sidebar/components/DraggableCollectionLink.tsx +++ b/app/components/Sidebar/components/DraggableCollectionLink.tsx @@ -91,7 +91,7 @@ function DraggableCollectionLink({ }, [collection.id, ui.activeCollectionId, locationStateStarred]); const handleDisclosureClick = React.useCallback((ev) => { - ev.preventDefault(); + ev?.preventDefault(); setExpanded((e) => !e); }, []); diff --git a/app/models/Collection.ts b/app/models/Collection.ts index bd52b708ea..21569f0e43 100644 --- a/app/models/Collection.ts +++ b/app/models/Collection.ts @@ -171,8 +171,11 @@ export default class Collection extends ParanoidModel { } pathToDocument(documentId: string) { - let path: NavigationNode[] | undefined; + let path: NavigationNode[] | undefined = []; const document = this.store.rootStore.documents.get(documentId); + if (!document) { + return path; + } const travelNodes = ( nodes: NavigationNode[], @@ -187,8 +190,8 @@ export default class Collection extends ParanoidModel { } if ( - document?.parentDocumentId && - node?.id === document?.parentDocumentId + document.parentDocumentId && + node.id === document.parentDocumentId ) { path = [...newPath, document.asNavigationNode]; return; @@ -199,10 +202,10 @@ export default class Collection extends ParanoidModel { }; if (this.documents) { - travelNodes(this.documents, []); + travelNodes(this.documents, path); } - return path || []; + return path; } @action diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index e37c72ff09..36f0388210 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -67,43 +67,45 @@ async function documentMover({ invariant(newCollection, "collection should exist"); - // Remove the document from the current collection - const response = await collection?.removeDocumentInStructure(document, { - transaction, - }); + if (document.publishedAt) { + // Remove the document from the current collection + const response = await collection?.removeDocumentInStructure(document, { + transaction, + }); - const documentJson = response?.[0]; - const fromIndex = response?.[1] || 0; + const documentJson = response?.[0]; + const fromIndex = response?.[1] || 0; - if (!documentJson) { - throw ValidationError("The document was not found in the collection"); + if (!documentJson) { + throw ValidationError("The document was not found in the collection"); + } + + // if we're reordering from within the same parent + // the original and destination collection are the same, + // so when the initial item is removed above, the list will reduce by 1. + // We need to compensate for this when reordering + const toIndex = + index !== undefined && + document.parentDocumentId === parentDocumentId && + document.collectionId === collectionId && + fromIndex < index + ? index - 1 + : index; + + // Add the document and it's tree to the new collection + await newCollection.addDocumentToStructure(document, toIndex, { + documentJson, + transaction, + }); } - // if we're reordering from within the same parent - // the original and destination collection are the same, - // so when the initial item is removed above, the list will reduce by 1. - // We need to compensate for this when reordering - const toIndex = - index !== undefined && - document.parentDocumentId === parentDocumentId && - document.collectionId === collectionId && - fromIndex < index - ? index - 1 - : index; - // Update the properties on the document record document.collectionId = collectionId; document.parentDocumentId = parentDocumentId; document.lastModifiedById = user.id; document.updatedBy = user; - // Add the document and it's tree to the new collection - await newCollection.addDocumentToStructure(document, toIndex, { - documentJson, - transaction, - }); - - if (collection) { + if (collection && document.publishedAt) { result.collections.push(collection); } diff --git a/server/policies/document.test.ts b/server/policies/document.test.ts index 627837556a..9646286ac2 100644 --- a/server/policies/document.test.ts +++ b/server/policies/document.test.ts @@ -128,7 +128,7 @@ describe("no collection", () => { expect(abilities.createChildDocument).toEqual(false); expect(abilities.delete).toEqual(true); expect(abilities.download).toEqual(true); - expect(abilities.move).toEqual(false); + expect(abilities.move).toEqual(true); expect(abilities.permanentDelete).toEqual(false); expect(abilities.pin).toEqual(false); expect(abilities.pinToHome).toEqual(false); diff --git a/server/policies/document.ts b/server/policies/document.ts index ac5e612a7b..f7ee39f69e 100644 --- a/server/policies/document.ts +++ b/server/policies/document.ts @@ -174,14 +174,7 @@ allow(User, "move", Document, (user, document) => { if (document.deletedAt) { return false; } - if (!document.publishedAt) { - return false; - } - invariant( - document.collection, - "collection is missing, did you forget to include in the query scope?" - ); - if (cannot(user, "update", document.collection)) { + if (document.collection && cannot(user, "update", document.collection)) { return false; } return user.teamId === document.teamId; From d4da33424b530d03a59f4ea391b141ec77be790a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 7 Jan 2023 10:01:21 -0500 Subject: [PATCH 18/61] fix: Math block overrides heading backspace key behavior --- shared/editor/packages/full.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/shared/editor/packages/full.ts b/shared/editor/packages/full.ts index 66ccc29bf6..58e6e86ad7 100644 --- a/shared/editor/packages/full.ts +++ b/shared/editor/packages/full.ts @@ -38,8 +38,6 @@ const fullPackage: (typeof Node | typeof Mark | typeof Extension)[] = [ OrderedList, Embed, ListItem, - Math, - MathBlock, Attachment, Notice, Heading, @@ -53,6 +51,8 @@ const fullPackage: (typeof Node | typeof Mark | typeof Extension)[] = [ Folding, Keys, BlockMenuTrigger, + Math, + MathBlock, ]; export default fullPackage; From a333f4810283a9b89103dacd70067860a01ce114 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 7 Jan 2023 10:58:22 -0500 Subject: [PATCH 19/61] fix: Hanging } --- app/components/PageTitle.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/components/PageTitle.tsx b/app/components/PageTitle.tsx index 1ffacf4e39..03973c8319 100644 --- a/app/components/PageTitle.tsx +++ b/app/components/PageTitle.tsx @@ -17,7 +17,7 @@ const PageTitle = ({ title, favicon }: Props) => { return ( - {team?.name ? `${title} - ${team.name}` : `${title} - ${env.APP_NAME}}`} + {team?.name ? `${title} - ${team.name}` : `${title} - ${env.APP_NAME}`} {favicon ? ( From 53414ec3bad967a8701beba7a73bfd64c98daf6d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 7 Jan 2023 11:52:09 -0800 Subject: [PATCH 20/61] feat: Server side translation setup (#4657) * Server side translation setup * docs --- app/index.tsx | 2 +- app/test/setup.ts | 2 +- .../index.test.ts => app/utils/i18n.test.ts | 8 +- app/utils/i18n.ts | 51 ++++++++++++- i18next-parser.config.js | 17 +---- package.json | 1 + server/routes/api/hooks.ts | 73 +++++++++++++------ server/services/web.ts | 3 + server/services/worker.ts | 3 + server/utils/i18n.ts | 58 +++++++++++++++ shared/i18n/index.ts | 34 --------- shared/i18n/locales/en_US/translation.json | 6 ++ yarn.lock | 5 ++ 13 files changed, 185 insertions(+), 78 deletions(-) rename shared/i18n/index.test.ts => app/utils/i18n.test.ts (90%) create mode 100644 server/utils/i18n.ts diff --git a/app/index.tsx b/app/index.tsx index a9ac001288..cbcc0430ed 100644 --- a/app/index.tsx +++ b/app/index.tsx @@ -5,7 +5,6 @@ import { Provider } from "mobx-react"; import * as React from "react"; import { render } from "react-dom"; import { Router } from "react-router-dom"; -import { initI18n } from "@shared/i18n"; import stores from "~/stores"; import Analytics from "~/components/Analytics"; import Dialogs from "~/components/Dialogs"; @@ -15,6 +14,7 @@ import ScrollToTop from "~/components/ScrollToTop"; import Theme from "~/components/Theme"; import Toasts from "~/components/Toasts"; import env from "~/env"; +import { initI18n } from "~/utils/i18n"; import Desktop from "./components/DesktopEventHandler"; import LazyPolyfill from "./components/LazyPolyfills"; import Routes from "./routes"; diff --git a/app/test/setup.ts b/app/test/setup.ts index 64b8c6ee67..2fe3b36699 100644 --- a/app/test/setup.ts +++ b/app/test/setup.ts @@ -3,7 +3,7 @@ import localStorage from "../../__mocks__/localStorage"; import Enzyme from "enzyme"; import Adapter from "enzyme-adapter-react-16"; -import { initI18n } from "@shared/i18n"; +import { initI18n } from "../utils/i18n"; initI18n(); diff --git a/shared/i18n/index.test.ts b/app/utils/i18n.test.ts similarity index 90% rename from shared/i18n/index.test.ts rename to app/utils/i18n.test.ts index 64b7fdab5f..12752c0ce4 100644 --- a/shared/i18n/index.test.ts +++ b/app/utils/i18n.test.ts @@ -1,8 +1,8 @@ import i18n from "i18next"; -import de_DE from "./locales/de_DE/translation.json"; -import en_US from "./locales/en_US/translation.json"; -import pt_PT from "./locales/pt_PT/translation.json"; -import { initI18n } from "."; +import de_DE from "../../shared/i18n/locales/de_DE/translation.json"; +import en_US from "../../shared/i18n/locales/en_US/translation.json"; +import pt_PT from "../../shared/i18n/locales/pt_PT/translation.json"; +import { initI18n } from "./i18n"; describe("i18n env is unset", () => { beforeEach(() => { diff --git a/app/utils/i18n.ts b/app/utils/i18n.ts index 6089068bc5..6add909544 100644 --- a/app/utils/i18n.ts +++ b/app/utils/i18n.ts @@ -17,6 +17,11 @@ import { zhCN, zhTW, } from "date-fns/locale"; +import i18n from "i18next"; +import backend from "i18next-http-backend"; +import { initReactI18next } from "react-i18next"; +import { languages } from "@shared/i18n"; +import { unicodeCLDRtoBCP47, unicodeBCP47toCLDR } from "@shared/utils/date"; const locales = { de_DE: de, @@ -38,8 +43,50 @@ const locales = { zh_TW: zhTW, }; -export function dateLocale(userLocale: string | null | undefined) { - return userLocale ? locales[userLocale] : undefined; +/** + * Returns the date-fns locale object for the given user language preference. + * + * @param language The user language + * @returns The date-fns locale. + */ +export function dateLocale(language: string | null | undefined) { + return language ? locales[language] : undefined; +} + +/** + * Initializes i18n library, loading all available translations from the + * API backend. + * + * @param defaultLanguage The default language to use if the user's language + * is not supported. + * @returns i18n instance + */ +export function initI18n(defaultLanguage = "en_US") { + const lng = unicodeCLDRtoBCP47(defaultLanguage); + i18n + .use(backend) + .use(initReactI18next) + .init({ + compatibilityJSON: "v3", + backend: { + // this must match the path defined in routes. It's the path that the + // frontend UI code will hit to load missing translations. + loadPath: (languages: string[]) => + `/locales/${unicodeBCP47toCLDR(languages[0])}.json`, + }, + interpolation: { + escapeValue: false, + }, + react: { + useSuspense: false, + }, + lng, + fallbackLng: lng, + supportedLngs: languages.map(unicodeCLDRtoBCP47), + keySeparator: false, + returnNull: false, + }); + return i18n; } export { locales }; diff --git a/i18next-parser.config.js b/i18next-parser.config.js index a5ffa187aa..0d79a31af5 100644 --- a/i18next-parser.config.js +++ b/i18next-parser.config.js @@ -8,7 +8,9 @@ module.exports = { defaultNamespace: "translation", // Default namespace used in your i18next config - defaultValue: "", + defaultValue(locale, namespace, key) { + return key; + }, // Default value to give to empty keys indentation: 2, @@ -60,10 +62,6 @@ module.exports = { skipDefaultValues: false, // Whether to ignore default values. - useKeysAsDefaultValue: true, - // Whether to use the keys as the default value; ex. "Hello": "Hello", "World": "World" - // This option takes precedence over the `defaultValue` and `skipDefaultValues` options - verbose: false, // Display info about the parsing including some stats @@ -71,15 +69,6 @@ module.exports = { // Exit with an exit code of 1 on warnings customValueTemplate: null, - // If you wish to customize the value output the value as an object, you can set your own format. - // ${defaultValue} is the default value you set in your translation function. - // Any other custom property will be automatically extracted. - // - // Example: - // { - // message: "${defaultValue}", - // description: "${maxLength}", // t('my-key', {maxLength: 150}) - // } i18nextOptions: { compatibilityJSON: "v3", diff --git a/package.json b/package.json index 396ccb565b..57e6e6dba6 100644 --- a/package.json +++ b/package.json @@ -104,6 +104,7 @@ "gemoji": "6.x", "http-errors": "2.0.0", "i18next": "^22.4.8", + "i18next-fs-backend": "^2.1.1", "i18next-http-backend": "^2.1.1", "immutable": "^4.0.0", "inline-css": "^4.0.1", diff --git a/server/routes/api/hooks.ts b/server/routes/api/hooks.ts index 744f02dc23..8c1beb1003 100644 --- a/server/routes/api/hooks.ts +++ b/server/routes/api/hooks.ts @@ -1,4 +1,5 @@ import crypto from "crypto"; +import { t } from "i18next"; import Router from "koa-router"; import { escapeRegExp } from "lodash"; import { IntegrationService } from "@shared/types"; @@ -18,6 +19,7 @@ import { import SearchHelper from "@server/models/helpers/SearchHelper"; import { presentSlackAttachment } from "@server/presenters"; import { APIContext } from "@server/types"; +import { opts } from "@server/utils/i18n"; import * as Slack from "@server/utils/slack"; import { assertPresent } from "@server/validation"; @@ -150,21 +152,6 @@ router.post("hooks.slack", async (ctx: APIContext) => { assertPresent(user_id, "user_id is required"); verifySlackToken(token); - // Handle "help" command or no input - if (text.trim() === "help" || !text.trim()) { - ctx.body = { - response_type: "ephemeral", - text: "How to use /outline", - attachments: [ - { - text: - "To search your knowledge base use `/outline keyword`. \nYou’ve already learned how to get help with `/outline help`.", - }, - ], - }; - return; - } - let user, team; // attempt to find the corresponding team for this request based on the team_id team = await Team.findOne({ @@ -225,12 +212,39 @@ router.post("hooks.slack", async (ctx: APIContext) => { } } + // Handle "help" command or no input + if (text.trim() === "help" || !text.trim()) { + ctx.body = { + response_type: "ephemeral", + text: "How to use /outline", + attachments: [ + { + text: t( + "To search your knowledgebase use {{ command }}. \nYou’ve already learned how to get help with {{ command2 }}.", + { + command: `/outline keyword`, + command2: `/outline help`, + ...opts(user), + } + ), + }, + ], + }; + return; + } + // This should be super rare, how does someone end up being able to make a valid // request from Slack that connects to no teams in Outline. if (!team) { ctx.body = { response_type: "ephemeral", - text: `Sorry, we couldn’t find an integration for your team. Head to your ${env.APP_NAME} settings to set one up.`, + text: t( + `Sorry, we couldn’t find an integration for your team. Head to your {{ appName }} settings to set one up.`, + { + ...opts(user), + appName: env.APP_NAME, + } + ), }; return; } @@ -292,7 +306,13 @@ router.post("hooks.slack", async (ctx: APIContext) => { query: text, results: totalCount, }); - const haventSignedIn = `(It looks like you haven’t signed in to ${env.APP_NAME} yet, so results may be limited)`; + const haventSignedIn = t( + `It looks like you haven’t signed in to {{ appName }} yet, so results may be limited`, + { + ...opts(user), + appName: env.APP_NAME, + } + ); // Map search results to the format expected by the Slack API if (results.length) { @@ -312,7 +332,7 @@ router.post("hooks.slack", async (ctx: APIContext) => { ? [ { name: "post", - text: "Post to Channel", + text: t("Post to Channel", opts(user)), type: "button", value: result.document.id, }, @@ -324,15 +344,24 @@ router.post("hooks.slack", async (ctx: APIContext) => { ctx.body = { text: user - ? `This is what we found for "${text}"…` - : `This is what we found for "${text}" ${haventSignedIn}…`, + ? t(`This is what we found for "{{ term }}"`, { + ...opts(user), + term: text, + }) + : t(`This is what we found for "{{ term }}"`, { + term: text, + }) + ` (${haventSignedIn})…`, attachments, }; } else { ctx.body = { text: user - ? `No results for "${text}"` - : `No results for "${text}" ${haventSignedIn}`, + ? t(`No results for "{{ term }}"`, { + ...opts(user), + term: text, + }) + : t(`No results for "{{ term }}"`, { term: text }) + + ` (${haventSignedIn})…`, }; } }); diff --git a/server/services/web.ts b/server/services/web.ts index af89f585ee..a57947184f 100644 --- a/server/services/web.ts +++ b/server/services/web.ts @@ -9,6 +9,7 @@ import mount from "koa-mount"; import enforceHttps, { xForwardedProtoResolver } from "koa-sslify"; import env from "@server/env"; import Logger from "@server/logging/Logger"; +import { initI18n } from "@server/utils/i18n"; import routes from "../routes"; import api from "../routes/api"; import auth from "../routes/auth"; @@ -37,6 +38,8 @@ if (env.CDN_URL) { } export default function init(app: Koa = new Koa()): Koa { + initI18n(); + if (isProduction) { // Force redirect to HTTPS protocol unless explicitly disabled if (env.FORCE_HTTPS) { diff --git a/server/services/worker.ts b/server/services/worker.ts index 71588f9a50..b2a5449c4e 100644 --- a/server/services/worker.ts +++ b/server/services/worker.ts @@ -1,6 +1,7 @@ import Logger from "@server/logging/Logger"; import { setResource } from "@server/logging/tracer"; import { traceFunction } from "@server/logging/tracing"; +import { initI18n } from "@server/utils/i18n"; import { globalEventQueue, processorEventQueue, @@ -11,6 +12,8 @@ import processors from "../queues/processors"; import tasks from "../queues/tasks"; export default function init() { + initI18n(); + // This queue processes the global event bus globalEventQueue.process( traceFunction({ diff --git a/server/utils/i18n.ts b/server/utils/i18n.ts new file mode 100644 index 0000000000..0e43db3af7 --- /dev/null +++ b/server/utils/i18n.ts @@ -0,0 +1,58 @@ +import path from "path"; +import i18n from "i18next"; +import backend from "i18next-fs-backend"; +import { languages } from "@shared/i18n"; +import { unicodeBCP47toCLDR, unicodeCLDRtoBCP47 } from "@shared/utils/date"; +import env from "@server/env"; +import { User } from "@server/models"; + +/** + * Returns i18n options for the given user or the default server language if + * no user is provided. + * + * @param user The user to get options for + * @returns i18n options + */ +export function opts(user?: User | null) { + return { + lng: unicodeCLDRtoBCP47(user?.language ?? env.DEFAULT_LANGUAGE), + }; +} + +/** + * Initializes i18n library, loading all available translations from the + * filesystem. + * + * @returns i18n instance + */ +export function initI18n() { + const lng = unicodeCLDRtoBCP47(env.DEFAULT_LANGUAGE); + i18n.use(backend).init({ + compatibilityJSON: "v3", + backend: { + loadPath: (language: string) => { + return path.resolve( + path.join( + __dirname, + "..", + "..", + "shared", + "i18n", + "locales", + unicodeBCP47toCLDR(language), + "translation.json" + ) + ); + }, + }, + preload: languages.map(unicodeCLDRtoBCP47), + interpolation: { + escapeValue: false, + }, + lng, + fallbackLng: lng, + keySeparator: false, + returnNull: false, + }); + return i18n; +} diff --git a/shared/i18n/index.ts b/shared/i18n/index.ts index c8ab0a6170..5eb04ad5cd 100644 --- a/shared/i18n/index.ts +++ b/shared/i18n/index.ts @@ -1,8 +1,3 @@ -import i18n from "i18next"; -import backend from "i18next-http-backend"; -import { initReactI18next } from "react-i18next"; -import { unicodeBCP47toCLDR, unicodeCLDRtoBCP47 } from "../utils/date"; - // Note: Updating the available languages? Make sure to also update the // locales array in app/utils/i18n.js to enable translation for timestamps. export const languageOptions = [ @@ -77,32 +72,3 @@ export const languageOptions = [ ]; export const languages: string[] = languageOptions.map((i) => i.value); - -export const initI18n = (defaultLanguage = "en_US") => { - const lng = unicodeCLDRtoBCP47(defaultLanguage); - i18n - .use(backend) - .use(initReactI18next) - .init({ - compatibilityJSON: "v3", - backend: { - // this must match the path defined in routes. It's the path that the - // frontend UI code will hit to load missing translations. - loadPath: (languages: string[]) => - `/locales/${unicodeBCP47toCLDR(languages[0])}.json`, - }, - interpolation: { - escapeValue: false, - }, - react: { - useSuspense: false, - }, - lng, - fallbackLng: lng, - supportedLngs: languages.map(unicodeCLDRtoBCP47), - // Uncomment when debugging translation framework, otherwise it's noisy - keySeparator: false, - returnNull: false, - }); - return i18n; -}; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index c4af6ff79f..3a94a8e42b 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -823,5 +823,11 @@ "This month": "This month", "Last month": "Last month", "This year": "This year", + "To search your knowledgebase use {{ command }}. \nYou’ve already learned how to get help with {{ command2 }}.": "To search your knowledgebase use {{ command }}. \nYou’ve already learned how to get help with {{ command2 }}.", + "Sorry, we couldn’t find an integration for your team. Head to your {{ appName }} settings to set one up.": "Sorry, we couldn’t find an integration for your team. Head to your {{ appName }} settings to set one up.", + "It looks like you haven’t signed in to {{ appName }} yet, so results may be limited": "It looks like you haven’t signed in to {{ appName }} yet, so results may be limited", + "Post to Channel": "Post to Channel", + "This is what we found for \"{{ term }}\"": "This is what we found for \"{{ term }}\"", + "No results for \"{{ term }}\"": "No results for \"{{ term }}\"", "Uploading": "Uploading" } diff --git a/yarn.lock b/yarn.lock index 8d03e6319b..0873b1a16e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8798,6 +8798,11 @@ husky@^8.0.2: resolved "https://registry.yarnpkg.com/husky/-/husky-8.0.2.tgz#5816a60db02650f1f22c8b69b928fd6bcd77a236" integrity sha512-Tkv80jtvbnkK3mYWxPZePGFpQ/tT3HNSs/sasF9P2YfkMezDl3ON37YN6jUUI4eTg5LcyVynlb6r4eyvOmspvg== +i18next-fs-backend@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/i18next-fs-backend/-/i18next-fs-backend-2.1.1.tgz#07c6393be856c5a398e3dfc1257bf8439841cd89" + integrity sha512-FTnj+UmNgT3YRml5ruRv0jMZDG7odOL/OP5PF5mOqvXud2vHrPOOs68Zdk6iqzL47cnnM0ZVkK2BAvpFeDJToA== + i18next-http-backend@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/i18next-http-backend/-/i18next-http-backend-2.1.1.tgz#72a21d61c2e96eea9ad45ba1b9dd0090e119709a" From 9617a15ae8b25804138a8dcdaf813855b02220be Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 7 Jan 2023 15:26:06 -0500 Subject: [PATCH 21/61] fix: No value supplied for attribute src It shouldn't be possible to have an image node with no src, but it does happen occassionally and this prevents the document from persisting. It's better to have a broken image than a doc that won't save --- shared/editor/nodes/Image.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/shared/editor/nodes/Image.tsx b/shared/editor/nodes/Image.tsx index b8dde6fffb..b837a74b12 100644 --- a/shared/editor/nodes/Image.tsx +++ b/shared/editor/nodes/Image.tsx @@ -168,7 +168,9 @@ export default class Image extends Node { return { inline: true, attrs: { - src: {}, + src: { + default: "", + }, width: { default: undefined, }, From cbfb7d2c23ef3690222242800ebb778779a6ffe2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Jan 2023 07:31:22 -0800 Subject: [PATCH 22/61] chore(deps): bump luxon from 3.0.1 to 3.2.1 (#4660) Bumps [luxon](https://github.com/moment/luxon) from 3.0.1 to 3.2.1. - [Release notes](https://github.com/moment/luxon/releases) - [Changelog](https://github.com/moment/luxon/blob/master/CHANGELOG.md) - [Commits](https://github.com/moment/luxon/compare/3.0.1...3.2.1) --- updated-dependencies: - dependency-name: luxon dependency-type: indirect ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index 0873b1a16e..82f9e7bd9e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10853,9 +10853,9 @@ lru_map@^0.3.3: integrity sha1-tcg1G5Rky9dQM1p5ZQoOwOVhGN0= luxon@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/luxon/-/luxon-3.0.1.tgz#6901111d10ad06fd267ad4e4128a84bef8a77299" - integrity sha512-hF3kv0e5gwHQZKz4wtm4c+inDtyc7elkanAsBq+fundaCdUBNJB1dHEGUZIM6SfSBUlbVFduPwEtNjFK8wLtcw== + version "3.2.1" + resolved "https://registry.yarnpkg.com/luxon/-/luxon-3.2.1.tgz#14f1af209188ad61212578ea7e3d518d18cee45f" + integrity sha512-QrwPArQCNLAKGO/C+ZIilgIuDnEnKx5QYODdDtbFaxzsbZcc/a7WFq7MhsVYgRlwawLtvOUESTlfJ+hc/USqPg== magic-string@^0.25.0, magic-string@^0.25.7: version "0.25.7" From 31c47ab37b13342473cc551dc07e8c46316a6f6e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Jan 2023 15:39:52 -0800 Subject: [PATCH 23/61] chore(deps): bump @joplin/turndown-plugin-gfm from 1.0.44 to 1.0.45 (#4663) Bumps [@joplin/turndown-plugin-gfm](https://github.com/laurent22/joplin-turndown-plugin-gfm) from 1.0.44 to 1.0.45. - [Release notes](https://github.com/laurent22/joplin-turndown-plugin-gfm/releases) - [Commits](https://github.com/laurent22/joplin-turndown-plugin-gfm/commits) --- updated-dependencies: - dependency-name: "@joplin/turndown-plugin-gfm" dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 57e6e6dba6..b8e721f37d 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,7 @@ "@getoutline/y-prosemirror": "^1.0.18", "@hocuspocus/provider": "^1.0.0-beta.6", "@hocuspocus/server": "^1.0.0-beta.6", - "@joplin/turndown-plugin-gfm": "^1.0.44", + "@joplin/turndown-plugin-gfm": "^1.0.45", "@juggle/resize-observer": "^3.4.0", "@outlinewiki/koa-passport": "^4.2.1", "@outlinewiki/passport-azure-ad-oauth2": "^0.1.0", diff --git a/yarn.lock b/yarn.lock index 82f9e7bd9e..aab9a094e7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2086,10 +2086,10 @@ resolved "https://registry.yarnpkg.com/@jonkemp/package-utils/-/package-utils-1.0.8.tgz#4bce132a18f34407a88bb15c28bd3ed3030c4776" integrity sha512-bIcKnH5YmtTYr7S6J3J86dn/rFiklwRpOqbTOQ9C0WMmR9FKHVb3bxs2UYfqEmNb93O4nbA97sb6rtz33i9SyA== -"@joplin/turndown-plugin-gfm@^1.0.44": - version "1.0.44" - resolved "https://registry.yarnpkg.com/@joplin/turndown-plugin-gfm/-/turndown-plugin-gfm-1.0.44.tgz#028e4c56bf58e57a4d0d923bb7d10a21c30d5c7d" - integrity sha512-lpVI/fpj0CKzWzpsOxsmqwjWlIrw+IZlIEz3h8Vqoviz8dCYbqSSY/4VxpiUDmBpxX/3Xk73R5BfzqiAHBmYqA== +"@joplin/turndown-plugin-gfm@^1.0.45": + version "1.0.45" + resolved "https://registry.yarnpkg.com/@joplin/turndown-plugin-gfm/-/turndown-plugin-gfm-1.0.45.tgz#c37cb58ecad97a6385fc27350b7aead8236e30c6" + integrity sha512-RUQfMrFqFp2wB0mOZPGOTq6LVUVBOhQg87+ecv1+qF2gTHZm3jQd77iV5Eddbg2WjCj06eCG99et3kdPf0YwVw== "@jridgewell/gen-mapping@^0.1.0": version "0.1.1" From 3e7f823e179a127b88689e894a02077840479d7e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Jan 2023 19:02:19 -0800 Subject: [PATCH 24/61] chore(deps): bump aws-sdk from 2.1189.0 to 2.1290.0 (#4664) Bumps [aws-sdk](https://github.com/aws/aws-sdk-js) from 2.1189.0 to 2.1290.0. - [Release notes](https://github.com/aws/aws-sdk-js/releases) - [Changelog](https://github.com/aws/aws-sdk-js/blob/master/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js/compare/v2.1189.0...v2.1290.0) --- updated-dependencies: - dependency-name: aws-sdk dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index b8e721f37d..99cc179132 100644 --- a/package.json +++ b/package.json @@ -72,7 +72,7 @@ "@tommoor/remove-markdown": "^0.3.2", "@types/mermaid": "^9.1.0", "autotrack": "^2.4.1", - "aws-sdk": "^2.1189.0", + "aws-sdk": "^2.1290.0", "babel-plugin-lodash": "^3.3.4", "babel-plugin-styled-components": "^2.0.7", "babel-plugin-transform-class-properties": "^6.24.1", diff --git a/yarn.lock b/yarn.lock index aab9a094e7..381a254d31 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4395,10 +4395,10 @@ available-typed-arrays@^1.0.5: resolved "https://registry.yarnpkg.com/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz#92f95616501069d07d10edb2fc37d3e1c65123b7" integrity sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw== -aws-sdk@^2.1189.0: - version "2.1189.0" - resolved "https://registry.yarnpkg.com/aws-sdk/-/aws-sdk-2.1189.0.tgz#8dd6b48dd7896642af8e2f86e026932a28e380d5" - integrity sha512-EqluXSo8XAR086nF9UAtPYwUm82ZIRqg8OmHBRQyftcrD1Z0pqMmiuvacXoEAJ/4UU8KKafbpYarxx8rH/pZjQ== +aws-sdk@^2.1290.0: + version "2.1290.0" + resolved "https://registry.yarnpkg.com/aws-sdk/-/aws-sdk-2.1290.0.tgz#cb4e56656cb4ad08a645cd016380df4b324f8261" + integrity sha512-qRrXLgK4FpkdxeagjrHuhtEEvYrvRbddTBg1I7KBuMCIhXHzSS3nEUmdZjdyMuQJEvt0BCJjwVkNh8e/5TauDQ== dependencies: buffer "4.9.2" events "1.1.1" From fddcbbd7af38e7ad666bcce04b73135568c5e523 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Jan 2023 19:02:44 -0800 Subject: [PATCH 25/61] chore(deps): bump react-hook-form from 7.37.0 to 7.41.5 (#4667) Bumps [react-hook-form](https://github.com/react-hook-form/react-hook-form) from 7.37.0 to 7.41.5. - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.37.0...v7.41.5) --- updated-dependencies: - dependency-name: react-hook-form dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 99cc179132..9a70d7069f 100644 --- a/package.json +++ b/package.json @@ -179,7 +179,7 @@ "react-dom": "^17.0.2", "react-dropzone": "^11.3.2", "react-helmet": "^6.1.0", - "react-hook-form": "^7.37.0", + "react-hook-form": "^7.41.5", "react-i18next": "^12.1.1", "react-merge-refs": "^2.0.1", "react-portal": "^4.2.0", diff --git a/yarn.lock b/yarn.lock index 381a254d31..4cc338dbf6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12927,10 +12927,10 @@ react-helmet@^6.1.0: react-fast-compare "^3.1.1" react-side-effect "^2.1.0" -react-hook-form@^7.37.0: - version "7.37.0" - resolved "https://registry.yarnpkg.com/react-hook-form/-/react-hook-form-7.37.0.tgz#4d1738f092d3d8a3ade34ee892d97350b1032b19" - integrity sha512-6NFTxsnw+EXSpNNvLr5nFMjPdYKRryQcelTHg7zwBB6vAzfPIcZq4AExP4heVlwdzntepQgwiOQW4z7Mr99Lsg== +react-hook-form@^7.41.5: + version "7.41.5" + resolved "https://registry.yarnpkg.com/react-hook-form/-/react-hook-form-7.41.5.tgz#dcd0e7438c15044eadc99df6deb889da5858a03b" + integrity sha512-DAKjSJ7X9f16oQrP3TW2/eD9N6HOgrmIahP4LOdFphEWVfGZ2LulFd6f6AQ/YS/0cx/5oc4j8a1PXxuaurWp/Q== react-i18next@^12.1.1: version "12.1.1" From 6be7409d8582d142eeff0eb80346ee2a8aa0b5b2 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 10 Jan 2023 18:13:59 -0500 Subject: [PATCH 26/61] fix: Mistake in i18n key --- app/components/GroupListItem.tsx | 2 +- shared/i18n/locales/en_US/translation.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/components/GroupListItem.tsx b/app/components/GroupListItem.tsx index 5f5fa4c5d9..f19a37360d 100644 --- a/app/components/GroupListItem.tsx +++ b/app/components/GroupListItem.tsx @@ -47,7 +47,7 @@ function GroupListItem({ group, showFacepile, renderActions }: Props) { } title={{group.name}} - subtitle={t("{{ count }} members", { count: memberCount })} + subtitle={t("{{ count }} member", { count: memberCount })} actions={ {showFacepile && ( diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 3a94a8e42b..5c91bf72d6 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -168,8 +168,8 @@ "You will receive an email when it's complete.": "You will receive an email when it's complete.", "A ZIP file containing the images, and documents in the Markdown format.": "A ZIP file containing the images, and documents in the Markdown format.", "A ZIP file containing the images, and documents as HTML files.": "A ZIP file containing the images, and documents as HTML files.", - "{{ count }} members": "{{ count }} members", - "{{ count }} members_plural": "{{ count }} members", + "{{ count }} member": "{{ count }} member", + "{{ count }} member_plural": "{{ count }} members", "Group members": "Group members", "Icon": "Icon", "Show menu": "Show menu", From 64b72bcf82a857e0806303eb82bae2f2b500c69e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 10 Jan 2023 20:32:37 -0500 Subject: [PATCH 27/61] /bin/bash -> /bin/sh for Docker --- build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sh b/build.sh index 1b8fe88cc8..73cd81177d 100755 --- a/build.sh +++ b/build.sh @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +#!/bin/sh yarn babel --extensions .ts,.tsx --quiet -d ./build/server ./server yarn babel --extensions .ts,.tsx --quiet -d ./build/shared ./shared From d5158f0a3466c1e4ca7a31dae758ffd5eb395bba Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 10 Jan 2023 20:32:43 -0500 Subject: [PATCH 28/61] 0.67.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 9a70d7069f..6787f57daa 100644 --- a/package.json +++ b/package.json @@ -358,5 +358,5 @@ "jpeg-js": "0.4.4", "qs": "6.9.7" }, - "version": "0.66.2" + "version": "0.67.0" } From 785b9888dd4cfc4a61dad902f4dd2c2a97f23653 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 11 Jan 2023 09:07:15 -0500 Subject: [PATCH 29/61] Respond to slack url verification challenge with JSON instead of raw body --- server/routes/api/hooks.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/server/routes/api/hooks.ts b/server/routes/api/hooks.ts index 8c1beb1003..30d7e84e74 100644 --- a/server/routes/api/hooks.ts +++ b/server/routes/api/hooks.ts @@ -46,8 +46,14 @@ function verifySlackToken(token: string) { // triggered by a user posting a getoutline.com link in Slack router.post("hooks.unfurl", async (ctx: APIContext) => { const { challenge, token, event } = ctx.request.body; + + // See URL verification handshake documentation on this page: + // https://api.slack.com/apis/connections/events-api if (challenge) { - return (ctx.body = ctx.request.body.challenge); + ctx.body = { + challenge, + }; + return; } assertPresent(token, "token is required"); From 4a97b35d5a61f5e924f5c6084a212c544f90036a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 11 Jan 2023 20:56:14 -0500 Subject: [PATCH 30/61] fix: Collection structure update on document move --- server/commands/documentMover.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index 36f0388210..6f8ed56e6f 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -71,6 +71,7 @@ async function documentMover({ // Remove the document from the current collection const response = await collection?.removeDocumentInStructure(document, { transaction, + save: collectionChanged, }); const documentJson = response?.[0]; @@ -92,19 +93,25 @@ async function documentMover({ ? index - 1 : index; + // Update the properties on the document record, this must be done after + // the toIndex is calculated above + document.collectionId = collectionId; + document.parentDocumentId = parentDocumentId; + document.lastModifiedById = user.id; + document.updatedBy = user; + // Add the document and it's tree to the new collection await newCollection.addDocumentToStructure(document, toIndex, { documentJson, transaction, }); + } else { + document.collectionId = collectionId; + document.parentDocumentId = parentDocumentId; + document.lastModifiedById = user.id; + document.updatedBy = user; } - // Update the properties on the document record - document.collectionId = collectionId; - document.parentDocumentId = parentDocumentId; - document.lastModifiedById = user.id; - document.updatedBy = user; - if (collection && document.publishedAt) { result.collections.push(collection); } From 3be170ddb835151e5535ca533572192c1107e153 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 11 Jan 2023 21:27:37 -0500 Subject: [PATCH 31/61] 0.67.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 6787f57daa..061eabff03 100644 --- a/package.json +++ b/package.json @@ -358,5 +358,5 @@ "jpeg-js": "0.4.4", "qs": "6.9.7" }, - "version": "0.67.0" + "version": "0.67.1" } From 17a8dbb3f0b9b9d375d8ba21ae4e4f5bcff69a96 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 12 Jan 2023 11:15:54 -0500 Subject: [PATCH 32/61] fix: Prevent moving documents into drafts --- .../Sidebar/components/DocumentLink.tsx | 4 +++- server/routes/api/documents/documents.test.ts | 20 +++++++++++++++++++ server/routes/api/documents/documents.ts | 4 ++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index bc7ce632a8..8b3eec6877 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -180,7 +180,9 @@ function InnerDocumentLink( setExpanded(true); }, canDrop: (_item, monitor) => - !!pathToNode && !pathToNode.includes(monitor.getItem().id), + !isDraft && + !!pathToNode && + !pathToNode.includes(monitor.getItem().id), hover: (_item, monitor) => { // Enables expansion of document children when hovering over the document // for more than half a second. diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 2a35bf62e5..568aac9c2a 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -1826,6 +1826,26 @@ describe("#documents.move", () => { ); }); + it("should fail if attempting to nest doc within a draft", async () => { + const { user, document, collection } = await seed(); + const draft = await buildDraftDocument({ + userId: user.id, + teamId: document.teamId, + collectionId: collection.id, + }); + const res = await server.post("/api/documents.move", { + body: { + id: document.id, + collectionId: collection.id, + parentDocumentId: draft.id, + token: user.getJwtToken(), + }, + }); + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("Cannot move document inside a draft"); + }); + it("should require id", async () => { const { user } = await seed(); const res = await server.post("/api/documents.move", { diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index f73b19b86d..b5a0f3acd5 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -904,6 +904,10 @@ router.post( userId: user.id, }); authorize(user, "update", parent); + + if (!parent.publishedAt) { + throw InvalidRequestError("Cannot move document inside a draft"); + } } const { From e347404502afbf2a1c0a041ac1b93d8ee31d15c0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 12 Jan 2023 21:48:09 -0500 Subject: [PATCH 33/61] chore: Improvements to document move behavior (#4689) * chore: Improvements to document move behavior * test --- app/scenes/DocumentMove.tsx | 7 --- server/commands/documentMover.test.ts | 49 +++++++++---------- server/commands/documentMover.ts | 5 +- server/models/Collection.test.ts | 47 ++++++++++++------ server/models/Collection.ts | 33 +++++++------ server/models/Document.ts | 36 ++++++++++++-- server/routes/api/documents/documents.test.ts | 4 +- 7 files changed, 112 insertions(+), 69 deletions(-) diff --git a/app/scenes/DocumentMove.tsx b/app/scenes/DocumentMove.tsx index e333bec133..6ce2ec232d 100644 --- a/app/scenes/DocumentMove.tsx +++ b/app/scenes/DocumentMove.tsx @@ -63,13 +63,6 @@ function DocumentMove({ document, onRequestClose }: Props) { if (onlyShowCollections) { results = results.filter((result) => result.type === "collection"); } else { - // Exclude root from search results if document is already at the root - if (!document.parentDocumentId) { - results = results.filter( - (result) => result.id !== document.collectionId - ); - } - // Exclude document if on the path to result, or the same result results = results.filter( (result) => diff --git a/server/commands/documentMover.test.ts b/server/commands/documentMover.test.ts index 5c80613a2d..8627aaded3 100644 --- a/server/commands/documentMover.test.ts +++ b/server/commands/documentMover.test.ts @@ -1,10 +1,6 @@ import { sequelize } from "@server/database/sequelize"; import Pin from "@server/models/Pin"; -import { - buildDocument, - buildCollection, - buildUser, -} from "@server/test/factories"; +import { buildDocument, buildCollection } from "@server/test/factories"; import { setupTestDatabase, seed } from "@server/test/support"; import documentMover from "./documentMover"; @@ -25,28 +21,31 @@ describe("documentMover", () => { expect(response.documents.length).toEqual(1); }); - it("should error when not in source collection documentStructure", async () => { - const user = await buildUser(); - const collection = await buildCollection({ - teamId: user.teamId, - }); - const document = await buildDocument({ + it("should succeed when not in source collection documentStructure", async () => { + const { document, user, collection } = await seed(); + const newDocument = await buildDocument({ + parentDocumentId: document.id, collectionId: collection.id, + teamId: collection.teamId, + userId: collection.createdById, + title: "Child document", + text: "content", }); - await document.archive(user.id); - - let error; - try { - await documentMover({ - user, - document, - collectionId: collection.id, - ip, - }); - } catch (err) { - error = err; - } - expect(error).toBeTruthy(); + const response = await documentMover({ + user, + document, + collectionId: collection.id, + parentDocumentId: undefined, + index: 0, + ip, + }); + expect(response.collections[0].documentStructure![0].children[0].id).toBe( + newDocument.id + ); + expect(response.collections.length).toEqual(1); + expect(response.documents.length).toEqual(1); + expect(response.documents[0].collection?.id).toEqual(collection.id); + expect(response.documents[0].updatedBy.id).toEqual(user.id); }); it("should move with children", async () => { diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index 6f8ed56e6f..dc6502d331 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -1,6 +1,5 @@ import invariant from "invariant"; import { Transaction } from "sequelize"; -import { ValidationError } from "@server/errors"; import { traceFunction } from "@server/logging/tracing"; import { User, Document, Collection, Pin, Event } from "@server/models"; import pinDestroyer from "./pinDestroyer"; @@ -74,11 +73,11 @@ async function documentMover({ save: collectionChanged, }); - const documentJson = response?.[0]; + let documentJson = response?.[0]; const fromIndex = response?.[1] || 0; if (!documentJson) { - throw ValidationError("The document was not found in the collection"); + documentJson = await document.toNavigationNode({ transaction }); } // if we're reordering from within the same parent diff --git a/server/models/Collection.test.ts b/server/models/Collection.test.ts index 38a159137d..68d27159c8 100644 --- a/server/models/Collection.test.ts +++ b/server/models/Collection.test.ts @@ -33,7 +33,10 @@ describe("getDocumentParents", () => { const document = await buildDocument(); const collection = await buildCollection({ documentStructure: [ - { ...parent.toJSON(), children: [document.toJSON()] }, + { + ...(await parent.toNavigationNode()), + children: [await document.toNavigationNode()], + }, ], }); const result = collection.getDocumentParents(document.id); @@ -46,7 +49,10 @@ describe("getDocumentParents", () => { const document = await buildDocument(); const collection = await buildCollection({ documentStructure: [ - { ...parent.toJSON(), children: [document.toJSON()] }, + { + ...(await parent.toNavigationNode()), + children: [await document.toNavigationNode()], + }, ], }); const result = collection.getDocumentParents(parent.id); @@ -66,9 +72,11 @@ describe("getDocumentTree", () => { test("should return document tree", async () => { const document = await buildDocument(); const collection = await buildCollection({ - documentStructure: [document.toJSON()], + documentStructure: [await document.toNavigationNode()], }); - expect(collection.getDocumentTree(document.id)).toEqual(document.toJSON()); + expect(collection.getDocumentTree(document.id)).toEqual( + await document.toNavigationNode() + ); }); test("should return nested documents in tree", async () => { @@ -76,15 +84,20 @@ describe("getDocumentTree", () => { const document = await buildDocument(); const collection = await buildCollection({ documentStructure: [ - { ...parent.toJSON(), children: [document.toJSON()] }, + { + ...(await parent.toNavigationNode()), + children: [await document.toNavigationNode()], + }, ], }); expect(collection.getDocumentTree(parent.id)).toEqual({ - ...parent.toJSON(), - children: [document.toJSON()], + ...(await parent.toNavigationNode()), + children: [await document.toNavigationNode()], }); - expect(collection.getDocumentTree(document.id)).toEqual(document.toJSON()); + expect(collection.getDocumentTree(document.id)).toEqual( + await document.toNavigationNode() + ); }); }); @@ -92,10 +105,11 @@ describe("#addDocumentToStructure", () => { test("should add as last element without index", async () => { const { collection } = await seed(); const id = uuidv4(); - const newDocument = new Document({ + const newDocument = await buildDocument({ id, title: "New end node", parentDocumentId: null, + teamId: collection.teamId, }); await collection.addDocumentToStructure(newDocument); expect(collection.documentStructure!.length).toBe(2); @@ -105,10 +119,11 @@ describe("#addDocumentToStructure", () => { test("should add with an index", async () => { const { collection } = await seed(); const id = uuidv4(); - const newDocument = new Document({ + const newDocument = await buildDocument({ id, title: "New end node", parentDocumentId: null, + teamId: collection.teamId, }); await collection.addDocumentToStructure(newDocument, 1); expect(collection.documentStructure!.length).toBe(2); @@ -118,10 +133,11 @@ describe("#addDocumentToStructure", () => { test("should add as a child if with parent", async () => { const { collection, document } = await seed(); const id = uuidv4(); - const newDocument = new Document({ + const newDocument = await buildDocument({ id, title: "New end node", parentDocumentId: document.id, + teamId: collection.teamId, }); await collection.addDocumentToStructure(newDocument, 1); expect(collection.documentStructure!.length).toBe(1); @@ -132,16 +148,18 @@ describe("#addDocumentToStructure", () => { test("should add as a child if with parent with index", async () => { const { collection, document } = await seed(); - const newDocument = new Document({ + const newDocument = await buildDocument({ id: uuidv4(), title: "node", parentDocumentId: document.id, + teamId: collection.teamId, }); const id = uuidv4(); - const secondDocument = new Document({ + const secondDocument = await buildDocument({ id, title: "New start node", parentDocumentId: document.id, + teamId: collection.teamId, }); await collection.addDocumentToStructure(newDocument); await collection.addDocumentToStructure(secondDocument, 0); @@ -154,10 +172,11 @@ describe("#addDocumentToStructure", () => { test("should append supplied json over document's own", async () => { const { collection } = await seed(); const id = uuidv4(); - const newDocument = new Document({ + const newDocument = await buildDocument({ id: uuidv4(), title: "New end node", parentDocumentId: null, + teamId: collection.teamId, }); await collection.addDocumentToStructure(newDocument, undefined, { documentJson: { diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 1660defa1e..287f344287 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -554,7 +554,7 @@ class Collection extends ParanoidModel { */ updateDocument = async function ( updatedDocument: Document, - options?: { transaction?: Transaction | null } + options?: { transaction?: Transaction | null | undefined } ) { if (!this.documentStructure) { return; @@ -563,21 +563,23 @@ class Collection extends ParanoidModel { const { id } = updatedDocument; const updateChildren = (documents: NavigationNode[]) => { - return documents.map((document) => { - if (document.id === id) { - document = { - ...(updatedDocument.toJSON() as NavigationNode), - children: document.children, - }; - } else { - document.children = updateChildren(document.children); - } + return Promise.all( + documents.map(async (document) => { + if (document.id === id) { + document = { + ...(await updatedDocument.toNavigationNode(options)), + children: document.children, + }; + } else { + document.children = await updateChildren(document.children); + } - return document; - }); + return document; + }) + ); }; - this.documentStructure = updateChildren(this.documentStructure); + this.documentStructure = await updateChildren(this.documentStructure); // Sequelize doesn't seem to set the value with splice on JSONB field // https://github.com/sequelize/sequelize/blob/e1446837196c07b8ff0c23359b958d68af40fd6d/src/model.js#L3937 this.changed("documentStructure", true); @@ -602,7 +604,10 @@ class Collection extends ParanoidModel { } // If moving existing document with children, use existing structure - const documentJson = { ...document.toJSON(), ...options.documentJson }; + const documentJson = { + ...(await document.toNavigationNode(options)), + ...options.documentJson, + }; if (!document.parentDocumentId) { // Note: Index is supported on DB level but it's being ignored diff --git a/server/models/Document.ts b/server/models/Document.ts index bb98a53142..563053d2cd 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -36,6 +36,7 @@ import parseTitle from "@shared/utils/parseTitle"; import { SLUG_URL_REGEX } from "@shared/utils/urlHelpers"; import { DocumentValidation } from "@shared/validations"; import slugify from "@server/utils/slugify"; +import type { NavigationNode } from "~/types"; import Backlink from "./Backlink"; import Collection from "./Collection"; import FileOperation from "./FileOperation"; @@ -750,14 +751,41 @@ class Document extends ParanoidModel { return notEmpty ? lines[1] : ""; }; - toJSON = () => { - // Warning: only use for new documents as order of children is - // handled in the collection's documentStructure + /** + * Returns a JSON representation of the document suitable for use in the + * collection documentStructure. + * + * @param options Optional transaction to use for the query + * @returns Promise resolving to a NavigationNode + */ + toNavigationNode = async (options?: { + transaction?: Transaction | null | undefined; + }): Promise => { + const childDocuments = await (this.constructor as typeof Document) + .unscoped() + .findAll({ + where: { + teamId: this.teamId, + parentDocumentId: this.id, + archivedAt: { + [Op.is]: null, + }, + publishedAt: { + [Op.ne]: null, + }, + }, + transaction: options?.transaction, + }); + + const children = await Promise.all( + childDocuments.map((child) => child.toNavigationNode(options)) + ); + return { id: this.id, title: this.title, url: this.url, - children: [], + children, }; }; } diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 568aac9c2a..796ade0835 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -231,7 +231,7 @@ describe("#documents.info", () => { expect(body.data.document.id).toEqual(document.id); expect(body.data.document.createdBy).toEqual(undefined); expect(body.data.document.updatedBy).toEqual(undefined); - expect(body.data.sharedTree).toEqual(document.toJSON()); + expect(body.data.sharedTree).toEqual(await document.toNavigationNode()); }); it("should not return sharedTree if child documents not shared", async () => { const { document, user } = await seed(); @@ -2622,7 +2622,7 @@ describe("#documents.update", () => { title: "Another doc", children: [], }, - { ...document.toJSON(), children: [] }, + { ...(await document.toNavigationNode()), children: [] }, ], }, ]; From d20f379943f46adb39a7b8e05ec8afa6381d490a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 12 Jan 2023 22:39:14 -0500 Subject: [PATCH 34/61] feat: Publish and Unpublish available in command menu fix: Add default error handling for menu actions --- app/actions/definitions/documents.tsx | 59 ++++++++++++++++++++++ app/actions/index.ts | 12 ++++- app/menus/DocumentMenu.tsx | 19 ++----- shared/i18n/locales/en_US/translation.json | 8 +-- 4 files changed, 77 insertions(+), 21 deletions(-) diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 871e7406e3..a9275e4894 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -20,6 +20,8 @@ import { ShuffleIcon, HistoryIcon, LightBulbIcon, + UnpublishIcon, + PublishIcon, } from "outline-icons"; import * as React from "react"; import { ExportContentType } from "@shared/types"; @@ -128,6 +130,61 @@ export const unstarDocument = createAction({ }, }); +export const publishDocument = createAction({ + name: ({ t }) => t("Publish"), + section: DocumentSection, + icon: , + visible: ({ activeDocumentId, stores }) => { + if (!activeDocumentId) { + return false; + } + const document = stores.documents.get(activeDocumentId); + return ( + !!document?.isDraft && stores.policies.abilities(activeDocumentId).update + ); + }, + perform: ({ activeDocumentId, stores, t }) => { + if (!activeDocumentId) { + return; + } + + const document = stores.documents.get(activeDocumentId); + + document?.save({ + publish: true, + }); + + stores.toasts.showToast(t("Document published"), { + type: "success", + }); + }, +}); + +export const unpublishDocument = createAction({ + name: ({ t }) => t("Unpublish"), + section: DocumentSection, + icon: , + visible: ({ activeDocumentId, stores }) => { + if (!activeDocumentId) { + return false; + } + return stores.policies.abilities(activeDocumentId).unpublish; + }, + perform: ({ activeDocumentId, stores, t }) => { + if (!activeDocumentId) { + return; + } + + const document = stores.documents.get(activeDocumentId); + + document?.unpublish(); + + stores.toasts.showToast(t("Document unpublished"), { + type: "success", + }); + }, +}); + export const subscribeDocument = createAction({ name: ({ t }) => t("Subscribe"), section: DocumentSection, @@ -662,6 +719,8 @@ export const rootDocumentActions = [ downloadDocument, starDocument, unstarDocument, + publishDocument, + unpublishDocument, subscribeDocument, unsubscribeDocument, duplicateDocument, diff --git a/app/actions/index.ts b/app/actions/index.ts index cd7a554add..738022f713 100644 --- a/app/actions/index.ts +++ b/app/actions/index.ts @@ -57,8 +57,16 @@ export function actionToMenuItem( icon, visible, dangerous: action.dangerous, - onClick: () => action.perform && action.perform(context), - selected: action.selected ? action.selected(context) : undefined, + onClick: () => { + try { + action.perform?.(context); + } catch (err) { + context.stores.toasts.showToast(err.message, { + type: "error", + }); + } + }, + selected: action.selected?.(context), }; } diff --git a/app/menus/DocumentMenu.tsx b/app/menus/DocumentMenu.tsx index f9d64a1889..15e0583a95 100644 --- a/app/menus/DocumentMenu.tsx +++ b/app/menus/DocumentMenu.tsx @@ -1,7 +1,6 @@ import { observer } from "mobx-react"; import { EditIcon, - UnpublishIcon, PrintIcon, NewDocumentIcon, RestoreIcon, @@ -39,6 +38,8 @@ import { archiveDocument, openDocumentHistory, openDocumentInsights, + publishDocument, + unpublishDocument, } from "~/actions/definitions/documents"; import useActionContext from "~/hooks/useActionContext"; import useCurrentTeam from "~/hooks/useCurrentTeam"; @@ -124,13 +125,6 @@ function DocumentMenu({ [showToast, t, document] ); - const handleUnpublish = React.useCallback(async () => { - await document.unpublish(); - showToast(t("Document unpublished"), { - type: "success", - }); - }, [showToast, t, document]); - const handlePrint = React.useCallback(() => { menu.hide(); window.print(); @@ -289,13 +283,8 @@ function DocumentMenu({ actionToMenuItem(importDocument, context), actionToMenuItem(createTemplate, context), actionToMenuItem(duplicateDocument, context), - { - type: "button", - title: t("Unpublish"), - onClick: handleUnpublish, - visible: !!can.unpublish, - icon: , - }, + actionToMenuItem(publishDocument, context), + actionToMenuItem(unpublishDocument, context), actionToMenuItem(archiveDocument, context), actionToMenuItem(moveDocument, context), actionToMenuItem(pinDocument, context), diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 5c91bf72d6..d015e82cc7 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -13,6 +13,10 @@ "Developer": "Developer", "Open document": "Open document", "New document": "New document", + "Publish": "Publish", + "Document published": "Document published", + "Unpublish": "Unpublish", + "Document unpublished": "Document unpublished", "Subscribe": "Subscribe", "Subscribed to document notifications": "Subscribed to document notifications", "Unsubscribe": "Unsubscribe", @@ -316,11 +320,9 @@ "Sort in sidebar": "Sort in sidebar", "Alphabetical sort": "Alphabetical sort", "Manual sort": "Manual sort", - "Document unpublished": "Document unpublished", "Document options": "Document options", "Restore": "Restore", "Choose a collection": "Choose a collection", - "Unpublish": "Unpublish", "Enable embeds": "Enable embeds", "Export options": "Export options", "Edit group": "Edit group", @@ -441,7 +443,6 @@ "Done Editing": "Done Editing", "New from template": "New from template", "Restore version": "Restore version", - "Publish": "Publish", "Publishing": "Publishing", "No history yet": "No history yet", "Stats": "Stats", @@ -659,7 +660,6 @@ "document updated": "document updated", "Posting to the {{ channelName }} channel on": "Posting to the {{ channelName }} channel on", "These events should be posted to Slack": "These events should be posted to Slack", - "Document published": "Document published", "Document updated": "Document updated", "Disconnect": "Disconnect", "API token copied to clipboard": "API token copied to clipboard", From e3db7455b33252e35b17a5c3520b21194b2b968f Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 13 Jan 2023 21:49:57 -0500 Subject: [PATCH 35/61] feat: Add optional SMTP_NAME configuration for connecting to SMTP servers that require the client to have a specific hostname --- server/emails/mailer.tsx | 8 ++++++-- server/env.ts | 6 ++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/server/emails/mailer.tsx b/server/emails/mailer.tsx index c6f584aa36..0d4dea367c 100644 --- a/server/emails/mailer.tsx +++ b/server/emails/mailer.tsx @@ -1,4 +1,5 @@ import nodemailer, { Transporter } from "nodemailer"; +import SMTPTransport from "nodemailer/lib/smtp-transport"; import Oy from "oy-vey"; import env from "@server/env"; import Logger from "@server/logging/Logger"; @@ -101,8 +102,9 @@ export class Mailer { } }; - private getOptions() { + private getOptions(): SMTPTransport.Options { return { + name: env.SMTP_NAME, host: env.SMTP_HOST, port: env.SMTP_PORT, secure: env.SMTP_SECURE ?? env.ENVIRONMENT === "production", @@ -124,7 +126,9 @@ export class Mailer { }; } - private async getTestTransportOptions() { + private async getTestTransportOptions(): Promise< + SMTPTransport.Options | undefined + > { try { const testAccount = await nodemailer.createTestAccount(); return { diff --git a/server/env.ts b/server/env.ts index 5207687c35..1d7b72471b 100644 --- a/server/env.ts +++ b/server/env.ts @@ -264,6 +264,12 @@ export class Environment { */ public SMTP_HOST = process.env.SMTP_HOST; + /** + * Optional hostname of the client, used for identifying to the server + * defaults to hostname of the machine. + */ + public SMTP_NAME = process.env.SMTP_NAME; + /** * The port of your SMTP server. */ From 0d53e5a7ba109c855f5f48bd392e1bb8d9011146 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 13 Jan 2023 22:18:25 -0500 Subject: [PATCH 36/61] chore: Clean build/ folder on every build, remove duplicative scripts --- package.json | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 061eabff03..60436dc6f6 100644 --- a/package.json +++ b/package.json @@ -9,16 +9,14 @@ "build:i18n": "i18next --silent 'shared/**/*.tsx' 'shared/**/*.ts' 'app/**/*.tsx' 'app/**/*.ts' 'server/**/*.ts' 'server/**/*.tsx' && yarn copy:i18n", "build:server": "./build.sh", "build:webpack": "webpack --config webpack.config.prod.js", - "build": "yarn build:webpack && yarn build:i18n && yarn build:server", + "build": "yarn clean && yarn build:webpack && yarn build:i18n && yarn build:server", "start": "node ./build/server/index.js", "dev": "NODE_ENV=development yarn concurrently -n api,collaboration -c \"blue,magenta\" \"node --inspect=0.0.0.0 build/server/index.js --services=collaboration,websockets,admin,web,worker\"", "dev:watch": "nodemon --exec \"yarn build:server && yarn dev\" -e js,ts,tsx --ignore build/ --ignore app/ --ignore shared/editor", "lint": "eslint app server shared", - "deploy": "git push heroku master", "prepare": "husky install", "postinstall": "rimraf node_modules/prosemirror-view/dist/index.d.ts", - "heroku-postbuild": "yarn build:webpack && yarn build:server && yarn copy:i18n && yarn db:migrate", - "sequelize:migrate": "sequelize db:migrate", + "heroku-postbuild": "yarn build && yarn db:migrate", "db:create-migration": "sequelize migration:create", "db:create": "sequelize db:create", "db:migrate": "sequelize db:migrate", From 6b438e346712af7485ae76d0c1815f281c847529 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 13 Jan 2023 22:22:31 -0500 Subject: [PATCH 37/61] fix: Background on TOC does not transition smoothly on theme change --- app/scenes/Document/components/Contents.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/scenes/Document/components/Contents.tsx b/app/scenes/Document/components/Contents.tsx index d3e43c33cd..a35d6d9ce7 100644 --- a/app/scenes/Document/components/Contents.tsx +++ b/app/scenes/Document/components/Contents.tsx @@ -102,6 +102,8 @@ const Sticky = styled.div` max-height: calc(100vh - 80px); background: ${(props) => props.theme.background}; + transition: ${(props) => props.theme.backgroundTransition}; + margin-top: 72px; margin-right: 52px; min-width: 204px; From 0cccd7141dac92f4b0a45ce6107a8609ffcf5534 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 13 Jan 2023 23:54:44 -0500 Subject: [PATCH 38/61] fix(collaboration): Avoid writing spurious changes from read-only users when serialized output changes --- server/collaboration/PersistenceExtension.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/server/collaboration/PersistenceExtension.ts b/server/collaboration/PersistenceExtension.ts index 547f72a12b..48f3a24380 100644 --- a/server/collaboration/PersistenceExtension.ts +++ b/server/collaboration/PersistenceExtension.ts @@ -86,13 +86,17 @@ export default class PersistenceExtension implements Extension { const [, documentId] = documentName.split("."); // Find the collaborators that have modified the document since it was last - // persisted and clear the map. + // persisted and clear the map, if there's no collaborators then we don't + // need to persist the document. const documentCollaboratorIds = this.documentCollaboratorIds.get( documentName ); - const collaboratorIds = documentCollaboratorIds - ? Array.from(documentCollaboratorIds.values()) - : [context.user?.id]; + if (!documentCollaboratorIds) { + Logger.debug("multiplayer", `No changes for ${documentName}`); + return; + } + + const collaboratorIds = Array.from(documentCollaboratorIds.values()); this.documentCollaboratorIds.delete(documentName); try { From 51baba8fa8803fa03dc9d06b258f072c72785bc1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 14 Jan 2023 20:45:15 -0500 Subject: [PATCH 39/61] fix: Small unfocusable area below last block in editor, closes #4713 --- shared/editor/components/Styles.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index 22e548af88..da29718d5e 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -149,6 +149,10 @@ width: 100%; & > * { margin-top: .5em; margin-bottom: .5em; + + &:last-child { + margin-bottom: 0; + } } & > :first-child, From a25372c18682d9c6ee3ee6a9ffffa5b625d797eb Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 14 Jan 2023 21:47:33 -0500 Subject: [PATCH 40/61] fix: Full-width images in editor are incorrectly aligned in RTL documents closes #4712 --- shared/editor/components/Styles.ts | 1 + shared/editor/nodes/Image.tsx | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index da29718d5e..c61b0fdb42 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -295,6 +295,7 @@ li { max-width: 100vw; clear: both; position: initial; + ${props.rtl ? `margin-right: var(--offset)` : `margin-left: var(--offset)`}; img { max-width: 100vw; diff --git a/shared/editor/nodes/Image.tsx b/shared/editor/nodes/Image.tsx index b837a74b12..2752b5e123 100644 --- a/shared/editor/nodes/Image.tsx +++ b/shared/editor/nodes/Image.tsx @@ -726,17 +726,22 @@ const ImageComponent = ( : { width: size.width || "auto" }; return ( -
+
{!dragging && size.width > 60 && size.height > 60 && (
); }; From 095028541d0273abd3ef9146acaa661bd4cdd56c Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 22 Jan 2023 10:14:17 -0500 Subject: [PATCH 55/61] fix: Missing translations --- shared/i18n/locales/en_US/translation.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 69564be6bb..de4d63250a 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -498,7 +498,7 @@ "The document will be accessible at <2>{{url}}": "The document will be accessible at <2>{{url}}", "More options": "More options", "Close": "Close", - "{{ teamName }} is using {{ appName }} to share documents, please login to continue.": "", + "{{ teamName }} is using {{ appName }} to share documents, please login to continue.": "{{ teamName }} is using {{ appName }} to share documents, please login to continue.", "Are you sure you want to delete the {{ documentTitle }} template?": "Are you sure you want to delete the {{ documentTitle }} template?", "Are you sure about that? Deleting the {{ documentTitle }} document will delete all of its history.": "Are you sure about that? Deleting the {{ documentTitle }} document will delete all of its history.", "Are you sure about that? Deleting the {{ documentTitle }} document will delete all of its history and {{ any }} nested document.": "Are you sure about that? Deleting the {{ documentTitle }} document will delete all of its history and one nested document.", @@ -731,7 +731,7 @@ "Export completed": "Export completed", "Receive a notification when an export you requested has been completed": "Receive a notification when an export you requested has been completed", "Getting started": "Getting started", - "Tips on getting started with features and functionality": "", + "Tips on getting started with features and functionality": "Tips on getting started with features and functionality", "New features": "New features", "Receive an email when new features of note are added": "Receive an email when new features of note are added", "Notifications saved": "Notifications saved", From f83b0ab5e3cf6c6beec55260fae7f1e0fc7e5f12 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 22 Jan 2023 10:22:41 -0500 Subject: [PATCH 56/61] fix: Remove :is selector (bad compatibility) --- shared/editor/components/ImageZoom/Controlled.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/editor/components/ImageZoom/Controlled.tsx b/shared/editor/components/ImageZoom/Controlled.tsx index ca5da561fb..ddd08cfdf7 100644 --- a/shared/editor/components/ImageZoom/Controlled.tsx +++ b/shared/editor/components/ImageZoom/Controlled.tsx @@ -318,7 +318,7 @@ class ControlledBase extends Component< } this.imgEl = contentEl.querySelector( - ':is(img, svg, [role="img"], [data-zoom]):not([aria-hidden="true"])' + 'img:not([aria-hidden="true"])' ) as SupportedImage | null; if (this.imgEl) { From aa88bb2a7b5c9a817009df30a83b69671747a5a0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 22 Jan 2023 10:32:31 -0500 Subject: [PATCH 57/61] fix: Check browser has print ability before showing Print option --- app/actions/definitions/documents.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 129f5b994c..60bf609ecf 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -439,7 +439,7 @@ export const printDocument = createAction({ isContextMenu ? t("Print") : t("Print document"), section: DocumentSection, icon: , - visible: ({ activeDocumentId }) => !!activeDocumentId, + visible: ({ activeDocumentId }) => !!(activeDocumentId && window.print), perform: async () => { window.print(); }, From 5b561e98f777808dbe8e686a6f1265b01ea4fa7e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 22 Jan 2023 07:50:32 -0800 Subject: [PATCH 58/61] chore: Add configurable per-document connection limit extension (#4717) * chore: Add configurable per-document connection limit extension * docs --- .../collaboration/ConnectionLimitExtension.ts | 64 +++++++++++++++++++ server/env.ts | 11 ++++ server/services/collaboration.ts | 2 + 3 files changed, 77 insertions(+) create mode 100644 server/collaboration/ConnectionLimitExtension.ts diff --git a/server/collaboration/ConnectionLimitExtension.ts b/server/collaboration/ConnectionLimitExtension.ts new file mode 100644 index 0000000000..8e4405666a --- /dev/null +++ b/server/collaboration/ConnectionLimitExtension.ts @@ -0,0 +1,64 @@ +import { + Extension, + onConnectPayload, + onDisconnectPayload, +} from "@hocuspocus/server"; +import env from "@server/env"; +import Logger from "@server/logging/Logger"; +import { trace } from "@server/logging/tracing"; + +@trace() +export class ConnectionLimitExtension implements Extension { + /** + * Map of documentId -> connection count + */ + connectionsByDocument: Map = new Map(); + + /** + * onDisconnect hook + * @param data The disconnect payload + */ + onDisconnect(data: onDisconnectPayload) { + const { documentName } = data; + + const currConnections = this.connectionsByDocument.get(documentName) || 0; + const newConnections = currConnections - 1; + this.connectionsByDocument.set(documentName, newConnections); + + Logger.debug( + "multiplayer", + `${newConnections} connections to "${documentName}"` + ); + + return Promise.resolve(); + } + + /** + * onConnect hook + * @param data The connect payload + */ + onConnect(data: onConnectPayload) { + const { documentName } = data; + + const currConnections = this.connectionsByDocument.get(documentName) || 0; + if (currConnections >= env.COLLABORATION_MAX_CLIENTS_PER_DOCUMENT) { + Logger.info( + "multiplayer", + `Rejected connection to "${documentName}" because it has reached the maximum number of connections` + ); + + // Rejecting the promise will cause the connection to be dropped. + return Promise.reject(); + } + + const newConnections = currConnections + 1; + this.connectionsByDocument.set(documentName, newConnections); + + Logger.debug( + "multiplayer", + `${newConnections} connections to "${documentName}"` + ); + + return Promise.resolve(); + } +} diff --git a/server/env.ts b/server/env.ts index 1d7b72471b..713f1ea340 100644 --- a/server/env.ts +++ b/server/env.ts @@ -147,6 +147,17 @@ export class Environment { process.env.COLLABORATION_URL ); + /** + * The maximum number of network clients that can be connected to a single + * document at once. Defaults to 100. + */ + @IsOptional() + @IsNumber() + public COLLABORATION_MAX_CLIENTS_PER_DOCUMENT = parseInt( + process.env.COLLABORATION_MAX_CLIENTS_PER_DOCUMENT || "100", + 10 + ); + /** * The port that the server will listen on, defaults to 3000. */ diff --git a/server/services/collaboration.ts b/server/services/collaboration.ts index d446ab6cb4..ea2d68fe96 100644 --- a/server/services/collaboration.ts +++ b/server/services/collaboration.ts @@ -5,6 +5,7 @@ import { Server } from "@hocuspocus/server"; import Koa from "koa"; import WebSocket from "ws"; import { DocumentValidation } from "@shared/validations"; +import { ConnectionLimitExtension } from "@server/collaboration/ConnectionLimitExtension"; import Logger from "@server/logging/Logger"; import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; import AuthenticationExtension from "../collaboration/AuthenticationExtension"; @@ -28,6 +29,7 @@ export default function init( timeout: 30000, maxDebounce: 10000, extensions: [ + new ConnectionLimitExtension(), new AuthenticationExtension(), new PersistenceExtension(), new LoggerExtension(), From d3dbf53d0b92b1adbd3cdb55a500eee3a7fe0028 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 22 Jan 2023 11:04:15 -0500 Subject: [PATCH 59/61] chore: Add insurance rate limiter for when Redis is down/reconnecting --- server/utils/RateLimiter.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/server/utils/RateLimiter.ts b/server/utils/RateLimiter.ts index 9aa6a2e16d..f18eb5175d 100644 --- a/server/utils/RateLimiter.ts +++ b/server/utils/RateLimiter.ts @@ -1,6 +1,7 @@ import { IRateLimiterStoreOptions, RateLimiterRedis, + RateLimiterMemory, } from "rate-limiter-flexible"; import env from "@server/env"; import Redis from "@server/redis"; @@ -14,11 +15,17 @@ export default class RateLimiter { static readonly rateLimiterMap = new Map(); + static readonly insuranceRateLimiter = new RateLimiterMemory({ + points: env.RATE_LIMITER_REQUESTS, + duration: env.RATE_LIMITER_DURATION_WINDOW, + }); + 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, + insuranceLimiter: this.insuranceRateLimiter, }); static getRateLimiter(path: string): RateLimiterRedis { From 312e11e7c1f78dbcfb86299a3ce5289acc5334b5 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 22 Jan 2023 11:31:48 -0500 Subject: [PATCH 60/61] fix: Any error from rate limiter results in 'Rate limit exceeded' screen --- server/middlewares/rateLimiter.ts | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/server/middlewares/rateLimiter.ts b/server/middlewares/rateLimiter.ts index aaedc36102..2ef85e925e 100644 --- a/server/middlewares/rateLimiter.ts +++ b/server/middlewares/rateLimiter.ts @@ -2,6 +2,7 @@ import { Context, Next } from "koa"; import { defaults } from "lodash"; import env from "@server/env"; import { RateLimitExceededError } from "@server/errors"; +import Logger from "@server/logging/Logger"; import Metrics from "@server/logging/Metrics"; import Redis from "@server/redis"; import RateLimiter from "@server/utils/RateLimiter"; @@ -27,19 +28,23 @@ export function defaultRateLimiter() { try { await limiter.consume(key); } catch (rateLimiterRes) { - ctx.set("Retry-After", `${rateLimiterRes.msBeforeNext / 1000}`); - ctx.set("RateLimit-Limit", `${limiter.points}`); - ctx.set("RateLimit-Remaining", `${rateLimiterRes.remainingPoints}`); - ctx.set( - "RateLimit-Reset", - `${new Date(Date.now() + rateLimiterRes.msBeforeNext)}` - ); + if (rateLimiterRes.points) { + ctx.set("Retry-After", `${rateLimiterRes.msBeforeNext / 1000}`); + ctx.set("RateLimit-Limit", `${limiter.points}`); + ctx.set("RateLimit-Remaining", `${rateLimiterRes.remainingPoints}`); + ctx.set( + "RateLimit-Reset", + `${new Date(Date.now() + rateLimiterRes.msBeforeNext)}` + ); - Metrics.increment("rate_limit.exceeded", { - path: ctx.path, - }); + Metrics.increment("rate_limit.exceeded", { + path: ctx.path, + }); - throw RateLimitExceededError(); + throw RateLimitExceededError(); + } else { + Logger.error("Rate limiter error", rateLimiterRes); + } } return next(); From da4a0189dc4ad69d0879508cca585be35e6fc2da Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 22 Jan 2023 14:37:52 -0800 Subject: [PATCH 61/61] Update rateLimiter.ts --- server/middlewares/rateLimiter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/middlewares/rateLimiter.ts b/server/middlewares/rateLimiter.ts index 2ef85e925e..d302e61432 100644 --- a/server/middlewares/rateLimiter.ts +++ b/server/middlewares/rateLimiter.ts @@ -28,7 +28,7 @@ export function defaultRateLimiter() { try { await limiter.consume(key); } catch (rateLimiterRes) { - if (rateLimiterRes.points) { + if (rateLimiterRes.msBeforeNext) { ctx.set("Retry-After", `${rateLimiterRes.msBeforeNext / 1000}`); ctx.set("RateLimit-Limit", `${limiter.points}`); ctx.set("RateLimit-Remaining", `${rateLimiterRes.remainingPoints}`);