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

@@ -8,6 +8,10 @@
- 지원 언어: 한국어 · English · 中文 · 日本語 · 독일어 · 프랑스어 · 러시아어 · 포르투갈어 · 스페인어 · 이탈리아어
- UI: 파일 업로드 또는 마이크 녹음 → 전사 입력 → 합성할 텍스트 입력 → 생성/재생/다운로드
## 녹음 동의 사이트 + 따라가며 녹음하는 봇
본인이 디스코드로 로그인해 녹음에 동의한 사람만 음성채널에서 따라가며 그 사람 목소리만 녹음합니다 (음성 모델 학습 데이터용). [`consent-recorder/README.md`](consent-recorder/README.md)
## 필요 사항
- Python 3.9+ (3.10~3.12 권장)

View File

@@ -0,0 +1,15 @@
# 디스코드 개발자 포털 (https://discord.com/developers/applications) 에서 만든 앱 값
DISCORD_BOT_TOKEN=
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
# 사이트 주소 (OAuth2 Redirects 에 <PUBLIC_URL>/callback 을 등록해야 함)
PUBLIC_URL=https://voice.example.com
# 동의 화면에 "누가 이 목소리 모델을 쓰는지"로 나오는 이름
OPERATOR_NAME=
# 녹음할 디스코드 서버 아이디 (쉼표로 여러 개). 비우면 봇이 들어간 모든 서버
ALLOWED_GUILD_IDS=
HOST=127.0.0.1
PORT=8787
DATA_DIR=./data
# 봇이 음성채널에 들어갈 때 그 채널 채팅에 녹음 안내를 남김 (1/0)
CHANNEL_NOTICE=1

4
consent-recorder/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
node_modules/
dist/
data/
.env

View File

@@ -0,0 +1,51 @@
# 녹음 동의 사이트 + 따라가며 녹음하는 봇
본인이 직접 사이트에서 **디스코드로 로그인하고 녹음 동의**를 누른 사람만, 디스코드 음성채널에 따라 들어가 **그 사람 목소리만** 녹음합니다.
녹음은 나중에 그 사람 목소리 모델(RVC 등)을 학습하는 데이터로 씁니다.
## 동작
- 사이트 (`src/site.ts`): 디스코드 로그인(OAuth2 `identify` 권한만) → 동의 문구 + 체크 3개(계정 주인 · AI 음성 모델 용도 이해 · 만 14세 이상)를 모두 직접 체크해야 동의.
내 상태(동의 여부 · 지금 녹음 중인 채널 · 녹음 개수/길이), 동의 철회(녹음 파일 같이 삭제 기본), 녹음 파일만 삭제, 로그아웃.
- 봇 (`src/bot.ts`): 동의한 사람이 음성채널에 들어가면 따라 들어가고, 옮기면 따라 옮기고, 동의자가 모두 나가면 나간다.
서버마다 음성 연결은 하나라서 한 서버에서 동의자가 여러 채널에 흩어져 있으면 지금 채널 유지 → 방금 움직인 사람 → 동의자가 많은 채널 순으로 고른다 (`src/follow.ts`).
- 녹음 (`src/recorder.ts`): 디스코드가 사람별로 따로 보내는 음성 스트림 중 **동의한 사람 것만 구독**한다. 동의 안 한 사람의 소리는 받지도 저장하지도 않는다.
말이 0.8초 끊길 때마다 파일 하나(최대 30초, 0.5초 미만 버림), Opus 그대로 `data/recordings/<아이디>/<날짜>/<id>.ogg`. 말하는 도중 철회하면 쓰던 파일도 버린다.
- 알림: 봇이 채널에 들어가면 그 채널 채팅에 녹음 안내(누구 목소리만 녹음하는지 + 사이트 주소)를 남기고, 봇 상태를 "🔴 동의한 사람 녹음 중"으로 바꾼다.
- 동의 기록: `consent_log` 테이블에 동의 · 철회 · 삭제 · 내보내기를 시각과 문구 버전으로 남긴다. 동의 문구를 바꾸면 `src/consent-text.ts` 의 `CONSENT_VERSION` 을 올린다 → 예전 동의자는 다시 동의할 때까지 녹음하지 않는다.
- 보안: 세션 · OAuth state 는 해시로만 저장, 디스코드 액세스 토큰은 저장하지 않음, 모든 form 에 CSRF 토큰 + Origin 확인, 클릭재킹 차단(`frame-ancestors 'none'`, `X-Frame-Options: DENY`), https 쿠키는 `__Host-` + Secure.
- 디스코드 음성 종단간 암호화(DAVE)는 `@discordjs/voice` 0.19 + `@snazzah/davey` 로 지원.
## 준비 (디스코드 개발자 포털)
1. https://discord.com/developers/applications 에서 앱 만들기
2. **Bot** 탭: 토큰 발급 → `DISCORD_BOT_TOKEN`. Privileged Intent 는 필요 없음
3. **OAuth2** 탭: Client ID / Client Secret → `DISCORD_CLIENT_ID` / `DISCORD_CLIENT_SECRET`, Redirects 에 `<PUBLIC_URL>/callback` 추가
4. 봇 초대: OAuth2 URL Generator 에서 scope `bot`, 권한 `View Channels` · `Connect` · `Send Messages`(녹음 안내용)
## 실행
```bash
cd consent-recorder
npm install
cp .env.example .env # 값 채우기
npm run build
npm start # 사이트 http://HOST:PORT + 봇
```
사이트는 기본 `127.0.0.1:8787` 에 뜬다. 바깥에서는 리버스 프록시(NPMplus 등)로 https 도메인을 붙인다 (`PUBLIC_URL` 은 https 여야 함).
## 학습 데이터 꺼내기
```bash
npm run cli -- status # 동의자 · 녹음 양
npm run cli -- export <디스코드 아이디> ./dataset # 48kHz 모노 wav, -18 LUFS 평준화 + 리미터 (ffmpeg 필요)
```
`export` 는 **지금 동의 중인 사람만** 내보낸다 (철회했거나 문구가 바뀐 사람은 거절). 철회한 사람의 이미 학습된 모델은 이 프로그램 밖에 있으므로 운영자가 직접 지워야 한다.
## 테스트
```bash
npm test # 가짜 디스코드 OAuth 서버로 로그인 → 동의 → 철회/삭제, CSRF · 클릭재킹, 채널 고르기, 동의자만 녹음
```

