From 994b7ad047bfc640ae63574bb1907883ad347bd1 Mon Sep 17 00:00:00 2001 From: Apoorv Mishra Date: Mon, 17 Jul 2023 20:26:32 +0530 Subject: [PATCH] feat(server): urls.unfurl endpoint --- server/routes/api/index.ts | 2 + server/routes/api/urls/index.ts | 1 + server/routes/api/urls/schema.ts | 36 ++++++ server/routes/api/urls/urls.test.ts | 140 +++++++++++++++++++++ server/routes/api/urls/urls.ts | 83 ++++++++++++ server/validation.ts | 29 +++++ shared/i18n/locales/en_US/translation.json | 5 + shared/utils/parseMentionUrl.ts | 12 ++ 8 files changed, 308 insertions(+) create mode 100644 server/routes/api/urls/index.ts create mode 100644 server/routes/api/urls/schema.ts create mode 100644 server/routes/api/urls/urls.test.ts create mode 100644 server/routes/api/urls/urls.ts create mode 100644 shared/utils/parseMentionUrl.ts diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index 604a9b9d55..0622bda509 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -32,6 +32,7 @@ import shares from "./shares"; import stars from "./stars"; import subscriptions from "./subscriptions"; import teams from "./teams"; +import urls from "./urls"; import users from "./users"; import views from "./views"; @@ -86,6 +87,7 @@ router.use("/", attachments.routes()); router.use("/", cron.routes()); router.use("/", groups.routes()); router.use("/", fileOperationsRoute.routes()); +router.use("/", urls.routes()); if (env.ENVIRONMENT === "development") { router.use("/", developer.routes()); diff --git a/server/routes/api/urls/index.ts b/server/routes/api/urls/index.ts new file mode 100644 index 0000000000..a9ef488c5a --- /dev/null +++ b/server/routes/api/urls/index.ts @@ -0,0 +1 @@ +export { default } from "./urls"; diff --git a/server/routes/api/urls/schema.ts b/server/routes/api/urls/schema.ts new file mode 100644 index 0000000000..ce7857c1bd --- /dev/null +++ b/server/routes/api/urls/schema.ts @@ -0,0 +1,36 @@ +import { isNil } from "lodash"; +import { z } from "zod"; +import { isUrl } from "@shared/utils/urls"; +import { ValidateURL } from "@server/validation"; +import BaseSchema from "../BaseSchema"; + +export const UrlsUnfurlSchema = BaseSchema.extend({ + body: z + .object({ + url: z + .string() + .url() + .refine( + (val) => { + try { + const url = new URL(val); + if (url.protocol === "mention:") { + return ValidateURL.isValidMentionUrl(val); + } + return isUrl(val); + } catch (err) { + return false; + } + }, + { message: ValidateURL.message } + ), + documentId: z.string().uuid().optional(), + }) + .refine( + (val) => + !(ValidateURL.isValidMentionUrl(val.url) && isNil(val.documentId)), + { message: "documentId required" } + ), +}); + +export type UrlsUnfurlReq = z.infer; diff --git a/server/routes/api/urls/urls.test.ts b/server/routes/api/urls/urls.test.ts new file mode 100644 index 0000000000..5abc44f774 --- /dev/null +++ b/server/routes/api/urls/urls.test.ts @@ -0,0 +1,140 @@ +import { User } from "@server/models"; +import { buildDocument, buildUser } from "@server/test/factories"; +import { getTestServer } from "@server/test/support"; + +const server = getTestServer(); + +describe("#urls.unfurl", () => { + let user: User; + beforeEach(async () => { + user = await buildUser(); + }); + + it("should fail with status 400 bad request when url is invalid", async () => { + const res = await server.post("/api/urls.unfurl", { + body: { + token: user.getJwtToken(), + url: "/doc/foo-bar", + }, + }); + + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("url: Invalid url"); + }); + + it("should fail with status 400 bad request when mention url is invalid", async () => { + const res = await server.post("/api/urls.unfurl", { + body: { + token: user.getJwtToken(), + url: "mention://1/foo/1", + }, + }); + + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("url: Must be a valid url"); + }); + + it("should fail with status 400 bad request when mention url is supplied without documentId", async () => { + const res = await server.post("/api/urls.unfurl", { + body: { + token: user.getJwtToken(), + url: "mention://2767ba0e-ac5c-4533-b9cf-4f5fc456600e/user/34095ac1-c808-45c0-8c6e-6c554497de64", + }, + }); + + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("body: documentId required"); + }); + + it("should fail with status 404 not found when mention user does not exist", async () => { + const res = await server.post("/api/urls.unfurl", { + body: { + token: user.getJwtToken(), + url: "mention://2767ba0e-ac5c-4533-b9cf-4f5fc456600e/user/34095ac1-c808-45c0-8c6e-6c554497de64", + documentId: "2767ba0e-ac5c-4533-b9cf-4f5fc456600e", + }, + }); + + const body = await res.json(); + expect(res.status).toEqual(404); + expect(body.message).toEqual("Mentioned user does not exist"); + }); + + it("should fail with status 404 not found when document does not exist", async () => { + const mentionedUser = await buildUser({ + teamId: user.teamId, + }); + + const res = await server.post("/api/urls.unfurl", { + body: { + token: user.getJwtToken(), + url: `mention://2767ba0e-ac5c-4533-b9cf-4f5fc456600e/user/${mentionedUser.id}`, + documentId: "2767ba0e-ac5c-4533-b9cf-4f5fc456600e", + }, + }); + + const body = await res.json(); + expect(res.status).toEqual(404); + expect(body.message).toEqual("Document does not exist"); + }); + + it("should fail with status 403 forbidden when user is not authorized to read mentioned user info", async () => { + const mentionedUser = await buildUser(); + const document = await buildDocument({ + teamId: user.teamId, + }); + + const res = await server.post("/api/urls.unfurl", { + body: { + token: user.getJwtToken(), + url: `mention://2767ba0e-ac5c-4533-b9cf-4f5fc456600e/user/${mentionedUser.id}`, + documentId: document.id, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(403); + expect(body.message).toEqual("Authorization error"); + }); + + it("should succeed with status 200 ok when valid mention url is supplied", async () => { + const mentionedUser = await buildUser({ teamId: user.teamId }); + const document = await buildDocument({ + teamId: user.teamId, + }); + + const res = await server.post("/api/urls.unfurl", { + body: { + token: user.getJwtToken(), + url: `mention://2767ba0e-ac5c-4533-b9cf-4f5fc456600e/user/${mentionedUser.id}`, + documentId: document.id, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.type).toEqual("mention"); + expect(body.title).toEqual(mentionedUser.name); + expect(body.meta.id).toEqual(mentionedUser.id); + }); + + it("should succeed with status 200 ok when valid document url is supplied", async () => { + const document = await buildDocument({ + teamId: user.teamId, + }); + + const res = await server.post("/api/urls.unfurl", { + body: { + token: user.getJwtToken(), + url: `http://localhost:3000/${document.url}`, + documentId: document.id, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.type).toEqual("document"); + expect(body.title).toEqual(document.titleWithDefault); + expect(body.meta.id).toEqual(document.id); + }); +}); diff --git a/server/routes/api/urls/urls.ts b/server/routes/api/urls/urls.ts new file mode 100644 index 0000000000..b6877ac4de --- /dev/null +++ b/server/routes/api/urls/urls.ts @@ -0,0 +1,83 @@ +import Router from "koa-router"; +import { head, orderBy } from "lodash"; +import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; +import parseMentionUrl from "@shared/utils/parseMentionUrl"; +import { NotFoundError } from "@server/errors"; +import auth from "@server/middlewares/authentication"; +import { transaction } from "@server/middlewares/transaction"; +import validate from "@server/middlewares/validate"; +import { Document, User } from "@server/models"; +import { authorize } from "@server/policies"; +import { APIContext } from "@server/types"; +import * as T from "./schema"; + +const router = new Router(); + +router.post( + "urls.unfurl", + auth(), + validate(T.UrlsUnfurlSchema), + transaction(), + async (ctx: APIContext) => { + const { url, documentId } = ctx.input.body; + const { user } = ctx.state.auth; + const { transaction } = ctx.state; + const urlObj = new URL(url); + if (urlObj.protocol === "mention:") { + const { modelId: userId } = parseMentionUrl(url); + + const [mentionedUser, document] = await Promise.all([ + User.findByPk(userId, { transaction }), + Document.findByPk(documentId!, { + userId, + transaction, + }), + ]); + if (!mentionedUser) { + throw NotFoundError("Mentioned user does not exist"); + } + if (!document) { + throw NotFoundError("Document does not exist"); + } + authorize(user, "read", mentionedUser); + authorize(user, "read", document); + + const lastView = head(orderBy(document.views, ["updatedAt"], ["desc"])); + + ctx.body = { + url, + type: "mention", + title: mentionedUser.name, + meta: { + id: mentionedUser.id, + lastActiveAt: mentionedUser.lastActiveAt, + lastViewedAt: lastView ? lastView.updatedAt : undefined, + }, + }; + + return; + } + + const docId = parseDocumentSlug(url); + const document = await Document.findByPk(docId!, { transaction }); + if (!document) { + throw NotFoundError("Document does not exist"); + } + authorize(user, "read", document); + + ctx.body = { + url, + type: "document", + title: document.titleWithDefault, + meta: { + id: document.id, + updatedAt: document.updatedAt, + createdAt: document.createdAt, + updatedBy: document.updatedBy, + createdBy: document.createdBy, + }, + }; + } +); + +export default router; diff --git a/server/validation.ts b/server/validation.ts index a8e9dd0ead..0c13387e9a 100644 --- a/server/validation.ts +++ b/server/validation.ts @@ -3,6 +3,7 @@ import { Primitive } from "utility-types"; import validator from "validator"; import isUUID from "validator/lib/isUUID"; import { SLUG_URL_REGEX } from "@shared/utils/urlHelpers"; +import { isUrl } from "@shared/utils/urls"; import { CollectionPermission } from "../shared/types"; import { validateColorHex } from "../shared/utils/color"; import { validateIndexCharacters } from "../shared/utils/indexCharacters"; @@ -186,3 +187,31 @@ export class ValidateIndex { public static regex = new RegExp("^[\x20-\x7E]+$"); public static message = "Must be between x20 to x7E ASCII"; } + +export class ValidateURL { + public static isValidMentionUrl = (url: string) => { + if (!isUrl(url)) { + return false; + } + try { + const urlObj = new URL(url); + if (urlObj.protocol !== "mention:") { + return false; + } + + const matches = url.match( + /^mention:\/\/([a-z0-9-]+)\/([a-z]+)\/([a-z0-9-]+)$/ + ); + if (!matches) { + return false; + } + + const [id, mentionType, modelId] = matches.slice(1); + return isUUID(id) && mentionType === "user" && isUUID(modelId); + } catch (err) { + return false; + } + }; + + public static message = "Must be a valid url"; +} diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index fc8ef837a9..7e8d5fa4c5 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -189,6 +189,11 @@ "{{ count }} member": "{{ count }} member", "{{ count }} member_plural": "{{ count }} members", "Group members": "Group members", + "Online now": "Online now", + "Last viewed": "Last viewed", + "Online": "Online", + "{{ username }} created": "{{ username }} created", + "{{ username }} updated": "{{ username }} updated", "Icon": "Icon", "Show menu": "Show menu", "Choose icon": "Choose icon", diff --git a/shared/utils/parseMentionUrl.ts b/shared/utils/parseMentionUrl.ts new file mode 100644 index 0000000000..f4ab806074 --- /dev/null +++ b/shared/utils/parseMentionUrl.ts @@ -0,0 +1,12 @@ +const parseMentionUrl = (url: string) => { + const matches = url.match( + /^mention:\/\/([a-z0-9-]+)\/([a-z]+)\/([a-z0-9-]+)$/ + ); + if (!matches) { + return {}; + } + const [id, mentionType, modelId] = matches.slice(1); + return { id, mentionType, modelId }; +}; + +export default parseMentionUrl;