feat(mobile): bind device identities and bound voice usage in 0.1.4 dev

This commit is contained in:
yilsem committed 2026-09-12 12:11:18 +03:00
1 parent ac6687181e
commit 5f75dcc99a
24 files changed
+909 -47

No files matched your search

+32 -9
View File
@@ -1,11 +1,13 @@
import { AccountClient, openPhoneConnection } from './transport.mjs'
import { VoiceSession } from './voice.mjs'
import { DEFAULT_VOICE_LIMITS, voiceLimits, usageLabel } from './voice-usage.mjs'
import { taskState } from './behavior.mjs'
import { parseInvite } from './invite.mjs'
import { InviteScanner } from './qr.mjs'
import { InviteScanner, drawQr } from './qr.mjs'
import { createDeviceIdentity } from './peer-identity.mjs'
const $ = id => document.getElementById(id)
if (globalThis.Capacitor?.isNativePlatform()) globalThis.Capacitor.registerPlugin('MobileSecrets')
let credentials = {}, account, connection, selected, approval, voice, pendingTask, usageTimer, voiceGeneration = 0
let credentials = {}, account, connection, selected, approval, voice, pendingTask, voiceGeneration = 0
let connectedDesktopId = null
let connectionEpoch = 0, selectionEpoch = 0
const status = text => { $('status').textContent = text }
@@ -17,9 +19,13 @@ const scanner = new InviteScanner($('qr-video'), async raw => {
const result = await account.call(`/v1/aiturk/mobile/invites/${invite.inviteId}/claim`, {
secret: invite.secret, display_name: $('device-name').value.trim() })
if (account !== targetAccount || epoch !== connectionEpoch) return
const identity = await createDeviceIdentity(result.device_id)
if (account !== targetAccount || epoch !== connectionEpoch) return
Object.assign(credentials, { deviceId: result.device_id, deviceToken: result.device_token,
pairingId: result.pairing_id, preferredDesktopId: invite.desktopId })
pairingId: result.pairing_id, preferredDesktopId: invite.desktopId,
desktopFingerprints: { [invite.desktopId]: invite.desktopFingerprint }, localFingerprint: identity.fingerprint })
await saveCredentials()
showPhoneIdentity()
$('pair-code').textContent = `Bilgisayarda bekleyen telefonu getirip şu kodu onaylayın: ${result.user_code}`
status('QR okundu. Bilgisayardaki açık telefon onayı bekleniyor.')
})
@@ -28,6 +34,12 @@ action('scan-invite', async () => { if (!account || credentials.deviceId) throw
action('stop-scan', async () => scanner.stop())
$('qr-file').onchange = async event => { try { await scanner.image(event.target.files[0]) } catch (error) { status(error.message) } finally { event.target.value = '' } }
async function saveCredentials() { if (native()) await native().save({ value: JSON.stringify(credentials) }) }
function showPhoneIdentity() {
$('phone-identity').value = credentials.localFingerprint ? JSON.stringify({ kind: 'aiturk-phone-identity', version: 1,
deviceId: credentials.deviceId, pairingId: credentials.pairingId, fingerprint: credentials.localFingerprint }) : ''
$('phone-identity-qr').hidden = !$('phone-identity').value
if ($('phone-identity').value) drawQr($('phone-identity-qr'), $('phone-identity').value)
}
function addText(container, role, text) { const p = document.createElement('p'); p.textContent = `${role}: ${text}`; $(container).append(p); while ($(container).children.length > 150) $(container).firstChild.remove() }
function action(id, work) { $(id).onclick = async () => { $(id).disabled = true; try { await work() } catch (error) { status(error.message) } finally { $(id).disabled = false } } }
function rpc(action, params) { if (!connection) throw new Error('Önce bilgisayara bağlanın.'); return connection.requests.call(action, params) }
@@ -76,6 +88,7 @@ action('logout', async () => {
if (token?.startsWith('tsml_')) await new AccountClient({ accountToken: token }).call('/v1/aiturk/mobile-auth/logout', {})
connectionEpoch++; stopVoice(); connection?.close(); connection = null; selected = null; account = null
credentials = {}; pendingTask = null; await saveCredentials()
showPhoneIdentity()
$('work').hidden = true; $('login-link').hidden = true; $('login-code').textContent = ''; $('pair-code').textContent = ''
status('Bu uygulamanın oturumu kapatıldı. IDE’de başlamış iş kendi çalışma kurallarıyla devam edebilir.')
})
@@ -87,8 +100,11 @@ action('pair', async () => {
if (!credentials.accountToken) throw new Error('Önce AITURK hesabınıza giriş yapın.')
account = new AccountClient(credentials)
const result = await account.call('/v1/aiturk/pairings', { display_name: $('device-name').value.trim(), platform: 'android' })
Object.assign(credentials, { deviceId: result.device_id, deviceToken: result.device_token, pairingId: result.pairing_id })
const identity = await createDeviceIdentity(result.device_id)
Object.assign(credentials, { deviceId: result.device_id, deviceToken: result.device_token, pairingId: result.pairing_id,
localFingerprint: identity.fingerprint })
await saveCredentials()
showPhoneIdentity()
$('pair-code').textContent = `Eşleştirme kimliği:\n${result.pairing_id}\n\nKod: ${result.user_code}\nSon geçerlilik: ${result.expires_at}`
status('Bilgisayardaki açık onay bekleniyor.')
})
@@ -130,14 +146,18 @@ action('select-session', async () => {
for (const [id, choice] of [['allow', 'once'], ['deny', 'deny']]) action(id, async () => { const target = requireSession(); await rpc('approval.respond', { sessionId: target.id, requestId: approval?.requestId, choice }); setApproval(null); status('Yanıt gerçek IDE onayına iletildi.') })
action('save-google', async () => { const key = $('google-key').value.trim(); $('google-key').value = ''; await rpc('google.key.save', { key }); status('Google anahtarı bilgisayarın güvenli kasasına kaydedildi.') })
action('delete-google', async () => { stopVoice(); await rpc('google.key.delete'); status('Google anahtarı bilgisayar kasasından silindi.') })
function stopVoice() { voiceGeneration++; voice?.stop(); voice = null; clearInterval(usageTimer); $('voice-status').textContent = 'Mikrofon kapalı. IDE işi devam edebilir.' }
function stopVoice() { voiceGeneration++; voice?.stop(); voice = null; $('voice-status').textContent = 'Mikrofon kapalı. IDE işi devam edebilir.' }
async function startVoice(microphone) {
if (!$('consent').checked) throw new Error('Önce Google veri ve ücret bilgisini okuyup kabul edin.')
const limits = voiceLimits({ minutes: $('voice-minutes').value, usd: $('voice-budget').value })
// Only non-secret preferences; account and API credentials remain in the
// native vault. No usage history or transcripts are stored here.
try { localStorage.setItem('aiturk.voice-limits', JSON.stringify(limits)) } catch {}
const target = { ...requireSession() }, targetConnection = connection, desktopId = connectedDesktopId
stopVoice(); const generation = voiceGeneration; const token = await rpc('voice.token')
if (generation !== voiceGeneration || document.hidden) return
const started = Date.now()
voice = new VoiceSession({ ...token,
voice = new VoiceSession({ ...token, limits,
onUsage: usage => { if (generation === voiceGeneration) $('usage').textContent = usageLabel(usage, usage.seconds) },
onText: (role, text) => addText('discussion', role, text),
onDraft: (text, intent) => { $('task').value = text; $('intent').value = intent; updatePreview(); status('Asistan görev taslağını hazırladı. Henüz IDE’ye gönderilmedi.') },
onSubmit: async (text, intent) => {
@@ -148,8 +168,7 @@ async function startVoice(microphone) {
pendingTask = { taskId: crypto.randomUUID(), sessionId: target.id, model: target.model, desktopId, intent, text }
return deliver()
},
onError: status, onState: text => { $('voice-status').textContent = text; if (voice?.stopped) clearInterval(usageTimer) } })
usageTimer = setInterval(() => { $('usage').textContent = `Bu uygulamanın ölçtüğü görüşme süresi: ${Math.floor((Date.now() - started) / 1000)} sn. Google kotası/faturası değildir.` }, 1000)
onError: status, onState: text => { $('voice-status').textContent = text } })
await voice.start(microphone)
}
action('voice-start', () => startVoice(true)); action('voice-text', () => startVoice(false))
@@ -189,4 +208,8 @@ action('disconnect', async () => { connectionEpoch++; stopVoice(); connection?.c
action('revoke', async () => { const data = await account.call('/v1/aiturk/mobile/devices'); const self = data.devices.find(d => d.self); await account.call(`/v1/aiturk/devices/${self.id}/revoke`, { expected_version: self.version }); stopVoice(); connection?.close(); connection = null; credentials = {}; await saveCredentials(); account = null; $('work').hidden = true; status('Bu telefonun erişimi iptal edildi.') })
document.addEventListener('visibilitychange', () => { if (document.hidden) { stopVoice(); scanner.stop() } })
window.addEventListener('pagehide', () => { stopVoice(); scanner.stop(); connection?.close() })
let savedLimits = DEFAULT_VOICE_LIMITS
try { const raw = localStorage.getItem('aiturk.voice-limits'); if (raw) savedLimits = voiceLimits(JSON.parse(raw)) } catch {}
$('voice-minutes').value = savedLimits.minutes; $('voice-budget').value = savedLimits.usd
try { const saved = await native()?.load(); if (saved?.value) { credentials = JSON.parse(saved.value); if (credentials.accountToken) { account = new AccountClient(credentials); status('Kayıtlı cihaz bulundu. Bilgisayarları yenileyerek bağlanın.') } } } catch { status('Android güvenli kasası açılamadı. Hesabınızı yeniden eşleştirin.') }
showPhoneIdentity()
+11 -1
View File
@@ -18,6 +18,10 @@
<video id="qr-video" hidden muted playsinline aria-label="QR kamera önizlemesi"></video>
<label>Alternatif: QR resmi seç<input id="qr-file" type="file" accept="image/*"></label>
<pre id="pair-code" aria-live="polite"></pre><p>Kodu bilgisayardaki AITURK Mobil bağlantı penceresinde onaylayın. Eşleştirme kimliğini kopyalayabilirsiniz.</p>
<label>Bu telefonun kimlik belgesi<textarea id="phone-identity" readonly aria-describedby="phone-identity-help"></textarea></label>
<canvas id="phone-identity-qr" hidden aria-label="Telefonun sertifika kimliği QR kodu"></canvas>
<p>Kimlik QR kodunun ekran görüntüsünü kendi bilgisayarınıza aktarabilir ve bilgisayarda “Telefon kimliği QR resmi” alanından açabilirsiniz. Onayı ayrıca bilgisayarda verin.</p>
<p id="phone-identity-help">Bu belgenin tamamını kendi bilgisayarınızdaki “Telefondan alınan kimlik belgesi” alanına aktarın. Bu, özel anahtar değil; onaylayacağınız telefonun sertifika kimliğidir. Başkasının gönderdiği belgeyi onaylamayın.</p>
<button id="devices" class="secondary">Onaydan sonra bilgisayarları bul</button>
<label>Bilgisayar<select id="desktop"><option value="">Önce cihazları bulun</option></select></label><button id="connect">Bilgisayara bağlan</button>
</section><section id="work" hidden><h2>2. IDE konuşması</h2><button id="sessions" class="secondary">Konuşmaları yenile</button>
@@ -28,9 +32,15 @@
<p><a href="https://aistudio.google.com/apikey" target="_blank" rel="noreferrer">Kendi Google AI Studio anahtarınızı oluşturun</a> · <a href="https://ai.google.dev/gemini-api/docs/pricing" target="_blank" rel="noreferrer">Güncel fiyat ve veri koşulları</a></p>
<label>Google AI Studio API anahtarı<input id="google-key" type="password" autocomplete="off" autocapitalize="none" spellcheck="false"></label><button id="save-google">Bilgisayarın güvenli kasasına kaydet</button><button id="delete-google" class="secondary">Google anahtarını sil</button>
<label><input id="consent" type="checkbox">Google'a veri aktarımını ve projemde ücret oluşabileceğini anladım.</label>
<fieldset><legend>Her yeni ses / yazışma oturumu için durdurma sınırı</legend>
<label>En fazla dakika (1–10)<input id="voice-minutes" type="number" min="1" max="10" step="1" value="10" inputmode="numeric"></label>
<label>Tahmini maliyet sınırı (USD)<input id="voice-budget" type="number" min="0.01" max="10" step="0.01" value="0.25" inputmode="decimal"></label>
<p>Sınırlar bir sonraki bağlantıda uygulanır; her yeni bağlantıda sayaç sıfırlanır. Tahmin ücretli tarifeyi kullanır; ücretsiz kotanız ölçülmez. Görüşme geçmişi ve metin tokenları da ücret oluşturabilir. Bildirim gecikirse veya tarife değişirse gerçek ücret sınırı aşabilir. İki dakika kullanım bildirimi gelmezse bağlantı kapanır. Otomatik yeniden bağlanılmaz; IDE işi durdurulmaz.</p>
</fieldset>
<div class="row"><button id="voice-start">Sesle konuş</button><button id="voice-text" class="secondary">Asistanla yazış</button></div>
<div class="row"><button id="voice-stop" class="secondary">Ses görüşmesini kapat</button><button id="silence" class="secondary">Asistanın sesini kes</button></div>
<p id="voice-status" role="status">Mikrofon kapalı.</p><small id="usage">Yerel süre: 0 sn. Google kalan kotası ölçülmüyor.</small>
<p id="voice-status" role="status">Mikrofon kapalı.</p><small id="usage">Henüz kullanım yok. Google kalan kotası ve faturası ölçülmüyor.</small>
<p><small>Tahmin tarifesi: Gemini 3.1 Flash Live Preview · 8 Eylül 2026. Vergi, indirim ve bildirilmemiş kullanım dahil değildir.</small></p>
<div id="discussion" class="history" aria-label="Google asistanı görüşmesi"></div>
<label>Asistanla fikrini geliştir<textarea id="idea" placeholder="Bu uygulamayı nasıl geliştirebiliriz?"></textarea></label><button id="discuss">Asistana yaz</button>
<h2>IDE'ye gönderilecek görev</h2><p>Fikir konuşması kendi başına iş başlatmaz. Aşağıdaki metnin tamamı seçili IDE konuşmasına gönderilir. Araştırma seçeneği değişiklik izni vermez.</p>
+5 -2
View File
@@ -1,11 +1,14 @@
import { normalizeFingerprint } from './peer-identity.mjs'
export function parseInvite(raw, now = Date.now()) {
if (typeof raw !== 'string' || raw.length > 800) throw new Error('Bu bir AITURK eşleştirme QR kodu değil.')
let data
try { data = JSON.parse(raw) } catch { throw new Error('Bu bir AITURK eşleştirme QR kodu değil.') }
if (!data || data.kind !== 'aiturk-mobile-invite' || data.version !== 1 ||
if (!data || data.kind !== 'aiturk-mobile-invite' || data.version !== 2 ||
!/^[0-9a-f-]{36}$/.test(data.inviteId) || !/^[0-9a-f-]{36}$/.test(data.desktopId) ||
!/^[A-Za-z0-9_-]{43}$/.test(data.secret) || !Number.isFinite(Date.parse(data.expiresAt)) ||
Date.parse(data.expiresAt) <= now || Date.parse(data.expiresAt) > now + 11 * 60000)
throw new Error('QR geçersiz veya süresi dolmuş. Bilgisayarda yeni kod oluşturun.')
return { inviteId: data.inviteId, desktopId: data.desktopId, secret: data.secret }
return { inviteId: data.inviteId, desktopId: data.desktopId, secret: data.secret,
desktopFingerprint: normalizeFingerprint(data.desktopFingerprint) }
}
+99
View File
@@ -0,0 +1,99 @@
// Standard WebRTC identities; private key material stays inside RTCCertificate.
// Pairing must persist the public fingerprint separately in its trusted record.
const DATABASE = 'aiturk-mobile-peer-identities-v1'
const STORE = 'certificates'
const failure = () => new Error('Cihaz kimliği doğrulanamadı. Mevcut eşleşmeyi kullanmayın; yeniden açık eşleştirme gerekli.')
function deviceKey(deviceId) {
if (typeof deviceId !== 'string' || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(deviceId)) throw failure()
return deviceId.toLowerCase()
}
export function normalizeFingerprint(value) {
if (typeof value !== 'string' || !/^(?:[0-9a-f]{2}:){31}[0-9a-f]{2}$/i.test(value)) throw failure()
return value.toUpperCase()
}
export function parsePhoneIdentity(raw, pairingId) {
if (typeof raw !== 'string' || raw.length > 700) throw failure()
let value
try { value = JSON.parse(raw) } catch { throw failure() }
if (value?.kind !== 'aiturk-phone-identity' || value.version !== 1 || value.pairingId !== pairingId) throw failure()
return { deviceId: deviceKey(value.deviceId), fingerprint: normalizeFingerprint(value.fingerprint) }
}
function identity(certificate) {
if (!(certificate instanceof RTCCertificate) || !Number.isFinite(certificate.expires) || certificate.expires <= Date.now()) throw failure()
const fingerprints = certificate.getFingerprints().filter(item => item.algorithm === 'sha-256')
if (fingerprints.length !== 1) throw failure()
return { certificate, fingerprint: normalizeFingerprint(fingerprints[0].value), expires: certificate.expires }
}
async function database() {
return new Promise((resolve, reject) => {
let blocked = false
const request = indexedDB.open(DATABASE, 1)
request.onupgradeneeded = () => request.result.createObjectStore(STORE)
request.onerror = () => reject(failure())
request.onblocked = () => { blocked = true; reject(failure()) }
request.onsuccess = () => {
if (blocked) { request.result.close(); return }
request.result.onversionchange = () => request.result.close()
resolve(request.result)
}
})
}
// Call only during an explicit NEW device pairing, never to repair a missing key.
// The read/write transaction chooses one winner across simultaneous windows.
export async function createDeviceIdentity(deviceId) {
const key = deviceKey(deviceId)
const candidate = await RTCPeerConnection.generateCertificate({ name: 'ECDSA', namedCurve: 'P-256' })
const db = await database()
try {
return await new Promise((resolve, reject) => {
const tx = db.transaction(STORE, 'readwrite'), store = tx.objectStore(STORE)
let selected
const read = store.get(key)
read.onsuccess = () => {
try {
selected = identity(read.result === undefined ? candidate : read.result)
if (read.result === undefined) store.add(candidate, key)
} catch { tx.abort() }
}
tx.oncomplete = () => resolve(selected)
tx.onabort = tx.onerror = () => reject(failure())
})
} finally { db.close() }
}
// Never generates or replaces a certificate. A lost key or changed public pin
// requires a new explicit pairing, not trust-on-first-use during reconnect.
export async function loadDeviceIdentity(deviceId, expectedFingerprint) {
const key = deviceKey(deviceId), expected = normalizeFingerprint(expectedFingerprint)
const db = await database()
try {
const certificate = await new Promise((resolve, reject) => {
const tx = db.transaction(STORE), request = tx.objectStore(STORE).get(key)
tx.oncomplete = () => resolve(request.result)
tx.onabort = tx.onerror = () => reject(failure())
})
const result = identity(certificate)
if (result.fingerprint !== expected) throw failure()
return result
} finally { db.close() }
}
// Application data channels use a single bundled DTLS identity. Check every
// advertised fingerprint before setRemoteDescription; native DTLS then verifies
// that the actual peer possesses the matching private key.
export function assertRemoteIdentity(sdp, trustedFingerprint) {
const expected = normalizeFingerprint(trustedFingerprint)
if (typeof sdp !== 'string' || sdp.length > 131072) throw failure()
const lines = sdp.split(/\r?\n/).filter(line => line.startsWith('a=fingerprint:'))
if (!lines.length) throw failure()
for (const line of lines) {
const match = /^a=fingerprint:sha-256 ((?:[0-9a-f]{2}:){31}[0-9a-f]{2})$/i.exec(line)
if (!match || normalizeFingerprint(match[1]) !== expected) throw failure()
}
}
+3 -2
View File
@@ -2,8 +2,9 @@
<p class="eyebrow">AITURK MOBİL · 8 EYLÜL 2026</p><h1>Verilerinizin yolu.</h1>
<p>Bu geliştirme sürümü Android için hazırlanmıştır. Gerçek telefon, ayrı internet ağları ve Google ses görüşmesi kabul testleri tamamlanmadan genel kullanıma hazır sayılmaz.</p>
<h2>Hesap ve cihazlar</h2><p>AITURK hesap API anahtarı ve iptal edilebilir cihaz sırrı telefonda Android Keystore ile, bilgisayarda Windows güvenli kasasıyla korunur. Eşleştirme kodları sürelidir; telefon bu bilgisayarda açıkça onaylanır. Cihaz iptali yeni işlemleri engeller; açık bağlantı da en geç bir sonraki yetki kontrolünde kapanır.</p>
<h2>Telefon ve bilgisayar</h2><p>Görev ve anahtar aktarımı WebRTC DTLS veri kanalından geçer. AITURK bağlantı hizmeti hesap/cihaz kimliklerini ve ağ bağlantı açıklamalarını (SDP, IP adresleri dahil) görür. Kayıtlar 90 saniye içinde yenilenmezse sona erer ve sonraki bağlantı sorgusunda temizlenir. Hizmet görev veya Google anahtarını saklamaz. Sinyalleşme hizmetine eş kimliğini doğru doğrulaması için güvenilir; kötü niyetli sinyalleşme sunucusuna karşı ayrıca doğrulanmış parmak izi koruması henüz yoktur.</p>
<h2>Telefon ve bilgisayar</h2><p>Görev ve anahtar aktarımı WebRTC DTLS veri kanalından geçer. AITURK bağlantı hizmeti hesap/cihaz kimliklerini ve ağ bağlantı açıklamalarını (SDP, IP adresleri dahil) görür. Kayıtlar 90 saniye içinde yenilenmezse sona erer ve sonraki bağlantı sorgusunda temizlenir. Hizmet görev veya Google anahtarını saklamaz. Cihaz sertifikaları yerel tarayıcı veritabanında; güvenilen karşı cihaz parmak izleri Android/Windows kasasında saklanır. Telefon bilgisayar kimliğini QR'dan, bilgisayar telefon kimliğini sizin aktarıp onayladığınız belgeden alır. Bağlantı bu kimliklerle karşılaştırılır; değişen veya kayıp kimlik yeniden açık eşleştirme gerektirir. Başkasının gönderdiği QR veya kimlik belgesini onaylamayın. Bu koruma ele geçirilmiş telefon/bilgisayarın güvenliğini sağlamaz; gerçek cihaz kabulü henüz tamamlanmadı.</p>
<h2>Google ses asistanı</h2><p>Kalıcı Google anahtarınız yalnız eşleştirdiğiniz bilgisayarda saklanır. Telefon kısa ömürlü erişimle doğrudan Google'a bağlanır. Ses ve Google görüşme metni Google tarafından işlenir; telefon-bilgisayar şifrelemesi Google'dan gizlilik sağlamaz. Ücretsiz katman verileri ürün geliştirme için kullanılabilir. Ücretli Google projesindeki çağrılar ücretlidir. Güncel koşullar için Google AI Studio ve Gemini API fiyat sayfasını okuyun.</p>
<h2>Geçmiş ve silme</h2><p>Ses kayıtları bu uygulama tarafından dosyaya yazılmaz. Görüşme metni ekranda geçici bellektedir. Temizleme düğmesi yerel görünümü temizler; aktif Google oturumunun bağlamı görüşme kapandığında bırakılır. IDE'ye gönderdiğiniz görev IDE'nin kendi geçmiş ve saklama kurallarına tabidir. Görev kimliği, içerik özeti ve gönderim durumu tekrar çalıştırmayı önlemek için bilgisayarda saklanır; görev metni bu kayıtta tutulmaz.</p>
<h2>Bilinen sınırlar</h2><p>TURN hizmeti henüz sağlanmadığından bazı farklı ağlarda bağlantı kurulamaz. QR tarama, tek dokunuşla hesap girişi, doğrulanmış maliyet tahmini, otomatik sesli görev yürütme ve gerçek cihaz değerlendirmesi henüz tamamlanmamıştır. Ses aracı şu anda görünür görev taslağı üretir; kullanıcı gönder düğmesiyle IDE'ye iletir. Bu sayfa eksik özellikleri çalışıyor olarak sunmaz.</p>
<h2>Maliyet kontrolü</h2><p>Google'ın bildirdiği tokenlar ücretli liste tarifesiyle tahmin edilir. Geçmiş bağlamı tekrar ücretlenebilir. Eksik ayrıntılar fiyat aralığıyla gösterilir; bildirilmemiş kullanım, vergi ve indirimler dahil değildir. Seçtiğiniz süre veya tahmini sınır dolduğunda yalnız Google bağlantısı kapanır; IDE işi devam edebilir. İki dakika kullanım bildirimi gelmezse bağlantı kapatılır. Bildirim gecikmesi ve tarife değişiklikleri nedeniyle gerçek ücret sınırı aşabilir. Her yeni oturumda sayaç sıfırlanır. Yalnız süre ve sınır tercihi cihazda saklanır; burada fatura ya da kalan ücretsiz kota ölçülmez.</p>
<h2>Bilinen sınırlar</h2><p>QR ve tarayıcı üzerinden kısa kodla hesap girişi geliştirildi; canlı hizmete dağıtılmadı. Asistan görünür taslak hazırlayıp açık uygulama/araştırma talimatıyla seçili IDE konuşmasına görev iletebilir; işlem onaylarını kullanıcı verir. Bu davranış, maliyet sınırı ve bağlantı akışı sentetik yanıtlarla test edildi. Gerçek Android/Google kalite, fatura ve ayrı ağ kabulü henüz yapılmadı. TURN dağıtımı ve kalıcı eş kimliği doğrulaması tamamlanmadan genel kullanıma hazır değildir.</p>
<a href="index.html">Uygulamaya dön</a></main></body></html>
+1
View File
@@ -9,3 +9,4 @@ button.secondary { background:var(--surface); color:var(--text); border:1px soli
.status { border-left:3px solid var(--accent); padding:10px 14px; color:var(--text); background:var(--surface) } .row { display:flex; align-items:center; flex-wrap:wrap; gap:4px } .row button { flex:1 } .history { max-height:340px; overflow:auto; padding:8px 0 } .history p { white-space:pre-wrap; overflow-wrap:anywhere } small { color:var(--muted) } input[type=checkbox] { width:24px; height:24px; vertical-align:middle; margin:0 8px 0 0 }
@media(prefers-reduced-motion:no-preference) { button { transition:background-color .1s } }
canvas,video{max-width:100%;height:auto}video{border-radius:12px}canvas{image-rendering:pixelated}
fieldset { min-width:0; border:1px solid var(--stroke); border-radius:8px; margin:22px 0; padding:14px } legend { max-width:100%; padding:0 6px; font-weight:600 }
+19 -3
View File
@@ -1,3 +1,4 @@
import { normalizeFingerprint, assertRemoteIdentity, loadDeviceIdentity } from './peer-identity.mjs'
export const GATEWAY = 'https://turkservis.online'
async function accountFetch(url, options) {
const plugin = globalThis.Capacitor?.Plugins?.MobileSecrets
@@ -103,10 +104,21 @@ export function rtcConfiguration(iceServers = []) {
}
export async function openPhoneConnection(account, desktopId, onEvent, iceServers = []) {
// Never obtain this trust anchor from the signaling response. It came from
// the QR physically displayed by the desktop and is stored in the phone vault.
const trusted = account.credentials?.desktopFingerprints
if (!trusted || !Object.hasOwn(trusted, desktopId))
throw new Error('Bu bilgisayarın güvenilen cihaz kimliği yok. Bilgisayarda yeni QR oluşturup yeniden eşleştirin.')
const fingerprint = normalizeFingerprint(trusted[desktopId])
const identity = await loadDeviceIdentity(account.credentials.deviceId, account.credentials.localFingerprint)
if (!iceServers.length) iceServers = (await account.call('/v1/aiturk/mobile/ice')).iceServers
const pc = new RTCPeerConnection(rtcConfiguration(iceServers))
const pc = new RTCPeerConnection({ ...rtcConfiguration(iceServers), certificates: [identity.certificate] })
const channel = pc.createDataChannel('aiturk-mobile-v1', { ordered: true })
const requests = new DataRequests(channel, onEvent)
let established = false
const requests = new DataRequests(channel, frame => {
// Failed handshakes surface their actual error, not a later generic close.
if (established || frame.event !== 'disconnected') onEvent(frame)
})
const id = crypto.randomUUID()
let heartbeat, closed = false
const close = () => { closed = true; clearInterval(heartbeat); channel.close(); pc.close() }
@@ -115,7 +127,10 @@ export async function openPhoneConnection(account, desktopId, onEvent, iceServer
await account.call('/v1/aiturk/mobile/channels', { channel_id: id, desktop_id: desktopId, sdp: pc.localDescription.sdp })
for (let attempt = 0; attempt < 35 && !closed; attempt++) {
const answer = await account.call(`/v1/aiturk/mobile/channels/${id}`)
if (answer.sdp) { await pc.setRemoteDescription({ type: 'answer', sdp: answer.sdp }); break }
if (answer.sdp) {
assertRemoteIdentity(answer.sdp, fingerprint)
await pc.setRemoteDescription({ type: 'answer', sdp: answer.sdp }); break
}
await new Promise(resolve => setTimeout(resolve, 1500))
}
await new Promise((resolve, reject) => {
@@ -125,6 +140,7 @@ export async function openPhoneConnection(account, desktopId, onEvent, iceServer
channel.addEventListener('close', () => { clearTimeout(timer); reject(new Error('Bağlantı kapandı.')) }, { once: true })
})
heartbeat = setInterval(() => { void account.call(`/v1/aiturk/mobile/channels/${id}/heartbeat`, {}).catch(close) }, 15000)
established = true
return { requests, close, pc, id }
} catch (error) { close(); throw error }
}
+87
View File
@@ -0,0 +1,87 @@
// Paid-list-price estimate, not a quota lookup or an invoice. Sources checked
// 2026-09-08: https://ai.google.dev/gemini-api/docs/pricing and /api/live.
// Live prompt counts include history billed again on each generation request.
export const VOICE_PRICING = Object.freeze({
model: 'gemini-3.1-flash-live-preview', checked: '2026-09-08',
input: Object.freeze({ TEXT: 0.75, AUDIO: 3, IMAGE: 1, VIDEO: 1 }),
output: Object.freeze({ TEXT: 4.5, AUDIO: 12 }),
})
export const DEFAULT_VOICE_LIMITS = Object.freeze({ minutes: 10, usd: 0.25 })
export function voiceLimits(value = DEFAULT_VOICE_LIMITS) {
const minutes = Number(value.minutes), usd = Number(value.usd)
// Ephemeral credentials currently expire after ten minutes; don't offer a
// duration the connection cannot actually support.
if (!Number.isInteger(minutes) || minutes < 1 || minutes > 10 ||
!Number.isFinite(usd) || usd < 0.01 || usd > 10)
throw new Error('Ses sınırı 1–10 dakika ve 0,01–10 USD arasında olmalı.')
return { minutes, usd }
}
function count(value) {
if (value === undefined) return 0 // protobuf omits zero-valued fields
if (!Number.isSafeInteger(value) || value < 0) throw new Error('Geçersiz kullanım sayacı.')
return value
}
function modalityCost(total, details, rates) {
if (details !== undefined && !Array.isArray(details)) throw new Error('Geçersiz kullanım ayrıntısı.')
let tokens = 0, low = 0, high = 0, uncertain = false
const minimum = Math.min(...Object.values(rates)), maximum = Math.max(...Object.values(rates))
for (const detail of details || []) {
const n = count(detail?.tokenCount), rate = Object.hasOwn(rates, detail?.modality) ? rates[detail.modality] : undefined
tokens += n; low += n * (rate ?? minimum); high += n * (rate ?? maximum)
if (rate === undefined && n) uncertain = true
}
if (tokens > total) throw new Error('Kullanım toplamı ayrıntılarla uyuşmuyor.')
const remainder = total - tokens
return { low: low + remainder * minimum, high: high + remainder * maximum,
uncertain: uncertain || remainder > 0 }
}
export function estimateUsage(metadata, model) {
if (model !== VOICE_PRICING.model) throw new Error('Bu ses modelinin fiyatı doğrulanmadı.')
if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata) ||
!['promptTokenCount', 'responseTokenCount', 'totalTokenCount'].some(k => k in metadata))
throw new Error('Google kullanım bilgisi eksik.')
const prompt = count(metadata.promptTokenCount), response = count(metadata.responseTokenCount)
const thoughts = count(metadata.thoughtsTokenCount), tools = count(metadata.toolUsePromptTokenCount)
const total = count(metadata.totalTokenCount)
if (metadata.totalTokenCount !== undefined && total < prompt + response)
throw new Error('Kullanım toplamı sayaçlarla uyuşmuyor.')
const input = modalityCost(prompt, metadata.promptTokensDetails, VOICE_PRICING.input)
const output = modalityCost(response, metadata.responseTokensDetails, VOICE_PRICING.output)
const tool = modalityCost(tools, metadata.toolUsePromptTokensDetails, VOICE_PRICING.input)
// Thinking/tool counters may overlap aggregate counts. Keep a range instead
// of promising a falsely precise bill or silently treating them as free.
const residual = Math.max(0, total - prompt - response)
const extraUpper = Math.max(residual * 12, thoughts * 4.5 + tool.high)
return { lowUsd: (input.low + output.low) / 1e6,
highUsd: (input.high + output.high + extraUpper) / 1e6,
uncertain: input.uncertain || output.uncertain || extraUpper > 0 || count(metadata.cachedContentTokenCount) > 0 }
}
export class VoiceUsage {
constructor(model, limits = DEFAULT_VOICE_LIMITS) {
this.model = model; this.limits = voiceLimits(limits)
this.lowUsd = 0; this.highUsd = 0; this.reports = 0; this.uncertain = false
}
add(metadata) {
// Do not de-duplicate equal reports: distinct requests can have equal
// token counts, and subtracting prior prompt counts loses history cost.
const cost = estimateUsage(metadata, this.model)
this.lowUsd += cost.lowUsd; this.highUsd += cost.highUsd
this.uncertain ||= cost.uncertain; this.reports++
return this.snapshot()
}
snapshot() {
return { lowUsd: this.lowUsd, highUsd: this.highUsd, reports: this.reports,
uncertain: this.uncertain, reached: this.highUsd >= this.limits.usd }
}
}
export function usageLabel(usage, seconds) {
const cost = !usage.reports ? 'Maliyet henüz bilinmiyor; Google kullanım bildirimi bekleniyor.' :
`Bildirilen kullanımın ücretli tarife tahmini: ${usage.lowUsd.toFixed(4)}–${usage.highUsd.toFixed(4)} USD${usage.uncertain ? ' (eksik ayrıntılar için aralık)' : ''}.`
return `Yerel süre: ${seconds} sn. ${cost} Gerçek fatura veya kalan ücretsiz kota değildir; IDE modeli dahil değildir.`
}
+30 -7
View File
@@ -1,4 +1,5 @@
import { ASSISTANT_INSTRUCTION, VOICE_TOOLS, VoiceDispatchGate, taskText } from './behavior.mjs'
import { VoiceUsage, VOICE_PRICING } from './voice-usage.mjs'
export function pcm16(samples, sampleRate) {
const length = Math.floor(samples.length * 16000 / sampleRate)
@@ -12,16 +13,23 @@ export function pcm16(samples, sampleRate) {
}
export class VoiceSession {
constructor({ token, model, onText, onDraft, onSubmit, onError, onState }) {
Object.assign(this, { token, model, onText, onDraft, onSubmit, onError, onState })
constructor({ token, model, onText, onDraft, onSubmit, onError, onState, onUsage, limits, now = () => performance.now() }) {
Object.assign(this, { token, model, onText, onDraft, onSubmit, onError, onState, onUsage, now })
this.usage = new VoiceUsage(model, limits)
this.sources = new Set(); this.stopped = false; this.nextPlayback = 0
this.dispatchGate = new VoiceDispatchGate(); this.receiveChain = Promise.resolve()
this.audioTranscript = ''; this.preparedDraft = null
}
async start(microphone = true) {
if (this.stopped) return
if (this.model !== VOICE_PRICING.model) throw new Error('Bu ses modelinin maliyet tarifesi doğrulanmadı; bağlantı açılmadı.')
this.startedAt = this.now(); this.lastUsageAt = this.startedAt
this.usageTimer = setInterval(() => this.checkLimits(), 1000)
this.checkLimits()
try {
this.context = new AudioContext()
await this.context.resume()
if (this.stopped) return
if (microphone) {
this.stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true } })
if (this.stopped) { this.stream.getTracks().forEach(t => t.stop()); return }
@@ -45,11 +53,21 @@ export class VoiceSession {
this.socket.onmessage = event => { this.receiveChain = this.receiveChain.then(() => this.receive(event)).catch(() => { this.onError('Ses yanıtı işlenemedi.'); this.stop() }) }
this.socket.onerror = () => { this.onError('Google ses bağlantısı kurulamadı. Anahtar, model erişimi ve kotayı kontrol edin.'); this.stop() }
this.socket.onclose = () => this.stop()
this.limit = setTimeout(() => { this.onText('bilgi', 'Bu görüşmenin 10 dakikalık yerel süre sınırı doldu. Bu bir fatura üst sınırı değildir.'); this.stop() }, 10 * 60000)
this.setupTimer = setTimeout(() => { if (!this.ready) { this.onError('Google ses başlangıcı zaman aşımına uğradı.'); this.stop() } }, 20000)
} catch { this.onError('Mikrofon veya ses bağlantısı açılamadı. Android mikrofon iznini kontrol edin; yazıyla devam edebilirsiniz.'); this.stop() }
}
send(frame) { if (this.socket?.readyState === 1) this.socket.send(JSON.stringify(frame)) }
checkLimits() {
if (this.stopped) return
const seconds = Math.floor((this.now() - this.startedAt) / 1000)
const usage = this.usage.snapshot()
this.onUsage?.({ ...usage, seconds })
let reason
if (usage.reached) reason = 'Belirlediğiniz tahmini maliyet sınırına ulaşıldı.'
else if (seconds >= this.usage.limits.minutes * 60) reason = 'Belirlediğiniz yerel görüşme süresi doldu.'
else if (this.now() - this.lastUsageAt >= 120000) reason = 'İki dakikadır Google kullanım bildirimi alınamadı; maliyet izlenemediği için görüşme kapatıldı.'
if (reason) { this.onText?.('bilgi', `${reason} Bu kontrol kesin fatura üst sınırı değildir.`); this.stop(reason) }
}
send(frame) { if (!this.stopped && this.socket?.readyState === 1) this.socket.send(JSON.stringify(frame)) }
text(text) {
if (!this.ready) throw new Error('Ses asistanı bağlantısı henüz hazır değil.')
this.interruptPlayback()
@@ -69,6 +87,11 @@ export class VoiceSession {
async receive(event) {
const data = JSON.parse(event.data instanceof Blob ? await event.data.text() : event.data)
if (this.stopped) return
if (data.usageMetadata) {
try { this.usage.add(data.usageMetadata); this.lastUsageAt = this.now(); this.checkLimits() }
catch { this.onError?.('Google kullanım bilgisi hesaplanamadı; maliyet takibi güvenilir olmadığı için ses görüşmesi kapatıldı.'); this.stop(); return }
if (this.stopped) return
}
if (data.setupComplete) { this.ready = true; clearTimeout(this.setupTimer); this.onState('Google asistanı bağlı.'); return }
if (data.error) { this.onError('Google ses isteğini reddetti. AI Studio erişim ve kotanızı kontrol edin.'); this.stop(); return }
const content = data.serverContent
@@ -116,12 +139,12 @@ export class VoiceSession {
source.start(start); this.nextPlayback = start + buffer.duration
}
interruptPlayback() { for (const source of this.sources) { try { source.stop() } catch {} }; this.sources.clear(); this.nextPlayback = 0 }
stop() {
stop(reason = '') {
if (this.stopped) return
this.stopped = true; this.ready = false; clearTimeout(this.limit); clearTimeout(this.setupTimer)
this.stopped = true; this.ready = false; clearInterval(this.usageTimer); clearTimeout(this.setupTimer)
this.dispatchGate.invalidate()
this.interruptPlayback(); this.stream?.getTracks().forEach(t => t.stop())
this.input?.disconnect(); this.capture?.disconnect(); this.silence?.disconnect()
this.socket?.close(); void this.context?.close(); this.onState('Ses görüşmesi kapalı. IDE işi devam edebilir.')
this.socket?.close(); void this.context?.close(); this.onState?.(`${reason ? reason + ' ' : ''}Ses görüşmesi kapalı. IDE işi devam edebilir.`)
}
}