passkey-mcp 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/SECURITY.md +3 -0
- passkey/__init__.py +17 -0
- passkey/__main__.py +6 -0
- passkey/audit.py +124 -0
- passkey/auth.py +141 -0
- passkey/bundle.py +276 -0
- passkey/cli/__init__.py +278 -0
- passkey/cli/handlers.py +221 -0
- passkey/cli/parser.py +310 -0
- passkey/cli.py +24 -0
- passkey/clipboard.py +79 -0
- passkey/commands.py +655 -0
- passkey/completion.py +234 -0
- passkey/dirs.py +79 -0
- passkey/doctor.py +194 -0
- passkey/generator.py +42 -0
- passkey/health.py +96 -0
- passkey/importers.py +497 -0
- passkey/interactive.py +274 -0
- passkey/keychain.py +409 -0
- passkey/mcp_commands.py +796 -0
- passkey/mcp_config.py +667 -0
- passkey/mcp_server.py +259 -0
- passkey/models.py +189 -0
- passkey/py.typed +0 -0
- passkey/runner.py +66 -0
- passkey/settings.py +127 -0
- passkey/sharing.py +266 -0
- passkey/templates.py +160 -0
- passkey_mcp-0.4.0.dist-info/METADATA +539 -0
- passkey_mcp-0.4.0.dist-info/RECORD +59 -0
- passkey_mcp-0.4.0.dist-info/WHEEL +5 -0
- passkey_mcp-0.4.0.dist-info/entry_points.txt +3 -0
- passkey_mcp-0.4.0.dist-info/licenses/LICENSE +21 -0
- passkey_mcp-0.4.0.dist-info/top_level.txt +3 -0
- tests/__init__.py +0 -0
- tests/conftest.py +42 -0
- tests/integration/__init__.py +0 -0
- tests/integration/test_mcp_integration.py +98 -0
- tests/test_audit.py +123 -0
- tests/test_auth.py +141 -0
- tests/test_bundle.py +295 -0
- tests/test_cli.py +239 -0
- tests/test_commands.py +44 -0
- tests/test_completion.py +79 -0
- tests/test_dirs.py +178 -0
- tests/test_generator.py +52 -0
- tests/test_health.py +106 -0
- tests/test_importers.py +333 -0
- tests/test_interactive.py +135 -0
- tests/test_keychain.py +233 -0
- tests/test_mcp_config.py +300 -0
- tests/test_mcp_server.py +546 -0
- tests/test_models.py +146 -0
- tests/test_runner.py +124 -0
- tests/test_settings.py +128 -0
- tests/test_sharing.py +64 -0
- tests/test_templates.py +126 -0
- tests/test_unwrap.py +179 -0
docs/SECURITY.md
ADDED
passkey/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Passkey - cross-platform system keychain secrets manager with MCP integration."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version as _package_version
|
|
4
|
+
|
|
5
|
+
from .keychain import delete_entry, get_entry, list_entries, save_entry
|
|
6
|
+
from .models import Entry
|
|
7
|
+
|
|
8
|
+
__version__ = _package_version("passkey-mcp")
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Entry",
|
|
12
|
+
"__version__",
|
|
13
|
+
"delete_entry",
|
|
14
|
+
"get_entry",
|
|
15
|
+
"list_entries",
|
|
16
|
+
"save_entry",
|
|
17
|
+
]
|
passkey/__main__.py
ADDED
passkey/audit.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Audit logging for passkey operations."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .dirs import get_data_dir
|
|
9
|
+
|
|
10
|
+
# When the log exceeds this size, the oldest half of the lines is dropped.
|
|
11
|
+
MAX_LOG_BYTES = 1_000_000 # ~1 MB
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_log_path() -> Path:
|
|
15
|
+
"""Get the audit log path, creating directory if needed."""
|
|
16
|
+
default = get_data_dir() / "audit.log"
|
|
17
|
+
log_path = Path(os.environ.get("PASSKEY_AUDIT_LOG", default))
|
|
18
|
+
log_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
19
|
+
return log_path
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _rotate_if_needed(log_path: Path) -> None:
|
|
23
|
+
"""Cap the log size by dropping the oldest half of the lines."""
|
|
24
|
+
try:
|
|
25
|
+
if not log_path.exists() or log_path.stat().st_size <= MAX_LOG_BYTES:
|
|
26
|
+
return
|
|
27
|
+
lines = log_path.read_text().splitlines(keepends=True)
|
|
28
|
+
keep = lines[len(lines) // 2 :]
|
|
29
|
+
log_path.write_text("".join(keep))
|
|
30
|
+
except OSError:
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _ensure_secure_permissions(path: Path) -> None:
|
|
35
|
+
"""Ensure file has secure permissions (owner only)."""
|
|
36
|
+
if path.exists():
|
|
37
|
+
current_mode = path.stat().st_mode & 0o777
|
|
38
|
+
if current_mode != 0o600:
|
|
39
|
+
path.chmod(0o600)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def log_operation(
|
|
43
|
+
operation: str,
|
|
44
|
+
entry_name: str | None = None,
|
|
45
|
+
details: dict | None = None,
|
|
46
|
+
success: bool = True,
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Log an operation to the audit log.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
operation: The operation type (create, read, update, delete, import, export)
|
|
52
|
+
entry_name: The entry involved, if any
|
|
53
|
+
details: Additional details as dict
|
|
54
|
+
success: Whether the operation succeeded
|
|
55
|
+
"""
|
|
56
|
+
log_path = get_log_path()
|
|
57
|
+
_rotate_if_needed(log_path)
|
|
58
|
+
|
|
59
|
+
record = {
|
|
60
|
+
"timestamp": datetime.now().isoformat(),
|
|
61
|
+
"operation": operation,
|
|
62
|
+
"success": success,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if entry_name:
|
|
66
|
+
record["entry"] = entry_name
|
|
67
|
+
|
|
68
|
+
if details:
|
|
69
|
+
record["details"] = details
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
with open(log_path, "a") as f:
|
|
73
|
+
f.write(json.dumps(record) + "\n")
|
|
74
|
+
# Ensure secure permissions on log file
|
|
75
|
+
_ensure_secure_permissions(log_path)
|
|
76
|
+
except Exception:
|
|
77
|
+
import sys as _sys
|
|
78
|
+
print(f"WARNING: audit log write failed ({log_path})", file=_sys.stderr)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def get_recent_logs(limit: int = 50) -> list[dict]:
|
|
82
|
+
"""Get recent audit log entries.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
limit: Maximum number of entries to return
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
List of log entries, most recent first
|
|
89
|
+
"""
|
|
90
|
+
log_path = get_log_path()
|
|
91
|
+
|
|
92
|
+
if not log_path.exists():
|
|
93
|
+
return []
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
with open(log_path) as f:
|
|
97
|
+
lines = f.readlines()
|
|
98
|
+
|
|
99
|
+
entries = []
|
|
100
|
+
for line in reversed(lines[-limit:]):
|
|
101
|
+
try:
|
|
102
|
+
entries.append(json.loads(line.strip()))
|
|
103
|
+
except json.JSONDecodeError:
|
|
104
|
+
continue
|
|
105
|
+
|
|
106
|
+
return entries
|
|
107
|
+
except Exception:
|
|
108
|
+
return []
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def clear_logs() -> bool:
|
|
112
|
+
"""Clear the audit log.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
True if successful, False otherwise
|
|
116
|
+
"""
|
|
117
|
+
log_path = get_log_path()
|
|
118
|
+
|
|
119
|
+
try:
|
|
120
|
+
if log_path.exists():
|
|
121
|
+
log_path.unlink()
|
|
122
|
+
return True
|
|
123
|
+
except Exception:
|
|
124
|
+
return False
|
passkey/auth.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""OS-level authentication for sensitive passkey operations.
|
|
2
|
+
|
|
3
|
+
This module is only reached when the user has explicitly opted in via
|
|
4
|
+
``passkey config require-auth on``. The primary protection for secrets is
|
|
5
|
+
always the OS keychain's own ACL; this is an optional extra prompt for
|
|
6
|
+
interactive terminal sessions. Headless code paths (``passkey run`` from
|
|
7
|
+
an MCP server) never call into this module.
|
|
8
|
+
|
|
9
|
+
Platform notes:
|
|
10
|
+
|
|
11
|
+
- macOS: ``sudo -v`` via the system PAM stack (Touch ID if pam_tid is
|
|
12
|
+
configured). Requires a tty; without one it simply fails closed.
|
|
13
|
+
- Linux: ``pkexec`` polkit dialog, with a getpass+sudo fallback.
|
|
14
|
+
- Windows: deliberately a no-op. The previous implementation used
|
|
15
|
+
ShellExecuteW "runas", which elevates a *separate* process and proves
|
|
16
|
+
nothing about the current one — security theater, dropped. Windows
|
|
17
|
+
protection comes from Credential Manager ACLs alone.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
|
|
23
|
+
from .keychain import PasskeyError
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _authenticate_macOS() -> bool:
|
|
27
|
+
"""Trigger macOS authentication dialog (Touch ID / password).
|
|
28
|
+
|
|
29
|
+
Uses 'sudo -v' which validates credentials via the system PAM stack.
|
|
30
|
+
This honors the user's PAM configuration, including Touch ID (pam_tid.so)
|
|
31
|
+
if set up in /etc/pam.d/sudo.
|
|
32
|
+
|
|
33
|
+
If credentials are cached by sudo, no dialog is shown (same 5-min window).
|
|
34
|
+
"""
|
|
35
|
+
try:
|
|
36
|
+
result = subprocess.run(
|
|
37
|
+
["sudo", "-v"],
|
|
38
|
+
capture_output=True,
|
|
39
|
+
text=True,
|
|
40
|
+
timeout=120,
|
|
41
|
+
)
|
|
42
|
+
return result.returncode == 0
|
|
43
|
+
except FileNotFoundError:
|
|
44
|
+
return False
|
|
45
|
+
except subprocess.TimeoutExpired:
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _authenticate_linux() -> bool:
|
|
50
|
+
"""Trigger Linux polkit authentication dialog.
|
|
51
|
+
|
|
52
|
+
Uses pkexec which shows a native desktop authentication dialog
|
|
53
|
+
(GNOME, KDE, etc.) via PolicyKit.
|
|
54
|
+
"""
|
|
55
|
+
try:
|
|
56
|
+
result = subprocess.run(
|
|
57
|
+
["/usr/bin/pkexec", "/usr/bin/true"],
|
|
58
|
+
capture_output=True,
|
|
59
|
+
text=True,
|
|
60
|
+
timeout=120,
|
|
61
|
+
)
|
|
62
|
+
return result.returncode == 0
|
|
63
|
+
except FileNotFoundError:
|
|
64
|
+
# pkexec not available, fall back to sudo
|
|
65
|
+
return _authenticate_sudo_fallback()
|
|
66
|
+
except subprocess.TimeoutExpired:
|
|
67
|
+
return False
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _authenticate_windows() -> bool:
|
|
71
|
+
"""Honest no-op on Windows.
|
|
72
|
+
|
|
73
|
+
There is no meaningful per-process auth oracle available to us on
|
|
74
|
+
Windows (UAC elevates a separate process, which proves nothing about
|
|
75
|
+
this one). Rather than pretend, we rely on Windows Credential Manager
|
|
76
|
+
ACLs and tell the user so.
|
|
77
|
+
"""
|
|
78
|
+
print(
|
|
79
|
+
"Note: OS-auth prompts are not supported on Windows; "
|
|
80
|
+
"relying on Credential Manager access controls.",
|
|
81
|
+
file=sys.stderr,
|
|
82
|
+
)
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _authenticate_sudo_fallback() -> bool:
|
|
87
|
+
"""Fallback: use getpass + sudo -S to verify user password.
|
|
88
|
+
|
|
89
|
+
This is less elegant (no GUI dialog) but works everywhere.
|
|
90
|
+
"""
|
|
91
|
+
import getpass
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
password = getpass.getpass("Admin password required: ")
|
|
95
|
+
result = subprocess.run(
|
|
96
|
+
["sudo", "-S", "true"],
|
|
97
|
+
input=password + "\n",
|
|
98
|
+
capture_output=True,
|
|
99
|
+
text=True,
|
|
100
|
+
timeout=30,
|
|
101
|
+
)
|
|
102
|
+
return result.returncode == 0
|
|
103
|
+
except (subprocess.TimeoutExpired, KeyboardInterrupt):
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def authenticate(reason: str = "Authenticate to access secrets") -> bool:
|
|
108
|
+
"""Trigger OS-level authentication.
|
|
109
|
+
|
|
110
|
+
Displays the native system authentication dialog (Touch ID, admin
|
|
111
|
+
password, UAC, or polkit). The specific mechanism depends on the OS.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
reason: Not used on all platforms, but provided for consistency
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
True if authentication succeeded, False otherwise
|
|
118
|
+
"""
|
|
119
|
+
if sys.platform == "darwin":
|
|
120
|
+
return _authenticate_macOS()
|
|
121
|
+
elif sys.platform == "linux":
|
|
122
|
+
return _authenticate_linux()
|
|
123
|
+
elif sys.platform == "win32":
|
|
124
|
+
return _authenticate_windows()
|
|
125
|
+
else:
|
|
126
|
+
return _authenticate_sudo_fallback()
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def require_auth(operation: str = "access secrets") -> None:
|
|
130
|
+
"""Require authentication or raise PasskeyError.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
operation: Description of what requires auth (for error message)
|
|
134
|
+
|
|
135
|
+
Raises:
|
|
136
|
+
PasskeyError: If authentication fails or is cancelled
|
|
137
|
+
"""
|
|
138
|
+
if not authenticate():
|
|
139
|
+
raise PasskeyError(
|
|
140
|
+
f"Authentication required to {operation}. Authentication failed or was cancelled."
|
|
141
|
+
)
|
passkey/bundle.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""Encrypted bundle export/import for portable secret transfer."""
|
|
2
|
+
|
|
3
|
+
import getpass
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import stat
|
|
7
|
+
import struct
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
12
|
+
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
|
13
|
+
|
|
14
|
+
from .audit import log_operation
|
|
15
|
+
from .keychain import PasskeyError, get_entry, list_entries, save_entry
|
|
16
|
+
from .models import Entry, is_valid_name
|
|
17
|
+
|
|
18
|
+
MAGIC = b"PK01"
|
|
19
|
+
FORMAT_VERSION = 1
|
|
20
|
+
SALT_LEN = 32
|
|
21
|
+
NONCE_LEN = 12
|
|
22
|
+
MIN_PASSPHRASE_LEN = 12
|
|
23
|
+
|
|
24
|
+
SCRYPT_N = 2**20
|
|
25
|
+
SCRYPT_R = 8
|
|
26
|
+
SCRYPT_P = 1
|
|
27
|
+
KEY_LEN = 32
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def check_file_permissions(
|
|
31
|
+
path: Path, allow_insecure: bool = False, strict: bool = False
|
|
32
|
+
) -> None:
|
|
33
|
+
"""Check that a file has no group/other permissions.
|
|
34
|
+
|
|
35
|
+
Default (strict=False): warn only. With strict=True, raise PasskeyError
|
|
36
|
+
for insecure files unless allow_insecure is set (the --insecure flag).
|
|
37
|
+
|
|
38
|
+
This is the single implementation used by bundles, exports, and
|
|
39
|
+
importers alike.
|
|
40
|
+
"""
|
|
41
|
+
try:
|
|
42
|
+
mode = path.stat().st_mode
|
|
43
|
+
except Exception:
|
|
44
|
+
return
|
|
45
|
+
if not mode & (stat.S_IRWXG | stat.S_IRWXO):
|
|
46
|
+
return
|
|
47
|
+
if strict and not allow_insecure:
|
|
48
|
+
raise PasskeyError(
|
|
49
|
+
f"'{path}' has insecure permissions ({oct(mode & 0o777)}).\n"
|
|
50
|
+
" This file may be readable by other users on this system.\n"
|
|
51
|
+
f" Fix with: chmod 600 '{path}'\n"
|
|
52
|
+
" Or use --insecure to import anyway."
|
|
53
|
+
)
|
|
54
|
+
print(
|
|
55
|
+
f"WARNING: '{path}' has insecure permissions ({oct(mode & 0o777)}).",
|
|
56
|
+
file=sys.stderr,
|
|
57
|
+
)
|
|
58
|
+
if strict and allow_insecure:
|
|
59
|
+
print(" Proceeding anyway due to --insecure flag.\n", file=sys.stderr)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _derive_key(passphrase: str, salt: bytes) -> bytes:
|
|
63
|
+
"""Derive a 256-bit key from passphrase using scrypt."""
|
|
64
|
+
kdf = Scrypt(salt=salt, length=KEY_LEN, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P)
|
|
65
|
+
return kdf.derive(passphrase.encode("utf-8"))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def export_bundle(
|
|
69
|
+
output_path: str,
|
|
70
|
+
entry_names: list[str] | None = None,
|
|
71
|
+
passphrase: str | None = None,
|
|
72
|
+
) -> Path:
|
|
73
|
+
"""Export entries to an encrypted bundle file.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
output_path: Destination file path
|
|
77
|
+
entry_names: Specific entries to export (None = all)
|
|
78
|
+
passphrase: Encryption passphrase (prompted if None)
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
Path to created bundle file
|
|
82
|
+
|
|
83
|
+
Raises:
|
|
84
|
+
PasskeyError: If Keychain access fails or no entries found
|
|
85
|
+
FileExistsError: If output file already exists
|
|
86
|
+
"""
|
|
87
|
+
path = Path(output_path).expanduser()
|
|
88
|
+
if path.exists():
|
|
89
|
+
raise FileExistsError(f"File already exists: {path}")
|
|
90
|
+
|
|
91
|
+
all_names = list_entries()
|
|
92
|
+
if not all_names:
|
|
93
|
+
raise PasskeyError("No entries to export")
|
|
94
|
+
|
|
95
|
+
if entry_names:
|
|
96
|
+
missing = set(entry_names) - set(all_names)
|
|
97
|
+
if missing:
|
|
98
|
+
raise PasskeyError(f"Entries not found: {', '.join(sorted(missing))}")
|
|
99
|
+
names_to_export = entry_names
|
|
100
|
+
else:
|
|
101
|
+
names_to_export = all_names
|
|
102
|
+
|
|
103
|
+
entries_data = []
|
|
104
|
+
for name in names_to_export:
|
|
105
|
+
entry = get_entry(name)
|
|
106
|
+
if entry:
|
|
107
|
+
entries_data.append(entry.to_export_dict())
|
|
108
|
+
|
|
109
|
+
if not entries_data:
|
|
110
|
+
raise PasskeyError("No entries could be read from Keychain")
|
|
111
|
+
|
|
112
|
+
if passphrase is None:
|
|
113
|
+
passphrase = getpass.getpass("Bundle passphrase (min 12 chars): ")
|
|
114
|
+
if len(passphrase) < MIN_PASSPHRASE_LEN:
|
|
115
|
+
raise PasskeyError(f"Passphrase must be at least {MIN_PASSPHRASE_LEN} characters")
|
|
116
|
+
confirm = getpass.getpass("Confirm passphrase: ")
|
|
117
|
+
if passphrase != confirm:
|
|
118
|
+
raise PasskeyError("Passphrases do not match")
|
|
119
|
+
|
|
120
|
+
if len(passphrase) < MIN_PASSPHRASE_LEN:
|
|
121
|
+
raise PasskeyError(f"Passphrase must be at least {MIN_PASSPHRASE_LEN} characters")
|
|
122
|
+
|
|
123
|
+
payload = json.dumps(
|
|
124
|
+
{
|
|
125
|
+
"version": "1.0",
|
|
126
|
+
"entry_count": len(entries_data),
|
|
127
|
+
"entries": entries_data,
|
|
128
|
+
}
|
|
129
|
+
).encode("utf-8")
|
|
130
|
+
|
|
131
|
+
salt = os.urandom(SALT_LEN)
|
|
132
|
+
nonce = os.urandom(NONCE_LEN)
|
|
133
|
+
key = _derive_key(passphrase, salt)
|
|
134
|
+
aesgcm = AESGCM(key)
|
|
135
|
+
ciphertext = aesgcm.encrypt(nonce, payload, None)
|
|
136
|
+
|
|
137
|
+
header = MAGIC + struct.pack(">I", FORMAT_VERSION)
|
|
138
|
+
|
|
139
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
140
|
+
try:
|
|
141
|
+
with os.fdopen(fd, "wb") as f:
|
|
142
|
+
f.write(header)
|
|
143
|
+
f.write(salt)
|
|
144
|
+
f.write(nonce)
|
|
145
|
+
f.write(ciphertext)
|
|
146
|
+
except BaseException:
|
|
147
|
+
os.unlink(path)
|
|
148
|
+
raise
|
|
149
|
+
|
|
150
|
+
log_operation("bundle_export", details={"count": len(entries_data)})
|
|
151
|
+
return path
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def import_bundle(
|
|
155
|
+
input_path: str,
|
|
156
|
+
passphrase: str | None = None,
|
|
157
|
+
mode: str = "skip",
|
|
158
|
+
) -> dict:
|
|
159
|
+
"""Import entries from an encrypted bundle file.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
input_path: Path to encrypted bundle
|
|
163
|
+
passphrase: Decryption passphrase (prompted if None)
|
|
164
|
+
mode: How to handle existing entries (skip, overwrite, merge)
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
Dict with import results: created, updated, skipped counts
|
|
168
|
+
|
|
169
|
+
Raises:
|
|
170
|
+
PasskeyError: If decryption fails or bundle is invalid
|
|
171
|
+
"""
|
|
172
|
+
path = Path(input_path).expanduser()
|
|
173
|
+
if not path.exists():
|
|
174
|
+
raise PasskeyError(f"File not found: {path}")
|
|
175
|
+
|
|
176
|
+
check_file_permissions(path)
|
|
177
|
+
|
|
178
|
+
with open(path, "rb") as f:
|
|
179
|
+
data = f.read()
|
|
180
|
+
|
|
181
|
+
min_size = len(MAGIC) + 4 + SALT_LEN + NONCE_LEN + 16
|
|
182
|
+
if len(data) < min_size:
|
|
183
|
+
raise PasskeyError("Invalid bundle file: too small")
|
|
184
|
+
|
|
185
|
+
magic = data[:4]
|
|
186
|
+
if magic != MAGIC:
|
|
187
|
+
raise PasskeyError("Invalid bundle file: bad magic bytes")
|
|
188
|
+
|
|
189
|
+
version = struct.unpack(">I", data[4:8])[0]
|
|
190
|
+
if version != FORMAT_VERSION:
|
|
191
|
+
raise PasskeyError(f"Unsupported bundle version: {version}")
|
|
192
|
+
|
|
193
|
+
offset = 8
|
|
194
|
+
salt = data[offset : offset + SALT_LEN]
|
|
195
|
+
offset += SALT_LEN
|
|
196
|
+
nonce = data[offset : offset + NONCE_LEN]
|
|
197
|
+
offset += NONCE_LEN
|
|
198
|
+
ciphertext = data[offset:]
|
|
199
|
+
|
|
200
|
+
if passphrase is None:
|
|
201
|
+
passphrase = getpass.getpass("Bundle passphrase: ")
|
|
202
|
+
|
|
203
|
+
key = _derive_key(passphrase, salt)
|
|
204
|
+
aesgcm = AESGCM(key)
|
|
205
|
+
|
|
206
|
+
try:
|
|
207
|
+
plaintext = aesgcm.decrypt(nonce, ciphertext, None)
|
|
208
|
+
except Exception:
|
|
209
|
+
raise PasskeyError("Decryption failed: wrong passphrase or corrupted bundle") from None
|
|
210
|
+
|
|
211
|
+
try:
|
|
212
|
+
payload = json.loads(plaintext.decode("utf-8"))
|
|
213
|
+
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
|
214
|
+
raise PasskeyError(f"Invalid bundle payload: {e}") from e
|
|
215
|
+
|
|
216
|
+
entries = payload.get("entries", [])
|
|
217
|
+
if not entries:
|
|
218
|
+
raise PasskeyError("Bundle contains no entries")
|
|
219
|
+
|
|
220
|
+
created = 0
|
|
221
|
+
updated = 0
|
|
222
|
+
skipped = 0
|
|
223
|
+
|
|
224
|
+
for entry_data in entries:
|
|
225
|
+
name = entry_data.get("name")
|
|
226
|
+
fields = entry_data.get("fields", {})
|
|
227
|
+
config = entry_data.get("config", {})
|
|
228
|
+
|
|
229
|
+
if not name or not fields:
|
|
230
|
+
skipped += 1
|
|
231
|
+
continue
|
|
232
|
+
|
|
233
|
+
if not is_valid_name(name):
|
|
234
|
+
print(f" {name}: skipped (invalid entry name)", file=sys.stderr)
|
|
235
|
+
skipped += 1
|
|
236
|
+
continue
|
|
237
|
+
|
|
238
|
+
existing = get_entry(name)
|
|
239
|
+
|
|
240
|
+
if existing and mode == "skip":
|
|
241
|
+
print(f" {name}: skipped (exists)")
|
|
242
|
+
skipped += 1
|
|
243
|
+
continue
|
|
244
|
+
|
|
245
|
+
if existing and mode == "merge":
|
|
246
|
+
changed = existing.merge_fields(fields)
|
|
247
|
+
for k, v in config.items():
|
|
248
|
+
existing.config[k] = v
|
|
249
|
+
if changed:
|
|
250
|
+
save_entry(existing, is_update=True)
|
|
251
|
+
print(f" {name}: merged ({len(changed)} fields)")
|
|
252
|
+
updated += 1
|
|
253
|
+
else:
|
|
254
|
+
print(f" {name}: skipped (no changes)")
|
|
255
|
+
skipped += 1
|
|
256
|
+
continue
|
|
257
|
+
|
|
258
|
+
entry = Entry(
|
|
259
|
+
name=name,
|
|
260
|
+
fields=fields,
|
|
261
|
+
config=config,
|
|
262
|
+
source="bundle-import",
|
|
263
|
+
)
|
|
264
|
+
save_entry(entry, is_update=existing is not None)
|
|
265
|
+
action = "updated" if existing else "created"
|
|
266
|
+
print(f" {name}: {action}")
|
|
267
|
+
if existing:
|
|
268
|
+
updated += 1
|
|
269
|
+
else:
|
|
270
|
+
created += 1
|
|
271
|
+
|
|
272
|
+
log_operation(
|
|
273
|
+
"bundle_import", details={"created": created, "updated": updated, "skipped": skipped}
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
return {"created": created, "updated": updated, "skipped": skipped}
|