feat: let authors pay once per paper instead of subscribing

Most authors use the service for one paper a few times a year, so a
subscription does not fit. Add cheap one-time options (Paper pack, Extra
repository, Live updates, Extended expiration, Never expire), cap free
dated expiration at 5 months, keep cheaper subscriptions for heavy users,
and make every new conference a paid review package in three sizes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Thomas DurieuxandClaude Opus 5.5 committed 2026-11-12 16:04:31 +00:00
1 parent 643f4b87e9
commit d25e5336ce
28 files changed
+1237 -261

No files matched your search

+48 -5
View File
@@ -1,13 +1,14 @@
import * as express from "express";
import { randomBytes } from "crypto";
import { createHash, randomBytes } from "crypto";
import { ensureAuthenticated } from "./connection";
import { getUser, handleError } from "./route-utils";
import config from "../../config";
import { BillingAccount, BillingGrant } from "../../core/billing/models";
import { billingOrigin, billingPlans, requireBilling } from "../../core/billing/config";
import { billingOrigin, billingPlans, requireBilling, PACK_PLANS, REPO_NEVER_UNTIL } from "../../core/billing/config";
import { createCheckout, stripeClient, fulfillCheckout, syncSubscription } from "../../core/billing/stripe";
import { saveBillingDraft, getBillingDraft } from "../../core/billing/drafts";
import { allowance } from "../../core/billing/quotas";
import { allowance, usableGrant } from "../../core/billing/quotas";
import RepositoryModel from "../../core/model/anonymizedRepositories/anonymizedRepositories.model";
import { receiveBillingEvent, billingFailure } from "../../core/billing/events";
import { createLogger } from "../../core/logger";
@@ -34,6 +35,44 @@ async function displayedPrice(id: string) {
priceCache.set(id, { expires: Date.now() + 60_000, value });
return value;
}
type GrantRow = { _id?: unknown; planId?: string | null; scope?: string | null; status?: string | null; until?: Date | null;
cancelAtPeriodEnd?: boolean | null; revoked?: boolean | null; revocationReason?: string | null; purchasedAt?: Date | null; priceId?: string | null };
// A readable purchase list: pack parts grouped, internal IDs and the
// year-9999 "no end" sentinel hidden, statuses reduced to a few states.
export async function purchaseHistory(grants: GrantRow[], now = new Date()) {
const state = (g: GrantRow) => g.revoked ? (g.revocationReason === "dispute" ? "disputed" : "refunded")
: g.status === "past_due" ? "overdue" : usableGrant(g, now) ? "active" : "ended";
const until = (g: GrantRow) => g.until && g.until.getTime() < REPO_NEVER_UNTIL.getTime() ? g.until : null;
const groups = new Map<string, GrantRow[]>();
for (const grant of grants) {
const id = String(grant._id);
const key = /^cs_.+:(repo_slot|author_pass|repo_extend)$/.test(id) && grants.filter(g => String(g._id).startsWith(id.split(":")[0] + ":")).length === PACK_PLANS.length
? id.split(":")[0] : id;
groups.set(key, [...(groups.get(key) || []), grant]);
}
const purchases = [];
for (const [key, rows] of groups) {
const first = rows[0];
const pack = rows.length > 1;
let amount: number | null = null, currency: string | null = null, interval: string | null = null;
if (first.priceId) {
try { const price = await displayedPrice(first.priceId); amount = price.unit_amount; currency = price.currency; interval = price.recurring?.interval || null; } catch { /* Price display is optional. */ }
}
const [kind, target] = String(first.scope || "").split(/:(.*)/s);
const states = rows.map(state);
purchases.push({
id: createHash("sha256").update(key).digest("hex").slice(0, 12),
planId: pack ? "repo_pack" : first.planId, recurring: ["author_monthly", "author_annual"].includes(first.planId || ""),
repoId: kind === "repo" ? target : null, conference: kind === "conference" ? target : null,
status: states.includes("disputed") ? "disputed" : states.includes("refunded") ? "refunded" : states.includes("overdue") ? "overdue"
: states.includes("active") ? "active" : "ended",
until: pack ? null : until(first), purchasedAt: first.purchasedAt || null, cancelAtPeriodEnd: !!first.cancelAtPeriodEnd, amount, currency, interval,
parts: pack ? rows.map(g => ({ planId: g.planId, until: until(g), status: state(g) })) : [],
});
}
return purchases.sort((a, b) => Number(b.status === "active" || b.status === "overdue") - Number(a.status === "active" || a.status === "overdue")
|| (b.purchasedAt?.getTime() || 0) - (a.purchasedAt?.getTime() || 0));
}
const router = express.Router();
router.use(ensureAuthenticated);
router.get("/", async (req, res) => {
@@ -42,14 +81,18 @@ router.get("/", async (req, res) => {
req.session.billingCSRF ||= randomBytes(32).toString("hex");
await new Promise<void>((resolve, reject) => req.session.save(error => error ? reject(error) : resolve()));
const account = await BillingAccount.findById(user.id).lean();
const grants = await BillingGrant.find({ owner: user.id }).select("planId scope status until cancelAtPeriodEnd revoked").lean();
const grants = await BillingGrant.find({ owner: user.id }).select("planId scope status until cancelAtPeriodEnd revoked revocationReason purchasedAt priceId").lean();
const repositories = config.BILLING_ENABLED ? await RepositoryModel.find({ owner: user.id, status: { $ne: "removed" } })
.select("repoId status options.expirationMode options.expirationDate").sort({ anonymizeDate: -1 }).limit(500).lean() : [];
const plans = config.BILLING_ENABLED ? await Promise.all(billingPlans().filter(p => p.priceId).map(async p => {
const price = await displayedPrice(p.priceId);
return { id: p.id, name: p.name, description: p.description, repositories: p.repositories, storage: p.storage,
amount: price.unit_amount, currency: price.currency, interval: price.recurring?.interval, intervalCount: price.recurring?.interval_count };
})) : [];
res.set("Cache-Control", "no-store").json({ enabled: config.BILLING_ENABLED, csrf: req.session.billingCSRF, plans, checkoutEnabled: config.BILLING_CHECKOUT_ENABLED,
res.set("Cache-Control", "no-store").json({ enabled: config.BILLING_ENABLED, csrf: req.session.billingCSRF, plans, checkoutEnabled: config.BILLING_CHECKOUT_ENABLED, freeExpirationMonths: config.FREE_EXPIRATION_MONTHS,
grants: grants.map(g => ({ planId: g.planId, scope: g.scope, status: g.revoked ? "revoked" : g.status, until: g.until, cancelAtPeriodEnd: g.cancelAtPeriodEnd })),
purchases: config.BILLING_ENABLED ? await purchaseHistory(grants) : [],
repositories: repositories.map(r => ({ repoId: r.repoId, status: r.status, expirationMode: r.options?.expirationMode, expirationDate: r.options?.expirationDate })),
portal: !!account?.customerId, allowance: config.BILLING_ENABLED ? await allowance(user.id) : null });
} catch (error) { handleError(error, res, req); }
});
+36 -24
View File
@@ -1,5 +1,5 @@
import config from "../../config";
import { billingError } from "../../core/billing/config";
import { billingError, billingPlans, isConferencePlan } from "../../core/billing/config";
import * as express from "express";
import AnonymousError from "../../core/AnonymousError";
import Conference from "../../core/Conference";
@@ -13,15 +13,26 @@ const router = express.Router();
// user needs to be connected for all user API
router.use(ensureAuthenticated);
const plans = [
{ id: "free_conference", name: "Free", pricePerRepo: 0, storagePerRepo: -1,
description: "<li>Uses each author's allowance</li><li>Conference dashboard</li>" },
{ id: "conference", name: "Review package", pricePerRepo: 0, storagePerRepo: config.PAID_CONFERENCE_STORAGE,
description: `<li>Up to ${config.PAID_CONFERENCE_REPOSITORIES} repositories</li><li>Up to 180 days</li><li>Prepaid at checkout</li>` },
];
// The free plan plus one review package per venue size, smallest first.
function conferencePlans() {
return [
{ id: "free_conference", name: "Free", pricePerRepo: 0, storagePerRepo: -1, repositories: 0, priceId: "",
description: "<li>Uses each author's allowance</li><li>Conference dashboard</li>" },
...billingPlans().filter(p => isConferencePlan(p.id)).map(p => ({ id: p.id as string, name: p.name, pricePerRepo: 0,
storagePerRepo: p.storage, repositories: p.repositories, priceId: p.priceId,
description: `<li>Up to ${p.repositories} repositories</li><li>Up to 180 days</li><li>Prepaid at checkout</li>` })),
];
}
// With billing enabled every new conference is a paid review package; the free
// plan is only offered on deployments without billing.
export function offeredConferencePlans() {
if (!config.BILLING_ENABLED) return conferencePlans().filter(p => p.id === "free_conference").map(({ priceId: _, ...p }) => p);
return conferencePlans().filter(p => isConferencePlan(p.id) && p.priceId).map(({ priceId: _, ...p }) => p);
}
router.get("/plans", async (req: express.Request, res: express.Response) => {
res.json(config.BILLING_ENABLED && config.STRIPE_CONFERENCE_PRICE ? plans : plans.filter(p => p.id === "free_conference"));
res.json(offeredConferencePlans());
});
router.get("/", async (req: express.Request, res: express.Response) => {
@@ -78,14 +89,16 @@ function validateConferenceForm(conf: any, isNew: boolean) {
object: conf,
httpStatus: 400,
});
if (!conf.plan || plans.filter((p) => p.id == conf.plan.planID).length != 1)
if (!conf.plan || conferencePlans().filter((p) => p.id == conf.plan.planID).length != 1)
throw new AnonymousError("invalid_plan", {
object: conf,
httpStatus: 400,
});
if (!Number.isFinite(new Date(conf.startDate).getTime()) || !Number.isFinite(new Date(conf.endDate).getTime())) throw billingError("conf_start_date_invalid");
if (conf.plan.planID === "conference" && ((isNew && (!config.BILLING_ENABLED || !config.STRIPE_CONFERENCE_PRICE)) || new Date(conf.endDate).getTime() - new Date(conf.startDate).getTime() > 180 * 86400_000)) throw billingError("billing_invalid_review_window");
const plan = plans.filter((p) => p.id == conf.plan.planID)[0];
if (isConferencePlan(conf.plan.planID) && ((isNew && (!config.BILLING_ENABLED || !offeredConferencePlans().some(p => p.id === conf.plan.planID))) || new Date(conf.endDate).getTime() - new Date(conf.startDate).getTime() > 180 * 86400_000)) throw billingError("billing_invalid_review_window");
// A new conference can only use a plan that is offered: paid when billing is on.
if (isNew && !offeredConferencePlans().some(p => p.id === conf.plan.planID)) throw new AnonymousError("invalid_plan", { object: conf, httpStatus: 400 });
const plan = conferencePlans().filter((p) => p.id == conf.plan.planID)[0];
if (plan.pricePerRepo > 0) {
const billing = conf.billing;
if (!billing)
@@ -135,7 +148,7 @@ export function applyConferenceForm(
model.name = body.name;
model.startDate = new Date(body.startDate);
model.endDate = new Date(body.endDate);
if (isNew) model.status = body.plan?.planID === "conference" ? "pending_payment" : "ready";
if (isNew) model.status = isConferencePlan(body.plan?.planID) ? "pending_payment" : "ready";
model.url = body.url;
model.options = body.options;
if (isNew) model.repositories = [];
@@ -161,10 +174,10 @@ router.post(
}
if (req.params.conferenceID) {
if (req.body.plan?.planID !== model.plan.planID) throw billingError("billing_plan_change_not_supported");
if (model.plan.planID === "conference" && (new Date(req.body.startDate).getTime() !== model.startDate.getTime() || new Date(req.body.endDate).getTime() !== model.endDate.getTime())) throw billingError("billing_review_window_locked");
if (isConferencePlan(model.plan.planID) && (new Date(req.body.startDate).getTime() !== model.startDate.getTime() || new Date(req.body.endDate).getTime() !== model.endDate.getTime())) throw billingError("billing_review_window_locked");
}
// Historical conference plans remain editable without being offered for purchase.
const legacyPlan = req.params.conferenceID && !plans.some(p => p.id === model.plan.planID);
const legacyPlan = req.params.conferenceID && !offeredConferencePlans().some(p => p.id === model.plan.planID);
validateConferenceForm(legacyPlan ? { ...req.body, plan: { planID: "free_conference" } } : req.body, !req.params.conferenceID);
applyConferenceForm(model, req.body, !req.params.conferenceID);
@@ -172,17 +185,11 @@ router.post(
model.owners.push(user.model.id);
model.conferenceID = req.body.conferenceID;
const chosen = conferencePlans().find((p) => p.id == req.body.plan.planID)!;
model.plan = {
planID: req.body.plan.planID,
pricePerRepository: plans.filter(
(p) => p.id == req.body.plan.planID
)[0].pricePerRepo,
quota: {
size: plans.filter((p) => p.id == req.body.plan.planID)[0]
.storagePerRepo,
file: 0,
repository: req.body.plan.planID === "conference" ? config.PAID_CONFERENCE_REPOSITORIES : 0,
},
planID: chosen.id,
pricePerRepository: chosen.pricePerRepo,
quota: { size: chosen.storagePerRepo, file: 0, repository: chosen.repositories },
};
if (req.body.billing)
@@ -232,6 +239,9 @@ router.get(
});
const user = await getUser(req);
const conference = new Conference(data);
// Authors see whether the conference pays for their repository's hosting.
const now = new Date();
const hosting = isConferencePlan(data.plan?.planID) && data.status === "ready" && data.startDate <= now && data.endDate > now;
try {
isOwnerOrAdmin(conference.ownerIDs, user);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -239,6 +249,7 @@ router.get(
o.repositories = (await conference.repositories()).map((r) =>
r.toJSON()
);
o.hosting = hosting;
res.json(o);
} catch {
return res.json({
@@ -248,6 +259,7 @@ router.get(
startDate: conference.startDate,
endDate: conference.endDate,
options: conference.options,
hosting,
});
}
} catch (error) {
+15 -7
View File
@@ -1,6 +1,6 @@
import Repository from "../../core/Repository";
import { sourceStorageSize } from "../../core/source/Source";
import { neverExpirationDeadline, validateBillingExpiration } from "../../core/billing/expiration";
import { maximumExpiration, neverExpirationDeadline, validateBillingExpiration } from "../../core/billing/expiration";
import config from "../../config";
import { assertConferenceAdmission, reserveRepository } from "../../core/billing/quotas";
import { resetOwnerAccessAlerts } from "../../core/owner-notifications";
@@ -206,10 +206,17 @@ router.post(
const user = await getUser(req);
isOwnerCoauthorOrAdmin(repo, user);
const newExpiration = extendExpirationDate(
const maximum = await maximumExpiration(String(repo.model.owner), repo.repoId, repo.model.conference);
let newExpiration = extendExpirationDate(
repo.model.options.expirationDate
);
validateBillingExpiration({ ...repo.model.options, expirationDate: newExpiration });
// Extend as far as the repository's limit allows, never shortening it.
if (config.BILLING_ENABLED && newExpiration > maximum) {
const current = repo.model.options.expirationDate && new Date(repo.model.options.expirationDate);
if (current && current >= maximum) throw new AnonymousError("expiration_limit_reached", { httpStatus: 402 });
newExpiration = maximum;
}
validateBillingExpiration({ ...repo.model.options, expirationDate: newExpiration }, maximum);
const reactivating = repo.status === RepositoryStatus.EXPIRED;
if (reactivating) await assertConferenceAdmission(String(repo.model.owner), repo.repoId, repo.model.conference);
const updates: Record<string, Date | string | null> = {
@@ -571,11 +578,12 @@ router.post(
// Keep proposed settings separate until cleanup passes the persisted fences.
const proposed = new AnonymizedRepositoryModel(repo.model.toObject());
if (repo.model.billingManaged) validateBillingExpiration(repoUpdate.options);
if (repo.model.billingManaged) validateBillingExpiration(repoUpdate.options,
await maximumExpiration(String(repo.model.owner), repo.repoId, repoUpdate.conference), repo.model.options.expirationDate);
if (config.BILLING_ENABLED && repoUpdate.options.expirationMode === "never" &&
(repo.model.options.expirationMode !== "never" || repo.model.billingNeverExpiresUntil)) {
proposed.billingNeverExpiresUntil = await neverExpirationDeadline(String(repo.model.owner),
repo.model.options.expirationMode === "never" ? repo.model.billingNeverExpiresUntil : undefined);
repo.model.options.expirationMode === "never" ? repo.model.billingNeverExpiresUntil : undefined, repo.repoId);
} else if (repoUpdate.options.expirationMode !== "never") {
proposed.billingNeverExpiresUntil = undefined;
}
@@ -801,9 +809,9 @@ router.post("/", async (req, res) => {
repo.owner = user.id;
repo.githubAccess = selectedAccess.binding;
validateBillingExpiration(repoUpdate.options);
validateBillingExpiration(repoUpdate.options, await maximumExpiration(user.id, repoUpdate.repoId, repoUpdate.conference));
if (repoUpdate.options.expirationMode === "never") {
repo.billingNeverExpiresUntil = await neverExpirationDeadline(user.id);
repo.billingNeverExpiresUntil = await neverExpirationDeadline(user.id, undefined, repoUpdate.repoId);
}
updateRepoModel(repo, repoUpdate);
repo.source.type = "GitHubStream";