-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Support HTTP headers with CORS-method #2957
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
rejas
merged 5 commits into
MagicMirrorOrg:develop
from
MagMar94:feature/support-http-headers-with-cors
Oct 30, 2022
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e27fd2e
Moved server logic to separate file.
1c8ea72
Added functionality for sending and recieving HTTP-headers.
1f21ee1
Merge branch 'develop' into feature/support-http-headers-with-cors
b904a1e
Merge branch 'develop' into feature/support-http-headers-with-cors
68e321b
Small changes after merging with develop-branch.
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| const fetch = require("./fetch"); | ||
| const fs = require("fs"); | ||
| const path = require("path"); | ||
| const Log = require("logger"); | ||
|
|
||
| /** | ||
| * Gets the config. | ||
| * | ||
| * @param {Request} req - the request | ||
| * @param {Response} res - the result | ||
| */ | ||
| function getConfig(req, res) { | ||
| res.send(config); | ||
| } | ||
|
|
||
| /** | ||
| * A method that forewards HTTP Get-methods to the internet to avoid CORS-errors. | ||
| * | ||
| * Example input request url: /cors?sendheaders=header1:value1,header2:value2&expectedheaders=header1,header2&url=http://www.test.com/path?param1=value1 | ||
| * | ||
| * Only the url-param of the input request url is required. It must be the last parameter. | ||
| * | ||
| * @param {Request} req - the request | ||
| * @param {Response} res - the result | ||
| */ | ||
| async function cors(req, res) { | ||
| try { | ||
| const urlRegEx = "url=(.+?)$"; | ||
| let url = ""; | ||
|
|
||
| const match = new RegExp(urlRegEx, "g").exec(req.url); | ||
| if (!match) { | ||
| url = "invalid url: " + req.url; | ||
| Log.error(url); | ||
| res.send(url); | ||
| } else { | ||
| url = match[1]; | ||
|
|
||
| const headersToSend = getHeadersToSend(req.url); | ||
| const expectedRecievedHeaders = geExpectedRecievedHeaders(req.url); | ||
|
|
||
| Log.log("cors url: " + url); | ||
| const response = await fetch(url, { headers: headersToSend }); | ||
|
|
||
| for (const header of expectedRecievedHeaders) { | ||
| const headerValue = response.headers.get(header); | ||
| if (header) res.set(header, headerValue); | ||
| } | ||
| const data = await response.text(); | ||
| res.send(data); | ||
| } | ||
| } catch (error) { | ||
| Log.error(error); | ||
| res.send(error); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Gets headers and values to attatch to the web request. | ||
| * | ||
| * @param {string} url - The url containing the headers and values to send. | ||
| * @returns {object} An object specifying name and value of the headers. | ||
| */ | ||
| function getHeadersToSend(url) { | ||
| const headersToSend = { "User-Agent": "Mozilla/5.0 MagicMirror/" + global.version }; | ||
| const headersToSendMatch = new RegExp("sendheaders=(.+?)(&|$)", "g").exec(url); | ||
| if (headersToSendMatch) { | ||
| const headers = headersToSendMatch[1].split(","); | ||
| for (const header of headers) { | ||
| const keyValue = header.split(":"); | ||
| if (keyValue.length !== 2) { | ||
| throw new Error(`Invalid format for header ${header}`); | ||
| } | ||
| headersToSend[keyValue[0]] = decodeURIComponent(keyValue[1]); | ||
| } | ||
| } | ||
| return headersToSend; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the headers expected from the response. | ||
| * | ||
| * @param {string} url - The url containing the expected headers from the response. | ||
| * @returns {string[]} headers - The name of the expected headers. | ||
| */ | ||
| function geExpectedRecievedHeaders(url) { | ||
| const expectedRecievedHeaders = ["Content-Type"]; | ||
| const expectedRecievedHeadersMatch = new RegExp("expectedheaders=(.+?)(&|$)", "g").exec(url); | ||
| if (expectedRecievedHeadersMatch) { | ||
| const headers = expectedRecievedHeadersMatch[1].split(","); | ||
| for (const header of headers) { | ||
| expectedRecievedHeaders.push(header); | ||
| } | ||
| } | ||
| return expectedRecievedHeaders; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the HTML to display the magic mirror. | ||
| * | ||
| * @param {Request} req - the request | ||
| * @param {Response} res - the result | ||
| */ | ||
| function getHtml(req, res) { | ||
| let html = fs.readFileSync(path.resolve(`${global.root_path}/index.html`), { encoding: "utf8" }); | ||
| html = html.replace("#VERSION#", global.version); | ||
|
|
||
| let configFile = "config/config.js"; | ||
| if (typeof global.configuration_file !== "undefined") { | ||
| configFile = global.configuration_file; | ||
| } | ||
| html = html.replace("#CONFIG_FILE#", configFile); | ||
|
|
||
| res.send(html); | ||
| } | ||
|
|
||
| /** | ||
| * Gets the MagicMirror version. | ||
| * | ||
| * @param {Request} req - the request | ||
| * @param {Response} res - the result | ||
| */ | ||
| function getVersion(req, res) { | ||
| res.send(global.version); | ||
| } | ||
|
|
||
| module.exports = { cors, getConfig, getHtml, getVersion }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| const { cors } = require("../../../js/server_functions"); | ||
|
|
||
| describe("server_functions tests", () => { | ||
| describe("The cors method", () => { | ||
| let fetchResponse; | ||
| let fetchResponseHeadersGet; | ||
| let fetchResponseHeadersText; | ||
| let corsResponse; | ||
| let request; | ||
|
|
||
| jest.mock("node-fetch"); | ||
| let nodefetch = require("node-fetch"); | ||
| let fetchMock; | ||
|
|
||
| beforeEach(() => { | ||
| nodefetch.mockReset(); | ||
|
|
||
| fetchResponseHeadersGet = jest.fn(() => {}); | ||
| fetchResponseHeadersText = jest.fn(() => {}); | ||
| fetchResponse = { | ||
| headers: { | ||
| get: fetchResponseHeadersGet | ||
| }, | ||
| text: fetchResponseHeadersText | ||
| }; | ||
| jest.mock("node-fetch", () => jest.fn()); | ||
| nodefetch.mockImplementation(() => fetchResponse); | ||
|
|
||
| fetchMock = nodefetch; | ||
|
|
||
| corsResponse = { | ||
| set: jest.fn(() => {}), | ||
| send: jest.fn(() => {}) | ||
| }; | ||
|
|
||
| request = { | ||
| url: `/cors?url=www.test.com` | ||
| }; | ||
| }); | ||
|
|
||
| test("Calls correct URL once", async () => { | ||
| const urlToCall = "http://www.test.com/path?param1=value1"; | ||
| request.url = `/cors?url=${urlToCall}`; | ||
|
|
||
| await cors(request, corsResponse); | ||
|
|
||
| expect(fetchMock.mock.calls.length).toBe(1); | ||
| expect(fetchMock.mock.calls[0][0]).toBe(urlToCall); | ||
| }); | ||
|
|
||
| test("Forewards Content-Type if json", async () => { | ||
| fetchResponseHeadersGet.mockImplementation(() => "json"); | ||
|
|
||
| await cors(request, corsResponse); | ||
|
|
||
| expect(fetchResponseHeadersGet.mock.calls.length).toBe(1); | ||
| expect(fetchResponseHeadersGet.mock.calls[0][0]).toBe("Content-Type"); | ||
|
|
||
| expect(corsResponse.set.mock.calls.length).toBe(1); | ||
| expect(corsResponse.set.mock.calls[0][0]).toBe("Content-Type"); | ||
| expect(corsResponse.set.mock.calls[0][1]).toBe("json"); | ||
| }); | ||
|
|
||
| test("Forewards Content-Type if xml", async () => { | ||
| fetchResponseHeadersGet.mockImplementation(() => "xml"); | ||
|
|
||
| await cors(request, corsResponse); | ||
|
|
||
| expect(fetchResponseHeadersGet.mock.calls.length).toBe(1); | ||
| expect(fetchResponseHeadersGet.mock.calls[0][0]).toBe("Content-Type"); | ||
|
|
||
| expect(corsResponse.set.mock.calls.length).toBe(1); | ||
| expect(corsResponse.set.mock.calls[0][0]).toBe("Content-Type"); | ||
| expect(corsResponse.set.mock.calls[0][1]).toBe("xml"); | ||
| }); | ||
|
|
||
| test("Sends correct data from response", async () => { | ||
| const responseData = "some data"; | ||
| fetchResponseHeadersText.mockImplementation(() => responseData); | ||
|
|
||
| let sentData; | ||
| corsResponse.send = jest.fn((input) => { | ||
| sentData = input; | ||
| }); | ||
|
|
||
| await cors(request, corsResponse); | ||
|
|
||
| expect(fetchResponseHeadersText.mock.calls.length).toBe(1); | ||
| expect(sentData).toBe(responseData); | ||
| }); | ||
|
|
||
| test("Sends error data from response", async () => { | ||
| const error = new Error("error data"); | ||
| fetchResponseHeadersText.mockImplementation(() => { | ||
| throw error; | ||
| }); | ||
|
|
||
| let sentData; | ||
| corsResponse.send = jest.fn((input) => { | ||
| sentData = input; | ||
| }); | ||
|
|
||
| await cors(request, corsResponse); | ||
|
|
||
| expect(fetchResponseHeadersText.mock.calls.length).toBe(1); | ||
| expect(sentData).toBe(error); | ||
| }); | ||
|
|
||
| test("Fetches with user agent by default", async () => { | ||
| await cors(request, corsResponse); | ||
|
|
||
| expect(fetchMock.mock.calls.length).toBe(1); | ||
| expect(fetchMock.mock.calls[0][1]).toHaveProperty("headers"); | ||
| expect(fetchMock.mock.calls[0][1].headers).toHaveProperty("User-Agent"); | ||
| }); | ||
|
|
||
| test("Fetches with specified headers", async () => { | ||
| const headersParam = "sendheaders=header1:value1,header2:value2"; | ||
| const urlParam = "http://www.test.com/path?param1=value1"; | ||
| request.url = `/cors?${headersParam}&url=${urlParam}`; | ||
|
|
||
| await cors(request, corsResponse); | ||
|
|
||
| expect(fetchMock.mock.calls.length).toBe(1); | ||
| expect(fetchMock.mock.calls[0][1]).toHaveProperty("headers"); | ||
| expect(fetchMock.mock.calls[0][1].headers).toHaveProperty("header1", "value1"); | ||
| expect(fetchMock.mock.calls[0][1].headers).toHaveProperty("header2", "value2"); | ||
| }); | ||
|
|
||
| test("Sends specified headers", async () => { | ||
| fetchResponseHeadersGet.mockImplementation((input) => input.replace("header", "value")); | ||
|
|
||
| const expectedheaders = "expectedheaders=header1,header2"; | ||
| const urlParam = "http://www.test.com/path?param1=value1"; | ||
| request.url = `/cors?${expectedheaders}&url=${urlParam}`; | ||
|
|
||
| await cors(request, corsResponse); | ||
|
|
||
| expect(fetchMock.mock.calls.length).toBe(1); | ||
| expect(fetchMock.mock.calls[0][1]).toHaveProperty("headers"); | ||
| expect(corsResponse.set.mock.calls.length).toBe(3); | ||
| expect(corsResponse.set.mock.calls[0][0]).toBe("Content-Type"); | ||
| expect(corsResponse.set.mock.calls[1][0]).toBe("header1"); | ||
| expect(corsResponse.set.mock.calls[1][1]).toBe("value1"); | ||
| expect(corsResponse.set.mock.calls[2][0]).toBe("header2"); | ||
| expect(corsResponse.set.mock.calls[2][1]).toBe("value2"); | ||
| }); | ||
| }); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.