feat: add moderation toggles for community content
Admin settings now control moderation per content type: video and blog submissions (off = auto-publish), board messages (on = held as pending after payment), and blog comments/likes (on = only admin-approved Nostr events are shown, via a new approval queue on the Moderation page). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
-- Approval queue for blog comments/likes, plus per-content-type moderation toggles.
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "NostrInteraction" (
|
||||
"eventId" TEXT NOT NULL PRIMARY KEY,
|
||||
"targetEventId" TEXT NOT NULL,
|
||||
"kind" INTEGER NOT NULL,
|
||||
"pubkey" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL DEFAULT '',
|
||||
"eventCreatedAt" INTEGER NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||
"reviewedBy" TEXT,
|
||||
"reviewedAt" DATETIME,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "NostrInteraction_status_kind_idx" ON "NostrInteraction"("status", "kind");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "NostrInteraction_targetEventId_idx" ON "NostrInteraction"("targetEventId");
|
||||
|
||||
-- Moderation toggles; defaults match the behaviour before the toggles existed.
|
||||
INSERT OR IGNORE INTO "Setting" ("id", "key", "value", "updatedAt") VALUES
|
||||
(lower(hex(randomblob(16))), 'moderation_videos', 'true', CURRENT_TIMESTAMP),
|
||||
(lower(hex(randomblob(16))), 'moderation_blog_submissions', 'true', CURRENT_TIMESTAMP),
|
||||
(lower(hex(randomblob(16))), 'moderation_board', 'false', CURRENT_TIMESTAMP),
|
||||
(lower(hex(randomblob(16))), 'moderation_blog_comments', 'false', CURRENT_TIMESTAMP),
|
||||
(lower(hex(randomblob(16))), 'moderation_blog_reactions', 'false', CURRENT_TIMESTAMP);
|
||||
@@ -290,3 +290,21 @@ model VideoCategoryLink {
|
||||
@@id([videoId, categoryId])
|
||||
@@index([categoryId])
|
||||
}
|
||||
|
||||
// Blog comments (kind 1) and likes (kind 7) seen on relays for a blog post.
|
||||
// Used as an approval queue when comment/like moderation is switched on.
|
||||
model NostrInteraction {
|
||||
eventId String @id
|
||||
targetEventId String
|
||||
kind Int
|
||||
pubkey String
|
||||
content String @default("")
|
||||
eventCreatedAt Int
|
||||
status String @default("pending") // pending | approved | rejected
|
||||
reviewedBy String?
|
||||
reviewedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([status, kind])
|
||||
@@index([targetEventId])
|
||||
}
|
||||
|
||||
@@ -31,6 +31,11 @@ async function main() {
|
||||
{ key: 'youtube_link', value: '' },
|
||||
{ key: 'discord_link', value: '' },
|
||||
{ key: 'linkedin_link', value: '' },
|
||||
{ key: 'moderation_videos', value: 'true' },
|
||||
{ key: 'moderation_blog_submissions', value: 'true' },
|
||||
{ key: 'moderation_board', value: 'false' },
|
||||
{ key: 'moderation_blog_comments', value: 'false' },
|
||||
{ key: 'moderation_blog_reactions', value: 'false' },
|
||||
];
|
||||
|
||||
for (const setting of settings) {
|
||||
|
||||
@@ -18,7 +18,7 @@ router.get('/', async (_req: Request, res: Response) => {
|
||||
}
|
||||
});
|
||||
|
||||
/** Toggle active <-> hidden */
|
||||
/** Toggle active <-> hidden (a pending message becomes hidden, i.e. rejected) */
|
||||
router.post('/:id/hide', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const rawId = req.params.id;
|
||||
@@ -44,6 +44,31 @@ router.post('/:id/hide', async (req: Request, res: Response) => {
|
||||
}
|
||||
});
|
||||
|
||||
/** Approve a message held for review (pending -> active) */
|
||||
router.post('/:id/approve', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const rawId = req.params.id;
|
||||
const id = Array.isArray(rawId) ? rawId[0] : rawId;
|
||||
const msg = await prisma.boardMessage.findUnique({ where: { id } });
|
||||
if (!msg) {
|
||||
res.status(404).json({ error: 'Not found' });
|
||||
return;
|
||||
}
|
||||
if (msg.status === 'deleted') {
|
||||
res.status(400).json({ error: 'Message is deleted' });
|
||||
return;
|
||||
}
|
||||
const updated = await prisma.boardMessage.update({
|
||||
where: { id: msg.id },
|
||||
data: { status: 'active' },
|
||||
});
|
||||
res.json(updated);
|
||||
} catch (err) {
|
||||
console.error('Admin approve board message error:', err);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
/** Soft-delete */
|
||||
router.delete('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { timingSafeEqual } from 'crypto';
|
||||
import { prisma } from '../db/prisma';
|
||||
import { isModerated } from '../lib/settings';
|
||||
import { requireAuth } from '../middleware/auth';
|
||||
import {
|
||||
createIncomingInvoice,
|
||||
@@ -215,6 +216,9 @@ async function promotePendingToMessage(paymentHash: string): Promise<{
|
||||
? pending.guestName
|
||||
: 'anon';
|
||||
|
||||
// With board moderation on, paid messages wait for an admin to approve them.
|
||||
const status = (await isModerated('moderation_board')) ? 'pending' : 'active';
|
||||
|
||||
try {
|
||||
await prisma.$transaction([
|
||||
prisma.boardMessage.create({
|
||||
@@ -225,7 +229,7 @@ async function promotePendingToMessage(paymentHash: string): Promise<{
|
||||
pubkey: pending.pubkey,
|
||||
profilePic: pending.profilePic,
|
||||
satsPaid: MESSAGE_PRICE_SATS,
|
||||
status: 'active',
|
||||
status,
|
||||
},
|
||||
}),
|
||||
prisma.boardInvoicePending.delete({ where: { paymentHash } }),
|
||||
@@ -296,9 +300,13 @@ router.get('/payment/:paymentHash/status', async (req: Request, res: Response) =
|
||||
const paid = await getPublicPaymentStatus(hash);
|
||||
const message = await prisma.boardMessage.findUnique({
|
||||
where: { paymentHash: hash },
|
||||
select: { id: true },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
res.json({
|
||||
paid: paid || !!message,
|
||||
messageCreated: !!message,
|
||||
pendingReview: message?.status === 'pending',
|
||||
});
|
||||
res.json({ paid: paid || !!message, messageCreated: !!message });
|
||||
} catch (err) {
|
||||
console.error('Board payment status error:', err);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { prisma } from '../db/prisma';
|
||||
import { requireAuth, requires } from '../middleware/auth';
|
||||
import { nostrService } from '../services/nostr';
|
||||
import { KIND_REACTION, KIND_REPLY, isKindModerated, recordInteractions } from '../services/nostrInteractions';
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -140,4 +142,162 @@ router.delete(
|
||||
}
|
||||
);
|
||||
|
||||
// ── Blog comment / like approval queue ──────────────────────────────────────
|
||||
|
||||
const INTERACTION_STATUSES = ['pending', 'approved', 'rejected'];
|
||||
const SCAN_POST_LIMIT = 200;
|
||||
const SCAN_CONCURRENCY = 5;
|
||||
|
||||
function parseKind(raw: unknown): number | undefined {
|
||||
const kind = Number(raw);
|
||||
return kind === KIND_REPLY || kind === KIND_REACTION ? kind : undefined;
|
||||
}
|
||||
|
||||
router.get(
|
||||
'/interactions',
|
||||
requireAuth,
|
||||
requires('moderation.act'),
|
||||
async (req: Request, res: Response) => {
|
||||
try {
|
||||
const status = INTERACTION_STATUSES.includes(req.query.status as string)
|
||||
? (req.query.status as string)
|
||||
: 'pending';
|
||||
const kind = parseKind(req.query.kind);
|
||||
|
||||
const where = { status, ...(kind ? { kind } : {}) };
|
||||
const [items, counts] = await Promise.all([
|
||||
prisma.nostrInteraction.findMany({
|
||||
where,
|
||||
orderBy: { eventCreatedAt: 'desc' },
|
||||
take: 500,
|
||||
}),
|
||||
prisma.nostrInteraction.groupBy({
|
||||
by: ['kind'],
|
||||
where: { status: 'pending' },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const posts = await prisma.post.findMany({
|
||||
where: { nostrEventId: { in: [...new Set(items.map((i) => i.targetEventId))] } },
|
||||
select: { nostrEventId: true, title: true, slug: true },
|
||||
});
|
||||
const postByEvent = new Map(posts.map((p) => [p.nostrEventId, p]));
|
||||
|
||||
const pending: Record<string, number> = { replies: 0, reactions: 0 };
|
||||
for (const c of counts) {
|
||||
if (c.kind === KIND_REPLY) pending.replies = c._count._all;
|
||||
if (c.kind === KIND_REACTION) pending.reactions = c._count._all;
|
||||
}
|
||||
|
||||
res.json({
|
||||
items: items.map((i) => ({ ...i, post: postByEvent.get(i.targetEventId) ?? null })),
|
||||
pending,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('List interactions error:', err);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/interactions/approve-all',
|
||||
requireAuth,
|
||||
requires('moderation.act'),
|
||||
async (req: Request, res: Response) => {
|
||||
try {
|
||||
const kind = parseKind(req.body?.kind);
|
||||
const result = await prisma.nostrInteraction.updateMany({
|
||||
where: { status: 'pending', ...(kind ? { kind } : {}) },
|
||||
data: { status: 'approved', reviewedBy: req.user!.pubkey, reviewedAt: new Date() },
|
||||
});
|
||||
res.json({ updated: result.count });
|
||||
} catch (err) {
|
||||
console.error('Approve all interactions error:', err);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Pulls comments/likes for recent visible posts from relays so the queue
|
||||
// fills even for posts nobody has opened since moderation was switched on.
|
||||
router.post(
|
||||
'/interactions/scan',
|
||||
requireAuth,
|
||||
requires('moderation.act'),
|
||||
async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const [repliesOn, reactionsOn] = await Promise.all([
|
||||
isKindModerated(KIND_REPLY),
|
||||
isKindModerated(KIND_REACTION),
|
||||
]);
|
||||
if (!repliesOn && !reactionsOn) {
|
||||
res.json({ scanned: 0, pending: 0, moderated: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const posts = await prisma.post.findMany({
|
||||
where: { visible: true },
|
||||
orderBy: { publishedAt: 'desc' },
|
||||
take: SCAN_POST_LIMIT,
|
||||
select: { nostrEventId: true },
|
||||
});
|
||||
|
||||
let scanned = 0;
|
||||
for (let i = 0; i < posts.length; i += SCAN_CONCURRENCY) {
|
||||
await Promise.all(
|
||||
posts.slice(i, i + SCAN_CONCURRENCY).map(async ({ nostrEventId }) => {
|
||||
const [replies, reactions] = await Promise.all([
|
||||
repliesOn ? nostrService.fetchReplies(nostrEventId) : [],
|
||||
reactionsOn ? nostrService.fetchReactions(nostrEventId) : [],
|
||||
]);
|
||||
await recordInteractions(nostrEventId, [...replies, ...reactions]);
|
||||
scanned++;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const pending = await prisma.nostrInteraction.count({ where: { status: 'pending' } });
|
||||
res.json({ scanned, pending, moderated: true });
|
||||
} catch (err) {
|
||||
console.error('Scan interactions error:', err);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/interactions/:eventId/:action',
|
||||
requireAuth,
|
||||
requires('moderation.act'),
|
||||
async (req: Request, res: Response) => {
|
||||
try {
|
||||
const action = req.params.action as string;
|
||||
if (action !== 'approve' && action !== 'reject') {
|
||||
res.status(400).json({ error: 'action must be approve or reject' });
|
||||
return;
|
||||
}
|
||||
const eventId = req.params.eventId as string;
|
||||
const existing = await prisma.nostrInteraction.findUnique({ where: { eventId } });
|
||||
if (!existing) {
|
||||
res.status(404).json({ error: 'Not found' });
|
||||
return;
|
||||
}
|
||||
const updated = await prisma.nostrInteraction.update({
|
||||
where: { eventId },
|
||||
data: {
|
||||
status: action === 'approve' ? 'approved' : 'rejected',
|
||||
reviewedBy: req.user!.pubkey,
|
||||
reviewedAt: new Date(),
|
||||
},
|
||||
});
|
||||
res.json(updated);
|
||||
} catch (err) {
|
||||
console.error('Review interaction error:', err);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { prisma } from '../db/prisma';
|
||||
import { KIND_REACTION, KIND_REPLY, moderateForPublic } from '../services/nostrInteractions';
|
||||
import { requireAuth, requires } from '../middleware/auth';
|
||||
import { authService, type ResolvedAccess } from '../services/auth';
|
||||
import { looksLikeApiKey, resolveApiKey } from '../services/apiKeys';
|
||||
@@ -280,7 +281,8 @@ router.get('/:slug/reactions', async (req: Request, res: Response) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const reactions = await nostrService.fetchReactions(eventId);
|
||||
const fetched = await nostrService.fetchReactions(eventId);
|
||||
const reactions = await moderateForPublic(eventId, KIND_REACTION, fetched);
|
||||
res.json({ count: reactions.length, reactions });
|
||||
} catch (err) {
|
||||
console.error('Get reactions error:', err);
|
||||
@@ -297,18 +299,8 @@ router.get('/:slug/replies', async (req: Request, res: Response) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const [replies, hiddenContent, blockedPubkeys] = await Promise.all([
|
||||
nostrService.fetchReplies(eventId),
|
||||
prisma.hiddenContent.findMany({ select: { nostrEventId: true } }),
|
||||
prisma.blockedPubkey.findMany({ select: { pubkey: true } }),
|
||||
]);
|
||||
|
||||
const hiddenIds = new Set(hiddenContent.map((h) => h.nostrEventId));
|
||||
const blockedKeys = new Set(blockedPubkeys.map((b) => b.pubkey));
|
||||
|
||||
const filtered = replies.filter(
|
||||
(r) => !hiddenIds.has(r.id) && !blockedKeys.has(r.pubkey)
|
||||
);
|
||||
const replies = await nostrService.fetchReplies(eventId);
|
||||
const filtered = await moderateForPublic(eventId, KIND_REPLY, replies);
|
||||
|
||||
res.json({ count: filtered.length, replies: filtered });
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { prisma } from '../db/prisma';
|
||||
import { requireAuth, requires } from '../middleware/auth';
|
||||
import { MODERATION_DEFAULTS, isModerationKey } from '../lib/settings';
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -13,6 +14,7 @@ const PUBLIC_SETTINGS = [
|
||||
'youtube_link',
|
||||
'discord_link',
|
||||
'linkedin_link',
|
||||
...Object.keys(MODERATION_DEFAULTS),
|
||||
];
|
||||
|
||||
router.get(
|
||||
@@ -61,6 +63,14 @@ router.patch(
|
||||
res.status(400).json({ error: 'key and value are required' });
|
||||
return;
|
||||
}
|
||||
if (typeof key !== 'string' || typeof value !== 'string') {
|
||||
res.status(400).json({ error: 'key and value must be strings' });
|
||||
return;
|
||||
}
|
||||
if (isModerationKey(key) && value !== 'true' && value !== 'false') {
|
||||
res.status(400).json({ error: `${key} must be "true" or "false"` });
|
||||
return;
|
||||
}
|
||||
|
||||
const setting = await prisma.setting.upsert({
|
||||
where: { key },
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { prisma } from '../db/prisma';
|
||||
import { requireAuth, requires } from '../middleware/auth';
|
||||
import { importPostFromNostr, resolveSubmissionImport } from '../services/postImport';
|
||||
import { importPostFromNostr, resolveSubmissionImport, type SubmissionRef } from '../services/postImport';
|
||||
import { isModerated } from '../lib/settings';
|
||||
import { isPubkeyBlocked } from '../services/nostrInteractions';
|
||||
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* Publishes the referenced Nostr article to the blog. Returns null when the
|
||||
* event can't be resolved from relays, in which case nothing was published.
|
||||
*/
|
||||
async function publishSubmission(submission: SubmissionRef) {
|
||||
const importInput = await resolveSubmissionImport(submission);
|
||||
if (!importInput) return null;
|
||||
return importPostFromNostr(importInput);
|
||||
}
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
requireAuth,
|
||||
@@ -16,6 +28,12 @@ router.post(
|
||||
return;
|
||||
}
|
||||
|
||||
const moderated = await isModerated('moderation_blog_submissions');
|
||||
if (!moderated && (await isPubkeyBlocked(req.user!.pubkey))) {
|
||||
res.status(403).json({ error: 'You are not allowed to submit posts.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const submission = await prisma.submission.create({
|
||||
data: {
|
||||
eventId: eventId || null,
|
||||
@@ -25,6 +43,24 @@ router.post(
|
||||
},
|
||||
});
|
||||
|
||||
// With moderation off the article is published right away. If the
|
||||
// import fails the submission stays PENDING for a human to look at.
|
||||
if (!moderated) {
|
||||
try {
|
||||
const post = await publishSubmission(submission);
|
||||
if (post) {
|
||||
const approved = await prisma.submission.update({
|
||||
where: { id: submission.id },
|
||||
data: { status: 'APPROVED', reviewedBy: 'auto' },
|
||||
});
|
||||
res.status(201).json({ ...approved, post: { slug: post.slug } });
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Auto-publish submission error:', err);
|
||||
}
|
||||
}
|
||||
|
||||
res.status(201).json(submission);
|
||||
} catch (err) {
|
||||
console.error('Create submission error:', err);
|
||||
@@ -100,15 +136,14 @@ router.patch(
|
||||
// marked APPROVED without a corresponding live post.
|
||||
let post = null;
|
||||
if (status === 'APPROVED') {
|
||||
const importInput = await resolveSubmissionImport(submission);
|
||||
if (!importInput) {
|
||||
post = await publishSubmission(submission);
|
||||
if (!post) {
|
||||
res.status(422).json({
|
||||
error:
|
||||
'Could not resolve the submitted Nostr event from relays. The post was not published, so the submission was left unchanged.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
post = await importPostFromNostr(importInput);
|
||||
}
|
||||
|
||||
const updated = await prisma.submission.update({
|
||||
|
||||
@@ -2,6 +2,8 @@ import { Router, Request, Response } from 'express';
|
||||
import slugifyLib from 'slugify';
|
||||
import type { Prisma } from '@prisma/client';
|
||||
import { prisma } from '../db/prisma';
|
||||
import { isModerated } from '../lib/settings';
|
||||
import { isPubkeyBlocked } from '../services/nostrInteractions';
|
||||
import { requireAuth, requires } from '../middleware/auth';
|
||||
import { INVALID_VIDEO_URL, embedUrlFor, isValidThumbnailUrl, parseVideoUrl, resolveVideo } from '../services/video';
|
||||
|
||||
@@ -243,7 +245,14 @@ router.get('/mine', requireAuth, async (req: Request, res: Response) => {
|
||||
router.post('/submit', requireAuth, async (req: Request, res: Response) => {
|
||||
try {
|
||||
const pubkey = req.user!.pubkey;
|
||||
const pending = await prisma.video.count({ where: { submittedBy: pubkey, status: 'PENDING' } });
|
||||
const moderated = await isModerated('moderation_videos');
|
||||
if (!moderated && (await isPubkeyBlocked(pubkey))) {
|
||||
sendError(res, 403, 'You are not allowed to submit videos.');
|
||||
return;
|
||||
}
|
||||
const pending = moderated
|
||||
? await prisma.video.count({ where: { submittedBy: pubkey, status: 'PENDING' } })
|
||||
: 0;
|
||||
if (pending >= MAX_PENDING_PER_USER) {
|
||||
sendError(
|
||||
res,
|
||||
@@ -316,7 +325,8 @@ router.post('/submit', requireAuth, async (req: Request, res: Response) => {
|
||||
thumbnailUrl: meta.thumbnailUrl,
|
||||
duration: meta.duration,
|
||||
meetupId,
|
||||
status: 'PENDING',
|
||||
// With moderation off, submissions go live straight away.
|
||||
...(moderated ? { status: 'PENDING' } : { status: 'PUBLISHED', publishedAt: new Date(), reviewedBy: 'auto' }),
|
||||
submittedBy: pubkey,
|
||||
...(categories.length ? { categories: { create: categories.map((c) => ({ categoryId: c.id })) } } : {}),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { prisma } from '../db/prisma';
|
||||
|
||||
/**
|
||||
* Per-content-type moderation switches, editable in Admin → Settings.
|
||||
* The defaults mirror the behaviour from before these toggles existed, so a
|
||||
* missing row never changes how the site behaves.
|
||||
*/
|
||||
export const MODERATION_DEFAULTS = {
|
||||
moderation_videos: true,
|
||||
moderation_blog_submissions: true,
|
||||
moderation_board: false,
|
||||
moderation_blog_comments: false,
|
||||
moderation_blog_reactions: false,
|
||||
} as const;
|
||||
|
||||
export type ModerationKey = keyof typeof MODERATION_DEFAULTS;
|
||||
|
||||
export function isModerationKey(key: string): key is ModerationKey {
|
||||
return Object.prototype.hasOwnProperty.call(MODERATION_DEFAULTS, key);
|
||||
}
|
||||
|
||||
export async function getBoolSetting(key: string, fallback: boolean): Promise<boolean> {
|
||||
const row = await prisma.setting.findUnique({ where: { key } });
|
||||
if (!row) return fallback;
|
||||
return row.value === 'true';
|
||||
}
|
||||
|
||||
export function isModerated(key: ModerationKey): Promise<boolean> {
|
||||
return getBoolSetting(key, MODERATION_DEFAULTS[key]);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { prisma } from '../db/prisma';
|
||||
import { isModerated } from '../lib/settings';
|
||||
|
||||
export const KIND_REPLY = 1;
|
||||
export const KIND_REACTION = 7;
|
||||
|
||||
interface NostrEventLike {
|
||||
id: string;
|
||||
pubkey: string;
|
||||
kind: number;
|
||||
content: string;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
export async function isPubkeyBlocked(pubkey: string): Promise<boolean> {
|
||||
const hit = await prisma.blockedPubkey.findFirst({ where: { pubkey }, select: { id: true } });
|
||||
return !!hit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers comments/likes seen on relays for a post so they can be reviewed.
|
||||
* Existing rows are left alone, so an approve/reject decision is never undone.
|
||||
*/
|
||||
export async function recordInteractions(targetEventId: string, events: NostrEventLike[]) {
|
||||
if (events.length === 0) return;
|
||||
const ids = events.map((e) => e.id);
|
||||
const known = await prisma.nostrInteraction.findMany({
|
||||
where: { eventId: { in: ids } },
|
||||
select: { eventId: true },
|
||||
});
|
||||
const knownIds = new Set(known.map((k) => k.eventId));
|
||||
const fresh = new Map<string, NostrEventLike>();
|
||||
for (const e of events) {
|
||||
if (!knownIds.has(e.id)) fresh.set(e.id, e);
|
||||
}
|
||||
if (fresh.size === 0) return;
|
||||
|
||||
// SQLite has no skipDuplicates; a concurrent request may insert the same
|
||||
// row, so insert one by one and ignore unique-constraint clashes.
|
||||
for (const e of fresh.values()) {
|
||||
try {
|
||||
await prisma.nostrInteraction.create({
|
||||
data: {
|
||||
eventId: e.id,
|
||||
targetEventId,
|
||||
kind: e.kind,
|
||||
pubkey: e.pubkey,
|
||||
content: (e.content || '').slice(0, 5000),
|
||||
eventCreatedAt: e.created_at,
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const code = err && typeof err === 'object' && 'code' in err ? (err as { code: string }).code : '';
|
||||
if (code !== 'P2002') throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function isKindModerated(kind: number): Promise<boolean> {
|
||||
return isModerated(kind === KIND_REACTION ? 'moderation_blog_reactions' : 'moderation_blog_comments');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the comments/likes that may be shown publicly. Hidden, blocked and
|
||||
* rejected events are always dropped. While moderation is on for this kind,
|
||||
* new events are queued for review and only approved ones are returned.
|
||||
*/
|
||||
export async function moderateForPublic<T extends NostrEventLike>(
|
||||
targetEventId: string,
|
||||
kind: number,
|
||||
events: T[]
|
||||
): Promise<T[]> {
|
||||
if (events.length === 0) return events;
|
||||
const moderated = await isKindModerated(kind);
|
||||
if (moderated) await recordInteractions(targetEventId, events);
|
||||
|
||||
const ids = events.map((e) => e.id);
|
||||
const [hidden, blocked, reviewed] = await Promise.all([
|
||||
prisma.hiddenContent.findMany({ where: { nostrEventId: { in: ids } }, select: { nostrEventId: true } }),
|
||||
prisma.blockedPubkey.findMany({ select: { pubkey: true } }),
|
||||
prisma.nostrInteraction.findMany({
|
||||
where: { eventId: { in: ids }, status: { not: 'pending' } },
|
||||
select: { eventId: true, status: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const hiddenIds = new Set(hidden.map((h) => h.nostrEventId));
|
||||
const blockedKeys = new Set(blocked.map((b) => b.pubkey));
|
||||
const statusById = new Map(reviewed.map((r) => [r.eventId, r.status]));
|
||||
|
||||
return events.filter((e) => {
|
||||
if (hiddenIds.has(e.id) || blockedKeys.has(e.pubkey)) return false;
|
||||
const status = statusById.get(e.id);
|
||||
if (status === 'rejected') return false;
|
||||
return moderated ? status === 'approved' : true;
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Eye, EyeOff, MessageSquare, Trash2, Zap } from "lucide-react";
|
||||
import { Check, Eye, EyeOff, MessageSquare, Trash2, X, Zap } from "lucide-react";
|
||||
import { api } from "@/lib/api";
|
||||
import {
|
||||
EmptyState,
|
||||
@@ -34,7 +34,7 @@ type Message = {
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type Tab = "all" | "active" | "hidden" | "deleted";
|
||||
type Tab = "all" | "pending" | "active" | "hidden" | "deleted";
|
||||
|
||||
export default function AdminBoardMessagesPage() {
|
||||
const confirm = useConfirm();
|
||||
@@ -60,7 +60,7 @@ export default function AdminBoardMessagesPage() {
|
||||
}, [load]);
|
||||
|
||||
const counts = useMemo(() => {
|
||||
const c: Record<Tab, number> = { all: rows.length, active: 0, hidden: 0, deleted: 0 };
|
||||
const c: Record<Tab, number> = { all: rows.length, pending: 0, active: 0, hidden: 0, deleted: 0 };
|
||||
for (const r of rows) if (r.status in c) c[r.status as Tab]++;
|
||||
return c;
|
||||
}, [rows]);
|
||||
@@ -81,6 +81,26 @@ export default function AdminBoardMessagesPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const approve = async (r: Message) => {
|
||||
try {
|
||||
await api.approveBoardMessage(r.id);
|
||||
setRows((prev) => prev.map((x) => (x.id === r.id ? { ...x, status: "active" } : x)));
|
||||
toast.success("Message approved and live");
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, "Could not approve"));
|
||||
}
|
||||
};
|
||||
|
||||
const reject = async (r: Message) => {
|
||||
try {
|
||||
await api.hideBoardMessage(r.id);
|
||||
setRows((prev) => prev.map((x) => (x.id === r.id ? { ...x, status: "hidden" } : x)));
|
||||
toast.success("Message rejected");
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, "Could not reject"));
|
||||
}
|
||||
};
|
||||
|
||||
const softDelete = async (r: Message) => {
|
||||
const ok = await confirm({
|
||||
title: "Delete this message?",
|
||||
@@ -102,7 +122,7 @@ export default function AdminBoardMessagesPage() {
|
||||
<div>
|
||||
<PageHeader
|
||||
title="Board messages"
|
||||
description="Lightning-paid messages on the public board. Hide to take one offline temporarily; delete removes it but keeps the payment history."
|
||||
description="Lightning-paid messages on the public board. Hide to take one offline temporarily; delete removes it but keeps the payment history. When board moderation is on in Settings, new messages wait here for approval."
|
||||
/>
|
||||
|
||||
<Toolbar>
|
||||
@@ -112,6 +132,9 @@ export default function AdminBoardMessagesPage() {
|
||||
onChange={setTab}
|
||||
tabs={[
|
||||
{ value: "all", label: "All", count: counts.all },
|
||||
...(counts.pending > 0 || tab === "pending"
|
||||
? [{ value: "pending" as const, label: "Awaiting review", count: counts.pending }]
|
||||
: []),
|
||||
{ value: "active", label: "Live", count: counts.active },
|
||||
{ value: "hidden", label: "Hidden", count: counts.hidden },
|
||||
{ value: "deleted", label: "Deleted", count: counts.deleted },
|
||||
@@ -147,11 +170,25 @@ export default function AdminBoardMessagesPage() {
|
||||
<span>{new Date(r.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" })}</span>
|
||||
</p>
|
||||
</div>
|
||||
<StatusBadge status={r.status} label={r.status === "active" ? "Live" : undefined} />
|
||||
<StatusBadge
|
||||
status={r.status}
|
||||
label={r.status === "active" ? "Live" : r.status === "pending" ? "Awaiting review" : undefined}
|
||||
/>
|
||||
<div className="flex shrink-0">
|
||||
<IconButton label={r.status === "hidden" ? "Show on board" : "Hide from board"} disabled={r.status === "deleted"} onClick={() => toggleHide(r)}>
|
||||
{r.status === "hidden" ? <Eye size={16} /> : <EyeOff size={16} />}
|
||||
</IconButton>
|
||||
{r.status === "pending" ? (
|
||||
<>
|
||||
<IconButton label="Approve" onClick={() => approve(r)}>
|
||||
<Check size={16} />
|
||||
</IconButton>
|
||||
<IconButton label="Reject" onClick={() => reject(r)}>
|
||||
<X size={16} />
|
||||
</IconButton>
|
||||
</>
|
||||
) : (
|
||||
<IconButton label={r.status === "hidden" ? "Show on board" : "Hide from board"} disabled={r.status === "deleted"} onClick={() => toggleHide(r)}>
|
||||
{r.status === "hidden" ? <Eye size={16} /> : <EyeOff size={16} />}
|
||||
</IconButton>
|
||||
)}
|
||||
<IconButton label="Delete" variant="danger" disabled={r.status === "deleted"} onClick={() => softDelete(r)}>
|
||||
<Trash2 size={16} />
|
||||
</IconButton>
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { nip19 } from "nostr-tools";
|
||||
import { Check, CheckCheck, Heart, MessageSquare, RefreshCw, ShieldCheck, X } from "lucide-react";
|
||||
import { api, type NostrInteraction } from "@/lib/api";
|
||||
import { Button, EmptyState, ErrorState, FilterTabs, ListSkeleton, Panel, Row, RowList, Toolbar, errorMessage, toast } from "@/components/admin/ui";
|
||||
|
||||
const KIND_REPLY = 1;
|
||||
const KIND_REACTION = 7;
|
||||
|
||||
type KindFilter = "replies" | "reactions";
|
||||
|
||||
const fmt = (sec: number) =>
|
||||
new Date(sec * 1000).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
function shortNpub(pubkey: string) {
|
||||
try {
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
return `${npub.slice(0, 12)}…${npub.slice(-6)}`;
|
||||
} catch {
|
||||
return `${pubkey.slice(0, 12)}…`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Approval queue for blog comments and likes, used when their moderation toggle is on. */
|
||||
export default function PendingInteractions({ onCountChange }: { onCountChange?: (n: number) => void }) {
|
||||
const [kind, setKind] = useState<KindFilter>("replies");
|
||||
const [items, setItems] = useState<NostrInteraction[]>([]);
|
||||
const [pending, setPending] = useState({ replies: 0, reactions: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [approvingAll, setApprovingAll] = useState(false);
|
||||
|
||||
const kindNumber = kind === "replies" ? KIND_REPLY : KIND_REACTION;
|
||||
|
||||
const load = async () => {
|
||||
setError("");
|
||||
try {
|
||||
const data = await api.getNostrInteractions({ status: "pending", kind: kindNumber });
|
||||
setItems(data.items);
|
||||
setPending(data.pending);
|
||||
onCountChange?.(data.pending.replies + data.pending.reactions);
|
||||
} catch (err) {
|
||||
setError(errorMessage(err, "Could not load the queue"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
load();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [kind]);
|
||||
|
||||
const review = async (item: NostrInteraction, action: "approve" | "reject") => {
|
||||
try {
|
||||
await api.reviewNostrInteraction(item.eventId, action);
|
||||
setItems((prev) => prev.filter((x) => x.eventId !== item.eventId));
|
||||
setPending((prev) => {
|
||||
const next = { ...prev, [kind]: Math.max(0, prev[kind] - 1) };
|
||||
onCountChange?.(next.replies + next.reactions);
|
||||
return next;
|
||||
});
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, "Could not update"));
|
||||
}
|
||||
};
|
||||
|
||||
const approveAll = async () => {
|
||||
setApprovingAll(true);
|
||||
try {
|
||||
const { updated } = await api.approveAllNostrInteractions(kindNumber);
|
||||
toast.success(`Approved ${updated} ${kind === "replies" ? "comment" : "like"}${updated === 1 ? "" : "s"}`);
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, "Could not approve"));
|
||||
} finally {
|
||||
setApprovingAll(false);
|
||||
}
|
||||
};
|
||||
|
||||
const scan = async () => {
|
||||
setScanning(true);
|
||||
try {
|
||||
const { scanned, moderated } = await api.scanNostrInteractions();
|
||||
if (!moderated) {
|
||||
toast.error("Comment and like moderation are both off in Settings, so there is nothing to queue");
|
||||
return;
|
||||
}
|
||||
toast.success(`Checked ${scanned} post${scanned === 1 ? "" : "s"} for new comments and likes`);
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, "Could not scan relays"));
|
||||
} finally {
|
||||
setScanning(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Toolbar>
|
||||
<FilterTabs
|
||||
label="Pending type"
|
||||
value={kind}
|
||||
onChange={setKind}
|
||||
tabs={[
|
||||
{ value: "replies", label: "Comments", count: pending.replies },
|
||||
{ value: "reactions", label: "Likes", count: pending.reactions },
|
||||
]}
|
||||
/>
|
||||
<div className="ml-auto flex gap-2">
|
||||
<Button size="sm" variant="ghost" icon={<RefreshCw size={14} />} loading={scanning} onClick={scan}>
|
||||
Scan posts
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
icon={<CheckCheck size={14} />}
|
||||
loading={approvingAll}
|
||||
disabled={items.length === 0}
|
||||
onClick={approveAll}
|
||||
>
|
||||
Approve all
|
||||
</Button>
|
||||
</div>
|
||||
</Toolbar>
|
||||
|
||||
{error ? (
|
||||
<ErrorState message={error} onRetry={load} />
|
||||
) : (
|
||||
<Panel>
|
||||
{loading ? (
|
||||
<ListSkeleton rows={3} />
|
||||
) : items.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={<ShieldCheck size={20} />}
|
||||
title={kind === "replies" ? "No comments waiting" : "No likes waiting"}
|
||||
description="While comment or like moderation is on in Settings, new ones appear here when a blog post is viewed, or after a scan."
|
||||
/>
|
||||
) : (
|
||||
<RowList>
|
||||
{items.map((item) => (
|
||||
<Row key={item.eventId}>
|
||||
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/[0.04] text-on-surface/45">
|
||||
{item.kind === KIND_REPLY ? <MessageSquare size={15} /> : <Heart size={15} />}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
{item.kind === KIND_REPLY ? (
|
||||
<p className="line-clamp-3 whitespace-pre-wrap break-words text-sm text-on-surface/85">{item.content}</p>
|
||||
) : (
|
||||
<p className="text-sm text-on-surface/85">{item.content && item.content !== "+" ? item.content : "❤️ Like"}</p>
|
||||
)}
|
||||
<p className="mt-0.5 truncate text-xs text-on-surface/45">
|
||||
<span className="font-mono" title={item.pubkey}>{shortNpub(item.pubkey)}</span>
|
||||
{" · "}
|
||||
{fmt(item.eventCreatedAt)}
|
||||
{item.post && (
|
||||
<>
|
||||
{" · on "}
|
||||
<Link href={`/blog/${item.post.slug}`} target="_blank" className="underline hover:text-on-surface">
|
||||
{item.post.title}
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-2">
|
||||
<Button size="sm" variant="secondary" icon={<Check size={14} />} onClick={() => review(item, "approve")}>
|
||||
Approve
|
||||
</Button>
|
||||
<Button size="sm" variant="danger" icon={<X size={14} />} onClick={() => review(item, "reject")}>
|
||||
Reject
|
||||
</Button>
|
||||
</div>
|
||||
</Row>
|
||||
))}
|
||||
</RowList>
|
||||
)}
|
||||
</Panel>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
|
||||
import { nip19 } from "nostr-tools";
|
||||
import { EyeOff, Plus, ShieldCheck, Undo2, UserX } from "lucide-react";
|
||||
import { api } from "@/lib/api";
|
||||
import PendingInteractions from "./PendingInteractions";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
@@ -23,7 +24,8 @@ import {
|
||||
toast,
|
||||
} from "@/components/admin/ui";
|
||||
|
||||
type Tab = "hidden" | "blocked";
|
||||
type Tab = "pending" | "hidden" | "blocked";
|
||||
type ListTab = Exclude<Tab, "pending">;
|
||||
|
||||
const fmt = (d: string) => new Date(d).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
|
||||
|
||||
@@ -46,19 +48,25 @@ function toHex(input: string): string {
|
||||
}
|
||||
|
||||
export default function ModerationPage() {
|
||||
const [tab, setTab] = useState<Tab>("hidden");
|
||||
const [tab, setTab] = useState<Tab>("pending");
|
||||
const [pendingCount, setPendingCount] = useState<number | undefined>(undefined);
|
||||
const [hidden, setHidden] = useState<any[]>([]);
|
||||
const [blocked, setBlocked] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [dialog, setDialog] = useState<Tab | null>(null);
|
||||
const [dialog, setDialog] = useState<ListTab | null>(null);
|
||||
|
||||
const load = async () => {
|
||||
setError("");
|
||||
try {
|
||||
const [h, b] = await Promise.all([api.getHiddenContent(), api.getBlockedPubkeys()]);
|
||||
const [h, b, p] = await Promise.all([
|
||||
api.getHiddenContent(),
|
||||
api.getBlockedPubkeys(),
|
||||
api.getNostrInteractions({ status: "pending" }).catch(() => null),
|
||||
]);
|
||||
setHidden(h);
|
||||
setBlocked(b);
|
||||
if (p) setPendingCount(p.pending.replies + p.pending.reactions);
|
||||
} catch (err) {
|
||||
setError(errorMessage(err, "Could not load moderation data"));
|
||||
} finally {
|
||||
@@ -92,11 +100,13 @@ export default function ModerationPage() {
|
||||
<div>
|
||||
<PageHeader
|
||||
title="Moderation"
|
||||
description="Hide individual Nostr events from the site, or block a pubkey from appearing anywhere."
|
||||
description="Approve blog comments and likes, hide individual Nostr events, or block a pubkey from appearing anywhere."
|
||||
actions={
|
||||
<Button variant="primary" icon={<Plus size={16} />} onClick={() => setDialog(tab)}>
|
||||
{tab === "hidden" ? "Hide an event" : "Block a pubkey"}
|
||||
</Button>
|
||||
tab !== "pending" && (
|
||||
<Button variant="primary" icon={<Plus size={16} />} onClick={() => setDialog(tab)}>
|
||||
{tab === "hidden" ? "Hide an event" : "Block a pubkey"}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -106,13 +116,16 @@ export default function ModerationPage() {
|
||||
value={tab}
|
||||
onChange={setTab}
|
||||
tabs={[
|
||||
{ value: "pending", label: "Pending", count: pendingCount },
|
||||
{ value: "hidden", label: "Hidden events", count: hidden.length },
|
||||
{ value: "blocked", label: "Blocked pubkeys", count: blocked.length },
|
||||
]}
|
||||
/>
|
||||
</Toolbar>
|
||||
|
||||
{error ? (
|
||||
{tab === "pending" ? (
|
||||
<PendingInteractions onCountChange={setPendingCount} />
|
||||
) : error ? (
|
||||
<ErrorState message={error} onRetry={load} />
|
||||
) : (
|
||||
<Panel>
|
||||
@@ -165,7 +178,7 @@ export default function ModerationPage() {
|
||||
);
|
||||
}
|
||||
|
||||
function ModerateDialog({ kind, onClose, onDone }: { kind: Tab | null; onClose: () => void; onDone: (k: Tab) => void }) {
|
||||
function ModerateDialog({ kind, onClose, onDone }: { kind: ListTab | null; onClose: () => void; onDone: (k: ListTab) => void }) {
|
||||
const [value, setValue] = useState("");
|
||||
const [reason, setReason] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import { ErrorState, Field, Input, PageHeader, Panel, SaveBar, Skeleton, errorMessage, toast } from "@/components/admin/ui";
|
||||
import { Checkbox, ErrorState, Field, Input, PageHeader, Panel, SaveBar, Skeleton, errorMessage, toast } from "@/components/admin/ui";
|
||||
|
||||
interface SettingField {
|
||||
key: string;
|
||||
@@ -10,6 +10,8 @@ interface SettingField {
|
||||
placeholder?: string;
|
||||
hint?: string;
|
||||
url?: boolean;
|
||||
/** On/off switch stored as "true"/"false"; the value is used when the key is missing. */
|
||||
toggle?: { default: boolean };
|
||||
}
|
||||
|
||||
const sections: { title: string; description: string; fields: SettingField[] }[] = [
|
||||
@@ -33,10 +35,52 @@ const sections: { title: string; description: string; fields: SettingField[] }[]
|
||||
{ key: "linkedin_link", label: "LinkedIn", placeholder: "https://linkedin.com/company/…", url: true },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Moderation",
|
||||
description: "Choose which community content waits for staff approval before it appears on the site.",
|
||||
fields: [
|
||||
{
|
||||
key: "moderation_videos",
|
||||
label: "Review submitted videos",
|
||||
hint: "Off: videos submitted by members are published immediately.",
|
||||
toggle: { default: true },
|
||||
},
|
||||
{
|
||||
key: "moderation_blog_submissions",
|
||||
label: "Review submitted blog posts",
|
||||
hint: "Off: submitted Nostr articles are imported and published immediately.",
|
||||
toggle: { default: true },
|
||||
},
|
||||
{
|
||||
key: "moderation_board",
|
||||
label: "Review message board posts",
|
||||
hint: "On: paid messages are held until approved in Message board.",
|
||||
toggle: { default: false },
|
||||
},
|
||||
{
|
||||
key: "moderation_blog_comments",
|
||||
label: "Review blog comments",
|
||||
hint: "On: only comments approved under Moderation → Pending are shown.",
|
||||
toggle: { default: false },
|
||||
},
|
||||
{
|
||||
key: "moderation_blog_reactions",
|
||||
label: "Review blog likes",
|
||||
hint: "On: only likes approved under Moderation → Pending are counted.",
|
||||
toggle: { default: false },
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const allFields = sections.flatMap((s) => s.fields);
|
||||
|
||||
function valueOf(f: SettingField, values: Record<string, string>): string {
|
||||
const v = values[f.key];
|
||||
if (f.toggle) return v === "true" || v === "false" ? v : String(f.toggle.default);
|
||||
return v || "";
|
||||
}
|
||||
|
||||
function urlError(value: string): string | null {
|
||||
if (!value.trim()) return null;
|
||||
try {
|
||||
@@ -71,7 +115,7 @@ export default function SettingsPage() {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const changed = allFields.filter((f) => (settings[f.key] || "") !== (original[f.key] || ""));
|
||||
const changed = allFields.filter((f) => valueOf(f, settings) !== valueOf(f, original));
|
||||
const errors = Object.fromEntries(allFields.filter((f) => f.url).map((f) => [f.key, urlError(settings[f.key] || "")]));
|
||||
const hasErrors = changed.some((f) => errors[f.key]);
|
||||
|
||||
@@ -82,7 +126,7 @@ export default function SettingsPage() {
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await Promise.all(changed.map((f) => api.updateSetting(f.key, (settings[f.key] || "").trim())));
|
||||
await Promise.all(changed.map((f) => api.updateSetting(f.key, valueOf(f, settings).trim())));
|
||||
setOriginal({ ...settings });
|
||||
toast.success("Settings saved");
|
||||
} catch (err) {
|
||||
@@ -94,7 +138,7 @@ export default function SettingsPage() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader title="Settings" description="Site-wide text and links." />
|
||||
<PageHeader title="Settings" description="Site-wide text, links and moderation." />
|
||||
|
||||
{error ? (
|
||||
<ErrorState message={error} onRetry={load} />
|
||||
@@ -115,6 +159,15 @@ export default function SettingsPage() {
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-10" />
|
||||
</div>
|
||||
) : f.toggle ? (
|
||||
<Checkbox
|
||||
key={f.key}
|
||||
id={`s-${f.key}`}
|
||||
label={f.label}
|
||||
description={f.hint}
|
||||
checked={valueOf(f, settings) === "true"}
|
||||
onChange={(e) => setSettings({ ...settings, [f.key]: String(e.target.checked) })}
|
||||
/>
|
||||
) : (
|
||||
<Field key={f.key} label={f.label} htmlFor={`s-${f.key}`} error={f.url ? errors[f.key] : null}>
|
||||
<Input
|
||||
|
||||
@@ -155,6 +155,8 @@ interface NostrReply {
|
||||
pubkey: string;
|
||||
content: string;
|
||||
created_at: number;
|
||||
/** Set on your own just-posted comment while comment moderation is on. */
|
||||
awaitingReview?: boolean;
|
||||
}
|
||||
|
||||
/** Likes (kind 7) and comments (kind 1 replies) on the post's Nostr event. */
|
||||
@@ -173,9 +175,13 @@ export function PostEngagement({
|
||||
const [replies, setReplies] = useState<NostrReply[]>([]);
|
||||
const [hasNostr, setHasNostr] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [commentsModerated, setCommentsModerated] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setHasNostr(hasNostrExtension());
|
||||
api.getPublicSettings()
|
||||
.then((s) => setCommentsModerated(s.moderation_blog_comments === "true"))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -230,6 +236,7 @@ export function PostEngagement({
|
||||
pubkey,
|
||||
content: comment.trim(),
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
awaitingReview: commentsModerated,
|
||||
},
|
||||
]);
|
||||
setComment("");
|
||||
@@ -238,7 +245,7 @@ export function PostEngagement({
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}, [comment, nostrEventId, authorPubkey, hasNostr]);
|
||||
}, [comment, nostrEventId, authorPubkey, hasNostr, commentsModerated]);
|
||||
|
||||
return (
|
||||
<section aria-labelledby="comments-heading" className="border-t border-white/[0.06] pt-10">
|
||||
@@ -298,6 +305,9 @@ export function PostEngagement({
|
||||
<span className="text-xs text-on-surface-variant/70">
|
||||
{formatDate(new Date(r.created_at * 1000))}
|
||||
</span>
|
||||
{r.awaitingReview && (
|
||||
<span className="text-xs text-on-surface-variant/70">· Awaiting moderation</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="whitespace-pre-wrap break-words text-sm leading-relaxed text-on-surface-variant">
|
||||
{r.content}
|
||||
|
||||
@@ -25,7 +25,7 @@ type BoardMessage = {
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type PayPhase = "idle" | "polling" | "confirming" | "paid";
|
||||
type PayPhase = "idle" | "polling" | "confirming" | "paid" | "review";
|
||||
|
||||
const MAX_LEN = 300;
|
||||
|
||||
@@ -160,9 +160,11 @@ export default function BoardPage() {
|
||||
await api.confirmBoardPayment(inv.payment_hash).catch(() => {});
|
||||
}
|
||||
|
||||
// Poll until the message actually appears in the list (max ~30s)
|
||||
// Poll until the message actually appears in the list (max ~30s),
|
||||
// or until we learn it is being held for moderation.
|
||||
let found = false;
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
let held = !!status.pendingReview;
|
||||
for (let attempt = 0; attempt < 15 && !held; attempt++) {
|
||||
const list = await api.getBoardMessages();
|
||||
setMessages(list as BoardMessage[]);
|
||||
if (list.some((m) => m.paymentHash === inv.payment_hash)) {
|
||||
@@ -173,13 +175,25 @@ export default function BoardPage() {
|
||||
if (attempt === 2) {
|
||||
await api.confirmBoardPayment(inv.payment_hash).catch(() => {});
|
||||
}
|
||||
const latest = await api.getBoardPaymentStatus(inv.payment_hash).catch(() => null);
|
||||
if (latest?.pendingReview) {
|
||||
held = true;
|
||||
break;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
}
|
||||
|
||||
if (pollRef.current) clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
|
||||
if (found) {
|
||||
if (held) {
|
||||
setPayPhase("review");
|
||||
setContent("");
|
||||
setGuestName("");
|
||||
setPostAsAnon(false);
|
||||
setHighlightPaymentHash(null);
|
||||
setTimeout(() => setPayPhase("idle"), 10000);
|
||||
} else if (found) {
|
||||
setPayPhase("paid");
|
||||
setContent("");
|
||||
setGuestName("");
|
||||
@@ -342,6 +356,9 @@ export default function BoardPage() {
|
||||
<span className="text-primary font-medium animate-pulse">Payment received — publishing…</span>
|
||||
)}
|
||||
{payPhase === "paid" && <span className="text-green-400 font-medium">Posted!</span>}
|
||||
{payPhase === "review" && (
|
||||
<span className="text-green-400 font-medium">Paid — your message will appear once a moderator approves it.</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{payError && <p className="text-error text-sm mt-3">{payError}</p>}
|
||||
|
||||
@@ -176,8 +176,12 @@ export default function DashboardPage() {
|
||||
payload = { title: extractTitle(event), eventId: hexId };
|
||||
}
|
||||
|
||||
await api.createSubmission(payload);
|
||||
setFormSuccess(`Submission "${payload.title}" sent for review!`);
|
||||
const created = await api.createSubmission(payload);
|
||||
setFormSuccess(
|
||||
created?.status === "APPROVED"
|
||||
? `"${payload.title}" is now published on the blog!`
|
||||
: `Submission "${payload.title}" sent for review!`
|
||||
);
|
||||
setNoteInput("");
|
||||
setShowForm(false);
|
||||
await loadSubmissions();
|
||||
|
||||
@@ -110,6 +110,9 @@ function usePendingCount(load: (() => Promise<unknown[]>) | null, pathname: stri
|
||||
|
||||
const loadPendingSubmissions = () => api.getSubmissions("pending");
|
||||
const loadPendingVideos = () => api.getAdminVideos("pending");
|
||||
const loadPendingBoard = () =>
|
||||
api.getAdminBoardMessages().then((list) => list.filter((m: { status: string }) => m.status === "pending"));
|
||||
const loadPendingInteractions = () => api.getNostrInteractions({ status: "pending" }).then((r) => r.items);
|
||||
|
||||
/** Navigation content shared by the desktop sidebar and the mobile drawer. */
|
||||
export function AdminNav({ onNavigate }: { onNavigate?: () => void }) {
|
||||
@@ -117,9 +120,13 @@ export function AdminNav({ onNavigate }: { onNavigate?: () => void }) {
|
||||
const { user, loading, can, logout } = useAuth();
|
||||
const pendingSubmissions = usePendingCount(user && can("submissions.review") ? loadPendingSubmissions : null, pathname);
|
||||
const pendingVideos = usePendingCount(user && can("videos.manage") ? loadPendingVideos : null, pathname);
|
||||
const pendingBoard = usePendingCount(user && can("board.manage") ? loadPendingBoard : null, pathname);
|
||||
const pendingInteractions = usePendingCount(user && can("moderation.act") ? loadPendingInteractions : null, pathname);
|
||||
const pendingByHref: Record<string, number> = {
|
||||
"/admin/submissions": pendingSubmissions,
|
||||
"/admin/videos": pendingVideos,
|
||||
"/admin/messages": pendingBoard,
|
||||
"/admin/moderation": pendingInteractions,
|
||||
};
|
||||
|
||||
const groups = adminNavGroups
|
||||
|
||||
@@ -187,7 +187,7 @@ export function VideoSubmissions() {
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await api.submitVideo({
|
||||
const created = await api.submitVideo({
|
||||
url,
|
||||
title,
|
||||
speaker: form.speaker.trim() || undefined,
|
||||
@@ -195,7 +195,11 @@ export function VideoSubmissions() {
|
||||
categories: form.categories.length ? form.categories : undefined,
|
||||
meetupId: form.meetupId || undefined,
|
||||
});
|
||||
setSuccess(`"${title}" was sent for review. We'll publish it once a moderator has had a look.`);
|
||||
setSuccess(
|
||||
created.status === "PUBLISHED"
|
||||
? `"${title}" is now live in the video archive.`
|
||||
: `"${title}" was sent for review. We'll publish it once a moderator has had a look.`
|
||||
);
|
||||
reset();
|
||||
setShowForm(false);
|
||||
await load();
|
||||
|
||||
+34
-1
@@ -17,6 +17,20 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export interface NostrInteraction {
|
||||
eventId: string;
|
||||
targetEventId: string;
|
||||
kind: number;
|
||||
pubkey: string;
|
||||
content: string;
|
||||
eventCreatedAt: number;
|
||||
status: "pending" | "approved" | "rejected";
|
||||
reviewedBy: string | null;
|
||||
reviewedAt: string | null;
|
||||
createdAt: string;
|
||||
post: { nostrEventId: string; title: string; slug: string } | null;
|
||||
}
|
||||
|
||||
export interface RedirectInput {
|
||||
source: string;
|
||||
destination: string;
|
||||
@@ -126,6 +140,23 @@ export const api = {
|
||||
request<any>("/moderation/block", { method: "POST", body: JSON.stringify({ pubkey, reason }) }),
|
||||
unblockPubkey: (id: string) =>
|
||||
request<void>(`/moderation/unblock/${id}`, { method: "DELETE" }),
|
||||
getNostrInteractions: (params: { status?: string; kind?: number } = {}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.status) qs.set("status", params.status);
|
||||
if (params.kind) qs.set("kind", String(params.kind));
|
||||
return request<{ items: NostrInteraction[]; pending: { replies: number; reactions: number } }>(
|
||||
`/moderation/interactions${qs.toString() ? `?${qs}` : ""}`
|
||||
);
|
||||
},
|
||||
reviewNostrInteraction: (eventId: string, action: "approve" | "reject") =>
|
||||
request<NostrInteraction>(`/moderation/interactions/${encodeURIComponent(eventId)}/${action}`, { method: "POST" }),
|
||||
approveAllNostrInteractions: (kind?: number) =>
|
||||
request<{ updated: number }>("/moderation/interactions/approve-all", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(kind ? { kind } : {}),
|
||||
}),
|
||||
scanNostrInteractions: () =>
|
||||
request<{ scanned: number; pending: number; moderated: boolean }>("/moderation/interactions/scan", { method: "POST" }),
|
||||
|
||||
// Users
|
||||
getUsers: () => request<any[]>("/users"),
|
||||
@@ -338,7 +369,7 @@ export const api = {
|
||||
{ method: "POST", body: JSON.stringify(data) }
|
||||
),
|
||||
getBoardPaymentStatus: (paymentHash: string) =>
|
||||
request<{ paid: boolean; messageCreated: boolean }>(
|
||||
request<{ paid: boolean; messageCreated: boolean; pendingReview?: boolean }>(
|
||||
`/messages/payment/${encodeURIComponent(paymentHash)}/status`
|
||||
),
|
||||
confirmBoardPayment: (paymentHash: string) =>
|
||||
@@ -365,6 +396,8 @@ export const api = {
|
||||
getAdminBoardMessages: () => request<any[]>("/admin/messages"),
|
||||
hideBoardMessage: (id: string) =>
|
||||
request<any>(`/admin/messages/${id}/hide`, { method: "POST" }),
|
||||
approveBoardMessage: (id: string) =>
|
||||
request<any>(`/admin/messages/${id}/approve`, { method: "POST" }),
|
||||
deleteBoardMessage: (id: string) =>
|
||||
request<any>(`/admin/messages/${id}`, { method: "DELETE" }),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user