# 0xkey > This file is very large and may be truncated. For an index of this content, please refer to https://docs.0xkey.io/llms.txt instead. > 0xkey TEE wallet cloud — developer documentation and API reference # Roadmap Source: https://docs.0xkey.io/0xkey/roadmap Current implementation status of 0xkey modules, APIs, chains, and protocols. **Legend:** **Supported** — available in Phase 1 · **Partial** — some flows work or known field differences · **Coming soon** — planned, not yet productized · **N/A** — not exposed in the current public API *** ## Runtime services | Component | Status | Notes | | :- | :- | :- | | Coordinator (activity orchestration, gRPC) | **Supported** | Organization / sub-org, wallet, policy, session dispatch | | Registrar (tenant, proxy config, magic-link session) | **Supported** | Control plane; coordinates with Coordinator for root org creation | | Auth Proxy (`POST /v1/*`) | **Supported** | 9 endpoints: `signup`, `otp_init`, `otp_verify`, `otp_login`, `oauth2_authenticate`, `oauth_login`, `email_auth`, `account`, `wallet_kit_config` — hosted at `https://authproxy.0xkey.io` | | API Gateway (HTTP→gRPC, stamp forwarding) | **Supported** | Full `PublicApiService` via grpc-gateway (`/public/v1/query/*`, `/public/v1/submit/*`) | | Dashboard Gateway + Dashboard (Next.js) | **Partial** | Session / WebAuthn baseline and 40+ console pages (orgs, users, wallets, policies, activities, tenants); full hosted-console narrative not yet complete | | Enclave: Signer | **Supported** | P-256 / secp256k1 / Ed25519 signing | | Enclave: Policy | **Partial** | CEL evaluation, consensus, ETH / Solana / EIP-712 / Tron contexts; per-chain `*.tx.*` parity for other non-EVM chains **Coming soon** | | Enclave: Notarizer | **Supported** | Organization aggregate notarization (genesis / sub-org / refresh / Merkle) | | Enclave: TLS Fetcher | **Supported** | External HTTPS (OIDC JWKS, OAuth token endpoints) with `FetchProof` | | Enclave: Transaction Parser | **Partial** | EVM (legacy + type 1/2/3/4), Solana (legacy + V0), EIP-712, Tron. BTC / Cosmos / Aptos / Sui / Sei / TON / XRP / Stellar / Doge **Coming soon** | | Company Wallets (institutional automation, policy + consensus, custodial send) | **Partial** | SKU docs + server path live — see [Company Wallets](/company-wallets/overview). Dashboard consensus UX / policy versioning / webhook replay hardening in progress. Gas sponsorship is **Enterprise**. Hybrid co-sign optional ([Hybrid co-signing](/company-wallets/hybrid-cosign)). BTC PSBT/policy **Coming soon** | | Verifiable Cloud / TEE product (external SKU) | **Coming soon** | Architecture chapters are illustrative | *** ## Authentication | Component | Status | Notes | | :- | :- | :- | | Passkey / WebAuthn + `stamp_login` | **Supported** | Validated with demo-style frontends | | Google OAuth (OIDC `id_token`) | **Supported** | Requires a real IdP token | | Email OTP | **Supported** | `otp_init` V3, `otp_verify` V2, `otp_login` V2; Resend-backed for email | | SMS OTP | **Partial** | API paths exist (`OTP_TYPE_SMS`); no real SMS provider wired in Phase 1 | | Email auth (magic link, `email_auth`) | **Supported** | Depends on mail delivery configuration | | OAuth2 code exchange (non-OIDC provider) | **Partial** | Enclave paths exist; not every provider is end-to-end validated | | Apple / Facebook / Discord / X social login | **Partial \~ Coming soon** | Depends on `oauthProviders` and deployment | | OIDC Federation (customer-registered IdP) | **Supported** | Org registers its own OIDC issuer via `create_oidc_provider`; enclave enforces issuer/audience allowlist + live JWKS verification for `oauth_login` and `create_oauth_providers`. See [Custom OIDC providers](/authentication/social-logins#custom-oidc-providers-your-own-identity-provider) | | Session: read-write + credential bundle (HPKE) | **Supported** | | | Session: read-only | **Partial** | API + executor wired; current TypeScript SDKs do not expose read-only session helpers | *** ## Public HTTP API | Category | Examples | Status | | :- | :- | :- | | Auth Proxy | `POST /v1/account`, `/v1/otp_init`, `/v1/otp_verify` | **Supported** | | Query | `get_sub_org_ids`, `get_wallets`, `get_wallet_accounts`, `get_user` | **Supported** | | Submit | `create_sub_organization`, `oauth_login` | **Supported** | | Submit | `stamp_login` | **Supported** (requires browser WebAuthn) | | Submit | `eth_send_raw_transaction` | **Partial** (executor wired; broadcast is a mock — `endpoint: "mock"`, no real RPC) | | Submit | `eth_send_transaction` (unsigned high-level, incl. Gas Station `sponsor`) | **Partial** — custodial sponsored / self-paid path wired for supported EVM chains; see Gas Station docs | | Submit | `sol_send_transaction` (unsigned high-level, incl. `sponsor`) | **Supported** — custodial self-paid + Solana fee sponsorship (platform fee-payer dual-sign); see [Sponsored Solana sends](/embedded-wallets/code-examples/sending-sponsored-solana-transactions) | | Submit | `tron_send_transaction` (unsigned high-level; TRX + TRC-20) | **Supported** — custodial build, broadcast, and status monitoring; no fee sponsorship yet; see [Tron](/networks/tron) | | Submit | `create_oauth_providers` (V1/V2) | **Supported** — binds a cryptographically-verified `(iss, sub)` OIDC identity to a user | | Submit / Query | `create_oidc_provider`, `update_oidc_provider`, `delete_oidc_provider`, `get_oidc_providers` | **Supported** — org-level, root-quorum-only trusted-issuer registry for [OIDC Federation](/authentication/social-logins#custom-oidc-providers-your-own-identity-provider) | | Submit / Query | `create_webhook_endpoint`, `update_webhook_endpoint`, `delete_webhook_endpoint`, `list_webhook_endpoints` | **Partial** (wired for `ACTIVITY_UPDATES`; update supports URL/name/active status, not subscription changes) | | Submit | `create_fiat_on_ramp_credential`, `init_fiat_on_ramp` (and CRUD) | **Coming soon** (notarize-only executor, no real on-ramp wired) | | Query | `get_send_transaction_status`, `get_on_ramp_transaction_status`, `get_gas_usage`, `get_nonces` | **Coming soon** (returns empty / zero-valued response) | | Query | `list_fiat_on_ramp_credentials` | **Coming soon** (returns empty list — not yet backed by storage) | | Query | `get_policy_evaluations` | **Partial** (Coordinator persists evaluations best-effort after a Policy ruling; data appears once a parser-backed activity has been evaluated) | | Query | `get_boot_proof`, `get_latest_boot_proof`, `list_app_proofs` | **Supported** — populated by `BootProofWorker` when `qos_host_control` is configured | | Query | `get_balances`, `get_app_status` (a.k.a. TVC App status) | **N/A** (no corresponding RPC in the current `public_api.proto`) | | Query | `get_attestation_document` | **Supported** — live NSM via qos_host (60s cache), store fallback; never returns empty success | | Other activities / queries | Various `create_*`, `sign_*`, `list_*` | **Partial / Coming soon** (depends on Coordinator enablement) | *** ## Chains and curves | Topic | Status | Notes | | :- | :- | :- | | Curve: secp256k1 | **Supported** | Primary EVM signing; BIP32 HD derivation | | Curve: Ed25519 | **Supported** | Solana / Sui / Aptos signing; SLIP-0010 HD (hardened-only) | | Curve: P-256 | **Supported** | WebAuthn and session keys (no HD derivation) | | **EVM** (Ethereum L1/L2) | **Supported** | Address derivation, in-enclave tx parsing, EIP-712, policy contexts | | **Solana (SVM)** | **Partial** | Address derivation + Ed25519 signing + in-enclave parsing + custodial `sol_send_transaction` (self-paid and fee sponsorship) **Supported**; rent sponsorship / ALT-sponsored patterns still constrained — see [Solana](/networks/solana) | | **Tron** | **Partial** | Address derivation + in-enclave tx parsing + policy contexts + custodial `tron_send_transaction` (TRX + TRC-20) **Supported**; fee sponsorship **Coming soon** | | Address derivation: Cosmos, Sei, Sui, Aptos, BTC variants, Doge, Stellar, TON, XRP | **Supported** | Address-only; signing via raw payload | | Transaction parsing & policy contexts: Bitcoin, Cosmos, Aptos, Sui, Sei, TON, XRP, Stellar, Doge, etc. | **Coming soon** | Network and policy-example pages are placeholders | | Hyperliquid, Stacks, Movement, IOTA, Tempo, Spark | **Coming soon** | No parser or address derivation yet | | Fiat on-ramp | **Coming soon** | Credential CRUD is a no-op compatibility layer | | Import / export wallets and private keys | **Partial** | Signer-side HPKE bundle path (`ExportWalletExecutor` etc.) wired end-to-end; Dashboard product flows still in progress | *** ## Client libraries | Item | Status | Notes | | :- | :- | :- | | TypeScript / React packages (`@0xkey-io/*`) | **Supported** | `@0xkey-io/react-wallet-kit`, `@0xkey-io/core`, `@0xkey-io/sdk-server`; see [SDK reference](/sdks/introduction) | | Go server SDK (`github.com/0xkey-io/sdk-go`) | **Supported** | Published on [pkg.go.dev](https://pkg.go.dev/github.com/0xkey-io/sdk-go) | | Swift SDK (iOS / macOS) | **Supported** | `0.1.0` via Swift Package Manager; see [Swift SDK](/sdks/swift) | | Kotlin SDK (Android) | **Supported** | `v0.1.1` via JitPack; see [Kotlin SDK](/sdks/kotlin) | | React Native | **Partial** | `@0xkey-io/react-native-wallet-kit` | | Flutter | **Coming soon** | | | Server-side (Ruby, Python, Rust) | **Coming soon** | | | CLI (`0xkey`) | **Partial** | Open-source [`0xkey-io/cli`](https://github.com/0xkey-io/cli); v0.1.0 via `go install` or source; Homebrew formula not published yet. See [Using the CLI](/sdks/cli) | *** ## Policies, webhooks, and observability | Topic | Status | Notes | | :- | :- | :- | | Policy CRUD, defaults, post-registration async deployment | **Supported** | | | Transaction parsing and fine-grained policy conditions | **Partial** | EVM + Solana + EIP-712 + Tron today; other chains **Coming soon** | | `get_policy_evaluations` (policy-evaluation history) | **Partial** | Coordinator writes evaluations best-effort after Policy returns a ruling; visible once a parser-backed activity has run | | Webhooks | **Partial** | Public API CRUD + delivery (ACTIVITY_UPDATES via outbox/Svix); JWKS at `GET /public/v1/discovery/webhooks/jwks` | | QuorumOS / remote attestation | **Supported** | Customer-facing `get_attestation` + boot/app proof queries; full pivot↔manifest verification via SDK `verifyBootProof` | | Public boot-proof / TVC / app-proof queries | **Partial** | Boot/app proofs **Supported**; TVC / `get_app_status` still N/A | *** ## Coming soon features (planned) The following capabilities are on the roadmap but not yet available in Phase 1: * **Company Wallets hardening** — Dashboard consensus UX, policy versioning, webhook replay hardening (the server path is already **Partial**) * **Non-EVM transaction parsing & policy** — Bitcoin, Cosmos, Aptos, Sui, Sei, TON, XRP, Stellar, Doge, plus Stacks / Movement / IOTA / Hyperliquid / Tempo / Spark * **On-chain broadcast pipeline** — real RPC for `eth_send_raw_transaction` (currently mock); broaden EVM high-level send maturity beyond today's Gas Station path * **Cookbook integrations** — Morpho, Aave, Jupiter, LiFi, 0x, Polymarket, Relay, Breeze, Yield XYZ, Base builder codes * **Fiat on-ramp** — third-party on-ramp credential flows and status tracking * **Wallet import / export end-to-end** — productized Dashboard / SDK flows on top of the existing HPKE primitives * **Social OAuth provider catalog** — broaden built-in `oauth2_authenticate` / social login coverage beyond Google + Apple (Facebook, Discord, X); OIDC Federation for customer-owned IdPs is already **Supported** * **Account abstraction** — EVM smart-account wallets beyond today's Gas Station / Solana fee-payer sponsorship * **Server-side SDKs** — Python, Ruby, Rust * **CLI tooling** — Homebrew tap publish + parity polish on top of the shipped [`0xkey-io/cli`](https://github.com/0xkey-io/cli) MVP * **Verifiable Cloud** — external TEE attestation product SKU / packaging (API surfaces for attestation + boot/app proofs are already Supported) * **Balance / TVC queries** — `get_balances`, `get_app_status` still absent from `public_api.proto` # Get activity Source: https://docs.0xkey.io/api-reference/activities/get-activity /scripts/openapi-gen/openapi.json post /public/v1/query/get_activity Get details about an activity. # Get policy evaluations Source: https://docs.0xkey.io/api-reference/activities/get-policy-evaluations /scripts/openapi-gen/openapi.json post /public/v1/query/get_policy_evaluations Get the policy evaluations for an activity. # List activities Source: https://docs.0xkey.io/api-reference/activities/list-activities /scripts/openapi-gen/openapi.json post /public/v1/query/list_activities List all activities within an organization. # Create API keys Source: https://docs.0xkey.io/api-reference/api-keys/create-api-keys /scripts/openapi-gen/openapi.json post /public/v1/submit/create_api_keys Add API keys to an existing user. # Delete API keys Source: https://docs.0xkey.io/api-reference/api-keys/delete-api-keys /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_api_keys Remove api keys from a user. # Get API key Source: https://docs.0xkey.io/api-reference/api-keys/get-api-key /scripts/openapi-gen/openapi.json post /public/v1/query/get_api_key Get details about an API key. # Get API keys Source: https://docs.0xkey.io/api-reference/api-keys/get-api-keys /scripts/openapi-gen/openapi.json post /public/v1/query/get_api_keys Get details about API keys for a user. # List App Proofs for an activity Source: https://docs.0xkey.io/api-reference/app-proof/list-app-proofs-for-an-activity /scripts/openapi-gen/openapi.json post /public/v1/query/list_app_proofs List the App Proofs for the given activity. # Attestation Source: https://docs.0xkey.io/api-reference/attestation/attestation /scripts/openapi-gen/openapi.json post /public/v1/query/get_attestation Get the raw AWS Nitro attestation document (COSE Sign1) for a live enclave app. Prefers a fresh NSM attestation from the enclave host; falls back to the latest stored boot proof. For full pivot↔quorum-manifest verification prefer get_latest_boot_proof + client-side verifyBootProof. # Create authenticators Source: https://docs.0xkey.io/api-reference/authenticators/create-authenticators /scripts/openapi-gen/openapi.json post /public/v1/submit/create_authenticators Create authenticators to authenticate requests to 0xkey. # Delete authenticators Source: https://docs.0xkey.io/api-reference/authenticators/delete-authenticators /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_authenticators Remove authenticators from a user. # Get authenticator Source: https://docs.0xkey.io/api-reference/authenticators/get-authenticator /scripts/openapi-gen/openapi.json post /public/v1/query/get_authenticator Get details about an authenticator. # Get authenticators Source: https://docs.0xkey.io/api-reference/authenticators/get-authenticators /scripts/openapi-gen/openapi.json post /public/v1/query/get_authenticators Get details about authenticators for a user. # Activate Billing Tier Source: https://docs.0xkey.io/api-reference/billing/activate-billing-tier /scripts/openapi-gen/openapi.json post /public/v1/submit/activate_billing_tier Activate a billing plan tier for the organization (product_id carries the plan SKU). # Delete Payment Method Source: https://docs.0xkey.io/api-reference/billing/delete-payment-method /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_payment_method Remove a payment method from the organization. # Set Payment Method Source: https://docs.0xkey.io/api-reference/billing/set-payment-method /scripts/openapi-gen/openapi.json post /public/v1/submit/set_payment_method Attach a tokenized payment method to the organization (V2, PSP token only — no raw card data). # Get a specific boot proof Source: https://docs.0xkey.io/api-reference/boot-proof/get-a-specific-boot-proof /scripts/openapi-gen/openapi.json post /public/v1/query/get_boot_proof Get the boot proof for a given ephemeral key. # Get the latest boot proof for an app Source: https://docs.0xkey.io/api-reference/boot-proof/get-the-latest-boot-proof-for-an-app /scripts/openapi-gen/openapi.json post /public/v1/query/get_latest_boot_proof Get the latest boot proof for a given enclave app name. # Configure gas sponsorship spend cap. Source: https://docs.0xkey.io/api-reference/broadcasting/configure-gas-sponsorship-spend-cap /scripts/openapi-gen/openapi.json post /public/v1/submit/upsert_gas_usage_config Configure the per-organization gas sponsorship spend cap: rolling window, native-currency limit (wei), and whether it is enforced. Enforced fail-closed before each sponsored broadcast. > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # Delegate an EOA to the 0xkey gas-station (platform-paid). Source: https://docs.0xkey.io/api-reference/broadcasting/delegate-an-eoa-to-the-0xkey-gas-station-platform-paid /scripts/openapi-gen/openapi.json post /public/v1/submit/submit_delegation Broadcast a one-time EIP-7702 delegation for an EOA. The caller signs the authorization off-chain (SIGN_RAW_PAYLOAD_V2 + PAYLOAD_ENCODING_EIP7702_AUTHORIZATION); the platform paymaster pays the gas to broadcast the Type-4 transaction that installs the 0xkey gas-station delegate. Only the 0xkey delegate address is accepted (allowlist). > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # Get gas usage and limits. Source: https://docs.0xkey.io/api-reference/broadcasting/get-gas-usage-and-limits /scripts/openapi-gen/openapi.json post /public/v1/query/get_gas_usage Get gas usage and gas limits for either the parent organization or a sub-organization. > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # Get nonces for an address. Source: https://docs.0xkey.io/api-reference/broadcasting/get-nonces-for-an-address /scripts/openapi-gen/openapi.json post /public/v1/query/get_nonces Get nonce values for an address on a given network. Can fetch the standard on-chain nonce and/or the gas station nonce used for sponsored transactions. > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # List gas sponsorship usage records. Source: https://docs.0xkey.io/api-reference/broadcasting/list-gas-sponsorship-usage-records /scripts/openapi-gen/openapi.json post /public/v1/query/list_gas_sponsorship_usage List the most recent gas sponsorship usage entries for an organization (newest first), joined with each sponsored transaction's broadcast lifecycle (tx hash, status, block, actual native fee). Powers the Gas Station sponsorship records table. > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # Prepare an unsigned EVM transaction. Source: https://docs.0xkey.io/api-reference/broadcasting/prepare-an-unsigned-evm-transaction /scripts/openapi-gen/openapi.json post /public/v1/query/prepare_eth_transaction Build an unsigned EVM transaction server-side: resolve nonce, gas limit and EIP-1559 fees from the network and assemble the unsigned envelope. The client then stamps the returned unsigned transaction (SIGN_TRANSACTION_V2) — no client-side RPC or nonce management required. > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # Prepare an unsigned Solana transaction. Source: https://docs.0xkey.io/api-reference/broadcasting/prepare-an-unsigned-solana-transaction /scripts/openapi-gen/openapi.json post /public/v1/query/prepare_sol_transaction Build an unsigned Solana transaction server-side: fetch a recent blockhash and assemble an unsigned System Transfer message. The client then stamps the returned unsigned transaction (SIGN_TRANSACTION_V2) and broadcasts via SolSendRawTransaction — no client-side RPC or blockhash management required. > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # Submit a transaction intent for broadcasting. Source: https://docs.0xkey.io/api-reference/broadcasting/submit-a-transaction-intent-for-broadcasting /scripts/openapi-gen/openapi.json post /public/v1/submit/eth_send_transaction Submit a transaction intent describing a transaction you would like to broadcast. > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # Submit a transaction intent for broadcasting. Source: https://docs.0xkey.io/api-reference/broadcasting/submit-a-transaction-intent-for-broadcasting-1 /scripts/openapi-gen/openapi.json post /public/v1/submit/sol_send_transaction Submit a transaction intent describing a transaction you would like to broadcast. > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # Submit a transaction intent for broadcasting. Source: https://docs.0xkey.io/api-reference/broadcasting/submit-a-transaction-intent-for-broadcasting-2 /scripts/openapi-gen/openapi.json post /public/v1/submit/tron_send_transaction Submit a native TRX transfer intent describing a transaction you would like to broadcast. > [!NOTE] > > **Status: Partial.** `sol_send_transaction` and `tron_send_transaction` are supported (no Tron fee sponsorship yet). `eth_send_transaction` and gas sponsorship (Gas Station) are partial: available for supported EVM chains only. `get_gas_usage` and `get_nonces` may return empty or zero-valued responses. See the [Roadmap](/0xkey/roadmap). # Approve activity Source: https://docs.0xkey.io/api-reference/consensus/approve-activity /scripts/openapi-gen/openapi.json post /public/v1/submit/approve_activity Approve an activity. # Reject activity Source: https://docs.0xkey.io/api-reference/consensus/reject-activity /scripts/openapi-gen/openapi.json post /public/v1/submit/reject_activity Reject an activity. # Remove organization feature Source: https://docs.0xkey.io/api-reference/features/remove-organization-feature /scripts/openapi-gen/openapi.json post /public/v1/submit/remove_organization_feature Remove an organization feature. This activity must be approved by the current root quorum. # Set organization feature Source: https://docs.0xkey.io/api-reference/features/set-organization-feature /scripts/openapi-gen/openapi.json post /public/v1/submit/set_organization_feature Set an organization feature. This activity must be approved by the current root quorum. # Create invitations Source: https://docs.0xkey.io/api-reference/invitations/create-invitations /scripts/openapi-gen/openapi.json post /public/v1/submit/create_invitations Create invitations to join an existing organization. # Delete invitation Source: https://docs.0xkey.io/api-reference/invitations/delete-invitation /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_invitation Delete an existing invitation. # Create MFA policy Source: https://docs.0xkey.io/api-reference/mfa-policies/create-mfa-policy /scripts/openapi-gen/openapi.json post /public/v1/submit/create_mfa_policy Create a new MFA policy for a user. # Delete MFA policy Source: https://docs.0xkey.io/api-reference/mfa-policies/delete-mfa-policy /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_mfa_policy Delete an MFA policy for a user. # Get MFA policies Source: https://docs.0xkey.io/api-reference/mfa-policies/get-mfa-policies /scripts/openapi-gen/openapi.json post /public/v1/query/get_mfa_policies Get all MFA policies for a user. # Get MFA policy Source: https://docs.0xkey.io/api-reference/mfa-policies/get-mfa-policy /scripts/openapi-gen/openapi.json post /public/v1/query/get_mfa_policy Get a single MFA policy for a user. # Get MFA status Source: https://docs.0xkey.io/api-reference/mfa-policies/get-mfa-status /scripts/openapi-gen/openapi.json post /public/v1/query/get_mfa_status Get the MFA status of an activity for one user or all voting users. # Update MFA policy Source: https://docs.0xkey.io/api-reference/mfa-policies/update-mfa-policy /scripts/openapi-gen/openapi.json post /public/v1/submit/update_mfa_policy Update an MFA policy for a user. # Create OIDC provider Source: https://docs.0xkey.io/api-reference/oidc-federation/create-oidc-provider /scripts/openapi-gen/openapi.json post /public/v1/submit/create_oidc_provider Register a customer OIDC Identity Provider as trusted for this (parent) organization's OAUTH_LOGIN / CreateOauthProviders. Only root-quorum admins may perform this. # Delete OIDC provider Source: https://docs.0xkey.io/api-reference/oidc-federation/delete-oidc-provider /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_oidc_provider Remove one or more registered OIDC Identity Providers. # Get OIDC providers Source: https://docs.0xkey.io/api-reference/oidc-federation/get-oidc-providers /scripts/openapi-gen/openapi.json post /public/v1/query/get_oidc_providers List the OIDC Identity Providers registered as trusted for this organization. # Update OIDC provider Source: https://docs.0xkey.io/api-reference/oidc-federation/update-oidc-provider /scripts/openapi-gen/openapi.json post /public/v1/submit/update_oidc_provider Update a registered OIDC Identity Provider's name, audiences, or enabled state. # Create a Fiat On Ramp Credential Source: https://docs.0xkey.io/api-reference/on-ramp/create-a-fiat-on-ramp-credential /scripts/openapi-gen/openapi.json post /public/v1/submit/create_fiat_on_ramp_credential Create a fiat on ramp provider credential > [!NOTE] > > **Status: Coming soon.** Credential operations only notarize the request; no fiat on-ramp provider is connected yet. Status and list queries return empty responses. See the [Roadmap](/0xkey/roadmap). # Delete a Fiat On Ramp Credential Source: https://docs.0xkey.io/api-reference/on-ramp/delete-a-fiat-on-ramp-credential /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_fiat_on_ramp_credential Delete a fiat on ramp provider credential > [!NOTE] > > **Status: Coming soon.** Credential operations only notarize the request; no fiat on-ramp provider is connected yet. Status and list queries return empty responses. See the [Roadmap](/0xkey/roadmap). # Get On Ramp transaction status Source: https://docs.0xkey.io/api-reference/on-ramp/get-on-ramp-transaction-status /scripts/openapi-gen/openapi.json post /public/v1/query/get_onramp_transaction_status Get the status of an on ramp transaction. > [!NOTE] > > **Status: Coming soon.** Credential operations only notarize the request; no fiat on-ramp provider is connected yet. Status and list queries return empty responses. See the [Roadmap](/0xkey/roadmap). # Init fiat on ramp Source: https://docs.0xkey.io/api-reference/on-ramp/init-fiat-on-ramp /scripts/openapi-gen/openapi.json post /public/v1/submit/init_fiat_on_ramp Initiate a fiat on ramp flow. > [!NOTE] > > **Status: Coming soon.** Credential operations only notarize the request; no fiat on-ramp provider is connected yet. Status and list queries return empty responses. See the [Roadmap](/0xkey/roadmap). # List Fiat On Ramp Credentials Source: https://docs.0xkey.io/api-reference/on-ramp/list-fiat-on-ramp-credentials /scripts/openapi-gen/openapi.json post /public/v1/query/list_fiat_on_ramp_credentials List all fiat on ramp provider credentials within an organization. > [!NOTE] > > **Status: Coming soon.** Credential operations only notarize the request; no fiat on-ramp provider is connected yet. Status and list queries return empty responses. See the [Roadmap](/0xkey/roadmap). # Update a Fiat On Ramp Credential Source: https://docs.0xkey.io/api-reference/on-ramp/update-a-fiat-on-ramp-credential /scripts/openapi-gen/openapi.json post /public/v1/submit/update_fiat_on_ramp_credential Update a fiat on ramp provider credential > [!NOTE] > > **Status: Coming soon.** Credential operations only notarize the request; no fiat on-ramp provider is connected yet. Status and list queries return empty responses. See the [Roadmap](/0xkey/roadmap). # Create sub-organization Source: https://docs.0xkey.io/api-reference/organizations/create-sub-organization /scripts/openapi-gen/openapi.json post /public/v1/submit/create_sub_organization Create a new sub-organization. # Delete sub-organization Source: https://docs.0xkey.io/api-reference/organizations/delete-sub-organization /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_sub_organization Delete a sub-organization. # Get configs Source: https://docs.0xkey.io/api-reference/organizations/get-configs /scripts/openapi-gen/openapi.json post /public/v1/query/get_organization_configs Get quorum settings and features for an organization. # Get sub-organizations Source: https://docs.0xkey.io/api-reference/organizations/get-sub-organizations /scripts/openapi-gen/openapi.json post /public/v1/query/list_suborgs Get all suborg IDs associated given a parent org ID and an optional filter. # Get verified sub-organizations Source: https://docs.0xkey.io/api-reference/organizations/get-verified-sub-organizations /scripts/openapi-gen/openapi.json post /public/v1/query/list_verified_suborgs Get all email or phone verified suborg IDs associated given a parent org ID. # Update organization name Source: https://docs.0xkey.io/api-reference/organizations/update-organization-name /scripts/openapi-gen/openapi.json post /public/v1/submit/update_organization_name Update the name of an organization. # Update root quorum Source: https://docs.0xkey.io/api-reference/organizations/update-root-quorum /scripts/openapi-gen/openapi.json post /public/v1/submit/update_root_quorum Set the threshold and members of the root quorum. This activity must be approved by the current root quorum. # API reference Source: https://docs.0xkey.io/api-reference/overview Browse 0xkey API activities and queries by tag. > [!NOTE] > > **Phase 1 status.** This reference is generated from the OpenAPI spec and lists every endpoint the public API exposes. Some endpoints are wired but return stubbed responses or have not been connected to downstream infrastructure yet: > > * **Broadcast** — `sol_send_transaction` (self-paid and fee-sponsored) is live for custodial Solana; EVM `eth_send_raw_transaction` / high-level send maturity varies — see the [Roadmap](/0xkey/roadmap). > * **Stubbed / empty queries** — `get_send_transaction_status`, `get_on_ramp_transaction_status`, `get_gas_usage`, `get_nonces`, `list_fiat_on_ramp_credentials` may return empty / zero-valued responses. Boot/app proofs and `get_attestation` are **Supported** when enclaves are booted and `qos_host_control` is configured. > * **Not in current proto** — `get_balances` and `get_tvc_app_status` have no corresponding RPC in the running services (their doc paths redirect to the [Roadmap](/0xkey/roadmap)). > * **Webhooks** — webhook endpoint CRUD and listing are wired. Current subscription support is limited to `ACTIVITY_UPDATES`; update supports URL/name/active status but not subscription changes. > * **Notarize-only** — `create_oauth_providers` returns an empty `provider_ids` list; fiat on-ramp CRUD activities only notarize, no real on-ramp is wired. > > See the [Roadmap](/0xkey/roadmap) for the authoritative status matrix. # Create policies Source: https://docs.0xkey.io/api-reference/policies/create-policies /scripts/openapi-gen/openapi.json post /public/v1/submit/create_policies Create new policies. # Create policy Source: https://docs.0xkey.io/api-reference/policies/create-policy /scripts/openapi-gen/openapi.json post /public/v1/submit/create_policy Create a new policy. # Create smart contract interface Source: https://docs.0xkey.io/api-reference/policies/create-smart-contract-interface /scripts/openapi-gen/openapi.json post /public/v1/submit/create_smart_contract_interface Create an ABI/IDL in JSON. # Delete policies Source: https://docs.0xkey.io/api-reference/policies/delete-policies /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_policies Delete existing policies. # Delete policy Source: https://docs.0xkey.io/api-reference/policies/delete-policy /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_policy Delete an existing policy. # Delete smart contract interface Source: https://docs.0xkey.io/api-reference/policies/delete-smart-contract-interface /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_smart_contract_interface Delete a smart contract interface. # Get policy Source: https://docs.0xkey.io/api-reference/policies/get-policy /scripts/openapi-gen/openapi.json post /public/v1/query/get_policy Get details about a policy. # Get smart contract interface Source: https://docs.0xkey.io/api-reference/policies/get-smart-contract-interface /scripts/openapi-gen/openapi.json post /public/v1/query/get_smart_contract_interface Get details about a smart contract interface. # List policies Source: https://docs.0xkey.io/api-reference/policies/list-policies /scripts/openapi-gen/openapi.json post /public/v1/query/list_policies List all policies within an organization. # List smart contract interfaces Source: https://docs.0xkey.io/api-reference/policies/list-smart-contract-interfaces /scripts/openapi-gen/openapi.json post /public/v1/query/list_smart_contract_interfaces List all smart contract interfaces within an organization. # Simulate policy chain Source: https://docs.0xkey.io/api-reference/policies/simulate-policy-chain /scripts/openapi-gen/openapi.json post /public/v1/query/simulate_policy_chain Simulate how the organization's policy chain would evaluate a hypothetical activity. Read-only dry-run executed by the enclave Policy Engine: no activity is created, no Ruling is signed, and consensus scenarios are evaluated with declared approvers instead of real signatures. # Update policy Source: https://docs.0xkey.io/api-reference/policies/update-policy /scripts/openapi-gen/openapi.json post /public/v1/submit/update_policy Update an existing policy. # Create private key tag Source: https://docs.0xkey.io/api-reference/private-key-tags/create-private-key-tag /scripts/openapi-gen/openapi.json post /public/v1/submit/create_private_key_tag Create a private key tag and add it to private keys. # Delete private key tags Source: https://docs.0xkey.io/api-reference/private-key-tags/delete-private-key-tags /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_private_key_tags Delete private key tags within an organization. # List private key tags Source: https://docs.0xkey.io/api-reference/private-key-tags/list-private-key-tags /scripts/openapi-gen/openapi.json post /public/v1/query/list_private_key_tags List all private key tags within an organization. # Update private key tag Source: https://docs.0xkey.io/api-reference/private-key-tags/update-private-key-tag /scripts/openapi-gen/openapi.json post /public/v1/submit/update_private_key_tag Update human-readable name or associated private keys. Note that this activity is atomic: all of the updates will succeed at once, or all of them will fail. # Create private keys Source: https://docs.0xkey.io/api-reference/private-keys/create-private-keys /scripts/openapi-gen/openapi.json post /public/v1/submit/create_private_keys Create new private keys. # Delete private keys Source: https://docs.0xkey.io/api-reference/private-keys/delete-private-keys /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_private_keys Delete private keys for an organization. # Export private key Source: https://docs.0xkey.io/api-reference/private-keys/export-private-key /scripts/openapi-gen/openapi.json post /public/v1/submit/export_private_key Export a private key. # Get private key Source: https://docs.0xkey.io/api-reference/private-keys/get-private-key /scripts/openapi-gen/openapi.json post /public/v1/query/get_private_key Get details about a private key. # Import private key Source: https://docs.0xkey.io/api-reference/private-keys/import-private-key /scripts/openapi-gen/openapi.json post /public/v1/submit/import_private_key Import a private key. # Init import private key Source: https://docs.0xkey.io/api-reference/private-keys/init-import-private-key /scripts/openapi-gen/openapi.json post /public/v1/submit/init_import_private_key Initialize a new private key import. # List private keys Source: https://docs.0xkey.io/api-reference/private-keys/list-private-keys /scripts/openapi-gen/openapi.json post /public/v1/query/list_private_keys List all private keys within an organization. # Get OAuth 2.0 credential Source: https://docs.0xkey.io/api-reference/publicapiservice/get-oauth-20-credential /scripts/openapi-gen/openapi.json post /public/v1/query/get_oauth2_credential Get details about an OAuth 2.0 credential. # Get webhook JWKS Source: https://docs.0xkey.io/api-reference/queries/get-webhook-jwks GET https://api.0xkey.io/public/v1/discovery/webhooks/jwks Fetch 0xkey webhook signature verification keys. Fetch the public Ed25519 keys used to verify 0xkey webhook signatures. This endpoint is public and does not require authentication. Cache the JWKS response according to the `Cache-Control` header. Match each JWK `kid` to the webhook delivery's `X-0xkey-Signature-Key-Id` header. If a delivery uses an unknown `kid`, refetch JWKS once before rejecting it. Current `Cache-Control`: ```text theme={"theme":{"light":"github-light","dark":"github-dark"}} public, max-age=86400, s-maxage=86400, stale-if-error=604800 ``` ### Response **keys** `array` *required* Public webhook signature verification keys. **keys details** Navigate to header keys. kid string required Key identifier. Match this value against `X-0xkey-Signature-Key-Id`. Navigate to header keys. kty string required Key type. Current value: `OKP`. Navigate to header keys. crv string required Key curve. Current value: `Ed25519`. Navigate to header keys. alg string required JWK algorithm. Current value: `EdDSA`. Navigate to header keys. use string required Key use. Current value: `sig`. Navigate to header keys. x string required Base64url-encoded Ed25519 public key. Navigate to header keys. x_0xkey_signature_algorithm string required 0xkey signature algorithm metadata. Current value: `ed25519`. Navigate to header keys. x_0xkey_signature_version string required 0xkey signature contract version metadata. Current value: `v1`. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"github-dark"}} curl https://api.0xkey.io/public/v1/discovery/webhooks/jwks ``` ```json 200 theme={"theme":{"light":"github-light","dark":"github-dark"}} { "keys": [ { "kid": "", "kty": "OKP", "crv": "Ed25519", "alg": "EdDSA", "use": "sig", "x": "", "x_0xkey_signature_algorithm": "ed25519", "x_0xkey_signature_version": "v1" } ] } ``` # Get send transaction status Source: https://docs.0xkey.io/api-reference/send-transactions/get-send-transaction-status /scripts/openapi-gen/openapi.json post /public/v1/query/get_send_transaction_status Get the status of a send transaction request. > [!NOTE] > > **Status note.** `get_send_transaction_status` is coming soon and may return an empty or zero-valued response. See the [Roadmap](/0xkey/roadmap). # List send transactions. Source: https://docs.0xkey.io/api-reference/send-transactions/list-send-transactions /scripts/openapi-gen/openapi.json post /public/v1/query/list_send_transactions List the most recent send-transaction records for an organization (newest first), optionally filtered to a single CAIP-2 network. > [!NOTE] > > **Status note.** `get_send_transaction_status` is coming soon and may return an empty or zero-valued response. See the [Roadmap](/0xkey/roadmap). # Create session profile Source: https://docs.0xkey.io/api-reference/session-profiles/create-session-profile /scripts/openapi-gen/openapi.json post /public/v1/submit/create_session_profile Create a new session profile for an organization. # Get session profile Source: https://docs.0xkey.io/api-reference/session-profiles/get-session-profile /scripts/openapi-gen/openapi.json post /public/v1/query/get_session_profile Get one session profile for an organization. # Get session profiles Source: https://docs.0xkey.io/api-reference/session-profiles/get-session-profiles /scripts/openapi-gen/openapi.json post /public/v1/query/get_session_profiles Get all session profiles for an organization. # Create read only session Source: https://docs.0xkey.io/api-reference/sessions/create-read-only-session /scripts/openapi-gen/openapi.json post /public/v1/submit/create_read_only_session Create a read only session for a user (valid for 1 hour). # Create read write session Source: https://docs.0xkey.io/api-reference/sessions/create-read-write-session /scripts/openapi-gen/openapi.json post /public/v1/submit/create_read_write_session Create a read write session for a user. # Login with a stamp Source: https://docs.0xkey.io/api-reference/sessions/login-with-a-stamp /scripts/openapi-gen/openapi.json post /public/v1/submit/stamp_login Create a session for a user through stamping client side (API key, wallet client, or passkey client). # Login with Oauth Source: https://docs.0xkey.io/api-reference/sessions/login-with-oauth /scripts/openapi-gen/openapi.json post /public/v1/submit/oauth_login Create an Oauth session for a user. # Login with OTP Source: https://docs.0xkey.io/api-reference/sessions/login-with-otp /scripts/openapi-gen/openapi.json post /public/v1/submit/otp_login Create an OTP session for a user. # Who am I Source: https://docs.0xkey.io/api-reference/sessions/who-am-i /scripts/openapi-gen/openapi.json post /public/v1/query/whoami Get basic information about your current API or WebAuthN user and their organization. Affords sub-organization look ups via parent organization for WebAuthN or API key users. # Sign raw payload Source: https://docs.0xkey.io/api-reference/signing/sign-raw-payload /scripts/openapi-gen/openapi.json post /public/v1/submit/sign_raw_payload Sign a raw payload. # Sign raw payloads Source: https://docs.0xkey.io/api-reference/signing/sign-raw-payloads /scripts/openapi-gen/openapi.json post /public/v1/submit/sign_raw_payloads Sign multiple raw payloads with the same signing parameters. # Sign transaction Source: https://docs.0xkey.io/api-reference/signing/sign-transaction /scripts/openapi-gen/openapi.json post /public/v1/submit/sign_transaction Sign a transaction. # Create an OAuth 2.0 Credential Source: https://docs.0xkey.io/api-reference/user-auth/create-an-oauth-20-credential /scripts/openapi-gen/openapi.json post /public/v1/submit/create_oauth2_credential Enable authentication for end users with an OAuth 2.0 provider # Create Oauth providers Source: https://docs.0xkey.io/api-reference/user-auth/create-oauth-providers /scripts/openapi-gen/openapi.json post /public/v1/submit/create_oauth_providers Create Oauth providers for a specified user. # Delete an OAuth 2.0 Credential Source: https://docs.0xkey.io/api-reference/user-auth/delete-an-oauth-20-credential /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_oauth2_credential Disable authentication for end users with an OAuth 2.0 provider # Delete Oauth providers Source: https://docs.0xkey.io/api-reference/user-auth/delete-oauth-providers /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_oauth_providers Remove Oauth providers for a specified user. # Get Oauth providers Source: https://docs.0xkey.io/api-reference/user-auth/get-oauth-providers /scripts/openapi-gen/openapi.json post /public/v1/query/get_oauth_providers Get details about Oauth providers for a user. # Init OTP auth Source: https://docs.0xkey.io/api-reference/user-auth/init-otp-auth /scripts/openapi-gen/openapi.json post /public/v1/submit/init_otp_auth Initiate an OTP auth activity. # List OAuth 2.0 Credentials Source: https://docs.0xkey.io/api-reference/user-auth/list-oauth-20-credentials /scripts/openapi-gen/openapi.json post /public/v1/query/list_oauth2_credentials List all OAuth 2.0 credentials within an organization. # Oauth Source: https://docs.0xkey.io/api-reference/user-auth/oauth /scripts/openapi-gen/openapi.json post /public/v1/submit/oauth Authenticate a user with an OIDC token (Oauth). # OAuth 2.0 authentication Source: https://docs.0xkey.io/api-reference/user-auth/oauth-20-authentication /scripts/openapi-gen/openapi.json post /public/v1/submit/oauth2_authenticate Authenticate a user with an OAuth 2.0 provider and receive an OIDC token to use with the LoginWithOAuth or CreateSubOrganization activities # OTP auth Source: https://docs.0xkey.io/api-reference/user-auth/otp-auth /scripts/openapi-gen/openapi.json post /public/v1/submit/otp_auth Authenticate a user with an OTP code sent via email or SMS. # Perform email auth Source: https://docs.0xkey.io/api-reference/user-auth/perform-email-auth /scripts/openapi-gen/openapi.json post /public/v1/submit/email_auth Authenticate a user via email. # Update an OAuth 2.0 Credential Source: https://docs.0xkey.io/api-reference/user-auth/update-an-oauth-20-credential /scripts/openapi-gen/openapi.json post /public/v1/submit/update_oauth2_credential Update an OAuth 2.0 provider credential # Init email recovery Source: https://docs.0xkey.io/api-reference/user-recovery/init-email-recovery /scripts/openapi-gen/openapi.json post /public/v1/submit/init_user_email_recovery Initialize a new email recovery. # Recover a user Source: https://docs.0xkey.io/api-reference/user-recovery/recover-a-user /scripts/openapi-gen/openapi.json post /public/v1/submit/recover_user Complete the process of recovering a user by adding an authenticator. # Create user tag Source: https://docs.0xkey.io/api-reference/user-tags/create-user-tag /scripts/openapi-gen/openapi.json post /public/v1/submit/create_user_tag Create a user tag and add it to users. # Delete user tags Source: https://docs.0xkey.io/api-reference/user-tags/delete-user-tags /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_user_tags Delete user tags within an organization. # List user tags Source: https://docs.0xkey.io/api-reference/user-tags/list-user-tags /scripts/openapi-gen/openapi.json post /public/v1/query/list_user_tags List all user tags within an organization. # Update user tag Source: https://docs.0xkey.io/api-reference/user-tags/update-user-tag /scripts/openapi-gen/openapi.json post /public/v1/submit/update_user_tag Update human-readable name or associated users. Note that this activity is atomic: all of the updates will succeed at once, or all of them will fail. # Init generic OTP Source: https://docs.0xkey.io/api-reference/user-verification/init-generic-otp /scripts/openapi-gen/openapi.json post /public/v1/submit/init_otp Initiate a generic OTP activity. # Verify generic OTP Source: https://docs.0xkey.io/api-reference/user-verification/verify-generic-otp /scripts/openapi-gen/openapi.json post /public/v1/submit/verify_otp Verify a generic OTP (legacy, plaintext otpCode). # Create users Source: https://docs.0xkey.io/api-reference/users/create-users /scripts/openapi-gen/openapi.json post /public/v1/submit/create_users Create users in an existing organization. # Delete users Source: https://docs.0xkey.io/api-reference/users/delete-users /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_users Delete users within an organization. # Get user Source: https://docs.0xkey.io/api-reference/users/get-user /scripts/openapi-gen/openapi.json post /public/v1/query/get_user Get details about a user. # List users Source: https://docs.0xkey.io/api-reference/users/list-users /scripts/openapi-gen/openapi.json post /public/v1/query/list_users List all users within an organization. # Update user Source: https://docs.0xkey.io/api-reference/users/update-user /scripts/openapi-gen/openapi.json post /public/v1/submit/update_user Update a user in an existing organization. # Update user's email Source: https://docs.0xkey.io/api-reference/users/update-users-email /scripts/openapi-gen/openapi.json post /public/v1/submit/update_user_email Update a user's email in an existing organization. # Update user's name Source: https://docs.0xkey.io/api-reference/users/update-users-name /scripts/openapi-gen/openapi.json post /public/v1/submit/update_user_name Update a user's name in an existing organization. # Update user's phone number Source: https://docs.0xkey.io/api-reference/users/update-users-phone-number /scripts/openapi-gen/openapi.json post /public/v1/submit/update_user_phone_number Update a user's phone number in an existing organization. # Create wallet Source: https://docs.0xkey.io/api-reference/wallets/create-wallet /scripts/openapi-gen/openapi.json post /public/v1/submit/create_wallet Create a wallet and derive addresses. # Create wallet accounts Source: https://docs.0xkey.io/api-reference/wallets/create-wallet-accounts /scripts/openapi-gen/openapi.json post /public/v1/submit/create_wallet_accounts Derive additional addresses using an existing wallet. # Delete wallet accounts Source: https://docs.0xkey.io/api-reference/wallets/delete-wallet-accounts /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_wallet_accounts Delete wallet accounts for an organization. # Delete wallets Source: https://docs.0xkey.io/api-reference/wallets/delete-wallets /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_wallets Delete wallets for an organization. # Export wallet Source: https://docs.0xkey.io/api-reference/wallets/export-wallet /scripts/openapi-gen/openapi.json post /public/v1/submit/export_wallet Export a wallet. # Export wallet account Source: https://docs.0xkey.io/api-reference/wallets/export-wallet-account /scripts/openapi-gen/openapi.json post /public/v1/submit/export_wallet_account Export a wallet account. # Get wallet Source: https://docs.0xkey.io/api-reference/wallets/get-wallet /scripts/openapi-gen/openapi.json post /public/v1/query/get_wallet Get details about a wallet. # Get wallet account Source: https://docs.0xkey.io/api-reference/wallets/get-wallet-account /scripts/openapi-gen/openapi.json post /public/v1/query/get_wallet_account Get a single wallet account. # Import wallet Source: https://docs.0xkey.io/api-reference/wallets/import-wallet /scripts/openapi-gen/openapi.json post /public/v1/submit/import_wallet Import a wallet. # Init import wallet Source: https://docs.0xkey.io/api-reference/wallets/init-import-wallet /scripts/openapi-gen/openapi.json post /public/v1/submit/init_import_wallet Initialize a new wallet import. # List wallets Source: https://docs.0xkey.io/api-reference/wallets/list-wallets /scripts/openapi-gen/openapi.json post /public/v1/query/list_wallets List all wallets within an organization. # List wallets accounts Source: https://docs.0xkey.io/api-reference/wallets/list-wallets-accounts /scripts/openapi-gen/openapi.json post /public/v1/query/list_wallet_accounts List all accounts within a wallet. # Update wallet Source: https://docs.0xkey.io/api-reference/wallets/update-wallet /scripts/openapi-gen/openapi.json post /public/v1/submit/update_wallet Update a wallet for an organization. # Create Webhook Endpoint Source: https://docs.0xkey.io/api-reference/webhooks/create-webhook-endpoint /scripts/openapi-gen/openapi.json post /public/v1/submit/create_webhook_endpoint Create a new webhook endpoint for the organization. > [!NOTE] > > **Status: Partial.** Endpoint create, update, delete, and list are available for `ACTIVITY_UPDATES` events. Update supports URL, name, and active status, not subscription changes. See the [Roadmap](/0xkey/roadmap). # Delete Webhook Endpoint Source: https://docs.0xkey.io/api-reference/webhooks/delete-webhook-endpoint /scripts/openapi-gen/openapi.json post /public/v1/submit/delete_webhook_endpoint Delete a webhook endpoint. > [!NOTE] > > **Status: Partial.** Endpoint create, update, delete, and list are available for `ACTIVITY_UPDATES` events. Update supports URL, name, and active status, not subscription changes. See the [Roadmap](/0xkey/roadmap). # List Webhook Endpoints Source: https://docs.0xkey.io/api-reference/webhooks/list-webhook-endpoints /scripts/openapi-gen/openapi.json post /public/v1/query/list_webhook_endpoints List all webhook endpoints for the organization. > [!NOTE] > > **Status: Partial.** Endpoint create, update, delete, and list are available for `ACTIVITY_UPDATES` events. Update supports URL, name, and active status, not subscription changes. See the [Roadmap](/0xkey/roadmap). # Update Webhook Endpoint Source: https://docs.0xkey.io/api-reference/webhooks/update-webhook-endpoint /scripts/openapi-gen/openapi.json post /public/v1/submit/update_webhook_endpoint Update an existing webhook endpoint (url, name, active status). > [!NOTE] > > **Status: Partial.** Endpoint create, update, delete, and list are available for `ACTIVITY_UPDATES` events. Update supports URL, name, and active status, not subscription changes. See the [Roadmap](/0xkey/roadmap). # Backend authentication Source: https://docs.0xkey.io/authentication/backend-setup Guide for integrating 0xkey authentication into your backend, covering session JWT creation, validation, and enforcing user access controls. ## Introduction This guide shows you how to use 0xkey as the foundation for your own backend authentication system. You’ll learn how to issue, send, and validate session JWTs, and enforce access controls in your backend. ## Why use backend authentication? There are several benefits to enforcing authenticated requests to your backend: 1. **User data**: Store and retrieve user data associated with 0xkey sub-organizations 2. **Metrics and monitoring**: Add custom validations, rate limiting, and logging 3. **Co-signing capabilities**: Enable 2/2 signing patterns where your application is a co-signer ## JWT authentication flow JSON Web Tokens (JWTs) provide a secure, stateless way to authenticate requests between your frontend and backend. Here's how to implement a JWT-based flow with 0xkey: ### Architecture overview ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant User participant Frontend participant Backend participant 0xkey %% Login/Signup Flow User->>Frontend: Login/Signup Action Frontend->>Backend: Send auth info Backend->>Backend: Create and sign 0xkey request Backend->>0xkey: Send signed request 0xkey->>Backend: Return session JWT Backend->>Frontend: Return session JWT Frontend->>Frontend: Store session JWT %% Subsequent Request Flow User->>Frontend: Action requiring Backend Authentication Frontend->>Backend: Send request with JWT Backend->>Backend: Validate JWT Backend->>Backend: Check user permissions Backend->>Frontend: Return response Frontend->>User: Update UI ``` ### High-level flow The overall pattern is similar, but may differ slightly depending on the auth method. Generally: * The user authenticates (via passkey, OTP, etc.) * A session is created with 0xkey, returning a session JWT * That session JWT is used to make authenticated requests to your backend ## Getting the session JWT 0xkey supports multiple authentication methods, each of which results in a session JWT that proves the user's identity. This section covers the two most common flows: passkey authentication and OTP (One-Time Passcode) authentication. It explains how each method ultimately produces a session JWT that your frontend can use to make authenticated requests to your backend. ### Passkey authentication 0xkey supports passkey authentication, which allows users to log in using their device’s biometric system or a hardware security key. In this guide, we’ll separate login and signup flows, since most apps handle them independently and the implementation details differ slightly. #### Signup flow ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant User participant Frontend participant Backend participant 0xkey User->>Frontend: Begin signup (create passkey) Frontend->>Frontend: Create passkey and ephemeral API key Frontend->>Backend: Send passkey + ephemeral API public key Backend->>0xkey: Create sub-org with passkey + API public key 0xkey->>Backend: Return subOrgId Backend->>Frontend: Return subOrgId Frontend->>Frontend: Create ZeroXKeyClient with ephemeral API key Frontend->>0xkey: Call stampLogin() using ephemeral API key 0xkey->>Frontend: Return session JWT User->>Frontend: Action requiring Backend Authentication Frontend->>Backend: Send request along with session JWT Backend->>Backend: Validate JWT Backend->>Backend: Check user permissions Backend->>Frontend: Return response Frontend->>User: Update UI ``` **1. Start the Signup Process** The user begins the signup flow by tapping a button like “Sign up with Passkey” on the frontend. **2. Generate Passkey and Temporary API Key** The frontend creates a passkey using WebAuthn, prompting the user for biometric or hardware authentication. At the same time, it silently generates a temporary API key in the background, which is used to stamp requests during the signup process. **Note:** We use a temporary API key during signup to avoid prompting the user twice for a passkey tap. Without it, we’d need to use the passkey to stamp the `stampLogin()` request later in the flow, which would trigger a second prompt right after creating the passkey. Using the API key instead allows us to create the session in the background with just a single tap. **3. Create a 0xkey Sub-organization** The frontend sends the passkey and API public key to the backend. The backend then uses the 0xkey API to create a new sub-organization and register both credentials as authenticators. **4. Create a Session** The frontend initializes a `ZeroXKeyClient` using the temporary API key and calls `stampLogin()`. 0xkey returns a session JWT representing the authenticated user session. **5. You're Now Authenticated** Your frontend can now make requests to your backend and attach the session JWT. The backend will validate the token on each request and verify that the user has permission to perform the requested action. #### Login flow ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant User participant Frontend participant Backend participant 0xkey User->>Frontend: Begin login Frontend->>Frontend: Call stampLogin() with passkeyStamper Frontend->>Frontend: Trigger WebAuthn prompt Frontend->>User: Request biometric/hardware authentication User->>Frontend: Tap to approve login Frontend->>0xkey: Send signed request to 0xkey 0xkey->>Frontend: Return session JWT User->>Frontend: Action requiring Backend Authentication Frontend->>Backend: Send request along with session JWT Backend->>Backend: Validate JWT Backend->>Backend: Check user permissions Backend->>Frontend: Return response Frontend->>User: Update UI ``` **1. Start the Login Process** The user begins the login flow by tapping a button like “Log in with Passkey” on the frontend. **2. Use Passkey to Authenticate** The frontend initializes a `ZeroXKeyClient` with a `passkeyStamper` and calls `stampLogin()`. This triggers a WebAuthn prompt, prompting the user to approve the login request using their passkey. **3. Create a Session** Once the user approves the request, the signed login is sent to 0xkey. 0xkey then returns a session JWT representing the authenticated user session. **4. You're Now Authenticated** Your frontend can now make requests to your backend and attach the session JWT. The backend will validate the token on each request and verify that the user has permission to perform the requested action. ### OTP authentication 0xkey also supports SMS and email-based One-Time Passcode (OTP) authentication, allowing users to log in by entering a code sent to their email or phone number. We’ll cover OTP login and signup together, since the flows are similar and most apps handle them in a unified way. ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant User participant Frontend participant Backend participant 0xkey User->>Frontend: Begin login (enter email/phone) Frontend->>Backend: Request OTP Backend->>0xkey: Call initOtp() 0xkey->>Backend: Return otpId Backend->>Frontend: Return otpId Frontend->>User: Prompt for OTP code User->>Frontend: Enter OTP code Frontend->>Backend: Verify OTP Backend->>0xkey: Call verifyOtp() 0xkey->>Backend: Return verification token Backend->>Frontend: Return verification token Frontend->>Frontend: Create API key Frontend->>Backend: Send API public key + verification token Backend->>0xkey: Call getSubOrgIds() with contact info 0xkey->>Backend: Return existing subOrgId (if any) alt SubOrgId not found Backend->>0xkey: Create new sub-org with contact 0xkey->>Backend: Return new subOrgId end Backend->>0xkey: Call otpLogin() with subOrgId, public key, and token 0xkey->>Backend: Return session JWT Backend->>Frontend: Return session JWT User->>Frontend: Action requiring Backend Authentication Frontend->>Backend: Send request along with session JWT Backend->>Backend: Validate JWT Backend->>Backend: Check user permissions Backend->>Frontend: Return response Frontend->>User: Update UI ``` **1. Start the Login Process** The user begins the login flow by entering their email or phone number on the frontend. **2. Request and Verify OTP** The frontend sends the contact info to your backend, which requests an OTP from 0xkey. Once the user receives and enters the code, your backend verifies it with 0xkey and receives a verification token. **3. Get or Create a 0xkey Sub-organization** The frontend generates an API key, then sends the API public key and verification token to the backend. The backend checks with 0xkey whether a sub-organization already exists for the contact. If not, it creates a new one. **4. Create a Session** The backend calls `otpLogin()` with the subOrgId, public key, and verification token. 0xkey returns a session JWT representing the authenticated user session, which the backend then returns to the frontend. **5. You're Now Authenticated** Your frontend can now make requests to your backend and attach the session JWT. The backend will validate the token on each request and verify that the user has permission to perform the requested action. ## Sending the JWT from the frontend After a user completes 0xkey authentication and a session is created (via passkey, OTP, or another supported method), your backend returns a session JWT to the frontend. This token proves the user’s identity and is the frontend’s responsibility to store and include in all future authenticated requests to your backend. The session JWT should be attached to each request using the `Authorization` header. This allows your backend to identify the authenticated user and enforce any necessary access control based on the `user_id` or `organization_id`. **Note:** These requests are sent to your own backend endpoints and may contain any application-specific payload, such as a form submission, a database mutation, or a business action. They are not necessarily related to 0xkey. Here’s an example of how the frontend might send the JWT: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} const response = await fetch("/api/your-backend-endpoint", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${sessionJwt}`, }, body: JSON.stringify({ /* your request payload */ }), }); ``` This adds the following header to your HTTP request: ```http theme={"theme":{"light":"github-light","dark":"github-dark"}} Authorization: Bearer ``` ## Validating the JWT in your backend After a user completes 0xkey authentication and a session is created (via passkey, OTP, or another supported method), your backend returns a session JWT to the frontend. This token proves the user's identity and is the frontend’s responsibility to store and include in all future authenticated requests. ### What does the session JWT contain? Before diving into how to verify the session JWT, it’s helpful to understand what’s actually inside it. The JWT includes information that identifies the authenticated user and the organization they belong to, as well as metadata like expiration time and session type. Here’s an example of a decoded session JWT: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} { "exp": , "public_key": "", "session_type": "SESSION_TYPE_READ_WRITE", "user_id": "", "organization_id": "" } ``` ### Validating the JWT To validate the session JWT: **1. Verify the Signature** Use the helper function `verifySessionJwtSignature` from [`@0xkey-io/crypto`](https://github.com/0xkey-io/sdk-js/blob/e10342cd111fbb9b1d168ff386b5dc263e3a5ce3/packages/crypto/src/index.ts#L409-L466) to confirm that the JWT was signed by 0xkey and hasn’t been modified. ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} import { verifySessionJwtSignature } from "@0xkey-io/crypto"; const isValid = await verifySessionJwtSignature(sessionJwt); if (!isValid) { throw new Error("Invalid JWT: failed signature verification"); } ``` **2. Decode the Session JWT** Before verifying expiration or enforcing access controls, you’ll need to decode the JWT payload to access fields like `user_id`, `organization_id`, and `exp`. Here’s an example helper you can define to decode and extract the session fields from the payload: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} export function decodeSessionJwt(token: string): { sessionType: string; userId: string; organizationId: string; expiry: number; publicKey: string; } { const [, payload] = token.split("."); if (!payload) { throw new Error("Invalid JWT: Missing payload"); } const decoded = JSON.parse(atob(payload)); const { exp, public_key: publicKey, session_type: sessionType, user_id: userId, organization_id: organizationId, } = decoded; if (!exp || !publicKey || !sessionType || !userId || !organizationId) { throw new Error("JWT payload missing required fields"); } return { sessionType, userId, organizationId, expiry: exp, publicKey, }; } ``` **3. Check the Expiration** Ensure that the token has not expired by validating the exp (expiration) claim. ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} if (decodedJwt.exp * 1000 < Date.now()) { throw new Error("Token has expired"); } ``` **4. Extract and Enforce Access Controls** Once the token is verified and decoded, use the `userId` and `organizationId` to enforce access control in your application. This step is application-specific and depends on how your backend maps users to organizations. For example, you might: * Look up the user in your database by `userId` * Confirm that the request targets the correct `organizationId` * Reject the request if the user is not linked to that organization This ensures that even with a valid JWT, a user can only access resources associated with their own 0xkey sub-organization. ## Advanced topics > [card] [Co-signing Transactions](/company-wallets/hybrid-cosign) > > Learn about advanced patterns like multi-signature setups requiring approvals > from both the user and the backend. # Credentials Source: https://docs.0xkey.io/authentication/credentials An overview of credentials and how they're used with various authentication methods ## Introduction After authenticating using frequently-used methods like [SMS OTP](/authentication/sms), [Email Authentication](/authentication/email), or [OAuth](/authentication/social-logins) (e.g., Google), users will make requests to 0xkey with a resulting API key. Each API key includes a `Credential` field specifying its type and public key. This Credential type can be used to identify how the API key was issued and which specific authentication method was used. [Passkeys](/authentication/passkeys/introduction), known as Authenticators within the context of 0xkey, also have the same `Credential` field and are equally distinguished by the credential type. ## Obtaining an API key's credential type and public key To obtain an API key's credential type and public key you can use the [GetAPIKey](/api-reference/queries/get-api-key) query. The API Key fields will be returned from this call and the credential `type` and `public_key` fields will be in the response. This will return an object that looks like: ```sh theme={"theme":{"light":"github-light","dark":"github-dark"}} { "apiKey": { "apiKeyId": "", "apiKeyName": "", "createdAt": { "nanos": "0", "seconds": "1752105687" }, "credential": { "publicKey": "", "type": "CREDENTIAL_TYPE_API_KEY_P256" }, "updatedAt": { "nanos": "0", "seconds": "1752105687" } } } ``` ## Credential types The table below describes all of the different credential types and what authentication methods correspond to that credential type | Type | Authentication Method(s) | | - | - | | **CREDENTIAL_TYPE_WEBAUTHN_AUTHENTICATOR** | [Passkey/Authenticator Authentication](/authentication/passkeys/introduction) | | **CREDENTIAL_TYPE_API_KEY_P256** | [CreateAPIKeys](/api-reference/activities/create-api-keys) - curveType API_KEY_CURVE_P256 | | **CREDENTIAL_TYPE_RECOVER_USER_KEY_P256** | [Email Recovery](/authentication/email#recovery-flow) | | **CREDENTIAL_TYPE_API_KEY_SECP256K1** | Used for Ethereum and SECP256K1 chainS [Wallet Authentication](/embedded-wallets/code-examples/wallet-auth) | | **CREDENTIAL_TYPE_EMAIL_AUTH_KEY_P256** | [Credential Bundle based Email Authentication](/authentication/email#credential-bundle-method) | | **CREDENTIAL_TYPE_API_KEY_ED25519** | Solana and ED25519 chains [Wallet Authentication](/embedded-wallets/code-examples/wallet-auth) | | **CREDENTIAL_TYPE_OTP_AUTH_KEY_P256** | OTP based [Email](/authentication/email#otp-based-method) or [SMS](/authentication/sms) Authentication | | **CREDENTIAL_TYPE_READ_WRITE_SESSION_KEY_P256** | [CreateReadWriteSession](/api-reference/activities/create-read-write-session) | | **CREDENTIAL_TYPE_OAUTH_KEY_P256** | [Social Logins](/authentication/social-logins) | | **CREDENTIAL_TYPE_LOGIN** | [IndexedDB Authentication](https://github.com/0xkey-io/sdk-js/tree/main/packages/core#indexeddbclient); OTP, Passkey, or OAuth | # Email auth & recovery Source: https://docs.0xkey.io/authentication/email Email Authentication enables users to authenticate and recover their 0xkey accounts using email-based verification. There are two methods of email authentication: #### One-time password * Uses a 6-9 digit or bech32 alphanumeric one-time password sent via email * Simple, and familiar user experience **One-Time Password Sandbox Environment** To test OTP codes in our sandbox environment you can use the following: * `alphanumeric` must be set to `false` * `otpLength` must be set to `6` * Email: [user@example.com](mailto:user@example.com) * OTP Code: `000000` #### Credential bundle * Sends an encrypted API key credential directly via email * Alternative method for specific use cases * More secure, but requires copying the full credential to the client Both methods provide users with an expiring API key for authentication or account recovery. ## Core mechanism Email Authentication is built with expiring API keys as the foundation. The two delivery mechanisms are: ### OTP-based method The authentication process happens in two steps: **Step 1** A 6-9 digit or alphanumeric OTP code is sent to the user's verified email address **Step 2** Upon verification of the correct code, an API key credential is generated and encrypted for the client ### Credential bundle method > [!NOTE] > > This method is only supported by **legacy iframe-based flows** and is not available in the current 0xkey SDKs. The API key credential is encrypted and delivered directly through email to the user. Once the credential is live on the client side (within the context of an iframe), it is readily available to stamp (authenticate) requests. See the [enclave to end-user secure channel](/security/enclave-secure-channels) for more info on how we achieve secure delivery. This flow remains available for existing legacy integrations but is not recommended for new implementations. As an alternative, we recommend using the email OTP flow, which is fully supported by the current SDKs. An example that sends a magic link using [magicLinkTemplate](https://docs.0xkey.io/authentication/email#email-auth-and-recovery:~:text=height%20of%20124px-,magicLinkTemplate,-%3A%20a%20template%20for) can be found [here](https://github.com/0xkey-io/sdk-js/tree/main/examples/magic-link-auth). ### Email recovery In 0xkey, email recovery **does not refer to a separate, recovery-only email address** (as commonly used in consumer products, where a recovery email can reset access but cannot itself be used to sign in). Instead, it means **adding email as an authentication method for a user**. Once added, that user can authenticate using email by default, alongside any other configured authenticators (such as passkeys, social logins or external wallets). The legacy iframe-based flow using `INIT_USER_EMAIL_RECOVERY` and `RECOVER_USER` still exists for backward compatibility with older integrations. These flows ultimately attach new authentication material (for example, a passkey) to the user. They are being deprecated and **should not be used for new integrations**. ## Prerequisites Make sure you have set up your primary 0xkey organization with at least one API user that can programmatically initiate email auth and create suborganizations. Check out our [Quickstart guide](/getting-started/quickstart) if you need help getting started. To allow an API user to initiate email auth, you'll need the following policy in your main organization: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "effect": "EFFECT_ALLOW", "consensus": "approvers.any(user, user.id == '')", "condition": "(activity.resource == 'AUTH' && activity.action == 'CREATE') || (activity.resource == 'ORGANIZATION' && activity.action == 'CREATE')" } ``` For OTP Auth signup and login flows you will need a user with the following policy ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "effect": "EFFECT_ALLOW", "consensus": "approvers.any(user, user.id == '')", "condition": "(activity.resource == 'AUTH' && activity.action == 'CREATE') || (activity.resource == 'OTP' && activity.action == 'CREATE') || (activity.resource == 'OTP' && activity.action == 'VERIFY') || (activity.resource == 'ORGANIZATION' && activity.action == 'CREATE')" } ``` > [!NOTE] > > Avoid using an API key that is also present in the sub-organization that you're targeting within the email activities. 0xkey identifies the user from the request signature and in case of an identical API key it will always prioritize the sub-organization user matching. As a result, it will try to evaluate the sub-organization policies instead of the parent ones. ## User experience ### OTP-based authentication flow The flow begins with a new activity of type `ACTIVITY_TYPE_INIT_OTP_V3` using the parent organization id with these parameters: * `otpType`: specify `"OTP_TYPE_EMAIL"` * `contact`: user's email address * `emailCustomization`: optional parameters for customizing emails * `userIdentifier`: optional parameter for rate limiting SMS OTP requests per user. We recommend generating this server-side based on the user's IP address or public key. See the [OTP Rate Limits](#otp-rate-limits) section below for more details. * `alphanumeric`: optional parameter for making this code bech32 alphanumeric or not. default: true * `otpLength`: optional parameter for selecting the length of the OTP. default: 9 * `expirationSeconds`: optional validity window (defaults to 5 minutes) * `sendFromEmailAddress` : optional custom email address from which to send the OTP email * `sendFromEmailSenderName` : optional custom sender name for use with sendFromEmailAddress; if left empty, will default to ‘Notifications’ * `replyToEmailAddress` : optional custom email address to use as reply-to The response to `ACTIVITY_TYPE_INIT_OTP_V3` includes an `otpEncryptionTargetBundle` which is used in OTP verification. After receiving the OTP, users complete OTP verification with `ACTIVITY_TYPE_VERIFY_OTP_V2` using the parent organization id which returns a verificationToken JWT: * `otpId`: ID from the init activity * `encryptedOtpBundle`: bundle generated using the otpEncryptionTargetBundle received during `ACTIVITY_TYPE_INIT_OTP_V3` and contains the 6-9 digit or alphanumeric code received via email, and the public key of a client-side generated keypair. * `expirationSeconds`: optional validity window (defaults to 1 hour) After receiving the verification token, users complete OTP authentication flow with `ACTIVITY_TYPE_OTP_LOGIN_V2` using the sub-organization ID associated with the contact from the first step: * `publicKey`: public key to add to organization data associated with the signing key in IndexedDB or SecureStorage. * `verificationToken`: JWT returned from successful `VERIFY_OTP` activity * `clientSignature`: This proves authorization for the verification token being used, and is generated using the keypair whose public key was provided in the `encryptedOtpBundle` during verification. * `expirationSeconds`: optional validity window (defaults to 15 minutes) * `invalidateExisting`: optional boolean to invalidate previous login sessions > [!NOTE] > > If you are migrating from a legacy OTP flow to the new updated flow, check out the [OTP Migration Guide](/authentication/otp-migration-guide) for details on required changes. ![auth otp email](https://mintcdn.com/chain/d2Wj9s7maL6f08Ct/images/authentication/img/auth_otp_email.png?fit=max\&auto=format\&n=d2Wj9s7maL6f08Ct\&q=85\&s=bf4309ca4a354e2493700dab8d957d1c) ### OTP rate limits In order to safeguard users, 0xkey enforces rate limits for OTP auth activities. If a `userIdentifier` parameter is provided, the following limits are enforced: * 3 requests per 3 minutes per unique `userIdentifier` * 3 retries max per code, after which point that code will be locked * 3 active codes per user, each with a 5 minute TTL ### Credential bundle authentication flow This alternative method uses `ACTIVITY_TYPE_EMAIL_AUTH` with these parameters: * `email`: user's email address (must match their registered email) * `targetPublicKey`: public key for credential encryption * `apiKeyName`: optional name (defaults to `Email Auth - `) * `expirationSeconds`: optional validity window (defaults to 15 minutes) * `emailCustomization`: optional parameters for customizing emails * `invalidateExisting`: optional boolean to invalidate previous Email Auth API keys ![auth email](https://mintcdn.com/chain/d2Wj9s7maL6f08Ct/images/authentication/img/auth_email.png?fit=max\&auto=format\&n=d2Wj9s7maL6f08Ct\&q=85\&s=7a1e80d7e11dcdaf8af458e7f1938a39) ## Email customization We offer customization for the following: * `appName`: the name of the application. This will be used in the email's subject, e.g. `Sign in to ${appName}` * `logoUrl`: a link to a PNG with a max width of 340px and max height of 124px * `magicLinkTemplate`: a template for the URL to be used in the magic link button, e.g. `https://dapp.xyz/%s`. The auth bundle will be interpolated into the `%s` ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} // Sign and submits the EMAIL_AUTH activity const response = await client.emailAuth({ type: "ACTIVITY_TYPE_EMAIL_AUTH", timestampMs: String(Date.now()), organizationId: , parameters: { email: , targetPublicKey: , apiKeyName: , expirationSeconds: , emailCustomization: { appName: , logoUrl: , magicLinkTemplate: } }, }); ``` ### Breaking change: `appName` required > [!WARNING] > > **Effective December 16, 2025** > > Beginning December 16, 2025, all email-based OTP and recovery activities will require the `appName` parameter. Existing SDK versions will continue working, but upgrading without setting an `appName` will break email-based flows. > > > [card] Auth Proxy Users > > > > **Affected:** Anyone using Auth Proxy without `appName` set > > > > **Action:** Set `appName` under [email configuration](https://app.0xkey.io/dashboard/walletKit) > > > [card] Server SDK Users > > > > **Affected:** Users calling `init_otp_auth`, `init_otp`, `email_recovery`, or `email_auth` without `appName` > > > > **Action:**\ > > • For `email_recovery` or `email_auth`: include `appName` in your request\ > > • For `init_otp` or `init_otp_auth`: update your API call to match the new input structure when upgrading to the latest server-SDK > > > [accordion] Server SDK code examples > > > > > [card] emailAuth & emailRecovery > > > > > > Both methods use the same parameter structure. Here's an example with `emailAuth`: > > > > > > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} > > > await client.emailAuth({ > > > parameters: { > > > email: "user@example.com", > > > targetPublicKey: "", > > > emailCustomization: { > > > appName: "Your App Name" // this is now required > > > } > > > } > > > }); > > > ``` > > > > > [card] initOtp & initOtpAuth > > > > > > Both methods use the same parameter structure. Here's an example with `initOtp`: > > > > > > ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} > > > await client.initOtp({ > > > parameters: { > > > otpType: "OTP_TYPE_EMAIL", > > > contact: "user@example.com", > > > appName: "Your App Name", // this is now required > > > emailCustomization: { > > > // other optional customization > > > } > > > } > > > }); > > > ``` > > > [card] Policy activity type updates > > > > If you manage email flows with policies, update to the new activity types: > > > > **EMAIL_AUTH**\ > > Old: `ACTIVITY_TYPE_EMAIL_AUTH`, `ACTIVITY_TYPE_EMAIL_AUTH_V2`\ > > New: `ACTIVITY_TYPE_EMAIL_AUTH_V3` > > > > **INIT_OTP_AUTH**\ > > Old: `ACTIVITY_TYPE_INIT_OTP_AUTH`, `ACTIVITY_TYPE_INIT_OTP_AUTH_V2`\ > > New: `ACTIVITY_TYPE_INIT_OTP_AUTH_V3` > > > > **INIT_OTP** (contact verification & signup)\ > > Old: `ACTIVITY_TYPE_INIT_OTP`, `ACTIVITY_TYPE_INIT_OTP_V2`\ > > New: `ACTIVITY_TYPE_INIT_OTP_V3` > > > > **VERIFY_OTP**\ > > Old: `ACTIVITY_TYPE_VERIFY_OTP`\ > > New: `ACTIVITY_TYPE_VERIFY_OTP_V2` > > > > **OTP_LOGIN**\ > > Old: `ACTIVITY_TYPE_OTP_LOGIN`\ > > New: `ACTIVITY_TYPE_OTP_LOGIN_V2` > > > > **INIT_USER_EMAIL_RECOVERY**\ > > Old: `ACTIVITY_TYPE_INIT_USER_EMAIL_RECOVERY`\ > > New: `ACTIVITY_TYPE_INIT_USER_EMAIL_RECOVERY_V2` ### Email templates We also support custom HTML email templates for [Enterprise](https://0xkey.io/contact-us) clients on the **Scale** tier. This allows you to inject arbitrary data from a JSON string containing key-value pairs. In this case, the `emailCustomization` variable may look like: ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} ... emailCustomization: { templateId: , templateVariables: "{\"username\": \"alice and bob\"}" } ... ``` In this specific example, the value `alice and bob` can be interpolated into the email template using the key `username`, referenced in the template with `{{ index .TemplateVariables "username" }}`. The use of such template variables is purely optional. Here’s an example of a custom HTML email template that includes the OTP code, referenced within the markup as `{{ .OtpCode }}`. For best compatibility across email providers, make sure to use PNG images within your templates. ![dynamic email auth example](https://mintcdn.com/chain/d2Wj9s7maL6f08Ct/images/embedded-wallets/img/email-auth-example-template.png?fit=max\&auto=format\&n=d2Wj9s7maL6f08Ct\&q=85\&s=0cedc034efbebeb0fcba28a30ca8d851) > [!WARNING] > > **Bespoke HTML templates** and **custom email sender domains** are available to [**Enterprise clients**](https://0xkey.io/contact-us) on the **Scale tier** or higher. If you are interested in implementing bespoke, fully-customized email templates, please reach out to [hello@0xkey.io](mailto:hello@0xkey.io). ### Custom email sender domain [Enterprise](https://0xkey.io/contact-us) clients can also customize the email sender domain. To get set up, please reach out to your 0xkey rep to get started but here is what you'll be able to configure: ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} // Optional custom email address from which to send the OTP email "sendFromEmailAddress": "notifs@mail.domain.com" // Optional custom sender name "sendFromEmailSenderName": "MyApp Notifications" // Optional reply-to email address "replyToEmailAddress": "reply@mail.domain.com" ``` Please keep in mind that: * Email has to be from a pre-whitelisted domain * If there is no `sendFromEmailAddress` or it's invalid, the other two fields are ignored * If `sendFromEmailSenderName` is absent, it defaults to "Notifications" (again, ONLY if `sendFromEmailAddress` is present and valid) * If `replyToEmailAddress` is absent, then there is no reply-to added. If it is present, it must ALSO be from a valid, whitelisted domain, but it doesn't have to be the same email address as the `sendFromEmailAddress` one (though once again, this first one MUST be present, or the other two feature are ignored) * **Sender name screening:** Some email clients (e.g. Gmail) screen sender names more aggressively than others (e.g. Apple Mail), which can lead to inconsistent display across clients. To ensure a consistent experience, keep your `sendFromEmailSenderName` "safe looking" — avoid underscores, special symbols, or unusual formatting that may cause it to be filtered or hidden. If you are interested in implementing bespoke, fully-customized email templates and sender domain, please reach out to [hello@0xkey.io](mailto:hello@0xkey.io). ### Authorization Authorization is managed through our [policy engine](/policies/overview): ### Authentication Both OTP-based and credential bundle authentication activities: * Can be performed by [root quorum](/concepts/users/root-quorum#root-quorum) or users with proper policy authorization * Require the respective feature to be enabled in the organization and sub-organization * Can target any user in the organization or sub-organizations Specifically: * For OTP-based auth (current): `ACTIVITY_TYPE_INIT_OTP_V3`, `ACTIVITY_TYPE_VERIFY_OTP_V2`, and `ACTIVITY_TYPE_OTP_LOGIN_V2` * For credential bundle auth: `ACTIVITY_TYPE_EMAIL_AUTH` ![email auth authorization](https://mintcdn.com/chain/SBPPOKcVznKsWQeY/images/authentication/img/diagrams/email_auth_authorization.png?fit=max\&auto=format\&n=SBPPOKcVznKsWQeY\&q=85\&s=010965b571ab2045a237f0baca02a0de) ### Example implementations * [OTP Auth Example](https://github.com/0xkey-io/sdk-js/tree/main/examples/otp-auth) * [Email Auth Example](https://github.com/0xkey-io/sdk-js/tree/main/examples/email-auth-local-storage) * [Demo Embedded Wallet](https://github.com/0xkey-io/demo-embedded-wallet) (source code) ## Implementation in organizations For organizations accessed via dashboard: 1. Ensure the required features are enabled: * `FEATURE_NAME_OTP_EMAIL_AUTH` for OTP-based authentication * `FEATURE_NAME_EMAIL_AUTH` for credential bundle authentication 2. Users initiating the request must have appropriate permissions ## Opting out Organizations can disable email-based features if their security model requires it: Use `ACTIVITY_TYPE_REMOVE_ORGANIZATION_FEATURE` to disable: * `FEATURE_NAME_OTP_EMAIL_AUTH` for OTP-based authentication * `FEATURE_NAME_EMAIL_AUTH` for credential bundle authentication When creating sub-organizations, use: * `disableOtpEmailAuth` parameter for OTP-based authentication * `disableEmailAuth` parameter for credential bundle authentication ## Implementation notes * Users are limited to: * 10 long-lived API keys * 10 expiring API keys (oldest are discarded when limit is reached) ### For top-level organizations * Both authentication methods are disabled by default * Must be enabled via `ACTIVITY_TYPE_SET_ORGANIZATION_FEATURE` ### For sub-organizations * Both authentication methods are enabled by default * Can be disabled during creation using `CreateSubOrganizationIntentV7` activity parameters Example of enabling OTP-based Email Auth: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} 0xkey request --host api.0xkey.io --path /public/v1/submit/set_organization_feature --body '{ "timestampMs": "'"$(date +%s)"'000", "type": "ACTIVITY_TYPE_SET_ORGANIZATION_FEATURE", "organizationId": "", "parameters": { "name": "FEATURE_NAME_OTP_EMAIL_AUTH" } }' --organization ``` Example of enabling credential bundle Email Auth: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} 0xkey request --host api.0xkey.io --path /public/v1/submit/set_organization_feature --body '{ "timestampMs": "'"$(date +%s)"'000", "type": "ACTIVITY_TYPE_SET_ORGANIZATION_FEATURE", "organizationId": "", "parameters": { "name": "FEATURE_NAME_EMAIL_AUTH" } }' --organization ``` # Email authentication Source: https://docs.0xkey.io/authentication/email-walkthrough Email auth is a powerful feature to couple with [sub-organizations](/concepts/sub-organizations) for your users. This approach empowers your users to authenticate their 0xkey in a simple way (via email!), while minimizing your involvement: we engineered this feature to ensure your organization is unable to take over sub-organizations even if it wanted to. The open-source [Demo Embedded Wallet](https://github.com/0xkey-io/demo-embedded-wallet) shows how email auth might be integrated. We encourage you to read its code before diving into your own implementation. ## Prerequisites Make sure you have set up your primary 0xkey organization with at least one API user that can programmatically initiate email auth on behalf of suborgs. Check out our [Quickstart guide](/getting-started/quickstart) if you need help getting started. To allow an API user to initiate email auth, you'll need the following policy in your main organization: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "effect": "EFFECT_ALLOW", "consensus": "approvers.any(user, user.id == '')", "condition": "activity.resource == 'AUTH' && activity.action == 'CREATE'" } ``` ## Helper packages * We have released open-source code to create target encryption keys, decrypt auth credentials, and sign 0xkey activities. We've deployed this as a static HTML page hosted on `authproxy.0xkey.io` meant to be embedded as an iframe element (see the code [here](https://github.com/0xkey-io/frames)). This ensures the auth credentials are encrypted to keys that your organization doesn't have access to (because they live in the iframe, on a separate domain) * We have also built a package to help you insert this iframe and interact with it in the context of email auth: [`@0xkey-io/iframe-stamper`](https://www.npmjs.com/package/@0xkey-io/iframe-stamper) In the rest of this guide we'll assume you are using these helpers. ## Email auth step-by-step Here's a diagram summarizing the email auth flow step-by-step: ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant Page as Auth page participant Iframe as Hidden iframe participant Business as Your business participant API as 0xkey participant Inbox as User inbox Note over Iframe: 1. Creates an encryption target key
(stored in the iframe's local storage) Page->>Business: 2. Email + iframe target public key Business->>API: 3. EMAIL_AUTH activity (signed by your business) API->>Inbox: 4. Auth bundle Inbox->>Page: 5. User pastes the bundle or opens the magic link Page->>Iframe: 6. Bundle saved and decrypted with the target key Page->>Iframe: 7. Unsigned user activity Iframe->>API: 8. Signs and submits the activity Note over Page,Iframe: 9-12. A new tab reloads the bundle from local
storage and signs further activities the same way ``` Let's review these steps in detail: **Step 1** User on `yoursite.xyz` clicks "auth", and a new auth UI is shown. We recommend this auth UI be a new hosted page of your site or application, which contains language explaining to the user what steps they will need to take next to successfully authenticate. While the UI is in a loading state your frontend uses [`@0xkey-io/iframe-stamper`](https://www.npmjs.com/package/@0xkey-io/iframe-stamper) to insert a new iframe element: ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} const iframeStamper = new IframeStamper({ iframeUrl: "https://authproxy.0xkey.io", // Configure how the iframe element is inserted on the page iframeContainerId: "your-container", iframeElementId: "0xkey-iframe", }); // Inserts the iframe in the DOM. This creates the new encryption target key const publicKey = await iframeStamper.init(); ``` **Step 2** Your code receives the iframe public key and shows the auth form, and the user enters their email address. **Step 3** Your app can now create and sign a new `EMAIL_AUTH` activity with the user email and the iframe public key in the parameters. Optional arguments include a custom name for the API key, and a specific duration (denoted in seconds) for it. Note: you'll need to retrieve the sub-organization ID based on the user email. **Step 4** Email is received by the user. **Step 5** User copies and pastes their auth code into your app. Remember: this code is an encrypted credential which can only be decrypted within the iframe. In order to enable persistent sessions, save the auth code in local storage: ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} window.localStorage.setItem("BUNDLE", bundle); ``` See [Email Customization](#email-customization) below to use a magic link instead of a one time code. **Step 6** Your app injects the auth code into the iframe for decryption: ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} await iframeStamper.injectCredentialBundle(code); ``` **Step 7** At this point, the user is authenticated! **Step 8** Your app should use [`@0xkey-io/iframe-stamper`](https://www.npmjs.com/package/@0xkey-io/iframe-stamper) to sign a new activity, e.g. `CREATE_WALLET`: ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} // New client instantiated with our iframe stamper const client = new ZeroXKeyClient( { baseUrl: "https://api.0xkey.io" }, iframeStamper, ); // Sign and submits the CREATE_WALLET activity const response = await client.createWallet({ type: "ACTIVITY_TYPE_CREATE_WALLET", timestampMs: String(Date.now()), organizationId: authResponse.organizationId, parameters: { walletName: "Default Wallet", accounts: [ { curve: "CURVE_SECP256K1", pathFormat: "PATH_FORMAT_BIP32", path: "m/44'/60'/0'/0/0", addressFormat: "ADDRESS_FORMAT_ETHEREUM", }, ], }, }); ``` **Step 9** User navigates to a new tab. **Step 10** Because the code was also saved in local storage (step 6), it can be injected into the iframe across different tabs, resulting in a persistent session. See the Demo Embedded Wallet for a [sample implementation](https://github.com/0xkey-io/demo-embedded-wallet/blob/main/src/providers/auth-provider.tsx), specifically dealing with sharing the iframeStamper across components. ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} const code = window.localStorage.getItem("BUNDLE"); await iframeStamper.injectCredentialBundle(code); ``` **Step 11** Again, the user is authenticated, and able to initiate activities! **Step 12** Just like step 8, the iframeStamper can be used to sign another activity. ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} const client = new ZeroXKeyClient( { baseUrl: "https://api.0xkey.io" }, iframeStamper, ); // Sign and submits a SIGN_TRANSACTION activity const response = await client.signTransaction({ type: "ACTIVITY_TYPE_SIGN_TRANSACTION_V2", timestampMs: String(Date.now()), organizationId: authResponse.organizationId, parameters: { signWith: "0x...", type: "TRANSACTION_TYPE_ETHEREUM", unsignedTransaction: "unsigned-tx", }, }); ``` Congrats! You've succcessfully implemented Email Auth! ## Integration notes ### Email customization We offer customization for the following: * `appName`: the name of the application. This will be used in the email's subject, e.g. `Sign in to ${appName}` * `logoUrl`: a link to a PNG with a max width of 340px and max height of 124px * `magicLinkTemplate`: a template for the URL to be used in the magic link button, e.g. `https://dapp.xyz/%s`. The auth bundle will be interpolated into the `%s` ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} // Sign and submits the EMAIL_AUTH activity const response = await client.emailAuth({ type: "ACTIVITY_TYPE_EMAIL_AUTH", timestampMs: String(Date.now()), organizationId: , parameters: { email: , targetPublicKey: , apiKeyName: , expirationSeconds: , emailCustomization: { appName: , logoUrl: , magicLinkTemplate: } }, }); ``` ### Bespoke email templates We also support custom HTML email templates for [**Enterprise**](https://0xkey.io/contact-us) clients. This allows you to inject arbitrary data from a JSON string containing key-value pairs. In this case, the `emailCustomization` variable may look like: ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} ... emailCustomization: { templateId: , templateVariables: "{\"username\": \"alice and bob\"}" } ... ``` In this specific example, the value `alice and bob` can be interpolated into the email template using the key `username`. The use of such template variables is purely optional. > [!WARNING] > > [**Bespoke HTML templates**](https://docs.0xkey.io/authentication/email-walkthrough#bespoke-email-templates) and [**custom email sender domains**](https://docs.0xkey.io/authentication/email-walkthrough#custom-email-sender-domain) are available to [**Enterprise clients**](https://0xkey.io/contact-us) on the **Scale tier** or higher. ### Custom email sender domain [Enterprise](https://0xkey.io/contact-us) clients can also customize the email sender domain. To get set up, please reach out to your 0xkey rep to get started but here is what you'll be able to configure: ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} message InitOtpAuthIntent { // Optional custom email address from which to send the OTP email optional string send_from_email_address = "notifs@mail.domain.com"; // Optional custom sender name (e.g. "MyApp Notifications") optional string send_from_email_sender_name = "MyApp Notifications"; // Optional reply-to email address optional string reply_to_email_address = "reply@mail.domain.com"; } ``` Please keep in mind that: * Email has to be from a pre-whitelisted domain * If there is no `send_from_email_address` or it's invalid, the other two fields are ignored * If `send_from_email_sender_name` is absent, it defaults to "Notifications" (again, ONLY if `send_from_email_address` is present and valid) * If `reply_to_email_address` is absent, then there is no reply-to added. If it is present, it must ALSO be from a valid, whitelisted domain, but it doesn't have to be the same email address as the `send_from_email_address` one (though once again, this first one MUST be present, or the other two feature are ignored) If you are interested in implementing bespoke, fully-customized email templates and sender domain, please reach out to [hello@0xkey.io](mailto:hello@0xkey.io). ### Credential validity checks By default, if a 0xkey request is signed with an expired credential, the API will return a 401 error. If you'd like to validate an injected credential, you can specifically use the `whoami` endpoint: ```js theme={"theme":{"light":"github-light","dark":"github-dark"}} const whoamiResponse = await client.getWhoami({ organizationId, }); ``` A valid response indicates the credential is still live; otherwise, an error including `unable to authenticate: api key expired` will be thrown. # OIDC Federation Source: https://docs.0xkey.io/authentication/oidc-federation Register your own OpenID Connect Identity Provider as a trusted issuer so your existing users can log in and bind identities to 0xkey sub-organizations — with every token cryptographically re-verified inside the enclave. **OIDC Federation** lets a parent organization register its *own* OIDC Identity Provider (an internal auth service, an Auth0/Cognito tenant, or any standards-compliant IdP) as a trusted issuer for its sub-organization users. It's the recommended path for customers who already have a user system and want to keep their IdP as the source of truth for identity while still getting cryptographically-verified, non-custodial logins into 0xkey. > [!NOTE] > > This page is the task-oriented integration guide. For the conceptual background and how federation compares to the built-in social providers (Google, Apple, …), see [Social logins → Custom OIDC providers](/authentication/social-logins#custom-oidc-providers-your-own-identity-provider). The mechanics below reuse the same enclave verification path described there. ## When to use federation > [card] Use OIDC Federation > > You operate your own IdP (or an Auth0/Cognito/Okta tenant) and want it to be the identity source of truth. You want to onboard *existing* users into embedded wallets without asking them to re-authenticate through a third-party social button. > [card] Use built-in social logins > > You just want "Sign in with Google/Apple/…". Those issuers are trusted by default — no registration needed. See [Social logins](/authentication/social-logins). Federation and built-in social logins are not mutually exclusive: a single sub-organization user can have both a Google identity and your own IdP identity bound to them. ## How it fits together Trust is established once, at the **organization** level; identity binding and login happen per **user**. ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant Admin as Root-quorum admin participant IdP as Your IdP participant App as Your app / backend participant 0xkey Note over Admin,0xkey: One-time, org-level trust setup Admin->>0xkey: CREATE_OIDC_PROVIDER (issuer, audiences) 0xkey->>Admin: providerId Note over IdP,0xkey: Per-user, at login time App->>IdP: Authenticate end-user (nonce = sha256(publicKey)) IdP->>App: id_token (OIDC JWT) App->>0xkey: oauth_login / CREATE_SUB_ORGANIZATION / CREATE_OAUTH_PROVIDERS 0xkey->>0xkey: Enclave fetches issuer JWKS live, verifies sig + iss/aud/exp/nonce 0xkey->>App: session JWT / bound identity ``` The enclave never trusts the token at face value: on **every** login or binding it independently fetches the issuer's discovery document and JWKS over HTTPS (through the [TLS Fetcher](/authentication/social-logins#oidc-token-verification)) and re-verifies the signature, `iss`, `aud`, `exp`, and `nonce`. ## Prerequisites for your IdP Your Identity Provider must expose the standard OIDC discovery surface: * **OIDC Discovery** at `https:///.well-known/openid-configuration`, returning at minimum `issuer` and `jwks_uri`. * **JWKS** served live over HTTPS at the discovered `jwks_uri`. 0xkey enforces full public-CA TLS validation — there is **no** self-signed / plain-HTTP / private-CA bypass, even in dev. * **Same-host `jwks_uri`.** For self-hosted (non-built-in) issuers, the `jwks_uri` host must match the issuer host. A mismatch is rejected (see [JWKS host binding](#jwks-host-does-not-match-issuer-host)). * **RS256 or ES256** signatures. Other algorithms are rejected. * **Stable `sub`.** The `sub` claim must be a stable, non-reassignable per-user identifier — `(iss, sub)` is 0xkey's identity primary key. If your IdP allows account merging or `sub` reassignment, review it carefully (see the [Auth0 caveat](/authentication/social-logins#auth0)). * **Key rotation grace period.** When you rotate signing keys, publish the new key *and* keep the old key in the JWKS until in-flight tokens expire. 0xkey simply trusts whatever the JWKS currently serves. ## Integration guide **1. Register your issuer (one-time, root-quorum)** Registering an issuer establishes trust for the whole parent organization. It is a **root-quorum-only** operation. From the **Dashboard**: go to **Wallet Kit → OIDC Providers → Add provider**, fill in a name, the issuer URL, and at least one audience. The UI wraps the same activity behind a passkey-gated flow. Or via the API with [`CREATE_OIDC_PROVIDER`](/api-reference/activities/create-oidc-provider): ```bash title="cURL — CreateOidcProvider" theme={"theme":{"light":"github-light","dark":"github-dark"}} curl --request POST \ --url https://api.0xkey.io/public/v1/submit/create_oidc_provider \ --header 'Content-Type: application/json' \ --header "X-Stamp: " \ --data '{ "type": "ACTIVITY_TYPE_CREATE_OIDC_PROVIDER", "timestampMs": "1746736509954", "organizationId": "", "parameters": { "providerName": "Acme Corp IdP", "issuer": "https://auth.acme.com", "audiences": ["acme-0xkey-client-id"] } }' ``` * `issuer` must **exactly** match the `iss` claim of your IdP's tokens, and is **immutable** — delete and re-create if it ever changes. * `audiences` is a **required, non-empty** allowlist of `aud` values (your OAuth2 client IDs). There is no wildcard — see [fail-closed audiences](/authentication/social-logins#fail-closed-no-wildcard-trust). **2. Mint an id_token bound to the session key** Before starting your IdP login flow, the frontend generates an API keypair (this becomes the session key). When it authenticates the user against your IdP, it sets the OIDC `nonce` to `sha256(publicKey)` so the resulting `id_token` is cryptographically bound to that key. If your IdP cannot customize `nonce`, 0xkey also accepts a `tknonce` claim — only one of the two needs to equal `sha256(publicKey)`. Registration-only flows (`CREATE_OIDC_PROVIDER`, `CREATE_SUB_ORGANIZATION`) don't carry a `publicKey`, so the nonce binding is not enforced there. **3. Onboard or log the user in** With the `id_token` and the API `publicKey`, your backend: 1. Looks up the sub-organization(s) associated with that identity. 2. If none exists, creates one with [`CREATE_SUB_ORGANIZATION`](/api-reference/organizations/create-sub-organization), seeding the user's OAuth provider from the token. 3. Calls [`oauth_login`](/api-reference/activities/login-with-oauth) with the `id_token` + `publicKey` to obtain a session JWT. Once your issuer is registered, this flow is **identical** to a built-in provider — `oauth_login` doesn't care whether the issuer is Google or your own IdP. **4. Bind additional identities to an existing user (optional)** To add your IdP as a login method for a user who already exists (e.g. they signed up with a passkey), submit [`CREATE_OAUTH_PROVIDERS`](/api-reference/activities/create-oauth-providers) with the raw `id_token`: ```bash title="cURL — CreateOauthProviders" theme={"theme":{"light":"github-light","dark":"github-dark"}} curl --request POST \ --url https://api.0xkey.io/public/v1/submit/create_oauth_providers \ --header 'Content-Type: application/json' \ --header "X-Stamp: " \ --data '{ "type": "ACTIVITY_TYPE_CREATE_OAUTH_PROVIDERS_V2", "timestampMs": "1746736509954", "organizationId": "", "parameters": { "userId": "", "oauthProviders": [ { "providerName": "acme-idp", "oidcToken": "" } ] } }' ``` > [!WARNING] > > Send `oidcToken` as a **flat string field** inside each `oauthProviders` entry, exactly as shown. Do not nest it under `tokenOrClaims`. The enclave re-verifies this token end-to-end before binding the identity. See [missing field `oidcToken`](#missing-field-oidctoken) if you hit a deserialization error. ## Managing the registry | Operation | Activity / Query | Notes | | - | - | - | | List providers | [`GET_OIDC_PROVIDERS`](/api-reference/queries/get-oidc-providers) | All registered issuers for the organization. | | Update a provider | [`UPDATE_OIDC_PROVIDER`](/api-reference/activities/update-oidc-provider) | Change `providerName`, `audiences`, or `enabled`. The `issuer` is immutable. | | Remove a provider | [`DELETE_OIDC_PROVIDER`](/api-reference/activities/delete-oidc-provider) | Future logins for that issuer fail immediately. Existing per-user bindings are **not** retroactively deleted — use [`DELETE_OAUTH_PROVIDERS`](/api-reference/activities/delete-oauth-providers) for those. | All three write operations are root-quorum-only. ## Security model > [!WARNING] > > Registering an issuer is a **trust decision**, not a convenience setting. Anyone who can mint a validly-signed token for a registered `(issuer, audience)` pair can log in as — or bind an identity to — any matching sub-organization user. Keep the audience list as narrow as possible and restrict `CREATE_/UPDATE_/DELETE_OIDC_PROVIDER` to root-quorum admins. * **Fail-closed audiences.** An empty audience list is rejected outright; there is no "trust this issuer for any audience" option. * **JWKS host binding.** For federated (non-built-in) issuers, the JWKS fetch host must match the issuer host — this blocks a tampered discovery document from redirecting key-fetching to an attacker-controlled host. * **Live verification.** Signature, `iss`, `aud`, `exp`, `nbf` (with 60s skew), and `nonce` are checked inside the enclave against the issuer's live JWKS on every login/binding — nothing is cached as "already trusted". ## Troubleshooting The verification errors below surface from the enclave during `oauth_login`, `CREATE_SUB_ORGANIZATION`, or `CREATE_OAUTH_PROVIDERS`. They are all **fail-closed** — a rejected token never results in a session or a bound identity. ### OIDC issuer '…' is not a registered/enabled trusted IdP for this organization **Cause:** the token's `iss` doesn't match any enabled provider registered for the organization. **Fix:** * Confirm you ran [`CREATE_OIDC_PROVIDER`](/api-reference/activities/create-oidc-provider) for this issuer against the **correct parent organization**, and that the provider is `enabled`. * The registered `issuer` must be byte-for-byte equal to the token's `iss` (watch for a trailing slash, `http` vs `https`, or a tenant path). The issuer is immutable — if it's wrong, delete and re-create. * Verify the registry with [`GET_OIDC_PROVIDERS`](/api-reference/queries/get-oidc-providers). ### JWT 'iss' mismatch: expected '…', got '…' **Cause:** the token's issuer differs from the provider's configured issuer. **Fix:** align your IdP's `iss` claim with the exact string you registered. These must match character-for-character. ### JWT 'aud' mismatch: expected one of \[…] **Cause:** the token's `aud` isn't in the registered audience allowlist. **Fix:** add the OAuth2 client ID your app uses to the provider's `audiences` via [`UPDATE_OIDC_PROVIDER`](/api-reference/activities/update-oidc-provider). If you use different client IDs per platform (web/iOS/Android), register each one you intend to accept — or standardize on a single client ID (see [the `aud` note](/authentication/social-logins#what-does-0xkey-use-from-the-oidc-tokens-to-prove-identity)). ### JWT 'nonce' does not match sha256(public_key) **Cause:** the token's `nonce` (or `tknonce`) isn't the SHA-256 of the API `publicKey` used in `oauth_login`. **Fix:** set the OIDC `nonce` to `sha256(publicKey)` when you start the IdP login flow, using the **same** keypair you later pass to `oauth_login`. This binding is enforced only during authentication, not during registration-only flows. ### JWT has expired **Cause:** the `id_token`'s `exp` is in the past by the time the enclave verifies it. **Fix:** OIDC `id_token`s are short-lived (often \~1 hour). Mint a fresh token immediately before the 0xkey call rather than reusing a stale one. ### JWKS host does not match issuer host Full message: `OIDC JWKS fetch URL host does not match issuer host: issuer='…', jwks_url='…'`. **Cause:** for a federated issuer, the `jwks_uri` in your discovery document points at a different host than the issuer. **Fix:** serve your JWKS on the same host as your issuer. (Built-in social providers like Google are exempt because they legitimately publish JWKS on a separate host; this check applies only to your own registered issuers.) ### Unsupported JWT algorithm / JWK not found for kid **Cause:** the token is signed with an unsupported algorithm (only `RS256` and `ES256` are accepted), or its `kid` isn't present in the currently-served JWKS. **Fix:** sign tokens with RS256 or ES256, and keep every currently-valid signing key published in your JWKS. During rotation, retain the previous key until all tokens signed with it have expired. ### invalid OIDC token **Cause:** malformed JWT (not three `.`-separated parts) or missing a required claim (`aud`, `sub`, `iss`). **Fix:** see [`invalid OIDC token`](/developer-reference/api-overview/errors#invalid-oidc-token) in the error reference. ### missing field `oidcToken` **Cause:** a `CREATE_OAUTH_PROVIDERS` request whose `oauthProviders[]` entries don't carry a top-level `oidcToken` string. **Fix:** put `oidcToken` as a flat field on each provider object (as in the [binding example](#integration-guide) above), not nested under `tokenOrClaims`. The enclave expects the raw `id_token` string per provider entry. ## Related > [card] [Social logins](/authentication/social-logins) > > Built-in providers, OAuth 2.0-only wrapper flow, and the full OIDC verification model. > [card] [Create OIDC provider](/api-reference/activities/create-oidc-provider) > > API reference for registering an issuer. > [card] [Create OAuth providers](/api-reference/activities/create-oauth-providers) > > API reference for binding an identity to a user. > [card] [Errors](/developer-reference/api-overview/errors) > > Full error-code reference and troubleshooting hub. # Updated OTP login and signup flow Source: https://docs.0xkey.io/authentication/otp-migration-guide How to migrate to 0xkey's new security-upgraded OTP authentication flows. 0xkey's OTP authentication flows (email and SMS) have been upgraded to pass OTP code attempts as encrypted bundles rather than in plaintext — raising the bar for security and ensuring that server compromises can no longer be leveraged to compromise an OTP login process. The new flow is recommended for its security improvements, and we've included a migration guide from legacy flows to the new flow below. ## Migration guide For implementations using 0xkey's legacy OTP flows, migrating to the updated OTP flows is a breaking change and will require some tweaks to implementations beyond just upgrading SDK versions. > [!WARNING] > > If you have policies written against specific versions of the activities mentioned below, you will need to update those policies to reference the new activity versions. ### Updated OTP flow activity types The following activities (and any subsequent versions) use the updated OTP flow: | Activity | Description | | - | - | | `ACTIVITY_TYPE_INIT_OTP_V3` | Initiates an OTP flow via email or SMS, returns an encryption bundle to be used during OTP verification | | `ACTIVITY_TYPE_VERIFY_OTP_V2` | Verifies OTP attempt securely, returns a verification token (JWT) | | `ACTIVITY_TYPE_CREATE_SUB_ORGANIZATION_V7` | Used to sign up; consumes verification token received after successful `VERIFY_OTP_V2` activity | | `ACTIVITY_TYPE_OTP_LOGIN_V2` | Used to log in and generate a session; consumes verification token received after successful `VERIFY_OTP_V2` activity | NOTE: Older activity versions such as `ACTIVITY_TYPE_INIT_OTP_V2`, `ACTIVITY_TYPE_VERIFY_OTP` use our legacy OTP flow and are not interchangeable with the new ones due to the new encryption protocol. Notably, for sub organization creation, which accepts OTP verification tokens, `ACTIVITY_TYPE_CREATE_SUB_ORGANIZATION_V7` can be used as part of the legacy flow and the new updated flow, while `ACTIVITY_TYPE_CREATE_SUB_ORGANIZATION_V8` onwards will no longer be compatible with legacy OTP verification tokens. ### Required updates to implementations The following updates are required to legacy OTP implementations to migrate to the updated OTP flow, after bumping SDK versions: * The response shape for `ACTIVITY_TYPE_INIT_OTP_V3` now includes an `otpEncryptionTargetBundle` which is to be used during otp verification. This requires persisting state between `INIT_OTP` and `VERIFY_OTP` which means OTP flows need to be initiated and verified by the same service, or the service initiating OTP needs to pass the encryption bundle received in the response to the app client which will verify the OTP code. * The request shape for `ACTIVITY_TYPE_VERIFY_OTP_V2` now includes an `encryptedOtpBundle` which is generated using the `otpEncryptionTargetBundle` received from `ACTIVITY_TYPE_INIT_OTP_V3`. This bundle will include a client-generated public key and the OTP code attempt. The `encryptOtpCodeToBundle` helper function from [@0xkey-io/crypto](https://www.npmjs.com/package/@0xkey-io/crypto) is used to generate the `encryptedOtpBundle` used during OTP verification. * The verification token received in the response of `ACTIVITY_TYPE_VERIFY_OTP_V2` is signed by a different key than legacy OTP verification tokens. This key is included in our updated SDKs. * Login and signup flows initiated using OTP verification tokens now require client signature objects, generated using the client generated keypair whose public key was used during OTP verification. This process is handled by our updated SDKs. * Finally, users managing OTP flows with policies will need to update any policies referencing a specific OTP-related activity type so they point to the new activity versions. For more information and a diagram of the new OTP flow, please refer to additional documentation [here](/security/enclave-secure-channels#otp-login-flow). # Overview Source: https://docs.0xkey.io/authentication/overview Learn about supported authentication methods for 0xkey, how to add them, and usage details. 0xkey's wallet system supports granular controls on who can access wallets and what actions different users can perform. To enforce these controls, 0xkey's API must verify the identity of the party requesting a wallet action, ensuring that only authorized actions are executed by the system. This process is known as **authentication**. 0xkey supports both **API authentication** and **user authentication** for authenticating access to wallets. ## API authentication With **API authentication**, 0xkey authenticates a request from your server directly using an **API secret**. This ensures that 0xkey only executes requests sent by your servers alone, and no other party. In addition to the API secret, you can also configure **authorization policies** that control specific wallets, private keys, and other resources. Any requests to use or update these resources require approval according to the corresponding policy. This allows you to enforce granular controls on all 0xkey resources. For backend implementation details, see our [Backend Setup](/authentication/backend-setup) guide. **API Reference**: [Create API Keys](/api-reference/api-keys/create-api-keys), [Get API Keys](/api-reference/api-keys/get-api-key) ## User authentication 0xkey is a powerful toolkit for progressive authentication of users. With fine-grained control over onboarding flows and wallet connections, you can improve conversion and craft better UX. Using any of 0xkey's client-side SDKs, your app can authenticate users across web2 and web3 accounts, including: * **WebAuthN/Passkeys**: Biometric or passkey-based login based on the WebAuthn standard. [Learn more](/authentication/passkeys/introduction) * **Email or SMS**: Passwordless login via a one-time passcode sent to a user's email address or phone number. [Learn more](/authentication/email) | [SMS Authentication](/authentication/sms) * **OAuth and social logins**: Social login with Google, Apple, Twitter, Discord, GitHub, LinkedIn, and more. [Learn more](/authentication/social-logins) * **Wallets**: External wallet login via Sign-In With Ethereum and Sign-In With Solana. [Learn more](/embedded-wallets/code-examples/wallet-auth) Your app can configure each of these authentication methods to be an upfront login method, or as an account that users link later. All of 0xkey's authentication methods create a common user object, where you can easily find a user's unique ID and all of the accounts they've linked to their profile. A user is a user, regardless of whether they've connected with a wallet, email or other account. Once a user successfully authenticates with 0xkey, 0xkey creates a session for that user that your app can use to represent an authenticated session or to make authenticated requests to your backend. For information about managing authenticated sessions, see our [Sessions](/authentication/sessions) documentation. ## Related resources > [card] [Passkey Introduction](/authentication/passkeys/introduction) > > Biometric and hardware-based passwordless authentication using WebAuthn > standard. > [card] [Email Authentication](/authentication/email) > > Passwordless login via one-time codes sent to users' email addresses. > [card] [SMS Authentication](/authentication/sms) > > User verification through one-time passwords sent via text message. > [card] [Social Logins](/authentication/social-logins) > > OAuth authentication with popular social providers like Google, Apple, and > Twitter. > [card] [Sessions](/authentication/sessions) > > Manage authenticated user sessions and access tokens in your application. # Discoverable vs. non-discoverable Source: https://docs.0xkey.io/authentication/passkeys/discoverable-vs-non-discoverable Also known as "resident" vs. "non-resident" credentials. From [the spec](https://www.w3.org/TR/webauthn-2/) > Historically, client-side discoverable credentials have been known as resident credentials or resident keys. Due to the phrases ResidentKey and residentKey being widely used in both the WebAuthn API and also in the Authenticator Model (e.g., in dictionary member names, algorithm variable names, and operation parameters) the usage of resident within their names has not been changed for backwards compatibility purposes. Also, the term resident key is defined here as equivalent to a client-side discoverable credential. What does this mean exactly? * "resident" credentials and "discoverable" credentials are the same * "non-resident" credentials and "non-discoverable" credentials are the same. The spec authors made this rename for clarity. With terminology out of the way, what is a "discoverable" credential compared to a "non-discoverable" credential? And why does it matter? ## Discoverable credentials A discoverable credential is a self-contained key pair, stored on the end-user's device. Discoverable credentials are preferred because keys are self-contained, can easily be synced and can be used across devices independently. Crucially for UX, the end-user is able to list their passkeys and choose which device/passkey they'd like to use: With discoverable credentials you don't have to keep track of credential IDs. Your authentication flow can simply be: "prompt the user with passkey authentication", and let the browser or device native UX handle the rest! The downside is you lose some control over these prompts, because they will vary depending on your users' OS and browser. ## Non-discoverable credentials A non-discoverable credential isn’t stored on the end-user's device fully: 0xkey must store the generated credential ID; otherwise the user won’t be able to sign. This is because the actual signing key is a combination of an “on-device” secret and the credential ID (see details [here](https://crypto.stackexchange.com/questions/105942/how-do-non-resident-keys-work-in-webauthn)). Why would you choose non-discoverable credentials? * Most hardware security keys have limited slots to store discoverable credentials, or will refuse to create new discoverable credentials on the hardware altogether. YubiKey 5 [advertises 25 slots](https://support.yubico.com/hc/en-us/articles/4404456942738-FAQ#h_01FFHQFVBW0995G2MKZGCKQVEJ), SoloKeys [support 50](https://github.com/solokeys/solo1/issues/156#issuecomment-477645573), NitroKeys 3 [support 10](https://github.com/Nitrokey/nitrokey-3-firmware/blob/0e23c75318e2016ac1cfb8345de9279e3ad2eaf9/components/apps/src/lib.rs#L390). Non-discoverable credentials aren't subject to these limits because they work off of a single hardware secret. * Security keys can only allow clearing of individual slots if they support [CTAP 2.1](https://fidoalliance.org/specs/fido-v2.1-rd-20201208/fido-client-to-authenticator-protocol-v2.1-rd-20201208.html). This is described in [this blog post](https://fy.blackhats.net.au/blog/2023-02-02-how-hype-will-turn-your-security-key-into-junk/). When security keys do not support CTAP 2.1, slots can only be freed up by resetting the hardware entirely, erasing all secrets at once. * Non-discoverable credentials take less space. This is important in some environments, but unlikely to be relevant if your users are storing passkeys in their Google or Apple accounts (plenty of space available there!) * Credential IDs have to be communicated during authentication (via the `allowCredentials` field). This allows browsers to offer better, more tailored prompts in some cases. For example: if the list contains a single authenticator with `"transports": ["AUTHENTICATOR_TRANSPORT_INTERNAL"]`, Chrome does “the right thing” by skipping the device selection popup: users go straight to the fingerprint popup, with no need to select “this device”! The downside to this is, of course, that you need to store credential IDs, and you need to make sure you can retrieve credentials for each user. This can be done with a table of credentials keyed by user email, for example. Or if you have your own authentication already, a list of credentials can be returned when the user logs in. For a live example using non-discoverable credentials, head to [app.0xkey.io](https://app.0xkey.io). That's right, 0xkey uses non-discoverable credentials because we need to offer broad support for security keys. We have some work ongoing to support both discoverable and non-discoverable credentials going forward. # Integrating Passkeys Source: https://docs.0xkey.io/authentication/passkeys/integration ## Passkey flow A typical passkey flow is composed of 4 main steps, depicted below: ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} flowchart LR Frontend["App frontend
(your.app.xyz)"] Device["End-user device
(passkey)"] Backend["App backend
(optional)"] API["0xkey API (api.0xkey.io)
Nitro enclave verifies the signature"] Frontend -- "1. Triggers passkey prompt" --> Device Device -- "2. Passkey signature" --> Frontend Frontend -- "3. Signed request" --> Backend Backend -- "4. Forwards signed request" --> API ``` 1. Your app frontend triggers a passkey prompt. 2. Your end-user uses their device to produce a signature with their passkey, and a signed request is produced. 3. The signed request is forwarded to your backend. This step is optional, see ["To Proxy or not to proxy"](#proxying-signed-requests) below for more information. 4. The signed request is verified within a 0xkey secure enclave. This flow happens once for **registration** and for each subsequent **authentication** or signature request. The main difference is the browser APIs used to trigger the passkey prompt in step (1): * **Passkey registration** uses `navigator.credentials.create`(as described in [this guide](https://web.dev/passkey-registration/)). `navigator.credentials.create` triggers the creation of a **new** passkey. * **Passkey authentication** uses `navigator.credentials.get`. See [this guide](https://web.dev/passkey-form-autofill/) for more information. `navigator.credentials.get` triggers a signature prompt for an **existing** passkey. ## Our SDK can help Our SDK has integrated passkey functionality, and we've built examples to help you get started. * [`@0xkey-io/http`](https://www.npmjs.com/package/@0xkey-io/http) has a helper to trigger passkey registration (`getWebAuthnAttestation`). See the [`react-wallet-kit`](https://github.com/0xkey-io/sdk-js/tree/main/examples/react-wallet-kit) example for a full passkey registration flow. * [`@0xkey-io/webauthn-stamper`](https://www.npmjs.com/package/@0xkey-io/webauthn-stamper) is a passkey-compatible stamper which integrates seamlessly with `ZeroXKeyClient`: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} import { WebauthnStamper } from "@0xkey-io/webauthn-stamper"; import { ZeroXKeyClient, createActivityPoller } from "@0xkey-io/http"; const stamper = new WebauthnStamper({ rpId: "your.app.xyz", }); // New HTTP client able to sign with passkeys const httpClient = new ZeroXKeyClient( { baseUrl: "https://api.0xkey.io" }, stamper ); // This will produce a signed request that can be POSTed from anywhere. // The `signedRequest` has a URL, a POST body, and a "stamp" (HTTP header name and value) const signedRequest = await httpClient.stampCreatePrivateKeys(...) // Alternatively, you can POST directly from your frontend. // Our HTTP client will use the webauthn stamper and the configured baseUrl automatically! const activityPoller = createActivityPoller({ client: client, requestFn: client.createPrivateKeys, }); // Contains the activity result; no backend proxy needed! const completedActivity = await activityPoller({ type: "ACTIVITY_TYPE_CREATE_PRIVATE_KEYS_V2", // (omitting the rest of this for brevity) }) ``` * [`@0xkey-io/viem`](https://www.npmjs.com/package/@0xkey-io/viem) is a package wrapping all of the above so that you work directly with Viem without worrying about passkeys. See [this demo](https://github.com/0xkey-io/demo-viem-passkeys). Regardless of whether you use our helpers and abstractions, take a look at [our registration and authentication options guide](/authentication/passkeys/options). This will help you choose the right options for your passkey flow. If you have questions, feedback, or find yourself in need of an abstraction or integration that doesn't exist yet, please get in touch with us! You can * Create an [issue on our SDK repo](https://github.com/0xkey-io/sdk-js/issues) * Join our slack community [here](https://github.com/orgs/0xkey/shared_invite/zt-3aemp2g38-zIh4V~3vNpbX5PsSmkKxcQ) * Contact us at [hello@0xkey.io](mailto:hello@0xkey.io) We're here to make this as easy as possible for you and your team! ## Passkey wallets with sub-organizations If you're wondering how to create independent, non-custodial wallets for your end-users, head to [Sub-Organizations](/concepts/sub-organizations). In short: you'll be able to pass the registered passkeys as part of a "create sub-organization" activity, making your end-users the sole owners of any resource created within the sub-organization (including private keys). Your organization will only have read permissions. # Introduction to Passkeys Source: https://docs.0xkey.io/authentication/passkeys/introduction Passkeys are born out of a new standard being pushed by major industry players: Apple and Google. Google has a great high-level introduction to passkeys at [https://developers.google.com/identity/passkeys](https://developers.google.com/identity/passkeys), and Apple has its own version here: [https://developer.apple.com/passkeys](https://developer.apple.com/passkeys) ## TLDR: what are passkeys? From a technical point of view, passkeys are cryptographic key pairs created on end-user devices. Apple and Google have done a great job making these key pairs usable: * Key generation happens in secure end-user hardware. * Using passkeys is easy thanks to native browser UIs and cross-device syncing. * Passkey recovery for users is supported natively by Apple via iCloud Keychain and Google via the Google Password Manager. Passkeys come with big security upgrades compared to traditional passwords: * Access to passkeys is gated with OS-level biometrics: faceID, touchID, lock screen patterns, and so on. * Passkeys are bound to the web domain that creates them. This is important to thwart phishing attacks, where an attacker hosts a similar-looking website to steal user credentials. This is doable with passwords; impossible with passkeys. * Because passkeys rely on public key cryptography, passkeys have two components: a public key and a private key. Private keys are never disclosed to websites or apps, making them a lot harder to steal. Only public keys are sent. To authenticate, passkeys sign messages (with their private keys) and provide signatures as proofs, similar to crypto wallets. ## Isn't this similar to WebAuthn? If you know about Webauthn, congratulations: a lot of this will feel familiar. Passkeys rely on the [same web standard](https://www.w3.org/TR/webauthn-2/) and the same browser APIs: `navigator.credentials.create` and `navigator.credentials.get`. The difference? Passkeys are resident credentials and they can be synced between devices. As a result, they are **not** device-bound and can be used from any device. ## How do cross-device syncing and recovery work? Synchronization and recovery are both supported natively by Apple and Google: * With Apple, Passkeys created on one device are synced through [iCloud Keychain](https://support.apple.com/en-us/HT204085) as long as the user is logged in with their Apple ID. Apple covers both syncing and recovery in ["About the security of passkeys"](https://support.apple.com/en-us/102195). For some additional detail, see [this Q\&A with the passkey team](https://developer.apple.com/news/?id=21mnmxow). Apple's account recovery process is documented in [this support page](https://support.apple.com/en-us/HT204921). * With Google, [Google Password Manager](https://passwords.google/) syncs passkeys across devices seamlessly. Google has plans to support syncing more broadly across different operating systems, see [this support summary](https://developers.google.com/identity/passkeys/supported-environments#chrome-passkey-support-summary). Recovery is covered in [this FAQ ("What happens if a user loses their device?")](https://developers.google.com/identity/passkeys/faq#what_happens_if_a_user_loses_their_device): it relies on Google's overall [account recovery process](https://support.google.com/accounts/answer/7682439?hl=en) because passkeys are attached to Google accounts. ## OS and browser support Modern browsers have great support for passkeys. See [caniuse](https://caniuse.com/passkeys) for detailed information. Support also varies by operating system: [this matrix](https://passkeys.dev/device-support/#matrix) has detailed information about OS-level support. ## Betting on WebAuthn and Passkeys We believe **it's time to move away from passwords** so we've built 0xkey without them. When you authenticate to 0xkey you'll be prompted to create a new passkey. Authentication to 0xkey requires a passkey signature. No password needed! Next up, learn about how you can integrate passkeys into your app, [here](/authentication/passkeys/integration). # Native Passkeys Source: https://docs.0xkey.io/authentication/passkeys/native If you're unfamiliar with passkeys broadly, head to for an overview. TL;DR: passkeys are cryptographic key pairs generated and stored on secure hardware. Typically this is your Mac's or iPhone's , your Android's , or an external security key plugged in via USB. * Registration ("sign up") creates a new key pair: this is your passkey * Authentication ("sign in") uses an existing passkey to sign a message, proving ownership of the associated private key stored on your device. ## Passkeys on the web Creating and using passkeys on the web is straightforward: browsers offer APIs to do it! * `navigator.credentials.create` creates a passkey * `navigator.credentials.get` prompts the user to select a passkey to sign a message Creating and checking a passkey in the browser doesn't require a backend. An important security feature of passkeys: they're **domain-bound** to prevent phishing. In other words: passkeys created on `app.example.com` won't be usable on `evil.example.com`, for example. Browsers prevent this. ## Native platform APIs ### Android In the Android ecosystem the `CredentialManager` supports creating and using passkeys with `CreatePublicKeyCredentialRequest` and `GetCredentialRequest`. See [the associated documentation](https://developer.android.com/training/sign-in/passkeys#sign-in) for more information. ### iOS iOS APIs to create and use passkeys are available as well: * `ASAuthorizationPlatformPublicKeyCredentialProvider(…).createCredentialRegistrationRequest` for passkey creation * `ASAuthorizationPlatformPublicKeyCredentialProvider(…).createCredentialAssertionRequest` for passkey usage See [these docs](https://developer.apple.com/documentation/authenticationservices/asauthorizationplatformpublickeycredentialprovider) for more info. ### Native 0xkey SDKs For fully native apps, use the [Swift SDK](/sdks/swift) (iOS / macOS) or the [Kotlin SDK](/sdks/kotlin) (Android). Both wrap the platform passkey APIs above, stamp 0xkey requests with passkeys or session keys, and cover sign-in, wallets and signing. ## Building with React Native 0xkey has a fully-featured [TypeScript SDK](https://github.com/0xkey-io/sdk-js/). It provides a type-safe client to call the 0xkey API and abstracts activity request signing. [React Native](https://reactnative.dev/) lets you write your app in Typescript and compile it into native code for both iOS and Android automatically. To sign 0xkey requests with native passkeys in a React Native application we've released [`@0xkey-io/react-native-passkey-stamper`](https://www.npmjs.com/package/@0xkey-io/react-native-passkey-stamper), a package compatible with our TypeScript client to sign 0xkey requests with native passkeys. Under the hood this package wraps [`react-native-passkey`](https://github.com/f-23/react-native-passkey), which calls the right native APIs on [iOS](https://github.com/f-23/react-native-passkey/blob/17184a1b1f6f3ac61e07aa784c9b64efb28b570e/ios/Passkey.swift#L29) and [Android](https://github.com/f-23/react-native-passkey/blob/17184a1b1f6f3ac61e07aa784c9b64efb28b570e/android/src/main/java/com/reactnativepasskey/PasskeyModule.kt#L30C44-L30C76), and exports a unified interface that we leverage. Bottom-line: if you've used our [webauthn stamper](https://www.npmjs.com/package/@0xkey-io/webauthn-stamper) or [API key stamper](https://www.npmjs.com/package/@0xkey-io/api-key-stamper), using our React Native passkey stamper will feel familiar. Take a look at the ["Installation"](https://www.npmjs.com/package/@0xkey-io/react-native-passkey-stamper#installation) and ["Usage"](https://www.npmjs.com/package/@0xkey-io/react-native-passkey-stamper#usage) sections to get started with passkeys in your React Native application. ## Linking apps and web domains Passkeys on native apps aren't app-bound, they're **domain** bound just like web passkeys. This may come as a surprise: you'll have to configure a web domain to use passkeys natively! Configuration is done separately per ecosystem, but the idea is the same: * iOS expects a JSON file at the domain root (`/.well-known/apple-app-site-association`): see Apple's [Supporting associated domains](https://developer.apple.com/documentation/xcode/supporting-associated-domains) * Android expects a JSON file at the domain root (`/.well-known/assetlinks.json`): see Android's [Verify Android App Links](https://developer.android.com/training/app-links/verify-android-applinks) This unlocks interesting flows where users use their web-created passkeys in a "companion" native app, or vice-versa. For example: a native app linked to your `app.example.com` domain would allow users to log into their account from a native mobile app *using their web-created passkey* as long as they're synced properly. Note that these associations are "many-to-many": a website can link multiple associated apps, and a single native application can choose to create passkeys for multiple domains, via a dropdown for example. However (as far as we know) a single passkey is always bound to a single web domain: it can't be bound to multiple web domains. # Passkey options Source: https://docs.0xkey.io/authentication/passkeys/options Whether you use the raw browser APIs or one of our helpers you'll have flexibility to set your own registration and authentication options. This page provides an overview and some recommendations related to these options. ## Registration options Mozilla has good (but lengthy) documentation on each option: [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create). Below we detail the most relevant options you'll want to think about. ### `challenge` This is the challenge signed by the end-user for registration. During registration this challenge isn't meaningful so we recommend picking a random challenge. It will not be visible to users. ### `timeout` Number of seconds before "giving up". The browser will simply show a timeout popup: ![Timeout popup](https://mintcdn.com/chain/QR4qTXB1wMmR9OqI/images/passkeys/img/passkeys/timeout.png?fit=max\&auto=format\&n=QR4qTXB1wMmR9OqI\&q=85\&s=eaa28bb7c582c13cfd418e474b8654b9) This UI isn't very helpful, so we recommend making the timeout long (5 minutes). The less your users see this, the better. ### `rp` The `rp` options is an object with 2 fields: `id` and `name`. `rp.id` (aka RPID) should be your app top-level domain. For example, if your app is hosted on `https://your.app.xyz` the RPID should be `app.xyz` unless you have good reasons to do otherwise (see below). > [accordion] Reasons to set RPID to specific sub-domains > > `rp.id`, or RPID, is a way to identify the website a passkey is associated with. Once set at registration time, it **determines the set of origins on which the passkey may be be used**. The [WebAuthn spec](https://www.w3.org/TR/webauthn-2/#relying-party-identifier) states that the RPID must be a “registrable domain suffix of, or equal to” the current domain. If the page creating a passkey is hosted at `https://your.app.xyz`, the RPID can thus be "your.app.xyz" or "app.xyz". > > A passkey with RPID "your.app.xyz" **cannot** be used on `https://www.app.xyz` or `https://foo.app.xyz`. However a passkey created with RPID "app.xyz" **will** be usable on all `https://*.app.xyz` sub-domains: `https://your.app.xyz`, `https://www.app.xyz`, `https://foo.app.xyz`, and so on. Hence our general recommendation above to set `app.xyz` (top-level domain) as the RPID to maximize flexibility. > > A reason why you might want to set the RPID to "your.app.xyz" instead of "app.xyz" like recommended above is extra security: if you are worried about user passkeys being usable across all your sub-domains, it makes sense to scope passkeys to the sub-domain they're meant to be used on, and only that sub-domain. > > If you scope passkeys to a specific sub-domain, be aware that migrating your app to a different sub-domain later will require a migration process where users have to re-enroll themselves by creating new passkeys on the new sub-domain. Passkeys cannot be transferred from one RPID to another. `rp.id` is shown in the browser's initial registration prompt. `rp.name` doesn't show up in the popup so can be set to anything. We recommend setting it to the correctly capitalized name of your app, in case browsers start showing it in their native UIs in the future. ### `attestation` This option indicates whether an attestation is needed, to prove the authenticator authenticity. In general, 0xkey doesn't need attestations. Most passkeys do not produce meaningful attestations for privacy reasons. In the context of passkey integrations, you can omit this option: it will default to "none". ### `pubKeyCredParams` and `alg` The `pubKeyCredParams` is a list of supported algorithms. If you're relying on 0xkey to validate passkey signatures, this list should be: `[{alg: -7, type: "public-key"}, {alg: -257, type: "public-key"}]`. The integers `-7` and `-257` are algorithm identifiers for ES256 (aka P256) and RS256 (aka RSA), respectively. The full list of possible values is part of the [COSE standard, maintained by IANA](https://www.iana.org/assignments/cose/cose.xhtml#algorithms). Currently 0xkey only supports ES256 and RS256. ### `user` The `user` field has three sub-fields: * `id`: also known as "user handle", isn't visible to the end-user. We **strongly recommend setting this to a random value** (e.g. `const id = new Uint8Array(32); crypto.getRandomValues(id)`) to make sure a new passkey is created. Be aware: **if you accidentally set this value to an existing user handle, the corresponding passkey will be overridden!** [This section of spec](https://www.w3.org/TR/webauthn-2/#dictionary-user-credential-params) is clear on the matter: "the user handle ought not be a constant value across different accounts, even for non-discoverable credentials". * `name`: this will show up in the browser's passkey list. We recommend setting this to something the user will recognize: their email, the name of your app, or potentially leave this up to the user: * `displayName`: as far as we can tell this doesn't show up in current browser UIs. It might show up in future iterations so it's best to populate this with the same value as `name`. ### `authenticatorSelection` This option has lots of consequences for UX, and it has many sub-options, outlined below. #### `authenticatorAttachment` This option, if set, restricts the type of authenticators that can be registered. See the table below for the values this option can take and their effect on registration prompts (captured via Chrome on a MacBook Pro). | Empty (default) | `platform` | `cross-platform` | | - | - | - | | If you want broad compatibility, leave this option empty, and the browser UI will allow for both internal and external passkeys. | If set to `platform`, only internal authenticators (face ID, touch ID, and so on) can be registered. | If set to `cross-platform`, only passkeys from other devices or attached via USB are allowed. | | The browser offers both internal and external authenticators. | ![authenticatorAttachment set to platform](https://mintcdn.com/chain/SBPPOKcVznKsWQeY/images/passkeys/img/passkeys/attachment_platform.png?fit=max\&auto=format\&n=SBPPOKcVznKsWQeY\&q=85\&s=e655b2ad36378ae4339953b0f75b8813) | ![authenticatorAttachment set to cross-platform](https://mintcdn.com/chain/SBPPOKcVznKsWQeY/images/passkeys/img/passkeys/attachment_cross_platform.png?fit=max\&auto=format\&n=SBPPOKcVznKsWQeY\&q=85\&s=8807fb43833d3fb1fb6f61e282eaea54) | #### `requireResidentKey` and `residentKey` These options allow you to specify whether you want your users to create discoverable or non-discoverable credentials. See [Discoverable vs. non-discoverable](/authentication/passkeys/discoverable-vs-non-discoverable) for more information. Default values: `residentKey` is `discouraged` and `requireResidentKey` is `false`. Important note: the default for `requireResidentKey` (`discouraged`) results in different outcomes based on OS: Android devices create non-discoverable credentials whereas iOS devices create discoverable credentials. If you want to create discoverable credentials whenever possible, set `requireResidentKey` to `false` and `residentKey` to `preferred`, which work across Android and iOS devices. #### `userVerification` "User verification" refers to mechanisms on the authenticators themselves such as PIN codes or biometric/fingerprint readers. This flag can be set to: * `discouraged`: yubikey PINs won't be required even if the device technically supports it. We've found that for TouchID/FaceID, authentication will still be required however. * `preferred`: yubikey PINs and other authentication mechanisms will be required if supported, but devices without them will be accepted. * `required`: authenticators without user verification support won't be accepted. To maximize compatibility we recommend setting `userVerification` to "discouraged" or "preferred" because some authenticators do not support user verification. Due to poor yubikey PIN UX in browsers, setting `userVerification` to "discouraged" is best unless you operate with a strict security threat model where user verification makes a big difference. "preferred" is the default value if you don't specify this option. ## Authentication options Mozilla's documentation on authentication options can be found here: [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get). Luckily there are fewer authentication options than registration. ### `challenge` This is the challenge to sign with the passkey. If you're integrating with 0xkey, the challenge should be the POST body of the request to be signed. Our SDK and helpers set this automatically for you already. ### `rpId` Must match the `rp.id` option during passkey registration. Passkeys are domain bound, so it's not possible to use a passkey registered with `rp.id` set to "foo.com" and use it on "bar.com". This is a core anti-phishing counter-measure. ### `allowCredentials` List of objects restricting which credentials can be used during authentication. This is crucial to specify if you're using [non-discoverable credentials](/authentication/passkeys/discoverable-vs-non-discoverable#non-discoverable-credentials) or if you want to tailor browser prompts to the right type of transport. Each object in this list has an ID (the credential ID) and a list of transports (e.g. "hybrid", "internal", "usb", etc). The `transports` list is **optional** but results in better, more targeted prompts. For example, here are screenshot of targeted prompts captured on Chrome, on a MacBook laptop: | `transports: ["internal"]` | `transports: ["usb"]` | `transports: ["hybrid"]` | | - | - | - | | The browser goes straight to the device's built-in authenticator. | ![authentication prompt with transports: usb](https://mintcdn.com/chain/QR4qTXB1wMmR9OqI/images/passkeys/img/passkeys/transport_usb.png?fit=max\&auto=format\&n=QR4qTXB1wMmR9OqI\&q=85\&s=c3b18070912addaaaec870f79056bbad) | ![authentication prompt with transport: hybrid](https://mintcdn.com/chain/QR4qTXB1wMmR9OqI/images/passkeys/img/passkeys/transport_hybrid.png?fit=max\&auto=format\&n=QR4qTXB1wMmR9OqI\&q=85\&s=39733b98a7ca760cf4504710bbad3702) | The credential ID needs to be passed as a buffer but is returned from registration as a base64-encoded value: make sure to decode it (in JavaScript: `Buffer.from(storedCredentialId, "base64")`) to avoid issues. If the wrong credential ID is specified, `transports: ["internal"]` is set, browsers error right away because they can enumerate internal credentials. Chrome, for example, displays the following error: ![Chrome error when no matching passkey has been found for the provided Credential ID](https://mintcdn.com/chain/QR4qTXB1wMmR9OqI/images/passkeys/img/passkeys/no_passkey_available.png?fit=max\&auto=format\&n=QR4qTXB1wMmR9OqI\&q=85\&s=621b6300f163d046a7e409168fda3f60) However, if the wrong credential ID is specified without `transports` set (or with other-than-internal `transports` set), browsers won't error right away because they can't enumerate external credentials. They will display an error once the user has pressed their security key or gone through the cross-device passkey flow: ![Chrome error when the credential ID used by the user is not in the allowCredentials list](https://mintcdn.com/chain/QR4qTXB1wMmR9OqI/images/passkeys/img/passkeys/wrong_credential_id.png?fit=max\&auto=format\&n=QR4qTXB1wMmR9OqI\&q=85\&s=aebb745ef18f421c7c554ec3c5e5f0ab) ### `attestation` See [`attestation`](#attestation) above. ### `timeout` See [`timeout`](#timeout) above. ### `UserVerification` See [`UserVerification`](#userverification) above. # Proxying signed requests Source: https://docs.0xkey.io/authentication/proxying-signed-requests 0xkey has an open CORS policy for its public API. This means your frontend can choose to POST sign requests straight to `https://api.0xkey.io`. Your frontend can also choose to forward the requests via a backend server (which POSTs the signed request to 0xkey). How should you decide what to do? Here are some considerations: * A backend proxy can be useful if you need to inspect and persist activity results. For example: if your users are creating wallets, you might want to persist the addresses. If your users are signing transactions, you might want to broadcast on their behalf. * Another reason why a backend server could be beneficial is monitoring, feature toggles, and validation: with a proxy you're able to control which requests are proxied and which aren't. You can also perform additional validation before signed requests are forwarded to 0xkey. * POSTing signed requests directly from your app frontend to 0xkey saves you the burden of running a proxy server, and takes you out of the loop so that your end-users interact directly with 0xkey. This is a "hands-off" approach that can work well if you want to give your end-users maximum flexibility and ownership over their sub-organization. # Sessions Source: https://docs.0xkey.io/authentication/sessions 0xkey sessions allow a user to take multiple, contiguous actions in a defined period of time. ## What is a session? Such actions can be divided into two buckets: * Read operations: Retrieving data (e.g., viewing wallet balances) * Write operations: Modifying data or performing sensitive actions (e.g., signing transactions) ## How can I create a session? ### Read-only sessions In terms of end-user experience, a read-only session might make sense in low-touch applications where users are primarily reading data (think viewing wallets and their balances). As for implementation, there are a few ways a developer can achieve read-only access on behalf of a user. Note: an end-user (sub-organization) falls hierarchically under the developer (parent-organization). #### Parent organization access By default, a parent organization has read access to all of its sub-organizations’ data. This means you can set up a federated model where the client makes requests to a backend (containing the parent organization’s API key credentials), the backend populates the requested data, and returns it back to the client. From an implementation perspective, each read request (i.e. `get` or `list`) requires an `organizationId` parameter. Populate that field with the sub-organization’s ID in order to get its data. #### Client side access Separately, if you would like the client to have all read requests encapsulated (instead of reading data via a proxy like in the previous approach), the client can initiate a read-only session via a [CreateReadOnlySession activity](/api-reference/activities/create-read-only-session). This activity returns a session string that, if passed into an HTTP request via `X-Session` header, gives permission to perform reads. Note that because this is an activity performed by an end user, it still requires authentication (for example, via passkey). 0xkey’s current SDKs, including `@0xkey-io/react-wallet-kit` and `@0xkey-io/core`, do not support read-only sessions. These SDKs are designed around cryptographically stamped, read-write sessions and do not expose the divergent request paths required for token-based read-only authentication. If you need read-only session support, interact with the 0xkey API directly and attach the session token to requests manually via the `X-Session` header. For most applications, read-write sessions are recommended. By default, a parent organization already has read access to all of its sub-organizations’ data, allowing clients to fetch read-only data via a backend using the parent organization’s API credentials, without requiring a separate read-only client session. ### Read-write sessions In contrast to read-only sessions, a read-write session makes sense when a user would like to make several authenticated write requests in a window of time. There are a few ways to achieve this: #### Creating a read-write session There are several mechanisms to obtain read-write sessions: OTP, OAuth, Passkey sessions, and Session refreshing ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant User as Target user (authorizing) participant API as 0xkey Note left of User: Creates a new P-256 key client-side
(IndexedDB or SecureStorage) User->>API: OTP_LOGIN / OAUTH_LOGIN / STAMP_LOGIN
(with the client-side public key) Note right of API: Adds the public key to the sub-org and
returns a signed session JWT (user,
expiration, client public key) API-->>User: Signed session JWT Note left of User: Stores the session JWT User->>API: Requests signed with the client-side key ``` Our SDK contains several abstractions that manage authentication. You can checkout all of our examples leveraging these examples [here](https://github.com/0xkey-io/sdk-js/tree/main/examples) **Note:** The session JWT is only metadata signed by 0xkey that references the client side stored API keypair, and is useful for verifying the session server-side or associating metadata, but it cannot be used to authenticate requests to 0xkey’s API. Only the session keypair can be used to create valid `x-stamp` signatures for API requests to 0xkey. In other words, solely the session JWT cannot be used to stamp requests outside of the client context. ### Mechanisms There are two primary mechanisms we offer that provide client side key generation and signing to support read-write sessions. #### IndexedDB (web only): For web apps that want stronger session persistence without relying on iframes or exposing credentials to your app’s JavaScript runtime, 0xkey supports using the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) API to generate unextractable asymmetric key pairs and store them securely in the browser’s IndexedDB. This approach enables long-lived, client-held sessions that survive page reloads, tab closures, and even browser restarts – **without ever exposing the private key** to your JavaScript code. 0xkey’s SDK provides helpers to: * Create a new session by generating a P-256 key pair via `crypto.subtle.generateKey()` * Sign requests * Store and retrieve the key using IndexedDB under a given session ID * Abstractions built on top of the `IndexedDBStamper` that simplify authentication flows This is currently the **most persistent** session model for modern browsers that support WebCrypto. It is especially valuable in Progressive Web App (PWA) contexts or when iframe and Local Storage approaches are insufficient. To see the IndexedDB-backed session mechanism in action, check out our 0xkey react-wallet-kit [playground](https://github.com/0xkey-io/sdk-js/tree/main/examples/with-sdk-js) or dedicated authentication examples like [oauth](https://github.com/0xkey-io/sdk-js/tree/main/examples/oauth), [email OTP](https://github.com/0xkey-io/sdk-js/tree/main/examples/otp-auth), and [external wallet authentication](https://github.com/0xkey-io/sdk-js/tree/main/examples/wallet-auth). Our [Web demo application](https://github.com/0xkey-io/demo-embedded-wallet) showcases complete end-to-end authentication flows and client-side session persistence backed by IndexedDB. #### SecureStorage (mobile only) Secure Storage operates essentially the same as IndexedDB with respect to authentication flows for 0xkey except it is mobile native and keys are generated using @0xkey-io/crypto rather than WebCrypto. #### LocalStorage: Another option is to create an API key and store it directly within Local Storage. However, this is a riskier setup than IndexedDb/SecureStorage as anyone who is able to access this client-side API key has full access to a User. ### Sessions FAQ > [accordion] How can I refresh a session? > > Once a user has a valid session, it is trivial to use that session to create a new session. The `refreshSession` abstraction will create a brand new session and automatically store the resulting new session in local storage. > [accordion] How can I delete a session? > > In order to delete a session, simply remove all user-related artifacts from Local Storage. > > ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} > /** > * Clears out all data pertaining to a user session. > * > * @returns {Promise} > */ > logout = async (): Promise => { > await removeStorageValue(StorageKeys.Client); > await removeStorageValue(StorageKeys.Session); > return true; > }; > ``` > [accordion] How long are sessions? > > The expiration of session keys can be specified to any amount of time using the `expirationSeconds` parameter. The default length is 900 seconds (15 minutes). > [accordion] How many session keys can be active at once? > > A user can have up to 10 expiring API keys at any given time. If you create an expiring API key that exceeds that limit, 0xkey automatically deletes one of your existing keys using the following priority: > > * Expired API keys are deleted first > * If no expired keys exist, the oldest unexpired key is deleted > If you are looking to invalidate existing sessions, you can use the `invalidateExisting` parameter for all `_LOGIN` activities. This will clear all existing session keys. > [accordion] Can I use the same sessions implementation for web and mobile? > > Absolutely! Through leveraging IndexedDb you can handle sessions in the same way for Web and PWAs. However, for React Native/Mobile applications you will need to leverage Secure Storage. # SMS authentication Source: https://docs.0xkey.io/authentication/sms SMS authentication enables users to authenticate their 0xkey account using their phone number via a 6-9 digit or bech32 alphanumeric one-time password (OTP). When authenticated, users receive an expiring API key stored in memory within an iframe, which functions like a session key to access their wallet. > [!WARNING] > > **Phase 1 status — Partial.** The OTP API paths (`otp_init` with `OTP_TYPE_SMS`, `otp_verify`, `otp_login`) exist and are compatible with the Auth Proxy, but **no real SMS provider is wired in Phase 1** — outbound SMS delivery, templates, rate limits, and delivery-attempt tracking are **Coming soon**. Use [Email OTP](/authentication/email) or [Passkeys](/authentication/passkeys/introduction) for production integrations today. See the [Roadmap](/0xkey/roadmap). ## Access and pricing SMS authentication is **Partial** in Phase 1: the OTP API paths exist, but no real SMS provider is wired yet. To discuss future Enterprise SMS access, contact [hello@0xkey.io](mailto:hello@0xkey.io). SMS pricing is usage-based and varies depending on the country of the destination phone number and the carrier. Prices are shown in U.S. cents per outbound SMS message segment. Taxes/surcharges separate. Select your country below to view pricing. Select Your Country To View Pricing Select Country Cost 0.000¢ ## Prerequisites Make sure you have set up your primary 0xkey organization with at least one API user that can programmatically initiate OTP and create sub-organizations. Check out our [Quickstart guide](/getting-started/quickstart) if you need help getting started. To allow an API user to initiate email auth, you'll need the following policy in your main organization: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "effect": "EFFECT_ALLOW", "consensus": "approvers.any(user, user.id == '')", "condition": "(activity.resource == 'AUTH' && activity.action == 'CREATE') || (activity.resource == 'OTP' && activity.action == 'CREATE') || (activity.resource == 'OTP' && activity.action == 'VERIFY') || (activity.resource == 'ORGANIZATION' && activity.action == 'CREATE')" } ``` ## How it works SMS authentication uses three activities: 1. `INIT_OTP_V3` — initiates a secure OTP flow and sends a 6–9 digit or alphanumeric OTP to the specified phone number. The response includes an `otpEncryptionTargetBundle` which is used in OTP verification. 2. `VERIFY_OTP_V2` — securely verifies the code and returns a signed verificationToken JWT 3. `OTP_LOGIN_V2` — validates the verificationToken and returns a session (signed with the verification token key) > [!NOTE] > > If you are migrating from a legacy OTP flow to the new updated flow, check out the [OTP Migration Guide](/authentication/otp-migration-guide) for details on required changes. ## Implementation ### Initiating SMS authentication The flow begins with a new activity of type `ACTIVITY_TYPE_INIT_OTP_V3` using the parent organization id with these parameters: * `otpType`: specify `"OTP_TYPE_SMS"` * `contact`: user's phone number * `emailCustomization`: optional parameters for customizing emails * `userIdentifier`: optional parameter for rate limiting SMS OTP requests per user. We recommend generating this server-side based on the user's IP address or public key. See the [OTP Rate Limits](#otp-rate-limits) section below for more details. * `alphanumeric`: optional parameter for making this code bech32 alphanumeric or not. default: true * `otpLength`: optional parameter for selecting the length of the OTP. default: 9 * `expirationSeconds`: optional validity window (defaults to 5 minutes) #### One-time password sandbox environment To test OTP codes in our sandbox environment you can use the following: * `alphanumeric` must be set to `false` * `otpLength` must be set to `6` * Phone Number: +1 999-999-9999 * OTP Code: `000000` In the sandbox environment, SMS delivery is simulated. Use the fixed OTP code `000000` (with the returned otpId) when calling `ACTIVITY_TYPE_VERIFY_OTP_V2` with the parent organization ID to obtain a verificationToken JWT: * `otpId`: ID from the init activity * `encryptedOtpBundle`: bundle generated using the otpEncryptionTargetBundle received during `ACTIVITY_TYPE_INIT_OTP_V3` and contains the 6-9 digit or alphanumeric code received via SMS, and the public key of a client-side generated keypair. * `expirationSeconds`: optional validity window (defaults to 1 hour) After receiving the verification token, users complete OTP authentication flow with `ACTIVITY_TYPE_OTP_LOGIN_V2` using the sub-organization ID associated with the contact from the first step: * `publicKey`: public key to add to organization data associated with the signing key in IndexedDB or SecureStorage. * `verificationToken`: JWT returned from successful `VERIFY_OTP` activity * `clientSignature`: This proves authorization for the verification token being used, and is generated using the keypair whose public key was provided in the `encryptedOtpBundle` during verification. * `expirationSeconds`: optional validity window (defaults to 15 minutes) * `invalidateExisting`: optional boolean to invalidate previous login sessions > [!NOTE] > > If you are migrating from a legacy OTP flow to the new updated flow, check out the [OTP Migration Guide](/authentication/otp-migration-guide) for details on required changes. ## Authorization SMS authentication requires proper permissions through policies or parent organization status. ## Enabling/disabling SMS auth ### For top-level organizations SMS authentication is disabled by default. Enable it using `ACTIVITY_TYPE_SET_ORGANIZATION_FEATURE`: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} 0xkey request --host api.0xkey.io --path /public/v1/submit/set_organization_feature --body '{ "timestampMs": "'"$(date +%s)"'000", "type": "ACTIVITY_TYPE_SET_ORGANIZATION_FEATURE", "organizationId": "", "parameters": { "name": "FEATURE_NAME_SMS_AUTH" } }' --organization ``` ### For sub-organizations * SMS auth is enabled by default * Disable during creation using `disableSmsAuth: true` in the `CreateSubOrganizationIntentV7` activity * Disable after creation using `ACTIVITY_TYPE_REMOVE_ORGANIZATION_FEATURE` with feature name `FEATURE_NAME_SMS_AUTH` ## Implementation notes * Users are limited to 10 long-lived API keys and 10 expiring API keys * When the expiring API key limit is reached, the oldest key is automatically discarded ## OTP rate limits In order to safeguard users, 0xkey enforces rate limits for OTP auth activities. If a `userIdentifier` parameter is provided, the following limits are enforced: * 3 requests per 3 minutes per unique `userIdentifier` * 3 retries max per code, after which point that code will be locked * 3 active codes per user, each with a 5 minute TTL # Social logins Source: https://docs.0xkey.io/authentication/social-logins Social logins provide a familiar and convenient way for users to access applications using their existing accounts from popular platforms like Google, Apple, Facebook, X/Twitter, etc. Under the hood, this functionality is powered by OAuth - a robust auth protocol which enables secure user verification through OpenID Connect ([OIDC](https://openid.net/specs/openid-connect-core-1_0.html)) tokens. This feature is available exclusively for sub-organization users. > [!NOTE] > > **Google** and **Apple** OIDC are the most extensively validated built-in providers end-to-end. Other built-in providers (Facebook, X/Twitter, Discord, Auth0, Cognito, …) and self-hosted enterprise IdPs are supported through [`CREATE_OAUTH_PROVIDERS`](/api-reference/activities/create-oauth-providers) and — for issuers you operate yourself — the [Custom OIDC Providers](#custom-oidc-providers-your-own-identity-provider) registry below. Every identity bound this way is cryptographically re-verified inside the enclave (signature, issuer, audience, expiry) before it's persisted; nothing is trusted at face value. Similar to [email auth](/authentication/email), social login authentication is ideal for users who prefer not to manage API keys or [passkeys](/authentication/passkeys/introduction) directly. This makes it particularly well-suited for onboarding users who are comfortable with traditional web2-style accounts but may be unfamiliar with cryptographic keys and credentials. An example implementing social login authentication for an organization can be found in our SDK repo [here](https://github.com/0xkey-io/sdk-js/tree/main/examples/oauth). ## Types of social login providers 0xkey supports two different types of Social Login Providers: 1. **OIDC Providers** (Google, Apple, Auth0, Cognito…) These providers issue your app an **OIDC ID Token** identifying an end-user, which can subsequently be passed to 0xkey as a means of authentication. 2. **OAuth 2.0-Only Providers** (X/Twitter, Discord…) These providers do *not* issue **OIDC ID Tokens** themselves, and instead provide only bare-bones OAuth 2.0. To work around this limitation, 0xkey runs the **OAuth 2.0 Authorization Code + PKCE** flow, calls the provider’s `who-am-I` endpoint using your app's credentials, and then uses the returned user data to **issue a short-lived OIDC ID token**. In effect, 0xkey acts as an "*OIDC Wrapper*" for these OAuth 2.0 Services. While the backend flows associated with these two types of Providers differ upstream of **OIDC ID Token** generation, they converge at that point and have no downstream differences. In both cases, the goal is to get an **OIDC ID Token** identifying the end user. ### Social login provider types - comparison The table below can be helpful in understanding the similarities and differences between the two types of Social Login Providers that 0xkey supports: | **Provider Type** | **OIDC Provider** | **OAuth 2.0-Only Providers** | | - | - | - | | Providers | Google, Apple, Facebook, Auth0, Cognito | X/Twitter, Discord | | Token Transport | Returned to your App by Provider | Returned by 0xkey after the **OAuth 2.0 Auth Code + PKCE** flow | | Issuer (`iss`) | Provider (iss = Provider URL) | 0xkey (iss = 0xkey URL) | | Audience (`aud`) | Provider’s `client_id` for your app | Provider’s `client_id` for your app | | Subject (`sub`) | Provider’s subject (stable user ID) | Derived from ID `who-am-I` response (e.g., `x:123456789`) | | Nonce (`nonce`) | Sent to Provider; echoed in ID token | Sent to 0xkey; echoed in ID token. | | Refresh/access | If the Provider returns them, you may use them | Not provided. | ## Roles and responsibilities * **0xkey**: Runs verifiable infrastructure to create credentials, verify OIDC tokens and, in the case of **OAuth 2.0-Only Providers**, issue them as well. * **Parent**: That's you! **For the rest of this guide we'll assume you, the reader, are a 0xkey customer**. We assume that you have: * An existing 0xkey organization (we'll refer to this organization as "the parent organization") * A web application frontend (we'll refer to this as just "app" or "web app") * A backend able to sign and POST 0xkey activities ("backend" or "parent backend") * **End-User**: The end-user is a user of your web app. They have an account with Google. * **OIDC Provider**: A provider able to authenticate your End-Users and provide OIDC tokens as proof. We'll use [Google](https://developers.google.com/identity/openid-connect/openid-connect) as an example. * **OAuth 2.0-Only Provider**: A provider of OAuth 2.0-based Authorization, for which 0xkey is able to act as an "*OIDC Wrapper*". ## Authentication sequence diagrams The sequence diagrams below display the differing flows for the two types of Social Login Providers. ### OIDC provider ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant User participant Frontend participant OAuth Provider participant Backend participant 0xkey Frontend->>Frontend: Create API keypair User->>Frontend: Clicks "Log in with " Frontend->>OAuth Provider: Start OAuth flow with nonce=sha256(API publicKey) OAuth Provider->>User: Prompt to grant permission User->>OAuth Provider: Grants permission OAuth Provider->>Frontend: Return oidcToken Frontend->>Backend: Send oidcToken + API publicKey Backend->>0xkey: Gets subOrgIds with that associated oidcToken 0xkey->>Backend: Return subOrgId (or null) alt SubOrgId not found Backend->>0xkey: Create sub-org using oidcToken 0xkey->>Backend: Return new subOrgId end Backend->>0xkey: Call oauth_login with oidcToken, API publicKey 0xkey->>Backend: Return session JWT Backend->>Frontend: Return session JWT ``` **1. Create API Key** The frontend generates an API keypair before starting the OAuth login flow. This keypair will later become the session keypair once the user is authenticated via 0xkey. **2. Start the OAuth Login Flow** The user begins the login process by clicking "Log in with \" on the frontend. **3. Initiate OAuth with Nonce** When starting the OAuth request to the provider, the frontend sets the `nonce` to `sha256(publicKey)` based on the API public key. This binds the resulting OIDC token to the keypair. **4. User Grants Permission** The OAuth provider prompts the user to grant permission to share their identity. Once approved, the OAuth provider returns an `oidcToken` to the frontend. **5. Send Credentials to Backend** The frontend sends the `oidcToken` and API public key to your backend. **6. Get or Create a 0xkey Sub-organization** The backend gets subOrgIds that are associated with that `oidcToken`. If no sub-organization exists, it creates one using the identity in the token. **7. Create a Session** The backend calls `oauth_login` with the `oidcToken`, and API public key. 0xkey validates that the token’s `nonce` matches `sha256(publicKey)` and returns a session JWT. The backend sends this JWT to the frontend. **8. You're Now Authenticated** Your frontend now treats the API keypair as the session keypair. It can use the private key to sign requests to 0xkey using the `x-stamp` header. ### OAuth 2.0-only provider ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant User participant Frontend participant OAuth Provider participant Backend participant 0xkey User->>Frontend: Clicks "Log in with " Frontend->>OAuth Provider: Start OAuth flow OAuth Provider->>User: Prompt to grant permission User->>OAuth Provider: Grants permission OAuth Provider->>Frontend: User redirected to redirect_uri and delivered auth_code Frontend->>Backend: User calls with redirect_uri and auth_code Backend->>0xkey: Send auth_code + redirect_uri via `OAuth2Authenticate` call 0xkey->>Backend: Return OIDC Token Backend->>0xkey: Gets subOrgIds with that associated oidcToken 0xkey->>Backend: Return subOrgId (or null) alt SubOrgId not found Backend->>0xkey: Create sub-org using oidcToken 0xkey->>Backend: Return new subOrgId end Backend->>0xkey: Call oauth_login with oidcToken, API publicKey 0xkey->>Backend: Return session JWT Backend->>Frontend: Return session JWT ``` **1. Create API Key** The frontend generates an API keypair before starting the OAuth login flow. This keypair will later become the session keypair once the user is authenticated via 0xkey. **2. Start the OAuth Login Flow** The user begins the login process by clicking "Log in with \" on the frontend. **3. Initiate OAuth** The frontend initiates the OAuth Authentication flow with the provider. **4. User Grants Permission** The OAuth provider prompts the user to grant permission to share their identity. Once approved, the OAuth provider returns an `oidcToken` to the frontend. **5. Provider Delivers auth_code** The provider delivers a short-lived auth_code via the redirect_uri. **6. Get OIDC Token** The backend exchanges the auth_code + redirect_uri for an OIDC ID Token using the `OAuth2Authenticate` activity. **7. Get or Create a 0xkey Sub-organization** The backend gets subOrgIds that are associated with that `oidcToken`. If no sub-organization exists, it creates one using the identity in the token. **8. Create a Session** The backend calls `oauth_login` with the `oidcToken`, and API public key. The backend sends this JWT to the frontend. NOTE: For this flow, the `nonce` is *not* required to match `sha256(publicKey)`. **9. You're Now Authenticated** Your frontend now treats the API keypair as the session keypair. It can use the private key to sign requests to 0xkey using the `x-stamp` header. ## What does 0xkey use from the OIDC tokens to prove identity? 0xkey parses and validates the following fields from the OIDC token to confirm the user's identity: * `issuer` (iss) – The OAuth provider that issued the token (e.g., `https://accounts.google.com`) * `audience` (aud) – The OAuth app’s client ID * `subject` (sub) – The unique identifier for the user in the OAuth provider's system **Note:**\ Some OAuth providers (like Google) encourage you to register separate client IDs for each platform (e.g., web, iOS, Android). However, as discussed above, in the 0xkey flow the `aud` claim from the OIDC token is used as part of how sub-organizations are identified. If a user logs in on one platform using the web client ID, and then later logs in on another platform using a different iOS client ID, the two tokens will have different `aud` values. Because of this, 0xkey will not consider them the same identity. To ensure users are recognized consistently across platforms, you must use the same OAuth client ID everywhere. In most cases, this means using your web client ID for web, iOS, and Android flows. ## OIDC token verification All OIDC tokens are verified inside of 0xkey's [secure enclaves](/security/secure-enclaves). We've designed a new secure enclave to fetch TLS content securely and bring [non-repudiation](https://en.wikipedia.org/wiki/Non-repudiation#In_digital_security) on top of TLS content: our TLS fetcher returns a URL and the fetched content, signed by the TLS fetcher's quorum key. By trusting the TLS fetcher quorum key, other 0xkey enclaves can bring TLS-fetched data into their computation safely. Verifying OIDC token is the first computation which requires this! To verify an OIDC token, other 0xkey enclaves receive the OIDC token as well as: * the signed content of the issuer's OpenId configuration. OpenId configuration **must** be hosted under `/.well-known/openid-configuration` for each domain. For Google for example, the issuer configuration is at [`accounts.google.com/.well-known/openid-configuration`](https://accounts.google.com/.well-known/openid-configuration). This JSON document contains, among other thing, a `jwksUri` key. The value for this key is a URL hosting the list of currently-valid OIDC token signers. * the signed content of the issuer's `jwksUri` (e.g., for Google, the `jwksUri` is [`googleapis.com/oauth2/v3/cert`](https://www.googleapis.com/oauth2/v3/certs)). This is a list of public keys against which the secure enclave can verify tokens. Note: **these public keys rotate periodically** (every \~6hrs), hence it's not possible to hardcode these public keys in our secure enclave code directly. We have to fetch them dynamically! With all of that, an enclave can independently verify an OIDC token without making outbound requests. Once the token is parsed and considered authentic, our enclaves match the `iss`, `aud` and `sub` attributes against the registered OAuth providers on the 0xkey sub-organization. We also check `exp` to make sure the OIDC token is not expired, and the `nonce` attribute (see next section). ## Nonce restrictions in OIDC tokens Our [`OAUTH_LOGIN`](https://docs.0xkey.io/api-reference/activities/login-with-oauth) activity requires 2 parameters minimum: * `oidcToken`: the base64 OIDC token * `publicKey`: the client-side public key generated by the user In order to prevent OIDC tokens from being used against multiple public keys, our enclaves parse the OIDC token and, as part of the validation logic, enforce that the `nonce` claim is set to `sha256(publicKey)`. For example, if the public key is `0394e549c71fa99dd5cf752fba623090be314949b74e4cdf7ca72031dd638e281a`, our enclaves expect the OIDC token nonce to be `1663bba492a323085b13895634a3618792c4ec6896f3c34ef3c26396df22ef82`. This restriction only applies during **authentication** (`OAUTH` activity). Registration via `CREATE_OAUTH_PROVIDER` and `CREATE_SUB_ORGANIZATION` activities is not affected since these activities do not accept a `publicKey` and do not return encrypted credentials as a result. If your OAuth provider does not allow you to customize `nonce` claims, 0xkey also accepts and validates `tknonce` claims. This is an alternative claim that will be considered. Only one of (`nonce`, `tknonce`) needs to be set to `sha256(publicKey)`; not both. ## OAuth vs. OIDC [OAuth2.0](https://datatracker.ietf.org/doc/html/rfc6749) is a separate protocol from [OIDC](https://openid.net/specs/openid-connect-core-1_0.html), with distinct goals: * "OAuth2.0" is an authorization framework * "OIDC" is an authentication framework We chose to name this feature "OAuth" because of the term familiarity: most 0xkey customers will have to setup an "OAuth" app with Google, and the user experience is often referred to as "OAuth" flows regardless of the protocol underneath. ## OIDC providers Below, some details and pointers about specific providers we've worked with before. If yours isn't listed below it does not mean it can't be supported: any OIDC provider should work with 0xkey's OAuth. ### Google This provider is extensively tested and supported. We've integrated it in our open-source [demo wallet](https://github.com/0xkey-io/demo-embedded-wallet), along with Apple and Facebook: ![OAuth demo wallet](https://mintcdn.com/chain/d2Wj9s7maL6f08Ct/images/authentication/img/oauth_demo_wallet.png?fit=max\&auto=format\&n=d2Wj9s7maL6f08Ct\&q=85\&s=459446f41ee32784fe29e8ba2dcf1bda) The code is open-source, feel free to [check it out](https://github.com/0xkey-io/demo-embedded-wallet) for reference. See [`src/components/auth.tsx`](https://github.com/0xkey-io/demo-embedded-wallet/blob/main/src/components/auth.tsx) for how OAuth providers are wired in the landing page. The main documentation for Google OIDC is available [here](https://github.com/0xkey-io/demo-embedded-wallet/blob/bf0e2292cbd2ee9cde6b241591b077fadf7ee71b/src/components/auth.tsx#L157). ### Apple Apple integration is also extensively tested and supported, and is integrated into our open-source [demo wallet](https://github.com/0xkey-io/demo-embedded-wallet). The code provides an [example component](https://github.com/0xkey-io/demo-embedded-wallet/blob/bf0e2292cbd2ee9cde6b241591b077fadf7ee71b/src/components/apple-auth.tsx) as well as an [example redirect handler](https://github.com/0xkey-io/demo-embedded-wallet/blob/bf0e2292cbd2ee9cde6b241591b077fadf7ee71b/src/app/\(landing\)/oauth-callback/apple/page.tsx). Documentation for Apple OIDC can be found [here](https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple). ### Facebook Facebook OIDC requires a [manual flow with PFKE](https://developers.facebook.com/docs/facebook-login/guides/advanced/oidc-token/) (Proof for Key Exchange). This flow requires a few extra steps compared with Apple or Google. Specifically: * You will need to generate a **code verifier** that can either be recalled (e.g. from a database) or reassembled in a later request. * You will need to provide a **code challenge** as a parameter of the OAuth redirect that is either the code verifier itself or the hash of the code verifier. * Instead of receiving the OIDC token after the OAuth flow, you will receive an **auth code** that must be exchanged for an OIDC token in a subsequent request. The code verifier and your app's ID are also required in this exchange. In our example demo wallet, we opt to avoid using a database in the authentication process and instead generate our verification code serverside using the hash of a nonce and a secret salt value. The nonce is then passed to and returned from the Facebook API as a **state** parameter (see [the API spec](https://developers.facebook.com/docs/facebook-login/guides/advanced/oidc-token/) for details). Finally, the server reconstructs the verification code by re-hashing the nonce and the the salt. The full flow is displayed below: ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} sequenceDiagram participant API as 0xkey participant Parent as Parent (backend) participant App participant User participant FB as Facebook API User->>App: Visits App->>Parent: Request / server action Note left of Parent: Generates a nonce, hashes it with a salt
to get the verifier, and hashes the
verifier to get the code challenge Parent-->>App: Code challenge, nonce App->>User: Redirect (client ID, code challenge, state=nonce) User->>FB: Facebook login FB-->>User: Auth code, state User->>App: Auth code, state App->>Parent: Request / server action (nonce from state) Note left of Parent: Reassembles the verifier by
hashing the nonce with the salt Parent->>FB: Client ID, auth code, verifier FB-->>Parent: OIDC token Parent-->>App: OIDC token App-->>API: Continue with the 0xkey flow from the Google example ``` Code for the [redirect component](https://github.com/0xkey-io/demo-embedded-wallet/blob/bf0e2292cbd2ee9cde6b241591b077fadf7ee71b/src/components/facebook-auth.tsx), [OAuth callback](https://github.com/0xkey-io/demo-embedded-wallet/blob/bf0e2292cbd2ee9cde6b241591b077fadf7ee71b/src/app/\(landing\)/oauth-callback/facebook/page.tsx), and [code exchange](https://github.com/0xkey-io/demo-embedded-wallet/blob/bf0e2292cbd2ee9cde6b241591b077fadf7ee71b/src/actions/0xkey.ts#L54) are all available in the example wallet repo. If you prefer to use a database such as Redis instead of reassembling the verification code, you can store the verification code and retrieve it in the exchange stage using a lookup key either passed as **state** or stored in local browser storage. ### Auth0 This provider was tested successfully and offers a wide range of authentication factors and integration. For example, Auth0 can wrap Twitter's auth or any other ["Social Connection"](https://marketplace.auth0.com/features/social-connections). In the testing process we discovered that Auth0 admins can manage users freely. Be careful about who can and can't access your Auth0 account: Auth0's management APIs allow for account merging. Specifically, anyone with a `users:update` scope token can call [this endpoint](https://auth0.com/docs/api/management/v2/users/post-identities) to arbitrarily link an identity. For example, if a Google-authenticated user (OIDC token `sub` claim: `google-oauth2|118121659617646047510`) gets merged into a Twitter-authenticated user (OIDC token `sub` claim: `twitter|47169608`), the OIDC token obtained by logging in through Google post-merge will be `twitter|47169608`. This can be surprising and lead to account takeover if an Auth0 admin is malicious. This is documented in Auth0's own docs, [here](https://auth0.com/docs/manage-users/user-accounts/user-account-linking#precautions). ### AWS Cognito Amazon Cognito supports the standard OIDC nonce parameter — you can supply a custom nonce value in the `/oauth2/authorize` request and Cognito will include it in the resulting ID token (as per [AWS documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html)). ## Custom OIDC providers: your own identity provider > [!NOTE] > > This is **OIDC Federation**: it lets a parent organization register its *own* OIDC Identity Provider (an internal auth service, Auth0/Cognito tenant, or any standards-compliant IdP) as a trusted issuer for its sub-organization users — distinct from the built-in social providers described above. It's the recommended long-term path for customers with an existing user system who want to keep their own IdP as the source of truth for identity while still getting cryptographically-verified, non-custodial logins into 0xkey. > > For a step-by-step walkthrough (register issuer → mint token → onboard/bind users) plus a dedicated troubleshooting section, see the [**OIDC Federation** integration guide](/authentication/oidc-federation). Every OIDC token 0xkey verifies — whether from Google, Apple, or a customer's own IdP — must have its `(issuer, audience)` pair pre-registered as trusted. Built-in social providers (Google, Apple, …) are trusted by default. For any other issuer, including your own IdP, you must register it first with `CREATE_OIDC_PROVIDER`. This is an **org-level, root-quorum-only** operation: it establishes trust for the whole (parent) organization, not a single user. > [!WARNING] > > Registering an issuer is a trust decision, not a convenience setting. Anyone who can mint a validly-signed token for a registered `(issuer, audience)` pair can log in as — or bind an identity to — any sub-organization user whose IdP matches. Only grant `CREATE_OIDC_PROVIDER`/`UPDATE_OIDC_PROVIDER`/`DELETE_OIDC_PROVIDER` to root-quorum admins, and keep the registered audience list as narrow as possible (see [fail-closed audiences](#fail-closed-no-wildcard-trust) below). ### Prerequisites for your IdP Your Identity Provider must expose the standard OIDC discovery surface — 0xkey's enclave fetches these live (through the same TLS Fetcher used for social logins) rather than trusting a cached copy: * **OIDC Discovery**: `https:///.well-known/openid-configuration`, returning at minimum `issuer` and `jwks_uri`. * **JWKS**: a live, HTTPS-hosted key set at the discovered `jwks_uri`. 0xkey enforces full public-CA TLS validation with no self-signed/dev bypass — there is no way to register an issuer served over plain HTTP or with a private CA. * **Key rotation**: when you rotate signing keys, publish the new key *and* keep the previous key in the JWKS for a grace period (0xkey has no rotation-schedule concept of its own — it simply trusts whatever the JWKS currently serves). Dropping the old key immediately invalidates any token signed with it that's still in flight. * **Stable `sub`**: the `sub` claim must be a stable, non-reassignable identifier for the user. If your IdP allows account merging or `sub` reassignment (see the [Auth0](#auth0) caveat above), review that flow carefully — `(iss, sub)` is 0xkey's identity primary key. ### Registering an issuer ```bash title="cURL — CreateOidcProvider" theme={"theme":{"light":"github-light","dark":"github-dark"}} curl --request POST \ --url https://api.0xkey.io/public/v1/submit/create_oidc_provider \ --header 'Content-Type: application/json' \ --header "X-Stamp: (see Authorizations — root-quorum signature required)" \ --data '{ "type": "ACTIVITY_TYPE_CREATE_OIDC_PROVIDER", "timestampMs": "1746736509954", "organizationId": "", "parameters": { "providerName": "Acme Corp IdP", "issuer": "https://auth.acme.com", "audiences": ["acme-0xkey-client-id"] } }' ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"github-dark"}} { "activity": { "result": { "createOidcProviderResult": { "providerId": "" } } } } ``` * `issuer` must exactly match the `iss` claim your IdP puts in its tokens, and **cannot be changed later** — delete and re-create if it changes. * `audiences` is the allowlist of `aud` claims (your OAuth2 client IDs) that are accepted for this issuer. Manage the registry with the matching queries/activities: * [`GET_OIDC_PROVIDERS`](/api-reference/queries/get-oidc-providers) — list all registered providers for an organization. * `UPDATE_OIDC_PROVIDER` — change `providerName`, `audiences`, or `enabled` (issuer is immutable). * `DELETE_OIDC_PROVIDER` — remove a provider. Existing per-user identity bindings for that issuer are **not** retroactively deleted (see [`DELETE_OAUTH_PROVIDERS`](/api-reference/activities/delete-oauth-providers) to remove those explicitly) but will fail future logins since the issuer is no longer trusted. You can also manage Custom OIDC Providers from the **Dashboard** → **Wallet Kit** → **OIDC Providers** tab, which wraps the same activities behind a passkey-gated UI. ### Fail-closed: no wildcard trust Registration requires **at least one** audience — an issuer with an empty audience list is rejected outright. There is no "trust this issuer for any audience" option: every login or identity-binding attempt must present a token whose `aud` is in the registered list, in addition to passing the standard `iss`/`exp`/signature/nonce checks described [above](#what-does-0xkey-use-from-the-oidc-tokens-to-prove-identity). ### How this differs from the built-in providers table | | Built-in providers (Google, Apple, …) | Custom OIDC providers | | - | - | - | | Trust source | Hardcoded issuer allowlist, shipped by 0xkey | Your own `CREATE_OIDC_PROVIDER` registration, scoped to your organization | | Who can register | N/A (always trusted) | Root-quorum admins of the parent organization only | | Audience allowlist | Configured per Auth Proxy / Wallet Kit settings | Explicit, required, fail-closed (no wildcard) | | JWKS host binding | Provider's JWKS host may legitimately differ from the issuer host (e.g. Google: `accounts.google.com` issues, `www.googleapis.com` serves JWKS) | JWKS host is checked against the registered issuer's host to prevent a compromised/incorrect discovery document from redirecting key-fetching to an attacker-controlled host | | Login and identity binding | `oauth_login`, `CREATE_OAUTH_PROVIDERS` | Same activities — once registered, a custom issuer works identically to a built-in one for `oauth_login` / `CREATE_OAUTH_PROVIDERS` / `CREATE_SUB_ORGANIZATION` | Once an issuer is registered, it participates in the exact same enclave verification path already described in this guide: signature verification against the issuer's live JWKS, `iss`/`aud`/`exp`/`nonce` enforcement, and `(iss, sub)` identity binding. There is no separate "custom provider" login flow — `oauth_login` doesn't know or care whether the issuer is Google or your own IdP. ### Social linking Social linking is the concept of automatically linking an email address to a 0xkey user by authenticating with a social provider. This allows an end-user to authenticate with the social provider, or a matching email address. Currently, we only allow automatic linking for Google social logins. The cases are as follows: 1. The end-user authenticates with Google. Their email address is automatically linked to their authentication methods and considered “verified,” allowing them to log in with email OTP or email auth in the future. 2. The end-user authenticates with a Google email address (e.g., @gmail.com) via email OTP or email auth. If they later authenticate with Google, the Google OIDC provider will automatically be added as a valid login method, provided the email matches. 3. The end-user has existing non-Google authentication methods (e.g. phone number, passkeys, etc.) and later adds Google OIDC as a login method (via [CREATE_OAUTH_PROVIDERS](/api-reference/activities/create-oauth-providers#api-key)). The email address in the Google account will be automatically marked as "verified" and linked to the existing user. For more information on how to implement social linking, see the [social linking code example](/embedded-wallets/code-examples/social-linking). ## Setup for OAuth 2.0-only providers ### Setting up X/Twitter Navigate to the [X developer portal](https://developer.twitter.com/en/portal/dashboard) and create/setup your app. In the **Keys and Tokens** section, you'll need to save your **Client ID** and **Client Secret** so that these values can be uploaded to 0xkey's servers: ![alt text](https://mintcdn.com/chain/SBPPOKcVznKsWQeY/images/authentication/img/x_client_information.png?fit=max\&auto=format\&n=SBPPOKcVznKsWQeY\&q=85\&s=ab9ca67c2fa74479ba22a8dd7309c011) #### Required scopes In order for 0xkey to access the `/2/users/me` endpoint, the following scopes must be set during Authorization: * `tweet.read` * `user.read` ### Setting up Discord Navigate to the [Discord developer portal](https://discord.com/developers) and create/setup your app. In the **General Information** section, you'll need to save your **Client ID** and **Client Secret** so that these values can be uploaded to 0xkey's servers: ![alt text](https://mintcdn.com/chain/SBPPOKcVznKsWQeY/images/authentication/img/discord_client_information.png?fit=max\&auto=format\&n=SBPPOKcVznKsWQeY\&q=85\&s=2aa5822b3ff2e934d93113b3052e4547) #### Required scopes In order for 0xkey to access the `/api/users/@me` endpoint, the following scopes must be set during Authorization: * `identify` * `email` ### Client secret upload For every OAuth 2.0-Only Social Provider that you wish to integrate with, you must upload the **Client ID** and **Client Secret** issued by that Provider to 0xkey's Servers. In order to protect these sensitive credentials, they will be encrypted to the Quorum Key of the TLS Fetcher enclave, which ensures they cannot be accessed outside of that environment. You can upload these credentials through the 0xkey Dashboard. In the **Wallet Kit** section of the dashboard, head to the **Socials** tab and click **Add provider**. Select the provider you want to add from the dropdown, and fill in the required fields. You can find these values in the provider's developer console. Any secrets will automatically be encrypted before uploading to 0xkey. Once uploaded, you can then use the **Credential Id** from the table shown to make requests to the `OAUTH2_AUTHENTICATE` activity. ![Facebook OAuth flow](https://mintcdn.com/chain/SBPPOKcVznKsWQeY/images/authentication/img/social-logins-table.png?fit=max\&auto=format\&n=SBPPOKcVznKsWQeY\&q=85\&s=73c99edddccfc9432629b8f3e103d496) See the [Auth Proxy](/embedded-wallets/features/auth-proxy) and [`demo-embedded-wallet`](https://github.com/0xkey-io/demo-embedded-wallet) for OAuth credential upload patterns using the SDK. ### Returning the encrypted bearer token When using OAuth 2.0-Only Social Providers, it is also possible to have the bearer token returned by the `OAuth2Authenticate` endpoint, which can be useful if you would like your app to have additional integrations involving this Social Provider. In order to guarantee the secure transfer of the bearer token, it must be encrypted to a P256 Encryption Key inside our secure enclave, returned to the caller, and then finally decrypted. Therefore, the return of the encrypted bearer token is dependent on the caller providing an optional `bearerTokenTargetPublicKey` parameter in the request to `OAuth2Authenticate`. See [`demo-embedded-wallet` OAuth callbacks](https://github.com/0xkey-io/demo-embedded-wallet/tree/main/src/app/\(landing\)/oauth-callback) for an example of the encrypted bearer-token return flow with `OAuth2Authenticate`. # Hybrid co-signing Source: https://docs.0xkey.io/company-wallets/hybrid-cosign Optional end-user + backend 2/2 approval — not the default Company Wallets path. > [!WARNING] > > **SKU boundary.** Company Wallets default to **organization multi-party approvals** (API users + human operators in the same org). End-user passkey **plus** backend API key (2/2) is a **hybrid / Embedded-adjacent** pattern. Use it only when you intentionally share custody with an end user. ## When to use this pattern * Business wallets where the end user must approve every spend * Compliance flows that require user presence + server automation * Migrating from a co-custody model without moving to full custodial Company automation ## When not to use it * Pure treasury / payment orchestration (use org consensus + API keys) * High-volume backend sweeps (user presence does not scale) ## Mechanism (shared platform) The engine is the same Activity consensus state machine: 1. Create a sub-organization with two root users (end-user authenticator + backend API key) and `rootQuorumThreshold: 2`, **or** 2. Use a policy `consensus` expression that requires both actors Typical flow: client stamps with passkey → activity enters `CONSENSUS_NEEDED` → backend calls `approveActivity` → enclave signs. Related reading: * [Delegated access (server-side)](/policies/delegated-access/backend) — backend-limited control under a user-owned sub-org * [Root quorum](/concepts/users/root-quorum) * [Embedded wallets](/embedded-wallets/overview) — preferred SKU when end-user auth is first-class ## Company Wallets default instead For institutional automation, prefer: 1. Parent org + API-only users 2. Tags + deny-by-default policies 3. `approvers.count() >= N` among operator passkeys 4. Optional custodial send + Enterprise sponsorship # Company Wallets integration guide Source: https://docs.0xkey.io/company-wallets/integration-guide Server-side patterns for policies, consensus, custodial send, webhooks, and attestation. This guide covers the production patterns for Company Wallets after you finish the [quickstart](/company-wallets/quickstart). ## Recommended org layout | Resource | Recommendation | | :- | :- | | Parent org | One root org for your company treasury / ops | | API-only users | One per automation role (`sweeper`, `deployer`, `agent`) | | Human operators | Passkey users in the same org for approvals | | Tags | Attach users to tags referenced by policies | | Sub-orgs | Optional isolation for customers / business units (parent read-only patterns) | Create API-only users with `createApiOnlyUsers`, then stamp all server calls with that keypair via `@0xkey-io/sdk-server`. ## Policy + consensus 1. Prefer **narrow allow** policies (recipient / selector / chain / value). 2. Add `consensus` for high-value paths (`approvers.count() >= 2`). 3. Use [Policy simulate](/policies/overview) in the Dashboard before enabling automation. 4. Root quorum (`updateRootQuorum`) gates org-level sensitive changes — separate from per-activity consensus. Templates: [Policy templates](/company-wallets/policy-templates). ## Custodial send matrix | API | Chains | Notes | | :- | :- | :- | | `ethSendTransaction` | EVM (see [Networks](/networks/overview)) | `sponsor: true` = Enterprise Gas Station | | `solSendTransaction` | Solana mainnet / devnet | Fee-payer sponsorship = Enterprise | | `tronSendTransaction` | Tron TRX / TRC-20 | No platform fee sponsorship | | `getSendTransactionStatus` | All of the above | Poll until confirmed / failed | Always fail closed when RPC providers are unavailable — do not treat empty statuses as success. ## Webhooks Subscribe to activity and send-transaction status updates for ops automation. Verify signatures via the public JWKS endpoint. See [Webhooks](/developer-reference/webhooks). ## Import / export HPKE-protected import/export is available on all plans (`key_export` is not a paid-tier gate). Use Dashboard import or server SDK export flows; never log plaintext mnemonics. Protocol: see technical design B3 / frames export UIs. ## Attestation checklist Before production: 1. Call `getAttestationDocument` (or boot/app proof APIs) against your target environment. 2. Verify with `@0xkey-io/crypto` helpers (`verifyAttestationDocument` / boot proof verify). 3. Pin expected PCR / manifest values from your ceremony release notes. Details: [Remote attestation](/security/remote-attestation). ## Hybrid end-user + backend co-sign If you need end-user passkey **and** backend API key (2/2), that is a **hybrid / Embedded-adjacent** pattern — not the default Company Wallets path. See [Hybrid co-signing](/company-wallets/hybrid-cosign). ## Language SDKs | SDK | Company path | | :- | :- | | `@0xkey-io/sdk-server` | Primary | | sdk-go | Examples for wallets / signing / tx management | | sdk-rust | Coming soon | | CLI | **Partial** (v0.1.0) — wallets, accounts, policies, activities, and stamped requests; see [Using the CLI](/sdks/cli) | ## Migration from Turnkey Public docs do **not** ship a one-click Turnkey migration funnel. Enterprise customers can request private migration assistance via [hello@0xkey.io](mailto:hello@0xkey.io). Policy DSL is not 1:1 with CEL — expect conversion and review. # Company Wallets Source: https://docs.0xkey.io/company-wallets/overview Organization-owned custodial wallets for backend automation, treasury ops, and policy-governed signing. **Company Wallets** are custodial wallets owned and operated by your organization. Your team controls who can sign, what they can sign, and under what conditions. The wallets belong to your business; 0xkey provides TEE-backed infrastructure to operate them securely at scale. Where [Embedded Wallets](/embedded-wallets/overview) give each end user their own wallet, Company Wallets centralize control within your organization. Backend services, operators, and automated systems sign through the Public API, governed by role-based access and the policy engine. ## Why Company Wallets * **Keys never leave the enclave.** Signing happens inside AWS Nitro TEEs; only signatures are returned. * **Deny-by-default policies.** CEL rules evaluated in-enclave control recipients, contracts, selectors, chains, and values. * **Multi-party approval.** Require N-of-M consensus (or root quorum) before sensitive activities complete. * **Server-first integration.** API keys + `@0xkey-io/sdk-server` / Go SDK — no end-user Auth Proxy dependency. * **Custodial send.** Build, policy-check, sign, and broadcast on EVM, Solana, and Tron in one activity. * **Enterprise gas sponsorship.** Platform paymaster / fee-payer on supported chains (Enterprise plan). * **Import / export.** HPKE-protected wallet and key migration without plaintext key exposure. * **Verifiable TEE.** Remote attestation and boot/app proofs for independent verification. ## How it works Your backend authenticates with an API key. Inside the enclave, the policy engine evaluates the request. If allowed (and any required approvers have voted), the signer produces a signature or the coordinator completes a custodial send. Private keys never leave the TEE. ### Access control model Company Wallets use a parent organization (sub-organizations for tenant isolation). Within that org you define: * **Users** — human operators and API-only service accounts * **Tags** — role groups (e.g. `deployer`, `treasury-ops`, `sweeper`) * **Policies** — CEL `effect` + `condition` + optional `consensus` * **Root quorum** — threshold for org-level sensitive changes See [Policies](/policies/overview), [Root quorum](/concepts/users/root-quorum), and [Transaction management](/concepts/transaction-management). ## Company Wallets vs Embedded Wallets | | Embedded Wallets | Company Wallets | | :- | :- | :- | | **Primary user** | End users in your app | Your team / backend services | | **Org model** | Sub-org per user (typical) | Parent-org automation | | **Auth surface** | Passkey, OTP, OAuth via Auth Proxy | API keys (passkeys optional for operators) | | **Default path** | Client SDK + sessions | Server SDK + stamped API | | **Hybrid co-sign** | Common (user + backend) | Optional — see [Hybrid co-signing](/company-wallets/hybrid-cosign) | ## Building with 0xkey 1. [Company Wallets quickstart](/company-wallets/quickstart) — API key → wallet → sign / send 2. [Integration guide](/company-wallets/integration-guide) — policies, consensus, webhooks 3. [Policy templates](/company-wallets/policy-templates) — treasury 2-of-N, allowlists, agent deny 4. [Remote attestation](/security/remote-attestation) — production verification checklist ### Use cases * [Payment orchestration](/company-wallets/use-cases/payment-orchestration) — sweeps, payouts, sponsored sends * [Treasury operations](/company-wallets/use-cases/treasury) — multi-party approvals for high-value moves * [Agent-restricted signing](/company-wallets/use-cases/agentic) — narrow automation with deny-by-default ### SDKs * TypeScript: [`@0xkey-io/sdk-server`](/sdks/introduction) * Go: [sdk-go](/sdks/go/landing) examples (`wallets`, `signing`, `transaction_management`, `delegated_access`) ### Related capabilities > [card] [Server-side delegated access](/policies/delegated-access/backend) > > Scope a backend API key with policies > [card] [Root quorum](/concepts/users/root-quorum) > > Multi-party control of the organization > [card] [Smart contract interfaces](/policies/smart-contract-interfaces) > > Write policies against decoded ABI / IDL calls > [card] [Security architecture](/security/our-approach) > > Enclaves, QuorumOS, secure hardware, attestation ## Chain support (Company path) | Layer | EVM | Solana | Tron | Bitcoin & others | | :- | :- | :- | :- | :- | | Address derivation | Supported | Supported | Supported | Address only (see [Networks](/networks/overview)) | | In-enclave parse + policy | Supported | Supported | Supported | Coming soon | | Custodial send | Supported | Supported | Supported | N/A (client broadcast) | | Gas sponsorship | Enterprise | Enterprise | Not available | N/A | ## Enterprise contact For Enterprise plan (gas sponsorship, custom limits, private migration assistance): [hello@0xkey.io](mailto:hello@0xkey.io). # Policy templates Source: https://docs.0xkey.io/company-wallets/policy-templates Ready-to-adapt CEL policies for treasury, automation allowlists, and agent deny-by-default. Copy these into Dashboard **Security → Policies** or `createPolicy`. Adjust addresses, tags, and thresholds. 0xkey is **deny-by-default** — missing allows mean reject. ## Treasury 2-of-N (high-value ETH transfer) Require two approvers from the `ops-team` tag for native transfers above a wei threshold: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "policyName": "treasury-eth-2ofn", "effect": "EFFECT_ALLOW", "condition": "activity.type == 'ACTIVITY_TYPE_ETH_SEND_TRANSACTION' && eth.tx.value >= decimal('1000000000000000000')", "consensus": "approvers.filter(user, user.tags.contains('ops-team')).count() >= 2" } ``` ## Automation allowlist (single recipient) Backend sweeper may only send to a fixed address: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "policyName": "sweeper-allowlist", "effect": "EFFECT_ALLOW", "condition": "activity.type == 'ACTIVITY_TYPE_SIGN_TRANSACTION_V2' && eth.tx.to == '0xYourHotWallet'", "consensus": "" } ``` ## Agent deny-by-default (explicit deny on broad sign) Block an agent-tagged user from arbitrary `signRawPayload` while allowing a narrow contract call elsewhere: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "policyName": "agent-deny-raw", "effect": "EFFECT_DENY", "condition": "activity.type == 'ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2' && credentials.any(c, c.user.tags.contains('agent'))", "consensus": "" } ``` > [!NOTE] > > Exact `credentials` / tag field names depend on enclave CEL context availability. Validate with Policy Simulate before production. If a field is unavailable, fall back to `activity.actor` / user-id equality conditions documented in [Policy language](/policies/language). ## Deployer allowlist (contract creation / specific selector) ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "policyName": "deployer-selector", "effect": "EFFECT_ALLOW", "condition": "activity.type == 'ACTIVITY_TYPE_SIGN_TRANSACTION_V2' && eth.tx.data[0:4] == '0x6057361d'", "consensus": "approvers.count() >= 1" } ``` ## Gas Station intent (Enterprise) When using `sponsor: true`, add policies for EIP-712 intent signing and paymaster execution as described in the Gas Station package (`@0xkey-io/gas-station` `policyUtils`). Keep paymaster execution policies separate from user intent policies. ## Solana / Tron Mirror the same patterns with `solana.tx.*` and `tron.tx.*` contexts — see [Policy language](/policies/language) and network pages. # Company Wallets quickstart Source: https://docs.0xkey.io/company-wallets/quickstart From API key to a signed or custodially sent transaction with the 0xkey server SDK. This guide assumes you have a 0xkey organization and an API keypair (create them in the [Dashboard](https://app.0xkey.io) under **Users → API keys**, or via `createApiOnlyUsers`). It uses the TypeScript server SDK. For Go, see [sdk-go examples](/sdks/go/landing). ## Installation ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install @0xkey-io/sdk-server ``` ## Sign or send your first transaction **1. Initialize the server client** Add credentials to `.env`: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} ZEROXKEY_API_BASE_URL=https://api.0xkey.io ZEROXKEY_ORGANIZATION_ID= ZEROXKEY_API_PRIVATE_KEY= ZEROXKEY_API_PUBLIC_KEY= ``` ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} import { ZeroXKey } from "@0xkey-io/sdk-server"; const client = new ZeroXKey({ apiBaseUrl: process.env.ZEROXKEY_API_BASE_URL!, defaultOrganizationId: process.env.ZEROXKEY_ORGANIZATION_ID!, apiPrivateKey: process.env.ZEROXKEY_API_PRIVATE_KEY!, apiPublicKey: process.env.ZEROXKEY_API_PUBLIC_KEY!, }).apiClient(); ``` **2. Create a wallet** ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} const { walletId, addresses } = await client.createWallet({ walletName: "treasury", accounts: [ { curve: "CURVE_SECP256K1", pathFormat: "PATH_FORMAT_BIP32", path: "m/44'/60'/0'/0/0", addressFormat: "ADDRESS_FORMAT_ETHEREUM", }, ], }); const ethereumAddress = addresses[0]; console.log("Ethereum address:", ethereumAddress, "walletId:", walletId); ``` For Solana, use `CURVE_ED25519` + `ADDRESS_FORMAT_SOLANA` + path `m/44'/501'/0'/0'`. For Tron, see [Tron](/networks/tron). **3. Add a deny-by-default allowlist policy (recommended)** Without an allow policy, signing is denied. Create a narrow policy for your automation user (replace tags / addresses as needed): ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} await client.createPolicy({ policyName: "treasury-eth-transfer-allowlist", effect: "EFFECT_ALLOW", condition: "activity.type == 'ACTIVITY_TYPE_SIGN_TRANSACTION_V2' && eth.tx.to == '0xApprovedRecipient'", consensus: "approvers.count() >= 1", notes: "Company Wallets quickstart sample", }); ``` See [Policy templates](/company-wallets/policy-templates) for treasury 2-of-N and agent deny patterns. **4. Sign a raw payload or custodially send** **Sign only** (you broadcast yourself): ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} const { r, s, v } = await client.signRawPayload({ signWith: ethereumAddress, payload: "0xdeadbeef", encoding: "PAYLOAD_ENCODING_HEXADECIMAL", hashFunction: "HASH_FUNCTION_KECCAK256", }); ``` **Custodial send** (0xkey builds, policy-checks, signs, broadcasts — EVM example): ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} const { sendTransactionStatusId } = await client.ethSendTransaction({ from: ethereumAddress, to: "0xApprovedRecipient", caip2: "eip155:84532", // Base Sepolia — use a funded testnet address value: "0", data: "0x", sponsor: false, }); const status = await client.getSendTransactionStatus({ sendTransactionStatusId, }); console.log(status); ``` > [!NOTE] > > `sponsor: true` (gas sponsorship) requires an **Enterprise** plan. Free / PAYG / Pro receive an entitlement error. See [Transaction management](/concepts/transaction-management) and billing entitlements. ## When an activity needs consensus If a policy sets `consensus` (e.g. `approvers.count() >= 2`), the activity stays in `ACTIVITY_STATUS_CONSENSUS_NEEDED` until enough approvers call `approveActivity` (or reject). Operators can approve in the [Dashboard → Activities](https://app.0xkey.io) or via the API. Approvals expire after **24 hours**. ## Next steps * [Integration guide](/company-wallets/integration-guide) — tags, webhooks, import/export * [Remote attestation](/security/remote-attestation) — verify TEE proofs in production * [demo-company-wallet](https://github.com/0xkey-io) — local/staging sandbox (org → policy → consensus → send) # Agent-restricted signing Source: https://docs.0xkey.io/company-wallets/use-cases/agentic Give automation agents narrow signing power with deny-by-default policies. Agents and bots should never hold broad signing rights. Company Wallets let you issue an API-only user, tag it `agent`, and allow only the exact actions you intend. ## Pattern 1. Create an API-only user + tag `agent` 2. **Deny** broad `signRawPayload` for that tag 3. **Allow** a specific contract selector / recipient / chain 4. Optional consensus for first-seen contracts 5. Meter usage via billing / webhooks; revoke by deleting the API key ## Controls * Prefer contract allowlists over “sign anything” * Keep agent keys out of root quorum * Use short-lived keys and rotate on incident ## Related * [Policy templates](/company-wallets/policy-templates) * [Delegated access](/policies/delegated-access/backend) — when the wallet is user-owned instead of company-owned # Payment orchestration Source: https://docs.0xkey.io/company-wallets/use-cases/payment-orchestration Sweeps, payouts, and custodial sends with policy-governed Company Wallets. Use Company Wallets when your backend must move funds at scale without exposing keys. ## Pattern 1. Hot wallet (or per-rail wallets) in a parent org 2. API-only `sweeper` / `payout` users with allowlist policies 3. Custodial `ethSendTransaction` / `solSendTransaction` / `tronSendTransaction` 4. Webhooks on send-transaction status for reconciliation 5. Optional Enterprise `sponsor: true` for gasless end-user or ops UX ## Controls * Recipient allowlists and value caps in CEL * Consensus for payouts above a threshold * Separate tags for initiate vs approve ## Related * [Quickstart](/company-wallets/quickstart) * [Policy templates](/company-wallets/policy-templates) * [Transaction management](/concepts/transaction-management) # Treasury operations Source: https://docs.0xkey.io/company-wallets/use-cases/treasury Multi-party approvals for high-value company treasury moves. Treasury teams need deny-by-default policies and human consensus without slowing automation for low-risk paths. ## Pattern 1. Cold / warm wallets as HD wallets in the parent org 2. Operator passkeys tagged `ops-team` 3. Policies with `consensus: approvers.filter(...).count() >= 2` for high value 4. Dashboard Activities for “votes remaining” and 24h expiry 5. Audit export / webhook stream for compliance ## Controls * Root quorum for org membership and policy admin changes * Separate automation keys that **cannot** move treasury (no allow policy) * Import/export only through HPKE channels with dual control ## Related * [Root quorum](/concepts/users/root-quorum) * [Policy templates](/company-wallets/policy-templates) * [Hybrid co-signing](/company-wallets/hybrid-cosign) — only if an external user must co-sign # Activities Source: https://docs.0xkey.io/concepts/activities Every state-changing request to 0xkey becomes an activity: a signed, policy-checked, auditable record with a status you can poll. An **activity** is the record 0xkey creates for every state-changing request: creating a wallet, signing a transaction, adding a user, updating a policy. Reads are **queries** and do not create activities. | | Activities | Queries | | :- | :- | :- | | Path | `POST /public/v1/submit/*` | `POST /public/v1/query/*` | | Stamped by a credential | Yes | Yes | | Evaluated by the policy engine | Yes | No | | Leaves an auditable record | Yes | No | ## Lifecycle 1. Your client builds the request body and [stamps](/developer-reference/api-overview/stamps) it with an API key or passkey. 2. The enclave verifies the stamp and identifies the user behind the credential. 3. The [policy engine](/policies/overview) evaluates the request. Root users can bypass policies once the [root quorum](/concepts/users/root-quorum) threshold is met. 4. If allowed, the activity executes inside the enclave and the result is attached to the activity. The response always carries an `activity` object. Branch on `activity.status`: | Status | Meaning | What to do | | :- | :- | :- | | `ACTIVITY_STATUS_COMPLETED` | Executed; `activity.result` is populated | Read the result | | `ACTIVITY_STATUS_PENDING` | Still processing asynchronously | Poll `get_activity` with `activity.id` | | `ACTIVITY_STATUS_CONSENSUS_NEEDED` | A policy requires more approvals | Collect approvals with `approve_activity` | | `ACTIVITY_STATUS_AUTHENTICATORS_NEEDED` | Additional authentication (MFA) is required | Complete the extra authentication step | | `ACTIVITY_STATUS_REJECTED` | An approver rejected it | Treat as final | | `ACTIVITY_STATUS_FAILED` | Execution failed; `activity.failure` explains why | Treat as final; fix the request | Approvals expire 24 hours after the first one; the activity itself does not. See [Submissions](/developer-reference/api-overview/submissions) for details. > [!NOTE] > > The SDKs poll for you. The Swift and Kotlin SDKs throw when an activity does not reach `COMPLETED`. The TypeScript `apiClient()` returns the activity instead, so check `activity.status` before reading the result. Branch on status and error code, not on message text. See [Errors](/developer-reference/api-overview/errors). ## Idempotency The request body is hashed into a fingerprint. Re-submitting the same body returns the same activity instead of executing twice. To run the same operation again, change `timestampMs`. ## Related * [Submissions](/developer-reference/api-overview/submissions) and [Queries](/developer-reference/api-overview/queries) * [Policy overview](/policies/overview) * [Activity endpoints](/api-reference/activities/overview) # Organizations Source: https://docs.0xkey.io/concepts/organizations An organization is a logical grouping of resources (e.g. users, policies, wallets). These resources can only be accessed by authorized and permissioned users within the organization. Resources are not shared between organizations. ## Root quorum All organizations are controlled by a [Root Quorum](/concepts/users/root-quorum) which contains the root users and the required threshold of approvals to take any action. Only the root quorum can update the root quorum or feature set. ## Features Organization features are 0xkey product offerings that organizations can opt-in to or opt-out of. Note that these features can be set and updated using the activities `ACTIVITY_TYPE_SET_ORGANIZATION_FEATURE` and `ACTIVITY_TYPE_REMOVE_ORGANIZATION_FEATURE`. The following is a list of such features: | Name | Description | Default | Notes | | - | - | - | - | | FEATURE_NAME_EMAIL_AUTH | Enables email bundle authentication | Enabled | The `email_auth` activity can only be initiated by a parent organization for a sub-organization. | | FEATURE_NAME_OTP_EMAIL_AUTH | Enables email OTP authentication | Enabled | The `init_otp`, `verify_otp` and `otp_login` activities can only be initiated by a parent organization for a sub-organization. | | FEATURE_NAME_WEBAUTHN_ORIGINS | The origin Webauthn credentials are scoped to | Disabled | Parent organization feature applies to all sub-organizations. If not enabled, sub-organizations default to allowing all origins: "\*". For Passkey WaaS, we highly recommend enabling this feature. Example value: "[https://0xkey.io"](https://0xkey.io%22) | | FEATURE_NAME_WEBHOOK | A URL to receive activity notification events | Disabled | Example value: "[https://your.service.com/webhook"](https://your.service.com/webhook%22) | ## Permissions All activity requests are subject to enforcement by 0xkey's policy engine. The policy engine determines if a request is allowed by checking the following: * Does this request violate our feature set? * Email auth cannot be initiated if disabled * Should this request be denied by default? * All import requests must target your own user * Does this request meet the root quorum threshold? * What is the outcome of evaluating this request against all organization policies? Outcomes include: * `OUTCOME_ALLOW`: the request is allowed to process * `OUTCOME_REQUIRES_CONSENSUS`: the request needs additional approvals * `OUTCOME_REJECTED`: the request should be rejected * `OUTCOME_DENY_EXPLICIT`: the request has been explicitly denied via policies * `OUTCOME_DENY_IMPLICIT`: the request has been implicitly denied as no policies grant the required permissions * Should this request be allowed by default? * Users can manage their own credentials unless policies explicitly deny this ## Resource limits Organizations have [resource limits](/concepts/resource-limits) for performance and security considerations. If you're bumping into these limits, check out sub-organizations below. ## Sub-organizations A sub-organization is an isolated organization that has a pointer to a parent organization. The parent organization has **read** access to all sub-organizations, but no **write** access. This means users within the parent organization have no ability to use wallets or alter any resources in the sub-organization. For more information on sub-organizations and common use cases for this functionality, follow along in the next section . # Concepts overview Source: https://docs.0xkey.io/concepts/overview Core building blocks of 0xkey: organizations, users, wallets, policies, and activities. 02 / CORE CONCEPTS 0xkey is built around a small set of composable *primitives*. Understanding them makes every integration decision straightforward. ## How 0xkey works Instead of directly managing private keys, **wallets are accessed through authenticators** — passkeys, API keys, or OAuth tokens. The enclave evaluates your policies before any signing operation proceeds. ``` Organization ├── Users (with credentials: passkey, API key, OAuth) ├── Wallets (HD seed → multiple chain accounts) └── Policies (govern all activities) └── Sub-organizations (isolated, one per end user) ├── Users ├── Wallets └── Policies ``` *** ## Organizations An **organization** is the top-level container for your application's resources: users, wallets, and policies. | Type | Description | | :- | :- | | **Parent organization** | Created when you sign up. Represents your entire application. Managed by your team via the Dashboard or API. | | **Sub-organization** | A fully isolated child organization. Typically represents one end user. The parent org has read access but **cannot modify** sub-org contents. | Sub-organizations are the foundation of 0xkey's embedded wallet model — each user gets their own isolated key space. *** ## Users A **user** is a resource inside an organization that can submit activities using a valid credential. | Type | Description | | :- | :- | | **Root user** | Can bypass the policy engine and take any action in the organization. Governed by the root quorum threshold. | | **Normal user** | Has no permissions unless explicitly granted by a policy. Used for end users and backend service accounts. | Users authenticate with one or more **credentials**: API keys, passkeys, or OAuth tokens. Multiple credential types can be attached to a single user. *** ## Wallets A **wallet** in 0xkey is an HD seed phrase that can derive many chain accounts (addresses). The seed never leaves the enclave. * One wallet can hold accounts across multiple chains * Accounts are derived by `addressFormat` (e.g., `ETHEREUM`, `SOLANA`) * Signing requests reference a specific wallet account, not the seed directly *** ## Policies **Policies** govern all activities in an organization. Every signing operation, user creation, and resource modification is evaluated against the applicable policies before it proceeds. * Policies use a simple condition language (`effect`, `consensus`, `condition`) * Root users can bypass the policy engine when the root quorum threshold is met * Policies can target specific users, user tags, wallet accounts, or activity types See [Policy overview](/policies/overview) and the [policy language reference](/policies/language). *** ## Activities An **activity** is any state-changing operation submitted to the 0xkey API — signing a transaction, creating a wallet, adding a user, etc. * Activities are submitted as HTTP `POST` requests to `/public/v1/submit/*` * Each activity goes through the policy engine before execution * The response includes an `activity` object with a `status` field (`ACTIVITY_STATUS_COMPLETED`, `ACTIVITY_STATUS_PENDING`, `ACTIVITY_STATUS_FAILED`, etc.) * Some activities require additional approvals and enter the `ACTIVITY_STATUS_CONSENSUS_NEEDED` state See [Activities](/concepts/activities) for the full lifecycle. Read-only operations use `/public/v1/query/*` and do not go through the policy engine. *** ## Further reading * [Organizations in depth](/concepts/organizations) * [Sub-organizations](/concepts/sub-organizations) * [Users and credentials](/concepts/users/introduction) * [Wallets](/concepts/wallets) * [Activities](/concepts/activities) * [Policies](/policies/overview) * [Security model](/concepts/security-model) * [API overview](/developer-reference/api-overview/intro) # Policy engine Source: https://docs.0xkey.io/concepts/policy-engine Our policy engine is the foundation for flexible controls and permissions within your organization. This page provides an overview of how to author policies. ## Policy structure Our policies are defined using **JSON**. The `effect` determines if an activity should be allowed or denied based on the evaluation of the `consensus` and `condition` fields. `consensus` and `condition` are composed of ergonomic expressions written in our [policy language](/policies/language) that must evaluate to a `bool`. `consensus` determines which user(s) may take an action (e.g. a given user ID). `condition` determines the conditions under which the policy applies (e.g. signing with a specific wallet). `condition` is **required**. Creating a policy whose `condition` is missing, empty, or only whitespace is rejected with HTTP 400 (`INVALID_ARGUMENT`, message `policy condition is required`); so is an update that sets `policyCondition` to an empty or whitespace-only value (an update that omits `policyCondition` keeps the current one). To write a policy that applies to every activity, set `"condition": "true"` explicitly. `consensus` is optional. #### See below for an example policy that allows a single user to send transactions to a single address ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "effect": "EFFECT_ALLOW", "consensus": "approvers.any(user, user.id == '')", "condition": "eth.tx.to == ''" } ``` ## Managing policies | Action | Endpoint | Activity type | Parameters | SDK method | | :- | :- | :- | :- | :- | | Create one | `POST /public/v1/submit/create_policy` | `ACTIVITY_TYPE_CREATE_POLICY_V3` | `policyName`, `effect`, `notes`, `condition`, optional `consensus` | `createPolicy` | | Create several | `POST /public/v1/submit/create_policies` | `ACTIVITY_TYPE_CREATE_POLICIES` | `policies[]` (same fields as above) | `createPolicies` | | Update | `POST /public/v1/submit/update_policy` | `ACTIVITY_TYPE_UPDATE_POLICY_V2` | `policyId` plus any of `policyName`, `policyEffect`, `policyCondition`, `policyConsensus`, `policyNotes` | `updatePolicy` | | Delete one | `POST /public/v1/submit/delete_policy` | `ACTIVITY_TYPE_DELETE_POLICY` | `policyId` | `deletePolicy` | | Delete several | `POST /public/v1/submit/delete_policies` | `ACTIVITY_TYPE_DELETE_POLICIES` | `policyIds[]` | `deletePolicies` | | List / get | `POST /public/v1/query/list_policies`, `/query/get_policy` | — | `organizationId`, `policyId` | `getPolicies`, `getPolicy` | The SDK method names are the same in `@0xkey-io/sdk-server`, the Swift SDK (`ZeroXKeyClient`), and the Kotlin SDK (`ZeroXKeyClient`). Deleting a policy ID that does not exist in the organization returns HTTP 404 (`NOT_FOUND`); call `list_policies` and retry with the current IDs. See [Errors](/developer-reference/api-overview/errors#policy-not-found). > [!TIP] > > For keys that are restricted by transaction fields (`eth.tx.*`, `solana.tx.*`, `tron.tx.*`), sign with the transaction-signing endpoints (such as `sign_transaction`), and add a policy that denies raw payload signing for those keys unless your integration needs it. See [Activity parameters](/policies/language#activity-parameters). ## Policy evaluation All policies defined within an Organization are evaluated on each request. The image below describes how an activity outcome is determined when resolving multiple policies. The rule follows the below steps: **Step 1** If a quorum of root users takes the action, the final outcome is `OUTCOME_ALLOW` **Step 2** Else if any applicable policy has `EFFECT_DENY`, the final outcome is `OUTCOME_DENY`. This is also referred to as "explicit deny." **Step 3** Else if at least one applicable policy has `EFFECT_ALLOW`, then the final outcome is `OUTCOME_ALLOW` **Step 4** Else the final outcome is `OUTCOME_DENY`. This is also referred to as "implicit deny." In cases of conflicts, `EFFECT_DENY` always wins. Stated differently: ![policy overview](https://mintcdn.com/chain/SBPPOKcVznKsWQeY/images/concepts/policies/img/diagrams/policy_overview.png?fit=max\&auto=format\&n=SBPPOKcVznKsWQeY\&q=85\&s=601f2ac7bc44966a6bef0ad813a7cda3) Almost all actions on 0xkey are implicitly denied by default. There are a few exceptions, however: * The Root Quorum bypasses any policies. * All users have implicit GET (read) permissions in their own Organization and any associated Sub-Organizations. * All users have implicit permission to change their own credentials, unless a policy explicitly allows or denies those actions. * All users have implicit permission to approve an activity if they were included in consensus (i.e., a user specified as part of the consensus required to approve a SIGN_TRANSACTION activity does not need separate, explicit permission to sign transactions). # Resource limits Source: https://docs.0xkey.io/concepts/resource-limits Learn more about how to structure your implementation to avoid resource limits. **0xkey is scalable to millions of users and millions of transactions.**\ \ However, we have limits on the number of resources within a **single organization** to avoid performance slowdowns and overly complex permission models. You can scale your organizational resources beyond these limits via sub-organizations. **You can create an unlimited number of sub-organizations within a single organization.**\ \ Currently, the resource limits within a single organization are as follows: | Resource | Maximum parent org allowance | Maximum sub-org allowance | | :- | :-: | :-: | | Sub-Organizations | unlimited | 0 | | HD Wallet Accounts | unlimited | unlimited | | HD Wallets | 100 | 100 | | Private keys | 1,000 | 1,000 | | Users | 100 | 100 | | Policies | 100 | 100 | | Invitations | 100 | 100 | | Tags | 100 | 10 | | Authenticators per user | 10 | 10 | | API keys per user (long-lived) | 10 | 10 | | API keys per user (expiring) | 10 | 10 | | OAuth providers per user | 10 | 10 | Note that if you create an expiring API key that would exceed the limit above, 0xkey automatically deletes one of your existing keys using the following priority: 1. Expired API keys are deleted first 2. If no expired keys exist, the oldest unexpired key is deleted If you are approaching any of these limits in your implementation and require support, reach out to the 0xkey team ([hello@0xkey.io](mailto:hello@0xkey.io)). # Security model Source: https://docs.0xkey.io/concepts/security-model How 0xkey protects keys: secure enclaves, verifiable requests, policy enforcement, and remote attestation. 0xkey never holds a usable private key outside a secure enclave. The model rests on four properties. ## 1. Keys only exist in plaintext inside enclaves Key generation, signing and policy evaluation run inside secure enclaves (Trusted Execution Environments) on AWS Nitro. Enclaves have no persistent storage, no interactive access and no external networking. Private keys are stored only as ciphertext and are decrypted only inside an enclave running verified 0xkey code. See [Secure enclaves](/security/secure-enclaves) and [Non-custodial key management](/security/non-custodial-key-mgmt). ## 2. Every request is signed by its author Each request carries a [stamp](/developer-reference/api-overview/stamps): a signature over the exact request body by an API key or passkey. The enclave verifies the stamp itself, so a compromised server between your client and the enclave cannot forge or alter a request. With [sub-organizations](/concepts/sub-organizations), only the end user's credentials can authorize use of the end user's keys. ## 3. Policies are enforced inside the enclave The [policy engine](/policies/overview) runs in the enclave and decides every [activity](/concepts/activities) before it executes. Restrict non-root users with policies, keep root users for administration, and protect the organization with a [root quorum](/concepts/users/root-quorum). ## 4. You can verify what is running QuorumOS, the enclave operating system, requires a quorum of operators to deploy enclave code or reconstruct core secrets; no single engineer can do either. [Remote attestation](/security/remote-attestation) lets you check that an enclave is genuine Nitro hardware running the expected measurements. ## Your responsibilities * Store API private keys in a secrets manager; never ship them to browsers or mobile apps. * Give each backend its own API user, scoped by policy, instead of a root key. * Prefer transaction signing over raw-payload signing so transaction-field policies apply. * Work through the [Launch checklist](/getting-started/launch-checklist) before going live. ## Read more > [card] [Our approach](/security/our-approach) > > The security framework end to end > [card] [Whitepaper](/whitepaper) > > Architecture and design principles in depth # Sub-organizations Source: https://docs.0xkey.io/concepts/sub-organizations Using 0xkey's flexible infrastructure, you can programmatically create and manage sub-organizations for your end-users. Sub-organizations aren't subject to size limits: you can create as many sub-organizations as needed. The parent organization has **read-only** visibility into all of its sub-organizations, and activities performed in sub-organizations roll up to the parent for billing purposes. We envision sub-organizations being very useful to model your end-users if you're a business using 0xkey for key management. Let's explore how. ## Creating sub-organizations Creating a new sub-organization is an activity performed by the parent organization. The activity itself takes the following attributes as inputs: * organization name * a list of root users * a root quorum threshold * \[optional] a wallet (note: in versions prior to V4, this was a private key) Root users can be programmatic or human, with one or many credentials attached. ## Using sub-organizations You can use this primitive to model end-user controlled wallets or custodial wallets. If you have another use-case in mind, or questions/feedback on this page, reach out to [hello@0xkey.io](mailto:hello@0xkey.io)! ## Deleting sub-organizations To delete a sub-organization, you can use the [delete sub-organization activity](/api-reference/activities/delete-sub-organization). Before proceeding, ensure that all private keys and wallets within the sub-organization have been exported to prevent any loss of funds. Alternatively, you can set the `deleteWithoutExport` parameter to `true` to bypass this requirement. By default, the `deleteWithoutExport` parameter is set to `false`. > [!NOTE] > > This activity must be initiated by a root user in the sub-organization that is > to be deleted. A parent org cannot delete a sub-organization without its > participation. # Transaction management Source: https://docs.0xkey.io/concepts/transaction-management Learn about 0xkey's gas sponsorship, transaction construction, broadcast, nonce management and monitoring capabilities. # Overview Traditionally, sending blockchain transactions onchain has been painful: * You need to fund wallets with native gas tokens, creating onboarding friction * Network congestion and fee spikes can cause transactions to stall or get dropped altogether 0xkey reduces this to a couple of API calls. We handle fees and our battle-tested broadcast logic ensures inclusion even under adverse network conditions. You and your users never touch gas tokens or deal with stuck transactions. ## Supported chains **EVM (sponsored):** * **Base** - eip155:8453 * **Polygon** - eip155:137 * **Ethereum** - eip155:1 **EVM testnets (sponsored):** * **Base (Sepolia)** - eip155:84532 * **Polygon (Amoy)** - eip155:80002 * **Ethereum (Sepolia)** - eip155:11155111 **Solana (sponsored):** * **Solana mainnet** - solana:mainnet * **Solana devnet** - solana:devnet **EVM (standard sends — construction, signing, and broadcast; gas paid by the sender):** * **Arbitrum One** - eip155:42161 * **BNB Chain** - eip155:56 **EVM testnets (standard sends):** * **Arbitrum (Sepolia)** - eip155:421614 * **BNB (Testnet)** - eip155:97 > Interested in another chain? Reach out to us! > [!NOTE] > > To access sponsored transactions, ensure that Gas Sponsorship is first enabled within your 0xkey dashboard. Then set `sponsor: true` and update the `caip2` parameter with the corresponding chain identifier. ## Concepts ### Gas sponsorship (aka gas abstraction, gasless transactions, fee abstraction) A single endpoint lets you toggle between standard and sponsored transactions. With sponsorship enabled, your users never need to hold native tokens to pay transaction fees — 0xkey covers them. Set `sponsor: true` to enable sponsorship, or `sponsor: false` to have fees paid by the sender's wallet. Either way, 0xkey handles construction, signing, broadcast, and status monitoring. The `sponsor` flag only controls who pays the fee. > [!NOTE] > > Gas Sponsorship is available to **Enterprise clients only**. Pay-as-you-go and Pro customers can access transaction construction, signing, and broadcast. If you'd like to leverage gas sponsorship, please reach out! ### Construction and Broadcast #### EVM A successful EVM transaction requires: * **Transaction construction**: assembling the payload (recipient, value, calldata) * **Nonce**: set correctly to order transactions and prevent conflicts * **Gas and tip fee**: estimated to ensure inclusion even during network congestion * **Signature**: cryptographically signing the transaction with the sender's private key * **Broadcast**: submitting the signed transaction to the network and monitoring for inclusion 0xkey handles all of this for you via `ethSendTransaction`. Whether or not you use sponsorship, you pass through minimal payloads and we take care of the rest. We auto-fill any fields you omit. This endpoint supports arbitrary EVM transactions — not just simple sends. You can interact with smart contracts, deploy contracts, or execute any valid EVM operation. #### Solana A successful Solana transaction requires: * **Transaction construction**: assembling the list of instructions (program, accounts, data) * **Recent blockhash**: fetched and attached at broadcast time to ensure the transaction is valid * **Compute unit limit**: estimated and set to prevent failed transactions due to insufficient compute * **Priority fee**: set to ensure timely inclusion under current network conditions * **Signature**: cryptographically signing the transaction with the sender's private key * **Broadcast**: submitting the signed transaction to the network and monitoring for confirmation 0xkey handles all of this for you via `solSendTransaction`. Whether or not you use sponsorship, you pass through a minimal payload and we manage the rest. > [!NOTE] > > On Solana, fee sponsorship and rent sponsorship are separate. `Sponsor Solana > Rent` is disabled by default and must be enabled in the dashboard before > 0xkey will pre-fund rent for account creation. If created accounts are later > closed, refunded rent can go back to the signer rather than the sponsor. See > [Solana Rent Sponsorship](/networks/solana-rent-refunds). For payer behavior, > static-key requirements, and account-creation caveats in sponsored flows, see > [Solana transaction construction for sponsored flows](/networks/solana-transaction-construction). ### Transaction status and enriched errors After you send a transaction, 0xkey monitors its status until it fails or is confirmed on-chain. ### Transaction Statuses The following statuses apply to both EVM and Solana transactions: | **Status** | **Description** | | - | - | | INITIALIZED | 0xkey has constructed and signed the transaction and prepared fees, but it has not yet been broadcast. | | BROADCASTING | 0xkey is actively broadcasting the transaction to the network and awaiting inclusion. | | INCLUDED | The transaction has been included in a block (EVM) or confirmed on-chain (Solana). | | FAILED | The transaction could not be included on-chain and will not be retried automatically. | ### EVM Smart Contract Transaction Errors For EVM transactions that revert, 0xkey runs a simulation to produce structured execution traces and decode common revert reasons — giving you actionable error messages instead of opaque hex data. | **Error type** | **Description** | | :- | :- | | UNKNOWN | The transaction reverted during on-chain execution or simulation, but the revert reason could not be decoded (e.g. missing ABI or unverified contract). | | NATIVE | The transaction reverted due to a built-in Solidity error, such as `require()`, `assert()`, or a plain `revert()`. | | CUSTOM | The transaction reverted due to a contract-defined custom error declared using Solidity's `error` keyword. | > [!NOTE] > > These error types describe how an EVM smart contract reverted during on-chain execution or pre-flight simulation. 0xkey application-level errors (e.g. signing failures, policy rejections) are not classified here and are instead surfaced via `Error.Message`. ### Spend limits 0xkey provides tools to manage your gas sponsorship budget. You configure USD fee limits at two levels: across all orgs and per sub-org. This gives you control over both total spend and per-user spend. You can set limit values and time windows through the dashboard. You can query current gas usage and limits through our endpoints. > [!TIP] > > 0xkey provides fee sponsorship and transaction broadcasting services only. In high-fee or congested network conditions, delays or non-inclusion may occur. It is the developer's responsibility to ensure appropriate spend limits are in place. ### Policy engine You can write policies against both sponsored and non-sponsored transactions using 0xkey's policy DSL: * **EVM**: use the `eth.tx` namespace * **Solana**: use the `solana.tx` namespace This means you can seamlessly switch between sponsored and non-sponsored transactions and still use the same policies. *Note:* 0xkey sets all fee-related fields to 0 for sponsored transactions. ### Billing 0xkey passes transaction fee costs through to you as a line item at the end of the month. You pay based on the USD value of fees at time of broadcast; 0xkey internalizes the inventory risk of token price changes. Our battle-tested fee estimation aims to be cost-efficient while ensuring quick transaction inclusion. ### Advanced #### Gas sponsorship smart contracts (EVM) We could not find a satisfactory setup for gas sponsorship contracts that were both fast and safe, so we made our own. The contracts are open source and you can check them out on [GitHub](https://github.com/0xkey-io/gas-station). Based on our benchmarks, these are the most efficient gas sponsorship contracts on the market. They achieve this through optimized logic, calldata encoding, and extensive use of assembly, which reduces gas overhead per sponsored transaction. The result: lower costs for you and faster execution for your users. #### Security Some gas sponsorship setups by other providers are subject to replay attacks. If a malicious actor compromises the provider infrastructure, they can replay the gas sponsorship request multiple times with different nonces to create multiple transactions from a single request. At 0xkey, we never cut corners on security: we perform transaction construction in enclaves, and as long as the request includes the relevant nonce or blockhash, only one transaction can be created from it. Since the user's authenticator signs requests and the enclave verifies signatures, a malicious actor cannot modify or replay the request. This is in line with 0xkey's core system design principle: everything can be compromised outside of the enclaves and funds will still be safe. By default, our SDKs include a special gas station nonce for sponsored transaction requests. ### RPCs 0xkey's send transaction and transaction status endpoints eliminate the need for third-party RPC providers. You save costs and reduce latency because we holistically incorporate internal data and minimize external calls. ## Next steps For implementation guides, see: * [Sending Sponsored EVM Transactions (React)](/0xkey/roadmap) - Using `@0xkey-io/react-wallet-kit` * [Sending Sponsored Solana Transactions (React)](/embedded-wallets/code-examples/sending-sponsored-solana-transactions) - Using `@0xkey-io/react-wallet-kit` * [Sending Sponsored Transactions](/company-wallets/code-examples/sending-sponsored-transactions) - Using `@0xkey-io/core` directly # Best practices Source: https://docs.0xkey.io/concepts/users/best-practices This page describes some best practices to consider as you set up users and policies while getting ready for production. ## Managing users **Enforce a security policy of least privilege for your users** Users on 0xkey should have the minimum required privilege to accomplish their job. When setting up users, consider this for their access type and policies that will grant the user permissions. **Use user tags to create groups of users with equal permissions** Referencing user tags in policies instead of individual users allows for clearer management of permissions. **When creating new users, consider verifying onboarding before adding tags** When inviting a web user to your 0xkey organization, you should consider real-life verification to confirm that they have onboarded correctly before granting that user permissions via tags. Granting tags prior to verification could provide an attacker permissions in your 0xkey organization if they are able to access the signup link. **Regularly review and remove unused users, user tags, and policies** If a user is unused or the user has left your company, you should remove them from your 0xkey organization to avoid compromise. **Attach multiple authenticators to web users** This ensures you don't lose access to the user. If an authenticator is lost or stolen, log in immediately to remove that authenticator from the user, or notify someone in your organization with permissions to delete the user. It's best to use multiple types of authenticators to ensure the security of your account if one fails. ## Protecting API keys API keys allow programmatic access to 0xkey, and thus anyone with access to your API key has the same level of access to your 0xkey organization as you do. Consider the following to better protect your API keys and 0xkey organization. **Don't embed API keys directly in your code** This reduces the ways that a hacker could acquire your API key. Our SDKs and CLI enable you to reference your API keys so you don't have to put them directly in your code. **Use different API-only users for different applications** This allows you to isolate permissions and differentiate activities between those applications. In the case that an API key is lost or stolen, it also allows you to revoke access solely for the affected application. **Use a secret management system to protect your API keys** Tools like Hashicorp Vault or AWS KMS can help you protect your API key from malicious access. **Regularly remove any unused API keys** This reduces the chance that an old key can be used to access your 0xkey organization. ## Setting up policies **Apply least-privilege permissions** 0xkey's policy engine allows you to enforce permissions at a fine-grained level. When setting up your account, we suggest you use the principle of least privilege, meaning that a user only has the minimum permissions that are necessary to perform their job. Create policies that ensure that users have least-privilege permissions. **Apply consensus to sensitive actions** Sensitive actions like changing policies or signing transactions should be carefully controlled as they can lead to funds being moved off of the platform. You can apply consensus to actions like this to ensure that multiple approvals are required. For example, the policy below specifies that 2 total approvals, including the initiating approval, are required to create a new policy. ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "policyName": "Require 2 approvers for creating a policy", "effect": "EFFECT_ALLOW", "consensus": "approvers.count() >= 2", "condition": "activity.type == 'ACTIVITY_TYPE_CREATE_POLICY_V3'" } ``` **Be especially careful with the ability to add policies** Within this principle of least privilege, Some actions should be treated more sensitively: * Adding policies * Signing transactions **Use allowlisting if you only send to a set of addresses** If your use case for 0xkey only requires you to send funds to a certain set of crypto addresses, you should set a policy that allowlists those addresses. See below for an example policy. ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "policyName": "ETH address whitelist", "effect": "EFFECT_ALLOW", "condition": "eth.tx.to == ''" } ``` # Credentials Source: https://docs.0xkey.io/concepts/users/credentials Credentials represent ways for Users to authenticate to 0xkey. All 0xkey Credentials are held by you, the end-user. 0xkey only keeps **public keys**. At the moment, 0xkey supports 2 types of Credentials: * Authenticators * API Keys Note that every 0xkey user needs at least one long-lived credential (a passkey, or non-expiring API key). This is to prevent users from getting locked out of their accounts. The exception is if the user belongs to a suborg, and [Email Auth](/authentication/email) is enabled for that sub-organization. ### Authenticators 0xkey uses [Webauthn](https://www.w3.org/TR/webauthn-2/) for authentication into its dashboard (no passwords!). Authenticators on 0xkey represent a Webauthn device registered on 0xkey. When logging into 0xkey, you'll be prompted for a signature with a registered device. This signature is then verified to grant dashboard access. To avoid repeated signatures, 0xkey's dashboard uses session cookies for read traffic. However, all write actions require an authenticator signature. ### API keys 0xkey API requests are authenticated with API key signatures. When you generate an API key (either through our CLI or through our dashboard), you generate a P-256 key pair. 0xkey keeps the public key, and you hold the private key. Requests made via SDK or CLI use the private API key to sign requests. 0xkey's public API expects all requests (e.g. to get data or to submit activities) to be signed. See our [API reference](/api-reference/api-keys/create-api-keys) for how to programmatically create API keys. # Introduction to users Source: https://docs.0xkey.io/concepts/users/introduction 0xkey users are resources within organizations or sub-organizations that can submit activities to 0xkey via a valid credential (e.g., API key, passkey). These requests can be made either by making direct API calls or through the 0xkey Dashboard. Users must have at least one valid credential (one of API key, passkey), with upper limits on credentials defined here in our [resource limits](/concepts/resource-limits). Users can also have associated “tags” which are logical groupings that can be referenced in policies. Users can only submit activities within their given organization — they cannot take action across organizations. A User's attributes are: * UUID: a globally unique ID (e.g. `fc6372d1-723d-4f7e-8554-dc3a212e4aec`), used as a unique identifier for a User in the context of Policies or User Tags, or Quorums. * Name and email * Authenticators: a list of authenticators (see below for information) * API key: a list of API keys (see below for information) * User tags: a list of User Tag UUIDs A **user belongs to one organization**, and one organization can have many (**up to 100**) users. If you need to create more users, consider using Sub-Organizations. # Root quorum Source: https://docs.0xkey.io/concepts/users/root-quorum When you create a 0xkey organization, your user is created and will default to being the sole member of the root quorum. Because of the wide scope of permissions, it is important to take care when using any users in the root quorum. The following offers a technical overview and some best practices. ## Technical overview The root quorum is a group of users who can execute any action and bypass the policy engine. The root quorum is defined by * `userIds`: the Ids of users who compose the quorum set * `threshold`: the number of quorum members required to execute an action as root Actions approved by the root quorum do not go through the policy engine; thus it is impossible to limit root quorum actions with any policies. The reason the root must be able to bypass the policy engine is that it is the only way for an organization to unbrick itself if it sets overly restrictive policies that do not allow it to update itself. We can refer to a root quorum configuration as `threshold / userIds.length`. So a quorum with a threshold of 2 and set size of 5 can be referred to as `2 / 5`. ### Defaults When you create an organization, the root quorum will default to being your user and a threshold of 1. ### Updating the root quorum Only the current root quorum can approve updates to the quorum. It is not possible to add editing permissions to the root quorum through policies. Both the website and public APIs expose the ability to update the root quorum. ## Best practices ### Limit tasks you perform with the root quorum The root quorum should only be used in cases where it is absolutely necessary. In particular, the root quorum should primarily be used to unblock an organization in the event of incorrect policies or lockout. For example, if you accidentally set overly-restrictive policies that prevent users from taking any action, the root quorum can be used to delete the relevant policies. ### Create scoped users for day-to-day actions Ensure that you have scoped policies for day-to-day actions that you expect to complete. For example, you may have an API user with permissions to only create sub-organizations. You can read more about creating policies in our [Policy Overview](/policies/overview). ### Using root users with policies We generally recommend creating non-root users for day-to-day operations and granting them narrowly scoped permissions via policies. However, root users can also be granted the ability to act without quorum approval for specific actions. By defining an explicit policy, you can allow an individual root user to perform certain activities without requiring approvals from the other root users, even if the organization’s root quorum threshold would normally require it. In other words, even if your organization enforces a root quorum with a threshold greater than 1 (for example, 2 / 3), a policy can allow a specific root user to independently perform the activity covered by that policy, while all other activities continue to require quorum approval. ### Configuration considerations There are primarily two factors to consider when setting the root quorum * how hard is it to get locked out of root? I.E. how many authenticators need to be lost/destroyed so the threshold cannot be met. * how many authenticators need to be compromised for an attacker to take root actions? For example, if a quorum is configured as 2/5, then * if 4 users lost all their authenticators, no root actions could be taken (including updating the quorum itself). * if 2 different users authenticators are compromised, an attacker could steal all the organizations funds. **Example Setups** The below examples are provided as a convenience only. It is up to you to ensure that the root quorum setup you design is appropriate for your particular circumstances in order to secure your organization and minimize the risk of lockout of root functionality. Failure to properly configure your root quorum setup could result in complete loss of funds. *High Value Organization* Special users should be created that are only used for root actions. Those users' authenticators should be stored in geographically distributed locations that have personal access controls, are natural disaster resistant, and have redundancy in case of hardware failure. These would only be used in the case of a disaster. For day to day admin operations, admin policies that use consensus can be put in place. These can be a set of finely scoped policies. *Low Value, End-User Directed Organization* The end-user and the business both have one user in the organization. The root quorum would be configured as a 1/2, which includes the business and end-users' Users. This allows the business support channel to unbrick the user if they lose access to their account or otherwise add overly restrictive policies. ### Monitor for unintended use Monitor your account for any unexpected activities coming from the root users. If you see an unexpected activity, you should remove any compromised authenticators or API keys. # Wallets Source: https://docs.0xkey.io/concepts/wallets A [hierarchical deterministic (HD) wallet](https://learnmeabitcoin.com/technical/hd-wallets) is a collection of cryptographic private/public key pairs that share a common seed. A wallet is used to generate accounts. ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "walletId": "eb98ae4c-07eb-4117-9b2d-8a453c0e1e64", "walletName": "default" } ``` #### Configuration Wallet seeds are generated with a default mnemonic length of 12 words. The [BIP-39 specification](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) supports mnemonic lengths of 12, 15, 18, 21, and 24 words. To enhance your Wallet's security, you may consider opting for a longer mnemonic length. This optional `mnemonicLength` field can be set when creating a Wallet. It's important to note that once the Wallet seed is generated, the mnemonic is permanent and cannot be altered. ## Accounts An account contains the directions for deriving a cryptographic key pair and corresponding address from a Wallet. In practice, this looks like: * The Wallet seed and Account curve are used to create a root key pair * The Account path format and path are used to derive an extended key pair from the root key pair * The Account address format is used to derive the address from the extended public key ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "address": "0x7aAE6F67798D1Ea0b8bFB5b64231B2f12049DB5e", "addressFormat": "ADDRESS_FORMAT_ETHEREUM", "curve": "CURVE_SECP256K1", "path": "m/44'/60'/0'/0/0", "pathFormat": "PATH_FORMAT_BIP32", "walletId": "eb98ae4c-07eb-4117-9b2d-8a453c0e1e64" } ``` **The account address is used to sign with the underlying extended private key.** #### HD wallet default paths HD wallets use standardized derivation paths to generate multiple accounts from a single seed. These paths follow a specific structure that allows for consistent address generation across different wallet implementations. Here are common default paths for some of the ecosystems supported by 0xkey: * Ethereum: `m/44'/60'/0'/0/0` * Cosmos: `m/44'/118'/0'/0/0` * Solana: `m/44'/501'/0'/0'` For a complete list of coin types and possible HD paths, refer to the [SLIP-0044 specification](https://github.com/satoshilabs/slips/blob/master/slip-0044.md). #### Address formats and curves See below for specific address formats that you can currently derive on 0xkey: | Type | Address Format | Curve | Default HD Path | | - | - | - | - | | n/a | ADDRESS_FORMAT_COMPRESSED | CURVE_SECP256K1 | m/0'/0 | | n/a | ADDRESS_FORMAT_COMPRESSED | CURVE_ED25519 | m/0'/0 | | n/a | ADDRESS_FORMAT_UNCOMPRESSED | CURVE_SECP256K1 | m/0'/0 | | Ethereum | ADDRESS_FORMAT_ETHEREUM | CURVE_SECP256K1 | m/44'/60'/0'/0/0 | | Cosmos | ADDRESS_FORMAT_COSMOS | CURVE_SECP256K1 | m/44'/118'/0'/0/0 | | Solana | ADDRESS_FORMAT_SOLANA | CURVE_ED25519 | m/44'/501'/0'/0 | | Tron | ADDRESS_FORMAT_TRON | CURVE_SECP256K1 | m/44'/195'/0'/0/0 | | Sui | ADDRESS_FORMAT_SUI | CURVE_ED25519 | m/44'/784'/0'/0/0 | | Aptos | ADDRESS_FORMAT_APTOS | CURVE_ED25519 | m/44'/637'/0'/0'/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_MAINNET_P2PKH | CURVE_SECP256K1 | m/44'/0'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_MAINNET_P2SH | CURVE_SECP256K1 | m/49'/0'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_MAINNET_P2WPKH | CURVE_SECP256K1 | m/84'/0'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_MAINNET_P2WSH | CURVE_SECP256K1 | m/48'/0'/0'/2'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_MAINNET_P2TR | CURVE_SECP256K1 | m/86'/0'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_TESTNET_P2PKH | CURVE_SECP256K1 | m/44'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_TESTNET_P2SH | CURVE_SECP256K1 | m/49'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_TESTNET_P2WPKH | CURVE_SECP256K1 | m/84'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_TESTNET_P2WSH | CURVE_SECP256K1 | m/48'/1'/0'/2'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_TESTNET_P2TR | CURVE_SECP256K1 | m/86'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_SIGNET_P2PKH | CURVE_SECP256K1 | m/44'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_SIGNET_P2SH | CURVE_SECP256K1 | m/49'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_SIGNET_P2WPKH | CURVE_SECP256K1 | m/84'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_SIGNET_P2WSH | CURVE_SECP256K1 | m/48'/1'/0'/2'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_SIGNET_P2TR | CURVE_SECP256K1 | m/86'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_REGTEST_P2PKH | CURVE_SECP256K1 | m/44'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_REGTEST_P2SH | CURVE_SECP256K1 | m/49'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_REGTEST_P2WPKH | CURVE_SECP256K1 | m/84'/1'/0'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_REGTEST_P2WSH | CURVE_SECP256K1 | m/48'/1'/0'/2'/0/0 | | Bitcoin | ADDRESS_FORMAT_BITCOIN_REGTEST_P2TR | CURVE_SECP256K1 | m/86'/1'/0'/0/0 | | Sei | ADDRESS_FORMAT_SEI | CURVE_ED25519 | m/44'/118'/0'/0/0 | | Stellar | ADDRESS_FORMAT_XLM | CURVE_ED25519 | m/44'/148'/0'/0'/0 | | Dogecoin | ADDRESS_FORMAT_DOGE_MAINNET | CURVE_SECP256K1 | m/44'/3'/0'/0/0 | | Dogecoin | ADDRESS_FORMAT_DOGE_TESTNET | CURVE_SECP256K1 | m/44'/1'/0'/0/0 | | TON | ADDRESS_FORMAT_TON_V3R2 | CURVE_ED25519 | m/44'/607'/0'/0/0 | | TON | ADDRESS_FORMAT_TON_V4R2 | CURVE_ED25519 | m/44'/607'/0'/0/0 | | XRP | ADDRESS_FORMAT_XRP | CURVE_SECP256K1 | m/44'/144'/0'/0/0 | | FLARE | ADDRESS_FORMAT_ETHEREUM | CURVE_SECP256K1 | m/44'/60'/0'/0/0 | | Spark | ADDRESS_FORMAT_SPARK_MAINNET | CURVE_SECP256K1 | m/8797555'/0'/0' | | Spark | ADDRESS_FORMAT_SPARK_REGTEST | CURVE_SECP256K1 | m/8797555'/0'/0' | #### Where can I learn more? In addition to the guide mentioned above on [HD Wallets](https://learnmeabitcoin.com/technical/hd-wallets), there is also a page specifically on [Derivation Paths](https://learnmeabitcoin.com/technical/derivation-paths). #### What if I don't see the address format for my network? You can use `ADDRESS_FORMAT_COMPRESSED` to generate a public key which can be used to sign with (only sign raw payloads supported). #### What is the difference between sign transaction and sign raw payload ? [SignRawPayload](https://docs.0xkey.io/api-reference/activities/sign-raw-payload): network-agnostic, curve-based signing of messages. [SignTransaction](https://docs.0xkey.io/api-reference/activities/sign-transaction): network-specific transaction signing, including [transaction parsing](https://docs.0xkey.io/networks/overview#:~:text=Tier%204%3A%20Transaction%20parsing%20and%20policy%20creation) and compatibility with our policy engine. #### What if I don't see the curve for my network? Contact us at [hello@0xkey.io](mailto:hello@0xkey.io). ## Delete wallets To delete wallets you can call the [delete wallets activity](/api-reference/wallets/delete-wallets). Before deleting a wallet it must have been exported to prevent loss of funds, or you can pass in the `deleteWithoutExport` parameter with the value `true` to override this. The `deleteWithoutExport` parameter, if not passed in, is default `false`. Note that this activity must be initiated by the wallet owner. ## Private keys 0xkey also supports raw private keys, but we recommend using Wallets since they offer several advantages: * Wallets can be used across various cryptographic curves * Wallets can generate millions of addresses for various digital assets * Wallets can be represented by a checksummed, mnemonic phrase making them easier to backup and recover ## Export keys Exporting on 0xkey enables you or your end users to export a copy of a Wallet or Private Key from our system at any time. While most 0xkey users opt to keep Wallets within 0xkey's secure infrastructure, the export functionality means you are never locked into 0xkey, and gives you the freedom to design your own backup processes as you see fit. Check out our [Export Wallet guide](/wallets/export-wallets) to allow your users to securely export their wallets. ## Import keys Importing on 0xkey enables you or your end users to import a Wallet or Private Key to our system. Check out our [Import Wallet guide](/wallets/import-wallets) to allow your users to securely import their wallets. ## Delete keys To delete private keys you can call the [delete private keys activity](/api-reference/private-keys/delete-private-keys). Before deleting a private key it must have been exported to prevent loss of funds, or you can pass in the `deleteWithoutExport` parameter with the value `true` to override this. The `deleteWithoutExport` parameter, if not passed in, is default `false`. Note that this activity must be initiated by the private key owner. # Errors Source: https://docs.0xkey.io/developer-reference/api-overview/errors How 0xkey APIs report errors, which responses carry an errorCode, and troubleshooting for common messages. ## Public API errors A failed request to the Public API (`https://api.0xkey.io`) returns the gRPC status of the call as JSON, with the matching HTTP status code: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "code": 3, "message": "organization mismatch: request is targeting organization (\"USER SUB ORG\"), but voters are in organization (\"OUR MAIN ORG\")", "details": [] } ``` | Field | Meaning | | :- | :- | | `code` | [gRPC status code](#grpc-error-codes). `3` is `INVALID_ARGUMENT`, returned with HTTP 400. | | `message` | Human-readable description of the failure. See [Detailed error messages](#detailed-error-messages) below. | | `details` | Currently always empty. | The JavaScript SDKs raise this as a `ZeroXKeyRequestError` with `code` and `details` properties. Its message reads: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} 0xkey error 3: organization mismatch: request is targeting organization ("USER SUB ORG"), but voters are in organization ("OUR MAIN ORG") (Details: []) ``` > [!WARNING] > > Public API errors do not include a categorized `errorCode` today. This is a known gap. Until it is closed, use the HTTP status or the gRPC `code` for broad handling (for example, retry `UNAVAILABLE` with backoff and re-authenticate on `UNAUTHENTICATED`), and show or log `message`. Do not parse `message`: it is written for people and can change. ## Rate limiting A request over its rate limit gets HTTP `429` with a `Retry-After` header (seconds) and `ratelimit-limit`, `ratelimit-remaining`, `ratelimit-reset`, `X-0xkey-RateLimit-Lane` and `X-0xkey-RateLimit-Scope` headers. If the request sends `Accept: application/problem+json`, the body is a [problem details](https://www.rfc-editor.org/rfc/rfc9457) document; otherwise it is the plain-text message `Too many requests. Please wait and try again in a few seconds`. ### Rate limit exceeded ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "type": "https://docs.0xkey.io/developer-reference/api-overview/errors#rate-limit-exceeded", "title": "Rate limit exceeded", "status": 429, "detail": "Too many requests. Please wait and try again in a few seconds", "code": "RATE_LIMIT_EXCEEDED", "lane": "activity", "scope": "root", "tightestScopes": ["root"], "retryAfterMs": 1000, "limit": 10, "burst": 20, "remaining": 0, "requestId": "..." } ``` `lane` is `query`, `activity` or `chain_expensive`; `scope` names the bucket that ran out. Wait at least `Retry-After` (or `retryAfterMs`) before retrying. ### Rate limit backend unavailable If the rate limiter itself cannot be reached, the request is rejected with HTTP `503`, `Retry-After: 1` and, for `application/problem+json` requests, `"code": "RATE_LIMIT_BACKEND_UNAVAILABLE"` with `type` `https://docs.0xkey.io/developer-reference/api-overview/errors#rate-limit-backend-unavailable`. Retry after a short delay. ## Pay API errors The Pay API (`https://api-pay.0xkey.io`, used by `@0xkey-io/pay`) returns a fixed error body on every non-2xx response from its payment endpoints: `GET /{network}/supported`, `POST /{network}/verify`, `POST /{network}/settle`, `POST /{network}/v1/settlements/charge`, `GET /{network}/v1/payments/{paymentId}`, and the organization payment reads `GET /{network}/v1/organizations/{organizationId}/payments` and `.../payments/{paymentId}`, where `network` is `base-mainnet` or `base-sepolia`. ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "errorCode": "PAYMENT_REQUEST_INVALID", "retryable": false } ``` | Field | Meaning | | :- | :- | | `errorCode` | Stable, machine-readable code. Branch on this field. | | `retryable` | Whether repeating the same request can succeed. | | `paymentId` | Present when the error concerns a known payment, for example with `PAYMENT_STATUS_UNKNOWN`. | `errorCode` is one of `PAYMENT_REQUEST_INVALID`, `PAYMENT_NETWORK_MISMATCH`, `PAYMENT_REQUIREMENTS_UNSUPPORTED`, `PAYMENT_AUTH_INVALID`, `PAYMENT_AUTH_FORBIDDEN`, `PAYMENT_AUTH_UNAVAILABLE`, `PAYMENT_INTENT_CONFLICT`, `PAYMENT_PROTOCOL_MISMATCH`, `PAYMENT_REVISION_MISMATCH`, `PAYMENT_NOT_FOUND`, `PAYMENT_SERVICE_UNAVAILABLE`, `PAYMENT_STATUS_UNKNOWN`, `PAYMENT_NOT_FULFILLABLE` or `FULFILLMENT_PERSISTENCE_UNAVAILABLE`. `PAYMENT_STATUS_UNKNOWN` is returned with HTTP 503 and `Retry-After: 2`; look the payment up again by `paymentId` instead of resubmitting it. The readiness probe `GET /ready` reports an unavailable or misconfigured dependency with HTTP 503 and `{"status": "unavailable", "errorCode": "...", "retryable": true | false}`, where `errorCode` is `PAY_GATEWAY_CONFIGURATION_INVALID`, `COORDINATOR_UNAVAILABLE`, `REPLAY_STORE_UNAVAILABLE` or `FACILITATOR_UNAVAILABLE`. ## Detailed error messages The below table enumerates common errors across different actions that can be taken using the API. It contains GRPC codes, HTTP codes, and error messages. More on GRPC error codes [below](#grpc-error-codes). Click on the message to view detailed explanation of possible causes and troubleshooting tips for that specific error. | GRPC Code | HTTP Code | Message | | :- | :- | :- | | InvalidArgument | 400 | [malformed organization ID provided](#malformed-organization-id-provided) | | InvalidArgument | 400 | [bad request body](#bad-request-body) | | InvalidArgument | 400 | [failed to load organizations](#failed-to-load-organizations) | | InvalidArgument | 400 | [policy label must be unique](#policy-label-must-be-unique) | | InvalidArgument | 400 | [invalid policy consensus](#invalid-policy-consensus) | | InvalidArgument | 400 | [invalid policy condition](#invalid-policy-condition) | | InvalidArgument | 400 | [policy condition is required](#policy-condition-is-required) | | InvalidArgument | 400 | [quorum threshold must be non-zero integer](#quorum-threshold-must-be-non-zero-integer) | | InvalidArgument | 400 | [quorum users missing](#quorum-users-missing) | | InvalidArgument | 400 | [invalid api key expiration](#invalid-api-key-expiration) | | InvalidArgument | 400 | [missing parameter: user authenticator attestation](#missing-parameter-user-authenticator-attestation) | | InvalidArgument | 400 | [invalid authenticator attestation](#invalid-authenticator-attestation) | | InvalidArgument | 400 | [missing parameter: user authenticator attestation auth data](#missing-parameter-user-authenticator-attestation-auth-data) | | InvalidArgument | 400 | [missing wallet params](#missing-wallet-params) | | InvalidArgument | 400 | [invalid path format](#invalid-path-format) | | InvalidArgument | 400 | [invalid path](#invalid-path) | | InvalidArgument | 400 | [invalid address format](#invalid-address-format) | | InvalidArgument | 400 | [invalid curve](#invalid-curve) | | InvalidArgument | 400 | [curve required](#curve-required) | | InvalidArgument | 400 | [invalid payload encoding](#invalid-payload-encoding) | | InvalidArgument | 400 | [invalid hash function](#invalid-hash-function) | | InvalidArgument | 400 | [invalid magic link template](#invalid-magic-link-template) | | InvalidArgument | 400 | [failed to get email template contents](#failed-to-get-email-template-contents) | | InvalidArgument | 400 | [failed to unmarshal template variables](#failed-to-unmarshal-template-variables) | | InvalidArgument | 400 | [organization mismatch](#organization-mismatch) | | InvalidArgument | 400 | [Wallet not found](#wallet-not-found) | | InvalidArgument | 400 | [invalid wallet account UUID](#invalid-wallet-account-uuid) | | InvalidArgument | 400 | [wallet account not part of your organization](#wallet-account-not-part-of-your-organization) | | InvalidArgument | 400 | [wallet account has not been exported](#wallet-account-has-not-been-exported) | | InvalidArgument | 400 | [invalid OIDC token](#invalid-oidc-token) | | InvalidArgument | 400 | [invalid email address](#invalid-email-address) | | InvalidArgument | 400 | [could not reach email](#could-not-reach-email) | | InvalidArgument | 400 | [auth_code must be set](#oauth2-parameter-errors) | | InvalidArgument | 400 | [code_verifier must be set](#oauth2-parameter-errors) | | InvalidArgument | 400 | [oauth2_credential_id must be set](#oauth2-parameter-errors) | | InvalidArgument | 400 | [redirect_uri must be set](#oauth2-parameter-errors) | | InvalidArgument | 400 | [client_id must be set](#oauth2-parameter-errors) | | Unauthenticated | 401 | [no valid authentication signature found for request](#no-valid-authentication-signature-found-for-request) | | Unauthenticated | 401 | [could not find public key in organization](#could-not-find-public-key-in-organization) | | Unauthenticated | 401 | [failed while looking up public key in parent organization](#failed-while-looking-up-public-key-in-parent-organization) | | Unauthenticated | 401 | [could not find public key in organization or its parent organization](#could-not-find-public-key-in-organization-or-its-parent-organization) | | Unauthenticated | 401 | [could not verify WebAuthN signature](#could-not-verify-webauthn-signature) | | Unauthenticated | 401 | [credential ID could not be found in organization or its parent organization](#credential-id-could-not-be-found-in-organization-or-its-parent-organization) | | Unauthenticated | 401 | [public key could not be found in organization or its parent organization](#public-key-could-not-be-found-in-organization-or-its-parent-organization) | | Unauthenticated | 401 | [more than one suborg associated with a credential ID](#more-than-one-suborg-associated-with-a-credential-id) | | Unauthenticated | 401 | [more than one suborg associated with a public key](#more-than-one-suborg-associated-with-a-public-key) | | Unauthenticated | 401 | [could not verify api key signature](#could-not-verify-api-key-signature) | | Unauthenticated | 401 | [expired api key](#expired-api-key) | | Unauthenticated | 401 | [malformed activity stamp](#malformed-activity-stamp) | | Unauthenticated | 401 | [could not extract webauthn stamp](#could-not-extract-webauthn-stamp) | | Unauthenticated | 401 | [could not extract api key stamp](#could-not-extract-api-key-stamp) | | Unauthenticated | 401 | [cannot authenticate public API activity request without a stamp (X-Stamp/X-Stamp-Webauthn header)](#cannot-authenticate-public-api-activity-request-without-a-stamp-x-stampx-stamp-webauthn-header) | | PermissionDenied | 403 | [request not authorized](#request-not-authorized) | | PermissionDenied | 403 | [api operations disabled](#api-operations-disabled) | | PermissionDenied | 403 | [authentication failed](#authentication-failed) | | NotFound | 404 | [webauthn authenticator not found in organization](#webauthn-authenticator-not-found-in-organization) | | NotFound | 404 | [webauthn authenticator not found in organization or parent organization](#webauthn-authenticator-not-found-in-organization-or-parent-organization) | | NotFound | 404 | [no organization found with the given ID](#no-organization-found-with-the-given-id) | | NotFound | 404 | [No activity found with fingerprint. Consensus activities must target an existing activity by fingerprint](#no-activity-found-with-fingerprint-consensus-activities-must-target-an-existing-activity-by-fingerprint) | | NotFound | 404 | [Policy not found](#policy-not-found) | | NotFound | 404 | [Wallet not found](#wallet-not-found) | | ResourceExhausted | 429 | [user has exceeded maximum authenticators](#user-has-exceeded-maximum-authenticators) | | ResourceExhausted | 429 | [user has exceeded maximum long-lived api keys](#user-has-exceeded-maximum-long-lived-api-keys) | | ResourceExhausted | 429 | [user has exceeded maximum short-lived api keys](#user-has-exceeded-maximum-short-lived-api-keys) | | ResourceExhausted | 429 | [this organization cannot execute activities because it is over its allotted quota. Please reach out to the 0xkey team (hello@0xkey.io) for more information.](#this-organization-cannot-execute-activities-because-it-is-over-its-allotted-quota-please-reach-out-to-the-oxkey-team-help0xkeycom-for-more-information) | | ResourceExhausted | 429 | [this sub-organization cannot execute activities because its parent is over its allotted quota. Please reach out to the 0xkey team (hello@0xkey.io) for more information.](#this-sub-organization-cannot-execute-activities-because-its-parent-is-over-its-allotted-quota-please-reach-out-to-the-oxkey-team-help0xkeycom-for-more-information) | | ResourceExhausted | 429 | [this organization cannot execute activities because it has been rate limited. Please reach out to the 0xkey team (hello@0xkey.io) for more information.](#this-organization-cannot-execute-activities-because-it-has-been-rate-limited-please-reach-out-to-the-oxkey-team-help0xkeycom-for-more-information) | | ResourceExhausted | 429 | [this sub-organization cannot execute activities because its parent has been rate limited. Please reach out to the 0xkey team (hello@0xkey.io) for more information.](#this-sub-organization-cannot-execute-activities-because-its-parent-has-been-rate-limited-please-reach-out-to-the-oxkey-team-help0xkeycom-for-more-information) | | Internal | 500 | [internal server error](#internal-server-error) | ## GRPC error codes The Public API reports every error as a gRPC status: the `code` field of the response body, also shown after `0xkey error` in SDK messages. Together with the HTTP status it is the only machine-readable classification of Public API errors today (see [Public API errors](#public-api-errors)). In the following example `0xkey error 3:` is gRPC code 3, `INVALID_ARGUMENT`, followed by the 0xkey error message. Example ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} 0xkey error 3: organization mismatch: request is targeting organization ("USER SUB ORG"), but voters are in organization ("OUR MAIN ORG") ``` ### GRPC status codes reference | Code | Number | Description | | - | - | - | | OK | 0 | Not an error; returned on success. | | CANCELLED | 1 | The operation was cancelled, typically by the caller. | | UNKNOWN | 2 | Unknown error. For example, this error may be returned when a `Status` value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error. | | INVALID_ARGUMENT | 3 | The client specified an invalid argument. Note that this differs from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name). | | DEADLINE_EXCEEDED | 4 | The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long | | NOT_FOUND | 5 | Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, `NOT_FOUND` may be used. If a request is denied for some users within a class of users, such as user-based access control, `PERMISSION_DENIED` must be used. | | ALREADY_EXISTS | 6 | The entity that a client attempted to create (e.g., file or directory) already exists. | | PERMISSION_DENIED | 7 | The caller does not have permission to execute the specified operation. `PERMISSION_DENIED` must not be used for rejections caused by exhausting some resource (use `RESOURCE_EXHAUSTED` instead for those errors). `PERMISSION_DENIED` must not be used if the caller can not be identified (use `UNAUTHENTICATED` instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions. | | RESOURCE_EXHAUSTED | 8 | Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space. | | FAILED_PRECONDITION | 9 | The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: (a) Use `UNAVAILABLE` if the client can retry just the failing call. (b) Use `ABORTED` if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use `FAILED_PRECONDITION` if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, `FAILED_PRECONDITION` should be returned since the client should not retry unless the files are deleted from the directory. | | ABORTED | 10 | The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`. | | OUT_OF_RANGE | 11 | The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike `INVALID_ARGUMENT`, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate `INVALID_ARGUMENT` if asked to read at an offset that is not in the range \[0,2^32-1], but it will generate `OUT_OF_RANGE` if asked to read from an offset past the current file size. There is a fair bit of overlap between `FAILED_PRECONDITION` and `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific error) when it applies so that callers who are iterating through a space can easily look for an `OUT_OF_RANGE` error to detect when they are done. | | UNIMPLEMENTED | 12 | The operation is not implemented or is not supported/enabled in this service. | | INTERNAL | 13 | Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors. | | UNAVAILABLE | 14 | The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations. | | DATA_LOSS | 15 | Unrecoverable data loss or corruption. | | UNAUTHENTICATED | 16 | The request does not have valid authentication credentials for the operation. | Source: [https://grpc.io/docs/guides/status-codes/](https://grpc.io/docs/guides/status-codes/) ## Troubleshooting ### no organization found with the given ID Common causes: * An unknown organization ID was passed in a request made to the 0xkey API Troubleshooting tips: * Confirm that you are using the proper Organization ID. All 0xkey resources are identified with a UUID, so confirm you are not passing a different resource's UUID as the organization ID in your request. ### malformed organization ID provided Common causes: * An improperly formatted organization ID UUID was passed in a request made to the 0xkey API Troubleshooting tips: * Confirm the the UUID conforms to the UUID standard `XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX` ### bad request body Common causes: * A malformed request body was passed in a request made to the Turnky API Troubleshooting tips: * A typical activity request has the `type`, `timestampMS`, and `organizationId` parameters at the top level and then a `parameters` parameter with more specific parameters based on the request type. For example a CREATE_WALLET activity request body might look something like this: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "type": "ACTIVITY_TYPE_CREATE_WALLET", "timestampMs": "", "organizationId": "string", "parameters": { "walletName": "string", "accounts": [ { "curve": "CURVE_SECP256K1", "pathFormat": "PATH_FORMAT_BIP32", "path": "string", "addressFormat": "ADDRESS_FORMAT_UNCOMPRESSED" } ], "mnemonicLength": 0 } } ``` * A get resource request body might look slightly different with less fields. An example of a GET_WALLET request body looks something like this: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "organizationId": "string", "walletId": "string" } ``` ### api operations disabled Common causes: * 0xkey has disabled API operations globally. Troubleshooting tips: * This situation will only happen in the most extreme case and should not be something you need to worry about. ### this organization cannot execute activities because it is over its allotted quota. Please reach out to the 0xkey team ([hello@0xkey.io](mailto:hello@0xkey.io)) for more information. Common causes: * You have exceeded your monthly signing quota. The first 25 signatures a month are free for "free" users. * You have reached a resource limit on a particular resource. You can find out about our resource limits [here](/concepts/resource-limits). Troubleshooting tips: * If you need to increase your signature limit take a look at our [pricing page](https://0xkey.io/contact-us) and contact us at [hello@0xkey.io](mailto:hello@0xkey.io)! * Resource limits are imposed globally and cannot be increased, speak with our team at [hello@0xkey.io](mailto:hello@0xkey.io) to understand how to better integrate 0xkey with your system to utilize 0xkey to its highest potential. ### this sub-organization cannot execute activities because its parent is over its allotted quota. Please reach out to the 0xkey team ([hello@0xkey.io](mailto:hello@0xkey.io)) for more information. Common causes: * You have exceeded your monthly signing quota. The first 25 signatures a month are free for "free" users. * You have reached a resource limit on a particular resource. You can find out about our resource limits [here](/concepts/resource-limits). Troubleshooting tips: * If you need to increase your signature limit take a look at our [pricing page](https://0xkey.io/contact-us) and contact us at [hello@0xkey.io](mailto:hello@0xkey.io)! * Resource limits are imposed globally and cannot be increased, speak with our team at [hello@0xkey.io](mailto:hello@0xkey.io) to understand how to better integrate 0xkey with your system to utilize 0xkey to its highest potential. ### this organization cannot execute activities because it has been rate limited. Please reach out to the 0xkey team ([hello@0xkey.io](mailto:hello@0xkey.io)) for more information. Common causes: * You have exceeded your rate limit. We need to maintain a per-customer rate limit to ensure that the service we provide to all of our customers service can be exceptional. Troubleshooting tips: * If you are interested in increasing your rate limit reach out to us at [hello@0xkey.io](mailto:hello@0xkey.io)! ### this sub-organization cannot execute activities because its parent has been rate limited. Please reach out to the 0xkey team ([hello@0xkey.io](mailto:hello@0xkey.io)) for more information. Common causes: * You have exceeded your rate limit. We need to maintain a per-customer rate limit to ensure that the service we provide to all of our customers service can be exceptional. Troubleshooting tips: * If you are interested in increasing your rate limit reach out to us at [hello@0xkey.io](mailto:hello@0xkey.io)! ### request not authorized Common causes: * A user that created a request is not allowed to complete the action that was requested. * For example a parent-organization trying to create a wallet within a sub-organization that does not have a delegated access API key. Troubleshooting tips: * Confirm that you are using the correct credentials for the request you are making. * Confirm that all necessary [policies](/policies/overview) are in place so that the action that is requested can be performed. ### no valid authentication signature found for request Common causes: * No signature, or [stamp](/developer-reference/api-overview/stamps), is attached to a request. All requests made to 0xkey's api must be stamped so that 0xkey can authenticate and authorize the user who performed the request. Troubleshooting tips: * Take a look at the page on [stamps](/developer-reference/api-overview/stamps) to get some information about stamps, what they are, and how they are created. * At a base level our SDK's abstract away the complicated stamping process for you. [Here](https://github.com/0xkey-io/sdk-js/tree/main/examples) are some example projects with our JS/TS SDK to get you started! ### could not find public key in organization Common causes: * The public key corresponding to the signature in a stamp is not found in the organization the request is targeting. This means that a request was formatted properly, but the authenticator used to create the request is not associated with the organization that the request was made for. Troubleshooting tips: * Ensure that you have added the proper authenticators to the organization you are targeting. * Ensure that you are targeting the proper organization. ### failed while looking up public key in parent organization Common causes: * The public key corresponding to the signature in a stamp is not found in the organization the request is targeting. This means that a request was formatted properly, but the authenticator used to create the request is not associated with the organization that the request was made for. Troubleshooting tips: * Ensure that you have added the proper authenticators to the organization you are targeting. * Ensure that you are targeting the proper organization. ### could not find public key in organization or its parent organization Common causes: * The public key corresponding to the signature in a stamp is not found in the organization the request is targeting. This means that a request was formatted properly, but the authenticator used to create the request is not associated with the organization that the request was made for. Troubleshooting tips: * Ensure that you have added the proper authenticators to the organization you are targeting. * Ensure that you are targeting the proper organization. ### could not verify WebAuthN signature Common causes: * The signature used to create a stamp for a request cannot be verified for the organization the request is targeting. Again this means the request is formatted properly, but the authenticator used to create the request is not associated with the organization that the request was made for. Troubleshooting tips: * Ensure that you have added the proper authenticators to the organization you are targeting. * Ensure that you are targeting the proper organization. ### credential ID could not be found in organization or its parent organization Common causes: * 0xkey cannot translate a public key obtained from a stamp that was created with a WebAuthn authenticator to a parent organization or one of its corresponding sub-organizations that the request was made for. Troubleshooting tips: * Ensure that you have added the proper authenticators to the organization you are targeting. * Ensure that you are targeting the proper organization. ### public key could not be found in organization or its parent organization Common causes: * 0xkey cannot translate a public key obtained from a stamp to a parent organization or one of its corresponding sub-organizations that the request was made for. Troubleshooting tips: * Ensure that you have added the proper authenticators to the organization you are targeting. * Ensure that you are targeting the proper organization. ### more than one suborg associated with a credential ID Common causes: * This error occurs for requests like [whoami](/api-reference/sessions/who-am-i). In particular this request tries to go backwards from the stamp to the public key then to a corresponding sub-orgnaization under a parent organization. If there are multiple sub-organizations with the same public key corresponding to an authenticator it is unknown who is initiating that particular request without more context. Troubleshooting tips: * Inlcude the sub-organization ID in the whoami request body. * Avoid including the same authenticator in multiple sub-organizations ### more than one suborg associated with a public key Common causes: * This error occurs for requests like [whoami](/api-reference/sessions/who-am-i). In particular this request tries to go backwards from the stamp to the public key then to a corresponding sub-orgnaization under a parent organization. If there are multiple sub-organizations with the same public key it is unknown who is initiating that particular request without more context. Troubleshooting tips: * Inlcude the sub-organization ID in the whoami request body. * Avoid including the same authenticator in multiple sub-organizations ### could not verify api key signature Common causes: * The signature used to create a stamp for a request cannot be verified for the organization the request is targeting. This means the request is formatted properly, but the api-key used to create the request is not associated with the organization that the request was made for. Troubleshooting tips: * Ensure that you have added the proper api-keys to the organization you are targeting. * Ensure that you are targeting the proper organization. ### expired api key Common causes: * The API key used for the request has expired Troubleshooting tips: * Create a new API key to use for the request * Create an API key that doesn't expire ### malformed activity stamp Common causes: * The stamp attached to a request is not formatted properly. Troubleshooting tips: * Take a look at the page on [stamps](/developer-reference/api-overview/stamps) to get some information about stamps, what they are, and how they are created. * At a base level our SDK's abstract away the complicated stamping process for you. [Here](https://github.com/0xkey-io/sdk-js/tree/main/examples) are some example projects with our JS/TS SDK to get you started! ### could not extract webauthn stamp Common causes: * A stamp is not attached to a request. Troubleshooting tips: * Take a look at the page on [stamps](/developer-reference/api-overview/stamps) to get some information about stamps, what they are, and how they are created. * At a base level our SDK's abstract away the complicated stamping process for you. [Here](https://github.com/0xkey-io/sdk-js/tree/main/examples) are some example projects with our JS/TS SDK to get you started! ### could not extract api key stamp Common causes: * A stamp is not attached to a request. Troubleshooting tips: * Take a look at the page on [stamps](/developer-reference/api-overview/stamps) to get some information about stamps, what they are, and how they are created. * At a base level our SDK's abstract away the complicated stamping process for you. [Here](https://github.com/0xkey-io/sdk-js/tree/main/examples) are some example projects with our JS/TS SDK to get you started! ### cannot authenticate public API activity request without a stamp (X-Stamp/X-Stamp-Webauthn header) Common causes: * A stamp is not attached to a request. Troubleshooting tips: * Take a look at the page on [stamps](/developer-reference/api-overview/stamps) to get some information about stamps, what they are, and how they are created. * At a base level our SDK's abstract away the complicated stamping process for you. [Here](https://github.com/0xkey-io/sdk-js/tree/main/examples) are some example projects with our JS/TS SDK to get you started! ### webauthn authenticator not found in organization Common causes: * The signature used to create a stamp for a request cannot be verified for the organization the request is targeting. This means the request is formatted properly, but the webauthn authenticator used to create the request is not associated with the organization that the request was made for. Troubleshooting tips: * Ensure that you have added the proper authenticator to the organization you are targeting. * Ensure that you are targeting the proper organization. ### webauthn authenticator not found in organization or parent organization Common causes: * The signature used to create a stamp for a request cannot be verified for the organization the request is targeting. This means the request is formatted properly, but the webauthn authenticator used to create the request is not associated with the organization that the request was made for. Troubleshooting tips: * Ensure that you have added the proper authenticator to the organization you are targeting. * Ensure that you are targeting the proper organization. ### invalid payload encoding Common causes: * This error is specific to the [sign_raw_payload](/api-reference/signing/sign-raw-payload) endpoint. A valid encoding needs to be passed so that 0xkey can properly sign the requested message. Troubleshooting tips: * Use a valid encoding scheme from the following: `PAYLOAD_ENCODING_HEXADECIMAL`, `PAYLOAD_ENCODING_TEXT_UTF8` ### invalid hash function Common causes: * This error is specific to the [sign_raw_payload](/api-reference/signing/sign-raw-payload) endpoint. A valid hash function needs to be passed so that 0xkey can properly hash and sign the requested message. Troubleshooting tips: * Use a valid hash function scheme from the following: `HASH_FUNCTION_NO_OP`, `HASH_FUNCTION_SHA256`, `HASH_FUNCTION_KECCAK256`, `HASH_FUNCTION_NOT_APPLICABLE` * More information about `HASH_FUNCTION_NO_OP` [here](/faq#what-does-hash_function_no_op-mean) * More information about `HASH_FUNCTION_NOT_APPLICABLE` [here](/faq#what-is-hash_function_not_applicable-and-how-does-it-differ-from-hash_function_no_op) ### invalid magic link template Common causes: * The email template provided for specific activities is invalid. Troubleshooting tips: * Read more about [bespoke email templates](/authentication/email-walkthrough#bespoke-email-templates) * Reach out to 0xkey at [hello@0xkey.io](mailto:hello@0xkey.io)! ### failed to get email template contents Common causes: * There was an error getting the email template for an associated activity Troubleshooting tips: * Reach out to 0xkey at [hello@0xkey.io](mailto:hello@0xkey.io)! ### failed to unmarshal template variables Common causes: * There are invalid template variables used in your email template. Troubleshooting tips: * Read more about [bespoke email templates](/authentication/email-walkthrough#bespoke-email-templates) * Reach out to 0xkey at [hello@0xkey.io](mailto:hello@0xkey.io)! ### authentication failed Common causes: * 0xkey was unable to authenticate the user based on the stamp provided. Troubleshooting tips: * Ensure that all proper authenticators and api-keys have been added to the organization. * Read more about how to create a stamp for a request [here](/developer-reference/api-overview/stamps) ### failed to load organizations Common causes: * A request is targeting an unknown organization ID. Troubleshooting tips: * Ensure that the passed organization ID in the request is valid. ### policy label must be unique Common causes: * A new policy that is to be created shares the same name as a different policy. Policy names must be unique, and names in general must be unique per resource, so that they can be properly identified. Troubleshooting tips: * Change the label/name that will be used for the new policy. * Delete the old policy. * Update the old policy to have a new name. ### invalid policy consensus Common causes: * An invalid consensus expression is passed. Troubleshooting tips: * Read more about policy structure [here](/policies/overview#policy-structure) ### invalid policy condition Common causes: * An invalid condition expression is passed. Troubleshooting tips: * Read more about policy structure [here](/policies/overview#policy-structure) ### policy condition is required Common causes: * A `create_policy` / `create_policies` request without a `condition`, or with an empty or whitespace-only `condition`. * An `update_policy` request that sets `policyCondition` to an empty or whitespace-only value. Troubleshooting tips: * Always send a `condition`. To match every activity, use `"condition": "true"`. * Read more about policy structure [here](/policies/overview#policy-structure) ### Policy not found Common causes: * A policy activity such as `delete_policy` or `delete_policies` references a policy ID that does not exist in the target organization, for example because it was already deleted or belongs to another (sub-)organization. Troubleshooting tips: * Call `list_policies` for the organization and retry with the current IDs. Do not retry the same request unchanged. ### Wallet not found Common causes: * The `walletId` does not exist in the target organization or was deleted. Troubleshooting tips: * Wallet-management activities that validate their parameters up front (for example `update_wallet`) return HTTP 400 `INVALID_ARGUMENT`; others (for example `create_wallet_accounts`) return HTTP 404 `NOT_FOUND`. Treat both as "resource does not exist". * Call `list_wallets` for the organization and retry with a current `walletId`. ### quorum threshold must be non-zero integer Common causes: * Quorum is the required amount of approvals by [root quorum members](/concepts/users/root-quorum) needed for an action to take place within an organization. Troubleshooting tips: * When creating a sub-organization or updating the root quroum amount, use a non-zero positive integer. ### quorum users missing Common causes: * A user marked as part of the root quorum is missing from the set of users within an organization. This is a validation error that can occur when trying to delete a user that is part of the root quorum. Troubleshooting tips: * Before deleting the user, remove them from the root quroum using [Update Root Quorum](/api-reference/organizations/update-root-quorum) ### invalid api key expiration Common causes: * An invalid expiration time was passed in for an api key's expiration time parameter when using [Create API Key](/api-reference/api-keys/create-api-keys) Troubleshooting tips: * The `expirationSeconds` parameter is passed as string of seconds of how long the key should last. Any non-positive non-integer string will be considered invalid. ### missing parameter: user authenticator attestation Common causes: * An attestation parameter is not passed when performing a request regarding an authenticator. For example [Create Authenticators](/api-reference/authenticators/create-authenticators) Troubleshooting tips: * The attestation generated by the authenticator includes a new key pair, the challenge, and device metadata that is signed, read more about attestations [here](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Attestation_and_Assertion). * An example of getting the correct parameters needed to use the Create Authenticators endpoint can be found within our [react-components](https://github.com/0xkey-io/sdk-js/blob/main/examples/react-components/src/app/dashboard/page.tsx#L246-L276) SDK example ### invalid authenticator attestation Common causes: * An attestation parameter is not valid when performing a request regarding an authenticator. For example [Create Authenticators](/api-reference/authenticators/create-authenticators) Troubleshooting tips: * The attestation generated by the authenticator includes a new key pair, the challenge, and device metadata that is signed, read more about attestations [here](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Attestation_and_Assertion). * An example of getting the correct parameters needed to use the Create Authenticators endpoint can be found within our [react-components](https://github.com/0xkey-io/sdk-js/blob/main/examples/react-components/src/app/dashboard/page.tsx#L246-L276) SDK example ### missing parameter: user authenticator attestation auth data Common causes: * The attestation auth data parameter is not valid when performing a request regarding an authenticator. For example [Create Authenticators](/api-reference/authenticators/create-authenticators). This parameter is obtained as part of the attestation object. Troubleshooting tips: * An example of getting the correct parameters needed to use the Create Authenticators endpoint can be found within our [react-components](https://github.com/0xkey-io/sdk-js/blob/main/examples/react-components/src/app/dashboard/page.tsx#L246-L276) SDK example ### user has exceeded maximum authenticators Common causes: * 0xkey allows up to 10 authenticators per user. This is a hard resource limit. More information on resource limits [here](/concepts/resource-limits). Troubleshooting Tips: * Delete any unnecessary authenticators attached to a user. * Create a new user within the same organization and attach the authenicator to that user. ### user has exceeded maximum long-lived api keys Common causes: * 0xkey allows up to 10 long-lived api keys per user. This is a hard resource limit. More information on resource limits [here](/concepts/resource-limits). Troubleshooting Tips: * Delete any unnecessary long-lived API keys attached to a user. * Create a new user within the same organization and attach the API key to that user. ### user has exceeded maximum short-lived api keys Common causes: * 0xkey allows up to 10 short-lived api keys per user. This is a hard resource limit. More information on resource limits [here](/concepts/resource-limits). Short-lived API keys will automatically be deleted from an organization when they are expired. Troubleshooting Tips: * Delete any unnecessary short-lived API keys attached to a user. * Create a new user within the same organization and attach the API key to that user. ### missing wallet params Common causes: * Some wallet/wallet account parameters have been omitted when creating a sub-organization Troubleshooting tips: * Include all of the required parameters when creating a wallet during sub-organization creation. More info on the parameters [here](/api-reference/organizations/create-sub-organization). ### invalid path format Common causes: * This error occurs when an invalid path format parameter is passed to a request like [Create Wallet Accounts](/api-reference/wallets/create-wallet-accounts). Troubleshooting tips: * For now the path format must be: `PATH_FORMAT_BIP32`. ### invalid path Common causes: * An invalid path parameter is passed to a request like [Create Wallet Accounts](/api-reference/wallets/create-wallet-accounts). Paths cannot be reused within the same HD wallet. Troubleshooting tips: * The path is a string that is used to derive a new account within an HD wallet. A list of default paths per address format can be found [here](/concepts/wallets#hd-wallet-default-paths) * Paths cannot be reused within the same HD wallet. ### invalid address format Common causes: * An invalid address format parameter is passed to a request like [Create Wallet Accounts](/api-reference/wallets/create-wallet-accounts). Troubleshooting tips: * 0xkey offers a wide range of support for many ecosystems. A list of valid address formats can be found in the table [here](/concepts/wallets#address-formats-and-curves). * More about 0xkey and general ecosystem support can be found [here](/networks/overview). ### invalid curve Common causes: * An invalid curve parameter is passed to a request like [Create Wallet Accounts](/api-reference/wallets/create-wallet-accounts). Troubleshooting tips: * Before ecosystem level integrations 0xkey offers support on a curve level. This makes us extendable to any ecosystem that is based on a curve we support. A list of valid curve parameters can be found in the table [here](/concepts/wallets#address-formats-and-curves). * More about 0xkey and general ecosystem support can be found [here](/networks/overview). ### curve required Common causes: * The curve parameter is not passed to a request like [Create Wallet Accounts](/api-reference/wallets/create-wallet-accounts). Troubleshooting tips: * Before ecosystem level integrations 0xkey offers support on a curve level. This makes us extendable to any ecosystem that is based on a curve we support. A list of valid curve parameters can be found in the table [here](/concepts/wallets#address-formats-and-curves). * More about 0xkey and general ecosystem support can be found [here](/networks/overview). ### failed to parse transaction Common causes: * The unsignedTransaction payload cannot be decoded by the policy engine, it might have not been serlialized properly. Troubleshooting tips: * Try to decode the payload independently and see if it returns the expected result. * We've noticed that for EIP1559 transaction types, the go-ethereum [MarshalBinary()](https://pkg.go.dev/github.com/ethereum/go-ethereum/core/types#Transaction.MarshalBinary) function will include the R, S, V values which should not be present within the serialized payload. Try to reconstruct the RLP payload manually without the R, S, V values, see the example below: > [accordion] main.go > > ```go theme={"theme":{"light":"github-light","dark":"github-dark"}} > package main > > import ( > "encoding/hex" > "fmt" > "log" > "math/big" > > "github.com/ethereum/go-ethereum/common" > "github.com/ethereum/go-ethereum/core/types" > "github.com/ethereum/go-ethereum/rlp" > ) > > func main() { > to := common.HexToAddress("0x...") > > txData := &types.DynamicFeeTx{ > ChainID: big.NewInt(1), > Nonce: 0, > GasTipCap: big.NewInt(12344), > GasFeeCap: big.NewInt(10010000000), > Gas: 100000, > To: &to, > Value: big.NewInt(1), > Data: hexDecode(""), > AccessList: types.AccessList{}, // Optional > } > > // RLP-encode only the fields included in the unsigned tx > unsignedRLP := encodeUnsignedDynamicFeeTx(txData) > > // Prepend EIP-1559 type byte (0x02) > serializedUnsigned := append([]byte{types.DynamicFeeTxType}, unsignedRLP...) > > fmt.Printf("Unsigned serialized tx: 0x%x\n", serializedUnsigned) > > } > > func encodeUnsignedDynamicFeeTx(tx *types.DynamicFeeTx) []byte { > rlpInput := []interface{}{ > tx.ChainID, > tx.Nonce, > tx.GasTipCap, > tx.GasFeeCap, > tx.Gas, > tx.To, > tx.Value, > tx.Data, > tx.AccessList, > } > out, err := rlp.EncodeToBytes(rlpInput) > if err != nil { > log.Fatalf("failed to encode RLP: %v", err) > } > return out > } > > func hexDecode(input string) []byte { > b, err := hex.DecodeString(input) > if err != nil { > log.Fatal(err) > } > return b > } > ``` ### No activity found with fingerprint. Consensus activities must target an existing activity by fingerprint Common causes: * This error occurs during the [Approve/Reject Activity](/api-reference/consensus/approve-activity) activity. The fingerprint parameter must be a fingerprint of a valid activity. Troubleshooting tips: * Confirm that a valid fingerprint of an activity that requires approval or rejection is passed as part of this activity. ### internal server error Common causes: * This error is thrown for a variety of internal server errors that are not due to user error. These activities will have an error id passed with them like: `internal server error (9fbfda54-7141-4192-ae72-8bac3512149a)` that can be used for troubleshooting. Troubleshooting tips: * Retry the activity. This could be a fluke case and the following activity could pass without failure. * If you think there is problem or if your service is degraded, please reach out to 0xkey [hello@0xkey.io](mailto:hello@0xkey.io) and provide the error id in the error message. ### organization mismatch Common causes: * The request is targeting one organization (e.g., a sub-organization), but the users signing/approving the request belong to a different organization (e.g., the parent organization) Troubleshooting tips: * Ensure the `organizationId` in your request matches the organization where your signing users are located ### invalid wallet account UUID Common causes: * A malformed or invalid UUID was provided for a wallet account ID Troubleshooting tips: * Verify the wallet account ID is a valid UUID in the format `XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX` ### wallet account not part of your organization Common causes: * Attempting to delete or modify a wallet account that belongs to a different organization * Using a wallet account ID from another organization Troubleshooting tips: * Verify the wallet account ID belongs to your organization * Check that you're using the correct organization ID in your request ### wallet account has not been exported Common causes: * Attempting to delete a wallet account that has not been exported * The `deleteWithoutExport` parameter is not set to `true` when trying to delete an unexported wallet account Troubleshooting tips: * Export the wallet account before deleting it using the export wallet account activity * Set `deleteWithoutExport` to `true` in your delete request if you want to delete without exporting (use with caution) ### invalid OIDC token Common causes: * The OIDC token format is invalid (not a valid JWT with 3 parts) * Required claims are missing from the OIDC token (`aud`, `sub`, or `iss`) * The token structure doesn't match the expected format Troubleshooting tips: * Verify the OIDC token is a valid JWT with three parts separated by periods (header.payload.signature) * Ensure the token includes all required claims: * `aud` (audience): The intended recipient of the token * `sub` (subject): The user identifier * `iss` (issuer): The identity provider that issued the token * Check that your OIDC provider is correctly configured to include these claims * If you use a self-hosted / custom IdP, see [OIDC Federation → Troubleshooting](/authentication/oidc-federation#troubleshooting) for issuer, audience, nonce, and JWKS-host errors. ### OIDC issuer is not a registered/enabled trusted IdP for this organization Common causes: * The token's `iss` does not match any enabled OIDC provider registered for the organization. Built-in social providers (Google, Apple, …) are trusted by default, but a self-hosted / custom issuer must be registered first. Troubleshooting tips: * Register the issuer with [`CREATE_OIDC_PROVIDER`](/api-reference/activities/create-oidc-provider) against the correct parent organization, and confirm it is `enabled`. * The registered `issuer` must match the token's `iss` byte-for-byte (watch for a trailing slash or `http` vs `https`). It is immutable — delete and re-create if wrong. * More detail in the [OIDC Federation guide](/authentication/oidc-federation#troubleshooting). ### JWT 'aud' mismatch Common causes: * The token's `aud` claim is not in the audience allowlist registered for the issuer. Troubleshooting tips: * Add the OAuth2 client ID your app uses to the provider's `audiences` via [`UPDATE_OIDC_PROVIDER`](/api-reference/activities/update-oidc-provider). Registration is fail-closed — there is no wildcard audience. * If you use different client IDs per platform, register each one, or standardize on a single client ID. ### JWT 'nonce' does not match sha256(public_key) Common causes: * During `oauth_login`, the token's `nonce` (or `tknonce`) is not the SHA-256 of the API `publicKey` presented in the request. Troubleshooting tips: * Set the OIDC `nonce` to `sha256(publicKey)` when starting the login flow, using the same keypair you pass to `oauth_login`. See [OIDC Federation → Troubleshooting](/authentication/oidc-federation#troubleshooting). ### OIDC JWKS fetch URL host does not match issuer host Common causes: * For a self-hosted (federated) issuer, the `jwks_uri` in the discovery document points at a different host than the issuer. This is rejected to prevent a tampered discovery document from redirecting key-fetching to an attacker-controlled host. Troubleshooting tips: * Serve your JWKS on the same host as your issuer. Built-in social providers are exempt from this check; your own registered issuers are not. ### failed to parse user JSON: missing field `data` (X/Twitter OAuth) Common causes: * X (Twitter) legacy Free tier developer apps were not automatically migrated to the new Pay-Per-Use pricing model when X launched their new [developer console and pricing](https://devcommunity.x.com/t/announcing-the-launch-of-x-api-pay-per-use-pricing/256476) * The app is still on a legacy Free plan, which no longer has access to the `GET /2/users/me` endpoint required for 0xkey's X OAuth flow Troubleshooting tips: * Go to [console.x.com](https://console.x.com/) and manually update your app to the **Pay-Per-Use** plan * This is a one-time migration — once updated, X OAuth with 0xkey should work as expected ### invalid email address Common causes: * Email address format is invalid Troubleshooting tips: * Verify the email address follows the standard format: `user@domain.com` * Remove any extra spaces or invalid characters from the email address ### could not reach email Common causes: * The email domain cannot be reached or verified * Invalid MX (Mail Exchange) records for the email domain * The email provider's servers are unreachable or non-existent * The domain doesn't have proper DNS configuration Troubleshooting tips: * Verify the email domain is a valid, active domain * Check that the email provider's MX records are properly configured * Try using an email address from a well-known provider (Gmail, Outlook, etc.) to test * If you believe this is in error, please contact 0xkey # Introduction Source: https://docs.0xkey.io/developer-reference/api-overview/intro 0xkey's API is a remote procedure call (RPC) API. > [!NOTE] > > The implementation status of every endpoint is tracked on the [Roadmap](/0xkey/roadmap). Endpoints listed in the API reference may be wired but stubbed in Phase 1 — always check the Roadmap before designing an integration. ## RPC/HTTP We chose RPC-over-HTTP for convenience and ease-of-use. Most of our users should be able to integrate with our API without a major re-architecture of their existing systems. Many client libraries are available to make requests to a RPC/HTTP API, across many languages. 0xkey will provide SDKs for the most popular programming languages. For other languages, a RPC/HTTP API ensures there is an easy integration path available via raw http clients. ## POST-only If you look at the [API reference](/api-reference/overview) you'll notice that all API calls to 0xkey are HTTP POST requests. Requests contain a POST body and a header with a digital signature over the POST body. We call this digital signature a [Stamp](/developer-reference/api-overview/stamps). Requests must be stamped by registered user credentials and verified by 0xkey's secure enclaves before they are processed. This ensures cryptographic integrity end-to-end which eliminates the ability for any party to modify a user's request. ### Queries and submissions 0xkey's API is divided into 2 broad categories: queries and submissions. * Queries are read requests (e.g. `get_users`, `list_users`) * Submissions are requests to execute a workload (e.g. `create_policy`, `sign_transaction`, `delete_user`) ## Dive deeper * Creating your first [Stamp](/developer-reference/api-overview/stamps) * Fetching data with [Queries](/developer-reference/api-overview/queries) * Executing workloads with [Submissions](/developer-reference/api-overview/submissions) # Queries Source: https://docs.0xkey.io/developer-reference/api-overview/queries Queries are read requests to 0xkey's API. Query URL paths are prefixed with `/public/v1/query`. Queries are not subject to enforcement of the policy engine. All users within an organization can read any data within the organization. Additionally, parent organizations have the ability to query data for all of their sub-organizations. # Stamps Source: https://docs.0xkey.io/developer-reference/api-overview/stamps Every request made to 0xkey must include a signature over the POST body attached as a HTTP header. Our secure enclave applications use this signature to verify the integrity and authenticity of the request. ### API keys To create a valid, API key stamped request follow these steps: **Step 1** Sign the JSON-encoded POST body with your API key to produce a `signature` (DER-encoded) **Step 2** Hex encode the `signature` **Step 3** Create a JSON-encoded stamp: * `publicKey`: the public key of API key, note that only P-256 keys (API_KEY_CURVE_P256) are currently supported * `signature`: the signature produced by the API key * `scheme`: `SIGNATURE_SCHEME_TK_API_P256` **Step 4** Base64URL encode the stamp **Step 5** Attach the encoded string to your request as a `X-Stamp` header **Step 6** Submit the stamped request to 0xkey's API ### WebAuthn To create a valid, Webauthn authenticator stamped request follow these steps: **Step 1** Compute the webauthn challenge by hashing the POST body bytes (JSON encoded) with SHA256. For example, if the POST body is `{"organization_id": "1234", "type": "ACTIVITY_TYPE_CREATE_API_KEYS", "params": {"for": "example"}`, the webauthn challenge is the string `7e8b4653fc7e51dc119cea031942f4693b4742ceca4dda269b925802b38b2147` **Step 2** Include the challenge amongst WebAuthn signing options. Refer to the existing stamper implementations in the [following section](#stampers)) for examples * Note that if you need to pass the challenge as bytes, you'll need to utf8-encode the challenge string (in JS, the challenge bytes will be `TextEncoder().encode("7e8b4653fc7e51dc119cea031942f4693b4742ceca4dda269b925802b38b2147")`) * Additional note for React Native contexts: the resulting string should then additionally be base64-encoded. See [implementation](https://github.com/0xkey-io/sdk-js/blob/b52db566e79a65eec8d8e7066053d6a3ac5f3943/packages/react-native-passkey-stamper/src/util.ts#L5-L10) **Step 3** Create a JSON-encoded stamp: * `credentialId`: the id of the webauthn authenticator * `authenticatorData`: the authenticator data produced by Webauthn assertion * `clientDataJson`: the client data produced by the Webauthn assertion * `signature`: the signature produced by the Webauthn assertion **Step 4** Attach the JSON-encoded stamp to your request as a `X-Stamp-Webauthn` header * Header names are case-insensitive (so `X-Stamp-Webauthn` and `X-Stamp-WebAuthn` are considered equivalent) * Unlike API key stamps, the format is just JSON; no base64URL encoding necessary! For example: `X-Stamp-Webauthn: {"authenticatorData":"UaQZ...","clientDataJson":"eyJ0...","credentialId":"Grf...","signature":"MEQ..."}` **Step 5** Submit the stamped request to 0xkey's API. If you would like your client request to be proxied through a backend, refer to the patterns mentioned [here](/authentication/passkeys/integration#proxying-signed-requests). The open-source [Demo Embedded Wallet](https://github.com/0xkey-io/demo-embedded-wallet/) uses this pattern. ### Stampers Our [JS SDK](https://github.com/0xkey-io/sdk-js) and [Go SDK](https://github.com/0xkey-io/sdk-go) abstract request stamping for you. If you choose to use an independent client, you will need to implement this yourself. For reference, check out our implementations: > [card] [API Key Stamper](https://github.com/0xkey-io/sdk-js/blob/main/packages/api-key-stamper) > [card] [WebAuthn Stamper](https://github.com/0xkey-io/sdk-js/blob/main/packages/webauthn-stamper) > [card] [React Native Stamper](https://github.com/0xkey-io/sdk-js/tree/main/packages/react-native-passkey-stamper) > [card] [iFrame Stamper](https://github.com/0xkey-io/sdk-js/tree/main/packages/iframe-stamper) > [card] [Telegram Cloud Storage Stamper](https://github.com/0xkey-io/sdk-js/tree/main/packages/telegram-cloud-storage-stamper) > [card] [IndexedDb Stamper](https://github.com/0xkey-io/sdk-js/tree/main/packages/indexed-db-stamper) > [card] [Wallet Stamper](https://github.com/0xkey-io/sdk-js/tree/main/packages/wallet-stamper) > [card] [Go API key helper](https://github.com/0xkey-io/sdk-go/tree/main/examples/apikey) The `0xkey` CLI (**Partial**, v0.1.0) can generate an API key and send stamped requests with `0xkey request`; see [Using the CLI](/sdks/cli). You can also use the stampers above or the Go `examples/apikey` helper to generate stamps for debugging. # Submissions Source: https://docs.0xkey.io/developer-reference/api-overview/submissions Submissions are requests to securely execute a workload. Submission URL paths are prefixed with `/public/v1/submit`. Submissions requests, if valid, produce an `Activity`. ### Activities Activities typically create, modify, or utilize a resource within 0xkey and are subject to consensus or condition enforcement via the policy engine. Activities are executed optimistically synchronous. This means that if we can process the request synchronously, we will. Otherwise, we'll fallback to asynchronous processing. Your services or applications should account for this by checking the response for the activity state: * If `activity.status == ACTIVITY_STATUS_COMPLETED`, `activity.result` field will be populated with a successful response. * If `activity.status == ACTIVITY_STATUS_FAILED`, `activity.failure` field will be populated with a failure reason. * If `activity.status == ACTIVITY_STATUS_CONSENSUS_NEEDED`, additional signatures (votes) are required to process the request. * If `activity.status == ACTIVITY_STATUS_PENDING`, the request is processing asynchronously. Activities do not expire but approvals (votes) do. When an activity is submitted, the requester’s submission counts as the first approval, which starts a 24-hour window. If consensus is not reached within that window, existing approvals expire and must be re-submitted while the activity remains in `ACTIVITY_STATUS_CONSENSUS_NEEDED`. You can get activity status updates by: * Re-submitting the request. See the notes on idempotency below. * Polling `get_activity` with the `activity.id` ### Idempotency The submission API is idempotent. For each request, the POST body is hashed into a fingerprint. Any two requests with the same fingerprint are considered the same request. If you resubmit the request, you'll get the same activity. If you want a new activity, you should modify the request timestamp `timestampMs` to produce a new fingerprint. # Webhooks Source: https://docs.0xkey.io/developer-reference/webhooks Create webhook endpoints, receive activity events, and verify 0xkey webhook signatures. Webhooks let your backend receive asynchronous 0xkey activity events. In the current release, webhook endpoints are organization-scoped and can subscribe to activity updates. > [!NOTE] > > **Current scope.** 0xkey currently supports the `ACTIVITY_UPDATES` subscription. This emits activity lifecycle events such as `activity.completed` and `activity.failed`. Balance and transaction subscriptions are not yet enabled. ## Create an endpoint You can create and manage webhook endpoints from the Dashboard under **Webhooks**. For API-based setup, submit a `ACTIVITY_TYPE_CREATE_WEBHOOK_ENDPOINT` activity: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} curl --request POST \ --url https://api.0xkey.io/public/v1/submit/create_webhook_endpoint \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'X-Stamp: ' \ --data '{ "type": "ACTIVITY_TYPE_CREATE_WEBHOOK_ENDPOINT", "timestampMs": "1781250000000", "organizationId": "", "parameters": { "url": "https://example.com/webhooks/0xkey", "name": "Production activity webhook", "subscriptions": [ { "eventType": "ACTIVITY_UPDATES", "filtersJson": "", "isActive": true } ] } }' ``` Production webhook URLs must use `https://`. Local development accepts `http://localhost` and `http://127.0.0.1`. ## Update or delete an endpoint Update supports the endpoint URL, display name, and active status: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} curl --request POST \ --url https://api.0xkey.io/public/v1/submit/update_webhook_endpoint \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'X-Stamp: ' \ --data '{ "type": "ACTIVITY_TYPE_UPDATE_WEBHOOK_ENDPOINT", "timestampMs": "1781250000000", "organizationId": "", "parameters": { "endpointId": "", "url": "https://example.com/webhooks/0xkey", "name": "Production activity webhook", "isActive": true } }' ``` > [!WARNING] > > Updating subscriptions is not supported yet. To change subscriptions, delete and recreate the endpoint. Delete removes the 0xkey endpoint and synchronizes the deletion to the delivery backend: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} curl --request POST \ --url https://api.0xkey.io/public/v1/submit/delete_webhook_endpoint \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'X-Stamp: ' \ --data '{ "type": "ACTIVITY_TYPE_DELETE_WEBHOOK_ENDPOINT", "timestampMs": "1781250000000", "organizationId": "", "parameters": { "endpointId": "" } }' ``` ## Delivery payload 0xkey sends a JSON POST body: ```json theme={"theme":{"light":"github-light","dark":"github-dark"}} { "eventId": "00000000-0000-4000-8000-000000000e01", "eventType": "activity.completed", "organizationId": "00000000-0000-4000-8000-0000000000c1", "activityId": "00000000-0000-7000-8000-0000000000a1", "data": { "activityType": "ACTIVITY_TYPE_CREATE_WALLET", "result": {} }, "timestamp": 1781250000000 } ``` `eventId` is stable across retries. Use it as your idempotency key. ## Delivery headers Every signed webhook delivery includes these `X-0xkey-*` headers: * `X-0xkey-Organization-Id`: the organization that owns the event. * `X-0xkey-Event-Type`: the event type, for example `activity.completed`. * `X-0xkey-Timestamp`: Unix timestamp in milliseconds for this delivery attempt. * `X-0xkey-Signature-Version`: signature contract version. Current value: `v1`. * `X-0xkey-Event-Id`: stable event ID, unchanged across retries. * `X-0xkey-Signature-Key-Id`: `kid` for selecting the JWKS verification key. * `X-0xkey-Signature-Algorithm`: current value: `ed25519`. * `X-0xkey-Signature`: lowercase hex-encoded Ed25519 signature. ## Verify signatures Fetch the public verification keys from: ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} curl https://api.0xkey.io/public/v1/discovery/webhooks/jwks ``` Match `X-0xkey-Signature-Key-Id` to the JWK `kid`. If the `kid` is unknown, refetch JWKS once before rejecting the delivery. The signed message is the UTF-8 prefix followed by the exact raw request body bytes: ```text theme={"theme":{"light":"github-light","dark":"github-dark"}} {version}.{algorithm}.{key_id}.{timestamp_ms}.{event_id}.{raw_body} ``` Where: * `version` is the `X-0xkey-Signature-Version` header (currently `v1`). * `algorithm` is the `X-0xkey-Signature-Algorithm` header (currently `ed25519`). * `key_id` is the `X-0xkey-Signature-Key-Id` header. * `timestamp_ms` is the raw `X-0xkey-Timestamp` header string (Unix milliseconds). * `event_id` is the `X-0xkey-Event-Id` header. * `raw_body` is the exact UTF-8 request body bytes received by your server. Example verification in TypeScript with `@0xkey-io/crypto`: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} import { verifyWebhookFromJWKS } from "@0xkey-io/crypto"; export async function handle0xkeyWebhook(req: Request) { const rawBody = await req.text(); const result = await verifyWebhookFromJWKS({ headers: req.headers, body: rawBody, jwksUrl: "https://api.0xkey.io/public/v1/discovery/webhooks/jwks", maxTimestampAgeMs: 300_000, }); if (!result.ok) { throw new Error(`webhook verification failed: ${result.reason}`); } const payload = JSON.parse(rawBody); return payload; } ``` To verify with a pinned public key instead of JWKS: ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}} import { verifyWebhook } from "@0xkey-io/crypto"; const result = verifyWebhook({ headers: req.headers, body: rawBody, verificationKeys: [ { keyId: process.env.ZEROXKEY_WEBHOOK_KEY_ID!, publicKey: process.env.ZEROXKEY_WEBHOOK_PUBLIC_KEY!, // JWKS `x` field (base64) }, ], maxTimestampAgeMs: 300_000, }); ``` > [!WARNING] > > Parse JSON only after signature verification. Verification must use the exact raw body bytes, not a re-serialized JSON object. ## Retries and idempotency 0xkey uses the delivery backend for retry and fanout. Your receiver should: * Return any `2xx` status only after the event is durably accepted. * Treat duplicate `eventId` values as successful no-ops. * Keep processing fast; enqueue long-running work and respond quickly. * Prefer HTTPS endpoints with stable DNS and TLS certificates. ## Related API reference * [Create webhook endpoint](/api-reference/webhooks/create-webhook-endpoint) * [Update webhook endpoint](/api-reference/webhooks/update-webhook-endpoint) * [Delete webhook endpoint](/api-reference/webhooks/delete-webhook-endpoint) * [List webhook endpoints](/api-reference/webhooks/list-webhook-endpoints) * [Get webhook JWKS](/api-reference/queries/get-webhook-jwks) # Add an additional passkey Source: https://docs.0xkey.io/embedded-wallets/code-examples/add-credential Register an additional passkey credential for an existing user. Additional passkeys are registered through WebAuthn after the user is authenticated. React Wallet Kit and `@0xkey-io/core` expose this via Auth Proxy and the public API. > [card] [Passkeys](/authentication/passkeys) > > Registration options and RPID requirements > [card] [React Wallet Kit](/sdks/react/getting-started) > > Account settings and credential management UI > [card] [API — create authenticators](/api-reference/activities/create-authenticators) > > `CREATE_AUTHENTICATORS` activity > [card] [Embedded Wallet Kit](/embedded-wallets/features/embedded-wallet-kit) > > Product overview # Authenticate a user with email Source: https://docs.0xkey.io/embedded-wallets/code-examples/authenticate-user-email Email OTP authentication runs through the [Auth Proxy](/embedded-wallets/features/auth-proxy). Use React Wallet Kit or `@0xkey-io/core` on the client and [`@0xkey-io/sdk-server`](/sdks/javascript-server) server actions on the backend. > [card] [Email authentication](/authentication/email) > > OTP flow, Auth Proxy endpoints, and security model > [card] [React Wallet Kit](/sdks/react/getting-started) > > Built-in email OTP in the login modal > [card] [TypeScript server](/sdks/javascript-server) > > `server.sendOtp`, `server.verifyOtp`, `server.otpLogin` > [card] [GitHub — otp-auth](https://github.com/0xkey-io/sdk-js/tree/main/examples/otp-auth) > > End-to-end OTP example # Authenticate a user with a passkey credential Source: https://docs.0xkey.io/embedded-wallets/code-examples/authenticate-user-passkey Passkey login is built into [React Wallet Kit](/sdks/react/getting-started) and [`@0xkey-io/core`](/sdks/typescript-frontend/getting-started) via Auth Proxy and WebAuthn stampers. > [card] [React Wallet Kit](/sdks/react/getting-started) > > `handleLogin` with passkeys enabled in Auth Proxy > [card] [@0xkey-io/core](/sdks/typescript-frontend/getting-started) > > `ZeroXKeyClient` + `passkeyConfig` for custom UI > [card] [Passkeys](/authentication/passkeys) > > RPID, registration, and authentication options > [card] [GitHub — react-wallet-kit](https://github.com/0xkey-io/sdk-js/tree/main/examples/react-wallet-kit) > > Full reference implementation # Client-side signing Source: https://docs.0xkey.io/embedded-wallets/code-examples/client-side-signing This guide covers how to set up client-side signing using 0xkey's `@0xkey-io/iframe-stamper` package and the `export-and-sign` iframe. This architecture enables secure transaction and message signing directly in the browser without exposing private keys to your application code. Note that mishandling of exported private keys introduces inherent risks; please proceed with caution. ## Overview Client-side signing allows you to: * Export private keys from 0xkey to a secure iframe * Sign transactions and messages directly in the browser via iframe * Maintain multiple keys simultaneously for signing operations * Keep private keys isolated from your application's JavaScript context ### Architecture ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}} flowchart TB subgraph app["Your Application"] subgraph frontend["Frontend"] stamper["IframeStamper"] end subgraph exporter["Backend (API Routes) or Frontend"] sdk["0xkey SDK
(exportWalletAccount)"] end stamper <--> sdk end subgraph iframe["export-and-sign Iframe"] embedded["Embedded Key
(P-256 ECDH)
localStorage"] inmemory["In-Memory Private Keys
{ address → key, keypair }
(memory only)"] end stamper <-->|"MessageChannel"| iframe ``` ### Security model 1. **Iframe Isolation**: Private keys never touch your application's JavaScript context 2. **HPKE Encryption**: Export bundles are encrypted end-to-end using RFC 9180 3. **Enclave Verification**: All bundles are signed by 0xkey's secure enclave 4. **Sandboxed Iframe**: The iframe runs with `allow-scripts allow-same-origin` sandbox restrictions 5. **Organization Validation**: Bundles are validated against your organization ID ## Prerequisites * Node.js v20+ * A 0xkey organization with API credentials * Wallet accounts to export (Solana addresses for signing support) * `@0xkey-io/iframe-stamper >= 2.7.0` ## Installation ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} npm install @0xkey-io/iframe-stamper @0xkey-io/sdk-server ``` ## Environment variables ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}} # .env.local NEXT_PUBLIC_ORGANIZATION_ID= NEXT_PUBLIC_BASE_URL=https://api.0xkey.io NEXT_PUBLIC_EXPORT_SIGN_IFRAME_URL=https://export.0xkey.io # Server-side only (never expose to client) # Not necessary if user performs export using a session directly via frontend API_PUBLIC_KEY= API_PRIVATE_KEY= ``` ## Sample implementation Note: the following is for a NextJS application with a separate frontend and backend. The foundations should be applicable for other configurations. ### Step 1: initialize the IframeStamper Create a component that initializes the iframe and manages its lifecycle. ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} import { IframeStamper } from "@0xkey-io/iframe-stamper"; import { useEffect, useState } from "react"; const IFRAME_CONTAINER_ID = "0xkey-iframe-container"; const IFRAME_ELEMENT_ID = "0xkey-iframe"; function SigningComponent() { const [iframeStamper, setIframeStamper] = useState( null ); useEffect(() => { const stamper = new IframeStamper({ iframeUrl: process.env.NEXT_PUBLIC_EXPORT_SIGN_IFRAME_URL!, iframeContainer: document.getElementById(IFRAME_CONTAINER_ID), iframeElementId: IFRAME_ELEMENT_ID, }); return () => { stamper.clear(); }; }, []); return (
{/* Iframe will be inserted here */}
); } ``` For an example in context, we highly recommend taking a look at the [wallet-export-sign example app](https://github.com/0xkey-io/sdk-js/blob/0af0303ca4714cf65f5177cdb05f824877713d2a/examples/wallet-export-sign/src/components/Export.tsx#L62-L107). ### Step 2: create the export caller (backend or client-side) The export call can be made from a backend API route or a trusted client-side environment. The example below shows a server-side API route; if you call from the client, avoid exposing key material. ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} // pages/api/exportWalletAccount.ts import type { NextApiRequest, NextApiResponse } from "next"; import { ZeroXKey } from "@0xkey-io/sdk-server"; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { walletAccountAddress, targetPublicKey } = req.body; const zeroXKeyClient = new ZeroXKey({ apiBaseUrl: process.env.NEXT_PUBLIC_BASE_URL!, apiPublicKey: process.env.API_PUBLIC_KEY!, apiPrivateKey: process.env.API_PRIVATE_KEY!, defaultOrganizationId: process.env.NEXT_PUBLIC_ORGANIZATION_ID!, }); const { address, exportBundle } = await zeroXKeyClient .apiClient() .exportWalletAccount({ organizationId: process.env.NEXT_PUBLIC_ORGANIZATION_ID!, address: walletAccountAddress, targetPublicKey: targetPublicKey, }); res.status(200).json({ address, exportBundle }); } ``` ### Step 3: export a private key to the iframe ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} import { KeyFormat } from "@0xkey-io/iframe-stamper"; import axios from "axios"; async function exportKeyToIframe( iframeStamper: IframeStamper, walletAccountAddress: string, organizationId: string ) { // Step 3a: Get or initialize the embedded key let embeddedKey = await iframeStamper.getEmbeddedPublicKey(); if (!embeddedKey) { embeddedKey = await iframeStamper.initEmbeddedKey(); } // Step 3b: Request export bundle from your export caller const response = await axios.post("/api/exportWalletAccount", { walletAccountAddress, targetPublicKey: embeddedKey, }); // Step 3c: Inject the bundle into the iframe const injected = await iframeStamper.injectKeyExportBundle( response.data.exportBundle, organizationId, KeyFormat.Hexadecimal, // or KeyFormat.Solana for Solana-formatted keys walletAccountAddress // Required for multi-key support ); if (!injected) { throw new Error("Failed to inject export bundle"); } // The key is now stored in-memory within the iframe // The embedded key remains available for additional exports } ``` ### Step 4: sign messages ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} import { MessageType } from "@0xkey-io/iframe-stamper"; async function signMessage( iframeStamper: IframeStamper, message: string, walletAccountAddress: string ): Promise { const signature = await iframeStamper.signMessage( { message, type: MessageType.Solana, }, walletAccountAddress // Required when multiple keys are loaded ); return signature; // Returns hex-encoded signature } ``` ### Step 5: sign transactions ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} import { TransactionType } from "@0xkey-io/iframe-stamper"; async function signTransaction( iframeStamper: IframeStamper, serializedTransaction: string, // Hex-encoded transaction bytes walletAccountAddress: string ): Promise { const signedTransaction = await iframeStamper.signTransaction( { transaction: serializedTransaction, type: TransactionType.Solana, }, walletAccountAddress ); return signedTransaction; // Returns hex-encoded signed transaction } ``` ## Multi-key support One of the key capabilities of client-side signing is the ability to load and manage multiple private keys simultaneously within the iframe. ### Loading multiple keys Since the embedded key persists across bundle injections, you can export multiple keys using the same embedded key (as long as it hasn't expired): ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} async function loadMultipleKeys( iframeStamper: IframeStamper, addresses: string[], organizationId: string ) { // Get or initialize the embedded key once let embeddedKey = await iframeStamper.getEmbeddedPublicKey(); if (!embeddedKey) { embeddedKey = await iframeStamper.initEmbeddedKey(); } for (const address of addresses) { const response = await axios.post("/api/exportWalletAccount", { walletAccountAddress: address, targetPublicKey: embeddedKey, // Same embedded key for all exports }); await iframeStamper.injectKeyExportBundle( response.data.exportBundle, organizationId, KeyFormat.Hexadecimal, address // Each key is stored by its address ); } } ``` ### Signing with different keys ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} // Sign with the first address const sig1 = await iframeStamper.signMessage( { message: "Hello", type: MessageType.Solana }, "address1..." ); // Sign with the second address const sig2 = await iframeStamper.signMessage( { message: "World", type: MessageType.Solana }, "address2..." ); ``` ### Clearing keys ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} // Clear a specific key await iframeStamper.clearEmbeddedPrivateKey("address1..."); // Clear all keys (no address parameter) await iframeStamper.clearEmbeddedPrivateKey(); ``` ## Key lifecycle and expiration Understanding the key lifecycle is important for building reliable applications. ### Embedded key (P-256 ECDH) * **Storage**: localStorage within the iframe * **TTL**: 48 hours (default) * **Purpose**: Decrypt incoming export bundles via HPKE * **Behavior**: Persists across bundle injections - the same embedded key can decrypt multiple export bundles until it expires or is explicitly cleared ### In-memory private keys * **Storage**: JavaScript memory only (never persisted) * **TTL**: 24 hours * **Purpose**: Sign messages and transactions * **Behavior**: Lost on page reload, cleared on expiration ### Handling expiration ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} // Re-export flow when keys expire or page reloads async function ensureKeyLoaded( iframeStamper: IframeStamper, address: string, organizationId: string ) { try { // Attempt to sign a test message await iframeStamper.signMessage( { message: "test", type: MessageType.Solana }, address ); } catch (error) { // Key not found or expired - re-export await exportKeyToIframe(iframeStamper, address, organizationId); } } ``` ## Key formats | Format | Description | Use Case | | - | - | - | | `KeyFormat.Solana` | Base58-encoded 64-byte format (private + public) | Phantom, Solflare, Solana keys | | `KeyFormat.Hexadecimal` | 64 hexadecimal digits (32 bytes) | Non-Solana | ## Complete example Here's a complete React component demonstrating the full flow: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}} import { IframeStamper, KeyFormat, MessageType, TransactionType, } from "@0xkey-io/iframe-stamper"; import { useEffect, useState } from "react"; import axios from "axios"; const IFRAME_CONTAINER_ID = "0xkey-iframe-container"; const IFRAME_ELEMENT_ID = "0xkey-iframe"; interface Props { organizationId: string; walletAccountAddress: string; } export function ClientSideSigner({ organizationId, walletAccountAddress, }: Props) { const [iframeStamper, setIframeStamper] = useState( null ); const [isKeyLoaded, setIsKeyLoaded] = useState(false); const [message, setMessage] = useState("Hello, 0xkey!"); const [signature, setSignature] = useState(""); // Initialize iframe useEffect(() => { const stamper = new IframeStamper({ iframeUrl: process.env.NEXT_PUBLIC_EXPORT_SIGN_IFRAME_URL!, iframeContainer: document.getElementById(IFRAME_CONTAINER_ID), iframeElementId: IFRAME_ELEMENT_ID, }); stamper .init() .then(() => setIframeStamper(stamper)) .catch(console.error); return () => stamper.clear(); }, []); // Export key to iframe const exportKey = async () => { if (!iframeStamper) return; let embeddedKey = await iframeStamper.getEmbeddedPublicKey(); if (!embeddedKey) { embeddedKey = await iframeStamper.initEmbeddedKey(); } const response = await axios.post("/api/exportWalletAccount", { walletAccountAddress, targetPublicKey: embeddedKey, }); await iframeStamper.injectKeyExportBundle( response.data.exportBundle, organizationId, KeyFormat.Hexadecimal, walletAccountAddress ); setIsKeyLoaded(true); }; // Sign message const handleSignMessage = async () => { if (!iframeStamper || !isKeyLoaded) return; const sig = await iframeStamper.signMessage( { message, type: MessageType.Solana }, walletAccountAddress ); setSignature(sig); }; return (
{!isKeyLoaded ? ( ) : (