1138
consent-recorder/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,25 @@
{
"name": "voice-copy-consent-recorder",
"version": "0.1.0",
"private": true,
"description": "디스코드 로그인으로 본인 동의를 받은 사람만 따라가 목소리를 녹음하는 봇 + 동의 사이트",
"type": "module",
"main": "dist/main.js",
"engines": { "node": ">=22.13" },
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"start": "node dist/main.js",
"cli": "node dist/cli.js",
"test": "node --import tsx --test test/*.test.ts"
},
"dependencies": {
"@discordjs/voice": "^0.19.2",
"discord.js": "^14.27.0"
},
"devDependencies": {
"@types/node": "^22.18.0",
"tsx": "^4.20.6",
"typescript": "^5.9.3"
}
}

183
consent-recorder/src/bot.ts Normal file
View File

@@ -0,0 +1,183 @@
import {
entersState,
getVoiceConnection,
joinVoiceChannel,
VoiceConnectionStatus,
type VoiceConnection,
} from '@discordjs/voice';
import { ActivityType, ChannelType, Client, GatewayIntentBits, PermissionFlagsBits, type Guild, type VoiceBasedChannel } from 'discord.js';
import type { Config } from './config.js';
import type { Store } from './db.js';
import { pickChannel, type Presence } from './follow.js';
import { Recorder } from './recorder.js';
/**
* 동의한 사람을 따라 음성채널에 들어가 그 사람 목소리만 녹음하는 봇.
* 서버마다 음성 연결은 하나라서, 한 서버 안에서 동의자가 여러 채널에 흩어져 있으면 한 채널만 따라간다 (follow.ts).
*/
export class FollowBot {
readonly client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] });
private recorders = new Map<string, Recorder>();
/** 서버별로 순서대로 처리 (들어가는 중에 또 움직여도 꼬이지 않게) */
private queue = new Map<string, Promise<void>>();
constructor(
private cfg: Config,
private store: Store,
) {
this.client.once('clientReady', () => {
console.log(`[bot] 로그인: ${this.client.user?.tag}`);
this.updatePresence();
for (const g of this.client.guilds.cache.values()) this.schedule(g);
});
this.client.on('voiceStateUpdate', (oldS, newS) => {
const me = this.client.user?.id;
// 누가 봇을 끊거나 다른 채널로 옮김: 정리하고 다시 판단 (동의자가 있는 채널로 돌아감)
const rec = this.recorders.get(newS.guild.id);
if (newS.id === me && rec && newS.channelId !== rec.channelId) this.drop(newS.guild.id);
if (newS.id === me || this.store.isConsented(newS.id) || this.recorders.has(newS.guild.id)) {
if (oldS.channelId && oldS.channelId !== newS.channelId) this.recorders.get(oldS.guild.id)?.stopUser(newS.id);
this.schedule(newS.guild, newS.id);
}
});
this.client.on('guildCreate', (g) => this.schedule(g));
}
async start(): Promise<void> {
await this.client.login(this.cfg.botToken);
}
async stop(): Promise<void> {
for (const gid of [...this.recorders.keys()]) this.drop(gid);
for (const g of this.client.guilds.cache.values()) getVoiceConnection(g.id)?.destroy();
await this.client.destroy();
}
/** 사이트에서 동의 · 철회한 직후: 그 사람이 있는 서버를 바로 다시 판단 */
consentChanged(userId: string): void {
for (const r of this.recorders.values()) if (!this.store.isConsented(userId)) r.stopUser(userId);
for (const g of this.client.guilds.cache.values()) {
if (g.voiceStates.cache.get(userId)?.channelId || this.recorders.has(g.id)) this.schedule(g, userId);
}
}
/** 이 사람을 지금 녹음 중인 채널 이름 */
recordingNow(userId: string): string | null {
for (const [gid, r] of this.recorders) {
const g = this.client.guilds.cache.get(gid);
if (g?.voiceStates.cache.get(userId)?.channelId === r.channelId) return g.channels.cache.get(r.channelId)?.name ?? '음성채널';
}
return null;
}
private schedule(guild: Guild, preferUserId?: string): void {
const prev = this.queue.get(guild.id) ?? Promise.resolve();
const next = prev.then(() => this.reconcile(guild, preferUserId)).catch((e) => console.error(`[bot] ${guild.name} 처리 오류`, e));
this.queue.set(guild.id, next);
}
private allowedGuild(guild: Guild): boolean {
return !this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(guild.id);
}
private canJoin(ch: VoiceBasedChannel): boolean {
const me = ch.guild.members.me;
if (!me || ch.type === ChannelType.GuildStageVoice) return false;
const p = ch.permissionsFor(me);
return !!p?.has(PermissionFlagsBits.ViewChannel) && p.has(PermissionFlagsBits.Connect) && ch.joinable;
}
private consentedPresence(guild: Guild): Presence[] {
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 });
}
return out;
}
private async reconcile(guild: Guild, preferUserId?: string): Promise<void> {
const current = this.recorders.get(guild.id)?.channelId ?? null;
const want = this.allowedGuild(guild) ? pickChannel(current, this.consentedPresence(guild), preferUserId) : null;
if (want === current) return;
this.drop(guild.id);
if (!want) {
console.log(`[bot] ${guild.name}: 동의한 사람이 없어 나감`);
this.updatePresence();
return;
}
const ch = guild.channels.cache.get(want) as VoiceBasedChannel | undefined;
if (!ch) return;
console.log(`[bot] ${guild.name}: "${ch.name}" 채널로 따라 들어감`);
const conn = joinVoiceChannel({
channelId: ch.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
selfDeaf: false, // 들어야 녹음할 수 있다
selfMute: true,
daveEncryption: true,
});
try {
await entersState(conn, VoiceConnectionStatus.Ready, 20_000);
} catch (e) {
console.error(`[bot] ${guild.name}: 음성채널 연결 실패`, e);
conn.destroy();
return;
}
this.watch(guild, conn);
const rec = new Recorder(this.store, this.cfg.dataDir, conn, guild.id, ch.id, (uid) => {
return guild.voiceStates.cache.get(uid)?.channelId === ch.id && this.store.isConsented(uid);
});
this.recorders.set(guild.id, rec);
this.updatePresence();
if (this.cfg.channelNotice) await this.notice(ch);
}
private watch(guild: Guild, conn: VoiceConnection): void {
conn.on('error', (e) => console.error('[bot] 음성 연결 오류', e));
conn.on(VoiceConnectionStatus.Disconnected, async () => {
try {
await Promise.race([
entersState(conn, VoiceConnectionStatus.Signalling, 5_000),
entersState(conn, VoiceConnectionStatus.Connecting, 5_000),
]);
} catch {
// 강퇴 · 채널 삭제 등: 정리하고 다시 판단 (동의자가 남아 있으면 다시 따라감)
if (getVoiceConnection(guild.id) === conn) conn.destroy();
this.drop(guild.id);
this.schedule(guild);
}
});
}
/** 음성채널 채팅에 녹음 안내 (권한이 없으면 건너뜀) */
private async notice(ch: VoiceBasedChannel): Promise<void> {
const ids = this.consentedPresence(ch.guild).filter((p) => p.channelId === ch.id).map((p) => `<@${p.userId}>`);
const text =
`🔴 **녹음 안내** — 이 채널에서 녹음에 동의한 사람(${ids.join(', ') || '동의자'})의 목소리만 따로 녹음합니다. ` +
`다른 분의 목소리는 녹음하지 않습니다. 동의 확인 · 철회: ${this.cfg.publicUrl}`;
try {
if ('send' in ch && typeof ch.send === 'function') await ch.send({ content: text, allowedMentions: { parse: [] } });
} catch (e: any) {
console.warn(`[bot] 녹음 안내를 남기지 못함 (${ch.name}): ${e?.message ?? e}`);
}
}
private drop(guildId: string): void {
const r = this.recorders.get(guildId);
if (!r) return;
r.close();
this.recorders.delete(guildId);
getVoiceConnection(guildId)?.destroy();
}
private updatePresence(): void {
const recording = this.recorders.size > 0;
this.client.user?.setPresence({
status: recording ? 'dnd' : 'online',
activities: [{ type: ActivityType.Custom, name: recording ? '🔴 동의한 사람 녹음 중' : '🎙️ 대기 중', state: recording ? '🔴 동의한 사람 녹음 중' : '🎙️ 대기 중' }],
});
}
}

