Engineering

API Authentication Deep Dive: How Proxed Securely Verifies Your Requests

API Authentication Deep Dive: How Proxed Securely Verifies Your Requests

Authentication is the foundation of API security. Let's explore how Proxed's multi-layered authentication works and why we designed it this way.


#
Authentication Flow Overview

When your app makes a request to Proxed, several security checks happen in sequence:

  1. Initial Identification: Your project is identified through a project ID in the URL path
  2. Authentication Method Detection: We determine which auth method you're using
  3. Key Verification: We validate your API key(s) using a split-key approach
  4. Device Validation: For production requests, we verify the authenticity of the iOS device
  5. Usage Checks: We ensure your account is in good standing and within usage limits

This process takes milliseconds but provides multiple layers of security.


#
Three Ways to Authenticate

We support multiple authentication methods to accommodate different use cases:

This is our primary method, supporting both test keys and device tokens:

curl -X POST https://api.proxed.dev/v1/openai/your-project-id/chat/completions \
  -H "Authorization: Bearer your-partial-key.your-token" \
  -H "Content-Type: application/json" \
  -d '{...}'

With this method:

  • The partial API key is extracted from the first part of the Bearer token
  • The second part can be either a test key or a DeviceCheck token
  • You don't need to provide an additional x-ai-key header

Why we use this format: Many AI SDKs don't support custom headers like x-ai-key, but they do support setting the Authorization header. The combined format allows us to transmit both the partial API key and device token in a single standard header that works with virtually any HTTP client or SDK.

#
2. Test Key Authentication (Development)

This method is designed for testing during development:

curl -X POST https://api.proxed.dev/v1/openai/your-project-id/chat/completions \
  -H "x-proxed-test-key: your-test-key" \
  -H "x-ai-key: your-partial-key" \
  -H "Content-Type: application/json" \
  -d '{...}'

This method:

  • Requires Test Mode to be enabled for your project
  • Requires both your test key and partial API key
  • Bypasses device verification
  • Should only be used during development

#
3. Device Token Authentication (Legacy)

Our original method, which we maintain for backward compatibility:

curl -X POST https://api.proxed.dev/v1/openai/your-project-id/chat/completions \
  -H "x-device-token: your-device-token" \
  -H "x-ai-key: your-partial-key" \
  -H "Content-Type: application/json" \
  -d '{...}'

This method:

  • Requires separate headers for the device token and API key
  • Still performs full device verification
  • Will eventually be deprecated in favor of the Bearer method

#
Under the Hood: How It Works

Let's explore what happens when a request hits our API gateway:

#
Project Resolution

We extract your project ID from the URL path parameter (/v1/provider/{projectId}/endpoint). This allows us to look up your project configuration, including whether you're in test mode and if device verification is enabled.

Using the project ID in the URL path makes your requests more RESTful and explicit about which project context they're operating in.

#
Key Splitting Architecture

We never store complete API keys for third-party providers. Instead:

  • You retain a portion of the key (partial key)
  • We store the complementary portion securely
  • Both parts are needed to reconstruct the full key
  • The full key only exists momentarily during request processing

This approach ensures that even if our servers were compromised, attackers would only have access to partial keys, not complete ones.

SDK Compatibility: Our Bearer token method (Authorization: Bearer partialKey.token) enables the use of standard AI SDKs that don't support custom headers. This means you can use official libraries from providers like OpenAI or Anthropic with minimal configuration, while still maintaining our security model.

#
Device Verification with Apple's DeviceCheck

For production requests, we validate that the request comes from a legitimate iOS device:

  1. Your app requests a DeviceCheck token from Apple
  2. Your app includes this token in the request to our API
  3. Our server validates this token with Apple's servers
  4. We proceed only if Apple confirms the device is legitimate

This prevents unauthorized usage from non-iOS environments, scripts, or emulators.


#
Authentication in Your iOS App

Here's how to implement authentication in your iOS app:

import DeviceCheck

