aboutsummaryrefslogtreecommitdiffstats
path: root/lang/js/src/Key.js
blob: 2800ae9ac553c51786bd00c2a82da7e213768312 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
/* 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 <http://www.gnu.org/licenses/>.
 * SPDX-License-Identifier: LGPL-2.1+
 *
 * Author(s):
 *     Maximilian Krambach <[email protected]>
 */

import { isFingerprint, isLongId } from './Helpers';
import { gpgme_error } from './Errors';
import { createMessage } from './Message';

/**
 * Validates the given fingerprint and creates a new {@link GPGME_Key}
 * @param {String} fingerprint
 * @param {Boolean} async If True, Key properties (except fingerprint) will be
 * queried from gnupg on each call, making the operation up-to-date, the
 * answers will be Promises, and the performance will likely suffer
 * @param {Object} data additional initial properties this Key will have. Needs
 * a full object as delivered by gpgme-json
 * @returns {Object|GPGME_Error} The verified and updated data
 */
export function createKey (fingerprint, async = false, data){
    if (!isFingerprint(fingerprint) || typeof (async) !== 'boolean'){
        return gpgme_error('PARAM_WRONG');
    }
    if (data !== undefined){
        data = validateKeyData(fingerprint, data);
    }
    if (data instanceof Error){
        return gpgme_error('KEY_INVALID');
    } else {
        return new GPGME_Key(fingerprint, async, data);
    }
}

/**
 * Represents the Keys as stored in the gnupg backend
 * It allows to query almost all information defined in gpgme Key Objects
 * Refer to {@link validKeyProperties} for available information, and the gpgme
 * documentation on their meaning
 * (https://www.gnupg.org/documentation/manuals/gpgme/Key-objects.html)
 *
 * @class
 */
class GPGME_Key {

    constructor (fingerprint, async, data){

        /**
         * @property {Boolean} If true, most answers will be asynchronous
         */
        this._async = async;

        this._data = { fingerprint: fingerprint.toUpperCase() };
        if (data !== undefined
            && data.fingerprint.toUpperCase() === this._data.fingerprint
        ) {
            this._data = data;
        }
    }

    /**
     * Query any property of the Key listed in {@link validKeyProperties}
     * @param {String} property property to be retreived
     * @returns {Boolean| String | Date | Array | Object |GPGME_Error}
     * the value of the property. If the Key is set to Async, the value
     * will be fetched from gnupg and resolved as a Promise. If Key is not
     * async, the armored property is not available (it can still be
     * retrieved asynchronously by {@link Key.getArmor})
     */
    get (property) {
        if (this._async === true) {
            switch (property){
            case 'armored':
                return this.getArmor();
            case 'hasSecret':
                return this.getGnupgSecretState();
            default:
                return getGnupgState(this.fingerprint, property);
            }
        } else {
            if (property === 'armored') {
                return gpgme_error('KEY_ASYNC_ONLY');
            }
            // eslint-disable-next-line no-use-before-define
            if (!validKeyProperties.hasOwnProperty(property)){
                return gpgme_error('PARAM_WRONG');
            } else {
                return (this._data[property]);
            }
        }
    }

    /**
     * Reloads the Key information from gnupg. This is only useful if you
     * use the GPGME_Keys cached. Note that this is a performance hungry
     * operation. If you desire more than a few refreshs, it may be
     * advisable to run {@link Keyring.getKeys} instead.
     * @returns {Promise<GPGME_Key|GPGME_Error>}
     * @async
     */
    refreshKey () {
        let me = this;
        return new Promise(function (resolve, reject) {
            if (!me._data.fingerprint){
                reject(gpgme_error('KEY_INVALID'));
            }
            let msg = createMessage('keylist');
            msg.setParameter('sigs', true);
            msg.setParameter('keys', me._data.fingerprint);
            msg.post().then(function (result){
                if (result.keys.length === 1){
                    const newdata = validateKeyData(
                        me._data.fingerprint, result.keys[0]);
                    if (newdata instanceof Error){
                        reject(gpgme_error('KEY_INVALID'));
                    } else {
                        me._data = newdata;
                        me.getGnupgSecretState().then(function (){
                            me.getArmor().then(function (){
                                resolve(me);
                            }, function (error){
                                reject(error);
                            });
                        }, function (error){
                            reject(error);
                        });
                    }
                } else {
                    reject(gpgme_error('KEY_NOKEY'));
                }
            }, function (error) {
                reject(gpgme_error('GNUPG_ERROR'), error);
            });
        });
    }

