Moved utility functions from assets to helpers

This commit is contained in:
Liyas Thomas
2020-09-26 07:57:45 +05:30
parent 8b3b6a471b
commit 66cd75dce8
5 changed files with 5 additions and 5 deletions

224
helpers/curlparser.js Normal file
View File

@@ -0,0 +1,224 @@
import * as cookie from "cookie"
import * as URL from "url"
import * as querystring from "querystring"
import parser from "yargs-parser"
/**
* given this: [ 'msg1=value1', 'msg2=value2' ]
* output this: 'msg1=value1&msg2=value2'
* @param dataArguments
*/
const joinDataArguments = (dataArguments) => {
let data = ""
dataArguments.forEach((argument, i) => {
if (i === 0) {
data += argument
} else {
data += `&${argument}`
}
})
return data
}
const parseCurlCommand = (curlCommand) => {
let newlineFound = /\\/gi.test(curlCommand)
if (newlineFound) {
// remove '\' and newlines
curlCommand = curlCommand.replace(/\\/gi, "")
curlCommand = curlCommand.replace(/\n/g, "")
}
// yargs parses -XPOST as separate arguments. just prescreen for it.
curlCommand = curlCommand.replace(/ -XPOST/, " -X POST")
curlCommand = curlCommand.replace(/ -XGET/, " -X GET")
curlCommand = curlCommand.replace(/ -XPUT/, " -X PUT")
curlCommand = curlCommand.replace(/ -XPATCH/, " -X PATCH")
curlCommand = curlCommand.replace(/ -XDELETE/, " -X DELETE")
curlCommand = curlCommand.trim()
let parsedArguments = parser(curlCommand)
let cookieString
let cookies
let url = parsedArguments._[1]
if (!url) {
for (let argName in parsedArguments) {
if (typeof parsedArguments[argName] === "string") {
if (["http", "www."].includes(parsedArguments[argName])) {
url = parsedArguments[argName]
}
}
}
}
let headers
const parseHeaders = (headerFieldName) => {
if (parsedArguments[headerFieldName]) {
if (!headers) {
headers = {}
}
if (!Array.isArray(parsedArguments[headerFieldName])) {
parsedArguments[headerFieldName] = [parsedArguments[headerFieldName]]
}
parsedArguments[headerFieldName].forEach((header) => {
if (header.includes("Cookie")) {
// stupid javascript tricks: closure
cookieString = header
} else {
let colonIndex = header.indexOf(":")
let headerName = header.substring(0, colonIndex)
let headerValue = header.substring(colonIndex + 1).trim()
headers[headerName] = headerValue
}
})
}
}
parseHeaders("H")
parseHeaders("header")
if (parsedArguments.A) {
if (!headers) {
headers = []
}
headers["User-Agent"] = parsedArguments.A
} else if (parsedArguments["user-agent"]) {
if (!headers) {
headers = []
}
headers["User-Agent"] = parsedArguments["user-agent"]
}
if (parsedArguments.b) {
cookieString = parsedArguments.b
}
if (parsedArguments.cookie) {
cookieString = parsedArguments.cookie
}
let multipartUploads
if (parsedArguments.F) {
multipartUploads = {}
if (!Array.isArray(parsedArguments.F)) {
parsedArguments.F = [parsedArguments.F]
}
parsedArguments.F.forEach((multipartArgument) => {
// input looks like key=value. value could be json or a file path prepended with an @
const [key, value] = multipartArgument.split("=", 2)
multipartUploads[key] = value
})
}
if (cookieString) {
const cookieParseOptions = {
decode: (s) => s,
}
// separate out cookie headers into separate data structure
// note: cookie is case insensitive
cookies = cookie.parse(cookieString.replace(/^Cookie: /gi, ""), cookieParseOptions)
}
let method
if (parsedArguments.X === "POST") {
method = "post"
} else if (parsedArguments.X === "PUT" || parsedArguments["T"]) {
method = "put"
} else if (parsedArguments.X === "PATCH") {
method = "patch"
} else if (parsedArguments.X === "DELETE") {
method = "delete"
} else if (parsedArguments.X === "OPTIONS") {
method = "options"
} else if (
(parsedArguments["d"] ||
parsedArguments["data"] ||
parsedArguments["data-ascii"] ||
parsedArguments["data-binary"] ||
parsedArguments["F"] ||
parsedArguments["form"]) &&
!(parsedArguments["G"] || parsedArguments["get"])
) {
method = "post"
} else if (parsedArguments["I"] || parsedArguments["head"]) {
method = "head"
} else {
method = "get"
}
let compressed = !!parsedArguments.compressed
let urlObject = URL.parse(url) // eslint-disable-line
// if GET request with data, convert data to query string
// NB: the -G flag does not change the http verb. It just moves the data into the url.
if (parsedArguments["G"] || parsedArguments["get"]) {
urlObject.query = urlObject.query ? urlObject.query : ""
let option = "d" in parsedArguments ? "d" : "data" in parsedArguments ? "data" : null
if (option) {
let urlQueryString = ""
if (!url.includes("?")) {
url += "?"
} else {
urlQueryString += "&"
}
if (typeof parsedArguments[option] === "object") {
urlQueryString += parsedArguments[option].join("&")
} else {
urlQueryString += parsedArguments[option]
}
urlObject.query += urlQueryString
url += urlQueryString
delete parsedArguments[option]
}
}
let query = querystring.parse(urlObject.query, null, null, {
maxKeys: 10000,
})
urlObject.search = null // Clean out the search/query portion.
const request = {
url,
urlWithoutQuery: URL.format(urlObject),
}
if (compressed) {
request["compressed"] = true
}
if (Object.keys(query).length > 0) {
request.query = query
}
if (headers) {
request.headers = headers
}
request["method"] = method
if (cookies) {
request.cookies = cookies
request.cookieString = cookieString.replace("Cookie: ", "")
}
if (multipartUploads) {
request.multipartUploads = multipartUploads
}
if (parsedArguments.data) {
request.data = parsedArguments.data
} else if (parsedArguments["data-binary"]) {
request.data = parsedArguments["data-binary"]
request.isDataBinary = true
} else if (parsedArguments["d"]) {
request.data = parsedArguments["d"]
} else if (parsedArguments["data-ascii"]) {
request.data = parsedArguments["data-ascii"]
}
if (parsedArguments["u"]) {
request.auth = parsedArguments["u"]
}
if (parsedArguments["user"]) {
request.auth = parsedArguments["user"]
}
if (Array.isArray(request.data)) {
request.dataArray = request.data
request.data = joinDataArguments(request.data)
}
if (parsedArguments["k"] || parsedArguments["insecure"]) {
request.insecure = true
}
return request
}
export default parseCurlCommand

