feat: complete node-agent pipeline, TLS proxy, billing cancel, password reset

Node-agent — full render pipeline (items 1-3):
- render-svc: ClaimedJob now includes aep_download_url (presigned MinIO GET,
  2h TTL, path=templates/{original_project_id}/template.aep)
- render-svc: POST /v1/internal/render/jobs/:id/output-upload-url
  allocates Export row + returns presigned MinIO PUT URL + export_id
- render-svc: db.CreateExportForJob() inserts export row with 30-day retention
- render-svc: InternalHandler now owns minio client (templatesBucket + exportsBucket)
  MINIO_TEMPLATES_BUCKET env var (default flatrender-templates)
- node-agent: runner/download.go — DownloadFile() + UploadFile() (stdlib only)
- node-agent: client.GetOutputUploadURL() + ClaimedJob.AEPDownloadURL field
- node-agent: runJob() full flow: download AEP → render → get upload URL →
  PUT output to MinIO → Complete(export_id)
  All steps are non-fatal with fallback (AEP miss → mock, upload fail → no export)

TLS reverse proxy (item 15):
- Caddyfile: three virtual hosts (DOMAIN, API_DOMAIN, STORAGE_DOMAIN)
  auto-TLS via Let's Encrypt; security headers; 512MB upload limit on API
- docker-compose.v2.yml: caddy:2-alpine service, ports 80/443/443udp,
  caddy_data + caddy_config volumes; env vars DOMAIN/API_DOMAIN/STORAGE_DOMAIN/ACME_EMAIL
- .env.v2.example: new Caddy + MINIO_TEMPLATES_BUCKET entries

Billing portal (item 5):
- Identity: POST /v1/users/me/plan/cancel — sets cancelled_at, auto_renew=false
  (access continues to expiry); 404 when no active plan
- POST /api/billing/cancel — frontend proxy, validates auth
- GET /api/billing/portal — redirects to /dashboard/settings?tab=billing
- SettingsBilling: "Cancel plan" button with confirm dialog + optimistic UI,
  "Change plan" button; becomes "use client" component

Password reset UI (item 7):
- POST /api/auth/password-reset — proxies /v1/auth/password/reset/request
  (always 200, anti-enumeration)
