앱 로그인: 늦게 도착한 이전 확인 응답이 잠금을 풀지 못하게

- 확인 요청마다 세대 번호를 붙이고, 새 확인 · 잠금(등록 해제) · 로그아웃 · 새 로그인 뒤에 도착한
  이전 응답(성공 · 실패 모두)은 버린다. 보낸 토큰과 지금 토큰이 다르면 역시 버린다
- 로그아웃은 서버 응답을 기다리기 전에 로컬에서 먼저 지우고 잠근다
- 회귀 테스트: 등록 해제 뒤 / 로그아웃 뒤 늦은 200 (이전 코드에서 둘 다 실패 확인)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 08:23:48 +09:00
parent c2a5547a68
commit a2487e6241
2 changed files with 94 additions and 2 deletions

View File

@@ -42,6 +42,11 @@ class HttpError extends Error {
export class AppAuth extends EventEmitter {
state: AuthState = { status: 'checking', user: null, role: null, offline: false, error: null, loginUrl: null, verifiedAt: null };
private loginSeq = 0;
/**
* 인증 세대. 확인을 새로 시작하거나 토큰을 지우거나(등록 해제 · 로그아웃) 새로 받으면(로그인) 올라간다.
* 늦게 도착한 이전 확인 응답(성공 · 실패 모두)은 버린다 — 잠근 뒤 옛 200 이 앱을 다시 여는 일을 막는다
*/
private gen = 0;
constructor(
private settings: SettingsStore,
@@ -86,6 +91,7 @@ export class AppAuth extends EventEmitter {
/** 로그인 정보 · 겜녹이 봇 토큰을 지운다 (등록 해제 · 로그아웃) */
private forget(): void {
this.gen++;
for (const k of ['appToken', 'builtinBotToken', 'auth'] as const) if (this.settings.hasSecret(k)) this.settings.setSecret(k, null);
}
@@ -93,17 +99,22 @@ export class AppAuth extends EventEmitter {
async check(): Promise<AuthState> {
if (this.state.status === 'waiting') return this.state;
const token = this.settings.getSecret('appToken');
const gen = ++this.gen;
if (!token) {
this.set({ status: 'signed_out', user: null, role: null, offline: false, error: null, verifiedAt: null });
return this.state;
}
// 응답을 기다리는 사이 다른 확인 · 로그아웃 · 잠금 · 새 로그인이 있었으면 이 응답은 버린다
const stale = () => gen !== this.gen || this.settings.getSecret('appToken') !== token;
try {
const me = await this.call<AppMe>('GET', '/app/me');
const me = await this.call<AppMe>('GET', '/app/me', undefined, token);
if (stale()) return this.state;
const cache = { user: me.user, role: me.role, verifiedAt: Date.now() };
this.settings.setSecret('auth', cache);
if (me.botToken !== (this.settings.getSecret('builtinBotToken') ?? null)) this.settings.setSecret('builtinBotToken', me.botToken);
this.set({ status: 'ok', user: me.user, role: me.role, offline: false, error: null, loginUrl: null, verifiedAt: cache.verifiedAt });
} catch (e: any) {
if (stale()) return this.state;
if (e instanceof HttpError && (e.status === 401 || e.status === 403)) {
const notReg = e.status === 403 && e.body?.error === 'not_registered';
log.warn(notReg ? '등록이 해제된 아이디라 잠급니다' : '로그인이 만료되어 잠급니다');
@@ -130,6 +141,7 @@ export class AppAuth extends EventEmitter {
/** 브라우저로 디스코드 로그인. 끝나거나 취소될 때까지 기다린다 */
async login(): Promise<AuthState> {
const seq = ++this.loginSeq;
this.gen++; // 진행 중이던 확인 응답은 버린다
let b: AppLoginBegin;
try {
b = await this.call<AppLoginBegin>('POST', '/auth/app/begin', {}, undefined);
@@ -152,6 +164,7 @@ export class AppAuth extends EventEmitter {
if (seq !== this.loginSeq) break;
if (r.state === 'pending') continue;
if (r.state === 'ok') {
this.gen++;
this.settings.setSecret('appToken', r.token);
this.state = { ...this.state, status: 'checking', loginUrl: null };
log.info(`로그인: ${r.user.name} (${r.role})`);
@@ -177,9 +190,10 @@ export class AppAuth extends EventEmitter {
async logout(): Promise<void> {
this.loginSeq++;
const token = this.settings.getSecret('appToken');
if (token) await this.call('POST', '/auth/app/logout', {}).catch(() => undefined);
// 먼저 로컬에서 지우고 잠근다 (서버 응답을 기다리는 사이 도착한 확인 응답이 다시 열지 못하게)
this.forget();
this.set({ status: 'signed_out', user: null, role: null, offline: false, error: null, loginUrl: null, verifiedAt: null });
if (token) await this.call('POST', '/auth/app/logout', {}, token).catch(() => undefined);
}
// ---- 관리자 화면 (서버가 역할을 다시 확인한다)

View File

@@ -154,3 +154,81 @@ test('관리자 전용 설정: 일반 유저가 바꾸면 안 되는 경로만
assert.deepEqual(adminOnlyPaths({ finetune: { schedule: 'nightly' } }), ['finetune']);
assert.deepEqual(adminOnlyPaths({ firstRunDone: true, general: { sfx: false } }), []);
});
/** /app/me 응답을 서버가 처리한 뒤 앱에 늦게 도착하게 붙잡는다 (hold() 로 다음 요청 하나를 잡고, 반환값으로 놓아준다) */
function holdMe() {
const real = globalThis.fetch;
let gate: { promise: Promise<void>; release: () => void } | null = null;
globalThis.fetch = (async (input: any, init?: any) => {
const r = await real(input, init);
if (gate && String(input).endsWith('/app/me')) {
const g = gate;
gate = null;
await g.promise;
}
return r;
}) as typeof fetch;
return {
hold: () => {
let release!: () => void;
const promise = new Promise<void>((r) => (release = r));
gate = { promise, release };
return release;
},
restore: () => (globalThis.fetch = real),
};
}
test('늦은 확인 응답: 등록 해제로 잠긴 뒤 이전 확인의 200 이 와도 다시 열리지 않는다', async () => {
const s = await stack();
const h = holdMe();
try {
const admin = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(SUPER), pollMs: 20 });
await admin.login();
await admin.adminAddUser(FRIEND, 'user');
const st = s.settingsFor();
const fr = new AppAuth(st, { version: 't', openUrl: s.browser(FRIEND), pollMs: 20 });
assert.equal((await fr.login()).status, 'ok');
// A: 서버는 200 을 줬지만 응답이 늦게 온다
const release = h.hold();
const a = fr.check();
await new Promise((r) => setTimeout(r, 100));
// 그 사이 등록 해제 → B: 403 → 잠김
await admin.adminRemoveUser(FRIEND);
assert.equal((await fr.check()).status, 'not_registered');
assert.equal(st.activeBotToken(), null);
// A 의 늦은 200 도착
release();
await a;
assert.equal(fr.state.status, 'not_registered', '늦은 200 이 잠금을 풀면 안 된다');
assert.equal(st.activeBotToken(), null, '지운 봇 토큰이 되살아나면 안 된다');
assert.equal(st.hasSecret('appToken'), false);
} finally {
h.restore();
await s.close();
}
});
test('늦은 확인 응답: 로그아웃 뒤 이전 확인의 200 이 와도 다시 열리지 않는다', async () => {
const s = await stack();
const h = holdMe();
try {
const st = s.settingsFor();
const auth = new AppAuth(st, { version: 't', openUrl: s.browser(SUPER), pollMs: 20 });
assert.equal((await auth.login()).status, 'ok');
const release = h.hold();
const a = auth.check();
await new Promise((r) => setTimeout(r, 100));
await auth.logout();
assert.equal(auth.state.status, 'signed_out');
release();
await a;
assert.equal(auth.state.status, 'signed_out', '늦은 200 이 로그아웃을 되돌리면 안 된다');
assert.equal(st.activeBotToken(), null);
assert.equal(st.hasSecret('auth'), false);
} finally {
h.restore();
await s.close();
}
});