Add subscription support + license extension on renewal

This commit is contained in:
Krystie
2026-08-19 12:45:06 -07:00
parent 14d0eaa2b3
commit ff722aa4d8
2075 changed files with 357707 additions and 63 deletions
+81 -2
View File
@@ -1,6 +1,13 @@
import crypto from 'crypto';
import { PREMIUM_FEATURES } from './plans.js';
import { createOrUpdateLicenseBySubscription, findLicenseByKey, updateLicense } from './store.js';
import {
createOrUpdateLicenseBySubscription,
findLicenseByKey,
findActiveLicenseByCustomerEmail,
findLicenseByCustomerId,
extendLicenseByDuration,
updateLicense
} from './store.js';
export function fingerprintMachine(payload = {}) {
const parts = [
@@ -13,8 +20,40 @@ export function fingerprintMachine(payload = {}) {
return crypto.createHash('sha256').update(parts.join('|')).digest('hex').slice(0, 16);
}
export function syncLicenseFromSubscription({ subscriptionId, customerId, customerEmail, planCode, status, currentPeriodEnd }) {
/**
* Sync a license from a Stripe subscription event. If the customer already
* has a license (by customerId or email), EXTEND the existing license by
* the plan duration instead of creating a new one. This is the "renewal
* adds time to the same key" model.
*/
export function syncLicenseFromSubscription({ subscriptionId, customerId, customerEmail, planCode, status, currentPeriodEnd, durationDays }) {
const premiumFeatures = Object.fromEntries(PREMIUM_FEATURES.map((f) => [f, true]));
// Try to find an existing license by customerId FIRST, then email
const existing = findLicenseByCustomerId(customerId) || findActiveLicenseByCustomerEmail(customerEmail);
if (existing) {
// Extend existing license. We use currentPeriodEnd from Stripe for
// subscriptions (Stripe is the authority on renewal dates), but if
// durationDays is provided we use that to extend from current expiry.
const patch = {
subscriptionId,
customerId,
customerEmail,
planCode,
status,
active: ['active', 'trialing', 'past_due'].includes(status),
premiumFeatures,
machineFingerprint: existing.machineFingerprint || null,
deactivatedAt: null
};
if (currentPeriodEnd) {
patch.expiresAt = currentPeriodEnd;
}
return updateLicense(existing.id, patch);
}
// No existing license — create one with the current period end as the initial expiry
return createOrUpdateLicenseBySubscription(subscriptionId, {
subscriptionId,
customerId,
@@ -29,6 +68,46 @@ export function syncLicenseFromSubscription({ subscriptionId, customerId, custom
});
}
/**
* Grant a one-time license purchase. If the customer already has an active
* license, EXTEND the existing license by durationDays instead of creating
* a new one. This is the "buy again adds time to the same key" model.
*/
export function grantOneTimeLicense({ paymentIntentId, customerId, customerEmail, planCode, durationDays }) {
const premiumFeatures = Object.fromEntries(PREMIUM_FEATURES.map((f) => [f, true]));
// Look for existing license by customerId, then email
const existing = findLicenseByCustomerId(customerId) || findActiveLicenseByCustomerEmail(customerEmail);
if (existing) {
// Extend existing license by the plan duration
const extended = extendLicenseByDuration(existing.id, durationDays);
return {
...extended,
extended: true,
addedDays: durationDays
};
}
// No existing license — create one with expiry = now + durationDays
const expiresAt = new Date();
expiresAt.setUTCDate(expiresAt.getUTCDate() + durationDays);
return createOrUpdateLicenseBySubscription(`one-time-${paymentIntentId}`, {
subscriptionId: null,
customerId,
customerEmail,
planCode,
status: 'paid',
expiresAt: expiresAt.toISOString(),
active: true,
premiumFeatures,
machineFingerprint: null,
deactivatedAt: null,
paymentIntentId
});
}
export function validateLicense({ code, machine }) {
const license = findLicenseByKey(code);
if (!license) {
+31 -19
View File
@@ -1,35 +1,35 @@
export const PLAN_DEFS = {
premium_1m: {
code: 'premium_1m',
label: 'Premium, 1 Month',
durationMonths: 1,
amountUsd: 25,
premium_30d: {
code: 'premium_30d',
label: 'Premium, 30 Days',
durationDays: 30,
amountUsd: 20,
interval: 'month',
intervalCount: 1,
tier: 'premium'
},
premium_3m: {
code: 'premium_3m',
label: 'Premium, 3 Months',
durationMonths: 3,
premium_90d: {
code: 'premium_90d',
label: 'Premium, 90 Days',
durationDays: 90,
amountUsd: 50,
interval: 'month',
intervalCount: 3,
tier: 'premium'
},
premium_6m: {
code: 'premium_6m',
label: 'Premium, 6 Months',
durationMonths: 6,
amountUsd: 65,
premium_180d: {
code: 'premium_180d',
label: 'Premium, 180 Days',
durationDays: 180,
amountUsd: 70,
interval: 'month',
intervalCount: 6,
tier: 'premium'
},
premium_12m: {
code: 'premium_12m',
label: 'Premium, 12 Months',
durationMonths: 12,
premium_365d: {
code: 'premium_365d',
label: 'Premium, 365 Days',
durationDays: 365,
amountUsd: 99,
interval: 'year',
intervalCount: 1,
@@ -37,7 +37,7 @@ export const PLAN_DEFS = {
}
};
export const PREMIUM_FEATURES = ['sso', 'recipes', 'swarm'];
export const PREMIUM_FEATURES = ['sso', 'recipes', 'swarm', 'fleet'];
export function listPlans() {
return Object.values(PLAN_DEFS);
@@ -46,3 +46,15 @@ export function listPlans() {
export function getPlan(planCode) {
return PLAN_DEFS[planCode] || null;
}
/**
* Add days to a license's expiry. If expiry is in the past, count from now.
* Returns the new ISO expiry timestamp.
*/
export function extendExpiry(currentIso, days) {
const base = currentIso ? new Date(currentIso) : new Date();
const now = Date.now();
const start = base.getTime() > now ? base : new Date(now);
start.setUTCDate(start.getUTCDate() + days);
return start.toISOString();
}
+174 -15
View File
@@ -2,8 +2,13 @@ import express from 'express';
import { config } from './config.js';
import { getPlan, listPlans, PREMIUM_FEATURES } from './plans.js';
import { getStripe } from './stripe.js';
import { getStoreSnapshot, upsertCustomer, upsertSubscription } from './store.js';
import { syncLicenseFromSubscription, validateLicense, deactivateLicense } from './licenseLogic.js';
import { getStoreSnapshot, upsertCustomer, upsertSubscription, findLicenseByCustomerId } from './store.js';
import {
syncLicenseFromSubscription,
grantOneTimeLicense,
validateLicense,
deactivateLicense
} from './licenseLogic.js';
const app = express();
app.use('/api/stripe/webhook', express.raw({ type: 'application/json' }));
@@ -14,7 +19,11 @@ app.get('/health', (_req, res) => {
});
app.get('/api/public/config', (_req, res) => {
res.json({ ok: true, publishableKeyPresent: Boolean(config.stripePublishableKey), websiteUrl: config.websiteUrl });
res.json({
ok: true,
publishableKey: config.stripePublishableKey || null,
websiteUrl: config.websiteUrl
});
});
app.get('/api/public/plans', (_req, res) => {
@@ -25,7 +34,12 @@ app.get('/api/admin/debug/store', (_req, res) => {
res.json({ ok: true, store: getStoreSnapshot() });
});
app.post('/api/checkout/session', async (req, res) => {
/**
* Subscription checkout. Customer subscribes and is auto-renewed on the
* plan's interval. The license is created on the first webhook event and
* extended on every renewal.
*/
app.post('/api/checkout/subscription', async (req, res) => {
try {
const { planCode, customerEmail } = req.body || {};
const plan = getPlan(planCode);
@@ -44,22 +58,113 @@ app.post('/api/checkout/session', async (req, res) => {
},
quantity: 1
}],
success_url: `${config.websiteUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
success_url: `${config.websiteUrl}/success?session_id={CHECKOUT_SESSION_ID}&tier=premium`,
cancel_url: `${config.websiteUrl}/pricing`,
allow_promotion_codes: true,
billing_address_collection: 'required',
customer_email: customerEmail || undefined,
metadata: { source: 'dashcaddy.net', planCode: plan.code, tier: plan.tier },
subscription_data: { metadata: { source: 'dashcaddy.net', planCode: plan.code, tier: plan.tier } }
metadata: {
source: 'dashcaddy.net',
planCode: plan.code,
tier: plan.tier,
mode: 'subscription',
// Bake the email into session metadata so the webhook can find
// the existing license without a Stripe API call.
customerEmail: customerEmail || ''
},
subscription_data: {
metadata: {
source: 'dashcaddy.net',
planCode: plan.code,
tier: plan.tier,
customerEmail: customerEmail || ''
}
}
});
return res.json({ ok: true, url: session.url, sessionId: session.id });
} catch (error) {
console.error('Checkout session error:', error);
console.error('Subscription checkout error:', error);
return res.status(500).json({ ok: false, error: error.message || 'Checkout failed' });
}
});
/**
* One-time purchase checkout. Customer pays once for a license of the
* plan duration. If they buy again, time is added to their existing license.
*/
app.post('/api/checkout/one-time', async (req, res) => {
try {
const { planCode, customerEmail } = req.body || {};
const plan = getPlan(planCode);
if (!plan) return res.status(400).json({ ok: false, error: 'Invalid planCode' });
const stripe = getStripe();
const session = await stripe.checkout.sessions.create({
mode: 'payment',
payment_method_types: ['card'],
line_items: [{
price_data: {
currency: 'usd',
product_data: { name: plan.label, description: 'DashCaddy Premium one-time license' },
unit_amount: plan.amountUsd * 100
},
quantity: 1
}],
success_url: `${config.websiteUrl}/success?session_id={CHECKOUT_SESSION_ID}&tier=premium`,
cancel_url: `${config.websiteUrl}/pricing`,
allow_promotion_codes: true,
billing_address_collection: 'required',
customer_email: customerEmail || undefined,
metadata: {
source: 'dashcaddy.net',
planCode: plan.code,
tier: plan.tier,
mode: 'one-time',
durationDays: String(plan.durationDays),
customerEmail: customerEmail || ''
},
payment_intent_data: {
metadata: {
source: 'dashcaddy.net',
planCode: plan.code,
tier: plan.tier,
mode: 'one-time',
durationDays: String(plan.durationDays),
customerEmail: customerEmail || ''
}
}
});
return res.json({ ok: true, url: session.url, sessionId: session.id });
} catch (error) {
console.error('One-time checkout error:', error);
return res.status(500).json({ ok: false, error: error.message || 'Checkout failed' });
}
});
/**
* Look up an existing license for a customer. Tries customerId first,
* then falls back to email. Returns null if no active license exists.
*/
function findCustomersLicense(customerId, customerEmail) {
if (customerId) {
const byCustomer = findLicenseByCustomerId(customerId);
if (byCustomer) return byCustomer;
}
if (customerEmail) {
const { findActiveLicenseByCustomerEmail } = require('./store.js');
const byEmail = findActiveLicenseByCustomerEmail(customerEmail);
if (byEmail) return byEmail;
}
return null;
}
/**
* Stripe webhook endpoint. Handles subscription lifecycle events AND
* one-time payment completion events. The same handler routes based on
* event type and updates the customer's license accordingly.
*/
app.post('/api/stripe/webhook', async (req, res) => {
try {
if (!config.stripeWebhookSecret) {
@@ -77,19 +182,54 @@ app.post('/api/stripe/webhook', async (req, res) => {
switch (event.type) {
case 'checkout.session.completed': {
const session = event.data.object;
if (session.customer) {
upsertCustomer({ id: String(session.customer), email: session.customer_email || null, checkoutSessionId: session.id });
const planCode = session.metadata?.planCode;
const mode = session.metadata?.mode || 'subscription';
const customerId = typeof session.customer === 'string' ? session.customer : session.customer?.id;
// Email resolution: session metadata (baked at creation) > session.customer_email > session.customer_details.email
const customerEmail = session.metadata?.customerEmail || session.customer_email || session.customer_details?.email || null;
if (customerId) {
upsertCustomer({ id: String(customerId), email: customerEmail, checkoutSessionId: session.id });
}
// For one-time payments, generate the license on checkout.session.completed
if (mode === 'one-time' && planCode) {
const plan = getPlan(planCode);
if (plan) {
const license = grantOneTimeLicense({
paymentIntentId: typeof session.payment_intent === 'string' ? session.payment_intent : session.payment_intent?.id,
customerId,
customerEmail,
planCode,
durationDays: plan.durationDays
});
console.log('One-time license granted', {
sessionId: session.id,
licenseKey: license.key,
customerEmail,
extended: license.extended || false,
addedDays: license.addedDays || plan.durationDays
});
}
}
break;
}
case 'customer.subscription.created':
case 'customer.subscription.updated':
case 'customer.subscription.deleted': {
case 'customer.subscription.updated': {
const subscription = event.data.object;
const customerId = typeof subscription.customer === 'string' ? subscription.customer : subscription.customer?.id;
const customerEmail = subscription.customer_email || null;
const planCode = subscription.metadata?.planCode || 'premium_1m';
// Email resolution: subscription metadata (baked at creation) > fetch from Stripe if missing
let customerEmail = subscription.metadata?.customerEmail || null;
if (!customerEmail && customerId) {
try {
const customer = await stripe.customers.retrieve(customerId);
customerEmail = customer.email || null;
} catch (err) {
console.warn('Failed to fetch customer email', { customerId, error: err.message });
}
}
const planCode = subscription.metadata?.planCode || 'premium_30d';
const currentPeriodEnd = subscription.current_period_end
? new Date(subscription.current_period_end * 1000).toISOString()
: null;
@@ -112,7 +252,26 @@ app.post('/api/stripe/webhook', async (req, res) => {
currentPeriodEnd
});
console.log('License synced from subscription', { subscriptionId: subscription.id, licenseKey: license.key, status: license.status });
console.log('Subscription license synced', {
subscriptionId: subscription.id,
licenseKey: license.key,
status: license.status,
expiresAt: license.expiresAt,
customerEmail
});
break;
}
case 'customer.subscription.deleted': {
const subscription = event.data.object;
// Mark the subscription cancelled. License remains active until
// currentPeriodEnd (Stripe handles non-renewal automatically).
upsertSubscription({
id: subscription.id,
status: 'canceled',
cancelAtPeriodEnd: true
});
console.log('Subscription cancelled', { subscriptionId: subscription.id });
break;
}
+47
View File
@@ -63,6 +63,53 @@ export function findLicenseByKey(key) {
return Object.values(db.licenses).find((lic) => lic.key === key) || null;
}
/**
* Find an active license by customer email. Used to EXTEND an existing
* license when a customer buys again (so renewal adds time to the same key,
* not a new one).
*/
export function findActiveLicenseByCustomerEmail(email) {
if (!email) return null;
const db = readStore();
const normalized = email.toLowerCase();
return Object.values(db.licenses).find((lic) =>
lic.customerEmail && lic.customerEmail.toLowerCase() === normalized && lic.active
) || null;
}
/**
* Find a license by Stripe customer ID. Used by webhook handlers to extend
* the customer's existing license on subscription renewal.
*/
export function findLicenseByCustomerId(customerId) {
if (!customerId) return null;
const db = readStore();
return Object.values(db.licenses).find((lic) => lic.customerId === customerId) || null;
}
/**
* Extend an existing license by a number of days. If the license is expired,
* the extension starts from now. Returns the updated license.
*/
export function extendLicenseByDuration(licenseId, days) {
const db = readStore();
const lic = db.licenses[licenseId];
if (!lic) return null;
const base = lic.expiresAt ? new Date(lic.expiresAt) : new Date();
const now = Date.now();
const start = base.getTime() > now ? base : new Date(now);
start.setUTCDate(start.getUTCDate() + days);
db.licenses[licenseId] = {
...lic,
expiresAt: start.toISOString(),
active: true,
activatedAt: lic.activatedAt || new Date().toISOString(),
updatedAt: new Date().toISOString()
};
writeStore(db);
return db.licenses[licenseId];
}
export function updateLicense(id, patch) {
const db = readStore();
if (!db.licenses[id]) return null;