'Sign in first.'],401); $user = (string)$user; $_SESSION['widget_csrf'] ??= bin2hex(random_bytes(32)); $csrf = $_SESSION['widget_csrf']; session_write_close(); if ($_SERVER['REQUEST_METHOD'] === 'GET') reply(['csrf_token'=>$csrf]); if ($_SERVER['REQUEST_METHOD'] !== 'POST') reply(['error'=>'Method not allowed.'],405); if (!hash_equals($csrf, $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '')) reply(['error'=>'Invalid CSRF token.'],403); $input = file_get_contents('php://input', false, null, 0, 4097); if (strlen($input) > 4096) reply(['error'=>'Request too large.'],413); try { $body = json_decode($input,true,16,JSON_THROW_ON_ERROR); } catch (Throwable $e) { reply(['error'=>'Invalid JSON.'],400); } if (!is_array($body)) reply(['error'=>'Expected an object.'],400); $options = [ 'text_media'=>['mode'=>'full_chat','non_live_voice'=>true], 'voice_media'=>['mode'=>'full_chat','non_live_voice'=>false], 'voice_only'=>['mode'=>'voice_only','non_live_voice'=>false] ]; $characters = [ 'maya'=>['name'=>'Maya','age'=>28,'gender'=>'female','voice'=>'eve', 'personality'=>'Warm, friendly, playful and concise.'], 'leo'=>['name'=>'Leo','age'=>30,'gender'=>'male','voice'=>'leo', 'personality'=>'Warm, confident, thoughtful and concise.'] ]; // Optionally add profile_photo_url and character_sheet_url to each definition. // Authorize these two character choices and three options for your users here. $character = $body['character'] ?? 'maya'; $option = $body['option'] ?? 'text_media'; $action = $body['action'] ?? 'create'; if (!is_string($character) || !isset($characters[$character]) || !is_string($option) || !isset($options[$option]) || !in_array($action,['create','sync'],true)) reply(['error'=>'Invalid selection.'],422); $key = getenv('WOWIFY_WIDGET_API_KEY'); $client = getenv('WOWIFY_CLIENT_ID'); $origin = getenv('WIDGET_ORIGIN'); $dbPath = getenv('WIDGET_DB_PATH'); if (!$key || !$client || !$origin || !$dbPath) reply(['error'=>'Widget server is not configured.'],503); // WIDGET_DB_PATH MUST be outside the document root; protect it and its directory. function upstream(string $path, ?array $payload = null): array { global $key, $client; $curl = curl_init('https://models.privatecloud.ai'.$path); curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER=>true, CURLOPT_CONNECTTIMEOUT=>5, CURLOPT_TIMEOUT=>25, CURLOPT_FOLLOWLOCATION=>false, CURLOPT_HTTPHEADER=>['API-Key: '.$key,'Client-ID: '.$client, 'Accept: application/json','Content-Type: application/json'] ]); if ($payload !== null) { curl_setopt($curl,CURLOPT_POST,true); curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($payload,JSON_THROW_ON_ERROR)); } $raw = curl_exec($curl); $status = (int)curl_getinfo($curl,CURLINFO_RESPONSE_CODE); curl_close($curl); if (!is_string($raw)) throw new RuntimeException('Upstream connection failed.'); $data = json_decode($raw,true,64,JSON_THROW_ON_ERROR); if (!is_array($data)) throw new RuntimeException('Invalid upstream response.'); return [$status,$data]; } try { umask(0077); $db = new PDO('sqlite:'.$dbPath,null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]); $db->exec('PRAGMA busy_timeout=5000'); $db->exec('CREATE TABLE IF NOT EXISTS widget_history (user_id TEXT, character_key TEXT, session_id TEXT, snapshot TEXT, PRIMARY KEY(user_id,character_key))'); // Persistent per-user request limit; also apply your app's budget/entitlement checks. $db->exec('CREATE TABLE IF NOT EXISTS widget_limits (user_id TEXT PRIMARY KEY, minute INTEGER, hits INTEGER)'); $minute = intdiv(time(),60); $q=$db->prepare('INSERT INTO widget_limits VALUES(?,?,1) ON CONFLICT(user_id) DO UPDATE SET hits=CASE WHEN minute=excluded.minute THEN hits+1 ELSE 1 END, minute=excluded.minute'); $q->execute([$user,$minute]); $q=$db->prepare('SELECT hits FROM widget_limits WHERE user_id=?'); $q->execute([$user]); if ((int)$q->fetchColumn()>20) reply(['error'=>'Please wait before retrying.'],429); $q=$db->prepare('SELECT * FROM widget_history WHERE user_id=? AND character_key=?'); $q->execute([$user,$character]); $row=$q->fetch(PDO::FETCH_ASSOC); $snapshot = $row && $row['snapshot'] ? json_decode($row['snapshot'],true) : null; if ($row && $row['session_id']) { [$status,$saved]=upstream('/voice-widget/api/sessions/'.$row['session_id'].'/history'); if ($status===200 && is_array($saved['event'] ?? null)) { $snapshot=$saved['event']; $q=$db->prepare('UPDATE widget_history SET snapshot=? WHERE user_id=? AND character_key=? AND session_id=?'); $q->execute([json_encode($snapshot,JSON_THROW_ON_ERROR),$user,$character,$row['session_id']]); } elseif ($status!==200 && !in_array($status,[404,410],true)) { reply(['error'=>'History lookup failed; retry shortly.'],502); } } if ($action==='sync') reply(['saved'=>$snapshot!==null]); $history=[]; // Restore bounded text; retain media in snapshot for your own media viewer. foreach (array_slice($snapshot['messages'] ?? [],-100) as $message) { if (!in_array($message['role'] ?? '',['user','assistant'],true) || !is_string($message['content'] ?? null)) continue; $content=$message['content']; if (strlen($content)>12000) { $content=substr($content,0,12000); while ($content!=='' && !preg_match('//u',$content)) $content=substr($content,0,-1); } $history[]=['role'=>$message['role'],'content'=>$content]; } while (strlen(json_encode($history,JSON_THROW_ON_ERROR))>240000) array_shift($history); [$status,$result]=upstream('/voice-widget/api/sessions',[ ...$options[$option], 'show_balance'=>false, 'origin'=>$origin, 'end_user_id'=>$user, 'top_up_url'=>getenv('WIDGET_TOP_UP_URL') ?: null, 'character'=>$characters[$character], 'history'=>$history, 'branding'=>['name'=>'Your Brand','labels'=>['title'=>'Chat with '.$characters[$character]['name']]] ]); if ($status!==201) reply(['error'=>'Session creation failed.'], in_array($status,[401,402,403,413,422,429],true)?$status:502); if (!preg_match('/^[a-f0-9]{32}$/D',$result['session_id'] ?? '')) throw new RuntimeException('Invalid session response.'); $q=$db->prepare('INSERT INTO widget_history VALUES(?,?,?,?) ON CONFLICT(user_id,character_key) DO UPDATE SET session_id=excluded.session_id,snapshot=excluded.snapshot'); $q->execute([$user,$character,$result['session_id'],$snapshot===null?null:json_encode($snapshot,JSON_THROW_ON_ERROR)]); reply($result,201); } catch (Throwable $e) { // Avoid logging credentials, frame URLs, or private conversation content. reply(['error'=>'Widget service temporarily unavailable.'],502); }