├── .github ├── workflows │ ├── build.yml │ └── npm-publish.yml ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── CONTRIBUTING.md ├── index.client.js ├── index.js ├── src ├── storageBrowser.js ├── storage.js ├── cache.js └── adobefetch.js ├── .gitignore ├── webpack.config.js ├── package.json ├── .eslintrc.js ├── sample └── getSample.js ├── test ├── mockData.js ├── headers.test.js ├── provided.test.js ├── config.test.js ├── storage.test.js └── jwt.test.js ├── CODE_OF_CONDUCT.md ├── dist ├── server.js └── client.js ├── README.md └── LICENSE /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build-package 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@master 14 | - name: Set up Node.js v14 15 | uses: actions/setup-node@master 16 | with: 17 | node-version: 14.x 18 | - name: install 19 | run: yarn install 20 | - name: test 21 | run: yarn test 22 | - name: coverage 23 | run: npx codecov 24 | - name: build 25 | run: yarn build 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ### Expected Behaviour 5 | 6 | ### Actual Behaviour 7 | 8 | ### Reproduce Scenario (including but not limited to) 9 | 10 | #### Steps to Reproduce 11 | 12 | #### Platform and Version 13 | 14 | #### Sample Code that illustrates the problem 15 | 16 | #### Logs taken while reproducing problem -------------------------------------------------------------------------------- /index.client.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const adobefetch = require('./src/adobefetch'); 14 | const storage = require('./src/storageBrowser'); 15 | 16 | module.exports = { 17 | config: adobefetch.getConfig(storage), 18 | normalizeHeaders: adobefetch.normalizeHeaders, 19 | generateRequestID: adobefetch.generateRequestID, 20 | AUTH_MODES: adobefetch.AUTH_MODES 21 | }; 22 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const storage = require('./src/storage'); 14 | const auth = require('@adobe/jwt-auth'); 15 | global.fetch = require('node-fetch'); 16 | const adobefetch = require('./src/adobefetch'); 17 | 18 | module.exports = { 19 | config: adobefetch.getConfig(storage, auth), 20 | normalizeHeaders: adobefetch.normalizeHeaders, 21 | generateRequestID: adobefetch.generateRequestID, 22 | AUTH_MODES: adobefetch.AUTH_MODES 23 | }; 24 | -------------------------------------------------------------------------------- /src/storageBrowser.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const TOKENS = 'tokens'; 14 | 15 | /** 16 | * Reads token cache from storage. 17 | * 18 | * @returns Promise 19 | */ 20 | async function read() { 21 | return JSON.parse(window.localStorage.getItem(TOKENS)); 22 | } 23 | 24 | /** 25 | * Saves token cache to storage. 26 | * 27 | * @param tokens 28 | * @returns {*} 29 | */ 30 | async function write(tokens) { 31 | return window.localStorage.setItem(TOKENS, JSON.stringify(tokens)); 32 | } 33 | 34 | module.exports.read = read; 35 | module.exports.write = write; 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | .idea 9 | 10 | # Runtime data 11 | pids 12 | *.pid 13 | *.seed 14 | *.pid.lock 15 | 16 | # Directory for instrumented libs generated by jscoverage/JSCover 17 | lib-cov 18 | 19 | # Coverage directory used by tools like istanbul 20 | coverage 21 | 22 | # nyc test coverage 23 | .nyc_output 24 | 25 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 26 | .grunt 27 | 28 | # Bower dependency directory (https://bower.io/) 29 | bower_components 30 | 31 | # node-waf configuration 32 | .lock-wscript 33 | 34 | # Compiled binary addons (https://nodejs.org/api/addons.html) 35 | build/Release 36 | 37 | # Dependency directories 38 | node_modules/ 39 | jspm_packages/ 40 | 41 | # TypeScript v1 declaration files 42 | typings/ 43 | 44 | # Optional npm cache directory 45 | .npm 46 | 47 | # Optional eslint cache 48 | .eslintcache 49 | 50 | # Optional REPL history 51 | .node_repl_history 52 | 53 | # Output of 'npm pack' 54 | *.tgz 55 | 56 | # Yarn Integrity file 57 | .yarn-integrity 58 | 59 | # dotenv environment variables file 60 | .env 61 | 62 | # next.js build output 63 | .next 64 | .node-persist 65 | .DS_Store 66 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | name: npm-publish 2 | on: 3 | push: 4 | branches: [ master ] 5 | jobs: 6 | npm-publish: 7 | name: npm-publish 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout repository 11 | uses: actions/checkout@master 12 | - name: Set up Node.js 13 | uses: actions/setup-node@master 14 | with: 15 | node-version: 14.x 16 | - name: install 17 | run: yarn install 18 | - name: test 19 | run: yarn test 20 | - name: build 21 | run: yarn build 22 | - name: Publish if version has been updated 23 | uses: mkiki/npm-publish-action@c4315ef5790b7bcec2cbb75b34e37681a409d78d 24 | with: # All of theses inputs are optional 25 | tag_name: "v%s" 26 | tag_message: "v%s" 27 | commit_pattern: "^Release (\\S+)" 28 | workspace: "." 29 | env: # More info about the environment variables in the README 30 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Leave this as is, it's automatically generated 31 | NPM_AUTH_TOKEN: ${{ secrets.ADOBE_BOT_NPM_TOKEN }} # This will be shared with your repo as an org secret 32 | NPM_AUTH: ${{ secrets.ADOBE_BOT_NPM_TOKEN }} # This will be shared with your repo as an org secret 33 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const path = require('path'); 14 | const nodeExternals = require('webpack-node-externals'); 15 | 16 | const serverConfig = { 17 | target: 'node', 18 | entry: './index.js', 19 | mode: 'production', 20 | output: { 21 | filename: 'server.js', 22 | path: path.resolve(__dirname, 'dist'), 23 | library: '@adobe/fetch', 24 | libraryTarget: 'commonjs2' 25 | }, 26 | externals: [nodeExternals()] 27 | }; 28 | 29 | const clientConfig = { 30 | target: 'web', 31 | entry: './index.client.js', 32 | mode: 'production', 33 | output: { 34 | filename: 'client.js', 35 | path: path.resolve(__dirname, 'dist'), 36 | library: '@adobe/fetch', 37 | libraryTarget: 'commonjs2' 38 | } 39 | }; 40 | 41 | module.exports = [clientConfig, serverConfig]; 42 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@adobe/api-fetch", 3 | "version": "0.3.4", 4 | "description": "Call Adobe APIs", 5 | "main": "dist/server.js", 6 | "browser": "dist/client.js", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/adobe/adobe-fetch.git" 10 | }, 11 | "bugs": { 12 | "url": "https://github.com/adobe/adobe-fetch/issues" 13 | }, 14 | "engines": { 15 | "node": ">=6.0.0" 16 | }, 17 | "scripts": { 18 | "lint": "eslint src test sample index*.js", 19 | "test": "jest", 20 | "build": "webpack" 21 | }, 22 | "keywords": [ 23 | "jwt", 24 | "api", 25 | "fetch", 26 | "adobe", 27 | "adobeio" 28 | ], 29 | "author": "Adobe Inc.", 30 | "license": "Apache-2.0", 31 | "publishConfig": { 32 | "registry": "https://registry.npmjs.org" 33 | }, 34 | "dependencies": { 35 | "@adobe/jwt-auth": "^0.3.1", 36 | "debug": "^4.3.1", 37 | "dotenv": "^8.2.0", 38 | "node-fetch": "^2.6.1", 39 | "node-persist": "^3.1.0", 40 | "uuid": "^8.3.1" 41 | }, 42 | "devDependencies": { 43 | "eslint": "^7.14.0", 44 | "eslint-config-prettier": "^6.15.0", 45 | "eslint-plugin-prettier": "^3.1.4", 46 | "jest": "^26.6.3", 47 | "prettier": "^2.2.0", 48 | "webpack": "^5.6.0", 49 | "webpack-cli": "^4.2.0", 50 | "webpack-node-externals": "^2.5.2" 51 | }, 52 | "jest": { 53 | "coverageDirectory": "./coverage/", 54 | "collectCoverage": true 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | module.exports = { 14 | extends: ['eslint:recommended', 'prettier'], // extending recommended config and config derived from eslint-config-prettier 15 | plugins: ['prettier'], // activating esling-plugin-prettier (--fix stuff) 16 | parserOptions: { 17 | ecmaVersion: 2017 18 | }, 19 | globals: { 20 | fetch: "readonly", 21 | localStorage: "readonly", 22 | window: "readonly" 23 | }, 24 | env: { 25 | es6: true, 26 | jest: true, 27 | node: true 28 | }, 29 | rules: { 30 | 'prettier/prettier': [ 31 | // customizing prettier rules (unfortunately not many of them are customizable) 32 | 'error', 33 | { 34 | singleQuote: true, 35 | trailingComma: 'none' 36 | } 37 | ], 38 | eqeqeq: ['error', 'always'] // adding some custom ESLint rules 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /src/storage.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const storage = require('node-persist'); 14 | const TOKENS = 'tokens'; 15 | 16 | let storagePromise = null; 17 | let storageInitialized = false; 18 | 19 | /** 20 | * Initialise storage (node-persist) 21 | * 22 | * @param options (Optional) 23 | * @returns Promise 24 | * @private 25 | */ 26 | async function _initStorage() { 27 | // Make sure init is only called once. 28 | if (!storagePromise) { 29 | storagePromise = storage.init().then(() => (storageInitialized = true)); 30 | } 31 | return storagePromise; 32 | } 33 | 34 | /** 35 | * Reads token cache from storage. 36 | * 37 | * @returns Promise 38 | */ 39 | async function read() { 40 | if (!storageInitialized) { 41 | await _initStorage(); 42 | } 43 | return await storage.getItem(TOKENS); 44 | } 45 | 46 | /** 47 | * Saves token cache to storage. 48 | * 49 | * @param tokens 50 | * @returns {*} 51 | */ 52 | async function write(tokens) { 53 | return await storage.setItem(TOKENS, tokens); 54 | } 55 | 56 | module.exports.read = read; 57 | module.exports.write = write; 58 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Description 4 | 5 | 6 | 7 | ## Related Issue 8 | 9 | 10 | 11 | 12 | 13 | 14 | ## Motivation and Context 15 | 16 | 17 | 18 | ## How Has This Been Tested? 19 | 20 | 21 | 22 | 23 | 24 | ## Screenshots (if appropriate): 25 | 26 | ## Types of changes 27 | 28 | 29 | 30 | - [ ] Bug fix (non-breaking change which fixes an issue) 31 | - [ ] New feature (non-breaking change which adds functionality) 32 | - [ ] Breaking change (fix or feature that would cause existing functionality to change) 33 | 34 | ## Checklist: 35 | 36 | 37 | 38 | 39 | - [ ] I have signed the [Adobe Open Source CLA](http://opensource.adobe.com/cla.html). 40 | - [ ] My code follows the code style of this project. 41 | - [ ] My change requires a change to the documentation. 42 | - [ ] I have updated the documentation accordingly. 43 | - [ ] I have read the **CONTRIBUTING** document. 44 | - [ ] I have added tests to cover my changes. 45 | - [ ] All new and existing tests passed. -------------------------------------------------------------------------------- /sample/getSample.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | require('dotenv').config(); 14 | 15 | /* 16 | 17 | GET sample: To use this sample, create an environment (.env) file with the following information: 18 | 19 | APIKEY= 20 | SECRET= 21 | ACCOUNT_ID= 22 | ORG_IG= 23 | META_SCOPES= 24 | PRIVATE_KEY= 25 | SAMPLE_URL= 26 | 27 | Alternatively, change the code below to use fs.readFileSync to read the private key from a file. 28 | */ 29 | 30 | const AdobeFetch = require('../index.js'); 31 | const { AUTH_MODES } = AdobeFetch; 32 | 33 | async function main() { 34 | const adobefetch = AdobeFetch.config({ 35 | auth: { 36 | mode: AUTH_MODES.JWT, 37 | clientId: process.env.APIKEY, 38 | clientSecret: process.env.SECRET, 39 | technicalAccountId: process.env.ACCOUNT_ID, 40 | orgId: process.env.ORG_ID, 41 | metaScopes: process.env.META_SCOPES.split(','), 42 | privateKey: process.env.PRIVATE_KEY // Alternative: require('fs').readFileSync('path/to/key') 43 | } 44 | }); 45 | 46 | try { 47 | const response = await adobefetch(process.env.SAMPLE_URL, { 48 | method: 'get' 49 | }); 50 | const json = await response.json(); 51 | console.log('Result: ', json); 52 | } catch (err) { 53 | console.log('Error while fetching:', err); 54 | } 55 | } 56 | 57 | main(); 58 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thanks for choosing to contribute! 4 | 5 | The following are a set of guidelines to follow when contributing to this project. 6 | 7 | ## Code Of Conduct 8 | 9 | This project adheres to the Adobe [code of conduct](../CODE_OF_CONDUCT.md). By participating, 10 | you are expected to uphold this code. Please report unacceptable behavior to 11 | [Grp-opensourceoffice@adobe.com](mailto:Grp-opensourceoffice@adobe.com). 12 | 13 | ## Have A Question? 14 | 15 | Start by filing an issue. The existing committers on this project work to reach 16 | consensus around project direction and issue solutions within issue threads 17 | (when appropriate). 18 | 19 | ## Contributor License Agreement 20 | 21 | All third-party contributions to this project must be accompanied by a signed contributor 22 | license agreement. This gives Adobe permission to redistribute your contributions 23 | as part of the project. [Sign our CLA](http://opensource.adobe.com/cla.html). You 24 | only need to submit an Adobe CLA one time, so if you have submitted one previously, 25 | you are good to go! 26 | 27 | ## Code Reviews 28 | 29 | All submissions should come in the form of pull requests and need to be reviewed 30 | by project committers. Read [GitHub's pull request documentation](https://help.github.com/articles/about-pull-requests/) 31 | for more information on sending pull requests. 32 | 33 | Lastly, please follow the [pull request template](PULL_REQUEST_TEMPLATE.md) when 34 | submitting a pull request! 35 | 36 | ## From Contributor To Committer 37 | 38 | We love contributions from our community! If you'd like to go a step beyond contributor 39 | and become a committer with full write access and a say in the project, you must 40 | be invited to the project. The existing committers employ an internal nomination 41 | process that must reach lazy consensus (silence is approval) before invitations 42 | are issued. If you feel you are qualified and want to get more deeply involved, 43 | feel free to reach out to existing committers to have a conversation about that. 44 | 45 | ## Security Issues 46 | 47 | Security issues shouldn't be reported on this issue tracker. Instead, [file an issue to our security experts](https://helpx.adobe.com/security/alertus.html) -------------------------------------------------------------------------------- /src/cache.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable require-atomic-updates */ 2 | /* 3 | Copyright 2019 Adobe. All rights reserved. 4 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. You may obtain a copy 6 | of the License at http://www.apache.org/licenses/LICENSE-2.0 7 | 8 | Unless required by applicable law or agreed to in writing, software distributed under 9 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 10 | OF ANY KIND, either express or implied. See the License for the specific language 11 | governing permissions and limitations under the License. 12 | */ 13 | 14 | // Consider a token expired 60 seconds before its calculated expiry time. 15 | const EXPIRY_THRESHOLD = 60 * 1000; 16 | 17 | /** 18 | * Reads cache from storage. 19 | * 20 | * @returns Promise 21 | */ 22 | async function readCache(cache) { 23 | if (!cache.disableStorage) { 24 | cache.tokens = (await cache.read()) || {}; 25 | cache.readOnce = true; 26 | } 27 | } 28 | 29 | /** 30 | * Save cache to storage. 31 | * 32 | * @returns Promise 33 | */ 34 | async function saveCache(cache) { 35 | if (!cache.disableStorage) { 36 | await cache.write(cache.tokens); 37 | } 38 | } 39 | 40 | /** 41 | * Stores new token in cache & storage. 42 | * 43 | * @param key 44 | * @param token 45 | * @returns Promise 46 | */ 47 | async function setToken(key, token, cache) { 48 | // Add expiry timestamp based on the server time. 49 | token.expires_at = Date.now() + token.expires_in - EXPIRY_THRESHOLD; 50 | 51 | await readCache(cache); 52 | cache.tokens[key] = token; 53 | await saveCache(cache); 54 | 55 | return token; 56 | } 57 | 58 | function _validToken(key, cache) { 59 | return cache.tokens !== undefined && 60 | cache.tokens[key] && 61 | cache.tokens[key].expires_at > Date.now() 62 | ? cache.tokens[key] 63 | : undefined; 64 | } 65 | 66 | /** 67 | * Gets a cached token if one is available and valid. 68 | * 69 | * @param key 70 | * @returns {undefined|*} 71 | */ 72 | async function getToken(key, cache) { 73 | let cacheRead = false; 74 | if (!cache.readOnce) { 75 | await readCache(cache); 76 | cacheRead = true; 77 | } 78 | 79 | let token = _validToken(key, cache); 80 | if (token || cacheRead) { 81 | return token; 82 | } else { 83 | await readCache(cache); 84 | return _validToken(key, cache); 85 | } 86 | } 87 | 88 | function config(options, defaultStorage) { 89 | const disableStorage = (options && options.disableStorage) || false; 90 | const readFunc = options.storage ? options.storage.read : defaultStorage.read; 91 | const writeFunc = options.storage 92 | ? options.storage.write 93 | : defaultStorage.write; 94 | 95 | const cache = { 96 | disableStorage: disableStorage, 97 | readOnce: disableStorage, 98 | read: readFunc, 99 | write: writeFunc, 100 | tokens: {} 101 | }; 102 | 103 | return { 104 | set: (key, token) => setToken(key, token, cache), 105 | get: (key) => getToken(key, cache) 106 | }; 107 | } 108 | 109 | module.exports.config = config; 110 | -------------------------------------------------------------------------------- /test/mockData.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxx'; 14 | const CLIENT_SECRET = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; 15 | const ACCOUNT_ID = 'xxxxxxxxxxxxxxxxxxxxxx@techacct.adobe.com'; 16 | const ORG_ID = 'xxxxxxxxxxxxxxxxxxxxxx@AdobeOrg'; 17 | const PRIVATE_KEY = 'aalsdjfajsldjfalsjkdfa ,lsjf ,aljs'; 18 | const IMS = 'https://ims-na1.adobelogin.com'; 19 | const SCOPES = ['ent_dataservices_sdk']; 20 | const TOKEN_KEY = `${CLIENT_ID}|${SCOPES.join(',')}`; 21 | const TOKEN_PROVIDED_KEY = `${CLIENT_ID}|org-${ORG_ID}`; 22 | const MOCK_URL = 'https://mock.com/mock'; 23 | const DEFAULT_TOKEN = { 24 | token_type: 'bearer', 25 | access_token: 'abcdef', 26 | expires_in: 86399956 27 | }; 28 | 29 | module.exports = { 30 | responseOK: { 31 | url: MOCK_URL, 32 | status: 200, 33 | statusText: 'OK', 34 | ok: true 35 | }, 36 | responseForbidden: { 37 | url: MOCK_URL, 38 | status: 403, 39 | statusText: 'Forbidden', 40 | ok: false 41 | }, 42 | responseUnauthorized: { 43 | url: MOCK_URL, 44 | status: 401, 45 | statusText: 'Unauthorized', 46 | ok: false 47 | }, 48 | responseUnauthorizedOther: { 49 | url: MOCK_URL, 50 | status: 444, 51 | statusText: 'Unauthorized', 52 | ok: false 53 | }, 54 | config: { 55 | clientId: CLIENT_ID, 56 | clientSecret: CLIENT_SECRET, 57 | technicalAccountId: ACCOUNT_ID, 58 | orgId: ORG_ID, 59 | metaScopes: SCOPES, 60 | privateKey: PRIVATE_KEY, 61 | ims: IMS 62 | }, 63 | providedConfig: { 64 | mode: 'provided', 65 | clientId: CLIENT_ID, 66 | orgId: ORG_ID, 67 | tokenProvider: async () => DEFAULT_TOKEN 68 | }, 69 | customProvidedConfig: (provider) => { 70 | return { 71 | mode: 'provided', 72 | clientId: CLIENT_ID, 73 | orgId: ORG_ID, 74 | tokenProvider: provider 75 | }; 76 | }, 77 | token_key: TOKEN_KEY, 78 | token_provided_key: TOKEN_PROVIDED_KEY, 79 | token: DEFAULT_TOKEN, 80 | token2: { 81 | token_type: 'bearer', 82 | access_token: 'mhmhmhmh', 83 | expires_in: 86399956 84 | }, 85 | valid_token: { 86 | [TOKEN_KEY]: { 87 | token_type: 'bearer', 88 | access_token: 'abcabc', 89 | expires_in: 86399956, 90 | expires_at: Date.now() + 100000 91 | }, 92 | [TOKEN_PROVIDED_KEY]: { 93 | token_type: 'bearer', 94 | access_token: 'abcabc', 95 | expires_in: 86399956, 96 | expires_at: Date.now() + 100000 97 | } 98 | }, 99 | expiring_token: { 100 | [TOKEN_KEY]: { 101 | token_type: 'bearer', 102 | access_token: 'xyzxyz', 103 | expires_in: 86399956, 104 | expires_at: Date.now() - 100000 105 | } 106 | }, 107 | url: MOCK_URL 108 | }; 109 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Adobe Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at Grp-opensourceoffice@adobe.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [https://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: https://contributor-covenant.org 74 | [version]: https://contributor-covenant.org/version/1/4/ -------------------------------------------------------------------------------- /test/headers.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const auth = require('@adobe/jwt-auth'); 14 | const adobefetch = require('../index'); 15 | const storage = require('node-persist'); 16 | const fetch = require('node-fetch'); 17 | const mockData = require('./mockData'); 18 | const { Headers } = jest.requireActual('node-fetch'); 19 | 20 | jest.mock('@adobe/jwt-auth'); 21 | jest.mock('node-persist'); 22 | jest.mock('node-fetch'); 23 | 24 | function expectHeader(key, value) { 25 | fetch.mockImplementation((url, options) => { 26 | expect(options.headers).toBeDefined(); 27 | expect(options.headers[key]).toBe(value); 28 | return Promise.resolve(mockData.responseOK); 29 | }); 30 | } 31 | 32 | describe('Validate headers behavior', () => { 33 | beforeEach(() => { 34 | // Default node-persist init/get/set - Do nothing 35 | storage.init.mockImplementation(() => Promise.resolve()); 36 | storage.getItem = jest.fn(() => Promise.resolve(undefined)); 37 | storage.setItem = jest.fn(() => Promise.resolve()); 38 | 39 | // Default auth - Return default token. 40 | auth.mockImplementation(() => Promise.resolve(mockData.token)); 41 | }); 42 | 43 | test('adds predefined headers', () => { 44 | expect.assertions(2); 45 | expectHeader('someheader', 'test'); 46 | 47 | const testFetch = adobefetch.config({ 48 | auth: mockData.config, 49 | headers: { someHeader: 'test' } 50 | }); 51 | return testFetch(mockData.url); 52 | }); 53 | 54 | test('predefined headers case insensitive', () => { 55 | expect.assertions(2); 56 | expectHeader('x-api-key', 'test'); 57 | const testFetch = adobefetch.config({ 58 | auth: mockData.config, 59 | headers: { 'X-API-KEY': 'test' } 60 | }); 61 | return testFetch(mockData.url); 62 | }); 63 | 64 | test('predefined headers can be a function', () => { 65 | expect.assertions(2); 66 | expectHeader('someheader', 'testThis'); 67 | const testFetch = adobefetch.config({ 68 | auth: mockData.config, 69 | headers: { someHeader: () => 'test' + 'This' } 70 | }); 71 | return testFetch(mockData.url); 72 | }); 73 | 74 | test('predefined headers can be overridden', () => { 75 | expect.assertions(2); 76 | expectHeader('someheader', 'test2'); 77 | 78 | const testFetch = adobefetch.config({ 79 | auth: mockData.config, 80 | headers: { someHeader: 'test' } 81 | }); 82 | return testFetch(mockData.url, { headers: { someHEADER: 'test2' } }); 83 | }); 84 | 85 | test('predefined headers can be overridden (Headers interface)', () => { 86 | expect.assertions(2); 87 | expectHeader('someheader', 'test2'); 88 | 89 | const headers = new Headers(); 90 | headers.set('someheader', 'test2'); 91 | 92 | const testFetch = adobefetch.config({ 93 | auth: mockData.config, 94 | headers: { someHeader: 'test' } 95 | }); 96 | return testFetch(mockData.url, { headers: headers }); 97 | }); 98 | 99 | test('headers can be added (Headers interface)', () => { 100 | expect.assertions(2); 101 | expectHeader('someheader', 'test'); 102 | 103 | const headers = new Headers(); 104 | headers.set('someheader', 'test'); 105 | 106 | const testFetch = adobefetch.config({ 107 | auth: mockData.config 108 | }); 109 | return testFetch(mockData.url, { headers: headers }); 110 | }); 111 | }); 112 | -------------------------------------------------------------------------------- /dist/server.js: -------------------------------------------------------------------------------- 1 | module.exports["@adobe/fetch"]=(()=>{var e={10:(e,t,r)=>{const n=r(75),o=r(819);global.fetch=r(786);const i=r(667);e.exports={config:i.getConfig(n,o),normalizeHeaders:i.normalizeHeaders,generateRequestID:i.generateRequestID,AUTH_MODES:i.AUTH_MODES}},667:(e,t,r)=>{const n=r(265),{v4:o}=r(231),i=r(682)("@adobe/fetch"),a={JWT:"jwt",Provided:"provided"};function s(){return o().replace(/-/g,"")}function u(e){let t={};if(e)if("function"==typeof e.entries)for(let r of e.entries()){const[e,n]=r;t[e.toLowerCase()]=n}else for(let r in e)t[r.toLowerCase()]=e[r];return t}async function c(e,t,r,n,o,s){const d=await async function(e,t,r,n){const o=e.auth_key;let i=await t.get(o);if(i&&!r)return i;{let r;r=e.mode===a.JWT?async()=>await n(e):async()=>await e.tokenProvider();try{if(i=await r(),i)return t.set(o,i);throw"Access token empty"}catch(e){throw console.error("Error while getting a new access token.",e),e}}}(r.auth,n,o,s),f=Object.assign({},t);f.headers=function(e,t,r){let n=function(e){let t={};for(let r in e){const n=e[r];t[r]="function"==typeof n?n():n}return t}(r);var o;return t&&t.headers&&(n=Object.assign(n,u(t.headers))),n.authorization=`${o=e.token_type,o[0].toUpperCase()+o.slice(1)} ${e.access_token}`,n}(d,t,r.headers),i(`${f.method||"GET"} ${e} - x-request-id: ${f.headers["x-request-id"]}`);const h=await fetch(e,f);return h.ok||(i(`${f.method||"GET"} ${e} - status ${h.statusText} (${h.status}). x-request-id: ${f.headers["x-request-id"]}`),401!==h.status&&403!==h.status||o)?h:(i(`${t.method||"GET"} ${e} - Will get new token.`),await c(e,t,r,n,!0,s))}e.exports={getConfig:function(e,t){return r=>{!function(e,t){if(!e.auth)throw"Auth configuration missing.";e.auth.mode||(e.auth.mode=t?a.JWT:a.Provided),function(e,t){let{mode:r,clientId:n,technicalAccountId:o,orgId:i,clientSecret:s,privateKey:u,metaScopes:c,storage:d,tokenProvider:f}=e;const h=[];if(r===a.JWT){if(!n&&h.push("clientId"),!o&&h.push("technicalAccountId"),!i&&h.push("orgId"),!s&&h.push("clientSecret"),!u&&h.push("privateKey"),(!c||0===c.length)&&h.push("metaScopes"),!t)throw"JWT authentication is not available in current setup.";if(u&&!("string"==typeof u||u instanceof Buffer||ArrayBuffer.isView(u)))throw"Required parameter privateKey is invalid";h.length||(e.auth_key=`${n}|${c.join(",")}`)}else{if(r!==a.Provided)throw`Invalid authentication mode - ${e.mode}`;if(!n&&h.push("clientId"),!i&&h.push("orgId"),!f&&h.push("tokenProvider"),h.length||(e.auth_key=`${n}|org-${i}`),f&&"function"!=typeof f)throw"Required parameter tokenProvider needs to be a function"}if(h.length>0)throw`Required parameter(s) ${h.join(", ")} are missing`;if(d){let{read:e,write:t}=d;if(!e)throw"Storage read method missing!";if(!t)throw"Storage write method missing!"}}(e.auth,t),e.headers=Object.assign({"x-api-key":e.auth.clientId,"x-request-id":()=>s(),"x-gw-ims-org-id":e.auth.orgId},u(e.headers))}(r,!!t);const o=n.config(r.auth,e);return(e,n={})=>function(e,t,r,n,o){return c(e,t,r,n,!1,o)}(e,n,r,o,t)}},normalizeHeaders:u,generateRequestID:s,AUTH_MODES:a}},265:e=>{async function t(e){e.disableStorage||(e.tokens=await e.read()||{},e.readOnce=!0)}function r(e,t){return void 0!==t.tokens&&t.tokens[e]&&t.tokens[e].expires_at>Date.now()?t.tokens[e]:void 0}e.exports.config=function(e,n){const o=e&&e.disableStorage||!1,i={disableStorage:o,readOnce:o,read:e.storage?e.storage.read:n.read,write:e.storage?e.storage.write:n.write,tokens:{}};return{set:(e,r)=>async function(e,r,n){return r.expires_at=Date.now()+r.expires_in-6e4,await t(n),n.tokens[e]=r,await async function(e){e.disableStorage||await e.write(e.tokens)}(n),r}(e,r,i),get:e=>async function(e,n){let o=!1;n.readOnce||(await t(n),o=!0);let i=r(e,n);return i||o?i:(await t(n),r(e,n))}(e,i)}}},75:(e,t,r)=>{const n=r(149),o="tokens";let i=null,a=!1;e.exports.read=async function(){return a||await async function(){return i||(i=n.init().then((()=>a=!0))),i}(),await n.getItem(o)},e.exports.write=async function(e){return await n.setItem(o,e)}},819:e=>{"use strict";e.exports=require("@adobe/jwt-auth")},682:e=>{"use strict";e.exports=require("debug")},786:e=>{"use strict";e.exports=require("node-fetch")},149:e=>{"use strict";e.exports=require("node-persist")},231:e=>{"use strict";e.exports=require("uuid")}},t={};return function r(n){if(t[n])return t[n].exports;var o=t[n]={exports:{}};return e[n](o,o.exports,r),o.exports}(10)})(); -------------------------------------------------------------------------------- /test/provided.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const fetch = require('node-fetch'); 14 | const storage = require('node-persist'); 15 | const mockData = require('./mockData'); 16 | const adobefetch = require('../index'); 17 | 18 | const TOKENS_KEY = 'tokens'; 19 | 20 | let testFetch = null; 21 | 22 | jest.mock('node-persist'); 23 | jest.mock('node-fetch'); 24 | 25 | function expectHeaders(url, options, access_token, apikey, orgid) { 26 | expect(options.headers).toBeDefined(); 27 | expect(options.headers['authorization']).toBe(`Bearer ${access_token}`); 28 | expect(options.headers['x-api-key']).toBe(apikey); 29 | expect(options.headers['x-gw-ims-org-id']).toBe(orgid); 30 | expect(options.headers['x-request-id']).toHaveLength(32); 31 | return Promise.resolve(mockData.responseOK); 32 | } 33 | 34 | describe('Validate provided behavior', () => { 35 | beforeEach(() => { 36 | // Default node-persist init/get/set - Do nothing 37 | storage.init.mockImplementation(() => Promise.resolve()); 38 | storage.getItem = jest.fn(() => Promise.resolve(undefined)); 39 | storage.setItem = jest.fn(() => Promise.resolve()); 40 | 41 | // Default fetch mock - Returns status 200 and expects the auth headers. 42 | fetch.mockImplementation((url, options) => 43 | expectHeaders( 44 | url, 45 | options, 46 | mockData.token.access_token, 47 | mockData.config.clientId, 48 | mockData.config.orgId 49 | ) 50 | ); 51 | }); 52 | 53 | test('adds authentication headers', () => { 54 | expect.assertions(5); 55 | testFetch = adobefetch.config({ auth: mockData.providedConfig }); 56 | return testFetch(mockData.url); 57 | }); 58 | 59 | test('caches access token', async () => { 60 | let providerCalled = 0; 61 | expect.assertions(11); 62 | testFetch = adobefetch.config({ 63 | auth: mockData.customProvidedConfig(() => { 64 | providerCalled++; 65 | return Promise.resolve(mockData.token); 66 | }) 67 | }); 68 | 69 | await testFetch(mockData.url); 70 | await testFetch(mockData.url); 71 | expect(providerCalled).toBe(1); 72 | }); 73 | 74 | test('get stored token if valid', async () => { 75 | expect.assertions(5); 76 | const token = mockData.valid_token[mockData.token_provided_key]; 77 | storage.getItem = jest.fn(() => { 78 | return Promise.resolve(mockData.valid_token); 79 | }); 80 | fetch.mockImplementation((url, options) => 81 | expectHeaders( 82 | url, 83 | options, 84 | token.access_token, 85 | mockData.config.clientId, 86 | mockData.config.orgId 87 | ) 88 | ); 89 | testFetch = adobefetch.config({ auth: mockData.providedConfig }); 90 | await testFetch(mockData.url); 91 | }); 92 | 93 | test('get new token when cached expires', async () => { 94 | expect.assertions(7); 95 | storage.getItem = jest.fn((key) => { 96 | expect(key).toBe(TOKENS_KEY); 97 | return Promise.resolve(mockData.expiring_token); 98 | }); 99 | testFetch = adobefetch.config({ auth: mockData.providedConfig }); 100 | await testFetch(mockData.url); 101 | }); 102 | 103 | test('get new token when fetch returns 401', async () => { 104 | expect.assertions(5); 105 | fetch.mockImplementation(() => 106 | Promise.resolve(mockData.responseUnauthorized) 107 | ); 108 | 109 | testFetch = adobefetch.config({ 110 | auth: mockData.customProvidedConfig(() => { 111 | fetch.mockImplementation((url, options) => 112 | expectHeaders( 113 | url, 114 | options, 115 | mockData.token2.access_token, 116 | mockData.config.clientId, 117 | mockData.config.orgId 118 | ) 119 | ); 120 | return Promise.resolve(mockData.token2); 121 | }) 122 | }); 123 | await testFetch(mockData.url); 124 | }); 125 | }); 126 | -------------------------------------------------------------------------------- /test/config.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const adobefetch = require('../index'); 14 | const adobefetchBrowser = require('../index.client'); 15 | const mockData = require('./mockData'); 16 | 17 | const { AUTH_MODES } = adobefetch; 18 | 19 | const { 20 | clientId, 21 | technicalAccountId, 22 | orgId, 23 | clientSecret, 24 | privateKey, 25 | metaScopes 26 | } = mockData.config; 27 | const { tokenProvider } = mockData.providedConfig; 28 | 29 | describe('Validate JWT config', () => { 30 | test('all parameters missing', () => { 31 | expect.assertions(1); 32 | return expect(() => adobefetch.config({})).toThrow( 33 | 'Auth configuration missing.' 34 | ); 35 | }); 36 | test('missing clientId', () => { 37 | expect.assertions(1); 38 | return expect(() => 39 | adobefetch.config({ 40 | auth: { 41 | clientSecret, 42 | technicalAccountId, 43 | orgId, 44 | metaScopes, 45 | privateKey 46 | } 47 | }) 48 | ).toThrow('Required parameter(s) clientId are missing'); 49 | }); 50 | test('missing clientSecret', () => { 51 | expect.assertions(1); 52 | return expect(() => 53 | adobefetch.config({ 54 | auth: { clientId, technicalAccountId, orgId, metaScopes, privateKey } 55 | }) 56 | ).toThrow('Required parameter(s) clientSecret are missing'); 57 | }); 58 | test('missing technicalAccountId', () => { 59 | expect.assertions(1); 60 | return expect(() => 61 | adobefetch.config({ 62 | auth: { clientId, clientSecret, orgId, metaScopes, privateKey } 63 | }) 64 | ).toThrow('Required parameter(s) technicalAccountId are missing'); 65 | }); 66 | test('missing orgId', () => { 67 | expect.assertions(1); 68 | return expect(() => 69 | adobefetch.config({ 70 | auth: { 71 | clientId, 72 | clientSecret, 73 | technicalAccountId, 74 | metaScopes, 75 | privateKey 76 | } 77 | }) 78 | ).toThrow('Required parameter(s) orgId are missing'); 79 | }); 80 | test('missing metaScopes', () => { 81 | expect.assertions(1); 82 | return expect(() => 83 | adobefetch.config({ 84 | auth: { clientId, clientSecret, technicalAccountId, orgId, privateKey } 85 | }) 86 | ).toThrow('Required parameter(s) metaScopes are missing'); 87 | }); 88 | test('missing privateKey', () => { 89 | expect.assertions(1); 90 | return expect(() => 91 | adobefetch.config({ 92 | auth: { clientId, clientSecret, technicalAccountId, orgId, metaScopes } 93 | }) 94 | ).toThrow('Required parameter(s) privateKey are missing'); 95 | }); 96 | 97 | test('privateKey is of wrong type', () => { 98 | expect.assertions(1); 99 | const privateKey = new Object(); 100 | return expect(() => 101 | adobefetch.config({ 102 | auth: { 103 | clientId, 104 | clientSecret, 105 | technicalAccountId, 106 | orgId, 107 | metaScopes, 108 | privateKey 109 | } 110 | }) 111 | ).toThrow('Required parameter privateKey is invalid'); 112 | }); 113 | }); 114 | 115 | describe('Validate Provided config', () => { 116 | test('all parameters missing', () => { 117 | return expect(() => 118 | adobefetch.config({ mode: AUTH_MODES.Provided }) 119 | ).toThrow('Auth configuration missing.'); 120 | }); 121 | test('missing clientId', () => { 122 | return expect(() => 123 | adobefetch.config({ 124 | auth: { 125 | mode: AUTH_MODES.Provided, 126 | orgId, 127 | tokenProvider 128 | } 129 | }) 130 | ).toThrow('Required parameter(s) clientId are missing'); 131 | }); 132 | test('missing orgId', () => { 133 | return expect(() => 134 | adobefetch.config({ 135 | auth: { 136 | mode: AUTH_MODES.Provided, 137 | clientId, 138 | tokenProvider 139 | } 140 | }) 141 | ).toThrow('Required parameter(s) orgId are missing'); 142 | }); 143 | test('missing tokenProvider', () => { 144 | return expect(() => 145 | adobefetch.config({ 146 | auth: { 147 | mode: AUTH_MODES.Provided, 148 | orgId, 149 | clientId 150 | } 151 | }) 152 | ).toThrow('Required parameter(s) tokenProvider are missing'); 153 | }); 154 | 155 | test('tokenProvider should be a function', () => { 156 | return expect(() => 157 | adobefetch.config({ 158 | auth: { 159 | mode: AUTH_MODES.Provided, 160 | orgId, 161 | clientId, 162 | tokenProvider: 'NOT A FUNCTION' 163 | } 164 | }) 165 | ).toThrow('Required parameter tokenProvider needs to be a function'); 166 | }); 167 | }); 168 | 169 | describe('Validate No JWT config', () => { 170 | test('JWT mode not supported', () => { 171 | return expect(() => 172 | adobefetchBrowser.config({ 173 | auth: { 174 | mode: AUTH_MODES.JWT, 175 | clientSecret, 176 | technicalAccountId, 177 | orgId, 178 | metaScopes, 179 | privateKey 180 | } 181 | }) 182 | ).toThrow('JWT authentication is not available in current setup.'); 183 | }); 184 | }); 185 | 186 | describe('Other config tests', () => { 187 | test('Other modes not supported', () => { 188 | return expect(() => 189 | adobefetch.config({ 190 | auth: { 191 | mode: 'testmode' 192 | } 193 | }) 194 | ).toThrow('Invalid authentication mode - testmode'); 195 | }); 196 | 197 | test('JWT mode is default', () => { 198 | let config = { 199 | clientId, 200 | technicalAccountId, 201 | orgId, 202 | clientSecret, 203 | privateKey, 204 | metaScopes 205 | }; 206 | adobefetch.config({ 207 | auth: config 208 | }); 209 | expect(config.mode).toBe(AUTH_MODES.JWT); 210 | }); 211 | 212 | test('Provided mode is default in nojwt', () => { 213 | let config = { 214 | clientId, 215 | orgId, 216 | tokenProvider 217 | }; 218 | adobefetchBrowser.config({ 219 | auth: config 220 | }); 221 | expect(config.mode).toBe(AUTH_MODES.Provided); 222 | }); 223 | }); 224 | -------------------------------------------------------------------------------- /test/storage.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const auth = require('@adobe/jwt-auth'); 14 | const fetch = require('node-fetch'); 15 | const adobefetch = require('../index'); 16 | const adobefetchBrowser = require('../index.client'); 17 | const mockData = require('./mockData'); 18 | 19 | const localStorageMock = (function () { 20 | let store = {}; 21 | return { 22 | getItem: (key) => store[key] || null, 23 | setItem: (key, value) => (store[key] = value.toString()), 24 | removeItem: (key) => delete store[key], 25 | clear: () => (store = {}) 26 | }; 27 | })(); 28 | 29 | Object.defineProperty(window, 'localStorage', { 30 | value: localStorageMock 31 | }); 32 | 33 | jest.mock('@adobe/jwt-auth'); 34 | jest.mock('node-fetch'); 35 | 36 | describe('Validate custom storage', () => { 37 | test('need a read method', () => { 38 | expect.assertions(1); 39 | const authConfig = Object.assign( 40 | { 41 | storage: { 42 | write: async () => {} 43 | } 44 | }, 45 | mockData.config 46 | ); 47 | 48 | return expect(() => 49 | adobefetch.config({ 50 | auth: authConfig 51 | }) 52 | ).toThrow('Storage read method missing'); 53 | }); 54 | 55 | test('need a write method', () => { 56 | expect.assertions(1); 57 | const authConfig = Object.assign( 58 | { 59 | storage: { 60 | read: async () => {} 61 | } 62 | }, 63 | mockData.config 64 | ); 65 | 66 | return expect(() => 67 | adobefetch.config({ 68 | auth: authConfig 69 | }) 70 | ).toThrow('Storage write method missing'); 71 | }); 72 | 73 | test('reads custom async', async () => { 74 | expect.assertions(2); 75 | const authConfig = Object.assign( 76 | { 77 | storage: { 78 | read: async () => { 79 | return mockData.valid_token; 80 | }, 81 | write: async () => {} 82 | } 83 | }, 84 | mockData.config 85 | ); 86 | 87 | const token = mockData.valid_token[mockData.token_key]; 88 | 89 | fetch.mockImplementation((url, options) => { 90 | expect(options.headers).toBeDefined(); 91 | expect(options.headers['authorization']).toBe( 92 | `Bearer ${token.access_token}` 93 | ); 94 | return Promise.resolve(mockData.responseOK); 95 | }); 96 | await adobefetch.config({ 97 | auth: authConfig 98 | })(mockData.url); 99 | }); 100 | 101 | test('reads custom promise', async () => { 102 | expect.assertions(2); 103 | const authConfig = Object.assign( 104 | { 105 | storage: { 106 | read: () => { 107 | return Promise.resolve(mockData.valid_token); 108 | }, 109 | write: async () => {} 110 | } 111 | }, 112 | mockData.config 113 | ); 114 | 115 | const token = mockData.valid_token[mockData.token_key]; 116 | 117 | fetch.mockImplementation((url, options) => { 118 | expect(options.headers).toBeDefined(); 119 | expect(options.headers['authorization']).toBe( 120 | `Bearer ${token.access_token}` 121 | ); 122 | return Promise.resolve(mockData.responseOK); 123 | }); 124 | await adobefetch.config({ 125 | auth: authConfig 126 | })(mockData.url); 127 | }); 128 | 129 | test('writes custom async', async () => { 130 | expect.assertions(1); 131 | let cached = {}; 132 | 133 | auth.mockImplementation(() => Promise.resolve(mockData.token)); 134 | fetch.mockImplementation(() => { 135 | return Promise.resolve(mockData.responseOK); 136 | }); 137 | 138 | const authConfig = Object.assign( 139 | { 140 | storage: { 141 | read: async () => { 142 | return cached; 143 | }, 144 | write: async (tokens) => { 145 | cached = tokens; 146 | } 147 | } 148 | }, 149 | mockData.config 150 | ); 151 | 152 | await adobefetch.config({ 153 | auth: authConfig 154 | })(mockData.url); 155 | 156 | expect(cached).toStrictEqual({ [mockData.token_key]: mockData.token }); 157 | }); 158 | 159 | test('writes custom promise', async () => { 160 | expect.assertions(1); 161 | let cached = {}; 162 | 163 | auth.mockImplementation(() => Promise.resolve(mockData.token)); 164 | fetch.mockImplementation(() => { 165 | return Promise.resolve(mockData.responseOK); 166 | }); 167 | 168 | const authConfig = Object.assign( 169 | { 170 | storage: { 171 | read: () => { 172 | return Promise.resolve(cached); 173 | }, 174 | write: (tokens) => { 175 | cached = tokens; 176 | return Promise.resolve(); 177 | } 178 | } 179 | }, 180 | mockData.config 181 | ); 182 | 183 | await adobefetch.config({ 184 | auth: authConfig 185 | })(mockData.url); 186 | 187 | expect(cached).toStrictEqual({ [mockData.token_key]: mockData.token }); 188 | }); 189 | }); 190 | 191 | describe('Validate local storage', () => { 192 | test('reads from local storage', async () => { 193 | expect.assertions(2); 194 | 195 | const token = mockData.valid_token[mockData.token_provided_key]; 196 | 197 | fetch.mockImplementation((url, options) => { 198 | expect(options.headers).toBeDefined(); 199 | expect(options.headers['authorization']).toBe( 200 | `Bearer ${token.access_token}` 201 | ); 202 | return Promise.resolve(mockData.responseOK); 203 | }); 204 | 205 | window.localStorage.clear(); 206 | window.localStorage.setItem('tokens', JSON.stringify(mockData.valid_token)); 207 | 208 | await adobefetchBrowser.config({ 209 | auth: mockData.providedConfig 210 | })(mockData.url); 211 | }); 212 | 213 | test('write to local storage', async () => { 214 | expect.assertions(1); 215 | 216 | const token = mockData.valid_token[mockData.token_provided_key]; 217 | 218 | window.localStorage.clear(); 219 | 220 | fetch.mockImplementation(() => Promise.resolve(mockData.responseOK)); 221 | 222 | await adobefetchBrowser.config({ 223 | auth: mockData.customProvidedConfig( 224 | () => mockData.valid_token[mockData.token_provided_key] 225 | ) 226 | })(mockData.url); 227 | 228 | const tokens = JSON.parse(window.localStorage.getItem('tokens')); 229 | expect(tokens[mockData.token_provided_key]).toStrictEqual(token); 230 | }); 231 | }); 232 | -------------------------------------------------------------------------------- /src/adobefetch.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const cache = require('./cache'); 14 | const { v4: uuid } = require('uuid'); 15 | const debug = require('debug')('@adobe/fetch'); 16 | const NO_CONFIG = 'Auth configuration missing.'; 17 | const AUTH_MODES = { 18 | JWT: 'jwt', 19 | Provided: 'provided' 20 | }; 21 | 22 | async function getToken(authOptions, tokenCache, forceNewToken, auth) { 23 | const key = authOptions.auth_key; 24 | let token = await tokenCache.get(key); 25 | 26 | if (token && !forceNewToken) { 27 | return token; 28 | } else { 29 | let authFunc = undefined; 30 | if (authOptions.mode === AUTH_MODES.JWT) { 31 | authFunc = async () => await auth(authOptions); 32 | } else { 33 | authFunc = async () => await authOptions.tokenProvider(); 34 | } 35 | 36 | try { 37 | token = await authFunc(); 38 | if (token) { 39 | return tokenCache.set(key, token); 40 | } else { 41 | throw 'Access token empty'; 42 | } 43 | } catch (err) { 44 | console.error('Error while getting a new access token.', err); 45 | throw err; 46 | } 47 | } 48 | } 49 | 50 | function capFirst(s) { 51 | return s[0].toUpperCase() + s.slice(1); 52 | } 53 | 54 | function generateRequestID() { 55 | return uuid().replace(/-/g, ''); 56 | } 57 | 58 | function normalizeHeaders(headers) { 59 | let normalized = {}; 60 | if (headers) { 61 | if (typeof headers.entries === 'function') { 62 | // This is a headers object, iterate with for..of. 63 | for (let pair of headers.entries()) { 64 | const [name, value] = pair; 65 | normalized[name.toLowerCase()] = value; 66 | } 67 | } else { 68 | // This is a normal JSON. Iterate with for.. in 69 | for (let name in headers) { 70 | normalized[name.toLowerCase()] = headers[name]; 71 | } 72 | } 73 | } 74 | return normalized; 75 | } 76 | 77 | function calculateHeaders(predefinedHeaders) { 78 | let headers = {}; 79 | for (let name in predefinedHeaders) { 80 | const value = predefinedHeaders[name]; 81 | if (typeof value === 'function') { 82 | headers[name] = value(); 83 | } else { 84 | headers[name] = value; 85 | } 86 | } 87 | return headers; 88 | } 89 | 90 | function getHeaders(token, options, predefinedHeaders) { 91 | let headers = calculateHeaders(predefinedHeaders); 92 | if (options && options.headers) { 93 | headers = Object.assign(headers, normalizeHeaders(options.headers)); 94 | } 95 | 96 | headers.authorization = `${capFirst(token.token_type)} ${token.access_token}`; 97 | return headers; 98 | } 99 | 100 | async function _fetch( 101 | url, 102 | opts, 103 | configOptions, 104 | tokenCache, 105 | forceNewToken, 106 | auth 107 | ) { 108 | const token = await getToken( 109 | configOptions.auth, 110 | tokenCache, 111 | forceNewToken, 112 | auth 113 | ); 114 | 115 | const fetchOpts = Object.assign({}, opts); 116 | fetchOpts.headers = getHeaders(token, opts, configOptions.headers); 117 | 118 | debug( 119 | `${fetchOpts.method || 'GET'} ${url} - x-request-id: ${ 120 | fetchOpts.headers['x-request-id'] 121 | }` 122 | ); 123 | const res = await fetch(url, fetchOpts); 124 | 125 | if (!res.ok) { 126 | debug( 127 | `${fetchOpts.method || 'GET'} ${url} - status ${res.statusText} (${ 128 | res.status 129 | }). x-request-id: ${fetchOpts.headers['x-request-id']}` 130 | ); 131 | if ((res.status === 401 || res.status === 403) && !forceNewToken) { 132 | debug(`${opts.method || 'GET'} ${url} - Will get new token.`); 133 | return await _fetch(url, opts, configOptions, tokenCache, true, auth); 134 | } 135 | } 136 | return res; 137 | } 138 | 139 | /** 140 | * Fetch function 141 | * 142 | * @return Promise 143 | * @param url 144 | * @param options 145 | */ 146 | function adobefetch(url, options, configOptions, tokenCache, auth) { 147 | return _fetch(url, options, configOptions, tokenCache, false, auth); 148 | } 149 | 150 | function verifyAuthConfig(options, hasAuthFunction) { 151 | let { 152 | mode, 153 | clientId, 154 | technicalAccountId, 155 | orgId, 156 | clientSecret, 157 | privateKey, 158 | metaScopes, 159 | storage, 160 | tokenProvider 161 | } = options; 162 | 163 | const errors = []; 164 | if (mode === AUTH_MODES.JWT) { 165 | !clientId ? errors.push('clientId') : ''; 166 | !technicalAccountId ? errors.push('technicalAccountId') : ''; 167 | !orgId ? errors.push('orgId') : ''; 168 | !clientSecret ? errors.push('clientSecret') : ''; 169 | !privateKey ? errors.push('privateKey') : ''; 170 | !metaScopes || metaScopes.length === 0 ? errors.push('metaScopes') : ''; 171 | if (!hasAuthFunction) { 172 | throw 'JWT authentication is not available in current setup.'; 173 | } 174 | 175 | if ( 176 | privateKey && 177 | !( 178 | typeof privateKey === 'string' || 179 | privateKey instanceof Buffer || 180 | ArrayBuffer.isView(privateKey) 181 | ) 182 | ) { 183 | throw 'Required parameter privateKey is invalid'; 184 | } 185 | if (!errors.length) { 186 | options.auth_key = `${clientId}|${metaScopes.join(',')}`; 187 | } 188 | } else if (mode === AUTH_MODES.Provided) { 189 | !clientId ? errors.push('clientId') : ''; 190 | !orgId ? errors.push('orgId') : ''; 191 | !tokenProvider ? errors.push('tokenProvider') : ''; 192 | if (!errors.length) { 193 | options.auth_key = `${clientId}|org-${orgId}`; 194 | } 195 | if (tokenProvider && typeof tokenProvider !== 'function') { 196 | throw 'Required parameter tokenProvider needs to be a function'; 197 | } 198 | } else { 199 | throw `Invalid authentication mode - ${options.mode}`; 200 | } 201 | 202 | if (errors.length > 0) { 203 | throw `Required parameter(s) ${errors.join(', ')} are missing`; 204 | } 205 | 206 | if (storage) { 207 | let { read, write } = storage; 208 | if (!read) { 209 | throw 'Storage read method missing!'; 210 | } else if (!write) { 211 | throw 'Storage write method missing!'; 212 | } 213 | } 214 | } 215 | 216 | function prepareConfig(config, hasAuthFunction) { 217 | if (!config.auth) { 218 | throw NO_CONFIG; 219 | } else { 220 | if (!config.auth.mode) { 221 | config.auth.mode = hasAuthFunction ? AUTH_MODES.JWT : AUTH_MODES.Provided; 222 | } 223 | verifyAuthConfig(config.auth, hasAuthFunction); 224 | } 225 | 226 | config.headers = Object.assign( 227 | { 228 | 'x-api-key': config.auth.clientId, 229 | 'x-request-id': () => generateRequestID(), 230 | 'x-gw-ims-org-id': config.auth.orgId 231 | }, 232 | normalizeHeaders(config.headers) 233 | ); 234 | } 235 | 236 | function getConfig(storage, auth = undefined) { 237 | return (configOptions) => { 238 | prepareConfig(configOptions, !!auth); 239 | 240 | const tokenCache = cache.config(configOptions.auth, storage); 241 | 242 | return (url, options = {}) => 243 | adobefetch(url, options, configOptions, tokenCache, auth); 244 | }; 245 | } 246 | 247 | module.exports = { 248 | getConfig: getConfig, 249 | normalizeHeaders: normalizeHeaders, 250 | generateRequestID: generateRequestID, 251 | AUTH_MODES: AUTH_MODES 252 | }; 253 | -------------------------------------------------------------------------------- /test/jwt.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const auth = require('@adobe/jwt-auth'); 14 | const { v4: uuid } = require('uuid'); 15 | const storage = require('node-persist'); 16 | const fetch = require('node-fetch'); 17 | const mockData = require('./mockData'); 18 | const adobefetch = require('../index'); 19 | 20 | const TOKENS_KEY = 'tokens'; 21 | 22 | let testFetch = null; 23 | 24 | jest.mock('@adobe/jwt-auth'); 25 | jest.mock('node-persist'); 26 | jest.mock('node-fetch'); 27 | 28 | function expectHeaders(url, options, access_token, apikey, orgid) { 29 | expect(options.headers).toBeDefined(); 30 | expect(options.headers['authorization']).toBe(`Bearer ${access_token}`); 31 | expect(options.headers['x-api-key']).toBe(apikey); 32 | expect(options.headers['x-gw-ims-org-id']).toBe(orgid); 33 | expect(options.headers['x-request-id']).toHaveLength(32); 34 | return Promise.resolve(mockData.responseOK); 35 | } 36 | 37 | describe('Validate auth behavior', () => { 38 | beforeEach(() => { 39 | // Default node-persist init/get/set - Do nothing 40 | storage.init.mockImplementation(() => Promise.resolve()); 41 | storage.getItem = jest.fn(() => Promise.resolve(undefined)); 42 | storage.setItem = jest.fn(() => Promise.resolve()); 43 | 44 | // Default auth - Return default token. 45 | auth.mockImplementation(() => Promise.resolve(mockData.token)); 46 | 47 | // Default fetch mock - Returns status 200 and expects the auth headers. 48 | fetch.mockImplementation((url, options) => 49 | expectHeaders( 50 | url, 51 | options, 52 | mockData.token.access_token, 53 | mockData.config.clientId, 54 | mockData.config.orgId 55 | ) 56 | ); 57 | 58 | // New adobe fetch object. 59 | testFetch = adobefetch.config({ auth: mockData.config }); 60 | }); 61 | 62 | test('adds authentication headers', () => { 63 | expect.assertions(5); 64 | return testFetch(mockData.url); 65 | }); 66 | 67 | test('caches access token', async () => { 68 | expect.assertions(11); 69 | await testFetch(mockData.url); 70 | let authCalled = false; 71 | auth.mockImplementation(() => { 72 | // This code should not be called since test uses a cached token. 73 | authCalled = true; 74 | return Promise.reject(); 75 | }); 76 | await testFetch(mockData.url); 77 | expect(authCalled).toBe(false); 78 | }); 79 | 80 | test('get stored token if valid', async () => { 81 | expect.assertions(5); 82 | const token = mockData.valid_token[mockData.token_key]; 83 | storage.getItem = jest.fn(() => { 84 | return Promise.resolve(mockData.valid_token); 85 | }); 86 | fetch.mockImplementation((url, options) => 87 | expectHeaders( 88 | url, 89 | options, 90 | token.access_token, 91 | mockData.config.clientId, 92 | mockData.config.orgId 93 | ) 94 | ); 95 | await testFetch(mockData.url); 96 | }); 97 | 98 | test('get new token when cached expires', async () => { 99 | expect.assertions(7); 100 | storage.getItem = jest.fn((key) => { 101 | expect(key).toBe(TOKENS_KEY); 102 | return Promise.resolve(mockData.expiring_token); 103 | }); 104 | await testFetch(mockData.url); 105 | }); 106 | 107 | test('get new token when fetch returns 401', async () => { 108 | expect.assertions(5); 109 | fetch.mockImplementation(() => { 110 | auth.mockImplementation(() => { 111 | fetch.mockImplementation((url, options) => 112 | expectHeaders( 113 | url, 114 | options, 115 | mockData.token2.access_token, 116 | mockData.config.clientId, 117 | mockData.config.orgId 118 | ) 119 | ); 120 | return Promise.resolve(mockData.token2); 121 | }); 122 | return Promise.resolve(mockData.responseUnauthorized); 123 | }); 124 | await testFetch(mockData.url); 125 | }); 126 | 127 | test('get new token when fetch returns 403', async () => { 128 | expect.assertions(5); 129 | fetch.mockImplementation(() => { 130 | auth.mockImplementation(() => { 131 | fetch.mockImplementation((url, options) => 132 | expectHeaders( 133 | url, 134 | options, 135 | mockData.token2.access_token, 136 | mockData.config.clientId, 137 | mockData.config.orgId 138 | ) 139 | ); 140 | return Promise.resolve(mockData.token2); 141 | }); 142 | return Promise.resolve(mockData.responseForbidden); 143 | }); 144 | await testFetch(mockData.url); 145 | }); 146 | 147 | test('returns response when fetch returns 444', async () => { 148 | fetch.mockImplementation(() => 149 | Promise.resolve(mockData.responseUnauthorizedOther) 150 | ); 151 | const res = await testFetch(mockData.url); 152 | expect(res).toBeDefined(); 153 | expect(res.status).toBe(444); 154 | expect(res.ok).toBe(false); 155 | }); 156 | 157 | test('allows x-api-key override', async () => { 158 | expect.assertions(5); 159 | fetch.mockImplementation((url, options) => 160 | expectHeaders( 161 | url, 162 | options, 163 | mockData.token.access_token, 164 | 'test-override', 165 | mockData.config.orgId 166 | ) 167 | ); 168 | await testFetch(mockData.url, { 169 | headers: { 'x-api-key': 'test-override' } 170 | }); 171 | }); 172 | 173 | test('allows x-request-id override', async () => { 174 | expect.assertions(6); 175 | const xrequestid = uuid().replace(/-/g, ''); 176 | 177 | fetch.mockImplementation((url, options) => { 178 | expect(options.headers['x-request-id']).toBe(xrequestid); 179 | return expectHeaders( 180 | url, 181 | options, 182 | mockData.token.access_token, 183 | mockData.config.clientId, 184 | mockData.config.orgId 185 | ); 186 | }); 187 | await testFetch(mockData.url, { 188 | headers: { 'x-request-id': xrequestid } 189 | }); 190 | }); 191 | 192 | test('token stored in default storage', async () => { 193 | expect.assertions(7); 194 | storage.setItem = jest.fn((key, value) => { 195 | expect(key).toBe(TOKENS_KEY); 196 | expect(value).toStrictEqual({ [mockData.token_key]: mockData.token }); 197 | }); 198 | await testFetch(mockData.url); 199 | }); 200 | 201 | test('token not stored if storage disabled', async () => { 202 | let setItemCalled = false; 203 | let getItemCalled = false; 204 | storage.getItem = jest.fn(() => { 205 | getItemCalled = true; 206 | return Promise.resolve({}); 207 | }); 208 | storage.setItem = jest.fn(() => { 209 | setItemCalled = true; 210 | return Promise.resolve(); 211 | }); 212 | testFetch = adobefetch.config({ 213 | auth: Object.assign({ disableStorage: true }, mockData.config) 214 | }); 215 | await testFetch(mockData.url); 216 | expect(setItemCalled).toBe(false); 217 | expect(getItemCalled).toBe(false); 218 | }); 219 | 220 | test('throws error if token is empty', () => { 221 | expect.assertions(1); 222 | const ERROR = 'Access token empty'; 223 | auth.mockImplementation(async () => undefined); 224 | fetch.mockImplementation(() => { 225 | return Promise.resolve(mockData.responseOK); 226 | }); 227 | return expect(testFetch(mockData.url)).rejects.toEqual(ERROR); 228 | }); 229 | 230 | test('rethrows JWT errors', () => { 231 | expect.assertions(1); 232 | const ERROR = 'Some Error'; 233 | auth.mockImplementation(async () => { 234 | throw ERROR; 235 | }); 236 | fetch.mockImplementation(() => Promise.resolve(mockData.responseOK)); 237 | return expect(testFetch(mockData.url)).rejects.toEqual(ERROR); 238 | }); 239 | }); 240 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 2 | [![Version](https://img.shields.io/npm/v/@adobe/fetch.svg)](https://npmjs.org/package/@adobe/fetch) 3 | [![Downloads/week](https://img.shields.io/npm/dw/@adobe/fetch.svg)](https://npmjs.org/package/@adobe/fetch) 4 | [![Build Status](https://github.com/adobe/adobe-fetch/actions/workflows/build.yml/badge.svg)](https://github.com/adobe/adobe-fetch/actions/workflows/build.yml) 5 | [![codecov](https://codecov.io/gh/adobe/adobe-fetch/branch/master/graph/badge.svg)](https://codecov.io/gh/adobe/adobe-fetch) 6 | 7 | [![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/adobe/adobe-fetch.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/adobe/adobe-fetch/context:javascript) 8 | 9 | # adobe-fetch 10 | 11 | Call Adobe APIs 12 | 13 | ## Goals 14 | 15 | Make calling Adobe APIs a breeze! 16 | 17 | This package will handle JWT authentication, token caching and storage. 18 | Otherwise it works exactly as [fetch](https://github.com/bitinn/node-fetch). 19 | 20 | This library now works in the browser as well, see information below. 21 | 22 | ### Installation 23 | 24 | ``` 25 | npm install --save @adobe/fetch 26 | ``` 27 | 28 | ### Common Usage 29 | 30 | ```javascript 31 | 32 | const AdobeFetch = require('@adobe/fetch'); 33 | const fs = require('fs'); 34 | 35 | const config = { 36 | auth: { 37 | clientId: 'asasdfasf', 38 | clientSecret: 'aslfjasljf-=asdfalasjdf==asdfa', 39 | technicalAccountId: 'asdfasdfas@techacct.adobe.com', 40 | orgId: 'asdfasdfasdf@AdobeOrg', 41 | metaScopes: ['ent_dataservices_sdk'] 42 | } 43 | }; 44 | 45 | config.auth.privateKey = fs.readFileSync('private.key'); 46 | 47 | const adobefetch = AdobeFetch.config(config); 48 | 49 | adobefetch("https://platform.adobe.io/some/adobe/api", { method: 'get'}) 50 | .then(response => response.json()) 51 | .then(json => console.log('Result: ',json)); 52 | 53 | ``` 54 | 55 | #### Config Auth object 56 | 57 | The `config.auth` object is where you pass in all the required and optional parameters to authenticate API calls. 58 | 59 | | parameter | integration name | required | type | default | 60 | | ------------------ | -------------------- | -------- | --------------------------------- | ------------------------------ | 61 | | clientId | API Key (Client ID) | true | String | | 62 | | technicalAccountId | Technical account ID | true | String | | 63 | | orgId | Organization ID | true | String | | 64 | | clientSecret | Client secret | true | String | | 65 | | privateKey | | true | String | | 66 | | passphrase | | false | String | | 67 | | metaScopes | | true | Comma separated Sting or an Array | | 68 | | ims | | false | String | | 69 | 70 | In order to determine which **metaScopes** you need to register for you can look them up by product in this [handy table](https://www.adobe.io/authentication/auth-methods.html#!AdobeDocs/adobeio-auth/master/JWT/Scopes.md). 71 | 72 | For instance, if you need to be authenticated to call API's for both GDPR and User Management you would [look them up](https://www.adobe.io/authentication/auth-methods.html#!AdobeDocs/adobeio-auth/master/JWT/Scopes.md) and find that they are: 73 | 74 | - GDPR: 75 | - User Management: 76 | 77 | Then you would create an array of **metaScopes** as part of the `config` object. For instance: 78 | 79 | ```javascript 80 | const config = { 81 | auth: { 82 | clientId: 'asasdfasf', 83 | clientSecret: 'aslfjasljf-=asdfalasjdf==asdfa', 84 | technicalAccountId: 'asdfasdfas@techacct.adobe.com', 85 | orgId: 'asdfasdfasdf@AdobeOrg', 86 | metaScopes: [ 87 | 'https://ims-na1.adobelogin.com/s/ent_gdpr_sdk', 88 | 'https://ims-na1.adobelogin.com/s/ent_user_sdk' 89 | ] 90 | } 91 | }; 92 | ``` 93 | 94 | However, if you omit the IMS URL, the package will automatically add it for you when making the call to generate the JWT. 95 | 96 | For example: 97 | 98 | ```javascript 99 | const config = { 100 | auth: { 101 | clientId: 'asasdfasf', 102 | clientSecret: 'aslfjasljf-=asdfalasjdf==asdfa', 103 | technicalAccountId: 'asdfasdfas@techacct.adobe.com', 104 | orgId: 'asdfasdfasdf@AdobeOrg', 105 | metaScopes: ['ent_gdpr_sdk', 'ent_user_sdk'] 106 | } 107 | }; 108 | ``` 109 | 110 | This is the recommended approach. 111 | 112 | #### Alternative authentication methods 113 | 114 | To use this library with an alternative authentication flow such as OAuth, or execute the JWT authentication flow outside of adobe-fetch, it is possible to use the **Provided** mode and provide the access token directly to adobe-fetch via an asynchronious function: 115 | 116 | ```javascript 117 | 118 | const AdobeFetch = require('@adobe/fetch'); 119 | const { AUTH_MODES } = AdobeFetch; 120 | 121 | const adobefetch = AdobeFetch).config({ 122 | auth: { 123 | mode: AUTH_MODES.Provided, 124 | clientId: 'asasdfasf', 125 | orgId: 'asdfasdfasdf@AdobeOrg', 126 | tokenProvider: async () => { ... Logic returning a valid access token object ... } 127 | } 128 | }); 129 | 130 | adobefetch("https://platform.adobe.io/some/adobe/api", { method: 'get'}) 131 | .then(response => response.json()) 132 | .then(json => console.log('Result: ',json)); 133 | 134 | ``` 135 | 136 | When the **adobefetch** call above happens for the first time, it will call the tokenProvider function provided and wait for it to return the access token. Access token is then cached and persisted, if it expires or is rejected by the API, the tokenProvider function will be called again to acquire a new token. 137 | 138 | A valid token has the following structure: 139 | ``` 140 | { 141 | token_type: 'bearer', 142 | access_token: <<>>, 143 | expires_in: <<>> 144 | } 145 | ``` 146 | 147 | #### Using in the browser 148 | 149 | In the browser only the **Provided** mode explained above is allowed, JWT is not supported. 150 | 151 | This is because the JWT workflow requires direct access to the private key and should be done in the server for security reasons. With Provided mode the access token can be acquired via a standard OAuth authentication flow and then used by adobe-fetch to call Adobe APIs. 152 | 153 | Using ```require('@adobe/fetch')``` in a web app will automatically use the browser version. 154 | You can also include the [bundled JS](dist/client.js) file directly in a script tag. 155 | 156 | 157 | #### Predefined Headers 158 | 159 | If you have HTTP headers that are required for each request, you can provide them in the configuration. 160 | They will be then added automatically to each request. 161 | 162 | You can provide either a value or a function. 163 | A function can be used when you need to generate a dynamic header value on each request. 164 | 165 | For example: 166 | 167 | ```javascript 168 | const config = { 169 | auth: { 170 | ... Auth Configuration ... 171 | }, 172 | headers: { 173 | 'x-sandbox-name': 'prod', 174 | 'x-request-id': () => idGenerationFunc() 175 | } 176 | }; 177 | ``` 178 | 179 | The following headers are added automatically. 180 | You can override these headers using a value or function as shown above, with the exception of **authorization**: 181 | 182 | - authorization **(Can not be overridden)** 183 | - x-api-key 184 | - x-request-id 185 | - x-gw-ims-org-id 186 | 187 | #### Custom Storage 188 | 189 | By default, [node-persist](https://github.com/simonlast/node-persist) is used to store all the active tokens locally. 190 | Tokens will be stored under **/.node-perist/storage** 191 | 192 | It is possible to use any other storage for token persistence. This is done by providing **read** and **write** methods as follows: 193 | 194 | ```javascript 195 | const config = { 196 | auth: { 197 | clientId: 'asasdfasf', 198 | 199 | ... 200 | 201 | storage: { 202 | read: function() { 203 | return new Promise(function(resolve, reject) { 204 | let tokens; 205 | 206 | // .. Some logic to read the tokens .. 207 | 208 | resolve(tokens); 209 | }); 210 | }, 211 | write: function(tokens) { 212 | return new Promise(function(resolve, reject) { 213 | 214 | // .. Some logic to save the tokens .. 215 | 216 | resolve(); 217 | }); 218 | } 219 | } 220 | } 221 | }; 222 | ``` 223 | 224 | Alternatively, use async/await: 225 | 226 | ```javascript 227 | const config = { 228 | auth: { 229 | clientId: 'asasdfasf', 230 | 231 | ... 232 | 233 | storage: { 234 | read: async function() { 235 | return await myGetTokensImplementation(); 236 | }, 237 | write: async function(tokens) { 238 | await myStoreTokensImplementation(tokens); 239 | } 240 | } 241 | } 242 | }; 243 | ``` 244 | 245 | ## Logging 246 | 247 | Every request will include a unique request identifier sent via the **x-request-id**. 248 | The request identifier can be overriden by providing it through the headers: 249 | ```javascript 250 | fetch(url, { 251 | headers: { 'x-request-id': myRequestID } 252 | }); 253 | ``` 254 | 255 | We use [debug](https://github.com/visionmedia/debug) to log requests. In order to see all the debug output, including the request identifiers, run your app with the **DEBUG** environment variable including the **@adobe/fetch** scope as follows: 256 | ``` 257 | DEBUG=@adobe/fetch 258 | ``` 259 | 260 | ### Contributing 261 | 262 | Contributions are welcomed! Read the [Contributing Guide](.github/CONTRIBUTING.md) for more information. 263 | 264 | ### Licensing 265 | 266 | This project is licensed under the Apache V2 License. See [LICENSE](LICENSE) for more information. 267 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Adobe 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /dist/client.js: -------------------------------------------------------------------------------- 1 | module.exports["@adobe/fetch"]=(()=>{var e={223:(e,t,r)=>{const n=r(667),o=r(390);e.exports={config:n.getConfig(o),normalizeHeaders:n.normalizeHeaders,generateRequestID:n.generateRequestID,AUTH_MODES:n.AUTH_MODES}},227:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(o=n))})),t.splice(o,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(447)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},447:(e,t,r)=>{e.exports=function(e){function t(e){let r,o=null;function s(...e){if(!s.enabled)return;const n=s,o=Number(new Date),a=o-(r||o);n.diff=a,n.prev=r,n.curr=o,r=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,o)=>{if("%%"===r)return"%";i++;const s=t.formatters[o];if("function"==typeof s){const t=e[i];r=s.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=n,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null===o?t.enabled(e):o,set:e=>{o=e}}),"function"==typeof t.init&&t.init(s),s}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{var t=1e3,r=60*t,n=60*r,o=24*n;function s(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}e.exports=function(e,a){a=a||{};var i,c,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(s){var a=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return 6048e5*a;case"days":case"day":case"d":return a*o;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===u&&isFinite(e))return a.long?(i=e,(c=Math.abs(i))>=o?s(i,c,o,"day"):c>=n?s(i,c,n,"hour"):c>=r?s(i,c,r,"minute"):c>=t?s(i,c,t,"second"):i+" ms"):function(e){var s=Math.abs(e);return s>=o?Math.round(e/o)+"d":s>=n?Math.round(e/n)+"h":s>=r?Math.round(e/r)+"m":s>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},614:(e,t,r)=>{"use strict";r.r(t),r.d(t,{NIL:()=>U,parse:()=>C,stringify:()=>d,v1:()=>h,v3:()=>A,v4:()=>x,v5:()=>$,validate:()=>i,version:()=>O});var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),o=new Uint8Array(16);function s(){if(!n)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(o)}const a=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,i=function(e){return"string"==typeof e&&a.test(e)};for(var c=[],u=0;u<256;++u)c.push((u+256).toString(16).substr(1));const d=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(c[e[t+0]]+c[e[t+1]]+c[e[t+2]]+c[e[t+3]]+"-"+c[e[t+4]]+c[e[t+5]]+"-"+c[e[t+6]]+c[e[t+7]]+"-"+c[e[t+8]]+c[e[t+9]]+"-"+c[e[t+10]]+c[e[t+11]]+c[e[t+12]]+c[e[t+13]]+c[e[t+14]]+c[e[t+15]]).toLowerCase();if(!i(r))throw TypeError("Stringified UUID is invalid");return r};var f,l,g=0,p=0;const h=function(e,t,r){var n=t&&r||0,o=t||new Array(16),a=(e=e||{}).node||f,i=void 0!==e.clockseq?e.clockseq:l;if(null==a||null==i){var c=e.random||(e.rng||s)();null==a&&(a=f=[1|c[0],c[1],c[2],c[3],c[4],c[5]]),null==i&&(i=l=16383&(c[6]<<8|c[7]))}var u=void 0!==e.msecs?e.msecs:Date.now(),h=void 0!==e.nsecs?e.nsecs:p+1,C=u-g+(h-p)/1e4;if(C<0&&void 0===e.clockseq&&(i=i+1&16383),(C<0||u>g)&&void 0===e.nsecs&&(h=0),h>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");g=u,p=h,l=i;var m=(1e4*(268435455&(u+=122192928e5))+h)%4294967296;o[n++]=m>>>24&255,o[n++]=m>>>16&255,o[n++]=m>>>8&255,o[n++]=255&m;var y=u/4294967296*1e4&268435455;o[n++]=y>>>8&255,o[n++]=255&y,o[n++]=y>>>24&15|16,o[n++]=y>>>16&255,o[n++]=i>>>8|128,o[n++]=255&i;for(var v=0;v<6;++v)o[n+v]=a[v];return t||d(o)},C=function(e){if(!i(e))throw TypeError("Invalid UUID");var t,r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r};function m(e,t,r){function n(e,n,o,s){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r>>9<<4)+1}function v(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function w(e,t,r,n,o,s){return v((a=v(v(t,e),v(n,s)))<<(i=o)|a>>>32-i,r);var a,i}function F(e,t,r,n,o,s,a){return w(t&r|~t&n,e,t,o,s,a)}function b(e,t,r,n,o,s,a){return w(t&n|r&~n,e,t,o,s,a)}function k(e,t,r,n,o,s,a){return w(t^r^n,e,t,o,s,a)}function I(e,t,r,n,o,s,a){return w(r^(t|~n),e,t,o,s,a)}const A=m("v3",48,(function(e){if("string"==typeof e){var t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(var r=0;r>5]>>>o%32&255,a=parseInt(n.charAt(s>>>4&15)+n.charAt(15&s),16);t.push(a)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[n/8])<>>32-t}const $=m("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var o=0;o>>0;v=y,y=m,m=E(C,30)>>>0,C=h,h=b}r[0]=r[0]+h>>>0,r[1]=r[1]+C>>>0,r[2]=r[2]+m>>>0,r[3]=r[3]+y>>>0,r[4]=r[4]+v>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]})),U="00000000-0000-0000-0000-000000000000",O=function(e){if(!i(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)}},667:(e,t,r)=>{const n=r(265),{v4:o}=r(614),s=r(227)("@adobe/fetch"),a={JWT:"jwt",Provided:"provided"};function i(){return o().replace(/-/g,"")}function c(e){let t={};if(e)if("function"==typeof e.entries)for(let r of e.entries()){const[e,n]=r;t[e.toLowerCase()]=n}else for(let r in e)t[r.toLowerCase()]=e[r];return t}async function u(e,t,r,n,o,i){const d=await async function(e,t,r,n){const o=e.auth_key;let s=await t.get(o);if(s&&!r)return s;{let r;r=e.mode===a.JWT?async()=>await n(e):async()=>await e.tokenProvider();try{if(s=await r(),s)return t.set(o,s);throw"Access token empty"}catch(e){throw console.error("Error while getting a new access token.",e),e}}}(r.auth,n,o,i),f=Object.assign({},t);f.headers=function(e,t,r){let n=function(e){let t={};for(let r in e){const n=e[r];t[r]="function"==typeof n?n():n}return t}(r);var o;return t&&t.headers&&(n=Object.assign(n,c(t.headers))),n.authorization=`${o=e.token_type,o[0].toUpperCase()+o.slice(1)} ${e.access_token}`,n}(d,t,r.headers),s(`${f.method||"GET"} ${e} - x-request-id: ${f.headers["x-request-id"]}`);const l=await fetch(e,f);return l.ok||(s(`${f.method||"GET"} ${e} - status ${l.statusText} (${l.status}). x-request-id: ${f.headers["x-request-id"]}`),401!==l.status&&403!==l.status||o)?l:(s(`${t.method||"GET"} ${e} - Will get new token.`),await u(e,t,r,n,!0,i))}e.exports={getConfig:function(e,t){return r=>{!function(e,t){if(!e.auth)throw"Auth configuration missing.";e.auth.mode||(e.auth.mode=t?a.JWT:a.Provided),function(e,t){let{mode:r,clientId:n,technicalAccountId:o,orgId:s,clientSecret:i,privateKey:c,metaScopes:u,storage:d,tokenProvider:f}=e;const l=[];if(r===a.JWT){if(!n&&l.push("clientId"),!o&&l.push("technicalAccountId"),!s&&l.push("orgId"),!i&&l.push("clientSecret"),!c&&l.push("privateKey"),(!u||0===u.length)&&l.push("metaScopes"),!t)throw"JWT authentication is not available in current setup.";if(c&&!("string"==typeof c||c instanceof Buffer||ArrayBuffer.isView(c)))throw"Required parameter privateKey is invalid";l.length||(e.auth_key=`${n}|${u.join(",")}`)}else{if(r!==a.Provided)throw`Invalid authentication mode - ${e.mode}`;if(!n&&l.push("clientId"),!s&&l.push("orgId"),!f&&l.push("tokenProvider"),l.length||(e.auth_key=`${n}|org-${s}`),f&&"function"!=typeof f)throw"Required parameter tokenProvider needs to be a function"}if(l.length>0)throw`Required parameter(s) ${l.join(", ")} are missing`;if(d){let{read:e,write:t}=d;if(!e)throw"Storage read method missing!";if(!t)throw"Storage write method missing!"}}(e.auth,t),e.headers=Object.assign({"x-api-key":e.auth.clientId,"x-request-id":()=>i(),"x-gw-ims-org-id":e.auth.orgId},c(e.headers))}(r,!!t);const o=n.config(r.auth,e);return(e,n={})=>function(e,t,r,n,o){return u(e,t,r,n,!1,o)}(e,n,r,o,t)}},normalizeHeaders:c,generateRequestID:i,AUTH_MODES:a}},265:e=>{async function t(e){e.disableStorage||(e.tokens=await e.read()||{},e.readOnce=!0)}function r(e,t){return void 0!==t.tokens&&t.tokens[e]&&t.tokens[e].expires_at>Date.now()?t.tokens[e]:void 0}e.exports.config=function(e,n){const o=e&&e.disableStorage||!1,s={disableStorage:o,readOnce:o,read:e.storage?e.storage.read:n.read,write:e.storage?e.storage.write:n.write,tokens:{}};return{set:(e,r)=>async function(e,r,n){return r.expires_at=Date.now()+r.expires_in-6e4,await t(n),n.tokens[e]=r,await async function(e){e.disableStorage||await e.write(e.tokens)}(n),r}(e,r,s),get:e=>async function(e,n){let o=!1;n.readOnce||(await t(n),o=!0);let s=r(e,n);return s||o?s:(await t(n),r(e,n))}(e,s)}}},390:e=>{const t="tokens";e.exports.read=async function(){return JSON.parse(window.localStorage.getItem(t))},e.exports.write=async function(e){return window.localStorage.setItem(t,JSON.stringify(e))}}},t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={exports:{}};return e[n](o,o.exports,r),o.exports}return r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(223)})(); --------------------------------------------------------------------------------