func makeAuthenticatedRequest() async throws {
    // 1. Generate a DeviceCheck token (for production)
    let deviceToken = try await getDeviceToken()

    // 2. Prepare the API request with projectId in the path
    let projectId = "your-project-id" // UUID format: e29c1826-f314-4c9c-801f-0ce1827c8153
    var request = URLRequest(url: URL(string: "https://api.proxed.dev/v1/openai/\(projectId)/chat/completions")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    // 3. Set authentication headers (Bearer token method)
    request.setValue("Bearer \(partialKey).\(deviceToken)", forHTTPHeaderField: "Authorization")

    // 4. Set request body and send
    request.httpBody = try JSONEncoder().encode(requestBody)
    let (data, response) = try await URLSession.shared.data(for: request)

    // 5. Process response
    // ...
}

func getDeviceToken() async throws -> String {
    guard DCDevice.current.isSupported else {
        throw AuthError.deviceCheckNotSupported
    }

    return try await withCheckedThrowingContinuation { continuation in
        DCDevice.current.generateToken { token, error in
            if let error = error {
                continuation.resume(throwing: error)
                return
            }

            guard let token = token else {
                continuation.resume(throwing: AuthError.tokenGenerationFailed)
                return
            }

            continuation.resume(returning: token.base64EncodedString())
        }
    }
}

#
Security Considerations

Our authentication system addresses several key security concerns:

  1. API Key Protection

    • Keys are never completely stored in any one location
    • Keys are never embedded in client apps
    • The full key is only momentarily reconstructed during request processing
  2. Request Forgery Prevention

    • DeviceCheck verification prevents requests from non-iOS sources
    • Multiple authentication factors (project ID, API key, device token)
    • Token-based approach that can be revoked if needed
  3. Usage Control

    • Rate limiting and usage tracking
    • Project-specific permissions and settings
    • Automatic detection of suspicious usage patterns

#
Best Practices

To maximize security in your application:

  1. Use Bearer Authentication: Our recommended method for all new implementations
  2. Rotate Keys Regularly: Create new API keys periodically
  3. Keep Test Mode Disabled in production environments
  4. Implement Proper Error Handling for authentication failures
  5. Monitor Your Usage to detect unauthorized access attempts
  6. Use HTTPS for all API communications
  7. Include Project ID in URL Path: Always use the project ID in the URL path for better REST practices

#
What's Next

Authentication is just one part of our security architecture. In upcoming posts, we'll explore:

  • Advanced rate limiting strategies
  • Custom validation rules for API requests
  • Enterprise security features
  • Multi-environment key management

By understanding and properly implementing these authentication methods, you're building a strong foundation for your AI-powered applications.

Updates

New Onboarding Flow

New Onboarding Flow

Last week we shipped a completely rebuilt onboarding experience. Here's what's new and why we made these changes.


#
The Problem

Setting up security for AI integrations has been unnecessarily complex. We kept seeing users struggle with the same issues:

  • Confused about where to start and what order to do things
  • Getting stuck during DeviceCheck configuration
  • Losing track of partial keys after creation
  • Missing important security steps

#
What's New

We've created a linear, guided flow that walks you through each setup step:

  1. Team creation → Just enter a name (that's it)
  2. Member invites → Add your colleagues with proper roles from day one
  3. DeviceCheck setup → Visual guide for Apple Developer credentials
  4. Partial keys → Smart key detection and safe client-side splitting

Each component works well on its own but forms a complete security system when combined.


#
Team Creation & Invites

Team Invite

The new team form is minimal - just enter a name and go. For invites, we added:

  • Multi-member invitations in one go (no more one-by-one)
  • Inline role selection (Owner/Member)
  • Email validation that catches common mistakes

#
DeviceCheck Made Simple

DeviceCheck Configuration

Configuring DeviceCheck used to require reading through pages of docs. Now:

  • Visual field explanations with tooltips
  • Inline documentation about Apple's credentials
  • Proper p8 file handling with validation
  • Smart error messages that tell you exactly what's wrong

#
Better Partial Key Management

Partial Keys

The key management interface got major improvements:

  • Auto-detection of key type (OpenAI, Anthropic, etc.)
  • One-time secure key splitting that happens client-side
  • Clear visuals showing which part is stored where
  • Copy protection for client parts with confirmation

#
Docs That Actually Help

Instead of generic documentation, we created specific guides:

Each component in the UI links directly to relevant documentation sections.


#
What's Next

We're focused on improving these specific areas next:

  • Usage notifications and alerts
  • Better usage analytics with cost forecasting
  • Real-time logging and monitoring of API requests
Engineering

New Structured Response Routes: Text and PDF Analysis

New Structured Response Routes: Text and PDF Analysis

#
New Structured Response Routes: Text and PDF Analysis

We're excited to announce two new routes in our API: Text and PDF analysis with structured responses. These additions complement our existing Vision route, providing a comprehensive suite of AI-powered analysis tools.

#
Text Analysis Route

The new /v1/text endpoint allows you to send text content and receive structured, schema-validated responses. This is perfect for:

  • Sentiment analysis
  • Topic extraction
  • Text summarization
  • Key phrase identification
  • Custom text analysis based on your schema

Example request:

POST /v1/text/<your-project-id>
Content-Type: application/json
x-ai-key: <your-api-key>

{
  "text": "Your text content here"
}

#
PDF Analysis Route

The /v1/pdf endpoint enables structured analysis of PDF documents. You can send PDFs either as a URL or base64-encoded data. This is ideal for:

  • Document summarization
  • Information extraction
  • Table and figure analysis
  • Content structuring
  • Custom PDF analysis based on your schema

Example request with URL:

POST /v1/pdf/<your-project-id>
Content-Type: application/json
x-ai-key: <your-api-key>

{
  "pdf": "https://example.com/document.pdf"
}

Example request with base64:

POST /v1/pdf/<your-project-id>
Content-Type: application/json
x-ai-key: <your-api-key>

{
  "pdf": "data:application/pdf;base64,..."
}

#
Key Features

Both routes include:

  • Schema Validation: Define your response structure in the project settings
  • Flexible Input: Support for various input formats
  • Security: Full DeviceCheck integration
  • Metrics Tracking: Monitor usage, latency, and performance
  • Error Handling: Comprehensive error reporting
  • Location Awareness: Optional geographic context for responses

#
Implementation Example

Here's a Swift example showing how to use both routes:

actor ContentAnalyzer {
    let apiKey = "<your-api-key>"
    let textEndpoint = "https://api.proxed.ai/v1/text/<your-project-id>"
    let pdfEndpoint = "https://api.proxed.ai/v1/pdf/<your-project-id>"

    // Analyze text
    func analyzeText(_ text: String) async throws {
        let token = await SimpleDeviceCheck.retrieveToken()

        var request = URLRequest(url: URL(string: textEndpoint)!)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(apiKey, forHTTPHeaderField: "x-ai-key")
        if let token = token {
            request.setValue(token, forHTTPHeaderField: "x-device-token")
        }
        request.httpBody = try JSONEncoder().encode(["text": text])

        let (data, _) = try await URLSession.shared.data(for: request)
        let analysis = try JSONDecoder().decode(Analysis.self, from: data)
        print("Analysis:", analysis)
    }

    // Analyze PDF from URL
    func analyzePDF(url: URL) async throws {
        let token = await SimpleDeviceCheck.retrieveToken()

        var request = URLRequest(url: URL(string: pdfEndpoint)!)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(apiKey, forHTTPHeaderField: "x-ai-key")
        if let token = token {
            request.setValue(token, forHTTPHeaderField: "x-device-token")
        }
        request.httpBody = try JSONEncoder().encode(["pdf": url.absoluteString])

        let (data, _) = try await URLSession.shared.data(for: request)
        let analysis = try JSONDecoder().decode(Analysis.self, from: data)
        print("Analysis:", analysis)
    }
}

#
Getting Started

  1. Create a new project in the dashboard
  2. Define your response schema
  3. Generate an API key
  4. Implement DeviceCheck security
  5. Start making requests!

Check out our documentation for detailed implementation guides and best practices.

#
What's Next?

We're continuously working on improving our API. Coming soon:

  • More input formats
  • Enhanced analysis capabilities
  • Additional language support
  • Advanced schema validation options

Stay tuned for more updates!

Product

Proxed.AI Public Launch: Secure AI Integration Made Simple

Proxed.AI Public Launch: Secure AI Integration Made Simple

I'm thrilled to announce that after months of development and testing, Proxed.AI will be opening its doors to the public in the coming weeks. This is a major milestone for us, and I wanted to share what's coming and how you can get early access.

#
What is Proxed.AI?

Proxed.AI is an open-source platform that makes securing AI API integrations as simple as changing a URL. No SDKs, no complex backend setup—just instant security and structured responses for your AI-powered iOS apps.

#
Key Features at Launch

#
🔐 One-URL Security

  • Secure your AI API keys with a simple URL change
  • Zero code changes required in your existing integration
  • Full support for OpenAI and Anthropic APIs

#
🛡️ DeviceCheck Integration

  • Hardware-level device verification
  • Automatic blocking of emulators and jailbroken devices

#
🧠 Visual Schema Builder

  • Design AI response structures visually
  • Drag-and-drop interface for creating type-safe schemas
  • Real-time validation and testing

#
📊 Analytics Dashboard

  • Monitor API usage in real-time
  • Track costs and performance
  • Detailed request logging and debugging

#
What's Coming Next?

  • Rate Limiting & Cost Control: Set custom usage limits and prevent unexpected costs
  • Multi-Provider Support: Seamlessly switch between different AI providers
  • Custom Validation Rules: Create advanced validation logic for your AI responses

#
Early Access

Want to try Proxed.AI before the public launch? We're offering early access to a limited number of developers. Here's how to get involved:

  1. Star our GitHub repository
  2. Follow us on Twitter

#
Open Source First

Proxed.AI is and will always be open source. We believe in transparency and community-driven development. Our entire codebase is available on GitHub, and we welcome contributions from the community.

#
Pricing

During the public beta, we're offering generous free tiers to help you get started:

  • Free Tier: 1,000 API calls/month
  • Pro Tier: 10,000 API calls/month at $10
  • Ultimate Tier: 50,000 API calls/month at $30

#
Get Ready

The public launch is just weeks away. Here's how you can prepare:

  1. Check out our documentation
  2. Review our integration guides
  3. Join our community platforms for updates

We can't wait to see what you'll build with Proxed.AI. Stay tuned for more updates and the official launch announcement!

Engineering

Secure Token Generation: Zero-Trust Key Management for iOS

Secure Token Generation: Zero-Trust Key Management for iOS

At Proxed, we've developed a unique approach to API key security that combines split-key architecture with Apple's DeviceCheck system. This ensures your API keys remain secure even if any single component is compromised.


#
The Challenge

Traditional API key management approaches have several vulnerabilities:

  • Complete keys stored on servers create single points of failure
  • Keys exposed in mobile apps can be extracted through reverse engineering
  • Difficult to track and control key usage effectively
  • No way to verify legitimate device usage

#
Our Solution: Multi-Layer Security

We've built a system that combines three security layers:

  1. Split-Key Architecture: Keys are split between server and client
  2. Apple DeviceCheck: Cryptographic verification of legitimate iOS devices
  3. Metadata Tracking: Version control and usage monitoring

This approach ensures:

  • No complete key exists in any single location
  • Only genuine iOS devices can make requests
  • Every key usage is tracked and auditable

#
Token Structure

Our token structure is designed for security and traceability:

Token Structure


#
How It Works

The process combines client-side key splitting with device verification:

  1. Key Splitting (Client-Side):

    • Generate cryptographic salt (16 chars)
    • Create random split point in the key
    • Add version and metadata
    • Split key into server and client parts
  2. Device Verification (iOS Only):

    • Generate DeviceCheck token
    • Get cryptographic validation from Apple
    • Include token with every API request
  3. Request Flow:

    // Generate DeviceCheck token
    DCDevice.current.generateToken { token, error in
        guard let token = token else {
            print("DeviceCheck error: \(error?.localizedDescription ?? "unknown")")
            return
        }
    
        // Make API request with token and client part
        let url = URL(string: "https://api.proxed.ai/v1/structured-response")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
    
        // Set required headers
        request.setValue("application/json", forHTTPHeaderField: "content-type")
        request.setValue(clientPart, forHTTPHeaderField: "x-ai-key")
        request.setValue(token.base64EncodedString(), forHTTPHeaderField: "x-device-token")
        request.setValue(projectId, forHTTPHeaderField: "x-project-id")
    
        // Request payload
        let payload = [...]
        request.httpBody = try? JSONSerialization.data(withJSONObject: payload)
    
        // Make the request
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Request error: \(error.localizedDescription)")
                return
            }
    
            guard let data = data,
                  let json = try? JSONSerialization.jsonObject(with: data) else {
                print("Invalid response")
                return
            }
    
            // Handle the AI response
            print("Response: \(json)")
        }.resume()
    }

