herdr-secret 0.1.1 → 0.2.0
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.
- package/README.md +25 -13
- package/cli.js +45 -14
- package/engine/agents/SKILL.md +68 -0
- package/engine/agents/instructions.md +8 -0
- package/engine/bin/herdr-secret +8 -0
- package/engine/bin/herdr-secret.cmd +12 -0
- package/engine/bin/herdr_secret.py +1713 -0
- package/engine/herdr-plugin.toml +67 -0
- package/engine/mods/herdr-secret/main.js +221 -0
- package/engine/mods/herdr-secret/mod.json +1 -0
- package/package.json +34 -8
|
@@ -0,0 +1,1713 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""herdr-secret: an agent asks the human for a credential through a herdr popup form.
|
|
3
|
+
|
|
4
|
+
herdr-secret ask NAME "what it is for" [--fields "username,password"] [--plain] [--timeout S]
|
|
5
|
+
Opens the form (a herdr popup, or in Herdr.app the herdr-secret mod's dialog) and waits.
|
|
6
|
+
Prints one line only:
|
|
7
|
+
OK|CANCELLED|TIMEOUT|FAILED NAME [(fields)] [[where it was stored]]
|
|
8
|
+
With --fields each value is stored as NAME.<field>; without, one hidden value as NAME.
|
|
9
|
+
herdr-secret get NAME value to stdout; refuses a terminal, so pipe it into the target
|
|
10
|
+
herdr-secret list stored names, never values
|
|
11
|
+
herdr-secret rm NAME delete NAME and any NAME.<field> entries
|
|
12
|
+
herdr-secret setup interactive setup: store check, PATH, Herdr.app mod, agent instructions,
|
|
13
|
+
test form
|
|
14
|
+
herdr-secret uninstall undo everything setup added (asks before deleting stored values)
|
|
15
|
+
|
|
16
|
+
Storage: macOS Keychain, Windows Credential Manager, Linux Secret Service (secret-tool),
|
|
17
|
+
or a 0600 file on Linux machines without a Secret Service. Values never pass through argv.
|
|
18
|
+
Python 3.8+, standard library only.
|
|
19
|
+
"""
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import secrets
|
|
23
|
+
import shutil
|
|
24
|
+
import signal
|
|
25
|
+
import subprocess
|
|
26
|
+
import sys
|
|
27
|
+
import tempfile
|
|
28
|
+
import time
|
|
29
|
+
import unicodedata
|
|
30
|
+
|
|
31
|
+
IS_WIN = os.name == "nt"
|
|
32
|
+
IS_MAC = sys.platform == "darwin"
|
|
33
|
+
SERVICE = "herdr-secret"
|
|
34
|
+
PLUGIN_ID = "mazemaker.secret"
|
|
35
|
+
NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
|
|
36
|
+
REQ_RE = re.compile(r"[A-Za-z0-9-]{1,64}")
|
|
37
|
+
FIELD_RE = re.compile(r"[a-z0-9_]{1,32}")
|
|
38
|
+
MAX_FIELDS = 6
|
|
39
|
+
MAX_VALUE = 1000 # characters; Windows Credential Manager holds at most 2560 bytes of UTF-16
|
|
40
|
+
PLAIN_BY_DEFAULT = {"user", "username", "email", "login", "host", "url"}
|
|
41
|
+
DEVNULL = subprocess.DEVNULL
|
|
42
|
+
CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
|
43
|
+
|
|
44
|
+
T = {"title": "Credential requested: ", "from": "From : ", "for": "For : ", "hidden": " (hidden)",
|
|
45
|
+
"save": "[ Save ]", "cancel": "[ Cancel ]", "value": "Value", "unknown": "unknown",
|
|
46
|
+
"help": "Tab/↑↓ move · Enter next · Ctrl-R reveal · Esc cancel",
|
|
47
|
+
"required": "All fields are required.", "saved": "Saved to {}.", "failed": "Could not save.",
|
|
48
|
+
"invalid": "Invalid request.", "reported": " (as reported by the requester)",
|
|
49
|
+
"replaces": "Replaces the stored value of: {}", "timeout": "Timed out. Nothing was saved.",
|
|
50
|
+
"toolong": "Too long (max {} characters).", "saved_to": "Saved : ",
|
|
51
|
+
"promise": "{} · never sent to the agent's chat"}
|
|
52
|
+
|
|
53
|
+
# What the form tells the human about where a value goes. Only the stores that really encrypt
|
|
54
|
+
# say so; the Linux file fallback says plainly that it does not.
|
|
55
|
+
STORE_NOTE = {"macOS Keychain": ("macOS Keychain (encrypted)", True),
|
|
56
|
+
"Windows Credential Manager": ("Windows Credential Manager (encrypted)", True),
|
|
57
|
+
"Secret Service": ("your keyring (encrypted)", True),
|
|
58
|
+
"file 0600": ("a file only you can read (not encrypted)", False)}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def store_note():
|
|
62
|
+
label = backends()[0].label
|
|
63
|
+
text, encrypted = STORE_NOTE.get(label, (label, False))
|
|
64
|
+
return T["promise"].format(text), encrypted
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def clean(text, limit=300):
|
|
68
|
+
"""Text from the asking agent is shown in the form: strip control characters so it cannot
|
|
69
|
+
move the cursor, recolour, overwrite the "From" line, or reorder text with bidi marks."""
|
|
70
|
+
return "".join(ch for ch in text
|
|
71
|
+
if not CONTROL.match(ch) and unicodedata.category(ch) not in ("Cf", "Zl", "Zp", "Co", "Cs"))[:limit]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def cwidth(ch):
|
|
75
|
+
if unicodedata.combining(ch):
|
|
76
|
+
return 0
|
|
77
|
+
return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def dwidth(text):
|
|
81
|
+
return sum(cwidth(c) for c in text)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def fit_head(text, width):
|
|
85
|
+
out, w = [], 0
|
|
86
|
+
for ch in text:
|
|
87
|
+
if w + cwidth(ch) > width:
|
|
88
|
+
break
|
|
89
|
+
out.append(ch)
|
|
90
|
+
w += cwidth(ch)
|
|
91
|
+
return "".join(out), w
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def fit_tail(text, width):
|
|
95
|
+
out, w = [], 0
|
|
96
|
+
for ch in reversed(text):
|
|
97
|
+
if w + cwidth(ch) > width:
|
|
98
|
+
break
|
|
99
|
+
out.append(ch)
|
|
100
|
+
w += cwidth(ch)
|
|
101
|
+
return "".join(reversed(out)), w
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def write_atomic(path, text):
|
|
105
|
+
"""Readers never see a half-written file: write a sibling temp file, then rename over."""
|
|
106
|
+
d = os.path.dirname(path)
|
|
107
|
+
fd, tmp = tempfile.mkstemp(dir=d, prefix=".tmp-") # created 0600
|
|
108
|
+
try:
|
|
109
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
110
|
+
f.write(text)
|
|
111
|
+
f.flush()
|
|
112
|
+
os.fsync(f.fileno())
|
|
113
|
+
os.replace(tmp, path)
|
|
114
|
+
except BaseException:
|
|
115
|
+
try:
|
|
116
|
+
os.unlink(tmp)
|
|
117
|
+
except OSError:
|
|
118
|
+
pass
|
|
119
|
+
raise
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def state_dir():
|
|
123
|
+
if IS_WIN:
|
|
124
|
+
base = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~\\AppData\\Local")
|
|
125
|
+
else:
|
|
126
|
+
base = os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state")
|
|
127
|
+
d = os.path.join(base, "herdr-secret")
|
|
128
|
+
os.makedirs(d, mode=0o700, exist_ok=True)
|
|
129
|
+
if not IS_WIN:
|
|
130
|
+
os.chmod(d, 0o700)
|
|
131
|
+
return d
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ---------------------------------------------------------------- storage backends
|
|
135
|
+
|
|
136
|
+
class MacKeychain:
|
|
137
|
+
label = "macOS Keychain"
|
|
138
|
+
|
|
139
|
+
def store(self, acct, value):
|
|
140
|
+
if CONTROL.search(value):
|
|
141
|
+
return False
|
|
142
|
+
esc = value.replace("\\", "\\\\").replace('"', '\\"')
|
|
143
|
+
cmd = f'add-generic-password -U -s {SERVICE} -a "{acct}" -w "{esc}"\n'
|
|
144
|
+
subprocess.run(["security", "-i"], input=cmd, text=True, stdout=DEVNULL, stderr=DEVNULL)
|
|
145
|
+
return self.fetch(acct) == value
|
|
146
|
+
|
|
147
|
+
def fetch(self, acct):
|
|
148
|
+
# `-w` alone prints non-ASCII data as bare hex, indistinguishable from a hex-looking
|
|
149
|
+
# password. `-g` marks it: `password: 0x<HEX> "..."` versus `password: "<text>"`.
|
|
150
|
+
r = subprocess.run(["security", "find-generic-password", "-s", SERVICE, "-a", acct, "-g"],
|
|
151
|
+
capture_output=True, text=True, errors="replace")
|
|
152
|
+
if r.returncode != 0:
|
|
153
|
+
return None
|
|
154
|
+
for line in r.stderr.splitlines():
|
|
155
|
+
if line.startswith("password: 0x"):
|
|
156
|
+
return bytes.fromhex(line[len("password: 0x"):].split()[0]).decode("utf-8", "replace")
|
|
157
|
+
if line.startswith('password: "') and line.endswith('"'):
|
|
158
|
+
return line[len('password: "'):-1]
|
|
159
|
+
if line == "password: ":
|
|
160
|
+
return ""
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
def remove(self, acct):
|
|
164
|
+
return subprocess.run(["security", "delete-generic-password", "-s", SERVICE, "-a", acct],
|
|
165
|
+
stdout=DEVNULL, stderr=DEVNULL).returncode == 0
|
|
166
|
+
|
|
167
|
+
def names(self):
|
|
168
|
+
r = subprocess.run(["security", "dump-keychain"], capture_output=True, text=True)
|
|
169
|
+
out, acct = [], None
|
|
170
|
+
for line in r.stdout.splitlines():
|
|
171
|
+
if line.startswith("keychain:"):
|
|
172
|
+
acct = None
|
|
173
|
+
m = re.search(r'"acct"<blob>="(.*)"$', line)
|
|
174
|
+
if m:
|
|
175
|
+
acct = m.group(1)
|
|
176
|
+
if f'"svce"<blob>="{SERVICE}"' in line and acct:
|
|
177
|
+
out.append(acct)
|
|
178
|
+
return out
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class SecretService:
|
|
182
|
+
label = "Secret Service"
|
|
183
|
+
|
|
184
|
+
def _run(self, args, value=None):
|
|
185
|
+
return subprocess.run(["secret-tool"] + args, input=value, text=True,
|
|
186
|
+
capture_output=True, timeout=30)
|
|
187
|
+
|
|
188
|
+
def store(self, acct, value):
|
|
189
|
+
r = self._run(["store", "--label", f"{SERVICE} {acct}", "service", SERVICE, "account", acct], value)
|
|
190
|
+
return r.returncode == 0 and self.fetch(acct) == value
|
|
191
|
+
|
|
192
|
+
def fetch(self, acct):
|
|
193
|
+
r = self._run(["lookup", "service", SERVICE, "account", acct])
|
|
194
|
+
return r.stdout.rstrip("\n") if r.returncode == 0 and r.stdout else None
|
|
195
|
+
|
|
196
|
+
def remove(self, acct):
|
|
197
|
+
return self._run(["clear", "service", SERVICE, "account", acct]).returncode == 0 and self.fetch(acct) is None
|
|
198
|
+
|
|
199
|
+
def names(self):
|
|
200
|
+
# `search` also prints each secret; only the account attribute is kept, nothing is shown.
|
|
201
|
+
r = self._run(["search", "--all", "service", SERVICE])
|
|
202
|
+
return [m.group(1) for m in re.finditer(r"^attribute\.account = (.+)$", r.stdout + r.stderr, re.M)]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class FileStore:
|
|
206
|
+
label = "file 0600"
|
|
207
|
+
|
|
208
|
+
def __init__(self):
|
|
209
|
+
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
|
|
210
|
+
self.dir = os.path.join(base, "herdr-secret", "store")
|
|
211
|
+
|
|
212
|
+
def _path(self, acct):
|
|
213
|
+
return os.path.join(self.dir, acct)
|
|
214
|
+
|
|
215
|
+
def store(self, acct, value):
|
|
216
|
+
os.makedirs(self.dir, mode=0o700, exist_ok=True)
|
|
217
|
+
os.chmod(self.dir, 0o700)
|
|
218
|
+
write_atomic(self._path(acct), value)
|
|
219
|
+
return self.fetch(acct) == value
|
|
220
|
+
|
|
221
|
+
def fetch(self, acct):
|
|
222
|
+
try:
|
|
223
|
+
with open(self._path(acct), encoding="utf-8") as f:
|
|
224
|
+
return f.read()
|
|
225
|
+
except OSError:
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
def remove(self, acct):
|
|
229
|
+
try:
|
|
230
|
+
os.unlink(self._path(acct))
|
|
231
|
+
return True
|
|
232
|
+
except OSError:
|
|
233
|
+
return False
|
|
234
|
+
|
|
235
|
+
def names(self):
|
|
236
|
+
try:
|
|
237
|
+
return sorted(n for n in os.listdir(self.dir) if not n.startswith("."))
|
|
238
|
+
except OSError:
|
|
239
|
+
return []
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class WinCred:
|
|
243
|
+
label = "Windows Credential Manager"
|
|
244
|
+
|
|
245
|
+
def __init__(self):
|
|
246
|
+
import ctypes
|
|
247
|
+
from ctypes import wintypes
|
|
248
|
+
self.ct = ctypes
|
|
249
|
+
|
|
250
|
+
class CREDENTIAL(ctypes.Structure):
|
|
251
|
+
_fields_ = [("Flags", wintypes.DWORD), ("Type", wintypes.DWORD),
|
|
252
|
+
("TargetName", wintypes.LPWSTR), ("Comment", wintypes.LPWSTR),
|
|
253
|
+
("LastWritten", wintypes.FILETIME), ("CredentialBlobSize", wintypes.DWORD),
|
|
254
|
+
("CredentialBlob", ctypes.POINTER(ctypes.c_ubyte)), ("Persist", wintypes.DWORD),
|
|
255
|
+
("AttributeCount", wintypes.DWORD), ("Attributes", ctypes.c_void_p),
|
|
256
|
+
("TargetAlias", wintypes.LPWSTR), ("UserName", wintypes.LPWSTR)]
|
|
257
|
+
|
|
258
|
+
self.CRED = CREDENTIAL
|
|
259
|
+
P = ctypes.POINTER(CREDENTIAL)
|
|
260
|
+
a = ctypes.WinDLL("advapi32", use_last_error=True)
|
|
261
|
+
a.CredWriteW.argtypes = [P, wintypes.DWORD]
|
|
262
|
+
a.CredWriteW.restype = wintypes.BOOL
|
|
263
|
+
a.CredReadW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(P)]
|
|
264
|
+
a.CredReadW.restype = wintypes.BOOL
|
|
265
|
+
a.CredDeleteW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD]
|
|
266
|
+
a.CredDeleteW.restype = wintypes.BOOL
|
|
267
|
+
a.CredEnumerateW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD),
|
|
268
|
+
ctypes.POINTER(ctypes.POINTER(P))]
|
|
269
|
+
a.CredEnumerateW.restype = wintypes.BOOL
|
|
270
|
+
a.CredFree.argtypes = [ctypes.c_void_p]
|
|
271
|
+
a.CredFree.restype = None
|
|
272
|
+
self.a = a
|
|
273
|
+
|
|
274
|
+
@staticmethod
|
|
275
|
+
def _target(acct):
|
|
276
|
+
return f"{SERVICE}:{acct}"
|
|
277
|
+
|
|
278
|
+
def store(self, acct, value):
|
|
279
|
+
ct = self.ct
|
|
280
|
+
blob = value.encode("utf-16-le")
|
|
281
|
+
buf = ct.create_string_buffer(blob, len(blob))
|
|
282
|
+
c = self.CRED()
|
|
283
|
+
c.Type = 1 # CRED_TYPE_GENERIC
|
|
284
|
+
c.TargetName = self._target(acct)
|
|
285
|
+
c.UserName = acct
|
|
286
|
+
c.CredentialBlobSize = len(blob)
|
|
287
|
+
c.CredentialBlob = ct.cast(buf, ct.POINTER(ct.c_ubyte))
|
|
288
|
+
c.Persist = 2 # CRED_PERSIST_LOCAL_MACHINE
|
|
289
|
+
ok = self.a.CredWriteW(ct.byref(c), 0)
|
|
290
|
+
ct.memset(buf, 0, len(blob))
|
|
291
|
+
return bool(ok) and self.fetch(acct) == value
|
|
292
|
+
|
|
293
|
+
def fetch(self, acct):
|
|
294
|
+
ct = self.ct
|
|
295
|
+
p = ct.POINTER(self.CRED)()
|
|
296
|
+
if not self.a.CredReadW(self._target(acct), 1, 0, ct.byref(p)):
|
|
297
|
+
return None
|
|
298
|
+
try:
|
|
299
|
+
c = p.contents
|
|
300
|
+
return ct.string_at(c.CredentialBlob, c.CredentialBlobSize).decode("utf-16-le")
|
|
301
|
+
finally:
|
|
302
|
+
self.a.CredFree(p)
|
|
303
|
+
|
|
304
|
+
def remove(self, acct):
|
|
305
|
+
return bool(self.a.CredDeleteW(self._target(acct), 1, 0))
|
|
306
|
+
|
|
307
|
+
def names(self):
|
|
308
|
+
ct = self.ct
|
|
309
|
+
from ctypes import wintypes
|
|
310
|
+
n = wintypes.DWORD()
|
|
311
|
+
arr = ct.POINTER(ct.POINTER(self.CRED))()
|
|
312
|
+
if not self.a.CredEnumerateW(f"{SERVICE}:*", 0, ct.byref(n), ct.byref(arr)):
|
|
313
|
+
return []
|
|
314
|
+
try:
|
|
315
|
+
return sorted(arr[i].contents.TargetName[len(SERVICE) + 1:] for i in range(n.value))
|
|
316
|
+
finally:
|
|
317
|
+
self.a.CredFree(arr)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def backends():
|
|
321
|
+
if IS_MAC:
|
|
322
|
+
return [MacKeychain()]
|
|
323
|
+
if IS_WIN:
|
|
324
|
+
return [WinCred()]
|
|
325
|
+
chain = [SecretService()] if shutil.which("secret-tool") else []
|
|
326
|
+
return chain + [FileStore()]
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def store_any(acct, value):
|
|
330
|
+
chain = backends()
|
|
331
|
+
for i, b in enumerate(chain):
|
|
332
|
+
try:
|
|
333
|
+
stored = b.store(acct, value)
|
|
334
|
+
except Exception:
|
|
335
|
+
stored = False
|
|
336
|
+
if not stored:
|
|
337
|
+
continue
|
|
338
|
+
for other in chain[:i] + chain[i + 1:]:
|
|
339
|
+
try:
|
|
340
|
+
other.remove(acct)
|
|
341
|
+
except Exception:
|
|
342
|
+
pass
|
|
343
|
+
# A store that refused this write (say a locked keyring) may still hold an older copy,
|
|
344
|
+
# and `get` asks it first. Report failure rather than leave the old value in front.
|
|
345
|
+
return b.label if fetch_any(acct) == value else None
|
|
346
|
+
return None
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def fetch_any(acct):
|
|
350
|
+
for b in backends():
|
|
351
|
+
try:
|
|
352
|
+
v = b.fetch(acct)
|
|
353
|
+
except Exception:
|
|
354
|
+
v = None
|
|
355
|
+
if v is not None:
|
|
356
|
+
return v
|
|
357
|
+
return None
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def remove_any(acct):
|
|
361
|
+
hit = False
|
|
362
|
+
for b in backends():
|
|
363
|
+
try:
|
|
364
|
+
hit = b.remove(acct) or hit
|
|
365
|
+
except Exception:
|
|
366
|
+
pass
|
|
367
|
+
return hit
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def names_any():
|
|
371
|
+
out = set()
|
|
372
|
+
for b in backends():
|
|
373
|
+
try:
|
|
374
|
+
out.update(b.names())
|
|
375
|
+
except Exception:
|
|
376
|
+
pass
|
|
377
|
+
return sorted(out)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
# ---------------------------------------------------------------- terminal form
|
|
381
|
+
|
|
382
|
+
BOLD, DIM, CYAN, RED, YELLOW, REV, RESET = "\x1b[1m", "\x1b[2m", "\x1b[36m", "\x1b[31m", "\x1b[33m", "\x1b[7m", "\x1b[0m"
|
|
383
|
+
GREEN = "\x1b[32m"
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class Term:
|
|
387
|
+
def __enter__(self):
|
|
388
|
+
if IS_WIN:
|
|
389
|
+
import msvcrt
|
|
390
|
+
self.msvcrt = msvcrt
|
|
391
|
+
os.system("") # turns on VT escape processing in the console
|
|
392
|
+
try:
|
|
393
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
394
|
+
except Exception:
|
|
395
|
+
pass
|
|
396
|
+
else:
|
|
397
|
+
import termios
|
|
398
|
+
import tty
|
|
399
|
+
self.termios = termios
|
|
400
|
+
self.fd = sys.stdin.fileno()
|
|
401
|
+
self.saved = termios.tcgetattr(self.fd)
|
|
402
|
+
tty.setraw(self.fd)
|
|
403
|
+
self.out("\x1b[?1049h\x1b[H\x1b[2J")
|
|
404
|
+
return self
|
|
405
|
+
|
|
406
|
+
def __exit__(self, *exc):
|
|
407
|
+
self.out("\x1b[?25h\x1b[?1049l")
|
|
408
|
+
if not IS_WIN:
|
|
409
|
+
self.termios.tcsetattr(self.fd, self.termios.TCSADRAIN, self.saved)
|
|
410
|
+
|
|
411
|
+
@staticmethod
|
|
412
|
+
def out(s):
|
|
413
|
+
sys.stdout.write(s)
|
|
414
|
+
sys.stdout.flush()
|
|
415
|
+
|
|
416
|
+
@staticmethod
|
|
417
|
+
def size():
|
|
418
|
+
return shutil.get_terminal_size((76, 24))
|
|
419
|
+
|
|
420
|
+
def key(self, timeout):
|
|
421
|
+
"""One key, or None after `timeout` seconds without input."""
|
|
422
|
+
return self._key_win(timeout) if IS_WIN else self._key_unix(timeout)
|
|
423
|
+
|
|
424
|
+
def _read(self, n):
|
|
425
|
+
buf = b""
|
|
426
|
+
while len(buf) < n:
|
|
427
|
+
chunk = os.read(self.fd, n - len(buf))
|
|
428
|
+
if not chunk:
|
|
429
|
+
break
|
|
430
|
+
buf += chunk
|
|
431
|
+
return buf
|
|
432
|
+
|
|
433
|
+
def _key_unix(self, timeout):
|
|
434
|
+
import select
|
|
435
|
+
if not select.select([self.fd], [], [], timeout)[0]:
|
|
436
|
+
return None
|
|
437
|
+
b = os.read(self.fd, 1)
|
|
438
|
+
if not b:
|
|
439
|
+
return "CANCEL"
|
|
440
|
+
c = b[0]
|
|
441
|
+
if c == 0x1B:
|
|
442
|
+
if not select.select([self.fd], [], [], 0.03)[0]:
|
|
443
|
+
return "ESC"
|
|
444
|
+
nxt = os.read(self.fd, 1)
|
|
445
|
+
if nxt not in (b"[", b"O"):
|
|
446
|
+
return "ESC"
|
|
447
|
+
seq = b""
|
|
448
|
+
while len(seq) < 8:
|
|
449
|
+
ch = os.read(self.fd, 1)
|
|
450
|
+
seq += ch
|
|
451
|
+
if ch.isalpha() or ch == b"~":
|
|
452
|
+
break
|
|
453
|
+
return {b"A": "UP", b"B": "DOWN", b"C": "RIGHT", b"D": "LEFT", b"Z": "BTAB"}.get(seq[-1:])
|
|
454
|
+
simple = {0x0D: "ENTER", 0x0A: "ENTER", 0x09: "TAB", 0x7F: "BS", 0x08: "BS",
|
|
455
|
+
0x03: "CANCEL", 0x04: "CANCEL", 0x15: "CLEAR", 0x12: "REVEAL"}
|
|
456
|
+
if c in simple:
|
|
457
|
+
return simple[c]
|
|
458
|
+
if c < 0x20:
|
|
459
|
+
return None
|
|
460
|
+
n = 1 if c < 0x80 else 2 if c >> 5 == 0b110 else 3 if c >> 4 == 0b1110 else 4 if c >> 3 == 0b11110 else 1
|
|
461
|
+
if n > 1:
|
|
462
|
+
b += self._read(n - 1)
|
|
463
|
+
ch = b.decode("utf-8", "ignore")
|
|
464
|
+
return ("CHAR", ch) if ch and ch.isprintable() else None
|
|
465
|
+
|
|
466
|
+
def _key_win(self, timeout):
|
|
467
|
+
m = self.msvcrt
|
|
468
|
+
end = time.time() + timeout
|
|
469
|
+
while not m.kbhit():
|
|
470
|
+
if time.time() >= end:
|
|
471
|
+
return None
|
|
472
|
+
time.sleep(0.03)
|
|
473
|
+
ch = m.getwch()
|
|
474
|
+
if ch in ("\x00", "\xe0"):
|
|
475
|
+
return {"H": "UP", "P": "DOWN", "K": "LEFT", "M": "RIGHT", "\x0f": "BTAB"}.get(m.getwch())
|
|
476
|
+
simple = {"\r": "ENTER", "\n": "ENTER", "\t": "TAB", "\x08": "BS", "\x1b": "ESC",
|
|
477
|
+
"\x03": "CANCEL", "\x15": "CLEAR", "\x12": "REVEAL"}
|
|
478
|
+
if ch in simple:
|
|
479
|
+
return simple[ch]
|
|
480
|
+
return ("CHAR", ch) if ch.isprintable() else None
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def wrap(text, width):
|
|
484
|
+
width = max(8, width)
|
|
485
|
+
lines, cur = [], ""
|
|
486
|
+
for word in text.split():
|
|
487
|
+
while dwidth(word) > width: # hard-split words longer than a line
|
|
488
|
+
head, _ = fit_head(word, width)
|
|
489
|
+
if cur:
|
|
490
|
+
lines.append(cur)
|
|
491
|
+
cur = ""
|
|
492
|
+
lines.append(head)
|
|
493
|
+
word = word[len(head):]
|
|
494
|
+
if cur and dwidth(cur) + 1 + dwidth(word) > width:
|
|
495
|
+
lines.append(cur)
|
|
496
|
+
cur = word
|
|
497
|
+
elif word:
|
|
498
|
+
cur = f"{cur} {word}" if cur else word
|
|
499
|
+
return lines + [cur] if cur else (lines or [""])
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
class Form:
|
|
503
|
+
def __init__(self, fields, name, who, purpose, notice, store=None):
|
|
504
|
+
self.fields, self.name, self.who, self.purpose, self.notice = fields, name, who, purpose, notice
|
|
505
|
+
self.store = store if store is not None else store_note() # (text, encrypted)
|
|
506
|
+
self.values = [[] for _ in fields]
|
|
507
|
+
self.reveal = [False] * len(fields)
|
|
508
|
+
self.focus = 0 # 0..n-1 fields, n = save, n+1 = cancel
|
|
509
|
+
self.error = ""
|
|
510
|
+
|
|
511
|
+
def build(self, cols, compact, pmax, nmax, blanks, show_help):
|
|
512
|
+
n = len(self.fields)
|
|
513
|
+
bw = max(24, min(cols - 4, 68))
|
|
514
|
+
lines, cursor = [], None
|
|
515
|
+
|
|
516
|
+
def add(text, style=""):
|
|
517
|
+
text, _ = fit_head(text, max(10, cols - 3))
|
|
518
|
+
lines.append(f" {style}{text}{RESET}" if style else f" {text}")
|
|
519
|
+
|
|
520
|
+
add(T["title"] + self.name, BOLD)
|
|
521
|
+
add(T["from"] + self.who + T["reported"], DIM)
|
|
522
|
+
pad = " " * dwidth(T["for"])
|
|
523
|
+
for i, part in enumerate(wrap(self.purpose, bw - len(pad))[:pmax]):
|
|
524
|
+
add((T["for"] if i == 0 else pad) + part)
|
|
525
|
+
text, encrypted = self.store
|
|
526
|
+
for i, part in enumerate(wrap(text, bw - len(pad))[:max(1, pmax - 1)]):
|
|
527
|
+
add((T["saved_to"] if i == 0 else pad) + part, GREEN if encrypted else YELLOW)
|
|
528
|
+
if self.notice:
|
|
529
|
+
for part in wrap(self.notice, bw)[:nmax]:
|
|
530
|
+
add(part, YELLOW)
|
|
531
|
+
if blanks:
|
|
532
|
+
add("")
|
|
533
|
+
for i, (_f, label, hidden) in enumerate(self.fields):
|
|
534
|
+
style = CYAN + BOLD if self.focus == i else ""
|
|
535
|
+
masked = hidden and not self.reveal[i]
|
|
536
|
+
raw = "".join(self.values[i])
|
|
537
|
+
full = ("•" * len(raw)) if masked else raw
|
|
538
|
+
if compact:
|
|
539
|
+
prefix = f"{'›' if self.focus == i else ' '} {label}{T['hidden'] if masked else ''}: "
|
|
540
|
+
shown, w = fit_tail(full, max(4, bw - dwidth(prefix)))
|
|
541
|
+
lines.append(f" {style}{prefix}{RESET}{shown}")
|
|
542
|
+
if self.focus == i:
|
|
543
|
+
cursor = (len(lines), 2 + dwidth(prefix) + w + 1)
|
|
544
|
+
else:
|
|
545
|
+
tag = f" {label}{T['hidden'] if masked else ''} "
|
|
546
|
+
inner = bw - 4
|
|
547
|
+
shown, w = fit_tail(full, inner)
|
|
548
|
+
add("┌" + tag + "─" * max(0, bw - 2 - dwidth(tag)) + "┐", style)
|
|
549
|
+
lines.append(f" {style}│{RESET} {shown}{' ' * (inner - w)} {style}│{RESET}")
|
|
550
|
+
if self.focus == i:
|
|
551
|
+
cursor = (len(lines), 2 + 2 + w + 1)
|
|
552
|
+
add("└" + "─" * (bw - 2) + "┘", style)
|
|
553
|
+
if self.error:
|
|
554
|
+
add(self.error, RED)
|
|
555
|
+
elif blanks:
|
|
556
|
+
add("")
|
|
557
|
+
save = f"{REV}{BOLD}{T['save']}{RESET}" if self.focus == n else f"{BOLD}{T['save']}{RESET}"
|
|
558
|
+
cancel = f"{REV}{T['cancel']}{RESET}" if self.focus == n + 1 else T["cancel"]
|
|
559
|
+
lines.append(f" {save} {cancel}")
|
|
560
|
+
if show_help:
|
|
561
|
+
if blanks:
|
|
562
|
+
add("")
|
|
563
|
+
add(T["help"], DIM)
|
|
564
|
+
return lines, cursor
|
|
565
|
+
|
|
566
|
+
def render(self, cols, rows):
|
|
567
|
+
"""Largest layout that fits. The title and "From" lines always come first and stay."""
|
|
568
|
+
for cfg in ((False, 3, 2, True, True), (True, 3, 2, True, True), (True, 2, 1, False, True),
|
|
569
|
+
(True, 1, 1, False, True), (True, 1, 1, False, False)):
|
|
570
|
+
lines, cursor = self.build(cols, *cfg)
|
|
571
|
+
if len(lines) <= rows:
|
|
572
|
+
break
|
|
573
|
+
lines = lines[:rows]
|
|
574
|
+
if cursor and cursor[0] > rows:
|
|
575
|
+
cursor = None
|
|
576
|
+
return lines, cursor
|
|
577
|
+
|
|
578
|
+
def handle(self, k):
|
|
579
|
+
"""Returns "SAVE", "CANCEL" or None."""
|
|
580
|
+
n = len(self.fields)
|
|
581
|
+
self.error = ""
|
|
582
|
+
if k in ("ESC", "CANCEL"):
|
|
583
|
+
return "CANCEL"
|
|
584
|
+
if k in ("TAB", "DOWN"):
|
|
585
|
+
self.focus = (self.focus + 1) % (n + 2)
|
|
586
|
+
elif k in ("BTAB", "UP"):
|
|
587
|
+
self.focus = (self.focus - 1) % (n + 2)
|
|
588
|
+
elif k in ("LEFT", "RIGHT") and self.focus >= n:
|
|
589
|
+
self.focus = n + 1 if self.focus == n else n
|
|
590
|
+
elif k == "ENTER":
|
|
591
|
+
if self.focus == n + 1:
|
|
592
|
+
return "CANCEL"
|
|
593
|
+
if self.focus >= n - 1:
|
|
594
|
+
empty = [i for i in range(n) if not self.values[i]]
|
|
595
|
+
if not empty:
|
|
596
|
+
return "SAVE"
|
|
597
|
+
self.focus, self.error = empty[0], T["required"]
|
|
598
|
+
else:
|
|
599
|
+
self.focus += 1
|
|
600
|
+
elif self.focus < n:
|
|
601
|
+
v = self.values[self.focus]
|
|
602
|
+
if k == "BS" and v:
|
|
603
|
+
v.pop()
|
|
604
|
+
elif k == "CLEAR":
|
|
605
|
+
v.clear()
|
|
606
|
+
elif k == "REVEAL":
|
|
607
|
+
self.reveal[self.focus] = not self.reveal[self.focus]
|
|
608
|
+
elif isinstance(k, tuple):
|
|
609
|
+
if len(v) >= MAX_VALUE:
|
|
610
|
+
self.error = T["toolong"].format(MAX_VALUE)
|
|
611
|
+
else:
|
|
612
|
+
v.append(k[1])
|
|
613
|
+
return None
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def run_form(term, form, deadline):
|
|
617
|
+
last = None
|
|
618
|
+
while True:
|
|
619
|
+
if deadline and time.time() >= deadline:
|
|
620
|
+
return "TIMEOUT"
|
|
621
|
+
cols, rows = term.size()
|
|
622
|
+
lines, cursor = form.render(cols, rows)
|
|
623
|
+
frame = "\x1b[H" + "\r\n".join(line + "\x1b[K" for line in lines) + "\x1b[J"
|
|
624
|
+
frame += f"\x1b[{cursor[0]};{cursor[1]}H\x1b[?25h" if cursor else "\x1b[?25l"
|
|
625
|
+
if frame != last: # only after a key or a resize
|
|
626
|
+
term.out(frame)
|
|
627
|
+
last = frame
|
|
628
|
+
k = term.key(1.0)
|
|
629
|
+
if k is None:
|
|
630
|
+
continue
|
|
631
|
+
action = form.handle(k)
|
|
632
|
+
if action == "CANCEL":
|
|
633
|
+
return None
|
|
634
|
+
if action == "SAVE":
|
|
635
|
+
return ["".join(v) for v in form.values]
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def parse_fields(spec, value_label="Value"):
|
|
639
|
+
if not spec:
|
|
640
|
+
return [("value", value_label, True)], True
|
|
641
|
+
out = []
|
|
642
|
+
for part in spec.split(","):
|
|
643
|
+
fname, _, kind = part.strip().partition(":")
|
|
644
|
+
if not FIELD_RE.fullmatch(fname) or kind not in ("", "plain", "hidden"):
|
|
645
|
+
raise ValueError(f"invalid field: {part.strip()!r}")
|
|
646
|
+
hidden = (kind == "hidden") if kind else fname not in PLAIN_BY_DEFAULT
|
|
647
|
+
out.append((fname, fname.replace("_", " ").capitalize(), hidden))
|
|
648
|
+
if len(out) > MAX_FIELDS or len({f for f, _, _ in out}) != len(out):
|
|
649
|
+
raise ValueError(f"up to {MAX_FIELDS} fields, no duplicates")
|
|
650
|
+
return out, len(out) == 1 and out[0][0] == "value"
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def store_fields(name, single, fields, values):
|
|
654
|
+
"""Store every value or none: on a failure the earlier fields get their old values back.
|
|
655
|
+
Returns (ok, where)."""
|
|
656
|
+
accts = [name if single else f"{name}.{f}" for f, _l, _h in fields]
|
|
657
|
+
prev = {a: fetch_any(a) for a in accts}
|
|
658
|
+
where, done = set(), []
|
|
659
|
+
for a, value in zip(accts, values):
|
|
660
|
+
label = store_any(a, value)
|
|
661
|
+
if label is None:
|
|
662
|
+
break
|
|
663
|
+
where.add(label)
|
|
664
|
+
done.append(a)
|
|
665
|
+
ok = len(done) == len(accts)
|
|
666
|
+
if not ok:
|
|
667
|
+
for a in done:
|
|
668
|
+
if prev[a] is None:
|
|
669
|
+
remove_any(a)
|
|
670
|
+
else:
|
|
671
|
+
store_any(a, prev[a])
|
|
672
|
+
prev.clear()
|
|
673
|
+
return ok, where
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def cmd_form():
|
|
677
|
+
name = os.environ.get("SECRET_NAME", "")
|
|
678
|
+
req = os.environ.get("SECRET_REQ", "")
|
|
679
|
+
try:
|
|
680
|
+
deadline = float(os.environ.get("SECRET_DEADLINE") or 0)
|
|
681
|
+
except ValueError:
|
|
682
|
+
deadline = 0
|
|
683
|
+
reported = []
|
|
684
|
+
|
|
685
|
+
def status(s):
|
|
686
|
+
if not reported and REQ_RE.fullmatch(req):
|
|
687
|
+
write_atomic(os.path.join(state_dir(), req + ".status"), s + "\n")
|
|
688
|
+
reported.append(s)
|
|
689
|
+
|
|
690
|
+
def bail(*_):
|
|
691
|
+
raise SystemExit(1)
|
|
692
|
+
|
|
693
|
+
guarded = () if IS_WIN else (signal.SIGHUP, signal.SIGTERM)
|
|
694
|
+
for sig in guarded:
|
|
695
|
+
signal.signal(sig, bail)
|
|
696
|
+
try:
|
|
697
|
+
if not NAME_RE.fullmatch(name) or not REQ_RE.fullmatch(req):
|
|
698
|
+
print(T["invalid"])
|
|
699
|
+
time.sleep(2)
|
|
700
|
+
return 1
|
|
701
|
+
fields, single = parse_fields(os.environ.get("SECRET_FIELDS", "").strip(), T["value"])
|
|
702
|
+
accts = [name if single else f"{name}.{f}" for f, _, _ in fields]
|
|
703
|
+
prev = {a: fetch_any(a) for a in accts}
|
|
704
|
+
existing = [a for a in accts if prev[a] is not None]
|
|
705
|
+
notice = T["replaces"].format(", ".join(existing)) if existing else ""
|
|
706
|
+
who = clean(os.environ.get("SECRET_FROM", ""), 80) or T["unknown"]
|
|
707
|
+
form = Form(fields, name, who, clean(os.environ.get("SECRET_PROMPT", "")), notice)
|
|
708
|
+
try:
|
|
709
|
+
with Term() as t:
|
|
710
|
+
result = run_form(t, form, deadline)
|
|
711
|
+
except KeyboardInterrupt:
|
|
712
|
+
result = None
|
|
713
|
+
if result is None:
|
|
714
|
+
status("CANCELLED")
|
|
715
|
+
return 1
|
|
716
|
+
if result == "TIMEOUT":
|
|
717
|
+
status("TIMEOUT")
|
|
718
|
+
print("\n " + T["timeout"])
|
|
719
|
+
time.sleep(1.5)
|
|
720
|
+
return 1
|
|
721
|
+
if guarded: # a stored value must never be reported as CANCELLED
|
|
722
|
+
signal.pthread_sigmask(signal.SIG_BLOCK, set(guarded))
|
|
723
|
+
ok, where = store_fields(name, single, fields, result)
|
|
724
|
+
result[:] = []
|
|
725
|
+
prev.clear()
|
|
726
|
+
status(("OK " + ", ".join(sorted(where))) if ok else "FAILED")
|
|
727
|
+
if guarded:
|
|
728
|
+
signal.pthread_sigmask(signal.SIG_UNBLOCK, set(guarded))
|
|
729
|
+
print("\n " + (T["saved"].format(", ".join(sorted(where))) if ok else T["failed"]))
|
|
730
|
+
time.sleep(0.8 if ok else 3)
|
|
731
|
+
return 0 if ok else 1
|
|
732
|
+
finally:
|
|
733
|
+
status("CANCELLED")
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
# ---------------------------------------------------------------- agent-side commands
|
|
737
|
+
|
|
738
|
+
def cmd_ask(argv):
|
|
739
|
+
if not argv:
|
|
740
|
+
print(__doc__.strip(), file=sys.stderr)
|
|
741
|
+
return 2
|
|
742
|
+
name, rest = argv[0], argv[1:]
|
|
743
|
+
purpose = rest.pop(0) if rest and not rest[0].startswith("--") else ""
|
|
744
|
+
fields, timeout = "", 300
|
|
745
|
+
while rest:
|
|
746
|
+
a = rest.pop(0)
|
|
747
|
+
if a == "--fields" and rest:
|
|
748
|
+
fields = rest.pop(0)
|
|
749
|
+
elif a == "--plain":
|
|
750
|
+
fields = "value:plain"
|
|
751
|
+
elif a == "--timeout" and rest:
|
|
752
|
+
timeout = max(5, int(rest.pop(0)))
|
|
753
|
+
else:
|
|
754
|
+
print(f"unknown option {a!r}", file=sys.stderr)
|
|
755
|
+
return 2
|
|
756
|
+
if not NAME_RE.fullmatch(name):
|
|
757
|
+
print("invalid NAME: letters, digits, _ . - and starting with a letter or digit", file=sys.stderr)
|
|
758
|
+
return 2
|
|
759
|
+
try:
|
|
760
|
+
parse_fields(fields)
|
|
761
|
+
except ValueError as e:
|
|
762
|
+
print(str(e), file=sys.stderr)
|
|
763
|
+
return 2
|
|
764
|
+
if in_app_terminal():
|
|
765
|
+
# A Herdr.app (herdr-core) terminal. herdr-core has no plugin popups; the herdr-secret
|
|
766
|
+
# mod shows the form as a Herdr.app dialog instead. Without it, say so at once rather
|
|
767
|
+
# than open a TUI popup nobody may be looking at.
|
|
768
|
+
if not os.path.exists(os.path.join(app_mod_dir(), "main.js")):
|
|
769
|
+
tag = f" ({fields})" if fields and fields != "value:plain" else ""
|
|
770
|
+
print(f"FAILED {name}{tag} [this terminal belongs to Herdr.app; install the herdr-secret mod "
|
|
771
|
+
f"with: npx herdr-secret@latest]")
|
|
772
|
+
return 1
|
|
773
|
+
return app_ask(name, purpose, fields, timeout)
|
|
774
|
+
req = f"{int(time.time())}-{os.getpid()}-{secrets.token_hex(4)}"
|
|
775
|
+
deadline = time.time() + timeout
|
|
776
|
+
herdr = os.environ.get("HERDR_BIN_PATH") or shutil.which("herdr") or "herdr"
|
|
777
|
+
cmd = [herdr, "plugin", "pane", "open", "--plugin", PLUGIN_ID,
|
|
778
|
+
"--entrypoint", "ask-windows" if IS_WIN else "ask", "--focus"]
|
|
779
|
+
env = {"SECRET_NAME": name, "SECRET_PROMPT": clean(purpose), "SECRET_FIELDS": fields,
|
|
780
|
+
"SECRET_REQ": req, "SECRET_DEADLINE": f"{deadline:.0f}",
|
|
781
|
+
"SECRET_FROM": os.environ.get("HERDR_PANE_ID", "outside herdr")}
|
|
782
|
+
for k, v in env.items():
|
|
783
|
+
cmd += ["--env", f"{k}={v}"]
|
|
784
|
+
tag = f" ({fields})" if fields and fields != "value:plain" else ""
|
|
785
|
+
try:
|
|
786
|
+
r = subprocess.run(cmd, stdout=DEVNULL, stderr=subprocess.PIPE, text=True)
|
|
787
|
+
except OSError as e:
|
|
788
|
+
print(f"FAILED {name}{tag} [herdr not runnable: {e}]")
|
|
789
|
+
return 1
|
|
790
|
+
if r.returncode != 0:
|
|
791
|
+
print(f"FAILED {name}{tag} [herdr: {r.stderr.strip()[:200]}]")
|
|
792
|
+
return 1
|
|
793
|
+
path = os.path.join(state_dir(), req + ".status")
|
|
794
|
+
while time.time() < deadline + 5: # the form closes itself at the deadline
|
|
795
|
+
if os.path.exists(path):
|
|
796
|
+
with open(path, encoding="utf-8") as f:
|
|
797
|
+
s = f.read().strip()
|
|
798
|
+
os.unlink(path)
|
|
799
|
+
word, _, where = s.partition(" ")
|
|
800
|
+
print(f"{word} {name}{tag}" + (f" [{where}]" if where else ""))
|
|
801
|
+
return 0 if word == "OK" else 1
|
|
802
|
+
time.sleep(0.5)
|
|
803
|
+
print(f"TIMEOUT {name}{tag}")
|
|
804
|
+
return 1
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
# ---------------------------------------------------------------- Herdr.app dialog
|
|
808
|
+
#
|
|
809
|
+
# Herdr.app runs its terminals in herdr-core, which has no plugin popups. There, ask opens the
|
|
810
|
+
# herdr-secret mod (mods/herdr-secret) as a Herdr.app dialog instead. Mods can run programs only
|
|
811
|
+
# with arguments (no stdin), so a typed value would show in the process list on its way to the
|
|
812
|
+
# store. So ask writes a one-time pad into the request (in a 0700 folder); the mod XORs each
|
|
813
|
+
# value with its slice of the pad and passes hex, and app-store undoes that and deletes the
|
|
814
|
+
# request, pad included. Every app-store call ends the request, so a pad never covers two values.
|
|
815
|
+
|
|
816
|
+
PAD_PER_FIELD = 4096 # bytes; MAX_VALUE characters are at most 4000 bytes of UTF-8
|
|
817
|
+
APP_MOD = "herdr-secret"
|
|
818
|
+
APP_MOD_FILES = ("main.js", "mod.json")
|
|
819
|
+
APP_MOD_MARK = "// herdr-secret for Herdr.app"
|
|
820
|
+
APP_GRACE = 1.0 # seconds between one dialog closing and the next opening
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def app_home():
|
|
824
|
+
return os.environ.get("HERDR_APP_HOME") or os.path.normpath(os.path.expanduser("~/.config/herdr-app"))
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def app_mod_dir():
|
|
828
|
+
return os.path.join(app_home(), "mods", APP_MOD)
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def is_our_mod(d):
|
|
832
|
+
try:
|
|
833
|
+
with open(os.path.join(d, "main.js"), encoding="utf-8") as f:
|
|
834
|
+
return f.readline().startswith(APP_MOD_MARK)
|
|
835
|
+
except OSError:
|
|
836
|
+
return False
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
def herdr_app_bin():
|
|
840
|
+
return shutil.which("herdr-app")
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def app_present():
|
|
844
|
+
return bool(herdr_app_bin()) or os.path.isdir(app_home())
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
def in_app_terminal():
|
|
848
|
+
return not os.environ.get("HERDR_PANE_ID") and bool(os.environ.get("HC_TERMINAL_SOCKET"))
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def app_state_dir():
|
|
852
|
+
"""The request and its answer. The mod finds them from its home() alone and does not see
|
|
853
|
+
this process's environment, so XDG_STATE_HOME and LOCALAPPDATA do not apply here."""
|
|
854
|
+
d = os.path.join(os.path.expanduser("~"), ".local", "state", "herdr-secret")
|
|
855
|
+
os.makedirs(d, mode=0o700, exist_ok=True)
|
|
856
|
+
if not IS_WIN:
|
|
857
|
+
os.chmod(d, 0o700)
|
|
858
|
+
return d
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def app_request_path():
|
|
862
|
+
return os.path.join(app_state_dir(), "app-request.json")
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def app_status_path(req):
|
|
866
|
+
return os.path.join(app_state_dir(), req + ".status")
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
def app_request(name, purpose, fields_spec, deadline):
|
|
870
|
+
"""Write the request the mod shows and return its id. Raises FileExistsError if another
|
|
871
|
+
request got there first: creating the file is what claims the one dialog."""
|
|
872
|
+
import json
|
|
873
|
+
fields, single = parse_fields(fields_spec)
|
|
874
|
+
req = f"{int(time.time())}-{os.getpid()}-{secrets.token_hex(4)}"
|
|
875
|
+
accts = [name if single else f"{name}.{f}" for f, _l, _h in fields]
|
|
876
|
+
known = set(names_any())
|
|
877
|
+
note, encrypted = store_note()
|
|
878
|
+
term = clean(os.environ.get("HC_TERMINAL_ID", ""), 40)
|
|
879
|
+
text = json.dumps({
|
|
880
|
+
"req": req, "name": name, "purpose": clean(purpose),
|
|
881
|
+
"from": f"terminal {term}" if term else T["unknown"],
|
|
882
|
+
"fields": [{"name": f, "label": label, "hidden": hidden} for f, label, hidden in fields],
|
|
883
|
+
"store": note, "encrypted": encrypted,
|
|
884
|
+
"replaces": [a for a in accts if a in known],
|
|
885
|
+
"deadline": deadline, "max": MAX_VALUE,
|
|
886
|
+
"pad": secrets.token_hex(PAD_PER_FIELD * len(fields)),
|
|
887
|
+
"python": sys.executable, "script": os.path.realpath(__file__),
|
|
888
|
+
})
|
|
889
|
+
fd = os.open(app_request_path(), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
890
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
891
|
+
f.write(text)
|
|
892
|
+
f.flush()
|
|
893
|
+
os.fsync(f.fileno())
|
|
894
|
+
return req
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def app_wait_turn(deadline):
|
|
898
|
+
"""One dialog at a time. False if another request was still open at our deadline."""
|
|
899
|
+
import json
|
|
900
|
+
path = app_request_path()
|
|
901
|
+
while os.path.exists(path):
|
|
902
|
+
try:
|
|
903
|
+
with open(path, encoding="utf-8") as f:
|
|
904
|
+
other = json.load(f)
|
|
905
|
+
if other.get("deadline", 0) + 5 < time.time():
|
|
906
|
+
os.unlink(path) # left behind by an asker that was killed
|
|
907
|
+
continue
|
|
908
|
+
except (OSError, ValueError, AttributeError):
|
|
909
|
+
pass
|
|
910
|
+
if time.time() >= deadline:
|
|
911
|
+
return False
|
|
912
|
+
time.sleep(0.5)
|
|
913
|
+
# mod.open toggles: a dialog that is still closing would be closed again instead of opened.
|
|
914
|
+
try:
|
|
915
|
+
with open(os.path.join(app_state_dir(), "app-done"), encoding="utf-8") as f:
|
|
916
|
+
wait = float(f.read()) + APP_GRACE - time.time()
|
|
917
|
+
if wait > 0:
|
|
918
|
+
time.sleep(min(wait, APP_GRACE))
|
|
919
|
+
except (OSError, ValueError):
|
|
920
|
+
pass
|
|
921
|
+
return True
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def app_raise():
|
|
925
|
+
"""mod.open shows the dialog in the Herdr window; bring that window forward too."""
|
|
926
|
+
if IS_MAC:
|
|
927
|
+
subprocess.run(["open", "-a", "Herdr"], stdout=DEVNULL, stderr=DEVNULL)
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def app_ask(name, purpose, fields_spec, timeout):
|
|
931
|
+
tag = f" ({fields_spec})" if fields_spec and fields_spec != "value:plain" else ""
|
|
932
|
+
deadline = time.time() + timeout
|
|
933
|
+
while True:
|
|
934
|
+
if not app_wait_turn(deadline):
|
|
935
|
+
print(f"TIMEOUT {name}{tag} [another credential request was still open]")
|
|
936
|
+
return 1
|
|
937
|
+
try:
|
|
938
|
+
req = app_request(name, purpose, fields_spec, deadline)
|
|
939
|
+
break
|
|
940
|
+
except FileExistsError:
|
|
941
|
+
continue
|
|
942
|
+
try:
|
|
943
|
+
try:
|
|
944
|
+
r = subprocess.run([herdr_app_bin() or "herdr-app", "do", "mod.open", "--name", APP_MOD],
|
|
945
|
+
capture_output=True, text=True, timeout=30)
|
|
946
|
+
err = "" if r.returncode == 0 else (r.stderr or r.stdout).strip() or f"exit {r.returncode}"
|
|
947
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
948
|
+
err = str(e)
|
|
949
|
+
if err:
|
|
950
|
+
print(f"FAILED {name}{tag} [herdr-app: {clean(err, 200)}]")
|
|
951
|
+
return 1
|
|
952
|
+
app_raise()
|
|
953
|
+
status_path = app_status_path(req)
|
|
954
|
+
while time.time() < deadline + 5: # the dialog closes itself at the deadline
|
|
955
|
+
if os.path.exists(status_path):
|
|
956
|
+
with open(status_path, encoding="utf-8") as f:
|
|
957
|
+
s = f.read().strip()
|
|
958
|
+
os.unlink(status_path)
|
|
959
|
+
word, _, where = s.partition(" ")
|
|
960
|
+
print(f"{word} {name}{tag}" + (f" [{where}]" if where else ""))
|
|
961
|
+
return 0 if word == "OK" else 1
|
|
962
|
+
time.sleep(0.5)
|
|
963
|
+
print(f"TIMEOUT {name}{tag}")
|
|
964
|
+
return 1
|
|
965
|
+
finally:
|
|
966
|
+
if app_load(req) is not None:
|
|
967
|
+
try:
|
|
968
|
+
os.unlink(app_request_path())
|
|
969
|
+
except OSError:
|
|
970
|
+
pass
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def app_load(req):
|
|
974
|
+
import json
|
|
975
|
+
if not REQ_RE.fullmatch(req or ""):
|
|
976
|
+
return None
|
|
977
|
+
try:
|
|
978
|
+
with open(app_request_path(), encoding="utf-8") as f:
|
|
979
|
+
request = json.load(f)
|
|
980
|
+
except (OSError, ValueError):
|
|
981
|
+
return None
|
|
982
|
+
return request if isinstance(request, dict) and request.get("req") == req else None
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
def app_finish(req, status):
|
|
986
|
+
"""End the request: the pad goes first, then the asker gets its answer."""
|
|
987
|
+
write_atomic(os.path.join(app_state_dir(), "app-done"), f"{time.time():.3f}\n")
|
|
988
|
+
if app_load(req) is not None:
|
|
989
|
+
try:
|
|
990
|
+
os.unlink(app_request_path())
|
|
991
|
+
except OSError:
|
|
992
|
+
pass
|
|
993
|
+
write_atomic(app_status_path(req), status + "\n")
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
def cmd_app_store(argv):
|
|
997
|
+
"""Called by the Herdr.app mod: app-store REQ HEX... (one padded value per field)."""
|
|
998
|
+
if not argv:
|
|
999
|
+
return 2
|
|
1000
|
+
req, hexes = argv[0], argv[1:]
|
|
1001
|
+
request = app_load(req)
|
|
1002
|
+
if request is None or not isinstance(request.get("deadline"), (int, float)) \
|
|
1003
|
+
or time.time() > request["deadline"] + 5:
|
|
1004
|
+
print("FAILED request expired")
|
|
1005
|
+
return 1
|
|
1006
|
+
|
|
1007
|
+
def fail(reason):
|
|
1008
|
+
app_finish(req, "FAILED " + reason)
|
|
1009
|
+
print("FAILED " + reason)
|
|
1010
|
+
return 1
|
|
1011
|
+
|
|
1012
|
+
try:
|
|
1013
|
+
name = request["name"]
|
|
1014
|
+
fields = [(f["name"], f["label"], f["hidden"]) for f in request["fields"]]
|
|
1015
|
+
pad = bytes.fromhex(request["pad"])
|
|
1016
|
+
except (KeyError, TypeError, ValueError):
|
|
1017
|
+
return fail("bad request")
|
|
1018
|
+
if not NAME_RE.fullmatch(name) or not fields or not all(FIELD_RE.fullmatch(f) for f, _l, _h in fields):
|
|
1019
|
+
return fail("bad request")
|
|
1020
|
+
if len(hexes) != len(fields):
|
|
1021
|
+
return fail("wrong number of values")
|
|
1022
|
+
values = []
|
|
1023
|
+
for i, h in enumerate(hexes):
|
|
1024
|
+
try:
|
|
1025
|
+
data = bytes.fromhex(h)
|
|
1026
|
+
except ValueError:
|
|
1027
|
+
return fail("bad value encoding")
|
|
1028
|
+
if len(data) > PAD_PER_FIELD:
|
|
1029
|
+
return fail("value too long")
|
|
1030
|
+
key = pad[i * PAD_PER_FIELD:i * PAD_PER_FIELD + len(data)]
|
|
1031
|
+
if len(key) != len(data):
|
|
1032
|
+
return fail("bad request")
|
|
1033
|
+
try:
|
|
1034
|
+
value = bytes(b ^ k for b, k in zip(data, key)).decode("utf-8")
|
|
1035
|
+
except UnicodeDecodeError:
|
|
1036
|
+
return fail("bad value encoding")
|
|
1037
|
+
if not value:
|
|
1038
|
+
return fail("empty value")
|
|
1039
|
+
if len(value) > MAX_VALUE:
|
|
1040
|
+
return fail("value too long")
|
|
1041
|
+
if CONTROL.search(value):
|
|
1042
|
+
return fail("control characters are not allowed")
|
|
1043
|
+
values.append(value)
|
|
1044
|
+
single = len(fields) == 1 and fields[0][0] == "value"
|
|
1045
|
+
ok, where = store_fields(name, single, fields, values)
|
|
1046
|
+
values[:] = []
|
|
1047
|
+
status = ("OK " + ", ".join(sorted(where))) if ok else "FAILED"
|
|
1048
|
+
app_finish(req, status)
|
|
1049
|
+
print(status)
|
|
1050
|
+
return 0 if ok else 1
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
def cmd_app_cancel(argv):
|
|
1054
|
+
"""Called by the Herdr.app mod: app-cancel REQ [TIMEOUT]."""
|
|
1055
|
+
req = argv[0] if argv else ""
|
|
1056
|
+
if app_load(req) is None:
|
|
1057
|
+
return 1
|
|
1058
|
+
app_finish(req, "TIMEOUT" if argv[1:2] == ["TIMEOUT"] else "CANCELLED")
|
|
1059
|
+
return 0
|
|
1060
|
+
|
|
1061
|
+
|
|
1062
|
+
# ---------------------------------------------------------------- setup wizard
|
|
1063
|
+
|
|
1064
|
+
ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
|
1065
|
+
BEGIN, END = "<!-- herdr-secret:begin -->", "<!-- herdr-secret:end -->"
|
|
1066
|
+
SH_BEGIN, SH_END = "# herdr-secret:begin", "# herdr-secret:end"
|
|
1067
|
+
MIN_HERDR = (0, 9, 5)
|
|
1068
|
+
TEST_NAME = "HERDR_SECRET_SETUP_TEST"
|
|
1069
|
+
AGENTS = [ # label, config dir, command, instruction file, skill dir
|
|
1070
|
+
("Claude Code", "~/.claude", "claude", "~/.claude/CLAUDE.md", "~/.claude/skills/herdr-secret"),
|
|
1071
|
+
("Codex", "~/.codex", "codex", "~/.codex/AGENTS.md", None),
|
|
1072
|
+
("OpenCode", "~/.config/opencode", "opencode", "~/.config/opencode/AGENTS.md", None),
|
|
1073
|
+
("Gemini CLI", "~/.gemini", "gemini", "~/.gemini/GEMINI.md", None),
|
|
1074
|
+
]
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def herdr_bin():
|
|
1078
|
+
return os.environ.get("HERDR_BIN_PATH") or shutil.which("herdr") or "herdr"
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
def herdr_json(*args):
|
|
1082
|
+
import json
|
|
1083
|
+
try:
|
|
1084
|
+
r = subprocess.run([herdr_bin(), *args], capture_output=True, text=True, timeout=30)
|
|
1085
|
+
return json.loads(r.stdout) if r.returncode == 0 and r.stdout.strip() else None
|
|
1086
|
+
except (OSError, ValueError, subprocess.TimeoutExpired):
|
|
1087
|
+
return None
|
|
1088
|
+
|
|
1089
|
+
|
|
1090
|
+
def herdr_version():
|
|
1091
|
+
try:
|
|
1092
|
+
out = subprocess.run([herdr_bin(), "--version"], capture_output=True, text=True, timeout=15).stdout
|
|
1093
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
1094
|
+
return None
|
|
1095
|
+
m = re.search(r"(\d+)\.(\d+)\.(\d+)", out)
|
|
1096
|
+
return tuple(int(x) for x in m.groups()) if m else None
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
def installed_plugin():
|
|
1100
|
+
d = herdr_json("plugin", "list", "--json") or {}
|
|
1101
|
+
for p in (d.get("result") or {}).get("plugins", []):
|
|
1102
|
+
if p.get("plugin_id") == PLUGIN_ID:
|
|
1103
|
+
return p
|
|
1104
|
+
return None
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
def plugin_version():
|
|
1108
|
+
try:
|
|
1109
|
+
with open(os.path.join(ROOT, "herdr-plugin.toml"), encoding="utf-8") as f:
|
|
1110
|
+
m = re.search(r'^version\s*=\s*"([^"]+)"', f.read(), re.M)
|
|
1111
|
+
return m.group(1) if m else "?"
|
|
1112
|
+
except OSError:
|
|
1113
|
+
return "?"
|
|
1114
|
+
|
|
1115
|
+
|
|
1116
|
+
def tilde(path):
|
|
1117
|
+
home = os.path.expanduser("~")
|
|
1118
|
+
return "~" + path[len(home):] if path.startswith(home) else path
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
def put_block(path, body, begin=BEGIN, end=END):
|
|
1122
|
+
"""Insert or replace our marked block, keeping the rest of the file and its permissions."""
|
|
1123
|
+
path = os.path.expanduser(path)
|
|
1124
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
1125
|
+
try:
|
|
1126
|
+
with open(path, encoding="utf-8") as f:
|
|
1127
|
+
old = f.read()
|
|
1128
|
+
mode = os.stat(path).st_mode & 0o777
|
|
1129
|
+
except FileNotFoundError:
|
|
1130
|
+
old, mode = "", 0o644
|
|
1131
|
+
block = f"{begin}\n{body.strip()}\n{end}\n"
|
|
1132
|
+
pat = re.compile(re.escape(begin) + r".*?" + re.escape(end) + r"\n?", re.S)
|
|
1133
|
+
if pat.search(old):
|
|
1134
|
+
new = pat.sub(lambda _m: block, old)
|
|
1135
|
+
else:
|
|
1136
|
+
new = old + ("\n" if old and not old.endswith("\n") else "") + ("\n" if old.strip() else "") + block
|
|
1137
|
+
if new != old:
|
|
1138
|
+
write_atomic(path, new)
|
|
1139
|
+
if not IS_WIN:
|
|
1140
|
+
os.chmod(path, mode)
|
|
1141
|
+
return path
|
|
1142
|
+
|
|
1143
|
+
|
|
1144
|
+
def drop_block(path, begin=BEGIN, end=END):
|
|
1145
|
+
path = os.path.expanduser(path)
|
|
1146
|
+
try:
|
|
1147
|
+
with open(path, encoding="utf-8") as f:
|
|
1148
|
+
old = f.read()
|
|
1149
|
+
mode = os.stat(path).st_mode & 0o777
|
|
1150
|
+
except FileNotFoundError:
|
|
1151
|
+
return False
|
|
1152
|
+
new = re.sub(r"\n?" + re.escape(begin) + r".*?" + re.escape(end) + r"\n?", "\n", old, flags=re.S)
|
|
1153
|
+
if new == old:
|
|
1154
|
+
return False
|
|
1155
|
+
new = new.strip("\n") + "\n" if new.strip() else ""
|
|
1156
|
+
write_atomic(path, new)
|
|
1157
|
+
if not IS_WIN:
|
|
1158
|
+
os.chmod(path, mode)
|
|
1159
|
+
return True
|
|
1160
|
+
|
|
1161
|
+
|
|
1162
|
+
def shell_profile():
|
|
1163
|
+
sh = os.path.basename(os.environ.get("SHELL", ""))
|
|
1164
|
+
if sh == "zsh":
|
|
1165
|
+
return os.path.expanduser("~/.zshrc"), 'export PATH="$HOME/.local/bin:$PATH"'
|
|
1166
|
+
if sh == "bash":
|
|
1167
|
+
prof = "~/.bash_profile" if IS_MAC and os.path.exists(os.path.expanduser("~/.bash_profile")) else "~/.bashrc"
|
|
1168
|
+
return os.path.expanduser(prof), 'export PATH="$HOME/.local/bin:$PATH"'
|
|
1169
|
+
if sh == "fish":
|
|
1170
|
+
return os.path.expanduser("~/.config/fish/conf.d/herdr-secret.fish"), "fish_add_path -g $HOME/.local/bin"
|
|
1171
|
+
return None, None
|
|
1172
|
+
|
|
1173
|
+
|
|
1174
|
+
def win_user_path(add=None, remove=None):
|
|
1175
|
+
import ctypes
|
|
1176
|
+
import winreg
|
|
1177
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_READ | winreg.KEY_WRITE) as k:
|
|
1178
|
+
try:
|
|
1179
|
+
cur, kind = winreg.QueryValueEx(k, "Path")
|
|
1180
|
+
except FileNotFoundError:
|
|
1181
|
+
cur, kind = "", winreg.REG_EXPAND_SZ
|
|
1182
|
+
parts = [p for p in cur.split(";") if p]
|
|
1183
|
+
same = lambda a, b: os.path.normcase(a.rstrip("\\")) == os.path.normcase(b.rstrip("\\")) # noqa: E731
|
|
1184
|
+
if add and not any(same(p, add) for p in parts):
|
|
1185
|
+
parts.append(add)
|
|
1186
|
+
if remove:
|
|
1187
|
+
parts = [p for p in parts if not same(p, remove)]
|
|
1188
|
+
new = ";".join(parts)
|
|
1189
|
+
if new == cur:
|
|
1190
|
+
return False
|
|
1191
|
+
winreg.SetValueEx(k, "Path", 0, kind, new)
|
|
1192
|
+
ctypes.windll.user32.SendMessageTimeoutW(0xFFFF, 0x1A, 0, "Environment", 0x2, 2000, None)
|
|
1193
|
+
return True
|
|
1194
|
+
|
|
1195
|
+
|
|
1196
|
+
def linux_keyring_install():
|
|
1197
|
+
for tool, cmd in (("apt-get", ["sudo", "apt-get", "install", "-y", "libsecret-tools"]),
|
|
1198
|
+
("dnf", ["sudo", "dnf", "install", "-y", "libsecret"]),
|
|
1199
|
+
("pacman", ["sudo", "pacman", "-S", "--needed", "--noconfirm", "libsecret"]),
|
|
1200
|
+
("zypper", ["sudo", "zypper", "install", "-y", "libsecret-tools"])):
|
|
1201
|
+
if shutil.which(tool):
|
|
1202
|
+
return cmd
|
|
1203
|
+
return None
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
class Wizard:
|
|
1207
|
+
def __init__(self, interactive):
|
|
1208
|
+
self.interactive = interactive
|
|
1209
|
+
|
|
1210
|
+
def step(self, i, total, title):
|
|
1211
|
+
print(f"\n{BOLD}{i}/{total} {title}{RESET}")
|
|
1212
|
+
|
|
1213
|
+
def ok(self, text):
|
|
1214
|
+
print(f" {GREEN}✓{RESET} {text}")
|
|
1215
|
+
|
|
1216
|
+
def warn(self, text):
|
|
1217
|
+
print(f" {YELLOW}!{RESET} {text}")
|
|
1218
|
+
|
|
1219
|
+
def bad(self, text):
|
|
1220
|
+
print(f" {RED}✗{RESET} {text}")
|
|
1221
|
+
|
|
1222
|
+
def note(self, text):
|
|
1223
|
+
print(f" {DIM}{text}{RESET}")
|
|
1224
|
+
|
|
1225
|
+
def yes(self, question, default=True):
|
|
1226
|
+
if not self.interactive:
|
|
1227
|
+
return default
|
|
1228
|
+
hint = "Y/n" if default else "y/N"
|
|
1229
|
+
while True:
|
|
1230
|
+
try:
|
|
1231
|
+
a = input(f" {question} [{hint}] ").strip().lower()
|
|
1232
|
+
except EOFError:
|
|
1233
|
+
return default
|
|
1234
|
+
if not a:
|
|
1235
|
+
return default
|
|
1236
|
+
if a in ("y", "yes"):
|
|
1237
|
+
return True
|
|
1238
|
+
if a in ("n", "no"):
|
|
1239
|
+
return False
|
|
1240
|
+
|
|
1241
|
+
|
|
1242
|
+
def setup_marker():
|
|
1243
|
+
return os.path.join(state_dir(), "setup.json")
|
|
1244
|
+
|
|
1245
|
+
|
|
1246
|
+
def write_marker(status, **extra):
|
|
1247
|
+
import json
|
|
1248
|
+
write_atomic(setup_marker(), json.dumps(dict(status=status, version=plugin_version(), **extra)) + "\n")
|
|
1249
|
+
|
|
1250
|
+
|
|
1251
|
+
def setup_store(w):
|
|
1252
|
+
v = secrets.token_hex(8)
|
|
1253
|
+
where = store_any(TEST_NAME, v)
|
|
1254
|
+
remove_any(TEST_NAME)
|
|
1255
|
+
if where is None:
|
|
1256
|
+
w.bad("Could not write to any credential store.")
|
|
1257
|
+
return False
|
|
1258
|
+
if where != FileStore.label:
|
|
1259
|
+
w.ok(f"{where} works")
|
|
1260
|
+
return True
|
|
1261
|
+
w.warn("No Secret Service (GNOME Keyring, KWallet) is reachable on this machine.")
|
|
1262
|
+
w.note("Without one, values are saved as unencrypted files that only your user can read (mode 0600).")
|
|
1263
|
+
cmd = None if shutil.which("secret-tool") else linux_keyring_install()
|
|
1264
|
+
if cmd and w.yes(f"Install secret-tool now ({' '.join(cmd)})?", default=False):
|
|
1265
|
+
subprocess.run(cmd)
|
|
1266
|
+
if shutil.which("secret-tool"):
|
|
1267
|
+
where = store_any(TEST_NAME, v)
|
|
1268
|
+
remove_any(TEST_NAME)
|
|
1269
|
+
if where == SecretService.label:
|
|
1270
|
+
w.ok("Secret Service works")
|
|
1271
|
+
return True
|
|
1272
|
+
w.warn("secret-tool is installed but no keyring is running (common on servers without a desktop).")
|
|
1273
|
+
if not w.yes("Use the 0600 file store on this machine?", default=True):
|
|
1274
|
+
w.bad("Setup stopped: no store you accepted.")
|
|
1275
|
+
return False
|
|
1276
|
+
w.ok("Using 0600 files in ~/.local/share/herdr-secret/store")
|
|
1277
|
+
return True
|
|
1278
|
+
|
|
1279
|
+
|
|
1280
|
+
def setup_command(w):
|
|
1281
|
+
"""Put herdr-secret on PATH. Returns what was changed, for uninstall."""
|
|
1282
|
+
changed = {}
|
|
1283
|
+
bindir_win = os.path.join(ROOT, "bin")
|
|
1284
|
+
if IS_WIN:
|
|
1285
|
+
if w.yes(f"Add {bindir_win} to your user PATH?"):
|
|
1286
|
+
if win_user_path(add=bindir_win):
|
|
1287
|
+
changed["winpath"] = bindir_win
|
|
1288
|
+
w.ok("Added to your user PATH. New terminals will find herdr-secret.")
|
|
1289
|
+
else:
|
|
1290
|
+
w.ok("Already on your user PATH.")
|
|
1291
|
+
else:
|
|
1292
|
+
w.warn(f"Skipped. Agents need {bindir_win} on PATH to run herdr-secret.")
|
|
1293
|
+
return changed
|
|
1294
|
+
target = os.path.join(ROOT, "bin", "herdr-secret")
|
|
1295
|
+
bindir = os.path.expanduser("~/.local/bin")
|
|
1296
|
+
link = os.path.join(bindir, "herdr-secret")
|
|
1297
|
+
os.makedirs(bindir, exist_ok=True)
|
|
1298
|
+
if os.path.lexists(link) and not (os.path.islink(link) and os.readlink(link).endswith(os.path.join("bin", "herdr-secret"))):
|
|
1299
|
+
w.bad(f"{tilde(link)} exists and is not ours; left it alone.")
|
|
1300
|
+
return changed
|
|
1301
|
+
if os.path.lexists(link):
|
|
1302
|
+
os.unlink(link)
|
|
1303
|
+
os.symlink(target, link)
|
|
1304
|
+
w.ok(f"Linked {tilde(link)}")
|
|
1305
|
+
if bindir in [os.path.expanduser(p) for p in os.environ.get("PATH", "").split(os.pathsep)]:
|
|
1306
|
+
w.ok("~/.local/bin is on PATH")
|
|
1307
|
+
return changed
|
|
1308
|
+
profile, line = shell_profile()
|
|
1309
|
+
if not profile:
|
|
1310
|
+
w.warn("~/.local/bin is not on PATH, and your shell's profile is unknown. Add it there.")
|
|
1311
|
+
elif w.yes(f"~/.local/bin is not on PATH. Add it in {tilde(profile)}?"):
|
|
1312
|
+
put_block(profile, line, SH_BEGIN, SH_END)
|
|
1313
|
+
changed["profile"] = profile
|
|
1314
|
+
w.ok(f"Added to {tilde(profile)}. New shells will find herdr-secret.")
|
|
1315
|
+
return changed
|
|
1316
|
+
|
|
1317
|
+
|
|
1318
|
+
def setup_agents(w):
|
|
1319
|
+
with open(os.path.join(ROOT, "agents", "instructions.md"), encoding="utf-8") as f:
|
|
1320
|
+
instructions = f.read()
|
|
1321
|
+
with open(os.path.join(ROOT, "agents", "SKILL.md"), encoding="utf-8") as f:
|
|
1322
|
+
skill = f.read()
|
|
1323
|
+
found = [a for a in AGENTS if os.path.isdir(os.path.expanduser(a[1])) or shutil.which(a[2])]
|
|
1324
|
+
if not found:
|
|
1325
|
+
w.note("No supported agent found (Claude Code, Codex, OpenCode, Gemini CLI).")
|
|
1326
|
+
w.note(f"For another agent, add {tilde(os.path.join(ROOT, 'agents', 'instructions.md'))} to its instructions.")
|
|
1327
|
+
return []
|
|
1328
|
+
for label, _d, _c, instr, skill_dir in found:
|
|
1329
|
+
files = [instr] + ([skill_dir + "/SKILL.md"] if skill_dir else [])
|
|
1330
|
+
w.note(f"{label}: {', '.join(files)}")
|
|
1331
|
+
if not w.yes(f"Teach {', '.join(a[0] for a in found)} to ask through herdr-secret?"):
|
|
1332
|
+
w.warn("Skipped. Run setup again to add them later.")
|
|
1333
|
+
return []
|
|
1334
|
+
done = []
|
|
1335
|
+
for label, _d, _c, instr, skill_dir in found:
|
|
1336
|
+
put_block(instr, instructions)
|
|
1337
|
+
if skill_dir:
|
|
1338
|
+
d = os.path.expanduser(skill_dir)
|
|
1339
|
+
os.makedirs(d, exist_ok=True)
|
|
1340
|
+
write_atomic(os.path.join(d, "SKILL.md"), skill)
|
|
1341
|
+
if not IS_WIN:
|
|
1342
|
+
os.chmod(os.path.join(d, "SKILL.md"), 0o644)
|
|
1343
|
+
done.append(label)
|
|
1344
|
+
w.ok(label)
|
|
1345
|
+
w.note("Agent sessions that are already running pick this up when they restart.")
|
|
1346
|
+
return done
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
# What a standalone install (Herdr.app without the herdr TUI plugin) copies to engine_home().
|
|
1350
|
+
# npm/stage.js packs the same files; npm/test checks that the two lists agree.
|
|
1351
|
+
ENGINE_FILES = ("herdr-plugin.toml", "bin/herdr_secret.py", "bin/herdr-secret", "bin/herdr-secret.cmd",
|
|
1352
|
+
"agents/instructions.md", "agents/SKILL.md",
|
|
1353
|
+
"mods/herdr-secret/main.js", "mods/herdr-secret/mod.json")
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
def engine_home():
|
|
1357
|
+
if IS_WIN:
|
|
1358
|
+
base = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~\\AppData\\Local")
|
|
1359
|
+
else:
|
|
1360
|
+
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
|
|
1361
|
+
return os.path.join(base, "herdr-secret", "engine")
|
|
1362
|
+
|
|
1363
|
+
|
|
1364
|
+
def same_path(a, b):
|
|
1365
|
+
return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b))
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
def same_file(a, b):
|
|
1369
|
+
try:
|
|
1370
|
+
with open(a, "rb") as f1, open(b, "rb") as f2:
|
|
1371
|
+
return f1.read() == f2.read()
|
|
1372
|
+
except OSError:
|
|
1373
|
+
return False
|
|
1374
|
+
|
|
1375
|
+
|
|
1376
|
+
def copy_file(src, dst, mode=0o644):
|
|
1377
|
+
"""A real file, replaced in one step: Herdr.app reloads a mod on every save."""
|
|
1378
|
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
|
1379
|
+
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(dst), prefix=".tmp-")
|
|
1380
|
+
os.close(fd)
|
|
1381
|
+
try:
|
|
1382
|
+
shutil.copyfile(src, tmp)
|
|
1383
|
+
if not IS_WIN:
|
|
1384
|
+
os.chmod(tmp, mode)
|
|
1385
|
+
os.replace(tmp, dst)
|
|
1386
|
+
except BaseException:
|
|
1387
|
+
try:
|
|
1388
|
+
os.unlink(tmp)
|
|
1389
|
+
except OSError:
|
|
1390
|
+
pass
|
|
1391
|
+
raise
|
|
1392
|
+
|
|
1393
|
+
|
|
1394
|
+
def install_engine(w):
|
|
1395
|
+
"""Without the herdr plugin there is no plugin folder to run from, and npx runs this copy
|
|
1396
|
+
from a cache that can be cleared. Copy it to engine_home() and carry on from there."""
|
|
1397
|
+
global ROOT
|
|
1398
|
+
dest = engine_home()
|
|
1399
|
+
if same_path(ROOT, dest):
|
|
1400
|
+
return True
|
|
1401
|
+
missing = [f for f in ENGINE_FILES if not os.path.isfile(os.path.join(ROOT, *f.split("/")))]
|
|
1402
|
+
if missing:
|
|
1403
|
+
w.bad(f"This copy of herdr-secret ({tilde(ROOT)}) is incomplete: {missing[0]} is missing.")
|
|
1404
|
+
return False
|
|
1405
|
+
pairs = [(os.path.join(ROOT, *f.split("/")), os.path.join(dest, *f.split("/"))) for f in ENGINE_FILES]
|
|
1406
|
+
fresh = not os.path.isdir(dest)
|
|
1407
|
+
if not all(same_file(s, d) for s, d in pairs):
|
|
1408
|
+
for (s, d), f in zip(pairs, ENGINE_FILES):
|
|
1409
|
+
copy_file(s, d, 0o755 if f.startswith("bin/herdr") and not f.endswith(".cmd") else 0o644)
|
|
1410
|
+
ROOT = dest
|
|
1411
|
+
w.ok(f"{'Installed' if fresh else 'Updated'} herdr-secret {plugin_version()} in {tilde(dest)}")
|
|
1412
|
+
return True
|
|
1413
|
+
|
|
1414
|
+
|
|
1415
|
+
def setup_app_mod(w):
|
|
1416
|
+
"""Copy the Herdr.app mod in as real files (Herdr.app does not follow symlinked mods) and
|
|
1417
|
+
have Herdr.app check it. Returns the mod folder, or None."""
|
|
1418
|
+
if not app_present():
|
|
1419
|
+
w.note("Herdr.app not found; skipped. Run setup again after installing it.")
|
|
1420
|
+
return None
|
|
1421
|
+
src, dest = os.path.join(ROOT, "mods", APP_MOD), app_mod_dir()
|
|
1422
|
+
if not all(os.path.isfile(os.path.join(src, f)) for f in APP_MOD_FILES):
|
|
1423
|
+
w.bad(f"This copy of herdr-secret has no Herdr.app mod ({tilde(src)}).")
|
|
1424
|
+
return None
|
|
1425
|
+
linked = os.path.islink(dest)
|
|
1426
|
+
exists = os.path.isdir(dest) and not linked
|
|
1427
|
+
if exists and not is_our_mod(dest):
|
|
1428
|
+
w.bad(f"{tilde(dest)} exists and is not herdr-secret's mod; left it alone.")
|
|
1429
|
+
return None
|
|
1430
|
+
if exists and all(same_file(os.path.join(src, f), os.path.join(dest, f)) for f in APP_MOD_FILES):
|
|
1431
|
+
w.ok(f"The mod in {tilde(dest)} is up to date")
|
|
1432
|
+
else:
|
|
1433
|
+
w.note("In Herdr.app terminals, herdr-secret ask shows its form as this mod's dialog.")
|
|
1434
|
+
verb = "Update" if exists or linked else "Install"
|
|
1435
|
+
if not w.yes(f"{verb} the Herdr.app mod in {tilde(dest)}?"):
|
|
1436
|
+
w.warn("Skipped. herdr-secret ask fails in Herdr.app terminals until the mod is installed.")
|
|
1437
|
+
return None
|
|
1438
|
+
if linked:
|
|
1439
|
+
os.unlink(dest) # the link only, never what it points to
|
|
1440
|
+
for f in APP_MOD_FILES:
|
|
1441
|
+
copy_file(os.path.join(src, f), os.path.join(dest, f))
|
|
1442
|
+
w.ok(f"{'Updated' if exists or linked else 'Installed'} {tilde(dest)}")
|
|
1443
|
+
app = herdr_app_bin()
|
|
1444
|
+
if not app:
|
|
1445
|
+
w.warn("herdr-app is not on PATH, so the mod was not checked. Herdr.app loads it when it starts.")
|
|
1446
|
+
return dest
|
|
1447
|
+
try:
|
|
1448
|
+
r = subprocess.run([app, "check", dest], capture_output=True, text=True, timeout=120)
|
|
1449
|
+
code, out = r.returncode, (r.stdout + r.stderr).strip()
|
|
1450
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
1451
|
+
code, out = 1, str(e)
|
|
1452
|
+
if code == 0:
|
|
1453
|
+
w.ok("herdr-app check passed")
|
|
1454
|
+
else:
|
|
1455
|
+
w.bad("herdr-app check failed:")
|
|
1456
|
+
for line in out.splitlines()[-6:]:
|
|
1457
|
+
w.note(line)
|
|
1458
|
+
return dest
|
|
1459
|
+
|
|
1460
|
+
|
|
1461
|
+
def setup_try(w):
|
|
1462
|
+
if not (w.interactive and sys.stdin.isatty()):
|
|
1463
|
+
w.note("Skipped (not interactive).")
|
|
1464
|
+
return
|
|
1465
|
+
if not w.yes("Try the form now? It saves a test value and deletes it right after."):
|
|
1466
|
+
return
|
|
1467
|
+
fields, _ = parse_fields("username,password")
|
|
1468
|
+
form = Form(fields, TEST_NAME, "herdr-secret setup", "Type anything. It is deleted right after.", "")
|
|
1469
|
+
try:
|
|
1470
|
+
with Term() as t:
|
|
1471
|
+
res = run_form(t, form, time.time() + 180)
|
|
1472
|
+
except KeyboardInterrupt:
|
|
1473
|
+
res = None
|
|
1474
|
+
if not isinstance(res, list):
|
|
1475
|
+
w.warn("Form closed without saving.")
|
|
1476
|
+
return
|
|
1477
|
+
where = {store_any(f"{TEST_NAME}.{f}", v) for (f, _l, _h), v in zip(fields, res)}
|
|
1478
|
+
res[:] = []
|
|
1479
|
+
for f, _l, _h in fields:
|
|
1480
|
+
remove_any(f"{TEST_NAME}.{f}")
|
|
1481
|
+
if None in where:
|
|
1482
|
+
w.bad("Saving failed.")
|
|
1483
|
+
else:
|
|
1484
|
+
w.ok(f"Saved to {', '.join(sorted(where))} and deleted again")
|
|
1485
|
+
|
|
1486
|
+
|
|
1487
|
+
def needs_terminal(argv, what):
|
|
1488
|
+
"""Without a terminal there is nobody to answer, so changes need an explicit --yes."""
|
|
1489
|
+
if sys.stdin.isatty() or "--yes" in argv or "-y" in argv:
|
|
1490
|
+
return False
|
|
1491
|
+
print(f"herdr-secret {what} asks before changing anything and needs a terminal. "
|
|
1492
|
+
f"Run it in one, or pass --yes to accept every default.", file=sys.stderr)
|
|
1493
|
+
return True
|
|
1494
|
+
|
|
1495
|
+
|
|
1496
|
+
def cmd_setup(argv):
|
|
1497
|
+
if needs_terminal(argv, "setup"):
|
|
1498
|
+
return 2
|
|
1499
|
+
interactive = sys.stdin.isatty() and "--yes" not in argv and "-y" not in argv
|
|
1500
|
+
if IS_WIN:
|
|
1501
|
+
os.system("")
|
|
1502
|
+
w = Wizard(interactive)
|
|
1503
|
+
in_popup = bool(os.environ.get("HERDR_PLUGIN_ENTRYPOINT_ID"))
|
|
1504
|
+
again = "herdr-secret setup"
|
|
1505
|
+
print(f"\n{BOLD}herdr-secret {plugin_version()} setup{RESET}")
|
|
1506
|
+
print(f"{DIM}Lets your coding agents ask you for credentials in a herdr popup or a Herdr.app dialog.{RESET}")
|
|
1507
|
+
try:
|
|
1508
|
+
w.step(1, 6, "Requirements")
|
|
1509
|
+
w.ok(f"Python {sys.version.split()[0]}")
|
|
1510
|
+
hv, app = herdr_version(), app_present()
|
|
1511
|
+
tui = hv is not None and hv >= MIN_HERDR
|
|
1512
|
+
if hv is None and not app:
|
|
1513
|
+
w.bad("Neither herdr (the TUI) nor Herdr.app was found. Install one from herdr.dev, then run this again.")
|
|
1514
|
+
return 1
|
|
1515
|
+
if hv is None:
|
|
1516
|
+
w.note("herdr (the TUI) not found; herdr-secret will work through Herdr.app.")
|
|
1517
|
+
elif not tui:
|
|
1518
|
+
old = (f"herdr {'.'.join(map(str, hv))} is too old; {'.'.join(map(str, MIN_HERDR))} or newer "
|
|
1519
|
+
f"is needed. Run: herdr update")
|
|
1520
|
+
if not app:
|
|
1521
|
+
w.bad(old)
|
|
1522
|
+
return 1
|
|
1523
|
+
w.warn(old + ". Until then, only Herdr.app is set up.")
|
|
1524
|
+
else:
|
|
1525
|
+
w.ok(f"herdr {'.'.join(map(str, hv))}")
|
|
1526
|
+
if app:
|
|
1527
|
+
w.ok(f"Herdr.app ({tilde(app_home())})")
|
|
1528
|
+
plugin = installed_plugin() if tui else None
|
|
1529
|
+
if plugin:
|
|
1530
|
+
w.ok("Plugin is registered with herdr")
|
|
1531
|
+
elif tui and w.yes(f"The plugin is not registered with herdr. Link this copy ({tilde(ROOT)})?"):
|
|
1532
|
+
subprocess.run([herdr_bin(), "plugin", "link", ROOT], stdout=DEVNULL)
|
|
1533
|
+
plugin = installed_plugin()
|
|
1534
|
+
(w.ok if plugin else w.bad)("Plugin linked" if plugin else "Linking failed")
|
|
1535
|
+
# Run as the herdr plugin, the command links into the plugin folder. Otherwise (Herdr.app
|
|
1536
|
+
# only, or a copy herdr does not know) it runs from an installed copy of this one.
|
|
1537
|
+
plugin_mode = bool(plugin and plugin.get("plugin_root") and same_path(plugin["plugin_root"], ROOT))
|
|
1538
|
+
if plugin_mode:
|
|
1539
|
+
again = f"herdr plugin action invoke {PLUGIN_ID}.setup"
|
|
1540
|
+
|
|
1541
|
+
w.step(2, 6, "Credential store")
|
|
1542
|
+
if not setup_store(w):
|
|
1543
|
+
write_marker("incomplete")
|
|
1544
|
+
return 1
|
|
1545
|
+
|
|
1546
|
+
w.step(3, 6, "The herdr-secret command")
|
|
1547
|
+
if not plugin_mode and not install_engine(w):
|
|
1548
|
+
write_marker("incomplete")
|
|
1549
|
+
return 1
|
|
1550
|
+
changed = setup_command(w)
|
|
1551
|
+
|
|
1552
|
+
w.step(4, 6, "Herdr.app mod")
|
|
1553
|
+
mod = setup_app_mod(w)
|
|
1554
|
+
|
|
1555
|
+
w.step(5, 6, "Your agents")
|
|
1556
|
+
agents = setup_agents(w)
|
|
1557
|
+
|
|
1558
|
+
w.step(6, 6, "Try it")
|
|
1559
|
+
setup_try(w)
|
|
1560
|
+
|
|
1561
|
+
write_marker("done", agents=agents, mod=mod, engine=None if plugin_mode else ROOT, **changed)
|
|
1562
|
+
print(f"\n{GREEN}{BOLD}Done.{RESET} Agents can now run: herdr-secret ask NAME \"what it is for\"")
|
|
1563
|
+
print(f"{DIM}Run setup again any time: {again}{RESET}")
|
|
1564
|
+
print(f"{DIM}Remove everything it added: herdr-secret uninstall{RESET}")
|
|
1565
|
+
return 0
|
|
1566
|
+
except KeyboardInterrupt:
|
|
1567
|
+
print(f"\n\nSetup cancelled. Run it again any time: {again}")
|
|
1568
|
+
if not os.path.exists(setup_marker()):
|
|
1569
|
+
write_marker("skipped")
|
|
1570
|
+
return 1
|
|
1571
|
+
finally:
|
|
1572
|
+
if in_popup and sys.stdin.isatty():
|
|
1573
|
+
try:
|
|
1574
|
+
input("\nPress Enter to close.")
|
|
1575
|
+
except (EOFError, KeyboardInterrupt):
|
|
1576
|
+
pass
|
|
1577
|
+
|
|
1578
|
+
|
|
1579
|
+
def cmd_uninstall(argv):
|
|
1580
|
+
if needs_terminal(argv, "uninstall"):
|
|
1581
|
+
return 2
|
|
1582
|
+
interactive = sys.stdin.isatty() and "--yes" not in argv and "-y" not in argv
|
|
1583
|
+
if IS_WIN:
|
|
1584
|
+
os.system("")
|
|
1585
|
+
w = Wizard(interactive)
|
|
1586
|
+
print(f"\n{BOLD}herdr-secret uninstall{RESET}")
|
|
1587
|
+
for label, _d, _c, instr, skill_dir in AGENTS:
|
|
1588
|
+
hit = drop_block(instr)
|
|
1589
|
+
if skill_dir:
|
|
1590
|
+
f = os.path.join(os.path.expanduser(skill_dir), "SKILL.md")
|
|
1591
|
+
if os.path.exists(f):
|
|
1592
|
+
os.unlink(f)
|
|
1593
|
+
try:
|
|
1594
|
+
os.rmdir(os.path.dirname(f))
|
|
1595
|
+
except OSError:
|
|
1596
|
+
pass
|
|
1597
|
+
hit = True
|
|
1598
|
+
if hit:
|
|
1599
|
+
w.ok(f"Removed instructions for {label}")
|
|
1600
|
+
for prof in ("~/.zshrc", "~/.bashrc", "~/.bash_profile"):
|
|
1601
|
+
if drop_block(prof, SH_BEGIN, SH_END):
|
|
1602
|
+
w.ok(f"Removed the PATH line from {prof}")
|
|
1603
|
+
fish = os.path.expanduser("~/.config/fish/conf.d/herdr-secret.fish")
|
|
1604
|
+
if os.path.exists(fish):
|
|
1605
|
+
os.unlink(fish)
|
|
1606
|
+
w.ok("Removed the fish PATH file")
|
|
1607
|
+
if IS_WIN:
|
|
1608
|
+
for b in dict.fromkeys([os.path.join(ROOT, "bin"), os.path.join(engine_home(), "bin")]):
|
|
1609
|
+
if win_user_path(remove=b):
|
|
1610
|
+
w.ok(f"Removed {b} from your user PATH")
|
|
1611
|
+
else:
|
|
1612
|
+
link = os.path.expanduser("~/.local/bin/herdr-secret")
|
|
1613
|
+
if os.path.islink(link) and os.readlink(link).endswith(os.path.join("bin", "herdr-secret")):
|
|
1614
|
+
os.unlink(link)
|
|
1615
|
+
w.ok("Removed ~/.local/bin/herdr-secret")
|
|
1616
|
+
mod = app_mod_dir()
|
|
1617
|
+
if os.path.isdir(mod) and not os.path.islink(mod):
|
|
1618
|
+
if is_our_mod(mod):
|
|
1619
|
+
shutil.rmtree(mod, ignore_errors=True)
|
|
1620
|
+
w.ok(f"Removed the Herdr.app mod ({tilde(mod)})")
|
|
1621
|
+
else:
|
|
1622
|
+
w.warn(f"{tilde(mod)} is not herdr-secret's mod; left it alone.")
|
|
1623
|
+
names = names_any()
|
|
1624
|
+
if names:
|
|
1625
|
+
w.note(f"Stored: {', '.join(names)}")
|
|
1626
|
+
if w.yes(f"Delete these {len(names)} stored credential(s) too?", default=False):
|
|
1627
|
+
for n in names:
|
|
1628
|
+
remove_any(n)
|
|
1629
|
+
w.ok("Deleted stored credentials")
|
|
1630
|
+
else:
|
|
1631
|
+
w.note("Kept. They stay in your credential store.")
|
|
1632
|
+
for f in (setup_marker(), os.path.join(app_state_dir(), "app-done")):
|
|
1633
|
+
try:
|
|
1634
|
+
os.unlink(f)
|
|
1635
|
+
except OSError:
|
|
1636
|
+
pass
|
|
1637
|
+
p = installed_plugin()
|
|
1638
|
+
if p and w.yes("Remove the plugin from herdr as well?"):
|
|
1639
|
+
local = (p.get("source") or {}).get("kind") == "local"
|
|
1640
|
+
subprocess.run([herdr_bin(), "plugin", "unlink" if local else "uninstall", PLUGIN_ID], stdout=DEVNULL)
|
|
1641
|
+
w.ok("Plugin removed from herdr")
|
|
1642
|
+
eng = engine_home()
|
|
1643
|
+
if os.path.isfile(os.path.join(eng, "bin", "herdr_secret.py")):
|
|
1644
|
+
shutil.rmtree(eng, ignore_errors=True)
|
|
1645
|
+
try:
|
|
1646
|
+
os.rmdir(os.path.dirname(eng)) # only when empty: the Linux file store lives beside it
|
|
1647
|
+
except OSError:
|
|
1648
|
+
pass
|
|
1649
|
+
w.ok(f"Removed {tilde(eng)}")
|
|
1650
|
+
print(f"\n{BOLD}Done.{RESET}")
|
|
1651
|
+
return 0
|
|
1652
|
+
|
|
1653
|
+
|
|
1654
|
+
def cmd_open_setup():
|
|
1655
|
+
entry = "setup-windows" if IS_WIN else "setup"
|
|
1656
|
+
return subprocess.run([herdr_bin(), "plugin", "pane", "open", "--plugin", PLUGIN_ID,
|
|
1657
|
+
"--entrypoint", entry, "--focus"], stdout=DEVNULL).returncode
|
|
1658
|
+
|
|
1659
|
+
|
|
1660
|
+
def cmd_startup():
|
|
1661
|
+
"""Runs when herdr starts: open the setup popup once if setup has never run."""
|
|
1662
|
+
if os.path.exists(setup_marker()):
|
|
1663
|
+
return 0
|
|
1664
|
+
return cmd_open_setup()
|
|
1665
|
+
|
|
1666
|
+
|
|
1667
|
+
def main(argv):
|
|
1668
|
+
cmd, args = (argv[0], argv[1:]) if argv else ("", [])
|
|
1669
|
+
if cmd == "form":
|
|
1670
|
+
return cmd_form()
|
|
1671
|
+
if cmd == "ask":
|
|
1672
|
+
return cmd_ask(args)
|
|
1673
|
+
if cmd == "setup":
|
|
1674
|
+
return cmd_setup(args)
|
|
1675
|
+
if cmd == "uninstall":
|
|
1676
|
+
return cmd_uninstall(args)
|
|
1677
|
+
if cmd == "open-setup":
|
|
1678
|
+
return cmd_open_setup()
|
|
1679
|
+
if cmd == "startup":
|
|
1680
|
+
return cmd_startup()
|
|
1681
|
+
if cmd == "app-store":
|
|
1682
|
+
return cmd_app_store(args)
|
|
1683
|
+
if cmd == "app-cancel":
|
|
1684
|
+
return cmd_app_cancel(args)
|
|
1685
|
+
if cmd == "list":
|
|
1686
|
+
for n in names_any():
|
|
1687
|
+
print(n)
|
|
1688
|
+
return 0
|
|
1689
|
+
if cmd in ("get", "rm") and args:
|
|
1690
|
+
if not NAME_RE.fullmatch(args[0]):
|
|
1691
|
+
print(f"herdr-secret {cmd}: invalid NAME", file=sys.stderr)
|
|
1692
|
+
return 2
|
|
1693
|
+
if cmd == "rm":
|
|
1694
|
+
targets = [args[0]] + [n for n in names_any() if n.startswith(args[0] + ".")]
|
|
1695
|
+
gone = [t for t in dict.fromkeys(targets) if remove_any(t)]
|
|
1696
|
+
print(f"removed {', '.join(gone)}" if gone else f"not found {args[0]}")
|
|
1697
|
+
return 0 if gone else 1
|
|
1698
|
+
if sys.stdout.isatty():
|
|
1699
|
+
print("herdr-secret get: stdout is a terminal; pipe it into the target", file=sys.stderr)
|
|
1700
|
+
return 2
|
|
1701
|
+
v = fetch_any(args[0])
|
|
1702
|
+
if v is None:
|
|
1703
|
+
print(f"herdr-secret get: {args[0]} not found", file=sys.stderr)
|
|
1704
|
+
return 1
|
|
1705
|
+
sys.stdout.buffer.write(v.encode("utf-8"))
|
|
1706
|
+
sys.stdout.flush()
|
|
1707
|
+
return 0
|
|
1708
|
+
print(__doc__.strip(), file=sys.stderr)
|
|
1709
|
+
return 2
|
|
1710
|
+
|
|
1711
|
+
|
|
1712
|
+
if __name__ == "__main__":
|
|
1713
|
+
sys.exit(main(sys.argv[1:]))
|