consent-recorder: fix review findings

- /delete discards the in-progress utterance before deleting files
- keep the current channel even when the bot itself fills it (joinable=false)
- bind OAuth state to the browser via a short-lived cookie
- reject consent submitted from a page showing an older consent version
- regression tests for all four

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-11 11:47:07 +09:00
parent 6e0801ea1c
commit 8da3e713d0
7 changed files with 122 additions and 17 deletions

View File

@@ -0,0 +1,32 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { ChannelType } from 'discord.js';
import { FollowBot } from '../src/bot.ts';
import { loadConfig } from '../src/config.ts';
import { Store } from '../src/db.ts';
/** 정원이 찬 채널 A(봇이 들어가 있음, joinable=false)와 같은 상태의 채널 B */
function fakeGuild() {
const guild: any = { id: 'g', members: { me: {} }, voiceStates: { cache: new Map() } };
const channel = (id: string) => ({ id, guild, type: ChannelType.GuildVoice, joinable: false, permissionsFor: () => ({ has: () => true }) });
const A = channel('A');
const B = channel('B');
guild.voiceStates.cache.set('u1', { id: 'u1', channelId: 'A', channel: A, member: { user: { bot: false } } });
guild.voiceStates.cache.set('u2', { id: 'u2', channelId: 'B', channel: B, member: { user: { bot: false } } });
return guild;
}
test('봇이 들어가 정원이 찬 지금 채널의 동의자는 그대로 따라간다 (나갔다 들어오기 반복 X)', async () => {
const store = new Store(':memory:');
store.consent({ id: 'u1', username: 'a' });
store.consent({ id: 'u2', username: 'b' });
const cfg = loadConfig({ PUBLIC_URL: 'http://localhost', DISCORD_CLIENT_ID: 'c', DISCORD_CLIENT_SECRET: 's' }, false);
const bot = new FollowBot(cfg, store);
const guild = fakeGuild();
assert.deepEqual(bot.consentedPresence(guild), []); // 들어가 있지 않으면 꽉 찬 채널은 못 들어감
(bot as any).recorders.set('g', { channelId: 'A' });
assert.deepEqual(bot.consentedPresence(guild), [{ userId: 'u1', channelId: 'A' }]); // 지금 채널 A 는 유지, 꽉 찬 B 는 제외
(bot as any).recorders.clear();
await bot.client.destroy();
store.close();
});

View File

