pax_global_header00006660000000000000000000000064145560212320014512gustar00rootroot0000000000000052 comment=19a6c7a84c947ab19bb428684e2c723146cc46ac numberstation-1.4.0/000077500000000000000000000000001455602123200144065ustar00rootroot00000000000000numberstation-1.4.0/.gitignore000066400000000000000000000041551455602123200164030ustar00rootroot00000000000000# Created by .ignore support plugin (hsz.mobi) ### Python template # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ /.idea *.glade~ /numberstation/numberstation.gresourcenumberstation-1.4.0/LICENSE000066400000000000000000000167441455602123200154270ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. numberstation-1.4.0/README.md000066400000000000000000000012641455602123200156700ustar00rootroot00000000000000Numberstation ============= A Gnome Authenticator clone. This generates 2fa tokens based on secrets installed. It registers as uri-handler for otpauth:// urls so they can be added from Megapixels. ![screenshot of numberstation](https://brixitcdn.net/metainfo/numberstation.png) Hub: [sr.ht/~martijnbraam/numberstation](https://sr.ht/~martijnbraam/numberstation/) Patches go to ~martijnbraam/public-inbox@lists.sr.ht, prefix with [PATCH numberstation] ## Features This application generates TOTP and HOTP tokens when supplied with otpauth urls or when manually added with the add dialog. There is also an import/export functionality that can read a file with one otpauth:// url per line.numberstation-1.4.0/build-aux/000077500000000000000000000000001455602123200163005ustar00rootroot00000000000000numberstation-1.4.0/build-aux/meson/000077500000000000000000000000001455602123200174215ustar00rootroot00000000000000numberstation-1.4.0/build-aux/meson/postinstall.py000066400000000000000000000011231455602123200223440ustar00rootroot00000000000000#!/usr/bin/env python3 from os import environ, path from subprocess import call prefix = environ.get('MESON_INSTALL_PREFIX', '/usr/local') datadir = path.join(prefix, 'share') destdir = environ.get('DESTDIR', '') if not destdir: print('Updating icon cache...') call(['gtk-update-icon-cache', '-qtf', path.join(datadir, 'icons', 'hicolor')]) print('Updating desktop database') call(['update-desktop-database', '-q', path.join(datadir, 'applications')]) print('Compiling GSettings schemas...') call(['glib-compile-schemas', path.join(datadir, 'glib-2.0', 'schemas')]) numberstation-1.4.0/contrib/000077500000000000000000000000001455602123200160465ustar00rootroot00000000000000numberstation-1.4.0/contrib/andotp.py000077500000000000000000000007231455602123200177120ustar00rootroot00000000000000#!/usr/bin/env python3 from urllib.parse import quote import json import sys items = json.load(sys.stdin) for item in items: if item["type"] != "TOTP": sys.stderr.write(f"Unknown code type {item['type']}\n") label = quote(item["label"]) secret = item["secret"] url = f"otpauth://totp/{label}?secret={secret}" if "issuer" in item and item["issuer"]: issuer = quote(item["issuer"]) url += f"&issuer={issuer}" print(url) numberstation-1.4.0/data/000077500000000000000000000000001455602123200153175ustar00rootroot00000000000000numberstation-1.4.0/data/meson.build000066400000000000000000000006021455602123200174570ustar00rootroot00000000000000install_data('org.postmarketos.Numberstation.desktop', install_dir: join_paths(get_option('datadir'), 'applications'), ) install_data(['org.postmarketos.Numberstation.appdata.xml'], install_dir : get_option('datadir') / 'metainfo') install_data('org.postmarketos.Numberstation.svg', install_dir: join_paths(get_option('datadir'), 'icons/hicolor/scalable/apps') ) numberstation-1.4.0/data/org.postmarketos.Numberstation.appdata.xml000066400000000000000000000113051455602123200256240ustar00rootroot00000000000000 org.postmarketos.Numberstation CC0-1.0 GPL-3.0 Numberstation TOTP authenticator application

A TOTP authenticator application like Google Authenticator and Gnome Authenticator

org.postmarketos.Numberstation.desktop numberstation http://brixitcdn.net/metainfo/numberstation.png https://sr.ht/~martijnbraam/numberstation https://todo.sr.ht/~martijnbraam/numberstation

