diff --git a/api.planx.uk/modules/ordnanceSurvey/controller.ts b/api.planx.uk/modules/ordnanceSurvey/controller.ts index d950eb36ab..79ebe1515c 100644 --- a/api.planx.uk/modules/ordnanceSurvey/controller.ts +++ b/api.planx.uk/modules/ordnanceSurvey/controller.ts @@ -1,6 +1,7 @@ import { useProxy } from "../../shared/middleware/proxy"; import { NextFunction, Request, Response } from "express"; import { IncomingMessage } from "http"; +import { request } from "https"; export const OS_DOMAIN = "https://api.os.uk"; @@ -28,7 +29,7 @@ export const useOrdnanceSurveyProxy = async ( return useProxy({ target: OS_DOMAIN, - onProxyRes: (proxyRes) => setCORPHeaders(proxyRes), + onProxyRes: (proxyRes) => setCORPHeaders(proxyRes, req), pathRewrite: (fullPath, req) => appendAPIKey(fullPath, req), })(req, res, next); }; @@ -36,8 +37,11 @@ export const useOrdnanceSurveyProxy = async ( const isValid = (req: Request): boolean => MAP_ALLOWLIST.some((re) => re.test(req.headers?.referer as string)); -const setCORPHeaders = (proxyRes: IncomingMessage): void => { +const setCORPHeaders = (proxyRes: IncomingMessage, req: Request): void => { proxyRes.headers["Cross-Origin-Resource-Policy"] = "cross-origin"; + proxyRes.headers["Access-Control-Allow-Origin"] = req.headers.origin; + proxyRes.headers["Access-Control-Allow-Headers"] = + "Origin, X-Requested-With, Content-Type, Accept"; }; export const appendAPIKey = (fullPath: string, req: Request): string => { diff --git a/api.planx.uk/modules/ordnanceSurvey/routes.ts b/api.planx.uk/modules/ordnanceSurvey/routes.ts index b8f5204c94..7006c7ebff 100644 --- a/api.planx.uk/modules/ordnanceSurvey/routes.ts +++ b/api.planx.uk/modules/ordnanceSurvey/routes.ts @@ -1,8 +1,20 @@ +import cors from "cors"; import { Router } from "express"; import { useOrdnanceSurveyProxy } from "./controller"; const router = Router(); -router.use("/proxy/ordnance-survey", useOrdnanceSurveyProxy); +// Because this route already uses MAP_ALLOWLIST, disable global CORS checks so map repo docs and HTML templates are accessible +const osProxyCORSOptions = { + credentials: true, + methods: "*", +}; + +router.options("/proxy/ordnance-survey", cors(osProxyCORSOptions)); +router.use( + "/proxy/ordnance-survey", + cors(osProxyCORSOptions), + useOrdnanceSurveyProxy, +); export default router;