feat(infra): payments (Stripe), auth scaffold, engine bridge, embeds, .env.example

Env-guarded so build stays green: /api/payments/[order_id]/deposit+release + /api/webhooks/stripe (lazy Stripe, 50/50 escrow, 501 until keys); /api/auth login|me|logout (HMAC signed-session scaffold, guarded dev login); lib/engine bridges edge->FastAPI (estimates defers to ENGINE_URL when set); components/embed for NocoDB/Metabase signed URLs; .env.example full inventory. tsc 0, build green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
2026-06-24 21:19:29 +02:00
co-authored by Claude Opus 4.8
parent 31128a71c8
commit ba96566c14
13 changed files with 281 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
import { NextRequest, NextResponse } from "next/server";
import { signSession, SESSION_COOKIE } from "@/lib/auth";
// POST /api/auth/login — guarded dev login (scaffold). Requires AUTH_SECRET +
// a matching DEV_LOGIN_KEY. Production replaces this with Auth.js + OAuth.
export async function POST(req: NextRequest) {
const { email, key } = await req.json().catch(() => ({ email: undefined, key: undefined }));
if (!process.env.AUTH_SECRET) {
return NextResponse.json({ error: { code: "auth_not_configured", message: "AUTH_SECRET saknas" } }, { status: 501 });
}
const devKey = process.env.DEV_LOGIN_KEY;
if (!devKey || key !== devKey) {
return NextResponse.json({ error: { code: "forbidden", message: "Dev-login kräver giltig nyckel" } }, { status: 403 });
}
if (!email) {
return NextResponse.json({ error: { code: "bad_request", message: "email krävs" } }, { status: 400 });
}
const token = await signSession({ email, iat: Date.now() });
const res = NextResponse.json({ ok: true, email });
res.cookies.set(SESSION_COOKIE, token, { httpOnly: true, sameSite: "lax", secure: true, path: "/", maxAge: 60 * 60 * 24 * 7 });
return res;
}
+9
View File
@@ -0,0 +1,9 @@
import { NextResponse } from "next/server";
import { SESSION_COOKIE } from "@/lib/auth";
// POST /api/auth/logout — clear the session cookie.
export async function POST() {
const res = NextResponse.json({ ok: true });
res.cookies.set(SESSION_COOKIE, "", { path: "/", maxAge: 0 });
return res;
}
+9
View File
@@ -0,0 +1,9 @@
import { NextRequest, NextResponse } from "next/server";
import { verifySession, SESSION_COOKIE } from "@/lib/auth";
// GET /api/auth/me — current session (or null).
export async function GET(req: NextRequest) {
const token = req.cookies.get(SESSION_COOKIE)?.value;
const session = await verifySession(token);
return NextResponse.json({ user: session ? { email: session.email } : null });
}
+5
View File
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { computeEstimate, type EntityType, type Frequency } from "@/lib/data";
import { engineFetch } from "@/lib/engine";
// POST /api/estimates (docs/04) — price/time/confidence for a configured job.
// Single source of truth for the estimate math; the configurator calls this.
@@ -11,6 +12,10 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 });
}
// Defer to the FastAPI data engine when it's running; fall back to local math.
const eng = await engineFetch("/estimates", { method: "POST", body: JSON.stringify(body) });
if (eng && eng.ok) return NextResponse.json(await eng.json());
const markets = Array.isArray(body.markets) ? (body.markets as string[]) : [];
const entity_type = (body.entity_type as EntityType) || "Bolag";
const fields = Array.isArray(body.fields) ? (body.fields as string[]) : [];
@@ -0,0 +1,35 @@
import { NextRequest, NextResponse } from "next/server";
import { getStripe } from "@/lib/stripe";
import { getOrder } from "@/lib/orders-store";
// POST /api/payments/{order_id}/deposit (docs/04) — Stripe Checkout for the 50% deposit.
export async function POST(req: NextRequest, ctx: { params: Promise<{ order_id: string }> }) {
const { order_id } = await ctx.params;
const order = await getOrder(order_id);
if (!order) return NextResponse.json({ error: { code: "not_found", message: "Order saknas" } }, { status: 404 });
const stripe = getStripe();
if (!stripe) {
return NextResponse.json(
{ error: { code: "stripe_not_configured", message: "Stripe ej konfigurerad (saknar STRIPE_SECRET_KEY)" } },
{ status: 501 },
);
}
const origin = req.nextUrl.origin;
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [{
quantity: 1,
price_data: {
currency: "sek",
unit_amount: order.deposit_ore,
product_data: { name: `0pt order ${order_id} — förskott 50 %` },
},
}],
success_url: `${origin}/order/${order_id}`,
cancel_url: `${origin}/bestall/forskott?order=${order_id}`,
metadata: { order_id, kind: "deposit" },
});
return NextResponse.json({ checkout_url: session.url });
}
@@ -0,0 +1,40 @@
import { NextRequest, NextResponse } from "next/server";
import { getStripe } from "@/lib/stripe";
import { getOrder, setStatus } from "@/lib/orders-store";
// POST /api/payments/{order_id}/release (docs/04) — charge the held 50% balance.
// Called on ACCEPT only; escrow balance is never charged before approval.
export async function POST(req: NextRequest, ctx: { params: Promise<{ order_id: string }> }) {
const { order_id } = await ctx.params;
const order = await getOrder(order_id);
if (!order) return NextResponse.json({ error: { code: "not_found", message: "Order saknas" } }, { status: 404 });
if (order.status !== "accepted") {
return NextResponse.json({ error: { code: "not_accepted", message: "Balans frigörs först vid godkänd leverans" } }, { status: 409 });
}
const stripe = getStripe();
if (!stripe) {
return NextResponse.json(
{ error: { code: "stripe_not_configured", message: "Stripe ej konfigurerad" } },
{ status: 501 },
);
}
const origin = req.nextUrl.origin;
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [{
quantity: 1,
price_data: {
currency: "sek",
unit_amount: order.balance_ore,
product_data: { name: `0pt order ${order_id} — slutbetalning 50 %` },
},
}],
success_url: `${origin}/order/${order_id}/validera`,
cancel_url: `${origin}/order/${order_id}/validera`,
metadata: { order_id, kind: "balance" },
});
await setStatus(order_id, "delivered");
return NextResponse.json({ checkout_url: session.url });
}
+27
View File
@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from "next/server";
import { getStripe } from "@/lib/stripe";
import { setStatus } from "@/lib/orders-store";
// POST /api/webhooks/stripe (docs/04) — verify signature, advance order status.
export async function POST(req: NextRequest) {
const stripe = getStripe();
const whSecret = process.env.STRIPE_WEBHOOK_SECRET;
const sig = req.headers.get("stripe-signature");
if (!stripe || !whSecret || !sig) {
return NextResponse.json({ received: false, reason: "not_configured" }, { status: 200 });
}
const body = await req.text();
let event;
try {
event = stripe.webhooks.constructEvent(body, sig, whSecret);
} catch {
return NextResponse.json({ error: "bad_signature" }, { status: 400 });
}
if (event.type === "checkout.session.completed") {
const s = event.data.object as { metadata?: { order_id?: string; kind?: string } };
const oid = s.metadata?.order_id;
const kind = s.metadata?.kind;
if (oid) await setStatus(oid, kind === "balance" ? "delivered" : "in_production");
}
return NextResponse.json({ received: true });
}