View File

@@ -0,0 +1,56 @@
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { loadDotEnv } from './config.js';
import { Store } from './db.js';
/**
* node dist/cli.js status 동의한 사람 · 녹음 양
* node dist/cli.js export <아이디> <폴더> 학습용 wav 로 내보내기 (지금 동의한 사람만)
*/
loadDotEnv(path.resolve('.env'));
const dataDir = path.resolve(process.env.DATA_DIR?.trim() || './data');
const store = new Store(path.join(dataDir, 'consent.db'));
const [cmd, ...args] = process.argv.slice(2);
function fmtMin(ms: number): string {
return `${(ms / 60000).toFixed(1)}분`;
}
if (cmd === 'status') {
const rows = store.db.prepare('SELECT * FROM consents ORDER BY consented_at').all() as any[];
if (!rows.length) console.log('동의 기록이 없습니다');
for (const r of rows) {
const s = store.recordingStats(r.user_id);
const state = store.isConsented(r.user_id) ? '동의' : r.revoked_at ? '철회' : '문구 바뀜(재동의 필요)';
console.log(`${r.user_id}\t${r.display_name || r.username}\t${state}\t녹음 ${s.count}개 · ${fmtMin(s.total_ms)}`);
}
} else if (cmd === 'export') {
const [userId, out] = args;
if (!userId || !out) {
console.error('사용법: export <디스코드 아이디> <내보낼 폴더>');
process.exit(2);
}
// 학습 데이터는 지금 동의 중인 사람 것만 꺼낼 수 있다
if (!store.isConsented(userId)) {
console.error(`${userId} 는 지금 녹음 · 학습에 동의한 상태가 아닙니다. 내보내지 않습니다.`);
process.exit(1);
}
const rows = store.recordings(userId);
fs.mkdirSync(out, { recursive: true });
let ok = 0;
for (const r of rows) {
if (!fs.existsSync(r.path)) continue;
const dst = path.join(out, `${r.id}.wav`);
// 48kHz 모노 · -18 LUFS 평준화 · 리미터
const p = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', r.path, '-ac', '1', '-ar', '48000', '-af', 'loudnorm=I=-18:TP=-1.5:LRA=11,alimiter=limit=0.89', dst]);
if (p.status === 0) ok++;
else console.warn(`변환 실패 ${r.path}: ${p.stderr?.toString().trim()}`);
}
store.log(userId, 'export', Date.now(), `${ok} files -> ${path.resolve(out)}`);
const total = rows.reduce((a, r) => a + r.duration_ms, 0);
console.log(`${ok}/${rows.length}개 내보냄 (${fmtMin(total)}) → ${path.resolve(out)}`);
} else {
console.log('명령: status | export <디스코드 아이디> <폴더>');
}
store.close();

View File

