// Проверка прав на сервере: что может гость, читатель (VIEWER), редактор (EDITOR) и админ. // Создаёт временных пользователей через приглашения и удаляет их в конце. // Запуск: KB_EMAIL=админ KB_PASSWORD=пароль node scripts/check-roles.mjs [адрес сайта] const base = process.argv[2] ?? 'http://localhost:8200'; const json = { 'X-Requested-With': 'kb', 'Content-Type': 'application/json' }; let failed = 0; async function call(method, path, { cookie, body } = {}) { const res = await fetch(base + path, { method, headers: { ...json, ...(cookie ? { Cookie: cookie } : {}) }, body: body ? JSON.stringify(body) : undefined, }); const cookies = res.headers.getSetCookie?.().map((c) => c.split(';')[0]).join('; '); let data = null; try { data = await res.json(); } catch { /* пустой ответ */ } return { status: res.status, data, cookie: cookies }; } function expect(name, got, want) { const ok = Array.isArray(want) ? want.includes(got) : got === want; if (!ok) failed++; console.log(`${ok ? 'ok ' : 'FAIL'} ${name}: ${got}${ok ? '' : ` (ожидалось ${want})`}`); } const admin = (await call('POST', '/api/auth/login', { body: { email: process.env.KB_EMAIL, password: process.env.KB_PASSWORD, remember: false } })).cookie; if (!admin) throw new Error('Не удалось войти админом: задайте KB_EMAIL и KB_PASSWORD'); // Пользователи с ролями через приглашения const stamp = Date.now(); async function invited(role) { const inv = await call('POST', '/api/admin/invites', { cookie: admin, body: { role } }); const reg = await call('POST', `/api/auth/invite/${inv.data.token}`, { body: { name: `Проверка ${role}`, email: `check-${role.toLowerCase()}-${stamp}@example.com`, password: 'check-password-1' }, }); return { cookie: reg.cookie, id: reg.data.user.id }; } const viewer = await invited('VIEWER'); const editor = await invited('EDITOR'); const tree = (await call('GET', '/api/tree', { cookie: admin })).data; const art = tree.articles.find((a) => !a.pinned); const edit = (await call('GET', `/api/edit/articles/${art.slug}`, { cookie: admin })).data; const draftBody = { md: edit.md, meta: edit.meta }; console.log('--- гость'); expect('дерево пустое', (await call('GET', '/api/tree')).data.articles.length, 0); expect('статья', (await call('GET', `/api/articles/${art.slug}`)).status, 401); expect('картинки', (await fetch(`${base}/uploads/assets/shkon/fig-1.webp`)).status, 401); expect('сохранение черновика', (await call('PUT', `/api/edit/articles/${art.id}/draft`, { body: draftBody })).status, 401); expect('список пользователей', (await call('GET', '/api/admin/users')).status, 401); console.log('--- читатель (VIEWER)'); expect('статья', (await call('GET', `/api/articles/${art.slug}`, { cookie: viewer.cookie })).status, 200); expect('данные редактора', (await call('GET', `/api/edit/articles/${art.slug}`, { cookie: viewer.cookie })).status, 403); expect('сохранение черновика', (await call('PUT', `/api/edit/articles/${art.id}/draft`, { cookie: viewer.cookie, body: draftBody })).status, 403); expect('публикация', (await call('POST', `/api/edit/articles/${art.id}/publish`, { cookie: viewer.cookie, body: draftBody })).status, 403); expect('создание статьи', (await call('POST', '/api/edit/articles', { cookie: viewer.cookie, body: { title: 'x', sectionId: art.sectionId } })).status, 403); expect('список пользователей', (await call('GET', '/api/admin/users', { cookie: viewer.cookie })).status, 403); console.log('--- редактор (EDITOR)'); expect('данные редактора', (await call('GET', `/api/edit/articles/${art.slug}`, { cookie: editor.cookie })).status, 200); expect('сохранение черновика', (await call('PUT', `/api/edit/articles/${art.id}/draft`, { cookie: editor.cookie, body: draftBody })).status, 200); expect('сброс черновика', (await call('DELETE', `/api/edit/articles/${art.id}/draft`, { cookie: editor.cookie })).status, 204); expect('список пользователей', (await call('GET', '/api/admin/users', { cookie: editor.cookie })).status, 403); expect('создание раздела', (await call('POST', '/api/admin/sections', { cookie: editor.cookie, body: { name: 'x', spaceId: tree.spaces[0].id, code: 'X', color: 'ink' } })).status, 403); expect('удаление статьи', (await call('DELETE', `/api/edit/articles/${art.id}`, { cookie: editor.cookie })).status, 403); console.log('--- без заголовка X-Requested-With (CSRF)'); const noCsrf = await fetch(`${base}/api/auth/logout`, { method: 'POST', headers: { Cookie: viewer.cookie } }); expect('запрос отклонён', noCsrf.status, 403); console.log('--- блокировка'); expect('админ блокирует читателя', (await call('PATCH', `/api/admin/users/${viewer.id}`, { cookie: admin, body: { blocked: true } })).status, 200); expect('заблокированный не читает', (await call('GET', `/api/articles/${art.slug}`, { cookie: viewer.cookie })).status, 401); // Уборка for (const u of [viewer, editor]) await call('DELETE', `/api/admin/users/${u.id}`, { cookie: admin }); console.log(failed ? `\nНе прошло: ${failed}` : '\nПрава проверяются на сервере'); process.exit(failed ? 1 : 0);