@@ -5,6 +5,7 @@ import os from 'node:os';
import path from 'node:path';
import { after, before, test } from 'node:test';
import { loadConfig } from '../src/config.ts';
import { CONSENT_VERSION } from '../src/consent-text.ts';
import { Store } from '../src/db.ts';
import { pickChannel } from '../src/follow.ts';
import { createSite } from '../src/site.ts';
@@ -16,6 +17,7 @@ let store: Store;
let base = '';
let tmp = '';
const changed: string[] = [];
const events: string[] = [];
before(async () => {
tmp = fs.mkdtempSync(path.join(os.homedir(), '.tmp-consent-'));
@@ -47,7 +49,11 @@ before(async () => {
{ PUBLIC_URL: base, DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec', DATA_DIR: tmp, OPERATOR_NAME: '승한', DISCORD_API: `http://127.0.0.1:${dport}` },
false,
);
site = createSite(cfg, store, { consentChanged: (id) => changed.push(id), recordingNow: () => null });
site = createSite(cfg, store, {
consentChanged: (id) => changed.push(id),
discardActive: (id) => events.push(`discard:${id}:${store.recordingStats(id).count}`),
recordingNow: () => null,
});
await new Promise<void>((r) => site.listen(port, '127.0.0.1', r));
});
@@ -70,11 +76,17 @@ async function login(): Promise<{ cookie: string; csrf: string }> {
assert.equal(auth.searchParams.get('scope'), 'identify');
assert.equal(auth.searchParams.get('redirect_uri'), `${base}/callback`);
const state = auth.searchParams.get('state')!;
const cb = await get(`/callback?code=good-code&state=${state}`);
const stateCookie = l.headers.get('set-cookie')!.split(';')[0];
assert.equal(stateCookie, `oauth_state=${state}`);
// 로그인을 시작하지 않은 브라우저(state 쿠키 없음 · 다른 값)에서 연 callback 은 거절 (state 는 그대로 남음)
assert.equal((await get(`/callback?code=good-code&state=${state}`)).status, 400);
assert.equal((await get(`/callback?code=good-code&state=${state}`, 'oauth_state=other')).status, 400);
const cb = await get(`/callback?code=good-code&state=${state}`, stateCookie);
assert.equal(cb.status, 303);
const cookie = cb.headers.get('set-cookie')!.split(';')[0];
assert.match(cookie, /^sid=/);
// state 는 한 번만 쓸 수 있다
assert.equal((await get(`/callback?code=good-code&state=${state}`)).status, 400);
assert.equal((await get(`/callback?code=good-code&state=${state}`, stateCookie)).status, 400);
const home = await (await get('/', cookie)).text();
assert.match(home, /하늘님/);
const csrf = /name="csrf" value="([^"]+)"/.exec(home)![1];
@@ -100,7 +112,13 @@ test('디스코드 로그인 → 모든 항목 체크해야 동의 → 철회하
assert.equal((await post('/consent', cookie, { csrf, self: '1', model: '1' })).status, 400);
assert.equal(store.isConsented(USER.id), false);
assert.equal((await post('/consent', cookie, { csrf, self: '1', model: '1', age: '1' })).status, 303);
// 예전 문구 화면에서 낸 동의(버전 없음 · 다른 버전)는 거절
assert.equal((await post('/consent', cookie, { csrf, self: '1', model: '1', age: '1' })).status, 409);
assert.equal((await post('/consent', cookie, { csrf, version: 'old', self: '1', model: '1', age: '1' })).status, 409);
assert.equal(store.isConsented(USER.id), false);
const version = /name="version" value="([^"]+)"/.exec(await (await get('/', cookie)).text())![1];
assert.equal(version, CONSENT_VERSION);
assert.equal((await post('/consent', cookie, { csrf, version, self: '1', model: '1', age: '1' })).status, 303);
assert.equal(store.isConsented(USER.id), true);
assert.deepEqual(changed, [USER.id]);
assert.match(await (await get('/', cookie)).text(), /녹음 동의함/);
@@ -111,11 +129,17 @@ test('디스코드 로그인 → 모든 항목 체크해야 동의 → 철회하
fs.writeFileSync(f, 'x');
store.addRecording({ id: 'a', user_id: USER.id, guild_id: 'g', channel_id: 'c', started_at: 1, duration_ms: 1500, path: f });
assert.match(await (await get('/', cookie)).text(), /1개 · 2초/);
// 파일 삭제: 진행 중인 녹음을 먼저 버린 뒤(그때는 아직 1개) 저장 파일을 지운다
assert.equal((await post('/delete', cookie, { csrf })).status, 303);
assert.deepEqual(events, [`discard:${USER.id}:1`]);
assert.equal(fs.existsSync(f), false);
fs.writeFileSync(f, 'x');
store.addRecording({ id: 'b', user_id: USER.id, guild_id: 'g', channel_id: 'c', started_at: 1, duration_ms: 1500, path: f });
assert.equal((await post('/revoke', cookie, { csrf, delete: '1' })).status, 303);
assert.equal(store.isConsented(USER.id), false);
assert.equal(fs.existsSync(f), false);
assert.equal(store.recordingStats(USER.id).count, 0);
assert.deepEqual(store.consentLog(USER.id).map((l) => l.action), ['consent', 'revoke', 'delete_recordings']);
assert.deepEqual(store.consentLog(USER.id).map((l) => l.action), ['consent', 'delete_recordings', 'revoke', 'delete_recordings']);
// 로그아웃하면 세션 끝
assert.equal((await post('/logout', cookie, { csrf })).status, 303);

View File

@@ -62,3 +62,28 @@ test('동의한 사람만 구독해서 저장하고, 철회하면 쓰던 파일
store.close();
fs.rmSync(tmp, { recursive: true, force: true });
});
test('파일 삭제 직전 진행 중인 녹음을 버리면 삭제 뒤에 남지 않는다', async () => {
const tmp = fs.mkdtempSync(path.join(os.homedir(), '.tmp-rec-'));
const store = new Store(':memory:');
store.consent({ id: 'yes', username: 'y' });
const conn = fakeConnection();
const rec = new Recorder(store, tmp, conn, 'g', 'c', (uid) => store.isConsented(uid));
conn.receiver.speaking.emit('start', 'yes');
const s = conn.receiver.subscriptions.get('yes')!;
for (let i = 0; i < 30; i++) s.write(OPUS_20MS); // 600ms, 아직 진행 중
await new Promise((r) => setImmediate(r));
rec.stopUser('yes'); // 사이트 /delete → discardActive
store.deleteRecordings('yes');
s.end();
await new Promise((r) => setImmediate(r));
assert.equal(store.recordings('yes').length, 0);
const left = fs.readdirSync(tmp, { recursive: true }).filter((f) => String(f).endsWith('.ogg'));
assert.deepEqual(left, []);
// 동의는 그대로라 다시 말하면 새로 녹음한다
conn.receiver.speaking.emit('start', 'yes');
assert.equal(conn.receiver.subscriptions.has('yes'), true);
rec.close();
store.close();
fs.rmSync(tmp, { recursive: true, force: true });
});