Imported Upstream version 1.12.0
[platform/upstream/gpgme.git] / lang / js / src / Message.js
1 /* gpgme.js - Javascript integration for gpgme
2  * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik
3  *
4  * This file is part of GPGME.
5  *
6  * GPGME is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation; either version 2.1 of
9  * the License, or (at your option) any later version.
10  *
11  * GPGME is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this program; if not, see <http://www.gnu.org/licenses/>.
18  * SPDX-License-Identifier: LGPL-2.1+
19  *
20  * Author(s):
21  *     Maximilian Krambach <mkrambach@intevation.de>
22  */
23
24 import { permittedOperations } from './permittedOperations';
25 import { gpgme_error } from './Errors';
26 import { Connection } from './Connection';
27
28 /**
29  * Initializes a message for gnupg, validating the message's purpose with
30  *   {@link permittedOperations} first
31  * @param {String} operation
32  * @returns {GPGME_Message} The Message object
33  */
34 export function createMessage (operation){
35     if (typeof (operation) !== 'string'){
36         throw gpgme_error('PARAM_WRONG');
37     }
38     if (permittedOperations.hasOwnProperty(operation)){
39         return new GPGME_Message(operation);
40     } else {
41         throw gpgme_error('MSG_WRONG_OP');
42     }
43 }
44
45 /**
46  * A Message collects, validates and handles all information required to
47  * successfully establish a meaningful communication with gpgme-json via
48  * [Connection.post]{@link Connection#post}. The definition on which
49  * communication is available can be found in {@link permittedOperations}.
50  * @class
51  * @protected
52  */
53 export class GPGME_Message {
54
55     constructor (operation){
56         this._msg = {
57             op: operation,
58             chunksize: 1023* 1024
59         };
60         this._expected = null;
61     }
62
63     get operation (){
64         return this._msg.op;
65     }
66
67     set expected (value){
68         if (value === 'uint8' || value === 'base64'){
69             this._expected = value;
70         }
71     }
72
73     get expected () {
74         return this._expected;
75     }
76     /**
77      * The maximum size of responses from gpgme in bytes. As of September 2018,
78      * most browsers will only accept answers up to 1 MB of size.
79      * Everything above that threshold will not pass through
80      * nativeMessaging; answers that are larger need to be sent in parts.
81      * The lower limit is set to 10 KB. Messages smaller than the threshold
82      * will not encounter problems, larger messages will be received in
83      * chunks. If the value is not explicitly specified, 1023 KB is used.
84      */
85     set chunksize (value){
86         if (
87             Number.isInteger(value) &&
88             value > 10 * 1024 &&
89             value <= 1024 * 1024
90         ){
91             this._msg.chunksize = value;
92         }
93     }
94
95     get chunksize (){
96         return this._msg.chunksize;
97     }
98
99     /**
100      * Returns the prepared message after their parameters and the completion
101      * of required parameters have been checked.
102      * @returns {Object|null} Object to be posted to gnupg, or null if
103      * incomplete
104      */
105     get message () {
106         if (this.isComplete() === true){
107             return this._msg;
108         } else {
109             return null;
110         }
111     }
112
113     /**
114      * Sets a parameter for the message. It validates with
115      * {@link permittedOperations}
116      * @param {String} param Parameter to set
117      * @param {any} value Value to set
118      * @returns {Boolean} True if the parameter was set successfully.
119      * Throws errors if the parameters don't match the message operation
120      */
121     setParameter ( param,value ){
122         if (!param || typeof (param) !== 'string'){
123             throw gpgme_error('PARAM_WRONG');
124         }
125         let po = permittedOperations[this._msg.op];
126         if (!po){
127             throw gpgme_error('MSG_WRONG_OP');
128         }
129         let poparam = null;
130         if (po.required.hasOwnProperty(param)){
131             poparam = po.required[param];
132         } else if (po.optional.hasOwnProperty(param)){
133             poparam = po.optional[param];
134         } else {
135             throw gpgme_error('PARAM_WRONG');
136         }
137         // check incoming value for correctness
138         let checktype = function (val){
139             switch (typeof (val)){
140             case 'string':
141                 if (poparam.allowed.indexOf(typeof (val)) >= 0
142                         && val.length > 0) {
143                     return true;
144                 }
145                 throw gpgme_error('PARAM_WRONG');
146             case 'number':
147                 if (
148                     poparam.allowed.indexOf('number') >= 0
149                         && isNaN(value) === false){
150                     return true;
151                 }
152                 throw gpgme_error('PARAM_WRONG');
153
154             case 'boolean':
155                 if (poparam.allowed.indexOf('boolean') >= 0){
156                     return true;
157                 }
158                 throw gpgme_error('PARAM_WRONG');
159             case 'object':
160                 if (Array.isArray(val)){
161                     if (poparam.array_allowed !== true){
162                         throw gpgme_error('PARAM_WRONG');
163                     }
164                     for (let i=0; i < val.length; i++){
165                         let res = checktype(val[i]);
166                         if (res !== true){
167                             return res;
168                         }
169                     }
170                     if (val.length > 0) {
171                         return true;
172                     }
173                 } else if (val instanceof Uint8Array){
174                     if (poparam.allowed.indexOf('Uint8Array') >= 0){
175                         return true;
176                     }
177                     throw gpgme_error('PARAM_WRONG');
178                 } else {
179                     throw gpgme_error('PARAM_WRONG');
180                 }
181                 break;
182             default:
183                 throw gpgme_error('PARAM_WRONG');
184             }
185         };
186         let typechecked = checktype(value);
187         if (typechecked !== true){
188             return typechecked;
189         }
190         if (poparam.hasOwnProperty('allowed_data')){
191             if (poparam.allowed_data.indexOf(value) < 0){
192                 return gpgme_error('PARAM_WRONG');
193             }
194         }
195         this._msg[param] = value;
196         return true;
197     }
198
199
200     /**
201      * Check if the message has the minimum requirements to be sent, that is
202      * all 'required' parameters according to {@link permittedOperations}.
203      * @returns {Boolean} true if message is complete.
204      */
205     isComplete (){
206         if (!this._msg.op){
207             return false;
208         }
209         let reqParams = Object.keys(
210             permittedOperations[this._msg.op].required);
211         let msg_params = Object.keys(this._msg);
212         for (let i=0; i < reqParams.length; i++){
213             if (msg_params.indexOf(reqParams[i]) < 0){
214                 return false;
215             }
216         }
217         return true;
218     }
219
220     /**
221      * Sends the Message via nativeMessaging and resolves with the answer.
222      * @returns {Promise<Object>} GPGME response
223      * @async
224      */
225     post (){
226         let me = this;
227         return new Promise(function (resolve, reject) {
228             if (me.isComplete() === true) {
229
230                 let conn  = new Connection;
231                 conn.post(me).then(function (response) {
232                     resolve(response);
233                 }, function (reason) {
234                     reject(reason);
235                 });
236             }
237             else {
238                 reject(gpgme_error('MSG_INCOMPLETE'));
239             }
240         });
241     }
242
243 }