From 5ec527de02c7b9150559ed9fb8abc1bc6cbbc41d Mon Sep 17 00:00:00 2001 From: paulpascal Date: Sun, 5 May 2024 23:07:10 +0000 Subject: [PATCH] fix: db authentication options --- src/lib/api.js | 65 +++++++++++++++++++++--------------------- src/lib/db.js | 15 ++++++++-- src/lib/main.js | 6 ++-- src/lib/nools-utils.js | 13 +++------ 4 files changed, 51 insertions(+), 48 deletions(-) diff --git a/src/lib/api.js b/src/lib/api.js index 838c25158..a11bb6510 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -5,7 +5,6 @@ const archivingApi = require('./archiving-api'); const environment = require('./environment'); const log = require('./log'); const url = require('url'); -const nools = require('./nools-utils'); const cache = new Map(); @@ -18,9 +17,9 @@ const withCookieSession = (...args) => { Object.assign(options, ...args.slice(1)); } - const sessionTokenHeader = nools.sessionTokenHeader(environment); - if (sessionTokenHeader || options.headers) { - options.headers = Object.assign({}, options.headers || {}, sessionTokenHeader); + const sessionToken = environment.sessionToken; + if (sessionToken || options.headers) { + options.headers = Object.assign({}, options.headers || {}, { Cookie: sessionToken }); } return options; @@ -66,7 +65,7 @@ const logDeprecatedTransitions = (settings) => { const updateAppSettings = (settings) => { return request.put({ url: `${environment.apiUrl}/_design/medic/_rewrite/update_settings/medic?replace=1`, - headers: { 'Content-Type': 'application/json' }, + headers: {'Content-Type': 'application/json'}, body: settings, }); }; @@ -76,9 +75,9 @@ const api = { const url = `${environment.apiUrl}/_design/medic/_rewrite/app_settings/medic`; return request.get({ url, json: true }) .catch(err => { - if (err.statusCode === 404) { + if(err.statusCode === 404) { throw new Error(`Failed to fetch existing app_settings from ${url}.\n` + - ` Check that CHT API is running and that you're connecting on the correct port!`); + ` Check that CHT API is running and that you're connecting on the correct port!`); } else { throw err; } @@ -175,38 +174,38 @@ const api = { if (!this._formsValidateEndpointFound) { // The endpoint to validate forms doesn't exist in the API, // (old version), so we assume form is valid but return special result - return Promise.resolve({ ok: true, formsValidateEndpointFound: false }); + return Promise.resolve({ok: true, formsValidateEndpointFound: false}); } return request.post({ uri: `${environment.instanceUrl}/api/v1/forms/validate`, headers: { 'Content-Type': 'application/xml' }, body: formXml, }) - .then(resp => { - try { - return JSON.parse(resp); - } catch (e) { - throw new Error('Invalid JSON response validating XForm against the API: ' + resp); - } - }) - .catch(err => { - if (err.statusCode === 404) { - // The endpoint doesn't exist in the API (old CHT version), so - // we assume the form is valid but return special JSON - // highlighting the situation, and remembering the lack - // of the endpoint so next call there is no need - // to call the missed endpoint again - this._formsValidateEndpointFound = false; - return { ok: true, formsValidateEndpointFound: false }; - } - if (err.statusCode === 400 && err.error) { - throw new Error(JSON.parse(err.error).error); - } - throw err; - }); + .then(resp => { + try { + return JSON.parse(resp); + } catch (e) { + throw new Error('Invalid JSON response validating XForm against the API: ' + resp); + } + }) + .catch(err => { + if (err.statusCode === 404) { + // The endpoint doesn't exist in the API (old CHT version), so + // we assume the form is valid but return special JSON + // highlighting the situation, and remembering the lack + // of the endpoint so next call there is no need + // to call the missed endpoint again + this._formsValidateEndpointFound = false; + return {ok: true, formsValidateEndpointFound: false}; + } + if (err.statusCode === 400 && err.error) { + throw new Error(JSON.parse(err.error).error); + } + throw err; + }); }, - async getCompressibleTypes() { + async getCompressibleTypes () { const parsedUrl = new url.URL(environment.apiUrl); const baseUrl = `${parsedUrl.protocol}//${parsedUrl.username}:${parsedUrl.password}@${parsedUrl.host}`; const configUrl = `${baseUrl}/api/couch-config-attachments`; @@ -215,7 +214,7 @@ const api = { return cache.get('compressibleTypes'); } const resp = await request.get({ url: configUrl, json: true }); - const compressibleTypes = resp.compressible_types.split(',').map(s => s.trim()); + const compressibleTypes = resp.compressible_types.split(',').map(s=>s.trim()); cache.set('compressibleTypes', compressibleTypes); return compressibleTypes; } catch (e) { @@ -231,7 +230,7 @@ const api = { Object.entries(api) .filter(([key, value]) => typeof value === 'function' && !archivingApi[key]) - .forEach(([key,]) => { + .forEach(([key, ]) => { archivingApi[key] = () => { // if this error is raised, somebody forgot to add a mock // implementation to ./archiving-api.js or the action isn't diff --git a/src/lib/db.js b/src/lib/db.js index 0a8caae04..0db000568 100644 --- a/src/lib/db.js +++ b/src/lib/db.js @@ -4,13 +4,22 @@ PouchDB.plugin(require('pouchdb-mapreduce')); const ArchivingDB = require('./archiving-db'); const environment = require('./environment'); -const nools = require('./nools-utils'); module.exports = () => { if (environment.isArchiveMode) { return new ArchivingDB(environment.archiveDestination); } - const headers = nools.sessionTokenHeader(environment); - return new PouchDB(environment.apiUrl, { ajax: { timeout: 60000, headers } }); + + return new PouchDB(environment.apiUrl, { + ajax: { timeout: 60000 }, + fetch: (url, opts) => { + const sessionToken = environment.sessionToken; + if (sessionToken) { + opts.headers.set('Cookie', sessionToken); + opts.credentials = 'include'; + } + return PouchDB.fetch(url, opts); + }, + }); }; diff --git a/src/lib/main.js b/src/lib/main.js index 18233b500..79a5b18cc 100755 --- a/src/lib/main.js +++ b/src/lib/main.js @@ -172,7 +172,7 @@ module.exports = async (argv, env) => { const expectedOptions = ['alpha', projectName]; if (productionUrlMatch && !expectedOptions.includes(productionUrlMatch[1])) { warn(`Attempting to use project for \x1b[31m${projectName}\x1b[33m`, - `against non-matching instance: \x1b[31m${redactBasicAuth(environment.instanceUrl)}\x1b[33m`); + `against non-matching instance: \x1b[31m${redactBasicAuth(environment.instanceUrl)}\x1b[33m`); if (!userPrompt.keyInYN()) { throw new Error('User aborted execution.'); } @@ -182,7 +182,7 @@ module.exports = async (argv, env) => { // GO GO GO // info(`Processing config in ${projectName}.`); - info('Actions:\n -', actions.map(({ name }) => name).join('\n - ')); + info('Actions:\n -', actions.map(({name}) => name).join('\n - ')); const skipCheckForUpdates = cmdArgs.check === false; if (actions.some(action => action.name === 'check-for-updates') && !skipCheckForUpdates) { @@ -216,7 +216,7 @@ function buildActions(cmdArgs, skipValidate) { actions = actions.filter(a => a !== 'check-git'); } - if (skipValidate) { + if(skipValidate) { warn('Skipping all form validation.'); const validateActions = [ 'validate-app-forms', diff --git a/src/lib/nools-utils.js b/src/lib/nools-utils.js index b6bac3617..fa8686644 100644 --- a/src/lib/nools-utils.js +++ b/src/lib/nools-utils.js @@ -2,11 +2,11 @@ const minify = js => js.split('\n') .map(s => s.trim() - .replace(/\s*\/\/.*/, '') // single-line comments (like this one) + .replace(/\s*\/\/.*/, '') // single-line comments (like this one) ).join('') - .replace(/\s*\/\*(?:(?!\*\/).)*\*\/\s*/g, '') /* this kind of comment */ - .replace(/function \(/g, 'function(') // different node versions do function.toString() differently :\ - ; + .replace(/\s*\/\*(?:(?!\*\/).)*\*\/\s*/g, '') /* this kind of comment */ + .replace(/function \(/g, 'function(') // different node versions do function.toString() differently :\ + ; const addBoilerplateToCode = code => `define Target { _id: null, contact: null, deleted: null, type: null, pass: null, date: null, groupBy: null } define Contact { contact: null, reports: null, tasks: null } @@ -15,12 +15,7 @@ rule GenerateEvents { when { c: Contact } then { ${code} } }`; -const sessionTokenHeader = environment => { - return environment.sessionToken ? { Cookie: `${environment.sessionToken}` } : undefined; -}; - module.exports = { addBoilerplateToCode, minify, - sessionTokenHeader, };