@@ -0,0 +1,59 @@
import fs from 'node:fs';
import path from 'node:path';
export interface Config {
botToken: string;
clientId: string;
clientSecret: string;
/** 사이트 바깥 주소 (끝 / 없음). OAuth 돌아올 주소는 <publicUrl>/callback */
publicUrl: string;
host: string;
port: number;
dataDir: string;
operatorName: string;
/** 비어 있으면 봇이 들어간 모든 서버 */
allowedGuildIds: Set<string>;
channelNotice: boolean;
/** 테스트에서 가짜 디스코드 API 로 바꿀 때만 */
discordApi: string;
discordAuthorizeUrl: string;
}
/** KEY=VALUE 형식 .env (따옴표 · 주석 지원, 이미 있는 환경 변수는 덮어쓰지 않음) */
export function loadDotEnv(file: string): void {
if (!fs.existsSync(file)) return;
for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
const m = /^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line);
if (!m || line.trimStart().startsWith('#')) continue;
let v = m[2];
if (/^(['"]).*\1$/.test(v)) v = v.slice(1, -1);
if (process.env[m[1]] === undefined) process.env[m[1]] = v;
}
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env, needBot = true): Config {
const req = (k: string) => {
const v = env[k]?.trim();
if (!v) throw new Error(`환경 변수 ${k} 가 비어 있습니다 (.env.example 참고)`);
return v;
};
const publicUrl = req('PUBLIC_URL').replace(/\/+$/, '');
const u = new URL(publicUrl);
if (u.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(u.hostname)) {
throw new Error('PUBLIC_URL 은 https 여야 합니다 (localhost 만 예외)');
}
return {
botToken: needBot ? req('DISCORD_BOT_TOKEN') : env.DISCORD_BOT_TOKEN?.trim() ?? '',
clientId: req('DISCORD_CLIENT_ID'),
clientSecret: req('DISCORD_CLIENT_SECRET'),
publicUrl,
host: env.HOST?.trim() || '127.0.0.1',
port: Number(env.PORT || 8787),
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)),
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

@@ -0,0 +1,22 @@
/**
* 동의 문구. 문구를 바꾸면 CONSENT_VERSION 을 올린다.
* 버전이 바뀌면 예전 버전에 동의한 사람은 "동의 안 함"으로 보고 녹음하지 않는다 (새 문구에 다시 동의해야 함).
*/
export const CONSENT_VERSION = '2026-11-11.1';
export function consentItems(operator: string): string[] {
return [
'녹음 봇은 내가 동의한 뒤 들어가는 디스코드 음성채널에 따라 들어와, 그 채널에서 <b>내 목소리만</b> 따로 녹음합니다. 같은 채널의 다른 사람 목소리는 녹음하지 않습니다.',
`녹음한 목소리로 <b>내 목소리를 흉내 내는 AI 음성 모델</b>을 만듭니다. <b>${operator}</b>이(가) 이 모델로 자기 말소리를 실시간으로 내 목소리처럼 바꿔 디스코드 · 게임 등에서 쓸 수 있습니다.`,
'봇이 채널에 들어오면 채널 채팅에 녹음 안내가 남고, 봇 상태가 "녹음 중"으로 바뀝니다.',
'언제든 이 사이트에서 동의를 철회할 수 있습니다. 철회하면 바로 녹음을 멈추고, 고르면 지금까지의 녹음 파일도 지웁니다. 이미 만든 음성 모델 삭제는 운영자에게 요청하면 지웁니다.',
'녹음 파일은 운영자 서버에만 보관하며 다른 곳에 공개하거나 팔지 않습니다.',
];
}
/** 동의할 때 하나씩 직접 체크해야 하는 항목 (form 이름 → 문구) */
export const CONSENT_CHECKS: Record<string, string> = {
self: '나는 지금 로그인한 디스코드 계정의 주인이며, 내 목소리에 대해 동의합니다.',
model: '내 목소리로 AI 음성 모델을 만들고 위 운영자가 내 목소리처럼 말하는 데 쓰는 것을 이해하고 동의합니다.',
age: '나는 만 14세 이상입니다.',
};

199
consent-recorder/src/db.ts Normal file
View File

@@ -0,0 +1,199 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { CONSENT_VERSION } from './consent-text.js';
export interface DiscordUser {
id: string;
username: string;
global_name?: string | null;
}
export interface ConsentRow {
user_id: string;
username: string;
display_name: string | null;
version: string;
consented_at: number;
revoked_at: number | null;
}
export interface RecordingRow {
id: string;
user_id: string;
guild_id: string;
channel_id: string;
started_at: number;
duration_ms: number;
path: string;
}
export interface SessionRow {
user_id: string;
username: string;
display_name: string | null;
csrf: string;
expires_at: number;
}
const SESSION_MS = 7 * 24 * 3600 * 1000;
const STATE_MS = 10 * 60 * 1000;
export const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
export class Store {
readonly db: DatabaseSync;
constructor(file: string) {
if (file !== ':memory:') fs.mkdirSync(path.dirname(file), { recursive: true });
this.db = new DatabaseSync(file);
this.db.exec(`
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS consents (
user_id TEXT PRIMARY KEY,
username TEXT NOT NULL,
display_name TEXT,
version TEXT NOT NULL,
consented_at INTEGER NOT NULL,
revoked_at INTEGER
);
-- 동의 · 철회 · 삭제 기록 (지우지 않는다: 언제 무엇에 동의했는지 증거)
CREATE TABLE IF NOT EXISTS consent_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
action TEXT NOT NULL,
version TEXT,
at INTEGER NOT NULL,
detail TEXT
);
CREATE TABLE IF NOT EXISTS recordings (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
started_at INTEGER NOT NULL,
duration_ms INTEGER NOT NULL,
path TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS recordings_user ON recordings(user_id, started_at);
CREATE TABLE IF NOT EXISTS sessions (
id_hash TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
username TEXT NOT NULL,
display_name TEXT,
csrf TEXT NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS oauth_states (
state_hash TEXT PRIMARY KEY,
expires_at INTEGER NOT NULL
);
`);
}
// ---- 동의 ----
/** 지금 문구(CONSENT_VERSION)에 동의했고 철회하지 않은 사람만 true */
isConsented(userId: string): boolean {
const r = this.getConsent(userId);
return !!r && r.revoked_at === null && r.version === CONSENT_VERSION;
}
getConsent(userId: string): ConsentRow | undefined {
return this.db.prepare('SELECT * FROM consents WHERE user_id = ?').get(userId) as ConsentRow | undefined;
}
consentedUserIds(): string[] {
return (
this.db.prepare('SELECT user_id FROM consents WHERE revoked_at IS NULL AND version = ?').all(CONSENT_VERSION) as { user_id: string }[]
).map((r) => r.user_id);
}
consent(user: DiscordUser, now = Date.now()): void {
this.db
.prepare(
`INSERT INTO consents (user_id, username, display_name, version, consented_at, revoked_at) VALUES (?, ?, ?, ?, ?, NULL)
ON CONFLICT(user_id) DO UPDATE SET username = excluded.username, display_name = excluded.display_name,
version = excluded.version, consented_at = excluded.consented_at, revoked_at = NULL`,
)
.run(user.id, user.username, user.global_name ?? null, CONSENT_VERSION, now);
this.log(user.id, 'consent', now);
}
revoke(userId: string, now = Date.now()): void {
this.db.prepare('UPDATE consents SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL').run(now, userId);
this.log(userId, 'revoke', now);
}
log(userId: string, action: string, now = Date.now(), detail: string | null = null): void {
this.db.prepare('INSERT INTO consent_log (user_id, action, version, at, detail) VALUES (?, ?, ?, ?, ?)').run(userId, action, CONSENT_VERSION, now, detail);
}
consentLog(userId: string): { action: string; version: string; at: number; detail: string | null }[] {
return this.db.prepare('SELECT action, version, at, detail FROM consent_log WHERE user_id = ? ORDER BY id').all(userId) as any;
}
// ---- 녹음 ----
addRecording(r: RecordingRow): void {
this.db
.prepare('INSERT INTO recordings (id, user_id, guild_id, channel_id, started_at, duration_ms, path) VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(r.id, r.user_id, r.guild_id, r.channel_id, r.started_at, r.duration_ms, r.path);
}
recordings(userId: string): RecordingRow[] {
return this.db.prepare('SELECT * FROM recordings WHERE user_id = ? ORDER BY started_at').all(userId) as unknown as RecordingRow[];
}
recordingStats(userId: string): { count: number; total_ms: number } {
const r = this.db.prepare('SELECT COUNT(*) AS count, COALESCE(SUM(duration_ms), 0) AS total_ms FROM recordings WHERE user_id = ?').get(userId) as any;
return { count: Number(r.count), total_ms: Number(r.total_ms) };
}
/** 이 사람 녹음 파일과 기록을 모두 지운다. 지운 파일 수 */
deleteRecordings(userId: string, now = Date.now()): number {
const rows = this.recordings(userId);
for (const r of rows) fs.rmSync(r.path, { force: true });
this.db.prepare('DELETE FROM recordings WHERE user_id = ?').run(userId);
this.log(userId, 'delete_recordings', now, String(rows.length));
return rows.length;
}
// ---- 로그인 세션 (쿠키에는 무작위 값, DB 에는 해시만) ----
newState(now = Date.now()): string {
const state = crypto.randomBytes(24).toString('base64url');
this.db.prepare('DELETE FROM oauth_states WHERE expires_at < ?').run(now);
this.db.prepare('INSERT INTO oauth_states (state_hash, expires_at) VALUES (?, ?)').run(sha256(state), now + STATE_MS);
return state;
}
/** 한 번만 쓸 수 있다 */
takeState(state: string, now = Date.now()): boolean {
const r = this.db.prepare('DELETE FROM oauth_states WHERE state_hash = ? AND expires_at >= ?').run(sha256(state), now);
return Number(r.changes) === 1;
}
newSession(user: DiscordUser, now = Date.now()): string {
const sid = crypto.randomBytes(32).toString('base64url');
this.db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now);
this.db
.prepare('INSERT INTO sessions (id_hash, user_id, username, display_name, csrf, expires_at) VALUES (?, ?, ?, ?, ?, ?)')
.run(sha256(sid), user.id, user.username, user.global_name ?? null, crypto.randomBytes(24).toString('base64url'), now + SESSION_MS);
return sid;
}
session(sid: string, now = Date.now()): SessionRow | undefined {
const r = this.db.prepare('SELECT user_id, username, display_name, csrf, expires_at FROM sessions WHERE id_hash = ?').get(sha256(sid)) as SessionRow | undefined;
return r && r.expires_at >= now ? r : undefined;
}
endSession(sid: string): void {
this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(sha256(sid));
}
close(): void {
this.db.close();
}
}

View File

@@ -0,0 +1,21 @@
/** 음성채널에 있는 사람 하나 */
export interface Presence {
userId: string;
channelId: string;
}
/**
* 봇이 이 서버에서 있어야 할 음성채널.
* - 동의한 사람이 지금 채널에 남아 있으면 그대로 (계속 옮겨 다니지 않음)
* - 아니면 방금 움직인 동의자의 채널, 그다음 동의자가 가장 많은 채널
* - 동의자가 아무도 없으면 null (나감)
*/
export function pickChannel(current: string | null, consented: Presence[], preferUserId?: string): string | null {
if (!consented.length) return null;
if (current && consented.some((p) => p.channelId === current)) return current;
const pref = preferUserId && consented.find((p) => p.userId === preferUserId);
if (pref) return pref.channelId;
const count = new Map<string, number>();
for (const p of consented) count.set(p.channelId, (count.get(p.channelId) ?? 0) + 1);
return [...count.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0][0];
}

View File

@@ -0,0 +1,30 @@
import path from 'node:path';
import { FollowBot } from './bot.js';
import { loadConfig, loadDotEnv } from './config.js';
import { Store } from './db.js';
import { createSite } from './site.js';
loadDotEnv(path.resolve('.env'));
const cfg = loadConfig();
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),
recordingNow: (id) => bot.recordingNow(id),
});
site.listen(cfg.port, cfg.host, () => console.log(`[site] ${cfg.publicUrl} (http://${cfg.host}:${cfg.port})`));
await bot.start();
let stopping = false;
for (const sig of ['SIGINT', 'SIGTERM'] as const) {
process.on(sig, async () => {
if (stopping) return;
stopping = true;
console.log('[main] 끄는 중 (녹음 중인 파일 저장)');
site.close();
await bot.stop().catch(() => undefined);
store.close();
process.exit(0);
});
}

