Compare commits

..
Author SHA1 Message Date
yilsemandClaude Opus 5 4d813c90ae Merge fix/ide-windows-vcruntime: AITURK IDE 1.0.0-beta.12 VC++ runtime fix
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 20:01:19 +03:00
yilsemandClaude Opus 5 9240576937 fix(desktop): resolve hoisted mobile vendor packages when bundling
A clean npm ci hoists qrcode-generator and jsqr to the workspace root, so the bundler now follows Node resolution from apps/mobile instead of assuming apps/mobile/node_modules.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 19:51:08 +03:00
yilsemandClaude Opus 5 233885d3a7 fix(desktop): ship the VC++ runtime the Windows voice wheels need
onnxruntime (wake word) and ctranslate2 (local speech-to-text) link against
msvcp140.dll and msvcp140_1.dll, which the managed CPython does not ship.
On Windows without the system VC++ Redistributable both imports failed with
"DLL load failed: The specified module could not be found", so "Hey Hermes"
and voice chat transcription never worked.

- Bundle the Microsoft-signed VC143 CRT set (14.44.35211, matching the
  managed CPython's vcruntime140) as a Windows extra resource with a SHA-256
  manifest.
- Before every local backend start, copy missing or mismatching CRT files
  beside the managed python.exe (the process image directory, searched first),
  verifying digests; never overwrite the interpreter's own vcruntime and never
  block boot. Existing installs heal on their next launch.
- Report an unloadable native voice wheel as a VC++ runtime problem in the
  wake-word requirements, local transcription and `hermes doctor`, instead of
  treating installed package metadata as proof the wheel loads.
- Bump AITURK IDE to 1.0.0-beta.12.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 19:46:39 +03:00
yilsem 456919df43 build(mobile): require explicit validated Android release identity 2026-09-12 16:02:23 +03:00
yilsem 52f792f00f feat(mobile): verify pinned Android release APK identity before distribution 2026-09-12 15:34:00 +03:00
yilsem 9a1d831d4b fix(desktop): complete Rolldown runtime dependency closure 2026-09-12 14:41:36 +03:00
yilsem 1fe367177c fix(windows): pin Vite Lightning CSS native dependency to matching version 2026-09-12 14:39:39 +03:00
yilsem 40c3c74282 fix(mobile): synchronize root lockfile QR dependencies 2026-09-12 14:36:33 +03:00
yilsem ee73fa8cce chore(desktop): prepare Windows x64 beta.11 candidate 2026-09-12 14:26:39 +03:00
yilsem f960716483 test(mobile): verify Windows host ancestry and 0.1.4 runtime integration 2026-09-12 12:17:16 +03:00
yilsem 5f75dcc99a feat(mobile): bind device identities and bound voice usage in 0.1.4 dev 2026-09-12 12:11:18 +03:00
yilsem ac6687181e fix(windows): probe compute host liveness without sending signals 2026-09-12 11:52:12 +03:00
yilsem 3f12c627ab fix(windows): append compute host logs without concurrent record loss 2026-09-12 11:49:46 +03:00
yilsem 4115f1b4c0 feat(mobile): add local QR scanning and desktop pairing invitations 2026-09-08 21:28:24 +03:00
yilsem c1929957a2 feat(mobile): connect Android and IDE to browser account login 2026-09-08 21:10:49 +03:00
yilsem b66daed07a feat(mobile): correlate voice tasks and recover results on reconnect 2026-09-08 21:00:28 +03:00
yilsem 9f9f3226a1 feat(mobile): add Android development client and scoped IDE companion 2026-09-08 16:54:28 +03:00
yilsem 3332458708 feat(desktop): open read-only TurkServis combo details in browser pane 2026-09-07 21:46:57 +03:00
134 changed files with 6857 additions and 33 deletions

No files matched your search

@@ -0,0 +1,51 @@
{
"schemaVersion": 1,
"product": "Microsoft Visual C++ 2015-2022 Redistributable (VC143 CRT)",
"version": "14.44.35211.0",
"architecture": "x64",
"publisher": "Microsoft Corporation (Authenticode doğrulandı)",
"files": [
{
"name": "msvcp140.dll",
"size": 557728,
"sha256": "0f885b509a685d2bbfa652fed26b5fb31d88fbdab0a978c641d1c7b8aa460aa9"
},
{
"name": "msvcp140_1.dll",
"size": 35952,
"sha256": "bfad5aef4c63a669e3c140655cdfdf395b6c979b400a447bd5dcb65ed8826c3d"
},
{
"name": "msvcp140_2.dll",
"size": 280200,
"sha256": "3ea06f0ee098b4823cb79599df3780e7f23cce52c19aac31d2a0d47efe33a5e9"
},
{
"name": "msvcp140_atomic_wait.dll",
"size": 50304,
"sha256": "640b2aefced484d0368eea5bdd06addd0658a3a70a49256e560d6923b404a479"
},
{
"name": "msvcp140_codecvt_ids.dll",
"size": 31872,
"sha256": "f2069a52880ec885ee7f0511186100eb7fada0411a2b4948fafea7735b878a18"
},
{
"name": "concrt140.dll",
"size": 324208,
"sha256": "2405355f0a58067b258f8df33c327e3a3d716eaac5a3a5aebb757842d85bd376"
},
{
"name": "vcruntime140.dll",
"size": 124544,
"sha256": "d5e4d9a3e835fa679450145d6a7d94e36573a509317111904d9b3712c30d9066",
"ownedByPython": true
},
{
"name": "vcruntime140_1.dll",
"size": 49792,
"sha256": "1f2d41c4aa5db0bc33ebf7b66d72943a817d7ce6cbe880502a9403823633093f",
"ownedByPython": true
}
]
}
+43 -1
View File
@@ -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,
@@ -32,6 +33,7 @@ import {
} from 'electron'
import { classifyActiveRuntime, needsPackagedRuntimeUpgrade } from './active-runtime-state'
import { describeVcRuntimeResult, ensureWindowsVcRuntime } from './windows-vc-runtime'
import { destroyKeepaliveAgents, downloadAgentFor, jsonAgentFor, withRetry } from './api-transport'
import { appIconCandidates, resolveAppIcon } from './app-icon'
import { stopBackendChild as stopBackendChildImpl, stopBackendTreesForUpdate } from './backend-child'
@@ -5220,6 +5222,22 @@ async function ensureRuntime(backend) {
)
}
// Voice wheels (onnxruntime, ctranslate2) need msvcp140*.dll, which the
// managed CPython does not ship. Place the bundled Microsoft CRT beside the
// managed python.exe before the backend imports anything. Never blocks boot:
// only the voice features depend on it.
if (IS_WINDOWS) {
const vcRuntime = ensureWindowsVcRuntime({
platform: process.platform,
venvRoot: VENV_ROOT,
sourceDir: IS_PACKAGED
? path.join(process.resourcesPath, 'vc-runtime', 'x64')
: path.join(APP_ROOT, 'assets', 'windows', 'vc-runtime', 'x64')
})
rememberLog(`[vc-runtime] ${describeVcRuntimeResult(vcRuntime)}`)
}
backend.command = getVenvPython(VENV_ROOT)
backend.label = `Hermes at ${ACTIVE_HERMES_ROOT} (venv: ${VENV_ROOT})`
updateBootProgress({
@@ -17717,6 +17735,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 +17762,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'),
+161
View File
@@ -0,0 +1,161 @@
import { createHash } from 'node:crypto'
import { mkdir, readFile, writeFile, rename } 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; this.writes = Promise.resolve() }
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) {
return this.update(reservation, 'accepted')
}
update(reservation, state) {
const operation = this.writes.then(async () => {
const previous = JSON.parse(await readFile(reservation.file, 'utf8'))
if (['complete', 'error', 'interrupted'].includes(previous.state)) return
const temporary = `${reservation.file}.tmp`
await writeFile(temporary, JSON.stringify({ hash: reservation.hash, state }), { mode: 0o600, flush: true })
await rename(temporary, reservation.file)
})
this.writes = operation.catch(() => {})
return operation
}
}
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()
this.tasks = new Map()
}
onEvent(event) {
if (['task.start', 'task.complete'].includes(event?.type)) {
const task = this.tasks.get(event.payload?.task_id)
if (!task || task.runtimeId !== event.session_id || task.terminal) return
const state = event.type === 'task.start' ? 'running' : event.payload.status
if (!['running', 'complete', 'error', 'interrupted'].includes(state)) return
task.terminal = state !== 'running'
task.state = state
if (task.terminal) this.journal.update(task.reservation, state).catch(() => {})
this.emit({ event: event.type, taskId: task.taskId, sessionId: task.sessionId, status: state,
text: typeof event.payload.text === 'string' ? event.payload.text.slice(0, 100000) : '' })
return
}
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') {
const capabilities = await this.rpc('gateway.capabilities', {})
if (!capabilities.client_task_tracking) throw new Error('IDE sürümü mobil görev takibini desteklemiyor. IDE güncellemesi gerekli.')
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)
const correlation = digest([this.deviceId, params.taskId])
if (!this.tasks.has(correlation)) this.tasks.set(correlation, { taskId: params.taskId, sessionId: params.sessionId,
runtimeId: this.selected.runtimeId, reservation, terminal: false, state: reservation.state || 'unknown' })
if (!reservation.fresh) {
// Recover a terminal event missed while the phone/companion was closed.
// Never resubmit even if the bounded replay window no longer has it.
const replay = await this.rpc('session.events.since', { session_id: this.selected.runtimeId, last_seen: 0 })
for (const frame of replay.events || []) if (frame.params?.payload?.task_id === correlation) this.onEvent(frame.params)
await this.journal.writes
const state = this.tasks.get(correlation).state
return { taskId: params.taskId, state, duplicate: true, historyRequired: !['complete', 'error', 'interrupted'].includes(state) }
}
await this.authorize()
await this.rpc('prompt.submit', { session_id: this.selected.runtimeId, text: params.text, queued: true,
client_task_id: correlation })
await this.journal.accepted(reservation)
if (!this.tasks.get(correlation).terminal) this.tasks.get(correlation).state = 'accepted'
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)
}
}
+94
View File
@@ -0,0 +1,94 @@
import { completeIce, rtcConfiguration, sendFrame } from './mobile/transport.mjs'
import { drawQr, InviteScanner } from './mobile/qr.mjs'
import { createDeviceIdentity, loadDeviceIdentity, assertRemoteIdentity, parsePhoneIdentity } from './mobile/peer-identity.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 } } }
const identityScanner = new InviteScanner(document.createElement('video'), async raw => {
if (raw.length > 700) throw new Error('Telefon kimlik belgesi çok büyük.')
const value = JSON.parse(raw)
const pairingId = $('pairing').value.trim() || value.pairingId
parsePhoneIdentity(raw, pairingId)
if (!/^[0-9a-f-]{36}$/.test(pairingId)) throw new Error('Eşleştirme kimliği geçersiz.')
$('pairing').value = pairingId; $('phone-identity').value = raw
status('Telefon kimliği QR resminden alındı. Telefondaki kısa kodu girin ve bu telefonu ayrıca onaylayın; henüz izin verilmedi.')
})
$('phone-identity-file').onchange = async event => {
try { await identityScanner.image(event.target.files[0]) }
catch (error) { status(error.message) }
finally { event.target.value = '' }
}
action('login-start', async () => { const result = await host.call('account.login.start'); $('login-code').textContent = `Açılan hesap sayfasında yalnız bu kodu onaylayın: ${result.code}` })
action('login-check', async () => { const result = await host.call('account.login.check'); status(result.approved ? 'Hesaba giriş yapıldı. Bu bilgisayarı eşleştirebilirsiniz.' : 'Tarayıcıdaki kod onayı bekleniyor.') })
action('logout', async () => { await host.call('account.logout'); listening = false; $('login-code').textContent = ''; status('Mobil oturum kapatıldı; hesap ve Google anahtarı bu bilgisayar kasasından temizlendi.') })
async function desktopIdentity(create = false) {
const setup = await host.call('setup')
if (!setup.deviceId) throw new Error('Önce bu bilgisayarı hesapla eşleştirin.')
if (setup.localFingerprint) return loadDeviceIdentity(setup.deviceId, setup.localFingerprint)
if (!create) throw new Error('Önce bu bilgisayarda yeni telefon QR kodu oluşturun.')
const identity = await createDeviceIdentity(setup.deviceId)
await host.call('identity.save', { deviceId: setup.deviceId, fingerprint: identity.fingerprint })
return identity
}
action('invite', async () => {
const identity = await desktopIdentity(true), invite = await host.call('invite.create')
drawQr($('invite-qr'), JSON.stringify({ ...invite, version: 2, desktopFingerprint: identity.fingerprint }))
$('invite-qr').hidden = false
$('invite-status').textContent = `Telefonda aynı hesaba giriş yapıp bu QR kodunu tarayın. Son geçerlilik: ${invite.expiresAt}`
})
action('invite-check', async () => { const result = await host.call('invite.check'); if (!result.pending) { status('QR ile gelen telefon henüz yok.'); return }; $('pairing').value = result.pending.pairingId; status(`${result.pending.name} bulundu. Telefondaki kısa kodu girip “Bu telefonu onayla” seçin.`) })
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(), identity: $('phone-identity').value.trim() }); $('phone-code').value = ''; $('phone-identity').value = ''; status('Telefon bu bilgisayarda kimliğiyle 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) {
assertRemoteIdentity(offer.sdp, offer.trustedPhoneFingerprint)
const ice = await host.call('ice')
const identity = await desktopIdentity()
const pc = new RTCPeerConnection({ ...rtcConfiguration(ice.iceServers), certificates: [identity.certificate] }), 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) })
+24
View File
@@ -0,0 +1,24 @@
<!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>
<button id="login-start">AITURK hesabımla giriş yap</button><p id="login-code"></p><button id="login-check">Girişi kontrol et</button>
<p>Çıkış, mobil bağlantıları kapatır ve bu penceredeki hesap/Google anahtarını Windows kasasından temizler; başlamış IDE işini durdurmaz.</p>
<button id="logout">Mobil oturumdan çık ve kasayı temizle</button>
<details><summary>Gelişmiş: hesap API anahtarı</summary>
<label>AITURK hesap API anahtarı<input id="account" type="password" autocomplete="off"></label>
<button id="save">Hesap anahtarını kaydet</button></details><button id="pair">Bu bilgisayarı hesabımla eşleştir</button>
<p id="code"></p><hr>
<button id="invite">Telefon için QR oluştur</button><canvas id="invite-qr" hidden aria-label="Süreli telefon eşleştirme QR kodu"></canvas>
<p id="invite-status"></p><button id="invite-check">QR ile gelen telefonu getir</button>
<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>
<label>Telefondan alınan kimlik belgesi<textarea id="phone-identity" maxlength="700"></textarea></label>
<label>Telefon kimliği QR resmi<input id="phone-identity-file" type="file" accept="image/*"></label>
<p>Yalnız kendi telefonunuzun gösterdiği belgenin tamamını buraya aktarın. Onay, bu telefonun sertifikasını bilgisayarınıza kaydeder; farklı sertifika yeniden açık eşleştirme gerektirir.</p>
<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 src="mobile/vendor/jsQR.js"></script><script type="module" src="mobile-host-ui.mjs"></script></body></html>
+157
View File
@@ -0,0 +1,157 @@
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'
import { normalizeFingerprint, parsePhoneIdentity, assertRemoteIdentity } from '../../mobile/src/peer-identity.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),
deviceId: secrets.deviceId, localFingerprint: secrets.localFingerprint }
}
if (action === 'identity.save') {
const previous = await vault.load(), fingerprint = normalizeFingerprint(params.fingerprint)
if (!previous.deviceId || previous.deviceId !== params.deviceId ||
(previous.localFingerprint && previous.localFingerprint !== fingerprint))
throw new Error('Cihaz kimliği sessizce değiştirilemez. Yeniden eşleştirin.')
await vault.save({ ...previous, localFingerprint: fingerprint })
return { saved: true }
}
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 === 'account.login.start') {
const previous = await vault.load()
if (previous.accountToken || clients.size) throw new Error('Kayıtlı hesap var. Önce mevcut cihazı iptal edin.')
const login = await new AccountClient({}).call('/v1/aiturk/mobile-auth/start', {})
if (!/^https:\/\/turkservis\.online\/account\/aiturk\/mobile-login\/[0-9a-f-]{36}$/.test(login.verificationUri)) throw new Error('Geçersiz giriş adresi.')
await vault.save({ ...previous, pendingLogin: login })
await shell.openExternal(login.verificationUri)
return { code: login.userCode }
}
if (action === 'account.login.check') {
const previous = await vault.load()
if (previous.accountToken || clients.size) throw new Error('Mevcut hesap veya bağlantı sessizce değiştirilemez.')
if (!previous.pendingLogin) throw new Error('Önce giriş başlatın.')
const result = await new AccountClient({ accountToken: previous.pendingLogin.deviceCode }).call('/v1/aiturk/mobile-auth/poll', {})
if (result.state !== 'approved') return { approved: false }
delete previous.pendingLogin
await vault.save({ ...previous, accountToken: result.accountToken })
return { approved: true }
}
if (action === 'account.logout') {
const previous = await vault.load(), token = previous.accountToken || previous.pendingLogin?.deviceCode
if (token?.startsWith('tsml_')) await new AccountClient({ accountToken: token }).call('/v1/aiturk/mobile-auth/logout', {})
for (const [id, entry] of clients) { entry.client.close(); send({ channelId: id, close: true }) }
clients.clear(); await vault.save({})
return { cleared: 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.')
const identity = parsePhoneIdentity(params.identity, params.pairingId)
const previous = await vault.load(), existing = previous.phoneFingerprints?.[identity.deviceId]
if (existing && existing !== identity.fingerprint) throw new Error('Kayıtlı telefon kimliği değiştirilemez. Cihazı iptal edip yeniden eşleştirin.')
const result = await call(`/v1/aiturk/pairings/${params.pairingId}/approve`, { user_code: params.code })
if (result.device_id !== identity.deviceId || result.status !== 'approved') throw new Error('Onaylanan telefon kimlik belgesiyle eşleşmiyor; bağlantı açılmadı.')
const current = await vault.load()
if (current.deviceId !== previous.deviceId || current.accountToken !== previous.accountToken) throw new Error('Onay sırasında hesap değişti; yeniden eşleştirin.')
await vault.save({ ...current, phoneFingerprints: { ...current.phoneFingerprints, [identity.deviceId]: identity.fingerprint } })
return result
}
if (action === 'devices') return call('/v1/aiturk/mobile/devices')
if (action === 'invite.create') return call('/v1/aiturk/mobile/invites', {})
if (action === 'invite.check') return call('/v1/aiturk/mobile/invites')
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') {
const data = await call('/v1/aiturk/mobile/channels'), secrets = await vault.load()
return { ...data, channels: data.channels.map(offer => {
const fingerprint = secrets.phoneFingerprints?.[offer.phone_id]
assertRemoteIdentity(offer.sdp, fingerprint)
return { ...offer, trustedPhoneFingerprint: fingerprint }
}) }
}
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.')
assertRemoteIdentity(offer.sdp, (await vault.load()).phoneFingerprints?.[offer.phone_id])
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
}
+5
View File
@@ -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)),
})
+52
View File
@@ -0,0 +1,52 @@
import { mkdir, readFile, writeFile, rename } from 'node:fs/promises'
import { join } from 'node:path'
import { ASSISTANT_INSTRUCTION, VOICE_TOOLS } 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: VOICE_TOOLS }],
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() }
}
}
@@ -0,0 +1,171 @@
import assert from 'node:assert/strict'
import crypto from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, test } from 'vitest'
import { ensureWindowsVcRuntime, loadVcRuntimeManifest, readPythonHome } from './windows-vc-runtime'
const here = path.dirname(fileURLToPath(import.meta.url))
const roots: string[] = []
function tempRoot() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'aiturk-vc-runtime-'))
roots.push(root)
return root
}
function sha256(data: Buffer) {
return crypto.createHash('sha256').update(data).digest('hex')
}
// A fake install: venv/pyvenv.cfg -> python home, plus a bundled source dir
// whose manifest describes the given files.
function fixture(files: Record<string, { data: string; ownedByPython?: boolean }>) {
const root = tempRoot()
const home = path.join(root, 'python home')
const venv = path.join(root, 'venv')
const source = path.join(root, 'bundle')
for (const dir of [home, venv, source]) {
fs.mkdirSync(dir, { recursive: true })
}
fs.writeFileSync(path.join(home, 'python.exe'), 'exe')
fs.writeFileSync(path.join(venv, 'pyvenv.cfg'), `home = ${home}\r\nversion_info = 3.11\r\n`)
const entries = Object.entries(files).map(([name, { data, ownedByPython }]) => {
const bytes = Buffer.from(data)
fs.writeFileSync(path.join(source, name), bytes)
return { name, size: bytes.length, sha256: sha256(bytes), ...(ownedByPython ? { ownedByPython } : {}) }
})
fs.writeFileSync(
path.join(source, 'manifest.json'),
JSON.stringify({ schemaVersion: 1, version: 'test', architecture: 'x64', files: entries })
)
return { home, venv, source }
}
afterEach(() => {
for (const root of roots.splice(0)) {
fs.rmSync(root, { recursive: true, force: true })
}
})
test('non-Windows platforms are left untouched', () => {
const { home, venv, source } = fixture({ 'msvcp140.dll': { data: 'crt' } })
assert.deepEqual(ensureWindowsVcRuntime({ platform: 'linux', venvRoot: venv, sourceDir: source }), {
status: 'skipped',
reason: 'not windows'
})
assert.equal(fs.existsSync(path.join(home, 'msvcp140.dll')), false)
})
test('readPythonHome parses pyvenv.cfg home with spaces', () => {
const { home, venv } = fixture({ 'msvcp140.dll': { data: 'crt' } })
assert.equal(readPythonHome(venv), home)
assert.equal(readPythonHome(path.join(venv, 'missing')), null)
})
test('missing CRT files are copied beside python.exe and verified', () => {
const { home, venv, source } = fixture({
'msvcp140.dll': { data: 'msvcp' },
'msvcp140_1.dll': { data: 'msvcp1' }
})
const result = ensureWindowsVcRuntime({ platform: 'win32', venvRoot: venv, sourceDir: source })
assert.deepEqual(result, { status: 'repaired', pythonHome: home, copied: ['msvcp140.dll', 'msvcp140_1.dll'] })
assert.equal(fs.readFileSync(path.join(home, 'msvcp140_1.dll'), 'utf8'), 'msvcp1')
assert.deepEqual(fs.readdirSync(home).filter(name => name.endsWith('.tmp')), [])
// Second launch: nothing to do.
assert.deepEqual(ensureWindowsVcRuntime({ platform: 'win32', venvRoot: venv, sourceDir: source }), {
status: 'ok',
pythonHome: home,
copied: []
})
})
test('a mismatching msvcp140 copy is replaced, a python-owned vcruntime is kept', () => {
const { home, venv, source } = fixture({
'msvcp140.dll': { data: 'good' },
'vcruntime140.dll': { data: 'bundled', ownedByPython: true }
})
fs.writeFileSync(path.join(home, 'msvcp140.dll'), 'stale')
fs.writeFileSync(path.join(home, 'vcruntime140.dll'), 'interpreter-owned')
const result = ensureWindowsVcRuntime({ platform: 'win32', venvRoot: venv, sourceDir: source })
assert.deepEqual(result, { status: 'repaired', pythonHome: home, copied: ['msvcp140.dll'] })
assert.equal(fs.readFileSync(path.join(home, 'msvcp140.dll'), 'utf8'), 'good')
assert.equal(fs.readFileSync(path.join(home, 'vcruntime140.dll'), 'utf8'), 'interpreter-owned')
})
test('a tampered bundled file is refused and nothing is written', () => {
const { home, venv, source } = fixture({ 'msvcp140.dll': { data: 'genuine' } })
fs.writeFileSync(path.join(source, 'msvcp140.dll'), 'tampered')
const result = ensureWindowsVcRuntime({ platform: 'win32', venvRoot: venv, sourceDir: source })
assert.equal(result.status, 'failed')
assert.match((result as { error: string }).error, /does not match its manifest digest/)
assert.equal(fs.existsSync(path.join(home, 'msvcp140.dll')), false)
})
test('an unresolvable python home fails without throwing', () => {
const { venv, source } = fixture({ 'msvcp140.dll': { data: 'crt' } })
fs.writeFileSync(path.join(venv, 'pyvenv.cfg'), 'home = C:\\does-not-exist\n')
assert.equal(ensureWindowsVcRuntime({ platform: 'win32', venvRoot: venv, sourceDir: source }).status, 'failed')
})
test('the shipped CRT set matches its manifest and covers the voice wheels', () => {
const sourceDir = path.join(here, '..', 'assets', 'windows', 'vc-runtime', 'x64')
const manifest = loadVcRuntimeManifest(sourceDir)
const names = manifest.files.map(file => file.name)
for (const required of ['msvcp140.dll', 'msvcp140_1.dll', 'vcruntime140.dll', 'vcruntime140_1.dll']) {
assert.ok(names.includes(required), `${required} must be bundled`)
}
for (const file of manifest.files) {
const bytes = fs.readFileSync(path.join(sourceDir, file.name))
assert.equal(bytes.length, file.size, file.name)
assert.equal(sha256(bytes), file.sha256, file.name)
}
})
test('the Windows package ships the CRT set as an extra resource', () => {
const pkg = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.json'), 'utf8'))
const resources = pkg.build.win.extraResources
assert.ok(
resources.some(entry => entry.from === 'assets/windows/vc-runtime/x64' && entry.to === 'vc-runtime/x64'),
'win.extraResources must carry vc-runtime/x64'
)
})
test('ensureRuntime places the CRT before handing the venv python to the backend', () => {
const source = fs.readFileSync(path.join(here, 'main.ts'), 'utf8')
const start = source.indexOf('async function ensureRuntime(')
const body = source.slice(start, source.indexOf('\nfunction ', start + 1))
const ensureIdx = body.indexOf('ensureWindowsVcRuntime(')
const commandIdx = body.indexOf('backend.command = getVenvPython(VENV_ROOT)')
assert.notEqual(ensureIdx, -1, 'ensureRuntime must call ensureWindowsVcRuntime')
assert.ok(ensureIdx < commandIdx, 'CRT must be in place before the backend command is chosen')
})
+168
View File
@@ -0,0 +1,168 @@
import crypto from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
// ── Windows VC++ runtime for the managed Python ─────────────────────────────
//
// Voice features load native wheels (onnxruntime for the wake word,
// ctranslate2 for local speech-to-text) that link against msvcp140.dll and
// msvcp140_1.dll. The managed CPython only ships vcruntime140*.dll, so on a
// Windows install without the system-wide VC++ Redistributable those imports
// fail with "DLL load failed / The specified module could not be found".
//
// The desktop package carries the Microsoft-signed VC143 CRT set and copies it
// next to the managed python.exe before every local backend start. That
// directory is the process image directory, which Windows searches first for
// extension-module dependencies, so a stale msvcp140.dll elsewhere on PATH can
// never win. Existing installs are healed on their next launch.
export interface VcRuntimeFile {
name: string
size: number
sha256: string
// Files the managed CPython already ships. Never overwrite an existing copy:
// the interpreter owns it and replacing a loaded DLL is not possible anyway.
ownedByPython?: boolean
}
export interface VcRuntimeManifest {
schemaVersion: 1
version: string
architecture: string
files: VcRuntimeFile[]
}
export type VcRuntimeResult =
| { status: 'skipped'; reason: string }
| { status: 'ok' | 'repaired'; pythonHome: string; copied: string[] }
| { status: 'failed'; pythonHome: string | null; copied: string[]; error: string }
const FILE_NAME_RE = /^[a-z0-9_]+\.dll$/i
const SHA256_RE = /^[0-9a-f]{64}$/
export function readPythonHome(venvRoot: string): string | null {
let text: string
try {
text = fs.readFileSync(path.join(venvRoot, 'pyvenv.cfg'), 'utf8')
} catch {
return null
}
for (const line of text.split(/\r?\n/)) {
const match = /^\s*home\s*=\s*(.+?)\s*$/i.exec(line)
if (match) {
return match[1]
}
}
return null
}
export function loadVcRuntimeManifest(sourceDir: string): VcRuntimeManifest {
const manifest = JSON.parse(fs.readFileSync(path.join(sourceDir, 'manifest.json'), 'utf8'))
if (manifest?.schemaVersion !== 1 || !Array.isArray(manifest.files) || manifest.files.length === 0) {
throw new Error('invalid VC++ runtime manifest')
}
for (const file of manifest.files) {
if (!FILE_NAME_RE.test(file?.name) || !SHA256_RE.test(file?.sha256) || !Number.isInteger(file?.size)) {
throw new Error(`invalid VC++ runtime manifest entry: ${JSON.stringify(file?.name)}`)
}
}
return manifest
}
function sha256File(filePath: string): string {
return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex')
}
function matches(filePath: string, file: VcRuntimeFile): boolean {
try {
return fs.statSync(filePath).size === file.size && sha256File(filePath) === file.sha256
} catch {
return false
}
}
function installFile(sourceDir: string, pythonHome: string, file: VcRuntimeFile) {
const source = path.join(sourceDir, file.name)
if (!matches(source, file)) {
throw new Error(`bundled ${file.name} does not match its manifest digest`)
}
const target = path.join(pythonHome, file.name)
const temp = `${target}.aiturk-${process.pid}.tmp`
try {
fs.copyFileSync(source, temp)
if (!matches(temp, file)) {
throw new Error(`copied ${file.name} failed digest verification`)
}
fs.renameSync(temp, target)
} finally {
fs.rmSync(temp, { force: true })
}
}
export function ensureWindowsVcRuntime({
platform,
venvRoot,
sourceDir
}: {
platform: NodeJS.Platform
venvRoot: string
sourceDir: string
}): VcRuntimeResult {
if (platform !== 'win32') {
return { status: 'skipped', reason: 'not windows' }
}
const pythonHome = readPythonHome(venvRoot)
if (!pythonHome || !fs.existsSync(path.join(pythonHome, 'python.exe'))) {
return { status: 'failed', pythonHome, copied: [], error: 'managed python home not found' }
}
const copied: string[] = []
try {
const manifest = loadVcRuntimeManifest(sourceDir)
for (const file of manifest.files) {
const target = path.join(pythonHome, file.name)
if (file.ownedByPython ? fs.existsSync(target) : matches(target, file)) {
continue
}
installFile(sourceDir, pythonHome, file)
copied.push(file.name)
}
} catch (error) {
return { status: 'failed', pythonHome, copied, error: error instanceof Error ? error.message : String(error) }
}
return { status: copied.length ? 'repaired' : 'ok', pythonHome, copied }
}
export function describeVcRuntimeResult(result: VcRuntimeResult): string {
if (result.status === 'skipped') {
return `skipped (${result.reason})`
}
if (result.status === 'failed') {
return `failed for ${result.pythonHome ?? 'unknown python home'}: ${result.error}` +
(result.copied.length ? ` (copied before failure: ${result.copied.join(', ')})` : '')
}
return result.status === 'repaired'
? `installed ${result.copied.join(', ')} into ${result.pythonHome}`
: `verified in ${result.pythonHome}`
}
+12 -2
View File
@@ -2,7 +2,7 @@
"name": "aiturk-ide",
"productName": "AITURK IDE",
"private": true,
"version": "1.0.0-beta.9",
"version": "1.0.0-beta.12",
"description": "TurkServis resmi yapay zekâ geliştirme ortamı. Hermes Agent tabanlıdır.",
"author": "AITURK / TurkServis",
"repository": {
@@ -290,7 +290,17 @@
"nsis",
"msi"
],
"signAndEditExecutable": false
"signAndEditExecutable": false,
"extraResources": [
{
"from": "assets/windows/vc-runtime/x64",
"to": "vc-runtime/x64",
"filter": [
"*.dll",
"manifest.json"
]
}
]
},
"linux": {
"category": "Development",
+24 -1
View File
@@ -10,9 +10,10 @@
// `electron` and `node-pty` are external (provided by the runtime / staged
// separately via stage-native-deps).
import { build } from 'esbuild'
import { createRequire } from 'node:module'
import { resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { mkdirSync } from 'node:fs'
import { mkdirSync, cpSync, existsSync } from 'node:fs'
const here = dirname(fileURLToPath(import.meta.url))
const root = resolve(here, '..')
@@ -63,3 +64,25 @@ await build({
logLevel: 'info',
})
console.log(`bundled ${preloadOut}${isDev ? ' (dev)' : ''}`)
for (const name of ['mobile-host.html', 'mobile-host-ui.mjs', 'mobile-preload.cjs']) {
cpSync(resolve(root, 'electron', name), resolve(distDir, name))
}
mkdirSync(resolve(distDir, 'mobile'), { recursive: true })
for (const name of ['transport.mjs', 'peer-identity.mjs', 'style.css', 'qr.mjs']) {
cpSync(resolve(root, '../mobile/src', name), resolve(distDir, 'mobile', name))
}
// A clean `npm ci` hoists the mobile vendor packages to the workspace root, so
// look them up along Node's resolution path from apps/mobile instead of
// assuming apps/mobile/node_modules exists.
const mobileRequire = createRequire(resolve(root, '../mobile/package.json'))
function mobilePackageDir(name) {
for (const base of mobileRequire.resolve.paths(name) ?? []) {
const dir = resolve(base, name)
if (existsSync(resolve(dir, 'package.json'))) return dir
}
throw new Error(`${name} is not installed for apps/mobile; run npm ci at the repository root`)
}
mkdirSync(resolve(distDir, 'mobile/vendor'), { recursive: true })
cpSync(resolve(mobilePackageDir('qrcode-generator'), 'dist/qrcode.mjs'), resolve(distDir, 'mobile/vendor/qrcode.mjs'))
cpSync(resolve(mobilePackageDir('jsqr'), 'dist/jsQR.js'), resolve(distDir, 'mobile/vendor/jsQR.js'))
cpSync(resolve(mobilePackageDir('jsqr'), 'LICENSE'), resolve(distDir, 'mobile/vendor/jsQR-LICENSE.txt'))
@@ -12,6 +12,7 @@ import {
setModelVisibilityOpen,
setVisibleModels
} from '@/store/model-visibility'
import { openPreview } from '@/store/preview'
import type { LocalRuntimeJob } from '@/types/hermes'
import { ModelCatalogMenu, type ModelMenuController } from './model-catalog-menu'
@@ -24,6 +25,7 @@ beforeAll(() => {
})
const getGlobalModelOptions = vi.fn()
vi.mock('@/store/preview', () => ({ openPreview: vi.fn() }))
vi.mock('@/hermes', () => ({
getGlobalModelOptions: (...args: unknown[]) => getGlobalModelOptions(...args),
@@ -88,6 +90,22 @@ function renderMenu() {
// the kanban board would end up disagreeing about what "my models" means —
// which is exactly the drift extracting this component was meant to prevent.
describe('the catalog owns model curation', () => {
it('opens the chosen TurkServis model details without selecting that model', async () => {
getGlobalModelOptions.mockResolvedValue({ providers: [{
models: ['Outer'], name: 'TurkServis', slug: 'turkservis', api_url: 'https://ai.turkservis.online/v1'
}] })
const select = renderMenu()
const trigger = await screen.findByRole('menuitem', { name: /Outer/ })
fireEvent.keyDown(trigger, { key: 'ArrowRight' })
fireEvent.click(await screen.findByRole('menuitem', { name: /Model \/ combo (details|ayrıntıları)/ }))
expect(openPreview).toHaveBeenCalledWith(expect.objectContaining({
kind: 'url', url: 'https://turkservis.online/router?model=Outer'
}))
expect(select).not.toHaveBeenCalled()
})
it('honours the stored Edit Models shortlist', async () => {
setVisibleModels(new Set([modelVisibilityKey('google', 'gemini-2.5-flash')]))
@@ -25,6 +25,7 @@ import { modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'
import { displayModelName, modelDisplayParts } from '@/lib/model-status-label'
import { DEFAULT_REASONING_EFFORT, reasoningEffortLabel } from '@/lib/reasoning-effort'
import { normalize } from '@/lib/text'
import { turkservisComboDetailsUrl } from '@/lib/turkservis-combo-details'
import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { $localModelsEnabled } from '@/store/local-models-flag'
@@ -38,6 +39,7 @@ import {
modelVisibilityKey,
setModelVisibilityOpen
} from '@/store/model-visibility'
import { openPreview } from '@/store/preview'
import { $collapsedProviders, toggleCollapsedProvider } from '@/store/provider-collapse'
import { $defaultReasoningEffort } from '@/store/session'
import type { LocalModelLoadProgress, ModelOptionProvider, ModelOptionsResponse } from '@/types/hermes'
@@ -588,6 +590,12 @@ export function ModelCatalogMenu({
fastControl={fastControl}
isActive={isCurrent}
model={family.id}
onOpenDetails={turkservisComboDetailsUrl(group.provider.api_url, family.id) ? () => {
const url = turkservisComboDetailsUrl(group.provider.api_url, family.id)!
closeMenu()
openPreview({ kind: 'url', label: t.shell.modelOptions.comboDetails, source: url, url })
} : undefined}
onSelectModel={nextModel => controller.select(nextModel, group.provider.slug)}
onSetOptions={patch =>
controller.setOptions(patch, {
@@ -29,6 +29,7 @@ function renderSubmenu(opts: {
fastControl: FastControl
isActive?: boolean
onSelectModel?: (model: string) => void
onOpenDetails?: () => void
onSetOptions: (patch: { effort?: string; fast?: boolean }) => void
reasoning: boolean
}) {
@@ -43,6 +44,7 @@ function renderSubmenu(opts: {
fastControl={opts.fastControl}
isActive={opts.isActive ?? true}
model="m1"
onOpenDetails={opts.onOpenDetails}
onSelectModel={opts.onSelectModel ?? vi.fn()}
onSetOptions={opts.onSetOptions}
provider="p1"
@@ -60,6 +62,19 @@ function renderSubmenu(opts: {
// ever writes directly again, picking an effort for a kanban card would reach
// over and change the user's live chat.
describe('ModelEditSubmenu reports edits without performing them', () => {
it('opens read-only details without selecting a model or changing its options', () => {
const onOpenDetails = vi.fn()
const onSelectModel = vi.fn()
const onSetOptions = vi.fn()
renderSubmenu({ fastControl: { kind: 'none' }, reasoning: false, onOpenDetails, onSelectModel, onSetOptions })
fireEvent.click(screen.getByRole('menuitem', { name: /Model \/ combo (details|ayrıntıları)/ }))
expect(onOpenDetails).toHaveBeenCalledOnce()
expect(onSelectModel).not.toHaveBeenCalled()
expect(onSetOptions).not.toHaveBeenCalled()
})
it('param fast: reports the toggle', () => {
const onSetOptions = vi.fn()
renderSubmenu({ fastControl: { kind: 'param', on: true }, onSetOptions, reasoning: false })
@@ -75,6 +75,8 @@ interface ModelEditSubmenuProps {
isActive: boolean
/** This row's model id. */
model: string
/** Read-only details; the owner handles opening without changing selection. */
onOpenDetails?: () => void
/** Switch to a specific model id (used to swap base ⇄ -fast variant). */
onSelectModel: (model: string) => Promise<boolean | void> | void
/** Report an option change. This submenu is PURE: it never writes to a
@@ -107,6 +109,7 @@ function ModelEditSubmenuBody({
effort,
fastControl,
isActive,
onOpenDetails,
onSelectModel,
onSetOptions,
reasoning
@@ -140,11 +143,19 @@ function ModelEditSubmenuBody({
const hasFast = fastControl.kind !== 'none'
const fastOn = fastControl.kind === 'none' ? false : fastControl.on
return !hasFast && !reasoning ? (
return !hasFast && !reasoning && !onOpenDetails ? (
<div className="px-2.5 py-3 text-xs text-(--ui-text-tertiary)">{copy.noOptions}</div>
) : (
<>
<DropdownMenuLabel className={dropdownMenuSectionLabel}>{copy.options}</DropdownMenuLabel>
{onOpenDetails ? (
<>
<DropdownMenuItem className={dropdownMenuRow} onSelect={onOpenDetails}>
{copy.comboDetails}
</DropdownMenuItem>
{hasFast || reasoning ? <DropdownMenuSeparator className="mx-0" /> : null}
</>
) : null}
{hasFast || reasoning ? <DropdownMenuLabel className={dropdownMenuSectionLabel}>{copy.options}</DropdownMenuLabel> : null}
{showThinkingToggle ? (
<DropdownMenuItem className={dropdownMenuRow} onSelect={event => event.preventDefault()}>
{copy.thinking}
+1
View File
@@ -2235,6 +2235,7 @@ export const ar = defineLocale({
fast: 'سريع'
},
modelOptions: {
comboDetails: 'تفاصيل النموذج / المجموعة',
noOptions: 'لا توجد خيارات لهذا النموذج',
options: 'الخيارات',
thinking: 'التفكير',
+1
View File
@@ -2999,6 +2999,7 @@ export const en: Translations = {
fast: 'Fast'
},
modelOptions: {
comboDetails: 'Model / combo details',
noOptions: 'No options for this model',
options: 'Options',
thinking: 'Thinking',
+1
View File
@@ -2624,6 +2624,7 @@ export const ja = defineLocale({
fast: '高速'
},
modelOptions: {
comboDetails: 'モデル / コンボの詳細',
noOptions: 'このモデルにはオプションがありません',
options: 'オプション',
thinking: '思考',
+1
View File
@@ -3022,6 +3022,7 @@ export const ru = defineLocale({
fast: 'Быстрая'
},
modelOptions: {
comboDetails: 'Сведения о модели / комбинации',
noOptions: 'Для этой модели нет опций',
options: 'Опции',
thinking: 'Размышление',
+1
View File
@@ -1281,6 +1281,7 @@ export const trOverrides: TranslationOverrides = {
fast: 'Hızlı'
},
modelOptions: {
comboDetails: 'Model / combo ayrıntıları',
noOptions: 'Bu model için seçenek yok',
options: 'Seçenekler',
thinking: 'Düşünme',
+1
View File
@@ -2546,6 +2546,7 @@ export interface Translations {
fast: string
}
modelOptions: {
comboDetails: string
noOptions: string
options: string
thinking: string
+1
View File
@@ -2523,6 +2523,7 @@ export const zhHant = defineLocale({
fast: '快速'
},
modelOptions: {
comboDetails: '模型 / 組合詳細資料',
noOptions: '此模型沒有可用選項',
options: '選項',
thinking: '思考',
+1
View File
@@ -3147,6 +3147,7 @@ export const zh: Translations = {
fast: '快速'
},
modelOptions: {
comboDetails: '模型 / 组合详情',
noOptions: '此模型没有可用选项',
options: '选项',
thinking: '思考',
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest'
import { turkservisComboDetailsUrl } from './turkservis-combo-details'
describe('TurkServis read-only details link', () => {
it('preserves the exact model and drops API query parameters', () => {
const result = turkservisComboDetailsUrl('https://ai.turkservis.online/v1?key=private', '9router-Team & A')!
expect(new URL(result).searchParams.get('model')).toBe('9router-Team & A')
expect(new URL(result).origin).toBe('https://turkservis.online')
expect(result).not.toContain('private')
})
it.each([undefined, '', 'invalid', 'http://ai.turkservis.online/v1',
'https://ai.turkservis.online.evil.test/v1', 'https://other.test/v1',
'https://user:secret@ai.turkservis.online/v1', 'https://ai.turkservis.online:9090/v1'
])('does not offer details for an unrelated or unsafe endpoint: %s', apiUrl => {
expect(turkservisComboDetailsUrl(apiUrl, 'Team')).toBeNull()
})
it('rejects missing and oversized model identities', () => {
expect(turkservisComboDetailsUrl('https://turkservis.online/v1', '')).toBeNull()
expect(turkservisComboDetailsUrl('https://turkservis.online/v1', 'x'.repeat(129))).toBeNull()
})
})
@@ -0,0 +1,21 @@
/** Details use the member portal's own login; API credentials never enter a URL. */
export function turkservisComboDetailsUrl(apiUrl: string | undefined, model: string): string | null {
if (!apiUrl || !model || model.length > 128) {return null}
try {
const endpoint = new URL(apiUrl)
if (
endpoint.protocol !== 'https:' || endpoint.username || endpoint.password || endpoint.port ||
!['ai.turkservis.online', 'turkservis.online'].includes(endpoint.hostname)
) {return null}
const details = new URL('https://turkservis.online/router')
details.searchParams.set('model', model)
return details.href
} catch {
return null
}
}
+1
View File
@@ -0,0 +1 @@
*.bat text eol=crlf
+8
View File
@@ -0,0 +1,8 @@
node_modules/
dist/
android/.gradle/
android/local.properties
android/**/build/
*.keystore
*.jks
test-results/
+236
View File
@@ -0,0 +1,236 @@
# AITURK Mobil — Android geliştirme sürümü 0.1.4
Bu bir **geliştirme paketi**; planın tamamlanmış ürün/kapalı beta kabulü değildir.
Android uygulaması, IDE adaptörü ve hesap doğrulamalı bağlantı servisi kodlandı.
Google Live ve gerçek telefon/ağ doğrulaması henüz yapılmadı. Canlı
turkservis.online veya kurulu IDE bu kaynak değişiklikleriyle güncellenmedi.
## Çalışan ve test edilen parçalar
- Capacitor 8.5.1 Android projesi; Türkçe erişilebilir kurulum ve yazılı kullanım.
- Tarayıcıda mevcut AITURK hesabıyla kısa kod onayı; uygulamaya parola girilmez.
Dar kapsamlı mobil oturum Windows/Android kasasında tutulur. Mevcut hesap API
anahtarı gelişmiş seçenek olarak korunur. Bu yeni giriş henüz canlıya dağıtılmadı.
Telefonun eşleşmesini hedef bilgisayar kendi cihaz tokenıyla onaylar.
- WebRTC DTLS/SCTP veri kanalı; büyük Unicode mesajları sınırlı parçalara bölme.
- Mevcut IDE `/api/sessions` ve JSON-RPC adaptörü. Konuşma ve seçili model
gönderimden önce doğrulanır. Model listesi icat edilmez.
- Görevden önce diske yazılan tekrar gönderim kaydı. Kabul sonucu belirsizse
ikinci kez çalıştırılmaz. Telefonun bekleyen gönderimi Android kasasında kalır.
- Gerçek IDE onay kimliği ve redakte edilmiş tam komutla yalnız `once`/`deny`.
Sürekli/genel izin, sudo/UAC veya ses modeli üzerinden onay yolu yoktur.
- Google anahtarı Windows `safeStorage`, hesap cihaz sırrı Android Keystore
AES-GCM kullanır. Android yedekleme ve cihazlar arası veri taşıma kapatılır.
- Anahtardan kısa ömürlü, model/araç/sistem talimatı kısıtlı Google Live token
üretme kodu; doğrudan Google WebSocket, PCM mikrofon/oynatma ve kapatma kodu.
- Ses görüşmesini kapatma IDE'ye interrupt göndermez. Görünür görev gönder
düğmesi ve ayrı IDE durdur düğmesi vardır.
- Google kullanım bildirimleri ücretli liste tarifesiyle tahmin edilir; her
isteğin tekrar faturalandırılan geçmişi de sayılır. Ayrıntısı eksik tokenlar
için fiyat aralığı gösterilir. Bu fatura, kredi veya ücretsiz kota sorgusu değildir.
- Kullanıcı her görüşme için 1–10 dakika ve 0,01–10 USD tahmini durdurma sınırı
seçer (varsayılan 10 dakika / 0,25 USD). Üst tahmin sınıra ulaşırsa, süre
dolarsa veya 120 saniye kullanım bildirimi gelmezse yalnız Google bağlantısı
kapanır. Otomatik yeniden bağlanılmaz. Her yeni oturumda sayaç sıfırlanır;
bu günlük/aylık bütçe veya Google tarafında kesin harcama tavanı değildir.
## Geliştirme kurulumu
Node 22+, JDK 21 ve Android API 36 gerekir. Bu çalışma sırasında araçlar
`%LOCALAPPDATA%/aiturk-mobile-tools` altına kuruldu; kullanıcı sistem PATH'i
veya yönetici ayarları değiştirilmedi.
```powershell
# Bu klasörde; kök depodaki kurulumu etkilemeyen Android kurulumu
npm ci --workspaces=false --ignore-scripts
npm test --workspaces=false
npm run android:sync --workspaces=false
# JAVA_HOME ve ANDROID_HOME kendi araç yollarınızı göstermeli
.\android\gradlew.bat -p android assembleDebug assembleRelease lintDebug
```
`app-debug.apk` geliştirici anahtarıyla imzalanır. `app-release-unsigned.apk`
üretim imzası içermez ve kurulabilir sürüm olarak paylaşılmamalıdır. Özel üretim
imza anahtarı oluşturulmadı; mağaza hesabı veya ücretli hizmet açılmadı.
Yayın adayı için sürüm ve Android sürüm kodu birlikte açıkça verilir:
```powershell
.\android\gradlew.bat -p android assembleRelease '-PaiturkReleaseVersion=0.1.4-beta.1' '-PaiturkReleaseVersionCode=6'
```
Bu komut yine **imzasız** APK üretir; üretim imzasını veya cihaz kabulünü atlamaz.
İki parametreden yalnız biri, `-dev` etiketi veya 5 ve daha küçük sürüm kodu
verilirse derleme durur. Parametresiz geliştirici derlemesi `0.1.4-dev` / 5 kalır.
Sonraki yayınlarda sürüm kodunu son dağıtılmış APK'dan daha büyük seçin; buradaki
alt sınır yalnız mevcut geliştirme sürümünü korur, uzak yayın envanterini sorgulamaz.
12 Eylül 2026: gerçek Gradle `assembleRelease` çalışması bu parametrelerle 55
saniyede tamamlandı; `aapt2` uygulama kimliği, `0.1.4-beta.1` / 6 ve debug
bayrağının olmadığını doğruladı. Test çıktısının SHA-256 değeri
`a93b93b3080ec484cc998ef316528ff7b947fa366b2ff5de375386acc66fffc4`.
`apksigner verify` imzasız çıktıyı reddetti (beklenen sonuç). Ayrı gerçek Gradle
çalışmaları eksik sürüm kodunu, `0.1.4-dev` yayın etiketini ve sürüm kodu 5'i
reddetti. Bu çıktı yayımlanmadı; imza ve cihaz kabulü değildir.
### Dağıtım APK'sının doğrulanması
`scripts/verify-android-release.mjs` dağıtım öncesi salt okunur APK kontrolüdür.
`--apk`, `--java`, `--apksigner` (Android SDK içindeki apksigner.jar), `--aapt2`,
`--certificate` (bağımsız olarak belirlenen üretim sertifikası SHA-256 değeri),
`--version` ve `--version-code` parametrelerinin tamamını ister. Sertifika pinini
kontrol edilen APK'dan otomatik türetmeyin. Bu araç anahtar üretmez veya APK imzalamaz.
Gerçek apksigner doğrulaması, v2/v3 imza, tek beklenen sertifika, uygulama kimliği
`online.turkservis.aiturk.mobile`, tam sürüm eşleşmesi ve debug bayrağı kontrol edilir.
Dosya doğrulama boyunca değişirse sonuç reddedilir. Debug sertifikası ve `-dev`
sürümü dağıtım için kabul edilmez. Başarılı rapor APK hash'ini verir fakat açıkça
`deviceAcceptanceVerified: false` içerir; fiziksel telefon kabulünün yerine geçmez.
12 Eylül 2026: mevcut mutual-identity geliştirici APK'sı gerçek SDK araçlarıyla
kontrol edildi ve beklenildiği gibi `debug-signing-certificate` ile reddedildi.
Üretim sertifikalı pozitif APK doğrulaması henüz yapılmadı.
## Uyumlu IDE ve bağlantı servisi
Bu kaynak ağacındaki masaüstü paketini normal masaüstü build süreciyle derleyin.
Derlenmiş IDE'yi `--aiturk-mobile` parametresiyle açın. IDE zaten açıksa parametre
mobil bağlantı penceresini açar; çalışmakta olan konuşma kapatılmaz.
Mobil pencere açılmadan uzaktan erişim etkinleşmez.
1. Bilgisayardaki mobil pencerede “AITURK hesabımla giriş yap” seçin; tarayıcıda
hesabınıza girip uygulamanın kodunu onaylayın. “Girişi kontrol et” ile tamamlayın.
2. Bilgisayarı hesapla eşleştirin; açılan mevcut portal sayfasında kodu onaylayın.
3. Android'de aynı AITURK hesabıyla tarayıcı kod girişini tamamlayın. Bilgisayarda
“Telefon için QR oluştur” seçip telefonda kamerayla veya QR resmiyle okuyun.
4. Bilgisayarda “QR ile gelen telefonu getir” seçin; telefonun gösterdiği kısa
kodu girip açıkça onaylayın. Uzun kimliği elle yazmak gerekmez.
5. Bilgisayarda “Mobil bağlantıyı aç”, telefonda “Bilgisayarları bul” ve “Bağlan”.
6. Gerçek IDE konuşmasını seçin. Yazılı görevi görünür önizlemeden gönderin.
7. Google anahtarını telefondaki ayrı güvenli girişten bilgisayara aktarın.
Veri/ücret bilgisini kabul ettikten sonra Google görüşmesini başlatın.
Gateway eş değişikliği `portal/routes_mobile.py` ve `router_gateway.py` içindedir.
Mevcut member guard korunur. Üretim kurulumu ve TURN koşulları eş gateway
deposunun `docs/aiturk-mobile-operations.md` dosyasında açıklanır.
## Doğrulama ve sınırlar
0.1.4-dev (Android versionCode 5), 12 Eylül 2026: 41 mobil test geçti;
tarayıcı uygulama testi, yerel sertifika/DTLS testi ve Electron IPC/Windows kasa
testi geçti. Telefon kimliği QR resminin onaysız içe alınması ve değiştirilmiş
cihaz kimliklerinin reddi test edildi. `assembleDebug lintDebug` başarılı,
uygulama lint sonucu 0 hata / 17 uyarı. Debug APK imzası doğrulandı ve kimlik,
taşıma, uygulama, davet, gizlilik ve ana sayfa dosyaları kaynakla karşılaştırıldı.
APK SHA-256: `94835E223B71BE36AFB26686D3EBC79D8976514FFDB4E7CDFC189ACE7E2F12A5`.
Bu APK geliştirici imzalıdır; üretim/gerçek Android kabulü değildir.
12 Eylül 2026 yerel doğrulaması: `npm test` 37/37 geçti. Ses başlangıcı
beklerken iptal ve kapatılmış oturumu yeniden açma regresyonları önce başarısız
testlerle gösterildi, sonra düzeltildi. `npm run android:sync` ve
`gradlew.bat assembleDebug lintDebug` başarılı; uygulama lint sonucu 0 hata,
17 uyarı. `scripts/browser-smoke.mjs` gerçek DTLS veri kanalında 240.000
karakter aktarımını ve sentetik Google kullanım sınırını doğruladı; Google'a
gerçek çağrı yapmadı. APK içindeki `voice.mjs` kaynakla birebir karşılaştırıldı.
Debug imzası `apksigner verify` ile doğrulandı; bu üretim imzası değildir.
APK SHA-256: `F5DB098DF0F1C59B92F274969FCAD926BCB2DD25AF823533A983085A18BFB966`.
Bu kontrolde `adb devices -l` bağlı cihaz göstermedi; fiziksel telefon kabulü
ve canlı yayın hâlâ tamamlanmadı.
`npm test`: davranış, tekrar gönderim, onay sınırı, ses temizliği ve token kısıtları.
`scripts/browser-smoke.mjs`: yeni test tarayıcısında gerçek DTLS veri kanalı,
240.000 karakter Unicode aktarımı, dar ekran taşması ve dokunma hedefi.
`scripts/electron-smoke.mjs`: gerçek Electron IPC ve Windows safeStorage turu;
yalnız sentetik bir test anahtarı kullanır.
`src/peer-identity.mjs` cihaz kimliğine göre kalıcı standart RTCCertificate
kaydını, atomik ilk oluşturmayı, kayıtlı parmak iziyle yüklemeyi ve SDP kimlik
kontrolünü uygular. Anahtar eksik veya geçersizse yükleme yeni sertifika üretmez.
Bilgisayar QR daveti sürüm 2 ile sertifika parmak izini taşır; telefon bunu
eşleştirme kaydına alır ve SDP uygulanmadan önce kontrol eder. Bilgisayar
bağlantıda kayıtlı sertifikasını kullanır. Eski sürüm 1 QR ve kimliği olmayan
elle eşleştirmeler veri bağlantısı açamaz; yeni QR ile yeniden eşleştirme gerekir.
Telefon da eşleştirmede kendi sertifikasını oluşturur ve bağlantıda aynı
sertifikayı yükler. Kullanıcı telefondaki kimlik belgesini bilgisayardaki
ilgili alana aktarır; `phone.approve` belgeyi eşleştirme kimliği ve sunucunun
onayladığı cihaz kimliğiyle karşılaştırıp Windows kasasına kaydeder. IDE hem
gelen bağlantı listesinde hem `channel.answer` yolunda kayıtlı telefon
parmak izini kontrol eder; renderer SDP'yi uygulamadan önce tekrar doğrular.
İlk kayıt için yerel açık onay gerekir; mevcut telefon kimliği sessizce
değiştirilemez. Telefon kimliğini QR olarak da gösterir. Kullanıcı ekran
görüntüsünü kendi bilgisayarına aktararak “Telefon kimliği QR resmi” alanından
okutabilir; eşleştirme kimliği ve belge doldurulur, fakat otomatik onay verilmez.
Kısa kod ve ayrı onay düğmesi gereklidir; elle belge aktarma yolu da korunur.
`node scripts/certificate-smoke.mjs`: 12 Eylül 2026'da izole Edge bağlamında
yerel WebRTC sertifikasının IndexedDB'ye yazılıp sayfa yenilendikten sonra
aynı parmak iziyle geri alınması, geri alınan sertifikayla gerçek DTLS veri
aktarımı ve yanlış SDP parmak izinde DTLS'nin `failed` durumuna geçmesi
doğrulandı. Test artık gerçek `peer-identity.mjs` modülünü kullanıyor; eşzamanlı
dört oluşturma çağrısının tek kimlikte birleşmesi, kayıp kaydın ve yanlış
parmak izinin reddi de geçti. Tarayıcı uygulama testi ayrıca QR ile eşlenen
bilgisayar yerine farklı sertifikalı SDP geldiğinde görünür kimlik hatası
verildiğini ve hiçbir IDE isteği gönderilmediğini doğruladı. Electron IPC testi
Windows kasasındaki parmak iziyle sertifikanın pencere yenilemesinden sonra
yüklenmesini ve sessiz kimlik değişiminin reddini doğruladı. Bu testlerde portal
ve Google gerçek servisleri kullanılmadı; canlı karşılıklı kimlik kabulü değildir.
Gerçek IDE yolunun testi, kök dizinden zorunlu test sarmalayıcısıyla çalışır:
```bash
scripts/run_tests.sh tests/tui_gateway/test_mobile_runtime_integration.py -q
```
Bu test gerçek IDE HTTP, WebSocket, konuşma veritabanı, prompt.submit ve
message.complete yolunu çalıştırır. Ücretli çıkarım servisi yerine yerel
deterministik sağlayıcı kullanılır. Aynı görev ikinci defa gönderildiğinde IDE
geçmişinde yalnız bir kullanıcı görevi oluşur. Gerçek Google/iş modeli kalite
ve maliyet testi olarak sayılmaz.
12 Eylül 2026, 0.1.4 kaynak doğrulaması: zorunlu `scripts/run_tests.sh`
sarmalayıcısıyla `test_compute_host.py`, `test_compute_host_phase1.py` ve
`test_mobile_runtime_integration.py` birlikte çalıştırıldı. 3 dosyada 16 test
geçti, 0 başarısız; süre 32,9 saniye. Windows venv yönlendirici sürecinin
bildirdiği PID, gerçek süreç soy ağacı üzerinden doğrulanır. Bu koşu yalnız
yerel sentetik sağlayıcı kullanır, telefon donanımı veya Google kabulü değildir.
Henüz tamamlanmayanlar:
- Karşılıklı cihaz kimliğinin gerçek Android ve paketlenmiş IDE arasında,
yeniden başlatma/iptal/anahtar kaybı senaryolarıyla uçtan uca kabulü.
İki yönün kodu var; tarayıcı ve Electron testleri gerçek cihaz kabulünün
yerine geçmez. Telefon QR çıktısının pikselden geri okunması ve Electron'da
QR resminin açık onay vermeden alanlara aktarılması test edildi; gerçek
telefon ekran görüntüsü aktarımı henüz denenmedi.
- Fiziksel Android'de kurulum, mikrofon, kesme, Keystore ve arka plan testi.
- Kullanıcıya ait test anahtarıyla Google Live doğrulaması ve Türkçe konuşma
senaryoları. Sıfır gerçek Google çağrısı yapıldı; ücret oluştuğu iddia edilmiyor.
- Canlı gateway/TURN kurulumu, ayrı mobil ve bilgisayar ağlarıyla tam akış.
- Giriş ve QR artık kodlandı: 9 HTTP/DB testi, 27 mobil testi, gerçek QR pikseli
okuyan (hesap/claim yanıtları sahte) tarayıcı akışı geçti. Fiziksel Android
kamera/giriş kabulü ve farklı ağ bağlantısı henüz yapılmadı.
- Açık talimatla prepare_task/submit_task devri ve görev kimlikli terminal
olayları kodlandı. 25 Node testi ve üç görevli gerçek yerel IDE bağlantı
testi geçti. Canlı Google transkript sırası ve Türkçe kalite kabulü henüz yok.
- Yeniden bağlantı bounded IDE olay tamponunu okuyarak kaçırılan görev
sonucunu alır. Tampon kaybı/backend yeniden başlaması durumunda sonuç
bilinmiyor kalabilir; iş otomatik tekrar çalıştırılmaz.
- Maliyet tahmini/ayarlanabilir oturum sınırı uygulandı: 35 Node testi ve
derlenmiş uygulamanın gerçek WebRTC, sentetik IDE/Google yanıtlı sınır akışı
geçti. Gerçek Google faturasına karşı karşılaştırma henüz yapılmadı.
- Bağımsız güvenlik incelemesi ve sinyalleşme sunucusuna karşı doğrulanmış
kalıcı eş parmak izi. WebRTC standart şifrelemesi vardır; eş kimliğinin
sinyalleşme hizmetine güven sınırı gizlenmez.
- Üretim imzası, kapalı beta kabulü ve turkservis.online indirme yayını.
Capacitor CLI'nin kullanılmayan iOS araç zincirinde `xcode → uuid` üzerinden
3 moderate geliştirme bağımlılığı uyarısı mevcut; Android runtime audit sonucu
ayrıca kontrol edilir. Bunları gizlemek için `npm audit fix --force` uygulanmadı.
## Resmî dayanaklar
- https://capacitorjs.com/docs/getting-started/environment-setup
- https://ai.google.dev/gemini-api/docs/live-api/ephemeral-tokens
- https://ai.google.dev/api/live
- https://ai.google.dev/gemini-api/docs/pricing
- https://github.com/coturn/coturn/blob/master/README.turnserver
+101
View File
@@ -0,0 +1,101 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
+2
View File
@@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep
+71
View File
@@ -0,0 +1,71 @@
apply plugin: 'com.android.application'
// Release identity is explicit; ordinary developer builds retain the -dev label.
def releaseVersion = providers.gradleProperty('aiturkReleaseVersion').orNull
def releaseCode = providers.gradleProperty('aiturkReleaseVersionCode').orNull
if ((releaseVersion == null) != (releaseCode == null)) {
throw new GradleException('Both aiturkReleaseVersion and aiturkReleaseVersionCode are required')
}
def selectedVersionCode = 5
if (releaseVersion != null) {
if (!(releaseVersion ==~ /\d+\.\d+\.\d+(?:-beta\.\d+)?/)) {
throw new GradleException('Release version must be X.Y.Z or X.Y.Z-beta.N; -dev is not a release')
}
if (!(releaseCode ==~ /[1-9]\d{0,9}/) || releaseCode.toLong() <= 5 || releaseCode.toLong() > 2100000000L) {
throw new GradleException('Release version code must be greater than 5 and at most 2100000000')
}
selectedVersionCode = releaseCode.toInteger()
}
android {
namespace = "online.turkservis.aiturk.mobile"
compileSdk = rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "online.turkservis.aiturk.mobile"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode selectedVersionCode
versionName releaseVersion ?: "0.1.4-dev"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
@@ -0,0 +1,19 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<application
android:allowBackup="false"
android:fullBackupContent="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:usesCleartextTraffic="false"
android:icon="@drawable/aiturk_icon"
android:label="@string/app_name"
android:roundIcon="@drawable/aiturk_icon"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
<!-- Permissions -->
</manifest>
@@ -0,0 +1,11 @@
package online.turkservis.aiturk.mobile;
import com.getcapacitor.BridgeActivity;
import android.os.Bundle;
public class MainActivity extends BridgeActivity {
@Override public void onCreate(Bundle savedInstanceState) {
registerPlugin(MobileSecretsPlugin.class);
super.onCreate(savedInstanceState);
}
}
@@ -0,0 +1,120 @@
package online.turkservis.aiturk.mobile;
import android.content.Context;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Base64;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.atomic.AtomicInteger;
/** Standard Android Keystore AEAD storage. Key never leaves AndroidKeyStore. */
@CapacitorPlugin(name = "MobileSecrets")
public class MobileSecretsPlugin extends Plugin {
private static final String ALIAS = "aiturk.mobile.account.v1";
private final AtomicInteger requests = new AtomicInteger();
@PluginMethod public void openLogin(PluginCall call) {
String url = call.getString("url", "");
if (!url.matches("https://turkservis\\.online/account/aiturk/mobile-login/[0-9a-f-]{36}")) {
call.reject("Geçersiz giriş adresi."); return;
}
try {
getActivity().startActivity(new android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)));
call.resolve();
} catch (Exception error) { call.reject("Tarayıcı açılamadı."); }
}
@PluginMethod public void request(PluginCall call) {
String path = call.getString("path", "");
String method = call.getString("method", "GET");
String body = call.getString("body", "");
if (!path.matches("/v1/aiturk/[A-Za-z0-9/_.-]+") || path.contains("..") ||
!method.matches("GET|POST|DELETE") || body.length() > 65536) {
call.reject("Geçersiz hesap isteği."); return;
}
if (requests.incrementAndGet() > 8) { requests.decrementAndGet(); call.reject("Bekleyen hesap istekleri var."); return; }
new Thread(() -> {
HttpsURLConnection connection = null;
try {
connection = (HttpsURLConnection) new URL("https://turkservis.online" + path).openConnection();
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(20000); connection.setReadTimeout(20000);
connection.setRequestMethod(method);
JSObject headers = call.getObject("headers", new JSObject());
for (String name : new String[] {"Authorization", "X-Aiturk-Device-ID", "X-Aiturk-Device-Token"}) {
String value = headers.getString(name, "");
if (value.length() > 1024 || value.contains("\r") || value.contains("\n")) throw new IllegalArgumentException();
if (!value.isEmpty()) connection.setRequestProperty(name, value);
}
connection.setRequestProperty("Content-Type", "application/json");
if (!body.isEmpty()) {
connection.setDoOutput(true);
try (java.io.OutputStream out = connection.getOutputStream()) { out.write(body.getBytes(StandardCharsets.UTF_8)); }
}
int status = connection.getResponseCode();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
InputStream input = status < 400 ? connection.getInputStream() : connection.getErrorStream();
if (input != null) try (InputStream stream = input) {
byte[] buffer = new byte[4096]; int count;
while ((count = stream.read(buffer)) != -1) {
if (bytes.size() + count > 262144) throw new IllegalStateException();
bytes.write(buffer, 0, count);
}
}
JSObject result = new JSObject(); result.put("status", status);
result.put("body", bytes.toString(StandardCharsets.UTF_8.name())); call.resolve(result);
} catch (Exception error) { call.reject("Hesap bağlantısı kurulamadı."); }
finally { if (connection != null) connection.disconnect(); requests.decrementAndGet(); }
}, "aiturk-account").start();
}
private SecretKey key() throws Exception {
KeyStore store = KeyStore.getInstance("AndroidKeyStore"); store.load(null);
if (!store.containsAlias(ALIAS)) {
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
generator.init(new KeyGenParameterSpec.Builder(ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build());
generator.generateKey();
}
return (SecretKey) store.getKey(ALIAS, null);
}
@PluginMethod public void save(PluginCall call) {
String value = call.getString("value");
if (value == null || value.length() > 65536) { call.reject("Geçersiz hesap kaydı."); return; }
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, key());
String encrypted = Base64.encodeToString(cipher.getIV(), Base64.NO_WRAP) + ":" +
Base64.encodeToString(cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)), Base64.NO_WRAP);
boolean saved = getContext().getSharedPreferences("aiturk-mobile", Context.MODE_PRIVATE)
.edit().putString("account", encrypted).commit();
if (!saved) throw new IllegalStateException();
call.resolve();
} catch (Exception error) { call.reject("Android güvenli kasasına kaydedilemedi."); }
}
@PluginMethod public void load(PluginCall call) {
try {
String saved = getContext().getSharedPreferences("aiturk-mobile", Context.MODE_PRIVATE).getString("account", null);
JSObject result = new JSObject();
if (saved != null) {
String[] parts = saved.split(":", 2);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key(), new GCMParameterSpec(128, Base64.decode(parts[0], Base64.NO_WRAP)));
result.put("value", new String(cipher.doFinal(Base64.decode(parts[1], Base64.NO_WRAP)), StandardCharsets.UTF_8));
}
call.resolve(result);
} catch (Exception error) { call.reject("Android güvenli kasası açılamadı."); }
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,5 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="256" android:viewportHeight="256">
<path android:fillColor="#081525" android:pathData="M0,0H256V256H0Z"/>
<path android:fillColor="#24D4C6" android:pathData="M128,30L230,218H185L164,178H92L71,218H26L128,30ZM128,109L106,151H150L128,109Z"/>
<path android:fillColor="#FFFFFF" android:pathData="M128,58L148,96H108L128,58Z"/>
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">AITURK Mobil</string>
<string name="title_activity_main">AITURK Mobil</string>
<string name="package_name">online.turkservis.aiturk.mobile</string>
<string name="custom_url_scheme">online.turkservis.aiturk.mobile</string>
</resources>
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">#081525</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/aiturk_icon</item>
<item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>
</style>
</resources>
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup disableIfNoEncryptionCapabilities="true">
<exclude domain="root" path="."/>
<exclude domain="file" path="."/>
<exclude domain="database" path="."/>
<exclude domain="sharedpref" path="."/>
<exclude domain="external" path="."/>
</cloud-backup>
<device-transfer>
<exclude domain="root" path="."/>
<exclude domain="file" path="."/>
<exclude domain="database" path="."/>
<exclude domain="sharedpref" path="."/>
<exclude domain="external" path="."/>
</device-transfer>
</data-extraction-rules>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
+29
View File
@@ -0,0 +1,29 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.13.0'
classpath 'com.google.gms:google-services:4.4.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
@@ -0,0 +1,3 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
+22
View File
@@ -0,0 +1,22 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+5
View File
@@ -0,0 +1,5 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'
+16
View File
@@ -0,0 +1,16 @@
ext {
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
androidxAppCompatVersion = '1.7.1'
androidxCoordinatorLayoutVersion = '1.3.0'
androidxCoreVersion = '1.17.0'
androidxFragmentVersion = '1.8.9'
coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.14.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
}
+8
View File
@@ -0,0 +1,8 @@
{
"appId": "online.turkservis.aiturk.mobile",
"appName": "AITURK Mobil",
"loggingBehavior": "none",
"webDir": "dist",
"server": { "androidScheme": "https", "cleartext": false },
"android": { "allowMixedContent": false, "webContentsDebuggingEnabled": false }
}
+1250
View File
File diff suppressed because it is too large. Load diff
+13
View File
@@ -0,0 +1,13 @@
{
"name": "aiturk-mobile",
"version": "0.1.4",
"private": true,
"type": "module",
"scripts": {
"build": "node scripts/build.mjs",
"test": "node --test tests/*.test.mjs",
"android:sync": "npm run build && cap sync android"
},
"dependencies": { "@capacitor/core": "8.5.1", "@capacitor/android": "8.5.1", "jsqr": "1.4.0", "qrcode-generator": "2.0.4" },
"devDependencies": { "@capacitor/cli": "8.5.1" }
}
+178
View File
@@ -0,0 +1,178 @@
import { chromium } from 'playwright'
import { createServer } from 'node:http'
import { readFile, mkdir } from 'node:fs/promises'
import { extname, resolve } from 'node:path'
import assert from 'node:assert/strict'
const root = resolve('dist')
const server = createServer(async (request, response) => {
try {
const path = decodeURIComponent(new URL(request.url, 'http://localhost').pathname)
const file = resolve(root, '.' + (path === '/' ? '/index.html' : path))
if (!file.startsWith(root + '\\') && !file.startsWith(root + '/')) throw new Error('outside assets')
const data = await readFile(file)
response.writeHead(200, { 'Content-Type': ({ '.html': 'text/html', '.mjs': 'text/javascript', '.js': 'text/javascript', '.css': 'text/css' })[extname(file)] || 'application/octet-stream' }); response.end(data)
} catch { response.writeHead(404); response.end() }
})
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
const browser = await chromium.launch({ channel: 'msedge', headless: true })
try {
const page = await browser.newPage({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 1 })
page.setDefaultTimeout(15000)
const errors = []; page.on('pageerror', error => errors.push(error.message))
await page.goto(`http://127.0.0.1:${server.address().port}`)
await page.getByRole('heading', { name: 'Fikrini konuş. Birlikte geliştir.' }).waitFor()
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false)
assert.ok((await page.getByRole('button', { name: 'Eşleştirme kodu oluştur' }).boundingBox()).height >= 48)
// UI wiring only: real account authentication is covered by gateway HTTP/DB
// tests. Never submit a credential to the live portal from this smoke test.
const loginCalls = []
await page.route('https://turkservis.online/v1/aiturk/mobile-auth/**', async route => {
const action = new URL(route.request().url()).pathname.split('/').at(-1); loginCalls.push(action)
const result = action === 'start' ? { deviceCode: 'tsml_fixture', userCode: 'ABCDEFGH',
verificationUri: 'https://turkservis.online/account/aiturk/mobile-login/11111111-1111-4111-8111-111111111111' }
: action === 'poll' ? { state: 'approved', accountToken: 'tsml_fixture' } : { revoked: true }
await route.fulfill({ status: 200, contentType: 'application/json', headers: { 'Access-Control-Allow-Origin': '*' }, body: JSON.stringify(result) })
})
await page.getByRole('button', { name: 'AITURK hesabımla giriş yap' }).click()
await page.getByText('Yalnız kendi hesabınızda bu kodu onaylayın: ABCDEFGH').waitFor()
await page.getByRole('button', { name: 'Girişi kontrol et' }).click()
await page.getByText('Hesaba giriş yapıldı.', { exact: true }).waitFor()
let claimed = false
await page.route('https://turkservis.online/v1/aiturk/mobile/invites/**/claim', async route => {
claimed = true
const body = route.request().postDataJSON(); assert.equal(body.secret, 'a'.repeat(43))
await route.fulfill({ status: 201, contentType: 'application/json', headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({ device_id: '33333333-3333-4333-8333-333333333333', device_token: 'fixture-device-secret', pairing_id: 'fixture-pair', user_code: 'QRSTUVWX' }) })
})
const qrImage = await page.evaluate(async () => {
const { drawQr } = await import('./qr.mjs'), canvas = document.createElement('canvas')
window.fixtureDesktopCertificate = await RTCPeerConnection.generateCertificate({ name: 'ECDSA', namedCurve: 'P-256' })
const desktopFingerprint = window.fixtureDesktopCertificate.getFingerprints().find(item => item.algorithm === 'sha-256').value
drawQr(canvas, JSON.stringify({ kind: 'aiturk-mobile-invite', version: 2, desktopFingerprint, inviteId: '11111111-1111-4111-8111-111111111111',
desktopId: '22222222-2222-4222-8222-222222222222', secret: 'a'.repeat(43), expiresAt: new Date(Date.now() + 600000).toISOString() }))
return canvas.toDataURL('image/png').split(',')[1]
})
await page.locator('#qr-file').setInputFiles({ name: 'invite.png', mimeType: 'image/png', buffer: Buffer.from(qrImage, 'base64') })
await page.getByText('Bilgisayarda bekleyen telefonu getirip şu kodu onaylayın: QRSTUVWX').waitFor()
assert.equal(claimed, true)
const phoneQr = await page.evaluate(() => {
const canvas = document.getElementById('phone-identity-qr')
const pixels = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height)
return { decoded: jsQR(pixels.data, pixels.width, pixels.height)?.data,
expected: document.getElementById('phone-identity').value, visible: !canvas.hidden }
})
assert.equal(phoneQr.visible, true)
assert.equal(phoneQr.decoded, phoneQr.expected)
// Run the actual app -> AccountClient -> WebRTC -> VoiceSession wiring.
// Portal, IDE responses and Google frames are synthetic; no paid/API traffic.
await page.route('https://turkservis.online/v1/aiturk/mobile/devices', route => route.fulfill({
json: { devices: [{ id: '22222222-2222-4222-8222-222222222222', name: 'Test bilgisayarı', platform: 'windows', self: false }] } }))
await page.route('https://turkservis.online/v1/aiturk/mobile/ice', route => route.fulfill({ json: { iceServers: [] } }))
await page.route('https://turkservis.online/v1/aiturk/mobile/channels**', async route => {
if (route.request().method() === 'POST' && !route.request().url().endsWith('/heartbeat')) {
const { sdp } = route.request().postDataJSON()
await page.evaluate(async sdp => {
const { completeIce, sendFrame } = await import('./transport.mjs')
const { assertRemoteIdentity } = await import('./peer-identity.mjs')
const trustedPhone = JSON.parse(document.getElementById('phone-identity').value)
assertRemoteIdentity(sdp, trustedPhone.fingerprint)
const pc = new RTCPeerConnection({ certificates: [window.fixtureDesktopCertificate] }); window.fixtureDesktop = pc; window.fixtureActions = []
pc.ondatachannel = event => { event.channel.onmessage = incoming => {
const request = JSON.parse(incoming.data); window.fixtureActions.push(request.action)
const results = {
'sessions.list': { sessions: [{ id: 'fixture-session', title: 'Test işi', model: 'fixture-model' }] },
'session.open': { model: 'fixture-model', messages: [], approval: null, running: false },
'voice.token': { token: 'fixture-only', model: 'gemini-3.1-flash-live-preview' },
}
sendFrame(event.channel, { id: request.id, result: results[request.action] || {} })
} }
await pc.setRemoteDescription({ type: 'offer', sdp })
await pc.setLocalDescription(await pc.createAnswer()); await completeIce(pc)
window.fixtureAnswer = pc.localDescription.sdp
}, sdp)
await route.fulfill({ json: {} })
} else await route.fulfill({ json: { sdp: await page.evaluate(() => window.fixtureAnswer) } })
})
await page.evaluate(() => {
window.fixtureVoiceSockets = []
window.WebSocket = class {
constructor(url) {
if (!url.startsWith('wss://generativelanguage.googleapis.com/')) throw new Error('Unexpected test socket')
this.readyState = 1; this.bufferedAmount = 0; window.fixtureVoiceSockets.push(this)
queueMicrotask(() => this.onopen?.())
}
send(raw) {
if (JSON.parse(raw).setup) queueMicrotask(() => this.onmessage?.({ data: JSON.stringify({ setupComplete: {} }) }))
}
close() { this.readyState = 3; this.onclose?.() }
}
})
await page.getByRole('button', { name: 'Onaydan sonra bilgisayarları bul' }).click()
await page.getByRole('button', { name: 'Bilgisayara bağlan', exact: true }).click()
await page.getByText('Bilgisayar bağlı. IDE konuşmasını seçin.', { exact: true }).waitFor()
await page.getByRole('button', { name: 'Konuşmaları yenile' }).click()
await page.getByRole('button', { name: 'Bu konuşmayı seç', exact: true }).click()
await page.getByText('IDE konuşması açıldı.', { exact: true }).waitFor()
await page.locator('#consent').check()
await page.locator('#voice-budget').fill('0.01')
await page.locator('#voice-minutes').fill('3')
await page.getByRole('button', { name: 'Asistanla yazış', exact: true }).click()
await page.getByText('Google asistanı bağlı.', { exact: true }).waitFor()
assert.match(await page.locator('#usage').textContent(), /henüz bilinmiyor/)
await page.evaluate(() => window.fixtureVoiceSockets[0].onmessage({ data: JSON.stringify({ usageMetadata: {
promptTokenCount: 1000, responseTokenCount: 1000, totalTokenCount: 2000,
promptTokensDetails: [{ modality: 'AUDIO', tokenCount: 1000 }],
responseTokensDetails: [{ modality: 'AUDIO', tokenCount: 1000 }],
} }) }))
await page.locator('#voice-status').filter({ hasText: 'maliyet sınırına ulaşıldı' }).waitFor()
assert.match(await page.locator('#usage').textContent(), /0\.0150–0\.0150 USD/)
assert.equal(await page.evaluate(() => window.fixtureVoiceSockets[0].readyState), 3)
assert.deepEqual(await page.evaluate(() => window.fixtureActions), ['sessions.list', 'session.open', 'voice.token'])
assert.deepEqual(await page.evaluate(() => JSON.parse(localStorage.getItem('aiturk.voice-limits'))), { minutes: 3, usd: 0.01 })
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false)
await mkdir('test-results', { recursive: true })
await page.screenshot({ path: 'test-results/android-voice-limit.png', fullPage: true })
await page.evaluate(() => window.fixtureDesktop.close())
// A signaling service returning another machine's valid SDP must not replace
// the identity captured from the user's QR or receive any IDE requests.
await page.evaluate(async () => {
window.fixtureDesktopCertificate = await RTCPeerConnection.generateCertificate({ name: 'ECDSA', namedCurve: 'P-256' })
})
await page.getByRole('button', { name: 'Bilgisayara bağlan', exact: true }).click()
await page.locator('#status').filter({ hasText: 'Cihaz kimliği doğrulanamadı' }).waitFor()
assert.deepEqual(await page.evaluate(() => window.fixtureActions), [])
await page.evaluate(() => window.fixtureDesktop.close())
await page.getByRole('button', { name: 'Bu uygulamadaki hesaptan çık' }).click()
await page.getByText('Bu uygulamanın oturumu kapatıldı.', { exact: false }).waitFor()
assert.deepEqual(loginCalls, ['start', 'poll', 'logout'])
await mkdir('test-results', { recursive: true })
await page.screenshot({ path: 'test-results/android-onboarding.png', fullPage: true })
const result = await page.evaluate(async () => {
const { completeIce, DataRequests, sendFrame } = await import('./transport.mjs')
const phone = new RTCPeerConnection(), desktop = new RTCPeerConnection()
try {
const channel = phone.createDataChannel('aiturk-mobile-v1'), requests = new DataRequests(channel, () => {})
const remoteReady = new Promise(resolve => { desktop.ondatachannel = event => {
event.channel.onmessage = incoming => {
const request = JSON.parse(incoming.data)
sendFrame(event.channel, { id: request.id, result: { action: request.action, text: 'Türkçe 🟢 '.repeat(24000) } })
}
event.channel.onopen = resolve
} })
await phone.setLocalDescription(await phone.createOffer()); await completeIce(phone)
await desktop.setRemoteDescription(phone.localDescription)
await desktop.setLocalDescription(await desktop.createAnswer()); await completeIce(desktop)
await phone.setRemoteDescription(desktop.localDescription)
await Promise.race([remoteReady, new Promise((_, reject) => setTimeout(() => reject(new Error('WebRTC timeout')), 15000))])
if (channel.readyState !== 'open') await new Promise(resolve => channel.onopen = resolve)
const response = await requests.call('session.history', { sessionId: 'fixture' })
return { length: response.text.length, expected: 'Türkçe 🟢 '.repeat(24000).length, action: response.action,
connectionState: phone.connectionState, dtls: phone.sctp.transport.state }
} finally { phone.close(); desktop.close() }
})
assert.equal(result.length, result.expected); assert.equal(result.dtls, 'connected'); assert.equal(result.action, 'session.history')
assert.deepEqual(errors, [])
console.log(JSON.stringify({ onboarding: 'passed', mockedLoginUi: 'passed', realQrImageWithMockedClaim: 'passed',
appWebRTCWithSyntheticGoogleUsageLimit: 'passed', qrPinnedDesktopReplacement: 'rejected', realWebRTC: result, errors }))
} finally { await browser.close(); server.close() }
+12
View File
@@ -0,0 +1,12 @@
import { cp, mkdir } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { dirname, join } from 'node:path'
await mkdir(new URL('../dist', import.meta.url), { recursive: true })
await cp(new URL('../src', import.meta.url), new URL('../dist', import.meta.url), { recursive: true })
const core = dirname(createRequire(import.meta.url).resolve('@capacitor/core/package.json'))
await cp(join(core, 'dist', 'capacitor.js'), new URL('../dist/capacitor.js', import.meta.url))
await mkdir(new URL('../dist/vendor', import.meta.url), { recursive: true })
await cp(new URL('../node_modules/qrcode-generator/dist/qrcode.mjs', import.meta.url), new URL('../dist/vendor/qrcode.mjs', import.meta.url))
await cp(new URL('../node_modules/jsqr/dist/jsQR.js', import.meta.url), new URL('../dist/vendor/jsQR.js', import.meta.url))
await cp(new URL('../node_modules/jsqr/LICENSE', import.meta.url), new URL('../dist/vendor/jsQR-LICENSE.txt', import.meta.url))
console.log('AITURK Android web assets built.')
+119
View File
@@ -0,0 +1,119 @@
// Real identity-module + native DTLS test; full app pairing is tested separately.
// Synthetic local peers, isolated browser context, no account or Google requests.
import { chromium } from 'playwright'
import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
import assert from 'node:assert/strict'
const server = createServer(async (request, response) => {
if (request.url === '/peer-identity.mjs') {
try {
const source = await readFile(new URL('../src/peer-identity.mjs', import.meta.url))
response.writeHead(200, { 'Content-Type': 'text/javascript' }); response.end(source)
} catch { response.writeHead(500); response.end() }
return
}
response.writeHead(200, { 'Content-Type': 'text/html' })
response.end('<!doctype html><title>Local certificate test</title>')
})
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
let browser
try {
browser = await chromium.launch({ channel: 'msedge', headless: true })
const page = await browser.newPage()
page.setDefaultTimeout(20000)
await page.goto(`http://127.0.0.1:${server.address().port}`)
const original = await page.evaluate(async () => {
const { createDeviceIdentity } = await import('/peer-identity.mjs')
const results = await Promise.all(Array.from({ length: 4 }, () => createDeviceIdentity('11111111-1111-4111-8111-111111111111')))
if (new Set(results.map(value => value.fingerprint)).size !== 1) throw new Error('Concurrent identity creation diverged')
const { certificate, fingerprint } = results[0]
return { fingerprints: certificate.getFingerprints(), fingerprint, expires: certificate.expires }
})
await page.reload()
const result = await page.evaluate(async expected => {
const { loadDeviceIdentity, assertRemoteIdentity } = await import('/peer-identity.mjs')
const { certificate } = await loadDeviceIdentity('11111111-1111-4111-8111-111111111111', expected)
let missingRejected = false, wrongPinRejected = false
try { await loadDeviceIdentity('22222222-2222-4222-8222-222222222222', expected) } catch { missingRejected = true }
try { await loadDeviceIdentity('11111111-1111-4111-8111-111111111111', Array(32).fill('00').join(':')) } catch { wrongPinRejected = true }
const peers = []
const complete = async pc => {
if (pc.iceGatheringState === 'complete') return
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => { cleanup(); reject(new Error('ICE timeout')) }, 10000)
const check = () => { if (pc.iceGatheringState === 'complete') { cleanup(); resolve() } }
const cleanup = () => { clearTimeout(timeout); pc.removeEventListener('icegatheringstatechange', check) }
pc.addEventListener('icegatheringstatechange', check); check()
})
}
try {
const phone = new RTCPeerConnection({ iceServers: [] })
const desktop = new RTCPeerConnection({ iceServers: [], certificates: [certificate] })
peers.push(phone, desktop)
const channel = phone.createDataChannel('certificate-probe')
desktop.ondatachannel = event => { event.channel.onmessage = message => event.channel.send(message.data) }
await phone.setLocalDescription(await phone.createOffer()); await complete(phone)
await desktop.setRemoteDescription(phone.localDescription)
await desktop.setLocalDescription(await desktop.createAnswer()); await complete(desktop)
const advertised = desktop.localDescription.sdp.split(/\r?\n/).filter(line => line.startsWith('a=fingerprint:'))
assertRemoteIdentity(desktop.localDescription.sdp, expected)
await phone.setRemoteDescription(desktop.localDescription)
const echo = await new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('DTLS echo timeout')), 15000)
channel.onmessage = event => { clearTimeout(timeout); resolve(event.data) }
channel.onopen = () => channel.send('Türkçe kimlik doğrulama 🟢')
if (channel.readyState === 'open') channel.onopen()
})
const goodDtls = phone.sctp.transport.state
const wrongCertificate = await RTCPeerConnection.generateCertificate({ name: 'ECDSA', namedCurve: 'P-256' })
const wrongFingerprint = wrongCertificate.getFingerprints().find(item => item.algorithm === 'sha-256').value.toUpperCase()
let untrustedPeerRejected = false
try { assertRemoteIdentity(desktop.localDescription.sdp, wrongFingerprint) } catch { untrustedPeerRejected = true }
const badPhone = new RTCPeerConnection({ iceServers: [] })
const badDesktop = new RTCPeerConnection({ iceServers: [], certificates: [certificate] })
peers.push(badPhone, badDesktop)
const badChannel = badPhone.createDataChannel('certificate-mismatch')
let mismatchOpened = false
badChannel.onopen = () => { mismatchOpened = true }
await badPhone.setLocalDescription(await badPhone.createOffer()); await complete(badPhone)
await badDesktop.setRemoteDescription(badPhone.localDescription)
await badDesktop.setLocalDescription(await badDesktop.createAnswer()); await complete(badDesktop)
await badPhone.setRemoteDescription({ type: 'answer', sdp: badDesktop.localDescription.sdp
.split(/\r?\n/).map(line => line.startsWith('a=fingerprint:sha-256 ')
? `a=fingerprint:sha-256 ${wrongFingerprint}` : line).join('\r\n') })
const mismatchState = await new Promise((resolve, reject) => {
const timeout = setTimeout(() => { cleanup(); reject(new Error('No definitive certificate rejection')) }, 15000)
const check = () => {
const state = badPhone.sctp?.transport.state
if (state === 'failed' || state === 'connected') { cleanup(); resolve(state) }
}
const cleanup = () => { clearTimeout(timeout); badPhone.removeEventListener('connectionstatechange', check) }
badPhone.addEventListener('connectionstatechange', check); check()
})
return { fingerprints: certificate.getFingerprints(), expires: certificate.expires,
nativeCertificate: certificate instanceof RTCCertificate, advertised, echo,
dtls: goodDtls, mismatchState, mismatchOpened, missingRejected, wrongPinRejected, untrustedPeerRejected }
} finally { for (const peer of peers) peer.close() }
}, original.fingerprint)
assert.equal(result.nativeCertificate, true)
assert.deepEqual(result.fingerprints, original.fingerprints)
assert.equal(result.expires, original.expires)
assert.ok(result.expires > Date.now())
const sha256 = original.fingerprints.find(item => item.algorithm === 'sha-256')
assert.ok(sha256)
assert.ok(result.advertised.some(line => line.toLowerCase() === `a=fingerprint:sha-256 ${sha256.value}`.toLowerCase()))
assert.equal(result.echo, 'Türkçe kimlik doğrulama 🟢')
assert.equal(result.dtls, 'connected')
assert.equal(result.mismatchState, 'failed')
assert.equal(result.mismatchOpened, false)
assert.equal(result.missingRejected, true)
assert.equal(result.wrongPinRejected, true)
assert.equal(result.untrustedPeerRejected, true)
console.log(JSON.stringify({ nativeCertificatePersistence: 'passed', reload: 'passed',
restoredCertificateDtlsEcho: 'passed', nativeFingerprintMismatch: 'rejected',
concurrentCreation: 'passed', missingKeyAndWrongPin: 'rejected', scope: 'identity module and native DTLS; not full app pairing' }))
} finally {
await browser?.close()
server.close()
}
+100
View File
@@ -0,0 +1,100 @@
import { app, safeStorage } from 'electron'
import { mkdtemp, readFile, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { resolve, join } from 'node:path'
import assert from 'node:assert/strict'
import { createMobileWindow } from '../../desktop/electron/mobile-host.mjs'
import { MobileVault } from '../../desktop/electron/mobile-secrets.mjs'
const directory = await mkdtemp(join(tmpdir(), 'aiturk-mobile-electron-'))
app.setPath('userData', join(directory, 'electron-profile'))
void app.whenReady().then(async () => {
let window
try {
assert.ok(safeStorage.isEncryptionAvailable(), 'Windows encryption unavailable')
window = createMobileWindow({ directory, assets: resolve('apps/desktop/dist'), show: false,
resolveBackend: async () => { throw new Error('No live backend in vault smoke test') } })
await new Promise(resolve => window.webContents.once('did-finish-load', resolve))
const result = await window.webContents.executeJavaScript(`(async () => {
const before = await mobileHost.call('setup');
await mobileHost.call('account.save', {token:'local-fake-account-for-encryption-test'});
const after = await mobileHost.call('setup');
return {before,after,heading:document.querySelector('h1').textContent};
})()`)
assert.equal(result.before.hasAccount, false); assert.equal(result.after.hasAccount, true)
const blob = await readFile(join(directory, 'mobile', 'mobile-secrets.bin'))
assert.ok(!blob.includes(Buffer.from('local-fake-account-for-encryption-test')))
const vault = new MobileVault(join(directory, 'mobile'), safeStorage)
assert.equal((await vault.load()).accountToken, 'local-fake-account-for-encryption-test')
await vault.save({ ...await vault.load(), deviceId: '11111111-1111-4111-8111-111111111111' })
const fingerprint = await window.webContents.executeJavaScript(`(async () => {
const { createDeviceIdentity } = await import('./mobile/peer-identity.mjs');
const setup = await mobileHost.call('setup');
const identity = await createDeviceIdentity(setup.deviceId);
await mobileHost.call('identity.save', {deviceId:setup.deviceId, fingerprint:identity.fingerprint});
let rejected = false;
try { await mobileHost.call('identity.save', {deviceId:setup.deviceId, fingerprint:Array(32).fill('00').join(':')}); }
catch { rejected = true; }
if (!rejected) throw new Error('Changed identity silently accepted');
return identity.fingerprint;
})()`)
assert.equal((await vault.load()).localFingerprint, fingerprint)
const reloaded = new Promise(resolve => window.webContents.once('did-finish-load', resolve))
window.webContents.reload(); await reloaded
const restored = await window.webContents.executeJavaScript(`(async () => {
const { loadDeviceIdentity } = await import('./mobile/peer-identity.mjs');
const setup = await mobileHost.call('setup');
const identity = await loadDeviceIdentity(setup.deviceId, setup.localFingerprint);
return identity.fingerprint;
})()`)
assert.equal(restored, fingerprint)
const originalFetch = globalThis.fetch, phoneId = '33333333-3333-4333-8333-333333333333'
const pairingId = '44444444-4444-4444-8444-444444444444', phonePin = Array(32).fill('AB').join(':')
let advertisedPin = phonePin, approvals = 0
globalThis.fetch = async (url, options) => {
const path = new URL(url).pathname
if (path === `/v1/aiturk/pairings/${pairingId}/approve` && options.method === 'POST') {
approvals++
return Response.json({ device_id: phoneId, status: 'approved' })
}
if (path === '/v1/aiturk/mobile/channels') return Response.json({ channels: [{ id: 'fixture-channel',
phone_id: phoneId, sdp: `v=0\r\na=fingerprint:sha-256 ${advertisedPin}\r\n` }] })
throw new Error('Unexpected network request in isolated test')
}
try {
const proof = JSON.stringify({ kind: 'aiturk-phone-identity', version: 1, pairingId, deviceId: phoneId, fingerprint: phonePin })
const qrImport = await window.webContents.executeJavaScript(`(async () => {
const { drawQr } = await import('./mobile/qr.mjs');
const canvas = document.createElement('canvas'); drawQr(canvas, ${JSON.stringify(proof)});
const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
const transfer = new DataTransfer(); transfer.items.add(new File([blob], 'phone-identity.png', {type:'image/png'}));
const input = document.getElementById('phone-identity-file'); input.files = transfer.files;
await input.onchange({target:input});
return {pairingId:document.getElementById('pairing').value, proof:document.getElementById('phone-identity').value,
status:document.getElementById('status').textContent};
})()`)
assert.equal(qrImport.pairingId, pairingId)
assert.equal(qrImport.proof, proof)
assert.match(qrImport.status, /henüz izin verilmedi/)
assert.equal(approvals, 0)
const accepted = await window.webContents.executeJavaScript(`mobileHost.call('phone.approve', ${JSON.stringify({ pairingId, code: 'QRSTUVWX', identity: proof })})`)
assert.equal(accepted.device_id, phoneId)
assert.equal((await vault.load()).phoneFingerprints[phoneId], phonePin)
const inbox = await window.webContents.executeJavaScript(`mobileHost.call('inbox')`)
assert.equal(inbox.channels[0].trustedPhoneFingerprint, phonePin)
advertisedPin = Array(32).fill('CD').join(':')
await assert.rejects(window.webContents.executeJavaScript(`mobileHost.call('inbox')`), /kimliği/)
await assert.rejects(window.webContents.executeJavaScript(`mobileHost.call('channel.answer', {channelId:'fixture-channel',sdp:'unused'})`), /kimliği/)
const changed = JSON.stringify({ kind: 'aiturk-phone-identity', version: 1, pairingId, deviceId: phoneId, fingerprint: advertisedPin })
await assert.rejects(window.webContents.executeJavaScript(`mobileHost.call('phone.approve', ${JSON.stringify({ pairingId, code: 'QRSTUVWX', identity: changed })})`), /kimliği/)
assert.equal(approvals, 1)
assert.equal((await vault.load()).phoneFingerprints[phoneId], phonePin)
} finally { globalThis.fetch = originalFetch }
await vault.save({})
const receipt = { realElectronIpc: 'passed', windowsSafeStorage: 'passed', desktopIdentityReload: 'passed',
silentIdentityReplacement: 'rejected', locallyApprovedPhonePin: 'passed',
changedPhoneBeforeAnswer: 'rejected', identityQrImportWithoutApproval: 'passed', heading: result.heading, checkedAt: new Date().toISOString() }
await writeFile('apps/mobile/test-results/electron-smoke.json', JSON.stringify(receipt))
console.log(JSON.stringify(receipt))
window.destroy(); app.exit(0)
} catch (error) { console.error(error); window?.destroy(); app.exit(1) }
})
+32
View File
@@ -0,0 +1,32 @@
import assert from 'node:assert/strict'
import { DeliveryJournal, MobileGatewayClient } from '../../desktop/electron/mobile-adapter.mjs'
const [port, directory] = process.argv.slice(2), events = []
const makeClient = () => new MobileGatewayClient(async () => ({ baseUrl: `http://127.0.0.1:${port}`,
wsUrl: `ws://127.0.0.1:${port}/api/ws?token=local-mobile-integration-token`, token: 'local-mobile-integration-token' }),
event => events.push(event), { deviceId: 'phone-fixture', journal: new DeliveryJournal(directory), authorize: async () => {} })
let client = makeClient()
try {
const list = await client.handle({ id: 'list', action: 'sessions.list' })
assert.ok(list.sessions.some(row => row.id === 'mobile-integration-session'))
const selected = await client.handle({ id: 'open', action: 'session.open', params: { sessionId: 'mobile-integration-session' } })
assert.equal(selected.model, 'mobile-fixture')
const request = { id: 'send', action: 'task.submit', params: { taskId: 'one-task', sessionId: 'mobile-integration-session',
model: selected.model, intent: 'research', text: 'MOBIL_GOREV_20260908: Yalnız bağlantı sınaması; dosya değiştirme.' } }
assert.equal((await client.handle(request)).state, 'accepted')
assert.equal((await client.handle(request)).duplicate, true)
const queued = ['second-task', 'third-task'].map(taskId => ({ ...request, params: { ...request.params, taskId,
text: 'MOBIL_SIRA_20260908: Aynı metin ama ayrı kullanıcı görev kimliği.' } }))
for (const entry of queued) assert.equal((await client.handle(entry)).state, 'accepted')
client.close()
client = makeClient()
await client.handle({ id: 'open-again', action: 'session.open', params: { sessionId: request.params.sessionId } })
for (const entry of [request, ...queued]) assert.equal((await client.handle(entry)).duplicate, true)
for (let i = 0; i < 600 && new Set(events.filter(event => event.event === 'task.complete').map(e => e.taskId)).size < 3; i++) await new Promise(resolve => setTimeout(resolve, 100))
const results = events.filter(event => event.event === 'task.complete')
assert.deepEqual([...new Set(results.map(e => e.taskId))].sort(), ['one-task', 'second-task', 'third-task'])
const result = results.find(event => event.taskId === 'one-task')
assert.ok(result, 'real runtime completion event missing')
assert.equal(result.taskId, 'one-task')
assert.equal(result.status, 'complete', JSON.stringify(result)); assert.equal(result.text, 'MOBIL_RUNTIME_OK')
console.log(JSON.stringify({ result, duplicateSuppressed: true }))
} finally { client.close() }
@@ -0,0 +1,77 @@
import { createHash } from 'node:crypto'
import { createReadStream } from 'node:fs'
import { lstat } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { spawnSync } from 'node:child_process'
import { parseArgs } from 'node:util'
import { pathToFileURL } from 'node:url'
export function validateAndroidRelease({ signature, badging, certificate, version, versionCode }) {
const expected = certificate.trim().replaceAll(':', '').toLowerCase()
if (!/^[a-f0-9]{64}$/.test(expected)) throw new Error('certificate-pin-invalid')
if (!/^\d+\.\d+\.\d+(?:-beta\.\d+)?$/.test(version)) throw new Error('release-version-invalid')
if (!Number.isSafeInteger(versionCode) || versionCode <= 0) throw new Error('version-code-invalid')
const signers = [...signature.matchAll(/^Signer #\d+ certificate SHA-256 digest: ([a-fA-F0-9]{64})\s*$/gm)]
if (signers.length !== 1 || signers[0][1].toLowerCase() !== expected) throw new Error('signing-certificate-mismatch')
if (/^Signer #\d+ certificate DN:.*\bCN=Android Debug\b/im.test(signature)) throw new Error('debug-signing-certificate')
if (!/^Verified using v[23](?:\.\d+)? scheme[^\r\n]*: true\s*$/m.test(signature)) throw new Error('modern-apk-signature-required')
const packages = [...badging.matchAll(/^package: name='([^']+)' versionCode='([^']+)' versionName='([^']+)'/gm)]
if (packages.length !== 1 || packages[0][1] !== 'online.turkservis.aiturk.mobile') throw new Error('application-id-mismatch')
if (packages[0][2] !== String(versionCode) || packages[0][3] !== version) throw new Error('apk-version-mismatch')
if (/^application-debuggable\b/m.test(badging)) throw new Error('debuggable-apk')
return { applicationId: packages[0][1], version, versionCode, certificateSha256: expected }
}
async function regularFile(path) {
let current = path
while (true) {
const info = await lstat(current)
if (info.isSymbolicLink()) throw new Error('apk-reparse-path')
if (current === path && !info.isFile()) throw new Error('apk-not-regular')
const parent = dirname(current)
if (parent === current) return
current = parent
}
}
async function digest(path) {
const hash = createHash('sha256')
for await (const chunk of createReadStream(path)) hash.update(chunk)
return hash.digest('hex')
}
function tool(executable, args) {
const env = { ...process.env }
delete env.JAVA_TOOL_OPTIONS
delete env._JAVA_OPTIONS
delete env.JDK_JAVA_OPTIONS
const result = spawnSync(executable, args, { env, encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 1024 * 1024 })
if (result.error || result.status !== 0) throw new Error('android-verification-tool-failed')
return result.stdout
}
export async function verifyAndroidRelease(options) {
const apk = resolve(options.apk)
await regularFile(apk)
const before = await lstat(apk)
const sha256 = await digest(apk)
const signature = tool(resolve(options.java), ['-jar', resolve(options.apksigner), 'verify', '--verbose', '--print-certs', apk])
const badging = tool(resolve(options.aapt2), ['dump', 'badging', apk])
const identity = validateAndroidRelease({ ...options, signature, badging })
await regularFile(apk)
const after = await lstat(apk)
if (before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || await digest(apk) !== sha256) throw new Error('apk-changed-during-verification')
return { verified: true, ...identity, size: after.size, sha256, deviceAcceptanceVerified: false }
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
const { values } = parseArgs({ options: Object.fromEntries(['apk', 'java', 'apksigner', 'aapt2', 'certificate', 'version', 'version-code'].map(name => [name, { type: 'string' }])) })
try {
if (Object.keys(values).length !== 7) throw new Error('all-release-verification-arguments-required')
console.log(JSON.stringify(await verifyAndroidRelease({ ...values, versionCode: Number(values['version-code']) })))
} catch (error) {
const code = /^[a-z][a-z0-9-]{1,95}$/.test(error.message) ? error.message : 'android-release-verification-failed'
console.error(JSON.stringify({ verified: false, code }))
process.exitCode = 1
}
}
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more