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>
This commit is contained in:
EJClaw
2026-11-11 21:16:53 +09:00
parent f45d349f96
commit 32ad429773
14 changed files with 473 additions and 8 deletions

View File

@@ -9,6 +9,8 @@ PUBLIC_URL=https://voice.example.com
OPERATOR_NAME=사금향
# 녹음할 디스코드 서버 아이디 (쉼표로 여러 개). 비우면 봇이 들어간 모든 서버
ALLOWED_GUILD_IDS=
# 음성 변환기 앱에서 녹음할 서버를 켜고 끌 수 있는 디스코드 아이디 (쉼표로 여러 개). 사이트에 로그인하면 "앱 연결 키"를 만들 수 있다
ADMIN_DISCORD_IDS=293719842274541579
HOST=127.0.0.1
PORT=8787
DATA_DIR=./data

View File

@@ -12,6 +12,7 @@
서버마다 음성 연결은 하나라서 한 서버에서 동의자가 여러 채널에 흩어져 있으면 지금 채널 유지 → 방금 움직인 사람 → 동의자가 많은 채널 순으로 고른다 (`src/follow.ts`).
- 녹음 (`src/recorder.ts`): 디스코드가 사람별로 따로 보내는 음성 스트림 중 **동의한 사람 것만 구독**한다. 동의 안 한 사람의 소리는 받지도 저장하지도 않는다.
말이 0.8초 끊길 때마다 파일 하나(최대 30초, 0.5초 미만 버림), Opus 그대로 `data/recordings/<아이디>/<날짜>/<id>.ogg`. 말하는 도중 철회하면 쓰던 파일도 버린다.
- 운영자 (`ADMIN_DISCORD_IDS`): 사이트에서 **앱 연결 키**를 만들고, 음성 변환기 앱의 "녹음 서버" 화면에서 그 키로 봇이 녹음할 서버를 켜고 끈다 (`GET/POST /api/guilds`, `Authorization: Bearer <키>`, 키는 해시로만 저장, 새로 만들면 예전 키는 무효). 끈 서버에서는 바로 나간다. `.env` 의 `ALLOWED_GUILD_IDS` 밖의 서버는 앱에서도 켤 수 없다.
- 알림: 봇이 채널에 들어가면 그 채널 채팅에 녹음 안내(누구 목소리만 녹음하는지 + 사이트 주소)를 남기고, 봇 상태를 "🔴 동의한 사람 녹음 중"으로 바꾼다.
- 동의 기록: `consent_log` 테이블에 동의 · 철회 · 삭제 · 내보내기를 시각과 문구 버전으로 남긴다. 동의 문구를 바꾸면 `src/consent-text.ts` 의 `CONSENT_VERSION` 을 올린다 → 예전 동의자는 다시 동의할 때까지 녹음하지 않는다.
- 보안: OAuth state 는 로그인을 시작한 브라우저 쿠키와 맞춰 확인, 동의 제출은 화면의 문구 버전이 지금 버전과 같을 때만, 세션 · state 는 해시로만 저장, 디스코드 액세스 토큰은 저장하지 않음, 모든 form 에 CSRF 토큰 + Origin 확인, 클릭재킹 차단(`frame-ancestors 'none'`, `X-Frame-Options: DENY`), https 쿠키는 `__Host-` + Secure.

View File