130
consent-recorder/src/ogg.ts Normal file
View File

@@ -0,0 +1,130 @@
import fs from 'node:fs';
// 출처: game_voice_recorder app/src/core/discord/ogg.ts (같은 작성자)
// Ogg Opus 파일 쓰기 (RFC 7845). 디스코드에서 받은 Opus 패킷을 다시 인코딩하지 않고 그대로 담는다.
const CRC_TABLE = (() => {
const t = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let r = i << 24;
for (let j = 0; j < 8; j++) r = r & 0x80000000 ? (r << 1) ^ 0x04c11db7 : r << 1;
t[i] = r >>> 0;
}
return t;
})();
function crc32(buf: Buffer): number {
let crc = 0;
for (let i = 0; i < buf.length; i++) crc = ((crc << 8) ^ CRC_TABLE[((crc >>> 24) & 0xff) ^ buf[i]]) >>> 0;
return crc >>> 0;
}
/** Opus 패킷 TOC 로 48kHz 기준 샘플 수 계산 */
export function opusSamples(packet: Buffer): number {
if (!packet.length) return 0;
const toc = packet[0];
const config = toc >> 3;
let frame: number;
if (config < 12) frame = [480, 960, 1920, 2880][config & 3];
else if (config < 16) frame = [480, 960][config & 1];
else frame = [120, 240, 480, 960][config & 3];
const c = toc & 3;
const count = c === 0 ? 1 : c === 3 ? (packet[1] ?? 0) & 0x3f : 2;
return frame * count;
}
/** 20ms 무음 Opus 프레임 (디스코드가 말이 끝날 때 보내는 것과 같은 값) */
export const SILENCE_FRAME = Buffer.from([0xf8, 0xff, 0xfe]);
export class OggOpusWriter {
private fd: number;
private serial = (Math.random() * 0xffffffff) >>> 0;
private seq = 0;
private granule = 0n;
private packets: Buffer[] = [];
private closed = false;
/** 담긴 오디오 길이 (48kHz 샘플) */
samples = 0;
bytes = 0;
constructor(
readonly path: string,
channels = 2,
) {
this.fd = fs.openSync(path, 'w');
const head = Buffer.alloc(19);
head.write('OpusHead', 0, 'ascii');
head[8] = 1;
head[9] = channels;
head.writeUInt16LE(0, 10); // pre-skip
head.writeUInt32LE(48000, 12);
head.writeInt16LE(0, 16);
head[18] = 0;
this.writePage([head], 0n, 0x02);
const vendor = Buffer.from('voice_copy', 'ascii');
const tags = Buffer.alloc(8 + 4 + vendor.length + 4);
tags.write('OpusTags', 0, 'ascii');
tags.writeUInt32LE(vendor.length, 8);
vendor.copy(tags, 12);
tags.writeUInt32LE(0, 12 + vendor.length);
this.writePage([tags], 0n, 0);
}
write(packet: Buffer): void {
if (this.closed) return;
this.packets.push(packet);
this.samples += opusSamples(packet);
if (this.packets.length >= 50) this.flush(false);
}
private flush(last: boolean): void {
if (!this.packets.length && !last) return;
this.granule = BigInt(this.samples);
this.writePage(this.packets, this.granule, last ? 0x04 : 0);
this.packets = [];
}
private writePage(packets: Buffer[], granule: bigint, flags: number): void {
const lacing: number[] = [];
for (const p of packets) {
let n = p.length;
while (n >= 255) {
lacing.push(255);
n -= 255;
}
lacing.push(n);
}
if (lacing.length > 255) {
// 한 페이지 최대 255 세그먼트. 넘으면 나눠 쓴다 (50패킷이면 생기지 않음)
const half = Math.ceil(packets.length / 2);
this.writePage(packets.slice(0, half), granule, flags & 0x02);
this.writePage(packets.slice(half), granule, flags & 0x04);
return;
}
const header = Buffer.alloc(27 + lacing.length);
header.write('OggS', 0, 'ascii');
header[4] = 0;
header[5] = flags;
header.writeBigInt64LE(granule, 6);
header.writeUInt32LE(this.serial, 14);
header.writeUInt32LE(this.seq++, 18);
header.writeUInt32LE(0, 22);
header[26] = lacing.length;
for (let i = 0; i < lacing.length; i++) header[27 + i] = lacing[i];
const page = Buffer.concat([header, ...packets]);
page.writeUInt32LE(crc32(page), 22);
fs.writeSync(this.fd, page);
this.bytes += page.length;
}
close(): void {
if (this.closed) return;
this.flush(true);
this.closed = true;
fs.closeSync(this.fd);
}
get durationMs(): number {
return Math.round(this.samples / 48);
}
}

