Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/web/REVENUE-PROCESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ npm run dev
|------|------|
| `src/lib/billing/checkout-config.ts` | Pure price/URL resolution |
| `src/lib/billing/stripe-checkout.ts` | Stripe session creation |
| `src/lib/billing/pro-feature-gate.ts` | Pro verification + checkout handoff for gated downloads |
| `src/lib/billing/turnstile.ts` | Cloudflare siteverify |
| `src/lib/billing/grok-lead.ts` | Grok/Composer metadata on paid tier |
| `src/lib/billing/kaizen-trace.ts` | Structured trace for renewal/debug |
Expand All @@ -66,6 +67,8 @@ npm run dev
|---------|------|-----|
| AI chat | 5/day | Unlimited, `grok-composer` lead model |
| Agent dispatch | Blocked (402) | Allowed |
| Workspace ZIP export | Blocked (402 + checkout) | Download enabled |
| `/api/v1/refinery/dataset` | Blocked (402 + checkout) | Metadata + JSONL download |
| API headers | — | `X-Lead-Model`, `X-Billing-Plan` on backend proxy |

## Returning users
Expand Down
125 changes: 125 additions & 0 deletions apps/web/src/app/api/__tests__/workspace-export-route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';

vi.mock('@/lib/billing/billing-context', () => ({
BILLING_EMAIL_COOKIE: 'er_billing_email',
resolveTrustedBillingEmail: vi.fn(async () => null),
}));

vi.mock('@/lib/billing/entitlement-store', () => ({
getEntitlement: vi.fn(async () => null),
isProSubscriber: vi.fn(async () => false),
}));

vi.mock('@/lib/billing/stripe-checkout', () => ({
getCheckoutSession: vi.fn(async () => ({
id: 'cs_test_paid_workspace_zip',
payment_status: 'paid',
status: 'complete',
customer_email: 'paid@example.com',
metadata: { plan: 'pro' },
})),
createProCheckoutSession: vi.fn(async () => ({
sessionId: 'cs_test_workspace_zip',
url: 'https://checkout.stripe.com/c/pay/cs_test_workspace_zip',
})),
}));

vi.mock('@/lib/billing/subscription-events', () => ({
activateFromCheckoutSession: vi.fn(async () => ({
email: 'paid@example.com',
plan: 'pro',
status: 'active',
leadModel: 'grok-4-1-fast',
updatedAt: '2026-09-08T00:00:00.000Z',
})),
}));

import { POST } from '@/app/api/workspace/export/route';
import { getEntitlement, isProSubscriber } from '@/lib/billing/entitlement-store';
import { activateFromCheckoutSession } from '@/lib/billing/subscription-events';
import { createProCheckoutSession, getCheckoutSession } from '@/lib/billing/stripe-checkout';

function request(body: unknown): Request {
return new Request('http://localhost/api/workspace/export', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
}

describe('POST /api/workspace/export', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('returns 402 with a Stripe checkout session when the caller is not Pro', async () => {
vi.mocked(isProSubscriber).mockResolvedValue(false);
vi.mocked(getEntitlement).mockResolvedValue(null);

const response = await POST(
request({
projectName: 'workspace-pack',
files: { 'README.md': '# workspace-pack\n' },
}),
);
const body = await response.json();

expect(response.status).toBe(402);
expect(body).toEqual({
error: 'Workspace ZIP exports require Pro. Upgrade to continue.',
code: 'payment_required',
upgradeRequired: true,
plan: 'free',
checkoutUrl: 'https://checkout.stripe.com/c/pay/cs_test_workspace_zip',
sessionId: 'cs_test_workspace_zip',
retryable: true,
verificationUrl: '/api/billing/activate',
});
expect(createProCheckoutSession).toHaveBeenCalledWith({
annual: false,
customerEmail: undefined,
flow: 'acquisition',
});
});

it('returns a ZIP attachment for Pro callers', async () => {
vi.mocked(isProSubscriber).mockResolvedValue(true);

const response = await POST(
request({
projectName: 'workspace-pack',
files: {
'README.md': '# workspace-pack\n',
'src/index.ts': "console.log('ok');\n",
},
}),
);

expect(response.status).toBe(200);
expect(response.headers.get('content-type')).toBe('application/zip');
expect(response.headers.get('content-disposition')).toContain('workspace-pack.zip');
expect(new Uint8Array(await response.arrayBuffer()).slice(0, 4)).toEqual(
new Uint8Array([0x50, 0x4b, 0x03, 0x04]),
);
expect(createProCheckoutSession).not.toHaveBeenCalled();
});

it('verifies a paid checkout session and sets the billing cookie before downloading', async () => {
vi.mocked(isProSubscriber).mockResolvedValue(false);
vi.mocked(getEntitlement).mockResolvedValue(null);

const response = await POST(
request({
projectName: 'workspace-pack',
files: { 'README.md': '# workspace-pack\n' },
sessionId: 'cs_test_paid_workspace_zip',
}),
);

expect(response.status).toBe(200);
expect(response.headers.get('set-cookie')).toContain('er_billing_email=');
expect(getCheckoutSession).toHaveBeenCalledWith('cs_test_paid_workspace_zip');
expect(activateFromCheckoutSession).toHaveBeenCalled();
expect(createProCheckoutSession).not.toHaveBeenCalled();
});
});
4 changes: 4 additions & 0 deletions apps/web/src/app/api/billing/status/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export async function GET(req: NextRequest) {
agentDispatch: false,
apiAccess: false,
chatDailyLimit: FREE_CHAT_DAILY_LIMIT,
workspaceZipExport: false,
refineryDatasetAccess: false,
},
routing: resolvePaidTierRouting(false),
renewalEligible: false,
Expand All @@ -39,6 +41,8 @@ export async function GET(req: NextRequest) {
agentDispatch: false,
apiAccess: false,
chatDailyLimit: FREE_CHAT_DAILY_LIMIT,
workspaceZipExport: false,
refineryDatasetAccess: false,
},
routing,
renewalEligible: Boolean(entitlement?.stripeCustomerId || email),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';

