# Cloudflare Calls TURN setup for Spaceship

This package already includes the Spaceship backend endpoint for Cloudflare Realtime TURN:

```text
api/cloudflare_turn.php
```

It also updates `js/app.js` so the browser fetches short-lived `iceServers` from your PHP backend. Your Cloudflare TURN key/token stays inside `api/config.php` and is never exposed directly in JavaScript.

## What you need from Cloudflare

You need either:

1. An existing Cloudflare TURN Key ID / UID and TURN API token / key, or
2. A Cloudflare Account ID plus a Cloudflare API token with `Calls Write` permission so the script can create the TURN key for you.

## Option A — you already created a TURN key in Cloudflare Dashboard

From the Spaceship project folder, run PowerShell:

```powershell
cd C:\xampp\htdocs\Spaceship
powershell -ExecutionPolicy Bypass -File .\tools\configure_cloudflare_turn.ps1
```

Paste the TURN Key ID / UID and TURN API token / key when asked.

The script updates:

```text
api/config.php
js/app.js
```

## Option B — create the TURN key automatically through Cloudflare API

First create a Cloudflare API token with `Calls Write` permission and copy your Cloudflare Account ID.

Then run:

```powershell
cd C:\xampp\htdocs\Spaceship
powershell -ExecutionPolicy Bypass -File .\tools\create_cloudflare_turn_key.ps1
```

Paste:

```text
Cloudflare Account ID
Cloudflare API token with Calls Write permission
```

The script will create a TURN key through Cloudflare API, then automatically patch Spaceship.

## Manual config check

Open:

```text
api/config.php
```

Confirm these lines contain real values:

```php
define('CLOUDFLARE_TURN_KEY_ID', 'YOUR_TURN_KEY_UID');
define('CLOUDFLARE_TURN_API_TOKEN', 'YOUR_TURN_KEY_SECRET');
define('CLOUDFLARE_TURN_TTL', 86400);
```

Open:

```text
js/app.js
```

Confirm:

```js
var METERED_TURN_API_URL = 'api/cloudflare_turn.php';
```

The variable name is still `METERED_TURN_API_URL` because it already existed in the project. It now points to the Cloudflare TURN endpoint.

## Required browser/server conditions

Calls still require HTTPS or localhost:

```text
https://yourdomain.com/Spaceship/
http://localhost/Spaceship/
```

Do not test camera/microphone through plain LAN HTTP such as:

```text
http://192.168.1.x/Spaceship/
```

## Test

1. Restart Apache in XAMPP.
2. Open Spaceship and press Ctrl+F5.
3. Login as User A on PC Wi-Fi.
4. Login as User B on a phone using mobile data.
5. Start a video call.
6. Allow camera and microphone.

To test the endpoint after login, open Browser DevTools Console and run:

```js
fetch('api/cloudflare_turn.php', {
  headers: { Authorization: 'Bearer ' + token }
}).then(r => r.json()).then(console.log)
```

Expected result: an array containing Cloudflare STUN/TURN URLs, username, and credential.

If it returns an error about PHP cURL, enable `extension=curl` in `php.ini` and restart Apache.
