chore(quality): resolve SonarQube code smells across website
All checks were successful
PR Checks / bot-install (pull_request) Successful in 13s
PR Checks / client-build (pull_request) Successful in 22s
PR Checks / server-tests (pull_request) Successful in 11m13s

Clears the 124 CODE_SMELL findings from the SonarQube scan (server, client,
and bot). All changes are behaviour-preserving refactors — no route, protocol,
schema, or config changes — verified against the full server (381) and client
(43) test suites plus a clean client build.

By rule:
- S3776 (20, cognitive complexity): extract helpers/handlers so each function
  drops under the threshold — shard model upsert builders, page/wiki update,
  block validation, notification stream mapping (dispatch table), SSO mobile
  login, shard ingest deps, uo-link socket backfill/connect, the bot slash-
  command dispatchers + discord manager, and the Shard/UserDetail/HeroEditor/
  CharacterStats React components.
- S4624 (34, nested template literals): pull inner templates into locals /
  a withQs() helper; rewrite shardEvents.describe() as a formatter table.
- S3358 (35, nested ternaries): lift to if/else vars, lookup maps, small
  components, or guarded JSX expressions.
- S6479 (12, array-index React keys): key by stable content instead of index
  (two in-editor lists left as-is; index matches their by-index edit model).
- S6353 (6): [0-9]/[^0-9] -> \d/\D.  S125 (5): reword state-shape comments that
  parsed as code.  S3800/S3782 (botScore): JSDoc-type PATH_WEIGHTS tuples.
- S6481 (2): memoize Auth/Site context values (and SiteContext brand).
- S4144: dedupe HeroEditor upload handler into useImageUpload().
- S1126 (2), S6035, S5869 (redundant A-Z under /i), S5843 (town-name regex ->
  prefix list): assorted one-liners.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-07-21 04:35:39 -05:00
parent 4993470fa2
commit 12d50fd615
59 changed files with 1088 additions and 848 deletions

View File

