From 32bca09f4bfdf05bf129c1e8c873b202d98824f6 Mon Sep 17 00:00:00 2001 From: zkldi Date: Fri, 2 Jul 2021 16:20:27 +0100 Subject: [PATCH] add cdn redirects --- server/src/server/router/cdn/router.test.ts | 20 ++++++++++++++++++++ server/src/server/router/cdn/router.ts | 21 +++++++++++++++++++++ server/src/server/router/router.ts | 2 ++ 3 files changed, 43 insertions(+) create mode 100644 server/src/server/router/cdn/router.test.ts create mode 100644 server/src/server/router/cdn/router.ts diff --git a/server/src/server/router/cdn/router.test.ts b/server/src/server/router/cdn/router.test.ts new file mode 100644 index 000000000..c248ca5df --- /dev/null +++ b/server/src/server/router/cdn/router.test.ts @@ -0,0 +1,20 @@ +import t from "tap"; +import { CDNStoreOrOverwrite } from "../../../lib/cdn/cdn"; +import { CloseAllConnections } from "../../../test-utils/close-connections"; +import mockApi from "../../../test-utils/mock-api"; + +t.test("GET /cdn", (t) => { + t.test("Should return this content at the CDN.", async (t) => { + await CDNStoreOrOverwrite("/foo", "hello world"); + + const res = await mockApi.get("/cdn/foo"); + + t.equal(res.body.toString(), "hello world"); + + t.end(); + }); + + t.end(); +}); + +t.teardown(CloseAllConnections); diff --git a/server/src/server/router/cdn/router.ts b/server/src/server/router/cdn/router.ts new file mode 100644 index 000000000..3e9e21df6 --- /dev/null +++ b/server/src/server/router/cdn/router.ts @@ -0,0 +1,21 @@ +import { Router } from "express"; +import { CDNRedirect } from "../../../lib/cdn/cdn"; + +const router: Router = Router({ mergeParams: true }); + +/** + * Redirect all /cdn/ requests to this servers' CDN. This is so the client can refer to + * (url)/cdn, and still have it resolve to our CDN internally. + * + * @example instead of + * + * @name GET /cdn/* + */ +router.get("*", (req, res) => { + console.log(req.originalUrl); + const url = req.originalUrl.replace(/^\/cdn/u, ""); + console.log(url); + return CDNRedirect(res, url); +}); + +export default router; diff --git a/server/src/server/router/router.ts b/server/src/server/router/router.ts index 5b5e6a9a6..3889a44e2 100644 --- a/server/src/server/router/router.ts +++ b/server/src/server/router/router.ts @@ -3,6 +3,7 @@ import { SetRequestPermissions } from "../middleware/auth"; import { RateLimitMiddleware } from "../middleware/rate-limiter"; import apiRouterV1 from "./api/v1/router"; import irRouter from "./ir/router"; +import cdnReRouter from "./cdn/router"; const router: Router = Router({ mergeParams: true }); @@ -15,5 +16,6 @@ router.use("/ir", irRouter); // but also may require custom authentication. router.use(SetRequestPermissions); router.use("/api/v1", apiRouterV1); +router.use("/cdn", cdnReRouter); export default router;