diff --git a/consent-recorder/README.md b/consent-recorder/README.md index ad0e5a6..086400b 100644 --- a/consent-recorder/README.md +++ b/consent-recorder/README.md @@ -13,7 +13,7 @@ 말이 0.8초 끊길 때마다 파일 하나(최대 30초, 0.5초 미만 버림), Opus 그대로 `data/recordings/<아이디>/<날짜>/.ogg`. 말하는 도중 철회하면 쓰던 파일도 버린다. - 알림: 봇이 채널에 들어가면 그 채널 채팅에 녹음 안내(누구 목소리만 녹음하는지 + 사이트 주소)를 남기고, 봇 상태를 "🔴 동의한 사람 녹음 중"으로 바꾼다. - 동의 기록: `consent_log` 테이블에 동의 · 철회 · 삭제 · 내보내기를 시각과 문구 버전으로 남긴다. 동의 문구를 바꾸면 `src/consent-text.ts` 의 `CONSENT_VERSION` 을 올린다 → 예전 동의자는 다시 동의할 때까지 녹음하지 않는다. -- 보안: 세션 · OAuth state 는 해시로만 저장, 디스코드 액세스 토큰은 저장하지 않음, 모든 form 에 CSRF 토큰 + Origin 확인, 클릭재킹 차단(`frame-ancestors 'none'`, `X-Frame-Options: DENY`), https 쿠키는 `__Host-` + Secure. +- 보안: OAuth state 는 로그인을 시작한 브라우저 쿠키와 맞춰 확인, 동의 제출은 화면의 문구 버전이 지금 버전과 같을 때만, 세션 · state 는 해시로만 저장, 디스코드 액세스 토큰은 저장하지 않음, 모든 form 에 CSRF 토큰 + Origin 확인, 클릭재킹 차단(`frame-ancestors 'none'`, `X-Frame-Options: DENY`), https 쿠키는 `__Host-` + Secure. - 디스코드 음성 종단간 암호화(DAVE)는 `@discordjs/voice` 0.19 + `@snazzah/davey` 로 지원. ## 준비 (디스코드 개발자 포털) @@ -47,5 +47,5 @@ npm run cli -- export <디스코드 아이디> ./dataset # 48kHz 모노 wav, -18 ## 테스트 ```bash -npm test # 가짜 디스코드 OAuth 서버로 로그인 → 동의 → 철회/삭제, CSRF · 클릭재킹, 채널 고르기, 동의자만 녹음 +npm test # 가짜 디스코드 OAuth 서버로 로그인(state 쿠키) → 동의(문구 버전) → 철회/삭제, CSRF · 클릭재킹, 채널 고르기 · 정원 찬 채널 유지, 동의자만 녹음 · 삭제 시 진행 중 녹음 폐기 ``` diff --git a/consent-recorder/src/bot.ts b/consent-recorder/src/bot.ts index d5e8d76..ab365b3 100644 --- a/consent-recorder/src/bot.ts +++ b/consent-recorder/src/bot.ts @@ -61,6 +61,11 @@ export class FollowBot { } } + /** 이 사람의 진행 중인 녹음을 버린다 (구독도 끊음. 다시 말하면 동의 상태대로 새로 녹음) */ + discardActive(userId: string): void { + for (const r of this.recorders.values()) r.stopUser(userId); + } + /** 이 사람을 지금 녹음 중인 채널 이름 */ recordingNow(userId: string): string | null { for (const [gid, r] of this.recorders) { @@ -87,13 +92,18 @@ export class FollowBot { return !!p?.has(PermissionFlagsBits.ViewChannel) && p.has(PermissionFlagsBits.Connect) && ch.joinable; } - private consentedPresence(guild: Guild): Presence[] { + /** + * 동의자가 있는 채널 목록. 봇이 이미 들어가 있는 채널은 입장 가능 여부를 다시 보지 않는다 + * (봇이 들어가 정원이 차면 joinable 이 false 가 되어 나갔다 들어오기를 반복하던 것) + */ + consentedPresence(guild: Guild): Presence[] { + const current = this.recorders.get(guild.id)?.channelId ?? null; const out: Presence[] = []; for (const vs of guild.voiceStates.cache.values()) { if (!vs.channelId || vs.id === this.client.user?.id || vs.member?.user.bot) continue; if (!this.store.isConsented(vs.id)) continue; const ch = vs.channel; - if (ch && this.canJoin(ch)) out.push({ userId: vs.id, channelId: vs.channelId }); + if (ch && (ch.id === current || this.canJoin(ch))) out.push({ userId: vs.id, channelId: vs.channelId }); } return out; } diff --git a/consent-recorder/src/main.ts b/consent-recorder/src/main.ts index 57ad94f..8055574 100644 --- a/consent-recorder/src/main.ts +++ b/consent-recorder/src/main.ts @@ -10,6 +10,7 @@ const store = new Store(path.join(cfg.dataDir, 'consent.db')); const bot = new FollowBot(cfg, store); const site = createSite(cfg, store, { consentChanged: (id) => bot.consentChanged(id), + discardActive: (id) => bot.discardActive(id), recordingNow: (id) => bot.recordingNow(id), }); diff --git a/consent-recorder/src/site.ts b/consent-recorder/src/site.ts index 694a4ca..b97ae1c 100644 --- a/consent-recorder/src/site.ts +++ b/consent-recorder/src/site.ts @@ -1,3 +1,4 @@ +import crypto from 'node:crypto'; import http from 'node:http'; import type { Config } from './config.js'; import { CONSENT_CHECKS, CONSENT_VERSION, consentItems } from './consent-text.js'; @@ -6,6 +7,8 @@ import type { DiscordUser, SessionRow, Store } from './db.js'; export interface SiteHooks { /** 동의 · 철회 직후. 봇이 바로 따라 들어가거나 녹음을 멈춘다 */ consentChanged(userId: string): void; + /** 이 사람의 진행 중인 녹음을 저장하지 않고 버린다 (파일 삭제 직전) */ + discardActive(userId: string): void; /** 이 사람이 지금 녹음되고 있는 채널 이름 (없으면 null) */ recordingNow(userId: string): string | null; } @@ -76,8 +79,10 @@ export function createSite(cfg: Config, store: Store, hooks: SiteHooks): http.Se const secure = cfg.publicUrl.startsWith('https://'); const redirectUri = `${cfg.publicUrl}/callback`; const cookieName = secure ? '__Host-sid' : 'sid'; - const setSid = (sid: string, maxAge: number) => - `${cookieName}=${sid}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? '; Secure' : ''}`; + const stateCookie = secure ? '__Host-oauth_state' : 'oauth_state'; + const cookie = (name: string, value: string, maxAge: number) => + `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? '; Secure' : ''}`; + const setSid = (sid: string, maxAge: number) => cookie(cookieName, sid, maxAge); const send = (res: http.ServerResponse, status: number, body: string, type = 'text/html; charset=utf-8', extra: Record = {}) => { res.writeHead(status, { @@ -147,7 +152,7 @@ ${error ? `

