Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(vault): route protected crypto through sandbox iframe (#827)

Call White73d03d97807b
diff --git a/docs/plans/vault-crypto-sandbox.md b/docs/plans/vault-crypto-sandbox.md
index e8bfcd723..748a49230 100644
--- a/docs/plans/vault-crypto-sandbox.md
+++ b/docs/plans/vault-crypto-sandbox.md
@@ -625,9 +625,12 @@ equivocation, the server also controls its own response headers and could omit
`worker-src 'none'` while serving the iframe, allowing a malicious same-origin
Service Worker to persist. `worker-src 'none'` helps in the honest-serve case,
but the parent cannot enforce the sandbox CSP for an equivocated navigation.
-This remains in the central-host equivocation residual bucket, bounded
-operationally by immutable versioned URLs, SRI inside the verified loader,
-reproducible builds, public hash transparency, fail-closed telemetry, and a
+The parent must at least navigate the iframe to the exact URL it fetched and
+hashed; verifying `/index.html` while loading `/index.html?...` reopens the
+equivocation gap as a separate byte request. This remains in the central-host
+equivocation residual bucket, bounded operationally by immutable versioned URLs,
+SRI inside the verified loader, reproducible builds, the sandbox `buildHash`
+ready/handshake gate, public hash transparency, fail-closed telemetry, and a
future browser-supported iframe-integrity or signed-web-bundle mechanism if one
ships.
diff --git a/storage/vault_service.py b/storage/vault_service.py
index 67f4e7c1a..c18ebccdc 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -2968,6 +2968,7 @@ def create_sign_request(
*,
digest: str,
scheme: str,
+ signing_context: dict[str, Any] | None = None,
requester: Any = None,
delivery: dict[str, Any] | None = None,
message_id: str | None = None,
@@ -2997,6 +2998,8 @@ def create_sign_request(
grantable=False,
)
delivery_payload.update({"digest": digest, "scheme": scheme, "card": card})
+ if signing_context is not None:
+ delivery_payload["signing_context"] = signing_context
conn.execute(
vault_requests.insert().values(
id=request_id,
diff --git a/storage/vault_webauthn.py b/storage/vault_webauthn.py
index 61dcc553c..5391cfd65 100644
--- a/storage/vault_webauthn.py
+++ b/storage/vault_webauthn.py
@@ -32,6 +32,7 @@ SUPPORTED_ALGS = {ALG_ES256, ALG_RS256}
_FLAG_UP = 0x01
_FLAG_UV = 0x04
_FLAG_AT = 0x40
+VAULT_SANDBOX_ORIGIN = "https://sandbox.avibe.bot"
class WebAuthnVerificationError(ValueError):
@@ -182,6 +183,34 @@ def _cbor_decode_first(data: bytes) -> Any:
return reader.decode()
+def _is_allowed_sandbox_top_origin(origin: str) -> bool:
+ parsed = urlsplit(str(origin or "").strip())
+ scheme = parsed.scheme.lower()
+ host = (parsed.hostname or "").lower()
+ if not scheme or not host:
+ return False
+ if host in {"localhost", "127.0.0.1", "::1"}:
+ return scheme in {"http", "https"}
+ return scheme == "https" and (host == "avibe.bot" or host.endswith(".avibe.bot"))
+
+
+def _validate_cross_origin_client_data(client_data: dict[str, Any], *, expected_origin: str) -> None:
+ cross_origin = client_data.get("crossOrigin")
+ if cross_origin in {None, False}:
+ return
+ if cross_origin is not True:
+ raise WebAuthnVerificationError("invalid WebAuthn crossOrigin flag")
+ if expected_origin != VAULT_SANDBOX_ORIGIN or client_data.get("origin") != VAULT_SANDBOX_ORIGIN:
+ raise WebAuthnVerificationError("cross-origin WebAuthn assertions are only accepted from the Vault sandbox")
+ top_origin = client_data.get("topOrigin")
+ # Safari may omit topOrigin for delegated WebAuthn; in that case the sandbox origin,
+ # frame policy, and sandbox-side parent allow-list remain the enforceable gates.
+ if top_origin is None:
+ return
+ if not isinstance(top_origin, str) or not _is_allowed_sandbox_top_origin(top_origin):
+ raise WebAuthnVerificationError("unexpected WebAuthn top origin")
+
+
def _client_data(client_data_json_b64: str, *, expected_type: str, expected_challenge_hash: str, expected_origin: str) -> tuple[dict[str, Any], bytes]:
client_data_json = b64decode(client_data_json_b64)
try:
@@ -192,8 +221,7 @@ def _client_data(client_data_json_b64: str, *, expected_type: str, expected_chal
raise WebAuthnVerificationError("unexpected WebAuthn client data type")
if client_data.get("origin") != expected_origin:
raise WebAuthnVerificationError("unexpected WebAuthn origin")
- if client_data.get("crossOrigin") not in {None, False}:
- raise WebAuthnVerificationError("cross-origin WebAuthn assertions are not accepted")
+ _validate_cross_origin_client_data(client_data, expected_origin=expected_origin)
challenge = b64decode(str(client_data.get("challenge") or ""))
if challenge_hash(challenge) != expected_challenge_hash:
raise WebAuthnVerificationError("WebAuthn challenge mismatch")
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index fba490562..0de37fb45 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -855,6 +855,7 @@ def test_public_show_page_clears_show_event_write_cookie(monkeypatch, tmp_path):
cookies = "\n".join(response.headers.getlist("set-cookie"))
assert "vibe_show_event_token=" in cookies
assert "Max-Age=0" in cookies
+ assert "sandbox.avibe.bot" not in response.headers.get("content-security-policy", "")
def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch, tmp_path):
diff --git a/tests/test_vault_api.py b/tests/test_vault_api.py
index cb5fa1096..f603f6459 100644
--- a/tests/test_vault_api.py
+++ b/tests/test_vault_api.py
@@ -5,9 +5,12 @@ REST create delegates sealing to avault and stores only the returned envelope.
from __future__ import annotations
+import base64
+import concurrent.futures
import json
import socket
import tempfile
+import threading
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import Mock
@@ -64,6 +67,15 @@ def _browser_ecdsa_signature_for_digest(digest: str, *, key_value: int = 1) -> t
return public_meta, signature
+def _signing_context(digest: str) -> dict:
+ return {
+ "kind": "avault-agent-operation",
+ "canonicalPreimage": f"vault-sign-test:{digest}",
+ "digestAlgorithm": "avault-operation-hash-v1",
+ "digest": digest,
+ }
+
+
def _assert_no_unlock_material(payload: object) -> None:
encoded = json.dumps(payload)
assert "secret_unlock_material" not in encoded
@@ -1068,6 +1080,88 @@ def test_create_protected_stores_browser_envelope_without_avault(monkeypatch):
assert json.loads(row["wrap_meta"]) == passkey_wrap_meta
+def test_vault_sandbox_root_metadata_persists_daemon_verification_key():
+ first = api.get_vault_sandbox_root_metadata()
+ second = api.get_vault_sandbox_root_metadata()
+
+ key = first["root_metadata"]["daemon"]["verificationKeys"][0]
+ assert key["alg"] == "ed25519"
+ assert key["keyId"] == "vault-daemon-ed25519-v1"
+ assert len(base64.b64decode(key["publicKey"])) == 32
+ assert second["root_metadata"]["daemon"]["verificationKeys"][0]["publicKey"] == key["publicKey"]
+
+
+def test_vault_sandbox_root_metadata_first_key_wins_under_concurrency(monkeypatch):
+ original = api._new_vault_daemon_binding_key
+ barrier = threading.Barrier(6)
+
+ def racing_key() -> dict[str, str]:
+ barrier.wait(timeout=5)
+ return original()
+
+ monkeypatch.setattr(api, "_new_vault_daemon_binding_key", racing_key)
+
+ with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:
+ results = list(executor.map(lambda _index: api.get_vault_sandbox_root_metadata(), range(6)))
+
+ keys = {
+ result["root_metadata"]["daemon"]["verificationKeys"][0]["publicKey"]
+ for result in results
+ }
+ assert len(keys) == 1
+
+
+def test_create_vault_agent_binding_signs_value_free_protected_grant(monkeypatch):
+ from cryptography.hazmat.primitives.asymmetric import ed25519
+
+ monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)
+ monkeypatch.setattr(api, "avault_agent_pubkey", Mock(return_value={"public_key": "agent-pk", "fingerprint": "agent-fp"}))
+ api.create_vault_secret(
+ {
+ "name": "PROTECTED_BINDING",
+ "protection": "protected",
+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": {"v": 1, "copies": [], "wrapped_dek": "d"}},
+ }
+ )
+ with api._vault_engine().begin() as conn:
+ request = vault_service.create_access_request(
+ conn,
+ "PROTECTED_BINDING",
+ requester={"session_id": "ses_binding"},
+ delivery={"session_id": "ses_binding"},
+ )
+ grant_id = request["card"]["grant_options"][0]["grant_id"]
+
+ result = api.create_vault_agent_binding(
+ {"request_id": request["id"], "grant_id": grant_id, "name": "PROTECTED_BINDING", "ttl_seconds": 300}
+ )
+
+ assert result["ok"] is True
+ assert result["agent_pubkey"] == {"public_key": "agent-pk", "fingerprint": "agent-fp"}
+ assert set(result["approval"]) == {"nonce", "expires_at_unix"}
+ binding = dict(result["binding"])
+ signature = binding.pop("signature")
+ root_key = api.get_vault_sandbox_root_metadata()["root_metadata"]["daemon"]["verificationKeys"][0]
+ public_key = ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(root_key["publicKey"]))
+ public_key.verify(
+ base64.b64decode(signature["value"]),
+ json.dumps(binding, sort_keys=True, separators=(",", ":")).encode("utf-8"),
+ )
+ assert signature["alg"] == "ed25519"
+ assert signature["keyId"] == root_key["keyId"]
+ assert binding["requestId"] == request["id"]
+ assert binding["grantId"] == grant_id
+ assert binding["agent"]["fingerprint"] == "agent-fp"
+ context = binding["context"]
+ assert context["purpose"] == "agent-deliver"
+ assert context["name"] == "PROTECTED_BINDING"
+ assert context["grantId"] == grant_id
+ assert context["ttlSecs"] == 300
+ assert isinstance(context["approvalNonce"], list)
+ assert len(context["approvalNonce"]) == 16
+ assert context["operationHash"] == api._agent_deliver_operation_hash("PROTECTED_BINDING", 300)
+
+
def test_protected_create_establishing_vmk_rejects_second_init(monkeypatch):
_establish_protected_secret_with_factor("FIRST_PROTECTED")
with api._vault_engine().connect() as conn:
@@ -1880,6 +1974,7 @@ def test_agent_sign_request_accepts_protected_browser_signature(monkeypatch):
"digest": digest,
"scheme": "ecdsa-secp256k1-recoverable",
"session_id": "ses_1",
+ "signing_context": _signing_context(digest),
}
)
@@ -1895,6 +1990,7 @@ def test_agent_sign_request_accepts_protected_browser_signature(monkeypatch):
assert requested["ok"] is True
assert requested["request"]["card"]["protection"] == "protected"
+ assert requested["request"]["delivery"]["signing_context"] == _signing_context(digest)
assert completed["ok"] is True
assert completed["signature"] == signature
assert api.get_vault_request(requested["request"]["id"])["result"] == {"type": "signature", "signature": signature}
@@ -3160,11 +3256,24 @@ def test_protected_sign_requires_browser_signature(monkeypatch):
"public_meta": public_meta,
}
)
- result = api.vault_sign({"name": "ETH_KEY", "digest": "00" * 32, "scheme": "ecdsa-secp256k1-recoverable"})
+ digest = "00" * 32
+ with pytest.raises(api.VaultApiError) as exc:
+ api.vault_sign({"name": "ETH_KEY", "digest": digest, "scheme": "ecdsa-secp256k1-recoverable"})
+ assert exc.value.code == "missing_signing_context"
+
+ result = api.vault_sign(
+ {
+ "name": "ETH_KEY",
+ "digest": digest,
+ "scheme": "ecdsa-secp256k1-recoverable",
+ "signing_context": _signing_context(digest),
+ }
+ )
assert result["ok"] is False
assert result["code"] == "browser_signature_required"
assert result["request"]["card"]["request_type"] == "sign"
assert result["request"]["card"]["grant_options"] == []
+ assert result["request"]["delivery"]["signing_context"] == _signing_context(digest)
def test_protected_sign_request_requires_pinned_signing_public_key(monkeypatch):
@@ -3182,7 +3291,14 @@ def test_protected_sign_request_requires_pinned_signing_public_key(monkeypatch):
)
with pytest.raises(api.VaultApiError) as exc:
- api.vault_sign({"name": "ETH_KEY", "digest": "00" * 32, "scheme": "ecdsa-secp256k1-recoverable"})
+ api.vault_sign(
+ {
+ "name": "ETH_KEY",
+ "digest": "00" * 32,
+ "scheme": "ecdsa-secp256k1-recoverable",
+ "signing_context": _signing_context("00" * 32),
+ }
+ )
assert exc.value.code == "invalid_request"
assert "per-use signable" in str(exc.value)
@@ -3232,7 +3348,14 @@ def test_protected_sign_completion_requires_matching_request(monkeypatch):
api.vault_sign({"name": "ETH_KEY", "digest": digest, "scheme": "ecdsa-secp256k1-recoverable", "signature": {"signature": "sig"}})
assert exc.value.code == "missing_request_id"
- pending = api.vault_sign({"name": "ETH_KEY", "digest": digest, "scheme": "ecdsa-secp256k1-recoverable"})
+ pending = api.vault_sign(
+ {
+ "name": "ETH_KEY",
+ "digest": digest,
+ "scheme": "ecdsa-secp256k1-recoverable",
+ "signing_context": _signing_context(digest),
+ }
+ )
request_id = pending["request"]["id"]
with pytest.raises(api.VaultApiError) as exc:
api.vault_sign(
@@ -3280,7 +3403,14 @@ def test_protected_sign_completion_rejects_malformed_browser_signature(monkeypat
}
)
digest = "00" * 32
- pending = api.vault_sign({"name": "ETH_KEY", "digest": digest, "scheme": "ecdsa-secp256k1-recoverable"})
+ pending = api.vault_sign(
+ {
+ "name": "ETH_KEY",
+ "digest": digest,
+ "scheme": "ecdsa-secp256k1-recoverable",
+ "signing_context": _signing_context(digest),
+ }
+ )
with pytest.raises(api.VaultApiError) as exc:
api.vault_sign(
@@ -3312,7 +3442,14 @@ def test_protected_sign_completion_rejects_signature_extra_fields(monkeypatch):
"public_meta": public_meta,
}
)
- pending = api.vault_sign({"name": "ETH_KEY", "digest": digest, "scheme": "ecdsa-secp256k1-recoverable"})
+ pending = api.vault_sign(
+ {
+ "name": "ETH_KEY",
+ "digest": digest,
+ "scheme": "ecdsa-secp256k1-recoverable",
+ "signing_context": _signing_context(digest),
+ }
+ )
with pytest.raises(api.VaultApiError) as exc:
api.vault_sign(
@@ -3352,7 +3489,14 @@ def test_protected_sign_completion_rejects_signature_that_does_not_verify(monkey
"public_meta": public_meta,
}
)
- pending = api.vault_sign({"name": "ETH_KEY", "digest": digest, "scheme": "ecdsa-secp256k1-recoverable"})
+ pending = api.vault_sign(
+ {
+ "name": "ETH_KEY",
+ "digest": digest,
+ "scheme": "ecdsa-secp256k1-recoverable",
+ "signing_context": _signing_context(digest),
+ }
+ )
with pytest.raises(api.VaultApiError) as exc:
api.vault_sign(
@@ -3392,7 +3536,14 @@ def test_protected_sign_completion_rejects_wrong_recovery_id(monkeypatch):
"public_meta": public_meta,
}
)
- pending = api.vault_sign({"name": "ETH_KEY", "digest": digest, "scheme": "ecdsa-secp256k1-recoverable"})
+ pending = api.vault_sign(
+ {
+ "name": "ETH_KEY",
+ "digest": digest,
+ "scheme": "ecdsa-secp256k1-recoverable",
+ "signing_context": _signing_context(digest),
+ }
+ )
with pytest.raises(api.VaultApiError) as exc:
api.vault_sign(
@@ -3437,7 +3588,14 @@ def test_protected_sign_completion_verifies_schnorr_browser_signature(monkeypatc
},
}
)
- pending = api.vault_sign({"name": "ETH_KEY", "digest": digest, "scheme": "schnorr-secp256k1-bip340"})
+ pending = api.vault_sign(
+ {
+ "name": "ETH_KEY",
+ "digest": digest,
+ "scheme": "schnorr-secp256k1-bip340",
+ "signing_context": _signing_context(digest),
+ }
+ )
result = api.vault_sign(
{
diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.py
index 53f4e399c..2bdf8bb0a 100644
--- a/tests/test_vault_cli.py
+++ b/tests/test_vault_cli.py
@@ -64,6 +64,17 @@ PROTECTED_SIGNING_PUBLIC_META = {
}
+def _signing_context_json(digest: str) -> str:
+ return json.dumps(
+ {
+ "kind": "avault-agent-operation",
+ "canonicalPreimage": f"vault-sign-test:{digest}",
+ "digestAlgorithm": "avault-operation-hash-v1",
+ "digest": digest,
+ }
+ )
+
+
def _create_standard_secret(name: str, *, sealed: Sealed | None = None, **kwargs):
with cli._open_vault_engine().begin() as conn:
return vault_service.create_secret(conn, name=name, sealed=sealed or _sealed(), **kwargs)
@@ -589,7 +600,7 @@ def test_sign_request_and_await_cli_reads_approved_signature_for_always_ask_stan
assert payload["result"] == {"type": "signature", "signature": {"signature": "ab" * 64, "recovery_id": 1}}
-def test_sign_request_cli_accepts_protected_keypair(capfd):
+def test_sign_request_cli_requires_context_for_protected_keypair(capfd):
with cli._open_vault_engine().begin() as conn:
vault_service.create_secret(
conn,
@@ -601,13 +612,28 @@ def test_sign_request_cli_accepts_protected_keypair(capfd):
public_meta=PROTECTED_SIGNING_PUBLIC_META,
)
- assert cli.cmd_vault_sign(_ns(name="PROTECTED_ETH_KEY", digest="00" * 32, scheme="ecdsa-secp256k1-recoverable")) == 0
+ assert cli.cmd_vault_sign(_ns(name="PROTECTED_ETH_KEY", digest="00" * 32, scheme="ecdsa-secp256k1-recoverable")) == 1
+ error = json.loads(capfd.readouterr().err)
+ assert error["code"] == "missing_signing_context"
+
+ assert (
+ cli.cmd_vault_sign(
+ _ns(
+ name="PROTECTED_ETH_KEY",
+ digest="00" * 32,
+ scheme="ecdsa-secp256k1-recoverable",
+ signing_context_json=_signing_context_json("00" * 32),
+ )
+ )
+ == 0
+ )
payload = json.loads(capfd.readouterr().out)
assert payload["kind"] == "vault_sign_request"
assert payload["request"]["secret_name"] == "PROTECTED_ETH_KEY"
assert payload["request"]["card"]["protection"] == "protected"
assert payload["request"]["card"]["grant_options"] == []
+ assert payload["request"]["delivery"]["signing_context"] == json.loads(_signing_context_json("00" * 32))
def test_vault_await_wait_treats_failed_request_as_terminal(capfd):
diff --git a/tests/test_vault_rest.py b/tests/test_vault_rest.py
index 231b7eae1..70a9f6a02 100644
--- a/tests/test_vault_rest.py
+++ b/tests/test_vault_rest.py
@@ -179,6 +179,36 @@ def test_rest_agent_pubkey_route(monkeypatch):
assert response.get_json() == {"ok": True, "public_key": "pk", "fingerprint": "fp"}
+def test_rest_security_headers_delegate_webauthn_to_sandbox_only():
+ client = app.test_client()
+
+ response = client.get("/api/csrf-token")
+
+ permissions = response.headers["Permissions-Policy"]
+ assert 'publickey-credentials-get=("https://sandbox.avibe.bot")' in permissions
+ assert 'publickey-credentials-create=("https://sandbox.avibe.bot")' in permissions
+ assert 'clipboard-write=(self "https://sandbox.avibe.bot")' in permissions
+ assert "publickey-credentials-get=(self" not in permissions
+ assert "publickey-credentials-create=(self" not in permissions
+ assert "frame-src 'self' https://sandbox.avibe.bot" in response.headers["Content-Security-Policy"]
+
+
+def test_rest_vault_authz_options_use_sandbox_rp_origin():
+ client = app.test_client()
+
+ response = client.post(
+ "/api/vault/authz/factors/webauthn/options",
+ json={},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ payload = response.get_json()
+ assert payload["rp_id"] == "sandbox.avibe.bot"
+ assert payload["origin"] == "https://sandbox.avibe.bot"
+ assert payload["webauthn"]["rp"]["id"] == "sandbox.avibe.bot"
+
+
def test_rest_requests_and_grants_routes(monkeypatch):
_mock_avault_p2(monkeypatch)
monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
diff --git a/tests/test_vault_service.py b/tests/test_vault_service.py
index f2cdedee0..6c1edf035 100644
--- a/tests/test_vault_service.py
+++ b/tests/test_vault_service.py
@@ -420,6 +420,96 @@ def test_webauthn_factor_registration_stores_public_key(vault):
assert json.loads(row["transports"]) == ["internal"]
+def test_sandbox_cross_origin_webauthn_registration_and_assertion_accept_allowed_parent(vault):
+ credential = WebAuthnTestCredential(rp_id="sandbox.avibe.bot", origin="https://sandbox.avibe.bot")
+
+ with vault.begin() as conn:
+ options = vs.create_webauthn_registration_options(conn, rp_id=credential.rp_id, origin=credential.origin)
+ registration = credential.registration_payload(
+ challenge_id=options["challenge_id"],
+ challenge_b64=options["webauthn"]["challenge"],
+ cross_origin=True,
+ top_origin="http://localhost:5173",
+ )
+ factor = vs.register_webauthn_factor(conn, registration, rp_id=credential.rp_id, origin=credential.origin, establishment=True)[
+ "factor"
+ ]
+
+ with vault.connect() as conn:
+ factor_row = conn.execute(select(vault_auth_factors).where(vault_auth_factors.c.id == factor["id"])).mappings().one()
+ public_key = factor_row["public_key"]
+ challenge = b"sandbox-cross-origin-challenge"
+ challenge_b64 = vault_webauthn.b64encode(challenge)
+ allowed_assertion = credential.assertion_authz(
+ challenge_id="vop_cross_origin",
+ factor_id=factor["id"],
+ challenge_b64=challenge_b64,
+ sign_count=2,
+ cross_origin=True,
+ top_origin="https://team.avibe.bot",
+ )["assertion"]
+ assert (
+ vault_webauthn.verify_assertion(
+ allowed_assertion,
+ credential_id=credential.credential_id_b64,
+ public_key=public_key,
+ alg=vault_webauthn.ALG_ES256,
+ stored_sign_count=1,
+ expected_challenge_hash=vault_webauthn.challenge_hash(challenge),
+ expected_origin=credential.origin,
+ rp_id=credential.rp_id,
+ ).sign_count
+ == 2
+ )
+
+ safari_assertion = credential.assertion_authz(
+ challenge_id="vop_cross_origin",
+ factor_id=factor["id"],
+ challenge_b64=challenge_b64,
+ sign_count=3,
+ cross_origin=True,
+ )["assertion"]
+ assert (
+ vault_webauthn.verify_assertion(
+ safari_assertion,
+ credential_id=credential.credential_id_b64,
+ public_key=public_key,
+ alg=vault_webauthn.ALG_ES256,
+ stored_sign_count=2,
+ expected_challenge_hash=vault_webauthn.challenge_hash(challenge),
+ expected_origin=credential.origin,
+ rp_id=credential.rp_id,
+ ).sign_count
+ == 3
+ )
+
+
+def test_sandbox_cross_origin_webauthn_rejects_wrong_top_origin():
+ credential = WebAuthnTestCredential(rp_id="sandbox.avibe.bot", origin="https://sandbox.avibe.bot")
+ challenge = b"sandbox-cross-origin-challenge"
+ challenge_b64 = vault_webauthn.b64encode(challenge)
+
+ assertion = credential.assertion_authz(
+ challenge_id="vop_cross_origin",
+ factor_id="vaf_cross_origin",
+ challenge_b64=challenge_b64,
+ cross_origin=True,
+ top_origin="https://evil.example",
+ )["assertion"]
+
+ with pytest.raises(vault_webauthn.WebAuthnVerificationError, match="top origin"):
+ vault_webauthn.verify_assertion(
+ assertion,
+ credential_id=credential.credential_id_b64,
+ public_key=vault_webauthn.b64encode(credential.public_key_cose()),
+ alg=vault_webauthn.ALG_ES256,
+ stored_sign_count=0,
+ expected_challenge_hash=vault_webauthn.challenge_hash(challenge),
+ expected_origin=credential.origin,
+ rp_id=credential.rp_id,
+ )
+
+
def test_delete_challenge_expiry_and_replay_are_rejected(vault):
credential = WebAuthnTestCredential()
diff --git a/tests/vault_webauthn_helpers.py b/tests/vault_webauthn_helpers.py
index 6a43330a4..0b6549924 100644
--- a/tests/vault_webauthn_helpers.py
+++ b/tests/vault_webauthn_helpers.py
@@ -76,16 +76,23 @@ def _cbor(value) -> bytes:
raise TypeError(f"unsupported CBOR test value: {type(value).__name__}")
-def _client_data(*, typ: str, challenge_b64: str, origin: str) -> bytes:
- return json.dumps(
- {
- "type": typ,
- "challenge": _b64url(_b64decode(challenge_b64)),
- "origin": origin,
- "crossOrigin": False,
- },
- separators=(",", ":"),
- ).encode("utf-8")
+def _client_data(
+ *,
+ typ: str,
+ challenge_b64: str,
+ origin: str,
+ cross_origin: bool = False,
+ top_origin: str | None = None,
+) -> bytes:
+ payload = {
+ "type": typ,
+ "challenge": _b64url(_b64decode(challenge_b64)),
+ "origin": origin,
+ "crossOrigin": cross_origin,
+ }
+ if top_origin is not None:
+ payload["topOrigin"] = top_origin
+ return json.dumps(payload, separators=(",", ":")).encode("utf-8")
@dataclass
@@ -124,11 +131,15 @@ class WebAuthnTestCredential:
challenge_b64: str,
sign_count: int = 1,
public_key_cose: bytes | None = None,
+ cross_origin: bool = False,
+ top_origin: str | None = None,
) -> dict:
client_data = _client_data(
typ=vault_webauthn.WEBAUTHN_CREATE_TYPE,
challenge_b64=challenge_b64,
origin=self.origin,
+ cross_origin=cross_origin,
+ top_origin=top_origin,
)
flags = 0x01 | 0x04 | 0x40
auth_data = (
@@ -162,11 +173,15 @@ class WebAuthnTestCredential:
factor_id: str,
challenge_b64: str,
sign_count: int = 2,
+ cross_origin: bool = False,
+ top_origin: str | None = None,
) -> dict:
client_data = _client_data(
typ=vault_webauthn.WEBAUTHN_GET_TYPE,
challenge_b64=challenge_b64,
origin=self.origin,
+ cross_origin=cross_origin,
+ top_origin=top_origin,
)
auth_data = (
hashlib.sha256(self.rp_id.encode("utf-8")).digest()
diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsx
index 96704e556..4b75bbad4 100644
--- a/ui/src/components/ui/vault-approval-card.tsx
+++ b/ui/src/components/ui/vault-approval-card.tsx
@@ -6,13 +6,7 @@ import { useApi, type SigningAddresses, type VaultRequest, type VaultSourceSelec
import { partitionTags } from '@/lib/vaultTags';
import { useProtectedVault, type ProtectedUnlockMaterial } from '@/lib/useProtectedVault';
import { SigningAddressList } from './signing-address-list';
-import {
- blindBoxAgentDeliverOperationHash,
- bytesToBase64,
- protectedDekReleaseBlindBoxContext,
- type BlindBox,
- type SignatureScheme,
-} from '@/lib/vaultCrypto';
+import { type BlindBox, type SignatureScheme } from '@/lib/vaultCrypto';
import { cn, copyTextToClipboard } from '@/lib/utils';
import { Badge } from './badge';
import { Button } from './button';
@@ -113,7 +107,12 @@ export const VaultApprovalCard: React.FC<{
// `grant_options[].unlock_material` are present for protected requests. No fetch or
// loading state is needed here — the single-request GET is agent-audience (value-free).
const card = (request.card ?? null) as ApprovalCard | null;
- const delivery = (request.delivery ?? {}) as { digest?: string; scheme?: string };
+ const delivery = (request.delivery ?? {}) as {
+ digest?: string;
+ scheme?: string;
+ signing_context?: Record<string, unknown>;
+ signingContext?: Record<string, unknown>;
+ };
const isSign = (card?.request_type ?? request.request_type) === 'sign';
const isKeypair = card?.kind === 'keypair';
@@ -218,30 +217,30 @@ export const VaultApprovalCard: React.FC<{
}),
);
} else {
- // Protected members — release each DEK in the browser as an opaque HPKE blind box
- // addressed to the resident avault agent, then relay only those boxes.
- const pubkey = await api.getVaultAgentPubkey();
- const agentPubkey = { public_key: pubkey.public_key, fingerprint: pubkey.fingerprint };
- const expiresAtUnix = Math.floor(Date.now() / 1000) + ttlSeconds;
+ // Protected members — ask the daemon for signed, value-free agent bindings, then let the
+ // sandbox release each DEK as an opaque HPKE blind box for that pinned resident agent.
+ let agentPubkey: { public_key: string; fingerprint: string } | null = null;
const deks: Array<{ name: string; dek_blindbox: BlindBox; approval: { nonce: string; expires_at_unix: number } }> = [];
for (const material of materials) {
- const approvalNonce = crypto.getRandomValues(new Uint8Array(16));
- const context = await protectedDekReleaseBlindBoxContext(material.name, {
- kind: 'agent-deliver',
- grantId,
- ttlSecs: ttlSeconds,
- approval: { nonce: approvalNonce, expiresAtUnix },
- operationHash: await blindBoxAgentDeliverOperationHash(material.name, ttlSeconds),
+ const binding = await api.createVaultAgentBinding({
+ request_id: request.id,
+ grant_id: grantId,
+ name: material.name,
+ ttl_seconds: ttlSeconds,
});
- // Value access only ever releases a delivery DEK — never a signing context.
- if (context.purpose !== 'agent-deliver') throw new Error(t('vaults.approval.errors.failed'));
- const dekBlindbox = await vault.releaseProtectedDelivery(material, agentPubkey, context);
+ failIfNotOk(binding);
+ if (agentPubkey && binding.agent_pubkey.fingerprint !== agentPubkey.fingerprint) {
+ throw new Error(t('vaults.approval.errors.failed'));
+ }
+ agentPubkey = binding.agent_pubkey;
+ const dekBlindbox = await vault.releaseProtectedDelivery(material, binding.binding);
deks.push({
name: material.name,
dek_blindbox: dekBlindbox,
- approval: { nonce: bytesToBase64(approvalNonce), expires_at_unix: expiresAtUnix },
+ approval: binding.approval,
});
}
+ if (!agentPubkey) throw new Error(t('vaults.approval.errors.failed'));
failIfNotOk(
await api.fulfillVaultAccessRequest(request.id, {
grant_id: grantId,
@@ -262,10 +261,12 @@ export const VaultApprovalCard: React.FC<{
const scheme = delivery.scheme;
if (!name || !digest || !scheme) throw new Error(t('vaults.approval.errors.missingDigest'));
if (isProtected) {
- // Protected keypair: open + sign locally, submit only the public signature.
+ // Protected keypair: the sandbox opens + signs, parent submits only the public signature.
const material = card?.secret_unlock_material;
if (!material) throw new Error(t('vaults.approval.errors.missingMaterial'));
- const sig = await vault.signProtectedRequest(material, digest, scheme as SignatureScheme);
+ const signingContext = delivery.signing_context ?? delivery.signingContext;
+ if (!signingContext || typeof signingContext !== 'object') throw new Error(t('vaults.approval.errors.missingDigest'));
+ const sig = await vault.signProtectedRequest(material, signingContext, scheme as SignatureScheme);
const signature: Record<string, unknown> = { signature: sig.signature };
if (sig.recovery_id != null) signature.recovery_id = sig.recovery_id;
failIfNotOk(await api.signVaultDigest({ name, request_id: request.id, digest, scheme, signature }));
diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsx
index 86d4bab66..45982ddae 100644
--- a/ui/src/components/ui/vault-secret-form.tsx
+++ b/ui/src/components/ui/vault-secret-form.tsx
@@ -323,7 +323,7 @@ export const VaultSecretForm: React.FC<{
}, [signingKey, api]);
const staticValueReady = staticSource === 'file' ? selectedFile != null && selectedFile.size > 0 : Boolean(value);
- const valueReady = isKeypair ? signingKey != null : staticValueReady;
+ const valueReady = protection === 'protected' ? true : isKeypair ? signingKey != null : staticValueReady;
const canSubmit = isEdit
? !submitting
: Boolean(secretName && valueReady) &&
@@ -375,6 +375,16 @@ export const VaultSecretForm: React.FC<{
}
};
+ useEffect(() => {
+ if (protection !== 'protected') return;
+ setValue('');
+ clearSelectedFile();
+ applySigningKey(null);
+ setImportHex('');
+ setSigningError(null);
+ setSigningAddresses(null);
+ }, [protection]);
+
const onSubmit = async (event: FormEvent) => {
event.preventDefault();
if (!canSubmit) return;
@@ -464,7 +474,7 @@ export const VaultSecretForm: React.FC<{
links: skillLinks.length ? { skills: skillLinks } : undefined,
policy: Object.keys(policy).length ? policy : undefined,
provision_request_id: provisionRequestId || undefined,
- ...(isKeypair && signingKey
+ ...(isKeypair && protection === 'standard' && signingKey
? {
kind: 'keypair',
signer_kind: 'local',
@@ -474,41 +484,52 @@ export const VaultSecretForm: React.FC<{
}
: {}),
};
- // For a signing key the sealed value is the raw 32-byte private key (avault
- // opens it back into a 32-byte signing key); for a static secret it is the
- // entered string.
- let plaintext: Uint8Array | string;
- if (isKeypair && signingKey) {
- plaintext = signingKey.privateKey;
- } else if (staticSource === 'file' && selectedFile) {
- try {
- fileBytesToWipe = new Uint8Array(await selectedFile.arrayBuffer());
- } catch (err) {
- throw new Error(t('vaults.dialog.errors.fileReadFailed'), { cause: err });
- }
- plaintext = fileBytesToWipe;
- } else {
- plaintext = value;
- }
let cryptoFields:
| { sealed: ProtectedRecordEnvelope }
| { blind_box: Awaited<ReturnType<typeof sealBlindBox>> };
let establishingVmk = false;
let authzFactorRegistration: Awaited<ReturnType<typeof protectedVault.sealValue>>['authzFactorRegistration'];
+ let protectedPublicMeta: Record<string, unknown> | undefined;
if (protection === 'protected') {
- // Browser-sealed under the session VMK; the daemon stores it opaquely (no avault, no
- // plaintext). For a signing key this seals the raw 32-byte private key, not a string.
- const sealed = await protectedVault.sealValue(secretName, plaintext);
+ // The sandbox owns protected plaintext/key entry and returns only an opaque envelope
+ // plus public key metadata for keypairs.
+ const sealed = await protectedVault.sealValue(secretName, kind);
cryptoFields = { sealed: sealed.envelope };
establishingVmk = sealed.establishingVmk;
authzFactorRegistration = sealed.authzFactorRegistration;
+ if (isKeypair && !sealed.publicKey) {
+ throw new Error(t('vaults.dialog.errors.invalidPublicKey'));
+ }
+ if (isKeypair) {
+ protectedPublicMeta = {
+ signing_public_key: { curve: 'secp256k1', public_key: sealed.publicKey },
+ ...(sealed.addresses ? { signing_addresses: sealed.addresses } : {}),
+ };
+ }
} else {
+ // For a standard signing key the sealed value is the raw 32-byte private key
+ // (avault opens it back into a 32-byte signing key); for a static secret it is
+ // the entered string.
+ let plaintext: Uint8Array | string;
+ if (isKeypair && signingKey) {
+ plaintext = signingKey.privateKey;
+ } else if (staticSource === 'file' && selectedFile) {
+ try {
+ fileBytesToWipe = new Uint8Array(await selectedFile.arrayBuffer());
+ } catch (err) {
+ throw new Error(t('vaults.dialog.errors.fileReadFailed'), { cause: err });
+ }
+ plaintext = fileBytesToWipe;
+ } else {
+ plaintext = value;
+ }
const pubkey = await api.getVaultPubkey();
cryptoFields = { blind_box: await sealBlindBox(plaintext, pubkey, standardCreateBlindBoxContext(secretName)) };
}
const created = await api.createVaultSecret(
{
...base,
+ ...(protectedPublicMeta ? { kind: 'keypair', signer_kind: 'local', public_meta: protectedPublicMeta } : {}),
...cryptoFields,
...(establishingVmk
? {
@@ -907,11 +928,13 @@ export const VaultSecretForm: React.FC<{
<Badge variant="secondary" className="bg-surface">{t('vaults.request.notSetYet')}</Badge>
</div>
- <label className="flex flex-col gap-1.5">
- <span className={FIELD_LABEL}>{t('vaults.dialog.value')}</span>
- {valueField}
- <span className="text-[11px] text-muted-foreground">{t('vaults.dialog.provisionValueHelp')}</span>
- </label>
+ {protection !== 'protected' && (
+ <label className="flex flex-col gap-1.5">
+ <span className={FIELD_LABEL}>{t('vaults.dialog.value')}</span>
+ {valueField}
+ <span className="text-[11px] text-muted-foreground">{t('vaults.dialog.provisionValueHelp')}</span>
+ </label>
+ )}
<label className="flex flex-col gap-1.5">
<span className={FIELD_LABEL}>{t('vaults.dialog.description')}</span>
@@ -983,14 +1006,14 @@ export const VaultSecretForm: React.FC<{
</label>
{/* Value (static) or signing-key builder (keypair) */}
- {!isKeypair && (
+ {!isKeypair && protection !== 'protected' && (
<label className="flex flex-col gap-1.5">
<span className={FIELD_LABEL}>{t('vaults.dialog.value')}</span>
{valueField}
</label>
)}
- {isKeypair && (
+ {isKeypair && protection === 'standard' && (
<div className="flex flex-col gap-2.5 rounded-[10px] border border-border bg-surface-2 px-3 py-3">
<span className="text-xs text-muted-foreground">{t('vaults.dialog.signingKeyHelp')}</span>
<div className="grid grid-cols-2 gap-2">
@@ -1079,7 +1102,7 @@ export const VaultSecretForm: React.FC<{
{signingError && <span className="text-xs text-destructive">{signingError}</span>}
- {!p2Ready && protection !== 'protected' && (
+ {!p2Ready && (
<div className="rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-xs text-warning">
{t('vaults.dialog.signingNeedsAvault', { version: AVAULT_P2_MIN_VERSION })}
</div>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 195bb0593..6b740ed91 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -130,6 +130,37 @@ export type VaultAccessFulfillmentPayload = {
deks?: Array<{ name: string; dek_blindbox: VaultBlindBox; approval: Record<string, unknown> }>;
};
+export type VaultSandboxRootMetadataResult = {
+ ok: boolean;
+ root_metadata: {
+ daemon: {
+ verificationKeys: Array<{ alg: 'ed25519'; keyId: string; publicKey: string }>;
+ };
+ };
+ code?: string;
+ message?: string;
+};
+
+export type VaultAgentBindingResult = {
+ ok: boolean;
+ agent_pubkey: { public_key: string; fingerprint: string };
+ binding: {
+ challengeId: string;
+ requestId: string;
+ grantId: string;
+ agent: {
+ publicKey: { public_key: string; fingerprint?: string };
+ fingerprint: string;
+ };
+ context: Record<string, unknown>;
+ expiresAt: string;
+ signature: { alg: 'ed25519'; keyId: string; value: string };
+ };
+ approval: { nonce: string; expires_at_unix: number };
+ code?: string;
+ message?: string;
+};
+
type VaultSealedEnvelope = {
ciphertext: string;
nonce: string;
@@ -456,6 +487,13 @@ export type ApiContextType = {
getVaultVmk: () => Promise<VaultVmkResult>;
getVaultPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;
getVaultAgentPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;
+ getVaultSandboxRootMetadata: () => Promise<VaultSandboxRootMetadataResult>;
+ createVaultAgentBinding: (payload: {
+ request_id: string;
+ grant_id: string;
+ name: string;
+ ttl_seconds?: number;
+ }) => Promise<VaultAgentBindingResult>;
deriveSigningAddresses: (publicKey: string) => Promise<{ ok: boolean; addresses?: SigningAddresses; code?: string; message?: string }>;
createVaultAuthzWebAuthnOptions: () => Promise<VaultWebAuthnRegistrationOptions>;
registerVaultAuthzWebAuthnFactor: (
@@ -2255,6 +2293,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
listVaultSecrets: () => getCachedJson('/api/vault/secrets', 1500),
getVaultPubkey: () => getCachedJson('/api/vault/pubkey', 1500),
getVaultAgentPubkey: () => getCachedJson('/api/vault/agent/pubkey', 1500),
+ getVaultSandboxRootMetadata: () => getCachedJson('/api/vault/sandbox/root-metadata', 1500, { handleError: false }),
+ createVaultAgentBinding: (payload) =>
+ postJson('/api/vault/agent-binding', payload, { handleError: false }),
deriveSigningAddresses: (publicKey) =>
postJson('/api/vault/signing-addresses', { public_key: publicKey }, { handleError: false }),
createVaultAuthzWebAuthnOptions: () => postJson('/api/vault/authz/factors/webauthn/options', {}),
diff --git a/ui/src/lib/useProtectedVault.test.ts b/ui/src/lib/useProtectedVault.test.ts
index eb3a42c73..42c249524 100644
--- a/ui/src/lib/useProtectedVault.test.ts
+++ b/ui/src/lib/useProtectedVault.test.ts
@@ -1,107 +1,67 @@
-import { describe, expect, it } from 'vitest';
-
-import { bytesToBase64 } from './vaultCrypto';
-import { passkeyAssertionOptionsFromServer, passkeyCreationOptions, passkeyPrfAssertionOptions, readPasskeyPrfResult } from './useProtectedVault';
-
-function passkeyCredential(first?: ArrayBuffer | ArrayBufferView | number[]): PublicKeyCredential {
- return {
- getClientExtensionResults: () => ({
- prf: {
- results: first ? { first } : {},
- },
- }),
- } as unknown as PublicKeyCredential;
-}
-
-describe('protected vault WebAuthn PRF result handling', () => {
- it('creates passkeys as required resident credentials', () => {
- const options = passkeyCreationOptions('alex-app.avibe.bot');
-
- expect(options.rp.id).toBe('alex-app.avibe.bot');
- expect(options.authenticatorSelection).toEqual({ residentKey: 'required', userVerification: 'required' });
- expect(options.extensions).toEqual({ prf: {} });
- });
-
- it('uses simple PRF eval with allowCredentials for credential-bound unlock', () => {
- const prfSalt = new Uint8Array(32).fill(0x11);
- const credentialId = new Uint8Array([1, 2, 3, 4]);
- const options = passkeyPrfAssertionOptions(
- [{ credentialId: bytesToBase64(credentialId), prfSalt }],
- 'alex-app.avibe.bot',
- );
- const prf = (options.extensions as { prf: { eval: { first: ArrayBuffer }; evalByCredential?: unknown } }).prf;
-
- expect(options.rpId).toBe('alex-app.avibe.bot');
- expect(options.userVerification).toBe('required');
- expect(options.allowCredentials).toHaveLength(1);
- expect(new Uint8Array(options.allowCredentials?.[0]?.id as ArrayBuffer)).toEqual(credentialId);
- expect(new Uint8Array(prf.eval.first)).toEqual(prfSalt);
- expect(prf.evalByCredential).toBeUndefined();
+import { describe, expect, it, vi } from 'vitest';
+
+import { authorizeProtectedDeleteWithSandbox, webauthnAvailable } from './useProtectedVault';
+import {
+ VAULT_SANDBOX_EXPECTED_BUILD_HASH,
+ VAULT_SANDBOX_IFRAME_URL,
+ VAULT_SANDBOX_IFRAME_RESOURCE_PATH,
+ VAULT_SANDBOX_ORIGIN,
+ VAULT_SANDBOX_PINNED_MANIFEST,
+ VAULT_SANDBOX_REQUIRED_RESOURCE_PATHS,
+} from './vaultSandboxManifest';
+
+describe('protected vault sandbox cutover', () => {
+ it('pins the deployed sandbox build and only verifies runtime resources', () => {
+ expect(VAULT_SANDBOX_ORIGIN).toBe('https://sandbox.avibe.bot');
+ expect(VAULT_SANDBOX_EXPECTED_BUILD_HASH).toBe('dev');
+ expect(VAULT_SANDBOX_IFRAME_RESOURCE_PATH).toBe('/index.html');
+ expect(VAULT_SANDBOX_IFRAME_URL).toBe(`${VAULT_SANDBOX_ORIGIN}${VAULT_SANDBOX_IFRAME_RESOURCE_PATH}`);
+ expect(VAULT_SANDBOX_PINNED_MANIFEST.resources['/index.html']).toMatch(/^sha256-/);
+ expect(VAULT_SANDBOX_REQUIRED_RESOURCE_PATHS).toContain(VAULT_SANDBOX_IFRAME_RESOURCE_PATH);
+ expect(VAULT_SANDBOX_REQUIRED_RESOURCE_PATHS.every((path) => !path.endsWith('.map'))).toBe(true);
});
- it('rejects multiple passkey entries instead of falling back to evalByCredential', () => {
- const prfSalt = new Uint8Array(32).fill(0x11);
-
- expect(() =>
- passkeyPrfAssertionOptions(
- [
- { credentialId: bytesToBase64(new Uint8Array([1])), prfSalt },
- { credentialId: bytesToBase64(new Uint8Array([2])), prfSalt },
- ],
- 'alex-app.avibe.bot',
- ),
- ).toThrow(/passkey-multiple-not-supported/);
+ it('fails closed outside a browser context', () => {
+ expect(webauthnAvailable()).toBe(false);
});
- it('builds delete assertion options from the server challenge without leaking factor ids to WebAuthn', () => {
- const challenge = new Uint8Array(32).fill(0x44);
- const credentialId = new Uint8Array([5, 6, 7, 8]);
- const options = passkeyAssertionOptionsFromServer({
- challenge: bytesToBase64(challenge),
- rpId: 'alex-app.avibe.bot',
- userVerification: 'required',
- allowCredentials: [
- {
- type: 'public-key',
- id: bytesToBase64(credentialId),
- factor_id: 'vaf_test',
- transports: ['internal'],
+ it('authorizes protected delete without requiring unlocked VMK state', async () => {
+ const credential = {
+ id: 'cred-1',
+ rawId: 'cred-1',
+ type: 'public-key',
+ response: { clientDataJSON: 'client', authenticatorData: 'auth', signature: 'sig' },
+ };
+ const api = {
+ createVaultDeleteChallenge: vi.fn(async () => ({
+ ok: true,
+ challenge_id: 'vop_delete',
+ webauthn: {
+ challenge: 'challenge',
+ rpId: 'sandbox.avibe.bot',
+ userVerification: 'required',
+ allowCredentials: [{ type: 'public-key', id: 'cred-1', factor_id: 'vaf_delete' }],
},
- ],
+ })),
+ };
+ const client = {
+ deleteAuthzAssertion: vi.fn(async () => ({ challengeId: 'vop_delete', assertion: credential })),
+ };
+
+ await expect(
+ authorizeProtectedDeleteWithSandbox('PROTECTED_KEY', api, async () => client as never),
+ ).resolves.toEqual({
+ kind: 'webauthn',
+ challenge_id: 'vop_delete',
+ factor_id: 'vaf_delete',
+ assertion: credential,
+ });
+ expect(api.createVaultDeleteChallenge).toHaveBeenCalledWith('PROTECTED_KEY', { handleError: false });
+ expect(client.deleteAuthzAssertion).toHaveBeenCalledWith({
+ challengeId: 'vop_delete',
+ operation: 'delete_secret',
+ secretName: 'PROTECTED_KEY',
+ webauthn: expect.any(Object),
});
-
- expect(new Uint8Array(options.challenge as ArrayBuffer)).toEqual(challenge);
- expect(options.rpId).toBe('alex-app.avibe.bot');
- expect(options.userVerification).toBe('required');
- expect(options.allowCredentials).toEqual([
- {
- type: 'public-key',
- id: options.allowCredentials?.[0]?.id,
- transports: ['internal'],
- },
- ]);
- expect(new Uint8Array(options.allowCredentials?.[0]?.id as ArrayBuffer)).toEqual(credentialId);
- expect('factor_id' in (options.allowCredentials?.[0] as Record<string, unknown>)).toBe(false);
- });
-
- it('copies the PRF output before handing it to the VMK wrap chain', () => {
- const source = new Uint8Array(32).fill(0x22);
- const backing = source.buffer as ArrayBuffer;
- const result = readPasskeyPrfResult(passkeyCredential(backing));
-
- structuredClone(backing, { transfer: [backing] });
-
- expect(result.byteLength).toBe(32);
- expect(result).toEqual(new Uint8Array(32).fill(0x22));
- });
-
- it('accepts a plain Array PRF output from browser extension passkey providers', () => {
- const source = Array.from({ length: 32 }, (_, index) => index + 1);
-
- expect(readPasskeyPrfResult(passkeyCredential(source))).toEqual(Uint8Array.from(source));
- });
-
- it('rejects a present but empty PRF output at the WebAuthn boundary', () => {
- expect(() => readPasskeyPrfResult(passkeyCredential(new ArrayBuffer(0)))).toThrow(/passkey-prf-unavailable/);
});
});
diff --git a/ui/src/lib/useProtectedVault.ts b/ui/src/lib/useProtectedVault.ts
index 8a1600f9e..d5201baa1 100644
--- a/ui/src/lib/useProtectedVault.ts
+++ b/ui/src/lib/useProtectedVault.ts
@@ -4,36 +4,20 @@ import {
useApi,
type ApiContextType,
type VaultDeleteAuthz,
- type VaultDeleteChallengeResult,
type VaultWebAuthnRegistrationPayload,
type VaultWebAuthnSerializedCredential,
} from '@/context/ApiContext';
import {
- base64ToBytes,
- buildWrapMeta,
- bytesToBase64,
- newPasskeyPrfSalt,
- newVmk,
- packProtectedRecord,
- passkeyPrfSaltEntries,
- releaseProtectedDek,
- sealProtected,
- signProtectedDigest,
- unpackProtectedRecord,
- unwrapVmk,
- webAuthnPrfExtensionInput,
- type AvaultPublicKey,
- type BlindBox,
- type ProtectedDekDeliveryBlindBoxContext,
- type ProtectedRecordEnvelope,
- type SignatureResult,
- type SignatureScheme,
-} from './vaultCrypto';
+ getVaultSandboxClient,
+ type DaemonAgentBinding,
+ type VaultSandboxSealResult,
+ type VaultSandboxSigningContext,
+} from './vaultSandboxClient';
+import { type BlindBox, type ProtectedRecordEnvelope, type SignatureResult, type SignatureScheme } from './vaultCrypto';
/**
- * The protected envelope + name the daemon hydrates onto a UI-audience request card
- * (`card.secret_unlock_material` / `scope_options[].unlock_material[]`). It is value-free
- * metadata; the browser opens it locally with the unlocked VMK to sign or release a DEK.
+ * Value-free protected material hydrated into UI approval cards. The parent app brokers it to the
+ * sandbox; the VMK, DEK, private key, and plaintext stay inside sandbox.avibe.bot.
*/
export type ProtectedUnlockMaterial = {
name: string;
@@ -41,50 +25,26 @@ export type ProtectedUnlockMaterial = {
envelope: ProtectedRecordEnvelope;
};
-/**
- * Protected-tier vault lifecycle for the Web UI.
- *
- * The Vault Master Key (VMK) lives only in browser memory and is wrapped by a
- * passkey (WebAuthn-PRF, Face ID / Touch ID / Windows Hello) into an opaque
- * `wrap_meta` the daemon stores per protected secret. The daemon never sees
- * the VMK or plaintext. No cross-origin sandbox yet — that hardening is a later
- * version.
- *
- * The unlocked VMK is cached at module scope so it survives `VaultSecretForm`
- * unmount/remount within one page session. A full reload re-initialises the module.
- */
export type ProtectedVaultStatus = 'checking' | 'needs-setup' | 'locked' | 'unlocked' | 'error';
+const VAULT_AUTO_LOCK_MS = 10 * 60 * 1000;
+
const sessionVault: {
- vmk: Uint8Array | null;
+ status: Exclude<ProtectedVaultStatus, 'checking' | 'error'>;
wrapMeta: string | null;
freshSetup: boolean;
authzFactorRegistration: VaultWebAuthnRegistrationPayload | null;
} = {
- vmk: null,
+ status: 'needs-setup',
wrapMeta: null,
freshSetup: false,
authzFactorRegistration: null,
};
-/**
- * Auto-lock. The plaintext VMK is zeroed this long after it was unlocked (the timer is
- * refreshed on every use), shrinking the window it sits in browser memory from "until reload"
- * to a few idle minutes. A manual "Lock now" or a full page reload also clears it.
- */
-const VAULT_AUTO_LOCK_MS = 10 * 60 * 1000;
let vaultLockExpiresAt: number | null = null;
let vaultAutoLockTimer: ReturnType<typeof setTimeout> | null = null;
const vaultLockListeners = new Set<() => void>();
-/**
- * Cross-tab lock: a manual "Lock now" broadcasts here so every open tab for this origin wipes its
- * own cached VMK, not just the tab that clicked. Auto-lock stays per-tab (each tab's idle timer is
- * independent, so an idle tab locking shouldn't wipe a tab you're actively using).
- *
- * Created lazily on first unlock (never at module import): `BroadcastChannel` also exists in
- * Node/Vitest, and an open-at-import channel keeps the process alive and can hang the UI test run.
- */
let vaultLockChannel: BroadcastChannel | null = null;
let vaultLockChannelInit = false;
function getVaultLockChannel(): BroadcastChannel | null {
@@ -93,7 +53,7 @@ function getVaultLockChannel(): BroadcastChannel | null {
if (typeof BroadcastChannel === 'undefined') return null;
vaultLockChannel = new BroadcastChannel('avibe-vault-lock');
vaultLockChannel.onmessage = (event: MessageEvent) => {
- if (event.data === 'lock') lockVault(false);
+ if (event.data === 'lock') void lockVault(false);
};
return vaultLockChannel;
}
@@ -102,7 +62,6 @@ function notifyVaultLockChange(): void {
for (const listener of [...vaultLockListeners]) listener();
}
-/** Subscribe to VMK unlock/auto-lock/lock transitions (module-global). Returns an unsubscribe. */
export function subscribeVaultLock(listener: () => void): () => void {
vaultLockListeners.add(listener);
return () => {
@@ -110,334 +69,173 @@ export function subscribeVaultLock(listener: () => void): () => void {
};
}
-/** Wall-clock ms when the VMK auto-locks, or null while locked. */
export function vaultUnlockExpiresAt(): number | null {
- return sessionVault.vmk ? vaultLockExpiresAt : null;
+ return sessionVault.status === 'unlocked' ? vaultLockExpiresAt : null;
}
-/** True once the auto-lock wall-clock deadline has passed (independent of the setTimeout). */
function autoLockExpired(): boolean {
return vaultLockExpiresAt != null && Date.now() >= vaultLockExpiresAt;
}
export function vaultUnlocked(): boolean {
- if (sessionVault.vmk && autoLockExpired()) {
- // Zero an expired VMK the instant anything checks the lock state, even if the (delayed) timer
- // hasn't fired — so no flow (delete gate, create/provision, approval) can treat a past-deadline
- // vault as unlocked.
- clearVmk();
- // Notify subscribers so other mounted forms/approval cards drop out of 'unlocked' too. Deferred
- // to a microtask because this may run during render (can't synchronously setState here).
+ if (sessionVault.status === 'unlocked' && autoLockExpired()) {
+ clearUnlockState();
queueMicrotask(notifyVaultLockChange);
+ void getVaultSandboxClient()
+ .then((client) => client.lock())
+ .catch(() => undefined);
return false;
}
- return sessionVault.vmk != null;
+ return sessionVault.status === 'unlocked';
}
-/**
- * Enforce the auto-lock deadline synchronously. Browser timers fire late when a tab is
- * backgrounded/suspended or the machine sleeps, so `setTimeout(lockVault)` can lag well past the
- * deadline; call this before trusting or using the VMK to lock the moment the wall clock is past
- * due. Safe in event/effect contexts (it notifies). Returns whether the vault is still unlocked.
- */
function enforceAutoLock(): boolean {
- if (sessionVault.vmk && autoLockExpired()) {
- lockVault();
+ if (sessionVault.status === 'unlocked' && autoLockExpired()) {
+ void lockVault(false);
return false;
}
- return sessionVault.vmk != null;
+ return sessionVault.status === 'unlocked';
}
-/**
- * True when the in-memory VMK is a fresh, uncommitted first-time setup — NOT a proven unlock of
- * the server's established vault. In the first-init collision path (another tab established the
- * real vault after this tab set up but before it saved a secret) a fresh-setup VMK is a loser key
- * that must not be treated as authorization to act on a real protected secret.
- */
export function vaultFreshSetup(): boolean {
return sessionVault.freshSetup;
}
function vaultStatusNow(): ProtectedVaultStatus {
- if (sessionVault.vmk) return 'unlocked';
- return sessionVault.wrapMeta ? 'locked' : 'needs-setup';
+ return sessionVault.status;
}
-/** Zero the VMK and cancel the pending auto-lock. Does not notify — callers decide. */
-function clearVmk(): void {
- sessionVault.vmk?.fill(0);
- sessionVault.vmk = null;
- vaultLockExpiresAt = null;
+function clearUnlockState(): void {
if (vaultAutoLockTimer) {
clearTimeout(vaultAutoLockTimer);
vaultAutoLockTimer = null;
}
+ vaultLockExpiresAt = null;
if (sessionVault.freshSetup) {
- // An uncommitted fresh VMK (set up but no protected secret saved yet) — drop it so a later
- // unlock can't seal under a stale local VMK that skips the atomic first-init guard. Done here
- // (not only in lockVault) so EVERY teardown path — manual lock, auto-lock, and the render-time
- // expiry in vaultUnlocked() — leaves a consistent state.
sessionVault.wrapMeta = null;
sessionVault.freshSetup = false;
sessionVault.authzFactorRegistration = null;
+ sessionVault.status = 'needs-setup';
+ } else {
+ sessionVault.status = sessionVault.wrapMeta ? 'locked' : 'needs-setup';
}
}
-/** Lock the vault now: zero the VMK, drop an uncommitted fresh-setup VMK, notify subscribers. */
-function lockVault(broadcast = false): void {
- clearVmk(); // zeros the VMK and drops any uncommitted fresh-setup state
+async function lockVault(broadcast = false): Promise<void> {
+ clearUnlockState();
notifyVaultLockChange();
- // A manual "Lock now" wipes every open tab for this origin, not just this one.
if (broadcast) getVaultLockChannel()?.postMessage('lock');
+ try {
+ await (await getVaultSandboxClient()).lock();
+ } catch {
+ // Local parent state is already locked; a best-effort sandbox lock failure remains fail-closed.
+ }
}
-/** (Re)start the auto-lock countdown; call on unlock and on every VMK use. Notifies subscribers. */
-function armVaultAutoLock(): void {
- if (!sessionVault.vmk) return;
- getVaultLockChannel(); // ensure this (unlocked) tab can receive a cross-tab "Lock now"
- vaultLockExpiresAt = Date.now() + VAULT_AUTO_LOCK_MS;
+function armVaultAutoLock(expiresAt?: number | null): void {
+ getVaultLockChannel();
+ const sandboxDeadline = typeof expiresAt === 'number' && Number.isFinite(expiresAt) ? expiresAt : null;
+ vaultLockExpiresAt = sandboxDeadline ?? Date.now() + VAULT_AUTO_LOCK_MS;
if (vaultAutoLockTimer) clearTimeout(vaultAutoLockTimer);
- vaultAutoLockTimer = setTimeout(() => lockVault(), VAULT_AUTO_LOCK_MS);
+ vaultAutoLockTimer = setTimeout(() => void lockVault(false), Math.max(0, vaultLockExpiresAt - Date.now()));
notifyVaultLockChange();
}
-const WEBAUTHN_RP_NAME = 'Avibe Vault';
-const WEBAUTHN_USER_HANDLE = new TextEncoder().encode('avibe-vault');
-
-/**
- * WebAuthn needs a secure context and a domain RP ID. Browsers reject raw IP RP IDs
- * (the default local `http://127.0.0.1:5123` workflow), so protected vault setup and
- * unlock only work on `localhost` or an HTTPS domain (e.g. the tunnel).
- */
-export function webauthnAvailable(): boolean {
- if (typeof window === 'undefined' || typeof window.PublicKeyCredential === 'undefined') return false;
- if (!window.isSecureContext) return false;
- const host = window.location.hostname;
- if (host === 'localhost') return true;
- if (host === '' || host.includes(':') || /^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return false; // IPv6/IPv4
- return host.includes('.');
-}
-
-/** A fresh ArrayBuffer copy — WebAuthn fields want BufferSource, not Uint8Array<ArrayBufferLike>. */
-function bufferSource(bytes: Uint8Array): ArrayBuffer {
- const out = new ArrayBuffer(bytes.byteLength);
- new Uint8Array(out).set(bytes);
- return out;
-}
-
-function randomChallenge(): ArrayBuffer {
- return bufferSource(crypto.getRandomValues(new Uint8Array(32)));
-}
-
-function bufferSourceFromBase64(value: string): ArrayBuffer {
- return bufferSource(base64ToBytes(value));
-}
-
-/** Strip a stored record's DEK fields back to the bare VMK wrap_meta ({v, copies, scheme?}). */
function baseVmkWrapMeta(wrapMeta: string): string {
const parsed = JSON.parse(wrapMeta) as Record<string, unknown>;
delete parsed.dek_nonce;
delete parsed.wrapped_dek;
+ delete parsed.record_meta;
return JSON.stringify(parsed);
}
-/** Record the WebAuthn RP ID (host) a passkey was bound to, so unlock only offers it on
- * the same site (the credential can't be asserted from a different host). */
-function withRpId(wrapMeta: string, rpId: string): string {
- const meta = JSON.parse(wrapMeta) as Record<string, unknown>;
- meta.rp_id = rpId;
- return JSON.stringify(meta);
-}
-
-function toUint8(buffer: ArrayBuffer | ArrayBufferView | ArrayLike<number>): Uint8Array {
- if (buffer instanceof ArrayBuffer) return new Uint8Array(buffer);
- if (ArrayBuffer.isView(buffer)) return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
- return Uint8Array.from(buffer);
-}
-
-function copyUint8(buffer: ArrayBuffer | ArrayBufferView | ArrayLike<number>): Uint8Array {
- return new Uint8Array(toUint8(buffer));
-}
-
-export function readPasskeyPrfResult(credential: PublicKeyCredential | null): Uint8Array {
- const ext = credential?.getClientExtensionResults() as { prf?: { results?: { first?: ArrayBuffer | ArrayBufferView | ArrayLike<number> } } } | undefined;
- const first = ext?.prf?.results?.first;
- if (!first) throw new Error('passkey-prf-unavailable');
- const prfOutput = copyUint8(first);
- if (prfOutput.byteLength === 0) throw new Error('passkey-prf-unavailable');
- return prfOutput;
-}
-
-export type PasskeyEntry = { credentialId?: string; prfSalt: Uint8Array };
-
-function singlePasskeyEntry(entries: PasskeyEntry[]): PasskeyEntry {
- if (entries.length === 0) throw new Error('passkey-not-configured');
- if (entries.length > 1) throw new Error('passkey-multiple-not-supported');
- return entries[0];
-}
-
-export function passkeyCreationOptions(
- rpId: string,
- challenge: ArrayBuffer | ArrayBufferView | ArrayLike<number> = randomChallenge(),
-): PublicKeyCredentialCreationOptions {
- return {
- rp: { name: WEBAUTHN_RP_NAME, id: rpId },
- user: { id: bufferSource(WEBAUTHN_USER_HANDLE), name: 'avibe-vault', displayName: WEBAUTHN_RP_NAME },
- challenge: bufferSource(toUint8(challenge)),
- pubKeyCredParams: [
- { type: 'public-key', alg: -7 },
- { type: 'public-key', alg: -257 },
- ],
- authenticatorSelection: { residentKey: 'required', userVerification: 'required' },
- extensions: { prf: {} } as AuthenticationExtensionsClientInputs,
- };
-}
-
-function passkeyCreationOptionsFromServer(
- webauthn: Awaited<ReturnType<ApiContextType['createVaultAuthzWebAuthnOptions']>>['webauthn'],
-): PublicKeyCredentialCreationOptions {
- return {
- rp: webauthn.rp,
- user: { ...webauthn.user, id: bufferSourceFromBase64(webauthn.user.id) },
- challenge: bufferSourceFromBase64(webauthn.challenge),
- pubKeyCredParams: webauthn.pubKeyCredParams,
- authenticatorSelection: webauthn.authenticatorSelection,
- extensions: webauthn.extensions,
- };
-}
-
-export function passkeyPrfAssertionOptions(entries: PasskeyEntry[], rpId: string): PublicKeyCredentialRequestOptions {
- const entry = singlePasskeyEntry(entries);
- const options: PublicKeyCredentialRequestOptions = {
- challenge: randomChallenge(),
- rpId,
- userVerification: 'required',
- extensions: webAuthnPrfExtensionInput(entry.prfSalt) as AuthenticationExtensionsClientInputs,
- };
- if (entry.credentialId) {
- options.allowCredentials = [
- {
- type: 'public-key' as const,
- id: bufferSource(base64ToBytes(entry.credentialId)),
- },
- ];
+function hasPasskeyCopy(wrapMeta: string | null): boolean {
+ if (!wrapMeta) return false;
+ try {
+ const meta = JSON.parse(wrapMeta) as { copies?: Array<{ kind?: string }> };
+ return Array.isArray(meta.copies) && meta.copies.some((copy) => copy?.kind === 'passkey');
+ } catch {
+ return false;
}
- return options;
-}
-
-export function passkeyAssertionOptionsFromServer(
- webauthn: VaultDeleteChallengeResult['webauthn'],
-): PublicKeyCredentialRequestOptions {
- return {
- challenge: bufferSourceFromBase64(webauthn.challenge),
- rpId: webauthn.rpId,
- userVerification: webauthn.userVerification,
- allowCredentials: webauthn.allowCredentials.map((entry) => ({
- type: 'public-key' as const,
- id: bufferSourceFromBase64(entry.id),
- ...(entry.transports ? { transports: entry.transports } : {}),
- })),
- };
}
-function serializeCredentialBase(credential: PublicKeyCredential): Pick<VaultWebAuthnSerializedCredential, 'id' | 'rawId' | 'type'> {
- return {
- id: credential.id,
- rawId: bytesToBase64(toUint8(credential.rawId)),
- type: credential.type,
- };
+function commitUnlocked(
+ wrapMeta: string,
+ freshSetup: boolean,
+ expiresAt?: number | null,
+ authzFactorRegistration: VaultWebAuthnRegistrationPayload | null = null,
+): void {
+ sessionVault.wrapMeta = baseVmkWrapMeta(wrapMeta);
+ sessionVault.status = 'unlocked';
+ sessionVault.freshSetup = freshSetup;
+ sessionVault.authzFactorRegistration = authzFactorRegistration;
+ armVaultAutoLock(expiresAt);
}
-export function serializeAttestationCredential(credential: PublicKeyCredential): VaultWebAuthnSerializedCredential {
- const response = credential.response as AuthenticatorAttestationResponse;
- const transports = typeof response.getTransports === 'function' ? response.getTransports() : [];
- return {
- ...serializeCredentialBase(credential),
- response: {
- clientDataJSON: bytesToBase64(toUint8(response.clientDataJSON)),
- attestationObject: bytesToBase64(toUint8(response.attestationObject)),
- transports,
- },
- };
+export function webauthnAvailable(): boolean {
+ return typeof window !== 'undefined' && typeof crypto !== 'undefined' && Boolean(crypto.subtle);
}
-export function serializeAssertionCredential(credential: PublicKeyCredential): VaultWebAuthnSerializedCredential {
- const response = credential.response as AuthenticatorAssertionResponse;
- return {
- ...serializeCredentialBase(credential),
- response: {
- clientDataJSON: bytesToBase64(toUint8(response.clientDataJSON)),
- authenticatorData: bytesToBase64(toUint8(response.authenticatorData)),
- signature: bytesToBase64(toUint8(response.signature)),
- userHandle: response.userHandle ? bytesToBase64(toUint8(response.userHandle)) : null,
- },
- };
+function isSerializedCredential(value: unknown): value is VaultWebAuthnSerializedCredential {
+ return typeof value === 'object' && value != null && 'rawId' in value && 'response' in value;
}
-/**
- * Assert the vault passkey and extract its PRF output. Keep the assertion on the
- * simple `prf.eval` path: iOS 1Password currently fails on `evalByCredential`,
- * while `allowCredentials + prf.eval` preserves the exact credential binding.
- */
-async function assertPasskeyPrf(entries: PasskeyEntry[]): Promise<{ prfOutput: Uint8Array; prfSalt: Uint8Array }> {
- const assertion = (await navigator.credentials.get({
- publicKey: passkeyPrfAssertionOptions(entries, window.location.hostname),
- })) as PublicKeyCredential | null;
- if (!assertion) throw new Error('passkey-cancelled');
- const prfOutput = readPasskeyPrfResult(assertion);
- const usedId = bytesToBase64(toUint8(assertion.rawId));
- const used = entries.find((entry) => entry.credentialId === usedId);
- return { prfOutput, prfSalt: used?.prfSalt ?? entries[0].prfSalt };
+function registrationFromSandbox(value: unknown): VaultWebAuthnRegistrationPayload | null {
+ if (typeof value !== 'object' || value == null) return null;
+ const candidate = value as Partial<VaultWebAuthnRegistrationPayload>;
+ if (typeof candidate.challenge_id === 'string' && isSerializedCredential(candidate.credential)) {
+ return candidate as VaultWebAuthnRegistrationPayload;
+ }
+ return null;
}
-/** Create a resident passkey, then assert it once to extract the PRF output. */
-async function setupPasskeyFactor(
- api: ApiContextType,
- prfSalt: Uint8Array,
-): Promise<{ prfOutput: Uint8Array; credentialId: string; registration: VaultWebAuthnRegistrationPayload }> {
- const options = await api.createVaultAuthzWebAuthnOptions();
- if (!options?.ok) throw new Error(options?.code || 'passkey-registration-options-failed');
- const created = (await navigator.credentials.create({
- publicKey: passkeyCreationOptionsFromServer(options.webauthn),
- })) as PublicKeyCredential | null;
- if (!created) throw new Error('passkey-cancelled');
- const credentialId = bytesToBase64(toUint8(created.rawId));
- const { prfOutput } = await assertPasskeyPrf([{ credentialId, prfSalt }]);
+export async function authorizeProtectedDeleteWithSandbox(
+ name: string,
+ api: Pick<ApiContextType, 'createVaultDeleteChallenge'>,
+ clientFactory = getVaultSandboxClient,
+): Promise<VaultDeleteAuthz> {
+ const challenge = await api.createVaultDeleteChallenge(name, { handleError: false });
+ if (!challenge?.ok) {
+ throw new Error(challenge?.code || challenge?.message || 'protected-delete-challenge-failed');
+ }
+ const result = await (await clientFactory()).deleteAuthzAssertion({
+ challengeId: challenge.challenge_id,
+ operation: 'delete_secret',
+ secretName: name,
+ webauthn: challenge.webauthn,
+ });
+ const assertion = result.assertion as VaultDeleteAuthz | VaultWebAuthnSerializedCredential;
+ if ('kind' in assertion && assertion.kind === 'webauthn' && assertion.factor_id) {
+ return assertion;
+ }
+ const credential = isSerializedCredential(assertion) ? assertion : assertion.assertion;
+ const rawId = credential.rawId;
+ const factor = rawId ? challenge.webauthn.allowCredentials.find((entry) => entry.id === rawId) : undefined;
+ if (!factor?.factor_id) throw new Error('protected-authz-factor-missing');
return {
- prfOutput,
- credentialId,
- registration: {
- challenge_id: options.challenge_id,
- credential: serializeAttestationCredential(created),
- },
+ kind: 'webauthn',
+ challenge_id: result.challengeId || challenge.challenge_id,
+ factor_id: factor.factor_id,
+ assertion: credential,
};
}
export function useProtectedVault() {
const api = useApi();
- const [status, setStatus] = useState<ProtectedVaultStatus>(sessionVault.vmk ? 'unlocked' : 'checking');
+ const [status, setStatus] = useState<ProtectedVaultStatus>(sessionVault.status);
const [error, setError] = useState<string | null>(null);
- // Re-sync this instance when the module VMK locks/unlocks elsewhere — notably when the
- // auto-lock timer fires while this component is mounted, or another instance unlocks. Don't
- // clobber the async discovery states ('checking'/'error').
useEffect(
() =>
subscribeVaultLock(() => {
- setStatus((prev) => {
- // A global unlock (from another dialog/tab) should win even over a stale 'error'/'checking'
- // discovery state — otherwise that instance stays disabled though the vault is now unlocked.
- if (sessionVault.vmk) return 'unlocked';
- // No VMK: don't clobber an in-flight discovery; otherwise reflect locked/needs-setup.
- return prev === 'checking' || prev === 'error' ? prev : vaultStatusNow();
- });
+ setStatus((prev) => (prev === 'checking' || prev === 'error' ? prev : vaultStatusNow()));
}),
[],
);
const refresh = useCallback(async () => {
- enforceAutoLock(); // a cached VMK past its deadline isn't "unlocked" — lock it before trusting it
- if (sessionVault.vmk) {
+ enforceAutoLock();
+ if (sessionVault.status === 'unlocked') {
setStatus('unlocked');
return;
}
@@ -446,167 +244,128 @@ export function useProtectedVault() {
try {
const res = await api.getVaultVmk();
if (!res?.ok) throw new Error('vmk-discovery-failed');
+ const sandbox = await getVaultSandboxClient();
if (res.exists && res.wrap_meta) {
sessionVault.wrapMeta = baseVmkWrapMeta(res.wrap_meta);
- setStatus('locked');
+ const sandboxStatus = await sandbox.status(sessionVault.wrapMeta);
+ if (sandboxStatus.state === 'unlocked') {
+ sessionVault.status = 'unlocked';
+ armVaultAutoLock(sandboxStatus.expiresAt);
+ } else {
+ sessionVault.status = 'locked';
+ }
} else {
sessionVault.wrapMeta = null;
- setStatus('needs-setup');
+ sessionVault.status = 'needs-setup';
}
- } catch {
- // A failed/transient discovery must NOT degrade to setup — that would let the
- // user mint a second VMK and split the vault key history. Surface an error.
+ setStatus(sessionVault.status);
+ } catch (err) {
+ sessionVault.status = sessionVault.wrapMeta ? 'locked' : 'needs-setup';
setStatus('error');
- setError('vmk-discovery-failed');
+ setError(err instanceof Error ? err.message : 'vmk-discovery-failed');
}
}, [api]);
- const commit = (
- vmk: Uint8Array,
- wrapMeta: string,
- freshSetup: boolean,
- authzFactorRegistration: VaultWebAuthnRegistrationPayload | null = null,
- ) => {
- sessionVault.vmk?.fill(0);
- sessionVault.vmk = vmk;
- sessionVault.wrapMeta = wrapMeta;
- sessionVault.freshSetup = freshSetup;
- sessionVault.authzFactorRegistration = authzFactorRegistration;
- armVaultAutoLock();
+ const setupPasskey = useCallback(async () => {
+ const sandbox = await getVaultSandboxClient();
+ const [authzOptions, rootMetadata] = await Promise.all([
+ api.createVaultAuthzWebAuthnOptions(),
+ api.getVaultSandboxRootMetadata(),
+ ]);
+ if (!authzOptions?.ok) throw new Error(authzOptions?.code || 'passkey-registration-options-failed');
+ if (!rootMetadata?.ok) throw new Error(rootMetadata?.code || 'sandbox-root-metadata-failed');
+ const result = await sandbox.setup({
+ vaultUserHandle: 'avibe-vault',
+ displayName: 'Avibe Vault',
+ existingProtectedVault: Boolean(sessionVault.wrapMeta),
+ authzCreationOptions: authzOptions,
+ rootMetadata: rootMetadata.root_metadata,
+ });
+ const authzRegistration = registrationFromSandbox(result.authzRegistration);
+ commitUnlocked(result.wrapMeta, true, result.expiresAt, authzRegistration);
setStatus('unlocked');
setError(null);
- };
-
- // First-time setup is passkey-only. A lost passkey is unrecoverable for now, so the
- // UI requires an explicit acknowledgement before calling this.
- const setupPasskey = useCallback(async () => {
- const prfSalt = newPasskeyPrfSalt();
- const { prfOutput, credentialId, registration } = await setupPasskeyFactor(api, prfSalt);
- const vmk = newVmk();
- const wrapMeta = await buildWrapMeta(vmk, [{ kind: 'passkey', prfOutput, prfSalt, credentialId }]);
- commit(vmk, withRpId(wrapMeta, window.location.hostname), true, registration);
}, [api]);
const unlockPasskey = useCallback(async () => {
const wrapMeta = sessionVault.wrapMeta;
if (!wrapMeta) throw new Error('vault-not-setup');
- const entries = passkeyPrfSaltEntries(wrapMeta);
- if (entries.length === 0) throw new Error('passkey-not-configured');
- const { prfOutput, prfSalt } = await assertPasskeyPrf(entries);
- commit(await unwrapVmk(wrapMeta, { kind: 'passkey', prfOutput, prfSalt }), wrapMeta, false);
+ const result = await (await getVaultSandboxClient()).unlock({ wrapMeta });
+ commitUnlocked(result.wrapMeta || wrapMeta, false, result.expiresAt);
+ setStatus('unlocked');
+ setError(null);
}, []);
- /**
- * Seal a value under the unlocked VMK into a stored protected envelope. Accepts a
- * string (static secret) or raw bytes (a keypair's 32-byte private key), so protected
- * signing keys seal the key material itself, not a UTF-8 string.
- */
const sealValue = useCallback(
async (
name: string,
- value: Uint8Array | string,
- ): Promise<{
- envelope: ProtectedRecordEnvelope;
- establishingVmk: boolean;
- authzFactorRegistration?: VaultWebAuthnRegistrationPayload;
- }> => {
+ kind: 'static' | 'keypair' = 'static',
+ ): Promise<
+ VaultSandboxSealResult & {
+ authzFactorRegistration?: VaultWebAuthnRegistrationPayload;
+ }
+ > => {
if (!enforceAutoLock()) throw new Error('vault-locked');
- const { vmk, wrapMeta, freshSetup } = sessionVault;
- if (!vmk || !wrapMeta) throw new Error('vault-locked');
+ const wrapMeta = sessionVault.wrapMeta;
+ if (!wrapMeta) throw new Error('vault-locked');
armVaultAutoLock();
- const valueBytes = typeof value === 'string' ? new TextEncoder().encode(value) : value;
- const sealed = await sealProtected(valueBytes, vmk, { name });
- // `establishingVmk` lets the create transaction enforce the atomic single-init
- // guard server-side (a UI re-check here can't be race-free); the daemon rejects a
- // second VMK so concurrent first-time setups can't split the key history.
+ const sealed = await (await getVaultSandboxClient()).seal({
+ name,
+ kind,
+ inputMode: 'sandbox-entry',
+ wrapMeta,
+ });
return {
- envelope: packProtectedRecord(sealed, wrapMeta),
- establishingVmk: freshSetup,
- authzFactorRegistration: freshSetup ? (sessionVault.authzFactorRegistration ?? undefined) : undefined,
+ ...sealed,
+ authzFactorRegistration: sessionVault.freshSetup
+ ? (sessionVault.authzFactorRegistration ?? undefined)
+ : undefined,
};
},
[],
);
const afterCreated = useCallback(() => {
- // The vault now exists server-side; subsequent creates this session aren't "establishing".
sessionVault.freshSetup = false;
sessionVault.authzFactorRegistration = null;
}, []);
- /**
- * Sign a digest locally with a protected keypair, approving a per-use sign request.
- * The private key is opened from the request's unlock material under the cached VMK,
- * used, and zeroed inside {@link signProtectedDigest} — only the public signature
- * leaves the browser. The VMK never escapes this module.
- */
const signProtectedRequest = useCallback(
- async (material: ProtectedUnlockMaterial, digest: string, scheme: SignatureScheme): Promise<SignatureResult> => {
+ async (
+ material: ProtectedUnlockMaterial,
+ signingContext: VaultSandboxSigningContext,
+ scheme: SignatureScheme,
+ ): Promise<SignatureResult> => {
if (!enforceAutoLock()) throw new Error('vault-locked');
- const { vmk } = sessionVault;
- if (!vmk) throw new Error('vault-locked');
armVaultAutoLock();
- const { sealed } = unpackProtectedRecord(material.envelope);
- return signProtectedDigest(sealed, vmk, { name: material.name }, digest, scheme);
+ return (await getVaultSandboxClient()).sign({ material, scheme, signingContext });
},
[],
);
- /**
- * Release a protected secret's DEK as an opaque HPKE blind box addressed to the
- * resident avault agent, approving a protected value-access request. The released DEK
- * is sealed to the agent's pinned public key inside {@link releaseProtectedDek}; the
- * daemon only ever relays the resulting blind box, never a raw DEK or plaintext.
- */
const releaseProtectedDelivery = useCallback(
- async (
- material: ProtectedUnlockMaterial,
- publicKey: AvaultPublicKey,
- context: ProtectedDekDeliveryBlindBoxContext,
- ): Promise<BlindBox> => {
+ async (material: ProtectedUnlockMaterial, agentBinding: DaemonAgentBinding): Promise<BlindBox> => {
if (!enforceAutoLock()) throw new Error('vault-locked');
- const { vmk } = sessionVault;
- if (!vmk) throw new Error('vault-locked');
armVaultAutoLock();
- const { sealed } = unpackProtectedRecord(material.envelope);
- return releaseProtectedDek(sealed, vmk, publicKey, { name: material.name }, context);
+ return (await getVaultSandboxClient()).releaseDEK({ material, agentBinding });
},
[],
);
const authorizeProtectedDelete = useCallback(
async (name: string): Promise<VaultDeleteAuthz> => {
- const challenge = await api.createVaultDeleteChallenge(name, { handleError: false });
- if (!challenge?.ok) {
- throw new Error(challenge?.code || challenge?.message || 'protected-delete-challenge-failed');
- }
- const assertion = (await navigator.credentials.get({
- publicKey: passkeyAssertionOptionsFromServer(challenge.webauthn),
- })) as PublicKeyCredential | null;
- if (!assertion) throw new Error('passkey-cancelled');
- const rawId = bytesToBase64(toUint8(assertion.rawId));
- const factor = challenge.webauthn.allowCredentials.find((entry) => entry.id === rawId);
- if (!factor?.factor_id) throw new Error('protected-authz-factor-missing');
- return {
- kind: 'webauthn',
- challenge_id: challenge.challenge_id,
- factor_id: factor.factor_id,
- assertion: serializeAssertionCredential(assertion),
- };
+ return authorizeProtectedDeleteWithSandbox(name, api);
},
[api],
);
const lock = useCallback(() => {
- lockVault(true);
+ void lockVault(true);
setStatus(vaultStatusNow());
}, []);
const discardAndRefresh = useCallback(async () => {
- // After an init collision (another tab established the vault first), drop the
- // rejected local VMK and reload the server's real wrap_meta so the user unlocks the
- // established vault instead of resealing under the loser VMK.
- clearVmk();
+ clearUnlockState();
sessionVault.wrapMeta = null;
sessionVault.freshSetup = false;
sessionVault.authzFactorRegistration = null;
@@ -614,29 +373,9 @@ export function useProtectedVault() {
await refresh();
}, [refresh]);
- const hasPasskey = useCallback(() => {
- const wrapMeta = sessionVault.wrapMeta;
- if (!wrapMeta) return false;
- try {
- return passkeyPrfSaltEntries(wrapMeta).length > 0;
- } catch {
- return false;
- }
- }, []);
+ const hasPasskey = useCallback(() => hasPasskeyCopy(sessionVault.wrapMeta), []);
- // A passkey can only be asserted on the host (RP ID) it was created on. Offer passkey
- // unlock only when the current host matches the stored one (legacy vaults without a
- // recorded rp_id are not blocked).
- const passkeyUsableHere = useCallback(() => {
- const wrapMeta = sessionVault.wrapMeta;
- if (!wrapMeta) return false;
- try {
- const meta = JSON.parse(wrapMeta) as { rp_id?: string };
- return !meta.rp_id || meta.rp_id === window.location.hostname;
- } catch {
- return true;
- }
- }, []);
+ const passkeyUsableHere = useCallback(() => hasPasskeyCopy(sessionVault.wrapMeta), []);
return {
status,
@@ -657,12 +396,6 @@ export function useProtectedVault() {
};
}
-/**
- * Reactive VMK lock state for a lightweight status/countdown UI. Subscribes to the
- * module-global auto-lock so an indicator can show the time left before the vault
- * auto-locks and offer an immediate "Lock now", without taking the full
- * {@link useProtectedVault} surface.
- */
export function useVaultLock(): { unlocked: boolean; remainingMs: number; lockNow: () => void } {
const [, forceRender] = useReducer((n: number) => n + 1, 0);
useEffect(() => subscribeVaultLock(forceRender), []);
@@ -672,8 +405,6 @@ export function useVaultLock(): { unlocked: boolean; remainingMs: number; lockNo
useEffect(() => {
if (!unlocked) return;
setNow(Date.now());
- // Tick the countdown, and enforce the deadline by wall-clock so a delayed timer (e.g. the tab
- // was suspended) locks promptly on resume instead of lingering unlocked.
const id = setInterval(() => {
enforceAutoLock();
setNow(Date.now());
@@ -683,6 +414,5 @@ export function useVaultLock(): { unlocked: boolean; remainingMs: number; lockNo
const expiresAt = vaultUnlockExpiresAt();
const remainingMs = expiresAt ? Math.max(0, expiresAt - now) : 0;
- // "Lock now" broadcasts so every open tab for this origin wipes its VMK, not just this one.
- return { unlocked, remainingMs, lockNow: () => lockVault(true) };
+ return { unlocked, remainingMs, lockNow: () => void lockVault(true) };
}
diff --git a/ui/src/lib/vaultSandboxClient.ts b/ui/src/lib/vaultSandboxClient.ts
new file mode 100644
index 000000000..169ae7f39
--- /dev/null
+++ b/ui/src/lib/vaultSandboxClient.ts
@@ -0,0 +1,449 @@
+import type {
+ SigningAddresses,
+ VaultDeleteAuthz,
+ VaultDeleteChallengeResult,
+ VaultWebAuthnRegistrationPayload,
+ VaultWebAuthnSerializedCredential,
+} from '@/context/ApiContext';
+import type { BlindBox, ProtectedRecordEnvelope, SignatureResult, SignatureScheme } from './vaultCrypto';
+import {
+ VAULT_SANDBOX_EXPECTED_BUILD_HASH,
+ VAULT_SANDBOX_IFRAME_URL,
+ VAULT_SANDBOX_IFRAME_RESOURCE_PATH,
+ VAULT_SANDBOX_MANIFEST_PATH,
+ VAULT_SANDBOX_ORIGIN,
+ VAULT_SANDBOX_PINNED_MANIFEST,
+ VAULT_SANDBOX_REQUIRED_RESOURCE_PATHS,
+} from './vaultSandboxManifest';
+
+const CHANNEL = 'avibe.vault.crypto';
+const VERSION = 1;
+const REQUIRED_OPS = [
+ 'status',
+ 'setup',
+ 'unlock',
+ 'lock',
+ 'seal',
+ 'unseal',
+ 'sign',
+ 'releaseDEK',
+ 'deleteAuthzAssertion',
+] as const;
+const DEFAULT_TIMEOUT_MS = 15_000;
+const INTERACTIVE_TIMEOUT_MS = 5 * 60_000;
+
+type VaultSandboxOp = (typeof REQUIRED_OPS)[number] | 'handshake';
+type PendingRequest = {
+ resolve: (value: unknown) => void;
+ reject: (err: Error) => void;
+ timer: number;
+ interactive: boolean;
+};
+
+type SandboxBuild = {
+ sandboxVersion?: string;
+ buildHash?: string;
+};
+
+type ReadyMessage = {
+ type: 'ready';
+ channel: typeof CHANNEL;
+ version: typeof VERSION;
+ build?: SandboxBuild;
+ capabilities?: { operations?: string[] };
+};
+
+type TerminalMessage =
+ | { channel: typeof CHANNEL; version: typeof VERSION; id: string; ok: true; result: unknown }
+ | { channel: typeof CHANNEL; version: typeof VERSION; id: string; ok: false; error: { code?: string; message?: string; retryable?: boolean } | string };
+
+export type VaultSandboxState = 'needs-setup' | 'locked' | 'unlocked';
+
+export type VaultSandboxStatusResult = {
+ state: VaultSandboxState;
+ expiresAt?: number | null;
+ freshSetup?: boolean;
+};
+
+export type VaultSandboxSetupResult = {
+ wrapMeta: string;
+ rpId: string;
+ credentialId: string;
+ authzRegistration?: VaultWebAuthnRegistrationPayload;
+ state: 'unlocked';
+ expiresAt?: number;
+};
+
+export type VaultSandboxUnlockResult = {
+ state: 'unlocked';
+ expiresAt?: number;
+ wrapMeta?: string;
+};
+
+export type VaultSandboxSealResult = {
+ envelope: ProtectedRecordEnvelope;
+ establishingVmk: boolean;
+ publicKey?: string;
+ addresses?: SigningAddresses;
+};
+
+export type VaultSandboxDeleteAssertionResult = {
+ challengeId: string;
+ assertion: VaultDeleteAuthz | VaultWebAuthnSerializedCredential;
+};
+
+export type DaemonAgentBinding = {
+ challengeId: string;
+ requestId: string;
+ grantId: string;
+ agent: {
+ publicKey: { public_key: string; fingerprint?: string };
+ fingerprint: string;
+ };
+ context: Record<string, unknown>;
+ expiresAt: string;
+ signature: { alg: 'ed25519'; keyId: string; value: string };
+};
+
+export type VaultSandboxSigningContext = Record<string, unknown>;
+
+export class VaultSandboxError extends Error {
+ readonly code: string;
+ readonly retryable: boolean;
+
+ constructor(code: string, message: string, retryable = false) {
+ super(message);
+ this.name = 'VaultSandboxError';
+ this.code = code;
+ this.retryable = retryable;
+ }
+}
+
+let integrityPromise: Promise<void> | null = null;
+let singleton: Promise<VaultSandboxClient> | null = null;
+
+function isObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value != null && !Array.isArray(value);
+}
+
+function randomId(): string {
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
+ return [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
+}
+
+function base64(bytes: ArrayBuffer): string {
+ const raw = String.fromCharCode(...new Uint8Array(bytes));
+ return btoa(raw);
+}
+
+async function sha256Subresource(value: ArrayBuffer): Promise<string> {
+ return `sha256-${base64(await crypto.subtle.digest('SHA-256', value))}`;
+}
+
+function failIntegrity(message: string): never {
+ throw new VaultSandboxError('sandbox_integrity_failed', message);
+}
+
+function sameManifestShape(live: unknown): live is typeof VAULT_SANDBOX_PINNED_MANIFEST {
+ if (!isObject(live) || live.algorithm !== VAULT_SANDBOX_PINNED_MANIFEST.algorithm || !isObject(live.resources)) {
+ return false;
+ }
+ const liveResources = live.resources as Record<string, unknown>;
+ const pinnedEntries = Object.entries(VAULT_SANDBOX_PINNED_MANIFEST.resources);
+ if (Object.keys(liveResources).length !== pinnedEntries.length) return false;
+ return pinnedEntries.every(([path, digest]) => liveResources[path] === digest);
+}
+
+export async function verifyVaultSandboxIntegrity(): Promise<void> {
+ if (integrityPromise) return integrityPromise;
+ integrityPromise = (async () => {
+ if (typeof window === 'undefined' || typeof crypto === 'undefined' || !crypto.subtle) {
+ failIntegrity('Sandbox integrity requires Web Crypto in a browser context');
+ }
+ const manifestUrl = `${VAULT_SANDBOX_ORIGIN}${VAULT_SANDBOX_MANIFEST_PATH}`;
+ const manifestResponse = await fetch(manifestUrl, { cache: 'no-store', mode: 'cors', credentials: 'omit' });
+ if (!manifestResponse.ok) {
+ failIntegrity(`Unable to fetch sandbox manifest (${manifestResponse.status})`);
+ }
+ const liveManifest = await manifestResponse.json();
+ if (!sameManifestShape(liveManifest)) {
+ failIntegrity('Sandbox manifest does not match the pinned build manifest');
+ }
+ if (!VAULT_SANDBOX_REQUIRED_RESOURCE_PATHS.includes(VAULT_SANDBOX_IFRAME_RESOURCE_PATH)) {
+ failIntegrity('Sandbox iframe URL is not pinned in the build manifest');
+ }
+
+ await Promise.all(
+ VAULT_SANDBOX_REQUIRED_RESOURCE_PATHS.map(async (path) => {
+ const response = await fetch(`${VAULT_SANDBOX_ORIGIN}${path}`, {
+ cache: 'no-store',
+ mode: 'cors',
+ credentials: 'omit',
+ });
+ if (!response.ok) {
+ failIntegrity(`Unable to fetch sandbox resource ${path} (${response.status})`);
+ }
+ const actual = await sha256Subresource(await response.arrayBuffer());
+ const expected = VAULT_SANDBOX_PINNED_MANIFEST.resources[path];
+ if (actual !== expected) {
+ failIntegrity(`Sandbox resource hash mismatch for ${path}`);
+ }
+ }),
+ );
+ })().catch((err) => {
+ integrityPromise = null;
+ throw err;
+ });
+ return integrityPromise;
+}
+
+function serializeSandboxError(error: { code?: string; message?: string; retryable?: boolean } | string): VaultSandboxError {
+ if (typeof error === 'string') return new VaultSandboxError('sandbox_error', error);
+ return new VaultSandboxError(
+ typeof error?.code === 'string' ? error.code : 'sandbox_error',
+ typeof error?.message === 'string' ? error.message : 'Sandbox request failed',
+ Boolean(error?.retryable),
+ );
+}
+
+function parseReadyMessage(data: unknown): ReadyMessage | null {
+ if (!isObject(data)) return null;
+ if (data.type !== 'ready' || data.channel !== CHANNEL || data.version !== VERSION) return null;
+ return data as ReadyMessage;
+}
+
+function parseTerminalMessage(data: unknown): TerminalMessage | null {
+ if (!isObject(data)) return null;
+ if (data.channel !== CHANNEL || data.version !== VERSION || typeof data.id !== 'string') return null;
+ if (data.ok === true && 'result' in data) return data as TerminalMessage;
+ if (data.ok === false && 'error' in data) return data as TerminalMessage;
+ return null;
+}
+
+export class VaultSandboxClient {
+ private iframe: HTMLIFrameElement;
+ private pending = new Map<string, PendingRequest>();
+ private readyPromise: Promise<ReadyMessage>;
+ private interactiveDepth = 0;
+
+ private constructor(iframe: HTMLIFrameElement) {
+ this.iframe = iframe;
+ this.readyPromise = this.waitForReady();
+ window.addEventListener('message', this.handleMessage);
+ }
+
+ static async create(): Promise<VaultSandboxClient> {
+ await verifyVaultSandboxIntegrity();
+ const iframe = document.createElement('iframe');
+ iframe.title = 'Avibe protected vault sandbox';
+ iframe.allow = 'publickey-credentials-get; publickey-credentials-create; clipboard-write';
+ iframe.referrerPolicy = 'no-referrer';
+ iframe.style.position = 'fixed';
+ iframe.style.inset = '0';
+ iframe.style.width = '100vw';
+ iframe.style.height = '100vh';
+ iframe.style.border = '0';
+ iframe.style.background = 'transparent';
+ iframe.style.zIndex = '2147483647';
+ iframe.style.pointerEvents = 'none';
+ iframe.style.colorScheme = 'normal';
+
+ const client = new VaultSandboxClient(iframe);
+ iframe.src = VAULT_SANDBOX_IFRAME_URL;
+ document.body.appendChild(iframe);
+ await client.handshake();
+ return client;
+ }
+
+ private get target(): Window {
+ const target = this.iframe.contentWindow;
+ if (!target) throw new VaultSandboxError('sandbox_unavailable', 'Sandbox iframe is unavailable', true);
+ return target;
+ }
+
+ private setInteractive(active: boolean): void {
+ this.interactiveDepth += active ? 1 : -1;
+ this.interactiveDepth = Math.max(0, this.interactiveDepth);
+ this.iframe.style.pointerEvents = this.interactiveDepth > 0 ? 'auto' : 'none';
+ }
+
+ private waitForReady(): Promise<ReadyMessage> {
+ return new Promise((resolve, reject) => {
+ const timer = window.setTimeout(() => {
+ window.removeEventListener('message', onMessage);
+ reject(new VaultSandboxError('sandbox_ready_timeout', 'Sandbox did not become ready', true));
+ }, DEFAULT_TIMEOUT_MS);
+ const onMessage = (event: MessageEvent) => {
+ if (event.origin !== VAULT_SANDBOX_ORIGIN || event.source !== this.iframe.contentWindow) return;
+ const ready = parseReadyMessage(event.data);
+ if (!ready) return;
+ window.clearTimeout(timer);
+ window.removeEventListener('message', onMessage);
+ const operations = ready.capabilities?.operations ?? [];
+ const missing = REQUIRED_OPS.filter((op) => !operations.includes(op));
+ if (ready.build?.buildHash !== VAULT_SANDBOX_EXPECTED_BUILD_HASH) {
+ reject(new VaultSandboxError('sandbox_build_mismatch', 'Sandbox build hash does not match the pinned manifest'));
+ } else if (missing.length > 0) {
+ reject(new VaultSandboxError('sandbox_capability_mismatch', `Sandbox is missing operations: ${missing.join(', ')}`));
+ } else {
+ resolve(ready);
+ }
+ };
+ window.addEventListener('message', onMessage);
+ });
+ }
+
+ private handleMessage = (event: MessageEvent): void => {
+ if (event.origin !== VAULT_SANDBOX_ORIGIN || event.source !== this.iframe.contentWindow) return;
+ const reply = parseTerminalMessage(event.data);
+ if (!reply) return;
+ const pending = this.pending.get(reply.id);
+ if (!pending) return;
+ this.pending.delete(reply.id);
+ window.clearTimeout(pending.timer);
+ if (pending.interactive) this.setInteractive(false);
+ if (reply.ok) {
+ pending.resolve(reply.result);
+ } else {
+ pending.reject(serializeSandboxError(reply.error));
+ }
+ };
+
+ private async handshake(): Promise<void> {
+ await this.readyPromise;
+ await this.request(
+ 'handshake',
+ {
+ parentOrigin: window.location.origin,
+ nonce: randomId(),
+ expectedBuildHash: VAULT_SANDBOX_EXPECTED_BUILD_HASH,
+ },
+ { timeoutMs: DEFAULT_TIMEOUT_MS },
+ );
+ }
+
+ private async request<T>(
+ op: VaultSandboxOp,
+ payload?: unknown,
+ options: { timeoutMs?: number; interactive?: boolean } = {},
+ ): Promise<T> {
+ await this.readyPromise;
+ const id = randomId();
+ const interactive = Boolean(options.interactive);
+ if (interactive) this.setInteractive(true);
+ const promise = new Promise<T>((resolve, reject) => {
+ const timer = window.setTimeout(() => {
+ this.pending.delete(id);
+ if (interactive) this.setInteractive(false);
+ reject(new VaultSandboxError('sandbox_request_timeout', `Sandbox ${op} request timed out`, true));
+ }, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
+ this.pending.set(id, {
+ resolve: (value) => resolve(value as T),
+ reject,
+ timer,
+ interactive,
+ });
+ });
+ this.target.postMessage({ channel: CHANNEL, version: VERSION, id, op, payload: payload ?? {} }, VAULT_SANDBOX_ORIGIN);
+ return promise;
+ }
+
+ status(wrapMeta?: string | null): Promise<VaultSandboxStatusResult> {
+ return this.request<VaultSandboxStatusResult>('status', wrapMeta ? { wrapMeta } : {});
+ }
+
+ setup(payload: {
+ vaultUserHandle: string;
+ displayName: string;
+ existingProtectedVault: boolean;
+ authzCreationOptions?: unknown;
+ rootMetadata?: unknown;
+ }): Promise<VaultSandboxSetupResult> {
+ return this.request<VaultSandboxSetupResult>('setup', payload, {
+ timeoutMs: INTERACTIVE_TIMEOUT_MS,
+ interactive: true,
+ });
+ }
+
+ unlock(payload: { wrapMeta: string }): Promise<VaultSandboxUnlockResult> {
+ return this.request<VaultSandboxUnlockResult>('unlock', payload, {
+ timeoutMs: INTERACTIVE_TIMEOUT_MS,
+ interactive: true,
+ });
+ }
+
+ lock(): Promise<{ ok?: boolean }> {
+ return this.request<{ ok?: boolean }>('lock', {}, { timeoutMs: DEFAULT_TIMEOUT_MS });
+ }
+
+ seal(payload: {
+ name: string;
+ kind: 'static' | 'keypair';
+ inputMode: 'sandbox-entry';
+ wrapMeta?: string | null;
+ }): Promise<VaultSandboxSealResult> {
+ return this.request<VaultSandboxSealResult>('seal', payload, {
+ timeoutMs: INTERACTIVE_TIMEOUT_MS,
+ interactive: true,
+ });
+ }
+
+ unseal(payload: {
+ material: ProtectedUnlockMaterialLike;
+ mode: 'sandbox-display' | 'sandbox-copy';
+ }): Promise<{ completed: boolean }> {
+ return this.request<{ completed: boolean }>('unseal', payload, {
+ timeoutMs: INTERACTIVE_TIMEOUT_MS,
+ interactive: true,
+ });
+ }
+
+ sign(payload: {
+ material: ProtectedUnlockMaterialLike;
+ scheme: SignatureScheme;
+ signingContext: VaultSandboxSigningContext;
+ }): Promise<SignatureResult> {
+ return this.request<SignatureResult>('sign', payload, {
+ timeoutMs: INTERACTIVE_TIMEOUT_MS,
+ interactive: true,
+ });
+ }
+
+ releaseDEK(payload: {
+ material: ProtectedUnlockMaterialLike;
+ agentBinding: DaemonAgentBinding;
+ }): Promise<BlindBox> {
+ return this.request<BlindBox>('releaseDEK', payload, {
+ timeoutMs: INTERACTIVE_TIMEOUT_MS,
+ interactive: true,
+ });
+ }
+
+ deleteAuthzAssertion(payload: {
+ challengeId: string;
+ operation: 'delete_secret';
+ secretName: string;
+ webauthn: VaultDeleteChallengeResult['webauthn'];
+ }): Promise<VaultSandboxDeleteAssertionResult> {
+ return this.request<VaultSandboxDeleteAssertionResult>('deleteAuthzAssertion', payload, {
+ timeoutMs: INTERACTIVE_TIMEOUT_MS,
+ interactive: true,
+ });
+ }
+}
+
+type ProtectedUnlockMaterialLike = {
+ name: string;
+ kind?: string | null;
+ envelope: ProtectedRecordEnvelope;
+};
+
+export async function getVaultSandboxClient(): Promise<VaultSandboxClient> {
+ if (!singleton) {
+ singleton = VaultSandboxClient.create().catch((err) => {
+ singleton = null;
+ throw err;
+ });
+ }
+ return singleton;
+}
diff --git a/ui/src/lib/vaultSandboxManifest.ts b/ui/src/lib/vaultSandboxManifest.ts
new file mode 100644
index 000000000..f8532d9de
--- /dev/null
+++ b/ui/src/lib/vaultSandboxManifest.ts
@@ -0,0 +1,33 @@
+export const VAULT_SANDBOX_ORIGIN = 'https://sandbox.avibe.bot';
+export const VAULT_SANDBOX_VERSION = '0.1.0';
+export const VAULT_SANDBOX_EXPECTED_BUILD_HASH = 'dev';
+
+export type VaultSandboxPinnedManifest = {
+ algorithm: 'sha256';
+ resources: Record<string, string>;
+};
+
+export const VAULT_SANDBOX_PINNED_MANIFEST: VaultSandboxPinnedManifest = {
+ algorithm: 'sha256',
+ resources: {
+ '/assets/index.CWzpiVRF.js': 'sha256-I6MUHfT7DaD2Mg5OVURvZBsY1uA6TA7sf7XcBkZBo0A=',
+ '/assets/index.CWzpiVRF.js.map': 'sha256-iYuql8cyRd3rf5gc6Ugx3L41WW2lPtoDf/zr+7XtnTo=',
+ '/assets/index.DpR35930.css': 'sha256-uk4usRuXbzaL7jOMlnzNPB+yaMVpnTMgriiC/zqRHoY=',
+ '/assets/nodeCryptoShim.DTwgsOT4.js': 'sha256-2Jr4p1Eu6bEPGgodAN8w7H7v/nkdob9vyK5uAmjpmrI=',
+ '/assets/nodeCryptoShim.DTwgsOT4.js.map': 'sha256-XeygI0Eab/VrjUng2V68o/bOP8UijmyexNz7YkwH4j4=',
+ '/index.html': 'sha256-d5Q3RQE/yyoqhghSbme/DDoxkIUeTzZuzrUPW/gx+oY=',
+ },
+};
+
+export const VAULT_SANDBOX_REQUIRED_RESOURCE_PATHS = Object.keys(VAULT_SANDBOX_PINNED_MANIFEST.resources)
+ .filter((path) => !path.endsWith('.map'))
+ .sort();
+
+export const VAULT_SANDBOX_MANIFEST_PATH = '/build-manifest.json';
+export const VAULT_SANDBOX_IFRAME_RESOURCE_PATH = '/index.html';
+
+// The iframe navigates to the exact document URL that the parent fetches and hashes.
+// Sandbox hosting should move this resource to an immutable /v/<version>/ path as soon as
+// the static host publishes one; until then the identical-URL gate closes the prior query
+// string equivocation gap while the pinned manifest remains the authority.
+export const VAULT_SANDBOX_IFRAME_URL = `${VAULT_SANDBOX_ORIGIN}${VAULT_SANDBOX_IFRAME_RESOURCE_PATH}`;
diff --git a/vibe/api.py b/vibe/api.py
index 81737d0b0..14e85895b 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1,5 +1,7 @@
import asyncio
+import base64
import contextlib
+import hashlib
import json
import logging
import os
@@ -22,6 +24,7 @@ from typing import Any, Dict, List, Optional
import yaml
from sqlalchemy import select
+from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from config import paths
from config.v2_config import CONFIG_LOCK, V2Config
@@ -1473,6 +1476,222 @@ def get_vault_vmk() -> dict:
return {"ok": True, "exists": wrap_meta is not None, "wrap_meta": wrap_meta}
+_VAULT_DAEMON_AGENT_BINDING_KEY = "vault.daemon_agent_binding_key.v1"
+
+
+def _b64(data: bytes) -> str:
+ return base64.b64encode(data).decode("ascii")
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def _parse_vault_daemon_binding_key(raw: object) -> dict[str, str] | None:
+ if not isinstance(raw, str):
+ return None
+ with contextlib.suppress(Exception):
+ payload = json.loads(raw)
+ if (
+ isinstance(payload, dict)
+ and isinstance(payload.get("keyId"), str)
+ and isinstance(payload.get("privateKey"), str)
+ and isinstance(payload.get("publicKey"), str)
+ ):
+ return payload
+ return None
+
+
+def _new_vault_daemon_binding_key() -> dict[str, str]:
+ from cryptography.hazmat.primitives import serialization
+ from cryptography.hazmat.primitives.asymmetric import ed25519
+
+ private_key = ed25519.Ed25519PrivateKey.generate()
+ private_raw = private_key.private_bytes(
+ encoding=serialization.Encoding.Raw,
+ format=serialization.PrivateFormat.Raw,
+ encryption_algorithm=serialization.NoEncryption(),
+ )
+ public_raw = private_key.public_key().public_bytes(
+ encoding=serialization.Encoding.Raw,
+ format=serialization.PublicFormat.Raw,
+ )
+ key_id = "vault-daemon-ed25519-v1"
+ return {"keyId": key_id, "privateKey": _b64(private_raw), "publicKey": _b64(public_raw)}
+
+
+def _load_or_create_vault_daemon_binding_key(conn) -> dict[str, str]:
+ from storage.models import state_meta
+
+ raw = conn.execute(
+ select(state_meta.c.value_json).where(state_meta.c.key == _VAULT_DAEMON_AGENT_BINDING_KEY)
+ ).scalar_one_or_none()
+ existing = _parse_vault_daemon_binding_key(raw)
+ if existing is not None:
+ return existing
+
+ payload = _new_vault_daemon_binding_key()
+ stmt = sqlite_insert(state_meta).values(
+ key=_VAULT_DAEMON_AGENT_BINDING_KEY,
+ value_json=json.dumps(payload, sort_keys=True),
+ updated_at=_utc_now_iso(),
+ )
+ conn.execute(stmt.on_conflict_do_nothing(index_elements=[state_meta.c.key]))
+ raw = conn.execute(
+ select(state_meta.c.value_json).where(state_meta.c.key == _VAULT_DAEMON_AGENT_BINDING_KEY)
+ ).scalar_one_or_none()
+ existing = _parse_vault_daemon_binding_key(raw)
+ if existing is not None:
+ return existing
+
+ conn.execute(
+ state_meta.update()
+ .where(state_meta.c.key == _VAULT_DAEMON_AGENT_BINDING_KEY)
+ .values(value_json=json.dumps(payload, sort_keys=True), updated_at=_utc_now_iso())
+ )
+ return payload
+
+
+def get_vault_sandbox_root_metadata() -> dict:
+ engine = _vault_engine()
+ with engine.begin() as conn:
+ key = _load_or_create_vault_daemon_binding_key(conn)
+ return {
+ "ok": True,
+ "root_metadata": {
+ "daemon": {
+ "verificationKeys": [
+ {
+ "alg": "ed25519",
+ "keyId": key["keyId"],
+ "publicKey": key["publicKey"],
+ }
+ ]
+ }
+ },
+ }
+
+
+def _u64_be(value: int) -> bytes:
+ if value < 0 or value > 0xFFFF_FFFF_FFFF_FFFF:
+ raise VaultApiError("ttl_seconds out of bounds", code="invalid_grant")
+ return value.to_bytes(8, "big")
+
+
+def _length_prefixed(fields: list[str | bytes]) -> bytes:
+ out = bytearray()
+ for field in fields:
+ data = field.encode("utf-8") if isinstance(field, str) else field
+ if len(data) > 0xFFFF_FFFF:
+ raise VaultApiError("blind-box AAD field is too large", code="invalid_grant")
+ out.extend(len(data).to_bytes(4, "big"))
+ out.extend(data)
+ return bytes(out)
+
+
+def _agent_deliver_operation_hash(name: str, ttl_seconds: int) -> str:
+ return hashlib.sha256(
+ _length_prefixed(["agent-deliver", name, _u64_be(ttl_seconds)])
+ ).hexdigest()
+
+
+def _signed_agent_binding(binding: dict[str, Any], key: dict[str, str]) -> dict[str, Any]:
+ from cryptography.hazmat.primitives.asymmetric import ed25519
+
+ private_key = ed25519.Ed25519PrivateKey.from_private_bytes(base64.b64decode(key["privateKey"]))
+ canonical = json.dumps(binding, sort_keys=True, separators=(",", ":"))
+ signature = _b64(private_key.sign(canonical.encode("utf-8")))
+ return {
+ **binding,
+ "signature": {
+ "alg": "ed25519",
+ "keyId": key["keyId"],
+ "value": signature,
+ },
+ }
+
+
+def create_vault_agent_binding(payload: dict) -> dict:
+ from storage import vault_crypto, vault_service
+
+ if not isinstance(payload, dict):
+ raise VaultApiError("payload must be an object", code="invalid_payload")
+ request_id = str(payload.get("request_id") or payload.get("requestId") or "").strip()
+ grant_id = str(payload.get("grant_id") or payload.get("grantId") or "").strip()
+ name = str(payload.get("name") or "").strip()
+ try:
+ ttl_seconds = int(payload.get("ttl_seconds") or payload.get("ttlSecs") or 300)
+ except (TypeError, ValueError) as exc:
+ raise VaultApiError("ttl_seconds must be an integer", code="invalid_grant") from exc
+ if not request_id or not grant_id:
+ raise VaultApiError("request_id and grant_id are required", code="invalid_request", status=409)
+ if ttl_seconds < 1 or ttl_seconds > 24 * 60 * 60:
+ raise VaultApiError("ttl_seconds out of bounds", code="invalid_grant")
+ if not vault_crypto.is_valid_secret_name(name):
+ raise VaultApiError("invalid secret name (use ^[A-Za-z_][A-Za-z0-9_]*$)", code="invalid_name")
+
+ engine = _vault_engine()
+ with engine.begin() as conn:
+ option = _grant_option_from_request(conn, request_id)
+ if grant_id != option["grant_id"]:
+ raise VaultApiError("grant id does not match the approval request", code="invalid_request", status=409)
+ if name not in set(option["member_names"]):
+ raise VaultApiError("secret is not part of the approval request", code="invalid_request", status=409)
+ try:
+ meta = vault_service.get_secret_meta(conn, name)
+ except vault_service.SecretNotFoundError as exc:
+ raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc
+ if meta.get("protection") != "protected":
+ raise VaultApiError("agent binding is only valid for protected secrets", code="not_protected", status=409)
+ key = _load_or_create_vault_daemon_binding_key(conn)
+
+ try:
+ _require_avault_grant_delivery_surface("resident agent grant")
+ agent_pubkey = avault_agent_pubkey()
+ except AvaultError as exc:
+ raise _vault_api_error_from_avault(exc, prefix="avault agent binding failed") from exc
+
+ now = datetime.now(timezone.utc)
+ expires_at = now + timedelta(seconds=ttl_seconds)
+ expires_at_unix = int(expires_at.timestamp())
+ approval_nonce = list(os.urandom(16))
+ context = {
+ "purpose": "agent-deliver",
+ "name": name,
+ "grantId": grant_id,
+ "ttlSecs": ttl_seconds,
+ "approvalNonce": approval_nonce,
+ "approvalExpiresAtUnix": expires_at_unix,
+ "operationHash": _agent_deliver_operation_hash(name, ttl_seconds),
+ }
+ binding = {
+ "challengeId": f"vab_{uuid.uuid4().hex}",
+ "requestId": request_id,
+ "grantId": grant_id,
+ "agent": {
+ "publicKey": {
+ "public_key": str(agent_pubkey["public_key"]),
+ "fingerprint": str(agent_pubkey["fingerprint"]),
+ },
+ "fingerprint": str(agent_pubkey["fingerprint"]),
+ },
+ "context": context,
+ "expiresAt": expires_at.isoformat().replace("+00:00", "Z"),
+ }
+ return {
+ "ok": True,
+ "agent_pubkey": {
+ "public_key": str(agent_pubkey["public_key"]),
+ "fingerprint": str(agent_pubkey["fingerprint"]),
+ },
+ "binding": _signed_agent_binding(binding, key),
+ "approval": {
+ "nonce": _b64(bytes(approval_nonce)),
+ "expires_at_unix": expires_at_unix,
+ },
+ }
+
+
def _vault_webauthn_context(origin: str | None):
from storage import vault_webauthn
@@ -2016,11 +2235,17 @@ def request_vault_sign(payload: dict) -> dict:
code="unsupported_signer_kind",
status=409,
)
+ signing_context = _verifiable_signing_context_from_payload(
+ payload,
+ digest=digest,
+ required=meta.get("protection") == "protected",
+ )
request = vault_service.create_sign_request(
conn,
name,
digest=digest,
scheme=scheme,
+ signing_context=signing_context,
requester=_vault_requester_payload(payload),
delivery=_vault_delivery_payload(payload),
expires_at=_expires_at_from_ttl(payload),
@@ -2544,6 +2769,40 @@ def _sign_digest_from_payload(value: object) -> str:
return digest.lower()
+def _verifiable_signing_context_from_payload(payload: dict, *, digest: str, required: bool = False) -> dict[str, Any] | None:
+ context = payload.get("signing_context")
+ if context is None:
+ context = payload.get("signingContext")
+ if context is None:
+ delivery = payload.get("delivery")
+ if isinstance(delivery, dict):
+ context = delivery.get("signing_context") if delivery.get("signing_context") is not None else delivery.get("signingContext")
+ if context is None:
+ if required:
+ raise VaultApiError("protected signing requires a verifiable signing_context", code="missing_signing_context", status=409)
+ return None
+ if not isinstance(context, dict):
+ raise VaultApiError("signing_context must be an object", code="invalid_request", status=409)
+ kind = context.get("kind")
+ if kind not in {"evm-transaction", "eip-712-typed-data", "avault-agent-operation"}:
+ raise VaultApiError("unsupported signing_context kind", code="invalid_request", status=409)
+ context_digest = context.get("digest")
+ if not isinstance(context_digest, str) or context_digest.lower() != digest:
+ raise VaultApiError("signing_context digest must match the sign request digest", code="invalid_request", status=409)
+ if kind == "evm-transaction":
+ if context.get("digestAlgorithm") != "keccak256" or not isinstance(context.get("chainId"), str):
+ raise VaultApiError("invalid evm signing_context", code="invalid_request", status=409)
+ if "unsignedTransaction" not in context:
+ raise VaultApiError("invalid evm signing_context", code="invalid_request", status=409)
+ elif kind == "eip-712-typed-data":
+ if context.get("digestAlgorithm") != "eip712" or "typedData" not in context:
+ raise VaultApiError("invalid EIP-712 signing_context", code="invalid_request", status=409)
+ else:
+ if context.get("digestAlgorithm") != "avault-operation-hash-v1" or not isinstance(context.get("canonicalPreimage"), str):
+ raise VaultApiError("invalid avault operation signing_context", code="invalid_request", status=409)
+ return dict(context)
+
+
def _protected_sign_invalid(message: str) -> VaultApiError:
return VaultApiError(message, code="invalid_request", status=409)
@@ -2873,11 +3132,13 @@ def vault_sign(payload: dict) -> dict:
if meta.get("protection") == "protected":
signature = payload.get("signature")
if not isinstance(signature, dict):
+ signing_context = _verifiable_signing_context_from_payload(payload, digest=digest, required=True)
request = vault_service.create_sign_request(
conn,
name,
digest=digest,
scheme=scheme,
+ signing_context=signing_context,
requester=payload.get("requester") if isinstance(payload.get("requester"), dict) else None,
delivery=payload.get("delivery") if isinstance(payload.get("delivery"), dict) else None,
)
@@ -2892,7 +3153,14 @@ def vault_sign(payload: dict) -> dict:
request_id = str(payload.get("request_id") or "")
if not request_id:
raise VaultApiError("request_id is required to complete protected signing", code="missing_request_id")
- vault_service.validate_sign_request(conn, request_id, name=name, digest=digest, scheme=scheme)
+ sign_request = vault_service.validate_sign_request(conn, request_id, name=name, digest=digest, scheme=scheme)
+ delivery = sign_request.get("delivery") if isinstance(sign_request.get("delivery"), dict) else {}
+ if not isinstance(delivery.get("signing_context"), dict):
+ raise VaultApiError(
+ "protected signing request is missing a verifiable signing_context",
+ code="missing_signing_context",
+ status=409,
+ )
signature = _normalized_protected_signature(signature)
# `meta` is the masked payload (derived addresses only, no raw key); source
# the pinned public key from storage for server-side verification.
diff --git a/vibe/cli.py b/vibe/cli.py
index 4a66a5c26..f4499b3ef 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -4714,6 +4714,20 @@ def _vault_cli_delivery(args, **fields) -> dict:
return delivery
+def _vault_cli_signing_context(args, *, digest: str, help_command: str) -> dict | None:
+ raw = getattr(args, "signing_context_json", None)
+ if raw is None:
+ return None
+ try:
+ context = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise TaskCliError("signing context must be valid JSON", code="invalid_signing_context", help_command=help_command) from exc
+ try:
+ return api._verifiable_signing_context_from_payload({"signing_context": context}, digest=digest, required=True)
+ except api.VaultApiError as exc:
+ raise TaskCliError(str(exc), code=exc.code, help_command=help_command) from exc
+
+
def _publish_cli_vaults_updated(
*,
scope: str,
@@ -6633,6 +6647,7 @@ def cmd_vault_sign(args):
raise TaskCliError(f"invalid secret name: {name!r} (use ^[A-Za-z_][A-Za-z0-9_]*$)", code="invalid_name", help_command=help_command)
digest = api._sign_digest_from_payload(getattr(args, "digest", None))
scheme = getattr(args, "scheme", None) or "ecdsa-secp256k1-recoverable"
+ signing_context = _vault_cli_signing_context(args, digest=digest, help_command=help_command)
engine = _open_vault_engine()
with engine.begin() as conn:
meta = vault_service.get_secret_meta(conn, name)
@@ -6645,12 +6660,19 @@ def cmd_vault_sign(args):
help_command=help_command,
)
needs_approval = vault_service.sign_needs_approval(conn, name)
+ if meta.get("protection") == "protected" and signing_context is None:
+ raise TaskCliError(
+ "protected signing requires --signing-context-json",
+ code="missing_signing_context",
+ help_command=help_command,
+ )
if needs_approval:
request = vault_service.create_sign_request(
conn,
name,
digest=digest,
scheme=scheme,
+ signing_context=signing_context,
requester=_vault_cli_requester(args),
delivery=_vault_cli_delivery(args, mode="sign"),
)
@@ -6660,6 +6682,7 @@ def cmd_vault_sign(args):
"name": name,
"digest": digest,
"scheme": scheme,
+ "signing_context": signing_context,
"requester": _vault_cli_requester(args),
}
)
@@ -10889,6 +10912,10 @@ def build_parser():
vault_sign_parser.add_argument("--skill", help="Skill requesting the signature")
vault_sign_parser.add_argument("--command", dest="operation_command", help="Operation shown to the user")
vault_sign_parser.add_argument("--egress", help="Egress description shown to the user")
+ vault_sign_parser.add_argument(
+ "--signing-context-json",
+ help="Verifiable signing context JSON required for protected keypairs",
+ )
vault_sign_parser.add_argument(
"--no-callback",
action="store_true",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 519bcb375..482b4f59b 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -124,6 +124,12 @@ TRACEBACK_EXCEPTION_PATTERN = re.compile(
)
CSRF_COOKIE_NAME = "vibe_csrf_token"
CSRF_HEADER_NAME = "X-Vibe-CSRF-Token"
+VAULT_SANDBOX_ORIGIN = "https://sandbox.avibe.bot"
+VAULT_SANDBOX_PERMISSIONS_POLICY = (
+ f'publickey-credentials-get=("{VAULT_SANDBOX_ORIGIN}"), '
+ f'publickey-credentials-create=("{VAULT_SANDBOX_ORIGIN}"), '
+ f'clipboard-write=(self "{VAULT_SANDBOX_ORIGIN}")'
+)
REMOTE_OAUTH_COOKIE_NAME = "__Host-vibe_remote_oauth"
REMOTE_OAUTH_RETRY_PARAM = "__vibe_oauth_retry"
# Lifetime of the short-lived OAuth handshake (signed state + PKCE cookie). The
@@ -2130,6 +2136,40 @@ def add_csrf_cookie(response: Response) -> Response:
return _ensure_csrf_cookie(response)
+def _merge_csp_frame_src(existing: str | None) -> str:
+ required = ["'self'", VAULT_SANDBOX_ORIGIN]
+ if not existing:
+ return f"frame-src {' '.join(required)}"
+ directives = [part.strip() for part in existing.split(";") if part.strip()]
+ for index, directive in enumerate(directives):
+ name, _, rest = directive.partition(" ")
+ if name.lower() != "frame-src":
+ continue
+ tokens = rest.split()
+ for token in required:
+ if token not in tokens:
+ tokens.append(token)
+ directives[index] = f"frame-src {' '.join(tokens)}"
+ return "; ".join(directives)
+ directives.append(f"frame-src {' '.join(required)}")
+ return "; ".join(directives)
+
+
+def _is_show_page_response_path(path: str) -> bool:
+ return path == "/show" or path.startswith("/show/") or path == "/p" or path.startswith("/p/")
+
+
+def add_vault_sandbox_security_headers(response: Response) -> Response:
+ if _is_show_page_response_path(request.path):
+ return response
+ response.headers["Permissions-Policy"] = VAULT_SANDBOX_PERMISSIONS_POLICY
+ response.headers["Content-Security-Policy"] = _merge_csp_frame_src(
+ response.headers.get("Content-Security-Policy")
+ )
+ return response
+
+
@app.after_request
def renew_remote_access_cookie(response: Response) -> Response:
# Logout handler explicitly clears the session cookie; never re-issue it.
@@ -3091,6 +3131,10 @@ def _webauthn_request_origin() -> str:
return f"{scheme}://{host}"
+def _vault_sandbox_webauthn_origin() -> str:
+ return VAULT_SANDBOX_ORIGIN
+
+
@app.route("/api/vault/secrets", methods=["GET"])
def vault_secrets_get():
from vibe import api
@@ -3139,6 +3183,26 @@ def vault_agent_pubkey_get():
return _vault_error_response(exc)
[email protected]("/api/vault/sandbox/root-metadata", methods=["GET"])
+def vault_sandbox_root_metadata_get():
+ from vibe import api
+
+ try:
+ return jsonify(api.get_vault_sandbox_root_metadata())
+ except ValueError as exc:
+ return _vault_error_response(exc)
+
+
[email protected]("/api/vault/agent-binding", methods=["POST"])
+def vault_agent_binding_post():
+ from vibe import api
+
+ try:
+ return jsonify(api.create_vault_agent_binding(request.json or {}))
+ except ValueError as exc:
+ return _vault_error_response(exc)
+
+
@app.route("/api/vault/vmk", methods=["GET"])
def vault_vmk_get():
from vibe import api
@@ -3151,7 +3215,7 @@ def vault_authz_webauthn_options_post():
from vibe import api
try:
- return jsonify(api.create_vault_authz_webauthn_options(origin=_webauthn_request_origin()))
+ return jsonify(api.create_vault_authz_webauthn_options(origin=_vault_sandbox_webauthn_origin()))
except ValueError as exc:
return _vault_error_response(exc)
@@ -3161,7 +3225,7 @@ def vault_authz_webauthn_register_post():
from vibe import api
try:
- return jsonify(api.register_vault_authz_webauthn_factor(request.json or {}, origin=_webauthn_request_origin()))
+ return jsonify(api.register_vault_authz_webauthn_factor(request.json or {}, origin=_vault_sandbox_webauthn_origin()))
except ValueError as exc:
return _vault_error_response(exc)
@@ -3181,7 +3245,7 @@ def vault_secrets_post():
from vibe import api
try:
- return jsonify(api.create_vault_secret(request.json or {}, origin=_webauthn_request_origin()))
+ return jsonify(api.create_vault_secret(request.json or {}, origin=_vault_sandbox_webauthn_origin()))
except ValueError as exc:
return _vault_error_response(exc)
@@ -3201,7 +3265,7 @@ def vault_secret_delete_challenge(name):
from vibe import api
try:
- return jsonify(api.create_vault_delete_challenge(name, origin=_webauthn_request_origin()))
+ return jsonify(api.create_vault_delete_challenge(name, origin=_vault_sandbox_webauthn_origin()))
except ValueError as exc:
return _vault_error_response(exc)