// 세션 토큰(HMAC), 비밀번호(PBKDF2), Google ID 토큰 검증. WebCrypto 만 사용. import { PBKDF2_ITER, TOKEN_TTL_MS } from "./rules.js"; const enc = new TextEncoder(); export function b64url(bytes) { let s = ""; for (const b of new Uint8Array(bytes)) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } export function unb64url(s) { s = s.replace(/-/g, "+").replace(/_/g, "/"); while (s.length % 4) s += "="; const bin = atob(s); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; } async function hmacKey(secret) { return crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]); } /** 토큰 = base64url(JSON{uid, exp}) + "." + base64url(HMAC). */ export async function signToken(secret, uid, now = Date.now()) { const body = b64url(enc.encode(JSON.stringify({ uid, exp: now + TOKEN_TTL_MS }))); const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret), enc.encode(body)); return `${body}.${b64url(sig)}`; } export async function verifyToken(secret, token, now = Date.now()) { if (typeof token !== "string") return null; const [body, sig] = token.split("."); if (!body || !sig) return null; let ok = false; try { ok = await crypto.subtle.verify("HMAC", await hmacKey(secret), unb64url(sig), enc.encode(body)); } catch { return null; } if (!ok) return null; try { const p = JSON.parse(new TextDecoder().decode(unb64url(body))); if (typeof p.uid !== "string" || typeof p.exp !== "number" || p.exp < now) return null; return p; } catch { return null; } } export async function hashPassword(password, saltB64 = null) { const salt = saltB64 ? unb64url(saltB64) : crypto.getRandomValues(new Uint8Array(16)); const key = await crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, ["deriveBits"]); const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt, iterations: PBKDF2_ITER }, key, 256); return { hash: b64url(bits), salt: b64url(salt) }; } export function timingSafeEqual(a, b) { if (a.length !== b.length) return false; let d = 0; for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i); return d === 0; } // ── Google ID 토큰 (RS256) ── let jwksCache = { at: 0, keys: [] }; async function googleKeys(fetchFn = fetch) { if (Date.now() - jwksCache.at < 3600_000 && jwksCache.keys.length) return jwksCache.keys; const res = await fetchFn("https://www.googleapis.com/oauth2/v3/certs"); const { keys } = await res.json(); jwksCache = { at: Date.now(), keys }; return keys; } /** 검증되면 payload({sub, email, …}), 아니면 null. audiences = 허용할 OAuth 클라이언트 ID 목록. */ export async function verifyGoogleIdToken(idToken, audiences, fetchFn = fetch) { if (!idToken || !audiences.length) return null; const parts = idToken.split("."); if (parts.length !== 3) return null; let header, payload; try { header = JSON.parse(new TextDecoder().decode(unb64url(parts[0]))); payload = JSON.parse(new TextDecoder().decode(unb64url(parts[1]))); } catch { return null; } if (header.alg !== "RS256") return null; const jwk = (await googleKeys(fetchFn)).find((k) => k.kid === header.kid); if (!jwk) return null; const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]); const ok = await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, unb64url(parts[2]), enc.encode(`${parts[0]}.${parts[1]}`)); if (!ok) return null; const now = Date.now() / 1000; if (!["accounts.google.com", "https://accounts.google.com"].includes(payload.iss)) return null; if (!audiences.includes(payload.aud)) return null; if (typeof payload.exp !== "number" || payload.exp < now) return null; if (!payload.sub) return null; return payload; }