mirror of
https://github.com/prosolis/gogobee.git
synced 2026-07-15 08:32:41 +00:00
Compare commits
4 Commits
667f87f9d0
...
long-exped
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8122973b74 | ||
|
|
cbfca525f5 | ||
|
|
f4a39b46e9 | ||
|
|
6a47be34bc |
@@ -7,6 +7,11 @@ BOT_DISPLAY_NAME=GogoBee
|
||||
# Which rooms the bot posts scheduled content to (comma-separated room IDs)
|
||||
BROADCAST_ROOMS=!roomid:example.com
|
||||
|
||||
# The daily 08:00 WOTD auto-post is disabled by default.
|
||||
# Set to true to enable it. The !wotd command and passive WOTD
|
||||
# usage tracking work regardless of this setting.
|
||||
ENABLE_WOTD_POST=false
|
||||
|
||||
# Admins who can run admin-only commands (comma-separated Matrix user IDs)
|
||||
ADMIN_USERS=@yourmxid:example.com
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ package bot
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"gogobee/internal/plugin"
|
||||
@@ -9,13 +11,24 @@ import (
|
||||
|
||||
// Registry manages plugin registration and event dispatch.
|
||||
type Registry struct {
|
||||
mu sync.RWMutex
|
||||
plugins []plugin.Plugin
|
||||
mu sync.RWMutex
|
||||
plugins []plugin.Plugin
|
||||
ignoredBots map[string]struct{}
|
||||
}
|
||||
|
||||
// NewRegistry creates an empty plugin registry.
|
||||
// NewRegistry creates an empty plugin registry. Senders listed in the
|
||||
// IGNORED_BOTS env var (comma-separated full Matrix user IDs, e.g.
|
||||
// "@pete:parodia.dev") are dropped before any plugin sees them.
|
||||
func NewRegistry() *Registry {
|
||||
return &Registry{}
|
||||
ignored := make(map[string]struct{})
|
||||
if raw := os.Getenv("IGNORED_BOTS"); raw != "" {
|
||||
for _, u := range strings.Split(raw, ",") {
|
||||
if u = strings.TrimSpace(u); u != "" {
|
||||
ignored[u] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
return &Registry{ignoredBots: ignored}
|
||||
}
|
||||
|
||||
// Register adds a plugin to the registry.
|
||||
@@ -42,6 +55,9 @@ func (r *Registry) Init() error {
|
||||
|
||||
// DispatchMessage sends a message context to all plugins in order.
|
||||
func (r *Registry) DispatchMessage(ctx plugin.MessageContext) {
|
||||
if _, ok := r.ignoredBots[string(ctx.Sender)]; ok {
|
||||
return
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
for _, p := range r.plugins {
|
||||
@@ -71,6 +87,9 @@ func (r *Registry) safeOnMessage(p plugin.Plugin, ctx plugin.MessageContext) {
|
||||
|
||||
// DispatchReaction sends a reaction context to all plugins in order.
|
||||
func (r *Registry) DispatchReaction(ctx plugin.ReactionContext) {
|
||||
if _, ok := r.ignoredBots[string(ctx.Sender)]; ok {
|
||||
return
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
for _, p := range r.plugins {
|
||||
|
||||
@@ -333,6 +333,9 @@ func runMigrations(d *sql.DB) error {
|
||||
// engages when a fork / elite / boss / supply pinch actually
|
||||
// needs a decision. CAS-claim on this column gates re-entry.
|
||||
`ALTER TABLE dnd_expedition ADD COLUMN last_autorun_at DATETIME`,
|
||||
// URL link previews now post the page's og:image/twitter:image
|
||||
// thumbnail; cache it alongside the title/description.
|
||||
`ALTER TABLE url_cache ADD COLUMN image_url TEXT NOT NULL DEFAULT ''`,
|
||||
}
|
||||
for _, stmt := range columnMigrations {
|
||||
if _, err := d.Exec(stmt); err != nil {
|
||||
@@ -1124,6 +1127,7 @@ CREATE TABLE IF NOT EXISTS url_cache (
|
||||
url TEXT PRIMARY KEY,
|
||||
title TEXT DEFAULT '',
|
||||
description TEXT DEFAULT '',
|
||||
image_url TEXT NOT NULL DEFAULT '',
|
||||
cached_at INTEGER DEFAULT (unixepoch())
|
||||
);
|
||||
|
||||
@@ -2041,15 +2045,15 @@ func SeedSchedulerDefaults(d *sql.DB) error {
|
||||
name string
|
||||
cron string
|
||||
}{
|
||||
{"prefetch", "5 0 * * *"}, // 00:05 daily
|
||||
{"maintenance", "0 3 * * *"}, // 03:00 daily
|
||||
{"wotd", "0 8 * * *"}, // 08:00 daily
|
||||
{"holidays", "0 7 * * *"}, // 07:00 daily
|
||||
{"releases", "0 9 * * 1"}, // 09:00 Monday
|
||||
{"birthday_check", "0 6 * * *"}, // 06:00 daily
|
||||
{"anime_releases", "0 10 * * *"},// 10:00 daily
|
||||
{"movie_releases", "0 11 * * *"},// 11:00 daily
|
||||
{"concert_digest", "0 12 * * 0"},// 12:00 Sunday
|
||||
{"prefetch", "5 0 * * *"}, // 00:05 daily
|
||||
{"maintenance", "0 3 * * *"}, // 03:00 daily
|
||||
{"wotd", "0 8 * * *"}, // 08:00 daily
|
||||
{"holidays", "0 7 * * *"}, // 07:00 daily
|
||||
{"releases", "0 9 * * 1"}, // 09:00 Monday
|
||||
{"birthday_check", "0 6 * * *"}, // 06:00 daily
|
||||
{"anime_releases", "0 10 * * *"}, // 10:00 daily
|
||||
{"movie_releases", "0 11 * * *"}, // 11:00 daily
|
||||
{"concert_digest", "0 12 * * 0"}, // 12:00 Sunday
|
||||
}
|
||||
|
||||
stmt, err := d.Prepare(`INSERT OR IGNORE INTO scheduler_config (job_name, cron_expr) VALUES (?, ?)`)
|
||||
|
||||
@@ -224,6 +224,12 @@ func (p *AdventurePlugin) Init() error {
|
||||
// existing caster rows once at startup so the lift reaches live
|
||||
// players without waiting for level-up.
|
||||
bootstrapCasterHPRefresh()
|
||||
// 2026-06-18 caster-aid: backfill default spells that postdate a
|
||||
// character's roll (ensureSpellsForCharacter only seeds an empty book),
|
||||
// and a one-off pet gift for an endgame player who never got the morning
|
||||
// arrival roll. Both idempotent via JobCompleted gates.
|
||||
bootstrapCasterSpellBackfill()
|
||||
bootstrapGrantStarterPet()
|
||||
// Phase R1 orphan-archive used to run here on every Init, but it
|
||||
// over-archived: it treats any active dnd_zone_run row not linked to
|
||||
// an active expedition as a legacy `!adventure dungeon` orphan, which
|
||||
|
||||
144
internal/plugin/bootstrap_josie_caster_aid.go
Normal file
144
internal/plugin/bootstrap_josie_caster_aid.go
Normal file
@@ -0,0 +1,144 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"gogobee/internal/db"
|
||||
"maunium.net/go/mautrix/id"
|
||||
)
|
||||
|
||||
// Two one-shot startup bootstraps that lift a low-DPS caster who was stuck in a
|
||||
// boss-wall "death loop". Diagnosis: the boss isn't overtuned — the player is an
|
||||
// over-levelled cleric whose damage output is structurally low. Two account
|
||||
// gaps, fixed idempotently here so they reach the live player without a respec.
|
||||
//
|
||||
// 1. bootstrapCasterSpellBackfill — characters created before a default spell
|
||||
// was added to defaultKnownSpells keep their original spellbook forever:
|
||||
// ensureSpellsForCharacter only seeds when the known-spell list is EMPTY, so
|
||||
// later default additions never reach existing casters. This backfills any
|
||||
// missing default into known+prepared (e.g. inflict_wounds, added to the
|
||||
// cleric defaults after the affected character was rolled). General + future
|
||||
// proof — it fixes any caster with the same stale-default gap.
|
||||
//
|
||||
// 2. bootstrapGrantStarterPet — a targeted gift of a combat companion to a
|
||||
// specific endgame player who never received the 25% morning pet-arrival
|
||||
// roll. A pet adds sustained per-round damage + deflect mitigation, which
|
||||
// helps caster trailers most.
|
||||
|
||||
// bootstrapCasterSpellBackfill adds any missing defaultKnownSpells entry to
|
||||
// every existing caster as known+prepared. addKnownSpell is idempotent and
|
||||
// leaves the prepared flag of already-known spells untouched (ON CONFLICT only
|
||||
// refreshes source), so this only ever adds the genuinely-missing defaults.
|
||||
func bootstrapCasterSpellBackfill() {
|
||||
const jobName = "caster_default_spell_backfill_v1"
|
||||
if db.JobCompleted(jobName, "once") {
|
||||
return
|
||||
}
|
||||
|
||||
chars, err := loadAllAdvCharacters()
|
||||
if err != nil {
|
||||
slog.Error("bootstrap: caster spell backfill — load characters failed", "err", err)
|
||||
return
|
||||
}
|
||||
|
||||
added := 0
|
||||
for _, ac := range chars {
|
||||
c, err := LoadDnDCharacter(ac.UserID)
|
||||
if err != nil || c == nil || !isSpellcaster(c) {
|
||||
continue
|
||||
}
|
||||
known, err := listKnownSpells(c.UserID)
|
||||
if err != nil {
|
||||
slog.Warn("bootstrap: caster spell backfill — list known failed", "user", c.UserID, "err", err)
|
||||
continue
|
||||
}
|
||||
have := make(map[string]bool, len(known))
|
||||
for _, k := range known {
|
||||
have[k.SpellID] = true
|
||||
}
|
||||
defaults := defaultKnownSpells(c.Class, c.Level)
|
||||
if c.Class == ClassRogue && c.Subclass == SubclassArcaneTrickster {
|
||||
defaults = arcaneTricksterDefaultSpells(c.Level)
|
||||
}
|
||||
for _, sid := range defaults {
|
||||
if have[sid] {
|
||||
continue
|
||||
}
|
||||
if err := addKnownSpell(c.UserID, sid, "class", true); err != nil {
|
||||
slog.Error("bootstrap: caster spell backfill — add failed", "user", c.UserID, "spell", sid, "err", err)
|
||||
continue
|
||||
}
|
||||
slog.Info("bootstrap: backfilled default spell", "user", c.UserID, "spell", sid)
|
||||
added++
|
||||
}
|
||||
}
|
||||
|
||||
db.MarkJobCompleted(jobName, "once")
|
||||
if added > 0 {
|
||||
slog.Warn("bootstrap: caster default-spell backfill complete", "spells_added", added)
|
||||
}
|
||||
}
|
||||
|
||||
// josieStarterPet identifies the one player the pet gift targets and the pet
|
||||
// it grants. Kept as data so the intent is legible: this is an admin gift, not
|
||||
// a game-wide policy.
|
||||
var josieStarterPet = struct {
|
||||
userID id.UserID
|
||||
typ string
|
||||
name string
|
||||
level int
|
||||
}{
|
||||
userID: "@holymachina:parodia.dev",
|
||||
typ: "dog",
|
||||
name: "Biscuit",
|
||||
level: 10,
|
||||
}
|
||||
|
||||
// bootstrapGrantStarterPet gives the targeted player a combat companion if they
|
||||
// have none. No-op once they have a pet (this gift, a later arrival, or one
|
||||
// chased away — we don't override the player's own pet history). Idempotent via
|
||||
// the job gate AND the has-pet guard.
|
||||
func bootstrapGrantStarterPet() {
|
||||
const jobName = "grant_starter_pet_holymachina_v1"
|
||||
if db.JobCompleted(jobName, "once") {
|
||||
return
|
||||
}
|
||||
g := josieStarterPet
|
||||
|
||||
char, err := loadAdvCharacter(g.userID)
|
||||
if err != nil || char == nil {
|
||||
// Target not present in this DB (e.g. fresh deploy) — mark done so we
|
||||
// don't re-scan every startup; the gift is a one-off, not a standing rule.
|
||||
db.MarkJobCompleted(jobName, "once")
|
||||
return
|
||||
}
|
||||
if char.PetType != "" || char.PetArrived {
|
||||
slog.Info("bootstrap: starter pet — target already has a pet, skipping", "user", g.userID)
|
||||
db.MarkJobCompleted(jobName, "once")
|
||||
return
|
||||
}
|
||||
|
||||
char.PetType = g.typ
|
||||
char.PetName = g.name
|
||||
char.PetLevel = g.level
|
||||
char.PetXP = 0
|
||||
char.PetArrived = true
|
||||
char.PetChasedAway = false
|
||||
if g.level >= 10 {
|
||||
// Mirror the babysit path that stamps the L10 date when a pet first
|
||||
// reaches the cap, so milestone/supply-shop logic stays consistent.
|
||||
char.PetLevel10Date = time.Now().UTC().Format("2006-01-02")
|
||||
}
|
||||
if err := saveAdvCharacter(char); err != nil {
|
||||
slog.Error("bootstrap: starter pet — save failed", "user", g.userID, "err", err)
|
||||
return
|
||||
}
|
||||
if err := upsertPlayerMetaPetState(char.UserID, petStateFromAdvChar(char)); err != nil {
|
||||
slog.Error("bootstrap: starter pet — player_meta mirror failed", "user", g.userID, "err", err)
|
||||
return
|
||||
}
|
||||
|
||||
db.MarkJobCompleted(jobName, "once")
|
||||
slog.Warn("bootstrap: granted starter pet", "user", g.userID, "pet", g.name, "level", g.level)
|
||||
}
|
||||
@@ -489,6 +489,14 @@ func (p *AdventurePlugin) handleCombatCastCmd(ctx MessageContext, args string) e
|
||||
PlayerHeal: out.PlayerHeal,
|
||||
EnemySkip: out.EnemySkip,
|
||||
}
|
||||
// Concentration AOE damage spells linger: the burst lands this round
|
||||
// (EnemyDamage) and the same value re-ticks every round_end after, via
|
||||
// the engine's concentration aura. spiritual_weapon already covers the
|
||||
// cleric's bonus-action half of the combo; this restores the action half.
|
||||
if spell.Concentration &&
|
||||
(spell.Effect == EffectDamageAuto || spell.Effect == EffectDamageSave) {
|
||||
eff.ConcentrationDmg = out.EnemyDamage
|
||||
}
|
||||
}
|
||||
|
||||
events, err := runCombatRound(sess, &player, &enemy, PlayerAction{Kind: ActionCast, Effect: eff})
|
||||
|
||||
@@ -332,6 +332,14 @@ type combatState struct {
|
||||
// Phase 10 SUB2b — Abjuration Arcane Ward HP buffer.
|
||||
arcaneWardHP int
|
||||
|
||||
// concentrationDmg — per-round damage of an active concentration AOE
|
||||
// (Spirit Guardians et al.). Armed by a !cast of a concentration damage
|
||||
// spell, ticked against the enemy every round_end until the fight ends
|
||||
// or another concentration spell overwrites it. Only the turn engine
|
||||
// reads it; SimulateCombat resolves whole fights in one pass and folds
|
||||
// the aura's value into the picker's concentration multiplier instead.
|
||||
concentrationDmg int
|
||||
|
||||
// Phase 13 bestiary slice 3 — stateful monster-ability effects. Each is
|
||||
// armed by applyAbility and read by the shared resolution primitives, so
|
||||
// both engines honour them; the turn-based engine additionally round-trips
|
||||
|
||||
@@ -239,6 +239,9 @@ func renderEvent(e CombatEvent, playerName, enemyName string, result CombatResul
|
||||
case "spirit_weapon_strike":
|
||||
return fmt.Sprintf(pickRand(narrativeSpiritWeapon), e.Damage)
|
||||
|
||||
case "concentration_tick":
|
||||
return fmt.Sprintf(pickRand(narrativeConcentrationTick), e.Damage)
|
||||
|
||||
case "pet_deflect":
|
||||
return pickRand(narrativePetDeflect)
|
||||
|
||||
@@ -536,6 +539,13 @@ var narrativeSpiritWeapon = []string{
|
||||
"✨ The spectral blade flickers, then bites. %d damage. It does not tire. It does not blink.",
|
||||
}
|
||||
|
||||
var narrativeConcentrationTick = []string{
|
||||
"🌀 The lingering aura grinds the enemy down — %d damage. Still humming. Still hungry.",
|
||||
"🌀 Your spell hasn't let go: the spirits sweep through again for %d damage.",
|
||||
"🌀 The radiant field pulses once more — %d damage. Concentration holds.",
|
||||
"🌀 The enemy steps wrong and the standing magic answers, %d damage. It does not move on.",
|
||||
}
|
||||
|
||||
var narrativePetDeflect = []string{
|
||||
"🐾 Your pet intercepts the blow. Damage halved. Your pet is now your best piece of equipment.",
|
||||
"🐾 Your pet pushes you aside at the last second. Impact reduced. You did not ask to be pushed. Results speak for themselves.",
|
||||
|
||||
@@ -77,6 +77,15 @@ type CombatStatuses struct {
|
||||
ArcaneWardHP int `json:"arcane_ward_hp,omitempty"`
|
||||
HealChargesLeft int `json:"heal_charges_left,omitempty"`
|
||||
|
||||
// ConcentrationDmg is the per-round damage of the player's active
|
||||
// concentration AOE (Spirit Guardians, Spike Growth, Call Lightning,
|
||||
// Flaming Sphere…). A one-shot !cast lands its burst the casting round,
|
||||
// then this re-ticks the aura at round_end every round until the fight
|
||||
// ends or another concentration spell overwrites it — the lingering half
|
||||
// of the spell the engine used to drop on the floor, which left clerics
|
||||
// and druids with no sustained DPS once their burst landed.
|
||||
ConcentrationDmg int `json:"concentration_dmg,omitempty"`
|
||||
|
||||
// Once-per-fight class/race/subclass one-shots: the "already used" flags.
|
||||
// Without persistence these reset every round on resume, letting a Halfling
|
||||
// reroll a nat 1 or an Orc rage every single round of a turn-based fight.
|
||||
|
||||
@@ -263,6 +263,74 @@ func TestTurnEngine_PoisonTickCanBeLethal(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTurnEngine_ConcentrationTickAtRoundEnd(t *testing.T) {
|
||||
sess := turnSession(CombatPhaseRoundEnd, 50, 80)
|
||||
sess.Statuses = CombatStatuses{ConcentrationDmg: 12}
|
||||
player, enemy := basePlayer(), baseEnemy()
|
||||
|
||||
events, err := stepEngine(sess, &player, &enemy, PlayerAction{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sess.EnemyHP != 68 {
|
||||
t.Errorf("enemy_hp = %d, want 68 (80 - 12 aura)", sess.EnemyHP)
|
||||
}
|
||||
if sess.Statuses.ConcentrationDmg != 12 {
|
||||
t.Errorf("concentration_dmg = %d, want 12 (aura persists)", sess.Statuses.ConcentrationDmg)
|
||||
}
|
||||
if len(events) != 1 || events[0].Action != "concentration_tick" || events[0].Damage != 12 {
|
||||
t.Errorf("expected one concentration_tick event, got %+v", events)
|
||||
}
|
||||
if sess.Round != 2 || sess.Phase != CombatPhasePlayerTurn {
|
||||
t.Errorf("round=%d phase=%q, want 2/player_turn", sess.Round, sess.Phase)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTurnEngine_ConcentrationTickCanBeLethal(t *testing.T) {
|
||||
sess := turnSession(CombatPhaseRoundEnd, 50, 9)
|
||||
sess.Statuses = CombatStatuses{ConcentrationDmg: 12}
|
||||
player, enemy := basePlayer(), baseEnemy()
|
||||
|
||||
if _, err := stepEngine(sess, &player, &enemy, PlayerAction{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sess.Status != CombatStatusWon || sess.Phase != CombatPhaseOver {
|
||||
t.Errorf("status=%q phase=%q, want won/over (aura dropped enemy)", sess.Status, sess.Phase)
|
||||
}
|
||||
if sess.EnemyHP != 0 {
|
||||
t.Errorf("enemy_hp = %d, want 0", sess.EnemyHP)
|
||||
}
|
||||
}
|
||||
|
||||
// A concentration damage cast lands its burst this round AND arms the aura so
|
||||
// it re-ticks at every subsequent round_end.
|
||||
func TestTurnEngine_ConcentrationCastArmsAura(t *testing.T) {
|
||||
sess := turnSession(CombatPhasePlayerTurn, 50, 200)
|
||||
player, enemy := basePlayer(), baseEnemy()
|
||||
|
||||
eff := &turnActionEffect{
|
||||
Label: "Spirit Guardians", Action: "spell_cast",
|
||||
EnemyDamage: 15, ConcentrationDmg: 15,
|
||||
}
|
||||
if _, err := stepEngine(sess, &player, &enemy, PlayerAction{Kind: ActionCast, Effect: eff}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sess.EnemyHP != 185 {
|
||||
t.Errorf("enemy_hp = %d, want 185 (200 - 15 burst)", sess.EnemyHP)
|
||||
}
|
||||
if sess.Statuses.ConcentrationDmg != 15 {
|
||||
t.Fatalf("concentration_dmg = %d, want 15 (aura armed)", sess.Statuses.ConcentrationDmg)
|
||||
}
|
||||
// Drive to round_end and confirm the aura bites again.
|
||||
sess.Phase = CombatPhaseRoundEnd
|
||||
if _, err := stepEngine(sess, &player, &enemy, PlayerAction{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sess.EnemyHP != 170 {
|
||||
t.Errorf("enemy_hp = %d, want 170 (185 - 15 aura tick)", sess.EnemyHP)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTurnEngine_Flee(t *testing.T) {
|
||||
sess := turnSession(CombatPhasePlayerTurn, 50, 50)
|
||||
player, enemy := basePlayer(), baseEnemy()
|
||||
|
||||
@@ -64,6 +64,12 @@ type turnActionEffect struct {
|
||||
EnemyDamage int
|
||||
PlayerHeal int
|
||||
EnemySkip bool // control spell: enemy forfeits its attack this round
|
||||
// ConcentrationDmg arms a per-round aura tick when a concentration damage
|
||||
// spell is cast: EnemyDamage is the burst that lands this round, this is
|
||||
// what re-ticks at every round_end after. Zero for one-shot spells; a
|
||||
// non-zero value overwrites any aura already running (5e: one
|
||||
// concentration at a time).
|
||||
ConcentrationDmg int
|
||||
}
|
||||
|
||||
// turnEngine wraps a combatState reconstructed from a persisted CombatSession
|
||||
@@ -125,6 +131,7 @@ func resumeTurnEngine(sess *CombatSession, player, enemy *Combatant, rng *rand.R
|
||||
autoCrit: sess.Statuses.AutoCritFirst,
|
||||
arcaneWardHP: sess.Statuses.ArcaneWardHP,
|
||||
healChargesLeft: sess.Statuses.HealChargesLeft,
|
||||
concentrationDmg: sess.Statuses.ConcentrationDmg,
|
||||
deathSaveUsed: sess.Statuses.DeathSaveUsed,
|
||||
luckyUsed: sess.Statuses.LuckyUsed,
|
||||
raged: sess.Statuses.Raged,
|
||||
@@ -299,6 +306,12 @@ func (te *turnEngine) stepPlayerActionEffect(eff *turnActionEffect) {
|
||||
hpCap := max(1, te.sess.PlayerHPMax-st.maxHPDrain)
|
||||
st.playerHP = min(hpCap, st.playerHP+eff.PlayerHeal)
|
||||
}
|
||||
// Arm / replace the concentration aura. A new concentration cast overwrites
|
||||
// the old one (5e: one concentration at a time); non-concentration casts
|
||||
// leave any running aura alone.
|
||||
if eff.ConcentrationDmg > 0 {
|
||||
st.concentrationDmg = eff.ConcentrationDmg
|
||||
}
|
||||
st.events = append(st.events, CombatEvent{
|
||||
Round: st.round, Phase: turnCombatPhase.Name, Actor: "player", Action: action,
|
||||
Damage: enemyDmg, PlayerHP: st.playerHP, EnemyHP: st.enemyHP, Desc: eff.Label,
|
||||
@@ -454,6 +467,20 @@ func (te *turnEngine) stepRoundEnd() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Concentration aura (Spirit Guardians et al.): the lingering spell bites
|
||||
// the enemy each round it stays up. Ticks before enemy regen so a lethal
|
||||
// pulse settles the fight before the enemy knits its wounds back.
|
||||
if st.concentrationDmg > 0 && st.enemyHP > 0 {
|
||||
st.enemyHP = max(0, st.enemyHP-st.concentrationDmg)
|
||||
st.events = append(st.events, CombatEvent{
|
||||
Round: st.round, Phase: CombatPhaseRoundEnd, Actor: "player", Action: "concentration_tick",
|
||||
Damage: st.concentrationDmg, PlayerHP: st.playerHP, EnemyHP: st.enemyHP,
|
||||
})
|
||||
if st.enemyHP <= 0 {
|
||||
te.finish(CombatStatusWon)
|
||||
return
|
||||
}
|
||||
}
|
||||
// Regenerate (monster ability): the enemy knits its wounds at round end.
|
||||
if st.enemyRegen > 0 && st.enemyHP > 0 && st.enemyHP < te.enemy.Stats.MaxHP {
|
||||
st.enemyHP = min(te.enemy.Stats.MaxHP, st.enemyHP+st.enemyRegen)
|
||||
@@ -499,6 +526,7 @@ func (te *turnEngine) commit() {
|
||||
s.AutoCritFirst = st.autoCrit
|
||||
s.ArcaneWardHP = st.arcaneWardHP
|
||||
s.HealChargesLeft = st.healChargesLeft
|
||||
s.ConcentrationDmg = st.concentrationDmg
|
||||
s.DeathSaveUsed = st.deathSaveUsed
|
||||
s.LuckyUsed = st.luckyUsed
|
||||
s.Raged = st.raged
|
||||
|
||||
@@ -42,6 +42,145 @@ func TestZoneRun_AutoAbandonsAfter24h(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A run reaped by the idle timeout must also terminate the wrapping active
|
||||
// expedition, or the expedition is orphaned 'active' over a dead run and the
|
||||
// player soft-locks (the original feywild "stuck, can't route" bug).
|
||||
func TestZoneRun_IdleTimeoutExtractsWrappingExpedition(t *testing.T) {
|
||||
setupZoneRunTestDB(t)
|
||||
uid := id.UserID("@orphan-run:example")
|
||||
defer cleanupExpeditions(uid)
|
||||
|
||||
run, err := startZoneRun(uid, ZoneGoblinWarrens, 1, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("startZoneRun: %v", err)
|
||||
}
|
||||
exp, err := startExpedition(uid, ZoneGoblinWarrens, run.RunID,
|
||||
ExpeditionSupplies{Current: 10, Max: 10, DailyBurn: 1, HarshMod: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("startExpedition: %v", err)
|
||||
}
|
||||
if err := setExpeditionRunID(exp.ID, run.RunID); err != nil {
|
||||
t.Fatalf("link run: %v", err)
|
||||
}
|
||||
// Backdate the run past the 24h stale threshold.
|
||||
if _, err := dbExecZoneRunBackdate(run.RunID, 25*time.Hour); err != nil {
|
||||
t.Fatalf("backdate: %v", err)
|
||||
}
|
||||
|
||||
got, err := getActiveZoneRun(uid)
|
||||
if err != nil {
|
||||
t.Fatalf("getActiveZoneRun: %v", err)
|
||||
}
|
||||
if got != nil {
|
||||
t.Errorf("expected nil after timeout, got run %q", got.RunID)
|
||||
}
|
||||
// The wrapping expedition must no longer be active.
|
||||
after, err := getExpedition(exp.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("getExpedition: %v", err)
|
||||
}
|
||||
if after == nil {
|
||||
t.Fatal("expedition row vanished")
|
||||
}
|
||||
if after.Status == ExpeditionStatusActive {
|
||||
t.Errorf("expedition still active after run idle-timeout; status=%q", after.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// A stale background fork auto-picks the first unlocked route so the
|
||||
// expedition keeps moving instead of idling out to the reaper.
|
||||
func TestAutoPickStaleFork_TakesAvailableRoute(t *testing.T) {
|
||||
setupZoneRunTestDB(t)
|
||||
uid := id.UserID("@stale-fork:example")
|
||||
defer cleanupExpeditions(uid)
|
||||
|
||||
run, err := startZoneRun(uid, ZoneGoblinWarrens, 1, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("startZoneRun: %v", err)
|
||||
}
|
||||
exp, err := startExpedition(uid, ZoneGoblinWarrens, run.RunID,
|
||||
ExpeditionSupplies{Current: 10, Max: 10, DailyBurn: 1, HarshMod: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("startExpedition: %v", err)
|
||||
}
|
||||
if err := setExpeditionRunID(exp.ID, run.RunID); err != nil {
|
||||
t.Fatalf("link run: %v", err)
|
||||
}
|
||||
pf := pendingFork{
|
||||
PendingAt: "goblin_warrens.cavern_junction",
|
||||
Options: []pendingChoice{
|
||||
{Index: 1, To: "goblin_warrens.guard_post", Label: "Guard Post",
|
||||
Unlocked: false, Lock: "perception_check", Reason: "Perception 8 vs DC 14"},
|
||||
{Index: 2, To: "goblin_warrens.kennel_path", Label: "Kennel Path",
|
||||
Unlocked: true, Lock: "none"},
|
||||
},
|
||||
}
|
||||
if err := writePendingFork(run.RunID, pf); err != nil {
|
||||
t.Fatalf("writePendingFork: %v", err)
|
||||
}
|
||||
r2, _ := getZoneRun(run.RunID)
|
||||
got, _ := decodePendingFork(r2.NodeChoices)
|
||||
if got == nil {
|
||||
t.Fatal("fork not persisted")
|
||||
}
|
||||
|
||||
p := &AdventurePlugin{}
|
||||
if ok := p.autoPickStaleFork(exp, r2, got); !ok {
|
||||
t.Fatal("expected auto-pick to commit a route")
|
||||
}
|
||||
after, _ := getZoneRun(run.RunID)
|
||||
if after.CurrentNode != "goblin_warrens.kennel_path" {
|
||||
t.Errorf("did not advance to the unlocked route: current_node=%q", after.CurrentNode)
|
||||
}
|
||||
if pf2, _ := decodePendingFork(after.NodeChoices); pf2 != nil {
|
||||
t.Errorf("pending fork not cleared after auto-pick")
|
||||
}
|
||||
}
|
||||
|
||||
// When every option is locked there's nothing safe to auto-pick — leave the
|
||||
// fork intact for the player (or the reaper).
|
||||
func TestAutoPickStaleFork_AllLockedLeavesForkIntact(t *testing.T) {
|
||||
setupZoneRunTestDB(t)
|
||||
uid := id.UserID("@locked-fork:example")
|
||||
defer cleanupExpeditions(uid)
|
||||
|
||||
run, err := startZoneRun(uid, ZoneGoblinWarrens, 1, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("startZoneRun: %v", err)
|
||||
}
|
||||
exp, err := startExpedition(uid, ZoneGoblinWarrens, run.RunID,
|
||||
ExpeditionSupplies{Current: 10, Max: 10, DailyBurn: 1, HarshMod: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("startExpedition: %v", err)
|
||||
}
|
||||
_ = setExpeditionRunID(exp.ID, run.RunID)
|
||||
pf := pendingFork{
|
||||
PendingAt: "goblin_warrens.cavern_junction",
|
||||
Options: []pendingChoice{
|
||||
{Index: 1, To: "goblin_warrens.guard_post", Label: "Guard Post",
|
||||
Unlocked: false, Lock: "perception_check", Reason: "DC 14"},
|
||||
},
|
||||
}
|
||||
if err := writePendingFork(run.RunID, pf); err != nil {
|
||||
t.Fatalf("writePendingFork: %v", err)
|
||||
}
|
||||
r2, _ := getZoneRun(run.RunID)
|
||||
before := r2.CurrentNode
|
||||
got, _ := decodePendingFork(r2.NodeChoices)
|
||||
|
||||
p := &AdventurePlugin{}
|
||||
if ok := p.autoPickStaleFork(exp, r2, got); ok {
|
||||
t.Fatal("expected no auto-pick when every option is locked")
|
||||
}
|
||||
after, _ := getZoneRun(run.RunID)
|
||||
if after.CurrentNode != before {
|
||||
t.Errorf("current_node moved on an all-locked fork: %q → %q", before, after.CurrentNode)
|
||||
}
|
||||
if pf2, _ := decodePendingFork(after.NodeChoices); pf2 == nil {
|
||||
t.Errorf("pending fork was cleared on an all-locked fork")
|
||||
}
|
||||
}
|
||||
|
||||
func TestZoneRun_FreshRunNotAutoAbandoned(t *testing.T) {
|
||||
setupZoneRunTestDB(t)
|
||||
uid := id.UserID("@fresh-run:example")
|
||||
|
||||
@@ -2,6 +2,7 @@ package plugin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -667,6 +668,45 @@ func (p *AdventurePlugin) expeditionCmdRun(ctx MessageContext) error {
|
||||
// run graph / harvest tally / supplies / threat — same as before, just
|
||||
// no streamFlow here. compact==true switches the underlying combat
|
||||
// narration into terse mode and auto-resolves elite (not boss) rooms.
|
||||
// forkAutoPickTimeout — how long a background fork may sit unanswered
|
||||
// before the autopilot picks an available route itself. Short enough that
|
||||
// the expedition keeps moving rather than idling out to the 24h stale-run
|
||||
// reaper; long enough that a player away for the evening still gets first
|
||||
// say on a genuine fork.
|
||||
const forkAutoPickTimeout = 8 * time.Hour
|
||||
|
||||
// autoPickStaleFork commits the first unlocked option of a stale background
|
||||
// fork, advancing the run to that node exactly as `!zone go <n>` would
|
||||
// (advanceZoneRunNode + region-transition hook). Returns false — no pick —
|
||||
// when every option is locked, so the caller re-emits the prompt and the
|
||||
// run idles on toward the reaper. The choice is logged as a narrative entry
|
||||
// so the end-of-day digest can surface the decision the player missed.
|
||||
func (p *AdventurePlugin) autoPickStaleFork(exp *Expedition, run *DungeonRun, pf *pendingFork) bool {
|
||||
var chosen *pendingChoice
|
||||
for i := range pf.Options {
|
||||
if pf.Options[i].Unlocked {
|
||||
chosen = &pf.Options[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if chosen == nil {
|
||||
return false // nothing unlocked — leave it for the player / reaper
|
||||
}
|
||||
if err := advanceZoneRunNode(run.RunID, chosen.To); err != nil {
|
||||
slog.Warn("expedition: auto-pick stale fork",
|
||||
"user", run.UserID, "run", run.RunID, "err", err)
|
||||
return false
|
||||
}
|
||||
g, _ := loadZoneGraph(run.ZoneID)
|
||||
fireGraphRegionTransition(run.UserID, g.Nodes[run.CurrentNode], g.Nodes[chosen.To])
|
||||
if exp != nil {
|
||||
_ = appendExpeditionLog(exp.ID, exp.CurrentDay, "narrative",
|
||||
fmt.Sprintf("autopilot took an available path after %dh idle at the fork: %s",
|
||||
int(forkAutoPickTimeout.Hours()), chosen.Label), "")
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *AdventurePlugin) runAutopilotWalk(ctx MessageContext, maxRooms int, compact, inlineBossCombat bool) autopilotWalkResult {
|
||||
exp, err := getActiveExpedition(ctx.Sender)
|
||||
if err != nil {
|
||||
@@ -679,18 +719,28 @@ func (p *AdventurePlugin) runAutopilotWalk(ctx MessageContext, maxRooms int, com
|
||||
return autopilotWalkResult{initErr: "No active region run. Try `!region` to refresh."}
|
||||
}
|
||||
|
||||
// Already standing at a pending fork: autopilot can't pick for the
|
||||
// player. Re-emit the prompt with rooms=0 so the background DM
|
||||
// suppression keeps quiet and we don't tick the rooms counter on a
|
||||
// no-op walk.
|
||||
// Already standing at a pending fork. The autopilot can't pick for the
|
||||
// player, so a fresh fork re-emits the prompt with rooms=0 (background
|
||||
// DM suppression keeps quiet; the rooms counter doesn't tick on a no-op
|
||||
// walk). But a background fork left unanswered past forkAutoPickTimeout
|
||||
// would otherwise idle all the way to the 24h stale-run reaper and end
|
||||
// the expedition — so once it's stale, auto-pick the first available
|
||||
// (unlocked) route and keep walking instead of stalling out.
|
||||
if run, rerr := getActiveZoneRun(ctx.Sender); rerr == nil && run != nil {
|
||||
if pf, derr := decodePendingFork(run.NodeChoices); derr == nil && pf != nil {
|
||||
zone := zoneOrFallback(run.ZoneID)
|
||||
return autopilotWalkResult{
|
||||
finalMsg: renderForkPrompt(zone, *pf),
|
||||
rooms: 0,
|
||||
reason: stopFork,
|
||||
picked := compact &&
|
||||
time.Since(run.LastActionAt) > forkAutoPickTimeout &&
|
||||
p.autoPickStaleFork(exp, run, pf)
|
||||
if !picked {
|
||||
zone := zoneOrFallback(run.ZoneID)
|
||||
return autopilotWalkResult{
|
||||
finalMsg: renderForkPrompt(zone, *pf),
|
||||
rooms: 0,
|
||||
reason: stopFork,
|
||||
}
|
||||
}
|
||||
// Auto-picked: the run now points at the chosen node. Fall
|
||||
// through into the walk loop so this same tick advances it.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -239,19 +239,26 @@ func TestFireBriefings_EventAnchoredActivePlayerDelivers(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
useEventAnchored(t, exp)
|
||||
|
||||
wall := time.Now().UTC()
|
||||
now := time.Date(wall.Year(), wall.Month(), wall.Day(), 6, 30, 0, 0, time.UTC)
|
||||
threshold := time.Date(now.Year(), now.Month(), now.Day(),
|
||||
expeditionBriefingHour, 0, 0, 0, time.UTC)
|
||||
activeActivity := threshold.Add(15 * time.Minute)
|
||||
priorBriefing := now.Add(-24 * time.Hour)
|
||||
// Pin start_date before today's threshold. Left at the default (real
|
||||
// time.Now()), a suite run after 06:00 UTC lands start_date past the
|
||||
// threshold and loadExpeditionsNeedingBriefing (start_date < threshold)
|
||||
// filters the row out — a wall-clock-of-day flake. useEventAnchored runs
|
||||
// after, so its cutoff tracks the backdated start and the run stays
|
||||
// event-anchored.
|
||||
startAt := now.Add(-24 * time.Hour)
|
||||
exp.StartDate = startAt
|
||||
if _, err := db.Get().Exec(
|
||||
`UPDATE dnd_expedition SET last_activity = ?, last_briefing_at = ? WHERE expedition_id = ?`,
|
||||
activeActivity, priorBriefing, exp.ID); err != nil {
|
||||
`UPDATE dnd_expedition SET start_date = ?, last_activity = ?, last_briefing_at = ? WHERE expedition_id = ?`,
|
||||
startAt, activeActivity, priorBriefing, exp.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
useEventAnchored(t, exp)
|
||||
|
||||
p := &AdventurePlugin{}
|
||||
p.fireExpeditionBriefings(now)
|
||||
|
||||
@@ -290,6 +290,17 @@ func getActiveZoneRun(userID id.UserID) (*DungeonRun, error) {
|
||||
}
|
||||
if time.Since(r.LastActionAt) > zoneRunInactivityTimeout {
|
||||
_ = abandonZoneRunByID(r.RunID)
|
||||
// A run reaped by the §4.3 idle timeout must also terminate the
|
||||
// wrapping active expedition. Without this, the expedition is left
|
||||
// status='active' pointing at a now-abandoned run: the autopilot's
|
||||
// runAutopilotWalk reads run==nil and bails, but the briefing/recap
|
||||
// ambient tickers keep firing — the player soft-locks at the last
|
||||
// fork, "stuck" with no way to route on. Mirror the run-loss seam,
|
||||
// but only when this run is the active expedition's current run so
|
||||
// a standalone (non-expedition) stale run still reaps cleanly.
|
||||
if exp, _ := getActiveExpedition(userID); exp != nil && exp.RunID == r.RunID {
|
||||
forceExtractExpeditionForRunLoss(userID, "run idle-timeout (§4.3 stale-run reap)")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
return r, nil
|
||||
|
||||
@@ -919,7 +919,12 @@ func (p *AdventurePlugin) pickAutoCombatAction(uid id.UserID, sess *CombatSessio
|
||||
if id := simPickSpiritualWeapon(c, uid, sess); id != "" {
|
||||
return "cast", id
|
||||
}
|
||||
if id := simPickSpell(c, uid); id != "" {
|
||||
// Once a concentration aura is up, a competent caster maintains it and
|
||||
// attacks (or casts a non-concentration spell) rather than burning a
|
||||
// slot to re-arm the same aura — so the picker excludes concentration
|
||||
// spells while one is active.
|
||||
auraActive := sess.Statuses.ConcentrationDmg > 0
|
||||
if id := simPickSpell(c, uid, auraActive); id != "" {
|
||||
return "cast", id
|
||||
}
|
||||
}
|
||||
@@ -1008,7 +1013,7 @@ func simPickSpiritualWeapon(c *DnDCharacter, uid id.UserID, sess *CombatSession)
|
||||
// - Among feasible candidates, prefer higher slot level (preserves
|
||||
// high-slot supremacy and burns the big slots first); tie-break on
|
||||
// expected damage from the dice string.
|
||||
func simPickSpell(c *DnDCharacter, uid id.UserID) string {
|
||||
func simPickSpell(c *DnDCharacter, uid id.UserID, auraActive bool) string {
|
||||
known, err := listKnownSpells(uid)
|
||||
if err != nil || len(known) == 0 {
|
||||
return ""
|
||||
@@ -1037,6 +1042,11 @@ func simPickSpell(c *DnDCharacter, uid id.UserID) string {
|
||||
if sp.CastTime == CastReaction {
|
||||
continue
|
||||
}
|
||||
// An aura is already ticking — don't re-arm it; prefer attacks or a
|
||||
// non-concentration spell this turn.
|
||||
if auraActive && sp.Concentration {
|
||||
continue
|
||||
}
|
||||
onList := false
|
||||
for _, cl := range sp.Classes {
|
||||
if cl == c.Class {
|
||||
|
||||
184
internal/plugin/link_thumbnail.go
Normal file
184
internal/plugin/link_thumbnail.go
Normal file
@@ -0,0 +1,184 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/gif" // register GIF decoder for DecodeConfig
|
||||
_ "image/jpeg" // register JPEG decoder for DecodeConfig
|
||||
_ "image/png" // register PNG decoder for DecodeConfig
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gogobee/internal/safehttp"
|
||||
|
||||
_ "golang.org/x/image/webp" // register WebP decoder for DecodeConfig
|
||||
|
||||
"maunium.net/go/mautrix/event"
|
||||
"maunium.net/go/mautrix/id"
|
||||
)
|
||||
|
||||
// thumbnailUserAgent identifies the bot when probing and downloading the
|
||||
// preview image for a posted link.
|
||||
const thumbnailUserAgent = "GogoBee/1.0 (+link thumbnail fetch)"
|
||||
|
||||
// thumbnailClient validates and downloads link-supplied image URLs. It routes
|
||||
// through safehttp so a posted link can't steer fetches at loopback / RFC1918 /
|
||||
// cloud-metadata IPs — the dial-time guard re-checks every redirect target too.
|
||||
// The 10 MiB download ceiling below bounds memory regardless.
|
||||
var thumbnailClient = safehttp.NewClient(15 * time.Second)
|
||||
|
||||
// resolveURL turns a possibly-relative ref into an absolute URL against base.
|
||||
func resolveURL(base, ref string) string {
|
||||
ref = strings.TrimSpace(ref)
|
||||
if ref == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return ref
|
||||
}
|
||||
r, err := url.Parse(ref)
|
||||
if err != nil {
|
||||
return ref
|
||||
}
|
||||
return b.ResolveReference(r).String()
|
||||
}
|
||||
|
||||
// normalizeImageURL rewrites known CDN thumbnail URLs to a higher-resolution
|
||||
// variant. Currently handles The Guardian's i.guim.co.uk, whose pages hand out
|
||||
// narrow thumbnails. Signed URLs are left alone (re-signing isn't possible),
|
||||
// as are unrecognized hosts.
|
||||
func normalizeImageURL(raw string) string {
|
||||
if raw == "" {
|
||||
return raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Host != "i.guim.co.uk" {
|
||||
return raw
|
||||
}
|
||||
q := u.Query()
|
||||
if q.Get("width") == "" || q.Get("s") != "" {
|
||||
return raw
|
||||
}
|
||||
q.Set("width", "1200")
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// validateImageURL HEAD-probes an image URL: it must be http(s), return 200,
|
||||
// have an image/* content type, and (if a length is declared) exceed 5 KiB so
|
||||
// tracking pixels are filtered. Returns false with no error on any failure.
|
||||
func validateImageURL(rawURL string) bool {
|
||||
if rawURL == "" || safehttp.ValidateURL(rawURL) != nil {
|
||||
return false
|
||||
}
|
||||
req, err := http.NewRequest("HEAD", rawURL, nil)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
req.Header.Set("User-Agent", thumbnailUserAgent)
|
||||
|
||||
resp, err := thumbnailClient.Do(req)
|
||||
if err != nil {
|
||||
slog.Debug("thumbnail: image HEAD failed", "url", rawURL, "err", err)
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return false
|
||||
}
|
||||
if !strings.HasPrefix(resp.Header.Get("Content-Type"), "image/") {
|
||||
return false
|
||||
}
|
||||
if cl := resp.Header.Get("Content-Length"); cl != "" {
|
||||
if size, err := strconv.ParseInt(cl, 10, 64); err == nil && size <= 5120 {
|
||||
return false // tracking pixel
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// SendImageFromURL downloads imageURL, uploads it to Matrix, and posts it as an
|
||||
// m.image event in roomID. Returns an error on any failure so callers can fall
|
||||
// back to a text-only preview. The fetch is SSRF-guarded and size-capped.
|
||||
func (b *Base) SendImageFromURL(roomID id.RoomID, imageURL string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", imageURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create image request: %w", err)
|
||||
}
|
||||
req.Header.Set("User-Agent", thumbnailUserAgent)
|
||||
|
||||
resp, err := thumbnailClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download image: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("image download status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 10*1024*1024))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read image: %w", err)
|
||||
}
|
||||
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if i := strings.IndexByte(contentType, ';'); i >= 0 {
|
||||
contentType = strings.TrimSpace(contentType[:i])
|
||||
}
|
||||
if contentType == "" {
|
||||
contentType = "image/jpeg"
|
||||
}
|
||||
if !strings.HasPrefix(contentType, "image/") {
|
||||
return fmt.Errorf("not an image: %s", contentType)
|
||||
}
|
||||
|
||||
// Decode dimensions so clients render the image inline rather than as a
|
||||
// downloadable file attachment.
|
||||
var width, height int
|
||||
if cfg, _, decErr := image.DecodeConfig(bytes.NewReader(data)); decErr == nil {
|
||||
width, height = cfg.Width, cfg.Height
|
||||
}
|
||||
|
||||
ext := ".jpg"
|
||||
switch contentType {
|
||||
case "image/png":
|
||||
ext = ".png"
|
||||
case "image/gif":
|
||||
ext = ".gif"
|
||||
case "image/webp":
|
||||
ext = ".webp"
|
||||
}
|
||||
filename := "thumbnail" + ext
|
||||
|
||||
uri, err := b.UploadContent(data, contentType, filename)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upload image: %w", err)
|
||||
}
|
||||
|
||||
content := &event.MessageEventContent{
|
||||
MsgType: event.MsgImage,
|
||||
Body: filename,
|
||||
FileName: filename,
|
||||
URL: uri.CUString(),
|
||||
Info: &event.FileInfo{
|
||||
MimeType: contentType,
|
||||
Size: len(data),
|
||||
Width: width,
|
||||
Height: height,
|
||||
},
|
||||
}
|
||||
_, err = b.Client.SendMessageEvent(context.Background(), roomID, event.EventMessage, content)
|
||||
return err
|
||||
}
|
||||
40
internal/plugin/link_thumbnail_test.go
Normal file
40
internal/plugin/link_thumbnail_test.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package plugin
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestResolveURL(t *testing.T) {
|
||||
cases := []struct {
|
||||
base, ref, want string
|
||||
}{
|
||||
{"https://e.com/news/story", "https://cdn.e.com/a.jpg", "https://cdn.e.com/a.jpg"},
|
||||
{"https://e.com/news/story", "//cdn.e.com/a.jpg", "https://cdn.e.com/a.jpg"},
|
||||
{"https://e.com/news/story", "/img/a.jpg", "https://e.com/img/a.jpg"},
|
||||
{"https://e.com/news/story", "a.jpg", "https://e.com/news/a.jpg"},
|
||||
{"https://e.com/news/story", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := resolveURL(c.base, c.ref); got != c.want {
|
||||
t.Errorf("resolveURL(%q, %q) = %q, want %q", c.base, c.ref, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeImageURL(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, in, want string
|
||||
}{
|
||||
{"non-guardian passthrough", "https://e.com/a.jpg?width=140", "https://e.com/a.jpg?width=140"},
|
||||
{"signed left alone", "https://i.guim.co.uk/x.jpg?width=140&s=abc", "https://i.guim.co.uk/x.jpg?width=140&s=abc"},
|
||||
{"no width passthrough", "https://i.guim.co.uk/x.jpg", "https://i.guim.co.uk/x.jpg"},
|
||||
{"empty", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := normalizeImageURL(c.in); got != c.want {
|
||||
t.Errorf("%s: normalizeImageURL(%q) = %q, want %q", c.name, c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
// Unsigned Guardian thumbnail gets bumped to width=1200.
|
||||
if got := normalizeImageURL("https://i.guim.co.uk/x.jpg?width=140"); got != "https://i.guim.co.uk/x.jpg?width=1200" {
|
||||
t.Errorf("normalizeImageURL unsigned = %q, want width=1200", got)
|
||||
}
|
||||
}
|
||||
429
internal/plugin/scenario_proddb_test.go
Normal file
429
internal/plugin/scenario_proddb_test.go
Normal file
@@ -0,0 +1,429 @@
|
||||
package plugin
|
||||
|
||||
// Scenario tests run against a copy of the prod DB (data/gogobee.db).
|
||||
// Gated on GOGOBEE_PRODDB_SCENARIOS=1 so they don't run on default
|
||||
// `go test ./...` invocations. Pattern mirrors setupAuditTestDB.
|
||||
//
|
||||
// Run with: GOGOBEE_PRODDB_SCENARIOS=1 go test -run TestScenario_ -v \
|
||||
// ./internal/plugin/
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gogobee/internal/db"
|
||||
"maunium.net/go/mautrix/id"
|
||||
)
|
||||
|
||||
func requireScenarioEnv(t *testing.T) {
|
||||
t.Helper()
|
||||
if os.Getenv("GOGOBEE_PRODDB_SCENARIOS") != "1" {
|
||||
t.Skip("scenario tests gated on GOGOBEE_PRODDB_SCENARIOS=1")
|
||||
}
|
||||
}
|
||||
|
||||
// ── Scenario: Josie caster-aid bootstraps ──────────────────────────────────
|
||||
//
|
||||
// Verifies (against a copy of the live DB) that the two 2026-06-18 caster-aid
|
||||
// bootstraps land for @holymachina: the spell backfill adds inflict_wounds to
|
||||
// her known+prepared book, and the pet gift grants a L10 dog mirrored into
|
||||
// player_meta. Both must be idempotent on a second run.
|
||||
func TestScenario_JosieCasterAid(t *testing.T) {
|
||||
requireScenarioEnv(t)
|
||||
setupAuditTestDB(t)
|
||||
|
||||
const uid = id.UserID("@holymachina:parodia.dev")
|
||||
|
||||
hasInflict := func() bool {
|
||||
known, err := listKnownSpells(uid)
|
||||
if err != nil {
|
||||
t.Fatalf("list known: %v", err)
|
||||
}
|
||||
for _, k := range known {
|
||||
if k.SpellID == "inflict_wounds" {
|
||||
return k.Prepared
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if hasInflict() {
|
||||
t.Fatal("precondition failed: target already knows inflict_wounds")
|
||||
}
|
||||
char, err := loadAdvCharacter(uid)
|
||||
if err != nil || char == nil {
|
||||
t.Fatalf("load target char: %v", err)
|
||||
}
|
||||
if char.PetArrived || char.PetType != "" {
|
||||
t.Fatal("precondition failed: target already has a pet")
|
||||
}
|
||||
|
||||
// Run twice to prove idempotency.
|
||||
for i := 0; i < 2; i++ {
|
||||
bootstrapCasterSpellBackfill()
|
||||
bootstrapGrantStarterPet()
|
||||
}
|
||||
|
||||
if !hasInflict() {
|
||||
t.Error("spell backfill did not add inflict_wounds as prepared")
|
||||
}
|
||||
|
||||
got, err := loadAdvCharacter(uid)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("reload target char: %v", err)
|
||||
}
|
||||
if !got.PetArrived || got.PetType != "dog" || got.PetLevel != 10 {
|
||||
t.Errorf("pet grant: arrived=%v type=%q level=%d, want true/dog/10",
|
||||
got.PetArrived, got.PetType, got.PetLevel)
|
||||
}
|
||||
pet, err := loadPetState(uid)
|
||||
if err != nil {
|
||||
t.Fatalf("load pet state: %v", err)
|
||||
}
|
||||
if !pet.HasPet() || pet.Level != 10 {
|
||||
t.Errorf("player_meta pet mirror: hasPet=%v level=%d, want true/10", pet.HasPet(), pet.Level)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Scenario 1: Phase 5-B HP bootstrap ─────────────────────────────────────
|
||||
//
|
||||
// Expected: bootstrapPhase5BHPRefresh() walks dnd_character rows where
|
||||
// dnd_level > 0, refreshes hp_max upward toward computeMaxHP (which
|
||||
// applies phase5BHPMult=1.5), bumps hp_current by the same delta, and
|
||||
// marks the daily_prefetch job key so reruns are no-ops.
|
||||
func TestScenario_Phase5BHPBootstrap(t *testing.T) {
|
||||
requireScenarioEnv(t)
|
||||
setupAuditTestDB(t)
|
||||
|
||||
type charRow struct {
|
||||
userID string
|
||||
class string
|
||||
level int
|
||||
conScore int
|
||||
hpMax int
|
||||
hpCurrent int
|
||||
}
|
||||
snapshot := func() map[string]charRow {
|
||||
rows, err := db.Get().Query(`
|
||||
SELECT user_id, class, dnd_level, con_score, hp_max, hp_current
|
||||
FROM dnd_character WHERE dnd_level > 0`)
|
||||
if err != nil {
|
||||
t.Fatalf("query: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]charRow{}
|
||||
for rows.Next() {
|
||||
var r charRow
|
||||
if err := rows.Scan(&r.userID, &r.class, &r.level, &r.conScore, &r.hpMax, &r.hpCurrent); err != nil {
|
||||
t.Fatalf("scan: %v", err)
|
||||
}
|
||||
out[r.userID] = r
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
before := snapshot()
|
||||
t.Logf("[pre-bootstrap] %d characters with dnd_level > 0", len(before))
|
||||
for _, r := range before {
|
||||
t.Logf(" %s class=%q L%d con=%d hp=%d/%d",
|
||||
r.userID, r.class, r.level, r.conScore, r.hpCurrent, r.hpMax)
|
||||
}
|
||||
|
||||
if db.JobCompleted("phase5b_hp_refresh_v1", "once") {
|
||||
t.Fatalf("job already marked completed before bootstrap — snapshot was post-bootstrap?")
|
||||
}
|
||||
|
||||
bootstrapPhase5BHPRefresh()
|
||||
|
||||
after := snapshot()
|
||||
if !db.JobCompleted("phase5b_hp_refresh_v1", "once") {
|
||||
t.Errorf("expected JobCompleted=true after bootstrap")
|
||||
}
|
||||
|
||||
refreshed := 0
|
||||
for uid, b := range before {
|
||||
a := after[uid]
|
||||
conMod := abilityModifier(b.conScore)
|
||||
_, ok := classInfo(DnDClass(b.class))
|
||||
var expectedMax int
|
||||
if !ok {
|
||||
expectedMax = 1 // computeMaxHP returns 1 for unknown class.
|
||||
} else {
|
||||
expectedMax = computeMaxHP(DnDClass(b.class), conMod, b.level)
|
||||
}
|
||||
// Bootstrap skips rows where newMax <= oldMax (never lowers HP).
|
||||
if expectedMax <= b.hpMax {
|
||||
if a.hpMax != b.hpMax {
|
||||
t.Errorf("%s: expected hp_max unchanged (%d), got %d", uid, b.hpMax, a.hpMax)
|
||||
}
|
||||
continue
|
||||
}
|
||||
delta := expectedMax - b.hpMax
|
||||
expectedCurrent := b.hpCurrent + delta
|
||||
if expectedCurrent > expectedMax {
|
||||
expectedCurrent = expectedMax
|
||||
}
|
||||
if expectedCurrent < 1 {
|
||||
expectedCurrent = 1
|
||||
}
|
||||
if a.hpMax != expectedMax {
|
||||
t.Errorf("%s: hp_max want %d got %d", uid, expectedMax, a.hpMax)
|
||||
}
|
||||
if a.hpCurrent != expectedCurrent {
|
||||
t.Errorf("%s: hp_current want %d (was %d, +delta %d) got %d",
|
||||
uid, expectedCurrent, b.hpCurrent, delta, a.hpCurrent)
|
||||
}
|
||||
// Wound-preservation invariant: absolute wound (max-current) stays
|
||||
// constant unless clamped at floor 1 or at the new ceiling.
|
||||
preWound := b.hpMax - b.hpCurrent
|
||||
postWound := a.hpMax - a.hpCurrent
|
||||
if preWound != postWound && expectedCurrent != 1 && expectedCurrent != expectedMax {
|
||||
t.Errorf("%s: wound size changed pre=%d post=%d (no clamp expected)",
|
||||
uid, preWound, postWound)
|
||||
}
|
||||
refreshed++
|
||||
t.Logf("[refreshed] %s: hp_max %d→%d (+%d), hp_current %d→%d",
|
||||
uid, b.hpMax, a.hpMax, delta, b.hpCurrent, a.hpCurrent)
|
||||
}
|
||||
t.Logf("[post-bootstrap] %d/%d characters refreshed", refreshed, len(before))
|
||||
|
||||
// Idempotency: second call is a no-op.
|
||||
bootstrapPhase5BHPRefresh()
|
||||
after2 := snapshot()
|
||||
for uid, a := range after {
|
||||
if after2[uid].hpMax != a.hpMax || after2[uid].hpCurrent != a.hpCurrent {
|
||||
t.Errorf("%s: second bootstrap call mutated HP", uid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Scenario 2: Magic-item plumbing ────────────────────────────────────────
|
||||
//
|
||||
// Expected:
|
||||
// - magic_item_equipped table exists (Phase 5 migration).
|
||||
// - magicItemRegistry is non-empty; rarity index covers every rarity.
|
||||
// - Slot classifier output (baked into magic_items_srd_data.go via gen)
|
||||
// puts known edge-case items in the right slot per the UX S4 fix.
|
||||
// - dailyCuriosStock() returns a non-empty rotating shelf.
|
||||
func TestScenario_MagicItemPlumbing(t *testing.T) {
|
||||
requireScenarioEnv(t)
|
||||
setupAuditTestDB(t)
|
||||
|
||||
// (a) Migration created the table.
|
||||
var n int
|
||||
err := db.Get().QueryRow(`
|
||||
SELECT COUNT(*) FROM sqlite_master
|
||||
WHERE type='table' AND name='magic_item_equipped'`).Scan(&n)
|
||||
if err != nil || n != 1 {
|
||||
t.Fatalf("magic_item_equipped table missing (n=%d err=%v)", n, err)
|
||||
}
|
||||
|
||||
// (b) Schema sanity — required columns.
|
||||
cols, err := db.Get().Query(`PRAGMA table_info(magic_item_equipped)`)
|
||||
if err != nil {
|
||||
t.Fatalf("pragma: %v", err)
|
||||
}
|
||||
defer cols.Close()
|
||||
have := map[string]bool{}
|
||||
for cols.Next() {
|
||||
var cid int
|
||||
var name, ctype string
|
||||
var notnull, pk int
|
||||
var dflt any
|
||||
_ = cols.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk)
|
||||
have[name] = true
|
||||
}
|
||||
for _, want := range []string{"user_id", "item_id", "slot"} {
|
||||
if !have[want] {
|
||||
t.Errorf("magic_item_equipped missing column %q (have: %v)", want, have)
|
||||
}
|
||||
}
|
||||
|
||||
// (c) Registry populated and rarity index covers every rarity.
|
||||
if len(magicItemRegistry) == 0 {
|
||||
t.Fatalf("magicItemRegistry is empty")
|
||||
}
|
||||
t.Logf("magicItemRegistry: %d items", len(magicItemRegistry))
|
||||
byRarity := magicItemsByRarity()
|
||||
for _, r := range []DnDRarity{RarityCommon, RarityUncommon, RarityRare, RarityVeryRare, RarityLegendary} {
|
||||
if len(byRarity[r]) == 0 {
|
||||
t.Errorf("rarity %q has no items in index", r)
|
||||
} else {
|
||||
t.Logf(" rarity %s: %d items", r, len(byRarity[r]))
|
||||
}
|
||||
}
|
||||
|
||||
// (d) Slot baking — known edge-case items from UX S4 B4 should land
|
||||
// in the slot the fix intended. Slots are baked into the generated
|
||||
// data file by the importer's classifier; the lookup is a fixed table.
|
||||
type slotCheck struct {
|
||||
id string
|
||||
wantSlot DnDSlot
|
||||
mustNotBeRingForSubstring string // sanity vs word-boundary regressions
|
||||
}
|
||||
checks := []slotCheck{
|
||||
{"ring_of_protection", DnDSlotRing1, ""},
|
||||
{"boots_of_striding_and_springing", DnDSlotFeet, "springing"},
|
||||
{"gloves_of_missile_snaring", DnDSlotHands, "snaring"},
|
||||
{"bag_of_devouring", "", "devouring"}, // wondrous w/ no carryable noun
|
||||
{"cloak_of_displacement", DnDSlotCloak, ""},
|
||||
}
|
||||
for _, c := range checks {
|
||||
item, ok := magicItemRegistry[c.id]
|
||||
if !ok {
|
||||
t.Errorf("registry missing %q", c.id)
|
||||
continue
|
||||
}
|
||||
if c.wantSlot != "" && item.Slot != c.wantSlot {
|
||||
t.Errorf("%s: slot=%q want %q", c.id, item.Slot, c.wantSlot)
|
||||
}
|
||||
if item.Slot == DnDSlotRing1 || item.Slot == DnDSlotRing2 {
|
||||
if c.mustNotBeRingForSubstring != "" {
|
||||
t.Errorf("%s: misclassified as ring (substring trap %q)",
|
||||
c.id, c.mustNotBeRingForSubstring)
|
||||
}
|
||||
}
|
||||
t.Logf(" %s → kind=%s slot=%q rarity=%s attune=%v",
|
||||
c.id, item.Kind, item.Slot, item.Rarity, item.Attunement)
|
||||
}
|
||||
|
||||
// (e) Daily curios shelf rotates and returns a non-empty list.
|
||||
shelf := dailyCuriosStock()
|
||||
if len(shelf) == 0 {
|
||||
t.Errorf("dailyCuriosStock returned empty")
|
||||
} else {
|
||||
t.Logf("dailyCuriosStock: %d items (first: %s @ %d, rarity %s)",
|
||||
len(shelf), shelf[0].Name, shelf[0].Value, shelf[0].Rarity)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Scenario 3: Expedition autopilot plumbing ──────────────────────────────
|
||||
//
|
||||
// Expected:
|
||||
// - dnd_expedition.last_ambient_at column exists (Phase 3 migration).
|
||||
// - autopilotFooter renders non-empty paused-state copy for pause
|
||||
// reasons; renders empty for terminal/already-narrated reasons.
|
||||
// - Ambient event pool has positive weights and non-empty flavor pools.
|
||||
func TestScenario_ExpeditionAutopilotPlumbing(t *testing.T) {
|
||||
requireScenarioEnv(t)
|
||||
setupAuditTestDB(t)
|
||||
|
||||
// (a) Migration column present.
|
||||
cols, err := db.Get().Query(`PRAGMA table_info(dnd_expedition)`)
|
||||
if err != nil {
|
||||
t.Fatalf("pragma: %v", err)
|
||||
}
|
||||
defer cols.Close()
|
||||
have := map[string]bool{}
|
||||
for cols.Next() {
|
||||
var cid int
|
||||
var name, ctype string
|
||||
var notnull, pk int
|
||||
var dflt any
|
||||
_ = cols.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk)
|
||||
have[name] = true
|
||||
}
|
||||
if !have["last_ambient_at"] {
|
||||
t.Errorf("dnd_expedition.last_ambient_at missing — Phase 3 migration didn't run")
|
||||
}
|
||||
|
||||
// (b) Stop-reason footers — pause reasons render copy, terminal
|
||||
// reasons render empty (death narration / completion block / etc.
|
||||
// is the final).
|
||||
type footerCheck struct {
|
||||
reason stopReason
|
||||
wantText bool
|
||||
}
|
||||
for _, c := range []footerCheck{
|
||||
{stopFork, true},
|
||||
{stopElite, true},
|
||||
{stopBoss, true},
|
||||
{stopHarvestCombat, true},
|
||||
{stopOK, true}, // hit room cap → "stretch complete"
|
||||
{stopEnded, false},
|
||||
{stopComplete, false},
|
||||
{stopBlocked, false},
|
||||
{stopBossSafety, false}, // res.final carries the held-back line
|
||||
} {
|
||||
got := autopilotFooter(c.reason, 3)
|
||||
if c.wantText && got == "" {
|
||||
t.Errorf("stop reason %v: expected non-empty footer, got empty", c.reason)
|
||||
}
|
||||
if !c.wantText && got != "" {
|
||||
t.Errorf("stop reason %v: expected empty footer, got %q", c.reason, got)
|
||||
}
|
||||
t.Logf(" %v (3 rooms) → %q", c.reason, got)
|
||||
}
|
||||
|
||||
// (c) Ambient event pool — every event has a positive weight and a
|
||||
// non-empty flavor pool. Build a temporary Expedition to satisfy
|
||||
// pickAmbientEvent's eligibility predicates without persisting.
|
||||
events := ambientEvents()
|
||||
if len(events) == 0 {
|
||||
t.Fatalf("ambientEvents() empty")
|
||||
}
|
||||
t.Logf("ambient pool: %d events", len(events))
|
||||
for _, ev := range events {
|
||||
if ev.Weight <= 0 {
|
||||
t.Errorf("ambient event %q has non-positive weight %d", ev.Kind, ev.Weight)
|
||||
}
|
||||
if len(ev.Pool) == 0 {
|
||||
t.Errorf("ambient event %q has empty pool", ev.Kind)
|
||||
} else {
|
||||
t.Logf(" %-22s weight=%d pool=%d sample=%q",
|
||||
ev.Kind, ev.Weight, len(ev.Pool), ev.Pool[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Scenario 4: Spell/help jargon regression ───────────────────────────────
|
||||
//
|
||||
// Expected: live merged spell registry has no banned-phrase leaks across
|
||||
// Description. Mirrors TestSpellDescriptionsAreJargonFree at runtime so
|
||||
// it shows up in this pass.
|
||||
func TestScenario_SpellJargonRegression(t *testing.T) {
|
||||
requireScenarioEnv(t)
|
||||
setupAuditTestDB(t)
|
||||
|
||||
// Mirror dnd_spells_prose_test's TestSpellDescriptionsAreJargonFree:
|
||||
// substring matches for jargon, regex for the SRD-importer placeholder
|
||||
// signature ("Whatever " + lowercase, distinct from legit contractions).
|
||||
bannedSubstrings := []string{
|
||||
"saving throw", "Saving Throw",
|
||||
"spell slot of", "Spell Slot of",
|
||||
"ability modifier", "Ability Modifier",
|
||||
"hit points equal to",
|
||||
}
|
||||
bannedRegexes := []*regexp.Regexp{
|
||||
regexp.MustCompile(`\bd(4|6|8|10|12|20|100)\b`),
|
||||
regexp.MustCompile(`\b\d+d\d+\b`),
|
||||
regexp.MustCompile(`\bWhatever [a-z]`), // placeholder signature
|
||||
regexp.MustCompile(`(?:\.\.\.|…)\s*$`), // trailing ellipsis
|
||||
regexp.MustCompile(`\b[a-z]{1,3}(?:\.\.\.|…)\s*$`), // truncated word
|
||||
regexp.MustCompile(`(?i)\bno larger than in any\b`),
|
||||
}
|
||||
totalSpells := 0
|
||||
leaks := 0
|
||||
for id, s := range dndSpellRegistry {
|
||||
totalSpells++
|
||||
desc := s.Description
|
||||
if desc == "" {
|
||||
continue
|
||||
}
|
||||
for _, b := range bannedSubstrings {
|
||||
if strings.Contains(desc, b) {
|
||||
t.Errorf("spell %q leaks banned phrase %q: %q", id, b, desc)
|
||||
leaks++
|
||||
}
|
||||
}
|
||||
for _, re := range bannedRegexes {
|
||||
if re.MatchString(desc) {
|
||||
t.Errorf("spell %q matches banned pattern %v: %q", id, re, desc)
|
||||
leaks++
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Logf("scanned %d spells; %d jargon leaks", totalSpells, leaks)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"gogobee/internal/db"
|
||||
"gogobee/internal/safehttp"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"maunium.net/go/mautrix"
|
||||
@@ -40,9 +41,10 @@ func NewURLsPlugin(client *mautrix.Client) *URLsPlugin {
|
||||
Base: NewBase(client),
|
||||
enabled: enabled,
|
||||
ignoreUsers: ignore,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 3 * time.Second,
|
||||
},
|
||||
// Route page scrapes through safehttp so a posted link can't steer the
|
||||
// fetch at loopback / RFC1918 / cloud-metadata IPs (re-checked on every
|
||||
// redirect), and can't OOM the parser by streaming an unbounded body.
|
||||
httpClient: safehttp.NewClient(8 * time.Second),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,12 +92,23 @@ func (p *URLsPlugin) OnMessage(ctx MessageContext) error {
|
||||
}
|
||||
|
||||
func (p *URLsPlugin) previewURL(ctx MessageContext, targetURL string) {
|
||||
title, desc, err := p.fetchPreview(targetURL)
|
||||
title, desc, image, err := p.fetchPreview(targetURL)
|
||||
if err != nil {
|
||||
slog.Debug("urls: fetch preview failed", "url", targetURL, "err", err)
|
||||
return
|
||||
}
|
||||
|
||||
if title == "" && desc == "" && image == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// Post the thumbnail first (best-effort), so it renders above the text.
|
||||
if image != "" && validateImageURL(image) {
|
||||
if err := p.SendImageFromURL(ctx.RoomID, image); err != nil {
|
||||
slog.Debug("urls: thumbnail post failed", "url", targetURL, "image", image, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
if title == "" && desc == "" {
|
||||
return
|
||||
}
|
||||
@@ -120,63 +133,69 @@ func (p *URLsPlugin) previewURL(ctx MessageContext, targetURL string) {
|
||||
}
|
||||
}
|
||||
|
||||
// fetchPreview retrieves og:title and og:description, checking cache first.
|
||||
func (p *URLsPlugin) fetchPreview(rawURL string) (string, string, error) {
|
||||
// fetchPreview retrieves og:title, og:description and og:image, checking cache first.
|
||||
func (p *URLsPlugin) fetchPreview(rawURL string) (title, desc, image string, err error) {
|
||||
d := db.Get()
|
||||
now := time.Now().UTC().Unix()
|
||||
cacheTTL := int64(24 * 60 * 60)
|
||||
|
||||
// Check cache
|
||||
var title, desc string
|
||||
var cachedAt int64
|
||||
err := d.QueryRow(
|
||||
`SELECT title, description, cached_at FROM url_cache WHERE url = ?`, rawURL,
|
||||
).Scan(&title, &desc, &cachedAt)
|
||||
err = d.QueryRow(
|
||||
`SELECT title, description, image_url, cached_at FROM url_cache WHERE url = ?`, rawURL,
|
||||
).Scan(&title, &desc, &image, &cachedAt)
|
||||
if err == nil && now-cachedAt < cacheTTL {
|
||||
return title, desc, nil
|
||||
return title, desc, image, nil
|
||||
}
|
||||
|
||||
// Fetch from web
|
||||
title, desc, err = p.scrapeOG(rawURL)
|
||||
title, desc, image, err = p.scrapeOG(rawURL)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
return "", "", "", err
|
||||
}
|
||||
|
||||
// Cache the result
|
||||
db.Exec("urls: cache write",
|
||||
`INSERT INTO url_cache (url, title, description, cached_at) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(url) DO UPDATE SET title = ?, description = ?, cached_at = ?`,
|
||||
rawURL, title, desc, now, title, desc, now,
|
||||
`INSERT INTO url_cache (url, title, description, image_url, cached_at) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(url) DO UPDATE SET title = ?, description = ?, image_url = ?, cached_at = ?`,
|
||||
rawURL, title, desc, image, now, title, desc, image, now,
|
||||
)
|
||||
|
||||
return title, desc, nil
|
||||
return title, desc, image, nil
|
||||
}
|
||||
|
||||
// scrapeOG fetches a URL and extracts og:title and og:description.
|
||||
func (p *URLsPlugin) scrapeOG(rawURL string) (string, string, error) {
|
||||
// scrapeOG fetches a URL and extracts og:title, og:description and og:image.
|
||||
func (p *URLsPlugin) scrapeOG(rawURL string) (string, string, string, error) {
|
||||
if err := safehttp.ValidateURL(rawURL); err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", rawURL, nil)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("create request: %w", err)
|
||||
return "", "", "", fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("User-Agent", "GogoBee Bot/1.0")
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml")
|
||||
|
||||
resp, err := p.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("fetch: %w", err)
|
||||
return "", "", "", fmt.Errorf("fetch: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", "", fmt.Errorf("status %d", resp.StatusCode)
|
||||
return "", "", "", fmt.Errorf("status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
// Cap the parsed body at 2 MiB — og: tags live in <head>, near the top.
|
||||
doc, err := goquery.NewDocumentFromReader(safehttp.LimitedBody(resp.Body, 2*1024*1024))
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("parse HTML: %w", err)
|
||||
return "", "", "", fmt.Errorf("parse HTML: %w", err)
|
||||
}
|
||||
|
||||
title := ""
|
||||
desc := ""
|
||||
image := ""
|
||||
|
||||
doc.Find("meta").Each(func(_ int, s *goquery.Selection) {
|
||||
prop, _ := s.Attr("property")
|
||||
@@ -186,6 +205,10 @@ func (p *URLsPlugin) scrapeOG(rawURL string) (string, string, error) {
|
||||
title = content
|
||||
case "og:description":
|
||||
desc = content
|
||||
case "og:image:secure_url", "og:image:url", "og:image":
|
||||
if image == "" && strings.TrimSpace(content) != "" {
|
||||
image = content
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -205,5 +228,9 @@ func (p *URLsPlugin) scrapeOG(rawURL string) (string, string, error) {
|
||||
})
|
||||
}
|
||||
|
||||
return strings.TrimSpace(title), strings.TrimSpace(desc), nil
|
||||
if image != "" {
|
||||
image = normalizeImageURL(resolveURL(rawURL, strings.TrimSpace(image)))
|
||||
}
|
||||
|
||||
return strings.TrimSpace(title), strings.TrimSpace(desc), image, nil
|
||||
}
|
||||
|
||||
146
internal/safehttp/safehttp.go
Normal file
146
internal/safehttp/safehttp.go
Normal file
@@ -0,0 +1,146 @@
|
||||
// Package safehttp provides an http.Client hardened against SSRF and
|
||||
// memory-DoS via hostile upstreams. Every outbound fetch the bot makes
|
||||
// against feed-supplied URLs (RSS articles, image hosts) should go through
|
||||
// one of these clients so a malicious feed can't steer the bot at loopback,
|
||||
// link-local, RFC1918, or cloud metadata IPs, and can't OOM the process by
|
||||
// streaming an unbounded body.
|
||||
package safehttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrBlockedHost is returned when a URL resolves to a non-public IP.
|
||||
var ErrBlockedHost = errors.New("safehttp: blocked non-public host")
|
||||
|
||||
// AllowPrivate, when true, disables the loopback/RFC1918 dial guard. It
|
||||
// exists for tests that spin up httptest.NewServer on 127.0.0.1 — never
|
||||
// set this in production.
|
||||
var AllowPrivate bool
|
||||
|
||||
// safeDialContext refuses connections to non-public IPs. It runs after
|
||||
// DNS resolution, so a hostile DNS rebinding that returns 127.0.0.1
|
||||
// still gets blocked at dial time.
|
||||
func safeDialContext(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ips, err := (&net.Resolver{}).LookupIP(ctx, "ip", host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var allowed net.IP
|
||||
for _, ip := range ips {
|
||||
if AllowPrivate || isPublicIP(ip) {
|
||||
allowed = ip
|
||||
break
|
||||
}
|
||||
}
|
||||
if allowed == nil {
|
||||
return nil, fmt.Errorf("%w: %s", ErrBlockedHost, host)
|
||||
}
|
||||
d := &net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}
|
||||
return d.DialContext(ctx, network, net.JoinHostPort(allowed.String(), port))
|
||||
}
|
||||
|
||||
// isPublicIP reports whether ip is a globally routable unicast address.
|
||||
// Rejects loopback, link-local, multicast, RFC1918, CGNAT, and the
|
||||
// AWS/GCP/Azure metadata IPs 169.254.169.254 / fd00:ec2::254 (these
|
||||
// already fall under link-local but spell it out for clarity).
|
||||
func isPublicIP(ip net.IP) bool {
|
||||
if ip == nil || ip.IsUnspecified() || ip.IsLoopback() ||
|
||||
ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() ||
|
||||
ip.IsMulticast() || ip.IsPrivate() {
|
||||
return false
|
||||
}
|
||||
// 100.64.0.0/10 (CGNAT) is not covered by IsPrivate on older Go.
|
||||
if v4 := ip.To4(); v4 != nil {
|
||||
if v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127 {
|
||||
return false
|
||||
}
|
||||
// 0.0.0.0/8 and friends.
|
||||
if v4[0] == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ValidateURL returns nil if the URL is http(s) and parseable. It does
|
||||
// not resolve DNS — the dial step does that — but it does reject bare
|
||||
// schemes (file://, gopher://, etc.) before we even open a connection.
|
||||
func ValidateURL(raw string) error {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
return fmt.Errorf("safehttp: unsupported scheme %q", u.Scheme)
|
||||
}
|
||||
if u.Host == "" {
|
||||
return errors.New("safehttp: empty host")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewClient returns an http.Client whose transport blocks non-public
|
||||
// destinations at dial time, caps redirects at 5, and re-validates each
|
||||
// redirect target's scheme. timeout is the per-request overall budget.
|
||||
func NewClient(timeout time.Duration) *http.Client {
|
||||
tr := &http.Transport{
|
||||
DialContext: safeDialContext,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 32,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
ResponseHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: tr,
|
||||
Timeout: timeout,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 5 {
|
||||
return errors.New("safehttp: stopped after 5 redirects")
|
||||
}
|
||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
||||
return fmt.Errorf("safehttp: unsupported redirect scheme %q", req.URL.Scheme)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// LimitedBody wraps r in a reader that errors once more than max bytes have
|
||||
// been read. Use to cap how much of a response body downstream parsers
|
||||
// (goquery, image.Decode) will ever see — a hostile origin streaming an
|
||||
// endless body otherwise OOMs the process.
|
||||
func LimitedBody(r io.Reader, max int64) io.Reader {
|
||||
return &limitedReader{R: r, N: max}
|
||||
}
|
||||
|
||||
type limitedReader struct {
|
||||
R io.Reader
|
||||
N int64
|
||||
}
|
||||
|
||||
func (l *limitedReader) Read(p []byte) (int, error) {
|
||||
if l.N <= 0 {
|
||||
return 0, fmt.Errorf("safehttp: response body exceeded cap")
|
||||
}
|
||||
if int64(len(p)) > l.N {
|
||||
p = p[:l.N]
|
||||
}
|
||||
n, err := l.R.Read(p)
|
||||
l.N -= int64(n)
|
||||
return n, err
|
||||
}
|
||||
6
main.go
6
main.go
@@ -406,8 +406,8 @@ func setupScheduledJobs(
|
||||
}
|
||||
})
|
||||
|
||||
// WOTD post at 08:00
|
||||
if strings.ToLower(os.Getenv("DISABLE_WOTD_POST")) != "true" {
|
||||
// WOTD post at 08:00 (disabled by default; opt in via ENABLE_WOTD_POST=true)
|
||||
if strings.ToLower(os.Getenv("ENABLE_WOTD_POST")) == "true" {
|
||||
c.AddFunc("0 8 * * *", func() {
|
||||
slog.Info("scheduler: posting WOTD")
|
||||
for _, r := range rooms {
|
||||
@@ -415,7 +415,7 @@ func setupScheduledJobs(
|
||||
}
|
||||
})
|
||||
} else {
|
||||
slog.Info("scheduler: WOTD daily post disabled via DISABLE_WOTD_POST")
|
||||
slog.Info("scheduler: WOTD daily post disabled (set ENABLE_WOTD_POST=true to enable)")
|
||||
}
|
||||
|
||||
// Game releases Monday 09:00
|
||||
|
||||
Reference in New Issue
Block a user