Files
auto-trade/lib/kis/token.ts

229 lines
6.3 KiB
TypeScript
Raw Normal View History

2026-02-10 11:16:39 +09:00
import { createHash } from "node:crypto";
2026-02-06 17:50:35 +09:00
import { clearKisApprovalKeyCache } from "@/lib/kis/approval";
2026-02-11 15:27:03 +09:00
import type { KisCredentialInput } from "@/lib/kis/config";
2026-02-06 17:50:35 +09:00
import { getKisConfig } from "@/lib/kis/config";
/**
* @file lib/kis/token.ts
2026-02-11 15:27:03 +09:00
* @description KIS // .
2026-02-06 17:50:35 +09:00
*/
interface KisTokenResponse {
access_token?: string;
access_token_token_expired?: string;
2026-02-11 15:27:03 +09:00
access_token_expired?: string;
2026-02-06 17:50:35 +09:00
expires_in?: number;
msg1?: string;
msg_cd?: string;
error?: string;
error_description?: string;
}
interface KisTokenCache {
token: string;
expiresAt: number;
}
interface KisRevokeResponse {
code?: number | string;
message?: string;
msg1?: string;
}
const tokenCacheMap = new Map<string, KisTokenCache>();
const tokenIssueInFlightMap = new Map<string, Promise<KisTokenCache>>();
const TOKEN_REFRESH_BUFFER_MS = 60 * 1000;
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)}`;
}
2026-02-11 15:27:03 +09:00
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)을 확인해 주세요.";
}
2026-02-06 17:50:35 +09:00
/**
2026-02-11 15:27:03 +09:00
* @description KIS .
* @see app/api/kis/validate/route.ts
2026-02-06 17:50:35 +09:00
*/
async function issueKisToken(credentials?: KisCredentialInput): Promise<KisTokenCache> {
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),
};
}
/**
2026-02-11 15:27:03 +09:00
* @description .
* @see lib/kis/domestic.ts
2026-02-06 17:50:35 +09:00
*/
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 inFlight = tokenIssueInFlightMap.get(cacheKey);
if (inFlight) {
const shared = await inFlight;
return shared.token;
}
const nextPromise = issueKisToken(credentials);
tokenIssueInFlightMap.set(cacheKey, nextPromise);
2026-02-11 15:27:03 +09:00
2026-02-06 17:50:35 +09:00
const next = await nextPromise.finally(() => {
tokenIssueInFlightMap.delete(cacheKey);
});
tokenCacheMap.set(cacheKey, next);
return next.token;
}
/**
2026-02-11 15:27:03 +09:00
* @description KIS .
* @see app/api/kis/revoke/route.ts
2026-02-06 17:50:35 +09:00
*/
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(" / ");
2026-02-11 15:27:03 +09:00
2026-02-06 17:50:35 +09:00
throw new Error(
detail
? `KIS 토큰 폐기 실패 (${config.tradingEnv}, ${response.status}): ${detail}`
: `KIS 토큰 폐기 실패 (${config.tradingEnv}, ${response.status})`,
);
}
tokenCacheMap.delete(cacheKey);
tokenIssueInFlightMap.delete(cacheKey);
clearKisApprovalKeyCache(credentials);
2026-02-11 15:27:03 +09:00
return payload.message ?? "액세스 토큰 폐기가 완료되었습니다.";
2026-02-06 17:50:35 +09:00
}