File size: 5,286 Bytes
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd4b277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd4b277
f41aded
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';
import { Router } from 'express';
import { ALLOW_REGISTRATION, ALLOWED_EMAILS, COOKIE_SECURE } from './config.js';
import { db } from './db.js';
import { HttpError, requireString } from './util.js';

const scryptAsync = promisify(scrypt);
const COOKIE = 'thoth_oturum';
const SESSION_DAYS = 30;

async function hashPassword(password) {
  const salt = randomBytes(16);
  const hash = await scryptAsync(password, salt, 64);
  return `${salt.toString('hex')}:${hash.toString('hex')}`;
}

async function verifyPassword(password, stored) {
  const [saltHex, hashHex] = stored.split(':');
  const expected = Buffer.from(hashHex, 'hex');
  const actual = await scryptAsync(password, Buffer.from(saltHex, 'hex'), expected.length);
  return timingSafeEqual(actual, expected);
}

const sha256 = (s) => createHash('sha256').update(s).digest('hex');

function startSession(res, userId) {
  const token = randomBytes(32).toString('hex');
  db.prepare(`INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (?, ?, datetime('now', ?))`)
    .run(sha256(token), userId, `+${SESSION_DAYS} days`);
  res.cookie(COOKIE, token, cookieOptions);
}

// HTTPS'te çerez, sayfa başka bir sitenin çerçevesinde (ör. huggingface.co'daki Space görünümü) açıldığında
// da gönderilir: SameSite=None + Partitioned. Başka sitelerden gelen istekler requireSameOrigin ile engellenir.
const cookieOptions = COOKIE_SECURE
  ? { httpOnly: true, secure: true, sameSite: 'none', partitioned: true, maxAge: SESSION_DAYS * 86_400_000 }
  : { httpOnly: true, sameSite: 'lax', maxAge: SESSION_DAYS * 86_400_000 };

/** Durum değiştiren istekler yalnızca Thoth arayüzünden gelebilir (CSRF koruması). */
export function requireSameOrigin(req, _res, next) {
  if (req.method !== 'GET' && req.method !== 'HEAD' && req.get('X-Thoth') !== '1') {
    throw new HttpError(403, 'İstek reddedildi: Thoth arayüzü dışından gönderildi.');
  }
  next();
}

function currentUser(req) {
  const token = req.cookies?.[COOKIE];
  if (!token) return null;
  return db.prepare(`
    SELECT u.id, u.email, u.name FROM sessions s JOIN users u ON u.id = s.user_id
    WHERE s.token_hash = ? AND s.expires_at > datetime('now')
  `).get(sha256(token)) ?? null;
}

export function requireUser(req, _res, next) {
  req.user = currentUser(req);
  if (!req.user) throw new HttpError(401, 'Oturum açmanız gerekiyor.');
  next();
}

// Parola deneme sınırı: aynı IP + e-posta için 15 dakikada en fazla 10 başarısız giriş.
const failures = new Map();
function checkRateLimit(key) {
  const now = Date.now();
  const entry = failures.get(key);
  if (entry && now - entry.first > 15 * 60_000) failures.delete(key);
  if ((failures.get(key)?.count ?? 0) >= 10) {
    throw new HttpError(429, 'Çok fazla başarısız deneme. Lütfen 15 dakika sonra tekrar deneyin.');
  }
}
function recordFailure(key) {
  const entry = failures.get(key) ?? { count: 0, first: Date.now() };
  entry.count += 1;
  failures.set(key, entry);
}

export const authRouter = Router();

authRouter.get('/me', (req, res) => {
  res.json({ user: currentUser(req), allowRegistration: ALLOW_REGISTRATION });
});

authRouter.post('/register', async (req, res) => {
  if (!ALLOW_REGISTRATION) throw new HttpError(403, 'Yeni kayıt şu anda kapalı.');
  const name = requireString(req.body.name, 'Ad soyad', { max: 80 });
  const email = requireString(req.body.email, 'E-posta', { max: 120 }).toLowerCase();
  const password = requireString(req.body.password, 'Parola', { min: 8, max: 200 });
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) throw new HttpError(400, 'Geçerli bir e-posta adresi girin.');
  if (ALLOWED_EMAILS.length && !ALLOWED_EMAILS.includes(email)) {
    throw new HttpError(403, 'Bu e-posta adresiyle kayıt izni yok. Platform yöneticisinden davet isteyin.');
  }
  if (db.prepare('SELECT 1 FROM users WHERE email = ?').get(email)) {
    throw new HttpError(409, 'Bu e-posta adresiyle zaten bir hesap var.');
  }
  const { lastInsertRowid } = db
    .prepare('INSERT INTO users (email, name, password_hash) VALUES (?, ?, ?)')
    .run(email, name, await hashPassword(password));
  startSession(res, Number(lastInsertRowid));
  res.json({ user: { id: Number(lastInsertRowid), email, name } });
});

authRouter.post('/login', async (req, res) => {
  const email = requireString(req.body.email, 'E-posta', { max: 120 }).toLowerCase();
  const password = requireString(req.body.password, 'Parola', { max: 200 });
  const key = `${req.ip}|${email}`;
  checkRateLimit(key);
  const row = db.prepare('SELECT id, email, name, password_hash FROM users WHERE email = ?').get(email);
  if (!row || !(await verifyPassword(password, row.password_hash))) {
    recordFailure(key);
    throw new HttpError(401, 'E-posta veya parola hatalı.');
  }
  failures.delete(key);
  startSession(res, row.id);
  res.json({ user: { id: row.id, email: row.email, name: row.name } });
});

authRouter.post('/logout', (req, res) => {
  const token = req.cookies?.[COOKIE];
  if (token) db.prepare('DELETE FROM sessions WHERE token_hash = ?').run(sha256(token));
  res.clearCookie(COOKIE, cookieOptions);
  res.json({ ok: true });
});