Files
evig/scripts/db/run-migration.sh
CatoandClaude Fable 5.1 e2c67d8aa5 chore(cleanup): dedupe migrations, blog scripts, i18n baseline; rate limiting over limitkit; no-console (#488)
* chore(db): empty the two byte-identical duplicate migrations instead of skipping one

004_ai_inventory_system.sql and 005_messaging_system.sql were 402- and
295-line copies of 004b and 005c (the originals were renamed with a suffix
in 21a6b2477, then re-added unsuffixed in e920eb231). Both names are
recorded in production's schema_migrations — backfilled by
083_backfill_schema_migrations.sql, which lists all four filenames — so
neither file can be deleted without a restore-from-backup audit reading it
as a vanished migration.

The bodies are gone; each file keeps a comment with the history. Applied
as a no-op, so the MIGRATION_SUPERSEDED skip list in migration-order.sh
(which existed only because 005's unguarded CREATE TRIGGERs aborted a
second application) is no longer needed and is removed from all three
runners' comments. The deploy script was not run; evidence is read from
the migration files and the runner sources only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* chore(scripts): delete the Strapi-era blog and docker setup scripts

scripts/setup-blog.sh and scripts/start-blog.sh were byte-identical copies
of tools/development/setup-blog.sh and start-blog.sh; all four drove a
Strapi blog that no longer exists (the blog is DB-backed, no compose file
has a Strapi service, and .gitignore's /strapi entry pointed at nothing).
tools/development/docker-setup.sh was the wrapper around the same stack.
Nothing in package.json, CI or the docs invoked any of them; the one
prose mention in docs/guides/system-integration.md now says so.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* fix(i18n): baseline states each missing key once, not once per locale

scripts/baselines/i18n-missing.json listed the same ~90 keys under each of
six locales — six near-identical blocks that jscpd flagged as the repo's
largest clone group. The generator now writes one entry per key naming
the locales it is missing from; the audit converts back to the per-locale
view it compares against, so its regression semantics are unchanged
(0 new, 0 fixed on regeneration).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(security): one rate limiter over limitkit, lockout kept apart

Two hand-rolled limiters served ~20 routes each: an lru-cache counter in
lib/security/rate-limit.ts and a bare-Map window in lib/auth/rate-limiter.ts.
Both are replaced by the fleet's limitkit (SHARED.md); evig keeps only its
limit VALUES and the call shapes routes were written against, so no route
changed beyond its import. The auth file's account-lockout half — a
per-account, DB-backed state, not rate limiting — lives on as
lib/auth/lockout.ts. AUTH_CONFIG.rateLimit moves next to the other limits
as AUTH_RATE_LIMITS; lru-cache is dropped.

Behaviour that changed underneath, deliberately: sliding windows instead
of a TTL that restarted on every hit, refusals no longer count (a hammered
key recovers when the attacker stops), the client IP is the last
X-Forwarded-For hop (the one Caddy wrote), and the store is bounded. The
login limit was "5 per 15 min then a 30-min block"; limitkit does not
model a punitive block, so it is 5 per sliding 30 minutes — the same
steady-state admission.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* chore(lint): no-console in src/, and a useMounted hook for the SSR mount flag

App code logs through src/lib/logger.ts, the one console sink. ESLint now
enforces no-console (warn/error allowed) across src/, with the logger and
tests carved out; scripts/ are CLIs whose stdout is their output and stay
uncovered.

Four components each carried a useState(false)+useEffect(setMounted(true))
pair with a react-hooks/set-state-in-effect exception. They share one
useMounted() built on useSyncExternalStore, which needs no effect and no
exception.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 22:42:11 -07:00

134 lines
4.7 KiB
Bash
Executable File

#!/bin/bash
# ============================================================================
# RevampIT Database Migration Runner
#
# Applies every .sql file under scripts/db/migrations/ exactly once, tracked
# in the `schema_migrations` table (created by 075).
#
# Behavior:
# - Files are applied in version-sorted order (`sort -V`), so 075 runs
# after 074, 100 runs after 99, etc. Pre-075 hyphenated/underscored
# names happen to sort the same way under -V as they did under plain
# `sort`; the bootstrap in 075 records them all so re-runs skip them.
# - Each file runs inside `BEGIN; ... COMMIT;` so a partial failure
# rolls back cleanly.
# - On success the filename is INSERTed into schema_migrations. On
# re-invocation, already-recorded files are skipped.
#
# Targets the LOCAL development PostgreSQL (Docker on localhost:5433 by
# default). To apply migrations to production (Hetzner), run via psql against
# $DATABASE_URL on the box — schema_migrations tracks applied files there too.
# ============================================================================
set -euo pipefail
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}RevampIT Database Migration${NC}"
echo -e "${GREEN}================================${NC}"
# Load .env if present
if [ -f ".env" ]; then
export $(grep -v '^#' .env | xargs)
fi
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5433}"
DB_NAME="${DB_NAME:-revampit_cms}"
DB_USER="${DB_USER:-postgres}"
DB_PASSWORD="${DB_PASSWORD:-postgres}"
MIGRATIONS_DIR="scripts/db/migrations"
echo ""
echo -e "${YELLOW}Configuration:${NC}"
echo " Host: $DB_HOST"
echo " Port: $DB_PORT"
echo " Database: $DB_NAME"
echo " User: $DB_USER"
echo " Migrations dir: $MIGRATIONS_DIR"
echo ""
psql_exec() {
PGPASSWORD="$DB_PASSWORD" psql -v ON_ERROR_STOP=1 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" "$@"
}
psql_query() {
PGPASSWORD="$DB_PASSWORD" psql -At -v ON_ERROR_STOP=1 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "$1"
}
echo -e "${YELLOW}Checking database connection...${NC}"
if ! psql_exec -c '\q' 2>/dev/null; then
echo -e "${RED}Error: Cannot connect to database${NC}"
echo "Make sure PostgreSQL is running: docker compose up -d db"
exit 1
fi
echo -e "${GREEN}✓ Database connection successful${NC}"
echo ""
# Ensure the tracking table exists. The canonical CREATE TABLE lives in
# migration 075; this is a defensive bootstrap so the first run on a
# pre-075 database (or a fresh database where 075 itself hasn't been
# applied yet) doesn't fail when we query schema_migrations below.
psql_exec -c "CREATE TABLE IF NOT EXISTS schema_migrations (filename TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW());" >/dev/null
# Pull the set of already-applied filenames so we can skip them. Use a
# temp file so the shell loop can do an O(1) lookup per candidate file.
APPLIED_FILE=$(mktemp)
trap 'rm -f "$APPLIED_FILE"' EXIT
psql_query "SELECT filename FROM schema_migrations" > "$APPLIED_FILE"
is_applied() {
grep -Fxq "$1" "$APPLIED_FILE"
}
echo -e "${YELLOW}Running migrations (version-sorted, skipping already-applied)...${NC}"
COUNT_APPLIED=0
COUNT_SKIPPED=0
# Ordering is shared with the CI replay and the production deploy — see
# scripts/db/migration-order.sh. Before that file, each runner sorted for
# itself and they disagreed, so a from-scratch local DB died on a duplicate
# that CI had been skipping for months.
# shellcheck source=scripts/db/migration-order.sh
source "$(dirname "${BASH_SOURCE[0]}")/migration-order.sh"
for path in $(migration_files); do
name=$(basename "$path")
if is_applied "$name"; then
COUNT_SKIPPED=$((COUNT_SKIPPED + 1))
continue
fi
echo -e "${YELLOW}→ $name${NC}"
# Wrap each migration in BEGIN/COMMIT so a partial failure rolls back.
# The INSERT into schema_migrations runs in the same transaction so a
# crash mid-file doesn't leave the runner thinking the file applied.
if PGPASSWORD="$DB_PASSWORD" psql -v ON_ERROR_STOP=1 \
-h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" <<EOSQL
BEGIN;
\i $path
INSERT INTO schema_migrations (filename) VALUES ('$name')
ON CONFLICT (filename) DO NOTHING;
COMMIT;
EOSQL
then
COUNT_APPLIED=$((COUNT_APPLIED + 1))
else
echo -e "${RED}✗ $name failed — rolled back${NC}"
exit 1
fi
done
echo ""
echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}✓ Migration run complete${NC}"
echo -e "${GREEN} applied: $COUNT_APPLIED · skipped (already applied): $COUNT_SKIPPED${NC}"
echo -e "${GREEN}================================${NC}"