Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add autotyping #2

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/workflows/package.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Package

on: [push]

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Package
run: make release
- name: Upload workflow artifact
uses: actions/upload-artifact@v1
with:
name: gopass.alfredworkflow
path: gopass.alfredworkflow
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea
*.iml
gopass.alfredworkflow
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
release:
zip -r ../gopass.alfredworkflow *
rm -f ../gopass.alfredworkflow
zip -r ./gopass.alfredworkflow ./* -x@alfred_package.ignore
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
Workflow to interact with gopass from [Alfred 3](https://www.alfredapp.com/workflows/) on MacOS.
You will need an Alfred 3 license in order to use workflows.
Currently querying entries and copying username or password to clipboard is supported.

## Screenshot

![gopass alfred screenshot](./screenshot.png)
Expand All @@ -11,6 +12,58 @@ Currently querying entries and copying username or password to clipboard is supp

Download the [latest release package](https://github.com/gopasspw/gopass-alfred/releases/latest) from github or build your own via `make release` in checked out repository.

## Autotyping

The plugin can also type a username / password combination automatically. You can start the action by issuing `gpa` in Alfred.

By default, a field called `autotype` will be used. The value can contain various statements.

Example: `user :tab :pass`

### Trigger Options

However, there are more options:

| Option | Effect |
|---------------|-------------------------------------------------------------------------------|
| user / pass | A field name (not prefixed with `:`. Can reference any other available field. |
| `:tab` | Issues a tab key |
| `:enter` | Enter key |
| `:space` | Space key |
| `:delete` | Delete key |
| `:delay` | Waits one second before continuing |
| `:clearField` | Clears the current input field (Issues Ctrl+A + backspace) |

A rather typical example looks like the following:

```
myPassword
---
autotype: :clearField user :tab pass :tab :tab :enter :delay :someYk :enter
user: myUsername
usernamePassword: user :tab pass
```

### Custom autotype options

You might have noted `:someYk` as option which was not listed in the table above. Not all commands can be hardcoded in a table like the one above. For example, you might have a form that requires a one-time-password such as from a YubiKey. You might be able to retrieve the information from a `bash` command - however.

Those commands can be put to a `.gopass_autotype_handlers.json` json file. It can be place in `$XDG_CONFIG`, which defaults to your `HOME` directory. Example: `/users/someUser/.gopass_autotype_handlers.json`

An example file content looks like the following:

```json
{
":someYk": "/usr/local/bin/ykman oath code | grep \"YubiKey:name\" | sed 's/.*\\([0-9]\\{6\\}\\)$/\\1/g'"
}
```

This example will retrieve a current TOTP token from the YubiKey by asking `ykman` for the current value and converts the output to the token.

### Autotyping other fields than `autotype`

The `gpa` command will always run the `autotype` field. However, you can also use `gpf` to autotype any available field in the gopass file. This also includes the trigger options from the table above.

## Development

Contributions to this project are welcome!
5 changes: 5 additions & 0 deletions alfred_package.ignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.idea
.env
.git
*.iml
.github
2 changes: 1 addition & 1 deletion get_password.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3

import subprocess
import sys
Expand Down
118 changes: 118 additions & 0 deletions gopass_autotype.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
#!/usr/bin/env python3

import json
import os
import subprocess
import sys
import time
from os.path import expanduser

home = expanduser("~")
my_env = os.environ.copy()
my_env['PATH'] = '/usr/local/bin:{}'.format(my_env['PATH'])

special_autotype_handlers = {
":tab": lambda: do_stroke(48),
":space": lambda: do_stroke(49),
":enter": lambda: do_stroke(36),
":delete": lambda: do_stroke(51),
":delay": lambda: time.sleep(1),
":clearField": lambda: clear_field_content()
}


def get_additional_autotype_handlers_filename():
base_path = os.getenv("XDG_CONFIG", home)
return '{base_path}/{filename}'.format(base_path=base_path, filename=".gopass_autotype_handlers.json")


def load_additional_autotype_handlers_config():
handlers_path = get_additional_autotype_handlers_filename()
if os.path.exists(handlers_path):
with open(handlers_path) as f:
return json.load(f)
else:
return {}
Comment on lines +24 to +35
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure why we need this?

What's supposed to be in the .gopass_autotype_handlers.json file?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added a bit of extra documentation. In the end it allows to include output from external commands in the autotype command. I explicitly use it to type YubiKey TOTP tokens in authentication forms, so I don't have to do it manually. It allows to fill forms completely, without any manual interaction (as long as you can code any part as bash commands)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general there is an updated documentation for the autotyping, also including the special commands and the additional handlers. Maybe that makes it more clear on how it works.



def execute_additional_autotype_handler(command):
command_result = os.popen(command).read()
do_type(command_result)


def load_additional_autotype_handlers():
config = load_additional_autotype_handlers_config()
return dict(map(lambda item: (item[0], lambda: execute_additional_autotype_handler(item[1])), config.items()))


def all_autotype_handlers():
additional = load_additional_autotype_handlers()
return {**additional, **special_autotype_handlers}


def do_type(to_type):
os.system(f"echo 'tell application \"System Events\" to keystroke \"{to_type}\"' | osascript")


def do_stroke(stroke):
os.system(f"echo 'tell application \"System Events\" to key code \"{stroke}\"' | osascript")


def clear_field_content():
os.system("""echo 'tell application "System Events" to keystroke "a" using command down' | osascript""")
do_stroke(51)
Comment on lines +61 to +63
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not convinced how this is actually clearing a field? Isn't it just adding 51 times a char a to the field?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well this is a bit special - how do you clear a field only from the command line? What I came up with is just issue a Ctrl+a and issue a backspace.
You can find the full reference of available keystrokes here.



def get_gopass_data_for(query):
return subprocess.run(["gopass", "show", "-f", query], stdout=subprocess.PIPE, env=my_env).stdout.decode("utf-8")


def parse_gopass_data(data):
lines = data.split("\n")
password = lines[0]
non_empty_lines = list(filter(lambda line: len(line) > 0, lines))
lines_splitted = map(lambda line: line.split(": "), non_empty_lines[1:])
lines_with_two_items = filter(lambda elements: len(elements) == 2, lines_splitted)
items_dict = {item[0]: item[1] for item in lines_with_two_items}
items_dict["pass"] = password
return items_dict


def autotype(items, field):
autotype = items.get(field)
handlers = all_autotype_handlers()
if autotype is None:
return
to_type = autotype.split(" ")
for word in to_type:
handler = handlers.get(word)
if handler is None:
mapped = items.get(word)
do_type(word if mapped is None else mapped)
else:
handler()


def autotype_list(path, parsed):
return [
{
"uid": result,
"title": result,
"subtitle": path,
"arg": f"{path} {result}",
"autocomplete": result
} for result in parsed.keys()
]


action = sys.argv[1]
path = sys.argv[2].split(" ")

data = get_gopass_data_for(path[0])
parsed = parse_gopass_data(data)
autotype_action = "autotype" if len(path) == 1 else path[1]

if action == 'list':
print(json.dumps({'items': autotype_list(path[0], parsed)}))
elif action == 'autotype':
autotype(parsed, autotype_action)
4 changes: 2 additions & 2 deletions gopass_filter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3

import os
import sys
Expand All @@ -22,7 +22,7 @@
"title": result.split('/')[-1],
"subtitle": '/'.join(result.split('/')[:-1]),
"arg": result,
"match": " ".join(set(re.split('[. /\-]', result))) + ' ' + result,
"match": " ".join(set(re.split('[. /\-_]', result))) + ' ' + " ".join(set(re.split('[/]', result))) + ' ' + result,
"autocomplete": result
} for result in stdout.decode('ascii').splitlines()
]
Expand Down
Loading