@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.
Files changed (248) hide show
  1. package/.claude-plugin/marketplace.json +20 -0
  2. package/.openclaw/AGENTS.md +100 -0
  3. package/.openclaw/extensions/agent-wallet/README.md +195 -0
  4. package/.openclaw/extensions/agent-wallet/dist/index.js +2198 -0
  5. package/.openclaw/extensions/agent-wallet/index.ts +2198 -0
  6. package/.openclaw/extensions/agent-wallet/openclaw.plugin.json +251 -0
  7. package/.openclaw/extensions/agent-wallet/package.json +49 -0
  8. package/.openclaw/extensions/agent-wallet/skills/cards/SKILL.md +211 -0
  9. package/.openclaw/extensions/agent-wallet/skills/wallet-operator/SKILL.md +30 -0
  10. package/CHANGELOG.md +1232 -0
  11. package/LICENSE +104 -0
  12. package/README.md +193 -2
  13. package/VERSION +1 -0
  14. package/agent-wallet/.env.example +63 -0
  15. package/agent-wallet/AGENTS.md +130 -0
  16. package/agent-wallet/CARD_VAULT.md +640 -0
  17. package/agent-wallet/README.md +615 -0
  18. package/agent-wallet/UPGRADE_COMPATIBILITY.md +66 -0
  19. package/agent-wallet/agent_wallet/__init__.py +16 -0
  20. package/agent-wallet/agent_wallet/approval.py +165 -0
  21. package/agent-wallet/agent_wallet/autonomous_permissions.py +281 -0
  22. package/agent-wallet/agent_wallet/autonomous_policy.py +305 -0
  23. package/agent-wallet/agent_wallet/autonomous_session.py +236 -0
  24. package/agent-wallet/agent_wallet/boot_key_migration.py +155 -0
  25. package/agent-wallet/agent_wallet/boot_key_recovery.py +57 -0
  26. package/agent-wallet/agent_wallet/bootstrap.py +194 -0
  27. package/agent-wallet/agent_wallet/card_catalog.py +243 -0
  28. package/agent-wallet/agent_wallet/card_runtime_secrets.py +108 -0
  29. package/agent-wallet/agent_wallet/card_vault.py +331 -0
  30. package/agent-wallet/agent_wallet/card_vault_cli.py +174 -0
  31. package/agent-wallet/agent_wallet/card_vault_import.py +65 -0
  32. package/agent-wallet/agent_wallet/card_vault_keychain.py +239 -0
  33. package/agent-wallet/agent_wallet/config.py +719 -0
  34. package/agent-wallet/agent_wallet/connector_cli.py +198 -0
  35. package/agent-wallet/agent_wallet/connectors/__init__.py +28 -0
  36. package/agent-wallet/agent_wallet/connectors/catalog.py +68 -0
  37. package/agent-wallet/agent_wallet/connectors/client.py +308 -0
  38. package/agent-wallet/agent_wallet/connectors/intent_policy.py +243 -0
  39. package/agent-wallet/agent_wallet/connectors/manifest.py +192 -0
  40. package/agent-wallet/agent_wallet/connectors/registry.py +341 -0
  41. package/agent-wallet/agent_wallet/encrypted_storage.py +314 -0
  42. package/agent-wallet/agent_wallet/evm_user_wallets.py +910 -0
  43. package/agent-wallet/agent_wallet/exceptions.py +10 -0
  44. package/agent-wallet/agent_wallet/file_ops.py +34 -0
  45. package/agent-wallet/agent_wallet/http_client.py +25 -0
  46. package/agent-wallet/agent_wallet/kernel_browser.py +479 -0
  47. package/agent-wallet/agent_wallet/kernel_cli.py +57 -0
  48. package/agent-wallet/agent_wallet/kernel_gateway.py +95 -0
  49. package/agent-wallet/agent_wallet/keystore.py +503 -0
  50. package/agent-wallet/agent_wallet/laso_card_vault.py +246 -0
  51. package/agent-wallet/agent_wallet/models.py +66 -0
  52. package/agent-wallet/agent_wallet/morpho_monitor.py +298 -0
  53. package/agent-wallet/agent_wallet/nonce_registry.py +59 -0
  54. package/agent-wallet/agent_wallet/openclaw_adapter.py +9129 -0
  55. package/agent-wallet/agent_wallet/openclaw_cli.py +658 -0
  56. package/agent-wallet/agent_wallet/openclaw_runtime.py +194 -0
  57. package/agent-wallet/agent_wallet/plugin_bundle.py +44 -0
  58. package/agent-wallet/agent_wallet/providers/__init__.py +1 -0
  59. package/agent-wallet/agent_wallet/providers/bags.py +202 -0
  60. package/agent-wallet/agent_wallet/providers/dexscreener.py +147 -0
  61. package/agent-wallet/agent_wallet/providers/evm_activity.py +257 -0
  62. package/agent-wallet/agent_wallet/providers/evm_portfolio.py +459 -0
  63. package/agent-wallet/agent_wallet/providers/imd.py +720 -0
  64. package/agent-wallet/agent_wallet/providers/jupiter.py +519 -0
  65. package/agent-wallet/agent_wallet/providers/kamino.py +404 -0
  66. package/agent-wallet/agent_wallet/providers/lifi.py +302 -0
  67. package/agent-wallet/agent_wallet/providers/solana_rpc.py +447 -0
  68. package/agent-wallet/agent_wallet/providers/tokenized_stocks.py +189 -0
  69. package/agent-wallet/agent_wallet/providers/wdk_evm_local.py +346 -0
  70. package/agent-wallet/agent_wallet/providers/x402.py +1972 -0
  71. package/agent-wallet/agent_wallet/sealed_keys.py +118 -0
  72. package/agent-wallet/agent_wallet/solana_stake.py +103 -0
  73. package/agent-wallet/agent_wallet/solana_tx.py +93 -0
  74. package/agent-wallet/agent_wallet/spending_limits.py +119 -0
  75. package/agent-wallet/agent_wallet/telemetry.py +481 -0
  76. package/agent-wallet/agent_wallet/transaction_policy.py +573 -0
  77. package/agent-wallet/agent_wallet/update_check.py +190 -0
  78. package/agent-wallet/agent_wallet/user_wallets.py +573 -0
  79. package/agent-wallet/agent_wallet/validation.py +31 -0
  80. package/agent-wallet/agent_wallet/vault_executor.py +456 -0
  81. package/agent-wallet/agent_wallet/wallet_layer/__init__.py +1 -0
  82. package/agent-wallet/agent_wallet/wallet_layer/base.py +1204 -0
  83. package/agent-wallet/agent_wallet/wallet_layer/base58.py +44 -0
  84. package/agent-wallet/agent_wallet/wallet_layer/factory.py +117 -0
  85. package/agent-wallet/agent_wallet/wallet_layer/solana.py +5246 -0
  86. package/agent-wallet/agent_wallet/wallet_layer/wdk_evm.py +2705 -0
  87. package/agent-wallet/examples/bootstrap_wallet.py +21 -0
  88. package/agent-wallet/examples/openclaw_runtime_onboarding.py +28 -0
  89. package/agent-wallet/examples/openclaw_user_wallet_example.py +31 -0
  90. package/agent-wallet/examples/openclaw_wallet_adapter_example.py +33 -0
  91. package/agent-wallet/openclaw.plugin.json +118 -0
  92. package/agent-wallet/pyproject.toml +36 -0
  93. package/agent-wallet/scripts/bootstrap_openclaw_evm.py +312 -0
  94. package/agent-wallet/scripts/build_release_bundle.py +210 -0
  95. package/agent-wallet/scripts/finalize_openclaw_local_wallet_config.py +121 -0
  96. package/agent-wallet/scripts/install_agent_wallet.py +1357 -0
  97. package/agent-wallet/scripts/install_openclaw_local_config.py +421 -0
  98. package/agent-wallet/scripts/install_openclaw_sealed_keys.py +117 -0
  99. package/agent-wallet/scripts/manage_openclaw_evm_wallet.py +333 -0
  100. package/agent-wallet/scripts/security_utils.py +37 -0
  101. package/agent-wallet/scripts/setup_evm_wallet.sh +140 -0
  102. package/agent-wallet/scripts/switch_openclaw_wallet_network.py +109 -0
  103. package/agent-wallet/skills/wallet-operator/SKILL.md +157 -0
  104. package/bin/lib/boot-key.mjs +184 -0
  105. package/bin/lib/evm-daemon.mjs +389 -0
  106. package/bin/lib/host-detection.mjs +259 -0
  107. package/bin/lib/integrations.mjs +578 -0
  108. package/bin/lib/release-python.mjs +9 -0
  109. package/bin/lib/update-transaction.mjs +235 -0
  110. package/bin/openclaw-agent-wallet.mjs +3354 -0
  111. package/claude-code/plugins/agent-wallet/.claude-plugin/plugin.json +19 -0
  112. package/claude-code/plugins/agent-wallet/.mcp.json +14 -0
  113. package/claude-code/plugins/agent-wallet/AGENTLAYER_AGENT_GUIDE.md +282 -0
  114. package/claude-code/plugins/agent-wallet/README.md +134 -0
  115. package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-approve.md +39 -0
  116. package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-revoke.md +17 -0
  117. package/claude-code/plugins/agent-wallet/commands/cards.md +129 -0
  118. package/claude-code/plugins/agent-wallet/commands/guide.md +40 -0
  119. package/claude-code/plugins/agent-wallet/commands/imd.md +125 -0
  120. package/claude-code/plugins/agent-wallet/commands/wallet-base.md +60 -0
  121. package/claude-code/plugins/agent-wallet/commands/wallet-ethereum.md +37 -0
  122. package/claude-code/plugins/agent-wallet/commands/wallet-evm.md +39 -0
  123. package/claude-code/plugins/agent-wallet/commands/wallet-setup.md +25 -0
  124. package/claude-code/plugins/agent-wallet/commands/wallet-sol.md +51 -0
  125. package/claude-code/plugins/agent-wallet/commands/wallet-statusline.md +34 -0
  126. package/claude-code/plugins/agent-wallet/commands/x402.md +121 -0
  127. package/claude-code/plugins/agent-wallet/commands/yield.md +62 -0
  128. package/claude-code/plugins/agent-wallet/hooks/hooks.json +16 -0
  129. package/claude-code/plugins/agent-wallet/scripts/bootstrap_backend.sh +136 -0
  130. package/claude-code/plugins/agent-wallet/scripts/enable_statusline.py +52 -0
  131. package/claude-code/plugins/agent-wallet/scripts/resolve_wallet_addresses.py +69 -0
  132. package/claude-code/plugins/agent-wallet/scripts/run_mcp.sh +66 -0
  133. package/claude-code/plugins/agent-wallet/scripts/wallet_statusline.py +130 -0
  134. package/claude-code/plugins/agent-wallet/scripts/wallet_statusline_setup.sh +40 -0
  135. package/claude-code/plugins/agent-wallet/skills/wallet-operator/SKILL.md +21 -0
  136. package/codex/plugins/agent-wallet/.codex-plugin/plugin.json +37 -0
  137. package/codex/plugins/agent-wallet/.mcp.json +15 -0
  138. package/codex/plugins/agent-wallet/README.md +158 -0
  139. package/codex/plugins/agent-wallet/scripts/run_mcp.sh +47 -0
  140. package/codex/plugins/agent-wallet/server.py +1797 -0
  141. package/codex/plugins/agent-wallet/skills/cards/SKILL.md +225 -0
  142. package/codex/plugins/agent-wallet/skills/imd/SKILL.md +145 -0
  143. package/codex/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
  144. package/codex/plugins/agent-wallet/skills/wallet-operator/SKILL.md +85 -0
  145. package/codex/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
  146. package/codex/plugins/agent-wallet/skills/x402/SKILL.md +159 -0
  147. package/codex/plugins/agent-wallet/skills/yield/SKILL.md +65 -0
  148. package/connectors/AGENTS.md +37 -0
  149. package/connectors/DEVELOPER_GUIDE.md +131 -0
  150. package/connectors/README.md +139 -0
  151. package/connectors/READ_ONLY_BETA.md +54 -0
  152. package/connectors/RELEASING.md +48 -0
  153. package/connectors/conformance/README.md +31 -0
  154. package/connectors/conformance/package.json +54 -0
  155. package/connectors/conformance/scripts/sync-license.mjs +3 -0
  156. package/connectors/conformance/scripts/sync-spec.mjs +16 -0
  157. package/connectors/conformance/src/cli.ts +43 -0
  158. package/connectors/conformance/src/index.ts +7 -0
  159. package/connectors/conformance/src/runner.ts +314 -0
  160. package/connectors/conformance/src/types.ts +27 -0
  161. package/connectors/conformance/test/fixtures/invalid-response-identity.json +14 -0
  162. package/connectors/conformance/test/fixtures/missing-tool-fixture.json +4 -0
  163. package/connectors/conformance/test/runner.test.mjs +151 -0
  164. package/connectors/conformance/tsconfig.json +17 -0
  165. package/connectors/examples/reference-crypto-data/Dockerfile +21 -0
  166. package/connectors/examples/reference-crypto-data/README.md +51 -0
  167. package/connectors/examples/reference-crypto-data/conformance.json +11 -0
  168. package/connectors/examples/reference-crypto-data/connector.json +95 -0
  169. package/connectors/examples/reference-crypto-data/package.json +21 -0
  170. package/connectors/examples/reference-crypto-data/railway.toml +9 -0
  171. package/connectors/examples/reference-crypto-data/src/connector.ts +137 -0
  172. package/connectors/examples/reference-crypto-data/src/server.ts +13 -0
  173. package/connectors/examples/reference-crypto-data/test/connector.test.mjs +97 -0
  174. package/connectors/examples/reference-crypto-data/tsconfig.json +17 -0
  175. package/connectors/package-lock.json +561 -0
  176. package/connectors/package.json +19 -0
  177. package/connectors/scripts/smoke-packed-packages.mjs +121 -0
  178. package/connectors/sdk-typescript/README.md +47 -0
  179. package/connectors/sdk-typescript/package.json +49 -0
  180. package/connectors/sdk-typescript/scripts/sync-license.mjs +3 -0
  181. package/connectors/sdk-typescript/src/connector.ts +204 -0
  182. package/connectors/sdk-typescript/src/errors.ts +11 -0
  183. package/connectors/sdk-typescript/src/http.ts +116 -0
  184. package/connectors/sdk-typescript/src/index.ts +26 -0
  185. package/connectors/sdk-typescript/src/types.ts +101 -0
  186. package/connectors/sdk-typescript/test/sdk.test.mjs +181 -0
  187. package/connectors/sdk-typescript/tsconfig.json +21 -0
  188. package/connectors/spec/connector-manifest.schema.json +340 -0
  189. package/connectors/spec/connector-protocol.md +159 -0
  190. package/connectors/spec/transaction-intent.schema.json +281 -0
  191. package/connectors/templates/read-only/.env.example +1 -0
  192. package/connectors/templates/read-only/Dockerfile +11 -0
  193. package/connectors/templates/read-only/README.md +33 -0
  194. package/connectors/templates/read-only/conformance.json +11 -0
  195. package/connectors/templates/read-only/connector.json +64 -0
  196. package/connectors/templates/read-only/package.json +21 -0
  197. package/connectors/templates/read-only/railway.toml +9 -0
  198. package/connectors/templates/read-only/src/connector.ts +61 -0
  199. package/connectors/templates/read-only/src/server.ts +14 -0
  200. package/connectors/templates/read-only/test/connector.test.mjs +62 -0
  201. package/connectors/templates/read-only/tsconfig.json +17 -0
  202. package/cursor/plugins/agent-wallet/.cursor-plugin/plugin.json +14 -0
  203. package/cursor/plugins/agent-wallet/README.md +62 -0
  204. package/cursor/plugins/agent-wallet/mcp.json +16 -0
  205. package/cursor/plugins/agent-wallet/scripts/run_mcp.sh +33 -0
  206. package/cursor/plugins/agent-wallet/server.py +33 -0
  207. package/cursor/plugins/agent-wallet/skills/cards/SKILL.md +210 -0
  208. package/cursor/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
  209. package/cursor/plugins/agent-wallet/skills/wallet-operator/SKILL.md +23 -0
  210. package/cursor/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
  211. package/cursor/plugins/agent-wallet/skills/x402/SKILL.md +130 -0
  212. package/hermes/plugins/agent_wallet/README.md +54 -0
  213. package/hermes/plugins/agent_wallet/__init__.py +55 -0
  214. package/hermes/plugins/agent_wallet/plugin.yaml +9 -0
  215. package/hermes/plugins/agent_wallet/schemas.py +211 -0
  216. package/hermes/plugins/agent_wallet/tools.py +622 -0
  217. package/install-from-github.sh +139 -0
  218. package/integrations/hedera/treasury-guard/README.md +92 -0
  219. package/integrations/hedera/treasury-guard/examples/treasury-policy.example.json +9 -0
  220. package/integrations/hedera/treasury-guard/package-lock.json +880 -0
  221. package/integrations/hedera/treasury-guard/package.json +8 -0
  222. package/integrations/hedera/treasury-guard/skills/onecraft-hedera-treasury/SKILL.md +22 -0
  223. package/integrations/hedera/treasury-guard/src/hedera-mirror-client.mjs +106 -0
  224. package/integrations/hedera/treasury-guard/src/hedera-signer.mjs +120 -0
  225. package/integrations/hedera/treasury-guard/src/treasury-cli.mjs +177 -0
  226. package/integrations/hedera/treasury-guard/src/treasury-policy.mjs +155 -0
  227. package/mcp/README.md +39 -0
  228. package/mcp/scripts/run_mcp.sh +37 -0
  229. package/mcp/server.py +33 -0
  230. package/package.json +106 -4
  231. package/scripts/check_release_version.mjs +72 -0
  232. package/scripts/version_targets.mjs +60 -0
  233. package/setup.sh +87 -0
  234. package/wdk-evm-wallet/.env.example +38 -0
  235. package/wdk-evm-wallet/README.md +254 -0
  236. package/wdk-evm-wallet/bootstrap.sh +8 -0
  237. package/wdk-evm-wallet/package-lock.json +2359 -0
  238. package/wdk-evm-wallet/package.json +43 -0
  239. package/wdk-evm-wallet/run-local.sh +12 -0
  240. package/wdk-evm-wallet/src/config.js +461 -0
  241. package/wdk-evm-wallet/src/imd.js +231 -0
  242. package/wdk-evm-wallet/src/json.js +35 -0
  243. package/wdk-evm-wallet/src/local_vault.js +407 -0
  244. package/wdk-evm-wallet/src/network_state.js +96 -0
  245. package/wdk-evm-wallet/src/pending_transactions.js +148 -0
  246. package/wdk-evm-wallet/src/server.js +849 -0
  247. package/wdk-evm-wallet/src/shutdown.js +63 -0
  248. package/wdk-evm-wallet/src/wdk_evm_wallet.js +10036 -0
