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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<dialog>` 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 `<dialog>` 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://<site>/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.
Expand Down
36 changes: 28 additions & 8 deletions api/_account.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -192,18 +204,26 @@ 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');
try {
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.' });
Expand Down
Loading
Loading