techtools
Головна / portal / src / comments / routes.ts

routes.ts

TypeScript · 265 рядків

1// Маршрути коментарів: вхід / реєстрація / вихід, підтвердження користувачів, сторінка «Коментарі», API.
2//   GET  /api/me                          хто я
3//   GET  /api/comments?path=&state=&author=   список (читати може будь-хто)
4//   POST /api/comments                    новий коментар (після входу й підтвердження)
5//   GET  /api/comments/C-12               один коментар; /context — уривок тексту з коміту коментаря («як було»)
6//   POST /api/comments/C-12/close         {answer, where, commit} — Claude чи адмін
7//   POST /api/comments/C-12/reopen        {text}
8//   POST /api/comments/C-12/anchor        {commit, blob, quote, prefix, suffix, heading} — переприв'язати
9//   POST /api/comments/C-12/edit          {text} — автор, поки коментар відкритий
10//   GET  /api/comments-export             уся база JSON (резервна копія; Claude чи адмін)
11import type { IncomingMessage, ServerResponse } from 'node:http'
12import { resolveRepoPath } from '../repo.ts'
13import { esc, layout, plainText } from '../render.ts'
14import { canComment, canResolve, checkPassword, currentUser, ensureDefaultAdmin, hashPassword, isAdmin, login, logout, sameOrigin } from './auth.ts'
15import { comments, users, type Comment, type State, type User } from './db.ts'
16import { privateFile, show } from './git.ts'
17
18type Res = ServerResponse
19const JSON_T = 'application/json; charset=utf-8'
20
21function json(res: Res, status: number, body: unknown) {
22  res.writeHead(status, { 'content-type': JSON_T, 'cache-control': 'no-cache' })
23  res.end(JSON.stringify(body))
24}
25function html(res: Res, status: number, body: string) {
26  res.writeHead(status, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' })
27  res.end(body)
28}
29function redirect(res: Res, to: string) { res.writeHead(303, { location: to }); res.end() }
30
31async function body(req: IncomingMessage): Promise<Record<string, any>> {
32  let size = 0
33  const chunks: Buffer[] = []
34  for await (const c of req) { size += c.length; if (size > 256_000) throw new Error('too large'); chunks.push(c) }
35  const text = Buffer.concat(chunks).toString('utf8')
36  if ((req.headers['content-type'] ?? '').includes('application/json')) return text ? JSON.parse(text) : {}
37  return Object.fromEntries(new URLSearchParams(text))
38}
39
40const str = (v: unknown, max: number) => (typeof v === 'string' ? v : '').slice(0, max)
41/** Документи, які можна коментувати: research/ і doc/, лише .md. */
42export const commentable = (path: string) => /^(research|doc)\/.+\.md$/.test(path) && (resolveRepoPath('/' + path)?.rel === path || !!privateFile(path))
43
44export const date = (iso: string) => iso ? new Date(iso).toLocaleString('uk-UA', { timeZone: 'Europe/Kyiv', day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : ''
45
46// ── сторінки входу
47
48function authPage(title: string, form: string, note = '') {
49  return layout({ title, rel: null, main: `<div class="auth"><h1>${esc(title)}</h1>${note ? `<p class="note">${note}</p>` : ''}${form}</div>` })
50}
51
52const NAME_RE = /^[\p{L}\p{N} ._-]{2,40}$/u
53
54function loginForm(next: string, name = '') {
55  return `<form method="post" action="/login" class="auth-form">
56    <input type="hidden" name="next" value="${esc(next)}">
57    <label>Ім'я <input name="name" value="${esc(name)}" autocomplete="username" required autofocus></label>
58    <label>Пароль <input name="pass" type="password" autocomplete="current-password" required></label>
59    <button class="btn" type="submit">Увійти</button>
60    <p class="muted">Немає облікового запису? <a href="/register?next=${encodeURIComponent(next)}">Зареєструватися</a></p>
61  </form>`
62}
63function registerForm(next: string, name = '') {
64  return `<form method="post" action="/register" class="auth-form">
65    <input type="hidden" name="next" value="${esc(next)}">
66    <label>Ім'я (так його бачитимуть під коментарями) <input name="name" value="${esc(name)}" autocomplete="username" required autofocus pattern="[\\p{L}\\p{N} ._\\-]{2,40}"></label>
67    <label>Пароль (не менше 8 символів) <input name="pass" type="password" autocomplete="new-password" minlength="8" required></label>
68    <button class="btn" type="submit">Зареєструватися</button>
69    <p class="muted">Коментувати можна після того, як адміністратор підтвердить обліковий запис.</p>
70  </form>`
71}
72const safeNext = (n: unknown) => typeof n === 'string' && n.startsWith('/') && !n.startsWith('//') ? n : '/'
73
74// ── сторінка користувачів (адмін)
75
76async function usersPage(me: User, note = '') {
77  const rows = users.all().map(u => `<tr${u.approved ? '' : ' class="pending"'}>
78    <td><b>${esc(u.name)}</b></td><td>${u.role === 'admin' ? 'адміністратор' : u.role === 'bot' ? 'програма (токен)' : 'користувач'}</td>
79    <td>${u.approved ? '<span class="badge ok">підтверджено</span>' : '<span class="badge draft">чекає</span>'}</td><td class="muted">${date(u.created_at)}</td>
80    <td>${u.id === me.id ? '<span class="muted">це ви</span>' : `<form method="post" action="/users" class="inline">
81      <input type="hidden" name="id" value="${u.id}">
82      ${u.approved ? '<button name="do" value="block" class="btn ghost">Заблокувати</button>' : '<button name="do" value="approve" class="btn">Підтвердити</button>'}
83      ${u.role === 'user' && u.approved ? '<button name="do" value="admin" class="btn ghost">Зробити адміном</button>' : ''}
84      ${u.role === 'admin' ? '<button name="do" value="user" class="btn ghost">Зняти адміна</button>' : ''}
85      ${!u.approved ? '<button name="do" value="remove" class="btn ghost">Видалити</button>' : ''}
86    </form>`}</td></tr>`).join('')
87  return layout({ title: 'Користувачі', rel: null, main: `<h1>Користувачі порталу</h1>${note ? `<p class="note">${note}</p>` : ''}
88    <p class="muted">Реєструються самі; коментувати можуть після підтвердження. Токен для програм (Claude) видає <code>node portal/src/comments/cli.ts token Claude</code> на машині порталу.</p>
89    <div class="table-wrap"><table><thead><tr><th>Ім'я</th><th>Роль</th><th>Стан</th><th>Зареєстровано</th><th></th></tr></thead><tbody>${rows}</tbody></table></div>` })
90}
91
92// ── зведена сторінка «Коментарі»
93
94function docTitle(path: string) { return path.split('/').pop()!.replace(/\.md$/, '') }
95
96export function commentLink(c: Comment) { return `/${c.path}#${c.ref}` }
97
98async function commentsPage(url: URL, me: User | null) {
99  const state = url.searchParams.get('state') ?? 'open'
100  const author = url.searchParams.get('author') ?? ''
101  const where = url.searchParams.get('in') ?? ''
102  const q = (url.searchParams.get('q') ?? '').trim().toLowerCase()
103  const all = comments.list()
104  const list = all.filter(c => (state === 'all' || c.state === state) && (!author || c.author === author) && (!where || c.path.startsWith(where))
105    && (!q || [c.text, c.quote, c.answer, c.ref, c.path].some(s => s.toLowerCase().includes(q))))
106  const open = all.filter(c => c.state === 'open').length
107  const authors = [...new Set(all.map(c => c.author))].sort()
108  const opt = (v: string, label: string, cur: string) => `<option value="${esc(v)}"${v === cur ? ' selected' : ''}>${esc(label)}</option>`
109  const rows = list.map(c => `<tr class="${c.state}">
110    <td><a href="${esc(commentLink(c))}"><b>${c.ref}</b></a></td>
111    <td><span class="badge ${c.state === 'open' ? 'draft' : 'ok'}">${c.state === 'open' ? 'відкритий' : 'вирішено'}</span></td>
112    <td><a href="/${esc(c.path)}">${esc(docTitle(c.path))}</a>${c.heading ? `<div class="muted">${esc(c.heading)}</div>` : ''}</td>
113    <td><q class="cq">${esc(c.quote.length > 140 ? c.quote.slice(0, 140) + '…' : c.quote)}</q><div>${esc(c.text)}</div></td>
114    <td>${esc(c.author)}<div class="muted">${date(c.created_at)}</div></td>
115    <td>${c.state === 'closed' ? `${esc(c.answer)}${c.answer_where ? `<div class="muted">→ ${esc(c.answer_where)}</div>` : ''}${c.answer_commit ? `<div class="muted"><code>${esc(c.answer_commit.slice(0, 8))}</code></div>` : ''}` : '<span class="muted">—</span>'}</td>
116  </tr>`).join('')
117  const main = `<h1>Коментарі</h1>
118    <p class="muted">Відкритих ${open} · вирішених ${all.length - open}. Коментарі до research/ і doc/ розбираються в чаті з Claude; відповідь і місце, де вона записана, — у колонці «Відповідь».</p>
119    <form class="cfilters" method="get">
120      <select name="state">${opt('open', 'Відкриті', state)}${opt('closed', 'Вирішені', state)}${opt('all', 'Усі', state)}</select>
121      <select name="author">${opt('', 'Усі автори', author)}${authors.map(a => opt(a, a, author)).join('')}</select>
122      <select name="in">${opt('', 'research/ і doc/', where)}${opt('research/', 'research/', where)}${opt('doc/', 'doc/', where)}</select>
123      <input name="q" value="${esc(q)}" placeholder="Пошук у тексті, цитаті, відповіді">
124      <button class="btn" type="submit">Показати</button>
125    </form>
126    <div class="table-wrap"><table class="ctable"><thead><tr><th>№</th><th>Стан</th><th>Документ</th><th>Цитата й коментар</th><th>Автор</th><th>Відповідь</th></tr></thead><tbody>${rows || '<tr><td colspan="6" class="muted">Нічого не знайдено</td></tr>'}</tbody></table></div>
127    ${me ? '' : '<p class="muted"><a href="/login?next=/comments">Увійдіть</a>, щоб коментувати.</p>'}`
128  return layout({ title: 'Коментарі', rel: null, main, wide: true })
129}
130
131// ── уривок тексту з коміту коментаря
132
133async function context(c: Comment) {
134  const md = await show(c.commit, c.path)
135  if (md === null) return { found: false, text: '', note: `Коміту ${c.commit.slice(0, 8)} немає в цьому репозиторії` }
136  const text = plainText(md)
137  const flat = (s: string) => s.replace(/\s+/g, ' ')
138  const all = flat(text), quote = flat(c.quote).trim()
139  let i = all.indexOf(flat(c.prefix) + quote)
140  i = i >= 0 ? i + flat(c.prefix).length : all.indexOf(quote)
141  if (i < 0) return { found: false, text: '', note: 'Цитату не знайдено й у старій версії' }
142  return { found: true, before: all.slice(Math.max(0, i - 300), i), quote: all.slice(i, i + quote.length), after: all.slice(i + quote.length, i + quote.length + 300) }
143}
144
145// ── маршрутизатор
146
147export async function handleComments(req: IncomingMessage, res: Res, url: URL): Promise<boolean> {
148  const path = url.pathname
149  const method = req.method ?? 'GET'
150  const isComments = path === '/login' || path === '/account' || path === '/register' || path === '/logout' || path === '/users' || path === '/comments'
151    || path === '/api/me' || path === '/api/comments-export' || path.startsWith('/api/comments')
152  if (!isComments) return false
153  if (method === 'POST' && !sameOrigin(req)) { json(res, 403, { error: 'origin' }); return true }
154  const me = currentUser(req)
155
156  if (path === '/login') {
157    if (method === 'GET') { html(res, 200, await authPage('Вхід', loginForm(safeNext(url.searchParams.get('next'))))); return true }
158    const f = await body(req)
159    ensureDefaultAdmin()
160    const u = users.byName(str(f.name, 40).trim())
161    if (!u || u.role === 'bot' || !checkPassword(str(f.pass, 200), u.pass)) { html(res, 401, await authPage('Вхід', loginForm(safeNext(f.next), str(f.name, 40)), 'Невірне ім\'я або пароль.')); return true }
162    login(req, res, u)
163    redirect(res, safeNext(f.next)); return true
164  }
165  if (path === '/register') {
166    if (method === 'GET') { html(res, 200, await authPage('Реєстрація', registerForm(safeNext(url.searchParams.get('next'))))); return true }
167    const f = await body(req)
168    const name = str(f.name, 40).trim().replace(/\s+/g, ' '), pass = str(f.pass, 200)
169    const err = !NAME_RE.test(name) ? 'Ім\'я — 2–40 літер, цифр, пробілів, крапок чи дефісів.' : pass.length < 8 ? 'Пароль — не менше 8 символів.' : users.byName(name) ? 'Таке ім\'я вже зайняте.' : ''
170    if (err) { html(res, 400, await authPage('Реєстрація', registerForm(safeNext(f.next), name), err)); return true }
171    const id = users.create(name, hashPassword(pass))
172    login(req, res, users.byId(id)!)
173    html(res, 200, await authPage('Реєстрація', `<p>Обліковий запис <b>${esc(name)}</b> створено й ви увійшли. Коментувати зможете, щойно адміністратор його підтвердить.</p><p><a class="btn" href="${esc(safeNext(f.next))}">Повернутися</a></p>`)); return true
174  }
175  if (path === '/account') {
176    if (!me || me.role === 'bot') { redirect(res, '/login?next=/account'); return true }
177    const form = (note = '') => authPage('Обліковий запис', `<p><b>${esc(me.name)}</b> · ${me.role === 'admin' ? 'адміністратор' : 'користувач'}${me.approved ? '' : ' · чекає підтвердження'}</p>
178      <form method="post" action="/account" class="auth-form">
179        <label>Поточний пароль <input name="pass" type="password" autocomplete="current-password" required></label>
180        <label>Новий пароль (не менше 8 символів) <input name="next" type="password" autocomplete="new-password" minlength="8" required></label>
181        <button class="btn" type="submit">Змінити пароль</button>
182      </form>`, note)
183    if (method === 'GET') { html(res, 200, await form()); return true }
184    const f = await body(req)
185    const u = users.byName(me.name)!
186    if (!checkPassword(str(f.pass, 200), u.pass)) { html(res, 400, await form('Поточний пароль невірний.')); return true }
187    if (str(f.next, 200).length < 8) { html(res, 400, await form('Новий пароль — не менше 8 символів.')); return true }
188    users.set(me.id, { pass: hashPassword(str(f.next, 200)) })
189    html(res, 200, await form('Пароль змінено.')); return true
190  }
191  if (path === '/logout') { logout(req, res); redirect(res, safeNext(url.searchParams.get('next'))); return true }
192
193  if (path === '/users') {
194    if (!isAdmin(me)) { me ? html(res, 403, await authPage('Користувачі', '<p>Сторінка лише для адміністратора.</p>')) : redirect(res, '/login?next=/users'); return true }
195    if (method === 'POST') {
196      const f = await body(req)
197      const u = users.byId(Number(f.id))
198      if (u && u.id !== me!.id) {
199        if (f.do === 'approve') users.set(u.id, { approved: true })
200        if (f.do === 'block') users.set(u.id, { approved: false })
201        if (f.do === 'admin') users.set(u.id, { role: 'admin' })
202        if (f.do === 'user' && u.role === 'admin') users.set(u.id, { role: 'user' })
203        if (f.do === 'remove') users.remove(u.id)
204      }
205      redirect(res, '/users'); return true
206    }
207    html(res, 200, await usersPage(me!)); return true
208  }
209  if (path === '/comments') { html(res, 200, await commentsPage(url, me)); return true }
210
211  // ── API
212  if (path === '/api/me') {
213    json(res, 200, me ? { name: me.name, role: me.role, approved: me.approved, canComment: canComment(me), canResolve: canResolve(me), pending: isAdmin(me) ? users.all().filter(u => !u.approved).length : 0 } : null)
214    return true
215  }
216  if (path === '/api/comments-export') {
217    if (!canResolve(me)) { json(res, 403, { error: 'forbidden' }); return true }
218    json(res, 200, { exported_at: new Date().toISOString(), users: users.all(), comments: comments.list() }); return true
219  }
220  if (path === '/api/comments' && method === 'GET') {
221    const state = url.searchParams.get('state')
222    json(res, 200, comments.list({ path: url.searchParams.get('path') ?? undefined, author: url.searchParams.get('author') ?? undefined, state: state === 'open' || state === 'closed' ? state as State : undefined }))
223    return true
224  }
225  if (path === '/api/comments' && method === 'POST') {
226    if (!canComment(me)) { json(res, me ? 403 : 401, { error: me ? 'Обліковий запис ще не підтверджено' : 'Потрібен вхід' }); return true }
227    const f = await body(req)
228    const c = {
229      path: str(f.path, 300), commit: str(f.commit, 40), blob: str(f.blob, 40), dirty: !!f.dirty,
230      quote: str(f.quote, 8000).trim(), prefix: str(f.prefix, 200), suffix: str(f.suffix, 200), heading: str(f.heading, 300), text: str(f.text, 5000).trim(),
231    }
232    if (!commentable(c.path) || !c.quote || !c.text) { json(res, 400, { error: 'Потрібні документ research/ чи doc/, виділений текст і коментар' }); return true }
233    json(res, 201, comments.create(c, me!)); return true
234  }
235  const m = /^\/api\/comments\/([^/]+)(?:\/(context|close|reopen|anchor|edit))?$/.exec(path)
236  if (!m) { json(res, 404, { error: 'not found' }); return true }
237  const c = comments.get(decodeURIComponent(m[1]))
238  if (!c) { json(res, 404, { error: 'Коментаря немає' }); return true }
239  const action = m[2]
240  if (!action && method === 'GET') { json(res, 200, c); return true }
241  if (action === 'context' && method === 'GET') { json(res, 200, await context(c)); return true }
242  if (method !== 'POST') { json(res, 405, { error: 'method' }); return true }
243  const f = await body(req)
244  if (action === 'close') {
245    if (!canResolve(me)) { json(res, 403, { error: 'Закриває Claude чи адміністратор після розбору в чаті' }); return true }
246    if (!str(f.answer, 5000).trim()) { json(res, 400, { error: 'Потрібна відповідь' }); return true }
247    json(res, 200, comments.close(c, me!, { answer: str(f.answer, 5000).trim(), where: str(f.where, 300).trim(), commit: str(f.commit, 40).trim() })); return true
248  }
249  if (action === 'reopen') {
250    if (!canComment(me)) { json(res, 403, { error: 'Потрібен вхід' }); return true }
251    json(res, 200, comments.reopen(c, me!, str(f.text, 5000).trim())); return true
252  }
253  if (action === 'anchor') {
254    if (!canResolve(me)) { json(res, 403, { error: 'forbidden' }); return true }
255    const a = { commit: str(f.commit, 40), blob: str(f.blob, 40), quote: str(f.quote, 8000).trim(), prefix: str(f.prefix, 200), suffix: str(f.suffix, 200), heading: str(f.heading, 300) }
256    if (!a.commit || !a.quote) { json(res, 400, { error: 'Потрібні коміт і цитата' }); return true }
257    json(res, 200, comments.anchor(c, me!, a)); return true
258  }
259  if (action === 'edit') {
260    if (!me || me.name !== c.author || c.state !== 'open') { json(res, 403, { error: 'Редагує автор, поки коментар відкритий' }); return true }
261    json(res, 200, comments.edit(c, me, str(f.text, 5000).trim())); return true
262  }
263  json(res, 404, { error: 'not found' }); return true
264}
265