chore: sync in-progress work across marketing, admin, API and tests

Snapshot of uncommitted work that had accumulated in the tree alongside
the Turnstile changes:

- marketing pages, SEO helpers (lib/seo.ts, lib/marketing/) and
  structured data
- admin billing actions and a per-user portfolio view, plus an admin
  error boundary
- rate limiting (lib/rate-limit.ts) applied across the /api/v1 surface
- CSP and proxy adjustments, accounting/webhook lib updates
- Playwright config and an e2e/unit test suite
- next bumped to ^16.3.4 with the lockfile regenerated
- generated AGENTS.md / CLAUDE.md

Authored by other sessions working in this tree; committed here so the
Turnstile work could be pushed without leaving the tree dirty.
Typecheck passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Leon Serfaty
2026-09-05 16:27:16 -04:00
co-authored by Claude Opus 5
parent 8f90347659
commit 1d02598786
71 changed files with 3641 additions and 819 deletions
+139 -4
View File
@@ -13,6 +13,13 @@ import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import { profiles, user as userTable } from "@/lib/db/schema"
import { executeAccountDeletion } from "@/lib/gdpr/delete"
import {
changePlanInStripe,
cancelSubscription,
resumeSubscription,
refundCharge,
} from "@/lib/admin/billing"
import type { Plan } from "@/types"
// ── gate ────────────────────────────────────────────────────────────────────
// Every server action re-verifies the caller is an admin. NEVER skip — these
@@ -26,24 +33,152 @@ async function guard() {
const planSchema = z.enum(["starter", "pro", "landlord", "lifetime"])
// ── change plan ─────────────────────────────────────────────────────────────
export async function changeUserPlan(userId: string, plan: string) {
// TWO DISTINCT OPERATIONS, deliberately not merged:
//
// "comp" — grant the entitlement in our database only. Stripe is untouched,
// so the user is billed exactly as before. This is the right choice
// for a free upgrade, a support gesture, or a user with no
// subscription at all.
// "stripe" — actually move their Stripe subscription (prorated), then mirror
// it locally. This CHARGES OR CREDITS REAL MONEY.
//
// Before this split, the only behaviour was "comp" while the UI called it
// "change plan" — so an admin granting Pro left the customer on their old
// Stripe subscription, silently desyncing entitlement from billing.
export async function changeUserPlan(
userId: string,
plan: string,
mode: "comp" | "stripe" = "comp",
interval: "month" | "year" = "month"
) {
const a = await guard()
const nextPlan = planSchema.parse(plan)
const existing = await db.query.profiles.findFirst({ where: eq(profiles.id, userId) })
const oldPlan = existing?.plan ?? null
if (mode === "stripe") {
const result = await changePlanInStripe(userId, nextPlan as Plan, interval)
if (!result.ok) return { ok: false as const, error: result.error }
await logAdminAction({
adminId: a.user.id,
action: "plan_change_stripe",
targetUserId: userId,
metadata: { from: oldPlan, to: nextPlan, interval, detail: result.detail },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: result.detail }
}
// Comp: entitlement only. Recorded as such so the audit trail distinguishes a
// deliberate free grant from a paid upgrade.
await db.update(profiles).set({ plan: nextPlan }).where(eq(profiles.id, userId))
await logAdminAction({
adminId: a.user.id,
action: "plan_change",
targetUserId: userId,
metadata: { from: oldPlan, to: nextPlan },
metadata: { from: oldPlan, to: nextPlan, mode: "comp", billingUnchanged: true },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true }
return {
ok: true as const,
detail: `Plan set to ${nextPlan} as a comp. Stripe billing was NOT changed.`,
}
}
// ── subscription lifecycle ──────────────────────────────────────────────────
export async function cancelUserSubscription(userId: string, immediate = false) {
const a = await guard()
const result = await cancelSubscription(userId, immediate)
if (!result.ok) return { ok: false as const, error: result.error }
await logAdminAction({
adminId: a.user.id,
action: "cancel_subscription",
targetUserId: userId,
metadata: { immediate, detail: result.detail },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: result.detail }
}
export async function resumeUserSubscription(userId: string) {
const a = await guard()
const result = await resumeSubscription(userId)
if (!result.ok) return { ok: false as const, error: result.error }
await logAdminAction({
adminId: a.user.id,
action: "resume_subscription",
targetUserId: userId,
metadata: { detail: result.detail },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: result.detail }
}
// ── refunds ─────────────────────────────────────────────────────────────────
// `amountCents` omitted refunds everything still outstanding on the charge. The
// charge is verified to belong to this user inside refundCharge().
export async function refundUserCharge(
userId: string,
chargeId: string,
amountCents?: number,
reason?: "duplicate" | "fraudulent" | "requested_by_customer"
) {
const a = await guard()
const result = await refundCharge(userId, chargeId, amountCents, reason)
if (!result.ok) return { ok: false as const, error: result.error }
await logAdminAction({
adminId: a.user.id,
action: "refund",
targetUserId: userId,
metadata: {
chargeId,
refundId: result.data.refundId,
amountCents: result.data.amount,
reason: reason ?? null,
},
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: result.detail }
}
// ── admin role management ───────────────────────────────────────────────────
// Promotes/demotes via the Better Auth admin plugin, which writes `user.role`.
// This replaces the previous situation where the ONLY way to create an admin was
// editing ADMIN_USER_IDS in env and redeploying.
//
// Self-demotion is blocked: an admin removing their own last access would need a
// redeploy to undo, and ADMIN_USER_IDS remains the break-glass path.
export async function setUserRole(userId: string, role: "admin" | "user") {
const a = await guard()
if (userId === a.user.id) {
throw new Error("You cannot change your own role. Ask another admin.")
}
await auth.api.setRole({
body: { userId, role },
headers: await headers(),
})
await logAdminAction({
adminId: a.user.id,
action: "set_role",
targetUserId: userId,
metadata: { role },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: role === "admin" ? "User promoted to admin." : "Admin access revoked." }
}
// ── ban ─────────────────────────────────────────────────────────────────────
@@ -132,7 +267,7 @@ export async function markEmailVerified(userId: string) {
await logAdminAction({
adminId: a.user.id,
action: "resend_verification",
action: "mark_email_verified",
targetUserId: userId,
metadata: { markedVerified: true },
})