    /**
     * Query the armored block of the Key directly from gnupg. Please note
     * that this will not get you any export of the secret/private parts of
     * a Key
     * @returns {Promise<String|GPGME_Error>}
     * @async
     */
    getArmor () {
        const me = this;
        return new Promise(function (resolve, reject) {
            if (!me._data.fingerprint){
                reject(gpgme_error('KEY_INVALID'));
            }
            let msg = createMessage('export');
            msg.setParameter('armor', true);
            msg.setParameter('keys', me._data.fingerprint);
            msg.post().then(function (result){
                resolve(result.data);
            }, function (error){
                reject(error);
            });
        });
    }

    /**
     * Find out if the Key is part of a Key pair including public and
     * private key(s). If you want this information about more than a few
     * Keys in synchronous mode, it may be advisable to run
     * {@link Keyring.getKeys} instead, as it performs faster in bulk
     * querying this state.
     * @returns {Promise<Boolean|GPGME_Error>} True if a private Key is
     * available in the gnupg Keyring.
     * @async
     */
    getGnupgSecretState (){
        const me = this;
        return new Promise(function (resolve, reject) {
            if (!me._data.fingerprint){
                reject(gpgme_error('KEY_INVALID'));
            } else {
                let msg = createMessage('keylist');
                msg.setParameter('keys', me._data.fingerprint);
                msg.setParameter('secret', true);
                msg.post().then(function (result){
                    me._data.hasSecret = null;
                    if (
                        result.keys &&
                        result.keys.length === 1 &&
                        result.keys[0].secret === true
                    ) {
                        me._data.hasSecret = true;
                        resolve(true);
                    } else {
                        me._data.hasSecret = false;
                        resolve(false);
                    }
                }, function (error){
                    reject(error);
                });
            }
        });
    }

    /**
     * Deletes the (public) Key from the GPG Keyring. Note that a deletion
     * of a secret key is not supported by the native backend.
     * @returns {Promise<Boolean|GPGME_Error>} Success if key was deleted,
     * rejects with a GPG error otherwise.
     */
    delete (){
        const me = this;
        return new Promise(function (resolve, reject){
            if (!me._data.fingerprint){
                reject(gpgme_error('KEY_INVALID'));
            }
            let msg = createMessage('delete');
            msg.setParameter('key', me._data.fingerprint);
            msg.post().then(function (result){
                resolve(result.success);
            }, function (error){
                reject(error);
            });
        });
    }

    /**
     * @returns {String} The fingerprint defining this Key. Convenience getter
     */
    get fingerprint (){
        return this._data.fingerprint;
    }
}

/**
 * Representing a subkey of a Key.
 * @class
 * @protected
 */
class GPGME_Subkey {

    /**
     * Initializes with the json data sent by gpgme-json
     * @param {Object} data
     * @private
     */
    constructor (data){
        this._data = {};
        let keys = Object.keys(data);
        const me = this;

        /**
         * Validates a subkey property against {@link validSubKeyProperties} and
         * sets it if validation is successful
         * @param {String} property
         * @param {*} value
         * @param private
         */
        const setProperty = function (property, value){
            // eslint-disable-next-line no-use-before-define
            if (validSubKeyProperties.hasOwnProperty(property)){
                // eslint-disable-next-line no-use-before-define
                if (validSubKeyProperties[property](value) === true) {
                    if (property === 'timestamp' || property === 'expires'){
                        me._data[property] = new Date(value * 1000);
                    } else {
                        me._data[property] = value;
                    }
                }
            }
        };
        for (let i=0; i< keys.length; i++) {
            setProperty(keys[i], data[keys[i]]);
        }
    }

    /**
     * Fetches any information about this subkey
     * @param {String} property Information to request
     * @returns {String | Number | Date}
     */
    get (property) {
        if (this._data.hasOwnProperty(property)){
            return (this._data[property]);
        }
    }

}

/**
 * Representing user attributes associated with a Key or subkey
 * @class
 * @protected
 */
class GPGME_UserId {

    /**
     * Initializes with the json data sent by gpgme-json
     * @param {Object} data
     * @private
     */
    constructor (data){
        this._data = {};
        const me = this;
        let keys = Object.keys(data);
        const setProperty = function (property, value){
            // eslint-disable-next-line no-use-before-define
            if (validUserIdProperties.hasOwnProperty(property)){
                // eslint-disable-next-line no-use-before-define
                if (validUserIdProperties[property](value) === true) {
                    if (property === 'last_update'){
                        me._data[property] = new Date(value*1000);
                    } else {
                        me._data[property] = value;
                    }
                }
            }
        };
        for (let i=0; i< keys.length; i++) {
            setProperty(keys[i], data[keys[i]]);
        }
    }

