@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,10 @@
|
|
|
1
|
+
"""Wallet package exceptions."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ProviderError(Exception):
|
|
5
|
+
"""A provider failed to return data."""
|
|
6
|
+
|
|
7
|
+
def __init__(self, provider: str, message: str, *, details: dict | None = None):
|
|
8
|
+
self.provider = provider
|
|
9
|
+
self.details = dict(details) if isinstance(details, dict) else None
|
|
10
|
+
super().__init__(f"[{provider}] {message}")
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Filesystem helpers for sensitive wallet/config state."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import tempfile
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def atomic_write_text(path: Path, content: str, *, mode: int = 0o600) -> None:
|
|
11
|
+
"""Atomically write text to a path with restrictive permissions."""
|
|
12
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
13
|
+
fd, temp_path = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
|
|
14
|
+
try:
|
|
15
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
16
|
+
handle.write(content)
|
|
17
|
+
handle.flush()
|
|
18
|
+
os.fsync(handle.fileno())
|
|
19
|
+
os.chmod(temp_path, mode)
|
|
20
|
+
os.replace(temp_path, path)
|
|
21
|
+
except Exception:
|
|
22
|
+
try:
|
|
23
|
+
os.unlink(temp_path)
|
|
24
|
+
except FileNotFoundError:
|
|
25
|
+
pass
|
|
26
|
+
raise
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def chmod_if_exists(path: Path, mode: int = 0o600) -> None:
|
|
30
|
+
"""Best-effort chmod for sensitive files."""
|
|
31
|
+
try:
|
|
32
|
+
path.chmod(mode)
|
|
33
|
+
except FileNotFoundError:
|
|
34
|
+
return
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Shared httpx async client for wallet providers."""
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
|
|
5
|
+
from agent_wallet.config import settings
|
|
6
|
+
|
|
7
|
+
_client: httpx.AsyncClient | None = None
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def get_client() -> httpx.AsyncClient:
|
|
11
|
+
global _client
|
|
12
|
+
if _client is None or _client.is_closed:
|
|
13
|
+
_client = httpx.AsyncClient(
|
|
14
|
+
timeout=httpx.Timeout(settings.http_timeout),
|
|
15
|
+
headers={"Accept": "application/json"},
|
|
16
|
+
follow_redirects=True,
|
|
17
|
+
)
|
|
18
|
+
return _client
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
async def close_client() -> None:
|
|
22
|
+
global _client
|
|
23
|
+
if _client and not _client.is_closed:
|
|
24
|
+
await _client.aclose()
|
|
25
|
+
_client = None
|
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
"""Managed Kernel sessions. No CDP, arbitrary code, cookies or filled DOM in tools.
|
|
2
|
+
|
|
3
|
+
Kernel is a trusted cloud processor: private fill values cross TLS to its
|
|
4
|
+
Playwright API and exist in its VM and merchant page. This is not isolation
|
|
5
|
+
from Kernel/account administrators or from the merchant's own JavaScript.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from typing import Any
|
|
14
|
+
from urllib.parse import quote
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
from agent_wallet.card_runtime_secrets import RuntimeVaultStorage
|
|
19
|
+
from agent_wallet.card_vault import CardVault
|
|
20
|
+
from agent_wallet.config import resolve_kernel_api_key
|
|
21
|
+
from agent_wallet.wallet_layer.base import WalletBackendError
|
|
22
|
+
|
|
23
|
+
BROWSER_SCHEMA = {"type": "object", "properties": {
|
|
24
|
+
"action": {"type": "string", "enum": ["open", "observe", "inspect", "click", "fill", "select", "press", "close", "status"]},
|
|
25
|
+
"browser_reference": {"type": "string", "pattern": "^[a-f0-9]{32}$"},
|
|
26
|
+
"url": {"type": "string"}, "selector": {"type": "string", "maxLength": 512},
|
|
27
|
+
"value": {"type": "string", "maxLength": 2048}, "user_intent": {"type": "boolean"},
|
|
28
|
+
}, "required": ["action"], "additionalProperties": False}
|
|
29
|
+
CHECKOUT_SCHEMA = {"type": "object", "properties": {
|
|
30
|
+
"action": {"type": "string", "enum": ["submit", "fill_only"], "default": "submit",
|
|
31
|
+
"description": "fill_only fills privately without clicking submit, then closes the browser."},
|
|
32
|
+
"browser_reference": {"type": "string", "pattern": "^[a-f0-9]{32}$"},
|
|
33
|
+
"page_url": {"type": "string"},
|
|
34
|
+
"fields": {"type": "array", "minItems": 3, "maxItems": 14, "items": {
|
|
35
|
+
"type": "object", "properties": {
|
|
36
|
+
"field": {"type": "string", "enum": ["card.number", "card.cvv", "card.exp_month", "card.exp_year", "card.expiry", "card.expiry_short", "card.exp_year_short", *["card.billing." + k for k in ("name", "line_1", "line_2", "city", "state", "zip", "country")]]},
|
|
37
|
+
"selector": {"type": "string", "maxLength": 512},
|
|
38
|
+
"frame_url": {"type": "string"},
|
|
39
|
+
}, "required": ["field", "selector"], "additionalProperties": False}},
|
|
40
|
+
"total_selector": {"type": "string", "maxLength": 512},
|
|
41
|
+
"expected_total": {"type": "string", "maxLength": 128},
|
|
42
|
+
"amount_usd": {"type": "string", "pattern": "^[0-9]{1,6}(\\.[0-9]{1,2})?$"},
|
|
43
|
+
"submit_selector": {"type": "string", "maxLength": 512},
|
|
44
|
+
"success_selector": {"type": "string", "maxLength": 512},
|
|
45
|
+
}, "required": ["browser_reference", "page_url", "fields", "total_selector", "expected_total", "amount_usd"], "additionalProperties": False}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _json(value: Any) -> str:
|
|
49
|
+
return json.dumps(value, ensure_ascii=True, allow_nan=False, separators=(",", ":"))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _selector(value: Any) -> str:
|
|
53
|
+
if not isinstance(value, str) or not 1 <= len(value) <= 512 or any(ord(c) < 32 for c in value):
|
|
54
|
+
raise WalletBackendError("Use a nonempty selector of at most 512 characters.")
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def validate_checkout(value: Any) -> dict[str, Any]:
|
|
59
|
+
from decimal import Decimal
|
|
60
|
+
from agent_wallet.vault_executor import _url, FIELDS
|
|
61
|
+
|
|
62
|
+
if (not isinstance(value, dict) or set(value) - set(CHECKOUT_SCHEMA["properties"])
|
|
63
|
+
or not set(CHECKOUT_SCHEMA["required"]) <= set(value)):
|
|
64
|
+
raise WalletBackendError("checkout requires a fixed browser, fields and total plan.")
|
|
65
|
+
action = value.get("action", "submit")
|
|
66
|
+
if action not in ("submit", "fill_only"):
|
|
67
|
+
raise WalletBackendError("checkout.action must be submit or fill_only.")
|
|
68
|
+
if action == "submit" and not {"submit_selector", "success_selector"} <= set(value):
|
|
69
|
+
raise WalletBackendError("Submitting checkout requires submit_selector and success_selector.")
|
|
70
|
+
if action == "fill_only" and set(value) & {"submit_selector", "success_selector"}:
|
|
71
|
+
raise WalletBackendError("fill_only must not include submit or success selectors.")
|
|
72
|
+
result = json.loads(_json(value))
|
|
73
|
+
if not isinstance(result["browser_reference"], str) or not re.fullmatch(r"[a-f0-9]{32}", result["browser_reference"]):
|
|
74
|
+
raise WalletBackendError("Invalid browser reference.")
|
|
75
|
+
_url(result["page_url"])
|
|
76
|
+
selector_keys = ("total_selector", "submit_selector", "success_selector") if action == "submit" else ("total_selector",)
|
|
77
|
+
for key in selector_keys:
|
|
78
|
+
_selector(result[key])
|
|
79
|
+
if len({result[k] for k in selector_keys}) != len(selector_keys):
|
|
80
|
+
raise WalletBackendError("Total, submit and success selectors must differ.")
|
|
81
|
+
amount = result["amount_usd"]
|
|
82
|
+
if not isinstance(amount, str) or not re.fullmatch(r"[0-9]{1,6}(?:\.[0-9]{1,2})?", amount) or Decimal(amount) <= 0:
|
|
83
|
+
raise WalletBackendError("A positive USD amount with at most two decimal places is required.")
|
|
84
|
+
# Intentionally narrow: refuse ambiguous localized/currency display strings.
|
|
85
|
+
total = result["expected_total"]
|
|
86
|
+
if not isinstance(total, str) or len(total) > 128:
|
|
87
|
+
raise WalletBackendError("Provide the exact displayed USD total.")
|
|
88
|
+
match = re.fullmatch(r"(?:USD\s*\$?|US\$|\$)\s*([0-9]+(?:\.[0-9]{2})?)|([0-9]+(?:\.[0-9]{2})?)\s*USD", re.sub(r"^(?:Donate|Pay)\s+", "", total.strip(), flags=re.IGNORECASE))
|
|
89
|
+
if not match or Decimal(match.group(1) or match.group(2)) != Decimal(amount):
|
|
90
|
+
raise WalletBackendError("expected_total must be an unambiguous USD price matching amount_usd, e.g. $19.99 or 19.99 USD.")
|
|
91
|
+
fields = result["fields"]
|
|
92
|
+
if not isinstance(fields, list) or not 3 <= len(fields) <= 14:
|
|
93
|
+
raise WalletBackendError("Bind the card number, CVV and expiry fields.")
|
|
94
|
+
seen, targets = set(), set()
|
|
95
|
+
for binding in fields:
|
|
96
|
+
if not isinstance(binding, dict) or set(binding) - {"field", "selector", "frame_url"} or not {"field", "selector"} <= set(binding):
|
|
97
|
+
raise WalletBackendError("Invalid checkout field binding.")
|
|
98
|
+
field = binding["field"]
|
|
99
|
+
if field not in FIELDS | {"card.expiry", "card.expiry_short", "card.exp_year_short"} or field in seen:
|
|
100
|
+
raise WalletBackendError("Unknown or repeated checkout card field.")
|
|
101
|
+
_selector(binding["selector"])
|
|
102
|
+
if "frame_url" in binding:
|
|
103
|
+
_url(binding["frame_url"])
|
|
104
|
+
target = (binding.get("frame_url", result["page_url"]), binding["selector"])
|
|
105
|
+
if target in targets:
|
|
106
|
+
raise WalletBackendError("Checkout field targets must be distinct.")
|
|
107
|
+
targets.add(target)
|
|
108
|
+
seen.add(field)
|
|
109
|
+
if not {"card.number", "card.cvv"} <= seen or not ({"card.exp_month", "card.exp_year"} <= seen or {"card.exp_month", "card.exp_year_short"} <= seen or seen & {"card.expiry", "card.expiry_short"}):
|
|
110
|
+
raise WalletBackendError("Card number, CVV and complete expiry are required.")
|
|
111
|
+
return result
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
DIAGNOSTIC_PHASES = {"precheck", "fill", "verify_total", "submit", "confirmation", "complete", "transport"}
|
|
115
|
+
DIAGNOSTIC_REASONS = {"precheck_failed", "page_changed", "fill_failed", "total_changed",
|
|
116
|
+
"success_already_visible", "submit_failed", "confirmation_not_observed",
|
|
117
|
+
"origin_changed", "completed", "filled_without_submit", "executor_result_unavailable"}
|
|
118
|
+
ERROR_CATEGORIES = {"card_declined", "card_invalid", "expiry_invalid", "cvv_invalid",
|
|
119
|
+
"authentication_required", "demo_restriction"}
|
|
120
|
+
FIELD_CATEGORIES = {"email", "name", "address", "postal_code", "phone", "card_number", "card_expiry", "card_cvv", "other"}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def safe_checkout_diagnostics(value: Any) -> dict:
|
|
124
|
+
"""Treat provider results as untrusted; never return free text or field values."""
|
|
125
|
+
if not isinstance(value, dict):
|
|
126
|
+
return {}
|
|
127
|
+
safe = {}
|
|
128
|
+
for key, allowed in (("phase", DIAGNOSTIC_PHASES), ("reason", DIAGNOSTIC_REASONS)):
|
|
129
|
+
if isinstance(value.get(key), str) and value[key] in allowed:
|
|
130
|
+
safe[key] = value[key]
|
|
131
|
+
for key, maximum in (("filled_fields", 14), ("invalid_fields", 1000), ("visible_alerts", 1000)):
|
|
132
|
+
if type(value.get(key)) is int and 0 <= value[key] <= maximum:
|
|
133
|
+
safe[key] = value[key]
|
|
134
|
+
for key in ("submit_attempted", "submit_completed"):
|
|
135
|
+
if type(value.get(key)) is bool:
|
|
136
|
+
safe[key] = value[key]
|
|
137
|
+
for key, allowed in (("invalid_field_categories", FIELD_CATEGORIES), ("error_categories", ERROR_CATEGORIES)):
|
|
138
|
+
if isinstance(value.get(key), list):
|
|
139
|
+
safe[key] = sorted({item for item in value[key][:32] if isinstance(item, str) and item in allowed})
|
|
140
|
+
return safe
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class KernelClient:
|
|
144
|
+
def __init__(self, key: str | None = None):
|
|
145
|
+
self.key = key or resolve_kernel_api_key()
|
|
146
|
+
if not self.key:
|
|
147
|
+
raise WalletBackendError("This direct Kernel session needs its original personal connection. It was not moved to the shared service.")
|
|
148
|
+
|
|
149
|
+
async def call(self, method: str, path: str, body: Any = None, *, missing_ok: bool = False) -> dict:
|
|
150
|
+
try:
|
|
151
|
+
async with httpx.AsyncClient(trust_env=False, follow_redirects=False, timeout=75) as client:
|
|
152
|
+
async with client.stream(method, "https://api.onkernel.com" + path,
|
|
153
|
+
headers={"Authorization": "Bearer " + self.key},
|
|
154
|
+
**({"json": body} if body is not None else {})) as response:
|
|
155
|
+
if missing_ok and response.status_code == 404:
|
|
156
|
+
return {}
|
|
157
|
+
if not 200 <= response.status_code < 300:
|
|
158
|
+
raise WalletBackendError("Kernel API request failed. Check the connection and saved operation status before retrying.")
|
|
159
|
+
data = bytearray()
|
|
160
|
+
async for chunk in response.aiter_bytes():
|
|
161
|
+
data.extend(chunk)
|
|
162
|
+
if len(data) > 512 * 1024:
|
|
163
|
+
raise WalletBackendError("Kernel response exceeded the private executor limit.")
|
|
164
|
+
result = json.loads(data) if data else {}
|
|
165
|
+
return result if isinstance(result, dict) else {}
|
|
166
|
+
except WalletBackendError:
|
|
167
|
+
raise
|
|
168
|
+
except Exception:
|
|
169
|
+
raise WalletBackendError("Kernel transport failed; check the saved operation before retrying.") from None
|
|
170
|
+
|
|
171
|
+
async def execute(self, session_id: str, code: str) -> dict:
|
|
172
|
+
data = await self.call("POST", "/browsers/" + quote(session_id, safe="") + "/playwright/execute",
|
|
173
|
+
{"code": code, "timeout_sec": 60})
|
|
174
|
+
# Discard stdout, stderr, error and tab metadata even on failure.
|
|
175
|
+
if data.get("success") is not True or not isinstance(data.get("result"), dict):
|
|
176
|
+
raise WalletBackendError("Kernel browser action did not complete. No private error details were returned.")
|
|
177
|
+
return data["result"]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# Scripts only return preselected properties, never DOM/HTML/input values wholesale.
|
|
181
|
+
PAGE = "const pages=browser.contexts().flatMap(c=>c.pages()); if(pages.length!==1) throw new Error('page count'); const p=pages[0]; p.setDefaultTimeout(8000);\n"
|
|
182
|
+
SNAPSHOT = r"""
|
|
183
|
+
const main = await p.evaluate(() => {
|
|
184
|
+
const cut=s=>String(s||'').replace(/(?:\d[ -]?){12,19}/g,'[redacted]').slice(0,8000);
|
|
185
|
+
const controls=Array.from(document.querySelectorAll('input,select,button,a')).slice(0,100).map(e=>({
|
|
186
|
+
tag:e.tagName.toLowerCase(),type:e.getAttribute('type'),id:e.id||null,name:e.getAttribute('name'),
|
|
187
|
+
autocomplete:e.getAttribute('autocomplete'),label:cut(e.getAttribute('aria-label')||((e.tagName==='BUTTON'||e.tagName==='A')?e.textContent:'')),
|
|
188
|
+
}));
|
|
189
|
+
const copy=document.body.cloneNode(true); copy.querySelectorAll('input,textarea,select,script,style').forEach(e=>e.remove());
|
|
190
|
+
return {url:cut(location.href),text:cut(copy.textContent),controls,frames:Array.from(document.querySelectorAll('iframe')).map(e=>({src:cut(e.src),title:cut(e.title)})).slice(0,20)};
|
|
191
|
+
});
|
|
192
|
+
const childFrames=[];
|
|
193
|
+
for(const f of p.frames().filter(f=>f!==p.mainFrame()).slice(0,20)) {
|
|
194
|
+
try { childFrames.push({url:f.url(),controls:await f.evaluate(()=>Array.from(document.querySelectorAll('input,select')).slice(0,30).map(e=>({tag:e.tagName,id:e.id,name:e.getAttribute('name'),autocomplete:e.getAttribute('autocomplete'),type:e.getAttribute('type')})))}); } catch (_) {}
|
|
195
|
+
}
|
|
196
|
+
return {...main,child_frames:childFrames};
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class KernelBrowser:
|
|
201
|
+
def __init__(self, vault: CardVault):
|
|
202
|
+
self.vault = vault
|
|
203
|
+
self.storage = RuntimeVaultStorage(vault, "browser")
|
|
204
|
+
|
|
205
|
+
def safe(self, ref: str, state: dict) -> dict:
|
|
206
|
+
return {"browser_reference": ref, "status": state["status"], "cleanup_pending": bool(state.get("cleanup_pending")),
|
|
207
|
+
"secrets_returned": False, "provider": "kernel",
|
|
208
|
+
"connection_mode": state.get("connection_mode", "direct")}
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def client(state: dict) -> KernelClient:
|
|
212
|
+
if state.get("connection_mode", "direct") == "direct":
|
|
213
|
+
return KernelClient()
|
|
214
|
+
key = state.get("session_key")
|
|
215
|
+
if state.get("connection_mode") != "shared" or not isinstance(key, str) or not key:
|
|
216
|
+
raise WalletBackendError("Shared browser credentials are unavailable; no replacement session was opened.")
|
|
217
|
+
if time.time() >= state.get("lease_expires_at", 0):
|
|
218
|
+
raise WalletBackendError("Shared browser session expired; no private request was sent.")
|
|
219
|
+
return KernelClient(key=key)
|
|
220
|
+
|
|
221
|
+
async def close(self, ref: str, state: dict) -> None:
|
|
222
|
+
state["status"] = "closed"
|
|
223
|
+
state["cleanup_pending"] = True
|
|
224
|
+
try:
|
|
225
|
+
self.storage.save(ref, state) # Persist inaccessible even if remote deletion fails.
|
|
226
|
+
finally:
|
|
227
|
+
await self._delete_remote(ref, state)
|
|
228
|
+
|
|
229
|
+
async def _delete_remote(self, ref: str, state: dict) -> None:
|
|
230
|
+
try:
|
|
231
|
+
if state.get("connection_mode") == "shared":
|
|
232
|
+
from agent_wallet.kernel_gateway import KernelGateway
|
|
233
|
+
closed = await KernelGateway(self.vault, state["gateway_url"]).close(state["lease_id"])
|
|
234
|
+
if not closed:
|
|
235
|
+
return
|
|
236
|
+
else:
|
|
237
|
+
await KernelClient().call("DELETE", "/browsers/" + quote(state["session_id"], safe=""), missing_ok=True)
|
|
238
|
+
state["cleanup_pending"] = False
|
|
239
|
+
state.pop("session_key", None)
|
|
240
|
+
self.storage.save(ref, state)
|
|
241
|
+
except Exception:
|
|
242
|
+
pass # Retry via close; remote session also has a short inactivity TTL.
|
|
243
|
+
|
|
244
|
+
async def invoke(self, args: dict) -> dict:
|
|
245
|
+
if set(args) - set(BROWSER_SCHEMA["properties"]):
|
|
246
|
+
raise WalletBackendError("Unsupported Kernel browser arguments.")
|
|
247
|
+
action = args.get("action")
|
|
248
|
+
if action not in BROWSER_SCHEMA["properties"]["action"]["enum"]:
|
|
249
|
+
raise WalletBackendError("Unsupported Kernel browser action.")
|
|
250
|
+
if action == "open":
|
|
251
|
+
if set(args) - {"action", "url", "user_intent"} or args.get("user_intent") is not True:
|
|
252
|
+
raise WalletBackendError("Opening a billable Kernel browser requires user_intent=true.")
|
|
253
|
+
from agent_wallet.vault_executor import _url, resolve_public_destination
|
|
254
|
+
await resolve_public_destination(_url(args.get("url")))
|
|
255
|
+
if not self.vault.config_path.exists():
|
|
256
|
+
self.vault.ensure_system() # Missing runtime-user vault, no owner unlock/UI.
|
|
257
|
+
self.vault._config()
|
|
258
|
+
self.storage._key() # Require working encryption before creating a paid resource.
|
|
259
|
+
ref = uuid.uuid4().hex
|
|
260
|
+
state = {"status": "allocating", "created_at": int(time.time())}
|
|
261
|
+
try:
|
|
262
|
+
if resolve_kernel_api_key():
|
|
263
|
+
# Existing personal keys and old browser records retain the
|
|
264
|
+
# original direct path. Shared access is selected only here.
|
|
265
|
+
data = await KernelClient().call("POST", "/browsers", {
|
|
266
|
+
"headless": True, "timeout_seconds": 300, "telemetry": {"enabled": False}})
|
|
267
|
+
session = data.get("session_id")
|
|
268
|
+
if not isinstance(session, str) or not 1 <= len(session) <= 256:
|
|
269
|
+
raise WalletBackendError("Kernel did not return a usable browser session.")
|
|
270
|
+
state.update(connection_mode="direct", session_id=session)
|
|
271
|
+
else:
|
|
272
|
+
from agent_wallet.kernel_gateway import KernelGateway
|
|
273
|
+
gateway = KernelGateway(self.vault)
|
|
274
|
+
state.update(connection_mode="shared", gateway_url=gateway.url, lease_id=ref)
|
|
275
|
+
# Durable allocation identity BEFORE the billable request.
|
|
276
|
+
# A lost response is closed by this lease, never reallocated.
|
|
277
|
+
self.storage.save(ref, state)
|
|
278
|
+
state.update(await gateway.allocate(ref))
|
|
279
|
+
state["status"] = "open"
|
|
280
|
+
self.storage.save(ref, state)
|
|
281
|
+
result = await self.client(state).execute(state["session_id"], PAGE + "await p.goto(" + _json(args["url"]) + ", {waitUntil:'domcontentloaded',timeout:30000});\n" + SNAPSHOT)
|
|
282
|
+
except BaseException:
|
|
283
|
+
await self.close(ref, state)
|
|
284
|
+
raise
|
|
285
|
+
return {**self.safe(ref, state), "page": result, "untrusted_page_content": True}
|
|
286
|
+
ref = args.get("browser_reference")
|
|
287
|
+
allowed = {"action", "browser_reference"}
|
|
288
|
+
if action == "inspect":
|
|
289
|
+
allowed.add("selector")
|
|
290
|
+
if action in {"click", "fill", "select", "press"}:
|
|
291
|
+
allowed |= {"selector", "user_intent"}
|
|
292
|
+
if action != "click":
|
|
293
|
+
allowed.add("value")
|
|
294
|
+
if set(args) - allowed:
|
|
295
|
+
raise WalletBackendError("Unsupported arguments for this browser action.")
|
|
296
|
+
async with self.vault.async_record_lock(ref):
|
|
297
|
+
state = self.storage.load(ref)
|
|
298
|
+
if action == "close":
|
|
299
|
+
await self.close(ref, state)
|
|
300
|
+
return self.safe(ref, state)
|
|
301
|
+
if action == "status":
|
|
302
|
+
return self.safe(ref, state)
|
|
303
|
+
if state["status"] != "open":
|
|
304
|
+
raise WalletBackendError("Browser is reserved for private checkout or closed; observation and interaction are disabled.")
|
|
305
|
+
code = PAGE
|
|
306
|
+
if action == "inspect":
|
|
307
|
+
selector = _selector(args.get("selector"))
|
|
308
|
+
code += "return {elements:await p.locator(" + _json(selector) + ").evaluateAll(es=>es.slice(0,40).map(e=>{const c=e.cloneNode(true); c.querySelectorAll('input,textarea,select,script,style').forEach(x=>x.remove()); return {tag:e.tagName,id:e.id,testid:e.getAttribute('data-testid'),text:['INPUT','TEXTAREA','SELECT'].includes(e.tagName)?'':String(c.textContent||'').replace(/(?:\\d[ -]?){12,19}/g,'[redacted]').slice(0,512)};}))};"
|
|
309
|
+
result = await self.client(state).execute(state["session_id"], code)
|
|
310
|
+
return {**self.safe(ref, state), "page": result, "untrusted_page_content": True}
|
|
311
|
+
if action != "observe":
|
|
312
|
+
if args.get("user_intent") is not True:
|
|
313
|
+
raise WalletBackendError("Browser interaction requires user_intent=true for the user's task.")
|
|
314
|
+
selector = _selector(args.get("selector"))
|
|
315
|
+
value = args.get("value")
|
|
316
|
+
if action != "click" and (not isinstance(value, str) or len(value) > 2048):
|
|
317
|
+
raise WalletBackendError("A public form value of at most 2048 characters is required.")
|
|
318
|
+
if action == "press" and value not in {"Tab", "Enter", "Escape", "ArrowDown", "ArrowUp"}:
|
|
319
|
+
raise WalletBackendError("Unsupported browser key.")
|
|
320
|
+
method = {"click": "click", "fill": "fill", "select": "selectOption", "press": "press"}[action]
|
|
321
|
+
code += "const el=p.locator(" + _json(selector) + "); if(await el.count()!==1) throw new Error('target count'); await el." + method + "(" + (_json(value) if action != "click" else "") + ");\n"
|
|
322
|
+
result = await self.client(state).execute(state["session_id"], code + SNAPSHOT)
|
|
323
|
+
return {**self.safe(ref, state), "page": result, "untrusted_page_content": True}
|
|
324
|
+
|
|
325
|
+
async def preflight(self, plan: dict, *, operation_id: str | None = None) -> None:
|
|
326
|
+
ref = plan["browser_reference"]
|
|
327
|
+
async with self.vault.async_record_lock(ref):
|
|
328
|
+
state = self.storage.load(ref)
|
|
329
|
+
if state["status"] != "open" and not (state["status"] == "reserved" and state.get("operation_id") == operation_id):
|
|
330
|
+
raise WalletBackendError("Kernel browser is unavailable or reserved for another operation.")
|
|
331
|
+
result = await self.client(state).execute(state["session_id"], self._check_code(plan) + "return {ready:true};")
|
|
332
|
+
if result.get("ready") is not True:
|
|
333
|
+
raise WalletBackendError("Checkout page is not ready.")
|
|
334
|
+
if operation_id:
|
|
335
|
+
state.update(status="reserved", operation_id=operation_id)
|
|
336
|
+
self.storage.save(ref, state)
|
|
337
|
+
|
|
338
|
+
@staticmethod
|
|
339
|
+
def _check_code(plan: dict) -> str:
|
|
340
|
+
# Exact page and displayed total checked both before approval and dispatch.
|
|
341
|
+
return PAGE + "const plan=" + _json(plan) + ";\n" + r"""
|
|
342
|
+
if(p.url()!==plan.page_url) throw new Error('page changed');
|
|
343
|
+
const fillOnly=plan.action==='fill_only';
|
|
344
|
+
const total=p.locator(plan.total_selector), submit=fillOnly?null:p.locator(plan.submit_selector), success=fillOnly?null:p.locator(plan.success_selector);
|
|
345
|
+
if(await total.count()!==1 || (await total.innerText()).trim()!==plan.expected_total.trim()) throw new Error('total changed');
|
|
346
|
+
if(!fillOnly && (await submit.count()!==1 || !(await submit.isVisible()))) throw new Error('submit unavailable');
|
|
347
|
+
if(!fillOnly && (await success.count()>1 || await success.isVisible())) throw new Error('success already present');
|
|
348
|
+
const targets=[], targetFrames=[];
|
|
349
|
+
for(const b of plan.fields){
|
|
350
|
+
const frames=b.frame_url?p.frames().filter(f=>f.url()===b.frame_url):[p.mainFrame()];
|
|
351
|
+
if(frames.length!==1) throw new Error('frame count');
|
|
352
|
+
const el=frames[0].locator(b.selector);
|
|
353
|
+
if(await el.count()!==1 || !(await el.isVisible()) || !(await el.isEditable())) throw new Error('field unavailable');
|
|
354
|
+
const tag=await el.evaluate(e=>e.tagName); if(!['INPUT','SELECT','TEXTAREA'].includes(tag)) throw new Error('field type');
|
|
355
|
+
targets.push(el); targetFrames.push(frames[0]);
|
|
356
|
+
}
|
|
357
|
+
for(let i=0;i<targets.length;i++) for(let j=i+1;j<targets.length;j++)
|
|
358
|
+
if(targetFrames[i]===targetFrames[j] && await targets[i].evaluate((e,other)=>e===other,await targets[j].elementHandle())) throw new Error('duplicate target');
|
|
359
|
+
"""
|
|
360
|
+
|
|
361
|
+
@staticmethod
|
|
362
|
+
def select_fields(plan: dict, fields: dict[str, str]) -> list[str]:
|
|
363
|
+
"""Resolve every requested secret before dispatch/private state changes."""
|
|
364
|
+
values = dict(fields)
|
|
365
|
+
try:
|
|
366
|
+
values.update({"card.expiry": fields["card.exp_month"] + "/" + fields["card.exp_year"],
|
|
367
|
+
"card.expiry_short": fields["card.exp_month"] + "/" + fields["card.exp_year"][-2:],
|
|
368
|
+
"card.exp_year_short": fields["card.exp_year"][-2:]})
|
|
369
|
+
return [values[b["field"]] for b in plan["fields"]]
|
|
370
|
+
except KeyError:
|
|
371
|
+
raise WalletBackendError("The saved card is missing a requested checkout field; no private fill was started.") from None
|
|
372
|
+
finally:
|
|
373
|
+
values.clear()
|
|
374
|
+
|
|
375
|
+
async def checkout(self, plan: dict, selected: list[str], operation_id: str) -> dict:
|
|
376
|
+
ref = plan["browser_reference"]
|
|
377
|
+
async with self.vault.async_record_lock(ref):
|
|
378
|
+
state = self.storage.load(ref)
|
|
379
|
+
if state.get("operation_id") != operation_id or state["status"] != "reserved":
|
|
380
|
+
raise WalletBackendError("Checkout session is not reserved by this operation.")
|
|
381
|
+
state["status"] = "private"
|
|
382
|
+
self.storage.save(ref, state) # No future DOM/observation access, including on crash.
|
|
383
|
+
try:
|
|
384
|
+
# Values are encoded as JSON data literals, never inserted as executable JS.
|
|
385
|
+
# No logs or errors escape this call. Kernel still processes the request.
|
|
386
|
+
code = r"""
|
|
387
|
+
let fillStarted=false, phase='precheck', filledFields=0, submitAttempted=false, submitCompleted=false;
|
|
388
|
+
async function finish(outcome,reason){
|
|
389
|
+
const diagnostic={phase,reason,filled_fields:filledFields,submit_attempted:submitAttempted,submit_completed:submitCompleted};
|
|
390
|
+
let invalid=0, alerts=0; const categories=new Set(), errors=new Set();
|
|
391
|
+
// Read only inside the private executor; return fixed categories/counts, never text/values.
|
|
392
|
+
try {
|
|
393
|
+
for(const context of browser.contexts()) for(const page of context.pages()) for(const frame of page.frames().slice(0,20)) {
|
|
394
|
+
try {
|
|
395
|
+
const d=await frame.evaluate(()=>{
|
|
396
|
+
const visible=e=>!!e.getClientRects().length && getComputedStyle(e).visibility!=='hidden';
|
|
397
|
+
const invalid=Array.from(document.querySelectorAll('input:invalid,select:invalid,textarea:invalid,[aria-invalid="true"]')).filter(visible);
|
|
398
|
+
const categories=invalid.map(e=>{
|
|
399
|
+
const a=e.getAttribute('autocomplete')||'', id=e.id.toLowerCase();
|
|
400
|
+
if(a==='cc-number'||id==='cardnumber') return 'card_number';
|
|
401
|
+
if(a==='cc-exp'||id==='cardexpiry') return 'card_expiry';
|
|
402
|
+
if(a==='cc-csc'||id==='cardcvc') return 'card_cvv';
|
|
403
|
+
if(a.includes('email')||e.type==='email'||id==='email') return 'email';
|
|
404
|
+
if(a.includes('tel')||e.type==='tel'||id.includes('phone')) return 'phone';
|
|
405
|
+
if(a.includes('postal-code')||id.includes('postal')) return 'postal_code';
|
|
406
|
+
if(a.includes('name')||id.includes('name')) return 'name';
|
|
407
|
+
if(a.includes('address')||a.includes('country')||id.includes('shipping')) return 'address';
|
|
408
|
+
return 'other';
|
|
409
|
+
});
|
|
410
|
+
const text=(document.body?.innerText||'').slice(0,65536), errors=[];
|
|
411
|
+
if(/card (?:was |has been )?declined/i.test(text)) errors.push('card_declined');
|
|
412
|
+
if(/(?:invalid|incorrect) card number|card number is (?:invalid|incorrect|incomplete)/i.test(text)) errors.push('card_invalid');
|
|
413
|
+
if(/(?:invalid|incorrect|expired) expir|expir(?:y|ation).*?(?:invalid|incorrect|incomplete)/i.test(text)) errors.push('expiry_invalid');
|
|
414
|
+
if(/(?:security code|cvc|cvv).*?(?:invalid|incorrect|incomplete)/i.test(text)) errors.push('cvv_invalid');
|
|
415
|
+
if(/authentication required|verify your identity|3d secure/i.test(text)) errors.push('authentication_required');
|
|
416
|
+
if(/(?:payments?|checkout).*?(?:disabled|not supported).*?demo|cannot (?:pay|process).*?demo/i.test(text)) errors.push('demo_restriction');
|
|
417
|
+
return {invalid:invalid.length,categories,errors,alerts:Array.from(document.querySelectorAll('[role="alert"]')).filter(visible).length};
|
|
418
|
+
});
|
|
419
|
+
invalid+=d.invalid; alerts+=d.alerts; d.categories.forEach(x=>categories.add(x)); d.errors.forEach(x=>errors.add(x));
|
|
420
|
+
} catch (_) {}
|
|
421
|
+
}
|
|
422
|
+
diagnostic.invalid_fields=Math.min(1000,invalid); diagnostic.visible_alerts=Math.min(1000,alerts);
|
|
423
|
+
diagnostic.invalid_field_categories=[...categories]; diagnostic.error_categories=[...errors];
|
|
424
|
+
} catch (_) {}
|
|
425
|
+
return {outcome,diagnostic};
|
|
426
|
+
}
|
|
427
|
+
try {
|
|
428
|
+
""" + self._check_code(plan) + "const values=" + _json(selected) + ";\n" + r"""
|
|
429
|
+
phase='fill';
|
|
430
|
+
for(let i=0;i<targets.length;i++) {
|
|
431
|
+
if(p.url()!==plan.page_url) return await finish(fillStarted?'unknown':'not_started','page_changed');
|
|
432
|
+
const tag=await targets[i].evaluate(e=>e.tagName);
|
|
433
|
+
// Input/change handlers may have effects even if this fill later fails.
|
|
434
|
+
fillStarted=true;
|
|
435
|
+
if(tag==='SELECT') await targets[i].selectOption(values[i]); else await targets[i].fill(values[i]);
|
|
436
|
+
filledFields++;
|
|
437
|
+
}
|
|
438
|
+
phase='verify_total';
|
|
439
|
+
if(p.url()!==plan.page_url) return await finish('unknown','page_changed');
|
|
440
|
+
if((await total.innerText()).trim()!==plan.expected_total.trim()) return await finish('unknown','total_changed');
|
|
441
|
+
if(fillOnly) { phase='complete'; return await finish('fields_filled','filled_without_submit'); }
|
|
442
|
+
if(await success.count()>1 || await success.isVisible()) return await finish('unknown','success_already_visible');
|
|
443
|
+
phase='submit'; submitAttempted=true;
|
|
444
|
+
await submit.click({timeout:8000}); submitCompleted=true;
|
|
445
|
+
phase='confirmation';
|
|
446
|
+
await success.waitFor({state:'visible',timeout:20000});
|
|
447
|
+
if(new URL(p.url()).origin!==new URL(plan.page_url).origin) return await finish('unknown','origin_changed');
|
|
448
|
+
phase='complete'; return await finish('merchant_confirmation_observed','completed');
|
|
449
|
+
} catch (_) {
|
|
450
|
+
const reason={precheck:'precheck_failed',fill:'fill_failed',verify_total:'total_changed',submit:'submit_failed',confirmation:'confirmation_not_observed'}[phase]||'precheck_failed';
|
|
451
|
+
return await finish(fillStarted?'unknown':'not_started',reason);
|
|
452
|
+
}
|
|
453
|
+
"""
|
|
454
|
+
result = await self.client(state).execute(state["session_id"], code)
|
|
455
|
+
outcome = result.get("outcome")
|
|
456
|
+
diagnostics = safe_checkout_diagnostics(result.get("diagnostic"))
|
|
457
|
+
fill_only = plan.get("action") == "fill_only"
|
|
458
|
+
status = "outcome_unknown"
|
|
459
|
+
if outcome == "not_started":
|
|
460
|
+
status = "checkout_unavailable"
|
|
461
|
+
elif fill_only and outcome == "fields_filled":
|
|
462
|
+
if (diagnostics.get("filled_fields") == len(plan["fields"])
|
|
463
|
+
and diagnostics.get("submit_attempted") is False
|
|
464
|
+
and diagnostics.get("submit_completed") is False):
|
|
465
|
+
status = "checkout_filled"
|
|
466
|
+
elif not fill_only and outcome == "merchant_confirmation_observed":
|
|
467
|
+
status = "checkout_submitted"
|
|
468
|
+
return {"status": status,
|
|
469
|
+
"merchant_confirmation_observed": status == "checkout_submitted",
|
|
470
|
+
"checkout_diagnostics": diagnostics}
|
|
471
|
+
finally:
|
|
472
|
+
await self.close(ref, state)
|
|
473
|
+
|
|
474
|
+
async def cleanup(self, plan: dict, operation_id: str) -> None:
|
|
475
|
+
ref = plan["browser_reference"]
|
|
476
|
+
async with self.vault.async_record_lock(ref):
|
|
477
|
+
state = self.storage.load(ref)
|
|
478
|
+
if state.get("operation_id") == operation_id:
|
|
479
|
+
await self.close(ref, state)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Owner-only terminal connection for Kernel; API keys never travel through tools."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import getpass
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import stat
|
|
9
|
+
|
|
10
|
+
from agent_wallet.config import resolve_boot_key, resolve_kernel_api_key, resolve_kernel_gateway_url, clear_secret_caches
|
|
11
|
+
from agent_wallet.kernel_browser import KernelClient
|
|
12
|
+
from agent_wallet.sealed_keys import resolve_sealed_keys_path, seal_keys, unseal_keys
|
|
13
|
+
from agent_wallet.wallet_layer.base import WalletBackendError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def run(command: str) -> int:
|
|
17
|
+
if command == "kernel-status":
|
|
18
|
+
personal = bool(resolve_kernel_api_key())
|
|
19
|
+
print(json.dumps({"configured": personal, "provider": "kernel",
|
|
20
|
+
"connection_mode": "direct" if personal else "shared_auto",
|
|
21
|
+
"shared_gateway_url": resolve_kernel_gateway_url() if not personal else None}))
|
|
22
|
+
return 0
|
|
23
|
+
from agent_wallet.card_vault import _file_locks
|
|
24
|
+
fcntl = _file_locks()
|
|
25
|
+
from agent_wallet.card_vault_cli import require_terminal
|
|
26
|
+
require_terminal()
|
|
27
|
+
boot = resolve_boot_key()
|
|
28
|
+
if not boot:
|
|
29
|
+
raise WalletBackendError("Install the wallet runtime before connecting Kernel.")
|
|
30
|
+
key = ""
|
|
31
|
+
if command == "kernel-connect":
|
|
32
|
+
key = getpass.getpass("Kernel API key (hidden): ").strip()
|
|
33
|
+
if not 16 <= len(key) <= 2048 or not key.isascii() or any(c.isspace() for c in key):
|
|
34
|
+
raise WalletBackendError("Invalid Kernel API key format.")
|
|
35
|
+
# Read-only validation; no browser creation or paid checkout.
|
|
36
|
+
asyncio.run(KernelClient(key).call("GET", "/browsers?limit=1"))
|
|
37
|
+
path = resolve_sealed_keys_path()
|
|
38
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
39
|
+
fd = os.open(path.with_suffix(".kernel.lock"), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
40
|
+
try:
|
|
41
|
+
info = os.fstat(fd)
|
|
42
|
+
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
|
|
43
|
+
raise WalletBackendError("Kernel connection lock must be an owner-only regular file.")
|
|
44
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
45
|
+
secrets = unseal_keys(boot)
|
|
46
|
+
if command == "kernel-connect":
|
|
47
|
+
secrets["kernel_api_key"] = key
|
|
48
|
+
else:
|
|
49
|
+
secrets.pop("kernel_api_key", None)
|
|
50
|
+
seal_keys(boot, secrets)
|
|
51
|
+
clear_secret_caches()
|
|
52
|
+
finally:
|
|
53
|
+
key = ""
|
|
54
|
+
os.close(fd)
|
|
55
|
+
print("Kernel connected. API key stored in the encrypted runtime bundle." if command == "kernel-connect"
|
|
56
|
+
else "Personal Kernel key removed. New browsers use shared access automatically when available. Existing direct sessions keep their inactivity timeout.")
|
|
57
|
+
return 0
|