diff --git a/app/api/billing/checkout/route.ts b/app/api/billing/checkout/route.ts
new file mode 100644
index 0000000..60c657a
--- /dev/null
+++ b/app/api/billing/checkout/route.ts
@@ -0,0 +1,80 @@
+import { NextRequest } from 'next/server';
+import { auth } from '@/lib/auth';
+import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
+import {
+ DEFAULT_TRIAL_PERIOD_DAYS,
+ getOrCreateStripeCustomerId,
+ getStripeCheckoutState,
+} from '@/lib/billing';
+import { rateLimit } from '@/lib/rate-limit';
+import { getStripe, getStripePriceId, isStripeConfigured } from '@/lib/stripe';
+import { isTrustedSameOriginRequest } from '@/lib/request-origin';
+
+function getAppOrigin(request: NextRequest) {
+ if (isTrustedSameOriginRequest(request)) {
+ const origin = request.headers.get('origin');
+ if (origin) {
+ return new URL(origin).origin;
+ }
+ }
+
+ return request.nextUrl.origin;
+}
+
+export async function POST(request: NextRequest) {
+ try {
+ const limited = await rateLimit(request, 'mutate');
+ if (limited) return limited;
+
+ if (!isTrustedSameOriginRequest(request)) {
+ return apiErrors.forbidden('Invalid request origin');
+ }
+
+ const session = await auth();
+ if (!session?.user?.id) {
+ return apiErrors.unauthorized();
+ }
+
+ if (!isStripeConfigured()) {
+ return apiErrors.internalError('Stripe billing is not configured');
+ }
+
+ const checkoutState = await getStripeCheckoutState(session.user.id);
+ if (checkoutState.hasActiveSubscription) {
+ return apiErrors.badRequest('An active subscription already exists for this account');
+ }
+
+ const stripe = getStripe();
+ const priceId = getStripePriceId();
+ const customerId = await getOrCreateStripeCustomerId(session.user.id);
+ const appOrigin = getAppOrigin(request);
+
+ const checkoutSession = await stripe.checkout.sessions.create({
+ mode: 'subscription',
+ customer: customerId,
+ line_items: [{ price: priceId, quantity: 1 }],
+ allow_promotion_codes: true,
+ success_url: `${appOrigin}/settings?billing=success`,
+ cancel_url: `${appOrigin}/settings?billing=canceled`,
+ metadata: {
+ userId: session.user.id,
+ },
+ subscription_data: {
+ metadata: {
+ userId: session.user.id,
+ },
+ ...(checkoutState.isTrialEligible ? { trial_period_days: DEFAULT_TRIAL_PERIOD_DAYS } : {}),
+ },
+ });
+
+ if (!checkoutSession.url) {
+ throw new Error('Stripe did not return a checkout URL');
+ }
+
+ const response = successResponse({ url: checkoutSession.url });
+ return withCacheControl(response, 'private, no-store');
+ } catch (error) {
+ console.error('Error creating Stripe checkout session:', error);
+ return apiErrors.internalError('Failed to start checkout');
+ }
+}
diff --git a/app/api/billing/portal/route.ts b/app/api/billing/portal/route.ts
new file mode 100644
index 0000000..8e230d7
--- /dev/null
+++ b/app/api/billing/portal/route.ts
@@ -0,0 +1,55 @@
+import { NextRequest } from 'next/server';
+import { auth } from '@/lib/auth';
+import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
+import { getBillingOverview } from '@/lib/billing';
+import { rateLimit } from '@/lib/rate-limit';
+import { getStripe, isStripeConfigured } from '@/lib/stripe';
+import { isTrustedSameOriginRequest } from '@/lib/request-origin';
+
+function getAppOrigin(request: NextRequest) {
+ if (isTrustedSameOriginRequest(request)) {
+ const origin = request.headers.get('origin');
+ if (origin) {
+ return new URL(origin).origin;
+ }
+ }
+
+ return request.nextUrl.origin;
+}
+
+export async function POST(request: NextRequest) {
+ try {
+ const limited = await rateLimit(request, 'mutate');
+ if (limited) return limited;
+
+ if (!isTrustedSameOriginRequest(request)) {
+ return apiErrors.forbidden('Invalid request origin');
+ }
+
+ const session = await auth();
+ if (!session?.user?.id) {
+ return apiErrors.unauthorized();
+ }
+
+ if (!isStripeConfigured()) {
+ return apiErrors.internalError('Stripe billing is not configured');
+ }
+
+ const billing = await getBillingOverview(session.user.id);
+ if (!billing.subscription.stripeCustomerId) {
+ return apiErrors.badRequest('No Stripe customer exists for this account');
+ }
+
+ const stripe = getStripe();
+ const portalSession = await stripe.billingPortal.sessions.create({
+ customer: billing.subscription.stripeCustomerId,
+ return_url: `${getAppOrigin(request)}/settings`,
+ });
+
+ const response = successResponse({ url: portalSession.url });
+ return withCacheControl(response, 'private, no-store');
+ } catch (error) {
+ console.error('Error creating Stripe portal session:', error);
+ return apiErrors.internalError('Failed to open billing portal');
+ }
+}
diff --git a/app/api/billing/route.ts b/app/api/billing/route.ts
new file mode 100644
index 0000000..636ab3b
--- /dev/null
+++ b/app/api/billing/route.ts
@@ -0,0 +1,40 @@
+import { auth } from '@/lib/auth';
+import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
+import { getBillingOverview } from '@/lib/billing';
+import { isStripeConfigured } from '@/lib/stripe';
+
+export async function GET() {
+ try {
+ const session = await auth();
+ if (!session?.user?.id) {
+ return apiErrors.unauthorized();
+ }
+
+ const billing = await getBillingOverview(session.user.id);
+ const response = successResponse({
+ isConfigured: isStripeConfigured(),
+ checkoutAvailable: isStripeConfigured() && !billing.subscription.hasActiveSubscription,
+ portalAvailable: isStripeConfigured() && Boolean(billing.subscription.stripeCustomerId),
+ subscription: {
+ status: billing.subscription.status,
+ label: billing.subscription.label,
+ hasActiveSubscription: billing.subscription.hasActiveSubscription,
+ hasActiveTrial: billing.subscription.hasActiveTrial,
+ hasBillingAccess: billing.subscription.hasBillingAccess,
+ priceId: billing.subscription.stripePriceId,
+ currentPeriodEnd: billing.subscription.currentPeriodEnd?.toISOString() ?? null,
+ cancelAtPeriodEnd: billing.subscription.cancelAtPeriodEnd ?? false,
+ cancelAt: billing.subscription.cancelAt?.toISOString() ?? null,
+ trialEndsAt: billing.subscription.trialEndsAt?.toISOString() ?? null,
+ billingAccessEndedAt: billing.subscription.billingAccessEndedAt?.toISOString() ?? null,
+ storageCleanupEligibleAt: billing.subscription.storageCleanupEligibleAt?.toISOString() ?? null,
+ },
+ workspaceCreation: billing.workspaceCreation,
+ });
+
+ return withCacheControl(response, 'private, no-store');
+ } catch (error) {
+ console.error('Error fetching billing overview:', error);
+ return apiErrors.internalError('Failed to fetch billing overview');
+ }
+}
diff --git a/app/api/projects/[projectId]/members/[memberId]/route.ts b/app/api/projects/[projectId]/members/[memberId]/route.ts
index 8510338..292b86d 100644
--- a/app/api/projects/[projectId]/members/[memberId]/route.ts
+++ b/app/api/projects/[projectId]/members/[memberId]/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
-import { auth } from '@/lib/auth';
+import { auth, checkProjectAccess } from '@/lib/auth';
import { ProjectMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
@@ -29,10 +29,11 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
+ const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const isOwner = project.ownerId === session.user.id;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
- if (!isOwner && !isAdmin) {
+ if (!access.canEdit || (!isOwner && !isAdmin)) {
return apiErrors.forbidden('Access denied');
}
@@ -44,15 +45,24 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
}
- const member = await db.projectMember.update({
- where: { id: memberId },
+ const member = await db.projectMember.findFirst({
+ where: { id: memberId, projectId },
+ select: { id: true },
+ });
+
+ if (!member) {
+ return apiErrors.notFound('Member');
+ }
+
+ const updatedMember = await db.projectMember.update({
+ where: { id: member.id },
data: { role: role as ProjectMemberRole },
include: {
user: { select: { id: true, name: true, image: true } },
},
});
- const response = successResponse(member);
+ const response = successResponse(updatedMember);
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error updating member role:', error);
@@ -82,11 +92,13 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
+ const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const isOwner = project.ownerId === session.user.id;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
- const memberToRemove = await db.projectMember.findUnique({
- where: { id: memberId },
+ const memberToRemove = await db.projectMember.findFirst({
+ where: { id: memberId, projectId },
+ select: { id: true, userId: true },
});
if (!memberToRemove) {
@@ -95,11 +107,11 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
const isSelf = memberToRemove.userId === session.user.id;
- if (!isOwner && !isAdmin && !isSelf) {
+ if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
return apiErrors.forbidden('Access denied');
}
- await db.projectMember.delete({ where: { id: memberId } });
+ await db.projectMember.delete({ where: { id: memberToRemove.id } });
const response = successResponse({ message: 'Member removed' });
return withCacheControl(response, 'private, no-store');
diff --git a/app/api/projects/[projectId]/members/invitations/[invitationId]/route.ts b/app/api/projects/[projectId]/members/invitations/[invitationId]/route.ts
index 6dd0dcb..f2f4dd6 100644
--- a/app/api/projects/[projectId]/members/invitations/[invitationId]/route.ts
+++ b/app/api/projects/[projectId]/members/invitations/[invitationId]/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from 'next/server';
import { InvitationStatus, ProjectMemberRole } from '@prisma/client';
-import { auth } from '@/lib/auth';
+import { auth, checkProjectAccess } from '@/lib/auth';
import { db } from '@/lib/db';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
@@ -29,10 +29,11 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
+ const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const isOwner = project.ownerId === session.user.id;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
- if (!isOwner && !isAdmin) {
+ if (!access.canEdit || (!isOwner && !isAdmin)) {
return apiErrors.forbidden('Only project owners and admins can cancel invitations');
}
diff --git a/app/api/projects/[projectId]/members/route.ts b/app/api/projects/[projectId]/members/route.ts
index eb7bef1..d936b79 100644
--- a/app/api/projects/[projectId]/members/route.ts
+++ b/app/api/projects/[projectId]/members/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
-import { auth } from '@/lib/auth';
+import { auth, checkProjectAccess } from '@/lib/auth';
import { InvitationRole, ProjectMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
@@ -29,11 +29,12 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
+ const access = await checkProjectAccess(project, session.user.id);
const isOwner = project.ownerId === session.user.id;
const isMember = project.members.length > 0;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
- if (!isOwner && !isMember) {
+ if (!access.hasAccess || (!isOwner && !isMember)) {
return apiErrors.forbidden('Access denied');
}
@@ -105,10 +106,11 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
+ const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const isOwner = project.ownerId === session.user.id;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
- if (!isOwner && !isAdmin) {
+ if (!access.canEdit || (!isOwner && !isAdmin)) {
return apiErrors.forbidden('Only project owners and admins can invite members');
}
diff --git a/app/api/projects/route.ts b/app/api/projects/route.ts
index 1ebc8e2..06951f2 100644
--- a/app/api/projects/route.ts
+++ b/app/api/projects/route.ts
@@ -1,8 +1,9 @@
import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
-import { auth } from '@/lib/auth';
+import { auth, checkWorkspaceAccess } from '@/lib/auth';
import { ProjectVisibility } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
+import { buildBillingAccessWhereInput } from '@/lib/billing';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
import { DEFAULT_COMMENT_TAGS } from '@/lib/comment-tags';
@@ -48,10 +49,14 @@ export async function GET(request: NextRequest) {
// Also include projects in workspaces where the user is a workspace member
...(workspaceId ? [] : [{
workspace: {
+ owner: buildBillingAccessWhereInput(),
members: { some: { userId: session.user.id } },
},
}]),
],
+ workspace: {
+ owner: buildBillingAccessWhereInput(),
+ },
};
// Filter by workspace if provided
@@ -150,10 +155,12 @@ export async function POST(request: NextRequest) {
return apiErrors.notFound('Workspace');
}
- const isWsOwner = workspace.ownerId === session.user.id;
- const isWsAdmin = workspace.members[0]?.role === 'ADMIN';
+ const access = await checkWorkspaceAccess(
+ { id: workspace.id, ownerId: workspace.ownerId },
+ session.user.id
+ );
- if (!isWsOwner && !isWsAdmin) {
+ if (!access.canEdit) {
return apiErrors.forbidden('Only workspace owners and admins can create projects');
}
@@ -164,7 +171,7 @@ export async function POST(request: NextRequest) {
description: description?.trim() || null,
slug,
visibility: visibility || ProjectVisibility.PRIVATE,
- ownerId: session.user.id,
+ ownerId: workspace.ownerId,
workspaceId,
},
include: {
diff --git a/app/api/stripe/webhook/route.ts b/app/api/stripe/webhook/route.ts
new file mode 100644
index 0000000..7e118fe
--- /dev/null
+++ b/app/api/stripe/webhook/route.ts
@@ -0,0 +1,88 @@
+import { NextRequest } from 'next/server';
+import type Stripe from 'stripe';
+import {
+ markSubscriptionCanceledByCustomerId,
+ syncStripeSubscriptionToUser,
+} from '@/lib/billing';
+import { getStripe, getStripeWebhookSecret } from '@/lib/stripe';
+
+export const runtime = 'nodejs';
+
+async function handleSubscriptionDeleted(subscription: Stripe.Subscription) {
+ const customerId =
+ typeof subscription.customer === 'string'
+ ? subscription.customer
+ : subscription.customer.id;
+
+ const currentPeriodEnd =
+ 'current_period_end' in subscription && typeof subscription.current_period_end === 'number'
+ ? new Date(subscription.current_period_end * 1000)
+ : null;
+ const endedAt =
+ 'ended_at' in subscription && typeof subscription.ended_at === 'number'
+ ? new Date(subscription.ended_at * 1000)
+ : currentPeriodEnd;
+
+ await markSubscriptionCanceledByCustomerId(customerId, {
+ currentPeriodEnd,
+ endedAt,
+ });
+}
+
+export async function POST(request: NextRequest) {
+ const signature = request.headers.get('stripe-signature');
+ if (!signature) {
+ return new Response('Missing Stripe signature', { status: 400 });
+ }
+
+ let event: Stripe.Event;
+
+ try {
+ const stripe = getStripe();
+ const body = await request.text();
+ event = stripe.webhooks.constructEvent(body, signature, getStripeWebhookSecret());
+ } catch (error) {
+ console.error('Failed to verify Stripe webhook:', error);
+ return new Response('Invalid webhook signature', { status: 400 });
+ }
+
+ try {
+ const stripe = getStripe();
+
+ switch (event.type) {
+ case 'checkout.session.completed': {
+ const session = event.data.object as Stripe.Checkout.Session;
+ if (session.mode === 'subscription' && session.subscription) {
+ const subscriptionId =
+ typeof session.subscription === 'string'
+ ? session.subscription
+ : session.subscription.id;
+ const subscription = await stripe.subscriptions.retrieve(subscriptionId);
+ await syncStripeSubscriptionToUser(subscription);
+ }
+ break;
+ }
+ case 'customer.subscription.created':
+ case 'customer.subscription.updated': {
+ const subscription = event.data.object as Stripe.Subscription;
+ await syncStripeSubscriptionToUser(subscription);
+ break;
+ }
+ case 'customer.subscription.deleted': {
+ const subscription = event.data.object as Stripe.Subscription;
+ await handleSubscriptionDeleted(subscription);
+ break;
+ }
+ default:
+ break;
+ }
+
+ return new Response(JSON.stringify({ received: true }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ } catch (error) {
+ console.error('Failed to process Stripe webhook:', error);
+ return new Response('Webhook processing failed', { status: 500 });
+ }
+}
diff --git a/app/api/workspaces/[workspaceId]/members/[memberId]/route.ts b/app/api/workspaces/[workspaceId]/members/[memberId]/route.ts
index 9ac0423..203e44d 100644
--- a/app/api/workspaces/[workspaceId]/members/[memberId]/route.ts
+++ b/app/api/workspaces/[workspaceId]/members/[memberId]/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
-import { auth } from '@/lib/auth';
+import { auth, checkWorkspaceAccess } from '@/lib/auth';
import { WorkspaceMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
@@ -30,10 +30,14 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Workspace');
}
+ const access = await checkWorkspaceAccess(
+ { id: workspace.id, ownerId: workspace.ownerId },
+ session.user.id
+ );
const isOwner = workspace.ownerId === session.user.id;
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
- if (!isOwner && !isAdmin) {
+ if (!access.canEdit || (!isOwner && !isAdmin)) {
return apiErrors.forbidden('Access denied');
}
@@ -45,15 +49,24 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
}
- const member = await db.workspaceMember.update({
- where: { id: memberId },
+ const member = await db.workspaceMember.findFirst({
+ where: { id: memberId, workspaceId },
+ select: { id: true },
+ });
+
+ if (!member) {
+ return apiErrors.notFound('Member');
+ }
+
+ const updatedMember = await db.workspaceMember.update({
+ where: { id: member.id },
data: { role: role as WorkspaceMemberRole },
include: {
user: { select: { id: true, name: true, image: true } },
},
});
- const response = successResponse(member);
+ const response = successResponse(updatedMember);
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error updating member role:', error);
@@ -83,12 +96,17 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Workspace');
}
+ const access = await checkWorkspaceAccess(
+ { id: workspace.id, ownerId: workspace.ownerId },
+ session.user.id
+ );
const isOwner = workspace.ownerId === session.user.id;
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
// Users can remove themselves, admins/owners can remove anyone
- const memberToRemove = await db.workspaceMember.findUnique({
- where: { id: memberId },
+ const memberToRemove = await db.workspaceMember.findFirst({
+ where: { id: memberId, workspaceId },
+ select: { id: true, userId: true },
});
if (!memberToRemove) {
@@ -97,11 +115,32 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
const isSelf = memberToRemove.userId === session.user.id;
- if (!isOwner && !isAdmin && !isSelf) {
+ if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
return apiErrors.forbidden('Access denied');
}
- await db.workspaceMember.delete({ where: { id: memberId } });
+ await db.$transaction(async (tx) => {
+ await tx.projectMember.deleteMany({
+ where: {
+ userId: memberToRemove.userId,
+ project: {
+ workspaceId,
+ },
+ },
+ });
+
+ await tx.project.updateMany({
+ where: {
+ workspaceId,
+ ownerId: memberToRemove.userId,
+ },
+ data: {
+ ownerId: workspace.ownerId,
+ },
+ });
+
+ await tx.workspaceMember.delete({ where: { id: memberToRemove.id } });
+ });
const response = successResponse({ message: 'Member removed' });
return withCacheControl(response, 'private, no-store');
diff --git a/app/api/workspaces/[workspaceId]/members/invitations/[invitationId]/route.ts b/app/api/workspaces/[workspaceId]/members/invitations/[invitationId]/route.ts
index e512c55..3546d24 100644
--- a/app/api/workspaces/[workspaceId]/members/invitations/[invitationId]/route.ts
+++ b/app/api/workspaces/[workspaceId]/members/invitations/[invitationId]/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from 'next/server';
import { InvitationStatus, WorkspaceMemberRole } from '@prisma/client';
-import { auth } from '@/lib/auth';
+import { auth, checkWorkspaceAccess } from '@/lib/auth';
import { db } from '@/lib/db';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
@@ -29,10 +29,14 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Workspace');
}
+ const access = await checkWorkspaceAccess(
+ { id: workspace.id, ownerId: workspace.ownerId },
+ session.user.id
+ );
const isOwner = workspace.ownerId === session.user.id;
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
- if (!isOwner && !isAdmin) {
+ if (!access.canEdit || (!isOwner && !isAdmin)) {
return apiErrors.forbidden('Only workspace owners and admins can cancel invitations');
}
diff --git a/app/api/workspaces/[workspaceId]/members/route.ts b/app/api/workspaces/[workspaceId]/members/route.ts
index 965c664..10ccf61 100644
--- a/app/api/workspaces/[workspaceId]/members/route.ts
+++ b/app/api/workspaces/[workspaceId]/members/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
-import { auth } from '@/lib/auth';
+import { auth, checkWorkspaceAccess } from '@/lib/auth';
import { InvitationRole, WorkspaceMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
@@ -53,11 +53,15 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Workspace');
}
+ const access = await checkWorkspaceAccess(
+ { id: workspace.id, ownerId: workspace.ownerId },
+ session.user.id
+ );
const isOwner = workspace.ownerId === session.user.id;
const isMember = workspace.members.length > 0;
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
- if (!isOwner && !isMember) {
+ if (!access.hasAccess || (!isOwner && !isMember)) {
return apiErrors.forbidden('Access denied');
}
@@ -145,10 +149,14 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Workspace');
}
+ const access = await checkWorkspaceAccess(
+ { id: workspace.id, ownerId: workspace.ownerId },
+ session.user.id
+ );
const isOwner = workspace.ownerId === session.user.id;
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
- if (!isOwner && !isAdmin) {
+ if (!access.canEdit || (!isOwner && !isAdmin)) {
return apiErrors.forbidden('Only workspace owners and admins can invite members');
}
diff --git a/app/api/workspaces/route.ts b/app/api/workspaces/route.ts
index d5f77e7..f6b5d6a 100644
--- a/app/api/workspaces/route.ts
+++ b/app/api/workspaces/route.ts
@@ -2,6 +2,7 @@ import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { rateLimit } from '@/lib/rate-limit';
+import { buildBillingAccessWhereInput, getWorkspaceCreationEligibility } from '@/lib/billing';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
// GET /api/workspaces - List all workspaces for the authenticated user
@@ -39,8 +40,8 @@ export async function GET(request: NextRequest) {
const where = {
OR: [
- { ownerId: session.user.id },
- { members: { some: { userId: session.user.id } } },
+ { ownerId: session.user.id, owner: buildBillingAccessWhereInput() },
+ { members: { some: { userId: session.user.id } }, owner: buildBillingAccessWhereInput() },
],
};
@@ -88,6 +89,13 @@ export async function POST(request: NextRequest) {
return apiErrors.unauthorized();
}
+ const billing = await getWorkspaceCreationEligibility(session.user.id);
+ if (!billing.canCreateWorkspace) {
+ return apiErrors.forbidden(
+ billing.reason || 'Upgrade your account to create another workspace'
+ );
+ }
+
const body = await request.json();
const { name, description } = body;
diff --git a/app/invitations/accept/page.tsx b/app/invitations/accept/page.tsx
index 8ad9119..04f99c4 100644
--- a/app/invitations/accept/page.tsx
+++ b/app/invitations/accept/page.tsx
@@ -1,5 +1,6 @@
import { redirect } from 'next/navigation';
import { auth } from '@/lib/auth';
+import { db } from '@/lib/db';
import { acceptInvitationTokenForUser } from '@/lib/invitations';
interface InvitationAcceptPageProps {
@@ -23,6 +24,26 @@ export default async function InvitationAcceptPage({ searchParams }: InvitationA
redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`);
}
+ const invitation = await db.invitation.findUnique({
+ where: { token },
+ select: {
+ id: true,
+ status: true,
+ scope: true,
+ workspaceId: true,
+ projectId: true,
+ },
+ });
+
+ function redirectToInvitationTarget(inviteStatus: string) {
+ if (invitation?.scope === 'WORKSPACE' && invitation.workspaceId) {
+ redirect(`/workspaces/${invitation.workspaceId}?invite=${inviteStatus}`);
+ }
+ if (invitation?.scope === 'PROJECT' && invitation.projectId) {
+ redirect(`/projects/${invitation.projectId}?invite=${inviteStatus}`);
+ }
+ }
+
const userEmail = session.user.email?.toLowerCase().trim();
if (!userEmail) {
redirect('/dashboard?invite=invalid_email');
@@ -35,13 +56,20 @@ export default async function InvitationAcceptPage({ searchParams }: InvitationA
});
if (result === 'accepted') {
+ redirectToInvitationTarget('accepted');
redirect('/dashboard?invite=accepted');
}
if (result === 'expired') {
+ redirectToInvitationTarget('expired');
redirect('/dashboard?invite=expired');
}
if (result === 'forbidden') {
redirect('/dashboard?invite=wrong_account');
}
+
+ if (result === 'not_found' && invitation?.status === 'ACCEPTED') {
+ redirectToInvitationTarget('already_accepted');
+ }
+
redirect('/dashboard?invite=not_found');
}
diff --git a/app/onboarding/onboarding-wizard.tsx b/app/onboarding/onboarding-wizard.tsx
index 7a85bf6..d82f49c 100644
--- a/app/onboarding/onboarding-wizard.tsx
+++ b/app/onboarding/onboarding-wizard.tsx
@@ -25,6 +25,13 @@ import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
import { cn } from '@/lib/utils';
type Visibility = 'PRIVATE' | 'INVITE' | 'PUBLIC';
@@ -110,9 +117,17 @@ function StepWelcome({ userName, onNext }: { userName: string; onNext: () => voi
// ─── Step 2: Create Workspace ──────────────────────────────────────────────────
function StepWorkspace({
+ canCreateWorkspace,
+ availableWorkspaces,
+ selectedWorkspaceId,
+ onWorkspaceSelected,
onNext,
onWorkspaceCreated,
}: {
+ canCreateWorkspace: boolean;
+ availableWorkspaces: Array<{ id: string; name: string; isOwner: boolean }>;
+ selectedWorkspaceId: string | null;
+ onWorkspaceSelected: (workspaceId: string) => void;
onNext: () => void;
onWorkspaceCreated: (id: string) => void;
}) {
@@ -144,6 +159,70 @@ function StepWorkspace({
}
};
+ if (!canCreateWorkspace) {
+ return (
+
+
+
+
+
+
Workspace access
+
+ Your account can't create a new workspace right now.
+
+
+
+ {availableWorkspaces.length > 0 ? (
+
+
+
+
+ You can still create projects inside workspaces where you already have admin access.
+
+
+
+
+ Choose a workspace
+
+
+
+
+
+ {availableWorkspaces.map((workspace) => (
+
+ {workspace.name}{workspace.isOwner ? ' (Owner)' : ' (Admin)'}
+
+ ))}
+
+
+
+
+
+ Continue
+
+
+
+ ) : (
+
+
+
+
+ You don't currently have a workspace where you can create projects. Ask a workspace owner to invite you as an admin, or upgrade later to create your own workspace.
+
+
+
+ Continue
+
+
+
+ )}
+
+ );
+ }
+
return (
@@ -217,10 +296,14 @@ function StepWorkspace({
function StepProject({
workspaceId,
+ availableWorkspaces,
+ canCreateWorkspace,
onNext,
onProjectCreated,
}: {
workspaceId: string | null;
+ availableWorkspaces: Array<{ id: string; name: string; isOwner: boolean }>;
+ canCreateWorkspace: boolean;
onNext: () => void;
onProjectCreated: (id: string) => void;
}) {
@@ -273,7 +356,13 @@ function StepProject({
- You skipped workspace creation. Projects require a workspace — you can create both from the dashboard later.
+
+ {canCreateWorkspace
+ ? 'You skipped workspace creation. Projects require a workspace — you can create both from the dashboard later.'
+ : availableWorkspaces.length === 0
+ ? 'You do not currently have permission to create projects in any workspace.'
+ : 'Pick a workspace in the previous step to create a project here.'}
+
Continue
@@ -547,10 +636,18 @@ function StepNotifications({ onFinish }: { onFinish: () => Promise }) {
// ─── Wizard Shell ──────────────────────────────────────────────────────────────
-export function OnboardingWizard({ userName }: { userName: string }) {
+export function OnboardingWizard({
+ userName,
+ canCreateWorkspace,
+ availableWorkspaces,
+}: {
+ userName: string;
+ canCreateWorkspace: boolean;
+ availableWorkspaces: Array<{ id: string; name: string; isOwner: boolean }>;
+}) {
const router = useRouter();
const [currentStep, setCurrentStep] = useState(1);
- const [createdWorkspaceId, setCreatedWorkspaceId] = useState(null);
+ const [createdWorkspaceId, setCreatedWorkspaceId] = useState(availableWorkspaces[0]?.id ?? null);
const [isCompleting, setIsCompleting] = useState(false);
const goNext = () => setCurrentStep((s) => Math.min(s + 1, TOTAL_STEPS));
@@ -615,10 +712,23 @@ export function OnboardingWizard({ userName }: { userName: string }) {
)}
{currentStep === 2 && (
-
+
)}
{currentStep === 3 && (
- {}} />
+ {}}
+ />
)}
{currentStep === 4 && (
diff --git a/app/onboarding/page.tsx b/app/onboarding/page.tsx
index 6082449..082fcf1 100644
--- a/app/onboarding/page.tsx
+++ b/app/onboarding/page.tsx
@@ -1,4 +1,5 @@
import { auth } from '@/lib/auth';
+import { buildBillingAccessWhereInput, getBillingOverview } from '@/lib/billing';
import { db } from '@/lib/db';
import { redirect } from 'next/navigation';
import { OnboardingWizard } from './onboarding-wizard';
@@ -9,10 +10,28 @@ export default async function OnboardingPage() {
redirect('/login');
}
- const user = await db.user.findUnique({
- where: { id: session.user.id },
- select: { onboardingCompletedAt: true, name: true, email: true },
- });
+ const [user, billing, creatableWorkspaces] = await Promise.all([
+ db.user.findUnique({
+ where: { id: session.user.id },
+ select: { onboardingCompletedAt: true, name: true, email: true },
+ }),
+ getBillingOverview(session.user.id),
+ db.workspace.findMany({
+ where: {
+ owner: buildBillingAccessWhereInput(),
+ OR: [
+ { ownerId: session.user.id },
+ { members: { some: { userId: session.user.id, role: 'ADMIN' } } },
+ ],
+ },
+ select: {
+ id: true,
+ name: true,
+ ownerId: true,
+ },
+ orderBy: { name: 'asc' },
+ }),
+ ]);
if (user?.onboardingCompletedAt) {
redirect('/dashboard');
@@ -20,5 +39,15 @@ export default async function OnboardingPage() {
const userName = user?.name || user?.email?.split('@')[0] || 'there';
- return ;
+ return (
+ ({
+ id: workspace.id,
+ name: workspace.name,
+ isOwner: workspace.ownerId === session.user.id,
+ }))}
+ />
+ );
}
diff --git a/bun.lock b/bun.lock
index 0961233..6f6b6e0 100644
--- a/bun.lock
+++ b/bun.lock
@@ -27,6 +27,7 @@
"react-window": "^2.2.7",
"sharp": "^0.34.5",
"sonner": "^2.0.7",
+ "stripe": "^20.4.1",
"tailwind-merge": "^3.4.0",
"tus-js-client": "^4.3.1",
"tw-animate-css": "^1.4.0",
@@ -1732,6 +1733,8 @@
"strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="],
+ "stripe": ["stripe@20.4.1", "", { "peerDependencies": { "@types/node": ">=16" }, "optionalPeers": ["@types/node"] }, "sha512-axCguHItc8Sxt0HC6aSkdVRPffjYPV7EQqZRb2GkIa8FzWDycE7nHJM19C6xAIynH1Qp1/BHiopSi96jGBxT0w=="],
+
"strnum": ["strnum@2.1.2", "", {}, "sha512-l63NF9y/cLROq/yqKXSLtcMeeyOfnSQlfMSlzFt/K73oIaD8DGaQWd7Z34X9GPiKqP5rbSh84Hl4bOlLcjiSrQ=="],
"styled-jsx": ["styled-jsx@5.1.6", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="],
diff --git a/components/layout/header.tsx b/components/layout/header.tsx
index c5dcc18..4b4c641 100644
--- a/components/layout/header.tsx
+++ b/components/layout/header.tsx
@@ -59,9 +59,10 @@ interface HeaderProps {
image?: string | null;
isAdmin?: boolean;
} | null;
+ showAppNavigation?: boolean;
}
-export function Header({ user }: HeaderProps) {
+export function Header({ user, showAppNavigation = false }: HeaderProps) {
const pathname = usePathname();
const [shortcutsOpen, setShortcutsOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
@@ -70,13 +71,17 @@ export function Header({ user }: HeaderProps) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
+ if (!user || !showAppNavigation) {
+ return;
+ }
+
e.preventDefault();
- if (user) setSearchOpen((v) => !v);
+ setSearchOpen((v) => !v);
}
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
- }, [user]);
+ }, [showAppNavigation, user]);
// Hide header on video player pages — they use full viewport with their own back button
const isVideoPage = /\/videos\/[^/]+($|\/compare)/.test(pathname) || pathname.startsWith('/watch/');
@@ -97,7 +102,7 @@ export function Header({ user }: HeaderProps) {
Navigation Menu
Access your projects and workspaces
- {navItems.map((item) => (
+ {showAppNavigation && navItems.map((item) => (
- {navItems.map((item) => (
+ {showAppNavigation && navItems.map((item) => (
- {user && (
+ {user && showAppNavigation && (
@@ -193,7 +198,7 @@ export function Header({ user }: HeaderProps) {
)}
- {user && (
+ {user && showAppNavigation && (
@@ -201,7 +206,7 @@ export function Header({ user }: HeaderProps) {
)}
- {user && (
+ {user && showAppNavigation && (
@@ -223,12 +228,16 @@ export function Header({ user }: HeaderProps) {
-
-
+
+
{user.name &&
{user.name}
}
{user.email && (
-
+
{user.email}
)}
@@ -273,7 +282,7 @@ export function Header({ user }: HeaderProps) {
- {user && }
+ {user && showAppNavigation && }
);
}
diff --git a/lib/auth.ts b/lib/auth.ts
index 9eb1bf7..508530a 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -3,6 +3,7 @@ import Credentials from 'next-auth/providers/credentials';
import bcrypt from 'bcryptjs';
import { db } from '@/lib/db';
import { ProjectMemberRole, WorkspaceMemberRole } from '@prisma/client';
+import { hasBillingAccess } from '@/lib/billing';
// Dummy hash for timing-safe comparison when user doesn't exist
// This prevents user enumeration via timing attacks
@@ -114,6 +115,7 @@ export async function checkProjectAccess(
// Check workspace membership/role
let workspaceRole: WorkspaceMemberRole | 'OWNER' | null = null;
+ let workspaceOwnerBillingAccess = false;
if (shouldLoadWorkspaceRole && userId) {
const [wsMember, wsOwner] = await Promise.all([
db.workspaceMember.findUnique({
@@ -121,7 +123,17 @@ export async function checkProjectAccess(
}),
db.workspace.findUnique({
where: { id: project.workspaceId },
- select: { ownerId: true },
+ select: {
+ ownerId: true,
+ owner: {
+ select: {
+ subscriptionStatus: true,
+ trialEndsAt: true,
+ stripeCurrentPeriodEnd: true,
+ billingAccessEndedAt: true,
+ },
+ },
+ },
}),
]);
@@ -130,13 +142,32 @@ export async function checkProjectAccess(
} else if (wsMember) {
workspaceRole = wsMember.role;
}
+
+ if (wsOwner?.owner) {
+ workspaceOwnerBillingAccess = hasBillingAccess(wsOwner.owner);
+ }
+ } else {
+ const wsOwner = await db.workspace.findUnique({
+ where: { id: project.workspaceId },
+ select: {
+ owner: {
+ select: {
+ subscriptionStatus: true,
+ trialEndsAt: true,
+ stripeCurrentPeriodEnd: true,
+ billingAccessEndedAt: true,
+ },
+ },
+ },
+ });
+ workspaceOwnerBillingAccess = wsOwner?.owner ? hasBillingAccess(wsOwner.owner) : false;
}
const isWorkspaceMember = !!workspaceRole;
const isWorkspaceAdmin = workspaceRole === WorkspaceMemberRole.ADMIN || workspaceRole === 'OWNER';
- const hasAccess = isOwner || isProjectMember || isPublic || isWorkspaceMember;
- const canEdit = isOwner || isProjectAdmin || isWorkspaceAdmin;
- const canDelete = isOwner || workspaceRole === 'OWNER';
+ const hasAccess = workspaceOwnerBillingAccess && (isOwner || isProjectMember || isPublic || isWorkspaceMember);
+ const canEdit = workspaceOwnerBillingAccess && (isOwner || isProjectAdmin || isWorkspaceAdmin);
+ const canDelete = workspaceOwnerBillingAccess && (isOwner || workspaceRole === 'OWNER');
return {
isOwner,
@@ -147,6 +178,7 @@ export async function checkProjectAccess(
hasAccess,
canEdit,
canDelete,
+ ownerBillingActive: workspaceOwnerBillingAccess,
};
}
@@ -166,9 +198,20 @@ export async function checkWorkspaceAccess(
const isMember = !!workspaceMember;
const isAdmin = workspaceMember?.role === WorkspaceMemberRole.ADMIN;
- const hasAccess = isOwner || isMember;
- const canEdit = isOwner || isAdmin;
- const canDelete = isOwner;
+ const owner = await db.user.findUnique({
+ where: { id: workspace.ownerId },
+ select: {
+ subscriptionStatus: true,
+ trialEndsAt: true,
+ stripeCurrentPeriodEnd: true,
+ billingAccessEndedAt: true,
+ },
+ });
+ const ownerBillingActive = owner ? hasBillingAccess(owner) : false;
+
+ const hasAccess = ownerBillingActive && (isOwner || isMember);
+ const canEdit = ownerBillingActive && (isOwner || isAdmin);
+ const canDelete = ownerBillingActive && isOwner;
return {
isOwner,
@@ -177,5 +220,6 @@ export async function checkWorkspaceAccess(
hasAccess,
canEdit,
canDelete,
+ ownerBillingActive,
};
}
diff --git a/lib/billing.ts b/lib/billing.ts
new file mode 100644
index 0000000..d02a4db
--- /dev/null
+++ b/lib/billing.ts
@@ -0,0 +1,418 @@
+import type { Prisma } from '@prisma/client';
+import type Stripe from 'stripe';
+import { BillingSubscriptionStatus } from '@prisma/client';
+import { db } from '@/lib/db';
+import { getStripe, getStripePriceId } from '@/lib/stripe';
+
+const ACTIVE_SUBSCRIPTION_STATUSES = new Set([
+ BillingSubscriptionStatus.ACTIVE,
+ BillingSubscriptionStatus.TRIALING,
+]);
+
+export const DEFAULT_TRIAL_PERIOD_DAYS = 7;
+const STORAGE_CLEANUP_GRACE_DAYS = 15;
+
+type BillingAccessSubject = {
+ subscriptionStatus: BillingSubscriptionStatus;
+ trialEndsAt: Date | null;
+ stripeCurrentPeriodEnd: Date | null;
+ stripeCancelAtPeriodEnd?: boolean | null;
+ stripeCancelAt?: Date | null;
+ billingAccessEndedAt: Date | null;
+};
+
+export function getDefaultTrialEndsAt(from: Date = new Date()) {
+ return new Date(from.getTime() + DEFAULT_TRIAL_PERIOD_DAYS * 24 * 60 * 60 * 1000);
+}
+
+export function hasActiveTrial(trialEndsAt: Date | null | undefined, now: Date = new Date()) {
+ return Boolean(trialEndsAt && trialEndsAt.getTime() > now.getTime());
+}
+
+export function hasActiveSubscription(status: BillingSubscriptionStatus | null | undefined) {
+ if (!status) return false;
+ return ACTIVE_SUBSCRIPTION_STATUSES.has(status);
+}
+
+export function hasBillingAccess(subject: BillingAccessSubject, now: Date = new Date()) {
+ if (hasActiveSubscription(subject.subscriptionStatus)) {
+ return true;
+ }
+
+ if (hasActiveTrial(subject.trialEndsAt, now)) {
+ return true;
+ }
+
+ return Boolean(
+ subject.stripeCurrentPeriodEnd && subject.stripeCurrentPeriodEnd.getTime() > now.getTime()
+ );
+}
+
+export function getBillingAccessEndDate(subject: BillingAccessSubject) {
+ if (subject.billingAccessEndedAt) {
+ return subject.billingAccessEndedAt;
+ }
+
+ if (subject.stripeCurrentPeriodEnd) {
+ return subject.stripeCurrentPeriodEnd;
+ }
+
+ return subject.trialEndsAt;
+}
+
+export function getStorageCleanupEligibleAt(subject: BillingAccessSubject) {
+ const accessEndDate = getBillingAccessEndDate(subject);
+ if (!accessEndDate) return null;
+
+ return new Date(accessEndDate.getTime() + STORAGE_CLEANUP_GRACE_DAYS * 24 * 60 * 60 * 1000);
+}
+
+export function buildBillingAccessWhereInput(now: Date = new Date()): Prisma.UserWhereInput {
+ return {
+ OR: [
+ { subscriptionStatus: { in: [BillingSubscriptionStatus.ACTIVE, BillingSubscriptionStatus.TRIALING] } },
+ { trialEndsAt: { gt: now } },
+ { stripeCurrentPeriodEnd: { gt: now } },
+ ],
+ };
+}
+
+export function buildExpiredBillingWhereInput(now: Date = new Date()): Prisma.UserWhereInput {
+ const cleanupCutoff = new Date(now.getTime() - STORAGE_CLEANUP_GRACE_DAYS * 24 * 60 * 60 * 1000);
+
+ return {
+ AND: [
+ {
+ NOT: buildBillingAccessWhereInput(now),
+ },
+ {
+ OR: [
+ { billingAccessEndedAt: { lte: cleanupCutoff } },
+ {
+ AND: [
+ { billingAccessEndedAt: null },
+ { trialEndsAt: { lte: cleanupCutoff } },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+}
+
+export function mapStripeSubscriptionStatus(
+ status: Stripe.Subscription.Status | null | undefined
+): BillingSubscriptionStatus {
+ switch (status) {
+ case 'trialing':
+ return BillingSubscriptionStatus.TRIALING;
+ case 'active':
+ return BillingSubscriptionStatus.ACTIVE;
+ case 'past_due':
+ return BillingSubscriptionStatus.PAST_DUE;
+ case 'canceled':
+ return BillingSubscriptionStatus.CANCELED;
+ case 'unpaid':
+ return BillingSubscriptionStatus.UNPAID;
+ case 'incomplete':
+ return BillingSubscriptionStatus.INCOMPLETE;
+ case 'incomplete_expired':
+ return BillingSubscriptionStatus.INCOMPLETE_EXPIRED;
+ default:
+ return BillingSubscriptionStatus.FREE;
+ }
+}
+
+export function getBillingStatusLabel(status: BillingSubscriptionStatus) {
+ switch (status) {
+ case BillingSubscriptionStatus.TRIALING:
+ return 'Trialing';
+ case BillingSubscriptionStatus.ACTIVE:
+ return 'Active';
+ case BillingSubscriptionStatus.PAST_DUE:
+ return 'Past due';
+ case BillingSubscriptionStatus.CANCELED:
+ return 'Canceled';
+ case BillingSubscriptionStatus.UNPAID:
+ return 'Unpaid';
+ case BillingSubscriptionStatus.INCOMPLETE:
+ return 'Incomplete';
+ case BillingSubscriptionStatus.INCOMPLETE_EXPIRED:
+ return 'Expired';
+ case BillingSubscriptionStatus.FREE:
+ default:
+ return 'Free';
+ }
+}
+
+export async function getStripeCheckoutState(userId: string) {
+ const user = await db.user.findUnique({
+ where: { id: userId },
+ select: {
+ subscriptionStatus: true,
+ billingTrialConsumedAt: true,
+ },
+ });
+
+ if (!user) {
+ throw new Error(`User ${userId} not found`);
+ }
+
+ return {
+ hasActiveSubscription: hasActiveSubscription(user.subscriptionStatus),
+ isTrialEligible: !user.billingTrialConsumedAt,
+ };
+}
+
+export async function getWorkspaceCreationEligibility(userId: string) {
+ const [user, ownedWorkspaceCount, invitedWorkspaceCount, projectOnlyCollaborationCount] = await Promise.all([
+ db.user.findUnique({
+ where: { id: userId },
+ select: {
+ subscriptionStatus: true,
+ trialEndsAt: true,
+ stripeCustomerId: true,
+ stripeSubscriptionId: true,
+ stripePriceId: true,
+ stripeCurrentPeriodEnd: true,
+ stripeCancelAtPeriodEnd: true,
+ stripeCancelAt: true,
+ billingAccessEndedAt: true,
+ },
+ }),
+ db.workspace.count({
+ where: { ownerId: userId },
+ }),
+ db.workspaceMember.count({
+ where: {
+ userId,
+ workspace: {
+ ownerId: {
+ not: userId,
+ },
+ },
+ },
+ }),
+ db.projectMember.count({
+ where: {
+ userId,
+ project: {
+ ownerId: {
+ not: userId,
+ },
+ workspace: {
+ ownerId: {
+ not: userId,
+ },
+ },
+ },
+ },
+ }),
+ ]);
+
+ if (!user) {
+ throw new Error(`User ${userId} not found`);
+ }
+
+ const billingAccess = hasBillingAccess(user);
+ const collaborationCount = invitedWorkspaceCount + projectOnlyCollaborationCount;
+ const canCreateWorkspace =
+ billingAccess || (ownedWorkspaceCount === 0 && collaborationCount === 0);
+
+ let reason: string | null = null;
+ if (!canCreateWorkspace) {
+ if (collaborationCount > 0 && ownedWorkspaceCount === 0) {
+ reason =
+ 'You are currently collaborating in someone else’s workspace or project. Start a subscription to create a workspace of your own.';
+ } else {
+ reason =
+ 'Your trial has ended. Start a subscription to create and keep owning workspaces.';
+ }
+ }
+
+ return {
+ canCreateWorkspace,
+ reason,
+ ownedWorkspaceCount,
+ invitedWorkspaceCount,
+ projectOnlyCollaborationCount,
+ subscription: {
+ status: user.subscriptionStatus,
+ label: getBillingStatusLabel(user.subscriptionStatus),
+ hasActiveSubscription: hasActiveSubscription(user.subscriptionStatus),
+ hasActiveTrial: hasActiveTrial(user.trialEndsAt),
+ hasBillingAccess: billingAccess,
+ stripeCustomerId: user.stripeCustomerId,
+ stripeSubscriptionId: user.stripeSubscriptionId,
+ stripePriceId: user.stripePriceId,
+ currentPeriodEnd: user.stripeCurrentPeriodEnd,
+ cancelAtPeriodEnd: user.stripeCancelAtPeriodEnd,
+ cancelAt: user.stripeCancelAt,
+ trialEndsAt: user.trialEndsAt,
+ billingAccessEndedAt: user.billingAccessEndedAt,
+ storageCleanupEligibleAt: getStorageCleanupEligibleAt(user),
+ },
+ };
+}
+
+export async function getBillingOverview(userId: string) {
+ const billing = await getWorkspaceCreationEligibility(userId);
+
+ return {
+ workspaceCreation: {
+ canCreateWorkspace: billing.canCreateWorkspace,
+ reason: billing.reason,
+ ownedWorkspaceCount: billing.ownedWorkspaceCount,
+ invitedWorkspaceCount: billing.invitedWorkspaceCount,
+ },
+ subscription: billing.subscription,
+ };
+}
+
+export async function getOrCreateStripeCustomerId(userId: string) {
+ const user = await db.user.findUnique({
+ where: { id: userId },
+ select: {
+ id: true,
+ email: true,
+ name: true,
+ stripeCustomerId: true,
+ },
+ });
+
+ if (!user) {
+ throw new Error(`User ${userId} not found`);
+ }
+
+ if (user.stripeCustomerId) {
+ return user.stripeCustomerId;
+ }
+
+ const stripe = getStripe();
+ const customer = await stripe.customers.create({
+ email: user.email ?? undefined,
+ name: user.name ?? undefined,
+ metadata: { userId: user.id },
+ });
+
+ await db.user.update({
+ where: { id: user.id },
+ data: { stripeCustomerId: customer.id },
+ });
+
+ return customer.id;
+}
+
+function getStripeTimestamp(value: unknown): number | null {
+ return typeof value === 'number' ? value : null;
+}
+
+function getInactiveBillingAccessEndedAt(subscription: Stripe.Subscription, currentPeriodEnd: number | null) {
+ const endedAt = getStripeTimestamp((subscription as Stripe.Subscription & { ended_at?: unknown }).ended_at);
+ const canceledAt = getStripeTimestamp((subscription as Stripe.Subscription & { canceled_at?: unknown }).canceled_at);
+ const reference = currentPeriodEnd ?? endedAt ?? canceledAt;
+
+ return reference ? new Date(reference * 1000) : new Date();
+}
+
+function getEntitledStripePriceId(subscription: Stripe.Subscription) {
+ const configuredPriceId = getStripePriceId();
+
+ return subscription.items.data.find((item) => item.price.id === configuredPriceId)?.price.id ?? null;
+}
+
+export async function syncStripeSubscriptionToUser(subscription: Stripe.Subscription) {
+ const customerId =
+ typeof subscription.customer === 'string'
+ ? subscription.customer
+ : subscription.customer.id;
+
+ const user = await db.user.findUnique({
+ where: { stripeCustomerId: customerId },
+ select: {
+ id: true,
+ billingTrialConsumedAt: true,
+ },
+ });
+
+ if (!user) {
+ return null;
+ }
+
+ const currentPeriodEnd =
+ 'current_period_end' in subscription && typeof subscription.current_period_end === 'number'
+ ? subscription.current_period_end
+ : null;
+ const cancelAt =
+ 'cancel_at' in subscription && typeof subscription.cancel_at === 'number'
+ ? subscription.cancel_at
+ : null;
+ const cancelAtPeriodEnd =
+ 'cancel_at_period_end' in subscription && typeof subscription.cancel_at_period_end === 'boolean'
+ ? subscription.cancel_at_period_end
+ : false;
+ const trialEnd =
+ 'trial_end' in subscription && typeof subscription.trial_end === 'number'
+ ? subscription.trial_end
+ : null;
+ const entitledPriceId = getEntitledStripePriceId(subscription);
+ const hasEntitledPrice = Boolean(entitledPriceId);
+ const mappedStatus = hasEntitledPrice
+ ? mapStripeSubscriptionStatus(subscription.status)
+ : BillingSubscriptionStatus.FREE;
+ const effectiveCurrentPeriodEnd = hasEntitledPrice && currentPeriodEnd
+ ? new Date(currentPeriodEnd * 1000)
+ : null;
+ const effectiveTrialEnd = hasEntitledPrice && trialEnd
+ ? new Date(trialEnd * 1000)
+ : null;
+ const hasAccess = hasEntitledPrice
+ && (hasActiveSubscription(mappedStatus) || Boolean(currentPeriodEnd && currentPeriodEnd * 1000 > Date.now()));
+
+ return db.user.update({
+ where: { id: user.id },
+ data: {
+ stripeSubscriptionId: subscription.id,
+ stripePriceId: entitledPriceId ?? subscription.items.data[0]?.price.id ?? null,
+ stripeCurrentPeriodEnd: effectiveCurrentPeriodEnd,
+ stripeCancelAtPeriodEnd: cancelAtPeriodEnd,
+ stripeCancelAt: cancelAt ? new Date(cancelAt * 1000) : null,
+ subscriptionStatus: mappedStatus,
+ trialEndsAt: effectiveTrialEnd,
+ billingTrialConsumedAt: hasEntitledPrice && trialEnd
+ ? (user.billingTrialConsumedAt ?? new Date())
+ : user.billingTrialConsumedAt,
+ billingAccessEndedAt: hasAccess
+ ? null
+ : getInactiveBillingAccessEndedAt(subscription, hasEntitledPrice ? currentPeriodEnd : null),
+ },
+ });
+}
+
+export async function markSubscriptionCanceledByCustomerId(
+ customerId: string,
+ options?: { currentPeriodEnd?: Date | null; endedAt?: Date | null }
+) {
+ const user = await db.user.findUnique({
+ where: { stripeCustomerId: customerId },
+ select: { id: true },
+ });
+
+ if (!user) {
+ return null;
+ }
+
+ return db.user.update({
+ where: { id: user.id },
+ data: {
+ subscriptionStatus: BillingSubscriptionStatus.CANCELED,
+ trialEndsAt: null,
+ stripeSubscriptionId: null,
+ stripePriceId: null,
+ stripeCurrentPeriodEnd: options?.currentPeriodEnd ?? null,
+ stripeCancelAtPeriodEnd: false,
+ stripeCancelAt: null,
+ billingAccessEndedAt: options?.endedAt ?? options?.currentPeriodEnd ?? new Date(),
+ },
+ });
+}
diff --git a/lib/route-access.ts b/lib/route-access.ts
index a3c2f79..2b7eed4 100644
--- a/lib/route-access.ts
+++ b/lib/route-access.ts
@@ -1,11 +1,13 @@
import { notFound, redirect } from 'next/navigation';
import { auth, checkProjectAccess, checkWorkspaceAccess } from '@/lib/auth';
+import { hasBillingAccess } from '@/lib/billing';
import { db } from '@/lib/db';
type AccessIntent = 'view' | 'manage';
const LOGIN_REDIRECT = '/login';
const FORBIDDEN_REDIRECT = '/dashboard';
+const BILLING_REDIRECT = '/settings';
function redirectForMissingAuth() {
redirect(LOGIN_REDIRECT);
@@ -15,6 +17,10 @@ function redirectForForbidden() {
redirect(FORBIDDEN_REDIRECT);
}
+function redirectForBilling() {
+ redirect(BILLING_REDIRECT);
+}
+
function ensureGuestPolicy(options: { userId?: string; intent: AccessIntent; allowPublicView: boolean }) {
const { userId, intent, allowPublicView } = options;
if (userId) return;
@@ -60,6 +66,92 @@ export async function requireAuthOrRedirect() {
return session;
}
+export async function requireBillingAccessOrRedirect(options?: {
+ userId?: string;
+}) {
+ const resolvedUserId = options?.userId ?? (await auth())?.user?.id;
+
+ if (!resolvedUserId) {
+ redirectForMissingAuth();
+ }
+
+ const user = await db.user.findUnique({
+ where: { id: resolvedUserId },
+ select: {
+ subscriptionStatus: true,
+ trialEndsAt: true,
+ stripeCurrentPeriodEnd: true,
+ billingAccessEndedAt: true,
+ },
+ });
+
+ if (!user || !hasBillingAccess(user)) {
+ redirectForBilling();
+ }
+
+ return user;
+}
+
+export async function hasCollaboratorBillingBackedAccess(userId: string) {
+ const now = new Date();
+
+ const [workspaceCount, projectCount] = await Promise.all([
+ db.workspace.count({
+ where: {
+ owner: {
+ OR: [
+ { subscriptionStatus: { in: ['ACTIVE', 'TRIALING'] } },
+ { trialEndsAt: { gt: now } },
+ { stripeCurrentPeriodEnd: { gt: now } },
+ ],
+ },
+ OR: [
+ { ownerId: userId },
+ { members: { some: { userId } } },
+ ],
+ },
+ }),
+ db.project.count({
+ where: {
+ workspace: {
+ owner: {
+ OR: [
+ { subscriptionStatus: { in: ['ACTIVE', 'TRIALING'] } },
+ { trialEndsAt: { gt: now } },
+ { stripeCurrentPeriodEnd: { gt: now } },
+ ],
+ },
+ },
+ OR: [
+ { ownerId: userId },
+ { members: { some: { userId } } },
+ { workspace: { members: { some: { userId } } } },
+ ],
+ },
+ }),
+ ]);
+
+ return workspaceCount > 0 || projectCount > 0;
+}
+
+export async function hasAppNavigationAccess(userId: string) {
+ const user = await db.user.findUnique({
+ where: { id: userId },
+ select: {
+ subscriptionStatus: true,
+ trialEndsAt: true,
+ stripeCurrentPeriodEnd: true,
+ billingAccessEndedAt: true,
+ },
+ });
+
+ if (user && hasBillingAccess(user)) {
+ return true;
+ }
+
+ return hasCollaboratorBillingBackedAccess(userId);
+}
+
export async function requireWorkspaceAccessOrRedirect(options: {
workspaceId: string;
userId?: string;
@@ -84,10 +176,16 @@ export async function requireWorkspaceAccessOrRedirect(options: {
const access = await checkWorkspaceAccess(workspace, resolvedUserId);
if (!access.hasAccess) {
+ if (!access.ownerBillingActive) {
+ redirectForBilling();
+ }
redirectForForbidden();
}
if (intent === 'manage' && !access.canEdit) {
+ if (!access.ownerBillingActive) {
+ redirectForBilling();
+ }
redirectForForbidden();
}
diff --git a/lib/share-links.ts b/lib/share-links.ts
index 4c42bc7..1aef3c2 100644
--- a/lib/share-links.ts
+++ b/lib/share-links.ts
@@ -1,6 +1,7 @@
import bcrypt from 'bcryptjs';
import type { ShareLink, SharePermission } from '@prisma/client';
import { db } from '@/lib/db';
+import { hasBillingAccess } from '@/lib/billing';
export const MAX_SHARE_PASSWORD_LENGTH = 128;
@@ -45,6 +46,24 @@ export async function validateShareLinkAccess({
}: ValidateShareLinkParams): Promise {
const link = await db.shareLink.findUnique({
where: { token },
+ include: {
+ project: {
+ select: {
+ workspace: {
+ select: {
+ owner: {
+ select: {
+ subscriptionStatus: true,
+ trialEndsAt: true,
+ stripeCurrentPeriodEnd: true,
+ billingAccessEndedAt: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
});
if (!link) {
@@ -60,6 +79,10 @@ export async function validateShareLinkAccess({
return { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false, link };
}
+ if (!link.project?.workspace.owner || !hasBillingAccess(link.project.workspace.owner)) {
+ return { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false, link };
+ }
+
if (link.passwordHash && !passwordVerified) {
if (!presentedPassword) {
return { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: true, link };
diff --git a/lib/stripe.ts b/lib/stripe.ts
new file mode 100644
index 0000000..6e68a1a
--- /dev/null
+++ b/lib/stripe.ts
@@ -0,0 +1,38 @@
+import Stripe from 'stripe';
+
+let stripeClient: Stripe | null = null;
+
+export function isStripeConfigured() {
+ return Boolean(process.env.STRIPE_SECRET_KEY && process.env.STRIPE_PRICE_ID);
+}
+
+export function getStripe() {
+ const secretKey = process.env.STRIPE_SECRET_KEY;
+ if (!secretKey) {
+ throw new Error('STRIPE_SECRET_KEY is not configured');
+ }
+
+ if (!stripeClient) {
+ stripeClient = new Stripe(secretKey);
+ }
+
+ return stripeClient;
+}
+
+export function getStripePriceId() {
+ const priceId = process.env.STRIPE_PRICE_ID;
+ if (!priceId) {
+ throw new Error('STRIPE_PRICE_ID is not configured');
+ }
+
+ return priceId;
+}
+
+export function getStripeWebhookSecret() {
+ const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
+ if (!webhookSecret) {
+ throw new Error('STRIPE_WEBHOOK_SECRET is not configured');
+ }
+
+ return webhookSecret;
+}
diff --git a/package.json b/package.json
index 2400b4c..de74f65 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"react-window": "^2.2.7",
"sharp": "^0.34.5",
"sonner": "^2.0.7",
+ "stripe": "^20.4.1",
"tailwind-merge": "^3.4.0",
"tus-js-client": "^4.3.1",
"tw-animate-css": "^1.4.0"
diff --git a/prisma/migrations/20260320110000_add_stripe_billing/migration.sql b/prisma/migrations/20260320110000_add_stripe_billing/migration.sql
new file mode 100644
index 0000000..574e2b4
--- /dev/null
+++ b/prisma/migrations/20260320110000_add_stripe_billing/migration.sql
@@ -0,0 +1,20 @@
+CREATE TYPE "BillingSubscriptionStatus" AS ENUM (
+ 'FREE',
+ 'TRIALING',
+ 'ACTIVE',
+ 'PAST_DUE',
+ 'CANCELED',
+ 'UNPAID',
+ 'INCOMPLETE',
+ 'INCOMPLETE_EXPIRED'
+);
+
+ALTER TABLE "users"
+ADD COLUMN "stripeCustomerId" TEXT,
+ADD COLUMN "stripeSubscriptionId" TEXT,
+ADD COLUMN "stripePriceId" TEXT,
+ADD COLUMN "stripeCurrentPeriodEnd" TIMESTAMP(3),
+ADD COLUMN "subscriptionStatus" "BillingSubscriptionStatus" NOT NULL DEFAULT 'FREE';
+
+CREATE UNIQUE INDEX "users_stripeCustomerId_key" ON "users"("stripeCustomerId");
+CREATE UNIQUE INDEX "users_stripeSubscriptionId_key" ON "users"("stripeSubscriptionId");
diff --git a/prisma/migrations/20260320123000_add_billing_trials_and_cleanup_dates/migration.sql b/prisma/migrations/20260320123000_add_billing_trials_and_cleanup_dates/migration.sql
new file mode 100644
index 0000000..578c3d5
--- /dev/null
+++ b/prisma/migrations/20260320123000_add_billing_trials_and_cleanup_dates/migration.sql
@@ -0,0 +1,7 @@
+ALTER TABLE "users"
+ADD COLUMN "trialEndsAt" TIMESTAMP(3),
+ADD COLUMN "billingAccessEndedAt" TIMESTAMP(3);
+
+UPDATE "users"
+SET "trialEndsAt" = "createdAt" + INTERVAL '7 days'
+WHERE "trialEndsAt" IS NULL;
diff --git a/prisma/migrations/20260321003000_add_subscription_cancel_state/migration.sql b/prisma/migrations/20260321003000_add_subscription_cancel_state/migration.sql
new file mode 100644
index 0000000..79c4227
--- /dev/null
+++ b/prisma/migrations/20260321003000_add_subscription_cancel_state/migration.sql
@@ -0,0 +1,3 @@
+ALTER TABLE "users"
+ADD COLUMN "stripeCancelAtPeriodEnd" BOOLEAN NOT NULL DEFAULT false,
+ADD COLUMN "stripeCancelAt" TIMESTAMP(3);
diff --git a/prisma/migrations/20260321094500_add_billing_trial_consumed_at/migration.sql b/prisma/migrations/20260321094500_add_billing_trial_consumed_at/migration.sql
new file mode 100644
index 0000000..43f2b91
--- /dev/null
+++ b/prisma/migrations/20260321094500_add_billing_trial_consumed_at/migration.sql
@@ -0,0 +1,6 @@
+ALTER TABLE "users"
+ADD COLUMN "billingTrialConsumedAt" TIMESTAMP(3);
+
+UPDATE "users"
+SET "billingTrialConsumedAt" = "trialEndsAt"
+WHERE "trialEndsAt" IS NOT NULL;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 17bff76..8008d32 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -22,6 +22,16 @@ model User {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
onboardingCompletedAt DateTime?
+ trialEndsAt DateTime?
+ billingTrialConsumedAt DateTime?
+ stripeCustomerId String? @unique
+ stripeSubscriptionId String? @unique
+ stripePriceId String?
+ stripeCurrentPeriodEnd DateTime?
+ stripeCancelAtPeriodEnd Boolean @default(false)
+ stripeCancelAt DateTime?
+ billingAccessEndedAt DateTime?
+ subscriptionStatus BillingSubscriptionStatus @default(FREE)
// Relations
accounts Account[]
@@ -44,6 +54,17 @@ model User {
@@map("users")
}
+enum BillingSubscriptionStatus {
+ FREE
+ TRIALING
+ ACTIVE
+ PAST_DUE
+ CANCELED
+ UNPAID
+ INCOMPLETE
+ INCOMPLETE_EXPIRED
+}
+
enum FeedbackEntryType {
FEEDBACK
REVIEW
diff --git a/scripts/bunny-orphan-cleanup.ts b/scripts/bunny-orphan-cleanup.ts
index 27a4732..3c7ee42 100644
--- a/scripts/bunny-orphan-cleanup.ts
+++ b/scripts/bunny-orphan-cleanup.ts
@@ -1,4 +1,5 @@
import { db, disconnectDb } from '../lib/db';
+import { cleanupExpiredBillingWorkspaces } from './expired-billing-cleanup';
const BUNNY_API_BASE = 'https://video.bunnycdn.com';
const BUNNY_VIDEO_ID_PATTERN = /^[A-Za-z0-9_-]{8,128}$/;
@@ -197,6 +198,10 @@ async function main() {
console.log(`[bunny-orphan-cleanup] Starting (${dryRun ? 'dry-run' : 'delete mode'})`);
console.log(`[bunny-orphan-cleanup] Grace period: ${graceHours}h`);
+ const expiredBillingCleanup = await cleanupExpiredBillingWorkspaces({ dryRun });
+ console.log(`[bunny-orphan-cleanup] Expired owner workspaces scanned: ${expiredBillingCleanup.scanned}`);
+ console.log(`[bunny-orphan-cleanup] Expired owner workspaces deleted: ${expiredBillingCleanup.deleted}`);
+
const { videos, scanned, skippedInvalid } = await listBunnyVideos(config);
const eligible = videos.filter((video) => video.uploadedAt.getTime() <= cutoff);
console.log(`[bunny-orphan-cleanup] Scanned: ${scanned}`);
diff --git a/scripts/expired-billing-cleanup.ts b/scripts/expired-billing-cleanup.ts
new file mode 100644
index 0000000..27f01d8
--- /dev/null
+++ b/scripts/expired-billing-cleanup.ts
@@ -0,0 +1,111 @@
+import { db } from '../lib/db';
+import { buildExpiredBillingWhereInput } from '../lib/billing';
+import { collectWorkspaceMediaUrls, deleteMediaFilesBestEffort } from '../lib/r2-cleanup';
+import { cleanupBunnyStreamVideosBestEffort } from '../lib/bunny-stream-cleanup';
+
+type ExpiredWorkspaceTarget = {
+ id: string;
+ ownerId: string;
+ ownerEmail: string | null;
+};
+
+async function getExpiredWorkspaceTargets(): Promise {
+ const expiredOwners = await db.user.findMany({
+ where: buildExpiredBillingWhereInput(),
+ select: { id: true },
+ });
+
+ if (expiredOwners.length === 0) {
+ return [];
+ }
+
+ return db.workspace.findMany({
+ where: {
+ ownerId: { in: expiredOwners.map((owner) => owner.id) },
+ },
+ select: {
+ id: true,
+ ownerId: true,
+ owner: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ }).then((workspaces) =>
+ workspaces.map((workspace) => ({
+ id: workspace.id,
+ ownerId: workspace.ownerId,
+ ownerEmail: workspace.owner.email,
+ }))
+ );
+}
+
+export async function cleanupExpiredBillingWorkspaces(options?: { dryRun?: boolean }) {
+ const dryRun = options?.dryRun ?? false;
+ const workspaces = await getExpiredWorkspaceTargets();
+
+ if (workspaces.length === 0) {
+ return { scanned: 0, deleted: 0 };
+ }
+
+ let deleted = 0;
+
+ for (const workspace of workspaces) {
+ const [workspaceVersionRefs, workspaceAssetRefs, mediaUrls] = await Promise.all([
+ db.videoVersion.findMany({
+ where: {
+ video: {
+ project: {
+ workspaceId: workspace.id,
+ },
+ },
+ },
+ select: {
+ providerId: true,
+ videoId: true,
+ },
+ }),
+ db.videoAsset.findMany({
+ where: {
+ provider: 'BUNNY',
+ providerVideoId: { not: null },
+ video: {
+ project: {
+ workspaceId: workspace.id,
+ },
+ },
+ },
+ select: {
+ providerVideoId: true,
+ },
+ }),
+ collectWorkspaceMediaUrls(workspace.id),
+ ]);
+
+ if (dryRun) {
+ const ownerLabel = workspace.ownerEmail ?? workspace.ownerId;
+ console.log(
+ `[expired-billing-cleanup] Would delete workspace ${workspace.id} owned by ${ownerLabel}`
+ );
+ continue;
+ }
+
+ const bunnyRefs = [
+ ...workspaceVersionRefs,
+ ...workspaceAssetRefs.map((asset) => ({
+ providerId: 'bunny',
+ videoId: asset.providerVideoId as string,
+ })),
+ ];
+
+ await db.workspace.delete({ where: { id: workspace.id } });
+ await Promise.all([
+ cleanupBunnyStreamVideosBestEffort(bunnyRefs),
+ deleteMediaFilesBestEffort(mediaUrls),
+ ]);
+ deleted += 1;
+ }
+
+ return { scanned: workspaces.length, deleted };
+}
diff --git a/scripts/r2-orphan-cleanup.ts b/scripts/r2-orphan-cleanup.ts
index dff8b15..6dfa95e 100644
--- a/scripts/r2-orphan-cleanup.ts
+++ b/scripts/r2-orphan-cleanup.ts
@@ -1,6 +1,7 @@
import { DeleteObjectCommand, ListObjectsV2Command, type ListObjectsV2CommandInput } from '@aws-sdk/client-s3';
import { db, disconnectDb } from '../lib/db';
import { r2Client, R2_BUCKET_NAME } from '../lib/r2';
+import { cleanupExpiredBillingWorkspaces } from './expired-billing-cleanup';
const UNATTACHED_UPLOAD_TTL_MS = 15 * 60 * 1000;
const CHUNK_SIZE = 500;
@@ -127,6 +128,10 @@ async function main() {
const dryRun = process.argv.includes('--dry-run');
console.log(`[r2-orphan-cleanup] Starting (${dryRun ? 'dry-run' : 'delete mode'})`);
+ const expiredBillingCleanup = await cleanupExpiredBillingWorkspaces({ dryRun });
+ console.log(`[r2-orphan-cleanup] Expired owner workspaces scanned: ${expiredBillingCleanup.scanned}`);
+ console.log(`[r2-orphan-cleanup] Expired owner workspaces deleted: ${expiredBillingCleanup.deleted}`);
+
const { candidates, scanned } = await listCleanupCandidates();
console.log(`[r2-orphan-cleanup] Scanned: ${scanned}, eligible (old enough): ${candidates.length}`);