    /**
     * Fetches information about the user
     * @param {String} property Information to request
     * @returns {String | Number}
     */
    get (property) {
        if (this._data.hasOwnProperty(property)){
            return (this._data[property]);
        }
    }

}

/**
 * Validation definition for userIds. Each valid userId property is represented
 * as a key- Value pair, with their value being a validation function to check
 * against
 * @protected
 * @const
 */
const validUserIdProperties = {
    'revoked': function (value){
        return typeof (value) === 'boolean';
    },
    'invalid':  function (value){
        return typeof (value) === 'boolean';
    },
    'uid': function (value){
        if (typeof (value) === 'string' || value === ''){
            return true;
        }
        return false;
    },
    'validity': function (value){
        if (typeof (value) === 'string'){
            return true;
        }
        return false;
    },
    'name': function (value){
        if (typeof (value) === 'string' || value === ''){
            return true;
        }
        return false;
    },
    'email': function (value){
        if (typeof (value) === 'string' || value === ''){
            return true;
        }
        return false;
    },
    'address': function (value){
        if (typeof (value) === 'string' || value === ''){
            return true;
        }
        return false;
    },
    'comment': function (value){
        if (typeof (value) === 'string' || value === ''){
            return true;
        }
        return false;
    },
    'origin':  function (value){
        return Number.isInteger(value);
    },
    'last_update':  function (value){
        return Number.isInteger(value);
    }
};

/**
 * Validation definition for subKeys. Each valid userId property is represented
 * as a key-value pair, with the value being a validation function
 * @protected
 * @const
 */
const validSubKeyProperties = {
    'invalid': function (value){
        return typeof (value) === 'boolean';
    },
    'can_encrypt': function (value){
        return typeof (value) === 'boolean';
    },
    'can_sign': function (value){
        return typeof (value) === 'boolean';
    },
    'can_certify':  function (value){
        return typeof (value) === 'boolean';
    },
    'can_authenticate':  function (value){
        return typeof (value) === 'boolean';
    },
    'secret': function (value){
        return typeof (value) === 'boolean';
    },
    'is_qualified': function (value){
        return typeof (value) === 'boolean';
    },
    'is_cardkey':  function (value){
        return typeof (value) === 'boolean';
    },
    'is_de_vs':  function (value){
        return typeof (value) === 'boolean';
    },
    'pubkey_algo_name': function (value){
        return typeof (value) === 'string';
        // TODO: check against list of known?['']
    },
    'pubkey_algo_string': function (value){
        return typeof (value) === 'string';
        // TODO: check against list of known?['']
    },
    'keyid': function (value){
        return isLongId(value);
    },
    'pubkey_algo': function (value) {
        return (Number.isInteger(value) && value >= 0);
    },
    'length': function (value){
        return (Number.isInteger(value) && value > 0);
    },
    'timestamp': function (value){
        return (Number.isInteger(value) && value > 0);
    },
    'expires': function (value){
        return (Number.isInteger(value) && value > 0);
    }
};

/**
 * Validation definition for Keys. Each valid Key property is represented
 * as a key-value pair, with their value being a validation function. For
 * details on the meanings, please refer to the gpgme documentation
 * https://www.gnupg.org/documentation/manuals/gpgme/Key-objects.html#Key-objects
 * @param {String} fingerprint
 * @param {Boolean} revoked
 * @param {Boolean} expired
 * @param {Boolean} disabled
 * @param {Boolean} invalid
 * @param {Boolean} can_encrypt
 * @param {Boolean} can_sign
 * @param {Boolean} can_certify
 * @param {Boolean} can_authenticate
 * @param {Boolean} secret
 * @param {Boolean}is_qualified
 * @param {String} protocol
 * @param {String} issuer_serial
 * @param {String} issuer_name
 * @param {Boolean} chain_id
 * @param {String} owner_trust
 * @param {Date} last_update
 * @param {String} origin
 * @param {Array<GPGME_Subkey>} subkeys
 * @param {Array<GPGME_UserId>} userids
 * @param {Array<String>} tofu
 * @param {Boolean} hasSecret
 * @protected
 * @const
 */
