op-hello 0.2.3__py3-none-any.whl
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.
- op_hello/__init__.py +227 -0
- op_hello/bin/op-hello +162 -0
- op_hello/cli.py +39 -0
- op_hello/py.typed +0 -0
- op_hello/windows/ahk-pause.ps1 +61 -0
- op_hello/windows/op-read.ps1 +152 -0
- op_hello-0.2.3.dist-info/METADATA +110 -0
- op_hello-0.2.3.dist-info/RECORD +10 -0
- op_hello-0.2.3.dist-info/WHEEL +4 -0
- op_hello-0.2.3.dist-info/entry_points.txt +2 -0
op_hello/__init__.py
ADDED
|
@@ -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
|
op_hello/bin/op-hello
ADDED
|
@@ -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
|
op_hello/cli.py
ADDED
|
@@ -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)
|
op_hello/py.typed
ADDED
|
File without changes
|
|
@@ -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,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
|
+
}
|
|
@@ -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,10 @@
|
|
|
1
|
+
op_hello/__init__.py,sha256=DiD19IJzXP8zSn4kAZ97JMboE9poZIpw7UzE04Yvp1A,8405
|
|
2
|
+
op_hello/cli.py,sha256=-ELprc8DQpdf5P7dXVVQu8jllEFeJQIGt15qTJ057AI,1428
|
|
3
|
+
op_hello/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
op_hello/bin/op-hello,sha256=k-XzKx2akDjteX_60Dhlc5uLHMQ5iQtIt5n-uOAe4mo,4402
|
|
5
|
+
op_hello/windows/ahk-pause.ps1,sha256=bSBtUaY_gSomKLQ7GIPg4QLIHuWguIRAJqn7mEHiSso,1415
|
|
6
|
+
op_hello/windows/op-read.ps1,sha256=r_eixTEI6-DBMCXhjoHhgcooqoGALs6_Dp6uTImxO0M,4991
|
|
7
|
+
op_hello-0.2.3.dist-info/METADATA,sha256=CL-IqpuivMZQimJ_7nzyaWoRe_Y3QUST6HvCXl6Sl6c,4597
|
|
8
|
+
op_hello-0.2.3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
op_hello-0.2.3.dist-info/entry_points.txt,sha256=T_xOlVFMAZnDG32_C4aDguvHQ2p94QHrsDazlfPoyg4,47
|
|
10
|
+
op_hello-0.2.3.dist-info/RECORD,,
|