@@ -4,6 +4,46 @@ const guildConfig = require('../../model/guildConfig')
const inviteLog = require('../../model/inviteLog')
const inviteRotator = require('../../invites/inviteRotator')
// Per-subcommand handlers, split out of execute() so the dispatch stays flat.
async function handleChannel(interaction) {
const channel = interaction.options.getChannel('channel')
if (!channel) {
const currentId = await guildConfig.getInviteChannelId(interaction.guildId)
const content = currentId ? `Invites are created in <#${currentId}>.` : 'No invite channel is set yet.'
await interaction.reply({ content, ephemeral: true })
return
}
await guildConfig.setInviteChannelId(interaction.guildId, channel.id)
await interaction.reply({ content: `Invite channel set to ${channel}.`, ephemeral: true })
}
async function handleRotate(interaction) {
await interaction.deferReply({ ephemeral: true })
try {
const invite = await inviteRotator.rotate(interaction.client, interaction.guildId, {
triggeredBy: interaction.user.id,
triggeredByTag: interaction.user.tag,
})
await interaction.editReply({ content: `New invite: https://discord.gg/${invite.code}` })
} catch (err) {
await interaction.editReply({ content: `Couldn't rotate the invite: ${err.message}` })
}
}
async function handleLog(interaction) {
const rows = await inviteLog.list(interaction.guildId, 10)
if (rows.length === 0) {
await interaction.reply({ content: 'No invite rotations logged yet.', ephemeral: true })
return
}
const lines = rows.map((r) => {
const who = r.triggered_by_tag || 'automatic (scheduled)'
const status = r.revoked_at ? `revoked ${new Date(r.revoked_at).toLocaleString()}` : 'active'
return `\`${r.invite_code}\` — by ${who} on ${new Date(r.created_at).toLocaleString()} (${status})`
})
await interaction.reply({ content: lines.join('\n'), ephemeral: true })
}
module.exports = {
data: {
name: 'invite',
@@ -40,46 +80,8 @@ module.exports = {
},
async execute(interaction) {
const sub = interaction.options.getSubcommand()
if (sub === 'channel') {
const channel = interaction.options.getChannel('channel')
if (!channel) {
const currentId = await guildConfig.getInviteChannelId(interaction.guildId)
const content = currentId ? `Invites are created in <#${currentId}>.` : 'No invite channel is set yet.'
await interaction.reply({ content, ephemeral: true })
return
}
await guildConfig.setInviteChannelId(interaction.guildId, channel.id)
await interaction.reply({ content: `Invite channel set to ${channel}.`, ephemeral: true })
return
}
if (sub === 'rotate') {
await interaction.deferReply({ ephemeral: true })
try {
const invite = await inviteRotator.rotate(interaction.client, interaction.guildId, {
triggeredBy: interaction.user.id,
triggeredByTag: interaction.user.tag,
})
await interaction.editReply({ content: `New invite: https://discord.gg/${invite.code}` })
} catch (err) {
await interaction.editReply({ content: `Couldn't rotate the invite: ${err.message}` })
}
return
}
if (sub === 'log') {
const rows = await inviteLog.list(interaction.guildId, 10)
if (rows.length === 0) {
await interaction.reply({ content: 'No invite rotations logged yet.', ephemeral: true })
return
}
const lines = rows.map((r) => {
const who = r.triggered_by_tag || 'automatic (scheduled)'
const status = r.revoked_at ? `revoked ${new Date(r.revoked_at).toLocaleString()}` : 'active'
return `\`${r.invite_code}\` — by ${who} on ${new Date(r.created_at).toLocaleString()} (${status})`
})
await interaction.reply({ content: lines.join('\n'), ephemeral: true })
}
if (sub === 'channel') return handleChannel(interaction)
if (sub === 'rotate') return handleRotate(interaction)
if (sub === 'log') return handleLog(interaction)
},
}

View File

@@ -5,6 +5,72 @@ const scheduledMessages = require('../../model/scheduledMessages')
const scheduler = require('../../scheduler/scheduler')
const { parseDuration } = require('../../utils/duration')
// Per-subcommand handlers, split out of execute() so the dispatch stays flat.
async function handleRecurring(interaction) {
const channel = interaction.options.getChannel('channel', true)
const cronExpr = interaction.options.getString('cron', true)
const message = interaction.options.getString('message', true)
if (!cron.validate(cronExpr)) {
await interaction.reply({ content: `"${cronExpr}" isn't a valid cron expression.`, ephemeral: true })
return
}
const id = await scheduledMessages.addRecurring({
guildId: interaction.guildId,
channelId: channel.id,
content: message,
cronExpression: cronExpr,
createdBy: interaction.user.id,
createdByTag: interaction.user.tag,
})
await scheduler.refresh()
await interaction.reply({ content: `Scheduled recurring message #${id} in ${channel} on \`${cronExpr}\`.`, ephemeral: true })
}
async function handleOnce(interaction) {
const channel = interaction.options.getChannel('channel', true)
const inInput = interaction.options.getString('in', true)
const message = interaction.options.getString('message', true)
const ms = parseDuration(inInput)
if (!ms) {
await interaction.reply({ content: 'Invalid time — use a number plus s/m/h/d, e.g. `30m`, `2h`, `1d`.', ephemeral: true })
return
}
const runAt = new Date(Date.now() + ms)
const id = await scheduledMessages.addOnce({
guildId: interaction.guildId,
channelId: channel.id,
content: message,
runAt,
createdBy: interaction.user.id,
createdByTag: interaction.user.tag,
})
await interaction.reply({ content: `Scheduled one-off message #${id} in ${channel} for ${runAt.toLocaleString()}.`, ephemeral: true })
}
async function handleRemove(interaction) {
const id = interaction.options.getInteger('id', true)
const removed = await scheduledMessages.remove(interaction.guildId, id)
await scheduler.refresh()
await interaction.reply({ content: removed ? `Removed scheduled message #${id}.` : `No scheduled message #${id} found.`, ephemeral: true })
}
async function handleList(interaction) {
const rows = await scheduledMessages.list(interaction.guildId)
if (rows.length === 0) {
await interaction.reply({ content: 'No scheduled messages.', ephemeral: true })
return
}
const lines = rows.map((r) => {
let kind
if (r.cron_expression) kind = `cron \`${r.cron_expression}\``
else if (r.sent_at) kind = `sent ${new Date(r.sent_at).toLocaleString()}`
else kind = `due ${new Date(r.run_at).toLocaleString()}`
const suffix = r.enabled ? '' : ' (disabled)'
return `**#${r.id}** <#${r.channel_id}> — ${kind}${suffix}`
})
await interaction.reply({ content: lines.join('\n'), ephemeral: true })
}
module.exports = {
data: {
name: 'schedule',
@@ -47,73 +113,9 @@ module.exports = {
},
async execute(interaction) {
const sub = interaction.options.getSubcommand()
if (sub === 'recurring') {
const channel = interaction.options.getChannel('channel', true)
const cronExpr = interaction.options.getString('cron', true)
const message = interaction.options.getString('message', true)
if (!cron.validate(cronExpr)) {
await interaction.reply({ content: `"${cronExpr}" isn't a valid cron expression.`, ephemeral: true })
return
}
const id = await scheduledMessages.addRecurring({
guildId: interaction.guildId,
channelId: channel.id,
content: message,
cronExpression: cronExpr,
createdBy: interaction.user.id,
createdByTag: interaction.user.tag,
})
await scheduler.refresh()
await interaction.reply({ content: `Scheduled recurring message #${id} in ${channel} on \`${cronExpr}\`.`, ephemeral: true })
return
}
if (sub === 'once') {
const channel = interaction.options.getChannel('channel', true)
const inInput = interaction.options.getString('in', true)
const message = interaction.options.getString('message', true)
const ms = parseDuration(inInput)
if (!ms) {
await interaction.reply({ content: 'Invalid time — use a number plus s/m/h/d, e.g. `30m`, `2h`, `1d`.', ephemeral: true })
return
}
const runAt = new Date(Date.now() + ms)
const id = await scheduledMessages.addOnce({
guildId: interaction.guildId,
channelId: channel.id,
content: message,
runAt,
createdBy: interaction.user.id,
createdByTag: interaction.user.tag,
})
await interaction.reply({ content: `Scheduled one-off message #${id} in ${channel} for ${runAt.toLocaleString()}.`, ephemeral: true })
return
}
if (sub === 'remove') {
const id = interaction.options.getInteger('id', true)
const removed = await scheduledMessages.remove(interaction.guildId, id)
await scheduler.refresh()
await interaction.reply({ content: removed ? `Removed scheduled message #${id}.` : `No scheduled message #${id} found.`, ephemeral: true })
return
}
if (sub === 'list') {
const rows = await scheduledMessages.list(interaction.guildId)
if (rows.length === 0) {
await interaction.reply({ content: 'No scheduled messages.', ephemeral: true })
return
}
const lines = rows.map((r) => {
const kind = r.cron_expression
? `cron \`${r.cron_expression}\``
: r.sent_at
? `sent ${new Date(r.sent_at).toLocaleString()}`
: `due ${new Date(r.run_at).toLocaleString()}`
return `**#${r.id}** <#${r.channel_id}> — ${kind}${r.enabled ? '' : ' (disabled)'}`
})
await interaction.reply({ content: lines.join('\n'), ephemeral: true })
}
if (sub === 'recurring') return handleRecurring(interaction)
if (sub === 'once') return handleOnce(interaction)
if (sub === 'remove') return handleRemove(interaction)
if (sub === 'list') return handleList(interaction)
},
}

View File

@@ -50,6 +50,42 @@ async function stop() {
log.info('discord client disconnected')
}
// Post-login startup: register commands and start the background workers. A
// failure here leaves the client connected but flags an error status.
async function onReady() {
try {
await registerCommands(client.application.id, guildId)
await scheduler.start(client)
tempRoleSweeper.start(client)
inviteScheduler.start(client, guildId)
await inviteTracker.prime(client, guildId)
status = 'connected'
statusDetail = null
lastConnectedAt = new Date()
log.info('discord client ready', { user: client.user?.tag, guildId })
} catch (err) {
status = 'error'
statusDetail = `startup failed: ${err.message}`
log.error('post-login startup failed (commands/scheduler/temp-roles/invites)', { message: err.message })
}
}
// Route an interaction: role-menu handler first, then chat-input slash commands.
async function onInteractionCreate(interaction) {
if (await roleMenuHandler.handleInteraction(interaction)) return
if (!interaction.isChatInputCommand()) return
const command = commands.get(interaction.commandName)
if (!command) return
try {
await command.execute(interaction)
} catch (err) {
log.error('command execution failed', { command: interaction.commandName, message: err.message })
const payload = { content: 'Something went wrong running that command.', ephemeral: true }
if (interaction.replied || interaction.deferred) await interaction.followUp(payload)
else await interaction.reply(payload)
}
}
// start({ token, guildId }) — (re)connects. Always stops any existing client
// first so re-saving config or toggling Enabled off/on is idempotent.
async function start({ token, guildId: gid }) {
@@ -72,39 +108,8 @@ async function start({ token, guildId: gid }) {
],
})
client.once('ready', async () => {
try {
await registerCommands(client.application.id, guildId)
await scheduler.start(client)
tempRoleSweeper.start(client)
inviteScheduler.start(client, guildId)
await inviteTracker.prime(client, guildId)
status = 'connected'
statusDetail = null
lastConnectedAt = new Date()
log.info('discord client ready', { user: client.user?.tag, guildId })
} catch (err) {
status = 'error'
statusDetail = `startup failed: ${err.message}`
log.error('post-login startup failed (commands/scheduler/temp-roles/invites)', { message: err.message })
}
})
client.on('interactionCreate', async (interaction) => {
if (await roleMenuHandler.handleInteraction(interaction)) return
if (!interaction.isChatInputCommand()) return
const command = commands.get(interaction.commandName)
if (!command) return
try {
await command.execute(interaction)
} catch (err) {
log.error('command execution failed', { command: interaction.commandName, message: err.message })
const payload = { content: 'Something went wrong running that command.', ephemeral: true }
if (interaction.replied || interaction.deferred) await interaction.followUp(payload)
else await interaction.reply(payload)
}
})
client.once('ready', onReady)
client.on('interactionCreate', onInteractionCreate)
client.on('messageCreate', messageFilter.handleMessageCreate)
client.on('guildMemberAdd', handleGuildMemberAdd)
client.on('guildMemberRemove', handleGuildMemberRemove)

View File

@@ -66,8 +66,7 @@ function detectSpam(message) {
async function isBypassed(message, cache) {
if (cache.allowChannels.has(message.channelId)) return true
const memberRoles = message.member ? message.member.roles.cache : null
if (memberRoles && [...memberRoles.keys()].some((id) => cache.allowRoles.has(id))) return true
return false
return Boolean(memberRoles && [...memberRoles.keys()].some((id) => cache.allowRoles.has(id)))
}
async function applyWarnAction(message, reason) {

View File

@@ -2,7 +2,7 @@
// current guild (anti-raid/anti-advertising). An invite that fails to resolve
// (expired/invalid/vanity-only) is treated as foreign too — safer default
// than silently letting an unresolvable link through.
const INVITE_REGEX = /(?:discord\.gg|discord(?:app)?\.com\/invite)\/([a-zA-Z0-9-]+)/gi
const INVITE_REGEX = /(?:discord\.gg|discord(?:app)?\.com\/invite)\/([a-z0-9-]+)/gi
// Returns the first foreign (or unresolvable) invite code found in the message,
// or null if the message contains no foreign invites. Returning the code (rather

View File

@@ -7,7 +7,7 @@ const MAX_TIMEOUT_MS = 28 * 86_400_000
function parseDuration(input) {
if (!input) return null
const match = /^(\d+)\s*(s|m|h|d)$/i.exec(input.trim())
const match = /^(\d+)\s*([smhd])$/i.exec(input.trim())
if (!match) return null
const [, amount, unit] = match
return Number(amount) * UNIT_MS[unit.toLowerCase()]

View File

@@ -2,6 +2,10 @@
// same-origin API (/api/v1) — proxied to the Express server in dev.
const BASE = '/api/v1'
// Prefix a non-empty query string with "?" (and nothing when it is empty), so
// callers can append it to a path without a dangling "?".
const withQs = (s) => (s ? `?${s}` : '')
class ApiError extends Error {
constructor(status, message, body) {
super(message)
@@ -84,7 +88,7 @@ export const api = {
if (opts.tag) qs.set('tag', opts.tag)
if (opts.q) qs.set('q', opts.q)
const s = qs.toString()
return req(`/public/wiki${s ? `?${s}` : ''}`)
return req(`/public/wiki${withQs(s)}`)
},
wikiCategories: () => req('/public/wiki/categories'),
wikiTags: () => req('/public/wiki/tags'),
@@ -105,17 +109,22 @@ export const api = {
if (opts.kind) qs.set('kind', opts.kind)
if (opts.limit) qs.set('limit', opts.limit)
const s = qs.toString()
return req(`/public/shard/feed${s ? `?${s}` : ''}`)
return req(`/public/shard/feed${withQs(s)}`)
},
economy: (limit) => {
const q = limit ? `limit=${limit}` : ''
return req(`/public/shard/economy${withQs(q)}`)
},
economy: (limit) => req(`/public/shard/economy${limit ? `?limit=${limit}` : ''}`),
online: () => req('/public/shard/online'),
idoc: () => req('/public/shard/idoc'),
champs: () => req('/public/shard/champs'),
// Protocol 2.0 boards.
guilds: () => req('/public/shard/guilds'),
governors: () => req('/public/shard/governors'),
governorHistory: (city, limit) =>
req(`/public/shard/governors/${encodeURIComponent(city)}/history${limit ? `?limit=${limit}` : ''}`),
governorHistory: (city, limit) => {
const q = limit ? `limit=${limit}` : ''
return req(`/public/shard/governors/${encodeURIComponent(city)}/history${withQs(q)}`)
},
presence: () => req('/public/shard/presence'),
houses: () => req('/public/shard/houses'),
},
@@ -129,7 +138,10 @@ export const api = {
admin: {
dashboard: () => req('/admin/dashboard'),
setSiteMode: (mode) => req('/admin/site-mode', { method: 'PUT', body: { mode } }),
listPosts: (category) => req(`/admin/posts${category ? `?category=${category}` : ''}`),
listPosts: (category) => {
const q = category ? `category=${category}` : ''
return req(`/admin/posts${withQs(q)}`)
},
getPost: (id) => req(`/admin/posts/${id}`),
createPost: (data) => req('/admin/posts', { method: 'POST', body: data }),
updatePost: (id, data) => req(`/admin/posts/${id}`, { method: 'PUT', body: data }),
@@ -216,7 +228,7 @@ export const api = {
if (params.limit) qs.set('limit', params.limit)
if (params.offset) qs.set('offset', params.offset)
const s = qs.toString()
return req(`/admin/moderation/recent${s ? `?${s}` : ''}`)
return req(`/admin/moderation/recent${withQs(s)}`)
},
modSearch: (q) => req(`/admin/moderation/search?q=${encodeURIComponent(q)}`),
modMembers: (params = {}) => {
@@ -225,21 +237,21 @@ export const api = {
if (params.limit) qs.set('limit', params.limit)
if (params.offset) qs.set('offset', params.offset)
const s = qs.toString()
return req(`/admin/moderation/members${s ? `?${s}` : ''}`)
return req(`/admin/moderation/members${withQs(s)}`)
},
modFilterHits: (params = {}) => {
const qs = new URLSearchParams()
if (params.limit) qs.set('limit', params.limit)
if (params.offset) qs.set('offset', params.offset)
const s = qs.toString()
return req(`/admin/moderation/filter-hits${s ? `?${s}` : ''}`)
return req(`/admin/moderation/filter-hits${withQs(s)}`)
},
modSpamHits: (params = {}) => {
const qs = new URLSearchParams()
if (params.limit) qs.set('limit', params.limit)
if (params.offset) qs.set('offset', params.offset)
const s = qs.toString()
return req(`/admin/moderation/spam-hits${s ? `?${s}` : ''}`)
return req(`/admin/moderation/spam-hits${withQs(s)}`)
},
modUser: (discordId) => req(`/admin/moderation/user/${discordId}`),
modUserActions: (discordId, params = {}) => {
@@ -248,7 +260,7 @@ export const api = {
if (params.limit) qs.set('limit', params.limit)
if (params.offset) qs.set('offset', params.offset)
const s = qs.toString()
return req(`/admin/moderation/user/${discordId}/actions${s ? `?${s}` : ''}`)
return req(`/admin/moderation/user/${discordId}/actions${withQs(s)}`)
},
modUserNotes: (discordId) => req(`/admin/moderation/user/${discordId}/notes`),
addModNote: (discordId, data) =>
@@ -261,7 +273,7 @@ export const api = {
if (params.limit) qs.set('limit', params.limit)
if (params.offset) qs.set('offset', params.offset)
const s = qs.toString()
return req(`/admin/moderation/appeals${s ? `?${s}` : ''}`)
return req(`/admin/moderation/appeals${withQs(s)}`)
},
getAppeal: (id) => req(`/admin/moderation/appeals/${id}`),
claimAppeal: (id) => req(`/admin/moderation/appeals/${id}/claim`, { method: 'POST' }),

View File

@@ -20,6 +20,25 @@ function Tile({ value, label }) {
)
}
// Fold the settled roster results into totals. `complete` is false when any
// account's roster failed (a partial result — shown as a dash rather than a
// misleadingly low count).
function summarizeRosters(rosters) {
let chars = 0
let online = 0
let complete = true
for (const r of rosters) {
if (r.status !== 'fulfilled') {
complete = false
continue
}
const cs = r.value.chars || []
chars += cs.length
online += cs.filter((c) => c.online).length
}
return { chars, online, complete }
}
export default function CharacterStats({ scope }) {
const [stats, setStats] = useState(null)
@@ -36,19 +55,7 @@ export default function CharacterStats({ scope }) {
// Roster is a live round-trip and can be unavailable (503); tolerate a
// partial result so a restarting shard doesn't blank the whole row.
const rosters = await Promise.allSettled(accounts.map((a) => scope.roster(a.account)))
let chars = 0
let online = 0
let complete = true
for (const r of rosters) {
if (r.status === 'fulfilled') {
const cs = r.value.chars || []
chars += cs.length
online += cs.filter((c) => c.online).length
} else {
complete = false
}
}
if (!cancelled) setStats({ linked, chars, online, complete })
if (!cancelled) setStats({ linked, ...summarizeRosters(rosters) })
} catch {
if (!cancelled) setStats({ error: true })
}

View File

@@ -121,7 +121,8 @@ function UnlinkButton({ account, onUnlink }) {
try {
await onUnlink(account)
} catch (err) {
setError(err.status === 403 ? 'Protected account — refused.' : err.status === 404 ? 'Not linked.' : (err.message || 'Could not unlink.'))
const byStatus = { 403: 'Protected account — refused.', 404: 'Not linked.' }
setError(byStatus[err.status] || err.message || 'Could not unlink.')
setBusy(false)
}
}

View File

@@ -34,14 +34,15 @@ function TextBlock({ props }) {
const align = props.align || 'center'
return (
<div style={{ textAlign: align, textShadow: '0 2px 22px rgba(0,0,0,0.82)' }}>
{(props.lines || []).map((line, i) => {
{(props.lines || []).map((line) => {
const Tag = /^(h1|h2|h3|p|span|div)$/.test(line.tag) ? line.tag : 'p'
const key = `${line.tag}:${(line.text || '').slice(0, 40)}`
// A rich-text line (e.g. the homepage teaser) carries sanitized HTML;
// sanitize again on render as defense in depth. Others render as text.
if (line.html) {
return (
<Tag
key={i}
key={key}
className="hero-rich"
style={lineStyle(line)}
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(line.text || '') }}
@@ -49,7 +50,7 @@ function TextBlock({ props }) {
)
}
return (
<Tag key={i} style={lineStyle(line)}>
<Tag key={key} style={lineStyle(line)}>
{line.text}
</Tag>
)
@@ -59,11 +60,11 @@ function TextBlock({ props }) {
}
function Buttons({ props }) {
const justify = props.align === 'left' ? 'flex-start' : props.align === 'right' ? 'flex-end' : 'center'
const justify = { left: 'flex-start', right: 'flex-end' }[props.align] || 'center'
return (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: props.gap ?? 12, justifyContent: justify }}>
{(props.items || []).map((b, i) => (
<Link key={i} to={b.to || '#'} className={`btn ${b.variant === 'ghost' ? 'btn-ghost' : 'btn-primary'}`}>
{(props.items || []).map((b) => (
<Link key={`${b.to || ''}:${b.label || ''}`} to={b.to || '#'} className={`btn ${b.variant === 'ghost' ? 'btn-ghost' : 'btn-primary'}`}>
{b.label}
</Link>
))}
@@ -160,12 +161,7 @@ export default function HeroElement({
children,
}) {
const anchor = element.anchor || 'center'
const transform =
anchor === 'center'
? 'translate(-50%, -50%)'
: anchor === 'top-right'
? 'translateX(-100%)'
: undefined
const transform = { center: 'translate(-50%, -50%)', 'top-right': 'translateX(-100%)' }[anchor]
// text_block/buttons may set a box width (px); kept within the containing block
// (the hero section live, or the editor canvas) with small side gutters.
const boxWidth =

View File

@@ -36,7 +36,7 @@ function AlignIcon({ align }) {
return (
<svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" aria-hidden="true">
{rows.map(([x1, x2], i) => (
<line key={i} x1={x1} y1={4 + i * 4} x2={x2} y2={4 + i * 4} />
<line key={`${x1}-${x2}`} x1={x1} y1={4 + i * 4} x2={x2} y2={4 + i * 4} />
))}
</svg>
)

View File

@@ -36,9 +36,12 @@ export default function ShardAccountActions({ account, style }) {
}
const kick = () =>
run('kick', () => api.admin.shardOps.kick({ account }), (r) =>
`Kicked${r && r.sessions != null ? ` (${r.sessions} session${r.sessions === 1 ? '' : 's'})` : ''}.`,
)
run('kick', () => api.admin.shardOps.kick({ account }), (r) => {
const n = r && r.sessions != null ? r.sessions : null
const plural = n === 1 ? '' : 's'
const sessions = n != null ? ` (${n} session${plural})` : ''
return `Kicked${sessions}.`
})
const unban = () => run('unban', () => api.admin.shardOps.unban(account), () => 'Unbanned.')
const ban = () =>
run('ban', () =>
@@ -49,7 +52,8 @@ export default function ShardAccountActions({ account, style }) {
}),
() => {
setBanOpen(false)
return `Banned${durationSec ? ` for ${durationSec}s` : ' indefinitely'}.`
const when = durationSec ? ` for ${durationSec}s` : ' indefinitely'
return `Banned${when}.`
})
const btn = { fontSize: '0.72rem', padding: '4px 10px' }

View File

@@ -31,12 +31,10 @@ export default function SiteHeader() {
const { siteTitle } = useSite()
// Where the auth entry points: staff → admin, player → portal, else sign in.
const account =
user && user.role && user.role !== 'player'
? { label: 'Admin', to: '/admin' }
: user
? { label: 'My Account', to: '/player' }
: { label: 'Sign in', to: '/account/login' }
let account
if (user && user.role && user.role !== 'player') account = { label: 'Admin', to: '/admin' }
else if (user) account = { label: 'My Account', to: '/player' }
else account = { label: 'Sign in', to: '/account/login' }
return (
<header

View File

@@ -26,8 +26,8 @@ export default function VendorSales({ fetchSales }) {
<p className="sans dim" style={{ margin: 0, fontSize: '0.86rem' }}>No vendor sales recorded yet.</p>
) : (
<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
{sales.map((s, i) => (
<li key={`${s.t}-${i}`} className="sans" style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: '0.9rem', color: 'var(--ink)' }}>
{sales.map((s) => (
<li key={`${s.t}-${s.itemType}-${s.price}`} className="sans" style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: '0.9rem', color: 'var(--ink)' }}>
<span style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{s.itemType || 'An item'}{s.amount > 1 ? ` ×${s.amount}` : ''} {Number(s.price || 0).toLocaleString()}gp
</span>

View File

@@ -1,4 +1,4 @@
import { createContext, useContext, useEffect, useState, useCallback } from 'react'
import { createContext, useContext, useEffect, useState, useCallback, useMemo } from 'react'
import { api } from '../api/client.js'
const AuthContext = createContext(null)
@@ -61,8 +61,15 @@ export function AuthProvider({ children }) {
}
}, [])
// Memoized so consumers don't re-render on every provider render (the callbacks
// are already stable via useCallback).
const value = useMemo(
() => ({ user, loading, login, register, loginTotp, ssoLoginTotp, logout, refresh }),
[user, loading, login, register, loginTotp, ssoLoginTotp, logout, refresh],
)
return (
<AuthContext.Provider value={{ user, loading, login, register, loginTotp, ssoLoginTotp, logout, refresh }}>
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
)

View File

@@ -1,4 +1,4 @@
import { createContext, useContext, useEffect, useState, useCallback } from 'react'
import { createContext, useContext, useEffect, useState, useCallback, useMemo } from 'react'
import { api } from '../api/client.js'
const SiteContext = createContext(null)
@@ -23,7 +23,7 @@ export function SiteProvider({ children }) {
refresh()
}, [refresh])
const brand = settings.brand || {}
const brand = useMemo(() => settings.brand || {}, [settings])
// Apply the instance accent color to the CSS variable the theme is built on,
// so branding flows to every `var(--accent)` at runtime (no rebuild).
@@ -31,17 +31,22 @@ export function SiteProvider({ children }) {
if (brand.accent) document.documentElement.style.setProperty('--accent', brand.accent)
}, [brand.accent])
const value = {
settings,
loading,
refresh,
brand,
mode: settings.site_mode || 'live',
siteTitle: brand.name || settings.site_title || 'Runic Gateway',
siteShortName: brand.shortName || brand.name || settings.site_title || 'Runic Gateway',
contactEmail: brand.contactEmail || settings.contact_email || '',
heroImage: brand.hero || '/assets/img/runic-emblem.png',
}
// Memoized so consumers don't re-render on every provider render (brand is a
// fresh object each render, which would otherwise churn the context value).
const value = useMemo(
() => ({
settings,
loading,
refresh,
brand,
mode: settings.site_mode || 'live',
siteTitle: brand.name || settings.site_title || 'Runic Gateway',
siteShortName: brand.shortName || brand.name || settings.site_title || 'Runic Gateway',
contactEmail: brand.contactEmail || settings.contact_email || '',
heroImage: brand.hero || '/assets/img/runic-emblem.png',
}),
[settings, loading, refresh, brand],
)
return <SiteContext.Provider value={value}>{children}</SiteContext.Provider>
}

View File

@@ -4,6 +4,16 @@
// membership) and the widget follows. Anything not matched lands in "Wilderness"
// so the bucket counts always reconcile to the true total.
// Named cities/towns, matched as a prefix on the (space/apostrophe-stripped)
// region name so "skara brae", "serpent's hold", etc. all resolve. Kept as a
// list rather than one giant alternation regex (simpler to read and retune).
const TOWN_PREFIXES = [
'moonglow', 'minoc', 'trinsic', 'jhelom', 'yew', 'skarabrae', 'magincia',
'newmagincia', 'vesper', 'nujelm', 'cove', 'ocllo', 'serpenthold', 'serpentshold',
'wind', 'delucia', 'papua',
]
const normalizeRegion = (r) => String(r).toLowerCase().replace(/['\s]/g, '')
// Ordered list of buckets. `label` shows in the widget; `match(region)` decides
// membership. First matching bucket wins; the last bucket is the catch-all.
export const BUCKETS = [
@@ -17,10 +27,10 @@ export const BUCKETS = [
id: 'towns',
label: 'Towns',
// The other named cities/towns.
match: (r) =>
/^(moonglow|minoc|trinsic|jhelom|yew|skara ?brae|magincia|new ?magincia|vesper|nujelm|cove|ocllo|serpent'?s? hold|wind|delucia|papua)/i.test(
r,
),
match: (r) => {
const norm = normalizeRegion(r)
return TOWN_PREFIXES.some((t) => norm.startsWith(t))
},
},
{
id: 'dungeons',

View File

@@ -10,73 +10,95 @@ function nameOf(who) {
const n = (v) => Number(v || 0).toLocaleString()
// A one-line human description of each event kind, keyed by kind. Each formatter
// takes the payload and returns a string. Conditional suffixes are pulled into
// locals so no template literal is nested inside another.
const DESCRIBERS = {
'vendor.sale': (p) => {
const qty = p.amount > 1 ? ` ×${p.amount}` : ''
return `${p.itemType || 'An item'}${qty} sold for ${n(p.price)}gp`
},
'player.death': (p) => {
const by = p.killer ? ` by ${nameOf(p.killer)}` : ''
return `${nameOf(p.who)} was slain${by}`
},
'player.murdered': (p) => {
const by = p.murderer ? ` by ${nameOf(p.murderer)}` : ''
return `${nameOf(p.victim)} was murdered${by}`
},
'mob.killed': (p) => `${nameOf(p.killer)} killed ${nameOf(p.killed)}`,
'skill.gain': (p) => {
const base = p.base != null ? ` (${p.base})` : ''
return `${nameOf(p.who)} gained ${p.skill}${base}`
},
'fame.change': (p) => `${nameOf(p.who)}s fame changed to ${n(p.new)}`,
'karma.change': (p) => `${nameOf(p.who)}s karma changed to ${n(p.new)}`,
'quest.complete': (p) => `${nameOf(p.who)} completed “${p.quest}`,
'house.decay': (p) => {
const region = p.region ? `${p.region}` : ''
return `${p.name || 'A house'} is now ${p.to || p.stage}${region}`
},
'mob.login': (p) => `${nameOf(p.who)} entered the world`,
'mob.logout': (p) => `${nameOf(p.who)} left the world`,
'economy.supply': (p) => `Gold supply: ${n(p.gold)} across ${n(p.accounts)} accounts`,
'server.hello': (p) => `Shard online — ${n(p.accounts)} accounts, ${n(p.mobiles)} mobiles`,
'server.shutdown': () => 'Shard shut down',
'server.crashed': (p) => {
const err = p.error ? `: ${p.error}` : ''
return `Shard crashed${err}`
},
'champ.update': (p) => {
const where = p.name || p.type || 'A champion spawn'
if (p.status === 'active' && p.bossUp) {
const boss = p.boss ? ` (${p.boss})` : ''
return `${where}: boss is up${boss}`
}
if (p.status === 'active') {
const level = p.level != null ? ` — level ${p.level}` : ''
return `${where} is active${level}`
}
if (p.status === 'cooldown') return `${where} is on cooldown`
return `${where} is ${p.status || 'idle'}`
},
'champ.remove': () => `A champion spawn ended`,
// Support (help-page) queue + in-game moderation (admin channel only)
'page.new': (p) => `New ${p.type || 'help'} page from ${nameOf(p.sender)}`,
'page.updated': (p) => {
const claimed = p.handled ? ' (claimed)' : ''
return `Help page from ${nameOf(p.sender)} updated${claimed}`
},
'page.closed': (p) => `Help page ${p.pageId || ''} closed`,
'admin.audit': (p) => {
const on = p.target ? ` on ${p.target}` : ''
const origin = p.origin ? ` [${p.origin}]` : ''
return `${p.actor || 'Staff'} ${p.action || 'acted'}${on}${origin}`
},
// Staff / sensitive (admin channel only)
'audit.set': (p) =>
`${nameOf(p.staff) || 'Staff'} set ${p.prop} on ${p.target || p.targetSerial} (${p.old}${p.new})`,
'audit.command': (p) => {
const args = p.args ? ` ${p.args}` : ''
return `${nameOf(p.staff) || 'Staff'} ran ${p.command}${args}`
},
'cheat.fastwalk': (p) => {
const ip = p.ip ? ` (${p.ip})` : ''
return `Fast-walk flagged: ${nameOf(p.who)}${ip}`
},
'account.login.attempt': (p) => {
const ip = p.ip ? ` from ${p.ip}` : ''
return `Login attempt: ${p.acct}${ip}`
},
'gold.change': (p) => {
const sign = p.delta >= 0 ? '+' : ''
return `${p.acct}: gold ${sign}${n(p.delta)}${n(p.new)}`
},
}
// A one-line human description of an event. Accepts either a stored event
// (with .payload) or a raw live frame (fields at top level).
export function describe(ev) {
const p = ev.payload || ev
switch (ev.kind) {
case 'vendor.sale':
return `${p.itemType || 'An item'}${p.amount > 1 ? ` ×${p.amount}` : ''} sold for ${n(p.price)}gp`
case 'player.death':
return `${nameOf(p.who)} was slain${p.killer ? ` by ${nameOf(p.killer)}` : ''}`
case 'player.murdered':
return `${nameOf(p.victim)} was murdered${p.murderer ? ` by ${nameOf(p.murderer)}` : ''}`
case 'mob.killed':
return `${nameOf(p.killer)} killed ${nameOf(p.killed)}`
case 'skill.gain':
return `${nameOf(p.who)} gained ${p.skill}${p.base != null ? ` (${p.base})` : ''}`
case 'fame.change':
return `${nameOf(p.who)}s fame changed to ${n(p.new)}`
case 'karma.change':
return `${nameOf(p.who)}s karma changed to ${n(p.new)}`
case 'quest.complete':
return `${nameOf(p.who)} completed “${p.quest}`
case 'house.decay':
return `${p.name || 'A house'} is now ${p.to || p.stage}${p.region ? `${p.region}` : ''}`
case 'mob.login':
return `${nameOf(p.who)} entered the world`
case 'mob.logout':
return `${nameOf(p.who)} left the world`
case 'economy.supply':
return `Gold supply: ${n(p.gold)} across ${n(p.accounts)} accounts`
case 'server.hello':
return `Shard online — ${n(p.accounts)} accounts, ${n(p.mobiles)} mobiles`
case 'server.shutdown':
return 'Shard shut down'
case 'server.crashed':
return `Shard crashed${p.error ? `: ${p.error}` : ''}`
case 'champ.update': {
const where = p.name || p.type || 'A champion spawn'
if (p.status === 'active' && p.bossUp) return `${where}: boss is up${p.boss ? ` (${p.boss})` : ''}`
if (p.status === 'active') return `${where} is active${p.level != null ? ` — level ${p.level}` : ''}`
if (p.status === 'cooldown') return `${where} is on cooldown`
return `${where} is ${p.status || 'idle'}`
}
case 'champ.remove':
return `A champion spawn ended`
// Support (help-page) queue + in-game moderation (admin channel only)
case 'page.new':
return `New ${p.type || 'help'} page from ${nameOf(p.sender)}`
case 'page.updated':
return `Help page from ${nameOf(p.sender)} updated${p.handled ? ' (claimed)' : ''}`
case 'page.closed':
return `Help page ${p.pageId || ''} closed`
case 'admin.audit':
return `${p.actor || 'Staff'} ${p.action || 'acted'}${p.target ? ` on ${p.target}` : ''}${p.origin ? ` [${p.origin}]` : ''}`
// Staff / sensitive (admin channel only)
case 'audit.set':
return `${nameOf(p.staff) || 'Staff'} set ${p.prop} on ${p.target || p.targetSerial} (${p.old}${p.new})`
case 'audit.command':
return `${nameOf(p.staff) || 'Staff'} ran ${p.command}${p.args ? ` ${p.args}` : ''}`
case 'cheat.fastwalk':
return `Fast-walk flagged: ${nameOf(p.who)}${p.ip ? ` (${p.ip})` : ''}`
case 'account.login.attempt':
return `Login attempt: ${p.acct}${p.ip ? ` from ${p.ip}` : ''}`
case 'gold.change':
return `${p.acct}: gold ${p.delta >= 0 ? '+' : ''}${n(p.delta)}${n(p.new)}`
default:
return ev.kind
}
const fmt = DESCRIBERS[ev.kind]
return fmt ? fmt(ev.payload || ev) : ev.kind
}
// Category grouping for the filter tabs.

View File

@@ -113,6 +113,14 @@ const TITLES = {
'/admin/account': 'Account Security',
}
// Fallback page title for dynamic sub-routes not in the exact-match TITLES map.
function sectionTitle(pathname) {
if (pathname.startsWith('/admin/moderation')) return 'Moderation'
if (pathname.startsWith('/admin/characters')) return 'My Characters'
if (pathname.startsWith('/admin/users/')) return 'User'
return 'Admin'
}
const navBtnBase = {
textAlign: 'left',
borderRadius: 8,
@@ -131,15 +139,7 @@ export default function AdminLayout() {
const { mode, siteTitle } = useSite()
const navigate = useNavigate()
const location = useLocation()
const title =
TITLES[location.pathname] ||
(location.pathname.startsWith('/admin/moderation')
? 'Moderation'
: location.pathname.startsWith('/admin/characters')
? 'My Characters'
: location.pathname.startsWith('/admin/users/')
? 'User'
: 'Admin')
const title = TITLES[location.pathname] || sectionTitle(location.pathname)
// The hero canvas editor needs room — let it use the full content width.
const wide = location.pathname === '/admin/hero'
const modeDot = mode === 'live' ? 'var(--mode-live)' : 'var(--mode-maint)'
@@ -236,7 +236,7 @@ export default function AdminLayout() {
</div>
<nav style={{ flex: 1, padding: '14px 12px', display: 'flex', flexDirection: 'column', gap: 4, overflowY: 'auto' }}>
{navGroups.map((group, gi) => {
{navGroups.map((group) => {
const links = group.items.map((n) => (
<NavLink
key={n.to}
@@ -258,7 +258,7 @@ export default function AdminLayout() {
// Untitled groups (Dashboard, Account) render their links directly.
if (!group.title) {
return (
<div key={`g${gi}`} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<div key={group.items[0]?.to || 'group'} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{links}
</div>
)

View File

@@ -140,6 +140,10 @@ export default function AdminLogin() {
}
}
let submitLabel = 'Sign in'
if (busy) submitLabel = 'Signing in…'
else if (stage === 'totp') submitLabel = 'Verify'
return (
<main
style={{
@@ -249,7 +253,7 @@ export default function AdminLogin() {
className="btn btn-primary"
style={{ display: 'block', width: '100%', borderRadius: 8, padding: 12, textAlign: 'center' }}
>
{busy ? 'Signing in…' : stage === 'totp' ? 'Verify' : 'Sign in'}
{submitLabel}
</button>
{/* SSO providers — only on the credentials step, only if any are enabled. */}

View File

@@ -123,7 +123,7 @@ export default function AccountAdmin() {
const [error, setError] = useState('')
// Enrollment state.
const [setup, setSetup] = useState(null) // { qr, otpauthUrl }
const [setup, setSetup] = useState(null) // fields qr and otpauthUrl once enrolling
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
const [msg, setMsg] = useState('')

View File

@@ -48,7 +48,7 @@ export default function Appeals() {
const reload = useCallback(() => setTick((t) => t + 1), [])
const [busyId, setBusyId] = useState('')
const [resolving, setResolving] = useState(null) // the appeal being resolved
const [notice, setNotice] = useState(null) // { text, tone }
const [notice, setNotice] = useState(null) // fields text and tone
const activeTab = STATUS_TABS.find((t) => t.key === tab) || STATUS_TABS[0]
const { loading, error, data } = useAsync(
@@ -210,6 +210,8 @@ function ResolveModal({ appeal, onClose, onResolved }) {
}
}
const verb = status === 'approved' ? 'approved' : 'denied'
return (
<Modal
title={`Resolve appeal — ${appeal.action_target_tag || appeal.discord_user_id}`}
@@ -221,7 +223,7 @@ function ResolveModal({ appeal, onClose, onResolved }) {
Cancel
</button>
<button onClick={submit} disabled={busy} className="btn btn-primary btn-sq">
{busy ? 'Saving…' : `Mark ${status === 'approved' ? 'approved' : 'denied'}`}
{busy ? 'Saving…' : `Mark ${verb}`}
</button>
</>
}

View File

@@ -44,6 +44,14 @@ function CallbackHint({ id }) {
)
}
// Live = enabled and healthy; Incomplete = enabled but missing/invalid config;
// Disabled otherwise.
function ProviderStatus({ provider: p }) {
if (p.enabled && p.health.valid) return <span className="sans" style={{ color: '#7fd0a4' }}>Live</span>
if (p.enabled) return <span className="sans" style={{ color: '#e0b070' }}>Incomplete</span>
return <span className="sans dim">Disabled</span>
}
function Toggle({ checked, onChange, label }) {
return (
<label className="sans" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: '0.9rem', color: 'var(--ink)' }}>
@@ -292,13 +300,7 @@ function CustomProviders({ items, onChanged }) {
<td className="adm-td" style={{ color: 'var(--head)' }}>{p.name}</td>
<td className="adm-td dim">{p.kind}</td>
<td className="adm-td">
{p.enabled && p.health.valid ? (
<span className="sans" style={{ color: '#7fd0a4' }}>Live</span>
) : p.enabled ? (
<span className="sans" style={{ color: '#e0b070' }}>Incomplete</span>
) : (
<span className="sans dim">Disabled</span>
)}
<ProviderStatus provider={p} />
</td>
<td className="adm-td" style={{ textAlign: 'right' }}>
<span className="link-accent" onClick={() => setEditing(p)}>Edit</span>

View File

@@ -115,8 +115,8 @@ export default function BotActivityAdmin() {
</td>
</tr>
)}
{events.map((ev, i) => (
<tr key={`${ev.ts}-${ev.ip}-${i}`}>
{events.map((ev) => (
<tr key={`${ev.ts}-${ev.ip}-${ev.type}`}>
<td className="adm-td dim">{dateTime(ev.ts)}</td>
<td className="adm-td" style={{ ...mono, color: 'var(--text)' }}>
{ev.ip}

View File

@@ -45,6 +45,9 @@ export default function Dashboard() {
const changed = dash.last_change || {}
let modeLabel = isLive ? 'Switch to Maintenance' : 'Switch to Live'
if (busy) modeLabel = 'Saving…'
return (
<section>
<div
@@ -82,7 +85,7 @@ export default function Dashboard() {
className="sans"
style={{ border: '1px solid var(--accent)', borderRadius: 999, padding: '11px 24px', background: 'rgba(127,153,189,0.14)', color: '#d8e2ef', fontWeight: 600, fontSize: '0.9rem', cursor: 'pointer' }}
>
{busy ? 'Saving…' : isLive ? 'Switch to Maintenance' : 'Switch to Live'}
{modeLabel}
</button>
</div>

View File

@@ -61,7 +61,7 @@ export default function EmailDelivery() {
const [busy, setBusy] = useState('')
const [msg, setMsg] = useState('')
const [actionError, setActionError] = useState('')
const [banner, setBanner] = useState(null) // { kind: 'ok'|'err', text }
const [banner, setBanner] = useState(null) // fields kind ('ok' or 'err') and text
const load = useCallback(async (seedForm = false) => {
try {

View File

@@ -23,6 +23,34 @@ function tooLargeToUpload(size) {
)
}
// Label for an image-upload button: busy, replace-existing, or first upload.
function uploadLabel(up, hasSrc) {
if (up) return 'Uploading…'
return hasSrc ? 'Replace' : 'Upload'
}
// Shared image-upload behaviour for the element panels that point props.src at
// the uploaded URL (moon + image). Returns the busy flag and file <input> handler.
function useImageUpload(onProps) {
const [up, setUp] = useState(false)
async function onFile(e) {
const f = e.target.files?.[0]
e.target.value = ''
if (!f) return
if (tooLargeToUpload(f.size)) return
setUp(true)
try {
const { url } = await api.admin.upload(f)
onProps({ src: url })
} catch {
/* ignore */
} finally {
setUp(false)
}
}
return { up, onFile }
}
function newElement(type, z) {
const base = { id: genId(), type, x: 50, y: 50, z, anchor: 'center' }
if (type === 'text_block') {
@@ -53,6 +81,23 @@ function scaleFontSize(v, ratio) {
return v
}
// The props patch for a resize drag, per element type: image width is a % of the
// canvas, moon size is px, and a text_block resizes its box and scales every
// line's font proportionally. `ctx` carries the drag origin + measured geometry.
function resizePatch(el, ctx) {
const { orig, dxPx, dxLogical, rectWidth, baseWidth, baseLines } = ctx
if (el.type === 'image') {
return { width: Math.round(clamp(orig + (dxPx / rectWidth) * 100, 5, 100)) } // %
}
if (el.type === 'moon') {
return { size: Math.round(clamp(orig + dxLogical, 24, 400)) } // px
}
const width = Math.round(clamp(orig + dxLogical, 120, 1180))
const ratio = baseWidth ? width / baseWidth : 1
const lines = baseLines.map((l) => ({ ...l, fontSize: scaleFontSize(l.fontSize, ratio) }))
return { width, lines }
}
export default function HeroEditor() {
const [layout, setLayout] = useState(null)
const [live, setLive] = useState(null)
@@ -203,7 +248,9 @@ export default function HeroEditor() {
if (!dim) return
const rect = canvasRef.current.getBoundingClientRect()
const sx = e.clientX
const orig = el.props?.[dim] ?? (dim === 'width' && el.type === 'image' ? 40 : dim === 'width' ? 600 : 64)
let defaultDim = 64
if (dim === 'width') defaultDim = el.type === 'image' ? 40 : 600
const orig = el.props?.[dim] ?? defaultDim
// Snapshot the starting width + lines for text blocks so font scaling is always
// computed against the drag origin (no rounding drift as the pointer moves).
const baseWidth = el.type === 'text_block' ? orig : 0
@@ -217,17 +264,7 @@ export default function HeroEditor() {
const move = (ev) => {
const dxPx = ev.clientX - sx
const dxLogical = dxPx / scale // client px → stage px
if (el.type === 'image') {
updateProps(el.id, { width: Math.round(clamp(orig + (dxPx / rect.width) * 100, 5, 100)) }) // %
} else if (el.type === 'moon') {
updateProps(el.id, { size: Math.round(clamp(orig + dxLogical, 24, 400)) }) // px
} else {
// text_block: resize the box and scale every line's font proportionally.
const width = Math.round(clamp(orig + dxLogical, 120, 1180))
const ratio = baseWidth ? width / baseWidth : 1
const lines = baseLines.map((l) => ({ ...l, fontSize: scaleFontSize(l.fontSize, ratio) }))
updateProps(el.id, { width, lines })
}
updateProps(el.id, resizePatch(el, { orig, dxPx, dxLogical, rectWidth: rect.width, baseWidth, baseLines }))
}
const up = () => {
node.removeEventListener('pointermove', move)
@@ -534,24 +571,7 @@ const swatch = { width: '100%', height: 38, padding: 2, border: '1px solid var(-
function MoonPanel({ element, onProps }) {
const p = element.props || {}
const [up, setUp] = useState(false)
// Reuses the shared admin upload endpoint (same as the image/background panels);
// a successful upload just points props.src at the returned URL.
async function onFile(e) {
const f = e.target.files?.[0]
e.target.value = ''
if (!f) return
if (tooLargeToUpload(f.size)) return
setUp(true)
try {
const { url } = await api.admin.upload(f)
onProps({ src: url })
} catch {
/* ignore */
} finally {
setUp(false)
}
}
const { up, onFile } = useImageUpload(onProps)
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div>
@@ -562,7 +582,7 @@ function MoonPanel({ element, onProps }) {
<p className="sans dim" style={{ margin: '0 0 8px', fontSize: '0.8rem' }}>Using the default moon from the hero artwork.</p>
)}
<label className="btn btn-ghost btn-sq" style={{ display: 'inline-block', cursor: 'pointer' }}>
{up ? 'Uploading…' : p.src ? 'Replace' : 'Upload'}
{uploadLabel(up, !!p.src)}
<input type="file" accept="image/*" onChange={onFile} hidden disabled={up} />
</label>
{p.src && (
@@ -613,29 +633,14 @@ function BadgePanel({ element, onProps }) {
function ImagePanel({ element, onProps }) {
const p = element.props || {}
const [up, setUp] = useState(false)
async function onFile(e) {
const f = e.target.files?.[0]
e.target.value = ''
if (!f) return
if (tooLargeToUpload(f.size)) return
setUp(true)
try {
const { url } = await api.admin.upload(f)
onProps({ src: url })
} catch {
/* ignore */
} finally {
setUp(false)
}
}
const { up, onFile } = useImageUpload(onProps)
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div>
<span className="field-label">Image</span>
{p.src && <img src={p.src} alt="" style={{ width: '100%', maxHeight: 90, objectFit: 'contain', borderRadius: 6, border: '1px solid var(--line)', marginBottom: 8 }} />}
<label className="btn btn-ghost btn-sq" style={{ display: 'inline-block', cursor: 'pointer' }}>
{up ? 'Uploading…' : p.src ? 'Replace' : 'Upload'}
{uploadLabel(up, !!p.src)}
<input type="file" accept="image/*" onChange={onFile} hidden disabled={up} />
</label>
</div>

View File

@@ -43,7 +43,7 @@ function CreateInvite({ onCreated }) {
const [sendEmail, setSendEmail] = useState(true)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [result, setResult] = useState(null) // { emailed, acceptUrl, emailError }
const [result, setResult] = useState(null) // fields emailed, acceptUrl, emailError
async function submit(e) {
e.preventDefault()
@@ -62,6 +62,16 @@ function CreateInvite({ onCreated }) {
}
}
const submitLabel = sendEmail ? 'Create & email' : 'Create link'
let resultText
if (result?.emailed) {
resultText = 'Invitation emailed. You can also share this single-use link:'
} else {
const emailNote = result?.emailError ? ` (email not sent: ${result.emailError})` : ''
resultText = `Invite created${emailNote}. Share this single-use link:`
}
return (
<div className="panel" style={{ padding: 22, marginBottom: 22 }}>
<div className="field-label" style={{ marginBottom: 10 }}>Invite someone</div>
@@ -77,7 +87,7 @@ function CreateInvite({ onCreated }) {
</select>
</label>
<button type="submit" disabled={busy} className="btn btn-primary btn-sq">
{busy ? 'Creating…' : (sendEmail ? 'Create & email' : 'Create link')}
{busy ? 'Creating…' : submitLabel}
</button>
</form>
@@ -90,9 +100,7 @@ function CreateInvite({ onCreated }) {
{result && (
<div style={{ marginTop: 14 }}>
<p className="sans" style={{ margin: '0 0 8px', fontSize: '0.84rem', color: result.emailed ? '#7fd0a4' : 'var(--muted)' }}>
{result.emailed
? 'Invitation emailed. You can also share this single-use link:'
: `Invite created${result.emailError ? ` (email not sent: ${result.emailError})` : ''}. Share this single-use link:`}
{resultText}
</p>
<CopyLink url={result.acceptUrl} />
</div>

View File

@@ -47,6 +47,15 @@ export default function ModerationUser() {
const counts = summary.counts || {}
const tabActions = actions.filter((a) => a.action_type === tab)
let tabBody
if (tab === 'notes') {
tabBody = <NotesTab discordId={discordId} notes={notes} isAdmin={isAdmin} onAdded={reload} />
} else if (tab === 'appeals') {
tabBody = <AppealsTab rows={appeals} />
} else {
tabBody = <ActionTable rows={tabActions} showDuration={tab === 'mute'} />
}
return (
<section>
<Link to="/admin/moderation" className="link-accent" style={{ fontSize: '0.85rem' }}>
@@ -89,13 +98,7 @@ export default function ModerationUser() {
</TabButton>
</div>
{tab === 'notes' ? (
<NotesTab discordId={discordId} notes={notes} isAdmin={isAdmin} onAdded={reload} />
) : tab === 'appeals' ? (
<AppealsTab rows={appeals} />
) : (
<ActionTable rows={tabActions} showDuration={tab === 'mute'} />
)}
{tabBody}
</section>
)
}

View File

@@ -252,6 +252,9 @@ export default function PageBuilder() {
const published = form.status === 'published'
let saveLabel = isEdit ? 'Save' : 'Create'
if (busy) saveLabel = 'Saving…'
return (
<section>
{/* Toolbar */}
@@ -268,7 +271,7 @@ export default function PageBuilder() {
</button>
)}
<button className="btn btn-primary btn-sq" onClick={() => save()} disabled={busy}>
{busy ? 'Saving…' : isEdit ? 'Save' : 'Create'}
{saveLabel}
</button>
</div>
@@ -277,7 +280,7 @@ export default function PageBuilder() {
{error}
{details.length > 0 && (
<ul style={{ margin: '6px 0 0', paddingLeft: 18 }}>
{details.map((d, i) => <li key={i}>{d}</li>)}
{details.map((d) => <li key={d}>{d}</li>)}
</ul>
)}
</div>
@@ -386,7 +389,7 @@ export default function PageBuilder() {
<span className="sans" style={{ color: 'var(--muted)', fontSize: '0.9rem' }}>Show in navigation</span>
</label>
<SelectField label="Nav group" value={form.settings.navGroup} onChange={setSetting('navGroup')} options={NAV_GROUPS} />
<TextField label="Nav order" value={form.settings.navOrder ?? ''} onChange={(v) => setSetting('navOrder')(v === '' ? null : v.replace(/[^0-9]/g, ''))} hint="Lower numbers appear first." />
<TextField label="Nav order" value={form.settings.navOrder ?? ''} onChange={(v) => setSetting('navOrder')(v === '' ? null : v.replace(/\D/g, ''))} hint="Lower numbers appear first." />
</div>
</div>

View File

@@ -109,14 +109,15 @@ export default function SettingsAdmin() {
// A rich field can't live inside a <label> (nested toolbar buttons +
// contenteditable), so it uses a plain <div> wrapper instead.
const Wrap = f.rich ? 'div' : 'label'
return (
<Wrap key={f.key} style={{ display: 'block' }}>
<span className="field-label">{f.label}</span>
{f.rich ? (
let field
if (f.rich) {
field = (
<Suspense fallback={<span className="spin" />}>
<RichTextEditor value={values[f.key]} onChange={setRaw(f.key)} variant="post" />
</Suspense>
) : f.options ? (
)
} else if (f.options) {
field = (
<select value={values[f.key]} onChange={set(f.key)} className="select">
{f.options.map((o) => (
<option key={o.value} value={o.value}>
@@ -124,11 +125,16 @@ export default function SettingsAdmin() {
</option>
))}
</select>
) : f.long ? (
<textarea value={values[f.key]} onChange={set(f.key)} className="textarea" style={{ minHeight: 90 }} />
) : (
<input type="text" value={values[f.key]} onChange={set(f.key)} className="input" />
)}
)
} else if (f.long) {
field = <textarea value={values[f.key]} onChange={set(f.key)} className="textarea" style={{ minHeight: 90 }} />
} else {
field = <input type="text" value={values[f.key]} onChange={set(f.key)} className="input" />
}
return (
<Wrap key={f.key} style={{ display: 'block' }}>
<span className="field-label">{f.label}</span>
{field}
{f.help && (
<span className="sans dim" style={{ display: 'block', marginTop: 6, fontSize: '0.76rem' }}>
{f.help}

View File

@@ -91,9 +91,26 @@ function AccountActions() {
}
const kick = () =>
run('kick', () => api.admin.shardOps.kick({ account: acct }), (r) => `Kicked ${acct}${r?.sessions != null ? ` (${r.sessions} session${r.sessions === 1 ? '' : 's'})` : ''}.`)
run('kick', () => api.admin.shardOps.kick({ account: acct }), (r) => {
const n = r?.sessions != null ? r.sessions : null
const plural = n === 1 ? '' : 's'
const sessions = n != null ? ` (${n} session${plural})` : ''
return `Kicked ${acct}${sessions}.`
})
const ban = () =>
run('ban', () => api.admin.shardOps.ban({ account: acct, durationSec: durationSec === '' ? undefined : Number(durationSec), reason: reason.trim() || undefined }), () => `Banned ${acct}${durationSec ? ` for ${durationSec}s` : ' indefinitely'}.`)
run(
'ban',
() =>
api.admin.shardOps.ban({
account: acct,
durationSec: durationSec === '' ? undefined : Number(durationSec),
reason: reason.trim() || undefined,
}),
() => {
const when = durationSec ? ` for ${durationSec}s` : ' indefinitely'
return `Banned ${acct}${when}.`
},
)
const unban = () => run('unban', () => api.admin.shardOps.unban(acct), () => `Unbanned ${acct}.`)
return (
@@ -200,6 +217,19 @@ function SupportQueue() {
return () => clearInterval(pollRef.current)
}, [load])
let queueBody
if (pages == null) {
queueBody = <p className="sans dim" style={{ margin: 0, fontSize: '0.86rem' }}>Loading</p>
} else if (pages.length === 0) {
queueBody = <p className="sans dim" style={{ margin: 0, fontSize: '0.86rem' }}>The queue is empty.</p>
} else {
queueBody = (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{pages.map((p) => <PageRow key={p.pageId} page={p} onDone={load} />)}
</div>
)
}
return (
<section style={{ borderTop: '1px solid var(--line-soft)', paddingTop: 22, display: 'flex', flexDirection: 'column', gap: 12 }}>
<h3 className="display" style={{ margin: 0, fontSize: '1.05rem', color: 'var(--head)' }}>Support queue</h3>
@@ -207,15 +237,7 @@ function SupportQueue() {
Open help pages from players. A reply reaches them in game (or on their next login).
</p>
{err && <span className="sans" style={{ color: '#d98b84', fontSize: '0.85rem' }}>{err}</span>}
{pages == null ? (
<p className="sans dim" style={{ margin: 0, fontSize: '0.86rem' }}>Loading</p>
) : pages.length === 0 ? (
<p className="sans dim" style={{ margin: 0, fontSize: '0.86rem' }}>The queue is empty.</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{pages.map((p) => <PageRow key={p.pageId} page={p} onDone={load} />)}
</div>
)}
{queueBody}
</section>
)
}

View File

@@ -84,6 +84,38 @@ function Standing({ scope }) {
)
}
// One house row — the many optional detail fields are gathered here so the
// Houses list stays a simple map.
function HouseRow({ house: h }) {
const location = h.region || (h.map != null ? `map ${h.map}` : 'unknown')
const coords = h.x != null ? ` · ${h.x}, ${h.y}` : ''
const owner = h.ownerAcct ? ` · ${h.ownerAcct}` : ''
const shares = h.coOwners || h.friends ? ` · ${h.coOwners || 0} co-owners, ${h.friends || 0} friends` : ''
return (
<li
style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'baseline', padding: '12px 14px', border: '1px solid var(--line)', borderRadius: 10, background: 'rgba(255,255,255,0.02)' }}
>
<div style={{ minWidth: 0 }}>
<div className="sans" style={{ color: 'var(--head)', fontSize: '0.95rem' }}>
{h.name || 'Unnamed house'}
{h.isIdoc && <span className="badge" style={{ marginLeft: 8, background: '#5b2020', color: '#f0c8c2' }}>IDOC</span>}
</div>
<div className="sans dim" style={{ fontSize: '0.78rem', marginTop: 2 }}>
{location}
{coords}
{owner}
{shares}
</div>
</div>
<div className="sans dim" style={{ flex: 'none', fontSize: '0.78rem', textAlign: 'right' }}>
{(h.decay || h.stage) ? <div style={{ color: h.isIdoc ? '#e0928a' : 'var(--muted)' }}>{h.decay || h.stage}</div> : null}
{h.price != null ? <div style={{ fontVariantNumeric: 'tabular-nums' }}>{Number(h.price).toLocaleString()} gp</div> : null}
{h.lastRefreshed ? <div>refreshed {ago(h.lastRefreshed)}</div> : null}
</div>
</li>
)
}
// Houses owned by the user's accounts, IDOC first (flagged).
function Houses({ scope }) {
const { data } = useAsync(() => scope.houses(), [scope])
@@ -96,28 +128,7 @@ function Houses({ scope }) {
) : (
<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
{data.map((h) => (
<li
key={h.serial}
style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'baseline', padding: '12px 14px', border: '1px solid var(--line)', borderRadius: 10, background: 'rgba(255,255,255,0.02)' }}
>
<div style={{ minWidth: 0 }}>
<div className="sans" style={{ color: 'var(--head)', fontSize: '0.95rem' }}>
{h.name || 'Unnamed house'}
{h.isIdoc && <span className="badge" style={{ marginLeft: 8, background: '#5b2020', color: '#f0c8c2' }}>IDOC</span>}
</div>
<div className="sans dim" style={{ fontSize: '0.78rem', marginTop: 2 }}>
{h.region || (h.map != null ? `map ${h.map}` : 'unknown')}
{h.x != null ? ` · ${h.x}, ${h.y}` : ''}
{h.ownerAcct ? ` · ${h.ownerAcct}` : ''}
{(h.coOwners || h.friends) ? ` · ${h.coOwners || 0} co-owners, ${h.friends || 0} friends` : ''}
</div>
</div>
<div className="sans dim" style={{ flex: 'none', fontSize: '0.78rem', textAlign: 'right' }}>
{(h.decay || h.stage) ? <div style={{ color: h.isIdoc ? '#e0928a' : 'var(--muted)' }}>{h.decay || h.stage}</div> : null}
{h.price != null ? <div style={{ fontVariantNumeric: 'tabular-nums' }}>{Number(h.price).toLocaleString()} gp</div> : null}
{h.lastRefreshed ? <div>refreshed {ago(h.lastRefreshed)}</div> : null}
</div>
</li>
<HouseRow key={h.serial} house={h} />
))}
</ul>
)}

View File

@@ -111,6 +111,9 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
}
}
let saveLabel = form.published ? 'Save & publish' : 'Save draft'
if (busy) saveLabel = 'Saving…'
return (
<>
<Modal
@@ -133,7 +136,7 @@ export default function WikiEditor({ slug, onClose, onSaved }) {
Cancel
</button>
<button onClick={save} disabled={busy || loading} className="btn btn-primary btn-sq">
{busy ? 'Saving…' : form.published ? 'Save & publish' : 'Save draft'}
{saveLabel}
</button>
</>
}

View File

@@ -80,11 +80,11 @@ export default function WikiHistory({ slug, onClose, onRestored }) {
</>
}
>
{loading ? (
<span className="spin" />
) : error ? (
{loading && <span className="spin" />}
{!loading && error && (
<p className="sans" style={{ margin: 0, color: '#d98b84', fontSize: '0.85rem' }}>{error}</p>
) : (
)}
{!loading && !error && (
<div className="wiki-history">
<ul className="wiki-history-list">
{revisions.map((r, i) => (
@@ -122,11 +122,16 @@ export default function WikiHistory({ slug, onClose, onRestored }) {
{parts.length === 0 || (parts.length === 1 && !parts[0].added && !parts[0].removed) ? (
<span className="muted">No textual differences.</span>
) : (
parts.map((p, i) => (
<span key={i} className={p.added ? 'diff-add' : p.removed ? 'diff-del' : ''}>
{p.value}
</span>
))
parts.map((p, i) => {
let cls = ''
if (p.added) cls = 'diff-add'
else if (p.removed) cls = 'diff-del'
return (
<span key={`${i}:${p.value}`} className={cls}>
{p.value}
</span>
)
})
)}
</div>
</>

View File

@@ -14,7 +14,7 @@ export default function AcceptInvite() {
const navigate = useNavigate()
const { refresh } = useAuth()
const [invite, setInvite] = useState(null) // { email, role }
const [invite, setInvite] = useState(null) // fields email and role
const [loadErr, setLoadErr] = useState('')
const [signupOk, setSignupOk] = useState(false)

View File

@@ -75,6 +75,9 @@ function ChangePassword({ account }) {
}
}
let pwLabel = hasPassword ? 'Change password' : 'Set password'
if (busy) pwLabel = 'Saving…'
return (
<Section title={hasPassword ? 'Password' : 'Set a password'}>
{!hasPassword && (
@@ -96,7 +99,7 @@ function ChangePassword({ account }) {
</label>
<div>
<button type="submit" disabled={busy} className="btn btn-primary btn-sq">
{busy ? 'Saving…' : hasPassword ? 'Change password' : 'Set password'}
{pwLabel}
</button>
</div>
<Note msg={msg} error={error} />

View File

@@ -125,6 +125,10 @@ export default function PlayerLogin() {
}
}
let submitLabel = 'Sign in'
if (busy) submitLabel = 'Signing in…'
else if (stage === 'totp') submitLabel = 'Verify'
return (
<PlayerShell
subtitle="Player sign-in"
@@ -181,7 +185,7 @@ export default function PlayerLogin() {
)}
<button type="submit" disabled={busy} className="btn btn-primary" style={{ display: 'block', width: '100%', borderRadius: 8, padding: 12, textAlign: 'center' }}>
{busy ? 'Signing in…' : stage === 'totp' ? 'Verify' : 'Sign in'}
{submitLabel}
</button>
{stage === 'creds' && providers.length > 0 && (

View File

@@ -75,15 +75,17 @@ export default function PlayerRegister() {
</p>
}
>
{avail === null ? (
{avail === null && (
<div style={{ display: 'grid', placeItems: 'center', padding: 20 }}>
<span className="spin" />
</div>
) : closed ? (
)}
{avail !== null && closed && (
<p className="sans" style={{ margin: 0, color: 'var(--muted)', fontSize: '0.9rem', textAlign: 'center', lineHeight: 1.6 }}>
Self-registration is currently closed. Please check back later.
</p>
) : (
)}
{avail !== null && !closed && (
<>
{avail.password && (
<form onSubmit={onSubmit}>

View File

@@ -91,6 +91,11 @@ function ChampDetail({ s }) {
)
}
// champion
let progress = ''
if (s.status === 'cooldown') progress = until(s.restartAt) || 'restarting'
else if (s.status === 'active') {
progress = `${Number(s.kills || 0).toLocaleString()} / ${Number(s.maxKills || 0).toLocaleString()} kills`
}
return (
<>
<div className="sans" style={line}>
@@ -98,13 +103,7 @@ function ChampDetail({ s }) {
Level {s.level ?? 0}
{s.bossUp && s.boss ? `${s.boss}` : ''}
</span>
<span>
{s.status === 'cooldown'
? until(s.restartAt) || 'restarting'
: s.status === 'active'
? `${Number(s.kills || 0).toLocaleString()} / ${Number(s.maxKills || 0).toLocaleString()} kills`
: ''}
</span>
<span>{progress}</span>
</div>
{s.status === 'active' && (
<div style={{ marginTop: 6 }}><Meter value={s.kills} max={s.maxKills} /></div>

View File

@@ -79,8 +79,8 @@ function TermHistory({ city }) {
)}
{data && data.length > 0 && (
<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 5 }}>
{data.map((t, i) => (
<li key={i} className="sans" style={{ display: 'flex', justifyContent: 'space-between', gap: 10, fontSize: '0.8rem', color: 'var(--ink)' }}>
{data.map((t) => (
<li key={`${t.startedAt}-${t.governor?.name ?? 'vacant'}`} className="sans" style={{ display: 'flex', justifyContent: 'space-between', gap: 10, fontSize: '0.8rem', color: 'var(--ink)' }}>
<span style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{t.governor?.name || 'Vacant'}
</span>
@@ -100,6 +100,7 @@ function TermHistory({ city }) {
function CityCard({ c }) {
const phase = PHASE[c.electionPhase] || null
const gov = c.governor
const candidatePlural = c.candidates === 1 ? '' : 's'
return (
<div className="panel" style={{ padding: 18 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
@@ -127,7 +128,7 @@ function CityCard({ c }) {
{c.electionPhase && c.electionPhase !== 'none' && (
<div className="sans dim" style={{ marginTop: 10, fontSize: '0.78rem' }}>
{c.candidates ? `${c.candidates} candidate${c.candidates === 1 ? '' : 's'}` : 'No candidates yet'}
{c.candidates ? `${c.candidates} candidate${candidatePlural}` : 'No candidates yet'}
{c.autoPickAt && until(c.autoPickAt) ? ` · resolves ${until(c.autoPickAt)}` : ''}
</div>
)}

View File

@@ -10,6 +10,14 @@ import { api } from '../../api/client.js'
import PlayersOnline from '../../components/PlayersOnline.jsx'
import { useAuth } from '../../contexts/AuthContext.jsx'
// Flavor line under the online/offline banner: online, configured-but-down, or
// not configured yet.
function statusMessage(online, enabled) {
if (online) return 'The gate to Britannia stands open.'
if (enabled) return 'The link to the game world is down — checking back automatically.'
return 'Live shard data is not configured yet.'
}
// ── Gold-supply sparkline ───────────────────────────────────────────────────
function Sparkline({ series }) {
if (!series || series.length < 2) return null
@@ -75,44 +83,7 @@ export default function Shard() {
{!loading && !error && data && (
<>
{/* Connection banner */}
<section
style={{
display: 'flex',
alignItems: 'center',
gap: 16,
padding: '24px 26px',
border: `1px solid ${online ? 'rgba(95,185,138,0.45)' : '#5a4a2a'}`,
borderRadius: 10,
background: online
? 'linear-gradient(180deg,rgba(22,46,34,0.5),rgba(16,26,20,0.4))'
: 'linear-gradient(180deg,rgba(58,46,22,0.5),rgba(30,26,16,0.4))',
marginBottom: 24,
}}
>
<span
style={{
flex: 'none',
width: 12,
height: 12,
borderRadius: '50%',
background: online ? 'var(--mode-live)' : 'var(--mode-maint)',
boxShadow: `0 0 12px ${online ? 'rgba(95,185,138,0.7)' : 'rgba(230,194,106,0.7)'}`,
}}
/>
<div>
<strong className="display" style={{ display: 'block', fontSize: '1.2rem', color: online ? '#bfe6cf' : '#f0e3c4' }}>
{online ? 'The shard is online' : 'The shard is offline'}
</strong>
<span className="sans" style={{ color: online ? '#a9cdb8' : '#cdbf9a', fontSize: '0.98rem' }}>
{online
? 'The gate to Britannia stands open.'
: status?.enabled
? 'The link to the game world is down — checking back automatically.'
: 'Live shard data is not configured yet.'}
</span>
</div>
</section>
<ConnectionBanner online={online} status={status} />
{/* Stat tiles */}
<section className="grid-2" style={{ gap: 14, marginBottom: 24 }}>
@@ -125,31 +96,7 @@ export default function Shard() {
<PlayersOnline />
</div>
{/* Staff online — linked staff accounts only; location is admin/mod-only */}
<section className="panel" style={{ padding: 20, marginBottom: 24 }}>
<div className="sans" style={{ color: 'var(--accent)', fontSize: '0.7rem', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>
Staff online
</div>
{(!data.online || data.online.length === 0) ? (
<p className="sans dim" style={{ margin: 0, fontSize: '0.88rem' }}>No staff are online right now.</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{data.online.map((p) => (
<div key={p.serial} className="sans" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, fontSize: '0.9rem', color: 'var(--ink)' }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
<span style={{ flex: 'none', width: 8, height: 8, borderRadius: '50%', background: '#7fd0a4' }} />
{p.name || p.serial}
</span>
{canSeeLocation && (
<span className="dim" style={{ flex: 'none', fontSize: '0.78rem' }}>
{p.map || '—'}{p.x != null ? ` (${p.x}, ${p.y})` : ''}
</span>
)}
</div>
))}
</div>
)}
</section>
<StaffOnline list={data.online} canSeeLocation={canSeeLocation} />
{/* Economy sparkline */}
{data.economy && data.economy.length > 1 && (
@@ -166,11 +113,14 @@ export default function Shard() {
<FeedList
title="Houses in danger (IDOC)"
empty="No houses are collapsing right now."
items={data.idoc.map((h) => ({
id: h.serial,
text: `${h.name || 'A house'}${h.region ? `${h.region}` : ''}`,
when: h.updatedAt,
}))}
items={data.idoc.map((h) => {
const region = h.region ? `${h.region}` : ''
return {
id: h.serial,
text: `${h.name || 'A house'}${region}`,
when: h.updatedAt,
}
})}
/>
</div>
@@ -212,6 +162,75 @@ export default function Shard() {
)
}
// Online/offline banner with the flavor line under it.
function ConnectionBanner({ online, status }) {
return (
<section
style={{
display: 'flex',
alignItems: 'center',
gap: 16,
padding: '24px 26px',
border: `1px solid ${online ? 'rgba(95,185,138,0.45)' : '#5a4a2a'}`,
borderRadius: 10,
background: online
? 'linear-gradient(180deg,rgba(22,46,34,0.5),rgba(16,26,20,0.4))'
: 'linear-gradient(180deg,rgba(58,46,22,0.5),rgba(30,26,16,0.4))',
marginBottom: 24,
}}
>
<span
style={{
flex: 'none',
width: 12,
height: 12,
borderRadius: '50%',
background: online ? 'var(--mode-live)' : 'var(--mode-maint)',
boxShadow: `0 0 12px ${online ? 'rgba(95,185,138,0.7)' : 'rgba(230,194,106,0.7)'}`,
}}
/>
<div>
<strong className="display" style={{ display: 'block', fontSize: '1.2rem', color: online ? '#bfe6cf' : '#f0e3c4' }}>
{online ? 'The shard is online' : 'The shard is offline'}
</strong>
<span className="sans" style={{ color: online ? '#a9cdb8' : '#cdbf9a', fontSize: '0.98rem' }}>
{statusMessage(online, status?.enabled)}
</span>
</div>
</section>
)
}
// Linked staff accounts currently online; in-game location is admin/mod-only.
function StaffOnline({ list, canSeeLocation }) {
return (
<section className="panel" style={{ padding: 20, marginBottom: 24 }}>
<div className="sans" style={{ color: 'var(--accent)', fontSize: '0.7rem', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>
Staff online
</div>
{(!list || list.length === 0) ? (
<p className="sans dim" style={{ margin: 0, fontSize: '0.88rem' }}>No staff are online right now.</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{list.map((p) => (
<div key={p.serial} className="sans" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, fontSize: '0.9rem', color: 'var(--ink)' }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
<span style={{ flex: 'none', width: 8, height: 8, borderRadius: '50%', background: '#7fd0a4' }} />
{p.name || p.serial}
</span>
{canSeeLocation && (
<span className="dim" style={{ flex: 'none', fontSize: '0.78rem' }}>
{p.map || '—'}{p.x != null ? ` (${p.x}, ${p.y})` : ''}
</span>
)}
</div>
))}
</div>
)}
</section>
)
}
function FeedList({ title, items, empty }) {
return (
<section className="panel" style={{ padding: 20 }}>

View File

@@ -68,7 +68,9 @@ export default function Wiki() {
const activeTag = searchParams.get('tag')
const activeQ = searchParams.get('q')
// Search / tag views fetch a filtered page list; otherwise all pages (grouped here).
const pageOpts = activeQ ? { q: activeQ } : activeTag ? { tag: activeTag } : {}
let pageOpts = {}
if (activeQ) pageOpts = { q: activeQ }
else if (activeTag) pageOpts = { tag: activeTag }
const { loading, error, data } = useAsync(
() =>
Promise.all([api.wikiCategories(), api.wiki(pageOpts)]).then(([categories, pages]) => ({

View File

@@ -37,6 +37,62 @@ function validateBlocks(blocks) {
return { valid: errors.length === 0, errors }
}
// Envelope: only the reserved keys, nothing smuggled at the top level.
function checkEnvelope(block, path, errors) {
for (const key of Object.keys(block)) {
if (!RESERVED_KEYS.includes(key)) {
errors.push(`${path}.${key} is not an allowed top-level key`)
}
}
}
// id — stable, unique across the whole page (top-level and nested share one
// namespace since ids are the future join point for revision history).
function checkId(block, path, seenIds, errors) {
if (typeof block.id !== 'string' || !ID_RE.test(block.id)) {
errors.push(`${path}.id must be a short id string`)
} else if (seenIds.has(block.id)) {
errors.push(`${path}.id duplicates another block id (${block.id})`)
} else {
seenIds.add(block.id)
}
}
// Per-block prop schema from the registry (skipped when props isn't an object —
// that's already reported separately).
function checkPropSchema(def, props, path, errors) {
if (!def.schema || !props || typeof props !== 'object') return
let schemaErrors = []
try {
schemaErrors = def.schema(props) || []
} catch (err) {
schemaErrors = [`schema threw: ${err.message}`]
}
for (const e of schemaErrors) errors.push(`${path}.props.${e}`)
}
// Nesting: only container blocks may hold sub-blocks, capped at one level.
function checkNesting(def, props, path, seenIds, errors, nested) {
if (nested) {
errors.push(`${path} is a container and may not be nested inside another container`)
return
}
for (const slot of def.containerSlots) {
const sub = props ? props[slot] : undefined
if (sub === undefined) continue // an empty slot is allowed
if (!Array.isArray(sub)) {
errors.push(`${path}.props.${slot} must be an array of blocks`)
continue
}
if (sub.length > MAX_SUBBLOCKS) {
errors.push(`${path}.props.${slot} may not exceed ${MAX_SUBBLOCKS} blocks`)
}
sub.forEach((child, j) => {
validateBlock(child, `${path}.props.${slot}[${j}]`, seenIds, errors, { nested: true })
})
}
}
/**
* Validate one block envelope in place. `nested` = true when validating a
* sub-block inside a container slot, which forbids further nesting.
@@ -47,22 +103,8 @@ function validateBlock(block, path, seenIds, errors, { nested }) {
return
}
// Envelope: only the reserved keys, nothing smuggled at the top level.
for (const key of Object.keys(block)) {
if (!RESERVED_KEYS.includes(key)) {
errors.push(`${path}.${key} is not an allowed top-level key`)
}
}
// id — stable, unique across the whole page (top-level and nested share one
// namespace since ids are the future join point for revision history).
if (typeof block.id !== 'string' || !ID_RE.test(block.id)) {
errors.push(`${path}.id must be a short id string`)
} else if (seenIds.has(block.id)) {
errors.push(`${path}.id duplicates another block id (${block.id})`)
} else {
seenIds.add(block.id)
}
checkEnvelope(block, path, errors)
checkId(block, path, seenIds, errors)
// visible — optional in input, but if present must be a boolean.
if (block.visible !== undefined && typeof block.visible !== 'boolean') {
@@ -82,38 +124,8 @@ function validateBlock(block, path, seenIds, errors, { nested }) {
return // can't validate props or nesting without a definition
}
// Per-block prop schema from the registry.
if (def.schema && props && typeof props === 'object') {
let schemaErrors = []
try {
schemaErrors = def.schema(props) || []
} catch (err) {
schemaErrors = [`schema threw: ${err.message}`]
}
for (const e of schemaErrors) errors.push(`${path}.props.${e}`)
}
// Nesting: only container blocks may hold sub-blocks, capped at one level.
if (def.container) {
if (nested) {
errors.push(`${path} is a container and may not be nested inside another container`)
return
}
for (const slot of def.containerSlots) {
const sub = props ? props[slot] : undefined
if (sub === undefined) continue // an empty slot is allowed
if (!Array.isArray(sub)) {
errors.push(`${path}.props.${slot} must be an array of blocks`)
continue
}
if (sub.length > MAX_SUBBLOCKS) {
errors.push(`${path}.props.${slot} may not exceed ${MAX_SUBBLOCKS} blocks`)
}
sub.forEach((child, j) => {
validateBlock(child, `${path}.props.${slot}[${j}]`, seenIds, errors, { nested: true })
})
}
}
checkPropSchema(def, props, path, errors)
if (def.container) checkNesting(def, props, path, seenIds, errors, nested)
}
module.exports = { validateBlocks, MAX_BLOCKS, MAX_SUBBLOCKS }

View File

@@ -92,6 +92,60 @@ function createTracker() {
}
const defaultTracker = createTracker()
// Per-kind mappers, each pushing 0+ targets onto `out` (and updating `tracker`
// for the upsert-transition kinds). Split out of mapShardEvent so that function
// stays a trivial dispatch + the public-safety filter.
const serverStatusUp = (event, tracker, out) =>
out.push({ streamId: 'server.status', ref: `up:${event.bootId || ''}` })
const serverStatusDown = (event, tracker, out) => out.push({ streamId: 'server.status', ref: 'down' })
const EVENT_MAPPERS = {
'server.hello': serverStatusUp,
'server.shutdown': serverStatusDown,
'server.crashed': serverStatusDown,
'house.decay': (event, tracker, out) => {
if (String(event.to).toUpperCase() !== 'IDOC') return
const ref = String(event.serial ?? '')
out.push({ streamId: 'idoc.warning', ref }) // public — location only
if (event.ownerAcct) {
out.push({ streamId: 'house.idoc', ref, ownerAccount: event.ownerAcct }) // personal
}
},
'champ.update': (event, tracker, out) => {
const { serial } = event
if (serial == null) return
const wasActive = tracker.champActive.get(serial) === true
const isActive = event.active === true
tracker.champActive.set(serial, isActive)
if (isActive && !wasActive) out.push({ streamId: 'champ.start', ref: String(serial) })
},
'champ.remove': (event, tracker) => {
if (event.serial != null) tracker.champActive.delete(event.serial)
},
'city.update': (event, tracker, out) => {
const { city } = event
if (!city) return
const gov = event.governor && event.governor.serial != null ? String(event.governor.serial) : null
const prev = tracker.cityGovernor.get(city)
tracker.cityGovernor.set(city, gov)
// Only a real transition to a new governor, and never on first sight
// (prev === undefined) so a reconnect snapshot isn't read as an election.
if (prev !== undefined && gov && gov !== prev) {
out.push({ streamId: 'governor.election', ref: String(city) })
}
},
'vendor.sale': (event, tracker, out) => {
if (event.ownerAcct) {
out.push({ streamId: 'vendor.sale', ref: String(event.t ?? ''), ownerAccount: event.ownerAcct })
}
},
'account.login.attempt': (event, tracker, out) => {
if (event.acct) {
out.push({ streamId: 'account.login', ref: String(event.t ?? ''), ownerAccount: event.acct })
}
},
}
// Map one shard event → an array of targets ({ streamId, ref, ownerAccount? }).
// May yield 0, 1, or 2 targets (an owner house.decay produces both the public
// idoc.warning and the personal house.idoc). Pure given `tracker`.
@@ -100,61 +154,8 @@ function mapShardEvent(event, tracker = defaultTracker) {
const kind = event.kind
const out = []
switch (kind) {
case 'server.hello':
out.push({ streamId: 'server.status', ref: `up:${event.bootId || ''}` })
break
case 'server.shutdown':
case 'server.crashed':
out.push({ streamId: 'server.status', ref: 'down' })
break
case 'house.decay': {
if (String(event.to).toUpperCase() !== 'IDOC') break
const ref = String(event.serial ?? '')
out.push({ streamId: 'idoc.warning', ref }) // public — location only
if (event.ownerAcct) {
out.push({ streamId: 'house.idoc', ref, ownerAccount: event.ownerAcct }) // personal
}
break
}
case 'champ.update': {
const { serial } = event
if (serial == null) break
const wasActive = tracker.champActive.get(serial) === true
const isActive = event.active === true
tracker.champActive.set(serial, isActive)
if (isActive && !wasActive) out.push({ streamId: 'champ.start', ref: String(serial) })
break
}
case 'champ.remove':
if (event.serial != null) tracker.champActive.delete(event.serial)
break
case 'city.update': {
const { city } = event
if (!city) break
const gov = event.governor && event.governor.serial != null ? String(event.governor.serial) : null
const prev = tracker.cityGovernor.get(city)
tracker.cityGovernor.set(city, gov)
// Only a real transition to a new governor, and never on first sight
// (prev === undefined) so a reconnect snapshot isn't read as an election.
if (prev !== undefined && gov && gov !== prev) {
out.push({ streamId: 'governor.election', ref: String(city) })
}
break
}
case 'vendor.sale':
if (event.ownerAcct) {
out.push({ streamId: 'vendor.sale', ref: String(event.t ?? ''), ownerAccount: event.ownerAcct })
}
break
case 'account.login.attempt':
if (event.acct) {
out.push({ streamId: 'account.login', ref: String(event.t ?? ''), ownerAccount: event.acct })
}
break
default:
break
}
const mapper = EVENT_MAPPERS[kind]
if (mapper) mapper(event, tracker, out)
// Defense in depth: a PUBLIC (non-personal) target may only ride a public-safe
// kind. Personal targets are owner-keyed and delivered solely to the owner, so

View File

@@ -48,6 +48,7 @@ const HONEYPOT_POINTS = BAN_THRESHOLD
// access logs (from many rotating IPs), so it carries the single highest weight:
// a lone hit exceeds the ban threshold on its own — effectively a 1-hit ban —
// and outweighs every other individual path.
/** @type {Array<[string, number]>} — scanner path prefix → score weight. */
const PATH_WEIGHTS = [
['/wp-admin/install.php', 200], // top offender in prod logs — near 1-hit ban
['/.env', 100],

View File

@@ -10,8 +10,8 @@ async function log({ req, userId, action, detail }) {
try {
const resolvedUserId = userId ?? (req && req.user ? req.user.id : null)
const ip = req ? req.ip : null
const detailStr =
detail == null ? null : typeof detail === 'string' ? detail : JSON.stringify(detail)
let detailStr = null
if (detail != null) detailStr = typeof detail === 'string' ? detail : JSON.stringify(detail)
await activityDb.insert({ userId: resolvedUserId, action, detail: detailStr, ip })
} catch (err) {
logger.error(`failed to record action "${action}"`, { error: err.message })

View File

@@ -40,7 +40,7 @@ function reshapeWindows(rows) {
// { d1, d7, d30 } sum row, coercing to a number and tolerating a null row.
function windowValue(row, key) {
if (!row) return 0
const col = key === '24h' ? row.d1 : key === '7d' ? row.d7 : row.d30
const col = { '24h': row.d1, '7d': row.d7 }[key] ?? row.d30
return Number(col) || 0
}

View File

@@ -130,35 +130,49 @@ function mapMetadata(metadata) {
return cols
}
// Per-setting validators — each throws a 400 or returns the accepted value. Split
// out of mapSettings so that function stays a flat dispatch (keeps its cognitive
// complexity low).
function validLayout(v) {
if (!LAYOUTS.includes(v)) {
throw new PageError(400, 'invalid_settings', `layout must be one of ${LAYOUTS.join(', ')}.`)
}
return v
}
function validShowInNav(v) {
if (typeof v !== 'boolean') {
throw new PageError(400, 'invalid_settings', 'showInNav must be a boolean.')
}
return v ? 1 : 0
}
function validNavGroup(v) {
if (v !== null && !NAV_GROUPS.includes(v)) {
throw new PageError(400, 'invalid_settings', `navGroup must be null or one of ${NAV_GROUPS.join(', ')}.`)
}
return v
}
function validNavOrder(v) {
if (v !== null && !Number.isInteger(v)) {
throw new PageError(400, 'invalid_settings', 'navOrder must be an integer or null.')
}
return v
}
function validTitle(v) {
if (typeof v !== 'string' || v.trim() === '' || v.length > 200) {
throw new PageError(400, 'invalid_title', 'Title is required (max 200 characters).')
}
return v.trim()
}
// Map the grouped `settings` object to DB columns (except `protected`, which is
// handled by the caller so the unprotect rule stays centralized).
function mapSettings(settings) {
const cols = {}
if (!settings || typeof settings !== 'object') return cols
if ('layout' in settings) {
if (!LAYOUTS.includes(settings.layout)) {
throw new PageError(400, 'invalid_settings', `layout must be one of ${LAYOUTS.join(', ')}.`)
}
cols.layout = settings.layout
}
if ('showInNav' in settings) {
if (typeof settings.showInNav !== 'boolean') {
throw new PageError(400, 'invalid_settings', 'showInNav must be a boolean.')
}
cols.show_in_nav = settings.showInNav ? 1 : 0
}
if ('navGroup' in settings) {
if (settings.navGroup !== null && !NAV_GROUPS.includes(settings.navGroup)) {
throw new PageError(400, 'invalid_settings', `navGroup must be null or one of ${NAV_GROUPS.join(', ')}.`)
}
cols.nav_group = settings.navGroup
}
if ('navOrder' in settings) {
if (settings.navOrder !== null && !Number.isInteger(settings.navOrder)) {
throw new PageError(400, 'invalid_settings', 'navOrder must be an integer or null.')
}
cols.nav_order = settings.navOrder
}
if ('layout' in settings) cols.layout = validLayout(settings.layout)
if ('showInNav' in settings) cols.show_in_nav = validShowInNav(settings.showInNav)
if ('navGroup' in settings) cols.nav_group = validNavGroup(settings.navGroup)
if ('navOrder' in settings) cols.nav_order = validNavOrder(settings.navOrder)
return cols
}
@@ -191,13 +205,10 @@ async function create(input, authorId) {
const { slug, title, blocks = [], status = 'draft', metadata, settings } = input
assertSlug(slug)
assertStatus(status)
if (typeof title !== 'string' || title.trim() === '' || title.length > 200) {
throw new PageError(400, 'invalid_title', 'Title is required (max 200 characters).')
}
const row = {
slug,
title: title.trim(),
title: validTitle(title),
blocks: buildBlocks(blocks),
status,
author_id: authorId,
@@ -219,6 +230,26 @@ async function create(input, authorId) {
return getById(id)
}
// Apply the status patch, stamping published_at the first time a page publishes.
function applyStatusPatch(fields, status, current) {
assertStatus(status)
fields.status = status
if (status === 'published' && !current.published_at) fields.published_at = new Date()
}
// Protected transitions: turning protection ON is allowed here; turning it OFF is
// not (must go through the password-gated unprotect endpoint), regardless of the
// request body. Turning OFF while already unprotected is a no-op.
function applyProtectedPatch(fields, settings, current) {
if (!settings || !('protected' in settings)) return
const want = settings.protected
if (want === true) {
fields.protected = 1
} else if (want === false && current.protected) {
throw new PageError(403, 'unprotect_required', 'Disabling protection requires the unprotect endpoint.')
}
}
async function update(id, patch) {
const current = await pagesDb.findById(id)
if (!current) throw new PageError(404, 'not_found', 'Page not found.')
@@ -230,41 +261,13 @@ async function update(id, patch) {
}
const fields = {}
if (patch.title !== undefined) {
if (typeof patch.title !== 'string' || patch.title.trim() === '' || patch.title.length > 200) {
throw new PageError(400, 'invalid_title', 'Title is required (max 200 characters).')
}
fields.title = patch.title.trim()
}
if (patch.blocks !== undefined) {
fields.blocks = buildBlocks(patch.blocks)
}
if (patch.status !== undefined) {
assertStatus(patch.status)
fields.status = patch.status
// Stamp published_at the first time a page becomes published.
if (patch.status === 'published' && !current.published_at) {
fields.published_at = new Date()
}
}
if (patch.title !== undefined) fields.title = validTitle(patch.title)
if (patch.blocks !== undefined) fields.blocks = buildBlocks(patch.blocks)
if (patch.status !== undefined) applyStatusPatch(fields, patch.status, current)
Object.assign(fields, mapMetadata(patch.metadata))
Object.assign(fields, mapSettings(patch.settings))
// Protected transitions: ON is allowed here; OFF is not (must go through the
// password-gated unprotect endpoint), regardless of the request body.
if (patch.settings && 'protected' in patch.settings) {
const want = patch.settings.protected
if (want === true) {
fields.protected = 1
} else if (want === false && current.protected) {
throw new PageError(403, 'unprotect_required', 'Disabling protection requires the unprotect endpoint.')
}
// want === false while already unprotected → no-op.
}
applyProtectedPatch(fields, patch.settings, current)
await pagesDb.update(id, fields)
return getById(id)

View File

@@ -15,7 +15,8 @@ function stableStringify(value) {
if (value === null || typeof value !== 'object') return JSON.stringify(value)
if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
const keys = Object.keys(value).sort()
return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`
const entries = keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`)
return `{${entries.join(',')}}`
}
// dedupe_key = sha256(kind + t + stable-json(payload)), truncated to 40 hex chars.

View File

@@ -54,9 +54,12 @@ const PUBLIC_ONLINE_ROLES = ['admin', 'editor', 'moderator']
// against shard_account_links (not the sidecar-supplied web_id) so a link takes
// effect immediately, regardless of whether the player has re-logged since
// linking, then through to users so only staff roles are surfaced publicly.
const listOnlineLinked = () =>
query(
`SELECT ${ONLINE_COLS.split(', ').map((c) => `o.${c}`).join(', ')}
const listOnlineLinked = () => {
const cols = ONLINE_COLS.split(', ')
.map((c) => `o.${c}`)
.join(', ')
return query(
`SELECT ${cols}
FROM shard_online o
JOIN shard_account_links l ON l.account = o.acct
JOIN users u ON u.id = l.user_id
@@ -64,6 +67,7 @@ const listOnlineLinked = () =>
ORDER BY o.name ASC`,
PUBLIC_ONLINE_ROLES,
)
}
// ── Economy supply series ────────────────────────────────────────────────
const insertEconomy = ({ accounts, gold, t }) =>

View File

@@ -8,6 +8,17 @@ const db = require('./shardState.db')
const MAX_ECONOMY = 1000
// Small coercion helpers, kept out of the upsert builders below so those stay
// flat (each inline `?? null` / ternary otherwise adds to cognitive complexity).
const orNull = (v) => v ?? null
const toDate = (v) => (v ? new Date(v) : null)
// Owner is an actor object (or null for an abandoned house); flatten to columns.
const ownerFields = (owner) => ({
owner_serial: orNull(owner?.serial),
owner_acct: orNull(owner?.acct),
owner_name: orNull(owner?.name),
})
// Map a camelCase online descriptor to DB columns, dropping undefined keys so a
// partial refresh only touches the fields it carries.
function onlineFields(data) {
@@ -180,23 +191,20 @@ async function listHousesForAccounts(accounts) {
// actor object (or null for an abandoned house).
async function upsertHouseRegistry(data) {
if (!data || !data.serial) return
const owner = data.owner || null
const fields = {
name: data.name ?? null,
owner_serial: owner ? owner.serial ?? null : null,
owner_acct: owner ? owner.acct ?? null : null,
owner_name: owner ? owner.name ?? null : null,
co_owners: data.coOwners ?? null,
friends: data.friends ?? null,
price: data.price ?? null,
decay: data.decay ?? null,
region: data.region ?? null,
map: data.map ?? null,
x: data.x ?? null,
y: data.y ?? null,
z: data.z ?? null,
built_on: data.builtOn ? new Date(data.builtOn) : null,
last_refreshed: data.lastRefreshed ? new Date(data.lastRefreshed) : null,
name: orNull(data.name),
...ownerFields(data.owner || null),
co_owners: orNull(data.coOwners),
friends: orNull(data.friends),
price: orNull(data.price),
decay: orNull(data.decay),
region: orNull(data.region),
map: orNull(data.map),
x: orNull(data.x),
y: orNull(data.y),
z: orNull(data.z),
built_on: toDate(data.builtOn),
last_refreshed: toDate(data.lastRefreshed),
in_registry: 1,
}
await db.upsertHouse(data.serial, fields)
@@ -222,15 +230,15 @@ async function listOnlineForAccounts(accounts) {
async function upsertChamp(ev) {
if (!ev || !ev.serial) return
await db.upsertChamp(ev.serial, {
category: ev.category ?? null,
type: ev.type ?? null,
name: ev.name ?? null,
status: ev.status ?? null,
category: orNull(ev.category),
type: orNull(ev.type),
name: orNull(ev.name),
status: orNull(ev.status),
active: ev.active ? 1 : 0,
map: ev.map ?? null,
x: ev.x ?? null,
y: ev.y ?? null,
z: ev.z ?? null,
map: orNull(ev.map),
x: orNull(ev.x),
y: orNull(ev.y),
z: orNull(ev.z),
boss_up: ev.bossUp ? 1 : 0,
payload: JSON.stringify(ev),
t: Number.isFinite(ev.t) ? ev.t : null,
@@ -280,18 +288,18 @@ async function upsertPage(ev) {
if (!pageId) return
const sender = ev.sender || {}
await db.upsertPage(pageId, {
type: ev.type ?? null,
sender_name: sender.name ?? null,
sender_acct: sender.acct ?? null,
web_id: sender.webId ?? null,
message: ev.message ?? null,
map: ev.map ?? null,
x: ev.x ?? null,
y: ev.y ?? null,
z: ev.z ?? null,
type: orNull(ev.type),
sender_name: orNull(sender.name),
sender_acct: orNull(sender.acct),
web_id: orNull(sender.webId),
message: orNull(ev.message),
map: orNull(ev.map),
x: orNull(ev.x),
y: orNull(ev.y),
z: orNull(ev.z),
sent_ms: Number.isFinite(ev.sentMs) ? ev.sentMs : null,
handled: ev.handled ? 1 : 0,
handler: ev.handler ?? null,
handler: orNull(ev.handler),
payload: JSON.stringify(ev),
})
}
@@ -406,19 +414,19 @@ async function listGuildsLedForAccounts(accounts) {
async function upsertGovernor(ev) {
if (!ev || !ev.city) return
await recordGovernorTransition(ev)
const gov = ev.governor || null
const elect = ev.governorElect || null
const gov = ev.governor
const elect = ev.governorElect
await db.upsertGovernor(ev.city, {
governor_serial: gov ? gov.serial ?? null : null,
governor_name: gov ? gov.name ?? null : null,
governor_acct: gov ? gov.acct ?? null : null,
governor_web_id: gov ? gov.webId ?? null : null,
elect_serial: elect ? elect.serial ?? null : null,
elect_name: elect ? elect.name ?? null : null,
elect_acct: elect ? elect.acct ?? null : null,
election_phase: ev.electionPhase ?? null,
candidates: ev.candidates ?? null,
auto_pick_at: ev.autoPickAt ? new Date(ev.autoPickAt) : null,
governor_serial: orNull(gov?.serial),
governor_name: orNull(gov?.name),
governor_acct: orNull(gov?.acct),
governor_web_id: orNull(gov?.webId),
elect_serial: orNull(elect?.serial),
elect_name: orNull(elect?.name),
elect_acct: orNull(elect?.acct),
election_phase: orNull(ev.electionPhase),
candidates: orNull(ev.candidates),
auto_pick_at: toDate(ev.autoPickAt),
payload: JSON.stringify(ev),
t: Number.isFinite(ev.t) ? ev.t : null,
})

View File

@@ -98,11 +98,10 @@ async function create({ slug, title, body, excerpt, categoryId, published, updat
return getBySlug(slug)
}
// Partial update — only keys present in `input` are written.
async function update(slug, input) {
const current = await wikiDb.findBySlug(slug)
if (!current) return null
// Map the partial `input` to DB columns (only keys present are written), and
// report the cleaned body for link rebuilding when the body changed. Split out of
// update() so that stays a flat sequence of write steps.
function mapUpdateFields(input, current) {
const fields = { updated_by: input.updatedBy ?? null }
let cleanForLinks = null
if ('title' in input) fields.title = input.title
@@ -116,7 +115,15 @@ async function update(slug, input) {
fields.published = input.published ? 1 : 0
if (input.published && !current.published_at) fields.published_at = new Date()
}
return { fields, cleanForLinks }
}
// Partial update — only keys present in `input` are written.
async function update(slug, input) {
const current = await wikiDb.findBySlug(slug)
if (!current) return null
const { fields, cleanForLinks } = mapUpdateFields(input, current)
await wikiDb.updateBySlug(slug, fields)
if (Array.isArray(input.tags)) await syncTags(current.id, input.tags)
if (cleanForLinks != null) await rebuildLinks(current.id, cleanForLinks)

View File

@@ -1113,7 +1113,7 @@ adminRouter.get(
// #swagger.tags = ['Admin · Moderation']
// #swagger.summary = 'Per-user moderation summary (counts, latest tag, linked account)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
param('discordId').matches(/^[0-9]{1,32}$/),
param('discordId').matches(/^d{1,32}$/),
validate,
moderation.getUser,
)
@@ -1122,7 +1122,7 @@ adminRouter.get(
// #swagger.tags = ['Admin · Moderation']
// #swagger.summary = 'Full moderation action history for a user'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
param('discordId').matches(/^[0-9]{1,32}$/),
param('discordId').matches(/^d{1,32}$/),
validate,
moderation.getUserActions,
)
@@ -1131,7 +1131,7 @@ adminRouter.get(
// #swagger.tags = ['Admin · Moderation']
// #swagger.summary = 'Staff notes for a user (admin_only notes hidden from moderators)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
param('discordId').matches(/^[0-9]{1,32}$/),
param('discordId').matches(/^d{1,32}$/),
validate,
moderation.getUserNotes,
)
@@ -1140,7 +1140,7 @@ adminRouter.post(
// #swagger.tags = ['Admin · Moderation']
// #swagger.summary = 'Add a staff note (admin_only visibility requires the admin role)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
param('discordId').matches(/^[0-9]{1,32}$/),
param('discordId').matches(/^d{1,32}$/),
body('body').isString().trim().isLength({ min: 1, max: 4000 }),
body('visibility').optional().isIn(['staff_only', 'admin_only']),
validate,
@@ -1209,7 +1209,7 @@ adminRouter.get(
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
// #swagger.parameters['discordId'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Discord snowflake.' }
/* #swagger.responses[200] = { description: 'Appeals for the user', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/AppealQueueItem" } } } } } */
param('discordId').matches(/^[0-9]{1,32}$/),
param('discordId').matches(/^d{1,32}$/),
validate,
moderation.getUserAppeals,
)

View File

@@ -26,8 +26,7 @@ async function isValidBotToken(token) {
const res = await fetch('https://discord.com/api/users/@me', {
headers: { Authorization: `Bot ${token}` },
})
if (res.status === 401) return false
return true
return res.status !== 401
} catch (err) {
log.warn('discord token validation unreachable — not blocking save', { message: err.message })
return true

View File

@@ -321,31 +321,58 @@ async function mintMobileAuthLink(req, sess, user, providerId, viaTotp) {
// code and 302s to the app callback instead of setting a session cookie. A 2FA
// account is routed through the same web TOTP form (carrying the bridge session)
// and completes in finishSsoTotp — the second factor is never bypassed.
async function finishMobileLogin(req, res, providerId, kind, tx, profile) {
// Validate the mobile bridge session. Returns the session, or sends the failure
// response (redirect when we still have a session for its redirect_uri, else a
// generic 400) and returns null so the caller stops.
async function requireValidBridgeSession(res, tx, providerId) {
const sess = await mobileBridge.getSession(tx.mobileSessionId)
if (!sess || sess.status !== 'pending' || new Date(sess.expires_at).getTime() <= Date.now()) {
log.warn('mobile sso callback: bridge session invalid/expired', { provider: providerId })
// Without a valid session we can't trust a redirect_uri — fail generically.
if (sess) return res.redirect(appError(sess, 'session_expired'))
return res
.status(400)
.json({ message: 'This sign-in session is invalid or has expired. Please try again from the app.' })
const invalid = !sess || sess.status !== 'pending' || new Date(sess.expires_at).getTime() <= Date.now()
if (!invalid) return sess
log.warn('mobile sso callback: bridge session invalid/expired', { provider: providerId })
// Without a valid session we can't trust a redirect_uri — fail generically.
if (sess) {
res.redirect(appError(sess, 'session_expired'))
return null
}
res
.status(400)
.json({ message: 'This sign-in session is invalid or has expired. Please try again from the app.' })
return null
}
let user
// Resolve the linked user for a mobile SSO login (link-only, with opt-in
// provisioning when registration mode allows it). On refusal, sends the redirect
// and returns null.
async function resolveMobileSsoUser(req, res, sess, providerId, profile) {
const identity = await userIdentities.findByProviderSubject(providerId, profile.subject)
if (identity) {
user = await users.getById(identity.user_id)
if (!user) return res.redirect(appError(sess, 'not_linked'))
} else {
const mode = await settings.getRegistrationMode()
if (mode !== 'sso' && mode !== 'both') {
log.warn('mobile sso login refused: no linked account', { provider: providerId })
return res.redirect(appError(sess, 'not_linked'))
const user = await users.getById(identity.user_id)
if (!user) {
res.redirect(appError(sess, 'not_linked'))
return null
}
user = await provisionSsoPlayer(req, providerId, profile)
if (!user) return res.redirect(appError(sess, 'error'))
return user
}
const mode = await settings.getRegistrationMode()
if (mode !== 'sso' && mode !== 'both') {
log.warn('mobile sso login refused: no linked account', { provider: providerId })
res.redirect(appError(sess, 'not_linked'))
return null
}
const user = await provisionSsoPlayer(req, providerId, profile)
if (!user) {
res.redirect(appError(sess, 'error'))
return null
}
return user
}
async function finishMobileLogin(req, res, providerId, kind, tx, profile) {
const sess = await requireValidBridgeSession(res, tx, providerId)
if (!sess) return
const user = await resolveMobileSsoUser(req, res, sess, providerId, profile)
if (!user) return
if (user.status && user.status !== 'active') {
log.warn('mobile sso login refused: inactive account', { provider: providerId, id: user.id, status: user.status })

View File

@@ -188,8 +188,10 @@ async function applyStateChange(event, deps) {
// Ingest one event. Returns { logged, stored } for tests/stats. `fromBackfill`
// suppresses the SSE broadcast (a reconnect replay shouldn't re-animate the
// live ticker). Never throws — a bad single event must not kill the feed.
async function ingest(event, deps = {}) {
const d = {
// Resolve the injectable dependencies to their live defaults (tests override a
// subset). Split out so ingest() isn't penalised for the fan of `|| default`s.
function resolveDeps(deps) {
return {
shardEvents: deps.shardEvents || shardEventsModel,
shardState: deps.shardState || shardStateModel,
shardLinks: deps.shardLinks || shardLinksModel,
@@ -198,6 +200,10 @@ async function ingest(event, deps = {}) {
pushDispatch: deps.pushDispatch || pushDispatch.fromShardEvent,
log: deps.log || defaultLog,
}
}
async function ingest(event, deps = {}) {
const d = resolveDeps(deps)
if (!event || typeof event.kind !== 'string') return { logged: false, stored: false }
// ws.hello / pong are transport frames, not game events.

View File

@@ -97,7 +97,8 @@ function getHistory({ kind, limit = 100 } = {}) {
if (kind) params.set('kind', kind)
if (limit) params.set('limit', String(limit))
const qs = params.toString()
return call(`/history${qs ? `?${qs}` : ''}`)
const suffix = qs ? `?${qs}` : ''
return call(`/history${suffix}`)
}
const getEconomy = (limit = 100) => call(`/economy?limit=${encodeURIComponent(limit)}`)
// Live board / queue projections — snapshotted on WS (re)connect and served from

View File

@@ -43,39 +43,40 @@ function buildUrl(wsUrl, token) {
return token ? `${wsUrl}${sep}token=${encodeURIComponent(token)}` : wsUrl
}
// One guarded board snapshot: fetch, verify `data[key]` is an array, hand it to
// `apply`, and (when given) log `label` with the row count. Isolated so a
// failed/absent board never aborts the rest of backfill — and so backfill()
// stays a flat sequence rather than nine repetitions of the same guard.
async function snapshot(fetchFn, key, apply, label) {
const res = await fetchFn()
if (!res.ok || !res.data || !Array.isArray(res.data[key])) return
await apply(res.data[key])
if (label) log.info(label, { count: res.data[key].length })
}
// Replay events through the dispatcher oldest-first (history/economy arrive
// newest-first) so latest-wins state settles correctly.
async function ingestReversed(events) {
for (const ev of [...events].reverse()) await shardIngest.ingest(ev, { fromBackfill: true })
}
async function ingestEach(events) {
for (const ev of events) await shardIngest.ingest(ev, { fromBackfill: true })
}
// Pull recent events from the sidecar's own store and replay them through the
// dispatcher (fromBackfill = no SSE re-broadcast). dedupe_key + INSERT IGNORE
// make this idempotent, so overlap with what we already stored is harmless.
async function backfill() {
try {
const hist = await uoLinkClient.getHistory({ limit: BACKFILL_LIMIT })
if (hist.ok && hist.data && Array.isArray(hist.data.events)) {
// History is newest-first; replay oldest-first so latest-wins state (e.g.
// house.decay stage) settles correctly.
const events = [...hist.data.events].reverse()
for (const ev of events) await shardIngest.ingest(ev, { fromBackfill: true })
log.info('backfilled events from /history', { count: events.length })
}
const eco = await uoLinkClient.getEconomy(200)
if (eco.ok && eco.data && Array.isArray(eco.data.series)) {
const series = [...eco.data.series].reverse()
for (const ev of series) await shardIngest.ingest(ev, { fromBackfill: true })
}
await snapshot(() => uoLinkClient.getHistory({ limit: BACKFILL_LIMIT }), 'events', ingestReversed, 'backfilled events from /history')
await snapshot(() => uoLinkClient.getEconomy(200), 'series', ingestReversed)
// Champ board + help-page queue have no replay stream — snapshot the
// authoritative current state directly (the sidecar guide's advice for both),
// reconciling our tables to it so a stale row from before a disconnect can't
// linger. Live champ.*/page.* deltas keep them fresh thereafter.
const champs = await uoLinkClient.getChamps()
if (champs.ok && champs.data && Array.isArray(champs.data.spawns)) {
await shardState.replaceChamps(champs.data.spawns)
log.info('snapshotted champ board from /champs', { count: champs.data.spawns.length })
}
const pages = await uoLinkClient.getPages()
if (pages.ok && pages.data && Array.isArray(pages.data.pages)) {
await shardState.replacePages(pages.data.pages)
log.info('snapshotted help-page queue from /pages', { count: pages.data.pages.length })
}
await snapshot(() => uoLinkClient.getChamps(), 'spawns', (s) => shardState.replaceChamps(s), 'snapshotted champ board from /champs')
await snapshot(() => uoLinkClient.getPages(), 'pages', (p) => shardState.replacePages(p), 'snapshotted help-page queue from /pages')
// ── Protocol 2.0 boards ──────────────────────────────────────────────
// Same as champs/pages: snapshot the authoritative current state and
@@ -83,21 +84,10 @@ async function backfill() {
// failed/absent board (e.g. no City Loyalty → empty /governors) never wipes
// another. Governors are NOT cleared before upsert (cities are fixed and the
// term-capture is idempotent, so a reconnect can't spawn spurious terms).
const guilds = await uoLinkClient.getGuilds()
if (guilds.ok && guilds.data && Array.isArray(guilds.data.guilds)) {
await shardState.replaceGuilds(guilds.data.guilds)
log.info('snapshotted guild board from /guilds', { count: guilds.data.guilds.length })
}
const governors = await uoLinkClient.getGovernors()
if (governors.ok && governors.data && Array.isArray(governors.data.cities)) {
await shardState.replaceGovernors(governors.data.cities)
log.info('snapshotted governor board from /governors', { count: governors.data.cities.length })
}
const houses = await uoLinkClient.getHouses()
if (houses.ok && houses.data && Array.isArray(houses.data.houses)) {
for (const ev of houses.data.houses) await shardIngest.ingest(ev, { fromBackfill: true })
log.info('snapshotted house registry from /houses', { count: houses.data.houses.length })
}
await snapshot(() => uoLinkClient.getGuilds(), 'guilds', (g) => shardState.replaceGuilds(g), 'snapshotted guild board from /guilds')
await snapshot(() => uoLinkClient.getGovernors(), 'cities', (c) => shardState.replaceGovernors(c), 'snapshotted governor board from /governors')
await snapshot(() => uoLinkClient.getHouses(), 'houses', ingestEach, 'snapshotted house registry from /houses')
const presence = await uoLinkClient.getPresence()
if (presence.ok && presence.data && typeof presence.data.count === 'number') {
await shardState.setPresence(presence.data)
@@ -150,66 +140,69 @@ async function connect() {
return
}
ws.on('open', async () => {
log.info('uo-link WS connected')
state.connected = true
state.lastConnectedAt = Date.now()
backoff = BACKOFF_MIN_MS
await uoLinkConfig.recordStatus({ status: 'connected', statusDetail: null, pluginConnected: true }).catch(() => {})
await backfill()
})
ws.on('message', async (raw) => {
let event
try {
event = JSON.parse(raw.toString())
} catch {
log.warn('dropping non-JSON WS frame')
return
}
if (event.kind === 'ws.hello') {
helloSeen = true
if (event.protocol && event.protocol !== state.protocol) {
log.error('uo-link protocol mismatch on ws.hello — closing', {
expected: state.protocol,
got: event.protocol,
})
await uoLinkConfig
.recordStatus({ status: 'error', statusDetail: `protocol mismatch: expected ${state.protocol}, got ${event.protocol}` })
.catch(() => {})
running = false
try {
ws.close()
} catch {
/* ignore */
}
}
return
}
if (event.kind === 'pong') return // sidecar heartbeat — ignore
state.lastEventAt = Number.isFinite(event.t) ? event.t : Date.now()
await shardIngest.ingest(event)
})
ws.on('close', async () => {
state.connected = false
if (running) state.reconnects += 1
log.warn('uo-link WS closed')
await uoLinkConfig
.recordStatus({ status: running ? 'reconnecting' : 'disconnected', pluginConnected: false })
.catch(() => {})
ws = null
scheduleReconnect()
})
ws.on('open', handleOpen)
ws.on('message', handleMessage)
ws.on('close', handleClose)
ws.on('error', (err) => {
log.warn('uo-link WS error', { message: err.message })
// 'close' fires after 'error'; reconnect is scheduled there.
})
}
// WS lifecycle handlers, split out of connect() so it stays a flat setup path.
async function handleOpen() {
log.info('uo-link WS connected')
state.connected = true
state.lastConnectedAt = Date.now()
backoff = BACKOFF_MIN_MS
await uoLinkConfig.recordStatus({ status: 'connected', statusDetail: null, pluginConnected: true }).catch(() => {})
await backfill()
}
// A ws.hello frame: mark it seen and, on a protocol mismatch, record the error
// and close (we won't run against an incompatible sidecar).
async function handleHello(event) {
helloSeen = true
if (!event.protocol || event.protocol === state.protocol) return
log.error('uo-link protocol mismatch on ws.hello — closing', { expected: state.protocol, got: event.protocol })
await uoLinkConfig
.recordStatus({ status: 'error', statusDetail: `protocol mismatch: expected ${state.protocol}, got ${event.protocol}` })
.catch(() => {})
running = false
try {
ws.close()
} catch {
/* ignore */
}
}
async function handleMessage(raw) {
let event
try {
event = JSON.parse(raw.toString())
} catch {
log.warn('dropping non-JSON WS frame')
return
}
if (event.kind === 'ws.hello') return handleHello(event)
if (event.kind === 'pong') return // sidecar heartbeat — ignore
state.lastEventAt = Number.isFinite(event.t) ? event.t : Date.now()
await shardIngest.ingest(event)
}
async function handleClose() {
state.connected = false
if (running) state.reconnects += 1
log.warn('uo-link WS closed')
await uoLinkConfig
.recordStatus({ status: running ? 'reconnecting' : 'disconnected', pluginConnected: false })
.catch(() => {})
ws = null
scheduleReconnect()
}
// Begin (or restart) the WS client. Idempotent — a running client is stopped
// first so a config save can re-point it at a new URL/token.
async function start() {