Skip to main content

Identity Cryptography

The Identity system gives every participant — human, agent, device — a cryptographic address. All actions are signed and verifiable, enabling trust without a central authority at runtime.

This page is the spec reference. For the everyday view (creating access keys, recovery codes, revoking), see Identity.

Theory and motivation

AI agents that communicate — internally within an application, or externally with other services and agents — need a trust mechanism. Traditional approaches rely on centralized session tokens or API keys that a server issues and validates. This creates a single point of failure and requires the central authority to be online for every interaction.

Osaurus takes a different approach: address-based identity. Every participant derives a cryptographic keypair and is identified by the address of its public key. When an agent signs a message, any verifier can confirm the signature came from that address without contacting a server. Authority flows from a human-controlled root key down to agents, and from there to devices — forming a verifiable chain of trust.

Design goals:

  1. Self-identifying — Every agent carries its own address. No lookup table or registry needed.
  2. Verifiable — Signatures can be checked by anyone holding the public address. No callbacks to a central authority.
  3. Hierarchical — Authority flows from human (master) to agent to device, with clear delegation boundaries.
  4. Offline-capable — Agents can prove their identity without network access to an identity server.
  5. Revocable — Compromised keys can be revoked at any level without replacing the entire identity tree.

Address hierarchy

Master Address (Human)
├── Agent Address (index 0)
├── Agent Address (index 1)
├── Agent Address (index 2)
│ ...
└── Device ID (per physical device)

Master address

The human's root identity. All authority flows from this address.

PropertyDetail
Curvesecp256k1
StorageiCloud Keychain (syncs across Apple devices)
AccessRequires biometric authentication (Face ID / Touch ID)
FormatChecksummed hex address (EIP-55 style), e.g. 0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18

The master key is a 32-byte random secret generated via SecRandomCopyBytes. Stored once in the Keychain and never exported. The address is derived from the corresponding secp256k1 public key via Keccak-256 hashing.

Agent addresses

Each agent gets a deterministic child key derived from the master key.

PropertyDetail
DerivationHMAC-SHA512 with domain separation
StorageNever stored — re-derived on demand from the master key
AssociationEach agent's agentIndex and agentAddress are persisted on the Agent model

Agent addresses enable per-agent scoping: an access key signed by an agent can only authorize actions for that specific agent.

Device ID

A hardware-bound identity that proves which physical device is making a request.

PropertyDetail
HardwareApple App Attest (Secure Enclave P-256 key)
Format8-character hex string derived from the attestation key ID
FallbackSoftware-generated random ID when App Attest is unavailable (development builds)

The device ID adds a second authentication factor: even if someone obtains a valid identity signature, they cannot forge the device assertion without physical access to the Secure Enclave.

Key derivation

Master key

32 random bytes (SecRandomCopyBytes)
→ secp256k1 private key
→ uncompressed public key (drop 0x04 prefix)
→ Keccak-256 hash
→ last 20 bytes
→ checksummed hex address (EIP-55)

Stored in iCloud Keychain with kSecAttrAccessibleWhenUnlocked. iCloud sync is attempted first; if unavailable, stored device-only with kSecAttrAccessibleWhenUnlockedThisDeviceOnly.

Agent key

HMAC-SHA512(
key: masterKey, // 32 bytes
data: "osaurus-agent-v1" || bigEndian(index) // domain + 4-byte index
)
→ first 32 bytes of HMAC output
→ same address derivation as master key

The domain prefix osaurus-agent-v1 prevents cross-protocol key reuse. The big-endian index encoding ensures a canonical byte representation across platforms. Each unique index produces a completely independent keypair.

Agent keys are never persisted. They are re-derived from the master key whenever a signature is needed, which requires biometric authentication to access the master key. The derived agentAddress is persisted on the Agent model so it can be displayed without triggering biometric prompts.

Device key

  • Hardware path: DCAppAttestService.generateKey() creates a P-256 key in the Secure Enclave. The key ID is hashed with SHA-256 and truncated to 4 bytes (8 hex characters) for the device ID.
  • Software fallback: 4 random bytes via SecRandomCopyBytes, stored in UserDefaults for stability across launches.

Two-layer request signing

Every authenticated API request carries a two-layer signed token. This binds each request to both a cryptographic identity and a physical device.

Token structure

header.payload.accountSignature.deviceAssertion

Four base64url-encoded segments joined by .:

SegmentEncodingContent
Headerbase64url(JSON)Algorithm, type, version
Payloadbase64url(JSON)Claims (see below)
Identity Signaturehexsecp256k1 recoverable signature (65 bytes)
Device Assertionbase64urlApp Attest assertion (or empty for software fallback)
{
"alg": "es256k+apple-attest",
"typ": "osaurus-id",
"ver": 5
}

Payload fields