const validKeyProperties = {
    'fingerprint': function (value){
        return isFingerprint(value);
    },
    'revoked': function (value){
        return typeof (value) === 'boolean';
    },
    'expired': function (value){
        return typeof (value) === 'boolean';
    },
    'disabled': function (value){
        return typeof (value) === 'boolean';
    },
    'invalid': function (value){
        return typeof (value) === 'boolean';
    },
    'can_encrypt': function (value){
        return typeof (value) === 'boolean';
    },
    'can_sign': function (value){
        return typeof (value) === 'boolean';
    },
    'can_certify': function (value){
        return typeof (value) === 'boolean';
    },
    'can_authenticate': function (value){
        return typeof (value) === 'boolean';
    },
    'secret': function (value){
        return typeof (value) === 'boolean';
    },
    'is_qualified': function (value){
        return typeof (value) === 'boolean';
    },
    'protocol': function (value){
        return typeof (value) === 'string';
        // TODO check for implemented ones
    },
    'issuer_serial': function (value){
        return typeof (value) === 'string';
    },
    'issuer_name': function (value){
        return typeof (value) === 'string';
    },
    'chain_id': function (value){
        return typeof (value) === 'string';
    },
    'owner_trust': function (value){
        return typeof (value) === 'string';
    },
    'last_update': function (value){
        return (Number.isInteger(value));
        // TODO undefined/null possible?
    },
    'origin': function (value){
        return (Number.isInteger(value));
    },
    'subkeys': function (value){
        return (Array.isArray(value));
    },
    'userids': function (value){
        return (Array.isArray(value));
    },
    'tofu': function (value){
        return (Array.isArray(value));
    },
    'hasSecret': function (value){
        return typeof (value) === 'boolean';
    }

};

/**
* sets the Key data in bulk. It can only be used from inside a Key, either
* during construction or on a refresh callback.
* @param {Object} key the original internal key data.
* @param {Object} data Bulk set the data for this key, with an Object structure
* as sent by gpgme-json.
* @returns {Object|GPGME_Error} the changed data after values have been set,
* an error if something went wrong.
* @private
*/
function validateKeyData (fingerprint, data){
    const key = {};
    if (!fingerprint || typeof (data) !== 'object' || !data.fingerprint
     || fingerprint !== data.fingerprint.toUpperCase()
    ){
        return gpgme_error('KEY_INVALID');
    }
    let props = Object.keys(data);
    for (let i=0; i< props.length; i++){
        if (!validKeyProperties.hasOwnProperty(props[i])){
            return gpgme_error('KEY_INVALID');
        }
        // running the defined validation function
        if (validKeyProperties[props[i]](data[props[i]]) !== true ){
            return gpgme_error('KEY_INVALID');
        }
        switch (props[i]){
        case 'subkeys':
            key.subkeys = [];
            for (let i=0; i< data.subkeys.length; i++) {
                key.subkeys.push(
                    new GPGME_Subkey(data.subkeys[i]));
            }
            break;
        case 'userids':
            key.userids = [];
            for (let i=0; i< data.userids.length; i++) {
                key.userids.push(
                    new GPGME_UserId(data.userids[i]));
            }
            break;
        case 'last_update':
            key[props[i]] = new Date( data[props[i]] * 1000 );
            break;
        default:
            key[props[i]] = data[props[i]];
        }
    }
    return key;
}

/**
 * Fetches and sets properties from gnupg
 * @param {String} fingerprint
 * @param {String} property to search for.
 * @private
 * @async
 */
function getGnupgState (fingerprint, property){
    return new Promise(function (resolve, reject) {
        if (!isFingerprint(fingerprint)) {
            reject(gpgme_error('KEY_INVALID'));
        } else {
            let msg = createMessage('keylist');
            msg.setParameter('keys', fingerprint);
            msg.post().then(function (res){
                if (!res.keys || res.keys.length !== 1){
                    reject(gpgme_error('KEY_INVALID'));
                } else {
                    const key = res.keys[0];
                    let result;
                    switch (property){
                    case 'subkeys':
                        result = [];
                        if (key.subkeys.length){
                            for (let i=0; i < key.subkeys.length; i++) {
                                result.push(
                                    new GPGME_Subkey(key.subkeys[i]));
                            }
                        }
                        resolve(result);
                        break;
                    case 'userids':
                        result = [];
                        if (key.userids.length){
                            for (let i=0; i< key.userids.length; i++) {
                                result.push(
                                    new GPGME_UserId(key.userids[i]));
                            }
                        }
                        resolve(result);
                        break;
                    case 'last_update':
                        if (key.last_update === undefined){
                            reject(gpgme_error('CONN_UNEXPECTED_ANSWER'));
                        } else if (key.last_update !== null){
                            resolve(new Date( key.last_update * 1000));
                        } else {
                            resolve(null);
                        }
                        break;
                    default:
                        if (!validKeyProperties.hasOwnProperty(property)){
                            reject(gpgme_error('PARAM_WRONG'));
                        } else {
                            if (key.hasOwnProperty(property)){
                                resolve(key[property]);
                            } else {
                                reject(gpgme_error(
                                    'CONN_UNEXPECTED_ANSWER'));
                            }
                        }
                        break;
                    }
                }
            }, function (error){
                reject(gpgme_error(error));
            });
        }
    });
}