@@ -0,0 +1,95 @@
1
+ """Shared browser provisioning only. Card values and browser code bypass this API."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import re
7
+ import time
8
+ import uuid
9
+ from urllib.parse import urlsplit
10
+
11
+ import httpx
12
+ from nacl.signing import SigningKey
13
+
14
+ from agent_wallet.card_runtime_secrets import RuntimeVaultStorage
15
+ from agent_wallet.config import resolve_kernel_gateway_url
16
+ from agent_wallet.wallet_layer.base import WalletBackendError
17
+
18
+ PROTOCOL = "agentlayer-kernel-v1"
19
+ CREATE_PATH = "/v1/kernel/browser-sessions"
20
+ IDENTITY_REFERENCE = "00000000000000000000000000000001"
21
+
22
+
23
+ class KernelGateway:
24
+ def __init__(self, vault, url=None):
25
+ self.vault = vault
26
+ self.url = resolve_kernel_gateway_url()
27
+ # Saved URLs cannot redirect signed requests to a different origin after
28
+ # a config change. Keep the old lease inaccessible until config is restored;
29
+ # server cleanup remains authoritative even after the client disappears.
30
+ if url is not None and url != self.url:
31
+ raise WalletBackendError("Restore the original provider gateway setting to close this shared browser. Server expiry still applies.")
32
+ self.identity = RuntimeVaultStorage(vault, "browser_identity")
33
+
34
+ async def _headers(self, method, path, body):
35
+ async with self.vault.async_record_lock(IDENTITY_REFERENCE):
36
+ target = self.identity.path(IDENTITY_REFERENCE)
37
+ if target.exists() or target.is_symlink():
38
+ state = self.identity.load(IDENTITY_REFERENCE)
39
+ try:
40
+ key = SigningKey(bytes.fromhex(state["signing_key"]))
41
+ except (ValueError, KeyError, TypeError):
42
+ raise WalletBackendError("Shared browser installation identity is invalid; it was not replaced.") from None
43
+ else:
44
+ key = SigningKey.generate()
45
+ self.identity.save(IDENTITY_REFERENCE, {"signing_key": bytes(key).hex()})
46
+ timestamp, nonce = str(int(time.time())), uuid.uuid4().hex
47
+ signed_path = urlsplit(self.url).path.rstrip("/") + path
48
+ message = "\n".join((PROTOCOL, method, signed_path, timestamp, nonce, hashlib.sha256(body).hexdigest())).encode()
49
+ return {"X-AgentLayer-Client-Key": bytes(key.verify_key).hex(),
50
+ "X-AgentLayer-Timestamp": timestamp, "X-AgentLayer-Nonce": nonce,
51
+ "X-AgentLayer-Signature": key.sign(message).signature.hex(),
52
+ "Content-Type": "application/json"}
53
+
54
+ async def _request(self, method, path, data=None):
55
+ body = json.dumps(data, separators=(",", ":")).encode() if data is not None else b""
56
+ headers = await self._headers(method, path, body) if method == "POST" else {}
57
+ try:
58
+ async with httpx.AsyncClient(timeout=75, trust_env=False, follow_redirects=False) as client:
59
+ async with client.stream(method, self.url + path, headers=headers, content=body) as response:
60
+ if response.status_code == 429:
61
+ raise WalletBackendError("Shared browser quota reached. Try again later; no checkout was started.")
62
+ if not 200 <= response.status_code < 300:
63
+ raise WalletBackendError("Shared browser service is unavailable. Your vault and saved payment operations are unchanged.")
64
+ raw = bytearray()
65
+ async for chunk in response.aiter_bytes():
66
+ raw.extend(chunk)
67
+ if len(raw) > 32 * 1024:
68
+ raise ValueError()
69
+ result = json.loads(raw)
70
+ if not isinstance(result, dict):
71
+ raise ValueError()
72
+ return result
73
+ except WalletBackendError:
74
+ raise
75
+ except Exception:
76
+ # Never surface a response/exception that may contain a scoped key.
77
+ raise WalletBackendError("Shared browser request did not complete. Saved cleanup will use the same lease; no automatic allocation retry.") from None
78
+
79
+ async def allocate(self, lease):
80
+ capabilities = await self._request("GET", "/v1/kernel/capabilities")
81
+ if capabilities.get("protocol") != PROTOCOL or capabilities.get("available") is not True:
82
+ raise WalletBackendError("Shared browser service is not enabled yet. Existing personal Kernel connections remain available.")
83
+ data = await self._request("POST", CREATE_PATH, {"lease_id": lease})
84
+ session, key, expires = data.get("session_id"), data.get("session_key"), data.get("expires_at")
85
+ if (data.get("protocol") != PROTOCOL or data.get("lease_id") != lease
86
+ or not isinstance(session, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,256}", session)
87
+ or not isinstance(key, str) or not 16 <= len(key) <= 8192
88
+ or any(ord(c) < 33 or ord(c) > 126 for c in key)
89
+ or type(expires) is not int or not time.time() < expires <= time.time() + 1830):
90
+ raise WalletBackendError("Invalid shared browser allocation; the lease will be closed.")
91
+ return {"session_id": session, "session_key": key, "lease_expires_at": expires}
92
+
93
+ async def close(self, lease):
94
+ result = await self._request("POST", CREATE_PATH + "/" + lease + "/close", {})
95
+ return result.get("closed") is True and result.get("cleanup_pending") is False
@@ -0,0 +1,503 @@
1
+ """Cross-platform, dependency-free secret storage for the wallet boot key.
2
+
3
+ Backends shell out to tools already present on each desktop OS:
4
+ - macOS: /usr/bin/security (generic password in the login keychain)
5
+ - Windows: powershell DPAPI (ConvertFrom/ConvertTo-SecureString), per-user+machine
6
+ - Linux: secret-tool (libsecret) iff a Secret Service is reachable
7
+ - fallback: a 0600 plaintext file (current behavior) — never chosen over a
8
+ working keystore.
9
+
10
+ The store holds ONE install-level secret (the boot key). See
11
+ BOOT_KEY_KEYCHAIN_ARCHITECTURE.md.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import platform
20
+ import shutil
21
+ import subprocess
22
+ from pathlib import Path
23
+ from typing import Protocol, runtime_checkable
24
+
25
+ from agent_wallet.config import resolve_openclaw_home
26
+ from agent_wallet.file_ops import atomic_write_text, chmod_if_exists
27
+
28
+ KEYSTORE_SERVICE = "ai.agentlayer.wallet"
29
+ BOOT_KEY_ITEM = "boot_key"
30
+ _PROBE_ITEM = "__probe__"
31
+ _KEYSTORE_BACKEND_ENV = "AGENT_WALLET_KEYSTORE_BACKEND"
32
+ _KEYSTORE_STATE_VERSION = 1
33
+ _KEYSTORE_STATE_FILENAME = "backend.json"
34
+
35
+ _SECURITY_BIN = "/usr/bin/security"
36
+ _SUBPROCESS_TIMEOUT = 10.0
37
+
38
+
39
+ def _service() -> str:
40
+ """Return the keystore namespace for the active wallet home.
41
+
42
+ Desktop keystores are global to the OS account, while ``OPENCLAW_HOME`` can
43
+ point at an isolated test or secondary installation. Keep the historical
44
+ service for the default home, but derive a stable namespace for every other
45
+ home so one installation cannot replace another installation's boot key.
46
+ Tests can still choose a readable throwaway namespace explicitly.
47
+ """
48
+ explicit = os.getenv("AGENT_WALLET_KEYSTORE_SERVICE", "").strip()
49
+ if explicit:
50
+ return explicit
51
+ home = resolve_openclaw_home().expanduser().resolve()
52
+ default_home = (_account_home() / ".openclaw").resolve()
53
+ if home == default_home:
54
+ return KEYSTORE_SERVICE
55
+ home_hash = hashlib.sha256(str(home).encode("utf-8")).hexdigest()[:16]
56
+ return f"{KEYSTORE_SERVICE}.home-{home_hash}"
57
+
58
+
59
+ def _account_home() -> Path:
60
+ """Return the OS account home without trusting a test-overridden ``HOME``."""
61
+ if os.name == "nt":
62
+ user_profile = os.getenv("USERPROFILE", "").strip()
63
+ if user_profile:
64
+ return Path(user_profile)
65
+ drive = os.getenv("HOMEDRIVE", "").strip()
66
+ home_path = os.getenv("HOMEPATH", "").strip()
67
+ if drive and home_path:
68
+ return Path(f"{drive}{home_path}")
69
+ try:
70
+ import pwd
71
+
72
+ return Path(pwd.getpwuid(os.getuid()).pw_dir)
73
+ except (ImportError, KeyError, OSError):
74
+ return Path.home()
75
+
76
+
77
+ def _legacy_unscoped_service() -> str | None:
78
+ """Return the pre-home-scoping service for safe compatibility reads."""
79
+ if os.getenv("AGENT_WALLET_KEYSTORE_SERVICE", "").strip():
80
+ return None
81
+ if _service() == KEYSTORE_SERVICE:
82
+ return None
83
+ state = _read_backend_state_payload()
84
+ if state and state["service"] == KEYSTORE_SERVICE:
85
+ return KEYSTORE_SERVICE
86
+ return None
87
+
88
+
89
+ def _backend_preference() -> str:
90
+ """Selected keystore backend.
91
+
92
+ auto (default) prefers the native OS keystore (macOS Keychain / Windows DPAPI /
93
+ Linux Secret Service) and falls back to a 0600 plaintext file. macOS Keychain
94
+ is prompt-free because set() writes with `-A` (open ACL, no partition-list).
95
+ Override with AGENT_WALLET_KEYSTORE_BACKEND=plaintext|macos-keychain|native|...
96
+ """
97
+ return os.getenv(_KEYSTORE_BACKEND_ENV, "auto").strip().lower()
98
+
99
+
100
+ def _state_path() -> Path:
101
+ return resolve_openclaw_home() / "keystore" / _KEYSTORE_STATE_FILENAME
102
+
103
+
104
+ def _read_backend_state_payload() -> dict[str, str] | None:
105
+ try:
106
+ payload = json.loads(_state_path().read_text(encoding="utf-8"))
107
+ except (OSError, ValueError):
108
+ return None
109
+ if not isinstance(payload, dict) or payload.get("version") != _KEYSTORE_STATE_VERSION:
110
+ return None
111
+ backend = str(payload.get("backend") or "").strip()
112
+ service = str(payload.get("service") or "").strip()
113
+ if backend not in {
114
+ "macos-keychain",
115
+ "windows-dpapi",
116
+ "linux-secretservice",
117
+ "plaintext-file",
118
+ }:
119
+ return None
120
+ return {"backend": backend, "service": service}
121
+
122
+
123
+ def _read_backend_state() -> dict[str, str] | None:
124
+ payload = _read_backend_state_payload()
125
+ if payload is None:
126
+ return None
127
+ service = payload["service"]
128
+ if service != _service():
129
+ return None
130
+ return payload
131
+
132
+
133
+ class KeyStoreError(Exception):
134
+ """Raised when a keystore backend operation fails unexpectedly."""
135
+
136
+
137
+ @runtime_checkable
138
+ class KeyStore(Protocol):
139
+ backend_id: str
140
+
141
+ def available(self) -> bool: ...
142
+ def get(self, name: str) -> str | None: ...
143
+ def set(self, name: str, value: str) -> None: ...
144
+ def delete(self, name: str) -> None: ...
145
+
146
+
147
+ def _timeout_output(value: str | bytes | None) -> str:
148
+ if value is None:
149
+ return ""
150
+ if isinstance(value, bytes):
151
+ return value.decode(errors="replace")
152
+ return value
153
+
154
+
155
+ def _run(
156
+ argv: list[str],
157
+ *,
158
+ input_text: str | None = None,
159
+ timeout: float = _SUBPROCESS_TIMEOUT,
160
+ ) -> subprocess.CompletedProcess[str]:
161
+ kwargs: dict[str, object] = {
162
+ "capture_output": True,
163
+ "text": True,
164
+ "timeout": timeout,
165
+ "check": False,
166
+ }
167
+ if input_text is None:
168
+ kwargs["stdin"] = subprocess.DEVNULL
169
+ else:
170
+ kwargs["input"] = input_text
171
+ try:
172
+ return subprocess.run(argv, **kwargs)
173
+ except subprocess.TimeoutExpired as exc:
174
+ return subprocess.CompletedProcess(
175
+ argv,
176
+ 124,
177
+ _timeout_output(exc.stdout),
178
+ _timeout_output(exc.stderr) or f"timed out after {timeout:g}s",
179
+ )
180
+
181
+
182
+ class MacKeychainStore:
183
+ backend_id = "macos-keychain"
184
+
185
+ def __init__(self, service: str | None = None) -> None:
186
+ self.service = service or _service()
187
+
188
+ def available(self) -> bool:
189
+ return platform.system() == "Darwin" and Path(_SECURITY_BIN).exists()
190
+
191
+ def get(self, name: str) -> str | None:
192
+ proc = _run([_SECURITY_BIN, "find-generic-password", "-s", self.service, "-a", name, "-w"])
193
+ if proc.returncode != 0:
194
+ return None # item not found (44) or other non-fatal lookup miss
195
+ value = proc.stdout.rstrip("\n")
196
+ return value or None
197
+
198
+ def set(self, name: str, value: str) -> None:
199
+ # Recreate the item fresh with an open ACL. This is the ONLY reliably
200
+ # prompt-free way to write a login-keychain item non-interactively:
201
+ # -A -> accessible to any application without a prompt, and it
202
+ # bypasses the Sierra+ partition-list mechanism entirely.
203
+ # delete+add -> never -U-update an existing item; updating one created
204
+ # with a different ACL (or setting its partition list)
205
+ # pops a GUI keychain-password dialog in the background.
206
+ # Trade-off: any process running as this user can read the key without a
207
+ # prompt — the same runtime exposure as a 0600 file. At-rest protection
208
+ # (backups, synced home dirs, a stolen disk) is fully preserved.
209
+ _run([_SECURITY_BIN, "delete-generic-password", "-s", self.service, "-a", name])
210
+ proc = _run([
211
+ _SECURITY_BIN, "add-generic-password",
212
+ "-s", self.service, "-a", name,
213
+ "-w", value, "-A",
214
+ ])
215
+ if proc.returncode != 0:
216
+ raise KeyStoreError(f"security add-generic-password failed: {proc.stderr.strip()}")
217
+
218
+ def delete(self, name: str) -> None:
219
+ _run([_SECURITY_BIN, "delete-generic-password", "-s", self.service, "-a", name])
220
+
221
+
222
+ class WindowsDpapiStore:
223
+ backend_id = "windows-dpapi"
224
+
225
+ def _blob_path(self, name: str) -> Path:
226
+ return resolve_openclaw_home() / "keystore" / f"{name}.dpapi"
227
+
228
+ def available(self) -> bool:
229
+ return platform.system() == "Windows" and shutil.which("powershell") is not None
230
+
231
+ def get(self, name: str) -> str | None:
232
+ path = self._blob_path(name)
233
+ if not path.exists():
234
+ return None
235
+ blob = path.read_text(encoding="utf-8").strip()
236
+ if not blob:
237
+ return None
238
+ script = (
239
+ "$ErrorActionPreference='Stop';"
240
+ "$b=[Console]::In.ReadToEnd().Trim();"
241
+ "$ss=ConvertTo-SecureString $b;"
242
+ "$p=[Runtime.InteropServices.Marshal]::PtrToStringUni("
243
+ "[Runtime.InteropServices.Marshal]::SecureStringToBSTR($ss));"
244
+ "[Console]::Out.Write($p)"
245
+ )
246
+ proc = _run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script], input_text=blob)
247
+ if proc.returncode != 0:
248
+ return None
249
+ return proc.stdout or None
250
+
251
+ def set(self, name: str, value: str) -> None:
252
+ script = (
253
+ "$ErrorActionPreference='Stop';"
254
+ "$v=[Console]::In.ReadToEnd();"
255
+ "$ss=ConvertTo-SecureString $v -AsPlainText -Force;"
256
+ "[Console]::Out.Write((ConvertFrom-SecureString $ss))"
257
+ )
258
+ proc = _run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script], input_text=value)
259
+ if proc.returncode != 0 or not proc.stdout.strip():
260
+ raise KeyStoreError(f"DPAPI ConvertFrom-SecureString failed: {proc.stderr.strip()}")
261
+ atomic_write_text(self._blob_path(name), proc.stdout.strip() + "\n", mode=0o600)
262
+
263
+ def delete(self, name: str) -> None:
264
+ path = self._blob_path(name)
265
+ try:
266
+ path.unlink()
267
+ except FileNotFoundError:
268
+ pass
269
+
270
+
271
+ class LinuxSecretServiceStore:
272
+ backend_id = "linux-secretservice"
273
+
274
+ def __init__(self, service: str | None = None) -> None:
275
+ self.service = service or _service()
276
+
277
+ def available(self) -> bool:
278
+ if platform.system() != "Linux" or shutil.which("secret-tool") is None:
279
+ return False
280
+ # A probe lookup succeeds (rc 0/1) only when a Secret Service answers;
281
+ # a missing/unreachable service errors out (rc >1) or times out.
282
+ try:
283
+ proc = _run(["secret-tool", "lookup", "service", self.service, "account", "__probe__"])
284
+ except subprocess.TimeoutExpired:
285
+ return False
286
+ return proc.returncode in (0, 1)
287
+
288
+ def get(self, name: str) -> str | None:
289
+ proc = _run(["secret-tool", "lookup", "service", self.service, "account", name])
290
+ if proc.returncode != 0:
291
+ return None
292
+ value = proc.stdout.rstrip("\n")
293
+ return value or None
294
+
295
+ def set(self, name: str, value: str) -> None:
296
+ proc = _run(
297
+ ["secret-tool", "store", "--label", f"{self.service} {name}",
298
+ "service", self.service, "account", name],
299
+ input_text=value,
300
+ )
301
+ if proc.returncode != 0:
302
+ raise KeyStoreError(f"secret-tool store failed: {proc.stderr.strip()}")
303
+
304
+ def delete(self, name: str) -> None:
305
+ _run(["secret-tool", "clear", "service", self.service, "account", name])
306
+
307
+
308
+ class PlaintextFileStore:
309
+ """Fallback: a 0600 file under OPENCLAW_HOME/keystore. Always available."""
310
+
311
+ backend_id = "plaintext-file"
312
+
313
+ def _path(self, name: str) -> Path:
314
+ return resolve_openclaw_home() / "keystore" / f"{name}.plaintext"
315
+
316
+ def available(self) -> bool:
317
+ return True
318
+
319
+ def get(self, name: str) -> str | None:
320
+ path = self._path(name)
321
+ if not path.exists():
322
+ return None
323
+ chmod_if_exists(path)
324
+ value = path.read_text(encoding="utf-8").strip()
325
+ return value or None
326
+
327
+ def set(self, name: str, value: str) -> None:
328
+ atomic_write_text(self._path(name), value.strip() + "\n", mode=0o600)
329
+
330
+ def delete(self, name: str) -> None:
331
+ try:
332
+ self._path(name).unlink()
333
+ except FileNotFoundError:
334
+ pass
335
+
336
+
337
+ _keystore_cache: dict[tuple[str, str, str], KeyStore] = {}
338
+
339
+
340
+ def clear_keystore_cache() -> None:
341
+ """Drop the memoized keystore backend (e.g. after env/service changes)."""
342
+ _keystore_cache.clear()
343
+
344
+
345
+ def resolve_keystore() -> KeyStore:
346
+ """Memoized keystore resolution.
347
+
348
+ Resolving probes the OS keystore with subprocess calls (`security`,
349
+ `secret-tool`, powershell), so cache the winning backend per
350
+ (preference, service) for the process lifetime. Cleared by
351
+ ``agent_wallet.config.clear_secret_caches`` / ``reload_settings``.
352
+ """
353
+ cache_key = (
354
+ _backend_preference(),
355
+ _service(),
356
+ str(resolve_openclaw_home().resolve()),
357
+ )
358
+ cached = _keystore_cache.get(cache_key)
359
+ if cached is not None:
360
+ return cached
361
+ store = _resolve_keystore_uncached()
362
+ _keystore_cache[cache_key] = store
363
+ return store
364
+
365
+
366
+ def _resolve_keystore_uncached() -> KeyStore:
367
+ """Return the first available OS-native backend, else the plaintext fallback."""
368
+ preference = _backend_preference()
369
+ if preference in {"plain", "plaintext", "plaintext-file", "file"}:
370
+ return PlaintextFileStore()
371
+
372
+ candidates: list[KeyStore]
373
+ if preference in {"macos", "macos-keychain", "keychain"}:
374
+ candidates = [MacKeychainStore()]
375
+ elif preference in {"windows", "windows-dpapi", "dpapi"}:
376
+ candidates = [WindowsDpapiStore()]
377
+ elif preference in {"linux", "linux-secretservice", "secretservice"}:
378
+ candidates = [LinuxSecretServiceStore()]
379
+ elif preference == "native":
380
+ candidates = [MacKeychainStore(), WindowsDpapiStore(), LinuxSecretServiceStore()]
381
+ else:
382
+ # Auto: native OS keystore first, plaintext fallback last. macOS Keychain
383
+ # is prompt-free now that set() uses `-A` (open ACL, no partition-list) and
384
+ # _backend_usable falls back gracefully if a session still can't authorize.
385
+ candidates = [MacKeychainStore(), WindowsDpapiStore(), LinuxSecretServiceStore()]
386
+
387
+ if preference == "auto":
388
+ state = _read_backend_state()
389
+ pinned = _store_for_backend(state["backend"]) if state else None
390
+ if pinned is not None:
391
+ candidates = [pinned, *[item for item in candidates if item.backend_id != pinned.backend_id]]
392
+
393
+ for candidate in candidates:
394
+ try:
395
+ if candidate.available() and _backend_usable(candidate):
396
+ return candidate
397
+ except Exception:
398
+ continue
399
+ return PlaintextFileStore()
400
+
401
+
402
+ def _store_for_backend(backend_id: str, *, service: str | None = None) -> KeyStore | None:
403
+ stores: dict[str, KeyStore] = {
404
+ "macos-keychain": MacKeychainStore(service),
405
+ "windows-dpapi": WindowsDpapiStore(),
406
+ "linux-secretservice": LinuxSecretServiceStore(service),
407
+ "plaintext-file": PlaintextFileStore(),
408
+ }
409
+ return stores.get(backend_id)
410
+
411
+
412
+ def read_legacy_unscoped_boot_key() -> str:
413
+ """Read the historical global service without probing or writing it.
414
+
415
+ This is used only as a compatibility candidate for an existing sealed
416
+ custom-home installation. The caller must verify the value against that
417
+ home's ``sealed_keys.json`` before accepting or migrating it.
418
+ """
419
+ legacy_service = _legacy_unscoped_service()
420
+ preference = _backend_preference()
421
+ if not legacy_service or preference in {"plain", "plaintext", "plaintext-file", "file"}:
422
+ return ""
423
+
424
+ if preference in {"macos", "macos-keychain", "keychain"}:
425
+ candidates: list[KeyStore] = [MacKeychainStore(legacy_service)]
426
+ elif preference in {"linux", "linux-secretservice", "secretservice"}:
427
+ candidates = [LinuxSecretServiceStore(legacy_service)]
428
+ elif preference in {"windows", "windows-dpapi", "dpapi"}:
429
+ candidates = []
430
+ else:
431
+ candidates = [
432
+ MacKeychainStore(legacy_service),
433
+ LinuxSecretServiceStore(legacy_service),
434
+ ]
435
+
436
+ for candidate in candidates:
437
+ try:
438
+ if not candidate.available():
439
+ continue
440
+ value = candidate.get(BOOT_KEY_ITEM)
441
+ if isinstance(value, str) and value.strip():
442
+ return value.strip()
443
+ except Exception:
444
+ continue
445
+ return ""
446
+
447
+
448
+ def record_keystore_backend(store: KeyStore) -> dict[str, object]:
449
+ """Persist a verified boot-key backend without replacing a temporary fallback."""
450
+ existing = _read_backend_state()
451
+ preference = _backend_preference()
452
+ if preference == "auto" and existing and existing["backend"] != store.backend_id:
453
+ return {
454
+ "recorded": False,
455
+ "backend": existing["backend"],
456
+ "fallback_backend": store.backend_id,
457
+ }
458
+ payload = {
459
+ "version": _KEYSTORE_STATE_VERSION,
460
+ "backend": store.backend_id,
461
+ "service": _service(),
462
+ }
463
+ atomic_write_text(_state_path(), json.dumps(payload, indent=2) + "\n", mode=0o600)
464
+ return {"recorded": True, "backend": store.backend_id, "fallback_backend": None}
465
+
466
+
467
+ def keystore_backend_status() -> dict[str, object]:
468
+ """Return non-secret diagnostics for the selected and persisted backend."""
469
+ state = _read_backend_state()
470
+ selected = resolve_keystore().backend_id
471
+ pinned = state["backend"] if state else None
472
+ return {
473
+ "selected": selected,
474
+ "pinned": pinned,
475
+ "fallback_active": bool(pinned and selected != pinned),
476
+ "preference": _backend_preference(),
477
+ }
478
+
479
+
480
+ def _backend_usable(candidate: KeyStore) -> bool:
481
+ """Return true when a native backend can read the live key or write safely.
482
+
483
+ A desktop keystore binary can exist while the session cannot authorize
484
+ non-interactive writes. Treat that as unavailable so install/migration uses
485
+ the bounded fallback instead of hanging or repeatedly failing.
486
+ """
487
+ try:
488
+ if candidate.get(BOOT_KEY_ITEM):
489
+ return True
490
+ except Exception:
491
+ pass
492
+
493
+ probe_value = "ok"
494
+ try:
495
+ candidate.set(_PROBE_ITEM, probe_value)
496
+ return candidate.get(_PROBE_ITEM) == probe_value
497
+ except Exception:
498
+ return False
499
+ finally:
500
+ try:
501
+ candidate.delete(_PROBE_ITEM)
502
+ except Exception:
503
+ pass