227
helpers/oauth.js Normal file
View File

@@ -0,0 +1,227 @@
const redirectUri = `${window.location.origin}/`
// GENERAL HELPER FUNCTIONS
/**
* Makes a POST request and parse the response as JSON
*
* @param {String} url - The resource
* @param {Object} params - Configuration options
* @returns {Object}
*/
const sendPostRequest = async (url, params) => {
const body = Object.keys(params)
.map((key) => `${key}=${params[key]}`)
.join("&")
const options = {
method: "post",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body,
}
try {
const response = await fetch(url, options)
const data = await response.json()
return data
} catch (err) {
console.error("Request failed", err)
throw err
}
}
/**
* Parse a query string into an object
*
* @param {String} searchQuery - The search query params
* @returns {Object}
*/
const parseQueryString = (searchQuery) => {
if (searchQuery === "") {
return {}
}
const segments = searchQuery.split("&").map((s) => s.split("="))
const queryString = segments.reduce((obj, el) => ({ ...obj, [el[0]]: el[1] }), {})
return queryString
}
/**
* Get OAuth configuration from OpenID Discovery endpoint
*
* @returns {Object}
*/
const getTokenConfiguration = async (endpoint) => {
const options = {
method: "GET",
headers: {
"Content-type": "application/json",
},
}
try {
const response = await fetch(endpoint, options)
const config = await response.json()
return config
} catch (err) {
console.error("Request failed", err)
throw err
}
}
// PKCE HELPER FUNCTIONS
/**
* Generates a secure random string using the browser crypto functions
*
* @returns {Object}
*/
const generateRandomString = () => {
const array = new Uint32Array(28)
window.crypto.getRandomValues(array)
return Array.from(array, (dec) => `0${dec.toString(16)}`.substr(-2)).join("")
}
/**
* Calculate the SHA256 hash of the input text
*
* @returns {Promise<ArrayBuffer>}
*/
const sha256 = (plain) => {
const encoder = new TextEncoder()
const data = encoder.encode(plain)
return window.crypto.subtle.digest("SHA-256", data)
}
/**
* Encodes the input string into Base64 format
*
* @param {String} str - The string to be converted
* @returns {Promise<ArrayBuffer>}
*/
const base64urlencode = (
str // Converts the ArrayBuffer to string using Uint8 array to convert to what btoa accepts.
) =>
// btoa accepts chars only within ascii 0-255 and base64 encodes them.
// Then convert the base64 encoded to base64url encoded
// (replace + with -, replace / with _, trim trailing =)
btoa(String.fromCharCode.apply(null, new Uint8Array(str)))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "")
/**
* Return the base64-urlencoded sha256 hash for the PKCE challenge
*
* @param {String} v - The randomly generated string
* @returns {String}
*/
const pkceChallengeFromVerifier = async (v) => {
const hashed = await sha256(v)
return base64urlencode(hashed)
}
// OAUTH REQUEST
/**
* Initiates PKCE Auth Code flow when requested
*
* @param {Object} - The necessary params
* @returns {Void}
*/
const tokenRequest = async ({
oidcDiscoveryUrl,
grantType,
authUrl,
accessTokenUrl,
clientId,
scope,
}) => {
// Check oauth configuration
if (oidcDiscoveryUrl !== "") {
const { authorization_endpoint, token_endpoint } = await getTokenConfiguration(oidcDiscoveryUrl)
authUrl = authorization_endpoint
accessTokenUrl = token_endpoint
}
// Store oauth information
localStorage.setItem("token_endpoint", accessTokenUrl)
localStorage.setItem("client_id", clientId)
// Create and store a random state value
const state = generateRandomString()
localStorage.setItem("pkce_state", state)
// Create and store a new PKCE code_verifier (the plaintext random secret)
const code_verifier = generateRandomString()
localStorage.setItem("pkce_code_verifier", code_verifier)
// Hash and base64-urlencode the secret to use as the challenge
const code_challenge = await pkceChallengeFromVerifier(code_verifier)
// Build the authorization URL
const buildUrl = () =>
`${authUrl + `?response_type=${grantType}`}&client_id=${encodeURIComponent(
clientId
)}&state=${encodeURIComponent(state)}&scope=${encodeURIComponent(
scope
)}&redirect_uri=${encodeURIComponent(redirectUri)}&code_challenge=${encodeURIComponent(
code_challenge
)}&code_challenge_method=S256`
// Redirect to the authorization server
window.location = buildUrl()
}
// OAUTH REDIRECT HANDLING
/**
* Handle the redirect back from the authorization server and
* get an access token from the token endpoint
*
* @returns {Object}
*/
const oauthRedirect = async () => {
let tokenResponse = ""
let q = parseQueryString(window.location.search.substring(1))
// Check if the server returned an error string
if (q.error) {
alert(`Error returned from authorization server: ${q.error}`)
}
// If the server returned an authorization code, attempt to exchange it for an access token
if (q.code) {
// Verify state matches what we set at the beginning
if (localStorage.getItem("pkce_state") != q.state) {
alert("Invalid state")
} else {
try {
// Exchange the authorization code for an access token
tokenResponse = await sendPostRequest(localStorage.getItem("token_endpoint"), {
grant_type: "authorization_code",
code: q.code,
client_id: localStorage.getItem("client_id"),
redirect_uri: redirectUri,
code_verifier: localStorage.getItem("pkce_code_verifier"),
})
} catch (err) {
console.log(`${error.error}\n\n${error.error_description}`)
}
}
// Clean these up since we don't need them anymore
localStorage.removeItem("pkce_state")
localStorage.removeItem("pkce_code_verifier")
localStorage.removeItem("token_endpoint")
localStorage.removeItem("client_id")
return tokenResponse
}
return tokenResponse
}
export { tokenRequest, oauthRedirect }

