-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathextension.js
501 lines (458 loc) · 14.1 KB
/
extension.js
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
const version = "1.1.7";
import Gdk from 'gi://Gdk';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import GObject from 'gi://GObject';
import St from 'gi://St';
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';
import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js';
import * as MessageTray from 'resource:///org/gnome/shell/ui/messageTray.js';
import {Extension, gettext as _} from 'resource:///org/gnome/shell/extensions/extension.js';
import * as Utils from './utils.js';
let pwCalc;
let uuid;
const CLIPBOARD_TYPE = St.ClipboardType.CLIPBOARD;
const PRIMARY_TYPE = St.ClipboardType.PRIMARY;
const RECENT_URL_KEY = 'recenturls';
const SHOW_COPY_NOTIFICATION_KEY = 'show-copy-notification';
const COPY_TO_CLIPBOARD_KEY = 'copy-to-clipboard';
const COPY_TO_PRIMARY_KEY = 'copy-to-primary-selection';
const KEEP_COPY_OF_ALIASES_IN_FILE_KEY = 'keep-copy-of-aliases-in-file';
const KEEP_COPY_OF_ALIASES_FILENAME_KEY = 'keep-copy-of-aliases-filename';
const DEFAULT_PASSWORD_LENGTH_KEY = 'default-password-length';
const PASSWORD_METHOD_KEY = 'password-method';
const LAST_VERSION_KEY = 'last-version';
export default class pwcalcExtension extends Extension {
//Consider this method deprecated. Only specify gettext-domain in metadata.json. GNOME Shell can automatically initiate the translation for you when it sees the gettext-domain key in metadata.json.
//ExtensionUtils.initTranslations(this.uuid);
enable() {
this._settings = this.getSettings();
uuid = this.uuid;
validate_pw_calculation();
pwCalc = new PasswordCalculator(this._settings,this);
Main.panel.addToStatusArea('pwCalc', pwCalc);
}
disable() {
pwCalc.destroy();
pwCalc = null;
this._settings = null;
}
}
let RecentAliasMenuItem = GObject.registerClass({
Signals: {
'select': {}
}
}, class RecentAliasMenuItem extends PopupMenu.PopupBaseMenuItem {
_init(text, params) {
super._init(params);
this.label = new St.Label({ text: text });
this.add_child(this.label);
}
activate(event) {
this._parent.close(true);
this.emit('select');
}
});
let SuggestionMenuItem = GObject.registerClass({
Signals: {
'select': {}
}
}, class SuggestionMenuItem extends PopupMenu.PopupBaseMenuItem {
_init(text, params) {
super._init(params);
this.label = new St.Label({ text: text });
this.add_child(this.label);
}
activate(event) {
this.emit('select');
}
});
let PasswordCalculator = GObject.registerClass(
class PasswordCalculator extends PanelMenu.Button {
_init(_settings,ext) {
super._init(0, 'PasswordCalculator', false);
this.settings=_settings;
this.ext=ext;
this.suggestionsItems=[];
this.loadConfig();
this.compat_password_method();
this.setupUI();
this.updateRecentURL();
}
setupUI() {
this.iconActor = new St.Icon({ icon_name: 'dialog-password-symbolic', style_class: 'system-status-icon' });
this.add_child(this.iconActor);
let topSection = new PopupMenu.PopupMenuSection();
let bottomSection = new PopupMenu.PopupMenuSection();
this.headingLabel = new St.Label({ text:_("Password Calculator"), style_class: "heading", can_focus:false });
this.urlCombo = new PopupMenu.PopupSubMenuMenuItem("");
this.urlText = new St.Entry({
name: "searchEntry",
hint_text: _("alias"),
track_hover: true,
can_focus: true,
style_class: "search-entry first"
});
let self=this;
this.urlText.clutter_text.connect('key-release-event', function(o,e) {
self.urlChanged.apply(self,[o,e]);
});
this.secretText = new St.Entry({
name: "searchEntry",
hint_text: _("secret"),
track_hover: true,
can_focus: true,
style_class: "search-entry last"
});
this.secretText.clutter_text.connect('text-changed', function(o,e) {
self.secretChanged.apply(self,[o,e]);
});
this.secretText.clutter_text.connect('key-release-event', function(o,e) {
self.gen.apply(self,[o,e]);
});
this.pwdText = new St.Label({style_class: "pwd", can_focus:false});
topSection.box.add_child(this.headingLabel);
topSection.box.add_child(this.urlText);
bottomSection.box.add_child(this.secretText);
bottomSection.box.add_child(this.pwdText);
topSection.box.add_style_class_name("pwCalc");
bottomSection.box.add_style_class_name("pwCalc");
this.menu.addMenuItem(topSection);
this.menu.addMenuItem(bottomSection);
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
this.menu.addMenuItem(this.urlCombo);
let item = new PopupMenu.PopupMenuItem(_("Settings"));
item.connect('activate', function(sender,open) {
self.ext.openPreferences();
});
this.menu.addMenuItem(item);
this.menu.connect('open-state-changed', function(sender,open) {
self.clear();
if (!open) self.urlText.clutter_text.grab_key_focus();
});
}
secretChanged(o,e) {
let st = this.secretText;
let sec = st.get_text();
let pwc='';
if (sec!="") pwc='\u25cf'; // ● U+25CF BLACK CIRCLE
st.clutter_text.set_password_char(pwc);
}
compat_password_method() {
let type = this.PasswordMethod;
let keys = this.recentURL;
if (this.LastVersion == "undefined" && type == "HMAC_SHA1") {
this.PasswordMethod = "HMAC_SHA1_INEXACT";
console.info(uuid + ": Setting password-method to HMC-SHA1_INEXACT, since it is the method used before.");
} else if (type == "__compat__") {
if (keys.length>0) {
this.PasswordMethod = "SHA1";
console.info(uuid + ": Initializing password-method to SHA1 due to preexisting aliases");
} else {
this.PasswordMethod = "HMAC_SHA1";
}
}
this.LastVersion = version;
}
urlChanged(o,e) {
var urls;
this.gen(o);
if (e.get_key_symbol() == Gdk.KEY_Return)
this.secretText.clutter_text.grab_key_focus();
else {
let url = this.urlText.get_text();
if (url.length>0)
urls = this.recentURL.filter(u => u.toLowerCase().indexOf(url.toLowerCase())!=-1);
}
this.updateSuggestions(urls);
}
gen(o,e) {
let url = this.urlText.get_text();
let sec = this.secretText.get_text();
if ((url!="")&&(sec!="")) {
let len = this.DefaultPasswordLength;
let type = this.PasswordMethod;
let calc = calculatePassword[type];
if (calc === undefined) return;
let pwd = calc(sec, url, len);
this.pwdText.set_text(this.obfuscate(pwd));
if (e && e.get_key_symbol() == Gdk.KEY_Return) {
this.copyAndSendNotification(pwd, url);
this.addRecentURL(url);
this.menu.hide();
}
} else {
this.pwdText.set_text(_("your password"));
}
}
obfuscate(text) {
let len = text.length;
let showcount;
if (len<=8) showcount=1;
else if (len<=12) showcount=2;
else if (len<=16) showcount=3;
else showcount=4;
return text.substring(0,showcount)+Array(len+1-2*showcount).join("\u00B7")+text.substring(len-showcount);
}
addRecentURL(url) {
var a=this.recentURL;
if (a.indexOf(url)<0) {
a.push(url);
a.sort();
this.recentURL=a;
}
}
copyAndSendNotification(pwd, url) {
let clipboard = St.Clipboard.get_default();
if (this.CopyToClipboard) {
clipboard.set_text(CLIPBOARD_TYPE,pwd);
if (this.ShowCopyNotification) showMessage(_("Password copied to clipboard."), url);
}
if (this.CopyToPrimarySelection) {
clipboard.set_text(PRIMARY_TYPE,pwd);
if (this.ShowCopyNotification) showMessage(_("Password copied to primary selection."), url);
}
}
clear() {
this.urlText.set_text("");
this.secretText.set_text("");
this.pwdText.set_text(_("your password"));
this.updateSuggestions();
}
updateSuggestions(list) {
this.suggestionsItems.forEach(i=>this.menu.box.remove_child(i));
this.suggestionsItems=[];
if (list!=null) {
list = removeDuplicates(list);
let N=list.length;
if (N>8) N=8;
for (let i=0;i<N;i++) {
let item = new SuggestionMenuItem(list[i]);
item.add_style_class_name("pwCalcSuggestion");
this.menu.addMenuItem(item,i+1);
item.connect('select', () => { this.urlSelected(list[i]); });
this.suggestionsItems.push(item);
}
}
}
updateRecentURL() {
let list = this.recentURL;
list = removeDuplicates(list);
this.urlCombo.menu.removeAll();
for (let i=0;i<list.length;i++) {
let item = new RecentAliasMenuItem(list[i]);
this.urlCombo.menu.addMenuItem(item, i);
item.connect('select', () => { this.urlSelected(list[i]); });
}
let labeltext;
if (list.length==0) labeltext=_("No Recent Aliases");
else labeltext=_("Recent Aliases");
this.urlCombo.label.set_text(labeltext);
}
urlSelected(URL) {
this.updateSuggestions();
this.urlText.set_text(URL);
this.secretText.clutter_text.grab_key_focus();
}
loadConfig() {
let self = this;
this._settingsC = this.settings.connect("changed::"+RECENT_URL_KEY,function(a,key) {
if (self.KeepCopyOfAliasesInFile) {
let fn=self.KeepCopyOfAliasesFilename;
let json=JSON.stringify(self.recentURL,null,"\t");
let success=GLib.file_set_contents(fn,json+"\n");
if (success==false) console.error(uuid + ": Unable to write to file "+fn);
}
});
}
get recentURL() {
var js=this.getString(RECENT_URL_KEY);
var obj;
try {
obj=JSON.parse(js);
} catch(e) {
obj=[];
}
return obj;
}
set recentURL(v)
{
var json=JSON.stringify(v);
if (json!==this.getString(RECENT_URL_KEY)) {
this.settings.set_string(RECENT_URL_KEY,json);
this.updateRecentURL();
}
}
getBool(key)
{
return this.settings.get_boolean(key);
}
getInteger(key)
{
return this.settings.get_int(key);
}
getString(key)
{
return this.settings.get_string(key);
}
setString(key,value)
{
return this.settings.set_string(key,value);
}
get ShowCopyNotification() {
return this.getBool(SHOW_COPY_NOTIFICATION_KEY);
}
get CopyToClipboard() {
return this.getBool(COPY_TO_CLIPBOARD_KEY);
}
get CopyToPrimarySelection() {
return this.getBool(COPY_TO_PRIMARY_KEY);
}
get DefaultPasswordLength() {
return this.getInteger(DEFAULT_PASSWORD_LENGTH_KEY);
}
get LastVersion() {
return this.getString(LAST_VERSION_KEY);
}
set LastVersion(v) {
return this.setString(LAST_VERSION_KEY,v);
}
get PasswordMethod() {
return this.getString(PASSWORD_METHOD_KEY);
}
set PasswordMethod(v) {
return this.setString(PASSWORD_METHOD_KEY,v);
}
get KeepCopyOfAliasesInFile() {
return this.getBool(KEEP_COPY_OF_ALIASES_IN_FILE_KEY);
}
get KeepCopyOfAliasesFilename() {
return this.getString(KEEP_COPY_OF_ALIASES_FILENAME_KEY);
}
});
function removeDuplicates(a) {
var b = {};
for (var i = 0; i < a.length; i++)
b[a[i]] = a[i];
var c = [];
for (var key in b)
c.push(key);
return c;
}
function showMessage(text, url) {
let source = new MessageTray.Source({
title: _('Password Calculator'),
iconName: 'dialog-password-symbolic',
});
Main.messageTray.add(source);
let notification = new MessageTray.Notification({
source: source,
title: 'Password for '+url,
body: text,
});
source.addNotification(notification);
}
function hex2bytearray(hex) {
var array = hex.match(/.{2}/g);
var bytes = new Uint8Array(20);
for (var i = 0; i < array.length; i++)
bytes[i] = parseInt(array[i], 16);
return bytes;
}
function hex2string(hex) {
var array = hex.match(/.{2}/g);
var bytes = new Uint8Array(20);
for (var i = 0; i < array.length; i++)
bytes[i] = parseInt(array[i], 16);
return String.fromCharCode.apply(null, bytes);
}
function string2bytearray(str) {
var bytes = new Uint8Array(str.length);
for (var i = 0; i < str.length; i++) {
bytes[i]=str.charCodeAt(i);
}
return bytes;
}
function FilledArray(len,value) {
var a=new Uint8Array(len);
for (var i=0;i<len;i++)
a[i]=value;
return a;
}
function sha1bytes(text) {
var c = new GLib.Checksum(GLib.ChecksumType.SHA1);
c.update(text);
//return c.get_digest();
return hex2bytearray(c.get_string());
}
function sha1string(text) {
var c = new GLib.Checksum(GLib.ChecksumType.SHA1);
c.update(text);
return c.get_string();
}
function uint8array_concat(a,b) {
return new Uint8Array([...a, ...b]);
}
var calculatePassword={
SHA1: function(secret, domain, length) {
if (secret==""||domain=="") return "";
var text = secret + domain;
var sha1 = sha1bytes(text);
var base64 = GLib.base64_encode(sha1);
return base64.substring(0, length);
},
HMAC_SHA1: function(secret, domain, length) {
if (secret==""||domain=="") return "";
var i_key_b = FilledArray(64,0x36);
var o_key_b = FilledArray(64,0x5c);
var i, j, sha1;
secret = string2bytearray(Utils.Utf8.encode(secret));
domain = string2bytearray(Utils.Utf8.encode(domain));
if (secret.length > 64)
secret = sha1string(secret);
for (i = 0; i < secret.length; i++) {
i_key_b[i] ^= secret[i];
o_key_b[i] ^= secret[i];
}
sha1 = sha1bytes(uint8array_concat(i_key_b,domain));
sha1 = sha1bytes(uint8array_concat(o_key_b,sha1));
var base64 = GLib.base64_encode(sha1);
return base64.substring(0, length);
},
HMAC_SHA1_INEXACT: function(secret, domain, length) {
if (secret==""||domain=="") return "";
var i_key_b = FilledArray(64,0x36);
var o_key_b = FilledArray(64,0x5c);
var i, j, sha1;
secret = string2bytearray(Utils.Utf8.encode(secret));
domain = string2bytearray(Utils.Utf8.encode(domain));
if (secret.length > 64)
secret = sha1sting(secret);
for (i = 0, j = secret.length; i < j; i += 1) {
i_key_b[i] ^= secret[i];
o_key_b[i] ^= secret[i];
}
sha1 = string2bytearray(sha1string(uint8array_concat(i_key_b,domain)));
sha1 = sha1bytes(uint8array_concat(o_key_b,sha1));
var base64 = GLib.base64_encode(sha1);
return base64.substring(0, length);
}
};
function error_pw_validation(type, ref, val) {
if (ref!=val)
console.error(uuid + ": Test "+type+" failed: reference value is "+ref + " but calculated " + val);
else
console.info(uuid + ": Test "+type+" success.");
}
function validate_pw_calculation() {
let sha1_ref = "pFWU9V+5Ns6ie+4F";
let hmac_sha1_ref = "p2FCQnf42dGKh5JU";
let hmac_sha1_inexact_ref = "gT7nAfjjcnOQDUIc";
let sha1_val = calculatePassword.SHA1("secret","domain",16);
let hmac_sha1_val = calculatePassword.HMAC_SHA1("secret","domain",16);
let hmac_sha1_inexact_val = calculatePassword.HMAC_SHA1_INEXACT("secret","domain",16);
error_pw_validation("SHA1", sha1_ref,sha1_val);
error_pw_validation("HMAC_SHA1", hmac_sha1_ref, hmac_sha1_val);
error_pw_validation("HMAC_SHA1_INEXACT", hmac_sha1_inexact_ref, hmac_sha1_inexact_val);
}