> ## Documentation Index
> Fetch the complete documentation index at: https://docs.shipmobilefast.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 3. AI Proxy Backend

> Set up your AI Proxy Backend.

### Now we need to set up our AI Proxy Backend.

<Info>
  The AI Proxy Backend is a NodeJS backend that will proxy requests to AI services.

  So your API keys are not exposed to the users. They are safe in the backend.
</Info>

# AI Proxy Backend Guide

## Requirement!

<Warning>
  Firebase Service Account JSON file.
</Warning>

You can not send requests to the backend without Firebase Token Verification. This is a security feature.

## Available Endpoints

* `/auth` `POST` endpoint for authentication and get secret key.
* `/ai/openai` `POST` endpoint for OpenAI requests
* `/ai/openai/stream` `POST` endpoint for OpenAI streaming requests
* `/ai/vision` `POST` endpoint for OpenAI Vision API requests
* `/ai/anthropic` `POST` endpoint for Anthropic requests
* `/ai/anthropic/stream` `POST` endpoint for Anthropic streaming requests
* `/ai/replicate/generate` `POST` endpoint for Replicate requests
* `/ai/fal/generate` `POST` endpoint for Fal AI requests

## Security Architecture

Our backend uses a multi-layer security approach:

1. First Layer: **API Key Protection**

* We don't send the API\_KEY directly
* Instead, we create a signature using the API\_KEY
* Check the `useHmac` hook and `api-client.ts` in the Expo code for implementation

2. Second Layer: **HMAC Authentication**

* Backend validates the signature
* If valid, returns an encrypted secret key
* App automatically decrypts and stores it in Keychain

3. Third Layer: **Firebase Authentication**

* Every request requires a Firebase idToken
* Tokens refresh hourly
* Backend caches tokens for 45 minutes
* 15-minute window for token updates

## Request Headers

```ts api-client.ts theme={null}
// For AI endpoints (POST)
method: 'POST',
headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${idToken}`, // Firebase idToken
    'x-signature': signature, // HMAC signature
    'x-timestamp': timestamp, // Timestamp
    'x-nonce': nonce, // Nonce
    ...
}
```

```ts useHmac.ts theme={null}
// For AUTH endpoint (POST)
    headers: {
    'Content-Type': 'application/json',
    'x-signature': signature,
    'x-timestamp': timestamp,
    'x-nonce': nonce,
    'x-app-identifier': appIdentifier,
    'x-device-id': deviceId,
    'x-platform': platform,
    'x-user-id': userId,
    },
```

## Important Notes

* Auth endpoint is used only once when the app first opens
* Rate limited to 1 auth request per 5 minutes
* HMAC secret key is stored securely in Keychain
* All requests require both HMAC signature and Firebase token

### How to start on Local?

1. You can start your backend on local with `pnpm run dev`
2. Then you can send requests to `http://localhost:3000/...`

