import { createHash } from "node:crypto"; import { mkdir, readFile, unlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { clearKisApprovalKeyCache } from "@/lib/kis/approval"; import type { KisCredentialInput } from "@/lib/kis/config"; import { getKisConfig } from "@/lib/kis/config"; /** * @file lib/kis/token.ts * @description KIS 액세스 토큰 발급/폐기/캐시를 관리합니다. */ interface KisTokenResponse { access_token?: string; access_token_token_expired?: string; access_token_expired?: string; expires_in?: number; msg1?: string; msg_cd?: string; error?: string; error_description?: string; } interface KisTokenCache { token: string; expiresAt: number; } interface PersistedTokenCache { [cacheKey: string]: KisTokenCache; } interface KisRevokeResponse { code?: number | string; message?: string; msg1?: string; } const tokenCacheMap = new Map(); const tokenIssueInFlightMap = new Map>(); const TOKEN_REFRESH_BUFFER_MS = 60 * 1000; const TOKEN_CACHE_FILE_PATH = join(process.cwd(), ".tmp", "kis-token-cache.json"); function hashKey(value: string) { return createHash("sha256").update(value).digest("hex"); } function getTokenCacheKey(credentials?: KisCredentialInput) { const config = getKisConfig(credentials); return `${config.tradingEnv}:${hashKey(config.appKey)}`; } async function readPersistedTokenCache() { try { const raw = await readFile(TOKEN_CACHE_FILE_PATH, "utf8"); return JSON.parse(raw) as PersistedTokenCache; } catch { return {}; } } async function writePersistedTokenCache(next: PersistedTokenCache) { await mkdir(join(process.cwd(), ".tmp"), { recursive: true }); await writeFile(TOKEN_CACHE_FILE_PATH, JSON.stringify(next), "utf8"); } async function getPersistedToken(cacheKey: string) { const cache = await readPersistedTokenCache(); const token = cache[cacheKey]; if (!token) return null; if (token.expiresAt - TOKEN_REFRESH_BUFFER_MS <= Date.now()) { delete cache[cacheKey]; await writePersistedTokenCache(cache); return null; } return token; } async function setPersistedToken(cacheKey: string, token: KisTokenCache) { const cache = await readPersistedTokenCache(); cache[cacheKey] = token; await writePersistedTokenCache(cache); } async function clearPersistedToken(cacheKey: string) { const cache = await readPersistedTokenCache(); if (!(cacheKey in cache)) return; delete cache[cacheKey]; if (Object.keys(cache).length === 0) { try { await unlink(TOKEN_CACHE_FILE_PATH); } catch { // ignore when file does not exist } return; } await writePersistedTokenCache(cache); } function tryParseTokenResponse(rawText: string): KisTokenResponse { try { return JSON.parse(rawText) as KisTokenResponse; } catch { return { msg1: rawText.slice(0, 200), }; } } function tryParseRevokeResponse(rawText: string): KisRevokeResponse { try { return JSON.parse(rawText) as KisRevokeResponse; } catch { return { message: rawText.slice(0, 200), }; } } function parseTokenExpiryText(value?: string) { if (!value) return null; const normalized = value.includes("T") ? value : value.replace(" ", "T"); const parsed = Date.parse(normalized); if (Number.isNaN(parsed)) return null; return parsed; } function resolveTokenExpiry(payload: KisTokenResponse) { if (typeof payload.expires_in === "number" && payload.expires_in > 0) { return Date.now() + payload.expires_in * 1000; } const absoluteExpiry = parseTokenExpiryText(payload.access_token_token_expired) ?? parseTokenExpiryText(payload.access_token_expired); if (absoluteExpiry) { return absoluteExpiry; } // 예외 상황 기본값: 23시간 return Date.now() + 23 * 60 * 60 * 1000; } /** * @description 토큰 발급 실패 원인 점검 문구를 만듭니다. * @see https://github.com/koreainvestment/open-trading-api */ function buildTokenIssueHint(detail: string, tradingEnv: "real" | "mock") { const lower = detail.toLowerCase(); const keyError = lower.includes("appkey") || lower.includes("appsecret") || lower.includes("secret") || lower.includes("invalid") || lower.includes("auth"); if (keyError) { return ` | 점검: ${tradingEnv === "real" ? "실전" : "모의"} 앱 키/시크릿 쌍을 확인해 주세요.`; } return " | 점검: API 서비스 상태와 거래 환경(real/mock)을 확인해 주세요."; } /** * @description KIS 액세스 토큰을 발급합니다. * @see app/api/kis/validate/route.ts */ async function issueKisToken(credentials?: KisCredentialInput): Promise { const config = getKisConfig(credentials); const tokenUrl = `${config.baseUrl}/oauth2/tokenP`; const response = await fetch(tokenUrl, { method: "POST", headers: { "content-type": "application/json; charset=utf-8", }, body: JSON.stringify({ grant_type: "client_credentials", appkey: config.appKey, appsecret: config.appSecret, }), cache: "no-store", }); const rawText = await response.text(); const payload = tryParseTokenResponse(rawText); if (!response.ok || !payload.access_token) { const detail = [payload.msg1, payload.error_description, payload.error, payload.msg_cd] .filter(Boolean) .join(" / "); const hint = buildTokenIssueHint(detail, config.tradingEnv); throw new Error( detail ? `KIS 토큰 발급 실패 (${config.tradingEnv}, ${response.status}): ${detail}${hint}` : `KIS 토큰 발급 실패 (${config.tradingEnv}, ${response.status})${hint}`, ); } return { token: payload.access_token, expiresAt: resolveTokenExpiry(payload), }; } /** * @description 캐시된 토큰을 반환하거나 새로 발급합니다. * @see lib/kis/domestic.ts */ export async function getKisAccessToken(credentials?: KisCredentialInput) { const cacheKey = getTokenCacheKey(credentials); const cached = tokenCacheMap.get(cacheKey); if (cached && cached.expiresAt - TOKEN_REFRESH_BUFFER_MS > Date.now()) { return cached.token; } const persisted = await getPersistedToken(cacheKey); if (persisted) { tokenCacheMap.set(cacheKey, persisted); return persisted.token; } const inFlight = tokenIssueInFlightMap.get(cacheKey); if (inFlight) { const shared = await inFlight; return shared.token; } const nextPromise = issueKisToken(credentials); tokenIssueInFlightMap.set(cacheKey, nextPromise); const next = await nextPromise.finally(() => { tokenIssueInFlightMap.delete(cacheKey); }); tokenCacheMap.set(cacheKey, next); await setPersistedToken(cacheKey, next); return next.token; } /** * @description 현재 KIS 액세스 토큰을 폐기합니다. * @see app/api/kis/revoke/route.ts */ export async function revokeKisAccessToken(credentials?: KisCredentialInput) { const config = getKisConfig(credentials); const cacheKey = getTokenCacheKey(credentials); const token = await getKisAccessToken(credentials); const response = await fetch(`${config.baseUrl}/oauth2/revokeP`, { method: "POST", headers: { "content-type": "application/json; charset=utf-8", }, body: JSON.stringify({ appkey: config.appKey, appsecret: config.appSecret, token, }), cache: "no-store", }); const rawText = await response.text(); const payload = tryParseRevokeResponse(rawText); const code = payload.code != null ? String(payload.code) : ""; const isSuccessCode = code === "" || code === "200"; if (!response.ok || !isSuccessCode) { const detail = [payload.message, payload.msg1].filter(Boolean).join(" / "); throw new Error( detail ? `KIS 토큰 폐기 실패 (${config.tradingEnv}, ${response.status}): ${detail}` : `KIS 토큰 폐기 실패 (${config.tradingEnv}, ${response.status})`, ); } tokenCacheMap.delete(cacheKey); tokenIssueInFlightMap.delete(cacheKey); await clearPersistedToken(cacheKey); clearKisApprovalKeyCache(credentials); return payload.message ?? "액세스 토큰 폐기가 완료되었습니다."; }