Add consent site + consent-only follow recorder bot

Discord OAuth login -> explicit consent (3 checkboxes, versioned text) ->
bot follows consenting users into voice channels and records only their
per-user streams. Revoke stops recording immediately and optionally deletes
files; consent log kept; export to training wav only for active consents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-11 11:43:06 +09:00
parent 0abadfb7e2
commit 6e0801ea1c
19 changed files with 2550 additions and 0 deletions

View File

@@ -0,0 +1,153 @@
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 { 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[] = [];
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: '승한', DISCORD_API: `http://127.0.0.1:${dport}` },
false,
);
site = createSite(cfg, store, { consentChanged: (id) => changed.push(id), recordingNow: () => null });
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>) =>
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 cb = await get(`/callback?code=good-code&state=${state}`);
assert.equal(cb.status, 303);
const cookie = cb.headers.get('set-cookie')!.split(';')[0];
// state 는 한 번만 쓸 수 있다
assert.equal((await get(`/callback?code=good-code&state=${state}`)).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, 303);
assert.equal(store.isConsented(USER.id), true);
assert.deepEqual(changed, [USER.id]);
assert.match(await (await get('/', cookie)).text(), /녹음 동의함/);
// 녹음 파일 하나 있다고 치고 철회 + 삭제
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초/);
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.equal((await post('/logout', cookie, { csrf })).status, 303);
assert.doesNotMatch(await (await get('/', cookie)).text(), /하늘님/);
});
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');
});

View File

@@ -0,0 +1,64 @@
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { PassThrough } from 'node:stream';
import { test } from 'node:test';
import { Store } from '../src/db.ts';
import { Recorder } from '../src/recorder.ts';
/** @discordjs/voice 수신기 흉내: speaking 'start' 이벤트 + 사람별 스트림 */
function fakeConnection() {
const subscriptions = new Map<string, PassThrough>();
const receiver = {
speaking: new EventEmitter(),
subscriptions,
subscribe(userId: string) {
const s = new PassThrough({ objectMode: true });
s.on('close', () => subscriptions.delete(userId));
subscriptions.set(userId, s);
return s;
},
};
return { receiver } as any;
}
const OPUS_20MS = Buffer.from([0x78, 0x01, 0x02, 0x03]); // TOC config 15 = 20ms 프레임 1개 (960 샘플)
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', 'no'); // 동의 안 한 사람
assert.equal(conn.receiver.subscriptions.has('no'), false);
conn.receiver.speaking.emit('start', 'yes');
const s = conn.receiver.subscriptions.get('yes')!;
for (let i = 0; i < 50; i++) s.write(OPUS_20MS); // 1초
await new Promise((r) => setImmediate(r));
s.end();
await new Promise((r) => setImmediate(r));
const rows = store.recordings('yes');
assert.equal(rows.length, 1);
assert.equal(rows[0].duration_ms, 1000);
assert.equal(fs.readFileSync(rows[0].path).subarray(0, 4).toString(), 'OggS');
// 말하는 도중 철회 → 저장 안 함
conn.receiver.speaking.emit('start', 'yes');
const s2 = conn.receiver.subscriptions.get('yes')!;
for (let i = 0; i < 50; i++) s2.write(OPUS_20MS);
await new Promise((r) => setImmediate(r));
store.revoke('yes');
s2.write(OPUS_20MS);
await new Promise((r) => setImmediate(r));
assert.equal(store.recordings('yes').length, 1);
assert.equal(fs.readdirSync(path.dirname(rows[0].path)).length, 1);
rec.close();
store.close();
fs.rmSync(tmp, { recursive: true, force: true });
});