diff --git a/lang/js/BrowserTestExtension/index.html b/lang/js/BrowserTestExtension/index.html index c49aedae..05d413ba 100644 --- a/lang/js/BrowserTestExtension/index.html +++ b/lang/js/BrowserTestExtension/index.html @@ -1,47 +1,40 @@

gpgmejs - Tests

The unittests rely on a separately packaged version of gpgmejs, with the different classes and functions exposed. These tests and their input values can be found in gpgme/lang/js/test. They do not test the overall functionality, but the individual behaviour of the components.

The functionality tests, to be found in gpgme/lang/js/BrowserTestExtension, check the overall functionality of the standard packaged version of gpgmejs.

diff --git a/lang/js/BrowserTestExtension/openpgpModeTest.html b/lang/js/BrowserTestExtension/openpgpModeTest.html deleted file mode 100644 index e7a12be9..00000000 --- a/lang/js/BrowserTestExtension/openpgpModeTest.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - -

Openpgp mode test

-
- - - - - - - - - - - - - - diff --git a/lang/js/BrowserTestExtension/tests/inputValues_openpgpjs.js b/lang/js/BrowserTestExtension/tests/inputValues_openpgpjs.js deleted file mode 100644 index 945955be..00000000 --- a/lang/js/BrowserTestExtension/tests/inputValues_openpgpjs.js +++ /dev/null @@ -1,32 +0,0 @@ -const openpgpInputs = { - pubKeyArmored: '-----BEGIN PGP PUBLIC KEY BLOCK-----\n' - + '\n' - + 'mQENBFrsKEkBCADKw4Wt8J6M/88qD8PO6lSMCxH1cpwH8iK0uPaFFYsJkkXo7kWf\n' - + 'PTAtrV+REqF/o80dvYcdLvRsV21pvncZz/HXLu1yQ18mC3XObrKokbdgrTTKA5XE\n' - + 'BZkNsqyaMMJauT18H4hYkSg62/tTdO1cu/zWv/LFf7Xyn6+uA74ovXCJlO1s0N2c\n' - + 'PShtr98QRzPMf2owgVk37JnDNp4gGVDGHxSZOuUwxgYAZYnA8SFc+c+3ZrQfY870\n' - + '+O4j3Mz4p7yD13AwP4buQLBsb/icxekeQCqpRJhLH9f7MdEcGXa1x36RcEkHdu+M\n' - + 'yJ392eMgD+dKNfRCtyTPhjZTxvbNELIBYICfABEBAAG0EHRlc3RAZXhhbXBsZS5v\n' - + 'cmeJAVQEEwEIAD4WIQTUFzW5Ejb9uIIEjFojAWNe7/DLBQUCWuwoSQIbAwUJA8Jn\n' - + 'AAULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAKCRAjAWNe7/DLBf9kB/wOQ/S60HGw\n' - + 'Fq07W9N01HWULyhHKoMmcHL6rfZ64oDqLxolPSasz7WAMW1jN4qtWJ0mFzwO83V6\n' - + 'kaBe+wF6Kqir6udFSBW9rPcFg6/VZXPltT0a6uacIHq6DyQ5iMW4YQWbVy9OR2rN\n' - + 'GkYo1JCBR0XdRJYCSX3yB4TWv/eXnZ37/WjmiTOIZh35rjs+NuU/S5JPDfAp2/k7\n' - + '0DevQeBsv+UjVXjWpNTZmPbvDnd995uSmC6UY4hzyP84ORYMYn9n1QAR0goxDN6U\n' - + 'unOf9Rlp1oMzdxMool/d1MlCxg2h3jheuhv7lgUF4KpvHOuEPXQ7UO417E0TYcDZ\n' - + '1J8Nsv87SZeEuQENBFrsKEkBCADjoEBhG/QPqZHg8VyoD1xYRAWGxyDJkX/GrSs6\n' - + 'yE+x2hk5FoQCajxKa/d4AVxOnJpdwhAfeXeSNaql5Ejgzax+Tdj9BV6vtGVJVv0p\n' - + 'O7bgAiZxkA6RHxtNqhpPnPQoXvUzkzpRgpuL+Nj4yIg7z1ITH6KQH4u5SI9vd+j/\n' - + '8i9Taz67pdZwuJjac8qBuJHjzAo1bjYctFYUSG5pbmMQyNLySzgiNkFa4DajODlt\n' - + '3RuqVGP316Fk+Sy2+60tC/HlX8jgMyMONfOGBQx6jk8tvAphS/LAqrrNepnagIyL\n' - + 'UGKU+L8cB2g1PGGp2biBFWqZbudZoyRBet/0yH/zirBdQJw1ABEBAAGJATwEGAEI\n' - + 'ACYWIQTUFzW5Ejb9uIIEjFojAWNe7/DLBQUCWuwoSQIbDAUJA8JnAAAKCRAjAWNe\n' - + '7/DLBf0pCACPp5hBuUWngu2Hqvg+tNiujfsiYzId3MffFxEk3CbXeHcJ5F32NDJ9\n' - + 'PYCnra4L8wSv+NZt9gIa8lFwoFSFQCjzH7KE86XcV3MhfdJTNb/+9CR7Jq3e/4Iy\n' - + '0N5ip7PNYMCyakcAsxvsNCJKrSaDuYe/OAoTXRBtgRWE2uyT315em02Lkr+2Cc/Q\n' - + 'k6H+vlNOHGRgnpI/OZZjnUuUfBUvMGHr1phW+y7aeymC9PnUGdViRdJe23nntMSD\n' - + 'A+0/I7ESO9JsWvJbyBmuiZpu9JjScOjYH9xpQLqRNyw4WHpZriN69F0t9Mmd7bM1\n' - + '+UyPgbPEr0iWMeyctYsuOLeUyQKMscDT\n' - + '=QyY6\n' - + '-----END PGP PUBLIC KEY BLOCK-----\n' -}; diff --git a/lang/js/BrowserTestExtension/tests/openpgpModeTest.js b/lang/js/BrowserTestExtension/tests/openpgpModeTest.js deleted file mode 100644 index cccaf604..00000000 --- a/lang/js/BrowserTestExtension/tests/openpgpModeTest.js +++ /dev/null @@ -1,169 +0,0 @@ -/* gpgme.js - Javascript integration for gpgme - * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik - * - * This file is part of GPGME. - * - * GPGME is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * GPGME is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, see . - * SPDX-License-Identifier: LGPL-2.1+ - */ - -describe('Encrypting-Decrypting in openpgp mode, using a Message object', function () { - it('Simple Encrypt-Decrypt', function (done) { - let prm = Gpgmejs.init({api_style: 'gpgme_openpgpjs'}); - prm.then(function (context) { - context.encrypt({ - data: openpgp.message.fromText(inputvalues.encrypt.good.data), - publicKeys: inputvalues.encrypt.good.fingerprint} - ).then(function (answer) { - expect(answer).to.not.be.empty; - expect(answer).to.be.an("object"); - expect(answer.data).to.include('BEGIN PGP MESSAGE'); - expect(answer.data).to.include('END PGP MESSAGE'); - let msg = openpgp.message.fromText(answer.data); - context.decrypt({message:msg}).then(function (result) { - expect(result).to.not.be.empty; - expect(result.data).to.be.a('string'); - expect(result.data).to.equal(inputvalues.encrypt.good.data); - context._GpgME.connection.disconnect(); - done(); - }); - }); - }); - }); - it('Keys as Fingerprints', function(done){ - let prm = Gpgmejs.init({api_style: 'gpgme_openpgpjs'}); - let input = inputvalues.encrypt.good.data_nonascii; - prm.then(function (context) { - context.encrypt({ - data: input, - publicKeys: inputvalues.encrypt.good.fingerprint} - ).then(function (answer) { - expect(answer).to.not.be.empty; - expect(answer.data).to.be.a("string"); - expect(answer.data).to.include('BEGIN PGP MESSAGE'); - expect(answer.data).to.include('END PGP MESSAGE'); - context.decrypt({message:answer.data}).then(function (result) { - expect(result).to.not.be.empty; - expect(result.data).to.be.a('string'); - expect(result.data).to.equal(input); - context._GpgME.connection.disconnect(); - done(); - }); - }); - }); - }); - it('Keys as openpgp Keys', function(){ - let prm = Gpgmejs.init({api_style: 'gpgme_openpgpjs'}); - let data = inputvalues.encrypt.good.data_nonascii; - let key = openpgp.key.readArmored(openpgpInputs.pubKeyArmored); - expect(key).to.be.an('object'); - prm.then(function (context) { - context.encrypt({ - data: data, - publicKeys: [key]} - ).then( function (answer) { - expect(answer).to.not.be.empty; - expect(answer.data).to.be.a("string"); - expect(answer.data).to.include('BEGIN PGP MESSAGE'); - expect(answer.data).to.include('END PGP MESSAGE'); - context.decrypt({message:answer.data}).then( function (result){ - expect(result).to.not.be.empty; - expect(result.data).to.be.a('string'); - expect(result.data).to.equal(data); - context._GpgME.connection.disconnect(); - done(); - }); - }); - }); - }); - it('Trying to send non-implemented parameters: passwords', function(done){ - let prm = Gpgmejs.init({api_style: 'gpgme_openpgpjs'}); - let data = 'Hello World'; - let key = inputvalues.encrypt.good.fingerprint; - prm.then(function (context) { - context.encrypt({ - data: data, - publicKeys: [key], - passwords: 'My secret password'} - ).then( function(){}, - function(error){ - expect(error).to.be.an.instanceof(Error); - expect(error.code).equal('NOT_IMPLEMENTED'); - done(); - }); - }); - }); - it('Trying to send non-implemented parameters: signature', function(done){ - let prm = Gpgmejs.init({api_style: 'gpgme_openpgpjs'}); - let data = 'Hello World'; - let key = inputvalues.encrypt.good.fingerprint; - prm.then(function (context) { - context.encrypt({ - data: data, - publicKeys: [key], - signature: {any: 'value'} - }).then( - function(){}, - function(error){ - expect(error).to.be.an.instanceof(Error); - expect(error.code).equal('NOT_IMPLEMENTED'); - done(); - }); - }); - }); -}); - -describe('Keyring in openpgp mode', function(){ - it('Check Existence and structure of Keyring after init', function(done){ - let prm = Gpgmejs.init({api_style: 'gpgme_openpgpjs'}); - prm.then(function (context) { - expect(context.Keyring).to.be.an('object'); - expect(context.Keyring.getPublicKeys).to.be.a('function'); - expect(context.Keyring.deleteKey).to.be.a('function'); - expect(context.Keyring.getDefaultKey).to.be.a('function'); - done(); - }); - }); - // TODO: gpgme key interface not yet there -}); - -describe('Decrypting and verification in openpgp mode', function(){ - it('Decrypt', function(){ - let msg = openpgp.message.fromText(inputvalues.encryptedData); - let prm = Gpgmejs.init({api_style: 'gpgme_openpgpjs'}); - prm.then(function (context) { - context.decrypt({message: msg}) - .then(function(answer){ - expect(answer.data).to.be.a('string'); - expect(result.data).to.equal('¡Äußerste µ€ før ñoquis@hóme! Добрый день\n'); - done(); - }); - }); - }); - it('Decryption attempt with bad data returns gnupg error', function(done){ - let msg = openpgp.message.fromText(bigString(0.1)); - let prm = Gpgmejs.init({api_style: 'gpgme_openpgpjs'}); - prm.then(function (context) { - context.decrypt({message: msg}) - .then( function(){}, - function(error){ - expect(error).to.be.an.instanceof(Error); - expect(error.code).to.equal('GNUPG_ERROR'); - expect(error.message).to.be.a('string'); - // TBD: Type of error - done(); - }); - }); - }).timeout(4000); -}); diff --git a/lang/js/BrowserTestExtension/tests/startup.js b/lang/js/BrowserTestExtension/tests/startup.js index a5614a83..5de70a6b 100644 --- a/lang/js/BrowserTestExtension/tests/startup.js +++ b/lang/js/BrowserTestExtension/tests/startup.js @@ -1,70 +1,54 @@ /* gpgme.js - Javascript integration for gpgme * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik * * This file is part of GPGME. * * GPGME is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * GPGME is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1+ */ describe('GPGME context', function(){ it('Starting a GpgME instance', function(done){ let prm = Gpgmejs.init(); prm.then( function(context){ expect(context.connection).to.not.be.undefined; expect(context).to.be.an('object'); expect(context.connection).to.be.an('object'); expect(context.Keyring).to.be.undefined; expect(context.encrypt).to.be.a('function'); expect(context.decrypt).to.be.a('function'); done(); }, function(errorr){ expect(error).to.be.undefined; done(); }); }); }); -describe('openpgp mode', function(){ - it('startup of openpgp mode returns the correct parameters', function(done){ - let prm = Gpgmejs.init({api_style:"gpgme_openpgpjs"}); - prm.then(function(context){ - expect(context).to.be.an('object'); - expect(context.connection).to.be.undefined; - expect(context.Keyring).to.be.an('object'); - expect(context.encrypt).to.be.a('function'); - expect(context.decrypt).to.be.a('function'); - done(); - }, function(error){ - expect(error).to.be.undefined; - done(); - }); - }); -}); describe('GPGME does not start with invalid parameters', function(){ for (let i=0; i < inputvalues.init.invalid_startups.length; i++){ it('Parameter '+ i, function(done){ let prm = Gpgmejs.init(inputvalues.init.invalid_startups[i]); prm.then(function(context){ expect(context).to.be.undefined; done(); }, function(error){ expect(error).to.be.an.instanceof(Error); expect(error.code).to.equal('PARAM_WRONG'); done(); }); }) } }); \ No newline at end of file diff --git a/lang/js/CHECKLIST b/lang/js/CHECKLIST index 75664ae5..278f39dd 100644 --- a/lang/js/CHECKLIST +++ b/lang/js/CHECKLIST @@ -1,28 +1,25 @@ NativeConnection: [X] nativeConnection: successfully sending an encrypt request, receiving an answer [X] nativeConnection successfull on Chromium, chrome and firefox [*] nativeConnection successfull on Windows, macOS, Linux - [*] nativeConnection with delayed, multipart (> 1MB) answer - -replicating Openpgpjs API: + [X] nativeConnection with delayed, multipart (> 1MB) answer [*] Message handling (encrypt, decrypt verify, sign) [x] encrypt, decrypt [ ] verify [ ] sign [*] Key handling (import/export, modifying, status queries) - [ ] Configuration handling + [*] Configuration handling [ ] check for completeness - [*] handling of differences to openpgpjs Communication with other implementations [ ] option to export SECRET Key into localstore used by e.g. mailvelope Management: [*] Define the gpgme interface [x] check Permissions (e.g. csp) for the different envs [X] agree on license [*] tests diff --git a/lang/js/README b/lang/js/README index 5dc3f50b..b597adb2 100644 --- a/lang/js/README +++ b/lang/js/README @@ -1,57 +1,52 @@ gpgmejs, as contained in this directory, is a javascript library for direct use of gnupg in browsers, with the help of nativeMessaging. Installation ------------- gpgmejs uses webpack, and thus depends on nodejs for building. Webpack can be installed by running `npm install webpack webpack-cli --save-dev`. To create a current version of the package, the command is `npx webpack --config webpack.conf.js`. If you want a more debuggable (i.e. not minified) build, just change the mode in webpack.conf.js. -TODO: gpgme_openpgpjs aims to offer an API similar to openpgpjs, throwing errors -if some part of the API is not implemented, 'translating' objects if possible. -This will be incorporated into the build process later, for now it is a line to -uncomment in src/index.js - Demo WebExtension: As soon as a bundled webpack is in dist/ the gpgmejs folder can just be included in the extensions tab of the browser in questions (extension debug mode needs to be active). For chrome, selecting the folder is sufficient, for firefox, the manifest.json needs to be selected. Please note that it is just for demonstration/debug purposes! In the browsers' nativeMessaging configuration folder a file 'gpgmejs.json' is needed, with the following content: (The path to the native app gpgme-json may need adaption) Chromium: ~/.config/chromium/NativeMessagingHosts/gpgmejson.json { "name": "gpgmejson", "description": "This is a test application for gpgmejs", "path": "/usr/bin/gpgme-json", "type": "stdio", "allowed_origins": ["chrome-extension://ExtensionIdentifier/"] } The ExtensionIdentifier can be seen on the chrome://extensions page, and changes on each reinstallation. Note the slashes in allowed_origins. Firefox: ~/.mozilla/native-messaging-hosts/gpgmejson.json { "name": "gpgmejson", "description": "This is a test application for gpgmejs", "path": "/usr/bin/gpgme-json", "type": "stdio", "allowed_extensions": ["ExtensionIdentifier@temporary-addon"] } The ExtensionIdentifier can be seen as Extension ID on the about:addons page if addon-debugging is active. In firefox, the temporary addon is removed once firefox exits, and the identifier will need to be changed more often. diff --git a/lang/js/src/Config.js b/lang/js/src/Config.js index e18728de..e85bbb82 100644 --- a/lang/js/src/Config.js +++ b/lang/js/src/Config.js @@ -1,31 +1,31 @@ /* gpgme.js - Javascript integration for gpgme * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik * * This file is part of GPGME. * * GPGME is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * GPGME is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1+ */ export const availableConf = { - api_style: ['gpgme', 'gpgme_openpgpjs'], null_expire_is_never: [true, false], - unconsidered_params: ['warn','reject', 'ignore'], + // cachedKeys: Some Key info will not be queried on each invocation, + // manual refresh by Key.refresh() + cachedKeys: [true, false] }; export const defaultConf = { - api_style: 'gpgme', null_expire_is_never: false, - unconsidered_params: 'reject', + cachedKeys: false }; \ No newline at end of file diff --git a/lang/js/src/Errors.js b/lang/js/src/Errors.js index b71004a5..bfe3a2f4 100644 --- a/lang/js/src/Errors.js +++ b/lang/js/src/Errors.js @@ -1,137 +1,129 @@ /* gpgme.js - Javascript integration for gpgme * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik * * This file is part of GPGME. * * GPGME is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * GPGME is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1+ */ const err_list = { // Connection 'CONN_NO_CONNECT': { msg:'Connection with the nativeMessaging host could not be' + ' established.', type: 'error' }, 'CONN_DISCONNECTED': { msg:'Connection with the nativeMessaging host was lost.', type: 'error' }, 'CONN_EMPTY_GPG_ANSWER':{ msg: 'The nativeMessaging answer was empty.', type: 'error' }, 'CONN_TIMEOUT': { msg: 'A connection timeout was exceeded.', type: 'error' }, 'CONN_UNEXPECTED_ANSWER': { msg: 'The answer from gnupg was not as expected.', type: 'error' }, 'CONN_ALREADY_CONNECTED':{ msg: 'A connection was already established.', type: 'warning' }, // Message/Data 'MSG_INCOMPLETE': { msg: 'The Message did not match the minimum requirements for' + ' the interaction.', type: 'error' }, 'MSG_EMPTY' : { msg: 'The Message is empty.', type: 'error' }, 'MSG_WRONG_OP': { msg: 'The operation requested could not be found', type: 'error' }, 'MSG_NO_KEYS' : { msg: 'There were no valid keys provided.', type: 'warning' }, 'MSG_NOT_A_FPR': { msg: 'The String is not an accepted fingerprint', type: 'warning' }, 'KEY_INVALID': { msg:'Key object is invalid', type: 'error' }, // generic 'PARAM_WRONG':{ msg: 'Invalid parameter was found', type: 'error' }, 'PARAM_IGNORED': { msg: 'An parameter was set that has no effect in gpgmejs', type: 'warning' }, - 'NOT_IMPLEMENTED': { - msg: 'A openpgpjs parameter was submitted that is not implemented', - type: 'error' - }, - 'NOT_YET_IMPLEMENTED': { - msg: 'Support of this is probable, but it is not implemented yet', - type: 'error' - }, 'GENERIC_ERROR': { msg: 'Unspecified error', type: 'error' } }; /** * Checks the given error code and returns an error object with some * information about meaning and origin * @param {*} code Error code. Should be in err_list or 'GNUPG_ERROR' * @param {*} info Error message passed through if code is 'GNUPG_ERROR' */ export function gpgme_error(code = 'GENERIC_ERROR', info){ if (err_list.hasOwnProperty(code)){ if (err_list[code].type === 'error'){ return new GPGME_Error(code); } if (err_list[code].type === 'warning'){ console.warn(code + ': ' + err_list[code].msg); } return null; } else if (code === 'GNUPG_ERROR'){ return new GPGME_Error(code, info); } else { return new GPGME_Error('GENERIC_ERROR'); } } class GPGME_Error extends Error{ constructor(code, msg=''){ if (code === 'GNUPG_ERROR' && typeof(msg) === 'string'){ super(msg); } else if (err_list.hasOwnProperty(code)){ super(err_list[code].msg); } else { super(err_list['GENERIC_ERROR'].msg); } this.code = code || 'GENERIC_ERROR'; } set code(value){ this._code = value; } get code(){ return this._code; } } \ No newline at end of file diff --git a/lang/js/src/gpgmejs.js b/lang/js/src/gpgmejs.js index 01cb92c3..3aa5957a 100644 --- a/lang/js/src/gpgmejs.js +++ b/lang/js/src/gpgmejs.js @@ -1,192 +1,192 @@ /* gpgme.js - Javascript integration for gpgme * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik * * This file is part of GPGME. * * GPGME is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * GPGME is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1+ */ import {Connection} from "./Connection" import {GPGME_Message, createMessage} from './Message' import {toKeyIdArray} from "./Helpers" import { gpgme_error } from "./Errors" import { GPGME_Keyring } from "./Keyring"; export class GpgME { /** * initializes GpgME by opening a nativeMessaging port * TODO: add configuration */ constructor(connection){ this.connection = connection; } set connection(conn){ if (this._connection instanceof Connection){ gpgme_error('CONN_ALREADY_CONNECTED'); } else if (conn instanceof Connection){ this._connection = conn; } else { gpgme_error('PARAM_WRONG'); } } get connection(){ if (this._connection){ if (this._connection.isConnected === true){ return this._connection; } return undefined; } return undefined; } set Keyring(keyring){ - if (ring && ring instanceof GPGME_Keyring){ - this._Keyring = ring; + if (keyring && keyring instanceof GPGME_Keyring){ + this._Keyring = keyring; } } get Keyring(){ return this._Keyring; } /** * @param {String} data text/data to be encrypted as String * @param {GPGME_Key|String|Array|Array} publicKeys Keys used to encrypt the message * @param {Boolean} wildcard (optional) If true, recipient information will not be added to the message */ encrypt(data, publicKeys, base64=false, wildcard=false){ let msg = createMessage('encrypt'); if (msg instanceof Error){ return Promise.reject(msg) } // TODO temporary msg.setParameter('armor', true); msg.setParameter('always-trust', true); if (base64 === true) { msg.setParameter('base64', true); } let pubkeys = toKeyIdArray(publicKeys); msg.setParameter('keys', pubkeys); putData(msg, data); if (wildcard === true){ msg.setParameter('throw-keyids', true); }; if (msg.isComplete === true){ return this.connection.post(msg); } else { return Promise.reject(gpgme_error('MSG_INCOMPLETE')); } } /** * @param {String} data TODO base64? Message with the encrypted data * @param {Boolean} base64 (optional) Response should stay base64 * @returns {Promise} decrypted message: data: The decrypted data. This may be base64 encoded. base64: Boolean indicating whether data is base64 encoded. mime: A Boolean indicating whether the data is a MIME object. info: An optional object with extra information. * @async */ decrypt(data, base64=false){ if (data === undefined){ return Promise.reject(gpgme_error('MSG_EMPTY')); } let msg = createMessage('decrypt'); if (base64 === true){ msg.expected = 'base64'; } if (msg instanceof Error){ return Promise.reject(msg); } putData(msg, data); return this.connection.post(msg); } deleteKey(key, delete_secret = false, no_confirm = false){ return Promise.reject(gpgme_error('NOT_YET_IMPLEMENTED')); let msg = createMessage('deletekey'); if (msg instanceof Error){ return Promise.reject(msg); } let key_arr = toKeyIdArray(key); if (key_arr.length !== 1){ return Promise.reject( gpgme_error('GENERIC_ERROR')); // TBD should always be ONE key? } msg.setParameter('key', key_arr[0]); if (delete_secret === true){ msg.setParameter('allow_secret', true); // TBD } if (no_confirm === true){ //TODO: Do we want this hidden deep in the code? msg.setParameter('delete_force', true); // TBD } if (msg.isComplete === true){ this.connection.post(msg).then(function(success){ // TODO: it seems that there is always errors coming back: }, function(error){ switch (error.msg){ case 'ERR_NO_ERROR': return Promise.resolve('okay'); //TBD default: return Promise.reject(gpgme_error('TODO') ); // // INV_VALUE, // GPG_ERR_NO_PUBKEY, // GPG_ERR_AMBIGUOUS_NAME, // GPG_ERR_CONFLICT } }); } else { return Promise.reject(gpgme_error('MSG_INCOMPLETE')); } } } /** * Sets the data of the message * @param {GPGME_Message} message The message where this data will be set * @param {*} data The data to enter */ function putData(message, data){ if (!message || !message instanceof GPGME_Message ) { return gpgme_error('PARAM_WRONG'); } if (!data){ return gpgme_error('PARAM_WRONG'); } else if (typeof(data) === 'string') { message.setParameter('data', data); } else if ( typeof(data) === 'object' && typeof(data.getText) === 'function' ){ let txt = data.getText(); if (typeof(txt) === 'string'){ message.setParameter('data', txt); } else { return gpgme_error('PARAM_WRONG'); } } else { return gpgme_error('PARAM_WRONG'); } } diff --git a/lang/js/src/gpgmejs_openpgpjs.js b/lang/js/src/gpgmejs_openpgpjs.js deleted file mode 100644 index 9c8cd2cc..00000000 --- a/lang/js/src/gpgmejs_openpgpjs.js +++ /dev/null @@ -1,301 +0,0 @@ -/* gpgme.js - Javascript integration for gpgme - * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik - * - * This file is part of GPGME. - * - * GPGME is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * GPGME is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, see . - * SPDX-License-Identifier: LGPL-2.1+ - */ - -/** - * This is a compatibility API to be used as openpgpjs syntax. - * Non-implemented options will throw an error if set (not null or undefined) - * TODO Some info about differences - */ - - import { GpgME } from "./gpgmejs"; - import {GPGME_Keyring} from "./Keyring"; - import { GPGME_Key, createKey } from "./Key"; - import { isFingerprint } from "./Helpers"; - import { gpgme_error } from "./Errors"; -import { Connection } from "./Connection"; - - - export class GpgME_openpgpmode { - - constructor(connection, config = {}){ - this.initGpgME(connection, config); - } - - get Keyring(){ - if (this._keyring){ - return this._keyring; - } - return undefined; - } - - initGpgME(connection, config = {}){ - if (connection && typeof(config) ==='object'){ - this._config = config; - if (!this._GpgME){ - this._GpgME = new GpgME(connection, config); - } - if (!this._keyring){ - this._keyring = new GPGME_Keyring_openpgpmode(connection); - } - } - } - - /** - * Encrypt Message - * Supported: - * @param {String|Message} data - * an openpgp Message is accepted here. - * @param {Key|Array} publicKeys - * //Strings of Fingerprints - * @param {Boolean} wildcard - * TODO: - * @param {Key|Array} privateKeys // -> encryptsign - * @param {module:enums.compression} compression //TODO accepts integer, if 0 (no compression) it won't compress - * @param {Boolean} armor // TODO base64 switch - * @param {Boolean} detached // --> encryptsign - * unsupported: - * @param {String|Array} passwords - * @param {Object} sessionKey - * @param {Signature} signature - * @param {Boolean} returnSessionKey - * @param {String} filename - * - * Can be set, but will be ignored: - * - * @returns {Promise} - * {data: ASCII armored message, - * signature: detached signature if 'detached' is true - * } - * @async - * @static - */ - encrypt(options) { - if (!options || typeof(options) !== 'object'){ - return Promise.reject(gpgme_error('PARAM_WRONG')); - } - if (options.passwords - || options.sessionKey - || options.signature - || options.returnSessionKey - || (options.hasOwnProperty('date') && options.date !== null) - ){ - return Promise.reject(gpgme_error('NOT_IMPLEMENTED')); - } - if ( options.privateKeys - || options.compression - || (options.hasOwnProperty('armor') && options.armor === false) - || (options.hasOwnProperty('detached') && options.detached == true) - ){ - return Promise.reject(gpgme_error('NOT_YET_IMPLEMENTED')); - } - if (options.filename){ - if (this._config.unconsidered_params === 'warn'){ - gpgme_error('PARAM_IGNORED'); - } else if (this._config.unconsidered_params === 'error'){ - return Promise.reject(gpgme_error('NOT_IMPLEMENTED')); - } - } - return this._GpgME.encrypt( - options.data, options.publicKeys, options.wildcard); - } - - /** Decrypt Message - * supported openpgpjs parameters: - * @param {Message|String} message Message object from openpgpjs - * Unsupported: - * @param {String|Array} passwords - * @param {Key|Array} privateKeys - * @param {Object|Array} sessionKeys - * Not yet supported, but planned - * @param {String} format (optional) return data format either as 'utf8' or 'binary' - * @param {Signature} signature (optional) detached signature for verification - * Ignored values: can be safely set, but have no effect - * @param {Date} date - * @param {Key|Array} publicKeys - * - * @returns {Promise} decrypted and verified message in the form: - * { data:String, filename:String, signatures:[{ keyid:String, valid:Boolean }] } - * @async - * @static - */ - decrypt(options) { - if (options.passwords - || options.sessionKeys - || options.privateKeys - ){ - return Promise.reject(gpgme_error('NOT_IMPLEMENTED')); - } - if ((options.hasOwnProperty('format') && options.format !== 'utf8') - || options.signature - ){ - return Promise.reject(gpgme_error('NOT_YET_IMPLEMENTED')); - } - if ((options.hasOwnProperty('date') && options.date !== null) - || options.publicKeys - ){ - if (this._config.unconsidered_params === 'warn'){ - GPMGEJS_Error('PARAM_IGNORED'); - } else if (this._config.unconsidered_params === 'reject'){ - return Promise.reject(GPMGEJS_Error('NOT_IMPLEMENTED')); - } - } - return this._GpgME.decrypt(options.message); - - // TODO: translate between: - // openpgp: - // { data:Uint8Array|String, - // filename:String, - // signatures:[{ keyid:String, valid:Boolean }] } - // and gnupg: - // data: The decrypted data. This may be base64 encoded. - // base64: Boolean indicating whether data is base64 encoded. - // mime: A Boolean indicating whether the data is a MIME object. - // info: An optional object with extra information. - } -} - -/** - * Translation layer offering basic Keyring API to be used in Mailvelope. - * It may still be changed/expanded/merged with GPGME_Keyring - */ -class GPGME_Keyring_openpgpmode { - constructor(connection){ - this._gpgme_keyring = new GPGME_Keyring(connection); - } - - /** - * Returns a GPGME_Key Object for each Key in the gnupg Keyring. This - * includes keys openpgpjs considers 'private' (usable for signing), with - * the difference that Key.armored will NOT contain any secret information. - * Please also note that a GPGME_Key does not offer full openpgpjs- Key - * compatibility. - * @returns {Array} - * //TODO: Check if IsDefault is also always hasSecret - * TODO Check if async is required - */ - getPublicKeys(){ - return translateKeys( - this._gpgme_keyring.getKeys(null, true)); - } - - /** - * Returns the Default Key used for crypto operation in gnupg. - * Please note that the armored property does not contained secret key blocks, - * despite secret blocks being part of the key itself. - * @returns {Promise } - */ - getDefaultKey(){ - this._gpgme_keyring.getSubset({defaultKey: true}).then(function(result){ - if (result.length === 1){ - return Promise.resolve( - translateKeys(result)[0]); - } - else { - // TODO: Can there be "no default key"? - // TODO: Can there be several default keys? - return gpgme_error('TODO'); - } - }, function(error){ - //TODO - }); - } - - /** - * Deletes a Key - * @param {Object} Object identifying key - * @param {String} key.fingerprint - fingerprint of the to be deleted key - * @param {Boolean} key.secret - indicator if private key should be deleted as well - - * @returns {Promise., Error>} TBD: Not sure what is wanted - TODO @throws {Error} error.code = ‘KEY_NOT_EXIST’ - there is no key for the given fingerprint - TODO @throws {Error} error.code = ‘NO_SECRET_KEY’ - secret indicator set, but no secret key exists - */ - deleteKey(key){ - if (typeof(key) !== "object"){ - return Promise.reject(gpgme_error('PARAM_WRONG')); - } - if ( !key.fingerprint || ! isFingerprint(key.fingerprint)){ - return Promise.reject(gpgme_error('PARAM_WRONG')); - } - let key_to_delete = createKey(key.fingerprint, this._gpgme_keyring_GpgME); - return key_to_delete.deleteKey(key.secret); - } -} - -/** - * TODO error handling. - * Offers the Key information as the openpgpmode wants - */ -class GPGME_Key_openpgpmode { - constructor(value, connection){ - this.init(value, connection); - } - - /** - * Can be either constructed using an existing GPGME_Key, or a fingerprint - * and a connection - * @param {String|GPGME_Key} value - * @param {Connection} connection - */ - init (value, connection){ - if (!this._GPGME_Key && value instanceof GPGME_Key){ - this._GPGME_Key = value; - } else if (!this._GPGME_Key && isFingerprint(value) && - connection instanceof Connection){ - this._GPGME_Key = createKey(value, connection); - } - } - - get fingerprint(){ - return this._GPGME_Key.fingerprint; - } - - get armor(){ - return this._GPGME_Key.armored; - } - - get secret(){ - return this._GPGME_Key.hasSecret; - } - - get default(){ - return this._GPGME_Key.isDefault; - } -} - -/** - * creates GPGME_Key_openpgpmode from GPGME_Keys - * @param {GPGME_Key|Array} input keys - * @returns {Array} - */ -function translateKeys(input){ - //TODO: does not check if inpout is okay! - if (!input){ - return null; - } - if (!Array.isArray(input)){ - input = [input]; - } - let resultset = []; - for (let i=0; i< input.length; i++) { - resultset.push(new GPGME_Key_openpgpmode(input[i])); - } - return resultset; -} \ No newline at end of file diff --git a/lang/js/src/index.js b/lang/js/src/index.js index fc406c66..8527b3f3 100644 --- a/lang/js/src/index.js +++ b/lang/js/src/index.js @@ -1,91 +1,86 @@ /* gpgme.js - Javascript integration for gpgme * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik * * This file is part of GPGME. * * GPGME is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * GPGME is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1+ */ import { GpgME } from "./gpgmejs"; import { gpgme_error } from "./Errors"; -import { GpgME_openpgpmode } from "./gpgmejs_openpgpjs"; import { Connection } from "./Connection"; import { defaultConf, availableConf } from "./Config"; /** * Initializes a nativeMessaging Connection and returns a GPGMEjs object * @param {Object} config Configuration. See Config.js for available parameters. Still TODO */ function init(config){ let _conf = parseconfiguration(config); if (_conf instanceof Error){ return Promise.reject(_conf); } return new Promise(function(resolve, reject){ let connection = new Connection; // TODO: Delayed reaction is ugly. We need to listen to the port's // event listener in isConnected, but in some cases this takes some // time (<5ms) to disconnect if there is no successfull connection. let delayedreaction = function(){ if (connection === undefined) { reject(gpgme_error('CONN_NO_CONNECT')); } if (connection.isConnected === true){ - if (_conf.api_style && _conf.api_style === 'gpgme_openpgpjs'){ - resolve(new GpgME_openpgpmode(connection, _conf)); - } else { - resolve(new GpgME(connection)); - } + resolve(new GpgME(connection, _conf)); } else { reject(gpgme_error('CONN_NO_CONNECT')); } }; setTimeout(delayedreaction, 5); }); } function parseconfiguration(rawconfig = {}){ if ( typeof(rawconfig) !== 'object'){ return gpgme_error('PARAM_WRONG'); }; let result_config = {}; let conf_keys = Object.keys(rawconfig); for (let i=0; i < conf_keys.length; i++){ if (availableConf.hasOwnProperty(conf_keys[i])){ let value = rawconfig[conf_keys[i]]; if (availableConf[conf_keys[i]].indexOf(value) < 0){ return gpgme_error('PARAM_WRONG'); } else { result_config[conf_keys[i]] = value; } } else { return gpgme_error('PARAM_WRONG'); } } let default_keys = Object.keys(defaultConf); for (let j=0; j < default_keys.length; j++){ if (!result_config.hasOwnProperty(default_keys[j])){ result_config[default_keys[j]] = defaultConf[default_keys[j]]; } } return result_config; }; export default { init: init } \ No newline at end of file