feat(web): admin app and public Suggest page (v4 Phase 4)
- webapp/admin/: a second Vite entry (/admin/, HashRouter), served only by the Worker after the Access check, with its own CSP. Review queue by status (approve, approve with override for previously removed games, reject), paste-to-add URLs, and a catalog editor for the three maintainer fields, removal with a public reason, and restore of removed games. Uses the published /data for search; every write is applied to the latest repository state by the Worker. An expired Access session surfaces as "sign in again" instead of a broken request. - /suggest (web only; the desktop/Android apps link to the website): itch.io link + optional note (<= 500 characters, deleted after 180 days), Cloudflare Turnstile loaded on demand, EN + VI strings. - Local development: DEV_ADMIN_EMAIL in .dev.vars lets `wrangler dev` on localhost into the admin without Access; it is ignored on any other host. Checked in wrangler dev with a local D1: queue listing, reject, approve answering "GitHub App not configured", catalog search/editor, and a Suggest submission (Turnstile test keys) landing in the queue; no CSP violations. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
19 files changed
+1065
-2
No files matched your search
@@ -0,0 +1,93 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { adminApi, errorText, shortSha, type AddResult } from './api'
|
||||
import { Notice, PUBLISH_NOTE } from './app'
|
||||
|
||||
const OUTCOME: Record<string, string> = {
|
||||
queued: 'new',
|
||||
invalid_url: 'not an itch.io game URL',
|
||||
duplicate_in_request: 'listed twice',
|
||||
duplicate_catalog: 'already in the catalog',
|
||||
duplicate_pending: 'already in the queue',
|
||||
previously_deleted: 'removed before',
|
||||
rejected: 'rejected before',
|
||||
}
|
||||
|
||||
export function AddPage() {
|
||||
const [text, setText] = useState('')
|
||||
const [override, setOverride] = useState(false)
|
||||
const [result, setResult] = useState<AddResult | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const client = useQueryClient()
|
||||
const urls = text
|
||||
.split(/\s+/)
|
||||
.map((u) => u.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const add = useMutation({
|
||||
mutationFn: () => adminApi.add(urls, override),
|
||||
onSuccess: (r) => {
|
||||
setResult(r)
|
||||
setError(null)
|
||||
if (r.results.some((x) => x.approved)) setText('')
|
||||
void client.invalidateQueries({ queryKey: ['queue'] })
|
||||
},
|
||||
onError: (e) => setError(errorText(e)),
|
||||
})
|
||||
|
||||
return (
|
||||
<section className="max-w-3xl">
|
||||
<h1 className="mb-1 text-lg font-semibold">Add games</h1>
|
||||
<p className="mb-3 text-sm text-muted-foreground">
|
||||
Paste itch.io game URLs (one per line, up to 200). New ones are approved right away and scraped by the
|
||||
ingest workflow; paid games are dropped there.
|
||||
</p>
|
||||
<label htmlFor="urls" className="sr-only">
|
||||
Game URLs
|
||||
</label>
|
||||
<textarea
|
||||
id="urls"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
rows={8}
|
||||
spellCheck={false}
|
||||
placeholder="https://creator.itch.io/game"
|
||||
className="w-full rounded-md border bg-background p-2 font-mono text-sm"
|
||||
/>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-4 text-sm">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={override} onChange={(e) => setOverride(e.target.checked)} />
|
||||
Override: also bring back removed or rejected games
|
||||
</label>
|
||||
<Button className="ml-auto" disabled={!urls.length || urls.length > 200 || add.isPending} onClick={() => add.mutate()}>
|
||||
{add.isPending ? 'Adding…' : `Add ${urls.length || ''}`}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mt-4">
|
||||
<Notice text={error} tone="error" onClose={() => setError(null)} />
|
||||
</div>
|
||||
)}
|
||||
{result && (
|
||||
<div className="mt-6">
|
||||
<p className="mb-2 text-sm">
|
||||
{result.results.filter((r) => r.approved).length} queued for ingest ({shortSha(result.sha)}). {PUBLISH_NOTE}
|
||||
</p>
|
||||
<table className="w-full text-sm">
|
||||
<tbody>
|
||||
{result.results.map((r, i) => (
|
||||
<tr key={`${r.input}-${i}`} className="border-b last:border-0">
|
||||
<td className="py-1.5 font-mono text-xs">{r.url ?? r.input}</td>
|
||||
<td className="py-1.5 text-muted-foreground">{OUTCOME[r.outcome] ?? r.outcome}</td>
|
||||
<td className="py-1.5">{r.approved ? 'queued' : r.reason ? r.reason.replace(/_/g, ' ') : '—'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Client for the Worker's /api/admin/* (worker/admin.ts). Same-origin only;
|
||||
* the Cloudflare Access cookie authenticates. When the Access session ends,
|
||||
* Access answers with a redirect to its login page — surfaced as
|
||||
* SessionExpired so the page can ask for a reload instead of failing oddly.
|
||||
*/
|
||||
|
||||
export class SessionExpired extends Error {
|
||||
constructor() {
|
||||
super('Your admin session has expired.')
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number
|
||||
readonly code: string
|
||||
|
||||
constructor(status: number, code: string, message?: string) {
|
||||
super(message ?? code)
|
||||
this.status = status
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
async function api<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
const res = await fetch(path, {
|
||||
method,
|
||||
credentials: 'same-origin',
|
||||
redirect: 'manual',
|
||||
headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
})
|
||||
if (res.type === 'opaqueredirect' || res.status === 401) throw new SessionExpired()
|
||||
const data = (await res.json().catch(() => ({}))) as { error?: string; message?: string }
|
||||
if (!res.ok) throw new ApiError(res.status, data.error ?? `http_${res.status}`, data.message)
|
||||
return data as T
|
||||
}
|
||||
|
||||
export type CandidateStatus = 'pending' | 'rejected' | 'queued' | 'ingested' | 'failed'
|
||||
|
||||
export interface Candidate {
|
||||
url: string
|
||||
source: 'rss' | 'form' | 'ext' | 'admin'
|
||||
status: CandidateStatus
|
||||
title: string | null
|
||||
image_url: string | null
|
||||
genre_hint: string | null
|
||||
flags: string[]
|
||||
note: string | null
|
||||
submitter: string | null
|
||||
discovered_at: string
|
||||
decided_at: string | null
|
||||
}
|
||||
|
||||
export interface Me {
|
||||
email: string
|
||||
writes: boolean
|
||||
}
|
||||
|
||||
export interface Decision {
|
||||
sha: string | null
|
||||
approved: string[]
|
||||
skipped: { url: string; reason: string }[]
|
||||
}
|
||||
|
||||
export interface AddResult {
|
||||
sha: string | null
|
||||
results: { input: string; url: string | null; outcome: string; approved: boolean; reason?: string }[]
|
||||
}
|
||||
|
||||
export type GameEdit = Partial<Record<'safe_virus' | 'nsfw' | 'notes', string>>
|
||||
|
||||
export const adminApi = {
|
||||
me: () => api<Me>('GET', '/api/admin/me'),
|
||||
queue: (status: CandidateStatus) =>
|
||||
api<{ counts: Record<CandidateStatus, number>; items: Candidate[] }>(
|
||||
'GET',
|
||||
`/api/admin/queue?status=${status}&limit=500`,
|
||||
),
|
||||
approve: (urls: string[], override: boolean) =>
|
||||
api<Decision>('POST', '/api/admin/queue/decide', { action: 'approve', urls, override }),
|
||||
reject: (urls: string[]) => api<{ rejected: string[] }>('POST', '/api/admin/queue/decide', { action: 'reject', urls }),
|
||||
add: (urls: string[], override: boolean) => api<AddResult>('POST', '/api/admin/add', { urls, override }),
|
||||
edit: (url: string, edit: GameEdit) => api<{ sha: string | null; edited: number }>('PATCH', '/api/admin/games', { url, edit }),
|
||||
remove: (url: string, reason: string) =>
|
||||
api<{ sha: string | null; removed: number }>('DELETE', '/api/admin/games', { url, reason }),
|
||||
restore: (url: string) => api<{ sha: string | null; queued: boolean }>('POST', '/api/admin/games/restore', { url }),
|
||||
}
|
||||
|
||||
export function shortSha(sha: string | null): string {
|
||||
return sha ? sha.slice(0, 7) : 'no commit'
|
||||
}
|
||||
|
||||
export function errorText(e: unknown): string {
|
||||
if (e instanceof SessionExpired) return e.message
|
||||
if (e instanceof ApiError) {
|
||||
const known: Record<string, string> = {
|
||||
forbidden: 'This account is not allowed to use the admin.',
|
||||
not_configured: 'The admin is not configured yet (Cloudflare Access / D1).',
|
||||
github_not_configured: 'Writes are off: the GitHub App is not configured.',
|
||||
needs_override: 'Previously removed — approve with override.',
|
||||
}
|
||||
return known[e.code] ?? e.message
|
||||
}
|
||||
return e instanceof Error ? e.message : String(e)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { NavLink, Navigate, Route, Routes } from 'react-router'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { SessionExpired, adminApi, errorText } from './api'
|
||||
import { AddPage } from './add'
|
||||
import { CatalogPage } from './catalog'
|
||||
import { QueuePage } from './queue'
|
||||
|
||||
const NAV = [
|
||||
{ to: '/queue', label: 'Review queue' },
|
||||
{ to: '/add', label: 'Add games' },
|
||||
{ to: '/catalog', label: 'Catalog' },
|
||||
]
|
||||
|
||||
export function AdminApp() {
|
||||
const me = useQuery({ queryKey: ['me'], queryFn: adminApi.me })
|
||||
|
||||
if (me.error) {
|
||||
return (
|
||||
<div className="mx-auto max-w-lg p-8 text-sm">
|
||||
<h1 className="mb-2 text-lg font-semibold">Admin unavailable</h1>
|
||||
<p className="mb-4 text-muted-foreground">{errorText(me.error)}</p>
|
||||
{me.error instanceof SessionExpired && (
|
||||
<button className="underline" onClick={() => window.location.reload()}>
|
||||
Sign in again
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
<header className="sticky top-0 z-10 border-b bg-background/95 backdrop-blur">
|
||||
<div className="mx-auto flex h-12 max-w-6xl items-center gap-6 px-4 text-sm">
|
||||
<span className="font-semibold">freeitchgames.win · admin</span>
|
||||
<nav className="flex gap-1">
|
||||
{NAV.map((n) => (
|
||||
<NavLink
|
||||
key={n.to}
|
||||
to={n.to}
|
||||
className={({ isActive }) =>
|
||||
cn('rounded-md px-3 py-1.5 hover:bg-accent', isActive && 'bg-accent font-medium')
|
||||
}
|
||||
>
|
||||
{n.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
<span className="ml-auto truncate text-muted-foreground">
|
||||
{me.data ? me.data.email : '…'}
|
||||
{me.data && !me.data.writes && ' · read-only (GitHub App not configured)'}
|
||||
</span>
|
||||
<a className="text-muted-foreground hover:text-foreground" href="/" target="_blank" rel="noreferrer">
|
||||
Site ↗
|
||||
</a>
|
||||
</div>
|
||||
</header>
|
||||
<main className="mx-auto max-w-6xl p-4">
|
||||
<Routes>
|
||||
<Route path="/queue" element={<QueuePage />} />
|
||||
<Route path="/add" element={<AddPage />} />
|
||||
<Route path="/catalog" element={<CatalogPage />} />
|
||||
<Route path="*" element={<Navigate to="/queue" replace />} />
|
||||
</Routes>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** A dismissible line reporting what the last action did. */
|
||||
export function Notice({ text, tone = 'info', onClose }: { text: string; tone?: 'info' | 'error'; onClose: () => void }) {
|
||||
return (
|
||||
<div
|
||||
role={tone === 'error' ? 'alert' : 'status'}
|
||||
className={cn(
|
||||
'mb-4 flex items-start gap-3 rounded-md border px-3 py-2 text-sm',
|
||||
tone === 'error' ? 'border-destructive/50 text-destructive' : 'bg-muted/50',
|
||||
)}
|
||||
>
|
||||
<span className="flex-1 whitespace-pre-line">{text}</span>
|
||||
<button aria-label="Dismiss" className="text-muted-foreground hover:text-foreground" onClick={onClose}>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const PUBLISH_NOTE = 'The public site shows it after the next build (a few minutes).'
|
||||
@@ -0,0 +1,221 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useAllGames, useDeletedGames } from '@/hooks/useGames'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { Game } from '@/types/game'
|
||||
import { adminApi, errorText, shortSha, type GameEdit } from './api'
|
||||
import { Notice, PUBLISH_NOTE } from './app'
|
||||
|
||||
const MAX_RESULTS = 50
|
||||
|
||||
function matches(query: string, ...fields: string[]): boolean {
|
||||
const q = query.trim().toLowerCase()
|
||||
return q.length > 0 && fields.some((f) => f.toLowerCase().includes(q))
|
||||
}
|
||||
|
||||
export function CatalogPage() {
|
||||
const games = useAllGames()
|
||||
const deleted = useDeletedGames()
|
||||
const [query, setQuery] = useState('')
|
||||
const [selected, setSelected] = useState<Game | null>(null)
|
||||
const [tab, setTab] = useState<'catalog' | 'removed'>('catalog')
|
||||
|
||||
const found = useMemo(
|
||||
() => (games.data?.games ?? []).filter((g) => matches(query, g.name, g.url, g.dev)).slice(0, MAX_RESULTS),
|
||||
[games.data, query],
|
||||
)
|
||||
const removed = useMemo(
|
||||
() => (deleted.data ?? []).filter((d) => !query.trim() || matches(query, d.name, d.url)).slice(-MAX_RESULTS).reverse(),
|
||||
[deleted.data, query],
|
||||
)
|
||||
|
||||
return (
|
||||
<section className="grid gap-6 md:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)]">
|
||||
<div>
|
||||
<div className="mb-3 flex gap-1 text-sm" role="tablist" aria-label="Catalog or removed games">
|
||||
{(['catalog', 'removed'] as const).map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
role="tab"
|
||||
aria-selected={tab === t}
|
||||
onClick={() => setTab(t)}
|
||||
className={cn('rounded-md px-3 py-1.5 hover:bg-accent', tab === t && 'bg-accent font-medium')}
|
||||
>
|
||||
{t === 'catalog' ? `Catalog ${games.data ? `(${games.data.games.length})` : ''}` : 'Removed'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<Input
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Search by name, developer or URL"
|
||||
aria-label="Search games"
|
||||
/>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
Data of the published site; edits apply to the latest repository state.
|
||||
</p>
|
||||
{tab === 'catalog' ? (
|
||||
<ul className="mt-3 divide-y text-sm">
|
||||
{games.isPending && <li className="py-2 text-muted-foreground">Loading catalog…</li>}
|
||||
{found.map((g) => (
|
||||
<li key={g.url}>
|
||||
<button
|
||||
onClick={() => setSelected(g)}
|
||||
className={cn('w-full py-2 text-left hover:bg-accent/50', selected?.url === g.url && 'bg-accent')}
|
||||
>
|
||||
<span className="font-medium">{g.name}</span>
|
||||
<span className="block text-xs text-muted-foreground">{g.url.replace('https://', '')}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{query && games.data && found.length === 0 && <li className="py-2 text-muted-foreground">No match.</li>}
|
||||
</ul>
|
||||
) : (
|
||||
<RemovedList entries={removed} />
|
||||
)}
|
||||
</div>
|
||||
<div>{selected && tab === 'catalog' && <GameEditor key={selected.url} game={selected} />}</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function GameEditor({ game }: { game: Game }) {
|
||||
const [edit, setEdit] = useState<Required<GameEdit>>({
|
||||
safe_virus: game.safe_virus,
|
||||
nsfw: game.nsfw,
|
||||
notes: game.notes ?? '',
|
||||
})
|
||||
const [reason, setReason] = useState('')
|
||||
const [notice, setNotice] = useState<{ text: string; tone: 'info' | 'error' } | null>(null)
|
||||
|
||||
const changed = (Object.keys(edit) as (keyof GameEdit)[]).filter((k) => edit[k] !== (game[k] ?? ''))
|
||||
const save = useMutation({
|
||||
mutationFn: () => adminApi.edit(game.url, Object.fromEntries(changed.map((k) => [k, edit[k]]))),
|
||||
onSuccess: (r) =>
|
||||
setNotice({
|
||||
tone: 'info',
|
||||
text: r.edited ? `Saved (${shortSha(r.sha)}). ${PUBLISH_NOTE}` : 'Nothing changed in the repository.',
|
||||
}),
|
||||
onError: (e) => setNotice({ tone: 'error', text: errorText(e) }),
|
||||
})
|
||||
const remove = useMutation({
|
||||
mutationFn: () => adminApi.remove(game.url, reason.trim()),
|
||||
onSuccess: (r) => setNotice({ tone: 'info', text: `Removed (${shortSha(r.sha)}); its resized covers were deleted. ${PUBLISH_NOTE}` }),
|
||||
onError: (e) => setNotice({ tone: 'error', text: errorText(e) }),
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border p-4 text-sm">
|
||||
<h2 className="text-base font-semibold">{game.name}</h2>
|
||||
<a href={game.url} target="_blank" rel="noreferrer noopener" className="text-xs text-muted-foreground hover:underline">
|
||||
{game.url}
|
||||
</a>
|
||||
<div className="mt-4">{notice && <Notice text={notice.text} tone={notice.tone} onClose={() => setNotice(null)} />}</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="grid gap-1">
|
||||
<span className="text-xs text-muted-foreground">Virus check</span>
|
||||
<select
|
||||
value={edit.safe_virus}
|
||||
onChange={(e) => setEdit({ ...edit, safe_virus: e.target.value })}
|
||||
className="h-9 rounded-md border bg-background px-2"
|
||||
>
|
||||
{['?', 'Yes', 'No', 'Caution'].map((v) => (
|
||||
<option key={v} value={v}>
|
||||
{v === '?' ? 'Not checked (?)' : v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
<span className="text-xs text-muted-foreground">NSFW (18+)</span>
|
||||
<select
|
||||
value={edit.nsfw}
|
||||
onChange={(e) => setEdit({ ...edit, nsfw: e.target.value })}
|
||||
className="h-9 rounded-md border bg-background px-2"
|
||||
>
|
||||
<option value="No">No</option>
|
||||
<option value="Yes">Yes</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<label className="mt-3 grid gap-1">
|
||||
<span className="text-xs text-muted-foreground">Notes (public)</span>
|
||||
<textarea
|
||||
value={edit.notes}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
onChange={(e) => setEdit({ ...edit, notes: e.target.value })}
|
||||
className="rounded-md border bg-background p-2"
|
||||
/>
|
||||
</label>
|
||||
<Button className="mt-3" disabled={!changed.length || save.isPending} onClick={() => save.mutate()}>
|
||||
{save.isPending ? 'Saving…' : 'Save'}
|
||||
</Button>
|
||||
|
||||
<div className="mt-8 border-t pt-4">
|
||||
<h3 className="mb-1 font-medium text-destructive">Remove from the catalog</h3>
|
||||
<p className="mb-2 text-xs text-muted-foreground">
|
||||
The reason is public (removed-games list). Use this for content-removal requests too.
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Input value={reason} maxLength={200} onChange={(e) => setReason(e.target.value)} placeholder="Reason" aria-label="Removal reason" />
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={!reason.trim() || remove.isPending}
|
||||
onClick={() => {
|
||||
if (window.confirm(`Remove "${game.name}" from the catalog?`)) remove.mutate()
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RemovedList({ entries }: { entries: { url: string; name: string; reason: string; deleted_at: string }[] }) {
|
||||
const [notice, setNotice] = useState<{ text: string; tone: 'info' | 'error' } | null>(null)
|
||||
const restore = useMutation({
|
||||
mutationFn: (url: string) => adminApi.restore(url),
|
||||
onSuccess: (r) =>
|
||||
setNotice({
|
||||
tone: 'info',
|
||||
text: r.queued ? `Queued for re-ingest (${shortSha(r.sha)}). ${PUBLISH_NOTE}` : 'Already queued.',
|
||||
}),
|
||||
onError: (e) => setNotice({ tone: 'error', text: errorText(e) }),
|
||||
})
|
||||
return (
|
||||
<div className="mt-3">
|
||||
{notice && <Notice text={notice.text} tone={notice.tone} onClose={() => setNotice(null)} />}
|
||||
<ul className="divide-y text-sm">
|
||||
{entries.map((d) => (
|
||||
<li key={d.url} className="flex items-start gap-3 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="font-medium">{d.name}</span>
|
||||
<span className="block truncate text-xs text-muted-foreground">
|
||||
{d.deleted_at.slice(0, 10)} · {d.reason}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={restore.isPending}
|
||||
onClick={() => {
|
||||
if (window.confirm(`Bring "${d.name}" back? It is re-scraped; a paid game is dropped again.`)) {
|
||||
restore.mutate(d.url)
|
||||
}
|
||||
}}
|
||||
>
|
||||
Restore
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<title>Admin · freeitchgames.win</title>
|
||||
</head>
|
||||
<body class="bg-background text-foreground antialiased">
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { HashRouter } from 'react-router'
|
||||
import '@/index.css'
|
||||
import { AdminApp } from './app'
|
||||
import { SessionExpired } from './api'
|
||||
|
||||
// Follow the system theme (the admin has no settings of its own).
|
||||
const dark = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
const applyTheme = () => document.documentElement.classList.toggle('dark', dark.matches)
|
||||
applyTheme()
|
||||
dark.addEventListener('change', applyTheme)
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: (count, error) => !(error instanceof SessionExpired) && count < 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const root = document.getElementById('root')
|
||||
if (!root) throw new Error('Root element not found')
|
||||
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<HashRouter>
|
||||
<AdminApp />
|
||||
</HashRouter>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,195 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { adminApi, errorText, shortSha, type Candidate, type CandidateStatus } from './api'
|
||||
import { Notice, PUBLISH_NOTE } from './app'
|
||||
|
||||
const STATUSES: { id: CandidateStatus; label: string }[] = [
|
||||
{ id: 'pending', label: 'Pending' },
|
||||
{ id: 'failed', label: 'Failed' },
|
||||
{ id: 'queued', label: 'Queued' },
|
||||
{ id: 'rejected', label: 'Rejected' },
|
||||
{ id: 'ingested', label: 'Ingested' },
|
||||
]
|
||||
|
||||
const SOURCE: Record<Candidate['source'], string> = { rss: 'RSS', form: 'Suggest form', ext: 'Extension', admin: 'Admin' }
|
||||
|
||||
const FLAG: Record<string, { label: string; variant: 'destructive' | 'secondary' | 'outline' }> = {
|
||||
previously_deleted: { label: 'previously removed', variant: 'destructive' },
|
||||
nsfw_keyword: { label: 'NSFW?', variant: 'secondary' },
|
||||
demo: { label: 'demo', variant: 'outline' },
|
||||
}
|
||||
|
||||
export function QueuePage() {
|
||||
const [status, setStatus] = useState<CandidateStatus>('pending')
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [notice, setNotice] = useState<{ text: string; tone: 'info' | 'error' } | null>(null)
|
||||
const client = useQueryClient()
|
||||
const queue = useQuery({ queryKey: ['queue', status], queryFn: () => adminApi.queue(status) })
|
||||
|
||||
const done = () => {
|
||||
setSelected(new Set())
|
||||
void client.invalidateQueries({ queryKey: ['queue'] })
|
||||
}
|
||||
const approve = useMutation({
|
||||
mutationFn: ({ urls, override }: { urls: string[]; override: boolean }) => adminApi.approve(urls, override),
|
||||
onSuccess: (d) => {
|
||||
const skipped = d.skipped.map((s) => ` ${s.url} — ${s.reason.replace(/_/g, ' ')}`).join('\n')
|
||||
setNotice({
|
||||
tone: 'info',
|
||||
text:
|
||||
`Queued ${d.approved.length} for ingest (${shortSha(d.sha)}). ${PUBLISH_NOTE}` +
|
||||
(skipped ? `\nSkipped:\n${skipped}` : ''),
|
||||
})
|
||||
done()
|
||||
},
|
||||
onError: (e) => setNotice({ tone: 'error', text: errorText(e) }),
|
||||
})
|
||||
const reject = useMutation({
|
||||
mutationFn: (urls: string[]) => adminApi.reject(urls),
|
||||
onSuccess: (d) => {
|
||||
setNotice({ tone: 'info', text: `Rejected ${d.rejected.length} (they stay blocked from every source).` })
|
||||
done()
|
||||
},
|
||||
onError: (e) => setNotice({ tone: 'error', text: errorText(e) }),
|
||||
})
|
||||
|
||||
const items = queue.data?.items ?? []
|
||||
const allSelected = items.length > 0 && items.every((c) => selected.has(c.url))
|
||||
const toggle = (url: string) =>
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(url)) next.delete(url)
|
||||
else next.add(url)
|
||||
return next
|
||||
})
|
||||
const urls = [...selected]
|
||||
const busy = approve.isPending || reject.isPending
|
||||
const canApprove = status !== 'queued' && status !== 'ingested'
|
||||
|
||||
return (
|
||||
<section>
|
||||
<div className="mb-4 flex flex-wrap items-center gap-1" role="tablist" aria-label="Queue status">
|
||||
{STATUSES.map((s) => (
|
||||
<button
|
||||
key={s.id}
|
||||
role="tab"
|
||||
aria-selected={status === s.id}
|
||||
onClick={() => {
|
||||
setStatus(s.id)
|
||||
setSelected(new Set())
|
||||
}}
|
||||
className={cn(
|
||||
'rounded-md px-3 py-1.5 text-sm hover:bg-accent',
|
||||
status === s.id && 'bg-accent font-medium',
|
||||
)}
|
||||
>
|
||||
{s.label}
|
||||
<span className="ml-1.5 tabular-nums text-muted-foreground">{queue.data?.counts[s.id] ?? ''}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{notice && <Notice text={notice.text} tone={notice.tone} onClose={() => setNotice(null)} />}
|
||||
|
||||
{canApprove && (
|
||||
<div className="mb-3 flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="text-muted-foreground">{selected.size} selected</span>
|
||||
<Button size="sm" disabled={!selected.size || busy} onClick={() => approve.mutate({ urls, override: false })}>
|
||||
Approve
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={!selected.size || busy}
|
||||
title="Also brings back games that were removed from the catalog before"
|
||||
onClick={() => {
|
||||
if (window.confirm(`Approve ${urls.length} game(s), including previously removed ones?`)) {
|
||||
approve.mutate({ urls, override: true })
|
||||
}
|
||||
}}
|
||||
>
|
||||
Approve with override
|
||||
</Button>
|
||||
{status !== 'rejected' && (
|
||||
<Button size="sm" variant="destructive" disabled={!selected.size || busy} onClick={() => reject.mutate(urls)}>
|
||||
Reject
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{queue.isPending && <p className="text-sm text-muted-foreground">Loading…</p>}
|
||||
{queue.error && <Notice text={errorText(queue.error)} tone="error" onClose={() => void queue.refetch()} />}
|
||||
{queue.data && items.length === 0 && <p className="text-sm text-muted-foreground">Nothing here.</p>}
|
||||
|
||||
{items.length > 0 && (
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b text-left text-xs uppercase text-muted-foreground">
|
||||
<tr>
|
||||
{canApprove && (
|
||||
<th className="w-8 py-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="Select all"
|
||||
checked={allSelected}
|
||||
onChange={() => setSelected(allSelected ? new Set() : new Set(items.map((c) => c.url)))}
|
||||
/>
|
||||
</th>
|
||||
)}
|
||||
<th className="w-20 py-2">Cover</th>
|
||||
<th className="py-2">Game</th>
|
||||
<th className="py-2">From</th>
|
||||
<th className="py-2">Found</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((c) => (
|
||||
<tr key={c.url} className="border-b align-top last:border-0">
|
||||
{canApprove && (
|
||||
<td className="py-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`Select ${c.title ?? c.url}`}
|
||||
checked={selected.has(c.url)}
|
||||
onChange={() => toggle(c.url)}
|
||||
/>
|
||||
</td>
|
||||
)}
|
||||
<td className="py-2">
|
||||
{c.image_url ? (
|
||||
<img src={c.image_url} alt="" loading="lazy" className="h-12 w-16 rounded object-cover" />
|
||||
) : (
|
||||
<div className="h-12 w-16 rounded bg-muted" />
|
||||
)}
|
||||
</td>
|
||||
<td className="py-2">
|
||||
<a href={c.url} target="_blank" rel="noreferrer noopener" className="font-medium hover:underline">
|
||||
{c.title ?? c.url.replace('https://', '')}
|
||||
</a>
|
||||
<div className="text-xs text-muted-foreground">{c.url.replace('https://', '')}</div>
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
{c.genre_hint && <Badge variant="outline">{c.genre_hint}</Badge>}
|
||||
{c.flags.map((f) => (
|
||||
<Badge key={f} variant={FLAG[f]?.variant ?? 'outline'}>
|
||||
{FLAG[f]?.label ?? f}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
{c.note && <p className="mt-1 whitespace-pre-line text-xs">“{c.note}”</p>}
|
||||
</td>
|
||||
<td className="py-2 text-xs text-muted-foreground">
|
||||
{SOURCE[c.source]}
|
||||
{c.submitter && c.source !== 'form' && c.source !== 'admin' && <div>{c.submitter}</div>}
|
||||
</td>
|
||||
<td className="py-2 text-xs tabular-nums text-muted-foreground">{c.discovered_at.slice(0, 10)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -18,6 +18,7 @@ const GameDetail = lazy(() => import('@/routes/game-detail'))
|
||||
const Charts = lazy(() => import('@/routes/charts'))
|
||||
const Settings = lazy(() => import('@/routes/settings'))
|
||||
const About = lazy(() => import('@/routes/about'))
|
||||
const Suggest = lazy(() => import('@/routes/suggest'))
|
||||
const ErrorPreview = lazy(() => import('@/routes/error-preview'))
|
||||
|
||||
function RouteFallback() {
|
||||
@@ -70,6 +71,7 @@ export default function App() {
|
||||
<Route path="/deleted" element={<Deleted />} />
|
||||
<Route path="/settings" element={<Settings />} />
|
||||
<Route path="/about" element={<About />} />
|
||||
<Route path="/suggest" element={<Suggest />} />
|
||||
<Route path="/errors/:code" element={<ErrorPreview />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
PanelLeft,
|
||||
Menu,
|
||||
Heart,
|
||||
Lightbulb,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -37,6 +38,7 @@ const NAV_ITEMS: NavItem[] = [
|
||||
{ to: '/games', label: 'nav.games', icon: Gamepad2 },
|
||||
{ to: '/charts', label: 'nav.charts', icon: BarChart3 },
|
||||
{ to: '/deleted', label: 'nav.deleted', icon: Trash2 },
|
||||
{ to: '/suggest', label: 'nav.suggest', icon: Lightbulb },
|
||||
{ to: '/settings', label: 'nav.settings', icon: Settings },
|
||||
{ to: '/about', label: 'nav.about', icon: Info },
|
||||
]
|
||||
|
||||
@@ -257,6 +257,29 @@ export const en = {
|
||||
"about.app.access": "Read-only and public: no account, no sign-in, no cookies. The catalog is served from this site and refreshed daily by the data pipeline.",
|
||||
"about.app.descSuffix": " catalog. Browse 2,600+ free games from itch.io, filter and sort them, and explore the dataset with charts.",
|
||||
"games.tip": "Tip: Shift-click column headers for multi-column sort.",
|
||||
// ---- suggest ----
|
||||
"nav.suggest": "Suggest a game",
|
||||
"titles.suggest": "Suggest a game",
|
||||
"suggest.intro": "Know a free itch.io game that is missing here? Send its link. Suggestions go into a review queue, and the maintainer checks each one before it is added.",
|
||||
"suggest.url": "Game link",
|
||||
"suggest.urlHint": "The game's itch.io page, like https://creator.itch.io/game.",
|
||||
"suggest.note": "Note (optional)",
|
||||
"suggest.notePrivacy": "Only the maintainer sees it, and it is deleted after 180 days. Please don't include personal data.",
|
||||
"suggest.challenge": "Anti-spam check",
|
||||
"suggest.submit": "Send suggestion",
|
||||
"suggest.sending": "Sending…",
|
||||
"suggest.closed": "Suggestions are closed right now. Please try again later.",
|
||||
"suggest.webOnly": "Suggestions are sent from the website.",
|
||||
"suggest.openWebsite": "Open the Suggest page on freeitchgames.win",
|
||||
"suggest.status.received": "Thanks! The game is in the review queue.",
|
||||
"suggest.status.alreadyListed": "This game is already in the catalog.",
|
||||
"suggest.status.alreadySuggested": "Someone already suggested this game; it is waiting for review.",
|
||||
"suggest.status.notAccepted": "This game can't be added to the catalog.",
|
||||
"suggest.error.invalidUrl": "That doesn't look like an itch.io game link.",
|
||||
"suggest.error.rateLimited": "Too many suggestions at once. Please wait a minute.",
|
||||
"suggest.error.challenge": "The anti-spam check failed. Please try again.",
|
||||
"suggest.error.challengeLoad": "The anti-spam check couldn't load. Check your connection or content blocker.",
|
||||
"suggest.error.generic": "Something went wrong. Please try again later.",
|
||||
} as const
|
||||
|
||||
export type MessageKey = keyof typeof en
|
||||
@@ -259,4 +259,27 @@ export const vi: Record<MessageKey, string> = {
|
||||
"about.app.access": "Chỉ xem và công khai: không tài khoản, không đăng nhập, không cookie. Danh mục được phục vụ từ chính trang này và làm mới hằng ngày bởi pipeline dữ liệu.",
|
||||
"about.app.descSuffix": ". Duyệt hơn 2.600 game miễn phí từ itch.io, lọc, sắp xếp và khám phá dữ liệu qua biểu đồ.",
|
||||
"games.tip": "Mẹo: Shift-click tiêu đề cột để sắp xếp theo nhiều cột.",
|
||||
// ---- suggest ----
|
||||
"nav.suggest": "Đề xuất game",
|
||||
"titles.suggest": "Đề xuất game",
|
||||
"suggest.intro": "Bạn biết một game miễn phí trên itch.io mà chưa có ở đây? Gửi link cho chúng tôi. Đề xuất sẽ vào hàng chờ duyệt, và maintainer kiểm tra từng game trước khi thêm.",
|
||||
"suggest.url": "Link game",
|
||||
"suggest.urlHint": "Trang itch.io của game, dạng https://creator.itch.io/game.",
|
||||
"suggest.note": "Ghi chú (không bắt buộc)",
|
||||
"suggest.notePrivacy": "Chỉ maintainer đọc được và sẽ bị xoá sau 180 ngày. Vui lòng không ghi thông tin cá nhân.",
|
||||
"suggest.challenge": "Kiểm tra chống spam",
|
||||
"suggest.submit": "Gửi đề xuất",
|
||||
"suggest.sending": "Đang gửi…",
|
||||
"suggest.closed": "Hiện chưa nhận đề xuất. Vui lòng thử lại sau.",
|
||||
"suggest.webOnly": "Đề xuất được gửi từ website.",
|
||||
"suggest.openWebsite": "Mở trang Đề xuất trên freeitchgames.win",
|
||||
"suggest.status.received": "Cảm ơn bạn! Game đã vào hàng chờ duyệt.",
|
||||
"suggest.status.alreadyListed": "Game này đã có trong danh mục.",
|
||||
"suggest.status.alreadySuggested": "Game này đã được đề xuất và đang chờ duyệt.",
|
||||
"suggest.status.notAccepted": "Game này không thể được thêm vào danh mục.",
|
||||
"suggest.error.invalidUrl": "Link này có vẻ không phải trang game trên itch.io.",
|
||||
"suggest.error.rateLimited": "Bạn gửi quá nhiều đề xuất cùng lúc. Vui lòng đợi một phút.",
|
||||
"suggest.error.challenge": "Kiểm tra chống spam không thành công. Vui lòng thử lại.",
|
||||
"suggest.error.challengeLoad": "Không tải được bước kiểm tra chống spam. Hãy kiểm tra kết nối hoặc trình chặn nội dung.",
|
||||
"suggest.error.generic": "Đã có lỗi xảy ra. Vui lòng thử lại sau.",
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Cloudflare Turnstile, loaded on demand (only the Suggest page needs it; the
|
||||
* site CSP allows its script and frame). Explicit rendering, so the widget
|
||||
* mounts and unmounts with the React component.
|
||||
*/
|
||||
|
||||
interface TurnstileOptions {
|
||||
sitekey: string
|
||||
action?: string
|
||||
theme?: 'auto' | 'light' | 'dark'
|
||||
callback: (token: string) => void
|
||||
'expired-callback'?: () => void
|
||||
'error-callback'?: () => void
|
||||
}
|
||||
|
||||
interface TurnstileApi {
|
||||
render(container: HTMLElement, options: TurnstileOptions): string
|
||||
reset(widgetId: string): void
|
||||
remove(widgetId: string): void
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: TurnstileApi
|
||||
}
|
||||
}
|
||||
|
||||
const SCRIPT = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
|
||||
let loading: Promise<TurnstileApi> | null = null
|
||||
|
||||
export function loadTurnstile(): Promise<TurnstileApi> {
|
||||
if (window.turnstile) return Promise.resolve(window.turnstile)
|
||||
loading ??= new Promise<TurnstileApi>((resolve, reject) => {
|
||||
const script = document.createElement('script')
|
||||
script.src = SCRIPT
|
||||
script.onload = () => (window.turnstile ? resolve(window.turnstile) : reject(new Error('Turnstile did not load')))
|
||||
script.onerror = () => {
|
||||
loading = null
|
||||
script.remove()
|
||||
reject(new Error('Turnstile did not load'))
|
||||
}
|
||||
document.head.appendChild(script)
|
||||
})
|
||||
return loading
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { ExtLink } from '@/components/ext-link'
|
||||
import { useDocumentTitle } from '@/hooks/useDocumentTitle'
|
||||
import { useT, type MessageKey } from '@/lib/i18n'
|
||||
import { isTauri } from '@/lib/runtime'
|
||||
import { SITE_ORIGIN } from '@/lib/config'
|
||||
import { loadTurnstile } from '@/lib/turnstile'
|
||||
|
||||
const MAX_NOTE = 500
|
||||
const ITCH_GAME = /^\s*(https?:\/\/)?[a-z0-9-]+\.itch\.io\/[a-z0-9_-]+\/?\s*$/i
|
||||
|
||||
type Result = { tone: 'ok' | 'error'; key: MessageKey }
|
||||
|
||||
const STATUS_KEY: Record<string, MessageKey> = {
|
||||
received: 'suggest.status.received',
|
||||
already_listed: 'suggest.status.alreadyListed',
|
||||
already_suggested: 'suggest.status.alreadySuggested',
|
||||
not_accepted: 'suggest.status.notAccepted',
|
||||
}
|
||||
const ERROR_KEY: Record<string, MessageKey> = {
|
||||
invalid_url: 'suggest.error.invalidUrl',
|
||||
rate_limited: 'suggest.error.rateLimited',
|
||||
challenge_failed: 'suggest.error.challenge',
|
||||
}
|
||||
|
||||
interface SuggestConfig {
|
||||
enabled: boolean
|
||||
sitekey: string | null
|
||||
}
|
||||
|
||||
export default function Suggest() {
|
||||
const t = useT()
|
||||
useDocumentTitle(t('titles.suggest'))
|
||||
|
||||
if (isTauri()) {
|
||||
return (
|
||||
<div className="container mx-auto max-w-xl space-y-3 p-6">
|
||||
<h1 className="text-2xl font-semibold">{t('titles.suggest')}</h1>
|
||||
<p className="text-muted-foreground">{t('suggest.webOnly')}</p>
|
||||
<ExtLink href={`${SITE_ORIGIN}/suggest`} className="text-primary underline-offset-4 hover:underline">
|
||||
{t('suggest.openWebsite')}
|
||||
</ExtLink>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return <SuggestForm />
|
||||
}
|
||||
|
||||
function SuggestForm() {
|
||||
const t = useT()
|
||||
const config = useQuery({
|
||||
queryKey: ['suggest-config'],
|
||||
queryFn: async (): Promise<SuggestConfig> => {
|
||||
const res = await fetch('/api/suggest')
|
||||
return res.ok ? ((await res.json()) as SuggestConfig) : { enabled: false, sitekey: null }
|
||||
},
|
||||
staleTime: 5 * 60_000,
|
||||
})
|
||||
const [url, setUrl] = useState('')
|
||||
const [note, setNote] = useState('')
|
||||
const [token, setToken] = useState('')
|
||||
const [sending, setSending] = useState(false)
|
||||
const [result, setResult] = useState<Result | null>(null)
|
||||
const widget = useRef<HTMLDivElement>(null)
|
||||
const widgetId = useRef<string | null>(null)
|
||||
|
||||
const sitekey = config.data?.enabled ? config.data.sitekey : null
|
||||
useEffect(() => {
|
||||
if (!sitekey || !widget.current) return
|
||||
let cancelled = false
|
||||
const el = widget.current
|
||||
loadTurnstile()
|
||||
.then((turnstile) => {
|
||||
if (cancelled) return
|
||||
widgetId.current = turnstile.render(el, {
|
||||
sitekey,
|
||||
action: 'suggest',
|
||||
theme: 'auto',
|
||||
callback: setToken,
|
||||
'expired-callback': () => setToken(''),
|
||||
'error-callback': () => setToken(''),
|
||||
})
|
||||
})
|
||||
.catch(() => setResult({ tone: 'error', key: 'suggest.error.challengeLoad' }))
|
||||
return () => {
|
||||
cancelled = true
|
||||
if (widgetId.current) window.turnstile?.remove(widgetId.current)
|
||||
widgetId.current = null
|
||||
}
|
||||
}, [sitekey])
|
||||
|
||||
const urlValid = ITCH_GAME.test(url)
|
||||
|
||||
async function submit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!urlValid || !token || sending) return
|
||||
setSending(true)
|
||||
setResult(null)
|
||||
try {
|
||||
const res = await fetch('/api/suggest', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: url.trim(), note: note.trim(), token }),
|
||||
})
|
||||
const data = (await res.json().catch(() => ({}))) as { status?: string; error?: string }
|
||||
if (res.ok && data.status) {
|
||||
setResult({ tone: data.status === 'received' ? 'ok' : 'error', key: STATUS_KEY[data.status] ?? 'suggest.error.generic' })
|
||||
if (data.status === 'received') {
|
||||
setUrl('')
|
||||
setNote('')
|
||||
}
|
||||
} else {
|
||||
setResult({ tone: 'error', key: ERROR_KEY[data.error ?? ''] ?? 'suggest.error.generic' })
|
||||
}
|
||||
} catch {
|
||||
setResult({ tone: 'error', key: 'suggest.error.generic' })
|
||||
} finally {
|
||||
setSending(false)
|
||||
setToken('')
|
||||
if (widgetId.current) window.turnstile?.reset(widgetId.current)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto max-w-xl space-y-4 p-6">
|
||||
<h1 className="text-2xl font-semibold">{t('titles.suggest')}</h1>
|
||||
<p className="text-muted-foreground">{t('suggest.intro')}</p>
|
||||
|
||||
{config.data && !config.data.enabled ? (
|
||||
<p className="rounded-md border p-3 text-sm">{t('suggest.closed')}</p>
|
||||
) : (
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="suggest-url">{t('suggest.url')}</Label>
|
||||
<Input
|
||||
id="suggest-url"
|
||||
type="url"
|
||||
inputMode="url"
|
||||
required
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder="https://creator.itch.io/game"
|
||||
aria-invalid={url !== '' && !urlValid}
|
||||
aria-describedby="suggest-url-hint"
|
||||
/>
|
||||
<p id="suggest-url-hint" className="text-xs text-muted-foreground">
|
||||
{url !== '' && !urlValid ? t('suggest.error.invalidUrl') : t('suggest.urlHint')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="suggest-note">{t('suggest.note')}</Label>
|
||||
<textarea
|
||||
id="suggest-note"
|
||||
value={note}
|
||||
maxLength={MAX_NOTE}
|
||||
rows={3}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
aria-describedby="suggest-note-hint"
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
/>
|
||||
<p id="suggest-note-hint" className="text-xs text-muted-foreground">
|
||||
{t('suggest.notePrivacy')} ({note.length}/{MAX_NOTE})
|
||||
</p>
|
||||
</div>
|
||||
<div ref={widget} aria-label={t('suggest.challenge')} className="min-h-[65px]" />
|
||||
<Button type="submit" disabled={!urlValid || !token || sending}>
|
||||
{sending ? t('suggest.sending') : t('suggest.submit')}
|
||||
</Button>
|
||||
{result && (
|
||||
<p role={result.tone === 'error' ? 'alert' : 'status'} className={result.tone === 'error' ? 'text-sm text-destructive' : 'text-sm'}>
|
||||
{t(result.key)}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import animate from 'tailwindcss-animate'
|
||||
|
||||
export default {
|
||||
darkMode: 'class',
|
||||
content: ['./index.html', './src/**/*.{ts,tsx}'],
|
||||
content: ['./index.html', './src/**/*.{ts,tsx}', './admin/**/*.{html,ts,tsx}'],
|
||||
theme: {
|
||||
container: {
|
||||
center: true,
|
||||
|
||||
@@ -25,5 +25,5 @@
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
"include": ["src", "admin"]
|
||||
}
|
||||
@@ -24,6 +24,14 @@ export default defineConfig({
|
||||
target: isTauri ? 'baseline-widely-available' : ['chrome111', 'edge111', 'firefox114', 'safari15.4', 'ios15.4'],
|
||||
chunkSizeWarningLimit: 600,
|
||||
rolldownOptions: {
|
||||
// Web: the public app + the maintainer-only admin (/admin/, served by
|
||||
// the Worker after the Access check). The Tauri apps ship the public app only.
|
||||
input: isTauri
|
||||
? undefined
|
||||
: {
|
||||
main: path.resolve(import.meta.dirname, 'index.html'),
|
||||
admin: path.resolve(import.meta.dirname, 'admin/index.html'),
|
||||
},
|
||||
output: {
|
||||
codeSplitting: {
|
||||
// Higher priority wins when a module matches several groups. Groups
|
||||
|
||||
@@ -71,7 +71,12 @@ function githubRepo(env: WorkerEnv): RepoOps | null {
|
||||
}
|
||||
}
|
||||
|
||||
const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
|
||||
|
||||
async function maintainer(request: Request, env: WorkerEnv): Promise<string> {
|
||||
// `wrangler dev` only: Access does not run on localhost. Set DEV_ADMIN_EMAIL
|
||||
// in .dev.vars; it is ignored for every other host.
|
||||
if (env.DEV_ADMIN_EMAIL && LOCAL_HOSTS.has(new URL(request.url).hostname)) return env.DEV_ADMIN_EMAIL
|
||||
const missing = missingConfig(env, [...ACCESS_CONFIG, 'ACCESS_AUD_ADMIN', 'ADMIN_EMAILS'])
|
||||
if (missing.length > 0) {
|
||||
console.error(`admin: not configured (${missing.join(', ')})`)
|
||||
|
||||
@@ -9,6 +9,8 @@ interface Secrets {
|
||||
GH_APP_PRIVATE_KEY?: string // PKCS#8 PEM of the GitHub App
|
||||
ADMIN_EMAILS?: string // comma-separated maintainer emails
|
||||
TURNSTILE_SECRET?: string
|
||||
/** Local `wrangler dev` only (admin without Access); ignored off localhost. */
|
||||
DEV_ADMIN_EMAIL?: string
|
||||
}
|
||||
|
||||
export type WorkerEnv = Env & Secrets
|
||||
|
||||
@@ -80,3 +80,19 @@ describe('admin authentication', () => {
|
||||
expect((await get('/admin/secrets.json', await jwt('owner@example.com'))).status).toBe(404)
|
||||
})
|
||||
})
|
||||
|
||||
describe('local development bypass', () => {
|
||||
const dev = { ...env, DEV_ADMIN_EMAIL: 'dev@localhost', ACCESS_AUD_ADMIN: '' } as WorkerEnv
|
||||
|
||||
it('lets wrangler dev on localhost in without Access', async () => {
|
||||
const url = new URL('http://localhost:8787/admin/')
|
||||
const res = await serveAdminApp(new Request(url), url, dev)
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
it('is ignored on any other host', async () => {
|
||||
expect((await get('/admin/', undefined, dev)).status).toBe(503)
|
||||
const withAccess = { ...env, DEV_ADMIN_EMAIL: 'dev@localhost' } as WorkerEnv
|
||||
expect((await get('/admin/', undefined, withAccess)).status).toBe(403)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user