- POST /api/auth/password-reset-confirm — proxies /v1/auth/password/reset/confirm
- AuthPageContent: "Forgot password?" link on sign-in tab opens 2-step reset flow
  (email → OTP+new-password) without leaving the auth page

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-06-01 16:41:13 +03:30
parent 12773e125a
commit bcc69f0a2e
19 changed files with 767 additions and 72 deletions
@@ -0,0 +1,29 @@
import { NextResponse } from "next/server";
import { gatewayFetch } from "@/lib/api/gateway";
export const dynamic = "force-dynamic";
/** POST /api/auth/password-reset-confirm — confirm reset with OTP + new password */
export async function POST(request: Request) {
let body: unknown;
try { body = await request.json(); } catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const { email, otp, new_password } = body as { email?: string; otp?: string; new_password?: string };
if (!email || !otp || !new_password) {
return NextResponse.json({ error: "email, otp, and new_password are required" }, { status: 400 });
}
const res = await gatewayFetch("/v1/auth/password/reset/confirm", {
method: "POST",
body: JSON.stringify({ email, otp, new_password }),
});
const data = await res.json().catch(() => null) as { message?: string } | null;
if (!res.ok) {
return NextResponse.json(
{ error: data?.message ?? "Invalid or expired code" },
{ status: res.status }
);
}
return NextResponse.json({ ok: true });
}
+24
View File
@@ -0,0 +1,24 @@
import { NextResponse } from "next/server";
import { gatewayFetch } from "@/lib/api/gateway";
export const dynamic = "force-dynamic";
/** POST /api/auth/password-reset — request a password reset OTP email */
export async function POST(request: Request) {
let body: unknown;
try { body = await request.json(); } catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const { email } = body as { email?: string };
if (!email) return NextResponse.json({ error: "email required" }, { status: 400 });
const res = await gatewayFetch("/v1/auth/password/reset/request", {
method: "POST",
body: JSON.stringify({ email }),
});
// Always return 200 to avoid user enumeration
if (!res.ok && res.status !== 404) {
return NextResponse.json({ error: "Request failed" }, { status: 500 });
}
return NextResponse.json({ ok: true });
}
+32
View File
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
import { gatewayUrl } from "@/lib/api/gateway";
import { getAccessToken } from "@/lib/auth/session";
export const runtime = "nodejs";
/** POST /api/billing/cancel — cancel the current active plan. */
export async function POST() {
const token = await getAccessToken();
if (!token) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const res = await fetch(gatewayUrl("/v1/users/me/plan/cancel"), {
method: "POST",
cache: "no-store",
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
});
if (!res.ok) {
const err = (await res.json().catch(() => null)) as { error?: string } | null;
return NextResponse.json(
{ error: err?.error ?? "Failed to cancel plan" },
{ status: res.status }
);
}
return NextResponse.json({ ok: true });
}
+14
View File
@@ -0,0 +1,14 @@
import { redirect } from "next/navigation";
export const runtime = "nodejs";
/**
* GET /api/billing/portal
*
* In the Stripe era this redirected to a Stripe-hosted portal.
* With V2 (ZarinPal / SnapPay) the portal is in-app — redirect to the
* billing tab in settings.
*/
export async function GET() {
redirect("/dashboard/settings?tab=billing");
}
+179 -40
View File
@@ -13,6 +13,7 @@ import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
type AuthTab = "sign-in" | "sign-up";
type AuthView = "main" | "forgot-password" | "reset-confirm";
/** Only allow same-origin relative redirects to avoid open-redirect issues. */
function safeNext(next: string | null): string {
@@ -29,11 +30,17 @@ export function AuthPageContent() {
searchParams.get("tab") === "sign-up" ? "sign-up" : "sign-in";
const [activeTab, setActiveTab] = useState<AuthTab>(initialTab);
const [view, setView] = useState<AuthView>("main");
const [authLoading, setAuthLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [formMessage, setFormMessage] = useState<string | null>(null);
// Forgot-password state
const [resetEmail, setResetEmail] = useState("");
const [resetOtp, setResetOtp] = useState("");
const [resetNewPassword, setResetNewPassword] = useState("");
const {
register,
handleSubmit,
@@ -64,9 +71,7 @@ export function AuthPageContent() {
checkSession().then((redirected) => {
if (mounted && !redirected) setAuthLoading(false);
});
return () => {
mounted = false;
};
return () => { mounted = false; };
}, [checkSession]);
const handleTabChange = (tab: AuthTab) => {
@@ -76,13 +81,22 @@ export function AuthPageContent() {
reset();
};
const goBack = () => {
setView("main");
setFormError(null);
setFormMessage(null);
setResetEmail("");
setResetOtp("");
setResetNewPassword("");
};
// ── Main sign-in / sign-up submit ──────────────────────────────────────────
const onSubmit = async (values: AuthFormValues) => {
setSubmitting(true);
setFormError(null);
setFormMessage(null);
const endpoint =
activeTab === "sign-in" ? "/api/auth/login" : "/api/auth/register";
const endpoint = activeTab === "sign-in" ? "/api/auth/login" : "/api/auth/register";
try {
const res = await fetch(endpoint, {
@@ -98,7 +112,6 @@ export function AuthPageContent() {
return;
}
// Registered but not auto-logged-in (verification gate) — prompt sign-in.
if (data?.registered && !data?.user) {
setFormMessage(
data.verificationRequired
@@ -111,7 +124,6 @@ export function AuthPageContent() {
return;
}
// Logged in — cookies are set; refresh server components and go.
router.replace(nextPath);
router.refresh();
} catch {
@@ -120,6 +132,54 @@ export function AuthPageContent() {
}
};
// ── Forgot password — step 1: request OTP ─────────────────────────────────
const handleForgotRequest = async (e: React.FormEvent) => {
e.preventDefault();
if (!resetEmail) return;
setSubmitting(true);
setFormError(null);
try {
await fetch("/api/auth/password-reset", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: resetEmail }),
});
// Always succeed (anti-enumeration)
setView("reset-confirm");
setFormMessage("If that email is registered, we sent a reset code.");
} catch {
setFormError("Network error. Please try again.");
} finally {
setSubmitting(false);
}
};
// ── Forgot password — step 2: confirm OTP + new password ──────────────────
const handleResetConfirm = async (e: React.FormEvent) => {
e.preventDefault();
if (!resetOtp || !resetNewPassword) return;
setSubmitting(true);
setFormError(null);
try {
const res = await fetch("/api/auth/password-reset-confirm", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: resetEmail, otp: resetOtp, new_password: resetNewPassword }),
});
const data = await res.json().catch(() => null) as { error?: string } | null;
if (!res.ok) {
setFormError(data?.error ?? "Invalid or expired code.");
} else {
setFormMessage("Password updated. You can now sign in.");
goBack();
}
} catch {
setFormError("Network error. Please try again.");
} finally {
setSubmitting(false);
}
};
if (authLoading) {
return (
<div className="flex min-h-[calc(100vh-4rem)] items-center justify-center py-20">
@@ -128,6 +188,96 @@ export function AuthPageContent() {
);
}
// ── Forgot password views ──────────────────────────────────────────────────
if (view === "forgot-password" || view === "reset-confirm") {
return (
<div className="mx-auto w-full max-w-md px-4 py-12 sm:py-16">
<div className="text-center">
<h1 className="font-heading text-2xl font-bold text-neutral-900">
{view === "forgot-password" ? "Reset your password" : "Enter reset code"}
</h1>
<p className="mt-2 text-sm text-neutral-600">
{view === "forgot-password"
? "We'll send a one-time code to your email."
: `Check your email for the code sent to ${resetEmail}`}
</p>
</div>
<div className="mt-8 rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
{view === "forgot-password" ? (
<form onSubmit={handleForgotRequest} className="space-y-4" noValidate>
<div>
<label htmlFor="reset-email" className="block text-sm font-medium text-neutral-700">
Email address
</label>
<input
id="reset-email"
type="email"
value={resetEmail}
onChange={(e) => setResetEmail(e.target.value)}
disabled={submitting}
required
className="mt-1.5 w-full rounded-lg border border-gray-100 bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 disabled:opacity-50"
/>
</div>
{formError && <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>}
<Button type="submit" className="w-full" disabled={submitting || !resetEmail}>
{submitting && <Loader2 className="h-4 w-4 animate-spin" />}
Send reset code
</Button>
</form>
) : (
<form onSubmit={handleResetConfirm} className="space-y-4" noValidate>
<div>
<label htmlFor="reset-otp" className="block text-sm font-medium text-neutral-700">
Reset code
</label>
<input
id="reset-otp"
type="text"
inputMode="numeric"
value={resetOtp}
onChange={(e) => setResetOtp(e.target.value)}
disabled={submitting}
required
placeholder="6-digit code"
className="mt-1.5 w-full rounded-lg border border-gray-100 bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 disabled:opacity-50"
/>
</div>
<div>
<label htmlFor="new-password" className="block text-sm font-medium text-neutral-700">
New password
</label>
<input
id="new-password"
type="password"
autoComplete="new-password"
value={resetNewPassword}
onChange={(e) => setResetNewPassword(e.target.value)}
disabled={submitting}
required
minLength={8}
className="mt-1.5 w-full rounded-lg border border-gray-100 bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 disabled:opacity-50"
/>
</div>
{formError && <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>}
{formMessage && <p className="rounded-lg bg-primary-50 px-3 py-2 text-sm text-primary-700">{formMessage}</p>}
<Button type="submit" className="w-full" disabled={submitting || !resetOtp || !resetNewPassword}>
{submitting && <Loader2 className="h-4 w-4 animate-spin" />}
Set new password
</Button>
</form>
)}
</div>
<button type="button" onClick={goBack} className="mt-4 block w-full text-center text-sm text-neutral-500 hover:text-neutral-700 transition-colors">
Back to sign in
</button>
</div>
);
}
// ── Main sign-in / sign-up view ────────────────────────────────────────────
return (
<div className="mx-auto w-full max-w-md px-4 py-12 sm:py-16">
<div className="text-center">
@@ -162,10 +312,7 @@ export function AuthPageContent() {
<div className="mt-6 rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
<div>
<label
htmlFor="email"
className="block text-sm font-medium text-neutral-700"
>
<label htmlFor="email" className="block text-sm font-medium text-neutral-700">
Email
</label>
<input
@@ -185,18 +332,24 @@ export function AuthPageContent() {
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-neutral-700"
>
Password
</label>
<div className="flex items-center justify-between">
<label htmlFor="password" className="block text-sm font-medium text-neutral-700">
Password
</label>
{activeTab === "sign-in" && (
<button
type="button"
onClick={() => { setView("forgot-password"); setFormError(null); setFormMessage(null); }}
className="text-xs text-primary-600 hover:underline focus-visible:outline-none"
>
Forgot password?
</button>
)}
</div>
<input
id="password"
type="password"
autoComplete={
activeTab === "sign-in" ? "current-password" : "new-password"
}
autoComplete={activeTab === "sign-in" ? "current-password" : "new-password"}
disabled={submitting}
className={cn(
"mt-1.5 w-full rounded-lg border bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-2 disabled:opacity-50",
@@ -205,28 +358,19 @@ export function AuthPageContent() {
{...register("password")}
/>
{errors.password && (
<p className="mt-1.5 text-xs text-red-600">
{errors.password.message}
</p>
<p className="mt-1.5 text-xs text-red-600">{errors.password.message}</p>
)}
</div>
{formError && (
<p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
{formError}
</p>
<p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>
)}
{formMessage && (
<p className="rounded-lg bg-primary-50 px-3 py-2 text-sm text-primary-700">
{formMessage}
</p>
<p className="rounded-lg bg-primary-50 px-3 py-2 text-sm text-primary-700">{formMessage}</p>
)}
<Button type="submit" className="w-full" disabled={submitting}>
{submitting ? (
<Loader2 className="h-4 w-4 animate-spin" aria-hidden />
) : null}
{submitting ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : null}
{activeTab === "sign-in" ? "Sign In" : "Create Account"}
</Button>
</form>
@@ -234,14 +378,9 @@ export function AuthPageContent() {
<p className="mt-6 text-center text-xs text-neutral-500">
By continuing, you agree to our{" "}
<Link href="/terms" className="text-primary-600 hover:underline">
Terms
</Link>{" "}
<Link href="/terms" className="text-primary-600 hover:underline">Terms</Link>{" "}
and{" "}
<Link href="/privacy" className="text-primary-600 hover:underline">
Privacy Policy
</Link>
.
<Link href="/privacy" className="text-primary-600 hover:underline">Privacy Policy</Link>.
</p>
</div>
);
@@ -1,5 +1,9 @@
import { CreditCard, ExternalLink, Zap } from "lucide-react";
"use client";
import { useState } from "react";
import { CreditCard, Loader2, Zap } from "lucide-react";
import { apiFetch } from "@/lib/api/fetch";
import type { PlanId } from "@/lib/plans";
interface SettingsBillingProps {
@@ -26,6 +30,28 @@ const PLAN_FEATURES: Record<PlanId, string[]> = {
export function SettingsBilling({ plan }: SettingsBillingProps) {
const isPaid = plan !== "free";
const [cancelling, setCancelling] = useState(false);
const [cancelled, setCancelled] = useState(false);
const [cancelError, setCancelError] = useState<string | null>(null);
const handleCancel = async () => {
if (!confirm("Cancel your plan? You'll keep access until the current period ends.")) return;
setCancelling(true);
setCancelError(null);
try {
const res = await apiFetch("/api/billing/cancel", { method: "POST" });
if (!res.ok) {
const data = (await res.json().catch(() => null)) as { error?: string } | null;
setCancelError(data?.error ?? "Failed to cancel plan. Please try again.");
} else {
setCancelled(true);
}
} catch {
setCancelError("Network error. Please try again.");
} finally {
setCancelling(false);
}
};
return (
<div className="rounded-xl border border-gray-100 bg-white p-6">
@@ -44,21 +70,12 @@ export function SettingsBilling({ plan }: SettingsBillingProps) {
<div className="flex items-center gap-2">
<p className="font-heading text-lg font-bold text-neutral-900">{PLAN_LABELS[plan]}</p>
<span className={`rounded-full px-2 py-0.5 text-xs font-semibold ${PLAN_COLORS[plan]}`}>
{isPaid ? "Active" : "Free tier"}
{cancelled ? "Cancels at period end" : isPaid ? "Active" : "Free tier"}
</span>
</div>
</div>
</div>
{isPaid ? (
<a
href="/api/billing/portal"
className="inline-flex items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-neutral-700 transition-colors hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
>
<CreditCard className="h-4 w-4" aria-hidden />
Manage billing
<ExternalLink className="h-3 w-3" aria-hidden />
</a>
) : (
{!isPaid && (
<a
href="/#pricing"
className="inline-flex items-center gap-1.5 rounded-lg bg-primary-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-primary-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
@@ -80,6 +97,40 @@ export function SettingsBilling({ plan }: SettingsBillingProps) {
</ul>
</div>
{/* Paid plan actions */}
{isPaid && !cancelled && (
<div className="mt-4 flex items-center gap-3">
<a
href="/#pricing"
className="inline-flex items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-neutral-700 transition-colors hover:bg-neutral-50"
>
<CreditCard className="h-4 w-4" aria-hidden />
Change plan
</a>
<button
type="button"
onClick={handleCancel}
disabled={cancelling}
className="inline-flex items-center gap-1.5 rounded-lg border border-red-200 px-3 py-1.5 text-sm font-medium text-red-600 transition-colors hover:bg-red-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
{cancelling ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
{cancelling ? "Cancelling…" : "Cancel plan"}
</button>
</div>
)}
{cancelError && (
<p className="mt-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
{cancelError}
</p>
)}
{cancelled && (
<p className="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
Your plan has been cancelled. You&apos;ll keep access until the end of your billing period.
</p>
)}
{!isPaid && (
<p className="mt-4 text-xs text-neutral-400">
Upgrade to unlock unlimited projects, 4K export, and premium templates.