#
Security Process

Here's the complete verification flow:

Security Process


#
Security Features

Our implementation includes multiple security layers:

  1. Split-Key Protection:

    • Server part stored securely in our infrastructure
    • Client part stored on device with metadata
    • Both parts required for key reconstruction
    • Key reassembled only during request processing
  2. Device Verification:

    • Every request requires valid DeviceCheck token
    • Tokens cryptographically signed by Apple
    • Prevents non-iOS device access
    • Automatic device validation
  3. Audit & Control:

    • Version tracking for key rotation
    • Usage monitoring per device
    • Suspicious activity detection
    • Granular access control

#
Implementation Example

Here's a real-world example of how the keys are split:

// Original API key
sk-abc123...xyz789

// After splitting
serverPart: "sk-abc1deadbeef"              // Stored on Proxed
clientPart: "23...xyz789deadbeef.00000001000169df12345678"
                                          ^       ^        ^
                                       version timestamp splitId

#
Getting Started

To implement this security system:

  1. Create a Proxed account
  2. Configure your iOS app with DeviceCheck
  3. Generate and split your API keys
  4. Make API calls using our SDK

We handle all the complexity of:

  • Key splitting and reassembly
  • Device verification
  • Usage tracking
  • Security monitoring

#
Future Enhancements

We're actively developing:

  • Automated key rotation
  • Enhanced usage analytics
  • Advanced threat detection
  • Multi-provider key management
  • Additional platform support

