- POST /api/fenjaops/invites on server.js (requireAuth+requireAdmin). Ignores any is_admin field in the body — always stores 0. Records the acting admin's email in invited_by so the audit trail shows who added whom (CLI adds still record "cli"). - admin/index.html: new "Invite a new user" form panel at the top (email + optional first name). - admin/admin.js: wires the form submit to the POST, shows inline success/error, refreshes the tables on success. - admin/admin.css: form styling matching the existing paper/ink palette; mobile stacks. - Docs: CLAUDE.md, PROJECT.md, OPERATIONS.md, CHECKLIST.md, README.md all updated. New non-negotiable property in PROJECT.md: no web endpoint can set is_admin=1 or delete an invite — promotion + removal stay on bin/invite.js. New CHECKLIST.md section H2 covers the page's gating, the invite form, and an escalation-path audit. Admin promotion and invite deletion remain CLI-only so a compromised admin session cannot escalate or evict. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
185 lines
5.9 KiB
JavaScript
185 lines
5.9 KiB
JavaScript
// ─────────────────────────────────────────────────────────────
|
|
// admin/admin.js — pulls invites + joins from the gated
|
|
// /api/fenjaops endpoints and renders them. Also wires up the
|
|
// "Invite a new user" form (POST /api/fenjaops/invites), which
|
|
// only creates non-admin invites. Promoting to admin stays on
|
|
// the CLI (bin/invite.js admin add) by design.
|
|
//
|
|
// Note: the public URL path is `/fenjaops` (not `/admin`) as a
|
|
// small obscurity measure. Internal names stay as "admin".
|
|
// ─────────────────────────────────────────────────────────────
|
|
|
|
function iso(ms) {
|
|
return new Date(ms).toISOString().replace('T', ' ').slice(0, 19) + 'Z';
|
|
}
|
|
|
|
function shortSession(id) {
|
|
if (!id) return '';
|
|
return id.slice(0, 10) + '…';
|
|
}
|
|
|
|
function escapeHtml(s) {
|
|
return String(s ?? '').replace(/[&<>"']/g, (c) => ({
|
|
'&': '&',
|
|
'<': '<',
|
|
'>': '>',
|
|
'"': '"',
|
|
"'": ''',
|
|
}[c]));
|
|
}
|
|
|
|
function renderInvites(rows) {
|
|
const tbody = document.querySelector('#t-invites tbody');
|
|
const empty = document.getElementById('empty-invites');
|
|
if (!rows.length) {
|
|
tbody.innerHTML = '';
|
|
empty.hidden = false;
|
|
return;
|
|
}
|
|
empty.hidden = true;
|
|
tbody.innerHTML = rows.map((r) => {
|
|
const when = new Date(r.invited_at).toISOString().slice(0, 10);
|
|
const admin = r.is_admin ? '<span class="badge">Admin</span>' : '';
|
|
return `<tr>
|
|
<td>${escapeHtml(r.email)}</td>
|
|
<td>${escapeHtml(r.first_name || '')}</td>
|
|
<td class="when">${when}</td>
|
|
<td>${escapeHtml(r.invited_by || '')}</td>
|
|
<td class="num">${admin}</td>
|
|
</tr>`;
|
|
}).join('');
|
|
}
|
|
|
|
function renderSummary(rows) {
|
|
const tbody = document.querySelector('#t-summary tbody');
|
|
const empty = document.getElementById('empty-summary');
|
|
if (!rows.length) {
|
|
tbody.innerHTML = '';
|
|
empty.hidden = false;
|
|
return;
|
|
}
|
|
empty.hidden = true;
|
|
tbody.innerHTML = rows.map((r) => `
|
|
<tr>
|
|
<td>${escapeHtml(r.email)}</td>
|
|
<td class="num">${r.click_count}</td>
|
|
<td class="when">${iso(r.first_clicked_at)}</td>
|
|
<td class="when">${iso(r.last_clicked_at)}</td>
|
|
</tr>
|
|
`).join('');
|
|
}
|
|
|
|
function renderClicks(rows) {
|
|
const tbody = document.querySelector('#t-clicks tbody');
|
|
const empty = document.getElementById('empty-clicks');
|
|
if (!rows.length) {
|
|
tbody.innerHTML = '';
|
|
empty.hidden = false;
|
|
return;
|
|
}
|
|
empty.hidden = true;
|
|
tbody.innerHTML = rows.map((r) => `
|
|
<tr>
|
|
<td class="when">${iso(r.clicked_at)}</td>
|
|
<td>${escapeHtml(r.email)}</td>
|
|
<td class="mono">${escapeHtml(shortSession(r.session_id))}</td>
|
|
</tr>
|
|
`).join('');
|
|
}
|
|
|
|
async function load() {
|
|
try {
|
|
const [invitesRes, joinsRes] = await Promise.all([
|
|
fetch('/api/fenjaops/invites', { credentials: 'same-origin' }),
|
|
fetch('/api/fenjaops/joins', { credentials: 'same-origin' }),
|
|
]);
|
|
|
|
if (!invitesRes.ok || !joinsRes.ok) {
|
|
// Session expired or admin flag revoked while the page was open —
|
|
// bounce to the front page rather than leaving stale tables.
|
|
window.location.href = '/';
|
|
return;
|
|
}
|
|
|
|
const invites = await invitesRes.json();
|
|
const joins = await joinsRes.json();
|
|
|
|
document.getElementById('stat-clicks').textContent = joins.total_clicks;
|
|
document.getElementById('stat-unique').textContent = joins.unique_users;
|
|
document.getElementById('stat-invites').textContent = invites.length;
|
|
document.getElementById('stat-admins').textContent = invites.filter((r) => r.is_admin).length;
|
|
|
|
renderInvites(invites);
|
|
renderSummary(joins.summary);
|
|
renderClicks(joins.clicks);
|
|
} catch (err) {
|
|
// Network failure — show a soft error rather than a blank page.
|
|
const stats = document.getElementById('stats');
|
|
stats.innerHTML = '<p style="color:var(--admin)">Failed to load admin data — check the server logs.</p>';
|
|
console.error('[admin]', err);
|
|
}
|
|
}
|
|
|
|
const ERROR_COPY = {
|
|
invalid_email: 'That email address is not valid.',
|
|
invalid_first_name: 'First name is invalid.',
|
|
first_name_too_long: 'First name is too long (max 64 characters).',
|
|
already_invited: 'That email is already on the invite list.',
|
|
};
|
|
|
|
function setupInviteForm() {
|
|
const form = document.getElementById('invite-form');
|
|
const msg = document.getElementById('invite-msg');
|
|
if (!form || !msg) return;
|
|
|
|
function show(text, cls) {
|
|
msg.textContent = text;
|
|
msg.classList.remove('ok', 'err');
|
|
msg.classList.add(cls);
|
|
msg.hidden = false;
|
|
}
|
|
|
|
form.addEventListener('submit', async (ev) => {
|
|
ev.preventDefault();
|
|
msg.hidden = true;
|
|
|
|
const data = new FormData(form);
|
|
const email = String(data.get('email') || '').trim();
|
|
const firstName = String(data.get('first_name') || '').trim();
|
|
const body = { email };
|
|
if (firstName) body.first_name = firstName;
|
|
|
|
const btn = form.querySelector('button[type="submit"]');
|
|
btn.disabled = true;
|
|
try {
|
|
const res = await fetch('/api/fenjaops/invites', {
|
|
method: 'POST',
|
|
credentials: 'same-origin',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
});
|
|
const payload = await res.json().catch(() => ({}));
|
|
|
|
if (res.status === 201) {
|
|
show(`Invited ${payload.email}.`, 'ok');
|
|
form.reset();
|
|
load();
|
|
return;
|
|
}
|
|
if (res.status === 401 || res.status === 404) {
|
|
window.location.href = '/';
|
|
return;
|
|
}
|
|
const code = payload.error || 'error';
|
|
show(ERROR_COPY[code] || `Error: ${code}`, 'err');
|
|
} catch (err) {
|
|
console.error('[admin] invite submit', err);
|
|
show('Network error — check server logs.', 'err');
|
|
} finally {
|
|
btn.disabled = false;
|
|
}
|
|
});
|
|
}
|
|
|
|
load();
|
|
setupInviteForm();
|