2026-10-25 18:20:21 +03:00
<? php
/**
* SnapCAD — YakNet Ekosistem OAuth 2.0 & Bulut JSON Veritabanı Yapı landı rması
*
* Gizli değerler (DB parolası , OAuth client secret) artı k kodda tutulmaz.
* Yerel geliştirmede proje kökündeki .env dosyası nı kullanı n.
* .env dosyası git'e eklenmemelidir; örnek için .env.example dosyası na bakı n.
*/
$autoloadPaths = [
__DIR__ . '/vendor/autoload.php' ,
dirname ( __DIR__ , 3 ) . '/vendor/autoload.php' ,
];
foreach ( $autoloadPaths as $autoloadPath ) {
if ( is_file ( $autoloadPath )) {
require_once $autoloadPath ;
break ;
}
}
use YakNet\YAuth\Provider\YakNetProvider ;
use GuzzleHttp\Client as GuzzleClient ;
date_default_timezone_set ( 'Europe/Istanbul' );
if ( class_exists ( \Dotenv\Dotenv :: class )) {
try {
\Dotenv\Dotenv :: createImmutable ( __DIR__ ) -> safeLoad ();
} catch ( Throwable $envError ) {
error_log ( '[SnapCAD Config] .env dosyası okunamadı : ' . $envError -> getMessage ());
if ( PHP_SAPI === 'cli' ) {
fwrite ( STDERR , "[SnapCAD] .env dosyası geçersiz. Ayrı ntı lar için PHP hata günlüğüne bakı n. \n " );
exit ( 1 );
}
http_response_code ( 500 );
header ( 'Content-Type: text/plain; charset=utf-8' );
echo "Sunucu yapı landı rma hatası . Lütfen yöneticiye başvurun. \n " ;
exit ;
}
}
/**
* .env / ortam değişkeni okur. Boş değerleri yok sayar.
*/
function snapcad_env ( string $key , ? string $default = null ) : ? string
{
$value = $_ENV [ $key ] ?? $_SERVER [ $key ] ?? getenv ( $key );
if ( $value === false || $value === null || $value === '' ) {
return $default ;
}
return trim (( string ) $value );
}
function snapcad_bool_env ( string $key , bool $default = false ) : bool
{
$value = snapcad_env ( $key );
if ( $value === null ) {
return $default ;
}
return filter_var ( $value , FILTER_VALIDATE_BOOLEAN );
}
/**
* Cloudflare Tunnel / ters proxy arkası nda HTTPS algı lar.
*/
function snapcad_is_https () : bool
{
if ( ! empty ( $_SERVER [ 'HTTPS' ]) && strtolower (( string ) $_SERVER [ 'HTTPS' ]) !== 'off' ) {
return true ;
}
if ( strtolower (( string )( $_SERVER [ 'HTTP_X_FORWARDED_PROTO' ] ?? '' )) === 'https' ) {
return true ;
}
if (( string )( $_SERVER [ 'SERVER_PORT' ] ?? '' ) === '443' ) {
return true ;
}
return false ;
}
function snapcad_json_response ( array $payload , int $status = 200 ) : void
{
if ( ! headers_sent ()) {
http_response_code ( $status );
header ( 'Content-Type: application/json; charset=utf-8' );
header ( 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0' );
}
echo json_encode ( $payload , JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
exit ;
}
/**
* Cloudflare Tunnel arkası nda gerçek istemci IP'sini bulmaya çalışır.
* Doğrudan erişimde X-Forwarded-For başlığına güvenmez.
*/
function snapcad_client_ip () : string
{
$remote = ( string )( $_SERVER [ 'REMOTE_ADDR' ] ?? '' );
$isLocalProxy = in_array ( $remote , [ '127.0.0.1' , '::1' ], true );
$candidates = [];
if ( $isLocalProxy ) {
$candidates [] = ( string )( $_SERVER [ 'HTTP_CF_CONNECTING_IP' ] ?? '' );
$candidates [] = ( string )( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ] ?? '' );
}
$candidates [] = $remote ;
foreach ( $candidates as $candidate ) {
$first = trim ( explode ( ',' , $candidate )[ 0 ]);
if ( filter_var ( $first , FILTER_VALIDATE_IP )) {
return $first ;
}
}
return 'unknown' ;
}
/**
* POST/PUT/PATCH/DELETE isteklerinde Origin/Referer kontrolü.
* SameSite=Lax çerezle birlikte CSRF riskini azaltı r.
*/
function snapcad_validate_origin () : void
{
$method = strtoupper (( string )( $_SERVER [ 'REQUEST_METHOD' ] ?? 'GET' ));
if ( ! in_array ( $method , [ 'POST' , 'PUT' , 'PATCH' , 'DELETE' ], true )) {
return ;
}
if ( PHP_SAPI === 'cli' ) {
return ;
}
$origin = trim (( string )( $_SERVER [ 'HTTP_ORIGIN' ] ?? '' ));
if ( $origin === '' ) {
$referer = trim (( string )( $_SERVER [ 'HTTP_REFERER' ] ?? '' ));
if ( $referer !== '' ) {
$parts = parse_url ( $referer );
if ( is_array ( $parts ) && ! empty ( $parts [ 'scheme' ]) && ! empty ( $parts [ 'host' ])) {
$origin = $parts [ 'scheme' ] . '://' . $parts [ 'host' ]
. ( ! empty ( $parts [ 'port' ]) ? ':' . $parts [ 'port' ] : '' );
}
}
}
// Tarayı cı dışı istemciler (curl, sunucu-sunucu) Origin/Referer göndermeyebilir.
if ( $origin === '' ) {
return ;
}
$allowed = [];
foreach ( explode ( ',' , ( string ) snapcad_env ( 'SNAPCAD_ALLOWED_ORIGINS' , '' )) as $item ) {
$item = rtrim ( trim ( $item ), '/' );
if ( $item !== '' ) {
$allowed [] = $item ;
}
}
$host = ( string )( $_SERVER [ 'HTTP_HOST' ] ?? '' );
if ( $host !== '' ) {
$allowed [] = ( snapcad_is_https () ? 'https' : 'http' ) . '://' . $host ;
}
foreach ( $allowed as $item ) {
if ( hash_equals ( rtrim ( $item , '/' ), rtrim ( $origin , '/' ))) {
return ;
}
}
snapcad_json_response ([ 'ok' => false , 'error' => 'Geçersiz istek kaynağı.' ], 403 );
}
/**
* Basit veritabanı tabanlı rate limit. IP + bucket başına sayaç tutar.
*/
function snapcad_enforce_rate_limit ( PDO $pdo , string $bucket , int $limit , int $windowSeconds ) : void
{
try {
$key = hash ( 'sha256' , $bucket . '|' . snapcad_client_ip ());
$cutoff = date ( 'Y-m-d H:i:s' , time () - max ( 1 , $windowSeconds ));
$stmt = $pdo -> prepare ( "
INSERT INTO snapcad_rate_limits (bucket_key, hits, window_start)
VALUES (:key, 1, NOW())
ON DUPLICATE KEY UPDATE
hits = IF(window_start < :cutoff_a, 1, hits + 1),
window_start = IF(window_start < :cutoff_b, NOW(), window_start)
" );
$stmt -> execute ([
':key' => $key ,
':cutoff_a' => $cutoff ,
':cutoff_b' => $cutoff ,
]);
$stmt = $pdo -> prepare ( "SELECT hits FROM snapcad_rate_limits WHERE bucket_key = :key LIMIT 1" );
$stmt -> execute ([ ':key' => $key ]);
$hits = ( int )( $stmt -> fetchColumn () ?: 0 );
// Eski sayaçları ara sı ra temizle (tablo sı nı rsı z büyümesin).
if ( random_int ( 1 , 100 ) === 1 ) {
$pdo -> prepare ( "DELETE FROM snapcad_rate_limits WHERE window_start < :cutoff" )
-> execute ([ ':cutoff' => date ( 'Y-m-d H:i:s' , time () - 86400 )]);
}
if ( $hits > $limit ) {
header ( 'Retry-After: ' . max ( 1 , $windowSeconds ));
snapcad_json_response ([
'ok' => false ,
'error' => 'Çok fazla istek. Lütfen biraz sonra tekrar deneyin.' ,
], 429 );
}
} catch ( Throwable $e ) {
// Rate limit altyapı sı çalışmı yorsa isteği engelleme; sadece logla.
error_log ( '[SnapCAD RateLimit] ' . $e -> getMessage ());
}
}
function snapcad_is_valid_share_code ( string $code ) : bool
{
return ( bool ) preg_match ( '/^[a-f0-9]{16}$/' , $code );
}
function snapcad_generate_share_code ( PDO $pdo ) : string
{
for ( $i = 0 ; $i < 8 ; $i ++ ) {
$code = bin2hex ( random_bytes ( 8 ));
$stmt = $pdo -> prepare ( "SELECT 1 FROM snapcad_cloud_projects WHERE share_code = :code LIMIT 1" );
$stmt -> execute ([ ':code' => $code ]);
if ( ! $stmt -> fetchColumn ()) {
return $code ;
}
}
return bin2hex ( random_bytes ( 12 ));
}
function snapcad_generate_pin () : string
{
return ( string ) random_int ( 100000 , 999999 );
}
// Sunucu taraflı sabitler. Gizli değerler .env'den gelir.
define ( 'YAKNET_DB_HOST' , ( string ) snapcad_env ( 'YAKNET_DB_HOST' , '127.0.0.1' ));
define ( 'YAKNET_DB_PORT' , ( string ) snapcad_env ( 'YAKNET_DB_PORT' , '3306' ));
define ( 'YAKNET_DB_NAME' , ( string ) snapcad_env ( 'YAKNET_DB_NAME' , 'yaknet_auth' ));
define ( 'YAKNET_DB_USER' , ( string ) snapcad_env ( 'YAKNET_DB_USER' , 'root' ));
define ( 'YAKNET_DB_PASS' , ( string ) snapcad_env ( 'YAKNET_DB_PASS' , '' ));
define ( 'YAKNET_AUTH_BASE_URL' , ( string ) snapcad_env ( 'YAKNET_AUTH_BASE_URL' , 'https://developer-console.yakhub.com.tr' ));
define ( 'YAKNET_CDN_ACCOUNT_JS' , ( string ) snapcad_env ( 'YAKNET_CDN_ACCOUNT_JS' , '' ));
define ( 'SNAPCAD_CANONICAL_URL' , rtrim (( string ) snapcad_env ( 'SNAPCAD_CANONICAL_URL' , 'https://snap.yakhub.com.tr' ), '/' ));
define ( 'SNAPCAD_CALLBACK_URL' , ( string ) snapcad_env ( 'SNAPCAD_CALLBACK_URL' , SNAPCAD_CANONICAL_URL . '/callback.php' ));
define ( 'YAKNET_CLIENT_ID' , ( string ) snapcad_env ( 'YAKNET_CLIENT_ID' , '' ));
define ( 'YAKNET_CLIENT_SECRET' , ( string ) snapcad_env ( 'YAKNET_CLIENT_SECRET' , '' ));
define ( 'YAKNET_OAUTH_VERIFY' , snapcad_bool_env ( 'YAKNET_OAUTH_VERIFY' , true ));
if ( session_status () === PHP_SESSION_NONE && ! headers_sent ()) {
ini_set ( 'session.use_strict_mode' , '1' );
ini_set ( 'session.use_only_cookies' , '1' );
ini_set ( 'session.cookie_httponly' , '1' );
ini_set ( 'session.cookie_samesite' , 'Lax' );
session_name ( 'snapcad_yaknet_sid' );
session_set_cookie_params ([
'lifetime' => 60 * 60 * 24 * 30 , // 30 gün
'path' => '/' ,
'domain' => '' ,
'secure' => snapcad_is_https (),
'httponly' => true ,
'samesite' => 'Lax' ,
]);
session_start ();
}
/**
* Resmi yaknet/y-auth YakNetProvider nesnesini döndürür.
*/
function snapcad_get_oauth_provider () : YakNetProvider
{
$provider = new YakNetProvider ([
'clientId' => YAKNET_CLIENT_ID ,
'clientSecret' => YAKNET_CLIENT_SECRET ,
'redirectUri' => SNAPCAD_CALLBACK_URL ,
'baseUrl' => YAKNET_AUTH_BASE_URL ,
]);
// TLS doğrulaması varsayı lan olarak açıktı r. Yerel sertifika sorunu varsa
// .env içinde YAKNET_OAUTH_VERIFY=false yapı labilir.
if ( class_exists ( GuzzleClient :: class )) {
$provider -> setHttpClient ( new GuzzleClient ([
'verify' => YAKNET_OAUTH_VERIFY ,
'timeout' => 15 ,
]));
}
return $provider ;
}
/**
* Yerel SnapCAD PHP oturumunu ve çerezini tamamen temizler.
*/
function snapcad_logout () : void
{
$_SESSION = [];
if ( ini_get ( 'session.use_cookies' ) && ! headers_sent ()) {
$params = session_get_cookie_params ();
setcookie (
session_name (),
'' ,
time () - 42000 ,
$params [ 'path' ] ?: '/' ,
$params [ 'domain' ] ?: '' ,
( bool ) $params [ 'secure' ],
( bool ) $params [ 'httponly' ]
);
}
if ( session_status () === PHP_SESSION_ACTIVE ) {
session_destroy ();
}
}
/**
* Merkez MySQL (yaknet_auth) PDO bağlantı sı nı döndürür ve
* SnapCAD tabloları nı /eksik sütunları nı otomatik hazı rlar.
*/
function snapcad_get_pdo () : ? PDO
{
static $pdo = null ;
if ( $pdo !== null ) {
return $pdo ;
}
try {
$dsn = sprintf (
'mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4' ,
YAKNET_DB_HOST ,
YAKNET_DB_PORT ,
YAKNET_DB_NAME
);
$pdo = new PDO ( $dsn , YAKNET_DB_USER , YAKNET_DB_PASS , [
PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION ,
PDO :: ATTR_DEFAULT_FETCH_MODE => PDO :: FETCH_ASSOC ,
PDO :: ATTR_EMULATE_PREPARES => false ,
PDO :: ATTR_TIMEOUT => 5 ,
]);
// Şema oluşturma/güncelleme artı k istek yolunda değil.
// Kurulum için bir kez: php database/migrate.php
if ( snapcad_bool_env ( 'SNAPCAD_AUTO_MIGRATE' , false )) {
require_once __DIR__ . '/database/schema.php' ;
snapcad_apply_schema ( $pdo );
}
return $pdo ;
} catch ( Throwable $e ) {
error_log ( '[SnapCAD DB Error] ' . $e -> getMessage ());
return null ;
}
}
/**
* Sunucu tarafı nda sabitlenmiş OAuth 2.0 bilgilerini döndürür.
* client_secret bilerek dışarı verilmez.
*/
function snapcad_get_oauth_credentials () : array
{
return [
'client_id' => YAKNET_CLIENT_ID ,
'redirect_uri' => SNAPCAD_CALLBACK_URL ,
'auth_base_url' => YAKNET_AUTH_BASE_URL ,
'configured' => YAKNET_CLIENT_ID !== '' && YAKNET_CLIENT_SECRET !== '' ,
];
}
2026-11-12 10:12:35 +03:00
function snapcad_desktop_token_ttl_days () : int
{
$raw = ( int ) snapcad_env ( 'SNAPCAD_DESKTOP_TOKEN_TTL_DAYS' , '180' );
return max ( 7 , min ( 3650 , $raw > 0 ? $raw : 180 ));
}
function snapcad_ensure_desktop_tokens_table ( PDO $pdo ) : void
{
static $ensured = false ;
if ( $ensured ) {
return ;
}
$pdo -> exec ( "
CREATE TABLE IF NOT EXISTS snapcad_desktop_tokens (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT UNSIGNED NOT NULL,
user_name VARCHAR(255) NOT NULL,
user_email VARCHAR(255) DEFAULT NULL,
user_avatar VARCHAR(512) DEFAULT NULL,
token_hash CHAR(64) DEFAULT NULL,
exchange_code_hash CHAR(64) DEFAULT NULL,
nonce_hash CHAR(64) DEFAULT NULL,
device_label VARCHAR(120) DEFAULT 'SnapCAD Masaüstü',
exchange_expires_at DATETIME DEFAULT NULL,
expires_at DATETIME NOT NULL,
last_used_at DATETIME DEFAULT NULL,
revoked_at DATETIME DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uq_token_hash (token_hash),
UNIQUE KEY uq_exchange_code_hash (exchange_code_hash),
INDEX idx_user_revoked (user_id, revoked_at),
INDEX idx_expires_at (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
" );
$ensured = true ;
}
function snapcad_get_request_header ( string $name ) : ? string
{
$serverKey = 'HTTP_' . strtoupper ( str_replace ( '-' , '_' , $name ));
$redirectKey = 'REDIRECT_' . $serverKey ;
foreach ([ $serverKey , $redirectKey ] as $key ) {
if ( ! empty ( $_SERVER [ $key ]) && is_string ( $_SERVER [ $key ])) {
return trim ( $_SERVER [ $key ]);
}
}
if ( function_exists ( 'getallheaders' )) {
$target = strtolower ( $name );
foreach ( getallheaders () as $headerName => $value ) {
if ( strtolower (( string ) $headerName ) === $target && is_string ( $value )) {
return trim ( $value );
}
}
}
return null ;
}
function snapcad_extract_desktop_token () : ? string
{
$authHeader = snapcad_get_request_header ( 'Authorization' );
if ( $authHeader !== null && preg_match ( '/^Bearer\s+([a-f0-9]{64})$/i' , $authHeader , $matches )) {
return strtolower ( $matches [ 1 ]);
}
$desktopHeader = snapcad_get_request_header ( 'X-SnapCAD-Desktop-Token' );
if ( $desktopHeader !== null && preg_match ( '/^([a-f0-9]{64})$/i' , $desktopHeader , $matches )) {
return strtolower ( $matches [ 1 ]);
}
return null ;
}
/**
* Masaüstü tek kullanı mlı k değişim kodu (180 sn) üretir; ası l uzun ömürlü token
* TLS arka kanalı ndan `desktop_exchange` ile alı nana kadar oluşturulmaz.
*
* @param array{id: int, name: string, email: string, avatar?: ?string} $user
*/
function snapcad_create_desktop_exchange ( PDO $pdo , array $user , string $nonce , string $deviceLabel = 'SnapCAD Masaüstü' ) : string
{
snapcad_ensure_desktop_tokens_table ( $pdo );
$exchangeCode = bin2hex ( random_bytes ( 24 ));
$exchangeHash = hash ( 'sha256' , $exchangeCode );
$nonceHash = hash ( 'sha256' , strtolower ( $nonce ));
$ttlDays = snapcad_desktop_token_ttl_days ();
$cleanDevice = mb_substr ( trim ( $deviceLabel ) ?: 'SnapCAD Masaüstü' , 0 , 120 );
// Süresi dolmuş eski masaüstü oturum kayı tları nı ara sı ra temizle.
if ( random_int ( 1 , 20 ) === 1 ) {
try {
$pdo -> exec ( "DELETE FROM snapcad_desktop_tokens WHERE expires_at < NOW() OR (exchange_expires_at IS NOT NULL AND exchange_expires_at < DATE_SUB(NOW(), INTERVAL 1 DAY))" );
} catch ( Throwable $e ) {
error_log ( '[SnapCAD DesktopCleanup] ' . $e -> getMessage ());
}
}
$stmt = $pdo -> prepare ( "
INSERT INTO snapcad_desktop_tokens
(user_id, user_name, user_email, user_avatar, token_hash, exchange_code_hash, nonce_hash, device_label, exchange_expires_at, expires_at)
VALUES
(:uid, :uname, :uemail, :uavatar, NULL, :ehash, :nhash, :device, DATE_ADD(NOW(), INTERVAL 180 SECOND), DATE_ADD(NOW(), INTERVAL :ttl DAY))
" );
$stmt -> execute ([
':uid' => ( int ) $user [ 'id' ],
':uname' => mb_substr (( string ) $user [ 'name' ], 0 , 255 ),
':uemail' => mb_substr (( string )( $user [ 'email' ] ?? '' ), 0 , 255 ),
':uavatar' => isset ( $user [ 'avatar' ]) && is_string ( $user [ 'avatar' ]) ? mb_substr ( $user [ 'avatar' ], 0 , 512 ) : null ,
':ehash' => $exchangeHash ,
':nhash' => $nonceHash ,
':device' => $cleanDevice ,
':ttl' => $ttlDays ,
]);
return $exchangeCode ;
}
/**
* Tek kullanı mlı k değişim kodunu atomik biçimde uzun ömürlü Bearer token ile takas eder.
*
* @return ?array{token: string, expires_at: string, ttl_days: int, user: array<string, mixed>}
*/
function snapcad_exchange_desktop_code ( PDO $pdo , string $exchangeCode , string $nonce ) : ? array
{
if ( ! preg_match ( '/^[a-f0-9]{48,128}$/i' , $exchangeCode ) || ! preg_match ( '/^[a-f0-9]{32,128}$/i' , $nonce )) {
return null ;
}
snapcad_ensure_desktop_tokens_table ( $pdo );
$exchangeHash = hash ( 'sha256' , strtolower ( $exchangeCode ));
$nonceHash = hash ( 'sha256' , strtolower ( $nonce ));
$ttlDays = snapcad_desktop_token_ttl_days ();
try {
$pdo -> beginTransaction ();
$sel = $pdo -> prepare ( "
SELECT id, user_id, user_name, user_email, user_avatar
FROM snapcad_desktop_tokens
WHERE exchange_code_hash = :ehash
AND nonce_hash = :nhash
AND revoked_at IS NULL
AND exchange_expires_at IS NOT NULL
AND exchange_expires_at > NOW()
LIMIT 1
FOR UPDATE
" );
$sel -> execute ([ ':ehash' => $exchangeHash , ':nhash' => $nonceHash ]);
$row = $sel -> fetch ();
if ( ! $row ) {
$pdo -> rollBack ();
return null ;
}
$rawToken = bin2hex ( random_bytes ( 32 ));
$tokenHash = hash ( 'sha256' , $rawToken );
$upd = $pdo -> prepare ( "
UPDATE snapcad_desktop_tokens
SET token_hash = :thash,
exchange_code_hash = NULL,
nonce_hash = NULL,
exchange_expires_at = NULL,
expires_at = DATE_ADD(NOW(), INTERVAL :ttl DAY),
last_used_at = NOW()
WHERE id = :id AND exchange_code_hash = :ehash
" );
$upd -> execute ([
':thash' => $tokenHash ,
':ttl' => $ttlDays ,
':id' => ( int ) $row [ 'id' ],
':ehash' => $exchangeHash ,
]);
if ( $upd -> rowCount () !== 1 ) {
$pdo -> rollBack ();
return null ;
}
$expStmt = $pdo -> prepare ( "SELECT UNIX_TIMESTAMP(expires_at) AS exp_ts FROM snapcad_desktop_tokens WHERE id = :id LIMIT 1" );
$expStmt -> execute ([ ':id' => ( int ) $row [ 'id' ]]);
$expTs = ( int )( $expStmt -> fetchColumn () ?: ( time () + ( $ttlDays * 86400 )));
$pdo -> commit ();
return [
'token' => $rawToken ,
'expires_at' => date ( 'c' , $expTs ),
'ttl_days' => $ttlDays ,
'user' => [
'id' => ( int ) $row [ 'user_id' ],
'name' => ( string ) $row [ 'user_name' ],
'email' => ( string )( $row [ 'user_email' ] ?? '' ),
'avatar' => $row [ 'user_avatar' ] ?: null ,
'auth_source' => 'yaknet_desktop_token' ,
],
];
} catch ( Throwable $e ) {
if ( $pdo -> inTransaction ()) {
$pdo -> rollBack ();
}
error_log ( '[SnapCAD DesktopExchange] ' . $e -> getMessage ());
return null ;
}
}
/**
* Uzun ömürlü masaüstü token'ı nı doğrular ve aktif kullanı mda kalan ömrünü kayar pencerede (sliding) uzatı r.
*
* @return ?array<string, mixed>
*/
function snapcad_resolve_desktop_token_user ( PDO $pdo , ? string $rawToken = null ) : ? array
{
$token = $rawToken ?? snapcad_extract_desktop_token ();
if ( $token === null ) {
return null ;
}
try {
snapcad_ensure_desktop_tokens_table ( $pdo );
$tokenHash = hash ( 'sha256' , strtolower ( $token ));
$stmt = $pdo -> prepare ( "
SELECT id, user_id, user_name, user_email, user_avatar,
UNIX_TIMESTAMP(expires_at) AS exp_ts,
(expires_at < DATE_ADD(NOW(), INTERVAL :half_ttl DAY)) AS needs_extend
FROM snapcad_desktop_tokens
WHERE token_hash = :thash
AND revoked_at IS NULL
AND expires_at > NOW()
LIMIT 1
" );
$ttlDays = snapcad_desktop_token_ttl_days ();
$halfTtlDays = max ( 1 , ( int ) floor ( $ttlDays / 2 ));
$stmt -> execute ([
':thash' => $tokenHash ,
':half_ttl' => $halfTtlDays ,
]);
$row = $stmt -> fetch ();
if ( ! $row ) {
return null ;
}
if ( ! empty ( $row [ 'needs_extend' ])) {
$upd = $pdo -> prepare ( "
UPDATE snapcad_desktop_tokens
SET last_used_at = NOW(),
expires_at = DATE_ADD(NOW(), INTERVAL :ttl DAY)
WHERE id = :id
" );
$upd -> execute ([ ':ttl' => $ttlDays , ':id' => ( int ) $row [ 'id' ]]);
$expTs = time () + ( $ttlDays * 86400 );
} else {
// Sı k isteklerde her saniye UPDATE yapmamak için last_used_at güncellemesini hafif tut.
if ( random_int ( 1 , 5 ) === 1 ) {
$pdo -> prepare ( "UPDATE snapcad_desktop_tokens SET last_used_at = NOW() WHERE id = :id" )
-> execute ([ ':id' => ( int ) $row [ 'id' ]]);
}
$expTs = ( int )( $row [ 'exp_ts' ] ?: ( time () + ( $ttlDays * 86400 )));
}
return [
'id' => ( int ) $row [ 'user_id' ],
'name' => ( string ) $row [ 'user_name' ],
'email' => ( string )( $row [ 'user_email' ] ?? '' ),
'avatar' => $row [ 'user_avatar' ] ?: null ,
'auth_source' => 'yaknet_desktop_token' ,
'token_expires_at' => date ( 'c' , $expTs ),
];
} catch ( Throwable $e ) {
error_log ( '[SnapCAD DesktopToken] ' . $e -> getMessage ());
return null ;
}
}
function snapcad_revoke_desktop_token ( PDO $pdo , ? string $rawToken = null ) : bool
{
$token = $rawToken ?? snapcad_extract_desktop_token ();
if ( $token === null ) {
return false ;
}
try {
snapcad_ensure_desktop_tokens_table ( $pdo );
$stmt = $pdo -> prepare ( "
UPDATE snapcad_desktop_tokens
SET revoked_at = NOW()
WHERE token_hash = :thash AND revoked_at IS NULL
" );
$stmt -> execute ([ ':thash' => hash ( 'sha256' , strtolower ( $token ))]);
return $stmt -> rowCount () > 0 ;
} catch ( Throwable $e ) {
error_log ( '[SnapCAD DesktopRevoke] ' . $e -> getMessage ());
return false ;
}
}