From 6e0801ea1c3eba7b103fa68f675672ac841211cb Mon Sep 17 00:00:00 2001 From: EJClaw Date: Wed, 11 Nov 2026 11:43:06 +0900 Subject: [PATCH] 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 --- README.md | 4 + consent-recorder/.env.example | 15 + consent-recorder/.gitignore | 4 + consent-recorder/README.md | 51 ++ consent-recorder/package-lock.json | 1138 ++++++++++++++++++++++++ consent-recorder/package.json | 25 + consent-recorder/src/bot.ts | 183 ++++ consent-recorder/src/cli.ts | 56 ++ consent-recorder/src/config.ts | 59 ++ consent-recorder/src/consent-text.ts | 22 + consent-recorder/src/db.ts | 199 +++++ consent-recorder/src/follow.ts | 21 + consent-recorder/src/main.ts | 30 + consent-recorder/src/ogg.ts | 130 +++ consent-recorder/src/recorder.ts | 136 +++ consent-recorder/src/site.ts | 245 +++++ consent-recorder/test/consent.test.ts | 153 ++++ consent-recorder/test/recorder.test.ts | 64 ++ consent-recorder/tsconfig.json | 15 + 19 files changed, 2550 insertions(+) create mode 100644 consent-recorder/.env.example create mode 100644 consent-recorder/.gitignore create mode 100644 consent-recorder/README.md create mode 100644 consent-recorder/package-lock.json create mode 100644 consent-recorder/package.json create mode 100644 consent-recorder/src/bot.ts create mode 100644 consent-recorder/src/cli.ts create mode 100644 consent-recorder/src/config.ts create mode 100644 consent-recorder/src/consent-text.ts create mode 100644 consent-recorder/src/db.ts create mode 100644 consent-recorder/src/follow.ts create mode 100644 consent-recorder/src/main.ts create mode 100644 consent-recorder/src/ogg.ts create mode 100644 consent-recorder/src/recorder.ts create mode 100644 consent-recorder/src/site.ts create mode 100644 consent-recorder/test/consent.test.ts create mode 100644 consent-recorder/test/recorder.test.ts create mode 100644 consent-recorder/tsconfig.json diff --git a/README.md b/README.md index 605821c..56e4205 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ - 지원 언어: 한국어 · English · 中文 · 日本語 · 독일어 · 프랑스어 · 러시아어 · 포르투갈어 · 스페인어 · 이탈리아어 - UI: 파일 업로드 또는 마이크 녹음 → 전사 입력 → 합성할 텍스트 입력 → 생성/재생/다운로드 +## 녹음 동의 사이트 + 따라가며 녹음하는 봇 + +본인이 디스코드로 로그인해 녹음에 동의한 사람만 음성채널에서 따라가며 그 사람 목소리만 녹음합니다 (음성 모델 학습 데이터용). [`consent-recorder/README.md`](consent-recorder/README.md) + ## 필요 사항 - Python 3.9+ (3.10~3.12 권장) diff --git a/consent-recorder/.env.example b/consent-recorder/.env.example new file mode 100644 index 0000000..08aafa4 --- /dev/null +++ b/consent-recorder/.env.example @@ -0,0 +1,15 @@ +# 디스코드 개발자 포털 (https://discord.com/developers/applications) 에서 만든 앱 값 +DISCORD_BOT_TOKEN= +DISCORD_CLIENT_ID= +DISCORD_CLIENT_SECRET= +# 사이트 주소 (OAuth2 Redirects 에 /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 diff --git a/consent-recorder/.gitignore b/consent-recorder/.gitignore new file mode 100644 index 0000000..e948a28 --- /dev/null +++ b/consent-recorder/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +dist/ +data/ +.env diff --git a/consent-recorder/README.md b/consent-recorder/README.md new file mode 100644 index 0000000..ad0e5a6 --- /dev/null +++ b/consent-recorder/README.md @@ -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/<아이디>/<날짜>/.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 에 `/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 · 클릭재킹, 채널 고르기, 동의자만 녹음 +``` diff --git a/consent-recorder/package-lock.json b/consent-recorder/package-lock.json new file mode 100644 index 0000000..91d46a7 --- /dev/null +++ b/consent-recorder/package-lock.json @@ -0,0 +1,1138 @@ +{ + "name": "voice-copy-consent-recorder", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "voice-copy-consent-recorder", + "version": "0.1.0", + "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" + }, + "engines": { + "node": ">=22.13" + } + }, + "node_modules/@discordjs/builders": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.15.0.tgz", + "integrity": "sha512-AifaDWTw6WUDhKBn8E6mwwoyjDAcfsYq+ZE0nKSu1dMH1NLR22D3hGkNx+ctEv8NqHEHdAZnP5REteHDmn1lkA==", + "dependencies": { + "@discordjs/formatters": "^0.6.2", + "@discordjs/util": "^1.2.0", + "@sapphire/shapeshift": "^4.0.0", + "discord-api-types": "^0.38.50", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.4", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/collection": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz", + "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==", + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz", + "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==", + "dependencies": { + "discord-api-types": "^0.38.33" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz", + "integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==", + "dependencies": { + "@discordjs/collection": "^2.1.1", + "@discordjs/util": "^1.2.0", + "@sapphire/async-queue": "^1.5.3", + "@sapphire/snowflake": "^3.5.5", + "@vladfrangu/async_event_emitter": "^2.4.6", + "discord-api-types": "^0.38.50", + "magic-bytes.js": "^1.13.0", + "tslib": "^2.6.3", + "undici": "^6.27.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", + "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/util": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz", + "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==", + "dependencies": { + "discord-api-types": "^0.38.33" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/voice": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@discordjs/voice/-/voice-0.19.2.tgz", + "integrity": "sha512-3yJ255e4ag3wfZu/DSxeOZK1UtnqNxnspmLaQetGT0pDkThNZoHs+Zg6dgZZ19JEVomXygvfHn9lNpICZuYtEA==", + "dependencies": { + "@snazzah/davey": "^0.1.9", + "@types/ws": "^8.18.1", + "discord-api-types": "^0.38.41", + "prism-media": "^1.3.5", + "tslib": "^2.8.1", + "ws": "^8.19.0" + }, + "engines": { + "node": ">=22.12.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz", + "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==", + "dependencies": { + "@discordjs/collection": "^2.1.0", + "@discordjs/rest": "^2.5.1", + "@discordjs/util": "^1.1.0", + "@sapphire/async-queue": "^1.5.2", + "@types/ws": "^8.5.10", + "@vladfrangu/async_event_emitter": "^2.2.4", + "discord-api-types": "^0.38.1", + "tslib": "^2.6.2", + "ws": "^8.17.0" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", + "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@emnapi/core": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", + "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", + "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", + "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" + } + }, + "node_modules/@sapphire/async-queue": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz", + "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/shapeshift": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz", + "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v16" + } + }, + "node_modules/@sapphire/snowflake": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz", + "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@snazzah/davey": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey/-/davey-0.1.12.tgz", + "integrity": "sha512-V+NlX5931RwVamZhhEfZekMdcvXDKdMAmHW1AuGaykVQsNyBOq3bpmGpoKRBDCYgFWKIufJ0Dcg3m4cYhvUy6g==", + "engines": { + "node": ">= 10" + }, + "funding": { + "url": "https://github.com/sponsors/Snazzah" + }, + "optionalDependencies": { + "@snazzah/davey-android-arm-eabi": "0.1.12", + "@snazzah/davey-android-arm64": "0.1.12", + "@snazzah/davey-darwin-arm64": "0.1.12", + "@snazzah/davey-darwin-x64": "0.1.12", + "@snazzah/davey-freebsd-x64": "0.1.12", + "@snazzah/davey-linux-arm-gnueabihf": "0.1.12", + "@snazzah/davey-linux-arm64-gnu": "0.1.12", + "@snazzah/davey-linux-arm64-musl": "0.1.12", + "@snazzah/davey-linux-x64-gnu": "0.1.12", + "@snazzah/davey-linux-x64-musl": "0.1.12", + "@snazzah/davey-wasm32-wasi": "0.1.12", + "@snazzah/davey-win32-arm64-msvc": "0.1.12", + "@snazzah/davey-win32-ia32-msvc": "0.1.12", + "@snazzah/davey-win32-x64-msvc": "0.1.12" + } + }, + "node_modules/@snazzah/davey-android-arm-eabi": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-android-arm-eabi/-/davey-android-arm-eabi-0.1.12.tgz", + "integrity": "sha512-6VC/an+Sx5dI5skb+90rYcIB1jhm48Rl0nDaw0UNT4bz1rMjpVfmmZqeocYXMq96IdbBMlE6OTKGcBm2C3gkQg==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-android-arm64": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-android-arm64/-/davey-android-arm64-0.1.12.tgz", + "integrity": "sha512-0Bwd03/JsTFhlPhF4q/LW0RxSzntFpQdhz+TBdFljYSg8IEyA38saPJeTNjpIgDfhAumPzvhCdfS6O5qT8yXDw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-darwin-arm64": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-darwin-arm64/-/davey-darwin-arm64-0.1.12.tgz", + "integrity": "sha512-lKMV6ITi9BQLt0fx/pAT7M8xcojVK7bryVJGdaW3bq8gABFslS3ti/KzrWabQvhpEV71FZe5mV0UcKHFVaTsZw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-darwin-x64": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-darwin-x64/-/davey-darwin-x64-0.1.12.tgz", + "integrity": "sha512-vXXc/eW/e3TQeb7VsdtrPqs3/22j0aSqiP1ZXmZtDjQRBwgSxwItWYa6sh5MELP2EHB2igNlGzB6Hc0XlbGi4g==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-freebsd-x64": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-freebsd-x64/-/davey-freebsd-x64-0.1.12.tgz", + "integrity": "sha512-G1gas5HrC4Xp3mRY0+OeAqXS6fG2tRgBEc8gQh69Hw4YK9RV9mzQKcmoKMkBM72U1+2C+2u57dolnKKzwozByQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-linux-arm-gnueabihf": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-linux-arm-gnueabihf/-/davey-linux-arm-gnueabihf-0.1.12.tgz", + "integrity": "sha512-97Fujh82r2Ll7dPZeNuoZ3yKfsqycf3c93OWXOo/ThNL/18Onl2Ht4SIvpX6VHhfeS9bDpHJ1lHCaz1b/i5ocw==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-linux-arm64-gnu": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-linux-arm64-gnu/-/davey-linux-arm64-gnu-0.1.12.tgz", + "integrity": "sha512-FWyAOv52cHKDM4BOsmImKKogHFvqNFoXmZcicNJbX3XpVl8Mas88ZoXQ+IA5V+qc9pNtAl1MbWwEZ9JrqAQtbg==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-linux-arm64-musl": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-linux-arm64-musl/-/davey-linux-arm64-musl-0.1.12.tgz", + "integrity": "sha512-ptRbLSQxtV6EjXppS5z7qaPDI0NRKhrkJYsTlAjEghmOvlAObozSCYYnMO6nbkt6Ab3+lWqyahClzcRNcD2ouw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-linux-x64-gnu": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-linux-x64-gnu/-/davey-linux-x64-gnu-0.1.12.tgz", + "integrity": "sha512-w86fZvhJn0ErOoAQHt2UbQ95V/cgwvfvQ4GlTPQLCzt58nn+rLlXLgPn90qYlSQrZxFW38rKXwqVOMbm9p+pwQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-linux-x64-musl": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-linux-x64-musl/-/davey-linux-x64-musl-0.1.12.tgz", + "integrity": "sha512-LLNnO+hfG41ymeI+O1YHo5/0h3aKaetUNLdkBwpdJsjoyKMXZaeCnB+aHNkkupJCMPmWS0g6iPMCHUOqZSBcTg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-wasm32-wasi": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-wasm32-wasi/-/davey-wasm32-wasi-0.1.12.tgz", + "integrity": "sha512-MPKFuqYVkDFXheR7qmtEY4FWxQ/ADfgsCojQWHi13sibUqCTR9q2F1LqNn2i9IVh3sh1sxeg87fdFMCH63pl7g==", + "cpu": [ + "wasm32" + ], + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^1.1.5" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@snazzah/davey-win32-arm64-msvc": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-win32-arm64-msvc/-/davey-win32-arm64-msvc-0.1.12.tgz", + "integrity": "sha512-Uf4OYHyfbXpzyaOqIV8/h6kv166Qni5+Bxmc1E/ov4uhhKO8qXbOky8zbVOzu0U4cv5ll3s4IQ8jDAJkx/K75Q==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-win32-ia32-msvc": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-win32-ia32-msvc/-/davey-win32-ia32-msvc-0.1.12.tgz", + "integrity": "sha512-nRVbKTsb2ldcPI8D4BDA7P/UeiMEMvR+wYuUMp7H1pRD/3dF2hKo+MzUU+Pn78EhuYA3CWHItiAcS/GsPld67A==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@snazzah/davey-win32-x64-msvc": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@snazzah/davey-win32-x64-msvc/-/davey-win32-x64-msvc-0.1.12.tgz", + "integrity": "sha512-AgUA3itPDVkxQq7RIkgE1thCiWePwWjyfOZefBBxGIlMWpRUOSwF4vY9kNLnrScyJcFULdR+Zm8PwiwV8/RKnw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@vladfrangu/async_event_emitter": { + "version": "2.4.7", + "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz", + "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/discord-api-types": { + "version": "0.38.58", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.58.tgz", + "integrity": "sha512-6utghVho47hBzmx8nIp+pKEDDNIlVk6On/J5Y1Q529payNLZjBsrw+mt+G5Y3NYRE3kgta6eBx5hRYVyfHGdOA==" + }, + "node_modules/discord.js": { + "version": "14.28.1", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.28.1.tgz", + "integrity": "sha512-Je5OcqgurnIUQK4vR+gQnmzOf/lNQsD6d/UkV8ZOj+bFa5zJXPyiGXlbywp2EagwshVT18y7YNQNSRd3FjYkDw==", + "dependencies": { + "@discordjs/builders": "^1.15.0", + "@discordjs/collection": "1.5.3", + "@discordjs/formatters": "^0.6.2", + "@discordjs/rest": "^2.6.3", + "@discordjs/util": "^1.2.0", + "@discordjs/ws": "^1.2.3", + "@sapphire/snowflake": "3.5.5", + "discord-api-types": "^0.38.50", + "fast-deep-equal": "3.1.3", + "lodash.snakecase": "4.1.1", + "magic-bytes.js": "^1.13.0", + "tslib": "^2.6.3", + "undici": "^6.27.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==" + }, + "node_modules/magic-bytes.js": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz", + "integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==" + }, + "node_modules/prism-media": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz", + "integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==", + "peerDependencies": { + "@discordjs/opus": ">=0.8.0 <1.0.0", + "ffmpeg-static": "^5.0.2 || ^4.2.7 || ^3.0.0 || ^2.4.0", + "node-opus": "^0.3.3", + "opusscript": "^0.0.8" + }, + "peerDependenciesMeta": { + "@discordjs/opus": { + "optional": true + }, + "ffmpeg-static": { + "optional": true + }, + "node-opus": { + "optional": true + }, + "opusscript": { + "optional": true + } + } + }, + "node_modules/ts-mixer": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz", + "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==" + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==" + }, + "node_modules/tsx": { + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "dev": true, + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici": { + "version": "6.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", + "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==" + }, + "node_modules/ws": { + "version": "8.22.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", + "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/consent-recorder/package.json b/consent-recorder/package.json new file mode 100644 index 0000000..7fa2dc9 --- /dev/null +++ b/consent-recorder/package.json @@ -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" + } +} diff --git a/consent-recorder/src/bot.ts b/consent-recorder/src/bot.ts new file mode 100644 index 0000000..d5e8d76 --- /dev/null +++ b/consent-recorder/src/bot.ts @@ -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(); + /** 서버별로 순서대로 처리 (들어가는 중에 또 움직여도 꼬이지 않게) */ + private queue = new Map>(); + + 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 { + await this.client.login(this.cfg.botToken); + } + + async stop(): Promise { + 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 { + 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 { + 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 ? '🔴 동의한 사람 녹음 중' : '🎙️ 대기 중' }], + }); + } +} diff --git a/consent-recorder/src/cli.ts b/consent-recorder/src/cli.ts new file mode 100644 index 0000000..7eec8d1 --- /dev/null +++ b/consent-recorder/src/cli.ts @@ -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(); diff --git a/consent-recorder/src/config.ts b/consent-recorder/src/config.ts new file mode 100644 index 0000000..5d0b173 --- /dev/null +++ b/consent-recorder/src/config.ts @@ -0,0 +1,59 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +export interface Config { + botToken: string; + clientId: string; + clientSecret: string; + /** 사이트 바깥 주소 (끝 / 없음). OAuth 돌아올 주소는 /callback */ + publicUrl: string; + host: string; + port: number; + dataDir: string; + operatorName: string; + /** 비어 있으면 봇이 들어간 모든 서버 */ + allowedGuildIds: Set; + 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', + }; +} diff --git a/consent-recorder/src/consent-text.ts b/consent-recorder/src/consent-text.ts new file mode 100644 index 0000000..82be201 --- /dev/null +++ b/consent-recorder/src/consent-text.ts @@ -0,0 +1,22 @@ +/** + * 동의 문구. 문구를 바꾸면 CONSENT_VERSION 을 올린다. + * 버전이 바뀌면 예전 버전에 동의한 사람은 "동의 안 함"으로 보고 녹음하지 않는다 (새 문구에 다시 동의해야 함). + */ +export const CONSENT_VERSION = '2026-11-11.1'; + +export function consentItems(operator: string): string[] { + return [ + '녹음 봇은 내가 동의한 뒤 들어가는 디스코드 음성채널에 따라 들어와, 그 채널에서 내 목소리만 따로 녹음합니다. 같은 채널의 다른 사람 목소리는 녹음하지 않습니다.', + `녹음한 목소리로 내 목소리를 흉내 내는 AI 음성 모델을 만듭니다. ${operator}이(가) 이 모델로 자기 말소리를 실시간으로 내 목소리처럼 바꿔 디스코드 · 게임 등에서 쓸 수 있습니다.`, + '봇이 채널에 들어오면 채널 채팅에 녹음 안내가 남고, 봇 상태가 "녹음 중"으로 바뀝니다.', + '언제든 이 사이트에서 동의를 철회할 수 있습니다. 철회하면 바로 녹음을 멈추고, 고르면 지금까지의 녹음 파일도 지웁니다. 이미 만든 음성 모델 삭제는 운영자에게 요청하면 지웁니다.', + '녹음 파일은 운영자 서버에만 보관하며 다른 곳에 공개하거나 팔지 않습니다.', + ]; +} + +/** 동의할 때 하나씩 직접 체크해야 하는 항목 (form 이름 → 문구) */ +export const CONSENT_CHECKS: Record = { + self: '나는 지금 로그인한 디스코드 계정의 주인이며, 내 목소리에 대해 동의합니다.', + model: '내 목소리로 AI 음성 모델을 만들고 위 운영자가 내 목소리처럼 말하는 데 쓰는 것을 이해하고 동의합니다.', + age: '나는 만 14세 이상입니다.', +}; diff --git a/consent-recorder/src/db.ts b/consent-recorder/src/db.ts new file mode 100644 index 0000000..bab18cd --- /dev/null +++ b/consent-recorder/src/db.ts @@ -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(); + } +} diff --git a/consent-recorder/src/follow.ts b/consent-recorder/src/follow.ts new file mode 100644 index 0000000..4d54cd4 --- /dev/null +++ b/consent-recorder/src/follow.ts @@ -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(); + 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]; +} diff --git a/consent-recorder/src/main.ts b/consent-recorder/src/main.ts new file mode 100644 index 0000000..57ad94f --- /dev/null +++ b/consent-recorder/src/main.ts @@ -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); + }); +} diff --git a/consent-recorder/src/ogg.ts b/consent-recorder/src/ogg.ts new file mode 100644 index 0000000..9247358 --- /dev/null +++ b/consent-recorder/src/ogg.ts @@ -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); + } +} diff --git a/consent-recorder/src/recorder.ts b/consent-recorder/src/recorder.ts new file mode 100644 index 0000000..be0773e --- /dev/null +++ b/consent-recorder/src/recorder.ts @@ -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(); + +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(); + 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(); + } +} diff --git a/consent-recorder/src/site.ts b/consent-recorder/src/site.ts new file mode 100644 index 0000000..694a4ca --- /dev/null +++ b/consent-recorder/src/site.ts @@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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 ` +${esc(title)}
${body}
`; +} + +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 { + const out: Record = {}; + 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 { + 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 = {}) => { + 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 = {}) => { + 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( + '목소리 녹음 동의', + `