vi.mock('@/lib/billing/billing-context', () => ({
BILLING_EMAIL_COOKIE: 'er_billing_email',
resolveTrustedBillingEmail: vi.fn(async () => null),
}));

vi.mock('@/lib/billing/entitlement-store', () => ({
getEntitlement: vi.fn(async () => null),
isProSubscriber: vi.fn(async () => false),
}));

vi.mock('@/lib/billing/stripe-checkout', () => ({
createProCheckoutSession: vi.fn(async () => ({
sessionId: 'cs_test_refinery_dataset',
url: 'https://checkout.stripe.com/c/pay/cs_test_refinery_dataset',
})),
}));

vi.mock('@/lib/training-store', () => ({
getTrainingStatus: vi.fn(async () => ({
metadata: {
totalExamples: 2,
lastUpdated: '2026-09-08T00:00:00.000Z',
lastVideoUrl: 'https://youtu.be/auJzb1D-fag',
lastVideoTitle: 'Canon',
tuningTriggered: false,
tuningTriggeredAt: null,
tuningJobId: null,
videosProcessed: ['https://youtu.be/auJzb1D-fag'],
},
readyForTuning: false,
progress: 2,
nextMilestone: 25,
})),
readTrainingFile: vi.fn(async () => '{"contents":[{"role":"user","parts":[{"text":"Analyze this video: https://youtu.be/auJzb1D-fag"}]}]}\n'),
}));

import { GET } from '@/app/api/v1/refinery/dataset/route';
import { getEntitlement, isProSubscriber } from '@/lib/billing/entitlement-store';
import { createProCheckoutSession } from '@/lib/billing/stripe-checkout';

function request(query = ''): Request {
return new Request(`http://localhost/api/v1/refinery/dataset${query}`, {
method: 'GET',
});
}

describe('GET /api/v1/refinery/dataset', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('returns 402 with Stripe checkout details for free callers', async () => {
vi.mocked(isProSubscriber).mockResolvedValue(false);
vi.mocked(getEntitlement).mockResolvedValue(null);

const response = await GET(request());
const body = await response.json();

expect(response.status).toBe(402);
expect(body).toEqual({
error: 'Refinery dataset access requires Pro. Upgrade to continue.',
code: 'payment_required',
upgradeRequired: true,
plan: 'free',
checkoutUrl: 'https://checkout.stripe.com/c/pay/cs_test_refinery_dataset',
sessionId: 'cs_test_refinery_dataset',
retryable: true,
verificationUrl: '/api/billing/activate',
});
expect(createProCheckoutSession).toHaveBeenCalledWith({
annual: false,
customerEmail: undefined,
flow: 'acquisition',
});
});

it('returns the raw dataset as a download for Pro callers', async () => {
vi.mocked(isProSubscriber).mockResolvedValue(true);

const response = await GET(request('?download=1'));
const text = await response.text();

expect(response.status).toBe(200);
expect(response.headers.get('content-type')).toBe('application/x-ndjson; charset=utf-8');
expect(response.headers.get('content-disposition')).toContain('refinery-dataset.jsonl');
expect(response.headers.get('x-training-examples')).toBe('2');
expect(text).toContain('Analyze this video: https://youtu.be/auJzb1D-fag');
expect(createProCheckoutSession).not.toHaveBeenCalled();
});
});
53 changes: 53 additions & 0 deletions apps/web/src/app/api/v1/refinery/dataset/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { NextResponse } from 'next/server';
import { applyVerifiedBillingCookie, requireProFeatureAccess } from '@/lib/billing/pro-feature-gate';
import { getTrainingStatus, readTrainingFile } from '@/lib/training-store';

