keeweb/app/scripts/plugins/plugin-gallery.js

89 lines
2.8 KiB
JavaScript
Raw Normal View History

2019-09-15 14:16:32 +02:00
import Backbone from 'backbone';
import kdbxweb from 'kdbxweb';
import { SettingsStore } from 'comp/settings/settings-store';
import { Links } from 'const/links';
import { SignatureVerifier } from 'util/data/signature-verifier';
import { Logger } from 'util/logger';
2017-05-13 22:36:07 +02:00
const PluginGallery = {
logger: new Logger('plugin-gallery'),
gallery: null,
loading: false,
loadError: null,
loadPlugins() {
if (this.gallery) {
return Promise.resolve(this.gallery);
}
this.loading = true;
this.loadError = false;
2017-06-06 20:40:27 +02:00
const ts = this.logger.ts();
2017-05-13 22:36:07 +02:00
return new Promise(resolve => {
this.logger.debug('Loading plugins...');
const xhr = new XMLHttpRequest();
2017-05-20 12:46:21 +02:00
xhr.open('GET', Links.Plugins + '/plugins.json?_=' + Date.now());
2017-06-06 20:40:27 +02:00
xhr.responseType = 'json';
2017-05-13 22:36:07 +02:00
xhr.send();
xhr.addEventListener('load', () => {
const data = xhr.response;
2017-06-06 20:40:27 +02:00
resolve(data);
2017-05-13 22:36:07 +02:00
});
xhr.addEventListener('error', () => {
this.logger.error('Network error loading plugins');
resolve();
});
2017-06-06 20:40:27 +02:00
}).then(data => {
return this.verifySignature(data).then(gallery => {
this.loading = false;
this.loadError = !gallery;
if (gallery) {
2019-08-18 08:05:38 +02:00
this.logger.debug(
`Loaded ${gallery.plugins.length} plugins`,
this.logger.ts(ts)
);
2017-06-06 20:40:27 +02:00
this.gallery = gallery;
this.saveGallery(gallery);
}
Backbone.trigger('plugin-gallery-load-complete');
return gallery;
});
});
},
verifySignature(gallery) {
const dataToVerify = JSON.stringify(gallery, null, 2).replace(gallery.signature, '');
2019-08-18 08:05:38 +02:00
return SignatureVerifier.verify(
kdbxweb.ByteUtils.stringToBytes(dataToVerify),
gallery.signature
)
2019-08-16 23:05:39 +02:00
.then(isValid => {
if (isValid) {
return gallery;
}
this.logger.error('JSON signature invalid');
})
.catch(e => {
this.logger.error('Error verifying plugins signature', e);
});
2017-06-06 20:40:27 +02:00
},
getCachedGallery() {
const ts = this.logger.ts();
return SettingsStore.load('plugin-gallery').then(data => {
2017-12-03 01:04:04 +01:00
if (data) {
return this.verifySignature(data).then(gallery => {
this.logger.debug(`Loaded cached plugin gallery`, this.logger.ts(ts));
return gallery;
});
}
2017-05-13 22:36:07 +02:00
});
2017-06-05 11:48:03 +02:00
},
saveGallery(data) {
SettingsStore.save('plugin-gallery', data);
2017-05-13 22:36:07 +02:00
}
};
2019-09-15 14:16:32 +02:00
export { PluginGallery };