diff --git a/CLAUDE.md b/CLAUDE.md index 68707b7..8d9d5b1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -111,7 +111,7 @@ 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. **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. +- **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 return: checkout comes back to `/editor/#pro=success` (a fragment, because a query string misses the service worker's cached editor page), the browser remembers the session id it started in `glint_pro_checkout`, and an unfinished checkout is re-checked quietly the next time the editor opens. The service worker now ignores every query parameter when matching cached pages (`ignoreURLParametersMatching`), so `/editor/?look=` and `?ext=` links also reach the editor for returning visitors. 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), `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. diff --git a/api/_billing.js b/api/_billing.js index 0bc588d..70f6966 100644 --- a/api/_billing.js +++ b/api/_billing.js @@ -214,15 +214,18 @@ export async function checkout(req, res) { 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`, + // The result rides in the fragment, and the editor remembers the session + // id itself: a query string would miss the service worker's cached editor + // page and land a returning visitor on the homepage instead. + success_url: `${origin}/editor/#pro=success`, + 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 }); + res.status(200).json({ url: session.url, id: session.id }); } catch (e) { fail(res, e); } diff --git a/scripts/regression-tests.mjs b/scripts/regression-tests.mjs index 71bee0c..b667985 100644 --- a/scripts/regression-tests.mjs +++ b/scripts/regression-tests.mjs @@ -1500,7 +1500,8 @@ async function testBillingRoutes() { 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.success_url, 'https://glint.test/editor/#pro=success'); + assert.ok(started.body.id.startsWith('cs_test_')); 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(); diff --git a/src/features/account-panel.js b/src/features/account-panel.js index 53ee2c3..42222fe 100644 --- a/src/features/account-panel.js +++ b/src/features/account-panel.js @@ -4,11 +4,12 @@ // 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, startCheckout, openBillingPortal, confirmCheckout } from './account.js'; +import { getAccount, onAccountChange, refreshAccount, hasOwnKey, resetDay, startCheckout, openBillingPortal, confirmCheckout, pendingCheckout, forgetCheckout } from './account.js'; import { showNotification } from '../ui/notification.js'; let dlg = null; let body = null; +let welcome = false; // just upgraded: the Pro box says what that brings function node(tag, className, text) { const n = document.createElement(tag); @@ -41,6 +42,7 @@ function build() { // Keys stay inside, so the editor's shortcuts never act behind the panel. dlg.addEventListener('keydown', (e) => e.stopPropagation()); dlg.addEventListener('click', (e) => { if (e.target === dlg) dlg.close(); }); + dlg.addEventListener('close', () => { welcome = false; }); } function costLine(costs) { @@ -89,7 +91,17 @@ 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.')); + if (welcome) { + const list = node('ul', 'account-perks'); + [ + `${usage.limit} hosted AI credits every month, starting now`, + 'They refill on the first of each month', + 'Cancel or change your card any time from this panel', + ].forEach((line) => list.append(node('li', '', line))); + box.append(node('h4', '', 'Welcome to Glint Pro'), node('p', 'account-note', 'Thank you for backing Glint. Here is what you have now:'), list); + } else { + 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.'), @@ -190,27 +202,40 @@ 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. +// Back from Stripe's checkout. The address says how it went (#pro=success or +// #pro=cancel) and this browser remembers which checkout it started, so the +// server can read the result from Stripe at once. A checkout that was started +// and never seen to finish (the tab was closed, the return landed elsewhere) +// is checked quietly the next time the editor opens. 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; + const fromHash = new URLSearchParams(window.location.hash.replace(/^#/, '')); + const fromQuery = new URLSearchParams(window.location.search); + const result = fromHash.get('pro') || fromQuery.get('pro'); + if (result) { + // Clean the address at once, so a reload never repeats this. + fromQuery.delete('pro'); + fromQuery.delete('session_id'); + const rest = fromQuery.toString(); + window.history.replaceState(null, '', window.location.pathname + (rest ? `?${rest}` : '')); + } + const saved = pendingCheckout(); + if (result === 'cancel') { forgetCheckout(); return; } + if (!saved) return; + const cameBack = result === 'success'; 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); + const outcome = await confirmCheckout(saved.id); if (outcome === 'pro') { - showNotification('Welcome to Glint Pro. Your credits are ready.', 'success', { duration: 7000 }); + forgetCheckout(); + welcome = true; + showNotification('Welcome to Glint Pro.', 'success', { duration: 7000 }); openAccountPanel(); + } else if (!cameBack) { + // Never finished, as far as Stripe knows. Stop asking after an hour. + if (Date.now() - saved.at > 3600 * 1000) forgetCheckout(); } 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); diff --git a/src/features/account.js b/src/features/account.js index c1518dd..fd691e3 100644 --- a/src/features/account.js +++ b/src/features/account.js @@ -128,12 +128,29 @@ async function billingPost(op, body = {}) { } } +// The checkout this browser started and has not seen the end of yet. +const CHECKOUT_KEY = 'glint_pro_checkout'; +export function pendingCheckout() { + try { + const saved = JSON.parse(localStorage.getItem(CHECKOUT_KEY) || 'null'); + if (saved && typeof saved.id === 'string' && /^cs_/.test(saved.id) && Date.now() - saved.at < 24 * 3600 * 1000) return saved; + if (saved) localStorage.removeItem(CHECKOUT_KEY); + } catch (e) { /* nothing saved */ } + return null; +} +export function forgetCheckout() { + try { localStorage.removeItem(CHECKOUT_KEY); } catch (e) { /* nothing saved */ } +} + // 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://')) { + // Remembered here so the editor can confirm the payment when the person + // comes back, however they come back. + try { localStorage.setItem(CHECKOUT_KEY, JSON.stringify({ id: String(data.id || ''), at: Date.now() })); } catch (e) { /* private mode */ } window.location.assign(data.url); return true; } diff --git a/src/styles.css b/src/styles.css index 5cc6186..1e8643d 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1082,6 +1082,8 @@ button.account-pill:focus-visible { outline: 2px solid var(--accent-line); outli .account-note + .account-note { margin-top: 6px; } .account-box h4 { margin: 0 0 4px; font-size: 13px; font-weight: 600; } .account-box .btn { margin-top: 10px; width: 100%; text-align: center; text-decoration: none; display: block; } +.account-perks { margin: 8px 0 0; padding-left: 18px; font-size: 12px; line-height: 1.7; color: var(--text-primary); } +.account-perks li::marker { color: var(--accent-primary); } .account-actions { display: flex; gap: 8px; margin-top: 4px; } .account-actions .btn { flex: 1; } .auth-modal-overlay { diff --git a/vite.config.js b/vite.config.js index b84ebd0..65b7bbc 100644 --- a/vite.config.js +++ b/vite.config.js @@ -225,6 +225,10 @@ export default defineConfig({ // v41 — the worker answers unknown navigations with the cached homepage. // Share links (/s/) and API routes must always reach the network, or // a returning visitor opening a link would see the homepage instead. + // The pages read their own query strings (?look=, ?ext=); without this a + // returning visitor's /editor/?look=... misses the cached page and falls + // back to the homepage. + ignoreURLParametersMatching: [/./], navigateFallbackDenylist: [/^\/s\//, /^\/api\//], manifestTransforms: [async (entries) => ({ // v41 — the share viewer is opened from links, never offline; keep it out.