export const runtime = 'nodejs';

export async function GET(request: Request) {
const url = new URL(request.url);
const access = await requireProFeatureAccess(request, {
featureKey: 'refinery_dataset',
featureLabel: 'Refinery dataset access',
sessionId: url.searchParams.get('sessionId') ?? url.searchParams.get('session_id'),
});
if (!access.ok) {
return access.response;
}

const status = await getTrainingStatus();
if (url.searchParams.get('download') !== '1') {
const response = NextResponse.json({
dataset: {
totalExamples: status.metadata.totalExamples,
readyForTuning: status.readyForTuning,
progress: status.progress,
nextMilestone: status.nextMilestone,
lastUpdated: status.metadata.lastUpdated,
},
downloadUrl: '/api/v1/refinery/dataset?download=1',
});
applyVerifiedBillingCookie(response, access.signedBillingEmail);
return response;
}

const dataset = await readTrainingFile();
if (!dataset) {
return NextResponse.json(
{ error: 'dataset_not_found', code: 'dataset_not_found' },
{ status: 404 },
);
}

const response = new NextResponse(dataset, {
status: 200,
headers: {
'cache-control': 'no-store',
'content-disposition': 'attachment; filename="refinery-dataset.jsonl"',
'content-type': 'application/x-ndjson; charset=utf-8',
'x-training-examples': String(status.metadata.totalExamples),
},
});
applyVerifiedBillingCookie(response, access.signedBillingEmail);
return response;
}
71 changes: 71 additions & 0 deletions apps/web/src/app/api/workspace/export/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { NextResponse } from 'next/server';
import { applyVerifiedBillingCookie, requireProFeatureAccess } from '@/lib/billing/pro-feature-gate';
import { studioExportFilename } from '@/lib/studio-pipeline-status';
import { zipUtf8Files } from '@/lib/zip-store';

export const runtime = 'nodejs';

type WorkspaceExportRequest = {
projectName?: string;
files?: Record<string, string>;
sessionId?: string;
};

function normalizeFiles(files: WorkspaceExportRequest['files']): Record<string, string> | null {
if (!files || typeof files !== 'object') return null;

const normalized: Record<string, string> = {};
for (const [path, content] of Object.entries(files)) {
if (typeof content !== 'string') return null;
const trimmedPath = path.trim().replace(/\\/g, '/');
if (!trimmedPath || trimmedPath.startsWith('/')) return null;
if (trimmedPath.split('/').some((part) => !part || part === '.' || part === '..')) return null;
normalized[trimmedPath] = content;
}

return Object.keys(normalized).length > 0 ? normalized : null;
}

function quotedFilename(filename: string): string {
return filename.replace(/"/g, '');
}

export async function POST(request: Request) {
let body: WorkspaceExportRequest;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'invalid_json', code: 'invalid_json' }, { status: 400 });
}

const files = normalizeFiles(body.files);
if (!files) {
return NextResponse.json(
{ error: 'files_required', code: 'files_required' },
{ status: 400 },
);
}

const access = await requireProFeatureAccess(request, {
featureKey: 'workspace_export',
featureLabel: 'Workspace ZIP exports',
sessionId: body.sessionId,
});
if (!access.ok) {
return access.response;
}

const filename = studioExportFilename(body.projectName);
const zip = zipUtf8Files(files);
const response = new NextResponse(Buffer.from(zip), {
status: 200,
headers: {
'cache-control': 'no-store',
'content-disposition': `attachment; filename="${quotedFilename(filename)}"`,
'content-length': String(zip.byteLength),
'content-type': 'application/zip',
},
});
applyVerifiedBillingCookie(response, access.signedBillingEmail);
return response;
}
Loading