- /delete discards the in-progress utterance before deleting files - keep the current channel even when the bot itself fills it (joinable=false) - bind OAuth state to the browser via a short-lived cookie - reject consent submitted from a page showing an older consent version - regression tests for all four Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
178 lines
8.5 KiB
TypeScript
178 lines
8.5 KiB
TypeScript
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 { CONSENT_VERSION } from '../src/consent-text.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[] = [];
|
|
const events: string[] = [];
|
|
|
|
before(async () => {
|
|
tmp = fs.mkdtempSync(path.join(os.homedir(), '.tmp-consent-'));
|
|
// 가짜 디스코드 OAuth API
|
|
discord = http.createServer((req, res) => {
|
|
let body = '';
|
|
req.on('data', (c) => (body += c));
|
|
req.on('end', () => {
|
|
if (req.url === '/oauth2/token' && req.method === 'POST') {
|
|
const f = new URLSearchParams(body);
|
|
if (f.get('code') !== 'good-code' || f.get('client_secret') !== 'sec') return res.writeHead(400).end('{}');
|
|
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ access_token: 'at' }));
|
|
}
|
|
if (req.url === '/users/@me' && req.headers.authorization === 'Bearer at') {
|
|
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(USER));
|
|
}
|
|
res.writeHead(404).end();
|
|
});
|
|
});
|
|
await new Promise<void>((r) => discord.listen(0, '127.0.0.1', r));
|
|
const dport = (discord.address() as any).port;
|
|
store = new Store(path.join(tmp, 'consent.db'));
|
|
site = http.createServer();
|
|
await new Promise<void>((r) => site.listen(0, '127.0.0.1', r));
|
|
const port = (site.address() as any).port;
|
|
site.close();
|
|
base = `http://127.0.0.1:${port}`;
|
|
const cfg = loadConfig(
|
|
{ PUBLIC_URL: base, DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec', DATA_DIR: tmp, OPERATOR_NAME: '승한', DISCORD_API: `http://127.0.0.1:${dport}` },
|
|
false,
|
|
);
|
|
site = createSite(cfg, store, {
|
|
consentChanged: (id) => changed.push(id),
|
|
discardActive: (id) => events.push(`discard:${id}:${store.recordingStats(id).count}`),
|
|
recordingNow: () => null,
|
|
});
|
|
await new Promise<void>((r) => site.listen(port, '127.0.0.1', r));
|
|
});
|
|
|
|
after(() => {
|
|
site.close();
|
|
discord.close();
|
|
store.close();
|
|
fs.rmSync(tmp, { recursive: true, force: true });
|
|
});
|
|
|
|
const get = (p: string, cookie = '') => fetch(base + p, { redirect: 'manual', headers: cookie ? { cookie } : {} });
|
|
const post = (p: string, cookie: string, form: Record<string, string>) =>
|
|
fetch(base + p, { method: 'POST', redirect: 'manual', headers: { cookie, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form) });
|
|
|
|
async function login(): Promise<{ cookie: string; csrf: string }> {
|
|
const l = await get('/login');
|
|
assert.equal(l.status, 303);
|
|
const auth = new URL(l.headers.get('location')!);
|
|
assert.equal(auth.origin + auth.pathname, 'https://discord.com/oauth2/authorize');
|
|
assert.equal(auth.searchParams.get('scope'), 'identify');
|
|
assert.equal(auth.searchParams.get('redirect_uri'), `${base}/callback`);
|
|
const state = auth.searchParams.get('state')!;
|
|
const stateCookie = l.headers.get('set-cookie')!.split(';')[0];
|
|
assert.equal(stateCookie, `oauth_state=${state}`);
|
|
// 로그인을 시작하지 않은 브라우저(state 쿠키 없음 · 다른 값)에서 연 callback 은 거절 (state 는 그대로 남음)
|
|
assert.equal((await get(`/callback?code=good-code&state=${state}`)).status, 400);
|
|
assert.equal((await get(`/callback?code=good-code&state=${state}`, 'oauth_state=other')).status, 400);
|
|
const cb = await get(`/callback?code=good-code&state=${state}`, stateCookie);
|
|
assert.equal(cb.status, 303);
|
|
const cookie = cb.headers.get('set-cookie')!.split(';')[0];
|
|
assert.match(cookie, /^sid=/);
|
|
// state 는 한 번만 쓸 수 있다
|
|
assert.equal((await get(`/callback?code=good-code&state=${state}`, stateCookie)).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, 409);
|
|
assert.equal((await post('/consent', cookie, { csrf, version: 'old', self: '1', model: '1', age: '1' })).status, 409);
|
|
assert.equal(store.isConsented(USER.id), false);
|
|
const version = /name="version" value="([^"]+)"/.exec(await (await get('/', cookie)).text())![1];
|
|
assert.equal(version, CONSENT_VERSION);
|
|
assert.equal((await post('/consent', cookie, { csrf, version, 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초/);
|
|
// 파일 삭제: 진행 중인 녹음을 먼저 버린 뒤(그때는 아직 1개) 저장 파일을 지운다
|
|
assert.equal((await post('/delete', cookie, { csrf })).status, 303);
|
|
assert.deepEqual(events, [`discard:${USER.id}:1`]);
|
|
assert.equal(fs.existsSync(f), false);
|
|
fs.writeFileSync(f, 'x');
|
|
store.addRecording({ id: 'b', user_id: USER.id, guild_id: 'g', channel_id: 'c', started_at: 1, duration_ms: 1500, path: f });
|
|
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', 'delete_recordings', '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');
|
|
});
|