Download server/auth.js from SSSAssist/Thoth: direct link, hf CLI and curl.
- Browser
- Download file 5.29 kB
-
https://huggingface.co/spaces/SSSAssist/Thoth/resolve/main/server/auth.js
- Command line
-
hf download hf://spaces/SSSAssist/Thoth/server/auth.js
-
curl -L -o auth.js https://huggingface.co/spaces/SSSAssist/Thoth/resolve/main/server/auth.js
5.29 kB
| 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 }); | |
| }); | |