@@ -84,6 +84,7 @@ export class FollowBot {
recordingNow(userId: string): string | null {
for (const [gid, r] of this.recorders) {
const g = this.client.guilds.cache.get(gid);
if (!this.store.isConsentedIn(userId, gid)) continue; // 이 서버는 녹음하지 않기로 한 사람 (다른 동의자를 녹음 중인 채널에 같이 있어도)
if (g?.voiceStates.cache.get(userId)?.channelId === r.channelId) return g.channels.cache.get(r.channelId)?.name ?? '음성채널';
}
return null;
@@ -95,8 +96,22 @@ export class FollowBot {
this.queue.set(guild.id, next);
}
/** .env 의 ALLOWED_GUILD_IDS 안에 있고, 운영자가 앱에서 끄지 않은 서버 */
private allowedGuild(guild: Guild): boolean {
return !this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(guild.id);
return (!this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(guild.id)) && this.store.guildEnabled(guild.id);
}
/** 운영자가 켜고 끌 수 있는 서버 (봇이 들어가 있고 ALLOWED_GUILD_IDS 안에 있는 곳) */
adminGuilds(): { id: string; name: string; enabled: boolean }[] {
return [...this.client.guilds.cache.values()]
.filter((g) => !this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(g.id))
.map((g) => ({ id: g.id, name: g.name, enabled: this.store.guildEnabled(g.id) }))
.sort((a, b) => a.name.localeCompare(b.name, 'ko'));
}
/** 운영자가 서버를 켜고 끈 직후: 끈 서버에서는 바로 나가고, 켠 서버에는 동의자가 있으면 따라 들어간다 */
guildSettingsChanged(): void {
for (const g of this.client.guilds.cache.values()) this.schedule(g);
}
private canJoin(ch: VoiceBasedChannel): boolean {

View File

@@ -13,6 +13,8 @@ export interface Config {
operatorName: string;
/** 비어 있으면 봇이 들어간 모든 서버 */
allowedGuildIds: Set<string>;
/** 앱 연결 키를 만들어 녹음할 서버를 켜고 끌 수 있는 디스코드 아이디 */
adminIds: Set<string>;
channelNotice: boolean;
/** 테스트에서 가짜 디스코드 API 로 바꿀 때만 */
discordApi: string;
@@ -52,6 +54,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env, needBot = true)
dataDir: path.resolve(env.DATA_DIR?.trim() || './data'),
operatorName: env.OPERATOR_NAME?.trim() || '사금향',
allowedGuildIds: new Set((env.ALLOWED_GUILD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean)),
adminIds: new Set((env.ADMIN_DISCORD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean)),
channelNotice: (env.CHANNEL_NOTICE ?? '1') !== '0',
discordApi: env.DISCORD_API?.trim() || 'https://discord.com/api/v10',
discordAuthorizeUrl: env.DISCORD_AUTHORIZE_URL?.trim() || 'https://discord.com/oauth2/authorize',

View File

@@ -73,6 +73,17 @@ export class Store {
guild_id TEXT NOT NULL,
PRIMARY KEY (user_id, guild_id)
);
-- 운영자가 음성 변환기 앱에서 끈 서버 (줄이 없으면 켜짐)
CREATE TABLE IF NOT EXISTS guild_settings (
guild_id TEXT PRIMARY KEY,
enabled INTEGER NOT NULL
);
-- 음성 변환기 앱 연결 키 (운영자 한 사람당 하나, 해시만 저장)
CREATE TABLE IF NOT EXISTS app_keys (
user_id TEXT PRIMARY KEY,
key_hash TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS recordings (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
@@ -165,6 +176,43 @@ export class Store {
return this.db.prepare('SELECT action, version, at, detail FROM consent_log WHERE user_id = ? ORDER BY id').all(userId) as any;
}
// ---- 운영자: 녹음할 서버 · 앱 연결 키 ----
/** 운영자가 끄지 않은 서버면 true (처음에는 모두 켜짐) */
guildEnabled(guildId: string): boolean {
const r = this.db.prepare('SELECT enabled FROM guild_settings WHERE guild_id = ?').get(guildId) as { enabled: number } | undefined;
return !r || r.enabled === 1;
}
setGuildEnabled(byUser: string, settings: Record<string, boolean>, now = Date.now()): void {
const up = this.db.prepare(
'INSERT INTO guild_settings (guild_id, enabled) VALUES (?, ?) ON CONFLICT(guild_id) DO UPDATE SET enabled = excluded.enabled',
);
for (const [g, on] of Object.entries(settings)) up.run(g, on ? 1 : 0);
const on = Object.keys(settings).filter((g) => settings[g]).sort();
this.log(byUser, 'admin_guilds', now, `on=${on.join(',')}`);
}
/** 새 앱 연결 키 (예전 키는 바로 못 쓰게 됨). 화면에 한 번만 보여 준다 */
newAppKey(userId: string, now = Date.now()): string {
const key = `vc_${crypto.randomBytes(24).toString('base64url')}`;
this.db
.prepare('INSERT INTO app_keys (user_id, key_hash, created_at) VALUES (?, ?, ?) ON CONFLICT(user_id) DO UPDATE SET key_hash = excluded.key_hash, created_at = excluded.created_at')
.run(userId, sha256(key), now);
this.log(userId, 'app_key', now);
return key;
}
appKeyUser(key: string): string | undefined {
const r = this.db.prepare('SELECT user_id FROM app_keys WHERE key_hash = ?').get(sha256(key)) as { user_id: string } | undefined;
return r?.user_id;
}
appKeyCreatedAt(userId: string): number | undefined {
const r = this.db.prepare('SELECT created_at FROM app_keys WHERE user_id = ?').get(userId) as { created_at: number } | undefined;
return r ? Number(r.created_at) : undefined;
}
// ---- 녹음 ----
addRecording(r: RecordingRow): void {

View File

@@ -13,6 +13,8 @@ const site = createSite(cfg, store, {
discardActive: (id) => bot.discardActive(id),
recordingNow: (id) => bot.recordingNow(id),
userGuilds: (id) => bot.userGuilds(id),
adminGuilds: () => bot.adminGuilds(),
guildSettingsChanged: () => bot.guildSettingsChanged(),
});
site.listen(cfg.port, cfg.host, () => console.log(`[site] ${cfg.publicUrl} (http://${cfg.host}:${cfg.port})`));

View File

@@ -13,6 +13,10 @@ export interface SiteHooks {
recordingNow(userId: string): string | null;
/** 봇과 이 사람이 함께 들어가 있는 서버 (녹음할 서버로 고를 수 있는 곳) */
userGuilds(userId: string): Promise<{ id: string; name: string }[]>;
/** 운영자가 켜고 끌 수 있는 서버 (음성 변환기 앱의 "녹음 서버" 화면) */
adminGuilds(): { id: string; name: string; enabled: boolean }[];
/** 운영자가 서버를 켜고 끈 직후 */
guildSettingsChanged(): void;
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
@@ -29,7 +33,7 @@ button,.btn{display:inline-block;border:0;border-radius:10px;padding:11px 18px;f
button.danger{background:var(--danger)}button.ghost{background:transparent;color:var(--muted);padding:6px 0}
.status{font-weight:700}.status.on{color:var(--ok)}.status.off{color:var(--muted)}.rec{color:var(--danger);font-weight:700}
.err{background:#fde7e9;color:#8a1c1c;border-radius:10px;padding:10px 14px}
form.inline{display:inline}fieldset{border:0;padding:0;margin:12px 0}legend{font-weight:700;padding:0}
form.inline{display:inline}code.key{display:block;word-break:break-all;background:var(--bg);border-radius:8px;padding:10px 12px;font-size:15px;user-select:all}fieldset{border:0;padding:0;margin:12px 0}legend{font-weight:700;padding:0}
`;
function page(title: string, body: string): string {
@@ -58,6 +62,10 @@ function cookies(req: http.IncomingMessage): Record<string, string> {
}
async function readForm(req: http.IncomingMessage): Promise<URLSearchParams> {
return new URLSearchParams(await readBody(req));
}
async function readBody(req: http.IncomingMessage): Promise<string> {
const chunks: Buffer[] = [];
let size = 0;
for await (const c of req) {
@@ -65,7 +73,7 @@ async function readForm(req: http.IncomingMessage): Promise<URLSearchParams> {
if (size > 16 * 1024) throw new HttpError(413, '요청이 너무 큽니다');
chunks.push(c as Buffer);
}
return new URLSearchParams(Buffer.concat(chunks).toString('utf8'));
return Buffer.concat(chunks).toString('utf8');
}
class HttpError extends Error {
@@ -122,6 +130,28 @@ export function createSite(cfg: Config, store: Store, hooks: SiteHooks): http.Se
return { ...cur, form };
}
const isAdmin = (userId: string) => cfg.adminIds.has(userId);
/** 음성 변환기 앱 → 사이트. Authorization: Bearer <앱 연결 키>, 키 주인이 지금도 운영자여야 한다 */
function appUser(req: http.IncomingMessage): string {
const m = /^Bearer (\S+)$/.exec(req.headers.authorization ?? '');
const user = m ? store.appKeyUser(m[1]) : undefined;
if (!user || !isAdmin(user)) throw new HttpError(401, '앱 연결 키가 맞지 않습니다');
return user;
}
const json = (res: http.ServerResponse, status: number, data: unknown) => send(res, status, JSON.stringify(data), 'application/json; charset=utf-8');
/** 운영자 화면: 음성 변환기 앱 연결 키 */
function adminCard(s: SessionRow, csrf: string, newKey?: string): string {
if (!isAdmin(s.user_id)) return '';
const made = store.appKeyCreatedAt(s.user_id);
return `<div class="card"><h2>음성 변환기 앱 연결 (운영자)</h2>
<p>음성 변환기 앱의 <b>녹음 서버</b> 화면에 이 사이트 주소와 앱 연결 키를 넣으면, 앱에서 봇이 녹음할 서버를 켜고 끌 수 있습니다.</p>
${newKey ? `<p>새 앱 연결 키 (이 화면에서 한 번만 보입니다. 앱에 붙여 넣으세요):</p><p><code class="key">${esc(newKey)}</code></p>` : made ? `<p class="muted">${fmtTime(made)}에 만든 키를 쓰고 있습니다. 새로 만들면 예전 키는 바로 못 씁니다.</p>` : ''}
<form method="post" action="/app-key">${csrf}<button type="submit">${made ? '앱 연결 키 새로 만들기' : '앱 연결 키 만들기'}</button></form></div>`;
}
function landing(error?: string): string {
return page(
'목소리 녹음 동의',
@@ -149,7 +179,7 @@ ${guilds.map((g) => `<label class="check"><input type="checkbox" name="guild" va
return picked;
}
async function home(s: SessionRow, error?: string): Promise<string> {
async function home(s: SessionRow, error?: string, newKey?: string): Promise<string> {
const guilds = await hooks.userGuilds(s.user_id);
const picked = new Set(store.consentGuilds(s.user_id));
const pickedNames = guilds.filter((g) => picked.has(g.id)).map((g) => esc(g.name));
@@ -186,6 +216,7 @@ ${error ? `<p class="err">${esc(error)}</p>` : ''}
<div class="card">${status}<p>녹음된 내 목소리: <b>${stats.count}개 · ${fmtDur(stats.total_ms)}</b></p>
${stats.count ? `<form method="post" action="/delete" class="inline">${csrf}<button class="danger" type="submit">녹음 파일 모두 삭제</button></form>` : ''}</div>
${consentForm}
${adminCard(s, csrf, newKey)}
<form method="post" action="/logout">${csrf}<button class="ghost" type="submit">로그아웃</button></form>`,
);
}
@@ -271,6 +302,31 @@ ${consentForm}
store.deleteRecordings(s.user_id);
return redirect(res, '/');
}
case 'POST /app-key': {
const { s } = await authedForm(req);
if (!isAdmin(s.user_id)) throw new HttpError(403, '운영자만 만들 수 있습니다');
return send(res, 200, await home(s, undefined, store.newAppKey(s.user_id)));
}
case 'GET /api/guilds': {
appUser(req);
return json(res, 200, { guilds: hooks.adminGuilds() });
}
case 'POST /api/guilds': {
const user = appUser(req);
let body: { enabled?: unknown };
try {
body = JSON.parse(await readBody(req));
} catch {
throw new HttpError(400, 'JSON 이 아닙니다');
}
if (!Array.isArray(body?.enabled) || !body.enabled.every((g) => typeof g === 'string')) throw new HttpError(400, 'enabled 는 서버 아이디 목록이어야 합니다');
const known = hooks.adminGuilds();
const on = new Set(body.enabled as string[]);
if ([...on].some((g) => !known.some((k) => k.id === g))) throw new HttpError(400, '봇이 들어가 있지 않은 서버입니다');
store.setGuildEnabled(user, Object.fromEntries(known.map((g) => [g.id, on.has(g.id)])));
hooks.guildSettingsChanged();
return json(res, 200, { guilds: hooks.adminGuilds() });
}
case 'POST /logout': {
const { sid } = await authedForm(req);
store.endSession(sid);
@@ -285,7 +341,8 @@ ${consentForm}
handle(req, res).catch((e) => {
const status = e instanceof HttpError ? e.status : 500;
if (!(e instanceof HttpError)) console.error('[site] 오류', e);
if (!res.headersSent) send(res, status, landing(e instanceof HttpError ? e.message : '서버 오류가 났습니다. 잠시 뒤 다시 해 주세요.'));
if (!res.headersSent && req.url?.startsWith('/api/')) json(res, status, { error: e instanceof HttpError ? e.message : '서버 오류' });
else if (!res.headersSent) send(res, status, landing(e instanceof HttpError ? e.message : '서버 오류가 났습니다. 잠시 뒤 다시 해 주세요.'));
else res.end();
});
});

View File

@@ -55,3 +55,39 @@ test('녹음할 서버로 고르지 않은 서버에서는 동의자라도 따
await bot.client.destroy();
store.close();
});
test('녹음 중 표시는 그 서버를 고른 사람에게만 (다른 동의자를 녹음 중인 채널에 같이 있어도)', async () => {
const store = new Store(':memory:');
store.consent({ id: 'u1', username: 'a' });
store.consent({ id: 'u3', username: 'c' });
store.setConsentGuilds('u1', ['g']);
store.setConsentGuilds('u3', ['other']);
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();
guild.voiceStates.cache.set('u3', { id: 'u3', channelId: 'A', member: { user: { bot: false } } });
guild.channels = { cache: new Map([['A', { name: 'A채널' }]]) };
(bot.client.guilds.cache as any).set('g', guild);
(bot as any).recorders.set('g', { channelId: 'A' });
assert.equal(bot.recordingNow('u1'), 'A채널');
assert.equal(bot.recordingNow('u3'), null);
(bot as any).recorders.clear();
(bot.client.guilds.cache as any).clear();
await bot.client.destroy();
store.close();
});
test('운영자가 앱에서 끈 서버는 따라가지 않는다', async () => {
const store = new Store(':memory:');
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(), name: '서버' };
(bot.client.guilds.cache as any).set('g', guild);
assert.equal((bot as any).allowedGuild(guild), true); // 처음에는 켜짐
store.setGuildEnabled('admin', { g: false });
assert.equal((bot as any).allowedGuild(guild), false);
assert.deepEqual(bot.adminGuilds(), [{ id: 'g', name: '서버', enabled: false }]);
(bot.client.guilds.cache as any).clear();
await bot.client.destroy();
store.close();
});

View File

@@ -18,6 +18,8 @@ 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-'));
@@ -46,7 +48,7 @@ before(async () => {
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: '승한', DISCORD_API: `http://127.0.0.1:${dport}` },
{ 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, {
@@ -57,6 +59,8 @@ before(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));
});
@@ -171,6 +175,41 @@ test('디스코드 로그인 → 모든 항목 체크해야 동의 → 철회하
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');