From 7ae892fe06c9517ef1f1761c50aa280637d15813 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 24 Jul 2022 09:37:20 +0100 Subject: [PATCH 01/30] fix: Long collection description prevents import (#3847) * fix: Long collection description prevents import fix: Parallelize attachment upload during import * fix: Improve Notion image import matching * chore: Bump JSZIP (perf) * fix: Allow redirect from /doc/ to canonical url * fix: Importing document with only title duplicates title in body --- app/scenes/Document/components/DataLoader.tsx | 7 +++- package.json | 2 +- server/commands/documentImporter.test.ts | 15 ++++++++ server/commands/documentImporter.ts | 2 +- server/models/Collection.ts | 5 +-- server/queues/tasks/ImportNotionTask.ts | 16 ++++++--- server/queues/tasks/ImportTask.ts | 36 +++++++++++-------- shared/validations.ts | 4 +++ yarn.lock | 14 ++++---- 9 files changed, 70 insertions(+), 31 deletions(-) create mode 100644 shared/validations.ts diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index 50f2d65736..3924274bd3 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -45,7 +45,12 @@ function DataLoader({ match, children }: Props) { const { team } = auth; const [error, setError] = React.useState(null); const { revisionId, shareId, documentSlug } = match.params; - const document = documents.getByUrl(match.params.documentSlug); + + // Allows loading by /doc/slug- or /doc/ + const document = + documents.getByUrl(match.params.documentSlug) ?? + documents.get(match.params.documentSlug); + const revision = revisionId ? revisions.get(revisionId) : undefined; const sharedTree = document ? documents.getSharedTree(document.id) diff --git a/package.json b/package.json index d35e2be66e..9a422e25f5 100644 --- a/package.json +++ b/package.json @@ -108,7 +108,7 @@ "is-printable-key-event": "^1.0.0", "json-loader": "0.5.4", "jsonwebtoken": "^8.5.0", - "jszip": "^3.7.1", + "jszip": "^3.10.0", "kbar": "0.1.0-beta.28", "koa": "^2.13.4", "koa-body": "^4.2.0", diff --git a/server/commands/documentImporter.test.ts b/server/commands/documentImporter.test.ts index c4139bbad3..889c234e10 100644 --- a/server/commands/documentImporter.test.ts +++ b/server/commands/documentImporter.test.ts @@ -148,6 +148,21 @@ describe("documentImporter", () => { expect(response.title).toEqual("Heading 1"); }); + it("should handle only title", async () => { + const user = await buildUser(); + const fileName = "markdown.md"; + const content = `# Title`; + const response = await documentImporter({ + user, + mimeType: "text/plain", + fileName, + content, + ip, + }); + expect(response.text).toEqual(""); + expect(response.title).toEqual("Title"); + }); + it("should fallback to extension if mimetype unknown", async () => { const user = await buildUser(); const fileName = "markdown.md"; diff --git a/server/commands/documentImporter.ts b/server/commands/documentImporter.ts index 5e761d0d8a..b7b8a25d8d 100644 --- a/server/commands/documentImporter.ts +++ b/server/commands/documentImporter.ts @@ -190,7 +190,7 @@ async function documentImporter({ if (text.startsWith("# ")) { const result = parseTitle(text); title = result.title; - text = text.replace(`# ${title}\n`, ""); + text = text.replace(`# ${title}`, "").trimStart(); } // If we parsed an emoji from _above_ the title then add it back at prefixing diff --git a/server/models/Collection.ts b/server/models/Collection.ts index f72ab2e319..71d5aa2f29 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -24,6 +24,7 @@ import isUUID from "validator/lib/isUUID"; import { MAX_TITLE_LENGTH } from "@shared/constants"; import { sortNavigationNodes } from "@shared/utils/collections"; import { SLUG_URL_REGEX } from "@shared/utils/urlHelpers"; +import { CollectionValidation } from "@shared/validations"; import slugify from "@server/utils/slugify"; import { NavigationNode, CollectionSort } from "~/types"; import CollectionGroup from "./CollectionGroup"; @@ -150,8 +151,8 @@ class Collection extends ParanoidModel { name: string; @Length({ - max: 1000, - msg: `description must be 1000 characters or less`, + max: CollectionValidation.maxDescriptionLength, + msg: `description must be ${CollectionValidation.maxDescriptionLength} characters or less`, }) @Column description: string; diff --git a/server/queues/tasks/ImportNotionTask.ts b/server/queues/tasks/ImportNotionTask.ts index 0dccf8b564..3607cf7400 100644 --- a/server/queues/tasks/ImportNotionTask.ts +++ b/server/queues/tasks/ImportNotionTask.ts @@ -139,13 +139,19 @@ export default class ImportNotionTask extends ImportTask { for (const image of imagesInText) { const name = path.basename(image.src); - const attachment = output.attachments.find((att) => att.name === name); + const attachment = output.attachments.find( + (att) => + att.path.endsWith(image.src) || + encodeURI(att.path).endsWith(image.src) + ); if (!attachment) { - Logger.info( - "task", - `Could not find referenced attachment with name ${name} and src ${image.src}` - ); + if (!image.src.startsWith("http")) { + Logger.info( + "task", + `Could not find referenced attachment with name ${name} and src ${image.src}` + ); + } } else { text = text.replace( new RegExp(escapeRegExp(image.src), "g"), diff --git a/server/queues/tasks/ImportTask.ts b/server/queues/tasks/ImportTask.ts index 47c553955d..0c2091b422 100644 --- a/server/queues/tasks/ImportTask.ts +++ b/server/queues/tasks/ImportTask.ts @@ -1,4 +1,5 @@ import { truncate } from "lodash"; +import { CollectionValidation } from "@shared/validations"; import attachmentCreator from "@server/commands/attachmentCreator"; import documentCreator from "@server/commands/documentCreator"; import { sequelize } from "@server/database/sequelize"; @@ -206,22 +207,26 @@ export default abstract class ImportTask extends BaseTask { const ip = user.lastActiveIp || undefined; // Attachments - for (const item of data.attachments) { - const attachment = await attachmentCreator({ - source: "import", - id: item.id, - name: item.name, - type: item.mimeType, - buffer: item.buffer, - user, - ip, - transaction, - }); - attachments.set(item.id, attachment); - } + await Promise.all( + data.attachments.map(async (item) => { + Logger.debug("task", `ImportTask persisting attachment ${item.id}`); + const attachment = await attachmentCreator({ + source: "import", + id: item.id, + name: item.name, + type: item.mimeType, + buffer: item.buffer, + user, + ip, + transaction, + }); + attachments.set(item.id, attachment); + }) + ); // Collections for (const item of data.collections) { + Logger.debug("task", `ImportTask persisting collection ${item.id}`); let description = item.description; if (description) { @@ -258,7 +263,9 @@ export default abstract class ImportTask extends BaseTask { }, defaults: { id: item.id, - description, + description: truncate(description, { + length: CollectionValidation.maxDescriptionLength, + }), createdById: fileOperation.userId, permission: "read_write", }, @@ -307,6 +314,7 @@ export default abstract class ImportTask extends BaseTask { // Documents for (const item of data.documents) { + Logger.debug("task", `ImportTask persisting document ${item.id}`); let text = item.text; // Check all of the attachments we've created against urls in the text diff --git a/shared/validations.ts b/shared/validations.ts new file mode 100644 index 0000000000..184ecb8471 --- /dev/null +++ b/shared/validations.ts @@ -0,0 +1,4 @@ +export const CollectionValidation = { + /* The maximum length of the collection description */ + maxDescriptionLength: 1000, +}; diff --git a/yarn.lock b/yarn.lock index b8d642b44e..a5b7ac5dff 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9628,15 +9628,15 @@ jsonwebtoken@^8.5.0: array-includes "^3.1.1" object.assign "^4.1.1" -jszip@^3.7.1: - version "3.7.1" - resolved "https://registry.yarnpkg.com/jszip/-/jszip-3.7.1.tgz#bd63401221c15625a1228c556ca8a68da6fda3d9" - integrity sha512-ghL0tz1XG9ZEmRMcEN2vt7xabrDdqHHeykgARpmZ0BiIctWxM47Vt63ZO2dnp4QYt/xJVLLy5Zv1l/xRdh2byg== +jszip@^3.10.0, jszip@^3.7.1: + version "3.10.0" + resolved "https://registry.yarnpkg.com/jszip/-/jszip-3.10.0.tgz#faf3db2b4b8515425e34effcdbb086750a346061" + integrity sha512-LDfVtOLtOxb9RXkYOwPyNBTQDL4eUbqahtoY6x07GiDJHwSYvn8sHHIw8wINImV3MqbMNve2gSuM1DDqEKk09Q== dependencies: lie "~3.3.0" pako "~1.0.2" readable-stream "~2.3.6" - set-immediate-shim "~1.0.1" + setimmediate "^1.0.5" jwa@^1.4.1: version "1.4.1" @@ -13272,10 +13272,10 @@ set-value@^2.0.0, set-value@^2.0.1: is-plain-object "^2.0.3" split-string "^3.0.1" -setimmediate@^1.0.4: +setimmediate@^1.0.4, setimmediate@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" - integrity sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU= + integrity sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA== setprototypeof@1.1.0: version "1.1.0" From 24170e868494fb0880401553bac5e83cc8896562 Mon Sep 17 00:00:00 2001 From: Apoorv Mishra Date: Sun, 24 Jul 2022 14:27:21 +0530 Subject: [PATCH 02/30] chore: Remove updatedAt column from events table (#3841) --- .../20220722184916-remove-event-updatedat.js | 14 ++++++++++++++ server/models/Event.ts | 3 +-- 2 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 server/migrations/20220722184916-remove-event-updatedat.js diff --git a/server/migrations/20220722184916-remove-event-updatedat.js b/server/migrations/20220722184916-remove-event-updatedat.js new file mode 100644 index 0000000000..84e9fe0104 --- /dev/null +++ b/server/migrations/20220722184916-remove-event-updatedat.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + async up (queryInterface, Sequelize) { + await queryInterface.removeColumn("events", "updatedAt"); + }, + async down (queryInterface, Sequelize) { + await queryInterface.addColumn("events", "updatedAt", { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.fn('NOW'), + }); + } +}; diff --git a/server/models/Event.ts b/server/models/Event.ts index 0e1c4727d9..4e2e7806df 100644 --- a/server/models/Event.ts +++ b/server/models/Event.ts @@ -20,7 +20,7 @@ import User from "./User"; import IdModel from "./base/IdModel"; import Fix from "./decorators/Fix"; -@Table({ tableName: "events", modelName: "event" }) +@Table({ tableName: "events", modelName: "event", updatedAt: false }) @Fix class Event extends IdModel { @IsUUID(4) @@ -106,7 +106,6 @@ class Event extends IdModel { globalEventQueue.add( this.build({ createdAt: now, - updatedAt: now, ...event, }) ); From 870d9ed41e5de3eaaa4e243777e83da64392afd0 Mon Sep 17 00:00:00 2001 From: Nan Yu Date: Sun, 24 Jul 2022 07:55:30 -0400 Subject: [PATCH 03/30] feat: allow external SSO methods to log into teams as long as emails match (#3813) * wip * wip * fix comments * better separation of conerns * fix up tests * fix semantics * fixup tsc * fix some tests * the old semantics were easier to use * add db:reset to scripts * explicitly throw for unauthorized external authorization * fix minor bug * add additional tests for user creator and team creator * yank the email matching logic out of teamcreator * renaming * fix type and test errors * adds test to ensure that accountProvisioner works with email matching * remove only * fix comments * recreate changes to allow self hosted to make teams --- package.json | 1 + server/commands/accountProvisioner.test.ts | 38 +++++ server/commands/accountProvisioner.ts | 47 +++++-- ...reator.test.ts => teamProvisioner.test.ts} | 75 ++++++++-- .../{teamCreator.ts => teamProvisioner.ts} | 28 ++-- ...reator.test.ts => userProvisioner.test.ts} | 115 +++++++++++----- .../{userCreator.ts => userProvisioner.ts} | 43 ++++-- server/routes/auth/providers/azure.ts | 6 +- server/routes/auth/providers/google.ts | 130 ++++++++---------- server/routes/auth/providers/oidc.ts | 2 +- server/routes/auth/providers/slack.ts | 2 +- 11 files changed, 322 insertions(+), 165 deletions(-) rename server/commands/{teamCreator.test.ts => teamProvisioner.test.ts} (73%) rename server/commands/{teamCreator.ts => teamProvisioner.ts} (88%) rename server/commands/{userCreator.test.ts => userProvisioner.test.ts} (76%) rename server/commands/{userCreator.ts => userProvisioner.ts} (83%) diff --git a/package.json b/package.json index 9a422e25f5..c574c93a12 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "db:create-migration": "sequelize migration:create", "db:migrate": "sequelize db:migrate", "db:rollback": "sequelize db:migrate:undo", + "db:reset": "sequelize db:drop && sequelize db:create && sequelize db:migrate", "upgrade": "git fetch && git pull && yarn install && yarn heroku-postbuild", "test": "yarn test:app && yarn test:server", "test:app": "jest --config=app/.jestconfig.json --runInBand --forceExit", diff --git a/server/commands/accountProvisioner.test.ts b/server/commands/accountProvisioner.test.ts index 7a65280de3..33b96048bb 100644 --- a/server/commands/accountProvisioner.test.ts +++ b/server/commands/accountProvisioner.test.ts @@ -108,6 +108,44 @@ describe("accountProvisioner", () => { spy.mockRestore(); }); + it("should allow authentication by email matching", async () => { + const existingTeam = await buildTeam(); + const providers = await existingTeam.$get("authenticationProviders"); + const authenticationProvider = providers[0]; + const userWithoutAuth = await buildUser({ + email: "email@example.com", + teamId: existingTeam.id, + authentications: [], + }); + + const { user, isNewUser, isNewTeam } = await accountProvisioner({ + ip, + user: { + name: userWithoutAuth.name, + email: "email@example.com", + avatarUrl: userWithoutAuth.avatarUrl, + }, + team: { + name: existingTeam.name, + avatarUrl: existingTeam.avatarUrl, + subdomain: "example", + }, + authenticationProvider: { + name: authenticationProvider.name, + providerId: authenticationProvider.providerId, + }, + authentication: { + providerId: "anything", + accessToken: "123", + scopes: ["read"], + }, + }); + expect(user.id).toEqual(userWithoutAuth.id); + expect(isNewTeam).toEqual(false); + expect(isNewUser).toEqual(false); + expect(user.authentications.length).toEqual(0); + }); + it("should throw an error when authentication provider is disabled", async () => { const existingTeam = await buildTeam(); const providers = await existingTeam.$get("authenticationProviders"); diff --git a/server/commands/accountProvisioner.ts b/server/commands/accountProvisioner.ts index 27dabc5a6d..f576f83937 100644 --- a/server/commands/accountProvisioner.ts +++ b/server/commands/accountProvisioner.ts @@ -8,9 +8,9 @@ import { AuthenticationProviderDisabledError, } from "@server/errors"; import { APM } from "@server/logging/tracing"; -import { Collection, Team, User } from "@server/models"; -import teamCreator from "./teamCreator"; -import userCreator from "./userCreator"; +import { AuthenticationProvider, Collection, Team, User } from "@server/models"; +import teamProvisioner from "./teamProvisioner"; +import userProvisioner from "./userProvisioner"; type Props = { ip: string; @@ -21,7 +21,7 @@ type Props = { username?: string; }; team: { - id?: string; + teamId?: string; name: string; domain?: string; subdomain: string; @@ -55,15 +55,45 @@ async function accountProvisioner({ authentication: authenticationParams, }: Props): Promise { let result; + let emailMatchOnly; try { - result = await teamCreator({ + result = await teamProvisioner({ ...teamParams, authenticationProvider: authenticationProviderParams, ip, }); } catch (err) { - throw InvalidAuthenticationError(err.message); + // The account could not be provisioned for the provided teamId + // check to see if we can try authentication using email matching only + if (err.id === "invalid_authentication") { + const authenticationProvider = await AuthenticationProvider.findOne({ + where: { + name: authenticationProviderParams.name, // example: "google" + teamId: teamParams.teamId, + }, + include: [ + { + model: Team, + as: "team", + required: true, + }, + ], + }); + + if (authenticationProvider) { + emailMatchOnly = true; + result = { + authenticationProvider, + team: authenticationProvider.team, + isNewTeam: false, + }; + } + } + + if (!result) { + throw InvalidAuthenticationError(err.message); + } } invariant(result, "Team creator result must exist"); @@ -74,20 +104,21 @@ async function accountProvisioner({ } try { - const result = await userCreator({ + const result = await userProvisioner({ name: userParams.name, email: userParams.email, username: userParams.username, isAdmin: isNewTeam || undefined, avatarUrl: userParams.avatarUrl, teamId: team.id, + emailMatchOnly, ip, authentication: { + authenticationProviderId: authenticationProvider.id, ...authenticationParams, expiresAt: authenticationParams.expiresIn ? new Date(Date.now() + authenticationParams.expiresIn * 1000) : undefined, - authenticationProviderId: authenticationProvider.id, }, }); const { isNewUser, user } = result; diff --git a/server/commands/teamCreator.test.ts b/server/commands/teamProvisioner.test.ts similarity index 73% rename from server/commands/teamCreator.test.ts rename to server/commands/teamProvisioner.test.ts index a6aba15f2a..c6e5f3b436 100644 --- a/server/commands/teamCreator.test.ts +++ b/server/commands/teamProvisioner.test.ts @@ -2,16 +2,16 @@ import env from "@server/env"; import TeamDomain from "@server/models/TeamDomain"; import { buildTeam, buildUser } from "@server/test/factories"; import { flushdb } from "@server/test/support"; -import teamCreator from "./teamCreator"; +import teamProvisioner from "./teamProvisioner"; beforeEach(() => flushdb()); -describe("teamCreator", () => { +describe("teamProvisioner", () => { const ip = "127.0.0.1"; it("should create team and authentication provider", async () => { env.DEPLOYMENT = "hosted"; - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Test team", subdomain: "example", avatarUrl: "http://example.com/logo.png", @@ -35,7 +35,7 @@ describe("teamCreator", () => { await buildTeam({ subdomain: "myteam", }); - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Test team", subdomain: "myteam", avatarUrl: "http://example.com/logo.png", @@ -58,7 +58,7 @@ describe("teamCreator", () => { await buildTeam({ subdomain: "myteam1", }); - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Test team", subdomain: "myteam", avatarUrl: "http://example.com/logo.png", @@ -72,10 +72,63 @@ describe("teamCreator", () => { expect(result.team.subdomain).toEqual("myteam2"); }); + it("should return existing team", async () => { + env.DEPLOYMENT = "hosted"; + const authenticationProvider = { + name: "google", + providerId: "example.com", + }; + const existing = await buildTeam({ + subdomain: "example", + authenticationProviders: [authenticationProvider], + }); + const result = await teamProvisioner({ + name: "Updated name", + subdomain: "example", + authenticationProvider, + ip, + }); + const { team, isNewTeam } = result; + expect(team.id).toEqual(existing.id); + expect(team.name).toEqual(existing.name); + expect(team.subdomain).toEqual("example"); + expect(isNewTeam).toEqual(false); + }); + + it("should error on mismatched team and authentication provider", async () => { + env.DEPLOYMENT = "hosted"; + const exampleTeam = await buildTeam({ + subdomain: "example", + authenticationProviders: [ + { + name: "google", + providerId: "example.com", + }, + ], + }); + + let error; + try { + await teamProvisioner({ + teamId: exampleTeam.id, + name: "name", + subdomain: "other", + authenticationProvider: { + name: "google", + providerId: "other.com", + }, + ip, + }); + } catch (e) { + error = e; + } + expect(error.id).toEqual("invalid_authentication"); + }); + describe("self hosted", () => { it("should allow creating first team", async () => { env.DEPLOYMENT = undefined; - const { team, isNewTeam } = await teamCreator({ + const { team, isNewTeam } = await teamProvisioner({ name: "Test team", subdomain: "example", avatarUrl: "http://example.com/logo.png", @@ -96,7 +149,7 @@ describe("teamCreator", () => { let error; try { - await teamCreator({ + await teamProvisioner({ name: "Test team", subdomain: "example", avatarUrl: "http://example.com/logo.png", @@ -124,7 +177,7 @@ describe("teamCreator", () => { name: "allowed-domain.com", createdById: user.id, }); - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Updated name", subdomain: "example", domain: "allowed-domain.com", @@ -158,7 +211,7 @@ describe("teamCreator", () => { let error; try { - await teamCreator({ + await teamProvisioner({ name: "Updated name", subdomain: "example", domain: "other-domain.com", @@ -175,7 +228,7 @@ describe("teamCreator", () => { expect(error).toBeTruthy(); }); - it("should return exising team", async () => { + it("should return existing team", async () => { env.DEPLOYMENT = undefined; const authenticationProvider = { name: "google", @@ -185,7 +238,7 @@ describe("teamCreator", () => { subdomain: "example", authenticationProviders: [authenticationProvider], }); - const result = await teamCreator({ + const result = await teamProvisioner({ name: "Updated name", subdomain: "example", authenticationProvider, diff --git a/server/commands/teamCreator.ts b/server/commands/teamProvisioner.ts similarity index 88% rename from server/commands/teamCreator.ts rename to server/commands/teamProvisioner.ts index 210a09a264..621b46c313 100644 --- a/server/commands/teamCreator.ts +++ b/server/commands/teamProvisioner.ts @@ -1,8 +1,8 @@ import { sequelize } from "@server/database/sequelize"; import env from "@server/env"; import { - InvalidAuthenticationError, DomainNotAllowedError, + InvalidAuthenticationError, MaximumTeamsError, } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -10,14 +10,14 @@ import { APM } from "@server/logging/tracing"; import { Team, AuthenticationProvider, Event } from "@server/models"; import { generateAvatarUrl } from "@server/utils/avatars"; -type TeamCreatorResult = { +type TeamProvisionerResult = { team: Team; authenticationProvider: AuthenticationProvider; isNewTeam: boolean; }; type Props = { - id?: string; + teamId?: string; name: string; domain?: string; subdomain: string; @@ -29,18 +29,18 @@ type Props = { ip: string; }; -async function teamCreator({ - id, +async function teamProvisioner({ + teamId, name, domain, subdomain, avatarUrl, authenticationProvider, ip, -}: Props): Promise { +}: Props): Promise { let authP = await AuthenticationProvider.findOne({ - where: id - ? { ...authenticationProvider, teamId: id } + where: teamId + ? { ...authenticationProvider, teamId } : authenticationProvider, include: [ { @@ -59,11 +59,9 @@ async function teamCreator({ team: authP.team, isNewTeam: false, }; - } - // A team id was provided but no auth provider was found matching those credentials - // The user is attempting to log into a team with an incorrect SSO - fail the login - else if (id) { - throw InvalidAuthenticationError("incorrect authentication credentials"); + } else if (teamId) { + // The user is attempting to log into a team with an unfamiliar SSO provider + throw InvalidAuthenticationError(); } // This team has never been seen before, if self hosted the logic is different @@ -176,5 +174,5 @@ async function provisionSubdomain(team: Team, requestedSubdomain: string) { export default APM.traceFunction({ serviceName: "command", - spanName: "teamCreator", -})(teamCreator); + spanName: "teamProvisioner", +})(teamProvisioner); diff --git a/server/commands/userCreator.test.ts b/server/commands/userProvisioner.test.ts similarity index 76% rename from server/commands/userCreator.test.ts rename to server/commands/userProvisioner.test.ts index 6969ba7f61..31aa473759 100644 --- a/server/commands/userCreator.test.ts +++ b/server/commands/userProvisioner.test.ts @@ -2,20 +2,20 @@ import { v4 as uuidv4 } from "uuid"; import { TeamDomain } from "@server/models"; import { buildUser, buildTeam, buildInvite } from "@server/test/factories"; import { flushdb, seed } from "@server/test/support"; -import userCreator from "./userCreator"; +import userProvisioner from "./userProvisioner"; beforeEach(() => flushdb()); -describe("userCreator", () => { +describe("userProvisioner", () => { const ip = "127.0.0.1"; - it("should update exising user and authentication", async () => { + it("should update existing user and authentication", async () => { const existing = await buildUser(); const authentications = await existing.$get("authentications"); const existingAuth = authentications[0]; const newEmail = "test@example.com"; const newUsername = "tname"; - const result = await userCreator({ + const result = await userProvisioner({ name: existing.name, email: newEmail, username: newUsername, @@ -30,9 +30,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual(newEmail); expect(user.username).toEqual(newUsername); expect(isNewUser).toEqual(false); @@ -50,7 +51,7 @@ describe("userCreator", () => { authentications: [], }); - const result = await userCreator({ + const result = await userProvisioner({ name: existing.name, email, username: "new-username", @@ -65,9 +66,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); const authentications = await user.$get("authentications"); expect(authentications.length).toEqual(1); @@ -85,7 +87,7 @@ describe("userCreator", () => { teamId: team.id, }); - const result = await userCreator({ + const result = await userProvisioner({ name: existing.name, email, username: "new-username", @@ -100,9 +102,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); const authentications = await user.$get("authentications"); expect(authentications.length).toEqual(1); @@ -115,7 +118,7 @@ describe("userCreator", () => { const existingAuth = authentications[0]; const newEmail = "test@example.com"; await existing.destroy(); - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "test@example.com", teamId: existing.teamId, @@ -128,9 +131,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual(newEmail); expect(isNewUser).toEqual(true); }); @@ -142,13 +146,13 @@ describe("userCreator", () => { let error; try { - await userCreator({ + await userProvisioner({ name: "Test Name", email: "test@example.com", teamId: existing.teamId, ip, authentication: { - authenticationProviderId: "example.org", + authenticationProviderId: uuidv4(), providerId: existingAuth.providerId, accessToken: "123", scopes: ["read"], @@ -165,7 +169,7 @@ describe("userCreator", () => { const team = await buildTeam(); const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "test@example.com", username: "tname", @@ -179,9 +183,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual("test@example.com"); expect(user.username).toEqual("tname"); expect(user.isAdmin).toEqual(false); @@ -195,7 +200,7 @@ describe("userCreator", () => { }); const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "test@example.com", username: "tname", @@ -219,7 +224,7 @@ describe("userCreator", () => { }); const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "test@example.com", username: "tname", @@ -236,7 +241,7 @@ describe("userCreator", () => { expect(tname.username).toEqual("tname"); expect(tname.isAdmin).toEqual(false); expect(tname.isViewer).toEqual(true); - const tname2Result = await userCreator({ + const tname2Result = await userProvisioner({ name: "Test2 Name", email: "tes2@example.com", username: "tname2", @@ -264,7 +269,7 @@ describe("userCreator", () => { }); const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: invite.name, email: "invite@ExamPle.com", teamId: invite.teamId, @@ -277,13 +282,46 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual(invite.email); expect(isNewUser).toEqual(true); }); + it("should create a user from an invited user using email match", async () => { + const externalUser = await buildUser({ + email: "external@example.com", + }); + + const team = await buildTeam({ inviteRequired: true }); + const invite = await buildInvite({ + teamId: team.id, + email: externalUser.email, + }); + + const authenticationProviders = await team.$get("authenticationProviders"); + const authenticationProvider = authenticationProviders[0]; + const result = await userProvisioner({ + name: invite.name, + email: "external@ExamPle.com", // ensure that email is case insensistive + teamId: invite.teamId, + emailMatchOnly: true, + ip, + authentication: { + authenticationProviderId: authenticationProvider.id, + providerId: "whatever", + accessToken: "123", + scopes: ["read"], + }, + }); + const { user, authentication, isNewUser } = result; + expect(authentication).toEqual(null); + expect(user.id).toEqual(invite.id); + expect(isNewUser).toEqual(true); + }); + it("should reject an uninvited user when invites are required", async () => { const team = await buildTeam({ inviteRequired: true }); @@ -292,7 +330,7 @@ describe("userCreator", () => { let error; try { - await userCreator({ + await userProvisioner({ name: "Uninvited User", email: "invite@ExamPle.com", teamId: team.id, @@ -323,7 +361,7 @@ describe("userCreator", () => { const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; - const result = await userCreator({ + const result = await userProvisioner({ name: "Test Name", email: "user@example-company.com", teamId: team.id, @@ -336,9 +374,10 @@ describe("userCreator", () => { }, }); const { user, authentication, isNewUser } = result; - expect(authentication.accessToken).toEqual("123"); - expect(authentication.scopes.length).toEqual(1); - expect(authentication.scopes[0]).toEqual("read"); + expect(authentication).toBeDefined(); + expect(authentication?.accessToken).toEqual("123"); + expect(authentication?.scopes.length).toEqual(1); + expect(authentication?.scopes[0]).toEqual("read"); expect(user.email).toEqual("user@example-company.com"); expect(isNewUser).toEqual(true); }); @@ -356,7 +395,7 @@ describe("userCreator", () => { let error; try { - await userCreator({ + await userProvisioner({ name: "Bad Domain User", email: "user@example.com", teamId: team.id, diff --git a/server/commands/userCreator.ts b/server/commands/userProvisioner.ts similarity index 83% rename from server/commands/userCreator.ts rename to server/commands/userProvisioner.ts index f9c6a9bfb0..9e51ddb050 100644 --- a/server/commands/userCreator.ts +++ b/server/commands/userProvisioner.ts @@ -1,12 +1,16 @@ import { sequelize } from "@server/database/sequelize"; import InviteAcceptedEmail from "@server/emails/templates/InviteAcceptedEmail"; -import { DomainNotAllowedError, InviteRequiredError } from "@server/errors"; +import { + DomainNotAllowedError, + InvalidAuthenticationError, + InviteRequiredError, +} from "@server/errors"; import { Event, Team, User, UserAuthentication } from "@server/models"; -type UserCreatorResult = { +type UserProvisionerResult = { user: User; isNewUser: boolean; - authentication: UserAuthentication; + authentication: UserAuthentication | null; }; type Props = { @@ -16,6 +20,7 @@ type Props = { isAdmin?: boolean; avatarUrl?: string | null; teamId: string; + emailMatchOnly?: boolean; ip: string; authentication: { authenticationProviderId: string; @@ -27,17 +32,18 @@ type Props = { }; }; -export default async function userCreator({ +export default async function userProvisioner({ name, email, username, isAdmin, + emailMatchOnly, avatarUrl, teamId, authentication, ip, -}: Props): Promise { - const { authenticationProviderId, providerId, ...rest } = authentication; +}: Props): Promise { + const { providerId, authenticationProviderId, ...rest } = authentication; const auth = await UserAuthentication.findOne({ where: { @@ -87,9 +93,8 @@ export default async function userCreator({ await auth.destroy(); } - // A `user` record might exist in the form of an invite even if there is no - // existing authentication record that matches. In Outline an invite is a - // shell user record. + // A `user` record may exist even if there is no existing authentication record. + // This is either an invite or a user that's external to the team const existingUser = await User.scope([ "withAuthentications", "withTeam", @@ -102,12 +107,11 @@ export default async function userCreator({ }, }); - // We have an existing invite for his user, so we need to update it with our - // new details, link up the authentication method, and count this as a new - // user creation. + // We have an existing user, so we need to update it with our + // new details and count this as a new user creation. if (existingUser) { // A `user` record might exist in the form of an invite. - // In Outline an invite is a shell user record with no authentication method + // An invite is a shell user record with no authentication method // that's never been active before. const isInvite = existingUser.isInvited; @@ -145,6 +149,12 @@ export default async function userCreator({ } ); + // We don't want to associate a user auth with the auth provider + // if we're doing a simple email match, so early return here + if (emailMatchOnly) { + return null; + } + return await existingUser.$create( "authentication", authentication, @@ -171,9 +181,16 @@ export default async function userCreator({ authentication: auth, isNewUser: isInvite, }; + } else if (emailMatchOnly) { + // There's no existing invite or user that matches the external auth email + // This is simply unauthorized + throw InvalidAuthenticationError(); } + // // No auth, no user – this is an entirely new sign in. + // + const transaction = await User.sequelize!.transaction(); try { diff --git a/server/routes/auth/providers/azure.ts b/server/routes/auth/providers/azure.ts index 0e99e4bf01..18649906ce 100644 --- a/server/routes/auth/providers/azure.ts +++ b/server/routes/auth/providers/azure.ts @@ -4,6 +4,7 @@ import jwt from "jsonwebtoken"; import type { Context } from "koa"; import Router from "koa-router"; import { Profile } from "passport"; +import { slugifyDomain } from "@shared/utils/domains"; import accountProvisioner, { AccountProvisionerResult, } from "@server/commands/accountProvisioner"; @@ -95,12 +96,13 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) { const team = await getTeamFromContext(ctx); const domain = email.split("@")[1]; - const subdomain = domain.split(".")[0]; + const subdomain = slugifyDomain(domain); + const teamName = organization.displayName; const result = await accountProvisioner({ ip: ctx.ip, team: { - id: team?.id, + teamId: team?.id, name: teamName, domain, subdomain, diff --git a/server/routes/auth/providers/google.ts b/server/routes/auth/providers/google.ts index 16af9d9126..4f9cd23ded 100644 --- a/server/routes/auth/providers/google.ts +++ b/server/routes/auth/providers/google.ts @@ -11,7 +11,6 @@ import accountProvisioner, { import env from "@server/env"; import { GmailAccountCreationError, - InviteRequiredError, TeamDomainRequiredError, } from "@server/errors"; import passportMiddleware from "@server/middlewares/passport"; @@ -19,7 +18,7 @@ import { User } from "@server/models"; import { StateStore, getTeamFromContext } from "@server/utils/passport"; const router = new Router(); -const providerName = "google"; +const GOOGLE = "google"; const scopes = [ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", @@ -34,7 +33,7 @@ type GoogleProfile = Profile & { email: string; picture: string; _json: { - hd: string; + hd?: string; }; }; @@ -63,87 +62,66 @@ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) { ) => void ) { try { - let result; - // "domain" is the Google Workspaces domain const domain = profile._json.hd; const team = await getTeamFromContext(ctx); - // Existence of domain means this is a Google Workspaces account - // so we'll attempt to provision an account (team and user) - if (domain) { - // remove the TLD and form a subdomain from the remaining - // subdomains of the form "foo.bar.com" are allowed as primary Google Workspaces domains - // see https://support.google.com/nonprofits/thread/19685140/using-a-subdomain-as-a-primary-domain - const subdomain = slugifyDomain(domain); - const teamName = capitalize(subdomain); - - // Request a larger size profile picture than the default by tweaking - // the query parameter. - const avatarUrl = profile.picture.replace("=s96-c", "=s128-c"); - - // if a team can be inferred, we assume the user is only interested in signing into - // that team in particular; otherwise, we will do a best effort at finding their account - // or provisioning a new one (within AccountProvisioner) - result = await accountProvisioner({ - ip: ctx.ip, - team: { - id: team?.id, - name: teamName, - domain, - subdomain, - }, - user: { - email: profile.email, - name: profile.displayName, - avatarUrl, - }, - authenticationProvider: { - name: providerName, - providerId: domain, - }, - authentication: { - providerId: profile.id, - accessToken, - refreshToken, - expiresIn: params.expires_in, - scopes, - }, - }); - } else { - // No domain means it's a personal Gmail account - // We only allow sign-in to existing user accounts with these - if (!team) { - // No team usually means this is the apex domain - // Throw different errors depending on whether we think the user is - // trying to create a new account, or log-in to an existing one - const userExists = await User.count({ - where: { email: profile.email.toLowerCase() }, - }); - - if (!userExists) { - throw GmailAccountCreationError(); - } - - throw TeamDomainRequiredError(); - } - - const user = await User.findOne({ - where: { teamId: team.id, email: profile.email.toLowerCase() }, + // No profile domain means personal gmail account + // No team implies the request came from the apex domain + // This combination is always an error + if (!domain && !team) { + const userExists = await User.count({ + where: { email: profile.email.toLowerCase() }, }); - if (!user) { - throw InviteRequiredError(); + // Users cannot create a team with personal gmail accounts + if (!userExists) { + throw GmailAccountCreationError(); } - result = { - user, - team, - isNewUser: false, - isNewTeam: false, - }; + // To log-in with a personal account, users must specify a team subdomain + throw TeamDomainRequiredError(); } + // remove the TLD and form a subdomain from the remaining + // subdomains of the form "foo.bar.com" are allowed as primary Google Workspaces domains + // see https://support.google.com/nonprofits/thread/19685140/using-a-subdomain-as-a-primary-domain + const subdomain = domain ? slugifyDomain(domain) : ""; + const teamName = capitalize(subdomain); + + // Request a larger size profile picture than the default by tweaking + // the query parameter. + const avatarUrl = profile.picture.replace("=s96-c", "=s128-c"); + + // if a team can be inferred, we assume the user is only interested in signing into + // that team in particular; otherwise, we will do a best effort at finding their account + // or provisioning a new one (within AccountProvisioner) + const result = await accountProvisioner({ + ip: ctx.ip, + team: { + teamId: team?.id, + name: teamName, + domain, + subdomain, + }, + user: { + email: profile.email, + name: profile.displayName, + avatarUrl, + }, + authenticationProvider: { + name: GOOGLE, + providerId: domain ?? "", + }, + authentication: { + providerId: profile.id, + accessToken, + refreshToken, + expiresIn: params.expires_in, + scopes, + }, + }); + return done(null, result.user, result); } catch (err) { return done(err, null); @@ -154,13 +132,13 @@ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) { router.get( "google", - passport.authenticate(providerName, { + passport.authenticate(GOOGLE, { accessType: "offline", prompt: "select_account consent", }) ); - router.get("google.callback", passportMiddleware(providerName)); + router.get("google.callback", passportMiddleware(GOOGLE)); } export default router; diff --git a/server/routes/auth/providers/oidc.ts b/server/routes/auth/providers/oidc.ts index 625a36d10a..8b8e159246 100644 --- a/server/routes/auth/providers/oidc.ts +++ b/server/routes/auth/providers/oidc.ts @@ -97,7 +97,7 @@ if (env.OIDC_CLIENT_ID && env.OIDC_CLIENT_SECRET) { const result = await accountProvisioner({ ip: ctx.ip, team: { - id: team?.id, + teamId: team?.id, // https://github.com/outline/outline/pull/2388#discussion_r681120223 name: "Wiki", domain, diff --git a/server/routes/auth/providers/slack.ts b/server/routes/auth/providers/slack.ts index ba2126f369..4d98a60cad 100644 --- a/server/routes/auth/providers/slack.ts +++ b/server/routes/auth/providers/slack.ts @@ -79,7 +79,7 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) { const result = await accountProvisioner({ ip: ctx.ip, team: { - id: team?.id, + teamId: team?.id, name: profile.team.name, subdomain: profile.team.domain, avatarUrl: profile.team.image_230, From ec35af4bc55067fde7b34615ee084840002d4820 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 24 Jul 2022 13:40:04 +0100 Subject: [PATCH 04/30] Refactor validations --- .../Sidebar/components/DocumentLink.tsx | 4 ++-- app/scenes/CollectionEdit.tsx | 4 ++-- app/scenes/CollectionNew.tsx | 4 ++-- .../Document/components/EditableTitle.tsx | 4 ++-- app/stores/DocumentsStore.ts | 4 ++-- server/commands/documentImporter.ts | 4 ++-- server/commands/pinCreator.ts | 9 +++++---- server/models/Collection.ts | 5 ++--- server/models/Document.ts | 6 +++--- server/models/Revision.ts | 6 +++--- server/models/TeamDomain.ts | 6 +++--- shared/constants.ts | 4 ---- shared/validations.ts | 20 ++++++++++++++++++- 13 files changed, 47 insertions(+), 33 deletions(-) diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 8a7aac0df3..c0519f293e 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -6,8 +6,8 @@ import { useDrag, useDrop } from "react-dnd"; import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; import styled from "styled-components"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import { sortNavigationNodes } from "@shared/utils/collections"; +import { DocumentValidation } from "@shared/validations"; import Collection from "~/models/Collection"; import Document from "~/models/Document"; import Fade from "~/components/Fade"; @@ -319,7 +319,7 @@ function InnerDocumentLink( onSubmit={handleTitleChange} onEditing={handleTitleEditing} canUpdate={canUpdate} - maxLength={MAX_TITLE_LENGTH} + maxLength={DocumentValidation.maxTitleLength} /> } isActive={(match, location: Location<{ starred?: boolean }>) => diff --git a/app/scenes/CollectionEdit.tsx b/app/scenes/CollectionEdit.tsx index 3ddbdadcb6..31a235ec72 100644 --- a/app/scenes/CollectionEdit.tsx +++ b/app/scenes/CollectionEdit.tsx @@ -3,7 +3,7 @@ import { observer } from "mobx-react"; import { useState } from "react"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; +import { CollectionValidation } from "@shared/validations"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; import IconPicker from "~/components/IconPicker"; @@ -94,7 +94,7 @@ const CollectionEdit = ({ collectionId, onSubmit }: Props) => { type="text" label={t("Name")} onChange={handleNameChange} - maxLength={MAX_TITLE_LENGTH} + maxLength={CollectionValidation.maxNameLength} value={name} required autoFocus diff --git a/app/scenes/CollectionNew.tsx b/app/scenes/CollectionNew.tsx index ce20cbbf10..5ea45a0957 100644 --- a/app/scenes/CollectionNew.tsx +++ b/app/scenes/CollectionNew.tsx @@ -3,7 +3,7 @@ import { observable } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; import { withTranslation, Trans, WithTranslation } from "react-i18next"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; +import { CollectionValidation } from "@shared/validations"; import RootStore from "~/stores/RootStore"; import Collection from "~/models/Collection"; import Button from "~/components/Button"; @@ -128,7 +128,7 @@ class CollectionNew extends React.Component { type="text" label={t("Name")} onChange={this.handleNameChange} - maxLength={MAX_TITLE_LENGTH} + maxLength={CollectionValidation.maxNameLength} value={this.name} required autoFocus diff --git a/app/scenes/Document/components/EditableTitle.tsx b/app/scenes/Document/components/EditableTitle.tsx index d1cffeafcb..e708293648 100644 --- a/app/scenes/Document/components/EditableTitle.tsx +++ b/app/scenes/Document/components/EditableTitle.tsx @@ -2,13 +2,13 @@ import { observer } from "mobx-react"; import * as React from "react"; import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import { light } from "@shared/styles/theme"; import { getCurrentDateAsString, getCurrentDateTimeAsString, getCurrentTimeAsString, } from "@shared/utils/date"; +import { DocumentValidation } from "@shared/validations"; import Document from "~/models/Document"; import ContentEditable, { RefHandle } from "~/components/ContentEditable"; import Star, { AnimatedStar } from "~/components/Star"; @@ -132,7 +132,7 @@ const EditableTitle = React.forwardRef( $emojiWidth={emojiWidth} $isStarred={document.isStarred} autoFocus={!value} - maxLength={MAX_TITLE_LENGTH} + maxLength={DocumentValidation.maxTitleLength} readOnly={readOnly} dir="auto" ref={ref} diff --git a/app/stores/DocumentsStore.ts b/app/stores/DocumentsStore.ts index 75bf6846ef..efd4c74b13 100644 --- a/app/stores/DocumentsStore.ts +++ b/app/stores/DocumentsStore.ts @@ -2,10 +2,10 @@ import path from "path"; import invariant from "invariant"; import { find, orderBy, filter, compact, omitBy } from "lodash"; import { observable, action, computed, runInAction } from "mobx"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import { DateFilter } from "@shared/types"; import { subtractDate } from "@shared/utils/date"; import naturalSort from "@shared/utils/naturalSort"; +import { DocumentValidation } from "@shared/validations"; import BaseStore from "~/stores/BaseStore"; import RootStore from "~/stores/RootStore"; import Document from "~/models/Document"; @@ -553,7 +553,7 @@ export default class DocumentsStore extends BaseStore { template: document.template, title: `${document.title.slice( 0, - MAX_TITLE_LENGTH - append.length + DocumentValidation.maxTitleLength - append.length )}${append}`, text: document.text, }); diff --git a/server/commands/documentImporter.ts b/server/commands/documentImporter.ts index b7b8a25d8d..974fc0ca86 100644 --- a/server/commands/documentImporter.ts +++ b/server/commands/documentImporter.ts @@ -5,8 +5,8 @@ import mammoth from "mammoth"; import quotedPrintable from "quoted-printable"; import { Transaction } from "sequelize"; import utf8 from "utf8"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import parseTitle from "@shared/utils/parseTitle"; +import { DocumentValidation } from "@shared/validations"; import { APM } from "@server/logging/tracing"; import { User } from "@server/models"; import dataURItoBuffer from "@server/utils/dataURItoBuffer"; @@ -221,7 +221,7 @@ async function documentImporter({ } // It's better to truncate particularly long titles than fail the import - title = truncate(title, { length: MAX_TITLE_LENGTH }); + title = truncate(title, { length: DocumentValidation.maxTitleLength }); return { text, diff --git a/server/commands/pinCreator.ts b/server/commands/pinCreator.ts index 7ce38427b4..12b957ea17 100644 --- a/server/commands/pinCreator.ts +++ b/server/commands/pinCreator.ts @@ -1,11 +1,10 @@ import fractionalIndex from "fractional-index"; import { Sequelize, Op, WhereOptions } from "sequelize"; +import { PinValidation } from "@shared/validations"; import { sequelize } from "@server/database/sequelize"; import { ValidationError } from "@server/errors"; import { Pin, User, Event } from "@server/models"; -const MAX_PINS = 8; - type Props = { /** The user creating the pin */ user: User; @@ -40,8 +39,10 @@ export default async function pinCreator({ }; const count = await Pin.count({ where }); - if (count >= MAX_PINS) { - throw ValidationError(`You cannot pin more than ${MAX_PINS} documents`); + if (count >= PinValidation.max) { + throw ValidationError( + `You cannot pin more than ${PinValidation.max} documents` + ); } if (!index) { diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 71d5aa2f29..1674cb1a56 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -21,7 +21,6 @@ import { Length as SimpleLength, } from "sequelize-typescript"; import isUUID from "validator/lib/isUUID"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import { sortNavigationNodes } from "@shared/utils/collections"; import { SLUG_URL_REGEX } from "@shared/utils/urlHelpers"; import { CollectionValidation } from "@shared/validations"; @@ -144,8 +143,8 @@ class Collection extends ParanoidModel { @NotContainsUrl @Length({ - max: MAX_TITLE_LENGTH, - msg: `name must be ${MAX_TITLE_LENGTH} characters or less`, + max: CollectionValidation.maxNameLength, + msg: `name must be ${CollectionValidation.maxNameLength} characters or less`, }) @Column name: string; diff --git a/server/models/Document.ts b/server/models/Document.ts index 42846cae4d..68cdd55655 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -35,12 +35,12 @@ import { import MarkdownSerializer from "slate-md-serializer"; import isUUID from "validator/lib/isUUID"; import * as Y from "yjs"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; import { DateFilter } from "@shared/types"; import getTasks from "@shared/utils/getTasks"; import parseTitle from "@shared/utils/parseTitle"; import unescape from "@shared/utils/unescape"; import { SLUG_URL_REGEX } from "@shared/utils/urlHelpers"; +import { DocumentValidation } from "@shared/validations"; import { parser } from "@server/editor"; import slugify from "@server/utils/slugify"; import Backlink from "./Backlink"; @@ -196,8 +196,8 @@ class Document extends ParanoidModel { urlId: string; @Length({ - max: MAX_TITLE_LENGTH, - msg: `Document title must be ${MAX_TITLE_LENGTH} characters or less`, + max: DocumentValidation.maxTitleLength, + msg: `Document title must be ${DocumentValidation.maxTitleLength} characters or less`, }) @Column title: string; diff --git a/server/models/Revision.ts b/server/models/Revision.ts index 572a67d8c5..c431832677 100644 --- a/server/models/Revision.ts +++ b/server/models/Revision.ts @@ -10,7 +10,7 @@ import { Length as SimpleLength, } from "sequelize-typescript"; import MarkdownSerializer from "slate-md-serializer"; -import { MAX_TITLE_LENGTH } from "@shared/constants"; +import { DocumentValidation } from "@shared/validations"; import Document from "./Document"; import User from "./User"; import IdModel from "./base/IdModel"; @@ -43,8 +43,8 @@ class Revision extends IdModel { editorVersion: string; @Length({ - max: MAX_TITLE_LENGTH, - msg: `Revision title must be ${MAX_TITLE_LENGTH} characters or less`, + max: DocumentValidation.maxTitleLength, + msg: `Revision title must be ${DocumentValidation.maxTitleLength} characters or less`, }) @Column title: string; diff --git a/server/models/TeamDomain.ts b/server/models/TeamDomain.ts index 6779f2607f..08d01e32b0 100644 --- a/server/models/TeamDomain.ts +++ b/server/models/TeamDomain.ts @@ -9,7 +9,7 @@ import { BeforeValidate, BeforeCreate, } from "sequelize-typescript"; -import { MAX_TEAM_DOMAINS } from "@shared/constants"; +import { TeamValidation } from "@shared/validations"; import { ValidationError } from "@server/errors"; import Team from "./Team"; import User from "./User"; @@ -59,9 +59,9 @@ class TeamDomain extends IdModel { const count = await this.count({ where: { teamId: model.teamId }, }); - if (count >= MAX_TEAM_DOMAINS) { + if (count >= TeamValidation.maxDomains) { throw ValidationError( - `You have reached the limit of ${MAX_TEAM_DOMAINS} domains` + `You have reached the limit of ${TeamValidation.maxDomains} domains` ); } } diff --git a/shared/constants.ts b/shared/constants.ts index e3f4be290a..cc5abc5b20 100644 --- a/shared/constants.ts +++ b/shared/constants.ts @@ -1,7 +1,3 @@ export const USER_PRESENCE_INTERVAL = 5000; export const MAX_AVATAR_DISPLAY = 6; - -export const MAX_TITLE_LENGTH = 100; - -export const MAX_TEAM_DOMAINS = 10; diff --git a/shared/validations.ts b/shared/validations.ts index 184ecb8471..b1d2bf7b39 100644 --- a/shared/validations.ts +++ b/shared/validations.ts @@ -1,4 +1,22 @@ export const CollectionValidation = { - /* The maximum length of the collection description */ + /** The maximum length of the collection description */ maxDescriptionLength: 1000, + + /** The maximum length of the collection name */ + maxNameLength: 100, +}; + +export const DocumentValidation = { + /** The maximum length of the document title */ + maxTitleLength: 100, +}; + +export const PinValidation = { + /** The maximum number of pinned documents on an individual collection or home screen */ + max: 8, +}; + +export const TeamValidation = { + /** The maximum number of domains per team */ + maxDomains: 10, }; From 71da57773e5ec5db4de6c6febf2c279896df42d4 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 24 Jul 2022 14:09:43 +0100 Subject: [PATCH 05/30] docs --- server/commands/accountProvisioner.ts | 24 ++++++++++++++++++++++++ server/commands/teamProvisioner.ts | 12 ++++++++++++ server/commands/userProvisioner.ts | 16 ++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/server/commands/accountProvisioner.ts b/server/commands/accountProvisioner.ts index f576f83937..ff4d0d017e 100644 --- a/server/commands/accountProvisioner.ts +++ b/server/commands/accountProvisioner.ts @@ -13,29 +13,53 @@ import teamProvisioner from "./teamProvisioner"; import userProvisioner from "./userProvisioner"; type Props = { + /** The IP address of the incoming request */ ip: string; + /** Details of the user logging in from SSO provider */ user: { + /** The displayed name of the user */ name: string; + /** The email address of the user */ email: string; + /** The public url of an image representing the user */ avatarUrl?: string | null; + /** The username of the user */ username?: string; }; + /** Details of the team the user is logging into */ team: { + /** + * The internal ID of the team that is being logged into based on the + * subdomain that the request came from, if any. + */ teamId?: string; + /** The displayed name of the team */ name: string; + /** The domain name from the email of the user logging in */ domain?: string; + /** The preferred subdomain to provision for the team if not yet created */ subdomain: string; + /** The public url of an image representing the team */ avatarUrl?: string | null; }; + /** Details of the authentication provider being used */ authenticationProvider: { + /** The name of the authentication provider, eg "google" */ name: string; + /** External identifier of the authentication provider */ providerId: string; }; + /** Details of the authentication from SSO provider */ authentication: { + /** External identifier of the user in the authentication provider */ providerId: string; + /** The scopes granted by the access token */ scopes: string[]; + /** The token provided by the authentication provider */ accessToken?: string; + /** The refresh token provided by the authentication provider */ refreshToken?: string; + /** A number of seconds that the given access token expires in */ expiresIn?: number; }; }; diff --git a/server/commands/teamProvisioner.ts b/server/commands/teamProvisioner.ts index 621b46c313..8c93cc49f2 100644 --- a/server/commands/teamProvisioner.ts +++ b/server/commands/teamProvisioner.ts @@ -17,15 +17,27 @@ type TeamProvisionerResult = { }; type Props = { + /** + * The internal ID of the team that is being logged into based on the + * subdomain that the request came from, if any. + */ teamId?: string; + /** The displayed name of the team */ name: string; + /** The domain name from the email of the user logging in */ domain?: string; + /** The preferred subdomain to provision for the team if not yet created */ subdomain: string; + /** The public url of an image representing the team */ avatarUrl?: string | null; + /** Details of the authentication provider being used */ authenticationProvider: { + /** The name of the authentication provider, eg "google" */ name: string; + /** External identifier of the authentication provider */ providerId: string; }; + /** The IP address of the incoming request */ ip: string; }; diff --git a/server/commands/userProvisioner.ts b/server/commands/userProvisioner.ts index 9e51ddb050..280a8a4af3 100644 --- a/server/commands/userProvisioner.ts +++ b/server/commands/userProvisioner.ts @@ -14,20 +14,36 @@ type UserProvisionerResult = { }; type Props = { + /** The displayed name of the user */ name: string; + /** The email address of the user */ email: string; + /** The username of the user */ username?: string; + /** Provision the new user as an administrator */ isAdmin?: boolean; + /** The public url of an image representing the user */ avatarUrl?: string | null; + /** + * The internal ID of the team that is being logged into based on the + * subdomain that the request came from, if any. + */ teamId: string; + /** Only match against existing user accounts using email, do not create a new account */ emailMatchOnly?: boolean; + /** The IP address of the incoming request */ ip: string; authentication: { authenticationProviderId: string; + /** External identifier of the user in the authentication provider */ providerId: string; + /** The scopes granted by the access token */ scopes: string[]; + /** The token provided by the authentication provider */ accessToken?: string; + /** The refresh token provided by the authentication provider */ refreshToken?: string; + /** The timestamp when the access token expires */ expiresAt?: Date; }; }; From 5e852170f925299ef0a8ef6a12ecb1165b44e6d0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 24 Jul 2022 19:15:34 +0100 Subject: [PATCH 06/30] perf: Read attachment buffers only when neccessary, closes #3849 --- server/queues/tasks/ImportMarkdownZipTask.ts | 2 +- server/queues/tasks/ImportNotionTask.ts | 2 +- server/queues/tasks/ImportTask.ts | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/server/queues/tasks/ImportMarkdownZipTask.ts b/server/queues/tasks/ImportMarkdownZipTask.ts index 8195918840..4053619fd2 100644 --- a/server/queues/tasks/ImportMarkdownZipTask.ts +++ b/server/queues/tasks/ImportMarkdownZipTask.ts @@ -71,7 +71,7 @@ export default class ImportMarkdownZipTask extends ImportTask { name: child.name, path: child.path, mimeType: mime.lookup(child.path) || "application/octet-stream", - buffer: await zipObject.async("nodebuffer"), + buffer: () => zipObject.async("nodebuffer"), }); return; } diff --git a/server/queues/tasks/ImportNotionTask.ts b/server/queues/tasks/ImportNotionTask.ts index 3607cf7400..bcbaa8c253 100644 --- a/server/queues/tasks/ImportNotionTask.ts +++ b/server/queues/tasks/ImportNotionTask.ts @@ -82,7 +82,7 @@ export default class ImportNotionTask extends ImportTask { name: child.name, path: child.path, mimeType, - buffer: await zipObject.async("nodebuffer"), + buffer: () => zipObject.async("nodebuffer"), sourceId, }); return; diff --git a/server/queues/tasks/ImportTask.ts b/server/queues/tasks/ImportTask.ts index 0c2091b422..03323368a8 100644 --- a/server/queues/tasks/ImportTask.ts +++ b/server/queues/tasks/ImportTask.ts @@ -66,7 +66,7 @@ export type StructuredImportData = { name: string; path: string; mimeType: string; - buffer: Buffer; + buffer: () => Promise; /** Optional id from import source, useful for mapping */ sourceId?: string; }[]; @@ -215,7 +215,7 @@ export default abstract class ImportTask extends BaseTask { id: item.id, name: item.name, type: item.mimeType, - buffer: item.buffer, + buffer: await item.buffer(), user, ip, transaction, From 865e6d048ec8f29e77d24cfbc8560322a6f5344b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 24 Jul 2022 20:29:59 +0100 Subject: [PATCH 07/30] fix: 'Export' option missing in collection menu for admins --- app/menus/CollectionMenu.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/menus/CollectionMenu.tsx b/app/menus/CollectionMenu.tsx index 0fbc5fc9fc..8591c033e1 100644 --- a/app/menus/CollectionMenu.tsx +++ b/app/menus/CollectionMenu.tsx @@ -266,7 +266,7 @@ function CollectionMenu({ { type: "button", title: `${t("Export")}…`, - visible: !!(collection && canUserInTeam.export), + visible: !!(collection && canUserInTeam.createExport), onClick: handleExport, icon: , }, @@ -296,7 +296,7 @@ function CollectionMenu({ alphabeticalSort, handleEdit, handlePermissions, - canUserInTeam.export, + canUserInTeam.createExport, handleExport, handleDelete, handleChangeSort, From 1c5864deee0cd35367f4e4da5da42da739210199 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 24 Jul 2022 13:11:11 -0700 Subject: [PATCH 08/30] chore(deps-dev): bump eslint-config-prettier from 8.3.0 to 8.5.0 (#3807) Bumps [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) from 8.3.0 to 8.5.0. - [Release notes](https://github.com/prettier/eslint-config-prettier/releases) - [Changelog](https://github.com/prettier/eslint-config-prettier/blob/main/CHANGELOG.md) - [Commits](https://github.com/prettier/eslint-config-prettier/compare/v8.3.0...v8.5.0) --- updated-dependencies: - dependency-name: eslint-config-prettier dependency-type: direct:development update-type: version-update:semver-minor ... 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 c574c93a12..cc82632e54 100644 --- a/package.json +++ b/package.json @@ -300,7 +300,7 @@ "enzyme": "^3.11.0", "enzyme-adapter-react-16": "^1.15.6", "eslint": "^7.6.0", - "eslint-config-prettier": "^8.3.0", + "eslint-config-prettier": "^8.5.0", "eslint-import-resolver-typescript": "^2.5.0", "eslint-plugin-es": "^4.1.0", "eslint-plugin-import": "^2.25.3", diff --git a/yarn.lock b/yarn.lock index a5b7ac5dff..cc120daf78 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6738,10 +6738,10 @@ escodegen@^2.0.0: optionalDependencies: source-map "~0.6.1" -eslint-config-prettier@^8.3.0: - version "8.3.0" - resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz#f7471b20b6fe8a9a9254cc684454202886a2dd7a" - integrity sha512-BgZuLUSeKzvlL/VUjx/Yb787VQ26RU3gGjA3iiFvdsp/2bMfVIWUVP7tjxtjS0e+HP409cPlPvNkQloz8C91ew== +eslint-config-prettier@^8.5.0: + version "8.5.0" + resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.5.0.tgz#5a81680ec934beca02c7b1a61cf8ca34b66feab1" + integrity sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q== eslint-import-resolver-node@^0.3.6: version "0.3.6" From 53a08cf3078c1feda1966c7f28747ad6a4e1d665 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 24 Jul 2022 23:51:04 +0100 Subject: [PATCH 09/30] chore: Basic protection against zip bombs --- server/utils/zip.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/server/utils/zip.ts b/server/utils/zip.ts index 1aa710d42b..67ba2c49ee 100644 --- a/server/utils/zip.ts +++ b/server/utils/zip.ts @@ -3,6 +3,7 @@ import path from "path"; import JSZip, { JSZipObject } from "jszip"; import { find } from "lodash"; import tmp from "tmp"; +import { ValidationError } from "@server/errors"; import Logger from "@server/logging/Logger"; import Attachment from "@server/models/Attachment"; import Collection from "@server/models/Collection"; @@ -193,8 +194,19 @@ export type FileTreeNode = { * @param paths An array of paths to files in the zip * @returns */ -export function zipAsFileTree(zip: JSZip) { - const paths = Object.keys(zip.files).map((filePath) => `/${filePath}`); +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) { From 30190866f8c2c6189105d34cb6b508f4917b4564 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 25 Jul 2022 08:59:30 +0100 Subject: [PATCH 10/30] test: Flakey test --- server/queues/tasks/ImportNotionTask.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/server/queues/tasks/ImportNotionTask.test.ts b/server/queues/tasks/ImportNotionTask.test.ts index a8c7838dde..68887aa51c 100644 --- a/server/queues/tasks/ImportNotionTask.test.ts +++ b/server/queues/tasks/ImportNotionTask.test.ts @@ -74,7 +74,11 @@ describe("ImportNotionTask", () => { // Check that the image url was replaced in the text with a redirect const attachments = Array.from(response.attachments.values()); + const attachment = attachments.find((att) => + att.key.endsWith("Screen_Shot_2022-04-21_at_2.23.26_PM.png") + ); + const documents = Array.from(response.documents.values()); - expect(documents[1].text).toContain(attachments[1].redirectUrl); + expect(documents[1].text).toContain(attachment?.redirectUrl); }); }); From 2c7d5ac3d8d2635c99d216befbaca29dcf8db5fa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Jul 2022 11:09:32 -0700 Subject: [PATCH 11/30] chore(deps-dev): bump @types/jsonwebtoken from 8.5.5 to 8.5.8 (#3864) Bumps [@types/jsonwebtoken](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jsonwebtoken) from 8.5.5 to 8.5.8. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jsonwebtoken) --- updated-dependencies: - dependency-name: "@types/jsonwebtoken" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 13 ++++--------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index cc82632e54..6e0012e793 100644 --- a/package.json +++ b/package.json @@ -235,7 +235,7 @@ "@types/invariant": "^2.2.35", "@types/ioredis": "^4.28.1", "@types/jest": "^27.0.2", - "@types/jsonwebtoken": "^8.5.5", + "@types/jsonwebtoken": "^8.5.8", "@types/koa": "^2.13.4", "@types/koa-compress": "^4.0.3", "@types/koa-helmet": "^6.0.4", diff --git a/yarn.lock b/yarn.lock index cc120daf78..c01e8c3bb2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2663,10 +2663,10 @@ resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4= -"@types/jsonwebtoken@^8.5.5": - version "8.5.5" - resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-8.5.5.tgz#da5f2f4baee88f052ef3e4db4c1a0afb46cff22c" - integrity sha512-OGqtHQ7N5/Ap/TUwO6IgHDuLiAoTmHhGpNvgkCm/F4N6pKzx/RBSfr2OXZSwC6vkfnsEdb6+7DNZVtiXiwdwFw== +"@types/jsonwebtoken@^8.5.8": + version "8.5.8" + resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-8.5.8.tgz#01b39711eb844777b7af1d1f2b4cf22fda1c0c44" + integrity sha512-zm6xBQpFDIDM6o9r6HSgDeIcLy82TKWctCXEPbJJcXb5AKmi5BNNdLXneixK4lplX3PqIVcwLBCGE/kAGnlD4A== dependencies: "@types/node" "*" @@ -13257,11 +13257,6 @@ set-blocking@^2.0.0: resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= -set-immediate-shim@~1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz#4b2b1b27eb808a9f8dcc481a58e5e56f599f3f61" - integrity sha1-SysbJ+uAip+NzEgaWOXlb1mfP2E= - set-value@^2.0.0, set-value@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b" From c8caeebdbaa8d9c1a7684d1d24c4a143ebf0f387 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Jul 2022 11:09:47 -0700 Subject: [PATCH 12/30] chore(deps): bump react-window from 1.8.6 to 1.8.7 (#3865) Bumps [react-window](https://github.com/bvaughn/react-window) from 1.8.6 to 1.8.7. - [Release notes](https://github.com/bvaughn/react-window/releases) - [Changelog](https://github.com/bvaughn/react-window/blob/master/CHANGELOG.md) - [Commits](https://github.com/bvaughn/react-window/commits) --- updated-dependencies: - dependency-name: react-window dependency-type: direct:production update-type: version-update:semver-patch ... 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 6e0012e793..a8f4309917 100644 --- a/package.json +++ b/package.json @@ -179,7 +179,7 @@ "react-table": "^7.7.0", "react-virtualized-auto-sizer": "^1.0.5", "react-waypoint": "^10.1.0", - "react-window": "^1.8.6", + "react-window": "^1.8.7", "reakit": "^1.3.10", "reflect-metadata": "^0.1.13", "refractor": "^3.5.0", diff --git a/yarn.lock b/yarn.lock index c01e8c3bb2..d67e21aa19 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12450,10 +12450,10 @@ react-waypoint@^10.1.0: prop-types "^15.0.0" react-is "^17.0.1" -react-window@^1.8.6: - version "1.8.6" - resolved "https://registry.yarnpkg.com/react-window/-/react-window-1.8.6.tgz#d011950ac643a994118632665aad0c6382e2a112" - integrity sha512-8VwEEYyjz6DCnGBsd+MgkD0KJ2/OXFULyDtorIiTz+QzwoP94tBoA7CnbtyXMm+cCeAUER5KJcPtWl9cpKbOBg== +react-window@^1.8.7: + version "1.8.7" + resolved "https://registry.yarnpkg.com/react-window/-/react-window-1.8.7.tgz#5e9fd0d23f48f432d7022cdb327219353a15f0d4" + integrity sha512-JHEZbPXBpKMmoNO1bNhoXOOLg/ujhL/BU4IqVU9r8eQPcy5KQnGHIHDRkJ0ns9IM5+Aq5LNwt3j8t3tIrePQzA== dependencies: "@babel/runtime" "^7.0.0" memoize-one ">=3.1.1 <6" From 3d9a8be86791e7dc807fe48e23fbeeb2748476a7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Jul 2022 11:21:04 -0700 Subject: [PATCH 13/30] chore(deps-dev): bump typescript from 4.4.4 to 4.7.4 (#3866) * chore(deps-dev): bump typescript from 4.4.4 to 4.7.4 Bumps [typescript](https://github.com/Microsoft/TypeScript) from 4.4.4 to 4.7.4. - [Release notes](https://github.com/Microsoft/TypeScript/releases) - [Commits](https://github.com/Microsoft/TypeScript/compare/v4.4.4...v4.7.4) --- updated-dependencies: - dependency-name: typescript dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * tsc * tsc Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Tom Moor --- app/models/User.ts | 2 +- app/stores/UiStore.ts | 2 +- package.json | 2 +- shared/editor/lib/ExtensionManager.ts | 1 + yarn.lock | 8 ++++---- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/app/models/User.ts b/app/models/User.ts index d920aec554..c1753d722f 100644 --- a/app/models/User.ts +++ b/app/models/User.ts @@ -1,5 +1,5 @@ import { computed, observable } from "mobx"; -import { Role } from "@shared/types"; +import type { Role } from "@shared/types"; import ParanoidModel from "./ParanoidModel"; import Field from "./decorators/Field"; diff --git a/app/stores/UiStore.ts b/app/stores/UiStore.ts index 8186dd8034..1c7abc6769 100644 --- a/app/stores/UiStore.ts +++ b/app/stores/UiStore.ts @@ -1,7 +1,7 @@ import { action, autorun, computed, observable } from "mobx"; import { light as defaultTheme } from "@shared/styles/theme"; import Document from "~/models/Document"; -import { ConnectionStatus } from "~/scenes/Document/components/MultiplayerEditor"; +import type { ConnectionStatus } from "~/scenes/Document/components/MultiplayerEditor"; import Storage from "~/utils/Storage"; const UI_STORE = "UI_STORE"; diff --git a/package.json b/package.json index a8f4309917..e29f71f880 100644 --- a/package.json +++ b/package.json @@ -323,7 +323,7 @@ "react-refresh": "^0.9.0", "rimraf": "^2.5.4", "terser-webpack-plugin": "^4.1.0", - "typescript": "^4.4.4", + "typescript": "^4.7.4", "url-loader": "^0.6.2", "webpack": "4.44.1", "webpack-cli": "^3.3.12", diff --git a/shared/editor/lib/ExtensionManager.ts b/shared/editor/lib/ExtensionManager.ts index 1c1ef1e6e3..bf4bd2a5c9 100644 --- a/shared/editor/lib/ExtensionManager.ts +++ b/shared/editor/lib/ExtensionManager.ts @@ -26,6 +26,7 @@ export default class ExtensionManager { let extension; if (typeof ext === "function") { + // @ts-expect-error We won't instantiate an abstract class extension = new ext(editor?.props); } else { extension = ext; diff --git a/yarn.lock b/yarn.lock index d67e21aa19..2a059ae8bb 100644 --- a/yarn.lock +++ b/yarn.lock @@ -14578,10 +14578,10 @@ typedarray@^0.0.6: resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= -typescript@^4.2.4, typescript@^4.4.4: - version "4.4.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.4.tgz#2cd01a1a1f160704d3101fd5a58ff0f9fcb8030c" - integrity sha512-DqGhF5IKoBl8WNf8C1gu8q0xZSInh9j1kJJMqT3a94w1JzVaBU4EXOSMrz9yDqMT0xt3selp83fuFMQ0uzv6qA== +typescript@^4.2.4, typescript@^4.7.4: + version "4.7.4" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.7.4.tgz#1a88596d1cf47d59507a1bcdfb5b9dfe4d488235" + integrity sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ== uc.micro@^1.0.1, uc.micro@^1.0.5: version "1.0.6" From 9b837763e64d3788fb98f2ba3558abf72e449bd7 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 20 Jul 2022 21:19:57 +0100 Subject: [PATCH 14/30] 0.65.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e29f71f880..9676221eee 100644 --- a/package.json +++ b/package.json @@ -340,5 +340,5 @@ "js-yaml": "^3.14.1", "jpeg-js": "0.4.4" }, - "version": "0.65.1" + "version": "0.65.2" } From f370b0296b8b0a7fe3d86f3169effd0dbeb155c5 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 25 Jul 2022 21:10:37 +0100 Subject: [PATCH 15/30] fix: File operation cleanup task should also remove import data --- .../tasks/CleanupExpiredFileOperationsTask.test.ts | 8 ++++---- .../queues/tasks/CleanupExpiredFileOperationsTask.ts | 10 +++------- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/server/queues/tasks/CleanupExpiredFileOperationsTask.test.ts b/server/queues/tasks/CleanupExpiredFileOperationsTask.test.ts index 81de4dc916..77e9e1c92c 100644 --- a/server/queues/tasks/CleanupExpiredFileOperationsTask.test.ts +++ b/server/queues/tasks/CleanupExpiredFileOperationsTask.test.ts @@ -11,11 +11,11 @@ import CleanupExpiredFileOperationsTask from "./CleanupExpiredFileOperationsTask beforeEach(() => flushdb()); describe("CleanupExpiredFileOperationsTask", () => { - it("should expire exports older than 30 days ago", async () => { + it("should expire exports older than 15 days ago", async () => { await buildFileOperation({ type: FileOperationType.Export, state: FileOperationState.Complete, - createdAt: subDays(new Date(), 30), + createdAt: subDays(new Date(), 15), }); await buildFileOperation({ type: FileOperationType.Export, @@ -35,11 +35,11 @@ describe("CleanupExpiredFileOperationsTask", () => { expect(data).toEqual(1); }); - it("should not expire exports made less than 30 days ago", async () => { + it("should not expire exports made less than 15 days ago", async () => { await buildFileOperation({ type: FileOperationType.Export, state: FileOperationState.Complete, - createdAt: subDays(new Date(), 29), + createdAt: subDays(new Date(), 14), }); await buildFileOperation({ type: FileOperationType.Export, diff --git a/server/queues/tasks/CleanupExpiredFileOperationsTask.ts b/server/queues/tasks/CleanupExpiredFileOperationsTask.ts index 0710a7d83f..299e8d7de2 100644 --- a/server/queues/tasks/CleanupExpiredFileOperationsTask.ts +++ b/server/queues/tasks/CleanupExpiredFileOperationsTask.ts @@ -2,10 +2,7 @@ import { subDays } from "date-fns"; import { Op } from "sequelize"; import Logger from "@server/logging/Logger"; import { FileOperation } from "@server/models"; -import { - FileOperationState, - FileOperationType, -} from "@server/models/FileOperation"; +import { FileOperationState } from "@server/models/FileOperation"; import BaseTask, { TaskPriority } from "./BaseTask"; type Props = { @@ -14,12 +11,11 @@ type Props = { export default class CleanupExpiredFileOperationsTask extends BaseTask { public async perform({ limit }: Props) { - Logger.info("task", `Expiring export file operations older than 30 days…`); + Logger.info("task", `Expiring file operations older than 15 days…`); const fileOperations = await FileOperation.unscoped().findAll({ where: { - type: FileOperationType.Export, createdAt: { - [Op.lt]: subDays(new Date(), 30), + [Op.lt]: subDays(new Date(), 15), }, state: { [Op.ne]: FileOperationState.Expired, From 086c3ec2d83d6603f8834b0a2ef5229f9638bef4 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 25 Jul 2022 23:43:56 +0100 Subject: [PATCH 16/30] fix: Allow more flexible SMTP connection when SSL is not required. Do not fail on self-signed certs --- server/emails/mailer.tsx | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/server/emails/mailer.tsx b/server/emails/mailer.tsx index f366391a98..bd58d278b4 100644 --- a/server/emails/mailer.tsx +++ b/server/emails/mailer.tsx @@ -103,11 +103,15 @@ export class Mailer { pass: env.SMTP_PASSWORD, } : undefined, - tls: env.SMTP_TLS_CIPHERS - ? { - ciphers: env.SMTP_TLS_CIPHERS, - } - : undefined, + tls: env.SMTP_SECURE + ? env.SMTP_TLS_CIPHERS + ? { + ciphers: env.SMTP_TLS_CIPHERS, + } + : undefined + : { + rejectUnauthorized: false, + }, }; } From 8fdd5bf73401f92d11f4f1057e051c0d21ad67fe Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 26 Jul 2022 20:10:00 +0100 Subject: [PATCH 17/30] fix: substitution of content when sending an image to a profile (#3869) * fix: Limit public uploads to basic image types * test --- app/components/Editor.tsx | 8 ++-- app/editor/components/CommandMenu.tsx | 7 +++- .../Settings/components/ImageUpload.tsx | 3 +- server/routes/api/attachments.test.ts | 37 +++++++++++++++++++ server/routes/api/attachments.ts | 11 +++++- server/utils/__mocks__/s3.ts | 2 + shared/editor/nodes/Image.tsx | 9 ++--- shared/utils/files.ts | 18 --------- shared/validations.ts | 21 +++++++++++ 9 files changed, 82 insertions(+), 34 deletions(-) diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx index d5d831fa0f..cbf69a373d 100644 --- a/app/components/Editor.tsx +++ b/app/components/Editor.tsx @@ -8,12 +8,10 @@ import { Optional } from "utility-types"; import insertFiles from "@shared/editor/commands/insertFiles"; import embeds from "@shared/editor/embeds"; import { Heading } from "@shared/editor/lib/getHeadings"; -import { - getDataTransferFiles, - supportedImageMimeTypes, -} from "@shared/utils/files"; +import { getDataTransferFiles } from "@shared/utils/files"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; import { isInternalUrl } from "@shared/utils/urls"; +import { AttachmentValidation } from "@shared/validations"; import Document from "~/models/Document"; import ClickablePadding from "~/components/ClickablePadding"; import ErrorBoundary from "~/components/ErrorBoundary"; @@ -212,7 +210,7 @@ function Editor(props: Props, ref: React.RefObject | null) { // Insert all files as attachments if any of the files are not images. const isAttachment = files.some( - (file) => !supportedImageMimeTypes.includes(file.type) + (file) => !AttachmentValidation.imageContentTypes.includes(file.type) ); insertFiles(view, event, pos, files, { diff --git a/app/editor/components/CommandMenu.tsx b/app/editor/components/CommandMenu.tsx index f6554fc3da..4f828e9d94 100644 --- a/app/editor/components/CommandMenu.tsx +++ b/app/editor/components/CommandMenu.tsx @@ -11,7 +11,8 @@ import { CommandFactory } from "@shared/editor/lib/Extension"; import filterExcessSeparators from "@shared/editor/lib/filterExcessSeparators"; import { EmbedDescriptor, MenuItem } from "@shared/editor/types"; import { depths } from "@shared/styles"; -import { supportedImageMimeTypes, getEventFiles } from "@shared/utils/files"; +import { getEventFiles } from "@shared/utils/files"; +import { AttachmentValidation } from "@shared/validations"; import Scrollable from "~/components/Scrollable"; import { Dictionary } from "~/hooks/useDictionary"; import Input from "./Input"; @@ -181,7 +182,9 @@ class CommandMenu extends React.Component, State> { insertItem = (item: any) => { switch (item.name) { case "image": - return this.triggerFilePick(supportedImageMimeTypes.join(", ")); + return this.triggerFilePick( + AttachmentValidation.imageContentTypes.join(", ") + ); case "attachment": return this.triggerFilePick("*"); case "embed": diff --git a/app/scenes/Settings/components/ImageUpload.tsx b/app/scenes/Settings/components/ImageUpload.tsx index 2b33ef4bb1..696149b327 100644 --- a/app/scenes/Settings/components/ImageUpload.tsx +++ b/app/scenes/Settings/components/ImageUpload.tsx @@ -5,6 +5,7 @@ import * as React from "react"; import AvatarEditor from "react-avatar-editor"; import Dropzone from "react-dropzone"; import styled from "styled-components"; +import { AttachmentValidation } from "@shared/validations"; import RootStore from "~/stores/RootStore"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; @@ -134,7 +135,7 @@ class ImageUpload extends React.Component { return ( {({ getRootProps, getInputProps }) => ( diff --git a/server/routes/api/attachments.test.ts b/server/routes/api/attachments.test.ts index c201d1bfa8..f8ff03758e 100644 --- a/server/routes/api/attachments.test.ts +++ b/server/routes/api/attachments.test.ts @@ -13,9 +13,46 @@ import { flushdb } from "@server/test/support"; const app = webService(); const server = new TestServer(app.callback()); +jest.mock("@server/utils/s3"); + beforeEach(() => flushdb()); afterAll(() => server.close()); +describe("#attachments.create", () => { + it("should require authentication", async () => { + const res = await server.post("/api/attachments.create"); + expect(res.status).toEqual(401); + }); + + it("should allow simple image upload for public attachments", async () => { + const user = await buildUser(); + const res = await server.post("/api/attachments.create", { + body: { + name: "test.png", + contentType: "image/png", + size: 1000, + public: true, + token: user.getJwtToken(), + }, + }); + expect(res.status).toEqual(200); + }); + + it("should not allow file upload for public attachments", async () => { + const user = await buildUser(); + const res = await server.post("/api/attachments.create", { + body: { + name: "test.pdf", + contentType: "application/pdf", + size: 1000, + public: true, + token: user.getJwtToken(), + }, + }); + expect(res.status).toEqual(400); + }); +}); + describe("#attachments.delete", () => { it("should require authentication", async () => { const res = await server.post("/api/attachments.delete"); diff --git a/server/routes/api/attachments.ts b/server/routes/api/attachments.ts index fccfc6865a..76cccd1997 100644 --- a/server/routes/api/attachments.ts +++ b/server/routes/api/attachments.ts @@ -1,6 +1,7 @@ import Router from "koa-router"; import { v4 as uuidv4 } from "uuid"; import { bytesToHumanReadable } from "@shared/utils/files"; +import { AttachmentValidation } from "@shared/validations"; import { sequelize } from "@server/database/sequelize"; import { AuthorizationError, ValidationError } from "@server/errors"; import auth from "@server/middlewares/authentication"; @@ -11,12 +12,13 @@ import { publicS3Endpoint, getSignedUrl, } from "@server/utils/s3"; -import { assertPresent, assertUuid } from "@server/validation"; +import { assertIn, assertPresent, assertUuid } from "@server/validation"; const router = new Router(); const AWS_S3_ACL = process.env.AWS_S3_ACL || "private"; router.post("attachments.create", auth(), async (ctx) => { + const isPublic = ctx.body.public; const { name, documentId, @@ -25,9 +27,15 @@ router.post("attachments.create", auth(), async (ctx) => { } = ctx.body; assertPresent(name, "name is required"); assertPresent(size, "size is required"); + const { user } = ctx.state; authorize(user, "createAttachment", user.team); + // Public attachments are only used for avatars, so this is loosely coupled. + if (isPublic) { + assertIn(contentType, AttachmentValidation.avatarContentTypes); + } + if ( process.env.AWS_S3_UPLOAD_MAX_SIZE && size > process.env.AWS_S3_UPLOAD_MAX_SIZE @@ -39,7 +47,6 @@ router.post("attachments.create", auth(), async (ctx) => { ); } - const isPublic = ctx.body.public; const s3Key = uuidv4(); const acl = isPublic === undefined ? AWS_S3_ACL : isPublic ? "public-read" : "private"; diff --git a/server/utils/__mocks__/s3.ts b/server/utils/__mocks__/s3.ts index 7caa2cf698..407f94a803 100644 --- a/server/utils/__mocks__/s3.ts +++ b/server/utils/__mocks__/s3.ts @@ -5,3 +5,5 @@ export const publicS3Endpoint = jest.fn().mockReturnValue("http://mock"); export const getSignedUrl = jest.fn().mockReturnValue("http://s3mock"); export const getSignedUrlPromise = jest.fn().mockResolvedValue("http://s3mock"); + +export const getPresignedPost = jest.fn().mockReturnValue({}); diff --git a/shared/editor/nodes/Image.tsx b/shared/editor/nodes/Image.tsx index 3c17965b04..b1e3949ce0 100644 --- a/shared/editor/nodes/Image.tsx +++ b/shared/editor/nodes/Image.tsx @@ -11,11 +11,8 @@ import { import * as React from "react"; import ImageZoom from "react-medium-image-zoom"; import styled from "styled-components"; -import { - getDataTransferFiles, - supportedImageMimeTypes, - getEventFiles, -} from "../../utils/files"; +import { getDataTransferFiles, getEventFiles } from "../../utils/files"; +import { AttachmentValidation } from "../../validations"; import insertFiles, { Options } from "../commands/insertFiles"; import { MarkdownSerializerState } from "../lib/markdown/serializer"; import uploadPlaceholderPlugin from "../lib/uploadPlaceholder"; @@ -413,7 +410,7 @@ export default class Image extends Node { // create an input element and click to trigger picker const inputElement = document.createElement("input"); inputElement.type = "file"; - inputElement.accept = supportedImageMimeTypes.join(", "); + inputElement.accept = AttachmentValidation.imageContentTypes.join(", "); inputElement.onchange = (event) => { const files = getEventFiles(event); insertFiles(view, event, state.selection.from, files, { diff --git a/shared/utils/files.ts b/shared/utils/files.ts index cd483e0fc6..efcb544f60 100644 --- a/shared/utils/files.ts +++ b/shared/utils/files.ts @@ -83,21 +83,3 @@ export function getEventFiles( ? Array.prototype.slice.call(event.target.files) : []; } - -/** - * An array of image mimetypes commonly supported by modern browsers - */ -export const supportedImageMimeTypes = [ - "image/jpg", - "image/jpeg", - "image/pjpeg", - "image/png", - "image/apng", - "image/avif", - "image/gif", - "image/webp", - "image/svg", - "image/svg+xml", - "image/bmp", - "image/tiff", -]; diff --git a/shared/validations.ts b/shared/validations.ts index b1d2bf7b39..e525d524d2 100644 --- a/shared/validations.ts +++ b/shared/validations.ts @@ -1,3 +1,24 @@ +export const AttachmentValidation = { + /** The limited allowable mime-types for user and team avatars */ + avatarContentTypes: ["image/jpg", "image/jpeg", "image/png"], + + /** Image mime-types commonly supported by modern browsers */ + imageContentTypes: [ + "image/jpg", + "image/jpeg", + "image/pjpeg", + "image/png", + "image/apng", + "image/avif", + "image/gif", + "image/webp", + "image/svg", + "image/svg+xml", + "image/bmp", + "image/tiff", + ], +}; + export const CollectionValidation = { /** The maximum length of the collection description */ maxDescriptionLength: 1000, From b7b1f5e1fd51f096aeda08ead2c4046935f0990e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 26 Jul 2022 20:10:13 +0100 Subject: [PATCH 18/30] fix: Cleanup attachments uploaded to S3 when import fails (#3868) --- server/queues/tasks/ImportTask.ts | 297 +++++++++++++++--------------- 1 file changed, 153 insertions(+), 144 deletions(-) diff --git a/server/queues/tasks/ImportTask.ts b/server/queues/tasks/ImportTask.ts index 03323368a8..70ca6bf865 100644 --- a/server/queues/tasks/ImportTask.ts +++ b/server/queues/tasks/ImportTask.ts @@ -198,38 +198,126 @@ export default abstract class ImportTask extends BaseTask { const documents = new Map(); const attachments = new Map(); - return sequelize.transaction(async (transaction) => { - const user = await User.findByPk(fileOperation.userId, { - transaction, - rejectOnEmpty: true, - }); + try { + return await sequelize.transaction(async (transaction) => { + const user = await User.findByPk(fileOperation.userId, { + transaction, + rejectOnEmpty: true, + }); - const ip = user.lastActiveIp || undefined; + const ip = user.lastActiveIp || undefined; - // Attachments - await Promise.all( - data.attachments.map(async (item) => { - Logger.debug("task", `ImportTask persisting attachment ${item.id}`); - const attachment = await attachmentCreator({ - source: "import", - id: item.id, - name: item.name, - type: item.mimeType, - buffer: await item.buffer(), - user, - ip, + // Attachments + await Promise.all( + data.attachments.map(async (item) => { + Logger.debug("task", `ImportTask persisting attachment ${item.id}`); + const attachment = await attachmentCreator({ + source: "import", + id: item.id, + name: item.name, + type: item.mimeType, + buffer: await item.buffer(), + user, + ip, + transaction, + }); + attachments.set(item.id, attachment); + }) + ); + + // Collections + for (const item of data.collections) { + Logger.debug("task", `ImportTask persisting collection ${item.id}`); + let description = item.description; + + if (description) { + // Check all of the attachments we've created against urls in the text + // and replace them out with attachment redirect urls before saving. + for (const aitem of data.attachments) { + const attachment = attachments.get(aitem.id); + if (!attachment) { + continue; + } + description = description.replace( + new RegExp(`<<${attachment.id}>>`, "g"), + attachment.redirectUrl + ); + } + + // Check all of the document we've created against urls in the text + // and replace them out with a valid internal link. Because we are doing + // this before saving, we can't use the document slug, but we can take + // advantage of the fact that the document id will redirect in the client + for (const ditem of data.documents) { + description = description.replace( + new RegExp(`<<${ditem.id}>>`, "g"), + `/doc/${ditem.id}` + ); + } + } + + // check if collection with name exists + const response = await Collection.findOrCreate({ + where: { + teamId: fileOperation.teamId, + name: item.name, + }, + defaults: { + id: item.id, + description: truncate(description, { + length: CollectionValidation.maxDescriptionLength, + }), + createdById: fileOperation.userId, + permission: "read_write", + }, transaction, }); - attachments.set(item.id, attachment); - }) - ); - // Collections - for (const item of data.collections) { - Logger.debug("task", `ImportTask persisting collection ${item.id}`); - let description = item.description; + let collection = response[0]; + const isCreated = response[1]; + + // create new collection if name already exists, yes it's possible that + // there is also a "Name (Imported)" but this is a case not worth dealing + // with right now + if (!isCreated) { + const name = `${item.name} (Imported)`; + collection = await Collection.create( + { + id: item.id, + description, + teamId: fileOperation.teamId, + createdById: fileOperation.userId, + name, + permission: "read_write", + }, + { transaction } + ); + } + + await Event.create( + { + name: "collections.create", + collectionId: collection.id, + teamId: collection.teamId, + actorId: fileOperation.userId, + data: { + name: collection.name, + }, + ip, + }, + { + transaction, + } + ); + + collections.set(item.id, collection); + } + + // Documents + for (const item of data.documents) { + Logger.debug("task", `ImportTask persisting document ${item.id}`); + let text = item.text; - if (description) { // Check all of the attachments we've created against urls in the text // and replace them out with attachment redirect urls before saving. for (const aitem of data.attachments) { @@ -237,7 +325,7 @@ export default abstract class ImportTask extends BaseTask { if (!attachment) { continue; } - description = description.replace( + text = text.replace( new RegExp(`<<${attachment.id}>>`, "g"), attachment.redirectUrl ); @@ -248,135 +336,56 @@ export default abstract class ImportTask extends BaseTask { // this before saving, we can't use the document slug, but we can take // advantage of the fact that the document id will redirect in the client for (const ditem of data.documents) { - description = description.replace( + text = text.replace( new RegExp(`<<${ditem.id}>>`, "g"), `/doc/${ditem.id}` ); } - } - // check if collection with name exists - const response = await Collection.findOrCreate({ - where: { - teamId: fileOperation.teamId, - name: item.name, - }, - defaults: { + const document = await documentCreator({ + source: "import", id: item.id, - description: truncate(description, { - length: CollectionValidation.maxDescriptionLength, - }), - createdById: fileOperation.userId, - permission: "read_write", - }, - transaction, - }); - - let collection = response[0]; - const isCreated = response[1]; - - // create new collection if name already exists, yes it's possible that - // there is also a "Name (Imported)" but this is a case not worth dealing - // with right now - if (!isCreated) { - const name = `${item.name} (Imported)`; - collection = await Collection.create( - { - id: item.id, - description, - teamId: fileOperation.teamId, - createdById: fileOperation.userId, - name, - permission: "read_write", - }, - { transaction } - ); - } - - await Event.create( - { - name: "collections.create", - collectionId: collection.id, - teamId: collection.teamId, - actorId: fileOperation.userId, - data: { - name: collection.name, - }, + title: item.title, + text, + collectionId: item.collectionId, + createdAt: item.createdAt, + updatedAt: item.updatedAt ?? item.createdAt, + publishedAt: item.updatedAt ?? item.createdAt ?? new Date(), + parentDocumentId: item.parentDocumentId, + user, ip, - }, - { transaction, + }); + documents.set(item.id, document); + + const collection = collections.get(item.collectionId); + if (collection) { + await collection.addDocumentToStructure(document, 0, { + transaction, + }); } - ); - - collections.set(item.id, collection); - } - - // Documents - for (const item of data.documents) { - Logger.debug("task", `ImportTask persisting document ${item.id}`); - let text = item.text; - - // Check all of the attachments we've created against urls in the text - // and replace them out with attachment redirect urls before saving. - for (const aitem of data.attachments) { - const attachment = attachments.get(aitem.id); - if (!attachment) { - continue; - } - text = text.replace( - new RegExp(`<<${attachment.id}>>`, "g"), - attachment.redirectUrl - ); } - // Check all of the document we've created against urls in the text - // and replace them out with a valid internal link. Because we are doing - // this before saving, we can't use the document slug, but we can take - // advantage of the fact that the document id will redirect in the client - for (const ditem of data.documents) { - text = text.replace( - new RegExp(`<<${ditem.id}>>`, "g"), - `/doc/${ditem.id}` - ); - } + // Return value is only used for testing + return { + collections, + documents, + attachments, + }; + }); + } catch (err) { + Logger.info( + "task", + `Removing ${attachments.size} attachments on failure` + ); - const document = await documentCreator({ - source: "import", - id: item.id, - title: item.title, - text, - collectionId: item.collectionId, - createdAt: item.createdAt, - updatedAt: item.updatedAt ?? item.createdAt, - publishedAt: item.updatedAt ?? item.createdAt ?? new Date(), - parentDocumentId: item.parentDocumentId, - user, - ip, - transaction, - }); - documents.set(item.id, document); - - const collection = collections.get(item.collectionId); - if (collection) { - await collection.addDocumentToStructure(document, 0, { transaction }); - } - } - - // Return value is only used for testing - return { - collections, - documents, - attachments, - }; - }); - } - - /** - * Optional hook to remove any temporary files that were created - */ - protected async cleanupData() { - // noop + await Promise.all( + Array.from(attachments.values()).map((model) => + Attachment.deleteAttachmentFromS3(model) + ) + ); + throw err; + } } /** From 2794057738ee75093aecf6fae2774b66ee813380 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 26 Jul 2022 22:06:47 +0100 Subject: [PATCH 19/30] fix: Sequelize rejectOnEmpty should result in 404 status --- server/logging/sentry.ts | 1 + server/middlewares/errorHandling.ts | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/server/logging/sentry.ts b/server/logging/sentry.ts index 6a35d5bd50..ed07e259fc 100644 --- a/server/logging/sentry.ts +++ b/server/logging/sentry.ts @@ -14,6 +14,7 @@ if (env.SENTRY_DSN) { // Validation "BadRequestError", "SequelizeValidationError", + "SequelizeEmptyResultError", "ValidationError", // Authentication diff --git a/server/middlewares/errorHandling.ts b/server/middlewares/errorHandling.ts index 6ee30234ec..1b5faa3db8 100644 --- a/server/middlewares/errorHandling.ts +++ b/server/middlewares/errorHandling.ts @@ -1,6 +1,6 @@ import { Context, Next } from "koa"; import { snakeCase } from "lodash"; -import { ValidationError } from "sequelize"; +import { ValidationError, EmptyResultError } from "sequelize"; export default function errorHandling() { return async function errorHandlingMiddleware(ctx: Context, next: Next) { @@ -20,7 +20,8 @@ export default function errorHandling() { } } - if (message.match(/Not found/i)) { + if (err instanceof EmptyResultError || message.match(/Not found/i)) { + message = "Resource not found"; ctx.status = 404; error = "not_found"; } From ea28dc46ebf775f30c8df9c401157262d59f113b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 26 Jul 2022 22:33:48 +0100 Subject: [PATCH 20/30] fix: Error in WebhookProcessor when team is permanatly destroyed --- server/commands/starCreator.ts | 6 +++--- server/queues/processors/WebhookProcessor.ts | 4 ++++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/server/commands/starCreator.ts b/server/commands/starCreator.ts index 02a55bae97..cdf960b614 100644 --- a/server/commands/starCreator.ts +++ b/server/commands/starCreator.ts @@ -54,7 +54,7 @@ export default async function starCreator({ index = fractionalIndex(null, stars.length ? stars[0].index : null); } - const response = await Star.findOrCreate({ + const [star, isCreated] = await Star.findOrCreate({ where: documentId ? { userId: user.id, @@ -69,12 +69,12 @@ export default async function starCreator({ }, transaction, }); - const star = response[0]; - if (response[1]) { + if (isCreated) { await Event.create( { name: "stars.create", + teamId: user.teamId, modelId: star.id, userId: user.id, actorId: user.id, diff --git a/server/queues/processors/WebhookProcessor.ts b/server/queues/processors/WebhookProcessor.ts index cb9393b803..3f0f4f12e3 100644 --- a/server/queues/processors/WebhookProcessor.ts +++ b/server/queues/processors/WebhookProcessor.ts @@ -7,6 +7,10 @@ export default class WebhookProcessor extends BaseProcessor { static applicableEvents: ["*"] = ["*"]; async perform(event: Event) { + if (!event.teamId) { + return; + } + const webhookSubscriptions = await WebhookSubscription.findAll({ where: { enabled: true, From 383bac241e908c4e73eaa4fbc26d44392b5c9ce3 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 26 Jul 2022 23:18:26 +0100 Subject: [PATCH 21/30] fix: Suppress ForbiddenError in error tracker --- server/logging/sentry.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/server/logging/sentry.ts b/server/logging/sentry.ts index ed07e259fc..cf857b1d8c 100644 --- a/server/logging/sentry.ts +++ b/server/logging/sentry.ts @@ -16,6 +16,7 @@ if (env.SENTRY_DSN) { "SequelizeValidationError", "SequelizeEmptyResultError", "ValidationError", + "ForbiddenError", // Authentication "UnauthorizedError", From f9d9a82e473a0e5da52b7063763255147e18eb9c Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 29 Jul 2022 09:15:48 +0100 Subject: [PATCH 22/30] fix: Cannot hit enter after sentance starting with forward slash closes #3879 --- app/editor/components/CommandMenu.tsx | 4 ++-- app/editor/index.tsx | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/app/editor/components/CommandMenu.tsx b/app/editor/components/CommandMenu.tsx index 4f828e9d94..cf172db1e7 100644 --- a/app/editor/components/CommandMenu.tsx +++ b/app/editor/components/CommandMenu.tsx @@ -36,7 +36,7 @@ export type Props = { onFileUploadStop?: () => void; onShowToast: (message: string) => void; onLinkToolbarOpen?: () => void; - onClose: () => void; + onClose: (insertNewLine?: boolean) => void; onClearSearch: () => void; embeds?: EmbedDescriptor[]; renderMenuItem: ( @@ -123,7 +123,7 @@ class CommandMenu extends React.Component, State> { if (item) { this.insertItem(item); } else { - this.props.onClose(); + this.props.onClose(true); } } diff --git a/app/editor/index.tsx b/app/editor/index.tsx index a17c6d8e1e..0de98128f5 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -554,7 +554,14 @@ export class Editor extends React.PureComponent< this.setState({ blockMenuOpen: true, blockMenuSearch: search }); }; - private handleCloseBlockMenu = () => { + private handleCloseBlockMenu = (insertNewLine?: boolean) => { + if (insertNewLine) { + const transaction = this.view.state.tr.split( + this.view.state.selection.to + ); + this.view.dispatch(transaction); + this.view.focus(); + } if (!this.state.blockMenuOpen) { return; } From cb9773ad8501f38af5d5af6cc0956325944f4b4e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 31 Jul 2022 18:59:40 +0100 Subject: [PATCH 23/30] chore: Add emailed confirmation code to account deletion (#3873) * wip * tests --- app/scenes/UserDelete.tsx | 109 +++++++++++++----- app/stores/AuthStore.ts | 9 +- .../templates/ConfirmUserDeleteEmail.tsx | 57 +++++++++ .../templates/components/CopyableCode.tsx | 21 ++++ server/models/User.ts | 18 ++- server/routes/api/users.test.ts | 47 +++----- server/routes/api/users.ts | 43 +++++-- shared/i18n/locales/en_US/translation.json | 3 +- 8 files changed, 238 insertions(+), 69 deletions(-) create mode 100644 server/emails/templates/ConfirmUserDeleteEmail.tsx create mode 100644 server/emails/templates/components/CopyableCode.tsx diff --git a/app/scenes/UserDelete.tsx b/app/scenes/UserDelete.tsx index 48186b1022..116b27b7e0 100644 --- a/app/scenes/UserDelete.tsx +++ b/app/scenes/UserDelete.tsx @@ -1,65 +1,120 @@ import { observer } from "mobx-react"; import * as React from "react"; +import { useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; +import { ReactHookWrappedInput as Input } from "~/components/Input"; import Modal from "~/components/Modal"; import Text from "~/components/Text"; +import env from "~/env"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; +type FormData = { + code: string; +}; + type Props = { onRequestClose: () => void; }; function UserDelete({ onRequestClose }: Props) { - const [isDeleting, setIsDeleting] = React.useState(false); + const [isWaitingCode, setWaitingCode] = React.useState(false); const { auth } = useStores(); const { showToast } = useToasts(); const { t } = useTranslation(); + const { register, handleSubmit: formHandleSubmit, formState } = useForm< + FormData + >(); - const handleSubmit = React.useCallback( + const handleRequestDelete = React.useCallback( async (ev: React.SyntheticEvent) => { ev.preventDefault(); - setIsDeleting(true); try { - await auth.deleteUser(); - auth.logout(); + await auth.requestDelete(); + setWaitingCode(true); } catch (error) { showToast(error.message, { type: "error", }); - } finally { - setIsDeleting(false); } }, [auth, showToast] ); + const handleSubmit = React.useCallback( + async (data: FormData) => { + try { + await auth.deleteUser(data); + auth.logout(); + } catch (error) { + showToast(error.message, { + type: "error", + }); + } + }, + [auth, showToast] + ); + + const inputProps = register("code", { + required: true, + }); + return ( -
- - - Are you sure? Deleting your account will destroy identifying data - associated with your user and cannot be undone. You will be - immediately logged out of Outline and all your API tokens will be - revoked. - - - - , - }} - /> - - + + {isWaitingCode ? ( + <> + + + A confirmation code has been sent to your email address, + please enter the code below to permanantly destroy your + account. + + + + , + }} + /> + + + + ) : ( + <> + + + Are you sure? Deleting your account will destroy identifying + data associated with your user and cannot be undone. You will + be immediately logged out of Outline and all your API tokens + will be revoked. + + + + )} + {env.EMAIL_ENABLED && !isWaitingCode ? ( + + ) : ( + + )}
diff --git a/app/stores/AuthStore.ts b/app/stores/AuthStore.ts index 0c4322f248..55d908a0e6 100644 --- a/app/stores/AuthStore.ts +++ b/app/stores/AuthStore.ts @@ -199,8 +199,13 @@ export default class AuthStore { }; @action - deleteUser = async () => { - await client.post(`/users.delete`); + requestDelete = () => { + return client.post(`/users.requestDelete`); + }; + + @action + deleteUser = async (data: { code: string }) => { + await client.post(`/users.delete`, data); runInAction("AuthStore#updateUser", () => { this.user = null; this.team = null; diff --git a/server/emails/templates/ConfirmUserDeleteEmail.tsx b/server/emails/templates/ConfirmUserDeleteEmail.tsx new file mode 100644 index 0000000000..0364aadc78 --- /dev/null +++ b/server/emails/templates/ConfirmUserDeleteEmail.tsx @@ -0,0 +1,57 @@ +import * as React from "react"; +import BaseEmail from "./BaseEmail"; +import Body from "./components/Body"; +import CopyableCode from "./components/CopyableCode"; +import EmailTemplate from "./components/EmailLayout"; +import EmptySpace from "./components/EmptySpace"; +import Footer from "./components/Footer"; +import Header from "./components/Header"; +import Heading from "./components/Heading"; + +type Props = { + to: string; + deleteConfirmationCode: string; +}; + +/** + * Email sent to a user when they request to delete their account. + */ +export default class ConfirmUserDeleteEmail extends BaseEmail { + protected subject() { + return `Your account deletion request`; + } + + protected preview() { + return `Your requested account deletion code`; + } + + protected renderAsText({ deleteConfirmationCode }: Props): string { + return ` +You requested to permanantly delete your Outline account. Please enter the code below to confirm your account deletion. + +Code: ${deleteConfirmationCode} +`; + } + + protected render({ deleteConfirmationCode }: Props) { + return ( + +
+ + + Your account deletion request +

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

+ +

+ {deleteConfirmationCode} +

+ + +