chore(billing): remove the Stripe rail, which was never configured anywhere (#508)

STRIPE_SECRET_KEY and the seven other STRIPE_* vars appear zero times outside
src/ and zero times in .env.example, so isStripeReady() could only ever return
false. Three API routes, a checkout route, a tier grid and a "Manage
subscription" button were all gated on it and permanently unreachable.

Confirmed empty in production before touching the schema:

    select count(*) filter (where stripe_customer_id    is not null),
           count(*) filter (where stripe_subscription_id is not null),
           count(*) from users;
    →  0 | 0 | 7

So this removes no data and, more to the point, changes nothing a user sees:
every code path already fell through to the branch below it.

WHAT STAYS. Plans are real and untouched. They are granted through the
OrangeCat/Bitcoin rail (/api/orangecat/entitlement -> recordOcBillingGrant),
with the expiry cron reverting a lapsed pass to free. The pricing CTA cascade
loses only its unreachable middle step: free -> TBA -> [stripe] -> BTC ->
start-free.

WHAT WAS ACTIVELY WRONG. Because isStripeReady() was false, the one part of
Billing that DID render was a notice telling the reader to "add
STRIPE_SECRET_KEY and price IDs" — an environment variable shown to a person
who does not deploy the app and could not act on it. That is the same mistake
NotificationsPill's comment already calls out. Billing now states the plan and
links to /pricing.

Removed: lib/stripe.ts, api/stripe/{checkout,portal,webhook}, api/checkout/
[plan], getUserByStripeCustomerId, two user columns (migration 0063), two
entries from the user-client-view redaction lists, the api/stripe/webhook entry
in proxy.ts's public matcher, the stripe npm dependency, and the smoke/auth
probes for routes that no longer exist.

BillingSettings drops "use client" — with the handlers gone it holds no state,
no effect and no search-param read.

Two mentions deliberately KEPT because they are not the rail: the placeholder
prose describing what a user might build ("Simple dashboard, automated
reminders, Stripe payments…") and the demo project's stack string.

pnpm run verify green. 28 files, 519 deletions.


Claude-Session: https://claude.ai/code/session_01UvjGNAS9CMfEGNW26tUR4P

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
CatoandClaude Opus 5 authored and GitHub committed 2026-09-05 17:04:53 +00:00
1 parent dae266e002
commit 81bf2041be
30 files changed
+8901 -519

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
ALTER TABLE "users" DROP CONSTRAINT "users_stripe_customer_id_unique";--> statement-breakpoint
ALTER TABLE "users" DROP CONSTRAINT "users_stripe_subscription_id_unique";--> statement-breakpoint
ALTER TABLE "users" DROP COLUMN "stripe_customer_id";--> statement-breakpoint
ALTER TABLE "users" DROP COLUMN "stripe_subscription_id";
File diff suppressed because it is too large. Load diff
+7
View File
@@ -435,6 +435,13 @@
"when": 1788426696563,
"tag": "0062_vengeful_lockjaw",
"breakpoints": true
},
{
"idx": 63,
"version": "7",
"when": 1788626716800,
"tag": "0063_rainy_mattie_franklin",
"breakpoints": true
}
]
}
-1
View File
@@ -137,7 +137,6 @@
"react": "19.2.8",
"react-dom": "19.2.8",
"shadcn": "^4.19.0",
"stripe": "^22.6.0",
"tailwind-merge": "^3.6.0",
"tw-animate-css": "^1.4.0",
"web-push": "^3.6.7",
-16
View File
@@ -110,9 +110,6 @@ importers:
shadcn:
specifier: ^4.19.0
version: 4.19.0(supports-color@8.1.1)(typescript@6.0.3)
stripe:
specifier: ^22.6.0
version: 22.6.0(@types/node@26.4.0)
tailwind-merge:
specifier: ^3.6.0
version: 3.6.0
@@ -4495,15 +4492,6 @@ packages:
resolution: {integrity: sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==}
engines: {node: '>=18'}
stripe@22.6.0:
resolution: {integrity: sha512-Ezk+WYEEwX2DLxFrKfb6coznlCMZvCaCYMNPXNHFSZkBIEzF5Hgm7RLb38q/0h9Ol5jsUJGJRorvhzAvckgfhw==}
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'}
@@ -9056,10 +9044,6 @@ snapshots:
strip-final-newline@4.0.0: {}
stripe@22.6.0(@types/node@26.4.0):
optionalDependencies:
'@types/node': 26.4.0
styled-jsx@5.1.6(@babel/core@7.29.7(supports-color@8.1.1))(react@19.2.8):
dependencies:
client-only: 0.0.1
-4
View File
@@ -160,10 +160,6 @@ for route in "${AUTH_API_ROUTES[@]}"; do
check_route "$route" 0 "$route" 1
done
# Routes that may return 503 when optional integrations (Stripe) are not configured.
# 401 (no session) or 503 (not configured) both prove the route isn't crashing.
check_route "/api/stripe/portal" 0 "/api/stripe/portal" 1 "503"
# Invitation token routes are excluded from the auth middleware so unauthenticated
# users can accept invites. A bogus token must return 404 — if it returns 401 the
# middleware exclusion regressed and new users can no longer accept invitations.
+1 -4
View File
@@ -38,8 +38,6 @@ const userRow = {
orangecatActorId: null,
plan: "pro",
planStatus: "active",
stripeCustomerId: "cus_123",
stripeSubscriptionId: "sub_456",
planExpiresAt: null,
privateZonePinSetAt: new Date("2026-01-01"),
fleetSettings: { a: 1 },
@@ -59,11 +57,10 @@ for (const field of Object.keys(USER_WITHHELD_FIELDS)) {
ok(!serialized.includes("bcrypt$secret"), "serialized export does not contain the password hash");
ok(!serialized.includes("scrypt$pin"), "serialized export does not contain the PIN hash");
// Billing ids: withheld from the export specifically.
// Fields withheld from the export specifically.
for (const field of USER_EXPORT_OMITTED_FIELDS) {
ok(!(field in exported), `${field} omitted from export`);
}
ok(!serialized.includes("cus_123"), "serialized export does not contain the Stripe customer id");
// Everything else the owner may see must survive — an export that quietly drops
// data fails its purpose (right of access) as surely as one that leaks.
-2
View File
@@ -54,8 +54,6 @@ const GUARDS = [
"getWidgetTokenByToken", // fcw_* write-only widget token
// Signed webhooks from other services
"WEBHOOK_SECRET",
"stripe-signature",
"constructEvent",
] as const;
/**
-19
View File
@@ -1381,25 +1381,6 @@ async function main(): Promise<void> {
}),
);
// Stripe portal — configured or 503
probes.push(
await probe(cookieHeader, "/api/stripe/portal", { expectStatus: [200, 303, 307, 503] }),
);
const webhookRes = await fetch(`${BASE}/api/stripe/webhook`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
signal: AbortSignal.timeout(15_000),
});
probes.push({
route: "CH04 POST /api/stripe/webhook (invalid sig)",
method: "POST",
status: webhookRes.status,
ok: [400, 503].includes(webhookRes.status),
note: webhookRes.status === 503 ? "Stripe not configured" : "signature rejected",
});
const metaIssues: string[] = [];
for (const [name, meta] of Object.entries(SUBSCRIPTION_META)) {
try {
-1
View File
@@ -30,7 +30,6 @@ const FULL_ROW_SOURCES = [
"getUserByUsername",
"getUserByEmail",
"getDefaultUser",
"getUserByStripeCustomerId",
"getUserByOrangeCatActorId",
"createUser",
"createInitialUser",
+1 -1
View File
@@ -161,7 +161,7 @@ import { join } from "node:path";
const proxySource = readFileSync(join(__dirname, "../../src/proxy.ts"), "utf8");
const matcherExclusion = proxySource.match(/"\/\(\(\?!(.+)\)\.\+\)"/)?.[1];
assert.ok(matcherExclusion, "proxy.ts matcher exclusion pattern not found");
for (const receiver of ["api/orangecat/", "api/solon/", "api/stripe/webhook"]) {
for (const receiver of ["api/orangecat/", "api/solon/"]) {
assert.ok(
matcherExclusion.split("|").includes(receiver.replace(/\./g, "\\.")) ||
matcherExclusion.split("|").includes(receiver),
-2
View File
@@ -76,8 +76,6 @@ const row: User = {
orangecatActorId: null,
plan: "free",
planStatus: null,
stripeCustomerId: null,
stripeSubscriptionId: null,
planExpiresAt: null,
privateZonePinHash: "deadbeef.cafe",
privateZonePinSetAt: new Date("2026-02-01T00:00:00Z"),
-3
View File
@@ -6,7 +6,6 @@ import { getUserById } from "@/db/queries/users";
import { getUserPreferences } from "@/db/queries/user-preferences";
import { SettingsTabs } from "@/components/settings/SettingsTabs";
import { PageLayout } from "@/components/ui/page-layout";
import { isStripeReady } from "@/lib/stripe";
import { getEnabledAuthProviders } from "@/lib/auth-providers";
import { getProjectLimit, isUnlimitedProjects } from "@/lib/plan";
import { ROUTES } from "@/config/auth";
@@ -39,8 +38,6 @@ export default async function SettingsPage() {
hasPassword: !!user.passwordHash,
plan: user.plan,
planStatus: user.planStatus ?? null,
stripeReady: isStripeReady(),
hasSubscription: !!user.stripeSubscriptionId,
}}
userPrefs={
userPrefs ?? {
-75
View File
@@ -1,75 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { getSessionUserId } from "@/lib/session";
import { stripe, STRIPE_PRICE_IDS, isStripeReady } from "@/lib/stripe";
import { getUserById, updateUserBilling } from "@/db/queries/users";
import { ROUTES } from "@/config/auth";
const PAID_PLANS = ["personal", "pro", "team"] as const;
type PaidPlan = (typeof PAID_PLANS)[number];
function isPaidPlan(value: string): value is PaidPlan {
return (PAID_PLANS as readonly string[]).includes(value);
}
export async function GET(req: NextRequest, { params }: { params: Promise<{ plan: string }> }) {
const { plan } = await params;
const userId = await getSessionUserId();
if (!userId) {
const signInUrl = new URL(ROUTES.SIGN_IN, req.url);
signInUrl.searchParams.set("callbackUrl", `/api/checkout/${plan}`);
return NextResponse.redirect(signInUrl);
}
if (!isPaidPlan(plan)) {
return NextResponse.redirect(new URL("/settings", req.url));
}
if (!isStripeReady() || !stripe) {
return NextResponse.redirect(new URL("/settings?billing=not-configured", req.url));
}
const user = await getUserById(userId);
if (!user) return NextResponse.redirect(new URL(ROUTES.SIGN_IN, req.url));
// Already on this plan
if (user.plan === plan && user.planStatus === "active") {
return NextResponse.redirect(new URL("/settings?billing=already-active", req.url));
}
const priceId = STRIPE_PRICE_IDS[plan].annual;
if (!priceId) {
return NextResponse.redirect(new URL("/settings?billing=not-configured", req.url));
}
let customerId = user.stripeCustomerId ?? undefined;
if (!customerId) {
const customer = await stripe.customers.create({
email: user.email ?? undefined,
name: user.name ?? undefined,
metadata: { fleetcrownUserId: userId },
});
customerId = customer.id;
await updateUserBilling(userId, { stripeCustomerId: customerId });
}
const origin = new URL(req.url).origin;
const checkoutSession = await stripe.checkout.sessions.create({
mode: "subscription",
customer: customerId,
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${origin}/settings?billing=success`,
cancel_url: `${origin}/settings?billing=canceled`,
metadata: { fleetcrownUserId: userId, plan },
subscription_data: {
metadata: { fleetcrownUserId: userId, plan },
},
});
if (!checkoutSession.url) {
return NextResponse.redirect(new URL("/settings?billing=error", req.url));
}
return NextResponse.redirect(checkoutSession.url);
}
-63
View File
@@ -1,63 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { stripe, STRIPE_PRICE_IDS, isStripeReady } from "@/lib/stripe";
import { getSessionUserId } from "@/lib/session";
import { getUserById, updateUserBilling } from "@/db/queries/users";
import { readJsonBody, z } from "@/lib/api/route-helpers";
import { LOCAL_DEV_URL } from "@/config/brand";
const CheckoutBody = z.object({
plan: z.enum(["personal", "pro", "team"] as const),
billing: z.enum(["monthly", "annual"]).default("annual"),
});
export async function POST(req: NextRequest) {
if (!isStripeReady() || !stripe) {
return NextResponse.json({ error: "Stripe not configured" }, { status: 503 });
}
const userId = await getSessionUserId();
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const dataOrResp = await readJsonBody(req, CheckoutBody);
if (dataOrResp instanceof NextResponse) return dataOrResp;
const { plan, billing } = dataOrResp;
const priceId = STRIPE_PRICE_IDS[plan][billing];
if (!priceId) {
return NextResponse.json(
{ error: `No price configured for ${plan}/${billing}` },
{ status: 503 },
);
}
const user = await getUserById(userId);
if (!user) return NextResponse.json({ error: "User not found" }, { status: 404 });
// Retrieve or create Stripe customer
let customerId = user.stripeCustomerId ?? undefined;
if (!customerId) {
const customer = await stripe.customers.create({
email: user.email ?? undefined,
name: user.name ?? undefined,
metadata: { fleetcrownUserId: userId },
});
customerId = customer.id;
await updateUserBilling(userId, { stripeCustomerId: customerId });
}
const origin = req.headers.get("origin") ?? process.env.NEXTAUTH_URL ?? LOCAL_DEV_URL;
const session = await stripe.checkout.sessions.create({
mode: "subscription",
customer: customerId,
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${origin}/settings?billing=success`,
cancel_url: `${origin}/settings?billing=canceled`,
metadata: { fleetcrownUserId: userId, plan },
subscription_data: {
metadata: { fleetcrownUserId: userId, plan },
},
});
return NextResponse.json({ url: session.url });
}
-28
View File
@@ -1,28 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { stripe, isStripeReady } from "@/lib/stripe";
import { getSessionUserId } from "@/lib/session";
import { getUserById } from "@/db/queries/users";
import { LOCAL_DEV_URL } from "@/config/brand";
export async function GET(req: NextRequest) {
if (!isStripeReady() || !stripe) {
return NextResponse.json({ error: "Stripe not configured" }, { status: 503 });
}
const userId = await getSessionUserId();
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const user = await getUserById(userId);
if (!user?.stripeCustomerId) {
return NextResponse.json({ error: "No billing account found" }, { status: 404 });
}
const origin = req.headers.get("origin") ?? process.env.NEXTAUTH_URL ?? LOCAL_DEV_URL;
const session = await stripe.billingPortal.sessions.create({
customer: user.stripeCustomerId,
return_url: `${origin}/settings`,
});
return NextResponse.redirect(session.url);
}
-87
View File
@@ -1,87 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import { getUserByStripeCustomerId, updateUserBilling } from "@/db/queries/users";
import type { Plan, PlanStatus } from "@/db/schema/users";
import type Stripe from "stripe";
export async function POST(req: NextRequest) {
if (!stripe) return NextResponse.json({ error: "Stripe not configured" }, { status: 503 });
const body = await req.text();
const signature = req.headers.get("stripe-signature") ?? "";
const secret = process.env.STRIPE_WEBHOOK_SECRET ?? "";
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, signature, secret);
} catch {
return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
}
try {
switch (event.type) {
case "checkout.session.completed": {
const session = event.data.object as Stripe.Checkout.Session;
if (session.mode !== "subscription") break;
const customerId = session.customer as string;
const plan = (session.metadata?.plan ?? "personal") as Plan;
const user = await getUserByStripeCustomerId(customerId);
if (user) {
await updateUserBilling(user.id, {
plan,
planStatus: "active",
stripeSubscriptionId: session.subscription as string,
});
}
break;
}
case "customer.subscription.updated": {
const sub = event.data.object as Stripe.Subscription;
const customerId = sub.customer as string;
const user = await getUserByStripeCustomerId(customerId);
if (!user) break;
const rawStatus = sub.status;
const planStatus: PlanStatus | null =
rawStatus === "active"
? "active"
: rawStatus === "past_due"
? "past_due"
: rawStatus === "canceled"
? "canceled"
: null;
const plan = (sub.metadata?.plan ?? user.plan) as Plan;
await updateUserBilling(user.id, { plan, planStatus, stripeSubscriptionId: sub.id });
break;
}
case "customer.subscription.deleted": {
const sub = event.data.object as Stripe.Subscription;
const user = await getUserByStripeCustomerId(sub.customer as string);
if (user) {
await updateUserBilling(user.id, {
plan: "free",
planStatus: "canceled",
stripeSubscriptionId: null,
});
}
break;
}
default:
// Unhandled event types are silently ignored
break;
}
} catch (err) {
// Signature is already verified above; the risk here is a DB blip mid-event
// (getUserByStripeCustomerId / updateUserBilling). Don't let it surface as an
// unhandled 500 + stack — return 500 deliberately so Stripe retries this
// idempotent event later, and the user isn't left on a stale plan silently.
console.error("[stripe/webhook] handler failed:", event.type, err);
return NextResponse.json({ error: "handler failed" }, { status: 500 });
}
return NextResponse.json({ received: true });
}
+10 -12
View File
@@ -4,7 +4,6 @@ import type { Metadata } from "next";
import { auth } from "@/auth";
import { PublicSurface } from "@/components/public/PublicSurface";
import { PublicHeaderActions } from "@/components/public/PublicHeaderActions";
import { isStripeReady } from "@/lib/stripe";
import { orangeCatPayUrl } from "@/lib/oc-pay";
import { ROUTES } from "@/config/auth";
import { APP_NAME } from "@/config/brand";
@@ -22,17 +21,19 @@ export const metadata: Metadata = {
};
/**
* Public pricing. Honest about billing state: paid CTAs open Stripe checkout
* only when it's configured (isStripeReady); until then every CTA routes to
* a free signup — never a dead "Buy" button. Flips live automatically the
* moment Stripe keys land, with no code change here.
* Public pricing. Honest about billing state: a paid CTA only appears when a
* rail can actually take the money — never a dead "Buy" button.
*
* The rail is Bitcoin via OrangeCat (orangeCatPayUrl), which needs no merchant
* account. A Stripe branch used to sit ahead of it, permanently unreachable:
* isStripeReady() was false in every environment, so every visitor already got
* the path below. Removing it changed no rendered output.
*/
export default async function PricingPage() {
const session = await auth();
const signedIn = Boolean(session?.user);
const stripeReady = isStripeReady();
// Resolve each plan's CTA target for the current state (signed-in? stripe live?).
// Resolve each plan's CTA target for the current state (signed in? BTC rail live?).
function ctaFor(plan: PricingPlan): { href: string; label: string } {
if (plan.key === "free") {
return signedIn
@@ -45,11 +46,8 @@ export default async function PricingPage() {
? { href: ROUTES.APP_HOME, label: `Open ${APP_NAME}` }
: { href: ROUTES.SIGN_UP, label: "Start free" };
}
if (stripeReady) {
return { href: `/api/checkout/${plan.key}`, label: plan.cta };
}
// Stripe blocked on incorporation — but the Bitcoin/OrangeCat rail needs no
// merchant account. If this tier has an OC pass configured, offer it.
// The Bitcoin/OrangeCat rail needs no merchant account. If this tier has
// an OC pass configured, offer it.
const btc = orangeCatPayUrl(plan.key);
if (btc) {
return { href: btc, label: "Pay in Bitcoin" };
+29 -137
View File
@@ -1,9 +1,5 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { postJson } from "@/lib/api/fetch";
import { PRICING_PLANS, PRICING_CURRENCY, PRICING_BILLING_NOTE } from "@/config/plans";
import Link from "next/link";
import { PRICING_BILLING_NOTE } from "@/config/plans";
import type { Plan } from "@/db/schema/users";
const PLAN_LABEL: Record<Plan, string> = {
@@ -16,151 +12,47 @@ const PLAN_LABEL: Record<Plan, string> = {
type Props = {
plan: Plan;
planStatus: string | null;
stripeReady: boolean;
hasSubscription: boolean;
};
const BILLING_MESSAGES: Record<string, { text: string; type: "success" | "info" | "error" }> = {
success: { text: "Subscription activated — welcome to the plan!", type: "success" },
canceled: { text: "Checkout canceled — no charge was made.", type: "info" },
error: { text: "Something went wrong during checkout. Please try again.", type: "error" },
"not-configured": { text: "Payment integration is not yet configured.", type: "info" },
"already-active": { text: "You're already on this plan.", type: "info" },
};
export function BillingSettings({ plan, planStatus, stripeReady, hasSubscription }: Props) {
const searchParams = useSearchParams();
const router = useRouter();
const pathname = usePathname();
const didProcess = useRef(false);
const [loading, setLoading] = useState<string | null>(null);
const [error, setError] = useState("");
// The ?billing= outcome is known at mount (we land here from a Stripe
// redirect), so the banner is seeded via the lazy initializer instead of a
// setState inside the effect — the effect below only strips the query param.
const [notice] = useState<{ text: string; type: "success" | "info" | "error" } | null>(() => {
const billingParam = searchParams.get("billing");
return billingParam ? (BILLING_MESSAGES[billingParam] ?? null) : null;
});
useEffect(() => {
if (didProcess.current) return;
if (!searchParams.get("billing")) return;
didProcess.current = true;
// Remove the query param so a page refresh doesn't re-show it
const params = new URLSearchParams(searchParams.toString());
params.delete("billing");
const newUrl = params.size > 0 ? `${pathname}?${params}` : pathname;
router.replace(newUrl, { scroll: false });
}, [pathname, router, searchParams]);
async function handleUpgrade(targetPlan: "personal" | "pro" | "team") {
setError("");
setLoading(targetPlan);
try {
const res = await postJson("/api/stripe/checkout", { plan: targetPlan, billing: "annual" });
const data = await res.json();
if (!res.ok) {
setError(data.error ?? "Failed to start checkout.");
return;
}
// location.assign() (a method call, not a mutation of a captured value)
// — same navigation, and Stripe Checkout is an external URL.
if (data.url) window.location.assign(data.url);
} catch {
setError("Something went wrong.");
} finally {
setLoading(null);
}
}
function handleManage() {
window.location.href = "/api/stripe/portal";
}
/**
* What plan you are on, and where to change it.
*
* This used to be a Stripe checkout surface: a tier grid, an upgrade handler
* posting to /api/stripe/checkout, a "Manage subscription" button opening the
* billing portal, and — because `isStripeReady()` was false in every
* environment — a permanent notice telling the reader to "add STRIPE_SECRET_KEY
* and price IDs". None of it could ever run, and the one part that DID render
* asked a person who does not deploy the app to set an environment variable.
*
* Stripe is gone (nothing was ever configured, no user row ever held a customer
* id). Plans themselves are real and stay: they are granted through the
* OrangeCat/Bitcoin rail at /api/orangecat/entitlement, with the expiry cron
* reverting a lapsed pass to free. So this section states the plan and points
* at the page that explains the tiers, rather than offering a checkout that
* does not exist.
*
* No "use client": with the handlers gone there is no state, no effect and no
* search-param read left in it.
*/
export function BillingSettings({ plan, planStatus }: Props) {
return (
<section className="ui-settings-section">
{notice && (
<p
className={`rounded-lg px-4 py-3 text-sm ${
notice.type === "success"
? "bg-status-positive/10 text-status-positive"
: notice.type === "error"
? "bg-status-negative/10 text-status-negative"
: "bg-surface-raised text-text-secondary"
}`}
>
{notice.text}
</p>
)}
<div className="flex items-start justify-between gap-4">
<div>
<h2 className="font-medium text-text-primary">Billing</h2>
<p className="text-sm text-text-tertiary">
Current plan:{" "}
<span className="text-text-secondary font-medium">{PLAN_LABEL[plan]}</span>
<span className="font-medium text-text-secondary">{PLAN_LABEL[plan]}</span>
{planStatus === "past_due" && (
<span className="ml-2 text-status-warning text-xs">· payment past due</span>
<span className="ml-2 text-xs text-status-warning">· payment past due</span>
)}
</p>
</div>
{hasSubscription && stripeReady && (
<button onClick={handleManage} className="ui-btn-secondary shrink-0 text-sm">
Manage subscription
</button>
)}
<Link href="/pricing" className="ui-btn-secondary shrink-0 text-sm">
See plans
</Link>
</div>
{!stripeReady && (
<p className="text-sm text-text-muted bg-surface-raised rounded-lg px-4 py-3">
Payment integration is not yet configured. Add{" "}
<code className="text-accent-text text-xs">STRIPE_SECRET_KEY</code> and price IDs to
enable subscriptions.
</p>
)}
{stripeReady && plan === "free" && (
<>
<div className="grid gap-3 sm:grid-cols-3">
{/* Tiers with a null price are to-be-announced — not sellable yet. */}
{PRICING_PLANS.filter((tier) => tier.key !== "free" && tier.priceMonthly !== null).map(
(tier) => {
const tierPlan = tier.key as "personal" | "pro" | "team";
return (
<div
key={tier.key}
className={`ui-panel rounded-xl p-4 space-y-3 ${tier.featured ? "border-accent-primary/40" : ""}`}
>
<div>
<p className="text-xs font-semibold uppercase tracking-widest text-text-muted">
{tier.name}
</p>
<p className="text-2xl font-bold text-text-primary mt-1">
{PRICING_CURRENCY} {tier.priceMonthly}
<span className="text-sm font-normal text-text-tertiary">/mo</span>
</p>
<p className="text-xs text-text-tertiary">{tier.tagline}</p>
</div>
<button
onClick={() => handleUpgrade(tierPlan)}
disabled={!!loading}
className={
tier.featured ? "ui-btn-primary w-full" : "ui-btn-secondary w-full"
}
>
{loading === tierPlan ? "Redirecting…" : tier.cta}
</button>
</div>
);
},
)}
</div>
<p className="text-xs text-text-muted">{PRICING_BILLING_NOTE}</p>
</>
)}
{error && <p className="ui-error">{error}</p>}
<p className="text-xs text-text-muted">{PRICING_BILLING_NOTE}</p>
</section>
);
}
+1 -8
View File
@@ -29,8 +29,6 @@ type Props = {
hasPassword: boolean;
plan: Plan;
planStatus: string | null;
stripeReady: boolean;
hasSubscription: boolean;
};
userPrefs: UserPreferencesData;
projects: UserProject[];
@@ -166,12 +164,7 @@ export function SettingsTabs({
{activeTab === "team" && <TeamSettings invitations={invitations} />}
{activeTab === "billing" && (
<Suspense>
<BillingSettings
plan={user.plan}
planStatus={user.planStatus}
stripeReady={user.stripeReady}
hasSubscription={user.hasSubscription}
/>
<BillingSettings plan={user.plan} planStatus={user.planStatus} />
</Suspense>
)}
</div>
-1
View File
@@ -129,7 +129,6 @@ export const DEMO_DENIED_PREFIXES: ReadonlyArray<readonly [string, DemoDenialRea
["/api/push", "outbound"],
// — money ——————————————————————————————————————————————————————————
["/api/stripe", "billing"],
["/api/checkout", "billing"],
["/api/subscriptions", "billing"],
+1 -1
View File
@@ -16,7 +16,7 @@ export type PricingPlan = {
name: string;
/**
* CHF per month. 0 = genuinely free; null = price to be announced — the tier
* stays visible, no number is shown, and every checkout rail (Stripe and the
* stays visible, no number is shown, and the checkout rail (the
* OrangeCat Bitcoin passes) is disabled for it until a number is set.
* Mirror any change in orangecat's src/config/fleetcrown-passes.ts + re-seed.
*/
+1 -1
View File
@@ -25,7 +25,7 @@ export async function recordOcBillingGrant(
/**
* Downgrade every user whose BTC pass has lapsed → free. Returns the count.
* Only touches non-free users with an expiry in the past; Stripe subscribers
* Only touches non-free users with an expiry in the past; a plan with
* (planExpiresAt null) are untouched. Idempotent — a second run finds none.
*/
export async function downgradeExpiredPlans(now = new Date()): Promise<number> {
+1 -1
View File
@@ -11,7 +11,7 @@ import type { Plan } from "@/db/schema/users";
* If improvement loops are only honest when they touch settled money, the
* operator needs one place that sums it. Read-only; founder-scoped in the UI.
*
* "Active paid" = any non-free plan whose pass hasn't lapsed. Stripe subs carry
* "Active paid" = any non-free plan whose pass hasn't lapsed. Grants carry
* a null expiry (recurring); BTC passes carry a future expiry. The daily
* downgrade cron flips lapsed passes back to free, so a non-free row with a
* null-or-future expiry is genuinely paying right now.
+1 -11
View File
@@ -86,27 +86,17 @@ export interface UpdateUserInput {
export interface UpdateUserBillingInput {
plan?: Plan;
planStatus?: PlanStatus | null;
stripeCustomerId?: string;
stripeSubscriptionId?: string | null;
/** OrangeCat/BTC-rail pass expiry (now + period). Null clears it (e.g. the
* expiry cron reverting to free, or a Stripe sub that manages its own cycle). */
* expiry cron reverting to free). */
planExpiresAt?: Date | null;
}
export async function getUserByStripeCustomerId(stripeCustomerId: string) {
return db.query.users.findFirst({ where: eq(users.stripeCustomerId, stripeCustomerId) }) ?? null;
}
export async function updateUserBilling(id: string, patch: UpdateUserBillingInput) {
const [updated] = await db
.update(users)
.set({
...(patch.plan !== undefined && { plan: patch.plan }),
...(patch.planStatus !== undefined && { planStatus: patch.planStatus }),
...(patch.stripeCustomerId !== undefined && { stripeCustomerId: patch.stripeCustomerId }),
...(patch.stripeSubscriptionId !== undefined && {
stripeSubscriptionId: patch.stripeSubscriptionId,
}),
...(patch.planExpiresAt !== undefined && { planExpiresAt: patch.planExpiresAt }),
updatedAt: new Date(),
})
+1 -3
View File
@@ -47,12 +47,10 @@ export const users = pgTable("users", {
// Billing
plan: text("plan").$type<Plan>().default("free").notNull(),
planStatus: text("plan_status").$type<PlanStatus>(),
stripeCustomerId: text("stripe_customer_id").unique(),
stripeSubscriptionId: text("stripe_subscription_id").unique(),
// OrangeCat/Bitcoin-rail passes are time-boxed (BTC has no native recurring):
// the entitlement webhook sets this to now + period, and the
// downgrade-expired-plans cron reverts the plan to free once it passes. Null =
// no expiry (free tier, or a Stripe subscription which manages its own cycle).
// no expiry (free tier).
planExpiresAt: timestamp("plan_expires_at", { withTimezone: true }),
// Private-zone PIN — scrypt hash in `<hash>.<salt>` format. Null = no PIN
// configured for this user; the gate stays open. Each user sets / changes
+1 -1
View File
@@ -5,7 +5,7 @@ import type { Plan } from "@/db/schema/users";
*
* Each paid tier maps to an OrangeCat product/pass with a BTC price; the URL is
* that pass's OC checkout. Read from env so the "Pay in Bitcoin" CTA lights up
* the moment the OC-side passes exist — no code change (mirrors isStripeReady).
* the moment the OC-side passes exist — no code change.
* Null everywhere today because the OC passes aren't created yet.
*/
export function orangeCatPayUrl(plan: Plan): string | null {
-29
View File
@@ -1,29 +0,0 @@
import Stripe from "stripe";
import type { Plan } from "@/db/schema/users";
// Returns null when STRIPE_SECRET_KEY is not set — routes guard against this.
export const stripe: Stripe | null = process.env.STRIPE_SECRET_KEY
? new Stripe(process.env.STRIPE_SECRET_KEY)
: null;
export const STRIPE_PRICE_IDS: Record<
Exclude<Plan, "free">,
{ monthly: string; annual: string }
> = {
personal: {
monthly: process.env.STRIPE_PRICE_PERSONAL_MONTHLY ?? "",
annual: process.env.STRIPE_PRICE_PERSONAL_ANNUAL ?? "",
},
pro: {
monthly: process.env.STRIPE_PRICE_PRO_MONTHLY ?? "",
annual: process.env.STRIPE_PRICE_PRO_ANNUAL ?? "",
},
team: {
monthly: process.env.STRIPE_PRICE_TEAM_MONTHLY ?? "",
annual: process.env.STRIPE_PRICE_TEAM_ANNUAL ?? "",
},
};
export function isStripeReady(): boolean {
return !!process.env.STRIPE_SECRET_KEY && !!process.env.STRIPE_WEBHOOK_SECRET;
}
+3 -6
View File
@@ -31,8 +31,6 @@ export const USER_CLIENT_FIELDS = [
"orangecatActorId",
"plan",
"planStatus",
"stripeCustomerId",
"stripeSubscriptionId",
"planExpiresAt",
// Not the PIN itself — only whether/when one was set, which Settings shows.
"privateZonePinSetAt",
@@ -68,10 +66,9 @@ export function toClientUser(user: User): ClientUser {
* narrowing of the allow-list, never a second answer to what is secret — that
* question has one answer, USER_WITHHELD_FIELDS, and both projections inherit it.
*/
export const USER_EXPORT_OMITTED_FIELDS = [
"stripeCustomerId",
"stripeSubscriptionId",
] as const satisfies ReadonlyArray<(typeof USER_CLIENT_FIELDS)[number]>;
export const USER_EXPORT_OMITTED_FIELDS = [] as const satisfies ReadonlyArray<
(typeof USER_CLIENT_FIELDS)[number]
>;
export type ExportUser = Omit<ClientUser, (typeof USER_EXPORT_OMITTED_FIELDS)[number]>;
+1 -2
View File
@@ -51,7 +51,6 @@ export const config = {
* trailing slash keeps GET /api/invitations (list) protected
* api/share/task/ – the assignee's read + accept/decline/deliver, by token;
* the path segment keeps every other /api/share child protected
* api/stripe/webhook – Stripe webhook; verifies its own Stripe-Signature header
* api/orangecat/ – OrangeCat webhooks (entitlement, events); each verifies its own HMAC signature
* api/solon/ – Solon governance webhooks (decision.finalized); verifies its own HMAC signature
* api/newsletter – public email-capture (zod + rate-limited in-handler)
@@ -65,6 +64,6 @@ export const config = {
* import-from-local\.sh – public bash one-liner users curl-pipe into their terminal
* to scan ~/dev and POST detected repos to /api/projects/import-from-local
*/
"/((?!_next/static|_next/image|favicon\\.ico|icon\\.svg|manifest\\.json|opengraph-image|twitter-image|robots\\.txt|sitemap\\.xml|rss\\.xml|sign-in|sign-up|forgot-password|reset-password|verify-email|setup|invite|download|whitepaper|thoughts|frontier|mission|philosophy|investors|roadmap|pricing|releases|privacy|terms|license|docs|blog|changelog|support|u/|share/project/|share/task/|beacon|import-from-local\\.sh|api/auth|api/agent/install|api/agent/daemon|api/health|api/setup|api/crons|api/system|api/beacon|api/invitations/|api/share/task/|api/stripe/webhook|api/orangecat/|api/solon/|api/newsletter|api/feedback|api/widget-boot|api/widget/transcribe|widget\\.js).+)",
"/((?!_next/static|_next/image|favicon\\.ico|icon\\.svg|manifest\\.json|opengraph-image|twitter-image|robots\\.txt|sitemap\\.xml|rss\\.xml|sign-in|sign-up|forgot-password|reset-password|verify-email|setup|invite|download|whitepaper|thoughts|frontier|mission|philosophy|investors|roadmap|pricing|releases|privacy|terms|license|docs|blog|changelog|support|u/|share/project/|share/task/|beacon|import-from-local\\.sh|api/auth|api/agent/install|api/agent/daemon|api/health|api/setup|api/crons|api/system|api/beacon|api/invitations/|api/share/task/|api/orangecat/|api/solon/|api/newsletter|api/feedback|api/widget-boot|api/widget/transcribe|widget\\.js).+)",
],
};