FieldTypeDescription
issstringIssuer address (master or agent)
devstringDevice ID (8-char hex)
cntuint64Monotonic counter (anti-replay)
iatintIssued-at timestamp (Unix seconds)
expintExpiration timestamp (Unix seconds, typically iat + 60)
audstringAudience (target service hostname)
actstringAction being authorized (e.g. "GET /v1/models")
parstring?Parent address (for agent-issued tokens, the master address)
idxuint32?Agent index (for agent-issued tokens)

Signing process

  1. Encode payload as JSON
  2. Layer 1 — Identity signature: Domain-separated secp256k1 signing
    • Envelope: \x19Osaurus Signed Message:\n<payload>
    • Hash: Keccak-256 of the envelope
    • Sign: secp256k1 with recovery (produces 65 bytes: r ‖ s ‖ v)
  3. Layer 2 — Device assertion: App Attest assertion over SHA-256 of the payload
  4. Assemble: base64url(header).base64url(payload).hex(accountSig).base64url(deviceAssertion)

The domain prefix Osaurus Signed Message prevents signed payloads from being replayed in other protocols that use the same curve.

Access keys (osk-v1)

Access keys are portable, long-lived tokens for external authentication. They allow tools, MCP clients, and remote agents to authenticate against Osaurus without biometric access to the device.

Format

osk-v1.<base64url-encoded-payload>.<hex-encoded-signature>

Three parts separated by .:

  1. Prefix: osk-v1 (identifies the token format and version)
  2. Payload: Base64url-encoded canonical JSON
  3. Signature: Hex-encoded 65-byte secp256k1 recoverable signature

Payload fields

FieldTypeDescription
audOsaurusIDAudience address (who this key is for)
cntuint64Counter value at creation time
expint?Expiration timestamp (null = never expires)
iatintIssued-at timestamp
issOsaurusIDIssuer address (who signed this key)
lblstring?Human-readable label
noncestringUnique identifier for revocation

Fields are sorted alphabetically for canonical JSON encoding (ensuring consistent signature verification).

Scoping

  • Master-scoped: Signed by the master key. iss and aud are both the master address. Grants access to all agents.
  • Agent-scoped: Signed by a derived agent key. iss and aud are both the agent address. Grants access only to that specific agent.

The /pair Bonjour flow always issues agent-scoped keys (agentIndex from the approved agent). Keys generated manually from the Settings UI may be either, depending on what the user selects.

Expiration options