Stay tuned for our next post about advanced key management strategies and best practices for secure key rotation.

Feature

Visual Schema Builder: Design Structured LLM Responses with Ease

Visual Schema Builder: Design Structured LLM Responses with Ease

Working with LLMs often requires structured responses, but designing and maintaining these schemas can be challenging. We're excited to introduce our Visual Schema Builder—a tool that makes designing structured LLM responses intuitive and efficient.


#
Visual Schema Design

Design your LLM response structures visually:

  • Drag-and-drop interface for response schema building
  • Real-time validation and preview
  • Instant code generation for your AI wrapper projects
  • Support for complex nested response structures
  • Built-in type system for reliable data extraction

#
Import & Export Flexibility

Seamlessly work with existing LLM schemas:

  • Import existing response schemas
  • Convert JSON examples to schemas
  • Import from Zod schemas
  • Export ready-to-use validation code
  • Export to Swift structs
  • Copy schema code with one click

#
Real-time Validation

Ensure your LLM responses match expectations:

  • Instant validation feedback
  • Type checking for response fields
  • Required field validation
  • Custom validation rules for LLM outputs
  • Format validation for specific data types

#
Code Generation

Generate validation code automatically:

  • Zod schemas for runtime validation
  • JSON Schema for API documentation
  • Swift structs for iOS clients

