@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,155 @@
1
+ """Transparent, verified migration of the boot key into the OS keystore.
2
+
3
+ Runs at backend startup. Non-destructive: plaintext is swept ONLY after the
4
+ keystore read-back verifies. Idempotent and best-effort — a partial sweep
5
+ re-runs cleanly next start. See BOOT_KEY_KEYCHAIN_ARCHITECTURE.md.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from pathlib import Path
12
+
13
+ from agent_wallet.config import (
14
+ read_boot_key_from_keystore,
15
+ resolve_boot_key,
16
+ resolve_openclaw_home,
17
+ )
18
+ from agent_wallet.file_ops import atomic_write_text
19
+ from agent_wallet.keystore import (
20
+ BOOT_KEY_ITEM,
21
+ PlaintextFileStore,
22
+ record_keystore_backend,
23
+ resolve_keystore,
24
+ )
25
+
26
+ _ENV_LINE_PREFIX = "AGENT_WALLET_BOOT_KEY="
27
+
28
+
29
+ def _env_boot_key_value(line: str) -> str | None:
30
+ """Return the boot-key value on an AGENT_WALLET_BOOT_KEY= line, else None."""
31
+ stripped = line.strip()
32
+ if not stripped.startswith(_ENV_LINE_PREFIX):
33
+ return None
34
+ return stripped[len(_ENV_LINE_PREFIX):].strip().strip('"').strip("'")
35
+
36
+
37
+ def _strip_boot_key_line(env_path: Path, expected: str) -> bool:
38
+ """Remove only the AGENT_WALLET_BOOT_KEY line whose value == expected.
39
+
40
+ Preserve all other vars, and never strip a line carrying a *different* value
41
+ (that would signal a key mismatch a human should look at). Returns True if
42
+ the file changed.
43
+ """
44
+ try:
45
+ lines = env_path.read_text(encoding="utf-8").splitlines()
46
+ except OSError:
47
+ return False
48
+ kept = [ln for ln in lines if _env_boot_key_value(ln) != expected]
49
+ if len(kept) == len(lines):
50
+ return False
51
+ atomic_write_text(env_path, ("\n".join(kept) + "\n") if kept else "", mode=0o600)
52
+ return True
53
+
54
+
55
+ def _candidate_env_files(runtime: Path) -> list[Path]:
56
+ """Boot-key .env locations to sweep, deduped.
57
+
58
+ Deliberately bounded: a recursive ``**/.env`` walk descends into the hundreds
59
+ of ``node_modules`` trees under the release dirs and effectively hangs onboarding
60
+ (observed: 650+ node_modules, glob never returns). The boot key was only ever
61
+ written to ``releases/<v>/agent-wallet/.env``; ``current``/``previous`` are
62
+ symlinks into ``releases`` and are resolved to dedupe against their targets.
63
+ """
64
+ candidates = list(runtime.glob("releases/*/agent-wallet/.env"))
65
+ candidates.append(runtime / "current" / "agent-wallet" / ".env")
66
+ candidates.append(runtime / "previous" / "agent-wallet" / ".env")
67
+ seen: set[str] = set()
68
+ out: list[Path] = []
69
+ for path in candidates:
70
+ try:
71
+ key = str(path.resolve())
72
+ except OSError:
73
+ key = str(path)
74
+ if key in seen:
75
+ continue
76
+ seen.add(key)
77
+ if path.exists():
78
+ out.append(path)
79
+ return out
80
+
81
+
82
+ def _sweep_plaintext(home: Path, expected: str) -> tuple[int, bool]:
83
+ """Strip matching boot-key lines from every runtime .env; delete the boot-key file.
84
+
85
+ Idempotent and value-scoped: only plaintext equal to the authoritative
86
+ keystore key is removed, so re-running after a fresh installer write (which
87
+ re-emits the same key) cleans it up on the next start.
88
+ """
89
+ runtime = home / "agent-wallet-runtime"
90
+ swept = 0
91
+ for env_path in _candidate_env_files(runtime):
92
+ try:
93
+ if _strip_boot_key_line(env_path, expected):
94
+ swept += 1
95
+ except Exception:
96
+ continue # best-effort; re-runs next start
97
+ removed = False
98
+ boot_file = runtime / "boot-key"
99
+ try:
100
+ if boot_file.read_text(encoding="utf-8").strip() == expected:
101
+ boot_file.unlink()
102
+ removed = True
103
+ except FileNotFoundError:
104
+ pass
105
+ except OSError:
106
+ pass
107
+ return swept, removed
108
+
109
+
110
+ def migrate_boot_key_to_keystore() -> dict:
111
+ """Move a legacy plaintext boot key into the keystore, verify, then sweep plaintext.
112
+
113
+ Runs on every startup (guarded once per process). When the keystore already
114
+ holds the key, it still re-sweeps any plaintext an installer re-emitted, so a
115
+ per-release .env write never re-establishes a permanent leak.
116
+ """
117
+ store = resolve_keystore()
118
+ home = resolve_openclaw_home()
119
+
120
+ # Do not sweep into a plaintext fallback: that offers no at-rest improvement,
121
+ # and the user explicitly chose to stay on the current file in that case.
122
+ if isinstance(store, PlaintextFileStore):
123
+ if read_boot_key_from_keystore():
124
+ record_keystore_backend(store)
125
+ return {"migrated": False, "backend": store.backend_id, "swept_env_files": 0,
126
+ "removed_boot_key_file": False, "reason": "no-os-keystore"}
127
+
128
+ authoritative = read_boot_key_from_keystore()
129
+ resolved = resolve_boot_key()
130
+ first_time = False
131
+ if authoritative != resolved:
132
+ if not resolved:
133
+ return {"migrated": False, "backend": store.backend_id, "swept_env_files": 0,
134
+ "removed_boot_key_file": False, "reason": "no-legacy-key"}
135
+ try:
136
+ store.set(BOOT_KEY_ITEM, resolved)
137
+ except Exception as exc:
138
+ return {"migrated": False, "backend": store.backend_id, "swept_env_files": 0,
139
+ "removed_boot_key_file": False, "reason": f"keystore-set-failed: {exc}"}
140
+ # Verify-before-delete.
141
+ if store.get(BOOT_KEY_ITEM) != resolved:
142
+ return {"migrated": False, "backend": store.backend_id, "swept_env_files": 0,
143
+ "removed_boot_key_file": False, "reason": "verify-failed"}
144
+ authoritative = resolved
145
+ first_time = True
146
+ elif not authoritative:
147
+ return {"migrated": False, "backend": store.backend_id, "swept_env_files": 0,
148
+ "removed_boot_key_file": False, "reason": "no-legacy-key"}
149
+
150
+ record_keystore_backend(store)
151
+ swept, removed = _sweep_plaintext(home, authoritative)
152
+ migrated = first_time or swept > 0 or removed
153
+ return {"migrated": migrated, "backend": store.backend_id, "swept_env_files": swept,
154
+ "removed_boot_key_file": removed,
155
+ "reason": "ok" if migrated else "already-clean"}
@@ -0,0 +1,57 @@
1
+ """User-facing boot-key export/import for paper backup and machine recovery.
2
+
3
+ The boot key is a retrievable string (baseline A), so recovery is simple: show
4
+ it for a paper backup, or write a recorded value back into the keystore on a new
5
+ machine. Full recovery kit = boot key + the already-encrypted sealed_keys.json +
6
+ wallet files. See BOOT_KEY_KEYCHAIN_ARCHITECTURE.md.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from agent_wallet.config import clear_secret_caches, resolve_boot_key
12
+ from agent_wallet.keystore import BOOT_KEY_ITEM, record_keystore_backend, resolve_keystore
13
+ from agent_wallet.wallet_layer.base import WalletBackendError
14
+
15
+ _EXPORT_WARNING = (
16
+ "SENSITIVE: anyone with this boot key AND your ~/.openclaw encrypted files "
17
+ "controls every wallet (Solana/EVM/BTC). Write it down and store it offline."
18
+ )
19
+
20
+
21
+ def export_boot_key() -> str:
22
+ """Return the live boot key. Raises if none is resolvable."""
23
+ key = resolve_boot_key()
24
+ if not key:
25
+ raise WalletBackendError(
26
+ "No boot key is available to export. The wallet is not set up on this machine."
27
+ )
28
+ return key
29
+
30
+
31
+ def import_boot_key(value: str) -> dict:
32
+ """Validate and write a recorded boot key, then verify the read-back."""
33
+ key = str(value or "").strip()
34
+ if not key:
35
+ raise WalletBackendError("A non-empty boot key is required for import.")
36
+ from agent_wallet.sealed_keys import resolve_sealed_keys_path, unseal_keys
37
+
38
+ if resolve_sealed_keys_path().exists():
39
+ try:
40
+ unseal_keys(key)
41
+ except Exception as exc:
42
+ raise WalletBackendError(
43
+ "The supplied boot key does not unlock the existing sealed wallet state."
44
+ ) from exc
45
+ store = resolve_keystore()
46
+ store.set(BOOT_KEY_ITEM, key)
47
+ if store.get(BOOT_KEY_ITEM) != key:
48
+ raise WalletBackendError(
49
+ f"Boot key import could not be verified from the {store.backend_id} keystore."
50
+ )
51
+ state = record_keystore_backend(store)
52
+ clear_secret_caches()
53
+ return {"imported": True, "backend": store.backend_id, "backend_state": state}
54
+
55
+
56
+ def export_warning() -> str:
57
+ return _EXPORT_WARNING
@@ -0,0 +1,194 @@
1
+ """Bootstrap helpers for provisioning agent wallets on first use."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from agent_wallet.config import normalize_solana_network, refuse_mainnet_wallet_recreation
9
+ from agent_wallet.file_ops import atomic_write_text
10
+ from agent_wallet.wallet_layer.base import WalletBackendError
11
+ from agent_wallet.wallet_layer.base58 import b58encode
12
+
13
+ WALLET_ADDRESS_PIN_KIND = "openclaw-agent-wallet-address-pin"
14
+ WALLET_ADDRESS_PIN_VERSION = 1
15
+
16
+
17
+ def _keypair_bytes_for_file(secret_key: bytes, public_key: bytes) -> list[int]:
18
+ return list(secret_key + public_key)
19
+
20
+
21
+ def generate_solana_wallet_material() -> dict[str, str]:
22
+ """Generate new Solana secret material without writing it to disk."""
23
+ try:
24
+ from nacl.signing import SigningKey
25
+ except ImportError as exc:
26
+ raise WalletBackendError(
27
+ "PyNaCl is required to auto-create a local Solana wallet."
28
+ ) from exc
29
+
30
+ signing_key = SigningKey.generate()
31
+ secret_key = signing_key.encode()
32
+ public_key = bytes(signing_key.verify_key)
33
+ return {
34
+ "address": b58encode(public_key),
35
+ "secret_material": json.dumps(_keypair_bytes_for_file(secret_key, public_key), indent=2),
36
+ }
37
+
38
+
39
+ def create_solana_wallet_file(path: Path) -> dict[str, str]:
40
+ """Create a new local Solana wallet file in Solana CLI JSON format."""
41
+ material = generate_solana_wallet_material()
42
+ atomic_write_text(path, material["secret_material"], mode=0o600)
43
+ return {
44
+ "address": material["address"],
45
+ "path": str(path),
46
+ }
47
+
48
+
49
+ def resolve_wallet_pin_path(path: Path) -> Path:
50
+ """Return the sidecar file used to pin an expected wallet address."""
51
+ return path.with_suffix(f"{path.suffix}.pin.json")
52
+
53
+
54
+ def load_wallet_pin(path: Path) -> dict[str, str] | None:
55
+ """Load wallet pin metadata if present and valid."""
56
+ pin_path = resolve_wallet_pin_path(path)
57
+ if not pin_path.exists():
58
+ return None
59
+ try:
60
+ payload = json.loads(pin_path.read_text(encoding="utf-8"))
61
+ except json.JSONDecodeError as exc:
62
+ raise WalletBackendError(f"Wallet pin file is malformed: {pin_path}") from exc
63
+ if not isinstance(payload, dict):
64
+ raise WalletBackendError(f"Wallet pin file is malformed: {pin_path}")
65
+ if payload.get("kind") != WALLET_ADDRESS_PIN_KIND:
66
+ raise WalletBackendError(f"Wallet pin file kind is invalid: {pin_path}")
67
+ if int(payload.get("version") or 0) != WALLET_ADDRESS_PIN_VERSION:
68
+ raise WalletBackendError(f"Wallet pin file version is invalid: {pin_path}")
69
+ address = str(payload.get("address") or "").strip()
70
+ network = str(payload.get("network") or "").strip().lower()
71
+ if not address or not network:
72
+ raise WalletBackendError(f"Wallet pin file is incomplete: {pin_path}")
73
+ return {
74
+ "address": address,
75
+ "network": network,
76
+ "path": str(pin_path),
77
+ }
78
+
79
+
80
+ def write_wallet_pin(path: Path, *, address: str, network: str) -> dict[str, str]:
81
+ """Persist the expected wallet address for later mismatch checks."""
82
+ normalized_network = normalize_solana_network(network)
83
+ payload = {
84
+ "kind": WALLET_ADDRESS_PIN_KIND,
85
+ "version": WALLET_ADDRESS_PIN_VERSION,
86
+ "address": address,
87
+ "network": normalized_network,
88
+ "wallet_file": path.name,
89
+ }
90
+ pin_path = resolve_wallet_pin_path(path)
91
+ atomic_write_text(pin_path, json.dumps(payload, indent=2), mode=0o600)
92
+ return {
93
+ "address": address,
94
+ "network": payload["network"],
95
+ "path": str(pin_path),
96
+ }
97
+
98
+
99
+ def ensure_wallet_pin(path: Path, *, address: str, network: str) -> dict[str, str]:
100
+ """Ensure the wallet pin exists and matches the expected address."""
101
+ expected_network = normalize_solana_network(network)
102
+ existing = load_wallet_pin(path)
103
+ if existing is None:
104
+ return write_wallet_pin(path, address=address, network=expected_network)
105
+ if existing["network"] != expected_network:
106
+ raise WalletBackendError(
107
+ f"Wallet pin network mismatch for {path}: expected {expected_network}, found {existing['network']}."
108
+ )
109
+ if existing["address"] != address:
110
+ raise WalletBackendError(
111
+ f"Wallet address mismatch for {path}: pinned {existing['address']}, derived {address}."
112
+ )
113
+ return existing
114
+
115
+
116
+ def refuse_recreation_if_pinned(path: Path, *, network: str) -> None:
117
+ """Refuse to recreate a wallet when a mainnet address is already pinned."""
118
+ expected_network = normalize_solana_network(network)
119
+ if expected_network != "mainnet" or not refuse_mainnet_wallet_recreation():
120
+ return
121
+ existing = load_wallet_pin(path)
122
+ if existing is None:
123
+ return
124
+ raise WalletBackendError(
125
+ "Refusing to create a new mainnet wallet because a pinned wallet address already exists "
126
+ f"for {path}. Restore the original wallet file for {existing['address']} instead of creating a new one."
127
+ )
128
+
129
+
130
+ def ensure_solana_wallet_ready() -> dict[str, str] | None:
131
+ """Ensure that a Solana wallet exists when auto-create is enabled."""
132
+ from agent_wallet.config import (
133
+ default_solana_wallet_path,
134
+ resolve_solana_private_key,
135
+ settings,
136
+ )
137
+
138
+ if settings.agent_wallet_backend.strip().lower() not in {"solana", "solana_local", "solana-local"}:
139
+ return None
140
+
141
+ if resolve_solana_private_key():
142
+ return {"address": "", "path": ""}
143
+
144
+ normalized_network = normalize_solana_network(settings.solana_network)
145
+ configured_path = settings.solana_agent_keypair_path.strip()
146
+ path = (
147
+ Path(configured_path).expanduser()
148
+ if configured_path
149
+ else default_solana_wallet_path(normalized_network)
150
+ )
151
+
152
+ if path.exists():
153
+ return {"address": "", "path": str(path)}
154
+
155
+ if not settings.solana_auto_create_wallet:
156
+ return None
157
+
158
+ refuse_recreation_if_pinned(path, network=normalized_network)
159
+ created = create_solana_wallet_file(path)
160
+ write_wallet_pin(path, address=created["address"], network=normalized_network)
161
+ return created
162
+
163
+
164
+ def describe_bootstrap() -> dict[str, str | bool]:
165
+ """Return the effective bootstrap configuration for installer/runtime usage."""
166
+ from agent_wallet.config import (
167
+ default_solana_wallet_path,
168
+ normalize_solana_network,
169
+ resolve_solana_rpc_url,
170
+ resolve_runtime_solana_rpc_urls,
171
+ settings,
172
+ )
173
+
174
+ normalized_network = normalize_solana_network(settings.solana_network)
175
+ configured_path = settings.solana_agent_keypair_path.strip()
176
+ path = (
177
+ Path(configured_path).expanduser()
178
+ if configured_path
179
+ else default_solana_wallet_path(normalized_network)
180
+ )
181
+ rpc_urls = resolve_runtime_solana_rpc_urls(
182
+ normalized_network,
183
+ settings.solana_rpc_url,
184
+ settings.solana_rpc_urls,
185
+ )
186
+ return {
187
+ "backend": settings.agent_wallet_backend,
188
+ "network": normalized_network,
189
+ "rpc_url": rpc_urls[0] if rpc_urls else resolve_solana_rpc_url(normalized_network, ""),
190
+ "rpc_urls": rpc_urls,
191
+ "auto_create_wallet": settings.solana_auto_create_wallet,
192
+ "keypair_path": str(path),
193
+ "sign_only": settings.agent_wallet_sign_only,
194
+ }
@@ -0,0 +1,243 @@
1
+ """Agent-safe card metadata and short-lived issuer retrieval credentials.
2
+
3
+ Encrypted under a purpose- and user-scoped runtime key. Never stores PAN/CVV.
4
+ Pending credentials can retrieve card data at Laso: this is a backend capability,
5
+ not cryptographic isolation from a compromised wallet runtime while pending.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import copy
11
+ import hashlib
12
+ import hmac
13
+ import json
14
+ import math
15
+ import re
16
+ import time
17
+ from datetime import datetime, timezone
18
+ from decimal import Decimal, InvalidOperation
19
+ from typing import Any
20
+
21
+ from nacl.exceptions import CryptoError
22
+ from nacl.secret import SecretBox
23
+
24
+ from agent_wallet.card_vault import CardVault
25
+ from agent_wallet.config import resolve_wallet_master_key
26
+ from agent_wallet.file_ops import atomic_write_text
27
+ from agent_wallet.wallet_layer.base import WalletBackendError
28
+
29
+ CARD_TYPES = {"Non-Reloadable U.S.", "Non-Reloadable International"}
30
+ STATUSES = {"pending", "queued", "ready", "failed", "cancelled", "expired", "depleted"}
31
+ TERMINAL = {"failed", "cancelled", "expired", "depleted"}
32
+ REFRESH_STATES = {"pending", "complete", "retry_later", "credentials_expired", "owner_access_required", "unavailable"}
33
+ JOB_TTL = 7 * 24 * 3600
34
+ MIN_REFRESH_INTERVAL = 3
35
+ MAX_STATE_BYTES = 128 * 1024
36
+
37
+
38
+ def card_object(body: dict[str, Any]) -> dict[str, Any]:
39
+ card = body.get("card")
40
+ return card if isinstance(card, dict) else body
41
+
42
+
43
+ def credentials(record: dict[str, Any]) -> dict[str, str]:
44
+ order = record.get("order") or {}
45
+ auth = order.get("auth") if isinstance(order.get("auth"), dict) else order
46
+ # Only actual credential fields, never unexpected provider data.
47
+ return {key: auth[key] for key in ("id_token", "refresh_token")
48
+ if isinstance(auth.get(key), str) and 0 < len(auth[key]) <= 16384}
49
+
50
+
51
+ def details_ready(record: dict[str, Any]) -> bool:
52
+ card = card_object(record.get("latest") or record.get("order") or {})
53
+ details = card.get("card_details")
54
+ if not isinstance(details, dict):
55
+ return False
56
+ number, cvv = details.get("card_number"), details.get("cvv")
57
+ try:
58
+ return (
59
+ isinstance(number, str) and re.fullmatch(r"[0-9]{12,19}", number) is not None
60
+ and isinstance(cvv, str) and re.fullmatch(r"[0-9]{3,4}", cvv) is not None
61
+ and 1 <= int(details["exp_month"]) <= 12
62
+ and 2000 <= int(details["exp_year"]) <= 2100
63
+ )
64
+ except (KeyError, ValueError, TypeError):
65
+ return False
66
+
67
+
68
+ def _timestamp(value: Any) -> str | None:
69
+ if type(value) not in {int, float} or not 946684800 <= value <= 4133980800:
70
+ return None
71
+ return datetime.fromtimestamp(value, timezone.utc).isoformat()
72
+
73
+
74
+ def _balance(value: Any) -> str | None:
75
+ if type(value) not in {str, int, float}:
76
+ return None
77
+ try:
78
+ amount = Decimal(str(value))
79
+ if amount.is_finite() and 0 <= amount <= 1000000 and amount.as_tuple().exponent >= -6:
80
+ return format(amount, "f")
81
+ except (InvalidOperation, ValueError):
82
+ pass
83
+ return None
84
+
85
+
86
+ class CardCatalog:
87
+ def __init__(self, vault: CardVault):
88
+ self.vault = vault
89
+
90
+ def _key(self) -> bytes:
91
+ master = resolve_wallet_master_key()
92
+ if not master:
93
+ raise WalletBackendError("The sealed wallet runtime key is required for pending card retrieval.")
94
+ return hmac.new(master.encode(), b"agentlayer-card-catalog-v1\0" + self.vault.scope.encode(), hashlib.sha256).digest()
95
+
96
+ def preflight(self) -> None:
97
+ self._key()
98
+
99
+ def _path(self, reference: str):
100
+ return self.vault._path(reference).with_suffix(".agent")
101
+
102
+ def save(self, reference: str, state: dict[str, Any]) -> None:
103
+ self.vault._config()
104
+ value = {"scope": self.vault.scope, "reference": reference, "state": state}
105
+ plaintext = json.dumps(value).encode()
106
+ if len(plaintext) > MAX_STATE_BYTES:
107
+ raise WalletBackendError("Card catalog state exceeds size limit.")
108
+ encrypted = bytes(SecretBox(self._key()).encrypt(plaintext))
109
+ atomic_write_text(self._path(reference), json.dumps({"kind": "agentlayer-card-catalog", "version": 1, "box": base64.b64encode(encrypted).decode()}))
110
+ self.vault._sync_directory()
111
+
112
+ def load(self, reference: str) -> dict[str, Any]:
113
+ self.vault._config()
114
+ if not self.vault._path(reference).is_file():
115
+ raise WalletBackendError("Saved card record was not found for this user.")
116
+ try:
117
+ envelope = self.vault._read(self._path(reference))
118
+ if envelope["kind"] != "agentlayer-card-catalog" or envelope["version"] != 1:
119
+ raise ValueError()
120
+ raw = SecretBox(self._key()).decrypt(base64.b64decode(envelope["box"], validate=True))
121
+ if len(raw) > MAX_STATE_BYTES:
122
+ raise ValueError()
123
+ value = json.loads(raw)
124
+ if value["scope"] != self.vault.scope or value["reference"] != reference or not isinstance(value["state"], dict):
125
+ raise ValueError()
126
+ return value["state"]
127
+ except (CryptoError, ValueError, KeyError, TypeError):
128
+ raise WalletBackendError("Card catalog authentication failed.") from None
129
+
130
+ def _entry(self, record: dict[str, Any], previous: dict[str, Any] | None = None) -> dict[str, Any]:
131
+ card = card_object(record.get("latest") or record.get("order") or {})
132
+ details = card.get("card_details")
133
+ details = details if isinstance(details, dict) else {}
134
+ number = details.get("card_number")
135
+ entry = dict(previous or {})
136
+ status = card.get("status")
137
+ entry.update({
138
+ "status": status if isinstance(status, str) and status in STATUSES else "unknown",
139
+ "card_type": record.get("card_type"),
140
+ "details_stored": details_ready(record),
141
+ })
142
+ if isinstance(number, str) and re.fullmatch(r"[0-9]{12,19}", number):
143
+ entry["last4"] = number[-4:]
144
+ if "available_balance" in details:
145
+ entry["balance"] = _balance(details["available_balance"])
146
+ return entry
147
+
148
+ def track(self, reference: str, record: dict[str, Any]) -> dict[str, Any]:
149
+ from agent_wallet.card_runtime_secrets import CardRuntimeSecrets
150
+
151
+ CardRuntimeSecrets(self.vault).capture(reference, record)
152
+ now = time.time()
153
+ entry = self._entry(record)
154
+ card = card_object(record.get("order") or {})
155
+ auth = credentials(record)
156
+ card_id = card.get("card_id")
157
+ active = (
158
+ not entry["details_stored"] and entry["status"] not in TERMINAL
159
+ and isinstance(record.get("card_type"), str) and record["card_type"] in CARD_TYPES
160
+ and isinstance(card_id, str) and 0 < len(card_id) <= 128
161
+ and bool(auth.get("id_token"))
162
+ )
163
+ job = {"card_id": card_id, "card_type": record["card_type"], "auth": auth,
164
+ "expires_at": now + JOB_TTL, "next_at": now, "attempts": 0} if active else None
165
+ state = {"entry": entry, "created_at": now, "checked_at": now if record.get("latest") else None,
166
+ "refresh_state": "pending" if active else "complete" if entry["details_stored"] or entry["status"] in TERMINAL else "owner_access_required",
167
+ "job": job}
168
+ self.save(reference, state)
169
+ return state
170
+
171
+ def update(self, reference: str, state: dict[str, Any], record: dict[str, Any]) -> None:
172
+ from agent_wallet.card_runtime_secrets import CardRuntimeSecrets
173
+
174
+ # Persist the executor capsule before retiring retrieval credentials.
175
+ CardRuntimeSecrets(self.vault).capture(reference, record)
176
+ # Do not report credential retirement unless the new catalog state is durable.
177
+ candidate = copy.deepcopy(state)
178
+ candidate["entry"] = self._entry(record, candidate.get("entry"))
179
+ candidate["checked_at"] = time.time()
180
+ if candidate["entry"]["details_stored"] or candidate["entry"]["status"] in TERMINAL:
181
+ candidate["job"] = None
182
+ candidate["refresh_state"] = "complete"
183
+ else:
184
+ candidate["refresh_state"] = "pending" if candidate.get("job") else "owner_access_required"
185
+ self.save(reference, candidate)
186
+ state.clear()
187
+ state.update(candidate)
188
+
189
+ def safe(self, reference: str, state: dict[str, Any]) -> dict[str, Any]:
190
+ # Filter even authenticated local metadata; never return the state/job object.
191
+ entry = state.get("entry")
192
+ entry = entry if isinstance(entry, dict) else {}
193
+ job = state.get("job")
194
+ job = job if isinstance(job, dict) else {}
195
+ status, card_type = entry.get("status"), entry.get("card_type")
196
+ last4 = entry.get("last4")
197
+ refresh_state = state.get("refresh_state")
198
+ next_at = job.get("next_at")
199
+ expires_at = job.get("expires_at")
200
+ active = bool(job) and _timestamp(expires_at) is not None and expires_at > time.time()
201
+ if job and not active:
202
+ refresh_state = "credentials_expired"
203
+ return {
204
+ "vault_reference": reference, "provider": "laso", "currency": "USD",
205
+ "status": status if isinstance(status, str) and status in STATUSES else "unknown",
206
+ "card_type": card_type if isinstance(card_type, str) and card_type in CARD_TYPES else None,
207
+ "last4": last4 if isinstance(last4, str) and re.fullmatch(r"[0-9]{4}", last4) else None,
208
+ "available_balance": _balance(entry.get("balance")), "balance_is_cached": True,
209
+ "details_stored": entry.get("details_stored") is True,
210
+ "private_use_stored": self.vault._path(reference).with_suffix(".use").is_file(),
211
+ "created_at": _timestamp(state.get("created_at")), "last_checked_at": _timestamp(state.get("checked_at")),
212
+ "refresh_available": active,
213
+ "refresh_state": refresh_state if isinstance(refresh_state, str) and refresh_state in REFRESH_STATES else "unavailable",
214
+ "next_check_at": _timestamp(next_at) if active else None,
215
+ "retry_after_seconds": min(300, max(0, math.ceil(next_at - time.time()))) if active and _timestamp(next_at) else None,
216
+ "stored_encrypted": True,
217
+ }
218
+
219
+ def get(self, reference: str) -> dict[str, Any]:
220
+ path = self._path(reference)
221
+ if not self.vault._path(reference).is_file():
222
+ raise WalletBackendError("Saved card record was not found for this user.")
223
+ if not path.exists() and not path.is_symlink():
224
+ return self.safe(reference, {"refresh_state": "owner_access_required"})
225
+ return self.safe(reference, self.load(reference))
226
+
227
+ def list(self, *, limit: int = 20, after: str | None = None) -> dict[str, Any]:
228
+ if type(limit) is not int or not 1 <= limit <= 100:
229
+ raise WalletBackendError("limit must be an integer between 1 and 100.")
230
+ if after is not None:
231
+ self.vault._path(after)
232
+ if not self.vault.config_path.exists() and not self.vault.config_path.is_symlink():
233
+ if any(self.vault.root.glob("*.card")):
234
+ raise WalletBackendError("Card vault metadata is missing; restore it before accessing saved cards.")
235
+ return {"cards": [], "next_cursor": None}
236
+ references = [ref for ref in self.vault.references() if after is None or ref > after]
237
+ cards = []
238
+ for ref in references[:limit]:
239
+ try:
240
+ cards.append(self.get(ref))
241
+ except WalletBackendError:
242
+ cards.append(self.safe(ref, {"refresh_state": "unavailable"}))
243
+ return {"cards": cards, "next_cursor": references[limit - 1] if len(references) > limit else None}