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 <noreply@anthropic.com>
This commit is contained in:
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
// Renders an embedded NocoDB view or Metabase dashboard inside 0pt's mono chrome.
|
||||
// The parent passes a server-generated SIGNED URL (docs/08) so the customer never
|
||||
// sees a separate login. No raw credentials reach the client.
|
||||
export function EmbeddedView({
|
||||
src,
|
||||
title,
|
||||
height = 720,
|
||||
}: {
|
||||
src: string | null;
|
||||
title: string;
|
||||
height?: number;
|
||||
}) {
|
||||
return (
|
||||
<div className="border border-border bg-background">
|
||||
<div className="flex items-center justify-between border-b border-border px-4 py-2.5">
|
||||
<span className="font-mono text-[11px] uppercase tracking-[0.12em] text-muted-foreground">{title}</span>
|
||||
<span className="inline-block h-1.5 w-1.5" style={{ backgroundColor: "var(--prov-3)" }} />
|
||||
</div>
|
||||
{src ? (
|
||||
<iframe
|
||||
src={src}
|
||||
title={title}
|
||||
className="w-full"
|
||||
style={{ height, border: "0" }}
|
||||
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center px-6 py-20 text-center">
|
||||
<p className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground">
|
||||
Vyn aktiveras vid leverans.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
// Lightweight signed-session scaffold (HMAC-SHA256 via Web Crypto, no deps).
|
||||
// Production auth = Auth.js + Postgres adapter + OAuth (docs/02) — wired once the
|
||||
// database is provisioned. This provides the session shape + a guarded dev login.
|
||||
const enc = new TextEncoder();
|
||||
export const SESSION_COOKIE = "0pt_session";
|
||||
|
||||
function b64url(buf: ArrayBuffer | Uint8Array): string {
|
||||
const b = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
|
||||
let s = "";
|
||||
for (const x of b) s += String.fromCharCode(x);
|
||||
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
}
|
||||
function fromB64url(s: string): Uint8Array {
|
||||
s = s.replace(/-/g, "+").replace(/_/g, "/");
|
||||
s += "=".repeat((4 - (s.length % 4)) % 4);
|
||||
const bin = atob(s);
|
||||
const u = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);
|
||||
return u;
|
||||
}
|
||||
async function hmacKey(): Promise<CryptoKey> {
|
||||
return crypto.subtle.importKey("raw", enc.encode(process.env.AUTH_SECRET ?? ""), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
||||
}
|
||||
|
||||
export async function signSession(payload: Record<string, unknown>): Promise<string> {
|
||||
const body = b64url(enc.encode(JSON.stringify(payload)));
|
||||
const sig = await crypto.subtle.sign("HMAC", await hmacKey(), enc.encode(body));
|
||||
return `${body}.${b64url(sig)}`;
|
||||
}
|
||||
|
||||
export async function verifySession(token: string | undefined | null): Promise<Record<string, unknown> | null> {
|
||||
if (!token || !process.env.AUTH_SECRET) return null;
|
||||
const [body, sig] = token.split(".");
|
||||
if (!body || !sig) return null;
|
||||
const ok = await crypto.subtle.verify("HMAC", await hmacKey(), fromB64url(sig), enc.encode(body));
|
||||
if (!ok) return null;
|
||||
try {
|
||||
return JSON.parse(new TextDecoder().decode(fromB64url(body)));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Bridge from the Vercel edge (Next route handlers) to the FastAPI data engine
|
||||
// (services/api) running on the VPS. When ENGINE_URL is set, the edge defers to
|
||||
// the engine as the single source of truth; otherwise it computes locally.
|
||||
export function hasEngine(): boolean {
|
||||
return Boolean(process.env.ENGINE_URL);
|
||||
}
|
||||
|
||||
export async function engineFetch(path: string, init?: RequestInit): Promise<Response | null> {
|
||||
const base = process.env.ENGINE_URL;
|
||||
if (!base) return null;
|
||||
try {
|
||||
return await fetch(`${base}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Internal-Token": process.env.INTERNAL_TOKEN ?? "",
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
cache: "no-store",
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import Stripe from "stripe";
|
||||
|
||||
// Lazy, env-guarded Stripe client. Returns null when STRIPE_SECRET_KEY is unset
|
||||
// so the app builds/runs without keys; payment routes 501 until configured.
|
||||
let _stripe: Stripe | null = null;
|
||||
|
||||
export function getStripe(): Stripe | null {
|
||||
const key = process.env.STRIPE_SECRET_KEY;
|
||||
if (!key) return null;
|
||||
if (!_stripe) _stripe = new Stripe(key);
|
||||
return _stripe;
|
||||
}
|
||||
@@ -56,6 +56,7 @@
|
||||
"react-resizable-panels": "^2.1.7",
|
||||
"recharts": "2.15.4",
|
||||
"sonner": "^1.7.4",
|
||||
"stripe": "^22.2.3",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vaul": "^1.1.2",
|
||||
|
||||
Generated
+16
@@ -149,6 +149,9 @@ importers:
|
||||
sonner:
|
||||
specifier: ^1.7.4
|
||||
version: 1.7.4(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
|
||||
stripe:
|
||||
specifier: ^22.2.3
|
||||
version: 22.2.3(@types/node@22.20.0)
|
||||
tailwind-merge:
|
||||
specifier: ^3.3.1
|
||||
version: 3.6.0
|
||||
@@ -1672,6 +1675,15 @@ packages:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
stripe@22.2.3:
|
||||
resolution: {integrity: sha512-9lrggvLtjO4Ef5WXH4t50ckHJcJgTD72xFB+KJgZCSszAH9zMV1BqU6PwmWbRLdcdX7LK6PbErBapiGK7pIb+g==}
|
||||
engines: {node: '>=18'}
|
||||
peerDependencies:
|
||||
'@types/node': '>=18'
|
||||
peerDependenciesMeta:
|
||||
'@types/node':
|
||||
optional: true
|
||||
|
||||
styled-jsx@5.1.6:
|
||||
resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
@@ -3141,6 +3153,10 @@ snapshots:
|
||||
|
||||
source-map-js@1.2.1: {}
|
||||
|
||||
stripe@22.2.3(@types/node@22.20.0):
|
||||
optionalDependencies:
|
||||
'@types/node': 22.20.0
|
||||
|
||||
styled-jsx@5.1.6(react@19.2.0):
|
||||
dependencies:
|
||||
client-only: 0.0.1
|
||||
|
||||
Reference in New Issue
Block a user