View File

@@ -0,0 +1,136 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { EndBehaviorType, type VoiceConnection } from '@discordjs/voice';
import type { Store } from './db.js';
import { OggOpusWriter, SILENCE_FRAME } from './ogg.js';
const FRAME = 960; // 20ms @48kHz
const SILENCE_MS = 800; // 말이 0.8초 끊기면 한 파일 끝
const MAX_SEC = 30; // 한 파일 최대 30초
const MIN_MS = 500; // 0.5초보다 짧으면 버림 (키 소리 · 끊긴 패킷)
/** 수신기가 꺼낸 Opus 패킷 → RTP 순번 · 타임스탬프 (패킷 도착이 몰려도 말 사이에 무음이 끼지 않게) */
const rtpOf = new WeakMap<Buffer, { seq: number; ts: number }>();
function tapRtp(receiver: unknown): void {
const r = receiver as { parsePacket?: (buf: Buffer, ...rest: unknown[]) => Buffer | undefined; __rtp?: boolean };
if (r.__rtp || typeof r.parsePacket !== 'function') return;
const orig = r.parsePacket.bind(r);
r.parsePacket = (buf: Buffer, ...rest: unknown[]) => {
const packet = orig(buf, ...rest);
if (packet && buf.length >= 12) rtpOf.set(packet, { seq: buf.readUInt16BE(2), ts: buf.readUInt32BE(4) });
return packet;
};
r.__rtp = true;
}
class Utterance {
readonly writer: OggOpusWriter;
readonly id = `${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}`;
readonly startedAt = Date.now();
private rtpBase: number | null = null;
private lastSeq = 0;
constructor(dir: string) {
fs.mkdirSync(dir, { recursive: true });
this.writer = new OggOpusWriter(path.join(dir, `${this.id}.ogg`));
}
/** 말 사이 짧은 쉼(디스코드는 패킷을 안 보냄)을 RTP 타임스탬프로 무음 프레임으로 채운다 */
place(packet: Buffer): void {
const rtp = rtpOf.get(packet);
let fill = 0;
if (rtp && this.rtpBase !== null) {
const d = (rtp.seq - this.lastSeq) & 0xffff;
if (d === 0 || d > 0x8000) return; // 중복 · 늦게 온 패킷
const behind = ((rtp.ts - this.rtpBase) >>> 0) - this.writer.samples;
if (behind >= FRAME / 2 && behind <= SILENCE_MS * 48) fill = Math.round(behind / FRAME);
else if (behind > SILENCE_MS * 48 || behind < -48000) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0;
}
if (rtp) {
if (this.rtpBase === null) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0;
this.lastSeq = rtp.seq;
}
for (let i = 0; i < fill; i++) this.writer.write(SILENCE_FRAME);
this.writer.write(packet);
}
}
/**
* 한 음성 연결에서 동의한 사람만 사람별로 따로 녹음한다.
* 동의하지 않은 사람의 음성 스트림은 구독하지 않으므로 받지도 저장하지도 않는다.
*/
export class Recorder {
private active = new Map<string, Utterance>();
private onSpeak = (userId: string) => this.subscribe(userId);
constructor(
private store: Store,
private dataDir: string,
private connection: VoiceConnection,
readonly guildId: string,
readonly channelId: string,
/** 지금 이 채널에 있고 동의한 사람인지 (말할 때마다 다시 확인) */
private allowed: (userId: string) => boolean,
) {
tapRtp(connection.receiver);
connection.receiver.speaking.on('start', this.onSpeak);
}
private subscribe(userId: string): void {
const recv = this.connection.receiver;
if (recv.subscriptions.has(userId) || !this.allowed(userId)) return;
const stream = recv.subscribe(userId, { end: { behavior: EndBehaviorType.AfterSilence, duration: SILENCE_MS } });
stream.on('data', (packet: Buffer) => {
if (!this.allowed(userId)) return this.stopUser(userId); // 녹음 도중 철회 · 채널 이동
let u = this.active.get(userId);
if (!u) {
u = new Utterance(path.join(this.dataDir, 'recordings', userId, new Date().toISOString().slice(0, 10)));
this.active.set(userId, u);
}
u.place(packet);
if (u.writer.samples >= MAX_SEC * 48000) this.finish(userId);
});
stream.once('end', () => this.finish(userId));
stream.once('close', () => this.finish(userId));
stream.on('error', (e) => console.warn(`[rec] 수신 오류 ${userId}`, e));
}
/** 이 사람 녹음을 바로 멈추고 쓰던 파일은 버린다 (철회 · 채널을 나감) */
stopUser(userId: string): void {
this.connection.receiver.subscriptions.get(userId)?.destroy();
const u = this.active.get(userId);
if (!u) return;
this.active.delete(userId);
u.writer.close();
fs.rmSync(u.writer.path, { force: true });
}
private finish(userId: string): void {
const u = this.active.get(userId);
if (!u) return;
this.active.delete(userId);
u.writer.close();
if (u.writer.durationMs < MIN_MS || !this.allowed(userId)) {
fs.rmSync(u.writer.path, { force: true });
return;
}
this.store.addRecording({
id: u.id,
user_id: userId,
guild_id: this.guildId,
channel_id: this.channelId,
started_at: u.startedAt,
duration_ms: u.writer.durationMs,
path: u.writer.path,
});
}
/** 지금 녹음 중인 파일을 모두 저장하고 연결 수신을 끊는다 */
close(): void {
this.connection.receiver.speaking.off('start', this.onSpeak);
for (const id of [...this.active.keys()]) this.finish(id);
for (const s of this.connection.receiver.subscriptions.values()) s.destroy();
}
}

