From 6d5313d552f891192bba7fb1519209041ff6c271 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 23:50:19 +0000 Subject: [PATCH] Add Glint Pro billing on Stripe Checkout with Managed Payments Four new ops on the account function: checkout, confirm (back from checkout), portal and webhook. The webhook uses only the event id, re-reads the event and the subscription from Stripe and stores Stripe's current state, so it needs no signing secret. The account panel shows Upgrade and Manage billing when billing is on, and handles the return from checkout. Billing stays off until STRIPE_SECRET_KEY and STRIPE_PRICE_ID are set; until then the panel keeps the waitlist link. Privacy and terms pages describe the payment handling. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016tciSRcwDsHcLgxbSDvQgC --- CLAUDE.md | 4 +- api/_account.js | 36 +++- api/_billing.js | 308 ++++++++++++++++++++++++++++++++++ api/account.js | 7 +- docs/BACKEND.md | 5 + docs/GLINT-PRO-STATUS.md | 39 ++++- privacy/index.html | 4 +- scripts/regression-tests.mjs | 178 +++++++++++++++++++- src/features/account-panel.js | 81 ++++++++- src/features/account.js | 57 ++++++- terms/index.html | 2 +- 11 files changed, 689 insertions(+), 32 deletions(-) create mode 100644 api/_billing.js diff --git a/CLAUDE.md b/CLAUDE.md index a5f19df..68707b7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -111,10 +111,10 @@ v41 Iris turns the current design, the Interactive Tour, or the Before / After c ### Glint Pro groundwork: waitlist, analytics, accounts and AI credits Not a versioned release; groundwork for a paid plan (Glint Pro: hosted AI, lasting share links, sync). The studio itself stays free, and site copy must keep saying so. Glint Pro itself will be a later numbered release (v42 Junction shipped separately). -- **Accounts and hosted AI credits (Clerk + Neon; Supabase is gone).** Supabase was removed entirely, and cloud project and template sync, the community gallery (`gallery.js`) and live collaboration (`collab.js`) went with it; projects now live only in the browser. Sign-in is Clerk: `src/features/auth.js` loads Clerk's two browser bundles from the Clerk instance's own Frontend API (host decoded from the publishable key), so there is no Clerk package in the build; without a key no sign-in UI shows and nothing loads. It exports `getToken()`, `getUser()`, `onAuthChange()`, `openSignIn()`, `isConfigured()`; the header pill is a Sign in button or Clerk's own user button. The key is read at build time from `VITE_CLERK_PUBLISHABLE_KEY` or `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` (the name Clerk's Vercel Marketplace install adds; `vite.config.js` `envPrefix` lets it through). Server side, `api/_account.js` verifies the Clerk session token with `@clerk/backend` `verifyToken` (`CLERK_SECRET_KEY`, or `CLERK_JWT_KEY` for a networkless check) and keeps plans and credit counts in Neon Postgres through `@neondatabase/serverless` (`DATABASE_URL` or `POSTGRES_URL`). The schema is `api/_account-schema.js` (`subscriptions`, `ai_usage`, and the atomic `glint_use_credits(user, cost, free_limit, pro_limit)` function, keyed by Clerk's text user id); **the server installs it itself** the first time a query fails with a missing function or table, so there is no SQL to run by hand. `metered(kind, handler)` wraps the six hosted AI routes, spends credits before the model call (`CREDIT_COSTS`: 1 for text / vision / enhance / agent, 5 for an image) and refunds them when the route answers with an error. It answers `401 { code: 'sign_in' }` or `402 { code: 'no_credits' }`; a Clerk or database failure answers 503 (closed, not free). **Metering is on only when the deployment has a Clerk key and a database URL**; without them the routes behave as before. Limits default to 20 free and 500 Pro credits a month (`AI_FREE_CREDITS`, `AI_PRO_CREDITS`). `api/account.js` is one function for every account route (`?op=me` today; checkout, portal and the payment webhook go here, not in new files). In the editor, `src/features/account.js` `hostedFetch(path, body)` is the only way to call a hosted AI route: it adds the token, turns a sign-in or out-of-credits answer into a 501 (which every caller already treats as "use the person's own key") and shows why in a toast unless the person has their own key; the `#ai-credits` header chip shows credits left and opens the account panel (`src/features/account-panel.js`, `openAccountPanel()`, Cmd-K `account-open`: a native `` with the plan, credits left, what each request costs, the Pro waitlist link, Manage account and Sign out; it reads `account.js` `getAccount()` and redraws on `onAccountChange`; checkout and billing buttons go in its Pro box). **A new hosted AI route must be wrapped in `metered()` and called through `hostedFetch()`.** Tests use `ACCOUNT_STORE=memory` and sign throwaway Clerk-shaped tokens. Still to build: checkout + webhook (a merchant of record such as Lemon Squeezy), share link perks, real prices. +- **Accounts and hosted AI credits (Clerk + Neon; Supabase is gone).** Supabase was removed entirely, and cloud project and template sync, the community gallery (`gallery.js`) and live collaboration (`collab.js`) went with it; projects now live only in the browser. Sign-in is Clerk: `src/features/auth.js` loads Clerk's two browser bundles from the Clerk instance's own Frontend API (host decoded from the publishable key), so there is no Clerk package in the build; without a key no sign-in UI shows and nothing loads. It exports `getToken()`, `getUser()`, `onAuthChange()`, `openSignIn()`, `isConfigured()`; the header pill is a Sign in button or Clerk's own user button. The key is read at build time from `VITE_CLERK_PUBLISHABLE_KEY` or `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` (the name Clerk's Vercel Marketplace install adds; `vite.config.js` `envPrefix` lets it through). Server side, `api/_account.js` verifies the Clerk session token with `@clerk/backend` `verifyToken` (`CLERK_SECRET_KEY`, or `CLERK_JWT_KEY` for a networkless check) and keeps plans and credit counts in Neon Postgres through `@neondatabase/serverless` (`DATABASE_URL` or `POSTGRES_URL`). The schema is `api/_account-schema.js` (`subscriptions`, `ai_usage`, and the atomic `glint_use_credits(user, cost, free_limit, pro_limit)` function, keyed by Clerk's text user id); **the server installs it itself** the first time a query fails with a missing function or table, so there is no SQL to run by hand. `metered(kind, handler)` wraps the six hosted AI routes, spends credits before the model call (`CREDIT_COSTS`: 1 for text / vision / enhance / agent, 5 for an image) and refunds them when the route answers with an error. It answers `401 { code: 'sign_in' }` or `402 { code: 'no_credits' }`; a Clerk or database failure answers 503 (closed, not free). **Metering is on only when the deployment has a Clerk key and a database URL**; without them the routes behave as before. Limits default to 20 free and 500 Pro credits a month (`AI_FREE_CREDITS`, `AI_PRO_CREDITS`). `api/account.js` is one function for every account route (`?op=me` today; checkout, portal and the payment webhook go here, not in new files). In the editor, `src/features/account.js` `hostedFetch(path, body)` is the only way to call a hosted AI route: it adds the token, turns a sign-in or out-of-credits answer into a 501 (which every caller already treats as "use the person's own key") and shows why in a toast unless the person has their own key; the `#ai-credits` header chip shows credits left and opens the account panel (`src/features/account-panel.js`, `openAccountPanel()`, Cmd-K `account-open`: a native `` with the plan, credits left, what each request costs, the Pro waitlist link, Manage account and Sign out; it reads `account.js` `getAccount()` and redraws on `onAccountChange`; checkout and billing buttons go in its Pro box). **A new hosted AI route must be wrapped in `metered()` and called through `hostedFetch()`.** Tests use `ACCOUNT_STORE=memory` and sign throwaway Clerk-shaped tokens. **Billing (Stripe Checkout with Managed Payments, so Stripe is the merchant of record).** `api/_billing.js` adds four ops to `api/account.js`: `checkout` (starts a subscription checkout for the signed-in person, tagged with their id in `client_reference_id` and the subscription's `metadata.glint_user`), `confirm` (back from checkout: reads the session from Stripe, only for the person who started it), `portal` (Stripe's billing portal) and `webhook`. **The webhook trusts nothing it is sent**: it takes only the event id, fetches that event from Stripe with our key, then fetches the subscription again and stores Stripe's current state (`rowFromSubscription`), so there is no signing secret and no raw-body handling, and a replayed or forged call can at most re-read a real subscription. Only `active` / `trialing` rows keep a period end (the credits function treats a future end date as still Pro); news about an older subscription never overwrites a live newer one. Plain HTTPS, no Stripe package. On when `STRIPE_SECRET_KEY` and `STRIPE_PRICE_ID` are set (`PRO_PRICE_LABEL` is the price text shown in the panel, `STRIPE_MANAGED_PAYMENTS=0` sells directly, `STRIPE_API_VERSION` overrides the pinned version); `me` then reports `billing: true` and the account panel shows Upgrade / Manage billing instead of the waitlist link. The editor side is `account.js` `startCheckout()` / `openBillingPortal()` / `confirmCheckout()`, and `account-panel.js` handles the `?pro=success&session_id=` return. Tests run against a stand-in Stripe (`testBillingRoutes`). Still to build: share link perks, real prices on the pricing page. - **Waitlist.** The pricing page's Pro card (`pricing/index.html`, `#pro`) has a `form[data-waitlist]` that `public/site.js` (0a) posts to `/api/waitlist`. `api/_waitlist.js` holds both routes as ops of the one share function (`vercel.json` rewrites `/api/waitlist` and `/api/waitlist-export` to `api/share.js`). The Blob store is public, so entries are stored unreadable: the file name is an HMAC of the email (which also de-duplicates) and the body is AES-256-GCM encrypted, both keyed from `SHARE_SIGNING_SECRET`. Changing that secret orphans the list. The join route answers the same whether or not the email was already there. Read the list with `curl -H "Authorization: Bearer $CRON_SECRET" https:///api/waitlist-export?format=csv`. -- **Analytics.** Vercel Web Analytics, no cookies. Marketing pages load it from `public/site.js` (0) (skipped on localhost) and send `open_studio` and `waitlist_join`. The editor uses `src/features/analytics.js` (`bindAnalytics()`, `track(name, data)`): `section_used` once per sidebar section per visit (a capture listener, so new sections are covered for free), `export`, `share_link`, `roll_develop`, `ai_blocked` (sign-in needed or out of credits). **Events carry feature names and choices only, never images, file names, colors or typed text;** if you add an event, list it on the privacy page. +- **Analytics.** Vercel Web Analytics, no cookies. Marketing pages load it from `public/site.js` (0) (skipped on localhost) and send `open_studio` and `waitlist_join`. The editor uses `src/features/analytics.js` (`bindAnalytics()`, `track(name, data)`): `section_used` once per sidebar section per visit (a capture listener, so new sections are covered for free), `export`, `share_link`, `roll_develop`, `ai_blocked` (sign-in needed or out of credits), `pro_checkout` (`step`: start or done). **Events carry feature names and choices only, never images, file names, colors or typed text;** if you add an event, list it on the privacy page. ### Persistence User data (templates, brand kits, projects, onboarding flags) is stored in `localStorage` under `glint_*` keys, each feature managing its own. `src/state/serialize.js` handles project save/load (`SERIALIZED_FIELDS` for the lean payload, `PROJECT_FIELDS` for heavier fields like dataURLs). There is no cloud sync (it left with Supabase). The Campaign folder lives in its own `glint_campaigns_v1` localStorage store and is never snapshotted. Projects (`glint_projects_v12`) are stored in IndexedDB (`src/state/project-db.js`, db `glint`, store `kv`) with a localStorage fallback (used when IndexedDB is unavailable or does not load within 8s); any project store found in localStorage is merged into IndexedDB on every healthy load (not one-time) and then removed, and the `glint_projects_idb` flag records that IndexedDB was used before, so a later load failure retries once and warns the user. The projects status line shows "Saved" only after the IndexedDB write commits. Share links (v41) keep each link's record and owner key in `glint_shares` (newest first, max 50, thumbnails dropped first on quota errors); the shares themselves live in Vercel Blob, not in the project. Since v40 the Projects panel's "History" button (whole-project versions) is labeled "Project timeline", so it is not confused with the History panel. diff --git a/api/_account.js b/api/_account.js index 872bc72..3c72172 100644 --- a/api/_account.js +++ b/api/_account.js @@ -54,7 +54,7 @@ export function readBearer(req) { return m && m[1].length < 4096 ? m[1] : ''; } -const unavailable = () => new ApiError(503, 'Hosted AI could not check your account just now. Try again in a moment.'); +export const unavailable = () => new ApiError(503, 'Hosted AI could not check your account just now. Try again in a moment.'); // Who does this Clerk session token belong to? Null means not signed in: no // token, an expired one, or one this Clerk instance did not sign. @@ -78,9 +78,16 @@ export async function userFromToken(cfg, token) { // Tests: the same rules as the Postgres function, in memory. const memoryUsage = new Map(); const memoryPro = new Set(); -export function memoryAccounts() { return { usage: memoryUsage, pro: memoryPro }; } +const memorySubs = new Map(); // user id -> subscription row, as api/_billing.js writes it +export function memoryAccounts() { return { usage: memoryUsage, pro: memoryPro, subs: memorySubs }; } +// The same test the Postgres function applies to a subscriptions row. +function rowIsPro(row) { + if (!row || row.plan !== 'pro') return false; + if (row.status === 'active' || row.status === 'trialing') return true; + return Boolean(row.current_period_end) && new Date(row.current_period_end).getTime() > Date.now(); +} function memoryUse(user, cost, freeLimit, proLimit) { - const plan = memoryPro.has(user) ? 'pro' : 'free'; + const plan = memoryPro.has(user) || rowIsPro(memorySubs.get(user)) ? 'pro' : 'free'; const limit = plan === 'pro' ? proLimit : freeLimit; const now = memoryUsage.get(user) || 0; let allowed = true; @@ -99,17 +106,22 @@ function db(cfg) { // database has not been set up yet, which the server does itself, once. const needsSchema = (e) => e && (e.code === '42883' || e.code === '42P01'); -async function postgresUse(cfg, args) { +// One query, installing the schema first if the database turns out to be empty. +export async function runSql(cfg, text, args) { const sql = db(cfg); try { - return (await sql.query(USE_CREDITS, args))[0].r; + return await sql.query(text, args); } catch (e) { if (!needsSchema(e)) throw e; for (const statement of SCHEMA) await sql.query(statement); - return (await sql.query(USE_CREDITS, args))[0].r; + return sql.query(text, args); } } +async function postgresUse(cfg, args) { + return (await runSql(cfg, USE_CREDITS, args))[0].r; +} + // cost > 0 spends, cost < 0 refunds, 0 only reads. export async function useCredits(cfg, userId, cost) { let out; @@ -192,6 +204,12 @@ export function metered(kind, handler) { }; } +// api/_billing.js plugs these in (it imports this module, so it cannot be +// imported here): what `me` says about billing and the person's subscription. +let billingInfo = null; +let subscriptionSummary = null; +export function useBilling(hooks) { billingInfo = hooks.info; subscriptionSummary = hooks.summary; } + // GET /api/account?op=me: what the editor shows as "credits left". export async function me(req, res) { res.setHeader('Cache-Control', 'no-store'); @@ -199,11 +217,13 @@ export async function me(req, res) { if (req.method !== 'GET') throw new ApiError(405, 'Method not allowed'); const cfg = accountConfig(); if (!cfg.enabled) { res.status(200).json({ enabled: false }); return; } - const base = { enabled: true, hosted: Boolean(serverOpenAIKey()), costs: CREDIT_COSTS, freeCredits: cfg.freeCredits, proCredits: cfg.proCredits }; + const billing = billingInfo ? billingInfo() : { billing: false }; + const base = { enabled: true, hosted: Boolean(serverOpenAIKey()), costs: CREDIT_COSTS, freeCredits: cfg.freeCredits, proCredits: cfg.proCredits, ...billing }; const user = await userFromToken(cfg, readBearer(req)); if (!user) { res.status(200).json({ ...base, signedIn: false }); return; } const usage = await useCredits(cfg, user.id, 0); - res.status(200).json({ ...base, signedIn: true, plan: usage.plan, used: usage.used, limit: usage.limit, resets: resetsAt() }); + const subscription = billing.billing && subscriptionSummary ? await subscriptionSummary(cfg, user.id) : null; + res.status(200).json({ ...base, signedIn: true, plan: usage.plan, used: usage.used, limit: usage.limit, resets: resetsAt(), ...(subscription ? { subscription } : {}) }); } catch (e) { if (!(e instanceof ApiError)) console.error('[account]', e); res.status(e instanceof ApiError ? e.status : 500).json({ error: e instanceof ApiError ? e.message : 'Something went wrong. Try again.' }); diff --git a/api/_billing.js b/api/_billing.js new file mode 100644 index 0000000..0bc588d --- /dev/null +++ b/api/_billing.js @@ -0,0 +1,308 @@ +// Glint Pro billing, on Stripe Checkout with Managed Payments (Stripe is the +// merchant of record: it sells to the customer and handles tax). Four routes of +// the one account function (api/account.js): +// +// POST ?op=checkout start a subscription checkout for the signed-in person +// POST ?op=confirm the person is back from checkout: bring the plan up to date +// POST ?op=portal open Stripe's billing portal (cancel, change card) +// POST ?op=webhook Stripe telling us a subscription changed +// +// Nothing here trusts what it is sent. The webhook body is only used for its +// event id: the event is then fetched from Stripe with our own key, and the +// subscription it points at is fetched again, so the row we store is always +// Stripe's current state. A made-up or replayed call can at most make us +// re-read a real subscription. (This also means no raw request body and no +// signing secret are needed.) +// +// Billing is on when the deployment has STRIPE_SECRET_KEY and STRIPE_PRICE_ID +// on top of what accounts need. There is no Stripe package: plain HTTPS. + +import { ApiError, parseBody } from './_shared.js'; +import { accountConfig, memoryAccounts, readBearer, runSql, unavailable, useBilling, userFromToken } from './_account.js'; + +const STRIPE = 'https://api.stripe.com'; +// A version new enough for managed_payments on Checkout Sessions. From +// 2025-03-31 a subscription's period lives on its items. +const DEFAULT_API_VERSION = '2026-10-28.endive'; +const USER_ID = /^[A-Za-z0-9_-]{1,128}$/; + +export function billingConfig() { + const account = accountConfig(); + const secretKey = process.env.STRIPE_SECRET_KEY || ''; + const priceId = process.env.STRIPE_PRICE_ID || ''; + return { + account, + secretKey, + priceId, + apiVersion: process.env.STRIPE_API_VERSION || DEFAULT_API_VERSION, + // Off only for an account that sells directly instead of through Stripe. + managed: process.env.STRIPE_MANAGED_PAYMENTS !== '0', + priceLabel: String(process.env.PRO_PRICE_LABEL || '').slice(0, 40), + enabled: Boolean(account.enabled && secretKey && /^price_[A-Za-z0-9]+$/.test(priceId)), + }; +} + +// ── Stripe over HTTPS ──────────────────────────────────────────────────────── + +class StripeError extends Error { + constructor(status, message, code) { super(message); this.status = status; this.code = code; } +} + +async function stripe(cfg, method, path, params) { + const headers = { Authorization: `Bearer ${cfg.secretKey}`, 'Stripe-Version': cfg.apiVersion }; + let body; + if (params) { + body = new URLSearchParams(params).toString(); + headers['Content-Type'] = 'application/x-www-form-urlencoded'; + } + let response; + try { + response = await fetch(STRIPE + path, { method, headers, body }); + } catch (e) { + throw new StripeError(0, e.message); + } + const data = await response.json().catch(() => ({})); + if (!response.ok) throw new StripeError(response.status, (data.error && data.error.message) || 'Stripe request failed', data.error && data.error.code); + return data; +} + +// ── the subscriptions table ────────────────────────────────────────────────── + +const iso = (seconds) => (typeof seconds === 'number' && seconds > 0 ? new Date(seconds * 1000).toISOString() : null); + +// What we keep from a Stripe subscription. Only a paid-up subscription carries +// an end date: the credits function treats a future end date as "still Pro", +// which must not happen for one that never got paid or was refunded and ended. +export function rowFromSubscription(sub) { + const status = typeof sub.status === 'string' ? sub.status.slice(0, 40) : 'incomplete'; + const item = sub.items && Array.isArray(sub.items.data) ? sub.items.data[0] : null; + const periodEnd = (item && item.current_period_end) || sub.current_period_end; + let end = null; + if (status === 'active' || status === 'trialing') end = iso(periodEnd); + else if (status === 'canceled') end = iso(sub.ended_at || sub.canceled_at) || new Date().toISOString(); + return { + plan: 'pro', + status, + current_period_end: end, + provider: 'stripe', + provider_customer_id: typeof sub.customer === 'string' ? sub.customer : (sub.customer && sub.customer.id) || null, + provider_subscription_id: sub.id, + }; +} + +const isLive = (status) => status === 'active' || status === 'trialing'; + +// An older subscription's news must not overwrite a newer, live one. +const UPSERT = `insert into subscriptions + (user_id, plan, status, current_period_end, provider, provider_customer_id, provider_subscription_id, updated_at) + values ($1, $2, $3, $4, $5, $6, $7, now()) + on conflict (user_id) do update set + plan = excluded.plan, status = excluded.status, current_period_end = excluded.current_period_end, + provider = excluded.provider, provider_customer_id = excluded.provider_customer_id, + provider_subscription_id = excluded.provider_subscription_id, updated_at = now() + where subscriptions.provider_subscription_id is null + or subscriptions.provider_subscription_id = excluded.provider_subscription_id + or excluded.status in ('active', 'trialing') + or subscriptions.status not in ('active', 'trialing')`; +const UPDATE_BY_SUBSCRIPTION = `update subscriptions set status = $2, current_period_end = $3, updated_at = now() + where provider_subscription_id = $1`; +const READ = 'select status, current_period_end, provider_customer_id, provider_subscription_id from subscriptions where user_id = $1'; + +async function saveRow(cfg, userId, row) { + if (cfg.memory) { + const { subs } = memoryAccounts(); + if (userId) { + const old = subs.get(userId); + const keep = old && old.provider_subscription_id && old.provider_subscription_id !== row.provider_subscription_id + && isLive(old.status) && !isLive(row.status); + if (!keep) subs.set(userId, { ...row }); + } else { + for (const old of subs.values()) { + if (old.provider_subscription_id === row.provider_subscription_id) Object.assign(old, { status: row.status, current_period_end: row.current_period_end }); + } + } + return; + } + if (userId) { + await runSql(cfg, UPSERT, [userId, row.plan, row.status, row.current_period_end, row.provider, row.provider_customer_id, row.provider_subscription_id]); + } else { + await runSql(cfg, UPDATE_BY_SUBSCRIPTION, [row.provider_subscription_id, row.status, row.current_period_end]); + } +} + +async function readRow(cfg, userId) { + if (cfg.memory) return memoryAccounts().subs.get(userId) || null; + return (await runSql(cfg, READ, [userId]))[0] || null; +} + +// Fetch the subscription from Stripe and store what it says now. `userHint` +// is who we already know it belongs to; otherwise its own metadata says. +async function syncSubscription(cfg, subscriptionId, userHint = '') { + if (!/^sub_[A-Za-z0-9]+$/.test(String(subscriptionId || ''))) return null; + const sub = await stripe(cfg, 'GET', `/v1/subscriptions/${subscriptionId}`); + const tagged = sub.metadata && typeof sub.metadata.glint_user === 'string' ? sub.metadata.glint_user : ''; + const userId = USER_ID.test(userHint) ? userHint : (USER_ID.test(tagged) ? tagged : ''); + const row = rowFromSubscription(sub); + await saveRow(cfg.account, userId, row); + return row; +} + +// ── what `me` reports ──────────────────────────────────────────────────────── + +useBilling({ + info() { + const cfg = billingConfig(); + return cfg.enabled ? { billing: true, ...(cfg.priceLabel ? { priceLabel: cfg.priceLabel } : {}) } : { billing: false }; + }, + async summary(accountCfg, userId) { + let row; + try { row = await readRow(accountCfg, userId); } catch (e) { console.error('[billing] could not read a subscription:', e.message); return null; } + if (!row) return null; + return { status: row.status, canManage: Boolean(row.provider_customer_id) }; + }, +}); + +// ── routes ─────────────────────────────────────────────────────────────────── + +function fail(res, e) { + if (e instanceof ApiError) { + res.status(e.status).json({ error: e.message, ...(e.code ? { code: e.code } : {}) }); + return; + } + if (e instanceof StripeError) { + console.error('[billing] Stripe said:', e.status, e.code || '', e.message); + res.status(502).json({ error: 'The payment service did not answer as expected. Try again in a moment.' }); + return; + } + console.error('[billing]', e); + res.status(500).json({ error: 'Something went wrong. Try again.' }); +} + +function coded(status, code, message) { + const e = new ApiError(status, message); + e.code = code; + return e; +} + +async function signedIn(req) { + if (req.method !== 'POST') throw new ApiError(405, 'Method not allowed'); + const cfg = billingConfig(); + if (!cfg.enabled) throw new ApiError(501, 'Glint Pro is not on sale on this copy of Glint.'); + const user = await userFromToken(cfg.account, readBearer(req)); + if (!user) throw coded(401, 'sign_in', 'Sign in first.'); + return { cfg, user }; +} + +// Where Stripe sends the person back to: this same site. +function siteOrigin(req) { + const host = String((req.headers && (req.headers['x-forwarded-host'] || req.headers.host)) || '').split(',')[0].trim(); + if (!/^[a-z0-9.-]+(:\d+)?$/i.test(host)) throw new ApiError(400, 'Bad request'); + return `${/^(localhost|127\.0\.0\.1)(:\d+)?$/.test(host) ? 'http' : 'https'}://${host}`; +} + +export async function checkout(req, res) { + res.setHeader('Cache-Control', 'no-store'); + try { + const { cfg, user } = await signedIn(req); + const row = await readRow(cfg.account, user.id).catch(() => { throw unavailable(); }); + if (row && isLive(row.status)) throw coded(409, 'already_pro', 'You are already on Glint Pro.'); + const origin = siteOrigin(req); + const params = { + mode: 'subscription', + 'line_items[0][price]': cfg.priceId, + 'line_items[0][quantity]': '1', + client_reference_id: user.id, + 'metadata[glint_user]': user.id, + 'subscription_data[metadata][glint_user]': user.id, + success_url: `${origin}/editor/?pro=success&session_id={CHECKOUT_SESSION_ID}`, + cancel_url: `${origin}/editor/?pro=cancel`, + }; + if (cfg.managed) params['managed_payments[enabled]'] = 'true'; + // Someone who subscribed before keeps one customer record at Stripe. + if (row && /^cus_[A-Za-z0-9]+$/.test(String(row.provider_customer_id || ''))) params.customer = row.provider_customer_id; + const session = await stripe(cfg, 'POST', '/v1/checkout/sessions', params); + if (!session.url) throw new StripeError(502, 'Checkout session has no url'); + res.status(200).json({ url: session.url }); + } catch (e) { + fail(res, e); + } +} + +export async function confirm(req, res) { + res.setHeader('Cache-Control', 'no-store'); + try { + const { cfg, user } = await signedIn(req); + const id = String(parseBody(req).session_id || ''); + if (!/^cs_(test|live)_[A-Za-z0-9]{8,200}$/.test(id)) throw new ApiError(400, 'Bad request'); + let session; + try { + session = await stripe(cfg, 'GET', `/v1/checkout/sessions/${id}`); + } catch (e) { + if (e instanceof StripeError && e.status === 404) throw new ApiError(404, 'That checkout was not found.'); + throw e; + } + // Only the person who started this checkout can claim it. + if (session.client_reference_id !== user.id) throw new ApiError(404, 'That checkout was not found.'); + if (session.status !== 'complete' || !session.subscription) { + res.status(200).json({ plan: 'free', pending: true }); + return; + } + const row = await syncSubscription(cfg, typeof session.subscription === 'string' ? session.subscription : session.subscription.id, user.id); + res.status(200).json({ plan: row && isLive(row.status) ? 'pro' : 'free', pending: !(row && isLive(row.status)) }); + } catch (e) { + fail(res, e); + } +} + +export async function portal(req, res) { + res.setHeader('Cache-Control', 'no-store'); + try { + const { cfg, user } = await signedIn(req); + const row = await readRow(cfg.account, user.id).catch(() => { throw unavailable(); }); + const customer = row && String(row.provider_customer_id || ''); + if (!customer || !/^cus_[A-Za-z0-9]+$/.test(customer)) throw new ApiError(404, 'There is no subscription to manage on this account.'); + const session = await stripe(cfg, 'POST', '/v1/billing_portal/sessions', { customer, return_url: `${siteOrigin(req)}/editor/` }); + if (!session.url) throw new StripeError(502, 'Portal session has no url'); + res.status(200).json({ url: session.url }); + } catch (e) { + fail(res, e); + } +} + +const SUBSCRIPTION_EVENTS = new Set([ + 'customer.subscription.created', 'customer.subscription.updated', 'customer.subscription.deleted', + 'customer.subscription.paused', 'customer.subscription.resumed', +]); + +export async function webhook(req, res) { + res.setHeader('Cache-Control', 'no-store'); + try { + if (req.method !== 'POST') throw new ApiError(405, 'Method not allowed'); + const cfg = billingConfig(); + if (!cfg.enabled) throw new ApiError(501, 'Billing is not set up.'); + let claimed; + try { claimed = parseBody(req); } catch (e) { claimed = {}; } + const id = claimed && typeof claimed.id === 'string' ? claimed.id : ''; + if (!/^evt_[A-Za-z0-9]{8,200}$/.test(id)) throw new ApiError(400, 'Bad request'); + let event; + try { + event = await stripe(cfg, 'GET', `/v1/events/${id}`); + } catch (e) { + // Not one of ours: say so plainly, without retries. + if (e instanceof StripeError && e.status === 404) throw new ApiError(400, 'Unknown event'); + throw e; + } + const object = (event.data && event.data.object) || {}; + if (event.type === 'checkout.session.completed' || event.type === 'checkout.session.async_payment_succeeded') { + const subscription = typeof object.subscription === 'string' ? object.subscription : object.subscription && object.subscription.id; + const user = typeof object.client_reference_id === 'string' ? object.client_reference_id : ''; + if (subscription) await syncSubscription(cfg, subscription, user); + } else if (SUBSCRIPTION_EVENTS.has(event.type)) { + await syncSubscription(cfg, object.id); + } + res.status(200).json({ received: true }); + } catch (e) { + // Anything but a plain "bad request" is worth Stripe trying again. + fail(res, e); + } +} diff --git a/api/account.js b/api/account.js index e178890..b25a863 100644 --- a/api/account.js +++ b/api/account.js @@ -1,10 +1,11 @@ // Glint Pro groundwork: one serverless function for every account route, // dispatched on ?op= like api/share.js (the Hobby plan allows 12 functions). -// Today that is `me`; checkout, the billing portal and the payment webhook -// join it when billing is built. +// `me` is the account itself; the rest is billing (api/_billing.js): checkout, +// confirming a finished checkout, the billing portal and Stripe's webhook. import { me } from './_account.js'; +import { checkout, confirm, portal, webhook } from './_billing.js'; -const ROUTES = { me }; +const ROUTES = { me, checkout, confirm, portal, webhook }; export default async function handler(req, res) { const raw = req.query && req.query.op; diff --git a/docs/BACKEND.md b/docs/BACKEND.md index f345da6..9562267 100644 --- a/docs/BACKEND.md +++ b/docs/BACKEND.md @@ -60,6 +60,11 @@ every file in `api/` without a leading underscore counts as one. | `DATABASE_URL` | Yes for AI credits | Added by the Neon Marketplace install (`POSTGRES_URL` also works). Clerk plus a database turns metering on. | | `ACCOUNT_STORE` | Tests only | `memory` keeps credit counts in the process. | | `AI_FREE_CREDITS` / `AI_PRO_CREDITS` | No | Monthly hosted AI credits per account. Default 20 and 500. | +| `STRIPE_SECRET_KEY` | Yes for Glint Pro billing | Stripe secret key (a sandbox key while testing). Sensitive. Used for checkout, the billing portal and to re-read events and subscriptions. | +| `STRIPE_PRICE_ID` | Yes for Glint Pro billing | The `price_...` id of the monthly Glint Pro price. With the key, this turns billing on. | +| `PRO_PRICE_LABEL` | No | Price text shown in the account panel, for example `$8 a month`. | +| `STRIPE_MANAGED_PAYMENTS` | No | `0` sells directly instead of through Managed Payments. Default on. | +| `STRIPE_API_VERSION` | No | Overrides the pinned Stripe API version. | ## Accounts and hosted AI credits diff --git a/docs/GLINT-PRO-STATUS.md b/docs/GLINT-PRO-STATUS.md index 187e5ba..72f949a 100644 --- a/docs/GLINT-PRO-STATUS.md +++ b/docs/GLINT-PRO-STATUS.md @@ -33,15 +33,38 @@ the status and the next steps. - Small leftover: the sign-in box says "glint-signin"; rename the application to Glint in Clerk's settings. +## Billing: built, waiting for its settings + +Checkout is built on Stripe Checkout with Managed Payments (Stripe sells as +the merchant of record). Lemon Squeezy was the first pick; its own sign-up now +points to Managed Payments, so that is what was used. Nothing is on sale until +the deployment has the settings below; until then the panel keeps showing the +waitlist link. + +To switch it on, in a Stripe **sandbox** first: + +1. Stripe: turn on Managed Payments, create the product "Glint Pro" with the + tax code "Software as a service (SaaS) - personal use" and a monthly price. +2. Vercel settings: `STRIPE_SECRET_KEY` (sandbox key, Sensitive), + `STRIPE_PRICE_ID` (`price_...`), `PRO_PRICE_LABEL` (for example + `$8 a month`). Redeploy. +3. Stripe: add a webhook destination (snapshot events) for + `https:///api/account?op=webhook` with `checkout.session.completed` + and the `customer.subscription.*` events. No signing secret is needed. +4. Stripe: save the customer portal settings once, so Manage billing opens. +5. Test with card 4242 4242 4242 4242: upgrade, see Pro and 500 credits, + cancel from Manage billing, see the plan end. + +This has only run against a stand-in Stripe and a local Postgres so far. The +first sandbox run is the real test, including whether the pinned API version +accepts `managed_payments`. + ## Next -- Checkout and webhook with a merchant of record (Lemon Squeezy was the pick), - as new ops in `api/account.js`. -- Vercel Pro plan before charging anyone (Hobby is non-commercial). -- The account panel is built (click the credits chip, or Cmd-K "Account"): - plan, credits left, costs, waitlist link, manage account, sign out. Add the - Upgrade and Manage billing buttons to it when checkout exists. -- Share link perks for Pro, then real prices on the pricing page. +- Go live: Vercel Pro plan first (Hobby is non-commercial), then the live + Stripe key and price, then real prices on the pricing page and the Pro card + there selling instead of collecting emails. Email the waitlist. +- Share link perks for Pro. - Watch whether 20 free credits is enough: the Design Agent spends one per step. Tune with `AI_FREE_CREDITS`. @@ -49,4 +72,6 @@ the status and the next steps. - The studio stays free; Pro covers the parts that cost money to run. - Starting numbers: about $8 a month, 20 free and 500 Pro credits. +- Payments: Stripe Managed Payments. A lapsed payment drops the account to + Free at once (no grace period); it returns to Pro when the payment clears. - Glint Pro will be its own numbered release (v42 Junction shipped separately). diff --git a/privacy/index.html b/privacy/index.html index d6b72c4..0c7741b 100644 --- a/privacy/index.html +++ b/privacy/index.html @@ -93,13 +93,13 @@

Share links

Accounts

The core editor needs no account, and neither do share links. Your projects stay in your browser and are not uploaded. Sign-in is optional and exists to count hosted AI use. It is run by Clerk, which stores your email address and login details, and the editor loads Clerk's sign-in script when it opens; Glint's own database holds only an account id, never your email or password.

-

When you use the hosted AI while signed in, we keep one number per account per month: how many credits were used. We do not store your prompts or images. If you later subscribe to Glint Pro, we will also keep the status of that subscription; card details stay with the payment provider.

+

When you use the hosted AI while signed in, we keep one number per account per month: how many credits were used. We do not store your prompts or images. If you subscribe to Glint Pro, the payment is handled by Stripe, which sells the subscription as the merchant of record and collects your payment details, billing address and any tax. Glint never sees your card. We keep the status of the subscription and Stripe's customer and subscription ids next to your account id, so the right plan applies.

Browser extension

The Glint Capture extension reads a tab only when you click its toolbar button and pick a capture (the activeTab permission); it has no standing access to your browsing and runs no tracking or analytics. The screenshot it takes is handed to the Glint studio and nowhere else: it is held in the extension's local storage for a moment in transit, then cleared once the editor loads it. The extension contains no remote code, and like the rest of the project its source is public.

Analytics

-

We use privacy-friendly, aggregate analytics (Vercel Analytics) to understand traffic and which parts of Glint get used. It sets no cookies. Along with page views, the site and the editor record a few named events: opening the studio from a page, joining the waitlist, the first time a sidebar section is used in a visit, an export (its format), creating a share link (its kind), and reaching the hosted AI limit. Events never include your images, file names, colors or anything you type. There are no advertising trackers and no cross-site profiling. We do not sell data.

+

We use privacy-friendly, aggregate analytics (Vercel Analytics) to understand traffic and which parts of Glint get used. It sets no cookies. Along with page views, the site and the editor record a few named events: opening the studio from a page, joining the waitlist, the first time a sidebar section is used in a visit, an export (its format), creating a share link (its kind), reaching the hosted AI limit, and starting or finishing a Glint Pro checkout. Events never include your images, file names, colors or anything you type. There are no advertising trackers and no cross-site profiling. We do not sell data.

Glint Pro waitlist

If you join the waitlist on the pricing page, we store your email address, the date, and the page you joined from. It is kept encrypted in Glint's storage on Vercel and used for one thing: telling you when Glint Pro opens. That email will include a way to leave the list. To leave sooner, contact us through GitHub.

diff --git a/scripts/regression-tests.mjs b/scripts/regression-tests.mjs index b7440ae..71bee0c 100644 --- a/scripts/regression-tests.mjs +++ b/scripts/regression-tests.mjs @@ -1420,6 +1420,181 @@ async function testHostedAiIsMetered() { } } + +// Glint Pro billing: checkout, the return from checkout, the webhook and the +// billing portal, against a stand-in for Stripe's API. +async function testBillingRoutes() { + const saved = { ...process.env }; + const realFetch = globalThis.fetch; + const KEYS = ['CLERK_SECRET_KEY', 'CLERK_JWT_KEY', 'DATABASE_URL', 'POSTGRES_URL', 'ACCOUNT_STORE', 'OPENAI_API_KEY', 'AI_FREE_CREDITS', 'AI_PRO_CREDITS', 'STRIPE_SECRET_KEY', 'STRIPE_PRICE_ID', 'STRIPE_API_VERSION', 'STRIPE_MANAGED_PAYMENTS', 'PRO_PRICE_LABEL']; + for (const k of KEYS) delete process.env[k]; + const { usage, pro, subs } = memoryAccounts(); + usage.clear(); pro.clear(); subs.clear(); + const USER = 'user_buyer1', OTHER = 'user_other2'; + const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); + const part = (o) => Buffer.from(JSON.stringify(o)).toString('base64url'); + const now = Math.floor(Date.now() / 1000); + const sign = (sub) => { + const head = part({ alg: 'RS256', typ: 'JWT', kid: 'ins_test', cat: 'cl_B7d4PD111AAA' }); + const body = part({ sid: 'sess_1', iss: 'https://clerk.glint.test', iat: now, nbf: now - 5, exp: now + 300, sub }); + return `${head}.${body}.${createSign('RSA-SHA256').update(`${head}.${body}`).sign(privateKey).toString('base64url')}`; + }; + const buyer = sign(USER), other = sign(OTHER); + + // The stand-in Stripe: what it holds, and every call made to it. + const stripe = { sessions: {}, subscriptions: {}, events: {}, calls: [] }; + const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)); + if (u.origin !== 'https://api.stripe.com') throw new Error('network down: ' + u); + const form = Object.fromEntries(new URLSearchParams(init.body || '')); + stripe.calls.push({ method: init.method, path: u.pathname, form, headers: init.headers }); + const missing = json(404, { error: { message: 'No such object', code: 'resource_missing' } }); + if (init.method === 'POST' && u.pathname === '/v1/checkout/sessions') { + const id = 'cs_test_' + 'a'.repeat(20) + Object.keys(stripe.sessions).length; + stripe.sessions[id] = { id, status: 'open', client_reference_id: form.client_reference_id, subscription: null, url: 'https://checkout.stripe.test/' + id }; + return json(200, stripe.sessions[id]); + } + if (init.method === 'POST' && u.pathname === '/v1/billing_portal/sessions') return json(200, { url: 'https://billing.stripe.test/' + form.customer }); + let m; + if ((m = /^\/v1\/checkout\/sessions\/(.+)$/.exec(u.pathname))) return stripe.sessions[m[1]] ? json(200, stripe.sessions[m[1]]) : missing; + if ((m = /^\/v1\/subscriptions\/(.+)$/.exec(u.pathname))) return stripe.subscriptions[m[1]] ? json(200, stripe.subscriptions[m[1]]) : missing; + if ((m = /^\/v1\/events\/(.+)$/.exec(u.pathname))) return stripe.events[m[1]] ? json(200, stripe.events[m[1]]) : missing; + return missing; + }; + const post = (op, body, token) => shareReq('POST', body, { query: { op }, headers: token ? { authorization: `Bearer ${token}` } : {} }); + const me = async (token) => (await callRoute(accountRouter, shareReq('GET', null, { query: { op: 'me' }, headers: { authorization: `Bearer ${token}` } }))).body; + const errors = console.error; + try { + process.env.CLERK_JWT_KEY = publicKey.export({ type: 'spki', format: 'pem' }); + process.env.ACCOUNT_STORE = 'memory'; + process.env.OPENAI_API_KEY = 'sk-test'; + process.env.AI_FREE_CREDITS = '3'; + process.env.AI_PRO_CREDITS = '40'; + + // No Stripe settings: nothing is on sale and nothing calls out. + assert.equal((await callRoute(accountRouter, post('checkout', {}, buyer))).statusCode, 501); + assert.equal((await callRoute(accountRouter, post('webhook', { id: 'evt_12345678' }))).statusCode, 501); + assert.equal((await me(buyer)).billing, false); + assert.equal(stripe.calls.length, 0); + + process.env.STRIPE_SECRET_KEY = 'sk_test_abc'; + process.env.STRIPE_PRICE_ID = 'price_123abc'; + process.env.PRO_PRICE_LABEL = '$8 a month'; + const info = await me(buyer); + assert.deepEqual([info.billing, info.priceLabel, info.plan, info.subscription], [true, '$8 a month', 'free', undefined]); + + // Checkout needs a signed-in person and only accepts POST. + const anon = await callRoute(accountRouter, post('checkout', {})); + assert.deepEqual([anon.statusCode, anon.body.code], [401, 'sign_in']); + assert.equal((await callRoute(accountRouter, shareReq('GET', null, { query: { op: 'checkout' }, headers: { authorization: `Bearer ${buyer}` } }))).statusCode, 405); + assert.equal(stripe.calls.length, 0); + + const started = await callRoute(accountRouter, post('checkout', {}, buyer)); + assert.equal(started.statusCode, 200); + assert.ok(started.body.url.startsWith('https://checkout.stripe.test/cs_test_')); + const call = stripe.calls.at(-1); + assert.equal(call.headers.Authorization, 'Bearer sk_test_abc'); + assert.equal(call.form.mode, 'subscription'); + assert.equal(call.form['line_items[0][price]'], 'price_123abc'); + assert.equal(call.form['managed_payments[enabled]'], 'true'); + assert.equal(call.form.client_reference_id, USER); + assert.equal(call.form['subscription_data[metadata][glint_user]'], USER); + assert.equal(call.form.success_url, 'https://glint.test/editor/?pro=success&session_id={CHECKOUT_SESSION_ID}'); + assert.equal(call.form.customer, undefined); + for (const banned of ['automatic_tax[enabled]', 'payment_method_types[0]', 'tax_id_collection[enabled]']) assert.equal(call.form[banned], undefined); + const sessionId = started.body.url.split('/').pop(); + + // Back from checkout before paying: still free. A stranger cannot claim it. + assert.deepEqual((await callRoute(accountRouter, post('confirm', { session_id: sessionId }, buyer))).body, { plan: 'free', pending: true }); + assert.equal((await callRoute(accountRouter, post('confirm', { session_id: sessionId }, other))).statusCode, 404); + assert.equal((await callRoute(accountRouter, post('confirm', { session_id: '../v1/customers' }, buyer))).statusCode, 400); + assert.equal((await me(buyer)).plan, 'free'); + + // The payment goes through. + const end = now + 30 * 86400; + stripe.subscriptions.sub_1 = { id: 'sub_1', status: 'active', customer: 'cus_9', metadata: { glint_user: USER }, items: { data: [{ current_period_end: end }] } }; + Object.assign(stripe.sessions[sessionId], { status: 'complete', subscription: 'sub_1' }); + assert.equal((await callRoute(accountRouter, post('confirm', { session_id: sessionId }, other))).statusCode, 404); + assert.equal((await me(other)).plan, 'free'); + assert.deepEqual((await callRoute(accountRouter, post('confirm', { session_id: sessionId }, buyer))).body, { plan: 'pro', pending: false }); + const paid = await me(buyer); + assert.deepEqual([paid.plan, paid.limit, paid.subscription.canManage], ['pro', 40, true]); + assert.equal(subs.get(USER).current_period_end, new Date(end * 1000).toISOString()); + + // Already Pro: no second checkout. The portal opens for the right customer. + const again = await callRoute(accountRouter, post('checkout', {}, buyer)); + assert.deepEqual([again.statusCode, again.body.code], [409, 'already_pro']); + assert.equal((await callRoute(accountRouter, post('portal', {}, buyer))).body.url, 'https://billing.stripe.test/cus_9'); + assert.equal(stripe.calls.at(-1).form.return_url, 'https://glint.test/editor/'); + assert.equal((await callRoute(accountRouter, post('portal', {}, other))).statusCode, 404); + + // The webhook trusts only what Stripe itself returns for the event id. + console.error = () => {}; + const forged = await callRoute(accountRouter, post('webhook', { id: 'evt_forged12345', type: 'customer.subscription.deleted', data: { object: { id: 'sub_1', status: 'canceled', metadata: { glint_user: USER } } } })); + assert.equal(forged.statusCode, 400); + assert.equal((await callRoute(accountRouter, post('webhook', { id: 'sub_1' }))).statusCode, 400); + assert.equal((await callRoute(accountRouter, post('webhook', {}))).statusCode, 400); + assert.equal((await me(buyer)).plan, 'pro'); + + // A real event whose body lies: the stored row follows Stripe, not the body. + stripe.events.evt_real0000001 = { id: 'evt_real0000001', type: 'customer.subscription.updated', data: { object: { id: 'sub_1' } } }; + assert.equal((await callRoute(accountRouter, post('webhook', { id: 'evt_real0000001', data: { object: { id: 'sub_1', status: 'canceled' } } }))).statusCode, 200); + assert.equal((await me(buyer)).plan, 'pro'); + + // Payment fails later: no longer Pro, even though a period end is in the future at Stripe. + stripe.subscriptions.sub_1.status = 'past_due'; + assert.equal((await callRoute(accountRouter, post('webhook', { id: 'evt_real0000001' }))).statusCode, 200); + assert.equal((await me(buyer)).plan, 'free'); + assert.equal(subs.get(USER).current_period_end, null); + stripe.subscriptions.sub_1.status = 'active'; + await callRoute(accountRouter, post('webhook', { id: 'evt_real0000001' })); + assert.equal((await me(buyer)).plan, 'pro'); + + // Cancelled and ended (say, refunded): free at once. + Object.assign(stripe.subscriptions.sub_1, { status: 'canceled', ended_at: now - 10 }); + stripe.events.evt_real0000002 = { id: 'evt_real0000002', type: 'customer.subscription.deleted', data: { object: { id: 'sub_1' } } }; + assert.equal((await callRoute(accountRouter, post('webhook', { id: 'evt_real0000002' }))).statusCode, 200); + assert.equal((await me(buyer)).plan, 'free'); + + // Subscribing again reuses the customer; checkout.session.completed alone is enough. + const second = await callRoute(accountRouter, post('checkout', {}, buyer)); + assert.equal(second.statusCode, 200); + assert.equal(stripe.calls.at(-1).form.customer, 'cus_9'); + const secondId = second.body.url.split('/').pop(); + stripe.subscriptions.sub_2 = { id: 'sub_2', status: 'active', customer: 'cus_9', metadata: {}, items: { data: [{ current_period_end: end }] } }; + Object.assign(stripe.sessions[secondId], { status: 'complete', subscription: 'sub_2' }); + stripe.events.evt_real0000003 = { id: 'evt_real0000003', type: 'checkout.session.completed', data: { object: { id: secondId, subscription: 'sub_2', client_reference_id: USER } } }; + assert.equal((await callRoute(accountRouter, post('webhook', { id: 'evt_real0000003' }))).statusCode, 200); + assert.equal((await me(buyer)).plan, 'pro'); + // Late news about the old, ended subscription does not undo the new one. + assert.equal((await callRoute(accountRouter, post('webhook', { id: 'evt_real0000002' }))).statusCode, 200); + assert.equal((await me(buyer)).plan, 'pro'); + assert.equal(subs.get(USER).provider_subscription_id, 'sub_2'); + // Events we do not act on are acknowledged. + stripe.events.evt_real0000004 = { id: 'evt_real0000004', type: 'invoice.paid', data: { object: { id: 'in_1' } } }; + assert.equal((await callRoute(accountRouter, post('webhook', { id: 'evt_real0000004' }))).statusCode, 200); + + // Stripe down: checkout says so (502) and the webhook asks to be retried. + globalThis.fetch = async () => { throw new Error('offline'); }; + subs.delete(USER); + assert.equal((await callRoute(accountRouter, post('checkout', {}, buyer))).statusCode, 502); + assert.equal((await callRoute(accountRouter, post('webhook', { id: 'evt_real0000003' }))).statusCode, 502); + + // Selling directly (not through Managed Payments) leaves the flag out. + process.env.STRIPE_MANAGED_PAYMENTS = '0'; + let sent = null; + globalThis.fetch = async (url, init) => { sent = Object.fromEntries(new URLSearchParams(init.body || '')); return json(200, { id: 'cs_test_x', url: 'https://checkout.stripe.test/x' }); }; + assert.equal((await callRoute(accountRouter, post('checkout', {}, buyer))).statusCode, 200); + assert.equal(sent['managed_payments[enabled]'], undefined); + } finally { + console.error = errors; + globalThis.fetch = realFetch; + usage.clear(); pro.clear(); subs.clear(); + for (const k of KEYS) { if (k in saved) process.env[k] = saved[k]; else delete process.env[k]; } + } +} + const tests = [ testFetchUrlRejectsPrivateHostsBeforeFetch, testFetchUrlUsesManualRedirects, @@ -1454,7 +1629,8 @@ const tests = [ testSharePlayersInlineCleanly, testShareRoutesRoundTrip, testWaitlistRoutes, - testHostedAiIsMetered + testHostedAiIsMetered, + testBillingRoutes ]; for (const test of tests) { diff --git a/src/features/account-panel.js b/src/features/account-panel.js index 918d25b..53ee2c3 100644 --- a/src/features/account-panel.js +++ b/src/features/account-panel.js @@ -4,7 +4,8 @@ // here once they exist. Everything is built with textContent; nothing from the // server or from Clerk is rendered as HTML. import { getUser, isConfigured, openSignIn, openUserProfile, signOut, onAuthChange } from './auth.js'; -import { getAccount, onAccountChange, refreshAccount, hasOwnKey, resetDay } from './account.js'; +import { getAccount, onAccountChange, refreshAccount, hasOwnKey, resetDay, startCheckout, openBillingPortal, confirmCheckout } from './account.js'; +import { showNotification } from '../ui/notification.js'; let dlg = null; let body = null; @@ -72,16 +73,52 @@ function creditsBox(usage, offer) { return box; } -function proBox(usage, offer) { +// A button that sends the person away to Stripe: it says so while it waits, +// and comes back to life if the hand-off did not happen. +function leavingButton(label, waiting, className, go) { + const b = button(label, className, async () => { + b.disabled = true; + b.textContent = waiting; + const left = await go(); + if (!left) { b.disabled = false; b.textContent = label; } + }); + return b; +} + +function proBox(usage, offer, signedIn) { const box = node('div', 'account-box'); + const billing = Boolean(offer && offer.billing); if (usage && usage.plan === 'pro') { - box.append(node('h4', '', 'You are on Glint Pro'), node('p', 'account-note', 'Thank you for backing Glint. Billing controls will show up here.')); + box.append(node('h4', '', 'You are on Glint Pro'), node('p', 'account-note', 'Thank you for backing Glint.')); + if (billing && usage.canManage) { + box.append( + node('p', 'account-note', 'Cancel, change your card or see receipts on the billing page, run by Stripe.'), + leavingButton('Manage billing', 'Opening billing...', 'btn-secondary', openBillingPortal), + ); + } return box; } const pro = offer && offer.proCredits; + const credits = pro ? `${pro} hosted AI credits a month` : 'More hosted AI credits'; + if (billing) { + const price = offer.priceLabel ? ` for ${offer.priceLabel}` : ''; + box.append( + node('h4', '', 'Glint Pro'), + node('p', 'account-note', `${credits}${price}. Cancel any time. The studio itself stays free.`), + ); + if (signedIn) { + box.append( + leavingButton('Upgrade to Glint Pro', 'Opening checkout...', 'btn-primary', startCheckout), + node('p', 'account-note', 'Payment is handled by Stripe, which sells Glint Pro on our behalf.'), + ); + } else { + box.append(node('p', 'account-note', 'Sign in first, then upgrade from here.')); + } + return box; + } box.append( node('h4', '', 'Glint Pro is coming'), - node('p', 'account-note', `${pro ? `${pro} hosted AI credits a month` : 'More hosted AI credits'} and share links that last. The studio itself stays free.`), + node('p', 'account-note', `${credits} and share links that last. The studio itself stays free.`), ); const link = node('a', 'btn btn-primary', 'Join the waitlist'); link.href = '/pricing/#pro'; @@ -107,7 +144,7 @@ function render() { node('p', 'account-note', `A free account gives you ${free || 'a set of'} hosted AI credits every month. The studio needs no account, and neither does your own API key.`), button('Sign in', 'btn-primary', () => { dlg.close(); openSignIn(); }), ); - parts.push(box, proBox(null, offer)); + parts.push(box, proBox(null, offer, false)); } else { const who = node('div', 'account-who'); const text = node('div', 'account-who-text'); @@ -130,7 +167,7 @@ function render() { } parts.push(box); } - parts.push(proBox(usage, offer)); + parts.push(proBox(usage, offer, true)); const actions = node('div', 'account-actions'); actions.append( @@ -153,9 +190,41 @@ export function openAccountPanel() { if (isConfigured()) refreshAccount(); } +// Back from Stripe's checkout: ?pro=success&session_id=... or ?pro=cancel. +// The address is cleaned at once, so a reload never repeats this. +function handleCheckoutReturn() { + const params = new URLSearchParams(window.location.search); + const result = params.get('pro'); + if (!result) return; + const sessionId = params.get('session_id') || ''; + params.delete('pro'); + params.delete('session_id'); + const rest = params.toString(); + window.history.replaceState(null, '', window.location.pathname + (rest ? `?${rest}` : '') + window.location.hash); + if (result !== 'success' || !sessionId) return; + let done = false; + // Wait for sign-in to settle: the server only confirms for the buyer. + onAuthChange(async (user) => { + if (done || !user) return; + done = true; + const outcome = await confirmCheckout(sessionId); + if (outcome === 'pro') { + showNotification('Welcome to Glint Pro. Your credits are ready.', 'success', { duration: 7000 }); + openAccountPanel(); + } else if (outcome === 'pending') { + showNotification('Thanks. Your payment is still being confirmed; your plan updates as soon as it is.', 'info', { duration: 9000 }); + setTimeout(() => refreshAccount(), 6000); + } else { + showNotification('Your payment could not be checked just now. If you paid, your plan updates within a minute.', 'info', { duration: 9000 }); + setTimeout(() => refreshAccount(), 15000); + } + }); +} + export function bindAccountPanel() { const chip = document.getElementById('ai-credits'); if (chip) chip.addEventListener('click', openAccountPanel); onAccountChange(render); onAuthChange(render); + handleCheckoutReturn(); } diff --git a/src/features/account.js b/src/features/account.js index 07ae93e..c1518dd 100644 --- a/src/features/account.js +++ b/src/features/account.js @@ -60,8 +60,8 @@ async function loadAccount() { const type = r.headers.get('content-type') || ''; const data = r.ok && type.includes('json') ? await r.json() : null; loadFailed = !data; - offer = data && data.enabled ? { costs: data.costs || {}, freeCredits: data.freeCredits, proCredits: data.proCredits, hosted: Boolean(data.hosted) } : null; - if (data && data.enabled && data.hosted && data.signedIn) setUsage({ used: data.used, limit: data.limit, plan: data.plan, resets: data.resets }); + offer = data && data.enabled ? { costs: data.costs || {}, freeCredits: data.freeCredits, proCredits: data.proCredits, hosted: Boolean(data.hosted), billing: Boolean(data.billing), priceLabel: typeof data.priceLabel === 'string' ? data.priceLabel : '' } : null; + if (data && data.enabled && data.hosted && data.signedIn) setUsage({ used: data.used, limit: data.limit, plan: data.plan, resets: data.resets, canManage: Boolean(data.subscription && data.subscription.canManage) }); else setUsage(null); } catch (e) { loadFailed = true; @@ -112,6 +112,59 @@ export async function hostedFetch(path, body, { quiet = false } = {}) { return new Response(JSON.stringify({ error: message }), { status: 501, headers: { 'Content-Type': 'application/json' } }); } +// POST to one of the billing routes as the signed-in person. Resolves to +// { ok, status, data }; never throws. +async function billingPost(op, body = {}) { + try { + const t = await token(); + const r = await fetch(`/api/account?op=${op}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...(t ? { Authorization: `Bearer ${t}` } : {}) }, + body: JSON.stringify(body), + }); + return { ok: r.ok, status: r.status, data: await r.json().catch(() => ({})) }; + } catch (e) { + return { ok: false, status: 0, data: {} }; + } +} + +// Send the person to Stripe's checkout page for Glint Pro. Resolves to false +// (after saying why) when it could not start. +export async function startCheckout() { + track('pro_checkout', { step: 'start' }); + const { ok, data } = await billingPost('checkout'); + if (ok && typeof data.url === 'string' && data.url.startsWith('https://')) { + window.location.assign(data.url); + return true; + } + if (data.code === 'already_pro') { showNotification('You are already on Glint Pro.', 'info'); refreshAccount(); return false; } + if (data.code === 'sign_in') { showNotification('Sign in first, then upgrade.', 'info', { action: { label: 'Sign in', run: openSignIn } }); return false; } + showNotification(data.error || 'Checkout could not start. Try again in a moment.', 'error'); + return false; +} + +// Stripe's own page for cancelling or changing the card. +export async function openBillingPortal() { + const { ok, data } = await billingPost('portal'); + if (ok && typeof data.url === 'string' && data.url.startsWith('https://')) { + window.location.assign(data.url); + return true; + } + showNotification(data.error || 'Billing could not open. Try again in a moment.', 'error'); + return false; +} + +// Back from checkout with ?pro=success&session_id=...: have the server read +// the result from Stripe so the plan is right at once, without waiting for +// the webhook. Resolves to 'pro', 'pending' or 'failed'. +export async function confirmCheckout(sessionId) { + const { ok, data } = await billingPost('confirm', { session_id: sessionId }); + await refreshAccount(); + if (!ok) return 'failed'; + if (data.plan === 'pro') { track('pro_checkout', { step: 'done' }); return 'pro'; } + return 'pending'; +} + export function bindAccount() { // bindAuth() announces the first sign-in state once Clerk has loaded. onAuthChange(() => { refreshAccount(); }); diff --git a/terms/index.html b/terms/index.html index a7ad08e..abbd7aa 100644 --- a/terms/index.html +++ b/terms/index.html @@ -47,7 +47,7 @@

Acceptable use

Use the tool for lawful purposes. Do not use Glint to create or distribute content that is illegal, infringes someone else's rights, or is designed to deceive or harm. Do not attempt to disrupt the service or abuse any hosted feature, including the optional AI backend.

Optional AI and third-party services

-

Some features are optional and connect to third parties. Cloud AI sends your current image and prompt to an AI provider when you click the button. Share links upload the rendered images to storage so they can be opened by link. Sign-in is provided by Clerk. When you use these, you also accept the terms and policies of those providers. Anything generated by an AI model may also be subject to that provider's usage terms.

+

Some features are optional and connect to third parties. Cloud AI sends your current image and prompt to an AI provider when you click the button. Share links upload the rendered images to storage so they can be opened by link. Sign-in is provided by Clerk. Glint Pro subscriptions are sold and billed by Stripe as the merchant of record, under its own terms; you can cancel at any time from your account panel. When you use these, you also accept the terms and policies of those providers. Anything generated by an AI model may also be subject to that provider's usage terms.

Open-source license

Glint is open source. Your use of the source code is governed by the license published in the project repository on GitHub. These terms cover your use of the hosted app and site.