initial dotfiles added

This commit is contained in:
2021-09-23 10:31:42 +01:00
parent bf6d582ee6
commit 051caa3bbb
52 changed files with 117419 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
# If a config.py file exists, this file is ignored unless it's explicitly loaded
# via config.load_autoconfig(). For more information, see:
# https://github.com/qutebrowser/qutebrowser/blob/master/doc/help/configuring.asciidoc#loading-autoconfigyml
# DO NOT edit this file by hand, qutebrowser will overwrite it.
# Instead, create a config.py - see :help for details.
config_version: 2
settings:
content.notifications.enabled:
https://www.netflix.com: false
https://www.youtube.com: false
scrolling.bar:
global: never
scrolling.smooth:
global: true
tabs.position:
global: left
tabs.show:
global: always
tabs.width:
global: 2%
+10
View File
@@ -0,0 +1,10 @@
https://portal.stir.ac.uk/security/login.jsp?requrl=/my-portal.jsp&&user=&userid= University of Stirling Portal Login
https://www.gchq-careers.co.uk/cyberfirst/ CyberFirst Bursaries and Apprenticeships 2020-21
https://myaccount.google.com/?utm_source=sign_in_no_continue Google Account
https://drive.google.com/drive/my-drive My Drive - Google Drive
https://cloud.digitalocean.com/projects/f6cd0d83-aac5-4ea4-853b-d7a552be85d5/resources?i=c8e679 fearrising404@gmail.com project - DigitalOcean
https://www.shhhhhhboo.xyz/ # Welcome to Simon's Gemini page! (Est 09/05/2021) # About Me # Contact
https://www.discogs.com/messages/ Inbox (5)
http://192.168.1.254/00000111500/gui/#/main/ Home
http://192.168.1.125/admin/index.php Pi-hole - raspberrypi
http://www.patorjk.com/software/taag/#p=testall&f=Calvin%20S&t=%3C3%20Linux Text to ASCII Art Generator (TAAG)
+240
View File
@@ -0,0 +1,240 @@
import dracula.draw
# Autogenerated config.py
#
# NOTE: config.py is intended for advanced users who are comfortable
# with manually migrating the config file on qutebrowser upgrades. If
# you prefer, you can also configure qutebrowser using the
# :set/:bind/:config-* commands without having to write a config.py
# file.
#
# Documentation:
# qute://help/configuring.html
# qute://help/settings.html
# Change the argument to True to still load settings configured via autoconfig.yml
config.load_autoconfig(True)
##dracula
dracula.draw.blood(c, {
'spacing': {
'vertical': 6,
'horizontal': 8
}
})
# Which cookies to accept. With QtWebEngine, this setting also controls
# other features with tracking capabilities similar to those of cookies;
# including IndexedDB, DOM storage, filesystem API, service workers, and
# AppCache. Note that with QtWebKit, only `all` and `never` are
# supported as per-domain values. Setting `no-3rdparty` or `no-
# unknown-3rdparty` per-domain on QtWebKit will have the same effect as
# `all`. If this setting is used with URL patterns, the pattern gets
# applied to the origin/first party URL of the page making the request,
# not the request URL. With QtWebEngine 5.15.0+, paths will be stripped
# from URLs, so URL patterns using paths will not match. With
# QtWebEngine 5.15.2+, subdomains are additionally stripped as well, so
# you will typically need to set this setting for `example.com` when the
# cookie is set on `somesubdomain.example.com` for it to work properly.
# To debug issues with this setting, start qutebrowser with `--debug
# --logfilter network --debug-flag log-cookies` which will show all
# cookies being set.
# Type: String
# Valid values:
# - all: Accept all cookies.
# - no-3rdparty: Accept cookies from the same origin only. This is known to break some sites, such as GMail.
# - no-unknown-3rdparty: Accept cookies from the same origin only, unless a cookie is already set for the domain. On QtWebEngine, this is the same as no-3rdparty.
# - never: Don't accept cookies at all.
config.set('content.cookies.accept', 'all', 'chrome-devtools://*')
# Which cookies to accept. With QtWebEngine, this setting also controls
# other features with tracking capabilities similar to those of cookies;
# including IndexedDB, DOM storage, filesystem API, service workers, and
# AppCache. Note that with QtWebKit, only `all` and `never` are
# supported as per-domain values. Setting `no-3rdparty` or `no-
# unknown-3rdparty` per-domain on QtWebKit will have the same effect as
# `all`. If this setting is used with URL patterns, the pattern gets
# applied to the origin/first party URL of the page making the request,
# not the request URL. With QtWebEngine 5.15.0+, paths will be stripped
# from URLs, so URL patterns using paths will not match. With
# QtWebEngine 5.15.2+, subdomains are additionally stripped as well, so
# you will typically need to set this setting for `example.com` when the
# cookie is set on `somesubdomain.example.com` for it to work properly.
# To debug issues with this setting, start qutebrowser with `--debug
# --logfilter network --debug-flag log-cookies` which will show all
# cookies being set.
# Type: String
# Valid values:
# - all: Accept all cookies.
# - no-3rdparty: Accept cookies from the same origin only. This is known to break some sites, such as GMail.
# - no-unknown-3rdparty: Accept cookies from the same origin only, unless a cookie is already set for the domain. On QtWebEngine, this is the same as no-3rdparty.
# - never: Don't accept cookies at all.
config.set('content.cookies.accept', 'all', 'devtools://*')
# Value to send in the `Accept-Language` header. Note that the value
# read from JavaScript is always the global value.
# Type: String
config.set('content.headers.accept_language', '', 'https://matchmaker.krunker.io/*')
# User agent to send. The following placeholders are defined: *
# `{os_info}`: Something like "X11; Linux x86_64". * `{webkit_version}`:
# The underlying WebKit version (set to a fixed value with
# QtWebEngine). * `{qt_key}`: "Qt" for QtWebKit, "QtWebEngine" for
# QtWebEngine. * `{qt_version}`: The underlying Qt version. *
# `{upstream_browser_key}`: "Version" for QtWebKit, "Chrome" for
# QtWebEngine. * `{upstream_browser_version}`: The corresponding
# Safari/Chrome version. * `{qutebrowser_version}`: The currently
# running qutebrowser version. The default value is equal to the
# unchanged user agent of QtWebKit/QtWebEngine. Note that the value
# read from JavaScript is always the global value. With QtWebEngine
# between 5.12 and 5.14 (inclusive), changing the value exposed to
# JavaScript requires a restart.
# Type: FormatString
config.set('content.headers.user_agent', 'Mozilla/5.0 ({os_info}) AppleWebKit/{webkit_version} (KHTML, like Gecko) {upstream_browser_key}/{upstream_browser_version} Safari/{webkit_version}', 'https://web.whatsapp.com/')
# User agent to send. The following placeholders are defined: *
# `{os_info}`: Something like "X11; Linux x86_64". * `{webkit_version}`:
# The underlying WebKit version (set to a fixed value with
# QtWebEngine). * `{qt_key}`: "Qt" for QtWebKit, "QtWebEngine" for
# QtWebEngine. * `{qt_version}`: The underlying Qt version. *
# `{upstream_browser_key}`: "Version" for QtWebKit, "Chrome" for
# QtWebEngine. * `{upstream_browser_version}`: The corresponding
# Safari/Chrome version. * `{qutebrowser_version}`: The currently
# running qutebrowser version. The default value is equal to the
# unchanged user agent of QtWebKit/QtWebEngine. Note that the value
# read from JavaScript is always the global value. With QtWebEngine
# between 5.12 and 5.14 (inclusive), changing the value exposed to
# JavaScript requires a restart.
# Type: FormatString
config.set('content.headers.user_agent', 'Mozilla/5.0 ({os_info}) AppleWebKit/{webkit_version} (KHTML, like Gecko) {upstream_browser_key}/{upstream_browser_version} Safari/{webkit_version} Edg/{upstream_browser_version}', 'https://accounts.google.com/*')
# User agent to send. The following placeholders are defined: *
# `{os_info}`: Something like "X11; Linux x86_64". * `{webkit_version}`:
# The underlying WebKit version (set to a fixed value with
# QtWebEngine). * `{qt_key}`: "Qt" for QtWebKit, "QtWebEngine" for
# QtWebEngine. * `{qt_version}`: The underlying Qt version. *
# `{upstream_browser_key}`: "Version" for QtWebKit, "Chrome" for
# QtWebEngine. * `{upstream_browser_version}`: The corresponding
# Safari/Chrome version. * `{qutebrowser_version}`: The currently
# running qutebrowser version. The default value is equal to the
# unchanged user agent of QtWebKit/QtWebEngine. Note that the value
# read from JavaScript is always the global value. With QtWebEngine
# between 5.12 and 5.14 (inclusive), changing the value exposed to
# JavaScript requires a restart.
# Type: FormatString
config.set('content.headers.user_agent', 'Mozilla/5.0 ({os_info}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99 Safari/537.36', 'https://*.slack.com/*')
# Load images automatically in web pages.
# Type: Bool
config.set('content.images', True, 'chrome-devtools://*')
# Load images automatically in web pages.
# Type: Bool
config.set('content.images', True, 'devtools://*')
# Enable JavaScript.
# Type: Bool
config.set('content.javascript.enabled', True, 'chrome-devtools://*')
# Enable JavaScript.
# Type: Bool
config.set('content.javascript.enabled', True, 'devtools://*')
# Enable JavaScript.
# Type: Bool
config.set('content.javascript.enabled', True, 'chrome://*/*')
# Enable JavaScript.
# Type: Bool
config.set('content.javascript.enabled', True, 'qute://*/*')
# Allow websites to show notifications.
# Type: BoolAsk
# Valid values:
# - true
# - false
# - ask
config.set('content.notifications.enabled', False, 'https://www.reddit.com')
#config.set('colors.webpage.darkmode.enabled', True)
#config.set('colors.webpage.prefers_color_scheme_dark', True)
# variables
black = "#000000"
darkgrey = "#030303"
magenta = "#ff009e"
midgrey = "#544d4d"
pink = "#ff00f3"
red = "#ff0000"
white = "#ffffff"
yellow = "#ffdb00"
c.colors.webpage.preferred_color_scheme = 'dark'
c.content.blocking.adblock.lists = ['https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/filters-2020.txt', 'https://easylist.to/easylist/easylist.txt', 'https://easylist.to/easylist/easyprivacy.txt', 'https://easylist.to/easylist/easylist.txt', 'https://easylist.to/easylist/easyprivacy.txt', 'https://easylist-downloads.adblockplus.org/easylistdutch.txt', 'https://easylist-downloads.adblockplus.org/abp-filters-anti-cv.txt', 'https://www.i-dont-care-about-cookies.eu/abp/', 'https://secure.fanboy.co.nz/fanboy-cookiemonster.txt']
c.content.blocking.method = 'both'
#c.content.user_stylesheets = '~/.config/qutebrowser/lol.css'
config.bind('<Ctrl-m>', 'spawn mpv --volume=50 {url}')
config.bind('<Ctrl-p>', 'spawn --userscript qute-pass')
#c.colors.completion.category.bg = black
#c.colors.completion.category.bg = darkgrey
#c.colors.completion.category.border.bottom = pink
#c.colors.completion.category.border.top = darkgrey
#c.colors.completion.category.border.top = darkgrey
#c.colors.completion.category.fg = white
#c.colors.completion.category.fg = white
#c.colors.completion.even.bg = midgrey
#c.colors.completion.fg = white
#c.colors.completion.item.selected.bg = pink
#c.colors.completion.item.selected.border.bottom = c.colors.completion.category.border.top
#c.colors.completion.item.selected.border.top = c.colors.completion.item.selected.bg
#c.colors.completion.item.selected.fg = white
#c.colors.completion.match.fg = pink
#c.colors.completion.odd.bg = darkgrey
#c.colors.contextmenu.disabled.bg = darkgrey
#c.colors.contextmenu.disabled.fg = midgrey
#c.colors.contextmenu.menu.bg = darkgrey
#c.colors.contextmenu.menu.fg = white
#c.colors.contextmenu.selected.bg = pink
#c.colors.contextmenu.selected.fg = white
#c.colors.downloads.bar.bg = black
#c.colors.hints.bg = black
#c.colors.hints.fg = pink
#c.colors.hints.match.fg = white
#c.colors.statusbar.insert.bg = pink
#c.colors.tabs.bar.bg = black
#c.colors.tabs.even.bg = midgrey
#c.colors.tabs.even.fg = c.colors.tabs.odd.fg
#c.colors.tabs.odd.bg = black
#c.colors.tabs.odd.fg = white
#c.colors.tabs.pinned.even.bg = black
#c.colors.tabs.pinned.even.fg = pink
#c.colors.tabs.pinned.odd.bg = midgrey
#c.colors.tabs.pinned.odd.fg = pink
#c.colors.tabs.pinned.selected.even.bg = pink
#c.colors.tabs.pinned.selected.odd.bg = pink
#c.colors.tabs.selected.even.bg = pink
#c.colors.tabs.selected.odd.bg = pink
#c.hints.border = black
#c.colors.webpage.darkmode.enabled = False
#c.colors.webpage.darkmode.algorithm = 'lightness-cielab'
#c.colors.webpage.darkmode.grayscale.all = True
#c.colors.webpage.darkmode.grayscale.images = 0.5
#c.colors.webpage.darkmode.policy.images = 'never'
#c.colors.webpage.darkmode.policy.page = 'smart'
c.url.searchengines["g"] = "https://www.google.co.uk/search?q={}"
c.url.searchengines["ddg"] = "https://www.duckduckgo.com/?q={}"
c.url.searchengines["b"] = "https://search.brave.com/search?q={}"
c.url.searchengines["aw"] = "https://wiki.archlinux.org/?search={}"
c.url.searchengines["yt"] = "http://www.youtube.com/results?search_query={}"
c.url.searchengines["w"] = "https://en.wikipedia.org/w/index.php?search={}&title=Special:Search"
c.url.searchengines["ebay"] = "https://www.ebay.co.uk/sch/{}"
c.url.searchengines["r"] = "https://www.reddit.com/r/{}"
c.url.searchengines["ws"] = "https://www.whosampled.com/search/?q={}"
c.url.searchengines["gt"] = "https://github.com/search/?q={}"
c.url.searchengines["dic"] = "http://www.dictionary.com/browse/{}"
c.url.searchengines["ety"] = "http://www.etymonline.com/index.php?allowed_in_frame=0&search={}"
c.url.searchengines["aur"] = "https://aur.archlinux.org/packages/?O=0&K={}"
c.url.searchengines["proton"] = "https://www.protondb.com/search?q={}"
c.url.searchengines["disc"] = "https://www.discogs.com/search/?q={}"
Submodule qutebrowser/dracula added at ba5bd6589c
View File
View File
+278
View File
@@ -0,0 +1,278 @@
#!/usr/bin/env python3
# Copyright 2017 Chris Braun (cryzed) <cryzed@googlemail.com>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""
Insert login information using pass and a dmenu-compatible application (e.g. dmenu, rofi -dmenu, ...). A short
demonstration can be seen here: https://i.imgur.com/KN3XuZP.gif.
"""
USAGE = """The domain of the site has to appear as a segment in the pass path,
for example: "github.com/cryzed" or "websites/github.com". How the username and
password are determined is freely configurable using the CLI arguments. As an
example, if you instead store the username as part of the secret (and use a
site's name as filename), instead of the default configuration, use
`--username-target secret` and `--username-pattern "username: (.+)"`.
The login information is inserted by emulating key events using qutebrowser's
fake-key command in this manner: [USERNAME]<Tab>[PASSWORD], which is compatible
with almost all login forms.
If you use gopass with multiple mounts, use the CLI switch --mode gopass to switch to gopass mode.
Suggested bindings similar to Uzbl's `formfiller` script:
config.bind('<z><l>', 'spawn --userscript qute-pass')
config.bind('<z><u><l>', 'spawn --userscript qute-pass --username-only')
config.bind('<z><p><l>', 'spawn --userscript qute-pass --password-only')
config.bind('<z><o><l>', 'spawn --userscript qute-pass --otp-only')
"""
EPILOG = """Dependencies: tldextract (Python 3 module), pass, pass-otp (optional).
For issues and feedback please use: https://github.com/cryzed/qutebrowser-userscripts.
WARNING: The login details are viewable as plaintext in qutebrowser's debug log (qute://log) and might be shared if
you decide to submit a crash report!"""
import argparse
import enum
import fnmatch
import functools
import os
import re
import shlex
import subprocess
import sys
import tldextract
def expanded_path(path):
# Expand potential ~ in paths, since this script won't be called from a shell that does it for us
expanded = os.path.expanduser(path)
# Add trailing slash if not present
return os.path.join(expanded, '')
argument_parser = argparse.ArgumentParser(description=__doc__, usage=USAGE, epilog=EPILOG)
argument_parser.add_argument('url', nargs='?', default=os.getenv('QUTE_URL'))
argument_parser.add_argument('--password-store', '-p',
default=expanded_path(os.getenv('PASSWORD_STORE_DIR', default='~/.password-store')),
help='Path to your pass password-store (only used in pass-mode)', type=expanded_path)
argument_parser.add_argument('--mode', '-M', choices=['pass', 'gopass'], default="pass",
help='Select mode [gopass] to use gopass instead of the standard pass.')
argument_parser.add_argument('--username-pattern', '-u', default=r'.*/(.+)',
help='Regular expression that matches the username')
argument_parser.add_argument('--username-target', '-U', choices=['path', 'secret'], default='path',
help='The target for the username regular expression')
argument_parser.add_argument('--password-pattern', '-P', default=r'(.*)',
help='Regular expression that matches the password')
argument_parser.add_argument('--dmenu-invocation', '-d', default='rofi -dmenu',
help='Invocation used to execute a dmenu-provider')
argument_parser.add_argument('--noinsert-mode', '-n', dest='insert_mode', action='store_false',
help="Don't automatically enter insert mode")
argument_parser.add_argument('--io-encoding', '-i', default='UTF-8',
help='Encoding used to communicate with subprocesses')
argument_parser.add_argument('--merge-candidates', '-m', action='store_true',
help='Merge pass candidates for fully-qualified and registered domain name')
argument_parser.add_argument('--extra-url-suffixes', '-s', default='',
help='Comma-separated string containing extra suffixes (e.g local)')
group = argument_parser.add_mutually_exclusive_group()
group.add_argument('--username-only', '-e', action='store_true', help='Only insert username')
group.add_argument('--password-only', '-w', action='store_true', help='Only insert password')
group.add_argument('--otp-only', '-o', action='store_true', help='Only insert OTP code')
stderr = functools.partial(print, file=sys.stderr)
class ExitCodes(enum.IntEnum):
SUCCESS = 0
FAILURE = 1
# 1 is automatically used if Python throws an exception
NO_PASS_CANDIDATES = 2
COULD_NOT_MATCH_USERNAME = 3
COULD_NOT_MATCH_PASSWORD = 4
class CouldNotMatchUsername(Exception):
pass
class CouldNotMatchPassword(Exception):
pass
def qute_command(command):
with open(os.environ['QUTE_FIFO'], 'w') as fifo:
fifo.write(command + '\n')
fifo.flush()
def find_pass_candidates(domain):
candidates = []
if arguments.mode == "gopass":
all_passwords = subprocess.run(["gopass", "list", "--flat" ], stdout=subprocess.PIPE).stdout.decode("UTF-8").splitlines()
for password in all_passwords:
if domain in password:
candidates.append(password)
else:
for path, directories, file_names in os.walk(arguments.password_store, followlinks=True):
secrets = fnmatch.filter(file_names, '*.gpg')
if not secrets:
continue
# Strip password store path prefix to get the relative pass path
pass_path = path[len(arguments.password_store):]
split_path = pass_path.split(os.path.sep)
for secret in secrets:
secret_base = os.path.splitext(secret)[0]
if domain not in (split_path + [secret_base]):
continue
candidates.append(os.path.join(pass_path, secret_base))
return candidates
def _run_pass(pass_arguments):
# The executable is conveniently named after it's mode [pass|gopass].
pass_command = [arguments.mode]
env = os.environ.copy()
env['PASSWORD_STORE_DIR'] = arguments.password_store
process = subprocess.run(pass_command + pass_arguments, env=env, stdout=subprocess.PIPE)
return process.stdout.decode(arguments.io_encoding).strip()
def pass_(path):
return _run_pass(['show', path])
def pass_otp(path):
if arguments.mode == "gopass":
return _run_pass(['otp', '-o', path])
return _run_pass(['otp', path])
def dmenu(items, invocation):
command = shlex.split(invocation)
process = subprocess.run(command, input='\n'.join(items).encode(arguments.io_encoding), stdout=subprocess.PIPE)
return process.stdout.decode(arguments.io_encoding).strip()
def fake_key_raw(text):
for character in text:
# Escape all characters by default, space requires special handling
sequence = '" "' if character == ' ' else '\{}'.format(character)
qute_command('fake-key {}'.format(sequence))
def extract_password(secret, pattern):
match = re.match(pattern, secret)
if not match:
raise CouldNotMatchPassword("Pattern did not match target")
try:
return match.group(1)
except IndexError:
raise CouldNotMatchPassword("Pattern did not contain capture group, please use capture group. Example: (.*)")
def extract_username(target, pattern):
match = re.search(pattern, target, re.MULTILINE)
if not match:
raise CouldNotMatchUsername("Pattern did not match target")
try:
return match.group(1)
except IndexError:
raise CouldNotMatchUsername("Pattern did not contain capture group, please use capture group. Example: (.*)")
def main(arguments):
if not arguments.url:
argument_parser.print_help()
return ExitCodes.FAILURE
extractor = tldextract.TLDExtract(extra_suffixes=arguments.extra_url_suffixes.split(','))
extract_result = extractor(arguments.url)
# Try to find candidates using targets in the following order: fully-qualified domain name (includes subdomains),
# the registered domain name, the IPv4 address if that's what the URL represents and finally the private domain
# (if a non-public suffix was used).
candidates = set()
attempted_targets = []
private_domain = ''
if not extract_result.suffix:
private_domain = ('.'.join((extract_result.subdomain, extract_result.domain))
if extract_result.subdomain else extract_result.domain)
for target in filter(None, [extract_result.fqdn, extract_result.registered_domain, extract_result.ipv4, private_domain]):
attempted_targets.append(target)
target_candidates = find_pass_candidates(target)
if not target_candidates:
continue
candidates.update(target_candidates)
if not arguments.merge_candidates:
break
else:
if not candidates:
stderr('No pass candidates for URL {!r} found! (I tried {!r})'.format(arguments.url, attempted_targets))
return ExitCodes.NO_PASS_CANDIDATES
selection = candidates.pop() if len(candidates) == 1 else dmenu(sorted(candidates), arguments.dmenu_invocation)
# Nothing was selected, simply return
if not selection:
return ExitCodes.SUCCESS
# If username-target is path and user asked for username-only, we don't need to run pass.
# Or if using otp-only, it will run pass on its own.
secret = None
if not (arguments.username_target == 'path' and arguments.username_only) and not arguments.otp_only:
secret = pass_(selection)
username_target = selection if arguments.username_target == 'path' else secret
try:
if arguments.username_only:
fake_key_raw(extract_username(username_target, arguments.username_pattern))
elif arguments.password_only:
fake_key_raw(extract_password(secret, arguments.password_pattern))
elif arguments.otp_only:
otp = pass_otp(selection)
fake_key_raw(otp)
else:
# Enter username and password using fake-key and <Tab> (which seems to work almost universally), then switch
# back into insert-mode, so the form can be directly submitted by hitting enter afterwards
fake_key_raw(extract_username(username_target, arguments.username_pattern))
qute_command('fake-key <Tab>')
fake_key_raw(extract_password(secret, arguments.password_pattern))
except CouldNotMatchPassword as e:
stderr('Failed to match password, target: secret, error: {}'.format(e))
return ExitCodes.COULD_NOT_MATCH_PASSWORD
except CouldNotMatchUsername as e:
stderr('Failed to match username, target: {}, error: {}'.format(arguments.username_target, e))
return ExitCodes.COULD_NOT_MATCH_USERNAME
if arguments.insert_mode:
qute_command('mode-enter insert')
return ExitCodes.SUCCESS
if __name__ == '__main__':
arguments = argument_parser.parse_args()
sys.exit(main(arguments))
+278
View File
@@ -0,0 +1,278 @@
#!/usr/bin/env python3
# Copyright 2017 Chris Braun (cryzed) <cryzed@googlemail.com>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""
Insert login information using pass and a dmenu-compatible application (e.g. dmenu, rofi -dmenu, ...). A short
demonstration can be seen here: https://i.imgur.com/KN3XuZP.gif.
"""
USAGE = """The domain of the site has to appear as a segment in the pass path,
for example: "github.com/cryzed" or "websites/github.com". How the username and
password are determined is freely configurable using the CLI arguments. As an
example, if you instead store the username as part of the secret (and use a
site's name as filename), instead of the default configuration, use
`--username-target secret` and `--username-pattern "username: (.+)"`.
The login information is inserted by emulating key events using qutebrowser's
fake-key command in this manner: [USERNAME]<Tab>[PASSWORD], which is compatible
with almost all login forms.
If you use gopass with multiple mounts, use the CLI switch --mode gopass to switch to gopass mode.
Suggested bindings similar to Uzbl's `formfiller` script:
config.bind('<z><l>', 'spawn --userscript qute-pass')
config.bind('<z><u><l>', 'spawn --userscript qute-pass --username-only')
config.bind('<z><p><l>', 'spawn --userscript qute-pass --password-only')
config.bind('<z><o><l>', 'spawn --userscript qute-pass --otp-only')
"""
EPILOG = """Dependencies: tldextract (Python 3 module), pass, pass-otp (optional).
For issues and feedback please use: https://github.com/cryzed/qutebrowser-userscripts.
WARNING: The login details are viewable as plaintext in qutebrowser's debug log (qute://log) and might be shared if
you decide to submit a crash report!"""
import argparse
import enum
import fnmatch
import functools
import os
import re
import shlex
import subprocess
import sys
import tldextract
def expanded_path(path):
# Expand potential ~ in paths, since this script won't be called from a shell that does it for us
expanded = os.path.expanduser(path)
# Add trailing slash if not present
return os.path.join(expanded, '')
argument_parser = argparse.ArgumentParser(description=__doc__, usage=USAGE, epilog=EPILOG)
argument_parser.add_argument('url', nargs='?', default=os.getenv('QUTE_URL'))
argument_parser.add_argument('--password-store', '-p',
default=expanded_path(os.getenv('PASSWORD_STORE_DIR', default='~/.password-store')),
help='Path to your pass password-store (only used in pass-mode)', type=expanded_path)
argument_parser.add_argument('--mode', '-M', choices=['pass', 'gopass'], default="pass",
help='Select mode [gopass] to use gopass instead of the standard pass.')
argument_parser.add_argument('--username-pattern', '-u', default=r'.*/(.+)',
help='Regular expression that matches the username')
argument_parser.add_argument('--username-target', '-U', choices=['path', 'secret'], default='path',
help='The target for the username regular expression')
argument_parser.add_argument('--password-pattern', '-P', default=r'(.*)',
help='Regular expression that matches the password')
argument_parser.add_argument('--dmenu-invocation', '-d', default='rofi -dmenu',
help='Invocation used to execute a dmenu-provider')
argument_parser.add_argument('--noinsert-mode', '-n', dest='insert_mode', action='store_false',
help="Don't automatically enter insert mode")
argument_parser.add_argument('--io-encoding', '-i', default='UTF-8',
help='Encoding used to communicate with subprocesses')
argument_parser.add_argument('--merge-candidates', '-m', action='store_true',
help='Merge pass candidates for fully-qualified and registered domain name')
argument_parser.add_argument('--extra-url-suffixes', '-s', default='',
help='Comma-separated string containing extra suffixes (e.g local)')
group = argument_parser.add_mutually_exclusive_group()
group.add_argument('--username-only', '-e', action='store_true', help='Only insert username')
group.add_argument('--password-only', '-w', action='store_true', help='Only insert password')
group.add_argument('--otp-only', '-o', action='store_true', help='Only insert OTP code')
stderr = functools.partial(print, file=sys.stderr)
class ExitCodes(enum.IntEnum):
SUCCESS = 0
FAILURE = 1
# 1 is automatically used if Python throws an exception
NO_PASS_CANDIDATES = 2
COULD_NOT_MATCH_USERNAME = 3
COULD_NOT_MATCH_PASSWORD = 4
class CouldNotMatchUsername(Exception):
pass
class CouldNotMatchPassword(Exception):
pass
def qute_command(command):
with open(os.environ['QUTE_FIFO'], 'w') as fifo:
fifo.write(command + '\n')
fifo.flush()
def find_pass_candidates(domain):
candidates = []
if arguments.mode == "gopass":
all_passwords = subprocess.run(["gopass", "list", "--flat" ], stdout=subprocess.PIPE).stdout.decode("UTF-8").splitlines()
for password in all_passwords:
if domain in password:
candidates.append(password)
else:
for path, directories, file_names in os.walk(arguments.password_store, followlinks=True):
secrets = fnmatch.filter(file_names, '*.gpg')
if not secrets:
continue
# Strip password store path prefix to get the relative pass path
pass_path = path[len(arguments.password_store):]
split_path = pass_path.split(os.path.sep)
for secret in secrets:
secret_base = os.path.splitext(secret)[0]
if domain not in (split_path + [secret_base]):
continue
candidates.append(os.path.join(pass_path, secret_base))
return candidates
def _run_pass(pass_arguments):
# The executable is conveniently named after it's mode [pass|gopass].
pass_command = [arguments.mode]
env = os.environ.copy()
env['PASSWORD_STORE_DIR'] = arguments.password_store
process = subprocess.run(pass_command + pass_arguments, env=env, stdout=subprocess.PIPE)
return process.stdout.decode(arguments.io_encoding).strip()
def pass_(path):
return _run_pass(['show', path])
def pass_otp(path):
if arguments.mode == "gopass":
return _run_pass(['otp', '-o', path])
return _run_pass(['otp', path])
def dmenu(items, invocation):
command = shlex.split(invocation)
process = subprocess.run(command, input='\n'.join(items).encode(arguments.io_encoding), stdout=subprocess.PIPE)
return process.stdout.decode(arguments.io_encoding).strip()
def fake_key_raw(text):
for character in text:
# Escape all characters by default, space requires special handling
sequence = '" "' if character == ' ' else '\{}'.format(character)
qute_command('fake-key {}'.format(sequence))
def extract_password(secret, pattern):
match = re.match(pattern, secret)
if not match:
raise CouldNotMatchPassword("Pattern did not match target")
try:
return match.group(1)
except IndexError:
raise CouldNotMatchPassword("Pattern did not contain capture group, please use capture group. Example: (.*)")
def extract_username(target, pattern):
match = re.search(pattern, target, re.MULTILINE)
if not match:
raise CouldNotMatchUsername("Pattern did not match target")
try:
return match.group(1)
except IndexError:
raise CouldNotMatchUsername("Pattern did not contain capture group, please use capture group. Example: (.*)")
def main(arguments):
if not arguments.url:
argument_parser.print_help()
return ExitCodes.FAILURE
extractor = tldextract.TLDExtract(extra_suffixes=arguments.extra_url_suffixes.split(','))
extract_result = extractor(arguments.url)
# Try to find candidates using targets in the following order: fully-qualified domain name (includes subdomains),
# the registered domain name, the IPv4 address if that's what the URL represents and finally the private domain
# (if a non-public suffix was used).
candidates = set()
attempted_targets = []
private_domain = ''
if not extract_result.suffix:
private_domain = ('.'.join((extract_result.subdomain, extract_result.domain))
if extract_result.subdomain else extract_result.domain)
for target in filter(None, [extract_result.fqdn, extract_result.registered_domain, extract_result.ipv4, private_domain]):
attempted_targets.append(target)
target_candidates = find_pass_candidates(target)
if not target_candidates:
continue
candidates.update(target_candidates)
if not arguments.merge_candidates:
break
else:
if not candidates:
stderr('No pass candidates for URL {!r} found! (I tried {!r})'.format(arguments.url, attempted_targets))
return ExitCodes.NO_PASS_CANDIDATES
selection = candidates.pop() if len(candidates) == 1 else dmenu(sorted(candidates), arguments.dmenu_invocation)
# Nothing was selected, simply return
if not selection:
return ExitCodes.SUCCESS
# If username-target is path and user asked for username-only, we don't need to run pass.
# Or if using otp-only, it will run pass on its own.
secret = None
if not (arguments.username_target == 'path' and arguments.username_only) and not arguments.otp_only:
secret = pass_(selection)
username_target = selection if arguments.username_target == 'path' else secret
try:
if arguments.username_only:
fake_key_raw(extract_username(username_target, arguments.username_pattern))
elif arguments.password_only:
fake_key_raw(extract_password(secret, arguments.password_pattern))
elif arguments.otp_only:
otp = pass_otp(selection)
fake_key_raw(otp)
else:
# Enter username and password using fake-key and <Tab> (which seems to work almost universally), then switch
# back into insert-mode, so the form can be directly submitted by hitting enter afterwards
fake_key_raw(extract_username(username_target, arguments.username_pattern))
qute_command('fake-key <Tab>')
fake_key_raw(extract_password(secret, arguments.password_pattern))
except CouldNotMatchPassword as e:
stderr('Failed to match password, target: secret, error: {}'.format(e))
return ExitCodes.COULD_NOT_MATCH_PASSWORD
except CouldNotMatchUsername as e:
stderr('Failed to match username, target: {}, error: {}'.format(arguments.username_target, e))
return ExitCodes.COULD_NOT_MATCH_USERNAME
if arguments.insert_mode:
qute_command('mode-enter insert')
return ExitCodes.SUCCESS
if __name__ == '__main__':
arguments = argument_parser.parse_args()
sys.exit(main(arguments))