51
helpers/pwa.js Normal file
View File

@@ -0,0 +1,51 @@
export default () => {
//*** Determine whether or not the PWA has been installed. ***//
// Step 1: Check local storage
let pwaInstalled = localStorage.getItem("pwaInstalled") === "yes"
// Step 2: Check if the display-mode is standalone. (Only permitted for PWAs.)
if (!pwaInstalled && window.matchMedia("(display-mode: standalone)").matches) {
localStorage.setItem("pwaInstalled", "yes")
pwaInstalled = true
}
// Step 3: Check if the navigator is in standalone mode. (Again, only permitted for PWAs.)
if (!pwaInstalled && window.navigator.standalone === true) {
localStorage.setItem("pwaInstalled", "yes")
pwaInstalled = true
}
//*** If the PWA has not been installed, show the install PWA prompt.. ***//
let deferredPrompt = null
window.addEventListener("beforeinstallprompt", (event) => {
deferredPrompt = event
// Show the install button if the prompt appeared.
if (!pwaInstalled) {
document.querySelector("#installPWA").style.display = "inline-flex"
}
})
// When the app is installed, remove install prompts.
window.addEventListener("appinstalled", (event) => {
localStorage.setItem("pwaInstalled", "yes")
pwaInstalled = true
document.getElementById("installPWA").style.display = "none"
})
// When the app is uninstalled, add the prompts back
return async () => {
if (deferredPrompt) {
deferredPrompt.prompt()
let outcome = await deferredPrompt.userChoice
if (outcome === "accepted") {
console.log("Hoppscotch was installed successfully.")
} else {
console.log("Hoppscotch could not be installed. (Installation rejected by user.)")
}
deferredPrompt = null
}
}
}