#
Advanced Features

Power features for complex LLM responses:

  • Custom validation rules for LLM output
  • Default values for missing fields
  • Optional response fields
  • Array validations for lists
  • Nested object support for complex data
  • Union types for varying responses
  • Enum support for fixed options
  • Description fields for documentation and LLM

#
Developer Experience

Built for LLM developers:

  • Keyboard shortcuts for rapid development
  • Search and replace across schema
  • Undo/redo support
  • Schema versioning (coming soon)

#
Getting Started

Start structuring your LLM responses:

  1. Visit your project
  2. Design your response structure
  3. Export code as Swift structs
  4. Use in your AI wrapper project

Transform your LLM responses from unstructured text to strongly-typed data with our Visual Schema Builder!

Product

How Proxed.AI Simplifies Secure AI API Integration

How Proxed.AI Simplifies Secure AI API Integration

Implementing an API proxy with DeviceCheck from scratch can be complex. That's why we built Proxed.AI—an open-source iOS SDK and cloud service that acts as a secure gateway for AI calls. Let's explore how it simplifies the process while maintaining robust security.


#
What is Proxed.AI?

Instead of building your own backend from scratch, you can leverage our managed proxy (or host it yourself) which is built with key security in mind. Our solution provides:

  • Ready-made secure proxy infrastructure
  • DeviceCheck integration
  • Comprehensive security features out of the box
  • Simple developer experience

#
Secure Key Management

We protect your API keys using a split-key approach:

  • Keys are never exposed in your mobile app
  • Keys never travel over the network
  • Your app only uses a project-specific identifiers
  • Even if someone decompiles your app, they get at most a fragment of your provider key
  • Our backend never has your full provider key without your permission
  • Only partial provider keys are stored on our servers

This drastically reduces the risk of key compromise while maintaining security.


#
Built-in DeviceCheck Verification

Every request through Proxed.AI includes automatic DeviceCheck verification:

  • Backend verifies tokens with Apple
  • No need to implement server-side logic yourself
  • Requests only go through from valid iOS clients
  • Zero configuration required from developers

#
Additional Safety Features

Beyond basic security, we provide comprehensive protection:

  • Rate limiting to prevent abuse
  • Usage tracking for monitoring
  • Cost monitoring out-of-the-box
  • Real-time logs and analytics
  • Unusual activity detection (coming soon)
  • Customizable usage limits
  • Automatic cost prevention (coming soon)

#
Easy Integration

From a developer's perspective, using Proxed.AI is straightforward:

  1. Configure your project and endpoint
  2. Replace direct API calls with Proxed.AI calls
  3. Let us handle:
    • Device verification
    • Key management
    • Response formatting
    • Security best practices

