release: SnapCAD Studio 1.0.10 (desktop menuler, macOS kisayollari, YakNet SSO)
Build and Push Docker Images / build (push) Canceled after 0s
Desktop Release / Build linux desktop (push) Canceled after 0s
Desktop Release / Build windows desktop (push) Canceled after 0s
Desktop Release / Attach packages to release (push) Canceled after 0s
Desktop Release / Build macos desktop (push) Canceled after 0s
CI / Typecheck and unit tests (push) Canceled after 0s

This commit is contained in:
Enes Yakıştır
2026-11-12 10:12:35 +03:00
parent d5cc023856
commit ee28672e23
81 changed files with 10729 additions and 821 deletions
+302
View File
@@ -369,3 +369,305 @@ function snapcad_get_oauth_credentials(): array
'configured' => YAKNET_CLIENT_ID !== '' && YAKNET_CLIENT_SECRET !== '',
];
}
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;
}
}