Files
music_quiz/apps/server/src/auth/sessions.ts
EJClaw 391bbe69e5 1단계 뼈대: joke-app에서 로그인(디스코드·게스트)·세션·권한·관리자·DB를 가져와 음악퀴즈용으로 정리, 새 디자인·아이콘, WS 연결·시계 맞추기, 테스트·e2e
- apps/server: Hono API(auth/me/config/admin), Bun WebSocket(welcome·ping/pong, 압축 끔), SQLite 마이그레이션
- 사이트 설정: 채팅 도배 방지 기본 꺼짐(관리자가 켬, 초당·순간 횟수)
- apps/web: 첫 화면·로그인·관리자(대시보드·사이트·사용자·관리자·기록), 라이트/다크, 휴대폰, noindex
- packages/shared: 닉네임 규칙, 프로토콜(zod), 시계 차이 계산
- 테스트 20개 + 브라우저 e2e 6단계 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 19:44:47 +09:00

91 lines
3.8 KiB
TypeScript

import type { Database } from 'bun:sqlite';
const DAY = 24 * 3600_000;
export const SESSION_TTL = { guest: 365 * DAY, member: 90 * DAY } as const;
export const SESSION_COOKIE = 'sid';
/** users.last_seen_at is written at most this often per user. */
const SEEN_EVERY = 60_000;
export function randomToken(bytes = 32): string {
const buf = new Uint8Array(bytes);
crypto.getRandomValues(buf);
return Buffer.from(buf).toString('base64url');
}
export function sha256Hex(input: string): string {
return new Bun.CryptoHasher('sha256').update(input).digest('hex');
}
export class Sessions {
constructor(private db: Database) {}
create(userId: string, kind: 'guest' | 'member', userAgent: string | null, now = Date.now()): { token: string; expiresAt: number } {
const token = randomToken();
const expiresAt = now + SESSION_TTL[kind];
this.db
.query('INSERT INTO sessions (token_hash, user_id, created_at, expires_at, last_used_at, user_agent) VALUES (?, ?, ?, ?, ?, ?)')
.run(sha256Hex(token), userId, now, expiresAt, now, userAgent?.slice(0, 200) ?? null);
return { token, expiresAt };
}
/** Resolves a token to a user id; slides expiry at most once per day. */
resolve(token: string, now = Date.now()): string | null {
const hash = sha256Hex(token);
const row = this.db
.query<{ user_id: string; expires_at: number; last_used_at: number; kind: 'guest' | 'member'; last_seen_at: number }, [string]>(
`SELECT s.user_id, s.expires_at, s.last_used_at, u.kind, u.last_seen_at FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = ? AND u.deleted_at IS NULL AND u.banned_at IS NULL`,
)
.get(hash);
if (!row) return null;
if (row.expires_at <= now) {
this.db.query('DELETE FROM sessions WHERE token_hash = ?').run(hash);
return null;
}
if (now - row.last_used_at > DAY) {
this.db
.query('UPDATE sessions SET last_used_at = ?, expires_at = ? WHERE token_hash = ?')
.run(now, now + SESSION_TTL[row.kind], hash);
}
// Idle guests are deleted after a day (docs/02), so remember when the user was last here.
if (now - row.last_seen_at > SEEN_EVERY) this.db.query('UPDATE users SET last_seen_at = ? WHERE id = ?').run(now, row.user_id);
return row.user_id;
}
revoke(token: string): void {
this.db.query('DELETE FROM sessions WHERE token_hash = ?').run(sha256Hex(token));
}
revokeAll(userId: string): void {
this.db.query('DELETE FROM sessions WHERE user_id = ?').run(userId);
}
purgeExpired(now = Date.now()): number {
return this.db.query('DELETE FROM sessions WHERE expires_at <= ?').run(now).changes;
}
}
/** Minimal HMAC-signed value for short-lived cookies (OAuth state + PKCE verifier). */
export async function signValue(secret: string, value: string): Promise<string> {
const mac = await hmac(secret, value);
return `${Buffer.from(value).toString('base64url')}.${mac}`;
}
export async function unsignValue(secret: string, signed: string): Promise<string | null> {
const dot = signed.lastIndexOf('.');
if (dot < 0) return null;
const value = Buffer.from(signed.slice(0, dot), 'base64url').toString();
const expected = await hmac(secret, value);
const given = signed.slice(dot + 1);
if (expected.length !== given.length) return null;
let diff = 0;
for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i);
return diff === 0 ? value : null;
}
async function hmac(secret: string, value: string): Promise<string> {
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value));
return Buffer.from(sig).toString('base64url');
}