fix(auth): 2단계 인증을 켠 사이트의 로그인 흐름 구현

2단계 인증은 7.0.6 에서 서버측이 갖춰졌지만 인증번호를 입력할 화면이 어느 버전에도
없었다. 그래서 그 설정을 켠 사이트는 관리자를 포함한 전원이 로그인할 수 없었다.

원인은 `POST /api/auth/login` 이 조건에 따라 **다른 형태의 200** 을 돌려준다는 것이다.
평소에는 `{token, user}` 지만 2단계 인증이 켜져 있으면 `{two_factor_required,
challenge_id, ...}` 를 돌려준다. 프론트는 앞의 형태만 선언하고 `response.data.user.language`
를 바로 읽었으므로 그 자리에서 TypeError 가 났고, 영문 원문이 로그인 화면에 그대로 노출됐다.
서버는 정상 응답했으므로 서버 로그에는 아무 흔적도 남지 않는다.

이어서 `setToken(undefined)` 가 `localStorage` 에 문자열 `"undefined"` 를 남겼다.
이 값은 truthy 라 이후 모든 요청이 `Bearer undefined` 로 나가 401 이 되고, 사용자에게는
「세션이 만료되었습니다」로 보인다. 관리자 로그인은 한발 더 나가 `null->isAdmin` 으로
500 이 되어, 설정을 되돌릴 수단까지 함께 사라졌다.

## 구현

- 로그인 응답을 판별 유니온(`LoginResult`)으로 표현하고, 형태를 판별한 뒤에 읽는다.
 `ApiClient.setToken` 은 비어 있지 않은 문자열만 저장한다.
- 사용자·관리자 로그인 화면에 인증번호 입력 단계를 추가했다. 같은 카드 안에서 넘어가며
 「인증번호 다시 받기」와 「처음부터」를 제공한다. 관리자 판정은 코드 확인에 성공한 뒤에
 수행하고, 거부할 때는 그 직전에 발급된 토큰을 회수한다.
- 재발송(`login/two-factor/resend`)은 기존 challenge 를 취소하고 새로 발행한다. 유효한
 코드를 여러 개 살려 두면 대입 시도의 표적이 넓어진다.
- 인증번호를 보내지 못하면 401 이 아니라 503 으로 답한다. 자격 증명은 올바른데 401 로
 뭉개면 사용자는 비밀번호를 의심하며 같은 시도를 반복하고, 운영자는 메일 설정이 깨진
 사실을 알 방법이 없다.
- 공개 본인인증 경로(`identity/verify`·`cancel`)가 로그인 목적의 challenge 를 소진하지
 못하도록 403 게이트를 세웠다. 소진되면 그 challenge 로 영영 로그인할 수 없다.
- 로그인 시도 제한 429 응답이 다국어 문구를 싣도록 했다(종전에는 프레임워크 기본 영문).
- 다국어 파라미터에서 파이프 표현식이 평가되지 않아 「유효시간 까지」처럼 값이 빠지던
 문제를 함께 고쳤다. 같은 결함이 문의 목록 화면에도 있었다.

## 이번 점검에서 함께 고친 것

- 계정 잠금(423)·발송 실패(503) 응답이 사용자·관리자 컨트롤러에 동일하게 복제돼 있었고
 그 주석 자신은 "단일 지점에서 만든다" 고 적혀 있었다. 페이로드에 필드가 하나 추가되면
 한쪽만 따라가 같은 실패를 두 화면이 다르게 안내하게 된다 — 트레이트로 통합했다.
- 테스트가 개발자 자신의 사이트 설정을 읽고 있었다. 2단계 인증을 켜 둔 환경에서는 로그인
 성공을 전제한 테스트가 503 으로 깨지는데 실패 메시지가 원인을 가리키지도 않는다.
 같은 결함군을 위해 이미 존재하던 단일 지점에 그 축을 추가했다.

## 버전

코어 7.0.11 · sirsoft-basic 1.1.4 · sirsoft-admin_basic 1.0.9 ·
번들 일본어팩 3종 · 템플릿 엔진 engine-v1.65.0.
This commit is contained in:
HeuJung committed 2026-09-07 17:08:14 +09:00
1 parent 72fb12f267
commit 50007d5cc6
98 files changed
+5815 -231

No files matched your search