OptionDuration
30d30 days
90d90 days (default for /pair)
1y1 year
neverNo expiration (only when the user opts in via the pairing dialog's "Remember this device permanently" toggle)

Validation

When a request arrives with an osk-v1 token:

  1. Parse the three segments (prefix, payload, signature)
  2. Decode the base64url payload into AccessKeyPayload
  3. Recover the signer address via ecrecover with Osaurus Signed Access domain prefix
  4. Verify issuer — recovered address must match payload.iss
  5. Check audiencepayload.aud must match the agent or master address
  6. Check whitelistpayload.iss must be in the effective whitelist
  7. Check revocation — not individually revoked (address + nonce) and not bulk-revoked (counter threshold)
  8. Check expirationpayload.exp must be in the future (if set)

Only metadata is stored after key creation (label, prefix, nonce, counter, addresses, dates). The full key string is shown once and never persisted.

Whitelist system

The whitelist controls which addresses are authorized to issue access keys. It operates at two levels:

Master-level whitelist

Addresses in the master whitelist can issue keys for any agent.

Per-agent overrides

Additional addresses can be authorized for specific agents only. These are additive — they extend the master whitelist, not replace it.

Effective whitelist

The effective whitelist for a given agent is computed as:

effective = masterWhitelist ∪ agentWhitelist[agent] ∪ {agentAddress, masterAddress}

The agent's own address and the master address are always implicitly included.

Storage

Whitelist data is persisted in macOS Keychain (kSecAttrAccessibleWhenUnlockedThisDeviceOnly), keyed by com.osaurus.whitelist.

Revocation

Access keys can be revoked through two mechanisms:

Individual revocation

Revoke a specific key by its (address, nonce) pair. The composite key address:nonce is added to the revocation set.

Bulk revocation

Revoke all keys from an address with counter values at or below a threshold. Implemented as a counter threshold per address — any key with cnt <= threshold is revoked.

When checking revocation:

isRevoked = revokedKeys.contains(address:nonce)
|| (counterThresholds[address] >= cnt)

Storage

Revocation data is persisted in macOS Keychain (kSecAttrAccessibleWhenUnlockedThisDeviceOnly), keyed by com.osaurus.revocations.

Recovery

During initial identity setup, a one-time recovery code is generated:

OSAURUS-XXXX-XXXX-XXXX-XXXX

Format: OSAURUS- prefix followed by 4 groups of 4 uppercase hex characters (8 random bytes = 64 bits of entropy).

The recovery code is:

  • Generated from SecRandomCopyBytes (cryptographically secure)
  • Shown to the user exactly once during setup
  • Discarded from application memory after display
  • Never stored on device in plaintext

Internal vs external communication

Internal communication

Agents within the same Osaurus instance authenticate using the full two-layer token system:

  • Layer 1: secp256k1 identity signature (master or agent key)
  • Layer 2: App Attest device assertion

Strongest authentication: both the cryptographic identity and the physical device are verified. Requires biometric access to the master key.

External communication

External tools, MCP clients, and remote agents authenticate using osk-v1 access keys:

  • Single-layer: secp256k1 signature only (no device assertion)
  • Portable: usable from any device or service
  • Scopable: master-scoped (all agents) or agent-scoped (single agent)
  • Revocable: individual or bulk revocation without affecting other keys

Access keys bridge the gap between hardware-bound internal identity and the need for third-party integrations that can't access the Secure Enclave.

Bonjour pairing

POST /pair is an unauthenticated, signature-verified flow used by the in-app connector to onboard a new device against a Bonjour-discovered agent.

  1. Connector signs a nonce with its connectorAddress private key (domain prefix Osaurus Signed Pairing)
  2. The Osaurus instance verifies the signature, resolves the target agent, and shows an approval dialog naming both the connector and the agent
  3. On approval, the host mints an agent-scoped osk-v1 key for the approved agent (agentIndex = agent.agentIndex) with a 90-day expiration by default. The user can opt in to a non-expiring key via the dialog's "Remember this device permanently" toggle
  4. The response body containing the new key is sent on the wire but never persisted to the request logInsightsService redacts both apiKey JSON values and Bearer osk-… headers as defense-in-depth across all logged bodies

Pairings approved before the agent-scoping fix are master-scoped, never-expiring keys. The Settings → Server pane labels them as Legacy and explains: "Pre-upgrade pairing — grants access to all agents and never expires."

Pre-auth body limits

Both Osaurus HTTP servers reject oversized request bodies before the auth gate runs, so an unauthenticated client cannot exhaust host memory:

EndpointLimitConfigurable via
POST /pair64 KiBServerConfiguration.maxPairingBodyBytes
Other public HTTP routes32 MiBServerConfiguration.maxRequestBodyBytes
Sandbox host bridge8 MiBhard-coded in HostAPIBridgeHandler

Both servers enforce the cap with a Content-Length pre-check at request head and a streaming guard at body chunks, so chunked clients and clients that lie about their declared length both hit 413 Payload Too Large.

Future: cross-instance communication

The address-based design naturally extends to agent-to-agent communication across different Osaurus instances. Since every agent has a globally unique address and can sign messages, agents can verify each other's identity without a shared authority — only knowledge of the other agent's address is needed.

Security properties

PropertyMechanism
Master key never leaves KeychainStored with kSecAttrAccessibleWhenUnlocked, read requires LAContext biometric auth
Agent keys never storedRe-derived on demand via HMAC-SHA512 from master key
Device keys hardware-boundSecure Enclave P-256 via App Attest (DCAppAttestService)
Anti-replayPer-device monotonic counter (cnt) persisted in UserDefaults; server rejects seen values
Domain separationOsaurus Signed Message, Osaurus Signed Access, Osaurus Signed Pairing prefixes prevent cross-protocol signature reuse
Recovery code single-useGenerated from SecRandomCopyBytes, shown once, never stored on device
Canonical encodingAccess key payloads use sorted-key JSON for deterministic signature verification
Memory safetyMaster key bytes are zeroed after use (memset / index-level zeroing)
Pairings scoped to one agent/pair mints agent-scoped keys (agentIndex from approved agent), 90-day default expiry
Issued credentials never logged/pair success path logs a redacted body; InsightsService.redactCredentials scrubs osk-v1 values and Bearer headers everywhere
Pre-auth body-size limits/pair capped at 64 KiB, other public routes at 32 MiB; rejected with 413 before the auth gate

File reference

FileResponsibility
MasterKey.swiftGenerate, store, read, sign with the secp256k1 master key in iCloud Keychain
AgentKey.swiftDeterministic child key derivation (HMAC-SHA512) and signing for per-agent identities
DeviceKey.swiftApp Attest key generation, attestation, assertion, and software fallback
OsaurusIdentity.swiftPublic entry point — orchestrates setup and two-layer request signing
IdentityModels.swiftData types: OsaurusID, TokenHeader, TokenPayload, AccessKeyPayload, AccessKeyInfo, AgentInfo, RevocationSnapshot
APIKeyManager.swiftGenerate, persist, and revoke osk-v1 access keys (metadata in Keychain)
APIKeyValidator.swiftImmutable, lock-free access key validation via ecrecover + whitelist + revocation
WhitelistStore.swiftMaster-level and per-agent address whitelist with Keychain persistence
RevocationStore.swiftIndividual and bulk access key revocation with Keychain persistence
CounterStore.swiftPer-device monotonic counter in UserDefaults
RecoveryManager.swiftOne-time recovery code generation at identity creation
CryptoHelpers.swiftKeccak-256, domain-separated signing, ecrecover, address derivation, encoding utilities
OsaurusIdentityError.swiftError types for the identity system

Related: