# Identity verification: prove which user your app calls PushFire for

Your server signs each user's external ID with a per-project identity secret. The app sends that hash to PushFire, so nobody with your public key can log in as another user or change their tags and opt-outs.

**Identity verification** proves to PushFire which user your app calls for. Your server computes an **identity hash** for each signed-in user with a secret that only your server knows. The app sends the hash with each subscriber call. PushFire then refuses a call for a user without the matching hash.

TODO for Erik before publishing: publish this guide only after the Swift SDK, Flutter SDK and Firebase extension releases that add identity verification. Check each method name in this guide against those releases: Swift **login(externalId:identityHash:)** and **setIdentityHash(_:)**, Flutter **loginSubscriber(identityHash:)** and **setIdentityHash**, and the Firebase extension release with **getIdentityHash**. Delete this paragraph when they match.

## Why you need identity verification

Your app ships a **Public key** (**pf_pk_…**). Anyone can extract it from the app bundle. Without identity verification, a person with that key can:

- call **login-subscriber** with any **externalId** and their own device. PushFire then links their device to that user, so they receive that user's push notifications.
- add, change or remove that user's tags, including the opt-out tags **OptOutPush** and **OptOutEmail**.
- change that user's profile or log that user out.

External IDs are often emails or sequential numbers, so they are easy to guess. Identity verification closes this gap. The public key alone is no longer enough to act as a user.

## How identity verification works

```text
 Your app                    Your server                      PushFire API
    |                             |                                 |
    | 1. user signs in            |                                 |
    |---------------------------->|                                 |
    |                             | 2. hash = HMAC-SHA256(          |
    |                             |      identity secret,           |
    |                             |      externalId)                |
    | 3. { externalId, hash }     |                                 |
    |<----------------------------|                                 |
    |                                                               |
    | 4. login-subscriber, tag and profile calls                    |
    |    Authorization: Bearer pf_pk_...                            |
    |    X-PushFire-Identity-Hash: <hash>                           |
    |-------------------------------------------------------------->|
    |                                      5. PushFire computes the |
    |                                         same hash and compares|
```

- The **identity secret** (**pfid_…**) belongs to your project. It stays on your server.
- The **identity hash** is **HMAC-SHA256(key = identity secret, message = externalId)**, written as 64 lowercase hex characters.
- The app sends the hash in the HTTP header **X-PushFire-Identity-Hash**. The SDKs do this for you.

The hash is needed on these six endpoints when the call names an **identified** subscriber (one with an **externalId**): **login-subscriber**, **logout-subscriber**, **update-subscriber**, **add-subscriber-tag**, **update-subscriber-tag** and **remove-subscriber-tag**. Anonymous subscribers (a device with no login) need no hash. **register-device** and **update-device** need no hash.

## Step 1: generate the identity secret