+12
View File
@@ -117,8 +117,20 @@ class ApiClient {
/**
* 토큰 저장
*
* 문자열이 아닌 값은 저장하지 않는다. `localStorage` 는 무엇을 넣든 문자열로 바꿔
* 저장하므로 `undefined` 를 넘기면 `"undefined"` 라는 truthy 문자열이 남고, 이후
* 모든 요청이 `Bearer undefined` 로 나가 401 로 튕긴다 — 화면에는 "세션이 만료되었습니다"
* 로 보여 원인을 추적할 단서가 남지 않는다.
*
* @since engine-v1.65.0
*/
setToken(token: string): void {
if (typeof token !== 'string' || token === '') {
logger.warn('Ignoring invalid auth token — token must be a non-empty string.');
return;
}
if (typeof window !== 'undefined') {
localStorage.setItem(this.TOKEN_KEY, token);
}
@@ -98,6 +98,28 @@ describe('ApiClient', () => {
it('토큰이 없으면 null을 반환해야 함', () => {
expect(apiClient.getToken()).toBeNull();
});
it('문자열이 아닌 토큰은 저장하지 않아야 함', () => {
// localStorage 는 무엇을 넣든 문자열로 바꾼다 — undefined 를 넘기면 "undefined" 라는
// truthy 문자열이 남아 이후 모든 요청이 Bearer undefined 로 나가고 401 로 튕긴다.
apiClient.setToken(undefined as unknown as string);
expect(localStorage.getItem('auth_token')).toBeNull();
expect(apiClient.getToken()).toBeNull();
});
it('빈 문자열 토큰도 저장하지 않아야 함', () => {
apiClient.setToken('');
expect(localStorage.getItem('auth_token')).toBeNull();
});
it('기존 토큰이 있어도 잘못된 값으로 덮어쓰지 않아야 함', () => {
apiClient.setToken('valid-token');
apiClient.setToken(null as unknown as string);
expect(apiClient.getToken()).toBe('valid-token');
});
});
describe('HTTP 메서드', () => {
+263 -68
View File
@@ -36,8 +36,38 @@ export interface AuthConfig {
loginEndpoint: string;
logoutEndpoint: string;
refreshEndpoint: string;
/** 2단계 인증 코드 확인 엔드포인트 */
twoFactorEndpoint: string;
/** 2단계 인증 코드 재발송 엔드포인트 */
twoFactorResendEndpoint: string;
}
/**
* 2단계 인증 challenge 정보
*
* 비밀번호 확인만 통과한 상태다 — 토큰은 아직 발급되지 않았고, 코드 확인에 성공해야
* 세션이 열린다.
*
* @since engine-v1.65.0
*/
export interface TwoFactorChallenge {
challengeId: string;
providerId: string;
expiresAt: string | null;
}
/**
* 로그인 결과
*
* 서버는 보안 환경설정에 따라 **두 가지 형태의 200** 을 돌려준다. 한 형태만 가정하면
* 다른 형태에서 토큰·사용자 필드가 없어 화면이 알 수 없는 오류로 멈춘다.
*
* @since engine-v1.65.0
*/
export type LoginResult =
| { status: 'authenticated'; user: AuthUser }
| { status: 'two_factor_required'; challenge: TwoFactorChallenge };
/**
* 인증된 사용자 정보
*/
@@ -62,6 +92,20 @@ export interface AuthState {
*/
type EventHandler = (...args: any[]) => void;
/**
* 로그인·2단계 인증 응답의 data 페이로드
*
* 두 형태(토큰 발급 / challenge 발급)가 같은 자리에 오므로 전부 선택 필드다.
*/
interface LoginResponseData {
token?: string;
user?: AuthUser;
two_factor_required?: boolean;
challenge_id?: string;
provider_id?: string;
expires_at?: string | null;
}
/**
* 기본 인증 설정
*/
@@ -74,6 +118,8 @@ const defaultConfigs: Record<AuthType, AuthConfig> = {
loginEndpoint: '/auth/admin/login',
logoutEndpoint: '/admin/auth/logout',
refreshEndpoint: '/admin/auth/refresh',
twoFactorEndpoint: '/auth/admin/login/two-factor',
twoFactorResendEndpoint: '/auth/admin/login/two-factor/resend',
},
user: {
type: 'user',
@@ -83,6 +129,8 @@ const defaultConfigs: Record<AuthType, AuthConfig> = {
loginEndpoint: '/auth/login',
logoutEndpoint: '/auth/logout',
refreshEndpoint: '/auth/refresh',
twoFactorEndpoint: '/auth/login/two-factor',
twoFactorResendEndpoint: '/auth/login/two-factor/resend',
},
};
@@ -238,15 +286,83 @@ export class AuthManager {
/**
* 로그인 처리
*
* 서버는 두 가지 형태의 200 을 돌려준다 — 토큰과 사용자가 실린 정상 응답, 그리고
* 2단계 인증이 켜져 있을 때의 challenge 응답이다. 후자에는 토큰도 사용자도 없으므로
* 세션을 열지 않고 challenge 만 돌려준다.
*
* @param type - 인증 타입
* @param credentials - 로그인 자격 증명
* @param options - 추가 옵션 (headers 등)
* @returns 인증된 사용자 정보
* @returns 인증 완료 또는 2단계 인증 요구
* @since engine-v1.65.0 반환 타입이 `AuthUser` 에서 `LoginResult` 로 바뀌었습니다.
*/
async login(
type: AuthType,
credentials: { email: string; password: string },
options?: { headers?: Record<string, string> }
): Promise<LoginResult> {
const apiClient = getApiClient();
const config = this.config.get(type);
if (!config) {
throw new Error(`Unknown auth type: ${type}`);
}
try {
// 추가 헤더 설정 (globalHeaders 지원)
const requestConfig = options?.headers ? { headers: options.headers } : undefined;
const response = await apiClient.post<{
success: boolean;
data: LoginResponseData;
}>(config.loginEndpoint, credentials, requestConfig);
if (response.success && response.data) {
// 2단계 인증 요구 — 토큰이 없으므로 상태를 건드리지 않는다.
if (response.data.two_factor_required === true) {
trackAuthEvent('login', true, undefined, { type, two_factor: true });
return {
status: 'two_factor_required',
challenge: {
challengeId: String(response.data.challenge_id ?? ''),
providerId: String(response.data.provider_id ?? ''),
expiresAt: response.data.expires_at ?? null,
},
};
}
// 두 필드가 모두 있을 때만 세션을 연다 — 한쪽만 보고 진행하면 undefined 토큰이
// 저장되어 이후 모든 요청이 401 이 된다.
if (response.data.token && response.data.user) {
return {
status: 'authenticated',
user: this.establishSession(type, response.data.token, response.data.user),
};
}
}
throw new Error('Login failed');
} catch (error: any) {
this.clearState();
throw this.enhanceAuthError(error, type, 'Login failed');
}
}
/**
* 2단계 인증 코드를 확인하고 로그인을 완료합니다.
*
* @param type - 인증 타입
* @param payload - challenge 식별자와 사용자가 받은 인증번호
* @param options - 추가 옵션 (headers 등)
* @returns 인증된 사용자 정보
* @since engine-v1.65.0
*/
async completeTwoFactor(
type: AuthType,
payload: { challengeId: string; code: string },
options?: { headers?: Record<string, string> }
): Promise<AuthUser> {
const apiClient = getApiClient();
const config = this.config.get(type);
@@ -255,88 +371,167 @@ export class AuthManager {
throw new Error(`Unknown auth type: ${type}`);
}
// 로그인 엔드포인트 결정
const loginEndpoint = type === 'admin'
? defaultConfigs.admin.loginEndpoint
: defaultConfigs.user.loginEndpoint;
try {
// 추가 헤더 설정 (globalHeaders 지원)
const requestConfig = options?.headers ? { headers: options.headers } : undefined;
const response = await apiClient.post<{
success: boolean;
data: {
token: string;
user: AuthUser;
};
}>(loginEndpoint, credentials, requestConfig);
data: LoginResponseData;
}>(
config.twoFactorEndpoint,
{ challenge_id: payload.challengeId, code: payload.code },
requestConfig
);
if (response.success && response.data) {
// 토큰 저장
apiClient.setToken(response.data.token);
// 사용자의 language 설정 확인 및 로케일 변경 처리
const userLanguage = response.data.user.language;
const currentLocale = localStorage.getItem(AuthManager.LOCALE_STORAGE_KEY);
const localeChanged = userLanguage && userLanguage !== currentLocale;
if (userLanguage) {
try {
localStorage.setItem(AuthManager.LOCALE_STORAGE_KEY, userLanguage);
} catch (error) {
logger.warn('Failed to save user language to localStorage:', error);
}
}
// 상태 업데이트
this.state = {
isAuthenticated: true,
user: response.data.user,
type: type,
};
this.emit('login', this.state);
this.emit('authStateChange', this.state);
// DevTools 추적
trackAuthEvent('login', true, undefined, {
userId: response.data.user.uuid,
email: response.data.user.email,
type,
});
// 로케일이 변경된 경우 TemplateApp 재초기화
if (localeChanged && (window as any).__templateApp) {
// changeLocale은 비동기이므로 await 하지 않고 실행
// navigate가 먼저 실행되고, changeLocale이 완료되면 UI가 업데이트됨
(window as any).__templateApp.changeLocale(userLanguage);
}
return response.data.user;
if (response.success && response.data?.token && response.data?.user) {
return this.establishSession(type, response.data.token, response.data.user);
}
throw new Error('Login failed');
} catch (error: any) {
this.clearState();
// Axios 에러에서 API 응답 메시지 추출
// error.response.data.message가 실제 서버 응답 메시지
const apiMessage = error.response?.data?.message;
const enhancedError: any = new Error(apiMessage || error.message || 'Login failed');
enhancedError.response = error.response;
enhancedError.status = error.response?.status;
// DevTools 추적
trackAuthEvent('login', false, enhancedError.message, {
type,
status: error.response?.status,
});
throw enhancedError;
throw this.enhanceAuthError(error, type, 'Login failed');
}
}
/**
* 2단계 인증 코드를 재발송합니다.
*
* 서버가 기존 challenge 를 취소하고 새로 발행하므로, 앞서 받은 인증번호는 더 이상
* 통하지 않습니다 — 호출자는 반드시 새 challenge 로 교체해야 합니다.
*
* @param type - 인증 타입
* @param payload - 재발송할 challenge 식별자
* @param options - 추가 옵션 (headers 등)
* @returns 새 challenge 정보
* @since engine-v1.65.0
*/
async resendTwoFactor(
type: AuthType,
payload: { challengeId: string },
options?: { headers?: Record<string, string> }
): Promise<TwoFactorChallenge> {
const apiClient = getApiClient();
const config = this.config.get(type);
if (!config) {
throw new Error(`Unknown auth type: ${type}`);
}
try {
const requestConfig = options?.headers ? { headers: options.headers } : undefined;
const response = await apiClient.post<{
success: boolean;
data: LoginResponseData;
}>(
config.twoFactorResendEndpoint,
{ challenge_id: payload.challengeId },
requestConfig
);
if (response.success && response.data?.challenge_id) {
return {
challengeId: String(response.data.challenge_id),
providerId: String(response.data.provider_id ?? ''),
expiresAt: response.data.expires_at ?? null,
};
}
throw new Error('Resend failed');
} catch (error: any) {
// 재발송 실패는 세션 상태와 무관하다 — 이미 열린 세션이 없으므로 상태를 지우지 않는다.
throw this.enhanceAuthError(error, type, 'Resend failed');
}
}
/**
* 토큰을 저장하고 인증 상태·로케일을 확정합니다.
*
* 정상 로그인과 2단계 인증 완료가 같은 후처리를 공유하도록 단일 지점에 둔다 —
* 갈라지면 한쪽 경로에서만 로케일 전환이나 이벤트 발행이 빠진다.
*
* @param type - 인증 타입
* @param token - 발급된 토큰
* @param user - 인증된 사용자
* @returns 인증된 사용자 정보
*/
private establishSession(type: AuthType, token: string, user: AuthUser): AuthUser {
const apiClient = getApiClient();
// 토큰 저장
apiClient.setToken(token);
// 사용자의 language 설정 확인 및 로케일 변경 처리
const userLanguage = user.language;
const currentLocale = localStorage.getItem(AuthManager.LOCALE_STORAGE_KEY);
const localeChanged = userLanguage && userLanguage !== currentLocale;
if (userLanguage) {
try {
localStorage.setItem(AuthManager.LOCALE_STORAGE_KEY, userLanguage);
} catch (error) {
logger.warn('Failed to save user language to localStorage:', error);
}
}
// 상태 업데이트
this.state = {
isAuthenticated: true,
user,
type,
};
this.emit('login', this.state);
this.emit('authStateChange', this.state);
// DevTools 추적
trackAuthEvent('login', true, undefined, {
userId: user.uuid,
email: user.email,
type,
});
// 로케일이 변경된 경우 TemplateApp 재초기화
if (localeChanged && (window as any).__templateApp) {
// changeLocale은 비동기이므로 await 하지 않고 실행
// navigate가 먼저 실행되고, changeLocale이 완료되면 UI가 업데이트됨
(window as any).__templateApp.changeLocale(userLanguage);
}
return user;
}
/**
* 인증 실패 오류에 서버 응답 정보를 실어 다시 던질 오류를 만듭니다.
*
* `code` 를 보존해야 호출자가 네트워크 실패(`ERR_NETWORK` 등)와 HTTP 오류를 구분해
* 다국어 문구로 안내할 수 있다 — axios 오류는 `TypeError` 가 아니다.
*
* @param error - 원본 오류
* @param type - 인증 타입
* @param fallbackMessage - 서버 메시지가 없을 때 쓸 기본 문구
* @returns 보강된 오류
*/
private enhanceAuthError(error: any, type: AuthType, fallbackMessage: string): any {
// Axios 에러에서 API 응답 메시지 추출
// error.response.data.message가 실제 서버 응답 메시지
const apiMessage = error?.response?.data?.message;
const enhancedError: any = new Error(apiMessage || error?.message || fallbackMessage);
enhancedError.response = error?.response;
enhancedError.status = error?.response?.status;
enhancedError.code = error?.code;
// DevTools 추적
trackAuthEvent('login', false, enhancedError.message, {
type,
status: error?.response?.status,
});
return enhancedError;
}
/**
* 로그아웃 처리
*/
@@ -308,7 +308,7 @@ describe('AuthManager', () => {
password: 'password',
});
expect(result).toEqual(mockUser);
expect(result).toEqual({ status: 'authenticated', user: mockUser });
expect(mockApiClient.setToken).toHaveBeenCalledWith('new-token');
expect(authManager.isAuthenticated()).toBe(true);
expect(authManager.getUser()).toEqual(mockUser);
@@ -381,5 +381,155 @@ describe('AuthManager', () => {
undefined
);
});
it('2단계 인증 응답에서는 토큰을 저장하지 않고 challenge 를 돌려줘야 합니다', async () => {
mockApiClient.post.mockResolvedValue({
success: true,
data: {
two_factor_required: true,
challenge_id: 'challenge-uuid',
provider_id: 'g7:core.mail',
expires_at: '2026-09-07T14:03:00+09:00',
},
});
const result = await authManager.login('user', {
email: 'test@example.com',
password: 'password',
});
expect(result).toEqual({
status: 'two_factor_required',
challenge: {
challengeId: 'challenge-uuid',
providerId: 'g7:core.mail',
expiresAt: '2026-09-07T14:03:00+09:00',
},
});
// 토큰도 사용자도 없는 응답이다 — 저장하면 이후 모든 요청이 Bearer undefined 로 나간다.
expect(mockApiClient.setToken).not.toHaveBeenCalled();
expect(authManager.isAuthenticated()).toBe(false);
});
it('updateConfig 로 바꾼 loginEndpoint 를 사용해야 합니다', async () => {
mockApiClient.post.mockResolvedValue({
success: true,
data: { token: 'new-token', user: { id: 1, name: 'T', email: 't@e.com' } },
});
authManager.updateConfig('user', { loginEndpoint: '/auth/custom-login' });
await authManager.login('user', { email: 'test@example.com', password: 'password' });
expect(mockApiClient.post).toHaveBeenCalledWith(
'/auth/custom-login',
{ email: 'test@example.com', password: 'password' },
undefined
);
});
it('네트워크 오류의 code 를 보존해야 합니다', async () => {
const networkError: any = new Error('Network Error');
networkError.code = 'ERR_NETWORK';
mockApiClient.post.mockRejectedValue(networkError);
// TypeError 가 아니므로 code 가 사라지면 네트워크 실패 판정이 불가능해진다.
await expect(
authManager.login('user', { email: 'test@example.com', password: 'password' })
).rejects.toMatchObject({ code: 'ERR_NETWORK' });
});
});
describe('completeTwoFactor', () => {
it('코드 확인에 성공하면 토큰을 저장하고 로그인 상태가 되어야 합니다', async () => {
const mockUser: AuthUser = {
id: 1,
name: 'Test User',
email: 'test@example.com',
};
mockApiClient.post.mockResolvedValue({
success: true,
data: { token: 'two-factor-token', user: mockUser },
});
const loginHandler = vi.fn();
authManager.on('login', loginHandler);
const result = await authManager.completeTwoFactor('user', {
challengeId: 'challenge-uuid',
code: '135790',
});
expect(result).toEqual(mockUser);
expect(mockApiClient.post).toHaveBeenCalledWith(
'/auth/login/two-factor',
{ challenge_id: 'challenge-uuid', code: '135790' },
undefined
);
expect(mockApiClient.setToken).toHaveBeenCalledWith('two-factor-token');
expect(authManager.isAuthenticated()).toBe(true);
expect(loginHandler).toHaveBeenCalled();
});
it('관리자 타입은 관리자 전용 엔드포인트를 사용해야 합니다', async () => {
mockApiClient.post.mockResolvedValue({
success: true,
data: { token: 't', user: { id: 1, name: 'T', email: 't@e.com' } },
});
await authManager.completeTwoFactor('admin', {
challengeId: 'challenge-uuid',
code: '135790',
});
expect(mockApiClient.post).toHaveBeenCalledWith(
'/auth/admin/login/two-factor',
{ challenge_id: 'challenge-uuid', code: '135790' },
undefined
);
});
it('실패 시 서버 메시지를 실은 에러를 throw 해야 합니다', async () => {
const error: any = new Error('Request failed');
error.response = { status: 401, data: { message: '인증번호가 올바르지 않습니다.' } };
mockApiClient.post.mockRejectedValue(error);
await expect(
authManager.completeTwoFactor('user', { challengeId: 'c', code: '000000' })
).rejects.toThrow('인증번호가 올바르지 않습니다.');
expect(authManager.isAuthenticated()).toBe(false);
});
});
describe('resendTwoFactor', () => {
it('새 challenge 를 돌려주고 토큰은 건드리지 않아야 합니다', async () => {
mockApiClient.post.mockResolvedValue({
success: true,
data: {
two_factor_required: true,
challenge_id: 'new-challenge',
provider_id: 'g7:core.mail',
expires_at: null,
},
});
const result = await authManager.resendTwoFactor('user', {
challengeId: 'old-challenge',
});
expect(result).toEqual({
challengeId: 'new-challenge',
providerId: 'g7:core.mail',
expiresAt: null,
});
expect(mockApiClient.post).toHaveBeenCalledWith(
'/auth/login/two-factor/resend',
{ challenge_id: 'old-challenge' },
undefined
);
expect(mockApiClient.setToken).not.toHaveBeenCalled();
});
});
});
+2
View File
@@ -4,4 +4,6 @@ export {
type AuthConfig,
type AuthUser,
type AuthState,
type TwoFactorChallenge,
type LoginResult,
} from './AuthManager';
@@ -132,6 +132,8 @@ export type ActionType =
| 'replaceUrl' // URL만 변경 (데이터소스 refetch 없음)
| 'apiCall' // API 호출
| 'login' // 로그인 (토큰 저장 포함)
| 'loginTwoFactor' // 2단계 인증 코드 확인 (로그인 완료)
| 'loginTwoFactorResend' // 2단계 인증 코드 재발송
| 'logout' // 로그아웃
| 'setState' // 상태 변경
| 'setError' // 에러 상태 설정
@@ -2464,6 +2466,22 @@ export class ActionDispatcher {
);
break;
case 'loginTwoFactor':
result = await this.handleLoginTwoFactor(
resolvedTarget!,
resolvedParams,
context
);
break;
case 'loginTwoFactorResend':
result = await this.handleLoginTwoFactorResend(
resolvedTarget!,
resolvedParams,
context
);
break;
case 'logout':
result = await this.handleLogout(resolvedTarget!, context);
break;
@@ -3828,8 +3846,7 @@ export class ActionDispatcher {
);
}
// target을 인증 타입으로 사용 (admin 또는 user)
const authType: AuthType = target === 'user' ? 'user' : 'admin';
const authType = this.resolveAuthType(target);
// 로그인 엔드포인트 결정 (globalHeaders 패턴 매칭용)
// ApiClient는 baseURL이 '/api'이므로 실제 요청 경로에 '/api' prefix 추가
@@ -3837,49 +3854,184 @@ export class ActionDispatcher {
? '/api/auth/admin/login'
: '/api/auth/login';
// globalHeaders에서 패턴 매칭되는 헤더 추출
// Stale Closure 방지: G7Core.state.getGlobal/getLocal()로 최신 상태 조회
// (cartKey 재발급 등 중간에 상태가 변경된 경우에도 최신 값 사용)
const currentGlobalState = (window as any).G7Core?.state?.getGlobal?.() || _context.state?._global || {};
const currentLocalState = (window as any).G7Core?.state?.getLocal?.() || _context.state?._local || {};
const expressionContext: Record<string, any> = {
_global: currentGlobalState,
_local: currentLocalState,
};
const globalHeadersResolved = this.getMatchingGlobalHeaders(loginEndpoint, expressionContext);
const authManager = AuthManager.getInstance();
try {
// AuthManager.login()을 통해 로그인 및 토큰 저장
// globalHeaders가 있으면 options.headers로 전달
const loginOptions = Object.keys(globalHeadersResolved).length > 0
? { headers: globalHeadersResolved }
: undefined;
const user = await authManager.login(
const result = await authManager.login(
authType,
{ email: body.email, password: body.password },
loginOptions
this.buildAuthRequestOptions(loginEndpoint, _context)
);
// 2단계 인증이 켜진 사이트에서는 아직 로그인이 끝나지 않았다. 레이아웃이 그 사실을
// 알 통로가 없으면 인증번호 입력 단계로 넘어갈 방법이 없다.
if (result.status === 'two_factor_required') {
return {
user: null,
two_factor_required: true,
challenge_id: result.challenge.challengeId,
provider_id: result.challenge.providerId,
expires_at: result.challenge.expiresAt,
};
}
// `user` 는 종전 계약 그대로 유지한다 — 기존 레이아웃이 `response.user` 를 읽는다.
return { user: result.user, two_factor_required: false };
} catch (error: any) {
throw this.toLoginActionError(error, 'Login failed');
}
}
/**
* loginTwoFactor 액션을 처리합니다.
*
* 비밀번호 확인 단계가 돌려준 challenge 와 사용자가 받은 인증번호로 로그인을 완료합니다.
*
* @param target 인증 타입 (admin 또는 user)
* @param params 요청 파라미터 (body에 challenge_id, code 포함)
* @param context 액션 컨텍스트
* @since engine-v1.65.0
*/
private async handleLoginTwoFactor(
target: string,
params: Record<string, any>,
context: ActionContext
): Promise<any> {
const { body } = params;
if (!body || !body.challenge_id || !body.code) {
throw new ActionError(
'loginTwoFactor requires challenge_id and code in body params'
);
}
const authType = this.resolveAuthType(target);
const endpoint = authType === 'admin'
? '/api/auth/admin/login/two-factor'
: '/api/auth/login/two-factor';
try {
const user = await AuthManager.getInstance().completeTwoFactor(
authType,
{ challengeId: String(body.challenge_id), code: String(body.code) },
this.buildAuthRequestOptions(endpoint, context)
);
return { user };
} catch (error: any) {
// AuthManager에서 이미 API 응답 메시지를 추출한 에러를 throw하므로
// error.message에 실제 서버 응답 메시지가 들어있음
const errorMessage = error.message || 'Login failed';
throw this.toLoginActionError(error, 'Login failed');
}
}
const apiError: any = new Error(errorMessage);
apiError.response = error.response?.data || {};
apiError.status = error.status || error.response?.status || 500;
/**
* loginTwoFactorResend 액션을 처리합니다.
*
* 서버가 기존 challenge 를 취소하고 새로 발행하므로, 레이아웃은 반환된 새
* `challenge_id` 로 반드시 교체해야 합니다.
*
* @param target 인증 타입 (admin 또는 user)
* @param params 요청 파라미터 (body에 challenge_id 포함)
* @param context 액션 컨텍스트
* @since engine-v1.65.0
*/
private async handleLoginTwoFactorResend(
target: string,
params: Record<string, any>,
context: ActionContext
): Promise<any> {
const { body } = params;
if (!body || !body.challenge_id) {
throw new ActionError(
errorMessage,
undefined,
apiError
'loginTwoFactorResend requires challenge_id in body params'
);
}
const authType = this.resolveAuthType(target);
const endpoint = authType === 'admin'
? '/api/auth/admin/login/two-factor/resend'
: '/api/auth/login/two-factor/resend';
try {
const challenge = await AuthManager.getInstance().resendTwoFactor(
authType,
{ challengeId: String(body.challenge_id) },
this.buildAuthRequestOptions(endpoint, context)
);
return {
two_factor_required: true,
challenge_id: challenge.challengeId,
provider_id: challenge.providerId,
expires_at: challenge.expiresAt,
};
} catch (error: any) {
throw this.toLoginActionError(error, 'Resend failed');
}
}
/**
* 액션 target 을 인증 타입으로 해석합니다.
*
* @param target 액션 target
* @returns 인증 타입
*/
private resolveAuthType(target: string): AuthType {
return target === 'user' ? 'user' : 'admin';
}
/**
* 인증 요청에 실을 globalHeaders 옵션을 만듭니다.
*
* 세 인증 핸들러가 같은 규칙을 공유하도록 단일 지점에 둔다 — 갈라지면 한 경로에만
* 공통 헤더가 빠져 그 요청만 조용히 다르게 나간다.
*
* @param endpoint 요청 경로 (globalHeaders 패턴 매칭용, '/api' prefix 포함)
* @param context 액션 컨텍스트
* @returns headers 옵션 (매칭된 헤더가 없으면 undefined)
*/
private buildAuthRequestOptions(
endpoint: string,
context: ActionContext
): { headers: Record<string, string> } | undefined {
// Stale Closure 방지: G7Core.state.getGlobal/getLocal()로 최신 상태 조회
// (cartKey 재발급 등 중간에 상태가 변경된 경우에도 최신 값 사용)
const currentGlobalState = (window as any).G7Core?.state?.getGlobal?.() || context.state?._global || {};
const currentLocalState = (window as any).G7Core?.state?.getLocal?.() || context.state?._local || {};
const expressionContext: Record<string, any> = {
_global: currentGlobalState,
_local: currentLocalState,
};
const resolved = this.getMatchingGlobalHeaders(endpoint, expressionContext);
return Object.keys(resolved).length > 0 ? { headers: resolved } : undefined;
}
/**
* AuthManager 오류를 액션 오류로 재포장합니다.
*
* `code` 를 보존해야 호출자가 네트워크 실패와 HTTP 오류를 구분해 다국어 문구로
* 안내할 수 있다 — axios 오류는 `TypeError` 가 아니다.
*
* @param error 원본 오류
* @param fallbackMessage 서버 메시지가 없을 때 쓸 기본 문구
* @returns 액션 오류
*/
private toLoginActionError(error: any, fallbackMessage: string): ActionError {
// AuthManager에서 이미 API 응답 메시지를 추출한 에러를 throw하므로
// error.message에 실제 서버 응답 메시지가 들어있음
const errorMessage = error?.message || fallbackMessage;
const apiError: any = new Error(errorMessage);
apiError.response = error?.response?.data || {};
apiError.status = error?.status || error?.response?.status || 500;
apiError.code = error?.code;
return new ActionError(errorMessage, undefined, apiError);
}
/**
@@ -5,6 +5,27 @@
>
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
## [engine-v1.65.0] - 2026-09-07
### Added
#### 2단계 인증 로그인 단계 지원
- 로그인 응답을 `LoginResult` 판별 유니온으로 표현 — 정상 로그인과 인증번호 요구(challenge)를 타입으로 구분 (AuthManager.ts)
- `completeTwoFactor()` / `resendTwoFactor()` 추가 — 인증번호 확인·재발송 (AuthManager.ts)
- `AuthConfig` 에 `twoFactorEndpoint` / `twoFactorResendEndpoint` 추가 (AuthManager.ts)
- 액션 핸들러 `loginTwoFactor` / `loginTwoFactorResend` 추가 — 레이아웃에서 인증번호 확인·재발송 (ActionDispatcher.ts)
- `login` 핸들러 반환에 `two_factor_required` / `challenge_id` / `provider_id` / `expires_at` 추가 (기존 `user` 필드 유지) (ActionDispatcher.ts)
- 레이아웃 편집기 [화면 동작] 탭에 두 핸들러 등록 (coreActionRecipes.ts, ActionAddPicker.tsx)
### Fixed
#### 2단계 인증이 켜진 사이트에서 로그인 화면이 영문 오류로 멈추던 문제
- 로그인 응답 형태를 하나로 가정해 인증번호 요구 응답에서 `TypeError` 원문이 오류 박스에 노출되던 문제 (AuthManager.ts)
- 문자열이 아닌 토큰이 저장되어 이후 모든 요청이 401 로 튕기던 문제 (ApiClient.ts)
- `updateConfig({ loginEndpoint })` 로 지정한 엔드포인트가 무시되던 문제 (AuthManager.ts)
- axios 네트워크 오류가 네트워크 실패로 판정되지 않아 영문 원문이 노출되던 문제 (networkResilience.ts, ActionDispatcher.ts)
- 다국어 파라미터 값의 파이프 필터(`$t:key|until={{x | datetime}}`)가 평가되지 않아 문장에서 값만 사라지던 문제 (TranslationEngine.ts)
## [engine-v1.64.7] - 2026-09-04
### Fixed
@@ -19,6 +19,7 @@ import { fetchStaticFirst } from '../support/fetchStaticFirst';
// 양쪽 모두 모듈 평가 시점이 아니라 메서드 실행 시점에만 서로를 참조하므로
// live binding 이 채워진 뒤에 사용된다.
import { dataBindingEngine } from './DataBindingEngine';
import { hasPipes } from './PipeRegistry';
const logger = createLogger('TranslationEngine');
@@ -505,6 +506,20 @@ export class TranslationEngine {
if (value.startsWith('{{') && value.endsWith('}}')) {
const expression = value.slice(2, -2).trim();
// 파이프 필터(`{{x | datetime}}`)는 표현식 평가기가 모른다 — `|` 를 비트 연산자로
// 읽어 평가에 실패하고, 아래 catch 가 빈 문자열을 돌려주므로 문장에서 값만 조용히
// 사라진다("유효시간 까지"). 파이프 전용 평가기로 먼저 처리한다.
// @since engine-v1.65.0
if (hasPipes(expression) && dataContext) {
try {
const piped = dataBindingEngine.evaluatePipeExpression(expression, dataContext);
return String(piped ?? '');
} catch (error) {
logger.error('Pipe expression evaluation failed:', expression, error);
return '';
}
}
// 복잡한 표현식인지 확인 (연산자, 괄호, 메서드 호출 등 포함)
// 산술 연산자(+, -, *, /, %), 비교 연산자(<, >, =), 논리 연산자, 공백(피연산자 분리)도 포함
const isComplexExpression = /[|&()[\]!?:+\-*/%<>=\s]/.test(expression);
@@ -10,7 +10,7 @@ import { GlobalHeaderRule } from '../LayoutLoader';
import { Logger } from '../../utils/Logger';
// AuthManager mock - login 호출 시 전달된 인자 추적
const mockLogin = vi.fn().mockResolvedValue({ id: 1, name: 'Test User' });
const mockLogin = vi.fn().mockResolvedValue({ status: 'authenticated', user: { id: 1, name: 'Test User' } });
const mockLogout = vi.fn().mockResolvedValue(undefined);
vi.mock('../../auth/AuthManager', () => ({
@@ -40,7 +40,7 @@ describe('ActionDispatcher - globalHeaders', () => {
mockNavigate = vi.fn();
mockGetToken.mockReset();
mockLogin.mockReset();
mockLogin.mockResolvedValue({ id: 1, name: 'Test User' });
mockLogin.mockResolvedValue({ status: 'authenticated', user: { id: 1, name: 'Test User' } });
dispatcher = new ActionDispatcher({ navigate: mockNavigate });
Logger.getInstance().setDebug(false);
@@ -0,0 +1,218 @@
/**
* ActionDispatcher 2단계 인증 핸들러 테스트
*
* 서버는 보안 환경설정에 따라 로그인에 **두 가지 형태의 200** 을 돌려준다. 레이아웃이
* 그 사실을 알 통로가 없으면 인증번호 입력 단계로 넘어갈 방법이 없고, 화면은 알 수 없는
* 오류로 멈춘다(공개 #133).
*
* @since engine-v1.65.0
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { ActionDispatcher, ActionDefinition } from '../ActionDispatcher';
import { Logger } from '../../utils/Logger';
const mockLogin = vi.fn();
const mockCompleteTwoFactor = vi.fn();
const mockResendTwoFactor = vi.fn();
const mockLogout = vi.fn().mockResolvedValue(undefined);
vi.mock('../../auth/AuthManager', () => ({
AuthManager: {
getInstance: vi.fn(() => ({
login: mockLogin,
logout: mockLogout,
completeTwoFactor: mockCompleteTwoFactor,
resendTwoFactor: mockResendTwoFactor,
})),
},
}));
vi.mock('../../api/ApiClient', () => ({
getApiClient: vi.fn(() => ({
getToken: vi.fn(),
})),
}));
describe('ActionDispatcher - 2단계 인증', () => {
let dispatcher: ActionDispatcher;
beforeEach(() => {
mockLogin.mockReset();
mockCompleteTwoFactor.mockReset();
mockResendTwoFactor.mockReset();
dispatcher = new ActionDispatcher({ navigate: vi.fn() });
Logger.getInstance().setDebug(false);
});
afterEach(() => {
Logger.getInstance().setDebug(false);
});
const context = () => ({ state: { _global: {}, _local: {} } });
const run = async (action: ActionDefinition) => {
const result = await dispatcher.dispatchAction(action, context() as any);
if (!result.success) {
throw result.error ?? new Error('action failed');
}
return result.data;
};
describe('login', () => {
it('challenge 응답을 레이아웃이 읽을 수 있는 형태로 돌려준다', async () => {
mockLogin.mockResolvedValue({
status: 'two_factor_required',
challenge: {
challengeId: 'challenge-uuid',
providerId: 'g7:core.mail',
expiresAt: '2026-09-07T14:03:00+09:00',
},
});
const result = await run({
type: 'click',
handler: 'login',
target: 'user',
params: { body: { email: 'a@b.c', password: 'pw' } },
});
expect(result).toMatchObject({
user: null,
two_factor_required: true,
challenge_id: 'challenge-uuid',
provider_id: 'g7:core.mail',
expires_at: '2026-09-07T14:03:00+09:00',
});
});
it('정상 로그인은 종전대로 user 를 돌려준다', async () => {
const user = { id: 1, name: 'Test User' };
mockLogin.mockResolvedValue({ status: 'authenticated', user });
const result = await run({
type: 'click',
handler: 'login',
target: 'user',
params: { body: { email: 'a@b.c', password: 'pw' } },
});
// 기존 레이아웃이 `response.user` 를 읽으므로 이 계약은 유지되어야 한다.
expect(result).toMatchObject({ user, two_factor_required: false });
});
});
describe('loginTwoFactor', () => {
it('challenge_id 와 code 로 로그인을 완료한다', async () => {
const user = { id: 1, name: 'Test User' };
mockCompleteTwoFactor.mockResolvedValue(user);
const result = await run({
type: 'click',
handler: 'loginTwoFactor',
target: 'user',
params: { body: { challenge_id: 'challenge-uuid', code: '135790' } },
});
expect(mockCompleteTwoFactor).toHaveBeenCalledWith(
'user',
{ challengeId: 'challenge-uuid', code: '135790' },
undefined
);
expect(result).toEqual({ user });
});
it('globalHeaders 패턴이 관리자 확인 요청에도 적용된다', async () => {
mockCompleteTwoFactor.mockResolvedValue({ id: 1 });
dispatcher.setGlobalHeaders([
{ pattern: '/api/auth/*', headers: { 'X-Cart-Key': 'ck_admin456' } },
]);
await run({
type: 'click',
handler: 'loginTwoFactor',
target: 'admin',
params: { body: { challenge_id: 'c', code: '135790' } },
});
expect(mockCompleteTwoFactor).toHaveBeenCalledWith(
'admin',
{ challengeId: 'c', code: '135790' },
{ headers: { 'X-Cart-Key': 'ck_admin456' } }
);
});
it('code 가 없으면 요청을 보내지 않는다', async () => {
await expect(
run({
type: 'click',
handler: 'loginTwoFactor',
target: 'user',
params: { body: { challenge_id: 'c' } },
})
).rejects.toThrow();
expect(mockCompleteTwoFactor).not.toHaveBeenCalled();
});
it('서버 오류 메시지를 그대로 실어 재포장한다', async () => {
const error: any = new Error('인증번호가 올바르지 않거나 유효시간이 지났습니다.');
error.response = { status: 401, data: { message: '인증번호가 올바르지 않거나 유효시간이 지났습니다.' } };
error.status = 401;
mockCompleteTwoFactor.mockRejectedValue(error);
await expect(
run({
type: 'click',
handler: 'loginTwoFactor',
target: 'user',
params: { body: { challenge_id: 'c', code: '000000' } },
})
).rejects.toThrow('인증번호가 올바르지 않거나 유효시간이 지났습니다.');
});
});
describe('loginTwoFactorResend', () => {
it('새 challenge 를 돌려준다', async () => {
mockResendTwoFactor.mockResolvedValue({
challengeId: 'new-challenge',
providerId: 'g7:core.mail',
expiresAt: null,
});
const result = await run({
type: 'click',
handler: 'loginTwoFactorResend',
target: 'user',
params: { body: { challenge_id: 'old-challenge' } },
});
expect(mockResendTwoFactor).toHaveBeenCalledWith(
'user',
{ challengeId: 'old-challenge' },
undefined
);
expect(result).toEqual({
two_factor_required: true,
challenge_id: 'new-challenge',
provider_id: 'g7:core.mail',
expires_at: null,
});
});
it('challenge_id 가 없으면 요청을 보내지 않는다', async () => {
await expect(
run({
type: 'click',
handler: 'loginTwoFactorResend',
target: 'user',
params: { body: {} },
})
).rejects.toThrow();
expect(mockResendTwoFactor).not.toHaveBeenCalled();
});
});
});
@@ -594,6 +594,9 @@ describe('TranslationEngine', () => {
complex: {
message: '{{user}}님이 {{action}}을 수행했습니다 ({{count}}건)',
},
auth: {
valid_until: '유효시간 {{until}} 까지',
},
};
(global.fetch as any).mockResolvedValueOnce({
@@ -710,6 +713,32 @@ describe('TranslationEngine', () => {
);
expect(result).toBe('총 100명 중 1-10명 표시');
});
// 파라미터 값 안의 파이프는 **필터**다. 표현식 평가기는 `|` 를 비트 연산자로 읽어
// 평가에 실패하고 빈 문자열을 돌려주므로, 문장에서 값만 조용히 사라진다
// ("유효시간 까지"). 오류도 경고도 남지 않아 화면을 보지 않으면 드러나지 않는다.
// @since engine-v1.65.0
it('파라미터 값의 파이프 필터가 적용된다', () => {
const result = engine.translate(
'auth.valid_until',
context,
'|until={{expires_at | datetime}}',
{ expires_at: '2026-09-07T14:03:00' }
);
expect(result).toBe('유효시간 2026-09-07 14:03 까지');
});
it('resolveTranslations 에서도 파라미터 파이프 필터가 적용된다', () => {
const result = engine.resolveTranslations(
'$t:auth.valid_until',
context,
{ expires_at: '2026-09-07T14:03:00' }
);
// 파라미터가 없으면 자리표시자는 그대로 둔다 (기존 동작 유지)
expect(result).toContain('유효시간');
});
});
describe('resolveTranslations 재귀 처리', () => {
@@ -33,6 +33,26 @@ describe('resolveActionFailureMessage', () => {
);
});
it('axios 네트워크 오류도 네트워크 계열로 안내한다', () => {
// axios 는 TypeError 가 아니라 AxiosError 로 reject 하며 종류는 code 에만 남는다.
// TypeError 만 보면 로그인 화면에 영문 원문(Network Error)이 그대로 노출된다.
const axiosError: any = new Error('Network Error');
axiosError.code = 'ERR_NETWORK';
expect(resolveActionFailureMessage(axiosError, 'login', undefined)).toBe(
'$t:core.errors.network_request_failed'
);
});
it('요청 시간 초과도 네트워크 계열로 안내한다', () => {
const timeout: any = new Error('timeout of 30000ms exceeded');
timeout.code = 'ECONNABORTED';
expect(resolveActionFailureMessage(timeout, 'login', undefined)).toBe(
'$t:core.errors.network_request_failed'
);
});
it('서버가 메시지를 주면 그대로 쓴다', () => {
expect(
resolveActionFailureMessage(new Error('boom'), 'apiCall', '유효하지 않은 레이아웃 전략입니다.')
@@ -24,7 +24,7 @@ const EXPECTED_HANDLERS = [
// C14~C16 데이터
'refetchDataSource', 'appendDataSource', 'updateDataSource',
// C17~C22 기타
'scrollIntoView', 'login', 'logout', 'setLocale', 'emitEvent', 'apiCall',
'scrollIntoView', 'login', 'loginTwoFactor', 'loginTwoFactorResend', 'logout', 'setLocale', 'emitEvent', 'apiCall',
// C24~C27 제어흐름(C23 top-level if 는 엔진 처리 — 카탈로그 비포함) + C29 conditions
'conditions', 'sequence', 'parallel', 'switch', 'suppress',
// 결제 진입(requestPgPayment)은 코어 카탈로그에서 제외됨 — 결제는 커머스 도메인이라
@@ -58,6 +58,8 @@ const GROUP_OF: Record<string, string> = {
apiCall: 'data',
scrollIntoView: 'etc',
login: 'etc',
loginTwoFactor: 'etc',
loginTwoFactorResend: 'etc',
logout: 'etc',
setLocale: 'locale',
emitEvent: 'etc',
@@ -285,6 +285,18 @@ export const CORE_ACTION_RECIPES: Record<string, ActionRecipeSpec> = {
params: [{ key: 'body', label: `$t:${L}.login.param_body`, widget: 'key-value' }],
build: { handler: 'login', params: { body: '{{body}}' } },
},
// C18-1 2단계 인증 코드 확인 (로그인 완료)
loginTwoFactor: {
label: `$t:${L}.login_two_factor.label`,
params: [{ key: 'body', label: `$t:${L}.login_two_factor.param_body`, widget: 'key-value' }],
build: { handler: 'loginTwoFactor', params: { body: '{{body}}' } },
},
// C18-2 2단계 인증 코드 재발송
loginTwoFactorResend: {
label: `$t:${L}.login_two_factor_resend.label`,
params: [{ key: 'body', label: `$t:${L}.login_two_factor_resend.param_body`, widget: 'key-value' }],
build: { handler: 'loginTwoFactorResend', params: { body: '{{body}}' } },
},
// C19 로그아웃 처리
logout: {
label: `$t:${L}.logout.label`,
@@ -59,13 +59,22 @@ export function isAbortError(error: unknown): boolean {
* fetch 스펙상 네트워크 오류는 TypeError 로 reject 된다. 취소(AbortError)는
* 호출부의 의도이므로 재시도 대상이 아니다.
*
* axios 경로(로그인 등 ApiClient 를 쓰는 요청)는 TypeError 가 아니라 `AxiosError` 로
* reject 되며 종류는 `code` 에만 남는다. TypeError 만 보면 그 경로의 네트워크 실패가
* 판정에서 빠져 영문 원문(`Network Error`)이 그대로 화면에 노출된다.
*
* @param error 검사할 에러
* @return bool 재시도할 가치가 있는 네트워크 실패이면 true
* @since engine-v1.53.0
* @since engine-v1.65.0 axios 네트워크 오류 코드(ERR_NETWORK/ECONNABORTED) 인식
*/
export function isNetworkFailure(error: unknown): boolean {
if (isAbortError(error)) return false;
return error instanceof TypeError;
if (error instanceof TypeError) return true;
const code = (error as { code?: string } | null)?.code;
return code === 'ERR_NETWORK' || code === 'ECONNABORTED';
}
let unloading = false;