feat(mobile): add Android development client and scoped IDE companion
This commit is contained in:
1 parent
3332458708
commit
9f9f3226a1
84 files changed
+4371
-4
No files matched your search
@@ -6,8 +6,9 @@ import https from 'node:https'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import tls from 'node:tls'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { pathToFileURL, fileURLToPath } from 'node:url'
|
||||
import { startChromeBridge } from './chrome-bridge.mjs'
|
||||
import { createMobileWindow } from './mobile-host.mjs'
|
||||
|
||||
import {
|
||||
app,
|
||||
@@ -17717,6 +17718,10 @@ if (!isPrimaryInstance) {
|
||||
app.exit(0)
|
||||
} else {
|
||||
app.on('second-instance', (_event, argv) => {
|
||||
if (process.platform === 'win32' && argv.includes('--aiturk-mobile')) {
|
||||
openMobileConnectionWindow()
|
||||
return
|
||||
}
|
||||
const url = _extractDeepLink(argv)
|
||||
|
||||
if (url) {
|
||||
@@ -17740,7 +17745,27 @@ app.on('open-url', (event, url) => {
|
||||
handleDeepLink(url)
|
||||
})
|
||||
|
||||
let mobileConnectionWindow: BrowserWindow | null = null
|
||||
function openMobileConnectionWindow() {
|
||||
if (mobileConnectionWindow && !mobileConnectionWindow.isDestroyed()) {
|
||||
mobileConnectionWindow.show()
|
||||
mobileConnectionWindow.focus()
|
||||
return
|
||||
}
|
||||
mobileConnectionWindow = createMobileWindow({
|
||||
directory: path.join(app.getPath('userData'), 'aiturk-mobile'),
|
||||
assets: path.dirname(fileURLToPath(import.meta.url)),
|
||||
resolveBackend: async () => {
|
||||
const profile = primaryProfileKey()
|
||||
if (globalRemoteActive() || profileHasRemoteOverride(profile)) throw new Error('Mobil bağlantı için yerel IDE bağlantısını seçin.')
|
||||
return ensureBackend(profile)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
// Explicit development/beta entry point; never enables remote access on boot.
|
||||
if (process.platform === 'win32' && process.argv.includes('--aiturk-mobile')) openMobileConnectionWindow()
|
||||
if (process.platform === 'win32' && process.env.LOCALAPPDATA) {
|
||||
void startChromeBridge({
|
||||
directory: path.join(process.env.LOCALAPPDATA, 'TurkServis', 'AITURK-IDE'),
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { ChromeGatewayClient } from './chrome-bridge.mjs'
|
||||
|
||||
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex')
|
||||
const identifier = value => typeof value === 'string' && /^[a-zA-Z0-9_.:-]{1,160}$/.test(value)
|
||||
|
||||
// Reserved BEFORE the RPC: a crash/timeout is indeterminate, never safe to resend.
|
||||
// Journal stores only hashes and delivery state, no prompt, token, or result.
|
||||
export class DeliveryJournal {
|
||||
constructor(directory) { this.directory = directory }
|
||||
async reserve(deviceId, taskId, envelope) {
|
||||
if (!identifier(deviceId) || !identifier(taskId)) throw new Error('Geçersiz görev kimliği.')
|
||||
await mkdir(this.directory, { recursive: true })
|
||||
const file = join(this.directory, `${digest([deviceId, taskId])}.json`)
|
||||
const hash = digest(envelope)
|
||||
try {
|
||||
await writeFile(file, JSON.stringify({ hash, state: 'unknown' }), { flag: 'wx', mode: 0o600, flush: true })
|
||||
return { file, hash, fresh: true }
|
||||
} catch (error) {
|
||||
if (error.code !== 'EEXIST') throw error
|
||||
let previous
|
||||
try { previous = JSON.parse(await readFile(file, 'utf8')) }
|
||||
catch { return { file, hash, fresh: false, state: 'unknown' } }
|
||||
if (previous.hash !== hash) throw new Error('Bu görev kimliği farklı bir içerikle kullanılmış.')
|
||||
return { file, hash, fresh: false, state: previous.state }
|
||||
}
|
||||
}
|
||||
async accepted(reservation) {
|
||||
await writeFile(reservation.file, JSON.stringify({ hash: reservation.hash, state: 'accepted' }), { mode: 0o600 })
|
||||
}
|
||||
}
|
||||
|
||||
export class MobileGatewayClient extends ChromeGatewayClient {
|
||||
constructor(resolveBackend, emit, { deviceId, journal, authorize, webSocket } = {}) {
|
||||
super(resolveBackend, emit, webSocket)
|
||||
this.deviceId = deviceId
|
||||
this.journal = journal
|
||||
this.authorize = authorize
|
||||
this.approval = null
|
||||
this.model = null
|
||||
this.chain = Promise.resolve()
|
||||
}
|
||||
|
||||
onEvent(event) {
|
||||
if (!this.selected || event?.session_id !== this.selected.runtimeId) return
|
||||
if (event.type === 'approval.request') {
|
||||
this.approval = this.approvalView(event.payload)
|
||||
this.emit({ event: 'approval.request', sessionId: this.selected.storedId, approval: this.approval })
|
||||
return
|
||||
}
|
||||
if (event.type === 'message.complete') this.approval = null
|
||||
super.onEvent(event)
|
||||
}
|
||||
|
||||
approvalView(payload) {
|
||||
if (!identifier(payload?.request_id) || typeof payload?.command !== 'string') return null
|
||||
// Retain full backend-redacted operation; never approve a clipped preview.
|
||||
if (payload.command.length > 48000) return null
|
||||
return { requestId: payload.request_id, command: payload.command,
|
||||
reason: typeof payload.reason === 'string' ? payload.reason : '',
|
||||
choices: (payload.choices || []).filter(x => ['once', 'deny'].includes(x)) }
|
||||
}
|
||||
|
||||
handle(message) {
|
||||
const result = this.chain.then(() => this.perform(message))
|
||||
this.chain = result.catch(() => {})
|
||||
return result
|
||||
}
|
||||
|
||||
async perform(message) {
|
||||
if (!message || !identifier(message.id)) throw new Error('Geçersiz istek.')
|
||||
await this.authorize()
|
||||
const params = message.params || {}
|
||||
if (message.action === 'session.open') {
|
||||
const list = await super.handle({ id: message.id, action: 'sessions.list' })
|
||||
if (!list.sessions.some(row => row.id === params.sessionId)) throw new Error('Bu IDE konuşması erişilebilir değil.')
|
||||
const result = await super.handle(message)
|
||||
this.model = result.model
|
||||
const resumed = await this.rpc('session.resume', { session_id: params.sessionId, cols: 96,
|
||||
source: 'desktop', defer_history: true, omit_messages: true, ...this.scope() })
|
||||
this.approval = this.approvalView(resumed.pending_approval)
|
||||
return { ...result, approval: this.approval }
|
||||
}
|
||||
if (message.action === 'task.submit') {
|
||||
if (this.selected?.storedId !== params.sessionId || !params.model || params.model !== this.model)
|
||||
throw new Error('Konuşma veya iş modeli değişti. Hedefi tekrar seçin.')
|
||||
if (typeof params.text !== 'string' || !params.text.trim() || params.text.length > 48000)
|
||||
throw new Error('Görev boş olamaz ve 48.000 karakteri aşamaz.')
|
||||
if (!['research', 'execute'].includes(params.intent)) throw new Error('Görev türü gerekli.')
|
||||
// A model change by the desktop between selection and delivery fails closed.
|
||||
const info = await this.rpc('session.resume', { session_id: params.sessionId, cols: 96,
|
||||
source: 'desktop', defer_history: true, omit_messages: true, ...this.scope() })
|
||||
if (info.info?.model !== params.model || info.session_id !== this.selected.runtimeId)
|
||||
throw new Error('IDE hedefi değişti. Konuşmayı yeniden seçin.')
|
||||
const envelope = { sessionId: params.sessionId, profile: this.backend.profile || 'default',
|
||||
model: params.model, text: params.text, intent: params.intent }
|
||||
const reservation = await this.journal.reserve(this.deviceId, params.taskId, envelope)
|
||||
if (!reservation.fresh) return { taskId: params.taskId, state: reservation.state, duplicate: true }
|
||||
await this.authorize()
|
||||
await this.rpc('prompt.submit', { session_id: this.selected.runtimeId, text: params.text, queued: true })
|
||||
await this.journal.accepted(reservation)
|
||||
return { taskId: params.taskId, state: 'accepted' }
|
||||
}
|
||||
if (message.action === 'approval.respond') {
|
||||
if (this.selected?.storedId !== params.sessionId || !this.approval ||
|
||||
params.requestId !== this.approval.requestId || !['once', 'deny'].includes(params.choice) ||
|
||||
!this.approval.choices.includes(params.choice)) throw new Error('Onay artık geçerli değil. IDE durumunu yenileyin.')
|
||||
const result = await this.rpc('approval.respond', { session_id: this.selected.runtimeId,
|
||||
request_id: params.requestId, choice: params.choice, all: false })
|
||||
if (!result.resolved) throw new Error('İşlem onayı daha önce yanıtlanmış veya sona ermiş.')
|
||||
this.approval = null
|
||||
return { resolved: true }
|
||||
}
|
||||
if (!['status', 'sessions.list', 'session.history', 'message.stop'].includes(message.action))
|
||||
throw new Error('Bu mobil işlem desteklenmiyor.')
|
||||
if (message.action === 'session.history' && this.selected?.storedId !== params.sessionId)
|
||||
throw new Error('Önce konuşmayı seçin.')
|
||||
return super.handle(message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { completeIce, rtcConfiguration, sendFrame } from './mobile/transport.mjs'
|
||||
const host = window.mobileHost, $ = id => document.getElementById(id), peers = new Map()
|
||||
const status = text => { $('status').textContent = text }
|
||||
function action(id, work) { $(id).onclick = async () => { $(id).disabled = true; try { await work() } catch (error) { status(error.message) } finally { $(id).disabled = false } } }
|
||||
action('save', async () => { const token = $('account').value; $('account').value = ''; await host.call('account.save', { token }); status('Hesap anahtarı Windows kasasına kaydedildi.') })
|
||||
action('pair', async () => { const pair = await host.call('desktop.pair'); $('code').textContent = `Açılan hesap sayfasında bu kodu onaylayın: ${pair.code}. Süre: ${pair.expiresAt}` })
|
||||
action('approve', async () => { await host.call('phone.approve', { pairingId: $('pairing').value.trim(), code: $('phone-code').value.trim().toUpperCase() }); $('phone-code').value = ''; status('Telefon bu bilgisayarda onaylandı.') })
|
||||
action('refresh', async () => {
|
||||
const data = await host.call('devices'); $('devices').replaceChildren()
|
||||
for (const device of data.devices) {
|
||||
const row = document.createElement('p'), label = document.createElement('span'), button = document.createElement('button')
|
||||
label.textContent = `${device.name} · ${device.platform}${device.self ? ' · Bu bilgisayar' : ''}`
|
||||
button.textContent = 'Cihazı iptal et'
|
||||
button.onclick = async () => { button.disabled = true; try { await host.call('device.revoke', { deviceId: device.id, version: device.version }); row.remove(); status('Cihaz iptal edildi.') } catch (error) { status(error.message); button.disabled = false } }
|
||||
row.append(label, button); $('devices').append(row)
|
||||
}
|
||||
})
|
||||
function close(id) { const entry = peers.get(id); if (!entry) return; peers.delete(id); clearInterval(entry.timer); entry.pc.close(); void host.call('channel.close', { channelId: id }) }
|
||||
host.onEvent(event => { if (event.close) { close(event.channelId); return }; const entry = peers.get(event.channelId); if (entry?.channel?.readyState === 'open') sendFrame(entry.channel, event.frame) })
|
||||
async function connect(offer) {
|
||||
const ice = await host.call('ice')
|
||||
const pc = new RTCPeerConnection(rtcConfiguration(ice.iceServers)), entry = { pc }; peers.set(offer.id, entry)
|
||||
pc.ondatachannel = event => {
|
||||
const channel = event.channel; entry.channel = channel
|
||||
if (channel.label !== 'aiturk-mobile-v1') { close(offer.id); return }
|
||||
let pending = 0
|
||||
channel.onmessage = async event => {
|
||||
if (typeof event.data !== 'string' || event.data.length > 65000 || ++pending > 8) { close(offer.id); return }
|
||||
let message
|
||||
try {
|
||||
message = JSON.parse(event.data)
|
||||
const result = await host.call('channel.request', { channelId: offer.id, message })
|
||||
if (channel.readyState === 'open') sendFrame(channel, { id: message.id, result })
|
||||
} catch (error) { if (message?.id && channel.readyState === 'open') channel.send(JSON.stringify({ id: message.id, error: error.message })) }
|
||||
finally { pending-- }
|
||||
}
|
||||
channel.onclose = () => close(offer.id)
|
||||
channel.onopen = () => status('Telefon şifreli veri kanalıyla bağlı.')
|
||||
}
|
||||
try {
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp: offer.sdp })
|
||||
await pc.setLocalDescription(await pc.createAnswer()); await completeIce(pc)
|
||||
await host.call('channel.answer', { channelId: offer.id, sdp: pc.localDescription.sdp })
|
||||
entry.timer = setInterval(() => { void host.call('channel.heartbeat', { channelId: offer.id }).catch(() => close(offer.id)) }, 10000)
|
||||
} catch (error) { close(offer.id); throw error }
|
||||
}
|
||||
let listening = false
|
||||
action('listen', async () => {
|
||||
if (listening) return
|
||||
listening = true; status('Onaylı telefon bağlantısı bekleniyor.')
|
||||
while (listening) {
|
||||
try { const data = await host.call('inbox'); for (const offer of data.channels) if (!peers.has(offer.id)) await connect(offer) }
|
||||
catch (error) { status(error.message); listening = false; break }
|
||||
await new Promise(resolve => setTimeout(resolve, 2000))
|
||||
}
|
||||
})
|
||||
window.addEventListener('pagehide', () => { listening = false; for (const id of peers.keys()) close(id) })
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html><html lang="tr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'">
|
||||
<title>AITURK Mobil bağlantısı</title><link rel="stylesheet" href="mobile/style.css"></head><body><main>
|
||||
<p class="eyebrow">AITURK · BİLGİSAYAR</p><h1>Telefonunu bağla.</h1>
|
||||
<p>Bu pencere açıkken eşleştirdiğiniz Android telefon seçtiğiniz IDE konuşmasına erişebilir. Google anahtarı Windows güvenli kasasında tutulur.</p>
|
||||
<p id="status" role="status" aria-live="polite">Bağlantı kapalı.</p>
|
||||
<label>AITURK hesap API anahtarı<input id="account" type="password" autocomplete="off"></label>
|
||||
<button id="save">Hesap anahtarını kaydet</button><button id="pair">Bu bilgisayarı hesabımla eşleştir</button>
|
||||
<p id="code"></p><hr>
|
||||
<h2>Telefona izin ver</h2><p>Telefondaki eşleştirme kimliğini ve 8 karakterli kodu buraya girin. Bu onay yalnız bu telefon ile bu bilgisayarı bağlar.</p>
|
||||
<label>Eşleştirme kimliği<input id="pairing"></label><label>Telefondaki kod<input id="phone-code" maxlength="8" autocapitalize="characters"></label>
|
||||
<button id="approve">Bu telefonu onayla</button><button id="listen">Mobil bağlantıyı aç</button>
|
||||
<h2>Cihazlar</h2><button id="refresh">Cihaz listesini yenile</button><div id="devices"></div>
|
||||
<p>Farklı ağlarda bağlantı kurulması ağınıza ve TURN hizmeti yapılandırmasına bağlıdır. Bu geliştirme sürümünde genel ağ erişimi henüz doğrulanmadı.</p>
|
||||
</main><script type="module" src="mobile-host-ui.mjs"></script></body></html>
|
||||
@@ -0,0 +1,103 @@
|
||||
import { join } from 'node:path'
|
||||
import { hostname } from 'node:os'
|
||||
import { BrowserWindow, ipcMain, safeStorage, shell } from 'electron'
|
||||
import { MobileVault, LiveTokenIssuer } from './mobile-secrets.mjs'
|
||||
import { DeliveryJournal, MobileGatewayClient } from './mobile-adapter.mjs'
|
||||
import { AccountClient } from '../../mobile/src/transport.mjs'
|
||||
|
||||
export function createMobileWindow({ directory, assets, resolveBackend, show = true }) {
|
||||
const vault = new MobileVault(join(directory, 'mobile'), safeStorage)
|
||||
const journal = new DeliveryJournal(join(directory, 'mobile', 'deliveries'))
|
||||
const issuer = new LiveTokenIssuer(vault)
|
||||
const clients = new Map()
|
||||
const window = new BrowserWindow({ width: 560, height: 800, show, title: 'AITURK Mobil bağlantısı',
|
||||
webPreferences: { preload: join(assets, 'mobile-preload.cjs'), contextIsolation: true,
|
||||
nodeIntegration: false, sandbox: true, backgroundThrottling: false } })
|
||||
window.setMenu(null)
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
|
||||
window.webContents.on('will-navigate', event => event.preventDefault())
|
||||
const api = async () => new AccountClient(await vault.load())
|
||||
const call = async (path, body, method) => (await api()).call(path, body, method)
|
||||
const send = frame => { if (!window.isDestroyed()) window.webContents.send('aiturk-mobile-event', frame) }
|
||||
const handler = async (event, action, params = {}) => {
|
||||
if (event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame) throw new Error('Geçersiz mobil pencere.')
|
||||
if (action === 'setup') {
|
||||
const secrets = await vault.load()
|
||||
return { paired: Boolean(secrets.deviceId), hasAccount: Boolean(secrets.accountToken), hasGoogle: Boolean(secrets.googleKey) }
|
||||
}
|
||||
if (action === 'account.save') {
|
||||
if (typeof params.token !== 'string' || params.token.length < 12 || params.token.length > 512) throw new Error('AITURK hesap anahtarı geçersiz.')
|
||||
if (clients.size) throw new Error('Hesap değiştirmeden önce mobil bağlantıyı kapatın.')
|
||||
const previous = await vault.load()
|
||||
if (previous.accountToken && previous.accountToken !== params.token) throw new Error('Hesabı değiştirmek için önce mevcut cihazı iptal edin ve bağlantı penceresini yeniden açın.')
|
||||
await vault.save({ ...previous, accountToken: params.token })
|
||||
return { saved: true }
|
||||
}
|
||||
if (action === 'desktop.pair') {
|
||||
const result = await call('/v1/aiturk/pairings', { display_name: hostname(), platform: 'windows-x64' })
|
||||
await vault.save({ ...await vault.load(), deviceId: result.device_id, deviceToken: result.device_token,
|
||||
pairingId: result.pairing_id })
|
||||
await shell.openExternal('https://turkservis.online' + result.verification_uri)
|
||||
return { code: result.user_code, expiresAt: result.expires_at }
|
||||
}
|
||||
if (action === 'phone.approve') {
|
||||
if (!/^[0-9a-f-]{36}$/.test(params.pairingId) || !/^[A-Z2-9]{8}$/.test(params.code)) throw new Error('Telefondaki eşleştirme bilgileri geçersiz.')
|
||||
return call(`/v1/aiturk/pairings/${params.pairingId}/approve`, { user_code: params.code })
|
||||
}
|
||||
if (action === 'devices') return call('/v1/aiturk/mobile/devices')
|
||||
if (action === 'device.revoke') {
|
||||
if (!/^[0-9a-f-]{36}$/.test(params.deviceId) || !Number.isInteger(params.version)) throw new Error('Geçersiz cihaz.')
|
||||
const result = await call(`/v1/aiturk/devices/${params.deviceId}/revoke`, { expected_version: params.version })
|
||||
for (const [id, entry] of clients) if (entry.phoneId === params.deviceId || result.self_revoked) {
|
||||
entry.client.close(); clients.delete(id); send({ channelId: id, close: true })
|
||||
}
|
||||
if (result.self_revoked) await vault.save({})
|
||||
return result
|
||||
}
|
||||
if (action === 'inbox') return call('/v1/aiturk/mobile/channels')
|
||||
if (action === 'ice') return call('/v1/aiturk/mobile/ice')
|
||||
if (action === 'channel.answer') {
|
||||
const inbox = await call('/v1/aiturk/mobile/channels')
|
||||
const offer = inbox.channels.find(row => row.id === params.channelId)
|
||||
if (!offer || clients.has(offer.id) || clients.size >= 4) throw new Error('Bağlantı isteği artık geçerli değil.')
|
||||
const authorize = () => call(`/v1/aiturk/mobile/channels/${offer.id}/heartbeat`, {})
|
||||
const client = new MobileGatewayClient(resolveBackend, frame => send({ channelId: offer.id, frame }),
|
||||
{ deviceId: offer.phone_id, journal, authorize })
|
||||
await call(`/v1/aiturk/mobile/channels/${offer.id}/answer`, { sdp: params.sdp })
|
||||
clients.set(offer.id, { client, phoneId: offer.phone_id, authorize })
|
||||
return { accepted: true }
|
||||
}
|
||||
if (action === 'channel.heartbeat') {
|
||||
const entry = clients.get(params.channelId)
|
||||
if (!entry) throw new Error('Bağlantı yok.')
|
||||
return entry.authorize()
|
||||
}
|
||||
if (action === 'channel.close') {
|
||||
clients.get(params.channelId)?.client.close(); clients.delete(params.channelId)
|
||||
return { closed: true }
|
||||
}
|
||||
if (action === 'channel.request') {
|
||||
const entry = clients.get(params.channelId)
|
||||
if (!entry) throw new Error('Bağlantı yok.')
|
||||
await entry.authorize()
|
||||
const message = params.message
|
||||
if (!message || JSON.stringify(message).length > 65000) throw new Error('İstek boyutu geçersiz.')
|
||||
if (message.action === 'google.key.save') {
|
||||
const key = message.params?.key
|
||||
if (typeof key !== 'string' || !/^[A-Za-z0-9_-]{20,256}$/.test(key)) throw new Error('Google anahtarı biçimi geçersiz.')
|
||||
await vault.save({ ...await vault.load(), googleKey: key })
|
||||
return { saved: true }
|
||||
}
|
||||
if (message.action === 'google.key.delete') {
|
||||
const secrets = await vault.load(); delete secrets.googleKey; await vault.save(secrets); return { deleted: true }
|
||||
}
|
||||
if (message.action === 'voice.token') return issuer.issue(entry.phoneId)
|
||||
return entry.client.handle(message)
|
||||
}
|
||||
throw new Error('Desteklenmeyen mobil işlem.')
|
||||
}
|
||||
ipcMain.handle('aiturk-mobile', handler)
|
||||
window.on('closed', () => { for (const entry of clients.values()) entry.client.close(); clients.clear(); ipcMain.removeHandler('aiturk-mobile') })
|
||||
void window.loadFile(join(assets, 'mobile-host.html'))
|
||||
return window
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
const { contextBridge, ipcRenderer } = require('electron')
|
||||
contextBridge.exposeInMainWorld('mobileHost', {
|
||||
call: (action, params) => ipcRenderer.invoke('aiturk-mobile', action, params),
|
||||
onEvent: callback => ipcRenderer.on('aiturk-mobile-event', (_event, value) => callback(value)),
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdir, readFile, writeFile, rename } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { ASSISTANT_INSTRUCTION, TASK_TOOL } from '../../mobile/src/behavior.mjs'
|
||||
|
||||
export class MobileVault {
|
||||
constructor(directory, safeStorage) { this.directory = directory; this.safeStorage = safeStorage }
|
||||
async load() {
|
||||
if (!this.safeStorage.isEncryptionAvailable()) throw new Error('Windows güvenli anahtar kasası kullanılamıyor.')
|
||||
try {
|
||||
const data = await readFile(join(this.directory, 'mobile-secrets.bin'))
|
||||
return JSON.parse(this.safeStorage.decryptString(data))
|
||||
} catch (error) { if (error.code === 'ENOENT') return {}; throw new Error('Mobil anahtar kasası açılamadı.') }
|
||||
}
|
||||
async save(value) {
|
||||
if (!this.safeStorage.isEncryptionAvailable()) throw new Error('Windows güvenli anahtar kasası kullanılamıyor.')
|
||||
const encrypted = this.safeStorage.encryptString(JSON.stringify(value))
|
||||
await mkdir(this.directory, { recursive: true })
|
||||
const file = join(this.directory, 'mobile-secrets.bin')
|
||||
await writeFile(file + '.tmp', encrypted, { mode: 0o600 })
|
||||
await rename(file + '.tmp', file)
|
||||
}
|
||||
}
|
||||
|
||||
export const LIVE_MODEL = 'gemini-3.1-flash-live-preview'
|
||||
export class LiveTokenIssuer {
|
||||
constructor(vault, fetcher = fetch, now = Date.now) { this.vault = vault; this.fetcher = fetcher; this.now = now; this.last = new Map() }
|
||||
async issue(deviceId) {
|
||||
const now = this.now()
|
||||
if (now - (this.last.get(deviceId) ?? -Infinity) < 30000) throw new Error('Yeni ses bağlantısı için 30 saniye bekleyin.')
|
||||
this.last.set(deviceId, now)
|
||||
const secrets = await this.vault.load()
|
||||
if (!secrets.googleKey) throw new Error('Önce kendi Google AI Studio anahtarınızı ekleyin.')
|
||||
let response
|
||||
try {
|
||||
response = await this.fetcher('https://generativelanguage.googleapis.com/v1beta/auth_tokens', {
|
||||
method: 'POST', headers: { 'x-goog-api-key': secrets.googleKey, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ uses: 1, expireTime: new Date(now + 10 * 60000).toISOString(),
|
||||
newSessionExpireTime: new Date(now + 60000).toISOString(),
|
||||
bidiGenerateContentSetup: { model: `models/${LIVE_MODEL}`,
|
||||
generationConfig: { responseModalities: ['AUDIO'] },
|
||||
systemInstruction: { parts: [{ text: ASSISTANT_INSTRUCTION }] },
|
||||
tools: [{ functionDeclarations: [TASK_TOOL] }],
|
||||
inputAudioTranscription: {}, outputAudioTranscription: {} } }),
|
||||
redirect: 'error', signal: AbortSignal.timeout(20000) })
|
||||
} catch { throw new Error('Google ses erişimine ulaşılamadı.') }
|
||||
if (!response.ok) throw new Error(response.status === 429 ? 'Google kotası veya istek sınırı doldu. AI Studio üzerinden kontrol edin.'
|
||||
: response.status === 401 || response.status === 403 ? 'Google anahtarı veya ses modeli erişimi geçersiz.' : 'Google ses erişimi oluşturulamadı.')
|
||||
const data = await response.json()
|
||||
if (typeof data.name !== 'string' || !data.name.startsWith('auth_tokens/')) throw new Error('Google geçerli kısa ömürlü erişim döndürmedi.')
|
||||
return { token: data.name, model: LIVE_MODEL, expiresAt: new Date(now + 10 * 60000).toISOString() }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user