@onecraft/wallet 0.0.0-stage → 0.1.145
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/.claude-plugin/marketplace.json +20 -0
- package/.openclaw/AGENTS.md +100 -0
- package/.openclaw/extensions/agent-wallet/README.md +195 -0
- package/.openclaw/extensions/agent-wallet/dist/index.js +2198 -0
- package/.openclaw/extensions/agent-wallet/index.ts +2198 -0
- package/.openclaw/extensions/agent-wallet/openclaw.plugin.json +251 -0
- package/.openclaw/extensions/agent-wallet/package.json +49 -0
- package/.openclaw/extensions/agent-wallet/skills/cards/SKILL.md +211 -0
- package/.openclaw/extensions/agent-wallet/skills/wallet-operator/SKILL.md +30 -0
- package/CHANGELOG.md +1232 -0
- package/LICENSE +104 -0
- package/README.md +193 -2
- package/VERSION +1 -0
- package/agent-wallet/.env.example +63 -0
- package/agent-wallet/AGENTS.md +130 -0
- package/agent-wallet/CARD_VAULT.md +640 -0
- package/agent-wallet/README.md +615 -0
- package/agent-wallet/UPGRADE_COMPATIBILITY.md +66 -0
- package/agent-wallet/agent_wallet/__init__.py +16 -0
- package/agent-wallet/agent_wallet/approval.py +165 -0
- package/agent-wallet/agent_wallet/autonomous_permissions.py +281 -0
- package/agent-wallet/agent_wallet/autonomous_policy.py +305 -0
- package/agent-wallet/agent_wallet/autonomous_session.py +236 -0
- package/agent-wallet/agent_wallet/boot_key_migration.py +155 -0
- package/agent-wallet/agent_wallet/boot_key_recovery.py +57 -0
- package/agent-wallet/agent_wallet/bootstrap.py +194 -0
- package/agent-wallet/agent_wallet/card_catalog.py +243 -0
- package/agent-wallet/agent_wallet/card_runtime_secrets.py +108 -0
- package/agent-wallet/agent_wallet/card_vault.py +331 -0
- package/agent-wallet/agent_wallet/card_vault_cli.py +174 -0
- package/agent-wallet/agent_wallet/card_vault_import.py +65 -0
- package/agent-wallet/agent_wallet/card_vault_keychain.py +239 -0
- package/agent-wallet/agent_wallet/config.py +719 -0
- package/agent-wallet/agent_wallet/connector_cli.py +198 -0
- package/agent-wallet/agent_wallet/connectors/__init__.py +28 -0
- package/agent-wallet/agent_wallet/connectors/catalog.py +68 -0
- package/agent-wallet/agent_wallet/connectors/client.py +308 -0
- package/agent-wallet/agent_wallet/connectors/intent_policy.py +243 -0
- package/agent-wallet/agent_wallet/connectors/manifest.py +192 -0
- package/agent-wallet/agent_wallet/connectors/registry.py +341 -0
- package/agent-wallet/agent_wallet/encrypted_storage.py +314 -0
- package/agent-wallet/agent_wallet/evm_user_wallets.py +910 -0
- package/agent-wallet/agent_wallet/exceptions.py +10 -0
- package/agent-wallet/agent_wallet/file_ops.py +34 -0
- package/agent-wallet/agent_wallet/http_client.py +25 -0
- package/agent-wallet/agent_wallet/kernel_browser.py +479 -0
- package/agent-wallet/agent_wallet/kernel_cli.py +57 -0
- package/agent-wallet/agent_wallet/kernel_gateway.py +95 -0
- package/agent-wallet/agent_wallet/keystore.py +503 -0
- package/agent-wallet/agent_wallet/laso_card_vault.py +246 -0
- package/agent-wallet/agent_wallet/models.py +66 -0
- package/agent-wallet/agent_wallet/morpho_monitor.py +298 -0
- package/agent-wallet/agent_wallet/nonce_registry.py +59 -0
- package/agent-wallet/agent_wallet/openclaw_adapter.py +9129 -0
- package/agent-wallet/agent_wallet/openclaw_cli.py +658 -0
- package/agent-wallet/agent_wallet/openclaw_runtime.py +194 -0
- package/agent-wallet/agent_wallet/plugin_bundle.py +44 -0
- package/agent-wallet/agent_wallet/providers/__init__.py +1 -0
- package/agent-wallet/agent_wallet/providers/bags.py +202 -0
- package/agent-wallet/agent_wallet/providers/dexscreener.py +147 -0
- package/agent-wallet/agent_wallet/providers/evm_activity.py +257 -0
- package/agent-wallet/agent_wallet/providers/evm_portfolio.py +459 -0
- package/agent-wallet/agent_wallet/providers/imd.py +720 -0
- package/agent-wallet/agent_wallet/providers/jupiter.py +519 -0
- package/agent-wallet/agent_wallet/providers/kamino.py +404 -0
- package/agent-wallet/agent_wallet/providers/lifi.py +302 -0
- package/agent-wallet/agent_wallet/providers/solana_rpc.py +447 -0
- package/agent-wallet/agent_wallet/providers/tokenized_stocks.py +189 -0
- package/agent-wallet/agent_wallet/providers/wdk_evm_local.py +346 -0
- package/agent-wallet/agent_wallet/providers/x402.py +1972 -0
- package/agent-wallet/agent_wallet/sealed_keys.py +118 -0
- package/agent-wallet/agent_wallet/solana_stake.py +103 -0
- package/agent-wallet/agent_wallet/solana_tx.py +93 -0
- package/agent-wallet/agent_wallet/spending_limits.py +119 -0
- package/agent-wallet/agent_wallet/telemetry.py +481 -0
- package/agent-wallet/agent_wallet/transaction_policy.py +573 -0
- package/agent-wallet/agent_wallet/update_check.py +190 -0
- package/agent-wallet/agent_wallet/user_wallets.py +573 -0
- package/agent-wallet/agent_wallet/validation.py +31 -0
- package/agent-wallet/agent_wallet/vault_executor.py +456 -0
- package/agent-wallet/agent_wallet/wallet_layer/__init__.py +1 -0
- package/agent-wallet/agent_wallet/wallet_layer/base.py +1204 -0
- package/agent-wallet/agent_wallet/wallet_layer/base58.py +44 -0
- package/agent-wallet/agent_wallet/wallet_layer/factory.py +117 -0
- package/agent-wallet/agent_wallet/wallet_layer/solana.py +5246 -0
- package/agent-wallet/agent_wallet/wallet_layer/wdk_evm.py +2705 -0
- package/agent-wallet/examples/bootstrap_wallet.py +21 -0
- package/agent-wallet/examples/openclaw_runtime_onboarding.py +28 -0
- package/agent-wallet/examples/openclaw_user_wallet_example.py +31 -0
- package/agent-wallet/examples/openclaw_wallet_adapter_example.py +33 -0
- package/agent-wallet/openclaw.plugin.json +118 -0
- package/agent-wallet/pyproject.toml +36 -0
- package/agent-wallet/scripts/bootstrap_openclaw_evm.py +312 -0
- package/agent-wallet/scripts/build_release_bundle.py +210 -0
- package/agent-wallet/scripts/finalize_openclaw_local_wallet_config.py +121 -0
- package/agent-wallet/scripts/install_agent_wallet.py +1357 -0
- package/agent-wallet/scripts/install_openclaw_local_config.py +421 -0
- package/agent-wallet/scripts/install_openclaw_sealed_keys.py +117 -0
- package/agent-wallet/scripts/manage_openclaw_evm_wallet.py +333 -0
- package/agent-wallet/scripts/security_utils.py +37 -0
- package/agent-wallet/scripts/setup_evm_wallet.sh +140 -0
- package/agent-wallet/scripts/switch_openclaw_wallet_network.py +109 -0
- package/agent-wallet/skills/wallet-operator/SKILL.md +157 -0
- package/bin/lib/boot-key.mjs +184 -0
- package/bin/lib/evm-daemon.mjs +389 -0
- package/bin/lib/host-detection.mjs +259 -0
- package/bin/lib/integrations.mjs +578 -0
- package/bin/lib/release-python.mjs +9 -0
- package/bin/lib/update-transaction.mjs +235 -0
- package/bin/openclaw-agent-wallet.mjs +3354 -0
- package/claude-code/plugins/agent-wallet/.claude-plugin/plugin.json +19 -0
- package/claude-code/plugins/agent-wallet/.mcp.json +14 -0
- package/claude-code/plugins/agent-wallet/AGENTLAYER_AGENT_GUIDE.md +282 -0
- package/claude-code/plugins/agent-wallet/README.md +134 -0
- package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-approve.md +39 -0
- package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-revoke.md +17 -0
- package/claude-code/plugins/agent-wallet/commands/cards.md +129 -0
- package/claude-code/plugins/agent-wallet/commands/guide.md +40 -0
- package/claude-code/plugins/agent-wallet/commands/imd.md +125 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-base.md +60 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-ethereum.md +37 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-evm.md +39 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-setup.md +25 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-sol.md +51 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-statusline.md +34 -0
- package/claude-code/plugins/agent-wallet/commands/x402.md +121 -0
- package/claude-code/plugins/agent-wallet/commands/yield.md +62 -0
- package/claude-code/plugins/agent-wallet/hooks/hooks.json +16 -0
- package/claude-code/plugins/agent-wallet/scripts/bootstrap_backend.sh +136 -0
- package/claude-code/plugins/agent-wallet/scripts/enable_statusline.py +52 -0
- package/claude-code/plugins/agent-wallet/scripts/resolve_wallet_addresses.py +69 -0
- package/claude-code/plugins/agent-wallet/scripts/run_mcp.sh +66 -0
- package/claude-code/plugins/agent-wallet/scripts/wallet_statusline.py +130 -0
- package/claude-code/plugins/agent-wallet/scripts/wallet_statusline_setup.sh +40 -0
- package/claude-code/plugins/agent-wallet/skills/wallet-operator/SKILL.md +21 -0
- package/codex/plugins/agent-wallet/.codex-plugin/plugin.json +37 -0
- package/codex/plugins/agent-wallet/.mcp.json +15 -0
- package/codex/plugins/agent-wallet/README.md +158 -0
- package/codex/plugins/agent-wallet/scripts/run_mcp.sh +47 -0
- package/codex/plugins/agent-wallet/server.py +1797 -0
- package/codex/plugins/agent-wallet/skills/cards/SKILL.md +225 -0
- package/codex/plugins/agent-wallet/skills/imd/SKILL.md +145 -0
- package/codex/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
- package/codex/plugins/agent-wallet/skills/wallet-operator/SKILL.md +85 -0
- package/codex/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
- package/codex/plugins/agent-wallet/skills/x402/SKILL.md +159 -0
- package/codex/plugins/agent-wallet/skills/yield/SKILL.md +65 -0
- package/connectors/AGENTS.md +37 -0
- package/connectors/DEVELOPER_GUIDE.md +131 -0
- package/connectors/README.md +139 -0
- package/connectors/READ_ONLY_BETA.md +54 -0
- package/connectors/RELEASING.md +48 -0
- package/connectors/conformance/README.md +31 -0
- package/connectors/conformance/package.json +54 -0
- package/connectors/conformance/scripts/sync-license.mjs +3 -0
- package/connectors/conformance/scripts/sync-spec.mjs +16 -0
- package/connectors/conformance/src/cli.ts +43 -0
- package/connectors/conformance/src/index.ts +7 -0
- package/connectors/conformance/src/runner.ts +314 -0
- package/connectors/conformance/src/types.ts +27 -0
- package/connectors/conformance/test/fixtures/invalid-response-identity.json +14 -0
- package/connectors/conformance/test/fixtures/missing-tool-fixture.json +4 -0
- package/connectors/conformance/test/runner.test.mjs +151 -0
- package/connectors/conformance/tsconfig.json +17 -0
- package/connectors/examples/reference-crypto-data/Dockerfile +21 -0
- package/connectors/examples/reference-crypto-data/README.md +51 -0
- package/connectors/examples/reference-crypto-data/conformance.json +11 -0
- package/connectors/examples/reference-crypto-data/connector.json +95 -0
- package/connectors/examples/reference-crypto-data/package.json +21 -0
- package/connectors/examples/reference-crypto-data/railway.toml +9 -0
- package/connectors/examples/reference-crypto-data/src/connector.ts +137 -0
- package/connectors/examples/reference-crypto-data/src/server.ts +13 -0
- package/connectors/examples/reference-crypto-data/test/connector.test.mjs +97 -0
- package/connectors/examples/reference-crypto-data/tsconfig.json +17 -0
- package/connectors/package-lock.json +561 -0
- package/connectors/package.json +19 -0
- package/connectors/scripts/smoke-packed-packages.mjs +121 -0
- package/connectors/sdk-typescript/README.md +47 -0
- package/connectors/sdk-typescript/package.json +49 -0
- package/connectors/sdk-typescript/scripts/sync-license.mjs +3 -0
- package/connectors/sdk-typescript/src/connector.ts +204 -0
- package/connectors/sdk-typescript/src/errors.ts +11 -0
- package/connectors/sdk-typescript/src/http.ts +116 -0
- package/connectors/sdk-typescript/src/index.ts +26 -0
- package/connectors/sdk-typescript/src/types.ts +101 -0
- package/connectors/sdk-typescript/test/sdk.test.mjs +181 -0
- package/connectors/sdk-typescript/tsconfig.json +21 -0
- package/connectors/spec/connector-manifest.schema.json +340 -0
- package/connectors/spec/connector-protocol.md +159 -0
- package/connectors/spec/transaction-intent.schema.json +281 -0
- package/connectors/templates/read-only/.env.example +1 -0
- package/connectors/templates/read-only/Dockerfile +11 -0
- package/connectors/templates/read-only/README.md +33 -0
- package/connectors/templates/read-only/conformance.json +11 -0
- package/connectors/templates/read-only/connector.json +64 -0
- package/connectors/templates/read-only/package.json +21 -0
- package/connectors/templates/read-only/railway.toml +9 -0
- package/connectors/templates/read-only/src/connector.ts +61 -0
- package/connectors/templates/read-only/src/server.ts +14 -0
- package/connectors/templates/read-only/test/connector.test.mjs +62 -0
- package/connectors/templates/read-only/tsconfig.json +17 -0
- package/cursor/plugins/agent-wallet/.cursor-plugin/plugin.json +14 -0
- package/cursor/plugins/agent-wallet/README.md +62 -0
- package/cursor/plugins/agent-wallet/mcp.json +16 -0
- package/cursor/plugins/agent-wallet/scripts/run_mcp.sh +33 -0
- package/cursor/plugins/agent-wallet/server.py +33 -0
- package/cursor/plugins/agent-wallet/skills/cards/SKILL.md +210 -0
- package/cursor/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
- package/cursor/plugins/agent-wallet/skills/wallet-operator/SKILL.md +23 -0
- package/cursor/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
- package/cursor/plugins/agent-wallet/skills/x402/SKILL.md +130 -0
- package/hermes/plugins/agent_wallet/README.md +54 -0
- package/hermes/plugins/agent_wallet/__init__.py +55 -0
- package/hermes/plugins/agent_wallet/plugin.yaml +9 -0
- package/hermes/plugins/agent_wallet/schemas.py +211 -0
- package/hermes/plugins/agent_wallet/tools.py +622 -0
- package/install-from-github.sh +139 -0
- package/integrations/hedera/treasury-guard/README.md +92 -0
- package/integrations/hedera/treasury-guard/examples/treasury-policy.example.json +9 -0
- package/integrations/hedera/treasury-guard/package-lock.json +880 -0
- package/integrations/hedera/treasury-guard/package.json +8 -0
- package/integrations/hedera/treasury-guard/skills/onecraft-hedera-treasury/SKILL.md +22 -0
- package/integrations/hedera/treasury-guard/src/hedera-mirror-client.mjs +106 -0
- package/integrations/hedera/treasury-guard/src/hedera-signer.mjs +120 -0
- package/integrations/hedera/treasury-guard/src/treasury-cli.mjs +177 -0
- package/integrations/hedera/treasury-guard/src/treasury-policy.mjs +155 -0
- package/mcp/README.md +39 -0
- package/mcp/scripts/run_mcp.sh +37 -0
- package/mcp/server.py +33 -0
- package/package.json +106 -4
- package/scripts/check_release_version.mjs +72 -0
- package/scripts/version_targets.mjs +60 -0
- package/setup.sh +87 -0
- package/wdk-evm-wallet/.env.example +38 -0
- package/wdk-evm-wallet/README.md +254 -0
- package/wdk-evm-wallet/bootstrap.sh +8 -0
- package/wdk-evm-wallet/package-lock.json +2359 -0
- package/wdk-evm-wallet/package.json +43 -0
- package/wdk-evm-wallet/run-local.sh +12 -0
- package/wdk-evm-wallet/src/config.js +461 -0
- package/wdk-evm-wallet/src/imd.js +231 -0
- package/wdk-evm-wallet/src/json.js +35 -0
- package/wdk-evm-wallet/src/local_vault.js +407 -0
- package/wdk-evm-wallet/src/network_state.js +96 -0
- package/wdk-evm-wallet/src/pending_transactions.js +148 -0
- package/wdk-evm-wallet/src/server.js +849 -0
- package/wdk-evm-wallet/src/shutdown.js +63 -0
- package/wdk-evm-wallet/src/wdk_evm_wallet.js +10036 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Backend-only card use capsules; never return their values through agent tools.
|
|
2
|
+
|
|
3
|
+
Unlike owner sealed boxes, these capsules are decryptable by the wallet runtime.
|
|
4
|
+
They enable authorized executors without owner Keychain authentication per use.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import hashlib
|
|
10
|
+
import hmac
|
|
11
|
+
import json
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from nacl.exceptions import CryptoError
|
|
15
|
+
from nacl.secret import SecretBox
|
|
16
|
+
|
|
17
|
+
from agent_wallet.card_vault import CardVault
|
|
18
|
+
from agent_wallet.config import resolve_wallet_master_key
|
|
19
|
+
from agent_wallet.file_ops import atomic_write_text
|
|
20
|
+
from agent_wallet.wallet_layer.base import WalletBackendError
|
|
21
|
+
|
|
22
|
+
MAX_RUNTIME_BYTES = 128 * 1024
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RuntimeVaultStorage:
|
|
26
|
+
"""Purpose-separated encrypted state within one existing user card vault."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, vault: CardVault, purpose: str):
|
|
29
|
+
if purpose not in {"use", "operation", "browser", "browser_identity"}:
|
|
30
|
+
raise WalletBackendError("Unsupported runtime vault purpose.")
|
|
31
|
+
self.vault, self.purpose = vault, purpose
|
|
32
|
+
|
|
33
|
+
def path(self, reference: str):
|
|
34
|
+
return self.vault._path(reference).with_suffix("." + self.purpose)
|
|
35
|
+
|
|
36
|
+
def _key(self) -> bytes:
|
|
37
|
+
master = resolve_wallet_master_key()
|
|
38
|
+
if not master:
|
|
39
|
+
raise WalletBackendError("The sealed wallet runtime key is required for private card use.")
|
|
40
|
+
return hmac.new(master.encode(), b"agentlayer-vault-runtime-v1\0" + self.purpose.encode() + b"\0" + self.vault.scope.encode(), hashlib.sha256).digest()
|
|
41
|
+
|
|
42
|
+
def save(self, reference: str, state: dict[str, Any]) -> None:
|
|
43
|
+
self.vault._config()
|
|
44
|
+
value = {"scope": self.vault.scope, "reference": reference, "purpose": self.purpose, "state": state}
|
|
45
|
+
plaintext = json.dumps(value, allow_nan=False).encode()
|
|
46
|
+
if len(plaintext) > MAX_RUNTIME_BYTES:
|
|
47
|
+
raise WalletBackendError("Runtime vault state exceeds size limit.")
|
|
48
|
+
box = bytes(SecretBox(self._key()).encrypt(plaintext))
|
|
49
|
+
atomic_write_text(self.path(reference), json.dumps({"version": 1, "box": base64.b64encode(box).decode()}))
|
|
50
|
+
self.vault._sync_directory()
|
|
51
|
+
|
|
52
|
+
def load(self, reference: str) -> dict[str, Any]:
|
|
53
|
+
self.vault._config()
|
|
54
|
+
try:
|
|
55
|
+
envelope = self.vault._read(self.path(reference))
|
|
56
|
+
if envelope["version"] != 1:
|
|
57
|
+
raise ValueError()
|
|
58
|
+
plaintext = SecretBox(self._key()).decrypt(base64.b64decode(envelope["box"], validate=True))
|
|
59
|
+
if len(plaintext) > MAX_RUNTIME_BYTES:
|
|
60
|
+
raise ValueError()
|
|
61
|
+
value = json.loads(plaintext)
|
|
62
|
+
if (value["scope"] != self.vault.scope or value["reference"] != reference
|
|
63
|
+
or value["purpose"] != self.purpose or not isinstance(value["state"], dict)):
|
|
64
|
+
raise ValueError()
|
|
65
|
+
return value["state"]
|
|
66
|
+
except (CryptoError, ValueError, KeyError, TypeError):
|
|
67
|
+
raise WalletBackendError("Runtime vault state authentication failed.") from None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class CardRuntimeSecrets:
|
|
71
|
+
def __init__(self, vault: CardVault):
|
|
72
|
+
self.vault = vault
|
|
73
|
+
self.storage = RuntimeVaultStorage(vault, "use")
|
|
74
|
+
|
|
75
|
+
def capture(self, reference: str, record: dict[str, Any]) -> None:
|
|
76
|
+
from agent_wallet.card_catalog import card_object, details_ready
|
|
77
|
+
|
|
78
|
+
if not details_ready(record):
|
|
79
|
+
return
|
|
80
|
+
details = card_object(record.get("latest") or record.get("order") or {})["card_details"]
|
|
81
|
+
fields = {
|
|
82
|
+
"card.number": details["card_number"],
|
|
83
|
+
"card.cvv": details["cvv"],
|
|
84
|
+
"card.exp_month": f'{int(details["exp_month"]):02d}',
|
|
85
|
+
"card.exp_year": str(int(details["exp_year"])),
|
|
86
|
+
}
|
|
87
|
+
address = details.get("billing_address")
|
|
88
|
+
if isinstance(address, dict):
|
|
89
|
+
for name in ("name", "line_1", "line_2", "city", "state", "zip", "country"):
|
|
90
|
+
value = address.get(name)
|
|
91
|
+
if isinstance(value, str) and len(value) <= 512:
|
|
92
|
+
fields["card.billing." + name] = value
|
|
93
|
+
self.storage.save(reference, {"fields": fields})
|
|
94
|
+
|
|
95
|
+
def available(self, reference: str) -> bool:
|
|
96
|
+
self.vault._config()
|
|
97
|
+
self.vault._read(self.vault._path(reference))
|
|
98
|
+
path = self.storage.path(reference)
|
|
99
|
+
return path.exists() or path.is_symlink()
|
|
100
|
+
|
|
101
|
+
def load_for_executor(self, reference: str) -> dict[str, str]:
|
|
102
|
+
# Call only inside an authorized executor, never as an agent-facing read.
|
|
103
|
+
self.vault._read(self.vault._path(reference))
|
|
104
|
+
state = self.storage.load(reference)
|
|
105
|
+
fields = state.get("fields")
|
|
106
|
+
if not isinstance(fields, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in fields.items()):
|
|
107
|
+
raise WalletBackendError("Invalid runtime card capsule.")
|
|
108
|
+
return fields
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""Local encrypted card records with owner authentication through macOS Keychain.
|
|
2
|
+
|
|
3
|
+
Legacy password-wrapped keys remain readable solely for explicit migration.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import base64
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import stat
|
|
14
|
+
import uuid
|
|
15
|
+
import time
|
|
16
|
+
from contextlib import asynccontextmanager, contextmanager
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from nacl import exceptions, pwhash, secret, utils
|
|
21
|
+
from nacl.public import PrivateKey, PublicKey, SealedBox
|
|
22
|
+
|
|
23
|
+
from agent_wallet.config import resolve_openclaw_home
|
|
24
|
+
from agent_wallet.file_ops import atomic_write_text
|
|
25
|
+
from agent_wallet.wallet_layer.base import WalletBackendError
|
|
26
|
+
|
|
27
|
+
KIND = "agentlayer-card-vault"
|
|
28
|
+
VERSION = 1
|
|
29
|
+
SYSTEM_VERSION = 2
|
|
30
|
+
MAX_BYTES = 2 * 1024 * 1024
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _file_locks():
|
|
34
|
+
# Unsupported card custody must not prevent the rest of the wallet backend
|
|
35
|
+
# (including Windows DPAPI startup) from importing. Never fall back to an
|
|
36
|
+
# unlocked vault operation on platforms without these locks.
|
|
37
|
+
try:
|
|
38
|
+
import fcntl
|
|
39
|
+
except ImportError:
|
|
40
|
+
raise WalletBackendError("Card vault operations require macOS or Linux file locking.") from None
|
|
41
|
+
return fcntl
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _b64(value: bytes) -> str:
|
|
45
|
+
return base64.b64encode(value).decode("ascii")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _unb64(value: str) -> bytes:
|
|
49
|
+
return base64.b64decode(value, validate=True)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class CardVault:
|
|
53
|
+
def __init__(self, user_id: str, *, home: Path | None = None):
|
|
54
|
+
if not isinstance(user_id, str) or not user_id.strip():
|
|
55
|
+
raise WalletBackendError("Card vault requires an explicit runtime user ID.")
|
|
56
|
+
self.scope = hashlib.sha256(user_id.encode()).hexdigest()
|
|
57
|
+
self.root = (home or resolve_openclaw_home()) / "card-vault" / self.scope
|
|
58
|
+
self.config_path = self.root / "vault.json"
|
|
59
|
+
|
|
60
|
+
def _read(self, path: Path) -> dict[str, Any]:
|
|
61
|
+
try:
|
|
62
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
|
63
|
+
with os.fdopen(fd, "r", encoding="utf-8") as handle:
|
|
64
|
+
info = os.fstat(handle.fileno())
|
|
65
|
+
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077 or info.st_uid != os.getuid():
|
|
66
|
+
raise ValueError("unsafe file")
|
|
67
|
+
if info.st_size > MAX_BYTES:
|
|
68
|
+
raise ValueError("oversized file")
|
|
69
|
+
value = json.load(handle)
|
|
70
|
+
if not isinstance(value, dict):
|
|
71
|
+
raise ValueError("invalid object")
|
|
72
|
+
return value
|
|
73
|
+
except (OSError, ValueError, TypeError):
|
|
74
|
+
raise WalletBackendError("Card vault file is missing, unsafe, or invalid.") from None
|
|
75
|
+
|
|
76
|
+
def _check_directory(self) -> None:
|
|
77
|
+
try:
|
|
78
|
+
info = self.root.lstat()
|
|
79
|
+
if not stat.S_ISDIR(info.st_mode) or info.st_mode & 0o077 or info.st_uid != os.getuid():
|
|
80
|
+
raise ValueError()
|
|
81
|
+
except (OSError, ValueError):
|
|
82
|
+
raise WalletBackendError("Vault directory must be owned by you with mode 0700.") from None
|
|
83
|
+
|
|
84
|
+
def _sync_directory(self) -> None:
|
|
85
|
+
fd = os.open(self.root, os.O_RDONLY | os.O_NOFOLLOW)
|
|
86
|
+
try:
|
|
87
|
+
os.fsync(fd)
|
|
88
|
+
finally:
|
|
89
|
+
os.close(fd)
|
|
90
|
+
|
|
91
|
+
@contextmanager
|
|
92
|
+
def record_lock(self, reference: str):
|
|
93
|
+
fcntl = _file_locks()
|
|
94
|
+
path = self._path(reference).with_suffix(".lock")
|
|
95
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
96
|
+
try:
|
|
97
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
98
|
+
yield
|
|
99
|
+
finally:
|
|
100
|
+
os.close(fd)
|
|
101
|
+
|
|
102
|
+
@asynccontextmanager
|
|
103
|
+
async def async_record_lock(self, reference: str):
|
|
104
|
+
fcntl = _file_locks()
|
|
105
|
+
path = self._path(reference).with_suffix(".lock")
|
|
106
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
107
|
+
deadline = time.monotonic() + 5
|
|
108
|
+
try:
|
|
109
|
+
while True:
|
|
110
|
+
try:
|
|
111
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
112
|
+
break
|
|
113
|
+
except BlockingIOError:
|
|
114
|
+
if time.monotonic() >= deadline:
|
|
115
|
+
raise WalletBackendError("A card update is already in progress. Check its status again shortly.") from None
|
|
116
|
+
await asyncio.sleep(0.1)
|
|
117
|
+
yield
|
|
118
|
+
finally:
|
|
119
|
+
os.close(fd)
|
|
120
|
+
|
|
121
|
+
def _config(self) -> dict[str, Any]:
|
|
122
|
+
self._check_directory()
|
|
123
|
+
config = self._read(self.config_path)
|
|
124
|
+
try:
|
|
125
|
+
if config["kind"] != KIND or config["version"] not in {VERSION, SYSTEM_VERSION} or config["scope"] != self.scope:
|
|
126
|
+
raise ValueError()
|
|
127
|
+
PublicKey(_unb64(config["public_key"]))
|
|
128
|
+
if config["version"] == VERSION:
|
|
129
|
+
# Fixed cost for reading legacy password-protected vaults.
|
|
130
|
+
if config["kdf"] != "argon2id-interactive":
|
|
131
|
+
raise ValueError()
|
|
132
|
+
else:
|
|
133
|
+
from agent_wallet.card_vault_keychain import PROTECTION
|
|
134
|
+
if config["protection"] != PROTECTION or not re.fullmatch(r"[a-f0-9]{32}", config["key_id"]):
|
|
135
|
+
raise ValueError()
|
|
136
|
+
if any(key in config for key in ("private_key", "salt", "kdf")):
|
|
137
|
+
raise ValueError()
|
|
138
|
+
except (KeyError, ValueError, TypeError):
|
|
139
|
+
raise WalletBackendError("Unsupported or invalid card vault configuration.") from None
|
|
140
|
+
return config
|
|
141
|
+
|
|
142
|
+
def check_ready(self) -> None:
|
|
143
|
+
config = self._config()
|
|
144
|
+
if config["version"] == SYSTEM_VERSION:
|
|
145
|
+
self._system_store().check(self._key_account(config))
|
|
146
|
+
# Test durable encrypted writes before an order can spend money.
|
|
147
|
+
probe = self.deposit({"type": "preflight"})
|
|
148
|
+
self._path(probe).unlink()
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def _wrap_key(private_key: PrivateKey, password: str) -> dict[str, str]:
|
|
152
|
+
if len(password) < 12:
|
|
153
|
+
raise WalletBackendError("Use a vault password of at least 12 characters.")
|
|
154
|
+
salt = utils.random(pwhash.argon2id.SALTBYTES)
|
|
155
|
+
key = pwhash.argon2id.kdf(
|
|
156
|
+
secret.SecretBox.KEY_SIZE, password.encode(), salt,
|
|
157
|
+
opslimit=pwhash.argon2id.OPSLIMIT_INTERACTIVE,
|
|
158
|
+
memlimit=pwhash.argon2id.MEMLIMIT_INTERACTIVE,
|
|
159
|
+
)
|
|
160
|
+
return {"salt": _b64(salt), "private_key": _b64(bytes(secret.SecretBox(key).encrypt(bytes(private_key))))}
|
|
161
|
+
|
|
162
|
+
def initialize(self, password: str) -> None:
|
|
163
|
+
private_key = PrivateKey.generate()
|
|
164
|
+
config = {
|
|
165
|
+
"kind": KIND, "version": VERSION, "scope": self.scope,
|
|
166
|
+
"public_key": _b64(bytes(private_key.public_key)),
|
|
167
|
+
"kdf": "argon2id-interactive", **self._wrap_key(private_key, password),
|
|
168
|
+
}
|
|
169
|
+
self.root.mkdir(parents=True, mode=0o700, exist_ok=True)
|
|
170
|
+
self._check_directory()
|
|
171
|
+
# Publish a complete key file atomically, without replacing any existing key.
|
|
172
|
+
temporary = self.root / f".init-{uuid.uuid4().hex}"
|
|
173
|
+
try:
|
|
174
|
+
atomic_write_text(temporary, json.dumps(config))
|
|
175
|
+
os.link(temporary, self.config_path, follow_symlinks=False)
|
|
176
|
+
self._sync_directory()
|
|
177
|
+
finally:
|
|
178
|
+
temporary.unlink(missing_ok=True)
|
|
179
|
+
|
|
180
|
+
def _system_store(self):
|
|
181
|
+
from agent_wallet.card_vault_keychain import MacCardKeychain
|
|
182
|
+
return MacCardKeychain(self.root)
|
|
183
|
+
|
|
184
|
+
def _key_account(self, config: dict[str, Any]) -> str:
|
|
185
|
+
return f"{self.scope}:{config['key_id']}"
|
|
186
|
+
|
|
187
|
+
def _system_config(self, private_key: PrivateKey) -> dict[str, Any]:
|
|
188
|
+
from agent_wallet.card_vault_keychain import PROTECTION
|
|
189
|
+
return {
|
|
190
|
+
"kind": KIND, "version": SYSTEM_VERSION, "scope": self.scope,
|
|
191
|
+
"public_key": _b64(bytes(private_key.public_key)),
|
|
192
|
+
"protection": PROTECTION, "key_id": uuid.uuid4().hex,
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
@contextmanager
|
|
196
|
+
def owner_lock(self):
|
|
197
|
+
fcntl = _file_locks()
|
|
198
|
+
self.root.mkdir(parents=True, mode=0o700, exist_ok=True)
|
|
199
|
+
self._check_directory()
|
|
200
|
+
fd = os.open(self.root / ".owner.lock", os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
201
|
+
try:
|
|
202
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
203
|
+
yield
|
|
204
|
+
finally:
|
|
205
|
+
os.close(fd)
|
|
206
|
+
|
|
207
|
+
def ensure_system(self) -> dict[str, Any]:
|
|
208
|
+
"""Idempotent install/update provisioning; never reads a private key or shows UI."""
|
|
209
|
+
with self.owner_lock():
|
|
210
|
+
if self.config_path.exists() or self.config_path.is_symlink():
|
|
211
|
+
config = self._config()
|
|
212
|
+
if config["version"] == VERSION:
|
|
213
|
+
return {"status": "migration_required", "created": False}
|
|
214
|
+
self._system_store().check(self._key_account(config))
|
|
215
|
+
return {"status": "ready", "created": False}
|
|
216
|
+
# Never create a different recipient for existing encrypted records.
|
|
217
|
+
if any(self.root.glob("*.card")):
|
|
218
|
+
raise WalletBackendError("Card vault key metadata is missing. Restore it from backup; existing cards were not replaced.")
|
|
219
|
+
private_key = PrivateKey.generate()
|
|
220
|
+
config = self._system_config(private_key)
|
|
221
|
+
self._system_store().create(self._key_account(config), bytes(private_key))
|
|
222
|
+
atomic_write_text(self.config_path, json.dumps(config))
|
|
223
|
+
self._sync_directory()
|
|
224
|
+
return {"status": "ready", "created": True}
|
|
225
|
+
|
|
226
|
+
def migrate_to_system(self, password: str) -> PrivateKey:
|
|
227
|
+
"""Preserve the existing recipient; replace only its key-protection mechanism."""
|
|
228
|
+
with self.owner_lock():
|
|
229
|
+
if self._config()["version"] == SYSTEM_VERSION:
|
|
230
|
+
return self.unlock()
|
|
231
|
+
private_key = self.unlock(password)
|
|
232
|
+
config = self._system_config(private_key)
|
|
233
|
+
store = self._system_store()
|
|
234
|
+
account = self._key_account(config)
|
|
235
|
+
store.create(account, bytes(private_key))
|
|
236
|
+
# Explicit owner authentication proves recovery before removing the old wrapper.
|
|
237
|
+
if store.get(account) != bytes(private_key):
|
|
238
|
+
raise WalletBackendError("System vault key verification failed. Existing password protection is preserved.")
|
|
239
|
+
atomic_write_text(self.config_path, json.dumps(config))
|
|
240
|
+
self._sync_directory()
|
|
241
|
+
return private_key
|
|
242
|
+
|
|
243
|
+
def unlock(self, password: str | None = None) -> PrivateKey:
|
|
244
|
+
config = self._config()
|
|
245
|
+
if config["version"] == SYSTEM_VERSION:
|
|
246
|
+
private = PrivateKey(self._system_store().get(self._key_account(config)))
|
|
247
|
+
if bytes(private.public_key) != _unb64(config["public_key"]):
|
|
248
|
+
raise WalletBackendError("macOS Keychain key does not match this card vault.")
|
|
249
|
+
return private
|
|
250
|
+
if password is None:
|
|
251
|
+
raise WalletBackendError("This legacy vault needs one-time migration: wallet vault migrate.")
|
|
252
|
+
try:
|
|
253
|
+
key = pwhash.argon2id.kdf(
|
|
254
|
+
secret.SecretBox.KEY_SIZE, password.encode(), _unb64(config["salt"]),
|
|
255
|
+
opslimit=pwhash.argon2id.OPSLIMIT_INTERACTIVE,
|
|
256
|
+
memlimit=pwhash.argon2id.MEMLIMIT_INTERACTIVE,
|
|
257
|
+
)
|
|
258
|
+
private = PrivateKey(secret.SecretBox(key).decrypt(_unb64(config["private_key"])))
|
|
259
|
+
if bytes(private.public_key) != _unb64(config["public_key"]):
|
|
260
|
+
raise ValueError()
|
|
261
|
+
return private
|
|
262
|
+
except (exceptions.CryptoError, ValueError, KeyError, TypeError):
|
|
263
|
+
raise WalletBackendError("Incorrect vault password or damaged vault key.") from None
|
|
264
|
+
|
|
265
|
+
def _path(self, reference: str) -> Path:
|
|
266
|
+
if not isinstance(reference, str) or not re.fullmatch(r"[a-f0-9]{32}", reference):
|
|
267
|
+
raise WalletBackendError("Invalid vault reference.")
|
|
268
|
+
return self.root / f"{reference}.card"
|
|
269
|
+
|
|
270
|
+
def _seal(self, reference: str, payload: dict[str, Any], *, part: str) -> None:
|
|
271
|
+
config = self._config()
|
|
272
|
+
path = self._path(reference) if part == "record" else self._path(reference).with_suffix("." + part)
|
|
273
|
+
plaintext = json.dumps({"scope": self.scope, "reference": reference, "part": part, "payload": payload})
|
|
274
|
+
if len(plaintext.encode()) > MAX_BYTES // 2:
|
|
275
|
+
raise WalletBackendError("Card vault record exceeds size limit.")
|
|
276
|
+
ciphertext = SealedBox(PublicKey(_unb64(config["public_key"]))).encrypt(plaintext.encode())
|
|
277
|
+
atomic_write_text(path, json.dumps({"version": VERSION, "sealed": _b64(ciphertext)}))
|
|
278
|
+
self._sync_directory()
|
|
279
|
+
|
|
280
|
+
def deposit(self, payload: dict[str, Any], *, reference: str | None = None) -> str:
|
|
281
|
+
reference = reference or uuid.uuid4().hex
|
|
282
|
+
self._seal(reference, payload, part="record")
|
|
283
|
+
return reference
|
|
284
|
+
|
|
285
|
+
def store_update(self, reference: str, *, latest: dict[str, Any] | None = None, auth: dict[str, str]) -> None:
|
|
286
|
+
if not self._path(reference).is_file():
|
|
287
|
+
raise WalletBackendError("Saved card record was not found for this user.")
|
|
288
|
+
# Keep auth separate so token rotation cannot erase already saved details.
|
|
289
|
+
self._seal(reference, {"auth": auth}, part="auth")
|
|
290
|
+
if latest is not None:
|
|
291
|
+
self._seal(reference, {"latest": latest}, part="update")
|
|
292
|
+
|
|
293
|
+
def _decrypt_part(self, reference: str, private_key: PrivateKey, *, part: str) -> dict[str, Any]:
|
|
294
|
+
path = self._path(reference) if part == "record" else self._path(reference).with_suffix("." + part)
|
|
295
|
+
envelope = self._read(path)
|
|
296
|
+
try:
|
|
297
|
+
if envelope["version"] != VERSION:
|
|
298
|
+
raise ValueError()
|
|
299
|
+
value = json.loads(SealedBox(private_key).decrypt(_unb64(envelope["sealed"])))
|
|
300
|
+
if value["scope"] != self.scope or value["reference"] != reference or value.get("part", "record") != part:
|
|
301
|
+
raise ValueError()
|
|
302
|
+
if not isinstance(value["payload"], dict):
|
|
303
|
+
raise ValueError()
|
|
304
|
+
return value["payload"]
|
|
305
|
+
except (exceptions.CryptoError, ValueError, KeyError, TypeError):
|
|
306
|
+
raise WalletBackendError("Card vault record failed authentication.") from None
|
|
307
|
+
|
|
308
|
+
def read(self, reference: str, private_key: PrivateKey) -> dict[str, Any]:
|
|
309
|
+
record = self._decrypt_part(reference, private_key, part="record")
|
|
310
|
+
for part in ("update", "auth"):
|
|
311
|
+
path = self._path(reference).with_suffix("." + part)
|
|
312
|
+
if path.exists() or path.is_symlink():
|
|
313
|
+
update = self._decrypt_part(reference, private_key, part=part)
|
|
314
|
+
if isinstance(update.get("latest"), dict):
|
|
315
|
+
record["latest"] = update["latest"]
|
|
316
|
+
if isinstance(update.get("auth"), dict):
|
|
317
|
+
record.setdefault("order", {})["auth"] = update["auth"]
|
|
318
|
+
return record
|
|
319
|
+
|
|
320
|
+
def remove_record(self, reference: str) -> None:
|
|
321
|
+
# Call under record_lock. Revoke the local pending capability first.
|
|
322
|
+
self._path(reference).with_suffix(".use").unlink(missing_ok=True)
|
|
323
|
+
self._path(reference).with_suffix(".agent").unlink(missing_ok=True)
|
|
324
|
+
self._path(reference).with_suffix(".update").unlink(missing_ok=True)
|
|
325
|
+
self._path(reference).with_suffix(".auth").unlink(missing_ok=True)
|
|
326
|
+
self._path(reference).unlink()
|
|
327
|
+
self._sync_directory()
|
|
328
|
+
|
|
329
|
+
def references(self) -> list[str]:
|
|
330
|
+
self._config()
|
|
331
|
+
return sorted(p.stem for p in self.root.glob("*.card") if re.fullmatch(r"[a-f0-9]{32}", p.stem))
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Human CLI for card retrieval. Secrets are never accepted as command arguments."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import asyncio
|
|
6
|
+
import getpass
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from agent_wallet.card_vault import CardVault, VERSION
|
|
13
|
+
from agent_wallet.card_catalog import CardCatalog
|
|
14
|
+
from agent_wallet.config import resolve_card_vault_user_id
|
|
15
|
+
from agent_wallet.laso_card_vault import card_object, refresh_record, summary
|
|
16
|
+
from agent_wallet.wallet_layer.base import WalletBackendError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def require_terminal() -> None:
|
|
20
|
+
# Terminal checks prevent accidental logging; macOS authenticates the owner.
|
|
21
|
+
if not sys.stdin.isatty() or not sys.stdout.isatty():
|
|
22
|
+
raise WalletBackendError("Run this command in your own interactive terminal; redirected secret output is disabled.")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def owner_summary(record: dict, reference: str) -> dict:
|
|
26
|
+
result = summary(record, reference)
|
|
27
|
+
card = card_object(record.get("latest") or record.get("order") or {})
|
|
28
|
+
result.update({
|
|
29
|
+
"card_id": card.get("card_id"),
|
|
30
|
+
"card_type": record.get("card_type"),
|
|
31
|
+
"created_at": record.get("created_at"),
|
|
32
|
+
"receipt_state": record.get("state"),
|
|
33
|
+
"http_status": record.get("http_status"),
|
|
34
|
+
})
|
|
35
|
+
payment = record.get("payment_result")
|
|
36
|
+
if isinstance(payment, dict):
|
|
37
|
+
result["payment"] = payment
|
|
38
|
+
return result
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def import_owner_record(vault: CardVault, reference: str, record: dict) -> None:
|
|
42
|
+
"""An authenticated owner can populate metadata/jobs for older vault records."""
|
|
43
|
+
from agent_wallet.card_runtime_secrets import CardRuntimeSecrets
|
|
44
|
+
|
|
45
|
+
catalog = CardCatalog(vault)
|
|
46
|
+
try:
|
|
47
|
+
CardRuntimeSecrets(vault).capture(reference, record)
|
|
48
|
+
except WalletBackendError:
|
|
49
|
+
pass
|
|
50
|
+
path = catalog._path(reference)
|
|
51
|
+
try:
|
|
52
|
+
if path.exists() or path.is_symlink():
|
|
53
|
+
catalog.load(reference)
|
|
54
|
+
return
|
|
55
|
+
except WalletBackendError:
|
|
56
|
+
pass
|
|
57
|
+
try:
|
|
58
|
+
catalog.track(reference, record)
|
|
59
|
+
except WalletBackendError:
|
|
60
|
+
# An unavailable runtime master must not prevent owner-only reveal.
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def main(argv: list[str] | None = None) -> int:
|
|
65
|
+
parser = argparse.ArgumentParser(prog="wallet vault")
|
|
66
|
+
parser.add_argument("command", choices=["kernel-connect", "kernel-status", "kernel-disconnect", "import", "provision", "init", "migrate", "status", "list", "show", "reveal", "refresh", "remove", "change-password"])
|
|
67
|
+
parser.add_argument("reference", nargs="?")
|
|
68
|
+
parser.add_argument("--user-id", default=None)
|
|
69
|
+
parser.add_argument("--output", type=Path, help="Explicitly export card details to a NEW private JSON file (reveal only).")
|
|
70
|
+
parser.add_argument("--card-type", choices=["us", "international"], default=None, help="Imported card type (import only, default us).")
|
|
71
|
+
args = parser.parse_args(argv)
|
|
72
|
+
try:
|
|
73
|
+
if args.card_type is not None and args.command != "import":
|
|
74
|
+
raise WalletBackendError("--card-type is only valid with import.")
|
|
75
|
+
if args.command.startswith("kernel-"):
|
|
76
|
+
if args.reference or args.output or args.user_id:
|
|
77
|
+
raise WalletBackendError("Kernel connection is shared by the local runtime and accepts no card arguments.")
|
|
78
|
+
from agent_wallet.kernel_cli import run
|
|
79
|
+
return run(args.command)
|
|
80
|
+
vault = CardVault(args.user_id or resolve_card_vault_user_id())
|
|
81
|
+
if args.output and args.command != "reveal":
|
|
82
|
+
raise WalletBackendError("--output is only valid with reveal.")
|
|
83
|
+
if args.command in {"show", "reveal", "refresh", "remove"} and not args.reference:
|
|
84
|
+
raise WalletBackendError("A vault reference is required.")
|
|
85
|
+
if args.command == "import":
|
|
86
|
+
if args.reference:
|
|
87
|
+
raise WalletBackendError("Import accepts no card credentials or reference as arguments.")
|
|
88
|
+
from agent_wallet.card_vault_import import import_interactive
|
|
89
|
+
card_type = "Non-Reloadable International" if args.card_type == "international" else "Non-Reloadable U.S."
|
|
90
|
+
print(json.dumps(import_interactive(vault, card_type), indent=2))
|
|
91
|
+
return 0
|
|
92
|
+
if args.command == "status":
|
|
93
|
+
config = vault._config() if vault.config_path.exists() else {}
|
|
94
|
+
print(json.dumps({"initialized": bool(config), "protection": config.get("protection", "legacy-password" if config else None), "scope": vault.scope, "path": str(vault.root)}))
|
|
95
|
+
return 0
|
|
96
|
+
if args.command in {"provision", "init"}:
|
|
97
|
+
result = vault.ensure_system()
|
|
98
|
+
print(json.dumps({"ok": True, **result}))
|
|
99
|
+
return 0
|
|
100
|
+
if args.command == "change-password":
|
|
101
|
+
raise WalletBackendError("The card vault uses your macOS login Keychain password. Manage it in system Keychain settings.")
|
|
102
|
+
require_terminal()
|
|
103
|
+
vault.ensure_system()
|
|
104
|
+
if vault._config()["version"] == VERSION:
|
|
105
|
+
password = getpass.getpass("Previous vault password (one-time migration): ")
|
|
106
|
+
private_key = vault.migrate_to_system(password)
|
|
107
|
+
del password
|
|
108
|
+
else:
|
|
109
|
+
private_key = vault.unlock()
|
|
110
|
+
if args.command == "migrate":
|
|
111
|
+
print("Card vault uses macOS login Keychain authentication.")
|
|
112
|
+
return 0
|
|
113
|
+
with vault.owner_lock():
|
|
114
|
+
if args.command == "list":
|
|
115
|
+
cards = []
|
|
116
|
+
for ref in vault.references():
|
|
117
|
+
with vault.record_lock(ref):
|
|
118
|
+
record = vault.read(ref, private_key)
|
|
119
|
+
import_owner_record(vault, ref, record)
|
|
120
|
+
cards.append(owner_summary(record, ref))
|
|
121
|
+
print(json.dumps(cards, indent=2))
|
|
122
|
+
return 0
|
|
123
|
+
record = vault.read(args.reference, private_key)
|
|
124
|
+
if args.command == "refresh":
|
|
125
|
+
with vault.record_lock(args.reference):
|
|
126
|
+
record = vault.read(args.reference, private_key)
|
|
127
|
+
record = asyncio.run(refresh_record(vault, args.reference, record))
|
|
128
|
+
if args.command == "remove":
|
|
129
|
+
if input(f"Type {args.reference} to remove the local encrypted record: ") != args.reference:
|
|
130
|
+
raise WalletBackendError("Removal cancelled.")
|
|
131
|
+
with vault.record_lock(args.reference):
|
|
132
|
+
vault.remove_record(args.reference)
|
|
133
|
+
print("Local record removed. The Laso card has not been cancelled.")
|
|
134
|
+
return 0
|
|
135
|
+
if args.command != "refresh":
|
|
136
|
+
with vault.record_lock(args.reference):
|
|
137
|
+
record = vault.read(args.reference, private_key)
|
|
138
|
+
import_owner_record(vault, args.reference, record)
|
|
139
|
+
result = owner_summary(record, args.reference)
|
|
140
|
+
if args.command == "reveal":
|
|
141
|
+
card = card_object(record.get("latest") or record.get("order") or {})
|
|
142
|
+
details = card.get("card_details")
|
|
143
|
+
if not isinstance(details, dict) or not details.get("card_number"):
|
|
144
|
+
raise WalletBackendError("Card details are not ready. Use wallet vault refresh <reference>.")
|
|
145
|
+
# Never reveal provider tokens, unexpected response fields, or payment credentials.
|
|
146
|
+
result = {"vault_reference": args.reference, "card_details": {k: details[k] for k in ("card_number", "exp_month", "exp_year", "cvv", "available_balance", "billing_address") if k in details}}
|
|
147
|
+
if args.output:
|
|
148
|
+
requested = args.output.expanduser().absolute()
|
|
149
|
+
destination = requested.parent.resolve() / requested.name
|
|
150
|
+
if destination.is_relative_to(vault.root.resolve()):
|
|
151
|
+
raise WalletBackendError("Export outside the encrypted vault directory.")
|
|
152
|
+
fd = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
|
153
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
154
|
+
json.dump(result, handle, indent=2)
|
|
155
|
+
handle.flush()
|
|
156
|
+
os.fsync(handle.fileno())
|
|
157
|
+
print("Card exported to a private plaintext JSON file. Remove it after use.")
|
|
158
|
+
return 0
|
|
159
|
+
print(json.dumps(result, indent=2))
|
|
160
|
+
return 0
|
|
161
|
+
except WalletBackendError as exc:
|
|
162
|
+
print(str(exc), file=sys.stderr)
|
|
163
|
+
return 1
|
|
164
|
+
except (OSError, ValueError):
|
|
165
|
+
# No traceback, provider body, password or token can enter shell logs.
|
|
166
|
+
print("Vault command failed. Check user ID, system Keychain access, record reference and file permissions. For pending cards, retry refresh later.", file=sys.stderr)
|
|
167
|
+
return 1
|
|
168
|
+
except (KeyboardInterrupt, EOFError):
|
|
169
|
+
print("Vault command cancelled.", file=sys.stderr)
|
|
170
|
+
return 1
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
if __name__ == "__main__":
|
|
174
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Owner-terminal import of existing cards; no card values in argv or output."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import getpass
|
|
5
|
+
import re
|
|
6
|
+
import uuid
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
|
|
9
|
+
from agent_wallet.card_catalog import CardCatalog, details_ready
|
|
10
|
+
from agent_wallet.card_runtime_secrets import RuntimeVaultStorage
|
|
11
|
+
from agent_wallet.card_vault import CardVault, SYSTEM_VERSION
|
|
12
|
+
from agent_wallet.wallet_layer.base import WalletBackendError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def import_interactive(vault: CardVault, card_type: str) -> dict:
|
|
16
|
+
from agent_wallet.card_vault_cli import require_terminal
|
|
17
|
+
|
|
18
|
+
require_terminal()
|
|
19
|
+
vault.ensure_system()
|
|
20
|
+
if vault._config()["version"] != SYSTEM_VERSION:
|
|
21
|
+
raise WalletBackendError("Migrate the owner vault before importing: wallet vault migrate")
|
|
22
|
+
catalog = CardCatalog(vault)
|
|
23
|
+
catalog.preflight()
|
|
24
|
+
RuntimeVaultStorage(vault, "use")._key()
|
|
25
|
+
# getpass must never fall back to echoed stdin, even with a broken terminal.
|
|
26
|
+
import warnings
|
|
27
|
+
with warnings.catch_warnings():
|
|
28
|
+
warnings.simplefilter("error", getpass.GetPassWarning)
|
|
29
|
+
try:
|
|
30
|
+
number = getpass.getpass("Card number (hidden): ")
|
|
31
|
+
expiry = getpass.getpass("Expiry MM/YY or MM/YYYY (hidden): ")
|
|
32
|
+
cvv = getpass.getpass("CVV (hidden): ")
|
|
33
|
+
except getpass.GetPassWarning:
|
|
34
|
+
raise WalletBackendError("Hidden terminal input is unavailable; import cancelled.") from None
|
|
35
|
+
number = re.sub(r"[ -]", "", number)
|
|
36
|
+
match = re.fullmatch(r"(0[1-9]|1[0-2])/([0-9]{2}|20[0-9]{2}|2100)", expiry.strip())
|
|
37
|
+
if not match:
|
|
38
|
+
raise WalletBackendError("Invalid expiry format; no card was imported.")
|
|
39
|
+
month, year = int(match[1]), int(match[2])
|
|
40
|
+
if year < 100:
|
|
41
|
+
year += 2000
|
|
42
|
+
details = {"card_number": number, "exp_month": str(month), "exp_year": str(year), "cvv": cvv.strip()}
|
|
43
|
+
now = datetime.now(timezone.utc)
|
|
44
|
+
record = {"type": "owner-imported-card", "source": "owner-terminal", "state": "imported",
|
|
45
|
+
"created_at": now.isoformat(), "card_type": card_type,
|
|
46
|
+
"order": {"status": "expired" if (year, month) < (now.year, now.month) else "ready", "card_details": details}}
|
|
47
|
+
if not details_ready(record):
|
|
48
|
+
raise WalletBackendError("Invalid card number, CVV or expiry; no card was imported.")
|
|
49
|
+
digits = [int(c) for c in number]
|
|
50
|
+
checksum = sum((d * 2 - 9 if d * 2 > 9 else d * 2) if i % 2 == len(digits) % 2 else d for i, d in enumerate(digits))
|
|
51
|
+
if checksum % 10:
|
|
52
|
+
raise WalletBackendError("Card number checksum is invalid; no card was imported.")
|
|
53
|
+
reference = uuid.uuid4().hex
|
|
54
|
+
try:
|
|
55
|
+
with vault.owner_lock(), vault.record_lock(reference):
|
|
56
|
+
vault.deposit(record, reference=reference)
|
|
57
|
+
try:
|
|
58
|
+
state = catalog.track(reference, record)
|
|
59
|
+
except Exception:
|
|
60
|
+
vault.remove_record(reference)
|
|
61
|
+
raise
|
|
62
|
+
return catalog.safe(reference, state)
|
|
63
|
+
finally:
|
|
64
|
+
details.clear()
|
|
65
|
+
number = expiry = cvv = "" # Best effort; Python cannot promise zeroization.
|