Numberstation 1.4.0 * Fix TOPT being wrong when waking from sleep

Numberstation 1.3.0 * Fix the back button on the code add page * Gracefully handle doubles in URLs * Remove unused icon * Remove duplicate version from appstream data

Numberstation 1.2.0 * Enable line-wrapping for key names so the key always fits on a phone screen

Numberstation 1.1.0 * Fixed bug when loading the gresource from cwd * Fixed behavior when loading a new otpauth key through a new instance

Numberstation 1.0.1 * Made version numbers correct everywhere in the software * Updated the changelog

Numberstation 1.0.0 * Implement token import/export functionality * HOTP keys are now fully supported

Numberstation 0.5.0 * Fix urlencoding in labels (from Tom Fitzhenry) * Add purism formfactor metadata to the desktop file

Numberstation 0.4.0 * Implement form for adding keys * Add a form in the UI to manually adding keys that are not in otpurl format

Numberstation 0.3.0 * Updated metainfo

Numberstation 0.2.0 * Repurposed icon from Gnome Authenticator * Added user-visible error messages when unlocking the keyring fails or duplicate keys are added * Use icons for delete/add buttons instead of text * Fixed gresource filename in meson build files

First release

numberstation-1.4.0/data/org.postmarketos.Numberstation.desktop000066400000000000000000000005371455602123200250710ustar00rootroot00000000000000[Desktop Entry] Name=Numberstation Encoding=UTF-8 Version=1.0 Type=Application Terminal=false Exec=numberstation %u GenericName=Authenticator Icon=org.postmarketos.Numberstation Categories=GTK;GNOME;Utility X-DBUS-ServiceName=org.postmarketos.Numberstation MimeType=x-scheme-handler/otpauth; StartupNotify=true X-Purism-FormFactor=Workstation;Mobile; numberstation-1.4.0/data/org.postmarketos.Numberstation.svg000066400000000000000000001301731455602123200242170ustar00rootroot00000000000000 Adwaita Icon Template image/svg+xml GNOME Design Team Adwaita Icon Template numberstation-1.4.0/meson.build000066400000000000000000000004131455602123200165460ustar00rootroot00000000000000project('numberstation', version: '1.4.0', meson_version: '>= 0.50.0', default_options: ['warning_level=2']) dependency('libhandy-1', version: '>=1.0.0') subdir('data') subdir('numberstation') meson.add_install_script('build-aux/meson/postinstall.py') numberstation-1.4.0/numberstation/000077500000000000000000000000001455602123200173005ustar00rootroot00000000000000numberstation-1.4.0/numberstation/__init__.py000066400000000000000000000000001455602123200213770ustar00rootroot00000000000000numberstation-1.4.0/numberstation/__main__.py000066400000000000000000000031471455602123200213770ustar00rootroot00000000000000import argparse import os import gi import sys from numberstation.window import NumberstationWindow gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gio gi.require_version('Handy', '1') from gi.repository import Handy class NumberstationApplication(Gtk.Application): def __init__(self, application_id, flags, version): Gtk.Application.__init__(self, application_id=application_id, flags=flags) self.connect("activate", self.open_window) self.connect("open", self.open_url) self.version = version self.window = None def open_window(self, *args): if self.window is None: self.window = NumberstationWindow(self, self.version) self.window.present() def open_url(self, app, files, *hint): self.open_window() for file in files: self.window.import_url(file.get_uri()) self.window.build_code_list() def main(version): Handy.init() if os.path.isfile('numberstation/numberstation.gresource'): print("Using resources from cwd/numberstation") resource = Gio.resource_load("numberstation/numberstation.gresource") Gio.Resource._register(resource) elif os.path.isfile('numberstation.gresource'): print("Using resources from cwd") resource = Gio.resource_load("numberstation.gresource") Gio.Resource._register(resource) app = NumberstationApplication("org.postmarketos.Numberstation", Gio.ApplicationFlags.HANDLES_OPEN, version=version) app.run(sys.argv) if __name__ == '__main__': main('development') numberstation-1.4.0/numberstation/meson.build000066400000000000000000000016011455602123200214400ustar00rootroot00000000000000pkgdatadir = join_paths(get_option('prefix'), get_option('datadir'), meson.project_name()) moduledir = join_paths(pkgdatadir, 'numberstation') gnome = import('gnome') gnome.compile_resources('numberstation', 'numberstation.gresource.xml', gresource_bundle: true, install: true, install_dir: pkgdatadir, ) python = import('python') conf = configuration_data() conf.set('PYTHON', python.find_installation('python3').path()) conf.set('VERSION', meson.project_version()) conf.set('localedir', join_paths(get_option('prefix'), get_option('localedir'))) conf.set('pkgdatadir', pkgdatadir) configure_file( input: 'numberstation.in', output: 'numberstation', configuration: conf, install: true, install_dir: get_option('bindir') ) sources = [ '__init__.py', '__main__.py', 'window.py', 'otpurl.py', ] install_data(sources, install_dir: moduledir) numberstation-1.4.0/numberstation/numberstation.gresource.xml000066400000000000000000000003321455602123200247070ustar00rootroot00000000000000 ui/numberstation.glade ui/style.css numberstation-1.4.0/numberstation/numberstation.in000077500000000000000000000007401455602123200225260ustar00rootroot00000000000000#!@PYTHON@ import os import sys import signal import gettext VERSION = '@VERSION@' pkgdatadir = '@pkgdatadir@' localedir = '@localedir@' sys.path.insert(1, pkgdatadir) signal.signal(signal.SIGINT, signal.SIG_DFL) if __name__ == '__main__': import gi from gi.repository import Gio resource = Gio.Resource.load(os.path.join(pkgdatadir, 'numberstation.gresource')) resource._register() from numberstation import __main__ sys.exit(__main__.main(VERSION)) numberstation-1.4.0/numberstation/otpurl.py000066400000000000000000000062171455602123200212050ustar00rootroot00000000000000import sys from datetime import datetime import pyotp from urllib.parse import urlparse, parse_qs, unquote, urlencode, urlunparse import hashlib class OTPUrl: def __init__(self, url): self.url = url parts = urlparse(url) if parts.scheme != 'otpauth': raise ValueError("Not an otpauth:// url") self.type = parts.hostname if self.type not in ['totp', 'hotp']: raise ValueError("Unknown key type '{}'".format(self.type)) self.label = unquote(parts.path[1:]) qs = parse_qs(parts.query) self.secret = qs['secret'][0] self.issuer = qs['issuer'][0] if 'issuer' in qs else None self.period = int(float(qs['period'][0])) if 'period' in qs else 30 self.digits = int(float(qs['digits'][0])) if 'digits' in qs else 6 self.initial_count = int(float(qs['counter'][0])) if 'counter' in qs else 0 if 'initial_count' in qs: self.initial_count = int(float(qs['initial_count'][0])) self.digest = hashlib.sha1 if 'digest' in qs: digest = qs['digest'][0] if hasattr(hashlib, digest): self.digest = getattr(hashlib, digest) @classmethod def create(cls, name, type, secret, duration=None, length=6, counter=None): if type == 'totp': otp = pyotp.TOTP(secret, interval=duration, digits=length) elif type == 'hotp': otp = pyotp.HOTP(secret, initial_count=counter, digits=length) return cls(otp.provisioning_uri(name=name)) def get_token(self): if self.type == 'totp': totp = pyotp.TOTP(self.secret, interval=self.period, digits=self.digits, digest=self.digest) base_timestamp = totp.interval * int(datetime.now().timestamp() / totp.interval) valid_until = datetime.fromtimestamp(base_timestamp + totp.interval) return totp.now(), valid_until elif self.type == 'hotp': hotp = pyotp.HOTP(self.secret, digits=self.digits, digest=self.digest, initial_count=self.initial_count) return hotp.at(0), None else: sys.stderr.write("Unknown key format '{}'\n".format(self.type)) return None, None def get_validity(self): """Returns floating value in the range 0.0-1.0 described how long generated code will be valid relative to update period """ if self.type == 'totp': secs_left = self.period - datetime.now().timestamp() % self.period return 1.0 * secs_left / self.period else: return None def get_url(self): properties = { 'secret': self.secret, 'issuer': self.issuer, 'digits': self.digits } if self.type == 'totp': properties['period'] = self.period elif self.type == 'hotp': properties['counter'] = self.initial_count qs = urlencode(properties, doseq=True) url = urlunparse(['otpauth', self.type, '/' + self.label, '', qs, '']) return url def __repr__(self): return ''.format(self.type, self.label, self.issuer) numberstation-1.4.0/numberstation/ui/000077500000000000000000000000001455602123200177155ustar00rootroot00000000000000numberstation-1.4.0/numberstation/ui/numberstation.glade000066400000000000000000000754251455602123200236220ustar00rootroot00000000000000 1 100 6 1 10 1 100 30 1 10 300 False GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_STRUCTURE_MASK Numberstation True False vertical True False Numberstation True strict True False True False True True True True False value-increase-symbolic False True 0 codes Codes True False 12 True True True True False go-previous-symbolic False True 0 add Add 1 True True True True False open-menu-symbolic end 1 False True 0 True False True True slide-left True False vertical False No error False True 0 True True True False none True False 300 100 True False True vertical True False 12 12 12 12 12 12 True vertical 12 True False True 0 True False True False True 1 False True 1 codes Codes True False vertical True True True False True False 300 100 True False 12 12 12 12 True False end Name 0 0 True True 1 0 True False end Type 0 1 True False vertical 10 Time-based OTP True True False True True False True 0 Hash-based OTP True True False True True add_totp False True 1 1 1 True False end Secret key 0 2 True True 1 2 True False end Timer 0 3 True False end Counter 0 4 True False end Token length 0 5 True True add_length_adj 1 5 True True add_timer_adj 1 3 True True 1 4 Add True False True True 1 6 True False True True 1 7 True True 0 add Add 1 True True 1 False hamburger True False vertical True True True app.import Import False True 0 True True True app.export Export False True 1 True False False True 2 True True True app.about About False True 3 main 1 numberstation-1.4.0/numberstation/ui/style.css000066400000000000000000000003521455602123200215670ustar00rootroot00000000000000label.token-label { } label.token-code, button.token-code { font-size: 2em; font-family: monospace; } button.token-code { margin-top: 7px; } label.errorbar { background: #c00; color: white; padding: 12px; }numberstation-1.4.0/numberstation/window.py000066400000000000000000000333461455602123200211720ustar00rootroot00000000000000from base64 import b32decode from datetime import datetime from collections import namedtuple import keyring import json import gi from keyring.errors import KeyringLocked from numberstation.otpurl import OTPUrl gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GLib, GObject, Gio, Gdk, GLib gi.require_version('Handy', '1') from gi.repository import Handy class NumberstationWindow: def __init__(self, application, version): self.application = application self.version = version Handy.init() builder = Gtk.Builder() builder.add_from_resource('/org/postmarketos/Numberstation/ui/numberstation.glade') builder.connect_signals(self) css = Gio.resources_lookup_data("/org/postmarketos/Numberstation/ui/style.css", 0) self.provider = Gtk.CssProvider() self.provider.load_from_data(css.get_data()) self.provider = Gtk.CssProvider() self.provider.load_from_data(css.get_data()) self.window = builder.get_object("main_window") self.window.set_application(self.application) self.error = builder.get_object("error") self.mainstack = builder.get_object("mainstack") self.headstack = builder.get_object("headstack") self.add_name = builder.get_object("add_name") self.add_secret = builder.get_object("add_secret") self.add_totp = builder.get_object("add_totp") self.add_counter = builder.get_object("add_counter") self.add_length = builder.get_object("add_length") self.add_timer = builder.get_object("add_timer") self.add_save = builder.get_object("add_save") self.hamburgermenu = builder.get_object("hamburgermenu") self.apply_css(self.window, self.provider) self.codes_box = builder.get_object("codes_box") self.tokens = [] self.gestures = [] self.init_actions() try: all_keys = keyring.get_password('numberstation', 'totp') if all_keys is not None: for url in json.loads(all_keys): try: temp = OTPUrl(url) temp.get_token() self.tokens.append(temp) except: print("Invalid key: {}, skipping".format(url)) except KeyringLocked: self.show_error("The keyring could not be opened") print("Could not unlock the keyring") self.timers = [] self.build_code_list() GLib.timeout_add(1000, self.update_codes) self.window.show() def apply_css(self, widget, provider): Gtk.StyleContext.add_provider(widget.get_style_context(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) if isinstance(widget, Gtk.Container): widget.forall(self.apply_css, provider) def init_actions(self): action = Gio.SimpleAction.new("about", None) action.connect("activate", self.on_about) self.application.add_action(action) action = Gio.SimpleAction.new("import", None) action.connect("activate", self.on_import) self.application.add_action(action) action = Gio.SimpleAction.new("export", None) action.connect("activate", self.on_export) self.application.add_action(action) def on_main_window_destroy(self, widget): Gtk.main_quit() def show_error(self, message): self.error.set_text(message) self.error.show() def import_url(self, url): try: url = OTPUrl(url) except ValueError as e: self.show_error(str(e)) print(e) return existing = False for token in self.tokens: if token.secret == url.secret: self.show_error("The code you tried to add already exists in the database") print("The code you tried to add already exists in the database, skipping...") existing = True if not existing: self.tokens.append(url) self.save_keyring() def update_code_label(self, label, progressbar, token): code, valid_until = token.get_token() if code is None: return user_code = code paste_code = code if len(code) % 4 == 0: user_code = ' '.join([code[i:i + 4] for i in range(0, len(code), 4)]) elif len(code) % 3 == 0: user_code = ' '.join([code[i:i + 3] for i in range(0, len(code), 3)]) elif len(code) % 2 == 0: user_code = ' '.join([code[i:i + 2] for i in range(0, len(code), 2)]) if token.type == 'totp': label.set_text(user_code) else: label.set_label(user_code) label.paste_code = paste_code if valid_until: progressbar.valid_until = valid_until else: if progressbar: progressbar.valid_until = None def update_codes(self): GLib.timeout_add(1000, self.update_codes) for timer in self.timers: if timer.valid_until is None: continue if timer.valid_until < datetime.now(): self.update_code_label(timer.display, timer, timer.token) timer.set_fraction(timer.token.get_validity()) def on_long_press(self, gesture, x, y, *args): eb = gesture.eb Buttonevent = namedtuple('ButtonEvent', 'button') self.on_context_menu(eb, Buttonevent(3)) def on_context_menu(self, eventbox, event): # Only right click if event.button != 3: return popup = Gtk.Popover() popup.set_relative_to(eventbox) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) box.set_spacing(6) box.set_margin_top(12) box.set_margin_bottom(12) box.set_margin_start(12) box.set_margin_end(12) label = Gtk.Entry() label.set_text(eventbox.token.label) label.index = eventbox.index label.connect("activate", self.on_update_label) box.pack_start(label, True, True, 0) icon_del = Gtk.Image(icon_name="user-trash-symbolic") btn_del = Gtk.Button() btn_del.set_image(icon_del) btn_del.get_style_context().add_class("destructive-action") btn_del.index = eventbox.index btn_del.connect('clicked', self.on_delete) box.pack_start(btn_del, False, False, 0) popup.add(box) popup.show_all() popup.popup() def on_delete(self, widget, *args): index = widget.index del self.tokens[index] self.save_keyring() self.build_code_list() def on_update_label(self, widget, *args): new_label = widget.get_text() self.tokens[widget.index].label = new_label self.save_keyring() self.build_code_list() def build_code_list(self): for child in self.codes_box: child.destroy() for index, token in enumerate(self.tokens): eb = Gtk.EventBox() grid = Gtk.Grid() grid.set_hexpand(True) display_label = token.label if ':' in token.label: part = token.label.split(':', maxsplit=1) display_label = f"{part[0]} ({part[1]})" label = Gtk.Label(display_label) label.set_line_wrap(True) label.get_style_context().add_class('token-label') grid.attach(label, 0, 0, 1, 1) if token.type == 'totp': code = Gtk.Label("000000") elif token.type == 'hotp': code = Gtk.Button("000000") code.set_hexpand(True) code.connect('clicked', self.on_hotp_click) code.get_style_context().add_class('token-code') code.token = token grid.attach(code, 0, 1, 1, 1) timer = Gtk.ProgressBar() timer.set_hexpand(True) timer.period = token.period self.update_code_label(code, timer, token) timer.token = token timer.display = code if not hasattr(timer, 'valid_until'): continue if timer.valid_until is not None: timer.show() timer.set_no_show_all(False) timer.set_fraction(token.get_validity()) else: timer.hide() timer.set_no_show_all(True) self.timers.append(timer) grid.attach(timer, 0, 2, 1, 1) eb.add(grid) eb.connect('button-release-event', self.on_context_menu) eb.token = token eb.index = index self.num_tokens = index longpress = Gtk.GestureLongPress.new(eb) longpress.eb = eb longpress.connect('pressed', self.on_long_press) self.gestures.append(longpress) self.codes_box.pack_start(eb, True, True, False) self.apply_css(self.codes_box, self.provider) self.codes_box.show_all() def save_keyring(self): print("Saving keyring") key_urls = [] for token in self.tokens: key_urls.append(token.get_url()) password = json.dumps(key_urls) keyring.set_password('numberstation', 'totp', password) def on_add_entry_clicked(self, widget, *args): self.mainstack.set_visible_child_name('add') self.headstack.set_visible_child_name('add') def on_back_clicked(self, widget, *args): self.mainstack.set_visible_child_name('codes') self.headstack.set_visible_child_name('codes') def on_save_clicked(self, widget, *args): name = self.add_name.get_text().strip() type = 'totp' if self.add_totp.get_active() else 'hotp' secret = self.add_secret.get_text().strip() duration = self.add_timer.get_value_as_int() length = self.add_length.get_value_as_int() counter = self.add_counter.get_text().strip() if counter == '': counter = None else: counter = int(counter) url = OTPUrl.create(name=name, type=type, secret=secret, duration=duration, length=length, counter=counter) existing = False for token in self.tokens: if token.secret == url.secret: self.show_error("The code you tried to add already exists in the database") print("The code you tried to add already exists in the database, skipping...") existing = True if not existing: self.tokens.append(url) self.save_keyring() self.build_code_list() self.mainstack.set_visible_child_name('codes') self.headstack.set_visible_child_name('codes') def on_add_secret_changed(self, widget, *args): value = self.add_secret.get_text() try: b32decode(value, casefold=True) self.add_secret.get_style_context().remove_class('error') self.add_save.set_sensitive(True) except: self.add_secret.get_style_context().add_class('error') self.add_save.set_sensitive(False) def on_hamburger_clicked(self, widget, *args): self.hamburgermenu.popup() def on_about(self, *args): dialog = Gtk.AboutDialog(transient_for=self.window) dialog.set_logo_icon_name('org.postmarketos.Numberstation') dialog.set_program_name('Numberstation') dialog.set_version(self.version) dialog.set_website('https://git.sr.ht/~martijnbraam/numberstation') dialog.set_authors(['Martijn Braam']) gtk_version = '{}.{}.{}'.format(Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()) comment = "Mobile friendly TOTP application\n\n" comment += 'Gtk: {}'.format(gtk_version) dialog.set_comments(comment) text = "Distributed under the GNU GPL(v3) license.\n" dialog.set_license(text) dialog.run() dialog.destroy() def on_import(self, *args): dialog = Gtk.FileChooserDialog(title="Select a file to import", parent=self.window, action=Gtk.FileChooserAction.OPEN) dialog.add_buttons( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK ) response = dialog.run() if response == Gtk.ResponseType.OK: filename = dialog.get_filename() with open(filename, 'r') as handle: for line in handle.readlines(): if '://' in line: self.import_url(line.strip()) self.build_code_list() dialog.destroy() def on_export(self, *args): dialog = Gtk.FileChooserDialog(title="Export secrets to a file", parent=self.window, action=Gtk.FileChooserAction.SAVE) dialog.add_buttons( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE, Gtk.ResponseType.OK ) response = dialog.run() if response == Gtk.ResponseType.OK: filename = dialog.get_filename() raw = [] for token in self.tokens: raw.append(token.get_url() + "\n") with open(filename, 'w') as handle: handle.writelines(raw) dialog.destroy() def on_hotp_click(self, widget, *args): clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) clipboard.set_text(widget.get_label().replace(' ', ''), -1) widget.token.initial_count += 1 self.save_keyring() self.update_code_label(widget, None, widget.token) def present(self): self.window.present()