Files
voice_copy/consent-recorder/test/consent.test.ts
EJClaw 32ad429773 Pick recording servers from the voice-changer app; fix per-server recording status
consent-recorder: operators (ADMIN_DISCORD_IDS) create an app key on the
site; the app calls GET/POST /api/guilds with it to turn servers on/off.
Turned-off servers are left immediately. recordingNow() now checks the
user picked that server, so someone who only chose server A is not shown
as recorded while sitting in a B channel the bot records for others.

voice-changer: new "녹음 서버" dialog (record_servers.py), network in a
worker thread, key saved in config/record-servers.json; upgrade cleanup
list knows the new file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:16:53 +09:00

242 lines
12 KiB
TypeScript

import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
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';
const USER = { id: '123456789012345678', username: 'haneul', global_name: '하늘' };
let discord: http.Server;
let site: http.Server;
let store: Store;
let base = '';
let tmp = '';
const changed: string[] = [];
const events: string[] = [];
const guildOn: Record<string, boolean> = {};
let settingsChanged = 0;
before(async () => {
tmp = fs.mkdtempSync(path.join(os.homedir(), '.tmp-consent-'));
// 가짜 디스코드 OAuth API
discord = http.createServer((req, res) => {
let body = '';
req.on('data', (c) => (body += c));
req.on('end', () => {
if (req.url === '/oauth2/token' && req.method === 'POST') {
const f = new URLSearchParams(body);
if (f.get('code') !== 'good-code' || f.get('client_secret') !== 'sec') return res.writeHead(400).end('{}');
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ access_token: 'at' }));
}
if (req.url === '/users/@me' && req.headers.authorization === 'Bearer at') {
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(USER));
}
res.writeHead(404).end();
});
});
await new Promise<void>((r) => discord.listen(0, '127.0.0.1', r));
const dport = (discord.address() as any).port;
store = new Store(path.join(tmp, 'consent.db'));
site = http.createServer();
await new Promise<void>((r) => site.listen(0, '127.0.0.1', r));
const port = (site.address() as any).port;
site.close();
base = `http://127.0.0.1:${port}`;
const cfg = loadConfig(
{ PUBLIC_URL: base, DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec', DATA_DIR: tmp, OPERATOR_NAME: '승한', ADMIN_DISCORD_IDS: USER.id, DISCORD_API: `http://127.0.0.1:${dport}` },
false,
);
site = createSite(cfg, store, {
consentChanged: (id) => changed.push(id),
discardActive: (id) => events.push(`discard:${id}:${store.recordingStats(id).count}`),
recordingNow: () => null,
userGuilds: async () => [
{ id: 'g1', name: '첫째 서버' },
{ id: 'g2', name: '둘째 서버' },
],
adminGuilds: () => ['g1', 'g2'].map((id) => ({ id, name: id, enabled: store.guildEnabled(id) })),
guildSettingsChanged: () => settingsChanged++,
});
await new Promise<void>((r) => site.listen(port, '127.0.0.1', r));
});
after(() => {
site.close();
discord.close();
store.close();
fs.rmSync(tmp, { recursive: true, force: true });
});
const get = (p: string, cookie = '') => fetch(base + p, { redirect: 'manual', headers: cookie ? { cookie } : {} });
const post = (p: string, cookie: string, form: Record<string, string> | string[][]) =>
fetch(base + p, { method: 'POST', redirect: 'manual', headers: { cookie, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form) });
async function login(): Promise<{ cookie: string; csrf: string }> {
const l = await get('/login');
assert.equal(l.status, 303);
const auth = new URL(l.headers.get('location')!);
assert.equal(auth.origin + auth.pathname, 'https://discord.com/oauth2/authorize');
assert.equal(auth.searchParams.get('scope'), 'identify');
assert.equal(auth.searchParams.get('redirect_uri'), `${base}/callback`);
const state = auth.searchParams.get('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}`, stateCookie)).status, 400);
const home = await (await get('/', cookie)).text();
assert.match(home, /하늘님/);
const csrf = /name="csrf" value="([^"]+)"/.exec(home)![1];
return { cookie, csrf };
}
test('디스코드 로그인 → 모든 항목 체크해야 동의 → 철회하면 녹음 파일 삭제', async () => {
assert.equal((await get('/callback?code=good-code&state=forged')).status, 400);
const { cookie, csrf } = await login();
assert.equal(store.isConsented(USER.id), false);
// CSRF 없거나 틀리면 거절
assert.equal((await post('/consent', cookie, { self: '1', model: '1', age: '1' })).status, 403);
assert.equal((await post('/consent', cookie, { csrf: 'x', self: '1', model: '1', age: '1' })).status, 403);
// 다른 사이트에서 보낸 요청 거절
const cross = await fetch(base + '/consent', {
method: 'POST', redirect: 'manual',
headers: { cookie, origin: 'https://evil.example', 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ csrf, self: '1', model: '1', age: '1' }),
});
assert.equal(cross.status, 403);
// 항목 하나라도 빠지면 거절
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, 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 page0 = await (await get('/', cookie)).text();
const version = /name="version" value="([^"]+)"/.exec(page0)![1];
assert.equal(version, CONSENT_VERSION);
// 봇과 함께 있는 서버만 고를 수 있고, 하나 이상 골라야 동의된다
assert.match(page0, /name="guild" value="g1"[^>]*><span>첫째 서버/);
const ok = { csrf, version, self: '1', model: '1', age: '1' };
assert.equal((await post('/consent', cookie, ok)).status, 400);
assert.equal((await post('/consent', cookie, { ...ok, guild: 'other' })).status, 400);
assert.equal(store.isConsented(USER.id), false);
assert.equal((await post('/consent', cookie, [...Object.entries(ok), ['guild', 'g1'], ['guild', 'g2']])).status, 303);
assert.equal(store.isConsented(USER.id), true);
assert.deepEqual(store.consentGuilds(USER.id), ['g1', 'g2']);
assert.deepEqual(changed, [USER.id]);
assert.match(await (await get('/', cookie)).text(), /녹음 동의함[\s\S]*녹음할 서버: <b>첫째 서버, 둘째 서버/);
// 녹음할 서버 바꾸기: 뺀 서버는 녹음하지 않는다. 다 빼면 어디서도 녹음하지 않음
assert.equal((await post('/guilds', cookie, { csrf, guild: 'other' })).status, 400);
assert.equal((await post('/guilds', cookie, { csrf, guild: 'g2' })).status, 303);
assert.deepEqual(changed, [USER.id, USER.id]);
assert.equal(store.isConsentedIn(USER.id, 'g1'), false);
assert.equal(store.isConsentedIn(USER.id, 'g2'), true);
assert.equal((await post('/guilds', cookie, { csrf })).status, 303);
assert.equal(store.isConsentedIn(USER.id, 'g2'), false);
assert.match(await (await get('/', cookie)).text(), /녹음할 서버: <b>없음/);
assert.equal((await post('/guilds', cookie, { csrf, guild: 'g1' })).status, 303);
// 녹음 파일 하나 있다고 치고 철회 + 삭제
const f = path.join(tmp, 'recordings', USER.id, 'a.ogg');
fs.mkdirSync(path.dirname(f), { recursive: true });
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), ['guilds', 'consent', 'guilds', 'guilds', 'guilds', 'delete_recordings', 'revoke', 'delete_recordings']);
// 철회한 뒤에는 서버를 바꿀 수 없다
assert.equal((await post('/guilds', cookie, { csrf, guild: 'g1' })).status, 400);
// 로그아웃하면 세션 끝
assert.equal((await post('/logout', cookie, { csrf })).status, 303);
assert.doesNotMatch(await (await get('/', cookie)).text(), /하늘님/);
});
test('운영자는 앱 연결 키를 만들어 앱에서 녹음할 서버를 켜고 끈다', async () => {
const { cookie, csrf } = await login();
assert.match(await (await get('/', cookie)).text(), /음성 변환기 앱 연결/);
assert.equal((await post('/app-key', cookie, {})).status, 403); // CSRF
const page = await (await post('/app-key', cookie, { csrf })).text();
const key = /<code class="key">([^<]+)<\/code>/.exec(page)![1];
const api = (method: string, k: string, body?: unknown) =>
fetch(base + '/api/guilds', { method, headers: { authorization: `Bearer ${k}`, 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
assert.equal((await fetch(base + '/api/guilds')).status, 401);
assert.equal((await api('GET', 'vc_wrong')).status, 401);
const list = await (await api('GET', key)).json();
assert.deepEqual(list.guilds.map((g: any) => [g.id, g.enabled]), [['g1', true], ['g2', true]]);
const r = await api('POST', key, { enabled: ['g1'] });
assert.equal(r.status, 200);
assert.deepEqual((await r.json()).guilds.map((g: any) => [g.id, g.enabled]), [['g1', true], ['g2', false]]);
assert.equal(store.guildEnabled('g2'), false);
assert.equal(settingsChanged, 1);
assert.equal((await api('POST', key, { enabled: ['nope'] })).status, 400);
assert.equal((await api('POST', key, { enabled: 'g1' })).status, 400);
assert.equal(store.guildEnabled('g2'), false);
// 새 키를 만들면 예전 키는 못 쓴다
const page2 = await (await post('/app-key', cookie, { csrf })).text();
const key2 = /<code class="key">([^<]+)<\/code>/.exec(page2)![1];
assert.equal((await api('GET', key)).status, 401);
assert.equal((await api('POST', key2, { enabled: ['g1', 'g2'] })).status, 200);
assert.equal(store.guildEnabled('g2'), true);
// 운영자가 아닌 사람의 키는 거절 (운영자 목록에서 빠진 경우 포함)
assert.equal((await api('GET', store.newAppKey('999999'))).status, 401);
assert.equal((await post('/logout', cookie, { csrf })).status, 303);
});
test('클릭재킹 막기 헤더', async () => {
const r = await get('/');
assert.equal(r.headers.get('x-frame-options'), 'DENY');
assert.match(r.headers.get('content-security-policy')!, /frame-ancestors 'none'/);
});
test('문구 버전이 바뀌면 예전 동의는 녹음하지 않는다', () => {
const s = new Store(':memory:');
s.consent({ id: '1', username: 'a' });
assert.equal(s.isConsented('1'), true);
s.db.prepare("UPDATE consents SET version = 'old'").run();
assert.equal(s.isConsented('1'), false);
assert.deepEqual(s.consentedUserIds(), []);
s.close();
});
test('따라갈 채널 고르기', () => {
assert.equal(pickChannel(null, []), null);
assert.equal(pickChannel('A', []), null);
const ps = [
{ userId: 'u1', channelId: 'A' },
{ userId: 'u2', channelId: 'B' },
{ userId: 'u3', channelId: 'B' },
];
assert.equal(pickChannel('A', ps, 'u2'), 'A'); // 지금 채널에 동의자가 남아 있으면 그대로
assert.equal(pickChannel(null, ps, 'u1'), 'A'); // 방금 움직인 사람
assert.equal(pickChannel(null, ps), 'B'); // 동의자 많은 채널
assert.equal(pickChannel('C', ps), 'B');
});