목소리 녹음 동의

+

AI 음성 모델을 만들기 위해 디스코드 음성채널에서 본인이 직접 동의한 사람의 목소리만 녹음합니다.

+${error ? `

${esc(error)}

` : ''} +

어떻게 쓰이나요

    ${consentItems(esc(cfg.operatorName)).map((t) => `
  • ${t}
  • `).join('')}
+

디스코드로 로그인

+

로그인은 내 디스코드 아이디와 이름만 확인합니다 (identify 권한). 동의는 로그인한 뒤 따로 누릅니다.

`, + ); + } + + 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 = ``; + const stale = c && c.revoked_at === null && c.version !== CONSENT_VERSION; + const status = on + ? `

● 녹음 동의함

${fmtTime(c!.consented_at)}에 동의 (문구 버전 ${esc(c!.version)})

+ ${live ? `

🔴 지금 “${esc(live)}” 채널에서 내 목소리를 녹음하고 있습니다

` : '

지금은 녹음하고 있지 않습니다. 음성채널에 들어가면 봇이 따라 들어옵니다.

'}` + : `

○ 녹음하지 않음

${ + stale ? '

동의 문구가 바뀌어서 다시 동의해야 녹음합니다.

' : c?.revoked_at ? `

${fmtTime(c.revoked_at)}에 동의를 철회했습니다.

` : '' + }`; + const consentForm = on + ? `

동의 철회

철회하면 바로 녹음을 멈추고 봇이 나를 따라오지 않습니다.

+
${csrf} + +
` + : `

녹음 동의

    ${consentItems(esc(cfg.operatorName)).map((t) => `
  • ${t}
  • `).join('')}
+
${csrf} +${Object.entries(CONSENT_CHECKS).map(([k, t]) => ``).join('')} +
`; + return page( + '목소리 녹음 동의', + `

${name}님

디스코드 아이디 ${esc(s.user_id)}

+${error ? `

${esc(error)}

` : ''} +
${status}

녹음된 내 목소리: ${stats.count}개 · ${fmtDur(stats.total_ms)}

+${stats.count ? `
${csrf}
` : ''}
+${consentForm} +
${csrf}
`, + ); + } + + async function oauthUser(code: string): Promise { + 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 { + 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('없는 페이지', '

없는 페이지입니다

처음으로

')); + } + } + + 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(); + }); + }); +} diff --git a/consent-recorder/test/consent.test.ts b/consent-recorder/test/consent.test.ts new file mode 100644 index 0000000..a11cd20 --- /dev/null +++ b/consent-recorder/test/consent.test.ts @@ -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((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((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((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) => + 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'); +}); diff --git a/consent-recorder/test/recorder.test.ts b/consent-recorder/test/recorder.test.ts new file mode 100644 index 0000000..648fa36 --- /dev/null +++ b/consent-recorder/test/recorder.test.ts @@ -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(); + 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 }); +}); diff --git a/consent-recorder/tsconfig.json b/consent-recorder/tsconfig.json new file mode 100644 index 0000000..9d7edb4 --- /dev/null +++ b/consent-recorder/tsconfig.json @@ -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"] +}