1. Open [console.pushfire.app](https://console.pushfire.app) and select your project.
2. Go to **Settings → Identity Verification**.
3. Click **Generate secret**.
4. Copy the secret. It starts with **pfid_**. The console shows it **once**. If you lose it, rotate it, as the section "Rotate the identity secret" below shows.
5. Store it as a server secret, for example **PUSHFIRE_IDENTITY_SECRET** in your server environment, in Supabase Edge Function secrets or in Google Cloud Secret Manager.

**Warning:** never put the identity secret in your app, a **NEXT_PUBLIC_** / **VITE_** / **EXPO_PUBLIC_** variable or a no-code frontend. With the secret, anyone can compute the hash for every user.

Do not turn on **Require identity verification** yet. Do that in step 5, after your app sends hashes.

## Step 2: compute the hash on your server

Compute the hash for the user that your server has authenticated. Never compute a hash for an **externalId** that the app sends in the request body. That would let any user get a hash for any other user.

Hash the **externalId** exactly as your app sends it to PushFire: the same characters, no trimming and no change of case. A numeric ID is hashed as its decimal string, so **123** and **"123"** give the same hash.

### Node.js and TypeScript

<!-- pushfire-identity.ts -->
```typescript
import crypto from 'node:crypto'

const secret = process.env.PUSHFIRE_IDENTITY_SECRET! // pfid_...

export function pushfireIdentityHash(externalId: string | number): string {
  return crypto.createHmac('sha256', secret).update(String(externalId)).digest('hex')
}

// Express: return the hash for the signed-in user only.
app.get('/me/pushfire-identity', requireAuth, (req, res) => {
  const externalId = req.user.id
  res.json({externalId, identityHash: pushfireIdentityHash(externalId)})
})
```

### Python

<!-- pushfire_identity.py -->
```python
import hashlib
import hmac
import os

SECRET = os.environ["PUSHFIRE_IDENTITY_SECRET"]  # pfid_...


def pushfire_identity_hash(external_id) -> str:
    return hmac.new(
        SECRET.encode("utf-8"), str(external_id).encode("utf-8"), hashlib.sha256
    ).hexdigest()


# FastAPI: return the hash for the signed-in user only.
@app.get("/me/pushfire-identity")
def pushfire_identity(user=Depends(current_user)):
    return {"externalId": user.id, "identityHash": pushfire_identity_hash(user.id)}
```

### Supabase Edge Function (Deno)

This function reads the user from the Supabase access token, so it returns a hash for the signed-in user only. Set the secret with **supabase secrets set PUSHFIRE_IDENTITY_SECRET=pfid_...**.

<!-- supabase/functions/pushfire-identity/index.ts -->
```typescript
import {createClient} from 'npm:@supabase/supabase-js@2'

const SECRET = Deno.env.get('PUSHFIRE_IDENTITY_SECRET')! // pfid_...

async function pushfireIdentityHash(externalId: string): Promise<string> {
  const encoder = new TextEncoder()
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(SECRET),
    {name: 'HMAC', hash: 'SHA-256'},
    false,
    ['sign'],
  )
  const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(externalId))
  return Array.from(new Uint8Array(signature), (b) => b.toString(16).padStart(2, '0')).join('')
}

Deno.serve(async (req) => {
  const token = req.headers.get('Authorization')?.replace('Bearer ', '') ?? ''
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL')!,
    Deno.env.get('SUPABASE_ANON_KEY')!,
  )
  const {data, error} = await supabase.auth.getUser(token)
  if (error || !data.user) return new Response('Unauthorized', {status: 401})

  const externalId = data.user.id
  return Response.json({externalId, identityHash: await pushfireIdentityHash(externalId)})
})
```

The app calls it with **supabase.functions.invoke('pushfire-identity')**, which sends the user's access token. A browser app also needs CORS headers on this function.

### Firebase: the PushFire Firebase extension

The callable function **getIdentityHash** is available in the next extension release. It works like this:

- It needs a signed-in Firebase Auth user and ignores any data the app sends.
- It reads the document **<your users collection>/<auth uid>**, takes the **externalId** with the extension's field mapping, and returns **{ externalId, identityHash }**.
- Your user documents must use the Firebase Auth UID as the document ID. Documents with automatic IDs are not supported yet.
- Set the new extension parameter **Identity secret** (**PUSHFIRE_IDENTITY_SECRET**) to your **pfid_** secret when you install or reconfigure the extension. Firebase stores it in Secret Manager.
- Without the secret, or when the document has no **externalId** value, the function returns the error **failed-precondition**.

The app calls it after Firebase sign-in and logs in to PushFire with exactly the values it returns:

```dart
final result = await FirebaseFunctions.instance
    .httpsCallable('ext-pushfire-subscribers-sync-getIdentityHash')
    .call();

// Log in with exactly the externalId and identityHash that the function returns.
await PushFireSDK.instance.loginSubscriber(
  externalId: result.data['externalId'] as String,
  identityHash: result.data['identityHash'] as String,
);
```

Until that release, use a Cloud Function of your own with the Node.js code above.

## Step 3: return the hash to the app after sign-in

After your sign-in finishes, the app asks your server for the hash. Your server answers with **externalId** and **identityHash**. Use the **externalId** from that response for the PushFire login, so the two always match.

The hash does not expire. The app can keep it with the user's session and ask again after each sign-in.

## Step 4: pass the hash to the SDK login

### Swift / iOS

```swift
let identity = try await myBackend.pushfireIdentity() // { externalId, identityHash }

try await PushFire.shared.login(
    externalId: identity.externalId,
    identityHash: identity.identityHash,
    name: "Ada Lovelace",
    email: "ada@example.com"
)
```

The SDK stores the hash and sends it on every later call for this user: tags, profile updates and logout.

### Flutter

```dart
final identity = await myBackend.pushfireIdentity(); // { externalId, identityHash }

await PushFireSDK.instance.loginSubscriber(
  externalId: identity.externalId,
  identityHash: identity.identityHash,
  name: user.displayName,
  email: user.email,
);
```

**Automatic login** (**AuthProvider.firebase**, **AuthProvider.supabase**, **FirebaseAuthProvider** or **SupabaseAuthProvider**) cannot ask your server for a hash. When you turn on verification, log in by hand as shown above, and check your SDK's README for the identity verification options of your version.

### FlutterFlow and Dreamflow

- **Dreamflow** uses the Flutter SDK. Ask the agent to call your hash endpoint after sign-in and pass **identityHash** to **loginSubscriber**, as in the Flutter example.
- **FlutterFlow**: add an API call to your hash endpoint after your sign-in action, then pass its **identityHash** to the login action. Keep verification off until your PushFire-Lib version has an identity hash parameter. Existing projects have until 2027-12-03.

### React Native, Android, web and the REST API

Send the header yourself on the six endpoints above. Keep the hash after login and clear it after logout:

```shell
curl -X POST https://api.pushfire.app/functions/v1/login-subscriber \
  -H "Authorization: Bearer $PUSHFIRE_PUBLIC_KEY" \
  -H "X-PushFire-Identity-Hash: $IDENTITY_HASH" \
  -H "Content-Type: application/json" \
  -d '{"data":{"deviceId":"DEVICE_UUID","externalId":"user_42"}}'
```

The [React Native](https://www.pushfire.app/docs/guides/react-native-push-notifications), [Android](https://www.pushfire.app/docs/guides/android-push-notifications) and [web](https://www.pushfire.app/docs/guides/web-push-notifications) guides show a client helper that sends the header.

## Step 5: turn on Require identity verification

1. Ship the app version that sends the hash.
2. Test it. PushFire already checks every hash that the app sends, even with verification off. A wrong hash returns **401 identity_verification_failed**, so you find mistakes before you turn verification on.
3. Wait until most of your users run that version. Older app versions send no hash, so their logins and tag calls fail after you turn verification on.
4. In **Settings → Identity Verification**, turn on **Require identity verification**.

You can turn it off again at any time.

## Rotate the identity secret

Rotate the secret when you think someone has seen it.

1. In **Settings → Identity Verification**, click **Rotate secret** and copy the new secret.
2. Put the new secret on your server.
3. PushFire accepts hashes from the **previous secret for 7 days** after a rotation. In that time, installed apps get new hashes from your server.
4. Give the app the new hash without a new login. Call **setIdentityHash** with the hash from your server, for example at app start:

```swift
try await PushFire.shared.setIdentityHash(identity.identityHash)
```

```dart
await PushFireSDK.instance.setIdentityHash(identity.identityHash);
```

After 7 days, hashes from the old secret return **401 identity_verification_failed**.

## Errors

The API returns these errors with the body **{ "error": "...", "errors": [{ "code": "...", "message": "..." }] }**. The SDKs report them as typed errors and do not retry.

- **401 identity_verification_required**: verification is on and the call sent no hash, or the project has no identity secret yet. Fetch the hash from your server and pass it to login.
- **401 identity_verification_failed**: the hash matches neither the current secret nor the previous one. Check that the server hashes the same **externalId** that the app sends, with the current secret.
- **403 external_id_change_not_allowed**: a call with the public key tried to change a subscriber's existing **externalId** while verification is on. Change it from your server with the Secret key.

**update-subscriber** checks the hash against the subscriber's stored **externalId**. To give an anonymous subscriber its first **externalId**, send the hash of the new value.

## When identity verification is on

- **New projects** get verification on by default. This default starts soon after the SDK releases that send the hash. Check the switch in **Settings → Identity Verification** to see the state of your project.
- **Existing projects** keep unverified access **until 2027-12-03**. On that date PushFire turns verification on for every project. Before then, PushFire emails each project owner whose app still sends identified calls without a hash.

## Test vectors for your implementation

Run your hash function against these values. Each line shows the secret, the **externalId** and the expected hash.

- **pfid_test_secret_0123456789abcdef**, **user_42**: **5bce94e3b7c422f9ad260cd2abc44b2b2fa73f296683ad1a3b54a437769a45c7**
- **pfid_test_secret_0123456789abcdef**, **123** (string or number): **28a2670e8e93ffde3fa53ea536c2e97b779632a14b8ee0a81f3270b7d4a71580**
- **pfid_test_secret_0123456789abcdef**, **alice@example.com**: **078615dfb449cf376da967822133763196245f088b73d53ed39cc7ed313314ad**
- **pfid_test_secret_0123456789abcdef**, **Zoë-東京**: **8a6259549dbd82b43e9aa924e5506c297bc658cf15a46e698d74979413c2a3a0**
- **another-secret**, **user_42**: **5d932a9fc933022922cd5488f445b03cc05d6444a241bf0d8a86b3fac6952dbe**

The key is the UTF-8 bytes of the whole secret string, including **pfid_**. The message is the UTF-8 bytes of the **externalId**.

## FAQ

### Do anonymous subscribers need an identity hash?

No. A subscriber without an **externalId** is a device with no login. Its calls need no hash. The hash is needed from the moment the app logs a user in.

### Do calls with the Secret key need an identity hash?

No. Calls with a Secret key (**pf_sk_…**), a Restricted key that holds a Secret scope, or a legacy key never need the hash. These keys belong on your server, which already knows who the user is.

### Can I put the identity secret or the Secret key in my app?

No. Never ship the identity secret (**pfid_…**) or a Secret key (**pf_sk_…**) in a mobile app, browser bundle or no-code frontend. The app gets only the Public key (**pf_pk_…**) and the hash for its own signed-in user.

### Can the app compute the hash itself?

No. To compute the hash, the app would need the identity secret, and then anyone could extract it. Always compute the hash on your server, a Supabase Edge Function or a Firebase Cloud Function.

### How do I hash a numeric external ID?

Hash its decimal string. **123** and **"123"** give the same hash. Do not add leading zeros, spaces or a decimal point.

### Does the hash expire?

No. A hash stays valid until you rotate the secret, and for 7 days after that.

## Next steps

- Keys: [Public and Secret keys](https://www.pushfire.app/docs/guides/developers-api-keys-public-and-secret).
- SDK setup: [Swift / iOS](https://www.pushfire.app/docs/guides/swift-push-notifications) and [Flutter](https://www.pushfire.app/docs/guides/flutter-push-notifications).
- Server calls: [Push notification REST API quickstart](https://www.pushfire.app/docs/guides/push-notification-rest-api-quickstart).