#
Open Source and Free During Beta

We believe in transparency and community:

  • Fully open source codebase
  • Free during beta period
  • Self-hosting option available
  • Community-driven development
  • Continuous improvements

#
Focus on What Matters

With Proxed.AI, you can concentrate on building great features instead of:

  • Wrestling with device verification
  • Managing API credentials
  • Handling complicated responses
  • Implementing security measures
  • Building proxy infrastructure

Our goal is to make secure AI integration a solved problem for iOS developers.


#
Getting Started

Ready to secure your AI API keys? Here's how:

  1. Check out our GitHub repo
  2. Follow our quick start guide

Stay tuned for our next post where we'll share real-world case studies of developers using Proxed.AI in production.

Security

Best Practices for Securing API Keys in Mobile Applications

Best Practices for Securing API Keys in Mobile Applications

Beyond the basic DeviceCheck implementation, there are several critical practices you should follow to ensure your API keys remain secure. Let's explore these essential security measures.


#
Never Embed Plain API Keys in the App

This is rule #1 of mobile app security:

  • Don't hardcode API keys in your app's binary
  • Attackers can easily decompile apps and extract keys
  • If you need a client-side identifier, use:
    • A less-privileged token
    • A project ID that maps to the real key on your server
    • Time-limited tokens generated by your backend

#
Use a Secure Backend Proxy

Your mobile app should be a thin client:

  • Route all API calls through your secure server
  • Keep real API keys on the server
  • Never let keys leave your control
  • Let your server handle sensitive operations
  • Enforce rate limits and authorization checks

#
Employ Device Attestation

Use platform-specific verification services:

  • iOS: DeviceCheck or App Attest
  • Android: Play Integrity API or SafetyNet
  • These provide cryptographic proof of app authenticity
  • Ensure API keys are only used by genuine app instances
  • Verify the environment is trusted

#
Secure Communications

Protect data in transit:

  • Always use HTTPS for network calls
  • Implement certificate pinning:
    • App only trusts your server's certificate
    • Prevents MITM attacks with fake certificates
    • Be careful with cert updates to avoid breaking the app
  • Validate all server responses
  • Use secure protocols and current best practices

#
Limit API Key Scope and Permissions

Minimize potential damage:

  • Use restrictive API keys when possible
  • Limit access to specific endpoints
  • Set usage caps and rate limits
  • Restrict to specific origins/IPs
  • Create separate keys for different functions
  • Follow the principle of least privilege

#
Monitor Usage and Rotate Keys

Stay vigilant:

  • Track API usage patterns
  • Set up alerts for:
    • Sudden usage spikes
    • Abnormal patterns
    • Geographic anomalies
    • Rate limit violations
  • Rotate keys periodically
  • Have a plan for emergency key rotation
  • Keep logs for forensic analysis

#
Store Keys Securely Server-Side

Don't forget server security:

  • Use environment variables or secure vaults
  • Never store keys in code or version control
  • Limit access to keys based on roles
  • Protect server endpoints:
    • Require proper authentication
    • Validate all inputs
    • Rate limit requests
    • Log access attempts

#
Defense in Depth

Remember, security is about layers:

  • Each measure adds protection
  • Multiple barriers slow attackers
  • Monitoring catches breaches early
  • Quick response limits damage
  • Regular audits find weaknesses

At Proxed, we implement all these best practices in our proxy service. Our infrastructure is designed with security-first principles, handling the complexity of key management, monitoring, and rotation so you don't have to. Stay tuned for our next post where we'll dive into real-world security incident case studies and lessons learned.

Engineering

Step-by-Step: Implementing DeviceCheck with an API Proxy

Step-by-Step: Implementing DeviceCheck with an API Proxy

Let's walk through how to implement DeviceCheck with an API proxy to protect your AI API keys. Instead of your app calling the AI service directly with the key, your app will call your own server, which holds the real API key and can perform DeviceCheck validation.


#
1. Set Up DeviceCheck in Apple Developer Account

First, enable DeviceCheck for your app:

  • Turn on the DeviceCheck capability for your App ID in your Apple Developer account
  • Generate a DeviceCheck private key (.p8 key file) in the Apple Developer portal
  • Make note of the key ID and your Apple Team ID—these will be used by your server

#
2. Integrate DeviceCheck in Your iOS App

In your Xcode project, import the DeviceCheck framework and generate a device token before making API calls:

guard DCDevice.current.isSupported else {
    // DeviceCheck not supported (e.g., running in Simulator)
    return
}

