op-hello 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+ # The v0.2.1 release tag predates this workflow. This lets the initial
8
+ # release be published manually without moving or recreating that tag.
9
+ workflow_dispatch:
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ jobs:
15
+ publish:
16
+ name: Build and publish
17
+ runs-on: ubuntu-latest
18
+ permissions:
19
+ contents: read
20
+ id-token: write # Required for PyPI trusted publishing.
21
+
22
+ steps:
23
+ - uses: actions/checkout@v6
24
+ with:
25
+ fetch-depth: 0
26
+
27
+ - name: Install uv
28
+ uses: astral-sh/setup-uv@v7
29
+ with:
30
+ enable-cache: true
31
+
32
+ - name: Set up Python
33
+ run: uv python install
34
+
35
+ - name: Build package
36
+ run: uv build
37
+
38
+ - name: Publish to PyPI
39
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,6 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ dist/
6
+ *.egg-info/
@@ -0,0 +1,50 @@
1
+ # op-hello agent guide
2
+
3
+ ## Purpose
4
+
5
+ `op-hello` is a portable Python library and CLI for reading 1Password `op://`
6
+ references. Applications should use `op_hello.read`, `op_hello.resolve`, and
7
+ `op_hello.clear_cache`; do not duplicate its platform/authentication logic.
8
+
9
+ ## Architecture and behavior
10
+
11
+ - Reader order: optional 1Password service-account SDK, native `op` CLI, the
12
+ packaged platform helper, then the WSL `op.exe` fallback.
13
+ - Linux/macOS use the shell helper and the native 1Password CLI. Windows uses
14
+ PowerShell, Windows Hello integration, and DPAPI-protected disk caching.
15
+ - The process cache is keyed by account and reference. `read()` accepts one to
16
+ eight references; `resolve()` leaves literal values unchanged.
17
+ - `OP_HELLO_ACCOUNT` takes precedence over `OP_ACCOUNT`; the `account=` API
18
+ argument takes precedence over both.
19
+ - Secret values belong only on successful stdout/API return values. Never log,
20
+ print in diagnostics, commit, or place them in examples. Scrub `op://`
21
+ references from failure messages.
22
+ - The SDK is optional. Keep CLI/helper fallbacks available when it is absent or
23
+ service-account authentication fails.
24
+
25
+ ## Packaging and platform files
26
+
27
+ - The PyPI distribution and console command are `op-hello`; the Python import
28
+ package is `src/op_hello` and applications import `op_hello`.
29
+ - `pyproject.toml` force-includes `bin/op-hello` and Windows PowerShell helpers
30
+ in the wheel. Preserve those paths when changing package layout.
31
+ - Keep account selection and caching behavior consistent across Python, Bash,
32
+ PowerShell, and WSL paths.
33
+
34
+ ## Development and release
35
+
36
+ - Inspect version state with `verkit inspect` and conventions with
37
+ `verkit conventions` (the local source is `~/repos/verkit`).
38
+ - For a patch/minor/major release, use `verkit release <part>` when an origin
39
+ remote is configured. It bumps the project version, commits, tags, and pushes;
40
+ it does **not** upload to PyPI.
41
+ - Without an origin remote, use `verkit promote <part> --no-amend`, then
42
+ `verkit tag --no-push`. This avoids amending the source commit. Build and
43
+ publish with `uv build` and `uv publish`. Configure PyPI trusted publishing
44
+ or supply a token through the supported environment/credential mechanism;
45
+ never put a token in command text, source, or logs.
46
+ - Before publishing, inspect the wheel and sdist to confirm both CLI helpers
47
+ are included. After upload, verify the release page and install the exact
48
+ version into a clean environment.
49
+ - Use the project's configured Python minimum and keep user-facing docs,
50
+ package metadata, CLI help, and agent guidance in sync.
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.5
2
+ Name: op-hello
3
+ Version: 0.2.3
4
+ Summary: Portable 1Password op:// secret reader with Windows Hello support
5
+ Requires-Python: >=3.9
6
+ Provides-Extra: sdk
7
+ Requires-Dist: onepassword-sdk>=0.4.2; extra == 'sdk'
8
+ Description-Content-Type: text/markdown
9
+
10
+ # op-hello
11
+
12
+ Read a 1Password secret so the desktop app can raise Windows Hello. Store
13
+ `op://Vault/Item/field` in the environment. Resolve it when the program starts.
14
+
15
+ ```bash
16
+ export API_TOKEN=op://Private/Service/credential
17
+ op-hello resolve "$API_TOKEN"
18
+ ```
19
+
20
+ Install the published package, or use this checkout for local development:
21
+
22
+ ```bash
23
+ uv add op-hello
24
+ uv add --editable ../op-hello
25
+ ```
26
+
27
+ Install the optional SDK extra to use service-account authentication:
28
+
29
+ ```bash
30
+ uv add "op-hello[sdk]"
31
+ ```
32
+
33
+ The public Python API is suitable for application adapters and plugins. It
34
+ tries `OP_SERVICE_ACCOUNT_TOKEN` with the optional 1Password SDK, then native
35
+ `op read`, then the bundled platform helper and WSL Windows CLI fallback. A
36
+ process-local cache avoids repeating reads; Windows also keeps a
37
+ DPAPI-protected cache for the configured TTL. `clear_cache()` clears the current
38
+ process cache; the Windows cache expires according to `OP_HELLO_CACHE_TTL`.
39
+ `OP_HELLO_ACCOUNT` or the existing `OP_ACCOUNT` selects an account.
40
+
41
+ Python projects that already use this checkout:
42
+
43
+ ```python
44
+ import os
45
+
46
+ from op_hello import clear_cache, read, resolve
47
+
48
+ token = resolve(os.environ["API_TOKEN"])
49
+ ```
50
+
51
+ Two fields:
52
+
53
+ ```bash
54
+ op-hello read op://Private/Service/client-id op://Private/Service/password
55
+ ```
56
+
57
+ Stdout is one secret per line and nothing else.
58
+
59
+ ## Why this exists
60
+
61
+ 1Password's secret-reference docs stop at `op read`. These are the parts that
62
+ take the time:
63
+
64
+ 1. Turn on **Settings → Developer → Integrate with 1Password CLI** in the desktop app.
65
+ 2. From WSL, call Windows `op.exe` (`C:\Program Files\1Password CLI\op.exe`). A Linux `op` session does not raise Windows Hello.
66
+ 3. Start that process with its working directory on `C:\Windows`. `cmd.exe` exits when the working directory is a WSL UNC path.
67
+ 4. If AutoHotkey is running, suspend it for the read. Its keyboard hook hides the Hello prompt. `windows/ahk-pause.ps1` does that, and it is skipped when AutoHotkey is not installed.
68
+ 5. Use `op read`. `op item get` returns an OTP seed instead of the current code.
69
+ 6. Cache the value for 15 minutes with DPAPI, for the current Windows user, in `%LOCALAPPDATA%\op-hello\`. The first read of a field can still prompt. A repeat within 15 minutes does not. Set `OP_HELLO_CACHE_TTL` to the number of minutes.
70
+ 7. A router or DNS failure looks like `RequestDelegatedSession`. That is the network. The error text says so, and it does not include the secret or the `op://` reference.
71
+
72
+ ## Layout
73
+
74
+ | Piece | Role |
75
+ |---|---|
76
+ | `bin/op-hello` | The program other languages call |
77
+ | `windows/op-read.ps1` | Windows Hello, DPAPI cache, optional AutoHotkey pause |
78
+ | `src/op_hello/` | `resolve()` and `read()` for Python |
79
+
80
+ PowerShell is the Windows implementation because Hello, DPAPI, and AutoHotkey are Windows APIs. A Go or Rust binary would still shell out to `op.exe` and reimplement those calls. On macOS and Linux, `op-hello` calls `op read` and the system biometric prompt is the 1Password app's own. The installed CLI and Python library share this same platform helper.
81
+
82
+ ## Use it from another language
83
+
84
+ Put `bin` on `PATH` and run `op-hello read`. Exit 0 and one line per secret means success. Anything else is on stderr.
85
+
86
+ The installed `op-hello` command and Python library both use the same platform helper. `OP_HELLO_BIN` overrides the helper path for deployments that provide their own adapter.
87
+
88
+ ## Limits
89
+
90
+ One command accepts up to eight references. The desktop app has to be unlocked, and someone has to be present for the first prompt. The call fails after `OP_HELLO_TIMEOUT` seconds (default 120) if nobody approves it.
91
+
92
+
93
+ ## Release
94
+
95
+ Use the local `verkit` CLI at `~/repos/verkit` to manage the semantic version:
96
+
97
+ ```bash
98
+ uv run --project ~/repos/verkit verkit inspect
99
+ uv run --project ~/repos/verkit verkit promote patch --no-amend
100
+ uv run --project ~/repos/verkit verkit tag --no-push
101
+ uv build
102
+ uv publish
103
+ ```
104
+
105
+ `verkit promote` and `verkit tag` commit the version bump and create a matching
106
+ local tag; neither uploads artifacts to PyPI. When an `origin` remote is
107
+ configured, use `verkit release patch` instead. Configure PyPI trusted publishing or provide credentials
108
+ through `uv publish`'s supported environment mechanism; never save tokens in
109
+ this repository. Verify the published version and install it from PyPI after
110
+ upload.
@@ -0,0 +1,101 @@
1
+ # op-hello
2
+
3
+ Read a 1Password secret so the desktop app can raise Windows Hello. Store
4
+ `op://Vault/Item/field` in the environment. Resolve it when the program starts.
5
+
6
+ ```bash
7
+ export API_TOKEN=op://Private/Service/credential
8
+ op-hello resolve "$API_TOKEN"
9
+ ```
10
+
11
+ Install the published package, or use this checkout for local development:
12
+
13
+ ```bash
14
+ uv add op-hello
15
+ uv add --editable ../op-hello
16
+ ```
17
+
18
+ Install the optional SDK extra to use service-account authentication:
19
+
20
+ ```bash
21
+ uv add "op-hello[sdk]"
22
+ ```
23
+
24
+ The public Python API is suitable for application adapters and plugins. It
25
+ tries `OP_SERVICE_ACCOUNT_TOKEN` with the optional 1Password SDK, then native
26
+ `op read`, then the bundled platform helper and WSL Windows CLI fallback. A
27
+ process-local cache avoids repeating reads; Windows also keeps a
28
+ DPAPI-protected cache for the configured TTL. `clear_cache()` clears the current
29
+ process cache; the Windows cache expires according to `OP_HELLO_CACHE_TTL`.
30
+ `OP_HELLO_ACCOUNT` or the existing `OP_ACCOUNT` selects an account.
31
+
32
+ Python projects that already use this checkout:
33
+
34
+ ```python
35
+ import os
36
+
37
+ from op_hello import clear_cache, read, resolve
38
+
39
+ token = resolve(os.environ["API_TOKEN"])
40
+ ```
41
+
42
+ Two fields:
43
+
44
+ ```bash
45
+ op-hello read op://Private/Service/client-id op://Private/Service/password
46
+ ```
47
+
48
+ Stdout is one secret per line and nothing else.
49
+
50
+ ## Why this exists
51
+
52
+ 1Password's secret-reference docs stop at `op read`. These are the parts that
53
+ take the time:
54
+
55
+ 1. Turn on **Settings → Developer → Integrate with 1Password CLI** in the desktop app.
56
+ 2. From WSL, call Windows `op.exe` (`C:\Program Files\1Password CLI\op.exe`). A Linux `op` session does not raise Windows Hello.
57
+ 3. Start that process with its working directory on `C:\Windows`. `cmd.exe` exits when the working directory is a WSL UNC path.
58
+ 4. If AutoHotkey is running, suspend it for the read. Its keyboard hook hides the Hello prompt. `windows/ahk-pause.ps1` does that, and it is skipped when AutoHotkey is not installed.
59
+ 5. Use `op read`. `op item get` returns an OTP seed instead of the current code.
60
+ 6. Cache the value for 15 minutes with DPAPI, for the current Windows user, in `%LOCALAPPDATA%\op-hello\`. The first read of a field can still prompt. A repeat within 15 minutes does not. Set `OP_HELLO_CACHE_TTL` to the number of minutes.
61
+ 7. A router or DNS failure looks like `RequestDelegatedSession`. That is the network. The error text says so, and it does not include the secret or the `op://` reference.
62
+
63
+ ## Layout
64
+
65
+ | Piece | Role |
66
+ |---|---|
67
+ | `bin/op-hello` | The program other languages call |
68
+ | `windows/op-read.ps1` | Windows Hello, DPAPI cache, optional AutoHotkey pause |
69
+ | `src/op_hello/` | `resolve()` and `read()` for Python |
70
+
71
+ PowerShell is the Windows implementation because Hello, DPAPI, and AutoHotkey are Windows APIs. A Go or Rust binary would still shell out to `op.exe` and reimplement those calls. On macOS and Linux, `op-hello` calls `op read` and the system biometric prompt is the 1Password app's own. The installed CLI and Python library share this same platform helper.
72
+
73
+ ## Use it from another language
74
+
75
+ Put `bin` on `PATH` and run `op-hello read`. Exit 0 and one line per secret means success. Anything else is on stderr.
76
+
77
+ The installed `op-hello` command and Python library both use the same platform helper. `OP_HELLO_BIN` overrides the helper path for deployments that provide their own adapter.
78
+
79
+ ## Limits
80
+
81
+ One command accepts up to eight references. The desktop app has to be unlocked, and someone has to be present for the first prompt. The call fails after `OP_HELLO_TIMEOUT` seconds (default 120) if nobody approves it.
82
+
83
+
84
+ ## Release
85
+
86
+ Use the local `verkit` CLI at `~/repos/verkit` to manage the semantic version:
87
+
88
+ ```bash
89
+ uv run --project ~/repos/verkit verkit inspect
90
+ uv run --project ~/repos/verkit verkit promote patch --no-amend
91
+ uv run --project ~/repos/verkit verkit tag --no-push
92
+ uv build
93
+ uv publish
94
+ ```
95
+
96
+ `verkit promote` and `verkit tag` commit the version bump and create a matching
97
+ local tag; neither uploads artifacts to PyPI. When an `origin` remote is
98
+ configured, use `verkit release patch` instead. Configure PyPI trusted publishing or provide credentials
99
+ through `uv publish`'s supported environment mechanism; never save tokens in
100
+ this repository. Verify the published version and install it from PyPI after
101
+ upload.
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env bash
2
+ # Read 1Password references.
3
+ # op-hello read op://Vault/Item/field [op://Vault/Item/other ...]
4
+ # op-hello resolve VALUE # print VALUE, or read it when it starts with op://
5
+ #
6
+ # From WSL this calls Windows op.exe so 1Password can raise Windows Hello.
7
+ # A Linux `op` session does not. On macOS and Linux, this calls `op read`.
8
+
9
+ set -euo pipefail
10
+
11
+ ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
12
+ TIMEOUT="${OP_HELLO_TIMEOUT:-120}"
13
+ MAX_REFS=8
14
+
15
+ usage() {
16
+ cat <<'EOF'
17
+ Usage:
18
+ op-hello read op://Vault/Item/field [op://Vault/Item/other ...]
19
+ op-hello resolve VALUE
20
+
21
+ VALUE is printed unchanged unless it starts with op://.
22
+ Each secret is one line on stdout.
23
+ EOF
24
+ }
25
+
26
+ scrub() {
27
+ sed -E \
28
+ -e 's#op://[^[:space:]]+#the 1Password item#g' \
29
+ -e '/UNC paths are not supported/d' \
30
+ -e '/CMD.EXE was started/d' \
31
+ -e '/Defaulting to Windows directory/d' \
32
+ -e '/^At /d' \
33
+ -e '/^CategoryInfo/d' \
34
+ -e '/^FullyQualifiedErrorId/d' \
35
+ -e '/^\+/d' \
36
+ -e '/^[[:space:]]*$/d'
37
+ }
38
+
39
+ hint_for() {
40
+ local low
41
+ low=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')
42
+ if [[ "$low" == *requestdelegatedsession* || "$low" == *"cannot setup session"* || "$low" == *"error initializing client"* ]]; then
43
+ printf '%s\n' "1Password could not open a session. Unlock the app if it is locked. If it is already unlocked, check the network; a router or DNS failure can cause this."
44
+ elif [[ "$low" == *"dial tcp"* || "$low" == *"no such host"* || "$low" == *"network is unreachable"* || "$low" == *"connection refused"* || "$low" == *"i/o timeout"* || "$low" == *"tls handshake"* ]]; then
45
+ printf '%s\n' "The machine could not reach 1Password. Check the network connection."
46
+ elif [[ "$low" == *"not signed in"* || "$low" == *"not authenticated"* ]]; then
47
+ printf '%s\n' "Unlock 1Password and approve the Windows Hello prompt."
48
+ fi
49
+ }
50
+
51
+ is_wsl() {
52
+ grep -qi microsoft /proc/version 2>/dev/null
53
+ }
54
+
55
+ run_real() {
56
+ if [[ -n "${OP_HELLO_DELEGATE:-}" ]]; then
57
+ "$OP_HELLO_DELEGATE" "$@"
58
+ return
59
+ fi
60
+ local ps_exe="/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"
61
+ if is_wsl && [[ -f "$ps_exe" ]]; then
62
+ local win_ps1 argv=()
63
+ win_ps1=$(wslpath -w "$ROOT/windows/op-read.ps1")
64
+ argv=("$ps_exe" -NoProfile -ExecutionPolicy Bypass -File "$win_ps1" "$@")
65
+ if [[ -x /init ]]; then
66
+ argv=(/init "${argv[@]}")
67
+ fi
68
+ (
69
+ cd /mnt/c/Windows
70
+ if command -v timeout >/dev/null 2>&1; then
71
+ timeout "$TIMEOUT" "${argv[@]}"
72
+ else
73
+ "${argv[@]}"
74
+ fi
75
+ )
76
+ return
77
+ fi
78
+ if command -v op >/dev/null 2>&1; then
79
+ local ref account args=()
80
+ account="${OP_HELLO_ACCOUNT:-${OP_ACCOUNT:-}}"
81
+ for ref in "$@"; do
82
+ args=(read "$ref")
83
+ if [[ -n "$account" ]]; then
84
+ args+=(--account "$account")
85
+ fi
86
+ op "${args[@]}"
87
+ done
88
+ return
89
+ fi
90
+ printf '%s\n' "op-hello: Windows PowerShell and the op CLI are both missing." >&2
91
+ return 1
92
+ }
93
+
94
+ run_captured() {
95
+ local outfile errfile rc scrubbed hint
96
+ outfile=$(mktemp)
97
+ errfile=$(mktemp)
98
+ set +e
99
+ run_real "$@" >"$outfile" 2>"$errfile"
100
+ rc=$?
101
+ set -e
102
+ if [[ "$rc" -ne 0 ]]; then
103
+ scrubbed=$(scrub <"$errfile" || true)
104
+ hint=$(hint_for "$scrubbed" || true)
105
+ if [[ -n "$hint" ]]; then
106
+ printf '%s\n' "$hint" >&2
107
+ fi
108
+ if [[ -n "$scrubbed" ]]; then
109
+ printf '%s\n' "$scrubbed" >&2
110
+ elif [[ "$rc" -eq 124 ]]; then
111
+ printf '%s\n' "1Password Windows Hello timed out. Approve the popup; this fails if you are away." >&2
112
+ else
113
+ printf '%s\n' "1Password read failed (exit $rc)." >&2
114
+ fi
115
+ rm -f "$outfile" "$errfile"
116
+ exit "$rc"
117
+ fi
118
+ cat "$outfile"
119
+ rm -f "$outfile" "$errfile"
120
+ }
121
+
122
+ require_refs() {
123
+ local ref
124
+ if [[ "$#" -lt 1 || "$#" -gt "$MAX_REFS" ]]; then
125
+ printf '%s\n' "op-hello read takes 1 to $MAX_REFS op:// references." >&2
126
+ exit 2
127
+ fi
128
+ for ref in "$@"; do
129
+ if [[ "$ref" != op://* ]]; then
130
+ printf '%s\n' "1Password references must start with op://." >&2
131
+ exit 2
132
+ fi
133
+ done
134
+ }
135
+
136
+ cmd=${1:-}
137
+ case "$cmd" in
138
+ read)
139
+ shift
140
+ require_refs "$@"
141
+ run_captured "$@"
142
+ ;;
143
+ resolve)
144
+ shift
145
+ if [[ "$#" -ne 1 ]]; then
146
+ usage >&2
147
+ exit 2
148
+ fi
149
+ if [[ "$1" == op://* ]]; then
150
+ run_captured "$1"
151
+ else
152
+ printf '%s\n' "$1"
153
+ fi
154
+ ;;
155
+ -h|--help|help|"")
156
+ usage
157
+ ;;
158
+ *)
159
+ usage >&2
160
+ exit 2
161
+ ;;
162
+ esac
@@ -0,0 +1,18 @@
1
+ # op-hello
2
+
3
+ `op-hello` is a Python library and CLI for securely reading 1Password `op://`
4
+ references with native CLI, service-account SDK, Windows Hello/DPAPI, and WSL
5
+ fallbacks. Applications should use the public `op_hello` API rather than
6
+ reimplement credential handling.
7
+
8
+ - [README](README.md): installation, API, CLI, environment configuration.
9
+ - [AGENTS.md](AGENTS.md): implementation, security, packaging, and release rules.
10
+ - [API module](src/op_hello/__init__.py): `read`, `resolve`, `clear_cache`, `is_available`.
11
+ - [CLI module](src/op_hello/cli.py): installed `op-hello` entry point.
12
+ - [Shell helper](bin/op-hello): cross-platform CLI and fallback behavior.
13
+ - [Windows reader](windows/op-read.ps1): Windows Hello, account selection, DPAPI cache.
14
+ - [Tests](tests/test_op_hello.py): API and CLI behavior.
15
+
16
+ Security: secret values are returned only to the caller; never log or expose
17
+ references or values in diagnostics. Preserve account-scoped caching and all
18
+ platform fallbacks.
@@ -0,0 +1,31 @@
1
+ [project]
2
+ name = "op-hello"
3
+ version = "0.2.3"
4
+ description = "Portable 1Password op:// secret reader with Windows Hello support"
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+
8
+ [project.scripts]
9
+ op-hello = "op_hello.cli:main"
10
+
11
+ [project.optional-dependencies]
12
+ sdk = ["onepassword-sdk>=0.4.2"]
13
+
14
+ [build-system]
15
+ requires = ["hatchling"]
16
+ build-backend = "hatchling.build"
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["src/op_hello"]
20
+
21
+ [tool.hatch.build.targets.wheel.sources]
22
+ "src/op_hello" = "op_hello"
23
+
24
+ [tool.pytest.ini_options]
25
+ pythonpath = ["src"]
26
+ testpaths = ["tests"]
27
+
28
+ [tool.hatch.build.targets.wheel.force-include]
29
+ "bin/op-hello" = "op_hello/bin/op-hello"
30
+ "windows/op-read.ps1" = "op_hello/windows/op-read.ps1"
31
+ "windows/ahk-pause.ps1" = "op_hello/windows/ahk-pause.ps1"
@@ -0,0 +1,227 @@
1
+ """Portable 1Password secret resolution, including Windows Hello in WSL.
2
+
3
+ Applications use :func:`read` / :func:`resolve` rather than invoking ``op``
4
+ directly. Reads try the service-account SDK, native ``op read``, the bundled
5
+ platform helper, then the WSL Windows CLI fallback. Values are cached only in
6
+ this process; the Windows helper also uses a DPAPI-protected cache.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import os
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ from importlib.metadata import PackageNotFoundError, version
17
+ from pathlib import Path
18
+ from typing import Optional
19
+
20
+ __all__ = ["clear_cache", "is_available", "read", "resolve"]
21
+
22
+ logger = logging.getLogger(__name__)
23
+ try:
24
+ _PACKAGE_VERSION = version("op-hello")
25
+ except PackageNotFoundError:
26
+ _PACKAGE_VERSION = "dev"
27
+ _CACHE: dict[tuple[str, str], str] = {}
28
+
29
+
30
+ def clear_cache() -> None:
31
+ """Clear cached values after a secret rotation or between isolated runs."""
32
+ _CACHE.clear()
33
+
34
+
35
+ def resolve(value: str, *, account: Optional[str] = None) -> str:
36
+ """Return a literal unchanged, or resolve an ``op://`` reference."""
37
+ text = value.strip()
38
+ if text.startswith("op://"):
39
+ return read(text, account=account)[0]
40
+ return text
41
+
42
+
43
+ def is_available() -> bool:
44
+ """Whether an SDK, 1Password CLI, or bundled helper is available."""
45
+ if os.environ.get("OP_SERVICE_ACCOUNT_TOKEN"):
46
+ return True
47
+ if shutil.which("op") or shutil.which("op.exe") or shutil.which("op-hello"):
48
+ return True
49
+ return _bundled_script().is_file()
50
+
51
+
52
+ def read(*refs: str, account: Optional[str] = None) -> list[str]:
53
+ """Read one to eight references, batch them, and reuse process-cached values.
54
+
55
+ ``account`` overrides ``OP_HELLO_ACCOUNT`` / ``OP_ACCOUNT``. Cocli uses
56
+ this to preserve its configured default; standalone apps can omit it.
57
+ """
58
+ cleaned = [ref.strip() for ref in refs if ref and ref.strip()]
59
+ if not cleaned or len(cleaned) > 8:
60
+ raise ValueError(
61
+ "op-hello can read one to eight 1Password references at a time"
62
+ )
63
+ for ref in cleaned:
64
+ if not ref.startswith("op://"):
65
+ raise ValueError("1Password references must start with op://")
66
+ selected_account = (
67
+ account
68
+ or os.environ.get("OP_HELLO_ACCOUNT")
69
+ or os.environ.get("OP_ACCOUNT")
70
+ or ""
71
+ )
72
+ keys = [(selected_account, ref) for ref in cleaned]
73
+ missing_keys = list(dict.fromkeys(key for key in keys if key not in _CACHE))
74
+ if missing_keys:
75
+ missing_refs = [ref for _, ref in missing_keys]
76
+ values = _read_uncached(*missing_refs, account=selected_account or None)
77
+ if len(values) != len(missing_keys):
78
+ raise RuntimeError(
79
+ f"1Password returned {len(values)} value(s); "
80
+ f"expected {len(missing_keys)}."
81
+ )
82
+ for key, value in zip(missing_keys, values):
83
+ if not value:
84
+ raise RuntimeError("1Password returned an empty secret.")
85
+ _CACHE[key] = value
86
+ return [_CACHE[key] for key in keys]
87
+
88
+
89
+ def _bundled_script() -> Path:
90
+ override = os.environ.get("OP_HELLO_BIN", "").strip()
91
+ if override:
92
+ return Path(override)
93
+ package = Path(__file__).resolve().parent
94
+ installed = package / "bin" / "op-hello"
95
+ if installed.is_file():
96
+ return installed
97
+ return Path(__file__).resolve().parents[2] / "bin" / "op-hello"
98
+
99
+
100
+ def _op_env(account: Optional[str] = None) -> dict[str, str]:
101
+ env = os.environ.copy()
102
+ selected = account or env.get("OP_HELLO_ACCOUNT") or env.get("OP_ACCOUNT")
103
+ if account:
104
+ env["OP_HELLO_ACCOUNT"] = account
105
+ env["OP_ACCOUNT"] = account
106
+ elif selected:
107
+ env.setdefault("OP_ACCOUNT", selected)
108
+ return env
109
+
110
+
111
+ def _run(
112
+ argv: list[str],
113
+ timeout: int = 60,
114
+ *,
115
+ cwd: Optional[str] = None,
116
+ account: Optional[str] = None,
117
+ ) -> subprocess.CompletedProcess[str]:
118
+ return subprocess.run(
119
+ argv,
120
+ capture_output=True,
121
+ text=True,
122
+ timeout=timeout,
123
+ cwd=cwd,
124
+ env=_op_env(account),
125
+ )
126
+
127
+
128
+ def _read_uncached(*refs: str, account: Optional[str] = None) -> list[str]:
129
+ values = _read_sdk(*refs)
130
+ if values is not None:
131
+ return values
132
+ values, native_error = _read_native_cli(*refs, account=account)
133
+ if values is not None:
134
+ return values
135
+ values, helper_error = _read_bundled_cli(*refs, account=account)
136
+ if values is not None:
137
+ return values
138
+ values, windows_error = _read_windows_cli(*refs, account=account)
139
+ if values is not None:
140
+ return values
141
+ detail = helper_error or windows_error or native_error or "1Password read failed."
142
+ detail = re.sub(r"op://[^\s]+", "the 1Password item", detail)
143
+ raise RuntimeError(detail)
144
+
145
+
146
+ def _read_sdk(*refs: str) -> Optional[list[str]]:
147
+ token = os.environ.get("OP_SERVICE_ACCOUNT_TOKEN")
148
+ if not token:
149
+ return None
150
+ try:
151
+ from onepassword.client import Client # type: ignore[import-not-found]
152
+
153
+ async def resolve_all() -> list[str]:
154
+ client = await Client.authenticate(
155
+ auth=token,
156
+ integration_name=os.environ.get("OP_HELLO_INTEGRATION_NAME", "op-hello"),
157
+ integration_version=os.environ.get(
158
+ "OP_HELLO_INTEGRATION_VERSION", _PACKAGE_VERSION
159
+ ),
160
+ )
161
+ return [str(await client.secrets.resolve(ref)) for ref in refs]
162
+
163
+ return asyncio.run(resolve_all())
164
+ except Exception:
165
+ logger.debug("1Password SDK lookup failed; trying configured CLI readers")
166
+ return None
167
+
168
+
169
+ def _account_args(account: Optional[str]) -> list[str]:
170
+ selected = account or os.environ.get("OP_HELLO_ACCOUNT") or os.environ.get("OP_ACCOUNT")
171
+ return ["--account", selected] if selected else []
172
+
173
+
174
+ def _read_native_cli(*refs: str, account: Optional[str] = None) -> tuple[Optional[list[str]], Optional[str]]:
175
+ binary = shutil.which("op")
176
+ if not binary or binary.lower().endswith(".exe"):
177
+ return None, None
178
+ values: list[str] = []
179
+ for ref in refs:
180
+ try:
181
+ result = _run([binary, "read", ref, *_account_args(account)], timeout=60, account=account)
182
+ except (OSError, subprocess.TimeoutExpired):
183
+ return None, None
184
+ if result.returncode:
185
+ return None, result.stderr.strip() or "1Password CLI read failed."
186
+ values.append(result.stdout.rstrip("\r\n"))
187
+ return values, None
188
+
189
+
190
+ def _read_bundled_cli(*refs: str, account: Optional[str] = None) -> tuple[Optional[list[str]], Optional[str]]:
191
+ script = _bundled_script()
192
+ if not script.is_file():
193
+ return None, None
194
+ bash = shutil.which("bash")
195
+ if not bash:
196
+ return None, "The op-hello platform helper requires Bash."
197
+ timeout = int(os.environ.get("OP_HELLO_TIMEOUT", "120"))
198
+ try:
199
+ result = _run([bash, str(script), "read", *refs], timeout=timeout + 5, account=account)
200
+ except (OSError, subprocess.TimeoutExpired):
201
+ return None, "1Password Windows Hello timed out or the helper could not start."
202
+ if result.returncode:
203
+ return None, result.stderr.strip() or "1Password platform helper failed."
204
+ lines = [line for line in result.stdout.splitlines() if line]
205
+ if len(lines) != len(refs):
206
+ return None, "1Password returned an unexpected number of values."
207
+ return lines, None
208
+
209
+
210
+ def _read_windows_cli(*refs: str, account: Optional[str] = None) -> tuple[Optional[list[str]], Optional[str]]:
211
+ """Last-resort WSL path matching Cocli's Windows op.exe fallback."""
212
+ if not Path("/mnt/c/Program Files/1Password CLI/op.exe").is_file():
213
+ return None, None
214
+ binary = "/mnt/c/Program Files/1Password CLI/op.exe"
215
+ values: list[str] = []
216
+ for ref in refs:
217
+ argv = [binary, "read", ref, *_account_args(account)]
218
+ if Path("/init").is_file():
219
+ argv.insert(0, "/init")
220
+ try:
221
+ result = _run(argv, timeout=60, cwd="/mnt/c/Windows", account=account)
222
+ except (OSError, subprocess.TimeoutExpired):
223
+ return None, "Windows 1Password CLI timed out or could not start."
224
+ if result.returncode:
225
+ return None, result.stderr.strip() or "Windows 1Password CLI read failed."
226
+ values.append(result.stdout.replace("\r", "").strip())
227
+ return values, None
@@ -0,0 +1,39 @@
1
+ """Installed command-line entry point for op-hello."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+
11
+ def _script() -> Path:
12
+ override = os.environ.get("OP_HELLO_BIN", "").strip()
13
+ if override:
14
+ return Path(override)
15
+ package = Path(__file__).resolve().parent
16
+ installed = package / "bin" / "op-hello"
17
+ if installed.is_file():
18
+ return installed
19
+ return Path(__file__).resolve().parents[2] / "bin" / "op-hello"
20
+
21
+
22
+ def main() -> None:
23
+ """Run the platform helper, preserving one-secret-per-line stdout."""
24
+ if os.name == "nt":
25
+ package = Path(__file__).resolve().parent
26
+ ps = shutil.which("powershell.exe") or shutil.which("powershell")
27
+ script = package / "windows" / "op-read.ps1"
28
+ if not ps or not script.is_file():
29
+ print("op-hello: Windows PowerShell helper is unavailable.", file=sys.stderr)
30
+ raise SystemExit(1)
31
+ proc = subprocess.run([ps, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script), *sys.argv[1:]])
32
+ else:
33
+ bash = shutil.which("bash")
34
+ script = _script()
35
+ if not bash or not script.is_file():
36
+ print("op-hello: bundled Bash helper is unavailable.", file=sys.stderr)
37
+ raise SystemExit(1)
38
+ proc = subprocess.run([bash, str(script), *sys.argv[1:]])
39
+ raise SystemExit(proc.returncode)
File without changes
@@ -0,0 +1,80 @@
1
+ import os
2
+ import subprocess
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from op_hello import read, resolve
8
+
9
+ ROOT = Path(__file__).resolve().parents[1]
10
+ CLI = ROOT / "bin" / "op-hello"
11
+
12
+
13
+ @pytest.fixture(autouse=True)
14
+ def _clear_cache() -> None:
15
+ import op_hello
16
+
17
+ op_hello._CACHE.clear()
18
+
19
+
20
+ def test_resolve_leaves_literals_alone(monkeypatch: pytest.MonkeyPatch) -> None:
21
+ monkeypatch.setenv("OP_HELLO_BIN", "/does/not/run")
22
+ assert resolve("mailbox-secret") == "mailbox-secret"
23
+
24
+
25
+ def test_read_uses_the_cli_once_and_then_the_cache(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
26
+ fake = tmp_path / "op-hello"
27
+ fake.write_text(
28
+ "#!/bin/sh\n"
29
+ "printf '%s\\n' one\n"
30
+ "printf '%s\\n' two\n",
31
+ encoding="utf-8",
32
+ )
33
+ fake.chmod(0o755)
34
+ calls = {"n": 0}
35
+ real_run = subprocess.run
36
+
37
+ def spy(*args, **kwargs):
38
+ calls["n"] += 1
39
+ return real_run(*args, **kwargs)
40
+
41
+ monkeypatch.setenv("OP_HELLO_BIN", str(fake))
42
+ monkeypatch.setattr(subprocess, "run", spy)
43
+ assert read("op://Vault/Item/a", "op://Vault/Item/b") == ["one", "two"]
44
+ assert read("op://Vault/Item/a") == ["one"]
45
+ assert calls["n"] == 1
46
+
47
+
48
+ def test_cli_resolve_prints_a_literal() -> None:
49
+ proc = subprocess.run(
50
+ [str(CLI), "resolve", "literal-value"],
51
+ check=False,
52
+ capture_output=True,
53
+ text=True,
54
+ )
55
+ assert proc.returncode == 0
56
+ assert proc.stdout == "literal-value\n"
57
+
58
+
59
+ def test_cli_scrubs_a_failed_reference(tmp_path: Path) -> None:
60
+ delegate = tmp_path / "fail.sh"
61
+ delegate.write_text(
62
+ "#!/bin/sh\n"
63
+ "echo 'RequestDelegatedSession for op://Private/Item/password' >&2\n"
64
+ "exit 1\n",
65
+ encoding="utf-8",
66
+ )
67
+ delegate.chmod(0o755)
68
+ env = os.environ.copy()
69
+ env["OP_HELLO_DELEGATE"] = str(delegate)
70
+ proc = subprocess.run(
71
+ [str(CLI), "read", "op://Private/Item/password"],
72
+ check=False,
73
+ capture_output=True,
74
+ text=True,
75
+ env=env,
76
+ )
77
+ assert proc.returncode == 1
78
+ assert "op://" not in proc.stderr
79
+ assert "the 1Password item" in proc.stderr
80
+ assert "check the network" in proc.stderr
@@ -0,0 +1,61 @@
1
+ # Suspend or resume AutoHotkey. Its keyboard hook steals the Windows Hello prompt.
2
+ # Usage: ahk-pause.ps1 -Suspend | -Resume
3
+
4
+ param(
5
+ [switch]$Suspend,
6
+ [switch]$Resume
7
+ )
8
+
9
+ if (-not $Suspend -and -not $Resume) {
10
+ Write-Error "Specify -Suspend or -Resume"
11
+ exit 1
12
+ }
13
+
14
+ $signature = @'
15
+ using System;
16
+ using System.Diagnostics;
17
+ using System.Runtime.InteropServices;
18
+
19
+ public static class AhkProc {
20
+ [DllImport("ntdll.dll")]
21
+ public static extern int NtSuspendProcess(IntPtr processHandle);
22
+
23
+ [DllImport("ntdll.dll")]
24
+ public static extern int NtResumeProcess(IntPtr processHandle);
25
+
26
+ public static void SuspendPid(int pid) {
27
+ using (var p = Process.GetProcessById(pid)) {
28
+ NtSuspendProcess(p.Handle);
29
+ }
30
+ }
31
+
32
+ public static void ResumePid(int pid) {
33
+ using (var p = Process.GetProcessById(pid)) {
34
+ NtResumeProcess(p.Handle);
35
+ }
36
+ }
37
+ }
38
+ '@
39
+
40
+ try {
41
+ Add-Type -TypeDefinition $signature -ErrorAction Stop | Out-Null
42
+ } catch {
43
+ # The type is already loaded in this process.
44
+ }
45
+
46
+ $procs = @(Get-Process -Name "AutoHotkey*" -ErrorAction SilentlyContinue)
47
+ if ($procs.Count -eq 0) {
48
+ exit 0
49
+ }
50
+
51
+ foreach ($p in $procs) {
52
+ try {
53
+ if ($Suspend) {
54
+ [AhkProc]::SuspendPid($p.Id)
55
+ } else {
56
+ [AhkProc]::ResumePid($p.Id)
57
+ }
58
+ } catch {
59
+ # The process exited between the list and the call.
60
+ }
61
+ }
@@ -0,0 +1,5 @@
1
+ @echo off
2
+ REM Windows entry: op-read.cmd "op://Vault/Item/field" ["op://Vault/Item/other"]
3
+ setlocal
4
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0op-read.ps1" %*
5
+ exit /b %ERRORLEVEL%
@@ -0,0 +1,152 @@
1
+ # Read one or more op:// secrets with Windows op.exe.
2
+ # AutoHotkey is suspended when ahk-pause.ps1 sits next to this script.
3
+ # A successful read is cached for this Windows user with DPAPI.
4
+ #
5
+ # Usage:
6
+ # op-read.ps1 "op://Vault/Item/field" ["op://Vault/Item/other" ...]
7
+ # One secret per line on stdout. Nothing else.
8
+
9
+ param(
10
+ [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
11
+ [string[]]$Refs
12
+ )
13
+
14
+ $ErrorActionPreference = "Stop"
15
+ $MaxRefs = 8
16
+
17
+ if ($Refs.Count -gt $MaxRefs) {
18
+ Write-Error "op-read accepts at most $MaxRefs references"
19
+ exit 1
20
+ }
21
+ foreach ($ref in $Refs) {
22
+ if (-not $ref.StartsWith("op://")) {
23
+ Write-Error "1Password references must start with op://"
24
+ exit 1
25
+ }
26
+ }
27
+
28
+ $op = $env:OP_EXE
29
+ if (-not $op) {
30
+ $op = "C:\Program Files\1Password CLI\op.exe"
31
+ }
32
+ if (-not (Test-Path $op)) {
33
+ $found = Get-Command op.exe -ErrorAction SilentlyContinue
34
+ if ($found) { $op = $found.Source }
35
+ }
36
+ if (-not (Test-Path $op)) {
37
+ Write-Error "op.exe not found. Install the 1Password CLI and turn on developer integration."
38
+ exit 1
39
+ }
40
+
41
+ $pause = if ($env:OP_AHK_PAUSE) { $env:OP_AHK_PAUSE } else { Join-Path $PSScriptRoot "ahk-pause.ps1" }
42
+ $cacheMinutes = 15
43
+ if ($env:OP_HELLO_CACHE_TTL) {
44
+ $cacheMinutes = [int]$env:OP_HELLO_CACHE_TTL
45
+ }
46
+ $cachePath = Join-Path $env:LOCALAPPDATA "op-hello\op-read-cache.json"
47
+ $cacheTtl = [TimeSpan]::FromMinutes($cacheMinutes)
48
+
49
+ function Get-RefKey([string]$Ref) {
50
+ $sha = [Security.Cryptography.SHA256]::Create()
51
+ try {
52
+ $bytes = [Text.Encoding]::UTF8.GetBytes($Ref)
53
+ return ([BitConverter]::ToString($sha.ComputeHash($bytes))).Replace("-", "")
54
+ } finally {
55
+ $sha.Dispose()
56
+ }
57
+ }
58
+
59
+ function Read-Cache {
60
+ if (-not (Test-Path $cachePath)) { return @{} }
61
+ try {
62
+ $raw = Get-Content -Raw -Path $cachePath | ConvertFrom-Json
63
+ $map = @{}
64
+ if ($raw) {
65
+ foreach ($prop in $raw.PSObject.Properties) { $map[$prop.Name] = $prop.Value }
66
+ }
67
+ return $map
68
+ } catch {
69
+ return @{}
70
+ }
71
+ }
72
+
73
+ function Get-Cached([string]$Ref) {
74
+ $cache = Read-Cache
75
+ $account = if ($env:OP_HELLO_ACCOUNT) { $env:OP_HELLO_ACCOUNT } else { $env:OP_ACCOUNT }
76
+ $key = Get-RefKey "$account`n$Ref"
77
+ if (-not $cache.ContainsKey($key)) { return $null }
78
+ $entry = $cache[$key]
79
+ if ([int64]$entry.exp -lt [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) { return $null }
80
+ Add-Type -AssemblyName System.Security
81
+ $protected = [Convert]::FromBase64String([string]$entry.blob)
82
+ $clear = [Security.Cryptography.ProtectedData]::Unprotect(
83
+ $protected, $null, [Security.Cryptography.DataProtectionScope]::CurrentUser)
84
+ return [Text.Encoding]::UTF8.GetString($clear)
85
+ }
86
+
87
+ function Set-Cached([string]$Ref, [string]$Value) {
88
+ Add-Type -AssemblyName System.Security
89
+ $dir = Split-Path $cachePath
90
+ if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir | Out-Null }
91
+ $protected = [Security.Cryptography.ProtectedData]::Protect(
92
+ [Text.Encoding]::UTF8.GetBytes($Value),
93
+ $null,
94
+ [Security.Cryptography.DataProtectionScope]::CurrentUser)
95
+ $cache = Read-Cache
96
+ $account = if ($env:OP_HELLO_ACCOUNT) { $env:OP_HELLO_ACCOUNT } else { $env:OP_ACCOUNT }
97
+ $cache[(Get-RefKey "$account`n$Ref")] = [pscustomobject]@{
98
+ exp = [DateTimeOffset]::UtcNow.Add($cacheTtl).ToUnixTimeSeconds()
99
+ blob = [Convert]::ToBase64String($protected)
100
+ }
101
+ $cache | ConvertTo-Json | Set-Content -Path $cachePath -Encoding UTF8
102
+ }
103
+
104
+ function Invoke-OpRead([string]$Ref) {
105
+ $cached = Get-Cached $Ref
106
+ if ($cached) { return $cached }
107
+ $psi = New-Object System.Diagnostics.ProcessStartInfo
108
+ $psi.FileName = $op
109
+ $account = if ($env:OP_HELLO_ACCOUNT) { $env:OP_HELLO_ACCOUNT } else { $env:OP_ACCOUNT }
110
+ if ($account) {
111
+ $psi.Arguments = "read `"$Ref`" --account `"$account`""
112
+ } else {
113
+ $psi.Arguments = "read `"$Ref`""
114
+ }
115
+ $psi.RedirectStandardOutput = $true
116
+ $psi.RedirectStandardError = $true
117
+ $psi.UseShellExecute = $false
118
+ $psi.CreateNoWindow = $true
119
+ $p = [System.Diagnostics.Process]::Start($psi)
120
+ $stdout = $p.StandardOutput.ReadToEnd()
121
+ $stderr = $p.StandardError.ReadToEnd()
122
+ $p.WaitForExit()
123
+ if ($p.ExitCode -ne 0) {
124
+ if ($stderr) { [Console]::Error.WriteLine($stderr.TrimEnd()) }
125
+ throw "op read failed (exit $($p.ExitCode))"
126
+ }
127
+ $value = ($stdout -replace "[\r\n]+", "").Trim()
128
+ if ($value) { Set-Cached $Ref $value }
129
+ return $value
130
+ }
131
+
132
+ $paused = $false
133
+ try {
134
+ if (Test-Path $pause) {
135
+ & $pause -Suspend 2>$null
136
+ $paused = $true
137
+ }
138
+ $values = @()
139
+ foreach ($ref in $Refs) {
140
+ $values += (Invoke-OpRead $ref)
141
+ }
142
+ if ($values -contains "" -or $values -contains $null) {
143
+ throw "Empty secret from 1Password"
144
+ }
145
+ foreach ($value in $values) {
146
+ Write-Output $value
147
+ }
148
+ } finally {
149
+ if ($paused) {
150
+ & $pause -Resume 2>$null
151
+ }
152
+ }