View File

@@ -0,0 +1,245 @@
import http from 'node:http';
import type { Config } from './config.js';
import { CONSENT_CHECKS, CONSENT_VERSION, consentItems } from './consent-text.js';
import type { DiscordUser, SessionRow, Store } from './db.js';
export interface SiteHooks {
/** 동의 · 철회 직후. 봇이 바로 따라 들어가거나 녹음을 멈춘다 */
consentChanged(userId: string): void;
/** 이 사람이 지금 녹음되고 있는 채널 이름 (없으면 null) */
recordingNow(userId: string): string | null;
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
const CSS = `
:root{color-scheme:light dark;--fg:#1d1d1f;--bg:#f5f5f7;--card:#fff;--muted:#6e6e73;--accent:#5865f2;--danger:#d93025;--ok:#188038}
@media (prefers-color-scheme:dark){:root{--fg:#f5f5f7;--bg:#111214;--card:#1e1f22;--muted:#a1a1a6}}
*{box-sizing:border-box}body{margin:0;font:16px/1.6 system-ui,-apple-system,"Apple SD Gothic Neo","Malgun Gothic",sans-serif;background:var(--bg);color:var(--fg)}
main{max-width:640px;margin:0 auto;padding:32px 20px}h1{font-size:24px;margin:0 0 8px}h2{font-size:18px;margin:24px 0 8px}
.card{background:var(--card);border-radius:14px;padding:20px 22px;margin:16px 0;box-shadow:0 1px 3px rgba(0,0,0,.08)}
.muted{color:var(--muted);font-size:14px}ul{padding-left:20px}li{margin:6px 0}
label.check{display:flex;gap:10px;align-items:flex-start;margin:10px 0}label.check input{margin-top:5px;width:18px;height:18px;flex-shrink:0}
button,.btn{display:inline-block;border:0;border-radius:10px;padding:11px 18px;font:inherit;font-weight:600;cursor:pointer;text-decoration:none;background:var(--accent);color:#fff}
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}
`;
function page(title: string, body: string): string {
return `<!doctype html><html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${esc(title)}</title><link rel="stylesheet" href="/style.css"></head><body><main>${body}</main></body></html>`;
}
function fmtTime(ts: number): string {
return new Date(ts).toLocaleString('ko-KR', { timeZone: 'Asia/Seoul' });
}
function fmtDur(ms: number): string {
const s = Math.round(ms / 1000);
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
return h ? `${h}시간 ${m}분` : m ? `${m}분 ${s % 60}초` : `${s}초`;
}
function cookies(req: http.IncomingMessage): Record<string, string> {
const out: Record<string, string> = {};
for (const part of (req.headers.cookie ?? '').split(';')) {
const i = part.indexOf('=');
if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
}
return out;
}
async function readForm(req: http.IncomingMessage): Promise<URLSearchParams> {
const chunks: Buffer[] = [];
let size = 0;
for await (const c of req) {
size += (c as Buffer).length;
if (size > 16 * 1024) throw new HttpError(413, '요청이 너무 큽니다');
chunks.push(c as Buffer);
}
return new URLSearchParams(Buffer.concat(chunks).toString('utf8'));
}
class HttpError extends Error {
constructor(
readonly status: number,
message: string,
) {
super(message);
}
}
export function createSite(cfg: Config, store: Store, hooks: SiteHooks): http.Server {
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 send = (res: http.ServerResponse, status: number, body: string, type = 'text/html; charset=utf-8', extra: Record<string, string | string[]> = {}) => {
res.writeHead(status, {
'Content-Type': type,
'Cache-Control': 'no-store',
// 다른 사이트가 이 페이지를 몰래 띄워 동의 버튼을 누르게 하지 못하게 (클릭재킹)
'Content-Security-Policy': "default-src 'none'; style-src 'self'; img-src 'self' https://cdn.discordapp.com; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
'X-Frame-Options': 'DENY',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
...extra,
});
res.end(body);
};
const redirect = (res: http.ServerResponse, to: string, extra: Record<string, string | string[]> = {}) => {
res.writeHead(303, { Location: to, 'Cache-Control': 'no-store', ...extra });
res.end();
};
function currentSession(req: http.IncomingMessage): { sid: string; s: SessionRow } | null {
const sid = cookies(req)[cookieName];
if (!sid) return null;
const s = store.session(sid);
return s ? { sid, s } : null;
}
/** 로그인 + CSRF 확인. 다른 사이트에서 보낸 form 으로 동의 · 철회되지 않게 */
async function authedForm(req: http.IncomingMessage): Promise<{ s: SessionRow; form: URLSearchParams; sid: string }> {
const cur = currentSession(req);
if (!cur) throw new HttpError(401, '로그인이 필요합니다');
const origin = req.headers.origin;
if (origin && origin !== new URL(cfg.publicUrl).origin) throw new HttpError(403, '잘못된 요청입니다');
const form = await readForm(req);
if (form.get('csrf') !== cur.s.csrf) throw new HttpError(403, '페이지가 오래되었습니다. 새로고침한 뒤 다시 해 주세요');
return { ...cur, form };
}
function landing(error?: string): string {
return page(
'목소리 녹음 동의',
`<h1>목소리 녹음 동의</h1>
<p class="muted">AI 음성 모델을 만들기 위해 디스코드 음성채널에서 <b>본인이 직접 동의한 사람</b>의 목소리만 녹음합니다.</p>
${error ? `<p class="err">${esc(error)}</p>` : ''}
<div class="card"><h2>어떻게 쓰이나요</h2><ul>${consentItems(esc(cfg.operatorName)).map((t) => `<li>${t}</li>`).join('')}</ul></div>
<p><a class="btn" href="/login">디스코드로 로그인</a></p>
<p class="muted">로그인은 내 디스코드 아이디와 이름만 확인합니다 (identify 권한). 동의는 로그인한 뒤 따로 누릅니다.</p>`,
);
}
function home(s: SessionRow, error?: string): string {
const c = store.getConsent(s.user_id);
const on = store.isConsented(s.user_id);
const stats = store.recordingStats(s.user_id);
const live = on ? hooks.recordingNow(s.user_id) : null;
const name = esc(s.display_name || s.username);
const csrf = `<input type="hidden" name="csrf" value="${esc(s.csrf)}">`;
const stale = c && c.revoked_at === null && c.version !== CONSENT_VERSION;
const status = on
? `<p class="status on">● 녹음 동의함</p><p class="muted">${fmtTime(c!.consented_at)}에 동의 (문구 버전 ${esc(c!.version)})</p>
${live ? `<p class="rec">🔴 지금 “${esc(live)}” 채널에서 내 목소리를 녹음하고 있습니다</p>` : '<p class="muted">지금은 녹음하고 있지 않습니다. 음성채널에 들어가면 봇이 따라 들어옵니다.</p>'}`
: `<p class="status off">○ 녹음하지 않음</p>${
stale ? '<p class="muted">동의 문구가 바뀌어서 다시 동의해야 녹음합니다.</p>' : c?.revoked_at ? `<p class="muted">${fmtTime(c.revoked_at)}에 동의를 철회했습니다.</p>` : ''
}`;
const consentForm = on
? `<div class="card"><h2>동의 철회</h2><p>철회하면 바로 녹음을 멈추고 봇이 나를 따라오지 않습니다.</p>
<form method="post" action="/revoke">${csrf}
<label class="check"><input type="checkbox" name="delete" value="1" checked><span>지금까지 녹음된 내 목소리 파일도 모두 삭제</span></label>
<button class="danger" type="submit">동의 철회</button></form></div>`
: `<div class="card"><h2>녹음 동의</h2><ul>${consentItems(esc(cfg.operatorName)).map((t) => `<li>${t}</li>`).join('')}</ul>
<form method="post" action="/consent">${csrf}
${Object.entries(CONSENT_CHECKS).map(([k, t]) => `<label class="check"><input type="checkbox" name="${k}" value="1" required><span>${esc(t)}</span></label>`).join('')}
<button type="submit">위 내용에 동의하고 녹음 시작</button></form></div>`;
return page(
'목소리 녹음 동의',
`<h1>${name}님</h1><p class="muted">디스코드 아이디 ${esc(s.user_id)}</p>
${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}
<form method="post" action="/logout">${csrf}<button class="ghost" type="submit">로그아웃</button></form>`,
);
}
async function oauthUser(code: string): Promise<DiscordUser> {
const tok = await fetch(`${cfg.discordApi}/oauth2/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri, client_id: cfg.clientId, client_secret: cfg.clientSecret }),
});
if (!tok.ok) throw new HttpError(400, `디스코드 로그인 실패 (토큰 ${tok.status})`);
const { access_token } = (await tok.json()) as { access_token?: string };
if (!access_token) throw new HttpError(400, '디스코드 로그인 실패 (토큰 없음)');
const me = await fetch(`${cfg.discordApi}/users/@me`, { headers: { Authorization: `Bearer ${access_token}` } });
if (!me.ok) throw new HttpError(400, `디스코드 로그인 실패 (사용자 ${me.status})`);
const u = (await me.json()) as DiscordUser;
if (!u?.id || !/^\d{5,25}$/.test(u.id)) throw new HttpError(400, '디스코드 사용자 정보가 올바르지 않습니다');
// 액세스 토큰은 아이디 확인에만 쓰고 저장하지 않는다
return { id: u.id, username: String(u.username ?? ''), global_name: u.global_name ?? null };
}
async function handle(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
const url = new URL(req.url ?? '/', 'http://x');
const route = `${req.method} ${url.pathname}`;
switch (route) {
case 'GET /style.css':
return send(res, 200, CSS, 'text/css; charset=utf-8', { 'Cache-Control': 'public, max-age=3600' });
case 'GET /health':
return send(res, 200, JSON.stringify({ ok: true }), 'application/json');
case 'GET /': {
const cur = currentSession(req);
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}`);
}
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('로그인 요청이 만료되었습니다. 다시 로그인해 주세요.'));
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) });
}
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, '모든 항목에 직접 체크해야 동의할 수 있습니다.'));
store.consent({ id: s.user_id, username: s.username, global_name: s.display_name });
hooks.consentChanged(s.user_id);
return redirect(res, '/');
}
case 'POST /revoke': {
const { s, form } = await authedForm(req);
store.revoke(s.user_id);
hooks.consentChanged(s.user_id); // 봇이 먼저 녹음을 멈춘 뒤 파일을 지운다
if (form.get('delete') === '1') store.deleteRecordings(s.user_id);
return redirect(res, '/');
}
case 'POST /delete': {
const { s } = await authedForm(req);
store.deleteRecordings(s.user_id);
return redirect(res, '/');
}
case 'POST /logout': {
const { sid } = await authedForm(req);
store.endSession(sid);
return redirect(res, '/', { 'Set-Cookie': setSid('', 0) });
}
default:
return send(res, 404, page('없는 페이지', '<h1>없는 페이지입니다</h1><p><a href="/">처음으로</a></p>'));
}
}
return http.createServer((req, res) => {
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 : '서버 오류가 났습니다. 잠시 뒤 다시 해 주세요.'));
else res.end();
});
});
}

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 });
});

View File

@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": "src",
"types": ["node"],
"lib": ["ES2023"]
},
"include": ["src/**/*.ts"]
}