앱 v1.2.1: 겜녹이 봇 토큰을 앱에 보내지 않고 사이트 서버가 봇을 대신 연결
- 사이트 서버: discord.js 로 디스코드 게이트웨이에 한 번 붙고(discord-source.ts), 로그인한 앱에 WS /app/bot/ws 로 중계(bot-broker.ts) · 앱이 보낸 op 4 는 지켜보는 서버의 음성채널 참여 · 나가기만 허용하고 필드를 다시 만들어 보낸다 · 디스코드가 준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)는 음성을 가진 앱에만 넘긴다. 음성은 앱 ↔ 디스코드로 바로 · 한 서버의 봇 음성은 마지막으로 요청한 앱이 가져가고 이전 앱은 taken. 이전 앱의 늦은 나가기 무시, 음성 가진 앱이 끊기면 봇을 뺀다 · 슬래시 명령은 서버가 받아 defer 후 그 서버를 지켜보는 앱으로 보낸다 · 등록 해제 · 로그아웃하면 그 유저의 중계 연결을 바로 끊는다 (4401), 30초마다 다시 확인 - /app/me 에서 botToken 제거. 앱은 v1.2.0 이 저장해 둔 봇 토큰을 시작할 때 지운다 - 앱: BotGateway 로 디스코드 연결을 분리 (RemoteGateway = 겜녹이 봇 서버 중계, LocalGateway = 다른 봇 토큰 직접 연결) Bot 은 discord.js 객체 대신 이 인터페이스만 쓴다. 중계가 로그인 만료를 알리면 바로 다시 확인해서 잠근다 - 로그인 확인: 잠그라는 응답(401 · 403)은 겹친 확인 때문에 늦게 와도 같은 토큰이면 따른다 (겹친 두 번째 확인이 401 을 받아 "등록되지 않은 아이디" 대신 "로그인 만료"로 잠기던 문제). 미등록 화면은 다시 확인해도 유지 - 테스트: 봇 중계 4건(토큰 미노출 · 음성 정보 전달 · 다른 PC 인계 · 명령 라우팅 · 해제 시 끊김), 겹친 확인 1건 실제 디스코드: voice-e2e GVR_E2E_RELAY=1 (서버 중계로 따라 들어가 녹음 · STT · 녹음 제외), login-e2e 19/19 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
231
site/server/package-lock.json
generated
231
site/server/package-lock.json
generated
@@ -10,6 +10,7 @@
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/static": "^8.2.0",
|
||||
"discord.js": "^14.27.0",
|
||||
"fastify": "^5.6.1",
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
@@ -21,6 +22,128 @@
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/builders": {
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",
|
||||
"integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",
|
||||
"dependencies": {
|
||||
"@discordjs/formatters": "^0.6.2",
|
||||
"@discordjs/util": "^1.2.0",
|
||||
"@sapphire/shapeshift": "^4.0.0",
|
||||
"discord-api-types": "^0.38.40",
|
||||
"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/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/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||
@@ -672,11 +795,40 @@
|
||||
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
|
||||
"integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="
|
||||
},
|
||||
"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/@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==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
@@ -685,11 +837,19 @@
|
||||
"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==",
|
||||
"dev": true,
|
||||
"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/abstract-logging": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
|
||||
@@ -839,6 +999,37 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/discord-api-types": {
|
||||
"version": "0.38.56",
|
||||
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.56.tgz",
|
||||
"integrity": "sha512-Hti4RZsGvF5C7SM8rF2MDHtIm0Hyfrlk84GpEA29nj91tvVVMvX+oQSCodu10t2ZcjFGofq8TX0YyC04B2E69Q=="
|
||||
},
|
||||
"node_modules/discord.js": {
|
||||
"version": "14.27.0",
|
||||
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.27.0.tgz",
|
||||
"integrity": "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==",
|
||||
"dependencies": {
|
||||
"@discordjs/builders": "^1.14.1",
|
||||
"@discordjs/collection": "1.5.3",
|
||||
"@discordjs/formatters": "^0.6.2",
|
||||
"@discordjs/rest": "^2.6.2",
|
||||
"@discordjs/util": "^1.2.0",
|
||||
"@discordjs/ws": "^1.2.3",
|
||||
"@sapphire/snowflake": "3.5.5",
|
||||
"discord-api-types": "^0.38.49",
|
||||
"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.25.12",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
|
||||
@@ -1156,6 +1347,16 @@
|
||||
"set-cookie-parser": "^3.0.1"
|
||||
}
|
||||
},
|
||||
"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/lru-cache": {
|
||||
"version": "11.5.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
|
||||
@@ -1164,6 +1365,11 @@
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"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/mime": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
|
||||
@@ -1487,6 +1693,16 @@
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"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.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
|
||||
},
|
||||
"node_modules/tsx": {
|
||||
"version": "4.23.15",
|
||||
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz",
|
||||
@@ -1975,11 +2191,18 @@
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "6.29.0",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz",
|
||||
"integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==",
|
||||
"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==",
|
||||
"dev": true
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/static": "^8.2.0",
|
||||
"discord.js": "^14.27.0",
|
||||
"fastify": "^5.6.1",
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
// 2) 브라우저: GET /auth/app/start/:id → 디스코드 OAuth → /auth/discord/callback (사이트 로그인과 같은 콜백, state 가 "app." 으로 시작)
|
||||
// 3) 콜백: 등록된 아이디면 앱 토큰 발급, 아니면 "등록되지 않은 아이디" 결과를 남긴다
|
||||
// 4) 앱: POST /auth/app/poll {id, secret} 로 결과를 받아 간다 (한 번만)
|
||||
// 5) 앱: GET /app/me (Bearer 토큰) 로 주기적으로 확인. 등록 해제되면 403 → 앱이 잠긴다. 겜녹이 봇 토큰은 여기서만 내려준다
|
||||
// 5) 앱: GET /app/me (Bearer 토큰) 로 주기적으로 확인. 등록 해제되면 403 → 앱이 잠긴다
|
||||
// 겜녹이 봇 토큰은 앱에 보내지 않는다. 봇은 서버가 연결하고 앱은 /app/bot/ws 로 중계받는다 (bot-broker.ts)
|
||||
import crypto from 'node:crypto';
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import type { AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
|
||||
@@ -24,8 +25,12 @@ interface Pending {
|
||||
|
||||
const sha = (s: string) => crypto.createHash('sha256').update(s).digest();
|
||||
|
||||
export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean }) {
|
||||
export function registerAppAuth(
|
||||
app: FastifyInstance,
|
||||
deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean; onRevoke?: (by: { userId?: string; token?: string }) => void },
|
||||
) {
|
||||
const { cfg, store, discord, secure } = deps;
|
||||
const revoke = (by: { userId?: string; token?: string }) => deps.onRevoke?.(by);
|
||||
const pending = new Map<string, Pending>();
|
||||
|
||||
const roleOf = (id: string): AppRole | null => (cfg.superAdmins.includes(id) ? 'superadmin' : (store.appUser(id)?.role ?? null));
|
||||
@@ -114,6 +119,7 @@ export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store
|
||||
const role = roleOf(s.userId);
|
||||
if (!role) {
|
||||
store.deleteAppSession(token);
|
||||
revoke({ token });
|
||||
reply.code(403).send({ error: 'not_registered', message: '등록되지 않은 아이디입니다', user: userInfo(s.userId) });
|
||||
return null;
|
||||
}
|
||||
@@ -126,12 +132,15 @@ export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store
|
||||
const user = userInfo(a.id);
|
||||
const ver = String(req.headers['x-gvr-version'] || '').slice(0, 20) || null;
|
||||
store.touchAppUser(a.id, { version: ver, name: user.name, avatar: user.avatar });
|
||||
return { user, role: a.role, botToken: cfg.botToken || null, serverTime: Date.now() } satisfies AppMe;
|
||||
return { user, role: a.role, serverTime: Date.now() } satisfies AppMe;
|
||||
});
|
||||
|
||||
app.post('/auth/app/logout', async (req) => {
|
||||
const t = bearer(req);
|
||||
if (t) store.deleteAppSession(t);
|
||||
if (t) {
|
||||
store.deleteAppSession(t);
|
||||
revoke({ token: t });
|
||||
}
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
@@ -203,11 +212,19 @@ export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store
|
||||
if (!a) return;
|
||||
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
|
||||
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
|
||||
revoke({ userId: req.params.id });
|
||||
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
|
||||
return { users: rows() };
|
||||
});
|
||||
|
||||
return { completeLogin };
|
||||
/** 겜녹이 봇 중계 연결 확인: 살아 있는 앱 토큰 + 등록된 아이디 */
|
||||
const verifyToken = (token: string): { userId: string; role: AppRole } | null => {
|
||||
const s = store.appSession(token);
|
||||
const r = s ? roleOf(s.userId) : null;
|
||||
return s && r ? { userId: s.userId, role: r } : null;
|
||||
};
|
||||
|
||||
return { completeLogin, verifyToken };
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
||||
|
||||
@@ -6,6 +6,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Config } from './config.js';
|
||||
import { registerAppAuth } from './app-auth.js';
|
||||
import { BotBroker, type BotSource } from './bot-broker.js';
|
||||
import { avatarUrl, DiscordApi } from './discord.js';
|
||||
import { RelayHub } from './relay.js';
|
||||
import { ServerStore, type Session } from './store.js';
|
||||
@@ -13,14 +14,17 @@ import { ServerStore, type Session } from './store.js';
|
||||
const SID = 'gvr_sid';
|
||||
const RECHECK_MS = 10 * 60000;
|
||||
|
||||
export async function buildServer(cfg: Config) {
|
||||
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
|
||||
export async function buildServer(cfg: Config, opts: { botSource?: BotSource } = {}) {
|
||||
const app = Fastify({ logger: { level: process.env.LOG_LEVEL || 'info' }, trustProxy: true, bodyLimit: 1024 * 1024, forceCloseConnections: true });
|
||||
const store = new ServerStore(cfg.dataDir);
|
||||
const hub = new RelayHub(store);
|
||||
const discord = new DiscordApi(cfg);
|
||||
await app.register(cookie, { secret: cfg.sessionSecret });
|
||||
const secure = cfg.publicUrl.startsWith('https://');
|
||||
const appAuth = registerAppAuth(app, { cfg, store, discord, secure });
|
||||
let broker: BotBroker | null = null;
|
||||
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
|
||||
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log);
|
||||
|
||||
const allowedGuilds = (): string[] => {
|
||||
const g = new Set(cfg.allowedGuilds);
|
||||
@@ -197,6 +201,20 @@ export async function buildServer(cfg: Config) {
|
||||
hub.deviceWss.handleUpgrade(req, socket, head, (ws) => hub.attachDevice(ws, d.id));
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/app/bot/ws') {
|
||||
if (!broker) {
|
||||
socket.write('HTTP/1.1 503 Service Unavailable\r\n\r\n');
|
||||
return socket.destroy();
|
||||
}
|
||||
const a = broker.authenticate(req);
|
||||
if (!a) {
|
||||
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
||||
return socket.destroy();
|
||||
}
|
||||
const b = broker;
|
||||
b.wss.handleUpgrade(req, socket, head, (ws) => b.attach(ws, a));
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/ws') {
|
||||
const fakeReq: any = { cookies: parseCookies(String(req.headers.cookie || '')), unsignCookie: (v: string) => app.unsignCookie(v), log: app.log };
|
||||
const s = await getSession(fakeReq);
|
||||
@@ -213,12 +231,13 @@ export async function buildServer(cfg: Config) {
|
||||
// 서버를 닫기 전에 WebSocket 을 먼저 끊는다 (안 끊으면 close 가 연결이 끝나길 기다리며 멈춘다)
|
||||
app.addHook('preClose', async () => {
|
||||
hub.close();
|
||||
broker?.close();
|
||||
});
|
||||
app.addHook('onClose', async () => {
|
||||
store.flush();
|
||||
});
|
||||
|
||||
return { app, store, hub };
|
||||
return { app, store, hub, broker };
|
||||
}
|
||||
|
||||
function parseCookies(h: string): Record<string, string> {
|
||||
|
||||
240
site/server/src/bot-broker.ts
Normal file
240
site/server/src/bot-broker.ts
Normal file
@@ -0,0 +1,240 @@
|
||||
// 겜녹이 봇 중계. 봇 토큰은 이 서버에만 있고, 앱(exe)에는 절대 보내지 않는다.
|
||||
// - 서버가 디스코드 게이트웨이에 한 번 붙는다 (BotSource). 앱은 /app/bot/ws 로 붙어 필요한 정보만 받는다
|
||||
// - 음성채널 참여: 앱의 @discordjs/voice 어댑터가 보낸 op 4 를 검사해서 서버가 대신 보내고,
|
||||
// 디스코드가 돌려준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)를 그 앱에만 넘긴다.
|
||||
// 음성 데이터는 앱 ↔ 디스코드 음성 서버로 바로 오간다 (이 서버를 거치지 않음)
|
||||
// - 한 디스코드 서버에서 봇은 음성채널 하나에만 있을 수 있다 → 마지막으로 참여를 요청한 앱이 가져가고, 이전 앱에는 taken
|
||||
import crypto from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import { WebSocket, WebSocketServer } from 'ws';
|
||||
import type { AppRole, BotGwChannel, BotGwFromApp, BotGwGuild, BotGwMember, BotGwToApp } from '@gvr/shared';
|
||||
|
||||
export interface BotVoiceEvent {
|
||||
guildId: string;
|
||||
member: BotGwMember;
|
||||
oldChannelId: string | null;
|
||||
newChannelId: string | null;
|
||||
channel: BotGwChannel | null;
|
||||
}
|
||||
export interface BotCommand {
|
||||
name: string;
|
||||
guildId: string;
|
||||
user: BotGwMember;
|
||||
voiceChannel: BotGwChannel | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 디스코드 게이트웨이 쪽 (실서버: discord-source.ts 의 discord.js, 테스트: 가짜).
|
||||
* 이벤트: 'ready', 'guilds', 'voiceState' (BotVoiceEvent), 'command' (BotCommand, respond(content))
|
||||
*/
|
||||
export interface BotSource extends EventEmitter {
|
||||
me(): BotGwMember | null;
|
||||
guilds(): BotGwGuild[];
|
||||
/** 음성채널 목록과 음성채널에 있는 사람 */
|
||||
snapshot(guildId: string): { guild: BotGwGuild; channels: BotGwChannel[]; voice: { member: BotGwMember; channelId: string }[] } | null;
|
||||
isVoiceChannel(guildId: string, channelId: string): boolean;
|
||||
members(guildId: string): Promise<BotGwMember[]>;
|
||||
registerCommands(guildId: string): Promise<void>;
|
||||
/** 서버마다 하나. 디스코드가 보낸 봇 자신의 음성 접속 정보를 handlers 로 넘기고, send 로 op 4 를 보낸다 */
|
||||
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }): { send: (payload: any) => boolean };
|
||||
}
|
||||
|
||||
interface Conn {
|
||||
id: string;
|
||||
ws: WebSocket;
|
||||
token: string;
|
||||
userId: string;
|
||||
guildId: string | null;
|
||||
at: number;
|
||||
}
|
||||
|
||||
const CMD_TIMEOUT_MS = 25000;
|
||||
const SNOWFLAKE = /^\d{17,20}$/;
|
||||
|
||||
export class BotBroker {
|
||||
readonly wss = new WebSocketServer({ noServer: true, maxPayload: 256 * 1024 });
|
||||
private conns = new Set<Conn>();
|
||||
/** 서버별로 지금 봇 음성 연결을 가진 앱 */
|
||||
private owners = new Map<string, Conn>();
|
||||
private adapters = new Map<string, { send: (payload: any) => boolean }>();
|
||||
private commandsDone = new Set<string>();
|
||||
private cmds = new Map<string, (content: string | null) => void>();
|
||||
private timer: NodeJS.Timeout;
|
||||
|
||||
constructor(
|
||||
private source: BotSource,
|
||||
/** 앱 토큰 확인 (등록 해제 · 로그아웃이면 null) */
|
||||
private verify: (token: string) => { userId: string; role: AppRole } | null,
|
||||
private log: { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void },
|
||||
) {
|
||||
source.on('ready', () => {
|
||||
const me = source.me();
|
||||
if (me) for (const c of this.conns) this.send(c, { t: 'ready', me, guilds: source.guilds() });
|
||||
});
|
||||
source.on('guilds', () => this.broadcast({ t: 'guilds', guilds: source.guilds() }));
|
||||
source.on('voiceState', (e: BotVoiceEvent) => {
|
||||
for (const c of this.conns) if (c.guildId === e.guildId) this.send(c, { t: 'voiceState', ...e });
|
||||
});
|
||||
source.on('command', (cmd: BotCommand, respond: (content: string) => void) => void this.onCommand(cmd).then(respond));
|
||||
// 등록 해제 · 로그아웃된 연결은 30초 안에 끊는다 (해제 · 로그아웃 API 는 kick 으로 바로 끊는다)
|
||||
this.timer = setInterval(() => {
|
||||
for (const c of this.conns) if (!this.verify(c.token)) c.ws.close(4401, 'unauthorized');
|
||||
for (const c of this.conns) if (c.ws.readyState === WebSocket.OPEN) c.ws.ping();
|
||||
}, 30000);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
clearInterval(this.timer);
|
||||
for (const c of this.conns) c.ws.terminate();
|
||||
}
|
||||
|
||||
/** 이 유저(또는 이 토큰)의 연결을 바로 끊는다 */
|
||||
kick(by: { userId?: string; token?: string }): void {
|
||||
for (const c of this.conns) if ((by.userId && c.userId === by.userId) || (by.token && c.token === by.token)) c.ws.close(4401, 'unauthorized');
|
||||
}
|
||||
|
||||
authenticate(req: IncomingMessage): { token: string; userId: string } | null {
|
||||
const token = /^Bearer\s+(\S+)$/i.exec(String(req.headers.authorization || ''))?.[1] ?? '';
|
||||
const a = token ? this.verify(token) : null;
|
||||
return a ? { token, userId: a.userId } : null;
|
||||
}
|
||||
|
||||
attach(ws: WebSocket, a: { token: string; userId: string }): void {
|
||||
const c: Conn = { id: crypto.randomBytes(6).toString('hex'), ws, token: a.token, userId: a.userId, guildId: null, at: Date.now() };
|
||||
this.conns.add(c);
|
||||
this.log.info({ user: a.userId, conn: c.id }, '겜녹이 봇 중계 연결');
|
||||
const me = this.source.me();
|
||||
if (me) this.send(c, { t: 'ready', me, guilds: this.source.guilds() });
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (isBinary || !this.conns.has(c)) return;
|
||||
let m: BotGwFromApp;
|
||||
try {
|
||||
m = JSON.parse(String(data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.onMessage(c, m);
|
||||
} catch (e) {
|
||||
this.log.warn(e, '봇 중계 메시지 처리 실패');
|
||||
}
|
||||
});
|
||||
const drop = () => this.drop(c);
|
||||
ws.on('close', drop);
|
||||
ws.on('error', drop);
|
||||
}
|
||||
|
||||
private drop(c: Conn): void {
|
||||
if (!this.conns.delete(c)) return;
|
||||
this.log.info({ user: c.userId, conn: c.id }, '겜녹이 봇 중계 끊김');
|
||||
// 앱이 꺼지거나 끊기면 봇을 음성채널에서 뺀다 (서버 연결은 계속 살아 있어서 그냥 두면 계속 남는다)
|
||||
for (const [g, o] of this.owners) {
|
||||
if (o !== c) continue;
|
||||
this.owners.delete(g);
|
||||
this.adapters.get(g)?.send({ op: 4, d: { guild_id: g, channel_id: null, self_mute: false, self_deaf: false } });
|
||||
}
|
||||
}
|
||||
|
||||
private send(c: Conn, m: BotGwToApp): void {
|
||||
if (c.ws.readyState === WebSocket.OPEN) c.ws.send(JSON.stringify(m));
|
||||
}
|
||||
private broadcast(m: BotGwToApp): void {
|
||||
for (const c of this.conns) this.send(c, m);
|
||||
}
|
||||
|
||||
private adapter(guildId: string) {
|
||||
let a = this.adapters.get(guildId);
|
||||
if (!a) {
|
||||
a = this.source.voiceAdapter(guildId, {
|
||||
server: (d) => {
|
||||
const o = this.owners.get(guildId);
|
||||
if (o) this.send(o, { t: 'vserver', guildId, data: d });
|
||||
},
|
||||
state: (d) => {
|
||||
const o = this.owners.get(guildId);
|
||||
if (o) this.send(o, { t: 'vstate', guildId, data: d });
|
||||
},
|
||||
});
|
||||
this.adapters.set(guildId, a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
private onMessage(c: Conn, m: BotGwFromApp): void {
|
||||
switch (m.t) {
|
||||
case 'watch': {
|
||||
const snap = SNOWFLAKE.test(String(m.guildId)) ? this.source.snapshot(m.guildId) : null;
|
||||
if (!snap) return;
|
||||
c.guildId = m.guildId;
|
||||
c.at = Date.now();
|
||||
this.send(c, { t: 'guild', ...snap });
|
||||
if (m.commands && !this.commandsDone.has(m.guildId)) {
|
||||
this.commandsDone.add(m.guildId);
|
||||
this.source.registerCommands(m.guildId).catch((e) => {
|
||||
this.commandsDone.delete(m.guildId);
|
||||
this.log.warn(e, '슬래시 명령 등록 실패');
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'voice': {
|
||||
// 앱이 보낼 수 있는 건 "지켜보는 서버의 음성채널 참여 · 나가기" 뿐이다
|
||||
const g = c.guildId;
|
||||
const d = m.payload?.d;
|
||||
if (!g || m.guildId !== g || m.payload?.op !== 4 || d?.guild_id !== g) return;
|
||||
const ch = d.channel_id === null ? null : String(d.channel_id);
|
||||
if (ch !== null && !this.source.isVoiceChannel(g, ch)) return;
|
||||
const owner = this.owners.get(g);
|
||||
if (ch === null) {
|
||||
// 이미 다른 PC 가 가져간 봇을 이전 PC 가 빼지 못하게
|
||||
if (owner !== c) return;
|
||||
this.owners.delete(g);
|
||||
} else if (owner !== c) {
|
||||
if (owner) this.send(owner, { t: 'taken', guildId: g });
|
||||
this.owners.set(g, c);
|
||||
}
|
||||
this.adapter(g).send({ op: 4, d: { guild_id: g, channel_id: ch, self_mute: !!d.self_mute, self_deaf: !!d.self_deaf } });
|
||||
return;
|
||||
}
|
||||
case 'cmd_res': {
|
||||
// 여러 PC 로 보낸 명령은 첫 응답만 쓴다
|
||||
this.cmds.get(m.id)?.(String(m.content ?? '').slice(0, 1800));
|
||||
return;
|
||||
}
|
||||
case 'req': {
|
||||
if (m.op !== 'members' || m.guildId !== c.guildId) return this.send(c, { t: 'res', id: m.id, ok: false, error: 'forbidden' });
|
||||
this.source.members(m.guildId).then(
|
||||
(data) => this.send(c, { t: 'res', id: m.id, ok: true, data }),
|
||||
(e) => this.send(c, { t: 'res', id: m.id, ok: false, error: String(e?.message ?? e) }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 슬래시 명령을 맞는 앱으로 보내고 첫 응답을 돌려준다 */
|
||||
private async onCommand(cmd: BotCommand): Promise<string> {
|
||||
const here = [...this.conns].filter((c) => c.guildId === cmd.guildId).sort((a, b) => b.at - a.at);
|
||||
if (!here.length) return '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.';
|
||||
const owner = this.owners.get(cmd.guildId);
|
||||
const mine = here.find((c) => c.userId === cmd.user.id);
|
||||
let targets: Conn[];
|
||||
if (cmd.name === '녹음제외' || cmd.name === '녹음참여') targets = here; // 각 PC 기록에 모두 남긴다
|
||||
else if (cmd.name === '녹음종료') targets = owner && here.includes(owner) ? [owner] : [];
|
||||
else targets = [mine ?? (owner && here.includes(owner) ? owner : here[0])];
|
||||
if (!targets.length) return '지금은 녹음 중이 아닙니다.';
|
||||
const id = crypto.randomBytes(8).toString('hex');
|
||||
const content = await new Promise<string | null>((resolve) => {
|
||||
const t = setTimeout(() => resolve(null), CMD_TIMEOUT_MS);
|
||||
this.cmds.set(id, (v) => {
|
||||
clearTimeout(t);
|
||||
this.cmds.delete(id);
|
||||
resolve(v);
|
||||
});
|
||||
for (const c of targets) this.send(c, { t: 'cmd', id, ...cmd });
|
||||
});
|
||||
this.cmds.delete(id);
|
||||
return content ?? '겜녹이 앱이 응답하지 않습니다. 잠시 뒤 다시 시도해 주세요.';
|
||||
}
|
||||
}
|
||||
114
site/server/src/discord-source.ts
Normal file
114
site/server/src/discord-source.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
// 서버의 겜녹이 봇 디스코드 연결 (discord.js). bot-broker.ts 의 BotSource 구현
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
|
||||
import type { BotGwChannel, BotGwGuild, BotGwMember } from '@gvr/shared';
|
||||
import type { BotCommand, BotSource, BotVoiceEvent } from './bot-broker.js';
|
||||
|
||||
/** 앱과 같은 슬래시 명령 (app/src/core/discord/bot.ts COMMANDS) */
|
||||
export const COMMANDS = [
|
||||
{ name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' },
|
||||
{ name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' },
|
||||
{ name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' },
|
||||
{ name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' },
|
||||
];
|
||||
|
||||
const member = (m: GuildMember): BotGwMember => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }), bot: m.user.bot });
|
||||
const guild = (g: Guild): BotGwGuild => ({ id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) });
|
||||
const isVoice = (c: { type: ChannelType } | null | undefined): c is VoiceBasedChannel => !!c && (c.type === ChannelType.GuildVoice || c.type === ChannelType.GuildStageVoice);
|
||||
|
||||
export class DiscordSource extends EventEmitter implements BotSource {
|
||||
readonly client: Client;
|
||||
|
||||
constructor(private log: { info: (o: any, m?: string) => void; error: (o: any, m?: string) => void }) {
|
||||
super();
|
||||
const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers] });
|
||||
this.client = c;
|
||||
c.on(Events.ClientReady, () => {
|
||||
log.info({ bot: c.user?.tag, guilds: c.guilds.cache.size }, '겜녹이 봇 디스코드 연결');
|
||||
this.emit('ready');
|
||||
});
|
||||
c.on(Events.GuildCreate, () => this.emit('guilds'));
|
||||
c.on(Events.GuildDelete, () => this.emit('guilds'));
|
||||
c.on(Events.Error, (e) => log.error(e, '디스코드 오류'));
|
||||
c.on(Events.VoiceStateUpdate, (o, n) => {
|
||||
const m = n.member ?? o.member;
|
||||
if (!m) return;
|
||||
const ch = n.channel;
|
||||
const e: BotVoiceEvent = { guildId: n.guild.id, member: member(m), oldChannelId: o.channelId, newChannelId: n.channelId, channel: ch ? { id: ch.id, name: ch.name } : null };
|
||||
this.emit('voiceState', e);
|
||||
});
|
||||
c.on(Events.InteractionCreate, async (i) => {
|
||||
if (!i.isChatInputCommand() || !i.guildId || !COMMANDS.some((x) => x.name === i.commandName)) return;
|
||||
try {
|
||||
await i.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
} catch (e) {
|
||||
log.error(e, '명령 응답 실패');
|
||||
return;
|
||||
}
|
||||
const m = i.guild?.members.cache.get(i.user.id) ?? (await i.guild?.members.fetch(i.user.id).catch(() => null)) ?? null;
|
||||
const vc = m?.voice.channel ?? null;
|
||||
const cmd: BotCommand = {
|
||||
name: i.commandName,
|
||||
guildId: i.guildId,
|
||||
user: m ? member(m) : { id: i.user.id, name: i.user.globalName || i.user.username, avatar: i.user.displayAvatarURL({ size: 128 }), bot: i.user.bot },
|
||||
voiceChannel: vc ? { id: vc.id, name: vc.name } : null,
|
||||
};
|
||||
this.emit('command', cmd, (content: string) => void i.editReply(content).catch((e) => log.error(e, '명령 응답 실패')));
|
||||
});
|
||||
}
|
||||
|
||||
login(token: string): Promise<string> {
|
||||
return this.client.login(token);
|
||||
}
|
||||
async destroy(): Promise<void> {
|
||||
await this.client.destroy();
|
||||
}
|
||||
|
||||
me(): BotGwMember | null {
|
||||
const u = this.client.isReady() ? this.client.user : null;
|
||||
return u ? { id: u.id, name: u.username, avatar: u.displayAvatarURL({ size: 128 }), bot: true } : null;
|
||||
}
|
||||
guilds(): BotGwGuild[] {
|
||||
return [...this.client.guilds.cache.values()].map(guild);
|
||||
}
|
||||
snapshot(guildId: string) {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return null;
|
||||
const channels: BotGwChannel[] = [];
|
||||
const voice: { member: BotGwMember; channelId: string }[] = [];
|
||||
for (const ch of g.channels.cache.values()) {
|
||||
if (!isVoice(ch)) continue;
|
||||
channels.push({ id: ch.id, name: ch.name });
|
||||
for (const m of ch.members.values()) voice.push({ member: member(m), channelId: ch.id });
|
||||
}
|
||||
return { guild: guild(g), channels, voice };
|
||||
}
|
||||
isVoiceChannel(guildId: string, channelId: string): boolean {
|
||||
const ch = this.client.guilds.cache.get(guildId)?.channels.cache.get(channelId);
|
||||
return isVoice(ch);
|
||||
}
|
||||
async members(guildId: string): Promise<BotGwMember[]> {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return [];
|
||||
const ms = await g.members.fetch().catch(() => g.members.cache);
|
||||
return [...ms.values()].map(member);
|
||||
}
|
||||
async registerCommands(guildId: string): Promise<void> {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return;
|
||||
await g.commands.set(COMMANDS);
|
||||
this.log.info({ guild: guildId }, '슬래시 명령 등록');
|
||||
}
|
||||
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }) {
|
||||
// discord.js 가 @discordjs/voice 용으로 주는 어댑터를 그대로 쓴다. 봇 자신의 음성 정보만 handlers 로 온다
|
||||
this.client.voice.adapters.set(guildId, { onVoiceServerUpdate: handlers.server, onVoiceStateUpdate: handlers.state, destroy: () => undefined });
|
||||
return {
|
||||
send: (payload: any) => {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return false;
|
||||
g.shard.send(payload);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
import { buildServer } from './app.js';
|
||||
import { loadConfig } from './config.js';
|
||||
import { DiscordSource } from './discord-source.js';
|
||||
|
||||
const cfg = loadConfig();
|
||||
const { app } = await buildServer(cfg);
|
||||
// 겜녹이 봇은 이 서버만 디스코드에 연결한다 (봇 토큰은 앱에 보내지 않는다). BOT_GATEWAY=0 이면 끈다
|
||||
let log: { info: (o: any, m?: string) => void; error: (o: any, m?: string) => void } = { info: () => undefined, error: (o, m) => console.error(m, o) };
|
||||
const botSource = process.env.BOT_GATEWAY === '0' ? undefined : new DiscordSource({ info: (o, m) => log.info(o, m), error: (o, m) => log.error(o, m) });
|
||||
const { app } = await buildServer(cfg, { botSource });
|
||||
log = app.log;
|
||||
await app.listen({ host: cfg.host, port: cfg.port });
|
||||
if (botSource) {
|
||||
// 디스코드에 못 붙어도 사이트는 계속 돈다 (discord.js 가 알아서 다시 연결)
|
||||
botSource.login(cfg.botToken).catch((e) => app.log.error(e, '겜녹이 봇 디스코드 연결 실패'));
|
||||
}
|
||||
const stop = async () => {
|
||||
await app.close();
|
||||
await botSource?.destroy();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', stop);
|
||||
|
||||
@@ -85,9 +85,9 @@ test('앱 로그인: 최고 관리자는 바로 로그인, 미등록 아이디
|
||||
assert.equal(sup.status, 200);
|
||||
assert.equal(sup.r.state, 'ok');
|
||||
assert.equal(sup.r.role, 'superadmin');
|
||||
const meSup = (await (await s.me(sup.r.token)).json()) as any;
|
||||
assert.equal(meSup.role, 'superadmin');
|
||||
assert.equal(meSup.botToken, 'bot-token', '등록된 유저에게만 겜녹이 봇 토큰을 내려준다');
|
||||
const meText = await (await s.me(sup.r.token)).text();
|
||||
assert.equal(JSON.parse(meText).role, 'superadmin');
|
||||
assert.ok(!meText.includes('bot-token') && !meText.includes('botToken'), '봇 토큰은 등록된 유저에게도 보내지 않는다 (서버가 봇을 대신 연결)');
|
||||
|
||||
// 미등록 아이디
|
||||
const no = await s.login(STRANGER);
|
||||
|
||||
Reference in New Issue
Block a user