passkey-vault-client 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ .DS_Store
3
+ .pytest_cache/
4
+ .venv/
5
+ *.pyc
6
+ /data/
7
+ /tmp/
8
+ dist/
9
+ node_modules/
10
+ test-results/
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.5
2
+ Name: passkey-vault-client
3
+ Version: 0.1.0
4
+ Summary: Requester SDK and the `pkv` CLI for passkey-vault: get one secret for one command after a passkey approval.
5
+ Project-URL: Homepage, https://github.com/pparkddo/passkey-vault
6
+ License-Expression: MIT
7
+ Keywords: ai-agents,cli,passkey,secrets,webauthn
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: cryptography>=42
10
+ Description-Content-Type: text/markdown
11
+
12
+ # passkey-vault-client
13
+
14
+ The requester side of [passkey-vault](https://github.com/pparkddo/passkey-vault): a small Python SDK
15
+ and the `pkv` command. It asks a passkey-vault server for one secret for one command, waits while you
16
+ approve the request with a passkey, then runs the command once with the secret.
17
+
18
+ ```sh
19
+ uv tool install "git+https://github.com/pparkddo/passkey-vault#subdirectory=packages/client"
20
+
21
+ pkv run github --stdin -- gh auth login --with-token # secret on stdin
22
+ pkv run api-token -c 'curl -H "Authorization: Bearer $PKV_SECRET" https://api.example.com'
23
+ ```
24
+
25
+ ```python
26
+ from passkey_vault_client import Client
27
+
28
+ request = Client("http://127.0.0.1:8741").request("github", "gh auth login --with-token")
29
+ print("Approve at", request.approve_url)
30
+ secret = request.wait() # bytes
31
+ ```
32
+
33
+ Only depends on `cryptography`. Reference: [docs/cli.md](https://github.com/pparkddo/passkey-vault/blob/main/docs/cli.md).
@@ -0,0 +1,22 @@
1
+ # passkey-vault-client
2
+
3
+ The requester side of [passkey-vault](https://github.com/pparkddo/passkey-vault): a small Python SDK
4
+ and the `pkv` command. It asks a passkey-vault server for one secret for one command, waits while you
5
+ approve the request with a passkey, then runs the command once with the secret.
6
+
7
+ ```sh
8
+ uv tool install "git+https://github.com/pparkddo/passkey-vault#subdirectory=packages/client"
9
+
10
+ pkv run github --stdin -- gh auth login --with-token # secret on stdin
11
+ pkv run api-token -c 'curl -H "Authorization: Bearer $PKV_SECRET" https://api.example.com'
12
+ ```
13
+
14
+ ```python
15
+ from passkey_vault_client import Client
16
+
17
+ request = Client("http://127.0.0.1:8741").request("github", "gh auth login --with-token")
18
+ print("Approve at", request.approve_url)
19
+ secret = request.wait() # bytes
20
+ ```
21
+
22
+ Only depends on `cryptography`. Reference: [docs/cli.md](https://github.com/pparkddo/passkey-vault/blob/main/docs/cli.md).
@@ -0,0 +1,22 @@
1
+ [project]
2
+ name = "passkey-vault-client"
3
+ version = "0.1.0"
4
+ description = "Requester SDK and the `pkv` CLI for passkey-vault: get one secret for one command after a passkey approval."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.10"
8
+ keywords = ["passkey", "webauthn", "secrets", "ai-agents", "cli"]
9
+ dependencies = ["cryptography>=42"]
10
+
11
+ [project.scripts]
12
+ pkv = "passkey_vault_client.cli:main"
13
+
14
+ [project.urls]
15
+ Homepage = "https://github.com/pparkddo/passkey-vault"
16
+
17
+ [build-system]
18
+ requires = ["hatchling"]
19
+ build-backend = "hatchling.build"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/passkey_vault_client"]
@@ -0,0 +1,35 @@
1
+ """Requester SDK and `pkv` CLI for passkey-vault."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from .client import (
6
+ DEFAULT_URL,
7
+ ApprovalRequest,
8
+ Client,
9
+ PkvError,
10
+ PollResult,
11
+ RequestDenied,
12
+ RequestExpired,
13
+ RequestTimeout,
14
+ SecretInfo,
15
+ ServerError,
16
+ )
17
+
18
+ try:
19
+ __version__ = version("passkey-vault-client")
20
+ except PackageNotFoundError: # running from a source tree without installing
21
+ __version__ = "0+unknown"
22
+
23
+ __all__ = [
24
+ "DEFAULT_URL",
25
+ "ApprovalRequest",
26
+ "Client",
27
+ "PkvError",
28
+ "PollResult",
29
+ "RequestDenied",
30
+ "RequestExpired",
31
+ "RequestTimeout",
32
+ "SecretInfo",
33
+ "ServerError",
34
+ "__version__",
35
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,242 @@
1
+ """pkv: run one command with one secret, after a passkey approval.
2
+
3
+ pkv setup # once: server URL and requester token
4
+ pkv list # what the vault holds (names, no secrets)
5
+ pkv run github -- gh auth login --with-token # argv, no shell
6
+ pkv run github -c 'curl -u "me:$PKV_SECRET" https://example.com' # through the shell
7
+ pkv run github --stdin -- gh auth login --with-token # secret on stdin instead of an env var
8
+
9
+ The approver sees the command exactly as it will run. The secret is put in the environment of that
10
+ one process (default variable PKV_SECRET) or written to its stdin, and nowhere else.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import dataclasses
17
+ import getpass
18
+ import json
19
+ import os
20
+ import re
21
+ import shlex
22
+ import signal
23
+ import subprocess
24
+ import sys
25
+ from typing import NoReturn
26
+
27
+ from . import __version__, config
28
+ from .client import DEFAULT_URL, Client, PkvError, RequestDenied, RequestExpired, RequestTimeout, ServerError
29
+
30
+ EXIT_DENIED = 3
31
+ EXIT_EXPIRED = 4 # expired or timed out
32
+ EXIT_ERROR = 5 # server, network or protocol error
33
+ EXIT_NOT_FOUND = 127
34
+ EXIT_INTERRUPTED = 130
35
+
36
+ ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
37
+ WINDOWS = os.name == "nt"
38
+
39
+
40
+ def _say(message: str) -> None:
41
+ print(f"pkv: {message}", file=sys.stderr, flush=True)
42
+
43
+
44
+ def _env_name(value: str) -> str:
45
+ if not ENV_NAME_RE.fullmatch(value):
46
+ raise argparse.ArgumentTypeError(f"not a valid environment variable name: {value!r}")
47
+ return value
48
+
49
+
50
+ def _parser() -> argparse.ArgumentParser:
51
+ p = argparse.ArgumentParser(prog="pkv", description="Use one passkey-vault secret for one command, after approval.")
52
+ p.add_argument("--version", action="version", version=f"pkv {__version__}")
53
+ sub = p.add_subparsers(dest="action", required=True)
54
+
55
+ server = argparse.ArgumentParser(add_help=False)
56
+ server.add_argument(
57
+ "--server",
58
+ default=None,
59
+ help=f"requester endpoint (env PKV_SERVER, then the config file, default {DEFAULT_URL}); "
60
+ "the requester token comes from PKV_TOKEN or the config file",
61
+ )
62
+
63
+ setup = sub.add_parser(
64
+ "setup",
65
+ parents=[server],
66
+ help="save the server URL and requester token, after checking them",
67
+ description="Check the server URL and requester token, then save them to the config file.",
68
+ )
69
+ setup.add_argument("--token-stdin", action="store_true", help="read the requester token from stdin")
70
+
71
+ listing = sub.add_parser("list", parents=[server], help="list the vault's secrets (names only, no values)")
72
+ listing.add_argument("--json", action="store_true", help="print JSON")
73
+
74
+ shell = "cmd /c" if WINDOWS else "/bin/sh -c"
75
+ run = sub.add_parser(
76
+ "run",
77
+ parents=[server],
78
+ help="request a secret and run one command with it",
79
+ description="Request SECRET for one command, wait for approval, then run the command once.",
80
+ epilog="Give the command after --, e.g. pkv run github -- gh auth login --with-token",
81
+ )
82
+ run.add_argument("secret", help="name of the vault item")
83
+ run.add_argument("-c", dest="shell_command", metavar="COMMAND", help=f"run COMMAND with {shell}")
84
+ run.add_argument(
85
+ "--env",
86
+ type=_env_name,
87
+ default="PKV_SECRET",
88
+ metavar="NAME",
89
+ help="environment variable that receives the secret (default PKV_SECRET)",
90
+ )
91
+ run.add_argument("--stdin", action="store_true", help="write the secret to the command's stdin instead")
92
+ run.add_argument(
93
+ "--timeout",
94
+ type=float,
95
+ default=330,
96
+ metavar="SECONDS",
97
+ help="give up waiting for a decision after this long (default 330)",
98
+ )
99
+ run.add_argument(
100
+ "--key-bits",
101
+ type=int,
102
+ default=3072,
103
+ choices=(2048, 3072, 4096),
104
+ help="size of the one-time RSA key (default 3072)",
105
+ )
106
+ return p
107
+
108
+
109
+ def _command(args: argparse.Namespace, argv: list[str], parser: argparse.ArgumentParser) -> tuple[str, list[str]]:
110
+ """Return (the command as shown to the approver, the argv to execute)."""
111
+ if bool(argv) == bool(args.shell_command):
112
+ parser.error("give the command either after -- or with -c, not both")
113
+ if args.shell_command:
114
+ shell = [os.environ.get("COMSPEC", "cmd.exe"), "/c"] if WINDOWS else ["/bin/sh", "-c"]
115
+ return args.shell_command, [*shell, args.shell_command]
116
+ return shlex.join(argv), argv
117
+
118
+
119
+ def _exec_with_env(argv: list[str], env: dict[str, str]) -> NoReturn:
120
+ """Replace this process with the command: signals and the exit status are the command's own,
121
+ and nothing of pkv (including its copy of the secret) outlives the exec."""
122
+ try:
123
+ os.execvpe(argv[0], argv, env)
124
+ except FileNotFoundError:
125
+ _say(f"command not found: {argv[0]}")
126
+ raise SystemExit(EXIT_NOT_FOUND) from None
127
+
128
+
129
+ def _run_child(argv: list[str], env: dict[str, str] | None, stdin_data: bytes | None) -> int:
130
+ """Run the command as a child, forwarding termination signals to it."""
131
+ try:
132
+ child = subprocess.Popen(argv, env=env, stdin=subprocess.PIPE if stdin_data is not None else None)
133
+ except FileNotFoundError:
134
+ _say(f"command not found: {argv[0]}")
135
+ return EXIT_NOT_FOUND
136
+ forwarded = [signal.SIGTERM, *([signal.SIGHUP] if hasattr(signal, "SIGHUP") else [])]
137
+ previous = {s: signal.signal(s, lambda signum, _frame: child.send_signal(signum)) for s in forwarded}
138
+ try:
139
+ if stdin_data is not None:
140
+ child.communicate(stdin_data)
141
+ while True:
142
+ try:
143
+ return child.wait()
144
+ except KeyboardInterrupt: # Ctrl-C reaches the child through the terminal; keep waiting
145
+ continue
146
+ finally:
147
+ for s, handler in previous.items():
148
+ signal.signal(s, handler)
149
+
150
+
151
+ def _setup(args: argparse.Namespace) -> int:
152
+ saved = config.load_file() or config.Settings()
153
+ interactive = sys.stdin.isatty()
154
+ server = args.server or os.environ.get("PKV_SERVER")
155
+ if not server and interactive:
156
+ server = input(f"Server URL [{saved.server}]: ").strip()
157
+ server = server or saved.server
158
+ if os.environ.get("PKV_TOKEN"):
159
+ token: str | None = os.environ["PKV_TOKEN"]
160
+ elif args.token_stdin:
161
+ token = sys.stdin.readline().strip()
162
+ elif interactive:
163
+ token = getpass.getpass("Requester token (from the server's data directory; empty if it has none): ").strip()
164
+ else:
165
+ token = saved.token
166
+ token = token or None
167
+
168
+ try:
169
+ secrets = Client(server, token).list_secrets()
170
+ names = ", ".join(s.name for s in secrets) or "none yet"
171
+ _say(f"connected to {server}: {len(secrets)} secret(s): {names}")
172
+ except ServerError as e:
173
+ if e.code != "vault_not_initialized":
174
+ _say(f"not saved: {e}")
175
+ return EXIT_ERROR
176
+ _say(f"connected to {server}; the vault is not set up yet (open the approval page to set it up)")
177
+ except PkvError as e:
178
+ _say(f"not saved: {e}")
179
+ return EXIT_ERROR
180
+ path = config.save(config.Settings(server=server, token=token))
181
+ _say(f"saved to {path}")
182
+ return 0
183
+
184
+
185
+ def _list(args: argparse.Namespace) -> int:
186
+ settings = config.resolve(args.server)
187
+ try:
188
+ secrets = Client(settings.server, settings.token).list_secrets()
189
+ except PkvError as e:
190
+ _say(str(e))
191
+ return EXIT_ERROR
192
+ if args.json:
193
+ print(json.dumps([dataclasses.asdict(s) for s in secrets], indent=2))
194
+ return 0
195
+ rows = [("NAME", "SITE", "ACCOUNT"), *((s.name, s.site, s.account) for s in secrets)]
196
+ widths = [max(len(r[i]) for r in rows) for i in range(2)]
197
+ for name, site, account in rows:
198
+ print(f"{name:<{widths[0]}} {site:<{widths[1]}} {account}".rstrip())
199
+ return 0
200
+
201
+
202
+ def main(argv: list[str] | None = None) -> int:
203
+ argv = sys.argv[1:] if argv is None else argv
204
+ # Everything after the first "--" is the command, verbatim; only what comes before is pkv's own.
205
+ own, command = (argv[: argv.index("--")], argv[argv.index("--") + 1 :]) if "--" in argv else (argv, [])
206
+ parser = _parser()
207
+ args = parser.parse_args(own)
208
+ if args.action == "setup":
209
+ return _setup(args)
210
+ if args.action == "list":
211
+ return _list(args)
212
+ shown, exec_argv = _command(args, command, parser)
213
+ settings = config.resolve(args.server)
214
+
215
+ try:
216
+ request = Client(settings.server, settings.token).request(args.secret, shown, key_bits=args.key_bits)
217
+ _say(f"approve using {args.secret} for this command: {request.approve_url}")
218
+ _say(f"waiting (the link expires at {request.expires_at})")
219
+ secret = request.wait(timeout=args.timeout)
220
+ except RequestDenied as e:
221
+ _say(str(e))
222
+ return EXIT_DENIED
223
+ except (RequestExpired, RequestTimeout) as e:
224
+ _say(str(e))
225
+ return EXIT_EXPIRED
226
+ except PkvError as e:
227
+ _say(str(e))
228
+ return EXIT_ERROR
229
+ except KeyboardInterrupt:
230
+ return EXIT_INTERRUPTED
231
+
232
+ _say("approved; running the command once")
233
+ if args.stdin:
234
+ return _run_child(exec_argv, None, secret)
235
+ env = {**os.environ, args.env: secret.decode("utf-8")}
236
+ if WINDOWS: # exec on Windows starts a new process and exits; a child behaves better there
237
+ return _run_child(exec_argv, env, None)
238
+ _exec_with_env(exec_argv, env)
239
+
240
+
241
+ if __name__ == "__main__":
242
+ raise SystemExit(main())
@@ -0,0 +1,193 @@
1
+ """Requester SDK.
2
+
3
+ from passkey_vault_client import Client
4
+
5
+ request = Client().request("github", "gh auth login --with-token")
6
+ print("Approve at", request.approve_url)
7
+ secret = request.wait() # bytes; raises RequestDenied / RequestExpired / RequestTimeout
8
+
9
+ Each request generates a fresh RSA key pair in memory. The private key never leaves the
10
+ ApprovalRequest object and is dropped after the first successful decryption.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ipaddress
16
+ import json
17
+ import time
18
+ import urllib.error
19
+ import urllib.request
20
+ from dataclasses import dataclass
21
+ from typing import Any, Literal
22
+ from urllib.parse import urlsplit
23
+
24
+ from cryptography.hazmat.primitives import hashes, serialization
25
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
26
+
27
+ from .protocol import b64url_decode, b64url_encode, oaep_label
28
+
29
+ DEFAULT_URL = "http://127.0.0.1:8741"
30
+ MAX_WAIT = 30 # the server's long-poll limit, in seconds
31
+
32
+ Status = Literal["pending", "approved", "denied", "expired"]
33
+
34
+
35
+ class PkvError(Exception):
36
+ """Base class for every error raised by this package."""
37
+
38
+
39
+ class ServerError(PkvError):
40
+ """The server rejected a call. `code` is the stable error code from docs/interface.md."""
41
+
42
+ def __init__(self, status: int, code: str, message: str) -> None:
43
+ super().__init__(f"{code}: {message} (HTTP {status})")
44
+ self.status, self.code, self.message = status, code, message
45
+
46
+
47
+ class RequestDenied(PkvError):
48
+ """The approver denied the request."""
49
+
50
+
51
+ class RequestExpired(PkvError):
52
+ """The request expired before it was approved and collected."""
53
+
54
+
55
+ class RequestTimeout(PkvError):
56
+ """wait() gave up before the request was decided."""
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class SecretInfo:
61
+ """What the vault holds under a name. Never includes the secret itself."""
62
+
63
+ name: str
64
+ site: str
65
+ account: str
66
+ updated_at: str
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class PollResult:
71
+ """One answer from the server. `ciphertext` is set only when status is "approved"."""
72
+
73
+ status: Status
74
+ ciphertext: bytes | None = None
75
+
76
+
77
+ def _is_loopback(url: str) -> bool:
78
+ host = urlsplit(url).hostname or ""
79
+ if host == "localhost":
80
+ return True
81
+ try:
82
+ return ipaddress.ip_address(host).is_loopback
83
+ except ValueError:
84
+ return False
85
+
86
+
87
+ class Client:
88
+ """Talks to the requester door of a passkey-vault server."""
89
+
90
+ def __init__(self, base_url: str = DEFAULT_URL, token: str | None = None, http_timeout: float = 10) -> None:
91
+ self.base_url = base_url.rstrip("/")
92
+ self.http_timeout = http_timeout
93
+ self._headers = {"Authorization": f"Bearer {token}"} if token else {}
94
+ # Never send loopback traffic through an HTTP(S)_PROXY from the environment.
95
+ handlers = [urllib.request.ProxyHandler({})] if _is_loopback(self.base_url) else []
96
+ self._opener = urllib.request.build_opener(*handlers)
97
+
98
+ def _call(
99
+ self, method: str, path: str, body: dict[str, Any] | None = None, timeout: float | None = None
100
+ ) -> dict[str, Any]:
101
+ data = None if body is None else json.dumps(body).encode()
102
+ headers = {**self._headers, **({"Content-Type": "application/json"} if data else {})}
103
+ req = urllib.request.Request(self.base_url + path, data=data, method=method, headers=headers)
104
+ try:
105
+ with self._opener.open(req, timeout=timeout or self.http_timeout) as r:
106
+ result: dict[str, Any] = json.loads(r.read())
107
+ return result
108
+ except urllib.error.HTTPError as e:
109
+ with e:
110
+ try:
111
+ err = json.loads(e.read() or b"{}")
112
+ except ValueError:
113
+ err = {}
114
+ raise ServerError(e.code, err.get("error", "http_error"), err.get("message", str(e.reason))) from None
115
+ except urllib.error.URLError as e:
116
+ raise PkvError(f"cannot reach the passkey-vault server at {self.base_url}: {e.reason}") from None
117
+
118
+ def list_secrets(self) -> list[SecretInfo]:
119
+ """Names and metadata of the vault's items (no secrets). Also a cheap connectivity check."""
120
+ body = self._call("GET", "/secrets")
121
+ return [SecretInfo(s["name"], s["site"], s["account"], s["updated_at"]) for s in body["secrets"]]
122
+
123
+ def request(self, secret: str, command: str, key_bits: int = 3072) -> ApprovalRequest:
124
+ """Ask for `secret` to be used for exactly `command` (shown verbatim to the approver)."""
125
+ key = rsa.generate_private_key(public_exponent=65537, key_size=key_bits)
126
+ pubkey_der = key.public_key().public_bytes(
127
+ serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo
128
+ )
129
+ body = self._call(
130
+ "POST", "/requests", {"secret": secret, "command": command, "pubkey": b64url_encode(pubkey_der)}
131
+ )
132
+ return ApprovalRequest(
133
+ self, body["id"], body["approve_url"], body["expires_at"], secret, command, pubkey_der, key
134
+ )
135
+
136
+
137
+ class ApprovalRequest:
138
+ """A pending request. Create it with Client.request(); the one-time key stays inside."""
139
+
140
+ def __init__(
141
+ self,
142
+ client: Client,
143
+ request_id: str,
144
+ approve_url: str,
145
+ expires_at: str,
146
+ secret: str,
147
+ command: str,
148
+ pubkey_der: bytes,
149
+ private_key: rsa.RSAPrivateKey,
150
+ ) -> None:
151
+ self.client = client
152
+ self.id = request_id
153
+ self.approve_url = approve_url
154
+ self.expires_at = expires_at
155
+ self.secret = secret
156
+ self.command = command
157
+ self.pubkey_der = pubkey_der
158
+ self._key: rsa.RSAPrivateKey | None = private_key
159
+
160
+ def __repr__(self) -> str:
161
+ return f"ApprovalRequest(id={self.id!r}, secret={self.secret!r}, command={self.command!r})"
162
+
163
+ def poll(self, wait: int = MAX_WAIT) -> PollResult:
164
+ """One long poll of up to `wait` seconds."""
165
+ wait = max(0, min(wait, MAX_WAIT))
166
+ body = self.client._call("GET", f"/requests/{self.id}?wait={wait}", timeout=wait + 10)
167
+ ciphertext = b64url_decode(body["ciphertext"]) if body["status"] == "approved" else None
168
+ return PollResult(body["status"], ciphertext)
169
+
170
+ def wait(self, timeout: float = 330) -> bytes:
171
+ """Block until the request is decided; return the secret as bytes."""
172
+ deadline = time.monotonic() + timeout
173
+ while True:
174
+ remaining = deadline - time.monotonic()
175
+ if remaining <= 0:
176
+ raise RequestTimeout(f"no decision within {timeout:.0f}s")
177
+ result = self.poll(int(min(MAX_WAIT, max(1, remaining))))
178
+ if result.status == "approved":
179
+ assert result.ciphertext is not None
180
+ return self.decrypt(result.ciphertext)
181
+ if result.status == "denied":
182
+ raise RequestDenied("the approver denied the request")
183
+ if result.status == "expired":
184
+ raise RequestExpired("the request expired")
185
+
186
+ def decrypt(self, ciphertext: bytes) -> bytes:
187
+ if self._key is None:
188
+ raise PkvError("this request's one-time key was already used")
189
+ label = oaep_label(self.id, self.command, self.pubkey_der)
190
+ oaep = padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=label)
191
+ plaintext = self._key.decrypt(ciphertext, oaep)
192
+ self._key = None # one-time key: drop it after a successful decryption
193
+ return plaintext
@@ -0,0 +1,66 @@
1
+ """pkv settings: where the server is and the requester token.
2
+
3
+ Precedence, highest first: command-line option, environment variable (PKV_SERVER, PKV_TOKEN), the
4
+ config file written by `pkv setup`, the built-in default.
5
+
6
+ The file is JSON so that it can be read on every supported Python (tomllib needs 3.11). It holds the
7
+ requester token, so it is written with mode 0600 inside a 0700 directory.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import tempfile
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ from .client import DEFAULT_URL
19
+
20
+
21
+ def config_path() -> Path:
22
+ if os.environ.get("PKV_CONFIG"):
23
+ return Path(os.environ["PKV_CONFIG"])
24
+ if os.name == "nt":
25
+ base = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")
26
+ else:
27
+ base = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
28
+ return base / "pkv" / "config.json"
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Settings:
33
+ server: str = DEFAULT_URL
34
+ token: str | None = None
35
+
36
+
37
+ def load_file() -> Settings | None:
38
+ path = config_path()
39
+ try:
40
+ data = json.loads(path.read_text(encoding="utf-8"))
41
+ except FileNotFoundError:
42
+ return None
43
+ return Settings(server=data.get("server") or DEFAULT_URL, token=data.get("token") or None)
44
+
45
+
46
+ def resolve(server_option: str | None) -> Settings:
47
+ saved = load_file() or Settings()
48
+ return Settings(
49
+ server=server_option or os.environ.get("PKV_SERVER") or saved.server,
50
+ token=os.environ.get("PKV_TOKEN") or saved.token,
51
+ )
52
+
53
+
54
+ def save(settings: Settings) -> Path:
55
+ path = config_path()
56
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
57
+ body = json.dumps({"server": settings.server, "token": settings.token}, indent=2) + "\n"
58
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".config.", suffix=".tmp") # created 0600
59
+ try:
60
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
61
+ f.write(body)
62
+ os.replace(tmp, path)
63
+ except BaseException:
64
+ Path(tmp).unlink(missing_ok=True)
65
+ raise
66
+ return path
@@ -0,0 +1,34 @@
1
+ """Byte-level rules a requester needs (docs/interface.md section 2), checked against test-vectors/.
2
+
3
+ Self-contained on purpose: requesters do not depend on the server package.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import re
10
+ import struct
11
+
12
+ LABEL_TAG = b"passkey-vault/oaep-label/v1"
13
+ _B64URL_RE = re.compile(r"^[A-Za-z0-9_-]*$")
14
+
15
+
16
+ def lp(x: str | bytes) -> bytes:
17
+ """Length-prefixed encoding: u32be(len) || bytes."""
18
+ b = x.encode("utf-8") if isinstance(x, str) else bytes(x)
19
+ return struct.pack(">I", len(b)) + b
20
+
21
+
22
+ def oaep_label(request_id: str, command: str, pubkey_der: bytes) -> bytes:
23
+ """The RSA-OAEP label that binds a ciphertext to one request, one command and one key."""
24
+ return lp(LABEL_TAG) + lp(request_id) + lp(command) + lp(pubkey_der)
25
+
26
+
27
+ def b64url_encode(b: bytes) -> str:
28
+ return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")
29
+
30
+
31
+ def b64url_decode(s: str) -> bytes:
32
+ if not isinstance(s, str) or not _B64URL_RE.match(s) or len(s) % 4 == 1:
33
+ raise ValueError("not base64url")
34
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))