From c4e00fbbfa6a1b9d74d4caacd9e20d67b68ba6aa Mon Sep 17 00:00:00 2001 From: Pouya Oftadeh Date: Tue, 1 Oct 2019 14:01:41 -0400 Subject: [PATCH 1/3] refactor: remove references to legacy folder --- .eslintignore | 1 - .prettierignore | 1 - package.json | 4 +--- 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/.eslintignore b/.eslintignore index f524a282..919faf0e 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,4 +1,3 @@ /node_modules -/legacy /build/** /test/ diff --git a/.prettierignore b/.prettierignore index 4680cec0..afd2efc7 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,4 +1,3 @@ /node_modules /docs -/legacy /build diff --git a/package.json b/package.json index e02698b8..860f955c 100644 --- a/package.json +++ b/package.json @@ -47,9 +47,7 @@ }, "jest": { "modulePathIgnorePatterns": [ - "/src/", - "/legacy/", - "/node_modules/" + "/src/" ] }, "scripts": { From cfbc86af49c6782ef014ba4033af88569a9b3641 Mon Sep 17 00:00:00 2001 From: Pouya Oftadeh Date: Tue, 1 Oct 2019 14:02:23 -0400 Subject: [PATCH 2/3] refactor: remove legacy folder --- .../CapabilityValidator.js | 222 --- legacy/Error/BadRequestError.js | 9 - legacy/Error/InternalServerError.js | 9 - legacy/Error/InvalidArgument.js | 12 - legacy/Error/MethodNotAllowedError.js | 9 - legacy/Error/NoSuchElement.js | 12 - legacy/Error/NotFoundError.js | 9 - legacy/Error/RequestTimeoutError.js | 9 - legacy/Error/SessionNotCreated.js | 11 - legacy/Error/WebDriverError.js | 15 - legacy/Error/errors.js | 6 - legacy/Request/Request.js | 10 - legacy/Session/Session.js | 551 ------- legacy/SessionsManager/SessionsManager.js | 72 - legacy/WebElement/WebElement.js | 83 - legacy/browser/browser.js | 275 ---- legacy/commands/commands.js | 21 - legacy/jsdom_extensions/addFileList.js | 44 - legacy/jsdom_extensions/tough-cookie/LICENSE | 12 - .../jsdom_extensions/tough-cookie/README.md | 507 ------ .../tough-cookie/lib/cookie.js | 1432 ----------------- .../tough-cookie/lib/memstore.js | 176 -- .../tough-cookie/lib/pathMatch.js | 61 - .../tough-cookie/lib/permuteDomain.js | 64 - .../tough-cookie/lib/pubsuffix-psl.js | 38 - .../tough-cookie/lib/store.js | 71 - .../tough-cookie/package.json | 97 -- .../pluma-selenium-client.js | 43 - legacy/pluma-webdriver.js | 102 -- legacy/routes/cookies.js | 72 - legacy/routes/elements/elements.js | 41 - legacy/routes/elements/fromElement.js | 109 -- legacy/routes/index.js | 99 -- legacy/routes/navigate.js | 32 - legacy/routes/timeouts.js | 16 - legacy/utils/utils.js | 43 - 36 files changed, 4394 deletions(-) delete mode 100644 legacy/CapabilityValidator/CapabilityValidator.js delete mode 100644 legacy/Error/BadRequestError.js delete mode 100644 legacy/Error/InternalServerError.js delete mode 100644 legacy/Error/InvalidArgument.js delete mode 100644 legacy/Error/MethodNotAllowedError.js delete mode 100644 legacy/Error/NoSuchElement.js delete mode 100644 legacy/Error/NotFoundError.js delete mode 100644 legacy/Error/RequestTimeoutError.js delete mode 100644 legacy/Error/SessionNotCreated.js delete mode 100644 legacy/Error/WebDriverError.js delete mode 100644 legacy/Error/errors.js delete mode 100644 legacy/Request/Request.js delete mode 100644 legacy/Session/Session.js delete mode 100644 legacy/SessionsManager/SessionsManager.js delete mode 100644 legacy/WebElement/WebElement.js delete mode 100644 legacy/browser/browser.js delete mode 100644 legacy/commands/commands.js delete mode 100644 legacy/jsdom_extensions/addFileList.js delete mode 100644 legacy/jsdom_extensions/tough-cookie/LICENSE delete mode 100644 legacy/jsdom_extensions/tough-cookie/README.md delete mode 100644 legacy/jsdom_extensions/tough-cookie/lib/cookie.js delete mode 100644 legacy/jsdom_extensions/tough-cookie/lib/memstore.js delete mode 100644 legacy/jsdom_extensions/tough-cookie/lib/pathMatch.js delete mode 100644 legacy/jsdom_extensions/tough-cookie/lib/permuteDomain.js delete mode 100644 legacy/jsdom_extensions/tough-cookie/lib/pubsuffix-psl.js delete mode 100644 legacy/jsdom_extensions/tough-cookie/lib/store.js delete mode 100644 legacy/jsdom_extensions/tough-cookie/package.json delete mode 100644 legacy/pluma-selenium-client/pluma-selenium-client.js delete mode 100644 legacy/pluma-webdriver.js delete mode 100644 legacy/routes/cookies.js delete mode 100644 legacy/routes/elements/elements.js delete mode 100644 legacy/routes/elements/fromElement.js delete mode 100644 legacy/routes/index.js delete mode 100644 legacy/routes/navigate.js delete mode 100644 legacy/routes/timeouts.js delete mode 100644 legacy/utils/utils.js diff --git a/legacy/CapabilityValidator/CapabilityValidator.js b/legacy/CapabilityValidator/CapabilityValidator.js deleted file mode 100644 index 6c3d2058..00000000 --- a/legacy/CapabilityValidator/CapabilityValidator.js +++ /dev/null @@ -1,222 +0,0 @@ -const validator = require('validator'); -const util = require('../utils/utils'); - -class CapabilityValidator { - constructor() { - this.valid = true; - } - - validate(capability, capabilityName) { - switch (capabilityName) { - case 'browserName': - case 'browserVersion': - case 'platformName': - this.valid = util.validate.type(capability, 'string'); - break; - case 'acceptInsecureCerts': - this.valid = util.validate.type(capability, 'boolean'); - break; - case 'pageLoadStrategy': - if (typeof capability !== 'string') this.valid = false; - else this.valid = true; - - if ( - this.valid - && capability !== 'none' - && capability !== 'eager' - && capability !== 'normal' - ) this.valid = false; - - break; - case 'unhandledPromptBehavior': - if (typeof capability !== 'string') this.valid = false; - else this.valid = true; - - if ( - this.valid - && capability !== 'dismiss' - && capability !== 'accept' - && capability !== 'dismiss and notify' - && capability !== 'accept and notify' - && capability !== 'ignore' - ) this.valid = false; - - break; - case 'proxy': - if (!util.validate.type(capability, 'object')) this.valid = false; - else this.valid = true; - - if (!this.valid || !CapabilityValidator.validateProxy(capability)) this.valid = false; - break; - case 'timeouts': - if (!util.validate.type(capability, 'object')) this.valid = false; - else this.valid = true; - - Object.keys(capability).forEach((key) => { - if (this.valid && !this.validateTimeouts(key, capability[key])) this.valid = false; - }); - break; - case 'plm:plumaOptions': - if (capability.constructor !== Object) this.valid = false; - else this.valid = true; - - if (this.valid && !CapabilityValidator.validatePlumaOptions(capability)) this.valid = false; - break; - default: - this.valid = false; - break; - } - return this.valid; - } - - static validatePlumaOptions(options) { - let validatedOptions = true; - - const allowedOptions = { - url(url) { - return validator.isURL(url); - }, - referrer(referrer) { - return validator.isURL(referrer); - }, - contentType(contentType) { - let valid; - const validTypes = ['text/html', 'application/xml']; - - if (contentType.constructor === String) valid = true; - else valid = false; - - if ( - validTypes.includes(contentType) - || contentType.substr(contentType.length - 4) === '+xml' - ) { - valid = true; - } else valid = false; - - return valid; - }, - includeNodeLocations(value) { - if (value.constructor === Boolean) return true; - return false; - }, - storageQuota(quota) { - return Number.isInteger(quota); - }, - runScripts(value) { - return value.constructor === Boolean; - }, - resources(resources) { - if (resources.constructor !== String) return false; - if (resources !== 'useable') return false; - return true; - }, - rejectPublicSuffixes(value) { - return value.constructor === Boolean; - }, - }; - - Object.keys(options).forEach((key) => { - if (!Object.keys(allowedOptions).includes(key)) validatedOptions = false; - if (validatedOptions) { - try { - validatedOptions = allowedOptions[key](options[key]); - } catch (err) { - validatedOptions = false; - } - } - }); - return validatedOptions; - } - - validateTimeouts(key, value) { - const timeoutTypes = ['script', 'pageLoad', 'implicit']; - this.valid = timeoutTypes.includes(key); - this.valid = this.valid - ? (Number.isInteger(value) && value > 0) - : this.valid; - return this.valid; - } - - static validateProxy(reqProxy) { - const proxyProperties = [ - 'proxyType', - 'proxyAutoConfigUrl', - 'ftpProxy', - 'httpProxy', - 'noProxy', - 'sslProxy', - 'socksProxy', - 'socksVersion', - ]; - - let validProxy = true; - - validProxy = !util.validate.isEmpty(reqProxy); - - if (validProxy) { - Object.keys(reqProxy).forEach((key) => { - if (validProxy) { - if (!proxyProperties.includes(key)) { - validProxy = false; - } else { - switch (key) { - case 'proxyType': - if (reqProxy[key] === 'pac') { - validProxy = Object.prototype.hasOwnProperty.call(reqProxy, 'proxyAutoConfigUrl'); - } else if ( - reqProxy[key] !== 'direct' - && reqProxy[key] !== 'autodetect' - && reqProxy[key] !== 'system' - && reqProxy[key] !== 'manual' - ) validProxy = false; - break; - case 'proxyAutoConfigUrl': - validProxy = validProxy - ? validator.isURL(reqProxy[key]) - : validProxy; - break; - case 'ftpProxy': - case 'httpProxy': - case 'sslProxy': - validProxy = (reqProxy.proxyType === 'manual'); - validProxy = validProxy - ? validator.isURL(reqProxy[key]) - : validProxy; - - break; - case 'socksProxy': - validProxy = (reqProxy.proxyType === 'manual'); - validProxy = validProxy - ? Object.prototype.hasOwnProperty.call(reqProxy, 'socksVersion') - : validProxy; - - validProxy = validProxy - ? validator.isURL(reqProxy[key]) - : validProxy; - break; - case 'socksVersion': - validProxy = (reqProxy.proxyType === 'manual'); - validProxy = validProxy - ? (Number.isInteger(reqProxy[key]) && reqProxy[key] > -1 && reqProxy[key] < 256) - : validProxy; - break; - case 'noProxy': - validProxy = util.validate.type(reqProxy[key], 'array'); - if (validProxy) { - reqProxy[key].forEach((url) => { - if (validProxy) validProxy = validator.isURL(url); - }); - } - break; - default: - validProxy = false; - } - } - } - }); - } - return validProxy; - } -} - -module.exports = CapabilityValidator; diff --git a/legacy/Error/BadRequestError.js b/legacy/Error/BadRequestError.js deleted file mode 100644 index 1f90993c..00000000 --- a/legacy/Error/BadRequestError.js +++ /dev/null @@ -1,9 +0,0 @@ -const WebDriverError = require('./WebDriverError'); - -class BadRequestError extends WebDriverError { - constructor(message) { - super(message, 400); - } -} - -module.exports = BadRequestError; diff --git a/legacy/Error/InternalServerError.js b/legacy/Error/InternalServerError.js deleted file mode 100644 index 2c3bc355..00000000 --- a/legacy/Error/InternalServerError.js +++ /dev/null @@ -1,9 +0,0 @@ -const WebDriverError = require('./WebDriverError'); - -class InternalServerError extends WebDriverError { - constructor(message) { - super(message, 500); - } -} - -module.exports = InternalServerError; diff --git a/legacy/Error/InvalidArgument.js b/legacy/Error/InvalidArgument.js deleted file mode 100644 index 89cb82df..00000000 --- a/legacy/Error/InvalidArgument.js +++ /dev/null @@ -1,12 +0,0 @@ -const BadRequest = require('./BadRequestError'); - -class InvalidArgument extends BadRequest { - constructor(command) { - const message = `The arguments passed to ${command} are either invalid or malformed`; - super(message); - this.value.error = 'invalid argument'; - this.value.message = message; - } -} - -module.exports = InvalidArgument; diff --git a/legacy/Error/MethodNotAllowedError.js b/legacy/Error/MethodNotAllowedError.js deleted file mode 100644 index 55f28621..00000000 --- a/legacy/Error/MethodNotAllowedError.js +++ /dev/null @@ -1,9 +0,0 @@ -class MethodNotAllowedError extends Error { - constructor(message) { - super(message); - this.name = 'MethodNotAllowedError'; - this.code = 405; - } -} - -module.exports = MethodNotAllowedError; diff --git a/legacy/Error/NoSuchElement.js b/legacy/Error/NoSuchElement.js deleted file mode 100644 index 57e84161..00000000 --- a/legacy/Error/NoSuchElement.js +++ /dev/null @@ -1,12 +0,0 @@ -const NotFoundError = require('./NotFoundError'); - -class NoSuchElement extends NotFoundError { - constructor() { - const message = 'An element could not be located on the page using the given search parameters.'; - super(message); - this.value.error = 'no such element'; - this.value.message = message; - } -} - -module.exports = NoSuchElement; diff --git a/legacy/Error/NotFoundError.js b/legacy/Error/NotFoundError.js deleted file mode 100644 index 76e67a6e..00000000 --- a/legacy/Error/NotFoundError.js +++ /dev/null @@ -1,9 +0,0 @@ -const WebDriverError = require('./WebDriverError'); - -class NotFoundError extends WebDriverError { - constructor(message) { - super(message, 404); - } -} - -module.exports = NotFoundError; diff --git a/legacy/Error/RequestTimeoutError.js b/legacy/Error/RequestTimeoutError.js deleted file mode 100644 index 71bb7ee0..00000000 --- a/legacy/Error/RequestTimeoutError.js +++ /dev/null @@ -1,9 +0,0 @@ -class RequestTimeoutError extends Error { - constructor(message) { - super(message); - this.name = 'RequestTimeOutError'; - this.code = 408; - } -} - -module.exports = RequestTimeoutError; diff --git a/legacy/Error/SessionNotCreated.js b/legacy/Error/SessionNotCreated.js deleted file mode 100644 index ea88bdea..00000000 --- a/legacy/Error/SessionNotCreated.js +++ /dev/null @@ -1,11 +0,0 @@ -const InternalServerError = require('./InternalServerError'); - -class SessionNotCreated extends InternalServerError { - constructor(message = '') { - super(message); - this.value.error = 'session not created'; - this.value.message = `A new session could not be created: ${message}`; - } -} - -module.exports = SessionNotCreated; diff --git a/legacy/Error/WebDriverError.js b/legacy/Error/WebDriverError.js deleted file mode 100644 index 052e2ede..00000000 --- a/legacy/Error/WebDriverError.js +++ /dev/null @@ -1,15 +0,0 @@ -class WebDriverError extends Error { - constructor(message, code) { - super(message); - Object.defineProperty(this, 'code', { - value: code, - writable: false, - enumerable: false, - }); - this.value = { - stacktrace: this.stack, - }; - } -} - -module.exports = WebDriverError; diff --git a/legacy/Error/errors.js b/legacy/Error/errors.js deleted file mode 100644 index 48ccc6a7..00000000 --- a/legacy/Error/errors.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports.MethodNotAllowed = require('./MethodNotAllowedError'); // remove -module.exports.NoSuchElement = require('./NoSuchElement'); -module.exports.NotFoundError = require('./NotFoundError'); -module.exports.RequestTimeout = require('./RequestTimeoutError'); // remove -module.exports.InvalidArgument = require('./InvalidArgument'); -module.exports.SessionNotCreated = require('./SessionNotCreated'); diff --git a/legacy/Request/Request.js b/legacy/Request/Request.js deleted file mode 100644 index aaae3cda..00000000 --- a/legacy/Request/Request.js +++ /dev/null @@ -1,10 +0,0 @@ - -class Request { - constructor(urlVariables, parameters, command) { - this.urlVariables = urlVariables; - this.parameters = parameters; - this.command = command; - } -} - -module.exports = Request; diff --git a/legacy/Session/Session.js b/legacy/Session/Session.js deleted file mode 100644 index bf14b9b0..00000000 --- a/legacy/Session/Session.js +++ /dev/null @@ -1,551 +0,0 @@ -const uuidv1 = require('uuid/v1'); -const validator = require('validator'); -const os = require('os'); -const { Mutex } = require('async-mutex'); -const { VM } = require('vm2'); -const { JSDOM } = require('jsdom'); - -const Browser = require('../browser/browser.js'); -const WebElement = require('../WebElement/WebElement.js'); -const { COMMANDS } = require('../commands/commands'); - -// custom -const { addFileList } = require('../jsdom_extensions/addFileList'); -const utils = require('../utils/utils'); - -// DOM specific -const { Event, HTMLElement } = new JSDOM().window; - -// W3C -const ELEMENT = 'element-6066-11e4-a52e-4f735466cecf'; - -// errors -const { - InvalidArgument, - SessionNotCreated, - InternalServerError, - NoSuchElement, -} = require('../Error/errors'); - -const CapabilityValidator = require('../CapabilityValidator/CapabilityValidator'); - -class Session { - constructor(requestBody) { - this.id = uuidv1(); - this.pageLoadStrategy = 'normal'; - this.secureTLS = true; - this.timeouts = { - implicit: 0, - pageLoad: 30000, - script: 30000, - }; - this.configureSession(requestBody); - this.mutex = new Mutex(); - } - - // delegates request - async process({ command, parameters, urlVariables }) { - let response = null; - - return new Promise(async (resolve, reject) => { - try { - switch (command) { - case COMMANDS.DELETE_SESSION: - await this.browser.close(); - break; - case COMMANDS.NAVIGATE_TO: - await this.navigateTo(parameters); - break; - case COMMANDS.GET_CURRENT_URL: - response = this.browser.getURL(); - break; - case COMMANDS.GET_TITLE: - response = this.browser.getTitle(); - break; - case COMMANDS.FIND_ELEMENT: - case COMMANDS.FIND_ELEMENTS: - response = this.elementRetrieval( - this.browser.dom.window.document, // start node - parameters.using, // strategy - parameters.value, // selector - ); - break; - case COMMANDS.GET_ELEMENT_TEXT: - response = this.browser.getKnownElement(urlVariables.elementId).getText(); - break; - case COMMANDS.FIND_ELEMENTS_FROM_ELEMENT: - case COMMANDS.FIND_ELEMENT_FROM_ELEMENT: - response = this.elementRetrieval( - this.browser.getKnownElement(urlVariables.elementId).element, - parameters.using, - parameters.value, - ); - break; - case COMMANDS.SET_TIMEOUTS: - break; - case COMMANDS.GET_TIMEOUTS: - break; - case COMMANDS.GET_ALL_COOKIES: - response = this.browser.getCookies(); - break; - case COMMANDS.ADD_COOKIE: - response = this.browser.addCookie(parameters.cookie); - break; - case COMMANDS.GET_ELEMENT_TAG_NAME: - response = this.browser.getKnownElement(urlVariables.elementId).getTagName(); - break; - case COMMANDS.GET_ELEMENT_ATTRIBUTE: - response = this.browser - .getKnownElement(urlVariables.elementId) - .getElementAttribute(urlVariables.attributeName); - break; - case COMMANDS.EXECUTE_SCRIPT: - response = await this.executeScript(parameters.script, parameters.args); - break; - case COMMANDS.ELEMENT_SEND_KEYS: - await this.sendKeysToElement(parameters.text, urlVariables.elementId); - break; - default: - break; - } - resolve(response); - } catch (err) { - reject(err); - } - }); - } - - sendKeysToElement(text, elementId) { - return new Promise(async (resolve, reject) => { - const webElement = this.browser.getKnownElement(elementId); - const { element } = webElement; - let files = []; - - if (text === undefined) reject(new InvalidArgument()); - - if (!webElement.isInteractable() && element.getAttribute('contenteditable') !== 'true') { - reject(new InvalidArgument('Element is not interactable')); // TODO: create new error class - } - - if (this.browser.activeElement !== element) element.focus(); - - if (element.tagName.toLowerCase() === 'input') { - if (text.constructor.name.toLowerCase() !== 'string') reject(new InvalidArgument()); - // file input - if (element.getAttribute('type') === 'file') { - files = text.split('\n'); - if (files.length === 0) throw new InvalidArgument(); - if (!element.hasAttribute('multiple') && files.length !== 1) throw new InvalidArgument(); - - await Promise.all(files.map(file => utils.fileSystem.pathExists(file))); - - addFileList(element, files); - element.dispatchEvent(new Event('input')); - element.dispatchEvent(new Event('change')); - } else if ( - element.getAttribute('type') === 'text' - || element.getAttribute('type') === 'email' - ) { - element.value += text; - element.dispatchEvent(new Event('input')); - element.dispatchEvent(new Event('change')); - } else if (element.getAttribute('type') === 'color') { - if (!validator.isHexColor(text)) throw new InvalidArgument('not a hex colour'); - element.value = text; - } else { - if ( - !Object.prototype.hasOwnProperty.call(element, 'value') - || element.getAttribute('readonly') - ) throw new Error('element not interactable'); // TODO: create error class - // TODO: add check to see if element is mutable, reject with element not interactable - element.value = text; - } - element.dispatchEvent(new Event('input')); - element.dispatchEvent(new Event('change')); - resolve(null); - } else { - // TODO: text needs to be encoded before it is inserted into the element - // innerHTML, especially important since js code can be inserted in here and executed - element.innerHTML += text; - resolve(null); - } - }); - } - - async navigateTo({ url }) { - let pathType; - - try { - if (validator.isURL(url)) pathType = 'url'; - else if (await utils.fileSystem.pathExists(url)) pathType = 'file'; - else throw new InvalidArgument('NAVIGATE TO'); - } catch (e) { - throw new InvalidArgument('NAVIGATE TO'); - } - - // pageload timer - let timer; - const startTimer = () => { - timer = setTimeout(() => { - throw new Error('timeout'); // TODO: create timeout error class - }, this.timeouts.pageLoad); - }; - - if (this.browser.getURL() !== url) { - startTimer(); - await this.browser.navigateToURL(url, pathType); - clearTimeout(timer); - } - } - - // sets and validates the timeouts object - setTimeouts(timeouts) { - const capabilityValidator = new CapabilityValidator(); - let valid = true; - Object.keys(timeouts).forEach((key) => { - valid = capabilityValidator.validateTimeouts(key, timeouts[key]); - if (!valid) throw new InvalidArgument(); - }); - - Object.keys(timeouts).forEach((validTimeout) => { - this.timeouts[validTimeout] = timeouts[validTimeout]; - }); - } - - getTimeouts() { - return this.timeouts; - } - - // configures session properties - configureSession(requestedCapabilities) { - this.id = uuidv1(); - - // configure Session object capabilties - const configuredCapabilities = this.configureCapabilties(requestedCapabilities); - // extract browser specific data - const browserConfig = configuredCapabilities['plm:plumaOptions']; - if (Object.prototype.hasOwnProperty.call(configuredCapabilities, 'acceptInsecureCerts')) { - browserConfig.strictSSL = !configuredCapabilities.acceptInsecureCerts; - } - - if (Object.prototype.hasOwnProperty.call(configuredCapabilities, 'rejectPublicSuffixes')) { - browserConfig.rejectPublicSuffixes = configuredCapabilities.rejectPublicSuffixes; - } - - if (configuredCapabilities.unhandledPromptBehavior) { - browserConfig.unhandledPromptBehavior = configuredCapabilities.unhandledPromptBehavior; - } - - this.browser = new Browser(browserConfig); - } - - // configures session object capabilties - configureCapabilties(requestedCapabilities) { - const capabilities = Session.processCapabilities(requestedCapabilities); - if (capabilities === null) throw new InternalServerError('could not create session'); - - // configure pageLoadStrategy - this.pageLoadStrategy = 'normal'; - if ( - Object.prototype.hasOwnProperty.call(capabilities, 'pageLoadStrategy') - && typeof capabilities.pageLoadStrategy === 'string' - ) { - this.pageLoadStrategy = capabilities.pageLoadStrategy; - } else { - capabilities.pageLoadStrategy = 'normal'; - } - - if (Object.prototype.hasOwnProperty.call(capabilities, 'proxy')) { - // TODO: set JSDOM proxy address - } else { - capabilities.proxy = {}; - } - - if (Object.prototype.hasOwnProperty.call(capabilities, 'timeouts')) { - this.setTimeouts(capabilities.timeouts); - } - capabilities.timeouts = this.timeouts; - - return capabilities; - } - - // validates, merges and matches capabilties - static processCapabilities({ capabilities }) { - const command = 'POST /session'; - const capabilityValidator = new CapabilityValidator(); - - const defaultCapabilities = [ - 'acceptInsecureCerts', - 'browserName', - 'browserVersion', - 'platformName', - 'pageLoadStrategy', - 'proxy', - 'timeouts', - 'unhandledPromptBehaviour', - 'plm:plumaOptions', - ]; - - if ( - !capabilities - || capabilities.constructor !== Object - || Object.keys(capabilities).length === 0 - ) { - throw new InvalidArgument(command); - } - - // validate alwaysMatch capabilties - const requiredCapabilities = {}; - if (capabilities.alwaysMatch !== undefined) { - defaultCapabilities.forEach((key) => { - if (Object.prototype.hasOwnProperty.call(capabilities.alwaysMatch, key)) { - const validatedCapability = capabilityValidator.validate( - capabilities.alwaysMatch[key], - key, - ); - if (validatedCapability) requiredCapabilities[key] = capabilities.alwaysMatch[key]; - else { - throw new InvalidArgument(command); - } - } - }); - } - - // validate first match capabilities - let allMatchedCapabilities = capabilities.firstMatch; - if (allMatchedCapabilities === undefined) { - allMatchedCapabilities = [{}]; - } else if ( - allMatchedCapabilities.constructor.name.toLowerCase() !== 'array' - || allMatchedCapabilities.length === 0 - ) { - throw new InvalidArgument(command); - } - /** - * @param {Array[Capability]} validatedFirstMatchCapabilties contains - * a list of all the validated firstMatch capabilties requested by the client - */ - const validatedFirstMatchCapabilties = []; - - allMatchedCapabilities.forEach((indexedFirstMatchCapability) => { - const validatedFirstMatchCapability = {}; - Object.keys(indexedFirstMatchCapability).forEach((key) => { - const validatedCapability = capabilityValidator.validate( - indexedFirstMatchCapability[key], - key, - ); - if (validatedCapability) { - validatedFirstMatchCapability[key] = indexedFirstMatchCapability[key]; - } - }); - validatedFirstMatchCapabilties.push(validatedFirstMatchCapability); - }); - - // attempt merging capabilities - const mergedCapabilities = []; - - validatedFirstMatchCapabilties.forEach((firstMatch) => { - const merged = Session.mergeCapabilities(requiredCapabilities, firstMatch); - mergedCapabilities.push(merged); - }); - - let matchedCapabilities; - mergedCapabilities.forEach((capabilites) => { - matchedCapabilities = Session.matchCapabilities(capabilites); - if (matchedCapabilities === null) throw new SessionNotCreated('Capabilities could not be matched'); - }); - - return matchedCapabilities; - } - - // merges capabilities in both - static mergeCapabilities(primary, secondary) { - const result = {}; - Object.keys(primary).forEach((key) => { - result[key] = primary[key]; - }); - - if (secondary === undefined) return result; - - Object.keys(secondary).forEach((property) => { - if (Object.prototype.hasOwnProperty.call(primary, property)) { - throw new InvalidArgument('POST /session'); - } - result[property] = secondary[property]; - }); - - return result; - } - - // matches supported capabilities - static matchCapabilities(capabilties) { - const matchedCapabilities = { - browserName: 'pluma', - browserVersion: 'v1.0', - platformName: os.platform(), - acceptInsecureCerts: false, - setWindowRect: false, - }; - - // TODO: add extension capabilities here in the future - let flag = true; - Object.keys(capabilties).forEach((property) => { - switch (property) { - case 'browserName': - case 'platformName': - if (capabilties[property] !== matchedCapabilities[property]) flag = false; - break; - case 'browserVersion': - // TODO: change to comparison algorith once more versions are released - if (capabilties[property] !== matchedCapabilities[property]) flag = false; - break; - case 'setWindowRect': - if (capabilties[property]) throw new InvalidArgument('POST /session'); - break; - // TODO: add proxy matching in the future - default: - break; - } - if (flag) matchedCapabilities[property] = capabilties[property]; - }); - - if (flag) return matchedCapabilities; - - return null; - } - - elementRetrieval(startNode, strategy, selector) { - // TODO: check if element is connected (shadow-root) https://dom.spec.whatwg.org/#connected - // check W3C endpoint spec for details - const endTime = new Date(new Date().getTime + this.timeouts.implicit); - let elements; - const result = []; - - if (!strategy || !selector) throw new InvalidArgument(); - if (!startNode) throw new NoSuchElement(); - - const locationStrategies = { - cssSelector() { - return startNode.querySelectorAll(selector); - }, - linkTextSelector(partial = false) { - const linkElements = startNode.querySelectorAll('a'); - const strategyResult = []; - - linkElements.forEach((element) => { - const renderedText = element.innerHTML; - if (!partial && renderedText.trim() === selector) strategyResult.push(element); - else if (partial && renderedText.includes(selector)) strategyResult.push(element); - }); - return result; - }, - tagName() { - return startNode.getElementsByTagName(selector); - }, - XPathSelector(document) { - const evaluateResult = document.evaluate(selector, startNode, null, 7); - const length = evaluateResult.snapshotLength; - const xPathResult = []; // according to W3C this should be a NodeList - for (let i = 0; i < length; i++) { - const node = evaluateResult.snapshotItem(i); - xPathResult.push(node); - } - return xPathResult; - }, - }; - - do { - try { - switch (strategy) { - case 'css selector': - elements = locationStrategies.cssSelector(); - break; - case 'link text': - elements = locationStrategies.linkTextSelector(); - break; - case 'partial link text': - elements = locationStrategies.linkTextSelector(true); - break; - case 'tag name': - elements = locationStrategies.tagName(); - break; - case 'xpath': - elements = locationStrategies.XPathSelector(this.browser.dom.window.document); - break; - default: - throw new InvalidArgument(); - } - } catch (error) { - // if ( - // error instanceof DOMException - // || error instanceof SyntaxError - // || error instanceof XPathException - // ) throw new Error('invalid selector'); - // // TODO: add invalidSelector error class - // else throw new UnknownError(); // TODO: add unknown error class - console.log(error); - } - } while (endTime > new Date() && elements.length < 1); - - elements.forEach((element) => { - const foundElement = new WebElement(element); - result.push(foundElement); - this.browser.knownElements.push(foundElement); - }); - return result; - } - - executeScript(script, args) { - const argumentList = []; - - args.forEach((arg) => { - if (arg[ELEMENT] !== undefined && arg[ELEMENT] !== null) { - const element = this.browser.getKnownElement(arg[ELEMENT]); - argumentList.push(element.element); - } else { - argumentList.push(arg); - } - }); - - // eslint-disable-next-line no-new-func - const scriptFunc = new Function('arguments', script); - - const vm = new VM({ - timeout: this.timeouts.script, - sandbox: { - window: this.browser.dom.window, - document: this.browser.dom.window.document, - func: scriptFunc, - arguments: argumentList, - }, - }); - let returned; - let response; - return new Promise((resolve, reject) => { - try { - console.log('ABOUT TO EXECUTE SCRIPT'); - returned = vm.run('func(arguments);'); - - if (returned instanceof Array) { - response = []; - returned.forEach((value) => { - if (value instanceof HTMLElement) { - const element = new WebElement(value); - this.browser.knownElements.push(element); - response.push(element); - } else response.push(value); - }); - } else if (returned instanceof HTMLElement) { - const element = new WebElement(returned); - this.browser.knownElements.push(element); - response = element; - } else response = returned; - resolve(response); - } catch (err) { - reject(err); - } - }); - } -} - -module.exports = Session; diff --git a/legacy/SessionsManager/SessionsManager.js b/legacy/SessionsManager/SessionsManager.js deleted file mode 100644 index 202284b2..00000000 --- a/legacy/SessionsManager/SessionsManager.js +++ /dev/null @@ -1,72 +0,0 @@ - -const os = require('os'); -const Session = require('../Session/Session'); -const { - NotFoundError, -} = require('../Error/errors'); - -class SessionsManager { - constructor() { - this.sessions = []; - this.readinessState = { - status: this.sessions.length, - value: { - message: 'PlumaDriver is ready for new sessions', - os: { - arch: os.arch(), - name: os.platform(), - version: os.release(), - }, - ready: true, - }, - }; - } - - createSession(requestBody) { - const session = new Session(requestBody); - this.sessions.push(session); - const sessionConfig = { - value: { - sessionId: session.id, - capabilities: { - browserName: 'pluma', - browserVersion: 'v1.0', - platformName: os.platform(), - acceptInsecureCerts: session.secureTLS, - setWindowRect: false, - pageLoadStrategy: session.pageLoadStrategy, - 'plm:plumaOptions': { - runScripts: session.browser.options.runScripts, - }, - unhandledPromtBehaviour: session.browser.unhandledPromtBehaviour, - proxy: session.proxy ? session.proxy : {}, - timeouts: session.timeouts, - }, - }, - }; - return sessionConfig; - } - - - findSession(sessionId) { - const foundSession = this.sessions.find(session => session.id === sessionId); - if (!foundSession) { - throw new NotFoundError(`Session ${sessionId} not found`); - } else { - return foundSession; - } - } - - async deleteSession(currentSession, request) { - const index = this.sessions.map(session => session.id).indexOf(currentSession.id); - await currentSession.process(request); - this.sessions.splice(index, 1); - } - - getReadinessState() { - this.readinessState.status = this.sessions.length; - return this.readinessState; - } -} - -exports.SessionsManager = SessionsManager; diff --git a/legacy/WebElement/WebElement.js b/legacy/WebElement/WebElement.js deleted file mode 100644 index 17927d9c..00000000 --- a/legacy/WebElement/WebElement.js +++ /dev/null @@ -1,83 +0,0 @@ -const uuidv1 = require('uuid/v1'); - -const { - isFocusableAreaElement, -} = require('../../node_modules/jsdom/lib/jsdom/living/helpers/focusing.js'); -const jsdomUtils = require('../../node_modules/jsdom/lib/jsdom/living/generated/utils.js'); - -const ELEMENT = 'element-6066-11e4-a52e-4f735466cecf'; -class WebElement { - constructor(element) { - Object.defineProperties(this, { - element: { - value: element, - writable: false, - enumerable: true, - }, - [ELEMENT]: { - value: uuidv1(), - writable: false, - enumerable: true, - }, - }); - } - - isInteractable() { - return isFocusableAreaElement(this.element[jsdomUtils.implSymbol]); - } - - getText() { - return this.element.textContent; - } - - getTagName() { - return this.element.tagName; - } - - getElementAttribute(name) { - const booleanAtrtibutes = [ - 'async', - 'autocomplete', - 'autofocus', - 'autoplay', - 'border', - 'challenge', - 'checked', - 'compact', - 'contenteditable', - 'controls', - 'default', - 'defer', - 'disabled', - 'formNoValidate', - 'frameborder', - 'hidden', - 'indeterminate', - 'ismap', - 'loop', - 'multiple', - 'muted', - 'nohref', - 'noresize', - 'noshade', - 'novalidate', - 'nowrap', - 'open', - 'readonly', - 'required', - 'reversed', - 'scoped', - 'scrolling', - 'seamless', - 'selected', - 'sortable', - 'spellcheck', - 'translate', - ]; - - if (booleanAtrtibutes.includes(name)) return this.element.hasAttribute(name).toString(); - return this.element.getAttribute(name); - } -} - -module.exports = WebElement; diff --git a/legacy/browser/browser.js b/legacy/browser/browser.js deleted file mode 100644 index 20acea08..00000000 --- a/legacy/browser/browser.js +++ /dev/null @@ -1,275 +0,0 @@ -const { JSDOM, ResourceLoader } = require('jsdom'); -const tough = require('../jsdom_extensions/tough-cookie/lib/cookie'); - -const { Cookie, CookieJar } = tough; - -// identifies a web element -const ELEMENT = 'element-6066-11e4-a52e-4f735466cecf'; - -const { InvalidArgument, NoSuchElement } = require('../Error/errors'); - -class Browser { - constructor(capabilties) { - this.options = Browser.configureJSDOMOptions(capabilties); - this.configureBrowser(this.options); - this.knownElements = []; - } - - // creates JSDOM object from provided options and (optional) url - async configureBrowser(options, url = null, pathType = 'url') { - let dom; - if (url !== null) { - if (pathType === 'url') { - dom = await JSDOM.fromURL(url, { - resources: options.resources, - runScripts: options.runScripts, - beforeParse: options.beforeParse, - pretendToBeVisual: true, - cookieJar: options.cookieJar, - }); - } else if (pathType === 'file') { - dom = await JSDOM.fromFile(url, { - resources: options.resources, - runScripts: options.runScripts, - beforeParse: options.beforeParse, - pretendToBeVisual: true, - cookieJar: options.cookieJar, - }); - } - - /* promise resolves after load event has fired. Allows onload events to execute - before the DOM object can be manipulated */ - const loadEvent = () => new Promise((resolve) => { - dom.window.addEventListener('load', () => { - resolve(dom); - }); - }); - - this.dom = await loadEvent(); - } else { - this.dom = await new JSDOM(' ', { - resources: options.resources, - runScripts: options.runScripts, - beforeParse: options.beforeParse, - pretendToBeVisual: true, - cookieJar: options.cookieJar, - }); - } - - // webdriver-active property (W3C) - this.dom.window.navigator.webdriver = true; - this.activeElement = this.dom.window.document.activeElement; - } - - static configureJSDOMOptions(capabilities) { - // TODO: configure proxy options if provided - const options = { - runScripts: capabilities.runScripts ? 'dangerously' : null, - unhandledPromptBehavior: capabilities.unhandledPromptBehavior - ? capabilities.unhandledPromptBehavior - : 'dismiss and notify', - strictSSL: typeof capabilities.strictSSL === 'boolean' ? capabilities.strictSSL : true, - }; - const resourceLoader = new ResourceLoader({ - strictSSL: options.strictSSL, - proxy: '', - }); - - const jar = new CookieJar(new tough.MemoryCookieStore(), { - looseMode: true, - rejectPublicSuffixes: typeof capabilities.rejectPublicSuffixes === 'boolean' ? capabilities.rejectPublicSuffixes : true, - }); - - const JSDOMOptions = { - resources: resourceLoader, - includeNodeLocations: true, - contentType: 'text/html', - cookieJar: jar, - }; - - if (options.runScripts !== null) JSDOMOptions.runScripts = options.runScripts; - - function beforeParseFactory(callback) { - return (window) => { - window.confirm = callback; - window.alert = callback; - window.prompt = callback; - }; - } - - let beforeParse; - if (options.unhandledPromptBehavior && options.runScripts) { - switch (options.unhandledPromptBehavior) { - case 'accept': - beforeParse = beforeParseFactory(() => true); - break; - case 'dismiss': - beforeParse = beforeParseFactory(() => false); - break; - case 'dismiss and notify': - beforeParse = beforeParseFactory((message) => { - console.log(message); - return false; - }); - break; - case 'accept and notify': - beforeParse = beforeParseFactory((message) => { - console.log(message); - return true; - }); - break; - case 'ignore': - break; - default: - break; - } - } - if (beforeParse) JSDOMOptions.beforeParse = beforeParse; - return JSDOMOptions; - } - - async navigateToURL(URL, pathType) { - if (URL) { - await this.configureBrowser(this.options, URL, pathType); - } - return true; - } - - getTitle() { - return this.dom.window.document.title; - } - - getURL() { - return this.dom.window.document.URL; - } - - addCookie(cookie) { - // object validates cookie properties - const validateCookie = { - name(name) { - return name !== null && name !== undefined; - }, - value(cookieValue) { - return this.name(cookieValue); - }, - domain(cookieDomain, currentURL) { - // strip current URL of path and protocol - let currentDomain = new URL(currentURL).hostname; - - // strip currentDomain of subdomains - const www = /^www\./; - - // remove leading www - if (currentDomain.search(www) > -1) currentDomain = currentDomain.replace(www, ''); - - if (currentDomain === cookieDomain) return true; // replace with success - - if (cookieDomain.indexOf('.') === 0) { - // begins with '.' - let cookieDomainRegEx = cookieDomain.substring(1).replace(/\./, '\\.'); - cookieDomainRegEx = new RegExp(`${cookieDomainRegEx}$`); - - if (currentDomain.search(cookieDomainRegEx) > -1) return true; - - const cleanCookieDomain = cookieDomain.substring(1); - if (cleanCookieDomain === currentDomain) return true; - - return false; - } - return false; - }, - secure(value) { - return typeof value === 'boolean'; - }, - httpOnly(httpOnly) { - return this.secure(httpOnly); - }, - expiry(expiry) { - return Number.isInteger(expiry); - }, - }; - - // check for null or undefined - if (cookie === null || cookie === undefined) throw new InvalidArgument(); - - // assert cookie has name and value properties - if ( - !Object.prototype.hasOwnProperty.call(cookie, 'name') - || !Object.prototype.hasOwnProperty.call(cookie, 'value') - ) throw new InvalidArgument(); - - // get the scheme of the provided cookie - const scheme = this.getURL().substr(0, this.getURL().indexOf(':')); - - // validate extracted scheme - if (scheme !== 'http' && scheme !== 'https' && scheme !== 'ftp') throw new InvalidArgument(); - - // validates cookie - Object.keys(validateCookie).forEach((key) => { - if (Object.prototype.hasOwnProperty.call(cookie, key)) { - if (key === 'domain') { - if (!validateCookie[key](cookie[key], this.getURL())) throw new InvalidArgument('ADD COOKIE'); - } else if (!validateCookie[key](cookie[key])) throw new InvalidArgument('ADD COOKIE'); - } - }); - - const validCookie = {}; - - // stores validated cookie properties in validCookie - Object.keys(cookie).forEach((key) => { - if (key === 'name') validCookie.key = cookie[key]; - else if (key === 'expiry') validCookie.expires = cookie[key]; - else validCookie[key] = cookie[key]; - }); - - // create tough cookie and store in jsdom cookie jar - try { - this.dom.cookieJar.store.putCookie(new Cookie(validCookie), err => err); - } catch (err) { - throw new Error('UNABLE TO SET COOKIE'); // need to create this error class - } - return null; - } - - // returns the cookies inside the jsdom object - getCookies() { - const cookies = []; - - this.dom.cookieJar.serialize((err, serializedJar) => { - if (err) throw err; - serializedJar.cookies.forEach((cookie) => { - const currentCookie = {}; - Object.keys(cookie).forEach((key) => { - // renames 'key' property to 'name' for W3C compliance and selenium functionality - if (key === 'key') currentCookie.name = cookie[key]; - else if (key === 'expires') { - // sets the expiry time in seconds form epoch time - // renames property for selenium functionality - const seconds = new Date(currentCookie[key]).getTime() / 1000; - currentCookie.expiry = seconds; - } else currentCookie[key] = cookie[key]; - }); - cookies.push(currentCookie); - }); - }); - - return cookies; - } - - // finds a known element in the known element list, throws no such error if element not found - getKnownElement(id) { - let foundElement = null; - this.knownElements.forEach((element) => { - if (element[ELEMENT] === id) foundElement = element; - }); - if (!foundElement) throw new NoSuchElement(); - return foundElement; - } - - // calls the jsdom close method terminating all timers created within jsdom scripts - close() { - this.dom.window.close(); - } -} - -module.exports = Browser; diff --git a/legacy/commands/commands.js b/legacy/commands/commands.js deleted file mode 100644 index f73a7de1..00000000 --- a/legacy/commands/commands.js +++ /dev/null @@ -1,21 +0,0 @@ -const COMMANDS = { - DELETE_SESSION: 'DELETE SESSION', - GET_TIMEOUTS: 'GET TIMEOUTS', - SET_TIMEOUTS: 'SET TIMEOUTS', - NAVIGATE_TO: 'NAVIGATE TO', - GET_TITLE: 'GET TITLE', - FIND_ELEMENT: 'FIND ELEMENT', - FIND_ELEMENTS: 'FIND ELEMENTS', - FIND_ELEMENT_FROM_ELEMENT: ' FIND ELEMENT FROM ELEMENT', - FIND_ELEMENTS_FROM_ELEMENT: 'FIND ELEMENTS FROM ELEMENTS', - GET_ELEMENT_TEXT: 'GET ELEMENT TEXT', - GET_CURRENT_URL: 'GET CURRENT URL', - GET_ALL_COOKIES: 'GET ALL COOKIES', - ADD_COOKIE: 'ADD COOKIE', - GET_ELEMENT_TAG_NAME: 'GET ELEMENT TAG NAME', - GET_ELEMENT_ATTRIBUTE: 'GET ELEMENT ATTRIBUTE', - EXECUTE_SCRIPT: 'EXECUTE SCRIPT', - ELEMENT_SEND_KEYS: 'ELEMENT SEND KEYS', -}; - -module.exports = { COMMANDS }; diff --git a/legacy/jsdom_extensions/addFileList.js b/legacy/jsdom_extensions/addFileList.js deleted file mode 100644 index 74b8c504..00000000 --- a/legacy/jsdom_extensions/addFileList.js +++ /dev/null @@ -1,44 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const mime = require('mime-types'); - -const { JSDOM } = require('jsdom'); - -const { File, FileList } = new JSDOM().window; - -const createFile = async (filePath) => { - const { mtimeMs: lastModified } = fs.statSync(filePath); - - const file = await new Promise((resolve, reject) => { - let f = null; - f = new File([fs.readFile(filePath)], path.basename(filePath), { - lastModified, - type: mime.lookup(filePath) || '', - }); - - if (f) resolve(f); - }); - return file; -}; - -function addFileList(input, filePaths) { - if (typeof filePaths === 'string') filePaths = [filePaths]; - else if (!Array.isArray(filePaths)) { - throw new Error('filePaths needs to be a file path string or an Array of file path strings'); - } - - const fileList = filePaths.map(fp => createFile(fp)); - fileList.__proto__ = Object.create(FileList.prototype); - - Object.defineProperty(input, 'files', { - value: fileList, - writable: false, - }); - - return input; -} - -module.exports = { - addFileList, - createFile, -}; diff --git a/legacy/jsdom_extensions/tough-cookie/LICENSE b/legacy/jsdom_extensions/tough-cookie/LICENSE deleted file mode 100644 index 22204e87..00000000 --- a/legacy/jsdom_extensions/tough-cookie/LICENSE +++ /dev/null @@ -1,12 +0,0 @@ -Copyright (c) 2015, Salesforce.com, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/legacy/jsdom_extensions/tough-cookie/README.md b/legacy/jsdom_extensions/tough-cookie/README.md deleted file mode 100644 index d28bd460..00000000 --- a/legacy/jsdom_extensions/tough-cookie/README.md +++ /dev/null @@ -1,507 +0,0 @@ -[RFC6265](https://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js - -[![npm package](https://nodei.co/npm/tough-cookie.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/tough-cookie/) - -[![Build Status](https://travis-ci.org/salesforce/tough-cookie.png?branch=master)](https://travis-ci.org/salesforce/tough-cookie) - -# Synopsis - -``` javascript -var tough = require('tough-cookie'); -var Cookie = tough.Cookie; -var cookie = Cookie.parse(header); -cookie.value = 'somethingdifferent'; -header = cookie.toString(); - -var cookiejar = new tough.CookieJar(); -cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb); -// ... -cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) { - res.headers['cookie'] = cookies.join('; '); -}); -``` - -# Installation - -It's _so_ easy! - -`npm install tough-cookie` - -Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken. - -## Version Support - -Support for versions of node.js will follow that of the [request](https://www.npmjs.com/package/request) module. - -# API - -## tough - -Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound". - -**Note**: prior to 1.0.x, several of these functions took a `strict` parameter. This has since been removed from the API as it was no longer necessary. - -### `parseDate(string)` - -Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`. - -### `formatDate(date)` - -Format a Date into a RFC1123 string (the RFC6265-recommended format). - -### `canonicalDomain(str)` - -Transforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects). - -### `domainMatch(str,domStr[,canonicalize=true])` - -Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". - -The `canonicalize` parameter will run the other two parameters through `canonicalDomain` or not. - -### `defaultPath(path)` - -Given a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC. - -The `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output. - -### `pathMatch(reqPath,cookiePath)` - -Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean. - -This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`. - -### `parse(cookieString[, options])` - -alias for `Cookie.parse(cookieString[, options])` - -### `fromJSON(string)` - -alias for `Cookie.fromJSON(string)` - -### `getPublicSuffix(hostname)` - -Returns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it. - -For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`. - -For further information, see http://publicsuffix.org/. This module derives its list from that site. This call is currently a wrapper around [`psl`](https://www.npmjs.com/package/psl)'s [get() method](https://www.npmjs.com/package/psl#pslgetdomain). - -### `cookieCompare(a,b)` - -For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). The sort algorithm is, in order of precedence: - -* Longest `.path` -* oldest `.creation` (which has a 1ms precision, same as `Date`) -* lowest `.creationIndex` (to get beyond the 1ms precision) - -``` javascript -var cookies = [ /* unsorted array of Cookie objects */ ]; -cookies = cookies.sort(cookieCompare); -``` - -**Note**: Since JavaScript's `Date` is limited to a 1ms precision, cookies within the same milisecond are entirely possible. This is especially true when using the `now` option to `.setCookie()`. The `.creationIndex` property is a per-process global counter, assigned during construction with `new Cookie()`. This preserves the spirit of the RFC sorting: older cookies go first. This works great for `MemoryCookieStore`, since `Set-Cookie` headers are parsed in order, but may not be so great for distributed systems. Sophisticated `Store`s may wish to set this to some other _logical clock_ such that if cookies A and B are created in the same millisecond, but cookie A is created before cookie B, then `A.creationIndex < B.creationIndex`. If you want to alter the global counter, which you probably _shouldn't_ do, it's stored in `Cookie.cookiesCreated`. - -### `permuteDomain(domain)` - -Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores. - -### `permutePath(path)` - -Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores. - - -## Cookie - -Exported via `tough.Cookie`. - -### `Cookie.parse(cookieString[, options])` - -Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed. - -The options parameter is not required and currently has only one property: - - * _loose_ - boolean - if `true` enable parsing of key-less cookies like `=abc` and `=`, which are not RFC-compliant. - -If options is not an object, it is ignored, which means you can use `Array#map` with it. - -Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response: - -``` javascript -if (res.headers['set-cookie'] instanceof Array) - cookies = res.headers['set-cookie'].map(Cookie.parse); -else - cookies = [Cookie.parse(res.headers['set-cookie'])]; -``` - -_Note:_ in version 2.3.3, tough-cookie limited the number of spaces before the `=` to 256 characters. This limitation has since been removed. -See [Issue 92](https://github.com/salesforce/tough-cookie/issues/92) - -### Properties - -Cookie object properties: - - * _key_ - string - the name or key of the cookie (default "") - * _value_ - string - the value of the cookie (default "") - * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()` - * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()` - * _domain_ - string - the `Domain=` attribute of the cookie - * _path_ - string - the `Path=` of the cookie - * _secure_ - boolean - the `Secure` cookie flag - * _httpOnly_ - boolean - the `HttpOnly` cookie flag - * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside) - * _creation_ - `Date` - when this cookie was constructed - * _creationIndex_ - number - set at construction, used to provide greater sort precision (please see `cookieCompare(a,b)` for a full explanation) - -After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes: - - * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied) - * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one. - * _creation_ - `Date` - **modified** from construction to when the cookie was added to the jar - * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute. - -### `Cookie([{properties}])` - -Receives an options object that can contain any of the above Cookie properties, uses the default for unspecified properties. - -### `.toString()` - -encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`. - -### `.cookieString()` - -encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '='). - -### `.setExpires(String)` - -sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `"Infinity"` (a string) is set. - -### `.setMaxAge(number)` - -sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly. - -### `.expiryTime([now=Date.now()])` - -### `.expiryDate([now=Date.now()])` - -expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds. - -Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` parameter -- is used to offset the `.maxAge` attribute. - -If Expires (`.expires`) is set, that's returned. - -Otherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents). - -### `.TTL([now=Date.now()])` - -compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply. - -The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned. - -### `.canonicalizedDoman()` - -### `.cdomain()` - -return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters. - -### `.toJSON()` - -For convenience in using `JSON.serialize(cookie)`. Returns a plain-old `Object` that can be JSON-serialized. - -Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are exported in ISO format (`.toISOString()`). - -**NOTE**: Custom `Cookie` properties will be discarded. In tough-cookie 1.x, since there was no `.toJSON` method explicitly defined, all enumerable properties were captured. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. - -### `Cookie.fromJSON(strOrObj)` - -Does the reverse of `cookie.toJSON()`. If passed a string, will `JSON.parse()` that first. - -Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are parsed via `Date.parse()`, not the tough-cookie `parseDate`, since it's JavaScript/JSON-y timestamps being handled at this layer. - -Returns `null` upon JSON parsing error. - -### `.clone()` - -Does a deep clone of this cookie, exactly implemented as `Cookie.fromJSON(cookie.toJSON())`. - -### `.validate()` - -Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive. - -validates cookie attributes for semantic correctness. Useful for "lint" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string -- you can future-proof with this construct: - -``` javascript -if (cookie.validate() === true) { - // it's tasty -} else { - // yuck! -} -``` - - -## CookieJar - -Exported via `tough.CookieJar`. - -### `CookieJar([store],[options])` - -Simply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used. - -The `options` object can be omitted and can have the following properties: - - * _rejectPublicSuffixes_ - boolean - default `true` - reject cookies with domains like "com" and "co.uk" - * _looseMode_ - boolean - default `false` - accept malformed cookies like `bar` and `=bar`, which have an implied empty name. - This is not in the standard, but is used sometimes on the web and is accepted by (most) browsers. - -Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods. - -### `.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))` - -Attempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.creation`, `.lastAccessed` and `.hostOnly` properties. - -The `options` object can be omitted and can have the following properties: - - * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. - * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. - * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies - * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. `Store` errors aren't ignored by this option. - -As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual). - -### `.setCookieSync(cookieOrString, currentUrl, [{options}])` - -Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). - -### `.getCookies(currentUrl, [{options},] cb(err,cookies))` - -Retrieve the list of cookies that can be sent in a Cookie header for the current url. - -If an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given. - -The `options` object can be omitted and can have the following properties: - - * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. - * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. - * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies - * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially). - * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the underlying store (the default `MemoryCookieStore` supports it). - -The `.lastAccessed` property of the returned cookies will have been updated. - -### `.getCookiesSync(currentUrl, [{options}])` - -Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). - -### `.getCookieString(...)` - -Accepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`. - -### `.getCookieStringSync(...)` - -Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). - -### `.getSetCookieStrings(...)` - -Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`. - -### `.getSetCookieStringsSync(...)` - -Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). - -### `.serialize(cb(err,serializedObject))` - -Serialize the Jar if the underlying store supports `.getAllCookies`. - -**NOTE**: Custom `Cookie` properties will be discarded. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. - -See [Serialization Format]. - -### `.serializeSync()` - -Sync version of .serialize - -### `.toJSON()` - -Alias of .serializeSync() for the convenience of `JSON.stringify(cookiejar)`. - -### `CookieJar.deserialize(serialized, [store], cb(err,object))` - -A new Jar is created and the serialized Cookies are added to the underlying store. Each `Cookie` is added via `store.putCookie` in the order in which they appear in the serialization. - -The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. - -As a convenience, if `serialized` is a string, it is passed through `JSON.parse` first. If that throws an error, this is passed to the callback. - -### `CookieJar.deserializeSync(serialized, [store])` - -Sync version of `.deserialize`. _Note_ that the `store` must be synchronous for this to work. - -### `CookieJar.fromJSON(string)` - -Alias of `.deserializeSync` to provide consistency with `Cookie.fromJSON()`. - -### `.clone([store,]cb(err,newJar))` - -Produces a deep clone of this jar. Modifications to the original won't affect the clone, and vice versa. - -The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. Transferring between store types is supported so long as the source implements `.getAllCookies()` and the destination implements `.putCookie()`. - -### `.cloneSync([store])` - -Synchronous version of `.clone`, returning a new `CookieJar` instance. - -The `store` argument is optional, but must be a _synchronous_ `Store` instance if specified. If not passed, a new instance of `MemoryCookieStore` is used. - -The _source_ and _destination_ must both be synchronous `Store`s. If one or both stores are asynchronous, use `.clone` instead. Recall that `MemoryCookieStore` supports both synchronous and asynchronous API calls. - -## Store - -Base class for CookieJar stores. Available as `tough.Store`. - -## Store API - -The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores. - -Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. - -Stores are asynchronous by default, but if `store.synchronous` is set to `true`, then the `*Sync` methods on the of the containing `CookieJar` can be used (however, the continuation-passing style - -All `domain` parameters will have been normalized before calling. - -The Cookie store must have all of the following methods. - -### `store.findCookie(domain, path, key, cb(err,cookie))` - -Retrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned. - -Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error). - -### `store.findCookies(domain, path, cb(err,cookies))` - -Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above. - -If no cookies are found, the callback MUST be passed an empty array. - -The resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done. - -As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only). - -### `store.putCookie(cookie, cb(err))` - -Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur. - -The `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties. - -Pass an error if the cookie cannot be stored. - -### `store.updateCookie(oldCookie, newCookie, cb(err))` - -Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store. - -The `.lastAccessed` property will always be different between the two objects (to the precision possible via JavaScript's clock). Both `.creation` and `.creationIndex` are guaranteed to be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are selected for automatic deletion (e.g., least-recently-used, which is up to the store to implement). - -Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object. - -The `newCookie` and `oldCookie` objects MUST NOT be modified. - -Pass an error if the newCookie cannot be stored. - -### `store.removeCookie(domain, path, key, cb(err))` - -Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint). - -The implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie. - -### `store.removeCookies(domain, path, cb(err))` - -Removes matching cookies from the store. The `path` parameter is optional, and if missing means all paths in a domain should be removed. - -Pass an error ONLY if removing any existing cookies failed. - -### `store.getAllCookies(cb(err, cookies))` - -Produces an `Array` of all cookies during `jar.serialize()`. The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format] data structure. - -Cookies SHOULD be returned in creation order to preserve sorting via `compareCookies()`. For reference, `MemoryCookieStore` will sort by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1ms. See `compareCookies` for more detail. - -Pass an error if retrieval fails. - -## MemoryCookieStore - -Inherits from `Store`. - -A just-in-memory CookieJar synchronous store implementation, used by default. Despite being a synchronous implementation, it's usable with both the synchronous and asynchronous forms of the `CookieJar` API. - -## Community Cookie Stores - -These are some Store implementations authored and maintained by the community. They aren't official and we don't vouch for them but you may be interested to have a look: - -- [`db-cookie-store`](https://github.com/JSBizon/db-cookie-store): SQL including SQLite-based databases -- [`file-cookie-store`](https://github.com/JSBizon/file-cookie-store): Netscape cookie file format on disk -- [`redis-cookie-store`](https://github.com/benkroeger/redis-cookie-store): Redis -- [`tough-cookie-filestore`](https://github.com/mitsuru/tough-cookie-filestore): JSON on disk -- [`tough-cookie-web-storage-store`](https://github.com/exponentjs/tough-cookie-web-storage-store): DOM localStorage and sessionStorage - - -# Serialization Format - -**NOTE**: if you want to have custom `Cookie` properties serialized, add the property name to `Cookie.serializableProperties`. - -```js - { - // The version of tough-cookie that serialized this jar. - version: 'tough-cookie@1.x.y', - - // add the store type, to make humans happy: - storeType: 'MemoryCookieStore', - - // CookieJar configuration: - rejectPublicSuffixes: true, - // ... future items go here - - // Gets filled from jar.store.getAllCookies(): - cookies: [ - { - key: 'string', - value: 'string', - // ... - /* other Cookie.serializableProperties go here */ - } - ] - } -``` - -# Copyright and License - -(tl;dr: BSD-3-Clause with some MPL/2.0) - -```text - Copyright (c) 2015, Salesforce.com, Inc. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. Neither the name of Salesforce.com nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. -``` diff --git a/legacy/jsdom_extensions/tough-cookie/lib/cookie.js b/legacy/jsdom_extensions/tough-cookie/lib/cookie.js deleted file mode 100644 index b512b271..00000000 --- a/legacy/jsdom_extensions/tough-cookie/lib/cookie.js +++ /dev/null @@ -1,1432 +0,0 @@ -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -'use strict'; -var net = require('net'); -var urlParse = require('url').parse; -var util = require('util'); -var pubsuffix = require('./pubsuffix-psl'); -var Store = require('./store').Store; -var MemoryCookieStore = require('./memstore').MemoryCookieStore; -var pathMatch = require('./pathMatch').pathMatch; -var VERSION = require('../package.json').version; - -var punycode; -try { - punycode = require('punycode'); -} catch(e) { - console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization"); -} - -// From RFC6265 S4.1.1 -// note that it excludes \x3B ";" -var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; - -var CONTROL_CHARS = /[\x00-\x1F]/; - -// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in -// the "relaxed" mode, see: -// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 -var TERMINATORS = ['\n', '\r', '\0']; - -// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' -// Note ';' is \x3B -var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; - -// date-time parsing constants (RFC6265 S5.1.1) - -var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; - -var MONTH_TO_NUM = { - jan:0, feb:1, mar:2, apr:3, may:4, jun:5, - jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 -}; -var NUM_TO_MONTH = [ - 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' -]; -var NUM_TO_DAY = [ - 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' -]; - -var MAX_TIME = 2147483647000; // 31-bit max -var MIN_TIME = 0; // 31-bit min - -/* - * Parses a Natural number (i.e., non-negative integer) with either the - * *DIGIT ( non-digit *OCTET ) - * or - * *DIGIT - * grammar (RFC6265 S5.1.1). - * - * The "trailingOK" boolean controls if the grammar accepts a - * "( non-digit *OCTET )" trailer. - */ -function parseDigits(token, minDigits, maxDigits, trailingOK) { - var count = 0; - while (count < token.length) { - var c = token.charCodeAt(count); - // "non-digit = %x00-2F / %x3A-FF" - if (c <= 0x2F || c >= 0x3A) { - break; - } - count++; - } - - // constrain to a minimum and maximum number of digits. - if (count < minDigits || count > maxDigits) { - return null; - } - - if (!trailingOK && count != token.length) { - return null; - } - - return parseInt(token.substr(0,count), 10); -} - -function parseTime(token) { - var parts = token.split(':'); - var result = [0,0,0]; - - /* RF6256 S5.1.1: - * time = hms-time ( non-digit *OCTET ) - * hms-time = time-field ":" time-field ":" time-field - * time-field = 1*2DIGIT - */ - - if (parts.length !== 3) { - return null; - } - - for (var i = 0; i < 3; i++) { - // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be - // followed by "( non-digit *OCTET )" so therefore the last time-field can - // have a trailer - var trailingOK = (i == 2); - var num = parseDigits(parts[i], 1, 2, trailingOK); - if (num === null) { - return null; - } - result[i] = num; - } - - return result; -} - -function parseMonth(token) { - token = String(token).substr(0,3).toLowerCase(); - var num = MONTH_TO_NUM[token]; - return num >= 0 ? num : null; -} - -/* - * RFC6265 S5.1.1 date parser (see RFC for full grammar) - */ -function parseDate(str) { - if (!str) { - return; - } - - /* RFC6265 S5.1.1: - * 2. Process each date-token sequentially in the order the date-tokens - * appear in the cookie-date - */ - var tokens = str.split(DATE_DELIM); - if (!tokens) { - return; - } - - var hour = null; - var minute = null; - var second = null; - var dayOfMonth = null; - var month = null; - var year = null; - - for (var i=0; i= 70 && year <= 99) { - year += 1900; - } else if (year >= 0 && year <= 69) { - year += 2000; - } - } - } - } - - /* RFC 6265 S5.1.1 - * "5. Abort these steps and fail to parse the cookie-date if: - * * at least one of the found-day-of-month, found-month, found- - * year, or found-time flags is not set, - * * the day-of-month-value is less than 1 or greater than 31, - * * the year-value is less than 1601, - * * the hour-value is greater than 23, - * * the minute-value is greater than 59, or - * * the second-value is greater than 59. - * (Note that leap seconds cannot be represented in this syntax.)" - * - * So, in order as above: - */ - if ( - dayOfMonth === null || month === null || year === null || second === null || - dayOfMonth < 1 || dayOfMonth > 31 || - year < 1601 || - hour > 23 || - minute > 59 || - second > 59 - ) { - return; - } - - return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); -} - -function formatDate(date) { - var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d; - var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; - var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; - var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; - return NUM_TO_DAY[date.getUTCDay()] + ', ' + - d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ - h+':'+m+':'+s+' GMT'; -} - -// S5.1.2 Canonicalized Host Names -function canonicalDomain(str) { - if (str == null) { - return null; - } - str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . - - // convert to IDN if any non-ASCII characters - if (punycode && /[^\u0001-\u007f]/.test(str)) { - str = punycode.toASCII(str); - } - - return str.toLowerCase(); -} - -// S5.1.3 Domain Matching -function domainMatch(str, domStr, canonicalize) { - if (str == null || domStr == null) { - return null; - } - if (canonicalize !== false) { - str = canonicalDomain(str); - domStr = canonicalDomain(domStr); - } - - /* - * "The domain string and the string are identical. (Note that both the - * domain string and the string will have been canonicalized to lower case at - * this point)" - */ - if (str == domStr) { - return true; - } - - /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ - - /* "* The string is a host name (i.e., not an IP address)." */ - if (net.isIP(str)) { - return false; - } - - /* "* The domain string is a suffix of the string" */ - var idx = str.indexOf(domStr); - if (idx <= 0) { - return false; // it's a non-match (-1) or prefix (0) - } - - // e.g "a.b.c".indexOf("b.c") === 2 - // 5 === 3+2 - if (str.length !== domStr.length + idx) { // it's not a suffix - return false; - } - - /* "* The last character of the string that is not included in the domain - * string is a %x2E (".") character." */ - if (str.substr(idx-1,1) !== '.') { - return false; - } - - return true; -} - - -// RFC6265 S5.1.4 Paths and Path-Match - -/* - * "The user agent MUST use an algorithm equivalent to the following algorithm - * to compute the default-path of a cookie:" - * - * Assumption: the path (and not query part or absolute uri) is passed in. - */ -function defaultPath(path) { - // "2. If the uri-path is empty or if the first character of the uri-path is not - // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. - if (!path || path.substr(0,1) !== "/") { - return "/"; - } - - // "3. If the uri-path contains no more than one %x2F ("/") character, output - // %x2F ("/") and skip the remaining step." - if (path === "/") { - return path; - } - - var rightSlash = path.lastIndexOf("/"); - if (rightSlash === 0) { - return "/"; - } - - // "4. Output the characters of the uri-path from the first character up to, - // but not including, the right-most %x2F ("/")." - return path.slice(0, rightSlash); -} - -function trimTerminator(str) { - for (var t = 0; t < TERMINATORS.length; t++) { - var terminatorIdx = str.indexOf(TERMINATORS[t]); - if (terminatorIdx !== -1) { - str = str.substr(0,terminatorIdx); - } - } - - return str; -} - -function parseCookiePair(cookiePair, looseMode) { - cookiePair = trimTerminator(cookiePair); - - var firstEq = cookiePair.indexOf('='); - if (looseMode) { - if (firstEq === 0) { // '=' is immediately at start - cookiePair = cookiePair.substr(1); - firstEq = cookiePair.indexOf('='); // might still need to split on '=' - } - } else { // non-loose mode - if (firstEq <= 0) { // no '=' or is at start - return; // needs to have non-empty "cookie-name" - } - } - - var cookieName, cookieValue; - if (firstEq <= 0) { - cookieName = ""; - cookieValue = cookiePair.trim(); - } else { - cookieName = cookiePair.substr(0, firstEq).trim(); - cookieValue = cookiePair.substr(firstEq+1).trim(); - } - - if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { - return; - } - - var c = new Cookie(); - c.key = cookieName; - c.value = cookieValue; - return c; -} - -function parse(str, options) { - if (!options || typeof options !== 'object') { - options = {}; - } - str = str.trim(); - - // We use a regex to parse the "name-value-pair" part of S5.2 - var firstSemi = str.indexOf(';'); // S5.2 step 1 - var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi); - var c = parseCookiePair(cookiePair, !!options.loose); - if (!c) { - return; - } - - if (firstSemi === -1) { - return c; - } - - // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string - // (including the %x3B (";") in question)." plus later on in the same section - // "discard the first ";" and trim". - var unparsed = str.slice(firstSemi + 1).trim(); - - // "If the unparsed-attributes string is empty, skip the rest of these - // steps." - if (unparsed.length === 0) { - return c; - } - - /* - * S5.2 says that when looping over the items "[p]rocess the attribute-name - * and attribute-value according to the requirements in the following - * subsections" for every item. Plus, for many of the individual attributes - * in S5.3 it says to use the "attribute-value of the last attribute in the - * cookie-attribute-list". Therefore, in this implementation, we overwrite - * the previous value. - */ - var cookie_avs = unparsed.split(';'); - while (cookie_avs.length) { - var av = cookie_avs.shift().trim(); - if (av.length === 0) { // happens if ";;" appears - continue; - } - var av_sep = av.indexOf('='); - var av_key, av_value; - - if (av_sep === -1) { - av_key = av; - av_value = null; - } else { - av_key = av.substr(0,av_sep); - av_value = av.substr(av_sep+1); - } - - av_key = av_key.trim().toLowerCase(); - - if (av_value) { - av_value = av_value.trim(); - } - - switch(av_key) { - case 'expires': // S5.2.1 - if (av_value) { - var exp = parseDate(av_value); - // "If the attribute-value failed to parse as a cookie date, ignore the - // cookie-av." - if (exp) { - // over and underflow not realistically a concern: V8's getTime() seems to - // store something larger than a 32-bit time_t (even with 32-bit node) - c.expires = exp; - } - } - break; - - case 'max-age': // S5.2.2 - if (av_value) { - // "If the first character of the attribute-value is not a DIGIT or a "-" - // character ...[or]... If the remainder of attribute-value contains a - // non-DIGIT character, ignore the cookie-av." - if (/^-?[0-9]+$/.test(av_value)) { - var delta = parseInt(av_value, 10); - // "If delta-seconds is less than or equal to zero (0), let expiry-time - // be the earliest representable date and time." - c.setMaxAge(delta); - } - } - break; - - case 'domain': // S5.2.3 - // "If the attribute-value is empty, the behavior is undefined. However, - // the user agent SHOULD ignore the cookie-av entirely." - if (av_value) { - // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E - // (".") character." - var domain = av_value.trim().replace(/^\./, ''); - if (domain) { - // "Convert the cookie-domain to lower case." - c.domain = domain.toLowerCase(); - } - } - break; - - case 'path': // S5.2.4 - /* - * "If the attribute-value is empty or if the first character of the - * attribute-value is not %x2F ("/"): - * Let cookie-path be the default-path. - * Otherwise: - * Let cookie-path be the attribute-value." - * - * We'll represent the default-path as null since it depends on the - * context of the parsing. - */ - c.path = av_value && av_value[0] === "/" ? av_value : null; - break; - - case 'secure': // S5.2.5 - /* - * "If the attribute-name case-insensitively matches the string "Secure", - * the user agent MUST append an attribute to the cookie-attribute-list - * with an attribute-name of Secure and an empty attribute-value." - */ - c.secure = true; - break; - - case 'httponly': // S5.2.6 -- effectively the same as 'secure' - c.httpOnly = true; - break; - - default: - c.extensions = c.extensions || []; - c.extensions.push(av); - break; - } - } - - return c; -} - -// avoid the V8 deoptimization monster! -function jsonParse(str) { - var obj; - try { - obj = JSON.parse(str); - } catch (e) { - return e; - } - return obj; -} - -function fromJSON(str) { - if (!str) { - return null; - } - - var obj; - if (typeof str === 'string') { - obj = jsonParse(str); - if (obj instanceof Error) { - return null; - } - } else { - // assume it's an Object - obj = str; - } - - var c = new Cookie(); - for (var i=0; i 1) { - var lindex = path.lastIndexOf('/'); - if (lindex === 0) { - break; - } - path = path.substr(0,lindex); - permutations.push(path); - } - permutations.push('/'); - return permutations; -} - -function getCookieContext(url) { - if (url instanceof Object) { - return url; - } - // NOTE: decodeURI will throw on malformed URIs (see GH-32). - // Therefore, we will just skip decoding for such URIs. - try { - url = decodeURI(url); - } - catch(err) { - // Silently swallow error - } - - return urlParse(url); -} - -function Cookie(options) { - options = options || {}; - - Object.keys(options).forEach(function(prop) { - if (Cookie.prototype.hasOwnProperty(prop) && - Cookie.prototype[prop] !== options[prop] && - prop.substr(0,1) !== '_') - { - this[prop] = options[prop]; - } - }, this); - - this.creation = this.creation || new Date(); - - // used to break creation ties in cookieCompare(): - Object.defineProperty(this, 'creationIndex', { - configurable: false, - enumerable: false, // important for assert.deepEqual checks - writable: true, - value: ++Cookie.cookiesCreated - }); -} - -Cookie.cookiesCreated = 0; // incremented each time a cookie is created - -Cookie.parse = parse; -Cookie.fromJSON = fromJSON; - -Cookie.prototype.key = ""; -Cookie.prototype.value = ""; - -// the order in which the RFC has them: -Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity -Cookie.prototype.maxAge = null; // takes precedence over expires for TTL -Cookie.prototype.domain = null; -Cookie.prototype.path = null; -Cookie.prototype.secure = false; -Cookie.prototype.httpOnly = false; -Cookie.prototype.extensions = null; - -// set by the CookieJar: -Cookie.prototype.hostOnly = null; // boolean when set -Cookie.prototype.pathIsDefault = null; // boolean when set -Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse -Cookie.prototype.lastAccessed = null; // Date when set -Object.defineProperty(Cookie.prototype, 'creationIndex', { - configurable: true, - enumerable: false, - writable: true, - value: 0 -}); - -Cookie.serializableProperties = Object.keys(Cookie.prototype) - .filter(function(prop) { - return !( - Cookie.prototype[prop] instanceof Function || - prop === 'creationIndex' || - prop.substr(0,1) === '_' - ); - }); - -Cookie.prototype.inspect = function inspect() { - var now = Date.now(); - return 'Cookie="'+this.toString() + - '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + - '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + - '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + - '"'; -}; - -// Use the new custom inspection symbol to add the custom inspect function if -// available. -if (util.inspect.custom) { - Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect; -} - -Cookie.prototype.toJSON = function() { - var obj = {}; - - var props = Cookie.serializableProperties; - for (var i=0; i=0.8" - }, - "files": [ - "lib" - ], - "homepage": "https://github.com/salesforce/tough-cookie", - "keywords": [ - "HTTP", - "cookie", - "cookies", - "set-cookie", - "cookiejar", - "jar", - "RFC6265", - "RFC2965" - ], - "license": "BSD-3-Clause", - "main": "./lib/cookie", - "name": "tough-cookie", - "repository": { - "type": "git", - "url": "git://github.com/salesforce/tough-cookie.git" - }, - "scripts": { - "cover": "nyc --reporter=lcov --reporter=html vows test/*_test.js", - "test": "vows test/*_test.js" - }, - "version": "2.4.3" -} diff --git a/legacy/pluma-selenium-client/pluma-selenium-client.js b/legacy/pluma-selenium-client/pluma-selenium-client.js deleted file mode 100644 index 4168bf90..00000000 --- a/legacy/pluma-selenium-client/pluma-selenium-client.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @fileoverview Defines the {@linkplain Driver WebDriver} client for the JSDOM browser. - * Every JSDOM session will be created with the default configuration. - * This ensures that cookies, cache, history, etc are not shared between - * different instatiations of the JSDOM object - * - * __Customizing JSDOM__ - * The capabilites for any JSDOM object can be customized using the {@linkplain Options} class. - */ - -const webdriver = require('selenium-webdriver'); -const { Browser, Capabilities } = require('selenium-webdriver/lib/capabilities'); - -/** - * Configuration options for the JSDOM driver - */ - -const JSDOM_OPTIONS_KEY = 'jsdomOptions'; - -class Options extends Capabilities { - /** - * @param {(Capabilties|MapObject)=} other Another set of - * capabilties to initialize this instance from. - */ - - constructor(other = undefined) { - super(other); - this.setBrowserName(Browser.JSDOM); - } - - // TODO: write function to customize JSDOM browser. - // Needs to be based off jsdom documentation and available configuration - // would be good to ask client what their specific needs are in order to - // cater this to them first and add more functionality later on. - - jsdomOptions() { - const options = this.get(JSDOM_OPTIONS_KEY) ? this.set(JSDOM_OPTIONS_KEY) : {}; - this.options = options; - return options; - } -} - -exports.Options = Options; diff --git a/legacy/pluma-webdriver.js b/legacy/pluma-webdriver.js deleted file mode 100644 index cf2dcc47..00000000 --- a/legacy/pluma-webdriver.js +++ /dev/null @@ -1,102 +0,0 @@ - -const express = require('express'); -const args = require('minimist')(process.argv.slice(2)); // for user provided port -const bodyParser = require('body-parser'); -const winston = require('winston'); -const expressWinston = require('express-winston'); - -const { SessionsManager } = require('./SessionsManager/SessionsManager'); -const { InvalidArgument } = require('./Error/errors.js'); -const { router } = require('./routes'); - - -const server = express(); -const HTTP_PORT = process.env.PORT || args.port || 3000; -process.env.NODE_ENV = process.env.NODE_ENV || 'dev'; - -const sessionsManager = new SessionsManager(); - -server.set('sessionsManager', sessionsManager); - -// middleware - -server.use(bodyParser.json()); - -// request logging -if (process.env.NODE_ENV !== 'test') { - const reqTransports = process.env.NODE_ENV === 'test' - ? [ - new winston.transports.Console({ level: 'info', timestamp: true }), - new winston.transports.File({ filename: 'pluma_requests.txt', level: 'info', timestamp: true }), - ] - : [new winston.transports.File({ filename: 'pluma_requests.txt', level: 'info', timestamp: true })]; - - - server.use(expressWinston.logger({ - transports: reqTransports, - format: winston.format.combine( - winston.format.json(), - winston.format.prettyPrint(), - ), - meta: true, - msg: 'HTTP {{req.method}} {{req.url}}', - expressFormat: true, - colorize: false, - })); -} - - -async function onHTTPStart() { - console.log(`listening on port ${HTTP_PORT}`); -} - -/* -------- ENDPOINTS -------------------- */ - -server.get('/', (req, res) => { - res.redirect(/* insert rick roll link here */); -}); - -// Status -server.get('/status', (req, res) => { - const state = sessionsManager.getReadinessState(); - res.status(200).json(state); -}); - - -/*---------------------------------------------------------*/ - -server.use(router); - -if (process.env.NODE_ENV !== 'test') { - // error logging - const errTransports = process.env.NODE_ENV === 'test' - ? [ - new winston.transports.Console({ level: 'error', timestamp: true }), - new winston.transports.File({ filename: 'pluma_error_log.txt', level: 'error', timestamp: true }), - ] - : [new winston.transports.File({ filename: 'pluma_error_log.txt', level: 'error', timestamp: true })]; - server.use(expressWinston.errorLogger({ - transports: errTransports, - format: winston.format.combine( - winston.format.json(), - winston.format.prettyPrint(), - ), - })); -} - - -// error handler -// eslint-disable-next-line no-unused-vars -server.use((err, req, res, next) => { - let error; - if (err instanceof SyntaxError) error = new InvalidArgument('Syntax Error'); - if (error === undefined) res.status(500).json(err); - else res.status(error.code).json(error); - process.exit(0); -}); - -server.listen(HTTP_PORT, async () => { - await onHTTPStart(); -}); - -module.exports = server; // for testing diff --git a/legacy/routes/cookies.js b/legacy/routes/cookies.js deleted file mode 100644 index 3f9122d6..00000000 --- a/legacy/routes/cookies.js +++ /dev/null @@ -1,72 +0,0 @@ - -const cookies = require('express').Router(); -const { COMMANDS } = require('../commands/commands'); - - -// add cookie -cookies.post('/', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - try { - req.sessionRequest.command = COMMANDS.ADD_COOKIE; - const response = await req.session.process(req.sessionRequest); - res.send(response); // returns SUCCESS: null for this endpoint - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// get all cookies -cookies.get('/', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - const response = {}; - try { - req.sessionRequest.command = COMMANDS.GET_ALL_COOKIES; - const foundCookies = await req.session.process(req.sessionRequest); - response.value = foundCookies; - res.json(response); - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// get named cookie -cookies.post('/:name', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - try { - // TODO: implement endpoint - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// delete cookie -cookies.delete('/:name', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - try { - // TODO: implement endpoint - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// delete all cookies -cookies.delete('/', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - try { - // TODO: implement endpoint - } catch (err) { - next(err); - } finally { - release(); - } -}); - -module.exports = cookies; diff --git a/legacy/routes/elements/elements.js b/legacy/routes/elements/elements.js deleted file mode 100644 index fe6a47f2..00000000 --- a/legacy/routes/elements/elements.js +++ /dev/null @@ -1,41 +0,0 @@ - -const elements = require('express').Router(); -const fromElement = require('./fromElement'); -const { COMMANDS } = require('../../legacy/commands/commands'); - -// errors -const { - NoSuchElement, -} = require('../../legacy/Error/errors.js'); - -// find element(s) -elements.post('/', async (req, res, next) => { - // endpoint currently ignores browsing contexts - const release = await req.session.mutex.acquire(); - let single = false; - - if (req.originalUrl.slice(req.originalUrl.lastIndexOf('/') + 1) === 'element') { - single = true; - } - try { - req.sessionRequest.command = single - ? COMMANDS.FIND_ELEMENT - : COMMANDS.FIND_ELEMENTS; - const response = {}; - const result = await req.session.process(req.sessionRequest); - if (result.length === 0) throw new NoSuchElement(); - response.value = single ? result[0] : result; - res.json(response); - } catch (err) { - next(err); - } finally { - release(); - } -}); - -elements.use('/:elementId', (req, res, next) => { - req.sessionRequest.urlVariables.elementId = req.params.elementId; - next(); -}, fromElement); - -module.exports = elements; diff --git a/legacy/routes/elements/fromElement.js b/legacy/routes/elements/fromElement.js deleted file mode 100644 index c5a90e34..00000000 --- a/legacy/routes/elements/fromElement.js +++ /dev/null @@ -1,109 +0,0 @@ - -const element = require('express').Router(); -const { COMMANDS } = require('../../legacy/commands/commands'); - -// errors -const { - NoSuchElement, -} = require('../../legacy/Error/errors.js'); - -// get element text -element.get('/text', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - try { - req.sessionRequest.command = COMMANDS.GET_ELEMENT_TEXT; - const text = await req.session.process(req.sessionRequest); - const response = { value: text }; - res.json(response); - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// find element(s) from element -element.post(['/element', '/elements'], async (req, res, next) => { - let single = false; - const release = await req.session.mutex.acquire(); - try { - if (req.originalUrl.slice(req.originalUrl.lastIndexOf('/') + 1) === 'element') { - single = true; - } - req.sessionRequest.command = single - ? COMMANDS.FIND_ELEMENT_FROM_ELEMENT - : COMMANDS.FIND_ELEMENTS_FROM_ELEMENT; - - const response = {}; - const result = await req.session.process(req.sessionRequest); - if (result === undefined - || result === null - || result.length === 0) throw new NoSuchElement(); - - response.value = single ? result[0] : result; - res.json(response); - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// get element tag name -element.get('/name', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - req.sessionRequest.command = COMMANDS.GET_ELEMENT_TAG_NAME; - try { - const result = await req.session.process(req.sessionRequest); - const response = { value: result }; - res.json(response); - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// get element attribute name -element.get('/attribute/:name', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - req.sessionRequest.command = COMMANDS.GET_ELEMENT_ATTRIBUTE; - req.sessionRequest.urlVariables.attributeName = req.params.name; - - try { - const result = await req.session.process(req.sessionRequest); - const response = { value: result }; - res.json(response); - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// send keys to element -element.post('/value', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - req.sessionRequest.command = COMMANDS.ELEMENT_SEND_KEYS; - try { - await req.session.process(req.sessionRequest); - res.send(null); - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// click element -element.post('/click', (req, res, next) => { - -}); - -// clear element -element.post('/clear', (req, res, next) => { - -}); - - -module.exports = element; diff --git a/legacy/routes/index.js b/legacy/routes/index.js deleted file mode 100644 index 46be4c80..00000000 --- a/legacy/routes/index.js +++ /dev/null @@ -1,99 +0,0 @@ -// routers -const router = require('express').Router(); -const elements = require('./elements/elements'); -const timeouts = require('./timeouts'); -const navigate = require('./navigate'); -const cookies = require('./cookies'); - -const Request = require('../legacy/Request/Request'); -const { COMMANDS } = require('../legacy/commands/commands'); - -// errors -const { InvalidArgument } = require('../legacy/Error/errors.js'); - -const utility = require('../utils/utils'); - -router.use('/session/:sessionId', (req, res, next) => { - const sessionsManager = req.app.get('sessionsManager'); - req.sessionId = req.params.sessionId; - req.session = sessionsManager.findSession(req.sessionId); - req.sessionRequest = new Request(req.params, req.body, null); - next(); -}); - -// New session -router.post('/session', async (req, res, next) => { - const sessionsManager = req.app.get('sessionsManager'); - try { - // not sure if this conditional is needed here, body-parser checks for this anyway - if (!(await utility.validate.requestBodyType(req, 'application/json'))) { - throw new InvalidArgument('POST /session'); - } - const newSession = sessionsManager.createSession(req.body); - res.json(newSession); - } catch (error) { - next(error); - } -}); - -// delete session -router.delete('/session/:sessionId', async (req, res, next) => { - const sessionsManager = req.app.get('sessionsManager'); - const release = await req.session.mutex.acquire(); - try { - req.sessionRequest.command = COMMANDS.DELETE_SESSION; - await sessionsManager.deleteSession(req.session, req.sessionRequest); - res.send(null); - if (sessionsManager.sessions.length === 0) process.exit(0); - } catch (error) { - next(error); - } finally { - release(); - } -}); - -// get title -router.get('/session/:sessionId/title', async (req, res, next) => { - let response = null; - const release = await req.session.mutex.acquire(); - try { - req.sessionRequest.command = COMMANDS.GET_TITLE; - const title = await req.session.process(req.sessionRequest); - response = { value: title }; - res.send(response); - } catch (err) { - next(err); - } finally { - release(); - } -}); - -router.post('/session/:sessionId/execute/sync', async (req, res, next) => { - let response = null; - const release = await req.session.mutex.acquire(); - try { - req.sessionRequest.command = COMMANDS.EXECUTE_SCRIPT; - const result = await req.session.process(req.sessionRequest); - response = { value: result }; - res.json(response); - } catch (err) { - next(err); - } finally { - release(); - } -}); - -// element(s) routes -router.use('/session/:sessionId/element', elements); -router.use('/session/:sessionId/elements', elements); - -// timeout routes -router.use('/session/:sessionId/timeouts', timeouts); - -// navigation routes -router.use('/session/:sessionId/url', navigate); - -// cookies routes -router.use('/session/:sessionId/cookie', cookies); - -module.exports = { router }; diff --git a/legacy/routes/navigate.js b/legacy/routes/navigate.js deleted file mode 100644 index 436b778e..00000000 --- a/legacy/routes/navigate.js +++ /dev/null @@ -1,32 +0,0 @@ -const navigate = require('express').Router(); - -const { COMMANDS } = require('../legacy/commands/commands'); - -// navigate to -navigate.post('/', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - try { - req.sessionRequest.command = COMMANDS.NAVIGATE_TO; - const response = await req.session.process(req.sessionRequest); - res.send(response); - } catch (error) { - next(error); - } finally { - release(); - } -}); - -// get current url -navigate.get('/', async (req, res, next) => { - const release = await req.session.mutex.acquire(); - try { - req.sessionRequest.command = COMMANDS.GET_CURRENT_URL; - const response = await req.session.process(req.sessionRequest); - res.send(response); - } catch (error) { - next(error); - } finally { - release(); - } -}); -module.exports = navigate; diff --git a/legacy/routes/timeouts.js b/legacy/routes/timeouts.js deleted file mode 100644 index e5038920..00000000 --- a/legacy/routes/timeouts.js +++ /dev/null @@ -1,16 +0,0 @@ -const timeouts = require('express').Router(); -const { InvalidArgument } = require('../Error/errors'); -const { COMMANDS } = require('../commands/commands'); - -timeouts.get('/', (req, res, next) => { - const response = { value: req.session.getTimeouts() }; - res.json(response); -}); - -// set timeouts -timeouts.post('/', (req, res, next) => { - req.session.setTimeouts(req.body); - res.send(null); -}); - -module.exports = timeouts; diff --git a/legacy/utils/utils.js b/legacy/utils/utils.js deleted file mode 100644 index ab43a0b2..00000000 --- a/legacy/utils/utils.js +++ /dev/null @@ -1,43 +0,0 @@ -const fs = require('fs'); - -const { - InvalidArgument, -} = require('../Error/errors'); - -exports.validate = { - requestBodyType(incomingMessage, type) { - if (incomingMessage.headers['content-type'].includes(type)) { - return true; - } - return false; - }, - type(testObj, type) { - if (testObj.constructor.name.toLowerCase() === type) return true; - return false; - }, - objectPropertiesAreInArray(object, array) { - let validObject = true; - - Object.keys(object).forEach((key) => { - if (!array.includes(key)) validObject = false; - }); - - if (validObject && Object.keys(object).length > array.length) validObject = false; - - return validObject; - }, - isEmpty(obj) { - return (Object.keys(obj).length === 0); - }, -}; - -exports.fileSystem = { - pathExists(path) { - return new Promise((res, rej) => { - fs.access(path, fs.F_OK, (err) => { - if (err) rej(new InvalidArgument()); - res(true); - }); - }); - }, -}; From 7f29edab306f7167e48ecec40a4a7e7b24ace90a Mon Sep 17 00:00:00 2001 From: Pouya Oftadeh Date: Tue, 8 Oct 2019 16:08:57 -0400 Subject: [PATCH 3/3] fix: add node_modules to Jest ignore paths --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 860f955c..ce43e39b 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,8 @@ }, "jest": { "modulePathIgnorePatterns": [ - "/src/" + "/src/", + "/node_modules/" ] }, "scripts": {