<Warning>
  But if you try to send requests with your local device, you can't do that.

  I believe the easiest way to test your backend is using the ngrok.

  You can check: [ngrok](https://ngrok.com/) but be careful. It is opening a tunnel to your local machine.

  Otherwise you can find your local ip address and send requests to it.
</Warning>

```bash theme={null}
ngrok http 3000
```

* Then you can send requests to `https://[your-ngrok-id].ngrok.app/...`

<br />

## How to create our AI Proxy Backend?

<Steps>
  <Step>
    Now you need to clone the AI Proxy Backend (NodeJS) Repository.

    <Warning>
      Make sure you are not in the `your-project-name` folder.
    </Warning>

    ```bash theme={null}
    git clone https://github.com/shipmobilefast/shipmobilefast-ai-backend.git [your-project-name]-backend
    ```
  </Step>

  <Step>
    Open your terminal and run the commend above.

    Then type `cd [your-project-name]-backend`.

    <Frame>
      <img src="https://mintcdn.com/shipmobilefast-51a499dc/4ztR-scAO2Zjz6Y6/images/aiwrapper/backend/1.png?fit=max&auto=format&n=4ztR-scAO2Zjz6Y6&q=85&s=f2a31af8848fd1687bf59d6754f87e1f" alt="Firebase" className="w-full" width="799" height="136" data-path="images/aiwrapper/backend/1.png" />
    </Frame>
  </Step>

  <Step>
    After cloning the project, create two environment files:

    ```bash theme={null}
    cp .env.example .env.local
    cp .env.example .env.production
    ```
  </Step>

  <Step>
    Install the dependencies. I am using `pnpm` but you can use `npm` or `yarn`.

    ```bash theme={null}
    pnpm install
    ```
  </Step>

  <Step>
    Then you need to run the `generate-keys` command to create the security keys.

    ```bash theme={null}
    pnpm generate-keys
    ```

    <Frame>
      <img src="https://mintcdn.com/shipmobilefast-51a499dc/4ztR-scAO2Zjz6Y6/images/aiwrapper/backend/2.png?fit=max&auto=format&n=4ztR-scAO2Zjz6Y6&q=85&s=9a560aba94b2f32740f173089676c467" alt="Firebase" className="w-full" width="624" height="227" data-path="images/aiwrapper/backend/2.png" />
    </Frame>

    <Info>
      You need to add to the `.env.production` file too.
    </Info>
  </Step>

  <Step>
    As you can see, the `API_KEY` and `HMAC_SECRET_KEY` are created.

    Now type your app identifier: like: `com.shipmobilefast.app`.

    And copy the `API_KEY` and paste it on the Expo project's `.env` file.

    * `ALLOWED_ORIGINS` is the list of origins that are allowed to send requests to the backend.
      So make it your app's identifier.

    <Frame>
      <img src="https://mintcdn.com/shipmobilefast-51a499dc/4ztR-scAO2Zjz6Y6/images/aiwrapper/backend/3.png?fit=max&auto=format&n=4ztR-scAO2Zjz6Y6&q=85&s=db3de4784a496cb70b8546c882f48daf" alt="Firebase" className="w-full" width="792" height="620" data-path="images/aiwrapper/backend/3.png" />
    </Frame>
  </Step>

  <Step>
    Get your AI Provider Keys.

    * OpenAI: [https://platform.openai.com/api-keys](https://platform.openai.com/api-keys)
    * Anthropic: [https://console.anthropic.com/settings/keys](https://console.anthropic.com/settings/keys)
    * Replicate: [https://replicate.com/account/api-tokens](https://replicate.com/account/api-tokens)
    * Fal AI: [https://fal.ai/dashboard/keys](https://fal.ai/dashboard/keys)

    Add your AI API keys to the `.env.local` and `.env.production` files.

    <Tip>
      You don't have to use all of them in the backend. You can use only the ones you need.
    </Tip>
  </Step>

  <Step>
    Now we need to download the Firebase Service Account JSON file.

    <Warning>
      This file is very important. Do not share it with anyone.
    </Warning>

    Go to the Project Settings and click on the `Service Accounts` tab.

    <Frame>
      <img src="https://mintcdn.com/shipmobilefast-51a499dc/4ztR-scAO2Zjz6Y6/images/aiwrapper/backend/4.png?fit=max&auto=format&n=4ztR-scAO2Zjz6Y6&q=85&s=143b849064960f50cb48ba55c16944ee" alt="Firebase" className="w-full" width="429" height="191" data-path="images/aiwrapper/backend/4.png" />
    </Frame>
  </Step>

  <Step>
    <Frame>
      <img src="https://mintcdn.com/shipmobilefast-51a499dc/4ztR-scAO2Zjz6Y6/images/aiwrapper/backend/5.png?fit=max&auto=format&n=4ztR-scAO2Zjz6Y6&q=85&s=828a0a3786e03e5d613b6bffea33bf01" alt="Firebase" className="w-full" width="798" height="151" data-path="images/aiwrapper/backend/5.png" />
    </Frame>
  </Step>

  <Step>
    Click on the `Generate New Private Key` button.

    <Frame>
      <img src="https://mintcdn.com/shipmobilefast-51a499dc/4ztR-scAO2Zjz6Y6/images/aiwrapper/backend/6.png?fit=max&auto=format&n=4ztR-scAO2Zjz6Y6&q=85&s=91acb12ac7f8ce77a9bd1a6fe8d0dcad" alt="Firebase" className="w-full" width="1042" height="656" data-path="images/aiwrapper/backend/6.png" />
    </Frame>
  </Step>

  <Step>
    Click on the `Generate Key` button.

    <Frame>
      <img src="https://mintcdn.com/shipmobilefast-51a499dc/4ztR-scAO2Zjz6Y6/images/aiwrapper/backend/7.png?fit=max&auto=format&n=4ztR-scAO2Zjz6Y6&q=85&s=b6c7384330dab7d39687a80b9ef3b8f2" alt="Firebase" className="w-full" width="678" height="277" data-path="images/aiwrapper/backend/7.png" />
    </Frame>
  </Step>

  <Step>
    After downloading the JSON file, you need to add it to the backend and change the name as `firebase-service-account.json`.

    <Warning>
      Make sure you add the file to the `.gitignore` file and never commit it to the repository.

      Never add this on Expo project.

      * It should be only in the root of the backend folder.
    </Warning>

    <Frame>
      <img src="https://mintcdn.com/shipmobilefast-51a499dc/4ztR-scAO2Zjz6Y6/images/aiwrapper/backend/8.png?fit=max&auto=format&n=4ztR-scAO2Zjz6Y6&q=85&s=160260accdd13cb25f68354b0c1339be" alt="Firebase" className="w-full" width="328" height="394" data-path="images/aiwrapper/backend/8.png" />
    </Frame>
  </Step>

  <Step>
    Now you can start the backend.

    ```bash theme={null}
    pnpm run dev
    ```

    <Frame>
      <img src="https://mintcdn.com/shipmobilefast-51a499dc/4ztR-scAO2Zjz6Y6/images/aiwrapper/backend/9.png?fit=max&auto=format&n=4ztR-scAO2Zjz6Y6&q=85&s=d97d22c22c023a8633517515b21ae77a" alt="Firebase" className="w-full" width="545" height="145" data-path="images/aiwrapper/backend/9.png" />
    </Frame>
  </Step>

  <Step>
    Don't forget to add API\_KEY to the Expo project's `.env` file.
  </Step>

  <Step>
    ### So how can I test the App? We haven't build the app yet. Let's go to the test on Simulators.

    <Card title="Build" icon="circle-play" href="/aiwrapper/build">
      Create a development build
    </Card>
  </Step>
</Steps>