DCDevice.current.generateToken { token, error in
    guard let token = token else {
        print("DeviceCheck token error: \(error?.localizedDescription ?? "unknown error")")
        return
    }
    let tokenData = token.base64EncodedString()
    // include tokenData in your request to the server
}

This code checks that DeviceCheck is available (it won't be on simulators or very old devices), then asynchronously generates a token. The token is base64-encoded for transmission.


#
3. Call Your API Proxy Instead of the AI API

Design your app to send requests to your own backend service rather than directly to the AI provider. For example:

  • Instead of calling OpenAI directly: api.openai.com/v1/chat/completions
  • Call your proxy: https://yourserver.com/api/chat

Include the DeviceCheck token in this request (as HTTP headers or JSON payload). Remember: never send the actual API key to the app.


#
4. Verify the DeviceCheck Token on the Server

When your server receives the request:

  • Validate the DeviceCheck token using Apple's server API
  • Create a JWT with your Team ID and private key
  • Send Apple's endpoint:
    • The device token
    • Your app's bundle ID
    • The JWT for authentication
  • Reject the request if validation fails

#
5. Execute the AI API Request Server-Side

If DeviceCheck validation succeeds:

  • Make the actual API call to the AI service from your server
  • Use the API key that's securely stored on the server
  • The key never leaves your server
  • Your server maintains full control

#
6. Return the Response to the App

Simply send the AI service's response back to your iOS app through the proxy. From the app's perspective, it just made a request to your backend and got results.


#
7. (Optional) Utilize DeviceCheck's Device Flags

For extra security:

  • Use DeviceCheck's two bits of device state to record trust or abuse
  • Flag devices that exceed usage limits or show suspicious behavior
  • Check these flags in future requests
  • Refuse service to flagged devices
  • This creates persistent blocking at the hardware level

#
The Security Loop

This implementation creates a secure loop:

  1. iOS app proves legitimacy with DeviceCheck
  2. Server verifies proof with Apple
  3. Only then does server use the API key
  4. Attackers can't bypass without a valid device token

At Proxed, we're implementing this exact flow in our proxy service, making it easy for developers to secure their AI API keys without building this infrastructure themselves. Stay tuned for our next post where we'll explore advanced DeviceCheck patterns and edge cases.

Security

How Apple DeviceCheck Helps Secure API Keys in iOS Apps

How Apple DeviceCheck Helps Secure API Keys in iOS Apps

Apple's DeviceCheck is a service that lets you verify if a request truly comes from an authentic iOS device running your app. In other words, DeviceCheck allows your backend to ask Apple for proof that an API call is from a legitimate iPhone/iPad and not from an emulator or malicious script.


#
What is DeviceCheck?

It's an Apple framework that provides a device-specific token and a server API to validate that token. When your iOS app uses DeviceCheck, it generates a cryptographic token unique to that device. Your server can send this token to Apple's DeviceCheck API to verify it. Apple essentially vouches that "Yes, this token came from a real iOS device with a valid app installation".


#
Verifying Legitimate Devices

When your iOS app uses DeviceCheck, it generates a cryptographic token unique to that device. Your server can send this token to Apple's DeviceCheck API to verify it. This helps confirm the request isn't coming from a spoofed environment. For example, one developer used DeviceCheck to ensure an HTTP request "actually originated from a mobile device" by verifying the token with Apple before proceeding.


#
Blocking Scripted Abuse

Without DeviceCheck, an attacker could potentially mimic API calls by crafting requests to your server or API endpoint directly. With DeviceCheck, those requests would fail because the attacker wouldn't have a valid device token from Apple. Only actual iOS devices running your app can obtain a valid token. This significantly raises the bar for anyone trying to abuse your API key from outside the app. It's no longer enough to steal the API key; they'd also need a jailbroken device or a way to fake Apple's device attestation (which is non-trivial).


#
Persisting Device State

DeviceCheck also allows you to store two bits of data per device on Apple's servers. These bits persist even if the user deletes and reinstalls the app. You can use them to:

  • Mark devices as suspicious
  • Blocklist abusive devices
  • Track device reputation
  • Remember and ban malicious devices at the hardware level

For instance, if you detect a certain device has abused your API (maybe by bypassing usage limits), you could set a bit for that device via DeviceCheck. Later, when that device attempts requests, your server can read those bits and refuse the request if the device was flagged.


#
Lightweight Attestation

DeviceCheck is not as heavy as Apple's full App Attest (which provides even stronger app integrity guarantees). However, DeviceCheck is easier to implement and supports older iOS versions. It provides a reasonable balance for many apps: it ensures the device is valid and allows basic tracking of device reputation.


#
The Complete Solution

While DeviceCheck is powerful, it's most effective when combined with other security measures. At Proxed, we're building a complete solution that integrates DeviceCheck with our secure API proxy and other best practices. This creates multiple layers of protection for your AI API keys.

Stay tuned for our next post where we'll dive into the technical implementation details of integrating DeviceCheck with a proxy server.

Security

Why You Need to Protect AI API Keys in Your App

Why You Need to Protect AI API Keys in Your App

Anyone building AI-powered mobile apps needs to handle API keys carefully. Let's dive into why this is crucial and what can go wrong if you don't.


#
Easy to Extract from Apps

Mobile apps can be downloaded and reverse-engineered by anyone—attackers can decompile your iOS app and extract hardcoded secrets like API keys. Even if you don't hardcode the key, any method of embedding it in the app (like in a hidden file or string) is vulnerable. In one real incident, a developer's OpenAI key was stolen and used to run up unauthorized requests because it was retrievable from the app's client-side code. Simply put: if the key lives in the app, determined hackers will find it.


#
Network Interception Risks

Even if you fetch the API key from a server at runtime instead of shipping it in the app, the key still has to travel to the device. A Man-in-the-Middle (MITM) attack could potentially intercept the key during transit if the connection isn't absolutely secure. Tools like proxy debuggers or rooted devices can sniff out API keys from network calls if not properly protected. Once a key is intercepted, an attacker can use it on their own system.


#
Unauthorized Usage & Abuse

When an API key is exposed, bad actors can use it to impersonate your app's traffic and call the API themselves. This may result in:

  • Fraudulent activities
  • Exhausted rate limits
  • Huge bills on pay-per-use plans
  • Potential data breaches
  • Denial of service

For example, attackers might script thousands of requests with your key, consuming your quota or triggering a denial of service. If your AI API returns sensitive data, a leaked key could even let outsiders extract private data from your backend.


#
"Secret Key" is Not a Security Solution

Some newcomers think "I'll hide the API key in the app" as a security measure. In reality, that's security by obscurity—not effective. If the client app alone knows the secret, it can be extracted. We need a better strategy than simply trusting a static key in the app.


#
The Solution

The best practice is to never ship or expose the secret key in your client app. Instead, you'll want to keep the key on a secure server and have your app communicate with that server. But even then, how do you ensure only your genuine app can talk to your server and use the key? That's where Apple's DeviceCheck comes in.

This is exactly why we're building Proxed—to help developers properly secure their AI API keys using DeviceCheck and other best practices. Stay tuned for more posts about our approach to solving this critical security challenge.

Engineering

Starting Proxed: Building the iOS AI API Protection I Need

Starting Proxed: Building the iOS AI API Protection I Need

I'm thrilled to share the start of Proxed—an iOS Proxy API with DeviceCheck integration. My goal is to solve some of the biggest headaches in working with AI models on iOS.


#
The Problem

Anyone who's developed AI-driven iOS apps knows the pain of juggling multiple interfaces, managing API keys across different products, and endlessly worrying about how to protect those keys. Current tooling is fragmented and unwieldy. Developers deserve a simpler, unified approach to safely integrate AI into their mobile apps.


#
What We're Building

Proxed is designed to be your secure gateway for AI calls on iOS. Core features include:

  • Secure Key Management: Protect your API keys behind a proxy, minimising exposure within your app
  • DeviceCheck Integration: Automatically verify genuine iOS devices, preventing illegitimate requests
  • Structured Responses: Define schemas and get neatly validated outputs, streamlining your AI workflows
  • Usage Tracking: Monitor usage to help manage costs and optimise performance

#
Open Source First

The best tools grow from real-world collaboration and feedback. That's why Proxed is open source. You can explore the code on GitHub and contribute your ideas, bug reports, and pull requests. Together, we can shape a platform that meets our shared needs.


#
Initial Focus

For this initial phase, I'm focusing on:

  • Core Platform Architecture
  • DeviceCheck Integration
  • Structured Responses

As these elements stabilise, I'll expand on them to provide even more features for AI-driven apps.


#
Get Involved

If you're passionate about making AI on iOS simpler and more secure, here's how to keep track:

  • Check out the code on GitHub
  • Follow our progress on X
  • Learn more about my background and vision for Proxed on our about page

I look forward to your insights and contributions as we build Proxed into a robust solution for iOS AI developers!