Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(rexctl): run voice servers on IPv6 with operator TURN (#3727)

Hampus831570ccce66
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.json
index ebea3791e..ffb0287dc 100644
--- a/fluxer_admin/openapi-admin.json
+++ b/fluxer_admin/openapi-admin.json
@@ -13256,7 +13256,9 @@
"draining": {
"description": "Whether placement sends new calls elsewhere while calls on this server finish",
"type": "boolean"
- }
+ },
+ "public_ipv4": {"nullable": true, "allOf": [{"$ref": "#/components/schemas/VoicePublicIpv4Type"}]},
+ "public_ipv6": {"nullable": true, "allOf": [{"$ref": "#/components/schemas/VoicePublicIpv6Type"}]}
}
},
"UpdateVoiceServerResponse": {
@@ -13322,6 +13324,16 @@
"type": "boolean",
"description": "Whether placement sends new calls elsewhere while calls on this server finish"
},
+ "public_ipv4": {
+ "nullable": true,
+ "description": "Public IPv4 address LiveKit gives to clients, or null when none is known",
+ "type": "string"
+ },
+ "public_ipv6": {
+ "nullable": true,
+ "description": "Public IPv6 address LiveKit gives to clients, or null when none is known",
+ "type": "string"
+ },
"health": {
"description": "Health of the server as this API node last saw it",
"allOf": [{"$ref": "#/components/schemas/VoiceServerHealthResponse"}]
@@ -13426,6 +13438,16 @@
"default": false,
"description": "Whether placement sends new calls elsewhere while calls on this server finish",
"type": "boolean"
+ },
+ "public_ipv4": {
+ "default": null,
+ "nullable": true,
+ "allOf": [{"$ref": "#/components/schemas/VoicePublicIpv4Type"}]
+ },
+ "public_ipv6": {
+ "default": null,
+ "nullable": true,
+ "allOf": [{"$ref": "#/components/schemas/VoicePublicIpv6Type"}]
}
},
"required": ["server_id", "endpoint", "api_key", "api_secret"]
@@ -13493,6 +13515,16 @@
"type": "boolean",
"description": "Whether placement sends new calls elsewhere while calls on this server finish"
},
+ "public_ipv4": {
+ "nullable": true,
+ "description": "Public IPv4 address LiveKit gives to clients, or null when none is known",
+ "type": "string"
+ },
+ "public_ipv6": {
+ "nullable": true,
+ "description": "Public IPv6 address LiveKit gives to clients, or null when none is known",
+ "type": "string"
+ },
"health": {
"description": "Health of the server as this API node last saw it",
"allOf": [{"$ref": "#/components/schemas/VoiceServerHealthResponse"}]
@@ -25675,6 +25707,16 @@
"type": "boolean",
"description": "Whether placement sends new calls elsewhere while calls on this server finish"
},
+ "public_ipv4": {
+ "nullable": true,
+ "description": "Public IPv4 address LiveKit gives to clients, or null when none is known",
+ "type": "string"
+ },
+ "public_ipv6": {
+ "nullable": true,
+ "description": "Public IPv6 address LiveKit gives to clients, or null when none is known",
+ "type": "string"
+ },
"health": {
"description": "Health of the server as this API node last saw it",
"allOf": [{"$ref": "#/components/schemas/VoiceServerHealthResponse"}]
@@ -25706,6 +25748,8 @@
"allowed_user_ids",
"internal_endpoint",
"draining",
+ "public_ipv4",
+ "public_ipv6",
"health",
"duplicate_api_key",
"created_at",
@@ -25790,6 +25834,18 @@
],
"additionalProperties": false
},
+ "VoicePublicIpv6Type": {
+ "type": "string",
+ "format": "ipv6",
+ "pattern": "^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$",
+ "description": "Public IPv6 address LiveKit gives to clients"
+ },
+ "VoicePublicIpv4Type": {
+ "type": "string",
+ "format": "ipv4",
+ "pattern": "^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$",
+ "description": "Public IPv4 address LiveKit gives to clients"
+ },
"APIErrorCode": {
"type": "string",
"enum": [
diff --git a/fluxer_admin/src/api/types/voice.rs b/fluxer_admin/src/api/types/voice.rs
index c6344cc89..e1d346ab3 100644
--- a/fluxer_admin/src/api/types/voice.rs
+++ b/fluxer_admin/src/api/types/voice.rs
@@ -40,6 +40,10 @@ pub struct VoiceServer {
pub internal_endpoint: Option<String>,
#[serde(default)]
pub draining: bool,
+ #[serde(default)]
+ pub public_ipv4: Option<String>,
+ #[serde(default)]
+ pub public_ipv6: Option<String>,
pub health: Option<VoiceServerHealth>,
#[serde(default)]
pub duplicate_api_key: bool,
diff --git a/fluxer_admin/src/routes/voice_actions.rs b/fluxer_admin/src/routes/voice_actions.rs
index 5eccb3ed7..262174492 100644
--- a/fluxer_admin/src/routes/voice_actions.rs
+++ b/fluxer_admin/src/routes/voice_actions.rs
@@ -104,16 +104,18 @@ pub(crate) fn build_server_body(form: &MultiValueForm) -> serde_json::Value {
},
);
}
- if let Some(raw) = form.first("internal_endpoint") {
- let trimmed = raw.trim();
- body.insert(
- "internal_endpoint".into(),
- if trimmed.is_empty() {
- serde_json::Value::Null
- } else {
- trimmed.into()
- },
- );
+ for field in ["internal_endpoint", "public_ipv4", "public_ipv6"] {
+ if let Some(raw) = form.first(field) {
+ let trimmed = raw.trim();
+ body.insert(
+ field.into(),
+ if trimmed.is_empty() {
+ serde_json::Value::Null
+ } else {
+ trimmed.into()
+ },
+ );
+ }
}
if form.contains_key("draining_field") {
body.insert("draining".into(), form.bool_value("draining").into());
diff --git a/fluxer_admin/src/templates/pages/voice_servers.rs b/fluxer_admin/src/templates/pages/voice_servers.rs
index 594d97de2..bb38d2ce1 100644
--- a/fluxer_admin/src/templates/pages/voice_servers.rs
+++ b/fluxer_admin/src/templates/pages/voice_servers.rs
@@ -210,6 +210,10 @@ fn server_card(
.internal_endpoint
.clone()
.unwrap_or_else(|| "Same as the endpoint".to_string());
+ let addresses_str = addresses_text(
+ server.public_ipv4.as_deref().filter(|v| !v.is_empty()),
+ server.public_ipv6.as_deref().filter(|v| !v.is_empty()),
+ );
let at_soft_limit = matches!(
(server.soft_connection_limit, connection_count),
(Some(limit), Some(count)) if limit > 0 && count >= limit
@@ -252,6 +256,7 @@ fn server_card(
(data_field_text("Health", &health_str))
(data_field_text("Draining", if server.draining { "Yes" } else { "No" }))
(data_field_text("Internal URL", &internal_str))
+ (data_field_text("Addresses", &addresses_str))
}
@if server.duplicate_api_key {
p class="mb-4 text-sm text-red-700" {
@@ -463,3 +468,12 @@ pub fn join_token_created_page(
LayoutOptions::default(),
)
}
+
+fn addresses_text(ipv4: Option<&str>, ipv6: Option<&str>) -> String {
+ match (ipv4, ipv6) {
+ (Some(v4), Some(v6)) => format!("IPv4 {v4}, IPv6 {v6}"),
+ (Some(v4), None) => format!("IPv4 {v4}"),
+ (None, Some(v6)) => format!("IPv6 only, {v6}"),
+ (None, None) => "Not reported".to_string(),
+ }
+}
diff --git a/fluxer_admin/src/templates/pages/voice_servers_forms.rs b/fluxer_admin/src/templates/pages/voice_servers_forms.rs
index bf3ee33e3..3b89564ef 100644
--- a/fluxer_admin/src/templates/pages/voice_servers_forms.rs
+++ b/fluxer_admin/src/templates/pages/voice_servers_forms.rs
@@ -33,6 +33,8 @@ pub fn edit_server_form(
.map_or_else(String::new, |v| v.to_string());
let notes = server.notes.as_deref().unwrap_or("");
let internal_endpoint = server.internal_endpoint.as_deref().unwrap_or("");
+ let public_ipv4 = server.public_ipv4.as_deref().unwrap_or("");
+ let public_ipv6 = server.public_ipv6.as_deref().unwrap_or("");
let vip_only = server.vip_only.unwrap_or(false);
let features_csv = server.required_guild_features.join(", ");
let guild_ids_csv = server.allowed_guild_ids.join(", ");
@@ -82,6 +84,26 @@ pub fn edit_server_form(
"http://voice-fra-server-1:7880",
INTERNAL_URL_HELPER,
))
+ div class="grid grid-cols-1 gap-4 md:grid-cols-2" {
+ (form_field_with_helper(
+ "Public IPv4",
+ &format!("{id_prefix}-public-ipv4"),
+ "public_ipv4",
+ "text",
+ public_ipv4,
+ "203.0.113.7",
+ PUBLIC_IP_HELPER,
+ ))
+ (form_field_with_helper(
+ "Public IPv6",
+ &format!("{id_prefix}-public-ipv6"),
+ "public_ipv6",
+ "text",
+ public_ipv6,
+ "2001:db8::7",
+ PUBLIC_IP_HELPER,
+ ))
+ }
(notes_field(&format!("{id_prefix}-notes"), notes))
(form_field_with_helper(
"API Key",
@@ -166,6 +188,24 @@ pub fn create_server_form(config: &AdminConfig, region_id: &str, csrf_token: &st
"http://voice-fra-server-1:7880",
INTERNAL_URL_HELPER,
))
+ (form_field_with_helper(
+ "Public IPv4 (optional)",
+ "new-server-public-ipv4",
+ "public_ipv4",
+ "text",
+ "",
+ "203.0.113.7",
+ PUBLIC_IP_HELPER,
+ ))
+ (form_field_with_helper(
+ "Public IPv6 (optional)",
+ "new-server-public-ipv6",
+ "public_ipv6",
+ "text",
+ "",
+ "2001:db8::7",
+ PUBLIC_IP_HELPER,
+ ))
}
(notes_field("new-server-notes", ""))
div class="space-y-3" {
@@ -189,6 +229,8 @@ pub fn create_server_form(config: &AdminConfig, region_id: &str, csrf_token: &st
})
}
+const PUBLIC_IP_HELPER: &str = "The address the LiveKit server gives to clients. Fluxer shows it here, and rexctl voice test uses it to choose which address families to test. Leave it empty if you don't know it.";
+
const INTERNAL_URL_HELPER: &str = "Fluxer uses this address for the LiveKit control API and health checks. Leave it empty to use the endpoint.";
fn form_field_with_helper(
diff --git a/fluxer_api/src/api/Config.ts b/fluxer_api/src/api/Config.ts
index dfaef0c85..7a81da28f 100644
--- a/fluxer_api/src/api/Config.ts
+++ b/fluxer_api/src/api/Config.ts
@@ -456,6 +456,7 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {
bundled: master.integrations.voice.bundled ?? true,
defaultRegion: master.integrations.voice.default_region,
p2pStunUrls: master.integrations.voice.p2p_stun_urls,
+ turnServers: master.integrations.voice.turn_servers ?? [],
joinAllowPrivateEndpoints: master.integrations.voice.join_allow_private_endpoints ?? false,
healthIntervalMs: master.integrations.voice.health_interval_ms ?? 15000,
},
diff --git a/fluxer_api/src/api/admin/services/AdminVoiceService.ts b/fluxer_api/src/api/admin/services/AdminVoiceService.ts
index e73d4494e..d21ed5763 100644
--- a/fluxer_api/src/api/admin/services/AdminVoiceService.ts
+++ b/fluxer_api/src/api/admin/services/AdminVoiceService.ts
@@ -280,6 +280,8 @@ export class AdminVoiceService {
draining: data.draining ?? false,
pinnedHostname: null,
pinnedSoftLimit: false,
+ publicIpv4: data.public_ipv4 ?? null,
+ publicIpv6: data.public_ipv6 ?? null,
restrictions: buildVoiceRestrictions(data),
});
await this.publishVoiceConfiguration({type: 'server_created', regionId: data.region_id, serverId: data.server_id});
@@ -323,6 +325,8 @@ export class AdminVoiceService {
if (data.notes !== undefined) updates.notes = data.notes;
if (data.internal_endpoint !== undefined) updates.internalEndpoint = data.internal_endpoint;
if (data.draining !== undefined) updates.draining = data.draining;
+ if (data.public_ipv4 !== undefined) updates.publicIpv4 = data.public_ipv4;
+ if (data.public_ipv6 !== undefined) updates.publicIpv6 = data.public_ipv6;
updates.restrictions = patchVoiceRestrictions(existing.restrictions, data);
updates.updatedAt = new Date();
await voiceRepository.upsertServer(updates);
@@ -411,6 +415,8 @@ export class AdminVoiceService {
allowed_user_ids: Array.from(server.restrictions.allowedUserIds).map((id) => id.toString()),
internal_endpoint: server.internalEndpoint,
draining: server.draining,
+ public_ipv4: server.publicIpv4,
+ public_ipv6: server.publicIpv6,
health: toHealthResponse(healthOf(getVoiceServerHealth(), server)),
duplicate_api_key: duplicates.has(server.apiKey),
created_at: server.createdAt?.toISOString() ?? null,
diff --git a/fluxer_api/src/api/config/APIConfig.ts b/fluxer_api/src/api/config/APIConfig.ts
index 5414ed63f..e2e8f943a 100644
--- a/fluxer_api/src/api/config/APIConfig.ts
+++ b/fluxer_api/src/api/config/APIConfig.ts
@@ -6,7 +6,7 @@ import type {
OperatorPassWithdrawalCountryTable,
} from '@app/api/operator_pass/OperatorPassPrices';
import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';
-import type {CachePurgeAdapterName, StoreProductSlotName} from '@fluxer/config/src/MasterConfig';
+import type {CachePurgeAdapterName, StoreProductSlotName, VoiceTurnServerConfig} from '@fluxer/config/src/MasterConfig';
import type {AccountIdentityMode, TagStyle} from '@fluxer/constants/src/AccountIdentityConstants';
import type {SmtpTlsMode} from '@fluxer/constants/src/SmtpConstants';
import type {OperatorPassCurrency} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';
@@ -220,6 +220,7 @@ export interface APIConfig {
longitude: number;
};
p2pStunUrls?: Array<string>;
+ turnServers: Array<VoiceTurnServerConfig>;
joinAllowPrivateEndpoints: boolean;
healthIntervalMs: number;
};
diff --git a/fluxer_api/src/api/database/types/VoiceTypes.ts b/fluxer_api/src/api/database/types/VoiceTypes.ts
index 3e76d77b8..95edb0ace 100644
--- a/fluxer_api/src/api/database/types/VoiceTypes.ts
+++ b/fluxer_api/src/api/database/types/VoiceTypes.ts
@@ -51,6 +51,8 @@ export interface VoiceServerRow {
draining: boolean | null;
pinned_hostname: string | null;
pinned_soft_limit: boolean | null;
+ public_ipv4: string | null;
+ public_ipv6: string | null;
created_at: Date | null;
updated_at: Date | null;
}
@@ -74,6 +76,8 @@ export const VOICE_SERVER_COLUMNS = [
'draining',
'pinned_hostname',
'pinned_soft_limit',
+ 'public_ipv4',
+ 'public_ipv6',
'created_at',
'updated_at',
] as const satisfies ReadonlyArray<keyof VoiceServerRow>;
diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.json
index 083a0ecaa..d4f5535b0 100644
--- a/fluxer_api/src/api/openapi/openapi.json
+++ b/fluxer_api/src/api/openapi/openapi.json
@@ -27259,6 +27259,14 @@
"longitude": {"anyOf": [{"type": "number", "minimum": -180, "maximum": 180}, {"type": "null"}]},
"soft_connection_limit": {
"anyOf": [{"type": "integer", "minimum": 1, "maximum": 2147483647}, {"type": "null"}]
+ },
+ "public_ipv4": {
+ "description": "Public IPv4 address, or an empty string for none",
+ "anyOf": [{"$ref": "#/components/schemas/VoicePublicIpv4Type"}, {"type": "string", "const": ""}]
+ },
+ "public_ipv6": {
+ "description": "Public IPv6 address, or an empty string for none",
+ "anyOf": [{"$ref": "#/components/schemas/VoicePublicIpv6Type"}, {"type": "string", "const": ""}]
}
},
"additionalProperties": false
@@ -27274,6 +27282,19 @@
"is_active": {"type": "boolean", "description": "Whether an admin keeps the server turned on"},
"draining": {"type": "boolean", "description": "Whether placement sends new calls elsewhere"},
"soft_connection_limit": {"description": "Soft connection limit, or null", "type": ["number", "null"]},
+ "public_ipv4": {
+ "description": "Public IPv4 address the server last reported, or null",
+ "type": ["string", "null"]
+ },
+ "public_ipv6": {
+ "description": "Public IPv6 address the server last reported, or null",
+ "type": ["string", "null"]
+ },
+ "turn_servers": {
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/VoiceTurnServer"},
+ "description": "TURN servers of the instance, for the LiveKit configuration of the voice server"
+ },
"health": {
"description": "Health of the server as this API node last saw it",
"$ref": "#/components/schemas/VoiceServerHealthResponse"
@@ -27288,6 +27309,9 @@
"is_active",
"draining",
"soft_connection_limit",
+ "public_ipv4",
+ "public_ipv6",
+ "turn_servers",
"health"
],
"additionalProperties": false
@@ -27306,6 +27330,17 @@
{"type": "null"}
]
},
+ "public_ipv6": {
+ "description": "Public IPv6 address of the voice machine",
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "ipv6",
+ "pattern": "^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$"
+ },
+ {"type": "null"}
+ ]
+ },
"region_id": {
"description": "Existing region the operator asked for",
"type": "string",
@@ -27380,7 +27415,12 @@
"type": "string",
"description": "Fluxer release of the API, or an empty string for a development build"
},
- "expires_at": {"type": "string", "description": "ISO 8601 timestamp when the token stops working"}
+ "expires_at": {"type": "string", "description": "ISO 8601 timestamp when the token stops working"},
+ "turn_servers": {
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/VoiceTurnServer"},
+ "description": "TURN servers of the instance, for the LiveKit configuration of the voice server"
+ }
},
"required": [
"server_id",
@@ -27394,7 +27434,8 @@
"webhook_url",
"api_code_version",
"release",
- "expires_at"
+ "expires_at",
+ "turn_servers"
],
"additionalProperties": false
},
@@ -27431,6 +27472,12 @@
"type": "string",
"format": "ipv4",
"pattern": "^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$"
+ },
+ "public_ipv6": {
+ "description": "Public IPv6 address of the voice machine",
+ "type": "string",
+ "format": "ipv6",
+ "pattern": "^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$"
}
},
"required": ["endpoint", "api_key", "api_secret"]
@@ -27442,9 +27489,14 @@
"region_id": {"type": "string", "description": "Region of the new server"},
"endpoint": {"type": "string", "description": "Endpoint of the new server"},
"webhook_url": {"type": "string", "description": "URL the server sends LiveKit webhooks to"},
- "node_url": {"type": "string", "description": "URL of the node routes for this server"}
+ "node_url": {"type": "string", "description": "URL of the node routes for this server"},
+ "turn_servers": {
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/VoiceTurnServer"},
+ "description": "TURN servers of the instance, for the LiveKit configuration of the voice server"
+ }
},
- "required": ["server_id", "region_id", "endpoint", "webhook_url", "node_url"],
+ "required": ["server_id", "region_id", "endpoint", "webhook_url", "node_url", "turn_servers"],
"additionalProperties": false
},
"EntranceSoundPlayRequest": {
@@ -45240,6 +45292,34 @@
"enum": ["online", "dnd", "idle", "invisible"],
"type": "string"
},
+ "VoiceTurnServer": {
+ "type": "object",
+ "properties": {
+ "host": {"type": "string", "description": "Hostname or IPv4 address of the TURN server"},
+ "port": {
+ "type": "integer",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991,
+ "description": "Port of the TURN server"
+ },
+ "protocol": {
+ "type": "string",
+ "enum": ["udp", "tcp", "tls"],
+ "description": "Transport clients use to connect to the TURN server"
+ },
+ "username": {"description": "Fixed TURN username", "type": "string"},
+ "credential": {"description": "Fixed TURN password", "type": "string"},
+ "secret": {"description": "Shared secret LiveKit signs short-lived TURN credentials with", "type": "string"},
+ "ttl": {
+ "description": "Lifetime of the signed credentials in seconds",
+ "type": "integer",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ }
+ },
+ "required": ["host", "port", "protocol"],
+ "additionalProperties": false
+ },
"VoiceServerHealthResponse": {
"type": "object",
"properties": {
@@ -45260,6 +45340,18 @@
"required": ["status", "checked_at", "error"],
"additionalProperties": false
},
+ "VoicePublicIpv6Type": {
+ "type": "string",
+ "format": "ipv6",
+ "pattern": "^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$",
+ "description": "Public IPv6 address LiveKit gives to clients"
+ },
+ "VoicePublicIpv4Type": {
+ "type": "string",
+ "format": "ipv4",
+ "pattern": "^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$",
+ "description": "Public IPv4 address LiveKit gives to clients"
+ },
"Int64Type": {
"anyOf": [{"type": "string"}, {"type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991}],
"format": "int64"
diff --git a/fluxer_api/src/api/voice/VoiceDataInitializer.ts b/fluxer_api/src/api/voice/VoiceDataInitializer.ts
index b8a1ee8b4..0a0ee6967 100644
--- a/fluxer_api/src/api/voice/VoiceDataInitializer.ts
+++ b/fluxer_api/src/api/voice/VoiceDataInitializer.ts
@@ -69,6 +69,8 @@ export class VoiceDataInitializer {
draining: false,
pinnedHostname: null,
pinnedSoftLimit: false,
+ publicIpv4: null,
+ publicIpv6: null,
restrictions: {
vipOnly: false,
requiredGuildFeatures: new Set(),
diff --git a/fluxer_api/src/api/voice/VoiceModel.ts b/fluxer_api/src/api/voice/VoiceModel.ts
index 56d7949b3..88dbe71ea 100644
--- a/fluxer_api/src/api/voice/VoiceModel.ts
+++ b/fluxer_api/src/api/voice/VoiceModel.ts
@@ -37,6 +37,8 @@ export interface VoiceServerRecord {
draining: boolean;
pinnedHostname: string | null;
pinnedSoftLimit: boolean;
+ publicIpv4: string | null;
+ publicIpv6: string | null;
createdAt: Date | null;
updatedAt: Date | null;
}
diff --git a/fluxer_api/src/api/voice/VoiceNodeService.ts b/fluxer_api/src/api/voice/VoiceNodeService.ts
index 97af9d66c..364d9d0a0 100644
--- a/fluxer_api/src/api/voice/VoiceNodeService.ts
+++ b/fluxer_api/src/api/voice/VoiceNodeService.ts
@@ -38,6 +38,7 @@ import type {
VoiceJoinRequest,
VoiceJoinResponse,
VoiceNodeResponse,
+ VoiceTurnServer,
} from '@fluxer/schema/src/domains/voice/VoiceNodeSchemas';
import {lookupGeoipByIp} from '@pkgs/geoip/src/GeoipLookup';
@@ -199,7 +200,7 @@ export class VoiceNodeService {
}
async preview(row: VoiceJoinTokenRow, body: VoiceJoinPreviewRequest, clientIp: string | null) {
- const point = await this.locate(body.public_ipv4 ?? clientIp);
+ const point = await this.locate(body.public_ipv4 ?? body.public_ipv6 ?? clientIp);
const region = await this.chooseRegion(row, body.region_id, point);
const servers = await this.deps.voiceRepository.listAllServers();
const response: VoiceJoinPreviewResponse = {
@@ -221,6 +222,7 @@ export class VoiceNodeService {
api_code_version: API_CODE_VERSION,
release: process.env.BUILD_VERSION?.trim() ?? '',
expires_at: row.expires_at.toISOString(),
+ turn_servers: turnServers(),
};
return response;
}
@@ -239,7 +241,7 @@ export class VoiceNodeService {
const point =
body.latitude !== undefined && body.longitude !== undefined
? {latitude: body.latitude, longitude: body.longitude}
- : await this.locate(body.public_ipv4 ?? clientIp);
+ : await this.locate(body.public_ipv4 ?? body.public_ipv6 ?? clientIp);
const region = await this.chooseRegion(row, body.region_id, point);
const servers = await voiceRepository.listAllServers();
const serverId = row.server_id ?? body.server_id ?? this.suggestServerId(region.id, servers);
@@ -280,6 +282,8 @@ export class VoiceNodeService {
internalEndpoint: row.internal_endpoint,
pinnedHostname: row.hostname ?? null,
pinnedSoftLimit: row.soft_connection_limit != null,
+ publicIpv4: body.public_ipv4 ?? null,
+ publicIpv6: body.public_ipv6 ?? null,
softConnectionLimit: row.soft_connection_limit ?? body.soft_connection_limit ?? null,
notes: row.notes ?? `Joined with a join token on ${now.toISOString().slice(0, 10)}`,
restrictions: {
@@ -312,6 +316,7 @@ export class VoiceNodeService {
endpoint,
webhook_url: `${Config.endpoints.apiPublic}/webhooks/livekit`,
node_url: `${Config.endpoints.apiPublic}${VOICE_NODE_PATH}`,
+ turn_servers: turnServers(),
};
} catch (error) {
await joinTokenRepository.release(row, claimId).catch(() => false);
@@ -357,6 +362,9 @@ export class VoiceNodeService {
is_active: server.isActive,
draining: server.draining,
soft_connection_limit: server.softConnectionLimit,
+ public_ipv4: server.publicIpv4,
+ public_ipv6: server.publicIpv6,
+ turn_servers: turnServers(),
health: toHealthResponse(healthOf(this.deps.health, server)),
};
}
@@ -383,6 +391,8 @@ export class VoiceNodeService {
if (body.latitude !== undefined) updated.latitude = body.latitude;
if (body.longitude !== undefined) updated.longitude = body.longitude;
if (body.soft_connection_limit !== undefined) updated.softConnectionLimit = body.soft_connection_limit;
+ if (body.public_ipv4 !== undefined) updated.publicIpv4 = body.public_ipv4 || null;
+ if (body.public_ipv6 !== undefined) updated.publicIpv6 = body.public_ipv6 || null;
await this.deps.voiceRepository.upsertServer(updated);
await this.deps.publish(
JSON.stringify({type: 'server_updated', regionId: server.regionId, serverId: server.serverId}),
@@ -489,6 +499,10 @@ export class VoiceNodeService {
}
}
+function turnServers(): Array<VoiceTurnServer> {
+ return Config.voice.turnServers.map((server) => ({...server}));
+}
+
function emptyRestrictions(): VoiceRegionRecord['restrictions'] {
return {
vipOnly: false,
diff --git a/fluxer_api/src/api/voice/VoiceRepository.ts b/fluxer_api/src/api/voice/VoiceRepository.ts
index 967106d1f..d9deacdda 100644
--- a/fluxer_api/src/api/voice/VoiceRepository.ts
+++ b/fluxer_api/src/api/voice/VoiceRepository.ts
@@ -179,6 +179,8 @@ export class VoiceRepository {
draining: server.draining,
pinned_hostname: server.pinnedHostname,
pinned_soft_limit: server.pinnedSoftLimit,
+ public_ipv4: server.publicIpv4,
+ public_ipv6: server.publicIpv6,
created_at: server.createdAt ?? new Date(),
updated_at: server.updatedAt ?? new Date(),
};
@@ -229,6 +231,8 @@ export class VoiceRepository {
draining: row.draining ?? false,
pinnedHostname: row.pinned_hostname ?? null,
pinnedSoftLimit: row.pinned_soft_limit ?? false,
+ publicIpv4: row.public_ipv4 ?? null,
+ publicIpv6: row.public_ipv6 ?? null,
createdAt: row.created_at,
updatedAt: row.updated_at,
};
diff --git a/fluxer_api/src/api/voice/VoiceServerEndpoints.ts b/fluxer_api/src/api/voice/VoiceServerEndpoints.ts
index ed9234285..5213a2256 100644
--- a/fluxer_api/src/api/voice/VoiceServerEndpoints.ts
+++ b/fluxer_api/src/api/voice/VoiceServerEndpoints.ts
@@ -87,12 +87,15 @@ export function parseNodeEndpoint(endpoint: string): URL {
throw new VoiceEndpointError('invalid', 'The endpoint must not have credentials, a query or a fragment');
}
if (isIP(bareHost(url)) === 6) {
- throw new VoiceEndpointError('invalid', 'An endpoint that is an IP address must be IPv4');
+ throw new VoiceEndpointError(
+ 'invalid',
+ 'An endpoint can be an IPv4 address but not an IPv6 address. Give a voice server on IPv6 a hostname with an AAAA record',
+ );
}
return url;
}
-async function resolveCheckedAddress(url: URL, allowPrivate: boolean): Promise<string> {
+async function resolveCheckedAddresses(url: URL, allowPrivate: boolean): Promise<Array<string>> {
const host = bareHost(url);
const addresses = isIP(host) ? [host] : await resolveHost(host).catch(() => []);
if (addresses.length === 0) {
@@ -101,7 +104,7 @@ async function resolveCheckedAddress(url: URL, allowPrivate: boolean): Promise<s
if (!allowPrivate && addresses.some((address) => !isPublicIpAddress(address))) {
throw new VoiceEndpointError('private', `${host} resolves to an address that is not public`);
}
- return addresses[0]!;
+ return addresses;
}
interface ProbeResponse {
@@ -165,18 +168,29 @@ function transportError(error: unknown): string {
return error instanceof Error ? error.message : 'connection failed';
}
+async function requestAny(
+ url: URL,
+ addresses: Array<string | null>,
+ options: Omit<Parameters<typeof request>[1], 'address'>,
+): Promise<ProbeResponse> {
+ const errors: Array<string> = [];
+ for (const address of addresses) {
+ try {
+ return await request(url, {...options, address});
+ } catch (error) {
+ errors.push(address ? `${address}: ${transportError(error)}` : transportError(error));
+ }
+ }
+ throw new VoiceEndpointError('unreachable', errors.join(', '));
+}
+
export async function probeLiveKit(
base: string,
options: {checkAddress: boolean; allowPrivate: boolean; timeoutMs: number},
): Promise<void> {
const url = withPath(base, '/');
- const address = options.checkAddress ? await resolveCheckedAddress(url, options.allowPrivate) : null;
- let response: ProbeResponse;
- try {
- response = await request(url, {method: 'GET', address, timeoutMs: options.timeoutMs});
- } catch (error) {
- throw new VoiceEndpointError('unreachable', transportError(error));
- }
+ const addresses = options.checkAddress ? await resolveCheckedAddresses(url, options.allowPrivate) : [null];
+ const response = await requestAny(url, addresses, {method: 'GET', timeoutMs: options.timeoutMs});
if (response.status !== 200 || response.body.trim() !== 'OK') {
throw new VoiceEndpointError('unreachable', `HTTP ${response.status}`);
}
@@ -188,21 +202,15 @@ export async function checkLiveKitKeys(
options: {checkAddress: boolean; allowPrivate: boolean; timeoutMs: number},
): Promise<void> {
const url = withPath(base, '/twirp/livekit.RoomService/ListRooms');
- const address = options.checkAddress ? await resolveCheckedAddress(url, options.allowPrivate) : null;
+ const addresses = options.checkAddress ? await resolveCheckedAddresses(url, options.allowPrivate) : [null];
const token = new AccessToken(keys.apiKey, keys.apiSecret, {ttl: 60});
token.addGrant({roomList: true});
- let response: ProbeResponse;
- try {
- response = await request(url, {
- method: 'POST',
- address,
- timeoutMs: options.timeoutMs,
- headers: {Authorization: `Bearer ${await token.toJwt()}`, 'Content-Type': 'application/json'},
- body: '{}',
- });
- } catch (error) {
- throw new VoiceEndpointError('unreachable', transportError(error));
- }
+ const response = await requestAny(url, addresses, {
+ method: 'POST',
+ timeoutMs: options.timeoutMs,
+ headers: {Authorization: `Bearer ${await token.toJwt()}`, 'Content-Type': 'application/json'},
+ body: '{}',
+ });
if (response.status === 401 || response.status === 403) {
throw new VoiceEndpointError('key_mismatch', `HTTP ${response.status}`);
}
diff --git a/fluxer_api/src/api/voice/tests/VoiceAvailabilityService.test.ts b/fluxer_api/src/api/voice/tests/VoiceAvailabilityService.test.ts
index 974ecfa8d..86b860c20 100644
--- a/fluxer_api/src/api/voice/tests/VoiceAvailabilityService.test.ts
+++ b/fluxer_api/src/api/voice/tests/VoiceAvailabilityService.test.ts
@@ -50,6 +50,8 @@ function createServer(overrides: Partial<VoiceServerRecord> = {}): VoiceServerRe
internalEndpoint: null,
pinnedHostname: null,
pinnedSoftLimit: false,
+ publicIpv4: null,
+ publicIpv6: null,
draining: false,
restrictions: {
vipOnly: false,
diff --git a/fluxer_api/src/api/voice/tests/VoiceRegionSelection.test.ts b/fluxer_api/src/api/voice/tests/VoiceRegionSelection.test.ts
index 7bb1ce02d..0b9472201 100644
--- a/fluxer_api/src/api/voice/tests/VoiceRegionSelection.test.ts
+++ b/fluxer_api/src/api/voice/tests/VoiceRegionSelection.test.ts
@@ -68,6 +68,8 @@ function createVoiceServer({
internalEndpoint: null,
pinnedHostname: null,
pinnedSoftLimit: false,
+ publicIpv4: null,
+ publicIpv6: null,
draining: false,
restrictions: {
vipOnly: false,
diff --git a/fluxer_docs/src/content/docs/admin-api/voice.mdx b/fluxer_docs/src/content/docs/admin-api/voice.mdx
index e98d2ea3f..e12185397 100644
--- a/fluxer_docs/src/content/docs/admin-api/voice.mdx
+++ b/fluxer_docs/src/content/docs/admin-api/voice.mdx
@@ -86,6 +86,8 @@ A voice server is one LiveKit deployment in one region, identified by its `regio
| allowed_user_ids | array[snowflake] | The only accounts allowed to use the server, when not empty (max 1000) |
| internal_endpoint | ?string | The `http://` or `https://` URL the API uses for the LiveKit control API and health checks, or null to use `endpoint` |
| draining | boolean | Whether new calls go to other servers while calls already on this one keep going |
+| public_ipv4 | ?string | The public IPv4 address LiveKit gives to clients, or null when none is known |
+| public_ipv6 | ?string | The public IPv6 address LiveKit gives to clients, or null when none is known |
| health | [health](#voice-server-health-object) object | The server's health as the API node that answered last saw it |
| duplicate_api_key | boolean | Whether another server uses the same `api_key` |
| created_at | ?ISO8601 timestamp | When the server was created |
@@ -321,6 +323,8 @@ Adds a server to a region. Requires `voice:server:create`.
| allowed_user_ids? | array[snowflake] | The only accounts allowed to use the server, when not empty (max 1000) |
| internal_endpoint? | ?string | The `http://` or `https://` URL the API uses for the control API and health checks (max 512 characters) |
| draining? | boolean | Whether new calls go to other servers (default false) |
+| public_ipv4? | ?string | The public IPv4 address LiveKit gives to clients, for the admin panel |
+| public_ipv6? | ?string | The public IPv6 address LiveKit gives to clients, for the admin panel |
<sup>1</sup> Send both coordinates or neither
@@ -364,6 +368,8 @@ Updates a server, and an array you send replaces the stored one. Requires `voice
| allowed_user_ids? | array[snowflake] | The only accounts allowed to use the server, when not empty (max 1000) |
| internal_endpoint? | ?string | The `http://` or `https://` URL the API uses for the control API and health checks, or null to use `endpoint` |
| draining? | boolean | Whether new calls go to other servers |
+| public_ipv4? | ?string | The public IPv4 address LiveKit gives to clients, or null to clear it |
+| public_ipv6? | ?string | The public IPv6 address LiveKit gives to clients, or null to clear it |
<sup>1</sup> Send both coordinates or neither, and send both as null to use the region's coordinates
@@ -534,7 +540,7 @@ These routes are for the voice machine, not for admins. They take `Authorization
<RouteHeader method="POST" path="/v1/voice/join/preview" unauthenticated />
-Shows what a join would choose, without using the token. The JSON body has `public_ipv4`, `region_id`, `cpu_count`, `memory_bytes` and `rexctl_version`, all optional. The response has the suggested `server_id`, `server_id_pinned` set to true when the token sets the server ID, the `region` with its `id`, `name`, `distance_km`, whether it's `new` and its `source`, the `latitude` and `longitude` from GeoIP rounded to 0.1 degrees, the `hostname` preset, a `suggested_hostname`, the `soft_connection_limit` preset, the `webhook_url`, the `api_code_version`, the `release` of the API and `expires_at`.
+Shows what a join would choose, without using the token. The JSON body has `public_ipv4`, `public_ipv6`, `region_id`, `cpu_count`, `memory_bytes` and `rexctl_version`, all optional. Fluxer looks up one address in GeoIP, the first of `public_ipv4`, `public_ipv6` and the address the request comes from. The response has the suggested `server_id`, `server_id_pinned` set to true when the token sets the server ID, the `region` with its `id`, `name`, `distance_km`, whether it's `new` and its `source`, the `latitude` and `longitude` from GeoIP rounded to 0.1 degrees, the `hostname` preset, a `suggested_hostname`, the `soft_connection_limit` preset, the `webhook_url`, the `api_code_version`, the `release` of the API, `expires_at` and the instance's `turn_servers`.
Fluxer picks the token's region first, then an existing region in `region_id`, then the existing region nearest to the machine when the instance has a GeoIP database, and the default region otherwise. It never creates a region unless the token has a new one. The `source` says which of these it used, as `token`, `requested`, `nearest` or `default`.
@@ -544,7 +550,7 @@ Registers the server and uses the token.
| Field | Type | Description |
| --- | --- | --- |
-| endpoint | string | The public `wss://` URL of the server. A host that is an IP address must be IPv4 |
+| endpoint | string | The public `wss://` URL of the server. A host that is an IP address must be IPv4. A server with only IPv6 needs a hostname |
| api_key | string | A LiveKit API key no other server uses (1-256 characters) |
| api_secret | string | Its secret (32-256 characters) |
| server_id? | string | The server ID, ignored when the token has one |
@@ -552,11 +558,14 @@ Registers the server and uses the token.
| latitude?<sup>1</sup> | number | The server's latitude |
| longitude?<sup>1</sup> | number | The server's longitude |
| soft_connection_limit? | integer | Ignored when the token has one |
-| public_ipv4? | string | The machine's public address, for GeoIP |
+| public_ipv4? | string | The machine's public IPv4 address, for GeoIP and the admin panel |
+| public_ipv6? | string | The machine's public IPv6 address, for GeoIP and the admin panel |
<sup>1</sup> Send both coordinates or neither
-Fluxer resolves the endpoint's host, refuses it when any address is private unless `FLUXER_VOICE_JOIN_ALLOW_PRIVATE_ENDPOINTS` is true, and connects to the address it checked. `GET` on the endpoint's path must answer `OK` within 10 seconds with a certificate Fluxer trusts, and the room service must accept the key and secret. Then Fluxer saves the server, active and not draining, and the token stops working. The response has `server_id`, `region_id`, `endpoint`, `webhook_url` and `node_url`.
+Fluxer resolves the endpoint's host, refuses it when any address is private unless `FLUXER_VOICE_JOIN_ALLOW_PRIVATE_ENDPOINTS` is true, and connects to the addresses it checked, one after another until one answers. `GET` on the endpoint's path must answer `OK` within 10 seconds with a certificate Fluxer trusts, and the room service must accept the key and secret. Then Fluxer saves the server, active and not draining, and the token stops working. The response has `server_id`, `region_id`, `endpoint`, `webhook_url`, `node_url` and `turn_servers`.
+
+`turn_servers` is the list in `FLUXER_LIVEKIT_TURN_SERVERS` on the instance, as objects with `host`, `port`, `protocol` and either `username` and `credential` or `secret` and `ttl`. It's empty when the setting is. rexctl puts it in the LiveKit configuration of the server.
| Status | Code | Condition |
| --- | --- | --- |
@@ -585,11 +594,11 @@ Fluxer refuses tokens with a `video` grant. LiveKit participant tokens and webho
<RouteHeader method="GET" path="/v1/voice/node" unauthenticated />
-Returns the server's `region_id`, `server_id`, `endpoint`, `latitude`, `longitude`, `is_active`, `draining`, `soft_connection_limit` and `health`.
+Returns the server's `region_id`, `server_id`, `endpoint`, `latitude`, `longitude`, `is_active`, `draining`, `soft_connection_limit`, `public_ipv4`, `public_ipv6`, `turn_servers` and `health`.
<RouteHeader method="PATCH" path="/v1/voice/node" unauthenticated />
-Takes `endpoint`, `draining`, `latitude`, `longitude` and `soft_connection_limit`, and returns the server like `GET`. Fluxer checks a new endpoint the same way as a join. When the server has an internal endpoint, Fluxer also tries the new public endpoint and logs a warning when it doesn't answer, without refusing the change. A new endpoint must keep the token's hostname, and a server can't change a soft connection limit the token set. A server can't change its region, its restrictions, `internal_endpoint` or `is_active`. A server an admin turned off stays off.
+Takes `endpoint`, `draining`, `latitude`, `longitude`, `soft_connection_limit`, `public_ipv4` and `public_ipv6`, and returns the server like `GET`. An empty string for `public_ipv4` or `public_ipv6` clears it. Fluxer checks a new endpoint the same way as a join. When the server has an internal endpoint, Fluxer also tries the new public endpoint and logs a warning when it doesn't answer, without refusing the change. A new endpoint must keep the token's hostname, and a server can't change a soft connection limit the token set. A server can't change its region, its restrictions, `internal_endpoint` or `is_active`. A server an admin turned off stays off.
<RouteHeader method="DELETE" path="/v1/voice/node" unauthenticated />
diff --git a/fluxer_docs/src/content/docs/operator/environment.mdx b/fluxer_docs/src/content/docs/operator/environment.mdx
index 7fb21d360..53d839b7c 100644
--- a/fluxer_docs/src/content/docs/operator/environment.mdx
+++ b/fluxer_docs/src/content/docs/operator/environment.mdx
@@ -310,7 +310,7 @@ The second STUN host LiveKit asks to find its public IP address, as `host:port`.
### `FLUXER_LIVEKIT_TURN_SERVERS`
-TURN relays LiveKit offers to browsers and apps, as a JSON array of objects with `host`, `port`, `protocol` and optional `username` and `credential`, such as `[{"host":"turn.example.com","port":3478,"protocol":"udp","username":"fluxer","credential":"secret"}]`. Use `udp`, `tcp` or `tls` for `protocol`. Set it when browsers and apps can't connect to the LiveKit ports directly, such as behind Cloudflare Tunnel. When it's empty, LiveKit offers no TURN relay. The default is `[]`. With rexctl, use `rexctl config set FLUXER_LIVEKIT_TURN_SERVERS`.
+TURN servers that browsers and apps get when they join a call, as a JSON array of objects with `host`, `port` and `protocol`, and either `username` and `credential` or `secret` with an optional `ttl`, such as `[{"host":"turn.example.com","port":3478,"protocol":"udp","secret":"a-long-random-secret"}]`. Use `udp`, `tcp` or `tls` for `protocol`, and a hostname or an IPv4 address for `host`. With `secret`, LiveKit makes short-lived credentials for each participant in the form coturn checks with `use-auth-secret`, and `ttl`, a whole number from 1, sets how many seconds they last. The bundled voice server and the servers you add with rexctl voice add give these to clients, and rexctl restarts the added servers one at a time when the list changes. A server that joined with rexctl voice join gets the list when it joins and on each rexctl upgrade in its voice folder, unless the instance runs an older release than the rexctl there. Set it when callers can't connect to a voice server directly, such as from networks that allow only port 443. When it's empty, clients get no TURN server. A value the API can't read stops it from starting, and rexctl config set refuses one. The default is `[]`. With rexctl, use `rexctl config set FLUXER_LIVEKIT_TURN_SERVERS`.
## Standalone voice servers
@@ -342,7 +342,11 @@ The UDP port for media on this host. LiveKit listens on the same port inside the
### `FLUXER_VOICE_NODE_IP`
-The public IPv4 address LiveKit gives to clients. Set `FLUXER_VOICE_USE_EXTERNAL_IP` to `false` with it.
+The public addresses LiveKit gives to clients. Give an IPv4 address, an IPv6 address, or both with a comma between them, such as `203.0.113.7,2001:db8::7`. Set `FLUXER_VOICE_USE_EXTERNAL_IP` to `false` with it. LiveKit offers an IPv6 address only when the server's Docker network has IPv6.
+
+### `FLUXER_VOICE_ICE_IPS`
+
+The address ranges LiveKit may offer to clients, as a JSON array of ranges such as `["::/0"]`. rexctl sets it to the families in `FLUXER_VOICE_NODE_IP`, so a server with only IPv6 offers no private IPv4 address of its container. Use `[]` to offer every address.
### `FLUXER_VOICE_USE_EXTERNAL_IP`
@@ -384,6 +388,10 @@ These go in `edge.env` next to `voice-edge.compose.yml` in the voice folder of t
The public IPv4 address of the voice machine, when an endpoint uses that address and not a hostname. The edge then answers clients that send no server name with the certificate for that address, which browsers need.
+### `FLUXER_VOICE_NETWORK_IPV6`
+
+Whether the voice network gets IPv6. Use `true` or `false`. rexctl sets it to `true` when it creates the network on a machine with a public IPv6 address. Docker can't add IPv6 to a network that already exists.
+
### `FLUXER_VOICE_EDGE_EMAIL`
The email address the voice edge gives Let's Encrypt for notices about its certificates. When it's empty, the edge gets certificates without one.
diff --git a/fluxer_docs/src/content/docs/operator/reverse-proxy.mdx b/fluxer_docs/src/content/docs/operator/reverse-proxy.mdx
index 555cad74c..da7d302a6 100644
--- a/fluxer_docs/src/content/docs/operator/reverse-proxy.mdx
+++ b/fluxer_docs/src/content/docs/operator/reverse-proxy.mdx
@@ -149,7 +149,7 @@ rexctl config set FLUXER_LIVEKIT_TURN_SERVERS '[{"host":"turn.example.com","port
Without rexctl, put the same value in `.env` between single quotes and run `docker compose up -d`.
-LiveKit hands the relay to browsers and apps when they join a call, and they use it when they can't connect to LiveKit directly. Keep `FLUXER_LIVEKIT_USE_EXTERNAL_IP` at `true` so LiveKit tells them its public address. LiveKit opens the path to the relay from its own side, which most routers let through without open ports. If calls still don't connect, your router probably blocks this and you need to open TCP port 7881 and UDP port 7882 after all.
+LiveKit hands the relay to browsers and apps when they join a call, and they use it when they can't connect to LiveKit directly. Voice servers that rexctl adds or joins hand out the same relays. See [TURN servers](/operator/voice-servers/#turn-servers). Keep `FLUXER_LIVEKIT_USE_EXTERNAL_IP` at `true` so LiveKit tells them its public address. LiveKit opens the path to the relay from its own side, which most routers let through without open ports. If calls still don't connect, your router probably blocks this and you need to open TCP port 7881 and UDP port 7882 after all.
On Kubernetes, add the relay to `livekit.extraConfig` in your values file.
diff --git a/fluxer_docs/src/content/docs/operator/rexctl.mdx b/fluxer_docs/src/content/docs/operator/rexctl.mdx
index 4e1da2b3f..b1617e831 100644
--- a/fluxer_docs/src/content/docs/operator/rexctl.mdx
+++ b/fluxer_docs/src/content/docs/operator/rexctl.mdx
@@ -1003,6 +1003,10 @@ rexctl voice add [flags]
Public IPv4 address LiveKit gives to clients, also the address the ports bind to when it's on this machine.
+- `--ipv6 string`
+
+ Public IPv6 address LiveKit gives to clients.
+
- `--lat float`
Latitude of the server.
@@ -1023,6 +1027,10 @@ rexctl voice add [flags]
Leave the firewall on this machine alone.
+- `--no-ipv6`
+
+ Give clients only the IPv4 address, even when this machine has IPv6.
+
- `--region string`
Existing voice region for the server.
@@ -1053,7 +1061,7 @@ rexctl voice hostname <id> <host>
### rexctl voice join
-Install a standalone LiveKit voice server on this machine and register it with the Fluxer instance at \<domain>. Get the token with rexctl voice token on the Fluxer machine, or with Add a voice server in the admin panel. The token works once. rexctl also reads it from FLUXER_VOICE_JOIN_TOKEN or, with --token-stdin, from standard input.
+Install a standalone LiveKit voice server on this machine and register it with the Fluxer instance at \<domain>. Get the token with rexctl voice token on the Fluxer machine, or with Add a voice server in the admin panel. The token works once. rexctl also reads it from FLUXER_VOICE_JOIN_TOKEN or, with --token-stdin, from standard input. The server offers IPv4 and IPv6 when the machine has both. On a machine with only IPv6, pass --hostname with an AAAA record that points here.
```sh
rexctl voice join <domain> [token] [flags]
@@ -1095,6 +1103,10 @@ rexctl voice join <domain> [token] [flags]
Public IPv4 address LiveKit gives to clients, also the address the ports bind to when it's on this machine.
+- `--ipv6 string`
+
+ Public IPv6 address LiveKit gives to clients.
+
- `--lat float`
Latitude of the server.
@@ -1115,6 +1127,10 @@ rexctl voice join <domain> [token] [flags]
Leave the firewall on this machine alone.
+- `--no-ipv6`
+
+ Give clients only the IPv4 address, even when this machine has IPv6.
+
- `--region string`
Existing voice region for the server.
diff --git a/fluxer_docs/src/content/docs/operator/voice-compose.mdx b/fluxer_docs/src/content/docs/operator/voice-compose.mdx
index c104839d1..567ced9c8 100644
--- a/fluxer_docs/src/content/docs/operator/voice-compose.mdx
+++ b/fluxer_docs/src/content/docs/operator/voice-compose.mdx
@@ -54,7 +54,8 @@ Set at least these values in it:
- `FLUXER_VOICE_API_KEY` to a key no other server of your instance uses, such as `fluxer-fra-server-1`.
- `FLUXER_VOICE_API_SECRET` to the output of `openssl rand -hex 32`.
- `FLUXER_VOICE_WEBHOOK_URL` to the webhook address.
-- `FLUXER_VOICE_NODE_IP` to the machine's public IPv4 address, and `FLUXER_VOICE_USE_EXTERNAL_IP` to `false`.
+- `FLUXER_VOICE_NODE_IP` to the machine's public IPv4 address, and `FLUXER_VOICE_USE_EXTERNAL_IP` to `false`. On a machine with IPv6, give both addresses with a comma between them, such as `203.0.113.7,2001:db8::7`. On a machine with only IPv6, give the IPv6 address. LiveKit offers the IPv6 address only when the server's Docker network has IPv6. On another machine, set `FLUXER_VOICE_NETWORK_IPV6` to `true` in `edge.env` before the edge starts for the first time. See [IPv6](/operator/voice-servers/#ipv6).
+- `FLUXER_LIVEKIT_TURN_SERVERS` to the same list as on the Fluxer machine, between single quotes, when your instance has TURN servers.
A second server on the same machine needs another `FLUXER_VOICE_TCP_PORT` and `FLUXER_VOICE_UDP_PORT`, such as 7883 and 7884.
diff --git a/fluxer_docs/src/content/docs/operator/voice-servers.mdx b/fluxer_docs/src/content/docs/operator/voice-servers.mdx
index a8fd92c35..f7818613a 100644
--- a/fluxer_docs/src/content/docs/operator/voice-servers.mdx
+++ b/fluxer_docs/src/content/docs/operator/voice-servers.mdx
@@ -49,6 +49,8 @@ Behind 1:1 NAT, as on AWS, Google Cloud, Oracle Cloud or a home router, the publ
rexctl voice add --ip 198.51.100.8
```
+When `network.ipv6` is on and the machine runs Docker 27 or later, `rexctl voice add` also gives the server the machine's public IPv6 address. Pass `--ipv6` to give the address yourself, or `--no-ipv6` to offer only IPv4. On a machine with only IPv6, it stops until you run `rexctl config set network.ipv6 true`.
+
A server added without `--ip` follows `voice.public_ip`. When you change that setting with `rexctl config set`, rexctl gives these servers the new address and restarts them one at a time, as an upgrade does. When Fluxer is stopped, they get it at the next `rexctl start`. A server added with `--ip` keeps its address.
After it adds a server, rexctl prints its TCP and UDP ports. Open them in your provider's firewall as well. The test at the end runs on the same machine and can't see that firewall.
@@ -83,14 +85,14 @@ The join command does this:
1. Reads your instance's public settings from its domain and stops when voice is off there.
2. Installs Docker when the machine has neither Docker nor Podman, as `rexctl install` does. On a machine with Podman older than 5.8.2 and no Fluxer instance, it stops. That Podman doesn't start voice servers again after a restart.
-3. Finds the machine's public IPv4 address, its CPU count, its memory and its firewall.
+3. Finds the machine's public IPv4 and IPv6 addresses, its CPU count, its memory and its firewall.
4. Asks your instance for the server's ID, region and webhook address, without using the token.
5. Picks free ports and a hostname or IP address for the endpoint.
6. Shows a summary and asks once. Pass `--yes` to go ahead without asking.
7. Raises the UDP buffer limits in `/etc/sysctl.d/61-fluxer-voice.conf`, which LiveKit needs for many calls. This needs root. Without root, rexctl shows the two commands to run with sudo. Then it starts an edge on ports 80 and 443 with Caddy, and the LiveKit server behind it.
8. Opens the server's ports, and ports 80 and 443, in ufw or firewalld.
9. Waits for a certificate, then registers the server with your instance. The token stops working once it's registered.
-10. Checks that browsers on your instance can connect to the server, that calls connect over UDP and TCP, and that your instance accepts the server's webhooks.
+10. Checks that browsers on your instance can connect to the server, that calls connect over UDP and TCP on each address family the server has, and that your instance accepts the server's webhooks.
When a step fails, run the same command again with the same token. rexctl picks up where it stopped, because the token is used only once the server is registered.
@@ -113,12 +115,13 @@ A token can set the region, the server ID, the hostname, a soft limit and the re
## Hostnames and certificates
-With no hostname, the endpoint uses the machine's public IPv4 address, such as `wss://203.0.113.7/livekit-fra-server-1`. Caddy gets a short-lived Let's Encrypt certificate for that address. The certificate lasts about 6 days, and Caddy renews it before it expires. This needs ports 80 and 443 open to the internet and no DNS record.
+With no hostname, the endpoint uses the machine's public IPv4 address, such as `wss://203.0.113.7/livekit-fra-server-1`. A machine with only IPv6 needs a hostname. See [IPv6](#ipv6). Caddy gets a short-lived Let's Encrypt certificate for that address. The certificate lasts about 6 days, and Caddy renews it before it expires. This needs ports 80 and 443 open to the internet and no DNS record.
-To use a hostname, add an `A` record that points at the machine first.
+To use a hostname, add an `A` record that points at the machine first. On a machine with IPv6, you can add an `AAAA` record too.
```
-voice-fra.chat.example.com. A 203.0.113.7
+voice-fra.chat.example.com. A 203.0.113.7
+voice-fra.chat.example.com. AAAA 2001:db8::7
```
Then pass it when you join.
@@ -127,7 +130,7 @@ Then pass it when you join.
rexctl voice join chat.example.com fvj_... --hostname voice-fra.chat.example.com
```
-When `voice-` followed by the region and your domain already points at the machine, rexctl uses it without being asked. When the hostname doesn't point at the machine yet, rexctl prints the record and waits up to 10 minutes. After that it uses the IP address and prints the command to switch later. With `--yes`, or without a terminal, it uses the IP address straight away.
+When `voice-` followed by the region and your domain already points at the machine, rexctl uses it without being asked. When the hostname doesn't point at the machine yet, rexctl prints the records and waits up to 10 minutes. After that it uses the IP address and prints the command to switch later. With `--yes`, or without a terminal, it uses the IP address straight away. A machine with only IPv6 has no IP address to fall back to. There rexctl waits up to 10 minutes for the `AAAA` record even with `--yes`, and stops when the record still doesn't point at the machine.
A token made with `--hostname` works only with that hostname. rexctl stops when you pass another one. It waits up to 10 minutes for the name to point at the machine, also with `--yes`, and stops before it starts anything when the name still doesn't. Add the record, then run the same command again.
@@ -139,7 +142,63 @@ On Cloudflare, set this record to **DNS only**. `rexctl voice join` checks that
A server from `rexctl voice add` uses your instance's domain, which can stay proxied. Only signalling goes through Cloudflare. Audio and video go straight to the machine's IP address, which LiveKit gives to clients.
-Voice servers serve IPv4 only. A machine with only an IPv6 address can't run one.
+## IPv6
+
+`rexctl voice join` and `rexctl voice add` find the machine's public IPv6 address with STUN. When STUN gets no answer over IPv6, they use the address the machine sends from on its default route. They check that it's a global address on the machine, and skip temporary addresses, which change over time. Pass `--ipv6` to give the address yourself, or `--no-ipv6` to offer only IPv4.
+
+A voice server on IPv6 needs Docker 27 or later, and not rootless Docker. With Podman, rootless Docker or an older Docker, a machine with IPv4 and IPv6 offers only IPv4, and rexctl stops on a machine with only IPv6.
+
+### Machines with IPv4 and IPv6
+
+LiveKit gives clients both addresses for media. Callers first open a WebSocket to the endpoint, and that needs an address of their own family. With an `A` record and no `AAAA` record for the hostname, or with an IP address as the endpoint, callers with only IPv6 can't connect. An endpoint that is an IP address is always IPv4. To let callers with only IPv6 in, use a hostname with an `AAAA` record that points at the machine. When the hostname has an `AAAA` record, it has to point at the machine.
+
+`rexctl voice add` uses your instance's domain as the endpoint. Callers with only IPv6 need an `AAAA` record for that domain too.
+
+The bundled voice server gives clients the Fluxer machine's IPv6 address too when `network.ipv6` is on.
+
+When `voice.public_ip` is empty, servers added without `--ip` give clients the machine's IPv4 address as rexctl last found it. When the machine gets a new IPv4 address, they get it the next time rexctl starts Fluxer, with `rexctl start` or when the machine starts on a system with systemd, and at the next `rexctl upgrade` to a new release. `rexctl doctor` warns when a server gives clients an old address.
+
+### Machines with only IPv6
+
+- The server needs a hostname with an `AAAA` record that points at the machine. An endpoint can't be an IPv6 address, because browsers can't allow one in the content security policy of the web app.
+- The Fluxer machine needs IPv6 too. Your instance checks the server through its endpoint, and the server sends webhooks to your instance's public API address. Run `rexctl config set network.ipv6 true` on the Fluxer machine, and give the API address an `AAAA` record.
+- Callers with IPv6 connect directly. Callers with only IPv4 need a TURN server you run and a machine that forwards ports 80 and 443, and `rexctl voice join` says so once the server has joined. See [Callers with only IPv4](#callers-with-only-ipv4).
+- `install.sh` and `rexctl upgrade` download rexctl from GitHub, which has no IPv6 address. Copy the Linux build of rexctl to the machine yourself, such as with `scp` from a machine with IPv4 and IPv6, and run `rexctl voice join` with it. Before you run `rexctl upgrade` for a new release, copy that release's rexctl there the same way.
+
+### Callers with only IPv4
+
+Without a TURN server, a caller with only IPv4 can't join a call on a server with only IPv6. With a TURN server you run, they can when all of the following is in place.
+
+- **Signalling.** The browser or app opens a WebSocket to the endpoint before any audio flows, and a TURN server can't help with that. An `A` record for the hostname has to point at a machine with IPv4 that you run, and that machine has to forward TCP ports 80 and 443 to the voice machine without ending TLS, such as with the nginx `stream` module. rexctl accepts such an `A` record and says what the machine has to do. Without it, the caller's WebSocket fails and the call doesn't start.
+- **Media.** A TURN server with IPv4 and IPv6, set up as in [TURN servers](#turn-servers). The caller connects to it over IPv4, and it relays to the voice server over IPv6. For that the TURN server has to hand the caller an IPv6 relay address. A client can ask for one ([RFC 6156](https://www.rfc-editor.org/rfc/rfc6156)), but browsers don't. coturn then hands out IPv4 relay addresses, its default, and the call doesn't connect. Set `allocation-default-address-family="ipv6"` in coturn. Callers then get IPv6 relay addresses, and audio and video flow both ways, with the caller connected to coturn over UDP or, when UDP is blocked, over TCP.
+
+With `allocation-default-address-family="ipv6"`, the TURN server gives no useful relay for a voice server with only IPv4. Callers who need the TURN server can't connect to such a server with that setting. Your instance gives every voice server the same list of TURN servers. Use the setting only when every voice server of your instance has IPv6.
+
+`rexctl voice test <id>` on a Fluxer machine with IPv4 tries **IPv4 through TURN** for a server with only IPv6, when your instance has TURN servers. It opens the WebSocket over IPv4, which goes to the machine the `A` record points at, and connects media only through the TURN servers the voice server gives clients over UDP and TCP, which it connects to over IPv4. Like a browser, it asks for no address family, so it passes only when the TURN server hands out IPv6 relay addresses. When the instance has no TURN servers, the test skips this.
+
+### Machines that joined before
+
+A voice machine that joined before rexctl supported IPv6 has a voice network without IPv6, and Docker can't add IPv6 to it. Its servers offer only IPv4, and a new `rexctl voice join` there says so. To offer IPv6, remove the servers with `rexctl voice remove --all` and join again with new tokens.
+
+## TURN servers
+
+A TURN server relays call media for callers who can't connect to a voice server directly. rexctl doesn't install or run one. When you run your own, give it to your instance on the Fluxer machine.
+
+```sh
+rexctl config set FLUXER_LIVEKIT_TURN_SERVERS '[{"host":"turn.example.com","port":3478,"protocol":"udp","secret":"a-long-random-secret"},{"host":"turn.example.com","port":3478,"protocol":"tcp","secret":"a-long-random-secret"}]'
+```
+
+With `secret`, LiveKit gives each participant short-lived credentials in the form coturn checks with `use-auth-secret`. Set the same secret as `static-auth-secret` in coturn. `ttl` sets how many seconds the credentials last, as a whole number from 1. An entry can have `username` and `credential` in place of `secret`. Every text field has to be filled in. `host` has to be a hostname or an IPv4 address, and field names are lower case. The API doesn't start with a list it can't read, and `rexctl config set` refuses such a list before it changes anything.
+
+Voice servers that rexctl manages give the list to clients that join a call on them.
+
+- The bundled server gets it when Fluxer restarts with the new setting.
+- Servers from `rexctl voice add` get it when you change the setting with `rexctl config set`. rexctl restarts them one at a time, as an upgrade does.
+- Servers from `rexctl voice join` get it when they join, and again on each `rexctl upgrade` in their voice folder. When the instance runs an older release than the rexctl in that folder, the upgrade leaves the servers as they are. A server that uses the edge of the Fluxer instance on the same machine also gets it when you change the setting, and when you upgrade that instance to a new release. A changed list restarts them the same way. The voice machine keeps the list, with the secret, in `voice/<id>/.env`.
+
+On [Kubernetes](/operator/kubernetes/), the chart doesn't pass the setting to the API. Servers that join an instance there get the list only when you put `FLUXER_LIVEKIT_TURN_SERVERS` in `api.env` in your values.
+
+For a server you run by hand or added in the admin panel, copy the same entries into `rtc.turn_servers` in its LiveKit configuration. With `voice.compose.yml`, set `FLUXER_LIVEKIT_TURN_SERVERS` in its settings file.
## Ports and firewalls
@@ -162,8 +221,7 @@ Behind a router or another NAT, forward each port to the same port number on the
## Networks a voice server can't serve
- **Shared address NAT (CGNAT, 100.64.0.0/10).** A machine with an address from 100.64.0.0/10 on its main network usually can't take incoming calls, and rexctl stops. Some providers use that range for private networks behind 1:1 NAT. When the machine has a public IPv4 address of its own, pass it with `--ip`. CGNAT behind a home router doesn't show on the machine. Run `rexctl voice test <id>` on the Fluxer machine to find it.
-- **IPv6 only.** Voice servers need a public IPv4 address.
-- **Networks that allow only port 443.** Some office and school networks block everything but HTTPS. Calls from there need TURN over TLS on port 443, which rexctl doesn't set up. See LiveKit's guide to [TURN](https://docs.livekit.io/transport/self-hosting/deployment/#improving-connectivity-with-turn).
+- **Networks that allow only port 443.** Some office and school networks block everything but HTTPS. Calls from there need TURN over TLS on port 443, which rexctl doesn't set up. Run your own and add it as in [TURN servers](#turn-servers), with `"protocol":"tls"` and `"port":443`.
## Machines with something else on ports 80 and 443
@@ -257,7 +315,7 @@ rexctl doctor
`rexctl voice list` on the Fluxer machine shows every server of your instance with its health, and marks the ones that run on that machine. On a voice machine it shows the servers there.
-`rexctl voice test` joins a throwaway room and reports whether UDP and TCP connect. A test on the machine that runs the server can't see your provider's firewall or your router. On the Fluxer machine, `rexctl voice test <id>` tests a server on another machine from outside its network, with a token your instance signs. When the server rejects that token, your instance has another secret for it than the server has.
+`rexctl voice test` joins a throwaway room and reports whether UDP and TCP connect, over IPv4 and IPv6 when the server and the machine running the test both have them. When the test machine lacks a family the server has, it says so. A test on the machine that runs the server can't see your provider's firewall or your router. On the Fluxer machine, `rexctl voice test <id>` tests a server on another machine from outside its network, with a token your instance signs. When the server rejects that token, your instance has another secret for it than the server has.
## Upgrade
diff --git a/fluxer_rexctl/cmd/config.go b/fluxer_rexctl/cmd/config.go
index 3a78a7b02..5cb412e09 100644
--- a/fluxer_rexctl/cmd/config.go
+++ b/fluxer_rexctl/cmd/config.go
@@ -607,7 +607,7 @@ func deploymentDone(name string, value *string) string {
case settings.SecretName(name) || name == settings.StorageSecret:
return fmt.Sprintf("Saved %s.", name)
}
- return fmt.Sprintf("Set %s to %s.", name, clip(settings.Mask(settings.Key{}, *value)))
+ return fmt.Sprintf("Set %s to %s.", name, clip(settings.Mask(settings.Key{Name: name}, *value)))
}
type adminChange struct {
@@ -792,6 +792,9 @@ func applySettings(ctx context.Context, app *App, inst *instance.Instance, e *en
if _, ok := changes[settings.VoicePublicIP]; ok && !r.change.Unchanged {
moveVoicePublicIP(ctx, app, inst, e, r.change.Applied)
}
+ if _, ok := changes[settings.TurnServersVar]; ok && r.change.Applied && !r.change.Unchanged && len(inst.State.Voice) > 0 {
+ upgradeLocalVoiceServers(ctx, app, inst, e)
+ }
if _, ok := changes[settings.VoiceBundled]; ok && r.change.Applied && !r.change.Unchanged {
restoreBundledVoiceServer(ctx, app, inst)
}
@@ -899,7 +902,7 @@ func newConfigRenderCmd(app *App) *cobra.Command {
if generated || settings.SecretName(name) {
s.Env[name] = settings.Masked
} else {
- s.Env[name] = settings.Mask(settings.Key{}, value)
+ s.Env[name] = settings.Mask(settings.Key{Name: name}, value)
}
}
var e engine.Engine
diff --git a/fluxer_rexctl/cmd/voice.go b/fluxer_rexctl/cmd/voice.go
index f92929fcf..88f731744 100644
--- a/fluxer_rexctl/cmd/voice.go
+++ b/fluxer_rexctl/cmd/voice.go
@@ -20,6 +20,7 @@ import (
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/voice"
)
@@ -373,6 +374,7 @@ func showVoiceStatus(ctx context.Context, app *App, e *engine.Engine, inst *inst
{"Endpoint", srv.Endpoint + ", " + reach},
{"Container", container},
{"Ports", fmt.Sprintf("%d/tcp, %d/udp", srv.TCPPort, srv.UDPPort)},
+ {"Addresses", addressesText(srv)},
{"Certificate", cert},
{"Calls", load},
{"LiveKit", srv.Image},
@@ -440,7 +442,7 @@ func newVoiceTestCmd(app *App) *cobra.Command {
ok := true
for _, srv := range servers {
app.UI.Info("Testing %s at %s", srv.ID, srv.Endpoint)
- results := runTransportTests(ctx, srv.Endpoint, func() (string, error) {
+ results := runTransportTests(ctx, srv.Endpoint, serverPaths(srv), func() (string, error) {
return voice.TestToken(srv.Key, srv.Secret, voice.TestRoom(), time.Now()), nil
}, !owner.State.IsVoice())
ok = reportTransports(app, results, true) && ok
@@ -457,37 +459,58 @@ func newVoiceTestCmd(app *App) *cobra.Command {
}
func testRemoteVoiceServer(c *cobra.Command, app *App, id string) error {
- return adminRead(c, app, func(ctx context.Context, api *adminapi.Client, _ *instance.Instance) error {
+ return adminRead(c, app, func(ctx context.Context, api *adminapi.Client, inst *instance.Instance) error {
regions, err := api.VoiceRegions(ctx)
if err != nil {
return err
}
region := ""
+ server := voice.FamilyIPv4
for _, r := range regions {
for _, s := range r.Servers {
if s.ServerId == id {
region = r.Id
+ if f := voice.FamilyOf(stringOf(s.PublicIpv4), stringOf(s.PublicIpv6)); f != voice.FamilyNone {
+ server = f
+ }
}
}
}
if region == "" {
return ui.Refused(fmt.Sprintf("Your instance has no voice server called %s.", id), "Run rexctl voice list to see the servers.")
}
+ tester := voice.FamilyOf(voice.DefaultRouteIPv4(), globalOnly(voice.DefaultRouteIPv6()))
+ paths := withoutUnsetTurn(app, inst, id, remotePaths(server, tester))
+ for _, fam := range []string{voice.FamilyIPv4, voice.FamilyIPv6} {
+ if (server == fam || server == voice.FamilyDual) && tester != fam && tester != voice.FamilyDual {
+ app.UI.Info("This machine has no %s, and rexctl can't test %s over %s from here.", familyName(fam), id, familyName(fam))
+ }
+ }
+ if len(paths) == 0 {
+ return ui.Refused(fmt.Sprintf("This machine and %s have no address family in common.", id), "Run the test on a machine with "+familyName(server)+".")
+ }
var endpoint string
var results []transportResult
- for _, t := range []voice.Transport{voice.TransportUDP, voice.TransportTCP} {
+ for _, p := range paths {
tok, err := api.VoiceTestToken(ctx, region, id)
if err == nil {
endpoint = tok.Endpoint
- err = voice.TestTransport(ctx, tok.Endpoint, tok.Token, t, false, 20*time.Second)
+ err = voice.TestTransport(ctx, tok.Endpoint, tok.Token, p, false, 20*time.Second)
}
- results = append(results, transportResult{Transport: t, Err: err})
+ results = append(results, transportResult{Path: p, Err: err})
}
app.UI.Info("Tested %s at %s from this machine.", id, endpoint)
if !reportTransports(app, results, false) {
- if slices.ContainsFunc(results, func(r transportResult) bool { return errors.Is(r.Err, voice.ErrTokenRejected) }) {
+ switch {
+ case slices.ContainsFunc(results, func(r transportResult) bool { return errors.Is(r.Err, voice.ErrTokenRejected) }):
app.UI.Info("%s rejected a token signed with the API secret your instance has for it. Put the server's own secret back in the admin panel. It's FLUXER_VOICE_API_SECRET in voice/%s/.env in the rexctl folder on the machine that runs it.", id, id)
- } else {
+ case slices.ContainsFunc(results, func(r transportResult) bool { return r.Path.Relay && errors.Is(r.Err, voice.ErrSignalling) }):
+ app.UI.Info("rexctl couldn't open the signalling connection to %s over IPv4. Callers with only IPv4 need an A record for its hostname at a machine that forwards ports 80 and 443 to it. See the voice servers guide.", id)
+ case slices.ContainsFunc(results, func(r transportResult) bool {
+ return r.Path.Relay && r.Err != nil && !errors.Is(r.Err, voice.ErrNoTurn)
+ }):
+ app.UI.Info("Media through your TURN server didn't connect. IPv4 through TURN needs a TURN server that hands out IPv6 relay addresses. See the voice servers guide.")
+ default:
app.UI.Info("Open the server's TCP and UDP ports in the firewall of its provider and on the machine itself.")
}
app.SetExit(ui.ExitFailed)
@@ -496,6 +519,43 @@ func testRemoteVoiceServer(c *cobra.Command, app *App, id string) error {
})
}
+func remotePaths(server, tester string) []voice.MediaPath {
+ paths := voice.MediaPaths(server, tester)
+ if server == voice.FamilyIPv6 && (tester == voice.FamilyIPv4 || tester == voice.FamilyDual) {
+ paths = append(paths, voice.MediaPath{Transport: voice.TransportUDP, Family: voice.FamilyIPv4, Relay: true})
+ }
+ return paths
+}
+
+func withoutUnsetTurn(app *App, inst *instance.Instance, id string, paths []voice.MediaPath) []voice.MediaPath {
+ relay := func(p voice.MediaPath) bool { return p.Relay }
+ if inst == nil || inst.State == nil || inst.State.IsVoice() || !slices.ContainsFunc(paths, relay) {
+ return paths
+ }
+ if list, err := settings.ParseTurnServers(inst.Setting(settings.TurnServersVar)); err != nil || len(list) > 0 {
+ return paths
+ }
+ app.UI.Info("%s offers only IPv6, and your instance gives clients no TURN server. Callers with only IPv4 can't join calls on it, and rexctl doesn't test IPv4 through TURN.", id)
+ return slices.DeleteFunc(paths, relay)
+}
+
+func familyName(f string) string {
+ switch f {
+ case voice.FamilyIPv6:
+ return "IPv6"
+ case voice.FamilyDual:
+ return "IPv4 and IPv6"
+ }
+ return "IPv4"
+}
+
+func globalOnly(ip string) string {
+ if voice.GlobalIPv6(ip) {
+ return ip
+ }
+ return ""
+}
+
func newVoiceHostnameCmd(app *App) *cobra.Command {
return &cobra.Command{
Use: "hostname <id> <host>",
@@ -524,9 +584,9 @@ func newVoiceHostnameCmd(app *App) *cobra.Command {
if err != nil {
return voice.HostnameMissing
}
- return voice.CheckHostname(answer, srv.NodeIP, voice.InterfaceAddresses())
+ return voice.CheckHostname(answer, srv.NodeIP, srv.NodeIPv6, voice.InterfaceAddresses())
}
- if !waitForHostname(ctx, app, name, srv.NodeIP, check, false, true) {
+ if !waitForHostname(ctx, app, name, voice.Reachability{PublicIPv4: srv.NodeIP, PublicIPv6: srv.NodeIPv6}, check, false, true) {
return ui.Refused(fmt.Sprintf("%s doesn't point at this machine yet.", name), "Fix the DNS record, then run the same command again.")
}
e, err := app.Engine(ctx, inst)
@@ -816,3 +876,22 @@ func voiceCommandAllowed(path string) bool {
}
return slices.Contains([]string{"voice", "uninstall", "upgrade", "auto-upgrade", "doctor", "status", "version", "docs", "use", "help", "completion"}, parts[1])
}
+
+func stringOf(p *string) string {
+ if p == nil {
+ return ""
+ }
+ return *p
+}
+
+func addressesText(srv *instance.VoiceServer) string {
+ switch {
+ case srv.NodeIP != "" && srv.NodeIPv6 != "":
+ return "IPv4 " + srv.NodeIP + ", IPv6 " + srv.NodeIPv6
+ case srv.NodeIPv6 != "":
+ return "IPv6 only, " + srv.NodeIPv6
+ case srv.NodeIP != "":
+ return "IPv4 " + srv.NodeIP
+ }
+ return "found by LiveKit with STUN"
+}
diff --git a/fluxer_rexctl/cmd/voice_add.go b/fluxer_rexctl/cmd/voice_add.go
index 95f43795d..b45d060d8 100644
--- a/fluxer_rexctl/cmd/voice_add.go
+++ b/fluxer_rexctl/cmd/voice_add.go
@@ -3,12 +3,14 @@
package cmd
import (
+ "cmp"
"context"
"fmt"
"net/netip"
"os"
"path/filepath"
"slices"
+ "strconv"
"strings"
"time"
@@ -33,6 +35,8 @@ type voiceFlags struct {
HasCoords bool
Hostname string
IP string
+ IPv6 string
+ NoIPv6 bool
TCPPort int
UDPPort int
SoftLimit int
@@ -58,6 +62,8 @@ func addVoiceOverrideFlags(c *cobra.Command, f *voiceFlags) {
fl.Float64Var(&f.Lat, "lat", 0, "latitude of the server")
fl.Float64Var(&f.Long, "long", 0, "longitude of the server")
fl.StringVar(&f.IP, "ip", "", "public IPv4 address LiveKit gives to clients, also the address the ports bind to when it's on this machine")
+ fl.StringVar(&f.IPv6, "ipv6", "", "public IPv6 address LiveKit gives to clients")
+ fl.BoolVar(&f.NoIPv6, "no-ipv6", false, "give clients only the IPv4 address, even when this machine has IPv6")
fl.IntVar(&f.TCPPort, "tcp-port", 0, "TCP port for media")
fl.IntVar(&f.UDPPort, "udp-port", 0, "UDP port for media")
fl.IntVar(&f.SoftLimit, "soft-limit", 0, "connections above which placement prefers another server")
@@ -95,9 +101,18 @@ func validateVoiceFlags(c *cobra.Command, f *voiceFlags) error {
if f.IP != "" {
ip, err := netip.ParseAddr(f.IP)
if err != nil || !ip.Is4() {
- return ui.Usage(fmt.Sprintf("Pass --ip as an IPv4 address. %s isn't one.", f.IP))
+ return ui.Usage(fmt.Sprintf("Pass --ip as an IPv4 address. %s isn't one. Pass an IPv6 address with --ipv6.", f.IP))
}
}
+ if f.IPv6 != "" {
+ if f.NoIPv6 {
+ return ui.Usage("Pass --ipv6 or --no-ipv6, not both.")
+ }
+ if !voice.GlobalIPv6(f.IPv6) {
+ return ui.Usage(fmt.Sprintf("Pass --ipv6 as a public IPv6 address. %s isn't one.", f.IPv6))
+ }
+ f.IPv6 = netip.MustParseAddr(f.IPv6).String()
+ }
for _, p := range []int{f.TCPPort, f.UDPPort, f.HTTPPort} {
if p < 0 || p > 65535 {
return ui.Usage("Pass a port from 1 to 65535.")
@@ -289,6 +304,13 @@ func planVoiceAdd(ctx context.Context, app *App, e *engine.Engine, inst *instanc
publicIP, _ = host.PublicIPv4(pctx)
cancel()
}
+ nodeIPv6, err := addIPv6(ctx, app, e, inst, publicIP, f)
+ if err != nil {
+ return nil, err
+ }
+ if nodeIPv6 != "" && nodeIP == "" {
+ nodeIP = publicIP
+ }
memory := f.Memory
if memory == "" {
memory = strings.TrimSpace(inst.Setting("FLUXER_LIVEKIT_MEMORY_LIMIT"))
@@ -348,6 +370,7 @@ func planVoiceAdd(ctx context.Context, app *App, e *engine.Engine, inst *instanc
TCPPort: tcp,
UDPPort: udp,
NodeIP: nodeIP,
+ NodeIPv6: nodeIPv6,
IPPinned: f.IP != "",
BindIP: bindIP,
Image: image,
@@ -366,6 +389,35 @@ func planVoiceAdd(ctx context.Context, app *App, e *engine.Engine, inst *instanc
return plans, nil
}
+func addIPv6(ctx context.Context, app *App, e *engine.Engine, inst *instance.Instance, publicIP string, f *voiceFlags) (string, error) {
+ v6 := detectIPv6(ctx, f)
+ if v6 == "" {
+ return "", nil
+ }
+ on, _ := strconv.ParseBool(strings.TrimSpace(inst.State.Settings[settings.IPv6]))
+ _, has6, err := e.NetworkIPv6(ctx, inst.Project()+"_fluxer")
+ if err != nil {
+ return "", engineFailure(err)
+ }
+ why, fix := "", ""
+ switch {
+ case !e.IPv6Voice():
+ why, fix = ipv6EngineText(e), fmt.Sprintf("Upgrade Docker to %s or later.", engine.MinDockerIPv6)
+ case !on || !has6:
+ why, fix = "network.ipv6 is off", "Run rexctl config set network.ipv6 true first."
+ case bindAddress(f.IP, voice.InterfaceAddresses()) != "":
+ why, fix = "--ip binds the ports to one IPv4 address", "Leave out --ip."
+ }
+ if why == "" {
+ return v6, nil
+ }
+ if publicIP == "" {
+ return "", ui.Refused("This machine has only IPv6, and "+why+".", fix)
+ }
+ app.UI.Info("This machine has IPv6 too. The new servers offer only IPv4, because %s.", why)
+ return "", nil
+}
+
func showVoiceAddSummary(app *App, inst *instance.Instance, region string, plans []plannedVoice, f *voiceFlags) {
u := app.UI
hostMem, _ := host.Hardware()
@@ -387,6 +439,7 @@ func showVoiceAddSummary(app *App, inst *instance.Instance, region string, plans
{"Region", region},
{"Endpoint", s.Endpoint},
{"Public IPv4", ip},
+ {"Public IPv6", orNone(s.NodeIPv6)},
{"Ports", fmt.Sprintf("%d/tcp, %d/udp", s.TCPPort, s.UDPPort)},
{"LiveKit", s.Image},
{"Memory limit", fmt.Sprintf("%s of %s", s.Memory, voice.HumanBytes(hostMem))},
@@ -472,6 +525,13 @@ func addOneVoiceServer(ctx context.Context, app *App, api *adminapi.Client, e *e
lat, long := float32(f.Lat), float32(f.Long)
body.Latitude, body.Longitude = &lat, &long
}
+ if v4 := cmp.Or(srv.NodeIP, plan.publicIP); v4 != "" {
+ body.PublicIpv4 = &v4
+ }
+ if srv.NodeIPv6 != "" {
+ v6 := srv.NodeIPv6
+ body.PublicIpv6 = &v6
+ }
_, err = api.CreateVoiceServer(ctx, srv.Region, body)
if err != nil {
return ui.Wrap(adminapi.Explain(err), fmt.Sprintf("Couldn't register %s with your instance.", srv.ID), undo)
@@ -496,7 +556,7 @@ func addOneVoiceServer(ctx context.Context, app *App, api *adminapi.Client, e *e
return ui.Wrap(adminapi.Explain(err), fmt.Sprintf("%s runs, and it's still draining.", srv.ID), fmt.Sprintf("Clear Draining for %s in the admin panel.", srv.ID))
}
app.UI.OK("Added voice server %s at %s.", srv.ID, srv.Endpoint)
- results := runTransportTests(ctx, srv.Endpoint, func() (string, error) {
+ results := runTransportTests(ctx, srv.Endpoint, serverPaths(saved), func() (string, error) {
return voice.TestToken(srv.Key, srv.Secret, voice.TestRoom(), time.Now()), nil
}, true)
reportTransports(app, results, true)
diff --git a/fluxer_rexctl/cmd/voice_join.go b/fluxer_rexctl/cmd/voice_join.go
index e79fe163a..d9d743a95 100644
--- a/fluxer_rexctl/cmd/voice_join.go
+++ b/fluxer_rexctl/cmd/voice_join.go
@@ -8,7 +8,6 @@ import (
"errors"
"fmt"
"io"
- "net"
"net/http"
"net/url"
"os"
@@ -25,6 +24,7 @@ import (
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/voice"
)
@@ -48,7 +48,8 @@ func newVoiceJoinCmd(app *App) *cobra.Command {
Short: "Install a voice server on this machine and connect it to an instance",
Long: "Install a standalone LiveKit voice server on this machine and register it with the Fluxer instance at <domain>. " +
"Get the token with rexctl voice token on the Fluxer machine, or with Add a voice server in the admin panel. " +
- "The token works once. rexctl also reads it from " + voiceTokenEnv + " or, with --token-stdin, from standard input.",
+ "The token works once. rexctl also reads it from " + voiceTokenEnv + " or, with --token-stdin, from standard input. " +
+ "The server offers IPv4 and IPv6 when the machine has both. On a machine with only IPv6, pass --hostname with an AAAA record that points here.",
Args: func(c *cobra.Command, args []string) error {
if len(args) == 0 {
return ui.Usage("Pass the domain of your Fluxer instance.")
@@ -164,6 +165,7 @@ type joinPlan struct {
edgeInst *instance.Instance
newEdge bool
firewall host.Firewall
+ netIPv6 bool
hostMem uint64
cpus int
image string
@@ -258,17 +260,18 @@ func planJoin(ctx context.Context, app *App, client *voice.Client, e *engine.Eng
if f.IP != "" {
publicIP = f.IP
}
- if publicIP == "" {
- return ui.Refused("This machine has no public IPv4 address that rexctl can find.", "Voice servers need IPv4. Pass --ip if the address is known.")
+ publicIPv6 := detectIPv6(ctx, f)
+ if publicIP == "" && publicIPv6 == "" {
+ return ui.Refused("This machine has no public IPv4 or IPv6 address that rexctl can find.", "Pass --ip or --ipv6 if the address is known.")
}
- reach, err := assessJoin(publicIP, f.IP, voice.InterfaceAddresses(), voice.DefaultRouteIPv4())
+ reach, err := assessJoin(app, publicIP, publicIPv6, f.IP, voice.InterfaceAddresses(), voice.DefaultRouteIPv4())
if err != nil {
return err
}
plan.reach = reach
plan.hostMem, plan.cpus = host.Hardware()
plan.preview, err = client.Preview(ctx, plan.disc.APIPublic, token, voice.PreviewRequest{
- PublicIPv4: publicIP, RegionID: f.Region, CPUCount: plan.cpus, MemoryBytes: plan.hostMem, RexctlVersion: app.Version,
+ PublicIPv4: reach.PublicIPv4, PublicIPv6: reach.PublicIPv6, RegionID: f.Region, CPUCount: plan.cpus, MemoryBytes: plan.hostMem, RexctlVersion: app.Version,
})
if err != nil {
return joinError(err, plan.domain, "")
@@ -278,6 +281,13 @@ func planJoin(ctx context.Context, app *App, client *voice.Client, e *engine.Eng
if err := planEdge(ctx, app, e, inst, plan, f); err != nil {
return err
}
+ network := voice.MachineNetwork
+ if plan.edgeInst != nil {
+ network = plan.edgeInst.Project() + "_fluxer"
+ }
+ if err := planJoinIPv6(ctx, app, e, inst, plan, network, f); err != nil {
+ return err
+ }
id, err := chooseJoinID(plan.preview, f.ID, inst, voiceIDsInUse(ctx, e, inst, voice.JoinedProject("")))
if err != nil {
return err
@@ -317,10 +327,6 @@ func planJoin(ctx context.Context, app *App, client *voice.Client, e *engine.Eng
soft = voice.SoftLimit(plan.cpus)
}
}
- network := voice.MachineNetwork
- if plan.edgeInst != nil {
- network = plan.edgeInst.Project() + "_fluxer"
- }
httpPort, httpBind := 0, ""
if f.NoEdge {
httpPort = f.HTTPPort
@@ -344,7 +350,8 @@ func planJoin(ctx context.Context, app *App, client *voice.Client, e *engine.Eng
UDPPort: udp,
HTTPPort: httpPort,
HTTPBind: httpBind,
- NodeIP: publicIP,
+ NodeIP: plan.reach.PublicIPv4,
+ NodeIPv6: plan.reach.PublicIPv6,
BindIP: bindAddress(f.IP, voice.InterfaceAddresses()),
Image: plan.image,
Pinned: f.Image != "",
@@ -356,6 +363,7 @@ func planJoin(ctx context.Context, app *App, client *voice.Client, e *engine.Eng
Instance: plan.domain,
Edge: plan.edge,
Joined: true,
+ Turn: settings.TurnServersValue(plan.preview.TurnServers),
}
if f.NoEdge {
plan.srv.Endpoint = strings.TrimRight(f.Endpoint, "/")
@@ -394,17 +402,71 @@ func chooseJoinID(preview *voice.Preview, flagID string, inst *instance.Instance
return voice.NextID(preview.Region.ID, taken), nil
}
-func assessJoin(publicIP, flagIP string, local []string, routeIP string) (voice.Reachability, error) {
- reach := voice.Assess(publicIP, local, routeIP)
- if reach.CGNAT && flagIP == "" {
- return reach, ui.Refused("This machine is behind CGNAT, a shared address that can't take incoming calls.", "Pass --ip with the machine's public address if it has one of its own.")
- }
+func assessJoin(app *App, publicIP, publicIPv6, flagIP string, local []string, routeIP string) (voice.Reachability, error) {
+ reach := voice.Assess(publicIP, publicIPv6, local, routeIP)
if flagIP != "" {
reach.CGNAT = false
}
+ if reach.CGNAT && reach.PublicIPv6 != "" {
+ app.UI.Info("This machine is behind CGNAT on IPv4, a shared address that can't take incoming calls. The server uses IPv6 only.")
+ reach.PublicIPv4, reach.BehindNAT, reach.CGNAT = "", false, false
+ }
+ if reach.CGNAT {
+ return reach, ui.Refused("This machine is behind CGNAT, a shared address that can't take incoming calls.", "Pass --ip with the machine's public address if it has one of its own.")
+ }
return reach, nil
}
+func detectIPv6(ctx context.Context, f *voiceFlags) string {
+ if f.NoIPv6 {
+ return ""
+ }
+ if f.IPv6 != "" {
+ return f.IPv6
+ }
+ pctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ seen, _ := host.PublicIPv6(pctx)
+ cancel()
+ return voice.MachineIPv6(seen)
+}
+
+func ipv6EngineText(e *engine.Engine) string {
+ switch {
+ case e.Kind != engine.Docker:
+ return fmt.Sprintf("voice servers on IPv6 need Docker %s or later, and this machine runs %s", engine.MinDockerIPv6, e.Kind)
+ case e.Rootless:
+ return "voice servers on IPv6 need rootful Docker, and this machine runs Docker rootless"
+ }
+ return fmt.Sprintf("voice servers on IPv6 need Docker %s or later, and this machine runs Docker %s", engine.MinDockerIPv6, e.Version)
+}
+
+func planJoinIPv6(ctx context.Context, app *App, e *engine.Engine, inst *instance.Instance, plan *joinPlan, network string, f *voiceFlags) error {
+ exists, has6, err := e.NetworkIPv6(ctx, network)
+ if err != nil {
+ return engineFailure(err)
+ }
+ why, fix := "", ""
+ switch {
+ case !e.IPv6Voice():
+ why, fix = ipv6EngineText(e), fmt.Sprintf("Upgrade Docker to %s or later.", engine.MinDockerIPv6)
+ case plan.edgeInst != nil && !has6:
+ why, fix = "the network of the Fluxer instance on this machine has no IPv6", "On this machine, run rexctl config set network.ipv6 true."
+ case exists && !has6, !exists && plan.edge == voice.EdgeOwn && !plan.newEdge && inst.State.VoiceEdge != nil && !inst.State.VoiceEdge.IPv6:
+ why, fix = "the voice network on this machine was made without IPv6", "Remove the voice servers on this machine with rexctl voice remove --all, then join again."
+ case bindAddress(f.IP, voice.InterfaceAddresses()) != "":
+ why, fix = "--ip binds the ports to one IPv4 address", "Leave out --ip."
+ }
+ if plan.reach.PublicIPv6 != "" && why != "" {
+ if plan.reach.PublicIPv4 == "" {
+ return ui.Refused("This machine has only IPv6, and "+why+".", fix)
+ }
+ app.UI.Info("This machine has IPv6 too. The server offers only IPv4, because %s.", why)
+ plan.reach.PublicIPv6 = ""
+ }
+ plan.netIPv6 = plan.reach.PublicIPv6 != ""
+ return nil
+}
+
func pickHTTPPort(taken map[host.Port]bool, tcp int, free func(int, string) bool) int {
for n := 7880; n < 7980; n++ {
if n != tcp && !taken[host.Port{Number: n, Proto: "tcp"}] && free(n, "tcp") {
@@ -507,29 +569,37 @@ func chooseAddress(ctx context.Context, app *App, plan *joinPlan, id string, f *
if name == "" {
name = pinned
}
+ only6 := plan.reach.PublicIPv4 == ""
resolve := hostnameLookup()
check := func(host string) voice.HostnameCheck {
answer, err := resolve(ctx, host)
if err != nil {
return voice.HostnameMissing
}
- return voice.CheckHostname(answer, plan.reach.PublicIPv4, voice.InterfaceAddresses())
+ return voice.CheckHostname(answer, plan.reach.PublicIPv4, plan.reach.PublicIPv6, voice.InterfaceAddresses())
}
- if name == "" && plan.preview.SuggestedHostname != "" && check(plan.preview.SuggestedHostname) == voice.HostnameOK {
+ if name == "" && plan.preview.SuggestedHostname != "" && check(plan.preview.SuggestedHostname).Usable() {
name = plan.preview.SuggestedHostname
}
+ if name == "" && only6 {
+ return ui.Refused("This machine has only IPv6, and a voice server on IPv6 needs a hostname.", fmt.Sprintf("Point a hostname at %s with an AAAA record, then pass it with --hostname.", plan.reach.PublicIPv6))
+ }
if name == "" {
plan.address, plan.ipCert = plan.reach.PublicIPv4, true
return nil
}
- if pinned != "" {
- if waitForHostname(ctx, app, name, plan.reach.PublicIPv4, check, f.DryRun, true) || f.DryRun {
+ if pinned != "" || only6 {
+ if waitForHostname(ctx, app, name, plan.reach, check, f.DryRun, true) || f.DryRun {
plan.address = name
return nil
}
- return ui.Refused(fmt.Sprintf("The token needs the hostname %s, and it doesn't point at this machine yet.", name), "Point it at "+plan.reach.PublicIPv4+" with DNS only, then run the same command again.")
+ why := fmt.Sprintf("%s doesn't point at this machine yet.", name)
+ if pinned != "" {
+ why = fmt.Sprintf("The token needs the hostname %s, and it doesn't point at this machine yet.", name)
+ }
+ return ui.Refused(why, "Point it at "+addressText(plan.reach)+" with DNS only, then run the same command again.")
}
- if waitForHostname(ctx, app, name, plan.reach.PublicIPv4, check, f.DryRun, false) {
+ if waitForHostname(ctx, app, name, plan.reach, check, f.DryRun, false) {
plan.address = name
return nil
}
@@ -538,9 +608,14 @@ func chooseAddress(ctx context.Context, app *App, plan *joinPlan, id string, f *
return nil
}
-func waitForHostname(ctx context.Context, app *App, name, ipv4 string, check func(string) voice.HostnameCheck, dryRun, always bool) bool {
+func addressText(addrs voice.Reachability) string {
+ return ui.JoinAnd(slices.DeleteFunc([]string{addrs.PublicIPv4, addrs.PublicIPv6}, func(s string) bool { return s == "" }))
+}
+
+func waitForHostname(ctx context.Context, app *App, name string, addrs voice.Reachability, check func(string) voice.HostnameCheck, dryRun, always bool) bool {
result := check(name)
- if result == voice.HostnameOK {
+ if result.Usable() {
+ hostnameNote(app, name, result)
return true
}
switch result {
@@ -549,11 +624,16 @@ func waitForHostname(ctx context.Context, app *App, name, ipv4 string, check fun
case voice.HostnameIPv6Elsewhere:
app.UI.Warn(fmt.Sprintf("%s has an AAAA record that points somewhere else.", name), "Remove that record. Let's Encrypt checks IPv6 first.")
default:
- app.UI.Info("%s doesn't point at this machine yet. Add this record at your DNS provider:", name)
+ app.UI.Info("%s doesn't point at this machine yet. Add these records at your DNS provider:", name)
app.UI.Info("")
- app.UI.Info(" %s. A %s", name, ipv4)
+ if addrs.PublicIPv4 != "" {
+ app.UI.Info(" %s. A %s", name, addrs.PublicIPv4)
+ }
+ if addrs.PublicIPv6 != "" {
+ app.UI.Info(" %s. AAAA %s", name, addrs.PublicIPv6)
+ }
app.UI.Info("")
- app.UI.Info("On Cloudflare, set the record to DNS only.")
+ app.UI.Info("On Cloudflare, set the records to DNS only.")
}
if dryRun || !always && (app.UI.Yes() || !app.UI.Interactive()) {
return false
@@ -570,14 +650,26 @@ func waitForHostname(ctx context.Context, app *App, name, ipv4 string, check fun
return false
case <-time.After(15 * time.Second):
}
- if check(name) == voice.HostnameOK {
+ if result := check(name); result.Usable() {
app.UI.OK("%s points at this machine.", name)
+ hostnameNote(app, name, result)
return true
}
}
return false
}
+func hostnameNote(app *App, name string, result voice.HostnameCheck) {
+ switch result {
+ case voice.HostnameIPv4Front:
+ app.UI.Info("%s also has an A record for another machine. That machine has to forward ports 80 and 443 here for callers with only IPv4.", name)
+ case voice.HostnameNoA:
+ app.UI.Warn(fmt.Sprintf("%s has no A record.", name), "Callers with only IPv4 can't connect to this server until you add one that points at this machine.")
+ case voice.HostnameNoAAAA:
+ app.UI.Warn(fmt.Sprintf("%s has no AAAA record.", name), "Callers with only IPv6 can't connect to this server until you add one that points at this machine.")
+ }
+}
+
func joinRegionText(p *voice.Preview, requested string) string {
region := p.Region.ID
if p.Region.Name != "" {
@@ -630,7 +722,7 @@ func showJoinSummary(app *App, plan *joinPlan, f *voiceFlags) {
ports = append(ports, "80/tcp", "443/tcp")
}
fw := joinFirewallText(plan.firewall, len(ports), f.NoFirewall)
- ip := s.NodeIP
+ ip := orNone(s.NodeIP)
if plan.reach.BehindNAT {
ip += ", behind NAT. Forward each port to the same port number on this machine."
}
@@ -640,6 +732,7 @@ func showJoinSummary(app *App, plan *joinPlan, f *voiceFlags) {
{"Endpoint", s.Endpoint},
{"Certificate", cert},
{"Public IPv4", ip},
+ {"Public IPv6", orNone(s.NodeIPv6)},
{"Ports", strings.Join(ports, ", ")},
{"Firewall", fw},
{"LiveKit", s.Image + ", " + plan.imageWhy},
@@ -659,6 +752,13 @@ func showJoinSummary(app *App, plan *joinPlan, f *voiceFlags) {
u.Info("Change any of these with flags. Run rexctl voice join --help to see them.")
}
+func orNone(v string) string {
+ if v == "" {
+ return "none"
+ }
+ return v
+}
+
func finishJoin(ctx context.Context, app *App, client *voice.Client, e *engine.Engine, inst *instance.Instance, token string, plan *joinPlan, f *voiceFlags) error {
srv := plan.srv
if existing := inst.State.VoiceServer(srv.ID); existing != nil {
@@ -673,7 +773,7 @@ func finishJoin(ctx context.Context, app *App, client *voice.Client, e *engine.E
if plan.edgeInst != nil {
inst.State.VoiceEdge = &instance.VoiceEdge{Instance: plan.edgeInst.Dir}
} else if inst.State.VoiceEdge == nil && srv.Edge == voice.EdgeOwn {
- inst.State.VoiceEdge = &instance.VoiceEdge{Email: f.Email}
+ inst.State.VoiceEdge = &instance.VoiceEdge{Email: f.Email, IPv6: plan.netIPv6}
}
saved := inst.State.VoiceServer(srv.ID)
if err := saveVoiceState(inst); err != nil {
@@ -757,11 +857,14 @@ func finishJoin(ctx context.Context, app *App, client *voice.Client, e *engine.E
}
app.UI.OK("Voice server %s joined %s in region %s.", saved.ID, plan.domain, joined.RegionID)
waitForVoiceOrigin(ctx, app, client, plan.domain, saved.Endpoint)
- results := runTransportTests(ctx, saved.Endpoint, func() (string, error) {
+ results := runTransportTests(ctx, saved.Endpoint, serverPaths(saved), func() (string, error) {
return voice.TestToken(saved.Key, saved.Secret, voice.TestRoom(), time.Now()), nil
}, false)
reportTransports(app, results, true)
app.UI.Info("Run rexctl voice test %s on the Fluxer machine to test from outside this network.", saved.ID)
+ if saved.NodeIP == "" {
+ app.UI.Info("%s", ipv6OnlyText(saved.ID, len(plan.preview.TurnServers) > 0))
+ }
if status, _, err := client.TestWebhook(ctx, saved.Webhook, saved.Key, saved.Secret, time.Now()); err != nil || status < 200 || status > 299 {
app.UI.Warn(fmt.Sprintf("%s doesn't accept a test webhook from %s.", plan.domain, saved.ID), "Run rexctl doctor to see why.")
} else {
@@ -782,6 +885,7 @@ func joinWithRetries(ctx context.Context, app *App, client *voice.Client, e *eng
APISecret: saved.Secret,
SoftLimit: saved.SoftLimit,
PublicIPv4: saved.NodeIP,
+ PublicIPv6: saved.NodeIPv6,
}
switch {
case plan.coords:
@@ -794,6 +898,9 @@ func joinWithRetries(ctx context.Context, app *App, client *voice.Client, e *eng
if err == nil {
return joined, nil
}
+ if code == voice.CodeEndpointUnreachable && saved.NodeIP == "" {
+ return nil, ui.Failed(fmt.Sprintf("%s couldn't connect to the server's endpoint (%s).", plan.domain, err), "The Fluxer machine may have no IPv6. On it, run rexctl config set network.ipv6 true, then run the same command here again.")
+ }
if plan.preview.ServerIDPinned {
return nil, pinnedJoinError(err, plan.domain, saved.ID)
}
@@ -844,6 +951,13 @@ func renameJoinedServer(ctx context.Context, app *App, e *engine.Engine, inst *i
})
}
+func ipv6OnlyText(id string, turn bool) string {
+ if turn {
+ return fmt.Sprintf("This server offers only IPv6. Callers with IPv6 connect to calls on it directly. Callers with only IPv4 can join through your TURN server when it hands out IPv6 relay addresses and an A record for the hostname points at a machine that forwards ports 80 and 443 here. Run rexctl voice test %s on the Fluxer machine to check, and see the voice servers guide.", id)
+ }
+ return "This server offers only IPv6. Callers with IPv6 connect to calls on it. Callers with only IPv4 can't, and your instance gives clients no TURN server. See the voice servers guide."
+}
+
func pinnedJoinError(err error, domain, id string) error {
if code := voice.CodeOf(err); code == voice.CodeIDInUse || code == voice.CodeKeyInUse {
return ui.Refused(fmt.Sprintf("%s already has a server called %s.", domain, id), "Delete it in the admin panel, or run rexctl voice token --id with another server ID for a new token.")
@@ -948,8 +1062,11 @@ func voiceEdgeSpec(inst *instance.Instance) engine.Spec {
if inst.State.VoiceEdge != nil && inst.State.VoiceEdge.Email != "" {
env["FLUXER_VOICE_EDGE_EMAIL"] = inst.State.VoiceEdge.Email
}
+ if inst.State.VoiceEdge != nil && inst.State.VoiceEdge.IPv6 {
+ env["FLUXER_VOICE_NETWORK_IPV6"] = "true"
+ }
for _, s := range inst.State.Voice {
- if u, err := url.Parse(s.Endpoint); err == nil && s.Edge == voice.EdgeOwn && net.ParseIP(u.Hostname()) != nil {
+ if u, err := url.Parse(s.Endpoint); err == nil && s.Edge == voice.EdgeOwn && voice.IsIPv4(u.Hostname()) {
env["FLUXER_VOICE_EDGE_IP"] = u.Hostname()
}
}
diff --git a/fluxer_rexctl/cmd/voice_lifecycle.go b/fluxer_rexctl/cmd/voice_lifecycle.go
index 52d570294..b1ff3637b 100644
--- a/fluxer_rexctl/cmd/voice_lifecycle.go
+++ b/fluxer_rexctl/cmd/voice_lifecycle.go
@@ -19,6 +19,7 @@ import (
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/voice"
)
@@ -161,6 +162,7 @@ func voiceServerStale(inst *instance.Instance, srv *instance.VoiceServer, image
func upgradeLocalVoiceServers(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine) {
if len(inst.State.Voice) > 0 {
+ followMachineIPv4(ctx, app, inst)
image := instanceLiveKitImage(inst)
api := app.adminClient(inst, e.Named(inst.Project(), inst.Dir))
for i := range inst.State.Voice {
@@ -176,6 +178,7 @@ func upgradeLocalVoiceServers(ctx context.Context, app *App, inst *instance.Inst
}
for _, other := range voiceMachinesUsing(inst) {
err := app.Locked(ctx, other, func() error {
+ refreshJoinedServers(ctx, app, other, true)
for _, srv := range staleVoiceServers(other, ownLiveKitImage()) {
if err := upgradeVoiceServer(ctx, app, e, nil, other, srv, voiceTargetImage(srv, ownLiveKitImage()), defaultDrainTimeout); err != nil {
return err
@@ -269,6 +272,7 @@ func runVoiceMachineUpgrade(ctx context.Context, app *App, inst *instance.Instan
app.UI.Info("%s runs %s, older than this rexctl. Voice servers stay on their LiveKit release until the instance catches up.", domain, target)
return nil
}
+ refreshJoinedServers(ctx, app, inst, !dryRun)
pending := staleVoiceServers(inst, image)
if dryRun {
for _, s := range pending {
@@ -310,6 +314,38 @@ func runVoiceMachineUpgrade(ctx context.Context, app *App, inst *instance.Instan
})
}
+func refreshJoinedServers(ctx context.Context, app *App, inst *instance.Instance, report bool) {
+ if len(inst.State.Voice) == 0 {
+ return
+ }
+ client := &voice.Client{HTTP: &http.Client{Timeout: 30 * time.Second}}
+ code := 0
+ if d, err := client.Discover(ctx, inst.State.Voice[0].Instance); err == nil {
+ code = d.APICodeVersion
+ }
+ for i := range inst.State.Voice {
+ srv := &inst.State.Voice[i]
+ if srv.NodeURL == "" {
+ continue
+ }
+ node, err := client.GetNode(ctx, srv.NodeURL, srv.Key, srv.Secret)
+ if err != nil {
+ app.UI.Detail("reading %s from %s: %v", srv.ID, srv.Instance, err)
+ continue
+ }
+ if node.Turn != nil {
+ srv.Turn = settings.TurnServersValue(*node.Turn)
+ }
+ if !report || code < voice.AddressesCodeVersion || stringOf(node.PublicIPv4) == srv.NodeIP && stringOf(node.PublicIPv6) == srv.NodeIPv6 {
+ continue
+ }
+ v4, v6 := srv.NodeIP, srv.NodeIPv6
+ if _, err := client.UpdateNode(ctx, srv.NodeURL, srv.Key, srv.Secret, voice.NodeUpdate{PublicIPv4: &v4, PublicIPv6: &v6}); err != nil {
+ app.UI.Detail("reporting the addresses of %s to %s: %v", srv.ID, srv.Instance, err)
+ }
+ }
+}
+
func runVoiceMachineUninstall(ctx context.Context, app *App, inst *instance.Instance) error {
_, servers, _ := localVoiceServers(inst, nil)
if len(servers) == 0 {
@@ -358,6 +394,7 @@ func voiceDirFlag(dir string) string {
}
func startLocalVoiceServers(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine) {
+ followMachineIPv4(ctx, app, inst)
for _, v := range deploy.VoiceOnNetwork(inst) {
srv := &v.Server
p, err := e.Load(ctx, deploy.VoiceSpec(v.Owner, srv))
diff --git a/fluxer_rexctl/cmd/voice_ops.go b/fluxer_rexctl/cmd/voice_ops.go
index 00b4d4ebb..eb41eaf40 100644
--- a/fluxer_rexctl/cmd/voice_ops.go
+++ b/fluxer_rexctl/cmd/voice_ops.go
@@ -5,6 +5,7 @@ package cmd
import (
"bytes"
"context"
+ "errors"
"fmt"
"os"
"os/exec"
@@ -60,7 +61,7 @@ func writeVoiceServer(inst *instance.Instance, srv *instance.VoiceServer) error
func startVoiceServer(ctx context.Context, app *App, e *engine.Engine, inst *instance.Instance, srv *instance.VoiceServer, s *ui.Step) error {
if srv.Network == voice.MachineNetwork {
- if err := e.EnsureNetwork(ctx, voice.MachineNetwork, voice.EdgeProject, "voice"); err != nil {
+ if err := e.EnsureNetwork(ctx, voice.MachineNetwork, voice.EdgeProject, "voice", srv.NodeIPv6 != ""); err != nil {
return engineFailure(err)
}
}
@@ -277,7 +278,7 @@ func followVoicePublicIP(inst *instance.Instance) []*instance.VoiceServer {
var out []*instance.VoiceServer
for i := range inst.State.Voice {
srv := &inst.State.Voice[i]
- if srv.Joined || srv.IPPinned || srv.NodeIP == ip {
+ if srv.Joined || srv.IPPinned || srv.NodeIP == ip || ip == "" && srv.NodeIPv6 != "" {
continue
}
srv.NodeIP = ip
@@ -286,6 +287,47 @@ func followVoicePublicIP(inst *instance.Instance) []*instance.VoiceServer {
return out
}
+var machineIPv4 = host.PublicIPv4
+
+func followMachineIPv4(ctx context.Context, app *App, inst *instance.Instance) {
+ if inst.State.IsVoice() || strings.TrimSpace(inst.State.Settings[settings.VoicePublicIP]) != "" {
+ return
+ }
+ var due []*instance.VoiceServer
+ for i := range inst.State.Voice {
+ srv := &inst.State.Voice[i]
+ if !srv.Joined && !srv.IPPinned && srv.BindIP == "" && srv.NodeIP != "" && srv.NodeIPv6 != "" {
+ due = append(due, srv)
+ }
+ }
+ if len(due) == 0 {
+ return
+ }
+ pctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ ip, err := machineIPv4(pctx)
+ cancel()
+ if err != nil || !voice.IsIPv4(ip) {
+ return
+ }
+ var moved []*instance.VoiceServer
+ for _, srv := range due {
+ if srv.NodeIP != ip {
+ srv.NodeIP = ip
+ moved = append(moved, srv)
+ }
+ }
+ if len(moved) == 0 {
+ return
+ }
+ if err := saveVoiceState(inst); err != nil {
+ app.UI.Warn(fmt.Sprintf("Couldn't give the voice servers this machine's new IPv4 address %s (%v).", ip, err), "Run rexctl start again.")
+ return
+ }
+ for _, srv := range moved {
+ app.UI.Info("Voice server %s now gives clients this machine's IPv4 address %s.", srv.ID, ip)
+ }
+}
+
func moveVoicePublicIP(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, restart bool) {
moved := followVoicePublicIP(inst)
if len(moved) == 0 {
@@ -341,30 +383,42 @@ func waitForEndpoint(ctx context.Context, base, edgeAddr string, insecure bool,
}
type transportResult struct {
- Transport voice.Transport
- Err error
+ Path voice.MediaPath
+ Err error
}
-func runTransportTests(ctx context.Context, endpoint string, token func() (string, error), insecure bool) []transportResult {
+func runTransportTests(ctx context.Context, endpoint string, paths []voice.MediaPath, token func() (string, error), insecure bool) []transportResult {
var out []transportResult
- for _, t := range []voice.Transport{voice.TransportUDP, voice.TransportTCP} {
+ for _, p := range paths {
tok, err := token()
if err == nil {
- err = voice.TestTransport(ctx, endpoint, tok, t, insecure, 20*time.Second)
+ err = voice.TestTransport(ctx, endpoint, tok, p, insecure, 20*time.Second)
}
- out = append(out, transportResult{Transport: t, Err: err})
+ out = append(out, transportResult{Path: p, Err: err})
}
return out
}
+func serverPaths(srv *instance.VoiceServer) []voice.MediaPath {
+ family := voice.FamilyOf(srv.NodeIP, srv.NodeIPv6)
+ if family == voice.FamilyNone {
+ family = voice.FamilyIPv4
+ }
+ return voice.MediaPaths(family, family)
+}
+
func reportTransports(app *App, results []transportResult, local bool) bool {
ok := true
for _, r := range results {
- name := strings.ToUpper(string(r.Transport))
+ name := r.Path.Name()
if r.Err == nil {
app.UI.OK("%s connects.", name)
continue
}
+ if errors.Is(r.Err, voice.ErrNoTurn) {
+ app.UI.Info("rexctl didn't test %s. The server gives clients no TURN server over UDP or TCP.", name)
+ continue
+ }
ok = false
app.UI.Warn(fmt.Sprintf("%s doesn't connect (%v).", name, r.Err), "")
}
diff --git a/fluxer_rexctl/go.mod b/fluxer_rexctl/go.mod
index 8bcd9004a..71bef3745 100644
--- a/fluxer_rexctl/go.mod
+++ b/fluxer_rexctl/go.mod
@@ -28,6 +28,7 @@ require (
golang.org/x/net v0.62.0
golang.org/x/sys v0.49.0
golang.org/x/term v0.47.0
+ google.golang.org/protobuf v1.36.12
)
require (
@@ -163,7 +164,6 @@ require (
google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e // indirect
google.golang.org/grpc v1.85.0 // indirect
- google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/ini.v1 v1.67.3 // indirect
gotest.tools/v3 v3.5.2 // indirect
tags.cncf.io/container-device-interface v1.1.1 // indirect
diff --git a/fluxer_rexctl/internal/adminapi/gen.go b/fluxer_rexctl/internal/adminapi/gen.go
index 30589b132..c978b6d1e 100644
--- a/fluxer_rexctl/internal/adminapi/gen.go
+++ b/fluxer_rexctl/internal/adminapi/gen.go
@@ -1919,7 +1919,9 @@ type CreateVoiceServerRequestBody struct {
Longitude *float32 `json:"longitude,omitempty"`
// Notes Free-form admin notes about this server
- Notes *string `json:"notes,omitempty"`
+ Notes *string `json:"notes,omitempty"`
+ PublicIpv4 *VoicePublicIpv4Type `json:"public_ipv4,omitempty"`
+ PublicIpv6 *VoicePublicIpv6Type `json:"public_ipv6,omitempty"`
// RequiredGuildFeatures Guild features required to use this server
RequiredGuildFeatures *[]string `json:"required_guild_features,omitempty"`
@@ -3022,7 +3024,9 @@ type UpdateVoiceServerRequestBody struct {
Longitude *float32 `json:"longitude,omitempty"`
// Notes Free-form admin notes about this server, or null to clear them
- Notes *string `json:"notes,omitempty"`
+ Notes *string `json:"notes,omitempty"`
+ PublicIpv4 *VoicePublicIpv4Type `json:"public_ipv4,omitempty"`
+ PublicIpv6 *VoicePublicIpv6Type `json:"public_ipv6,omitempty"`
// RequiredGuildFeatures Guild features required to use this server
RequiredGuildFeatures *[]string `json:"required_guild_features,omitempty"`
@@ -3201,6 +3205,12 @@ type VoiceP2pConfigUpdateRequest struct {
RolloutSalt *string `json:"rollout_salt,omitempty"`
}
+// VoicePublicIpv4Type Public IPv4 address LiveKit gives to clients
+type VoicePublicIpv4Type = string
+
+// VoicePublicIpv6Type Public IPv6 address LiveKit gives to clients
+type VoicePublicIpv6Type = string
+
// VoiceRegionAdminResponse defines model for VoiceRegionAdminResponse.
type VoiceRegionAdminResponse struct {
// AllowedGuildIds Guild IDs explicitly allowed to use this region
@@ -3278,6 +3288,12 @@ type VoiceServerAdminResponse struct {
// Notes Free-form admin notes about this server, or null when there are none
Notes *string `json:"notes"`
+ // PublicIpv4 Public IPv4 address LiveKit gives to clients, or null when none is known
+ PublicIpv4 *string `json:"public_ipv4"`
+
+ // PublicIpv6 Public IPv6 address LiveKit gives to clients, or null when none is known
+ PublicIpv6 *string `json:"public_ipv6"`
+
// RegionId ID of the region this server belongs to
RegionId string `json:"region_id"`
diff --git a/fluxer_rexctl/internal/checks/dns.go b/fluxer_rexctl/internal/checks/dns.go
index d6d18e168..28e90b69c 100644
--- a/fluxer_rexctl/internal/checks/dns.go
+++ b/fluxer_rexctl/internal/checks/dns.go
@@ -44,12 +44,8 @@ func runDNS(ctx context.Context, e *Env) Result {
return fail(fmt.Sprintf("%s doesn't point to this machine yet.", e.Domain),
fmt.Sprintf("Add an A record for it pointing to %s, then run rexctl doctor.", public))
}
- if pointsHere(addrs, public) {
- shown := public
- if shown == "" {
- shown = addrs[0].IP.String()
- }
- return pass(fmt.Sprintf("%s points to this machine (%s).", e.Domain, shown))
+ if matched := matchHere(addrs, public); len(matched) > 0 {
+ return pass(fmt.Sprintf("%s points to this machine (%s).", e.Domain, strings.Join(matched, ", ")))
}
if e.forwardsHere(ctx) {
return pass(fmt.Sprintf("%s points to %s, which forwards to this machine.", e.Domain, addrs[0].IP))
@@ -61,7 +57,7 @@ func runDNS(ctx context.Context, e *Env) Result {
fmt.Sprintf("Change its A record to %s, then run rexctl doctor.", public))
}
-func pointsHere(addrs []net.IPAddr, public string) bool {
+func matchHere(addrs []net.IPAddr, public string) []string {
pub := net.ParseIP(public)
local := map[string]bool{}
if ifaces, err := net.InterfaceAddrs(); err == nil {
@@ -71,15 +67,13 @@ func pointsHere(addrs []net.IPAddr, public string) bool {
}
}
}
+ var matched []string
for _, a := range addrs {
- if pub != nil && a.IP.Equal(pub) {
- return true
- }
- if local[a.IP.String()] {
- return true
+ if pub != nil && a.IP.Equal(pub) || local[a.IP.String()] {
+ matched = append(matched, a.IP.String())
}
}
- return false
+ return matched
}
func (e *Env) forwardsHere(ctx context.Context) bool {
diff --git a/fluxer_rexctl/internal/checks/voice.go b/fluxer_rexctl/internal/checks/voice.go
index 32bd5c965..227764c32 100644
--- a/fluxer_rexctl/internal/checks/voice.go
+++ b/fluxer_rexctl/internal/checks/voice.go
@@ -178,15 +178,23 @@ func runVoiceNodeIP(ctx context.Context, e *Env) Result {
if len(servers) == 0 || e.Engine == nil {
return skip("")
}
- public, perr := e.publicAddress(ctx)
+ public4, err4 := host.PublicIPv4(ctx)
+ seen6, _ := host.PublicIPv6(ctx)
+ public6 := voice.MachineIPv6(seen6)
var problems []string
for _, s := range servers {
+ if s.NodeIPv6 != "" && public6 != "" && s.NodeIPv6 != public6 {
+ problems = append(problems, fmt.Sprintf("%s gives clients %s and this machine's public IPv6 address is %s", s.ID, s.NodeIPv6, public6))
+ }
if s.NodeIP != "" {
- if perr == nil && s.NodeIP != public && s.BindIP == "" {
- problems = append(problems, fmt.Sprintf("%s gives clients %s and this machine's public address is %s", s.ID, s.NodeIP, public))
+ if err4 == nil && s.NodeIP != public4 && s.BindIP == "" {
+ problems = append(problems, fmt.Sprintf("%s gives clients %s and this machine's public IPv4 address is %s", s.ID, s.NodeIP, public4))
}
continue
}
+ if s.NodeIPv6 != "" {
+ continue
+ }
if strings.Contains(strings.ToLower(e.voiceLogs(ctx, s, 300)), "could not resolve external ip") {
problems = append(problems, s.ID+" can't find its public address")
}
diff --git a/fluxer_rexctl/internal/deploy/voice.go b/fluxer_rexctl/internal/deploy/voice.go
index 81239249a..cefc48a80 100644
--- a/fluxer_rexctl/internal/deploy/voice.go
+++ b/fluxer_rexctl/internal/deploy/voice.go
@@ -48,24 +48,27 @@ const (
func VoiceEnv(inst *instance.Instance, srv *instance.VoiceServer) voice.Env {
env := voice.Env{
- ID: srv.ID,
- Key: srv.Key,
- Secret: srv.Secret,
- WebhookURL: srv.Webhook,
- Network: srv.Network,
- TCPPort: srv.TCPPort,
- UDPPort: srv.UDPPort,
- HTTPPort: srv.HTTPPort,
- HTTPBind: srv.HTTPBind,
- NodeIP: srv.NodeIP,
- BindIP: srv.BindIP,
- Image: srv.Image,
- Memory: srv.Memory,
+ ID: srv.ID,
+ Key: srv.Key,
+ Secret: srv.Secret,
+ WebhookURL: srv.Webhook,
+ Network: srv.Network,
+ TCPPort: srv.TCPPort,
+ UDPPort: srv.UDPPort,
+ HTTPPort: srv.HTTPPort,
+ HTTPBind: srv.HTTPBind,
+ NodeIP: srv.NodeIP,
+ NodeIPv6: srv.NodeIPv6,
+ BindIP: srv.BindIP,
+ Image: srv.Image,
+ Memory: srv.Memory,
+ TurnServers: srv.Turn,
}
if !inst.State.IsVoice() {
env.StunPrimary = inst.Setting("FLUXER_LIVEKIT_STUN_PRIMARY")
env.StunSecondary = inst.Setting("FLUXER_LIVEKIT_STUN_SECONDARY")
env.LogLevel = inst.Setting("FLUXER_LIVEKIT_LOG_LEVEL")
+ env.TurnServers, _ = settings.NormalTurnServers(inst.Setting(settings.TurnServersVar))
}
return env
}
diff --git a/fluxer_rexctl/internal/engine/api.go b/fluxer_rexctl/internal/engine/api.go
index ed1bc0306..e47601b26 100644
--- a/fluxer_rexctl/internal/engine/api.go
+++ b/fluxer_rexctl/internal/engine/api.go
@@ -20,6 +20,8 @@ const (
const (
MinPodman = "5.4.0"
MinDocker = "24.0.0"
+
+ MinDockerIPv6 = "27.0.0"
)
const DefaultReadyTimeout = 10 * time.Minute
diff --git a/fluxer_rexctl/internal/engine/apply.go b/fluxer_rexctl/internal/engine/apply.go
index 183a8a23b..2f0ca52e6 100644
--- a/fluxer_rexctl/internal/engine/apply.go
+++ b/fluxer_rexctl/internal/engine/apply.go
@@ -451,7 +451,7 @@ func (p *Project) wrap(op string, err error) error {
return &Error{Op: op, Class: ClassOf(err), Err: err}
}
-func (e *Engine) EnsureNetwork(ctx context.Context, name, project, key string) error {
+func (e *Engine) EnsureNetwork(ctx context.Context, name, project, key string, ipv6 bool) error {
c, err := e.api()
if err != nil {
return err
@@ -461,12 +461,35 @@ func (e *Engine) EnsureNetwork(ctx context.Context, name, project, key string) e
} else if !cerrdefs.IsNotFound(err) {
return err
}
- _, err = c.NetworkCreate(ctx, name, client.NetworkCreateOptions{
+ opts := client.NetworkCreateOptions{
Driver: "bridge",
Labels: map[string]string{api.ProjectLabel: project, api.NetworkLabel: key},
- })
+ }
+ if ipv6 {
+ opts.EnableIPv6 = &ipv6
+ }
+ _, err = c.NetworkCreate(ctx, name, opts)
if cerrdefs.IsConflict(err) {
return nil
}
return err
}
+
+func (e *Engine) NetworkIPv6(ctx context.Context, name string) (bool, bool, error) {
+ c, err := e.api()
+ if err != nil {
+ return false, false, err
+ }
+ res, err := c.NetworkInspect(ctx, name, client.NetworkInspectOptions{})
+ if cerrdefs.IsNotFound(err) {
+ return false, false, nil
+ }
+ if err != nil {
+ return false, false, err
+ }
+ return true, res.Network.EnableIPv6, nil
+}
+
+func (e *Engine) IPv6Voice() bool {
+ return e.Kind == Docker && !e.Rootless && AtLeast(e.Version, MinDockerIPv6)
+}
diff --git a/fluxer_rexctl/internal/host/sys.go b/fluxer_rexctl/internal/host/sys.go
index 5128ba73e..e748ccc6d 100644
--- a/fluxer_rexctl/internal/host/sys.go
+++ b/fluxer_rexctl/internal/host/sys.go
@@ -46,9 +46,17 @@ func PublicIP(ctx context.Context) (string, error) {
}
func PublicIPv4(ctx context.Context) (string, error) {
+ return publicIPOver(ctx, "udp4")
+}
+
+func PublicIPv6(ctx context.Context) (string, error) {
+ return publicIPOver(ctx, "udp6")
+}
+
+func publicIPOver(ctx context.Context, network string) (string, error) {
var last error = ErrNoPublicIP
for _, server := range stunServers {
- ip, err := stunQuery(ctx, "udp4", server)
+ ip, err := stunQuery(ctx, network, server)
if err == nil {
return ip.String(), nil
}
diff --git a/fluxer_rexctl/internal/instance/bundleenv.go b/fluxer_rexctl/internal/instance/bundleenv.go
index 6d3dc49b7..28481fc74 100644
--- a/fluxer_rexctl/internal/instance/bundleenv.go
+++ b/fluxer_rexctl/internal/instance/bundleenv.go
@@ -315,7 +315,7 @@ func literalDefault(defs []string) string {
return defs[0]
}
-var voiceSharedVars = []string{"FLUXER_LIVEKIT_IMAGE", "FLUXER_LIVEKIT_LOG_LEVEL", "FLUXER_LIVEKIT_STUN_PRIMARY", "FLUXER_LIVEKIT_STUN_SECONDARY"}
+var voiceSharedVars = []string{"FLUXER_LIVEKIT_IMAGE", "FLUXER_LIVEKIT_LOG_LEVEL", "FLUXER_LIVEKIT_STUN_PRIMARY", "FLUXER_LIVEKIT_STUN_SECONDARY", "FLUXER_LIVEKIT_TURN_SERVERS"}
var voiceRequiredVars = []string{"FLUXER_VOICE_ID", "FLUXER_VOICE_API_KEY", "FLUXER_VOICE_API_SECRET", "FLUXER_VOICE_WEBHOOK_URL"}
diff --git a/fluxer_rexctl/internal/instance/envvars.go b/fluxer_rexctl/internal/instance/envvars.go
index a61c6ecf1..cdbedd651 100644
--- a/fluxer_rexctl/internal/instance/envvars.go
+++ b/fluxer_rexctl/internal/instance/envvars.go
@@ -103,14 +103,15 @@ var envVars = []envVar{
{"FLUXER_LIVEKIT_USE_EXTERNAL_IP", "voice", "Whether LiveKit finds its public IP address through STUN. Use `true` or `false`. Set it to `false` when you set FLUXER_LIVEKIT_NODE_IP."},
{"FLUXER_LIVEKIT_STUN_PRIMARY", "voice", "The first STUN host LiveKit asks to find its public IP address, as `host:port`. Point it at another STUN host to avoid contacting Google."},
{"FLUXER_LIVEKIT_STUN_SECONDARY", "voice", "The second STUN host LiveKit asks to find its public IP address, as `host:port`."},
- {"FLUXER_LIVEKIT_TURN_SERVERS", "voice", "TURN relays LiveKit offers to browsers and apps, as a JSON array of objects with `host`, `port`, `protocol` and optional `username` and `credential`, such as `[{\"host\":\"turn.example.com\",\"port\":3478,\"protocol\":\"udp\",\"username\":\"fluxer\",\"credential\":\"secret\"}]`. Use `udp`, `tcp` or `tls` for `protocol`. Set it when browsers and apps can't connect to the LiveKit ports directly, such as behind Cloudflare Tunnel. When it's empty, LiveKit offers no TURN relay."},
+ {"FLUXER_LIVEKIT_TURN_SERVERS", "voice", "TURN servers that browsers and apps get when they join a call, as a JSON array of objects with `host`, `port` and `protocol`, and either `username` and `credential` or `secret` with an optional `ttl`, such as `[{\"host\":\"turn.example.com\",\"port\":3478,\"protocol\":\"udp\",\"secret\":\"a-long-random-secret\"}]`. Use `udp`, `tcp` or `tls` for `protocol`, and a hostname or an IPv4 address for `host`. With `secret`, LiveKit makes short-lived credentials for each participant in the form coturn checks with `use-auth-secret`, and `ttl`, a whole number from 1, sets how many seconds they last. The bundled voice server and the servers you add with rexctl voice add give these to clients, and rexctl restarts the added servers one at a time when the list changes. A server that joined with rexctl voice join gets the list when it joins and on each rexctl upgrade in its voice folder, unless the instance runs an older release than the rexctl there. Set it when callers can't connect to a voice server directly, such as from networks that allow only port 443. When it's empty, clients get no TURN server. A value the API can't read stops it from starting, and rexctl config set refuses one."},
{"FLUXER_VOICE_ID", "voice-server", "The ID of the voice server, such as `fra-server-2`. Use lowercase letters, digits and dashes. The container answers as `voice-` followed by this ID on the voice network, and the edge routes `/livekit-` followed by this ID to it."},
{"FLUXER_VOICE_API_KEY", "voice-server", "The LiveKit API key of this server. Every voice server of an instance needs its own key, such as `fluxer-` followed by the server ID."},
{"FLUXER_VOICE_API_SECRET", "voice-server", "The LiveKit API secret that goes with FLUXER_VOICE_API_KEY, at least 32 characters, such as the output of `openssl rand -hex 32`."},
{"FLUXER_VOICE_WEBHOOK_URL", "voice-server", "The URL LiveKit sends its webhooks to. On the Fluxer machine it's `http://api:8080/webhooks/livekit`. On another machine it's the public API address followed by /webhooks/livekit."},
{"FLUXER_VOICE_TCP_PORT", "voice-server", "The TCP port for media on this host. LiveKit listens on the same port inside the container, and each server on a host needs its own."},
{"FLUXER_VOICE_UDP_PORT", "voice-server", "The UDP port for media on this host. LiveKit listens on the same port inside the container, and each server on a host needs its own."},
- {"FLUXER_VOICE_NODE_IP", "voice-server", "The public IPv4 address LiveKit gives to clients. Set FLUXER_VOICE_USE_EXTERNAL_IP to `false` with it."},
+ {"FLUXER_VOICE_NODE_IP", "voice-server", "The public addresses LiveKit gives to clients. Give an IPv4 address, an IPv6 address, or both with a comma between them, such as `203.0.113.7,2001:db8::7`. Set FLUXER_VOICE_USE_EXTERNAL_IP to `false` with it. LiveKit offers an IPv6 address only when the server's Docker network has IPv6."},
+ {"FLUXER_VOICE_ICE_IPS", "voice-server", "The address ranges LiveKit may offer to clients, as a JSON array of ranges such as `[\"::/0\"]`. rexctl sets it to the families in FLUXER_VOICE_NODE_IP, so a server with only IPv6 offers no private IPv4 address of its container. Use `[]` to offer every address."},
{"FLUXER_VOICE_USE_EXTERNAL_IP", "voice-server", "Whether LiveKit finds its public IP address through STUN. Use `true` or `false`."},
{"FLUXER_VOICE_BIND_IP", "voice-server", "The host address the media ports are published on, for a host with more than one public address. When it's empty, Docker publishes them on every address."},
{"FLUXER_VOICE_HTTP_PORT", "voice-server", "The port that voice-http.compose.yml publishes LiveKit's HTTP and WebSocket port on, for your own proxy."},
@@ -120,6 +121,7 @@ var envVars = []envVar{
{"FLUXER_VOICE_GOMEMLIMIT", "voice-server", "The soft memory limit of the Go runtime in LiveKit. Keep it at about 85% of FLUXER_VOICE_MEMORY_LIMIT."},
{"FLUXER_VOICE_STOP_GRACE", "voice-server", "How long Docker waits for the calls on the server to end when it stops or replaces the container, before it stops LiveKit anyway."},
{"FLUXER_VOICE_EDGE_IP", "voice-edge", "The public IPv4 address of the voice machine, when an endpoint uses that address and not a hostname. The edge then answers clients that send no server name with the certificate for that address, which browsers need."},
+ {"FLUXER_VOICE_NETWORK_IPV6", "voice-edge", "Whether the voice network gets IPv6. Use `true` or `false`. rexctl sets it to `true` when it creates the network on a machine with a public IPv6 address. Docker can't add IPv6 to a network that already exists."},
{"FLUXER_VOICE_EDGE_EMAIL", "voice-edge", "The email address the voice edge gives Let's Encrypt for notices about its certificates. When it's empty, the edge gets certificates without one."},
{"FLUXER_S3_ENDPOINT", "storage", ""},
{"FLUXER_S3_PUBLIC_ENDPOINT", "storage", "When it's empty, the api and worker use FLUXER_S3_ENDPOINT, and the web app doesn't let browsers upload to the object store."},
diff --git a/fluxer_rexctl/internal/instance/shipped.json b/fluxer_rexctl/internal/instance/shipped.json
index 92b99b513..47403789a 100644
--- a/fluxer_rexctl/internal/instance/shipped.json
+++ b/fluxer_rexctl/internal/instance/shipped.json
@@ -61,6 +61,7 @@
"98e840268063fcc8f285364dc8b0098e416621ea99e9a92ab986661200f122e9",
"9b4da1d640c6c7882cc583f5fcb04a7a3c478a3b167ceefe9a1fdc8613e7a547",
"9ddb7e697174484b2411c6b7239e73374200512597bd5de9f9654ff796e3a39a",
+ "a0fcbc346ae2c9038294e921fa0cd53c0dbabfc92c005e72825b22c6f4c562f3",
"a3b0de3f98f20af674ba28457062092e2efa64744ff56d3b82947ec2148e629b",
"a61adc1611286d1336bdd4ed8da55258bc1467cfc824161a30bb992ac69607c6",
"a7915e920ff78b5e3ea4e70e44c69353b0af6d549c0fa5fe4cae919f5bad25ec",
@@ -201,6 +202,7 @@
"8fc464560ddfd9068035acafde0dbe4fa96aad78b43e382ccd03ab89f1369cfa",
"90fcefc650f64640eb0527ec287b721748635e9214902c076d2b7abf3faa624c",
"9140244e91fb0262f6e6c53a9f7e89780213018f7edbc1c9e6925a143e9cee06",
+ "925c29e195d785e4e69a9498da1bc2d8934d273b64ec6a0a9bac0a57dc095061",
"9341b083d98c743766dfa13a1424f9a138c5ba9f2ff03a89caf7590685fa22a0",
"94bc891e0d91439c447b4faaa9c29bd685878e04ae30e350f086d60173119671",
"970565bc2040669194a47efa6cd0a78f8d6738f4396012fa55cca4b3022c9b6e",
@@ -266,10 +268,17 @@
"d36c5a277a6c57c50e3a659e2ff60306862a11b3d3e44c54567b49d2d64779c0"
],
"voice/Caddyfile.voice": ["193a85faef0174276028f154858bfd98aaaebc2e2ba2d09c1154ff24156d3060"],
- "voice/voice-edge.compose.yml": ["8c42013b22dc829072af16e1db89a902358cf2c07e1a44bdd6297421ffba397c"],
+ "voice/voice-edge.compose.yml": [
+ "19a13bae355f3ca6cee1b0d0b6be651a513747fbc2de319df0ef0e5917f30d21",
+ "8c42013b22dc829072af16e1db89a902358cf2c07e1a44bdd6297421ffba397c"
+ ],
"voice/voice-http.compose.yml": [
"80433a0f965a050fcc88dad63d6887cca9dbc06b1d2344c4e8a898049ad55d6b",
"f7a207a03625b080768b57f89a44b5828384d0efb528f92f30aa18034e4cf40d"
],
- "voice/voice.compose.yml": ["b0ea7cf174eea1b5b882f21f7ab08f6526ecac6e96cb98ab990b3a0e8e6f26d9"]
+ "voice/voice.compose.yml": [
+ "4b0a3514c1ebd2e440921475007d3b1ef69d016679e0f90cb421be4017844e5c",
+ "b0ea7cf174eea1b5b882f21f7ab08f6526ecac6e96cb98ab990b3a0e8e6f26d9",
+ "cf5f6fa4f88a9934cf299fc96a3a4f14e89b8fc6854d99d842f9ac23c5315f1c"
+ ]
}
diff --git a/fluxer_rexctl/internal/instance/state.go b/fluxer_rexctl/internal/instance/state.go
index 9ac9abdd7..10d8abb68 100644
--- a/fluxer_rexctl/internal/instance/state.go
+++ b/fluxer_rexctl/internal/instance/state.go
@@ -18,7 +18,7 @@ import (
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
)
-const StateSchema = generatedSchema + 1
+const StateSchema = generatedSchema + 2
var ErrNewerState = errors.New("instance: state was written by a newer rexctl")
@@ -71,6 +71,7 @@ type VoiceServer struct {
HTTPPort int `json:"http_port,omitempty"`
HTTPBind string `json:"http_bind,omitempty"`
NodeIP string `json:"node_ip,omitempty"`
+ NodeIPv6 string `json:"node_ipv6,omitempty"`
IPPinned bool `json:"pinned_node_ip,omitempty"`
BindIP string `json:"bind_ip,omitempty"`
Image string `json:"image"`
@@ -86,6 +87,7 @@ type VoiceServer struct {
Edge string `json:"edge,omitempty"`
Joined bool `json:"joined,omitempty"`
Drained bool `json:"drained,omitempty"`
+ Turn string `json:"turn_servers,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
@@ -93,6 +95,7 @@ type VoiceEdge struct {
Email string `json:"email,omitempty"`
Opened []string `json:"opened,omitempty"`
Instance string `json:"instance,omitempty"`
+ IPv6 bool `json:"ipv6,omitempty"`
}
func (s *State) IsVoice() bool { return s != nil && s.Kind == KindVoice }
diff --git a/fluxer_rexctl/internal/settings/keys.go b/fluxer_rexctl/internal/settings/keys.go
index 264e71e62..60eff41dd 100644
--- a/fluxer_rexctl/internal/settings/keys.go
+++ b/fluxer_rexctl/internal/settings/keys.go
@@ -232,8 +232,12 @@ func Lookup(set *stack.Set, custom []string, name string, adminSchema []adminapi
if !slices.Contains(set.Vars, name) && !slices.Contains(custom, name) {
return Key{}, unknown(name)
}
+ validate := validText
+ if name == TurnServersVar {
+ validate = validTurnServers
+ }
return Key{Name: name, Kind: Raw, Type: "text", Vars: []string{name}, Secret: SecretName(name),
- Stateful: generatedStateful(name), Validate: validText}, nil
+ Stateful: generatedStateful(name), Validate: validate}, nil
}
func unknown(name string) error {
diff --git a/fluxer_rexctl/internal/settings/mask.go b/fluxer_rexctl/internal/settings/mask.go
index 0280c14dc..7c8b79811 100644
--- a/fluxer_rexctl/internal/settings/mask.go
+++ b/fluxer_rexctl/internal/settings/mask.go
@@ -3,7 +3,9 @@
package settings
import (
+ "encoding/json"
"net/url"
+ "slices"
"strings"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
@@ -34,9 +36,31 @@ func Mask(key Key, value string) string {
if key.Secret {
return Masked
}
+ if key.Name == TurnServersVar || slices.Contains(key.Vars, TurnServersVar) {
+ return MaskTurnServers(value)
+ }
return maskUserinfo(value)
}
+func MaskTurnServers(value string) string {
+ var list []map[string]any
+ if err := json.Unmarshal([]byte(value), &list); err != nil {
+ return Masked
+ }
+ for _, entry := range list {
+ for _, field := range []string{"secret", "credential"} {
+ if _, ok := entry[field]; ok {
+ entry[field] = Masked
+ }
+ }
+ }
+ out, err := json.Marshal(list)
+ if err != nil {
+ return Masked
+ }
+ return string(out)
+}
+
func maskUserinfo(value string) string {
u, err := url.Parse(value)
if err != nil || u.User == nil || u.Host == "" {
diff --git a/fluxer_rexctl/internal/settings/turn.go b/fluxer_rexctl/internal/settings/turn.go
new file mode 100644
index 000000000..0ac7a7354
--- /dev/null
+++ b/fluxer_rexctl/internal/settings/turn.go
@@ -0,0 +1,149 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package settings
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "slices"
+ "strings"
+ "unicode"
+)
+
+const TurnServersVar = "FLUXER_LIVEKIT_TURN_SERVERS"
+
+type TurnServer struct {
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Protocol string `json:"protocol"`
+ Username string `json:"username,omitempty"`
+ Credential string `json:"credential,omitempty"`
+ Secret string `json:"secret,omitempty"`
+ TTL int `json:"ttl,omitempty"`
+}
+
+var turnFields = []string{"host", "port", "protocol", "username", "credential", "secret", "ttl"}
+
+var errTurnList = errors.New("Give the TURN servers as one JSON array of objects with host, port and protocol.")
+
+func ParseTurnServers(raw string) ([]TurnServer, error) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return nil, nil
+ }
+ var entries []json.RawMessage
+ if err := json.Unmarshal([]byte(raw), &entries); err != nil || entries == nil {
+ return nil, errTurnList
+ }
+ list := make([]TurnServer, 0, len(entries))
+ for i, data := range entries {
+ t, err := parseTurnServer(data, i+1)
+ if err != nil {
+ return nil, err
+ }
+ list = append(list, t)
+ }
+ return list, nil
+}
+
+func parseTurnServer(data json.RawMessage, n int) (TurnServer, error) {
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(data, &fields); err != nil || fields == nil {
+ return TurnServer{}, fmt.Errorf("Give TURN server %d as a JSON object.", n)
+ }
+ for key := range fields {
+ if !slices.Contains(turnFields, key) {
+ return TurnServer{}, fmt.Errorf("TURN server %d has the field %q, which Fluxer doesn't know. Use host, port, protocol, username, credential, secret and ttl.", n, key)
+ }
+ }
+ var t TurnServer
+ var ok, hasUser, hasCred, hasSecret, hasTTL bool
+ if t.Host, ok = turnString(fields, "host"); !ok || strings.ContainsAny(t.Host, ":/[]") || strings.IndexFunc(t.Host, turnSpace) >= 0 {
+ return TurnServer{}, fmt.Errorf("Give TURN server %d a host that is a hostname or an IPv4 address.", n)
+ }
+ if t.Port, ok = turnInt(fields, "port"); !ok || t.Port < 1 || t.Port > 65535 {
+ return TurnServer{}, fmt.Errorf("Give TURN server %d a port from 1 to 65535.", n)
+ }
+ if t.Protocol, ok = turnString(fields, "protocol"); !ok || t.Protocol != "udp" && t.Protocol != "tcp" && t.Protocol != "tls" {
+ return TurnServer{}, fmt.Errorf("Give TURN server %d the protocol udp, tcp or tls.", n)
+ }
+ for _, f := range []struct {
+ key string
+ dst *string
+ has *bool
+ }{{"username", &t.Username, &hasUser}, {"credential", &t.Credential, &hasCred}, {"secret", &t.Secret, &hasSecret}} {
+ if _, *f.has = fields[f.key]; !*f.has {
+ continue
+ }
+ if *f.dst, ok = turnString(fields, f.key); !ok {
+ return TurnServer{}, fmt.Errorf("Give TURN server %d a %s that is text and not empty.", n, f.key)
+ }
+ }
+ switch {
+ case hasSecret && (hasUser || hasCred):
+ return TurnServer{}, fmt.Errorf("Give TURN server %d a secret, or a username and credential, and not both.", n)
+ case hasUser != hasCred:
+ return TurnServer{}, fmt.Errorf("Give TURN server %d both a username and a credential.", n)
+ }
+ if _, hasTTL = fields["ttl"]; hasTTL {
+ if t.TTL, ok = turnInt(fields, "ttl"); !ok || t.TTL < 1 || !hasSecret {
+ return TurnServer{}, fmt.Errorf("Give TURN server %d a ttl only with a secret, as a whole number of seconds from 1.", n)
+ }
+ }
+ return t, nil
+}
+
+func turnString(fields map[string]json.RawMessage, key string) (string, bool) {
+ data, ok := fields[key]
+ if !ok || bytes.Equal(bytes.TrimSpace(data), []byte("null")) {
+ return "", false
+ }
+ var s string
+ if json.Unmarshal(data, &s) != nil || s == "" {
+ return "", false
+ }
+ return s, true
+}
+
+func turnInt(fields map[string]json.RawMessage, key string) (int, bool) {
+ data, ok := fields[key]
+ if !ok || bytes.Equal(bytes.TrimSpace(data), []byte("null")) {
+ return 0, false
+ }
+ var f float64
+ if json.Unmarshal(data, &f) != nil || f != math.Trunc(f) || f < math.MinInt32 || f > math.MaxInt32 {
+ return 0, false
+ }
+ return int(f), true
+}
+
+func turnSpace(r rune) bool {
+ return unicode.IsSpace(r) || r == 0xFEFF
+}
+
+func TurnServersValue(list []TurnServer) string {
+ if len(list) == 0 {
+ return ""
+ }
+ var b bytes.Buffer
+ enc := json.NewEncoder(&b)
+ enc.SetEscapeHTML(false)
+ _ = enc.Encode(list)
+ return strings.ReplaceAll(strings.TrimSpace(b.String()), "'", `'`)
+}
+
+func validTurnServers(v string) error {
+ _, err := ParseTurnServers(v)
+ return err
+}
+
+func NormalTurnServers(raw string) (string, error) {
+ list, err := ParseTurnServers(raw)
+ if err != nil {
+ return "", err
+ }
+ return TurnServersValue(list), nil
+}
diff --git a/fluxer_rexctl/internal/stack/files/.env.example b/fluxer_rexctl/internal/stack/files/.env.example
index bec7656d9..aad757c5f 100644
--- a/fluxer_rexctl/internal/stack/files/.env.example
+++ b/fluxer_rexctl/internal/stack/files/.env.example
@@ -502,12 +502,22 @@ FLUXER_VAPID_PRIVATE_KEY=
# rexctl: rexctl config set FLUXER_LIVEKIT_STUN_SECONDARY
# FLUXER_LIVEKIT_STUN_SECONDARY=
-# TURN relays LiveKit offers to browsers and apps, as a JSON array of objects
-# with host, port, protocol and optional username and credential, such as
-# [{"host":"turn.example.com","port":3478,"protocol":"udp","username":"fluxer","credential":"secret"}].
-# Use udp, tcp or tls for protocol. Set it when browsers and apps can't
-# connect to the LiveKit ports directly, such as behind Cloudflare Tunnel.
-# When it's empty, LiveKit offers no TURN relay.
+# TURN servers that browsers and apps get when they join a call, as a JSON
+# array of objects with host, port and protocol, and either username and
+# credential or secret with an optional ttl, such as
+# [{"host":"turn.example.com","port":3478,"protocol":"udp","secret":"a-long-random-secret"}].
+# Use udp, tcp or tls for protocol, and a hostname or an IPv4 address for
+# host. With secret, LiveKit makes short-lived credentials for each
+# participant in the form coturn checks with use-auth-secret, and ttl, a whole
+# number from 1, sets how many seconds they last. The bundled voice server and
+# the servers you add with rexctl voice add give these to clients, and rexctl
+# restarts the added servers one at a time when the list changes. A server
+# that joined with rexctl voice join gets the list when it joins and on each
+# rexctl upgrade in its voice folder, unless the instance runs an older
+# release than the rexctl there. Set it when callers can't connect to a voice
+# server directly, such as from networks that allow only port 443. When it's
+# empty, clients get no TURN server. A value the API can't read stops it from
+# starting, and rexctl config set refuses one.
# default: []
# rexctl: rexctl config set FLUXER_LIVEKIT_TURN_SERVERS
# FLUXER_LIVEKIT_TURN_SERVERS=
diff --git a/fluxer_rexctl/internal/stack/files/docker-compose.yml b/fluxer_rexctl/internal/stack/files/docker-compose.yml
index 4c5edd8c4..41cb648c2 100644
--- a/fluxer_rexctl/internal/stack/files/docker-compose.yml
+++ b/fluxer_rexctl/internal/stack/files/docker-compose.yml
@@ -117,6 +117,7 @@ x-fluxer-env: &fluxer-env
FLUXER_LIVEKIT_DEFAULT_REGION: '${FLUXER_LIVEKIT_DEFAULT_REGION:-{"id":"default","name":"Default","emoji":"🌍","latitude":0,"longitude":0}}'
FLUXER_LIVEKIT_URL: ${FLUXER_LIVEKIT_URL:-${FLUXER_PUBLIC_ORIGIN:-${FLUXER_PUBLIC_SCHEME:-https}://${FLUXER_DOMAIN:-}:${FLUXER_PUBLIC_PORT:-443}}/livekit}
FLUXER_VOICE_P2P_STUN_URLS: ${FLUXER_VOICE_P2P_STUN_URLS:-}
+ FLUXER_LIVEKIT_TURN_SERVERS: ${FLUXER_LIVEKIT_TURN_SERVERS:-[]}
FLUXER_VOICE_JOIN_ALLOW_PRIVATE_ENDPOINTS: ${FLUXER_VOICE_JOIN_ALLOW_PRIVATE_ENDPOINTS:-}
FLUXER_VOICE_HEALTH_INTERVAL_MS: ${FLUXER_VOICE_HEALTH_INTERVAL_MS:-}
diff --git a/fluxer_rexctl/internal/stack/files/voice/voice-edge.compose.yml b/fluxer_rexctl/internal/stack/files/voice/voice-edge.compose.yml
index 1ae108dc8..c7bef0a63 100644
--- a/fluxer_rexctl/internal/stack/files/voice/voice-edge.compose.yml
+++ b/fluxer_rexctl/internal/stack/files/voice/voice-edge.compose.yml
@@ -32,6 +32,7 @@ services:
networks:
voice:
name: ${FLUXER_VOICE_NETWORK:-fluxer-voice}
+ enable_ipv6: ${FLUXER_VOICE_NETWORK_IPV6:-false}
volumes:
edge-data:
diff --git a/fluxer_rexctl/internal/stack/files/voice/voice.compose.yml b/fluxer_rexctl/internal/stack/files/voice/voice.compose.yml
index 549d3bd99..366b2f6f5 100644
--- a/fluxer_rexctl/internal/stack/files/voice/voice.compose.yml
+++ b/fluxer_rexctl/internal/stack/files/voice/voice.compose.yml
@@ -23,9 +23,12 @@ services:
udp_port: ${FLUXER_VOICE_UDP_PORT:-7882}
use_external_ip: ${FLUXER_VOICE_USE_EXTERNAL_IP:-true}
node_ip: "${FLUXER_VOICE_NODE_IP:-}"
+ ips:
+ includes: ${FLUXER_VOICE_ICE_IPS:-[]}
stun_servers:
- ${FLUXER_LIVEKIT_STUN_PRIMARY:-stun.l.google.com:19302}
- ${FLUXER_LIVEKIT_STUN_SECONDARY:-stun1.l.google.com:19302}
+ turn_servers: ${FLUXER_LIVEKIT_TURN_SERVERS:-[]}
turn:
enabled: false
webhook:
diff --git a/fluxer_rexctl/internal/voice/net.go b/fluxer_rexctl/internal/voice/net.go
index 75cd733d3..4da9fcccf 100644
--- a/fluxer_rexctl/internal/voice/net.go
+++ b/fluxer_rexctl/internal/voice/net.go
@@ -7,6 +7,7 @@ import (
"context"
"crypto/tls"
"crypto/x509"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -30,6 +31,16 @@ var cloudflareRanges = []string{
"173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
"108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17",
"162.158.0.0/15", "104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
+ "2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
+ "2a06:98c0::/29", "2c0f:f248::/32",
+}
+
+var unusableIPv6 = []netip.Prefix{
+ netip.MustParsePrefix("fc00::/7"),
+ netip.MustParsePrefix("2002::/16"),
+ netip.MustParsePrefix("2001::/32"),
+ netip.MustParsePrefix("2001:db8::/32"),
+ netip.MustParsePrefix("3fff::/20"),
}
func IsCloudflare(addr string) bool {
@@ -76,16 +87,146 @@ func DefaultRouteIPv4() string {
return ""
}
+func DefaultRouteIPv6() string {
+ conn, err := net.Dial("udp6", "[2001:db8::1]:9")
+ if err != nil {
+ return ""
+ }
+ defer conn.Close()
+ if a, ok := conn.LocalAddr().(*net.UDPAddr); ok {
+ return a.IP.String()
+ }
+ return ""
+}
+
+func TemporaryIPv6() []string {
+ data, err := os.ReadFile("/proc/net/if_inet6")
+ if err != nil {
+ return nil
+ }
+ return parseIfInet6(string(data))
+}
+
+func parseIfInet6(data string) []string {
+ var out []string
+ for _, line := range strings.Split(data, "\n") {
+ fields := strings.Fields(line)
+ if len(fields) < 5 || len(fields[0]) != 32 {
+ continue
+ }
+ flags, err := strconv.ParseUint(fields[4], 16, 32)
+ if err != nil || flags&0x01 == 0 {
+ continue
+ }
+ raw, err := hex.DecodeString(fields[0])
+ if err != nil {
+ continue
+ }
+ if ip, ok := netip.AddrFromSlice(raw); ok {
+ out = append(out, ip.String())
+ }
+ }
+ return out
+}
+
+func IsIPv4(addr string) bool {
+ ip, err := netip.ParseAddr(addr)
+ return err == nil && ip.Is4()
+}
+
+func IsIPv6(addr string) bool {
+ ip, err := netip.ParseAddr(addr)
+ return err == nil && ip.Is6() && !ip.Is4In6()
+}
+
+func GlobalIPv6(addr string) bool {
+ ip, err := netip.ParseAddr(addr)
+ if err != nil || !ip.Is6() || ip.Is4In6() || ip.Zone() != "" || !ip.IsGlobalUnicast() {
+ return false
+ }
+ for _, p := range unusableIPv6 {
+ if p.Contains(ip) {
+ return false
+ }
+ }
+ return true
+}
+
+func UsableIPv6(addr string, local, temporary []string) bool {
+ if !GlobalIPv6(addr) {
+ return false
+ }
+ ip := netip.MustParseAddr(addr).String()
+ return slices.Contains(local, ip) && !slices.Contains(temporary, ip)
+}
+
+func StableIPv6(observed string, local, temporary []string) string {
+ if UsableIPv6(observed, local, temporary) {
+ return netip.MustParseAddr(observed).String()
+ }
+ seen, err := netip.ParseAddr(observed)
+ if err != nil || !GlobalIPv6(observed) {
+ return ""
+ }
+ net64, _ := seen.Prefix(64)
+ for _, a := range local {
+ if ip, err := netip.ParseAddr(a); err == nil && net64.Contains(ip) && UsableIPv6(a, local, temporary) {
+ return ip.String()
+ }
+ }
+ return ""
+}
+
+func MachineIPv6(observed string) string {
+ local, temporary := InterfaceAddresses(), TemporaryIPv6()
+ if observed != "" {
+ return StableIPv6(observed, local, temporary)
+ }
+ return StableIPv6(DefaultRouteIPv6(), local, temporary)
+}
+
+const (
+ FamilyNone = ""
+ FamilyIPv4 = "ipv4"
+ FamilyIPv6 = "ipv6"
+ FamilyDual = "dual"
+)
+
+func FamilyOf(ipv4, ipv6 string) string {
+ switch {
+ case ipv4 != "" && ipv6 != "":
+ return FamilyDual
+ case ipv4 != "":
+ return FamilyIPv4
+ case ipv6 != "":
+ return FamilyIPv6
+ }
+ return FamilyNone
+}
+
+func NodeIPs(ipv4, ipv6 string) string {
+ var parts []string
+ for _, ip := range []string{ipv4, ipv6} {
+ if ip != "" {
+ parts = append(parts, ip)
+ }
+ }
+ return strings.Join(parts, ",")
+}
+
type Reachability struct {
PublicIPv4 string
+ PublicIPv6 string
BehindNAT bool
CGNAT bool
}
-func Assess(publicIPv4 string, local []string, routeIP string) Reachability {
- r := Reachability{PublicIPv4: publicIPv4}
+func (r Reachability) Family() string { return FamilyOf(r.PublicIPv4, r.PublicIPv6) }
+
+func Assess(publicIPv4, publicIPv6 string, local []string, routeIP string) Reachability {
+ r := Reachability{PublicIPv4: publicIPv4, PublicIPv6: publicIPv6}
r.BehindNAT = publicIPv4 != "" && !slices.Contains(local, publicIPv4)
- r.CGNAT = IsCGNAT(routeIP)
+ r.CGNAT = publicIPv4 != "" && IsCGNAT(routeIP)
return r
}
@@ -96,7 +237,12 @@ type DNSAnswer struct {
type Resolver func(ctx context.Context, name string) (DNSAnswer, error)
-var dohServers = []string{"https://1.1.1.1/dns-query", "https://8.8.8.8/resolve"}
+var dohServers = []string{
+ "https://1.1.1.1/dns-query",
+ "https://8.8.8.8/resolve",
+ "https://[2606:4700:4700::1111]/dns-query",
+ "https://[2001:4860:4860::8888]/resolve",
+}
func PublicLookup(hc *http.Client) Resolver {
return func(ctx context.Context, name string) (DNSAnswer, error) {
@@ -172,28 +318,71 @@ const (
HostnameElsewhere
HostnameIPv6Elsewhere
HostnameProxied
+ HostnameIPv4Front
+ HostnameNoA
+ HostnameNoAAAA
)
-func CheckHostname(answer DNSAnswer, publicIPv4 string, ownIPv6 []string) HostnameCheck {
+func (h HostnameCheck) Usable() bool {
+ return h == HostnameOK || h == HostnameIPv4Front || h == HostnameNoA || h == HostnameNoAAAA
+}
+
+func CheckHostname(answer DNSAnswer, publicIPv4, publicIPv6 string, ownIPv6 []string) HostnameCheck {
+ all := slices.Concat(answer.A, answer.AAAA)
+ if len(all) > 0 && !slices.ContainsFunc(all, func(a string) bool { return !IsCloudflare(a) }) {
+ return HostnameProxied
+ }
+ own := func(a string) bool {
+ ip, err := netip.ParseAddr(a)
+ if err != nil {
+ return false
+ }
+ return slices.ContainsFunc(append([]string{publicIPv6}, ownIPv6...), func(o string) bool {
+ p, err := netip.ParseAddr(o)
+ return err == nil && p == ip
+ })
+ }
+ if publicIPv4 == "" && publicIPv6 != "" {
+ if len(answer.AAAA) == 0 {
+ return HostnameMissing
+ }
+ if !all6(answer.AAAA, own) {
+ return HostnameElsewhere
+ }
+ if len(answer.A) > 0 {
+ return HostnameIPv4Front
+ }
+ return HostnameOK
+ }
if len(answer.A) == 0 {
+ if publicIPv6 != "" && len(answer.AAAA) > 0 && all6(answer.AAAA, own) {
+ return HostnameNoA
+ }
return HostnameMissing
}
- if !slices.ContainsFunc(answer.A, func(a string) bool { return !IsCloudflare(a) }) {
- return HostnameProxied
- }
for _, a := range answer.A {
if a != publicIPv4 {
return HostnameElsewhere
}
}
- for _, a := range answer.AAAA {
- if !slices.Contains(ownIPv6, a) {
- return HostnameIPv6Elsewhere
- }
+ if !all6(answer.AAAA, own) {
+ return HostnameIPv6Elsewhere
+ }
+ if publicIPv6 != "" && len(answer.AAAA) == 0 {
+ return HostnameNoAAAA
}
return HostnameOK
}
+func all6(records []string, own func(string) bool) bool {
+ for _, a := range records {
+ if !own(a) {
+ return false
+ }
+ }
+ return true
+}
+
func HTTPBase(endpoint string) string {
u, err := url.Parse(endpoint)
if err != nil {
diff --git a/fluxer_rexctl/internal/voice/node.go b/fluxer_rexctl/internal/voice/node.go
index 80ae8cd26..d4d86937d 100644
--- a/fluxer_rexctl/internal/voice/node.go
+++ b/fluxer_rexctl/internal/voice/node.go
@@ -17,6 +17,8 @@ import (
"strconv"
"strings"
"time"
+
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
)
const (
@@ -24,6 +26,8 @@ const (
NodeAudience = "fluxer-voice-node"
NodePath = "/voice/node"
nodeTokenLife = 2 * time.Minute
+
+ AddressesCodeVersion = 2
)
const (
@@ -180,6 +184,7 @@ func deref(list *[]string) []string {
type PreviewRequest struct {
PublicIPv4 string `json:"public_ipv4,omitempty"`
+ PublicIPv6 string `json:"public_ipv6,omitempty"`
RegionID string `json:"region_id,omitempty"`
CPUCount int `json:"cpu_count,omitempty"`
MemoryBytes uint64 `json:"memory_bytes,omitempty"`
@@ -196,15 +201,16 @@ type Preview struct {
New bool `json:"new"`
Source string `json:"source"`
} `json:"region"`
- Latitude *float64 `json:"latitude"`
- Longitude *float64 `json:"longitude"`
- Hostname *string `json:"hostname"`
- SuggestedHostname string `json:"suggested_hostname"`
- SoftLimit *int `json:"soft_connection_limit"`
- WebhookURL string `json:"webhook_url"`
- APICodeVersion int `json:"api_code_version"`
- Release string `json:"release"`
- ExpiresAt string `json:"expires_at"`
+ Latitude *float64 `json:"latitude"`
+ Longitude *float64 `json:"longitude"`
+ Hostname *string `json:"hostname"`
+ SuggestedHostname string `json:"suggested_hostname"`
+ SoftLimit *int `json:"soft_connection_limit"`
+ WebhookURL string `json:"webhook_url"`
+ APICodeVersion int `json:"api_code_version"`
+ Release string `json:"release"`
+ ExpiresAt string `json:"expires_at"`
+ TurnServers []settings.TurnServer `json:"turn_servers"`
}
type JoinRequest struct {
@@ -217,6 +223,7 @@ type JoinRequest struct {
Longitude *float64 `json:"longitude,omitempty"`
SoftLimit int `json:"soft_connection_limit,omitempty"`
PublicIPv4 string `json:"public_ipv4,omitempty"`
+ PublicIPv6 string `json:"public_ipv6,omitempty"`
}
type Joined struct {
@@ -228,15 +235,18 @@ type Joined struct {
}
type Node struct {
- RegionID string `json:"region_id"`
- ServerID string `json:"server_id"`
- Endpoint string `json:"endpoint"`
- Latitude *float64 `json:"latitude"`
- Longitude *float64 `json:"longitude"`
- IsActive bool `json:"is_active"`
- Draining bool `json:"draining"`
- SoftLimit *int `json:"soft_connection_limit"`
- Health struct {
+ RegionID string `json:"region_id"`
+ ServerID string `json:"server_id"`
+ Endpoint string `json:"endpoint"`
+ Latitude *float64 `json:"latitude"`
+ Longitude *float64 `json:"longitude"`
+ IsActive bool `json:"is_active"`
+ Draining bool `json:"draining"`
+ SoftLimit *int `json:"soft_connection_limit"`
+ Turn *[]settings.TurnServer `json:"turn_servers"`
+ PublicIPv4 *string `json:"public_ipv4"`
+ PublicIPv6 *string `json:"public_ipv6"`
+ Health struct {
Status string `json:"status"`
CheckedAt *string `json:"checked_at"`
Error *string `json:"error"`
@@ -256,10 +266,12 @@ func (c *Client) Join(ctx context.Context, api, token string, req JoinRequest) (
}
type NodeUpdate struct {
- Endpoint *string `json:"endpoint,omitempty"`
- Draining *bool `json:"draining,omitempty"`
- Latitude *float64 `json:"latitude,omitempty"`
- Longitude *float64 `json:"longitude,omitempty"`
+ Endpoint *string `json:"endpoint,omitempty"`
+ PublicIPv4 *string `json:"public_ipv4,omitempty"`
+ PublicIPv6 *string `json:"public_ipv6,omitempty"`
+ Draining *bool `json:"draining,omitempty"`
+ Latitude *float64 `json:"latitude,omitempty"`
+ Longitude *float64 `json:"longitude,omitempty"`
}
func (c *Client) GetNode(ctx context.Context, nodeURL, key, secret string) (*Node, error) {
diff --git a/fluxer_rexctl/internal/voice/transport.go b/fluxer_rexctl/internal/voice/transport.go
index 793beb402..0831e3d47 100644
--- a/fluxer_rexctl/internal/voice/transport.go
+++ b/fluxer_rexctl/internal/voice/transport.go
@@ -10,14 +10,17 @@ import (
"encoding/json"
"errors"
"fmt"
+ "net"
"net/http"
"net/url"
"strings"
"sync"
+ "syscall"
"time"
"github.com/pion/webrtc/v4"
"golang.org/x/net/websocket"
+ "google.golang.org/protobuf/encoding/protowire"
)
type Transport string
@@ -27,11 +30,64 @@ const (
TransportTCP Transport = "tcp"
)
+type MediaPath struct {
+ Transport Transport
+ Family string
+ Relay bool
+}
+
+func (p MediaPath) Name() string {
+ family := "IPv4"
+ if p.Family == FamilyIPv6 {
+ family = "IPv6"
+ }
+ if p.Relay {
+ return "IPv4 through TURN"
+ }
+ return strings.ToUpper(string(p.Transport)) + " over " + family
+}
+
+func (p MediaPath) networkTypes() []webrtc.NetworkType {
+ switch {
+ case p.Relay:
+ return []webrtc.NetworkType{webrtc.NetworkTypeUDP4, webrtc.NetworkTypeUDP6}
+ case p.Transport == TransportTCP && p.Family == FamilyIPv6:
+ return []webrtc.NetworkType{webrtc.NetworkTypeTCP6}
+ case p.Transport == TransportTCP:
+ return []webrtc.NetworkType{webrtc.NetworkTypeTCP4}
+ case p.Family == FamilyIPv6:
+ return []webrtc.NetworkType{webrtc.NetworkTypeUDP6}
+ }
+ return []webrtc.NetworkType{webrtc.NetworkTypeUDP4}
+}
+
+func MediaPaths(server, tester string) []MediaPath {
+ var out []MediaPath
+ for _, fam := range []string{FamilyIPv4, FamilyIPv6} {
+ if hasFamily(server, fam) && hasFamily(tester, fam) {
+ out = append(out, MediaPath{TransportUDP, fam, false}, MediaPath{TransportTCP, fam, false})
+ }
+ }
+ return out
+}
+
+func hasFamily(set, fam string) bool { return set == fam || set == FamilyDual }
+
var (
ErrTransportTimeout = errors.New("voice: no media path within the time limit")
ErrTokenRejected = errors.New("voice: the server rejected the access token")
+ ErrNoTurn = errors.New("voice: the instance gives clients no TURN server over UDP or TCP")
+ ErrSignalling = errors.New("voice: signalling connection failed")
+ errNotIPv4 = errors.New("voice: not an IPv4 address")
)
+func ipv4Only(network, _ string, _ syscall.RawConn) error {
+ if network != "tcp4" {
+ return errNotIPv4
+ }
+ return nil
+}
+
const TestRoomPrefix = "rexctl-test-"
func TestRoom() string {
@@ -95,7 +151,85 @@ func rtcURL(endpoint, token string) (string, string, error) {
return u.String(), origin, nil
}
-func TestTransport(ctx context.Context, endpoint, token string, transport Transport, insecure bool, timeout time.Duration) error {
+func protoBytes(b []byte, num protowire.Number) [][]byte {
+ var out [][]byte
+ for len(b) > 0 {
+ n, typ, l := protowire.ConsumeTag(b)
+ if l < 0 {
+ return out
+ }
+ b = b[l:]
+ if typ == protowire.BytesType {
+ v, m := protowire.ConsumeBytes(b)
+ if m < 0 {
+ return out
+ }
+ if n == num {
+ out = append(out, v)
+ }
+ b = b[m:]
+ continue
+ }
+ m := protowire.ConsumeFieldValue(n, typ, b)
+ if m < 0 {
+ return out
+ }
+ b = b[m:]
+ }
+ return out
+}
+
+func protoString(b []byte, num protowire.Number) string {
+ values := protoBytes(b, num)
+ if len(values) == 0 {
+ return ""
+ }
+ return string(values[len(values)-1])
+}
+
+func relayServers(ctx context.Context, raw []byte) []webrtc.ICEServer {
+ var out []webrtc.ICEServer
+ for _, join := range protoBytes(raw, 1) {
+ for _, s := range protoBytes(join, 5) {
+ var urls []string
+ for _, u := range protoBytes(s, 1) {
+ if v4 := ipv4TurnURL(ctx, string(u)); v4 != "" {
+ urls = append(urls, v4)
+ }
+ }
+ if len(urls) > 0 {
+ out = append(out, webrtc.ICEServer{URLs: urls, Username: protoString(s, 2), Credential: protoString(s, 3)})
+ }
+ }
+ }
+ return out
+}
+
+func ipv4TurnURL(ctx context.Context, raw string) string {
+ rest, ok := strings.CutPrefix(raw, "turn:")
+ if !ok {
+ return ""
+ }
+ hostPort, query, _ := strings.Cut(rest, "?")
+ h, port, err := net.SplitHostPort(hostPort)
+ if err != nil {
+ h, port = hostPort, "3478"
+ }
+ if !IsIPv4(h) {
+ addrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip4", h)
+ if err != nil || len(addrs) == 0 {
+ return ""
+ }
+ h = addrs[0].Unmap().String()
+ }
+ out := "turn:" + net.JoinHostPort(h, port)
+ if query != "" {
+ out += "?" + query
+ }
+ return out
+}
+
+func TestTransport(ctx context.Context, endpoint, token string, path MediaPath, insecure bool, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
target, origin, err := rtcURL(endpoint, token)
@@ -107,21 +241,73 @@ func TestTransport(ctx context.Context, endpoint, token string, transport Transp
return err
}
cfg.TlsConfig = &tls.Config{InsecureSkipVerify: insecure}
+ if path.Relay {
+ cfg.Dialer = &net.Dialer{Control: ipv4Only}
+ }
ws, err := cfg.DialContext(ctx)
if err != nil {
return dialFailed(ctx, target, insecure, err)
}
defer ws.Close()
- se := webrtc.SettingEngine{}
- if transport == TransportTCP {
- se.SetNetworkTypes([]webrtc.NetworkType{webrtc.NetworkTypeTCP4})
- } else {
- se.SetNetworkTypes([]webrtc.NetworkType{webrtc.NetworkTypeUDP4})
+ joined := make(chan []byte, 1)
+ answers := make(chan webrtc.SessionDescription, 1)
+ candidates := make(chan webrtc.ICECandidateInit, 32)
+ readErr := make(chan error, 1)
+ go func() {
+ first := true
+ for {
+ var raw []byte
+ if err := websocket.Message.Receive(ws, &raw); err != nil {
+ readErr <- err
+ return
+ }
+ if first {
+ first = false
+ joined <- raw
+ continue
+ }
+ var msg signalMessage
+ if json.Unmarshal(raw, &msg) != nil {
+ continue
+ }
+ switch {
+ case msg.Answer != nil:
+ answers <- *msg.Answer
+ case msg.Trickle != nil && publisherTarget(msg.Trickle.Target):
+ var init webrtc.ICECandidateInit
+ if json.Unmarshal([]byte(msg.Trickle.CandidateInit), &init) == nil {
+ candidates <- init
+ }
+ case msg.Leave != nil:
+ readErr <- errors.New("voice: the server ended the session")
+ return
+ }
+ }
+ }()
+
+ var join []byte
+ select {
+ case join = <-joined:
+ case err := <-readErr:
+ return fmt.Errorf("voice: signalling closed before joining: %w", err)
+ case <-ctx.Done():
+ return fmt.Errorf("voice: no join response: %w", ctx.Err())
}
+
+ conf := webrtc.Configuration{}
+ if path.Relay {
+ conf.ICEServers = relayServers(ctx, join)
+ if len(conf.ICEServers) == 0 {
+ return ErrNoTurn
+ }
+ conf.ICETransportPolicy = webrtc.ICETransportPolicyRelay
+ }
+ se := webrtc.SettingEngine{}
+ se.SetNetworkTypes(path.networkTypes())
se.SetICEMulticastDNSMode(0)
api := webrtc.NewAPI(webrtc.WithSettingEngine(se))
- pc, err := api.NewPeerConnection(webrtc.Configuration{})
+ pc, err := api.NewPeerConnection(conf)
if err != nil {
return err
}
@@ -163,49 +349,6 @@ func TestTransport(ctx context.Context, endpoint, token string, transport Transp
return err
}
- joined := make(chan struct{})
- answers := make(chan webrtc.SessionDescription, 1)
- candidates := make(chan webrtc.ICECandidateInit, 32)
- readErr := make(chan error, 1)
- go func() {
- first := true
- for {
- var raw []byte
- if err := websocket.Message.Receive(ws, &raw); err != nil {
- readErr <- err
- return
- }
- if first {
- first = false
- close(joined)
- continue
- }
- var msg signalMessage
- if json.Unmarshal(raw, &msg) != nil {
- continue
- }
- switch {
- case msg.Answer != nil:
- answers <- *msg.Answer
- case msg.Trickle != nil && publisherTarget(msg.Trickle.Target):
- var init webrtc.ICECandidateInit
- if json.Unmarshal([]byte(msg.Trickle.CandidateInit), &init) == nil {
- candidates <- init
- }
- case msg.Leave != nil:
- readErr <- errors.New("voice: the server ended the session")
- return
- }
- }
- }()
-
- select {
- case <-joined:
- case err := <-readErr:
- return fmt.Errorf("voice: signalling closed before joining: %w", err)
- case <-ctx.Done():
- return fmt.Errorf("voice: no join response: %w", ctx.Err())
- }
offer, err := pc.CreateOffer(nil)
if err != nil {
return err
@@ -240,9 +383,9 @@ func TestTransport(ctx context.Context, endpoint, token string, transport Transp
case <-connected:
return nil
case <-failed:
- return noMediaPath(transport)
+ return noMediaPath(path)
case err := <-readErr:
- return signallingClosed(transport, haveAnswer, err)
+ return signallingClosed(path, haveAnswer, err)
case <-ctx.Done():
return ErrTransportTimeout
}
@@ -269,16 +412,16 @@ func dialFailed(ctx context.Context, target string, insecure bool, err error) er
}
}
}
- return fmt.Errorf("voice: signalling connection failed: %w", err)
+ return fmt.Errorf("%w: %w", ErrSignalling, err)
}
-func noMediaPath(transport Transport) error {
- return fmt.Errorf("voice: no %s media path to the server", strings.ToUpper(string(transport)))
+func noMediaPath(path MediaPath) error {
+ return fmt.Errorf("voice: no media path to the server with %s", path.Name())
}
-func signallingClosed(transport Transport, answered bool, err error) error {
+func signallingClosed(path MediaPath, answered bool, err error) error {
if answered {
- return noMediaPath(transport)
+ return noMediaPath(path)
}
return fmt.Errorf("voice: signalling closed: %w", err)
}
diff --git a/fluxer_rexctl/internal/voice/voice.go b/fluxer_rexctl/internal/voice/voice.go
index 458882b10..7ca68d046 100644
--- a/fluxer_rexctl/internal/voice/voice.go
+++ b/fluxer_rexctl/internal/voice/voice.go
@@ -98,6 +98,7 @@ type Env struct {
HTTPPort int
HTTPBind string
NodeIP string
+ NodeIPv6 string
BindIP string
Image string
Memory string
@@ -105,11 +106,13 @@ type Env struct {
StunPrimary string
StunSecondary string
LogLevel string
+ TurnServers string
}
func (e Env) Values() map[string]string {
useExternal := "true"
- if e.NodeIP != "" {
+ nodeIP := NodeIPs(e.NodeIP, e.NodeIPv6)
+ if nodeIP != "" {
useExternal = "false"
}
out := map[string]string{
@@ -120,7 +123,8 @@ func (e Env) Values() map[string]string {
"FLUXER_VOICE_NETWORK": e.Network,
"FLUXER_VOICE_TCP_PORT": strconv.Itoa(e.TCPPort),
"FLUXER_VOICE_UDP_PORT": strconv.Itoa(e.UDPPort),
- "FLUXER_VOICE_NODE_IP": e.NodeIP,
+ "FLUXER_VOICE_NODE_IP": nodeIP,
+ "FLUXER_VOICE_ICE_IPS": iceIPs(e.NodeIP, e.NodeIPv6),
"FLUXER_VOICE_USE_EXTERNAL_IP": useExternal,
"FLUXER_VOICE_BIND_IP": e.BindIP,
"FLUXER_LIVEKIT_IMAGE": orDefault(e.Image, DefaultImage),
@@ -136,6 +140,7 @@ func (e Env) Values() map[string]string {
"FLUXER_LIVEKIT_STUN_PRIMARY": e.StunPrimary,
"FLUXER_LIVEKIT_STUN_SECONDARY": e.StunSecondary,
"FLUXER_LIVEKIT_LOG_LEVEL": e.LogLevel,
+ "FLUXER_LIVEKIT_TURN_SERVERS": e.TurnServers,
} {
if v != "" {
out[k] = v
@@ -144,6 +149,16 @@ func (e Env) Values() map[string]string {
return out
}
+func iceIPs(v4, v6 string) string {
+ switch {
+ case v4 != "" && v6 == "":
+ return `["0.0.0.0/0"]`
+ case v4 == "" && v6 != "":
+ return `["::/0"]`
+ }
+ return "[]"
+}
+
func (e Env) File() []byte {
values := e.Values()
keys := make([]string, 0, len(values))
@@ -153,11 +168,18 @@ func (e Env) File() []byte {
slices.Sort(keys)
var b strings.Builder
for _, k := range keys {
- fmt.Fprintf(&b, "%s=%s\n", k, values[k])
+ fmt.Fprintf(&b, "%s=%s\n", k, envValue(values[k]))
}
return []byte(b.String())
}
+func envValue(v string) string {
+ if strings.ContainsAny(v, " \"'{}[]$#\\") && !strings.Contains(v, "'") {
+ return "'" + v + "'"
+ }
+ return v
+}
+
func orDefault(v, fallback string) string {
if strings.TrimSpace(v) == "" {
return fallback
diff --git a/packages/config/src/MasterConfig.ts b/packages/config/src/MasterConfig.ts
index 63f0f9084..5876fcc89 100644
--- a/packages/config/src/MasterConfig.ts
+++ b/packages/config/src/MasterConfig.ts
@@ -15,6 +15,16 @@ export const TAG_STYLE_NAMES = ['none', 'random'] as const;
type TagStyleName = (typeof TAG_STYLE_NAMES)[number];
type SmtpTlsModeName = 'implicit' | 'starttls' | 'opportunistic' | 'none';
+export interface VoiceTurnServerConfig {
+ host: string;
+ port: number;
+ protocol: 'udp' | 'tcp' | 'tls';
+ username?: string;
+ credential?: string;
+ secret?: string;
+ ttl?: number;
+}
+
interface SmtpConfig {
host: string;
port: number;
@@ -219,6 +229,7 @@ export interface MasterConfig {
longitude: number;
};
p2p_stun_urls?: Array<string>;
+ turn_servers?: Array<VoiceTurnServerConfig>;
join_allow_private_endpoints?: boolean;
health_interval_ms?: number;
};
diff --git a/packages/config/src/config_loader/EnvironmentOverrides.ts b/packages/config/src/config_loader/EnvironmentOverrides.ts
index df9975e74..eb8742646 100644
--- a/packages/config/src/config_loader/EnvironmentOverrides.ts
+++ b/packages/config/src/config_loader/EnvironmentOverrides.ts
@@ -188,6 +188,7 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {
FLUXER_LIVEKIT_BUNDLED: {path: ['integrations', 'voice', 'bundled'], parse: parseBoolean},
FLUXER_LIVEKIT_DEFAULT_REGION: {path: ['integrations', 'voice', 'default_region'], parse: parseJsonObject},
FLUXER_VOICE_P2P_STUN_URLS: {path: ['integrations', 'voice', 'p2p_stun_urls'], parse: parseCsv},
+ FLUXER_LIVEKIT_TURN_SERVERS: {path: ['integrations', 'voice', 'turn_servers'], parse: parseTurnServers},
FLUXER_VOICE_JOIN_ALLOW_PRIVATE_ENDPOINTS: {
path: ['integrations', 'voice', 'join_allow_private_endpoints'],
parse: parseBoolean,
@@ -481,6 +482,49 @@ function parseJsonArray(raw: string): Array<unknown> {
throw new Error('must be a JSON array');
}
+const TURN_SERVER_FIELDS = new Set(['host', 'port', 'protocol', 'username', 'credential', 'secret', 'ttl']);
+
+function optionalString(entry: ConfigObject, key: string, n: number): string | undefined {
+ const value = entry[key];
+ if (value === undefined) return undefined;
+ if (typeof value !== 'string' || value === '') throw new Error(`entry ${n} must have a text ${key}`);
+ return value;
+}
+
+function parseTurnServers(raw: string): Array<ConfigObject> {
+ if (raw.trim() === '') return [];
+ return parseJsonArray(raw).map((entry, index) => {
+ const n = index + 1;
+ if (!isConfigObject(entry)) throw new Error(`entry ${n} must be a JSON object`);
+ for (const key of Object.keys(entry)) {
+ if (!TURN_SERVER_FIELDS.has(key)) throw new Error(`entry ${n} has the unknown field ${key}`);
+ }
+ const {host, port, protocol, ttl} = entry;
+ if (typeof host !== 'string' || host === '' || /[:/\s[\]]/.test(host)) {
+ throw new Error(`entry ${n} must have a host that is a hostname or an IPv4 address`);
+ }
+ if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535) {
+ throw new Error(`entry ${n} must have a port from 1 to 65535`);
+ }
+ if (protocol !== 'udp' && protocol !== 'tcp' && protocol !== 'tls') {
+ throw new Error(`entry ${n} must have the protocol udp, tcp or tls`);
+ }
+ const username = optionalString(entry, 'username', n);
+ const credential = optionalString(entry, 'credential', n);
+ const secret = optionalString(entry, 'secret', n);
+ if (secret !== undefined && (username !== undefined || credential !== undefined)) {
+ throw new Error(`entry ${n} must have a secret, or a username and credential, and not both`);
+ }
+ if ((username === undefined) !== (credential === undefined)) {
+ throw new Error(`entry ${n} must have both a username and a credential`);
+ }
+ if (ttl !== undefined && (secret === undefined || typeof ttl !== 'number' || !Number.isInteger(ttl) || ttl < 1)) {
+ throw new Error(`entry ${n} may have a ttl only with a secret, as a whole number of seconds`);
+ }
+ return entry;
+ });
+}
+
function parseInteger(raw: string): number {
const trimmed = raw.trim();
if (!/^-?\d+$/.test(trimmed)) {
diff --git a/packages/constants/src/AppConstants.ts b/packages/constants/src/AppConstants.ts
index 46a1fb5fa..03f96e852 100644
--- a/packages/constants/src/AppConstants.ts
+++ b/packages/constants/src/AppConstants.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-export const API_CODE_VERSION = 1;
+export const API_CODE_VERSION = 2;
export const DEFAULT_API_VERSION = 1;
export const FLUXERBOT_ID = '0';
export const ME = '@me';
diff --git a/packages/schema/src/domains/admin/AdminVoiceSchemas.ts b/packages/schema/src/domains/admin/AdminVoiceSchemas.ts
index 2a2663fe8..aa5be1b7d 100644
--- a/packages/schema/src/domains/admin/AdminVoiceSchemas.ts
+++ b/packages/schema/src/domains/admin/AdminVoiceSchemas.ts
@@ -60,6 +60,10 @@ export const VoiceRegionAdminResponse = z.object({
export type VoiceRegionAdminResponse = z.infer<typeof VoiceRegionAdminResponse>;
+export const VoicePublicIpv4Type = z.ipv4().describe('Public IPv4 address LiveKit gives to clients');
+
+export const VoicePublicIpv6Type = z.ipv6().describe('Public IPv6 address LiveKit gives to clients');
+
export const VoiceServerAdminResponse = z.object({
region_id: z.string().describe('ID of the region this server belongs to'),
server_id: z.string().describe('Unique identifier for the voice server'),
@@ -80,6 +84,14 @@ export const VoiceServerAdminResponse = z.object({
.nullable()
.describe('URL the API uses for the control API and health checks, or null to use the endpoint'),
draining: z.boolean().describe('Whether placement sends new calls elsewhere while calls on this server finish'),
+ public_ipv4: z
+ .string()
+ .nullable()
+ .describe('Public IPv4 address LiveKit gives to clients, or null when none is known'),
+ public_ipv6: z
+ .string()
+ .nullable()
+ .describe('Public IPv6 address LiveKit gives to clients, or null when none is known'),
health: VoiceServerHealthResponse.describe('Health of the server as this API node last saw it'),
duplicate_api_key: z.boolean().describe('Whether another server uses the same API key'),
created_at: z.string().nullable().describe('ISO 8601 timestamp when the server was created'),
@@ -191,6 +203,8 @@ export const CreateVoiceServerRequestBody = z
.optional()
.default(false)
.describe('Whether placement sends new calls elsewhere while calls on this server finish'),
+ public_ipv4: VoicePublicIpv4Type.nullable().optional().default(null),
+ public_ipv6: VoicePublicIpv6Type.nullable().optional().default(null),
})
.refine((data) => areServerCoordinatesPaired(data.latitude, data.longitude), {
error: 'Latitude and longitude must both be provided or both be omitted',
@@ -236,6 +250,8 @@ export const UpdateVoiceServerRequestBody = z
.boolean()
.optional()
.describe('Whether placement sends new calls elsewhere while calls on this server finish'),
+ public_ipv4: VoicePublicIpv4Type.nullable().optional(),
+ public_ipv6: VoicePublicIpv6Type.nullable().optional(),
})
.refine((data) => areServerCoordinatesPaired(data.latitude, data.longitude), {
error: 'Latitude and longitude must both be provided or both be omitted',
diff --git a/packages/schema/src/domains/voice/VoiceNodeSchemas.ts b/packages/schema/src/domains/voice/VoiceNodeSchemas.ts
index e57c208ef..35d6396ed 100644
--- a/packages/schema/src/domains/voice/VoiceNodeSchemas.ts
+++ b/packages/schema/src/domains/voice/VoiceNodeSchemas.ts
@@ -1,6 +1,10 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {VoiceServerHealthResponse} from '@fluxer/schema/src/domains/admin/AdminVoiceSchemas';
+import {
+ VoicePublicIpv4Type,
+ VoicePublicIpv6Type,
+ VoiceServerHealthResponse,
+} from '@fluxer/schema/src/domains/admin/AdminVoiceSchemas';
import {createStringType} from '@fluxer/schema/src/primitives/SchemaPrimitives';
import {z} from 'zod';
@@ -14,8 +18,25 @@ const LatitudeType = z.number().min(-90).max(90);
const LongitudeType = z.number().min(-180).max(180);
const SoftLimitType = z.number().int().min(1).max(2147483647);
+export const VoiceTurnServer = z.object({
+ host: z.string().describe('Hostname or IPv4 address of the TURN server'),
+ port: z.number().int().describe('Port of the TURN server'),
+ protocol: z.enum(['udp', 'tcp', 'tls']).describe('Transport clients use to connect to the TURN server'),
+ username: z.string().optional().describe('Fixed TURN username'),
+ credential: z.string().optional().describe('Fixed TURN password'),
+ secret: z.string().optional().describe('Shared secret LiveKit signs short-lived TURN credentials with'),
+ ttl: z.number().int().optional().describe('Lifetime of the signed credentials in seconds'),
+});
+
+export type VoiceTurnServer = z.infer<typeof VoiceTurnServer>;
+
+const TurnServersType = z
+ .array(VoiceTurnServer)
+ .describe('TURN servers of the instance, for the LiveKit configuration of the voice server');
+
export const VoiceJoinPreviewRequest = z.object({
public_ipv4: z.ipv4().nullable().optional().describe('Public IPv4 address of the voice machine'),
+ public_ipv6: z.ipv6().nullable().optional().describe('Public IPv6 address of the voice machine'),
region_id: VoiceIdType.optional().describe('Existing region the operator asked for'),
cpu_count: z.number().int().min(1).max(4096).optional().describe('CPU count of the voice machine'),
memory_bytes: z.number().int().min(0).optional().describe('Memory of the voice machine in bytes'),
@@ -45,6 +66,7 @@ export const VoiceJoinPreviewResponse = z.object({
api_code_version: z.number().int().describe('Version of the API server code'),
release: z.string().describe('Fluxer release of the API, or an empty string for a development build'),
expires_at: z.string().describe('ISO 8601 timestamp when the token stops working'),
+ turn_servers: TurnServersType,
});
export type VoiceJoinPreviewResponse = z.infer<typeof VoiceJoinPreviewResponse>;
@@ -60,6 +82,7 @@ export const VoiceJoinRequest = z
longitude: LongitudeType.optional(),
soft_connection_limit: SoftLimitType.optional(),
public_ipv4: z.ipv4().optional().describe('Public IPv4 address of the voice machine'),
+ public_ipv6: z.ipv6().optional().describe('Public IPv6 address of the voice machine'),
})
.refine((data) => (data.latitude === undefined) === (data.longitude === undefined), {
error: 'Latitude and longitude must both be provided or both be omitted',
@@ -74,6 +97,7 @@ export const VoiceJoinResponse = z.object({
endpoint: z.string().describe('Endpoint of the new server'),
webhook_url: z.string().describe('URL the server sends LiveKit webhooks to'),
node_url: z.string().describe('URL of the node routes for this server'),
+ turn_servers: TurnServersType,
});
export type VoiceJoinResponse = z.infer<typeof VoiceJoinResponse>;
@@ -87,6 +111,9 @@ export const VoiceNodeResponse = z.object({
is_active: z.boolean().describe('Whether an admin keeps the server turned on'),
draining: z.boolean().describe('Whether placement sends new calls elsewhere'),
soft_connection_limit: z.number().nullable().describe('Soft connection limit, or null'),
+ public_ipv4: z.string().nullable().describe('Public IPv4 address the server last reported, or null'),
+ public_ipv6: z.string().nullable().describe('Public IPv6 address the server last reported, or null'),
+ turn_servers: TurnServersType,
health: VoiceServerHealthResponse.describe('Health of the server as this API node last saw it'),
});
@@ -99,6 +126,14 @@ export const UpdateVoiceNodeRequest = z
latitude: LatitudeType.nullable().optional(),
longitude: LongitudeType.nullable().optional(),
soft_connection_limit: SoftLimitType.nullable().optional(),
+ public_ipv4: z
+ .union([VoicePublicIpv4Type, z.literal('')])
+ .optional()
+ .describe('Public IPv4 address, or an empty string for none'),
+ public_ipv6: z
+ .union([VoicePublicIpv6Type, z.literal('')])
+ .optional()
+ .describe('Public IPv6 address, or an empty string for none'),
})
.strict()
.refine((data) => (data.latitude === undefined) === (data.longitude === undefined), {
diff --git a/tools/dev/cassandra_target_schema.json b/tools/dev/cassandra_target_schema.json
index dc176606e..e0eda47fa 100644
--- a/tools/dev/cassandra_target_schema.json
+++ b/tools/dev/cassandra_target_schema.json
@@ -10438,6 +10438,14 @@
{
"name": "pinned_soft_limit",
"type": "boolean"
+ },
+ {
+ "name": "public_ipv4",
+ "type": "text"
+ },
+ {
+ "name": "public_ipv6",
+ "type": "text"
}
],
"primary_key": "((region_id), server_id)",