diff --git a/server/middlewares/appHeaders.ts b/server/middlewares/appHeaders.ts new file mode 100644 index 0000000000..4095359882 --- /dev/null +++ b/server/middlewares/appHeaders.ts @@ -0,0 +1,31 @@ +import type { Context, Next } from "koa"; +import env from "@server/env"; + +/** + * Middleware that sets the response headers that are needed when serving the + * web application. + * + * @returns the middleware function. + */ +export default function appHeaders() { + // Sentry needs this header to report all performance metrics, see: + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin + const timingOrigins = [env.URL]; + + if (env.SENTRY_DSN) { + timingOrigins.push("https://sentry.io"); + } + + const timingAllowOrigin = timingOrigins.join(", "); + + return async function appHeadersMiddleware(ctx: Context, next: Next) { + ctx.set("Timing-Allow-Origin", timingAllowOrigin); + + // Allow the JS Self-Profiling API to be used for local performance work. + if (env.isDevelopment) { + ctx.set("Document-Policy", "js-profiling"); + } + + await next(); + }; +} diff --git a/server/routes/app.ts b/server/routes/app.ts index 8e6324a384..f07e251ae5 100644 --- a/server/routes/app.ts +++ b/server/routes/app.ts @@ -1,6 +1,7 @@ import fs from "node:fs"; import path from "node:path"; import util from "node:util"; +import Router from "@koa/router"; import type { Context, Next } from "koa"; import { escape } from "es-toolkit/compat"; import { isbot } from "isbot"; @@ -26,7 +27,28 @@ import { getTeamFromContext } from "@server/utils/passport"; import prefetchTags from "@server/utils/prefetchTags"; import readManifestFile from "@server/utils/readManifestFile"; import { RedisPrefixHelper } from "@server/utils/RedisPrefixHelper"; +import { isInvalidAppPath } from "@server/utils/url"; import { loadPublicShare } from "@server/commands/shareLoader"; +import { + getWorkspaceRedirectUrl, + getWorkspaceRenderOptions, +} from "./workspace"; + +/** Options used to render the app shell. */ +export interface AppRenderOptions { + title?: string; + description?: string; + content?: string; + canonical?: string; + shortcutIcon?: string; + image?: string; + siteName?: string; + rootShareId?: string; + isShare?: boolean; + markdownUrl?: string; + analytics?: Integration[]; + allowIndexing?: boolean; +} const readFile = util.promisify(fs.readFile); const entry = "app/index.tsx"; @@ -139,20 +161,7 @@ const readIndexFile = async (): Promise => { export const renderApp = async ( ctx: Context, next: Next, - options: { - title?: string; - description?: string; - content?: string; - canonical?: string; - shortcutIcon?: string; - image?: string; - siteName?: string; - rootShareId?: string; - isShare?: boolean; - markdownUrl?: string; - analytics?: Integration[]; - allowIndexing?: boolean; - } = {} + options: AppRenderOptions = {} ) => { const { title = env.APP_NAME, @@ -444,3 +453,23 @@ export const renderShare = async (ctx: Context, next: Next) => { markdownUrl: document || collection ? markdownUrl : undefined, }); }; + +const router = new Router(); + +router.get("{/*path}", async (ctx, next) => { + if (isInvalidAppPath(ctx.path)) { + ctx.status = 404; + return; + } + + const team = await getTeamFromContext(ctx); + const redirectUrl = await getWorkspaceRedirectUrl(ctx, team); + if (redirectUrl) { + ctx.redirect(redirectUrl); + return; + } + + return renderApp(ctx, next, await getWorkspaceRenderOptions(team)); +}); + +export default router; diff --git a/server/routes/assets.ts b/server/routes/assets.ts new file mode 100644 index 0000000000..26b2d8427d --- /dev/null +++ b/server/routes/assets.ts @@ -0,0 +1,103 @@ +import crypto from "node:crypto"; +import path from "node:path"; +import { formatRFC7231 } from "date-fns"; +import Router from "@koa/router"; +import { send } from "@koa/send"; +import { languages } from "@shared/i18n"; +import { Day } from "@shared/utils/time"; +import env from "@server/env"; +import { NotFoundError } from "@server/errors"; + +const router = new Router(); + +router.get( + ["/images/{*path}", "/email/{*path}", "/fonts/{*path}"], + async (ctx, next) => { + let sent; + + try { + sent = await send(ctx, ctx.path, { + root: path.resolve(__dirname, "../../../public"), + // 7 day expiry, these assets are mostly static but do not contain a hash + maxAge: Day.ms * 7, + setHeaders: (res) => { + res.setHeader("Access-Control-Allow-Origin", "*"); + }, + }); + } catch (err) { + if (!isNotFound(err)) { + throw err; + } + } + + if (!sent) { + await next(); + } + } +); + +if (env.isProduction) { + router.get("/static/{*path}", async (ctx) => { + try { + const pathname = ctx.path.substring(8); + if (!pathname) { + throw NotFoundError(); + } + + await send(ctx, pathname, { + root: path.join(__dirname, "../../app/"), + // Hashed static assets get 1 year expiry plus immutable flag + maxAge: Day.ms * 365, + immutable: true, + setHeaders: (res, filePath) => { + res.setHeader("Service-Worker-Allowed", "/"); + res.setHeader("Access-Control-Allow-Origin", "*"); + + // The service worker is not hashed and must always be revalidated + // so that browsers detect and install new versions. + if (path.basename(filePath) === "sw.js") { + res.setHeader("Cache-Control", "no-cache"); + } + }, + }); + } catch (err) { + // Serve a bad request instead of not found if the file doesn't exist, + // this prevents CDNs from caching the response and allows them to + // continue serving old file versions. + if (isNotFound(err)) { + ctx.status = 400; + return; + } + + throw err; + } + }); +} + +router.get("/locales/:lng.json", async (ctx) => { + const { lng } = ctx.params; + + if (!languages.includes(lng as (typeof languages)[number])) { + ctx.status = 404; + return; + } + + await send(ctx, path.join(lng, "translation.json"), { + setHeaders: (res, _, stats) => { + res.setHeader("Last-Modified", formatRFC7231(stats.mtime)); + res.setHeader("Cache-Control", `public, max-age=${7 * Day.seconds}`); + res.setHeader( + "ETag", + crypto.createHash("md5").update(stats.mtime.toISOString()).digest("hex") + ); + res.setHeader("Access-Control-Allow-Origin", "*"); + }, + root: path.join(__dirname, "../../shared/i18n/locales"), + }); +}); + +function isNotFound(err: unknown): boolean { + return err instanceof Error && "status" in err && err.status === 404; +} + +export default router; diff --git a/server/routes/embeds.ts b/server/routes/embeds.ts index 92943ead7f..598299a838 100644 --- a/server/routes/embeds.ts +++ b/server/routes/embeds.ts @@ -1,3 +1,4 @@ +import Router from "@koa/router"; import escape from "escape-html"; import type { Context, Next } from "koa"; import env from "@server/env"; @@ -224,3 +225,12 @@ ${resizeObserverScript(ctx)} return next(); }; + +const router = new Router(); + +router.get( + ["/embeds/gitlab", "/embeds/github", "/embeds/dropbox", "/embeds/pinterest"], + renderEmbed +); + +export default router; diff --git a/server/routes/index.ts b/server/routes/index.ts index d5cd833862..64dfcb836a 100644 --- a/server/routes/index.ts +++ b/server/routes/index.ts @@ -1,275 +1,29 @@ -import crypto from "node:crypto"; -import path from "node:path"; -import { formatRFC7231 } from "date-fns"; import Koa from "koa"; -import Router from "@koa/router"; -import { send } from "@koa/send"; -import { languages } from "@shared/i18n"; -import { TeamPreference } from "@shared/types"; -import { parseDomain } from "@shared/utils/domains"; -import { Day } from "@shared/utils/time"; import env from "@server/env"; -import { NotFoundError } from "@server/errors"; -import shareDomains from "@server/middlewares/shareDomains"; -import { Integration } from "@server/models"; -import { getSessionRedirectUrl } from "@server/utils/authentication"; -import { SessionsCookieHelper } from "@server/utils/SessionsCookieHelper"; -import { getTeamFromContext } from "@server/utils/passport"; -import { isInvalidAppPath } from "@server/utils/url"; -import apexRedirect from "../middlewares/apexRedirect"; -import { renderApp, renderShare } from "./app"; +import apexRedirect from "@server/middlewares/apexRedirect"; +import appHeaders from "@server/middlewares/appHeaders"; +import app from "./app"; +import assets from "./assets"; import discovery from "./discovery"; -import { renderEmbed } from "./embeds"; +import embeds from "./embeds"; import errors from "./errors"; +import shares from "./shares"; const koa = new Koa(); -const router = new Router(); - -// serve public assets -router.use( - ["/images/{*path}", "/email/{*path}", "/fonts/{*path}"], - async (ctx, next) => { - let done; - - if (ctx.method === "HEAD" || ctx.method === "GET") { - try { - done = await send(ctx, ctx.path, { - root: path.resolve(__dirname, "../../../public"), - // 7 day expiry, these assets are mostly static but do not contain a hash - maxAge: Day.ms * 7, - setHeaders: (res) => { - res.setHeader("Access-Control-Allow-Origin", "*"); - }, - }); - } catch (err) { - if (!(err instanceof Error && "status" in err && err.status === 404)) { - throw err; - } - } - } - - if (!done) { - await next(); - } - } -); - -router.use( - [ - "/share/:shareId", - "/share/:shareId/doc/:documentSlug", - "/share/:shareId/{*path}", - ], - (ctx) => { - const redirectPath = ctx.path.replace(/^\/share/, "/s"); - ctx.redirect(redirectPath + ctx.request.URL.search); - ctx.status = 301; - } -); - -if (env.isProduction) { - router.get("/static/{*path}", async (ctx) => { - try { - const pathname = ctx.path.substring(8); - if (!pathname) { - throw NotFoundError(); - } - - await send(ctx, pathname, { - root: path.join(__dirname, "../../app/"), - // Hashed static assets get 1 year expiry plus immutable flag - maxAge: Day.ms * 365, - immutable: true, - setHeaders: (res, filePath) => { - res.setHeader("Service-Worker-Allowed", "/"); - res.setHeader("Access-Control-Allow-Origin", "*"); - - // The service worker is not hashed and must always be revalidated - // so that browsers detect and install new versions. - if (path.basename(filePath) === "sw.js") { - res.setHeader("Cache-Control", "no-cache"); - } - }, - }); - } catch (err) { - if (err instanceof Error && "status" in err && err.status === 404) { - // Serve a bad request instead of not found if the file doesn't exist - // This prevents CDN's from caching the response, allowing them to continue - // serving old file versions - ctx.status = 400; - return; - } - - throw err; - } - }); -} - -router.get("/locales/:lng.json", async (ctx) => { - const { lng } = ctx.params; - - if (!languages.includes(lng as (typeof languages)[number])) { - ctx.status = 404; - return; - } - - await send(ctx, path.join(lng, "translation.json"), { - setHeaders: (res, _, stats) => { - res.setHeader("Last-Modified", formatRFC7231(stats.mtime)); - res.setHeader("Cache-Control", `public, max-age=${7 * Day.seconds}`); - res.setHeader( - "ETag", - crypto.createHash("md5").update(stats.mtime.toISOString()).digest("hex") - ); - res.setHeader("Access-Control-Allow-Origin", "*"); - }, - root: path.join(__dirname, "../../shared/i18n/locales"), - }); -}); - -router.use(discovery.routes()); - -router.get("/s/:shareId.:format", shareDomains(), renderShare); -router.get("/s/:shareId", shareDomains(), renderShare); -router.get( - "/s/:shareId/doc/:documentSlug.:format", - shareDomains(), - renderShare -); -router.get("/s/:shareId/doc/:documentSlug", shareDomains(), renderShare); -router.get("/s/:shareId/{*path}", shareDomains(), renderShare); - -router.get("/embeds/gitlab", renderEmbed); -router.get("/embeds/github", renderEmbed); -router.get("/embeds/dropbox", renderEmbed); -router.get("/embeds/pinterest", renderEmbed); - -router.use(shareDomains()); - -router.get("/doc/:documentSlug", async (ctx, next) => { - if (ctx.state?.rootShare) { - return renderShare(ctx, next); - } - return next(); -}); - -router.get("/sitemap.xml", async (ctx) => { - if (ctx.state?.rootShare) { - ctx.redirect(`/api/shares.sitemap?id=${ctx.state?.rootShare.id}`); - } else { - ctx.status = 404; - } -}); - -// Client routes that render without an authenticated session. -const publicAppPaths = [ - "/", - "/create", - "/logout", - "/desktop-redirect", - "/oauth/authorize", -]; - -function isPublicAppPath(path: string) { - return publicAppPaths.includes(path.replace(/\/+$/, "") || "/"); -} - -// catch all for application -router.get("{/*path}", async (ctx, next) => { - if (isInvalidAppPath(ctx.path)) { - ctx.status = 404; - return; - } - - if (ctx.state?.rootShare) { - // Only allow root path for root share domains, return 404 for other paths. - // Valid paths like /doc/:documentSlug and /sitemap.xml are handled above. - if (ctx.path !== "/") { - ctx.status = 404; - return; - } - return renderShare(ctx, next); - } - - const team = await getTeamFromContext(ctx); - - if (env.isCloudHosted) { - // Redirect to main domain if no team is found - if (!team || team.isSuspended) { - if (env.isProduction && ctx.hostname !== parseDomain(env.URL).host) { - ctx.redirect(env.URL); - return; - } - - if (!team) { - const teams = await SessionsCookieHelper.reconcile(ctx); - - // Links to app paths on the root domain, such as those in emails, are - // sent on to the workspace the browser is signed in to. - if (!isPublicAppPath(ctx.path)) { - const url = getSessionRedirectUrl(ctx, teams); - if (url) { - ctx.redirect(url); - return; - } - } - } - } - - // Redirect to the team's canonical url, taking into account custom domains - // and hosted subdomains, if the request arrived on a different host. - else if (team && !team.isTeamUrl(ctx.href)) { - const url = new URL(team.url); - url.pathname = ctx.path; - url.search = ctx.search; - ctx.redirect(url.toString()); - return; - } - } - - const analytics = await Integration.findAnalyticsIntegrationsForTeam( - team?.id - ); - - const publicBranding = - team?.getPreference(TeamPreference.PublicBranding) ?? false; - - return renderApp(ctx, next, { - title: publicBranding && team?.name ? team.name : undefined, - description: - publicBranding && team?.description ? team.description : undefined, - analytics, - shortcutIcon: - publicBranding && team?.avatarUrl - ? ((await team.publicAvatarUrl()) ?? undefined) - : undefined, - }); -}); - -// In order to report all possible performance metrics to Sentry this header -// must be provided when serving the application, see: -// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin -const timingOrigins = [env.URL]; - -if (env.SENTRY_DSN) { - timingOrigins.push("https://sentry.io"); -} - -koa.use(async (ctx, next) => { - ctx.set("Timing-Allow-Origin", timingOrigins.join(", ")); - - // Allow the JS Self-Profiling API to be used for local performance work. - if (env.isDevelopment) { - ctx.set("Document-Policy", "js-profiling"); - } - await next(); -}); +koa.use(appHeaders()); koa.use(apexRedirect()); + if (env.ENVIRONMENT === "test") { koa.use(errors.routes()); } -koa.use(router.routes()); +koa.use(assets.routes()); +koa.use(discovery.routes()); +koa.use(embeds.routes()); +koa.use(shares.routes()); + +// The app router has a catch-all route, so it must be last. +koa.use(app.routes()); export default koa; diff --git a/server/routes/shares.ts b/server/routes/shares.ts new file mode 100644 index 0000000000..573bf394a8 --- /dev/null +++ b/server/routes/shares.ts @@ -0,0 +1,61 @@ +import Router from "@koa/router"; +import shareDomains from "@server/middlewares/shareDomains"; +import { renderShare } from "./app"; + +const router = new Router(); + +// Legacy share urls. +router.get( + [ + "/share/:shareId", + "/share/:shareId/doc/:documentSlug", + "/share/:shareId/{*path}", + ], + (ctx) => { + const redirectPath = ctx.path.replace(/^\/share/, "/s"); + ctx.redirect(redirectPath + ctx.request.URL.search); + ctx.status = 301; + } +); + +router.use(shareDomains()); + +router.get( + [ + "/s/:shareId.:format", + "/s/:shareId", + "/s/:shareId/doc/:documentSlug.:format", + "/s/:shareId/doc/:documentSlug", + "/s/:shareId/{*path}", + ], + renderShare +); + +// Routes below are only served for a share on its own custom domain. +router.get("/doc/:documentSlug", (ctx, next) => { + if (ctx.state.rootShare) { + return renderShare(ctx, next); + } + return next(); +}); + +router.get("/sitemap.xml", (ctx) => { + if (ctx.state.rootShare) { + ctx.redirect(`/api/shares.sitemap?id=${ctx.state.rootShare.id}`); + } else { + ctx.status = 404; + } +}); + +router.get("{/*path}", (ctx, next) => { + if (!ctx.state.rootShare) { + return next(); + } + if (ctx.path !== "/") { + ctx.status = 404; + return; + } + return renderShare(ctx, next); +}); + +export default router; diff --git a/server/routes/workspace.test.ts b/server/routes/workspace.test.ts new file mode 100644 index 0000000000..0191afcfb7 --- /dev/null +++ b/server/routes/workspace.test.ts @@ -0,0 +1,99 @@ +import { randomUUID } from "node:crypto"; +import { IncomingMessage, ServerResponse } from "node:http"; +import { Socket } from "node:net"; +import Koa from "koa"; +import { TeamPreference } from "@shared/types"; +import { buildTeam } from "@server/test/factories"; +import { setSelfHosted } from "@server/test/support"; +import { + getWorkspaceRedirectUrl, + getWorkspaceRenderOptions, +} from "./workspace"; + +function buildContext(url: string) { + const { host, pathname, search } = new URL(url); + const req = new IncomingMessage(new Socket()); + req.method = "GET"; + req.url = pathname + search; + req.headers = { host }; + return new Koa().createContext(req, new ServerResponse(req)); +} + +describe("getWorkspaceRedirectUrl", () => { + it("should return undefined on the canonical host", async () => { + const subdomain = `canonical-${randomUUID()}`; + const team = await buildTeam({ subdomain }); + const ctx = buildContext(`https://${subdomain}.outline.dev/search`); + + expect(await getWorkspaceRedirectUrl(ctx, team)).toBeUndefined(); + }); + + it("should return the canonical url with the path and query", async () => { + const id = randomUUID(); + const team = await buildTeam({ + subdomain: `current-${id}`, + previousSubdomains: [`previous-${id}`], + }); + const ctx = buildContext( + `https://previous-${id}.outline.dev/search?query=hello` + ); + + expect(await getWorkspaceRedirectUrl(ctx, team)).toEqual( + `https://current-${id}.outline.dev/search?query=hello` + ); + }); + + it("should not redirect a suspended workspace to its canonical url", async () => { + const id = randomUUID(); + const team = await buildTeam({ + subdomain: `current-${id}`, + previousSubdomains: [`previous-${id}`], + suspendedAt: new Date(), + }); + const ctx = buildContext(`https://previous-${id}.outline.dev/search`); + + expect(await getWorkspaceRedirectUrl(ctx, team)).toBeUndefined(); + }); + + it("should return undefined without a workspace or sessions", async () => { + const ctx = buildContext("https://app.outline.dev/settings"); + + expect(await getWorkspaceRedirectUrl(ctx, undefined)).toBeUndefined(); + }); + + it("should return undefined when self hosted", async () => { + setSelfHosted(); + const team = await buildTeam({ subdomain: `self-${randomUUID()}` }); + const ctx = buildContext("https://other.example.com/search"); + + expect(await getWorkspaceRedirectUrl(ctx, team)).toBeUndefined(); + }); +}); + +describe("getWorkspaceRenderOptions", () => { + it("should return only analytics without public branding", async () => { + const team = await buildTeam({ description: "A description" }); + + expect(await getWorkspaceRenderOptions(team)).toEqual({ analytics: [] }); + }); + + it("should return only analytics without a workspace", async () => { + expect(await getWorkspaceRenderOptions(undefined)).toEqual({ + analytics: [], + }); + }); + + it("should return the workspace name and description with public branding", async () => { + const team = await buildTeam({ + description: "A description", + preferences: { [TeamPreference.PublicBranding]: true }, + }); + + expect(await getWorkspaceRenderOptions(team)).toEqual({ + analytics: [], + title: team.name, + description: "A description", + shortcutIcon: undefined, + }); + }); +}); diff --git a/server/routes/workspace.ts b/server/routes/workspace.ts new file mode 100644 index 0000000000..6e3f44ed7a --- /dev/null +++ b/server/routes/workspace.ts @@ -0,0 +1,95 @@ +import type { Context } from "koa"; +import { TeamPreference } from "@shared/types"; +import { parseDomain } from "@shared/utils/domains"; +import env from "@server/env"; +import { Integration, type Team } from "@server/models"; +import { getSessionRedirectUrl } from "@server/utils/authentication"; +import { SessionsCookieHelper } from "@server/utils/SessionsCookieHelper"; +import type { AppRenderOptions } from "./app"; + +/** + * Returns the URL to redirect an app request to when the request did not + * arrive on the canonical host of a usable workspace. When no workspace is + * found, the sessions cookie is reconciled. + * + * @param ctx the request context. + * @param team the workspace for the request host, if any. + * @returns the URL to redirect to, or undefined to render the app. + */ +export async function getWorkspaceRedirectUrl( + ctx: Context, + team: Team | null | undefined +): Promise { + if (!env.isCloudHosted) { + return; + } + + if (team && !team.isSuspended) { + if (team.isTeamUrl(ctx.href)) { + return; + } + + const url = new URL(team.url); + url.pathname = ctx.path; + url.search = ctx.search; + return url.toString(); + } + + if (env.isProduction && ctx.hostname !== parseDomain(env.URL).host) { + return env.URL; + } + + if (team) { + return; + } + + const teams = await SessionsCookieHelper.reconcile(ctx); + + // Links to app paths on the root domain, such as those in emails, are sent + // on to the workspace the browser is signed in to. + if (isPublicAppPath(ctx.path)) { + return; + } + + return getSessionRedirectUrl(ctx, teams); +} + +/** + * Returns the options used to render the app shell for a workspace. + * + * @param team the workspace for the request host, if any. + * @returns the render options. + */ +export async function getWorkspaceRenderOptions( + team: Team | null | undefined +): Promise { + const analytics = await Integration.findAnalyticsIntegrationsForTeam( + team?.id + ); + + if (!team?.getPreference(TeamPreference.PublicBranding)) { + return { analytics }; + } + + return { + analytics, + title: team.name || undefined, + description: team.description || undefined, + shortcutIcon: team.avatarUrl + ? ((await team.publicAvatarUrl()) ?? undefined) + : undefined, + }; +} + +// Client routes that render without an authenticated session. +const publicAppPaths = [ + "/", + "/create", + "/logout", + "/desktop-redirect", + "/oauth/authorize", +]; + +function isPublicAppPath(pathname: string) { + return publicAppPaths.includes(pathname.replace(/\/+$/, "") || "/"); +}