${esc(error)}

` : ''} ` : `

녹음 동의

    ${consentItems(esc(cfg.operatorName)).map((t) => `
  • ${t}
  • `).join('')}
-
${csrf} +${csrf} ${Object.entries(CONSENT_CHECKS).map(([k, t]) => ``).join('')}
`; return page( @@ -191,23 +196,30 @@ ${consentForm} return send(res, 200, cur ? home(cur.s) : landing()); } case 'GET /login': { - const q = new URLSearchParams({ client_id: cfg.clientId, response_type: 'code', redirect_uri: redirectUri, scope: 'identify', state: store.newState() }); - return redirect(res, `${cfg.discordAuthorizeUrl}?${q}`); + // state 를 이 브라우저 쿠키에도 넣어 둔다: 남이 받은 callback 주소를 열어도 그 사람 계정으로 로그인되지 않게 + const state = store.newState(); + const q = new URLSearchParams({ client_id: cfg.clientId, response_type: 'code', redirect_uri: redirectUri, scope: 'identify', state }); + return redirect(res, `${cfg.discordAuthorizeUrl}?${q}`, { 'Set-Cookie': cookie(stateCookie, state, 600) }); } case 'GET /callback': { const state = url.searchParams.get('state') ?? ''; const code = url.searchParams.get('code') ?? ''; - if (url.searchParams.get('error')) return send(res, 400, landing('디스코드 로그인을 취소했습니다.')); - if (!state || !store.takeState(state)) return send(res, 400, landing('로그인 요청이 만료되었습니다. 다시 로그인해 주세요.')); + const clear = { 'Set-Cookie': cookie(stateCookie, '', 0) }; + if (url.searchParams.get('error')) return send(res, 400, landing('디스코드 로그인을 취소했습니다.'), undefined, clear); + const mine = cookies(req)[stateCookie] ?? ''; + const sameBrowser = mine.length === state.length && state.length > 0 && crypto.timingSafeEqual(Buffer.from(mine), Buffer.from(state)); + if (!sameBrowser || !store.takeState(state)) return send(res, 400, landing('로그인 요청이 만료되었습니다. 다시 로그인해 주세요.'), undefined, clear); if (!code) return send(res, 400, landing('디스코드 로그인 실패 (code 없음)')); const user = await oauthUser(code); const sid = store.newSession(user); - return redirect(res, '/', { 'Set-Cookie': setSid(sid, 7 * 24 * 3600) }); + return redirect(res, '/', { 'Set-Cookie': [setSid(sid, 7 * 24 * 3600), cookie(stateCookie, '', 0)] }); } case 'POST /consent': { const { s, form } = await authedForm(req); const missing = Object.keys(CONSENT_CHECKS).filter((k) => form.get(k) !== '1'); if (missing.length) return send(res, 400, home(s, '모든 항목에 직접 체크해야 동의할 수 있습니다.')); + // 예전 문구를 띄워 둔 화면에서 낸 동의는 받지 않는다 + if (form.get('version') !== CONSENT_VERSION) return send(res, 409, home(s, '동의 문구가 바뀌었습니다. 바뀐 내용을 읽고 다시 동의해 주세요.')); store.consent({ id: s.user_id, username: s.username, global_name: s.display_name }); hooks.consentChanged(s.user_id); return redirect(res, '/'); @@ -221,6 +233,7 @@ ${consentForm} } case 'POST /delete': { const { s } = await authedForm(req); + hooks.discardActive(s.user_id); // 지금 녹음 중인 파일도 저장하지 않고 버린 뒤 지운다 store.deleteRecordings(s.user_id); return redirect(res, '/'); } diff --git a/consent-recorder/test/bot.test.ts b/consent-recorder/test/bot.test.ts new file mode 100644 index 0000000..c578d4c --- /dev/null +++ b/consent-recorder/test/bot.test.ts @@ -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(); +}); diff --git a/consent-recorder/test/consent.test.ts b/consent-recorder/test/consent.test.ts index a11cd20..baf85f7 100644 --- a/consent-recorder/test/consent.test.ts +++ b/consent-recorder/test/consent.test.ts @@ -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((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); diff --git a/consent-recorder/test/recorder.test.ts b/consent-recorder/test/recorder.test.ts index 648fa36..cb19358 100644 --- a/consent-recorder/test/recorder.test.ts +++ b/consent-recorder/test/recorder.test.ts @@ -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 }); +});